text
stringlengths
180
608k
[Question] [ In traditional FizzBuzz, you are asked to print the numbers from 1 to 100, but replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of both 3 and 5 (i.e. 15) with "FizzBuzz". However, as an evil interviewer, I've invented my own twisted version of FizzBuzz, which I've decided to name BizzFuzz and give to you in a coding interview. The rules of the game are: * Print each number from 1 to 100, except if the number meets one of the conditions below. + If the number is divisible by 4, print "Fizz". + If the number is divisible by 5, print "Buzz". + If the number is divisible by 4, but the number immediately *after* it is divisible by 5, print "FizzBuzz" instead of "Fizz", and print the next number regularly. + If the number is divisible by 5, but the number immediately *after* it is divisible by 4, print "BuzzFizz" instead of "Buzz", and print the next number regularly. + If the number is immediately *before* a number divisible by both 4 and 5, print "Bizz". + If the number is immediately *after* a number divisible by both 4 and 5, print "Fuzz". + If the number is divisible by both 4 and 5, print "BizzFuzz". The shortest code to implement all these rules in any language wins. [Answer] ## Python, 114 ``` a='Fizz' b='Buzz' c='Bizz' d='Fuzz' e=c+d f=a+b g=b+a i=1 exec"print eval('ediifiiiaibiaiigiiic'[i%20]);i+=1;"*100 ``` Original solution (**131**): ``` f='Fizz' for i in range(1,101):x=i%20;print('Bizz'*(x%19<1)+'Fuzz'*(x<2)or(i%4<1)*f+'Buzz'*(i%5<1or x==4)+f*(x==15)or i,i)[x%11==5] ``` [Answer] ## GolfScript (83 80 chars) (NB Howard's suggestion in the comments allows to reduce to 78 chars, but with trailing spaces on some lines). This uses the character `\0`, so here it is in xxd format: ``` 0000000: 3130 302c 7b29 2e32 3025 2742 6946 750a 100,{).20%'BiFu. 0000010: 0046 750a 0000 0046 6942 750a 0000 0000 .Fu....FiBu..... 0000020: 4669 0a00 0042 750a 0000 4669 0a00 0000 Fi...Bu...Fi.... 0000030: 4275 4669 0a00 0000 0042 690a 2731 2c2f BuFi.....Bi.'1,/ 0000040: 3d32 2f27 7a7a 272a 5c6e 2b6f 727d 2f0a =2/'zz'*\n+or}/. ``` and base64: ``` MTAwLHspLjIwJSdCaUZ1CgBGdQoAAABGaUJ1CgAAAABGaQoAAEJ1CgAARmkKAAAAQnVGaQoAAAAA QmkKJzEsLz0yLyd6eicqXG4rb3J9Lwo= ``` Using **^** as a stand-in for `\0`, it's ``` 100,{).20%'BiFu **^**Fu **^****^****^**FiBu **^****^****^****^**Fi **^****^**Bu **^****^**Fi **^****^****^**BuFi **^****^****^****^**Bi '1,/=2/'zz'*\n+or}/ ``` Still not a particularly interesting problem. --- An explanation was requested: For values `0` to `99` inclusive: ``` 100,{ ... }/ ``` Increment the value (we want `1` to `100`) and also find out what the incremented value is `mod 20`: ``` ).20% ``` Split the magic string around `\0` characters: ``` MAGIC_STRING 1,/ ``` Take the (`x mod 20`)th element of that array, split it into 2-character chunks, and glue them back together with `zz`. Note: the string is either empty (in which case there are no chunks, so we end up with the empty string) or is a sequence of `[BF][iu]` prefixes followed by a newline. ``` =2/'zz'* ``` Take the other copy of the incremented number which we kept on the stack, and append a newline. Now whichever string we keep will end with a newline. ``` \n+ ``` Apply a fallback operation. (This is similar to `||` in JavaScript or `COALESCE` in SQL). ``` or ``` [Answer] ### Python 2, 131 ``` F,B,Z,I='Fizz','Buzz','Fuzz','Bizz' for i in range(1,101):print{5:Z,19:I,i%4:B,i%5*4:F,3:B+F,16:F+B,0:I+Z,1:i,4:i}.get(i%4+i%5*4,i) ``` [Answer] An ungolfed reference implementation in Python that implements every rule literally (420 chars): ``` n = 1 while(n <= 100): if(n % 20 == 0): print "BizzFuzz" elif((n - 1) % 20 == 0): print "Fuzz" elif((n + 1) % 20 == 0): print "Bizz" elif(n % 5 == 0 and (n + 1) % 4 == 0): print "BuzzFizz" print n + 1 n += 1 elif(n % 4 == 0 and (n + 1) % 5 == 0): print "FizzBuzz" print n + 1 n += 1 elif(n % 4 == 0): print "Fizz" elif(n % 5 == 0): print "Buzz" else: print n n += 1 ``` [Answer] # Python, 150 This is derivative of minitechs (earlier) answer, but I've squeezed enough out of it to make my own: ``` F,B,Z,I='Fizz','Buzz','Fuzz','Bizz' for i in range(1,101):a,b=i%4,i%5*4;print i if a+b in [1,4] else {5:Z,19:I,a:B,b:F,3:B+F,16:F+B,0:I+Z}.get(a+b,i) ``` The degolfed version isn't much more readable, but the `r` that minitech was using is only triggered if on the next iteration the sum if `a,b` was either `1,0` or `0,4`, which is equivalent to `i%4 or i%5 == 0`so it was only going to appear in those circumstance. So it was possible to remove the assignment and calculation of `r` and derive it from the current value of `i` using `a` and `b`: ``` F,B,Z,I='Fizz','Buzz','Fuzz','Bizz' for i in range(1,101): a,b=i%4,i%5*4; print i if a+b in [1,4] else {5:Z,19:I,a:B,b:F,3:B+F,16:F+B,0:I+Z}.get(a+b,i) ``` It also includes @WolframH's suggestions. [Answer] ## R: 170 characters ``` a=b=1:100 o=!a%%4 i=!a%%5 w=o&i a[o]="Fizz" a[i]="Buzz" a[c(i,F)&c(F,o)]="FizzBuzz" a[c(F,i)&c(o,F)]="BuzzFizz" a[w[-1]]="Bizz" a[c(F,w)]="Fuzz" a[w]="BizzFuzz" cat(a[b]) ``` [Answer] ## Javascript 127 bytes ``` f='Fizz';b='Buzz';F='Fuzz';B='Bizz';z=n=>(n?z(n-1):0,console.log([f,b,B,F,B+F,f+b,b+f,n]["43775777071707767772"[n%20]]));z(100) ``` ## Explanation ``` f = 'Fizz'; b = 'Buzz'; F = 'Fuzz'; B = 'Bizz'; z = n => ( n?z(n-1):0, // If n is greater than 0, we keep going downwards, this happens before printing. console.log( // These are the values that we a want to print, it is // very important that it is written inline inside the // function, otherwise, we couldn't have 'n' in it [f,b,B,F,B+F,f+b,b+f,n][ // The game cycles every 20 steps, so we can build a // look up table that we'll use to index into the other // table. We take advantage of implicit string -> Number // conversion inside the index operator, and use a // string instead of an array, saving 1 byte per entry "43775777071707767772"[n%20]]) ); z(100); ``` [Answer] ## Tcl, 185 chars ``` while {[incr i]<101} {puts [expr {$i%4?$i%5?($i-1)%4|($i-1)%5?($i+1)%4|($i+1)%5?$i:"Fuzz":"Bizz":($i-1)%4?($i+1)%4?"Buzz":"BuzzFizz":$i:($i-1)%5?($i+1)%5?$i%5?"Fizz":"FizzBuzz":$i:$i}]} ``` ]
[Question] [ A [bracelet](https://en.wikipedia.org/wiki/Necklace_(combinatorics) "Wikipedia") consists of a number, \$\mathit{N}\$, of beads connected in a loop. Each bead may be any of \$\mathit{C}\$ colours. Bracelets are invariant under rotation (shifting beads around the loop) and reflection (turning the bracelet over). Here are all \$11\$ bracelets with exactly two beads of each of three different colours. [Source](https://en.wikipedia.org/wiki/Necklace_(combinatorics)#/media/File:Bracelets222.svg "Wikipedia") ([Tilman Piesk](https://commons.wikimedia.org/wiki/User:Watchduck "Wikipedia:user=Watchduck")). ![2-2-2 Bracelets](https://i.stack.imgur.com/CGdzC.png) A bracelet has \$\mathit{S}\$ stripes if merging all adjacent beads of identical colour until no longer possible would result in a bracelet with \$\mathit{S}\$ beads. In the above picture, the bracelet in the first column has \$3\$ stripes, while those in the second, third, fourth and fifth columns have \$4\$, \$6\$, \$5\$, and \$6\$ stripes, respectively. Equivalently a bracelet has \$\mathit{S}\$ stripes if precisely \$\mathit{d}\$ neighbouring pairs of beads have different colours, where $$\mathit{d} = \begin{cases} 0, & \text{if $\mathit{S}=1$} \\ S, & \text{if $\mathit{S}>1$} \end{cases}$$ Note: The above picture does not show all stripey bracelets with six beads as it only shows those with *exactly* two of each of three *different* colours - there are \$92\$ distinct bracelets with six beads when choosing from three colours which may be partitioned into sets of stripey bracelets with \$3\$, \$15\$, \$10\$, \$36\$, \$15\$, and \$13\$ members with \$1\$ to \$6\$ stripes, respectively. ### Challenge Given \$\mathit{N}\$, \$\mathit{C}\$, and \$\mathit{S}\$ output the number, \$|\mathit{B}\_{\mathit{N},\mathit{C},\mathit{S}}|\$, of different \$\mathit{N}\$-bead bracelets with \$\mathit{S}\$ stripes whose beads may be any of \$\mathit{C}\$ colours. All three of the inputs are positive integers. You may assume that \$\mathit{S} \le \mathit{N}\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make the shortest code possible in your programming language of choice when measured in bytes. ### Examples ###### N = 4 beads, C = 3 colours, S = 4 stripes \$|\mathit{B}\_{4,3,4}| = 6\$ ``` -R--G--R--G- -R--G--R--Y- -R--G--Y--G- -R--Y--R--Y- -R--Y--G--Y- -G--Y--G--Y- ``` ###### N = 5 beads, C = 2 colours, S = 4 stripes \$|\mathit{B}\_{5,2,4}| = 2\$: ``` -R--R--G--R--G- -R--G--R--G--G- ``` ###### N = 5 beads, C = 4 colours, S = 1 stripe \$|\mathit{B}\_{5,4,1}| = 4\$: ``` -R--R--R--R- -G--G--G--G- -Y--Y--Y--Y- -B--B--B--B- ``` ###### N = 6 beads, C = 3 colours, S = 4 stripes \$|\mathit{B}\_{6,3,4}| = 36\$: ``` -R--G--G--R--Y--Y- ⇦ top of column 2 in the image -R--R--Y--G--G--Y- ⇦ middle of column 2 in the image -R--R--G--Y--Y--G- ⇦ bottom of column 2 in the image -R--R--R--G--R--G- (... the rest don't have exactly two of each colour) -R--R--R--G--R--Y- -R--R--R--G--Y--G- -R--R--R--Y--R--Y- -R--R--R--Y--G--Y- -R--R--G--R--R--G- -R--R--G--R--R--Y- -R--R--G--R--G--G- -R--R--G--R--Y--Y- -R--R--G--G--R--Y- -R--R--G--G--Y--G- -R--R--Y--R--R--Y- -R--R--Y--R--Y--Y- -R--R--Y--G--Y--Y- -R--G--R--G--G--G- -R--G--R--Y--Y--Y- -R--G--G--R--G--G- -R--G--G--G--R--Y- -R--G--G--G--Y--G- -R--G--G--Y--G--G- -R--G--G--Y--Y--G- -R--G--Y--Y--Y--G- -R--Y--R--Y--Y--Y- -R--Y--G--G--G--Y- -R--Y--G--G--Y--Y- -R--Y--G--Y--Y--Y- -R--Y--Y--R--Y--Y- -R--Y--Y--G--Y--Y- -G--G--G--Y--G--Y- -G--G--Y--G--G--Y- -G--G--Y--G--Y--Y- -G--Y--G--Y--Y--Y- -G--Y--Y--G--Y--Y- ``` ###### N = 6 beads, C = 3 colours, S = 6 stripes \$|\mathit{B}\_{6,3,6}| = 13\$: ``` -R--G--Y--R--Y--G- ⇦ top of column 3 in the image -R--G--Y--G--R--Y- ⇦ middle of column 3 in the image -R--G--R--Y--G--Y- ⇦ bottom of column 3 in the image -R--G--Y--R--G--Y- ⇦ only of column 5 in the image -R--G--R--G--R--G- (... the rest don't have exactly two of each colour) -R--G--R--G--R--Y- -R--G--R--G--Y--G- -R--G--R--Y--R--Y- -R--G--Y--G--Y--G- -R--Y--R--Y--R--Y- -R--Y--R--Y--G--Y- -R--Y--G--Y--G--Y- -G--Y--G--Y--G--Y- ``` ### Test cases ``` N, C, S, # 1, 1, 1, 1 1, 3, 1, 3 2, 1, 1, 1 2, 1, 2, 0 2, 2, 1, 2 3, 2, 3, 0 3, 5, 2, 20 4, 2, 4, 1 4, 3, 4, 6 * see above 5, 2, 4, 2 * see above 5, 3, 4, 15 5, 4, 1, 4 * see above 5, 8, 1, 8 5, 8, 2, 112 5, 8, 3, 336 5, 8, 4, 1400 5, 8, 5, 1680 6, 3, 1, 3 6, 3, 2, 15 6, 3, 3, 10 6, 3, 4, 36 * see above 6, 3, 5, 15 6, 3, 6, 13 * see above 6, 4, 3, 40 6, 5, 1, 5 6, 5, 2, 50 6, 5, 3, 100 6, 5, 4, 410 6, 5, 5, 510 6, 5, 6, 430 ``` --- Brownie points for matching or beating \$18\$ bytes in [Jelly](https://github.com/DennisMitchell/jelly "GitHub") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~44~~ 42 bytes A function taking three curried arguments, call as `f[N][C][S]`. ``` (+/=)@+/~-1=':+?{a@*<a,:|'a:(#x)':x,x}'+!# ``` [Try it online!](https://ngn.codeberg.page/k#eJwtzEEKwyAUBNC9p7DJQq0pEv0/FNNQoftueoJscoIshLQ9e3+mQXgO4+CSrQ+TKz58L/1ksr9vcznf5i6/zZxtW53Jtasf40+tUmu2vZYz9jqJEXk3inKPSUwiS0OSSUwiI/ORSZasr4cRJkiQxwH/70aYIMH/6yASesaSseSjIchwcEo1T/3QL902au3MUoJZf6jSMIk=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 21 (20†) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LIãεā._Dí«Σ}н}ÙʒγgQ}g ``` Inputs in the order \$C,N,S\$. [Try it online](https://tio.run/##ATgAx/9vc2FiaWX//0xJw6POtcSBLl9Ew63Cq86jfdC9fcOZypLOs2dRfWf//zMKNAo0/y0tbm8tbGF6eQ) or [verify halve of the test cases](https://tio.run/##yy9OTMpM/V9WGZSg5Gx7eL@OH4gIBhIKj9omKSjZVyaEhf73iTi8@NzWI4168S6H1x5afW5x7YW9tYdnnpp0bnN6ZGBt@n@d/9HRxjomOiaxOtFGOqZg2gRIGwJpYx0zMB9Em8XqKEQb6hhCJSC0oY4RnDYCGwDhG@kY6xgDaVMgDRE3gRoEsiD2v65uXr5uTmJVJQA) (the test cases with larger \$N\$ time out). **Explanation:** Step 1: Get a list of all possible bracelets of size \$N\$ using up to \$C\$ amount of colors: ``` L # Push a list in the range [1, first (implicit) input C] Iã # Take the cartesian product with the second input N ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f/fx/Pw4v@2So65@aV5JQr5aQpJRYnJqTmpJcUKRam5iZl5mXnpVgpK9un2/425TLhM/uvq5uXr5iRWVQIA) Step 2: Only keep unique bracelets by removing rotations and reflections: ``` ε # Map over each inner list: ā._ # Get a list of all its rotations: ā # Push a list in the range [1,length] (without popping) ._ # Rotate the original list each value amount of times towards the left D # Duplicate this list of rotations í # Reverse each inner list « # Merge the two lists together Σ} # Sort the list of lists - † should have been just { н # Only keep the first one }Ù # After the outer map: uniquify the list of lists ``` [Try just the first 2 steps online.](https://tio.run/##AVUAqv9vc2FiaWX//0xJw6POtcSBLl9Ew63Cq86jfdC9fcOZ/z0iQW1vdW50IG9mIGJyYWNlbGV0cyByZW1haW5pbmc6ICI/Zz//Mwo0CjT/LS1uby1sYXp5) Step 3: Only keep bracelets with \$S\$ amount of stripes: ``` ʒ # Filter the lists by: γ # Split it into groups of equal adjacent items g # Pop and push the length Q # Check if it's equal to the third (implicit) input S } # Close the filter ``` [Try just the first 3 steps online.](https://tio.run/##AVwAo/9vc2FiaWX//0xJw6POtcSBLl9Ew63Cq86jfdC9fcOZypLOs2dRff89IkFtb3VudCBvZiBicmFjZWxldHMgcmVtYWluaW5nOiAiP2c//zMKNAo0/y0tbm8tbGF6eQ) Step 4: Output the amount of valid stripey bracelets remaining: ``` g # Pop and push the length # (which is output implicitly as result) ``` † - The `Σ}` (sort-by builtin without implementation) should have been `{` (sort builtin) for -1 byte, but due to some weird bug it doesn't work in this case.. :/ It does change the order somewhat, but definitely not to the expected lexicographical order.. [Here an example output for the expected vs actual sorted rotations+reflections of a sample bracelet.](https://tio.run/##yy9OTMpM/f//SKNevMvhtYdWcyk5lxYVpeaVWCkoKNm7KCjocCm5VhSkJpekplhBRM4trgUKOiaXlCbmAFVBBKt1/v@PNtQx1jHRMYr9r6ubl6@bk1hVCQA) [Answer] # [Python 3](https://docs.python.org/3/), ~~148~~ 147 bytes ``` lambda N,C,S:sum(t==t[j::k]+t[:j:k]for*t,j,k in product(*map(range,[C]*N+[N]),[1,-1])if(len([*groupby(t*2)])//2or 1)==S)/N/2 from itertools import* ``` [Try it online!](https://tio.run/##PY5Bb6MwEIXv/hWTU2zqbbANKELiUFXqMZfujeVAAnRJwUa2c4ii/Pbs2KRrC31vPG@Gt1z9X6PVY6j@PKZ2PnYtHPg7/yzdZaa@qnx9Lsvv5sXX5Rk5GJt4fubfMGpYrOkuJ0@TuV2obfVXz@v3Jjm81IeG8VrwX6Jh40CnXtM6@bLmshyv1CeSNWy3k8aCYFX1yXaHnSSDNTOMvrfemMnBOC/G@uSxEtzVkWPbQQUf7eR6gjlgGnUfYmDv1flu1CUBPJqfuOMGrSHWqD0Pxle3TKOnjEXPOMBAo5HBpgKzToazWJygw3agN33ntxN@7o4pbz/@@6a6mfuW/Z9YY/22l57gWm18eFkXrsu2b9MEvnfewdI613ebLXsIiJcIUEhF5LMOlJAioyIKqbBWkKOSKckQGRozfM6gIHmsJTLUIkeBgAy5R@4jcZeQUSlQqogKXVmaRpmDKPYpKZ5ZAmVYFQQ@rR38YRFF/tMqQARzTBI82IA8UkK@PoTpVWWQiVXhfSqcVek/ "Python 3 – Try It Online") -1 Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) Ungolfed: ``` from itertools import product def f(N,C,S): z = 0 for t in product(range(C),repeat=N): if sum(t[i] != t[i-1] for i in range(N)) == S*(S>1): for i in range(N): u = t[i:]+t[:i] z += t == u z += t[::-1] == u return z // (2*N) ``` Uses [Burnside's lemma](https://en.wikipedia.org/wiki/Burnside%27s_lemma). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ṗµṙJ;U$Ṃ)QŒgẈċ⁵ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bmXwrXhuZlKO1Uk4bmCKVHFkmfhuojEi@KBtf///zP/Nf80 "Jelly – Try It Online") Port of @Kevin Cruijssen's 05AB1E answer, so upvote that! ## Explanation ``` ṗµṙJ;U$Ṃ)QŒgẈċ⁵ - Dyadic link taking C, N and S as the third command-line argument ṗ - C cartesian-power N (C implicitly converted to range [1..C]) µ ) - Over each X: J - Get list [1, len(X)] ṙ - For each Y in that, rotate X left by Y $ - Last two links as a monad: U - Reverse each ; - Concatenate Ṃ - Minimum Q - After map, uniquify Œg - Split into groups of adjacent equal elements (vectorizes) Ẉ - Length of each ċ⁵ - Count occurences of the third input (S) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` ɾ↔ƛż¨VǓ:RJg;UvĠvLO ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiyb7ihpTGm8W8wqhWx5M6UkpnO1V2xKB2TE8iLCIiLCIzXG41XG40Il0=) Same as my Jelly answer, so ports 05AB1E. [Answer] # [Python](https://www.python.org), 153 bytes ``` lambda n,c,s:len({a for x in product(*[range(c)]*n)if s==len([*groupby(a:=min(x[k::r]+x[:k:r]for k in range(n)for r in[-1,1]))])}) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JY5NCoMwFIT3PUWWeTYupC2UgCdJXcSf2KC-hGcEpfQgpRuhtNuep7ep4mrgY-Zjnh8_havD-WXSy3sIJj7_Hq3u8lIzFIXoZVshv2lmHLGRWWSeXDkUgUeKNNYVLyCLEKxhfZquXRXV5AafT1zLtLPIR9VISdl-VLJZchU1q2ibI6yAFqDiRCQZQAZ32BlyHbOhouBc2zPbeUch2g5-PVkM3PCTOIgjwEbnecs_) -6 thanks to Jonathan Allan [Answer] # [Pyth](https://github.com/isaacg1/pyth), 54 bytes ``` LhSsm,.<_bd.<bdlbV.CUEEV.pNI!/YyHIqQ|ltr8+HhH1 aYyH;lY ``` [Try it online!](https://tio.run/##K6gsyfj/3ycjuDhXR88mPilFzyYpJScpTM851NU1TK/Az1NRP7LSw7MwsCanpMhC2yPDw1AhEShinRP5/78RlymXMQA "Pyth – Try It Online") Takes three inputs in order of `S`, `C`, `N` [Answer] # Python3, 299 bytes: ``` R=range def f(N,c,S): q,p,K=[(N,S,[])],[],0 while q: n,s,r=q.pop(0) if(t:=[r[k:]+r[:k]for k in R(N)]+[r[::-1]])!=n+s==0<(r[0]-r[-1]or S==1)>0==any(j in p for j in t):p+=t;v=r;K+=S==sum(v!=(v:=x)for x in r) elif n:q+=[(n+~j,s-1,r+[i]*-~j)for i in{*R(c)}-{([-1]+r)[-1]}for j in R(n)] return K ``` [Try it online!](https://tio.run/##ZVJNb@IwED3Xv2LKHrCJQfkWStd72SNSD3DM5hBKsjUfxjgp26pq/zo7NgmtQIom7z2/8Yw1o9/a572KptqcTnNhSvW3Iquqhpo@8ie@YBmBA9d8JnIUFjwvWIGB@wT@PcttBQc0gOINN@Iw0XtNfYaCrGmbidzkm6zwTJ5tinpvYANSwZw@ssLDoywbB0XB7oXyGiH8n9TkfjE2OaroXQgRsF@@EKV6o2ubqMHe4WDLMu2J9uEozMPME@htXnb0eC/oMROvzPperc/YXqqtrEFlBw@foLzPNW/GATdeLovR@HPtzBLN76M5fWIf43dqO/AMs7@PS8k5VawgYKr2xSiYneRO702LnGgjVUtrGvOIx4xdeMLDKx7z4BtPr/yWp8jbqmkbEDAYDB45/Oaw4PCDBBy6z8LIwYiEX@oZYvQt7BiJHIysiiFxLPRJ7EBs82J3jDEFGEFTVVAu98eKJL0lvNHP/iCxOHaF4hvP1OnTDtp2grAjmB5FaUdsfuz7HcMYpFOfpF9PPMPQ1Ttje9JbbPdXjZ8Pkm8JGIPoxtQ93N2UuGJJB7FY0suuWE8wJQ56Yr8LsfdFPo6M9PsEbo6TRm9lS4d/1JDlQVZk5G5UcljifHelpjh5jjs0qaValdst@lbekIPENbgrm6bCDavpqGQgBCxP/wE) Completes all the test cases in <20 seconds. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~63~~ 56 bytes ``` NθNηNζILΦEXηθEθ﹪÷ιXηλη∧⁼∧⊖ζζLΦι⁻λ§ι⊕μ⁼ι⌊Eθ⌊E⟦ι⮌ι⟧Eθ§ν⁺λπ ``` [Try it online!](https://tio.run/##XU9Na8MwDL3vV/gog3ta2aWnsm4QaEvZtfTgxWIx2Eri2Nnon3flfqYT2PKT9J6e60aHutUu54q6FLfJf2OAXi5eprj5h4@Md8FShHc9RFgj/cQGPq2L3NzoDnbtb6Ep0UslSqHn1JrkWqgoruxoDYJV4j7nJA82stxLMvDRJ@0GKM8V1gE9UkTDe5Uo53kh62wspQEck2NFBv9KraIH0ctzKHEVvlCsTx5u7iZwz@0vHDEMbFIe7j@4iRMbd5d9nZzGIuc38SrmeTa6Ew "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηNζ ``` Input `N`, `C` and `S`. ``` IL ``` Output the number of ... ``` ΦEXηθEθ﹪÷ιXηλη ``` ... all of the rotations and reflections of all of the bracelets of `N` beads with `C` colours, filtered where... ``` ∧⁼∧⊖ζζLΦι⁻λ§ι⊕μ ``` ... they have `S` stripes, and ... ``` ⁼ι⌊Eθ⌊E⟦ι⮌ι⟧Eθ§ν⁺λπ ``` ... the bracelet is in its canonical form, which is the minimum of its rotations and reflections, i.e. limiting the output to unique bracelets. [Answer] # JavaScript (ES7), 158 bytes ``` (n,c,s)=>(F=k=>k--&&([...p=[...Array(n)].map((_,i)=>q=k/c**i%c|0)].some(v=>F[p=[p.pop(t+=q!=v),...p]]|F[[...p].reverse(q=v)],t=0)|t+!t-s?0:F[p]=1)+F(k))(c**n) ``` [Try it online!](https://tio.run/##ZY/fboIwGMXvfYpvidNWC@OvF5pidjFegjSTdLg5FJASkkV5gyW72eX2HnseX2CPwEqRBWPSnLS/nnO@9jUsQ8HzTVZoSfoU1Wtao4RwIjD1kE9j6sWaNhqhQNf1jDZ6n@fhG0ow03dhhtAj2UjrnsZ3fDLZ3PKjIW9EuotQST0/kJlMz9IMFVO6v6ElJk0RY0c/UJVMz6MyykWE9vKSkYIa@FhMbwpNLI25zDNq4qmPYoyRHJDgehEMAAIwSbeAkY7Yitgdsa48LZFq9MgZdsRWxO555N5V0PpHjjo7vWpHZaTOOuJ2HqtHWo/p9pCj5jsdmV39oyVWP9aixmdcouYZs0vkXgelmv368@Nl14AN9HWaP4T8BaEAEgKcgCCQRwIYBuoBTxORbiN9mz6jFRoekorA8MCVigqD5slNChTW6JzGVUuoalnC@Pfn4/T1KXUMcxifvt/H1QrjRf0H "JavaScript (Node.js) – Try It Online") ### Commented ``` (n, c, s) => // outer function taking the parameters ( F = k => // inner recursive function taking a counter k k-- && ( // stop when k = 0 / decrement it [... p = // build an array p[] [...Array(n)] // of n elements, .map((_, i) => // filled with: q = // values from 0 to c - 1 k / c ** i % c // with the last one saved in q | 0 // ) // end of map() ].some(v => // for each value v in a copy of this array: F[ // test whether we've already generated p = [ // a rotation of the same pattern p.pop( // we use pop() to compute the rotations t += q != v // and, at the same time, we keep track of ), // the number of stripes in t by counting ...p // runs of equal beads ] // ] | // F[ // test whether we've already generated [...p].reverse( // a reflection of the same pattern q = v // save the last bead in q ) // ], // t = 0 // start with t = 0 ) | // end of some(); if it was truthy or the t + !t - s ? // number of stripes is not the expected one: 0 // leave the final result unchanged : // else: F[p] = 1 // increment the final result and mark the // pattern as generated ) + F(k) // add the result of a recursive call )(c ** n) // initial call to F ``` ]
[Question] [ # Let's talk about divisors... Leaving out perfect squares (for a moment), all positive integers can be expressed as the **product** of 2 of their divisors. Quick example for `126`: Here are all the divisors of `126` [![enter image description here](https://i.stack.imgur.com/GI2NM.jpg)](https://i.stack.imgur.com/GI2NM.jpg) As you can see all the divisors can be paired. Here are what we will call the **Divisor Pairs**: `[1, 126], [2, 63], [3, 42], [6, 21], [7, 18], [9, 14]` For this challenge we will need only the **last pair of this list** (which is the **center pair** of the picture): `[9,14]`.We will call this pair the **MaxMin Divisor Pair**. The **Difference of MaxMin Divisor Pair** **(DMDP)** is the difference of the two elements of the pair which is `[9,14]=5` One more example for `544`. The divisors are: > > [1, 2, 4, 8, 16, **17, 32**, 34, 68, 136, 272, 544] > > > and **DMDP(544)=15** because `32-17=15` What about the **perfect squares**? All perfect squares have **DMDP=0** Let's take for example `64` with divisors > > {1, 2, 4, **8**, 16, 32, 64} > > > As you can see in this case the **MaxMin Divisor Pair** is `[8,8]` which has `DMDP=0` we are almost done.. # The Challenge Given an integer `n>0`, output **how many integers less than or equal to** `10000`, **have DMDP less than** `n` # Test Cases ***input -> output*** ``` 1->100 (those are all the perfect squares) 5->492 13->1201 369->6175 777->7264 2000->8478 5000->9440 9000->9888 10000->10000 20000->10000 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").Shortest answer in bytes **wins**. [Answer] ## JavaScript (ES7), 60 bytes ``` f=(n,i=1e4,j=i**.5|0)=>i?i%j?f(n,i,j-1):(i/j-j<n)+f(n,i-1):0 ``` Probably exceeds your recursion limit, so you might prefer the iterative version for 70 bytes: ``` n=>[...Array(1e4)].map(g=(j=++i**.5|0)=>i%j?g(j-1):k+=i/j-j<n,i=k=0)|k ``` [Answer] # Java 8, ~~151~~ ~~111~~ ~~110~~ ~~101~~ 98 bytes ``` n->{int r=0,x=10000,i;for(;x-->0;r-=i-n>>-1)for(i=x;i-->1&&(x<i*i|x%i>0||(i=x/i-i)>i););return r;} ``` -10 bytes thanks to *@Nevay*. -3 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##jZFRT8MgFIXf@yvuiwuYUYuLNguWf@Be9mh8QNaZO7vbhtKlZu1vr7Tu1SABEs75knOAk7kYUTclnQ5fk61M28KrQbomAEi@dEdjS9jNx0UAy@aduArKGFaYrTceLeyAoICJhL7OiCuydV/ILIw1qmPtmOqF0JlyokBBWgvJZxWLXmEw5GrF@he8x6G/Q50Nw@w8oECukSuuXOk7R@DUOKkkpDbdRxVSb@GXGg9wDsXZ3jukz7d3MPy39f679eU5rTufNsHyFTFKLZN8ucOf/lPEl5sIsHneRog8zyPEY3i9WM84so0jyz/9o8yNGZNx@gE) ``` n->{ // Method with integer as parameter and return-type int r=0, // Result-integer, starting at 0 x=10000, // Index-integer `x` for the outer loop, starting at 10,000 i; // Index-integer `i` for the inner loop, uninitialized for(;x-->0; // Loop `x` in the range (10000, 0]: r-=i-n>>-1) // If the MaxMin-Divisor Pair's difference is lower than the input, // add 1 to the result (after every iteration) for(i=x;i-->1 // Inner loop `i` in the range (`x`, 1]: &&(x<i*i // If the current square of `i` is smaller than or equals to `x`, |x%i>0 // and the current `x` is divisible by `i`: ||(i=x/i-i)// Calculate the MaxMin-Division difference >i);); // And stop the inner loop return r;} // After the loops, return the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes 1 byte thanks to Jonathan Allan. ``` ȷ4RÆDạU$Ṃ€<⁸S ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//yLc0UsOGROG6oVUk4bmC4oKsPOKBuFP///8yMDAw "Jelly – Try It Online") [Answer] # [R](https://www.r-project.org/), 73 ~~77~~ bytes Thanks to @Guiseppe for the 4 bytes ``` sum(sapply(1:1e4,function(x)min(abs((w=which(x%%1:x<1))-rev(w))))<scan()) ``` [Try it online!](https://tio.run/##DcFRCoAgEAXA0whvoUChfsQOY2IopIlm2umtmTxGqQFFp3S@EFLYZTpqNLe/IjoFH6H3ArStOW8cOmNCdiWI5mwfNPqpYnQE0Vg55@MD "R – Try It Online") Have lost the vectorize function to calculate the DMDP and is now using a sapply over the function. The truthies for items which are less than the input are summed for the result. [Answer] # Mathematica, 64 bytes ``` Count[Divisors~Array~1*^4,a_/;#+a[[i=⌈Tr[1^a]/2⌉]]>a[[-i]]]& ``` [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) ## Usage ``` f = Count[Divisors~Array~1*^4,a_/;#+a[[i=⌈Tr[1^a]/2⌉]]>a[[-i]]]& ```   ``` f[1] ``` > > > ``` > 100 > > ``` > > ``` f /@ {1, 5, 13, 369, 777, 2000, 5000, 9000, 10000, 20000} ``` > > > ``` > {100, 492, 1201, 6175, 7264, 8478, 9440, 9888, 10000, 10000} > > ``` > > ## Explanation ``` Divisors~Array~1*^4 ``` Generate the lists of divisors, from `1` to `10000`. (the lists of divisors are sorted automatically) ``` Count[ ..., a_/; ... ] ``` Count the occurrences of elements `a`, such that... ``` #+a[[i=⌈Tr[1^a]/2⌉]]>a[[-i]]] ``` `(input) + (left one of the middle element(s)) > (right one of the middle element(s))` If there is only one middle element, left = right. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ ~~17~~ ~~16~~ ~~15~~ 12 bytes ``` 4°ƒNÑÂα{нI‹O ``` [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//zTCsMaSTsORw4LOsXvQvUnigLlP//83Nzc "05AB1E – Try It Online") **Explanation** ``` 4°ƒ # for N in [0 ... 10**4] do: NÑ # push divisors of N Â # bifurcate α # element-wise absolute difference { # sort н # pop the head (smallest difference) I‹ # is it smaller than the input? O # sum the stack ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` 1e4:"@Z\2Y"dJ2/)G<vs ``` The code times out in TIO. Here's an example run with the offline compiler: ``` >> matl 1e4:"@Z\2Y"dJ2/)G<vs > 13 1201 ``` [Answer] # [R](https://www.r-project.org/), 91 bytes ``` function(n)sum(sapply(1:1e4,function(x,d=(1:x)[x%%1:x<1])diff(d[median(seq(d))+.5*0:1]))<n) ``` Takes a different (worse) approach to computing the DMDP than [MickyT's solution](https://codegolf.stackexchange.com/a/141007/67312) by using array indexing and `diff` to compute it. Alas. [Try it online!](https://tio.run/##PclBCoMwEEbhvfcQ5q@hJFA3Yk4iXUgnA4E6VaOQnj5m5erB@/YivsipnyP@lBTpXCjN6/r9kxtceJnbsmFfX8aU27Z2dG9wFCGelsBxVkphIwa6Z/@wQ1WMiiLk0Aj11lqUCw "R – Try It Online") [Answer] # Mathematica, ~~119~~ 115 bytes ``` (n=#;Tr[1^Select[Last@#-First@#&/@(Take[Divisors@#,Round[{-.1,.1}+(1+Length@Divisors@#)/2]]&/@Range@10000),#<n&]])& ``` I *finally* got this thing working and I've been trying for the past half an hour. .\_. ## Example run [![no description for you!](https://i.stack.imgur.com/atqki.png)](https://i.stack.imgur.com/atqki.png) [Answer] # Mathematica, 78 bytes ``` (s=#;Tr[1^Select[Table[#2-#&@@Quantile[Divisors@i,{.5,.51}],{i,10^4}],#<s&]])& ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 19 bytes ``` #ȯV<⁰Sz≠↔§f`¦ḣḣ□100 ``` No TIO link, since it times out. [This version](https://tio.run/##yygtzv7/X/nE@jCbR40bgqsedS541Dbl0PK0hEPLHu5YDESGBgb///83BAA "Husk – Try It Online") uses 100 in place of 10000 and finishes in a couple of seconds. ## Explanation Husk has no divisors built-in or support for scientific notation yet. ``` #ȯV<⁰Sz≠↔§f`¦ḣḣ□100 Input is n (accessed with ⁰). □100 Square of 100: 10000 ḣ Inclusive range from 1. # Count number of elements for which ȯ this composition of 3 functions gives truthy result: Argument k, say k = 12. §f`¦ḣ Divisors of k: ḣ Range: [1,2,3,..,12] §f Filter by `¦ divides k: [1,2,3,4,6,12] Sz≠↔ Absolute differences of divisor pairs: ↔ Reverse: [12,6,4,3,2,1] Sz Zip with divisor list ≠ using absolute difference: [11,4,1,1,4,11] V<⁰ Is any of these less than n? ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~25~~ ~~19~~ 17 bytes ``` L²õÈâ ®aX/ZÃd<UÃè ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=TLL1yOIgrmFYL1rDZDxVw+g=&input=MTM=) --- ## Explanation Implicit input of integer `U`. ``` L²õ ``` Generate an array of integers (`õ`) from 1 to 100 (`L`) squared. ``` Èâ Ã ``` Pass each through a function (where `X` is the current element) that generates an array of the divisors (`â`) of `X`. ``` ® Ã ``` Map over that array of divisors, where `Z` is the current element. ``` aX/Z ``` Get the absolute difference (`a`) of `Z` and `X` divided by `Z`. ``` d<U ``` Are any of the elements (`d`) in the resulting array less than `U`? ``` è ``` Count the truthy elements and implicitly output the result. [Answer] # Ruby, 62 bytes ``` ->n{(1..1e4).count{|x|(1..x).any?{|i|1>x%i&&x/i<=i&&i-x/i<n}}} ``` [Try it online.](https://tio.run/##KypNqvyfZvtf1y6vWsNQT88w1URTLzm/NK@kuqaiBiRSoamXmFdpX12TWWNoV6GaqaZWoZ9pYwukM3VBrLza2tr/BaUlxQpp0aYGBgax/wE) [Answer] # TI-BASIC, 46 bytes Note that TI-BASIC is a tokenized language. Also, the E in line 2 is a small capital E, found by pressing 2ND+, . ``` Input A DelVar DFor(B,1,E4 For(C,1,√(B If not(fPart(B/C B/C-C<A End D+Ans→D End ``` Result will be in D, and Ans immediately after program execution. If it is to be displayed, adding two more bytes (newline and `Ans`) would suffice. [Answer] # [Python 2](https://docs.python.org/2/), 134 bytes ``` lambda i:len(filter(lambda n:n<i,[reduce(lambda x,y:y-x,[[x,n/x]for x in range(1,int(n**.5+1))if n%x<1][-1])for n in range(1,10001)])) ``` [Try it online!](https://tio.run/##TY5BDsIgEEX3nmI2JqCjgkabEj0JsqgKSlKnDcWEnr6Wqombv3jz/s@0fXw0tB3c6TzU1fNyq8Cr2hJzvo42sC8jRUePOtjb62p/MGGv@lVCrRPSJhnXBEjgCUJFd8skeoqMFov1fik59w5ono7S6JU0PLv070ohhOSG8yHaLnZwAi0R9ghyh7A7lAhFUSBsR23EU5ZT5qL4HISZzfKwz8PTjII2jF@AY54Pbw "Python 2 – Try It Online") Eugh... need to do *much* better. [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes A bit on the slow side, uses 5 seconds per test case ``` lambda x:sum(x>min(abs(y/t-t)for t in range(1,y+1)if y%t<1)for y in range(1,10001)) ``` [Try it online!](https://tio.run/##TY1dC4IwFIav81ecm2CjE22KiZL9kYqY5WqQU9wJ3K9fTejj5r143q/B0723adD1MTxU11wVTJV7dmzad8Yy1TjmN7QmrvsRCIyFUdlbyyT6leRGg1/STs6u/3elEEJyHqh1dL4o1zqo4SAxR5lhti2xKApM3yHMo5RRYkfMUJyS@e9Tjsu/pSpZDKOxBJp9IQ8v) [Answer] # PHP, 94+1 bytes ``` for(;$n++<1e4;$c+=$d<$argn)if(($i=$n**.5)>~~$i){while($n%++$i);for($d=1;$n%--$i;)$d++;}echo$c; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/d29d5bceac53b3881f2eed6e7006def821897f88). [Answer] # VB.NET (.NET 4.5) ~~116~~ 115 bytes ``` Function A(n) For i=1To 10^4 Dim s As Byte=Math.Sqrt(i) While i Mod s>0 s-=1 End While A-=i/s-s<n Next End Function ``` --- Explanation: A function that takes `n` as a parameter, and returns the result. Starts at the square root, and looks for the nearest integer that evenly divides (will be the smaller of the `MaxMin Divisor Pair`). Then gets the larger of the pair (`i/s`), finds the difference, and compares against the input. --- Golfing strategies used: * `Dim` is expensive, so the fewer variables I declare the better. * I start searching at the square root, but only want to look at integers. By declaring `s` as an integral type, it casts to the floor for me. * VB uses `^` as exponent. So while `10000` is 5 characters, `10^4` is only 4. * VB creates an automatic variable with the same name and type as the function definition (in my case A). At the end of the function, if there is no `return`, the value of the function variable will be returned instead. So I save characters by not declaring a separate variable and not using a return statement. * VB has very forgiving typing/casting. `i` is assumed `Integer` because I assigned a integer literal. `A` is assumed `Object` but as soon as I add an integer, it behaves like an `Integer`. * Rather than `if` checking the that the difference is satisfactory, add it directly to the result by casting the boolean to an integer. However, VB uses `-1` for `True`, so subtract to get the correct sign. * Technically, we want `Mod` to not be `0`. Taking the modulus of a negative number in VB.NET will give a negative result. But, everything is positive so I can save a byte by turning `<>` into `>`. * The largest number to check is 10000. The square root of that is 100. So I only need a `Byte` to store that, saving bytes in the declaration by using a shorter named type. [Try it online!](https://tio.run/##fdE9b8MgEAbgnV9xW82AC01SK1JdyW2Tqc6SSNkqEfvUnOSAArgfv97FVN1qszA8d7yn44N8rztx0p4aYTCIizV2qG3bdwg1e6ELEGgPZAK@o4MbqGMBOLz25NBDi02nnQ5kjYfPM8WufLc5wDJfQWtjgbFh2PamGSugygxnW@uASnWwoOTbMkV4qDw8fQcsax3O@f7qQkacHdN7FCNb8I@SeVEqtjEtJGCVKOnWC/9g2A6/QpK/qGHfn6DWZBh7jqPZDvOjo4CvZDCrMsUhHv6vrWZMLfikLe7XfMqKopi0Oykln5plxtYzpuSI03mjsbSwuKd0/3758AM) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 104 bytes ``` x=>{int o=0,i=1;for(;i<=10000;i++)for(int j=1;j<=i;j++)if(i%j<1&Math.Abs(j-i/j)<x){o++;break;}return o;} ``` [Try it online!](https://tio.run/##fdFBS8MwFAfws/0UYag0dJ3NSi0lTUEETw4GHjyIh6ym89WZQJLKpPSz17Rz4EGSQ/J4@RH@SWoT10qLsTMg9@jp21jxSYP6wI1B2z4wlluo0UMn6xKkXSI3VQ0bj6zqXYkUS5bACG2UDimUjCRuUIgiPHUm0brdtmRAW9eEJoSrtiTXG27fV3c7E7Yx3LS4POJeRRHdacE/6KCF7bREig4jPUf4UvCGNhxkaKx2WV9eEdd7g/vg4l5Jow5i9azBikeQIrxckLjqm5DgYYHp/yKbReYRJD0dknpMelvMyK0elef5rNzqUWv3djObCl/ys8v8rji7wu/mTztdNfHLdfI34q8cgmH8AQ "C# (.NET Core) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes ``` Boole@Array[AtomQ@√(4a+#^2)&,#,0,Or]~Sum~{a,1*^4}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yk/PyfVwbGoKLEy2rEkPzfQ4VHHLA2TRG3lOCNNNR1lHQMd/6LYuuDS3LrqRB1DrTiTWrX/AUWZeSXRyrp2aQ7KsWp1wcmJeXXVXIY6XKY6XIbGOlzGZpY6XObm5jpcRgYGBkBhMGkJJg0NwBRIwoCr9j8A "Wolfram Language (Mathematica) – Try It Online") Slow. ]
[Question] [ **See also: [Parsing](https://codegolf.stackexchange.com/questions/90333/number-plate-golf-parsing)** ## Introduction You're working on a government programming team, who have been programming the speed cameras. However, the group of people who have programmed the speed calculator have taken up too much space, so you have to make the number plate recognition software as small as possible. ## Challenge Given an image of a number plate, return the text on the plate. ## Number plates The following are all of the characters which your program must recognise: ### ABCDEFG ![](https://i.stack.imgur.com/sMT8h.jpg) ### H1JKLMN0 ![](https://i.stack.imgur.com/mlGmd.jpg) ### PQRSTUVW ![](https://i.stack.imgur.com/9PplD.jpg) ### XYZ01234 ![](https://i.stack.imgur.com/MT3Xb.jpg) ### 56789 ![](https://i.stack.imgur.com/RDbR0.jpg) ### Note On British number plates, the characters for I (i) and 1 (one) are the same and the characters for O (o) and 0 (zero) are the same. For that reason, always assume characters are the numbers. I.e. the following number plate is 10 (one zero): ![](https://i.stack.imgur.com/Qatfa.jpg) ## Examples ### C0D3 GLF ![](https://i.stack.imgur.com/njTF4.jpg) ### B3T4 DCY ![](https://i.stack.imgur.com/Eoh40.jpg) ### M1NUS 15 ![](https://i.stack.imgur.com/EQcA0.jpg) ### YET1CGN ![](https://i.stack.imgur.com/SuYt0.png) ## Other rules Internet access and OCR libraries and functions are disallowed. The number plates will always look identical to the ones shown above. All number plates will be roughly same size (there will be some inaccuracies due to cropping method). If you require lossless PNG versions of any number plates, I will supply them to you. ## Scoring The shortest program in bytes wins. **All number plates are screenshots of the search bar at [this site](http://www.click4reg.co.uk)** [Answer] # C, 409 bytes (and I'm as surprised as anybody) ``` f(w,h,d,X,T,B,x,y,b,v,u,t,a)char*d;{for(x=X=0;++x<w;){for(y=b=h;y--;a=0)d[(y*w+x)*3+1]&224||(b=0,X||(X=x,T=B=y),T=y<T?y:T,B=y>B?y:B);if(X*b){for(B+=1-T,X=x-X,v=5;v--;)for(u=4;u--;a|=(b>X/4*(B/5)*.35)<<19-u*5-v)for(b=0,t=X/4;t--;)for(y=B/5;y--;)b+=!(d[((v*B/5+y+T)*w+x-X+u*X/4+t)*3+1]&224);X=!putchar("g------a----mj---et-u--6----7--8s4-c-x--q--d9xy5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l"[a%101-7]);}}} ``` Takes as input: the width (`w`) and height (`h`) of the image, followed by the packed RGB data as an array of `char`s (`d`). All the other function parameters are variable declarations in disguise. Ignores everything except the green channel, and applies a threshold of 32 as an initial pass. Mostly the same as @DavidC's method, except this checks that at least 35% of each sample box is filled. Hopefully that makes it more robust to scale changes, but who knows. I used a brute-force method to find out which resampling size and coverage percent to use for the best reliability (i.e. fewest cases of one character having multiple interpretations). It turned out that a 4x5 grid with 35% coverage was best. I then used a second brute-force method to calculate the best bit arrangement and modulo value to pack the character data into a short string — the low bit at the top-left, increasing in x then y, with the final value % 101 turned out best, giving this lookup table: ``` -------g------a----mj---et-u--6----7--8s4-c-x--q--d9xy5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l-- ``` Subtracting 7 means the initial -'s can be removed, and the last 2 can be removed without any extra work. This removal means that certain invalid inputs could cause an invalid memory read, so it could segfault on particular images. ### Usage: To get the images into it, I wrote a wrapper using libpng. Also it turns out that despite the filename, the images in the question are actually jpegs (!), so you'll need to manually export them as pngs first. ``` #include <png.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char *const *argv) { if(argc < 2) { fprintf(stderr, "Usage: %s <file.png>\n", argv[0]); return 1; } const char *file = argv[1]; FILE *const fp = fopen(file, "rb"); if(fp == NULL) { fprintf(stderr, "Failed to open %s for reading\n", file); return 1; } png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ); if(!png_ptr) { fclose(fp); fprintf(stderr, "Failed to initialise LibPNG (A)\n"); return 1; } png_infop info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); fclose(fp); fprintf(stderr, "Failed to initialise LibPNG (B)\n"); return 1; } if(setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); fprintf(stderr, "Error while reading PNG\n"); return 1; } png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 0); png_read_png( png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_GRAY_TO_RGB | PNG_TRANSFORM_STRIP_ALPHA, NULL ); const png_bytep *const rows = png_get_rows(png_ptr, info_ptr); const int w = png_get_image_width(png_ptr, info_ptr); const int h = png_get_image_height(png_ptr, info_ptr); unsigned char *const data = malloc(w*h*3 * sizeof(unsigned char)); for(int y = 0; y < h; ++ y) { for(int x = 0; x < w; ++ x) { memcpy(&data[y*w*3], rows[y], w * 3 * sizeof(unsigned char)); } } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); f(w, h, (char*) data); free(data); return 0; } ``` ### Breakdown ``` f( // Function w,h,d, // Parameters: width, height, RGB data X,T,B,x,y,b,v,u,t,a // Variables )char*d;{ // K&R syntax to save lots of type decls for(x=X=0;++x<w;){ // Loop through each column of the image: for(y=b=h;y--;a=0) // Loop through pixels in column: d[(y*w+x)*3+1]&224||( // If green < 32: (char could be signed or unsigned) b=0, // This is not a blank line X||(X=x,T=B=y), // Start a new character if not already in one T=y<T?y:T, // Record top of character B=y>B?y:B // Record bottom of character ); if(X*b){ // If we just found the end of a character: // Check cell grid & record bits into "a" for(B+=1-T,X=x-X,v=5;v--;) for(u=4;u--;a|=(b>X/4*(B/5)*.35)<<19-u*5-v) // Calculate coverage of current cell for(b=0,t=X/4;t--;) for(y=B/5;y--;) b+=!(d[((v*B/5+y+T)*w+x-X+u*X/4+t)*3+1]&224); // Look up meaning of "a" in table & print, reset X to 0 X=!putchar( "g------a----mj---et-u--6----7--8s4-c-x--q--d9x" "y5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l" [a%101-7] ); } } } ``` [Answer] # Mathematica ~~1170 1270 1096 1059 650 528 570 551 525~~ 498 bytes The latest version saves 27 bytes by not requiring that the plate be "trimmed" before it is parsed. The penultimate version saved 26 bytes by using only 10 of the original 24 sample points. ``` z=Partition;h@i_:=i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@z[{45,99,27,81,63,81,9,63,45,63,9,45,45,45,63,45,45,27,45,9},2];f@p_:=h/@SortBy[Select[p~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},100<Last@ImageDimensions@#[[2,1]]<120&],#[[2,2,1]]&][[All,2,1]]/.Thread[IntegerDigits[#,2,10]&/@(z[IntegerDigits[Subscript["ekqeuiv5pa5rsebjlic4i5886qsmvy34z5vu4e7nlg9qqe3g0p8hcioom6qrrkzv4k7c9fdc3shsm1cij7jrluo", "36"]],4]/.{a__Integer}:> FromDigits[{a}])-> Characters@"BD54TARP89Q0723Z6EFGCSWMNVYXHUJKL1"] ``` --- 122 bytes saved through LegionMammal978's idea of packing the long list of base 10 numbers as a single, base 36 number. He pared another 20 bytes off the final code. The jump from 528 to 570 bytes was due to additional code to ensure that the order of the letters returned corresponded to the order of the letters on the license plate. The centroid for each letter contains the x-coordinate, which reveals the relative positions of the letters along x. --- **Ungolfed Code** ``` coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1]; h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :> ⌈z⌉ & /@ coordinates, {6, 4}]; plateCrop[img_]:=ColorReplace[ImageTrim[img,{{100,53},{830,160}}],Yellow]; codes={{{15,13,15,13,13,15},"B"},{{15,8,8,8,9,15},"C"},{{15,13,13,13,13,15},"D"},{{15,8,14,8,8,15},"E"},{{15,8,14,8,8,8},"F"},{{15,8,8,11,9,15},"G"},{{6,6,6,6,15,9},"A"},{{9,9,15,15,9,9},"H"},{{8,8,8,8,8,15},"L"},{{9,15,15,15,13,9},"M"},{{15,9,9,9,9,15},"0"},{{9,10,12,14,10,9},"K"},{{9,13,13,11,11,9},"N"},{{8,8,8,8,8,8},"1"},{{1,1,1,1,9,15},"J"},{{15,9,15,14,8,8},"P"},{{15,9,9,9,15,15},"Q"},{{15,9,15,14,10,11},"R"},{{15,8,12,3,1,15},"S"},{{9,15,6,6,6,6},"V"},{{15,6,6,6,6,6},"T"},{{9,15,15,15,15,15},"W"},{{9,9,9,9,9,15},"U"},{{9,14,6,6,14,9},"X"},{{9,14,6,6,6,6},"Y"},{{15,3,2,4,12,15},"Z"},{{15,9,9,9,9,15},"0"},{{8,8,8,8,8,8},"1"},{{15,1,3,6,12,15},"2"},{{15,1,3,1,9,15},"3"},{{2,6,6,15,2,2},"4"},{{7,12,14,1,1,15},"5"},{{15,8,14,9,9,15},"6"},{{15,1,2,2,6,4},"7"},{{15,9,15,9,9,15},"8"},{{15,9,15,1,9,15},"9"}}; decryptRules=Rule@@@codes; isolateLetters[img_]:=SortBy[Select[ComponentMeasurements[plateCrop[img],{"Image","Centroid"}],ImageDimensions[#[[2,1]]][[2]]>100&],#[[2,2,1]]&][[All,2,1]] f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolateLetters[plate]/.decryptRules ``` **Overview** The basic idea is to check whether a systematic sampling of pixels from the input image matches pixels from the same location on the bonafide images. Much of the code consists of the bit signatures for each character, The diagram shows the pixels that are sampled from the letters "J", "P","Q", and "R". [![jpqr](https://i.stack.imgur.com/qFSve.png)](https://i.stack.imgur.com/qFSve.png) The pixel values can be represented as matrices. The dark, bold `1`'s correspond to black cells. The `0`'s correspond to white cells. [![jjjj](https://i.stack.imgur.com/M8mkJ.png)](https://i.stack.imgur.com/M8mkJ.png) These are the decryption replacement rules for J P Q R. {1, 1, 1, 1, 9, 15} -> "J", {15, 9, 15, 14, 8, 8} -> "P", {15, 9, 9, 9, 15, 15} -> "Q", {15, 9, 15, 14, 10, 11} -> "R" It should be possible to understand why the rule for "0" is: {15, 9, 9, 9, 9, 15} -> "0" and thus distinguishable from the letter "Q". --- The following shows the 10 points used in the final version. These points are sufficient for identifying all of the characters. [![reduced](https://i.stack.imgur.com/G8612.png)](https://i.stack.imgur.com/G8612.png) --- **What the functions do** `plateCrop[img]` removes the frame and left edge from the plate, makes the background white. I was able to eliminate this function from the final version by selecting image components, possible letters that were between 100 and 120 pixels high. [![platecrop](https://i.stack.imgur.com/0iYRY.png)](https://i.stack.imgur.com/0iYRY.png) --- `isolateLetters[img]` removes the individual letters from the cropped image. We can display how it works by showing where the cropped image, output from `plateCrop` goes as input for `isolateLetters`. The output is a *list* of individual characters. [![letters](https://i.stack.imgur.com/L26da.png)](https://i.stack.imgur.com/L26da.png) --- `Coordinates` are 24 evenly distributed positions for checking the pixel color. The coordinates correspond to those in the first figure. ``` coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1]; ``` {{9, 99}, {27, 99}, {45, 99}, {63, 99}, {9, 81}, {27, 81}, {45, 81}, {63, 81}, {9, 63}, {27, 63}, {45, 63}, {63, 63}, {9, 45}, {27, 45}, {45, 45}, {63, 45}, {9, 27}, {27, 27}, {45, 27}, {63, 27}, {9, 9}, {27, 9}, {45, 9}, {63, 9}} --- `h` converts the pixels to binary. ``` h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :> ⌈z⌉ & /@ coordinates, {6, 4}]; ``` --- `codes` are the signature for each character. The decimal values are abbreviations of the binary code for black (0) and White (1) cells. In the golfed version, base 36 is used. ``` codes={{{15, 9, 9, 9, 9, 15}, "0"}, {{8, 8, 8, 8, 8, 8}, "1"}, {{15, 1, 3,6,12, 15}, "2"}, {{15, 1, 3, 1, 9, 15}, "3"}, {{2, 6, 6, 15, 2, 2}, "4"}, {{7, 12, 14, 1, 1, 15},"5"}, {{15, 8, 14, 9, 9, 15}, "6"}, {{15, 1, 2, 2, 6, 4},"7"}, {{15, 9, 15, 9, 9, 15}, "8"}, {{15, 9, 15, 1, 9, 15},"9"}, {{6, 6, 6, 6, 15, 9}, "A"}, {{15, 13, 15, 13, 13, 15}, "B"}, {{15, 8, 8, 8, 9, 15}, "C"}, {{15, 13, 13, 13, 13, 15}, "D"}, {{15, 8, 14, 8, 8, 15}, "E"}, {{15, 8, 14, 8, 8, 8},"F"}, {{15, 8, 8, 11, 9, 15}, "G"}, {{9, 9, 15, 15, 9, 9}, "H"}, {{1, 1, 1, 1, 9, 15}, "J"}, {{9, 10, 12, 14, 10, 9}, "K"}, {{8, 8, 8, 8, 8, 15}, "L"}, {{9, 15, 15, 15, 13, 9}, "M"}, {{9, 13, 13, 11, 11, 9}, "N"}, {{15, 9, 15, 14, 8, 8}, "P"}, {{15, 9, 9, 9, 15, 15}, "Q"}, {{15, 9, 15, 14, 10, 11}, "R"}, {{15, 8, 12, 3, 1, 15}, "S"}, {{15, 6, 6, 6, 6, 6}, "T"}, {{9, 9, 9, 9, 9, 15}, "U"}, {{9, 15, 6, 6, 6, 6}, "V"}, {{9, 15, 15, 15, 15, 15}, "W"}, {{9, 14, 6, 6, 14, 9}, "X"}, {{9, 14, 6, 6, 6, 6}, "Y"}, {{15, 3, 2, 4, 12, 15}, "Z"}}; ``` (\* `decryptRules` are for replacing signatures with their respective character \*) ``` decryptRules=Rule@@@codes; ``` `f` is the function that takes an image of a license plate and returns a letter. ``` f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolate[plateCrop@plate]/.decryptRules; ``` [![plates](https://i.stack.imgur.com/9K5Xj.png)](https://i.stack.imgur.com/9K5Xj.png) {"A", "B", "C", "D", "E", "F", "G"} {"H", "1", "J", "K", "L", "M", "N", "0"} {"P", "Q", "R", "S", "T", "U", "V", "W"} {"X", "Y", "Z", "0", "1", "2", "3", "4"} {"5", "6", "7", "8", "9"} --- ## Golfed The code is shortened by using a single decimal number to represent all 24 bits (white or black) for each character. For example, the letter "J" uses the following replacement rule: `1118623 -> "J"`. 1118623 corresponds to ``` IntegerDigits[1118623 , 2, 24] ``` {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1} which can be repackaged as ``` ArrayReshape[{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}, {6, 4}] ``` {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}} which is simply the matrix for "J" that we saw above. ``` %//MatrixForm ``` [![matrix](https://i.stack.imgur.com/XDJMs.png)](https://i.stack.imgur.com/XDJMs.png) Another savings comes from representing the alphabet as `"0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"` rather than as a list of letters. Finally, all of the functions from the long version, except `h`, were integrated into the function `f` rather than defined separately. --- ``` h@i_:=ArrayReshape[i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@Join@@Table[{x,y},{y,99,0,-18},{x,9,72,18}],{6,4}];f@p_:=#~FromDigits~2&/@(Join@@@h/@SortBy[Select[p~ImageTrim~{{100,53},{830,160}}~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},Last@ImageDimensions@#[[2,1]]>100&],#[[2,2,1]]&][[;;,2,1]])/.Thread[IntegerDigits[36^^1c01agxiuxom9ds3c3cskcp0esglxf68g235g1d27jethy2e1lbttwk1xj6yf590oin0ny1r45wc1i6yu68zxnm2jnb8vkkjc5yu06t05l0xnqhw9oi2lwvzd5f6lsvsb4izs1kse3xvx694zwxz007pnj8f6n,8^8]->Characters@"J4A51LUHKNYXVMW732ZTCGSFE60Q98PRDB"] ``` [Answer] ## C#, ~~1040~~ 1027 bytes ``` using System;using System.Drawing;class _{static Bitmap i;static bool b(int x,int y)=>i.GetPixel(x,y).GetBrightness()<.4;static char l(int x,int y){if(y<45)return b(x+5,145)?((b(x+30,100)||b(x+30,50))?(b(x+68,94)?(b(x+40,50)?'D':b(x+40,120)?(b(x+45,80)?'M':'N'):'H'):b(x,97)?(b(x+30,140)?'E':b(x+60,70)?(b(x+50,140)?'R':'P'):'F'):b(x+65,45)?(b(x+5,100)?'K':b(x+30,145)?'Z':'X'):'B'):b(x+30,140)?'L':'1'):b(x+30,55)?(b(x+60,70)?'7':'T'):b(x+2,100)?'U':b(x+30,70)?'W':b(x+15,100)?'V':'Y';if(y<70)return b(x+50,110)?(b(x+50,70)?(b(x+10,110)?(b(x+30,100)?(b(x+55,80)?'8':'6'):b(x+55,80)?'0':'G'):b(x+10,70)?(b(x+60,80)?'9':'S'):b(x+60,120)?'3':'2'):'G'):b(x+30,125)?'Q':'C';if(y>150)return'A';if(y>120)return'J';else return b(x+10,135)?'5':'4';}static void Main(string[]z){i=new Bitmap(Console.ReadLine());bool s=true;int w=int.MinValue;for(int x=100;x<800;++x){for(int y=40;y<160;++y)if(s){if(b(x,y)){if(w>50)Console.Write(' ');Console.Write(l(x,y));s=false;goto e;}}else if(b(x,y))goto e;if(!s){s=true;w=0;}else++w;e:continue;}}} ``` Ungolfed: ``` using System; using System.Drawing; class _ { static Bitmap bmp; static bool b(int x, int y) => bmp.GetPixel(x, y).GetBrightness() < .4; static char l(int x, int y) { if (y < 45) return b(x + 5, 145) ? ((b(x + 30, 100) || b(x + 30, 50)) ? (b(x + 68, 94) ? (b(x + 40, 50) ? 'D' : b(x + 40, 120) ? (b(x + 45, 80) ? 'M' : 'N') : 'H') : b(x, 97) ? (b(x + 30, 140) ? 'E' : b(x + 60, 70) ? (b(x + 50, 140) ? 'R' : 'P') : 'F') : b(x + 65, 45) ? (b(x + 5, 100) ? 'K' : b(x + 30, 145) ? 'Z' : 'X') : 'B') : b(x + 30, 140) ? 'L' : '1') : b(x + 30, 55) ? (b(x + 60, 70) ? '7' : 'T') : b(x + 2, 100) ? 'U' : b(x + 30, 70) ? 'W' : b(x + 15, 100) ? 'V' : 'Y'; if (y < 70) return b(x + 50, 110) ? (b(x + 50, 70) ? (b(x + 10, 110) ? (b(x + 30, 100) ? (b(x + 55, 80) ? '8' : '6') : b(x + 55, 80) ? '0' : 'G') : b(x + 10, 70) ? (b(x + 60, 80) ? '9' : 'S') : b(x + 60, 120) ? '3' : '2') : 'G') : b(x + 30, 125) ? 'Q' : 'C'; if (y > 150) return 'A'; if (y > 120) return 'J'; if (y > 95) return b(x + 10, 135) ? '5' : '4'; return '-'; } static void Main(string[] args) { bmp = new Bitmap(Console.ReadLine()); bool state = true; int space = int.MinValue; for (int x = 100; x < 800; ++x) { for (int y = 40; y < 160; ++y) if (state) { if (b(x, y)) { if (space > 50) Console.Write(' '); Console.Write(l(x, y)); state = false; goto bad; } } else if (b(x, y)) goto bad; if (!state) { state = true; space = 0; } else ++space; bad: continue; } } } ``` Basically I found some specific reference points to check yellow/black to determine the identity of each character. [Answer] # PHP – ~~1741~~ ~~1674~~ 1143 bytes It was first set up by learning the profiles of the characters from the first few examples, which then summarized each character into six numbers. I chose six because I originally had five, and it didn't work as great as I'd like, but six seems to work much better. Much of the optimization involves squeezing these profiles into smaller and smaller byte counts. The first and second profile `*lhdfdn` and `|nnmmkk` are actually the blue blob with "GB" at the bottom `*`, and the right border `|`, which we're ignoring. It's safer to include them so that the blob and right border have something to match against. Should handle any image format, any reasonable scaling provided the aspect ratio doesn't change too much, any dark on light color, and even a bit of noise and shading! It does need the border, at least at the top and bottom, that's part of the profile. ``` <?php $X=[];foreach(str_split('*lhdfdn|nnmmkkA<njjk;BOnKB`^Chn::E7DHn?1X`EnkGGD4Fn_330!Gnj9G[IHnX!!XnJ%(##knKnX.EN6LnX!!!!Mn_<:bnNn^77_nPn^33@6QhfBDjnRn_8LaDSOlYYnUT$$nn$$Uh_##^nV9c][n;W_nWTlhXHnLTiCY4LhnM5ZJbnmaI0ng88lk1nnnnnn2C[__n`34B?Kna4+=Fnb"5NnUReX6gnKKaM7*4Xnb=8gkIIne9K`KKni',7)as$s){$t=[];foreach(str_split(substr($s,1))as$u)$t[]=ord($u)-11;$X[$s[0]]=$t;}echo m(r($argv[1]),$X)."\n";function r($u){$a=[];$i=imagecreatefromstring(file_get_contents($u));$w=imagesx($i);$h=imagesy($i);$s=[];for($x=0;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p['red']+6*$p['green']+$p['blue']<1280)$s[$x]++;}}$j=0;$k=[];for($x=0;$x<$w;$x++){if($s[$x]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$x];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,intval(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=intval($x*$m+0.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;$i++)$t+=pow($a[$i]-$x[$i],2);if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return trim($r,'|*');} ``` Save as `ocr.php`, then run from the command line: ``` $ php ocr.php http://i.imgur.com/UfI63md.png ABCDEFG $ php ocr.php http://i.imgur.com/oSAK7dy.png H1JKLMN0 $ php ocr.php http://i.imgur.com/inuIHjm.png PQRSTUVW $ php ocr.php http://i.imgur.com/Th0QkhT.png XYZ01234 $ php ocr.php http://i.imgur.com/igH3ZPQ.png 56789 $ php ocr.php http://i.imgur.com/YfVwebo.png 10 $ php ocr.php http://i.imgur.com/3ibQARb.png C0D3GLF $ php ocr.php http://i.imgur.com/c7XZqhL.png B3T4DCY $ php ocr.php http://i.imgur.com/ysBgXhn.png M1NUS15 ``` For those that are interested, here is the learning code. Save as `learn.php` and run from the command line, no arguments. ``` <?php define('BANDS', 6); main(); function main() { $glyphs = []; learn($glyphs, 'http://imgur.com/UfI63md.png', '*ABCDEFG|'); learn($glyphs, 'http://imgur.com/oSAK7dy.png', '*H1JKLMN0|'); learn($glyphs, 'http://imgur.com/inuIHjm.png', '*PQRSTUVW|'); learn($glyphs, 'http://imgur.com/Th0QkhT.png', '*XYZ01234|'); learn($glyphs, 'http://imgur.com/igH3ZPQ.png', '*56789|'); $profiles = summarize($glyphs); foreach ($profiles as $glyph=>$profile) { print $glyph; foreach ($profile as $value) print chr($value + 11); print "\n"; } } function learn(&$glyphs, $url, $answer) { $image = imagecreatefromstring(file_get_contents($url)); $width = imagesx($image); $height = imagesy($image); $counts = []; for ($x = 0; $x < $width; $x++) { $counts[$x] = 0; for ($y = 0; $y < $height; $y++) { $pixel = imagecolorsforindex($image, imagecolorat($image, $x, $y)); if (3 * $pixel['red'] + 6 * $pixel['green'] + $pixel['blue'] < 1280) $counts[$x]++; } } $index = 0; $expanded = []; for ($x = 0; $x < $width; $x++) { if ($counts[$x] > $height / 10) for ($inner = 0; $inner < BANDS; $inner++) $expanded[] = $counts[$x]; else if (count($expanded)) { $glyphs[$answer[$index]] = $expanded; $index++; $expanded = []; } } } function summarize($glyphs) { $profiles = []; foreach ($glyphs as $glyph=>$expanded) { $averages = []; $bands = array_chunk($expanded, count($expanded) / BANDS); foreach ($bands as $band) $averages[] = array_sum($band) / count($band); $scaling = 99 / max($averages); $profile = []; foreach ($averages as $average) $profile[] = intval($average * $scaling + 0.5); $profiles[$glyph] = $profile; } return $profiles; } ?> ``` [Answer] # PHP, ~~971~~ 970 bytes Draws heavily upon [Yimin Rong](https://codegolf.stackexchange.com/users/15259/yimin-rong)'s [answer](https://codegolf.stackexchange.com/a/90308/58556), which can be seriously golfed down, especially the array indices, and put into a Phar with gzip compression. [Download the phar](http://mehr.it/golf/ocr.phar) This is my improved base version at ~~1557~~ 1535 bytes, saved simply under the filename "o": ``` <?$X=[[99,92,45,45,97,96],[99,99,99,99,99,99],[56,80,84,84,99,85],[41,55,52,64,99,86],[32,50,59,99,87,23],[67,99,74,71,90,77],[92,99,64,64,86,66],[31,41,77,99,87,50],[92,96,62,62,99,90],[64,85,64,64,99,94],''=>[99,99,98,98,96,96],A=>[49,99,95,95,96,48],B=>[68,99,64,55,85,83],C=>[93,99,47,47,58,44],D=>[61,99,52,38,77,85],E=>[99,96,60,60,57,41],F=>[99,84,40,40,37,22],G=>[99,95,46,60,80,62],H=>[99,77,22,22,77,99],1=>[99,99,99,99,99,99],J=>[26,29,24,24,96,99],K=>[99,77,35,58,67,43],L=>[99,77,22,22,22,22],M=>[99,84,49,47,87,99],N=>[99,83,44,44,84,99],P=>[99,83,40,40,53,43],Q=>[93,91,55,57,95,99],R=>[99,84,45,65,86,57],S=>[68,97,78,78,99,74],T=>[25,25,99,99,25,25],U=>[93,84,24,24,83,99],V=>[46,88,82,80,99,48],W=>[84,99,76,73,97,93],X=>[61,99,65,73,94,56],Y=>[41,65,93,99,66,42],Z=>[63,87,99,98,86,62]];echo m(r($argv[1]),$X);function r($u){$a=[];$i=imagecreatefromstring(join('',file($u)));$w=imagesx($i);$h=imagesy($i);$s=[];for(;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p[red]+6*$p[green]+$p[blue]<1280)$s[$x]++;}}$j=0;$k=[];for(;$z<$w;$z++){if($s[$z]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$z];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,~~(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=~~($x*$m+.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;)$t+=($a[$i]-$x[$i++])**2;if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return$r;} ``` ## Improvements: 1st stage * Numeric array indices removed and reordered the array, string indices as implicit constants 2nd stage * Replaced `intval` with `~~` (saves 8 bytes, two occurences) * for-loop initialization removed where unnecessary * `file_get_contents($u)` replaced with `join('',file($u))` (saves 5 bytes) * and a few others Unfortunately, all the second stage improvements only translate into 1 byte less gzipped code. :-D And this code was used to create the Phar: ``` <?php $phar = new Phar('o.phar'); $phar->addFile('o'); $phar['o']->compress(Phar::GZ); $phar->setStub('<?Phar::mapPhar(o.phar);include"phar://o.phar/o";__HALT_COMPILER();'); ``` Test with `php ocr.phar http://i.imgur.com/i8jkCJu.png` or any other of the test case images. ]
[Question] [ [Martin](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) has created a [nice snippet](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet) that can be used to keep track of the score for answers to challenges. That's great and all, but wouldn't it be better if you could keep track of it yourself? Create a program that compares the byte counts in itself with the rest of the answers to this question, and returns "I'm answer number n". Rules: * The byte count in your own answer can be hardcoded in the code * The function can take the url as input, or it can be hardcoded. The chars for the url will not count toward the byte count, so it's not necessary to use a url-shortener. * url-addresses to answers cannot be hardcoded * The score for the answers can be found from the header, (the same way Martin's snippet does). * The answer header must have the correct format (described below). * If it's possible to run the program online, please share a link to an online compiler (or a code snippet that can be executed from the answer). If it's not possible, please show how to call the function, and show the output from your own compiler (at the time you posted the answer. You don't need to update it unless you want to of course). * You have to actually compare the answer with the other answers to this question. Simply writing a script `I'm answer number 1.` in some language is not legal. * If other answers have the same number of bytes as your own, you can choose if you want to be best or worse of them. The header must be formatted: ``` # Language Name, N bytes ``` Strike-through etc cannot be used, so if the code size is changed, show it in bold text below the header or indicate it in some other way. The output must be `I'm answer number n.`, where the number `n` is the position (trailing newline/spaces are OK). So, the shortest answer will output: "I'm answer number 1.", the second will be "I'm answer number 2." etc. This is code golf, so the shortest answer in bytes will win. [Answer] # Python 2, 145 bytes ``` from requests import* print"I'm answer number %s."%(sorted([int(a["body"].split(",")[1].split()[0])for a in get('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=activity&site=codegolf&filter=!SWJ_BpAceOT6L*G2Qa').json()["items"]]).index(145)+1) ``` Output from 2015-10-10 17:30:00 UTC: ``` I'm answer number 1. ``` I didn't count any of the URL for my score, if I should please comment on how much I should add to it. Has own score hardcoded in it, assumes that it's already posted. Will break if ever more than 99 answers are posted. [Answer] # AutoIt, 175 bytes (202 bytes - 27 for the URL) ``` #include<String.au3> $0=_StringBetween $1=1 For $2 In $0(BinaryToString(InetRead("http://q.codegolf.xyz/60204")),'<h1>',' b') $1+=$0($2,', ','')[0]<175?1:0 Next ConsoleWrite("I'm answer number "&$1&".") ``` Output from 2015-10-09 17:47:00 UTC: ``` I'm answer number 1. ``` [Answer] # JavaScript (ES7), 149 bytes 283 bytes - 134 for the URL. I've never use HTTP requests before, but here goes... ``` x=z=>alert(`I'm answer number ${[for(y of z.items)y.body.match(/, (\d+)/)[1]].sort().indexOf("149")+1}.`);document.write('<script src="//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T&callback=x">\x3C/script>') ``` Tested successfully in Firefox 41. First it looks through the headers of all the answers to find their byte-counts, then it finds the first position with byte-count ~~243~~ 149. It's currently set up to check only the first 100 answers, and will break if someone gets under 100 bytes, but it works for now. ;) Thanks to [@GeorgeReith](https://codegolf.stackexchange.com/questions/60204/how-are-you-doing#60297) for the much shorter technique. Old version using AJAX (243 bytes): ``` x=new XMLHttpRequest,x.onreadystatechange=_=>{if(x.readyState==4&&x.status==200)alert(`I'm answer number ${[for(y of JSON.parse(x.responseText).items)y.body.match(/, (\d+)/)[1]].sort((a,b)=>a-b).indexOf("243")+1}.`)},x.open("GET","//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T",!0),x.send() ``` [Answer] # PHP, 158 ~~159~~ ~~164~~ bytes ``` I'm answer number <?for(;$h[]=json_decode(fread(gzopen('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r),1e4),1)[items][+$i++][body];);echo array_sum(preg_filter(~„ÑÕß×£›ÔÖ߆‹šŒÃЗÎÑÕ‚Œš,~ÛÎÃÎÊÇ,$h)),~Ñ; ``` 127 bytes from `'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T'` not counted ### Formatted version with ungolfed strings: ``` <? for(; $h[]=json_decode( fread( gzopen( 'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r ), 1e4 ), 1 )[items][+$i++][body]; ); echo"I'm answer number ", array_sum( preg_filter('{.* (\d+) bytes</h1.*}se','$1<159', $h) ), "."; ``` * Loads the JSON response (one time per answer actually to save 5 bytes, thanks to @Blackhole) * Collects answer bodies in `$h` * replaces whole text with "1" (true) if the byte count is <=159, or "" (false) otherwise * sums the results The character sequences like `¶Ø’ßž‘Œˆšß‘Š’šß` are valid constant names in PHP, but because the constants do not exist are treated as string literal. `~` inverts them, this one to `"I'm answer number "` (saving a byte for one quotation mark each) ### Usage ``` php -derror_reporting=0 howareyou.php ``` > > I'm answer number 1. > > > [Answer] # Javascript (ES6), 186 bytes (335 - 149 bytes for the URL) ``` a=d=>alert(`I'm answer number ${d.items.map(q=>(y=[q.body.match(/, (\d+)/)[1],(x=q.owner.user_id==11182)])&&x?z=y:y).sort().indexOf(z)+1}.`) document.write(`<script src="https://api.stackexchange.com/questions/60204/answers?pagesize=100&order=desc&sort=activity&site=codegolf&filter=!)Q2B_A19OPkd2j8JforD00f5&callback=a">\x3C/script>`) ``` [Answer] # Perl, 107 bytes ``` use LWP;print"I'm answer number ",1+grep($_<107,LWP::UserAgent->new->get('http://codegolf.stackexchange.com/q/60204')->content=~/<h1>.+, (\d+)/g),'.'; ``` Slightly less golfed: ``` use LWP; $agent = new LWP::UserAgent(); $response = $agent->get('http://codegolf.stackexchange.com/q/60204'); @answers = $response->content =~ m/<h1>.+, (\d+)/g; print "I'm answer number ", 1+grep($_<107, @answers), '.'; ``` --- **Sample Usage** ``` $ perl my_rank.pl I'm answer number 1. ``` [Answer] # Awk, 153 bytes ``` BEGIN{if(u){print"I\047m answer number "system("curl -s "u"|awk -f a")".";exit}FS="1>.*,|es<\/h"}NF==3{r+=($2+0)<153?1:0}END{exit(r<1?1:r)} ``` This should be saved to a file `a` and run like: ``` awk -v u=http://codegolf.stackexchange.com/questions/60204/how-are-you-doing -f a ``` I'm subtracting the 68 bytes for `http://codegolf.stackexchange.com/questions/60204/how-are-you-doing` and adding 13 to the code for the bootstrapping `awk -v u=` and `-f a`. Less golfed, this can be even shorter: ``` curl -s http://codegolf.stackexchange.com/questions/60204/how-are-you-doing | awk -F"1>.*,|es<\/h" 'NF==3{r+=(0+$2)<103?1:0}END{print"I\047m answer number "(r<1?1:0)"."}' ``` It always prefers itself in ties. The byte count is hard coded in each. The more golfy version has the script calling itself and outputting the exit value via system. In each case only counts lower than the hard-coded value increment `r`, which then has to be adjusted back to `1` if it's leading. This will fail to correctly find bytes if there's whitespace between `bytes` and `</h1>` and probably a number of other cases I haven't considered. As of `Sun Oct 11 05:17:51 UTC 2015`, this gives: ``` I'm answer number 3. ``` [Answer] # GNU Awk, 156 bytes (Inspired by [n0741337](https://codegolf.stackexchange.com/users/46078/n0741337)'s [Awk solution](https://codegolf.stackexchange.com/a/60339).) This one does it all itself, without running external command. ``` BEGIN{d="/inet/tcp/0/"h"/80" print"GET "p" HTTP/1.1\nHost:"h"\n"|&d while(d|&getline)n+=match($0,/1>.*, ([0-9]+)/,m)&&m[1]<156 print"I'm answer number",n+1} ``` Expects hostname and path as separate values. Given they are available for free, hopefully this not breaks the rules. Sample run: ``` bash-4.3$ awk -v h=codegolf.stackexchange.com -v p=/questions/60204/how-are-you-doing -f number.awk I'm answer number 4 ``` ]
[Question] [ Given an unsorted list of unique strictly positive integers, minimally sort it into a 2D matrix. The input list is guaranteed to be of composite length, which means the output matrix is not necessarily square, but is of size `n x m` with `n,m > 1`. "Minimally sort" here means the following: * Sort the list in ascending order. * Compact the output matrix as much as possible -- minimize the sum of the dimensions of the matrix (for example, for `20` input elements as input, a `5x4` or `4x5` output matrix is required, and not a `2x10`). * Compact the sorted numbers as far to the upper-left of the matrix as possible, starting with the first element in the sorted list. * This can be thought of as sorting the list, then slicing it along the matrix's anti-diagonals, starting with the upper-left. ## Examples: For input `1..20` output is either a 5x4 or a 4x5 matrix as follows: ``` 1 2 4 7 11 3 5 8 12 15 6 9 13 16 18 10 14 17 19 20 1 2 4 7 3 5 8 11 6 9 12 15 10 13 16 18 14 17 19 20 ``` For input `[3, 5, 12, 9, 6, 11]` output is a 2x3 or 3x2 as follows ``` 3 5 9 6 11 12 3 5 6 9 11 12 ``` For input `[14, 20, 200, 33, 12, 1, 7, 99, 58]`, output is a 3x3 as follows ``` 1 7 14 12 20 58 33 99 200 ``` For input `1..10` the output should be a 2x5 or 5x2 as follows ``` 1 2 4 6 8 3 5 7 9 10 1 2 3 4 5 6 7 8 9 10 ``` For input `[5, 9, 33, 65, 12, 7, 80, 42, 48, 30, 11, 57, 69, 92, 91]` output is a 5x3 or 3x5 as follows ``` 5 7 11 33 57 9 12 42 65 80 30 48 69 91 92 5 7 11 9 12 33 30 42 57 48 65 80 69 91 92 ``` ### Rules * The input can be assumed to fit in your language's native integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ ~~22~~ 20 bytes ``` pS€ỤỤs LÆDżṚ$SÞḢç/ịṢ ``` [Try it online!](https://tio.run/##y0rNyan8/78g@FHTmoe7lwBRMZfP4TaXo3se7pylEnx43sMdiw4v13@4u/vhzkX/D7e7//8fbaqjYKmjYGyso2AGZBoa6SiY6yhYGOgomACZJhZAKSDb0FBHwRQobgZUagkUtzSMBQA) Saved 2 bytes thanks to @[Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). ## Explanation ``` pS€ỤỤs Helper link. Input: integer a (LHS), integer b (RHS) p Cartesian product between [1, 2, ..., a] and [1, 2, ..., b] S€ Sum each pair Ụ Grade up Ụ Grade up again (Obtains the rank) s Split into slices of length b LÆDżṚ$SÞḢç/ịṢ Main link. Input: list A L Length ÆD Divisors $ Monadic pair Ṛ Reverse ż Interleave Now contains all pairs [a, b] where a*b = len(A) SÞ Sort by sum Ḣ Head (Select the pair with smallest sum) ç/ Call helper link Ṣ Sort A ị Index into sorted(A) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~160~~ ~~158~~ ~~153~~ 151 bytes -2 bytes thanks to Erik the Outgolfer -2 bytes thanks to Mr. Xcoder ``` s=sorted(input()) l=len(s) x=int(l**.5) while l%x:x+=1 n=1 o=eval(`l/x*[[]]`) while s: for i in range(l/x)[max(0,n-x):n]:o[i]+=s.pop(0), n+=1 print o ``` [Try it online!](https://tio.run/##NY3LDsIgFAX3fMXdmECLtQ8bbRO@hJC0iWhJ8EKgKn59pQsXc1aTOf67Lg7bbYsiurDqGzXoXytljFhhNdLISBIGV2qLouoZ@SzGarCHNKZSNAQzTuj3bOlkT6mQUqnpb8WRwN0FMGAQwowPTbPD5HNOtOZ4TGxENTppVCli5Z2nNeMEcA/7kE/BbZtszhzaeidP13Fo2gyHC4dh4NBf1Q8 "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##TU7tasQgEPx/T7F/ymlue41J0w8Pn0SEC5zpCVZDlNY@faqxgQq6u@PszMw/8e5dt643PcFEAuUHyCeI4JeobxnYZiusdvuQhHGR2KY5DxX4vhurwT4knk6CbZD7q17or9GSq31KjZRKXf9vhGoGk1/AgHGwjO5Dk8yl8nNMpEX3mCh3intp1EmE8@xn0lKsa243m5ccCPwadYhByKrCsGMUZY8wILAO4R3hJXdMoWTPCF1bbn76vv4zhNfMyrThTeEuwhhVhxKwiJeMmwmvlqW/TKQUetmg43H9BQ "Python 2 – Try It Online") [Answer] # R ~~110~~ 95 bytes ``` function(x){n=sum(x|1) X=matrix(x,max(which(!n%%1:n^.5))) X[order(col(X)+row(X))]=sort(x) t(X)} ``` [Try it online!](https://tio.run/##LY3bCoMwDEDf/YruQUhZGUatU6H/IYwNxK0ozBaqYmHbt7t4eWiay8mJWzRTi55MM3bWgOcfo4apB/9FHlSqr0fXefCirz3Mbde0cDJhiKV5XCTnhNyse74cNPYNFT87O9PH72qwbiRbMFL5WzRgGUc80NBAIpgUDGPBCsEyypDvA0wFi6P1UUiSnUHBrkQSKvONwxIPkdwMK5gdQiJz2k0pTXMaRaudNqmfEVqsN@na8gc "R – Try It Online") ### How it works ``` f <- function(x) { n <- sum(x|1) # length p <- max(which(!n%%1:n^.5)) # height of matrix X <- matrix(x, p) # initialize matrix X[order(col(X) + row(X))] <- sort(x) # filling the matrix using position distance to the top left corner t(X) # probably required by OP } ``` [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) saved a whopping 15(!) bytes by the following tricks * replacing `length(x)` by `sum(x|1)` (-1 byte) * `floor()` is not required as `:` rounds down anyway (-7) * `^.5` is shorter than `sqrt()` (-3) * using `col(X) + row(X)` instead of `outer` (nice!) * could not get rid of the `t(X)` though - disappointing ;) ### Original solution ``` function(x){ n=length(x) p=max(which(!n%%1:floor(sqrt(n)))) X=outer(1:p,1:(n/p),`+`) X[order(X)]=sort(x) t(X)} ``` It would look more fancy with `outer` being replaced by `row(X)+col(X)`, but that would require to initialize the output matrix `X` first. [Try it online!](https://tio.run/##LY1bCsIwEEX/u4r4IUwwYqcva7H7EERQqrGFmtQYURDXXm9bAwkzuWfOuL7XYrsU@mkq31hDb/kJTNlezNXXaIKuvJ3e9KqbqqaZmc@50K21jh5358lInGBX2qe/OOKiU1yQWXVSHRdHBHvrzgh28lA@LHj4PLpvrwFHoQw0VRQrkSrBkRIbJTJULKeAEyWicLh44nhiWIk1SKBpPnJc8F@UjoYBzP5CkDlmE5RJjigc7JjEfwZ0M@zEtv4H "R – Try It Online") [Answer] # JavaScript (ES6), 172 bytes ``` l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r) ``` ## Explanation ``` l=>( // Take a list l as input l.sort((a,b)=>b-a), // Sort it n=l.length, // Get the length n w=l.findIndex((_,i)=>!(i*i<n|n%i)),// Find the first integer w where w >= √n and n % w = 0 a=l=>[...Array(l)], // Helper function a r=a(n/w).map(_=>a(w)), // Create the grid r of size w, n/w a(w+n/w).map((_,x)=> // For every x from 0 to w + n/w: r.map((s,y)=> // For every row s in r: x-y in s&&( // If the index x-y is in s: s[x-y]=l.pop()))), // Set s[x-y] to the next element of l r) // Return r ``` ## Test Cases ``` f=l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r) l=m=>console.log(JSON.stringify(m)) l(f([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])) l(f([3,5,12,9,6,11])) l(f([14,20,200,33,12,1,7,99,58])) l(f([1,2,3,4,5,6,7,8,9,10])) ``` [Answer] # [Perl 5](https://www.perl.org/), 132 bytes ``` sub d{$,=0|sqrt(@_=sort{$a-$b}@_);--$,while@_%$,;map{$r++,$c--for@_/$,..$c;$a[$r++][$c--]=$_;$c=++$i,$r=0if$r<0||$c<0||$r>=$,}@_;@a} ``` [Try it online!](https://tio.run/##HcztasIwGIbhU3mQd6A0afNW6wc1khPYETgJtSoGOluTjjFaT32Z7s/954K7O/umiDF8HXEaSGg1hrvvp8bq0Pp@oErS8WHsrJSSxPfVNWdj30iUn1U3kE8SQbWUl9Ybm5FIU6pLqvYvOOxfctBkS6p1kpAT5LVyF/JbNY5U/9fvNInnvzTVI4bqZ2LITp47nKaha1yffYQkE9vdLDJyzLFAgSVWWGMDVmAG5@A5eAEuwEvwCrwGb5Ar5Pzbdr1rbyHK9yJVrP4A "Perl 5 – Try It Online") Subroutine returns a 2-D array. TIO link includes footer code for displaying test result. [Answer] # [Octave](https://www.gnu.org/software/octave/), 151 bytes ``` function f(v)n=floor(sqrt(l=nnz(v)));while i=mod(l,n);++n;end;A=nan(m=l/n,n);for k=[1:m 2*m:m:l];do A(k)=sort(v)(++i);until~mod(k+=m-1,m)|k>l;end;A'end ``` Using three different kinds of loop constructs. [Try it online!](https://tio.run/##LY3LbsMgEEX3/YrZFQJVjF91jKiU74iyiGKjIsOgOo4jVVV/3RliLxhdXc6cidfpMvfLYu94nVxEsGzmaKyPcWS3n3Fi3iD@Usm5fnw734MzIXbMS@RaCNQ9dvpo8IIsGL/HVNs4wmBOqg2Q70IbWn/WXYQjG7i5RXLOnAnhuL7j5Px/0g3ChA8lA/8bvvzqfKe5WEaaPDvzN0qFhEqCyiUcJNSU1NqrUkKepUejKFZESfgkkMiq2bBWbaLqZUhkvQkJbWi5pFg29JUlO61SXxN6SDfp2vIE) **Unrolled:** ``` function f(v) n = floor(sqrt(l=nnz(v))); while i = mod(l,n); ++n; end; A = nan(m=l/n, n); for k = [1:m 2*m:m:l]; do A(k) = sort(v)(++i); until ~mod(k+=m-1, m) | k>l; end; A' end ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` ḟȯΛ≤Σ∂MCP¹→←½ḊL ``` This works by brute force, so longer test cases may time out. [Try it online!](https://tio.run/##AUIAvf9odXNr///huJ/Ir86b4omkzqPiiIJNQ1DCueKGkuKGkMK94biKTP///1szMCwxMSw1Nyw2OSw5Miw5MSw0LDYsNV0 "Husk – Try It Online") ## Explanation ``` ḟȯΛ≤Σ∂MCP¹→←½ḊL Implicit input, a list of integers x. L Length of x (call it n). Ḋ List of divisors. ½ Split at the middle. →← Take last element of first part. This is a divisor d that minimizes d + n/d. P¹ List of permutations of x. MC Cut each into slices of length d. ḟ Find the first of these matrices that satisfies this: ∂ Take anti-diagonals, Σ flatten them, ȯΛ≤ check that the result is sorted (each adjacent pair is non-decreasing). ``` [Answer] # JavaScript (ES6), 233 bytes ``` f=s=>{l=s.length;i=Math.sqrt(l)|0;for(;l%++i;);p=(x)=>(x/i|0+x%i)*l+x%i;m=[...Array(l).keys()].sort((x,y)=>p(x)-p(y));return s.sort((a,b)=>a-b).map((x,i)=>m.indexOf(i)).reduce((a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a,[])} ``` **Explanation** ``` f=s=>{ // Take array `s` of numbers as input l=s.length // short-hand for length i=Math.sqrt(l)|0 // = Math.floor(Math.sqrt(l)) for(;l%++i;); // i = width j=l/i // j = height p=(x)=>(x/i|0+x%i)*l+x%i // helper to calculate (sort-of) ~manhattan // distance (horizontal distance weighted // slightly stronger), from top-left corner // to the number x, if numbers 0,...,l are // arranged left-to-right, top-to-bottom // in an l=i*j grid m=[...Array(l).keys()] // range array .sort((x,y)=>p(x)-p(y)), // manhatten-sorted, sort-of... return s.sort((a,b)=>a-b) // sort input array by numbers, .map((x,i,w)=>w[m.indexOf(i)]) // then apply inverse permutation of the // range-grid manhatten-sort mapping. .reduce( // slice result into rows (a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a ,[] ) } ``` [Answer] # Java 10, ~~199~~ ~~188~~ 186 bytes ``` a->{int j=a.length,m=0,n,i=0,k=0;for(n=m+=Math.sqrt(j);m*n<j;n=j/++m);var R=new int[m][n];for(java.util.Arrays.sort(a);i<m+n;i++)for(j=0;j<=i;j++)if(i-j<n&j<m)R[j][i-j]=a[k++];return R;} ``` [Try it online.](https://tio.run/##dVLBbqMwEL3vV/i0gjKhGEISarxSP6A9pEfkg5eS1g42XeOkqqJ8ezpx2MMqG2Qse@bNzJs31nIvZ/p1e2p7OY7kSSp7@EGIsr5zG9l25Pl8DYZGNIK0UTgRGTO0H/HHNXrpVUueiSWcnOTs1wFBRHOZ9p198@9geAYWFO5bnrHN4CLLTcKfpH9Pxz/ORzpm5s7Wmlmu75PExGwvHVlz232G0kY0VoRAjYTTnVd9@uic/BrTccB4pKNqk1imkiQOMKyja66YRoPaRGqma/tT1yZeN1o0eBVcNtskEcx1fucsWbPjiV36@dj97rGfqa39oF6JQWGiF@@UfWuEjC@i@G700V@K4kAhhwLmUMIClrCCCmgGlALNgRZA50BLoAugS6AroBXk2TGoeJWowBQYVGEeSm9gMF2e4cqgKEIFLFlVUK5u4a/Jnb8b6BL9mHcReCA8g3kO8xUUoaFyCYsKKmQ4xf/7DoJgIeHlrZyPk2Ln0QSjfLBpGwVPHDyEvHyNvjPpsPPpB@rse3s9bD9cZoADn4j/J2qidDx9Aw) Based on [my answer here](https://codegolf.stackexchange.com/a/163276/52210). **Explanation:** ``` a->{ // Method with int-array parameter and int-matrix return-type int j=a.length, // Length of the input-array m=0,n, // Amount of rows and columns i=0,k=0; // Index integers for(n=m+=Math.sqrt(j); // Set both `m` and `n` to floor(√ `j`) m*n<j; // Loop as long as `m` multiplied by `n` is not `j` n=j/++m); // Increase `m` by 1 first with `++m` // and then set `n` to `j` integer-divided by this new `m` var R=new int[m][n]; // Result-matrix of size `m` by `n` for(java.util.Arrays.sort(a); // Sort the input-array i<m+n;) // Loop as long as `i` is smaller than `m+n` for(j=0;j<=i;j++) // Inner loop `j` in range [0,`i`] if(i-j<n&j<m) // If `i-j` is smaller than `n`, and `j` smaller than `m` // (So basically check if they are still within bounds) R[j][i-j]=a[k++]; // Add the number of the input array at index `k`, // to the matrix in the current cell at `[j,i-j]` return R;} // Return the result-matrix ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~269~~ ~~253~~ 226 bytes * Saved ~~16~~ ~~43~~ bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` j,w,h,x,y;c(int*a,int*b){a=*a-*b;}f(A,l)int*A;{int B[l];qsort(A,l,4,c);for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));} ``` [Try it online!](https://tio.run/##dU/LboMwEDy3XxEhpcIwSDav4Bg3Sn6DciBUlCCapEkqQIRvpwvqoYdG8tqrnceOc@cjz8exQoMSLTqVm4fjzcow3XvWZ9rKHGuvhsLcombTdKt6eha7pE7V1/V0uU0IfORMFaeL2ehSV9pVrW6s0qlVZdusXlb3@4SAMAZqJmjTrKtZoirdxsRWLXGnQae56mLdqo4GrdPFzUsXl5tdQr3dWU2qra1tr/mvOq7V@UKZCtN4Oy7fF4Zt0tZl88oZdkmVMqaG8TM7HE3WPz8V5vTFJGW9gAuPkgcIsUIECcEhBIQL4UH4EAFECLGCiCAkXD5QMXX@vl1Nw2Dqr5lHNiSU5CXEgPABjVxdTofD8@ZFtFlKBNEA@UjyT8yB6gE9IAJ5h3Mc4nP4LvwI3vy3YIVQQlJQCimCvx7D@AM "C (gcc) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), 214 bytes, using `-zexecstack`-lambdas * Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for this hackier, yet slimmer version. ``` j,w,h,x,y;f(A,l)int*A;{int B[l];qsort(A,l,4,L"\x62b078bǃ");for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));} ``` [Try it online!](https://tio.run/##dU/NboJAED63T9GQ2LDwkezyJ@tCjZ77BspBqaiUqhUaoMqpD9e3Kh1MDx5qspOdzPcz3yTWOkm6LkOFDWo0KtUnyNl2VxoTdaLvYTrLY/Ve7I9lj8DFszavfXvJh8Hy@0tjKt0f9SraRFlkqzqqjI2Vq8w0WT7IzuceAWEM1PTQuBplF4nKojoktqqJ2w@aiKsmjGrV0KC2mrB6bMLNeDqj3myMKo6MiWmO@J86zNXhSAFTXZvvBi8PmqnT1kH1xBmmsyxmTLXd22K709np/i7VdeLOYnYSsOHQGR58DBFAQnAIAWFDOBAuhAfhQwwhAggJm7dUTB0@ykLX6N5rM4dsSCjJS4gW/g0audqcHofjXBbRZinhBS3kLck/MVuqG3SPCOTtX@IQn8O14QZwLrd5Q/gSkoJSSOFde7TdT5Lmi3XRWZ@repUU5SJ5/QU "C (gcc) – Try It Online") ]
[Question] [ ### Introduction The *middle-square* method is used for the generation of pseudorandom numbers. However, this is not a good method in practice, since its period is usually very short and has some severe weaknesses. How does this work? Let's take an example: For the seed, we pick `123456`: ``` Seed 123456 ``` The seed squared (seed × seed), is equal to: ``` Seed² 15241383936 ``` We started with a **6-digit** number. That means that the seed squared should deliver a **12-digit** number. If this is not the case, leading zeroes are added to compensate: ``` Seed² 015241383936 ``` We then take the middle part of the number, with **the same size** as the seed: ``` Seed² 015241383936 ^^^^^^ ``` This is then our **new seed**: `241383`. We repeat the same process as shown above. We get the following: ``` 0: 123456 015241383936 | | 1: 241383 058265752689 | | 2: 265752 070624125504 | | 3: 624125 389532015625 | | 4: 532015 283039960225 | | 5: 039960 001596801600 | | 6: 596801 ``` And this keeps on in a while... Now we know what the middle-square method is, let's get to the challenge: --- ### The Task Every seed **has** a *period*. The period of a *n*-digit seed cannot be longer than 8n. For example, the seed `82`. This would give the following sequence: ``` 82 > 72 > 18 > 32 > 02 > 00 > 00 > 00 > 00 > 00 |____|____|____|____|____|____|____|____|____|___... 0 1 2 3 4 5 6 7 8 9 ``` You can see that the period is equal to **5**, before containing the same digit again. Your task is, **when given a seed greater than 0 containing no leading zeroes, output the period of the seed**. So, in this case, you need to output `5`. Another example is: `24`, which gives the following: ``` 24 > 57 > 24 |____|____|___... 0 1 2 ``` As you can see, not all sequences end in `0`. This cycle has a period of *1*. --- ### Test cases ``` Input > Output 24 > 1 82 > 5 123456 > 146 8989 > 68 789987 > 226 ``` The pastebins with the sequences for [123456](http://pastebin.com/MLxM9Pup), [8989](http://pastebin.com/HM1AhQFq), [789987](http://pastebin.com/X42VaX0r) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! **You can assume that the input will never have an uneven number of digits.** [Answer] ### Pure bash, ~~162 131 116 113~~ 107 Saved 3 bytes by using `$c`... Thanks [@Dennis](https://codegolf.stackexchange.com/posts/comments/179039?noredirect=1) for help me to save 6 more bytes. `---- begin middleSquare ----` ``` for((b=$1;i[c=10#$b]<2;)){ a=${#b} printf -v b %0$[a*2]d $[c*c] b=${b:a/2:a};((i[10#$b]++)) };echo ${#i[@]} ``` `---- end middleSquare ----` ``` for testCase in 24 82 123456 8989 789987 111111;do printf "%12s: " $testCase bash middleSquare $testCase done 24: 2 82: 5 123456: 146 8989: 68 789987: 226 111111: 374 ``` ### Square formated, 131 `---- begin middleSquare ----` ``` for((b=$1;i[ 10#$b]<2;1)) do a="${#b}" printf -v b\ %0$[a*2]d \ $[10#$b**2]; b=${b:a/2:a} ((i[10#$b]++ ));done;ech\ o ${#i[@]:0} ``` `---- end middleSquare ----` ``` for testCase in 24 82 123456 8989 789987 111111;do printf "%12s: %9d\n" $testCase $( bash middleSquare $testCase) done 24: 2 82: 5 123456: 146 8989: 68 789987: 226 111111: 374 ``` ### Old but with fancy output, 162 `---- begin middleSquare ----` ``` for((b=$1;i[10#$b ]<2;1))do a=${#b} printf -v b %0$[a *2]d $[10#$b**2] b=${b:a/2:a};((i[ 10#$b]++));print\ f "%9d %s\n" ${#\ i[@]} $b;done;ec\ ho -- ${#i[@]} -- ``` `---- end middleSquare ----` ``` bash middleSquare 24 1 57 2 24 2 57 -- 2 -- for testCase in 24 82 123456 8989 789987 111111 do while read f v f do r=$v;done < <( bash middleSquare $testCase) printf "%12s: %11d\n" $testCase $r done 24: 2 82: 5 123456: 146 8989: 68 789987: 226 111111: 374 ``` [Answer] # Jelly, ~~26~~ ~~24~~ 18 bytes ``` ³DL⁵* ²:¢½¤%¢µÐĿL’ ``` [Try it online!](http://jelly.tryitonline.net/#code=wrNETOKBtSoKwrI6wqLCvcKkJcKiwrXDkMS_TOKAmQ&input=&args=MTIzNDU2) ### How it works ``` ³DL⁵* Helper link. No arguments. ³ Yield the original input. D Convert from integer to base 10. L Get l, the length of the decimal representation. ⁵* Compute 10 ** l. ²:¢½¤%¢µÐĿL’ Main link. Input: n (integer) ² Square n. ¢½¤ Call the helper link and take the square root of the result. : Integer division; divide the left result by the right one. ¢ Call the helper link. % Take the left result modulo the right one. µ Convert the previous chain into a link, and begin a new chain. ÐĿ Repeat the previous chain until the results are no longer unique, updating n in each iteration. Collect the intermediate results. L Get the length of the list of results. ’ Decrement. ``` [Answer] ## JavaScript (ES7), 82 bytes ``` f=(n,p={},m=-1,l=n.length)=>p[n]?m:f(`${n*n+100**l}`.substr(l/2+1,l,p[n]=1),p,++m) ``` Accepts input in the form of a string, e.g. "82", and returns an integer. Simple tail recursive technique to check each seed in turn against a hash of seeds that have already been seen. I add 100\*\*l to the square to ensure a consistent length. [Answer] # Python ~~3~~ 2, ~~139~~ ~~114~~ 97 bytes Thanks to Seeq for golfing off 25 bytes and thanks to Dennis for golfing off 17 bytes! Code: ``` s=`input()`;u=[];l=len(s)/2 while not s in u:u+=[s];s=`int(s)**2`.zfill(l*4)[l:3*l] print~-len(u) ``` Can definitely be golfed further. This was also the code used to make the test cases :P. [Answer] # Pyth, 21 bytes ``` tl.us_<>_`^N2/lz2lzsz ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=tl.us_%3C%3E_%60%5EN2%2Flz2lzsz&input=123456&test_suite_input=24%0A82%0A123456%0A8989%0A789987&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=tl.us_%3C%3E_%60%5EN2%2Flz2lzsz&input=123456&test_suite_input=24%0A82%0A123456%0A8989%0A789987&debug=0&test_suite=1) edit: Found the edge case `1000`, which didn't worked with my previous code. Fixed it for 1 byte. ### Explanation: ``` tl.us_<>_`^N2/lz2lzsz implicit: z = input string .u sz apply the following instructions to N, starting with N = int(z), until it runs into a loop: ^N2 square it ` convert it to a string _ reverse order > /lz2 remove the first len(z)/2 < lz remove everything but the first len(z) _ reverse order s convert to int .u returns the list of all intermediate values l compute the length of this list t minus 1 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 33 ~~35~~ ~~40~~ bytes ``` `t0)2^10GVnXK2/^/k10K^\vtun@>]n2- ``` [**Try it online!**](http://matl.tryitonline.net/#code=YHQwKTJeMTBHVm5YSzIvXi9rMTBLXlx2dHVuQD5dbjIt&input=MTIzNDU2) ``` ` % do...while t % duplicate. Take input implicitly on first iteration 0) % pick last value of array 2^ % square 10 % push 10 GVn % number of digits of input XK % copy that to clipboard K 2/ % divide by 2 ^ % power /k % divide and floor. This removes rightmost digits from the square value 10K^ % 10 ^ number of digits of input \ % modulo. This takes the central part of the squared number v % concatenate this new number to array of previous numbers tun@> % does the number of unique values exceed the iteration index? ] % if so: next iteration. Else: exit loop n2- % desired result is the amount of numbers minus 2. Implicitly display ``` [Answer] # Oracle SQL 11.2, 184 bytes ``` WITH v(v,p,n)AS(SELECT:1,'0',-1 FROM DUAL UNION ALL SELECT SUBSTR(LPAD(POWER(v,2),LENGTH(v)*2,0),LENGTH(v)/2+1,LENGTH(v)),v,n+1 FROM v)CYCLE v SET c TO 1 DEFAULT 0 SELECT MAX(n)FROM v; ``` Un-golfed ``` WITH v(v,p,n) AS ( SELECT :1,'0',-1 FROM DUAL UNION ALL SELECT SUBSTR(LPAD(POWER(v,2),LENGTH(v)*2,0), LENGTH(v)/2+1, LENGTH(v)),v,n+1 FROM v ) CYCLE v SET c TO 1 DEFAULT 0 SELECT MAX(n) FROM v; ``` It uses the build in cycle detection to stop the recursivity. [Answer] # Julia, 64 bytes ``` f(n,A=[],p=10^endof(dec(n)))=n∈A?-1:f(n^2÷√p%p,[A...n],p)+1 ``` Try it with [Coding Ground](http://goo.gl/0osTMa). [Answer] # Mathematica, 80 bytes ``` (a=10^⌊Log10@#+1⌋;Length@NestWhileList[⌊#^2/a^.5⌋~Mod~a&,#,Unequal,All]-2)& ``` [Answer] # CJam, 37 bytes ``` q{__,W*:D;~_*sD2/<D>]___|=:A;~A}g],(( ``` Ran into an annoying stack-order issue that I can't immediately see how to resolve. It's also incredibly slow. How it works: Each iteration pushes the new value on top of the stack, then we wrap the stack into an array, and see if it's the same as its union with itself (to see if it has any duplicate elements). When it has duplicate elements, stop, and see how many elements are in the stack. [Answer] # Python 2, 82 bytes ``` def f(n,A=[],l=0):l=l or len(`n`)/2;return-(n in A)or-~f(n*n/10**l%100**l,A+[n],l) ``` Try it on [Ideone](http://ideone.com/FC1SfF). [Answer] ## Python, 124 bytes ``` def f(s,p=-1,n=0,m=[]): x=len(str(s))*2 while n not in m:m+=[s];y=str(s*s).zfill(x);n=int(y[x/4:x*3/4]);p+=1;s=n return p ``` [Answer] ## VBSCRIPT, 131 bytes ``` s=inputbox(c):l=len(s):do:t=t&","&s:s=space(l*2-len(s*s))&s*s:s=mid(s,l/2+1,l):i=i+1:loop until instr(t,","&s)>0:msgbox i-1 ``` Best I could do with vbscript, first time poster so go easy on me! ]
[Question] [ The goal of this challenge is to compute *one kind of* numerology digit from strings containing characters and numbers. * The input may be through any convenient method (standard input, arguments, separated file). * The input may contain any printable ASCII chars, but only alphanumerical (`A-Z`, `a-z`, and `0-9`) have to be considered. * The output must be a digit between `1` and `9` or a star `*` if no letter and no digit where found... (or even `0` if input contain any number of `0` *and* nothing else but this doesn't matter). * Letter values are mapped in this way: ``` 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z ``` * The *numerology digit* is computed by adding each value of string, then repeat until there is only one digit. Sample for `13579`, `Hello, world!`, `00 0 00`, `!@#$%^&*();`, and `3.141592`: ``` 13579 => 1 + 3 + 5 + 7 + 9 = 25 => 2 + 5 = 7 Hello, world! => 8 + 5 + 3 + 3 + 6 + 5 + 6 + 9 + 3 + 4 = 52 => 5 + 2 = 7 00 0 00 => 0 + 0 + 0 + 0 + 0 = 0 !@#$%^&*(); => * => * 3.141592 => 3 + 1 + 4 + 1 + 5 + 9 + 2 = 25 => 2 + 5 = 7 3.1415926535897932384 => 3 + 1 + 4 + 1 + 5 + 9 + 2 + 6 + 5 + 3 + 5 + 8 + 9 + 7 + 9 + 3 + 2 + 3 + 8 + 4 = 97 => 9 + 7 = 16 => 1 + 6 = 7 ``` (This is great, most of this samples give `7`! But it's just sample ;) Some more tests: ``` Bob => 2 + 6 + 2 = 10 => 1 + 0 = 1 Charlie => 3 + 8 + 1 + 9 + 3 + 9 + 5 = 38 => 3 + 8 = 11 => 1 + 1 = 2 Anna => 1 + 5 + 5 + 1 = 12 => 1 + 2 = 3 Fana => 6 + 1 + 5 + 1 = 13 => 1 + 3 = 4 Gregory => 7 + 9 + 5 + 7 + 6 + 9 + 7 = 50 => 5 + 0 = 5 Denis => 4 + 5 + 5 + 9 + 1 = 24 => 2 + 4 = 6 Erik => 5 + 9 + 9 + 2 = 25 => 2 + 5 = 7 Helen => 8 + 5 + 3 + 5 + 5 = 26 => 2 + 6 = 8 Izis => 9 + 8 + 9 + 1 = 27 => 2 + 7 = 9 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ### Shortest by language ``` <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 = document.referrer.split("/")[4]; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 0; 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] # Matlab, 121 bytes ``` s=[input('','s'),'*'];while nnz(s)>1;s=num2str(sum(mod([s(48<s&s<58)-4,s(96<s&s<123)+2,s(64<s&s<91)-2],9)+1));end;disp(s) ``` Matlab is just not made for strings =( [Answer] ## Mathematica, ~~174~~ ~~168~~ 163 bytes ``` Catch[#-9Floor[Max[#-1,1]/9]&@If[(a=Tr[Characters@#/.{(b=a_String)?DigitQ:>FromDigits@a,b?LetterQ:>LetterNumber@a~Mod~9,b->0}])<1&&#~StringFreeQ~"0",Throw@"*",a]]& ``` Does the first step, then computes the digital root. [Answer] # Ruby, ~~97~~ 74 characters ``` n=->s{(t=eval s.tr('a-z9A-Z','1-9'*6).scan(/\d/)*?+)&&t>9?n[t.to_s]:t||?*} ``` Sample run: ``` 2.1.5 :001 > n=->s{(t=eval s.tr('a-z9A-Z','1-9'*6).scan(/\d/)*?+)&&t>9?n[t.to_s]:t||?*} => #<Proc:0x00000001b4b3f0@(irb):4 (lambda)> 2.1.5 :002 > puts ['13579', 'Hello, world!', '00 0 00', '!@#$%^&*();', ' ', '3.141592', '3.1415926535897932384', 'Bob', 'Charlie', 'Anna', 'Izis'].map{|s|'%s : %s'%[n[s],s]} 7 : 13579 7 : Hello, world! 0 : 00 0 00 * : !@#$%^&*(); * : 7 : 3.141592 7 : 3.1415926535897932384 1 : Bob 2 : Charlie 3 : Anna 9 : Izis ``` [Answer] # Perl, ~~91 89 76~~ 74 bytes 73 + 1 for `-p` switch ``` s/[a-z]/(ord($&)%32-1)%9+1/eig;$t="*",s/\d/$t+=$&/eg,$_=$t until/^[*\d]$/ ``` Tests ``` for test in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' \ '3.141592' '3.1415926535897932384' \ Bob Charlie Anna Fana Gregory Denis Erik Helen Izis ;do perl -pe ' s/[a-z]/(ord($&)%32-1)%9+1/eig;$t="*",s/\d/$t+=$&/eg,$_=$t until/^[*\d]$/ ' < <(echo -n "$test") echo " $test" done ``` ``` 7 13579 7 Hello, world! 0 00 0 00 * !@#$%^&*(); * 7 3.141592 7 3.1415926535897932384 1 Bob 2 Charlie 3 Anna 4 Fana 5 Gregory 6 Denis 7 Erik 8 Helen 9 Izis ``` Thanks @manatwork for helping me to save **~~2 14 16 15~~ 17** chars!! ... I've thinked about: *`N % 32 + Y` may replace `( N & 31 ) + Y`*! [Answer] ## ES6, 98 bytes ``` s=>(m=s.match(/[1-9a-z]/gi))?(t=8,m.map(c=>t+=c>'@'?c.charCodeAt()&31:+c),t%9+1):/0/.test(s)?0:'*' ``` Ungolfed: ``` function(s) { var m = s.match(/[1-9a-z]/gi); if (m) { var t = 0; for (var i = 0; i < m.length; i++) { if (m[i] > '@') t += m[i].charCodeAt(0) & 31; else t += parseInt(m[i]); } return t % 9 || 9; } return /0/.test(s) ? 0 : "*"; } ``` 94-byte version that only works on short strings: ``` s=>(m=s.match(/[1-9a-z]/gi))?m.map(c=>c>'@'?c.charCodeAt()&31:c).join``%9||9:/0/.test(s)?0:'*' ``` Using `match`, `map` and `join` turned out to be shorter than using `replace` twice: ``` s=>(m=s.replace(/[^1-9a-z]/gi,''))?m.replace(/[a-z]/gi,c=>c.charCodeAt()&31)%9||9:/0/.test(s)?0:'*' ``` Test it here: <https://jsbin.com/zizosayisi/edit?js,console> [Answer] # Gema, 161 characters ``` *=@n{*} n:\A=@set{t;};<L1>=@set{t;@add{$t;@add{@mod{@sub{@mod{@char-int{$0};32};1};9};1}}};<D1>=@set{t;@add{$t;$0}};?=;\Z=@cmps{$t;;;\*;@cmpn{$t;9;$t;$t;@n{$t}}} ``` (Written only to try whether recursive domain calls work.) Sample run: ``` bash-4.3$ for input in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' '3.141592' '3.1415926535897932384'; do > echo -n "'$input' : " > gema '*=@n{*};n:\A=@set{t;};<L1>=@set{t;@add{$t;@add{@mod{@sub{@mod{@char-int{$0};32};1};9};1}}};<D1>=@set{t;@add{$t;$0}};?=;\Z=@cmps{$t;;;\*;@cmpn{$t;9;$t;$t;@n{$t}}}' <<< "$input" > echo > done '13579' : 7 'Hello, world!' : 7 '00 0 00' : 0 '!@#$%^&*();' : * ' ' : * '3.141592' : 7 '3.1415926535897932384' : 7 ``` [Answer] ## JavaScript (ES6), ~~162~~ ~~159~~ 157 bytes ``` f=_=>{for(_=_.replace(/\W+/g,''),g=$=>''+[...$.toUpperCase()].reduce((p,a)=>isNaN(a)?p+(a.charCodeAt()-64)%9:+a+p,0);1<(l=_.length);_=g(_));return!l?'*':g(_)} ``` Still trying to look for a way to use implicit return in the outer function. ### Ungolfed + unminified ``` f = str => { str = str.replace(/\W+/g, ''); recursiveFunc = $ => String([...$.toUpperCase()].reduce( (prev, val) => isNaN(val) ? prev + (val.charCodeAt() - 64) % 9 : Number(val) + prev, 0 )); while (1 < (len = str.length)) { str = recursiveFunc(str); } return len === 0 ? '*' : recursiveFunc(str) } ``` 1. Strips out all non-alphanumeric characters 2. Calls a function recursively to reduce the characters to their respective values while the string is longer than 1 character. 1. Converts the string to uppercase to easily work with ASCII codes 2. Convert to array using spread operator and run an accumulator 3. Use the global `isNaN` function (which casts its input) to check if it's not a number * If it isn't, convert to ASCII code and mod 9 to get its respective value * If it is a number, cast it 3. If the length is 0, no alphanumeric characters were present (return an asterisk), otherwise return the output of the recursive function. [Answer] ## Haskell, 126 bytes ``` l x=[n|(c,n)<-zip(['0'..'9']++['a'..'z']++'\0':['A'..'Z'])$0:cycle[1..9],c==x] g[]="*" g[x]=show x g x=f$show$sum x f=g.(l=<<) ``` Usage: `f "Hello, world!"` -> `"7"`. `l` is a lookup table for characters to list of integers (singleton list, if char is found, empty list otherwise). `f` lookups every char of it's argument and flattens the returned list of lists into a simple list of integers and calls `g` to check the end condition (empty list (-> `*`) or single integer) or to call `f` with the sum of the list for another round. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 64 bytes ``` jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] ``` This uses [current version (4.0.0)](https://github.com/lmendo/MATL/releases/tag/4.0.0) of the language. I have a feeling that it could be made shorter... ### Test cases ``` >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > 13579 7 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > Hello, world! 7 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > 00 0 00 0 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > !@#$%^&*(); * >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > 3.141592 7 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > 3.1415926535897932384 7 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > Bob 1 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > Charlie 2 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > Anna 3 >> matl > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*'] > > Izis 9 ``` [Answer] ## Seriously, 50 bytes ``` ,$ù;ú1╤▀+;#pX╗@-@-;Y`'*.`╬X1WX`╜í;s9*@%u`MΣ$;lDWX ``` Hex Dump: ``` 2c24973ba331d1df2b3b237058bb402d402d3b5960272a2e7f 60ce5831575860bda13b73392a402575604de4243b6c445758 ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=2c24973ba331d1df2b3b237058bb402d402d3b5960272a2e7f60ce5831575860bda13b73392a402575604de4243b6c445758&input=Hello,%20World!) Explained: ``` ,$ù Read input, make it a string, lowercase ú Push lowercase alphabet 1╤▀+ Prepend base 10 digits. ;#pX╗ Remove "0" from a copy and stash in reg0 ; @- Remove alphanumerics from input copy @- Remove nonalphanumerics from input ;Y Push 1 if string is empty, else 0 `'*.`╬ If top is truthy, output * and halt X Discard boolean 1 Push 1 to enter loop WX WX Loop while top of stack is truthy ` `M Map this function over the string ╜ Push alphanumeric string from reg0 í Push index of this char in it ;s9* Push 9 if found, else -9 @%u Take index mod previous: this yields the correct conversion from the numerology Σ Sum the resulting digits. $ Convert the sum to a string. ;lD push 1 less than its length ``` [Answer] ## Pyth, 39 bytes ``` IK@J+jkUTGrz0WtK=K`smh%xtJd9-K\0)K).?\* ``` [Try It Online](https://pyth.herokuapp.com/?code=IK%40J%2BjkUTGrz0WtK%3DK%60smh%25xtJd9-K%5C0%29K%29.%3F%5C%2a&test_suite=1&test_suite_input=Hello%2C+World%21%0A00+0+00%0A%21%40%23%24%25%5E%26%2a%28%29%3B%0A3.141592%0A3.1415926535897932384%0ABob%0ACharlie%0AAnna%0AFana%0AGregory%0ADenis%0AErik%0AHelen%0AIzis&debug=0) I'm just doing this because I can't sleep. Maybe I'll explain it tomorrow... [Answer] # Pure bash, ~~199~~ 194 bytes ``` eval a+={a..z};r="$1";while [ "${r:1}" ];do o=;for ((i=0;i<${#r};i++));do l=${r:i:1};case $l in [a-zA-Z])d=${a%${l,}*};((o+=$((${#d}%9+1))));;[0-9]) ((o+=l));;esac;done;r="$o";done;echo "${o:-*}" ``` (second line break is only for avoiding scrollbar) Test rule: ``` numerology() { eval a+={a..z}; r="$1"; while [ "${r:1}" ]; do o=; for ((i=0; i<${#r}; i++)) do l=${r:i:1}; case $l in [a-zA-Z]) d=${a%${l,}*}; ((o+=$((${#d}%9+1)))) ;; [0-9]) ((o+=l)) ;; esac; done; r="$o"; done; echo "${o:-*}" } for test in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' \ '3.141592' '3.1415926535897932384'\ Bob Charlie Anna Fana Gregory Denis Erik Helen Izis ;do echo "$(numerology "$test")" $test done ``` ``` 7 13579 7 Hello, world! 0 00 0 00 * !@#$%^&*(); * 7 3.141592 7 3.1415926535897932384 1 Bob 2 Charlie 3 Anna 4 Fana 5 Gregory 6 Denis 7 Erik 8 Helen 9 Izis ``` [Answer] # JavaScript (ES6), 78 ~~83~~ Recursive solution. Being tail recursion, the variables t and r have not to be local. ``` f=x=>(t=r=0,x.replace(/\w/g,d=>t+=1+~-parseInt(d,r=36)%9),t>9?f(''+t):r?t:'*') ``` **Explained** ``` f=x=>( t = 0, // set initial value of counter to 0 r = 0, // flag to verify that we found at last one alphanumeric chars x.replace(/\w/g, d => ( // execute the following for each alphanumeric character // t += 1 + ~-parseInt(d,r=36) % 9 explained below r = 36, // set flag, could be any nonzero value d = parseInt(d,36), // convert to numeric. a..z -> 10..25, case insensitive. d = 1 + (d-1) % 9, // this is the arithmetic conversion required ( // works also with 0 because the strange implementation of % in javascript for negative numbers t = t + d // add to global counter ) ), t > 9 // if t > 9 then we found some alphanumeric char, but we must repeat the loop on t ? f(''+t) // recursive call, t is numeric and must become a string : r // check flag r ? t // if alphanumeric found, return t : '*' // else return '*' ) ``` **Test snippet** ``` f=x=>(t=r=0,x.replace(/\w/g,d=>t+=1+~-parseInt(d,r=36)%9),t>9?f(''+t):r?t:'*') console.log=x=>O.textContent+=x+'\n'; ;[['13579',7],['Hello, world!',7],['00 0 00',0],['!@#$%^&*();','*'], ['3.141592',7],['3.1415926535897932384',7], ['Bob', 1],['Charlie', 2],['Anna', 3],['Fana', 4],['Gregory', 5], ['Denis', 6],['Erik', 7],['Helen', 8],['Izis', 9]] .forEach(t=>{ i=t[0]+'' k=t[1] r=f(i) console.log(i+' -> ' + r + (k==r? ' OK':' Fail - expected '+k)) }) ``` ``` <pre id=O></pre> ``` [Answer] ## Mathematica, 133 bytes ``` f[s_]:= ToCharacterCode@ToUpperCase@s-64/.{a_/;17>-a>6:>a+16,b_/;b<1||b>26:>""}//If[Or@@NumberQ/@#,Tr@#/.""->0//.a_:>Tr@IntegerDigits@a,"*"]& ``` A bit different from LegionMammal978's above. My function turns everything into a character code, then filters out the non-alphanumeric things (replacing them with empty strings). If there are no alphanumerics, then it returns \*, otherwise it takes the digital root. This could be significantly (~15B) shorter if I didn't have to deal with the all-zeros-string case. C'est la vie. Mathematica magic, for the uninitiated: `foo//.a_:>Tr@IntegerDigits@a` is a repeated replacement: it replaces any numbers `a` in foo with the sum of their digits, then it replaces again until it hits a fixed point, i.e. `a` stops changing under replacement. **Tests:** ``` f /@ {"13579", "Hello,world!", "00 0 00", "!@#$%^&*()", "3.141592","3.1415926535897932384"} => {7, 7, 0, "*", 7, 7} f /@ {"Bob", "Charlie", "Anna", "Fana", "Gregory", "Denis", "Erik", "Helen", "Izis"} => {1, 2, 3, 4, 5, 6, 7, 8, 9} ``` ]
[Question] [ *This is my first code golf so please let me know if it's too broad or if I'm missing any information for a good puzzle!* # Challenge In Ontario and possibly other areas of the world, electricity is billed using [Time-Of-Use (TOU) pricing](https://hydroottawa.com/residential/time-of-use/rate-periods/), which varies the cost per kilowatt-hour according to when you use power. Given a date and time, I want to know whether I'm in an on-peak (red), mid-peak (yellow), or off-peak (green) time period. # Input Assume that input is provided in an acceptable timezone-less [ISO 8601 date-time format](https://en.wikipedia.org/wiki/ISO_8601) with the minimum precision of hours: `YYYY-MM-DDThh[:mm[:ss]]` (the T is literal). ### Examples * 2014-09-01T14 * 2014-09-01T17:30 * 2014-09-01T17:30:02 # Output The output should be a string `On`, `Mid`, or `Off`. # Rules * Shortest code wins * For the purposes of this challenge, ignore statutory holidays * Assume the information found in this post. The actual rules of time-of-use pricing might change in the future by the Ontario Ministry of Energy. # Information ## Summer weekdays (May 1st to October 31st) ![Time-of-use clock for summer weekdays](https://static.hydroottawa.com/images/residential/time-of-use/tou-circle-summer_en.png) * Off-peak: 19h00 - 07h00 * Mid-peak: 07h00 - 11h00 and 17h00 - 19h00 * On-peak: 11h00 - 17h00 ## Winter weekdays (November 1st to April 30th) ![Time-of-use clock for winter weekdays](https://static.hydroottawa.com/images/residential/time-of-use/tou-circle-winter_en.png) * Off-peak: 19h00 - 07h00 * Mid-peak: 11h00 - 17h00 * On-peak: 07h00 - 11h00 and 17h00 - 19h00 ## Weekends ![Time-of-use clock on weekends](https://static.hydroottawa.com/images/residential/time-of-use/tou-circle-weekend_en.png) * Off-peak: All day [Answer] # Python 2 - 164 ``` from datetime import* d,t=input().split('T') y,m,d=map(int,d.split('-')) t=int(t[:2]) print'OMOfinfd'[(1+((10<t<17)==(4<m<11)))*(date(y,m,d).weekday()<5<6<t<19)::3] ``` --- If needed, below is a explanation of the logic in the final line: The final line prints a slice of `'OMOfinfd'` depending on the evaluation of its conditionals. * First, evaluate the operation `1+((10<t<17)==(4<m<11))`. If the XNOR between the conditions `10<t<17` and `4<m<11` is `False`, this will evaluate to `1+False => 1+0 => 1`. Otherwise, the operation will evaluate to `1+True => 1+1 => 2`. * Finally, multiply that result of the above operation by whether the day is a weekday and whether the time is between 6am-7pm. If this is `False`, either the day is a weekend or the time is between 7pm-6am, and the result will be `(1|2)*0 => 0`. Otherwise the result will be `(1|2)*1 => 1|2`. A result of `0` will print `Off`, `1` will print `Mid`, and `2` will print `On`. [Answer] ## C# - ~~240~~ 220 chars ``` string x(string s){var d=DateTime.Parse((s+":00:00").Substring(0,19));int h=d.Hour,i=(int)d.DayOfWeek,x=d.Month;string o="off",m="mid",f="on";return i==6|i==0?o:x>=5&x<11?h>18|h<7?o:h>10&h<17?f:m:h>18|h<7?o:h>10&h<17?m:f;} ``` Nothing special. Straight forward coding. Thanks to w0lf :) [Answer] ## Ruby - 135 Abuses the Time module. Input by command line argument. ``` d=Time.new(*$*[0].scan(/\d+/)[0..3]) o,m,f=%w{On Mid Off} o,m=m,o if (d.mon-5)%10<6 p d.wday%6<1||(12>h=(d.hour+5)%24)?f:15<h&&h<22?m:o ``` **Edit:** Thanks w0lf for Time which helped shorten and solve a bug. [Answer] ## Ruby - ~~147 144 143 141 137~~ 135 ``` x=->s{y,m,d,h=s.scan(/\d+/).map &:to_i g=Time.new(y,m,d).wday%6<1?0:[0..11,4..9].count{|r|r===h-7} %W{Off Mid On}[m<5||m>10?(3-g)%3:g]} ``` This represents a function which takes a string as a parameter and returns a string. Here's an online demo with some test cases: **<http://ideone.com/wyIydw>** [Answer] ## Groovy - 621 534 524 491 chars Some further golfing to do, but pretty simple when leveraging Joda-Time ``` @Grab(group='joda-time',module='joda-time',version='2.3') f={p,a->org.joda.time.format.DateTimeFormat.forPattern(p).parseDateTime a} g={p,a->def x=null;try{x=f p,a}catch(Exception e){}} a=args[0] d=["",":mm",":mm:ss"].collect{g "yyyy-MM-dd'T'HH$it",a}.find{it} r="Off" m="Mid" j={d,a,b->d.hourOfDay>a&&d.hourOfDay<b} k={j(it,6,11)||(j(it,16,19))} if(d.dayOfWeek<6){x=d.monthOfYear;if(x>4&&x<12){if(j(d,10,17))r="On";if(k(d))r=m}else if(x<5||x>10){if(j(d,10,17))r=m;if(k(d))r="On"}} println r ``` sample runs: ``` bash-3.2$ ./run.peak.sh groovy Peak.groovy 2014-08-26T19 Off groovy Peak.groovy 2014-08-26T07:00 Mid groovy Peak.groovy 2014-08-26T18:00:00 Mid groovy Peak.groovy 2014-08-26T12:30:30 On groovy Peak.groovy 2014-11-01T00 Off groovy Peak.groovy 2014-02-05T11:11:11 Mid groovy Peak.groovy 2014-01-05T08:08 Off groovy Peak.groovy 2014-12-18T18:59:59 On groovy Peak.groovy 2014-08-31T14 Off ``` Ungolfed: ``` @Grab(group='joda-time',module='joda-time',version='2.3') f = { p,a -> org.joda.time.format.DateTimeFormat.forPattern(p).parseDateTime a} g = { p,a -> def x=null; try{x=f p,a} catch(Exception e) {} } a=args[0] d = ["",":mm",":mm:ss"].collect{g "yyyy-MM-dd'T'HH$it",a}.find{it} r = "Off" m = "Mid" j = {d,a,b -> d.hourOfDay > a && d.hourOfDay < b} k = { j(it,6,11) || (j(it,16,19)) } if (d.dayOfWeek<6) { x = d.monthOfYear; if ( x>4 && x<12 ) { if (j(d,10,17)) r="On"; if (k(d)) r=m } else if (x<5||x>10) { if (j(d,10,17)) r=m; if (k(d)) r="On" } } println r ``` [Answer] ## R, ~~243~~ 204 characters ``` b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,2,3),f(w,3,2)))]) ``` Indented and commented: ``` b=strptime(scan(,""),"%Y-%m-%dT%H") #Takes stdin and converts into POSIXct i=function(x)as.integer(format(b,x)) #Format the POSIXct and convert it to integer h=i("%H") #Format to hours d=i("%m%d") #Format to Month/Day w=d>1100|d<430 #True if winter time, false if summer f=ifelse cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19, #If weekend or night 1, #Case 1 f(h>11&h<17, #Else if mid-day f(w,3,2), #Case 2 in winter, case 3 in summer f(w,2,3)))]) #else vice versa ``` Examples: ``` > b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))]) 1: 2014-08-26T15 2: Read 1 item On > b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))]) 1: 2014-12-10T15 2: Read 1 item Mid > b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))]) 1: 2014-08-26T23 2: Read 1 item Off ``` [Answer] ## Bash, 286 this is a simple bash answer using the date program ``` d(){ date -d $1 +%$2; };D=$(echo $1|sed 's/\(T..\)$/\1:00/');H=$(d $D H);M=$(d $D m);if [ $(d $D u) -gt 5 ]||[ $H -lt 7 ]||[ $H -gt 18 ];then echo Off;exit;fi;if [ $M -gt 4 ]&&[ $M -lt 11 ];then I=On;O=Mid;else I=Mid;O=On;fi;if [ $H -gt 10 ]&&[ $H -lt 17 ];then echo $I;else echo $O;fi ``` [Answer] Here goes another one! # JavaScript, ~~175~~ 171 ``` function f(x){d=new Date(x.slice(0,10));t=x.slice(11,13),m=(x.slice(5,7)+1)%12;return(t<8||t>18||!(d.getUTCDay()%6)?'off':((t<11||t>17)?(m<5?'on':'mid'):(m<5?'mid':'on'))} ``` Unminified: ``` function f(x) { d = new Date(x.slice(0, 10)); t = x.slice(11, 13), m = (x.slice(5, 7) + 1) % 12; return (t < 8 || t > 18 || !(d.getUTCDay() % 6) ? 'off' : ((t < 11 || t > 17) ? (m < 5 ? 'on' : 'mid') : (m < 5 ? 'mid' : 'on')) } ``` Only works on interpreters where an ISO8601 date string can be passed into the [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) constructor. # CoffeeScript, ~~192~~ 189 Surprisingly, it's longer in CoffeeScript because there's no ternary operator in that language (which as you can see from my JavaScript, I heavily relied on). ``` f=(x)->d=new Date(x.slice(0,10));t=x.slice(11,13);m=(x.slice(5,7)+1)%12;return'off'if(t<8||t>18||!(d.getUTCDay()%6));if(t<11||t>17)then(if m<5then'on'else'mid')else(if m<5then'mid'else'on') ``` [Answer] # ES6 - 146 This is in function form, uses a couple nasty hacks. ``` let y,m,d,h,c=s=>[y,m,d,h]=s.split(/[T:-]/g).map(i=>+i),new Date(y,m,d).getDay()in{0:1,6:1}||h<20||8>h?'Off':['Mid','On'][(10>h&&h>16)^(m>5||m<8)] ``` Explained: ``` // These variables are declared outside of the function scope to save // characters. let y, // year m, // month d, // day h, // hour c = s => // c for check, called as c(isoString) [y, m, d, h] = // Assign to fields s.split(/[T:-]/g) // Split at delimiters .map(i => +i), // Convert all to numbers // Comma used to keep it as a single statement. new Date(y, m, d).getDay() // Create Date to get day of week in {0:1, 6:1} // Check if it is good (0 = Sunday, 6 = Saturday). It // is shorter to use an object literal than to // do individual checks. || h < 20 || 8 > h ? // h is between 7 and 19 (7pm) 'Off' : // Return 'Off' ['Mid','On'][ // Two other outputs (10 > h && h > 16) ^ // Check if it is 11-16 (5pm) (m > 5 || m < 8)] // Invert that if the month is in summer/fall. Note // that this returns a number, either 1 or 0. This // is an ugly hack using the bitwise xor operator. ``` [Answer] # Python 3 - 352 chars ``` import datetime as dt t=input() i=int p=print a='on' b='mid' c='off' m=i(t[5:7]) h=i(t[11:13]) d=dt.date(i(t[0:4]),m,i(t[8:10])).weekday() if 5==d or 6==d:p(c) elif h>=19 and h<7:p(c) elif m<=10 and m>=4: if h>=7 and h<11:p(b) if h>=11 and h<17:p(a) if h>=17 and h<19:p(b) else: if h>=7 and h<11:p(a) if h>=11 and h<17:p(b) if h>=17 and h<19:p(a) ``` [Answer] ## Java - ~~426~~ 309 / 301? (see comments) ``` String z(String a){ DateParser b=new DateParser(a); boolean c=b.parseEcmaDate(); Integer[]d=b.getDateFields(); GregorianCalendar e=new GregorianCalendar(d[0],d[1]-(c?0:1),d[2]); e.setTimeZone(new SimpleTimeZone(0,"")); return(124>>e.get(7)&1)>0&d[3]>6&d[3]<19? d[3]>10&d[3]<17^(1008>>e.get(2)&1)>0?"Mid":"On":"Off"; } ``` Example output: ``` 2014-03-02T00 Off 2014-03-02T06 Off 2014-03-02T07 Off 2014-03-02T10 Off 2014-03-02T11 Off 2014-03-02T16 Off 2014-03-02T17 Off 2014-03-02T18 Off 2014-03-02T19 Off 2014-03-02T23 Off 2014-04-02T00 Off 2014-04-02T06 Off 2014-04-02T07 On 2014-04-02T10 On 2014-04-02T11 Mid 2014-04-02T16 Mid 2014-04-02T17 On 2014-04-02T18 On 2014-04-02T19 Off 2014-04-02T23 Off 2014-05-02T00 Off 2014-05-02T06 Off 2014-05-02T07 Mid 2014-05-02T10 Mid 2014-05-02T11 On 2014-05-02T16 On 2014-05-02T17 Mid 2014-05-02T18 Mid 2014-05-02T19 Off 2014-05-02T23 Off ``` I used the same EXOR trick as the Python submission. ~~I also used a `+` as an OR function, for when it's `weekend OR night`.~~ My other big trick: bit masks. For example, to see if a number is between 2 and 6 (Monday to Friday), first create a bit pattern where the interesting values are 1: ``` 6 2 0b1111100 = 124 ``` Then, use bit shift to get the interesting bit to the LSB and extract it: ``` (124 >> day_of_week) & 1 ``` Similarly, I made bit patterns for months and hours: ``` 9 4 0b1111110000 = 1008 76 76 0b111110000000000001111111 = 16253055 0b000000011111100000000000 = 129024 ``` Unfortunately, it turns out simply `x>y&x<z` is shorter in most cases, so I didn't use it in some places. And finally, a bit of hackery (highly implementation dependent) with `jdk.nashorn.internal.parser.DateParser`: When `parseEcmaDate()` doesn't completely parse a date (like when it reads hour and hits end of string), it returns false. * When it finishes properly, the date is stored in an `Integer[]` (auto-unboxing ftw), with the month fixed to be base-0 (like other Java classes). * When it returns false, it aborted half-way and didn't do this fixing. It however still put whatever it parsed into the array, which is readily available. Hence the `-(c?0:1)`. [Answer] Nothing stops me from entering my own, and there's other shorter ones here anyways, so… # PHP 5.4+, 194 ``` <?function f($x){$t=substr($x,11,2);$m=(substr($x,5,2)+1)%12;if($t<8||$t>18||(new DateTime(substr($x,0,10)))->format('N')>5)return'off';return($t<11||$t>17)?($m<5?'on':'mid'):($m<5?'mid':'on');} ``` Unminified and commented: ``` <? function f($x) { $t = substr($x,11,2); // hour $m = (substr($x,5,2) + 1) % 12; // month shifted up by 1 if ($t < 8 || $t > 18 || (new DateTime(substr($x,0,10)))->format('N') > 5) return 'off'; // evenings and weekends return ($t < 11 || $t > 17) ? ($m < 5 ? 'on' : 'mid') // morning and mid-afternoon : ($m < 5 ? 'mid' : 'on'); // afternoon } ``` Also note that the `date.timezone` directive in php.ini must be set, otherwise an Exception will be thrown. ]
[Question] [ We are going to bring down an imaginary building with a series of explosions. Our building is a 5x5 matrix of integers ranging 1-9, each representing a single brick. The challenge is to set of a series of explosions to bring down our building as much as we can, why not! Each brick that is connected (horizontally, vertically, diagonally) to a copy of itself will represent a payload that is going to explode in the next detonation. The bricks above those that are blown to bits will fall down. We will continue these steps untill we cannot demolish the building any further: Look at the 'building' to find connected copies of integers for an explosion, set of the explosion to let bricks above the explosion fall down to create a new *array of digits*. If an explosion occured make sure to backfill your 'building' with a zero to represent rising smoke from the ashes. Though, extra imaginary digital kudos if you used actual [clouds](https://www.compart.com/en/unicode/U+2601), e.g: [![enter image description here](https://i.stack.imgur.com/lKfBh.png)](https://i.stack.imgur.com/lKfBh.png) > [![enter image description here](https://i.stack.imgur.com/W4cYM.png)](https://i.stack.imgur.com/W4cYM.png) > [![enter image description here](https://i.stack.imgur.com/1ux7j.png)](https://i.stack.imgur.com/1ux7j.png) > [![enter image description here](https://i.stack.imgur.com/CVcJt.png)](https://i.stack.imgur.com/CVcJt.png) Your final output, the result of this challenge, should represent the ruins after the last possible detonation with the aforementioned smoke rising from the ashes. In the case of no possible explosions, sadly output == input. In the occurence of a single big explosion (or multiple explosions for that matter) to bring the whole building down, the result is simply an array of clouds. **Samples:** [![enter image description here](https://i.stack.imgur.com/Tj353.png)](https://i.stack.imgur.com/Tj353.png) > [![enter image description here](https://i.stack.imgur.com/gxPcu.png)](https://i.stack.imgur.com/gxPcu.png) [![enter image description here](https://i.stack.imgur.com/BPwyu.png)](https://i.stack.imgur.com/BPwyu.png) > [![enter image description here](https://i.stack.imgur.com/xm0Ds.png)](https://i.stack.imgur.com/xm0Ds.png) [![enter image description here](https://i.stack.imgur.com/01b0e.png)](https://i.stack.imgur.com/01b0e.png) > [![enter image description here](https://i.stack.imgur.com/GAOQR.png)](https://i.stack.imgur.com/GAOQR.png) [![enter image description here](https://i.stack.imgur.com/ypRE4.png)](https://i.stack.imgur.com/ypRE4.png) > [![enter image description here](https://i.stack.imgur.com/wgpWT.png)](https://i.stack.imgur.com/wgpWT.png) [![enter image description here](https://i.stack.imgur.com/VTLvO.png)](https://i.stack.imgur.com/VTLvO.png) > [![enter image description here](https://i.stack.imgur.com/VTLvO.png)](https://i.stack.imgur.com/VTLvO.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 31 bytes ``` 12:"9:"t@=t3Y6Z+*~*]tg&S5:q5*+) ``` Input and output are 2D numerical arrays, with `0` for smoke in the output. [Try it online!](https://tio.run/##y00syfn/39DISsnSSqnEwbbEONIsSlurTiu2JF0t2NSq0FRLW/P//2hzBVMFYwVzBWNrIGGiYKlgpmAIYloqWACZRtZAwkTBUMFIwcQaqNIICC0UTGMB "MATL – Try It Online") Or [verify all test cases](https://tio.run/##jVC7DsIwDNz5CqsDFa065NVXhMTAH8AArSLBxAIDUgYmfr34nFYwIivR@XI@23lc4326TEr3WddncbeN5lwPZfEuQrytD65/uqLcTCGvqvy0H17HaWzIkaGGjOfLUkc1KcCOWoba82VJkSbrWak5WnJhNSqaw9P/8KeOnY2EhsIKMIDC4MULAEQdBkPewQ4JnyRG4r4szykMlpF@aXyVxnfJ2SRf1C2tpR@eWSZ1IC0UNX9Hy6bKLxxaz1xaRDhqwgc). ### How it works You can see a convolution coming, can't you? ``` 12:" % For each n in [1 2 ... 12]. 12 is a bound on the number of explosions 9:" % For each k in [1 2 ... 9] t % Duplicate the numerical 2D array (A). Triggers implicit input the % first time @= % Compare element-wise with k. Gives a zero-one 2D array (B) t % Duplicate 3Y6 % Push [1 1 1; 1 0 1; 1 1 1]. This defines the neighbourhood Z+ % 2D convolution, maintaining size. This counts, for each entry in % (B), how many ones there are in its neighbourhood * % Multiply, element-wise. This counts, only for each entry in (B) % equal to one, how many ones it has around ~ % Negate. This gives zero for entries that are going to disappear, % one otherwise * % Multiply by (A), element-wise. This sets the required entries to % zero ] % End tg % Duplicate. Convert to logical: non-zero values become one &S % Sort each column, and output the indices that correspond to the % sorting. Gives a 2D array containing a permutation of [1 2 ... 5] % in each column (C). This sorting corresponds to sending the zeros % to the top of each column 5: % Push [1 2 ... 5] q5* % Subtract 1, multiply element-wise by 5. Gives [0 5 10 15 20] + % Add to (C) with implicit expansion. This gives the linear indices % that will send zeros to the top of each column ) % Reference indexing % End (implicit) % Display (implicit) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~52~~ 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ9EDNQ©˜ƶ5äΔ2Fø0δ.ø}2Fø€ü3}®*€€à}Иs¢2@*_*}ø0δ†ø ``` Uses `0` for smoke. [Try it online](https://tio.run/##yy9OTMpM/f//3BRLVxe/wEMrT885ts308JJzU4zcDu8wOLdF7/COWhDzUdOaw3uMaw@t0wKyQJwFtYcnnJ5TfGiRkYNWvFYtWPGjhgWHd/z/Hx1trmOqY6xjrmMcqwNkm@hY6pjpGILZljoWQLYRkG0GFDfUMdIxAbJNgbQRUMY0Nva/rm5evm5OYlUlAA) or [verify all test cases](https://tio.run/##lZCxSsNQFIb3PkXIGE6kuTdpmkKpgjqKziFI1A6FkpY2FSIE1Cdw6ODQoYiLIE5SAnVKwKWQh8iLxHNOElE3uYR89z//yX9OJnP/YjQsr9XT2TAMI306GwXh8EoZBdNF2FNUiNIttNSDy3DhjxtVUQdRv8yXztHhyVn6slt9bqzsOV@K4yxp5@97WRITFvev2YeM0zcNiS7rOHvYrebpk9jXzrWYzcXtOkvKuEmYLMIqeNBv/Z3puwbptq0Wj3dqD9LNoHRd1wYLJNggPUA2wYEOGMwOdJEFcgd1AwSYyBa@BVYszwPFdQ2oD5b@x7/aKUUCHcE2k0kys0Y1ZMFu2bTTsCQ5/GW64VO30M36odPwrNGSTXq1l1HvZdUpssrg9maSKp0c6GzaqWCyrYO/sIspBttY5UlqtV6QVbA9zyt1PZjoY/8m@gI). **Explanation:** ``` Δ # Loop until the result no longer changes: 9E # Loop `N` in the range [1,9]: D # Duplicate the current matrix # (which will be the implicit input-matrix in the first iteration) NQ # Check which values are equal to `N` in the copy © # Store this matrix of 1s/0s in variable `®` (without popping) ˜ # Flatten it to a list ƶ # Multiply each value by its 1-based index 5ä # Convert the list back to a 5x5 matrix Δ # Loop until it no longer changes to flood-fill the positive values: 2Fø0δ.ø} # Add a border of 0s around the matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Map over each row: 0 .ø # Add a leading/trailing 0 2Fø€ü3} # Convert it into overlapping 3x3 blocks: 2F } # Loop 2 times again: ø # Zip/transpose; swapping rows/columns € # Map over each inner list: ü3 # Convert it to a list of overlapping triplets ®* # Multiply each 3x3 block by the value in matrix `®` # (so the 0s remain 0s) €€à # Keep the largest value from each 3x3 block: €€ # Nested map over each 3x3 block: à # Pop and push its flattened maximum } # Close the flood-fill loop Иs¢2@*_* # Remove all islands of 2 or more cells from the matrix: Ð # Triplicate the resulting matrix of 0s and positive islands ˜ # Flatten the top copy s # Swap so the other copy of the matrix is at the top ¢ # For each value in the matrix, count its occurrences in the list 2@ # Check for each count whether it's >= 2 * # Multiply these checks to the matrix of 0s and positive islands _ # Check for each value whether it's equal to 0 # (the falsey results are the islands we'll remove) * # Multiply it to the values of the matrix to 'explode' the islands } # Close the [1,9]-loop ø0δ†ø # Collapse the bricks of the building down after the explosions: ø # Zip the matrix; swapping rows/columns δ # Map over each inner list (each column): 0 † # Filter all 0s to the front ø # Zip/transpose it back # (after which the result is output implicitly) ``` [Answer] # JavaScript (ES7), 167 bytes Expects a matrix of integers. Returns another matrix of integers, with `0` for smoke. ``` f=(m,V=[],X,Y)=>~m.map((r,y)=>r.map((v,x)=>X+1?6>>(X-x)**2+(Y-y)**2&V==v?V='':0:V[x]=f(m,v,x,y)+[V[x]]))/X?V:m+''==(V.map((s,j)=>m.map((r,i)=>r[j]=~~s[4-i])),m)?m:f(m) ``` [Try it online!](https://tio.run/##dU47b9swEN75K4gMFRnJbEiKlOWA9tSMWQIIDmQNqkOnMvRwScWwEcR/3TkqRTv1BvK7u@9x@/pY@61rDuOsH17s9bozpEsKU1bJOnmmZnnpWFcfCHHJGTr31RyTEzTrmK/0cknWsxO9vRUxeZ6dA/hWGHNcFSaKFneLojxVZgeeoAGLuAyDitLv61Wx6OIoMoYUX64@2YPr37wm5JX7ylwuvkxnDYiSjq66BbjRq7O/3xpnSbTzEWXO1i8PTWufzv2W3FE2Dk@ja/pXQpk/tM1Ibjb9pr@hbDe4H/X2F/HYLPE7wri1I@6wwf4fEWjhhIlSMsZ8NfWPb91P6@AIUIVyFhg4HHMPk@3Q@6G1rB1eCWwmhQsOju2HpidRROkftOkjimM8/ffog14zJTOJsjTXHGX5XAukUy5SpISYK4R4qP@@0yeQlFJwlEohOQIkJRKcA0a5FjxHPNe5hkWu1YRTmKs0BzUkcUhSoJAgUJMHqJVUAtZCpgrpbJ5zFKBGAUIcwOwT "JavaScript (Node.js) – Try It Online") ## How? We use the same recursive function to process two distinct steps: 1. Fill an array of strings representing the updated columns of the matrix without removed cells. Then convert this array back to a matrix. 2. Test whether a given cell should be removed. ### Step 1 The variable \$V\$ is initially set to an empty array and the variables \$X\$ and \$Y\$ are undefined. For each cell at \$(x,y)\$ with value \$v\$, we insert the result of the second step at the beginning of \$V[x]\$ (coerced to an empty string if it's still undefined): ``` V[x] = f(m, v, x, y) + [V[x]] ``` Once all cells have been processed, we transpose the strings stored in \$V\$ to build the new matrix with each column filled with leading 0's wherever needed: ``` V.map((s, j) => m.map((r, i) => r[j] = ~~s[4 - i]) ) ``` If the matrix is unchanged, we stop and return it. Otherwise, we do a recursive call at step 1. ### Step 2 The variable \$V\$ is set to the value of the cell being tested and the variables \$X\$ and \$Y\$ hold its coordinates. We walk through each cell at \$(x,y)\$ and set \$V\$ to an empty string as soon as a neighbor cell with the same value \$v\$ is detected. A neighbor cell is a cell whose squared Euclidean distance with the reference cell is either \$1\$ or \$2\$. This is tested with a bitmask: ``` 6 >> (X - x) ** 2 + (Y - y) ** 2 & V == v ``` NB: Because the matrix is \$5\times5\$, the maximum squared Euclidean distance is \$32\$, in which case the shift amount will wrap to \$0\$. Fortunately, this will still work as expected. Once all cells have been processed, we simply return \$V\$. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes ``` E⁵SW¬⁼υθ«≔υθ≔E⁵⟦⟧υF⁵F⁵«Jκ⁻⁴λ¿¬№KMKK⊞§υκKK»⎚GT⁵☁↑Eυ⪫κω ``` [Try it online!](https://tio.run/##RY9NasMwEIXX1imGrEagLpLYBiWrELJIwMXQdFW6MKliC6uSY1tNS8mit@j5ehF35PRnpXlv0HvfHKqiPbjCDEPeattjVjSYCNjaxvd3PVklcs6X7FxpowBvXY@bky9Mh17AiVbwzqJV1@nSXp3ln/yJenjkAnzwj64FTDj8vvQz2vnnZu@wFpBp6zuMBZjQF0X6eK1bO09cuVJ15lyrkNKCCFgcct9VuOq39km9hv76f0sZFxatjSpaDCJ35q10Fhd7AYQ1@fr8mIz@ePfiviEEIqaQndM2EJ3Hyy/DINPZVLKpTGXK5jOZJuMcM5piOdy8mG8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` E⁵S ``` Copy the input to the canvas. ``` W¬⁼υθ« ``` Repeat until two iterations produce the same result. ``` ≔υθ ``` Save the result of the previous iteration. ``` ≔E⁵⟦⟧υ ``` Start collecting lonely bricks for this iteration. ``` F⁵F⁵«Jκ⁻⁴λ ``` Loop over the columns from left to right and the rows from bottom to top. ``` ¿¬№KMKK⊞§υκKK ``` If this brick is lonely then collect it. ``` »⎚ ``` Clear the canvas. ``` GT⁵☁ ``` Output a background of clouds, leaving the cursor at the bottom left. ``` ↑Eυ⪫κω ``` Output the lonely bricks from left to right and bottom to top. [Answer] # [Julia 1.8](http://julialang.org/), 144 bytes ``` !o=(k=keys(o)).|>_->(o.=[(2>count(o[i].==get.([o],i-k[7].+k[1:3,1:3],0)))o[i] for i=k];[o[j,i]<1&&(o[j-1:j,i]=o[[j,j-1],i]) for i=1:5,j=5:-1:2]) ``` [Try it online!](https://tio.run/##tVLRbtowFH0eX3HbSZ2jGYNJAjRd0OiemLaXvXrR5IBpDVmCElOBtH9ntmNImyKt6jYUIt9zj4@PT@5qm0lOd4e3MC9@briClQGAEgroXqlNFfV6d1Ldb1OiCb3PpvuF53c9y@tttlnW8/uD4djr3PJKkDuh0DSKpmmlSj5X07LkewyzKPrESyUqyfNZvhA7DAux5NtMeRCD3aNJZNbAnWeGxi83FIz6QeAM3ZYFX8x5pUh6XPE0E2jXtmScfBNLtPMOF0WM1vFa7CtUeB75NfnRnaCCxAwNJvNimytUMJmQONbOCWJFgmV3zUYJeb9mNPKx/ie473meocGyKEHG6@SGFWyFZfKBXl1pgVWXRqaMC6ZhXWmVxHNsGoV4FYeR5gwS72BBkDmUgi8ymYsKeR3QP45TbVs88Iygr0JxsuGlvjSqNplUSOLL7@pS@wB9By3QnQCT7wghN4ndvZCax/eI12KbUuYqy530BW9znvaPjbQuP/KqEqUCDnEM6Rm9phL54sDYCEOIwcegFzouMECA4RrDEAN1gK7GFhgYYGgZVFd6YYDQLgeWFCbJG8b6GJrHUB4DfhugDeDbd@CO6dtjRla1wxi1pXsM5a@BP3p9FdD2alPz7eV8m5N1Ehwr3wGuV/MMMDgK@P/Sa/AkeeO1/tj1adcupBoz78ZajYVthv1arlcPzwu90jbgn2eE1tlpBk7DR5vhC5vU/FNkzuvjoI@51nyz97W5PjMfnpuB@tTAORnaYR7b1Khz4tou6KbdjI1r673W639Q/Q0 "Julia 1.0 – Try It Online") mutates the input. uses zeros for ashes [Answer] # Python3, 507 bytes: ``` E=enumerate def S(b): q=[*b] while q: Q=[q.pop(0)];R=[Q[0]] while Q: x,y=Q.pop(0) F=1 for X,Y in[(1,0),(0,1),(0,-1),(-1,0),(-1,-1),(1,-1),(-1,1),(1,1)]: C=(x+X,y+Y) if C in b and b[C]==b[(x,y)] and C not in R:Q+=[C];F=0;R+=[C];q.remove(C) if F and len(R)>1:yield R def f(b): while 1: F=1 for i in S({(x,y):v for x,r in E(b)for y,v in E(r)if v}): F=0 for x,y in i:b[x][y]=0 if F:return b b=[*map(list,zip(*[[j for j in i if 0==j]+[*filter(None,i)]for i in zip(*b)]))] ``` [Try it online!](https://tio.run/##nZNNj5swEIbP9a@wcomdkAjbQAKRe4l2j5WSvezKRVVQiNYRAQJsGlr1t6djQ/ajaqUqHPDM8Lyvx2NRts1zkYt5WV0udzLNXw5ptWlStE13@IEkNEL4KNUoiRH@/qyzFB@hgldSHadlURKXxou1VCvlxkD0yMog@Oy0ctVDJr@XzCy7osKPzhPWuSLMcalDXIfZ98Qsk64Gi03Za7XLGI2tOV5Kch4/Ou34yZpjvcNL8MQJ3uRbnKhlLGWiCDRBY1ta4rxoDLGOVmMJ3xf30l2su/A4rdJDcUrJ0rqB2b0VZWlO1vQzi1qdZlu8tmPZdWPpzspMO93RzMm02eGB/LQbRydbOzuVqd6BzKStc@rSisI@p1806qbjXqcDUgPoKFHnWLWx/WJaiqq0eangjJAncCmHTUkyXTfOD12SkVJ7K99bsRG4Uu7jsRrtdNakFflS5Kmjafzap5UlNKY0vtQMSzwYDNDMFzOBZl4YMDQL5wFHgce4h3zO5z4yRM17lJnnn2@LincoR0IIzpAnuGAIIiEQZ0z0qNejYcBZiFgYhAFAYeDb2IO674UWRbV/tYXWGLTmg5UAJ9@ag60vfN6zwZXlwvNRMJuHDJkwQCaEpiCcday53ab4lhSbaktquJhP/cRVN2ydNx8G@H6wuJ7WZaYbMvyaD2GiCKE3jry5Mmp8ywq8iKZAdeFwMhxx@FH@LuJ/iP5HI27QeLc0598iCj6ILr8B) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 24 bytes ``` ŻṖ;"⁺Ḋ)Zð⁺ċ""Ị×ZṠÞ€Zµ$ƬṪ ``` [Try it online!](https://tio.run/##lZA9CsJAEIV7TyHBRphmd7P5wQN4h4QtbcQLWGojxF47sZYUNoIxYGHUe2wuss5MNqClLCHfvnmTN5P5bLFYOveqbbWbBO3qZq/FOGvOSM9tENi6aPaZrY7NoV2X2eMyepe2OrlmMx3P29V9MHAuz2PQoCAGZQA5hBQiEMwpJMgSOUJdgIQQWeNbYkUbA8M8F@APlv7jn3ZKUUBHsi1kUsysUQ1Zslv17TQsSSl/mW74@Ba66S@dhmeNluzTu72E30v7FNVlcHs/SZdODnT27VQI2RbhL0wwRbCNVZ7Eq35BViE25gM "Jelly – Try It Online") *-2 with `¬¬$` -> `Ṡ`, -1 with dyadic chaining via extreme chain separator abuse* The neighborhood logic feels a bit... unhinged, but I'm not mentally present enough to devise or steal anything better at the moment. ``` ) For each row: ŻṖ Prepend 0 and remove the last element, ;" concatenate with corresponding original elements, ⁺ and do the same Ḋ with the first element removed. Z Transpose, ð⁺ and do it again. ċ"" How many times is the middle in each neighborhood? Ị× Zero out elements with counts greater than 1. Z €Z For each column, Þ sort its elements by Ṡ their signs. µ$ƬṪ Repeat all of that while unique. ``` [Answer] # Python 3.8, ~~231~~ 227 bytes ``` def f(a,X=range(5)): while(b:=[[(i:=a[r][c])-i*any(all([r-2<R<r+2,c-2<C<c+2,(r,c)!=(R,C),a[R][C]==i])for R in X for C in X)for c in X]for r in X])!=a:a=[[([0]*5+[R[c]for R in b if R[c]])[-5:][r]for c in X]for r in X] return a ``` [Try it online!](https://tio.run/##lZDNboMwEITveQr3ZicbqdiYJCiceANOkSwfHAqNpYhEVqoqT093F/ojJZcKIT7Gw8wu1/vtdBnM9prG8a3rRS8DHKoUhvdOWqXKhfg8xXMnj2XlnIxlFVzyrvVqHZdhuMtwPkuX1nrf7NNKQ4tU71skmaBVL5VsoFYQXONd7asqetVfkmhEHMRBENaMrLaMnjBNiAGhDNTsXv3SrlyD1T8BRxF7QYpXbm1Lj5M9j1mI1N0@0iDCeE1xuMleOrcBCwY2YDwg57CDAjLmHWyRNXKBegYacmSLT40nFuvU4jcng/lCz//4eQ71GqBLsz9nMsys0RmyZrd5yKE96GzHXfSG9/wtvdk/Ou3FGu3/MM@0ezbvbudeM7Vyzvds0zzkQOdDDjly9hf4v7fYm7GfVZ5tVufdWYUN5Yxf "Python 3.8 (pre-release) – Try It Online") ## Ungolfed and commented ``` def f(a): for _ in range(25):a=h(g(a)) return a # Replace connected integers with 0s def g(a): b=[[*i]for i in a] for r in range(5): for c in range(5): i=a[r][c] if I(a,r,c,i):b[r][c]=0 else:b[r][c]=i return b # Check surrounding cells def I(a,r,c,i): for R in range(5): for C in range(5): if r-2<R<r+2and c-2<C<c+2and(r,c)!=(R,C)and a[R][C]==i:return 1 return 0 # Drop numbers down based on positions of 0 def h(a): b=[[0]*5for i in a] for c in range(5): C=([0]*5+[R[c]for R in a if R[c]])[-5:] for r in range(5):b[r][c]=C[r] return b ``` [Try it online!](https://tio.run/##lVHBjpswEL3zFVP1ArteKUBINiic6KVXrpZVOcaA1dSODNGqX5/OGDbZlr1UFmLmzfObN@PL72lwNr/dWt1BF8ukjKBzHn6AseCl7XWcFUkpqyHusZpE4PV09RZkFH2FRl/OUmlQzlqtJt3irUn32o/wZqYBNmNEuv2se6o4fzKC5A3JSzH38o9eBfECqP4FwVSSe8GVCEkH32PJPFPMJOVpLlQbKunzqO@IuRs@keF60OonjFfv3dW2xvag9Pk8u/ygN/tqPvNVr3114F@yY3P0z5m0LShM6qMKSYyCyZcqblidUE3yRvBaVJUpF1vp3eCGDH7z7gL2@utEO2zdG/qWI@7VWbi40UzG2RFch2SyPDwWuxFPxWqzqyXWVRyYz7zB7dyHlDQEISLhL0Uplln/fpj3ldb4f2z1dvH45nEXc75nBcvZnuWCYbxlB7ZjaYgP7BXjDOMd4inL2BbjAv8ZVgpsm0QPnZQtBzn/F3@uQ31zRicL/G2I8hAHjGoYZ4Gdr3RoDqodQi/K8FvuUlZ8wGmugNH8Kz/z7Okye7H0zeeuQefd2@yHGMhc6RBjG/g73Pcr9k0DP6DB24IusweU7Unn9gc "Python 3 – Try It Online") ]
[Question] [ Given some input array `a = [a1, a2, ..., an]` and a positive integer `k`, shuffle the input array `a` such that no entry is farther than `k` from its initial position. ### Example Given the array `[1, 2, 3, 4, 5, 6]` and `k = 1`, this means the entry `3` can be at following positions: ``` [*, 3, *, *, * ,*] [*, *, 3, *, *, *] (original position) [*, *, *, 3, *, *] ``` ### Details * Uniform randomness over all permissible permutations is *not* required, but * You can assume the input array is limited to the range `[1, n]` (or `[0, n-1]`, where `n` is the length). * all permissible permutations must have a nonzero probability of occurring. * Instead of shuffling an input array, you can also just take `k` and the length of the array `n` (or `n+-1` alternatively) as an input, and output a permutation in a suitable encoding (i.e as a list of indices etc). For this you can use 0 or 1 based indexing. * Instead of `k` you can also take `k-1` or `k+1` as an input if it is more suitable. * You can assume that `0 < k < [length of array]`. * Alternatively to sampling one random permutation you can also output *all* permissible permutations. [Answer] # [R](https://www.r-project.org), 47 bytes ``` \(n,k){while(any(abs((a=sample(n))-1:n)>k))0 a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6Fjf1YzTydLI1q8szMnNSNRLzKjUSk4o1NBJtixNzC4AieZqauoZWeZp22ZqaBlyJtVBtaokFBTmVGkWpBTmZyYklqRqGBkCgk6ZhpmOoqaljqFOSmJSTqglRvWABhAYA) Takes the length `n` and the maximum distance allowed `k` and returns a permutation on `1:n` by rejection sampling. Footer computes 10000 iterations of `f(6,1)` and tabulates the results for each index to give a rough distribution. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œʒāα@P ``` 1-based input-list, and outputs all possible permutations. Outputting a random one would be 2 bytes longer by adding a trailing `}Ω`. [Try it online.](https://tio.run/##yy9OTMpM/f//6ORTk440ntvoEPD/f7ShjpGOsY6JjqmOWSyXIQA) **Explanation:** ``` œ # Push a list of permutations of the first (implicit) input-list ʒ # Filter this list of permutations by: ā # Push a list in the range [1,length] (without popping) α # Get the absolute difference between the values at the same positions @ # Check for each whether the second (implicit) input is >= the value P # Product to check if all are truthy # (after which the filtered list is output implicitly) ``` [Answer] # JavaScript (ES6), ~~89~~ 87 bytes Expects `(array)(k)`. ``` a=>g=k=>a.every((v,i)=>!(1/b[j=i+Math.random()*(k-~k)-k|0])/a[j]&&[b[j]=v],b=[])?b:g(k) ``` [Try it online!](https://tio.run/##DcpLDoIwEADQq9QNmdEBxN/CZPAEnqDpYoCCUKQGSBMT49Wrb/0GCbLUc/9a08k3NrYchcuOHZeS2WDnN0CgHrncQJFXeuB@d5f1kc0yNf4JuAWXfh2m7rM3mIseTJLo/zMcDFWsDd6qawcOY@2nxY82G30HLeiC1IHUkdSJ1JnUxSAUiPEH "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array g = k => // k = max. distance a.every((v, i) => // for each value v at position i in a[]: !( // abort if: 1 / b[ // - b[j] is already defined j = i + // where j is randomly chosen in Math.random() * // [i-k .. i+k] (k - ~k) - k | 0 // ] // or: ) / a[j] && // - a[j] is not defined [ // otherwise: b[j] = v // set b[j] to v and keep going ], // b = [] // start with b[] = empty array ) ? // end of every; if sucessful: b // return b[] : // else: g(k) // try again ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Œ!ạJ{Ṁ<ʋƇ ``` A dyadic Link that accepts the length, `n`, on the left and the minimum illegal distance, `k+1`, on the right and yields a list of all permutations as 1-indexed indices. **[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZIh4bqhSnvhuYA8yovGh////zX/Mw "Jelly – Try It Online")** ### How? ``` Œ!ạJ{Ṁ<ʋƇ - Link: n; k+1 Œ! - all permutations of [1..n] Ƈ - filter keep those for which: ʋ - last four links as a dyad - f(P, k+1): { - use k+1 with: J - range of length -> I = [1..k+1] ạ - P absolute difference I (vectorises) -> distances Ṁ - maximum < - is less than k+1? ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~72~~ ~~64~~ ~~63~~ 62 bytes Lambda that accepts length of array minus one `n-1`, and minimum illegal distance for an element to be moved `k+1`. ``` ->n,k{a=*0..n;a.shuffle!.all?{(a.index(_1)-_1).abs<k}||redo;a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY37XTt8nSyqxNttQz09PKsE_WKM0rT0nJSFfUSc3LsqzUS9TLzUlIrNOINNXWBWC8xqdgmu7ampig1Jd86sRZiyo48W1OubFsjLq6C0pJihbToPF1DnWxtw1iI9IIFEBoA "Ruby – Attempt This Online!") *-8 bytes thanks to @Dingus* [Answer] # [Python 3](https://docs.python.org/3/), ~~104~~ ~~94~~ 92 bytes ## Code ``` lambda l,k:[p for p in permutations(l)if all(-k<p[i]-i<k for i in l)] from itertools import* ``` Takes as input: * The list `[0, 1, ..., n-2, n-1]` where `n` is the length of the list * `k+1` Outputs all possible permutations. [Try it online!](https://tio.run/##JY07DsIwEAV7n@KVNjgS4dOgcJKQwohYrLz@yNkUnN4E6J5mRnrlLa@cTs3jhntjFx9PB7bhOhb4XFFACWWucRUnlNOi2ZCHY9ZdGMpIU0dD@KX0TdlMytccQTJXyZkXUCy5yq7xdjEeLHqLo8XJ4mxxmVTYcK/qvKws2/SaLQL26I0qlZLovzLtAw) ## Explanation * Uses `itertools.permutations` to get all permutations of the list. * Only adds each one to the output list if `-k<p[i]-i<k` is `True` for every index `i` and value `p[i]` in the permutation. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~17~~ ~~13~~ 11 bytes ``` ʁṖ'→ƛ←ḟε;G≥ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiyoHhuZYn4oaSxpvihpDhuJ/OtTtH4omlIiwiO+KBiyIsIjVcbjMiXQ==) *-4 bytes thanks to emanresu A* *-1 byte thanks to Aaroneous Miller* [Answer] # Python3, 178 bytes: ``` lambda a,k:f([*enumerate(a)],k,a,0,[]) def f(a,k,l,j,c): if len(a)==j:yield c;return for x,y in a: if abs(x-j)<=k and(C:=list.count)(l,y)>C(c,y):yield from f(a,k,l,j+1,c+[y]) ``` [Try it online!](https://tio.run/##Rc29DoIwFIbhnas4Y6tHo3Ex1bqQeBPIcOhPBEpLSkno1SMmJk7f8uR7x5zewV@uY1yf8rU6GhpNQNgLy6qd8fNgIiXDiNfYI@EJq5oX2liwbFPosEPFRQGtBWf85qTsRG6N06Bu0aQ5@gJsiLBghtYDbfaLqZnYcuj4XfZAXrNSSNdO6ajC7BNnDjN/lExt83uzMQz/6P6Mal/lmq/rBw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` NθFN⊞υ⁰W⊙υ∨⊖№υλ‹θ↔⁻κλUMυ‽LυIυ ``` [Try it online!](https://tio.run/##TY0xDsIwDEX3niKjIxUJFpZOVVmQWqi4QdoaWpE4bRKDOH1ImPBi6b1v/3FWbrRKx3imlcOFzYAONlkVd@sE/EMpRc9@Bi7FPvn3vGgUUNMnk6uDE44ODVLACRrLFDLXUpaiRe9hK0U9eKs5IHQLsYfnT@cRnVoba4yiKR/d0rYGWqRHSH0pUBW9W9LHRvmQQRXjoTjG3Ut/AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a random permissible permutation. Explanation: ``` Nθ ``` Input `k`. ``` FN⊞υ⁰ ``` Input `n` and create an illegal permutation (unless `n=1`, in which case there is only one permutation). ``` W⊙υ∨⊖№υλ‹θ↔⁻κλ ``` Repeat until the permutation is both legal and permissible... ``` UMυ‽Lυ ``` ... randomise the permutation. ``` Iυ ``` Output the permissible permutation. [Answer] # [Python](https://www.python.org), 106 bytes ``` from random import* f=lambda L,k:(shuffle(Z:=L[::])or all([k>abs(s-n)for n,s in zip(L,Z)])and Z or f(L,k)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU87bsMwFNt9CgJdpPR5yBeFAPcEHjvZMQIFiWBVsixI8pBcpUuW5k65TZS0RSeCfATJ93X1p9SP7nL5npIq326fKowDgnSHDHrwY0izQlVWDvuDRE1GsNhPStkja0RVt0J0fAyQ1rLWvMt9ZLF0XGXJUYR2OGvPamp4x3MmGuSLyoLh_Ldxa1BhUWjnp7SzOqZM2zlhQVgSVoQ1YdMVPmiXmGL_PjKvc86LF3xIc4zIDDJCOjwteGwwPx1_390B) Returns a new list. Requires the input list to be in the format `[1,2,...,n-1,n]` where `n` is the length of the list. Taking `k+1` as an input [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 66 bytes ``` [ iota dup [ v- vabs [ >= ] with ∀ ] 2with filter-permutations ] ``` [Try it online!](https://tio.run/##JYwxDsIwEAT7vGI/kEhQUICgRTQ0iCpK4TgXcSKxjX0OoqPknXzEmKSb2V1tr7RYn66X0/m4xZ28oQGjkls10b8JsyxJNKxtR4toO7ZsVJ6wDnCeRF7OsxEEekQymgJ2RbHCJtVgKwpddKgxlZhUGzId9mjw5Pz@/bwzrmfueRDypSM/RlHC1gQ0SathQJV@ "Factor – Try It Online") Takes \$k\$ and a length \$l\$ and outputs all zero-indexed sets of indices of length \$l\$ that satisfy the distance constraint given by \$k\$. [Answer] # [Haskell](https://www.haskell.org) (Lambdabot), 72 bytes Operator `#` that accepts length of array minus one `n-1`, and minimum illegal distance for an element to be moved `k+1`. ``` n#k=[x|x<-permutations[0..n],all(\y->abs(fromJust(elemIndex y x)-y)<k)x] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNpczcgvyiEgWXxJJEPZ_M4hIuZAHfxMqk1KWlJWm6Fjc98pSzbaMraipsdAtSi3JLSxJLMvPziqMN9PTyYnUSc3I0Yip17RKTijXSivJzvUqLSzRSc1JzPfNSUisUKhUqNHUrNW2yNStioeYp5yZm5inYKqTkcykoFJSWBJcU-eQpqCgUZ-SXAykTBWUFY4jSBQsgNAA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` Ṗ'ż-ȧ⁰≤A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYnxbwtyKfigbDiiaRBIiwiIiwiWzEsMiwzLDQsNSw2XVxuMSJd) Port of 05AB1E. ## How? ``` Ṗ'ż-ȧ⁰≤A Ṗ # All permutations of the (implicit) first input ' # Filter by: ż # Length range [1, length] -ȧ # Absolute differences of values in the same positions ⁰≤ # For each, is it less than or equal to the second input? A # Are they all truth? ``` ``` ]
[Question] [ ## Background [Tetris](https://en.wikipedia.org/wiki/Tetris) is a single-player game played on a rectangular grid with tetromino pieces. When you fill one or more lines with tetrominoes, the filled lines are removed, and all blocks above them move down accordingly. In the following diagrams, `.` is an empty space, `#` is an existing block, and the tetromino marked with `A`s is the one just placed: ``` One line cleared example #...AA.. -> ........ ####AA## #...##.. --- Two lines cleared example (note that the 3rd line moved down once, while the top line moved twice) ...A.... ........ ###A#### ........ ##.A.##. -> ...#.... ###A#### ##.#.##. ####.### ####.### ``` ## Challenge Two board states will be given as input. One is right before a specific tetromino appears (the left-side state of the above diagrams, without `A`s), and the other is right after the tetromino is placed and line clears are completed (the right-side state). Given this information, recover the type of the tetromino placed between the two states, which is one of the following seven types: ``` O J L S T Z I ## # # ## # ## #### ## ### ### ## ### ## ``` You can assume the following: * The input is valid; the two boards have the same dimensions, and the game state can be changed from the first to the second by placing a single tetromino. Also, the placed tetromino is completely inside the grid before line clearing occurs (i.e. it won't be placed above the ceiling of the given grid, even partially). * The answer is unique. * The width of the board is at least 5. For this challenge, ignore the rotation rules of actual Tetris games, and assume that any tetromino placement is valid, as long as the tetromino does not overlap with existing blocks or float in the air. This allows placing a tetromino inside a closed room (which actually happens in some exotic games). You can take the input as a matrix (or equivalent) consisting of two distinct values for spaces and blocks. You can output the type of the tetromino as one of seven distinct values of your choice. Allowed output formats include numbers, strings, and possibly nested or multi-dimensional arrays of numbers and/or strings. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases The notation is the same as the above example. `Before` and `After` are the two input grids, `Answer` is the expected output (given as alphabet code), and `Explanation` shows where the tetromino is placed. ``` Before: ...... ...... After: ..##.. ..##.. Answer: O Explanation: ..AA.. ..AA.. ---------------- Before: ..#### ...### #.#### After: ...... ...... ..#### Answer: T Explanation: ..#### AAA### #A#### ---------------- Before: ...### ...### #..... After: ...... ..#### #..... Answer: L (J doesn't work since the piece will be floating) Explanation: ..A### AAA### #..... ---------------- Before: ##..## ##..## ##..## After: ...... ###.## ##.### Answer: S Explanation: ##A.## ##AA## ##.A## ---------------- Before: ##.## ##..# ##.## After: ..... ..... ..... Answer: T Explanation: self-explanatory ---------------- Before: .###. #...# ..... #...# .###. After: ..... .###. #...# ..#.. .###. Answer: T Explanation: .###. #...# ..A.. #AAA# .###. ``` [Answer] # JavaScript (ES10), ~~286~~ 282 bytes Expects `(a)(b)`, where \$a\$ and \$b\$ are 2 lists of binary strings. Returns an integer between \$0\$ and \$6\$ for `JLTIOZS`, or \$-1\$ if there's no solution (but we're not supposed to support that). ``` a=>b=>"0NF71ZMA13FM000F1F1F1IFL2R8I38LT357N368H".match(/../g).findIndex(p=>b.some((r,y)=>[...r].some((_,x)=>!b.some((s,i)=>[...a.map(B=r=>'0b'+r),~0].flatMap(t=(r,Y,a)=>~(q=((parseInt(p,36)||4369)>>(Y-y)*4&15)<<x,t|=q&a[Y+1],q|=q&r?~0:r)+2**s.length?q:(i--,[]))[i]^B(s)|!t))))%14>>1 ``` [Try it online!](https://tio.run/##bVBhb9owEP3eX5ESrbHBMUlDKevqVKs0NCbopNEvNGSTCYZmSp1gexNojL/O7MxMZe1Zytnv3nt3ue/0J5WZyCvl83LO9guypySekbgR3PUvw4fR@zDqj4Ig6IfmDPrD8y@9QdQb3kcXl3dRt/exgZ@oyh5BG@P2EuJFzucDPmdrUGkfLMsnBoBAG0jiBGMsUgt9Q2sNnR4YEuWWQbVfBW6JILEXzLyWgGgXpHhRUDXSBUW02wRRzd6BFQGgokKyAVegQlEXbredqPsWxjGY@BvY7JyFF/D6eo3UlqzOaDJphSlambu42QVXArbOm02JC8aX6vFmdQVy30dJCmGSp19vgYTbUwV1vAk7cRzuBVv9yAUD3kJ6EAtG5/28YOMNz0AAsSrHSuR8CSCWVZEr0J5yvzXlbb2VUnygeknSIbHz68RxEoqcWeoQR1quN@VTrk3Nz9esZwULCwML3bYqaMb0wttL5GQGbAGdiOO5nhn2nfbPSi7LguGiXILGp@H94PPDuJEsAIVgBlNN@Q33uI4Tm3R23fpZJ/@/qHHXNWyT3L@vk2MPy3lFi4@0h4bPRRZ9oTXTmPJROmi10KKv9v1XxZZjhUffl9Ma13oe11LsvcYP2iOSe0D@AA "JavaScript (Node.js) – Try It Online") ## How? ### Shape encoding Each shape is encoded with 2 digits in base 36, which allows to store: $$\lfloor 2\times\log\_2 36\rfloor=10\text{ bits}$$ The bits are arranged in a \$4\times 4\$ matrix, with the piece wedged in the upper right corner. The least significant bit is mapped to the top-right cell and there are 6 implicit leading zeros. Examples: * The 1st entry is `0N` in base 36, which is \$23\$ in decimal and \$0000010111\$ in binary. This is a `J`. * The 6th entry is `FM` in base 36, which is \$562\$ in decimal and \$1000110010\$ in binary. This is a `T`. [![examples](https://i.stack.imgur.com/Ex28K.png)](https://i.stack.imgur.com/Ex28K.png) All shapes can be encoded that way, except the vertical `I`. This one is encoded as `00` and its actual value (\$4369\$ in decimal) is hard-coded separately. ### Main algorithm The main algorithm consists of 5 nested loops where we try to put each shape \$p\$ at each possible position \$(x,y)\$ in the grid \$a\$ and figure out which one leads to the grid \$b\$. Whenever a row is completed, we yield an empty array so that `.flatMap()` deletes this row and we decrement the index \$i\$ of the entry that needs to be read in the resulting array to account for the row shift. We may end up with a negative \$i\$. But because we use a XOR for the comparison, undefined rows behave like they were set to \$0\$, which is what we want. ``` "...".match(/../g) // list of shapes .findIndex(p => // for each shape p: b.some((r, y) => // for each y: [...r].some((_, x) => // for each x: !b.some((s, i)=> // for each row s at position i in b: [ ...a.map( // using the helper function B, decode a[] by B = r => '0b' + r // converting each binary string to an integer ), ~0 // and append a full line at the bottom ].flatMap(t = // initialize t to a non-numeric value (r, Y, a) => // for each row r at position Y in this array: ~( // q = ( // q is the 4-bit mask of the shape ( parseInt(p, 36) // decoded from the base-36 value p, || 4369 ) // >> (Y - y) * 4 // keeping only the bits for this row & 15 // ) << x, // and left-shifting by x t |= q & a[Y + 1], // update the 'touching' mask q |= q & r ? ~0 // invalidate the row if q overlaps r : r // otherwise, merge q and r ) + 2 ** s.length ? // if the resulting line is not full: q // yield q : // else: (i--, []) // decrement i and yield an empty array, // which results in the deletion of this // line by flatMap() )[i] // end of flatMap(); extract the i-th row ^ B(s) // the test fails if this row is not equal to s | !t // or the shape is floating in the air ) // end of some() ) // end of some() ) // end of some() ) // end of findIndex() ``` ### Final result The shapes are stored in the following order: ``` 0N F7 1Z MA 13 FM 00 0F 1F 1F 1I FL 2R 8I 38 LT 35 7N 36 8H 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 **J** **J** **L** **L** **T** **T** **I** **I** **O** **O** **Z** **Z** **S** **S** **J** **J** **L** **L** **T** **T** ``` which is why the final result is the value returned by `.findIndex()` modulo \$14\$, divided by \$2\$ and rounded towards \$0\$. (NB: The shape `O` is stored twice so that it doesn't break the pattern.) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 156 124 bytes Takes two matrices, `1` indicating an empty tile, `2` indicating a tile with a piece. Maps `O => 15, I => 1, J => 57, L => 60, S => 30, T => 23, Z => 51`. ``` hI{∧Ḋ}ᵐ²O;I{zzᵐ+ᵐ²};21ẹᵗ↔c{≡ᵛ²h|∧1}ᵍbᵐ{-₁ᵐ²}ʰc~t?&h{{∧2}ᵐ}ʰ↺₁;O↰₂c∋3∧O{{¬=₀&}ˢ\}↰₇{\↔ᵐ|}{↔↔ᵐ|}{l₂ccẹ~ḃ{15|23|30|51|57|60}}|1 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P8Oz@lHH8oc7umofbp1waJO/tWd1VRWQqQ3m1lobGT7ctfPh1umP2qYkVz/qXPhw6@xDmzJqgHoMgTp6k4DKqnUfNTVClJ/akFxXYq@WUQ0y1AhkJFDoUdsuoAJr/0dtGx41NSU/6ug2Bsr6V1cfWmP7qKlBrfb0ophasGR7dQzQHqCumtpqIAPOzgHpSwY6pO7hjuZqQ9MaI@MaY4MaU8MaU/MaM4Pa2hrD//@jo6MNdUDQCARjddB4RjqGMBgL5EYbIvEhao2wq439HwUA) or [try all test cases (with nicer I/O)!](https://tio.run/##VVAxS8NAFN79FeUdZLENJqV2KOpcETLoZNvBBjVgQVCh2LsrGiG2iuAgiDjpooNDKRTajh31V9z9kfjuLmmTDPe@@9733fde2hdHfnDdOT914wLtQqG0XYCuRcXsvn1GwQY5@HIYEFVdLibPi7E6ZTSS0VuFOhXkwQPmqFoHVqkqsAtsc0OBPWBlDfaBuWUFDlCjxYdgcTEfysE3nBx1Lo9twJt6Ow7qFAVi@mDyvFqd9noI1018zXXEfCYmrzJ68akcfojJ@2IcMDUpOp7aKKMlGd4a@e/I71/tWAGl6QpIyWiOgppn9qj6cvCopvMoXfxsyfDG4n@fTW66jkubGIVGximCJe7IMPR9nKUvpnf4K3BD3BbXw7@A@3POnDhuNGDN1l9aoKgYQjSjC7SKDcMRolSqEHMz4qw9kaUeO@fJBGTFaUN7VKTiciXjQUPSWOUsKTtprAy5M5lKPaFDScInWPMZZ05Hlgy0Wv8) (Byte count is a bit longer because the header increases the predicate numbers.) ### How it works We search for a matrix `O` so that the input plus `O` after the removal rules will be equal to the output. We then trim `O` to contain a submatrix, bounded by the tetromino. Trying all orientations, it either fits in a 2 by x matrix – then we can convert it from base 2. Otherwise it is the `I` piece. ``` h{∧Ḋ}ᵐ²O ``` Before this challenge, I would have created a matrix of the same dimension by taking the input length, mapping the rows length over it, and say every element should be a number … but this is much neater: `O` is the input, but every element in it is just any number. This is much neater! ``` ;I{zzᵐ+ᵐ²} ``` `O` + Input ``` ;21ẹᵗ↔c{≡ᵛ²h|∧1}ᵍbᵐ ``` This is a very convoluted way to split in the rows into ((contains only 2s), (doesn't contain only 2s)). There are technically shorter versions, but all my attempts forced labelization of the numbers, slowing the program down to pure brute force. (This was really frustrating finding a version that works at all.) ``` {-₁ᵐ²}ʰc~t? ``` Subtract 1 from the removed rows, and join ((contained only 2s, now only 1s), (rest)) back together. This should be equal to the second input matrix. ``` &h{{∧2}ᵐ}ʰ↺₁;O↰₃c∋3 ``` If we take the input matrix, set the top row to only 2s, rotate it up, and after adding `O` there should be a 3: then the tetromino wasn't floating. ``` ∧O{{¬=₀&}ˢ\}↰₅ ``` Trim `O` so it only contains the tetromino. It would be nice if this could end here. However, `O` isn't guaranteed to be a tetromino by now and could be some disconnected 1s. So … ``` {\↔ᵐ|}{↔↔ᵐ|}{l₂ccẹ~ḃ{15|23|30|51|57|60}}|1 ``` Check all rotations, and if it is a 2 by x matrix, convert to base 2 and check if one of the numbers matches. If nothing matches, it is the I piece. ]
[Question] [ Suppose an infinite tiling of hexagons composed of `|/\` characters. ``` / \ / \ / \ / \ | | | | | \ / \ / \ / \ / etc. | | | | \ / \ / \ / ``` Given input `n > 0`, output a triangular portion of that tiling as depicted in the below examples, anchored with a `_` in the middle of a hexagon: ``` n=1 \_/ n=2 \/ \/ \_/ n=3 \ | / \/ \/ \_/ n=4 \/ \ / \/ \ | / \/ \/ \_/ n=5 \ | | / \/ \ / \/ \ | / \/ \/ \_/ n=6 \/ \ / \ / \/ \ | | / \/ \ / \/ \ | / \/ \/ \_/ n=7 \ | | | / \/ \ / \ / \/ \ | | / \/ \ / \/ \ | / \/ \/ \_/ n=8 \/ \ / \ / \ / \/ \ | | | / \/ \ / \ / \/ \ | | / \/ \ / \/ \ | / \/ \/ \_/ and so on ``` ### Rules * Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * Output can be to the console, saved as an image, returned as a list of strings, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` i=k=input() while i:i-=1;print(" "*(k+~i)+"\\"+i*' / |\ '[i%2::2])[:k-~i]+"_/"[i>0:] ``` [Try it online!](https://tio.run/##BcFNCsIwEAbQfU8xDEjzQ6lmVUbSiyTBldCPSAwlIkLp1eN79de2d3G9w2ePUj9N6eG74fUkCCZ/u9cdpSkmNirbE9pyjGxhRpqJjkg0BlyciEs6SJ5OJMuPmQPWq6Telz8 "Python 2 – Try It Online") One of Erik’s tricks allowed me to golf 3 bytes! Saved 3 bytes thanks to Jonathan Allan. ## How this works First off, this gets input from STDIN and assigns it to two separate variables `i` and `k`. Then, while the variable `i` is truthy, we decrement it and generate the strings accordingly; this is a shorthand for looping from the input - 1 all the way down to 0. ### Generating the Strings I'll split this into more parts: * First off, getting the leading spacing is achieved with `" "*(k+~i)`. Since `i` is mapped through the range **(input, 0]**, we must subtract it from `k` (our safely stored original input), decrement and repeat a space that many times. * `+"\\"` - Adds the character `"\"` to the spaces above. * `' / |\ '[i%2::2]` - Generates our two strings, namely `"/ \ "` and `" | "`, in the following manner: + If `i` is odd, **i % 2** is **1**, thus `[i%2::2]` returns each 2 characters of our larger string, starting at index **1** (0-indexed). + If `i` is even, **i % 2** is **1**, thus the mechanism above does the same except it starts at index **0**. * `+~-i*` - Repeats the string generated above, either `"/ \ "` or `" | "`, **i-1** times, and appends it to the other strings. The benefit of the bitwise operator (`~` - Bitwise Complement, Equivalent to **i** subtracted from **-1**) is that it doesn't require parenthesis in this context. * `[:k-~i]` - Gets all the characters of the strings concatenated above until index **k-~i = k - (-1 - i) = k + 1 + i**. * `+"_/"[i>0:]` - This only adds `"/"` if **i ≥ 1**, else it appends `_/`. ## Full example / execution details Let's grab an example of how things work for an input of **4**: ``` i=k=input() # i and k are assigned to 4. while i: # Starts the loop. The initial value of i is 4. i-=1; # Decrement i. i is now 3. " "*(k+~i) # A space repeated k - 1 - i = 4 - 1 - 3 = 0 times. +"\\" # Plus the character "\". CS (Current string): "\". ' / |\ '[i%2::2] # The string ' / |\ '[3%2::2] = ' / |\ '[1::2] = "/ \ ". i* # ^ repeated i = 3 times: "/ \ / \ / \ ". + # And concatenate. CS: "\/ \ / \ / \ " [:k-~i] # Get the characters of ^ up to index k + 1 + i = 4 + 1 + 3 = 8. # CS: "\/ \ / \". +"_/"[i>0:] # Append "_/"[i>0:] = "_/"[3>0:] = "_/"[1:] = "/". # CS: "\/ \ / \/". print # Output the result "\/ \ / \/". while i: # i is truthy (> 0), thus we loop again. i-=1; # Decrement i. i becomes 2. " "*(k+~i) # " " repeated 4 - 2 - 1 = 1 time. +"\\" # Plus "\". CS: " \". ' / |\ '[i%2::2] # ' / |\ '[2%2::2] = ' / |\ '[::2] = " | ". +i* # Repeat i = 2 times and append: " | ". CS: " \ | |". [:k-~i] # CS up until k + 1 + i = 4 + 2 + 1 = 7. CS: " \ | ". +"_/"[i>0:] # Append "/". CS: " \ | /". print # Outputs the CS: " \ | /". while i: # i is truthy (> 0), thus we loop again. i-=1; # Decrement i. i is now 1. " "*(k+~i) # " " repeated 4 - 1 - 1 = 2 times. +"\\" # Plus "\". CS: " \". ' / |\ '[i%2::2] # ' / |\ '[2%2::2] = ' / |\ '[::2] = "/ \ ". +i* # Repeat i = 1 time and append: "/ \ ". CS: " \/ \ ". [:k-~i] # CS up until k + i + 1 = 4 + 2 = 6. CS: " \/ \". +"_/"[i>0:] # Append "/". CS: " \/ \/". print # Outputs the CS: " \/ \/". while i: # i is truthy (> 0), thus we loop again. i-=1; # Decrement i. i is now 0. " "*(k+~i) # " " repeated 4 - 1 - 0 = 3 times. +"\\" # Plus "\". CS: " \". ' / |\ '[i%2::2] # ' / |\ '[1%2::2] = ' / |\ '[1::2] = " | ". +i* # Repeat i = 0 times and append: " \". CS: " \". [:k-~i] # CS up until k + i + 1 = 4 + 0 + 1 = 5. CS: " \". +"_/"[i>0:] # Append "_/" (because i > 0 is False since i == 0). CS: " \_/". print # Outputs the CS: " \_/". while i: # i == 0, hence the condition is falsy and the loop ends. # Program terminates. ``` [Answer] # [Python 2](https://docs.python.org/2/), 90 bytes ``` n=N=input() while N:print' '*(n-N)+'\\'+(('/ \| '[N%2::2]*n)[:N*2-1],'_')[N<2]+'/';N-=1 ``` [Try it online!](https://tio.run/##BcFNCsIwEAbQvaeYjXz5MZTOSqK5wlwgCa6EBmQMkiKCd0/f67@xvZXn1CSpad@Hsafv1l5Pktg/TQcIzmgQ61EKvDFYiKj8iZDlzDFydWpzFMdhrRc8YLPcuXosuElI65zXAw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 33 bytes ``` 1ŸεÐi'_ë"/ \ | "4ôsès∍}'\ì.∞}.c ``` [Try it online!](https://tio.run/##ATcAyP8wNWFiMWX//zHFuM61w5BpJ1/DqyIvIFwgICB8ICI0w7Rzw6hz4oiNfSdcw6wu4oiefS5j//84 "05AB1E – Try It Online") [Answer] # Mathematica, 131 bytes ``` Join[Table[s=StringRiffle@Table[If[OddQ@i,"/ \\"," | "],⌈i/2⌉];""<>{"\\",If[!OddQ@i,{" ",s," "},s],"/"},{i,#-1,1,-1}],{"\_/"}]& ``` returns a list of strings [Try it online!](https://tio.run/##LY29CsJAEIRfZV3BakOIYKWRtNr4210OOc2dLiQRzHUxvUKeMi9yrmg18M03TGX8zVbG88UEBymE9Z1rdTTn0qomPfgH19c9O1fa7AdXTm2KYpcxYQx5joTwBNQ09C@Op0P/1nPExbLFbyfy6G@3CEiN2NhRo2Us2TKNo4QSipJOi5GfhOpJ2Mqrh8ypmQ4f "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~129~~ ~~119~~ 112 bytes ``` \d+ $* ¶$`a $'$' m`$ / /$ _/ ^.¶ a( )*/ a$#1/ \d+ $* 1 / a ( )*/ $#1/ \d+ $* 1 | a /¶ a/¶ a \ ``` [Try it online!](https://tio.run/##VYy7CYBAEETzqWLAhfMDLhfYjagLGhhoIIbWZQE2di4KghNM8nhvm/Z5tZTasYKUBHGdMhglSCCWQaAgVdAruvo6AcvpK0qFSRYVr4kIpdEDH/5THg6N6gl7Dm1KzQ0 "Retina – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` NθG↖→↓θ“ ″✂=AL«Q"η\`”←_↖θ‖B ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orID@nMj0/T8MqtMAnNa1ER8EqKDM9A0S75Jfn6SgU6igoKSjUxOQp6CvExMTkgVgxMQr6SiC9RZl5JRpWEH1K8UhCMMNANgSlpuWkJpc4lZaUpBal5VRqaFr//2/xX7csBwA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Python 2](https://docs.python.org/2/), ~~123~~ ~~112~~ ~~110~~ ~~109~~ ~~100~~ ~~98~~ 96 bytes ``` i=n=input() while i:a=i%2;print' '*(n-i)+'\%s/'%['_',((-~i/2)*'/ \ |'[a::2])[a:~a]][i>1];i-=1 ``` [Try it online!](https://tio.run/##DcVBCsIwEAXQvaeYTZikNYRmJSnxImmQLIR@kDHYiBSkV4@@zat7W5/ie0eUCKnvps3ps@JxJ4QSofxcX5DGxIMWCzPyojbHKvGNz1rbA86bgR0RLURfTiUEn82/o@SccJ3yDBun3i8/ "Python 2 – Try It Online") * Saved a bunch of bytes by using input and string formatting as in [Rod's answer](https://codegolf.stackexchange.com/a/146648/38592) * Saved 2 bytes thanks to Mr. Xcoder [Answer] # [Python 2](https://docs.python.org/2/), 103 bytes ``` i=n=input() while i:print' '*(n-i)+'\%s/'%' '.join(['/\\'*(-~i/2),['_',' '+'| '*(i/2)][i>1]][i%2]);i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2zzYzr6C0REOTqzwjMydVIdOqoCgzr0RdQV1LI083U1NbPUa1WF9dFSigl5WfmacRra4fEwOU1K3L1DfS1IlWj1fXAUpqq9eAtIDEYqMz7QxjgaSqUaymdaaureH//xYA "Python 2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~97~~ 93 bytes ``` {⍵=1:1 3⍴'\_/'⋄x←' ',' ',⍨∇⍵-1⋄y←1+2×⍵-1⋄2|⍵:x⍪⍨'\','/',⍨y⍴' | '⋄x⍪⍨'\/','\/',⍨(y-2)⍴' \ /'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bbQ2tDBWMH/VuUY@J11d/1N1SAZRQV1DXAeFHvSsedbQDVekaAmUqgTKG2kaHp8MEjGqALKuKR72rgArVY4B69MF6KkHGKSjUKEDMg0oD5cAEkKNRqWukCVYUo6CvXgt0zaEVj3o3WwAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~28~~ 27 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ╔.H∫"C↕‽«‘4nwιF«Im}¹⌡¾\/¹№╚ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTU0LkgldTIyMkIlMjJDJXUyMTk1JXUyMDNEJUFCJXUyMDE4NG53JXUwM0I5RiVBQkltJTdEJUI5JXUyMzIxJUJFJTVDLyVCOSV1MjExNiV1MjU1QQ__,inputs=NQ__) [Answer] # [Haskell](https://www.haskell.org/), ~~96~~ 95 bytes ``` f n=[([1..n-x]>>" ")++'\\':take(2*x+1)(cycle$("_":a)!!x)++"/"|x<-[n,n-1..0]] a="/ \\ ":" | ":a ``` [Try it online!](https://tio.run/##DYtBCoMwEADvfcW6CCZN1dpLITR@osdESpCIYrqUGiEF/57mNHOYme22Ou9TmoCUZrprGqrj0PcIyIWojKlksKtjt3MUHWfjb/SuZPhCaXlRxNxgi0d81JouVOf9Ogwnq7AFYwAlAhwZNr3tQqDgs4dn@EIJO/mF3JZtgnv6Aw "Haskell – Try It Online") 0-indexed and returns a list of lines. [Answer] ## Haskell, ~~101~~ 99 bytes ``` j 1=["\\_/"] j n|r<-([1,3..n-1]>>)=('\\':cycle[init$r"/ \\ ",' ':r" | "]!!n++"/"):map(' ':)(j$n-1) ``` Returns a list of lines. [Try it online!](https://tio.run/##FY1LCoMwGAb3PcXnj5AEX4TuQuMJ2lWXiYiI0GgMktpFwbundjsDM6/hvUzepzRDakPW9g11lxnhiLeKG1le6zpUsmtboTmzlqnxO/rJuOD2PFIDa0ElA1ORcADUZVkoCmpIqHXY@N8IPudnQ6R1cAEaJ3/02D77c4/3gBznW6Yf "Haskell – Try It Online") How it works: ``` j 1=["\\_/"] -- base case, n=1 j n -- for all other n |r<-([1,3..n-1]>>) -- let r be the function that makes n/2 copies of -- it's argument = -- the result is '\\': -- a backslash, followed by cycle[ ]!!n -- the inner part, which is init$r"/ \\ " -- all but the last char of some copies of -- "/ \ " for even line numbers, or ' ':r" | " -- some copies of " | " prepended by a space -- for odd line numbers -- (chosen by indexing an infinite list of -- both values alternating) ++"/" -- followed by a slash : -- and append a j$n-1 -- recursive call with n-1 map(' ':) -- where each line is prepended by a space ``` Edit: @Laikoni saved two bytes. Thanks! [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~315~~ 306 bytes ``` i->{String r="";int j=0,k,u=i*2;char[][]c=new char[i][u+1];c[i-1][i]=95;for(;j<i;r+="".valueOf(c[j++]).replace('\0',' ')+"\n")for(k=0;k<u+1;k++){if(k==j)c[j][k]=92;if(k==u-j)c[j][k]=47;if(k>j&k<u-j)if((i-j)%2<1)c[j][k]=(k-j-1)%2<1?(char)(47+((k-j-1)/2)%2*45):32;else if((k-j-1)%4==2)c[j][k]='|';}return r;} ``` [Try it online!](https://tio.run/##RZHNbsIwEITPzVNYSG1s8lMSQKh1TG@Veqh64BhycIMBJ8GJHJsKUZ493UBEfbH2251Za1zwIw/qRqhiU3by0NTaoAJYaI2swq1VuZG1CsfUcRr7Xckc5RVvW/TJpUJn56E13AB8HwaTD2XETmgfrYyWardEe3kUiKFOBsvzjSHNRiMqFSxiE7/0LZPjmOZ7rtMszXKmxA@6VjJLrRdlNE9lEGVQspc53dYa0yKRVHtgEx55ZcXXFudp4XkZCbVoKp4L7K4nru8il3ijtRqRXlWyCS0TcKSl55Gz3AJhBQFllpbgHdMbssE/nC2ucFk8gRI4FFjC/Rgn0X0Il0ERRFf2hvuXEzxbeHjAzzF0xrM5eZ3GVFStQL3JIJkxFt993F@XXrQwViuk6aWjQ@JDxsdabtABcse3HNMMcQJ/gIazOrVGHMLamrCBvsF99CFvmuqEoykh9Dp5cS7dHw "Java (OpenJDK 8) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 198 bytes Finally got it below 200 bytes. Will probably post an explanation later. ``` i->{for(int k=i+1;i>0;System.out.println(("".format("%"+(k-i)+"s","")+"\\"+(i<2?"":"".format("%"+(i-1)+"s","")).replace(" ","/ \\ , | ".split(",")[i%2])).substring(0,i<2?k:k+i)+(--i<1?"_/":"/")));} ``` [Try it online!](https://tio.run/##XY@9bsJAEITr81OsVkI6y/ZhU1BgfuoUoaG0UXTAgRabs@U7kCLiZ3cWK0mRarWjmW80V/3QSdMaez1Vw7HWzsG7JvsMBFlvurM@Gtg@AxDi0dAJLpJloDAPRB8Eor0fajqC89rzGR03Tsud78heij3okElizMAK3hh5MZ1qdecMP1IX6f7FElYx@Zf6g9uC5cxAyfp5brqxuFpRlOW0TvPdp/Pmppq7Vy13@dpKiajYeNNe4gQjWSUURugwRuRblizRcrZBXPwzUpL9GUPVmbbm1RKBhSmUJcQAX4DKtTVxIsawoMlsz1Z3P7hxqUzjF7paVBF3yiShZbbBjylXTZkZ5v0g8qAfhvk3 "Java (OpenJDK 8) – Try It Online") [Answer] # JavaScript (ES6), ~~89~~ 85 bytes ``` f=(y,s='\\')=>--y?s+(y&1?' / \\':' | ').repeat(y).slice(~y-y)+`/ `+f(y,' '+s):s+'_/' ``` ### Demo ``` f=(y,s='\\')=>--y?s+(y&1?' / \\':' | ').repeat(y).slice(~y-y)+`/ `+f(y,' '+s):s+'_/' console.log(f(1)) console.log(f(2)) console.log(f(3)) console.log(f(4)) console.log(f(5)) console.log(f(6)) console.log(f(7)) ``` [Answer] # CJam, 43 ``` ri_{S*'\@(:X" | / \ "4/=X*X2*)<'_e|'/NX}/; ``` [Try it online](http://cjam.aditsu.net/#code=ri_%7BS*%27%5C%40(%3AX%22%20%20%7C%20%2F%20%5C%20%224%2F%3DX*X2*)%3C%27_e%7C%27%2FNX%7D%2F%3B&input=8) [Answer] # PHP, 89+1 bytes ``` while($k=$argn-$n)echo($p=str_pad)("",$n++),$p("\\",2*$k,$k>1?$k&1?" | ":"/ \ ":_),"/ "; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/71e3795a77c65c4d95c80c96c093e86d2da2db07). [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~46~~ 44 bytes ``` j_m+<++*;t-Qd\\*d%2>" / |\ "%d2h+Qd>"_/"._ ``` **[Try it here!](https://pyth.herokuapp.com/?code=j_m%2B%3C%2B%2B%2a%3Bt-Qd%5C%5C%2ad%252%3E%22+%2F++%7C%5C++%22%25d2h%2BQd%3E%22_%2F%22._&test_suite=1&test_suite_input=1%0A2%0A5%0A6&debug=0)** ]
[Question] [ The [3BV](http://www.minesweeper.info/wiki/3BV) of a [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) board represents the minimum number of left clicks required to solve the board if you already know the solution. It stands for "Bechtel's Board Benchmark Value". Here's [his site](http://www.stephan-bechtel.de/3bv.htm) explaining it. Below is a solved Minesweeper board. The flags indicate mines; tiles without mines indicate the count of adjacent mines, including diagonally, except that tiles that should have "0" are left blank instead. The image shows which tiles need to be clicked in order to solve the board. [![Counting 3BV](https://i.stack.imgur.com/sF8v3.png)](https://i.stack.imgur.com/sF8v3.png) **Clicks counted towards the 3BV are:** * **One for each flood-filled area** of blank tiles (zero mines adjacent) and their non-blank neighbors. * **One for each other non-mine tile.** --- ### Another Example (3BV = 39) [![Solved Minesweeper board](https://i.stack.imgur.com/ZFXD7.png)](https://i.stack.imgur.com/ZFXD7.png) [![Clicks required](https://i.stack.imgur.com/1KZsx.png)](https://i.stack.imgur.com/1KZsx.png) --- Given a 2D array of values, `0` for clear and `1` for a mine (or a boolean), **return the 3BV**. A board's dimensions will be at least 8x8, and at most 24x30, inclusive. Your program should handle all possible boards, not just the examples. **Note: A board will never contain only mines.** ### Example I/O: ``` [[0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,1,0,0,1,0], [0,1,0,0,1,0,0,0], [0,0,1,0,0,0,0,1], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]] 23 [[0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0], [0,0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0], [0,1,0,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,1,0,0,0,1,0,1,0,1,0], [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0], [0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1], [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0], [1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0], [0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0,0,1,1,0,0], [0,1,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0], [0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0], [0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0]] 187 ``` [Answer] # MATLAB, ~~92~~ ~~90~~ ~~86~~ ~~83~~ ~~79~~ ~~74~~ 72 bytes ``` x=input('');I=@(x)~imdilate(x,ones(3));[C,N]=bwlabel(I(x));nnz(I(C)-x)+N ``` This solution accepts the input in the form of a 2D matrix of 0's and 1's and will display the 3BV value for the provided input. Here is slightly modified [demo](http://ideone.com/KcBMLO) in Octave for those of you without MATLAB. **Explanation** The input matrix is dilated using a 3 x 3 matrix of `1`'s and then inverted (using `~`) which identifies all of the points that do not have mines as neighbors (`1`) or do (`0`). To determine the number of connected regions, we use `bwlabel` to label each connected region of `1`'s. The first output is the label matrix (`0` where the input was zero and any value in the range `1...N` where there was a `1` in the input where `N` is the index of the connected group that it belongs to). The second output is the number of regions (the number of clicks required to open them). The result of the `bwlabel` is shown in the image on the left. [![enter image description here](https://i.stack.imgur.com/XKmfZ.png)](https://i.stack.imgur.com/XKmfZ.png) We expand the first output of `bwlabel` using `imdilate` (all non-zeros are expanded) using a 3 x 3 matrix of `1`'s. The result is shown in the image in the middle. To determine the remaining clicks, we then count the squares that are not in this expanded region (`~imdilate()`) and not a mine (`-x`) (white squares in the image on the right) and add this to the total number of open regions (the number of different colors in the image on the left) to get the 3BV. [Answer] # Octave, ~~86~~ ~~84~~ ~~79~~ 66 bytes ``` @(x)nnz(~imdilate(c=imerode(~x,o=ones(3)),o)-x)+max(bwlabel(c)(:)) ``` This solution creates an anonymous function named `ans` which can then be passed a 2D matrix of `0`'s and `1`'s. The logic is the same as my MATLAB answer but uses a few tricks that Octave has to offer to save space. This solution requires that the `image` package is installed. [**Demo here**](http://ideone.com/aHoYRo) [Answer] # MATL, ~~24~~ ~~22~~ 21 bytes *1 byte saved thanks to @Luis* ``` 4Y6Z+~l2#ZIw7MZ+G+~z+ ``` Try it at [MATL Online](https://matl.io/?code=4Y6Z%2B%7El2%23ZIw7MZ%2BG%2B%7Ez%2B&inputs=%5B0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%3B+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%3B+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+0%2C+1%2C+0%3B+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+1%2C+0%2C+0%2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2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%3B+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%2C+0%2C+0%3B+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+0%2C+0%3B+0%2C+1%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%3B+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%3B+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D&version=20.0.0) **Explanation** Again, this is similar to my MATLAB and Octave answers to this question. ``` % Implicitly grab input array 4Y6 % Push the literal [1 1 1; 1 1 1; 1 1 1] to the stack Z+ % Perform 2D convolution of the input with this array ~ % Negate the result l2#ZI % Call bwlabeln which dilates each open region and the second output % returns the number of open regions w % Flip the top two stack elements 7M % Push the literal [1 1 1; 1 1 1; 1 1 1] to the stack again Z+ % Perform 2D convolution G+ % Explicitly grab the input and add it to the result ~z % Count the number of 0's in the result (the remaining number of clicks) + % Add the total number of remaining clicks to the number of open regions ``` ]
[Question] [ ## Introduction Gijswijt's sequence ([A090822](https://oeis.org/A090822)) is famously really, REALLY slow. To illustrate: * The first 3 appears in the 9th term (alright). * The first 4 appears in the 220th term (a long way away, but feasible). * The first 5 appears at (approximately) the **10^(10^23)th term** (just no). * No one really even knows where the first 6 is... it's suspected it's at the... ### 2^(2^(3^(4^5)))th term. **You can assume that you won't have to deal with a two-digit number.** The sequence is generated like so: 1. The first term is 1. 2. Each term after that is the amount of repeating "blocks" previous to it (if there are multiple repeating "blocks", the largest amount of repeating blocks is used). To clarify, here are the first few terms. `1 -> 1, 1` (one repeating block (`1`), so the digit recorded is `1`) `1, 1 -> 1, 1, 2` (two repeating blocks (`1`), so the digit recorded is `2`) `1, 1, 2 -> 1, 1, 2, 1` (one repeating block (`2` or `1, 1, 2`), so the digit recorded is `1`) `1, 1, 2, 1 -> 1, 1, 2, 1, 1` (you get the idea) `1, 1, 2, 1, 1 -> 1, 1, 2, 1, 1, 2` `1, 1, 2, 1, 1, 2 -> 1, 1, 2, 1, 1, 2, 2` (two repeating blocks (`1, 1, 2`), so the digit recorded is `2`) ## Task Your task is, as stated in the question, to generate n digits of the Gijswijt sequence. ## Instructions * The input will be an integer `n`. * Your code can output the digits in any form (a list, multiple outputs, etc.). This is code golf, so shortest code in bytes wins. [Answer] # Pyth, ~~25~~ ~~22~~ 21 bytes ``` t_u+eSmtfxG*Td1._GGQN ``` OP confirmed that we only need to handle single-digit numbers. This allowed to store the list as a string of digits. -> Saved 3 bytes Try it online: [Demonstration](http://pyth.herokuapp.com/?code=t_u%2BeSmtfxG*Td1._GGQN&input=30&debug=0) ### Explanation: ``` t_u+...GQN implicit: Q = input number N start with the string G = '"' u Q do the following Q times: ... generate the next number + G and prepend it to G _ print reversed string at the end t remove the first char (the '"') ``` And here's how I generate the next number: ``` eSmtfxG*Td1._G ._G generate all prefixes of G m map each prefix d to: f 1 find the first number T >= 1, so that: *Td d repeated T times xG occurs at the beginning of G S sort all numbers e take the last one (maximum) ``` ### 21 bytes with lists ``` _u+eSmhhrcGd8SlGGtQ]1 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=_u%2BeSmhhrcGd8SlGGtQ]1&input=20&debug=0) Uses the same ideas of Martin and Peter. At each step I split the string into pieces of length 1, pieces of length 2, ... Then I range-length-encode them and use the maximal first run as next number. ### 20 bytes with strings ``` t_u+eSmhhrcGd8SlGGQN ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=t_u%2BeSmhhrcGd8SlGGQN&input=20&debug=0) Combines the ideas of the two codes above. [Answer] ## CJam, ~~33~~ ~~31~~ ~~30~~ 27 bytes *Thanks to Peter Taylor for saving 1 byte.* ``` 1sri({),:)1$W%f/:e`$W=sc+} ``` [Test it here.](http://cjam.aditsu.net/#code=1sri(%7B)%2C%3A)1%24W%25f%2F%3Ae%60%24W%3Dsc%2B%7D%2F&input=220) ### Explanation ``` 1s e# Initialise the sequence as "1". ri( e# Read input N and decrement. { e# For each I from 0 to N-1... ) e# Increment to get I from 1 to N. , e# Turn into a range [0 1 ... I-1]. :) e# Increment each element to get [1 2 ... I]. 1$ e# Copy sequence so far. W% e# Reverse the copy. f/ e# For each element x in [1 2 ... I], split the (reversed) sequence e# into (non-overlapping) chunks of length x. These are the potentially e# repeated blocks we're looking for. We now want to find the splitting e# which starts with the largest number of equal blocks. :e` e# To do that, we run-length encode each list blocks. $ e# Then we sort the list of run-length encoded splittings, which primarily e# sorts them by the length of the first run. W= e# We extract the last splitting which starts with the longest run. sc e# And then we extract the length of the first run by flattening e# the list into a string and retrieving the first character. + e# This is the new element of the sequence, so we append it. }/ ``` [Answer] ## CJam (30 29 27 24 bytes) ``` '1ri{{)W$W%/e`sc}%$W>+}/ ``` [Online demo](http://cjam.aditsu.net/#code='1ri%7B%7B)W%24W%25%2Fe%60sc%7D%25%24W%3E%2B%7D%2F&input=220) This is very much a joint effort with Martin. * The clever use of run-length encoding (`e``) to identify repetitions is Martin's * So is the use of `W$` to simplify the stack management * I eliminated a couple of increment/decrement operations by using `$W>+` special-casing, as explained in the dissection below --- My first 30-byte approach: ``` 1ari{,1$f{W%0+_@)</{}#}$W>+}/` ``` [Online demo](http://cjam.aditsu.net/#code=1ari%7B%2C1%24f%7BW%250%2B_%40)%3C%2F%7B%7D%23%7D%24W%3E%2B%7D%2F%60&input=220) ### Dissection ``` 1a e# Special-case the first term ri{ e# Read int n and iterate for i=0 to n-1 ,1$f{ e# Iterate for j=0 to i-1 a map with extra parameter of the sequence so far W%0+ e# Reverse and append 0 to ensure a non-trivial non-repeating tail _@)</ e# Take the first j+1 elements and split around them {}# e# Find the index of the first non-empty part from the split e# That's equivalent to the number of times the initial word repeats } $W>+ e# Add the maximal value to the sequence e# NB Special case: if i=0 then we're taking the last term of an empty array e# and nothing is appended - hence the 1a at the start of the program }/ ` e# Format for pretty printing ``` [Answer] ## Haskell, 97 bytes ``` f 1=[1] f n|x<-f$n-1=last[k|k<-[1..n],p<-[1..n],k*p<n,take(k*p)x==([1..k]>>take p x)]:x reverse.f ``` The third line defines an anonymous function that takes an integer and returns a list of integers. [See it in action.](http://ideone.com/CTGlIH) ## Explanation The helper function `f` constructs the sequence in reverse, by recursively checking whether the previous sequence begins with a repeated block. `k` is the number of repetitions, and `p` is the length of the block. ``` f 1=[1] -- Base case: return [1] f n|x<-f$n-1= -- Recursive case; bind f(n-1) to x. last[k|k<-[1..n], -- Find the greatest element k of [1..n] such that p<-[1..n], -- there exists a block length p such that k*p<n, -- k*p is at most the length of x, and take(k*p)x -- the prefix of x of length p*k == -- is equal to ([1..k]>>take p x) -- the prefix of length p repeated k times. ]:x -- Insert that k to x, and return the result. reverse.f -- Composition of reverse and f. ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~66~~ 60 bytes ``` +1`((\d+)?(?<1>\2)*(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))! $1$#1 ``` Input is a unary integer using `!` as the digit (although that could be changed to any other non-numeric character). Output is simply a string of digits. [Try it online!](http://retina.tryitonline.net/#code=KzFgKChcZCspPyg_PDE-XDIpKig_PCFcMyg_Pig_PC0xPlwzKSopKD8hLipcMikoLispKSkhCiQxJCMx&input=ISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhIQ) (Alternatively, for convenience [here's a version that takes decimal input.](http://retina.tryitonline.net/#code=LisKJCohCisxYCgoXGQrKT8oPzwxPlwyKSooPzwhXDMoPz4oPzwtMT5cMykqKSg_IS4qXDIpKC4rKSkpIQokMSQjMQ&input=MzA)) For testing purposes, this can be sped up *a lot* with a small modification, which allows testing of input 220 in under a minute: ``` +1`((\d+)?(?<1>\2)*(?=!)(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))! $1$#1 ``` [Try it online!](http://retina.tryitonline.net/#code=KzFgKChcZCspPyg_PDE-XDIpKig_PSEpKD88IVwzKD8-KD88LTE-XDMpKikoPyEuKlwyKSguKykpKSEKJDEkIzE&input=ISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhIQ) ([Decimal version.](http://retina.tryitonline.net/#code=LisKJCohCisxYCgoXGQrKT8oPzwxPlwyKSooPz0hKSg_PCFcMyg_Pig_PC0xPlwzKSopKD8hLipcMikoLispKSkhCiQxJCMx&input=MjIw)) If you want to test even larger numbers, it's best to just feed it some massive input and put a `:` after the initial `+`. This will make Retina print the current sequence each time it finishes computing a new digit (with all the digits off-by-one). ### Explanation The solution consists of a single regex substitution, which is applied to the input repeatedly until the result stops changing, which in this case happens because the regex no longer matches. The `+` at the beginning introduces this loop. The `1` is a limit which tells Retina only to replace the first match (this is only relevant for the very first iteration). In each iteration, the stage replaces one `!` (from the left) with the next digit of the sequence. As usual, if you need a primer on balancing groups [I refer you to my SO answer](https://stackoverflow.com/questions/17003799/what-are-regular-expression-balancing-groups/17004406#17004406). Here is an annotated version of the regex. Note that the goal is to capture the maximum number of repeated blocks in group `1`. ``` ( # Group 1, this will contain some repeated block at the end # of the existing sequence. We mainly need this so we can # write it back in the substitution. We're also abusing it # for the actual counting but I'll explain that below. (\d+)? # If possible (that is except on the first iteration) capture # one of more digits into group 2. This is a candidate block # which we're checking for maximum repetitions. Note that this # will match the *first* occurrence of the block. (?<1>\2)* # Now we capture as many copies of that block as possible # into group 1. The reason we use group 1 is that this captures # one repetition less than there is in total (because the first # repetition is group 2 itself). Together with the outer # (unrelated) capture of the actual group one, we fix this # off-by-one error. More importantly, this additional capture # from the outer group isn't added until later, such that the # lookbehind which comes next doesn't see it yet, which is # actually very useful. # Before we go into the lookbehind note that at the end of the # regex there's a '!' to ensure that we can actually reach the # end of the string with this repetition of blocks. While this # isn't actually checked until later, we can essentially assume # that the lookbehind is only relevant if we've actually counted # repetitions of a block at the end of the current sequence. (?<! # We now use a lookbehind to ensure that this is actually the # largest number of repetitions possible. We do this by ensuring # that there is no shorter block which can be matched more # often from the end than the current one. The first time this # is true (since, due to the regex engine's backtracking rules, # we start from longer blocks and move to shorter blocks later), # we know we've found the maximum number of repetitions. # Remember that lookbehinds are matched right-to-left, so # you should read the explanation of the lookbehind from # bottom to top. \3 # Try to match *another* occurrence of block 3. If this works, # then this block can be used more often than the current one # and we haven't found the maximum number of repetitions yet. (?> # An atomic group to ensure that we're actually using up all # repetitions from group 1, and don't backtrack. (?<-1>\3)* # For each repetition in group 1, try to match block 3 again. ) (?!.*\2) # We ensure that this block isn't longer than the candidate # block, by checking that the candidate block doesn't appear # right of it. (.+) # We capture a block from the end into group 3. ) # Lookbehind explanation starts here. Read upwards. ) ! # As I said above, this ensures that our block actually reaches # the end of the string. ``` Finally, after this is all done, we write back `$1` (thereby deleting the `!`) as well as the number of captures in the group with `$#1` which corresponds to the maximum number of repetitions. [Answer] # Pyth, ~~41~~ 38 bytes ``` J]1VSQ=J+h.MZmh+fn@c+J0dT<JdSNZSNJ;P_J ``` [Try it online!](http://pyth.herokuapp.com/?code=J%5D1VSQ%3DJ%2Bh.MZmh%2Bfn%40c%2BJ0dT%3CJdSNZSNJ%3BP_J&input=9&debug=0) [Answer] # Ruby, 84 bytes The Retina answer inspired me to do a regex-based solution to find the best sequence instead of somehow counting sequences in an array, but with less of the genius (negative lookbehinds with quantifiers don't seem to be allowed in Ruby, so I doubt I could directly port Retina's answer over anyways) ``` ->n{s='';n.times{s+=(1..n).map{|i|s=~/(\d{#{i}})\1+$/?$&.size/i: 1}.max.to_s};s[-1]} ``` Given an already-generated sequence `s`, it maps over all `i` from `1` to `s.length` (`n` was used in this case to save bytes since `n>=s.length`) and then uses this regex to help calculate the number of repetitions of a subsequence with length `i`: ``` /(.{#{i}})\1+$/ /( # Assign the following to group 1 .{#{i}} # Match `i` number of characters ) # End group 1 \1+ # Match 1 or more repetitions of group 1 $/ # Match the end of string ``` If a match is found of that length, it calculates the number of repetitions by dividing the length of the given match `$&` by `i`, the length of the subsequence; if no match was found, it is treated as `1`. The function then finds the maximum number of repetitions from this mapping and adds that number to the end of the string. ]
[Question] [ *This is the 2-dimensional generalisation [of this challenge](https://codegolf.stackexchange.com/q/5529/8478).* For our purposes, one matrix (or 2D array) *A* is considered a **submatrix** of another matrix *B*, if *A* can be obtained by completely removing a number of rows and columns from *B*. *(Note: some sources have different/more restrictive definitions.)* Here's an example: ``` A = [1 4 B = [1 2 3 4 5 6 2 1] 6 5 4 3 2 1 2 1 2 1 2 1 9 1 8 2 7 6] ``` We can delete columns 2, 3, 5, 6 and rows 2, 4 from *B* to obtain *A*: ``` B = [1 2 3 4 5 6 [1 _ _ 4 _ _ [1 4 = A 6 5 4 3 2 1 --> _ _ _ _ _ _ --> 2 1] 2 1 2 1 2 1 2 _ _ 1 _ _ 9 1 8 2 7 6] _ _ _ _ _ _] ``` Note that *A* is still a submatrix of *B* if all rows or all columns of *B* are retained (or in fact if *A = B*). ## The Challenge You guessed it. Given two non-empty integer matrices *A* and *B*, determine if *A* is a submatrix of *B*. 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. Input may be in any convenient format. The matrices can be given as nested lists, strings using two different separators, flat lists along with the dimensions of the matrix, etc, as long as the input is not pre-processed. You may choose to take *B* first and *A* second, as long as your choice is consistent. You may assume that the elements of the matrices are positive and less then 256. Output should be [truthy](http://meta.codegolf.stackexchange.com/a/2194/8478) if *A* is a submatrix of *B* and [falsy](http://meta.codegolf.stackexchange.com/a/2194/8478) otherwise. The specific output value does not have to be consistent. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases Each test case is on a separate line, `A, B`. Truthy cases: ``` [[1]], [[1]] [[149, 221]], [[177, 149, 44, 221]] [[1, 1, 2], [1, 2, 2]], [[1, 1, 1, 2, 2, 2], [3, 1, 3, 2, 3, 2], [1, 1, 2, 2, 2, 2]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 7, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]] [[228, 66], [58, 228]], [[228, 66], [58, 228]] [[1, 2], [2, 1]], [[1, 2, 2], [2, 1, 2], [2, 2, 1]] [[136, 196], [252, 136]], [[136, 252, 210, 196, 79, 222], [222, 79, 196, 210, 252, 136], [252, 136, 252, 136, 252, 136], [180, 136, 56, 252, 158, 222]] ``` Falsy cases: ``` [[1]], [[2]] [[224, 15]], [[144, 15, 12, 224]] [[41], [150]], [[20, 41, 197, 150]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [7, 8, 9], [4, 5, 6]] [[1, 2, 2], [2, 1, 2], [2, 2, 1]], [[1, 2], [2, 1]] [[1, 2, 2], [2, 1, 2]], [[1, 2], [2, 1], [2, 2]] [[1, 2], [3, 4]], [[5, 3, 4, 5], [2, 5, 5, 1], [4, 5, 5, 3], [5, 1, 2, 5]] [[158, 112], [211, 211]], [[158, 211, 189, 112, 73, 8], [8, 73, 112, 189, 211, 158], [211, 158, 211, 158, 211, 158], [21, 158, 199, 211, 212, 8]] ``` [Answer] # Pyth, 10 bytes ``` }CQsyMCMyE ``` [Test suite](https://pyth.herokuapp.com/?code=%7DCQsyMCMyE&input=%5B%5B1%5D%5D%0A%5B%5B1%5D%5D%0A%5B%5B1%2C+3%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D%2C+%5B6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%2C+%5B2%2C+1%2C+2%2C+1%2C+2%2C+1%5D%2C+%5B9%2C+1%2C+8%2C+2%2C+7%2C+6%5D%5D%0A%5B%5B1%5D%5D%0A%5B%5B2%5D%5D%0A%5B%5B3%2C+1%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%5D%2C+%5B3%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+2%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D%2C+%5B6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%2C+%5B2%2C+1%2C+2%2C+1%2C+2%2C+1%5D%2C+%5B9%2C+1%2C+8%2C+2%2C+7%2C+6%5D%5D%0A&test_suite=1&test_suite_input=%5B%5B1%5D%5D%0A%5B%5B1%5D%5D%0A%5B%5B1%2C+3%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D%2C+%5B6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%2C+%5B2%2C+1%2C+2%2C+1%2C+2%2C+1%5D%2C+%5B9%2C+1%2C+8%2C+2%2C+7%2C+6%5D%5D%0A%5B%5B1%5D%5D%0A%5B%5B2%5D%5D%0A%5B%5B3%2C+1%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%5D%2C+%5B3%5D%5D%0A%5B%5B5%2C+1%2C+255%2C+3%5D%5D%0A%5B%5B1%2C+4%5D%2C+%5B2%2C+2%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%5D%2C+%5B6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%2C+%5B2%2C+1%2C+2%2C+1%2C+2%2C+1%5D%2C+%5B9%2C+1%2C+8%2C+2%2C+7%2C+6%5D%5D&debug=0&input_size=2) This is fairly straightforward. First, we consider B as a list of rows, and take all subsets using `yE`. Then, each of those matrices is transposed with `CM`, and all subsets are taken of their rows, with `yM`. Concatenating these sublists with `s` gives all possible transposed submatrices. So we transpose A with `CQ`, and check if it is present with `}`. [Answer] # Dyalog APL, ~~53~~ 43 bytes ``` (⊂A)∊⊃∘.{∧/∊2</¨⍺⍵:B[⍺;⍵]⋄⍬}/⍳¨(⍴A←⎕)/¨⍴B←⎕ ``` `B←⎕`, `A←⎕`prompt for `B` and `A` `⍴B`, `⍴A` dimensions of `B` and `A` `/¨` replicate each, e.g. `2 3/¨4 5` → `(4 4) (5 5 5)` `⍳¨` all indices in each of the coordinate systems with those dimensions `∘.{`…`}/` table of possible submatrices, where each submatrix is defined as the result of the anonymous function `{`…`}` applied between a pair of coordinates `⍺` and `⍵` `∧/∊2</¨:` if both `⍺` and `⍵` are (`∧/∊`) both (`¨`) increasing (`2</`), then... `B[⍺;⍵]` return submatrix of `B` created from the intersections of rows `⍺` and columns `⍵` `⋄⍬` else, return an empty vector (something that A is not identical to) `(⊂A)∊⊃` check if the whole of `A` (`⊂A`) is a member of `∊` any of the submatrices (`⊃`) --- ### Old 53-byte solution: ``` {(⊂⍺)∊v∘.⌿h/¨⊂⍵⊣v h←(⍴⍺){↓⍉⍺{⍵/⍨⍺=+⌿⍵}(⍵/2)⊤⍳⍵*2}¨⍴⍵} ``` `{`…`}` an anonymous inline function, where `⍺` is left argument and `⍵` is right argument `⍴` shape, e.g. 2 3 for a 2-by-3 matrix `(⍴⍺){`…`}¨⍴⍵` for each pair of corresponding dimension-lengths, apply this anonymous function `⍳⍵*2` indices of the square of, i.e. 2 → 1 2 3 4 `(⍵/2)⊤` convert to binary (number of bits is dimension-length squared) `{⍵/⍨⍺=+⌿⍵}` of the binary table, select the columns (`⍵/⍨`) where the number of 1s (`+⌿⍵`) is equal to the the length of that dimension in the potential submatrix (`⍺=`) `↓⍉` make table into list of columns `v h←` store as `v`(ertical masks) and `h`(horizontal masks) `⊣` then `h/¨⊂⍵` apply each horizontal mask to the right argument matrix `v∘.⌿` apply each vertical mask each one of the horizontally masked versions of the large matrix `(⊂⍺)∊` check if the left argument matrix is member thereof [Answer] ## Jelly, ~~12~~ 10 bytes *Thanks @Dennis for -2 bytes* ``` ZŒP ÇÇ€;/i ``` Nearly the same algorithm as @isaacg, except we transpose the matrix before taking subsets. ``` ZŒP Helper link. Input: z Z Transpose z ZŒP All subsets of columns of z. ÇÇ€;/i Main link. Input: B, A. B is a list of rows. Ç Call the helper link on B. This is the subsequences of columns of A. Ç€ Call the helper link on each column-subsequence. Now we have a list of lists of submatrices of B. ;/ Flatten that once. The list of submatrices of B. i then get the 1-based index of A in that list. If A is not in the list, returns 0. ``` Try it [here](http://jelly.tryitonline.net/#code=WsWSUArDh8OH4oKsOy9p&input=&args=W1sxMzYsIDI1MiwgMjEwLCAxOTYsIDc5LCAyMjJdLCBbMjIyLCA3OSwgMTk2LCAyMTAsIDI1MiwgMTM2XSwgWzI1MiwgMTM2LCAyNTIsIDEzNiwgMjUyLCAxMzZdLCBbMTgwLCAxMzYsIDU2LCAyNTIsIDE1OCwgMjIyXV0+W1sxMzYsIDE5Nl0sIFsyNTIsIDEzNl1d). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ⊇z⊇z ``` [Try it online!](https://tio.run/##nVLNTsMwDH6VqOeCGjdp0ws8SNXDQPwcJiEN0ARjF5BgcOItuCKkXTjyJuuLFNtx0hTBBWlV7M@f7c/2jhaz4/Ob@cUZDKtlpvYOVLY8XPWP7/39w267@froN2/Z1eL6ZD@7I/N0Nr9Ee737fF7vtq9D//J0S98wtKptW911ueKH3@BD9E2TK4BAq@tcMWSMwJ4GgL62wjLs4AdEMrEWIgiQQy@Zns@4QEIoGSgZKMekkcTZvq7RHLWFaC9QHnEbEktobE/FyEF9KK8iEzkuV01UklDqH5So@88a/2mUVA/suFQMVJxsHW3SyYC/4GlnXhbIsmO7AMoLaU6MJeImVSSHKdM0PI7xkOVL0QxCt/zT42RWRrbhkDZWKys6GM8ElvqUlYihCEOgC@bgYfg/6VUBeJ8DTIn5Sa0Rnca1KwS1MeJ3Ou6HfK19N026ddgTMwnSrmEOSsEVOIo6bzPIYU@0LtZJ0lPLxwXUTcgEKkSHVt03 "Brachylog – Try It Online") Takes matrix B through the input variable and matrix A through the output variable, and outputs through success or failure. This is pretty much just the Pyth solution, except the input is more implicit and there's no explicit generation or membership checking for the powersets. ``` B ⊇ has a sublist z which transposed ⊇ has a sublist z which transposed is A. ``` [Answer] # Mathematica, 40 ~~65~~ bytes ``` !FreeQ[s[# ]&/@(s=Subsets)@#2,# ]& ``` Explanation: See one of the other answers -- it looks like they all did the same thing. [Answer] ## Haskell, 66 bytes ``` import Data.List t=transpose s=subsequences (.((s.t=<<).s)).elem.t ``` Usage example: `( (.((s.t=<<).s)).elem.t ) [[149, 221]] [[177, 149, 44, 221]]` -> `True`. A non-pointfree version is ``` f a b = elem(transpose a) $ (subsequences.transpose=<<) $ subsequences b subsequences b -- make all subsequences of b, i.e. all -- all combinations of rows removed (subsequences.transpose=<<) -- transpose each such sub-matrix and -- remove rows again. Concatenate into a -- single list elem(transpose a) -- check if the transposition of a is in -- the list ``` [Answer] # Python + NumPy, ~~176~~ 173 bytes ``` from itertools import* from numpy import* def f(A,B): r,c=A.shape R,C=B.shape S=combinations print any([all(B[ix_(i,j)]==A)for i in S(range(R),r)for j in S(range(C),c)]) ``` ]
[Question] [ [Wordle](https://en.wikipedia.org/wiki/Wordle_(video_game)) is a [daily online word game](https://www.powerlanguage.co.uk/wordle/) that has received [considerable attention recently](https://www.nytimes.com/2022/01/03/technology/wordle-word-game-creator.html). # The Game The object is to guess a secret word in the fewest attempts. Consider the following instance of the game: ![](https://i.stack.imgur.com/3PtA4m.png) The secret word is `rebus`, and the player's first guess was `arise`. The letters `r`, `s`, and `e` are displayed in yellow to indicate that these letters appear in the secret word, but not at these locations. Meanwhile, the letters in gray do not appear in the secret word at all. The player uses this information to formulate a second guess: `route`. Here, the `r` appears in green, indicating that `r` appears in the secret word at this location. Notice that each guess is an English word. A comment on duplicated letters: If the first guess above were `river`, then the first `r` would appear in green, but the second `r` would appear in gray. In general, the duplicated letters are only highlighted if they are similarly duplicated in the solution, and letters appear in green whenever possible. As another example, suppose the secret is `inane` and we guess `nanny`. Then our first `n` will be marked in yellow, the second in gray, and the third in green. In this case, only two of our three `n`s are highlighted since the secret only has two `n`s. # The Challenge In this challenge, you will write code that plays Wordle as well as possible. The following link contains a curated list of 2315 common 5-letter words: [words.txt](https://www.dropbox.com/s/p83p1ueoq053xog/words.txt?dl=0) Notably, every Wordle solution to date appears on this list, and I suspect future solutions will, too. Your code will play Wordle by iteratively selecting words from the above `.txt` file and receiving Wordle-style feedback on which letters appear in the secret word. To evaluate your code, play this game 2315 times (each time using a different secret word from the above `.txt` file), and record the number of guesses it took to win. (While the official game terminates after six guesses, in this challenge, you may take arbitrarily many guesses.) In the end, your score will be the histogram of the number of guesses required, arranged in a tuple. For example, `(1,1000,900,414)` is a 4-tuple that indicates that the code solved every word in only 4 guesses, with 414 words requiring all 4 guesses, 900 taking only 3, 1000 taking only 2, and one word being identified after a single guess. Your code must be deterministic (i.e., your first guess will be fixed), and so the first entry of your score tuple will necessarily be `1`. A comment on implementation: There are a few ways to organize things (and to encourage participation, I don't want to impose any one way), but one approach is to write three programs: the game, the player, and the evaluator. The game receives a secret and a guess (both from words.txt) and outputs Wordle-style feedback. The player interacts with the game for some fixed secret word. The evaluator makes the player play the game for each secret word from words.txt. (One might use submissions from [Build a Mastermind engine](https://codegolf.stackexchange.com/questions/12486/build-a-mastermind-engine) to write the game program, but for this challenge, the interesting program is the player.) # The Winner Scores will be compared in [lexicographic order](https://en.wikipedia.org/wiki/Lexicographic_order). That is, shorter tuples are better, and tuples of the same size are first compared in the last entry, then second-to-last entry, etc. For example: `(1,1000,900,414)` < `(1,1000,899,415)` < `(1,999,900,415)` < `(1,998,900,415,1)` Lowest score wins. [Answer] # [Python 3](https://docs.python.org/3/), (1, 149, 945, 1118, 102) ``` from collections import Counter # history: a list of tuple of (guess, feedback) # feedback: a list of length 5, each element can be MISS, CLOSE, or MATCH def play(history): # Hard coded first guess turn = len(history) + 1 if turn == 1: return 'trace' # When there are few words left remaining_words = [word for word in WORDS if all(get_feedback(guess, word) == feedback for guess, feedback in history)] if len(remaining_words) <= 2: return remaining_words[0] # Hardcoded hard case if turn == 3 and history == [('trace', [MISS, CLOSE, MISS, MISS, CLOSE]), ('risen', [CLOSE, MISS, MISS, MATCH, MISS])]: return 'howdy' guess_list = WORDS if turn > 2 and len(remaining_words) < 100 else remaining_words return find_best_guest(guess_list, remaining_words) def find_best_guest(guess_list, secret_list): R = [] secret_set = set(secret_list) for guess in guess_list: c = Counter([tuple(get_feedback(guess, secret)) for secret in secret_list]) R.append([guess, len(c), guess in secret_set, -max(c.values())]) best_guess = max(R, key=lambda t:t[1:])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vHj0chvxr@W6yVQSxDZCp2dT3C3345/MmUI2aLpQ6h9U@EhzgPMpz9Fz7K8PB3EbJd/tjswPZq/u@@HL53djh@xembIf2ytP6jncaX2CvdY171g/RVHNSKF5mh/xjOaIf9U2pKD8fHmIMYNkeZX//TMo93hu7FavvM89DfLPTfS3vVnL5Cy9AfJw/HL1xqelk3UsaneSVjLukfvn0aLvb23pvtNJmhflM/vP3m6GH8quinBB@@@qgTtNj@TvThKObp@ChxUon3/fdLn46fV3j/9klUY/cTvNcJ9XjMVzcfc@FI@th/DPXtNyzow9s@j63/hci7VyJPg0hpPkcxPf7r46dVUVoPeLjb2A9fSYKn4avjz9vHV7edD/fgd/L3I34C9lfDd8mOYiEPoxwNjznZL0mG0k5iSutPwLLz8PnIUedimf6vMW9I/kn6mBOSRH@Z9V733w7vjqq/au6/D19/deSng/izAl/39CA1@0d6QrOT5JMkfKWDHl7rg09L@BDXJsyS4J@rgEN0@jB/5EpHxDFv@q@WiJHwg/4gba/6h9dT5h1myPH3F5/mCf7/BcqiomFrjp/Znb4U/bmJUui9WId/kcF@94T/Hvv8GWUvEl3cf7V4@GJ4eBV7JO8V/NlPEEP@6fPNpIfStqdX6vjh81@05Wno31wfmum9zJqPv/j13T4Hft9/AaX/SOxwuLM@TXuVeZSKcQL8m3b68eLn4Qh8Qk5Qlk@vZscTJ/n9h4OZzVv@aLBm9NkwfPYkfz77sn/hgtSPf7dsPs09Vuu3w9evq4PCRD1//HktUDEk@@UPEP/xz99@9/0P//k/fzh@PfqzYzF@9kYzxUQ4VsIT4x4ff/rp/wA) # Big idea Each time, I pick the guess from the list of remaining words (words matching all previous guesses), such that the guess maximize the number of possible outcomes. For example, at the start, we guess "trace". This splits the possible secrets into 150 groups, only one of which is possible based on the feedback. For the second guess, if we guess a word from that group, then there is 1 universe where we guess correctly. Thus in total, we have 150 universes where we guess correctly within the first 2 turns. By maximizing the number of groups each turn, we can make sure that there are more universes where we guess correctly early on. Following the naive strategy above, the result is `(1, 149, 1044, 904, 178, 31, 7, 1)`. If we score by lexicographical order from left to right, without caring about the length of the tuple, then this is the largest tuple possible. Heuristically, this is good since if the left entries of the tuple are as large as possible, then the right most entries will be small. However, because the most important criteria is the length of the tuple, I have to tweak this algorithm a bit to get rid of all cases that have >5 turns. # Optimization * If we have too few remaining words, then we might have to guess a word outside of those, to get the best split. Specifically, I allow selecting from outside if we're at the 3rd guess (or after) and there are less than 100 remaining words. * I brute forced search a some hard subtrees (e.g. 'trace' -> 'risen') to get the worst case at most 5 guesses. [Answer] # [Python 3](https://docs.python.org/3/), [1, 49, 871, 1354, 40] **Idea** 1. Use Knuth's minimax algorithm for Mastermind as default strategy. That is, minimize the number of remaining words for worst case group. 2. Find good starting words. 'alter', 'cater', 'close', 'crate', 'crone', 'lance', 'react', 'slant', 'stole', 'trace' are some of the good words (best 10 in my opinion). 'trace' and 'crate' score [1, x, x, x, 9x, 1] and 'alter', 'cater', 'trace' words score [1, x, x, x, 100]. Other words have 110 5th guess or less. (All using default strategy) 3. Do this recursively. * For each nth word, for each worst case group which results in at least one 5th guess, try every single word and find 10 best word that minimizes number of 5th guess. For example, first guess 'lance' and feedback CLOSE, CLOSE, MISS, MISS, MATCH leaves 2 5th guesses using second move from default strategy 'blast'. One can find that using either 'sight', 'smart', 'sharp', or 'fight' reduces number of 5th guess to 1 and one can recursively continue from there. ``` from collections import Counter hard_codes = {(): 'lance', (0, 1, 0, 0, 0): 'sport', (1, 1, 0, 0, 2): 'sight', (0, 2, 0, 0, 0): 'storm', (0, 2, 0, 0, 1): 'straw', (0, 0, 0, 0, 1): 'posit', (0, 0, 0, 0, 1, 0, 0, 0, 0, 0): 'defer', (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1): 'berry', (0, 0, 0, 0, 1, 0, 0, 0, 0, 1): 'deter', (0, 0, 0, 0, 1, 0, 2, 0, 0, 0): 'rowdy', (0, 0, 0, 0, 1, 0, 0, 0, 1, 0): 'drier', (0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 2): 'fiber', (0, 0, 0, 0, 1, 0, 0, 1, 0, 0): 'sever', (0, 0, 1, 0, 1): 'sewer', (1, 0, 0, 0, 1, 0, 0, 0, 2, 2): 'disco', (0, 0, 0, 0, 0): 'frost', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0): 'pudgy', (0, 0, 0, 0, 0, 0, 0, 1, 0, 0): 'buddy', (0, 0, 0, 0, 0, 0, 0, 2, 0, 0): 'woody', (0, 0, 0, 0, 0, 0, 2, 2, 0, 0): 'buddy', (0, 0, 0, 0, 0, 0, 0, 0, 1, 0): 'mushy', (1, 0, 0, 0, 0): 'still', (1, 0, 0, 0, 0, 0, 0, 0, 1, 0): 'plumb', (1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0): 'flood', (1, 0, 0, 0, 0, 0, 0, 0, 2, 1): 'fudge', (0, 0, 0, 0, 2): 'first', (0, 0, 1, 0, 0): 'wrist', (0, 0, 1, 0, 0, 0, 0, 0, 0, 0): 'nymph'} # history: a list of feedbacks, flattened # feedback: a list of length 5, each element can be MISS, CLOSE, or MATCH def play(history, remaining_words): history = tuple(history) if history in hard_codes: return hard_codes[history] if len(remaining_words) <= 2: return remaining_words[0] key = lambda g: max(Counter(tuple(get_feedback(g, c)) for c in remaining_words).values()) return min(WORDS, key=key) ``` [Try it online!](https://tio.run/##nZ1NjyM5cobv9Svk9WHVRmE93cZcBu6DMV7DBmwvsLOAD4PBIpXJzKTEJDn8UEpl@Levg4r3VXVVq6tbA8xinyaD32QwGGSq4rnMwf/T3/7rP376afNx893Dj//5p5/@KPT@4b/@5S8//rvQh4fBjJvJlL@Oxgy7rj9sp2pyftxk0ydT3v3wsNmU7mC8CP/8b53L5pfNP2y@l9BkcnWlBbf8GTqGtLEb6zep85PZfn/JYLOxUkjL92f7y@bjR2Qu/9BYZnaJ3VzqhvBL0Rr8l1QNC3jsWxHG18Wkrhit83NRn@SG7H7Y9MEX6y9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q3K3V0rXdSLGEjnKf/5w/svz/5S3PfHX9P@1D6FSuV8eaSVMi6bV6Q@PFtS/Ctr5480ty/6AGtNR0ua/Nv/Aw "Python 3 – Try It Online") Some interesting results outside of code golf (they have larger word set for guessing and the strategy cannot be applied to this challenge): * Youtuber 3Blue1Brown [solves Wordle using information theory](https://www.youtube.com/watch?v=fRed0Xmc2Wg) and achieves a score of [0, 80, 1225, 965, 45]. * Jonathan Olson [solves Wordle with only 18 5th guess or worse](https://jonathanolson.net/experiments/optimal-wordle-solutions). [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html) ``` ┌─ ╵ 1 2 3 4 5 6 7 8 9 1 56 407 861 722 210 44 13 1 ┘ ``` The strategy is very basic, this just chooses the first word in the word lists that is still possible according to the previous results. I will improve on that later, but for now I just wanted to get the "infrastructure" up. ``` #!/usr/bin/env bqn # Judge takes the correct and word and a guess, and returns a pair of vectors # The first has 1's at green letters, the second one 1's at yellow letters Judge ← { word 𝕊 guess: wrong ← ¬correct ← word=guess misplaced ← (+`⊸×wrong)⊏0∾word(⊒∘⊢<·+˝=⌜)○(wrong⊸/)guess correct⋈misplaced } # Game takes a path to the word list, # plays every single word, and returns an histogram Game ← { 𝕊 file: words ← •FLines file 1↓˘⊒˜⊸≍≠¨⊔˜ {𝕩⊸Judge _Player words}¨ words } # The Player takes a monadic judge as its left operand and a word list as the right argument # It has to guess until it finds the right word and return its score ( Don't cheat ;) ) _Player ← { Ju _P words: score ← Ju attempt←⊑words ¬∧´⊑score ? 1+Ju _P words/˜(score≡Judge⟜attempt)¨ words ; 1 } •Show Game "words.txt" ``` This should be run in the same directory as the *words.txt* file. You can try a modified version with only 100 words online [here](https://mlochbaum.github.io/BQN/try.html#code=IyEvdXNyL2Jpbi9lbnYgYnFuCgojIEp1ZGdlIHRha2VzIHRoZSBjb3JyZWN0IGFuZCB3b3JkIGFuZCBhIGd1ZXNzLCBhbmQgcmV0dXJucyBhIHBhaXIgb2YgdmVjdG9ycwojIFRoZSBm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JvdGFiaG9yYWJpZGVhYmxlZGFib2RlYWJvcnRhYm91dGFib3ZlYWJ1c2VhYnlzc2Fjb3JuYWNyaWRhY3RvcmFjdXRlYWRhZ2VhZGFwdGFkZXB0YWRtaW5hZG1pdGFkb2JlYWRvcHRhZG9yZWFkb3JuYWR1bHRhZmZpeGFmaXJlYWZvb3RhZm91bGFmdGVyYWdhaW5hZ2FwZWFnYXRlYWdlbnRhZ2lsZWFnaW5nYWdsb3dhZ29ueWFnb3JhYWdyZWVhaGVhZGFpZGVyYWlzbGVhbGFybWFsYnVtYWxlcnRhbGdhZWFsaWJpYWxpZW5hbGlnbmFsaWtlYWxpdmVhbGxheWFsbGV5YWxsb3RhbGxvd2FsbG95YWxvZnRhbG9uZWFsb25nYWxvb2ZhbG91ZGFscGhhYWx0YXJhbHRlcmFtYXNzYW1hemVhbWJlcmFtYmxlYW1lbmRhbWlzc2FtaXR5YW1vbmdhbXBsZWFtcGx5YW11c2VhbmdlbGFuZ2VyYW5nbGVhbmdyeWFuZ3N0YW5pbWVhbmtsZWFubmV4YW5ub3lhbm51bGFub2RlYW50aWNhbnZpbGFvcnRhYXBhcnRhcGhpZGFwaW5nYXBuZWFhcHBsZWFwcGx5YXByb24i), the full program is a bit too much for the JS interpreter. [Answer] # Clojure, (1 59 1051 1166 38) ``` (def lookup { ;; turn 1 "" "stole", ;; turn 2 "*-*--" "prawn", "*----" "prank", "*--++" "spiel", "-+-+-" "final", "--+-*" "gourd", "*-*+-" "whoop", "*-*-*" "ranch", "-+*--" "truth", "++--+" "buyer", "+---*" "ranch", "--*+-" "dwarf", "--**-" "diner", "--*--" "droop", "-+++-" "total", "-+--*" "birch", "+--+-" "pubic", "*---*" "chirp", "---*+" "wordy", "-+-*-" "baggy", "---++" "rival", "-*--+" "utter", "-+-*+" "wound", "--+--" "hardy", "+-+-+" "verso", "*+--+" "sweep", "-++++" "motel", "*--+*" "smack", "+---+" "purer", "-+*+-" "graft", "+-+-*" "morph", "-+-+*" "earth", "*--*-" "ralph", "--*+*" "vegan", "---+*" "gland", "--*-+" "epoxy", "-++-+" "motor", "*+--*" "unzip", "**--*" "vigor", "-+---" "truth", "*+-+-" "split", "---+-" "brain", "*+*--" "churn", "**---" "prank", "+++--" "trash", "+--+*" "pulse", "---**" "aping", "*+---" "faith", "*--+-" "clink", "--+-+" "rocky", "-+*-*" "trove", "-++-*" "route", "++--*" "wrath", "+-*--" "rigid", "--++-" "local", "--+++" "mover", "+--++" "welsh", "**-*-" "still", "+-+--" "bacon", "*--**" "shale", "-+-++" "craft", "*--*+" "wimpy", "-+--+" "taint", "**--+" "drank", "----*" "guard", "+----" "champ", "--+*-" "dwarf", "***-*" "trunk", "***--" "murky", "----+" "cedar", "-----" "cramp", "---*-" "diary", "--*-*" "drank", "+-++-" "lousy", "-+-**" "blink", "++*--" "roost", "*-+--" "sonar", "+-*-*" "woman", "*-++-" "salvo", "++---" "dairy", "*---+" "preen", "-++--" "burnt", ;; turn 3 "----+-+--*" "unify" }) (defn pick-guess [words] (let [nwords (count words) candidates (if (> 3 nwords) words dict) comparator #(let [f (frequencies (for [word words] (game word %)))] (- (* 100 (apply max (vals f))) (count f) (if (some #{%} words) 1 0) (reduce (fn [a [k v]] (+ a (* (/ v nwords) (/ (Math/log (/ nwords v)) (Math/log 2))))) 0 f))) counts (into {} (map (juxt identity comparator) candidates))] (apply min-key counts candidates))) (defn player [blackbox] (loop [depth 1 history "" words dict] (let [guess (or (lookup history) (pick-guess words)) feedback (blackbox guess)] (println guess) (println feedback) (if (= feedback "*****") depth (recur (inc depth) (str history feedback) (filter #(= feedback (game % guess)) words)))))) ``` [Player](https://tio.run/##bZzdkuO4kUbv@ykUPTGOqmrX2mPfrcPrJ9gn6J0LSgJJlEiCgx@xVA4/@@53PkrdPY7tiTiBSoIgfhKJTACa05TeWg7/@3QO/WFL@VwOn7tjd7ocxBJghcdwg6mKY8piPCOfwllMTqfM09TMK5LmEm6lHLpTyouYo/KfKiWcGiWfu8Fc9dY5mHNcTN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Nbe@fCYVBYVm/f9NTzN738ZY7e2xuX14t/8OUCv833/I99ZAOhlzt8H1gp6O8/6x0NdFy4lxq9d/brHx5xJgK25v@P9k@HX37av/1XpQ4/PWwFY7grzlPixqKKfLq7qPeimdZf1Wsv8rtu97Vdve//vh5vUg2P@Y93u/TPSqd/0mPp9ENdPEyPYn7eJ5rsyt8OF69IWiv@yZh8He8@HZ6@dtH18PO90rtxePxxef5G855e//73RwW@LfVfzL5r8P@Pw/dato82N0Ciz1qtcJ@/7xJbhF1r7816NMRK63//ePJdgGn5tgUOJn72MNxDAmX8Pw) ## Strategy Good heuristic rules behind picking the best next guess have already been discussed in the answers by [Surculose Sputum](https://codegolf.stackexchange.com/a/241133/78274) and [didgogns](https://codegolf.stackexchange.com/a/242412/78274). However, any heuristics can still arrive quite far from the optimal solution, that's why it is always helpful to include some kind of more extensive evaluation of possible guesses, even if we don't undertake the daunting exercise of exhaustive search through all possible subtrees. In this solution instead of fixing problematic cases in the deeper branches of the guessing tree, I decided to add an extensive enumeration step early in the process. In essence, this algorithm uses 2 predefined guesses instead of 1: * For the 1st guess, the word `stole` was chosen as it produced the most promising results. * For the 2nd guess, a (semi-)exhaustive enumeration was run. For any possible feedback from the game after the 1st guess that still leaves more than 2 valid secret candidates, further simulation was run with each of the top 200 words by heuristic score, and those that produced the best results were encoded in the lookup table used to pick the guess. * 3rd & later guesses are normally picked using the heuristic. This procedure alone results in the overall score of `(1 59 1051 1164 40)`, which at the time of writing, ties the best answer for the number of 5-guesses, but gets an edge in 4-guesses. Then, I went further into some worse-case branches and found a better guess in the 3rd turn that saves another 2 points. Other such improvements are likely possible. ## Heuristic score Since the challenge asks to optimize for the worst case, the primary factor for picking the best guess should be the minimax - the least among the maximum numbers of remaining secrets in each group. For the tie breaker score, I tried throwing in a mix including: * The count of different possible feedbacks from a guess * An indicator, if the word is still valid as a guess itself * The information gain from the guess (as explained in [3Blue1Brown](https://www.youtube.com/watch?v=v68zYyaEmEA) video) However, the exact definition of the score that will yield better overall results at this stage becomes pretty much hit or miss, so that performing more exhaustive search seems like a more promising direction for potential further improvement. [Answer] # [JavaScript (Node.js)](https://nodejs.org) ## [ 1, 101, 650, 1000, 465, 87, 11 ] A simple algorithm computing the list of remaining possible words and picking either the first one if there are less than 3 of them, or the one located at a precomputed index otherwise. (This is therefore playing in 'hard mode'.) The precomputed values are based on a hash of the list of remaining words and were simply found with a naive random search running for a while. They are probably very far from optimal ones. ``` const GRAY = 0; const YELLOW = 1; const GREEN = 2; const LOOKUP = {'14143202':1,'26364370':2,'30190943':3,'38882992':23,'43995839':2,'46997544':2,'47100915':2,'58773399':2,'70621541':3,'76111564':0,'78629445':0,'83279074':4,'53c11c74':2100,'921bd960':36,'2528c69d':1,'7964d0cf':11,'2e48ad14':2,'8b3ca4cb':0,'79c8a291':121,'8cf4eed6':3,'67c21ff2':1,'bc7835a4':33,'26270c62':16,'5095e262':0,'6fc77853':90,'aa78d00f':2,'efd5ee03':13,'f7e85504':0,'9ed6869a':13,'2f28d552':2,'ebadec4c':9,'dd657502':1,'75e99b72':9,'9e4d1e39':1,'6b1ee6bc':0,'94847f8e':2,'d69854c6':1,'79f08c51':29,'975ea22e':5,'74a4f766':4,'93913d7d':1,'f5a80453':3,'834b3950':10,'d311f685':3,'cf69c214':0,'3c1bb448':1,'eea7d694':7,'67980f55':2,'5bc6e50f':1,'b6a74c7f':1,'41086a3f':5,'c42acaa3':5,'f1ed7962':19,'f013f6de':1,'e2c19ca8':6,'bd62ab41':2,'31850f4c':14,'a65e6c62':1,'d8d65610':0,'0b60b7a3':7,'377f178d':1,'bed253cc':2,'55417f48':21,'2a195973':2,'89b99ca0':0,'5734ec44':1,'d994dab6':6,'747ac68c':1,'5cbfb6df':4,'6d145f3f':9,'cd7cd6dd':4,'ef04be81':2,'4332f7de':4,'9d0bdd07':1,'dc12394d':9,'90ae0678':2,'c76b85f1':4,'ec06d2ca':2,'c1c8a84f':10,'e8c899d1':0,'cc022066':14,'48f50318':3,'cac2bc3a':3,'e25292bb':1,'48a08d77':5,'14db746d':1,'f086993f':0,'5ce89220':9,'f9ad9ada':1,'229f8965':0,'0c4905a7':0,'0302235f':0,'96f622f5':0,'54252eab':2,'0c8e25a6':3,'9286bc52':3,'d2d53386':2,'c8f8fb4e':166,'702bb5a4':16,'38cbb5d6':0,'4474aa82':18,'d96b3f5d':28,'30ec466d':4,'8796640a':2,'5ccf8034':4,'f397de6b':18,'40ba7a83':38,'85ee6b8a':2,'1ee95569':0,'e6881291':1,'165b616c':0,'bb9a5866':0,'79fbfdcf':27,'b43dee5f':2,'50f28e4b':197,'f2ba2523':23,'fdef66e9':1,'e53b6fb5':1,'d6d16e7d':15,'708ab8ab':13,'c1214176':1,'453b0ab9':1,'bf525f76':6,'9baaa801':12,'99a34529':3,'e8cdc21c':1,'a1d69531':3,'43cb5c4e':4,'f2cc4081':3,'4497f9dd':3,'2c4dd2f4':3,'7f76ec38':1,'216cf28f':6,'427af08e':1,'5565ea4a':3,'ab97f7e6':5,'d621e228':2,'ac239f20':6,'ab593aad':1,'e1a6be75':0,'07a70237':1,'e5849d40':1,'0771e66f':0,'f0b2ccad':3,'5263f0b5':4,'dc007dc6':1,'8061bddc':2,'1b738423':7,'9c3c3eb4':3,'2c207b38':3,'1e560e0c':1,'9d483c9c':1,'a54ad297':3,'adf1e213':1,'8ece546f':0,'2868ded4':1,'0be47967':2,'76c48ab0':1,'ec5a2986':5,'08f02724':4,'2f1e8fe0':13,'61b01746':2,'a945af43':2,'b3298621':0,'c902c85d':0,'59b4b3a6':0,'65adc148':7,'da2d4f4f':1,'bdabc7b7':1,'363a673f':78,'57df5665':21,'4dff9da8':2,'0e86ae9c':7,'6c77953e':1,'714ca992':2,'32f55d3c':0,'8f730c78':4,'bef4237c':9,'0cd58e64':1,'9782b612':1,'46e616b4':5,'d8aea010':1,'9928cb50':12,'49a9a502':0,'899b630b':2,'e62dc0ee':0,'5e422bc1':1,'028f178c':1,'0d18106f':1,'73318b3f':1,'f99ae1c9':34,'e1cd8425':4,'4dfed81f':3,'add3dd22':10,'3b3db49a':0,'f1034ad7':2,'4a5046f3':1,'7ac5ce28':2,'28536ff5':0,'75ea6e53':1,'63fea0b1':2,'ab09cc25':2,'d6ceba64':2,'bfc4bed7':3,'960d9151':0,'cd868422':3,'11a4d91c':1,'83a7119c':0,'6c552bd4':0,'77095d30':10,'c8bcfcac':2,'ba21e593':0,'3d336693':5,'fba36a94':2,'10f9f1ed':2,'6204e786':0,'6e07f888':2,'2bb3482a':10,'d686a716':2,'e31d35d2':2,'dce35a86':0,'78d964ba':1,'851c0f3b':1,'37f4f3b4':2,'fe75e788':1,'93d09506':5,'604107e8':0,'44c077ae':13,'0f7f452d':1,'7c9bce8b':4,'7e6687c7':2,'7e58e0a8':5,'7dbabf3c':0,'65aec92b':74,'5b0b56f2':4,'ce548f7e':1,'f37040ba':0,'61a3de73':0,'6e752063':1,'f70d8eb1':0,'3855ec7a':4,'ec9b1d60':1,'a9de0559':2,'5db0cc60':3,'09ac011b':1,'06f2bd54':19,'c0abb288':1,'7740b151':8,'a2e3e28b':0,'f4c7948d':2,'dd7e56a0':2,'257e38eb':2,'8ec556e6':2,'fad4a8aa':2,'007da174':3,'48a5ee80':8,'daf0805d':1,'2c0bbd90':22,'a68704dd':2,'2edc16a2':0,'bdd7d751':1,'12fa8a9c':2,'bd6c82c1':5,'daa03ebb':2,'14a007cc':3,'b057a058':3,'fe2e6048':3,'930b8a67':2,'e6021a93':0,'715f9f50':2,'3bb3f9c8':2,'314ae620':2,'bf9d0ff9':3,'d6f78470':3,'6ffd5525':0,'bfa4d989':7,'2fcb4ed3':1,'8dff3605':2,'cc0e1441':2,'510e2239':2,'932cad71':4,'8a2babae':7,'b5069042':2,'870facb1':2,'81dc1545':2,'a366065a':2,'7f92a451':1,'17e04242':1,'00f397da':1,'5c792244':0,'d0bb4351':0,'98ffa283':3,'78bac9e6':2,'14f2bafd':0,'d086c2ee':2,'08a38507':0,'5fd0ea1d':3,'2ba1913e':0,'117654e7':1,'f5eea614':7,'b811e17b':1,'69dda9de':3,'46b94977':2,'7b766732':3,'af195935':2,'b1eb20d4':3,'8b66476e':2,'aa533625':0,'be9f3907':0,'743ce282':3,'02a97dc8':4,'42bec4ec':0,'5f8be41b':2,'4e053217':17,'efaf99ff':2,'558976a8':3,'f61dff94':2,'13784ef6':0,'05354011':0,'382e4364':1,'6f20b790':1,'e1b754bf':2,'c979fdaf':1,'ddd9b414':1,'2a2dddfc':3,'7f585610':2,'dc70293f':12,'7f328e23':2,'bbc51714':4,'d970cf9e':1,'f1db083f':3,'c698465c':1,'d67bb6a4':2,'6bf5c971':0,'a5dad7ee':3,'c20230d7':2,'6c69bcc4':2,'ddaa91fc':0,'aceffaa8':3,'5ac4f937':0,'fb589434':0,'e3f3c1d7':2,'062698f6':0,'67cff0e7':0,'2c367774':1,'5f163080':0,'c526fc35':0,'b77cce91':0,'f69aa500':2,'9f5bb9b2':1,'88c58554':2,'4524f59e':1,'d8d3541e':1,'c007c12f':0,'71a48e89':4,'897fcd24':0,'8f6a94fe':0,'4ab727d1':3,'95d7089e':0,'44b3c427':4,'689a27db':2,'42f43571':3,'b02a73cd':0,'c4310e8c':1,'e605072f':5,'cea8ea81':1,'072fdcc0':1,'bb4c095c':1,'bb6830d5':2,'ae22f8fb':1,'ffa4e084':1,'79aec494':2,'db71d0dc':2,'8f481b7a':4,'5e30001f':1,'0e114e8c':1,'6ecfeac0':0,'da3c8846':1,'bb77b1b0':1,'3d8d6830':3,'063be66d':0,'b07584b9':1,'e6aa8602':2,'00ee7c82':4,'8a0b3a9b':1,'fff50a02':2,'9522070e':2,'9fb93302':2,'f5c487bb':1,'f3becf6c':2,'7acd7d34':1,'e39973c9':0,'48a2f6d7':10,'c556b389':0,'aae28d8b':2,'26394f7b':2,'6987fcb5':1,'3c8b70b5':1,'0ec76191':3,'bede1e43':3,'e9e75a90':2,'93ecaaaf':7,'9c85d484':0,'6cfc5c54':4,'0e956f0c':0,'e0ee2ae6':2,'ae37d2b7':6,'e7356cc4':1,'191bee62':4,'34ac52df':2,'edf40c22':1,'a3c46eae':1,'07c59ea8':0,'cebc4b79':2,'b83825b1':4,'967d3108':2,'52674dd2':1,'ad289b28':0,'671ce983':5,'3f340614':1,'99027f41':4,'96da67b7':0,'4a8871e3':0}; let wordList = require('fs').readFileSync(0).toString().split(' '); let stat = []; wordList.forEach(secret => { let hist = solve(word => guess(word, secret)), n = hist.length; console.log('[' + secret + '] ' + hist.join(' ')); stat[n] = -~stat[n]; }); console.log(stat.slice(1)); function solve(blackBox) { let list = [...wordList], hist = [], w, j; for(j = 1;; j++) { let key = list.join(''), md5 = require('crypto').createHash('md5').update(key).digest('hex').slice(0, 8); w = list[list.length < 3 ? 0 : LOOKUP[md5]]; hist.push(w); let res = blackBox(w); if(res.every(c => c == GREEN)) { break; } list = filter(list, w, res); } return hist; } function filter(list, w, res) { let cnt = {}; let exact = {}; res.map((c, i) => c == GRAY ? (cnt[w[i]] = ~~cnt[w[i]], exact[w[i]] = true) : cnt[w[i]] = -~cnt[w[i]]); let pattern = RegExp(res.map((c, i) => c == GREEN ? w[i] : '[^' + w[i] + ']').join('')); let newList = list.filter(word => pattern.test(word)); res.forEach((_, i) => { if(cnt[w[i]] !== undefined) { newList = newList.filter(word => { let n = [...word].reduce((p, c) => p += c == w[i], 0); return exact[w[i]] ? n == cnt[w[i]] : n >= cnt[w[i]]; }); } }); return newList; } function guess(word, secret) { let misplaced = {}; [...secret].forEach((c, i) => c != word[i] ? misplaced[c] = -~misplaced[c] : 0); return [...word].map((c, i) => c == secret[i] ? GREEN : misplaced[c] ? (misplaced[c]--, YELLOW) : GRAY); } ``` [Try it online!](https://tio.run/##dXxrr@S4td33@RV1P3U33G7o/ZjJXOMGcG6AGHHgiyAwGpOAosgqnSOJsh5Vp3pg/3VnrUX19DhwBo0F1ia1SW7uJ6UzL@ZuNrsOy/7bOfTu7@@OzV22fR3s/u6Hv9swb/vl3//0b3@@4L8fL8kP30XSn3//hz/88X@RlH4l/fuffv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@@hHvzjGSBP/KGb4QcKiC9A3gE@5Akfuvd76A3Ug39iAeRKHvKBD71Feugt0kO1z0M3xkB4oYf@vgC4EXkL8VBF81DNAkTV9tDXwkCsE4gq7yGP94CX43jGa6DG88QfqjKAK8fzSw8g13kLGkNbe8jjPQbe6D5U1wPh64CwoIe@CHrIjz1UCzwGvuV5qCJ46IYQyL2orgeqV3LQW8KHPNgj8M0vUG2@HQByPNIBtb889bdiQs6oPPOh98tE/R0v16NvaB/KPx/6bvYhfwVkr757AYrCO6WHvq4Hxjb3rvs0oNqH2sztnwhW@@WpN4BPvfV7au/PwDFP5bpfHG35i2LQF/rk/ws "JavaScript (Node.js) – Try It Online") [Answer] # Python **[1, 108, 696, 952, 436, 101, 17, 4]** Of course, the fact that there are 8 elements sucks, but I'll update the answer as I improve my algorithm. Complete code, including scoring: ``` # Wordle challenge. with open('words.txt', 'r') as wordsFile: words = wordsFile.read().split('\n') resultsDict = {} # dictionary format is easier, but then it will be converted to a tuple. def best(pool): # it's a function that determines the word with the "most common" letters. best_word = '' for _ in range(5): best_word += max('abcdefghijklmnopqrstuvwxyz', key=lambda letter: len([w for w in pool if w.startswith(best_word + letter)])) return best_word def get_feedback(guess, wo): # it's a function to give feedback. return [ 'LET' * (guessed in wo) + 'POS' * (guessed in wo and guessed == actual) for guessed, actual in zip(guess, wo) ] for word in words: guesses = 0 cur_words = words while True: cur_guess = best(cur_words) # guess the best word. feedback = get_feedback(cur_guess, word) # "word" is only accessed here. Nowhere else. guesses += 1 if all([x == 'LETPOS' for x in feedback]): # mission accomplished break # set "cur_words" to a new set based on the feedback. cur_words = [ w for w in cur_words if all([w[i] == cur_guess[i] for i in range(5) if feedback[i] == 'LETPOS']) and all([cur_guess[i] in w and w[i] != cur_guess[i] for i in range(5) if feedback[i] == 'LET']) and all([cur_guess[i] not in w for i in range(5) if feedback[i] == '']) ] if resultsDict.get(guesses): resultsDict[guesses] += 1 else: resultsDict[guesses] = 1 print(resultsDict, words.index(word)) resultsTuple = [resultsDict.get(i) or 0 for i in range(1, max(resultsDict.keys()) + 1)] print(resultsTuple) ``` All I do here is pick the word with the most common letters each time. For instance, if there are 5 words: ``` abcde abcfg aedri bbbbb cdegh ``` It goes through the first letters: a, a, a, b, and c. It sees that a is the most common, so it starts with a. Its guess so far is: a Same for the second letters: as it has isolated a as the first letter, it only considers b, b, and e. (of the first three words). It sees that b is more common, so it adds b. Its guess so far is: ab Same for third letters: abc Fourth letter: both d and f are equally common, so in picking the maximum it just chooses the first one: d Now the only option is e, so its guess is **abcde**. ]
[Question] [ You are given 3 non negative numbers: \$x\$, \$y\$ and \$z\$, and must minimize the number of digits (non negative) inserted at any place in the numbers \$x\$, \$y\$, or \$z\$ to make $$x + y = z$$ (a clarification: you can add any non negative digit any number of time at any place ) (you can assume that \$x\$, \$y\$, \$z\$ and your final integers after insertion won't overflow the integer limit in your language) Example: $$x=1, y=10, z=30$$ $$1 + 10 = 30 $$ $$1(0) +1(2)0 = (1)30$$ i.e \$10+120 = 130\$ The minimum insertions is 3 here. $$x=1 , y=1 , z=3$$ $$1 + 1 = 3 $$ $$(3)1 + 1 = 3(2) \;\text{or}\; 1 + 1(2) = (1)3$$ Here, the answer is 2. $$x=11 , y=11 , z=33$$ $$11 + 11 = 33$$ $$11(2) + 1(2)1 = (2)33 \;\text{or}\; 1(2)1 + (2)11 = 33(2)$$ Here, the answer is 3. $$x=3 , y=0 , z=0$$ $$3 + 0 = 0$$ $$3 + 0 = 0(3)$$ Here, the answer is 1,because as stated in earlier clarification, you can add any non negative digit any number of time at any place, so there can be leading zeroes too. There can be multiple ways for same number of minimal insertion. If possible while answering please write a short explanation of what you did. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes per language wins. [Answer] # JavaScript (ES6), 164 bytes *Thanks to @l4m2 for identifying several bugs and suggesting the alternate version below* ``` (x,y,z)=>(F=k=>(g=(k,s=z+`-${x}-`+y,n=9)=>eval(s.replace(/\d+/g,'"$&"'))?k&&[...s,0].some((_,i)=>g(k-1,s.slice(0,i)+n+s.slice(i)))||n&&g(k,s,n-1):1)(k)?k:F(k+1))(0) ``` [Try it online!](https://tio.run/##dY7BTsMwDIbvPEU1TZmtOFminDopcNtLAGJVl0UlIZ0WNG1jPHtJQXDpONiS/fn/f782xya3h27/LlK/dcPODnCiM13Q3sPahtK9hUDZXvhGzD9On2LDz5RsXQ7csYmQ5cHtY9M6WD5t@dLTYjZnswXiQ2DsUUqZST3L3L85gBfqisxDEJqyzLErKlV2PPHfsUPE6zUx5sdUSkLjSiOEYrdaQ@AaERQObZ9yH52MvYcdVJoqragyCvFuir7LTJAeVaWMua2qR9N/UaWnqP7J0vUUmYLUzTf@UMkavgA "JavaScript (Node.js) – Try It Online") ### How? We build the string `s` with the pattern `z-x-y` and recursively attempt to insert `k` additional digits until `eval(s)` is 0. ### Commented ``` (x, y, z) => ( // main function taking (x, y, z) F = k => ( // F is a recursive function taking a counter k g = ( // g is a recursive function taking: k, // k = number of digits to insert s = z + `-${x}-` + y, // s = expression string "z-x-y" n = 9 // n = next digit to insert ) => // eval(s.replace( // if the expression does not evaluate to 0: /\d+/g, '"$&"' // (add quotes to prevent any number with a )) ? // leading 0 to be parsed as octal) k && // if k is not equal to 0, [...s, 0].some((_, i) => // for each position i from 0 to len(s): g( // do a recursive call to g: k - 1, // decrement k s.slice(0, i) + n + // insert n at position i s.slice(i) // (and implicitly restart with n = 9) ) // end of recursive call ) || // end of some() n && // if n is not equal to 0: g(k, s, n - 1) // do a recursive call to g with n - 1 : // else: 1 // success )(k) // initial call to g with the current value of k ? // if successful: k // return k : // else: F(k + 1) // try again with k + 1 )(0) // initial call to F with k = 0 ``` --- # JavaScript (Node.js), 158 bytes *A slower but 6 bytes shorter variant suggested by @l4m2* ``` (x,y,z)=>(F=k=>(g=(k,s=z+`-${x}-`+y,i=~s.length*-10)=>k*i--?g(k-1,s.slice(0,t=i/10)+i%10+s.slice(t))|g(k,s,i):!eval(s.replace(/\d+/g,'"$&"')))(k)?k:F(k+1))(0) ``` [Try it online!](https://tio.run/##dc7NbsIwDADg@56iQwxs4rSJcipSxo2n2IGqhCxL1CJSIWA/r96lm@BSODiS/fknH9WxivXB7TvetFvT73QPJzrTBfUrrLVPr9XgKeoL2/Dp5@mbb9iZnP6JeTCN7d4XXIrU7BeO85UFzyXFPAZXGxDUaVckZu5FCnYtd4hfdthJDpfP5lgFiPnB7EOVsHjbssLSfDKdTeaICB5XfrkGz2RKBPZ128Q2mDy0FnaQScqkoEwJxKcx/YUakRymUih1f6oclj6kTI6p/L8lyzGpROLuN26UbvW/ "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 161 ~~257~~ bytes ``` def g(L): k=0;F="-%s %s %s"%L, while all(sum(map(int,X.split()))for X in F):k+=1;F=[x[:y/10+1]+`y%10`+x[y/10+1:]for x in F for y in range(10*len(x))] return k ``` [Try it online!](https://tio.run/##hZBRa8IwFIXf8yuCUEzW65a07sFKHvYwYeDehRiw1KjFGkubbu2v79JU3d4WLuR8l5Obwy07e7qaqO/3@oCPZE0ThM@CLVdiMgtq7GsSrAHh71NeaJwWBambC7mkJcmNhc1zXRa5JZTSw7XCG5wbvKLJORTczZCtTLoXzkKuwl0XcLYLWzk2EjX4W@/Hg@wGWaXmqAlnT4U2pKVUIVxp21QGn3ura1sLiYjkwCNXCiIKA7I5cHh9IHAGMVMQj@iYQxzfOYII5grYzbsAroB7iIEBu4N/xVn0ywtYeCtSCA2Bc/OVFnBtrLuG7D6fW1@aDR1xJMQ7pBsxeiV7KK4oRbis3ArJdPbv2ZoPUzZWBPVya97bUmdW70d6y2zjfvP6M7XZyclpQP6GgzHRjYQYkdL@Bw) *-1 byte thanks to @ovs!* Takes in a tuple of 3 integers `L`, in order `(z, x, y)`. **How it works**: `F` stores all insertions with `k` digits added (in the form "-z x y"). At each stage, we check if string `X` in `F` splits to three integers that satisfy the equality by evaluating the sum of (the integers in) `X.split()`. When going to the next stage, the `+1` in the slicing prevents a digit from being inserted before the minus sign. The `int` conversion is to prevent any leading zero from being interpreted as an octal integer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞.ΔI„+-S.ιSÐм.ø.œJs>ù9Ýyãδ.ιJ.E_à ``` Extremely slow brute-force approach, so it's barely unable to complete any of the test cases resulting in 3.. [Try it online](https://tio.run/##AUIAvf9vc2FiaWX//@KIni7OlEnigJ4rLVMuzrlTw5DQvC7DuC7Fk0pzPsO5OcOdecOjzrQuzrlKLkVfw6D//1sxLDEsM10). Here a slightly faster but incorrect approach to at least show the three test cases work as intended: [Try it online](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/x91zNM7N@XQukcN87R1g/XO7Qw@vFXv8A69o5O9iu0O77Q8PLfy8OJzW4ASXnqu8YcX/K/V@R8dbahjaKBjbBCrowBi6hiDGUAWkGkcGwsA). The difference is the `õ.ø`, which is `Ðм.ø` in the full program. The `õ.ø` surround the list of characters with a single leading/trailing empty string, whereas the `Ðм.ø` surrounds it with multiple empty leading/trailing strings (up to the amount of digits in the total input, plus 2 for the `+-`). **Explanation:** ``` ∞.Δ # Find the first positive integer which is truthy for: I # Push the input-list [x,y,z] „+-S # Push character-pair ["+","-"] .ι # Interleave it with the input-list # i.e. [1,10,30] → [1,"+",10,"-",30] S # Convert it to a flattened list of characters # → [1,"+",1,0,"-",3,0] Ð # Triplicate this list м # Remove all characters in this list from the list, # leaving a list of empty strings of the same size # i.e. [1,"+",1,0,"-",3,0] → ["","","","","","",""] .ø # Surround the earlier list with these empty strings as # leading/trailing items # → ["","","","","","","",1,"+",1,0,"-",3,0,"","","","","","",""] ``` The examples in the rest of the explanation uses a single empty leading/trailing string, since it's otherwise a bit too verbose. The actual functionality remains the same. ``` .œ # Get all partitions of this list # → [[[""],["1"],["+"],["1"],["0"],["-"],["3"],["0"],[""]], # [[""],["1"],["+"],["1"],["0"],["-"],["3"],["0", ""]], # ..., # [["","1","+","1","0","-","3","0",""]]] J # Join each inner-most list together to a string # → [["","1","+","1","0","-","3","0",""], # ["","1","+","1","0","-","3","0"], # ..., # ["1+10-30"]] s # Swap so the current number is at the top of the stack > # Increase it by 1 # i.e. 3 → 4 ù # Only keep the partitions of that size # → [["","1","+","10-30"], # ["","1","+1","0-30"], # ..., # ["1+10-","3","0",""]] 9Ý # Push list [0,1,2,3,4,5,6,7,8,9] yã # Get the current number's cartesian product of this list # i.e. 3 → [[0,0,0], [0,0,1], ..., [9,9,9]] δ # Apply on the two lists double-vectorized: .ι # Interleave the lists # → [[["",0,"1",0,"+",0,"10-30"],["",0,"1",0,"+",1,"10-30"],...], # [["",0,"1",0,"+1",0,"0-30"],["",0,"1",0,"+1",1,"0-30"],...], # ..., # [...,["1+10-",9,"3",9,"0",9,""]]] J # Join every inner-most list to a string # → [["010+010-30","010+110-30",...], # ["010+100-30","010+110-30",...], # ..., # [...,"1+10-93909"]] .E # Evaluate each as Python-code # → [[-10,90,...], # [80,90,...], # ..., # [...,-93898]] _ # Check if any result is 0 (1 if 0; 0 otherwise) à # And take the flattened maximum to check if any was truthy # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 50 bytes ``` ⊞υθW⬤υ⁻Σκ⊗I⊟⪪κ=«≔υη≔⟦⟧υFηF⊕LθFχ⊞υ⁺⁺…κλμ✂κλ»I⁻L⊟υLθ ``` [Try it online!](https://tio.run/##TY9Ba8MwDIXPy68QPcnMg4UeRw4hvQw2COQ4eshcrzZRnDa2N8bob3flpIUZbCOJ994nZfpZTT2l1EZvMEo4i5fix1jSgDVR7rxbFz12ccRBSNhN8ZP0AZveB2ynE3YnsgEHCZtqI9YDf8VD7b09uqw37HgvP/YSYq6/phnQCFj@V6dmPWoX2PdNu2MweM42y7B8FnCHa4lJlqf5VaQbw/mcTMw18u3IKr02BIdcina2Lqyo6xY398wdWfAvjAUplY9ltU1P33QF "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an "equation" i.e. `1+1=3`. Quite slow but usually manages to compute answers of up to 3 on TIO. Edit: Tweaked to be slightly less slow. Explanation: ``` ⊞υθ ``` Start with the initial equation. ``` W⬤υ⁻Σκ⊗I⊟⪪κ=« ``` Repeat while none of the equations add up. Charcoal has a builtin for taking the sum of all the strings of digits within a string, but this obviously gives `x+y+z`, so I compare that against `2z`. (Using an evaluation function would fail if I ever inserted a leading zero anywhere.) ``` ≔υη≔⟦⟧υ ``` Make a copy of the list so far so that I can empty it out. ``` FηF⊕LθFχ ``` For each equation, each possible insertion point and each digit, ... ``` ⊞υ⁺⁺…κλμ✂κλ ``` ... insert the digit into the equation at that point and save the result. ``` »I⁻L⊟υLθ ``` Output the number of digits inserted. [Answer] # [Ruby](https://www.ruby-lang.org/), 142 bytes ``` ->*x{r=[a=x];3.times{|x|w=a[x];(w..?9+w).grep(/#{w.chars*".*"}/){|z|*b=a;b[x]=z;r<<b}}until eval"%s+%s==%s"%a=r.shift;a.join.size-x.join.size} ``` [Try it online!](https://tio.run/##VYrNCoJAFIX3PYWNCDnmtXAleusFghYtWoiLMTQnzGRGG/Pn2c0Kig4cOOfjE3X8GFMc7Q1tOoEhwybyXaj4NZFd3/QKWTiRhQLYepYy4SyScuHonYJTxoSkBCgZHLPr257GyPx40rH1RRDEw1AXFc@15M5yYkjLkIiGJAZDATLjaeUzuNx4AZK3id389jCWWhqSNVm@665INPsS70X/yPQ@kqZrh93@OJ8yPgE "Ruby – Try It Online") Input integers as strings, is very slow if the solution is 3 or more. ### Quick explanation: ``` ->*x{r=[a=x]; ``` The arguments are in an array, we need to create a copy of that (a), and an array of possible solutions (r) ``` 3.times{|x|w=a[x];(w..?9+w).grep(/#{w.chars*".*"}/){|z|*b=a;b[x]=z;r<<b}} ``` Add a single digit in all possible positions to each argument separately. Instead of interpolating strings, generate all numbers between the argument and the same number with a 9 prepended, and then filter using a regex (e.g.: if the argument is "11", find all numbers containing the regex /1.\*1/ between 11 and 911) ``` until eval"%s+%s==%s"%a=r.shift;a.join.size-x.join.size} ``` Evaluate the expression using the first element of the array of possible solutions. If this is false, then repeat the process using this element as a starting point for the next iteration. We don't need to check for octal numbers since no 0 will be prepended to any number (and this solves also the case [0,0,0]) If the comparison is true, the result we need is the difference in length between the solution and the input arguments (concatenated). [Answer] # [Haskell](https://www.haskell.org/), ~~125~~ 120 bytes ``` f.pure.unwords f l=last$1+f[take i s++d:drop i s|s<-l,i<-[0..length s],d<-show$56^7]:[0|0<-foldr1(-).map read.words<$>l] ``` [Try it online!](https://tio.run/##HY3fasMgHIXvfYrfRaEJUZc/bIMu9gkGe4AsA6kmkVoVtXQtffY5k7vvcD7OWXg4S63TzL7TRN3VS3o1N@tFQBNopnmIu6aahsjPEhSEqhIH4a1b@Rl6orHqyVBTqqWZ4wJhxKInYbG33evbz/t4GOpn3ZPJauGbgpT0wh14yQXdTvrdUY/pwpVhwiIoFLZltrNUbC9tSYPjpnhhe7Ivsz3L@KmMRKBlHH7xHT9Gti2B@uAmsHUa8pLzysRizsoD30fGcoc3HWcqEayXqYGmhq4GcoQO5QDdii1qMuewpe7vNGk@h0ROziXy1f4D "Haskell – Try It Online") The relevant function is `f.pure.unwords`, which takes as input a list `[x,z,y]`; integers are represented as strings. ]
[Question] [ You've probably heard of Fibonacci numbers. Ya know, that integer sequence that starts with `1, 1`, and then each new number is the sum of the last two? ``` 1 1 2 3 5 8 13... ``` And so on. Challenges about Fibonacci numbers [are pretty popular 'round here](https://codegolf.stackexchange.com/questions/tagged/fibonacci). But who says that the Fibonacci numbers have to start with `1, 1`? Why couldn't they start with `0, 1`? Alright, let's redefine them to start at 0: ``` 0 1 1 2 3 5 8 13... ``` But... We don't have to stop there either! If we can add the last two numbers to get the next one, we could also subtract the first number from the second number to prepend a new number. So it could start with `1, 0`: ``` 1 0 1 1 2 3 5 8 13... ``` We can even end up with negatives: ``` -1 1 0 1 1 2 3 5 8 13... ``` And this series also goes on forever. I think it's interesting how it ends up kinda mirroring the regular Fibonacci numbers, just with every other number made negative: ``` 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13... ``` Let's call this series the "Extended Fibonacci Number", or **EFN**. Since there isn't really an obvious negative number to start this series on, we'll say that **0** shows up at **0**, the regular Fibonacci numbers extend in to the positive indices, and the negative (half-negative?) Fibonacci numbers extend in to the negative indices, like so: ``` Indices: ...-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 ... Values: ...13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13... ``` This leads into today's challenge: > > Given an integer **N**, return *every* index at which **N** appears in the **EFN** series. > > > Some random observations on this task: * **1** appears more times in the **EFN** than any other number: `[-1, 1, 2]`. No number will appear in more than 3 places. * Every Fibonacci number > 1 will show up either once (3, 8, 21, etc.) or twice (2, 5, 13, etc.) ## Rule Clarifications: * If `abs(N)` is not a Fibonacci number, it will never appear in the **EFN** series, so you must output nothing/an empty collection if possible, or if that is not possible in your language, you can output some constant non-numeric value. * If **N** appears at multiple places in the **EFN**, your output does not need to be sorted. Although each index must appear exactly once. * Although most [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges allow you to choose whether you want to use 1-based or 0-based indexing, this challenge *must* use the indexing described (where 0 appears at 0). * You may take I/O through any standard format. ## Test Cases ``` -13: [] -12: [] -11: [] -10: [] -9: [] -8: [-6] -7: [] -6: [] -5: [] -4: [] -3: [-4] -2: [] -1: [-2] 0: 0 1: [-1, 1, 2] 2: [-3, 3] 3: [4] 4: [] 5: [-5, 5] 6: [] 7: [] 8: [6] 9: [] 10: [] 11: [] 12: [] 13: [-7, 7] ``` And some larger test cases: ``` 89: [-11, 11] 1836311903: [46] 10000: [] -39088169: [-38] ``` As usual, shortest answer in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 78 bytes *4 bytes saved thanks to nimi* ``` a#b=a:b#(a-b) f 0=[0] f a=do{(i,x)<-zip[0..a*a+1]$0#1;[-i|x==a]++[i|abs x==a]} ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTbRKklZI1E3SZMrTcHANtogFkgn2qbkV2tk6lRo2uhWZRZEG@jpJWolahvGqhgoG1pH62bWVNjaJsZqa0dn1iQmFSuAebX/cxMz82xzEwt84xUKijLzSlRAenUt9PRiNYCiCmlgtqFlrOZ/AA "Haskell – Try It Online") First we set up `(#)`, `(#)` takes two parameters, `a` and `b`, and returns the a list starting with `a` and followed by `b#(a-b)`. This creates an infinite list, but because Haskell is lazy we don't need to wory about it looping forever. This essentially works backwards creating the Fibonacci sequence before a certain pair. For example `(0#1)` would be the list of all the Fibonacci numbers with negative index. From here we make `f`. `f` takes a argument `a` which is the number we are trying to find in the sequence. Here we use `do` notation to do a list comprehension. We start by taking the first `a*a+1` elements of the list `0#1`1. Since the function `a*a+1` grows faster than the inverse of the Fibonacci sequence we can be sure that if we check within this bound we will find all the results. This prevents us from searching an infinite list. Then for each value `x` and index `i`, if `x==a` we found `a` in the negative half of the sequence so we return `-i`, and if `abs x==a` we return `i` as well because the absolute value of the negative half is the positive half so we found it there. Since this makes the list `[0,0]` for `0` we hardcode the correct output for that one. 1: This trick is taken from [Οurous' Clean answer](https://codegolf.stackexchange.com/a/179662/56656). The same speedup aplies here as there, replace `a*a+1` with `abs a+1` to save a lot of time. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~132~~ ~~120~~ 109 bytes ``` import StdEnv g n|n<2=n=g(n-1)+g(n-2) ?k=[e\\p<-[0..k*k+1],e<-if(isOdd p)([~p,p]%(0,k))[p*sign k]|g p==abs k] ``` [Try it online!](https://tio.run/##FY2xDoIwFAB3vqKLCQVKgEQnGhYdTEwcGAtDhVKb0kdj0cSE@OnWOt3ddMMsOHizjM9ZIMMVeGXs8lhRu44neEUSwQZ1RYHKGEiJ0z8qHDWaMtF1tiasyHOd6LTsM1ETNcXKXccRWRyzj81sv4uLTGPMbOKUBKT7TSJLKb@54L5deZjRsLaoQYwc8vzQ@@8wzVw6T84Xf3wDN2oI4fy@MJ7cAwrzAw "Clean – Try It Online") `g :: Int -> Int` is the Fibonacci function. `? :: Int -> [Int]` just indexes into the elements of the EFN within `k^2+1` of `0`. For a version that runs in a sane ammount of time, change `k*k+1` to `abs k+1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` A‘ŒRÆḞẹ_A_2 ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//QeKAmMWSUsOG4bie4bq5X0FfMv/Dh8WS4bmY//8tMQ "Jelly – Try It Online") [Answer] # JavaScript (ES6), ~~94~~ 93 bytes ``` n=>(g=a=>a*a<n*n?g(b,b+=a,i++):a%n)(i=0,b=1)?[]:i&1?n<0?~n?[]:-2:i-1?[-i,i]:[-i,i,2]:n<0?-i:i ``` [Try it online!](https://tio.run/##HY3BbsMgEETv/QourSCGCOzWtWkwp36F5QN2Y5cqWqqk6rG/7s4GaYZdeDv7lX7Tbbnm7x9D5eO8r2GnMMgtpDCkQzrRgeImZz1XIelcVcqnR1IyB6vn4FQcJ5@fXKSTjX/Enal9Ni6OJus8@ful68kzYLLP@9sojGs0rGZzbBbWQx30CrXQC/QMMXontQAGR4M3fIEACB5jmOYUjuNcXuC6pm2c6y3XFofDett1ru3F9HBcy/U9LZ@SRBjEUuhWLufjpWyStFglKaX2fw "JavaScript (Node.js) – Try It Online") Or [**92 bytes**](https://tio.run/##HY3BTsMwEETvfIUvILvYlTcpIQl1cuIrohyc0ASjao1axKnqr4dZLM3Yu/t2/BV/43W@pO8fx/njtC1h49DpNcTQxV088o77VU92eg7RJhe487ebI9PGRzY6BW@nQKYfxjY9Uc9H399ZKle099QPybo0trjIFmim7W1QjkoLK8RIzMMaqIZeoQp6gQ6QoP@kVcDgKNDDCARA8FjDtqRInOTKB1SXVUnUeHl7HAlrfF1T1ajxYb/ky3ucPzWr0Kk58zWfT/tzXjVbtWg2xmx/) if we can return \$-0\$ for \$n=0\$. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 52 50 bytes Requires `⎕IO←0` ``` {X-⍨⍸⍵=F,⍨⌽0,F×1 ¯1⍴⍨≢F←{⍵≤1:1⋄+/∇¨⍵-1 2}¨⍳X←1+|⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/qyN0H/WueNS741HvVls3HRC7Z6@Bjtvh6YYKh9YbPurdAhLqXOQGVF0NVPOoc4mhleGj7hZt/Ucd7YeAOrfqGioY1YJYmyOAigy1a4Bitf/TgOxHvX0Qm7qaD603ftQ2EcgLDnIGkiEensH/gQI6@ho6jzpmqFspqB9a4aepA1LTO/XQijQgD2SYMcR1m43MAQ "APL (Dyalog Classic) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~104~~ 102 bytes ``` [1-9].* $* (-)?(\b1|(?>\3?)(\2))*(1)$|(0)?.* $5$1$4$4$#2$* -1(11)+$ ^1(11)+$ -$&,$& 1+ $.& ^2$ -1,1,2 ``` [Try it online!](https://tio.run/##NYoxDoJAEEX7fw1HMgMMYYZdwMYtPYRI1MTCxsJYcvd1Lcxrft5/78fn@brlPZ@u@Wx6uHQ1qAarJF7utnE6LkMSXlykZhPauJf0iyIZhcLOS6/GZtIQsP6XUtVSBWtAXYXVi7HWWs9ZZ@gEHaERGqAD1MuJHgbHgICIERPmLw "Retina 0.8.2 – Try It Online") Explanation: ``` [1-9].* $* ``` Convert to unary, unless the input is zero. ``` (-)?(\b1|(?>\3?)(\2))*(1)$|(0)?.* $5$1$4$4$#2$* ``` Calculate the Fibonacci index of the absolute value, but if the number is not a Fibonacci number then delete it, unless it was zero. This uses @MartinEnder's Fibonacci-testing regex. ``` -1(11)+$ ``` Delete negative numbers whose absolute values are odd Fibonacci numbers. ``` ^1(11)+$ -$&,$& ``` Add negative indices for odd positive Fibonacci numbers. ``` 1+ $.& ``` Convert to decimal. ``` ^2$ -1,1,2 ``` Add the extra indices for `1`. [Answer] # [Actually](https://github.com/Mego/Seriously), 34 bytes ``` ;╗3*;±kSix⌠;;AF@;1&@0>*YτD(s**╜=⌡░ ``` Brute-force saves the day Explanation: ``` ;╗3*;±kSix⌠;;AF@;1&@0>*YτD(s**╜=⌡░ ;╗ save a copy of the input (let's call it N) to register 0 (the main way to get additional values into functions) 3*;± -3*N, 3*N kSi push to list, sort, flatten (sort the two values on the stack so that they are in the right order for x) x range(min(-3*N, 3*N), max(-3*N, 3*N)) ⌠;;AF@;1&@0>*YτD(s**╜=⌡░ filter (remove values where function leaves a non-truthy value on top of the stack): ;; make two copies of parameter (let's call it n) AF absolute value, Fib(|n|) @; bring a copy of n to the top of the stack and make another copy 1& 0 if n is divisible by 2 else 1 @0> 1 if n is negative else 0 (using another copy of n) * multiply those two values (acts as logical AND: is n negative and not divisible by 2) YτD logical negate, double, decrement (maps [0, 1] to [1, -1]) (s sign of n (using the last copy) ** multiply Fib(|n|), sign of n, and result of complicated logic (deciding whether or not to flip the sign of the value for the extended sequence) ╜= push value from register 0, equality comparison (1 if value equals N else 0) ``` [Try it online!](https://tio.run/##ATsAxP9hY3R1YWxsef//O@KVlzMqO8Kxa1NpeOKMoDs7QUZAOzEmQDA@KlnPhEQocyoq4pWcPeKMoeKWkf//MQ "Actually – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 92 bytes ``` f=lambda x,l=[],i=0,a=0,b=1:i<x*x+2and f(x,l+[i][:a==x]+[-i][:i%2*2*a-a==x],i+1,b,a+b)or{*l} ``` [Try it online!](https://tio.run/##HYlBCsIwEEWv0o2QZqbQxl1xThKymFCDAzENJUpEPHuMfnjweD@/ym1P59YCRb77jYeKkaxDoRm542lZ5VJ1BcNpG4LqP1hxdmWi6sBOP5eT0Ubz9G8osKBHBj/ux1vHT8uHpKKCuj45Kkn5UdTY1@Yv "Python 3 – Try It Online") Returns a set of indices. [Answer] # [Python 2](https://docs.python.org/2/), ~~87~~ 85 bytes ``` f=lambda v,a=0,b=1,i=1:v*v>=a*a and[i]*(v==b)+[1-i]*((-1)**i*a==v)+f(v,b,a+b,i+1)or[] ``` [Try it online!](https://tio.run/##FcrBCsIwDADQu1@RY9NmYNXTIPuRskPKrAa0HWUE/Pqqxwdv/xzPVi9jFH7JO28CRsJnyhxJOc7mbWHxAlK3pKt3xpwxpDj94aaI3qsXZsNQnFEmCZk0RGw9raO0DgpaoUt93H/9SvGG8wlg71oPUILiFMcX "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` x*ÝʒÅfIÄQ}Ii®šë1KIdiÐ`ÉiD(ì}ëD`Èi(ë¯ ``` There has to be a better approach.. >.> There are six (or seven if we include `0`) different scenarios for this challenge, and it's killing me.. [Try it online](https://tio.run/##AT4Awf9vc2FiaWX//3gqw53KksOFZknDhFF9SWnCrsWhw6sxS0lkacOQYMOJaUQow6x9w6tEYMOIaSjDq8Kv//8tMQ) or [verify all test cases](https://tio.run/##AVQAq/9vc2FiaWX/MTNEKHPFuHZ5w5BVPyIgLT4gIj//eCrDncqSw4VmWMOEUX1YacKuxaHDqzFLWGRpw5Bgw4lpRCjDrH3Dq0Rgw4hpKMOrwq//fX19LP8). **Explanation:** ``` x*Ý # Create a list in the range [0, (implicit) input * input * 2] ʒ } # Filter this list by: Åf # Where the Fibonacci value at that index IÄQ # Is equal to the absolute value of the input Ii # If the input is exactly 1: ®š # Prepend -1 to the list ë # Else: 1K # Remove all 1s (only applies to input -1) Idi # If the input is non-negative: Ð`Éi } # If the found index in the list is odd: D(ì # Prepend its negative index to the list ë # Else (the input is negative): D`Èi # If the found index in the list is even: ( # Negate the found index ë # Else (found index is odd): ¯ # Push an empty array # (Output the top of the stack implicitly as result) ``` Some step-by-step examples: ``` Input: Filtered indices: Path it follows (with actions) and result: -8 [6] NOT 1 → neg → even index → negate index: [-6] -5 [5] NOT 1 → neg → odd index → push empty array: [] -1 [1,2] NOT 1 → (remove 1) neg → even remaining index: negate index: [-2] 0 [0] NOT 1 → even index → negate index: [0] 1 [1,2] 1 → prepend -1: [-1,1,2] 5 [5] NOT 1 → non-neg → odd index → Prepend neg index: [-5,5] 8 [6] NOT 1 → non-neg → even index → (nothing): [6] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ ~~92~~ 94 bytes ``` x=input() i=a=0;b=1 while x*x>=a: if 0<a==x:print i if[-a,a][i%2]==x:print-i a,b=b,a+b;i+=1 ``` [Try it online!](https://tio.run/##Pcm9CoAgFAbQ3adwCfoxMMfq60Wi4QpFF8IkjOzprZbWc/wd1t2ZlCLY@TPkhWAQdGfRiGvlbZaxjAOoFZIXqXsCYusPdkHyR2NNiqaRMzP9U79DysIqqmzHFZqUzAM "Python 2 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 144 bytes ``` o=>{int c=0,n=1,i=0,k=Math.Abs(o);for(;c<k;i++,n+=c,c=n-c);return new[]{c>k|o<0?0.1:i,(i>0|o<0)&i%2>0&c==k?-i:0.1,o==1?2:0.1}.Where(p=>p!=0.1);} ``` [Try it online!](https://tio.run/##FU67TsMwFN37FSGCypadyOnWONcRA0ggmDtUDK1x2quU68pxxBDy7cFZznM4xw6FHXB5Hck2SFG@vdD448LpfHPNtx8TGdPB4sFMqc4sKElQSUzcw@cpXsvn88A8150PTNum1yiEJAFWWqDCch1cHANl5H6PX5M1/Z9vVKvKqkbJ0KjV8i0@7YzaWoC@LbBOrfQAVbtb5Vweri44dgdzf4AUcD0verMOrpcQiv1eY7OCEHxzCBjdB5Jjj/mEc53lYogB6VK@eySWy1x2DDnnevkH "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ Your task here is simple: Given a list of integer sets, find the set union. In other words, find the shortest list of integer sets that contain all the elements in the original list of sets (but no other elements). For example: ``` [1,5] and [3,9] becomes [1,9] as it contains all of the elements in both [1,5] and [3,9] [1,3] and [5,9] stays as [1,3] and [5,9], because you don't want to include 4 ``` Sets are notated using range notation: `[1,4]` means the integers `1,2,3,4`. Sets can also be unbounded: `[3,]` means all of the integers `>= 3`, and `[,-1]` means all of the integers `<= -1`. It is guaranteed that the first element of the range will not be greater than the second. You can choose to take sets in string notation, or you can use 2-element tuples, using a constant non-integer as the "infinite" value. You can use two distinct constants to represent the infinite upper bound and the infinite lower bound. For example, in Javascript, you could use `[3,{}]` to notate all integers `>= 3`, as long as you consistently used `{}` across all test cases. Test cases: ``` [1,3] => [1,3] [1,] => [1,] [,9] => [,9] [,] => [,] [1,3],[4,9] => [1,9] [1,5],[8,9] => [1,5],[8,9] [1,5],[1,5] => [1,5] [1,5],[3,7] => [1,7] [-10,7],[1,5] => [-10,7] [1,1],[2,2],[3,3] => [1,3] [3,7],[1,5] => [1,7] [1,4],[8,] => [1,4],[8,] [1,4],[-1,] => [-1,] [1,4],[,5] => [,5] [1,4],[,-10] => [1,4],[,-10] [1,4],[,] => [,] [1,4],[3,7],[8,9],[11,20] => [1,9],[11,20] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answer as short as possible! [Answer] # [R](https://www.r-project.org/) + `intervals`, ~~90 87~~ 81 bytes ``` function(...)t(reduce(Intervals(rbind(...),type="Z")))+c(1,-1) library(intervals) ``` [Try it online!](https://tio.run/##bY9NDoIwEIX3nMKw6sQpsYBREz0AV3AHpZAmpJpaTDh9bflRBFZ9/d68zqu29e5KbdUqbuRDkSiKwBAtypYLkikj9DtvXkQXUpW9iaZ7ilt4DwFgzwlDyiBoZKFz3RE5BcDWxJsJQDCoTFWjpk7iZX75eT6BnKRfn@HRg/MS@OMPJHianmQHpxczzIMY42F0qpWsB9Nh3bxSjyjbYL78cYO5Cht0lR/X@8/5FgxjF7Mf "R – Try It Online") Input is a list of intervals. `-Inf` and `Inf` are R built-ins for minus/plus infinity. Output is a matrix of columns of intervals. Not usually a fan of using non-standard libraries but this one was fun. TIO doesn't have `intervals` installed. You can try it on your own installation or at <https://rdrr.io/snippets/> The `intervals` package supports real and integer (`type = "Z"`) intervals and the `reduce` function is a built-in for what the challenge wants, but the output seems to default to open intervals, so ~~`close_intervals`~~ `+c(1,-1)` is needed to get the desired result. [Old version had examples in list of lists](https://tio.run/##dZDNCoMwEITvPoV4ysIKjT@0hfYBvPbYS9EYIRCiRC369NY0RdTGS8J8mdlMoqfKv4VT1SvWiVqRAZisW/4SquP6ncuWaF72jJNsAQ8LdCFUiQNgNzb8HjwDAPCkKHSuR7LEYZJ508iRSNF2dmGEYgyA3qIyVa10OEu87sHWYyYgI8nGRzE18OKCZvuDMZ7X19DTrB1eamCEkY2sq8fuQGJr7Ct/cUgPuHlkesDnagcnzlm/WuYjTDuK0RwH9CuYPg "R – Try It Online") which might be convenient so I've left the link here. [Answer] # JavaScript (ES6), 103 bytes *Saved 1 byte thanks to @Shaggy* *Saved 1 byte thanks to @KevinCruijssen* Expects `+/-Infinity` for infinite values. ``` a=>(a.sort(([p],[P])=>p-P).map(m=M=([p,q])=>p<M+2?M=q>M?q:M:(b.push([m,M]),m=p,M=q),b=[]),b[0]=[m,M],b) ``` [Try it online!](https://tio.run/##hZLLboMwEEX3/QqWtjKQ8IjSRDVZd2Epe8sLSEJLFV6BVurXU8eUloeNWVhiZg53uL4f0VdUn@9p2dh5cbm2CWkjEqLIqYt7gxArObATxyQs7RN2sqhEGaFE1KGS1Re68o6UVCE9Vgd6QLFTftbviGVAOYaMlCCaGGLCxGvMNpzIFsS4PRd5Xdyuzq14QwlizAWfW8qHY2yt1xYJLTn0NCdXr3mS5mnzzRfIOWj3GOz1oOgtgFPlIaja1BeGBjO5yaZ7FbkV5LOJ7Ic0/OM08BrSh90yuVO45G5EWaU6ILshhaorSA88qT1MhikNvkbTvK8LgbRvnqYR2Q3pcFuRxtHv6sm/UG1Vwuq7GYPCTK7ZWPaMH/hf3RTk4DcUXd6E4S54D/FJkPtG@wM "JavaScript (Node.js) – Try It Online") ### How? We first sort the intervals by their lower bound, from lowest to highest. Upper bounds are ignored. We then iterate over the sorted intervals \$[p\_n,q\_n]\$, while keeping track of the current lower and upper bounds \$m\$ and \$M\$, initialized to \$p\_1\$ and \$q\_1\$ respectively. For each interval \$[p\_n,q\_n]\$: * If \$p\_n\le M+1\$: this interval can be merged with the previous ones. But we may have a new upper bound, so we update \$M\$ to \$\max(M,q\_n)\$. * Otherwise: there is a gap between the previous intervals and this one. We create a new interval \$[m,M]\$ and update \$m\$ and \$M\$ to \$p\_n\$ and \$q\_n\$ respectively. At the end of the process, we create a last interval with the current bounds \$[m,M]\$. ### Commented ``` a => ( // a[] = input array a.sort(([p], [P]) => // sort the intervals by their lower bound; we do not care about p - P) // the upper bounds for now .map(m = M = // initialize m and M to non-numeric values ([p, q]) => // for each interval [p, q] in a[]: p < M + 2 ? // if M is a number and p is less than or equal to M + 1: M = q > M ? q : M // update the maximum M to max(M, q) : ( // else (we've found a gap, or this is the 1st iteration): b.push([m, M]), // push the interval [m, M] in b[] m = p, // update the minimum m to p M = q // update the maximum M to q ), // b = [] // start with b[] = empty array ), // end of map() b[0] = [m, M], b // overwrite the 1st entry of b[] with the last interval [m, M] ) // and return the final result ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~118~~ ~~113~~ ~~112~~ ~~111~~ ~~106~~ ~~105~~ ~~104~~ 101 bytes ``` x=input() x.sort();a=[];b,c=x[0] for l,r in x: if l>c+1:a+=(b,c),;b,c=l,r c=max(c,r) print[(b,c)]+a ``` Saved one byte thanks to Mr.Xcoder, one thanks to Jonathan Frech, and three thanks to Dead Possum. [Try it online!](https://tio.run/##fZBRb4MgFIXf@RU3vhQmLkXbdG3D/ojxgTFNSRwY6hL26x3c2WRxziduvnMu58DwNd6cLSft3luQkGXZFKSxw@dIGQnPd@fjcFWybq5vXMtQ7xvSOQ8992AshAsB00H/qnNxUbmk0cQ4WqODgJYfKlDNPSODN3as0dDkaopJhLSh1ZCin8RpqqngULGG4ND1To10Z2y3Y8hmUCDhcF6Df5bwRg708FiI4JjAyxLg@RtUHE4ICrFP48IjEig5lLP3p3i14jzMeWvlUCvEhrh44XFLjE235H8zHq3xU1L7KJTxqm8 "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~89~~ 76 bytes ``` ->a{[*a.sort.reduce{|s,y|s+=y;y[0]-s[-3]<2&&s[-3,3]=s.max;s}.each_slice(2)]} ``` [Try it online!](https://tio.run/##RY5NC4JAGITv/gpP0cfr4ielZkfBi6cu8bLEZisFhuIquKi/3dY@b/PMDMzU7UVOeTQZB9bjmhFR1g2p@bXNeD8IkIPYRDKUaFJDoOHQvb1YzAIcGgnyYF0oRsJZdjuL4p7xpb2i44SIlipQ0BDjomRNECRpnKTJ8QS6//bnAqALP/QU7v7oKnRg@zEBLQts8xv6r9CjVKPqQ9UP3VDpOXZq@wk "Ruby – Try It Online") Sort the array, then flatten by appending all the ranges to the first: if a range overlaps the previous one, discard 2 elements from the last 3 (keeping only the max). Unflatten everything at the end. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~46~~ ~~39~~ 38 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ├&P◙╛╛ΘΩ¿σa○♦◘♣┐¬≥∩ó¬îî◙k]∙♣•╘○π≡¡jN<♀ ``` [Run and debug it](https://staxlang.xyz/#p=c326500abebee9eaa8e56109040805bfaaf2efa2aa8c8c0a6b5df90507d409e3f0ad6a4e3c0c&i=%22%5B1,3%5D,%5B2,4%5D,%5B4,6%5D,%5B7,9%5D,%5B11,13%5D%22%0A%22%5B1,3%5D%22%0A%22%5B1,%5D%22%0A%22%5B,9%5D%22%0A%22%5B,%5D%22%0A%22%5B1,3%5D,%5B4,9%5D%22%0A%22%5B1,5%5D,%5B8,9%5D%22%0A%22%5B1,5%5D,%5B1,5%5D%22%0A%22%5B1,5%5D,%5B3,7%5D%22%0A%22%5B-10,7%5D,%5B1,5%5D%22%0A%22%5B1,1%5D,%5B2,2%5D,%5B3,3%5D%22%0A%22%5B3,7%5D,%5B1,5%5D%22%0A%22%5B1,4%5D,%5B8,%5D%22%0A%22%5B1,4%5D,%5B-1,%5D%22%0A%22%5B1,4%5D,%5B,5%5D%22%0A%22%5B1,4%5D,%5B,-10%5D%22%0A%22%5B1,4%5D,%5B,%5D%22%0A%22%5B1,4%5D,%5B3,7%5D,%5B8,9%5D,%5B11,20%5D%22&a=1&m=2) This program takes input in the originally specified string notation. [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~367~~ ~~362~~ 357 bytes ``` uses math;type r=record a,b:real end;procedure d(a:array of r);var i,j:word;t:r;begin for i:=0to length(a)-1do for j:=0to i do if a[i].a<a[j].a then begin t:=a[i];a[i]:=a[j];a[j]:=t;end;j:=0;for i:=1to length(a)-1do if a[j].b>=a[i].a-1then begin a[j].a:=min(a[i].a,a[j].a);a[j].b:=max(a[i].b,a[j].b)end else j:=j+1;for i:=0to j do writeln(a[i].a,a[i].b)end; ``` [Try it online!](https://tio.run/##ZVLBcoIwEL33K/ZWmAYxqOOUlN56661Hp4cNRA1DwYao9evtJqGI04vJ27f73ubhAfsSm2R7KK/XY696@EK7F/ZyUGAKo8rOVIBM5kZhA6qtxMF0paqORkEVYY7G4AW6LZhYnNCAZnV@phlhcyOk2ukWth2V82JuO2hUu7P7COOEV50n6kBoIKy3gBv9OcMX3NR0gN2rFoKIzQvHCffjrrW71nS1wi3lZMRgxP8ZeWFSlK9FMEj4RDqY5cWXbqNAs1CKRZgiCn8CJQMlYzIF1fTKPaB@4mLyyNq95Wy0Vc1EUA9T4pqmb9/Hkz4hLWmht2h1CT7HHh7S1KU45LqZz2b806eL7U4VUcTZOmbRgj3HsRh65a03u@vN2IJ6kyVb0bFiPJ27oYm8bw4VeVfxuTwAfCj7PgTJMpoFymrus@IjoHTWAXDPLEZAzLMDf1E8Yv7oReh/E08IceckaWtXkYNTNgI5guC0HAExqwAyz9wAMfTuuy3kuIWkk77I7PoL "Pascal (FPC) – Try It Online") A procedure that takes a [dynamic array](https://www.freepascal.org/docs-html/ref/refsu14.html#x38-510003.3.1) of records consisting of 2 range bounds, modifies the array in place and then writes it on standard output, one range per line. (Sorry for that twisted sentence.) Uses `1/0` for ubounded up and `-1/0` for unbounded down. [Readable version](https://tio.run/##dVNNj5swEL3zK@a2oBIMyaarwKKeeuutx2gPY3CCEcGu7exH/3w62AlJdlULyXpvxjNvPtBoGxwWO92cTkcrLBzQdVXkPrQAg@Ne1EY0yrQR@IMpL43AIUAxtlWkjWpEezQC2hhLNAY/QO3C46SKXtGATPvyjYJUrvR0FXGxlyMF2SmylnUOTsEgxr3rYkwWBbTKZ5jM/dksLySA3AFu5UuGz7jt6QLXiREuMcNxZT35VDMxoYnr77ieOHchfD3gM1ZXccV/xM0qFsWzj5vxGyHA2EGYvYiumTIs64Mc4/AqDVRS3Xpw8sD34MGDB0@is7ZwD1ZMCvtvxfSSsd/C/TqLS4lMiBqVA62slXwQsAAEaUFpUham0wkz0Z1zumSMqjwesgH/ojnabGeE0H4nMmX2TI6teM90p384pWVTb/LV9yz3ea0CbeToQNI3Wiew/TTQnjoFb0Y6MdwULX1JU6tPjP38c3yVr0jddWAdOtkEjRYixqbVOW/UNs@y4mXeqzqOi/QpSeNVukmog8GXX32Xd77LdEW@i8d0Tdc6LVienDfz88IGln9hL7t12@ylHx1ucz/YYgY0w6cACm9ZzYAsmwlcevKA5YMPQn9OcmOo7jJxUj8x/JxpOQM@g5DpcQZkWQew9JYrIAvVf6eCzyo43TSZ7PQP) It would be nice to just return the array with corrected number of elements, but the dynamic array passed to function/procedure is not dynamic array anymore... First I found [this](http://forum.lazarus.freepascal.org/index.php?topic=9036.0), then there is this [excellent, mind-boggling explanation](http://rvelthuis.de/articles/articles-openarr.html). This is the best data structure I could found for shortening the code. If you have better options, feel free to make a suggestion. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes ``` List@@(#-{0,1}&/@IntervalUnion@@(Interval[#+{0,1}]&/@#))& ``` [Try it online!](https://tio.run/##dYxfC4IwFMW/ijCQpCu6NKo3IQiEgl56Eh9GKA3cXawVxNhnX1fLx97On985Sthbp4SVVxHORqJtTuLehKN82KpasNTlwH2cVTXazrzEcEGpkZrZN2w5IS0xLEniAC5yjkPhPZBIa@wlSvuGWXzzEQBXwu6H8Rw2FHBYz31J9v96bItpsqUPGnJY5d5Hvs2yvR6eCg/aqDZ8AA "Wolfram Language (Mathematica) – Try It Online") Takes input as a list of lists `{a,b}` representing the interval `[a,b]`, where `a` can be `-Infinity` and `b` can be `Infinity`. Uses the built-in `IntervalUnion`, but of course we have to massage the intervals into shape first. To pretend that the intervals are integers, we add 1 to the upper bound (making sure that the union of `[1,3]` and `[4,9]` is `[1,9]`). At the end, we undo this operation, and turn the result back into a list of lists. There's also a completely different approach, which clocks in at **73 bytes**: ``` NumericalSort@#//.{x___,{a_,b_},{c_,d_},y___}/;b+1>=c:>{x,{a,b~Max~d},y}& ``` Here, after sorting the intervals, we just replace two consecutive intervals by their union whenever that would be a single interval, and repeat until there is no such operation left to be done. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~88~~ ~~79~~ 78 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` g≠i˜AKïDW<UZ>VIøεAXY‚Nè:}ïø{©˜¦2ôíÆ1›.œʒíεćsO_*}P}н€g®£εø©θàDYQiA}V®нßDXQiA}Y‚ ``` Infinity is input as the lowercase alphabet (`'abcdefghijklmnopqrstuvwxyz'`). [Try it online](https://tio.run/##MzBNTDJM/f8//VHngszTcxy9D693CbcJjbIL8zy849xWx4jIRw2z/A6vsKo9vP7wjupDK0/PObTM6PCWw2sPtxk@atild3TyqUmH157beqS92D9eqzag9sLeR01r0g@tO7T43NbDOw6tPLfj8AKXyMBMx9qwQ@su7D083yUCxAGZ@/9/dLShjkmsTrRSYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZZWSjq4pUIWxjjmItNAxMQDSFjqWQNLQUMcIxDMy1cFnAEilqY6RcWwsAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL//RHnQsyT89x9D683iXcJjTKLqzy8I5zWx0jIh81zPI7vMKq9vD6wzuqD608PefQMqPDWw6vPdxm@Khhl97RyacmHV57buuR9mL/eK3agNoLex81rUk/tO7Q4nNbD@84tPLcjsMLXCIDMx1rww6tu7D38HyXCBAHZO7/2sOrK2t1/kdHRxvqGMfG6igogFjqiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVXqUEX4lOhYEqOICEtAbtKJNoGbZ6hjCuRboPFBJDLfWMccytc1NACyUVUYAvlGOkZgdTAfG2OoMgHbQ8iJMJW6hsT5BqQWb5iYEq8U6DfiFRPtOkhIgEIYGB6GOkYk2KFrCtdvbKFjYoBmDjDUTfG7A6jSVMcIGCexAA). **Important note:** If there was an actual `Infinity` and `-Infinity`, it would have been **~~43~~ 42 bytes** instead. So ~~little over 50%~~ around 30% is as work-around for the lack of `Infinity`.. ``` {©Dg≠i˜¦2ôíÆ1›.œʒíεćsO_*}P}н€g®£εø©θàV®нßY‚ ``` [Try it online](https://tio.run/##MzBNTDJM/f8//VHngszqQytPzzm0zOjwlsNrD7cZPmrYpXd08qlJh9ee23qkvdg/Xqs2oPbC3kdNa9IPrTu0@NzWwzsOrTy34/CCsEPrLuw9PD/yUcOs//@jow11TGJ1onUt4UBH1xQoYKxjDiItdEwMgLSFjiWQNDTUMQLxjEx1EMpB4qY6RsaxsQA) (with `Infinity` replaced with `9999999999` and `-Infinity` replaced with `-9999999999`). Can definitely be golfed substantially. In the end it turned out very, very ugly full of workarounds. But for now I'm just glad it's working. **Explanation:** ``` Dg≠i # If the length of the implicit input is NOT 1: # i.e. [[1,3]] → length 1 → 0 (falsey) # i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]] # → length 8 → 1 (truthy) ˜ # Take the input implicit again, and flatten it # i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]] # → [1,4,"a..z",-5,3,7,38,40,8,9,11,20,25,"a..z",15,23] AK # Remove the alphabet # i.e. [1,4,"a..z",-5,3,7,38,40,8,9,11,20,25,"a..z",15,23] # → ['1','4','-5','3','7','38','40','8','9','11','20','25','15','23'] ï # Cast everything to an integer, because `K` turns them into strings.. # i.e. ['1','4','-5','3','7','38','40','8','9','11','20','25','15','23'] # → [1,4,-5,3,7,38,40,8,9,11,20,25,15,23] D # Duplicate it W< # Determine the min - 1 # i.e. [1,4,-5,3,7,38,40,8,9,11,20,25,15,23] → -5 U # Pop and store it in variable `X` Z> # Determine the max + 1 # i.e. [1,4,-5,3,7,38,40,8,9,11,20,25,15,23] → 40 V # Pop and store it in variable `Y` Iø # Take the input again, and transpose/zip it (swapping rows and columns) # i.e. [[1,4],["a..z",-5],[3,7],[38,40],[8,9],[11,20],[25,"a..z"],[15,23]] # → [[1,'a..z',3,38,8,11,25,15],[4,-5,7,40,9,20,'a..z',23]] ε } # Map both to: A # Push the lowercase alphabet XY‚ # Push variables `X` and `Y`, and pair them into a list Nè # Index into this list, based on the index of the mapping : # Replace every alphabet with this min-1 or max+1 # i.e. [[1,'a..z',3,38,8,11,25,15],[4,-5,7,40,9,20,'a..z',23]] # → [['1','-6','3','38','8','11','25','15'],['4','-5','7','40','9','20','41','23']] ï # Cast everything to integers again, because `:` turns them into strings.. # i.e. [['1','-6','3','38','8','11','25','15'],['4','-5','7','40','9','20','41','23']] # → [[1,-6,3,38,8,11,25,15],[4,-5,7,40,9,20,41,23]] ø # Now zip/transpose back again # i.e. [[1,-6,3,38,8,11,25,15],[4,-5,7,40,9,20,41,23]] # → [[1,4],[-6,-5],[3,7],[38,40],[8,9],[11,20],[25,41],[15,23]] { # Sort the pairs based on their lower range (the first number) # i.e. [[1,4],[-6,-5],[3,7],[38,40],[8,9],[11,20],[25,41],[15,23]] # → [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]] © # Store it in the register (without popping) ˜ # Flatten the list # i.e. [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]] # → [-6,-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40] ¦ # And remove the first item # i.e. [-6,-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40] # → [-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40] 2ô # Then pair every two elements together # i.e. [-5,1,4,3,7,8,9,11,20,15,23,25,41,38,40] # → [[-5,1],[4,3],[7,8],[9,11],[20,15],[23,25],[41,38],[40]] í # Reverse each pair # i.e. [[-5,1],[4,3],[7,8],[9,11],[20,15],[23,25],[41,38],[40]] # → [[1,-5],[3,4],[8,7],[11,9],[15,20],[25,23],[38,41],[40]] Æ # Take the difference of each pair (by subtracting) # i.e. [[1,-5],[3,4],[8,7],[11,9],[15,20],[25,23],[38,41],[40]] # → [6,-1,1,2,-5,2,-3,40] 1› # Determine for each if they're larger than 1 # i.e. [6,-1,1,2,-5,2,-3,40] → [1,0,0,1,0,1,0,1] .œ # Create every possible partition of these values # i.e. [1,0,0,1,0,1,0,1] → [[[1],[0],[0],[1],[0],[1],[0],[1]], # [[1],[0],[0],[1],[0],[1],[0,1]], # ..., # [[1,0,0,1,0,1,0],[1]], # [[1,0,0,1,0,1,0,1]]] ʒ } # Filter the partitions by: í # Reverse each inner partition # i.e. [[1],[0,0,1],[0,1],[0,1]] → [[1],[1,0,0],[1,0],[1,0]] ε } # Map each partition to: ć # Head extracted # i.e. [1,0,0] → [0,0] and 1 # i.e. [1] → [] and 1 # i.e. [1,0,1] → [1,0] and 1 s # Swap so the rest of the list is at the top of the stack again O # Take its sum # i.e. [0,0] → 0 # i.e. [] → 0 # i.e. [1,0] → 1 _ # And check if it's exactly 0 # i.e. 0 → 1 (truthy) # i.e. 1 → 0 (falsey) * # And multiply it with the extracted head # (is only 1 when the partition has a single trailing 1 and everything else a 0) # i.e. 1 and 1 → 1 (truthy) # i.e. 1 and 0 → 0 (falsey) P # And check if all mapped partitions are 1 н # Take the head (there should only be one valid partition left) # i.e. [[[1],[0,0,1],[0,1],[0,1]]] → [[1],[0,0,1],[0,1],[0,1]] €g # Take the length of each inner list # i.e. [[1],[0,0,1],[0,1],[0,1]] → [1,3,2,2] ® # Push the sorted pairs we've saved in the register earlier £ # Split the pairs into sizes equal to the partition-lengths # i.e. [1,3,2,2] and [[-6,-5],[1,4],[3,7],[8,9],[11,20],[15,23],[25,41],[38,40]] # → [[[-6,-5]],[[1,4],[3,7],[8,9]],[[11,20],[15,23]],[[25,41],[38,40]]] ε # Map each list of pairs to: ø # Zip/transpose (swapping rows and columns) # i.e. [[1,4],[3,7],[8,9]] → [[1,3,8],[4,7,9]] # i.e. [[25,41],[38,40]] → [[25,38],[41,40]] © # Store it in the register θ # Take the last list (the ending ranges) # i.e. [[25,38],[41,40]] → [41,40] à # And determine the max # i.e. [41,40] → 41 DYQi } # If this max is equal to variable `Y` # i.e. 41 (`Y` = 41) → 1 (truthy) A # Replace it back to the lowercase alphabet V # Store this max in variable `Y` ® # Take the zipped list from the register again н # This time take the first list (the starting ranges) # i.e. [[25,38],[41,40]] → [25,38] ß # And determine the min # i.e. [25,38] → 25 DXQi } # If this min is equal to variable `X` # i.e. 25 (`X` = -6) → 0 (falsey) A # Replace it back to the lowercase alphabet Y‚ # And pair it up with variable `Y` (the max) to complete the mapping # i.e. 25 and 'a..z' → [25,'a..z'] # Implicitly close the mapping (and output the result) # i.e. [[[-6,-5]],[[1,4],[3,7],[8,9]],[[11,20],[15,23]],[[25,41],[38,40]]] # → [['a..z',-5],[1,9],[11,23],[25,'a..z']] # Implicit else (only one pair in the input): # Output the (implicit) input as is # i.e. [[1,3]] ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~346~~ 342 bytes Compiler flags `-DP=printf("(%d,%d)\n"`,`-DB=a[i+1]`, and `-DA=a[i]` ``` typedef struct{int a,b;}t;s(t**x,t**y){if((*x)->a>(*y)->a)return 1;else if((*x)->a<(*y)->a)return -1;}i;f(t**a){for(i=0;A;)i++;qsort(a,i,sizeof(t*),s);for(i=0;B;i++){if(B->a<=A->b+1){A->b=B->b;if(B->a<A->a)A->a=B->a;else B->a=A->a;}}for(i=0;A;i++){if(!B)break;if(A->a!=B->a)P,A->a,A->b);}P,A->a,A->b);} ``` [Try it online!](https://tio.run/##XZDLboMwEEX3fIWDlMoDRoImVR9TIoH6AdmnLMwrsppCip0qKeLXSz1USdRu5nF8587IRVDsZLMdR3PaV2VVM226Q2F61RgmRY6DQc2N5x2FDSfoVc25d4RgJVfc9jZDV5lD17AIq52u2FXw/E8QRDgorMlNQl@3HVdxiAmC8n380G1nuBRKaPVVtaQCoQHPshStalqfknWcBKvcj6CnHFuU4/kpoZUUCMvfo6iiEYnDcF18dpylkHeVfCMLEs2mSVgLaijkgMPfbqT/eZeq4dA7hnlyc5ehIzdhxmJ2ww30kVgORKILWYj7idxeyIN4nMjiOhWJ23BiS2L8s1WlByE6@4PR3K25hCcX0KECnWH8Luqd3OoxeFnH@84eVXOXz0sxL@G1cS1OY7lRfpTZMqEy@wE "C (clang) – Try It Online") ]
[Question] [ ## Introduction Suppose you have a list of lists of integers (or any objects really, but let's stick to integers for simplicity). The lists may be of different lengths, and some of them may be empty. Let's write the lists in a tabular format: ``` [[ 1, 2, 3, 4, 5], [ 6, 7], [ 8, 9, 10, 11], [], [12, 13, 14], [15, 16, 17, 18]] ``` This table has 5 vertical columns, containing the numbers `1, 6, 8, 12, 15`, `2, 7, 9, 13, 16`, `3, 10, 14, 17`, `4, 11, 18`, and `5`. If we reverse each column, we obtain the lists `15, 12, 8, 6, 1`, `16, 13, 9, 7, 2`, `17, 14, 10, 3`, `18, 11, 4`, and `5`. Let's plug those numbers back into the columns of the table while keeping the lengths of the rows the same as before: ``` [[15, 16, 17, 18, 5], [12, 13], [ 8, 9, 14, 11], [], [ 6, 7, 10], [ 1, 2, 3, 4]] ``` Your task is to implement this operation. ## Input and output Your input is a list of lists of nonnegative integers, representing the rows. The rows may have different lengths, and some of them may be empty. There will always be at least one row. Your output is the result of reversing each column, as detailed above. Input and output may be in any reasonable format. The lowest byte count in each language wins. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test cases ``` [[]] -> [[]] [[],[]] -> [[],[]] [[8,5,1]] -> [[8,5,1]] [[1,200],[0,3]] -> [[0,3],[1,200]] [[],[3,9],[1],[]] -> [[],[1,9],[3],[]] [[],[5,8,7],[0,6,5,7,1]] -> [[],[0,6,5],[5,8,7,7,1]] [[1,8,5],[7,5,4],[],[1]] -> [[1,5,4],[7,8,5],[],[1]] [[],[],[2],[],[31],[],[5],[],[],[],[7]] -> [[],[],[7],[],[5],[],[31],[],[],[],[2]] [[1,10,100,1000],[2,20,200],[3,30],[4],[5,50,500],[6,60],[7]] -> [[7,60,500,1000],[6,50,200],[5,30],[4],[3,20,100],[2,10],[1]] [[8,4],[3,0,4,8,1],[8],[0,8],[9,7,1,6],[3,8,1,9,5]] -> [[3,8],[9,7,1,9,5],[0],[8,8],[3,0,1,6],[8,4,4,8,1]] [[3,9,3],[5],[1],[3,5],[9,0,6,2],[1,3],[4,9,2],[6,6,7,8,7]] -> [[6,6,7],[4],[1],[9,9],[3,3,2,8],[1,0],[5,5,6],[3,9,3,2,7]] [[8,5,6],[3,5,2,4,9],[4,3,8,3,7],[6,1,1],[1,8,9,9],[9,1,2],[8,7]] -> [[8,7,2],[9,1,9,9,7],[1,8,1,3,9],[6,1,8],[4,3,2,4],[3,5,6],[8,5]] [[2,4],[1,4],[0,8,7,3],[4,9,2,5],[2,8,0],[0,8,3],[7,3,1],[],[3,3,7,8]] -> [[3,3],[7,3],[0,8,7,8],[2,8,1,5],[4,9,3],[0,8,0],[1,4,2],[],[2,4,7,3]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ḟṚṁṣj z-ç€-ZFḟ-ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hjvkPd856uLPx4c7FWVxVuoeXP2paoxvlBhTXBYr@P9zu/v9/dLSCoY6CgoIRiDAGESYgwjRWh0shWsEMxDaHsC1AbEsgYWgAIgzBomDCEKTZEKTZ0AQiYApigzQbmoMIi9hYAA "Jelly – Try It Online") or [verify all test cases](https://tio.run/##VVI9TxtBEO39K/YHjMnu7e3tbpMyXdpIYLlwnIswskjEQSSogIYeOpQoRRSloYwULKhA/JDzHznm63yOdXfrfTPzZt/bOaiXy9Oua@9/tqvbdnXRrn4djM7Gz3/Wl3fjvXeIjxHtXm4wsD7/bsZvzfr8x8v1h@er9cXj0@83pr3/RwFnFoefFvPZcd2Y5mQ@r5sGjDWfZ4vlyVG9Q1Wj9uEvll3e7Zrhp@XvZ1/N8X5tZh@/fKsNvke8XS4O62YH07C86yaT6ZROQOsIPzDsQaAEAVwP6gZhB4W1mGPB90H6CxpQMg@ZoP9pHYO@b4BrgASRySpsEId@PdbnSIzbJ0Yj5pfERF20yCkWNUdiqg4mhSzeyaoZ8sRt9bTdTukreho5h7P48Et2FKhenfHgaSn57MHiQ9sKKrvdKOKeQj1BRalCEAYCT7ROOzi7UZRAohZKFEvnS2wZfTOZBRXHMQYZzdCmfishs0dEmRglMilDcqWlVniVfL9BL9RzXQa6n4JvlaIlZhUiEyLfqrZkQNU4LsziERTc1oFIDnrizJG4GUFBA2IlV5ZAqjxzVnhgxxwJhDcjUrCEOIxuZCiz5syFjo2RISWSpMSF2hrUh8DHENTx1/I0bhSzFygErMY8z58HHRnSiXYM/mt8w5S03jFTqV5bZcSeoGNL@qlw@go "Jelly – Try It Online"). ### How it works ``` z-ç€-ZFḟ-ṁ Main link. Argument: M (matrix / 2D array) z- Zip the rows of M, using -1 as filler. ç€- Map the helper link over the result, with right argument -1. Z Zip the rows of the result. F Flatten the resulting matrix. ḟ- Filterfalse -1; remove all occurrences of -1. ṁ Mold; shape the result like M. ḟṚṁṣj Helper link. Left argument: A (row / 1D array). Right argument: -1 ḟ Filterfalse; remove all occurrences of -1. Ṛ Reverse the resulting vector. ṣ Split A at occurrences of -1. ṁ Mold; shape the vector to the left like the 2D array to the right. j Join the resulting 2D array, separating by -1. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~20~~ ~~19~~ 16 [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 charater set") [-4 thanks to ngn.](https://codegolf.stackexchange.com/posts/154251/revisions) Full program. Prompts for input from STDIN. ``` ⍟0~¨⍨↓⍉⌽@×⍤1⍉↑*⎕ ``` [Try it online!](https://tio.run/##fVG7TsNAEOzzFe4O0Ca688WvIhIoQIF4SBgKFKVwhENjJQhSQEOFzNNREEKUFFCkyC/QwJ/cj5jddSSaXKzznfZmb3ZmNznP6qfXSTY8K834bfvQ5BPlhoF5ul3BeD82xWy1YYqxwKh9IsRlko2EQBjjeKtx3N7bxDCf9IZXznDg1Pst2ket0UWaIvD4mQ6SXpbGG7tH9KiYiZq5v@uXpviQNz9TU0xN/mqKB/P8vf77boovRUH@sob8JWaWDn/9GsY78cG@IzqdblfUFl2DDQnBA2XBFLhS4lMJ2s6rIcJd2Ssg4kEIARP5WC5YUhDlYF6AWU1iJGK7I@i41aFVdXrVUa3AWkRJXPyTOxddzo1q0HQ0WbIncVHogy@X8IUsVYOEJsonJSFbpT0is@AzjhhEaG8xC7YRu1xZUJzv8XtqGblUjDYxy60kITM11T7VqqoHLuqK@C1p0DwIH7UoZg2RMeJKipntnC77VLxLqv2viLW6eCfnmOYhapjPRVNZbEhX/AE "APL (Dyalog Unicode) – Try It Online") **Explanation with example walk-through** `⎕` prompt for evaluated input  `[[1,8,5],[7,5,4],[],[1]]` `*` raise *e* to the power of that (*e*n which ensures that there will be no zeros)  `[[2.7,2981,148.4],[1096.6,148.4,54.6],[],[2.7]]` `↑` mix the lists into a single matrix, padding with zeros:  `┌ ┐`  `│2.7E0 3.0E3 1.5E2│`  `│1.1E3 1.5E2 5.5E1│`  `│0.0E0 0.0E0 0.0E0│`  `│2.7E0 0.0E0 0.0E0│`  `└ ┘` `⍉` transpose  `┌ ┐`  `│2.7E0 1.1E3 0.0E0 2.7E0│`  `│3.0E3 1.5E2 0.0E0 0.0E0│`  `│1.5E2 5.5E1 0.0E0 0.0E0│`  `└ ┘` `⌽@×⍤1` reverse the positive elements of each row  `┌ ┐`  `│2.7E0 1.1E3 0.0E0 2.7E0│`  `│1.5E2 3.0E3 0.0E0 0.0E0│`  `│5.5E1 1.5E2 0.0E0 0.0E0│`  `└ ┘` `⍉` transpose  `┌ ┐`  `│2.7E0 1.5E2 5.5E1│`  `│1.1E3 3.0E3 1.5E2│`  `│0.0E0 0.0E0 0.0E0│`  `│2.7E0 0.0E0 0.0E0│`  `└ ┘` `↓` split the matrix into a list of lists  `[[2.7,148.4,54.6],[1096.6,2981,148.4],[0,0,0],[2.7,0,0]]` `0~¨⍨` remove zeros from each list  `[[2.7,148.4,54.6],[1096.6,2981,148.4],[],[2.7]]` `⍟` natural logarithm  `[[1,5,4],[7,8,5],[],[1]]` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ 13 bytes *saved 2 bytes thanks to @Shaggy* ``` y@=XfÊX£o ®fÄ ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=eUA9WGbKWKNvCq5mxA==&input=W1sgMSwgICAyLCAgIDMsICAgNCwgICA1XSwKIFsgNiwgICA3XSwKIFsgOCwgICA5LCAgMTAsICAxMV0sCiBbXSwKIFsxMiwgIDEzLCAgMTRdLAogWzE1LCAgMTYsICAxNywgIDE4XV0KLVE=) The second line can be removed if we are allowed to pad the rows with null values, saving 4 bytes. ### Explanation ``` y@ =XfÊ X£ o Implicit: U = input array UyX{U=Xfl Xm{Uo}} (Ungolfed) UyX{ } Map each column X in the input by this function: U=Xfl Set U to X filtered to only items whose factorial is truthy; this just gets rid of the empty slots in the column. Xm{ } Map each item in X to Uo the last item in U, popping this item from the list. Due to the way .map works in JS, this is only called on real items and not empty slots, so this preserves empty slots. Newline: set U to the resulting column-reversed array ® fÄ Due to the way y works, there will now be `undefined` in some rows. UmZ{Zf+1} (Ungolfed) mZ{ } Map each row Z in U to Zf+1 Z filtered to only items where the item + 1 is truthy. undefined + 1 is NaN, which is falsy, and thus eliminated. Implicit: output result of last expression ``` [Answer] # [K4](http://kx.com/download/), 36 bytes **Solution:** ``` +{x[w]:|x w:&~^x;x}'x'[::;]@!|/#:'x: ``` **Examples:** ``` q)k)+{x[w]:|x w:&~^x;x}'x'[::;]@!|/#:'x:(1 2 3 4 5;6 7;8 9 10 11;0#0N;12 13 14;15 16 17 18) 15 16 17 18 5 12 13 8 9 14 11 6 7 10 1 2 3 4 q)k)+{x[w]:|x w:&~^x;x}'x'[::;]@!|/#:'x:(0#0N;5 8 7; 0 6 5 7 1) 0 6 5 5 8 7 7 1 ``` **Explanation:** This one has been a pain, and I'm still working to simplify the elided indexing. Instead of indexing in at, for example, `x[0]` which would return the first *row*, we want to take the first *column*, which can be done using `x[;0]`. However passing variable `y` into `x[;]` treats it as doing `x[y]` not `x[;y]` hence shoving the `::` in there: `x[::;]`. This is equivalent to flipping the list of lists, but flip requires all lists to be equal length! ``` +{x[w]:|x w:&~^x;x}'x'[::;]@!|/#:'x: / the solution x: / save input as variable x #:' / count (#:) each (') |/ / take the max of these lengths ! / til, range 0..max-1 @ / apply (index into) [::;] / :: is a kind of null, x' / index into x at each of these { ; }' / two statement lambda on each (') ^x / null x (returns true if entry is null) ~ / not, so flip true/false & / where, indexes where true w: / save as variable w x / index into w at these indexes | / reverse x[w]: / store this back in variable x at indexes w x / return x from function + / flip the result ``` [Answer] # [Haskell](https://www.haskell.org/), 174 bytes ``` f x=map g.h.map(g.reverse>>=(!)).h$take(maximum$length<$>x).(++z).map pure<$>x g=concat h x|g x==[]=x|4>2=foldr(zipWith(:))z x x!(c:d)|c==[]=c:x!d|a:b<-x=[a]:b!d _!y=y z=[]:z ``` [Try it online!](https://tio.run/##dVNNb5tAEL37V6wjH0CeID7Nh4KlqqdKlXrooQeCKmI2YMXGFiYNsfzf3ZnZxXYUYmGWnXnz5u1jqIvDi9xszudn0afbYi8qq7ZwNSqrlf9ke5DLZWpMTdOqZ13xIo1t0a@3r9vZRjZVVz/Mlr1pGfP50aQqsX9tJcUmVbraNauim9SiP1XInWZ52p/8pZs@7zZlaxzX@z/rrjYS0zyKftJPjVVSmqcVA1dJPy1PRfL0cN@nWZEnT9Ny8nf6nr5PjphPjudtsW5EKsodtux@d@3PRszE3bfNRnTy0B3EvjgcZJmIOzGfi0O9exNGgUnj0eihNcX9UuCBRZoK3HCFORGXn6IUd4/Nr9cON0hzk61k933XdLLBNmiO2LfrphMWElrCaGVRiiQRWL9uKuqTZT8QXMk2z6nHWy1bqUWmN6yZMLIszwXgY6agww84BdcsjAEiCMAZIHrzCeSAa9tYb4M3QOkRdGK0rQcxAT4KcDjojUvBaAARhNxogVLCq7IhNmBUbkRoxJgQq33qQgo0haNjocao3KhjkLlq8Ry1ary6wltHaXsLGSoGmjGNjo0X/8lUFz3U/nrg0eLzKQMbL9ouYGHftg1xT6mBYEFQRRBcCTyidXQHx/7itBEorA0@2kLaI7aa7jGZDAvOYw5itE1L8G4AMbtJDSKOEpkqQ3JN@7kxjgdPUKCHxGOWGOgtuzwplPUR5SoLIOTZ0AI4oE/qcGGs/AOXRTig7Ai0/pgz4RcfgMIEiPCZxwc6sccdFngYhxkjUF1ijLh8vPD64YQcitmPmAsdNk19BkQSaWJXWx5oj4IRUQrj8N3meb@4wT7hIcHWOY9n2gM9eOQBWnV9Uzp/YYp0vcNMvn4PtmbEnqCHn9ygwg/y8jNNcKxMVhKUOy729fP8Pw "Haskell – Try It Online") ### Ungolfed/Explanation The idea is to wrap all elements in `[]` and pad the rows with `[]` (turned out to be shorter than padding with a negative integer, this allows negative inputs as well which is nice), then transpose, reverse all rows and transpose again and flatten each row: ``` map concat -- flatten each row . transpose' -- transpose (*) . map (\row-> reverse (concat row) ! row) -- reverse each row (see below) . transpose' -- tranpose (*) $ take (maximum $ length <$> x) -- only keep up as many as longest row . (++ z) -- pad row with [],[],.. . map (\e-> [e]) -- wrap elements in [] <$> x ``` \* This transpose function (`h`) simply returns the list if there are no elements at all. The reverse function has to ignore `[]` elements (eg. `[[],[1],[],[3],[4]]` -> `[[],[4],[],[3],[1]]`), it does so by receiving two arguments: The first one are the elements in reverse order (eg. `[4,3,1]`) and the second one the original row. ``` x@(a:b) ! (c:d) | c == [] = c:x ! d -- if current element is []: skip it | otherwise = [a]:b ! d -- else: replace with new one (a) and continue _ ! y = y -- base case (if no new elements are left): done ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ ~~105~~ 92 bytes ``` def f(l):x=map(lambda*n:[v for v in n if-1<v],*l);return[map(list.pop,x[:len(k)])for k in l] ``` [Try it online!](https://tio.run/##VVTRjqMwDHzvV@QRVr5TQghJetcvQTz0tKCrlqWIstXe1/dsxylUokA8nnE8cZn/rX@vU/V4vPeDGoqxPH6fPs9zMZ4//7yf36Zje1fDdVF3dZnUpC7DD/P73sHbWP5a@vVrmVrOvtzWn/N1hu/2OPZT8VF2JbE@iDV2j7W/rTd1Uu1BqaJtuw4U3UuQNeQQ7KIBHJgUl9eMGKi0xlwNNuH0AhLeq1qIFN/rGw7Zl0q4cBDAs2SDtXwunCM5IyHbPgJDHik1KVIt5hmJeMlIyL5faKv0sCY9JS1dfvODFvuEnJ9FdrsxGi/@kTsV2iFGWbD0qLkNp/GiZQON3mp5XBGQ6Q0lJrrb6JZEjegb/dpXgJSioca@aZ@BDaR7JOugYRwxiOgL17U7OLJZpBo4SlKJhNIi@qyGh8vH7uSILZMj0IFVfNKE1phVpWbB8yFzVV5KT4ZpMfkEFVc2kBp3suXIiH@dzgQ5BGqm10C9WRZucOOGhQIk8YiRilvxeao9ByJ3Hplm2Jw0tyQRRLYSa5244badJMjwXfOQPvtmR7Ah0IJZnkkLMkPUL5qSD0LQp04QtmGdWvzWoocVQWaYDCBiVx66w2FeLtOqzuNYDAX980t1Oqmlv32NK39LKAY5gB8I/jqUj/8 "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), ~~79~~ 76 bytes ``` (a,d=[],g=s=>a.map(b=>b.map((c,i)=>(d[i]=d[i]||[])[s](c))))=>g`push`&&g`pop` ``` Edit: Saved 3 bytes thanks to @ETHproductions. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ≢¨⍴¨∘↓∘⍉⍉∘↑{⍵\⌽⍵/⍺}⍤1∘⍉∘↑=⍨ ``` [Try it online!](https://tio.run/##RVJNixQxEL33r6jbdKDFpNPpjwX/iZcBGVkcGFn6ssheZFl2V3tZEcGzeNiDR70IXvwp@SPje1VpB9Lp5L2ql3qpbN/un7263O4Pr4/54cv5Id88@uMOc7779vcpLz8x3X7NN585L3cc3H56l5dfL/PHP/g9z8vvq7x8DyVE@Rd5eToeZwgxEmIXWO4QebbZbc/3G6yAX@QP15vDm81VVTf5/n1efri5LCp8GLP9jB8lSbAIXVZ1kNZ7V3uJbta5IMyuo0yuboIrMqC4j66o10lGGZjcQ2ygMlHdOiMV5SkjoQFhHbMpOgPlFijJgpaq66Y1JAb7a8DKDW4@LU/0Gn2S4MnBY@gHny3MmeMoEXPTsdDkMbDrpScGeRTVK1jyesZoXvqfF6kVTDV4vaiqHkUZLx1cBYAj7wfTxKuQniQImWB55nplCNQNZEZiVNBo6BWpiu1gg5qkZ2GbmMzrbtk2UB0iWvUhg/ZmtrUVzKSJLYR3aXlMEHWUrK5J4UFdFCgB6JjSCeuOlOpRWXDaU1WbsG9ZKY9jz1vDQDI8qF99SswcTau1e0rmMeFMRQInry9ntUOXKFa8EZEPJoo9CxqBUb1JI9bs0ZICszu7N28iOELscdEaU6p/ "APL (Dyalog Unicode) – Try It Online") [Answer] ## Clojure, 123 bytes ``` #(map(fn[i R](map(fn[j _](let[V(for[Q %](get Q j))F filter](nth(reverse(F + V))(count(F +(take i V))))))(range)R))(range)%) ``` I was expecting `(+ nil)` to throw an exception, but it evaluates to `nil` :o This operates without padding, instead it counts how many of the previous rows are at least as long as the current row `R`. ]
[Question] [ # Challenge Given the phase of the moon, draw it using ASCII art. Your program must handle new moon, waxing crescent, first quarter, waxing gibbous, full moon, waning gibbous, last quarter, and waning crescent. Your input will be an integer. ``` 0 -> new moon 1 -> waxing crescent 2 -> first quarter 3 -> waxing gibbous 4 -> full moon 5 -> waning gibbous 6 -> last quarter 7 -> waning crescent ``` The ASCII art is all placed on a 16x8 grid (because character dimension ratios). You can replace `.` with any character and `#` with any other non-whitespace character. The output for new moon should be: ``` ................ ................ ................ ................ ................ ................ ................ ................ ``` For waxing crescent: ``` ..........###### ............#### .............### .............### .............### .............### ............#### ..........###### ``` For first quarter: ``` ........######## ........######## ........######## ........######## ........######## ........######## ........######## ........######## ``` For waxing gibbous: ``` ......########## ....############ ...############# ...############# ...############# ...############# ....############ ......########## ``` And for full moon: ``` ################ ################ ################ ################ ################ ################ ################ ################ ``` The waning crescent is just the waxing crescent with each line reversed, as with the waning gibbous and the waxing gibbous, and the first and last quarter. # Rules * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * You may choose to output waxing/waning in the opposite direction if you want, though it should make no difference (the graphics shown in this question are for the northern hemisphere) * Your output must be exactly as specified. Your newlines can be any reasonable line separator, and you may have a trailing newline if you would like. [Answer] ## JavaScript (ES6), ~~121~~ ... ~~103~~ 92 bytes ``` f=(n,i=128)=>i--?f(n,i)+(i%16?'':` `)+'.#.'[i%16+4*n-~-'31000013'[n&1?i>>4:1]*~-(n&2)>>4]:'' ``` ### Demo ``` f=(n,i=128)=>i--?f(n,i)+(i%16?'':` `)+'.#.'[i%16+4*n-~-'31000013'[n&1?i>>4:1]*~-(n&2)>>4]:'' o.innerHTML=f(0) ``` ``` <input type="range" oninput="o.innerHTML=f(this.value)" value=0 min=0 max=7><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -7 bytes moving from bit-mask to comparison-mask -2 bytes with some tacit programming improvements -1 byte moving to the southern hemisphere -1 byte - **use the all-new `ɓ` chain separator** ...its first ever use! ``` “>,##‘m0Dm€0ż@€4Ḷ¤Œṙɓ%4>C¹⁸:4¤?Y ``` Uses the characters `0` for `.` and `1` for `#`. All cases in a test suite at **[Try it online!](https://tio.run/nexus/jelly#@/@oYY6djrLyo4YZuQYuuY@a1hgc3eMApEwe7th2aMnRSQ93zjw5WdXEzvnQzkeNO6xMDi2xj/x/dM/hdqCaSBD@/z/aQMdQx0jHWMdEx1THTMc8FgA)** ### How? Builds a mask capturing the first four phases, and rather than reversing the lines complements the resulting values of the modulo-4 phase result when the phase div-4 is non-zero. I originally built a bit mask, but the mask values were `0`,`8`,`12`, and `14` - `0000`, `1000`, `1100`, and `1110` - these have `phase` leading ones - so a comparison-mask could be used instead. ``` “>,##‘m0Dm€0ż@€4Ḷ¤Œṙɓ%4>C¹⁸:4¤?Y - Main link 1: number phase “>,##‘ - code-page index literal [62,44,35,35] m0 - reflect -> [62,44,35,35,35,35,44,62] D - decimalise -> [[6,2],[4,4],[3,5],[3,5],[3,5],[3,5],[4,4],[6,2]] m€0 - reflect €ach -> [[6,2,2,6],[4,4,4,4],[3,5,5,3],[3,5,5,3],[3,5,5,3],[3,5,5,3],[4,4,4,4],[6,2,2,6]] ¤ - nilad and link(s) as a nilad: 4 - literal 4 Ḷ - lowered range -> [0,1,2,3] ż@€ - zip (reverse @rguments) for €ach -> [[[0,6],[1,2],[2,2],[3,6]],[[0,4],[1,4],[2,4],[3,4]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,3],[1,5],[2,5],[3,3]],[[0,4],[1,4],[2,4],[3,4]],[[0,6],[1,2],[2,2],[3,6]]] Œṙ - run-length decode -> [[0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3],[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3],[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3],[0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3]] - i.e.: 0000001122333333 - 0000111122223333 - Marking out the separate 0001111122222333 - regions as filled up by 0001111122222333 - the phases of the moon in 0001111122222333 - the southern hemisphere. 0001111122222333 - 0000111122223333 - 0000001122333333 - ɓ - dyadic chain separation & swap arguments, call that m %4 - phase mod 4 > - greater than? (vectorises across m) 1 if so 0 if not ? - if: ¤ - nilad followed by link(s) as a nilad: ⁸ - link's left argument, phase :4 - integer divide by 4 C - then: complement ¹ - else: identity (do nothing) Y - join with newlines - implicit print ``` [Answer] # [Haskell](https://www.haskell.org/), ~~98~~ 90 bytes ``` f i=do{a<-[3,1,0,0,0,0,1,3];[".#."!!div(i*4+x+[0,a-1,0,1-a]!!mod i 4)16|x<-[0..15]]++"\n"} ``` It loops through the rows and columns using the list monad (a `do` block for rows and a list comprehension for columns) and determines which character for each cell using a expression of the input (`i`), offset value for the row (`a`), and column index (`x`). Saved 8 bytes by simplifying the subexpression for the true offset. [Answer] # [Python 2](https://docs.python.org/2/), ~~144~~ ~~142~~ 127 bytes ``` i=input() a,b='#.'[::i/4*2-1] i%=4 for x in range(8):y=(int(abs(x-3.5))or 1)+2;y=[y,16-y][i>2];y=[i*4,y][i%2];print(16-y)*a+b*y ``` [Try it online!](https://tio.run/nexus/python2#LcxBCoMwFATQfU4REMn/UdNq01KE9CLiIqFV/iZKasGcPk2ls5x5TCJDfv1sgMzWztBJW/8UhRJLEKoQjEqj2bQEvnPyPFg/v@COPeM50QD5Dax7w95c1BUxuxar7lhp4vTo@mjaWxP/fiCp6zgOVHbjUa0hP3Ar4YewcjKmdP4C "Python 2 – TIO Nexus") Can definitely be golfed further, tips are appreciated :) Golfed off 1 byte thanks to undergroundmonorail! Golfed off many bytes thanks to ovi and Mego because I'm a fool who forgets to not use 4 spaces for codegolf :) [Answer] # PHP, 105 Bytes ``` for(;$i++<8;)echo($p=str_pad)($p("",[16,16-$b=_64333346[$i],8,$b][3&$a=$argn],_M[$a/4]),16,M_[$a/4])." "; ``` [Try it online!](https://tio.run/nexus/php#LYw9D4IwFEV3fkbzYtpYPwgESQpxMAwO6OJWSVOwQpfSPHAy@tcRjXe6N@fmZHvf@cAg9qjQ@B5H61r6LtTpfDkeCiaCe49GNx1F7VpDt3zH9AAaW8ee08yoALtcZqlgpul6Cj4fRlRe39jcKSFchgkPkxXUuUriaE6cSLAVTznUlYwWoPOfruKqlKA3ccXmPy/Vf6xJQMT0lZOrI@LhBjNSsEy8pg8 "PHP – TIO Nexus") [Answer] ## Mathematica, 125 bytes ``` s=Switch;Grid@If[1<#<6,#&,1-#&][s[m=#~Mod~4,0,0,2,1,_,1-{3.4,5}~DiskMatrix~{8,16}]s[m,1,h=Table[Boole[i>8],8,{i,16}],_,1-h]]& ``` Returns a grid using `1` and `0` instead of `.` and `#` respectively. It works using two masks, one circular one and one half-shaded one, and logically combining them to get the appropriate shapes. The two masks are made with `1-{3.4,5}~DiskMatrix~{8,16}` for the circular one, and `Table[Boole[i>8],8,{i,16}]` for the half one. The logic is as follows: ``` output = f(a AND b) where f, a and b are: n | f a b --+----------- 0 | NOT F ◨ 1 | NOT ○ ◧ 2 | 1 T ◨ 3 | 1 ○ ◨ 4 | 1 F ◨ 5 | 1 ○ ◧ 6 | NOT T ◨ 7 | NOT ○ ◨ ``` The logic is simulated with `1`s and `0`s by using multiplication for `AND` and `x -> 1-x` for `NOT`. A bonus (non-ASCII) solution, for 28 bytes: `IconData["MoonPhase",#/4-1]&` ]
[Question] [ # Fibonacci Numbers Fibonacci Numbers start with `f(1) = 1` and `f(2) = 1` (some includes `f(0) = 0` but this is irrelevant to this challenge. Then, for `n > 2`, `f(n) = f(n-1) + f(n-2)`. # The challenge Your task is to find and output the `n`-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer. Also, your answer must compute the 100th term in a reasonable time. # Testcases ``` n result corresponding product (for reference) 1 1 1 2 2 2 3 3 3 4 4 2*2 5 5 5 6 6 2*3 7 8 2*2*2 or 8 8 9 3*3 9 10 2*5 10 12 2*2*3 11 13 13 12 15 3*5 13 16 2*2*2*2 or 2*8 14 18 2*3*3 15 20 2*2*5 16 21 21 17 24 2*2*2*3 or 3*8 18 25 5*5 19 26 2*13 20 27 3*3*3 100 315 3*5*21 ``` # References * [Obligatory OEIS A065108](https://oeis.org/A065108) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~26~~ ~~24~~ ~~23~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆDf÷߀FðḊ¡ 1ç#2+С1¤Ṫ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZEZsO3w5_igqxGw7DhuIrCoQoxw6cjMivDkMKhMcKk4bmq&input=&args=MTAw) ### How it works ``` 1ç#2+С1¤Ṫ Main link. Argument: n (integer) ¤ Combine the three links to the left into a niladic chain. 2 Set the left argument and the return value to 2 (third positive Fibonacci number). 1 Yield 1 (second positive Fibonacci number). +С Compute the sum of the return value and right argument, replacing the return value with the sum and the right argument with the previous return value. Do this n times, collecting all return values in a list. This returns A, the first n Fibonacci numbers greater than 1. 1 Set the return value to 1. ç# Call the helper link with left argument k = 1, 2, 3... and right argument A = [2, 3, 5...] until n of them return a truthy value. Collect the matches in a list. Ṫ Tail; extract the last (n-th) match. ÆDf÷߀FðḊ¡ Helper link. Left argument: k. Right argument: A Ḋ Dequeue; yield r := [2, ..., k]. ð ¡ If r in non-empty, execute the chain to the left. Return k otherwise. ÆD Yield the positive divisors of k. ÷ Divide k by all Fibonacci numbers in A. f Filter; keep divisors that belong to k÷A, i.e., all divisors d for which k÷d belongs to A. ߀ Recursively call the helper link for each kept divisor d, with left argument d and right argument A. F Flatten the result, yielding a non-empty array iff any of the recursive calls yielded a non-empty array or a number. If the left argument is 1, the helper link returns 1, so the array will be non-empty if the consecutive divisions by Fibonacci numbers eventually produced a 1. ``` [Answer] # Julia, 79 bytes ``` !k=any(i->√(5i^2+[4,-4])%1∋k%i<!(k÷i),2:k)^~-k <|(n,k=1)=n>0?n-!k<|-~k:~-k ``` [Try it online!](http://julia.tryitonline.net/#code=IWs9YW55KGktPuKImig1aV4yK1s0LC00XSklMeKIi2slaTwhKGvDt2kpLDI6aylefi1rCjx8KG4saz0xKT1uPjA_bi0hazx8LX5rOn4tawoKZm9yIG4gaW4gWzE6MjA7MTAwXQogICAgQHByaW50ZigiJTNkOiAlM2RcbiIsIG4sIDx8KG4pKQplbmQ&input=) ### Background In [Advanced Problems and Solutions, H-187: Fibonacci is a square](http://www.fq.math.ca/Scanned/10-4/advanced10-4.pdf), the proposer shows that ![Fibonacci/Lucas identity](https://i.stack.imgur.com/NN5DR.png) where **Ln** denotes the **n**th [Lucas number](https://en.wikipedia.org/wiki/Lucas_number), and that – conversely – if ![converse Fibonacci/Lucas identity](https://i.stack.imgur.com/yB3Qn.png) then **n** is a Fibonacci number and **m** is a Lucas number. ### How it works We define the binary operator `<|` for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. When called with only one argument (**n**), `<|` initializes **k** as **1**. While **n** is positive, it subtracts **!k** (**1** if **k** is a product of Fibonacci numbers, **0** if not) from **n** and recursively calls itself, increments **k** by **1**. Once **n** reaches **0**, the desired amount of products have been found, so `<|` returns the previous value of **k**, i.e., **~-k = k - 1**. The unary operator `!`, redefined as a test for Fibonacci number products, achieves its task as follows. * If **k = 1**, **k** is a product of Fibonacci numbers. In this case, we raise the return value of `any(...)` to the power **~-k = k - 1 = 0**, so the result will be **1**. * If **k > 1**, the result will be the value of `any(....)`, which will return **true** if and only if the predicate `√(5i^2+[4,-4])%1∋k%i<!(k÷i)` returns **true** for some integer **i** such that **2 ≤ i ≤ k**. The chained conditions in the predicate hold if `k%i` belongs to `√(5i^2+[4,-4])%1` and `k%i` is less than `!(k÷i)`. + `√(5i^2+[4,-4])%1` takes the square root of **5i2 + 4** and **5i2 - 4** and computes their residues modulo **1**. Each modulus is **0** if the corresponding number is a perfect square, and a positive number less than **1** otherwise. Since `k%i` returns an integer, it can only belong to the array of moduli if **k % i = 0** (i.e., **k** is divisible by **i**) and at least one among **5i2 + 4** and **5i2 - 4** is a perfect square (i.e., **i** is a Fibonacci number). + `!(k÷i)` recursively calls **1** with argument **k ÷ i** (integer division), which will be greater than **0** if and only if **k ÷ i** is a product of Fibonacci numbers. By induction, **!** has the desired property. [Answer] ## Python, 90 bytes ``` f=lambda n,a=2,b=3:n<2or n%a<f(n/a)or n-a>0<f(n,b,a+b) g=lambda k,n=1:k and-~g(k-f(n),n+1) ``` The main function `g` outputs the `k`th Fibonacci product, 1-indexed. It computes `g(100)` as `315` almost instantly. It goes so with a general recursive recipe of counting up numbers `n` looking for `k` instances that satisfy the function `f`. Each such instance lowers the required count `k` until it reaches `0`. The auxiliary function `f` tests a number for being a Fibonacci product. It recursively generates the Fibonacci numbers in its optional arguments `a` and `b`. It outputs "yes" if any of the following is true: * `n<2`. This implies `n==1`, the trivial product) * `n%a<f(n/a)`. This requires `n%a==0` and `f(n/a)==True`, i.e. that `n` is a multiple of the Fibonacci number `a`, and removing this factor of `a` still yield a Fibonacci product. * `n-a>0<f(n,b,a+b)`, equivalent to `n>a and f(n,b,a+b)`. Checks that the current Fibonacci number being tested isn't at least `n`, and some greater Fibonacci number works. Thanks to Dennis for 2 saving bytes using the inequality short-circuit instead of `and`. The function `g` can be one byte shorter as ``` lambda k:filter(f,range(k*k+1))[k] ``` if `g(k)` is always at most `k*k`, which I'm not sure is asymptotically true. A bound of `2**k` suffices, but then `g(100)` takes too long. Maybe instead the recursive of `g` can be done in `f`. [Answer] # [Perl 6](http://perl6.org), ~~95~~ 93 bytes ``` ~~{(1..\*).grep({$/=$\_;map {->{$/%$\_||($//=$\_);$/}...\*!%%$\_;0},reverse 2,3,&[+]...\*>$\_;2>$/})[$\_]}~~ {(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]} ``` ( 0 based index ) ### Test: ``` my &fib-prod = {(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]} say fib-prod 0 ..^ 20; # (1 2 3 4 5 6 8 9 10 12 13 15 16 18 20 21 24 25 26 27) say time-this { say fib-prod 100 -1; }; # 315 # 1.05135779 sub time-this (&code) { my $start = now; code(); now - $start; } ``` ### Explanation: ``` { (1..*).grep( { $/ = $_; # copy the input ($_) to $/ map { # map used just for side effect ->{ $/ % $_ # if $/ is divisible by the current fib factor || ($/ /= $_) # divide it out once ; # return the current value in $/ $/ } ... # repeat until that returns: * !%% $_ # something that is not divisible by the current fib factor ;0 }, # the possible fibonacci factors plus one, reversed # ( the extra is to save one byte ) reverse 2,3,&[+] ... *>$_; # is the end result of factoring equal to 1 # ( for the grep above ) 2 > $/ } )[ $_ ] # get the value at 0-based index } ``` [Answer] # Python 3, ~~175~~ ~~170~~ 148 bytes *Thanks to @Dennis for -22 bytes* ``` j=x=int(input()) y=1,1 exec('y+=y[-2]+y[-1],;'*x) i=c=0 while c<x: if j>=x:j=0;i+=1;t=i if t%y[~j]<1:t/=y[~j];j-=1 if t<2:c+=1;j=x j+=1 print(i) ``` Takes input from STDIN and prints to STDOUT. This is one-indexed. Computing the 100th term takes roughly a tenth of a second. **How it works** ``` j=x=int(input()) Get term number x from STDIN and set Fibonacci number index j to x to force initialisation of j later y=1,1 Initialise tuple y with start values for Fibonacci sequence exec('y+=y[-2]+y[-1],;'*x) Compute the Fibonacci sequence to x terms and store in y i=c=0 Initialise test number i and term counter c while c<x: Loop until x th term is calculated if j>=x:j=0;i+=1;t=i Initialise Fibonacci number index j, increment i and initialise temp variable t for looping through all j for some i. Executes during the first pass of the loop since at this point, j=x if t%y[~j]<1:t/=y[~j];j-=1 Find t mod the j th largest Fibonacci number in y and if no remainder, update t by dividing by this number. Decrementing j means that after a later increment, no change to j occurs, allowing for numbers that are divisible by the same Fibonacci number more than once by testing again with the same j if t<2:c+=1;j=x If repeated division by ever-smaller Fibonacci numbers leaves 1, i must be a Fibonacci product and c is incremented. Setting j equal to x causes j to be reset to 0 during the next loop execution j+=1 Increment j print(i) i must now be the x th Fibonacci product. Print i to STDOUT ``` [Try it on Ideone](http://ideone.com/gpUFCK) [Answer] # Python 2, ~~120~~ 107 bytes ``` g=lambda k:1/k+any(k%i==0<g(k/i)for i in F) F=2,3;k=0;n=input() while n:F+=F[k]+F[-1],;k+=1;n-=g(k) print k ``` Test it on [Ideone](http://ideone.com/MjvRR5). ### How it works We initialize **F** as the tuple **(2, 3)** (the first two Fibonacci number greater than **1**), **k** as **0** and **n** as an integer read from STDIN. While **n** is positive, we do the following: * Append the next Fibonacci number, computed as **F[k] + F[-1]**, i.e., the sum of the last two elements of **F** to the tuple **F**. * Increment **k**. * Subtract **g(k)** from **n**. **g** returns **1** if and only if **k** is a product of Fibonacci numbers, so once **n** reaches **0**, **k** is the **n**th Fibonacci number and we print it to STDOUT. **g** achieves its purpose as follows. * If **k** is **1**, it is a product of Fibonacci numbers, and `1/k` makes sure we return **1**. * If **k** is greater than **1**, we call `g(k/i)` recursively for all Fibonacci numbers **i** in **F**. `g(k/i)` recursively tests if **k / i** is a Fibonacci number product. If `g(k/i)` returns **1** and **i** divides **k** evenly, **k % i = 0** and the condition `k%i<g(k/i)` holds, so **g** will return **1** if and only if there is a Fibonacci number such that **k** is the product of that Fibonacci number and another product of Fibonacci numbers. [Answer] # JavaScript (ES6), 136 Quite slow golfed this way, computing term 100 in about 8 seconds in my PC. ``` (n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a') ``` *Less golfed* and faster too (avoiding `eval`) ``` n=>{ F=i=> i>1 ? F(i-1)+F(i-2) : i+1; // recursive calc Fibonacci number K=(n,i=1,d,x)=>{ // recursive check divisibility for(; (d=F(i++))<=n && !(x=!(n%d)&&K(n/d)); ); return x||n<2 }; for(a=0; n; ) K(++a) && --n; return a } ``` **Test** ``` X=(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a') function test() { var i=+I.value O.textContent=X(i) } test() ``` ``` <input id=I value=100 > <button onclick="test()">Go</button><pre id=O></pre> ``` [Answer] ## Haskell, 123 bytes ``` f=2:scanl(+)3f m((a:b):c)=a:m(b?(a#c)) v#((a:b):c)|v==a=b?(v#c) _#l=l y?(z:e)|y>z=z:y?e a?b=a:b l=1:m[[a*b|b<-l]|a<-f] (l!!) ``` Very lazy, much infinite! Possibly not the shortes way, but I had to try this approach, a generalization of a quite well known method to compute the list of hamming numbers. `f` is the list of fibonacci numbers starting from 2. For brevity, let's say that a lol (list of lists) is an infinite list of ordered infinite lists, ordered by their first elements. `m` is a function to merge a lol, removing duplicates. It uses two infix helper functions. `?` inserts an infinite sorted list into a lol. `#` removes a value from a lol that may appear as head of the first lists, reinserting the remaining list with `?`. Finally, `l` is the list of numbers which are products of fibonacci numbers, defined as 1 followed by the merge of all the lists obtained by multiplying `l` with a fibonacci number. The last line states the required function (as usual without binding it to a name, so don't copy it as is) using `!!` to index into the list, which makes the function 0-indexed. There is no problem computing the 100th or 100,000th number. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes Note that Husk is newer than this challenge. However it and the most useful function for this golf (`Ξ`) were not created with this challenge in mind. ``` S!!Ṡ¡ȯuΞIṪ*İf ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//9TISHhuaDCocivdc6eSeG5qirEsGb///8xMDA "Husk – Try It Online") **More efficient version for 14 bytes:** [Try it online!](https://tio.run/##ASUA2v9odXNr///ihpJVTSHhuaDCocivdc6eSeG5qirEsGb///8xMDAw) [Answer] # Python 2, ~~129~~ ~~128~~ ~~125~~ ~~123~~ 121 bytes ``` g=lambda k:1/k|any(abs(round(5**.5*i)**2-5*i*i)==4>k%i<g(k/i)for i in range(k+1)) f=lambda n,k=1:n and f(n-g(k),k+1)or~-k ``` Test it on [Ideone](http://ideone.com/zjkUa6). ]
[Question] [ Given a number \$n\$, write a program that finds the smallest base \$b ≥ 2\$ such that \$n\$ is a palindrome in base \$b\$. For example, an input of \$28\$ should return the base \$3\$ since \$28\_{10} = 1001\_3\$. Although \$93\$ is a palindrome in both base \$2\$ and base \$5\$, the output should be \$2\$ since \$2<5\$. ## Input A positive integer \$n < 2^{31}\$. ## Output Return the smallest base \$b ≥ 2\$ such that the base \$b\$ representation of \$n\$ is a palindrome. Do not assume any leading zeros. Samples (input => output): > > \$11 \to 10\$ > > > \$32 \to 7\$ > > > \$59 \to 4\$ > > > \$111 \to 6\$ > > > ## Rules The shortest code wins. [Answer] ### GolfScript, 20 characters ``` ~:x,2>{x\base.-1%=}? ``` A different approach with GolfScript other than [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'. It avoids the costly explicit loop in favour of a *find* operator. [Try online](http://golfscript.apphb.com/?c=OyIzMiIKCn46eCwyPnt4XGJhc2UuLTElPX0%2FCg%3D%3D&run=true). ``` ~:x # interpret and save input to variable x ,2> # make a candidate list 2 ... x-1 (note x-1 is the maximum possible base) { # {}? find the item on which the code block yields true x\ # push x under the item under investigation base # perform a base conversion .-1% # make a copy and reverse it = # compare reversed copy and original array }? ``` [Answer] ## Mathematica, ~~67~~ 66 bytes ``` g[n_]:=For[i=1,1>0,If[(d=n~IntegerDigits~++i)==Reverse@d,Break@i]] ``` Can't really compete with GolfScript here in terms of code size, but the result for 232 is basically returned instantly. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~12~~ 9 bytes Unless I've missed a trick (it's late!), this should work for all numbers up to and including at least `2**53-1`. In my (admittedly limited and entirely random) testing, I've gotten results up to base ~~`11601`~~ `310,515`(!) so far. Not too shabby when you consider JavaScript only natively supports bases `2` to `36`. ``` @ìX êê}a2 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QOxYIOrqfWEy&input=MTIzNDU2Nzg5MDk=) * Thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) for pointing out something new to me that saved 3 bytes and increased the efficiency considerably. --- ## Explanation Implicit input of integer `U`. ``` @ }a2 ``` Starting with `2`, return the first number that returns true when passed through the following function, with `X` being the current number ``` ìX ``` Convert `U` to an array of base `X` digits. ``` êê ``` Test if that array is a palindrome. [Answer] # [CJam](http://sourceforge.net/p/cjam/wiki/Home/), 19 bytes / GolfScript, 23 bytes ``` q~:N;1{)_N\b_W%=!}g ``` or ``` ~:N;1{).N\base.-1%=!}do ``` Try it online: * [CJam](http://cjam.aditsu.net/ "CJam interpreter") * [GolfScript](http://golfscript.apphb.com/?c=IjkzIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2BOk47MXspLk5cYmFzZS4tMSU9IX1kbw%3D%3D "Web GolfScript") ### Examples ``` $ cjam base.cjam <<< 11; echo 10 $ cjam base.cjam <<< 111; echo 6 $ golfscript base.gs <<< 11 10 $ golfscript base.gs <<< 111 6 ``` ### How it works ``` q~:N; # Read the entire input, interpret it and save the result in “N”. 1 # Push 1 (“b”). { # ) # Increment “b”. _N\ # Duplicate “b”, push “N” and swap. b # Push the array of digits of “N” in base “b”. _W% # Duplicate the array and reverse it. =! # Compare the arrays. }g # If they're not equal, repeat the loop. ``` For GolfScript, `q~` is `~`, `_` is `.`, `b` is `base`, `W` is `-1` and `g` is `do`. [Answer] ## JavaScript, 88 bytes ``` f=function(n){for(a=b='+1';a^a.split('').reverse().join('');a=n.toString(++b));return+b} ``` **Ungolfed:** ``` f = function(n) { for(a = b = '+1'; // This is not palindrome, but equals 1 so we have at least one iteration a ^ a.split('').reverse().join(''); // test a is palindrome a = n.toString(++b)); return+b } ``` [Answer] # J - 28 char ``` #.inv~(-.@-:|.@)(1+]^:)^:_&2 ``` Explained: * `#.inv~` - Expand left argument to the base in the right argument. * `(-.@-:|.@)` - Return 0 if the expansion is palindromic, and 1 otherwise. * `(1+]^:)` - Increment the right argument by one if we returned 1, else take no action. * `^:_` - Repeat the above incrementing until it takes no action. * `&2` - Prepare the right argument as 2, making this a function of one argument. Examples: ``` #.inv~(-.@-:|.@)(1+]^:)^:_&2 (28) 3 #.inv~(-.@-:|.@)(1+]^:)^:_&2 every 93 11 32 59 111 NB. perform on every item 2 10 7 4 6 #.inv~(-.@-:|.@)(1+]^:)^:_&2 every 1234 2345 3456 4567 5678 6789 22 16 11 21 31 92 ``` [Answer] # Javascript, 105 bytes ``` function f(n){for(var b=2,c,d;d=[];++b){for(c=n;c;c=c/b^0)d.push(c%b);if(d.join()==d.reverse())return b}} ``` **JSFiddle:** <http://jsfiddle.net/wR4Wf/1/> Note that this implementation also works correctly for large bases. For example, `f(10014)` returns 1668 (10014 is 66 in base 1668). [Answer] # Bash + coreutils, 100 bytes ``` for((b=1;b++<=$1;)){ p=`dc<<<${b}o$1p` c=tac ((b<17))&&c=rev [ "$p" = "`$c<<<$p`" ]&&echo $b&&exit } ``` Uses `dc` to do base formatting. The tricky thing is `dc`'s format is different for n > 16. Testcases: ``` $ ./lowestbasepalindrome.sh 11 10 $ ./lowestbasepalindrome.sh 32 7 $ ./lowestbasepalindrome.sh 59 4 $ ./lowestbasepalindrome.sh 111 6 $ ``` [Answer] ## R, ~~122~~ 95 bytes ``` function(n)(2:n)[sapply(2:n,function(x){r={};while(n){r=c(n%%x,r);n=n%/%x};all(r==rev(r))})][1] ``` **Three-year old solution at 122 bytes:** ``` f=function(n)(2:n)[sapply(sapply(2:n,function(x){r=NULL;while(n){r=c(n%%x,r);n=n%/%x};r}),function(x)all(x==rev(x)))][1] ``` With some explanations: ``` f=function(n)(2:n)[sapply( sapply(2:n,function(x){ #Return the decomposition of n in bases 2 to n r=NULL while(n){ r=c(n%%x,r) n=n%/%x} r } ), function(x)all(x==rev(x))) #Check if palindrome ][1] #Return the first (i. e. smallest) for which it is ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 9 bytes ``` ḟoS=↔`B⁰2 ``` Thanks @Zgarb for -2! [Try it online!](https://tio.run/##ASsA1P9odXNr/8K24oKH/@G4n29TPeKGlGBC4oGwMv///1sxMSwzMiw1OSwxMTFd "Husk – Try It Online") ### Explanation ``` ḟ( )2 -- find least number ≥ 2 that satisfies: `B⁰ -- convert input to base (` flips arguments) S=↔ -- is palindrome (x == ↔x) ``` [Answer] # [Python 2](https://docs.python.org/2/), 79 bytes ``` def f(n,b=2): l=[];m=n while m:l+=m%b,;m/=b return(l==l[::-1])*b or f(n,b+1) ``` [Try it online!](https://tio.run/##JcxBCoMwEEDR/ZxiNoVMtZRJ6aKROYm4CY0YSEYJEenpU8H9/2/71WVV29o3zDgb7b1YcoBJxmnIooDHElPA7FIn@eb7IT/FA5ZQ96ImiaTRuQdPdPe4lovomNq18UmpRN32aghwK1GrORuixgwvC@8PMPMf "Python 2 – Try It Online") *-1 bytes thanks to 97.100.97.109* I'm not sure what input/output format the question wanted. I wrote a function. The code uses an optional input `b` to track the current base it's testing. The `while` loops converts the number to a list of digits in base `b`. The last line returns `b` if `l` is a palindrome, and recursively tries the next `b` otherwise. The index-by-Boolean trick doesn't work here because it would cause both options to be evaluated regardless of the Boolean, and the recursion would never bottom out. [Answer] ### Note: Pyth is newer than this question, so this answer is not eligible to win. # Pyth, 10 bytes ``` fq_jQTjQT2 ``` [Try it here.](https://pyth.herokuapp.com/?code=fq_jQTjQT2&input=111&debug=0) [Answer] # Scala, 83 bytes ``` def s(n:Int)=(for(b<-2 to n;x=Integer.toString(n,b);if(x==x.reverse))yield(b)).min ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ¼[¼¾вÂQ# ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0J7oQ3sO7buw6XBToPL//4ZGxiamZuYWlgYA) [Answer] # [Perl 5](https://www.perl.org/), 84 + 1 (-p) = 85 bytes ``` $\=1;{++$\;my@r;$n=$_;do{push@r,$n%$\}while$n=int$n/$\;@t=@r;map$_-pop@t&&redo,@r}}{ ``` [Try it online!](https://tio.run/##DcpRCoMwDADQy2T@qAw/BoNSyEEKIliwoEmIFRmlVzfr93sSdf@YQfCTK30PwR0/VAfkYXYrF7nODXUAekGo95b22ChRBnq3i9m3fCwC8ygsmLtO48oDaq3F7Puw5MR02ih/ "Perl 5 – Try It Online") [Answer] # JavaScript 72 bytes ``` F=(n,b=2)=>eval(`for(t=n,a=c="";t;t=t/b|0)a=t%b+a,c+=t%b`)^a?F(n,b+1):b console.log(F(11) == 10) console.log(F(32) == 7) console.log(F(59) == 4) console.log(F(111) == 6) ``` [Answer] # Mathematica 42 bytes A variation of Martin Ender's entry. Makes use of `IntegerReverse` (made available in version 10.3) which dispenses with `IntegerDigits`. ``` (i=2;While[#~IntegerReverse~i !=#,i++];i)& ``` [Answer] # Java 8, 103 bytes ``` n->{int b=1,l;for(String s;!(s=n.toString(n,++b)).equals(new StringBuffer(s).reverse()+""););return b;} ``` **Explanation:** [Try it here.](https://tio.run/##hY8/T8MwEMX3foqj01lpLQXEgKwwsDHQpSNicNxL5eKeg/8EoSqfPbhNGVGlu@Hee9Lv3kEPeu174sPuczJOxwhv2vJpAWA5Uei0Idicz4sABl@LvKcALFRRx7JlYtLJGtgAQwMTr59P53Db1CunOh9wm4LlPUR1h7FhmfwsIK@qqhVC0lfWLiLTN8zOS@46ChiFDDRQiISiWi6FEipQyoGhVeOkZnifW1fg1x8Gb3dwLB2u0PcP0GIusP2JiY7S5yT7YiXHyNJgXYtLl38DD/c3Ao9PNwL1H2NcjNMv) ``` n->{ // Method with integer as both parameter and return-type int b=1, // Base-integer, starting at 1 l; // Length temp integer for(String s; // Temp String !(s=n.toString(n,++b)) // Set the String to `n` in base `b+1` // (by first increase `b` by 1 using `++b`) .equals(new StringBuffer(s).reverse()+""); // And continue looping as long as it's not a palindrome ); // End of loop return b; // Return the resulting base integer } // End of method ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 2b@ŒḂ¥1# ``` [Try it online!](https://tio.run/##y0rNyan8/98oyeHopIc7mg4tNVT@f7j9UdMaoJiFjoKlsY6CoaGOgrGRjoKpJYhtCAA "Jelly – Try It Online") ## How it works ``` 2b@ŒḂ¥1# - Main link. Takes an integer n on the left ¥ - Group the previous 2 links into a dyad f(b, n): b@ - Convert n to base b ŒḂ - Is palindrome? 2 1# - Count up b = 2, 3, 4, ... returning the first b that's true under f(b, n) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 43 bytes -1 byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) ``` ->n{(2..).find{d=n.digits _1 d==d.reverse}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3tXXt8qo1jPT0NPXSMvNSqlNs8_RSMtMzS4oV4g25UmxtU_SKUstSi4pTa2uhWswLFNyiDQ1jFRSUFQwNuEA8YyMwT8EczDO1hPBMuCAqgUqBPDOI9gULIDQA) ]
[Question] [ A friend has an add-on card in their computer which generates a perfectly random number from 1 to 5 inclusive. Unfortunately, they spilt cola on it somehow, and it now generates only 2's for all numbers from 1 to 4. Luckily the randomness is preserved, but 2 has a probability of 80% and 5 has a probability of 20%, and there are no 1's, 3's or 4's generated. Using this random source (call it `BrokenRand()` or something similar), write a working random number generator which produces numbers from 1 to 5 each with an equal 20% probability with the same perfect randomness as the original source. Shortest program wins. Bonus points awarded for the minimum number of calls to `BrokenRand` impartially by a demographically-selected customer service focus consultancy, broken down by age and sex - i.e. me. [Answer] ## JavaScript - 69 characters This uses the [von Neumann extractor](http://en.wikipedia.org/wiki/Randomness_extractor#Von_Neumann_extractor) to generate unbiased bits; the general algorithm is also described on the [HotBits website](http://www.fourmilab.ch/hotbits/how3.html). Three bits are used to form a number from 0 to 7. All numbers 5 and above are discarded, and 1 is added to each of the rest before they are printed. I made a [simulation to show that this is not heavily biased](http://jsfiddle.net/Gf3fC/10/). You need to provide your own function `r()` to access the RNG. ``` for(;;v<5&&alert(v+1))for(v=i=0;i<3;a-b&&(v*=2,v+=a<b,i++))b=r(a=r()) ``` [Answer] ## scala 79 chars: ``` // preparation: val r = util.Random def defektRNG = if (r.nextInt (5) == 0) 5 else 2 (1 to 20).foreach (_ => print (" " + defektRNG)) // first impression: // 2 2 2 2 2 2 2 5 2 2 5 2 2 2 5 2 2 2 2 2 def rnd : Int = { val k = (1 to 5).map (_ => defektRNG) if (k.sum == 13) k.findIndexOf (_ == 5) + 1 else rnd } // first impression: (1 to 20).foreach (_ => print (" " + rnd)) // 3 3 2 3 5 2 2 5 1 1 3 4 3 2 5 3 3 1 5 4 // control: (1 to 50000).map (_ => rnd).groupBy (identity) .map (_._2.length) // scala.collection.immutable.Iterable[Int] = List(10151, 9997, 9971, 9955, 9926) ``` Now for the real golf, defektRNG alias brokenRand is renamed to b. ``` def r:Int={val k=(1 to 5).map(_=>b) if(k.sum==13)k.findIndexOf(_==5)+1 else r} ``` How it works: Most often, b returns a sequence of 2s. But if you do 5 calls to b, you will very often end with a result of 4x2 and 1x5, it is the second most probable event, and can be 5-2-2-2-2, 2-5-2-2-2, 2-2-5-2-2, 2-2-2-5-2 and 2-2-2-2-5. These have in common, that the sum is 4\*2+5=13. The index of the first five can be used to define a valid random number. If there is more or less than one 5, a sum greater or lower 13, repeat. A counter in 'rnd' aka 'r' can show how many calls are necessary in average to produce the numbers. There are 121 200 calls to r for 50 000 random numbers, which is not impressing. :) [Answer] ## [><> (Fish)](http://esolangs.org/wiki/Fish) - 55 bytes Updated to use the same algorithm as @user unknown in his scala answer ``` <v?=d+&:i&+&:i&+&:i&+&:i&:i 0 >1+$5(?vnao; ^ < ``` It expects the broken generator to be connected to stdin; here's the [python script I used](https://gist.github.com/968548). The code matches the current Fish spec, but I used a [modified version](https://gist.github.com/968535) of the old interpreter. ```` bash:$ for i in $(seq 1000); do ./bad_rand.py | ./myfish.py rand.fish; done >res.txt bash:$ for i in $(seq 5); do echo -n "$i : "; grep -c $i res.txt; done 1 : 193 2 : 204 3 : 198 4 : 206 5 : 199 ```` I'd do a bigger sample but it's slow. [Answer] # GolfScript, 23 bytes Late answer, but since this just happened to pop up on the front page... ``` 0{;[{r}5*].5?)\5-,4-}do ``` Uses the same algorithm as [user unknown's Scala solution](https://codegolf.stackexchange.com/a/2567). Assumes that the biased random number generator is given as a GolfScript subroutine named `r`; you can define a suitable biased RNG yourself e.g. as: ``` {5rand!3*2+}:r; ``` [Here's a quick test demonstrating lack of bias.](http://golfscript.apphb.com/?c=IyBEZWZpbmUgYmlhc2VkIFJORzoKezVyYW5kITMqMit9OnI7CgojIFJ1biBkZS1iaWFzZXIgMTAwIHRpbWVzLCBjb2xsZWN0IHJlc3VsdHM6Clt7IAogICAgMHs7W3tyfTUqXS41PylcNS0sNC19ZG8KfTEwMCpdOmE7CgojIENvdW50IGFuZCBwcmludCBmcmVxdWVuY3kgb2YgZWFjaCBvdXRjb21lOgphLiZ7Wy5hLkAtLSxdcH0v) Unfortunately, the online GolfScript server is kind of slow, so I had to cut the demonstration down to just 100 samples to make it complete on time. If running the test locally with the [GolfScript interpreter](http://www.golfscript.com/golfscript/), try increasing the `100*` to `1000*` or even `10000*`. (The GolfScript server also sometimes randomly freezes and times out anyway. If this happens for you, trying again usually solves it. It happens with other code too, and only happens on the server, not on my own computer, so I'm confident that it's a problem with the server and not with my code.) [Answer] # Python 3, 119 bytes ``` def F(): l=[] while 1: l=[] for i in range(5): l.append(B()) if l.count(5) == 1: return l.index(5) ``` Could be golfed to below 100 probably, but it's decent for now. Have no idea how a Python answer (or one with this method) hasn't popped up. Assumes the broken random function is B. ]
[Question] [ **Challenge:** I want to know about the real roots of polynomials. As a pure mathematician, I care about the existence of such roots, rather than their numeric values. The challenge is to write the shortest program that takes a polynomial, of degree at most 4, and simply returns how many distinct real roots said polynomial has. Polynomials with degree 4 or less have the unique property that there exist closed forms (such as the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula)), which give all their roots. You can google these forms or find some useful related information in the appendix. **Input:** the coefficients of a polynomial. For simplicity, we shall only care about polynomials with integer coefficients. You may input this as a list, get the coefficients one at a time, or use any other reasonable method. You may, for example, require polynomials of degree d to inputted as lists of length d+1. You should specify how you convert a polynomial of degree at most 4 into a valid input. **Output:** the number of distinct real roots of said polynomial. (meaning roots with multiplicity are only counted once) You must output one of the integers 0,1,2,3,4 for valid polynomials, and trailing spaces are completely fine. (the special case of the polynomial, \$P(x) = 0\$, is discussed in the scoring section) **Examples:** in these examples, we represent a polynomial, \$P\$, as a list L, where `L[i]` contains the coefficient of \$x^i\$ in \$P\$. (with index starting at 0) \$P(x) = 1\$, `input: [1], output: 0` \$P(x) = 1+2x\$, `input: [1,2], output: 1` \$P(x) = 1+x^2\$, `input: [1,0,1], output: 0` \$P(x) = 1+x+x^2+x^3 = (x+1)(1+x^2)\$, `input: [1,1,1,1], output: 1` \$P(x) = 2+3x+x^2 = (x+2)(x+1)\$, `input: [2,3,1], output: 2` \$P(x) = 1-2x+x^2 = (x-1)^2\$, `input: [1,-2,1], output: 1` **Scoring:** *-5 bytes* if the polynomial, \$P(x) = 0\$, outputs a representation of infinity, such as: the infinity float in python, the Unicode symbol `∞`, or a string that can be mathematically interpreted to evaluate to infinity, like "1/0". (otherwise, you don't need to handle this case) Otherwise, shortest code wins. (however I am personally quite interested in seeing answers which don't rely on built-in root finders) **Appendix: Closed Forms** Starting with the basics: *Degree 0:* \$P(x) = a\$, roots: none, (or all reals, if a = 0) *Degree 1:* \$P(x) = ax+b\$, roots: \$x=-b/a\$ *Degree 2:* \$P(x) = ax^2+bx+c\$, roots: \$x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\$ Then, we have the harder ones. For these, it becomes quite verbose to state the closed forms. I've paraphrased some ways you can deduce the number of roots by considering discriminants, you may also seek to find the closed forms of the roots. *Degree 3:* From [Wikipedia](https://en.wikipedia.org/wiki/Cubic_equation#Nature_of_the_roots). \$ P(x) = ax^3+bx^2+cx+d\$. We define the discriminant as \$\Delta = 18abcd -4b^3d+b^2d^2-4ac^3-27a^3d^2\$. If \$\Delta > 0\$ then there are 3 distinct roots, if \$\Delta = 0\$, then there are two distinct real roots, otherwise then \$ \Delta < 0\$ and there is only one real root. *Degree 4:* From [Wikipedia](https://en.wikipedia.org/wiki/Quartic_function#Nature_of_the_roots).\$ P(x) = ax^4+bx^3+cx^2+dx+e\$. We define the discriminant as $$\begin{align} \Delta\ =\ &256 a^3 e^3 - 192 a^2 b d e^2 - 128 a^2 c^2 e^2 + 144 a^2 c d^2 e - 27 a^2 d^4 \\ &+ 144 a b^2 c e^2 - 6 a b^2 d^2 e - 80 a b c^2 d e + 18 a b c d^3 + 16 a c^4 e \\ &- 4 a c^3 d^2 - 27 b^4 e^2 + 18 b^3 c d e - 4 b^3 d^3 - 4 b^2 c^3 e + b^2 c^2 d^2 \end{align}$$ If \$\Delta > 0\$ then there are two distinct real roots. Otherwise things get more complicated. Defining \$P = 8ac - 3b^2\$, \$D = 64 a^3 e - 16 a^2 c^2 + 16 a b^2 c - 16 a^2 bd - 3 b^4\$, then if \$ \Delta < 0 \$ and \$ P < 0\$ and \$ D < 0 \$ then there are 4 distinct real roots. Otherwise, if \$ \Delta < 0\$, there are 2 distinct real roots. Finally, if \$\Delta = 0\$, we define \$\Delta\_0=c^2-3bd+12ae\$ and \$R= b^3+8da^2-4abc\$. If \$D =0\$, then: * \$ P < 0\$ implies two distinct real roots * \$ P > 0\$ implies zero distinct real roots * \$P = 0\$ implies four distinct real roots Else, if \$\Delta\_0 = 0\$, then there are two distinct real roots. Else, if \$P<0\$ and \$D <0\$ there are three distinct real roots. Else, there are one real root. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~285 ... 248~~ 247 - 5 = 242 bytes *Fixed a bug and saved a couple of bytes by borrowing [@Grimmy's method](https://codegolf.stackexchange.com/a/200156/58563) for the final count of the real roots* Expects the coefficients from highest to lowest. This is an implementation of [Sturm's theorem](https://en.wikipedia.org/wiki/Sturm%27s_theorem#The_theorem), and therefore works for **any degree**, which might be a bit overkill for this challenge. ``` p=>1/p[1]?(h=(A,[[c,...q],[...p]]=A,n=q.length)=>n?h([(g=i=>1/p[(j=i)+n]?g(i+1,q.map(v=>p[++j]-=v*p[i],p[i]/=c)):p.slice(-n).map(v=>-v))(0),...A]):A)([p.flatMap(v=>1/p[++i]?(p.length-i)*v:[],i=k=s=0),p]).map(p=>s+=Math.sign(k*(k=p[0])))|s:1/!!+p-1 ``` [Try it online!](https://tio.run/##hdDdboIwFAfw@z1FvWvtBxTYjcnR8AAmu2@6hDCEKit1EMKSvbuDqXNq45qmvWj76/@cbdZnbf5hXMdt81YcNnBwsJSBU1KvcAU4ZUrlTAix10yNm9MaUmZhL@rCll1FYGlXFVa4BHN8iLdgCLV6VWJDJduL98zhHpZOUbrVHPq5U0azaQkgJ2ThRFubvMDckvNd3hOCQzL9m2qySAlWTmzqrFsfz6d/KDVjRHfKwQ2Z9wulmYEdtDC@dfrIjfW0FNZZV4nWlBbv5ngHToWaEPLVLmQwm1HH5SFvbNvUhaibEm/wzzm6H0GAXvBAIES@YezGWNN9Pt1g8jEmvVh4q0QM@aCzEg3UA8m7LAyFHuisDK@Rhwk9ymleQRclppN0HcmXJWYoepQlHmh0nSXyKNzTmz8Kv@@N9Fc0toZP3i92UZKxopgPXP6TRR6J5CQlk3RRnkcl4VN/kinYwBOE4sM3 "JavaScript (Node.js) – Try It Online") ### How? We first test whether the degree is \$0\$, which is an edge case: ``` p => // p[] = polynomial coefficients 1 / p[1] ? // if p[1] is defined: ... // general case : // else: 1 / !!+p - 1 // return +Infinity if p[0] = 0, or 0 otherwise ``` For the general case, we use the recursive function \$h\$ to build the [Sturm sequence](https://en.wikipedia.org/wiki/Sturm%27s_theorem) of polynomials in reverse order \$[p\_n,...,p\_1,p\_0]\$, where \$p\_0\$ is the input and \$p\_n\$ is of degree \$0\$. The initial call to \$h\$ is performed with \$[q,p]\$ where \$q\$ is the derivative of \$p\$ computed as follows: ``` p.flatMap(v => // for each coefficient v in p[]: 1 / p[++i] ? // increment i; if p[i] is defined: (p.length - i) * v // multiply v by the exponent at this position - 1 : // else: [], // this is the constant term: discard it i = k = s = 0 // start with i = 0 (k and s are used later) ) // end of flatMap() ``` Below is the definition of \$h\$: ``` h = ( // h is a recursive function taking: A, // A[] = current Sturm sequence, which is split into: [[c, ...q], [...p]] // c = 1st coefficient of the divisor = A, // q[] = other coefficients of the divisor // p[] = copy of the dividend n = q.length // n = number of coefficients in q[] ) => // n ? // if n is not equal to 0: h([g(0), ...A]) // preprend a new polynomial to A[], using g (see below) : // else: A // end of recursion: return A[] ``` Where \$g\$ computes the remainder of \$p/q\$, multiplied by \$-1\$: ``` g = i => // g is a recursive function taking a counter i 1 / p[(j = i) + n] ? // copy i into j; if p[j + n] is defined: g( // do a recursive call: i + 1, // with i + 1 q.map(v => // for each coefficient v in q[]: p[++j] -= // increment j; subtract from p[j]: v * p[i], // v multiplied by p[i] p[i] /= c // start by normalizing p[i], using c ) // end of map() ) // end of recursive call : // else: p.slice(-n) // end of recursion: isolate the remainder .map(v => -v) // and invert all signs ``` Finally, we compute the number of real roots by applying the following code to the Sturm sequence: ``` .map(p => // for each polynomial p in the sequence: s += Math.sign( // add to s the sign of: k * // multiply the previous leading coefficient (k = p[0]) // by the leading coefficient of p (and update k) ) // NB: k and s are initialized to 0 earlier in the code ) | s // end of map(); yield s ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes ``` gЦƶ‚í룬/D₂0š*₂-2£δ*˜0š2ôO+(¦¦}€нüP.±O ``` [Try it online!](https://tio.run/##AVQAq/9vc2FiaWX//2fFoMKmxrbigJrDrc67wqPCrC9E4oKCMMWhKuKCgi0ywqPOtCrLnDDFoTLDtE8rKMKmwqZ94oKs0L3DvFAuwrFP//9bMiwgMywgMV0 "05AB1E – Try It Online") 05AB1E doesn't have a built-in to get the roots of a polynomial, so we use [Sturm's theorem](https://en.wikipedia.org/wiki/Sturm%27s_theorem#The_theorem) ``` g # length of the input (degree + 1) Š # push two more copies of the input ¦ # drop the first coefficient ƶ # multiply each coefficient by its 1-based index # => this is the derivative of the input ‚ # pair the input with its derivative í # reverse both, so the constant coeff is now last λ£ } # recursively compute the Sturm's sequence: # (initially, a(n-2) = input and a(n-1) = derivative) ¬/ # divide a(n-1) by its first element D # duplicate ₂ # push a(n-2) 0š # prepend a 0 * # multiply ₂- # subtract a(n-2) 2£ # keep the first two coefficients # => this is the polynomial division -a(n-2) / a(n-1) δ* # double-vectorized multiplication ˜ # flatten 0š # prepend a 0 2ô # split in groups of 2 O # sum each group + # add a(n-2) # => this is the remainder ( # negate ¦¦ # drop the two leading zeroes €н # keep only the highest-order coefficient of each polynom üP # pairwise product .± # sign of each O # sum ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~25~~ ~~32~~ ~~31~~ 27 bytes *+7 bytes for bugfix* *-4 bytes thanks to @JungHwanMin* ``` Length@#&@@RootIntervals@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc1L70kw0FZzcEhKD@/xDOvJLWoLDGnGCjyP6AoM68kOi3aSEFbwbgCSFTEGcXG/gcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) - 5 = 7 ``` ÆrQṠṠƑ€SµİẸ? ``` A monadic link accepting a list of coefficients from highest degree to lowest which yields a number or the list `[inf]` if all the integers given were zero. As a full program prints the number or `inf`. **[Try it online!](https://tio.run/##y0rNyan8//9wW1Hgw50LgOjYxEdNa4IPbT2y4eGuHfb///@PNogFAA "Jelly – Try It Online")** ### How? ``` ÆrQṠṠƑ€SµİẸ? - Link: list of coefficients ? - if... Ẹ - ...condition: any? µ - ...then: the monadic chain: Ær - roots Q - de-duplicate Ṡ - sign if real; complex conjugate if complex (vectorises) € - for each: Ƒ - is invariant under?: Ṡ - sign if real; complex conjugate if complex S - sum İ - ...else: inverse ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 8 bytes Pari/GP has a built-in for this. It takes an polynomial as input, e.g., `1-2*x+x^2`. ``` polsturm ``` [Try it online!](https://tio.run/##LYjLCoAgFAV/5eLK50Jd149EgRtDsLqYgX29abU4zMxBl4JasXoYKh7xzFfaqkOMN0VQI2AKe25KehDwFBmTMGkJWhheOspiXnRpsxKMsLz8vzKfzqw@ "Pari/GP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` lambda c:sum(f.real==f for f in set(polyroots(c))) from numpy.polynomial.polynomial import* ``` [Try it online!](https://tio.run/##TY7LCsMgEEXXzVfcpSk25LEL5EvSLKyNVFBH1Czy9baWlBQG5s4cmDl@Ty9yQzaYcM9G2MdTQI5xs0w1YRVmmhQUBShoh7gm5snsgShFJuu6rlQgC7dZvzeFOLJamL8IbT2FdM1SxDV@vsxzt3DMHUd/9JbjtzqqTD3HcIJbf@b2IEtVxGQR@x4fq4sP2iVmilp@Aw "Python 3 – Try It Online") Had to include `set()` to take care of "double" roots. `polyroots([1, -2, 1])` gives `[1., 1.]`... [Answer] # [R](https://www.r-project.org/), 44 bytes ``` sum(!Im(unique(zapsmall(polyroot(scan()))))) ``` [Try it online!](https://tio.run/##K/r/v7g0V0PRM1ejNC@zsDRVoyqxoDg3MSdHoyA/p7IoP79Eozg5MU9DEwz@GykYKxj@BwA "R – Try It Online") `zapsmall` is necessary to deal with numerical imprecision, as otherwise e.g. `2 3 1` test case would fail. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~9~~ 13 - 5 = 8 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) Monadic link expecting list of coefficients from lowest to highest. ``` ÆrÆiṪÐḟQLµİẸ? ``` You can [try it online](https://tio.run/##ASMA3P9qZWxsef//w4Zyw4Zp4bmqw5DhuJ9RTP///1sxLC0xMCwxXQ)! How it works: ``` Ær Find the roots of the polynomial Æi and split each root into [real part, imaginary part] Ðḟ Filter the list, removing elements Ṫ where the imaginary part is Truthy (i.e. other than 0) Q Remove duplicates L and return the length of that. ``` This is the main part. Then `µİẸ?` checks if there is any non-zero coefficient. If not, returns infinity. If there is, just run the previous program I described. Borrowed the final four bytes `µİẸ?` from [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/200141/75323), increasing my count by 4 but gaining the bonus -5, for a total of -1. ]
[Question] [ ## Background [SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus), or simply SKI calculus, is a system similar to lambda calculus, except that SKI calculus uses a small set of *combinators*, namely `S`, `K`, and `I` instead of lambda abstraction. Unlike lambda calculus, beta reduction is possible only when a combinator is given enough arguments to reduce. The three combinators in SKI calculus are defined as follows: $$ \begin{aligned} S\;x\;y\;z & \overset{S}{\implies} x\;z\;(y\;z) \\ K\;x\;y & \overset{K}{\implies} x \\ I\;x & \overset{I}{\implies} x \end{aligned} $$ For example, the SKI expression \$ e=S(K(S\;I))K \$ is equivalent to the lambda expression \$ λx.λy.y\;x \$, as applying two arguments to \$ e \$ reduces to the desired result: $$ \begin{aligned} S(K(S\;I))K\;x\;y & \overset{S}{\implies} (K(S\;I)x)(K\;x)y \\ & \overset{K}{\implies} S\;I(K\;x)y \\ & \overset{S}{\implies} (I\;y)(K\;x\;y) \\ & \overset{I,K}{\implies} y\;x \end{aligned} $$ It is known that [any lambda expression can be converted to a SKI expression](https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis). A [Church numeral](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals) is an encoding of natural numbers (including zero) as a lambda expression. The Church encoding of a natural number \$ n \$ is \$ λf. λx. f^n\;x \$ - given a function \$ f \$ and an argument \$ x \$, \$ f \$ repeatedly applied to \$ x \$ \$ n \$ times. It is possible to construct a lambda expression (and therefore a SKI expression) that performs various arithmetic (e.g. addition, multiplication) in Church encoding. Here are a few examples of Church numerals and Church arithmetic functions: (The given SKI expressions are possibly not minimal.) $$ \begin{array}{r|r|r} \text{Expr} & \text{Lambda} & \text{SKI} \\ \hline 0 & λf. λx. x & K\;I \\ 1 & λf. λx. f\;x & I \\ 2 & λf. λx. f(f\;x) & S (S (K\;S) K) I \\ \text{Succ} \; n & λn. λf. λx. f(n\;f\;x) & S (S (K\;S) K) \\ m+n & λm. λn. λf. λx. m\;f(n\;f\;x) & S (K S) (S (K (S (K\;S) K))) \end{array} $$ ## Challenge Write an SKI expression that accepts a Church numeral of \$ n \$ and evaluates to the Church numeral of \$ \lfloor n/2 \rfloor \$. ## Scoring and winning criterion The score is the total number of `S`, `K`, and `I` combinators used. The submission with the lowest score wins. [Here is a Python script](https://tio.run/##hVLLTsMwELznK1bi4F1RoC23oJ44RT3miFDkJA6NSJ3ITlHKz5dNnGcL4mLZuzPjmbWrc30o9fMlhB0U8hinEhp/2J3H3bcPDX4Tnnkhb/8HuPGCRafxvFRlUEljVWQ/c7TkewC2lsknA9@Cdz5lpYEEcg227QHkmTuKcB8I34HfHjbvTBj3qL5kgQlbaRmq6Di7HQgcGI@yqpROMbiBEEPiQeyxKiukF5DXhYWIxLi7yqj6ZPRkw8WzSWnGeCPmdMQpxiwkOVJdRgnqbhzsTI@8fniZPxtjhg79sCHMCJu5l9/wTXdDZsrjeEeP1jhD3bPcmu3cAVsE1VRGWZuX2kKZwevhZJIDrFewWcHWu6tMrmvsNacHFRyO2M@f/X/aIYa4D2lPDnfjpRtc70WmaV5zzWNmxAd@soUS67RqgyKRIDdqZeuo56BcQTy9koT79i/shmENqG7eksht4lkEWRR4K9jZlO37Gqk/FG7WrhQvSm3AlnaQxZeK2pAcQQhxCS68Tq1FsCXhKlHXYKOzQE9PsL1K5FBDJvJ@STIIXQfZrieCCNuP7ovV/Mcv3dHlBw "Python 3 – Try It Online") to check the correctness and score of your SKI expression. For the record, I have a (relatively naïve) solution of score 126. [Answer] # 40 combinators ``` S(S(SI(K(S(S(KS)K)(K(S(S(KS)(S(KK)S))(K(S(KK)(S(S(KS)K)))))))))(K(S(SI(K(KI)))(K(KI)))))(KK) ``` [Try it online!](https://tio.run/##hVNNb6NADL3zKyz1MLaatkl6Y5XTnhBHjlWFBhg2qAQQQyrSP596ZvhMWm0OxGO/Zz@/gebSHevq9RrBAUp5SjIJvT9Glyn68qHHL8ILP8gLfwH3XrCq9J6XqRwa2WoV648CNfkegO5k@sHAt@CdT3ndQgpFBdrUAIrcHUUUBsJ34Len3TsTphjVpywxZSmGoUrLORxA4Mh4lk2jqgyDOwgxJBmbPTd1g/QH5G1i1URiYke1qju31SzDrafTup3WmzDnE85rLJYkR@rqOMXK2sHKqok3mJf7CxtzdOinHWFO2C@1/ITv7YS8rU/TjAFd4QL1yO22LOcBWCKovmmV1kVdaahz@Hs8t@kRthvYbWDvPTRtUXU49JwvVPByxHp@rf@nHGGEYUQhOdydFmvcoEVmWdFxzmNmzAe@slUn7mO6jR2JBDmrle7igYNyA8l8SxIezbtwGM0aUdZvSeSCZLGCLEu8b2hlSnO/raz@KdxtXSpZpcyChnaU5aeKzZK8ghDialyIAit9ED/H5hlSRC7F4Qwafw5s@GHgjvbfRCFdecA8deXZWsuNWbbAHiy8enmB/Y1ZDjXaRd4PJo2Nbj3ab2eCiMw35IvN8mNaq6PrNw) Generated with a little help from a slightly modified version of [my answer to Combinatory Conundrum](https://codegolf.stackexchange.com/a/128136/39242): $$\begin{align\*} \textit{zero} &= λf. λx. x = KI \\ \textit{succ} &= λn. λf. λx. f\,(n\,f\,x) = S(S(KS)K) \\ \textit{zero-pair} &= λf. f\,\textit{zero}\,\textit{zero} = S(SI(K\,\textit{zero}))(K\,\textit{zero}) \\ \textit{next-pair-helper} &= λf. λm. λn. f\,n\,(\textit{succ}\,m) \\ &= S(S(KS)(S(KK)S))(K(S(KK)\,\textit{succ})) \\ \textit{next-pair} &= λp. λf. p\,(\textit{next-pair-helper}\,f) \\ &= S(S(KS)K)(K\,\textit{next-pair-helper}) \\ \textit{half} &= λn. n\,\textit{next-pair}\,\textit{zero-pair}\,K \\ &= S(S(SI(K\,\textit{next-pair}))(K\,\textit{zero-pair}))(KK) \end{align\*}$$ [Answer] # 31 combinators ``` S(S(S(SI(K(S(S(KS)(S(KK)S))(K(S(KK)(S(S(KS)K)))))))(KK))(K(KI)))(K(KI)) ``` [Try it online!](https://tio.run/##hVNNb6swELzzK1bqwbtq2ibpjaec3glx5FhVyIB5QSWAbFKR/vl0jflMWr1EStbe2fHMGJpLe6yr12sEByjlKckkdP5YXabqy4cOvwgv/ENe@Au484JVp/O8TOXQSG1UbD4KNOR7AKaV6QcD34J3XuW1hhSKCoztARS5W4ooDITvwG9Pu3cemGpUn7LElKXYCVX2M4cDCBwnnmXTqCrD4A5CDElGsuembpD@gLzdWJFITPqjtGrPupplOHsmrfVkb8KcTzjbWJgkN9TWcYpVHwcrq6a5IbzcX8SYo0M/7Qhzwm6p5Sd815@Q6/o0nTGgK1ygHpluy3IegCWC6hqtjCnqykCdw9/jWadH2G5gt4G999Doompx4JwvVLA5Yj2/9v/TjjDCMKKQHO5OSx/coEVmWdHynseTMS/4ylZMzGPZRkYiQS5qZdp4mEG5gWS@JQmP9lk4jGGNqD5vSeSKZGFBliXeE/Yypb1fLat/Cndbt5WstqxBO3aU5aeKrUm2IIS42hT4G/TiJyMhRawgdCVGsy/7sXu2GQY0/V@Zaz5gFc/62Jtc@gbbXcTy8gL7m1wcakyGvB/yGIlu49hv5wER2dfFF5vle7NWR9dv "Python 3 – Try It Online") $$\begin{align\*} \textit{zero} &= λf. λx. x = KI \\ \textit{succ} &= λn. λf. λx. f\,(n\,\,f\,\,x) = S(S(KS)K) \\ \textit{fst} &= λm. λn. m = K \\ \textit{next} &= λg. λm. λn. g\,\,n\,(\textit{succ}\,\,m) = S(S(KS)(S(KK)S))(K(S(KK)\,\textit{succ})) \\ \textit{half} &= λn. n\,\,\textit{next}\,\,\textit{fst}\,\,\textit{zero}\,\,\textit{zero} = S(S(S(SI(K\,\textit{next}))(K\,\textit{fst}))(K\,\textit{zero}))(K\,\textit{zero}) \end{align\*}$$ [Answer] # 56 combinators ``` S(K(SI(KK)))(S(SI(K(S(S(K(S(K(S(S(K(S(KS)K))S)(KK)))(S(K(SI))K)))(SI(K(KI))))(S(K(S(S(KS)K)))(SI(KK))))))(K(S(SI(K(KI)))(K(KI))))) ``` [Try it online!](https://tio.run/##hVNNb6swELzzK1bqwbtq2ibpjaec3glx5FhVyIB5QSWAgFSkfz5d25iPpNW7RGt7ZjwzDs2lP9bV6zWCA5TylGQSBt9Nl2n68mHAL8IL/5AX/gIevGB1MnhepnJoZNupuPsosCPfA@h6mX4w8C1451Vet5BCUUGnzwCK3C5FFAbCt@C3p907E6YZ1acsMWUrmqFKwzkcQKBjPMumUVWGwR2EGJI4seembpD@gLzdWIlITMxVrerPbTXbsPG6tG6neBPmfMI5xiIkWVJfxylWpg52Vk28sbzcX9SYo0U/7QhzwmHp5Sf8YG7I2/o03TGiK1ygHlluy3YegC2CGppWdV1RVx3UOfw9ntv0CNsN7Daw9x6atqh6HDXnBxUcjtjPr@f/OY4wwjCikCzuzospbvQis6zoec9jZswLfrKVEutoNadIJMhWrbo@HjkoN5DMryThUf8XDq4shzJ9SyI7JIsIsizxXtDYlPp9W1n9U7jb2q1ktaUDatpRlp8q1iE5ghDialwHGGrTbF@PGLks82RScUiH0yQiu9CUkFfuYG5hUtZz6OQNduLQlW3M3lbNrh3fVGoOuKlFoy8vsL@p1KJcqeT9UKUTum1yv50JItJfmi82y09u7Y6u3w "Python 3 – Try It Online") This is the hand-optimized version of my own solution (originally of score 126). I also used the "pair" construct, but in rather basic way. $$ \begin{align\*} \textit{zero} &= λf. λx. x = KI \\ \textit{succ} &= λn. λf. λx. f\,(n\,f\,x) = S(S(KS)K) \\ \textit{pair} &= λx. λy. λf. f\,x\,y \\ \textit{zero-pair} &= \textit{pair}\,\textit{zero}\,\textit{zero} \\ \textit{fst} &= λp. p\,(λx. λy. x) \\ \textit{snd} &= λp. p\,(λx. λy. y) \\ \textit{next-pair} &= λp. \textit{pair}\,(\textit{snd}\,p)\,(\textit{succ}\,(\textit{fst}\,p))\\ \textit{half} &= λn. \textit{fst}\,(n\,\textit{next-pair}\,\textit{zero-pair}) \end{align\*} $$ Then I used [\$SKIBC\$-conversion](https://en.wikipedia.org/wiki/Combinatory_logic#Combinators_B,_C). Those reverse-applications generated lots of \$C\$s (\$C = (S (S (K (S (K S) K)) S) (K K))\$), which turned out to be very heavy even after reduction. [Answer] # 45 combinators ``` S(K(SI(KK)))(S(SI(K(SI(K(S(K(S(S(KS)(S(K(SI))K))))(S(KK)(S(KK)(S(S(KS)K)))))))))(K(S(SI(K(KI)))(K(KI))))) ``` From `\n.(\p.p(\xy.x))(n(\p.p(\xyf.fy(\fz.f(xfz))))(\f.f00))`. ]
[Question] [ One of my favorite mathematical pastimes is to draw a rectangular grid, then to find all of the rectangles that are visible in that grid. Here, take this question, and venture for yourself! **Can you count the number of rectangles?** ``` +-----+-----+-----+-----+ | | | | | | | | | | +-----+-----+-----+-----+ | | | | | | | | | | +-----+-----+-----+-----+ | | | | | | | | | | +-----+-----+-----+-----+ | | | | | | | | | | +-----+-----+-----+-----+ ``` The total number of rectangles for this *4* x *4* [minichess board](https://en.wikipedia.org/wiki/Minichess#4.C3.974.2C_4.C3.975_and_4.C3.978_chess) is exactly > > `100` > > > Were you correct? **Related math:** [How many rectangles are there on an 8×8 checkerboard?](https://math.stackexchange.com/q/1586270/32803) ## The Challenge Write the shortest **function/program** that counts the total number of visible rectangles on a non-toroidal **grid/image**. **Related challenges:** [Count the Unique Rectangles!](https://codegolf.stackexchange.com/q/87500/11933), [Find number of rectangles in a 2D byte array](https://codegolf.stackexchange.com/q/18631/11933). ## Input Format Your function or program can choose to work with either text-based input or graphical input. ### Text-based Input The grid will be an *m*-by-*n* (*m* rows, *n* columns) ASCII grid consisting of the following characters: * spaces, * `-` for parts of a horizontal line segment, * `|` for parts of a vertical line segment, and * `+` for corners. You can introduce this ASCII grid as the input/argument to your program/function in the form of * a single string delimited by line-breaks, * a string without newlines but with one or two integers encoding the dimensions of the grid, or * an array of strings. **Note:** The text-based input contains at least *1* row and at least *1* column. ### Graphical Input Alternatively, the grids are encoded as black-and-white PNG images of *5\*n* pixels wide and *5\*m* pixels high. Each image consists of *5 px \* 5 px* blocks that correspond to the ASCII input by: * Spaces are converted to white blocks. These blocks are called the *whitespace* blocks. * Line segments and corners are converted to *non*-whitespace blocks. The center pixel of such blocks are black. * **Edit:** If two corners (in the ASCII input) are connected by a line segment, the corresponding block centers (in the graphical input) should be connected by a black line, too. This means that each block could only be chosen from ![Please ignore the blue boundaries.](https://i.stack.imgur.com/khsAP.png) [(Click here for larger image)](https://i.stack.imgur.com/ghzHS.png). **Note:** The blue boundaries are only for illustration purposes. Graphical input is at least *5* px wide and *5* px high. You can convert the graphical input to any monochrome image, potentially of other image file formats). If you choose to convert, please specify in the answer. There is no penalty to conversion. ## Output Format If you are writing a program, it must display a non-negative number indicating the total number of rectangles in the input. If you are writing a function, it should also return a non-negative number indicating the total number of rectangles in the input. ## Example Cases **Case 1,** Graphic: [![Case 1](https://i.stack.imgur.com/S2zql.png)](https://i.stack.imgur.com/S2zql.png) (*30* px \* *30* px), ASCII: (*6* rows, *6* cols) ``` +--+ | | | ++-+ +-++ | | | +--+ ``` Expected output: `3` **Case 2,** Graphic: [![Case 2](https://i.stack.imgur.com/QkEMz.png)](https://i.stack.imgur.com/QkEMz.png) (*20* px \* *20* px), ASCII: (*4* rows, *4* cols) ``` ++-+ |+++ +++| +-++ ``` Expected output: `6` **Case 3,** Graphic: [![Case 3](https://i.stack.imgur.com/uXKCs.png)](https://i.stack.imgur.com/uXKCs.png) (*55* px \* *40* px), ASCII: (*8* rows, *11* cols) ``` +++--+ +-+++ | | | ++--+ +--+--++ ++ | || | || ++ +--++ ++ ``` Expected output: `9` **Case 4,** Graphic: [![Case 4](https://i.stack.imgur.com/dR6ih.png)](https://i.stack.imgur.com/dR6ih.png) (*120* px \* *65* px), ASCII: (*13* rows, *24* cols) ``` +--+--+ +--+ +--+ +--+ | | | | | | | | | +--+--+ | | | | | | | | | +--+--+--+--+--+ +--+--+ | | | | | | | | ++ +-+-+-+-+ +--+ +--+ ++ | | | | | +-+-+-+-+-+-+-+-+-+-+-+ | | | | | | | | | | | | +-+-+-+-+-+-+-+-+-+-+-+ | | | | | | | | | | | | +-+-+-+-+-+-+-+-+-+-+-+ ``` Expected output: `243` **Case 5,** Graphic: [![Case 5](https://i.stack.imgur.com/AZEh2.png)](https://i.stack.imgur.com/AZEh2.png) (*5* px \* *5* px. Yes, it *is* there!), ASCII: Just a single space. Expected output: `0` **Case 6,** Graphic: [![Case 6](https://i.stack.imgur.com/PIPLn.png)](https://i.stack.imgur.com/PIPLn.png) (*35* px \* *20* px), ASCII: (*4* rows, *7* cols) ``` +--+--+ |++|++| |++|++| +--+--+ ``` Expected output: `5` ## Assumptions To make life easier, you are guaranteed that: * By being *non-toroidal*, the grid does not wrap either horizontally or vertically. * There are no loose ends, *e.g.* `+---` or `+- -+`. All line segments have two ends. * Two lines that meet at `+` must intersect each other at that point. * You do not have to worry about invalid inputs. Rules against standard loopholes apply. Please treat squares as rectangles. Optionally, you could remove the trailing spaces on each row of the grid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your entry as short as possible. Text-based and graphical solutions will compete together. ## Leaderboard ``` var QUESTION_ID=137707,OVERRIDE_USER=11933;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## JavaScript (ES6), ~~176~~ 171 bytes ``` g=a=>Math.max(...b=a.map(a=>a.length))-Math.min(...b)?``:f(a);f= a=>a.map((b,i)=>[...b].map((_,j)=>n+=a.join` `.split(eval(`/\\+(?=[-+]{${j}}\\+[^]{${l=b.length+~j}}([|+].{${j}}[|+][^]{${l}}){${i}}\\+[-+]{${j}}\\+)/`)).length>>1),n=0)|n ``` ``` <textarea rows=8 cols=8 oninput=o.textContent=g(this.value.split`\n`)></textarea><pre id=o> ``` Takes input as an array of strings of equal length. Explanation: Creates a series of regular expressions that match rectangles of all possible widths and heights (and some impossible widths and heights, but that's code golf for you) and counts how many matches they all produce. Because there's a capturing group in the regexp, `split` returns `2n+1` for `n` matches, so I right shift by 1 to get the number of matches, as that saves a byte over making the group non-capturing. [Answer] ## [Grime](https://github.com/iatorm/grime), ~~31~~ 28 bytes ``` T=\+[+\-]*\+/[+|]/+$ n`T&To2 ``` [Try it online!](https://tio.run/##Sy/KzE39/z/ENkY7WjtGN1YrRls/WrsmVl9bhSsvIUQtJN/o/39tXV0QUgATSCRXjYICGMFoGOKC6cCQgDGhCuAIrkMBVYcClwICIElog3RAIbKTQBI1ClCIUIIKESpQIbXUAwA "Grime – Try It Online") Takes input in ASCII format. ## Explanation Grime's syntax is very close to regular expressions. Each line defines a pattern that may or may not match a rectangle of characters. `T` matches a rectangle whose top row and left column look valid. ``` T=\+[+\-]*\+/[+|]/+$ T= Define T as \+[+\-]*\+ a row that matches this regex / and below that [+|]/+ a column of + or | $ with anything to its right. ``` The second row is the "main program". ``` n`T&To2 n` Print number of rectangles that match T the pattern T & and To2 T rotated 180 degrees. ``` [Answer] # [J](http://jsoftware.com/), ~~103~~ ~~95~~ ~~86~~ ~~80~~ ~~76~~ 70 bytes ``` [:+/@,]*/@('-|++'*/@(e.,&'+')~&>]({.,{:)&.>@;|:;{.;{:);._3"$~2+$#:i.@$ ``` [Try it online!](https://tio.run/##rVFBboMwELzzilWLMHTBkYFQyVYj/tGiHFCiNpc8ACtfp7s2dk2l3updMLMzHtvLbV2v8KbhXeNhrKeXw1iKxiIK/rrIuhAoqkdxmspF1ouuCnkajdVmkYaQkefuKX@0mD/rLznmWTYrdjsPMH2AwKZBALslYuMyFoB5kc2tW9L7JaSg7XlYFhPdOVopx9Mi9LbAtLcPdkzwwxMwBxtnk09fdxpn3zv7to8nZne/xc87HNnCPoP@dz3e2fMxgx72@nTYtGN0Rx/pYahuIcR@RP0@wP4R/6SnNh65jYoip59EeHBtfU27atHlNm1FkWWX@fMOpblWMKsUtCnoUtCn4JiCYV2/AQ) Takes input as an array of strings with trailing spaces (so that each string is the same size). Uses the *full* subarray operator `;._3` to iterate over every possible subarray size larger than 2 x 2, and counts the subarrays that are valid rectangles. Completes all test cases almost instantly. [Answer] # Mathematica, ~~136~~ ~~134~~ 132 bytes ``` S=Tr@*Flatten;S@Table[1-Sign@S@{d[[{i,j},k;;l]],d[[i;;j,{k,l}]]},{i,($=Length)[d=ImageData@#]},{j,i+1,$@d},{k,w=$@#&@@d},{l,k+1,w}]& ``` Usage: (for old 136-byte version, but the new version is basically identical) [![_](https://i.stack.imgur.com/EnGN6.png)](https://i.stack.imgur.com/EnGN6.png) Note: * This runs in time O(m2 n2 max(m, n)), so only use small inputs. * Although this is supposed to work with binary images, apparently it can work with non-binary images. (but black must be identically zero) * The graphics doesn't necessarily be constructed with 5x5 blocks, the blocks can be smaller. * `@*` is new in version 10. In older versions, use `Tr~Composition~Flatten` instead of `Tr@*Flatten`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~60 53 52 51~~ 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÑFQe⁹ṚẆ;W¤ Ḣ,Ṫ =”+ÇÇ€Ạȧ1ŀ Zç⁾+-ȧç⁾+|$ Ẇ;"/€Ẇ€Ç€€FS ``` A full program accepting a list of strings (equal length rows) and printing the count. **[Try it online!](https://tio.run/##y0rNyan8///wRLfA1EeNOx/unPVwV5t1@KElXA93LNJ5uHMVl@2jhrnah9sPtz9qWvNw14ITyw2PNnBFHV7@qHGftu6J5RBGjQoXSJ@SPlhRG5AEqwcit@D///9HKykoaGtr6@pqKygoKOlwKShp6wL5Cgo1MH4NmA1WApXXBSFtoBCYrwAGIFU1WPkgw4D6QVqQ@GCgFAsA "Jelly – Try It Online")** ...or for ease of copy & pasting input use [this](https://tio.run/##y0rNyan8///wRLfA1EeNOx/unPVwV5t1@KElXA93LNJ5uHMVl@2jhrnah9sPtz9qWvNw14ITyw2PNnBFHV7@qHGftu6J5RBGjQrXw91bQFqV9MHq2oAkWAsQuQX///9fQUFbW1tXV1tBQYFLWxfIVlCoAbFrwDRYigtEAJE2kMulAAYg2RoUNkgjUD1IGZQNBgA "Jelly – Try It Online") full program (with an extra byte to split lines) - do note the lines are required to contain trailing spaces for the program to function correctly though. ### How? ``` ÑFQe⁹ṚẆ;W¤ - Link 1, sidesAreValid?: list of lists, area; list allowedSideCharacters Ñ - call the next link (2) as a monad (get the sides in question - note: these sides do not include the corners since the area was modified - to not include the other sides by the first call to link 2 inside link 3. F - flatten into a single list Q - de-duplicate (unique characters) ¤ - nilad followed by link(s) as a nilad: ⁹ - right argument (either "+-" or "+|" ) Ṛ - reverse (either "-+" or "|+" ) Ẇ - all sublists (either ["-","+","-+"] or ["|","+","|+"] ) W - wrap (either ["+-"] or ["+|"] ) ; - concatenate (either ["-","+","-+","+-"] or ["|","+","|+","+|"]) e - exists in? Ḣ,Ṫ - Link 2, topAndTail helper: list Ḣ - head (get the first element and modify the list) Ṫ - tail (get the last element and modify the list) , - pair (the elements together) =”+ÇÇ€Ạȧ1ŀ - Link 3, isPartlyValid?: list of lists, area; list allowedSideCharacters =”+ - equal to '+'? (vectorises across the whole area, 1 if so, 0 otherwise) Ç - call the last link (2) as a monad (gets the values for two edges) Ç€ - call the last link (2) as a monad for €ach (...values for the four corners) Ạ - all? (all corners are '+' 1 if so, 0 if not) 1ŀ - call link number 1 as a dyad with sideCharacters as the right argument - ...and the modified area on the left ȧ - logical and (both all corners are '+' and the sides in question look right) Zç⁾+-ȧç⁾+|$ - Link 4, isValidSquare?: list of lists, area Z - transpose ç⁾+- - call the last link (3) as a dyad with right argument "+-" $ - last two links as a monad: ç⁾+| - call the last link (3) as a dyad with right argument "+|" ȧ - logical and (1 if so 0 otherwise) Ẇ;"/€Ẇ€Ç€€FS - Main Link: list of lists of characters, rows Ẇ - all sublists (= all non-zero length runs of rows) /€ - reduce €ach by: " - zip with: ; - concatenation (= all non-zero length vertical edges) Ẇ€ - all sublists for €ach (= all possible areas) Ç€€ - call the last link (4) as a monad for €ach for €ach (for each area) F - flatten S - sum ``` [Answer] # [Slip](https://github.com/Sp3000/Slip), 32 29 bytes ``` $a([+`-]*`+>[+`|]*`+>){2}$A ``` [Try it online!](https://slip-online.herokuapp.com/?code=%24a%28%5B%2B%60-%5D%2a%60%2B%3E%5B%2B%60%7C%5D%2a%60%2B%3E%29%7B2%7D%24A&input=%20%20%2B%2B%2B--%2B%20%20%20%0A%2B-%2B%2B%2B%20%20%7C%20%20%20%0A%7C%20%20%7C%20%20%2B%2B--%2B%0A%2B--%2B--%2B%2B%20%2B%2B%0A%20%20%20%20%20%20%7C%20%20%7C%7C%0A%20%20%20%20%20%20%7C%20%20%7C%7C%0A%2B%2B%20%20%20%20%2B--%2B%2B%0A%2B%2B%20%20%20%20%20%20%20%20%20&config=no) 27 bytes of code + 2 bytes for the `n` and `o` flags. Takes input in the same format provided in the question (i.e. newline-delimited block of lines). [Answer] ## Haskell, ~~180~~ ~~167~~ 166 bytes ``` l=length a%b=[a..b-1] h c a g b=all(`elem`c)$g<$>[a..b] f s|(#)<-(!!).(s!!)=sum[1|y<-1%l s,x<-1%l(s!!0),i<-0%y,j<-0%x,h"+|"i(#x)y,h"+-"j(y#)x,h"+|"i(#j)y,h"+-"j(i#)x] ``` [Try it online!](https://tio.run/##vVHbboMwDH3PV7hcpEQBVNpX2I8gpIaOcllg02ASSPl3FgIMMlD3NttynJOTo8TOWfOWcj4MPORpnbU5YnYSRszzEtePUQ53YJBBEjLO8S3laXW7EysLrBfFidEDGoFNErj4dCIebmQOm68q8kUfuL7NoXE6VYxHZ@IUgXu2e6ccl87JDSqMApsd6cfaNUrcm2TFyxUvJB4PrQ8hRCAhdwzDQTCZISgd4ymy3IoRai@aEKi0yVsdABXLusRe@BllAWfqTxyogK4CGwqstqFQXWX27Xd0ioDFdTtS0R0OVXT/P5VxjtdpjvKbdG6efpPSXROnttHj7v9q1dpr8SdK1eiUyA6davngihW1fPLruyR8fBZ1CxY8oPX17UXfXodv "Haskell – Try It Online") Go through all possible corner positions with four nested loops and check if all the chars on the lines between them consist of `+-` (horizontal) or `+|` (vertical). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ ~~39~~ ~~34~~ 33 bytes ``` ,Z;.ị$⁺€ḟ€"⁾-|Fḟ”+ ẆḊÐfZ€µ⁺€ẎÇÐḟL ``` [Try it online!](https://tio.run/##y0rNyan8/18nylrv4e5ulUeNux41rXm4Yz6QVHrUuE@3xg3EaZirzfVwV9vDHV2HJ6RFAeUObYWq3NV3uP3wBKAan////0era@vqgpACmEAi1XW4FNRrFBTACEbDEFgSphOrJIwLVQRHKDoVUHUqgCUVEABJUhumEwqRnQqTrFGAQVSAqhMVKqDpRIW00hkLAA) or [View all cases.](https://tio.run/##tVJLCsJADN33FEGELtLxAu5deQKlS12IFxCyUBcKCuIFxAu4FUoFF/Yk7UXG@TQzTcGlyZDJTN5LX8msFuv1RutsNh7Vr/Ow2ZXN/lEXdxMHze6taGIP2xsmdXmoi1N1Xc5M7fNskeWlOlZXg5nq6mgutJ4nME9RKQRIs8QEAqCYIyr0uUkQyOcOEnLLTvPMNQpwQmQiIsUWLdCw0H8VYg1dX6HDgRih7ELgxuDM4ujHhe3o9WH3whkr9l3Bi4mxK4KAd15C0Y8qn1tUWJILkgvdP4FeFeMovHcFhyoBu7QeVzr0udL/yHVjELMID4jCyxEHhuVJ/gU) Based on my [answer](https://codegolf.stackexchange.com/a/137724/6710) in J. ## Explanation ``` ,Z;.ị$⁺€ḟ€"⁾-|Fḟ”+ Helper. Input: 2d array of characters Z Transpose , Pair ; Concatenate with $ The tail and head .ị Select at index 0.5 -> Select at index 0 and 1 Jelly uses 1-based modular indexing, so 0 means to select the tail ⁺€ Repeat on each - This selects the last and first rows, last and first columns, and the 4 corners ⁾-| The string array ['-', '|'] " Vectorize ḟ€ Filter each F Flatten ”+ The character '+' ḟ ẆḊÐfZ€µ⁺€ẎÇÐḟL Main. Input: 2d array of characters µ Combine into a monad Ẇ Generate all sublists Ðf Filter for the values that are truthy (non-empty) Ḋ Dequeue Z€ Transpose each ⁺€ Repeat on each Ẏ Tighten, join all lists on the next depth ÇÐḟ Discard the values where executing the helper returns truthy L Length ``` ]
[Question] [ Most people would cut circular pizzas into [circular sectors](https://en.wikipedia.org/wiki/Circular_sector) to divide them up evenly, but it's also possible to divide them evenly by cutting them vertically like so, where each piece has the same area (assume the pizza has no crust): ![](https://i.stack.imgur.com/8vfaT.png) # Challenge Your task is to make a program or function that takes a positive integer \$n\$ where \$2 \le n \le 100\$ that represents how many vertical slices a circular pizza with a radius of \$100\$ will be cut into as input and outputs the horizontal distance from the center of each cut (which will make each slice have the same area) from left to right (or right to left, since the cuts are symmetrical), rounded to the nearest integer. Note that this will probably require more than just a simple formula. # Rules * Input and output can be in any convenient format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins. # Test cases | Input | Output | | --- | --- | | 2 | [0] | | 3 | [26, 26] | | 4 | [40, 0, 40] | | 5 | [49, 16, 16, 49] | | 6 | [55, 26, 0, 26, 55] | | 7 | [60, 34, 11, 11, 34, 60] | | 8 | [63, 40, 20, 0, 20, 40, 63] | | 9 | [66, 45, 26, 9, 9, 26, 45, 66] | | 10 | [69, 49, 32, 16, 0, 16, 32, 49, 69] | | 50 | [90, 83, 78, 73, 69, 64, 60, 57, 53, 49, 46, 42, 39, 35, 32, 29, 25, 22, 19, 16, 13, 9, 6, 3, 0, 3, 6, 9, 13, 16, 19, 22, 25, 29, 32, 35, 39, 42, 46, 49, 53, 57, 60, 64, 69, 73, 78, 83, 90] | | 82 | [92, 88, 84, 81, 78, 75, 72, 69, 67, 64, 62, 59, 57, 55, 52, 50, 48, 46, 44, 41, 39, 37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 12, 10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 44, 46, 48, 50, 52, 55, 57, 59, 62, 64, 67, 69, 72, 75, 78, 81, 84, 88, 92] | | 97 | [93, 89, 86, 83, 80, 77, 75, 73, 70, 68, 66, 64, 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 43, 41, 39, 37, 36, 34, 32, 30, 29, 27, 25, 24, 22, 20, 19, 17, 15, 14, 12, 11, 9, 7, 6, 4, 2, 1, 1, 2, 4, 6, 7, 9, 11, 12, 14, 15, 17, 19, 20, 22, 24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 41, 43, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 73, 75, 77, 80, 83, 86, 89, 93] | | 100 | [93, 90, 86, 83, 81, 78, 76, 73, 71, 69, 67, 64, 62, 60, 59, 57, 55, 53, 51, 49, 47, 46, 44, 42, 40, 39, 37, 35, 34, 32, 30, 29, 27, 25, 24, 22, 21, 19, 17, 16, 14, 13, 11, 9, 8, 6, 5, 3, 2, 0, 2, 3, 5, 6, 8, 9, 11, 13, 14, 16, 17, 19, 21, 22, 24, 25, 27, 29, 30, 32, 34, 35, 37, 39, 40, 42, 44, 46, 47, 49, 51, 53, 55, 57, 59, 60, 62, 64, 67, 69, 71, 73, 76, 78, 81, 83, 86, 90, 93] | [Answer] # [R](https://www.r-project.org/), 74 bytes (partial, probabilistic solution) A bit of a silly Monte Carlo solution based on the fact that the histogram of eigenvalues of an \$N \times N\$ symmetric matrix with Gaussian entries converges to a semicircle with base \$[-2\sqrt{N}, 2\sqrt{N}]\$ as \$N \rightarrow \infty\$. Taking \$N = 50^2\$, this is the semicircle with base \$[-100, 100]\$. By a result known as eigenvalue rigidity, the eigenvalue quantiles are all within \$\sim 50/N\$ of the corresponding quantiles of the semicircle. Hence, we solve this problem by computing the eigenvalues of a \$50^2 \times 50^2\$ matrix with Gaussian entries and finding the quantiles from \$1/n\$ to \$(n-1)/n\$ of the sample: ``` \(n)round(abs(quantile(eigen(matrix(rnorm(50^4),50^2),T)[[1]],1:(n-1)/n))) ``` This is obviously not an exact solution, and when a true value is close to the form \$k + 0.5\$ for integer \$k\$, the estimate can be off the true rounded value by \$\pm 1\$. It also takes a long time to find the eigenvalues of a \$ 50^2 \times 50^2\$ matrix, so in the demonstration I can only run two test cases before timing out. [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHiNBvdpaUlaboWN71iNPI0i_JL81I0EpOKNQpLE_NKMnNSNVIz01PzNHITS4oyKzSK8vKLcjVMDeJMNHWApJGmTohmdLRhbKyOoZVGnq6hpn6epqYmxMRdBUWZeSUaaRqGBpqaXAiOAUzBggUQGgA) [Answer] # [JavaScript (V8)](https://v8.dev/), 87 bytes Prints the results. ``` n=>{for(t=0,x=w=1e6;x--+w;t*n>15708e8&&print((x*x)**.5/1e4+.49|(t=0)))t+=(w*w-x*x)**.5} ``` [Try it online!](https://tio.run/##TU5LCoMwFNz3FG9RJIlPq62f2BB3PUUpKKKtRaJoUMF6dhsXhS5mYH4w73zMh6KvO@2MfKvkpmS6VG1PtPRwlpP0y0jMjmNPQjOV@mHs8ZJbVtfXShMys5ky5oYnvwxsN0g@@45Sqm1JJjY5v3zdxB3OCBeEACFEiBBiBI6QIPiesQy4KSTxrj14HFzz4pYXL6JAprBA0aqhbUq3aZ8kMx4cF7VeMyqgIsrwf27kSsX2BQ "JavaScript (V8) – Try It Online") **NB**: This gives the same results as the OP for all test cases. We may disagree for some other inputs, but I've no way of knowing. ### Commented ``` n => { // n = input for( // loop: t = 0, // start with t = 0 x = w = 1e6; // and x = w = 1000000 x-- + w; // stop when x = -w (decrement x afterwards) t * n > 15708e8 // if t * n > round(pi / 2 * w² / 10^8) * 10^8 ... && // print( // ... print floor(abs(x) * 100 / w + 0.49) (x * x) ** .5 // / 1e4 + .49 // | (t = 0) // and reset t to 0 ) // ) // t += // at each iteration, add to t: (w * w - x * x) // sqrt(w² - x²) ** .5 // } // ``` [Answer] # [Python](https://www.python.org), ~~225~~ ~~202~~ 152 bytes *-23 bytes thanks to @solid.py* ``` lambda n:[h(pi*abs(a/n-.5))//2for a in range(1,n)] def h(a,p=0): while(d:=a-p*(r:=sqrt(1-p*p))-asin(p))>1E-9:p+=d/r/2 return 200*p+1 from math import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVXNbtNAEJa4IPIUy81uHbLr9a69kcwNXqL04DYOsZo4xkkFvAkSl0oI3gmehvmz4waqSra8O7_ffDOTfP_VfT1u9u3Dj0P54ef9cT0vfn_bVrubVaXa5dUm6pqL6uYQVYt2_sbF8WKRrve9qlTTqr5qP9aRSdr4eraq12oTVUlX6ng5U583zbaOVsuymncXUb8sD5_6Y2Tg0sXxvDo0bQSHt-bdPCy7y3K16BfpTPX18b5vVar1RXdpZut-v1O76rhRza7b98cLxvfn5QvMdrupb--iNqm_dPXtsV5hWohwKA9RG8OR9OW2biMQxiWdRlvQNxIC3ZTCoppTUTp5ZB6zETlBtKvm-nU5KOEyaIek76vtoR5lN31d3cGt65v2CIDJJkFQsxkXkapXyZW-juVq8Zr6RKV-lGUoy3Si4MlOpo7EIVHG85uFUedR5xyGITf8ODeqc1R7kNsMXA2_ePan8AXZWEwJ_pw91Xz1djQLZIbZJVugJxWJP5VhNJkGBArZUgat-YNXFPtTDY7sAxgUgCIv4LVoAC8hhYpyeC07ZpgQgliM7ThgikAQFuYaiLKED1NSckvnwAoyCOxAjgKUAgZOQIkCJ0YACIQABQaIQBFwmFBJTQ7gXKASjAsjFUHgPJWqcgkEdxekOtA7vCPxhSQHm8xIpbmAg4TWSMW5gAdZaqRykBknRSIbyCpVDsFS7i2dPclRTWZW3HLhxUhYJ2kCp6X0TuAEhkcwPcNG-FSGk7ICl0nl5sJdKnQUTA_RBOeQnmaN5jZAsgIcCs9EFxA8z8UZG4ANweL8iU-aFgSCe5A9wak949XzTtAA6DNuMxkSfcZvJsQZmql8QrGhZ2Q556EzYp-dEa0lfnZGthY8meCbEm6fID2TugsZ1oF4zzwhX8SbYx4L2TjiF7fZTlZYDx2gvRw6MEyzl0jm34mmDkynGtfHyO7mky6k_BPzaLqf68J0yr2waccu8KA72vVx1i1JeNyHRlhx9WcT_1wjppOvpYShEbn8WhgpeboB-j9bYIRCP9kEaQZSjs3gv8KHB_7-BQ) Uses Newton's method to find the inverse of the formula \$ \int\_0^h 2 \sqrt{1-h²} dh = h \sqrt{1-h²} + \sin^{-1}(h)\$ for the area of a slice of height h from the center in a circle of radius 1. [Answer] # [R](https://www.r-project.org), ~~84~~ 83 bytes ``` \(n,r=2e8)for(x in -r:r)if((F=F+(r^2-x^2)^.5)>pi*2e16/n)F=!print(abs(round(x/2e6))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVDLctMwFB22-Qox3Uhg01q2_EgqZliQVYZNy45JR3XkwWDkjCwzppl8STdhwUeVD-h3cCyFXRfH1j333HMfj7_t6en5gli9001rNNnb1jjKiOtJ3Xedrl2g9I78VN2oh2hO_eitjrUa2u4Xqb_q-jtxenCkVoMelgtfIA9Kfvq82aya0dSu7Q2dfBz1o9uP7m5w8NjdBVO5_rC5-cjahr6UZQdlBqlW6vo69pZWu9EaCpYddTfow5ypqYomtrrHDMtlWGNix-Pigiz27cODkn9G18Tl080XaiIruS5Z01s6kdaQ2C7t3J2u5fottVseT1vOtu8Ee79v33Cd5JeGreXrYKvuB2r70ezodMl1zhgL1n9fffOdaMnZQnUdDfIXF75lUta04hEpSyADkogUeBcCAJ9XQAEglyMWiAVigbyY46uIZNBnOQBNhvoUmhSaFJo0BcBxcBwcB8fBcXAJuARcAi4Bl8AvgR_sZjeIInLlv5lnypD2svRcVgSb2c7binObKrT17cV5nCqM58fMw9jz-H4NcV6rCmv6dYuw_nwGf44ynMefCe-K_z_56RT-_wA) (but it will time-out before completing), or [Attempt a less-accurate version with only 4 million x-axis steps](https://ato.pxeger.com/run?1=bU9NU8IwEL3zK-JwSbQVCJ8F4owHOTFe0JsDE8p27FhTJkmdCsMv8YIHfxR_wJM_wk2iNw6veX27-_btx6c-nr6bRMMGslwB2epcWcqILUlaFgWkNkiwIW-yqMBErvRaaohBmrx4J-kzpC_EgrEklQbMuOEHxF6K-8f5fJJVKrV5qWjt_6OystvKroxFj80qmIrZ7Xxxx_KMnquyvVRGyImcTmNvqcFWWlFU2QEKA3tXSamMajZZY4bxOJxRs8Oh0SSNbb7bSfFV2SwenRZPVEVacBiwrNS0JrkisR5rt53OxOyK6iWP6yVny-s-u9nmlxw6vKXYTFwEW7k2VJeV2tC6xaHHGPuz_vGLaL_NGrIoaOg-e-8DEyKlSTsio25EhiMEvoME0UOg3h8iUOuh1hsgeES6yLt9BHKOnCPnyDvIO9jTwX5ngR0RafvvwCuu4BuSMOAHk2DkDZOwwC9KwmIXwAXxgZIQ0AV1gZP2_83HY3h_AQ). Straightforward loop-over-x-values approach, not as elegant as [Damian Pavlyshyn's probabilistic approach in R](https://codegolf.stackexchange.com/a/264139/95126), but produces a single defined output for any input `n`. Calculates the area-so-far in 400 million x-axis steps across the pizza, outputting the rounded x-axis value each time it hits the intended slice-area, and resetting the area-so-far back to zero. Setting the area-so-far back to zero, instead of subtracting the slice-area and keeping the remainder for the next slice, is rather inaccurate, and so necessitates the huge number of x-axis steps to match all the test-cases. Subtracting the slice-area at each step would require ≈10,000x less steps to achieve the required accuracy, but costs [5 bytes more](https://ato.pxeger.com/run?1=bVBLbtswFES3PgWDbMhEaixKtCQ7KtBFvTK6aQt0UThgZApRq1IGSRVqDJ-kG3fRQ6UH6Dk6Ip1dFk_im5k37_Prtzk9_bskRu1U02pF9qbVjjLielL3XadqFyC1Iz9kNygbTdT33qhYSdt2P0n9oOpvxCnrSC2tssuZL6gOsnr_abNZNYOuXdtrOvo86ge3H9yddfDY3QXTav128-Edaxv6EssOUttKruTtbewtjXKD0RQoO6rOqsPE1FRGI1vdY4blMqwxsuNxdklm-_bxUVZ_BtfExdPnL1RHpuIqY01v6EhaTWKzNFN3uq7W1_qKmi2Pxy1n29fiZt_ecFWwNwkDGV_Mr4K3vLfU9IPe0RE8Z4wF_7-vvvp2tOBsJruOBvmLW39kVVXTkkekKBAZIolIjncuEMAXJSJHgFsgF8gFcgFeTPk8Ihn02QIBTYb6FJoUmhSaNEUA48A4MA6MA-PAEmAJsARYAiyBXwI_2E1uEEVk7r-ZR4pAe1l6LsuDzWTnbcW5TRna-vbiPE4ZxvNjLsLY0_h-DXFeqwxr-nXzsP50Bn-OIpzHnwnvkj-f_HQK__8). [Answer] # [JavaScript (V8)](https://v8.dev/), 93 bytes ``` n=>{q=2;for(S=x=1;S;x-=1e-6)q<(S+=(1-x*x)**.5/Math.PI*2e-6*n)&&q++*print((x*x)**.5*100+.5|0)} ``` [Try it online!](https://tio.run/##TY1NC4JAGITv/Yr3ELFfbruWZm3brUOHIPAYQSKahqyfhGD@dtsOQZcZ5pmBeUavqI2bvOqcVzClejL6MNTaVWnZoFD3WqpQ9Y6WiePjeo9CqpF0etJjQri3PEddxi8n4tqaGLxY1JSSqslNh9BvRKQQlHtvgcdJXcFlsGKwZuAx8BlsGAQMtgyksEh8XcBtxu3/MYozZEAfYIC4NG1ZJLwoH@huGcwHM@7uWEGKjNX/3sYRq@kD "JavaScript (V8) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 69 bytes ``` Nθ≔XE⊗φ⁻⊕⊗ι⊗φ²ηUMηΣ⁻¹÷⁺ιηX⊗φ²≔ΣηζUMη↨…ηκ¹I↔÷⁻⁺⁴φ⌕AEΦηκ⁻÷×θιζ÷×θ§ηκζ¹χ ``` [Try it online!](https://tio.run/##ZVDLasMwELz3K3RcgQpN6KX05DoEfEgxtD8gW2q9VFo5lpQ@ft6VrDoJVCCBZmdnZrcf5NQ7aea5oTGG52g7PcGRP95U3uM7Qes@E3CQI@xc7IxW8MYFOyBFDw31k7aaQkLXKvJUvlDzb5vukBSTSO2slaRgEOwlWigyG8EaCjs8odLQmoRgbhCseF/7bnk@53BZIxN//qk/Sa@h/u6Nrgc3ZuQj8Ta5t52QAtTSB6g670wMGi7@JdKS4l6w7LlHUpUxyw72aEKK9Ce3bmHtfUWrPRwFwyXT9VjnUhUaUvqrSCw0XoKl5y7PNs8P8@3J/AI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the desired number of slices. ``` XE⊗φ⁻⊕⊗ι⊗φ²η ``` Generate a list of odd numbers from `-1999` to `1999` and square them. ``` UMηΣ⁻¹÷⁺ιηX⊗φ² ``` For each square odd number, add all of the square odd numbers to it, and count how many are less than 4 million. ``` ≔Σηζ ``` Get the total "area". ``` UMη↨…ηκ¹ ``` Get the cumulative area at each potential slice point. Note that there are still `2000` points at this stage, with coordinates from `-99.95` to `99.95` in steps of `0.1`. ``` I↔÷⁻⁺⁴φ⌕AEΦηκ⁻÷×θιζ÷×θ§ηκζ¹χ ``` Find the slice points where the area increases to the next fraction of the total area and calculate the nearest integer slice points. [Answer] # [Perl 5](https://www.perl.org/), 95 bytes ``` sub{($n,$c,$s)=@_;map$-=.49+abs$_/100,grep$c<($s+=$n/15708*sqrt 1-$_**2/1e8)-1&&++$c,-1e4..1e4} ``` [Try it online!](https://tio.run/##dZNbb9pAEIXf@RUrZCEwA@x9vVC3vFdqXvrWRIhQE1VqCDG0ahXlt9Mz45TSVAXLWs/lzLdn7X3Tfg2nYlufDt9un4bFjooNFYdRvVwt7tf7YlJPfR6vbw/Fama0pru22RebN8PiMK6L3cyEpKvy8NgelZkUq7K0M9NUo4kZDMZjKE1M46dT3J5Pi972oR32Pimr6rdK3xCWjpc2ko3y6PnRa9Lku3yQQCYT@fJZgpGDIaAJhbiFIOHE4ajJeTKGLyxiJ1NJykGVLKtbHkDRSTJLEuqimPG38hA7JqMlnzGdnGUMzTcsEYhZdZxSlDVVjlJFySFDkedTSBQc13qoWnJQCdxtMQcTodhtz2EwZKGOZqwR4HDmEi6U6dyaWYbFMgtDHkN4VOaxGA6E/LJtcXq5rofZUoWMp8oIX6BkBTFJq6WQBTRQwBruVDLBkzdCnGSyI2eEOwmRI2uEPpEJwovNwALge7Ij7KRtvjftoVmuO6PTGcdRlamKzFppSkmIQI@doD2@QLF7FQWcsP@Hy12gRT5qdkdf0HkxTl8AegE08DZ1iGRGrxDxhl8w8nl2jJ1rURjNX8Yx49k7HIeRo06/MS2/aH8c/B/m2ccomK7DZCfR9MpLddMbPfWUuv/JX@uy@bHHx1qsFhJSy7uHYz0otsiNOLRvv@yOqs9lfdU8YoWCvnqn@lfv@2qu@mVZfrj6qPB0Ua52@Livd0op9DWbY/N5rlhCQhCYK/mx1jXq0Pp8@gU "Perl 5 – Try It Online") [Answer] # [Python](https://www.python.org), 146 bytes ``` lambda n:[round(min(range(900),key=lambda d:abs(tau/n*k+sin(a:=2*acos(d/900))-a))/9)for k in[[i,n-i][i>n/2]for i in range(1,n)]] from math import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVXNbtNAEL5xyFMsPdnFJd5d7643UniRNAe3cahV4kS2I7VCvARXLpUQHHkfeBrmz8EEqkZ2vDs7P998M2N_-X54HO727dPX7fL623HYXpU_P3-odjebSrWLVbc_tptk17RJV7Xv6yTmeZrd149LUdksqps-GarjvL28f9ODXrVYmsvqdt8nmzlqp1dVms5jut136l417WrVZO1Vs14179q5WaO4AbFi_zpr0_V6tu32O7WrhjvV7A77brhkZL9e_Rjqfrit-rpXS_VxpuBnFvC3ytcZ7SztjM-U8SIqSFTkmYKrGBUdS2OmtOe7iHLk6cg59EFG-HBOTgOdehDbAgw137j2o--SVSyGA2uObHLeeitakbUwsoSKdBmR-DEBnS9QMSJEiGQYbs4P3KLYj-gdaUc4LgFAKOG2eAw3YYRUAtyWzQoMBi4senbsziAIhISRRoIsYcOAFNrSOvIBKUQ2IEOBSQ4jB6BAkQMjAARCgCIDRKAIOJ5INJQHmJZ4BKqllnzAbTCSUxA3sHdRcoNzh3tkvJTQoFNoyTMINAhnteQbBDrIjJa8QaadpIhcIKeUNzgzXFRae5LjMalZMQvCiha3TsJEDkvhncCJDI9geoaN8CkNJ2lFTpPSDcKcETpKpodognU0Y5MFYhFClaBeeia5BNchiCmSj8XA1PwfNqlTEAY2f_EMo_aMVc-TQMXPz5gtpEHyM3YLoU1TP4UJwZquE8eBG06LfnFGcy7-izOqc8FTCL4p3fYZygvJu5RGHWn3zBPyRbw55rGUaSN-cYrtaXRhGol-GsiR_rGRvbjR_zYz0T9taJwbLUMbJiUw_Fr5q7FfKsG0wb1QaU8l4B53NOSnNrck4U4fq2DF1J81-0tVmDZ9LimMVQjymtCS8rT58_8MgBYK_WQIpBJIOVXi02yG35mHTO2Pw-E44Pfm9CF52wz1rk_SBRWsg-_KNnlIadNsYf96KVasgL9D17RDAu660WOm-vqwvLhuLzJVtxtcwTrlz9bTEz9_Aw) [Answer] # [Python](https://www.python.org), ~~126~~ 125 bytes ``` from math import* def f(q,m=0): for i in range(1,q):exec('m=sin(pi/q*i-pi/2-m*sqrt(1-m*m));'*99999);print(abs(round(m*100))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY49DoJAEEZ7TjGdMxuIYKUQDoOyK1vM_gxLooUnsaGRO3kbIcSved_r3nsJzzR4N8-fKZni_H0Z8QzcpQEsBy9JZb02YDDm3JZUZ2C8gAXrQDp311jlkWr90Dc8cDtah8Eeo7LFilPBaoySsFoPEzUHddlGTRDrEnbXEcVPrkdWVVkS0R6xGNx0l3_ZDw) Uses an iterative approach to converge to the true answer. This version is extremely slow and will time out. --- # [Python](https://www.python.org), ~~134~~ 133 bytes ``` from math import* def f(q,m=0): for i in range(1,q): for j in[0]*99999:m=sin(pi/q*i-pi/2-m*sqrt(1-m*m)) print(abs(round(m*100))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY49DoJAFIR7TvHKtxuIi5WSeBJjgYGVZ_L257EUHsBT2NDInbyNi8RpZuZLJpnXEh5p8G6e31Oy1eHztOIZuE0DEAcvSRddb8FiLPlkVFOA9QIE5EBad-uxLuNKf_ie8dlc9HFVw6eRHAbaRU1Vtn3FeoySsM6BlcqjIOQSttcRxU-uQ9a1MUqp7cxica1b-T_8Ag) This version will not time out. ]
[Question] [ This problem will have you analyzing circles drawn on the grid, with the gridlines drawn at integer values of \$x\$ and \$y\$. Let \$\varepsilon\$ be a very small number (think, \$\varepsilon = 0.0001\$). If we paint a filled-in circle of radius \$\varepsilon\$ centered at the origin, it will require paint to be in \$4\$ boxes; painting a circle of radius \$1 + \varepsilon\$ will send the paintbrush to \$12\$ different boxes (second, red circle); painting a circle of radius \$\sqrt 2 + \varepsilon\$ will send the paintbrush to \$16\$ different boxes (third, green circle). There's no way to draw a circle based at the origin that lives in exactly \$13\$ or \$14\$ or \$15\$ boxes, so the possible number of boxes that a circle can live in is given by `[4, 12, 16, ...]`. [![Circles based at the origin containing 4, 12, 16, ... boxes](https://i.stack.imgur.com/9FzcE.png)](https://i.stack.imgur.com/9FzcE.png) # Rules This challenge will give you a point \$(x,y)\$ on the plane consisting of two rational numbers \$x\$ and \$y\$. Your job is to output the first sixteen (or more!) terms of the sequence consisting of all numbers \$b\$ such that there is a way to draw a circle centered at \$(x,y)\$ that contains a part of exactly \$b\$ boxes. Any reasonable input is allowed: you can take the center point as a pair of floats, a complex number, a list containing numerators and denominators in some order, etc. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. # Examples In my example, the inputs are written as pairs of rational numbers. The first entry in the table is illustrated above. ``` [input] | [output] (x, y) | sequence -----------+---------------------------------------------------------------------- (0/1, 0/1) | 4, 12, 16, 24, 32, 36, 44, 52, 60, 68, 76, 80, 88, 104, 112, 120, ... (5/1, 5/2) | 2, 6, 8, 12, 16, 20, 22, 26, 34, 38, 40, 44, 48, 52, 56, 60, ... (1/3, 8/1) | 2, 4, 6, 8, 10, 12, 14, 18, 20, 22, 24, 26, 28, 30, 32, 34, ... (1/2, 3/2) | 1, 5, 9, 13, 21, 25, 29, 37, 45, 49, 61, 69, 77, 81, 89, 97, ... (1/3,-1/3) | 1, 3, 4, 6, 8, 9, 11, 13, 15, 17, 19, 21, 22, 24, 26, 29, ... (1/9, 8/7) | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ... ``` (If it helps, the first example is given by \$4\$ times [A000592](https://oeis.org/A000592).) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 317 313 305 298 281 274 231 221 210 207 195 181 136 126 111 109 108 bytes -an enormous 94 bytes thanks to mazzy! I must say, I never expected to beat Charcoal in this challenge; and when I posted that 317 byte answer, I certainly never expected to get it all the way down to the low 100s. I'm hopeful I can shave those final 10 to get to sub-100, but this feels so very optimized! Takes the x and y offsets (center of the circle) as inputs. Generates all points in the range `(-9..9,-9..9)`, then adds points for potential border intersections, which handles offset circles, and handles doubling point values on x,0 or 0,y coordinates when the circle is centered on the origin. Groups all of those points by their squared distance from the origin, then for each group outputs the sum of the group's count and the counts of all groups with distance smaller than that group. Multiplies all of the squared distances by 1e7 then casts to Integer to avoid issues with floating points. Because it groups the distances, it does output more than the first 16 terms, but as the challenger stated that this is acceptable, the TIO link truncates the output to the first 16 terms to make it more clear which tests succeed. ``` $x,$y=$args|%{,(-9..9+($p=$_%1)|%{($t=$_-$p)*$t*1e7})} $x|%{$n=$_;$y|%{[Int]($n+$_)}}|group|% c*|%{($s+=$_)} ``` [Try it online!](https://tio.run/##jZNNj9owEIbv/IpRZLoJSdjY@RaKhLRSpV7aquwNIQTUu2UFSRo7KivIb6djJ6Fc2OJD4vnwPO9Y47L4wyvxi@92Z/JS5xu5LfJsALiOZ3JwyHtGVtWrOA2Pjumm43Fqm6TMyHJILfSZROLeJaU1InJEedxYzYAcMEJyDEzIO27nX3K5MEluk6XVNKfXqqjL0xA2I11A2Jnyn/Gc5EI@rQQXkMHU1CKmR/1Ta5uXtVQbFfQcz7pE@KHkG8l/6ogRAGVAI2AB@Az8CIIAQgaRB1ECcQSJB0kC1MM8lcg8o63UOLdgZvhILQe/zLoFxfqQ9GAPGAMWgY8KEgg8pSBIlIgwQh3/59FHH3kJUm/zgpboaSj2kvTcQKFZAr6n@w/uwTHE@R@0RyGEFKgPjAILgaXgxxCEEKQQUYhSiGNIKCQppPG97bnqdxvodx0ilioyDYHGQFMt4dJmeg8t1ZcZfwBjGhciMG6RnqYyDQ40O@pJA2tAnnFSRTY1rauhVUOvjK/1fs2rjDatIKLVOKRH4rSPO9dy3DvbzIqLeidRk/np8hZhqpOtk@A7TAX3ZVsJiXKuis9kpQ61Bsow5sTEV/lWbHPDAcNaGI2lLVBme1DUmw0XIjM6quHy38ZFZJek27Sz@ffZUy1ksf@2fsPwYnp8UJGH7Kpf257MupJ97ckPXfkfohk03dWdPhfVfiXd59V6x89/AQ "PowerShell – Try It Online") # Ungolfed At this point, the ungolfed solution is more a representation of the logic behind my solution than it is an ungolfed version of the solution - as the iterations have been made, I haven't been able to keep up with the changes on the ungolfed version. I am leaving it in here, despite the discrepancy, in hopes that it will inspires to answer in their language of choice (or port it to their language) ``` #Take the x-offset, y-offset, and starting radius as a parameter #radius starts at 0, so that the first element will be the count of points on the origin of the circle param($xOffset,$yOffset,$radius=0) #set the x and y offsets to be in the range [0,1) $xOffset=$xOffset % 1 $yOffset=$yOffset % 1 #do 16 times (for the required 16 elements) 1..16|%{ #make an array of points $points = @() #set our limits to the edge of the bounding box of the circle #this will normally be within 1 of the actual circle, but offsets of .5 #will increase the search space due to .NET's banker's rounding $upperSearchLimitX = [Int]($xOffset+$radius+1) $lowerSearchLimitX = -$upperSearchLimitX $upperSearchLimitY = [Int]($yOffset+$radius+1) $lowerSearchLimitY = -$upperSearchLimitY #generate x and y for every combination of values in those ranges $lowerSearchLimitX..$upperSearchLimitX | %{ $x = $_ $lowerSearchLimitY..$upperSearchLimitY | %{ $y = $_ #add the point to our list $points+=@{x=$x;y=$y} #If x is zero, also add a special point that represents a border intersection to the list #this will also make x,0 points count for two when the center is at 0,0 if (!$x) { $points+=@{x=$x+$xOffset;y=$y} } #If y is zero, also add a special point that represents a border intersection to the list #this will also make 0,y points count for two when the center is at 0,0 if (!$y) { $points+=@{x=$x;y=$y+$yOffset} } } } #add the center point to the list $points += @{x=$xOffset;y=$yOffset} #set the minimum point as the closest point to our current circle that's outside of the bounds of the circle $minimum = $points|?{ ($_.distance=[Math]::Sqrt(($_.x-$xOffset)*($_.x-$xOffset)+($_.y-$yOffset)*($_.y-$yOffset))) -gt $radius }|sort distance -t 1 #set our new radius to be that point's distance from the x offset $radius = $minimum.distance #count the number of points that lie inside (but not on the boundary of) this new circle, output implicitly @($points|?{$_.distance -lt $radius}).Count } ``` [Try it online!](https://tio.run/##jZVtb9owEMdfk09xi7I1WQiNnedW0ZAqTZq0rdPoiyGEqpSaNRUBmjgaCPLZme3EAXXQgQTx5R5@/7vYYbn4Q/LiicxmO21azic0XcxjBdhns1smeZLp2up2Oi0I7WpruciTx7QsYttQpDOWC3gPSJGRsVyIu6jXQ/72/UbpaMtFOqcFxNDXDWaWyyXJByTJJ09f0yylv5hn9GVOxy3cbJgm4vEzLvpVvHWkypHSw33p9Tmlh0dLD@GYil7viIYt8I472ooV0u756h/EkbyhzOtoa5kox2bG/c2KDfx6zeZbcUc6Bf2dtjJAZLyOM@UQ9wkHWesTWSLYlENqs9i32j9Akz1BEX0AaBO0LJ2nWZlBLOO3nzYgWLp233tMC5rMJyQefUvo0/jqavCSU517VpYsaHx8ZZvcXluSUvsPbMMA6zeF5pEK0dtikVOQNLAo24qdJoCPtlHZ6lE6fX2v90AoWLO2cmX0bhblnCrVrlI0Sgp6kxSk3tHi9PQ34sI/6XxZUr7gTrvLTo30kNWSTCh5FB7VBYQB@YBdcDA4PrgueBh8G/wQAh9CG8IQkM3ieCC21bpS1T0F071LZHTZLzZOQVl9CCXYBowB@@AwBSG4NlfghlyE5zMd/@ehS4fxQkY9zXNroi2grJdQcl2OxiE4tujfPQeHGc55oz0EHkSAHMAIsAc4AicA1wM3Ah@BH0EQQIggjCAKzm3P4pfTQKfpkGERJyMPUAAoEhLaNqNzaJEYZvAGDAucx4BBjbQFFQuwK9i@JCnsdX3HdmoR87fuftOyV7IwvpfZA8ljVNWCNKGmq0lkzI5Cc@u@J2/WkTkpSnY2YvjQ/odAX8QeVBrQnEXotcGY6khjh9d6ZidN7YJqjNXKEBZws04sysmEFEWsNgjVIi9qq6gJEj2Z8ejH4KYs6CK7fXhm7nF/c8E9F/FBc6Z5PWhKytrXP0XlPaJSqmZO28@LPEuodZc8zMjuLw "PowerShell – Try It Online") I'm not the best at making images; if anyone can recommend a good tool for things like these, let me know. But here's a rough sketch of all the points that get checked along with the order we iterate to them in for x=3/8, y=1/4 [![First 9 iterations](https://i.stack.imgur.com/XkBKk.png)](https://i.stack.imgur.com/XkBKk.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 117 bytes ``` NθNηNζNε≧×εθ≧×ηζ≧×ηε≔⁰ηW‹Lυ¹⁶«≔⟦⟧δF…·±ηηF…·±ηηF¬›ΣX⟦κλ⟧²ηF…·÷⁺θκε±÷⁺θκ±εF…·÷⁺ζλε±÷⁺ζλ±εF¬№δ⟦νξ⟧⊞δ⟦νξ⟧F¬№υLδ⊞υLδ≦⊕η»Iυ ``` [Try it online!](https://tio.run/##jVFLa8JAED7rr5jjLGyhCvbSU7FQhFaC7U08pGaaXUw2uo9YUvrb0wlJrUoqXpb9HvvNzM5axXZdxFldz8w2@HnI38niTtwPj7E6w9UZJsYv8fbBOZ2ahU6Vxzedk5NAEnb/ikpCdUlsYlsFb5lgtFc6I8Bnco4Pk3qFQUgY3QkBX8NBZ16uJCTsHnwUFnBm1llwuqRFbFLCOaWxJx6pSRRwrWVeeHyyxLzF15BjVOz5ttxIyLjaWLTe/ryZ8Y@61AlhxDTuJGxEM52ErlK/oRNJiCuDK27mYnBn6AluxpsWwXhMJCyNhM9Vo0XBqSPm90v/3EFCt4dEHB6ckPzmsOCmf0s5GU9Ju9DvYWQ150xjx2HsrusJjGAC4/qmzH4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as numerator denominator numerator denominator. Explanation: ``` NθNηNζNε ``` Input the co-ordinates. ``` ≧×εθ≧×ηζ≧×ηε ``` Increase the scale of the grid so that the gridlines are drawn at intervals given by the product of the denominators. ``` ≔⁰η ``` Start enumerating circles with radius \$ \sqrt h + ε \$. ``` W‹Lυ¹⁶« ``` Repeat until 16 box counts have been found. ``` ≔⟦⟧δ ``` Start with an empty list of boxes. ``` F…·±ηηF…·±ηη ``` Search points with a distance of up to and including \$ h \$ both horizontally and vertically. ``` F¬›ΣX⟦κλ⟧²η ``` Skip points whose distance from the desired point is greater than \$ h \$. ``` F…·÷⁺θκε±÷⁺θκ±εF…·÷⁺ζλε±÷⁺ζλ±ε ``` Consider all boxes touching this point. ``` F¬№δ⟦νξ⟧⊞δ⟦νξ⟧ ``` Add the box to the list of boxes if it's not already present. ``` F¬№υLδ⊞υLδ ``` Add the count of boxes to the list of box counts if it's not already present. ``` ≦⊕η ``` Move on to the next radius. ``` »Iυ ``` Print all of the box counts found. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~51~~ 50 bytes ``` p-9:9*tJ*!+1ei1GP*1Gp\tFF5Mth3$v-!Z}J*!+u-|X<S&Y'Ys ``` The input consists of an array containing the denominators followed by an array containing the numerators. The output may contain more than 16 terms. [Try it online!](https://tio.run/##y00syfn/v0DX0spSq8RLS1HbMNU9IFPL0L0gpsTNzdS3JMNYpUxXMaoWJFeqWxNhE6wWqR5Z/P9/tKGCYSxXtIGCQSwA) Or [verify all test cases](https://tio.run/##y00syfmf8L9A19LKUqvES0tR2zDVPSBTy9C9IKbEzc3UtyTDWKVMVzGqFiRXqlsTYROsFqkeWfzf0MxK0yWqIuR/tKGCYSxXtIGCAZA0VDACkqYKpkDSGCxuqGABJI3A4oYKxmBxYzBbFyRtqWAOVQQA) (with output trimmed to 16 terms for convenience) ### Explanation Let (*x*, *y*) be the input values modulo 1. The code checks the distance from the (*x*, *y*) to each square with lower left corner (*a*, *b*), where *a* and *b* are integers. To do that, 9 points of the square are tested: (*a*+*m*,*b*+*n*) with *m* = 0, *x*, 1 and *n* = 0, *y*, 1, and the minimum of the 9 distances is kept. A grid of 19×19 squares with *a*, *b* = −9, −8, ..., 9 is generated. The distance from (*x*, *y*) to each square is computed as described in the preceding paragraph. The 361 distances are sorted and run-length encoded, and the cumulative sum of the run lengths is the desired output. To keep floating-point issues as controlled as possible, instead of using the actual values for *x*, *y*, *a*, *b*, *m*, *n*, the code uses those values multiplied by the product of the two input denominators. ``` p % Implicit input: array with the denominators. Product -9:9 % Push [-9, -8, ... 9] * % Multiply, element-wise tJ* % Duplicate, multiply by j (imaginary unit) element-wise !+ % Transpose, add with broadcast. This generates the 19×19 grid of % complex values 1e % Linearize into a row vector i % Input: array with the numerators 1GP % Push first input again. Flip it * % Multiply, element-wise 1Gp % Push first input again. Product (*) \ % Modulo, element-wise (**) t % Duplicate FF % Push [0 0] 5Mth % Push (*) again. Duplicate, concatenate with itself horizontally 3$v % Concatenate three elements vertically. Gives a 3×2 matrix - % Subtract (*) with broadcast ! % Transpose. The result is a 2×3 matrix Z} % Split into two rows with 3 elements J* % Multiply by j (imaginary unit) element-wise !+ % Transpose, add with broadcast. This gives a 3×3 matrix with the % 9 points to be considered in each square u % Unique. This gives a column vector with the (unique) values -| % Subtract with broadcast, absolute value. Gives a 9×361 matrix X< % Minimum of each column. This gives the 361 distances S % Sort &Y' % Run-length encoding, producing only the run lengths Ys % Cumulative sum. Implicit display ``` [Answer] # [Perl 5](https://www.perl.org/), 225 bytes ``` sub f{my($x,$y,@a,@r,%b,$n,$i)=(@_,map{[cos,sin],[-cos,sin],[cos,-sin],[-cos,-sin]}map$_/12.566,0..720);while(@r<16){$n+=2e-3;$b{int$x+$n*$$\_[0]+1e4,int$y+$n\*$$_[1]+1e4}++for@a;$b=keys%b;$i=0,push@r,$b if$b>$r[-1]&&$i++>1}@r} ``` [Try it online!](https://tio.run/##TVHbbqswEHzPV/jBbeGwSWxzTTlE/EDf@oZQFCpy6rYBBIlOEOLb012HXJBsxrO7M2NoyvbHPx@7kr2X3eH19a1uS3ZA2CVrP57te5bSKbFmGcvEUgLDLQeWMQ@YVLgCYAqxi9hF7CH2EQcCVwQsRC5CHCGWgobMlBI5y4FEfRL1l8qIYonhAIsexHFYIVaIXTLCmicuRh5i48Z8mgpuonLpouWUlOreg7CYxClM9GDgXUwUibqCNpp0vbso3XFKKskU1wpF0EvhWeFZ4dkNMRliD3GAfIDvMCRzGopWNBXeRVeUNLyJGs8psT@lDi/JjRmll9MNqI@uwSR1ysCI2vFsV7eW@W/2MGP47HuL66oBXp4aO0n5Jr7RJ@A9UVi@kvxffUi@al29wAvsppZLUXcWVYGqFpVTIwlEYst47o4F2w1XYUi3kLbwVACvgGs7sdIN7LfNkH3UHXS6yiGb3yGh@QNr8Ij9fLOUauEHAYjFIlTCjv9/6p/SStu/MrAHXjmJKuduzItBVwd@cnj1h/NNJnJHlh4Q1185abjRcfAjpVscSb7LvnsqYq4TAc2x@8TEvGB6x4s1b7O5zJ@fuXactRzTdjyffwE "Perl 5 – Try It Online") All brawn and no brain, but the 5 given tests passes in about 11 seconds at link above. It's easy to find new tests that will fail. The function f starts at the given input (x,y) and circles around in ever wider circles counting boxes it falls into. To be (almost) sure it found all boxes it needs two rounds for a new number of boxes to be registered into the return array @r. This solution is bound to have floating point "rounding errors" and "over- or understepping" when the radius is increased. To solve this properly I'd try to sort the distances of the edges of the close by boxes, but I'm too lazy to even think about that now. ``` sub f{ my($x,$y,@a,@r,%b,$n,$i)= ( @_, map {[cos,sin],[-cos,sin], [cos,-sin],[-cos,-sin]} map $_/12.566, 0..720 ); #12.566 ~ 4*π while(@r<16){ #repeat until 16 elems found $n+=2e-3; #increase radius $b{ int$x+$n*$$\_[0]+1e4, #keys of dict b contains found boxes int$y+$n\*$$_[1]+1e4 }++ #+1e4 to avoid rounding up for x<0 or y<0 for @a; #for all angles tested $b=keys%b; #b = number of boxes so far $i=0, push@r,$b #register b in solution if if !@r || $b > $r[-1] && $i++ > 1#it's > last number and if it's #found at least twice } @r #return the 16 counts found } ``` [Answer] ## Javascript, 199 bytes My first code golf in a long time! I originally started with a brute force solution, but couldn't get the step sizes small enough to have it produce the correct answers in a timely manner. So here's a more elegant solution that iterates points in a similar fashion to Zaelin's answer. ``` (x,y)=>{b={0:1};g=w=>b[d=parseInt(w*1e7)]=1+(b[d]|0);for(u=x%1-9;++u<9;){g(u*u);for(v=y%1-9;++v<9;)g(u*u+v*v)||u+1<9||g(v*v)}s=0;return Object.keys(b).sort((a,b)=>a-b).map(v=>(s+=b[v])).slice(0,16)} ``` [Try it online!](https://jsfiddle.net/v1L756kc/1/) ### Ungolfed ``` (x, y) => { b = { 0: 1 }; // initialize a map for the lengths g = (w) => { // function g is used to add to the map d = parseInt(w * 1e7); // avoid floating point rounding errors b[d] = 1 + (b[d] | 0); // increment point with length d } for (u = (x % 1) - 9; ++u < 9; ) { //loop over "u" coordinates g(u * u); // add horizontal line for (v = (y % 1) - 9; ++v < 9; ) // loop over "v" coords g(u * u + v * v); // add corner (u + 1 < 9) || g(v * v); // add vertical line (but only once per above for loop) } s = 0; // sum of circles up to this point return Object.keys(b) .sort((a, b) => a - b) .map((v) => (s += b[v])) // aggregate number of circles visited .slice(0, 16); // first 16 terms only }; ``` It relies on the fact that every new vertical, horizontal and corner node found represents exactly one new grid square found. Note that the x=0 or y=0 cases do not have to be treated specially, it just means that we hit a node and a vertical/horizontal line at the same time, which represents the multiple new grid squares hit. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 15 bytes ``` 9:NṡvJΠ$v∆dsĠ@¦ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCLin6ggMSAzIC8gfCAxTiAzIC8g4p+pOiIsIjk6TuG5oXZKzqAkduKIhmRzxKBAwqYiLCIiLCIiXQ==) Mostly a port of [Zaelin Goodwin's Powershell answer](https://codegolf.stackexchange.com/a/217459/100664), go look at that if you want to understand why this works. Outputs more than the first 16 terms, although beyond that not all terms may be accurate. ``` ṡ # Range from 9 # 9 to :N # -9 vJ # Append x and y to two copies of that Π # Take the cartesian product $v∆d # Distance between each point and the input s # Sort Ġ@ # Take lengths of runs of identical items ¦ # Cumulative sum ``` ]
[Question] [ This challenge is inspired by [this app](https://play.google.com/store/apps/details?id=com.andreasabbatini.logicgamestk). The test cases are borrowed from that app. --- This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, where the objective is to solve the largest test cases in the least amount of time. There are provided some smaller test cases, so that people might test their algorithms faster. --- You'll be given a square input grid, of dimensions **n-by-n** where **9 <= n <= 12**. This grid will be divided into **n** areas, where the cells of each area has a unique identifiers (I'll use lower case letters from **a-l** in the the text here, but you may choose whatever you like, for instance integers **1-12**). The input may look like this (optional input format): ``` aabbbbbcc adddbbbcc adeeecccc adddefgcc hhhdifggg hdddifffg hhhiifffg hihiifffg iiiiiiggg ``` Or, easier to visualize: [![enter image description here](https://i.stack.imgur.com/AoZTJm.jpg)](https://i.stack.imgur.com/AoZTJm.jpg) ## Challenge: You are to place **2\*n** trees in this park, according to the following rules: * There shall be exactly **2** trees per column, and **2** trees per row * All areas shall have exactly **2** trees. * No trees can be adjacent to another tree, vertically, horizontally or diagonally The solution to the layout above is: [![enter image description here](https://i.stack.imgur.com/J3mEKm.jpg)](https://i.stack.imgur.com/J3mEKm.jpg) Note: There is only one solution to each puzzle ### Additional rules: * The input and output formats are optional + The output might for instance be a list of indices, a grid with **1/0** indicating if there's a tree in that position, or a modified version of the input where the trees are indicated * The execution time must be deterministic * The program must finish withing 1 minute at @isaacg's computer + Specs: 4 CPUs, i5-4300U CPU @ 1.9 GHz, 7.5G of RAM. * In case your program can't solve the two largest test case in one minute each then the time for the second largest (**n=11**) will be your score. You'll lose against a solution that solves the largest case. ### Test cases: I might edit this list if submissions seems to be customized to fit these test cases. **12-by-12**: ``` --- Input --- aaaaabccccdd aaaaabccccdd aaaaabbbbddd eeeafffgbghh eeaafffgbghh eefffffggghh eeefijffghhh iieiijjjjkhh iiiiijjjjkhk lljjjjjjjkkk llllllkkkkkk llllllkkkkkk --- Solution --- aaaaabcccCdD aaaaaBcCccdd aAaaabbbbdDd eeeaffFgBghh eeAaFffgbghh eefffffGgGhh EeefijffghhH iiEiIjjjjkhh IiiiijjjjkHk lljJjJjjjkkk lLllllkkKkkk lllLllKkkkkk ``` **11-by-11**: ``` --- Input --- aaaaaaabbcc adddabbbbcc edddbbbbbbc eddddbbbbbb effffggghhh effffgghhii eefffjjhhii eeeejjjhhii eeejjjjkiii jjjjjjkkiii jjjjjkkkiii --- Solution --- aaAaaaabbCc adddAbBbbcc eDddbbbbbbC eddDdBbbbbb effffggGhHh eFfffGghhii eefFfjjhHii EeeejjjhhiI eeEjjjjKiii JjjjJjkkiii jjjjjkKkIii ``` **10-by-10** ``` --- Input --- aaaaabccdd aeaabbbccd aeaabfbgcd eeeaafggcd eeeaafghcd eeeiifghcd ieiiigghcd iiijighhcd jjjjighhcd jjjggghhdd --- Solution --- aaAaabccdD aeaaBbBccd aEaabfbgcD eeeaaFgGcd eEeAafghcd eeeiiFghCd IeiIigghcd iiijigHhCd JjJjighhcd jjjgGghHdd ``` **9-by-9** ``` --- Input --- aabbbbbcc adddbbbcc adeeecccc adddefgcc hhhdifggg hdddifffg hhhiifffg hihiifffg iiiiiiggg --- Solution --- aAbBbbbcc adddbbBcC adEeEcccc AdddefgCc hhhDiFggg hDddifffG hhhiIfFfg HiHiifffg iiiiiIgGg --- Input --- aaabbbccc aaaabbccc aaaddbcce ffddddcce ffffddeee fgffdheee fggfhhhee iggggheee iiigggggg --- Solution --- aaAbBbccc AaaabbcCc aaaDdBcce fFddddcCe fffFdDeee fGffdheeE fggfHhHee IggggheeE iiIgggGgg ``` [Answer] ## JavaScript (ES6), 271 bytes Takes input as an array of arrays of characters. Returns an array of bitmasks (integers) describing the position of the trees on each row, where the least significant bit is the leftmost position. ``` f=(a,p=0,r=[S=y=0],w=a.length)=>a.some((R,y)=>a.some((_,x)=>r[y]>>x&1&&(o[k=R[x]]=-~o[k])>2),o=[])?0:y<w?[...Array(1<<w)].some((_,n)=>(k=n^(x=n&-n))<=x*2|k&-k^k|n&(p|p/2|p*2)||r.some((A,i)=>r.some((B,j)=>A&B&n&&i<y&j<i))?0:(w=r[y],f(a,r[y++]=n,r),r[--y]=w,S))&&S:S=[...r] ``` ### Formatted and commented ``` f = ( // given: a, // - a = input matrix p = 0, // - p = previous bitmask r = [ // - r = array of tree bitmasks S = y = 0 ], // - S = solution / y = current row w = a.length // - w = width of matrix ) => // a.some((R, y) => a.some((_, x) => // if there's at least one area with more r[y] >> x & 1 && (o[k = R[x]] = -~o[k]) > 2 // than two trees: ), o = []) ? // 0 // abort right away : // else: y < w ? // if we haven't reached the last row: [...Array(1 << w)].some((_, n) => // for each possible bitmask n: (k = n ^ (x = n & -n)) <= x * 2 | // if the bitmask does not consist of k & - k ^ k | // exactly two non-consecutive bits, n & (p | p / 2 | p * 2) || // or is colliding with the previous r.some((A, i) => r.some((B, j) => // bitmask, or generates more than two A & B & n && i < y & j < i // trees per column: )) ? // 0 // yield 0 : // else: ( // w = r[y], // save the previous bitmask f(a, r[y++] = n, r), // recursive call with the new one r[--y] = w, // restore the previous bitmask S // yield S ) // ) && S // end of some(): return false or S : // else: S = [...r] // this is a solution: save a copy in S ``` ### Test cases This snippet includes an additional function to display the results in a more readable format. It is too slow to solve the last test case. Expected runtime: ~5 seconds. ``` f=(a,p=0,r=[S=y=0],w=a.length)=>a.some((R,y)=>a.some((_,x)=>r[y]>>x&1&&(o[k=R[x]]=-~o[k])>2),o=[])?0:y<w?[...Array(1<<w)].some((_,n)=>(k=n^(x=n&-n))<=x*2|k&-k^k|n&(p|p/2|p*2)||r.some((A,i)=>r.some((B,j)=>A&B&n&&i<y&j<i))?0:(w=r[y],f(a,r[y++]=n,r),r[--y]=w,S))&&S:S=[...r] format = (a, w) => a.map(n => [...('0'.repeat(w) + n.toString(2)).slice(-w)].reverse().join('')).join('\n') console.log(format(f([ [..."aabbbbbcc"], [..."adddbbbcc"], [..."adeeecccc"], [..."adddefgcc"], [..."hhhdifggg"], [..."hdddifffg"], [..."hhhiifffg"], [..."hihiifffg"], [..."iiiiiiggg"] ]), 9)); console.log(format(f([ [..."aaabbbccc"], [..."aaaabbccc"], [..."aaaddbcce"], [..."ffddddcce"], [..."ffffddeee"], [..."fgffdheee"], [..."fggfhhhee"], [..."iggggheee"], [..."iiigggggg"] ]), 9)); console.log(format(f([ [..."aaaaabccdd"], [..."aeaabbbccd"], [..."aeaabfbgcd"], [..."eeeaafggcd"], [..."eeeaafghcd"], [..."eeeiifghcd"], [..."ieiiigghcd"], [..."iiijighhcd"], [..."jjjjighhcd"], [..."jjjggghhdd"] ]), 10)); ``` [Answer] # C, official time: 5ms for 12x12 ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <omp.h> #define valT char #define posT int #ifndef _OPENMP # warning Building without OpenMP support # define omp_get_max_threads() 1 # define omp_get_num_threads() 1 # define omp_get_thread_num() 0 #endif #define MIN_THREADED_SIZE 11 static void complete(posT n, valT *workspace) { const posT s = n * 3 + 2; const valT *regions = workspace; valT *output = &workspace[n*2+1]; for(posT y = 0; y < n; ++ y) { for(posT x = 0; x < n; ++ x) { // putchar(output[y*s+x] ? '*' : '-'); putchar(regions[y*s+x] + (output[y*s+x] ? 'A' : 'a')); } putchar('\n'); } _Exit(0); } static void solveB(const posT n, valT *workspace, valT *pops, const posT y) { const posT s = n * 3 + 2; const valT *regions = workspace; const valT *remaining = &workspace[n]; valT *output = &workspace[n*2+1]; for(posT r = 0; r < n; ++ r) { if(pops[r] + remaining[r] < 2) { return; } } for(posT t1 = 0; t1 < n - 2; ++ t1) { posT r1 = regions[t1]; if(output[t1+1-s]) { t1 += 2; continue; } if(output[t1-s]) { ++ t1; continue; } if((pops[t1+n] | pops[r1]) & 2 || output[t1-1-s]) { continue; } output[t1] = 1; ++ pops[t1+n]; ++ pops[r1]; for(posT t2 = t1 + 2; t2 < n; ++ t2) { posT r2 = regions[t2]; if(output[t2+1-s]) { t2 += 2; continue; } if(output[t2-s]) { ++ t2; continue; } if((pops[t2+n] | pops[r2]) & 2 || output[t2-1-s]) { continue; } output[t2] = 1; ++ pops[t2+n]; ++ pops[r2]; if(y == 0) { complete(n, &workspace[-s*(n-1)]); } solveB(n, &workspace[s], pops, y - 1); output[t2] = 0; -- pops[t2+n]; -- pops[r2]; } output[t1] = 0; -- pops[t1+n]; -- pops[r1]; } } static void solve(const posT n, valT *workspace) { const posT s = n * 3 + 2; valT *regions = workspace; valT *remaining = &workspace[n]; valT *pops = &workspace[n*s]; // memset(&remaining[n*s], 0, n * sizeof(valT)); for(posT y = n; (y --) > 0;) { memcpy(&remaining[y*s], &remaining[(y+1)*s], n * sizeof(valT)); for(posT x = 0; x < n; ++ x) { valT r = regions[y*s+x]; valT *c = &remaining[y*s+r]; valT *b = &pops[r*3]; if(*c == 0) { *c = 1; b[0] = y - 1; b[1] = x - 1; b[2] = x + 1; } else if(x < b[1] || x > b[2] || y < b[0]) { *c = 2; } else { b[1] = b[1] > (x - 1) ? b[1] : (x - 1); b[2] = b[2] < (x + 1) ? b[2] : (x + 1); } } // memset(&output[y*s], 0, (n+1) * sizeof(valT)); } memset(pops, 0, n * 2 * sizeof(valT)); posT sz = (n + 1) * s + n * 3; if(n >= MIN_THREADED_SIZE) { for(posT i = 1; i < omp_get_max_threads(); ++ i) { memcpy(&workspace[i*sz], workspace, sz * sizeof(valT)); } } #pragma omp parallel for if (n >= MIN_THREADED_SIZE) for(posT t1 = 0; t1 < n - 2; ++ t1) { valT *workspace2 = &workspace[omp_get_thread_num()*sz]; valT *regions = workspace2; valT *output = &workspace2[n*2+1]; valT *pops = &workspace2[n*s]; posT r1 = regions[t1]; output[t1] = pops[t1+n] = pops[r1] = 1; for(posT t2 = t1 + 2; t2 < n; ++ t2) { posT r2 = regions[t2]; output[t2] = pops[t2+n] = 1; ++ pops[r2]; solveB(n, &regions[s], pops, n - 2); output[t2] = pops[t2+n] = 0; -- pops[r2]; } output[t1] = pops[t1+n] = pops[r1] = 0; } } int main(int argc, const char *const *argv) { if(argc < 2) { fprintf(stderr, "Usage: %s 'grid-here'\n", argv[0]); return 1; } const char *input = argv[1]; const posT n = strchr(input, '\n') - input; const posT s = n * 3 + 2; posT sz = (n + 1) * s + n * 3; posT threads = (n >= MIN_THREADED_SIZE) ? omp_get_max_threads() : 1; valT *workspace = (valT*) calloc(sz * threads, sizeof(valT)); valT *regions = workspace; for(posT y = 0; y < n; ++ y) { for(posT x = 0; x < n; ++ x) { regions[y*s+x] = input[y*(n+1)+x] - 'a'; } } solve(n, workspace); fprintf(stderr, "Failed to solve grid\n"); return 1; } ``` Compiled with GCC 7 using the `-O3` and `-fopenmp` flags. Should have similar results on any version of GCC with OpenMP installed. ``` gcc-7 Trees.c -O3 -fopenmp -o Trees ``` Input and output format are as given in the question. On my machine this takes ~~0.009s~~ ~~0.008s~~ 0.005s for the 12x12 example, and ~~0.022s~~ ~~0.020s~~ 0.019s to run all the examples. On the benchmark machine, isaacg reports 5ms for the 12x12 example using the original (non-threaded) version of the code. Usage: ``` ./Trees 'aaabbbccc aaaabbccc aaaddbcce ffddddcce ffffddeee fgffdheee fggfhhhee iggggheee iiigggggg' ``` --- Just a simple brute-force solver, working on one row at a time. It runs at a good speed by recognising impossible situations early (e.g. no region cells remaining, but less than 2 trees in the region). The first update improves cache hits by putting related data close together in memory, and makes the possible-trees-remaining-in-segment calculations slightly smarter (now accounts for the fact that trees cannot be adjacent). It also extracts the outermost loop so that fewer special cases are needed in the hottest part of the algorithm. The second update makes the outermost loop run in parallel across the available processors (using OpenMP), giving a linear speed boost. This is only enabled for n >= 11, since the overhead of spawning threads outweighs the benefits for smaller grids. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), Official Timing: 1.2s on 12x12 edit: no longer code golf ``` import java.util.*; // Callable method, takes an int[][] and modifies it static void f(int[][] areas){ List<List<BitSet>> areaBitSets = new ArrayList<>(); List<List<BitSet>> areaTreeBitSets = new ArrayList<>(); for(int i = 0; i < areas.length; i++){ areaBitSets.add(new ArrayList<BitSet>()); areaTreeBitSets.add(new ArrayList<BitSet>()); } // Add a bitset to our list representing each possible square, grouped by area for(int i=0; i < areas.length; i++){ for(int j=0; j < areas.length; j++){ BitSet b = new BitSet(); b.set(i*areas.length + j); areaBitSets.get(areas[i][j]).add(b); } } // Fold each set onto itself so each area bitset has two trees for(int i=0; i < areas.length; i++){ for(int j=0; j<areaBitSets.get(i).size()-1; j++){ for(int k=j+1; k <areaBitSets.get(i).size(); k++){ if(canFoldTogether(areaBitSets.get(i).get(j),areaBitSets.get(i).get(k), areas.length)){ BitSet b = (BitSet)areaBitSets.get(i).get(j).clone(); b.or(areaBitSets.get(i).get(k)); areaTreeBitSets.get(i).add(b); } } } } // Starting with area 0 add each area one at a time doing Cartesian products Queue<BitSet> currentPossibilities = new LinkedList<>(); Queue<BitSet> futurePossibilities = new LinkedList<>(); currentPossibilities.addAll(areaTreeBitSets.get(0)); for(int i=1; i < areaTreeBitSets.size(); i++){ while(!currentPossibilities.isEmpty()){ BitSet b= (BitSet)currentPossibilities.poll().clone(); for(BitSet c: areaTreeBitSets.get(i)){ if(canFoldTogether(b,c,areas.length)){ BitSet d=(BitSet)b.clone(); d.or(c); futurePossibilities.add(d); } } } currentPossibilities.addAll(futurePossibilities); futurePossibilities.clear(); } // Get final output and modify the array BitSet b = currentPossibilities.poll(); for(int i=0; i<areas.length*areas.length; i++){ areas[i/areas.length][i%areas.length] = b.get(i)?1:0; } } // Helper method which determines whether combining two bitsets // will still produce a valid output static boolean canFoldTogether(BitSet a, BitSet b, int size){ // See if there are trees too close to each other int c=-1; while((c=a.nextSetBit(c+1))>=0){ int d=-1; while((d=b.nextSetBit(d+1))>=0){ int r1=c/size; int r2=d/size; int c1=c%size; int c2=d%size; int rDifference = r1>r2 ? r1-r2 : r2-r1; int cDifference = c1>c2 ? c1-c2 : c2-c1; if(rDifference<2 && cDifference<2) return false; } } // Check for row and column cardinality BitSet f,g; for(int i=0; i<size; i++){ f = new BitSet(); f.set(i*size,(i+1)*size); g=(BitSet)f.clone(); f.and(a); g.and(b); f.or(g); if(f.cardinality()>2){ return false; } f=new BitSet(); for(int j = 0; j<size; j++){ f.set(j*size+i); } g=(BitSet)f.clone(); f.and(a); g.and(b); f.or(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7DhQBt7L3IfaQAbiKBpU1BUFXtxFIioxnUA6@kKeo/Eta3hRPYRENPH1cmxjBsLcXKksyKTQpLAYkFmdTMFgVukZJWxKGsFjrB3WZvm6KETqJhxr5aS2iP0MMwCKaTkcephSWPMA@aTGIfmjShFVyFE3pkHThpdo0nSUcXRdSrji5ElV1NjT/zNEVWMqR@gqanagyf8DnA5zHaG6iwReEOiIZTakE0HFALouMBrYNS4hk6HcPr176S03HQyFjFMKsySCOhWXeJcj5ndGkTAJTcuGyiUuQrGygqsYnGzU4@pf1Za844duoVSWcBlpbFl0X1CcepdH89idnjCpc2V7h0iAMlkS/uvsQ7MjjAmfcBKURVW69IMB3XgqeLsu2sp5MOh6riq6jeFyUfLXWW83zh3D3kjdrxf@e6Fy2liFE5Stw/9MoDmX@cWuGxjFwYhSuVO1LN7Imq16vOWFilGCTo7m7UB6i3ENu41t7Ydt8H1NHrfWeU3940UG/xrWoW8c5r70uUfX6wrYEa/SvUu5b23mvtqAr5EduPNeSHBupjKfm2fFYov4WjTtjHl8DC0SMudAyHLdINZHlrgbbeRp2376Dh/gQ14A@zbwYCQ/biVhu2GpaVxCXW3l9wz@XapmavlxIb2e5vKYib73CNaWBERvbD8ddwfAz7eLwk3YpgACJAkf2V3g9K@@WyYlMH9wVnxOZTmxV3jNdDI4v0IyZwSu6dIiw3Hv4B "Java (OpenJDK 8) – Try It Online") TIO link is for the 12x12 test case. TIO reports 2.429s for the run time. Takes an array of integers as the input and modifies the array to contain 1s for trees and 0s for non-trees. This runs for all testcases. The largest testcase runs on my machine in less than a second, although I have a pretty powerful machine Test code for the 12x12, can modify for others ``` public static void main(String[] args){ int[][] test = {{0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3}, {0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3}, {0, 0, 0, 0, 0, 1, 1, 1, 1, 3, 3, 3}, {4, 4, 4, 0, 5, 5, 5, 6, 1, 6, 7, 7}, {4, 4, 0, 0, 5, 5, 5, 6, 1, 6, 7, 7}, {4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7}, {4, 4, 4, 5, 8, 9, 5, 5, 6, 7, 7, 7}, {8, 8, 4, 8, 8, 9, 9, 9, 9, 10, 7, 7}, {8, 8, 8, 8, 8, 9, 9, 9, 9, 10, 7, 10}, {11, 11, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10}, {11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10}, {11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10}}; long l = System.currentTimeMillis(); f(test); System.out.println("12x12: " + (System.currentTimeMillis() - l) + "ms"); for(int[] t : test){ System.out.println(Arrays.toString(t)); } } ``` Produces this on my machine: ``` 12x12: 822ms [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1] [0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0] [0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0] [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] [0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0] [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0] [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] [0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0] ``` [Answer] # [Clingo](http://potassco.sourceforge.net/), ≈ 7 ms for 12×12, 116 bytes ``` {t(X,Y):c(X,Y,Z)}=2:-Z=1..n. :-X=1..n,{t(X,1..n)}!=2. :-Y=1..n,{t(1..n,Y)}!=2. :-t(X,Y),t(X+1,Y;X+1,Y+1;X,Y+1;X-1,Y+1). ``` (Newlines are optional and not counted.) Run with `clingo plant.lp - -c n=<n>` where `<n>` is the grid size. The input format is a list of `c(X,Y,Z).` statements for each cell (`X`, `Y`) colored `Z`, with 1 ≤ `X`, `Y`, `Z` ≤ `n`, separated by optional whitespace. The output includes `t(X,Y)` for each tree at (`X`, `Y`). The time is pretty meaningless as it’s basically just startup time, so consider this a vote for larger test cases. ### Demo ``` $ clingo plant.lp -c n=12 - <<EOF > c(1,1,1). c(2,1,1). c(3,1,1). c(4,1,1). c(5,1,1). c(6,1,2). c(7,1,3). c(8,1,3). c(9,1,3). c(10,1,3). c(11,1,4). c(12,1,4). > c(1,2,1). c(2,2,1). c(3,2,1). c(4,2,1). c(5,2,1). c(6,2,2). c(7,2,3). c(8,2,3). c(9,2,3). c(10,2,3). c(11,2,4). c(12,2,4). > c(1,3,1). c(2,3,1). c(3,3,1). c(4,3,1). c(5,3,1). c(6,3,2). c(7,3,2). c(8,3,2). c(9,3,2). c(10,3,4). c(11,3,4). c(12,3,4). > c(1,4,5). c(2,4,5). c(3,4,5). c(4,4,1). c(5,4,6). c(6,4,6). c(7,4,6). c(8,4,7). c(9,4,2). c(10,4,7). c(11,4,8). c(12,4,8). > c(1,5,5). c(2,5,5). c(3,5,1). c(4,5,1). c(5,5,6). c(6,5,6). c(7,5,6). c(8,5,7). c(9,5,2). c(10,5,7). c(11,5,8). c(12,5,8). > c(1,6,5). c(2,6,5). c(3,6,6). c(4,6,6). c(5,6,6). c(6,6,6). c(7,6,6). c(8,6,7). c(9,6,7). c(10,6,7). c(11,6,8). c(12,6,8). > c(1,7,5). c(2,7,5). c(3,7,5). c(4,7,6). c(5,7,9). c(6,7,10). c(7,7,6). c(8,7,6). c(9,7,7). c(10,7,8). c(11,7,8). c(12,7,8). > c(1,8,9). c(2,8,9). c(3,8,5). c(4,8,9). c(5,8,9). c(6,8,10). c(7,8,10). c(8,8,10). c(9,8,10). c(10,8,11). c(11,8,8). c(12,8,8). > c(1,9,9). c(2,9,9). c(3,9,9). c(4,9,9). c(5,9,9). c(6,9,10). c(7,9,10). c(8,9,10). c(9,9,10). c(10,9,11). c(11,9,8). c(12,9,11). > c(1,10,12). c(2,10,12). c(3,10,10). c(4,10,10). c(5,10,10). c(6,10,10). c(7,10,10). c(8,10,10). c(9,10,10). c(10,10,11). c(11,10,11). c(12,10,11). > c(1,11,12). c(2,11,12). c(3,11,12). c(4,11,12). c(5,11,12). c(6,11,12). c(7,11,11). c(8,11,11). c(9,11,11). c(10,11,11). c(11,11,11). c(12,11,11). > c(1,12,12). c(2,12,12). c(3,12,12). c(4,12,12). c(5,12,12). c(6,12,12). c(7,12,11). c(8,12,11). c(9,12,11). c(10,12,11). c(11,12,11). c(12,12,11). > EOF clingo version 5.1.0 Reading from plant.lp ... Solving... Answer: 1 c(1,1,1) c(2,1,1) c(3,1,1) c(4,1,1) c(5,1,1) c(6,1,2) c(7,1,3) c(8,1,3) c(9,1,3) c(10,1,3) c(11,1,4) c(12,1,4) c(1,2,1) c(2,2,1) c(3,2,1) c(4,2,1) c(5,2,1) c(6,2,2) c(7,2,3) c(8,2,3) c(9,2,3) c(10,2,3) c(11,2,4) c(12,2,4) c(1,3,1) c(2,3,1) c(3,3,1) c(4,3,1) c(5,3,1) c(6,3,2) c(7,3,2) c(8,3,2) c(9,3,2) c(10,3,4) c(11,3,4) c(12,3,4) c(1,4,5) c(2,4,5) c(3,4,5) c(4,4,1) c(5,4,6) c(6,4,6) c(7,4,6) c(8,4,7) c(9,4,2) c(10,4,7) c(11,4,8) c(12,4,8) c(1,5,5) c(2,5,5) c(3,5,1) c(4,5,1) c(5,5,6) c(6,5,6) c(7,5,6) c(8,5,7) c(9,5,2) c(10,5,7) c(11,5,8) c(12,5,8) c(1,6,5) c(2,6,5) c(3,6,6) c(4,6,6) c(5,6,6) c(6,6,6) c(7,6,6) c(8,6,7) c(9,6,7) c(10,6,7) c(11,6,8) c(12,6,8) c(1,7,5) c(2,7,5) c(3,7,5) c(4,7,6) c(5,7,9) c(6,7,10) c(7,7,6) c(8,7,6) c(9,7,7) c(10,7,8) c(11,7,8) c(12,7,8) c(1,8,9) c(2,8,9) c(3,8,5) c(4,8,9) c(5,8,9) c(6,8,10) c(7,8,10) c(8,8,10) c(9,8,10) c(10,8,11) c(11,8,8) c(12,8,8) c(1,9,9) c(2,9,9) c(3,9,9) c(4,9,9) c(5,9,9) c(6,9,10) c(7,9,10) c(8,9,10) c(9,9,10) c(10,9,11) c(11,9,8) c(12,9,11) c(1,10,12) c(2,10,12) c(3,10,10) c(4,10,10) c(5,10,10) c(6,10,10) c(7,10,10) c(8,10,10) c(9,10,10) c(10,10,11) c(11,10,11) c(12,10,11) c(1,11,12) c(2,11,12) c(3,11,12) c(4,11,12) c(5,11,12) c(6,11,12) c(7,11,11) c(8,11,11) c(9,11,11) c(10,11,11) c(11,11,11) c(12,11,11) c(1,12,12) c(2,12,12) c(3,12,12) c(4,12,12) c(5,12,12) c(6,12,12) c(7,12,11) c(8,12,11) c(9,12,11) c(10,12,11) c(11,12,11) c(12,12,11) t(1,7) t(1,9) t(2,3) t(2,11) t(3,5) t(3,8) t(4,10) t(4,12) t(5,5) t(5,8) t(6,2) t(6,10) t(7,4) t(7,12) t(8,2) t(8,6) t(9,4) t(9,11) t(10,1) t(10,6) t(11,3) t(11,9) t(12,1) t(12,7) SATISFIABLE Models : 1+ Calls : 1 Time : 0.009s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s) CPU Time : 0.000s ``` To make the input/output format easier to deal with, here are Python programs to convert from and to the format given in the challenge. ### Input ``` import sys print(' '.join("c({},{},{}).".format(x + 1, y + 1, ord(cell) - ord('a') + 1) for y, row in enumerate(sys.stdin.read().splitlines()) for x, cell in enumerate(row))) ``` ### Output ``` import re import sys for line in sys.stdin: c = {(int(x), int(y)): int(z) for x, y, z in re.findall(r'\bc\((\d+),(\d+),(\d+)\)', line)} if c: t = {(int(x), int(y)) for x, y in re.findall(r'\bt\((\d+),(\d+)\)', line)} n, n = max(c) for y in range(1, n + 1): print(''.join(chr(ord('aA'[(x, y) in t]) + c[x, y] - 1) for x in range(1, n + 1))) print() ``` ]
[Question] [ Output this binary sequence of length 1160: ``` -++-+--++-++-+--+--++-+--+--++-+--++-++-+-++--++-+---+-++-+--+--++++--+--++-+--++-++----++-++-+-++--++-+-+---++-+--++-++-+--++-+--+---+-++-+--++-++-+--+--++-++-+--++-+--+++-+-+----+++-+--+--+++---++-++-+--+--+++--+-+-+--+-+++-++-+--+--++-+--++-++-+--+--++--+++---+++-+---++-+--++--+-+--+-+++-+--++-++-+--++-+--+--++-+--++--+-++-+-+--+-+-++-+--++-+--+--++-+-+-++-+-+-++---+-+--++++--+---++-+-++-+--++-+--+--++-+--++++--+---+-++++--+--++-++-+--++-+--+--++-+--++-++-+--++-+--+--++-++-+----+++-+--++--+++---+-++-+--+-++---+-++-++-+--+--++--++++-+--+--+--++++--+--+++---++-++-+--++--+-+--+--++-++-+--+--+-+++-++-+--+--++--+-++-++-+--+--+--++-++-+--+++---++-+--++-++---+++---++-++----+++--+-++-+--+--++-+--++-++-+-++--++--++----+++-++--++----++-+++--++---+++----+-+-++-++-++-+-+----+++--++-+--++-++-+--+--+--++-+--++-++-+--++--+-+--+-+-+-++++---+-+-++--+--+-+-+-++-+-+++--+-+--+--+-+++--+-+++---++-+--+--++-++--++---++-+-++--++-+---+-++-+--+-++--++-+--++-+--+-+++-+--++--+-+-+++--+-+--++-++-+--+--+-++---+-++-+-++--++-+--+++-+----++--+-++-+-++--++-+--++-+-++--++-+---+-++-+--+++----+-+-++--++-+--++-++-++-+--+--+--++++---++---+-+-++-+-+++--+-++--+-+--+-+-++---+++-++ ``` **The sequence** This finite sequence is tightly structured in a way that I hope lends to unique methods for compression. It arises from the Erd≈ës discrepancy problem, which was featured in a [previous challenge](https://codegolf.stackexchange.com/questions/59608/four-steps-to-the-left-vipers-four-steps-to-the-right-a-cliff-dont-die). Treating the terms as +1 and -1, this is a maximal-length sequence of discrepancy 2, which means that: > > For every positive step size `d`, if you take every `d`'th term (starting with the `d`th term), the running sum of the resulting sequence remains between -2 and 2 inclusive. > > > If you think of each `+` to mean a step right and `-` to mean a step left, this means that the walk of every `d`th instruction never travels more than 2 steps away from the start position. For example, for `d=3`, taking every 3rd term gives the sequence `+-++--+--+-...`, whose running sums are `[1,0,1,2,1,0,1,0,-1,0,1,...]`, which never hit -3 or 3. ``` -++-+--++-++-+--+--++-+--+--++-+--+... ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ + - + + - - + - - + - 1 0 1 2 1 0 1 0 -1 0 -1 ... ``` This sequence was found in 2014 via a computer search. [See this paper](https://arxiv.org/pdf/1405.3097v2.pdf), where the sequence is reproduced in Appendix B. The search proves that 1160 is the maximum length of a discrepancy-2 sequence, though there is more than one sequence of that length. The Erd≈ës discrepancy problem, [proven in 2015](https://arxiv.org/abs/1509.05363), says that any such sequence must have finite length for any maximum discrepancy `c` in place of 2. **Time requirement** Your code should finish within *5 seconds*. This is to limit brute-forcing. **Output format** You can use any two fixed distinct characters or values for `+` and `-` in any list-like or string-like format. The format should be one where the 1160 bit-values can be directly read off, not for example encoded as a number via its binary representation or a string via character values. For string output, a trailing newline is allowed. **Leaderboard** ``` var QUESTION_ID=122304,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/122304/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 149 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‚Äú√óGO·∫à*m¬¨¬ø3d{·∫ã·∫°‚Ū@∆Å]Zƒä·ªµINB∆¨·∏ä·πø·∫ä*N¬π·∫∏√∑∆≤·∫ã…ºo·π¨·∏≥¬£¬Æ‚Åæ∆ô≈í·ªç¬°[P1&·∫°‚Ǩ·∫ä †N·ªåX·∏¢·πñƒó√ê√ü‚Å𷪧·π󬨂ÅπE#·ª•·∏∑·∏å·πÅ≈º≈ºR=∆ä√ë¬≥ƒ±…≤-·π≠·ªå·πæ…≤·∫éƒø·ª¥‚Å∂‚Ǩ·∏ãt…¶√ê\·ªµ∆í‚Åæ∆í·ª•·π´·π°ƒäKp∆≠·∫èka·π™,·∫ä»ß‚Ū·∏ÖM…ì%Y·∏∑s∆≤∆≠l¬§√¶ƒäb·π¨9D6·∫é∆ò·∫ì^≈í‚Å∑∆ù·∏∑·∏∑‚Ǩ·∏ü1g‚ÄôB ``` There is some pattern, for example only 81 of the 256 length 8 binary strings are present if one chops the sequence into eights, but I have not (at least yet) noticed any way to utilise any to reduce byte count from this straight forward base 250 compression converted to a binary list. **[Try it online!](https://tio.run/nexus/jelly#HY9NSwJRFIZ/TNTCciFB0CIIKSIii1Z9QxG0qCioXRsnCGK0MoVMSEwzgxqDtJr7IQr3zlya/sU7f8TOuDtwzvs87@mH6UddnFuCuIodKUf1xvfOITIQ1dCS08baWvdsyO/5VNI4YDZ4D8KOpRSHYNo1LboNOsfgtGyrZ/URWl1T8vOQ16q6sZwYiUAXDmX@nlKQ2VWwGvi9V9Q5XQktDlkHLyqHxtkhyBcwFywLbvkdv7MyZWx9p9reZ9CKgzcpD94NyHnj9SC/QusnYrPMWdDQuU2qafKRPx@B@Dt41bMXTkwT4vZgB/xtjGr8vtJfYJeLQWF4jWynpmWah6quG569S29MzkwQ3jxAFLZ9ormmPOjkDkyVxH6YLiX7qgaZIVV8tP8P "Jelly ‚Äì TIO Nexus")** (the footer formats the binary list to a string for easier direct comparison). [Answer] # [Python 2](https://docs.python.org/2/), ~~269~~ ~~259~~ ~~256~~ ~~247~~ ~~245~~ 243 bytes ``` r=[1] c=int('bmqnh8j8rdo4mirjos6uxbfthu8t39pjy6up43axryzwbwcu5d528nsakitjwqbo6dnnozy0oybhk6jduaoc53lqkzdb04opj5t50a24w9he5y7qbgd2',36) while c:t=sum(sum(r[::-k])/3for k in range(1,264)if len(r)%k<1);r[-1:]=cmp(0,t)or c%2*2-1,1;c>>=t==0 print r ``` [Try it online!](https://tio.run/nexus/python2#Fc8xkoMgAEDR3lPQZCI7OisorDFLLuJYCGgEFBRxjLm8my1@@Yp/elajJhJM2RBf@bTYodSll66YlNdupduL92HYypDfZn3QbS7y9uWP9853sRFJcGnX1qig94U7Kq117yNzBx8M1XJrnSD5uJi35FnhZk0CyVpc7LehI8fPwp8SX5Ocwmgf1NgBUQW2blP8n6@rKjUN/M5754EBygLf2mcXowTTAqoejJ2NPbyYXwTvvk5R1TAxzXGWBPgR4oK/cIoSdBePBwuMZdHsP5fAn@cf "Python 2 ‚Äì TIO Nexus") [Answer] ## JavaScript (ES6), ~~263~~ ~~253~~ 252 bytes I tried to use as less payload data as possible. Sadly -- but not surprisingly -- this requires quite a lot of decompression code. Breakdown: * payload data: 75 bytes, encoded as a 100-character Base64 string * code: ~~163~~ ~~153~~ 152 bytes Below is a formatted version without the data. The raw code is in the demo snippet. ``` f = (a = Array(264).fill(n = p = 0)) => n++ < 1160 ? '+/-'[ p += !a.some((v, i) => n % i | v * v - 4 ? 0 : r = v / 2, r = atob`...`.charCodeAt(p / 8) >> p % 8 & 1 || -1 ), r + 1 ] + f(a.map((v, i) => n % i ? v : v - r)) : '' ``` ### How? We keep track of the running sums **a[i]** of every **i**-th terms. Each time one these sums hit the lower bound **-2**, we know that the next term must be a **+**. The same logic applies to the upper bound. This is helpful up to **i = 264** and doesn't save any extra byte beyond that. This leaves us with 599 terms that cannot be guessed. We store them as **‚åà599 / 8‚åâ = 75** bytes, encoded in a 100-character Base64 string. ### Demo ``` f=(a=Array(264).fill(n=p=0))=>n++<1160?'+/-'[p+=!a.some((v,i)=>n%i|v*v-4?0:r=v/2,r=atob`aaLpW0oUDbs8lXXhj5IqpM3ctZD1Q6qtrJKqXmbBRkoZh3o1zCL1WhUo2Yu9KkU2q0CGI33SUzvb5wW+KgnZrZfUY/UhMtnBdEk8`.charCodeAt(p/8)>>p%8&1||-1),r+1]+f(a.map((v,i)=>n%i?v:v-r)):'' o.innerHTML = f() ``` ``` <pre id=o style="white-space:pre-wrap;word-wrap:break-word"> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~110~~ ~~109~~ 107 bytes ``` ;1mS‚Ǩ:3o/N»Ø¬Æ·π™·π≠·∏∑ ‚Äúƒñ·πÑ·∫ã{X·πõ-ƒ∞I·πó¬Æ6‚ź·∏û2a‚Ū!ƒä·∫⻕+¬°∆묕mvr·∫ìs·πò√ó‚Å¥√ß&$n·ª¥·ª§)M7?·∫ä·∫é·∏Ö=·π†∆àT·πô·∏廕·ª•·∫ãX·∏å‚ŵ·∏¢‚Å∫·∏≤L√∑√¶T∆•ƒøv‚Ǩ%·∏ü¬¢¬Æ!ƒñ‚ÄôB·∏§‚Äô¬©·πõ‚ÅΩ¬°…†√ÜD‚ǨN√ß/ ``` This takes too long on TIO, but it finishes in under 3 seconds on my desktop computer. [Try it online!](https://tio.run/nexus/jelly#AdYAKf//OzFtU@KCrDozby9OyK/CruG5quG5reG4twrigJzEluG5hOG6i3tY4bmbLcSwSeG5l8KuNuKBvOG4njJh4oG7IcSK4bqJyKUrwqHGkcKlbXZy4bqTc@G5mMOX4oG0w6cmJG7hu7Thu6QpTTc/4bqK4bqO4biFPeG5oMaIVOG5meG4jMil4bul4bqLWOG4jOKBteG4ouKBuuG4skzDt8OmVMalxL924oKsJeG4n8Kiwq4hxJbigJlC4bik4oCZwqnhuZvigb3Cocmgw4ZE4oKsTsOnL/// "Jelly ‚Äì TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~135~~ ~~133~~ ~~130~~ ~~129~~ ~~105~~ 104 bytes ``` 42‚ÄúI=ƒ∞ƒóZP*√∞E·∏Ñ·∫à·πÜ'mB∆ùƒó≈ª∆ù6¬Æ·πÜ…º·∏•[b»¶ƒó·π°V¬£(6·πò…±X)·πÑ·∫π6~K7¬∞»§√Ñ·ª¥¬•∆ù√á5pr·∏≥ƒ°≈ª¬£∆≠·πó·πÑF·πæ·∏É{¬©@…º‚Äô·∏É√уãL L+√ò.√ÜDm@N√ᬰ¬ß¬ßNo¬•/·π†o-·π≠ √á‚ÅΩ¬°…†¬°·∏ä ``` Based on the previous elements of the sequence, the algorithm makes an educated guess what the next element could be. This works for all but 99 elements, whose indices are hardcoded so the corresponding elements can be swapped. [Try it online!](https://tio.run/##AcMAPP9qZWxsef//NDLigJxJPcSwxJdaUCrDsEXhuIThuojhuYYnbULGncSXxbvGnTbCruG5hsm84bilW2LIpsSX4bmhVsKjKDbhuZjJsVgp4bmE4bq5Nn5LN8KwyKTDhOG7tMKlxp3DhzVwcuG4s8ShxbvCo8at4bmX4bmERuG5vuG4g3vCqUDJvOKAmeG4g8OExItMCkwrw5guw4ZEbUBOw4fCocKnwqdOb8KlL@G5oG8t4bmtCsOH4oG9wqHJoMKh4biK//8 "Jelly ‚Äì Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 224 bytes ``` 862:o'$Te]BQHoHxkw!-CEjv(j=zGp.8_C{\?wkH{t&%W.:ja#7=+>"/,=0wDJ+"2BREtgh9_2I%1>+99T3kPrknzlJ}&8kUR(S!pX]C]05u{"6MHA7"gg(M6\5Vp.k.18Y(c~m&wroTrN)sf" |>\,Lg80C:nUez|l;<h~m(%]4xx6?`=qGtZ):d"*"@~1M.T}jJ)Bl7>Ns >9$8R1MlkG'F3:qZaY" ``` The ouput is of the form `1 0 0 1 0 ...`, where `1` corresponds to `'-'` and `0` corresponds to `'+'`. [Try it online!](https://tio.run/nexus/matl#BcGBToJAAADQX9FL8AgjwISD4izIIBauCCsdzFwZjkNBpGCg/Dq91yJJVJN@z1sH@ouVWCUpuhfGJPqDkVaZKYeWRu2PC2LVOU29c2q0OpM1FoPLgcYX9zYLRN2d5OFGWYqPlIBZRfGG5Dkjuyq2TzQiMxe@dtOPwAj40W8NJMe6k0EYQkfyR28pRzgBzeFXs6WLLPGyKXP4AZ0j9gdPIeINdTdbV8f4@mbTbCEVXJWlNP7U9ma@YNRvcA5uG8HhvFNkM3os4@mhg5UecgUnJmb/YajuF6s5aNt/ "MATL ‚Äì TIO Nexus") ### Explanation The sequence has been run-length encoded. All 720 runs have lengths 1, 2, 3 or 4, with 3 or 4 being less common. So each 3 has been replaced by 2, 0, 1 (a run of 2, then a run of 0 of the other symbol, then a run of 1 again) and similarly each 4 has been replaced by 2, 0, 2. This gives a ternary array of length 862. This array is converted to base-94 encoding, and is the long string shown in the code (`'$Te...kG'`). Base 94 encoding uses all 95 printable ASCII chars except for the single quote (which would have to be escaped). The code converts that string from base 94 to base 3, and uses the result to run-length decode the symbols `[1 0 1 0 ... 0]` (array of length 862). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 95 bytes ``` ‚Äúq·∫° Ç·πÖs‚ÅΩf√ò ãZ%B√ûƒ°ƒ±¬Ω.m0&u‚Å∫Ts∆ù»ßAu·ª¥≈º‚Å∂3u√û$+»∑@4·π¢‚ÄôB·∏§C¬©¬µmL√ÜD$¬ßS·π†»Ø¬Æ·π™NL·∏ü‚Äú‚Å∂ .¬£¬µ+¬£g√ê9√ꬶ.√±√󬵬•¬§¬Æ‚Äò√Ñ·∏§¬§…ó}¬°·π≠√∏‚ÅΩ¬°…†¬°·∏ä ``` A middle point between my two previous approaches. The code attempts to guess 842 elements of the sequence and hardcodes the remaining 318 ones. 19 of the guesses are incorrect and have to be reverted via a list of hardcoded indices. [Try it online!](https://tio.run/##AbYASf9qZWxsef//4oCcceG6ocqC4bmFc@KBvWbDmMqLWiVCw57EocSxwr0ubTAmdeKBulRzxp3Ip0F14bu0xbzigbYzdcOeJCvIt0A04bmi4oCZQuG4pEPCqcK1bUzDhkQkwqdT4bmgyK/CruG5qk5M4bif4oCc4oG2IC7Co8K1K8KjZ8OQOcOQwqYuw7HDl8K1wqXCpMKu4oCYw4ThuKTCpMmXfcKh4bmtw7jigb3CocmgwqHhuIr//w "Jelly ‚Äì Try It Online") ### How it works ``` ‚Äúq·∫° Ç·πÖs‚ÅΩf√ò ãZ%B√ûƒ°ƒ±¬Ω.m0&u‚Å∫Ts∆ù»ßAu·ª¥≈º‚Å∂3u√û$+»∑@4·π¢‚Äô ``` This is a bijective base 250 literal that uses Jelly's code page for digits and encodes the integer \$\scriptsize 380009100940380065412452185545474826295694594854898450166594167299196720639075810827320738450934\$, which `¬©` stores in the register. ``` B·∏§C¬© ``` `B` converts the integer to binary, `·∏§` unhalves/doubles the resulting bits, then `C` subtracts the results from \$1\$. The result is a list of 318 copies of \$\pm1\$. ``` ¬µmL√ÜD$¬ßS·π†»Ø¬Æ·π™NL·∏ü‚Äú‚Å∂ .¬£¬µ+¬£g√ê9√ꬶ.√±√󬵬•¬§¬Æ‚Äò√Ñ·∏§¬§…ó}¬°·π≠ ``` This monadic chain takes a prefix of the desired output (with a prepended \$0\$) and appends the next element of the output. The chain works as follows: ``` mL√ÜD$¬ßS·π†»Ø¬Æ·π™NL·∏ü‚Äú‚Å∂ .¬£¬µ+¬£g√ê9√ꬶ.√±√󬵬•¬§¬Æ‚Äò√Ñ·∏§¬§…ó}¬°·π≠ Monadic chain. Arument: A (array) L√Ü√ê$ Compute all divisors of the length of A. m For each divisor d, generate the subarray of each d-th element. ¬ß Take the sum of each subarray. S Take the sum of the sums. ·π† Take the sign of the sum. »Ø¬Æ If the result is 0, replace it with the array in the register. ·π™ Tail; pop and yield the last element, modifying the register for a zero sum. This is a no-op for a non-zero sum. ‚Äú‚Å∂ .¬£¬µ+¬£g√ê9√ꬶ.√±√󬵬•¬§¬Æ‚Äò√Ñ·∏§¬§ Yield all indices of incorrect guesses. NL·∏ü …ó¬° If the length of A doesn't appear among the indices, negate the result. ·π≠ Append the result to A. ``` ``` √∏‚ÅΩ¬°…†¬°·∏ä ``` This niladic chain resets the return value to \$0\$, calls the monadic link from above 1160 times (`‚ÅΩ¬°…†` encodes the integer \$1160\$), then removes the first element (\$0\$) with `·∏ä`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 150 bytes ``` ‚Äùa‚àß‚à®~‚ÑÖ¬πê√∑Ժ،º6fÔº£C‚ź‚àï‚ŵ^;Ÿ‘¬´¬∑T:‚àïÔº§ _=v¬ßAÔº®Œ,—<Ôº∞r¬¢E!‚󮬱Ժ¨^|.œÑ"ÔºÆO‚Äúš√æùŽ‚àß<n`b√ûÔº•√∑Œ≤$+Ôº∫‚ü¶5‚Å∂‚Ū.Œª‹Œ∂d‚ߥX>w,‚äû?‹‚üß‚åà‚™™-h√∑¬≥N‚ÄúÔº´‚Å∫L¬ø>œÅ@Ôº∞‚ü≤‚Üò3ŒΩŒ∑Kx√∑?>™Ž¬ø•:8Ôº∂¬¶¬£œŒµÔºß‚Üßx‚ÑÖ7¬∂ NÔº≤√º"m”‚ü¶)&¬∂bÔº•“Ôºπv‚Äù ``` [Try it online!](https://tio.run/nexus/charcoal#DZDNSgJhGIXX0VUkEUTmJvrBTItoVdimhSsriWhTixbmIsoBkyFFihIr1IEsRzT6sZxBfUs4s/@8h/cG3kuwb3sW53nOGXG6ss@mzWbjgjNX6OLGc4U@FC0cCtXW2SA2i2x04suwcIsW3J2gToRexndXkrDXhBrI@1EKCX2e4nljgksNfAm9xc8Dw4xP6H2b02U8eX@ooKBRoZO9hFcVevVc1Z6cEeqxVZ9nw2GjH1B95JRzwPZPLHzm5@tqBDm2bM6b3GzOHnkuvqO6TqjFRm8Lg/Dl0FjVZLbanH2YU7/K3Ux5biSMRxQwQDG4JOSgjhrKqiNkc9ZO6aGLcMaiQm2PfMe41wLTU3ASWgp3Qt2kfmU0@gc "Charcoal ‚Äì TIO Nexus") Makes use of Charcoal's builtin string compression. Uses `.` for `-` and `!` for `+`. [Answer] ## CJam, 153 bytes ``` "Ke¬≤√âL¬∫[ O%2¬πd¬≤√ù,√âe√±lr[¬¥Ke√ô.Y¬≠K-iZ[*T√´ √äYl¬∞√ù √ãe√ãd¬ºY%¬≥l69,√ñ√âm√ô¬§¬∂√âcN9<il¬≤S3√Ñ√è#8√µ$¬Ød¬∂√ã%√זּ√ï(√ñ√묣√⬶]-2√ãEd¬∂)/4¬¶YL¬∫X√µ2√â-¬∞√ßR5¬©√Ñ"256b2b ``` Uses `1` for `-`, and `0` for `+`. Contains unprintables. [Try it online!](https://tio.run/nexus/cjam#fVNBSwJBFL4bdOgQ1NESqvEVbCkJXTsZBdUhky6mB2G79Bu8qGgUuJDkqTAiorIMik7f@2E22u7szOzWZWfm7Tffe@/73oyS8PIVDLi@g69iAt5eysFnWQZ6aXhcr6DBr@55cR7vEnbF12ivFvA0myd41WN4xZVDfkxwo@DihXsJiWiOYc0yvgtow0MvhbcpN5tLs2Q7m5EEd/jg@im83dxW1cXgYJ1rfLGwycNFPM@V5c9mCl3uTKPPnSV56xK340pwg/4JOdzcRhctiUNvGd7aBvoFWfoRDx2ukyzifh@tDB64lnQy2ZJTGo1ICBI0@f5uKLLxfwkVIQMsomCKuSWIIrkCEhJ/lKHDFIu/DYL2rcnqH0VMX2ZEUVgVGgxxNRvIMGEsTGhLwBzopmSKIxeaPiJelr9VVRHSugj6VTDtaMmijobLpuChUCZDRHk7hUFiz4aZh0JX/51MDauf/MshqzIkNI4UKNJIjLya2b4yylwtTiIcxlCTYLFtIqHPQvShmeWZk0lWLsuIkEdYr4nMATZTxJVh6GcqE5kW0oXRmifjrQR@/QA "CJam ‚Äì TIO Nexus") This is pretty simple. Converts a long sequence from base 256 to base 2. [Answer] # [Python 3](https://docs.python.org/3/), ~~236~~ 232 bytes Thanks to [Mego](https://codegolf.stackexchange.com/users/45941/mego) for saving 4 bytes ``` #coding:437 print(bin(int.from_bytes('√ªKe‚ñì‚ïîL‚ïë[\r√ªO%2‚ï£d‚ñì‚ñå,√ª‚ïîe√®¬±lr[\x1a‚î§Ke√Ü‚îò√Ñ.Y¬°\x16K-√ªiZ√ª[*TŒ¥\r‚ï©Yl‚ñë‚ñå\r√Ü‚ï¶e√Ü‚ï¶d‚ïùY√Ñ√ª¬•%‚îÇ\x0bl69,‚ïì‚ïîm\x12‚îò√±‚ïîc√ªN9<il‚ñìS3‚îÄ‚ïß#8‚å°$¬ª\x19d‚ï¶%√ú‚ïí\x0e¬™‚ïí(‚ïì‚ï§√∫√ª‚ï¬™]-2‚ï¶E√ú√¨d‚•)√ª/4¬™YL‚ïëX‚å°2‚ïî-‚ñëœÑR√¨5‚åê‚îÄ'.encode('437'),'big'))[2:]) ``` [Try it online!](https://tio.run/nexus/bash#VZE7T8JQFIB3fkUTJG0NrbxEMMTNCaOJOohgDJSqTbAltRrZjCFMDCK9xAEHBFEJC4mTd7tn1/9w/gieNi4u99zz@s7LqHrSlpRMZhPatXeW05stqVCQZF1eRg2nbtnnm5n0RqTpWran1CxbIamfuc7laa3lmVeKDLxo4qCPzN9B1itXXOB7sRSycT2wDrpx4OQz4V0sGm65cpusoj8pmtBB/wnaekmMyJYtasCtY@Dl1cPvz4qL7KPUwEGP8gnYQTY1w7eO7LkEbeDiNYb@feU2UWtk83FkQf1LAqUC6gLZC@kG8N18wSJO/yCN/h2yt2gOu6MVwSkyXw@jpjEYInskkilm9FFC1gS@wrbFWMxONJpmug1DmAcp4lUFvpYRs1Iw7xHxyO1r1OxPex/m69h9oFqybtq0PlORaXuyGpdr1rmsquXU5om61CMRy3DsG0nTPEcymhQiFf6f4O8ioY/0SLPlXTh2@r91@Qs "Python 3 ‚Äì TIO Nexus") Uses the CP-437 encoding. Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for pointing out an error. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~284 275~~ 273 bytes ``` f(i){for(i=1160;i--;)putchar(L"ÂòªÁãä·¢≠ÌâèÏ¥∂ÍúäÎçÖ¶¶ÌÉãÌô©‰•¢ÁäõΩ•Ï¥¥ÍãíÊçôʧ∂‚πúÌú©Â§™‚´±ù©•‰§¥Óöõù≠êÏúä„ÉúÏ∞ª‰∂¨ÈöìÏõÉʶ±„öúÂ≠âÓ¥¶„öíÌå©ÏßÜÔíìù©åÊ•¢Íô±È≠ÉÊ¥¥„íöÔâ≠‰º¢ÍöìÔàµÍ¨îÍìïÍï©Ê¶ñÎìíÂã©Ìܶ‚ô±È©≠‰Æ¥Íì•ÈéçÁîé„ööÌ穉¥¢‰öõù´çʶ∞Íì≤ÎçÖ‰¥∂Îíöi"[i/16]>>i%16&1|48);} ``` [Try it online!](https://tio.run/##FZDfSsJQAMbfRSjmhdQgJJB8gt4gupCBdS76g9RVdTWS3JzFjkYe581wJ066cHEahL1M7uzIznbUN7B5@cH34@P3aaUzTdts6goo3tWvGgo4UtXyfgWUSpXi9e2Ndl5rKMeF@G22MI0/15et54yGwjFS6zHGWOqm7BPmuQtjkBIvo1SYNrf6fBTOfxzpkHj0MR8H6yHx2Igu0WA99F8yx4h0J5vOWDhJEMwGOsdBhJzYby0pjpAt2yR7b65smHNt7rmiHyS@zimNbLRq@ezXFQiunr7FpCtgT/QIx68ptGOTyCae52Xis08qoJd0rEW3EyEkLcKoy7b7Y4vjqYBfuQCjYWojUDgBe2r5tFoFO2p5V70/OCxWHjYXNXCp5J8o2/AP "C (gcc) ‚Äì Try It Online") Just an array lookup. Edit: -2 and bugfix thanks to @S.S.Anne [Answer] # [Python 2](https://docs.python.org/2/), ~~364~~ 250 bytes Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for saving 114 bytes. ``` print bin(int('28x0lphxjx8ze4uuhtdzo0oebr25amtmuxm62cbit0ibdwjm2sf50clh2ejq0a73ndseo5tove8uqca6nf66bo4abbkg867woh2b435at0o3pddvqmsqp29b6as5bd4eo28xgwkkj607gp66icba1q4n9fc13dltp45j340mpzbc56wsrbb3oejnczsbzfgh82xdi8aku8m4wlmwuxkgy4yaew7pu4p1g',36))[2:] ``` [Try it online!](https://tio.run/nexus/python2#Dc5LdoMgFADQrXSW5JwOkJ@kW@npgAeIqHwUCMTN24zu9F7pcKF8gQv3j/cbFh1tae5LF6ehtc5FnxFFAwdm0hdfu@dYgSvIgW6Lx3liSG0zNsuO5EiCziayEl9G1F1JHibOIVIJsFrBxxZnDJQwWVAkSevX7vOe8BO4zAw0NfETsG1dF45Gmzh3CuSw0/Cc1ED0VhJlC6HIpxMU4y0fACSaJagzwznZWeCunZBrFZ62zbfaV/umb2namCpNg719E/54/OKfv@v6Bw "Python 2 ‚Äì TIO Nexus") [Answer] ## [C#](http://csharppad.com/gist/fe76ec516d5c0b9eb1c7d9168476d936), 385 bytes --- ### Data * **Input** none * **Output** `String` The pretended result. --- ### Golfed ``` ()=>{var s="i¬¥\u009aM6¬≥E¬§√≤i¬∞√ö√çF\u009bM\"√ìi6\u009au\u000e\u0093\u008d¬§√•K¬¥\u009am&q√묶R√©¬¥√íi\u0096¬•i¬§√הּ\u0014√≤5¬¶\u0093O\"√≤m4\u009am4\u009bC¬¶qib√öL√¥\u0093√â√Ü√ì)6\u0092√≠&[I6\u009ci¬±√Ü√É\u0096\u0093M¬¨√å;0√ú√á\n√õP√¶\u009bI4√öe*√±Y*√ó).\\i6cY¬¢√í√ç4¬∫er\u009bIb√ñi√ê√ãY¬¶¬≥E¬ß\n√ç6√íO\u0018¬≠r√äV;";var o="";foreach(var c in s)foreach(var b in Convert.ToString(c,2).PadLeft(8,'0'))o+=(char)(43+(49-(int)b)*2);return o;}; ``` --- ### Ungolfed ``` () => { var s = "i¬¥\u009aM6¬≥E¬§√≤i¬∞√ö√çF\u009bM\"√ìi6\u009au\u000e\u0093\u008d¬§√•K¬¥\u009am&q√묶R√©¬¥√íi\u0096¬•i¬§√הּ\u0014√≤5¬¶\u0093O\"√≤m4\u009am4\u009bC¬¶qib√öL√¥\u0093√â√Ü√ì)6\u0092√≠&[I6\u009ci¬±√Ü√É\u0096\u0093M¬¨√å;0√ú√á\n√õP√¶\u009bI4√öe*√±Y*√ó).\\i6cY¬¢√í√ç4¬∫er\u009bIb√ñi√ê√ãY¬¶¬≥E¬ß\n√ç6√íO\u0018¬≠r√äV;"; var o = ""; foreach( var c in s ) foreach( var b in Convert.ToString( c, 2 ).PadLeft( 8, '0' ) ) o += (char) ( 43 + ( 49 - (int) b ) * 2 ); return o; }; ``` --- ### Full code ``` using System; namespace Namespace { class Program { static void Main( String[] args ) { Func<String> f = () => { var s = "i¬¥\u009aM6¬≥E¬§√≤i¬∞√ö√çF\u009bM\"√ìi6\u009au\u000e\u0093\u008d¬§√•K¬¥\u009am&q√묶R√©¬¥√íi\u0096¬•i¬§√הּ\u0014√≤5¬¶\u0093O\"√≤m4\u009am4\u009bC¬¶qib√öL√¥\u0093√â√Ü√ì)6\u0092√≠&[I6\u009ci¬±√Ü√É\u0096\u0093M¬¨√å;0√ú√á\n√õP√¶\u009bI4√öe*√±Y*√ó).\\i6cY¬¢√í√ç4¬∫er\u009bIb√ñi√ê√ãY¬¶¬≥E¬ß\n√ç6√íO\u0018¬≠r√äV;"; var o = ""; foreach( var c in s ) foreach( var b in Convert.ToString( c, 2 ).PadLeft( 8, '0' ) ) o += (char) ( 43 + ( 49 - (int) b ) * 2 ); return o; }; Console.WriteLine( $" Input: <none>\nOutput: {f()}\n" ); Console.ReadLine(); } } } ``` --- ### Releases * **v1.0** - `385 bytes` - Initial solution. --- ### Notes * None [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 149 bytes ``` ‚Ä¢19G√àR√ï≈∏ p—Ç6¬Ω√∑√ú;–≤V√•ŒîƒÄ√à‚ÇѬ§√ú¬≥A í–º5[¬¶P≈†√Ö√∏≈ì^‚Äö‚ÇÜ√®¬≥¬¶√¨√≥V‚ÄúL√õ'√üq;Œ±√錩¬™√Ƭª(2‚à笩d√§f√ó5 V5√ö‚Äùg√ú/\^(√É‚àä∆µ!3≈°√ç3¬∞(¬ßA√é‚Äû«ù‚ÇÇ√à‚ÇÖ√߬£6√≥√†√ñCsa*z∆í√ö¬•√é\¬™D¬π,n‚àä√∞ÀÜ.√´√ßPŒ±«ù∆í.√â‚àç¬Ø√º‚ÇǬ≥Œõ‚Äòg‚àçŒò√æ‚Äú‚Äö≈ìŒî–∏‚Äπ‚Ä¢b ``` Super boring. Just a compressed number. Uses `1` for `-` and `0` for `+`. [Try it online!](https://tio.run/nexus/05ab1e#FZBBS8JgHIfvfYo6NSKMkgnhSQq6dJAOuyRCEXmLolunl5WyAneYVjJnmalLi9JGNMk6/H9tQsHL@grvF1mv19/h@T08sWCt5dUNGFu4DPyZwz89RZ94h5OOXjV0ePWbwRD6GbXhkJf5saKxuk3dbNBEEX5QyQtmC72EB/Koiyd4mmDOJurzuD1K8yFM3qM@nulDWRFGmXp7aO/jWp3VVNiCNQpwlnJ5BafCuAjf5pLBHcpJGijkZmAKdjNpCF2fChTh0n0KHpq4WjveWTgJLdjUgZmj/jqNFg8kAIPfUgKPcLN8OGmEVgLn088XjCWEPF4XrFaQC6/hS1pK86DCq5Ev2EhW2I3jfw "05AB1E ‚Äì TIO Nexus") [Answer] # PHP, 276 Bytes ``` <?=gzinflate(base64_decode("dVJRFgMgCDoQj/tfb2+boqj9VJohQgQI8rv+D1yHuIIytGLsYh6vwAlYIMS62mVCiWMm56vfHiGOuTwjiMHQEC7OVlkNzzK0LZFTN8l0gavGdX4wOfJDsZpXZS0csig0l13wEsoRlvKzhYHMv+F9MnxaCXHWrC2Kx4UqQ8o4qmgNcsjbzA5lZG7LE6LdNMlt2sRKFpNhk/sL59N6DSMKp4No7vP2QcP0c2XWb6nPblqYfJBfHw==")); ``` [Try it online!](https://tio.run/nexus/php#BcHJcoIwAADQf/Gk40GkEHVapmNB9kRRy3bpsAYwGjEYlJ@n741f3woe6ltJkq6YpgkrgPSXFxnNi@kk9@2jjiFWNeo1i65MxXlK22bj27TysGetH3yuLd/m07LeneGyqAK835LIgicgXn21DuBVBrw0a2P/PPdNDU1vp672PrmgYXAEN9bPaE0EnHAjD6V@X9oai@9hfBIyVmOBLD/6HaNHwp2hikzI5/oG3l6JGprBQxWdl/TbemsqtVeMMtakw1YmsbFyd8DNESSdyI6OfkfVZcFceYOAdoLOXUJ0xQ@ilx2ETAyDFNwOKWmj0v4pzV5RJrPZ5zj@Aw "PHP ‚Äì TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), 245 bytes ``` puts"%b"%"28x0lphxjx8ze4uuhtdzo0oebr25amtmuxm62cbit0ibdwjm2sf50clh2ejq0a73ndseo5tove8uqca6nf66bo4abbkg867woh2b435at0o3pddvqmsqp29b6as5bd4eo28xgwkkj607gp66icba1q4n9fc13dltp45j340mpzbc56wsrbb3oejnczsbzfgh82xdi8aku8m4wlmwuxkgy4yaew7pu4p1g".to_i(36) ``` Output 0 for + and 1 for -. [Try it online!](https://tio.run/nexus/ruby#Dc5bboQgFADQvZhM0v40yOPKrKbhAqIoggMMjJu3PSs4d6olDw8cHgOVnexp6b7Ly/Jal2KuSKLFFxUqlFB7AKpxLWRF03ygeRZE7wu1/iRqYofJNooS31bWUys4ZgCMXCFuTsLU4kKRM6EKiSwZ8z5DPhN9Iqgs0HAb/wOubZsHMrkEsGpU48mP56xHZvaSuPCMk5Au1AJafiGyaP2hr4zX7BZJu1ml2qoMvO2h1b65D/8o26ZUeRrd8FPi7/rF4Pu@/wA "Ruby ‚Äì TIO Nexus") [Answer] ## Perl, 164 bytes ``` print unpack'b*','-Y¬≤l√笢%O [¬≥b√ô¬≤D√ãlY¬Æp√⬱%¬ß√í-Y¬∂deJ-Ki¬•%¬´√ï(O¬¨e√â√≤DO¬∂,Y¬∂,√ô√ÇeF[2/√âc√ãlI¬∑d√öl9c√Éi√â¬≤53√ú;√£P√õ g√ô,[¬¶TT√´t:l√ÜEK¬≥,]¬¶N√ôFk√ìe√笢√•P¬≥lK√≤¬µNSj√ú' ``` Hexdump: ``` 00000000: 7072 696e 7420 756e 7061 636b 2762 2a27 print unpack'b*' 00000010: 2c27 962d 59b2 6ccd a225 4f96 0d5b b362 ,'.-Y.l..%O..[.b 00000020: d9b2 44cb 966c 59ae 70c9 b125 a7d2 2d59 ..D..lY.p..%..-Y 00000030: b664 8e8b 654a 972d 4b96 69a5 9625 abd5 .d..eJ.-K.i..%.. 00000040: 284f ac65 c9f2 444f b62c 59b6 2cd9 c265 (O.e..DO.,Y.,..e 00000050: 8e96 465b 322f c993 63cb 946c 49b7 64da ..F[2/..c..lI.d. 00000060: 926c 3996 8d63 c369 c9b2 3533 dc0c 3be3 .l9..c.i..53..;. 00000070: 50db 0a67 d992 2c5b a654 8f9a 54eb 9474 P..g..,[.T..T..t 00000080: 3a96 6cc6 9a45 4bb3 2c5d a64e d992 466b :.l..EK.,].N..Fk 00000090: 960b d39a 65cd a2e5 50b3 6c4b f218 b54e ....e...P.lK...N 000000a0: 536a dc27 Sj.' ``` The obvious, boring solution: just put all the bits in a binary string, 8 bits per byte. Uses 0 for - and 1 for +. I‚Äôll try to golf this some more. [Answer] # [Retina](https://github.com/m-ender/retina), 333 bytes ``` ADG-RMCGHQFDLEM+-FAG-CADGPAKBBLHBCH-EGHJBORGEH-HB-FJOBPRCA+JAG-A+A+NJHQLIB-R+Q-OQPRAGP-HBEH-CGNCDGEH+BCCHQH-PDJCEGOGECDGCPK-FNH-EDLHCRIEELHDELEKE-HLJDDA+LHFGCFADJJBK+-JDCJBI+JCOOLGEDELMCGNAGKBEJKJEGCNCIF+BLECMMCAKLJDFDGCH+-E-JIQDJJNHD¬∂ R GF Q +C P EA O CK N D- M I-A L -- K D+ J CB I A++ H E+ G AB F -AD E C+ D B+ C -B B -+ A -++-+- ``` [Try it online!](https://tio.run/##DY67cSBBCET9ToUiCGAYWGb2m4EMGXLOuFJsCkCJrcbB6Hr9mv@f31//Pt4X0oKf3SLv3qbvxF2CbaWXDNWZaskeWXo@4cmp3OvU6zGhWqSQ0FF5z035oZvP@3okrsUt2OKwtlqkZnknX63M4wxfqV2D@7HcbaY9m/vM5tOHc85qTWhmD@vSqnQQV7PSjcrOc4Yvcr18SAz1GuVhh22ddLrtu8lYhr4mkti5tns5jmy/P3gQHTfIcMEFJ2zgQGPs2FgwwYyBRiiYYoMQIeGEgCg6WBocRmhQgoEVCibIOsTE7/sH "Retina ‚Äì Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 416 bytes ``` f(i){for(i=1160;i--;)putchar(L"\x72ca563b\xd24f18ad\xa70acd36\x59a6b345\xd669d0cb\x729b4962\xcd34ba65\x6359a2d2\x2e5c6936\x592ad729\xda652af1\xe69b4934\xc70adb50\xcc3b30dc\x96934dac\x69b1c6c3\x5b49369c\x3692ed26\xc9c6d329\xda4cf493\xa6716962\x6d349b43\xf26d349a\xa6934f22\xab14f235\xa569a4d5\xb4d26996\xd1a652e9\x9a6d2671\xa4e54bb4\x750e938d\xd369369a\x469b4d22\x69b0dacd\xb345a4f2\xb49a4d36i"[i/32]>>i%32&1?43:45);} ``` [Try it online!](https://tio.run/##JVHLTgMxDPyXSqDtoSKJHW9DRfkB/oDl4DgbyIGHKpAiIb69TNrLatYzHo8d272anc91atvf@nma2oP34g5ttztsv36@7U1P09Nm6XMwjUJ56SVw9XstS9fZqRWSpcekkokjWJFUnOXRkTInCUuHhrMKWCEoQ0EtrNEkXXuDFojRC03Q6pe@yuglRi9mlBwdkFEmV2zpCY1cFAgyb2IEl6GXhBq@YS0BzpZMCl2d2SoEyCyzl0sqUIwpqNVwwTpYONcAVrMHIGTG2km5AGWGbUpwLn5EXeGMxVGckVl5jZwzMs/RrYn2uBCOM1LBmcdGZTgDOIQHOy6mmDKcxwiStnludxRejsd2Q@HWPzLdc9we/s7v2j4mPNE0fv4B "C (gcc) ‚Äì Try It Online") [Answer] # Deadfish~, 2609 bytes ``` {iiii}iiiiicddcciicddciiccddcciicddcciicddciiccddciiccddcciicddciiccddciiccddcciicddciiccddcciicddcciicddciicddcciiccddcciicddciicccddciicddcciicddciiccddciiccddcccciiccddciiccddcciicddciiccddcciicddcciiccccddcciicddcciicddciicddcciiccddcciicddciicddciicccddcciicddciiccddcciicddcciicddciiccddcciicddciiccddciicccddciicddcciicddciiccddcciicddcciicddciiccddciiccddcciicddcciicddciiccddcciicddciiccddccciicddciicddciiccccddccciicddciiccddciiccddccciicccddcciicddcciicddciiccddciiccddccciiccddciicddciicddciiccddciicddccciicddcciicddciiccddciiccddcciicddciiccddcciicddcciicddciiccddciiccddcciiccddccciicccddccciicddciicccddcciicddciiccddcciiccddciicddciiccddciicddccciicddciiccddcciicddcciicddciiccddcciicddciiccddciiccddcciicddciiccddcciiccddciicddcciicddciicddciiccddciicddciicddcciicddciiccddcciicddciiccddciiccddcciicddciicddciicddcciicddciicddciicddcciicccddciicddciiccddcccciiccddciicccddcciicddciicddcciicddciiccddcciicddciiccddciiccddcciicddciiccddcccciiccddciicccddciicddcccciiccddciiccddcciicddcciicddciiccddcciicddciiccddciiccddcciicddciiccddcciicddcciicddciiccddcciicddciiccddciiccddcciicddcciicddciiccccddccciicddciiccddcciiccddccciicccddciicddcciicddciiccddciicddcciicccddciicddcciicddcciicddciiccddciiccddcciiccddcccciicddciiccddciiccddciiccddcccciiccddciiccddccciicccddcciicddcciicddciiccddcciiccddciicddciiccddciiccddcciicddcciicddciiccddciiccddciicddccciicddcciicddciiccddciiccddcciiccddciicddcciicddcciicddciiccddciiccddciiccddcciicddcciicddciiccddccciicccddcciicddciiccddcciicddcciicccddccciicccddcciicddcciiccccddccciiccddciicddcciicddciiccddciiccddcciicddciiccddcciicddcciicddciicddcciiccddcciiccddcciiccccddccciicddcciiccddcciiccccddcciicddccciiccddcciicccddccciiccccddciicddciicddcciicddcciicddcciicddciicddciiccccddccciiccddcciicddciiccddcciicddcciicddciiccddciiccddciiccddcciicddciiccddcciicddcciicddciiccddcciiccddciicddciiccddciicddciicddciicddcccciicccddciicddciicddcciiccddciiccddciicddciicddciicddcciicddciicddccciiccddciicddciiccddciiccddciicddccciiccddciicddccciicccddcciicddciiccddciiccddcciicddcciiccddcciicccddcciicddciicddcciiccddcciicddciicccddciicddcciicddciiccddciicddcciiccddcciicddciiccddcciicddciiccddciicddccciicddciiccddcciiccddciicddciicddccciiccddciicddciiccddcciicddcciicddciiccddciiccddciicddcciicccddciicddcciicddciicddcciiccddcciicddciiccddccciicddciiccccddcciiccddciicddcciicddciicddcciiccddcciicddciiccddcciicddciicddcciiccddcciicddciicccddciicddcciicddciiccddccciiccccddciicddciicddcciiccddcciicddciiccddcciicddcciicddcciicddciiccddciiccddciiccddcccciicccddcciicccddciicddciicddcciicddciicddccciiccddciicddcciiccddciicddciiccddciicddciicddcciicccddccciicddcc ``` [Try it online!](https://deadfish.surge.sh/#WMXu+2S0x/z/609a8tPWnrXlry09a8teWnrXlp609a9aeWnrXi1609a8teWh5a8tPWvLT1p4WnrT1r1p5aeteteLT1ry09aeteWnrXlrxa9aeteWnrT1ry15aetPWvLT1ry0eteteFo9a8teWjxaetPWvLXlo8teteteWvWj1p615a8tPWvLT1p615a8tPLR4tHrXi09a8tPLXrXlr1o9a8tPWnrXlp615a8tPWvLTy1609a9a8tetetPWvLT1ry15aetetetPWvWvWni1615aHlrxaetetPWvLT1ry15aeteWh5a8WvWh5a8tPWnrXlp615a8tPWvLT1p615aeteWvLT1p614Wj1ry08tHi1609a8tetPFr1p609a8teWnloeteWvLXloeWvLR4tPWnrXlp5a9a8teWnrT1ry15a9aPWnrXlry08tetPWnrXlry15aetPWvLR4tPWvLT1p4tHi09aeFo8tetPWvLXlp615aetPWvWnlp5aeFo9aeWnhaetHlp4tHha9a9aetPWnrXrXhaPLT1ry09aeteWvLXlp615aetPWvLTy1615a9a9a9aHi161608teWvWvWvWnrXrR5a9a8teWvWjy160eLT1ry15aetPLTxaetetPLT1rxa9aeteWvWnlp615aeteWvWj1ry08tetetHlr1ry09aeteWvLXrTxa9aetetPLT1ry0eteFp5a9aetetPLT1ry09a9aeWnrXi1609a8tHha9a9aeWnrXlp609aeteWvLXloeLTxa9a9aetetHlr1p5a9a8tetetPFo9aA==) Do I care that there's a sensible way to do this? No. ]
[Question] [ Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s). --- **The Challenge** We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, `n`. **Input** - A positive integer, `n` (up to `2**32-1` should be handled) **Output** - An ASCII representation of the stack arrangement as defined below. This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line; This may contain a single trailing new line; and The characters representing chips may be in lowercase if you prefer. The stack arrangement will: * Contain the fewest chips possible, given the denominations (see below); * Will have equal valued chips in "stacks" (columns); * Be ordered such that the shorter stacks are to the right of taller stacks; and * Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right) The chips themselves are to be represented as individual characters identifying their colour: ``` White : 1 = W Red : 5 = R Green : 25 = G Black : 100 = B Yellow : 500 = Y Pink : 1K = P Orange : 5K = O Cyan : 25K = C Magenta : 100K = M Aqua-blue : 500K = A Lavender : 1M = L Indigo : 5M = I Turquoise : 25M = T Violet : 100M = V Silver : 500M = S ``` --- **Example** For `n = 276,352` the smallest number of chips would be: ``` 2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1 MM CCC P BBB GG WW ``` The single `P` must go on the far right, then the three stacks of size `2` must go next, - but the `MM` must go furthest to the right followed by the `GG` and then the `WW` since `100K > 25 > 1` then the two stacks of size `3` go on the left, - but the `CCC` must go to the right of the `BBB` since `25K > 100` Now we must place these chips into actual stacks, to make our output: ``` BC BCWGM BCWGMP ``` --- **Test Cases** ``` Input: 1 Output: W Input: 9378278 Output: L LWGPCM LWGPCMB LWGPCMBI Input: 22222222 Output: ROI ROI ROIWBPML ROIWBPML Input: 1342185143 Output: WRCIV WRCIVOLS WRCIVOLSGBMT Input: 2147483647 Output: RMIS RMISPC RMISPCWL RMISPCWLGBYOTV Input: 4294967295 Output: S S S S SRML SRMLGOIT SRMLGOITBPCV SRMLGOITBPCVA ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. No loopholes, yada yada, you know the drill. [Answer] # JavaScript (ES6), ~~185~~ ~~177~~ ... 171 bytes ``` f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+` `+s) ``` ### Formatted and commented ``` (a, s = '') => ( // a = bankroll OR array of chip stacks a = ( // s = string of chip initials for this iteration a[0] ? // if 'a' already is an array: a // use it as-is : // else, 'a' is the bankroll: [...(m = '25455') + m + m] // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3) .map((m, i) => // v = current chip value = previous value / m ( // k = floor(a / v) = number of these chips a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v k * 16 + i // saved in array: chip index in bits 0-3 ), // and number of chips in bits 4+ v = 1E9 // initial chip value = 1 billion ) // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.) .sort((a, b) => b - a) // sort the chip stacks ) // .map(n => // for each chip stack: n > 15 && // if there's at least one remaining chip of ( // this kind: s += 'SVTILAMCOPYBGRW'[n & 15], // append its initial to the string n - 16 // decrement the number of chips in this stack ) // ), // process recursive call if there was at least s && f(a) + '\n' + s // one non-empty chip stack (the next lines are ) // appended at the beginning of the final string) ``` ### Demo ``` let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+` `+s) function update() { document.getElementById('o').innerHTML = f(+document.getElementById('i').value); } update(); ``` ``` <input id="i" value="1342185143" oninput="update()"><pre id="o"></pre> ``` [Answer] # Pyth, ~~56~~ ~~55~~ 52 bytes The code contains some unprintables, so here's a reversible `xxd` hexdump. ``` 00000000: 3d48 516a 5f2e 745f 2023 6c44 2a56 2e22 =HQj_.t_ #lD*V." 00000010: 4159 261c 0c24 2087 0c86 1e22 6d68 412e AY&..$ ...."mhA. 00000020: 4448 645f 2e75 2a4e 5950 2a33 6a37 3733 DHd_.u*NYP*3j773 00000030: 3620 362f 6 6/ ``` [Try it online.](http://pyth.herokuapp.com/?code=%3DHQj_.t_%20%23lD*V.%22AY%26%1C%0C%24%20%C2%87%0C%C2%86%1E%22mhA.DHd_.u*NYP*3j7736%206%2F&input=276352&test_suite_input=1%0A276352%0A9378278%0A22222222%0A1342185143%0A2147483647%0A4294967295&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%3DHQj_.t_%20%23lD*V.%22AY%26%1C%0C%24%20%C2%87%0C%C2%86%1E%22mhA.DHd_.u*NYP*3j7736%206%2F&input=276352&test_suite=1&test_suite_input=1%0A276352%0A9378278%0A22222222%0A1342185143%0A2147483647%0A4294967295&debug=0) Pro tip: to golf `1` in the end of a program accepting a nonzero number in `Q`, just add `/`. `/QQ`, which in Python would be `Q // Q`, is 1 for nonzero `Q`. Without compression and unprintables (55 bytes): ``` =HQj_.t_ #lD*V"SVTILAMCOPYBGRW"mhA.DHd_.u*NYP*3j7736 6/ ``` [Answer] # Ruby, ~~181~~ 177 bytes ``` ->n{*a=5*10**8 14.times{|i|a<<a[-1]/[5,4,5,5,2][i%5]} a=a.zip("SVTILAMCOPYBGRW".chars).map{|v,c|[-(n/v),v,c,n%=v]}.sort l=-a[0][0] (1..l).map{|i|a.map{|d|l-i<-d[0]?d[2]:""}*""}} ``` [Tests on Ideone](http://ideone.com/Epfmmb). [Answer] ## Python 2.7, ~~282~~ ~~248~~ 238 bytes ``` c=input();L=[] for i in range(15):m=[5,1,25,5,1][i%5]*10**int("886665533322000"[i]);L+=[[c/m,i,"SVTILAMCOPYBGRW"[i]]];c%=m L.sort();S=[] while L[~1][0]: s="" for X in L[::-1]: if X[0]>0:X[0]-=1;s+=X[2] S+=[s] for s in S[::-1]:print s ``` **Explanation:** Fill list `L` with elements `[quanity, chip_order, chip_character]` indicating the quantity of each type of chip , where `chip_order` ensures chips of equal quantity get sorted in reverse order (higher value chips *first*). Take chips from `L` in reverse to build strings for each line. Print lines in reverse to get smallest lines on top. *Thanks to [Blue](https://codegolf.stackexchange.com/users/42855/blue) for some of the improvements.* [Answer] ## Mathematica, 440 bytes ``` n=Input[] c=Characters["SVTILAMCOPYBGRW"] l=Reap[Do[n=n-#[[-i]]*Sow[Floor[n/#[[-i]]]]&@FoldList[Times,1,{5,5,4,5,2,5,5,4,5,2,5,5,4,5}],{i,1,15}]][[2,1]] StringJoin@@((StringJoin[#,"\n"])&/@StringJoin/@Reverse/@((PadRight[#,Max[l],""]&/@Sort[Table[If[l[[n]]>0,Table[c[[n]],l[[n]]],Nothing],{n,1,15}],If[Length[#1]==Length[#2],Position[c,#1[[1]]][[1,1]]<Position[c,#2[[1]]][[1,1]],Length[#1]<Length[#2]]&])[[All,#]]&/@Range[Max[l]])//Reverse) ``` The ASCI-representation and right order swallows most of the code. **\*Only works with Version11 *and higher* (use of Nothing)\*** [Answer] # PHP, 274 Bytes ``` $t=$argv[1];$n=[500,100,25,5,1];$c=YBGRWAMCOPSVTIL;foreach($n as$k=>$v)for($i=0;$i<3;)$r[$v*10**($i*3)]=$c[$k+$i++*5];krsort($r);foreach($r as$v=>$k)$t-=($x[$v]=floor($t/$v))*$v;ksort($x);arsort($x);for($y=max($x);$y;$y--){foreach($x as$k=>$v)if($v>=$y)echo$r[$k];echo"\n";} ``` ]
[Question] [ # Introduction **tl;dr** Continuously output the current distance from the Earth to the Sun. --- Simplified, the orbit of the Earth around the Sun is an ellipse. So the actual distance between both is constantly changing. This distance can be calculated for any given day using [this formula](https://physics.stackexchange.com/q/177949/104540): [![d/AU=1-0.01672 cos(0.9856(day-4))](https://i.stack.imgur.com/ImmYv.png)](https://i.stack.imgur.com/ImmYv.png) The equation can be split into the following parts2: * `1` represents *1 AU* (astronomical unit), equals `149,597,870.691 km` * `0.01672` is the [orbital eccentricity](https://en.wikipedia.org/wiki/Orbital_eccentricity) between the Earth and the Sun * `cos` is of course the cosine function, **but with argument in degrees rather than radians** * `0.9856` is *360° / 365.256363 days*, a full rotation in one year, where `365.256363` is the length of a sidereal year, in mean solar days * `day` is the day of the year `[1-365]` * `4` represents the offset to the [perihelion](https://en.wikipedia.org/wiki/Perihelion_and_aphelion), which is between 4th and 6th of January The formula takes a whole day but for the purpose of this challenge – a continuously output – you have to be more accurate; or nothing much will happen till the next day. Simply add the percentage of the past time to the current day, like1: ``` day + (h * 3600 + m * 60 + s) / 864 / 100 ``` A few Examples: * 1 January, 23:59:59 `1.99998842592593` * 1 January, 18:00:00 `1.75` * 1 January, 12:00:00 `1.50` * 1 January, 06:00:00 `1.25` # Input This challenge has no input. --- If your language can't get the current time, you can get it as an input to your program. Valid inputs are *timestamps* or complete *date-time strings* that suits the language best. Passing the current day alone (like `5` for 5th January or `5.25` for the same day at 6 o'clock) is not allowed. # Output Output the current distance from the Earth to the Sun: * Output the value in `km`. * Update the value *at least every second*. Example output: ``` 152098342 ``` If it doesn't increase your byte count, you can also pretty print the result: ``` 152,098,342 152,098,342 km ``` # Requirements * You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins. * Standard loopholes are disallowed. # Example implementation I've prepared an example implementation in JavaScript. It's neither competitive nor golfed. ``` // dayOfYear from http://stackoverflow.com/a/8620357/1456376 Date.prototype.dayOfYear = function() { var j1= new Date(this); j1.setMonth(0, 0); return Math.round((this-j1)/8.64e7); } // vars var e = document.getElementById('view'), au = 149597870.691, deg2rad = Math.PI/180, date = now = value = null; // actual logic function calculate() { date = new Date(); now = date.dayOfYear() + (date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()) / 864 / 100; value = 1 - 0.01672 * Math.cos(deg2rad * 0.9856 * (now - 4)); // supported in Firefox and Chrome, unfortunately not in Safari e.innerHTML = Math.round(value * au).toLocaleString('en-US') + ' km'; setTimeout(calculate, 1000); } // let's do this calculate(); ``` ``` <div id="view"></div> ``` --- 1 To not unreasonably increase complexity, you don't have to convert your local time to UTC. If you use UTC please add a note to your answer. 2 For more details see "[Earth-Sun distance on a given day of the year](https://physics.stackexchange.com/a/177952/104540)" over at [Physics](https://physics.stackexchange.com/) [Answer] ## TI-BASIC, 38 bytes ``` Disp 25018086(59.8086-cos(5022635.4⁻¹checkTmr(83761 prgmA ``` For a TI-84+ series calculator. Name this `prgmA`. Note that this overflows the stack after a few thousand iterations; use a `While 1:...:End` instead if this is a problem, for two extra bytes. This uses the perihelion on January 1, 1997, 23:16 UTC for reference, and is accurate to within a few dozen kilometers (about 7 digits of accuracy) for the next few years. [Answer] # Java - 185 180 bytes ``` static void d(){while(true){System.err.println(149597870.691*(1-.01672*Math.cos(Math.toRadians(.9856*(Calendar.getInstance().get(6)+LocalTime.now().toSecondOfDay()/8.64e4-4)))));}} ``` This uses the fact that there are 86,400 seconds in a day and is using local time, not GMT. Output happens much more than once per second. Not sure if import statements should be included in byte count. To include a 1 second delay adds about 26 bytes e.g. ``` static void d(){try{while(true){System.err.println(149597870.691*((1-.01672*Math.cos(Math.toRadians(.9856*(Calendar.getInstance().get(6)+LocalTime.now().toSecondOfDay()/8.64e4-4)))));Thread.sleep(1000L);}}catch(Exception e){}} ``` Java definitely isn't the most golfable language. :) Removed a few bytes thanks to @insertusernamehere [Answer] ## Python, 101 bytes ``` import time,math a=149597870.691 while 1:print(a-a*.01672*math.cos((time.time()-345600)/5022635.53)) ``` 345600 = 4\*24\*3600 (four days) 5022635.53 ≌ (365.256363\*24\*3600)/(2π) (seconds in year/2π) [Answer] # Bash/coreutils/bc, 101 bytes ``` #!/bin/bash bc -l <<<"149597870.691*(1-.01672*c((`date +%s`-`date -d 4-Jan +%s`)/5022635.5296))" sleep .5 exec $0 ``` This computes the offset from the 4th of January in seconds, so uses a corresponding constant to convert to radians. Half a year converts to roughly pi: ``` $ bc -l <<<"(365.256363/2*86400)/5022635.5296" 3.14159265361957033371 ``` The rest of the calculation is straight from the question. [Answer] # Mathematica, 97 bytes ``` Dynamic[1496*^5-2501*^3Cos[.9856#&@@Now~DateDifference~{DateValue@"Year",1,4}],UpdateInterval->1] ``` **Explanation** `{DateValue@"Year",1,5}` represents 5th of January this year, and `...~DateDifference~...` gives the temporal distance. `Dynamic[...,UpdateInterval->1]` update the expression once per second. [Answer] ## F#, 178 bytes ``` open System Seq.initInfinite(fun _-> let n=DateTime.Now (1.-0.01672*Math.Cos(0.0172*((n-DateTime.Today).TotalDays+float(n.DayOfYear-4))))*149597870.691)|>Seq.iter(printfn"%f") ``` This is an F# script that runs well in F# Interactive. For simplicity's sake, the "continuous output" requirement is taken to literal levels, although I did lose a byte to make the output print on a new line every iteration so that it wasn't *too* bad. =P Ungolfed and explained: ``` Seq.initInfinite (fun _ -> // Create an infinite sequence, with each element being defined by the following function let n = DateTime.Now let dayOffset = n.DayOfYear - 4 // Day of year returns the day as a number between 1 and 366 let today = n - DateTime.Today // Extract the current day, so the hours, minutes and all let partialDay = today.TotalDays // Get the value of 'today' as a floating point number of days // so between 0 and 1 in this case - exactly what I needed // And now, the formula - note that 0.9856 has been combined with the conversion from degrees to radians, giving 0.0172 (1. - 0.01672 * Math.Cos (0.0172 * (partialDay + float dayOffset))) * 149597870.691 ) |> Seq.iter (fun i -> printfn "%f" i) // For each of the (infinity of) numbers, print it ``` [Answer] ## Pyth, 51 bytes ``` #*149597870.691-1*.01672.t*c-.dZ86400 31558149*2.nZ1 ``` ### Alternate formula d/AU = 1 - 0.01672 cos ( 2π [time since perihelion]/[orbital period] ) This formula is essentially the same as the OP's formula, except it is generalized to be able to use any perihelion as a reference date. The OP's formula has [time since perihelion] as ( day - 4 ) and has ( 2π rad / [orbital period] ) pre-calculated as 0.9856deg/day. In my solution I am using the perihelion closest to the Unix epoch, 2nd January 1970. ### The code Hand-compiled to pythonic pseudocode: ``` # while 1: *149597870.691 print( 149597870.691 * ( # implicit print -1 1 - ( *.01672 0.1672 * ( .t trigo( * multiply( c divide( -.dZ86400 unixTime-86400, 31558149 31558149 ), *2.nZ 2*pi ), 1 1 # 1 means cos ))))) ``` This is essentially just turning the following formula into code: d = ( 1 - 0.01672 cos ( 2π (t - 86400)/31558149 ) ) \* 149597870.691 where t is the Unix time. [Answer] # Python 2.4 - 158 bytes ``` import time,math while 1:t=time.localtime();print(int(149597870.691*(1-.01672*math.cos(math.radians(.9856*(t[7]+(t[3]*3600+t[4]*60+t[5])/864.0/100.0-4)))))) ``` Takes the local time and spits out the distance. time.localtime() returns a tuple and can be referenced [here](https://docs.python.org/2/library/time.html?highlight=time#time.struct_time). [Answer] ## C, 338 ``` #include <stdio.h> #include <time.h> #include <math.h> int main () { time_t rt; struct tm * ti; while(1) { time(&rt); ti = localtime(&rt); double d = 1.0 - .01672*cos(0.0174533 * .9856*((ti->tm_yday + (ti->tm_hour * 3600.0 + ti->tm_mday * 60.0 + ti->tm_sec) / 86400.0) - 4)); printf ("%f\n", d * 149598000.0);} } ``` [Answer] ## HP‑41C series, 78 Bytes This program requires an HP‑41CX or an HP‑41C/CV with a time module plugged in. It works only correctly from October 15, 1582 through September 10, 4320. Ensure the display format allows for displaying 9 digits (e. g. `FIX 4`, the default setting). You may set flag 29 to enable the insertion of a thousands separator for every group of three digits in the integer part. Set flag 28 to use commas as thousands separators (as opposed to periods). Flag 28 and 29 set are the default setting. ``` 01♦LBL⸆S 5 Bytes global label requires 4 + (length of string) Bytes 02 DEG 1 Byte ensure Degree mode is selected ─── get day number (zero-based) ──────────────────────────────────────────────── 03 DATE 2 Byte today’s date: has MM.DDYYYY or DD.MMYYYY format 04 ENTER↑ 1 Byte replicate value 05 ENTER↑ 1 Byte again because `ENTER↑` disables stack lift NULL 1 Byte invisible Null byte before numbers 06 1 E6 3 Bytes put 1,000,000 on top of stack 07 * 1 Byte multiply so X = MMDDYYYY or DDMMYYYY NULL 1 Byte 08 1 E4 3 Bytes put 1,000 on top of stack 09 MOD 1 Byte isolate YYYY NULL 1 Byte 10 1 E6 3 Bytes 11 / 1 Byte divide YYYY by 1,000,000 NULL 1 Byte 12 1.01 4 Bytes 13 + 1 Byte X = January 1, current year 14 X≷Y 1 Byte swap X and Y so difference is positive 15 DDAYS 2 Bytes difference of days – accounts for leap year ─── get fractional time of day ───────────────────────────────────────────────── 16 TIME 2 Bytes obtain time in HH.MMSSss format 17 HR 1 Byte convert HH.MMSSss into decimal hours format NULL 1 Byte 18 24 2 Bytes 24 hours 19 / 1 Byte ─── compose `day` as in specification ────────────────────────────────────────── 20 + 1 Byte combine day number and time NULL 1 Byte 21 3 1 Byte perihelion bias for zero-based day numbering 22 − 1 Byte ─── perform calculation ──────────────────────────────────────────────────────── NULL 1 Byte 23 .9856 5 Bytes use .985609113 for improved precision 24 * 1 Byte 25 COS 1 Byte NULL 1 Byte 26 −.01672 7 Bytes 27 * 1 Byte NULL 1 Byte 28 149,597,870.7 11 Bytes 29 + 1 Byte 30 PSE 1 Byte delay execution for about one second 31 GTO⸆S 3 Bytes `PSE` displays contents of X-register ``` NB: The actual calculator (in hardware) is too slow to perform all operations within one second. It needs roughly 3 seconds + 1 second for `PSE`. However, this is a circumstance *outside* the realm of the programming language. ]
[Question] [ In this task you will take as input a non-negative integer \$n\$, and output the number of pairs of non-negative integers \$a,b\$ such that both are palindromes\*, \$a \leq b\$, and \$a+b = n\$. For example if \$n\$ is \$22\$ then the valid pairs are \$ \begin{array}{c|c} a & b \\ \hline 0 & 22 \\ 11 & 11 \\ \end{array} \$ So the output is \$2\$. As another example, if \$n\$ is \$145\$ then the valid pairs are \$ \begin{array}{c|c} a & b \\ \hline 4 & 141 \\ 44 & 101 \\ \end{array} \$ So the output is 2. Your submission should be a program or function. Answers will be scored in bytes with fewer bytes being the goal. ## Test Cases \$ \begin{array}{c|c c|c} \mathrm{Input} & \mathrm{Output} & \mathrm{Input} & \mathrm{Output} \\ \hline 0 & 1 & 12 & 5\\ 1 & 1 & 13 & 4\\ 2 & 2 & 14 & 4\\ 3 & 2 & 15 & 3\\ 4 & 3 & 16 & 3\\ 5 & 3 & 17 & 2\\ 6 & 4 & 18 & 2\\ 7 & 4 & 19 & 1\\ 8 & 5 & 20 & 1\\ 9 & 5 & 21 & 0\\ 10 & 5 & 22 & 2\\ 11 & 5 & 23 & 1\\ \end{array} \$ [OEIS A260254](http://oeis.org/A260254) --- \* In base 10 [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŻŒḂ€ḋṚ$HĊ ``` A monadic Link accepting a non-negative integer which yields a non-negative integer. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//xbvFkuG4guKCrOG4i@G5miRIxIr///8xMg "Jelly – Try It Online")** ### How? Counts all pairs without the \$a\leq b\$ restriction, halves and rounds up. Note that the halved count is only a fraction if \$\frac n 2\$ is a palindrome and in such cases we want to count this \$a=b\$ pair. ``` ŻŒḂ€ḋṚ$HĊ - Link: integer, n e.g. 22 Ż - zero-range [0,1,2,...,9,10,11,12,...,21,22] € - for each: ŒḂ - is palindrome (digits) [1,1,1,...,1,0,1,0,...0,1] $ - last two links as a monad: Ṛ - reverse [1,0,...,0,1,0,1,...,1,1,1] ḋ - dot-product 3 (=1×1+1×0+...+1×0+1×1+0×1+...+0×1+1×1) H - halve 1.5 Ċ - ceil 2 ``` [Answer] # JavaScript (ES6), ~~ 74 ~~ 73 bytes ``` n=>(g=a=>a>n-a?0:![a,n-a].some(n=>[...n+''].reverse().join``-n)+g(-~a))`` ``` [Try it online!](https://tio.run/##DcnBCsIwDADQ@74inpbQNQy9qZ0fMgYtsxsbmkgru4j@et3twVvDFvKYltfbit5jmVwR1@HsgutCJzbc2vOhD82ugbM@I@7dM7OYuh44xS2mHJF41UW8t0JmRvsLRN6XSRMKOGgvIHB1cDztMIbgUwGMKlkfkR86ozQwoRBV3/IH "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~73 70~~ 63 bytes ``` lambda n:sum(`n-v`+`v`==(`v`+`n-v`)[::-1]for v in range(n/2+1)) ``` **[Try it online!](https://tio.run/##RYvNCsIwEITvPsXemlCj/bktpC9ihY1otGC2JaYBKX32mJyc0zcfM8s3vGbuktVjeht3uxtg/KxOEKtINUXSWlCh0uUFUbVXO3uIMDF4w8@H4HNXt1Kmovmv@6aReICcxU8cqg2Hfgc1wLZXp7x1Jgg@ghWcvz8 "Python 2 – Try It Online")** Note that: ``` (string_a == reverse(string_a)) and (string_b == reverse(string_b)) ``` is equivalent to ``` reverse(string_a + string_b) == (string_b + string_a) ``` (where `+` is concatenation) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 99 bytes ``` N-C:-aggregate_all(count,(between(0,N,A),B is N-A,B=<A,+A,+B),C). +N:-atom_codes(N,C),reverse(C,C). ``` [Try it online!](https://tio.run/##Pc5LCoMwEAbgvadwGXFGTHyXdqHucwWxdgiCNUVtPb5NsQnM4mNe/K9FT1rhuo/HIbG9YK/UQqrfqOuniQ36PW/A7rTtRDOLQUIdQOOPqy@xhuZ2rSE01QTQBpEXSvNg089u0A9amTRNWOhDy0qs/W0ch@@zGHkAngG3SFCcSDE5kVnkmJ4oLErMTlQWPHbiTsIpsZc8dXL/ee5U2BS8dKpsROFSC47xX8LuicRMoy8 "Prolog (SWI) – Try It Online") # Ungolfed Code After adding white space, this solution reads very similarly to the challenge specification. It simply asks for the number of pairs palindrome integers within specified bounds that sum to N. ``` count_splits(N,C) :- aggregate_all(count,( between(0,N,A), B is N-A, B=<A, palindrome(A), palindrome(B) ),C). palindrome(N) :- atom_codes(N,C), reverse(C,C). ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝεÂQ}Â*O;î ``` Port of [@*JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/198823/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f//8NxzWw83BdYebtLytz687v9/QxNTAA) or [verify all test cases](https://tio.run/##ASkA1v9vc2FiaWX/MjPGkk4/IiDihpIgIj9O/8OdzrXDglF9w4IqTzvDrv8s/w). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input-integer] ε # Map each value to:  # Bifurcate the value; short for Duplicate & Reverse copy Q # And check if it's equal to the value itself (1 if a palindrome; 0 if not) } # After the map: bifurcate the entire list as well * # Multiply the values at the same indices in the lists O # Take the sum of that ;î # And then halve and ceil it # (after which the result is output implicitly) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` {+grep {.flip eq[R,] $_},(^$_ Z($_...$_/2))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wju9KLVAoVovLSezQCG1MDpIJ1ZBJb5WRyNOJV4hSkMlXk9PTyVe30hTs/Z/cWKlQm5iAVCnjoKhnp6R8X8A "Perl 6 – Try It Online") Finds the number of pairs of numbers such that the reverse of the string representation is equal to the string representation of the reversed pair. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ILΦ⊕⊘θ⬤I⟦ι⁻θι⟧⁼λ⮌λ ``` [Try it online!](https://tio.run/##JYqxCgIxDEB/pWMKdRB0chJRFBSOW8Wh1OAFYqRprr8fD@4tb3ivTFnLL7P7oCQGp9wM7igfm@BCbKhwk6L4RTF8wzVzX1RjTOHIvO5PSuFBMjeoKVB8Le1c58wNOIURO2pD4LhycN/u9r7p/Ac "Charcoal – Try It Online") Link is to verbose version of code. The halved input has to be incremented because `a` needs to vary over the inclusive range from `0` to `n/2`. Explanation: ``` θ Input `n` ⊘ Halved ⊕ Incremented Φ Filter over implicit range ⟦ Begin list ι Current index `a` θ Input `n` ι Current index `a` ⁻ Subtracted (i.e. `b`) ⟧ End list I Vectorised cast to string ⬤ Both strings satisfy λ Current string ⮌ Reversed λ Current string ⁼ Are equal L Length I Cast to string for implicit print ``` [Answer] # Python 3.8, ~~89~~ ~~87~~ ~~68~~ 66 bytes Adapting [Jonathan's clever answer](https://codegolf.stackexchange.com/a/198824/75323) to Python 3 (with f format strings) and removing `[]` for a generator expression instead of list comprehension, we shave 21 bytes with ``` lambda n:sum(f"{i}{n-i}"==f"{n-i}{i}"[::-1]for i in range(n//2+1)) ``` [Try it online](https://tio.run/##RczBCgIhGATge0/x40kJWayIEOxF2g5GWT@0s2LbYRGf3fTUnGa@w8R1ec3Yn2KqgdxY33663T3Bfr6TDCJzydBchHNt9NZEXKzV5kphTsTEoOTxfEgMw25rlKrd8XdzOCq7oZaYGEt/RSF9phwkVBGq/gA) My old answer: ``` lambda n:len([i for i in range(n//2+1)if(s:=str(i))==s[::-1]and(t:=str(n-i))==t[::-1]]) ``` You can [try it online](https://tio.run/##JclNCsIwEAbQq8xyBikl/oAEcpLaRaSNDtSvYTIbTx/Bbt@rX3/vuNyr9ULp0bf8eS6ZELcVPCmV3UhJQZbxWhnjeD4F0cItpubGKpJSm2IcwpyxsB@M4R9@xCy9msK5cLjeRPoP) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~70 69~~ 67 bytes -2 thanks to Arnauld (change each string cast from `x+''+y` to `x+[y]`) I don't really know much JavaScript, I based this around Arnauld's answer, any advice is very welcome! ``` n=>(g=a=>(v=n-a)<a?0:(v+[a]==[...a+[v]].reverse().join``)+g(-~a))`` ``` **[Try it online!](https://tio.run/##DcbBCsIwDADQ@74ix4S6MvSmi35IKTTMdmyMVDrpRfTX6y6Pt0qVfSrL691rfsaWuCnfcWY5rKy90CiP4YrVOPHMzlorxlXvbYk1lj0i2TUvGgKZGfufEIXQUi6owDDcQGFkOF@OGEPw6QCmrHveot3yjHqChErUfdsf "JavaScript (Node.js) – Try It Online")** Note that: ``` (string_a == reverse(string_a)) and (string_b == reverse(string_b)) ``` is equivalent to ``` reverse(string_a + string_b) == (string_b + string_a) ``` (where `+` is concatenation) [Answer] # [PHP](https://php.net/), ~~83~~ ~~86~~ ~~85~~ 73 bytes ``` for(;$i<=$argn/2;$i++)$k+=strrev($j=$argn-$i)==$j&&strrev($i)==$i;echo$k; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoPA/Lb9Iw1ol08ZWJbEoPU/fCMjW1tZUyda2LS4pKkot01DJgkjpqmRq2tqqZKmpwSTA/Ezr1OSMfJVs6///jQz/5ReUZObnFf/XdQMA "PHP – Try It Online") -13 bytes and bug fix thanks to @640KB [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~114~~ \$\cdots\$ ~~105~~ 98 bytes Saved 7 bytes thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!!! ``` i;m;p(n){for(i=0,m=n;i=i*10+n%10,n/=10;);n=i==m;}r;a;f(n){for(a=r=0;a<=n/2;)r+=p(a)*p(n-a++);n=r;} ``` [Try it online!](https://tio.run/##Nc3BCoMwEIThe54iCELWKEZ7HPdNegm2lhyylcWexGdPtdDrwPfP3L3muZSEjNUJ7ctbXeLQZhYkTs0QvNRDaKXnIYAgnJgzDkXE8geRlQPixNKPIPW8ukjN2eui95dRHCXHJI52Y38Xslk5jUzjDd4LGWtXPdfFVfXjLlV7xQnG6nP7qNgAc5jyBQ "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 63 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.875 bytes ``` ½ʀ2('Ḃ⁼;- ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBbD0iLCIiLCLCvcqAMign4biC4oG8Oy0iLCIiLCIwXG4xXG4yXG4zXG40XG41XG42XG43XG44XG45XG4xMFxuMTFcbjEyXG4xM1xuMTRcbjE1XG4xNlxuMTdcbjE4XG4xOVxuMjBcbjIxXG4yMlxuMjMiXQ==) Bitstring: ``` 000100100000010110000001100101111001000100100001100010110111001 ``` ## Explained ``` ½ʀ2('Ḃ⁼;-­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‏​⁢⁠⁡‌­ ½ʀ # ‎⁡Push the range [0, input / 2] for later 2( # ‎⁢Twice: 'Ḃ⁼; # ‎⁣ Filter the top of the stack by is palindromic - # ‎⁤ And subtract that from the input. - # ‎⁢⁡ This acts as a check for pairs, by keeping numbers that are palindromes before and after subtraction # ‎⁢⁢The l flag outputs the length of the top of the stack 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). Only took me around [3 and a half years to finally write this answer](https://chat.stackexchange.com/transcript/106764?m=54128072#54128072). Things sure have changed since then. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` )rmÑ_x^mÅε*Σ)½ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/1@zKPfwxPiKuNzDree2ap1brHlo7///BlyGXEZcxlwmXKZchgZcRkZcRsZchiamAA) **Explanation:** ``` ) # Increase the (implicit) input-integer by 1 r # Pop and push a list in the range [0, input+1) mÑ # Check for each value whether it's a palindrome (1 if truthy; 0 if falsey) _ # Duplicate this list x # Reverse the copy ^ # Zip the two together to create pairs m # Map over each pair, Å # using the following two commands: ε # Reduce by: * # Multiplying Σ # Then take the sum of this list ) # Increase this sum by 1 ½ # And integer-divide it by 2 # (after which the entire stack joined together is output implicitly) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 51 bytes ``` $\+=($,==reverse$,)&&$_==reverse;++$,<=--$_&&redo}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWQ0XH1rYotSy1qDhVRUdTTU0lHs631tZW0bGx1dVViVdTK0pNya@t/v/f0OBffkFJZn5e8X9dX1M9A0OD/7oFAA "Perl 5 – Try It Online") ]
[Question] [ Given 4 points on the 2D planes `A, B, C, D`, calculate the area of the intersection region of the triangles `OAB` and `OCD`, where `O` is the center of the plane, having coordinate `(0, 0)`. Algorithms that runs in constant time complexity (in terms of arithmetic operations) are encouraged, but not forced. # Rules * Each point is represented as two real numbers, denotes their X and Y coordinate. + Optionally, if your programming language (or some library of your programming language) has built-in `Point` type or equivalent, it is allowed to take `Point` object as input. * The input is given as 4 points, in the formats, including but not limited to: + A list of 8 coordinates. + A list of 4 points, each point can be represented in any convenient format. + Two lists of 2 points. + etc. * You cannot assume particular ordering of the points (counter-clockwise order or clockwise order) * You cannot assume that the point `O` is passed as input. In other word, program must not take and use extraneous input. * You cannot assume all the points are different. In other words, the triangles may be degenerate. You need to also handle that case (see test cases below) * The absolute or relative difference must be less than `10-3` for the sample test cases below. # Winning criteria This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes win! # Sample test cases ``` Ax Ay Bx By Cx Cy Dx Dy area 5 1 1 3 -1 0 0 -1 0 5 1 1 3 -1 0 0 0 0 5 1 1 3 0 0 0 0 0 5 1 1 3 3 4 4 -3 4.50418 5 1 1 3 1 2 2 1 1.5 5 1 1 3 -2 5 4 -2 1.74829 5 1 1 3 -2 5 5 4 2.96154 5 1 1 3 3 5 5 4 1.88462 5 1 1 3 3 5 3 1 3.92308 5 1 1 3 3 5 4 -1 5.26619 5 1 1 3 5 1 4 -1 0 5 1 1 3 5 1 1 3 7 1 3 1 3 5 1 1 3 0 1 3 1 3 1 3 1 3 0 4 8 4 -1 -2 6 -2 -3 0 1.2 3.4 -0.3 4.2 5 7.6 -1.1 2.4 2.6210759326188535 3.1 0.6 0.1 7.2 5.2 0.7 0.9 8 9.018496993987977 ``` If anyone want, here are the outputs for the first test case group in exact form: ``` 0 0 0 46375/10296 3/2 1792/1025 77/26 49/26 51/13 23345/4433 0 7 0 0 0 ``` Illustration image for test case `5 1 1 3 3 4 4 -3` (the area of the green quadrilateral is the expected output): [![Image](https://i.snag.gy/FqhUSz.jpg)] [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` 0&@@Area@BooleanRegion[And,Simplex[{0{,}}~Join~#]&/@#]& ``` [Try it online!](https://tio.run/##jZRdS@QwFIbv91cEFsSVNOYkaZsMCNVLYXFZ926Yi6LtWHBS6cygUupfH8@ZTne0VlpCmrfJOU8@@qardPOQrdJNcZfubvJ8fvvqN@nLbHZXrhbs9Iz921aelXnOntPKF365Zme/flDg32xZlP6q3Pr79WxWZcvFh@7fWbreVtmhP7/YyZMkuayyNLkqy8cs9W3Y/NLf89ti9fSYvcxrWfOmebsuC//2c3FynuBj96cq/CbJk7quQ86g4awGznRDog5QSlKSswCapqEFhwywaOxgEgs1uOLJHDmMoTKGkfw7iJzM0JwZEgZ3pHsUzQyWABsRSgN2FIZKkVA08pkFTGFBLcJRTID5Ybco1T8fhdJQAyI2VrnpuJD2OkAjnhIugtBMOa8Dy3w5rZYEwloTqakgzWEARAemhVNa2qkgw4MhkiFHhUJFEbgxVNczgKLWtOacSgGuByDUxp8R@9QRROuhI0KOIY49fURXewg0m@1MB0fnRKRQ/L8dhtn2JNA7ET2Cr6sRmKjF/mIFUtAdE@qwM3yLRQsFAVyJzkeYRDmMEih@7wIMZRSH/jT9WbSg30jLkqTj4ySKRuJ2xHF7mAIzKAErUDDZgsKwOtyUExKscZFz2tnYxfSVdu8 "Wolfram Language (Mathematica) – Try It Online") Shaved a few bytes off the trivial answer. ``` %@{{{5, 1}, {1, 3}}, {{3, 4}, {4, -3}}} yields 46375/10296 or 4.504176379 ``` Replacing `Area` with `DiscretizeRegion` will show the intersection. [![enter image description here](https://i.stack.imgur.com/b8c0F.png)](https://i.stack.imgur.com/b8c0F.png) By the way, this will work with any simplexes, not just triangles. -1 Byte thanks to JungHwan Min @user202729's suggestion added 4 bytes but makes it yield 0 for degenerate triangles [Answer] # [Python 2](https://docs.python.org/2/) + PIL, ~~341~~ ~~318~~ ~~313~~ ~~284~~ 270 bytes Special thanks to Dennis that promptly added PIL on TIO -23 bytes thanks to Mr. Xcoder ``` import PIL.Image as I,PIL.ImageDraw as D l=[i*1000for i in[0,0]+input()+[0,0]] z=zip(*[[i-min(t)for i in t]for t in l[::2],l[1::2]]) print sum(map(int.__mul__,*map(lambda i,c:D.Draw(i).polygon(c,1)or i.getdata(),map(I.new,'11',[[max(l)-min(l)]*2]*2),[z[:3],z[3:]])))/1e6 ``` [Try it online!](https://tio.run/##PY5Ba4QwEIXv/orcNnFnU6NtD8LevAg99D4ESXddO5DE4Ea265@3Rmjhg3nvMcO88Izfoy/XlVwYp8g@2w/ZOjP0zNxZC/@2mcwjRU1mz0i5KoriNk6MGHksoNBH8mGOXBx3p7PlvFDgOSKdHHkexd82izrJmKTFui41WFRpapGFiXxk99lxZwLftOw6N9uugzwF1rivq2EEl7qRqREnIcNon8Po@QWUSD/k0MeriYYLSDet9P0DDkodANGZH27F3sgKnZcbAnDButKwYFVvHYR4Uf37uuIbMLVT7bzunCr9Cw "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##hZJda8MgFIbv8yu8m3bGqTFZGuhdbwq72L1IcWvaCeaDxLKtf75T062wLgwOnhPfx5yXw@k/3VvX8vPZNH03OPC8eSKbRh9qoEewwT@f60G/h6t1sqv3YA97VCXArqRZMEr33QAMMK2kmKr7/j5mlYDT6mR6uJDSpI1poUPfIHAqlC6UVlYVV9hKFrJCCRhqdxxaMB4b2OgemtaR7bY52u0WL8KF1c3LTgODX6s1CcagQaTv7Oeha@ErZih0IYfa7bTTEOHwZkPa@h3fMXaHpWz0B7QoerJILbgPhOVJVpnCJ5lV3gVCD6wWZ1ePblxJKXMMWIwMg9QnGiNlymeicDJH0L8B@o/uQ8RIvSUgSE4FK28of/IYwQYj@a0Pr@XTf3hEHkXJl3NYID3FybJgufjL0xVipCxFwWegbLKUkSXPaDkDicv8csKLgt26mmoxP@Vr7fXHSf8ZzG@d3urX86r7duWl6TSXYkrpN6OSJK6uXwzsN3U82rjFcVGqfvDLetH2MGSEJ@b8BQ "Python 2 – Try It Online") To calculate the diference this literally draw the triangles and check the amount of pixels that are painted in both images. This method inserted a rounding error, that is softened by increasing the image size. ### Explanation ``` #the image/triangles are enlarged to increase the precision #a pair of zeros are inserted in the start and at the end, this way "l" will have all 6 points to draw the triangles l=[i*1000for i in[0,0]+input()+[0,0]] #split the input in x and y, where x=l[::2] and y=l[1::2] #get the smallest number on each list, that will be "0" if there is no negative number, to be used as offset. #this will be used to overcome the fact that PIL won't draw on negative coords #zip "x" and "y" lists, to create a list containing the points z=zip(*[[i-min(t)for i in t]for t in x,y]) #create 2 (B&W) blank images #where the size is the difference between the smallest and the largest coord. map(I.new,'11',[[max(l)-min(l)]*2]*2) #draw both triangles and return the pixel list of each image map(lambda i,c:D.Draw(i).polygon(c,1)or i.getdata(),<result of previous line>,[z[:3],z[3:]]) #count the amount of overlapping pixels by summing the color of each pixel, if the pixel is "1" in both images, then the triangles are overlapping, then the amount of pixels is divided by the initial enlarging factor squared (1e6) print sum(map(int.__mul__,*<result of previous line>))/1e6 ``` ]
[Question] [ You should write a 100-byte long brainfuck (BF) program. One character will removed from it in every possible way the resulting 100 new (99-byte long) programs. E.g. for the program `++.>.` the 5 subprograms are `+.>.`, `+.>.`, `++>.`, `++..` and `++.>` . Your score will be the number of unique outputs the 100 programs generate. Higher score is better. ## Details * **Your programs will be terminated after outputting the first character.** * Invalid or non-terminating programs and programs generating empty outputs are not counted towards the score. * The BF cells are 8 bit wrapping ones. (255+1=0, 0-1=255) * Your program is given no input. If you use `,` in the code it set's the current cell to `0`. * There are no cells on the left side of the starting position. E.g. `<.` is invalid but `.<` is valid as the execution is terminated at `.`. The tape is unbounded in the other direction. * Programs with unbalanced brackets (`[` and `]`) are invalid. * Your original program can be shorter than 100 bytes as it's easy to extend it to 100 bytes without changing the score. * Your original program doesn't have to be valid BF code. You can use [this python3 program (ideone link)](http://ideone.com/ScWFs5) to determine the score of your answer. (For long-running programs you may need to modify the `maxstep` variable.) ## Example *(For simplicity this program is shorter than 100 bytes.)* ``` Solution: ++,+[-]+><.-,-. Score: 3 Explanation: Subprogram => Output +,+[-]+><.-,-. => 1 +,+[-]+><.-,-. => 1 +++[-]+><.-,-. => 1 ++,[-]+><.-,-. => 1 ++,+-]+><.-,-. => None ++,+[]+><.-,-. => None ++,+[-+><.-,-. => None ++,+[-]><.-,-. => 0 ++,+[-]+<.-,-. => None ++,+[-]+>.-,-. => 0 ++,+[-]+><-,-. => 255 ++,+[-]+><.,-. => 1 ++,+[-]+><.--. => 1 ++,+[-]+><.-,. => 1 ++,+[-]+><.-,- => 1 Unique outputs are [0, 1, 255] Score is 3 for ++,+[-]+><.-,-. (length = 15) ``` In case of a tie the winner is the one with the shorter code. (Your program can be shorter than 100 bytes as stated in the Details section.) If the codes are equal length the winner is the earlier poster. *Bonus puzzle: without the bolded restriction can you find a program with score 100?* [Answer] # Score: 35 41 69 78 ~~79~~ 83 (Remove the newline.) ``` -->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>- >+>->+>->+>->+>->+>->+>->+>->+>++[>[-<+++>]<<++]>. ``` [Try it online!](https://tio.run/##vVZLj5swEL7zK6aHChCBJK22hyjm0KrbU6uVuj1RhBxwEu8Sm9qG3fz6dHjkTbKrqi0Swsx88/psZijWZinF@83Gtm3reyoVg4rmPKNGKpjjfXf36Qv8Kpk2XAqwPyrKxbxMH0GXs0LJhaIrDU/cLKEUHHEgS1OURtuW9fm5YKnRMNvZpDJjMFdyBdpQkVGVAReIDizrVqpHlrXKpTGFngyHiyAIUikME8anFeU5neXMN9KnJWatfCnyNUJmCFoN7zn7Lst8@LXMDSLFYjjL5Wy4otowNdzlEBRrq67VytgcZhSBKcsc5U4swEuSUfOsK08xN1CtvL74HFJC7MjeixoTj4x3ApZ3qPgU5R@gECOno2OAYqZUAm5prpm1BRFygOoQ96psAQyRZ9rWvimO4UaW1DBHDVb0GVkoyM2ovrpaMYCQ5pyDA2/fpGhjaSAQjeLWDtctSw@7Ve1992LUeu/paclzhsiaS9wU5uRMYCgXcP9bsyl06R0Tgump6CEGQsAOT9hs0/AIjM/Fc9SEBOow2j03a7INaFEwkTkj90jf7N4u6LQ3qH8x6BRG/eFOyewP5/WE0xFHJTjN04OxC2/h3c2HK178l7z4r/ES9HjpqqidXLEcXI4/umIW9XE97yzJJWJzKYtUlsJA36bsT98eF15y1R5n75Kf0wPZl29/ZlddHpMQv9rp2SF82dGWzTf/j03/tWzG/4LN6M/Z7DkITaeqpYfCi@2SPaesMP3t1MIkk0TQFUuSJtEkWeFsSpIuX02akei0ranSRLPtSz2V@HEn1e5Bj8ORjPBoNOGxh5vtjSf7T7Uiu3lQw/aNr8JumGVOtZcUigvToAY2Ce1BtU0lyLhOcWg7dSGtsMXaP8WPo@kPVDF7oKUyOFgqTPIY3P5ocI39oi4CAQO7qQ5tcFVXtsA/CtLpa7WLKpxgtu1uNr4feuHfvD0vCiN/6nleGE/xEYfBbw "Python 3 – Try It Online") I'm not sure exactly why it works... # Score: 79 ``` X->>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+> +>+>+>+>+>+>+>+>+>+>+>+[>[-<+>>+<]+>[-<+>]<<<+]>>. ``` [Try it online!](https://tio.run/##vVZLb5tAEL7zK6aHChAG41bpwWI5tGp6ahUpqVSJIrSGtU2Cd@nuQpJf7w4Pv7ETVW2xLJaZb17fLjOUz3op@Pv12jRN4zYVkkFNizyjWkiY4//m5tMX@FUxpXPBwfwoac7nVfoAqpqVUiwkXSl4zPUSKp4jDkSly0or0zA@P5Us1QpmW5tUZAzmUqxAacozKjPIOaI9w7gW8oFlnXKpdamm4/HC87xUcM24dmlN84LOCuZq4dIKs5au4MUzQmYIWo3vcnYrqmL8tSo0IvliPCvEbLyiSjM53ubglc9GU6uRsTnMKAJTllnSnhqAlyB@e28qTzE3kJ28ufI5pISYkbkTtSYOmWwFrOhR8THK3UMhRgT@IUAyXUkO17RQzNiACNlD9Yg7WXUAhsgTbWffFsdwIyuqmSVHK/qELJTkym@uvlYMwIU@5WDP2zfBu1gKCER@3NnhumPpfrtqvG8ftHzeeXpc5gVDZMMlbgqzCsYxlA24/51ZAH16h4RgejK6j4EQMMMjNrs0HAKTU/EcNSGBJoyyT83abD1aloxnlm8f6Nvd2wYNBoO6Z4MG4A@HOyZzOJwzEE5FOSrBau8OTGx4C@@uPlzw4r7kxX2NF2/AS19F4@SC5eh8fP@CWTTE9by3JOeILYQoU1FxDUObsjt9O1x4zlV3nJ1zfo4P5FC@w5lddHlIQvxqpyeH8GVHGzbf/D823deyGf8LNqM/Z3PgILSdqpHuC8@2S/aUslIPt1MDk0wSTlcsSdpEk2SFsylJ@nwVaUei1bWmWhHFNg/NVMoPO6my93ocjmSER/40jx3cbGcy3b2qNdnOgwa2a3w1dsMss@qdpJQ51y1qZJLQHNWbVLwsVykObasppBN2WPMn/34w/YFKZo6UkBoHS41JHoK7D41cYb9oikDAyGyrQxtcNZUt8IuC9PpGbaMKJ5hp2uv1DzcMnb/xi8LIDRx0FsROt4yDIHDiMPR@Aw "Python 3 – Try It Online") It was *supposed to* sum 2\*mem[i]\*i and add the number of cells (+const) where the addresses are counted from the right to the left. The multiplier 2 and number of cells can make removing + and > having different parity. It indeed worked like that in the 69 points version. But the latest version broke that and got something else by coincidence. It calculates sum(mem[i]\*i+i+1) and removing + and > does almost the same, except for the sum(i) which has a difference of the number of cells, which is also the number of different output for either removing + and >. For the bonus: > > +.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+. > > > [Answer] # Score: ~~37~~ 43 ``` +>-,->,+-><->-[>---+-+<[--->>+><,+>>>++<><<<+<[>--]]><><+-+>+<<+<><+++<[[<[---->-<-]>++>],>,]<,]<+-. ``` EDIT: Now my program allows some square brackets. Not going to win any prizes with it, but that's what I get for making some weighted RNGs do the busy work for me. This was generated by a program I wrote in C. For every `N`th character removed, here are the outputs: ``` N = 0 => 158 N = 1 => 158 N = 2 => 158 N = 3 => 187 N = 4 => 129 N = 5 => 100 N = 6 => 158 N = 7 => 13 N = 8 => 1 N = 9 => 211 N = 10 => 129 N = 11 => 1 N = 12 => 57 N = 13 => 255 N = 14 => Mismatched Braces N = 15 => 59 N = 16 => 11 N = 17 => 11 N = 18 => 11 N = 19 => 117 N = 20 => 11 N = 21 => 117 N = 22 => 166 N = 23 => Mismatched Braces N = 24 => 206 N = 25 => 206 N = 26 => 206 N = 27 => 147 N = 28 => 147 N = 29 => 158 N = 30 => 148 N = 31 => 188 N = 32 => 51 N = 33 => 17 N = 34 => 84 N = 35 => 84 N = 36 => 84 N = 37 => 158 N = 38 => 158 N = 39 => 94 N = 40 => 46 N = 41 => 94 N = 42 => 94 N = 43 => 94 N = 44 => 17 N = 45 => 196 N = 46 => Mismatched Braces N = 47 => 149 N = 48 => No Termination N = 49 => No Termination N = 50 => Mismatched Braces N = 51 => Mismatched Braces N = 52 => 45 N = 53 => 77 N = 54 => 45 N = 55 => 77 N = 56 => 50 N = 57 => 209 N = 58 => 50 N = 59 => 251 N = 60 => 249 N = 61 => 99 N = 62 => 99 N = 63 => 117 N = 64 => 89 N = 65 => 207 N = 66 => 89 N = 67 => 115 N = 68 => 115 N = 69 => 115 N = 70 => 95 N = 71 => Mismatched Braces N = 72 => Mismatched Braces N = 73 => 104 N = 74 => Mismatched Braces N = 75 => No Termination N = 76 => No Termination N = 77 => No Termination N = 78 => No Termination N = 79 => Left Overflow N = 80 => 3 N = 81 => 2 N = 82 => No Termination N = 83 => Mismatched Braces N = 84 => No Termination N = 85 => 133 N = 86 => 133 N = 87 => 0 N = 88 => Mismatched Braces N = 89 => 158 N = 90 => 0 N = 91 => 4 N = 92 => Mismatched Braces N = 93 => 0 N = 94 => 158 N = 95 => Mismatched Braces N = 96 => 0 N = 97 => 157 N = 98 => 159 N = 99 => None ``` There are a total of 37 unique outputs, which are (in numerical order): ``` 0, 1, 2, 3, 4, 11, 13, 17, 45, 46, 50, 51, 57, 59, 77, 84, 89, 94, 95, 99, 100, 104, 115, 117, 129, 133, 147, 148, 149, 157, 158, 159, 166, 187, 188, 196, 206, 207, 209, 211, 249, 251, 255 ``` I am ~~90%~~ 100% certain this solution is not optimal~~, but proving that may be exceedingly difficult~~. There are a few things that are clear. Having no `.` symbols until the last character *seems* to be the way to go~~, and square brackets (`[]`) seem to be rather useless~~. I did a little bit of thinking here, which I'd like to outline: Let `L` be the length of the code in bytes (in the challenge, `100`), and `n` be the number of unique outputs of the sub programs. For `L=3`, there are several optimal solutions of the form `+-.`, where `n=2` (in this case, the outputs are 1 and 255 for `+.` and `-.`, respectively.) This puts the best ratio for `L = 3` at `n/L = 66.67%`. Note that this ratio cannot be beaten for at least `L<10`. For `L=10`, the solutions are simple enough to bruteforce it. Here are all the best solutions, at `n = 6`: ``` ++>-->+<+. => 6 ++>-->+<+. => 6 +++>->+<+. => 6 --->->+<+. => 6 ++>---><+. => 6 +++>--><+. => 6 -->++>-<-. => 6 +++>+>-<-. => 6 --->+>-<-. => 6 -->+++><-. => 6 --->++><-. => 6 ``` Which yields a score ratio of `n/L = 60%`. As `L->infinity`, it is clear that the ratio must approach 0, since there only 255 possible outputs for a potentially infinite `L`. The ratio does NOT, however, decrease uniformly. It is not possible to construct a solution for `n=6, L=9`, so the best possible ratio for `L=9` is `5/9 = 55.56% < 60%`. This begs the question, how *quickly*, and in what matter, does the ratio descend? For `L = 100`, and at `10^9 checks/second`, it would take several orders of magnitude longer than the lifetime of the universe to bruteforce an optimal solution. Is there an elegant way to go about this? ~~I very much doubt that it is down to `37%` for `L = 100`.~~ The ratio actually increases, up to `L=100`. View other answers to confirm. I'd love to hear your evaluations of the above. I ~~could be~~ was atrociously wrong, after all. ]
[Question] [ # Input The first line will be a certain string repeated any amount of times. For example, it could be `abcabcabcabc`, `[];[];[];`, etc. It may be cut off; for example: `1231231231`. Always find the shortest string; for example, if the line is `22222`, then the string is `2`, not `22` or `22222` or anything else. The string will always be repeated at least 2 full times. All subsequent lines will be that pattern offset by any number. For example, it could be: ``` abcabcabc cabcabcab bcabcabca ``` (offset by 1), or it could be: ``` abcdefabcdefabcdefabc cdefabcdefabcdefabcde efabcdefabcdefabcdefa ``` (offset by 4). One of the characters in the input will be wrong. (It is guaranteed not to be on the first line.) For example, in this input: ``` a=1a=1a=1 =1a=1a=1a 1a=11=1a= a=1a=1a=1 =1a=1a=1a ``` the `1` on line 3 is the odd one out. # Output You must output the (zero-based, starting from the top left) coordinates of the odd one out. For example, in the above input, the corresponding output is `4,2`. You may also output `4 2`, or `"4""2"`, or even `[[4],[2]]`, or any other format, as long as you can tell what the output is supposed to be. # Test cases Input: ``` codegolfcodegolfco egolfcodegolfcodeg lfcodegolfcodegoff odegolfcodegolfcod golfcodegolfcodego fcodegolfcodegolfc ``` Output: `16,2` Input: ``` ][[][][[][][[][][[][][[ [][][[][][[][][[][][[][ [][[][][[][][[][][[][][ [[][][[]]][[][][[][][[] ``` Output: `8,3` Input: ``` ... . . ... ``` Output: `1,1` Input: ``` ababa babab ababb babab ``` Output: `4,2` # Go! [Answer] # Perl, 212 191 181 168 bytes ``` $_=<>;/^(((.*?)(.*?))\2+)\3$/;$x=$1x4;while(<>){chop;$x=~/\Q$_\E/&&next;for$i(0..y///c-1){for$r(split//,$x){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&die$i,$",$.-1,$/}}} ``` * This version uses an optimized trick for catching the reply unit, learned in Dennis' [answer](https://codegolf.stackexchange.com/a/24646/16143). * Optimization by using the property that all lines have equal lengths. * Line end is also needed for the last line, otherwise `chomp` instead of `chop` should be used. * Optimizations of ardnew's [comment](https://codegolf.stackexchange.com/questions/24633/find-the-odd-character-out-in-a-pattern/24644?noredirect=1#comment52878_24644) added. Old version, 212 bytes: ``` $_=<>;chop;/^(.+?)\1+(??{".{0,".(-1+length$1).'}'})$/;$;=$1;while(<>){$x=$;x length;chop;$x=~/\Q$_\E/&&next;for$i(0..-1+length$_){for$r(split//,$;){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&exit print$i,$",$.-1}}} ``` ## Ungolfed version: ``` $_ = <>; # read first line /^(((.*?)(.*?))\2+)\3$/; # The repeat unit \2 consists of \3 and \4, # and the start part \2 can be added at the end (as partial or even full unit). $x = $1 x 4; # $x is long enough to cover each following line # Old version: # /^(.+?)\1+(??{ ".{0," . (-1 + length $1) . '}' })$/; # $a = $1; # $a is the repeat unit. # The unit is caught by a non-greedy pattern (.+?) that is # repeated at least once: \1+ # The remaining characters must be less than the unit length. # The unit length is known at run-time, therefore a "postponed" # regular expression is used for the remainder. # process the following lines until the error is found while (<>) { # old version: # $x = $a x length; # $x contains the repeated string unit, by at least one unit longer # than the string in the current line chop; # remove line end of current line $x =~ /\Q$_\E/ && next; # go to next line, if current string is a substring of the repeated units; # \Q...\E prevents the interpretation of special characters # now each string position $x is checked, if it contains the wrong character: for $i (0 .. y///c - 1) { # y///c yields the length of $_ for $r (split //, $x) { #/ (old version uses $a) # replace the character at position $i with a # character from the repeat unit $b = $_; $b =~ s/(.{$i})./$1$r/; $x =~ /\Q$b\E/ && die $i, $", $. - 1, $/; # $" sets a space and the newline is added by $/; # the newline prevents "die" from outputting line numbers } } } ``` [Answer] # ~~Bash~~ Perl, ~~231~~ ~~229~~ ~~218~~ ~~178~~ ~~164~~ ~~166~~ ~~138~~ ~~106~~ 74 bytes ``` /^(((.*).*)\2+)\3$/;$_.=$1x2;$.--,die$+[1]if/^(.*)(.)(.*) .*\1(?!\2).\3/ ``` The script requires using the `-n` switch, which accounts for two of the bytes. The idea of appending two copies of all full repetitions of the pattern has been taken from [MT0's answer](https://codegolf.stackexchange.com/a/24889). In contrast to all other answers, this approach attempts to extract the pattern of the current input line in each iteration; it will fail on the line containing the odd character (and use the pattern of the previous line instead). This is done to include the pattern extraction in the loop, which manages to save a few bytes. ### Ungolfed version ``` #!/usr/bin/perl -n # The `-n' switch makes Perl execute the entire script once for each input line, just like # wrapping `while(<>){…}' around the script would do. /^(((.*).*)\2+)\3$/; # This regular expression matches if `((.*).*)' - accessible via the backreference `\2' - # is repeated at least once, followed by a single repetition of `\3" - zero or more of the # leftmost characters of `\2' - followed by the end of line. This means `\1' will contain # all full repetitions of the pattern. Even in the next loop, the contents of `\1' will be # available in the variable `$1'. $_.=$1x2; # Append two copies of `$1' to the current line. For the line, containing the odd # character, the regular expression will not have matched and the pattern of the previous # line will get appended. # # Since the pattern is repeated at least two full times, the partial pattern repetition at # the end of the previous line will be shorter than the string before it. This means that # the entire line will the shorter than 1.5 times the full repetitions of the pattern, # making the two copies of the full repetitions of the pattern at least three times as # long as the input lines. $.-- , die $+[1] if # If the regular expression below matches, do the following: # # 1. Decrement the variable `$.', which contains the input line number. # # This is done to obtain zero-based coordinates. # # 2. Print `$+[1]' - the position of the last character of the first subpattern of the # regular expression - plus some additional information to STDERR and exit. # # Notably, `die' prints the (decremented) current line number. /^(.*)(.)(.*) .*\1(?!\2).\3/; # `(.*)(.)(.*)', enclosed by `^' and a newline, divides the current input line into three # parts, which will be accesible via the backreferences `\1' to `\3'. Note that `\2' # contains a single character. # # `.*\1(?!\2).\3' matches the current input line, except for the single character between # `\1' and `\3' which has to be different from that in `\2', at any position of the line # containing the pattern repetitions. Since this line is at least thrice as long as # `\1(?!\2).\3', it will be matched regardless of by how many characters the line has been # rotated. ``` ### Example For the test case ``` codegolfcodegolfco egolfcodegolfcodeg lfcodegolfcodegoff odegolfcodegolfcod golfcodegolfcodego fcodegolfcodegolfc ``` the output of the golfed version is ``` 16 at script.pl line 1, <> line 2. ``` meaning that the odd character has the coordinates `16,2`. This ~~blatantly abuses~~ takes advantage of the liberal output format. Just before exiting, the contents of some of Perl's special variables are: ``` $_ = lfcodegolfcodegoff\ncodegolfcodegolfcodegolfcodegolf $1 = lfcodegolfcodego $2 = f $3 = f ``` (`$n` contains the match of the subpattern accessible via the backreference `\n`.) [Answer] # C, 187 bytes Limitations. * Don't use input strings longer than 98 characters :) **Golfed version** ``` char s[99],z[99],*k,p,i,I,o,a;c(){for(i=0;k[i]==s[(i+o)%p];i++);return k[i];}main(){for(gets(k=s);c(p++););for(;!(o=o>p&&printf("%d,%d\n",I,a))&&gets(k=z);a++)while(o++<p&&c())I=I<i?i:I;} ``` **Ungolfed version** ``` char s[99],z[99],*k,p,i,I,o,a; c() { for(i=0 ;k[i]==s[(i+o)%p] ;i++) ; return k[i]; } main() { for(gets(k=s);c(p++);) ; for(;!(o=o>p&&printf("%d,%d\n",I,a)) && gets(k=z);a++) while(o++ < p && c()) I=I<i?i:I; } ``` [Answer] ## Python, ~~303~~ 292 ``` r=raw_input R=range s=r() l=len(s) m=1 g=s[:[all((lambda x:x[1:]==x[:-1])(s[n::k])for n in R(k))for k in R(1,l)].index(True)+1]*l*2 while 1: t=r() z=[map(lambda p:p[0]==p[1],zip(t,g[n:l+n]))for n in R(l)] any(all(y)for y in z)or exit("%d,%d"%(max(map(lambda b:b.index(False),z)),m)) m+=1 ``` Input goes through stdin. I'll explain it if there's any demand, but it doesn't look like I'm going to win anyway. [Answer] ## Perl, ~~157~~ 154 **Edit**: -3 thanks to ardnew' suggestion. ``` <>=~/^(((.*?).*?)\2+)\3$/;$p=$2;$n=$+[1];while(<>){s/.{$n}/$&$&/;/(\Q$p\E)+/g;$s=$p;1while/./g*$s=~/\G\Q$&/g;print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos} ``` It took me some time (on and off, of course, not 5 days ;-) ), and idea about algorithm was initially elusive (though I felt it was there), but finally (and suddenly) it became all clear. If string length is multiple of pattern length, and even if the string doesn't start with the beginning of the pattern, concatenating string with itself will produce pattern in place of concatenation (imagine infinite repetition of a word on circular ribbon - the place of welding is not important). So, the idea is to trim the line to multiple unit length and concatenate original to it. The result, even for the string containing the wrong character, is guaranteed to match to pattern at least once. From there on it's easy to find position of offending character. First line is shamelessly borrowed from Heiko Oberdiek's answer :-) ``` <>=~/^(((.*?).*?)\2+)\3$/; # Read first line, find the repeating unit $p=$2; # and length of whole number of units. $n=$+[1]; # Store as $p and $n. while(<>){ # Repeat for each line. s/.{$n}/$&$&/; # Extract first $n chars and # append original line to them. /(\Q$p\E)+/g; # Match until failure (not necessarily from the # beginning - doesn't matter). $s=$p; # This is just to reset global match position # for $s (which is $p) - we could do without $s, # $p.=''; but it's one char longer. # From here, whole pattern doesn't match - 1while/./g*$s=~/\G\Q$&/g; # check by single char. # Extract next char (if possible), match to # appropriate position in a pattern (position # maintained by \G assertion and g modifier). # We either exhaust the string (then pos is # undefined and this was not the string we're # looking for) or find offending char position. print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos } ``` [Answer] # JavaScript (ES6) - ~~147~~ ~~133~~ 136 Characters ``` s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Expects the string to be tested to be in the variable `s` and outputs the result to the console. ``` var repetitionRE = /^(((.*).*)\2+)\3\n/; // Regular expression to find repeating sequence // without any trailing sub-string of the sequence. var sequence = repetitionRE.exec(s)[1]; // Find the sequence string. s.split('\n') // Split the input into an array. .map( ( row, index ) => // Anonymous function using ES6 arrow syntax { var testStr = row + '᛫'+ sequence + sequence; // Concatenate the current row, a character which won't // appear in the input and two copies of the repetitions // of the sequence from the first line. var match = /^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(testStr); // Left of the ᛫ finds sub-matches for a single // character and the sub-strings before and after. // Right of the ᛫ looks for any number of characters // then the before and after sub-matches with a // different character between. if ( match ) console.log( match[1].length, index ); // Output the index of the non-matching character // and the row. } ); ``` **Test Case 1** ``` s="codegolfcodegolfco\negolfcodegolfcodeg\nlfcodegolfcodegoff\nodegolfcodegolfcod\ngolfcodegolfcodego\nfcodegolfcodegolfc" s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 16 2 ``` **Test Case 2** ``` s="][[][][[][][[][][[][][[\n[][][[][][[][][[][][[][\n[][[][][[][][[][][[][][\n[[][][[]]][[][][[][][[]" s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 8 3 ``` **Test Case 3** ``` s="...\n. .\n..." s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 1 1 ``` **Test Case 4** ``` s="ababa\nbabab\nababb\nbabab" s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 4 2 ``` **Test Case 5** ``` s="xyxy\nyyxy" s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 0 1 ``` **Test Case 6** ``` s="ababaababa\nababaaaaba" s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i)) ``` Outputs ``` 6 1 ``` ]
[Question] [ The [Utah teapot](http://en.wikipedia.org/wiki/Utah_teapot), originally created by Martin Newell, is a convenient object for testing 3D graphics programs. The task is to create a wireframe image of the teapot in perspective projection. To encourage the idea of a *source-code application*, the viewing and camera control may be isolated and excluded from the count. This is so the parameters and input file may be modified and the code re-used to generate diverse images, but it is not necessary to create a full-fledged utility that accepts complicated command-line arguments or such. A "hackerly" balance is sought. ![wireframe teapot](https://i.stack.imgur.com/2Vm8u.png) ref. StackOverflow: [How do Bezier Patches work in the Utah Teapot?](https://stackoverflow.com/questions/14558814/how-do-bezier-patches-work-in-the-utah-teapot) So there are three subtasks here: * read-in the [teapot data](http://code.google.com/p/xpost/downloads/detail?name=teapot) in its [original format](https://web.archive.org/web/20131107090427/http://www.sjbaker.org/wiki/index.php?title=The_History_of_The_Teapot). * subdivide the patch data using deCasteljau splitting or other method. Other methods are using Bezier basis matrices and evaluating the polynomials (standard refs, like Foley and van Dam, Newmann and Sproull), or [Bernstein basis methods](http://www.ams.org/samplings/feature-column/fcarc-bezier) (which are still beyond me). * project the points to 2D (if the language does not support 3D natively) and draw the outline of each small patch as seen from an Eye point whose view is centered on a LookAt point and whose vertical axis is aligned with the vertical axis of the teapot (ie. draw it "upright" from a nice vantagepoint). Assuming that reading line-oriented text data from a file is little trouble, this challenge is really about getting *hands-on* with Bi-Cubic Bezier patch data. Since the simple normal test for backface culling is not sufficient (the patches are not all oriented outward), no hidden-line or -surface removal is necessary. As a wireframe, it should look just fine with the back visible. The appearance may be improved by adjusting the line-width depending upon the distance from the eye, but this is not strictly necessary (my own programs do not do this). This is both [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [rosetta-stone](/questions/tagged/rosetta-stone "show questions tagged 'rosetta-stone'"). Answers competing in the golf should include a count as normal. But submissions in unusual languages are very much encouraged, even if they're not particularly short. For Kolmogorov-complexity enthusiasts, there is a [more concise dataset](http://web.archive.org/web/20160404161539/https://code.google.com/p/xpost/downloads/detail?name=teapotsimp&can=2&q=) where the full set may be reconstructed by adding rotations and mirroring of patches. And in Jim Blinn's *A Trip Down the Graphics Pipeline*, there is an even more concise method of generation by using the fact that the individual patches have rotational or other symmetries. The entire body (or lid) can be described by a single Bezier curve which is rotated around the y-axis. The spout and handles can be described by the two curves of their profile, and then selecting the intermediate control points to approximate a circular extrusion. [Answer] ## Postscript Not fully golfed, but this illustrates a different approach than deCasteljau subdivision: evaluating the basis polynomial. Uses [mat.ps](http://web.archive.org/web/20160404161539/https://code.google.com/p/xpost/downloads/detail?name=mat.ps&can=2&q=). ``` (mat.ps)run[ % load matrix library, begin dictionary construction /N 17 /C [ 0 7 4 ] % Cam /E [ 0 0 40 ] % Eye /R 0 roty 120 rotx 90 rotz % Rot: pan tilt twist matmul matmul /f(teapot)(r)file /t{token pop exch pop} % parse a number or other ps token /s{(,){search not{t exit}if t 3 1 roll}loop} % parse a comma-separated list /r{token pop{[f 99 string readline pop s]}repeat}>>begin % parse a count-prefixed paragraph of csv numbers [/P[f r]/V[f r]/v{1 sub V exch get} % Patches and Vertices and vert lookup shortcut /B[[-1 3 -3 1][3 -6 3 0][-3 3 0 0][1 0 0 0]] % Bezier basis matrix /A{dup dup mul exch 2 copy mul 3 1 roll 1 4 array astore} % x->[x^3 x^2 x 1] /M{[1 index 0 4 getinterval 2 index 4 4 getinterval % flattened matrix->rowXcolumn matrix 3 index 8 4 getinterval 4 index 12 4 getinterval]exch pop} /J{ C{sub}vop R matmul 0 get % perspective proJection [x y z]->[X Y] aload pop E aload pop 4 3 roll div exch neg 4 3 roll add 1 index mul 4 1 roll 3 1 roll sub mul} >>begin 300 400 translate 1 14 dup dup scale div currentlinewidth mul setlinewidth % global scale /newline { /line {moveto /line {lineto} store} store } def newline P{ 8 dict begin [exch{v J 2 array astore}forall]/p exch def % load patch vertices and project to 2D /X[p{0 get}forall] M B exch matmul B matmul def % multiply control points by Bezier basis /Y[p{1 get}forall] M B exch matmul B matmul def 0 1 N div 1 1 index .2 mul add{A/U exch def % interpolate the polynomial over (u,v)/(N) /UX U X matmul def /UY U Y matmul def 0 1 N div 1 1 index .2 mul add{A/V exch 1 array astore transpose def /UXV UX V matmul def /UYV UY V matmul def UXV 0 get 0 get UYV 0 get 0 get line }for newline }for 0 1 N div 1 1 index .2 mul add{A/V exch def % interpolate the polynomial over (u,v)/(N) /V [V] transpose def /XV X V matmul def /YV Y V matmul def 0 1 N div 1 1 index .2 mul add{A/U exch 1 array astore transpose def /UXV U XV matmul def /UYV U YV matmul def UXV 0 get 0 get UYV 0 get 0 get line }for newline }for end %exit }forall stroke ``` ![Bezier-basis teapot](https://i.stack.imgur.com/pghgf.png) ## 1112 Stripping out the vertical lines, and discounting the parameters, yields this 1112 char version. Uses [mat.ps](http://web.archive.org/web/20160404161539/https://code.google.com/p/xpost/downloads/detail?name=mat.ps&can=2&q=). ``` (mat.ps)run[ % 12 /N 17 /C [ 0 7 4 ] % Cam /E [ 0 0 40 ] % Eye /R 0 roty 120 rotx 90 rotz % Rot: pan tilt twist matmul matmul /f(teapot)(r)file/t{token pop exch pop}/s{(,){search not{t exit}if t % 1100 3 1 roll}loop}/r{token pop{[f 99 string readline pop s]}repeat}>>begin[/P[f r]/V[f r]/v{1 sub V exch get}/B[[-1 3 -3 1][3 -6 3 0][-3 3 0 0][1 0 0 0]]/A{dup dup mul exch 2 copy mul 3 1 roll 1 4 array astore}/M{[1 index 0 4 getinterval 2 index 4 4 getinterval 3 index 8 4 getinterval 4 index 12 4 getinterval]exch pop}/J{C{sub}vop R matmul 0 get aload pop E aload pop 4 3 roll div exch neg 4 3 roll add 1 index mul 4 1 roll 3 1 roll sub mul}>>begin 300 400 translate 1 14 dup dup scale div currentlinewidth mul setlinewidth /newline{/line{moveto/line{lineto}store}store}def newline P{8 dict begin[exch{v J 2 array astore}forall]/p exch def/X[p{0 get}forall] M B exch matmul B matmul def/Y[p{1 get}forall] M B exch matmul B matmul def 0 1 N div 1 1 index .2 mul add{A/U exch def/UX U X matmul def/UY U Y matmul def 0 1 N div 1 1 index .2 mul add{A/V exch 1 array astore transpose def/UXV UX V matmul def/UYV UY V matmul def UXV 0 get 0 get UYV 0 get 0 get line}for newline}for end}forall stroke ``` ![Bezier-basis loops](https://i.stack.imgur.com/ng9P8.png) [Answer] # Processing (java), 314 (237 without camera control) Not including the array definitions: ``` void setup(){size(640,480,P3D);}void draw(){background(0);noFill();stroke(255);translate(width/2,height/2,70);scale(30);rotateX(map(mouseX,0,width,0,TWO_PI));rotateY(map(mouseY,0,height,0,TWO_PI));for(int[] p:patches){beginShape();for(int pt:p){vertex(data[pt-1][0],data[pt-1][1],data[pt-1][2]);}endShape(CLOSE);}} ``` Data array definitions: ``` float [][] data = {{1.4,0.0,2.4}, {1.4,-0.784,2.4}, {0.784,-1.4,2.4}, {0.0,-1.4,2.4}, {1.3375,0.0,2.53125}, {1.3375,-0.749,2.53125}, {0.749,-1.3375,2.53125}, {0.0,-1.3375,2.53125}, {1.4375,0.0,2.53125}, {1.4375,-0.805,2.53125}, {0.805,-1.4375,2.53125}, {0.0,-1.4375,2.53125}, {1.5,0.0,2.4}, {1.5,-0.84,2.4}, {0.84,-1.5,2.4}, {0.0,-1.5,2.4}, {-0.784,-1.4,2.4}, {-1.4,-0.784,2.4}, {-1.4,0.0,2.4}, {-0.749,-1.3375,2.53125}, {-1.3375,-0.749,2.53125}, {-1.3375,0.0,2.53125}, {-0.805,-1.4375,2.53125}, {-1.4375,-0.805,2.53125}, {-1.4375,0.0,2.53125}, {-0.84,-1.5,2.4}, {-1.5,-0.84,2.4}, {-1.5,0.0,2.4}, {-1.4,0.784,2.4}, {-0.784,1.4,2.4}, {0.0,1.4,2.4}, {-1.3375,0.749,2.53125}, {-0.749,1.3375,2.53125}, {0.0,1.3375,2.53125}, {-1.4375,0.805,2.53125}, {-0.805,1.4375,2.53125}, {0.0,1.4375,2.53125}, {-1.5,0.84,2.4}, {-0.84,1.5,2.4}, {0.0,1.5,2.4}, {0.784,1.4,2.4}, {1.4,0.784,2.4}, {0.749,1.3375,2.53125}, {1.3375,0.749,2.53125}, {0.805,1.4375,2.53125}, {1.4375,0.805,2.53125}, {0.84,1.5,2.4}, {1.5,0.84,2.4}, {1.75,0.0,1.875}, {1.75,-0.98,1.875}, {0.98,-1.75,1.875}, {0.0,-1.75,1.875}, {2.0,0.0,1.35}, {2.0,-1.12,1.35}, {1.12,-2.0,1.35}, {0.0,-2.0,1.35}, {2.0,0.0,0.9}, {2.0,-1.12,0.9}, {1.12,-2.0,0.9}, {0.0,-2.0,0.9}, {-0.98,-1.75,1.875}, {-1.75,-0.98,1.875}, {-1.75,0.0,1.875}, {-1.12,-2.0,1.35}, {-2.0,-1.12,1.35}, {-2.0,0.0,1.35}, {-1.12,-2.0,0.9}, {-2.0,-1.12,0.9}, {-2.0,0.0,0.9}, {-1.75,0.98,1.875}, {-0.98,1.75,1.875}, {0.0,1.75,1.875}, {-2.0,1.12,1.35}, {-1.12,2.0,1.35}, {0.0,2.0,1.35}, {-2.0,1.12,0.9}, {-1.12,2.0,0.9}, {0.0,2.0,0.9}, {0.98,1.75,1.875}, {1.75,0.98,1.875}, {1.12,2.0,1.35}, {2.0,1.12,1.35}, {1.12,2.0,0.9}, {2.0,1.12,0.9}, {2.0,0.0,0.45}, {2.0,-1.12,0.45}, {1.12,-2.0,0.45}, {0.0,-2.0,0.45}, {1.5,0.0,0.225}, {1.5,-0.84,0.225}, {0.84,-1.5,0.225}, {0.0,-1.5,0.225}, {1.5,0.0,0.15}, {1.5,-0.84,0.15}, {0.84,-1.5,0.15}, {0.0,-1.5,0.15}, {-1.12,-2.0,0.45}, {-2.0,-1.12,0.45}, {-2.0,0.0,0.45}, {-0.84,-1.5,0.225}, {-1.5,-0.84,0.225}, {-1.5,0.0,0.225}, {-0.84,-1.5,0.15}, {-1.5,-0.84,0.15}, {-1.5,0.0,0.15}, {-2.0,1.12,0.45}, {-1.12,2.0,0.45}, {0.0,2.0,0.45}, {-1.5,0.84,0.225}, {-0.84,1.5,0.225}, {0.0,1.5,0.225}, {-1.5,0.84,0.15}, {-0.84,1.5,0.15}, {0.0,1.5,0.15}, {1.12,2.0,0.45}, {2.0,1.12,0.45}, {0.84,1.5,0.225}, {1.5,0.84,0.225}, {0.84,1.5,0.15}, {1.5,0.84,0.15}, {-1.6,0.0,2.025}, {-1.6,-0.3,2.025}, {-1.5,-0.3,2.25}, {-1.5,0.0,2.25}, {-2.3,0.0,2.025}, {-2.3,-0.3,2.025}, {-2.5,-0.3,2.25}, {-2.5,0.0,2.25}, {-2.7,0.0,2.025}, {-2.7,-0.3,2.025}, {-3.0,-0.3,2.25}, {-3.0,0.0,2.25}, {-2.7,0.0,1.8}, {-2.7,-0.3,1.8}, {-3.0,-0.3,1.8}, {-3.0,0.0,1.8}, {-1.5,0.3,2.25}, {-1.6,0.3,2.025}, {-2.5,0.3,2.25}, {-2.3,0.3,2.025}, {-3.0,0.3,2.25}, {-2.7,0.3,2.025}, {-3.0,0.3,1.8}, {-2.7,0.3,1.8}, {-2.7,0.0,1.575}, {-2.7,-0.3,1.575}, {-3.0,-0.3,1.35}, {-3.0,0.0,1.35}, {-2.5,0.0,1.125}, {-2.5,-0.3,1.125}, {-2.65,-0.3,0.9375}, {-2.65,0.0,0.9375}, {-2.0,-0.3,0.9}, {-1.9,-0.3,0.6}, {-1.9,0.0,0.6}, {-3.0,0.3,1.35}, {-2.7,0.3,1.575}, {-2.65,0.3,0.9375}, {-2.5,0.3,1.125}, {-1.9,0.3,0.6}, {-2.0,0.3,0.9}, {1.7,0.0,1.425}, {1.7,-0.66,1.425}, {1.7,-0.66,0.6}, {1.7,0.0,0.6}, {2.6,0.0,1.425}, {2.6,-0.66,1.425}, {3.1,-0.66,0.825}, {3.1,0.0,0.825}, {2.3,0.0,2.1}, {2.3,-0.25,2.1}, {2.4,-0.25,2.025}, {2.4,0.0,2.025}, {2.7,0.0,2.4}, {2.7,-0.25,2.4}, {3.3,-0.25,2.4}, {3.3,0.0,2.4}, {1.7,0.66,0.6}, {1.7,0.66,1.425}, {3.1,0.66,0.825}, {2.6,0.66,1.425}, {2.4,0.25,2.025}, {2.3,0.25,2.1}, {3.3,0.25,2.4}, {2.7,0.25,2.4}, {2.8,0.0,2.475}, {2.8,-0.25,2.475}, {3.525,-0.25,2.49375}, {3.525,0.0,2.49375}, {2.9,0.0,2.475}, {2.9,-0.15,2.475}, {3.45,-0.15,2.5125}, {3.45,0.0,2.5125}, {2.8,0.0,2.4}, {2.8,-0.15,2.4}, {3.2,-0.15,2.4}, {3.2,0.0,2.4}, {3.525,0.25,2.49375}, {2.8,0.25,2.475}, {3.45,0.15,2.5125}, {2.9,0.15,2.475}, {3.2,0.15,2.4}, {2.8,0.15,2.4}, {0.0,0.0,3.15}, {0.0,-0.002,3.15}, {0.002,0.0,3.15}, {0.8,0.0,3.15}, {0.8,-0.45,3.15}, {0.45,-0.8,3.15}, {0.0,-0.8,3.15}, {0.0,0.0,2.85}, {0.2,0.0,2.7}, {0.2,-0.112,2.7}, {0.112,-0.2,2.7}, {0.0,-0.2,2.7}, {-0.002,0.0,3.15}, {-0.45,-0.8,3.15}, {-0.8,-0.45,3.15}, {-0.8,0.0,3.15}, {-0.112,-0.2,2.7}, {-0.2,-0.112,2.7}, {-0.2,0.0,2.7}, {0.0,0.002,3.15}, {-0.8,0.45,3.15}, {-0.45,0.8,3.15}, {0.0,0.8,3.15}, {-0.2,0.112,2.7}, {-0.112,0.2,2.7}, {0.0,0.2,2.7}, {0.45,0.8,3.15}, {0.8,0.45,3.15}, {0.112,0.2,2.7}, {0.2,0.112,2.7}, {0.4,0.0,2.55}, {0.4,-0.224,2.55}, {0.224,-0.4,2.55}, {0.0,-0.4,2.55}, {1.3,0.0,2.55}, {1.3,-0.728,2.55}, {0.728,-1.3,2.55}, {0.0,-1.3,2.55}, {1.3,0.0,2.4}, {1.3,-0.728,2.4}, {0.728,-1.3,2.4}, {0.0,-1.3,2.4}, {-0.224,-0.4,2.55}, {-0.4,-0.224,2.55}, {-0.4,0.0,2.55}, {-0.728,-1.3,2.55}, {-1.3,-0.728,2.55}, {-1.3,0.0,2.55}, {-0.728,-1.3,2.4}, {-1.3,-0.728,2.4}, {-1.3,0.0,2.4}, {-0.4,0.224,2.55}, {-0.224,0.4,2.55}, {0.0,0.4,2.55}, {-1.3,0.728,2.55}, {-0.728,1.3,2.55}, {0.0,1.3,2.55}, {-1.3,0.728,2.4}, {-0.728,1.3,2.4}, {0.0,1.3,2.4}, {0.224,0.4,2.55}, {0.4,0.224,2.55}, {0.728,1.3,2.55}, {1.3,0.728,2.55}, {0.728,1.3,2.4}, {1.3,0.728,2.4}, {0.0,0.0,0.0}, {1.5,0.0,0.15}, {1.5,0.84,0.15}, {0.84,1.5,0.15}, {0.0,1.5,0.15}, {1.5,0.0,0.075}, {1.5,0.84,0.075}, {0.84,1.5,0.075}, {0.0,1.5,0.075}, {1.425,0.0,0.0}, {1.425,0.798,0.0}, {0.798,1.425,0.0}, {0.0,1.425,0.0}, {-0.84,1.5,0.15}, {-1.5,0.84,0.15}, {-1.5,0.0,0.15}, {-0.84,1.5,0.075}, {-1.5,0.84,0.075}, {-1.5,0.0,0.075}, {-0.798,1.425,0.0}, {-1.425,0.798,0.0}, {-1.425,0.0,0.0}, {-1.5,-0.84,0.15}, {-0.84,-1.5,0.15}, {0.0,-1.5,0.15}, {-1.5,-0.84,0.075}, {-0.84,-1.5,0.075}, {0.0,-1.5,0.075}, {-1.425,-0.798,0.0}, {-0.798,-1.425,0.0}, {0.0,-1.425,0.0}, {0.84,-1.5,0.15}, {1.5,-0.84,0.15}, {0.84,-1.5,0.075}, {1.5,-0.84,0.075}, {0.798,-1.425,0.0}, {1.425,-0.798,0.0} }; int [][] patches = { {32}, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}, {4,17,18,19,8,20,21,22,12,23,24,25,16,26,27,28}, {19,29,30,31,22,32,33,34,25,35,36,37,28,38,39,40}, {31,41,42,1,34,43,44,5,37,45,46,9,40,47,48,13}, {13,14,15,16,49,50,51,52,53,54,55,56,57,58,59,60}, {16,26,27,28,52,61,62,63,56,64,65,66,60,67,68,69}, {28,38,39,40,63,70,71,72,66,73,74,75,69,76,77,78}, {40,47,48,13,72,79,80,49,75,81,82,53,78,83,84,57}, {57,58,59,60,85,86,87,88,89,90,91,92,93,94,95,96}, {60,67,68,69,88,97,98,99,92,100,101,102,96,103,104,105}, {69,76,77,78,99,106,107,108,102,109,110,111,105,112,113,114}, {78,83,84,57,108,115,116,85,111,117,118,89,114,119,120,93}, {121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136}, {124,137,138,121,128,139,140,125,132,141,142,129,136,143,144,133}, {133,134,135,136,145,146,147,148,149,150,151,152,69,153,154,155}, {136,143,144,133,148,156,157,145,152,158,159,149,155,160,161,69}, {162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177}, {165,178,179,162,169,180,181,166,173,182,183,170,177,184,185,174}, {174,175,176,177,186,187,188,189,190,191,192,193,194,195,196,197}, {177,184,185,174,189,198,199,186,193,200,201,190,197,202,203,194}, {204,204,204,204,207,208,209,210,211,211,211,211,212,213,214,215}, {204,204,204,204,210,217,218,219,211,211,211,211,215,220,221,222}, {204,204,204,204,219,224,225,226,211,211,211,211,222,227,228,229}, {204,204,204,204,226,230,231,207,211,211,211,211,229,232,233,212}, {212,213,214,215,234,235,236,237,238,239,240,241,242,243,244,245}, {215,220,221,222,237,246,247,248,241,249,250,251,245,252,253,254}, {222,227,228,229,248,255,256,257,251,258,259,260,254,261,262,263}, {229,232,233,212,257,264,265,234,260,266,267,238,263,268,269,242}, {270,270,270,270,279,280,281,282,275,276,277,278,271,272,273,274}, {270,270,270,270,282,289,290,291,278,286,287,288,274,283,284,285}, {270,270,270,270,291,298,299,300,288,295,296,297,285,292,293,294}, {270,270,270,270,300,305,306,279,297,303,304,275,294,301,302,271}, {306} }; ``` More readable version: ``` void setup() { size(640,480,P3D); } void draw() { background(0); noFill(); stroke(255); translate(width/2,height/2,70); scale(30); rotateX(map(mouseX,0,width,0,TWO_PI)); rotateY(map(mouseY,0,height,0,TWO_PI)); for (int[] p:patches) { beginShape(); for (int pt:p) { vertex(data[pt-1][0],data[pt-1][2],data[pt-1][2]); } endShape(CLOSE); } } ``` And some pics: ![finished product](https://i.stack.imgur.com/7J3e2.png) Another version with some interesting effects: ``` void setup(){size(640,480,P3D);} void draw(){ background(0);noFill();stroke(255); translate(width/2,height/2,70);scale(30); rotateX(map(mouseX,0,width,0,TWO_PI));rotateY(map(mouseY,0,height,0,TWO_PI)); for(int[] p:patches){ //beginShape(QUADS); for(int pt:p){ for(int pu:p){ //vertex(data[pu-1][0],data[pu-1][4],data[pu-1][2]); line(data[pt-1][0],data[pt-1][5],data[pt-1][2],data[pu-1][0],data[pu-1][6],data[pu-1][2]); }} //endShape(CLOSE); } } ``` ![version 2](https://i.stack.imgur.com/9TWuP.png) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 7 years ago. [Improve this question](/posts/16036/edit) Create short source code in your favourite compiled language that compiles into a big (not less than 104857600 bytes) executable file. The program must be runnable (assuming 1GB of free memory) and can do anything (preferrable something simple like a hello world). Usage of non-obvious tricks is encouraged. Boring example in C: ``` int a[1024*1024*25] = { 1 }; int main(){} ``` Bonus points if it can be "explained" why the executable can't be reduced in size (i.e. all bloat is actually used somehow). [Answer] OK, here's another one in C, going for the vaguely defined bonus points: ``` #define a(x) x,x|1,x|2,x|3,x|4,x|5,x|6,x|7 #define b(x) a(x),a(x|8),a(x|16),a(x|24) #define c(x) b(x),b(x|32),b(x|64),b(x|96) #define d(x) c(x),c(x|128),c(x|256),c(x|384) #define e(x) d(x),d(x|512),d(x|4<<8),d(x|6<<8) #define f(x) e(x),e(x|2048),e(x|4096),e(x|6144) #define g(x) f(x),f(x|8192),f(x|4<<12),f(x|6<<12) #define h(x) g(x),g(x|2<<14),g(x|4<<14),g(x|6<<14) #define i(x) h(x),h(x|2<<16),h(x|4<<16),h(x|6<<16) #define j(x) i(x),i(x|2<<18),i(x|4<<18),i(x|6<<18) #define k(x) j(x),j(x|2<<20),j(x|4<<20),j(x|6<<20) int u,v,z[]={k(0),k(2<<22),k(4<<22),k(6<<22)} int main(){for(u=v=0;u<1<<25;u++)v|=u!=z[u];return v;} ``` Basically, at compile time, it build a ascending sequence of integers from 0 to 225 − 1. At runtime, it verifies that the sequence indeed contains the expected values, and if not, returns a non-zero error code. Ps. If I did my math right, the executable should be over 100 MiB. I'll let you know the exact size once it's done compiling... [Answer] ## C# Not sure if this qualifies as short, because the source code ended up being >30k :) I.e - too big to quote. Here's a slightly shortened version of it ``` using System.Collections.Generic; class Program { static void Main() { var a = new List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(); } } ``` The code I actually compiled can be found here: <http://pastebin.com/R5T3e3J0> This will create a .EXE file of ~45KiB when compiled without optimizations. Compile it again with Ngen.exe (Native Image Generator) and it becomes a whopping 104MiB! This works due to how the CLR generic type system works. Each and every List<> in the above code will generate a new type declaration (normally through JIT compilation, but Ngen performs AOT compilation). So one type for List< int >, another for List< List< int > >, and so on. So for this code, a total of 5160 different generic lists will be created. [Answer] **COBOL** ``` ID DIVISION. PROGRAM-ID. BLOAT. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 THE-TEST-STRINGS. 05 FILLER OCCURS 11584 TIMES. 10 TEST-STRING PIC X(11584). LOCAL-STORAGE SECTION. 01 FIRST-TIME-FLAG PIC X VALUE "Y". 01 DISP-BEFORE-STRING COMP PIC 9(8). 01 LOOP-COUNTER COMP PIC 9(8). 01 START-STRING. 05 FILLER OCCURS 0 TO 11584 TIMES DEPENDING ON DISP-BEFORE-STRING. 10 FILLER PIC X. 05 THE-SUBSTRING PIC X(12). 01 INITIAL-STRING PIC X(12) VALUE "HELLO WORLD!". LINKAGE SECTION. 01 STRING-PARAMETER PIC X(11584). 01 THE-RESULT PIC X. PROCEDURE DIVISION USING STRING-PARAMETER THE-RESULT . IF FIRST-TIME-FLAG = "Y" PERFORM SET-UP-STRINGS END-IF PERFORM VARYING LOOP-COUNTER FROM 1 BY 1 UNTIL LOOP-COUNTER GREATER THAN 11584 OR STRING-PARAMETER EQUAL TO TEST-STRING ( LOOP-COUNTER ) END-PERFORM IF STRING-PARAMETER EQUAL TO TEST-STRING ( LOOP-COUNTER ) MOVE "Y" TO THE-RESULT ELSE MOVE "N" TO THE-RESULT END-IF GOBACK . SET-UP-STRINGS. PERFORM VARYING LOOP-COUNTER FROM 0 BY 1 UNTIL LOOP-COUNTER EQUAL TO 11584 MOVE 11584 TO DISP-BEFORE-STRING MOVE SPACE TO START-STRING MOVE LOOP-COUNTER TO DISP-BEFORE-STRING MOVE INITIAL-STRING TO THE-SUBSTRING MOVE START-STRING TO TEST-STRING ( LOOP-COUNTER + 1 ) END-PERFORM MOVE "N" TO FIRST-TIME-FLAG . ``` A little knowledge can be a dangerous thing. It can be faster to do one large compare than a lot of small compares; IBM's Enterprise COBOL (up to Version 4.2) can have a maximum WORKING-STORAGE of 128MB (Version 5.0 can have 2GB); LOCAL-STORAGE offers a further 128MB if you need more space. The task is to confirm that a 11584-byte piece of storage has the value "HELLO WORLD!" somewhere, and the rest is space. The, fictitious, programmer decides to write a sub-program for this (just in case it is needed elsewhere), and to include their high-performance technique (bonus). The programmer calculates that 11584 \* 11584 is 128MB, so uses WORKING-STORAGE for a huge table, and LOCAL-STORAGE for everything else that is needed. The programmer codes it up, and smiles knowingly to themselves when the compile is clean. They were right about the 128MB. Tests the code. It works. Possibly a little slow, but there's a heavy load on machine. Smiles again, thinking how slow it would be if coded without their level of expert knowledge. The WORKING-STORAGE comes in at 134,189,056 bytes, and there's a good few bytes of other stuff as well. Should be large enough. The reality is that doing a long compare instead of a short compare, as implemented here, is a very slow way to do it. Even slower, the LOCAL-STORAGE, which is initialised by run-time routines every time a sub-program is called, causes the entire 128MB to be set up for each CALL. The programmer was just plain wrong about the size of the table, there is enough room without using LOCAL-STORAGE. Long compares can beat short compares, but only when the actual number of compares is reduced. I considered swapping the LOCAL-STORAGE and WORKING-STORAGE around, it is just far less likely someone would code it that way round, so I didn't. Putting a VALUE SPACE on the table (if it had been in LOCAL-STORAGE) would have initilised the table *twice* on each CALL, so even slower. The Bloat can't be removed, without rewriting the program. Most of the code is bad, though there is one useful technique. This is not a real-life example, but I can imagine someone doing it, if that someone is clever enough :-) Compiling is no problem at all. Running it with every possibility quickly proves to be not worth attempting. Of course, there is a plain old Bug as well. A very common one in "searching" tasks. [Answer] # PowerBASIC ``` #BLOAT(104857600) FUNCTION PBMAIN PRINT "Hello World" BEEP END FUNCTION ``` [Answer] # Scala ``` import scala.{specialized=>s} import scala.Specializable.{Everything=>E} class Printer[@s(E) A, @s(E) B, @s(E) C, @s(E) D, @s(E) E, @s(E) F, @s(E) G, @s(E) H]{ def print(a:A,b:B,c:C)=println(s"$a, $b, $c") } object Main extends App{ (new Printer[Int,Int,Int,Int,Int,Int,Int,Int]).print(1,2,3) } ``` --- The specialized annotation creates a new class for each type in order to prevent boxing when the types eventually all get turned into objects. It will create 10^8 ((`Everything` consists of 10 types)^(8 type parameters on the class)) class files, each 300-500 bytes, if it doesn't crash first. --- This could be explained by saying that performance is important, especially if the class actually did more than have a method to print. Using generic specialized methods instead of putting it all in the declaration would also make it harder to notice [Answer] ## Javascript ``` function bigenough(){ var kbytes = $('html').html().length; return (kbytes>1024*100); } while(!bigenough()){ $('html').append('<p>WASSUP</p>');} ``` Run this code in Browser Console on this page and when complete, save the page. it should result in a file size greater than 100 MB. Still testing. Will post actual size once done. **update-** the saved page is the result executable. The v8 engine of chrome is the compiler. And the code I posted is the program. i admit that it does take quiet a long to compile. :D ]
[Question] [ # Introduction Often, people refer to dates as the "second Friday in August, 2018" or the "fourth Sunday in March, 2012". But it's hard to tell what date that is! Your task to is to write a program that receives a year, a month, a day of the week, and an integer, and output that date. # Challenge * For input, you will get a year, a month, a day of week, and a number. * You can take input in any reasonable format, like using a string for the day of week or using a zero indexed weekday, or even take the year and month in a single string. Do explain your input format in your answer, though. * The integer that tells you which day of week in the month to target will be an integer from 1-5. The integer will never refer to a day of week that does not exist(e.g. the fifth Friday of February 2019, which doesn't exist). * Years will always be positive. * Your output can be in any reasonable format, including printing your final date. However, please explain your output format un your answer. * Providing the year and month in the output is optional. Also, you may assume the date is valid. # Example Input and Output Consider this input, with the format being taking in the year as a 4 digit number, month as an integer, day of week as string, and the ordinal number as an integer: > > 2019, 3, Saturday, 2 > > 2019, 12, Sunday, 1 > > 2019, 9 Saturday, 1 > > > Output: > > March 9 > > December 1 > > September 7 > > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. [Answer] # MediaWiki Template, 19 bytes ``` {{#time:r|{{{1}}}}} ``` This is a MediaWiki Template ParserFunctions port of [this PHP answer](https://codegolf.stackexchange.com/a/178228/44718) Note: `#time` use PHP `strtotime` internally. --- Sample Input > > {{#time:r|second saturday of March 2019}} > > > Sample Output > > Sat, 09 Mar 2019 00:00:00 +0000 > > > [Answer] # Japt, ~~19~~ 15 bytes Input is: year, 0-based index of month, 0-based index of day of the week (`0` is Sunday) & `n`. ``` _XµW¶Ze}f@ÐUVYÄ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=X1i1V7ZaZX1mQNBVVlnE&input=MjAxOQoyCjYKMg==) ``` :Implicit input of U=year, V=month, W=weekday & X=n }f :Output the first element generated by the right function that returns : falsey (0) when passed through the left function @ :Right function. Y=0-based index of current iteration ÐUVYÄ : new Date(U,V,Y+1) _ :Left function. Z=date being passed Xµ : Decrement X by W¶ : Test W for equality with Ze : Z.getDay() ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~52~~ 48 bytes ``` {1+($^c+4-Date.new($^a,$^b,1).daycount)%7+$^d*7} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9pQW0MlLlnbRNclsSRVLy@1HMhN1FGJS9Ix1NRLSaxMzi/NK9FUNddWiUvRMq/9X5xYqZCmYWRgaKmjYKyjYKajYKhpzYUsamiko2AARGjClmDFQNH/AA "Perl 6 – Try It Online") Anonymous code block that takes input as year, month, day of week (Sunday is 0) and week number (0 indexed). Output is a date object. ### Old Explanation: ``` { } # Anonymous code block ( Date.new( )) # Create a new date with $^a,$^b,1 # With year, month and the first day $_= # Save in the variable $_ + # Add to this $^c+4 # The given day plus 4 ( -.daycount) # The number of days since 17 Nov, 1858 %7 # Modulo 7 to get the correct day +$^d*7 # Plus the 7 times the number of weeks ``` [Answer] # [PHP](https://php.net/), ~~46~~, ~~43~~, 31 bytes ``` <?=date(d,strtotime($argv[1])); ``` [Try it online!](https://tio.run/##K8go@P/fxt42JbEkVSNFp7ikqCS/JDM3VUMlsSi9LNowVlPT@v///8Wpyfl5KQrFiSWlRSmJlQr5aQq@iUXJGQpGBoaWAA "PHP – Try It Online") The program receives as input a string like `"second saturday of March 2019"` The program prints the day number. *-12 bytes thanks to Shaggy.* [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 59 bytes ``` (y,m,d,w)=>1+(d-(int)new DateTime(y,m,1).DayOfWeek+7)%7+7*w ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXooOG7RTSFGz/a1Tq5Oqk6JRr2toZamuk6GoAZTTzUssVXBJLUkMyc1PBCgw19VwSK/3TwlNTs7XNNVXNtc21yv9bcwUUAZVrpGkYGRha6hjrgDXDFeoFJ5aUFqUkVgK1a1pz/QcA "C# (Visual C# Interactive Compiler) – Try It Online") -27 bytes thanks to @EmbodimentOfIgnorance! Less golfed code... ``` // y: year // m: month // d: day of week (0 is Sunday) // w: week number (0 based) (y,m,d,w)=> // start on the first day of the month 1+ // determine the number of days to // the first occurrence of the // requested weekday (d-(int)new DateTime(y,m,1).DayOfWeek+7)%7+ // add the number of requested weeks 7*w ``` The return value is an integer for the day of the month of the requested date. [Answer] # SmileBASIC, ~~58~~ ~~51~~ ~~48~~ ~~46~~ 45 bytes ``` READ N,M$DTREAD M$OUT,,D,W?(5-W+D*2)MOD 7+N*7 ``` Input is in the form: `week,year/month/weekday` * `week`: week number, 0-indexed * `year`: year, 4 digits * `month`: month (1-indexed), 2 digits `0`-padded * `weekday`: day of the week (1-indexed, 1=Sunday), 2 digits `0`-padded Output is the day of the month, 0 indexed. The 2nd Saturday in March 2019 would be `1,2019/03/07` → `8` (March 9th) ## Ungolfed ``` READ WEEK,M$ DTREAD M$ OUT ,,D,W 'Functions in SB can output multiple values using OUT. 'In this case, we don't need the first 2 values, so no variables are given. PRINT (5-W+ D*2) MOD 7 +WEEK*7 ``` ## Explanation The input form was specifically chosen so that the year/month/weekday could be passed directly to `DTREAD`, which is a function which parses a `YYYY/MM/DD` string and returns the year/month/day as numbers, as well as calculating the day of the week. However, notice that, where `DTREAD` expects the day of the month, we're giving it the day of the week instead. This complicates things, but also means that there are fewer input values and we don't need to add `/01` to the end of the date string. `DTREAD` outputs `W` and `D`. `W` is the weekday, and `D` is the day-of-the-week of the `W`th day of the month. (So, if you input `7` as the weekday, `D` will be `7` and `W` will be whatever day-of-the-week the 7th day of the month is) The expression `(5-W+D*2)MOD 7` is used to get the 1st occurrence of the input weekday, as a 0-indexed day of the month. (I figured this one out mostly through trial and error) After that, the program just adds `WEEK*7`. --- I really wish there were separate words for "day of the week" and "day of the month". [Answer] # [MATL](https://github.com/lmendo/MATL), ~~28~~ 27 bytes ``` '1 'ihYO31:q+t8XOi=!A)i)1XO ``` This uses three inputs: * String with month and year: `'March 2019'` * String with three letters, first capitalized, indicating day of the week: '`Sat`' * Number: `2`. Output is a string with day, year and month separated with dashes: `09-Mar-2019`. [Try it online!](https://tio.run/##y00syfn/X91QQT0zI9Lf2NCqULvEIsI/01bRUTNT0zDCHyjpm1iUnKFgZGBoqc6lHpxYos5lBAA "MATL – Try It Online") ### Explanation Consider inputs `'March 2019'`, `'Sat'`, `2`. ``` '1 ' % Push this string % STACK: '1 ' ih % Input string: month and year. Concatenate % STACK: '1 March 2019' YO % Convert to serial date number % STACK: 737485 31:q+ % Create vector [0 1 2 ... 30] and add element-wise % STACK: [737485 737486 737487 ... 737515] t8XO % Duplicate. Convert to date format 'ddd': day of week in three letters. Gives % a 2D char array % STACK: [737485 737486 737487 ... 737515], ['Fri'; 'Sat'; 'Sun'; ...; 'Sun'] i= % Input string: day of week in three letters. Compare element-wise with broadcast % STACK: [737485 737486 737487 ... 737515], % [0 0 0; 0 0 0; ...; 1 1 1; 0 0 0; ... 1 1 1; ...] !A % True for rows containing only 1 % STACK: [737485 737486 737487 ... 737515], [0 0 ... 1 ... 0 ... 1 ...] ) % Index: uses the second vector as a mask into the first % STACK: [737486 737493 737500 737507 737514] i) % Input number. Index % STACK: 737493 1XO % Convert to date format 'dd-mmm-yyyy'. Implicit display % STACK: '09-Mar-2019' ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~92~~ 82 bytes 82 bytes thanks to @Jo King ``` lambda y,m,d,w:z(y,m)[w-(z(y,m)[0][d]>0)][d] from calendar import* z=monthcalendar ``` [Try it online!](https://tio.run/##XY1BCoMwFET3nuJDN0n5BaO0JYJewqV1kTYVBZNIiIhePjXSFtvVDG94zDC71ujUN5DDzfdC3aWAGRVKnLKFrI1W04m8W1xXsi5iGiJqrFHwEP1TS2GhU4Ox7hgtuTLatR/uB9tpRxqSxIwjpAhnhIRSOMCXlMKNVop5HSAvgEe/DksQLmvspIDKUW8O21gQ2Z/It7O9x3dfLChX/wI "Python 3 – Try It Online") ### Original version, 92 bytes ``` from calendar import* def f(y,m,d,w): x=monthcalendar(y,m) if x[0][d]:w-=1 return x[w][d] ``` [Try it online!](https://tio.run/##Xc3BCoMwDIDhe58isIsdGVhlGxXcS3gUD2W1KKytlIr69F0rbLidAn/ykWnzgzVlCMpZDU/x6o0UDkY9WefPRPYKVLahRokLrQistbbGD5/DtKIERgVrm3et7KrlUjMCrvezMzEuKYbJjcZnKityxhFKhCtCQSmc4FsaEYUUW1xA/QBOfg0rEG5xHFBKzWx2w/aWIPuDfH92dPzwiyVyD28 "Python 3 – Try It Online") Takes the year as an integer, month as a 1-indexed integer, day of the week as a 0-index integer where Monday is `0` and Sunday is `6`, and week of the month as a 1-indexed integer. How it works: ``` # import monthcalendar from calendar import* # function with 4 inputs def f(y,m,d,w): # get a 2-D array representing the specified month # each week is represented by an array # and the value of each element is its date of the month # Monday is the 0th element of each week, Sunday is the 6th element # days of the first week of the month before the 1st are 0s x=monthcalendar(y,m) # if the first week of the month includes the desired day of week # convert the week of month to 0-index so that it takes into account the first week if x[0][d]:w-=1 # return the weekday of the week number specified return x[w][d] ``` [Answer] # [R](https://www.r-project.org/), ~~72~~ 69 bytes ``` function(y,m,d,n,D=as.Date(paste0(y,-m,-1))+0:31)D[weekdays(D)==d][n] ``` [Try it online!](https://tio.run/##TcqxCsMgEIDhvS8Sj16CZ5ZacPMNOoYMUhVKybVEpeTpjYQMXb//X2s0NRZ@5teHxYYLemS0xqXBuhzE16UcZAv9gj0BXOV9JLDTL4S3d1sSFozx88RzjUJJ0jhi93C5rK12qOBy8A1JNS98KJ2qUf/PBHUH "R – Try It Online") Taking input as : * Year number * Month number (1-12) * Weekday string in the current locale (TIO requires english name with capital letter) * Ordinal number (1-indexed) [Answer] # [Groovy](http://groovy-lang.org/), 46 bytes ``` {y,m,d,w->r=new Date(y,m,7*w) r-(r.day+7-d)%7} ``` [Try it online!](https://tio.run/##Sy/Kzy@r/J9m@7@6UidXJ0WnXNeuyDYvtVzBJbEkVQMkZq5VrslVpKtRpJeSWKltrpuiqWpe@7@gKDOvJCdPI03D0NBSR8FIR8EMSGpq/gcA "Groovy – Try It Online") Input as years since 1900, 0-indexed month, 0-indexed day (Sunday being 0) and week number [Answer] # [Scala](http://www.scala-lang.org/), 86 bytes ``` (y,m,d,w)=>{var r=new java.util.Date(y,m,7*w) r.setDate(r.getDate-(r.getDay+7-d)%7) r} ``` [Try it online!](https://tio.run/##VYvBCoJAFEX3fsXbBE6NA0YkBQZBBC36gmgx6Rgj01PGpybit09mBLW4l8Pl3CqRRrrilquE4Cw1gnqSwrSCfVlC7zXSQrY91piQLnB1OSHx3@SykaImbcRBkrrGzu/4g6e8ZfGuf59tjKqFf21yonnLPCsqRdNkxf1DwRe7RRSkbBaN1uBKq5EM@pkfhhsOSw7rsRnzBvcC "Scala – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~64~~ 60 bytes ``` func[y m d n][a: to-date[1 m y]d - a/10 - 7 % 7 +(n * 7)+ a] ``` [Try it online!](https://tio.run/##bY1BCsIwFET3PcVsBLUUmxYstjcQulF3IYtPk9CCppImi5w@htqNIJ9hYHiPb5WMNyW5yHQbtTcDD3hBwghOLdxcSHKKs7QFIVGATqxM1WCXku8NjmgOOUjEt52Mg0ZVsgtqnFGhw6KG2UjcyXkrKWDW6MkO40plP0qThDopbpysxMOrZROu/hn@8Gy9Dnqyi0Of3mw4GU/2a8QP "Red – Try It Online") Takes the year, the month and the weekday as numbers, 1-indexed, Monday is the first day of the week. [Answer] ## JavaScript (ES6), ~~49~~ 48 bytes ``` f= (a,d,n)=>(d+6-new Date(...a,7).getDay())%7+n*7-6 ``` ``` <div oninput=o.textContent=f([+y.value,+m.value],+d.value,+n.value)>Year: <input id=y type=number value=2019><br>Month: <select id=m><option value=0>Jan<option value=1>Feb<option value=2>Mar<option value=3>Apr<option value=4>May<option value=5>Jun<option value=6>Jul<option value=7>Aug<option value=8>Sep<option value=9>Oct<option value=10>Nov<option value=11>Dec</select><br>Day: <select id=d><option value=0>Sun<option value=1>Mon<option value=2>Tue<option value=3>Wed<option value=4>Thu<option value=5>Fri<option value=6>Sat</select><br>Count: <input id=n type=number value=1 min=1 max=5><pre id=o> ``` Takes parameters as `f([year, month], day, number)`. Month and day of week (starting on Sunday) are zero-indexed. Edit: Saved 1 byte thanks to @Shaggy. [Answer] # TSQL, 106 bytes ``` DECLARE @ datetime='2019',@m int=3,@w char(2)='saturday',@p int=2 SELECT dateadd(wk,datediff(d,x,dateadd(m,@m-1,@)-1)/7,x)+@p*7FROM(SELECT charindex(@w,' tuwethfrsasu')/2x)x ``` Output: ``` 2019-03-09 00:00:00.000 ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/958119/get-the-date-of-the-nth-day-of-week-in-a-given-year-and-month)** [Answer] # [Kotlin](https://kotlinlang.org), ~~131~~ 84 bytes 47 bytes thanks to ASCII-only's code and comment. Input: year, monthNumber, weekdayNumber, weekNumber All integers 1 to maximum on single line. Week day number is Sunday of 1 to Saturday of 7. The main program makes the year lose 1900 for Date class and month and weekday are shifted to start with zero instead of one before calling the lambda. You can enter your arguments in the input text box to try your own dates. Output: a Date class instance. The main program displays the result like: Sat Mar 09 00:00:00 UTC 2019. There is an expanded version with comments explaining the code for those wishing to learn more. ``` {y,m,d,w->val r=java.util.Date(y,m,7*w) r.setDate(r.getDate()-(r.getDay()+7-d)%7) r} ``` [Try it online!](https://tio.run/##hVdbj9s2E333r2AW6NZqZW3sJPXG@DZA2jRtgN7QzUtRfA@0RNvsSqJLUut1gvz29MwM6UsaoA9xJHGuZ2bOcO9cbG3/8epKvem3Q1yovdG@VJ3r4@aXoVsavDR6nx93xtzJ8wgqL9tW2T6atfFBTVV0qtMPths65XoVbL9ujYJ1U6nboYcV0rFJ8lbHweObcis1r0Z09J03OppGrZxXcQPB2jVGrV27UvVGt63p12ZBgpsYt2FxdUXndFyFqOs78wApiFS1667@HkyI1vXhajq/ns3mpPabd2uvuw6Bqd@Gd@9aE9Sl@o6c/AArJPKDiXBtkHI0FBk9AwmVAqX0kbHSam3vTU8ahJfSfSOQcR6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HL684NhJUj8TAso9c1vfLqYbCQhGlNHY@crpb7BZ2TCgc7eE@AHyhfNw2U7ukGcDQp1cgmdgab@t4kboXxMk1xA@uizMDeHvVRNebbU5c8tHtrWiaERBqJr@kME4xOobVemxDGlPsCcxzThKVnBCRPI@pQCpFfi4X6S9/raoi2rRj19yMiBuLzMLRR3XxyPj65OZZq/hVZKqAi4lUwkaXS6zq9FpMx@z3I8cF@XHw9nyCy4ou52MDU9Ulk9EEhz5TViFPsQKZjJB4W6qX3ev@/W@aGFwWChjrEf5JBQFGTIiN5AhbRBFdc5IH6AMbklFu1Xagxg3X2U6jJi09BuhH166eoJIb44/t92ZVNuZu8IDv@5lPMcAqoipE/AnSKjT/Dg9HwHz6yi7fYf4jY0wyd5HJWheMtTcI63pZcLV1UgwN@zyboro6u3baW7pOiwrDswK0hNane0jUDdMAf5Tz/EVCJzht2iWkmFqDr62HhHiRpTv4Cs4hC3KQbWjiMdOa48qRgOol7w9d7ohZOWiLjLSz3YLm@D7FCmVI9sf@Fo2osYLiv9RD4OoM/GwwvSAo@AtT3o7QCc0g3DPJPAGdcPHpUMT7jC3VRVATG@9S/NlbRoSvGBX/4wL92pcZipQr2HdrjBtvu8jJZ/vPx/2kbEq9W1WwGdr28TNZUFpmKSFVNZyeKs/x1/hmVJ/nwWZGOGJq2H2/HB8cT8loevUym5cGOOrrB56PZQuyZNpgkGzfe7dQbbJO1bl8m9v8@Izq@@BadJeqPLooRK9HSPEG9pP3Ft6HybDQbs9IY9jLrnFaYKvUBFYzYtWPjvQOvvaVI6JpWpIrknE9iKNNtPdnmmM7hmdKWx/r/Br/FZw@nAAS4TT9/es2qcsg0hYYSviKK@vgP "Kotlin – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ 28 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Full program. Prompts for `[year,month]` (January is 1), then for day (Sunday is 0), then for n (first is 1). ``` ¯1⎕DT⎕⊃d/⍨⎕=7|d←(⍳31)+1⎕DT⊂⎕ ``` `⎕` prompt console for `[year,month]` numbers `1⎕DT⊂` days since 1899-12-31 of the 0th of that month `(⍳31)+` add the **i**ntegers 1…31 to that `d←` store in `d` (for **d**ay numbers) `7|` division remainder when dividing by 7 (day-of-week with Sunday being 0 due to good epoch) `⎕=` prompt console for day-of-week number and get mask where equal the day-of-week numbers `d/⍨` filter `d` with that mask `⎕⊃` prompt console for n and use that to pick from the list of day numbers `¯1⎕DT` datetime stamp (has trailing zeros for hours, minutes, seconds, milliseconds) [Answer] # [Go](https://go.dev), 177 bytes ``` import."time" func f(y,m,d string,n int)string{t,_:=Parse("20061",y+m) D:=Hour*24 for t.Weekday().String()!=d{t=t.Add(D)} for i:=1;i<n;i++{t=t.Add(D*7)} return t.Format("Jan2")} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZHRatswFIbZZfUUZ7qSEs2N3bEuynRhCGUUOgq5GCMLrWbLqagtG1keGJMn2U0Y7AH2ON3TTLbSlV3p6Jd0_vP9-vFzXx-fVo3MHuVeQSW1QbpqausiXFQO_9u0zmqzb_8Tstp8x786V7x5__T7WXe6UhgVncmgID2rWA7hLTOgjaNhMzh2x8WttK0iOFks3sWY9fOKojUXH-vOzpK3qKgtuOizUo-57AmNNtNLQl-LfHDCRWmekzU9TPc0F_FKfzArPZ-_HM4u_bFVrrPGd7qqbSUdwdfSJJgewuB_XinXNwrSccouczB8UdIyuKmNe2Cwlv1p_BV86qqR4IAC3ZgVoTCgmov7ZBEv4QI20nv5aSFBkxInsOnMKMRBWL5cie9Ry8V2lw4B4Y6VwAVYafxHbJpSO1IzwF8NHk3OFBdXWpV5S0qKzswYX-pqTdT2YueFVsimUSYnLYN0YuBqu9idQHwd7yYaXyW-8izcHCh6tpZcBON2QLce15WGSOZ_UEYhDxmdEpGR7zIuvgWl6HyGbqTNHmCJ1ipT1TdlPetGNS7Ul2h27l1OaR-PYf0L) Outputs the month and the day as `Jan2`. ### Explanation ``` import."time" func f(y,m,d string,n int)string{ t,_:=Parse("20061",y+m) ``` Parse the date to get the first of the month. `time.Date()` is not feasible here because of the need for a location, which we don't need here. ``` D:=Hour*24 ``` A time constant alias because Go doesn't provide time constants higher than `Hour`. ``` for t.Weekday().String()!=d{t=t.Add(D)} ``` Increment the day until we get the desired day. ``` for i:=1;i<n;i++{t=t.Add(D*7)} ``` Add weeks until we get the desired `n`-th day of the month. ``` return t.Format("Jan2")} ``` Return a string of the date, formatted as a 3-letter month and the date. ]
[Question] [ ## The setup: A social network reports the number of votes a post has in two ways: the number of **net upvotes** (total upvotes - total downvotes), and the **% of votes that were upvotes**, rounded to the nearest integer (.5 rounds up). The number of net upvotes is an integer (not necessarily positive), and the second is guaranteed to be an integer between 0 and +100 inclusive. The number of upvotes and the number of downvotes are both either zero or positive 32-bit integers (you can specify signed or unsigned). Assume that if there are zero total votes, the percentage upvoted is reported as zero. ## The challenge: Given these two integers (net upvotes and % upvoted), what is the shortest program you can write which determines the lowest number of **total upvotes** the post received, with all the constraints above satisfied? Input constraints are guaranteed. If the input does not satisfy the constraints above, the program behavior is up to you. Bonus kudos if it doesn't enter an infinite loop or otherwise crash. Consider returning a negative number if you want more guidance. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution (measured in bytes) wins. * Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. Bonus kudos for a client-side Web language like Javascript. * If you have interesting solutions in multiple languages, post them [separately](https://codegolf.meta.stackexchange.com/questions/181/multiple-answers-from-the-same-person-to-a-question). * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, or full programs. Your call. * [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation of how the code works. * Keep in mind that if you are doing an integer division operation that *truncates* (e.g. 20/3=6) rather than *rounds*, that might not be fully correct. * Additional test cases that explore the edge cases in the above constraints are welcome. * While the expected return type is numeric, [boolean "false" can be used in place of 0](https://codegolf.meta.stackexchange.com/a/9067/47168). ## Example test cases: The first column is just a reference number included to facilitate discussion. ``` ref net %up answer 1 0 0 => 0 2 -5 0 => 0 3 -4 17 => 1 4 -3 29 => 2 5 -2 38 => 3 6 -1 44 => 4 7 0 50 => 1 8 5 100 => 5 9 4 83 => 5 10 3 71 => 5 11 2 63 => 5 12 1 56 => 5 13 1234 100 => 1234 14 800 90 => 894 (tip: don't refer to this as the "last test case;" others may be added.) ``` [Answer] # JavaScript (ES6), 47 bytes Takes input in currying syntax `(n)(p)`, where **n** is the number of net upvotes and **p** is the percentage of upvotes. [May return `false` for `0`](https://codegolf.meta.stackexchange.com/a/9067/58563). ``` n=>p=>(g=u=>u/(u-n/2)*50+.5^p?g(u+1):u)(n>0&&n) ``` [Try it online!](https://tio.run/##fc/dCoMgGIDh867Co9BF@V82sN3JIFrFRmisudtvSh2MWjsR5PnU10f9rqfmeR9fqbG3du70bHQ16gr22unKYehSgxk6SZJk8jpeeugSis4OQVORODZobqyZ7NBmg@1hBwEABMGwIIAxINGWU/mfhWdaLEz3zD2zcmG2Z@aZq4X5nqlnIRYW0c9ySY7eBr6ckpXlnkO54occygt6yKE8Pz4dymX@mynj4istbLcXKBL@Vq4TqhTzBw "JavaScript (Node.js) – Try It Online") ### Commented ``` n => p => ( // given n and p g = u => // g = recursive function taking u = number of upvotes u / (u - n / 2) // compute u / (total_votes / 2) * 50 + .5 // turn it into a percentage, add 1/2 ^ p ? // XOR it with p, which gives 0 if the integer parts are matching // if the result is not equal to 0: g(u + 1) // try again with u + 1 : // else: u // stop recursion and return u )(n > 0 && n) // initial call to g() with u = max(0, n) ``` ### Edge cases Let **Fn(u) = u / (u - n / 2) \* 50 + 0.5** * If **u = 0** and **n = 0**, then **Fn(u) = NaN** and **Fn(u) XOR p = p**. So, we return **u = 0** if **n = p = 0** (first iteration of the first test case) or continue with the recursion if **p != 0** (first iteration of the 7th test case). * If **u > 0** and **u = n / 2**, then **Fn(u) = +Infinity** and -- again -- **Fn(u) XOR p = p**. Unless **p = 0**, we just go on with the next iteration. (This happens in the 9th and 11th test cases.) [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ëI╩½• ╠☺Vì∞«S↑♠αS ``` [Run and debug it](https://staxlang.xyz/#p=8949caab0720cc01568decae531806e053&i=0+++0%0A-5++0%0A-4++17%0A-3++29%0A-2++38%0A-1++44%0A0+++50%0A5+++100%0A4+++83%0A3+++71%0A2+++63%0A1+++56&a=1&m=2) This is brute force. It starts with 0 for candidate upvotes, and increments until it satisfies the formula. Unpacked, ungolfed, and commented, it looks like this. ``` 0 push zero { start filter block... candidate upvotes is on the stack cHx- calculate candidate downvotes for denominator (upvotes * 2 - net) c1? if denominator is zero, replace it with 1 :_ floating point division AJ* multiply by 100 j round to integer ;= is equal to second input? increment until a match is found }gs ``` [Run this one](https://staxlang.xyz/#c=0+++++%09push+zero%0A%7B+++++%09start+filter+block...%0A++++++%09candidate+upvotes+is+on+the+stack%0A++cHx-%09calculate+candidate+downvotes+for+denominator+%28upvotes+*+2+-+net%29%0A++c1%3F+%09if+denominator+is+zero,+replace+it+with+1%0A++%3A_++%09floating+point+division%0A++AJ*+%09multiply+by+100%0A++j+++%09round+to+integer%0A++%3B%3D++%09is+equal+to+second+input%3F%0A+++%09increment+until+a+match+is+found%0A%7Dgs&i=0+++0%0A-5++0%0A-4++17%0A-3++29%0A-2++38%0A-1++44%0A0+++50%0A5+++100%0A4+++83%0A3+++71%0A2+++63%0A1+++56&a=1&m=2) [Answer] # [Clean](https://clean.cs.ru.nl), ~~114~~ ~~107~~ 104 bytes ``` import StdEnv ? =toReal o toInt $a d#e= ?d = ?a+until(\c#b= ~c*e/(e-100.0) = ?(?100*b/(?b+c))==e)inc 0.0 ``` [Try it online!](https://tio.run/##FYo9C4MwFAB3f8UDHRLFquAasrSD0KmuXZ5JLIF8FH0WuvSnN02X4@BOOYMh@agPZ8CjDcn6Z9wIZtKX8CokCIo3gw4iUJwCFRWCLo0AqYsMbI5A1rG7KhcBH1Wbjpl26PtTz/@dyez10jG5NIpzIQy3QUHOaSbcqChhBQFVfldoBxjH9FWrw8ee2umazu@A3qr9Bw "Clean – Try It Online") Defines the function `$ :: Int Int -> Real`, where the arguments are signed integers and the return value is a double-precision float exactly representable by a 32-bit signed integer. It checks every value of `c` in the equation `b=-cd/(d+1)` to find a `b` satisfying `a+c=b` and `b/(b+c)=d`, since the smallest `c` results in the smallest `b`, take the first element of the set of all solutions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes [mildly broken] ``` *²·т-/ò²т;Qi1 ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f69CmQ9svNunqH950aNPFJuvATMP//3UNuUxMAA "05AB1E – Try It Online") Explanation: To solve this, I assumed inputs a, b and expected result x. Given the info in the setup, that gave me the equation: ``` 2x 100x ———— - a = —————— a b ``` Rearranging for x gives ``` ab x = —————————— 2b - 100 ``` The only test case this doesn't work for is 0, 50 - I simply hardcoded to check for this. ``` *²·т-/ò²т;Qi1 Implicit Inputs: a, b STACK (bottom to top) * Multiply the inputs together [ab] ²· Take the second input * 2 [ab, 2b] т- Subtract 100 [ab, 2b - 100] /ò Divide and round [round(ab/(2b-100))] ²т;Qi1 If 2nd input = 50, push 1 to stack { Implicitly output top item of stack [either 1, or round(...)] } ``` [Answer] # Go 1.10, 154 bytes ``` func h(n,u float64)float64{if u==50{return 1};r:=Round(n*u/(2*u-100));s:=Round(n*(u+.5)/(2*u-99));v:=s/(2*s-n);if v>1||Round(v*100)!=u{return r};return s} ``` [Try it on Go Playground!](https://play.golang.org/p/q9Ef2TyDotG) (TIO runs Go 1.9, which doesn't have math.Round) Ungolfed version ``` func haters(n, u float64) float64 { if u == 50 { return 1 } r := Round(n * u / (2*u - 100)) //Test the case where we were given a percentage that was rounded down (e.g. 90.4% given as 90%) //We test this by adding 0.5% to u. The denominator is just a simplified form of 2*(u+0.5) - 100 s := Round(n * (u + .5) / (2*u - 99)) //Check if s is a valid result v := s / (2*s - n) if v > 1 || Round(v*100) != u { return r } //s is strictly less than r, so we don't need to check the minimum. return s } ``` In the interests of adding an explanation, the above formula for r can be derived by simultaneously solving `n=v-d` and `u = 100 * v/(v + d)` for v, where v and d are the number of upvotes and downvotes respectively. The derived formula is undefined for v = 50, so we have to handle that case (which we do with the first if statement). ]
[Question] [ Consider the process of "picking" a nested list. Picking is defined as follows: * If the argument is a list, take an element from the list at random (uniformly), and pick from that. * If the argument is not a list, simply return it. An example implementation in Python: ``` import random def pick(obj): if isinstance(obj, list): return pick(random.choice(obj)) else: return obj ``` For simplicity, we assume that nested lists only contain integers or further nested lists. Given any list, it is possible to create a flattened version which is indistinguishable by `pick`, i.e. picking from it yields the same results, with the same probability. For example, "pick-flattening" the list ``` [1, 2, [3, 4, 5]] ``` yields the list ``` [1, 1, 1, 2, 2, 2, 3, 4, 5] ``` . The reason simply flattening is invalid is because elements of sub-lists have a lower probability of being chosen, e.g. in the list `[1, [2, 3]]` the 1 has a 2/4 = 1/2 chance of being chosen while 3 and 4 both have a 1/4 chance each. Also note that picking from a singleton list is equivalent to picking from its element, and that picking from an empty list has no meaning. ## The Challenge Given a nested list of nonnegative integers, return a flattened list of nonnegative integers from which picking yields the same results with the same probability. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (measured in bytes) wins. ## Specifications * The inputs `[2, 3, 4]`, `[2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]`, and `[2, [3, 3], [[4]]]` are equivalent (i.e. they should give equivalent results). * The outputs `[2, 2, 2, 2, 3, 3, 3, 3]` and `[2, 3]` are equivalent (i.e. either one could be output). * You can assume only numbers in the inclusive range 1-100 will be present in the lists. * You can assume the top-level input will be a list, i.e. `2` is not a valid input. * You can use any reasonable representation of nested lists, for example: `[1, [2, 3]]`, `1 {2 3}`, `"[ 1 [ 2 3 ] ]"`, etc. * Instead of a list, you can output a multiset or a mapping, or, since only numbers in the range 1-100 are allowed, a length-100 list of integers representing quantities. ## Test Cases Note that the listed outputs are only one valid possibility; see specifications for what constitutes a valid input or output. ``` format: input -> output [3] -> [3] [1, [1, 1]] -> [1] [1, [2, 3]] -> [1, 1, 2, 3] [2, 3, [4, [5, 5, 6], 6, 7]] -> [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7] [[1, 1, 2], [2, 3, 3]] -> [1, 2, 3] [[1, 1, 2], [2, 3, 3, 3]] -> [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~41~~ 20 bytes ``` Flatten@*Tuples//@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfLSexpCQ1z0ErpLQgJ7VYX99BWe1/QFFmXomDc35OaW6eW35RbnQ1l4ICUHl0tXFtrA6MbagDRIa1qCJGOsbIIkCuTrWJTrWpjqmOWa2OmY45sixIv45RLVgXqj5UGbAcV23sfwA "Wolfram Language (Mathematica) – Try It Online") Ignore the many warnings, it all works out in the end. ## How it works For a list of depth 2 such as `{{1,2},{3},{4,5,6}}`, `Tuples` will generate the list `{{1,3,4},{1,3,5},{1,3,6},{2,3,4},{2,3,5},{2,3,6}}` corresponding to all the ways to pick an element from `{1,2}` *and* pick an element from `{3}` *and* pick an element from `{4,5,6}`. If we `Flatten` this, then we get all the elements with the correct frequencies, because picking an element from *one* of `{1,2}`, `{3}` or `{4,5,6}` is equivalent to picking an element from all of them, then choosing which one to keep. We use `//@` to apply this at all levels of the input. In the process, Mathematica complains a lot, because it's turning atoms such as `17` into `Tuples[17]`, which is really not supposed to be a thing. But these simplify to the right result later on (`Tuples` is happy to treat `Tuples[17]` as a list of length 1, even if it has a head other than `List`), so the complaining is irrelevant. [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ ~~102~~ 99 bytes ``` g=lambda y=[],*z:[w+[n]for n in y for w in g(*z)]or[y] f=lambda x:x<[]and[x]or sum(g(*map(f,x)),[]) ``` [Try it online!](https://tio.run/##dUzLDoIwEDzbr9hji3sBfCREvmTdQw0BTaQQxNDy87UF8Wayk8zsPHo33juTed@UT93eKg2uJMZkLmjak@G6G8DAw4CDSKdIG5nMiruBHIt6q9nCXoi1qcgGC17vVoZcq3tZo1UKiZWPCzYuXIWknFEApbgg5Z/KEPJVRRYeh4AjQrgTByCcV3vpIWSMWzT/a3w9VYhdPzzMCLW0yn8A "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ߀Œp$¬¡F ``` [Try it online!](https://tio.run/##y0rNyan8///w/EdNa45OKlA5tObQQrf/h9uBXPf//zWijWN1uBSiDXXA2DAWzjPSUTCG8EAsoIAJEJvqKACRWSwQ6yiYQ6TB@nQUjGJ1YEqNcUpA5TQB "Jelly – Try It Online") ### How it works ``` ߀Œp$¬¡F Main link. Argument: x (array or positive integer) ¬ Compute elementwise logical NOT of x: a non-empty array for a non-empty array, 0 for a positive integer. ¡ Apply the link to the left once if ¬ returned a non-empty array, zero timed if it returned 0. $ Monadic chain: ߀ Map the main link over x. Œp Take the Cartesian product. F Flatten the result. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` L€P⁸ṁ€ẎµÐL ``` [Try it online!](https://tio.run/##y0rNyan8/9/nUdOagEeNOx7ubASyHu7qO7T18ASf/4fbj056uHPG///R0YY6CkBkFKujEG2ko2AMRLGxAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 128 bytes ``` def f(l,p=0):m=reduce(int.__mul__,[i*0<[]or len(i)for i in l]);return p*(p==l)or f(sum([(([i],i)[i*0>0]*m)[:m]for i in l],[]),l) ``` [Try it online!](https://tio.run/##Tc3NDgIhDATgV@HYbhqzP7dVfJGm4eBCbAJIcDn49Ig3b5OZfJnyOZ@vvPZ@@GACRCp2xj3Z6o/28KD5vDiXWnSOWKf5xvKqJvoMimEkNZpNFLxWf7aaTZmgWBtxTAHeLQEDsAop/vR9likh70n@LLEgReyljrOhmBdaaB39ShttIti/ "Python 2 – Try It Online") Port of my Jelly answer. -12 thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech). [Answer] # [C (gcc)](https://gcc.gnu.org/), 234 223 bytes ``` h[9][101];o[101];n[9];l;L;e;main(x){for(;(x=scanf("%d",&e))>=0;x?++h[l][e],++n[l]:(e=getchar())-'['?e-']'?0:--l:++l>L&&++L);for(e=1,l=L+1;l--;){for(x=101;--x;o[x]+=e*h[l][x]);e*=n[l];}while(o[x]--?printf("%d ",x):++x<101);} ``` [Try it online!](https://tio.run/##JY5RasMwEESvIgy1tVkv2G2TUm8VX8A3EPow6iY2qEpxAxWUnN2Vk69ZZmHe83T2fl0n@@5s27SOL4@IueDAAwt/jXPUCf5Ol0WzTubHj/Gki6fPoi4F4GgaTj3iZIOz4mrEmK9OiznL1U/jogGoslUvVLmqbzqi0CGG41CWiAPwtiumrYMZsOVAxA9WMtmEiVJ2Sg6N7O6I5IBlZzYI336nOYje/kT99zLH691MFXWCDEkfeQL4tq7P6kXZV2X3aq8OTh3Um/sH "C (gcc) – Try It Online") **Explanation:** ``` h[9][101]; // <- number occurences per nesting level o[101]; // <- number occurences in "flattened" array n[9]; // <- number of entries per nesting level l; // <- current nesting level L; // <- max nesting level e; // <- multi-purpose temporary main(x){ // x: multi-purpose temporary for(; // while not EOF try reading number (x=scanf("%d",&e))>=0; // number was read? x // then increment occurence and # entries in level ?++h[l][e],++n[l] // else read any character ... if not [ :(e=getchar())-'[' // if not ] ?e-']' // do nothing ?0 // else decrement nesting level :--l // else increment nesting level and adjust max level :++l>L&&++L); // init factor in e to 1, iterate over nesting level from innermost for(e=1,l=L+1;l--;){ // iterate over all numbers for(x=101; --x; // add factor times occurence on current level to output o[x]+=e*h[l][x]); // multiply factor by number of entries on current level e*=n[l]; } // iterate over all numbers and output count times while(o[x]--?printf("%d ",x):++x<101); } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~144~~ 139 bytes ``` def f(A,p):[F.append((len(A)*p,a))if a*0<[]else f(a,len(A)*p)for a in A] F=[];f(input(),1);R=[] for v in F:R+=max(F)[0]/v[0]*[v[1]] print R ``` [Try it online!](https://tio.run/##lY/RToQwEEXf@YpJfWmx6gKrm4CYEBI@gNemD43bZptgt1kR16/HAcGQKBtt7jRpe2Z6r/9oD0cX92VOCOn32oChBfcsFdWt8l67PaWNdrRgoeeKMWtAhZtHIXXzqpFVfH5l5ngCBdZBIYMqFzIz1Dr/1lLGI5bVeBMMSDcgVVpf5y/qTCsmNvKuwy0UnYikDPzJuhbqHv1k@qyfyfvBNhrKdDhASXqRSFhdVzdPgEAgIg5D4cQVKJqgmEOyDuEEDiMSjCQ2bLHuOaAeJBaHHbaPdDyil5X8QdtZ0zcL7b6EbmZvcsqwjDF7n4z/gn7Ti5g/9b8E8hM "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~132~~ 131 bytes ``` f=A=>(_=(a,m)=>[].concat(...a.map(m)),n=1,A=A.map(a=>a.map?f(a):[a]),_(A,a=>n*=a.length),_(A,a=>_(a.map(x=>Array(n/a.length).fill(x))))) ``` ``` f=A=>(_=(a,m)=>[].concat(...a.map(m)),n=1,A=A.map(a=>a.map?f(a):[a]),_(A,a=>n*=a.length),_(A,a=>_(a,x=>Array(n/a.length).fill(x)))) console.log( f( [3] ) ) console.log( f( [1, [1, 1]] ) ) console.log( f( [1, [2, 3]] ) ) console.log( f( [2, 3, [4, [5, 5, 6], 6, 7]] ) ) console.log( f( [[1, 1, 2], [2, 3, 3]] ) ) console.log( f( [[1, 1, 2], [2, 3, 3, 3]] ) ) console.log( f( [1, 2, [3, 4, 5], [6, 7]] ) ) ``` ]
[Question] [ ### Description I guess everyone knows the fairy tale of Rapunzel and the prince. For those who do not: [read it here.](http://www.pitt.edu/%7Edash/grimm012.html) However, Rapunzel had just had her hair cut, so it might not be long enough to let her prince climb up! She may get very sad.. ### Challenge Your task is to write a function that evaluates what Rapunzel will be saying when the prince calls for her to let her hair down: When her hair is longer than or equal to the tower is tall plus an extra meter (safety guidelines), she becomes veeeery happy and says `Aaaah!`, with the number of `a`s being the same as `length of her hair - height of the tower`. Otherwise, her hair does not have sufficient length, and she starts crying: `Booho!`, where the `o`s before the `h` equal two thirds of `height of the tower - length of her hair`, and the `o`s after the h being the rest. The number of `o`s after the `B` must be rounded, so if you get `2.6`, there will be 3 `o`s, and the others must be after the `h`. ### I/O You are given positive integers (including null) as arguments, as a list or as two single numbers, in the order you find it the most convenient, but you must state in which order you take them. As the output, print what Rapunzel will be saying. ### Test cases In the test cases, the first number will be the hair length. ``` 0, 0 -> 'Bh!' (probably a dry sob..) 2, 1 -> 'Aah!' 1, 2 -> 'Boh!' 1, 4 -> 'Booho!' 4, 1 -> 'Aaaah!' 2, 4 -> 'Boho!' ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~43 41 40 38 34 33 32~~ 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *~~There's probably a much~~ Is there a shorter way though~~!~~ ? ...this was quite some golfing!* ``` ‘:3;ạ¥⁸4ẋ+;€⁹¦7Ṛṭ;8ị“øŻPLC» ạç> ``` A full program printing the result\*. **[Try it online!](https://tio.run/##AUoAtf9qZWxsef//4oCYOjM74bqhwqXigbg04bqLKzvigqzigbnCpjfhuZrhua07OOG7i@KAnMO4xbtQTEPCuwrhuqHDpz7///8xNP8yNA "Jelly – Try It Online")** ### How? ``` ‘:3;ạ¥⁸4ẋ+;€⁹¦7Ṛṭ;8ị“øŻPLC» - Link 1: number, abs(hair-tower); number, (hair > tower)? ‘ - increment -> abs(hair-tower)+1 :3 - integer divide by 3 -> (abs(hair-tower)+1)//3 - ...the remainder amount after removing 2/3 rounded ⁸ - chain's left argument, abs(hair-tower) ¥ - last two links as a dyad: _ - subtract (yields the 2/3 rounded amount) ; - concatenate 4ẋ - repeat 4 (vectorises) (i.e. [[4,4,...],[4,...]]) + - add (hair > tower)? (vectorises) (i.e. 4s->5s if so) ¦ - sparse application: ;€ 7 - of: concatenate €ach with a 7 ⁹ - to indexes: chain's right argument, (hair-tower)? Ṛ - reverse the list ṭ - tack (hair-tower)? ;8 - concatenate an 8 “øŻPLC» - compression of the word "Abroach" & the string "!B" ị - index into "Abroach!B" (1-indexed & modular, so 0->B) - implicit (smashed) print ạç> - Main link: number, hair; number, tower ạ - absolute difference -> abs(hair-tower) > - greater than? -> (hair > tower)? (1 if so, else 0) ç - call the last link (1) as a dyad ``` \* As a monadic link it returns a list of characters and lists of characters e.g. `['B', [['o', 'o', 'h'], ['o']], '!']`, as a full program the implicit print smashes this e.g. `Booho!` [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` lambda l,h:["B"+"o"*round((h-l)*2/3)+"h"+"o"*round((h-l)/3),"A"+"a"*(l-h)+"h"][l>h]+"!" ``` [Try it online!](https://tio.run/##ZYpBDoIwEEX3nmKc1bSdRiisSCTRa2AXGELapLaE4MLTV2rYuXr57/3ls7kUmzxfHzmMr@c0QmDXDXhHhQnlmt5xInI6CGkujVDo/sKuGW@7HlFS0O53skPonVV4xjynFTz4CANVDJVgIMNQF9YM5mBb2B7elG27Eyyrjxt5BtQ9IMNM0guRvw "Python 3 – Try It Online") Arguments to the function are taken in the order `length of hair`, `height of tower`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ ~~35~~ 32 bytes Input order: `length of hair`, `height of tower` ``` ‹i¹α'a×"Aÿh!"ë¹-x‚>3÷R'o×'hý…Bÿ! ``` [Try it online!](https://tio.run/##AT0Awv8wNWFiMWX//@KAuWnCuc6xJ2HDlyJBw79oISLDq8K5LXjigJo@M8O3Uidvw5cnaMO94oCmQsO/If//Mgo0 "05AB1E – Try It Online") **Explanation** ``` ‹i # if h < l ¹α # push absolute difference of h and l 'a× # repeat "a" that many times "Aÿh!" # interpolate between "A" and "h!" ë # else ¹- # push h-l x‚ # pair with its double >3÷ # increment and integer divide by 3 R # reverse the list 'o× # for each, repeat "o" that many times 'hý # merge the o's on "h" …Bÿ! # interpolate between "B" and "!" ``` [Answer] # Javascript, ~~105~~ 97 bytes Thanks to Oki for helping save 7 bytes! ``` p=(t,s)=>(s||"o").repeat(t) l=>h=>(d=l-h,o=d/3-.5|0,l>h?`A${p(d,"a")}h`:`B${p(o-d)}h`+p(-o))+"!" ``` Defines an anonymous currying function. Use like `f(length)(height)` [Try it online!](https://tio.run/##ZclNDsIgEEDhfW8hcTGTAv60bkyo0ZOUFCo1pEMKcWM9O7ZLdfm@99BPHbtpCEmMZGzOQUHiEVUDcZ4ZMZSTDVYnSFj0yqvGLcsoLxwnZXaVkKd5z33jLu11@wpgONMM3649t7e1SZi1ygCCEEu2YbmjMZK30tMdejgiVIjFN1a4@C8eEOo/rHFxzB8 "JavaScript – Try It Online") [Answer] # PHP>=7.1, 111 bytes ``` [,$h,$t]=$argv;echo BA[$b=$h>$t],($r=str_repeat)(oa[$b],$c=round(($a=abs($h-$t))*($b?:2/3))),h,$r(o,$a-$c),"!"; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/ff61ba88498ebfbd0f153e075e1e1d5bd6add1b4) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` _‘”aẋŒt;⁾h!ɓ_÷1.,3+.”oẋ“Bh!”żð>? ``` [Try it online!](https://tio.run/##y0rNyan8/z/@UcOMRw1zEx/u6j46qcT6UeO@DMWTk@MPbzfU0zHW1gNK5QOlHjXMccpQBHKO7jm8wc7@////Rv9NAA "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). Only works as full program. Arguments are in order: hair, tower [Answer] # Julia, 101 bytes ``` g(h,t)=h>t?string("A","a"^(h-t),"h!"):string("B","o"^round(Int,(t-h)*2/3),"h","o"^round(Int,(t-h)/3)) ``` Arguments to the function are taken in the order `length of Hair`, `height of Tower`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 84 76 bytes It's really rather long, but I spent too much time on this not to post it. Takes two integer arguments: 1. length of hair 2. length of tower Any tips on golfing this would be appreciated. ``` ³>⁴×111ð;ø³>⁴¬×97 97ðxø³ạ⁴ 111ðxø¢L÷3×⁸ær0:1 2Çṭ2£“h”ṭµ1ÇṭµFḟ1£ >¬+65¥;¢;33Ọ ``` [Try it online!](https://tio.run/##y0rNyan8///QZrtHjVsOTzc0NDy8wfrwDgj/0JrD0y3NuSzND2@oAIk93LUQKMoFVgQSWORzeLvx4emPGnccXlZkYGXIZXS4/eHOtUaHFj9qmJPxqGEukHNoqyFY8NBWt4c75hseWsxld2iNtpnpoaXWhxZZGxs/3N3z//9/Q6P/RiYA "Jelly – Try It Online") [Answer] # R, 117 bytes ``` x=diff(scan());cat(`if`(x>0,paste0("A",rep("a",x),"h!"),paste0("B",rep("o",F<-round(-2*x/3)),"h",rep("o",-x-F),"!"))) ``` A bit long, pretty sure this can be golfed down. Takes input from STDIN in the order `Tower, Hair`. [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` lambda h,t:("BA"+(abs(h-t)*2+1)/3*"oa"+"h"+(abs(h-t)+1)/3*"ao"+"h!!")[h>t::2] ``` An unnamed function taking hair length, `h`, and tower height, `t`, and returning a string. **[Try it online!](https://tio.run/##TYxBDoIwEEX3nqLOagYGpWNXTSTRa6iLEkNKIpRgN4Zw9grEhZuXn/eTN3yiD72k5nxPL9fVT6c8R4twvUCOrn6jLyJlkms6njIIDnLwf8/Pu7D6/R7o5qtorTxSE8Y1pdpeIZZcEqOwXqhZNpqFZjOybW1YDJHdqWFs@4gwlTOrSc@qqNQkMxyWZOciLlVuVhJR@gI "Python 2 – Try It Online")** Builds a string starting with `BA`, followed by two thirds of the difference rounded of the string `oa` repeated, followed by a single `h`, then the remainder amount of `ao` repeated, and finally `h!!`. The return value is then every second character starting with either the `B` or `A` via the slice notation `[h>t::2]`. [Answer] ## Perl, 107 bytes Takes hair length first, tower length second. ``` sub b{(($c=$_[0]-$_[1])>0?'A'.'a'x--$c.'h':do{$o=int(2/3*($c*=-1)+.5);'B'.('o'x$o).'h'.('o'x($c-$o))}).'!'} ``` ]
[Question] [ **The simple part:** Given an input string containing only printable ASCII-characters (space - tilde), count the number of occurrences of each character and return the result on any convenient format. The result for a string `a%hda7a` should be something like: `a:3, %:1, h:1, 7:1, d:1`. Sorting is unnecessary, the delimiters and formats are optional but it must be easily understood which number corresponds to which character. You shall not include characters that are not in the input string (`a:3, b:0, c:0, d:1, ...` is not OK). **The real challenge:** Convert every character in your code to an 8-bit binary number (or 16-bit if you're using UTF-16 or similar), and enumerate every character starting at `0`. For every character (`i` is the enumerator), the `i%7`-bit1 **must** be `1`. The bits are numbered from the right. All other bits can be whatever you want. Let's use the following code as an example: ``` [f]-xif)#f ``` Converting this to binary we get the array below. The first number (representing `[` has a `1` in the 0'th position, so that one is OK. The second number (representing `f` has a `1` in the 1'st position, so that one is OK too. Continue like this, and you'll see that the code above is valid. ``` C 76543210 Bit number - -------- ---------- [ 0101101***1*** 0 - OK f 011001***1***0 1 - OK ] 01011***1***01 2 - OK - 0010***1***101 3 - OK x 011***1***1000 4 - OK i 01***1***01001 5 - OK f 0***1***100110 6 - OK ) 0010100***1*** 0 - OK # 001000***1***1 1 - OK f 01100***1***10 2 - OK ``` If we change the code into: `]f[-xif)#f` we'll get the following start of the sequence: ``` C 76543210 Bit number - -------- ---------- ] 01011101 0 <- OK f 01100110 1 <- OK [ 01011011 2 <- Not OK - 00101101 3 <- OK ``` As we see, the third character `[` doesn't have a `1` in the 2nd position (zero-indexed), and this code is therefore not valid. **Test cases:** ``` Input: This is a string containing some symbols: ".#!".#&/# Output: ! " # & / : T a b c e g h i l m n o r s t y . 7 1 2 3 1 1 1 1 2 1 1 1 2 1 5 1 2 4 3 1 6 2 1 2 ``` Any reasonable output format is OK (whatever is most convenient to you). You could for instance have: `:7, !:1, ":2, #:3, &:1, /:1, T:1, a:2 ...` or `[ ,7][!,1][",2][#,3][&,1]...`. The output is on any standard way (return from function, printed to STDOUT etc.) 1`i` modulus `7`. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win[ref](http://meta.codegolf.stackexchange.com/a/10132/31516). [Answer] ## Pyke, ~~1~~ 6 bytes ``` 1cn;1c ``` [Try it here!](http://pyke.catbus.co.uk/?code=1cn%3B1c&input=00110001+-+1) ``` 1c - chunk(size=1, input) n;1 - noop. c - count(^) ``` Half of this code is just no-ops... ``` 00110001 - 1 01100011 - c 01101110 - n 00111011 - ; 00110001 - 1 01100011 - c ``` [Answer] ## Pyth, ~~12~~ ~~8~~ 7 bytes -1 byte thanks to @Loovjo ``` m+d/Qd{ { # remove all duplicated elements from the (implicit) input m # map each element (d) of the parameter (the set from previous operation) /Qd # count the occurrences of d in Q +d # concatenate with d ``` binary representation ``` 0110110**1** m 001010**1**1 + 01100**1**00 d 0010**1**111 / 010**1**0001 Q 01**1**00100 d 0**1**111011 { ``` [Try here](https://pyth.herokuapp.com/?code=m%2Bd%2FQd%7BQ&input=%27aa111ZZZZ%27&debug=0) [Answer] # Befunge-93, 150 bytes ``` ={<{p+}3/}*77\%*7{7:\+{}{1g}+3/*77\%*7{7:}=:_{}{}={}{}{v#{}{}`x1:~ }-}=*}{2*}97}:<$}={$_v#}!:-*84g+3/*77\%*7{7:}=:}:}+}1{}<_{@# }{}{}={}{}{}={^.},\={< ``` [Try it online!](http://befunge.tryitonline.net/#code=PXs8e3ArfTMvfSo3N1wlKjd7NzpcK3t9ezFnfSszLyo3N1wlKjd7Nzp9PTpfe317fT17fXt9e3Yje317fWB4MTp-Cn0tfT0qfXsyKn05N306PCR9PXskX3YjfSE6LSo4NGcrMy8qNzdcJSo3ezc6fT06fTp9K30xe308X3tAIwp9e317fT17fXt9e309e14ufSxcPXs8&input=VGhpcyBpcyBhIHN0cmluZyBjb250YWluaW5nIHNvbWUgc3ltYm9sczogIi4jISIuIyYvIw) I started by writing this as a regular Befunge program, which I golfed as much as possible. I then added padding to make sure the various characters in the program only appeared in permitted positions. This padding relied on the fact that unsupported commands are ignored in Befunge-93, so I just needed a sequence of unused characters whose bits aligned with the positions required (the sequence I used was `={}{}{}`). The complicated bit was that the various branches between lines needed to line up correctly (e.g. the `v` arrow in one line, would need to line up with the `<` arrow below it). This was further complicated by the fact that the bridge command (`#`) could not be separated from its adjacent branching arrow. Initially I tried generating the padding programatically, but in the end it was mostly a manual process. Because of the size of the program I'm not going to list the full character analysis, but this is a sample from the beginning and the end: ``` = 00111101 0 { 01111011 1 < 00111100 2 { 01111011 3 p 01110000 4 + 00101011 5 } 01111101 6 3 00110011 0 / 00101111 1 ... { 01111011 1 ^ 01011110 2 . 00101110 3 } 01111101 4 , 00101100 5 \ 01011100 6 = 00111101 0 { 01111011 1 < 00111100 2 ``` The line breaks are treated as a newline characters, so will either be in position 1 or 3. [Answer] ## [MATL](https://github.com/lmendo/MATL), 17 bytes ``` u"G91x@=zD91x@uRD ``` Displays the count, then the corresponding character, all newline-separated. Biggest difficulty is the `@` which is `0b01000000`; I hope I can find a way to make do without it. [Try it online!](https://tio.run/nexus/matl#@1@q5G5pWOFgW@UCokqDXP7/V09MSk5PVwcA "MATL – TIO Nexus") Explanation: ``` u" % Implicit input. Take (u)nique characters and loop (") over them. G % Take the input a(G)ain 91x % Filler: push 91, delete immediately. @ % Push current character of loop = % Check for equality with earlier G z % Count number of equal characters D % Display 91x % More filler! @ % Get loop character again uR % Filler: two NOPs for the single-character @ D % Display. Implicitly end loop. ``` ### MATL, 15 bytes (questionable output) If just leaving two row vectors on the stack is allowed (function-like behaviour as per [this](http://meta.codegolf.stackexchange.com/a/8507/32352) Meta post), we can get down to ``` u"G91x@=zv]v!Gu ``` But here, the output is not quite as neatly ordered. [Answer] # CJam, 14 bytes ``` q__|_ @sfe=]zp ``` [Try it here.](http://cjam.aditsu.net/#code=q__%7C_%20%40sfe%3D%5Dzp&input=foobar12321) The space before the `@` and the `s` after it are filler characters inserted to make the ASCII codes fit the required pattern: the space does nothing, and the `s` just converts a string into a string. Other than that, this is a pretty simple and straightforward implementation of the challenge task: ``` q_ "read the input and make a copy of it"; _| "collapse repeated characters in the copy"; _ "save a copy of the collapsed string"; @ "pull the original input string to the top of the stack"; s "(does nothing here)"; fe= "for each character in the collapsed string, count the ..."; "... number of times it occurs in the original string"; ]z "pair up the counts with the saved copy of the collapsed string"; p "print the string representation of the result"; ``` For the input `foobar123`, this code outputs `[['f 1] ['o 2] ['b 1] ['a 1] ['r 1] ['1 2] ['2 2] ['3 1]]`. If simply printing the counts on one line and the corresponding characters on another, as in: ``` [1 2 1 1 1 2 2 1] fobar123 ``` is considered an acceptable output format, then the `]z` may be omitted to save two bytes, for a total of **12 bytes**. Yes, the shortened code will still pass the bit pattern requirement. Ps. I also wrote [a simple source code checker](http://cjam.aditsu.net/#code=q_N%5Cee%7B~i2b%5C7%25~%3D%7D%25&input=q__%7C_%20%40sfe%3D%5Dzp) for this challenge. Given a line of code as input, it will first echo that line and then print the same line with each character replaced by its (*n* % 7)-th ASCII bit. If the second line is all ones, the input is valid. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes in Jelly's codepage ``` ṢZṢṀŒr ``` [Try it online!](https://tio.run/nexus/jelly#@/9w56IoIH64s@HopKL///@HZGQWKwBRokJxSVFmXrpCcn5eSWJmHohZnJ@bqlBcmZuUn1NspaCkp6wIxGr6ygA) This is a function that returns a list of (character, count) pairs. (Jelly represents such lists as text, e.g. if they're sent to standard output, by concatenating the elements, which is why you have to treat this as a function rather than a complete program. ([Here's](https://tio.run/nexus/jelly#@/9w56IoIH64s@HopKKjkx7unPH///@QjMxiBSBKVCguKcrMS1dIzs8rSczMAzGL83NTFYorc5Pyc4qtFJT0lBWBWE1fGQA) the same program with some code appended to call the function and then print the internal structure to standard output, proving that the output's in an unambiguous format.) Binary representation and explanation: ``` 76543210 Ṣ 1011011**1** Sort the characters of the input Z 010110**1**0 Transpose the list (it's 1D, so this effectively wraps it in a list) Ṣ 10110**1**11 Sort the list (a no-op, as it has only one element) Ṁ 1100**1**000 Take the largest (i.e. only) element Œ 000**1**0011 First byte of a two-byte command r 01**1**10010 Run-length encode ``` It can be seen that the second, third, and fourth characters cancel each other out and are only there to maintain the bit pattern we need. `Œr` is just too convenient, though, and padding the program so that we can use it probably gives us a shorter program than trying to solve the problem without the builtin would. ]
[Question] [ Good Evening Ladies and Gentleman. Tonight - we have a code challenge. A competition that will be defined not in the amount of points (a la Asteroids) but simply whether you can finish it (a la Zelda). And for the sake of comparison, the amount of bytes (uh... but you said...). Your challenge is to compose a single quine that compiles in both [WhiteSpace](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29) and any other language of your choice. Both quines must have absolutely identical output (which as a quine is absolutely identical to the source code). Your quine must be more then 3 bytes in length. Your score is the size of your source code in bytes. Given that this challenge involves WhiteSpace, please escape your answers so that they are clear - preferably in the C style. Your score is the original source in bytes - not the escaped version. Good luck. [Answer] ## Whitespace and Perl, ~~992~~ 975 characters Good Evening Ladies and Gentlemen. To start with, here is my submission encoded in base64, which I feel is the best way to communicate a large Whitespace program. (You really don't want to use an encoding that leaves any whitespace as-is, so there's no point in selecting something more "readable".) ``` c2F5PDwgeDI7c2F5PDwwLDAgIApzYXk8PCB4MjtzYXk8PDAsMCAgCgoJCQogICAJCSAgCSAgCSAJ CSAgCSAgCQkgCSAJIAkJCQkJICAJCSAJCQkgCQkJCQkgCSAJIAkJIAkgCSAgIAkJCQkJICAg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ICAgICAJCQoJIAkgIAogICAJCQoJICAKCgkJCiAK CgoJCjAK ``` Here's an excerpt that highlights all of the visible parts of the source. `⇥` is used to indicate a tab and `↲` to indicate a newline. ``` say<< x2;say<<0,0 ↲ say<< x2;say<<0,0 ↲ ↲ ⇥⇥↲ ⇥⇥ ⇥ [... etcetera ... skipping rest of a really long line ...]↲ ⇥⇥⇥ ⇥⇥[... etcetera ... shorter but still quite a long line ...]↲ ↲ ↲ ↲ ⇥ ⇥↲ [... etcetera ... whole lotta whitespace in here ...] ⇥⇥↲ ↲ ↲ ↲ ⇥↲ 0↲ ``` Perl was the natural choice for the second language in this challenge, being one of the best general-purpose languages for writing compact quines. My shortest Perl quine is 19 bytes: ``` say<< x2 say<< x2   ``` – and you can see how it was the seed for the Perl half of the double quine. My best Whitespace quine, in comparison, is 541 bytes long. (Though shorter ones do exist – 445 bytes is the best I've seen.) From the Perl interpreter's point of view, the first line of the double quine's source file contains the two statements that make up the entire program proper, as the remaining contents are two quoted strings. The first string is the repeated line of Perl, and is delimited by the blank third line. The second string is all whitespace, and runs from the fourth line of the source all the way to the `0` delimiter at the bottom of the file. When taken as a Whitespace program, the first four lines contain three instructions that are largely useless. (Their effect is to push two zero values onto the stack, and then discard the second one.) They're included just to get safely past the newlines that the Perl program requires – the real program starts after that. Rather than quote the unreadable source any further, here's a paraphrasing of the instructions that make up the Whitespace program, in an assembly-like format: ``` # Representation of "say<< ;say<<0,0 \n" in base 122 as ASCII chars. PERLCODE = 44892457841068708924520433691075560592081 # Represention of the whitespace program, following the "push PERLCODE" # instruction, in base 3 (see comments on wsout). WSCODE = 9823454421986355730445143846606456399449033186160554878002671428613111806443504867738858766142050504887335990409088441824104338753030405625930185 # Set up the stack and the heap. The first three instructions are not # particularly useful; they're just there to skip past the newlines in # the Perl code. (Though the initial zero on the stack does get used # at the very end.) push 0 push 0 jneg wsout push WSCODE push PERLCODE dup dup push 0 copy 1 # Output the first four lines of the file. perl: dup mod 122 putchar div 122 dup jnzero perl pop jzero perl push 68 # represents "jneg wsout" call wsout # Output the rest of the file. copy 1 call pushout push 2 call wsout call pushout call wsout putnum push 2 call wsout exit # pushout: Output a Whitespace push instruction, using the number on # the top of the stack as the instruction's argument. (Recursion is # used to output the bits MSB-first.) pushout: push 0 dup call wsout call wsout bits: dup jzero bitend dup mod 2 swap div 2 call bits bitend: call wsout ret # wsout: Output a sequence of whitespace characters as represented by # the number on the top of the stack. The number is read in base 3, # LSB-first, with 0 = SPC, 1 = TAB, 2 = NL. Calling wsout with a value # of zero will output a single space. wsout: dup mod 3 mul -23 # some ugly math that transforms mod -24 # (0, 1, 2) into (32, 9, 10) add 32 putchar div 3 dup jnzero wsout pop ret ``` The giant numbers at the top are what we Whitespace users have to use in lieu of actual strings. Don't bother trying to run this on a Whitespace interpreter that doesn't have proper bignum support. Finally, here's the program again, but this time with C-style escapes, since it was specifically requested: ``` say<< x2;say<<0,0 \nsay<< x2;say<<0,0 \n\n\t\t\n \t\t \t \t \t\t \t \t\t \t \t \t\t\t\t\t \t\t \t\t\t \t\t\t\t\t \t \t \t\t \t \t \t\t\t\t\t \t\t \t \t\t \t \t\t \t \t\t\t\t \t \t \t\t \t \t \t\t \t \t\t\t \t\t\t\t\t \t\t\t \t\t\t\t \t\t\t \t \t\t\t\t\t \t\t \t\t \t\t\t\t\t\t\t\t \t \t \t \t\t\t \t\t\t\t\t \t\t\t\t \t \t \t\t\t\t\t \t \t \t \t \t \t \t\t \t\t\t \t \t\t\t\t\t\t \t\t \t \t \t\t \t \t\t \t \t\t\t \t \t\t\t\t\t\t \t \t\t\t\t \t\t\t\t \t\t\t \t\t\t \t \t \t\t\t\t \t\t \t\t\t \t\t\t \t\t\t \t\t\t \t\t \t \t \t\t\t \t \t \t\t \t \t \t \t \t \t\t \t \t \t\t\t\t \t \t\t \t \t\t \t \t \t \t\t \t\t \t\t \t\t\t \t\t\t \t\t\t \t \t\n \t \t\t\t\t\t \t\t \t \t \t \t \t\t\t \t \t \t\t \t \t \t\t\t\t \t\t \t\t \t \t \t\t\t \t\t\t\t \t\t\t \t \t \t \t\t\t \t\t\t\t \t \t\t \t \t \t\t\t\t \t \t \t\t \t \t\n \n \n \n \t \t\n\n \t\n \n \t\t\t\t \t \n\t \t\t\t\n \t\t\t\t \t \n\t \t \n \t\t\n\t \n\n\t\t\t\n \n\n\n\t \t\n \t \t \n\n \t\n \t \t\n\n \t \n \t \n\n \t\n\n \t \n\n \t\n\t\n \t \t \n\n \t\n\n\n\n\n \n \n \n \n \t\n\n \t\n\n \n \n \n\t \n \n \t \n\t \t\t \n\t \t \n\t \t \n \t \n\n \n \n \t\t\n\t \t\t \t\t \t\t\t\n\t \n \t\t\t \n\t \t\t \t \n\t \t\n \t\t\n\t \t \n \t\t\n\t \n\n\t\t\n \n\n\n\t\n0\n ``` ]
[Question] [ Hashiwokakero ("build bridges" in Japanese) is a puzzle where you are tasked with connecting a group of islands with bridges. The rules are: 1. Bridges must run either vertically or horizontally between two islands. 2. Bridges may not cross each other. 3. A pair of islands may be connected by at most two parallel bridges. 4. Each island is marked with a number between 1 and 8, inclusive. The number of bridges connected to an island must match the number on that island. 5. The bridges must connect the islands into a single connected group. Your task is to write a program that will solve Hashiwokakero puzzles. You may assume that any given puzzle is solvable and that there is only one solution. The program should be reasonably efficient. For example, solving the 25x25 puzzle below shouldn't take more than 10 minutes on an average PC and it shouldn't use more than a gigabyte of memory. Solving smaller puzzles like the 7x7 one should take seconds. **Input:** The puzzle will be given as a 2D map of characters, with the digits `1` to `8` representing islands, and spaces representing water. The lines will be padded with spaces if necessary to make them all the same length. Islands will always be separated horizontally and vertically by at least one square of water so that there is room to place the potential bridge between them. There will always be at least two islands in a puzzle. Your program should preferably read the puzzle map from standard input, but you may specify an alternate input method if your programming language requires it. **Output:** The output should be like the input, except with spaces replaced by bridges as necessary. The bridges should be drawn using Unicode box drawing characters `─` (U+2500), `│` (U+2502), `═` (U+2550) and `║` (U+2551) to represent horizontal and vertical single and double bridges. If Unicode characters are a problem, you may use the ASCII characters `-`, `|`, `=` and `H` instead. **Winning criteria:** This is code golf. The shortest correct and reasonably efficient solution wins. **Examples:** Puzzle (7x7): ``` 2 2 1 1 4 3 3 2 4 3 2 3 1 3 4 2 ``` Solution: ``` 2─2──1 │1──4─3 3──2║ ║ │ │4 ║ │3─2║ 3 1║ ║ │ 3──4─2 ``` Puzzle (25x25): ``` 2 2 2 2 1 1 2 2 2 2 2 1 3 5 4 4 2 2 2 4 5 5 4 2 2 1 3 2 1 1 3 3 2 2 3 4 4 4 4 5 4 3 2 3 2 4 5 4 2 3 2 1 4 2 4 3 1 1 2 2 1 3 1 1 6 4 2 3 2 4 3 6 3 2 2 2 3 3 2 5 2 4 3 2 1 1 2 1 3 3 3 3 5 8 7 6 5 4 2 3 1 1 2 1 1 5 1 4 5 6 3 1 2 1 1 2 2 3 4 3 5 4 4 3 3 8 7 5 1 2 2 3 1 2 2 1 1 2 2 2 2 5 7 6 3 3 3 3 6 3 5 3 2 2 2 3 2 1 2 3 2 2 3 4 6 4 5 5 3 3 5 1 2 1 2 2 1 1 3 2 1 1 2 3 6 5 2 2 2 3 4 4 4 2 1 2 2 2 2 2 2 2 1 1 3 2 ``` Solution: ``` 2─2─2──2 1 1─2─2──2──2─2 │ │ │1─3═5══4══4─2│ 2 2─4─5══5═4═2│2──1 │ │3 │ 2│ ║1│ 1─3═3─2│ │ 2║ │ ║3═4│4══4─4═5─4─3──2 │3 2 4═5─4│ │ │ ║ │ │2───3│ │2─1║ ║4─2│ 4─3 │ 1│ 1 │2 2│1─3 ║║ │1 ║1──6══4 │ 2│ │3─2──4║ 3══6─3 ║ │ │ │2 2│2═3 │3──2 │ ║ 5─2│ 4─3│ │2─1│ │ │ │ ║ ║ │1 ║ │2 │ 1─3─3─3─3─5═8═7═6──5═4│ 2──3───1│1─2│ ║ │ ║ ││ 1 │ 1──5─1││ 4─5─6─3─1│2 1│ │1──2║ │2 │ ║ ║ │3═4│ │3─5═4 │4──3│ 3═8═7═5│1│2 2│ │ ║ 3│ 1│2──2║ │ ║1│1│ │2 │ ║ ║2 │2──2│5═7═6─3─3 3│ 3─6─3│ 5═3 │2│ ║2│2─3│ ║2 │ ║ │ ║ │ 1│2─3║2│ ║2 3│ 4═6──4─5─5──3─3─5││1║│ │2 │ │1 │ │2║2──1│ ║1││3│ 2│ │ 1│ │ 1║2│3══6═5─2││2 │2─3──4═4──4─2│ │ │1│ 2─2──2─2──2─2─2 1 1─3─2 ``` [Additional puzzles can be found here](http://www.menneske.no/hashi/eng/index.html). [Answer] ## Haskell, 1074 characters ``` main=interact$unlines.(\f@(l:_)->let a=(length l,length f)in head.filter(網(0,0)a).計(0,0)a$f).lines 橋=結"─═"数;結=zip;網 置@(右,下) 域@(幅,高) 地|下>=高=實|右>=幅=網(0,下+1)域 地|目 置 地`含`島 =折((&&).折((&&).not.(`含`島))實)實(潔 置 域 地)|實=網(右+1,下)域 地 導=[(種,動)|動<-[1,-1],種<-"─═│║"];潔 置 域 地=折(拡 置 域)(換 地 置 '0')導 拡 置 域(種,動)地|([地],置)<-続(行 置 種 動)域 種 動 種 地=潔 置 域 地|實=地 計 置@(右,下)域@(幅,高)地|下>=高=[地]|右>=幅=計(0,下+1)域 地|[価]<-目 置 地`価`島 =見込(価-環 置 域 地)>>=折(\種->(fst.続(行 置 種 1)域 種 1' '=<<))[地]>>=計(右+1,下)域 |實=計(右+1,下)域 地;見込 価|価<0=[]|価>4=[]|實=[[""],["─","│"],["─│","║","═"],["─║","═│"],["═║"]]!!価 続 置 域 種 動 空 地|存 置 域=建 置 域 種 動 空 地|實=([],置) 建 置 域 種 動 空 地|目 置 地`含`島=([地],置)|目 置 地==空=続(行 置 種 動)域 種 動 空(換 地 置 種) |實=([],置);存(右,下)(幅,高)|右>=0,幅>右,0<=下=高>下|實=not 實;環 置 域 地=折(環行 置 域 地)0導 環行 置 域 地(種,動)数|置<-行 置 種 動,存 置 域,事<-目 置 地,事==種,[価]<-事`価`(橋++桥)=数+価|實=数 行(右,下)種 数|種`含`橋=(右+数,下)|實=(右,下+数);目(右,下)地=地!!下!!右;島=結"12345678"数 換 地(右,下)事|(上に,線:下に)<-捌 下 地,(左,古:右)<-捌 右 線=上に++(左++(事:右)):下に 折=foldl.flip;捌 0覧=([],覧);捌 数(物:覧)|(一覧,他)<-捌(数-1)覧=(物:一覧,他);實=1>0;数=[1..] 価 _[]=[];価 事((物,数):覧)|事==物=[数]|實=価 事 覧;含 事 覧|[_]<-価 事 覧=實|實=1<0;桥=結"│║"数 ``` --- Originally, I had it even more purely Japanese by also implementing the primitive functions in terms of simple pattern matching and list combinations: ## Haskell, 1192 ``` main=interact$unlines.(\f@(l:_)->let a=(length l,length f)in head.filter(網(0,0)a).計(0,0)a$f).lines 橋=結合"─═"数;結合 []_=[];結合(事:覧)(物:一覧)=(事,物):結合 覧 一覧 網 置@(右,下) 域@(幅,高) 地|下>=高=實|右>=幅=網(0,下+1)域 地|目 置 地`含`島 =折る((&&).折る((&&).反対.(`含`島))實)實(潔 置 域 地)|實=網(右+1,下)域 地 導=[(種,動)|動<-[1,-1],種<-"─═│║"];潔 置 域 地=折る(拡 置 域)(換 地 置 '0')導 拡 置 域(種,動)地|([地],置)<-続(行 置 種 動)域 種 動 種 地=潔 置 域 地|實=地 計 置@(右,下)域@(幅,高)地|下>=高=[地]|右>=幅=計(0,下+1)域 地|[価]<-目 置 地`価`島 =見込(価-環 置 域 地)>>=折る(\種->(一.続(行 置 種 1)域 種 1' '=<<))[地]>>=計(右+1,下)域 |實=計(右+1,下)域 地;見込 価|価<0=[]|価>4=[]|實=[[""],["─","│"],["─│","║","═"],["─║","═│"],["═║"]]!!価 続 置 域 種 動 空 地|存 置 域=建 置 域 種 動 空 地|實=([],置) 建 置 域 種 動 空 地|目 置 地`含`島=([地],置)|目 置 地==空=続(行 置 種 動)域 種 動 空(換 地 置 種) |實=([],置);存(右,下)(幅,高)|右>=0,幅>右,0<=下=高>下|實=反対 實;環 置 域 地=折る(環行 置 域 地)0導 環行 置 域 地(種,動)数|置<-行 置 種 動,存 置 域,事<-目 置 地,事==種,[価]<-事`価`結 橋 桥=数+価|實=数 行(右,下)種 数|種`含`橋=(右+数,下)|實=(右,下+数);一(第,第二)=第;目(右,下)地=地!!下!!右;島=結合"12345678"数 換 地(右,下)事|(上に,線:下に)<-捌 下 地,(左,古:右)<-捌 右 線=結 上に(結 左(事:右):下に);変 関[]=[] 変 関(物:覧)=関 物:変 関 覧;折る 関 物[]=物;折る 関 物(事:覧)=折る 関(関 事 物)覧;捌 0覧=([],覧) 捌 数(物:覧)|(一覧,他)<-捌(数-1)覧=(物:一覧,他);實=1>0;反対 真|真=1<0|實=實;数=[1..];結=(++) 価 _[]=[];価 事((物,数):覧)|事==物=[数]|實=価 事 覧;含 事 覧|[_]<-価 事 覧=實|實=1<0;桥=結合"│║"数 ``` --- ``` $ make ; def0 +RTS -M1g < test-25x25.txt ghc -o bin/def0 golfed0.hs -rtsopts -O2 [1 of 1] Compiling Main ( golfed0.hs, golfed0.o ) Linking bin/def0 ... 2─2─2──2 1 1─2─2──2──2─2 │ │ │1─3═5══4══4─2│ 2 2─4─5══5═4═2│2──1 │ │3 │ 2│ ║1│ 1─3═3─2│ │ 2║ │ ║3═4│4══4─4═5─4─3──2 │3 ... ``` runs in ≈3 minutes on my *i5*. --- Commented version: ``` type Board = [[Char]] type Location = (Int,Int) type BoardDimensions = (Int,Int) main=interact$unlines.(\f@(l:_) ->let a=(length l,length f) -- dimensions of the field from the input in head.filter(網(0,0)a) -- ↙− determine all possible ways to build bridges {- ↑ -} .計(0,0)a $ f ).lines -- and use the first that is simply connected. -- islands, bridges 島=結合"12345678"数; 橋=結合"─═"数; 桥=結合"│║"数; 数=[1..] -- each with the associated "value" from the natural numbers _↗ -- plan & commit the building of bridges 計 :: Location -> BoardDimensions -> Board -> [Board] 計 置@(右,下) 域@(幅,高) 地 |下>=高=[地] -- Walk over the board until every location was visited. |右>=幅=計(0,下+1)域 地 |[価]<-目 置 地`価`島 -- When there is an island, read it's "value" 価 =見込(価-環 置 域 地) -- substract the value of the already-built bridges; fetch the ways to build bridges with the remaining value >>=折る(\種->(一.続(行 置 種 1)域 種 1' '=<<))[地] -- for each of these ways, try to build a bridge. >>=計(右+1,下)域 -- for every possibility where that was successful, go on with the resultant board. |實=計(右+1,下)域 地 -- Ways to build bridges with value 価: 見込 :: Int -> [[Char]] 見込 価 |価<0=[] -- not possible to build bridges with negative value |価>4=[] -- nor with value >4 (we're always building south- / eastwards) |實=[ [""] -- value 0 ,["─","│"] -- value 1 ,["─│","║","═"],["─║","═│"],["═║"]]!!価 -- ... and so on -- continue, if Location is on the board, with the building of a bridge of type 種 続 :: Location -> BoardDimensions -> Char -> Int -> Char -> Board -> ([Board],Location) 続 置 域 種 動 空 地 |存 置 域=建 置 域 種 動 空 地 |實=([],置) -- build that bridge, 建 :: Location -> BoardDimensions -> Char -> Int -> Char -> Board -> ([Board],Location) 建 置 域 種 動 空 地 |目 置 地`含`島=([地],置) -- but if we've reached an island we're done |目 置 地==空 -- if we're in water or what else (空, can also take on the value of 種 if we only want to check if the bridge is already there) =続(行 置 種 動)域 種 動 空(換 地 置 種) -- place (換) the bridge and go (行く) to the next location |實=([],置) -- if we've reached something else (i.e. crossing bridges), return no result. -- number of connections present at location 置 環 :: Location -> BoardDimensions -> Board -> Int 環 置 域 地=折る(環行 置 域 地)0導 -- for all neighbouring positions 環行 置 域 地(種,動)数 |置<-行 置 種 動,存 置 域 -- if they're on the board ,事<-目 置 地,事==種 -- and there's a bridge in the correct direction ,[価]<-事`価`結 橋 桥=数+価 -- check its value and sum it to the previous ones |實=数 -- if there's no bridge there, don't sum anything 導=[(種,動)|動<-[1,-1],種<-"─═│║"] -- directions to go -- -- -- -- -- -- -- -- -- -- -- -- -- test for connectedness: 網 :: Location -> BoardDimensions -> Board -> Bool 網 置@(右,下) 域@(幅,高) 地 -- Walk over the board until an island is |下>=高=實 -- found. 潔 marks all islands connected to |右>=幅=網(0,下+1)域 地 -- that island; then check if any unmarked |目 置 地`含`島=折る((&&).折る((&&).反対.(`含`島))實)實(潔 置 域 地) -- islands are left in the |實=網(右+1,下)域 地 -- result. -- mark islands connected to the one at 置: 潔 :: Location -> BoardDimensions -> Board -> Board 潔 置 域 地 =折る(拡 置 域)(換 地 置 '0')[(種,動)|動<-[1,-1],種<-"─═│║"] -- mark the island at 置 with '0', then, for all the possible ways to go... -- Proceed with the marking in some direction 拡 :: Location -> BoardDimensions -> (Char,Int) -> Board -> [[Char]] 拡 置 域(種,動)地 -- if an island is found in the given direction, give control to 潔 there |([地],置)<-続(行 置 種 動)域 種 動 種 地=潔 置 域 地 |實=地 -- if none is found (i.e. there was no bridge), just return the board without further marking -- -- -- -- -- -- -- -- -- -- -- -- -- Primitives: 存 :: Location -> BoardDimensions -> Bool 存(右,下)(幅,高)|右>=0,幅>右,0<=下=高>下|實=反対 實 -- check if (右,下) is on the board 行 :: Location -> Char->Int -> Location 行(右,下)種 数|種`含`橋=(右+数,下)|實=(右,下+数) -- go in some direction (determined by where 種 leads to) 目 :: Location -> Board -> Char 目(右,下)地=地!!下!!右 -- lookup what's at location (右,下) -- replace what's at (右,下) with 事 換 :: Board -> Location -> Char -> Board 換 地(右,下)事|(上に,線:下に)<-捌 下 地,(左,古:右)<-捌 右 線=結 上に(結 左(事:右):下に) 変 :: (a -> b) -> [a] -> [b] 変 関[]=[] -- Standard Haskell map function (just noticed I didn't actually use it at all) 変 関(物:覧)=関 物:変 関 覧 折る :: (b -> a -> a) -> a -> [b] -> a 折る 関 物[]=物 -- equivalent 折る=foldl.flip 折る 関 物(事:覧)=折る 関(関 事 物)覧 捌 0覧=([],覧) 捌 数(物:覧)|(一覧,他)<-捌(数-1)覧=(物:一覧,他) -- splitAt 實=1>0 --true 反対 真|真=1<0|實=實 -- not 結=(++) -- list linking 一(第,第二)=第 -- fst 価 :: Eq a => a -> [(a,b)] -> [b] 価 _[]=[] -- lookup function 価 事((物,数):覧)|事==物=[数]|實=価 事 覧 含 :: Eq a => a -> [(a,b)] -> Bool 含 事 覧|[_]<-価 事 覧=實|實=1<0 -- equivalent 含 x = elem x . map fst 結合 []_=[] -- zip 結合(事:覧)(物:一覧)=(事,物):結合 覧 一覧 ``` [Answer] ## Python, 1079 chars ``` import sys,re,copy A=sys.stdin.read() W=A.find('\n')+1 r=range V={} E=[] for i in r(len(A)): if'0'<A[i]<'9':V[i]=int(A[i]) for d in(1,W):m=re.match('[1-8]( +)[1-8]',A[i::d]);E+=[[i,i+len(m.group(1))*d+d,d,r(3)]]if m else[] def S(E): q,t=0,1 while q!=t: for e in E: if any(d[0]and e[3][0]==0and any(i in r(a+c,b,c)for i in r(e[0]+e[2],e[1],e[2]))for a,b,c,d in E):e[3]=[0] for i in V: m=sum(min(e[3])for e in E if i in e[:2]);n=sum(max(e[3])for e in E if i in e[:2]) if m>V[i]or n<V[i]:return for e in E: if m+2>V[i]and i in e[:2]:e[3]=e[3][:V[i]-m+1] if n-2<V[i]and i in e[:2]:e[3]=e[3][V[i]-n-1:] t=q;q=sum(len(e[3])for e in E) Q=[min(V)] i=0 while Q[i:]: x=Q[i];i+=1 for e in E: if x in e[:2]: if sum(e[3]): for y in e[:2]: if y not in Q:Q+=[y] if len(Q)!=len(V):return U=[e for e in E if e[3][1:]] if U: for w in U[0][3]:U[0][3]=[w];S(copy.deepcopy(E)) else: B=A for a,b,c,d in E: if d[0]: for i in r(a+c,b,c):B=B[:i]+[{1:'─',W:'│'},{1:'═',W:'║'}][d[0]-1][c]+B[i+1:] print(B) sys.exit(0) S(E) ``` The code does a pretty straightforward exhaustive search in `S`, using some constraint propagation to make it run in a reasonable time. `E` represents the current set of edges, in the format *[from,to,delta,possible weights]*. *from* and *to* are island identifiers and *delta* is either 1 for horizontal edges or *W* (=width of lines) for vertical edges. *possible weights* is a sublist of *[0,1,2]* encoding the current known state of that edge (0=no bridge, 1 = single bridge, 2 = double bridge). `S` does three things. First it propagates information, like if one edge no longer has a 0 weight as a possibility, then all edges that cross it are eliminated (their possible weights are set to [0]). Similarly, if the sum of the minimum weight for edges incident on an island equals the island's weight, then all of those edges are set to their minimum. Second, `S` checks that the graph is still connected using non [0] edges (the `Q` computation). Finally, `S` picks an edge that is still not fully determined and calls itself recursively, setting that edge to one of its remaining possibilities. Takes about 2 minutes for the biggest example. [Answer] ## C# - ~~6601~~ ~~5661~~ 2225 ``` using System;using System.Collections.Generic;using Google.OrTools.ConstraintSolver; using System.Linq;namespace A{class N{public int R,C,Q;public bool F;public N(int r, int c,int q){R=r;C=c;Q=q;}}class E{private static int i;public N A,B;public int I; public E(N a,N b){A=a;B=b;I=i++;}}class H{public void G(string i){var o=P(i);var g= new List<E>();foreach(var m in o){var r=o.Where(x=>x.R==m.R&&x.C>m.C).OrderBy(x=>x.C) .FirstOrDefault();if(r!=null){g.Add(new E(m,r));}var d=o.Where(x=>x.C==m.C&&x.R>m.R) .OrderBy(x=>x.R).FirstOrDefault();if(d!=null){g.Add(new E(m,d));}}var s=new Solver("H") ;int n=g.Count;var k=s.MakeIntVarArray(n,0,2);foreach(var j in o){var w=j;var y=g.Where (x=>x.A==w||x.B== w).Select(x=>k[x.I]).ToArray();s.Add(s.MakeSumEquality(y,j.Q));} foreach(var u in g.Where(x=>x.A.R==x.B.R)){var e=u;var v=g.Where(x=>x.A.R<e.A.R&&x.B.R >e.A.R&&x.A.C>e.A.C&&x.A.C< e.B.C);foreach (var f in v){s.Add(s.MakeEquality(k[e.I]*k[f. I],0));}}if(o.Count>2){foreach(var e in g.Where(x=>x.A.Q==2&&x.B.Q==2)){s.Add(k[e.I]<=1) ;}foreach(var e in g.Where(x=>x.A.Q==1&&x.B.Q==1)){s.Add(k[e.I]==0);}}var z=s.MakePhase (k,0,0);s.NewSearch(z);int c=0;while(s. NextSolution()){if(C(k,o,g)){N(k,o,g);Console.WriteLine();c++;}}Console.WriteLine(c);} bool C(IntVar[]t,List<N>d,List<E>g){var a=d[0];a.F=true;var s=new Stack<N>();s.Push(a); while(s.Any()){var n=s.Pop();foreach(var e in g.Where(x=>x.A==n||x.B==n)){var o=e.A==n? e.B:e.A;if(t[e.I].Value()>0&&!o.F){o.F=true;s.Push(o);}}}bool r=d.All(x=>x.F);foreach (var n in d){n.F=false;}return r;}void N(IntVar[]t,IList<N>n,List<E>e){var l=new List<char[]>();for(int i=0;i<=n.Max(x=>x.R);i++){l.Add(new string(' ',n.Max(x=>x.C)+1) .ToCharArray());}foreach(var o in n){l[o.R][o.C]=o.Q.ToString()[0];N d=o;foreach(var g in e.Where(x=>x.A==d)){var v=t[g.I].Value();if(v>0){char p;int c;if(g.B.R==o.R){p=v==1 ?'─':'═';c=o.C+1;var r=l[o.R];while(c<g.B.C){r[c]=p;c++;}}else{p=v==1?'│':'║';c=o.R+1; while(c<g.B.R){l[c][o.C]=p;c++;}}}}}foreach(var r in l){Console.WriteLine(new string(r)) ;}}List<N>P(string s){var n=new List<N>();int r=0;foreach(var l in s.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries)){for(int c=0;c<l.Length;c++){if(l[c]!=' ' ){n.Add(new N(r,c,l[c]-'0'));}}r++;}return n;}}} ``` Not particularly well-golfed. Uses constraint programming library from [google or-tools.](http://code.google.com/p/or-tools/) Builds constraints for total edge counts and to eliminate crossing bridges, but it is a bit harder to define constrains to ensure they are all connected. I did add logic to prune 2=2 and 1-1 components, but I still have to go through the final list (39 on the large one) and eliminate those which are not fully connected. Works pretty fast. Takes only a couple seconds on largest example. Ungolfed: ``` using System; using System.Collections.Generic; using Google.OrTools.ConstraintSolver; using System.Linq; namespace Hashi { public class Node { public int Row, Col, Req; public bool Flag; public Node(int r, int c, int q) { Row = r; Col = c; Req = q; } } public class Edge { private static int idx = 0; public Node A, B; public int Index; public Edge(Node a, Node b) { A = a; B = b; Index = idx++; } } public class HashiSolver { public void Go(string input) { IList<Node> nodes = Parse(input); var edges = new List<Edge>(); //add edges between nodes; foreach (var node in nodes) { var r = nodes.Where(x => x.Row == node.Row && x.Col > node.Col).OrderBy(x => x.Col).FirstOrDefault(); if (r != null) { edges.Add(new Edge(node, r)); } var d = nodes.Where(x => x.Col == node.Col && x.Row > node.Row).OrderBy(x => x.Row).FirstOrDefault(); if (d != null) { edges.Add(new Edge(node, d)); } } var solver = new Solver("Hashi"); int n = edges.Count; var toSolve = solver.MakeIntVarArray(n, 0, 2); //add total node edge total constraints foreach (var node in nodes) { var node1 = node; var toConsider = edges.Where(x => x.A == node1 || x.B == node1).Select(x => toSolve[x.Index]).ToArray(); solver.Add(solver.MakeSumEquality(toConsider, node.Req)); } //add crossing edge constraints foreach (var ed in edges.Where(x => x.A.Row == x.B.Row)) { var e = ed; var conflicts = edges.Where(x => x.A.Row < e.A.Row && x.B.Row > e.A.Row && x.A.Col > e.A.Col && x.A.Col < e.B.Col); foreach (var conflict in conflicts) { solver.Add(solver.MakeEquality(toSolve[e.Index] * toSolve[conflict.Index], 0)); } } if (nodes.Count > 2) { //remove 2=2 connections foreach (var e in edges.Where(x => x.A.Req == 2 && x.B.Req == 2)) { solver.Add(toSolve[e.Index] <= 1); } //remove 1-1 connections foreach (var e in edges.Where(x => x.A.Req == 1 && x.B.Req == 1)) { solver.Add(toSolve[e.Index] == 0); } } var db = solver.MakePhase(toSolve, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); int c = 0; while (solver.NextSolution()) { if (AllConnected(toSolve, nodes, edges)) { Print(toSolve, nodes, edges); Console.WriteLine(); c++; } } Console.WriteLine(c); } private bool AllConnected(IntVar[] toSolve, IList<Node> nodes, List<Edge> edges) { var start = nodes[0]; start.Flag = true; var s = new Stack<Node>(); s.Push(start); while (s.Any()) { var n = s.Pop(); foreach (var edge in edges.Where(x => x.A == n || x.B == n)) { var o = edge.A == n ? edge.B : edge.A; if (toSolve[edge.Index].Value() > 0 && !o.Flag) { o.Flag = true; s.Push(o); } } } bool r = nodes.All(x => x.Flag); foreach (var n in nodes) { n.Flag = false; } return r; } private void Print(IntVar[] toSolve, IList<Node> nodes, List<Edge> edges) { var l = new List<char[]>(); for (int i = 0; i <= nodes.Max(x => x.Row); i++) { l.Add(new string(' ', nodes.Max(x => x.Col) + 1).ToCharArray()); } foreach (var node in nodes) { l[node.Row][node.Col] = node.Req.ToString()[0]; Node node1 = node; foreach (var edge in edges.Where(x => x.A == node1)) { var v = toSolve[edge.Index].Value(); if (v > 0) { //horizontal if (edge.B.Row == node.Row) { char repl = v == 1 ? '─' : '═'; int col = node.Col + 1; var r = l[node.Row]; while (col < edge.B.Col) { r[col] = repl; col++; } } //vertical else { char repl = v == 1 ? '│' : '║'; int row = node.Row + 1; while (row < edge.B.Row) { l[row][node.Col] = repl; row++; } } } } } foreach (var r in l) { Console.WriteLine(new string(r)); } } private IList<Node> Parse(string s) { var n = new List<Node>(); int row = 0; foreach (var line in s.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { for (int col = 0; col < line.Length; col++) { if (line[col] != ' ') { n.Add(new Node(row, col, line[col] - '0')); } } row++; } return n; } } } ``` ]
[Question] [ Given a number N from 2 to 8, place any nonzero number of queens on a grid of any size so that every queen has exactly N queens (counting itself) in each of its row, column, and each diagonal. **This challenge has a significant [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") runtime limit.** Your code must finish all N from 2 to 8 (combined) within the 60-second timeout on [TIO](https://tio.run/#). This makes brute force unlikely to work. Some example outputs are below. You can use this [verification script](https://tio.run/##fVXfa@NGEH62/orBeYh8URTbzXGcqR9KoXAv0VEKfRDCbKSxvURaqbsrO@7Rvz2dmZVsJ4UKLO1@@83vmXV38vvWLN9u9t53bvXw4LwqX9oD2m3dHtOybR7Uw@Pnxy/zxXwZVbiFHfpNpdWuNap28c7qKgGLh/VvtMXZKgLQWwZWwGdrfuWr1f2ioJNKNwtYQ41GBGcBWl5B@bxg1KLvrdkwQod5XsC2tbABbeDVKrPDWFTdBfF7WMxYPXNse/zAEp/CYdnW7w@Xw@E7iznruGNykaquQ1PFI1zkjF48vBaLohv4vywuHj8vv379Mpcsuq7WflNr52Pt0arnGhM47tHi4NGZRKexKssEiNcMnPU1kx9KOR/Deh0IlxN@SHwMJBfnw4NUsP8Qc6rUSGaVF/oQMXGiq63Fqi8xHl0VN4dwqGzF7E03XWs9uJPjBP26x/KF3VWkyVp1gnYLi1sn5fmrRzSOjiqYDxA2nT9Bg@gd@D1SUUylvW6NkzRShvX2FIumBAxlZCLrDdbYoCGhNTj0seubgUQJmBHJOSSn3nMTmH4zB1VTz53F9eBmOj0LLc7gteQvEkzTOw97dUBQnnpa0a41GAIjFdHkBr6rCnzLgTiqPklz7@/8HrQDq3Y7rKJJo143hJLztIob1cW0S4JRcV@M0WCETqWhgU8Qj1L3Mk10NJtdj4QIFeQD7Tkvso8m1NB9Yxj4W3fxp2CDWDzjbpGAfHlE8/eTP@ScJn2wgge2kss9kMAftseCrdXaIGsXqzJVYu4uKF6Mi2U0oSI5CbnjeiUgkhTt0GlDHd0Mfl7DjzmV@x/pqNYcpJZXDZXehi7Kbqk05Js/ttBS@9ANsFdWlaFRDZXhWmo@SFE7SnN5uiZcrTxuWMrF/N4MYQuynqbZlHtu8DDPBU61qfBV6CE1vOLc8AVyXZGLwoIj@R2pNdiBzrYlutDw2nS9j8Yk5rxInbdUqqCbAdZF80V4pU1qSY3wiUGDxssiCm705kW4l8tHiNS@EsYTWaCsxEKUm/jcaQFarIpo0lniwFMyDt/HNIUOSuBp9nYDf1q6D@DU9twgrq95jFvwSIOhXEi9o3ixxAoreD6x3qOmacBXKlN9kvF5rhU5Pkb6jP5I4wSoyn3QVCqHKSXw25Ytgao5BadhDuG7/MUBh3vfbu/56z6UOxG5kpqhdyhpn4bgprDtTcn3DXUpeRk8IgaNtzY0vqpK35ZRmmVpGtEvG98BiX6KaMdLfghMecm/KBtXQTAsg3hYpVmUjnRWGL6p4GeY8cDPhD@gWcCzYPBf) to confirm your outputs. *N=2* ``` .OO. O..O O..O .OO. ``` *N=3* (by Christian Sievers) ``` ..OOO...... .O.O...O... OO...O..... O...O....O. O......O..O ..O...O..O. ..O..O....O .O...O..O.. .......OO.O ...O..O..O. ....O.O.O.. ``` *N=4* (by Christian Sievers) ``` ...OO..OO... ..OO....OO.. .O...OO...O. OO........OO O....OO....O ..O.O..O.O.. ..O.O..O.O.. O....OO....O OO........OO .O...OO...O. ..OO....OO.. ...OO..OO... ``` Your output grid can be square or rectangular. It may have empty rows and/or columns, even ones on the outside as a "margin" that makes the array bigger than necessary. You can output as a 2D array of two distinct values of your choice, or as a string that displays as such. For the 60-second time limit, running verification code doesn't have to happen within this time. If your language is not on TIO, you test it on any reasonable machine. On the off chance that your grids might be so big that TIO can't print them, it's allowed to run the test with storing all 7 grids instead of printing them, such as to a size-7 list where that any of them may be retrieved. [Answer] # Python 2, 141 138 bytes [Try it online!](https://tio.run/##lVXBkuI2ED2jr@jsHGyDYTBFdjNUfMimKqk97RxSuTguSoMFiLVlR5JZyNZ@@6RbsrGZyiUn5O7X3a/7tURztcdarV7ZA@zqRooC9rqu4Cy03Msdt7JWYHZaNpaxh6O1jdk8PhrLd19qxOzL@utiV1eP/HH94/rDMlmuWCH2cBB2W0h@qBUvTXjQsojhpbQaUvhDtyLaMIBCVvhZCuX8EVq4MUJb7xg82TInpxa21WpLFgzLshz2tQZbW16CVHDRXB1EuILpkBLmkEQ5xhJS119HuBvGUfGIXV3@ByLDwLyHAci9a2Qz5kMQmFF8vuBNI1ThI8ngw7tgURqxocM4mMrOwacIqXfH@i4R5XDZhkGMU6Ay8OtR7L4QO66Aa82vUO8hCYzr7O9WCGXQVcCyM4mqsVeohLAG7FEgeVVIUts4AZ3@19BlikFh@xN33opSVEJhUApG2NC0VQfKcEgI8hLeY2N490mdeYnK3cJlR3Px7haU3IzjyF9cM1VrLBz5WQC3KDDHr1oJ3ximYJMHeOYFrgM1YqSxGE2LcLBHkAY0PxxEwSYVv2zRiuTxFFa8IZljX9TRd8VwvbwcuHq4T2EfNXerha4oGq@UC8qRA37TXNw3m6BebaXI8I9swqmvgSi6FyaJwf2uqNj9belmrsW5qyLOVCX7DZ0idvcnp2qlVIKyu6pu@1y5mU@c9IcVm6BIxrXckF4xuEjsttukTkcTwc8pfFui3N8Zk1VToyayjs3VMGaFsdsdN76iv2oxPGE/tZYHicS3xhaSJov4hTvfuerWDj78YDcYmmW9@HjFEp8@h8FfKlicaqmcOsbqeCgdoURDhvs4ZCIuYucUGkVMgyB4ValUTWsR85xmq5@WOXNPB041S07xU7xenubrZfx@fZq9X@eb5/RbM5NT66Yvafa@YRWRoSHD83emU2/98LSKWKOlsll2mV2nyYn8LvbiYnM6Xv3xFekw1is39LLAFcAL0oowWpimlNbN4U23b8bJGN19ypOxSZYFtBgBlfEX3F0x3A1EI7lDnzYOorxf3s5FQKLUQ/IYMkSxCcHI0QMMw71zrULw5/gPQgvTltZsAj/Y2D3SGESLP4gRgyPcPaU@j427l8b/R9joVuB3wv6vjKqtMNPWMca/D169FJza3ATdRtGtzuQsyekhxN5DGc2CDQQ42QAH8xmC3EPy/K32/cWfJ5F/zKlwP78Uhq3NRiz8433KoziYz@cfRUnvhfEjRdiL0Fh75picZkmER8IhCXpV@9g0XXo2p3s27t8L6eCTP4b/kC6B1L@ZsF0yRuOhj86jPgbr678 "Python 2 – Try It Online") ``` n=input() P=[280] for t in[1j,9,40j-40,64j+64]:P={p+i*t for i in range(n)for p in P} r=range(792) print[[x+y*1jin P for x in r]for y in r] ``` Takes `n` as input and prints a list of lists of booleans. While the grids are generated within the 60 second time limit, they are larger than TIO's 128KiB limit, so they were simplified to be printable via TIO thanks to math junkie. I added in the verification script to the TIO link so it can also be verified within TIO. Here's my attempt at drawing my original solution for n=3. Hopefully this helps visualize it. Replace 57 with 40 and 408 with 64 for the current solution. [![hand_drawn_solution](https://i.stack.imgur.com/ohFQl.png)](https://i.stack.imgur.com/ohFQl.png) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~85~~ 77 bytes ``` ->n{j=n**3+n ((0...n*n).map{|i|((?.*n*n+?O)*9)[~i%n+i/n*n,j]}+[?.*j]*j)*n*$/} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOss2T0vLWDuPS0PDQE9PL08rT1MvN7GguiazRkPDXk8LKKBt76@pZakZXZepmqedqQ8U0cmKrdWOBspmxWplaQLVqOjX/jfSKy0oydew0Kyuya0pKC0pVkiLzo2t/Q8A "Ruby – Try It Online") Similar to and inspired by cardboard\_box's answer, but rotated by 45 degrees. Below are the first 16 lines of the output for `n=4`. It should be apparent that that within each 16x16 box, the queens form diagonal lines of 4. In between the boxes there is a single blank column. If this was not there, the diagonal lines of each `n**2` x `n**2` box would line up exactly with its neighbour when `n` is even. There are clearly 4 queens on each horizontal row and 1 queen in each vertical column (except the blank ones.) The rest of the pattern is a repeat of the below, interspersed with `n**3+n` rows of blanks to ensure the diagonals do not clash (I could get away with just a few rows less, but the code is shorter this way.) The output is truncated by TIO so it's only possible to get full output up to 5, but it's apparent from the way the pattern is constructed that it meets the rules. Output has been verified up to 5. ``` .............O................O................O................O... ..............O................O................O................O.. ...............O................O................O................O. ................O................O................O................O .........O................O................O................O....... ..........O................O................O................O...... ...........O................O................O................O..... ............O................O................O................O.... .....O................O................O................O........... ......O................O................O................O.......... .......O................O................O................O......... ........O................O................O................O........ .O................O................O................O............... ..O................O................O................O.............. ...O................O................O................O............. ....O................O................O................O............ ...many blank rows, then repeat the above a total of 4 times... ``` ]
[Question] [ You are given a square matrix of width \$\ge2\$, containing square numbers \$\ge1\$. Your task is to make all square numbers 'explode' until all of them have disappeared. You must print or return the final matrix. More specifically: 1. Look for the highest square \$x^2\$ in the matrix. 2. Look for its smallest adjacent neighbor \$n\$ (either horizontally or vertically and without wrapping around). 3. Replace \$x^2\$ with \$x\$ and replace \$n\$ with \$n\times x\$. Repeat the process from step 1 until there's no square anymore in the matrix. ### Example Input matrix: $$\begin{pmatrix} 625 & 36\\ 196 & 324 \end{pmatrix}$$ The highest square \$625\$ explodes into two parts of \$\sqrt{625}=25\$ and merges with its smallest neighbor \$36\$, which becomes \$36\times 25=900\$: $$\begin{pmatrix} 25 & 900\\ 196 & 324 \end{pmatrix}$$ The highest square \$900\$ explodes and merges with its smallest neighbor \$25\$: $$\begin{pmatrix} 750 & 30\\ 196 & 324 \end{pmatrix}$$ The highest square \$324\$ explodes and merges with its smallest neighbor \$30\$: $$\begin{pmatrix} 750 & 540\\ 196 & 18 \end{pmatrix}$$ The only remaining square \$196\$ explodes and merges with its smallest neighbor \$18\$: $$\begin{pmatrix} 750 & 540\\ 14 & 252 \end{pmatrix}$$ There's no square anymore, so we're done. ### Rules * The input matrix is **guaranteed** to have the following properties: + at each step, the highest square will always be unique + at each step, the smallest neighbor of the highest square will always be unique + the sequence will not repeat forever * The initial matrix may contain \$1\$'s, but you do not have to worry about making \$1\$ explode, as it will never be the highest or the only remaining square. * I/O can be processed in any reasonable format * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ### Test cases ``` Input : [[16,9],[4,25]] Output: [[24,6],[20,5]] Input : [[9,4],[1,25]] Output: [[3,12],[5,5]] Input : [[625,36],[196,324]] Output: [[750,540],[14,252]] Input : [[1,9,49],[1,4,1],[36,25,1]] Output: [[3,6,7],[6,2,7],[6,5,5]] Input : [[81,4,64],[16,361,64],[169,289,400]] Output: [[3,5472,8],[624,323,1280],[13,17,20]] Input : [[36,100,1],[49,144,256],[25,49,81]] Output: [[6,80,2],[42,120,192],[175,21,189]] Input : [[256,169,9,225],[36,121,144,81],[9,121,9,36],[400,361,100,9]] Output: [[384,13,135,15],[24,1573,108,54],[180,11,108,6],[380,209,10,90]] Input : [[9,361,784,144,484],[121,441,625,49,25],[256,100,36,81,529],[49,4,64,324,16],[25,1,841,196,9]] Output: [[171,19,700,4032,22],[11,210,525,7,550],[176,60,6,63,23],[140,112,1152,162,368],[5,29,29,14,126]] ``` [Answer] # [R](https://www.r-project.org/), ~~301~~ ~~287~~ ~~277~~ ~~274~~ ~~222~~ ~~217~~ ~~195~~ ~~186~~ ~~178~~ 174 bytes Nothing particularly creative, including the zero buffering of the peripheral elements of the entry matrix, [an earlier version](https://tio.run/##JY3RasMwDEXf/RXZQ0BulFK3adno9CXGg86h1AFroUmJna3fninbwxWcy@HqvvS0XB/sx/DFkPS3mmi6BX/bxks6t@Q/A7eKaXhESD9Gf2yPavg34CUJlaXRKlxhFQYRZKHI1ML8XsuCLFYGRxDGhLPWElUEmiBvchm4THZw0jDVHgxytReIFCoPjDULdBTtBHW20WmnipmyDe7vyPNztt0KndvMqkjUQ7aMziI7/VTpufQQL@M9JPBwOKHZ7dBg84amaXB/PElWejUaD1ovvw) later improved by Robin: ``` function(x){w=which.max if(any(s<-!x^.5%%1)){ y=cbind(NA,rbind(NA,x,NA),NA) z=y[i]=y[i<-w(y*y%in%x[s])]^.5 m=i+c(r<--c(1,nrow(y)),-r) y[j]=y[j<-m[w(-y[m])]]*z x=p(y[r,r])} x} ``` [Try it on-line](https://tio.run/##NYxBCoMwFET3OUW7EP63iaCtQsEsegEvEFKwKWKEpJK2mCiePdVFYWaYxbxxceSx@1r10S8LHpeJT71WfWZaT3QHrQ3wrtnR37MySXLEhQSuHto@oblR9y@eNjfcTWYehJZ71GyCkIZE28SLt0S5XRDD9UmBqxlTkFPrXtsGkTKHJIhh54aaGTEBC8JsjExn4vkIQTjqJK7Er3EE036c9qCgKkqaXyt63lRckB4KxPgD) Using a sequence of numbers as its entry, and hence removing the call to a function, Nick Kennedy earlier managed [a 186 bytes version](https://tio.run/##FU5basMwELyK@mHYTawQJXZIKu8BegahEtd5WHG0kNhgiVJf3ZVhZ2AeDPue55HG1jXtxtdBn6czNT@OLzpQ39QMqFP4vELNEfpKfoTvTZllCvE3EnT0xTecBugmXw9vFyDkXMnnle9DCwFTF6cunXY0QlzFzHEWTG9Re3LrBqTKJTDxeoe5yhl1NA9LiSrpzQgyGm/R2hVE4xbf2WUy/RbNq5L7T04DL/unw7w/CLXdCiWKk1BFIXblIWFRRzX/Aw) of the algorithm as follows (with [-10 bytes by Robin](https://tio.run/##FU5LCsIwFLxKXBTes40YrUVJs/ACXiBEWqPYSJNFWmiC2KvXdDED82EYvyyTmDqju51tA2/mRuiHcU8exKBbB8hT2L@gdRGGmm7CfXfKMob4jeJ2nUdIZNvRmwChcDXtX@49dhAw9XC@XVdwIyaI25gZlwU5KORWmFyDrynVwAqXH7CgHnmUHyUS1dTKCWiUVqFSW4jSrL5R62h6FqUvvPrxsBwrwvZ7wkh5IawsyeFUJazqzJY/)): ``` w=which.max;`~`=cbind;x=scan();while(any(s<-!x^.5%%1)){y=NA~t(NA~matrix(x,n<-length(x)^.5)~NA)~NA;i=w(y*y%in%x[s]);=i+c(r<--c(1,n+2),-r);y[j]=y[j<-m[w(-y[m])]]*(y[i]=y[i]^.5);x=y[r,r]};x ``` avoiding the definition of a (recursive) function, plus other nice gains. [Try it on-line](https://tio.run/##FU5LCsIwFLxKXBTes40YrUVJs/ACXiBEWqPYSJNFWmiC2KvXdDED82EYvyyTmDqju51tA2/mRuiHcU8exKBbB8hT2L@gdRGGmm7CfXfKMob4jeJ2nUdIZNvRmwChcDXtX@49dhAw9XC@XVdwIyaI25gZlwU5KORWmFyDrynVwAqXH7CgHnmUHyUS1dTKCWiUVqFSW4jSrL5R62h6FqUvvPrxsBwrwvZ7wkh5IawsyeFUJazqzJY/) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~140~~ 135 bytes Takes a flat list as input, outputs a flat list. ``` ->m{i=1;(i=m.index m.reject{|e|e**0.5%1>0}.max m[i+[1,-1,l=m.size**0.5,-l].min_by{|j|i+j>=0&&m[i+j]||m.max}]*=m[i]**=0.5if i)while i;m} ``` [Try it online!](https://tio.run/##JY7dbsIwDEbv@xTZxRAUEzUl7dqh8CJVhPhxN1dJiyBsMMqzdy74zuc7n@zTZXcbajMs1v5ORq2mZLyk9oBX4eUJG9yHe489xnEis3e1Th7Sb6@Rr2heKVgocOyf6e8lwMJZ6and7G73vulp3qxNMpmMdmP73o/dh40NAxvHhhtUC5r9fpNDQSv/GKg9XoIwAn@2TnxhOEfdc6@rZyJrtw0BWxs5bBm/4Hh/BDKQx7M4dJHgOYpuzBzt8W2agGBhxg8cp5PP0G1oFmF7GKqqhGWu4KPQoLQGXWgLlUoVaK0gTzPQJaQZszTLQSUJ21AoyNKSGWcacg3LlNv5UwIFBTdVmUNp7T8 "Ruby – Try It Online") Explanation: ``` ->m{ # Anonymous lambda i=1; # Initialize i for the while loop ( # Start while loop i=m.index # Get index at... m.reject{|e| } # Get all elements of m, except the ones with... e**0.5%1>0 # a square root with a fractional component .max # Get the largest of these m[i+ # Get item at... [1,-1,l=m.size**0.5,-l] # Get possible neighbors (up, down, left, right) .min_by{|j|i+j>=0&&m[i+j]|| # Find the one with the minimum value at neighbor m.max} # If out of range, return matrix max so # neighbor isn't chosen ] *=m[i]**=0.5 # Max square becomes its square root, then multiply # min neighbor by it )while i # End while loop. Terminate when index is nil. m} # Return matrix. ``` [Answer] # [Python 2](https://docs.python.org/2/), 188 bytes ``` M=input() l=int(len(M)**.5) try: while 1:m=M.index(max(i**.5%1or i for i in M));_,n=min((M[m+i],m+i)for i in m/l*[-l]+-~m%l*[1]+[l][:m/l<l-1]+m%l*[-1]);M[m]**=.5;M[n]*=M[m] except:print M ``` [Try it online!](https://tio.run/##PU5LbsMgEN37FGwiAcZuIJjaTn0EToBQVTVUQQJiWURxNr26OzhSF/Pmzfsg5me@3pLYNj35NN8zJlUAlnFwCWtCaduRKi/PsUKPqw8O8TFOuvXp4lYcv1bsS@TAbwvy6GdHn5Am5PzJ0hR9wlibWHvLAMh/IL4Fappg6@Y3HoByW5tgzQj6R2jg2lUg5Ax1S@nUdsCSpVO5K7d@uzmP8wJfRXrbzMDQSXGG3nvJEJcAcmcCNCkBlOiAQaxs0SnwjsdSYqgHuxPDy4aSgjmJ0lavOPh9eYMPIAz2Dw "Python 2 – Try It Online") Full program. Takes input and prints as a flat list. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 236 bytes ``` {my@k=.flat;my \n=$_;loop {my (\i,\j)=@k>>.sqrt.grep({$_+|0==$_},:kv).rotor(2).max(*[1]);last if 0>i;$/=((0,1),(0,-1),(1,0),(-1,0)).map({$!=i+n*.[0]+.[1];+$!,n>.[0]+i/n&.[1]+i%n>=0??@k[$!]!!Inf}).min(*[1]);@k[i,$0]=j,j*$1};@k.rotor(+n)} ``` [Try it online!](https://tio.run/##RY7LboMwEEX3/QojuZENjmNDQE0tE7b9hoAiFqEyD0MBVUUp307HUaRuZubcO6/hNrbJ1i1oV@nt3i1Zo3nVlrMCKbcaX1Xb9wMCB5HcsLymOmvSlE9f48w/x9tA7vga/AoNrSt7b74pH/u5H0lIeVf@EP8iC6racpqRqZBIjcIHTYhgkjKIe5ckExD3Lrkht9LTJrA@v4gi4LBBBdhjNn2wOdid0wLzalMtzuesuWCv8LwPW60wb@zzKOiGYVHomtU@lisIz98CS9dNvUzlgipESBLGDEUJZYjIUwJleKT0347fIvDDGBwZxq7LcQQkxIPAODJ0AqJq@wM "Perl 6 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~49~~ 48 bytes ``` `ttX^tt1\~*X>X>XJt?wy=(tt5M1Y6Z+*tXzX<=*Jq*+w}** ``` [Try it online!](https://tio.run/##FYu7CgIxEEV/5ZYy2@zMTsaEuNov2Mcn2mshDCwK@usxy@VU95zn3R@13tzL1Z3PPyrbtsl383tcuYc9H@zYkZdP2Yw0vaibv0S1nhIGY6yjglWhUTNYGKoMkwBNkJAbBu775iIygqS8PApTDNJSWxQwYss4GdLlDw) Or [verify all test cases](https://tio.run/##LU89bwIxDN37K7yBAkjnnOMmOmiXTkjdOqTAVXQvA1IkoFL716/Ppsri57wvnz7b13Scjq3Vj9b48BvqE962PV9um3lr6ZXfdbcIrX7X9SZsz2Fx@QlhGsfZajWrL7vr27RnpTKQUEzjw76QDMT3WWNa9gpYdNlHwYYJ/8UIQjz0Ch4x9tkWakqlXvl/LBQz@F0HBrjcdRBBTyyWBmfIAbNZALsEopgGMn5kZ2aIiqNCVgeGHmJ@xSsbeszibMmWDbIIetwDzND9XQlDSrF4E2tNuA3R3oYpQ4aD4fwH). ### How it works ``` ` % Do...while tt % Duplicate twice. Takes a matrix as input (implicit) the first time X^ % Square root of each matrix entry tt % Duplicate twice 1\~ % Modulo 1, negate. Gives true for integer numbers, false otherwise * % Multiply, element-wise. This changes non-integers into zero X>X> % Maximum of matrix. Gives maximum integer square root, or zero XJ % Copy into clipboard J t % Duplicate ? % If non-zero wy % Swap, duplicate from below. Moves the true-false matrix to top = % Equals, element-wise. This gives a matrix which is true at the % position of the maximum that was previously identified, and % false otherwise ( % Write the largest integer square root into that position tt % Duplicate twice 5M % Push again the matrix which is true for the position of maximum 1Y6 % Push matrix [0 1 0; 1 0 1; 0 1 0] (von Neumann neighbourhood) Z+ % 2D convolution, keeping size. Gives a matrix which is 1 for the % neighbours of the value that was replaced by its square root * % Multiply. This replaces the value 1 by the actual values of % the neighbours t % Duplicate XzX< % Minimum of non-zero entries = % Equals, element-wise. This gives a matrix which is true at the % position of the maximum neighbour, and zero otherwise * % Multiply, element-wise. This gives a matrix which contains the % maximum neighbour, and has all other entries equal to zero J % Push the maximum integer root, which was previously stored q % Subtract 1 * % Multiply element-wise. This gives a matrix which contains the % maximum neighbour times (maximum integer root minus 1) + % Add. This replaces the maximum neighbour by the desired value, % that is, the previously found maximum integer square root % times the neighbour value w % Swap } % Else. This means there was no integer square root, so no more % iterations are neeeded ** % Multiply element-wise twice. Right before this the top of the % stack contains a zero. Below there are the latest matrix with % square roots and two copies of the latest matrix of integers, % one of which needs to be displayed as final result. The two % multiplications leave the stack containing a matrix of zeros % and the final result below % End (implicit). The top of the stack is consumed. It may be a % positive number, which is truthy, or a matrix of zeros, which is % falsy. If truthy a new iteration is run. If falsy the loop exits % Display (implicit) ``` [Answer] # JavaScript (ES6), ~~271~~ ~~259~~ ~~250~~ 245 bytes ``` m=>{for(l=m.length;I=J=Q=-1;){for(i=0;i<l;i++)for(j=0;j<l;j++)!((q=m[i][j]**.5)%1)&&q>Q&&(I=i,J=j,Q=q);if(I<0)break;d=[[I-1,J],[I+1,J],[I,J-1],[I,J+1]];D=d.map(([x,y])=>(m[x]||0)[y]||1/0);[x,y]=d[D.indexOf(Math.min(...D))];m[x][y]*=Q;m[I][J]=Q}} ``` Thanks to [Luis felipe De jesus Munoz](https://codegolf.stackexchange.com/users/78039/luis-felipe-de-jesus-munoz) for −14 bytes! Explanation: ``` m => { // m = input matrix // l = side length of square matrix // I, J = i, j of largest square in matrix (initialized to -1 every iteration) // Q = square root of largest square in matrix for (l = m.length; (I = J = Q = -1); ) { // for each row, for (i = 0; i < l; i++) // for each column, for (j = 0; j < l; j++) // if sqrt of m[i][j] (assigned to q) has no decimal part, // (i.e. if m[i][j] is a perfect square and q is its square root,) !((q = m[i][j] ** 0.5) % 1) && // and if this q is greater than any previously seen q this iteration, q > Q && // assign this element to be the largest square in matrix. ((I = i), (J = j), (Q = q)); // if we did not find a largest square in matrix, break loop. if (I < 0) break; // d = [i, j] pairs for each neighbor of largest square in matrix d = [[I - 1, J], [I + 1, J], [I, J - 1], [I, J + 1]]; // D = value for each neighbor in d, or Infinity if value does not exist D = d.map(([x, y]) => (m[x] || 0)[y] || 1 / 0); // x = i, y = j of smallest adjacent neighbor of largest square [x, y] = d[D.indexOf(Math.min(...D))]; // multiply smallest adjacent neighbor by square root of largest square m[x][y] *= Q; // set largest square to its square root m[I][J] = Q; } // repeat until no remaining squares in matrix // no return necessary; input matrix is modified. }; ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 220 bytes ``` n=>l=>{for(int g;n.Any(x=>Math.Sqrt(x)%1==0);n[n.Select((a,b)=>(x:Math.Abs(b/l-g/l)+Math.Abs(b%l-g%l)==1?a:1<<30,y:b)).OrderBy(x=>x).First().y]*=n[g])n[g=n.IndexOf(n.Max(x=>Math.Sqrt(x)%1==0?x:0))]=(int)Math.Sqrt(n[g]);} ``` [Try it online!](https://tio.run/##bVJRb5swEH7nV3hIlezVdXFCGYSYKpvUqVOrVk2lPSAeSOqkaMgwQ1aSKL89O5tmmaK@mLvv7vvuu0vmzcW8KfY3KzUf3xVNOy5Um9DJvC0qZeNkIfZKJKVItotKY4DQMlZsota4E8l93r6y6W/d4o6ccSE8EqtUsaks5bzFOKczIhLcjWzfZNbg2WV5sbwsyfkROQPkrCRC8Ot8xMfjoUfXoxkh7EG/SP3VzukIuyl002LC1tlnodJlRuARit2qF9k9LLBi93n3oaXrbuQRkgnjnRyrViPe7WPn7bUoJb5V7FHKX5igTwJdcIK2DkJ/co02SKAnmb/cFUpiEgP6UxettKl7q@pVi0Zo6@1cija2jA2rpuYtCZCnrS7U8rmaaJ2vcd@zwDXB5anaw6oFuYOam7rnjeWyH1WhsEtdWp/cVsm3LUQ7wr7ralW/X4vBmcmhE4CPlLpDfSmSJcsJOXcz9/2NHWfnOPj4h0DmdieL9IJQAcv9tWwo7MueZF3mc9gphWEuOeaZzeP/jtsTpnVZtMbZP@Mwkz3mupGEPVfGS399LduVVghvKDr5STfsW7UCBNp2@zTlAY0ymvp0cJVlTppG1IeUH9JgcEWHgUGigA4HvgU5ha7ItvmUw3cYQD9EphgaMLAiwAj4IY7oIASa59kuYHDPs2Q/otw3880YkIE87KUAooYIVLBjx/ABt92hYUY2jXqDoGzHGdnofRWTfwl9y/BD6wMIvg@m@kFW1o6xbJClV4OoN2W2MCuDhd4YpyEwzSFA/y8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 224 bytes ``` (l=#;While[(c=Length)[m=Select[Join@@l,IntegerQ[Sqrt@#]&]]>0,t=##&@@#&@@SortBy[Select[(g=#&@@Position[l,f=Max@m])+#&/@{{1,0},{0,1},{-1,0},{0,-1}},Min@#>0&&Max@#<=c@l&],l[[##]]&@@#&];l[[##&@@g]]=(n=Sqrt@f);l[[t]]=l[[t]]n];l)& ``` [Try it online!](https://tio.run/##NY5Ba8QgEIX/SkGQhM5SdY1N2LpIby1d2JLDHsRDCK4bMIamHlpCfntq0vYwM8437/Hsm3izfRO7tlmcXDIv0eFy67zVWSvfbHDxlute1tbbNurXoQtKeXgJ0To7vuv6Y4wKGWzMkUCUCGGl1qqHMT5/6z9b5uQKz8NnF7shaA9XeWq@VG/ye4Qf1DRRIDNMBGjqu/9lR@cZTikRHQnGqwE9yVZ5bMBrjZAxW5o5bFt6O2NkFuT2qWu@4pjI7whJluPlPHYh3imnp6mCvaDwWHKgnAMveQqljALnFAQrgFfAisRYIYASktRQUihYlVi6cRAc9iy5xSYCCmVy0kpANc9mWX4A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 157 bytes ``` a=>g=(l,m=n=i=j=0)=>a.map((o,k)=>m>o||o**.5%1||[m=o,i=k])|m&&a.map((o,k)=>n*n<o*n|((i/l|0)-(k/l|0))**2+(i%l-k%l)**2-1||[n=o,j=k])|[a[i]=m**=.5,a[j]=m*n]|g(l) ``` [Try it online!](https://tio.run/##VVDLboMwELznK7gkselCMTEulur8Qb8AoQilhAJ@RA3qyf9O166iJifvzs7Mznrqfrrb@Xu8Lpl1n/16UWunjoMiGoyyalSTKqg6drnproQ4mLExR@e9S9O82jLvG6McjGpuqTe73RPRpvbdpdYTMr5qX9CMzPGlaVq@kHGrs3mrQ5MFH4s@U/RpumZslUlTlVfQNVOobesHoum69LclUYlJ1DEhOlS57u2wfEHAsLvobvnADKfAOFFILsRQVEJydvbmdJ9rNxCTT260ZA/JnlK62QRb0jRMgGyh4VBWbUvvqASOIHsGRVnBQQRcCjiU/GHEABUySjgwfA8CtVj9U@owEtEW1YLdawlljeKieOCWlYAwwRkmiG6sZMA4hzq4y9jKvzQojX4MX/l0Q0Dfah51vI7rUMY57sZwXEI0j8uiB5pDVcbvkDFsuBKDRBIwqFEZbg9b1l8 "JavaScript (Node.js) – Try It Online") -14 bytes thanks the @Arnauld who also wrote a nice test harness :) Anonymous function that takes a 1-dimensional array as input and a length parameter specifying number if columns/rows. Curried input is specified as `f(array)(length)`. ``` // a: 1-dimensional array of values // g: recursive function that explodes once per recursive call // l: number of columns, user specified // m: max square value // n: min neighbor // i: index of max square // j: index of min neighbor a=>g=(l,m=n=i=j=0)=> // use .map() to iterate and find largest square a.map((o,k)=> // check size of element m>o|| // check if element is a square o**.5%1|| // new max square found, update local variables [m=o,i=k])| // after first .map() is complete, continue iff a square is found // run .map() again to find smallest neighbor m&&a.map((o,k)=> // check size of element n*n<o*n| // check relative position of element ((i/l|0)-(k/l|0))**2+(i%l-k%l)**2-1|| // a new smallest neighbor found, update local variables [n=o,j=k])| // update matrix in-place, largest square is reduced, // smallest neighbor is increased [a[i]=m**=.5,a[j]=m*n]| // make recursive call to explode again g(l) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~70~~ 67 bytes ``` ’dL½$}©+Ø.,U$;N$¤%®‘¤<®Ạ$Ƈæ.®‘ịÐṂḢ;ḷ;€ị½¥×÷ƭ⁹Ḣ¤¦Ṫ}¥ƒ ׯ²$MḢçɗ⁸Ẹ?ƊÐL ``` [Try it online!](https://tio.run/##PZCxS8NAFMb3/B1x8lFy6TXmiOBml@rmICGbLtJZECwkHSzoUlxaQUWkrSjaoUObVLq8g4B/xt0/Et9drFPuffd@3/ddLs673auq0unDWQc3bg/fd@W4ASdudOziZAfnOh3jZB/nav3ilgM5a1hJfd/JoSr6Kn@NVL6KdP@TJNzgVI7kqvzSWUFXOMGZKj56OC3vHbq4wYV7RLp8@xnpLFfr/KC8lcNO1Y50@ojLa1xe4lKnT9GhHKj8WRVZuWi7jhyQv8nQ2eq0qmInjlkAIoGYg99KEiBBAKeZ/c@B34JmYCQRQNPntcqA9oRd5MDo2wyIoJO9DY0aWB9iArY9C/BD4jyvXiOGeZ7FuQDGTQmTREY0h39mpIFBCaZONon5zK6HBhV2FHVJ8raBxldsH2SEvZBbhIe2ChGcU686yvraHIuTL7R8UdcyDzHvpg51NQYhkeZvUICT/AI "Jelly – Try It Online") I’m sure this can be done much more briefly, but I found this harder than it first appeared. Explanation to follow once I’ve tried to golf it better. A full program that takes a list of integers corresponding to the square matrix and returns a list of integers representing the final exploded matrix.l [Answer] # Java 8, ~~299~~ ~~297~~ ~~289~~ 279 bytes ``` m->{for(int l=m.length,i,j,I,J,d,M,t,x,y;;m[x][y]*=d){for(i=l*l,I=J=d=0;i-->0;)d=Math.sqrt(t=m[i/l][i%l])%1==0&t>d*d?(int)Math.sqrt(m[I=i/l][J=i%l]):d;if(d<1)break;for(M=-1>>>1,m[x=I][y=J]=d,t=4;t-->0;)try{M=m[i=I+t/2-t/3*2][j=t<1?J-1:1/t+J]<M?m[x=i][y=j]:M;}finally{continue;}}} ``` -18 bytes thanks to *@ceilingcat*. Modifies the input-matrix instead of returning a new one to save bytes. [Try it online.](https://tio.run/##hVRRb6JAEH7vr9iY9AK6KIuUE@naZ03oXdJHwsNWsF0L6OHo1RB@uzeLWpuebE0QWGa@75tvZncpdsJaJm@HeSY2GxIKWVQ3hMgC0nIh5il5VK@E7FYyIXMD16M4ikluBrhc3@DfBgTIOXkkBeHkkFuTarEqVSDJeN7P0uIFXqmkSzqlM5rQkAJ9p/sgyKP3ONrHXZ6YxwyedTM65TOecDuQljWxAzPhoYDX/uZPCQbwPJKDLI7kbRabt4xz@wdMkm7yoNjMS2AeTXkTOONN6DgJ5MJI7pn5XKbiLVBsIbfYZDJhFGXwKQrhs5gnFLgbwJEayn0VKko@7cHAsWAw7DpxtORwzx5mFhuzAfRm8X34oCCkgljG4zCoF7IQWbav5qsCZLFNg7quD4Gyar19ztCqk2ONpTkabjxBKYsXtFWYR7ch3YBRpH/Jye@qYh4lfk2br//9KuJS566um6ZcyyY@JW57NtNne84dJUOvNZ/5Hh06ro6foXrq@joJWANhrQFDjyoVTEcyQhCF4ulKRake08Ywz6fOCOXato4NFTHbRkamaYtPmat6024eUWVhHKrXsCECVboI2uhgs1rRlCqHNawKsTUOcVScuutaix40fh0r9XV@IJKK/DlyG3Z3pHEYmV2XUe9cu6aipnLFjpWpDt85vtbv0wSogcRx@cZ3HLsR6lADfKnu86nW7NGm2MvJd9yiT/sNpHl/tYX@GncvZIXRmRbrLYxJ52TSukwB9r/VVyM/rRX9@cfzNYhfW/gW40redeGfk7/qV4fgTpREjM8rl7XdWJgftn1lMzqk0y/TdSrAcC1j1@t0zNMxb5hmD9/pWXy7VCVWXfXhHw) **Explanation:** ``` m->{ // Method with integer-matrix input and no return-type for(int l=m.length, // Dimension-length `l` of the matrix i,j,I,J,d,M,t,x,y; // Temp integers ; // Loop indefinitely: m[x][y]*=d){ // After every iteration: multiply `x,y`'s value with `d` for(I=J=d=0, // (Re)set `I`, `J`, and `d` all to 0 i=l*l;i-->0;) // Loop over all the cells: d= // Set `d` to: Math.sqrt(t=m[i/l][i%l])%1==0? // If the current value is a perfect square *t>d*d? // And if it's larger than `d` squared: (int)Math.sqrt(m[I=i/l][J=i%l]) // Set `I,J` to the current coordinate // And `d` to the square-root of the current value :d; // Else: leave `d` the same if(d<1) // If `d` is still 0 after the nested loop // (which means there are no more square-numbers) break; // Stop the infinite loop for(M=-1>>>1, // (Re)set `M` to Integer.MAX_VALUE m[x=I][y=J]=d, // Replace the value at `I,J` with `d` t=4;t-->0;) // Loop `t` in the range (4, 0]: try{M= // Set `M` to: m[i=I+t/2-t/3*2] // If `t` is 3: // Go to the row above // Else-if `t` is 2: // Go to the row below // Else (`t` is 0 or 1): // Stay in the current row // (and save this row in `i`) [j=t<1?J-1:1/t+J]// If `t` is 0: // Go to the column left // Else-if `t` is 1: // Go to the column right // Else (`t` is 2 or 3): // Stay in the current column // (and save this column in `j`) <M? // And if the value in this cell is smaller than `M`: m[x=i][y=j] // Set `x,y` to `i,j` // And `M` to the current value in `i,j` :M; // Else: leave `M` the same }finally{continue;}}} // Catch and ignore IndexOutOfBoundsExceptions ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 141 bytes ``` f=(a,I,J,r)=>a.map((x,i)=>x.map((y,j)=>(1+J?(i-I)**2+(j-J)**2-1|r<y:y**.5%1||r>y)||(P=i,Q=j,r=y)))|1+J?f(a,a[P][Q]*=a[I][J]**=.5):r&&f(a,P,Q) ``` [Try it online!](https://tio.run/##VVBNi8IwEL37K3pZSeK0mJhmG9m4Z3vSc8gh@LG0WCutLBb6391JRFahkHnvzXsz09r/@n7XVZdrem73h/vR4Ec8rKGEjpqVzxp/IeQGFYLbAwxQIyB8Vn6TKl1TxsSM1GkZipSP3dewHBjL8g8@jt1qoONINqaCramhMwOldAzWI07xduPs1jHj7drZ0jFmspwuu@k0qBvY0vv10F8TkzSJWSXkSBoKya499@3pkJ3aH8R0Mgk9xFquQDuwEkTuHH2yGiSS/J1UIoeFCrxWsBDyReKADh0tEji@C4VerP5biiCpGItuxZ@1BlGgeT5/6RW5gqCghhvENC44cCmhCOk6Qv3YBq0xj@Or324I7Gcho08WcRzapMTZuJzUEMPjsJiB4ZCL@Dt0XDZciYvEJuBQoDPcHqbc/wA "JavaScript (Node.js) – Try It Online") Take input 2D array ]
[Question] [ Given a string as input, output one or more variants of the string such that: * No character is in it's original position * No character is adjacent to a character that it was originally adjacent to You can assume this will always be possible for the given string, and will only contain single case alphabetical characters (`[a-z]` or `[A-Z]` if you prefer) Note that duplicates of the same character are not considered unique. For example, given the input `programming`, the output cannot contain an `m` at the 7th **or** 8th character, and cannot contain a `g` at the 4th **or** 11th character (1 indexed) ## Example: Take the string `abcdef` The following would be a valid output: `daecfb` However the following would be invalid: `fdbcae` as in this example `c` and `b` are still adjacent. Adjacency also wraps, meaning you could not do `fdbeca` as `f` and `a` are still adjacent. ## Testcases: Note these are not the **only** valid outputs for the given inputs Written as `input -> output`: ``` helowi -> ioewhl mayube -> euabmy stephens -> nhseespt aabcdeffghij -> dbfhjfigaeca ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 bytes ``` ẋ2ṡ2Ṣ€ dzǤœ&¬ɓ³=Sȯ ẊÇ¿ ``` [Try it online!](https://tio.run/##y0rNyan8///hrm6jhzsXAvGiR01ruA63H9oMxEuOTlY7tObk5EObbYNPrOd6uKsLKLj/////xSWpBRmpecVf8/J1kxOTM1IB "Jelly – Try It Online") Extremely long by virtue of my being awful at Jelly, but it finally works, at least... still in the process of golfing. ``` link that generates a list of sorted adjacent pairs: ẋ2 duplicate argument ("abc" -> "abcabc") ṡ2 slices of 2 (-> "ab","bc","ca","ab","bc") Ṣ€ sort each link that tests for invalid permutations: Ç get sorted adjacent pairs of argument ³Ç¤ do the same for the original input œ& set intersection, then... ¬ ...inverse; i.e. do they have no elements in common ɓ ȯ logical OR the result of that with... ³= elementwise equality with original input, and... S ...sum; i.e. are some characters in the same position main link: Ẋ shuffle the input list ¿ while Ç the result of the previous link is truthy ``` [Answer] # [Python 2](https://docs.python.org/2/), 185 bytes ``` from itertools import* x=input() g=lambda m:set(zip(m*2,(m*2)[1:])) for l in permutations(x): if not((g(l)|g(l[::-1]))&(g(x)|g(x[::-1]))or any(a==b for a,b in zip(x,l))):print`l`[2::5] ``` [Try it online!](https://tio.run/##NY29CsMgFEZ3n@JOjbekQwJdhDxJCESpSQX/MDdgSt/d6tDlDAe@88WL3sGPpWwpODCkE4VgDzAuhkR3lifj40kc2T5Z6dRLghOHJv4xkbv72DfgPIgFkW0hgQXjIerkTpJkgj94RsHAbOADcb5zi9@KWYjHUDe3anIz@W9qQ/qLy2lS0IKyVy3Z/nJvEVHEZDytdp1HIZ5LKZ2T16l09wM "Python 2 – Try It Online") Prints all valid strings [Answer] # PHP>=7.1, 147 Bytes ``` for($a=$argn,$r="^$a[-1].*$a[0]$",$k=0;$v=$a[$k];)$r.="|^.{{$k}}$v|$v".($l=$a[$k++-1])."|$l$v";for(;preg_match("#$r#",$s=str_shuffle($a)););echo$s; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/ff9639358c96755feecb1e5016fbf58b726a67a6) # PHP>=7.1, 184 Bytes Use the levenshtein distance instead of a Regex way ``` for($a=$argn;$v=$a[$k];$r[]=$l.$v)$r[]=$v.($l=$a[$k++-1]);for(;!$t&&$s=str_shuffle($a);)for($t=1,$i=0;$v=$s[$i];$t*=$v!=$a[$i++])foreach($r as$x)$t*=levenshtein($x,$s[$i-1].$v);echo$s; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/82c1d3d19dd32cbf4eaef6073b13adc428be5285) # [PHP](https://php.net/), 217 bytes Version under 7.1 ``` for($l=strlen($a=$argn),$r=$a[$k=0].$a[$l-1]."|".$a[$l-1]."$a[0]|^{$a[$l-1]}.*$a[0]$";$v=$a[$k];!$k?:$r.="|$v".$a[$k-1],++$k<$l?$r.="|$v".$a[$k]:0)$r.="|^.{{$k}}$v";for(;preg_match("#$r#",$s=str_shuffle($a)););echo$s; ``` [Try it online!](https://tio.run/##XY9NboMwEIX3vUWHt8ANscg2jsVBGidCyMSVXWOZNFkAx86amqBKVXbfvB/pTTBhPlTBhDfU8eIlGe26@xeJue1iDif7a3Ta56jlM8AKxESfsLJUfAG33SlOI/07EpVqPA1/ysQ/nhJI4La2lXiHrfaIXNKI29q2KVtsNrAHuOrFUvuSrdKJDwPsNCVLLCNFiPpy/q6vjckpQ8yoQL/sPvfmp22dTuMZE0zoxnToxZwtQEd/9Ijp0Yfvtk3dGP0L "PHP – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` p.jP;?z≠ᵐ&j¬{s₂p~s}P∧ ``` [Try it online!](https://tio.run/##ATYAyf9icmFjaHlsb2cy//9wLmpQOz964omg4bWQJmrCrHtz4oKCcH5zfVDiiKf//yJhc2RmZ2gi/1o "Brachylog – Try It Online") ## Explanation I really would have wanted for `p.;?z≠ᵐ&j¬{s₂p~s~j}` to work for 2 bytes less, but it seems `~j` is not smart enough... ``` p.jP;?z≠ᵐ&j¬{s₂p~s}P∧ Input is a string, say ? = "asdfgha" p Take a permutation of ?, say "sfagadh". . It is the output. j Concatenate it to itself: "sfagadhsfagadh" P Call that string P. ;? Pair P with the input: ["sfagadhsfagadh","asdfgha"] z Zip, repeating elements of the longer string: [["s","a"],["f","s"],["a","d"],...,["a","g"],["d","h"],["h","a"]] ≠ᵐ Each pair must have different elements. & Start new predicate j Concatenate ? to itself: "asdfghaasdfgha" ¬{ } The following cannot be satisfied: s₂ Take a substring of length 2 p and permute it. ~s It is a substring of P P. ∧ Do not unify P with the output. ``` [Answer] # PHP 7.1, ~~136~~ 131 bytes inspired by [Jörg´s solution](https://codegolf.stackexchange.com/a/125350/55735): ``` for($a=$argn;$c=$a[$k];)$r.="|$c".($d=$a[$k-1])."|$d$c|^.{".+$k++."}$c";while(preg_match("#$a$r#",($s=str_shuffle($a)).$s));echo$s; ``` Run as pipe with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/88d76bcb156a2ddeb88effca91b04f2958a04eae). (Make sure that PHP version 7.1 or above is selected) Requires PHP 7.1; add 14 bytes for older PHP: Replace `$k-1` with `($k?:strlen($a))-1`; (two more bytes for PHP<5.3: `$k?$k-1:strlen($a)-1`) **breakdown** ``` # A: loop through input to collect sub-expressions for($a=$argn;$c=$a[$k];) $r.="|$c".($d=$a[$k-1]) # 1. pair of characters ."|$d$c" # 2. reversed pair ."|^.{".+$k++."}$c"; # 3. $c is at k-th position # B: shuffle input until regex does not match the result while(preg_match("#$a$r#",($s=str_shuffle($a)).$s)); # (input as dummy sub-expression) # C: print result echo$s; ``` [Answer] # PHP 7.1, ~~187 185 172 178~~ 143 bytes ``` do for($r=str_shuffle($s=$argn),$p=$i=0;$c=$s[$i];$p+=($c==$z)+preg_match("#$a|$b#",$s.$s))$b=strrev($a=$r[$i-1].$z=$r[$i++]);while($p);echo$r; ``` Run as pipe with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/a136a8d3393176a2361271a3126b9eefadf9959e). (Make sure that PHP version 7.1.0 or above is selected!) **breakdown** ``` do for($r=str_shuffle($s=$argn), # 2. shuffle input $p=$i=0;$c=$s[$i]; # 3. loop through input $p+=($c==$z) # 2. set $p if char is at old position +preg_match("#$a|$b#",$s.$s) # or if adjacency occurs in input ) $b=strrev($a=$r[$i-1].$z=$r[$i++]); # 1. concat current with previous character while($p); # 1. loop until $p is falsy echo$r; # 4. print ``` [Answer] # Ruby, ~~110~~ ~~97~~ 102 bytes ``` ->s{x=s.chars t=s*2 x.shuffle!while s.size.times.any?{|i|a,b=(x*2)[i,2];a==s[i]||t[a+b]||t[b+a]} x*''} ``` [Try it online!](https://tio.run/##JcvPDoIgHADgu09BXixUpvR/jXoQxgEcDDaz5k8XJj52Z9rq9J2@flRTNCyWV5g9A9JY2UMyMMA08QTsaEyrVy/rWo2AgHtrMri7BiK76TYHF2Sh2NpjuuGuoOIiGQPuRAgDl7n6qXIplsTjLFtiXf07mtETGZ5WNd3u9ofj6ZwKtMRP9ygb2Vj9BQ "Ruby – Try It Online") [Answer] # JavaScript 6, 116 Bytes ``` f=x=>(h=[...x].sort(_=>Math.random(z=0)-.5)).some(y=>y==x[z]||(x+x).match(y+(q=h[++z]||h[0])+'|'+q+y))?f(x):h.join`` ``` ``` f=x=>(h=[...x].sort(_=>Math.random(z=0)-.5)).some(y=>y==x[z]||(x+x).match(y+(q=h[++z]||h[0])+'|'+q+y))?f(x):h.join`` console.log (f('abcdef')); ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~23~~ 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` å╘┤‼¬½P¥ë└w↕⌐î◘E{╟u!Ö ``` [Run and debug online!](https://staxlang.xyz/#p=86d4b413aaab509d89c07712a98c08457bc7752199&i=helowi%0Amayube%0Astephens%0Aaabcdeffghij&a=1&m=2) Thanks for @recursive for saving 2 bytes. Takes a very long time to run. A more reasonable/feasible version is (just 2 bytes longer) ``` Ç≡╨áiS║çdèû.#-Gî☺└╨◙σφ+ ``` [Run and debug online!](https://staxlang.xyz/#p=80f0d0a06953ba87648a962e232d478c01c0d00ae5ed2b&i=helowi%0Amayube%0Astephens%0Aaabcdeffghij&a=1&m=2) ## Explanation Uses the unpacked version to explain. ``` w|Nc_:=nGyG|*{E-!f+}ch+2B w Loop anything before `}` while |N Next permutation (starting from the input) c_:= Index where the current array has the same element as the input (*) }ch+2B Define a block that finds all contiguous pairs in current string, including the pair `[last element, first element]` nG Apply the defined block to current string yG Do the same for the input |* Outer product, contains pairs (which themselves are pairs) constructed from the last two array. { f Only keep pairs E-! whose two elements have the same set of characters + Prepend the array at step (*). This is used as the condition for the while loop ``` ]
[Question] [ Your task is to find the *nth* Fibonacci number, but *n* is not necessarily an integer. The Fibonacci sequence, 0-indexed, goes as follows: ``` 0, 1, 2, 3, 4, 5, 6, 7, ... 1, 1, 2, 3, 5, 8, 13, 21, ... ``` However, what happens if we want the 2*.4*th number? The 2.4th number is 0.4 times the difference between the 3rd and 2nd Fibonacci numbers plus the 2nd Fibonacci number. So, the 2.4th Fibonacci number is `2 + 0.4 * (3 – 2) = 2.4`. Similarly, the 6.35th Fibonacci number is `13 + 0.35 * (21 – 13) = 15.8`. Your task is to find the *nth* Fibonacci number, such that *n* is greater than or equal to 0. You may do this zero- or one-indexed, just please say which one you are using. ### This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! Some more examples: ``` 0 1 4.5 6.5 0.7 1 7 21 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` _Ḟ1+¡ ``` This is an iterative solution without built-ins. It uses the same indexing as the challenge spec. [Try it online!](https://tio.run/nexus/jelly#@x//cMc8Q@1DC////2@mZ2wKAA "Jelly – TIO Nexus") ### Background Let **f** be the function defined in the challenge spec and **F** the Fibonacci function defined as usual (i.e., with **F(0) = 0**). For a non-negative integer **n**, we have **f(n) = F(n + 1)**. When **0 ≤ x < 1**, the challenge spec defines **f(n + x)** as **f(n) + (f(n + 1) - f(n))x**. Clearly, this just affects the base cases, but not the recursive formula, i.e., **f(n) = f(n - 1) + f(n - 2)** holds as it would for **F**. This means we can simplify the definition for non-integer arguments to the easier **f(n) = f(n) + f(n - 1)x**. As others have noted in their answers, the recursive relationship also holds for non-integer arguments. This is easily verifiable, as ![proof](https://i.stack.imgur.com/pzd91.png) Since **f(0) = f(1) = 1**, **f** in constant in the interval **[0, 1]** and **f(0 + x) = 1** for all **x**. Furthermore, **f(-1) = F(0) = 0**, so **f(-1 + x) = f(-1) + (f(0) - f(-1))x = 0 + 1x = x**. These base cases cover in **[-1, 1)**, so together with the recursive formula, they complete the definition of **f**. ### How it works As before, let **n + x** be the only argument of our monadic program. `¡` is a *quick*, meaning that it consumes some links to its left and turns them into a *quicklink*. `¡` in particular consumes either one or two links. * `<F:monad|dyad><N:any>` calls the link **N**, returning **r**, and executes **F** a total of **r** times. * `<nilad|missing><F:monad|dyad>` sets **r** to the last command-line argument (or an input from STDIN in their absence) and executes **F** a total of **r** times. Since `1` is a nilad (a link without arguments), the second case applies, and `+¡` will execute `+` **n** times (a non-integer argument is rounded down). After each call to `+`, the left argument of the quicklink is replaced with the return value, and the right argument with the previous value of the left argument. As for the entire program, `Ḟ` floors the input, yielding **n**; then `_` subtract the result from the input, yielding \*\*x, which becomes the return value. `1+¡` then calls `+¡` – as described before – with left argument **1 = f(0 + x)** and right argument **x = f(-1 + x)**, which computes the desired output. [Answer] # Mathematica, 32 bytes ``` If[#<2,1~Max~#,#0[#-1]+#0[#-2]]& ``` Pure function taking a nonnegative real number as input and returning a real number. If `1~Max~#` were replaced by `1`, this would be the standard recursive definition of the 0-indexed Fibonacci numbers for integer arguments. But `1~Max~#` is the correct piecewise linear function for real inputs between 0 and 2, and the recursion takes care of the rest. (Trivia fact: changing this to the 1-indexed Fibonacci numbers can be accomplished simply by changing the `Max` to a `Min`!) The shortest I could get with the builtin is the 37-byte `(b=Fibonacci)[i=Floor@#](#-i)+b[i+1]&`. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` f=lambda n:n<3and max(1,n)or f(n-1)+f(n-2) ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJBnlWdjnJiXopCbWKFhqJOnmV@kkKaRp2uoqQ2ijDT/FxRl5pUAxYz0TDS5YBwzPWNTGE@9UP0/AA "Python 2 – TIO Nexus") [Answer] ## JavaScript (ES6), 30 bytes ``` f=x=>x<1?1:x<2?x:f(x-1)+f(x-2) ``` ``` <input type=number value=2.4 oninput="O.value=f(value)"> <input id=O value=2.4 disabled> ``` Trivial modification of the zero-indexed recursive Fibonacci sequence definition. May give slight rounding errors for some inputs. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 12 bytes ``` ’Ñ+Ñ ’»0‘ÇỊ? ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYebhidqHJ3IBGYd2GzxqmHG4/eHuLvv///@b6RmbAgA "Jelly – TIO Nexus") Non-builtin solution. ## Explanation **Helper function `1Ŀ`** ``` ’Ñ+Ñ Ñ Call the main program on ’ {the input} - 1; Ñ Call the main program on {the input}; + Add those results{and return the result} ``` **Main program** ``` ’»0‘ÇỊ? ’ Subtract 1 »0 but replace negative results with 0 Ị? If the result is less than or equal to 1 ‘ Return the result plus 1 Ç else return the result ``` An input in the range 0 to 1 will therefore saturated-subtract to 0, thus we add 1 to get F(0)=F(1)=1. An input in the range 1 to 2 will return itself. Those base cases are sufficient to do a typical Fibonacci recursion and calculate the other values from there. [Answer] ## Excel, ~~137 124 119 113 102~~ 97 Bytes Non-recursive/iterative approach. (Directly calculate the nth terms) This uses the **one-indexed** method. Adding `+1` to `=TRUNC(B1)` changes it to zero-indexed. ``` =A7+(A8-A7)*MOD(B1,1) =5^.5 =(1+A2)/2 =TRUNC(B1) =A4+1 =-1/A3 =(A3^A4-A6^A4)/A2 =(A3^A5-A6^A5)/A2 ``` The code snippet is intended to be placed starting in cell **A1**. The input cell is **B1**. The output cell is **A1**. [Answer] # JavaScript (ES6), ~~67~~ 64 bytes Has a few issues with rounding ``` n=>(i=(g=(z,x=1,y=0)=>z?g(--z,x+y,x):y)(++n|0))+n%1*(g(++n|0)-i) ``` --- ## Try It ``` f= n=>(i=(g=(z,x=1,y=0)=>z?g(--z,x+y,x):y)(++n|0))+n%1*(g(++n|0)-i) console.log(f(2.4)) console.log(f(6.35)) console.log(f(42.42)) ``` [Answer] # PHP, 90 Bytes ``` for($f=[1,1];$i<$a=$argn;)$f[]=$f[+$i]+$f[++$i];echo$f[$b=$a^0]+($a-$b)*($f[$b+1]-$f[$b]); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/3d09f38da7d5b85f869697421c67a810ffa1740c) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 9 bytes ``` ,‘ḞÆḞḅ%1$ ``` This uses the same indexing as the challenge spec. [Try it online!](https://tio.run/nexus/jelly#@6/zqGHGwx3zDrcBiYc7WlUNVf7//2@mZ2wKAA "Jelly – TIO Nexus") ### Background Per the spec, we have **F(n + x) = F(n) + (F(n + 1) - F(n))x**, for natural **n** and **0 ≤ x < 1**. Since **F(n + 1) = F(n) + F(n - 1)**, this can be rewritten as **F(n + x) = F(n) + F(n - 1)x**. Furthermore, the indexing used in the challenge spec defines a function **f(n) = F(n + 1)** (where **F** is the usual Fibonacci function, i.e., **F(0) = 0**), so we get the formula **f(n + x) = F(n + 1) + F(n)x**. ### How it works ``` ,‘ḞÆḞḅ%1$ Main link. Argument: n + x ‘ Increment; yield n + 1 + x. , Pair; yield [n + x, n + 1 + x]. Ḟ Floor; yield [n, n + 1]. ÆḞ Fibonacci; yield [F(n), F(n + 1)]. %1$ Modulus 1; yield (n + x) % 1 = x. ḅ Unbase; yield F(n)x + F(n + 1). ``` [Answer] # [Perl 6](https://perl6.org), ~~48~~ 38 bytes ## 48 ``` {$/=(1,1,*+*...*)[$_,$_+1];$0+($_-.Int)*($1-$0)} ``` [Try it](https://tio.run/nexus/perl6#NY7BSsQwFEX3@YrLECRp0tdGbRVCxa17d1bK0IlQqJ1iUlFKv8hPcDc/Vmtn@jbvcu673Dd4h8@casvev3FVHw8OxTzypBBGGx2piIgi@cIrzStlXi1PleBVTE9dkJHgJuapnOYl@xicDyigTj9t0zkv5OmXfN82QSSlV4m0bFi6npcry/p230GtEcvejh@XdPwAgbLp@iFolO6rd3VwB0iMDGg8/t8Tqy01NltjN65sKsO4wWnHpjmnm8ylgMnoni37PIbdUnaWOWUspbuNXwSuzR8 "Perl 6 – TIO Nexus") ## 38 ``` sub f(\n){3>n??max 1,n!!f(n-1)+f(n-2)} ``` [Try it](https://tio.run/nexus/perl6#NY5NDoIwFIT3PcXgqg1QqQiaEH8O4bIbxZKQQCW2GA3hRB7BnRdD5OdtZvLNm5dXG4VHzNOkM/UFGZWaNeFeHw7l@QnhacfJqPYFc/@yYm1XvnC0yljs4H7fRa6Voez74aYqckuX0rhLlpC6P3vqtxJSFWcNd6gkJLvdp7a/B4XMdVVbD1I9K5VadQVDQ4Dc9J8MGfMwZx4WzcBaaZsZtgvSdjEPIxUAIuJb0us4gqx5NNqYRyTgm5lPBivxAw "Perl 6 – TIO Nexus") ## Expanded: ## 48 ``` { $/ = # store here so we can use $0 and $1 ( 1,1,*+*...* # Fibonacci sequence )[ $_, # get the value by using floor of the input $_ + 1 # and get the next value ]; $0 # the first value from above + ( $_ - .Int ) # the fractional part of the input * ( $1 - $0 ) # the difference between the two values in the sequence } ``` (`$0` and `$1` is short for `$/[0]` and `$/[1]`) ## 38 ``` sub f (\n) { 3 > n # if n is below 3 ?? max 1, n # return it if it is above 1, or return 1 # if it was below 1, the answer would be 1 # the result for numbers between 1 and 3 # would be the same as the input anyway !! f(n-1) + f(n-2) # the recursive way to get a fibonacci number } ``` This was inspired by other [Python](https://codegolf.stackexchange.com/questions/117986/linear-interpolation-of-the-fibonacci-sequence/117991#117991), and [Javascript](https://codegolf.stackexchange.com/questions/117986/linear-interpolation-of-the-fibonacci-sequence/117988#117988) solutions [Answer] # [Julia 0.5](http://julialang.org/), 31 bytes This is basically just Rod's answer translated. ``` f(n)=n<3?max(1,n):f(n-1)+f(n-2) ``` [Try it online!](https://tio.run/nexus/julia5#@5@mkadpm2djbJ@bWKFhqJOnaQUU0TXU1AZRRpr/C4oy80py8jTSNIz0TDQ1uRB8Mz1jU03N/0AAAA "Julia 0.5 – TIO Nexus") ]
[Question] [ # Challenge Given the following C# method: ``` private static bool Test(bool a, bool b) { if (a && b) return false; if (a) if (b) return true; return false; } ``` Supply the values `a` and `b` so that `true` is returned. # Winning condition The first entry who can supply the correct arguments to make the given method evaluate to `true` wins. [Answer] ``` static void Main(string[] args) { bool a, b; unsafe { int* pa = (int*)&a; int* pb = (int*)&b; *pa = 1; *pb = 2; } Console.Write(Test(a, b)); } ``` This prints `True` for me with the C# implementation that comes with Visual Studio 2015. I actually don't know any C#, but I figured I'd try to write some C code and see if it worked. I was hoping that the compiler would assume that True is always represented as 1 and use a bitwise AND. In Debug mode, this is indeed the case (it worked with Release too). It uses a bitwise AND for the first condition and two comparisons to zero for the second: ``` if (a && b) return false; 002C2E92 movzx eax,byte ptr [ebp-3Ch] 002C2E96 movzx edx,byte ptr [ebp-40h] 002C2E9A and eax,edx 002C2E9C and eax,0FFh 002C2EA1 mov dword ptr [ebp-44h],eax 002C2EA4 cmp dword ptr [ebp-44h],0 002C2EA8 je 002C2EB2 002C2EAA xor edx,edx 002C2EAC mov dword ptr [ebp-48h],edx 002C2EAF nop 002C2EB0 jmp 002C2EE4 if (a) if (b) return true; 002C2EB2 movzx eax,byte ptr [ebp-3Ch] 002C2EB6 mov dword ptr [ebp-4Ch],eax 002C2EB9 cmp dword ptr [ebp-4Ch],0 002C2EBD je 002C2EDC 002C2EBF movzx eax,byte ptr [ebp-40h] 002C2EC3 mov dword ptr [ebp-50h],eax 002C2EC6 cmp dword ptr [ebp-50h],0 002C2ECA je 002C2EDC 002C2ECC mov eax,1 002C2ED1 and eax,0FFh 002C2ED6 mov dword ptr [ebp-48h],eax 002C2ED9 nop 002C2EDA jmp 002C2EE4 return false; 002C2EDC xor edx,edx 002C2EDE mov dword ptr [ebp-48h],edx 002C2EE1 nop 002C2EE2 jmp 002C2EE4 } 002C2EE4 mov eax,dword ptr [ebp-48h] 002C2EE7 lea esp,[ebp-0Ch] 002C2EEA pop ebx 002C2EEB pop esi 002C2EEC pop edi 002C2EED pop ebp 002C2EEE ret ``` ]
[Question] [ A [fountain](http://mathworld.wolfram.com/Fountain.html) is arrangement of coins in rows so that each coin touches two coins in the row below it, or is in the bottom row, and the bottom row is connected. Here's a 21 coin fountain: [![From http://mathworld.wolfram.com/Fountain.html](https://i.stack.imgur.com/9BBBn.gif)](https://i.stack.imgur.com/9BBBn.gif) --- Your challenge is to count how many different fountains can be made with a given number of coins. You will be given as input a positive integer `n`. You must output the number of different `n`-coin fountains that exist. Standard I/O rules, standard loopholes banned. Solutions should be able to calculate `n = 10` in under a minute. --- Desired output for `n = 1 ... 10`: ``` 1, 1, 2, 3, 5, 9, 15, 26, 45, 78 ``` This sequence is [OEIS A005169](https://oeis.org/A005169). --- This is code golf. Fewest bytes wins. [Answer] # Mathematica, 59 bytes ``` SeriesCoefficient[1-Fold[1-x^#2/#&,Range[#,0,-1]],{x,0,#}]& ``` Based on the Mathematica program on OEIS by Jean-François Alcover. [Answer] ## Python, 57 bytes ``` f=lambda n,i=0:sum(f(n-j,j)for j in range(1,i+2)[:n])or 1 ``` As observed on [OEIS](https://oeis.org/A005169), if you shift each row half a step relative to the row below it, the column sizes form a sequence of positive integers with a maximum upward step of 1. The function `f(n,i)` counts the sequences with sum `n` and last number `i`. These can be recursively summed for each choice of the next column size from `1` to `i+1`, which is `range(1,i+2)`. Truncating to `range(1,i+2)[:n]` prevents columns from using more coins than remain, avoiding needing to say that negative `n`'s give `0`. Moreover, it avoids an explicit base case, since the empty sum is `0` and doesn't recurse, but `f(0)` needs to be set to `1` instead, for which `or 1` suffices (as would `+0**n`). [Answer] # Haskell, ~~60~~ 48 bytes Thanks to @nimi for providing a way shorter solution! ``` n#p|p>n=0|p<n=sum$map((n-p)#)[1..p+1]|1<2=1 (#1) ``` Old version. ``` t n p|p>n=0|p==n=1|p<n=sum[t (n-q) q|q<-[1..p+1]] s n=t n 1 ``` The function calculating the value is `s`, implementation of the recursive formula found here: <https://oeis.org/A005169> [Answer] ## Haskell, 43 bytes ``` n%i=sum[(n-j)%j|j<-take n[1..i+1]]+0^n (%0) ``` See [Python answer](https://codegolf.stackexchange.com/a/67827/20260) for explanation. Same length with `min` rather than `take`: ``` n%i=sum[(n-j)%j|j<-[1..min(i+1)n]]+0^n (%0) ``` [Answer] # Pyth, ~~21~~ 20 bytes ``` Ms?>GHgL-GHShHqGHgQ1 ``` [Try it online.](https://pyth.herokuapp.com/?code=Ms%3F%3EGHgL-GHShHqGHgQ1&input=6&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=Ms%3F%3EGHgL-GHShHqGHgQ1&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) This is a direct implementation of the recursive formula on the [OEIS page](https://oeis.org/A005169), like the [Matlab answer](https://codegolf.stackexchange.com/a/67751/30164). [Answer] # Matlab, ~~115~~ 105 bytes ``` function F=t(n,varargin);p=1;if nargin>1;p=varargin{1};end;F=p==n;if p<n;for q=1:p+1;F=F+t(n-p,q);end;end ``` Implementation of the recursive formula found here: <https://oeis.org/A005169> ``` function F=t(n,varargin); p=1; if nargin>1 p=varargin{1}; end; F=p==n; if p<n; for q=1:p+1; F=F+t(n-p,q); end; end; ``` [Answer] # Julia, ~~44~~ 43 bytes ``` f(a,b=1)=a>b?sum(i->f(a-b,i),1:b+1):1(a==b) ``` This uses recursive formula on OEIS. Explanation ``` function f(a, b=1) if a > b # Sum of recursing sum(i -> f(a-b, i), 1:b+1) else # Convert bool to integer 1 * (a == b) end end ``` Has anyone else noticed that strike through 44 is regular 44?? [Answer] # Python 3, 88 bytes ``` f=lambda n,p:sum([f(n-p,q)for q in range(1,p+2)])if p<n else int(p==n) t=lambda n:f(n,1) ``` [Answer] # JavaScript (ES6), 63 Implementing the recursive formula at OEIS page ``` F=(n,p=1,t=0,q=0)=>p<n?eval("for(;q++<=p;)t+=F(n-p,q)"):p>n?0:1 ``` [Answer] # APL, 26 bytes ``` {⍵≥⍺:⍵=⍺⋄+/(⍺-⍵)∘∇¨⍳⍵+1}∘1 ``` Straightforward implementation of the first formula from the sequence explanation page. Honestly, I didn't understand anything, so let's check the results: ``` {⍵≥⍺:⍵=⍺⋄+/(⍺-⍵)∘∇¨⍳⍵+1}∘1¨⍳10 1 1 2 3 5 9 15 26 45 78 ``` ]
[Question] [ Write the shortest possible program that draws a Bresenham line in ASCII art. Your program should take two integers `x` and `y` (command line or stdin, your choice) and draw an ASCII line which starts in the upper left and goes right `x` units and down `y` units. You must use `_` and `\` characters and place them in the correct location according to [Bresenham's](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) algorithm. You may assume `x >= y`, so no vertical segments are required. Note that because you're using the `_` character, for a line with `y=3` you will likely need to output 4 lines of text (and you may emit a leading blank line when it isn't necessary). examples: ``` 11 3 _ \___ \___ \_ 11 1 _____ \_____ 5 4 \ \_ \ \ ``` For points which are exactly halfway you may choose either rounding: ``` 10 1 ____ \_____ or _____ \____ ``` [Answer] # Perl, 74 ``` / /;print int(.5+$_*$'/$`)>int(.5+--$_*$'/$`)?$/.$"x$_.'\\':'_'for 1..$` ``` Run with `-n` option (counted in code size). ``` $ perl -n bresenham.pl <<<'11 3' _ \___ \___ \_ $ perl -n bresenham.pl <<<'11 1' _____ \_____ $ perl -n bresenham.pl <<<'5 4' \ \_ \ \ $ perl -n bresenham.pl <<<'10 1' ____ \_____ ``` [Answer] # C ~~136~~ 123 Characters ``` z,x,y,i,f;main(){for(scanf("%d%d",&x,&y);i<=x;i++){f=f?printf("_"):1;z+=y;if(2*z>=x&&i<x)f=0,z-=x,printf("\n%*c",i+1,92);}} ``` [Answer] # Delphi, 109 bytes Quite small if you ask me : ``` var x,y,i:Word;begin Read(x,y);for i:=1to(x)do if(i*y+x div 2)mod x<y then Write(^J,'\':i)else Write('_')end. ``` The 2 integers are read from the command line. The newline is written by the seldomly used `^J` syntax (meaning LineFeed), the following '`\`' character is indented using the little-known syntax :`Write(string:width)`. It's a pitty Delphi `div` for integer-divide (instead of just `\`). Ah well... [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 39 bytes ``` {⍉↑(-1++\a)↑¨'_\'[a←-2-/⌊.5+⍵×⍺÷⍨⍳1+⍺]} ``` [Try it online!](https://tio.run/##bU29CsIwEN59im5RSqzxZ/FVjIRQqRQCldZFpJNSqBqxg7g7uYsIHe2b3IvUq7VWwQuE776/kzNFJwupvCm1lQwC185hf3Q9iA6d3MF/CTqGKGlSZppcthA@LkRwMpIo0i61YLdpD0zQt@wEOs3uoC@grwyZdBzm@bzsuEF89hHCZuVYKA2JI11FEKHmw3aNV1H2wwZjRg9DCRHGZwg@LoSot2JKptpKhhR5VubF34RAz8DoGy8PCrw@UBl5FeBY1/mq@2l7lz0B "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` F…·¹θ⎇‹﹪⁺×ιη⌊∕θ²θη¶\¦_ ``` It took a while to figure out the right formula, but it now works! Credit to the Delphi answer. Link is to verbose version of code. [Try it online!](https://tio.run/##JctBCsIwEEDRq0hWMzBdKHoAQQqCbqQ7IxKT0Q6kCU1ooKePEXcPPt@OJtlofK19THAO1i9ZCt9M@DBsaUbcDJyCSStcOGe4Rrf4CEfnYJCJMwiNSL2P7T5JEccw0w4R2/orSgetFamnwlrvB9o/atcVTq@Yucnx3/Jevw "Charcoal – Try It Online") ]
[Question] [ Inspired by a recent question on SO... Write a function to print a binary tree in the following format: ``` 3 / \ 1 5 \ / \ 2 4 6 ``` 1. The output should consist of a line of nodes, followed by a line of `/` and `\` characters indicating relationships, followed by a line of nodes, etc. 2. You can assume all nodes are representable as a single character. 3. Adjacent nodes on the lowest level should be separated by at least one space, nodes further up should be separated as appropriate. 4. Nodes with two children should be placed precisely in the middle of their direct children. 5. Relationship slashes should be halfway between the parent and the appropriate child (round whichever way you want). Input: The input will be provided as an argument to your function. I won't specify the exact structure of the tree, however it must be usable as an actual binary tree. No "trees are represented in my program as strings coincidentally looking like the expected output". You may print to an output stream or return a string containing the output, your choice. Points for shortest code, but I'd much prefer a fully working long solution than a 90%-working short one. --- *Update for the bounty:* For the bounty, I (Optimizer) am making slight changes: * Input can be from STDIN,ARGV or function argument. * Output needs to be on STDOUT (or `console.log` for JS) * You can assume that input is in a form of array, for ex. `[1,2,3]` or `[1 2 3]` *Update 2* - The binary tree should actually be a binary search tree. Since I did not mention this initially, I will allow users to treat the converting a normal array into a binary search tree array as a separate program and the final byte count will only be for the program to take in the array as argument and print it like a binary tree. [Answer] Fortran 77 -- 1085 characters ``` subroutine q(u,t) implicit integer(i-z) character*33 f,g dimension t(u) m=ceiling(log(real(u))/log(2.)) v=2**(m+1)-1 do l=1,m n=2**(l-1) k=2**(m-l+2)-3 w=(3+k)*2**(l-1)-k p=1+(v-w)/2 if(l.ne.1)then write(f,'(A,I3,A)')'(A',p,',$)' print f,' ' write(f,'(A5,I3,A3)')'(A3,A',k,',$)' do j=2**(l-1),2**l-1 if(t(j/2).lt.0.or.t(j).lt.0)then print f,' ',' ' elseif(mod(j,2).eq.0)then print f,' /',' ' else print f,' \ ',' ' endif enddo print* endif write(f,'(A,I3,A)')'(A',p,',$)' print f,' ' write(f,'(A5,I3,A3)')'(I3,A',k,',$)' write(g,'(A2,I3,A3)')'(A',k+3,',$)' do j=2**(l-1),2**l-1 if(t(j).ge.0)then print f,t(j),' ' else print g,' ' endif enddo print* enddo end ``` The tree is represented in the input array `t` in the usual fashion, root at 1, root->left at 2, root->right at 3 root->left->left at 4... The output should fit in a conventional terminal up to 5 levels deep. I use exactly one slash between each pair of nodes, which looks pretty silly near the top once there are four or more levels. I allowed for up to three digit nodes. Full program with comments and a launching scaffold: ``` program tree parameter (l=8) ! How many nodes to support dimension i(l) c Initialize the array to all empty nodes do j=1,l i(j)=-1 end do c Fill in some values i(1)=3 i(2)=1 i(3)=5 i(5)=2 i(6)=4 i(7)=7 c i(14)=6 c i(15)=8 c Call the printing routine call q(l,i) stop end c Print an ASCII representation of the tree c c u the length of the array containing the tree c t an integer array representing the tree. c c The array contains only non-negative values, and empty nodes are c represented in the array with -1. c c The printed representation uses three characters for every node, c and places the (back) slash equally between the two node-centers. subroutine q(u,t) implicit integer(i-z) character*33 f,g dimension t(u) m=ceiling(log(real(u))/log(2.)) ! maximum depth of the tree v=2**(m+1)-1 ! width needed for printing the whole tree ! Optimized from 3*2**m + 1*((2**m)-1) at ! the bottom level do l=1,m n=2**(l-1) ! number of nodes on this level k=2**(m-l+2)-3 ! internode spacing w=(3+k)*2**(l-1)-k ! width needed for printing this row ! Optimized from 3*2**l + k*((2**l)-1) at ! the bottom level p=1+(v-w)/2 ! padding for this row c Print the connecting lines associated with the previous level if(l.ne.1)then ! Write the connecting lines write(f,'(A,I3,A)')'(A',p,',$)' print f,' ' write(f,'(A5,I3,A3)')'(A3,A',k,',$)' do j=2**(l-1),2**l-1 if(t(j/2).lt.0.or.t(j).lt.0)then print f,' ',' ' elseif(mod(j,2).eq.0)then print f,' /',' ' else print f,' \ ',' ' endif enddo print* endif c Print the nodes on this level write(f,'(A,I3,A)')'(A',p,',$)' print f,' ' write(f,'(A5,I3,A3)')'(I3,A',k,',$)' write(g,'(A2,I3,A3)')'(A',k+3,',$)' do j=2**(l-1),2**l-1 if(t(j).ge.0)then print f,t(j),' ' else print g,' ' endif enddo print* enddo end ``` Output with input equivalent to the example: ``` $ ./a.out 3 / \ 1 5 \ / \ 2 4 7 ``` [Answer] # CJam, 100 99 bytes ``` q~_,2b,)2\#:Q1@{_2$<Q(S*:T*TQ2/:Q@ts[N+_0@{@1$' >{2$St2$_Q3*&2/^_4$>"\/"=t}*@)}/;U*o]o1:U$>\2*\}h]; ``` Input must be a list of characters, without any ascii control characters. Empty nodes are denoted by a space. It also must be a perfect binary tree with exactly 2n-1 nodes. Example: ``` ['6 '3 '7 '1 '4 ' '9 '0 '2 ' '5 ' ' '8 ' ] ``` Or simply use strings: ``` "63714 902 5 8 " ``` Output: ``` 6 / \ 3 7 / \ \ 1 4 9 / \ \ / 0 2 5 8 ``` ### Explanation ``` q~ " Read input. "; _,2b, " Get tree height. "; )2\#:Q " Get (displayed) tree width and save it in Q. "; 1@ " Push X=1 and rotate the input to top. "; { " Do: "; _2$< " Get first X characters from the input. "; Q(S*:T " T = (Q-1) spaces. "; * " Separate the X characters by T. "; TQ2/:Q@t " Put the string in the middle of T, and divide Q by 2. "; s " Concatenate everything into a string. This is the line of node labels. "; [ N+ " Append a newline. "; _ " Duplicate. "; 0@ " Push a 0 and rotate the original string to top. "; { " For each character: "; @ " Rotate the duplicate to top. "; 1$' > " Test if the current character is greater than a space. "; { " If true: "; 2$St " Set the current character in the duplicate to space. "; 2$ " Copy the current position I (the number initialized with 0). "; _Q3*&2/^ " Calculate I ^ ((I & (3*Q))>>1), the position of the relationship character. "; _4$> " Test if it is greater than the current position. "; "\/"= " Select the relationship character. "; t " Change the character in the duplicate. "; }* @) " Increment the current position. "; }/ " The last two items are the line of relationship characters and the tree width. "; ; " Discard the tree width. "; U* " If it is the first line, empty the line of relationship characters. "; o " Output. "; ]o " Output the line of node labels. "; 1:U " Mark it not the first line. "; $> " Remove the first X characters from the input. "; \2*\ " Multiply X by 2. "; }h " ...while the input is not empty. "; ]; " Discard everything in the stack. "; ``` ## Conversion script ``` [[0LL]W] [q~{_a_:i={'0+}*}%La2*f+ _,,]z$ 1$a+ { { 1$1=1$1=>:T { ~@0=2 3$1=t @1@ta\+ }* T }g }* 0=1=a { { (M\+:M; La[' LL]aer~ }% _[' LL]a- }g ]; M0+`-3<']+ ``` It accepts either characters or single digit numbers. Examples (all are the same): ``` ['6 '7 '9 '3 '1 '2 '8 '4 '0 '5] [6 7 9 3 1 2 8 4 0 5] "6793128405" ``` Output: ``` ['6 '3 '7 '1 '4 ' '9 '0 '2 ' '5 ' ' '8 ' ] ``` It's a straight-forward Cartesian tree construction. [Answer] # APL, 125 characters ``` {⍵{x←⍵[0;d←⌈2÷⍨1⌷⍴⍵]←↑⍺ 2 1∇{x[2↓⍳↑⍴x;(⍳d)+d×⍺-1]←⍵(⍺⍺⍣t←0≠⍴⍵)2↓x[;⍳d] x[1;d+(⌈d÷4)ׯ1*⍺]←' /\'[t×⍺]}¨⍺[2 1] x}' '⍴⍨2(×,*)≡⍵} ``` Example: ``` {⍵{x←⍵[0;d←⌈2÷⍨1⌷⍴⍵]←↑⍺ 2 1∇{x[2↓⍳↑⍴x;(⍳d)+d×⍺-1]←⍵(⍺⍺⍣t←0≠⍴⍵)2↓x[;⍳d] x[1;d+(⌈d÷4)ׯ1*⍺]←' /\'[t×⍺]}¨⍺[2 1] x}' '⍴⍨2(×,*)≡⍵}('1' ('2' ('3' ('4' ()()) ('5' ()())) ('6' ()('7' ()())))('8' ()('9' ('0' ()())()))) ``` [Tested here.](http://ngn.github.io/apl/web/#code=%7B%u2375%7Bx%u2190%u2375%5B0%3Bd%u2190%u23082%F7%u23681%u2337%u2374%u2375%5D%u2190%u2191%u237A%0A2%201%u2207%7Bx%5B2%u2193%u2373%u2191%u2374x%3B%28%u2373d%29+d%D7%u237A-1%5D%u2190%u2375%28%u237A%u237A%u2363t%u21900%u2260%u2374%u2375%292%u2193x%5B%3B%u2373d%5D%0Ax%5B1%3Bd+%28%u2308d%F74%29%D7%AF1*%u237A%5D%u2190%27%20/%5C%27%5Bt%D7%u237A%5D%7D%A8%u237A%5B2%201%5D%0Ax%7D%27%20%27%u2374%u23682%28%D7%2C*%29%u2261%u2375%7D%28%271%27%20%28%272%27%20%28%273%27%20%28%274%27%20%28%29%28%29%29%20%28%275%27%20%28%29%28%29%29%29%20%28%276%27%20%28%29%28%277%27%20%28%29%28%29%29%29%29%28%278%27%20%28%29%28%279%27%20%28%270%27%20%28%29%28%29%29%28%29%29%29%29) [Answer] # Python 2, 411 bytes ``` import math def g(a,o,d,l,b): if l<0: return c=2*b+1 k=2*l+1 o[k]=' '*b n=d-l p=1 if n==0 else 3*2**n-1 o[k-1]=p/2*' ' i=0 for v in a[2**l-1:2**l*2-1]: v=' ' if v==None else v o[k]+=v+' '*c m=' ' if v==' ' else '/' if i%2==0 else '\\' o[k-1]+=m+max(1,b)*' ' if i%2==0 else m+p*' ' i+=1 g(a,o,d,l-1,c) def f(a): d=int(math.log(len(a),2)) o=['']*(d*2+2) g(a,o,d,d,0) print '\n'.join(o[1:]) ``` Note: First indentation level is 1 space, second is one tab. Call `f` with a list of one-character strings or `None`'s, eg. `f(['1',None,'3'])`. The list can't be empty. This should obey the rules for the bounty. # Converter script: Converts and array to the format used by the binary tree printer. Example: ``` $ python conv.py [3,5,4,6,1,2] ['3', '1', '5', None, '2', '4', '6'] ``` - ``` import sys def insert(bt, i): if i < bt[0]: j = 0 else: j = 1 n = bt[1][j] if n == [None]: bt[1][j] = [i, [[None], [None]]] else: insert(bt[1][j], i) def insert_empty(bt, i): if i == 0: return if bt == [None]: bt += [[[None], [None]]] insert_empty(bt[1][0], i - 1) insert_empty(bt[1][1], i - 1) def get(l, level): if level == 0: if type(l) == list: return ([], l) else: return ([l], []) elif type(l) != list: return ([], []) res = [] left = [] for r, l in [get(i, level - 1) for i in l]: res += r left += l return (res, left) if __name__ == '__main__': l = eval(sys.argv[1]) bt = [l[0], [[None], [None]]] map(lambda x: insert(bt, x), l[1:]) depth = lambda l: 0 if type(l) != list else max(map(depth, l)) + 1 d = (depth(bt) + 1) / 2 insert_empty(bt, d - 1) flat = [] left = bt i = 0 while len(left) > 0: f, left = get(left, 1) flat += f i += 1 for i in range(len(flat) - 1, -1, -1): if flat[i] == None: flat.pop() else: break flat = map(lambda x: None if x == None else str(x), flat) print flat ``` # Examples: To run these you should have the main file named `bt.py` and the converter file named `conv.py`. ``` $ python conv.py [3,5,4,6,1,2] | python -c 'import bt; bt.f(input())' 3 / \ 1 5 \ / \ 2 4 6 $ python conv.py [5,4,3,7,9] | python -c 'import bt; bt.f(input())' 5 / \ 4 7 / \ 3 9 $ python conv.py [1,2,3,4,5,6] | python -c 'import bt; bt.f(input())' 1 \ 2 \ 3 \ 4 \ 5 \ 6 $ python conv.py [6,5,4,3,2,1] | python -c 'import bt; bt.f(input())' 6 / 5 / 4 / 3 / 2 / 1 ``` [Answer] # Ruby, 265 bytes ``` def p(t);h=Math.log(t.length,2).to_i;i=-1;j=[];0.upto(h){|d|s=2**(h-d)-1;c=2**d;if d>0;m=' '*(s+s/2)+'I'+' '*(s-s/2);1.upto(d){m+=' '+m.reverse};w=i;puts m.gsub(/I/){|o|t[w+=1]?(w%2==0?'\\':'/'):' '};end;puts (0...c).map{' '*s+(t[i += 1]or' ').to_s+' '*s}*' ';};end ``` **The @proudhaskeller version, 269 bytes** ``` def p(t);h=Math.log(t.length,2).to_i;i=-1;j=[];0.upto(h){|d|s=(z=2**(h-d))-1;c=2**d;if d>0;m=' '*(s+z/2)+'I'+' '*(s-z/2);1.upto(d){m+=' '+m.reverse};w=i;puts m.gsub(/I/){|o|t[w+=1]?(w%2==0?'\\':'/'):' '};end;puts (0...c).map{' '*s+(t[i += 1]or' ').to_s+' '*s}*' ';};end ``` --- **Explaination** The verbose version: ``` def p(t) depth = Math.log(t.length, 2).floor i = -1 j = [] (0..depth).each do |d| s = 2 ** (depth-d)-1 c = 2 ** d if d > 0 m = ' '*(s+s/2) + '|' + ' '*(s-s/2) w = i 1.upto(d) { m += ' ' + m.reverse } puts m.gsub(/\|/) { |o| t[w+=1] ? (w%2==0 ? '\\' : '/') : ' ' } end puts (0...c).map{' '*s+(t[i += 1]or' ').to_s+' '*s}*' ' end end ``` --- ]
[Question] [ This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will have you computing OEIS sequence [A300154](https://oeis.org/A300154). > > Consider a spiral on an infinite hexagonal grid. a(n) is the number of cells in the part of the spiral from 1st to n-th cell that are on the same [row\*] or diagonal (in any of three directions) as the n-th cell along the spiral, including that cell itself. > > > (\*I have very slightly changed the definition to match the orientation of the GIF below.) The sequence begins ``` 1, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 6, 7, 7, 8, 7, 8, 9, 8, 9, 8, 9, 10, 9, 10, 11, 9, 10, 11, 10, 11, 12, 10, 11, 12, 13, 11, 12, 13, 11, 12, 13, 14, 12, 13, 14, 15, 12, 13, 14, 15, 13, 14, 15, 16, 13, 14, 15, 16, 17, 14 ``` # Example Below is an example of the first fifteen terms of the sequence. On a hexagonal tiling, go in a spiral, and after each step, count the number of cells that you can "see" from that position, including the cell itself. [![Example of A300154](https://i.stack.imgur.com/KAJup.gif)](https://i.stack.imgur.com/KAJup.gif) # Challenge The challenge is simple, write a program that takes a positive integer `n` and computes \$A300154(n)\$. Again, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. *(Note: I will also award an additional bounty of 200 rep to the first person who completes this challenge in [Hexagony](https://esolangs.org/wiki/Hexagony).)* [Answer] # JavaScript (ES6), ~~178 169~~ 168 bytes Returns the \$n\$ first terms as an array. ``` n=>(X=[1],Y=[L=1],d=5,j=x=y=0,g=a=>--n?g([...a,(X[x+=~-'210012'[d%=6]]=-~X[x])+(Y[y+=~-'1221'[j?d:d++]]=-~Y[y])+(Z[x+y]=-~Z[x+y])-2],++j%L?0:(j%=L*6)?d++:L++):a)(Z=[1]) ``` [Try it online!](https://tio.run/##JY5NCsIwEEav4qZkxvzQBOyiMPYCPUA1ZBGMFoMkoiLtxqvXVFfffLw3w0T/9s/T43p/yZTDebnQkmgPA1ntxIFsTyUD7USkiWaqxUie9lKmbgSrlPICBjtx@khmdF1rw2yoqHGO5KcAhxwOdv5xbYxmNnahDZz/hEJW4VgOzGv/DyiNE5zHqu/qFmJF/bbBruy0PefYeoTj@h0up5ye@XZWtzzCBRqDKuZrAiY2DHH5Ag "JavaScript (Node.js) – Try It Online") ### How? This is a rather naive approach that actually computes the spiral with [cube coordinates](https://www.redblobgames.com/grids/hexagons/#coordinates-cube) \$(x,y,x+y)\$ and keeps track of the number of cells on each row \$Z[x+y]\$, each diagonal \$Y[y]\$ and each anti-diagonal \$X[x]\$. ### Commented ``` n => ( // n = input X = [1], Y = [L = 1], // X[] = anti-diagonals, Y[] = diagonals, L = layer d = 5, // d = direction in [0..5] j = // j = cell index in the current layer x = y = 0, // (x, y) = coordinates g = a => // g = main recursive function taking the output a[] --n ? // decrement n; if we haven't computed enough terms: g( // recursive call: [ ...a, // append the previous terms ( X[x += // update x and increment X[x] ~-'210012'[d %= 6] // pick dx according to d ] = -~X[x] // ) + // ( Y[y += // update y and increment Y[y] ~-'1221'[j ? d // pick dy according to d : d++] // increment d afterwards if j = 0 ] = -~Y[y] // (i.e. this is the 1st cell of the layer) ) + // (Z[x + y] = -~Z[x + y]) // increment Z[x + y] - 2 // subtract 2 from X[x] + Y[y] + Z[z] because ], // the current cell is counted three times ++j // increment j % L ? // if it's not the last cell of this side: 0 // do nothing : // else: (j %= L * 6) ? // if it's not the last cell of the layer: d++ // increment d : // else: L++ // increment L ) // end of recursive call : // else: a // we're done: return a[] )(Z = [1]) // initial call to g with a[] = Z[] = [1] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 bytesSBCS ``` ⊢↑∘(∊⊢+∘(⍳¨⌊,⌈)¨÷∘3)⍳,⊢ ``` [Try it online!](https://tio.run/##7Zu7bhNREIZ7P4VLIow0c@bcpqYhFRLhBSKBaSKB6KiRLGMlVigi0UKVjoKC3rzJvojZY@SEWOu9npuTSOvdc2b@//vnAcanH86evfl0evb@3frj22kxu8TJWEzGtHnk5lHbR28es32Xj92@@e4b4eaDeOd48xU7Z6o5y52zqrj/f9YVd9PibivuvKe2cxdQXRPYviZEdU1QTb2iJuT@ulA96rqmbhp6@@q2ocf9ewT1PcIW/ZoeieY@0fA@yeY@qZaahj7pdhoy/jRkW2q4g66FRkJ7nQygkx10kjpqW@qk7KaVKpxW6m5aaXroO2il7a6XHF6voLteYT9PV70S/TyK4nmU7OdRaoCvh0fp/j5l4vuU7e9TPNDb06dhmFdjOq8Ww7yaPPgHeLUc7tcqvV/r4X5tPDEG@rX1w9CcD8OAH4ZBjxwPDCP8cQzlxzHSH8cozyxPHKP9sozJl2WsX5bhADyPLAv@efYAeDYAz1IgpmeelWGYVh0O0@owTGsCcgMwrQ3HtXx4XIZwXMaw7FBcFmHZTIfLZhmWzSoCPyCbdXg@m8Pnsw3PZ46UEZiPAJFCEPB@pSCIaDEIFDkrUg6CjByGoO53GoKOHodgEmVGzkOwiUIR@GGlotsTShSLbg8paXaiXHQLVknD0a1wPeR0dPtpiePR7b5lMUPifHTLfVkMgW518HGK2ynQ7UZmMgYiZzZLJnOggMyGQfE4Te00KPIbB93eb5YzZTYPugXnLIdCtzodc6pRsbw6flnMLmFdLH4Us6/F/NuTYr4oL083x4tfq@vifDEpzudHq@s/v8siHZXVSalYu/9EFBfLf4zF59VPcoTl1cmr5@X79Yvjk/V0jKPyByP3D4ov36djAoC/ "APL (Dyalog Unicode) – Try It Online") A tacit function that returns the first `n` terms of the sequence. ### Observation ``` n m | f(n,m): m consecutive integers starting at n --------------- 1 0 | 1 1 | 1 2 0 | 2 1 | 2 3 1 | 3 3 1 | 3 4 1 | 4 4 2 | 4 5 5 1 | 5 5 2 | 5 6 6 2 | 6 7 6 2 | 6 7 7 2 | 7 8 7 3 | 7 8 9 8 2 | 8 9 8 3 | 8 9 10 9 3 | 9 10 11 9 3 | 9 10 11 --------------- Flattened: 1 2 3 3 4 4 5 5 5 6 6 7 6 7 7 8 7 8 9 8 9 8 9 10 9 10 11 9 10 11 ``` Though I don't have a rigorous argument that the pattern is mathematically correct, the test cases show that the first 3000 terms agree with [Arnauld's JS answer](https://codegolf.stackexchange.com/a/201264/78410). ### How it works: the code Uses `⎕IO←0`, so `⍳ n` gives `0 1 2 .. n-1`. ``` ⊢↑∘(∊⊢+∘(⍳¨⌊,⌈)¨÷∘3)⍳,⊢ ⍝ Input: n ⍳,⊢ ⍝ Generate 0..n ( ) ⍝ For each number k... ÷∘3 ⍝ Divide k by 3 ( )¨ ⍝ For each item of above, ⌊,⌈ ⍝ Collect its floor and ceil; ⍝ (0 0)(0 1)(0 1)(1 1)(1 2)(1 2)(2 2)... ⍳¨ ⍝ For each number i, generate 0..i-1 ⍝ (2 3) -> ((0 1)(0 1 2)) ⊢+∘ ⍝ Add k to each pair of ranges (results of f(n,m)) ∊ ⍝ Enlist; collect all numbers into a vector ⊢↑∘ ⍝ Take first n numbers ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 48 bytes ``` 0i:"J_Q@q:gJJq1_J_tQ5$h@Y"&h]YsG:)&Zjyy+vt0Z)=as ``` [**Try it online!**](https://tio.run/##y00syfn/3yDTSskrPtCh0Crdy6vQMN4rviTQVCXDIVJJLSM2stjdSlMtKquyUrusxCBK0zax@P9/QwMA) Or [**verify all test cases**](https://tio.run/##y00syflvZmSl5BDhXfHfwNtKySs@0KHQKt3Lq9Aw3iu@JNBUJcMhUkktIzay2NtKUy0qq7JSu6zEIErTNrH4v8t/AA). ### Explanation This uses coordinate axes 60 degrees apart, so that cell coordinates are integer values. In addition, coordinates `(r,s)` are stored as a complex number `r+j*s`, where `j` is the imaginary unit. The code first creates `n` layers of the spiral, which is enough (for most inputs, it is much more than enough). This is done by a loop that adds one layer in each iteration. The first cell is at the origin. For each new layer, the displacements from one cell to the next are defined (in the chosen system of complex coordinates): a displacement "outward" (to create room for the layer) and then several displacements "around" to complete a turn. Once all displacements for all layers have been specified, a cumulative sum produces the cell positions. To see what is meant by "layer" and how the spiral is built, you can [**graphically depict the spiral**](https://matl.suever.net/?code=0i%3A%22J_Q%40q%3AgJJq1_J_tQ5%24h%40Y%22%26h%5DYs%27o-%27%26XG&inputs=4&version=22.2.1) with `n` layers. Note that the spiral is deformed because the plot uses orthogonal axes (real and imaginary), instead of axes with 60-degree separation. Once the spiral has been created, the first `n` cells are kept. From these, the last cell is the reference. To detect which cells are in the same row/diagonal as the reference cell, the condition is that the candidate cell should have either the same value of the *first* coordinate as the reference cell, or the same value of the *second* coordinate, or the same value of the *sum* of coordinates. ``` 0 % Push 0. This is the initial cell i:" % Input n. For each k in [1 2 ... n] J_Q % Push 1-j @q:g % Push [1 1 1 ... 1] (k-1 entries) J % Push j Jq % Push -1+j 1_ % Push -1 J_ % Push -j tQ % Duplicate, add 1: pushes 1-j 5$h % Concatenate 5 elements into a row vector: [j -1+j -1 -j 1-j] @Y" % Repeat each entry k times &h % Concatenate everything into a row vector ] % End Ys % Cumulative sum G:) % Keep first n entries. Gives a row vector of size n &Zj % Push real and imaginary parts. Gives two row vectors yy+ % Duplicate top two elements in the stack, add v % Concatenate the three row vectors into a 3-row matrix t % Duplicate 0Z) % Keep last column = % Equal? Element-wise with broadcast. Gives a true-false matrix a % Any: true for columns that contain at least one true entry s % Sum. Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes A monadic link taking an integer as input; computes the first `n` terms of the sequence. ``` ÷3Ḟ,ĊƊḶ+ ŻÇ€Fḣ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//w7cz4bieLMSKxorhuLYrCsW7w4figqxG4bij////OQ "Jelly – Try It Online") This is a port of [Bubbler's answer](https://codegolf.stackexchange.com/a/201332/75323), so be sure to upvote him as well! **How it works:** ``` ŻÇ€Fḣ Main link: monad taking integer n as input Ż Create the range [0, ..., n] Ç€ Map the auxiliar link over the range. F Flatten... ḣ and take the first n elements of that. ÷3Ḟ,ĊƊḶ+ Auxiliar link: monad taking integer k as input ÷3 Divide by 3. , Ɗ Create a pair (a, b) Ḟ Ċ with the floor and ceiling of the division. Ḷ Finally create the ranges [0, ..., a-1] and [0, ..., b-1] + and add k to each number in each range. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` ↑ṁ₁N †+¹ṁŀSe→÷3 ``` [Try it online!](https://tio.run/##yygtzv7//1HbxIc7Gx81NfpxPWpYoH1oJ5B3tCE49VHbpMPbjf///28KAA "Husk – Try It Online") ]
[Question] [ # Can Alice win the game? The game's rules are as follows. First, a finite non empty set of positive integers \$X\$ is defined. Then, Alice and Bob take turns choosing positive integers, with Alice going first. Each integer must be strictly less than the previous one, and the game ends when one of the players chooses \$1\$. Alice wins if the numbers she and Bob chose sum to a number in \$X\$, otherwise Bob wins. ### Example games Define \$X=\{20, 47\}\$. Alice chooses \$19\$, Bob chooses \$2\$, Alice chooses \$1\$. We have \$19+2+1=22\$ which is not in \$X\$ so Bob wins. --- Define \$X=\{5, 6, 7, 8\}\$. Alice chooses \$4\$, Bob chooses \$3\$, Alice chooses \$1\$. We have \$4+3+1=8\$ which is in \$X\$ so Alice wins. ### Challenge Your challenge is to write a program or function without standard loopholes which, when given a collection of positive integers \$X\$, will output or produce some consistent value if Alice has a winning strategy, and a different consistent value if Alice does not have a winning strategy. A winning strategy is a strategy which will let Alice win no matter how Bob plays. Note that in the first example game Alice did not have a winning strategy: If her first choice was any number other than \$19\$ or \$46\$ then Bob could choose \$1\$ and win. On the other hand if her first choice was \$19\$ or \$46\$ then Bob could choose \$2\$ and win. In the second example, Alice did have a winning strategy: After choosing \$4\$, she could choose \$1\$ after any of Bob's possible choices and win (or Bob could choose \$1\$ and she would win immediately). ### Input and output The input will be a collection of positive integers in ascending order, in any convenient format, given with any convenient input method. This collection represents the set \$X\$. The output will be one of two distinct values chosen by you, depending on whether or not Alice has a winning strategy with the given collection. Example IO: ``` Input -> Possible Output 20 47 -> false 5 6 7 8 -> true 5 6 7 10 -> true (Alice chooses 4. If Bob chooses 3, Alice chooses 2; otherwise she chooses 1.) 5 6 7 11 -> false (A chooses n>6, B chooses n-1. A chooses 6 or 5, B chooses 2. A chooses 4, B chooses 3. A chooses n<4, B chooses 1.) ``` ### Rules * No standard loopholes * Shortest code in bytes wins ### Note This was the result of trying to make a finite version of the [Banach Game](https://en.wikipedia.org/wiki/Banach_game). [Answer] # JavaScript (ES6), ~~89 85 83~~ 81 bytes Takes input as a set. Returns either \$0\$ or \$1\$. **Note**: Although it doesn't make sense from a theoretical perspective, the set is expected to be defined in ascending order so that the highest value appears at the end once it's converted back to an array. ``` f=(s,n=~[...s].pop(),b,t=0,g=i=>--i>n?b^f(s,i,!b,t-i)||g(i):0)=>~n?b^g``:s.has(t) ``` [Try it online!](https://tio.run/##jc69CsIwFEDh3aeIWy7chFTUSiH1IRxLpT@maaQkxQRdSl89Vnel8/mGc6@ftW8fZgzMupuKsZPUo5VzwTn3JR/dSAEbDFKglkbmjJncnptrtzCD26UwA9OkqYFMgMznT9RVlXne154GiK2z3g2KD07Tjlr1IhcVaJGUALD5EXcCyT79Jw5IjkhSJKdVKhHr2PcqvgE "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: s, // s = input set n = ~[...s] // n = opposite of the value played by the previous player, .pop(), // or -(maximum value of the set + 1) for the first iteration b, // b = flag telling whether it's Bob's turn t = 0, // t = sum of all (positive) values played so far g = i => // g is a recursive function taking a counter i <= 0 --i > n ? // decrement i; if i is greater than n: b ^ // invert the result of the following call if it's Bob's turn f( // recursive call to g: s, // pass s unchanged i, // pass the new value of i !b, // invert the flag b t - i // subtract i from the sum ) // end of recursive call || g(i) // if the above result is falsy, try a recursive call to g : // else: 0 // stop recursion ) => // ~n ? // if n is not equal to -1: b ^ g`` // invoke g with i = [''] (zero'ish) // and invert the result if it's Bob's turn : // else: s.has(t) // return true if t is in s (Alice wins), or false otherwise ``` [Answer] # [R](https://www.r-project.org/), ~~86~~ 83 bytes -1 byte by using `!m` instead of `m<1`; -1 byte by realizing I only need one long OR `||` (the first one can be a short OR `|`); -1 byte by toggling `B` and using subtraction instead of equality of booleans. ``` a=function(x,m=max(x),B=T)!m|all(x-1)-B||any(sapply(1:m,function(y)!a(x-y,y-1,!B))) ``` [Try it online!](https://tio.run/##XYxLCsMwDET3PYW9k0CGKDRNCXjjM/QCIhAo2G7oByzw3d2EQhfZDMzjzTxbE7988vy@PzIUSj5JgYIU/A1tqhIjFMfoQq2SFV6yrlGBp0T/laKVTVJSx2QDIjYBxpNAv8cMfUfmPOJehun6YwOZC5mRDHd4JLw9fAE "R – Try It Online") Exhaustive recursive search. Takes input as a vector. Outputs `TRUE` or `FALSE`. At each step, subtracts the value chosen by the player from all the values in the set `x`. Alice wins if at her turn, the updated `x` includes `1`. Bob wins if at his turn, the updated `x` does not include `1`. To this end, the function includes a boolean `B`, worth `TRUE` when Alice plays and `FALSE` when Bob plays, and checks `all(x != 1) != B`. If this condition is verified then the player wins, else the player wins if there is a move which makes the other player lose (last condition in the code, uses recursion). The initial `!m` (equivalent to `m!=0`) is there to check whether at the last move, the other player played `1` even though it is a losing move. Edit: Arnauld added an explanation to his JavaScript answer while I was typing; it seems we have similar algorithms. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 bytes ``` Ḣ’,_@ɗ€Ḣ;€CÑ€¬Ẹ 1ǬḢoḊ’Ạ=ɗ/$Ʋ? Ṁ,;0Ç ``` [Try it online!](https://tio.run/##y0rNyan8///hjkWPGmbqxDucnP6oaQ2QZw2knA9PBJKH1jzctYPL8HD7IZB4/sMdXUCVD3ctsD05XV/l2CZ7roc7G3SsDQ63/z866eHOGdaPGuYo6NopPGqYa324netwO9CIyP//o7mijQx0TMxjdbiiTXXMdMx1LBBMQwMktmEsVywA "Jelly – Try It Online") Translation of [@RobinRyder’s R solution](https://codegolf.stackexchange.com/a/196501/42248) so be sure to upvote that one! [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ ~~101~~ 100 bytes ``` f=lambda A,t=0,s=1,m=0:t<1if(s in A)^t else[any,all][t](f(A,1-t,s+i,i)for i in range(2,m or max(A))) ``` [Try it online!](https://tio.run/##TY7RCsIgAEWf6yt8m9Id6KgWIwO/QwyMthLUjelD@3rbnurtcM@Fe6clv8fYlDJIb8PjaYlClhxJCgTJu3wVbqCJuEgUu2fS@9RrGxdY743Ohg5UQdQZ6eDg2DDOxG3l2cZXTxsEsibBfqhijJVNq01rLQx0w3FsDYg@4YwWlx8K/sfCmG6/m2YX8/quqm8V1lVWvg "Python 2 – Try It Online") Returns `True`/`False` for if Alice has a winning strategy. Recurses alternating between Alice and Bob (with `t==0/1`, respectively). `s-1` is the running sum of choices so far; and `m-1` is the maximum integer value allowed for a player to choose. If `s` is in `A` and it's Alice's turn, she wins by choosing `1`. If `s` is **not** in `A` and it's Bob's turn, he would choose `1` and Alice loses. In both cases, that would stop the recursion. Otherwise, if `m==0`, then this is Alice's first turn; and she cannot win if she chooses a value greater than or equal to `max(A)`. If it is Alice's turn, then she can win if there is `any` valid integer choice that eventually ends up winning. Conversely, on Bob's turn, Alice wins only if none of Bob's possible choices guarantee eventually in a loss for Alice; which is to say that Alice wins on Bob's turn only if `all` his choices eventually yield an Alice win. ]
[Question] [ The task is to write a radiation-hardened irradiator. What do I mean by that, exactly? An irradiator is a program that, when given a string as input, will output all possible versions of the string with one character removed. For example, given the input `Hello, world!`, the program should output: ``` ello, world! Hllo, world! Helo, world! Helo, world! Hell, world! Hello world! Hello,world! Hello, orld! Hello, wrld! Hello, wold! Hello, word! Hello, worl! Hello, world ``` An irradiator, however, must be protected from its radiation, so the irradiator you write must also survive when put through itself. That is, when any single byte of your program is removed, the program must still function properly. ## Test cases ``` abc -> bc; ac; ab foo bar -> oo bar:fo bar:fo bar:foobar:foo ar:foo br:foo ba source -> ource;surce;sorce;souce;soure;sourc; ``` ## Specifications * You may take input by any acceptable method by our [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The output may be either a list of strings or a printed list delimited by a character or group of characters. A trailing delimiter is acceptable * The output may be in any order as long as it contains all of the possible versions * Duplicate entries (such as the two `Helo, world!`s in the first example) may be filtered out, but this is not necessary * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 26 bytes ``` æIg<ùˆ\æIg<ùˆ\æIg<ùˆ¯¯{Å`s ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8DLPdJvDO0@3xWBhHVp/aH314daE4v//PVJzcvJ1FMrzi3JSFAE "05AB1E – Try It Online"), or [try all irradiated versions](https://tio.run/##rdAxCsIwGMXxPcfo5hBPEA@QCzhlaIUSBLFDilA7t/dwCW5ZRMj6fWMP9YmDUKjUN7i94ccb/k2oDsdapFDWG87T6DguFiVKPQ9lUBwxZTHlMWUgxBlC04gpB6FlkO/KYspjykBoHmQFzYKsKgehT5BfymLKY8pAiDOE3l//Q5Qw1UOIB0yVqqAn3SjS/dJt9zt6bJxIW4dWtD43@lRduxc "05AB1E – Try It Online"). The shortest irradiator I could find is 5 bytes: ``` æ # powerset of the input Ig # length of the input < # - 1 ù # elements of a with length b ``` The idea is to repeat that 3 times, then do majority voting: ``` æIg<ù # irradiate ˆ # add the result to the global array \ # pop (in case the above instruction gets irradiated) æIg<ùˆ\ # idem æIg<ùˆ # no pop, it's okay to dirty the stack at this point ¯ # push global array ¯ # and again, so at least one goes through { # sort Å # conveniently ignored by the parser ` # dump s # swap # and implicitly output ``` `Å` is a prefix for 2-byte commands, but there's no `Å`` command, which is why the `Å` gets ignored. We'll need it later, though. Sorting makes sure the majority vote is in the middle of the array. Dumping then swapping gets that value to the top of the stack. Any irradiation in the initial part only results in an error in the global array, which gets solved by the majority vote. Irradiations in the final `{Å`s` bit are much trickier to reason about: * `Å` is ignored anyway, so it's okay to irradiate it * If the backtick is irradiated, `Å`s` becomes `Ås`, which is the "get middle of the array" extended command. * If `{` or `s` are irradiated, that means nothing else is, so the global array is the same value three times. In that case we don't need sorting/swapping, any value will work. [Answer] # 8086 machine code (MS-DOS .COM), 83 bytes Runnable in DOSBox or your favourite steam-powered computing engine. The string to irradiate is given as a command line argument. Binary: ``` 00000000 : EB 28 28 8A 0E 80 00 49 BD 83 00 B4 02 51 8A 0E : .((....I.....Q.. 00000010 : 80 00 BE 82 00 AC 39 EE 74 04 88 C2 CD 21 E2 F5 : ......9.t....!.. 00000020 : 59 45 B2 0A CD 21 E2 E5 C3 90 EB D7 D7 8A 0E 80 : YE...!.......... 00000030 : 00 49 BD 83 00 B4 02 51 8A 0E 80 00 BE 82 00 AC : .I.....Q........ 00000040 : 39 EE 74 04 88 C2 CD 21 E2 F5 59 45 B2 0A CD 21 : 9.t....!..YE...! 00000050 : E2 E5 C3 : ... ``` Readable: ``` cpu 8086 org 0x100 jmp part2 db 0x28 part1: mov cl, [0x80] dec cx mov bp, 0x83 mov ah, 0x02 .l: push cx mov cl, [0x80] mov si, 0x82 .k: lodsb cmp si, bp je .skip mov dl, al int 0x21 .skip: loop .k pop cx inc bp mov dl, 10 int 0x21 loop .l ret nop part2: jmp part1 db 0xd7 mov cl, [0x80] dec cx mov bp, 0x83 mov ah, 0x02 .l: push cx mov cl, [0x80] mov si, 0x82 .k: lodsb cmp si, bp je .skip mov dl, al int 0x21 .skip: loop .k pop cx inc bp mov dl, 10 int 0x21 loop .l ret ``` # Rundown The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a short jump, and so is only two bytes long, where the second byte is the displacement (i.e. distance to jump, with sign determining direction). We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen. The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive one byte off the mark. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden. For both jumps, we duplicate the displacement byte, making each jump part 3 bytes long. This ensures that irradiation in one of the two last bytes will still make the jump valid. Irradiation in the first byte will stop the jump from happening at all, since the last two bytes will form a completely different instruction. Take the first jump: ``` EB 28 28 jmp +0x28 / db 0x28 ``` If either of the `0x28` bytes are removed, it will still jump to the same place. If the `0xEB` byte is removed, we will instead end up with ``` 28 28 sub [bx + si], ch ``` which is a benign instruction on MS-DOS (other flavours might disagree), and then we fall through to code 1, which must be clean, since the damage was in jump 1. If the jump is taken, we land at the second jump: ``` EB D7 D7 jmp -0x29 / db 0xd7 ``` If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The duplicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. If we either land one byte off (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the two remaining bytes will also here be benign: ``` D7 D7 xlatb / xlatb ``` Whichever the case, if we end up executing those two instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe. ## Testing The following program was used to automatically create all versions of the .COM file. It also creates a BAT file that can be run in the target environment, which runs each irradiated binary, and pipes their outputs to separate text files. Comparing the output files to validate is easy enough, but DOSBox does not have `fc`, so it was not added to the BAT file. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fin, *fout, *fbat; int fsize; char *data; if (!(fin = fopen(argv[1], "rb"))) { fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]); exit(1); } if (!(fbat = fopen("tester.bat", "w"))) { fprintf(stderr, "Could not create BAT test file.\n"); exit(2); } fseek(fin, 0L, SEEK_END); fsize = ftell(fin); fseek(fin, 0L, SEEK_SET); if (!(data = malloc(fsize))) { fprintf(stderr, "Could not allocate memory.\n"); exit(3); } fread(data, 1, fsize, fin); fprintf(fbat, "@echo off\n"); for (int i = 0; i < fsize; i++) { char fname[512]; sprintf(fname, "%03d.com", i); fprintf(fbat, "%s Hello, world! > %03d.txt\n", fname, i); fout = fopen(fname, "wb"); fwrite(data, 1, i, fout); fwrite(data + i + 1, 1, fsize - i - 1, fout); fclose(fout); } free(data); fclose(fin); fclose(fbat); } ``` ]
[Question] [ Let's start by re-defining a **reflection** of a character in a 2-d array of characters: > > Given a square 2-d array of characters with distinct lowercase alphabetical letters, define a reflection of a letter in the matrix as swapping it with the character directly across from it through the center of the square. > > > Thus, a reflection of the letter `c` in ``` abcde fghij klmno pqrst uvwxy ``` would result in the configuration ``` abwde fghij klmno pqrst uvcxy ``` because the `c` and the `w` have been switched. Some more examples (with the same original configuration as above): > > Reflecting the character `e` would form > > > ``` abcdu fghij klmno pqrst evwxy ``` > > Reflecting the character `m` would make > > > ``` abcde fghij klmno pqrst uvwxy ``` > > Reflecting the character `b` would form > > > ``` axcde fghij klmno pqrst uvwby ``` ## The Challenge Given a 2-d array of characters with distinct lowercase letters, go through each character in a given string and "reflect" it in the matrix. *Clarifications: The letters in the string are from `a-z`, the letters are unique, and the array is at least 1x1 and at most 5x5 (obviously, as there are only 26 characters in the English alphabet.)* The characters in the string are guaranteed to be in the 2-d array. The string is at most 100 characters long. ## Input An string `s`, an integer `N`, and then a `NxN` array of characters. ## Example Input: ``` ac 2 ab cd ``` Output: ``` dc ba ``` \*Reason: First, reflect the `a` with the `d`. Then, reflect the `c` with the `b` because `c` is the second letter in the input string. --- ## Scoring * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Current Winner ``` <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 = 163084; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Python 2](https://docs.python.org/2/), 76 bytes ``` lambda s,a:[a[[i,~i][(s.count(c)+s.count(a[~i]))%2]]for i,c in enumerate(a)] ``` [Try it online!](https://tio.run/##PYk7DgIhFAD7PQWNASKx2NLEkyDFgwUXXR7IR93Gq6MmaqaZzKS1zhHH7g7HvkDQE5AiYC9BSi@eXklWdiY2rMzw7U9Bvg/nm1EpFzPxwhCPxGILNkO1DLjqKXusxDEK5gMVFLSZKB@G/zE26G@37jT782UJGNM1l9pu98dKeX8B "Python 2 – Try It Online") Takes input: * `s`: string * `N`: ignored * `a`: joined string of chars Returns a flat list of chars --- If I *have* to take the array as a list: # [Python 2](https://docs.python.org/2/), ~~111~~ ~~108~~ ~~107~~ 104 bytes ``` lambda s,n,a:[[x[sum(map(s.count,x))%2]for i in range(n)for x in[[a[j][i],a[~j][~i]]]]for j in range(n)] ``` [Try it online!](https://tio.run/##Tc7LCsIwEAXQvV@RjUwLg4uCG8EvGbOYvjTVpLUPrRt/veZSERM4XGZuIN1rvLQhW@rjabmpz0s1AwfWg8gsw@QTr10y7Ip2CiPPabrNbN32xhkXTK/hXCUhxWCOAxGVxoqzrPKO4e1sPNg2/3W7dL0Lo6kT0gKXOGMRUmLKybJQnFBJ1qabza9aVD4n3n@LJjYjBShBFR8aoRr5DC7AgWZdXZFvwIMA2nXVId9BDwYwrqsJ@QGeYAYvfG35AA "Python 2 – Try It Online") Takes input: * `s`: string * `n`: int * `a`: 2D lists of chars Returns a 2D list of chars [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~85~~ ~~68~~ 66 bytes Using `eval`, with a loop inside it saved a lot of bytes! I got the inspiration from [this answer](https://codegolf.stackexchange.com/a/163111/31516) by [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)! ``` @(c,N,A)eval"for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A" ``` [Try it online!](https://tio.run/##DcXdCsIgGADQV4ndqPQlFHQ1Pkh2vxcYC8yfMp2utZY9vXluTlKr3EyxyDkvF6qgB8HMJkNj07LrUIGgNriZesZQUI9DRuuipgKxY9BfT/vjIY@sNVGDaIqlRGoCZxiIvCltSEvs/eGedR@mmOrza3mv9c/2zT8ysvIH "Octave – Try It Online") ### Explanation: ``` f=@(c,N,A) % Anonymous function that takes the three input variables eval"... % Evaluate the string and run it: for C=c, % Loop over the character list 'c' .. x=find(A==C) % Find the index where the character C is in A, and store it as 'x' .. k=[x,N^2+1-x] % Create a vector with the index of C, and the index of its reflection A(flip(k))=A(k) % Swap the elements in these positions end % End loop A" % Display the new 'A' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` FW;Ṛi,C$¥¦/ṁḷY ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//Rlc74bmaaSxDJMKlwqYv4bmB4bi3Wf///1snYWInCiwnY2QnXf9hYw "Jelly – Try It Online") Full program. Explanation: ``` FW;Ṛi,C$¥¦/ṁḷY Main link. Input: ['ab','cd'] (left), 'ac' (right). FW **F**latten and **W**rap it in a list. Current value = ['abcd']. ; Concatenate it with right argument. ['abcd','a','c'] / Reduce from left: Ṛ ¦ Apply **Ṛ**everse at... i ¥ the index (of right argument in left argument)... ,C$ and its complement index. ``` The last operation needs more explanation. Denote f = `Ṛi,C$¥¦`, then for value `['abcd','a','c']` it computes `('abcd' f 'a') f 'c'`, which expands to: ``` Ṛi,C$¥¦ Function **f**. Assume left argument = 'abcd' and right argument = 'a' Ṛ First, compute the reverse. Get 'dcba'. i ¥ To compute the indices to apply to, first the index of 'a' in 'abcd' is ('abcd' i 'a') = 1. (first index) ,C$ Then pair with (1 C) = 0. (last index) ¦ Apply 'dcba' to 'abcd' at indices 0 and 1: a**bc**d **d**cb**a** ^1 ^0 ==== dbca ``` [Answer] # [R](https://www.r-project.org/), ~~74~~ 61 bytes -13 bytes thanks to Giuseppe. ``` function(s,n,m){for(x in s)m[v]=rev(m[v<-(i=x==m)|rev(i)]);m} ``` [Try it online!](https://tio.run/##FY69UsMwEAZ7PUVG1d3MR7pU5FqegI5JISsSFlhycpJ/MsCzG6fb2W1WtyhbnIpvaSxUUZD5J45K6yGVQ@X8MV9Ew0w7nF8oySqS@fdpEl/4Nf9tkaYypNqoNq23ITWyPuTOwlpmnODqMbumaSUN7nr0daYm1btCS@@aWHWLZfR7CypvjO6h4yLvzMahg8cVwUR8okfCl/nGgLxvjuaGOxQVzUyYsWDFw2z/ "R – Try It Online") Inputs a vector of characters to search as `s`, size of the matrix as `n` and matrix itself as `m`. If it is absolutely necessary to take the first argument as *string*, that would pretty much spoil the fun. [Answer] # Java 10, ~~126~~ ~~123~~ ~~116~~ 114 bytes ``` (s,n,m)->{for(var c:s)for(int N=n*n,i,j;N-->0;)if(m[i=N/n][j=N%n]==c){m[i][j]=m[n+~i][n+~j];m[n+~i][n+~j]=c;N=0;}} ``` Modifies the input character-matrix instead of returning a new one to save bytes. [Try it online.](https://tio.run/##fVPLbsIwELz3K1aRqtjFpJyJjFT13KgSR5SDMQYcYie1HShC6a9T59EKKKmURN4de3ZmvcnYno2z1e7Mc2YtvDGpTw8AUjth1owLSJoQYF/IFXDEt8wsUrCk2QGaQJfwKYVjv7H2r3@sY05ySEADhTOyRBOFx7PTujBozwzwqcXNuiFJqH7SRJIsTsbj2STGco3UQtLkWaeLjCaPOqWU45PP@TilaqFHX37pv1kaX0WUxwmdxHV9jjsdZbXMvY5eTutBeYdo7ozUG6@a4c6eE9ahgC0DAlocfl11IFzkTiELSbgMa3IH4h5ahXWL1G0/fpi5UEPcvipfiSByxatHXoxhR4R/2IP1ZiuzIXCXK10MgeWHsW4IrPaHz@MNeCH7@hrbvrU@ur41139x750RHXFkb6qBinKhN25L@vEAmB@tEyoqKheVnsvlGtlRMA16uDTCueN7g6B/jgyJvDz@R2EzcP38sqnCfSvusGf@n4gqJ/OoNdK46owjhvvK9fkb) **Explanation:** ``` (s,n,m)->{ // Method with the three parameters and no return-type for(var c:s) // Loop over the characters given: for(int N=n*n,i,j;N-->0;) // Inner loop over the cells of the matrix: if(m[i=N/n][j=N%n]==c){ // If the current character and matrix-value are equals: m[i][j]=m[n+~i][n+~j];m[n+~i][n+~j]=c; // Swap the values in the matrix at indices [i, j] and [n-i-1, n-j-1] N=0;}} // And stop the inner loop (go to next iteration of the outer loop) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~95~~ 93 bytes ``` (x,s,N)->{for(var c:s)for(int i=-1;++i<N;){var t=x[i];if(t==c){x[i]=x[N+~i];x[N+~i]=t;i=N;}}} ``` [Try it online!](https://tio.run/##dVJdb5swFH02v@KqUiUohLbr2yjTqk2T9jBWrY9RHlxjiBkxmW2yRhH96/TahqTqOgnJ5vqc@3HObeiOLpry97jtH1vBgLVUa/hBhQwOAfn8rZfMiE7S9rs0XFWU8YBMUG2owUPMD/CLVy1nJiDIJLtOlKB8JGRrqpYroAlMN51YHhRRFpAhIG9zOvIGmwgfjBKytlxV68intkwJOdiWaq7SHW17/rMKLWR5tbI5HaYUG0RJuABpQ3MTSmHUYa9Xqem@YPhOKboPHRG/y0u4x6oGC1s03WNsawMIwyIqAfkK@pVXQh6h88ioGXRbrqjpFOImaQBLj@FTopMiWnw6VJ0Kd1QB@6gje7dNi3xxncWxuC2y6GAfTf60FKtMVKHJcxYd7B@GivgZo9OZm0zkRTYMw0jIqbWp6qk53vINl0YDlSVs5xkV132LthGVzoa5KZ1GH95olFhZ3fjvSOKsnOXToP/0VPFZw3csPqY4eeMXQ05Wv7ZC8r9HO1At8HKhl1cZHrdoMog4RqJjniCNhzQe0niIx5CHvTZ8k3a9SV0vVXh2zuDMzq6WdnMExND4lbLTOWX/YbXS787glf/P8xAM43gz0kdW8qpei5Gymq9fAA "Java (JDK) – Try It Online") # [Java (JDK)](http://jdk.java.net/), 131 bytes ``` (x,s,n)->{for(var c:s)for(int i=~0;++i<n*n;){int a=i/n,b=i%n;var t=x[a][b];if(t==c){x[a][b]=x[n+~a][n+~b];x[n+~a][n+~b]=t;break;}}} ``` # [Java (JDK)](http://jdk.java.net/), ~~138~~ 135 bytes ``` (x,s,n)->s.forEach(c->{for(int i=~0,a=i/n,b=i%n;++i<n*n;){var t=x[a][b];if(t==(char)c){x[a][b]=x[n+~a][n+~b];x[n+~a][n+~b]=t;break;}}}) ``` # [Java (JDK)](http://jdk.java.net/), 112 bytes ``` (x,s,N)->{for(var c:s)for(var v:x.entrySet())if(v.getValue()==N-x.get(c))x.put(v.getKey(),x.put(c,N-x.get(c)));} ``` [Try it online!](https://tio.run/##jVTBbtswDD3LX0H0JK@O216bplixYVuxtRtWYJcgB8VWErm25EmKm6zIt2eUZMduu27zIbYo8vGRfEzBGjYq8vu9qGqlLRR4TtdWlOkXIe95/omZ1Q2rx1FUr@elyCArmTFww4SMHiNycgJXWrMtaL4oeWaFkiCk5XrBMh6Rtx/W0htZed1bWyRjmcXXwR2@B4yIIDBplMg7VPqEy8XXeYHGBBzkkutLYAkE23QGJnGIcBuPI7KLiKf4XouGa8hU/iK7T1NhNfTOaiGXiMD00sSBBMZ@5NaiHa2uzIVWFeLXa2RJXJ5cVDDxIdPTWVpyubQr6nKTf3CuWI2Bkj/AU8fLEB2So6F2yRtWrrlB20JpoC6vwODTMb4uHAX8OD5GzoQgbIrsaMcoWzF9ZamIsS0d8KFX7tK0LFqjjzvrK5n1ZN6peuvIuCiW4dAMWAVz3k2J567zCpg8TOMVxs@T9PQ9o6mYdT09G1TQM7mWwgpWil/9YAb6UzXXzCqNvq2iQMNkTzeJSW7j0eUjUqINQz2cm7j7bs43KZdWb@@4pXEsFrRJl9z@cI2n8WRyO9q4M83ieOMb7K8/8y2Nk2DIkoFPPN7tCXnZOxzPf0nD@f9NHq2LS3xVlhSPg/a0VffN4SWvsDgnIJ12O9VCJEEFiVfyCM5eiAQhkEmXMCiRxqlVfvHpQDuIMHPhgI9fDomBbvYxCtmuUvNTW4pOA6rfcOc8UQfjVoKZwPkV5ciDVNx6PkFodaAeXJl9cBGCixBctDoL927wHM5d4uHwvQMJv8MMmdKam1rJ/LCTqPh2pviIBVA@UA1MnIr1VMIbJH8MxayFJndbY3mVqrVNa4cewrya0O8IjnyLyPMSsTiYa87uoz9glDJIY@f@93b7PZtnOV8sV2LPsiVf/QY "Java (JDK) – Try It Online") # [Java (JDK)](http://jdk.java.net/), 70 bytes ``` (x,X,s,N)->{for(var c:s)x.put(X.get(N-x.get(c)),x.put(c,N-x.get(c)));} ``` [Try it online!](https://tio.run/##hVNNbxoxED17f8UoJ29jNsm1JKhVqrZRm7RqpCpSxMEsBrxZ7K1tCGnEb6fjj2WhIS0H7B3PPL95flPxJe9V44eNnDfaOKjwu1g4WRdfpXoQ48/czq5508@yZjGqZQllza2Fay5V9pyRkxN4bwx/AiMmtSid1AqkcsJMeCky8u7jQoUgr6@6aEKyjjtctunwI2JkBIHJUstxi0r3uJx/G1UYZOAhp8IMYMVgPyOdMIipA7hrt/dDsMzfCTd5PyPrjIQmPhi5FAZKPX7BLxCZY7/01hmppojAzdTmkSbWfhLOYRyjXoiJ0XPEbxbYByln3GC@E/MGZYKLUHl/OiycvsSjIB31PIhnpDCB4iZHed2ssL@Mo6m0qIWaullI/U@rc94gjhKPf2kyoAeqX0hpxPL63wCxaQw0vuklrxfCYmyiTSAPEotP@7icY0NvQOH2@BjVCnIRZFegNlSyVpV7OQy4JF4dTrsjfKtwut7e3MotajEXyllwuvVJp/j2MEl@dkDyrSF8jU0tp2Bbn3Qfdo1fcrt/PbegQ9FrKgT4BLQVIxC12CDmtVD41d1zpaSTvJa/O2vtzJhuhOFOG8xNUwNorw1dsTtm2U3eGzwjFbrk6Om3Nl8FVe@KqXD0prcKa5nnLMZLthPL@@sNIR2PBN@xaNnisSnaAY1vx7z5WGyYxdeHHpzt2OY7TlDA8lp7p6J6AfY1B@27ZxchaaIfPZOuuIrFVSyuktok/O2WY2H3hhIVNWNhQlaA8soJeJvmocAs83SLCuURjsgJUOE1@@kHgOZwcREalnAMVcp5jgu5fbJo6EIvXNH462PhF4E@xOwjOIr@x9/ICP6QPrzjSXaAdUjKDuDWirazss7Wmw0flWMxmc4k7oTkfwA "Java (JDK) – Try It Online") All of these code snippets function in essentially the same way since only difference between them is the type of the variable x. The first has it set as `char[]`, the second as `char[][]` and the third as `List<Object>`. The fourth and fifth are quite unique solutions, and so I'll go over the specific details of them last. As somewhat of a side note, the first of these three entries inputs the total quantity of elements in the initial array (i.e., `N = n * n`). Here's how the first three entries work: ``` (array, reflect, size) -> { // Initializes lambda expression for (char c: reflect) // Loops through soon-to-be reflected characters for (int i = 0; i < size; i++) // Loops through elements in array if (array[i] == c) // Checks if this element should be reflected { var temp = array[i]; // Reflects elements array[i] = array[size - 1 - i]; array[size - 1 - i] = temp; break; // Goes on to reflect next character } }; ``` I feel like these entries can be further golfed with use of nested functions and lambda expressions, but I have been unable to do so thus far. I instead went on to create the fourth entry, as shown below in all of its golfed glory: ``` (x,s,N)->{ for(var c:s) for(var v:x.entrySet()) if(v.getValue()==N-x.get(c)) x.put(v.getKey(),x.put(c,N-x.get(c))); } ``` The fifth is quite similar. These particular lambda expressions are unique, in the sense that `s` is an `Object[]` and N is one less than the total quantity of elements in the initial array. But most importantly, `x` is a `LinkedHashMap<Object, Integer>`. Well, what's so special about all of that? The idea behind changing all of these things was to allow for a short for loop going over the elements of `s`, thus ridding the program of tightly packing for loops with ugly garbage. It essentially simplified things for the code and I. Unfortunately, doing so would mean indexing the initial array to find the index of each element, contradicting its intended purpose. It was at that moment that I realized that replacing the array input with some `Map` subclass would allow me to use the elements to be reflected as a way to index the elements in the array directly. So I did the only logical solution: map half of the array elements to their corresponding pairs to simplify reflection. Didn't work, big surprise. But I didn't give up and mapped each element to its corresponding array index and the idea was looking good. Next problem: given an element in the array, finding its reflective pair couldn't be done without more for loops, if statements and precious bytes altogether. But a more immediate problem came from this, too: printing the array. In retrospect, it would've been possible to instead input a copy of the array and use the original's elements to get the key-value pairs, but I found a better solution: the `LinkedHashMap`. This class contains the nested class `Entry`, which allows for much simpler key-value pairing, which just so happened to be at the root of both problems. So now that I've gone over why I made these changes and how the base of this setup should work, I'll use what we've learned to give the code some more context: ``` (x,s,N)->{ // Initializing lambda expression for(var c:s) // Looping over elements to be reflected for(var v:x.entrySet()) // Looping over key-value pairs... if(v.getValue()==N-x.get(c)) // ...until element opposite current is found x.put(v.getKey(),x.put(c,N-x.get(c))); // Swapping elements } ``` You should note that the line involving the actual reflection has a nested `put` method, because it returns the key that was changed, thus removing an extra variable initialization for the swapping process. But what about my *fifth* entry? Am I taking this simple challenge too seriously? **Yes!** This solution has a very low byte count, because it's the same as the fourth, but with an extra input: `X`. Unlike `x`, which is the array converted to a `LinkedHashMap<Object, Integer>`, `X` is the reverse: a `LinkedHashMap<Integer, Object>`. This allows us to skip searching for any element's index and instead just look it up in `X`, thus removing a lot of code. As a final side note, the only entries that allow more characters to be reflected than there are in the initial array are the fourth and fifth. Will this be the end? Thanks to **@KevinCruijssen** for the inspiration and for saving two bytes from my first entry. [Answer] # C, ~~84~~ ~~86~~ 83 bytes +2 bytes to use a temporary variable instead of chained XOR when swapping variables, allowing for the central letter to be swapped with itself -3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` f(s,n,a,i,j,t)char*s,*a,*i;{for(;*s;*i=t)i=index(a,*s++),t=a[j=a-i+n*n-1],a[j]=*i;} ``` [Try it online!](https://tio.run/##TZDdTsMwDIWvm6ewioba1EUMJG668CJbL7L0zxF4qAkIaeqzF6dDiIvIx@eTfay4enRuvSN2b59dD4cQO7o8TK/qvzUTj@KtQxGQ0SKhx1i6yc46oLaoqbkOl7lodGg0mViSIe7670JQqKoSo7FHb2xNFWuu9y1K2xoZW1biCO@WuEjCzqND2BZr0V@luqosAUYgBN@oLEEIx6eXFsGmIl5wloci34UT7zp5IUcICPcyZUvhv3dvUs4kMPDYAMEBWIocCBKzIX9D/oa8IAHZh3xATAEuT6EEGhgq8G3a@EdPnKd@Uct6Hnv1rOzZdf0wTvQD "C (gcc) – Try It Online") Un-golfed: ``` f(s,n,a,i,j,t) char*s,*a,*i; { for(;*s;*i=t) { //Loop while end of s hasn't been reached i=index(a,*s++); //i = pointer to char in a with value *s, then get next char s t=a[j=a-i+n*n-1]; //j = index of char in a which is opposite i, then swap i and a[j] a[j]=*i; } } ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~122~~ 111 bytes ``` lambda l,n,A:[[[A[a][b],A[~b][~a]][sum(map(l.count,[A[a][b],A[~b][~a]]))%2]for b in range(n)]for a in range(n)] ``` [Try it online!](https://tio.run/##bY69CoMwFEZ3n@IuJQkEh7oVHHyO2ww3ajQlXsUfsIuvnvoDhUK3w/nO8A3vue05iy5/xkCdrQiCZl08ELFAMmiNLnCzBjcyBqelkx0NMqRlv/Cs/zRK3e7G9SNY8AwjcVNLVqehHxNXyAGDn2YpyJZC6Yur2n25ab1QJkmO1O2Z0JBpWFUyjJ73/ckiffWez1Pi4mNXKn4A "Python 3 – Try It Online") Returns a 2D array of chars. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 96 bytes ``` +`^(.)(.*¶(.|¶)*)((.)((.|¶)*))?\1(?(4)|(((.|¶)*)(.))?)((?<-3>.|¶)*$(?(3).)) $2$11$9$1$6$5$12 1A` ``` [Try it online!](https://tio.run/##K0otycxL/P9fOyFOQ09TQ0/r0DYNvZpD2zS1NDVAAjCOpn2MoYa9holmjQZcDCivaQ9UYm@ja2wHEVMBqjHWBIpzqRipGBqqWKoYqpipmKoYGnEZOib8/5@amJzBlZiUzJWSmsaVnpEJAA "Retina 0.8.2 – Try It Online") Takes the string `s` and the array of characters as a newline-delimited string without the integer `N`. Explanation: Each character `c` of `s` is processed in turn. The regex matches two positions equidistant from the ends of the array, of which one is `c` and the other is its mirror `m`. These characters are swapped and `c` is removed from `s`. ``` +` ``` Processes each character of `s` in turn. ``` ^(.) ``` `$1` captures `c`. ``` (.*¶(.|¶)*) ``` `$3` captures a stack of characters in the array prefixing one of `c` or `m`. `$2` captures the rest of `s` plus all of these characters. ``` ((.)((.|¶)*))? ``` If `m` precedes `c`, `$4` has a value, `$5` captures `m` and `$6` captures the characters between `m` and `c`. `$7` captures `$6` as a stack but its value is not used. ``` \1 ``` `c` is now matched in the array itself. ``` (?(4)|(((.|¶)*)(.))?) ``` If `m` wasn't already matched, then `$8` optionally captures a value, in which case `$9` captures the characters from `c` to `m`, `$10` captures `$9` as a stack which is unused and `$11` captures `m`. The value is optional in case `c` and `m` are the same character. ``` ((?<-3>.|¶)*$(?(3).)) ``` `$12` captures the characters suffixing the other of `c` and `m`. A balancing group is used to ensure `$12` is as long as `$3` was deep, i.e. the prefix and suffix are the same length. ``` $2$11$9$1$6$5$12 ``` The pieces are then put back together - first the rest of `s` and the prefix of the array, then if `c` preceeded `m` then `m` then the middle, then `c`, then if `m` preceeded `c` then the middle then `m`, then the suffix. ``` 1A` ``` Now that `s` is empty it is deleted. [Answer] # JavaScript, 85 bytes Takes string `S` and an array `A` as joined string. ``` ([...S],[...A])=>S.map(c=>[A[j],A[i]]=[A[i=A.indexOf(c)],A[j=A.length+~i]])&&A.join`` ``` ``` f= ([...S],[...A])=>S.map(c=>[A[j],A[i]]=[A[i=A.indexOf(c)],A[j=A.length+~i]])&&A.join`` console.log( f('abcd','ac') ) ``` [Answer] # [Perl 5](https://www.perl.org/) `-lpF`, 97 bytes ``` $i=0|<>;$_=join'',<>;s/\W//g;for$k(@F){/$k/g;$t=substr$_,-pos,1;eval"y/$t$k/$k$t/"}s%.{$i}%$&$/%g ``` [Try it online!](https://tio.run/##DcoxDoIwFADQvccgH9EEKAxMiHFic3YxIaCApZXW/oIQ5OpWxpc8VWuRWAssi77HUwpF1knWe56/AentSmmbNlID35/zw0KBbwaT4VCh0VD4gZLox2k9lsKZKZgtAAdDnRXdcAG2urAD6rbWTowkpKzuj5o07ZN1hItXL4l6azRkGD/T/JPKMNmjDS5JGMWRDYTK/w "Perl 5 – Try It Online") ]
[Question] [ ## Challenge Given a time and a timezone as input, output the time in that timezone. ## Time The time will be given in 24 hour format like so: ``` hh:mm ``` Where hh is the two digit hour and mm is the two digit minute. Note that the hour and the minute will always be padded with zeroes like so: ``` 06:09 ``` All the times given are at UTC+00:00. *The hours in your output do not have to be padded wih zeroes but your time it must be in 24 hour format* ## Timezone The timezone will be given in the following format: ``` UTC±hh:mm ``` Where ± is either going to be a + or a - and hh, is the two digit hour and mm is the two digit minute (again, these will be padded with zeroes). To find the time in that timezone, you either add (if the symbol is +) or subtract (if the symbol is -) the time after the UTC± from the inputted time. For example, if the input was `24:56` and `UTC-02:50`, you would subtract 2 hours and 50 minutes from 24:56: ``` 24:56 02:50 - ----- 22:06 ``` The output would be `22:06`. ## Examples ### Chicago ``` Input: 08:50 and UTC-06:00 Output: 02:50 ``` ### Kathmandu ``` Input: 09:42 and UTC+05:45 Output: 15:27 ``` ### Samoa ``` Input: 06:42 and UTC+13:00 Output: 19:42 ``` ### Hawaii ``` Input: 02:40 and UTC-10:00 Output: 16:40 ``` Note that this has gone to the previous day. ### Tokyo ``` Input: 17:25 and UTC+09:00 Output: 02:25 ``` Note that this has gone to the following day. ## Rules You must not use any built in date functions or libraries. Assume all input will be valid times and time offsets. The timezone will be in the range `UTC-24:00` to `UTC+24:00` inclusive. In the case of *half past midnight*, the correct representation should be `00:30`, ***not*** `24:30`. ## Winning The shortest code in bytes wins. [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/), 45 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ### Expression Takes two strings as right argument. ``` 24 60⊤∘⍎∘⍕('+-'∩⍕),'/',(0 60⊥2⊃':'⎕VFI ¯5∘↑)¨ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@///f8ijtglGJgpmBo@6ljzqmPGotw9MTtVQ19ZVf9SxEsjU1FHXV9fRMAArWmr0qKtZ3Ur9Ud/UMDdPhUPrTUHq2yZqHlrBFaKgbmBhZWqgrqAeGuKsa2BmZQBkP@qdq@CckZmcmJ4PVmFpZWIEUaFtYGplYgpR4Z1YkpGbmJdSClZjhlBjaAw3JTgxNz8RLG9kZQKzxdAALu@RWJ6YmQlSYGhuZWQKs8QSriAkP7syHwA "APL (Dyalog APL) – TIO Nexus") ### Explanation `24 60⊤` the number-to-base-*a*24*b*60 conversion `∘` of `⍎` the evaluation `∘` of `⍕` the formatted (i.e. flattened with separating spaces) `('+-'∩⍕)` intersection of "+-" and the formatted input (this extracts the plus or minus) `,` followed by `(`...`)¨` the following for each of the inputs (the time and the offset)  `0 60⊥` the *a*∞*b*60-to-number conversion of  `2⊃` the second element of  `':'⎕VFI` the, using colon as field separator, **V**erified and **F**ixed **I**nput of  `¯5∘↑` the last five characters ("hh:mm") ### Step-by-step on "17:25" and "UTC+09:00" The left-side expression on the right side data, gives the data of the next line. ``` '17:25' 'UTC+09:00' / / \ \ (...)¨ applies the function train to both inputs / / \ \ ¯5∘↑ '17:25' 'UTC+09:00' ':'⎕VFI '17:25' '09:00' 2⊃ (1 1)(17 25) (1 1)(9 0) 0 60⊥ 17 25 9 0 1045 540 \ \ / / This is where ¨ stops, and execution continues on the resulting list \ \ / / '/', 1045 540 ('+-'∩⍕), '/' 1045 540 ⍕ '+' '/' 1045 540 ⍎ '+ / 1045 540' 24 60⊤ 1585 2 25 ``` [Answer] # C, 109 bytes ``` a,b,c;f(char*t,char*z){for(c=0;z[3];t=z+=3)sscanf(t,"%d:%d",&a,&b),c+=b+a*60;printf("%d:%02d",c/60%24,c%60);} ``` Invoke as follows: ``` int main() { f("17:25", "UTC+09:00"); } ``` [Answer] ## JavaScript (ES6), 101 bytes ``` (t,z,g=s=>+(s[3]+s[7]+s[8])+s.slice(3,6)*60,m=g('UTC+'+t)+g(z)+1440)=>(m/60%24|0)+':'+(m/10%6|0)+m%10 ``` Would be 121 bytes if I padded the hours. [Answer] # Python 2, 129 bytes ``` def T(t,a):f=[int.__add__,int.__sub__]["-"in a];m=f(int(t[3:5]),int(a[7:9]));print`f(int(t[0:2])+m/60,int(a[4:6]))%24`+":"+`m%60` ``` Call as `T("02:45", "UTC-05:33")` [Answer] # Python 2, 84 bytes ``` def f(t,z):i=int;r=60*(i(t[:2])+i(z[3:6]))+i(t[3:])+i(z[3]+z[7:]);print r/60%24,r%60 ``` All test cases are at [**ideone**](http://ideone.com/vsxuOa) Output format is space separated, with no leading zeros. [Answer] # Java 201 bytes ``` String T(String t,String z){return(24+Integer.valueOf(t.substring(0,2))+Integer.valueOf((String)z.subSequence(3,6)))%24+":"+(60+Integer.valueOf(t.substring(3,5))+Integer.valueOf(z.substring(7,9)))%60;} ``` Called as T("12:00", "UTC+02:40") Unglolfed for the logic, ``` String T(String t, String z) { int i = (24 + Integer.valueOf(t.substring(0, 2)) + Integer.valueOf((String) z.subSequence(3, 6))) % 24; int j = (60 + Integer.valueOf(t.substring(3, 5)) + Integer.valueOf(z.substring(7, 9))) % 60; return i + ":" + j; } ``` Any help to get it under 200 would be appreciated! [Answer] ## Javascript (ES6), ~~93~~ 92 bytes ``` t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10 ``` ### Test cases ``` let f = t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10 console.log(f("08:50 UTC-06:00")); // 2:50 console.log(f("09:42 UTC+05:45")); // 15:27 console.log(f("06:42 UTC+13:00")); // 19:42 console.log(f("02:40 UTC-10:00")); // 16:40 console.log(f("17:25 UTC+09:00")); // 2:25 ``` [Answer] ## Ruby, 95 bytes ``` g=->s{"60*"+s.scan(/\d+/).map(&:to_i)*?+} f=->t,z{r=eval(g[t]+z[3]+g[z]);print r/60%24,?:,r%60} ``` ## Usage ``` f[gets,gets] ``` ### Inputs(example) ``` 08:50 UTC-06:00 ``` [Answer] # Java ~~156~~ ~~150~~ ~~149~~ ~~147~~ 142 bytes ``` t->z->{Integer H=100,T=H.valueOf(t.replace(":","")),Z=H.valueOf(z.replace(":","").substring(3)),c=(T/H+Z/H+24)*60+T%H+Z%H;return c/60%24+":"+c%60;} ``` ## Test cases & ungolfed ``` import java.util.function.BiFunction; public class Main { public static void main(String[] args) { BiFunction<String,String,String> f = (t,z)->{ Integer H = 100, // Hundred, used several times, shorter as variable T = H.valueOf(t.replace(":","")), // as int (HHMM) Z = H.valueOf(z.replaceAll("[UTC:]","")), // as int (-HHMM) c = (T/H + Z/H + 24) * 60 + T%H + Z%H; // transform into minutes return c/60%24+":"+c%60; }; test(f, "08:50", "UTC-06:00", "02:50"); test(f, "09:42", "UTC+05:45", "15:27"); test(f, "03:42", "UTC-05:45", "21:57"); test(f, "06:42", "UTC+13:00", "19:42"); test(f, "02:40", "UTC-10:00", "16:40"); test(f, "17:25", "UTC+09:00", "02:25"); } private static void test(BiFunction<String,String,String> f, String time, String zone, String expected) { // Padding is allowed. Make sure the padding is skipped for the test, then. String result = String.format("%2s:%2s", (Object[])f.apply(time, zone).split(":")).replace(" ","0"); if (result.equals(expected)) { System.out.printf("%s + %s: OK%n", time, zone); } else { System.out.printf("%s + %s: Expected \"%s\", got \"%s\"%n", time, zone, expected, result); } } } ``` ## Shavings * 150 -> 149: `a/H*60+b/H*60` -> `(a/H+b/H)*60` * 149 -> 147: `(T/H+Z/H)*60+1440` -> `(T/H+Z/H+24)*60`. * 147 -> 142: `z.replace(":","").substring(3)` -> `z.replaceAll("[UTC:]","")` [Answer] # C# 214 205 183 Bytes ``` string f(char[]t,char[]u){int s=~(u[3]-45),z=48,m=(t[3]-z)*10+t[4]-z+((u[7]-z)*10+u[8]-z)*s,h=(t[0]-z)*10+t[1]-z+((u[4]-z)*10+u[5]-z)*s+m/60+(m>>8)+24;return$"{h%24}:{(m+60)%60:D2}";} ``` 205 byte version ``` string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int s=u[3]<45?1:-1,m=P(T[1])+P(u.Substring(7))*s,h=P(T[0])+P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24}:{(m+60)%60:D2}";} ``` Ungolfed ``` string f(char[] t, char[] u) { int s = ~(u[3]-45), z = 48, m = (t[3] - z) * 10 + t[4] - z + ((u[7] - z) * 10 + u[8] - z) * s, h = (t[0] - z) * 10 + t[1] - z + ((u[4] - z) * 10 + u[5] - z) * s + m / 60 + (m>>8) + 24; return $"{h % 24}:{(m + 60) % 60:D2}"; } ``` Original 214: ``` string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int h=P(T[0]),m=P(T[1]),s=u[3]<45?1:-1;m+=P(u.Substring(7))*s;h+=P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24:D2}:{(m+60)%60:D2}";} ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 40 bytes ``` r{':/60b}:F~r3>(\F\~1440,=60b{s2Te[}%':* ``` [Try it online!](https://tio.run/nexus/cjam#Lco/C8IwFATwvZ/CRSr@IS@vedFe0UXoKLS2k3URXAVxDMlXj6lxOfjd3fui3FUFdA36JvauhLL08GhDV51WUzsFbQxtj6l0Hx6eN78ssY73l1eRCGIX43DeEUOooEPKbAtKrmF49oYERorU/q2r384w@a9ptt6DJf/r5C8 "CJam – TIO Nexus") (As a test suite.) ### Explanation ``` r e# Read first input (time). {':/60b}:F e# Define a function F, which splits a string around ':' and e# treats the two elements as base-60 digits. ~ e# Run that function on the first input. r3> e# Read the second input and discard the 'UTC'. ( e# Pull off the +-. \F e# Apply F to the timezone offset. \~ e# Execute the + or - on the two amounts of minutes. 1440,= e# Modulo 1440 to fit everything into the 24-hour format. 60b e# Obtain base 60 digits again. {s2Te[}% e# Convert each digit to a string and pad it to 2 decimal digits. ':* e# Join them with a ':'. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 100 bytes ``` : 59$*:, +`(\d+): $1,$1 \d+ $* T`1`0`-.+ ^ 1440$* +`10|\D 1{1440} ^(1{60})*(.*) $#1:$.2 \b\d\b 0$& ``` [Try it online!](https://tio.run/nexus/retina#LcpBDoIwEAXQ/T@FiaMpLZCZ2qLMVhMvgLvGNIRbIGfHIm4m8/7/J/PMqyL2ZLWGyyZNrlKQ1CQoP8hiyJI5N63DGxICl8hl4U96ADJvyQK8jcwdL5U1ra1AR1FqPdKYpjSC6byuzBq7w2u4N@w1MvhW7u5OubjX4Dc7jhoiSvq3XH6917DvhTfLVX3c933xFw "Retina – TIO Nexus") ### Explanation ``` : 59$*:, ``` Replaces each `:` with 59 of them and a comma as a separator. ``` +`(\d+): $1,$1 ``` Repeatedly duplicates the number in front of a `:`. So the first two stages multiply the hour-value by 60. ``` \d+ $* ``` Convert each number to unary. ``` T`1`0`-.+ ``` If there's a minus sign in the input, then this transliteration stage turns all the `1`s after it into `0`s. We're basically using `0` as a unary `-1` digit here. ``` ^ 1440$* ``` Insert 1440 `1`s (i.e. a full day). This is to ensure that the time doesn't get negative. ``` +`10|\D ``` This repeatedly removes all non-digits (i.e. the space, the `UTC`, the `+` or `-`, as well as all the `,` we've inserted) and the `10` combination, thereby cancelling positive and negative digits. This basically subtracts the second number from the first if it's negative, or adds it otherwise. ``` 1{1440} ``` Removes 1440 `1`s if possible (basically taking the result modulo 1440 to fit it into a single 24 hours). ``` ^(1{60})*(.*) $#1:$.2 ``` Decompose the number into hours and minutes by matching as many chunks of 60 digits as possible (counting the chunks with `$#1`) followed by the remaining digits (whose length is counted with `$.2`). ``` \b\d\b 0$& ``` If there are any single digits in the result, prepend a zero. ]
[Question] [ You should write a program or function which receives a string as input and outputs or returns if the input is an ASCII tree. ``` _ \/ / \_/ | | ``` ASCII trees consist of characters `/ \ | _ spaces` and `newlines`. The non-whitespace characters connect two edge points of their cells by a line segment: * `/` connects the bottom left and top right corners * `\` connects the bottom right and top left corners * `|` connects the middle points of the bottom edge and top edge * `_` connects the bottom left and bottom right corners and the middle point of the bottom edge (Note that this means that `|` can only connect with `|` or `_` but not with `/` or `\`.) An ASCII picture is called a tree if the following rules apply: * Exactly one point (the root) of exactly one character touches to the bottom edge of the last row. * You can reach any point of any line segment by: + starting from the root + using only the line segments + never going into a downward direction (not even sideways downward) ## Input * A string consisting of the characters `/ \ | _ space` and `newline` containing at least one non-whitespace character. * You can choose of two input format: + No unnecessary whitespace around the tree (as seen in the examples). + No unnecessary whitespace around the tree (as seen in the examples) except spaces on the right side of the rows to make all rows the same length. * Trailing newline is optional. ## Output * A consistent [truthy](http://meta.codegolf.stackexchange.com/a/2194/7311) value if the input is an ascii tree. * A consistent [falsy](http://meta.codegolf.stackexchange.com/a/2194/7311) value if the input isn't an ascii tree. ## Examples Valid trees: ``` | ``` ``` _ \/ / \_/ | | ``` ``` / / \/ \ \____/ \/ / / ``` ``` \___/ / \ \___/ | | ``` ``` __/ _/ / ``` ``` ____ \ ___ \ \/ \/\_____/ \/ \/ \__/ | | ``` Invalid trees (with extra explanations which are not parts of the inputs): ``` \/ \_______/ \__ / | \_/ <- reachable only on with downward route | ``` ``` _ <- multiple roots ``` ``` \/ <- multiple root characters ``` ``` /\ <- multiple roots ``` ``` | <- unreachable part | ``` ``` __/ / <- unreachable parts | ``` ``` \____/ | | <- multiple roots ``` ``` _\__/ <- unreachable parts (_ and \ don't connect to each other) | ``` This is code-golf so the shortest entry wins. [Answer] # Mathematica, ~~345~~ 300 bytes Still quite long, but I guess it's a start... ``` (s=StringSplit;v=Reverse;#=="|"||#=="\\"||#=="/"&[""<>s@#]&&(g={};i=0;(c={i,++j};d={i,j+1/2};e=2d-c;g=Join[g,Switch[#,"|",{d->{1,0}+d},"/",{c->c+1},"\\",{e->{i+1,j}},"_",{c->d,d->e,e->c},_,{}]])&/@Characters[++i;j=0;#]&/@{##};Sort@VertexOutComponent[Graph@g,g[[1,1]]]==Union@@List@@@g)&@@v@s[#," "])& ``` Here is a slightly ungolfed version: ``` ( s = StringSplit; v = Reverse; # == "|" || # == "\\" || # == "/" &[ "" <> s@# ] && ( g = {}; i = 0; ( c = {i, ++j}; d = {i, j + 1/2}; e = 2 d - c; g = Join[g, Switch[#, "|", {d -> {1, 0} + d}, "/", {c -> c + 1}, "\\", {e -> {i + 1, j}}, "_", {c -> d, d -> e, e -> c}, _, {} ]] ) & /@ Characters[ ++i; j = 0; # ] & /@ {##}; Sort@VertexOutComponent[Graph@g, g[[1, 1]]] == Union @@ List @@@ g ) & @@ v@s[#, "\n"] ) & ``` This defines an unnamed function which takes the string as input and returns `True` or `False`. The basic idea is first to check that there's a single root, and then to build an actual (directed) `Graph` object to check if all vertices can be reached from the root. Here is how we build the graph: Imagine an integer grid overlaid onto the ASCII art, where integer coordinates correspond to the corners of the character cells. Then on each of the cells there are six relevant points that can be connected. Here is an example, where I've also labelled the points `a` to `f`: ``` | | | | ---(2,3)---(2.5,3)---(3,2)--- | d e f | | | | | | | | | | | | | | a b c | ---(2,2)---(2.5,2)---(3,2)--- | | | | ``` So we can build a graph whose vertices are these half-integer coordinates, and whose edges are determined by the non-space characters in the input. `|` connects `b` to `e`, `/` connects `a` to `f` and `\` connects `c` to `d`. Note that these must be directed edges to ensure that we're never moving downwards while traversing the graph later. For `_` we can go either way, so in theory we need four edges `a -> b`, `b -> a`, `b -> c`, `c -> b`. However, we can notice that all that matters is that there's a cycle containing all three vertices, so we can shorten this to three edges: `a -> b`, `b -> c`, `c -> a`. Building this graph is quite simple in Mathematica, because *any* object can act as a vertex, so I can actually build a graph whose vertices *are* the coordinate pairs. Finally, we check that every vertex can be reached from the root. The root's coordinate is easily found as the very first vertex we added to the graph. Then the shortest way I have found to check if all vertices can be reached is to check if the `VertexOutComponent` of the root (i.e. the set of all vertices reachable from the root) is identical to the set of all vertices in the graph. [Answer] # [PMA/Snails](https://codegolf.stackexchange.com/a/47495/30688), ~~99~~ 93 Prints 1 if it satisfies the "tree" definition or 0 if not. The rectangular space-padded form of input is preferred, although it costs only one byte (using the `F` option) to convert the ragged version to a space-filled rectangle, which was useful in testing. ``` & \ |{(\_|\|)d=\||(\\a7|\/d|\_da7)=\\|(\\d|\/a5|\_da5)=\/|(\_lr|\|d|\/l|\\r)=\_},^_!(r.,^ )d~ ``` Ungolfed, outdated version (for my personal viewing pleasure) : ``` F& \ | { \_ (lr=\_|da5=\/|da7=\\|d=\|) | \/ (l=\_|a5=\/|d=\\) | \\ (r=\_|a7=\\|d=\/) | \|d=(\_|\|) }, ^_ !(r.,^ ) d~ ``` This turns out to be fairly well suited to the current language features. Unfortunately, I had to spend a few hours chasing down a reference counting bug before it could work. The `&` option means that the match must succeed at every character. From each non-space starting point it checks for a downward path to the bottom. Making a finite state machine with a regex is luckily much shorter by using assertions, here `=` ... . At the bottom row, it checks that there are no non-space characters to the right. [Answer] # Ruby 226 ~~227 228~~ ``` ->i{w=i.index(?\n)+1 t=[i.index(/[^ _] *\n\z/)] a=->x,c{(i[x]==c||i[x]==?_)&&t<<x} ((x=t.pop)&&(s=x-w;c=i[x])<?0?(a[s+1,?/];a[s,?\\]):c<?]?(a[s-1,?\\];a[s,?/]):c<?`?(a[x-1,?\\];a[x+1,?/]):a[s,?|] i[x]=' ')while t!=[] !i[/\S/]} ``` Online test: <http://ideone.com/Z7TLTt> The program does the following: * searches for a root (a `\`, `/`, or `|` on the last row) * starting from that root, climb the tree using the rules and replacing every visited char with a space * at the end, see if our string is fully composed of whitespace (meaning a valid tree), or not (invalid tree; not all pieces have been "visited") Here it is ungolfed: ``` F =-> input { row_size = input.index(?\n)+1 root_coord = input.index /[^ _] *\n\z/ # coordinates to process todo = [root_coord] add_todo = -> coord, char{ if input[coord] == char || input[coord] == ?_ todo << coord end } while todo.any? x = todo.pop next unless x # exit quickly if no root present case input[x] when ?| add_todo[x - row_size, ?|] when ?_ add_todo[x - 1, ?\\] add_todo[x + 1, ?/] when ?/ add_todo[x - row_size + 1, ?/] add_todo[x - row_size, ?\\] when ?\\ add_todo[x - row_size - 1, ?\\] add_todo[x - row_size, ?/] end input[x]=' ' end input.strip < ?* } ``` ]
[Question] [ In 2009, [Hannah Alpert described](https://www.emis.de/journals/INTEGERS/papers/j57/j57.pdf) the "far-difference" representation, a novel way of representing integers as sums and differences of Fibonacci numbers according to the following rules: * every two terms of the same sign differ in index by at least 4, and * every two terms with different signs differ in index by at least 3. ### Example ``` n | far-difference +----+------------------------------+ | 10 | 13 - 3 = F_5 - F_2 | | 11 | 13 - 2 = F_5 - F_1 | | 12 | 13 - 1 = F_5 - F_0 | | 13 | 13 = F_5 | | 14 | 13 + 1 = F_5 + F_0 | | 15 | 13 + 2 = F_5 + F_1 | | 16 | 21 - 5 = F_6 - F_3 | | 17 | 21 - 5 + 1 = F_6 - F_3 + F_0 | | 18 | 21 - 3 = F_6 - F_2 | | 19 | 21 - 2 = F_6 - F_1 | | 20 | 21 - 1 = F_6 - F_0 | +----+------------------------------+ ``` As a non-example, we do not write \$16 = 13 + 3 = F\_5 + F\_2\$ because \$13 = F\_5\$ and \$3 = F\_2\$ have the same sign and therefore violate the first rule because their index differs by \$3\$. As another non-example, we do not write \$8 = 13 - 5 = F\_5 - F\_3\$ because \$13 = F\_5\$ and \$-5 = - F\_3\$ have different signs and violate the second rule because their index differs by \$2\$. # Challenge Write a program that takes an integer `n` as an input and outputs a list of numbers that describes its far-difference representation, or any other reasonable output (e.g. `[21, -5, 1]` or `"21 - 5 + 1"`.) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. [Answer] # [Python](https://www.python.org), 148 bytes ``` g=lambda n,j=1:n>sum(map(f,range(j,0,-4)))and g(n,j+1)or n*[1]and[f(j)]+([-x for x in g(-n)]if(n:=n-f(j))<0else g(n)) f=lambda n:n<2or f(n-1)+f(n-2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RZA9bsMwDIV3n0IjGUuBFXQojLhH6JrBMALVkRwbNmXIMpDeo1uWLOmdeptSSH8mgg-Pjx95_Zzf49nT7XZfo1PPXx9dNZrp7WQEyaHSJb0s6wSTmcHJYKizMMhCqidENHQSHbAt1-iDoE2tG9ZqBwM2OdTqIhzrF9ET-xRh0zugsiKVHLgv7LjYlICYub-tJe13PMVOpTFPZYc_bId-mn2Iwq3URu_HJXOi-u-2Y1iPrWnPFl49WQTHuRw1JIAHu5a6KLDMxBx6inxKl0ge8b8v-AY) Not 100% sure about this though output looks ok. ### How? Assuming the desired representation exists and is unique the following recursion should work: Find the smallest sum \$F\_n+F\_{n-4}+F\_{n-8}+...\$ that is at least as large as N where N is the number we wish to represent. Then the representation starts with \$F\_n\$. And now we use recursion on the difference between N and \$F\_n\$ and that's it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` NθWθ«≔⟦÷θ↔θ⟧ηW‹↔ΣΦ⮌η¬﹪μ⁴↔θ⊞ηΣ…⮌η²≧⁻↨η⁰θ⟦I↨η⁰ ``` [Try it online!](https://tio.run/##VY9BqwIxDITP66/IMYUKIt486YogqIgexUNdiy1023XTroj42/uyPFHMaWBmviSVUW0VlMt55ZsUt6k@6xZvYjq4G@s0sITnoJgR2avH48rHhe3sReNNwuxMwaXIWoiTBMOl4t1aayL8@IdU49K6yOS97nRLGo2QsA0RN@GSXMBawkT080sVsEtk0EjoEeWjcro0ofmhjDnGizeq@T9yb6@GudYnkjBXfUrCiIP9U8WutT7isVQU8WuKE3uvnCejPOzcHw "Charcoal – Try It Online") Link is to verbose version of code. Uses my observation that the first term in the expansion of `N` is `F(n)` where `A097083(n)` is the largest term not greater than `N`, and then assumes that the remaining terms can be calculated by subtracting `F(n)` from `N` (adjusting for the sign of `N`). ``` Nθ ``` Input `N`. ``` Wθ« ``` Repeat until `N` is zero. ``` ≔⟦÷θ↔θ⟧η ``` Start with the sign of `N`. ``` W‹↔ΣΦ⮌η¬﹪μ⁴↔θ ``` While `A097083(n)` is less than `N`... ``` ⊞ηΣ…⮌η² ``` ... calculate the next Fibonacci number. ``` ≧⁻↨η⁰θ ``` Subtract `F(n)` from `N`. ``` ⟦I↨η⁰ ``` Output `F(n)` on its own line. [Answer] # JavaScript (ES6), 106 bytes This version is based on [@Neil's insight](https://codegolf.stackexchange.com/a/255256/58563) about [A097083](https://oeis.org/A097083) and the conjectured formula from OEIS: $$\text{A097083}(n)=\lfloor F(n+2)/\sqrt{5}\rfloor$$ Returns an array of integers. ``` f=(n,k=s=1)=>n?(g=n=>v=n<3?n:g(n-1)+g(n-2))(k+2)*v<n*n*5?f(n,k+1):[g(k)*s,...f((n-v)/s*(s*=v<n||-1),1)]:[] ``` [Try it online!](https://tio.run/##FY3BDoMgEER/heMuIBWbXiyrH2I8GCum1SyNNJz8d4qnmcN7M58pTXE@3t9fxeG15OwJWG8UySJ13MNKTF0idvee2xW4sqiuaBBhUw3K5FiyfPT@8pTFdlhhQxm1McZDIRPeooQoqZDnWXxtcWyHMftwAAsS9ilYuJJ1XZpSKObAMeyL2UO50qJMI@Y/ "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 127 bytes Returns a space-separated string such as `21 -5 1`. ``` f=(n,a=[1,-1])=>(g=([v,...a],s,p,d)=>v?g(a,s,p,-~d)||d>3&d!=5&&g(a,s-v,[p]+v+' '):s?0:o=p)(a,n)?o:f(n,[v=a[0]+a[2]||2,-v,...a]) ``` [Try it online!](https://tio.run/##LY3NCsMgEIRfZXtJXPzBtPSS1uRBxIPEJLQElVg8hb66ldDL7My3y87bZpum/RU/3Ac3l7Io4plVumO8M6gGsiqiMxNCWMMSi8xVmMeV2DPxr8PjcMOtcRd1b5qT88x0NDTTFlrs0yj7oCLWjccx9Est0FlZLQ21@mqO48r4vwHLEnbiQUH3AA/POqWsjlKEKfgUtllsYa0XFFrgQxUK9SFi@QE "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·ÅF.āæεU1®‚XgãεX*]€`ʒø`ü2εÄ`α4y.±O_-@}PsOIQ*}нøн ``` Brute-force, so very slow.. [Try it online](https://tio.run/##AVsApP9vc2FiaWX//8K3w4VGLsSBw6bOtVUxwq7igJpYZ8OjzrVYKl3igqxgLs6Uw7hgw7wyzrXDhGDOsTR5LsKxT18tQH1Qc09JUSp9w7jQvf//MjX/LS1uby1sYXp5) or [verify all few test cases](https://tio.run/##AXAAj/9vc2FiaWX/VMaSTlQrw5BWPyIg4oaSICI/Iv/Ct8OFRi7EgcOmzrVVMcKu4oCaWGfDo861WCpd4oKsYC7OlMO4YMO8Ms61w4RgzrE0eS7CsU9fLUB9UHNPWVEqfcO40L3/Ii5WLP//LS1uby1sYXp5). **Explanation:** ``` · # Double the (implicit) input-integer ÅF # Push a list of all Fibonacci values <= this 2*input .ā # Enumerate this list, pairing each with their 0-based index æ # Get the powerset of this list of Fibonacci-index pairs ε # Map each list of pairs to: U # Pop and store the current list in variable `X` 1®‚ # Push pair [1,-1] Xg # Push the length of the current list `X` ã # Get the cartesian product of the [1,-1] and this length ε # Map over each list of 1s and/or -1s: X* # Multiply the values to the values in list `X` ] # Close the nested maps €` # Flatten it one level down .Δ # Find the first result which is truthy for: ø # Zip/transpose; swapping rows/columns ` # Pop and push the list of values and indices separated to the stack ü2 # Get all overlapping pairs of the indices ε # Map over each pair of indices: Ä # Get the absolute values of both indices in the pair ` # Pop and push them to the stack α # Get the absolute difference between the two 4 # Push 4 y # Push the current pair of indices again .± # Get the sign of each index O # Sum the pair of signs together (either -2; 0; or 2) _ # Check if it's equal to 0 (1 if 0; 0 if -2 or 2) - # Subtract that from the 4 @ # Check if the earlier difference is >= this 4-signDiff } # Close the inner map P # Check if all of them were truthy by taking the product s # Swap so the list of values is at the top O # Sum them together IQ # Check if this sum is equal to the input * # Check if both were truthy }ø # After the find_first: zip/transpose; swapping rows/columns н # Only keep the first list of values # (which is output implicitly as result) ``` ]
[Question] [ There are several ways to create headers on posts on the Stack Exchange network. The format that's most commonly1 used on PPCG seems to be: ``` # Level one header ## Level two header ### Level three header ``` Note the space after the hash marks. Also, note that trailing hash marks are not included. ## Challenge: Take a (possibly multiline) string as input, and output the string on the following format: * If the header is level 1, then output each letter 4-by-4 times * If the header is level 2, then output each letter 3-by-3 times * If the header is level 3, then output each letter 2-by-2 times * If a line is not a header then output it as it is. To illustrate: ``` --- Level 1 --- # Hello --- Output--- HHHHeeeelllllllloooo HHHHeeeelllllllloooo HHHHeeeelllllllloooo HHHHeeeelllllllloooo --- Level 2 --- ## A B C def --- Output --- AAA BBB CCC dddeeefff AAA BBB CCC dddeeefff AAA BBB CCC dddeeefff --- Level 3 --- ### PPCG! --- Output--- PPPPCCGG!! PPPPCCGG!! ``` Simple as that! --- ### Rules: * You must support input over multiple lines. Using `\n` etc. for newlines is OK. + There won't be lines containing only a `#` followed by a single space * The output must be presented over multiple lines. You may not output `\n` instead of literal newlines. + Trailing spaces and newlines are OK. --- ### Test cases: Input and output are separated by a line of `...`. ``` # This is a text with two different ### headers! ........................................................ TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt with two different hheeaaddeerrss!! hheeaaddeerrss!! ``` --- ``` This input has ## trailing hash marks ## #and a hash mark without a space after it. ........................................................ This input has tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ###### tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ###### tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ###### #and hash marks without a space after it. ``` --- ``` # This ## is ### strange #### ### ........................................................ TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee #### ### ``` --- ``` Multiple ### newlines! # :) ........................................................ Multiple nneewwlliinneess!! ## nneewwlliinneess!! ## :) ``` --- ``` Line with only a hash mark: # ### ^ Like that! ........................................................ Line with only a hash mark: # ^^ LLiikkee tthhaatt!! ^^ LLiikkee tthhaatt!! ``` 1: I haven't really checked, but I *think* it's true. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~51~~ 50 bytes *Saved 1 byte thanks to @RickHitchcock - golfed regex* ``` ['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl] ``` [Try it online!](https://tio.run/##TU9BasMwELzrFUN1UNKmMaXtISUkIYaeAj70GCdUduRa2JKMJDv49e4m9FAEM6tlZnc2RFk26jJNR3Gecb7l2zlmy6e5OOZcvOfPuwbpF5rHBl51OHzy79NrYqhuT9Puo2KCI3Wm86pWNuhBgSOqEFHKoALjHPuRBNZ5ZELsvVaWmhyz0nWj1z91xMtq9YZ9Omc8FjW4V7Jl/P5ireBIpC1chduvat1VeSjjoi6dxZpDB/S2se5qFyj6CCPtSFptG@iIi/IUKlAZ0N29lXfmPkvaktJEFkZTuPa2wUjqE2gKj4dY91E@LCAxSK@ljX8hoiSUdCGdLT3Ntr0plA9Ldjs3@5eX/OCc6ShEQKPtRZLJtaTDerPeEJ2H80CUZtmBKMmTnIgwYQIVXB@nXw "Stacked – Try It Online") Anonymous function that takes input from the stack and leaves it on the stack. ## Explanation ``` ['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl] [ mrepl] perform multiline replacement '^(##?#?) (.+)' regex matching headers [ ]3/ on each match: \#' count number of hashes 5\- 5 - (^) @k set k to number of repetitions CS convert the header to a char string k* repeat each char `k` times k rep repeat said string `k` times LF#` join by linefeeds ``` [Answer] # JavaScript (ES6), ~~111~~ 105 bytes *Saved 6 bytes thanks to @Shaggy* ``` s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>` ${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim()) ``` Matches 1-3 hashes at the beginning of the string or preceded by a new line, then repeats each character in the match along with the match itself, based on the length of the hashes. **Test Cases:** ``` let f= s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>` ${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim()) console.log(f('# This is a text\nwith two different\n### headers!')); console.log('______________________________________________'); console.log(f('This input has\n## trailing hash marks ##\n#and a hash mark without a space after it.')); console.log('______________________________________________'); console.log(f('# This ## is ### strange\n#### ###')); console.log('______________________________________________'); console.log(f('Multiple\n\n\n### newlines! # \n:)')); console.log('______________________________________________'); console.log(f('Line with only a hash mark:\n#\n### ^ Like that!')); ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~125~~ 104 bytes ``` m(`(?<=^# .*). $0$0$0$0 (?<=^## .*). $0$0$0 (?<=^### .*). $0$0 ^# $%'¶$%'¶$%'¶ ^## $%'¶$%'¶ ^### $%'¶ ``` [**Try it online**](https://tio.run/##VY9BTsMwEEX3c4ofuYiWRcS6AvUCZce6YkQmtdXUieypChfjAFwsjBMKrWyN9J/n/xkn0RB5HI/Lt@Xm6XnnUD@salo8zodmeEMv7AqS@Whxd//99V@o2OhWX8A4Orz6kGGXofKhdA7qoeceTWhbSRKVSr8XbiTliub2OJwUnrO9QROHLsR90R5HTocM58hxbCz0D6Ik92Zj5IHfBdyqJASt6XcJy5qqQ7bMuJcy2RVAL6dOw9AJ0bRNlLNNlFzBfrJe0dbElI8@dp/XU9fkJscO23AQqGetfgA) *Saved 21 bytes thanks to Neil.* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~43~~ ~~42~~ 40 bytes *1 byte removed thanks to [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)!* ``` `j[]y'^##?#? 'XXgn:(2M4:QP&mt~+t&Y"0YcDT ``` This outputs a trailing space in each line (allowed by the challenge), and exits with an error (allowed by default) after producing the ouput. [**Try it online!**](https://tio.run/##jY/BSsNAEIbv@xR/OtBahCLiKZdeemxBoYcWsTg0k@zaZBOyU2IvvnrcRBGPGZaBHZjvn69iLfv@/eP17bY4Ea1pjcXhUPj07nH3lL48zyv9utf5cfZwPG/2fU/YWxcQH0PlU03n1EK7GpnLc2nFqyEiWOFM2pCY1YQyP0zfXBWWQwRAW3al88Xwt6i4vQQQGWKfxeS/IYb4Oq4xQsNnAecqLZyupgX/6sTAsRNCDPaFDA40DKZhdtdSXVOKMaO8ly7eLiEBwaTLaYxt3Bh1UPvy9l8yNTRiT9i6i0Ata/IN) ### Explanation ``` ` % Do...while loop j % Input a line as unevaluated string [] % Push empty array y % Duplicate from below: push input line again '^##?#? ' % Push string for regexp pattern XX % Regexp. Returns cell array with the matched substrings g % Get cell array contents: a string, possibly empty n % Length, say k. This is the title level plus 1, or 0 if no title :( % Assign the empty array to the first k entries in the input line % This removing those entries from the input 2M % Push k again 4:QP % [1 2 3 4], add 1 , flip: pushes [5 4 3 2] &m % Push index of k in that array, or 0 if not present. This gives % 4 for k=2 (title level 1), 3 for k=3 (tile level 2), 2 for k=2 % (title level 1), and 0 for k=0 (no title). The entry 5 in the % array is only used as placeholder to get the desired result. t~+ % Duplicate, negate, add. This transforms 0 into 1 t&Y" % Repeat each character that many times in the two dimensions 0Yc % Postpend a column of char 0 (displayed as space). This is % needed in case the input line was empty, as MATL doesn't % display empty lines D % Display now. This is needed because the program will end with % an error, and so implicit display won't apply T % True. This is used as loop condition, to make the loop infinite % End (implicit) ``` [Answer] # Perl 5, 47 +1 (-p) bytes ``` s/^##?#? //;$.=6-("@+"||5);$_=s/./$&x$./ger x$. ``` [try it online](https://tio.run/##K0gtyjH9/79YP05Z2V7ZXkFf31pFz9ZMV0PJQVuppsZU01ol3rZYX09fRa1CRU8/PbVIAUj//6@sEJKRWaygrKwAJpUVikuKEvPSU7mUQRwg5vqXX1CSmZ9X/F@3AAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` FN«Sι≔⊕⌕E³…⁺×#κι⁴### θF⎇θ✂ι⁻⁵θLι¹ι«G↓→↑⊕θκ→»D⎚ ``` [Try it online!](https://tio.run/##TY/BTsMwDIbP7VOY9uJK4YAGl3FCTEhIFE2sPEBo3cZamnRpujKhPXtJygUpsf9Yv77fqZV0tZV6WVrrAF/NMPn3qf8ih0UBP2myTg7esemQi8c0eRpH7kxw1o56Mp4afGHTYCkH3AgorW5wr6cRK@5pxCzPBBwLARzufRFKluc5ZFGdIm/NrcgZ6S54EnDQXBNyILEJlIdoE/BGpvMKI@Ruha3LJXurL501uN3Z2QjYfnCnfOifg4D/G0bEMaYlpT0T/vni@5omu6kfMOpnTdJFdV2WTZpDpXiEcCR4@vbpzF6Bny003LbkAjiNP1EkG3LjzXJ71r8 "Charcoal – Try It Online") Link is to verbose version of code. Charcoal doesn't really do string array input, so I've had to add the array length as an input. Explanation: ``` FN«Sι ``` Loop over the appropriate number of input strings. ``` ≔⊕⌕E³…⁺×#κι⁴### θ ``` Create an array of strings by taking the input and prefixing up to 2 #s, then truncating to length 4, then try to find `###` in the array, then convert to 1-indexing. This results in a number which is one less than the letter zoom. ``` F⎇θ✂ι⁻⁵θLι¹ι« ``` If the letter zoom is 1 then loop over the entire string otherwise loop over the appropriate suffix (which is unreasonably hard to extract in Charcoal). ``` G↓→↑⊕θκ→ ``` Draw a polygon filled with the letter ending at the top right corner, and then move right ready for the next letter. ``` »D⎚ ``` Print the output and reset ready for the next input string. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~31~~ 28 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ¶Θ{■^##?#? øβlF⁄κ6κ5%:GI*∑∙P ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUI2JXUwMzk4JTdCJXUyNUEwJTVFJTIzJTIzJTNGJTIzJTNGJTIwJUY4JXUwM0IybEYldTIwNDQldTAzQkE2JXUwM0JBNSUyNSUzQUdJKiV1MjIxMSV1MjIxOVBGJTBBaW5wdXRzLnZhbHVlJXUyMDFEJXUyMTkyRg__,inputs=TXVsdGlwbGUlMEElMEElMEElMjMlMjMlMjMlMjBuZXdsaW5lcyUyMSUyMCUyMyUyMCUwQSUzQSUyOSUwQSUwQSUyMyUyMFRoaXMlMjBpcyUyMGElMjB0ZXh0JTBBd2l0aCUyMHR3byUyMGRpZmZlcmVudCUwQSUyMyUyMyUyMyUyMGhlYWRlcnMlMjElMEElMjMlMjBzaXplJTIwNCUwQSUyMyUyMyUyMHNpemUlMjAzJTBBJTIzJTIzJTIzJTIwc2l6ZSUyMDIlMEFzaXplJTIwMQ__) - extra code added because the code is a function and takes input on stack (SOGL can't take multiline input otherwise :/) - `inputs.value”` - push that string, `→` - evaluate as JS, `F` - call that function Explanation: ``` ¶Θ split on newlines { for each item ■^##?#? push "^##?#? " øβ replace that as regex with nothing l get the new strings length F⁄ get the original strings length κ and subtract from the original length the new strings length 6κ from 6 subtract that 5% and modulo that by 5 - `6κ5%` together transforms 0;2;3;4 - the match length to 1;4;3;2 - the size : duplicate that number G and get the modified string ontop I rotate it clockwise - e.g. "hello" -> [["h"],["e"],["l"],["l"],["o"]] * multiply horizontally by one copy of the size numbers - e.g. 2: [["hh"],["ee"],["ll"],["ll"],["oo"]] ∑ join that array together - "hheelllloo" ∙ and multiply vertiaclly by the other copy of the size number: ["hheelllloo","hheelllloo"] P print, implicitly joining by newlines ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 130 bytes ``` x=>for l:x.split("\n"){L=l.find(" ")print(L>3or L+len(l.lstrip("\#"))-len(l)?l:"\n".join(["".join(c*(5-L)for c:l[L+1to])]*(5-L)))} ``` [Try it online!](https://tio.run/##LU1LCsMgFNznFPKyea8hgpRuAkku4A1SV2kFy0PFuAiUnt2apgMDwzCfmEIOvtix7ONkQxI87HKL7DLC3QO99cjSOv9AEEAxOZ9RT9ca1B0/PbLkLScXa7oFov7n0czD0Zav4Dwu8BfrBW@9puNlHXjRncrBkDldok855y1C01aIygYWJXIQvTJE5Qs "Proton – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 147 bytes ``` def f(x): for l in x.split("\n"):L=l.find(" ");print(L>3or L+len(l.lstrip("#"))-len(l)and l or"\n".join(["".join(c*(5-L)for c in l[L+1:])]*(5-L))) ``` [Try it online!](https://tio.run/##NY27CsIwFIZn8xTxZDnH0kARl4o6CQ5B3WsHsQlGDkmJHerT19bL9vHxX9pXd49hOQyNddJhT6WYuZgkSx9kr58t@w7hEoBKs2HtfGgQJNC6TT50aLbLMWwytgFZ87NLvkVQQJR/FF1DM27FNE3oR/QBK/jBbYGr3ND0dpveuDJZUdZUfz3R4BAAxMEyR6HkwV4bm@ZCKXn/4G7EP2uthTqeznsxVqqizIuahjc "Python 3 – Try It Online") -1 byte thanks to Mr. Xcoder [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 268 + 18 bytes ``` n=>{var r="";for(int l=0,c;l<n.Length;l++){var m=n[l];var s=m.Split(' ');var y=s[0];if(!y.All(x=>x==35)|y.Length>3|s.Length<2)r+=m+'\n';else for(int i=0,k=y.Length;i<5-k;i++){for(c=1;c<m.Length-k;)r+=new string(m.Substring(k,m.Length-k)[c++],5-k);r+='\n';}}return r;}; ``` [Try it online!](https://tio.run/##lVLBbqMwED2Xr5jCISAo6m7VyxpHqirtKSut1JX2kKaS1zFgYUzWHpqglG9PDYG210jIGr2Zee/NE9ze8MaIU2ulLuCpsyjqdCX1f@JxxayF36YpDKvh6F1ZZCg5vDZyC7@Y1KFF47bWG2CmsJEb8SaCn63m2dxN4FwtIQd60nR5fGUGDPV9kjcmlBpB0duEE5XpdCV0gSVRcRyNYzXVa7UhQ2lpnT7tlMRwAYtohDpq17cbIvPwuksflAoPdHmg9O4@eusmquXdm53K7HtkYlrHi2e9IEJZAbO@dPoVnVeIzO5vKiIHD8MEp98Iz@qp6zoDjRb76a7Q2Wr/TXWVfM5Fax7Hm8RxRcRtjLJ9bwS2RoMhPTmRObDHRttGifSvkShc/CLMw08Fl/AR/AD@lNKC@xigOKCfgL@XWALuG9jKPBdG6BENggBKwbbC2Gsf@ii6SOesonctQsnsmQ/QMKmGX8RBJdTMVBaCYGwyvXWOPnAYPDVumYHdMS6A5SgMSEwvtzKd7PTHNxiaTBdiOjIYsMtZB3h0CY1W3VfvP0biOcIXWMlKAJYM5xi9q97rT@8 "C# (.NET Core) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 131 bytes ``` from re import* print(sub("^(#+) (.*?)$",lambda x:((sub('(.)',r'\1'*(5-len(x[1])),x[2])+'\n')*(5-len(x[1])))[:-1],input(),flags=M)) ``` [Try it online!](https://tio.run/##VY9Bi4MwFITv/opHUsh7mgrusheh9Bf01pt14XWrNVRjSCK1v9667WHZ43zDDDPuEbvRfi7GuinCDnoezhcuQQhx7EyAN@84JFJC9Gx6Y6@/uoOB/S2AlIlkewH@g3A3a@kaYwiOfxrgNjYeTMzX1qX14wC@ATO40cc0cd7YiGE6o/hGmRFgnu5pI/R7CswlvlyFOSnt1alQKX5t@8biXBU1kZ6rj5oydbKK/jtUldui1q8PSLrt@Rp2B6JleQI "Python 3 – Try It Online") I used Python 3 in order to use `[]` with regex. [Answer] # PHP, 122+1 bytes ``` for($y=$z=" "==$s[$i=strspn($s=$argn,"#")]&&$i?5-$i++:1+$i=0;$y--;print" ")for($k=$i;~$c=$s[$k++];)echo str_pad($c,$z,$c); ``` Run as pipe with `-nR` (will work on one input line after another) or [try it online](http://sandbox.onlinephpfunctions.com/code/07226b470ecae8bbdbd1dde71cf416af5e858c2b). [Answer] # [J](http://jsoftware.com/), 55 bytes ``` ([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)] ``` I don't know how to make TIO work with J regex, so I can't provide a working link. Here's how to test it in the J interpreter (tested with J804) ``` f=.([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)] txt=.'# Hello'; '## A B C def'; '### PPCG!'; '#and a hash mark without a space after it.'; '##### ###' ; f each txt HHHHeeeelllllllloooo HHHHeeeelllllllloooo HHHHeeeelllllllloooo HHHHeeeelllllllloooo AAA BBB CCC dddeeefff AAA BBB CCC dddeeefff AAA BBB CCC dddeeefff PPPPCCGG!! PPPPCCGG!! #and a hash mark without a space after it. ##### ### ``` I simulate a multiline string through a list of boxed strings. [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ ~~124~~ 117 bytes ``` while 1:l=raw_input();i=l.find(' ');v=5-i*(l[:i]in'###');exec"print[l,''.join(c*v for c in l[i+1:])][v<5];"*(v>4or v) ``` [Try it online!](https://tio.run/##TY7BTsMwDIbvfgpvObQdMGmIXVrGE4wbt6qgqHUXs5BWidduT1/SghCSZcm/7f/7@5uYzj1O02jYEu5ye/B6/GDXXyTNCj7YbcuuSRNMsmI47B94k9oy54pdopSKIl2pXveenZT2Pkm2nx27tN4M2HYea2SHtuS7XV5lVTk876tivUmHl6e4HLJpUvhmOGAsjUJXgZHFoIwdNty25MkJRA4a0g35sAL4uZ/zodEhLlG8ZsvuNM8Gv7Q/B1QKlHZNdP0Tcbbu4pvG0OuaULdCHlm2AL8xotnSFYZo6k40s9UsALxerHBvCWAJ5GiMTAorVAh5BnCM04LAztnbf3AOanl5xyOfCcVoWX0D "Python 2 – Try It Online") or ``` while 1:l=raw_input();i=l.find(' ');t=''<l[:i]in'###';exec"print[l,''.join(c*(5-i)for c in l[i+1:])][t];"*(t<1or 5-i) ``` [Try it online!](https://tio.run/##TY7BasMwDIbvegq1PjjptkIHuyTNG3S33UI2TKLUWj0n2Cppnz5zsjEGQqBf0v/9413s4J/nebLsCA@Fq4KZPtiPV8nykiu379l3mUadl1JpfXR1wQ17rZTSJd2o3Y6BvdTuUev958A@a3fZyxPn/RCwRfboan44FE3e1NKU210mx0NaLSfzrPDNcsRUBoVuAhOLRZkG7LjvKZAXSCS0ZDoKcQPwc7/kQ2tiWqIEw479eZktfplwiagUKOO75Pon4mI9pDeDcTQtoemFArLsAX5jJLO1K4zJ1J9pYatFAHi9OuHREcAayNOUmBQ3qBCKHOCUphWBg3f3/@AC1Pryjie@EIo1svkG "Python 2 – Try It Online") [Answer] # JavaScript, 112 bytes ``` x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join` `)(5-n.length)) ``` ``` f= x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join` `)(5-n.length)) ``` ``` <textarea id=i style=display:block oninput=o.value=f(i.value)></textarea> <output id=o style=display:block;white-space:pre></output> ``` [Answer] # C# 4.5 158 Bytes Where i is the input in the form of a string. ``` int l,m,t,s=0;while(i[s]=='#'){s++;};t=s>0?4-s+1:1;for(l=0;l<t;l++){foreach(char c in i.Skip(s>0?s+1:0))for(m=0;m<t;m++)Console.Write(c);Console.WriteLine();} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é!?q╚<╙≈╣íå▒{¼Φ8ôƒ¡m↨;-◘-u♥ ``` [Run and debug it](https://staxlang.xyz/#p=82213f71c83cd3f7b9a186b17bace838939fad6d173b2d082d7503&i=This+input+has%0A%23%23+trailing+hash+marks+%23%23%0A%23and+a+hash+mark+without+a+space+after+it.%0A) This was fun. ]
[Question] [ ## Introduction I've previously created [two](https://codegolf.stackexchange.com/questions/48089/reconstruct-a-permutation) [challenges](https://codegolf.stackexchange.com/questions/69799/know-a-sequence-by-its-subsequences) where the idea is to reconstruct an object using as few query-type operations as possible; this will be the third. ## The task Your inputs shall be a non-empty string `S` over the alphabet `abc` and its length, and your output shall be `S`. With no restrictions, this would of course be a trivial task; the catch is that you're not allowed to access `S` directly. The only thing you're allowed to do to `S` is to call the function `num_occur(T, S)`, where `T` is some other string, and `num_occur` counts the number of occurrences of `T` in `S`. Overlapping occurrences are counted as distinct, so `num_occur(T, S)` really returns the number of indices `i` such that ``` S[i, i+1, …, i+length(T)-1] == T ``` For example, `num_occur("aba", "cababaababb")` will return `3`. Note also that `num_occur(S, S)` will return `1`. The result of `num_occur("", S)` is undefined, and you should not call the function on an empty string. In short, you should write a function or program that takes `S` and `length(S)` as inputs, calls `num_occur` on some shorter strings and `S` some number of times, reconstructs `S` from that information and returns it. ## Rules and scoring Your goal is to write a program that makes as few calls to `num_occur` as possible. In [this repository](https://github.com/iatorm/random-data), you will find a file called `abc_strings.txt`. The file contains 100 strings, each on its own line, between lengths 50 and 99. Your score is the **total number of calls to `num_occur` on these inputs**, lower score being better. Your solution will preferably keep track of this number as it runs, and print it upon finishing. The strings are generated by choosing uniformly random letters from `abc`; you are allowed to optimize for this method of generating the strings, but **not** the strings themselves. There is no time limit, except that you should run your solution on the test cases before submitting it. You solution should work for any valid input `S`, not just the test cases. You are encouraged to share your implementation of `num_occur` too, if you're not using someone else's. To get the ball rolling, here's an implementation in Python: ``` def num_occur(needle, haystack): num = 0 for i in range(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: num += 1 return num ``` [Answer] ## Javascript, ~~14325~~ 14311 calls We start with an empty string and go our way recursively by adding a new letter at the end or at the beginning of the current string while we still have at least one match. All previous results from `numOccur()` are saved in the `sym` object and we use this data to reject immediately any new string that can't possibly be a candidate. **EDIT**: Because we always start with `'a'`, we always know the exact number of `a` in the string. We use this information to end the process earlier when we detect that only a sequence of `a` is missing. Also fixed the regular expression which was invalid in Chrome and IE. ``` var test = [ 'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab', // etc. ]; var call = 0; function guess(S, len) { var sym = {}; recurse(S, len, "", sym); return sym.result; } function recurse(S, len, s, sym) { var dictionary = []; if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) { if(s.length == len) { sym.result = s; } else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) { dictionary = [ Array(len - s.length + 1).join('a') ]; } else { dictionary = [ "a", "b", "c" ]; } dictionary.some(function(e) { return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym); }); return true; } return false; } function isCandidate(s, sym) { return sym[s] === undefined && Object.keys(sym).every(function(k) { return count(s, k) <= sym[k]; }); } function count(s0, s1) { return (s0.match(new RegExp(s1, 'g')) || []).length; } function numOccur(S, s) { call++; return count(S, s); } test.forEach(function(S) { if(guess(S, S.length) != S) { console.log("Failed for: '" + S + "'"); } }); console.log(call + " calls"); ``` Full executable snippet below. ``` var test = [ 'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab', 'caccbbababbaaaccbcabbaabaabcacabacaababcabcbbacaac', 'bbbbaacabcabacaccaaaabaaacaacabbcbacabaccbbcbabbcbc', 'abbcbcbccbccaacaccaccaabaccbbcabaaccabccbbbabbbcabc', 'aabacbbbcaaabcccaccccbcaabcacaccbabbbcccacabaaababca', 'bccbbaaccaaccacabaaaabbbbaababacabaaabacbcacbbbbabaa', 'bbbcbcabbacbaacbacabcbabbacacbbcbcabbaabbbccbacaaacac', 'ccbcbbbaaaaaccbaacbabbbcbccbabaabccbcbcbcbabcbbccacba', 'aacbcbcabcbcbccbabbacacbcaaababbbcacaacaccbabbbbabcaac', 'bcabacaabbacccacaabcaaacbcbcbacabbababcabbbbacbaaaabbb', 'abbaccccabbbcbbaacccacbcaacababaccabbabbacbbbaabaacbaba', 'cabbacabacccabcabacbaacbaababcaccbacbaaaacbbabbbccabbbb', 'bcabccaaabcbaaccaabccbbcbabaccababbbaccccacaaccaccacbcab', 'abbcbabaacbcbbabbccccbccabcbbaccacbabcacbaacbccbcabcccbc', 'bcbacabbaabcccabccacbcbccbcbbbccacbbccaabaacccccbcabaaccc', 'baccbcacaccacbbbcccbaaacbaccacbbacbbbaccccacbabcbbbaacabb', 'bcccabaaaabcbbbaaccbcaccbaabacccaaacbaabaccccacabaccacbcac', 'baabcbbcaabcacbabbcacccbcabbabaacbbbababbbbbccccccbcbbcbcc', 'bacacbbabbcbbcaacabcccccbbacabcaabbbcbbabaacbcbbaccaaacbbac', 'ccabccbccbaaacbcccccabacbbabbbbccbccccabaabaabbaacbabcabbcb', 'abbaccbcaabacbbacabaabbcbacbacacabccbbcccaccbbacbbbaacbaccab', 'bbbbaaabababcccbbbababacbacbaabbabccacccaaacabaccababaccbcac', 'bbcbbbbcccaccbbbcbcaaccbcacaabbbbabaaabbbaaacbbaaccbacaccabbb', 'cacabcabcbcbbbbcabbbccccccccacaaabaacbcaabbabcacbcbcccccacaab', 'babbcacabaabbccabcbbaacccaaccbabcbbcbcbbbcabbcccbcacbabccaccac', 'ccbbcbcbcaacbcaaccacbcaabbbcbbaccbbabacacccccaccaababcacccccba', 'bcccbcacccccabccabccbcbccaccaaacbcacabaabcbcccaccaaaabbcacbbcaa', 'cbbcacbbacaacbabccaabbaabacacbcbcbabcaccabbbbcabbbabaaacccaabcc', 'aabbaacccaaacbcaabcabaabbbaababbbbcbacabbbbbbbbccaccccbbaccbbaaa', 'abbcccabbabbaccccaacbabbccccbbbbccaaacaabacbabbabcabacbaabcbcacb', 'bcacbccccaacbbcaccbcbcbbabacabacabbcaaabbccabcccbaacabcbbcacababb', 'acabacaabcabbcccccbcacaccccbccaaaacacbbbccbcaabaacbbbacabcbcaabca', 'caabbaccaacbbcbaacbcabccacacabbcbcbbacabbbaacccaacccabaaaccbbacbaa', 'baaabbcbbbaacabacbcaaacabbacaacbacabbcabcccbabcbbacacbbababccacabc', 'abbbacbaabcabbcabbbabaababbaabcacbabbaababcabbbccccbcaacbbcccabaccb', 'caaababcacccaccababaccbabbccaabbbbbabaabcabccbabbbbbbcbacbabcbcccbb', 'abbbcaaaaacaaacbbbcbacabbcbbbccacaccacacabacacbbccbbbcbaccabbcbaabbc', 'bacacbcccabcabaabacccbcaaabcabbbcccaacbabacbaabbcccacaacbabbcacbaabb', 'bacaaaccbaababbbbbcaabcabaacccabacccbabcbccbbcbcaacbbaabcaccaaaacaabb', 'bbacaacccaaacacccbbacbcbbaaaccccabbbbcbbbabaaaaccbccaababaccbbccacaca', 'aacccccbabaccbcbcbbaccbacbcbacaababaaaccbaaabaabcccccacbbaabcccaababcc', 'babacacbbbacbbbbbabbabababacabacaaacbbccaccabacaacbabbbaccacccbcaaabbb', 'bcaccabbabbcbcabccbbcaacbbcbacbcabaaaaaacaaacaccbcaaccaaccacbaccacaabbc', 'acbcbbcbbaacbbbabbaabacabbcccabacabcabacccacbcaacacabcaaaabbabcccbcbabb', 'ccbcbcccbccbbbabaabbaababbcbacacbcbaacaccccccbcbacacbcabaaaacaacbbbbacba', 'cccbcbaaabcbbcbabbbaccabbabcacbaccbcababbababcbcaccabbbccabaabaaccccacbb', 'bbabcbcaabbacaabcababbbccbccccaaaabaccbbbbababbcabbabbaccaaaabbcbbbcbaccc', 'cbacaccaaaacaacbbcbbacaccabacaacacaacaacabccaaaccccacaaaaabcbcabaabaacccb', 'bcacbccabcccabababbbbcabaacabcbbaacaaaabbbacccaaabccbaabcbbabbbcccabaabbbb', 'cbccacabaaacabbccbacabccacabcbaccbababcccabbabbbbbbccbaabbaacaacaaaabcbabb', 'abcbcabbcabaababccbcacabbcbcabcaabbbabbcaaabaaaaacbaabaaababccacbabcbaccbab', 'aabbabbbcacaaaabcbcabccccacbacbccacacaabccacccaaacacbcccaabbbccacacbbccbbac', 'caacbbccacaaaacabaacbcaaaccbbabbcacababbbabcbccbaabccaababbcbacbccababbcbbbc', 'aaabaaaabbbbbcbbbacabccbaaaaabaacbacbcccbccacccacaaacaccbbabcbcccbbccccabbcb', 'cccccacacbacbbcbbcabcbaabbcbbbacabcbbccccaaacabcababbcaaccaabccabaccbcaccbaba', 'ccaaaccbccacabcacaccbccaabacacabaabbbaacbcacaacbaaabbbbabbabcccabcabbaccacacc', 'cbbbcaccbcacccbacccaaaabacaacccbcbcbabbbaababacccccccabbaaabbcbaabbbbbbaaaaaaa', 'ccbcbcbaabbccabbabbccbacbabacbcacbccacaabbcacaaccabbbbcbacbbcaaabaabccaacccacb', 'caaabcabaacbbabcbccabcacbbcccabcacbbcaabaacaaabbbcacaaccaccaaaacaaccbbaaaacaaac', 'bbacacbbaaaacbcabbbbbaabacaccabcbabbccbbbabbbacccababbcababcbbcacbababbbaaabcca', 'bbacbbacacaccccbabbbbcabbcccbcacaabbcabbccaaaaabcbbcccaccbcbbbccabcbaccacbacbaba', 'baccbcababbacabcbabacaababbaabcabbcbcbccabacbbaaaaabacaaacaacbacbcabacabaaccbcab', 'accacccabccbabcbcbaababacabcabbcaccbccabbabcbcabbaabccacbbbbcaacbccaababbababbaba', 'bbcccbcbcbccccbcaaccaaacacbbaacbcccbbcabbbccabaacbacaaaccbcbaacababaccacbcbaaccac', 'acbccccaabcabbbcbbccbccbacbcabcccacbcabbaacbababbbcbbccacbacccbbbaccbaaaabbbabaccb', 'babcacaccbccbaaabaabbbaabcaabaaccccacaacbaccbcbabbbbbbabcbbbbacbacbabcbbbacbbbbbbc', 'caabcaaaaabacccacbbbaabaabccaabcbaabbcbcbbbccbabbccbcbabbbbccacbcbcbacaaccccacbbabc', 'bbaaabbabccaccacbcbbccaaaaababbacccbabcbacabacbaacbcabaaacacaaaaacaaacabbbbccabbbca', 'bbcbccababbbaabbabcbbaacbccbaacbababbabcbaaccbcbcabacaabacaacabcababbaaabbbbbbccccbb', 'acabcabccaaccccacbcaabaccacaaabcbabbabbaccbbaaacacabcabbcabababaccccbcbabaacbbcccbab', 'bacaaaaacbcacbbbaaaaabbbbcbbcbbbcaccccbacaccbbcbabbbccbaaabbcbaccacacbcbcacbcbaaabacc', 'bbcaabccbcaccbabbacbaacacccccaabbbccbccbbbcccbacaaaccccbccbbbbabccaaacaabbbbacaacabab', 'aaaccccbbabbcacabaacacbabbcacbcccbcbaaacaabaabacbbaabcbbbbbcacbaccaacaacbccacbbcacbbaa', 'bbcacabcbbcbabbabbbacaaabcabbbbacbacbabacbbbbbabacabbabaabcabbaabbbaaccbcabcababcaaacc', 'ccccbaacbbcaccaccbaaacaccbabbabaabbababcacacaaccbbcbccaaaaaaacbccacbacbabbbabcabaabaabb', 'abacacbaccacaaacaccbcbabcaacbccaccbbacbabcababcaabcaabcbcabbcbacabaaaaaabaccccbbbcbabac', 'ccccacbaaabaaacabbabacbbacbabcbbcaaaaacaccacabcaacabcbcbcaccabcaaccbaccabcccbccacccbacbc', 'bcaabcaacacccbcababccacacbccccccbbaaabacabbcbbbcbaaacbbacababbaccccacbbcbacaacbabcbaccbc', 'cbcbbaabacbaacbbcabbbbaccbaabbacbcccaaabbabacabbbababcaabcacbaccacacaccbbbbcbcbbaaacbcbba', 'ccbcabcaabcbabbbcbcbbabacabacbbaccbbcbcabcaccaaccbaccbaacacacbbaacaaaaabcaaaacbcccbcccaaa', 'cbbababacbbabbabaabaaaabcacbacbcccbacbccbbcaabcabaccacccbbcaacacccccaccabaabccacbaccabaaba', 'cbbbaaacaccbcabccacbccabacbcbcccccacaccbbcccbcbbbaababcaaaacaabbbccbacbaccabccccbbbcaaaabb', 'bbabbacaaccacccbbcabbacbcbabcccaccacbacbccababbbcacbabbbcabbbbacabcabcbaacbaabcbccacaaaccbc', 'babcbaabccabcabaaabcaaaabaaaaccbcbcacbbbccaccccaacbcbabbbaaaccacaaabacbbabbcacbcaaaaabaabab', 'acbabbccacaccabccbcbabacccbabbaacbccbcaabccbcbababccacbbbaabbaaaababbcaaaaabccbacbbcacbcacba', 'cbccbbaacacccacacacbbbcbbccabcaaaabbcacacacaccbacaacbcbcbccaacaaaaaacbacacbabbbcccabbbbababa', 'cabaabaccbbcccabaccbbacbcabbbbbaccccccbcbcbcbbccbaaabbbbcabacabccaacbcbcbabccbbcabacababccaab', 'bccaacbabcbccaccbabcbbcbaaccbaacabbcabbbacbbccabcabccabccbacbaacbccabccaabaaabcaababacacccaac', 'aacabcccaaccacbbcbbbbacaacacbcbcaabbcbbacbabcbccaabcbbbbaabccbbbacaababcabaacaccababacbcbccbba', 'caaabbcbcbcabccccacacaaababbacbabacbaaccbcbabbaaacbbccccaaaabbccbcabcbccbbaaccbbbabcaabcbbbcab', 'aacbbcbbcbaccccbaaaabcbaaabaaacaacaaacacacabaaabacbaaaacccbaaabbbcbbbacbcbccabccaabbaabcbcbccba', 'abaccbcacabbbbacabaacaccbcbaabbaccaabbbbbababbbcbbbbacaacabbbabcaccbacabbabcbbacbbaaccbcbacaabc', 'aacaaaacccabcccacacbaaccccababcaccaccacbbbacabccbbcbbbacaccbbbbbaabacbacbcbcabccaaccababacaabcbb', 'baabbabaaccabcbbabcacccccaabbccbccbcaacbbbccccbbcbacaabcccccbbabbabbcacbbccbcacabbbbaaaaccbcacca', 'aabacbaacbbccabbbacbcbbbabacaacccabbcabacacaaaabbcbbbcbbbcababbccbbacbbabcaacbacbbcaabbbcbaaaccaa', 'aacabaaccaaabcacccabbaabbcacbabccacabaccaaaaccccccaabcbbbaabcbcccacaccbcaaacaaaabaababccbbbcccaac', 'bcaccbcacaccbacbcccbcbbcabaabbabcccbaaababbbabbcbcbcaabbabbccccbabccabbccccabaaabccbacabccabbbacaa', 'ccaacbabcccbabacabaccccbcbbcccbbbacbbbcccacababccbbaaaaababbabccbccabcccbccabaccbcbcacbbbaacabccaa', 'caccbababcbcbabccabcbbaccbbbabcbacbcbcbcabcbacbcacabbcaabbbbbbbcbbaabcacccbcaabccacbccbbcccaabcbcac', 'bbcccaabacbacbccbbbbbaabccaaabbaabcaabbcbabbbaabcbcbacbaccabacacaaaababccaaaccacaabaabcacbcaccbaabb' ]; var call = 0; function guess(S, len) { var sym = {}; recurse(S, len, "", sym); return sym.result; } function recurse(S, len, s, sym) { var dictionary = []; if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) { if(s.length == len) { sym.result = s; } else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) { dictionary = [ Array(len - s.length + 1).join('a') ]; } else { dictionary = [ "a", "b", "c" ]; } dictionary.some(function(e) { return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym); }); return true; } return false; } function isCandidate(s, sym) { return sym[s] === undefined && Object.keys(sym).every(function(k) { return count(s, k) <= sym[k]; }); } function count(s0, s1) { return (s0.match(new RegExp(s1, 'g')) || []).length; } function numOccur(S, s) { call++; return count(S, s); } test.forEach(function(S) { if(guess(S, S.length) != S) { console.log("Failed for: '" + S + "'"); } }); console.log(call + " calls"); ``` [Answer] # Python, 15205 calls ``` def findS(S, len_s, alphabeth = "abc"): if len_s == 0: return "" current = "" add_at_start = True while len(current) < len_s: worked = False for letter in alphabeth: if add_at_start: current_new = current + letter else: current_new = letter + current if num_occur(current_new, S) > 0: current = current_new worked = True break if not worked: add_at_start = False return current ``` This submission is most likely suboptimal, because it only uses `num_occur` to check if a string is a substring of `S`, and it never uses it to actually count the amount of substrings. The algorithm works by storing a string `current` which is built up to be equal to `S` in the end. Here are all the steps in the algorithm: 1. We set `current` equal to `''` 2. Go through each letter in the alphabet, and do the following: 2.1. Create a new string `current_new`, and set it equals to `current` followed by the letter. 2.2. Check if `current_new` is included in `S` by running `num_occur` on it and see if the result is greater than one. 2.3. If `current_new` is included in `S`, set `current` to `current_new` and go back to step 2. Else, we go to the next letter. 3. If the length of `current` is equal to the length of `S` we can say that we are done. Else, we go back to step 2, but modify step 2.1 to make `current_new` equal to the letter followed by `current` instead. When we reach this step again, we are done. [Answer] # Python 2, ~~14952~~ 14754 calls Very similar to the first answer, but doesn't try next characters which result in impossible substrings that: * we know from `num_occur` that they don't occur in the target (from previous calls) * we already used the substring more often than it occurs according to `num_occur` ~~(will add counting of substrings in a minute)~~ done ``` def get_that_string(h,l,alpha = "abc"): dic = {} s = "" ##costs 1 additional call per example, but its worth it char_list = [num_occur(j,h) for j in alpha[:-1]] char_list.append(l - sum(char_list)) for y, z in zip(char_list,alpha): dic[z] = y end_reached = False while len(s) < l: for t in alpha: if not end_reached: neu_s = s + t substrings = [neu_s[i:] for i in range(len(neu_s))] else: neu_s = t + s substrings = [neu_s[:i+1] for i in range(len(neu_s))] ## Test if we know that that can't be the next char all_in_d = [suff for suff in substrings if suff in dic.keys()] poss=all(map(dic.get,all_in_d)) if poss: if not neu_s in dic.keys(): dic[neu_s] = num_occur(neu_s,h) if dic[neu_s] > 0: s=neu_s for suff in all_in_d: dic[suff] -= 1 break else: end_reached = True ##print s return s ## test suite start import urllib def num_occur(needle, haystack): global calls calls += 1 num = 0 for i in range(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: num += 1 return num calls = 0 url = "https://raw.githubusercontent.com/iatorm/random-data/master/abc_strings.txt" inputs = urllib.urlopen(url).read().split("\n") print "Check: ", inputs == map(lambda h: get_that_string(h, len(h)), inputs) print "Calls: ", calls ``` [Answer] # Python ~~12705~~ 12632 calls 1. make a list of 2 characters strings occurrences 2. sort the list 3. build the string trying the most probable character first, don't test if there is only one possibility 4. update the list 5. if the list is empty it is finished else step 2 *I used Loovjo function skeleton. I never code in Python I needed a bootsrap* **EDIT:** *Added code for one character length strings* *Added code to reject already matched patterns* ``` def finds(S): if len(S) == 0: return "" if len(S) == 1 if num_occur("a",S) == 1 : return "a" if num_occur("b",S) == 1 : return "b" return "c" tuples=[] alphabet=[ "aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb"] for s in alphabet : tuples.append( (num_occur(s,S), s) ) sum=0 for (i,s) in tuples : sum+=i tuples.append( (len(S)-sum-1, "cc") ) tuples.sort(key=lambda x:(-x[0],x[1])) (i, current) = tuples[0] tuples[0] = (i-1, current) add_at_start = True nomatch=[] while len(tuples) > 0: worked = False tuples.sort(key=lambda x:(-x[0],x[1])) count=0 if not add_at_start : for (n, s) in tuples : if s[0]==current[-1:] : count+=1 for i in range(len(tuples)): (n, s)=tuples[i] if add_at_start: if current[0] == s[1] : current_new = s[0] + current possible=True for nm in nomatch : lng=len(nm) if current_new[0:lng] == nm : possible=False break if possible and num_occur(current_new, S) > 0: current = current_new worked = True else : nomatch.append(current_new) else: if current[-1:] == s[0] : current_new = current + s[1] possible=True for nm in nomatch : lng=len(nm) if current_new[-lng:] == nm : possible=False break if count == 1 or (possible and num_occur(current_new, S) > 0) : current = current_new worked = True else : nomatch.append(current_new) if worked : if n == 1: del tuples[i] else : tuples[i] = (n-1, s) break if not worked: add_at_start = False return current ``` ]
[Question] [ ## Challenge You just bought a brand new chair! Problem is, you have no idea how to control it so you'll need to write a program to do it for you. [![Example of an adjustable chair](https://i.stack.imgur.com/dg3mt.jpg)](https://i.stack.imgur.com/dg3mt.jpg) You can only sit in the unadjusted chair for so long. So your code will need to be as short as possible. ## Examples ``` 5,3,2,2,1 O | | | _ | | |_|_ | | O ``` ``` 3,5,2,3,5 O | _ | | |__|__ | | __|__ OOOOO ``` ``` 2,13,1,1,13 O | _ |______|______ ______|______ OOOOOOOOOOOOO ``` *Am I the only one who thinks this look like an airplane?* ## Chair parts The chair has various components: ``` O | | <- Backrest | _ <- Armrest | | |__|__ <- Seat | | <- Leg _|_ OOO <- Wheels ``` ## Input You will be outputting a chair given various variables. The input will be in the following order, all inputs will be positive integers (always greater than 0) and will always be provided. 1. Backrest Height 2. Seat Width **always odd** 3. Armrest Height **Always less than backrest height** 4. Leg Height 5. Wheel count **Always less than or equal to seat width** and **Always odd** ## Detailed part Descriptions The parts of the chair are: --- **Backrest:** This amount of `|` is the **Backrest Height** ``` O | | ``` **Seat:** The amount of `_` is the **Seat Width**, insert a `|` in the middle for the armrest. ``` __|__ ``` **Armrest:** The amount of `|` is the **Armrest Height**. This should be inserted in the middle of the seat. ``` _ | | ``` **Leg:** The amount of `|` is determined by **Leg Height** ``` | | ``` **Wheels:** The wheels are centered below the legs. If they are more than one, all but the center wheel should have `_` in the line above them. ``` _ _ OOO ``` ## Output The output may have a trailing newline. Each line may have trailing spaces. Leading whitespace is not allowed [Answer] # JavaScript (ES6), 197 bytes ``` (b,s,a,l,w)=>eval('o="";for(i=0;i<b+l+2;i++)o+=(i?i>b?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(i<b+l?x:"_")[r](w/2))+"|"+p):"|"+(p=(i-b?x=" ":"_")[r="repeat"](s/2))+(i>b-a?"|":i<b-a?x:"-")+p:"O")+`\n`') ``` ## Explanation Well this got rather convoluted quite quickly. I'll just comment on what each line does at a high level. Hopefully with this formatting it's not too hard to follow all the ternary operators. ``` (b,s,a,l,w)=> eval( o=""; for(i=0;i<b+l+2;i++) // for each line o+=(i? // add to output // Leg lines i>b? x[r](s/2-w/2+1) // spaces before wheels +( i>b+l? "O"[r](w) // wheels : (p=(i<b+l?x:"_")[r](w/2)) // spaces or wheel cover before leg +"|" // leg +p // spaces or wheel cover after leg ) // Backrest lines : "|" // backrest +(p=(i-b?x=" ":"_")[r="repeat"](s/2)) // spaces or seat before armrest +(i>b-a?"|":i<b-a?x:"-") // armrest +p // spaces or seat after armrest // Headrest line :"O") +\`\n\` ) ``` ## Test ``` var solution = (b,s,a,l,w)=>eval('o="";for(i=0;i<b+l+2;i++)o+=(i?i>b?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(i<b+l?x:"_")[r](w/2))+"|"+p):"|"+(p=(i-b?x=" ":"_")[r="repeat"](s/2))+(i>b-a?"|":i<b-a?x:"-")+p:"O")+`\n`') ``` ``` Input separated by commas (,) = <input type="text" id="input" value="5,3,2,3,5" /> <button onclick="result.textContent=solution(...input.value.split(',').map(x=>+x))">Go</button> <pre id="result"></pre> ``` [Answer] # Python 2, 157 bytes ``` b,s,a,l,w=input() y,z,n,A='|_\n ' s/=2;W=w/2;x=A*s;X=n+A*(s-W+1);Y=n+y print'O'+Y*(b-a-1)+Y+x+z+(Y+x+y)*(a-1)+n+(y+z*s)*2+(n+A+x+y)*(l-1)+X+z*W+y+z*W+X+'O'*w ``` --- **Example:** `3,7,1,2,5` ``` O | | _ |___|___ | __|__ OOOOO ``` [Answer] # JavaScript (ES6), 182 An anonymous function. Using template strings, there are 3 newlines that are significant an included in the byte count. ``` (b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=` `+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=` `+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,` `+R()+v)+f+g+v+g+f+R(w,'O') ``` No loops, using repeat for the same purpose. **Less golfed** ``` (b, s, a, l, w, // parameters // local variables as parameters with default values R = (x=s/2,c=' ')=>c.repeat(x), // shortcut for repeat f = `\n`+R(s/2+1-w/2), // filler before the wheels (used twice) h = R(s/2,'_'), // half seat (used twice) g = R(w/2,'_'), // last wheel support (used twice) v = '|', // vertical bar (used many times) u = `\n`+v // newline + bar (define below in the golfed version) )=> 'O'+R(b+~a, u)+ // backrest u+R()+'_'+ // backrest + armrest top R(a-1, u+R()+v)+ // backrest + armrest u+h+v+h+ // seat R(l-1, `\n`+R()+v)+ // leg f+g+v+g+ // wheels support f+R(w, 'O') // wheels ``` **Test Snippet** ``` f=(b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=` `+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=` `+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,` `+R()+v)+f+g+v+g+f+R(w,'O') console.log=x=>O.innerHTML=x+'\n' function test() { p=I.value.match(/\d+/g).map(x=>+x) console.log(p+'\n'+f(...p)+'\n') } ``` ``` Input <input type="text" id="I" value="5,5,3,2,3" /> <button onclick="test()">Go</button> <pre id="O"></pre> ``` [Answer] # LabVIEW, 146 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) This got a lot bigger than I imagined... There won't be a GIF this time, on the one Hand because of the size on the other hand because there's no way anyone can follow all the data flowing. It does work, unless you get LabVIEW and suggest a file hoster there will be no way to check though. [![](https://i.stack.imgur.com/QfoU3.jpg)](https://i.stack.imgur.com/QfoU3.jpg) [Answer] # SpecBAS - ~~185~~ 168 bytes ``` 1 INPUT b's'a'l'w: sx=(s/2)+1,wx=sx-(w/2) 2 ?"o"'("|"#13)*b 3 ?AT b,1;"_"*s;AT b+l,wx;"_"*w;AT b-a,sx;"-" 4 FOR i=b+1-a TO b+l: ?AT i,sx;"|": NEXT i 5 ?AT b+l+1,wx;"0"*w ``` Now that SpecBAS allows `?` to be used instead of `PRINT` and doesn't need `LET` before variable assignment, it starts being a bit better at golfing. Also helps that you can specify y,x print positions to avoid having to work out lots of spacing. This prints back, seat, arms and legs then wheels. EDIT: to print the back, replace a `FOR...NEXT` loop with pipe + return multiplied by the height (`("|"#13)*b`) [![enter image description here](https://i.stack.imgur.com/dqRkB.png)](https://i.stack.imgur.com/dqRkB.png) [Answer] ## Perl, 181 bytes *includes +1 for `-n`. Put in a file and `echo 5,3,2,2,1 | perl -n file.pl`* ``` ($b,$s,$a,$l,$w)=/\d+/g;$,=$/;print'O',('|')x($b-$a-1),($D='|'.$"x($s/=2)).'_',("$D|")x--$a,($q='|'.'_'x$s).$q,($"x$s.' |')x--$l,($x=$"x(1+$s-($W=$w/2))).'_'x$W.'|'.'_'x$W,$x.O x$w ``` With comments: ``` #!/usr/bin/perl -n # -n: iterate stdin, put in $_ ($b,$s,$a,$l,$w)=/\d+/g; # get the parameters $,=$/; # set $OUTPUT_FIELD_SEPARATOR to \n; # this is printed between each of print's args print # shorter than `-p` and @_=(...); $"=$/; $_="@_"; 'O', # the headrest ('|')x($b-$a-1), # space between headrest and armrest. # (...) x $n: produces $n lists. ($D='|' . $"x($s/=2)) # backrest and padding ($"=' ') up to armrest . '_', # armrest. ("$D|")x--$a, # backrest, padding, armrest ($q='|' . '_'x$s) . $q, # backrest bottom and 1/2 seat, armrest bottom and 1/2 seat ($" x $s . ' |' ) x --$l, # padding before leg and leg, repeated leg-1 times ( $x = $" x (1+$s - ($W=$w/2) ) # padding before wheel top ) . '_'x$W . '|' # left side of wheel top, wheel top, . '_'x$W, # right side of wheel top $x . O x$w # padding before wheels, wheels ``` ]
[Question] [ You are given a partially filled Connect 4 grid (7x6). ``` O X O X X O X O O X O X O X X O X X X O O X O O O X X O X ``` (Input can be given as a 1D or 2D array and as letters or numbers, etc.) Assume that * X started the game. * Nobody has won yet. * Players may not have played well until now, but now onwards they will both employ optimal strategies. * Input grid is not faulty. You must output a single value that indicates which player wins (or a draw) Code golf challenge; so shortest code wins. Your program does not have to actual compute the output in reasonable amount of time, but you should be able to prove that the output will be obtained correctly in a finite amount of time. [Answer] # Perl, ~~119~~ ~~118~~ 117 bytes Includes +4 for `-0p` Give rotated board padded with spaces on STDIN (gravity pulls stones to the right) ``` connect4.pl OXXX XOO OX OOXX XXXO XXOOXO OOXXOO ^D ``` `connect4.pl`: ``` #!/usr/bin/perl -p0 y/XO/OX/if$^S|y/X//>y/O//;$_=$$_||=/Z@{[map"|O".".{$_}O"x3,0,5..7]}/sx||s% (?! )%$_="$`X$'";do$0%eg?/1/?3:1+/2/:2 ``` Prints `3` if player to move wins, `1` if player to move loses and `2` for a draw. On older perls you can use a literal `^S` to gain one byte. If you don't mind ***extreme*** inefficiency you can leave out the `$$_||=` (transposition table) and gain 6 more bytes. If you leave out the `$_=` it will show you where to play instead of the result (play on `1` and win if there is one, play on `2` and draw if there is one or play on any `3` and lose) Builds and evaluates a complete minimax tree. You will run out of memory and time unless the board is already reasonably well filled. ]
[Question] [ Without using any built-in factoring/polynomial functions, factor a polynomial completely into irreducibles over the integers or a finite field. # Input Your program/function will receive some prime (or zero) number `n` as input. The field/ring is the finite field of that order (ie `Z/nZ`), or just `Z` if `n` is `0`. Your program may fail if `n` is not `0` or a prime. The polynomial will be in `F[x]`. Your program/function will also receive the polynomial as input. There is some flexibility in the input, be sure to specify how you intend to receive input. For example, the polynomial could be input as a list of coefficients, or in the form most people expect (ex:`50x^3 + x^2`), or some other reasonable form. Or the format of inputting the field/ring could also be different. # Output Your program/function will output the polynomial factored completely. You may leave multiple roots expanded (ie `(x + 1)(x + 1)` instead of `(x + 1)^2`). You may remove whitespace between binary operators. You may replace juxtaposition with `*`. You may insert whitespace in weird places. You may reorder the factors into whatever order you want. The `x` term could just be `(x)`. `x` can be written as `x^1`; however the constant term **may not** have `x^0`. Extraneous `+` signs are allowable. You **may not** have a term with a `0` in front, they **must** be left out. The leading term of each factor **must** be positive, negative signs must be outside. Test cases, your program should be able to produce output for each of these in reasonable time (say, <= 2 hours): Input: `2, x^3 + x^2 + x + 1` Output: `(x + 1)^3` Input: `0, x^3 + x^2 + x + 1` Output: `(x + 1)(x^2 + 1)` Input: `0, 6x^4 – 11x^3 + 8x^2 – 33x – 30` Output: `(3x + 2)(2x - 5)(x^2 + 3)` Input: `5, x^4 + 4x^3 + 4x^2 + x` Output: `x(x + 4)(x + 4)(x + 1)` Input: `0, x^5 + 5x^3 + x^2 + 4x + 1` Output: `(x^3 + 4x + 1)(x^2 + 1)` Special thanks to Peter Taylor for critiquing my test cases [Answer] ## GolfScript (222 bytes) ``` ~.@:[[email protected]](/cdn-cgi/l/email-protection)\{abs+}/2@,2/)?*or:^{\1$^base{^q- 2/-}%.0=1=1$0=q>+{{:D[1$.,2$,-)0:e;{.0=0D=%e|:e;(D(@\/:x@@[{x*~)}%\]zip{{+}*q!!{q%}*}%}*e+])0-{;0}{@;@\D.}if}do}*;\).^3$,)2/?<}do;][[1]]-{'('\.,:x;{.`'+'\+'x^'x(:x+x!!*+\!!*}%')'}/ ``` [Online demo](http://golfscript.apphb.com/?c=OycyWzEgMSAxIDFdJwoKfi5AOnFALjBce2Ficyt9LzJALDIvKT8qb3I6XntcMSReYmFzZXtecS0gMi8tfSUuMD0xPTEkMD1xPit7ezpEWzEkLiwyJCwtKTA6ZTt7LjA9MEQ9JWV8OmU7KEQoQFwvOnhAQFt7eCp%2BKX0lXF16aXB7eyt9KnEhIXtxJX0qfSV9KmUrXSkwLXs7MH17QDtAXEQufWlmfWRvfSo7XCkuXjMkLCkyLz88fWRvO11bWzFdXS17JygnXC4sOng7ey5gJysnXCsneF4neCg6eCt4ISEqK1whISp9JScpJ30v) ### Notes 1. The input format is `n` followed by a GolfScript array of coefficients from most to least significant. E.g. `0, x^5 + 5x^3 + x^2 + 4x + 1` should be formatted as `0 [1 0 5 1 4 1]`. 2. Over a finite field, there are only finitely many polynomials of sufficiently small degree to be relevant. However, this is not the case over `Z`. I handle `Z` by using a relaxed form of Mignotte's height bound. A great paper on height bounds in factoring is [Bounds on Factors in Z[x]](http://arxiv.org/abs/0904.3057), John Abbott, 2009 (link is to arxiv preprint; his CV says that it has been accepted by the *Journal of Symbolic Computation*). The most relaxed form given there is in terms of the L-2 norm, but to save bytes I relax further and use the L-1 norm instead. Then it's a case of brute forcing by trial division. 3. Over a finite field, every polynomial is a constant times a monic polynomial, so I only do trial division by monic polynomials and save a reciprocal in the field. However, `Z` is only a ring and so it's necessary to do trial division by non-monic candidate factors. I manage to get away with not implementing rational numbers by doing a leading factor division test and accumulating an "error" flag in `e`. 4. Both points 2 and 3 imply that the case of factoring over `Z` is generally slower, and can't be tested with the online demo. However, the slowest of the official test cases takes 10 minutes, which is well within the "reasonable" time limit. ]
[Question] [ Imagine the following diagrams as sets of vertical criss-crossing tubes. ``` 1 2 1 2 1 2 3 4 \ / \ / \ / \ / X | | | / \ / \ / \ / \ 2 1 1 2 | X | \ / \ / X X / \ / \ 3 1 4 2 ``` In the leftmost diagram, the `1` and `2` slide down their respective slashes, cross at the `X`, and come out at opposite sides from where they started. It's the same idea in the middle diagram, but the `|` signifies that the paths do not cross, so nothing changes. The rightmost diagram shows a more complex tube routing that permutes `1 2 3 4` into `3 1 4 2`. # Goal Your goal in this code golf challenge is to draw these "tube routing diagrams" given a permutation such as `3 1 4 2`. The shortest program in bytes will win. # Details 1. Input comes from stdin as any permutation of the numbers from 1 to *n* separated by spaces, where *n* is a positive integer. You may assume all input is well formed. 2. The routing diagram output goes to stdout. * "Dropping" the numbers 1 through *n* in order into the top of the diagram should result in the input permutation coming out at the bottom. (Top and bottom are always layers of slashes.) * The diagram does not need to be optimally small. It may be as many levels as necessary as long as it is correct. * The diagram should only contain the characters `\/ X|` as well as newlines (no numbers). * `|` should always be used on the outermost intersections since using `X` wouldn't make sense. * A few leading or trailing spaces is fine as long as the diagram is all lined up correctly. # Examples An input of `3 1 4 2` might produce (same as above) ``` \ / \ / | | / \ / \ | X | \ / \ / X X / \ / \ ``` An input of `1` might produce ``` \ | / | \ | / ``` An input of `3 2 1` might produce ``` \ / \ X | / \ / | X \ / \ X | / \ / ``` An input of `2 1 3 4 6 5` might produce ``` \ / \ / \ / X | X / \ / \ / \ ``` [Answer] ## Python, 290 ``` def g(o,u=1): s=['|']*o for i in range(o,n-1,2):v=r[i+1]in a[:a.index(r[i])]*u;s+=['|X'[v]];r[i:i+2]=r[i:i+2][::1-2*v] print' '*(1-o)+' '.join(s+['|']*(o^n%2))*u+'\n'*u+(' / \\'*n)[2*o:][:n*2] a=map(int,raw_input().split()) n=len(a) r=range(1,n+1) o=1 g(1,0) g(0) while r!=a:g(o);o^=1 ``` I went for a fairly basic approach, but it turned out a bit longer than I was hoping. It considers the list in pairs and decides whether or not to swap each pair. This is repeated for every intersecting row until the list matches the input. Example: ``` $ python path.py 5 3 8 1 4 9 2 7 6 \ / \ / \ / \ / \ | | | X | / \ / \ / \ / \ / | X X X X \ / \ / \ / \ / \ X X X X | / \ / \ / \ / \ / | X X | X \ / \ / \ / \ / \ X X X | | / \ / \ / \ / \ / | | | X | \ / \ / \ / \ / \ ``` [Answer] # Python 2, 218 219 220 222 224 227 243 247 252 259 261 264 ``` l=map(int,raw_input().split()) f=n=len(l) o=s=n*' \ /' while f+n%2: f-=1;i=f+n&1;a=s[2*i:][:2*n]+'\n| '[::2-i] while~i>-n:a+='|X'[l[i+1]<l[i]]+' ';l[i:i+2]=sorted(l[i:i+2]);i+=2 o=a+f%2*'|'+'\n'+o print o[:-2*n] ``` I took a slightly different approach: I find the swaps necessary to sort the input, then vertically invert that to get the swaps necessary to turn the sorted list into the input. As an added bonus of this approach, it can take an arbitrary list of numbers and give the permutation path to turn the sort of the input into the input. Example: ``` $ python sort_path.py <<< '3 1 4 5 9 2 6 8 7' \ / \ / \ / \ / \ | | | | | / \ / \ / \ / \ / | | | | | \ / \ / \ / \ / \ | | | | | / \ / \ / \ / \ / | | | | | \ / \ / \ / \ / \ | | | | | / \ / \ / \ / \ / | X | | X \ / \ / \ / \ / \ | X | X | / \ / \ / \ / \ / | | X X | \ / \ / \ / \ / \ X | X | | / \ / \ / \ / \ / | | | | X \ / \ / \ / \ / \ ``` Improvements: 264 -> 261: Switched outer loop from for to while. 261 -> 259: Used `f%2` instead of `(c^m)`, because in python arithmetic operators have higher priority than bitwise operators. 259 -> 252: Switched inner loop from for to while. Combined `i` and `c` variables. 252 -> 247: Changed build then reverse to just build in reverse order. 247 -> 243: Added newlines manually, instead of using join. 243 -> 227: Adopted grc's method of slash line generation (thanks grc!) and added s. 227 -> 224: Moved slash line generation to before inner while loop to remove a `%4` and save a character by using extended slicing. 224 -> 222: Removed m. 222 -> 220: `f%2+n%2` -> `f+n&1` 220 -> 219: `| 1<n-1|` -> `|~i>-n|` (removed leading space) 219 -> 218: Combined initializations of `o` and `s` and moved the slice to the end. [Answer] ## HTML JavaScript, ~~553~~ 419 Thank you to @izlin and @TomHart for pointing out my errors. ``` p=prompt();b=p.split(" "),l=b.length,d=l%2,o="",s=["","","\\/"],n="\n",a=[];for(i=0;i<l;i++){a[b[i]-1]=i+1;s[1]+=" "+s[2][i%2];s[0]+=" "+s[2][(i+1)%2];o+=" "+(i+1)}s[1]+=n,s[0]+=n;o+=n+s[1];f=1,g=2;do{var c="";for(var i=(f=f?0:1);i<l-1;i+=2)if(a[i]>a[i+1]){c+=" x ";g=2;t=a[i];a[i]=a[i+1];a[i+1]=t;}else c+=" | ";if(g==2){o+=(d?(f?"| "+c:c+" |"):(f?"| "+c+" |":c))+n;o+=(s[f]);}}while(--g);o+=" "+p;alert(o); ``` Test here: <http://goo.gl/NRsXEj> ![enter image description here](https://i.stack.imgur.com/yxFo9.png) ![enter image description here](https://i.stack.imgur.com/Ns0Pw.png) [Answer] ## Javascript - 395 378 if i don't print the numbers on my output, but it looks much better and improves the readability. [Test it here](http://jsfiddle.net/29rr7/3/). (with ungolfed version) golfed Version: ``` a=prompt(),n=a.split(" "),l=n.length,k=[],s="",i=1;for(j=0;j<l;j++){k[n[j]-1]=j+1;s+=" "+(j+1)}s+="\n";while(i++){for(j=0;j<l;j++)s+=i%2?j%2?" \\":" /":j%2?" /":" \\";for(z=0,y=0;z<l-1;z++)if(k[z]>k[z+1])y=1;if(y==0&&i!=2)break;s+="\n";for(m=i%2;m<l;m+=2){s+=i%2&&m==1?"|":"";if(k[m]>k[m+1]){[k[m],k[m+1]]=[k[m+1],k[m]];s+=i%2?" X":" X "}else{s+=i%2?" |":" | "}}s+="\n"}s+="\n "+a;alert(s) ``` ### Explanation First I substitude the input, with the index number and change the first line with the results. For example ``` 3 1 4 2 v v v v substitude with 1 2 3 4 so the first line will become: 1 2 3 4 v v v v 2 4 1 3 sorting 1,2,3,4 to 3,1,4,2 is equivalent to 2,4,1,3 to 1,2,3,4 ``` With this substitution i can use a bubble-sort algorithm to sort 2,4,1,3 to 1,2,3,4 and the graph will be the shortest possible one we're searching for. If you have any ideas how i can make the code smaller just comment :) ### Example ``` input: 3 4 2 1 7 5 6 output: 1 2 3 4 5 6 7 \ / \ / \ / \ X | | | / \ / \ / \ / | X | X \ / \ / \ / \ X X X | / \ / \ / \ / | X | | \ / \ / \ / \ 3 4 2 1 7 5 6 ``` [Answer] # Cobra - 334 ~~344~~ ~~356~~ ~~360~~ ``` class P def main a,o,n=CobraCore.commandLineArgs[1:],['/','\\'],0 c,l=a.count,a.sorted while (n+=1)%2or l<>a p,d='',(~n%4+4)//3 for i in n%2*(c+1-c%2),p,o=p+o[1]+' ',[o.pop]+o for i in 1+d:c-n%2*c:2 z=if(l[:i]<>a[:i],1,0) l.swap(i-z,i) p+=' ['|X'[z]] ' print[['','| '][d]+[p,p+'|'][d^c%2],p][n%2][:c*2] ``` It works by moving each element into place starting from the left. Due to this, it will often output a ridiculously large (although still correct) path-map. ## Examples: ``` 3 1 4 2 \ / \ / X X / \ / \ | X | \ / \ / X X / \ / \ | X | \ / \ / X X / \ / \ | X | \ / \ / ``` ]
[Question] [ The general [SAT](http://en.wikipedia.org/wiki/Boolean_satisfiability_problem) (boolean satisfiability) problem is NP-complete. But [2-SAT](http://en.wikipedia.org/wiki/2-satisfiability), where each clause has only 2 variables, is in [P](http://en.wikipedia.org/wiki/P_%28complexity%29). Write a solver for 2-SAT. Input: A 2-SAT instance, encoded in [CNF](http://en.wikipedia.org/wiki/Conjunctive_normal_form) as follows. The first line contains V, the number of boolean variables and N, the number of clauses. Then N lines follow, each with 2 nonzero integers representing the literals of a clause. Positive integers represent the given boolean variable and negative integers represent the variable's negation. ## Example 1 ### input ``` 4 5 1 2 2 3 3 4 -1 -3 -2 -4 ``` which encodes the formula *(x1 or x2) and (x2 or x3) and (x3 or x4) and (not x1 or not x3) and (not x2 or not x4)*. The only setting of the 4 variables that makes the whole formula true is *x1=false, x2=true, x3=true, x4=false*, so your program should output the single line ### output ``` 0 1 1 0 ``` representing the truth values of the V variables (in order from *x1* to *xV*). If there are multiple solutions, you may output any nonempty subset of them, one per line. If there is no solution, you must output `UNSOLVABLE`. ## Example 2 ### input ``` 2 4 1 2 -1 2 -2 1 -1 -2 ``` ### output ``` UNSOLVABLE ``` ## Example 3 ### input ``` 2 4 1 2 -1 2 2 -1 -1 -2 ``` ### output ``` 0 1 ``` ## Example 4 ### input ``` 8 12 1 4 -2 5 3 7 2 -5 -8 -2 3 -1 4 -3 5 -4 -3 -7 6 7 1 7 -7 -1 ``` ### output ``` 1 1 1 1 1 1 0 0 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1 0 ``` (or any nonempty subset of those 3 lines) Your program must handle all N,V < 100 in a reasonable time. Try [this example](http://keithandkatie.com/hard2sat.txt) to make sure your program can handle a big instance. Smallest program wins. [Answer] ## Haskell, 278 characters ``` (∈)=elem r v[][]=[(>>=(++" ").show.fromEnum.(∈v))] r v[]c@(a:b:_)=r(a:v)c[]++r(-a:v)c[]++[const"UNSOLVABLE"] r v(a:b:c)d|a∈v||b∈v=r v c d|(-a)∈v=i b|(-b)∈v=i a|1<3=r v c(a:b:d)where i w|(-w)∈v=[]|1<3=r(w:v)(c++d)[] t(n:_:c)=(r[][]c!!0)[1..n]++"\n" main=interact$t.map read.words ``` Not brute force. Runs in polynomial time. Solves the hard problem (60 variables, 99 clauses) quickly: ``` > time (runhaskell 1933-2Sat.hs < 1933-hard2sat.txt) 1 1 1 0 0 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 real 0m0.593s user 0m0.502s sys 0m0.074s ``` *And actually, most of that time is spent compiling the code!* Full source file, with test cases and quick-check tests [available](https://bitbucket.org/mtnviewmark/haskell-playground/src/c4dd324f35f7/golf/1933-2Sat.hs). **Ungolf'd:** ``` -- | A variable or its negation -- Note that applying unary negation (-) to a term inverts it. type Term = Int -- | A set of terms taken to be true. -- Should only contain a variable or its negation, never both. type TruthAssignment = [Term] -- | Special value indicating that no consistent truth assignment is possible. unsolvable :: TruthAssignment unsolvable = [0] -- | Clauses are a list of terms, taken in pairs. -- Each pair is a disjunction (or), the list as a whole the conjuction (and) -- of the pairs. type Clauses = [Term] -- | Test to see if a term is in an assignment (∈) :: Term -> TruthAssignment -> Bool a∈v = a `elem` v; -- | Satisfy a set of clauses, from a starting assignment. -- Returns a non-exhaustive list of possible assignments, followed by -- unsolvable. If unsolvable is first, there is no possible assignment. satisfy :: TruthAssignment -> Clauses -> [TruthAssignment] satisfy v c@(a:b:_) = reduce (a:v) c ++ reduce (-a:v) c ++ [unsolvable] -- pick a term from the first clause, either it or its negation must be true; -- if neither produces a viable result, then the clauses are unsolvable satisfy v [] = [v] -- if there are no clauses, then the starting assignment is a solution! -- | Reduce a set of clauses, given a starting assignment, then solve that reduce :: TruthAssignment -> Clauses -> [TruthAssignment] reduce v c = reduce' v c [] where reduce' v (a:b:c) d | a∈v || b∈v = reduce' v c d -- if the clause is already satisfied, then just drop it | (-a)∈v = imply b | (-b)∈v = imply a -- if either term is not true, the other term must be true | otherwise = reduce' v c (a:b:d) -- this clause is still undetermined, save it for later where imply w | (-w)∈v = [] -- if w is also false, there is no possible solution | otherwise = reduce (w:v) (c++d) -- otherwise, set w true, and reduce again reduce' v [] d = satisfy v d -- once all caluses have been reduced, satisfy the remaining -- | Format a solution. Terms not assigned are choosen to be false format :: Int -> TruthAssignment -> String format n v | v == unsolvable = "UNSOLVABLE" | otherwise = unwords . map (bit.(∈v)) $ [1..n] where bit False = "0" bit True = "1" main = interact $ run . map read . words where run (n:_:c) = (format n $ head $ satisfy [] c) ++ "\n" -- first number of input is number of variables -- second number of input is number of claues, ignored -- remaining numbers are the clauses, taken two at a time ``` In the golf'd version, `satisfy` and `format` have been rolled into `reduce`, though in order to avoid passing `n`, `reduce` returns a function from a list of variables (`[1..n]`) to the string result. --- * Edit: (330 -> 323) made `s` an operator, better handling of the newline * Edit: (323 -> 313) first element from a lazy list of results is smaller than a custom short-circuit operator; renamed main solver function 'cause I like using `∮` as an operator! * Edit: (313 -> 296) keep clauses as a single list, not a list of lists; process it two elements at a time * Edit: (296 -> 291) merged the two mutually recursive functions; it was cheaper to inline `★` so test now renamed `∈` * Edit: (291 -> 278) inlined output formatting into results generation [Answer] # J, 119 103 ``` echo'UNSOLVABLE'"_`(#&c)@.(*@+/)(3 :'*./+./"1(*>:*}.i)=y{~"1 0<:|}.i')"1 c=:#:i.2^{.,i=:0&".;._2(1!:1)3 ``` * Passes all test cases. No noticeable runtime. * Brute force. Passes test cases below, oh, N=20 or 30. Not sure. * Tested via [completely brain-dead test script](https://gist.github.com/901212) (By visual inspection) **Edit:** Eliminated `(n#2)` and thus `n=:`, as well as eliminating some rank parens (thanks, isawdrones). Tacit->explicit and dyadic->monadic, eliminating a few more characters each. `}.}.` to `}.,`. **Edit:** Whoops. Not only is this a non-solution for large N, but `i. 2^99x` -> "domain error" to add insult to stupidity. Here's the ungolfed original version and brief explanation. ``` input=:0&".;._2(1!:1)3 n =:{.{.input clauses=:}.input cases=:(n#2)#:i.2^n results =: clauses ([:*./[:+./"1*@>:@*@[=<:@|@[{"(0,1)])"(_,1) cases echo ('UNSOLVABLE'"_)`(#&cases) @.(*@+/) results ``` * `input=:0&".;._2(1!:1)3` cuts input on newlines and parses numbers on each line (accumulating the results into input). * n is assigned to `n`, clause matrix assigned to `clauses` (don't need the clause count) * `cases` is 0..2n-1 converted to binary digits (all test cases) * `(Long tacit function)"(_,1)` is applied to each case in `cases` with all of `clauses`. * `<:@|@[{"(0,1)]` gets a matrix of the operands of the clauses (by taking abs(op number) - 1 and dereferencing from case, which is an array) * `*@>:@*@[` gets clause-shaped array of 'not not' bits (0 for not) via abuse of signum. * `=` applies the not bits to the operands. * `[:*./[:+./"1` applies `+.` (and) across the rows of the resulting matrix, and `*.` (or) across the result of that. * All of those results end up as a binary array of 'answers' for each case. * `*@+/` applied to results gives a 0 if there are results and 1 if there are none. * `('UNSOLVABLE'"_)` ``(#&cases) @.(*@+/) results` runs constant function giving 'UNSOLVABLE' if 0, and a copy of each 'solution' element of cases if 1. * `echo` magic-prints the result. [Answer] ## [K](https://github.com/kevinlawler/kona/) - 89 The same method as the J solution. ``` n:**c:.:'0:`;`0::[#b:t@&&/+|/''(0<'c)=/:(t:+2_vs!_2^n)@\:-1+_abs c:1_ c;5:b;"UNSOLVABLE"] ``` [Answer] # OCaml + Batteries, 438 436 characters Requires an OCaml Batteries Included top-level: ``` module L=List let(%)=L.mem let rec r v d c n=match d,c with[],[]->[String.join" "[?L:if x%v then"1"else"0"|x<-1--n?]]|[],(x,_)::_->r(x::v)c[]n@r(-x::v)c[]n@["UNSOLVABLE"]|(x,y)::c,d->let(!)w=if-w%v then[]else r(w::v)(c@d)[]n in if x%v||y%v then r v c d n else if-x%v then!y else if-y%v then!x else r v c((x,y)::d)n let(v,_)::l=L.of_enum(IO.lines_of stdin|>map(fun s->Scanf.sscanf s"%d %d"(fun x y->x,y)))in print_endline(L.hd(r[][]l v)) ``` I must confess, this is a direct translation of the Haskell solution. In my defense, that in turn is a direct coding of the algorithm [presented here](http://suraj.lums.edu.pk/~cs514s05/data/2SAT.pdf) [PDF], with the mutual `satisfy`-`eliminate` recursion rolled into a single function. An unobfuscated version of the code, minus the use of Batteries, is: ``` let rec satisfy v c d = match c, d with | (x, y) :: c, d -> let imply w = if List.mem (-w) v then raise Exit else satisfy (w :: v) (c @ d) [] in if List.mem x v || List.mem y v then satisfy v c d else if List.mem (-x) v then imply y else if List.mem (-y) v then imply x else satisfy v c ((x, y) :: d) | [], [] -> v | [], (x, _) :: _ -> try satisfy (x :: v) d [] with Exit -> satisfy (-x :: v) d [] let rec iota i = if i = 0 then [] else iota (i - 1) @ [i] let () = Scanf.scanf "%d %d\n" (fun k n -> let l = ref [] in for i = 1 to n do Scanf.scanf "%d %d\n" (fun x y -> l := (x, y) :: !l) done; print_endline (try let v = satisfy [] [] !l in String.concat " " (List.map (fun x -> if List.mem x v then "1" else "0") (iota k)) with Exit -> "UNSOLVABLE") ) ``` (the `iota k` pun I hope you'll forgive). [Answer] ## Ruby, 253 ``` n,v=gets.split;d=[];v.to_i.times{d<<(gets.split.map &:to_i)};n=n.to_i;r=[1,!1]*n;r.permutation(n){|x|y=x[0,n];x=[0]+y;puts y.map{|z|z||0}.join ' 'or exit if d.inject(1){|t,w|t and(w[0]<0?!x[-w[0]]:x[w[0]])||(w[1]<0?!x[-w[1]]:x[w[1]])}};puts 'UNSOLVABLE' ``` But it's slow :( Pretty readable once expanded: ``` n,v=gets.split d=[] v.to_i.times{d<<(gets.split.map &:to_i)} # read data n=n.to_i r=[1,!1]*n # create an array of n trues and n falses r.permutation(n){|x| # for each permutation of length n y=x[0,n] x=[0]+y puts y.map{|z| z||0}.join ' ' or exit if d.inject(1){|t,w| # evaluate the data (magic!) t and (w[0]<0 ? !x[-w[0]] : x[w[0]]) || (w[1]<0 ? !x[-w[1]] : x[w[1]]) } } puts 'UNSOLVABLE' ``` ]
[Question] [ An "Egyptian fraction" is a list of *distinct* fractions with a numerator of \$1\$. For example: \$ \frac 1 1+ \frac 1 2 + \frac 1 3 + \frac 1 6 \$ The "size" of an Egyptian fraction is just the number of terms involved. Your task is to take a positive integer \$n\$ and output the smallest Egyptian fraction that sums to \$n\$. In the case of ties (there are ties) you may output any of the tied fractions. Since the numerator is always 1 you may output your answer as a list of denominators instead. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code within the bounds of your chosen language and algorithm with answers being scored in bytes. Fast answers are encouraged but must take steps to achieve the goal such as removing unnecessary whitespace or giving the variables short names. Feel free to include **(fast)** in your answer title along with the language and byte count if you do give it a go for speed. ## Precision While our default precision is that the algorithm needs to be *theoretically* correct, if you try to do this challenge with floating point numbers you will get results that are wrong almost immediately. It's also not at all difficult to solve this challenge using only integers. For this reason in addition to being theoretically correct answers must also give correct calculations for \$n < 4\$. As an additional clarification *theoretically* correct means that you cannot for example assume some arbitrary bound on the size of the denominator to restrict your search space. Any bounds used to restrict the search space must be theoretically justified. ## Test cases The sizes for the first 3 solutions next to a potential output are: \$ 1, \frac 1 1\\ 4, \frac 1 1+ \frac 1 2 + \frac 1 3 + \frac 1 6 \\ 13, \frac 1 1+\frac 1 2+\frac 1 3+\frac 1 4+\frac 1 5+\frac 1 6+\frac 1 7+\frac 1 8+\frac 1 9+\frac 1{15}+\frac 1{18}+\frac 1{40}+\frac 1{42} \\ \$ The first two I have calculated and verified by hand. The third one was verified by a computer program that ran for about 5 seconds. Since the search space is infinite, I am not 100% sure that my program doesn't miss some potential solution. But I have hand verified that there are no solutions up to 11. And I do have a solution of size 13. My program doesn't find a solution for 4 in a reasonable amount of time but it is easy to check that the answer is at least 31 terms long, and my program confirms that it is at least 32 terms long. [Answer] # [Haskell](https://www.haskell.org/), 103 bytes ``` head.([1..]>>=).g 1 0 g b i a d=[[]|a<1]++[j:o|j<-[max(div(b-1)a)i+1..div(b*d)a],o<-g(b*j)j(a*j-b)$d-1] ``` [Try it online!](https://tio.run/##HYuxDoIwFEV3vuINDi3QxhonAyzORkaT0piHhdIKhYgxDny7Fd3uOTm3w/ne9H0Y0HrIYcDpdAVSeWAFTA/rn0B8Ci14SkEKzvcqateuCl2DmpOfUkWRU25AwDYyUIMFBJ1LqRbMhEoS6Q7j4jImB3wTbV@kZoIitcn6/WOsKap0zJhZt6OOYOxYTTeaCRXC59b2aObALseyDOy8@wI "Haskell – Try It Online") This uses iterative deepening depth-first search, using the bound \$\frac a{bd} ≤ \frac 1j ≤ \frac ab\$ on the first term \$\frac1j\$ of a size-\$d\$ Egyptian fraction for \$\frac ab\$. Unclear if this qualifies as “fast”, but it does solve \$n = 4\$ in a few seconds: \begin{split} 4 = {}&\frac11 + \frac12 + \frac13 + \frac14 + \frac15 + \frac16 + \frac17 + \frac18 + \frac19 + \frac1{10} + \frac1{11} + \frac1{12} + \frac1{13} \\ &+ \frac1{14} + \frac1{15} + \frac1{16} + \frac1{17} + \frac1{18} + \frac1{19} + \frac1{20} + \frac1{21} + \frac1{22} + \frac1{23} + \frac1{24} \\ &+ \frac1{25} + \frac1{26} + \frac1{27} + \frac1{28} + \frac1{30} + \frac1{34} + \frac1{100} + \frac1{11934} + \frac1{14536368}. \end{split} [Answer] # [Python 3](https://docs.python.org/3/), 159 130 125 bytes ``` f=lambda x,s={1},i=1,p=1,l=[]:i<7**x**x**x and f(x,s^{i},1+i*(i in s),p*i,l+[s]*(sum(p//y for y in s)==x*p))or min(l,key=len) ``` [Try it online!](https://tio.run/##NY1BCoMwFET3PcWHbpL4QYILQZpLdCsW0hrrpzEGY6lBPLvVSmFmMzPM83Fse5eta6Os7u61hgmDmuWCpCT6zVaVVUGXXIjpEGhXQ8O23W2mBWVCghGQg8DRC0KblKESLLw75tM0QtMPEI9eqUl4zregI8csvkxU1ji@nuFqvNUPA/kfs5M@NLaQn/aHH2HQ7mmYxIwXJ/ADuZERNow4X78 "Python 3 – Try It Online") Bruteforces trough all Egyptian fractions, in order of maximum denominator. A limit of \$7^{x^{x^x}}\$ is used to stop the program. Then the shortest fraction is picked. Now the elephant in the room is the upper bound \$7^{x^{x^x}}\$. This corresponds to the maximum denominator in an optimal solution. Let's see how this bound is obtained. Let's first make an upper bound for the length of the Egyptian fraction. To construct the egyptian fraction for `x`, we first greedily pick unit fractions, until the next one would get us over `x`. For example, if `x` is 2, then we would do \$\frac{1}{1}+\frac{1}{2}+\frac{1}{3}\$, stopping before \$\frac{1}{4}\$, since that would result in a sum greater then 2. Note that this initial tail has length less than \$e^x\$. Now we have \$2-(\frac{1}{1}+\frac{1}{2}+\frac{1}{3})=\frac{1}{6}\$. Here we got lucky, and the difference is already a unit fraction. If it isn't, we can use the [greedy algorithm](https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions) to turn the difference into a unit fraction. The amount of fractions that the greedy algorithm introduces is at most the denominator of the difference. The denominator is less than the numerator which is less than \$e^x!\$. Finally, if we have an integer egyptian fraction of length `l`, the numerator can be at most `l^l`. To see why, note that the numerator of the last fraction can't be greater than the product of the other numerators. Now we have the upper bound \$(e^x!)^{e^x!}\$. When \$x\ge 4\$, \$(e^x!)^{e^x!}<7^{x^{x^x}}\$. The seven takes care of values of \$x\$ less than 4. Proof for \$(e^x!)^{e^x!}<x^{x^{x^x}}\$: \$(e^x!)^{e^x!}<((e^x)^{e^x})^{(e^x){e^x}}=(e^{xe^x})^{e^{xe^x}}=e^{xe^xe^{xe^x}}=e^{xe^{x+xe^x}}\$ \$x+xe^x< x^x\$ \$xe^{x+xe^x} < x^{x^x}\$ \$e^{xe^{x+xe^x}}<7^{x^{x^x}}\$ [Answer] # [Python 3](https://docs.python.org/3/), ~~180~~ 161 bytes ``` def f(n): u,*r=0,(0,1,n,1) for l,q,a,b,*x in r: if a==0: if(l>u>0)<1:u=l;o=x if u<1or(u-l)*b>=a*q>0:r+=(l+1,q+1,a*q-b,q*b,*x,q),(l,q+1,a,b,*x) return o ``` [Try it online!](https://tio.run/##JY7RCoQgEEXf@4p5VJtA6a1N/8XY2g1kzCGh/XpX62HgcrnMOcfv/EYaS3mvG2yC5NRBRsVWo9BokNDIDrbIEDChxwXVBTsB1x3sG3hrdYs1i@Cy03I2U7bhFe31LPJsIos8BKkWZ71KTk/cWxF6g6lebYYFk2qfMUkU4alvVGXzemYmiKVJ0M329FmFQRibLRy80ykIb31Z/g "Python 3 – Try It Online") This does a kind of breadth-first search over sets of fractions. When it finds a first valid representation, it uses the length of that as an upper bound. With the upper bound we can cut search branches when the target number can't be reached with the remaining number of fractions. This only uses integer arithmetic, given enough memory and time it should be able to calculate any value. Local results: ``` $ time python3 ef.py 1 [1] 2 [1, 2, 3, 6] 3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 230, 57960] python3 ef.py 15.89s user 2.03s system 98% cpu 18.148 total ``` --- At the cost of ~60 bytes we can use sharper bounds for cutting the search, skip fractions that would lead to higher sums, and traverse the search tree in a depth-first order. This allows us to get \$n=4\$ on TIO: ``` def f(n): u,*r=0,(0,1,n,1) while r: l,q,a,b,*x=r.pop() if a*q==b: if(l+1>u>0)<1:u=l+1;o=x+[q] elif u<1or(u+~l)*b>=a*q>0:A=a*q-b;B=q*b;D,M=divmod(B,A);r+=(l,q+1,a,b,*x),(l+1,max(q+1,D+(M>0)),A,B,*x,q) return o ``` [Try it online!](https://tio.run/##LY9NboQwDIX3cwovHeKpiKpuhgkSaLZzgqoLEKGDlEmCRVrY9OrUVF355z3r80vb8ojh9Zy2tO374EYYMajLCTIVbEvCkgwFMuoE34/JO2DRwNNMHfVUrJZfUkwoMkwjdMVsbX84ZEKvTZ3rUl3NJVsZqmhX/T5/iOy8uPPVRMasf7wq@trKcV1emqOe@6q1c9FXN7rbYfp6xgFbalTF2qLAtfnHKzoo9OxWPJY3jXcBKmqoFZVm@YvdkjlA3MfIEGAKwF34dGgI3o6gwGD/QkubeAoLBgLvArIiYLX/Ag "Python 3 (PyPy) – Try It Online") [Answer] # Python3, 386 bytes: ``` def f(n): A,I=[1],[] while sum(1/i for i in A)+1/(A[-1]+1)<=n:A.append(A[-1]+1) q = [(A[:],n,0)] while 1: c,d,k = q.pop(0) if(s:=sum(1/i for i in c))==n:return c F=1 if d: l= c[-1] while (s+1/(l:=l+1))>n or l in I: if l>10e7:I.append(A.pop());q=[(A[:],n,0)];F=0;break if F:q.append((c+[l],d-(k:=l>(c[-1]+1)),k)) if k and F: q.append((c[:-1]+[c[-1]+1],d,k)) ``` [Try it online!](https://tio.run/##ZZDNboMwEITvPMUevcJJcHNoZWokLkg8g8WB8qMgXGN@oqpPT9eQREi97Vrzzcza/S63wV4/3LSuddNCyyzKAFKeKy0KrosAfm6daWC@fzNx6aAdJuigs5BiKC4s1SdRhAI/lZXpuXSusfXrMYARFGjaZcEtj/DlJigDKl7zngTj2Q2ORSSHrmWzVP@yKkRFAVOz3CfaSJgpscmh9k5gFFQ@1M97Apt9PSOVoSKYWCAv473yDfCoSUTUvMv8VXvrgRiP6tg5zlQUf01N2Qc7l8nxibAq1Kbg9Yn1lJSw6nE58h73e6CH0tbEePjAaemV@gEU/isQVzd1dmEtI4fgOb8d5itp/gA) Local results (Macbook Pro): ``` 1 [1] 2 [1, 2, 3, 6] 3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 230, 57960] 4 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 45, 7397, 82673165] python3 egyptian_tests.py 29.14s user 0.15s system 99% cpu 29.480 total ``` ]
[Question] [ As many of you will know, almost every programming language has a standard casing system; unfortunately, we have not been able to agree on a singular system to use and now must frequently switch between camelCase, snake\_case, PascalCase and kebab-case. Now I know what you're thinking... wouldn't it be nice if we had a program that could convert from one casing to another? Well - soon we're going to have plenty!!! *(This is where you come in)* ## Challenge You're job is to write a program/function that will take an input string, and a casing system. It will then print/return the converted string. ### Inputs: You're program will receive two inputs, an alphabetic string that is to be converted and a string that **will always** be one of `kebab` `camel` `pascal` or `snake`. ### Outputs: You're program should output a string that conforms to the new casing. You can assume the input string is valid and will only conform to one of the casings (*i.e. it won't be* `mixed_Casing`). As most programming languages prefer lowercase variable names, you should convert all letters to lowercase unless it is needed to be upper case for the casing requirements. * Snake Case: All letters are lower case, with underscores separating words. * Kebab Case: All letters are lower case, with hyphens separating words. * Camel Case: The first letter of every word after the first is capitalized, with no spaces. * Pascal Case: The first letter of every word is capitalized, with no spaces. ## Test Cases: ``` "aJavaVariable", "snake" = "a_java_variable" "a_python_variable", "kebab" = "a-python-variable" "golf", "camel" = "golf" "camelToPascal", "pascal" = "CamelToPascal" "PascalToCamel", "camel" = "pascalToCamel" "", "snake" = "" "doHTMLRequest", "kebab" = "do-h-t-m-l-request" ``` ``` <!-- Run the snippet to see the leaderboard. Report any bugs to @ozewski on Github. --> <iframe src="https://ozewski.github.io/ppcg-leaderboard/?id=216396" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style> ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~127 126~~ 120 bytes Expects `(string)(type)`. ``` s=>t=>s.split(/_|-|(?=[A-Z])/).map((s,i)=>(k=parseInt(t,29)%5,(b=Buffer(s))[0]=b[0]&95|(k+!i>1)<<5,b)).join(['-_'[k-3]]) ``` [Try it online!](https://tio.run/##jdBBa4MwFMDxu5@iE7a@R43dWjwUGse209ilsJ7mRKKLw2oTMdlOfndXJV6kkl3CI/wf@ZET@2Uqa4paEyG/eJfTTtFQ01D5qq4KDeukJS080uiJfMS4Rv/MagDlFUhDKGnNGsVfhQbtbXZ4G3iQ0uefPOcNKMToPqbp5bjbBS2Uq5sifMD9PvBSRP8kCwHRkiTLqCTbOMYuk0LJivuV/IYcXCVYyRMtk2Fw0dy4iM6kLHnKUqIlsZYZO/PqKN9t3eHyKexKuFgt3E/houPMYQdLv2GGeay1NNg3Wzdip6EdO7zQb5hhHmstDfbF1o3YaWjH1sNmvzJO89x/tAZ8sJcj@Ura/QE "JavaScript (Node.js) – Try It Online") ### How? The type string \$t\$ is converted to an ID \$k \in [0..4]\$ by parsing it as a base-29 value and applying a modulo \$5\$: ``` type | base 29 -> dec. | mod 5 ----------+-----------------+------- "pascal" | 520544830 | 0 "camel" | 8750191 | 1 "kebab" | 14496618 | 3 "snake" | 20373819 | 4 ``` This formula was chosen because it puts *pascal* next to *camel* and *kebab* next to *snake*, allowing the following expressions: * Put the leading character in uppercase if 1) the type is *pascal* (\$k=0\$), or 2) the type is *camel* (\$k=1\$) and this is not the first word (\$i\neq 0\$): ``` (b = Buffer(s))[0] = b[0] & 95 | (k + !i > 1) << 5 ``` * Join with `"-"` for *kebab* (\$k=3\$), `"_"` for *snake* (\$k=4\$) or an empty string otherwise: ``` .join(['-_'[k - 3]]) ``` [Answer] # [Perl 5](https://www.perl.org/) `-lF'_|-|(?=[A-Z])'`, 69 bytes ``` $,=('_','-')[$c=3-ord(<>)%14%7];say map$c>1&&$i++||$c>2?ucfirst:lc,@F ``` [Try it online!](https://tio.run/##NYtdC4IwGEbv9yu6MKfkIvsgqLS6iYiCiOiiCHmdq8Tl1mZBsN/eCqSb5xwOPJIpPrDWCSIPJzjABPsnh0Y9IlTmTWK/Gfabw/NYw7txB@nQOHRdJ2@1jPl5d/qkl1zpasRpMFtYCyt4wQFUDilnSJdQMASJfFc3USavfy9YCim6Cn5BFO6M17sXW9AUOJI1MrHcb9Y79ngyXdWfj5BVLkptyWbQ7oQdS/gCJ4YYbxqd5uR49vEX "Perl 5 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 81 bytes ``` T`l\_-`L_`^.|_.|-. \B(?=[A-Z].*¶s) _ \B(?=[A-Z].*¶k) - T`L`l`^.(?!.*¶p)|_.|-. 1G` ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg8z8kIScmXjfBJz4hTq8mXq9GV48rxknD3jbaUTcqVk/r0LZiTa54NKFsTS5drpAEn4QcoCYNe0WQWIEmVLehe8L//4leiWWJYYlFmYlJOak6xXmJ2alcifEFlSUZ@XnxZTDx7NSkxCSu9PycNJ3kxNzUHC4wGZIfkFicnJijUwCmuKDaU/I9Qnx9glILS1OLSyBaAQ "Retina 0.8.2 – Try It Online") Takes input on separate lines but link includes test suite that splits the input on commas. Explanation: ``` T`l\_-`L_`^.|_.|-. ``` Uppercase the first letter and any letters after `_` or `-`, which get deleted. This gives you Pascal case. ``` \B(?=[A-Z].*¶s) _ \B(?=[A-Z].*¶k) - ``` Prefix interior capital letters with `_` (for snake case) or `-` (for kebab case). ``` T`L`l`^.(?!.*¶p)|_.|-. ``` Except for Pascal case, lowercase the first letter, plus (since we just marked them) all the letters for snake or kebab case. ``` 1G` ``` Delete the second input (the case) leaving the result. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~50~~ ~~48~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .ªÐáмÙ¡¸˜Dgi`.œ.ΔD™Q]l²ÇO5%©2‹i„_-®èýë™J®4Qićlì ``` [Try it online](https://tio.run/##AWgAl/9vc2FiaWX//y7CqsOQw6HQvMOZwqHCuMucRGdpYC7Fky7OlETihKJRXWzCssOHTzUlwqky4oC5aeKAnl8twq7DqMO9w6vihKJKwq40UWnEh2zDrP//ZG9IVE1MUmVxdWVzdAprZWJhYg) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCqNJ/vUOrDk84vPDCnsMzDy08tOP0HJf0zAS9o5P1zk1xedSyKDA2J@Jwu7@p6qGVRo8admY@apgXr3to3eEVh/ceXg2U9zq0ziQw80h7zuE1/5X0wnT@R0crJXolliWGJRZlJiblpCrpKBXnJWanKsXqAGXiCypLMvLz4ssQstmpSYlJYNn0/Jw0oEByYm5qDlgAzArJD0gsTk7MAcoUQBggKRRjU/I9Qnx9glILS1OLS1CMxGYhwnyIwSH5zmARuEwsAA). **Explanation:** ``` .ª # Sentence capitalize the first (implicit) input-string, which titlecases # without removing existing capital letters Ð # Triplicate that string á # Only leave its letters м # Remove all those letters (so only "-"/"_" are left, if any) Ù # Uniquify the potential multiple "-"/"_" to a single character ¡ # Split the string on this character ¸˜ # Wrap it into a list, and flatten Dg # Get the length of a copy of this list i # If this length is 1 (thus no "-"/"_" were present): ` # Push the string to the stack to remove the wrapped list .œ # Get all partitions of this string .Δ # Find the first partition which is truthy for: D # Duplicate the list of substrings ™ # Titlecase each string Q # Check that the two lists are equal ] # Close both the find_first and if-statement l # Lowercase each string in the list ² # Push the second input-string Ç # Convert it to a list of codepoint integers O # Sum those 5% # And take modulo-5 on it (snake=0; kebab=1; camel=4; pascal=3) © # Store this in variable `®` (without popping) 2‹i # If it's smaller than 2 (thus snake or kebab): „_- # Push string "_-" ®è # (0-based) index `®` into this string ý # Join the list by this character as delimiter ë # Else (thus camel or pascal): ™ # Titlecase each string in the list J # Join them together ®4Qi # If `®` equals 4 (thus camel): ć # Extract head; pop and push remainder-string and first character # separated to the stack l # Lowercase this first character ì # And then prepend it back in front of the remainder-string # (after which the result is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~112~~ 103 bytes ``` ->s,c{x=s.split(/(?=[A-Z])|-|_/).map{x=c[5]||x&&c<?d?_1.capitalize: _1.downcase}*(c>?s??_:c[?k]??-:'')} ``` [Try it online!](https://tio.run/##XZBPT4NAEMXv/RQbmrRgWHowXhrpxvRijCbGNB4khAzL1q5sWWShtrJ8dsqfUIunnXm/92YmmxXhqd66NV4pm5ZHVzkqFTw3FyZxvQf84Vsa62BhOXtIS8310aXena/1cTaj9yQi3KGQ8hwE/2VLxJ1I/iQUFKtuTLoiipBgST0S@4Tg5XxuVbU3QciAJzjAO2QcQsEMGxkqgbgrIPhqUHC4sM4epKd8J5MrGRkxCyHsIrineBz6lGLbYgp7JtqiF1rUSRv5CopCh9JLtR6j1j26r5d6vJHrYfZlSTomrTmSj5uX5zf2XTCVjy6PJN7hHO@xwNmAJ77DgO4CJThl5q2FIok0T9Iit1HcfKyNZJE3nW5GN49CxrTscGWjadk6KmNAW@8q6A9qn2@6DLhiqEgEU/@9yHX/fG1qwpKoPgM "Ruby – Try It Online") (+1 byte because TIO doesn't support ruby 2.7's `_1`) Multiple bytes saved thanks to @Dingus * `x` tracks whether it's not the first iteration * `c[5]` asks whether it's `"pascal"` (the only one with 6 letters) * `c>?s` asks if `c` is greater than `'s'`, this is only true for `"snake"`, etc. * the multiplication at the end is equivalent to `join` [Answer] # [Laravel](https://laravel.com/)/PHP, 264 bytes It accepts a GET request to `/{string}/{kebab|camel|pascal|snake}` as input, and output is done via dumping. Bytes are counted for the one file that I wrote. web.php: ``` <? use Illuminate\Support\Str;Illuminate\Support\Facades\Route::get('/{a}/{b}',function(){$a=str_replace("_","-",request()->a);switch(request()->b[0]){case'p':dd(Str::studly($a));case'c':dd(Str::camel($a));case'k':dd(Str::kebab($a));default:dd(Str::snake($a));}}); ``` I wrote/ran this on [PHP Sandbox](https://phpsandbox.io/) and verified it with PHPUnit tests like so (must be run one at a time!): ``` $this->get('/aJavaVariable/snake'); $this->get('/a_python_variable/kebab'); $this->get('/golf/camel'); $this->get('/camelToPascal/pascal'); $this->get('/PascalToCamel/camel'); $this->get('//snake'); // 404 (no output) $this->get('/doHTMLRequest/kebab'); ``` Could probably save bytes by using Laravel < 6 and the helpers str\_\*, but didn't feel like verifying it would run. Does anyone see any other shortcuts? ]
[Question] [ Let me explain one by one the above terms... We will call \$\text{Z-Factorial}(n)\$ of a positive integer \$n\$, \$n!\$ (i.e. \$n\$ factorial) without any trailing zeros. So, \$\text{Z-Factorial}(30)\$ is \$26525285981219105863630848\$ because \$30!=265252859812191058636308480000000\$ We will call `Modified Z-Factorial` of \$n\$, the \$\text{Z-Factorial}(n) \mod n\$. So, `Modified Z-Factorial` of \$30\$, is \$\text{Z-Factorial}(30) \mod 30\$ which is \$26525285981219105863630848 \mod 30 = 18\$ We are interested in those \$n\$'s for which the `Modified Z-Factorial of n` is a Prime Number ***Example*** The number \$545\$ is **PMZ** because \$\text{Z-Factorial}(545) \mod 545 = 109\$ which is prime Here is a list of the first values of \$n\$ that produce `Prime Modified Z-Factorial (PMZ)` ``` 5,15,35,85,545,755,815,1135,1165,1355,1535,1585,1745,1895,1985,2005,2195,2495,2525,2545,2615,2705,2825,2855,3035,3085,3155,3205,3265,3545,3595,3695,3985,4135,4315,4385,4415,4685,4705,4985,5105,5465,5965,6085,6155,6185,6385,6415,6595... ``` **Task** The above list goes on and your task is to find the \$k\$th ***PMZ*** **Input** A positive integer \$k\$ **Output** The \$kth\$ ***PMZ*** **Test Cases** here are some **1-indexed** test cases. Please state which indexing system you use in your answer to avoid confusion. Your solutions need only work within the bounds of your language's native integer size. ``` input -> output 1 5 10 1355 21 2615 42 5465 55 7265 100 15935 500 84815 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` [N!0ÜN%pi®>©¹Q#N ``` **Input** is **1-based** k. **Outputs** the k-th PMZ. Explanation: ``` [N!0ÜN%pi®>©¹Q#N [ Start infinite loop N! Factorial of the index 0Ü Remove trailing zeros N% Mod index p Is prime? i If it is: ®>© Increment the value stored in register c (initially -1) ¹Q Is the value equals the input? #N If it does, push the index (which is the PMZ) and break ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2k/R4PAcP9WCzEPr7A6tPLQzUNnv/38TAA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` !Dt0Ḍ%⁸Ẓµ#Ṫ ``` A full program reading from STDIN which prints the result to STDOUT. **[Try it online!](https://tio.run/##AR4A4f9qZWxsef//IUR0MOG4jCXigbjhupLCtSPhuar//zY "Jelly – Try It Online")** ### How? ``` !Dt0Ḍ%⁸Ẓµ#Ṫ - Main Link: no arguments # - set n=0 (implicit left arg) and increment getting the first (implicit input) values of n which are truthy under: µ - the monadic chain (f(n)): ! - factorial -> n! D - convert from integer to decimal digits t0 - trim zeros Ḍ - convert from decimal digits to integer ⁸ - chain's left argument, n % - modulo Ẓ - is prime? Ṫ - tail - implicit print ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 58 bytes ``` D,f,@,Rb*BDBGbUdb*!!*BFJiA%P x:? Wx,`y,+1,`z,$f>y,`x,-z Oy ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQScoScvJxck9KTQlSUtRUcvJzSvTUTWAq8LKniu8QiehUkfbUCehSkclza5SJ6FCR7eKy7/y////RpYA "Add++ – Try It Online") Times outs for \$k \ge 30\$ on TIO ## How it works ``` D,f,@, ; Define a function, f, taking 1 argument, n ; Example: STACK = [30] Rb* ; Factorial STACK = [265252859812191058636308480000000] BD ; Convert to digits STACK = [2 6 5 ... 0 0 0] BGbU ; Group adjacents STACK = [[2] [6] [5] ... [8] [4] [8] [0 0 0 0 0 0 0]] db*!! ; If last is all 0s *BF ; remove it STACK = [[2] [6] [5] ... [8] [4] [8]] Ji ; Join to make integer STACK = [26525285981219105863630848] A% ; Mod n STACK = [18] P ; Is prime? STACK = [0] ; Return top value 0 x:? ; Set x to the input Wx, ; While x > 0 `y,+1, ; y = y + 1 `z,$f>y, ; z = f(y) `x,-z ; x = x - z ; We count up with y ; If y is PMZ, set z to 1 else 0 ; Subtract z from x, to get x PMZs Oy ; Output y ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 0-indexed. Only works, in practice, for `0` & `1` as once we go over `21!` we exceed JavaScript's `MAX_SAFE_INTEGER`. ``` ÈÊsÔsÔuX j}iU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yMpz1HPUdVggan1pVQ&input=MQ) ``` ÈÊsÔsÔuX j}iU :Implicit input of integer U È :Function taking an integer X as argument Ê : Factorial s : String representation Ô : Reverse sÔ : Repeat (There has to be a shorter way to remove the trailing 0s!) uX : Modulo X j : Is prime? } :End function iU :Pass all integers through that function, returning the Uth one that returns true ``` [Answer] # [R](https://www.r-project.org/), ~~99~~ 93 bytes *Edit: -6 bytes (and -4 bytes from arbitrary-precision version) thanks to Giuseppe* ``` k=scan();while(k){F=F+1;z=gamma(F+1);while(!z%%5)z=z/10;x=z%%F;k=k-(x==2|all(x%%(2:x^.5)))};F ``` [Try it online!](https://tio.run/##NYpLDsIgFAD3nuI1hggxfkrSTQkuOYAHMHlBrARKDaURUc9eu3E3k5k4z06OGgNl4nm33lDH3kqqbS2K7LDvkS78b1UhpGFFlkN9FFkupoSTbkezlPyD3tNMCOVtvuwbxthXqJmvVmsIQzItaPR68pjsEEYwWRtzhfNmBNR6ipgMhKk30S4bRAydgdsQAcMLbHhMCU68Aph/ "R – Try It Online") Uses the straightforward approach, following the steps of the explanation. Unfortunately goes out of limits of [R](https://www.r-project.org/)'s numerical accuracy at factorial(21), so fails for any k>2. An arbitrary-precision version (which is not limited to small k, but is less golf-competitive) is: **[R](https://www.r-project.org/) + gmp, [115 bytes](https://tio.run/##JYtBCsIwEABfs7CLWJtCL8a95hnCVkIMSYqkgjGtb4@UHoeZyS36KUv@oksvaoGXh8xI@vP00WKg1bAs3eRdRXNSpCs7SUkOOKIKMN4UVa5wAdXrsh9@fltn8y4N6cDhjIV52CRGLADDtdy7keinTVN9@wM)** [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` !foṗS%ȯ↔↔ΠN ``` [Try it online!](https://tio.run/##yygtzv7/XzEt/@HO6cGqJ9Y/apsCROcW@P3//98IAA "Husk – Try It Online") ## Explanation ``` !foṗS%ȯ↔↔ΠN f N filter list of natural numbers by: Π take factorial ↔↔ reverse twice, remove trailing zeros S% mod itself ṗ is prime? ! get element at index n ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~89 ... 79~~ 77 bytes ``` n=>(g=y=>y%10n?(p=k=>y%--k?p(k):~-k||--n?g(x*=++i):i)(y%=i):g(y/10n))(x=i=2n) ``` [Try it online!](https://tio.run/##FYtBDoIwEADvvKIXkq24Cl404MJbCBZSS9qGNoYq@nRrPc0kk7n3j94Ni7QetbmJOFLU1MJEgdqQV6XuwJL6O6LqLChef1BtG6LuJlh3VBSS15JDyCnJBOGYJs5hJUknzeNoFpiFZ5oRq5qEK7FzYlFw9soYG4x2ZhaH2Uyg92yENDfZO36N9TK1iOh8Pyh08inoUpblDw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~145~~ ~~140~~ ~~138~~ 129 bytes ``` def f(n,r=0): c=d=2 while r<n: c+=1;d*=c while 1>d%10:d//=10 i=d%c;r+=i==2or i and min(i%j for j in range(2,i)) return c ``` [Try it online!](https://tio.run/##JY/BCgIxDETv/YpBWNhqxbbqRY0/Ih6WtutGNEpdEb9@bfGUmZdkSJ7fcXjIeppi6tG3YjJZvVMIFMkrfAa@JeSDFISwILePcwpF/xvuGBtnd3G1ImcLZYpN2OcFMZF/ZDA6ibiztNxc0RdyBQtyJ5fUesNaK@Q0vrMgTPK@v0A4OQNnDXypG2@w3VZvz0rV/dSFoUbU4XoT8MwsY1u5wWx5nJnyRnVaTz8 "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~126~~ 125 bytes ``` def f(n,r=0): c=d=2 while r<n: c+=1;d*=c while d%10<1:d/=10 i=d%c r+=i==2or i and min(i%j for j in range(2,i)) print c ``` [Try it online!](https://tio.run/##JY5NCsIwEIXXnVM8hEKrEZOgm@p4EXFRktZO0VGiIp6@Nrga3vd@mMf3NdzVT1PsevSVmsS2bgiBI3vCZ5Brh3TQhoqwYrePSw5U/HEsnT24Jm7YWSqEYzlbacXC7O8JglYjbqKVlCP6mYwQRWr10lXeSF0THkn0hTDp@/YE4@QMnDXw8916g90ua3smyvWuDUNeyOH5n383Q4PF@rgwVPRVlvX0Aw "Python 2 – Try It Online") --- Explanation: Keep dividing by 10 as long as the current factorial is divisible by 10, and then check the factorial modulo current number for primality. Thanks to *caird coinheringaahing* for -20 bytes and *Dominic van Essen* for -9 bytes! [Answer] # [Haskell](https://www.haskell.org/), ~~129~~ 111 bytes ``` g n |n`mod`10>0=n |0<1=g$div n 10 f=(!!)[n|n<-[1..],let p=mod(g$product[1..n])n,[x|x<-[2..p],mod p x<1]==[p]] ``` [Try it online!](https://tio.run/##TY5NboMwEIX3nGKCWNjKlNoEp6mEc4J21aVlNSgQiALGSpzWSNydmlaVsns/32heW94uddfNcwMmgskc@qE6cLZncrGs4LJJqvMXGOAsOkmyWlFlJlM8KZ6mGrvagZXhhjSJvQ7V/eiWwmhqUPnJBy5LU6sxIGDBF1xLqazWcwseRgkxiWG9BnJrh2/wdNExBbmHhziB038Fz4/F@BeS2tv66OqKxlHUl2cDEvrSvn@CvbsPd30zoH7fTcTjSMMmwlFQJJwh34hFZRyzLRc0DCOCMdzlu@ACEAjxugkyz1Dk24UVAl@yoH4A "Haskell – Try It Online") `g` removes `0`s from number. `f` takes `k`th element from an infinite list comprehension where: `[x|x<-[2..p],mod p x==0]==[p]` is `prime` condition( compares list of divisors of `p` and a list of just p). And `p` is `mod(g$foldr(*)1[1..n])n` the modulo of factorial passed through `g`. Saved 18 thanks to [user](https://codegolf.stackexchange.com/users/95792/user) ]
[Question] [ Write a function that takes a string of letters and spaces (no need to handle non-letters) and performs the ANNOUNCER VOICE translation algorithm as follows: * First, uppercase everything. * For each word, + *Elongate* each consonant cluster by tripling each letter; except, if the word *begins* with a consonant cluster, do not elongate that cluster. For example, `other` should become `OTTTHHHEEERRR` but `mother` should become `MOTTTHHHEEERRR`. + *Elongate* the final vowel by tripling it. * In both cases of *elongation*, if you're tripling a letter, first coalesce it with duplicate letters on either side. For example, `hill` should become `HIIILLL` and `bookkeeper` should become `BOOKKKEEPPPEEERRR`. * For the purposes of this challenge, `y` counts as a consonant. * Clarification/simplification: You may assume that each pair of words is separated by a single space, and that the input contains no consecutive spaces, and that the input will not be the empty string. * Shortest code wins! Test vectors: ``` > sunday sunday SUNNNDDDAAAYYY SUNNNDDDAAAYYY > mia hamm MIAAA HAAAMMM > chester alan arthur CHESSSTTTEEERRR ALLLAAANNN ARRRTTTHHHUUURRR > attention please ATTTENNNTTTIOOONNN PLEASSSEEE > supercalifragilisticexpialidocious SUPPPERRRCCCALLLIFFFRRRAGGGILLLISSSTTTICCCEXXXPPPIALLLIDDDOCCCIOUUUSSS > moo MOOO > Aachen AACCCHHHEEENNN > Oooh OOOHHH > grifffest GRIFFFEEESSSTTT > k K > aaaabbbbc AAAABBBBCCC ``` --- Here's a reference implementation which I would move to an answer except that as of this morning the question's been closed. :P ``` import itertools,re def j(s):return re.match('^[AEIOU]+$',s) def c(s):return ''.join(sum(([h,h,h]for h in[k for k,g in itertools.groupby(s)]),[])) def v(s): while len(s)>=2 and s[-2]==s[-1]:s=s[:-1] return s+s[-1]+s[-1] def a(n): r='' for w in n.split(): if r:r+=' ' ss=re.split('([AEIOU]+)', w.upper()) for i,s in enumerate(ss): r += [v(s),s][any(j(t) for t in ss[i+1:])]if j(s)else[s,c(s)][i>0] return r while 1:print a(raw_input('> ')) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 175 bytes ``` 1↓' +'⎕R' '⊢'[AEIOU][^AEIOU]+ '⎕R{m/⍨1,3×2≠/m←⍵.Match}'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1'⊢'$| |^'⎕R' '⊢1(819⌶)⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9OCO/tOS/4aO2yeoK2uqP@qYGqSuoP@papB4d5@jq6R8aq60AFq021n/UsepR71Y938SS5IxadY1oiLxmjKGWBkyxlr2CJlC/AlQOzIxTgBoE5MEUKoC1QayLMQRDI6C0GhRDhMDOUKlRqImDugvsMEMNC0PLRz3bNB/1zgN54L8CGID9wVVcmpeSWKkAobiQZXIzExUyEnNzUQSTM1KLS1KLFBJzEvMUEotKMkqLUOQTS0pS80oy8/MUCnJSE4tTuVDtKkgtSk7MyUwrSkzPzMksLslMTq0oyASKpOQnZ@aXFqM6ID8fAA "APL (Dyalog Unicode) – Try It Online") `⍞` prompt for character input `1(819⌶)` convert to uppercase (819 ≈ Big) `⊢` pass the result further (serves to separate the strings and the 1) `'$| |^'⎕R' '` **R**eplace:  the end, any space, and the beginning  → two spaces `⊢` pass the result further (serves to separate two groups of strings) `'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1'` **R**eplace:  any number of identical vowels and any number of non-vowels and a space  → the vowel thrice and the unmodified consonants  a space and a vowel  → themselves  a space and a consonant cluster  → themselves  a run of identical consonants  → three of those vowels `'[AEIOU][^AEIOU]+ '⎕R{`…`}` **R**eplace:  a run of non-vowels and a space  → the result of the following anonymous function with the namespace `⍵` as argument:   `⍵.Match` the text that was found   `m←` assign that to `m`   `2≠/` pair-wise different-from   `3×` multiply by three   `1,` prepend one   `m/⍨` use that to replicate `m` `⊢` pass the result further (serves to separate two strings) `' +'⎕R' '` **R**eplace:  one or more spaces  → with a single space `1↓` drop the initial letter (a space) [Answer] # APL, 90 bytes ``` {1↓∊{s←{⍵⊂⍨1,2≠/⍵}⋄x↑⍨¨(3⌈≢¨s⍵)⌊≢¨x←s⍵/⍨(1+2×{⌽<\⌽⍵}∨~∧∨\)⍵∊'AEIOU'}¨w⊂⍨w=⊃w←' ',1(819⌶)⍵} ``` Explanation: * `1(819⌶)⍵`: convert to uppercase * `w⊂⍨w=⊃w←' ',`: split on spaces * `{`...`}¨`: for each word... + `s←{⍵⊂⍨1,2≠/⍵}`: `s` is a function that splits a string into groups of contiguous matching characters + `⍵∊'AEIOU'`: mark the vowels + `(`...`)`: see which characters to triplicate - `~∧∨\`: all consonants past the first vowel, - `{⌽<\⌽⍵}`: the last vowel. - `2×`: multiply the bit vector by two, - `1+`: and add one. Now all selected characters have `3` and the rest have `1`. + `⍵/⍨`: replicate each character in `⍵` by the given amount + `x←s`: split it up into strings of matching characters, and store this in `x`. + `(3⌈≢¨s⍵)`: the length of each group of matching characters in the input word, with a maximum of 3. + `⌊≢¨`: the minimum of that and the lengths of the groups in `x`. + `x↑⍨¨`: make each group be that length * `1↓∊`: flatten the result and drop the first character (the space that was added at the beginning to help with splitting) [Answer] # JS (ES6), ~~138~~ ~~134~~ 129 bytes ``` s=>s.toUpperCase()[r="replace"](/(\w)\1/g,"$1")[r](/[AEIOU](?=[^AEIOU]*( |$))/g,s=>s+s+s)[r](/\B./g,s=>/[AEIOU]/.test(s)?s:s+s+s) ``` WAAAYYY TOOO MAAANNNYYY BYYYTTTEEESSS. Contains `AEIOU` 3 times, but I can't golf those into one. [-4 bytes thanks to HyperNeutrino](https://codegolf.stackexchange.com/q/133642/72412) ### Ungolfed ``` function v(str){ return str.toUpperCase().replace(/(\w)\1/g,"$1").replace(/[AEIOU](?=[^AEIOU]*( |$))/g,s=>s+s+s).replace(/\B./g,s=>[..."AEIOU"].includes(s)?s:s+s+s); } ``` *I like to write, not read code.* [Answer] ## Python, 417 bytes Here's a reference implementation in Python. Not terribly golfed. ``` import itertools,re def j(s):return re.match('^[AEIOU]+$',s) def c(s):return ''.join(sum(([h,h,h]for h in[k for k,g in itertools.groupby(s)]),[])) def v(s): while len(s)>=2 and s[-2]==s[-1]:s=s[:-1] return s+s[-1]+s[-1] def a(n): r='' for w in n.split(): if r:r+=' ' ss=re.split('([AEIOU]+)',w.upper()) for i,s in enumerate(ss): r+=[v(s),s][any(j(t) for t in ss[i+1:])]if j(s)else[s,c(s)][i>0] return r ``` Test with: ``` while True: print a(raw_input('> ')) ``` [Answer] # [Python 3](https://docs.python.org/3/), 238 bytes ``` def f(s): s=s.upper();k=[s[0]];s=''.join(k+[s[i]for i in range(1,len(s))if s[i]!=s[i-1]]) for i in range(1,len(s)):k+=[s[i]]*(3-2*(s[i]in'AEIOU'and i!=max(map(s.rfind,'AEIOU')))) return''.join(k) print(' '.join(map(f,input().split()))) ``` [Try it online!](https://tio.run/##dU67DsIwDNz7FWaKA6XisRVlYGBgYmJCGSI1AdPiRkkqwdeXFCE2bjhbd76T/Svdet6OY2MdOIyyLiCqWA3e24By16pLvKy03kUlRHXvibFdZIm06wMQEEMwfLW4LjvLOS/JwWTPVOblWmtZwL/Tul2oT5ee43a5meO0E4v94Xg6C8MN0Ew9zBMfxmOsgiNuyq8rMwoINg2Bf5/JwgfihAK@yhR0JbEfEsoq@o7yzBhHk5LlRD2D76yJ9g0 "Python 3 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 139 + 1 (-p) = 140 bytes ``` $_=uc,s/^([^AEIOU]*)//,$s=$1,s/([^AEIOU])\1*/$1x(($q=length$&)>3?$q:3)/ge,s/.*?\K([AEIOU])\1*/$1x(($q=length$&)>3?$q:3)/e,print"$s$_ "for@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rY0WadYP04jOs7R1dM/NFZLU19fR6XYVsUQKAwX1Ywx1NJXMazQ0FAptM1JzUsvyVBR07QztlcptDLW1E9PBSrW07KP8daIJkpDqk5BUWZeiZJKsUq8glJafpGD2///iUCQBATJ//ILSjLz84r/6/qa6hkYGvzXTQQA "Perl 5 – Try It Online") Even handles the "aaaabbbbc" test case in accordance with the example. ]
[Question] [ **Challenge:** You are given a base 10 number. For each base from 10 counting down to base 2: 1. Take the original input number as a base 10 string, and remove any digits of the number which are invalid for the base. 2. Interpret the resulting number string in the that base. If this gives 1 or 0, terminate the whole process. 3. Output or print its largest prime factor, as decimal number. The output can be an array of the largest prime factors. **Sample cases:** Input: ``` 987654321 ``` Output: ``` 379721 10593529 1091 179 1493 293 19 7 ``` Alternately: ``` [379721,10593529,1091,179,1493,293,19,7] ``` This prints the largest prime factors of \$987654321\$, \$87654321\_9 = 42374116\_{10}\$, \$7654321\_{8} = 2054353\_{10}\$, and so on until it reaches \$1\_2\$, where it stops. [Answer] ## Pyth, 25 bytes ``` sfTm>1PiFdC,.u-N`tYKrT1zK ``` ``` z get input as a string .u rT1 cumulative reduce over [10,9,...,2] -N`tY remove one minus the number (10,9,...) from the input C, K K pair each step along the chain with corresponding base m map over [["987654321", 10],...]: iFd apply the base-conversion (splat over i) P prime factorization, smallest to largest >1 take [the last element], or [] if empty (1 or 0) fT remove the []s from 0s or 1s s join the one-element arrays together ``` [Try it here.](https://pyth.herokuapp.com/?code=sfTm%3E1PiFdC%2C.u-N%60tYKrT1zK&input=987654321&debug=0) [Answer] # Pyth - 16 bytes ``` V_S9#ePi~-z`NhNB ``` [Try it online here](http://pyth.herokuapp.com/?code=V_S9%23ePi%7E-z%60NhNB&input=987654321&debug=0). ~~There are sometimes a few blank lines on inputs without all the digits, lemme know if that's a problem.~~ [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~17~~ 15 bytes ``` 9:PQ"G@ZAYfXzX> ``` This takes the number as a string with quotes, which is allowed by default. [**Try it online!**](http://matl.tryitonline.net/#code=OTpQUSJHQFpBWWZYelg-&input=Jzk4NzY1NDMyJw) ### Explanation ``` 9:PQ % Push array [10, 9, ..., 2] " % For each number in that array. These are the bases to be considered G % Push input. Forces for input to be taken implicitly first time @ % Push current base ZA % Convert from that base to base 10, discarding non-valid digits Yf % Prime factors. Gives empty for input 1, and 0 for input 0 Xz % Non-zero values. Gives empty if previous result was 0, or else % leaves it as it was X> % Maximum of array. For empty input gives empty % Implicitly end for each % Implicitly display. Empty arrays are not displayed ``` [Answer] # Julia, 101 bytes ``` f(s,x=[],b=10)=(t=filter(c->c<=47+b,s))>"1"&&b>1?f(s,[x;maximum(keys(factor(parse(Int,t,b))))],b-1):x ``` This is a recursive function that accepts the input as a string and returns an array. Ungolfed: ``` function f(s, x=[], b=10) # Filter the string down to only the digits valid for base b t = filter(c -> c <= 47 + b, s) # If the filtered string isn't "1" or "0" and b is a valid base if t > "1" && b > 1 # Call the function again, appending the maximum prime factor # of t in base b to the argument x and decrementing the base f(s, [x; maximum(keys(factor(parse(Int, t, b))))], b-1) else # Otherwise return the array x end end ``` [Answer] # Mathematica, 83 bytes ``` FactorInteger[Select[IntegerDigits@#,#<a&]~FromDigits~a][[-1,1]]~Table~{a,10,2,-1}& ``` Anonymous function, returns a list. Not that complicated, to be honest. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` D<ƇḅṛɗⱮ⁵ÆfṀ€t0 ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//RDzGh@G4heG5m8mX4rGu4oG1w4Zm4bmA4oKsdDD///85ODc2NTQzMjE "Jelly – Try It Online") ## How it works ``` D<ƇḅṛɗⱮ⁵ÆfṀ€t0 - Main link. Takes an integer n on the left D - Cast n to digits, D ɗ - Previous 3 links as a dyad f(D, k): <Ƈ - Keep elements of D less than k ṛ - Yield k ḅ - Convert to base k ⁵ - 10 Ɱ - Yield the range 1 ≤ k ≤ 10 and map f(D, k) over each Æf - Prime factors Ṁ€ - Maximum of each, or 0 if empty list t0 - Trim zeros ``` [Answer] # Ruby, 120 bytes Recursive function, takes the input as a string. ``` f=->n,b=2{require'prime';i=n.tr([*b.to_s..?9].join,"").to_i(b) b>10?[]:f[n,b+1]+[*i>1?Prime.prime_division(i).max[0]:p]} ``` [Answer] ## Pyke, 19 bytes, noncompeting (add splat\_node functon) ``` DTAbPe ;1TtD=T`"":r ``` [Try it here!](http://pyke.catbus.co.uk/?code=DTAbPe%0A%3B1TtD%3DT%60%22%22%3Ar&input=%22987654321%22) Takes input in quotes, exits with an error. Explanation (newline replaced with \n): ``` D - Duplicate the first item on the stack (And get it from input first time) TAb - Convert input to base (whatever's in T, 10 default) Pe - get the highest prime factor of the number \n;1 - print it out and get rid of it TtD=T - T -= 1 `"": - input = input.replace(str(t), "") r - GOTO start ``` ]
[Question] [ Suppose we use the following rules to pull a single string from another string, one containing only ASCII printable characters and called an `*`-string. If the string runs out before the process halts, that is an error, and the result of the process is undefined in that case: 1. Start with `d=1, s=""` 2. Whenever you encounter a `*`, multiply `d` by 2. Whenever you encounter another character, concatenate it to the end of `s` and subtract 1 from `d`. If now `d=0`, halt and return `s` **Defined Examples**: ``` d->d 769->7 abcd56->a *abcd56->ab **abcd56->abcd *7*690->769 ***abcdefghij->abcdefgh ``` **Undefined Examples**: (note that the empty string would be one of these as well) ``` *7 **769 *7* *a*b * ``` Your job is to take a string and return the shortest `*`-string that produces that string. **Program Examples**: ``` 7->7 a->a ab->*ab abcd->**abcd 769->*7*69 ``` Your program should handle any string containing at least one character and only non-`*` ASCII printable characters. You can never return strings for which the process is undefined, since by definition they cannot produce ANY strings. Standard loopholes and I/O rules apply. [Answer] # JavaScript (ES6), 61 bytes ``` f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s ``` Recursive function that does the following: * If `d` is less than or equal to remaining string length divided by 2: Append `*` to output and multiply `d` by 2 * Else: Shift the string and append to output, subtract 1 from `d`. See it in action: ``` f=(s,d=2)=>s?d>s.length?s[0]+f(s.slice(1),d-2):'*'+f(s,d*2):s input.oninput = e => output.innerHTML = f(input.value); ``` ``` <input id="input" type="text"/> <p id="output"></p> ``` [Answer] ## Pyth, ~~29~~ ~~27~~ (Noticed broken) ~~27~~ ~~26~~ 25 bytes ``` +*\*sKllzXJ-^2.EKlzz?J\*k ``` Explanation to come. [Test Suite](http://pyth.herokuapp.com/?code=%2B%2a%5C%2asKllzXJ-%5E2.EKlzz%3FJ%5C%2ak&input=a%0Aab%0Aabc%0Aabcd%0Aabcde%0Aabcdef%0Aabcdefg%0Aabcdefgh&test_suite=1&test_suite_input=a%0Aab%0Aabc%0Aabcd%0Aabcde%0Aabcdef%0Aabcdefg%0Aabcdefgh&debug=0) [Answer] # Pyth (36 27 bytes) Thanks to Jakube for a 9 byte improvement! Currently not as good as [muddyfish's answer](https://codegolf.stackexchange.com/a/75912/52152), but whatever ``` KlzJ1VzWgKyJp\*=yJ)pN=tK=tJ ``` [Test Suite](https://pyth.herokuapp.com/?code=KlzJ1VzWgKyJp%5C*%3DyJ%29pN%3DtK%3DtJ&input=goodbye&test_suite=1&test_suite_input=769%0AHello+World!%0Aabcd%0AThis+answer+is+pretty+good+now!%0AThank+you+Jakube!&debug=0) Translation to python: ``` | z=input() #occurs by default Klz | K=len(z) J1 | J=1 Vz | for N in z: WgKyJ | while K >= J*2: p\* | print("*", end="") =yJ | J=J*2 ) | #end inside while pN | print(N, end="") =tK | K=K-1 =tJ | J=J-1 ``` [Answer] ## C, 125 bytes ``` main(int q,char**v){++v;int i=1,n=strlen(*v);while(n>(i*=2))putchar(42);for(i-=n;**v;--i,++*v)!i&&putchar(42),putchar(**v);} ``` This takes advantage of the very regular pattern of star positions to output the correct encoding. Initially I tried a bruteforce recursive solution, but in retrospect it should have been obvious that there was a simpler mathematical solution. Essentially you will always have `2^floor(log_2(length))` stars at the start of your output, and a final star after `2^ceil(log_2(length)) - length` characters (if that works out to at least 1 character). The (slightly) ungolfed version is as follows ``` main(int q,char**v){ ++v; // refer to the first command line argument int i=1, n=strlen(*v); // set up iteration variables while(n > (i*=2)) // print the first floor(log2(n)) '*'s putchar(42); for(i-=n; **v; --i, ++*v) // print the string, and the final '*' !i&&putchar(42),putchar(**v); } ``` [Answer] ## JavaScript (ES6), ~~88~~ 77 bytes ``` f=(s,l=s.length,p=2)=>l<2?s:p<l?"*"+f(s,l,p*2):s.slice(0,p-=l)+"*"+s.slice(p) ``` At first I thought that `abcde` had to be `*a**bcde` but it turns out that `**abc*de` works just as well. This means that the output is readily constructed using floor(log₂(s.length)) leading stars, plus an additional star for strings whose length is not a power of two. Edit: Saved 8 bytes by calculating the number of leading stars recursively. Saved a further 3 bytes by special-casing strings of length 1, so that I can treat strings whose length is a power of 2 as having an extra leading star. [Answer] **Haskell, 68 bytes** ``` f d[]="" f d xs|length xs>=d*2='*':f(d*2)xs f d(x:xs)=x:f(d-1)xs ``` Same as the other answers, really. If EOF, output an empty string. If length remaining is more than twice `d`, output a star and double `d`. Otherwise, output the next character and subtract one from `d`. Ungolfed: ``` f d ( []) = "" f d ( xs) | length xs >= d*2 = '*' : f (d*2) xs f d (x:xs) = x : f (d-1) xs ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` F=->a,s="",d=1{x,*y=a d<1?s:x==?*?F[y,s,d*2]:F[y,s+x,d-1]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN63cbHXtEnWKbZWUdFJsDasrdLQqbRO5UmwM7YutKmxt7bXs3aIrdYp1UrSMYq3ATO0KnRRdw9haiAm3GP0KSkuKFdyiVcujU2JjFXACZQVdO4UULoRqcwUzBUtcOsCqzZFUJyokKSQrpCiYKphh6gGrTkRSraWARz1EdRKKcjwaoMqTU1A0mAO1AN2vYIDDNeZmlmgWIKxIVUhTSFfIUMhUyALphluQmpaeAQlWWAQBAA) ]
[Question] [ Write the shortest code that calculates all possible (legal) moves of current player from a given FEN string. [What is FEN string? (Wikipedia)](http://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) * Shortest code wins, language doesn't matter. * Output moves must obey [chess rules of movement](http://en.wikipedia.org/wiki/Rules_of_chess#Movement) **except *en passant*, castling, and pawn promotion.** * Ignore check, checkmate, and stalemate, king cannot be captured situations too. You can set outputs differently as you want (for example: `A2-A4`, `A2A4`, `a2a4`, `a2->a4`...) **Test cases:** ``` # INPUT 1: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 ``` ``` # OUTPUT 1 A2-A4, A2-A3, B2-B4, B2-B3, C2-C4, C2-C3, D2-D4, D2-D3, E2-E4, E2-E3, F2-F4, F2-F3, G2-G4, G2-G3, H2-H4, H2-H3, B1-A3, B1-C3, G1-F3, G1-H3 ``` ``` # INPUT 2 7k/8/8/8/8/8/PP6/Q1q4K w - - 0 1 ``` ``` # OUTPUT 2 A1-B1, A1-C1, A2-A3, A2-A4, B2-B3, B2-B4, H1-H2, H1-G1, H1-G2 ``` [Answer] # C - 391 bytes Takes input as command line arguments and prints to stdout with the squares labeled from 0 to 63. OK, I had a few minutes so I tried to delete all the bits relating to the detection of check. I think it is now not very efficient though... ``` O(x,y){return((x&7)-(y&7))/5;} B[64],*b=B,J=32,M,L,x,*X,N; main(int c,char**V){ for(;x=*V[1]++;c=J&2**V[2]) x>56?*b++=x:x>47?b+=x-48:0; for(;b-->B;) for(M=-1,N=*b%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*b|J);*b&&*b&J^c&&(M=M<0?*++*V%J:-M,**V<96);) for(x=b-B,L=N?9^*b&8:1+(x/8==1+c/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^c&&N|(!*X^M&1&&M<0^!c)?printf("%d-%d ",b-B,x),L*!*X:0) X=B+(x+=M);} ``` **478 byte check-detecting version** ``` O(x,y){return((x&7)-(y&7))/5;} B[64],*b=B,c,I,J=32; main(int C,char**V){ int*D,M,L,t,x,*X,N; for(;b-B<64;C=c=J&2**V[2]) (t=*V[1]++)>56?*b++=t:t>47?b+=t-48:0; for(D=b;D-->B;) for(M=-1,N=*D%J^16,*V=strchr("bGInFJOQrAHkAGHIqAGHIpGHIx",*D|J);*D&&*D&J^C&&(M=M<0?*++*V%J:-M,**V<96);) for(x=D-B,L=N?9^*D&8:1+(x/8==1+C/6);L--*!(O(x,x+M)|O(x>>3,x+M>>3));L=!*X|~*X&J^C&&N|(!*X^M&1&&M<0^!C)?c^C?I|=*X%J==11:(*X=*D,*D=I=0,main(C^J,V+1),*D=*X,I||printf("%d-%d ",D-B,x)),L*!(*X=t):0) X=B+(x+=M),t=*X;} ``` [Answer] ## Java 1455 ``` String q(String f){int[][]b=new int[8][8];int i=0,j=0,k,l,m,n,c;HashSet<String>h=new HashSet<String>();while((c=f.charAt(i))>32){if(c>48&c<57)j+=c-49;if(c==47)j--;if(c>56)b[j%8][j/8]=c;i++;j++;}boolean w=f.charAt(++i)>99;for(i=0;i<8;i++)for(j=0;j<8;j++)if((c=b[i][j])<91?w&c>0:!w){switch(c%32){case 14:for(k=0;k<8;k++){l=(k/4+1)*(k%2*2-1)+i;m=(2-k/4)*(k%4/2*2-1)+j;if(b(l,m)&&(w&b[l][m]%91<40|!w&b[l][m]<91))h.add(h(i,j,l,m));}break;case 11:for(k=0;k<8;k++){l=i+(k==4?1:k/3-1);m=j+(k==4?1:k%3-1);if(b(l,m)&&(w&b[l][m]%91<40|!w&b[l][m]<91))h.add(h(i,j,l,m));}break;case 17:for(k=0;k<8;k++){for(n=1;n<9;n++){l=i+n*(k==4?1:k/3-1);m=j+n*(k==4?1:k%3-1);if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;case 2:for(k=0;k<4;k++){for(n=1;n<9;n++){l=i+n*(k/2*2-1);m=j+n*(k%2*2-1);if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;case 18:for(k=0;k<4;k++){for(n=1;n<9;n++){l=i+n*(k/2*(k%2*2-1));m=j+n*((1-k/2)*(k%2*-2+1));if(b(l,m)){c=b[l][m];if(w&c%91<40|!w&c<91)h.add(h(i,j,l,m));if(c>0)break;}else break;}}break;default:m=w?-1:1;if(b[i][j+m]<1){h.add(h(i,j,i,j+m));if(b[i][j+2*m]<1&j==(w?6:1))h.add(h(i,j,i,j+2*m));}for(l=-1;i+l<8&i+l>=0&l<2;l+=2){c=b[i+l][j+m];if(c>0&(c<91?!w:w))h.add(h(i,j,i+l,j+m));}}}return h.toString();}boolean b(int l,int m){return m>=0&m<8&l>=0&l<8;}String h(int i,int j,int l,int m){return""+g(i)+(8-j)+g(l)+(8-m);}char g(int i){return(char)(i+65);} ``` [Answer] # Python 553 ~~649~~ ~~678~~ ``` b,Q=raw_input(),range;R=Q(8);D="w"in b for i in Q(9):b=b.replace(`i`,"_"*i) if D:b=b.swapcase() def X(h,v,c): h+=x;v+=y if c and h|v in R and"a">b[v*9+h]:print chr(65+x)+`8-y`+chr(65+h)+`8-v`;return"_"==b[v*9+h] for y in R: for x in R: z=y*9+x;p=b[z];N=p=="n";j=[p in"qrk"]*4+[p in"qbk"]*4 if"p"==p:j[D]=k=(1,-1)[D];X(1,k,b[z+10*k]<"_");X(-1,k,b[z+8*k]<"_") for i in Q(1,(2,(y==(1,6)[D])+2,8)["kp".find(p)]): for k in R:j[k]=X((0,0,-i,i,-i,i,-i,i)[k],(i,-i,0,0,-i,-i,i,i)[k],j[k]) for v,h in((2,1),(1,2)):X(v,h,N);X(-v,-h,N);X(-v,h,N);X(v,-h,N) ``` Two-space indent is tab char, which saves 5 bytes. It occurs to me that you can likely make it evaluate reasonable moves to a decent ply and keep it under 1024 bytes :) I started looking through other [chess](/questions/tagged/chess "show questions tagged 'chess'") questions, but there doesn't seem to be a codegolf chess engine question... [Answer] # Python 638 637 (482?) bytes ``` exec"""p=raw_input() for x in"12345678":p=p.replace(x,"~"*int(x)) b=map(ord,"#"*21+p[:71].replace("/","##")+"#"*21) d,e=-10,126 if not"w"in p:b,d=[x^32*(64<x<e)for x in b],10 B=[-9,9,-11,11] R=[-1,1,-d,d] Q=B+R c=Zx:chr(96+x%10)+chr(58-x/10) for x,p in enumerate(b): def O(y): if 111<b[y]:print c(x)+c(y) s=ZL:[O(x+X)for X in L];m=ZL,z=x:L&(O(z+L[0]),m(L,z+L[0])if e==b[z+L[0]]else m(L[1:])) if p==80:e==b[x+d]&(O(x+d)or e==b[x+d*2]&35==b[x-d*2]&O(x+d*2)),111<b[x+d-1]<e&O(x+d-1),111<b[x+d+1]<e&O(x+d+1) p==75&s(Q),p==78&s([-12,12,-8,8,-21,21,-19,19]),p==82&m(R),p==66&m(B),p==81&m(Q)""".replace("Z","lambda ").replace("&"," and ") ``` Note: after `def O(y):` there is a newline and a tab char before `if` Note: by using zlib module it's possible to get a valid Python source code of 482 bytes by simply compressing the real source: ``` #encoding=koi8-r import zlib exec zlib.decompress("x°MRKkЦ0>╞~┘Pы Eё╜Е4▌Ц█.9Br*1зБ┤B╠#°■╙=Лoъ╠M⌡│╬г0█\\pcл⌡╝x9╣ЧМф9^:Х╘e:·=м⌠Eй2oЭ╞нЫsQ9─ЩeсS{ЦAR ╕ПЭруюь4жрГыBшОhЖхпy`B▌╬ 58ёt:NхИHшк█╫ЁSK}VBmРПgOyР╢\n+'╬Z║╔▒╣иу√═╢╜-ы#G╙├з▓²Yк=╘л!dуkг≈┴?u$dOФ╘\n▐HфАюВ9]Шж╦╝╦9^┼▄пзИ√ Э│mi╜WeЧa3ъА╗╢бae┘.║WsьdЫ√Ы<ТВэГзьъ ЙПiB╤≥П-Ъ■⌡<╡▌Б┬1╚3╕лGjщЫЙ(з╧н,>$Eш⌠FыdmШ<x,Р╔Mc;≥м╒2DLc!`Л≥рvЕFCИЪtyв%Н║╞╤≤O╝|'═┤)B|н*┘T╛▐рKпK;╔Я╓АШ& бУ╗j└;│И╬Ж╝Щ\\4e]P&НРeZ╢5┼ДГt╚У") ``` [Answer] # JavaScript (E6) 481 ~~492 550~~ **Edit** Fixed a nasty bug in knight moving. A lot of work to keep the byte count the same. (Not counting leading spaces and newlines kept for readability) ``` B=f=> [for(c of(o=b='',f=f.split(w=' '))[0])b+=-c?w.repeat(c):c<'0'?z=10:c]+ [...b].map((c,p)=> (K=d=>(d=b[p+d])==w?0:d>'a'?m:d>'A'?-m:9)(0)-1||( t='pPkKnNrRQqBb'.search(c), O=d=>K(d)<1?o+=w+P(p)+P(p+d):0, S=(d,s=0)=>O(d*++s)&&!K(d*s)&&S(d,s), //o+='\n'+P(p)+' '+c, // Uncomment to display pieces list t<2?[for(i of[~(s=t<1?z:-z),1-s])~K(i)||O(i)]+!K(s)&&O(s)&&(p/z|0)==t*5+1&!K(s+=s)&&O(s) :t<6?[for(i of t<4?[1,9,z,11]:[12,8,21,19])O(i)+O(-i)] :[for(i of[t>7&&9,t>7&&11,t<z,t<z&&z])S(i)+S(-i)] ) ,m=f[1]<'w'?1:-1, //console.log(','+([...b]+',').replace(/1,0/g,'\n')), // Uncomment to display chessboard P=p=>'ABCDEFGH'[p%z]+(9+~p/z|0))&&o ``` **Less Golfed** ``` B=f=>( o=b='',[for(c of f)b+=-c?'.'.repeat(c):c], m=(w=b[72]=='w')?1:2,n=3-m, t=0, P=p=>'ABCDEFGH'[p%9]+(9+~p/9|0), b=b.slice(0,71), // console.log(b.replace(/\//g,'\n')), // Uncomment to display chessboard [...b].map((c,p)=>{ r=p/9|0 K=k=>(k=b[k])=='.'?0:k>'a'?m:k>'A'?n:9 J=d=>K(p+d)<2, O=d=>J(d)?o+=' '+P(p)+P(p+d):0, S=(s,d)=>O(d*++s)&&!K(p+d*s)?S(s,d):0; if(K(p)==2){ // o+='\n'+P(p)+ ' '+c; // Uncomment to display pieces list if (c=='P') { (f=!K(p-9))&&O(-9), f&r==6&&!K(p-18)&&O(-18), [for(i of[10,8])K(p-i)==1&&O(-i)] } else if (c=='p') { (f=!K(p+9))&&O(+9), f&r==1&&!K(p+18)&&O(+18), [for(i of[10,8])K(p+i)==1&&O(+i)] } else if (c=='K' |c=='k') [for(i of[1,8,9,10])O(i)+O(-i)] else if (c=='N' | c=='n') [for(i of[11,7,19,17])O(i)+O(-i)] else { if (c!='r' & c!='R') [for(i of[10,8])S(0,i)+S(0,-i)] if (c!='b' & c!='B') [for(i of[9,1])S(0,i)+S(0,-i)] } } }), o ) ``` **Test** in FireFox/FireBug console ``` B("7k/8/8/8/8/1P6/P7/Q1q4K w - - 0 1") ``` *Output* ``` B3B4 A2A3 A2A4 A1B2 A1C3 A1D4 A1E5 A1F6 A1G7 A1H8 A1B1 A1C1 H1G1 H1H2 H1G2 ``` [Answer] ## JAVA 631 599 594 Fixed a bug in the 599-bytes version (thank you Jack for pointing this out!) and shortened the code to 594-bytes. ``` class F{ public static void main(String[]A){int p=0,i=8,u,v,d,z[]={0,1,-1,2,1,0,1};String f=A[0],S[]="p,n,rqk,bqk,aA,PNBRQK,aAPNBRQK".split(","); for(;i>0;)f=f.replace(""+i,"a"+(--i==0?"":i)); for(;p<448;p++) for(int k=p%7,w=A[1].equals("w")?32:0,c=f.charAt(p/7%8+p/56*9),a=z[k],b=k==4?2:1,q=0;S[(k/2-1|k-1)/2].indexOf(c+w)>=0&&q++<(k<3?1:4);i=a,a=b,b=-i){ for(i=1,d=97;d==97&&((u=p/7%8+i*a)|(v=p/56+i*b*(1-w/16)))>=0&&(u|v)<8&&i<(k>4?(c=='K'||c=='k')?2:9:(k<1&&p/56==w/6+1?3:2))&&S[61/(61^(k*k-2))+5].indexOf((d=f.charAt(u+9*v))-w)>=0;i++)System.out.printf("%c%d%c%d ",65+p/7%8,8-p/56,65+u,8-v);}}} ``` Compile: `javac F.java` Run: `java F 6pk/6pp/8/8/8/p7/PP4pp/Q2p2pK w - - 0 1` Output: `B2B3 B2B4 B2A3 A1B1 A1C1 A1D1 H1H2 H1G1 H1G2` ]
[Question] [ *This was written as part of the [First Periodic Premier Programming Puzzle Push](http://meta.codegolf.stackexchange.com/q/298/15).* ### The Game A starting and ending word of the same length are provided. The objective of the game is to change one letter in the starting word to form a different valid word, repeating this step until the ending word is reached, using the fewest amount of steps. For example, given the words TREE and FLED, the output would be: ``` TREE FREE FLEE FLED 2 ``` ### Specifications * The Wikipedia articles for the [OWL](http://en.wikipedia.org/wiki/Official_Tournament_and_Club_Word_List) or [SOWPODS](http://en.wikipedia.org/wiki/SOWPODS) might be a useful starting point as far as word lists go. * The program should support two ways of selecting the start and end words: 1. Specified by the user via command-line, stdin, or whatever is suitable for your language of choice (just mention what you're doing). 2. Selecting 2 words at random from the file. * The starting and ending words, as well as all interim words should be the same length. * Each step should be printed out on its line. * The final line of your output should be the number of interim steps that were required to get between the starting and ending words. * If a match cannot be found between the starting and ending words, the output should consist of 3 lines: the beginning word, the ending word, and the word OY. * Include the Big O Notation for your solution in your answer * Please include 10 unique starting and ending words pairs (with their output, of course) to show the steps your program produces. (To save space, while your program should output these on individual lines, you can consolidate these into a single line for posting, replacing new lines with spaces and a comma between each run. ### Goals / Winning Criteria * The fastest/best Big O solution producing the shortest interim steps after one week will win. * If a tie results from the Big O criteria, the shortest code will win. * If there is still a tie, the first solution to reach its fastest and shortest revision will win. ### Tests / Sample Output ``` DIVE DIME DAME NAME 2 PEACE PLACE PLATE SLATE 2 HOUSE HORSE GORSE GORGE 2 POLE POSE POST PAST FAST 3 ``` ### Validation I am working on a script that can be used to validate the output. It will: 1. Ensure that each word is valid. 2. Ensure that each word is exactly 1 letter different from the previous word. It will not: 1. Check that the shortest number of steps were used. Once I've gotten that written, I will of course update this post. (: [Answer] Since length is listed as a criterion, here's the golfed version at 1681 characters (could probably still be improved by 10%): ``` import java.io.*;import java.util.*;public class W{public static void main(String[] a)throws Exception{int n=a.length<1?5:a[0].length(),p,q;String f,t,l;S w=new S();Scanner s=new Scanner(new File("sowpods"));while(s.hasNext()){f=s.next();if(f.length()==n)w.add(f);}if(a.length<1){String[]x=w.toArray(new String[0]);Random r=new Random();q=x.length;p=r.nextInt(q);q=r.nextInt(q-1);f=x[p];t=x[p>q?q:q+1];}else{f=a[0];t=a[1];}H<S> A=new H(),B=new H(),C=new H();for(String W:w){A.put(W,new S());for(p=0;p<n;p++){char[]c=W.toCharArray();c[p]='.';l=new String(c);A.get(W).add(l);S z=B.get(l);if(z==null)B.put(l,z=new S());z.add(W);}}for(String W:A.keySet()){C.put(W,w=new S());for(String L:A.get(W))for(String b:B.get(L))if(b!=W)w.add(b);}N m,o,ñ;H<N> N=new H();N.put(f,m=new N(f,t));N.put(t,o=new N(t,t));m.k=0;N[]H=new N[3];H[0]=m;p=H[0].h;while(0<1){if(H[0]==null){if(H[1]==H[2])break;H[0]=H[1];H[1]=H[2];H[2]=null;p++;continue;}if(p>=o.k-1)break;m=H[0];H[0]=m.x();if(H[0]==m)H[0]=null;for(String v:C.get(m.s)){ñ=N.get(v);if(ñ==null)N.put(v,ñ=new N(v,t));if(m.k+1<ñ.k){if(ñ.k<ñ.I){q=ñ.k+ñ.h-p;N Ñ=ñ.x();if(H[q]==ñ)H[q]=Ñ==ñ?null:Ñ;}ñ.b=m;ñ.k=m.k+1;q=ñ.k+ñ.h-p;if(H[q]==null)H[q]=ñ;else{ñ.n=H[q];ñ.p=ñ.n.p;ñ.n.p=ñ.p.n=ñ;}}}}if(o.b==null)System.out.println(f+"\n"+t+"\nOY");else{String[]P=new String[o.k+2];P[o.k+1]=o.k-1+"";m=o;for(q=m.k;q>=0;q--){P[q]=m.s;m=m.b;}for(String W:P)System.out.println(W);}}}class N{String s;int k,h,I=(1<<30)-1;N b,p,n;N(String S,String d){s=S;for(k=0;k<d.length();k++)if(d.charAt(k)!=S.charAt(k))h++;k=I;p=n=this;}N x(){N r=n;n.p=p;p.n=n;n=p=this;return r;}}class S extends HashSet<String>{}class H<V>extends HashMap<String,V>{} ``` The ungolfed version, which uses package names and methods and doesn't give warnings or extend classes just to alias them, is: ``` package com.akshor.pjt33; import java.io.*; import java.util.*; // WordLadder partially golfed and with reduced dependencies // // Variables used in complexity analysis: // n is the word length // V is the number of words (vertex count of the graph) // E is the number of edges // hash is the cost of a hash insert / lookup - I will assume it's constant, but without completely brushing it under the carpet public class WordLadder2 { private Map<String, Set<String>> wordsToWords = new HashMap<String, Set<String>>(); // Initialisation cost: O(V * n * (n + hash) + E * hash) private WordLadder2(Set<String> words) { Map<String, Set<String>> wordsToLinks = new HashMap<String, Set<String>>(); Map<String, Set<String>> linksToWords = new HashMap<String, Set<String>>(); // Cost: O(Vn * (n + hash)) for (String word : words) { // Cost: O(n*(n + hash)) for (int i = 0; i < word.length(); i++) { // Cost: O(n + hash) char[] ch = word.toCharArray(); ch[i] = '.'; String link = new String(ch).intern(); add(wordsToLinks, word, link); add(linksToWords, link, word); } } // Cost: O(V * n * hash + E * hash) for (Map.Entry<String, Set<String>> from : wordsToLinks.entrySet()) { String src = from.getKey(); wordsToWords.put(src, new HashSet<String>()); for (String link : from.getValue()) { Set<String> to = linksToWords.get(link); for (String snk : to) { // Note: equality test is safe here. Cost is O(hash) if (snk != src) add(wordsToWords, src, snk); } } } } public static void main(String[] args) throws IOException { // Cost: O(filelength + num_words * hash) Map<Integer, Set<String>> wordsByLength = new HashMap<Integer, Set<String>>(); BufferedReader br = new BufferedReader(new FileReader("sowpods"), 8192); String line; while ((line = br.readLine()) != null) add(wordsByLength, line.length(), line); if (args.length == 2) { String from = args[0].toUpperCase(); String to = args[1].toUpperCase(); new WordLadder2(wordsByLength.get(from.length())).findPath(from, to); } else { // 5-letter words are the most interesting. String[] _5 = wordsByLength.get(5).toArray(new String[0]); Random rnd = new Random(); int f = rnd.nextInt(_5.length), g = rnd.nextInt(_5.length - 1); if (g >= f) g++; new WordLadder2(wordsByLength.get(5)).findPath(_5[f], _5[g]); } } // O(E * hash) private void findPath(String start, String dest) { Node startNode = new Node(start, dest); startNode.cost = 0; startNode.backpointer = startNode; Node endNode = new Node(dest, dest); // Node lookup Map<String, Node> nodes = new HashMap<String, Node>(); nodes.put(start, startNode); nodes.put(dest, endNode); // Heap Node[] heap = new Node[3]; heap[0] = startNode; int base = heap[0].heuristic; // O(E * hash) while (true) { if (heap[0] == null) { if (heap[1] == heap[2]) break; heap[0] = heap[1]; heap[1] = heap[2]; heap[2] = null; base++; continue; } // If the lowest cost isn't at least 1 less than the current cost for the destination, // it can't improve the best path to the destination. if (base >= endNode.cost - 1) break; // Get the cheapest node from the heap. Node v0 = heap[0]; heap[0] = v0.remove(); if (heap[0] == v0) heap[0] = null; // Relax the edges from v0. int g_v0 = v0.cost; // O(hash * #neighbours) for (String v1Str : wordsToWords.get(v0.key)) { Node v1 = nodes.get(v1Str); if (v1 == null) { v1 = new Node(v1Str, dest); nodes.put(v1Str, v1); } // If it's an improvement, use it. if (g_v0 + 1 < v1.cost) { // Update the heap. if (v1.cost < Node.INFINITY) { int bucket = v1.cost + v1.heuristic - base; Node t = v1.remove(); if (heap[bucket] == v1) heap[bucket] = t == v1 ? null : t; } // Next update the backpointer and the costs map. v1.backpointer = v0; v1.cost = g_v0 + 1; int bucket = v1.cost + v1.heuristic - base; if (heap[bucket] == null) { heap[bucket] = v1; } else { v1.next = heap[bucket]; v1.prev = v1.next.prev; v1.next.prev = v1.prev.next = v1; } } } } if (endNode.backpointer == null) { System.out.println(start); System.out.println(dest); System.out.println("OY"); } else { String[] path = new String[endNode.cost + 1]; Node t = endNode; for (int i = t.cost; i >= 0; i--) { path[i] = t.key; t = t.backpointer; } for (String str : path) System.out.println(str); System.out.println(path.length - 2); } } private static <K, V> void add(Map<K, Set<V>> map, K key, V value) { Set<V> vals = map.get(key); if (vals == null) map.put(key, vals = new HashSet<V>()); vals.add(value); } private static class Node { public static int INFINITY = Integer.MAX_VALUE >> 1; public String key; public int cost; public int heuristic; public Node backpointer; public Node prev = this; public Node next = this; public Node(String key, String dest) { this.key = key; cost = INFINITY; for (int i = 0; i < dest.length(); i++) if (dest.charAt(i) != key.charAt(i)) heuristic++; } public Node remove() { Node rv = next; next.prev = prev; prev.next = next; next = prev = this; return rv; } } } ``` As you can see, the running cost analysis is `O(filelength + num_words * hash + V * n * (n + hash) + E * hash)`. If you'll accept my assumption that a hash table insertion/lookup is constant time, that's `O(filelength + V n^2 + E)`. The particular statistics of the graphs in SOWPODS mean that `O(V n^2)` really dominates `O(E)` for most `n`. Sample outputs: IDOLA, IDOLS, IDYLS, ODYLS, ODALS, OVALS, OVELS, OVENS, EVENS, ETENS, STENS, SKENS, SKINS, SPINS, SPINE, 13 WICCA, PROSY, OY BRINY, BRINS, TRINS, TAINS, TARNS, YARNS, YAWNS, YAWPS, YAPPS, 7 GALES, GASES, GASTS, GESTS, GESTE, GESSE, DESSE, 5 SURES, DURES, DUNES, DINES, DINGS, DINGY, 4 LICHT, LIGHT, BIGHT, BIGOT, BIGOS, BIROS, GIROS, GIRNS, GURNS, GUANS, GUANA, RUANA, 10 SARGE, SERGE, SERRE, SERRS, SEERS, DEERS, DYERS, OYERS, OVERS, OVELS, OVALS, ODALS, ODYLS, IDYLS, 12 KEIRS, SEIRS, SEERS, BEERS, BRERS, BRERE, BREME, CREME, CREPE, 7 This is one of the 6 pairs with the longest shortest path: GAINEST, FAINEST, FAIREST, SAIREST, SAIDEST, SADDEST, MADDEST, MIDDEST, MILDEST, WILDEST, WILIEST, WALIEST, WANIEST, CANIEST, CANTEST, CONTEST, CONFEST, CONFESS, CONFERS, CONKERS, COOKERS, COOPERS, COPPERS, POPPERS, POPPETS, POPPITS, POPPIES, POPSIES, MOPSIES, MOUSIES, MOUSSES, POUSSES, PLUSSES, PLISSES, PRISSES, PRESSES, PREASES, UREASES, UNEASES, UNCASES, UNCASED, UNBASED, UNBATED, UNMATED, UNMETED, UNMEWED, ENMEWED, ENDEWED, INDEWED, INDEXED, INDEXES, INDENES, INDENTS, INCENTS, INCESTS, INFESTS, INFECTS, INJECTS, 56 And one of the worst-case soluble 8-letter pairs: ENROBING, UNROBING, UNROPING, UNCOPING, UNCAPING, UNCAGING, ENCAGING, ENRAGING, ENRACING, ENLACING, UNLACING, UNLAYING, UPLAYING, SPLAYING, SPRAYING, STRAYING, STROYING, STROKING, STOOKING, STOOPING, STOMPING, STUMPING, SLUMPING, CLUMPING, CRUMPING, CRIMPING, CRISPING, CRISPINS, CRISPENS, CRISPERS, CRIMPERS, CRAMPERS, CLAMPERS, CLASPERS, CLASHERS, SLASHERS, SLATHERS, SLITHERS, SMITHERS, SMOTHERS, SOOTHERS, SOUTHERS, MOUTHERS, MOUCHERS, COUCHERS, COACHERS, POACHERS, POTCHERS, PUTCHERS, PUNCHERS, LUNCHERS, LYNCHERS, LYNCHETS, LINCHETS, 52 Now that I think I've got all the requirements of the question out of the way, my discussion. For a CompSci the question obviously reduces to shortest path in a graph G whose vertices are words and whose edges connect words differing in one letter. Generating the graph efficiently isn't trivial - I actually have an idea I need to revisit to reduce the complexity to O(V n hash + E). The way I do it involves creating a graph which inserts extra vertices (corresponding to words with one wildcard character) and is homeomorphic to the graph in question. I did consider using that graph rather than reducing to G - and I suppose that from a golfing point of view I should have done - on the basis that a wildcard node with more than 3 edges reduces the number of edges in the graph, and the standard worst case running time of shortest path algorithms is `O(V heap-op + E)`. However, the first thing I did was to run some analyses of the graphs G for different word lengths, and I discovered that they're extremely sparse for words of 5 or more letters. The 5-letter graph has 12478 vertices and 40759 edges; adding link nodes makes the graph worse. By the time you're up to 8 letters there are fewer edges than nodes, and 3/7 of the words are "aloof". So I rejected that optimisation idea as not really helpful. The idea which did prove helpful was to examine the heap. I can honestly say that I've implemented some moderately exotic heaps in the past, but none as exotic as this. I use A-star (since C provides no benefit given the heap I'm using) with the obvious heuristic of number of letters different from the target, and a bit of analysis shows that at any time there are no more than 3 different priorities in the heap. When I pop a node whose priority is (cost + heuristic) and look at its neighbours, there are three cases I'm considering: 1) neighbour's cost is cost+1; neighbour's heuristic is heuristic-1 (because the letter it changes becomes "correct"); 2) cost+1 and heuristic+0 (because the letter it changes goes from "wrong" to "still wrong"; 3) cost+1 and heuristic+1 (because the letter it changes goes from "correct" to "wrong"). So if I relax the neighbour I'm going to insert it at the same priority, priority+1, or priority+2. As a result I can use a 3-element array of linked lists for the heap. I should add a note about my assumption that hash lookups are constant. Very well, you may say, but what about hash computations? The answer is that I'm amortising them away: `java.lang.String` caches its `hashCode()`, so the total time spent computing hashes is `O(V n^2)` (in generating the graph). There is another change which affects the complexity, but the question of whether it is an optimisation or not depends on your assumptions about statistics. (IMO putting "the best Big O solution" as a criterion is a mistake because there isn't a best complexity, for a simple reason: there isn't a single variable). This change affects the graph generation step. In the code above, it's: ``` Map<String, Set<String>> wordsToLinks = new HashMap<String, Set<String>>(); Map<String, Set<String>> linksToWords = new HashMap<String, Set<String>>(); // Cost: O(Vn * (n + hash)) for (String word : words) { // Cost: O(n*(n + hash)) for (int i = 0; i < word.length(); i++) { // Cost: O(n + hash) char[] ch = word.toCharArray(); ch[i] = '.'; String link = new String(ch).intern(); add(wordsToLinks, word, link); add(linksToWords, link, word); } } // Cost: O(V * n * hash + E * hash) for (Map.Entry<String, Set<String>> from : wordsToLinks.entrySet()) { String src = from.getKey(); wordsToWords.put(src, new HashSet<String>()); for (String link : from.getValue()) { Set<String> to = linksToWords.get(link); for (String snk : to) { // Note: equality test is safe here. Cost is O(hash) if (snk != src) add(wordsToWords, src, snk); } } } ``` That's `O(V * n * (n + hash) + E * hash)`. But the `O(V * n^2)` part comes from generating a new n-character string for each link and then computing its hashcode. This can be avoided with a helper class: ``` private static class Link { private String str; private int hash; private int missingIdx; public Link(String str, int hash, int missingIdx) { this.str = str; this.hash = hash; this.missingIdx = missingIdx; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { Link l = (Link)obj; // Unsafe, but I know the contexts where I'm using this class... if (this == l) return true; // Essential if (hash != l.hash || missingIdx != l.missingIdx) return false; for (int i = 0; i < str.length(); i++) { if (i != missingIdx && str.charAt(i) != l.str.charAt(i)) return false; } return true; } } ``` Then the first half of the graph generation becomes ``` Map<String, Set<Link>> wordsToLinks = new HashMap<String, Set<Link>>(); Map<Link, Set<String>> linksToWords = new HashMap<Link, Set<String>>(); // Cost: O(V * n * hash) for (String word : words) { // apidoc: The hash code for a String object is computed as // s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // Cost: O(n * hash) int hashCode = word.hashCode(); int pow = 1; for (int j = word.length() - 1; j >= 0; j--) { Link link = new Link(word, hashCode - word.charAt(j) * pow, j); add(wordsToLinks, word, link); add(linksToWords, link, word); pow *= 31; } } ``` By using the structure of the hashcode we can generate the links in `O(V * n)`. However, this has a knock-on effect. Inherent in my assumption that hash lookups are constant time is an assumption that comparing objects for equality is cheap. However, the equality test of Link is `O(n)` in the worst case. The worst case is when we have a hash collision between two equal links generated from different words - i.e. it occurs `O(E)` times in the second half of the graph generation. Other than that, except in the unlikely event of a hash collision between non-equal links, we're good. So we've traded in `O(V * n^2)` for `O(E * n * hash)`. See my previous point about statistics. [Answer] # Java **Complexity** : ?? (I don't have a CompSci Degree, so i'd appreciate help in this matter.) **Input** : Provide Pair of words (more than 1 pair if you wish) in the command line. If no Command line is specified 2 distinct random words are chosen. ``` import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; public class M { // for memoization private static Map<String, List<String>> memoEdits = new HashMap<String, List<String>>(); private static Set<String> dict; private static List<String> edits(String word, Set<String> dict) { if(memoEdits.containsKey(word)) return memoEdits.get(word); List<String> editsList = new LinkedList<String>(); char[] letters = word.toCharArray(); for(int i = 0; i < letters.length; i++) { char hold = letters[i]; for(char ch = 'A'; ch <= 'Z'; ch++) { if(ch != hold) { letters[i] = ch; String nWord = new String(letters); if(dict.contains(nWord)) { editsList.add(nWord); } } } letters[i] = hold; } memoEdits.put(word, editsList); return editsList; } private static Map<String, String> bfs(String wordFrom, String wordTo, Set<String> dict) { Set<String> visited = new HashSet<String>(); List<String> queue = new LinkedList<String>(); Map<String, String> pred = new HashMap<String, String>(); queue.add(wordFrom); while(!queue.isEmpty()) { String word = queue.remove(0); if(word.equals(wordTo)) break; for(String nWord: edits(word, dict)) { if(!visited.contains(nWord)) { queue.add(nWord); visited.add(nWord); pred.put(nWord, word); } } } return pred; } public static void printPath(String wordTo, String wordFrom) { int c = 0; Map<String, String> pred = bfs(wordFrom, wordTo, dict); do { System.out.println(wordTo); c++; wordTo = pred.get(wordTo); } while(wordTo != null && !wordFrom.equals(wordTo)); System.out.println(wordFrom); if(wordTo != null) System.out.println(c - 1); else System.out.println("OY"); System.out.println(); } public static void main(String[] args) throws Exception { BufferedReader scan = new BufferedReader(new FileReader(new File("c:\\332609\\dict.txt")), 40 * 1024); String line; dict = new HashSet<String>(); //the dictionary (1 word per line) while((line = scan.readLine()) != null) { dict.add(line); } scan.close(); if(args.length == 0) { // No Command line Arguments? Pick 2 random // words. Random r = new Random(System.currentTimeMillis()); String[] words = dict.toArray(new String[dict.size()]); int x = r.nextInt(words.length), y = r.nextInt(words.length); while(x == y) //same word? that's not fun... y = r.nextInt(words.length); printPath(words[x], words[y]); } else { // Arguments provided, search for path pairwise for(int i = 0; i < args.length; i += 2) { if(i + 1 < args.length) printPath(args[i], args[i + 1]); } } } } ``` [Answer] ## c on unix Using dijkstra algorithm. A large fraction of the code is a costume n-ary tree implementation, which serves to hold * The wordlist (thus minimizing the number of times the input file is read (twice for no arguments, once for other cases) on the assumption that file IO is slow * The partial trees as we build them. * The final path. Anyone interested in seeing *how* it works should probably read `findPath`, `process`, and `processOne` (and their associated comments). And maybe `buildPath` and `buildPartialPath`. The rest is bookkeeping and scaffolding. Several routines used during testing and development but not in the "production" version have been left in place. I'm using `/usr/share/dict/words` on my Mac OS 10.5 box, which has so many long, esoteric entries that letting it run completely at random generates a *lot* of `OY`s. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getline.h> #include <time.h> #include <unistd.h> #include <ctype.h> const char*wordfile="/usr/share/dict/words"; /* const char*wordfile="./testwords.txt"; */ const long double RANDOM_MAX = (2LL<<31)-1; typedef struct node_t { char*word; struct node_t*kids; struct node_t*next; } node; /* Return a pointer to a newly allocated node. If word is non-NULL, * call setWordNode; */ node*newNode(char*word){ node*n=malloc(sizeof(node)); n->word=NULL; n->kids=NULL; n->next=NULL; if (word) n->word = strdup(word); return n; } /* We can use the "next" links to treat these as a simple linked list, * and further can make it a stack or queue by * * * pop()/deQueu() from the head * * push() onto the head * * enQueue at the back */ void push(node*n, node**list){ if (list==NULL){ fprintf(stderr,"Active operation on a NULL list! Exiting\n"); exit(5); } n->next = (*list); (*list) = n; } void enQueue(node*n, node**list){ if (list==NULL){ fprintf(stderr,"Active operation on a NULL list! Exiting\n"); exit(5); } if ( *list==NULL ) { *list=n; } else { enQueue(n,&((*list)->next)); } } node*pop(node**list){ node*temp=NULL; if (list==NULL){ fprintf(stderr,"Active operation on a NULL list! Exiting\n"); exit(5); } temp = *list; if (temp != NULL) { (*list) = temp->next; temp->next=NULL; } return temp; } node*deQueue(node**list){ /* Alias for pop */ return pop(list); } /* return a pointer to a node in tree matching word or NULL if none */ node* isInTree(char*word, node*tree){ node*isInNext=NULL; node*isInKids=NULL; if (tree==NULL || word==NULL) return NULL; if (tree->word && (0 == strcasecmp(word,tree->word))) return tree; /* prefer to find the target at shallow levels so check the siblings before the kids */ if (tree->next && (isInNext=isInTree(word,tree->next))) return isInNext; if (tree->kids && (isInKids=isInTree(word,tree->kids))) return isInKids; return NULL; } node* freeTree(node*t){ if (t==NULL) return NULL; if (t->word) {free(t->word); t->word=NULL;} if (t->next) t->next=freeTree(t->next); if (t->kids) t->kids=freeTree(t->kids); free(t); return NULL; } void printTree(node*t, int indent){ int i; if (t==NULL) return; for (i=0; i<indent; i++) printf("\t"); printf("%s\n",t->word); printTree(t->kids,indent+1); printTree(t->next,indent); } /* count the letters of difference between two strings */ int countDiff(const char*w1, const char*w2){ int count=0; if (w1==NULL || w2==NULL) return -1; while ( (*w1)!='\0' && (*w2)!='\0' ) { if ( (*w1)!=(*w2) ) count++; w1++; w2++; } return count; } node*buildPartialPath(char*stop, node*tree){ node*list=NULL; while ( (tree != NULL) && (tree->word != NULL) && (0 != strcasecmp(tree->word,stop)) ) { node*kid=tree->kids; node*newN = newNode(tree->word); push(newN,&list); newN=NULL; /* walk over all all kids not leading to stop */ while ( kid && (strcasecmp(kid->word,stop)!=0) && !isInTree(stop,kid->kids) ) { kid=kid->next; } if (kid==NULL) { /* Assuming a preconditions where isInTree(stop,tree), we should * not be able to get here... */ fprintf(stderr,"Unpossible!\n"); exit(7); } /* Here we've found a node that either *is* the target or leads to it */ if (strcasecmp(stop,kid->word) == 0) { break; } tree = kid; } return list; } /* build a node list path * * We can walk down each tree, identfying nodes as we go */ node*buildPath(char*pivot,node*frontTree,node*backTree){ node*front=buildPartialPath(pivot,frontTree); node*back=buildPartialPath(pivot,backTree); /* weld them together with pivot in between * * The front list is in reverse order, the back list in order */ node*thePath=NULL; while (front != NULL) { node*n=pop(&front); push(n,&thePath); } if (pivot != NULL) { node*n=newNode(pivot); enQueue(n,&thePath); } while (back != NULL) { node*n=pop(&back); enQueue(n,&thePath); } return thePath; } /* Add new child nodes to the single node in ts named by word. Also * queue these new word in q * * Find node N matching word in ts * For tword in wordList * if (tword is one change from word) AND (tword not in ts) * add tword to N.kids * add tword to q * if tword in to * return tword * return NULL */ char* processOne(char *word, node**q, node**ts, node**to, node*wordList){ if ( word==NULL || q==NULL || ts==NULL || to==NULL || wordList==NULL ) { fprintf(stderr,"ProcessOne called with NULL argument! Exiting.\n"); exit(9); } char*result=NULL; /* There should be a node in ts matching the leading node of q, find it */ node*here = isInTree(word,*ts); /* Now test each word in the list as a possible child of HERE */ while (wordList != NULL) { char *tword=wordList->word; if ((1==countDiff(word,tword)) && !isInTree(tword,*ts)) { /* Queue this up as a child AND for further processing */ node*newN=newNode(tword); enQueue(newN,&(here->kids)); newN=newNode(tword); enQueue(newN,q); /* This might be our pivot */ if ( isInTree(tword,*to) ) { /* we have found a node that is in both trees */ result=strdup(tword); return result; } } wordList=wordList->next; } return result; } /* Add new child nodes to ts for all the words in q */ char* process(node**q, node**ts, node**to, node*wordList){ node*tq=NULL; char*pivot=NULL; if ( q==NULL || ts==NULL || to==NULL || wordList==NULL ) { fprintf(stderr,"Process called with NULL argument! Exiting.\n"); exit(9); } while (*q && (pivot=processOne((*q)->word,&tq,ts,to,wordList))==NULL) { freeTree(deQueue(q)); } freeTree(*q); *q=tq; return pivot; } /* Find a path between w1 and w2 using wordList by dijkstra's * algorithm * * Use a breadth-first extensions of the trees alternating between * trees. */ node* findPath(char*w1, char*w2, node*wordList){ node*thePath=NULL; /* our resulting path */ char*pivot=NULL; /* The node we find that matches */ /* trees of existing nodes */ node*t1=newNode(w1); node*t2=newNode(w2); /* queues of nodes to work on */ node*q1=newNode(w1); node*q2=newNode(w2); /* work each queue all the way through alternating until a word is found in both lists */ while( (q1!=NULL) && ((pivot = process(&q1,&t1,&t2,wordList)) == NULL) && (q2!=NULL) && ((pivot = process(&q2,&t2,&t1,wordList)) == NULL) ) /* no loop body */ ; /* one way or another we are done with the queues here */ q1=freeTree(q1); q2=freeTree(q2); /* now construct the path */ if (pivot!=NULL) thePath=buildPath(pivot,t1,t2); /* clean up after ourselves */ t1=freeTree(t1); t2=freeTree(t2); return thePath; } /* Convert a non-const string to UPPERCASE in place */ void upcase(char *s){ while (s && *s) { *s = toupper(*s); s++; } } /* Walks the input file stuffing lines of the given length into a list */ node*getListWithLength(const char*fname, int len){ int l=-1; size_t n=0; node*list=NULL; char *line=NULL; /* open the word file */ FILE*f = fopen(fname,"r"); if (NULL==f){ fprintf(stderr,"Could not open word file '%s'. Exiting.\n",fname); exit(3); } /* walk the file, trying each word in turn */ while ( !feof(f) && ((l = getline(&line,&n,f)) != -1) ) { /* strip trailing whitespace */ char*temp=line; strsep(&temp," \t\n"); if (strlen(line) == len) { node*newN = newNode(line); upcase(newN->word); push(newN,&list); } } fclose(f); return list; } /* Assumes that filename points to a file containing exactly one * word per line with no other whitespace. * It will return a randomly selected word from filename. * * If veto is non-NULL, only non-matching words of the same length * wll be considered. */ char*getRandomWordFile(const char*fname, const char*veto){ int l=-1, count=1; size_t n=0; char *word=NULL; char *line=NULL; /* open the word file */ FILE*f = fopen(fname,"r"); if (NULL==f){ fprintf(stderr,"Could not open word file '%s'. Exiting.\n",fname); exit(3); } /* walk the file, trying each word in turn */ while ( !feof(f) && ((l = getline(&line,&n,f)) != -1) ) { /* strip trailing whitespace */ char*temp=line; strsep(&temp," \t\n"); if (strlen(line) < 2) continue; /* Single letters are too easy! */ if ( (veto==NULL) || /* no veto means chose from all */ ( ( strlen(line) == strlen(veto) ) && /* veto means match length */ ( 0 != strcasecmp(veto,line) ) /* but don't match word */ ) ) { /* This word is worthy of consideration. Select it with random chance (1/count) then increment count */ if ( (word==NULL) || (random() < RANDOM_MAX/count) ) { if (word) free(word); word=strdup(line); } count++; } } fclose(f); upcase(word); return word; } void usage(int argc, char**argv){ fprintf(stderr,"%s [ <startWord> [ <endWord> ]]:\n\n",argv[0]); fprintf(stderr, "\tFind the shortest transformation from one word to another\n"); fprintf(stderr, "\tchanging only one letter at a time and always maintaining a\n"); fprintf(stderr, "\tword that exists in the word file.\n\n"); fprintf(stderr, "\tIf startWord is not passed, chose at random from '%s'\n", wordfile); fprintf(stderr, "\tIf endWord is not passed, chose at random from '%s'\n", wordfile); fprintf(stderr, "\tconsistent with the length of startWord\n"); exit(2); } int main(int argc, char**argv){ char *startWord=NULL; char *endWord=NULL; /* intialize OS services */ srandom(time(0)+getpid()); /* process command line */ switch (argc) { case 3: endWord = strdup(argv[2]); upcase(endWord); case 2: startWord = strdup(argv[1]); upcase(startWord); case 1: if (NULL==startWord) startWord = getRandomWordFile(wordfile,NULL); if (NULL==endWord) endWord = getRandomWordFile(wordfile,startWord); break; default: usage(argc,argv); break; } /* need to check this in case the user screwed up */ if ( !startWord || ! endWord || strlen(startWord) != strlen(endWord) ) { fprintf(stderr,"Words '%s' and '%s' are not the same length! Exiting\n", startWord,endWord); exit(1); } /* Get a list of all the words having the right length */ node*wordList=getListWithLength(wordfile,strlen(startWord)); /* Launch into the path finder*/ node *theList=findPath(startWord,endWord,wordList); /* Print the resulting path */ if (theList) { int count=-2; while (theList) { printf("%s\n",theList->word); theList=theList->next; count++; } printf("%d\n",count); } else { /* No path found case */ printf("%s %s OY\n",startWord,endWord); } return 0; } ``` Some output: ``` $ ./changeword dive name DIVE DIME DAME NAME 2 $ ./changeword house gorge HOUSE HORSE GORSE GORGE 2 $ ./changeword stop read STOP STEP SEEP SEED REED READ 4 $ ./changeword peace slate PEACE PLACE PLATE SLATE 2 $ ./changeword pole fast POLE POSE POST PAST FAST 3 $ ./changeword QUINTIPED LINEARITY OY $ ./changeword sneaky SNEAKY WAXILY OY $ ./changeword TRICKY TRICKY PRICKY PRINKY PRANKY TRANKY TWANKY SWANKY SWANNY SHANNY SHANTY SCANTY SCATTY SCOTTY SPOTTY SPOUTY STOUTY STOUTH STOUSH SLOUSH SLOOSH SWOOSH 19 $ ./changeword router outlet ROUTER ROTTER RUTTER RUTHER OUTHER OUTLER OUTLET 5 $ ./changeword IDIOM IDISM IDIST ODIST OVIST OVEST OVERT AVERT APERT APART SPART SPARY SEARY DEARY DECRY DECAY DECAN DEDAN SEDAN 17 ``` Complexity analysis is non-trivial. The search is a two-sided, iterative deepening. * For each node examined I walk the entire word list (though limited to words of the right length). Call the length of the list `W`. * The minimum number of steps is `S_min = (<number of different letter>-1)` because if we are only one letter apart we score the change at 0 intermediate steps. The maximum is hard to quantify see the TRICKY--SWOOSH run above. Each half of the tree will be `S/2-1` to `S/2` * I have not done an analysis of the branching behavior of the tree, but call it `B`. So the minimum number of operations is around `2 * (S/2)^B * W`, not really good. ]
[Question] [ The Pascal's triangle and the Fibonacci sequence have an interesting connection: [![enter image description here](https://i.stack.imgur.com/31e0v.png)](https://i.stack.imgur.com/31e0v.png) *Source: [Math is Fun - Pascal's triangle](https://www.mathsisfun.com/pascals-triangle.html)* Your job is to prove this property in Lean theorem prover (Lean 3 + mathlib). Shortest code in bytes wins. ``` import data.nat.choose.basic import data.nat.fib import data.list.defs import data.list.nat_antidiagonal theorem X (n : ℕ) : ((list.nat.antidiagonal n).map (function.uncurry nat.choose)).sum = n.succ.fib := sorry -- replace this with actual proof ``` Since the statement itself depends on the current version of mathlib, it is encouraged to use [Lean web editor](https://leanprover-community.github.io/lean-web-editor/) (as opposed to TIO) to demonstrate that your answer is correct. Some primer on the built-ins used: * `nat` or `ℕ` is the set/type of natural numbers including zero. * `list.nat.antidiagonal n` creates a list of all pairs that sum to `n`, namely `[(0,n), (1,n-1), ..., (n,0)]`. * `nat.choose n k` or `n.choose k` is equal to \$\_nC\_k\$. * `nat.fib n` or `n.fib` is the Fibonacci sequence defined with the initial terms of \$f\_0 = 0, f\_1 = 1\$. In mathematics notation, the equation to prove is $$ \forall n \in \mathbb{N},\; \sum^{n}\_{i=0}{\_iC\_{n-i}} = f\_{n+1} $$ ## Rules * Your code should provide a named theorem or lemma `X` having the exact type as shown above. [Any kind of sidestepping is not allowed.](https://codegolf.meta.stackexchange.com/a/23938/78410) * The score of your submission is the length of your entire source code in bytes (including the four imports given and any extra imports you need). [Answer] # Lean, 299 bytes ``` import data.list data.nat.fib open nat def s(n k):=((list.nat.antidiagonal n).map$λa:_×_,choose(a.1+k)a.2).sum def X:∀n,s n 0=fib(n+1)|0:=rfl|1:=rfl|(n+2):=by{let:∀k,s(n+2)k=choose k(n+2)+s n k+s(n+1)k,induction n;intro;simp[s,(∘),<-add_one,add_assoc,*]at*;ring,rw[one_add,choose],ring,safe} ``` [Try it on Lean Web Editor](https://leanprover-community.github.io/lean-web-editor/#code=import%20data.list%20data.nat.fib%0Aopen%20nat%0Adef%20s%28n%20k%29%3A%3D%28%28list.nat.antidiagonal%20n%29.map%24%CE%BBa%3A_%C3%97_%2Cchoose%28a.1%2Bk%29a.2%29.sum%0Adef%20X%3A%E2%88%80n%2Cs%20n%200%3Dfib%28n%2B1%29%7C0%3A%3Drfl%7C1%3A%3Drfl%7C%28n%2B2%29%3A%3Dby%7Blet%3A%E2%88%80k%2Cs%28n%2B2%29k%3Dchoose%20k%28n%2B2%29%2Bs%20n%20k%2Bs%28n%2B1%29k%2Cinduction%0An%3Bintro%3Bsimp%5Bs%2C%28%E2%88%98%29%2C%3C-add_one%2Cadd_assoc%2C*%5Dat*%3Bring%2Crw%5Bone_add%2Cchoose%5D%2Cring%2Csafe%7D%0A%0Aexample%20%3A%20%E2%88%80%20%28n%20%3A%20%E2%84%95%29%2C%0A%20%20%28%28list.nat.antidiagonal%20n%29.map%20%28function.uncurry%20nat.choose%29%29.sum%0A%20%20%3D%20n.succ.fib%20%3A%3D%0A%20%20X) [Answer] # Lean, ~~247~~ 243 bytes ``` import data.nat.fib data.list open nat list.nat def X:∀n,((antidiagonal n).map$function.uncurry choose).sum=fib(n+1)|0:=rfl|1:=rfl|(n+2):=by rw[fib_add_two,antidiagonal_succ_succ'];simpa[<-X,antidiagonal_succ',<-add_assoc,<-list.sum_map_add] ``` [Try it on Lean Web Editor](https://leanprover-community.github.io/lean-web-editor/#code=import%20data.nat.fib%20data.list%0Aopen%20nat%20list.nat%0Adef%20X%3A%E2%88%80n%2C%28%28antidiagonal%20n%29.map%24function.uncurry%0Achoose%29.sum%3Dfib%28n%2B1%29%7C0%3A%3Drfl%7C1%3A%3Drfl%7C%28n%2B2%29%3A%3Dby%0Arw%5Bfib_add_two%2Cantidiagonal_succ_succ%27%5D%3Bsimpa%5B%3C-X%2Cantidiagonal_succ%27%2C%3C-add_assoc%2C%3C-list.sum_map_add%5D) *(Note 2/15/2022: this will work within 24 hours)* Perhaps it's cheating, since I contributed very relevant lemmas about antidiagonals to mathlib that were just merged this morning, but I added them for other reasons, I promise! The Lean Web Editor is updated daily, so it should eventually work. ]
[Question] [ ## Background In Haskell and many other functional languages, function application `f(x)` is simply written as `f x`. Also, this form of function application is left-associative, which means `f x y z` is `((f x) y) z`, or `((f(x))(y))(z)`. Haskell also has a binary operator called `$`. `f $ x` does function application just like `f x`, but it is right-associative, which means you can write `f $ g $ h $ x` to mean `f(g(h(x)))`. If you used Haskell enough, you might have once wondered, "would it be nice if `f x` itself were right-associative?" Now it's about time to see this in action. For the sake of simplicity, let's assume all the identifiers are single-character and omit the spaces entirely. ## Challenge Given a valid expression written using left-associative function application, convert it to the minimal equivalent expression where function application is right-associative. The result must not contain any unnecessary parentheses. An expression is defined using the following grammar: ``` expr := [a-z] | "(" expr ")" | expr expr ``` To explain this in plain English, a valid expression is a lowercase English letter, another expression wrapped in a pair of parens, or multiple expressions concatenated. I/O can be done as a string, a list of chars, or a list of codepoints. The input is guaranteed to have minimal number of parens under left-associative system. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` input -> output --------------- foo -> (fo)o b(ar) -> bar q(uu)x -> (quu)x abcde -> (((ab)c)d)e f(g(hx)) -> fghx g(fx)(hy) -> (gfx)hy ``` [Answer] # JavaScript, 71 bytes *Saved 2 bytes by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).* ``` f=(e,l='',r=e.shift())=>(r=r>{}?r:r<f&&f(e))?f(e,l[1]?`(${l})`+r:l+r):l ``` [Try it online!](https://tio.run/##dczRCoJAEIXh@x5DQmfQFrq1Vh9EBFfdUWNxa9QwxGffim7buwPfz7mpp5oaHu7zabStdo4k6MTIKEpYajH1A82AKDNgydm255zylcKQQCPm9G2Lc5lXcNzMjlXMqYkZU@MaO07WaGFsBwSFECIga4MS8XL4YzUoRq8@YFlw9bKqm1Z7laCDfkX/@2esCP3rV7g3 "JavaScript (Node.js) – Try It Online") * `l`, `r` are two operand [Answer] # [Perl 5](https://www.perl.org/) `-p`, 73 bytes ``` 1while$e='(\w|\((?1)*\))',s/$e$e(?=$e)/($&)/;1while s/\(($e*)\)(?!$e)/$1/ ``` [Try it online!](https://tio.run/##JcpBCsIwEEbhfU6hMNj5ixKycCUlF8mm1UlTKKY2lkbw7MaK2/e@SebxXIpZwzAKSVOxW9@O2RrUDqiOSdPW2TYk0EwH6Msf75LeHEkNB7b73yajS/Exqo7bGerBy4Ks2u56E@W555AB1bPP4PDCJ07PId5TOU1f "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 60 bytes ``` ;Ṫ$FL$¡1ĿØ(jƊ¹ŒḊ?€ =þØ(Ä_Ż}ỊṖʋ/aSƲœp⁸;2ĿW$}¥2/Ẏ3œṖW;¥2/ẎƲÐLÇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/64c5VKm4@KocWGh7Zf3iGRtaxrkM7j056uKPL/lHTGi7bw/uAgodb4o/urn24u@vhzmmnuvUTg49tOjq54FHjDmujI/vDVWoPLTXSf7irz/joZKCCcGso99imwxN8Drf/t37UMEdB107hUcNc68PtXA93bzncDjQ78v//tPx8riSNxCJNrkKN0lLNCq7EpOSUVK40jXSNjApNTa50jbQKTY2MSk0A "Jelly – Try It Online") A full program taking a string argument and printing the result to STDOUT. Uses recursion in both links, but in both cases replacing `1Ŀ` or `2Ŀ` with `ß` fails to work. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 94 bytes ``` +1`((\w|(\()|(?<-3>\)))+?(?(3)^)){2}(?!\)) ($&) +`\(((\w|(\()|(?<-3>\)))+)\)(?(3)^)(?=\)|$) $1 ``` [Try it online!](https://tio.run/##bcyxCsIwFIXh/b6FEOUcgkPtqmb0JS6SVJvWxdJiMWJ89tjB0fWH75/ax@0eyhonX2zlAX1mKJjh9tv6qCStg0PNM/nefeBWSxOYDcV6xV9A5Y/AHZTZUExVShwGaRAmyoh5ZpLQXK6tRHTo0zLtEBPRv/gF "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +1` ``` Make the first possible substitution each time, looping until no more substitutions are possible. This means that in the case of `abcde`, only `ab` is surrounded the first time, then `(ab)c` the second time, et cetera. ``` ((\w|(\()|(?<-3>\)))+?(?(3)^)){2}(?!\)) ($&) ``` Put parentheses around any pair of expressions that does not already have one. ``` +`\(((\w|(\()|(?<-3>\)))+)\)(?(3)^)(?=\)|$) $1 ``` Remove any parentheses not needed under right association. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes ``` F⁺(S¿⁼ι(⊞υ⟦⟧«F⁼ι)≔⪫⊟υωιF‹¹L§υ±¹⊞υ⟦⪫()⪫⊟υω⟧⊞§υ±¹ι»⪫⊟υω ``` [Try it online!](https://tio.run/##bY8xC4MwEIVn/RWH0x2kg7OTQweLFKFj6SA2xkCI1iStpfS3p1GHFunBLcd733vXdPXY9LXyvu1HwEo5gwkmDAo9OHuyo9QCiQhkC7i/uVoZlAyCJNwqZzp0DM4XymKuDIdXHC2cHyXNytwYKTQeeqmx6gd0xOARVgbj6ii5MZgyKLkWtsPcFvrKp5l@5KK2HFOa55u5sBKk0HWDpblOtAj/YtbYd1yF5@y2E2XeC2wnwu5JfndXHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁺(S ``` Loop over the input with an extra `(` prefixed as this is golfier then setting up the stack manually. ``` ¿⁼ι(⊞υ⟦⟧« ``` For each `(`, push a new empty list to the stack. ``` F⁼ι) ``` If the next character is a `)`, then... ``` ≔⪫⊟υωι ``` the next term is actually the joined list at the top of the stack. ``` F‹¹L§υ±¹ ``` If the list at the top of the stack already has two terms, then... ``` ⊞υ⟦⪫()⪫⊟υω⟧ ``` ... replace it with a list of a `()` wrapped term. ``` ⊞§υ±¹ι ``` Push the current term to the list at the top of the stack. ``` »⪫⊟υω ``` Join and output any remaining terms. ]
[Question] [ This challenge is from a game called [Keep Talking And Nobody Explodes.](http://www.keeptalkinggame.com/) *Memory is a fragile thing but so is everything else when a bomb goes off, so pay attention!* – from the [manual](https://ktane.timwi.de/HTML/Memory.html) # The Objective A number from 1–4 is given as the "display", along with scrambled numbers 1–4 as the "buttons." The output must be the label of the correct "button." Repeat this process 5 times. # The Format The input format must be: ``` <display #> <buttons #> ``` Repeated 5 times. As long as the numbers are distinguishable and the `<display #>` is dedicated separately, the input format and type don't matter. For any input that doesn't fit this format, the entire challenge falls in *don't care* situation. The output format and type don't matter as long as the numbers are distinguishable. # Which button to press Pressing a button means to output the label of the button. The buttons are indexed from left to right, and are 1-indexed. **For the 1st line:** If the display is 1, press the button in the second position. If the display is 2, press the button in the second position. If the display is 3, press the button in the third position. If the display is 4, press the button in the fourth position. **For the 2nd line:** If the display is 1, press the button labeled “4”. If the display is 2, press the button in the same position as you pressed in line #1. If the display is 3, press the button in the first position. If the display is 4, press the button in the same position as you pressed in line #1. **For the 3rd line:** If the display is 1, press the button with the same label you pressed in line #2. If the display is 2, press the button with the same label you pressed in line #1. If the display is 3, press the button in the third position. If the display is 4, press the button labeled “4”. **For the 4th line:** If the display is 1, press the button in the same position as you pressed in line #1. If the display is 2, press the button in the first position. If the display is 3, press the button in the same position as you pressed in line #2. If the display is 4, press the button in the same position as you pressed in line #2. **For the last line:** If the display is 1, press the button with the same label you pressed in line #1. If the display is 2, press the button with the same label you pressed in line #2. If the display is 3, press the button with the same label you pressed in line #4. If the display is 4, press the button with the same label you pressed in line #3. # An Example Given the following input: ``` 2 1432 4 3214 2 4213 1 4231 1 3214 ``` For the 1st line, press the button in the second position, so output `4`. For the 2nd line, press the button in the same position as you pressed in line #1, so output `2`. For the 3rd line, press the button with the same label you pressed in line #1, so output `4`. For the 4th line, press the button in the same position as you pressed in line #1, so output `2`. For the last line, press the button with the same label you pressed in line #1, so output `4`. So the entire output is `42424`, in any format and type. [Answer] # JavaScript (ES6), ~~109 106 105~~ 104 bytes Takes input as a list of pairs `[display, "buttons"]`. Returns a list of pressed buttons. ``` a=>a.map(([d,b],i)=>a[i]=b[a[~i]=(n='_5567.848106.80990132'[i*4+d])>3?n>7?a[7-n]:n-4:b.search(a[n]||4)]) ``` [Try it online!](https://tio.run/##VcvdCoIwGMbx865idNJWOtxHacL0Ql5GvH6VUVtodCTdupmE0NEDP57/FV/Yl137eIbOV/XYmBFNhvyOD0qhCgobtGwCaK0pAOE9LXVmc9rvDzFPdCKiA0@i4zESSm6g3epdZVmmcpfFOUIcOpu6UKcF72vsygtFcHYYNLNsLL3r/a3mN3@mDYUVIUBkQNZCK7kmNphBT6Ck0At8H1oKtYCYQYk/@CUry9j4AQ "JavaScript (Node.js) – Try It Online") ### How? The action for each line and each displayed value is encoded as a single character as follows (with 0-indexed lines and positions): * \$n=0\$ to \$3\$: press the button with the same label that we pressed in line \$n\$ * \$n=4\$ to \$7\$: press the button in position \$n-4\$ * \$n=8\$ or \$9\$: press the button in the same position as we pressed in line \$n-8\$ * `"."`: press the button labeled "\$4\$" Translating the rules described in the challenge into these codes leads to the groups `5567`, `.848`, `106.`, `8099` and `0132`, which are concatenated into a single lookup string. The purpose of the leading `"_"` is just to deal with the 1-indexed input. The input array \$a[\:]\$ is re-used to store both the labels that are pressed and their positions. For each line \$i\$, we store the label in \$a[i]\$ and its position in \$a[-i-1]\$. ### Commented ``` a => // a[] = input a.map(([d, b], // for each pair of displayed value d and buttons b i) => // at position i in a[]: a[i] = b[ // save the label in a[i] a[~i] = // save its position in a[-i-1] ( n = // n = action code taken from ... '_5567.848106.80990132' // ... our lookup string ... [i * 4 + d] // ... at position i * 4 + d ) > 3 ? // if n is greater than 3: n > 7 ? // if n is greater than 7: a[7 - n] // re-use the position used at line n - 8, // stored in a[-(n-8)-1], i.e. a[7-n] : // else: n - 4 // use the position n - 4 : // else: b.search(a[n] // look for the label used at line n || 4) // or look for '4' if a[n] is undefined, // which happens only when n is '.' ] // end of button lookup ) // end of map() ``` [Answer] # [Python 2](https://docs.python.org/2/), 415 375 351 317 299 273 265 bytes ``` a=[0]*5;x=input() for i,z in enumerate(x):j,q=z;exec'a[i]'+['=[q[j-1],j]',';k=a[0][1];a[i]=[4,q.index(4)+1]if j<2else[q[k-1],k]if j-3else[q[0],1]','=[4if j>3else a[j<2][0]if j<3else q[0]]','=[q[a[j>1][1]-1]]if j-2else[q[0]]','=a[6>>4-j&3];print[l[0]for l in a]'][i] ``` [Try it online!](https://tio.run/##PU9LboMwEN33FF7V0AxVDKSLUHOR0Sys1lEN1AFCJJrL0xlA2fl9/ab/m36uMV8WZ/FIb6dqtiH29ylJXy7XUQV4qBCVj/dfP7rJJ3N6bmCwj8rP/ks7DKQPqC0O2GSGoCENumqt4zI0VInBYgnDe4jffk7K9GAoXFTzmfvu5jnWSqxduazYuSOBkSJOCl@vvHLIKWJxzW@ceDfngKzXRn7lxq0vf/atHocfdV1mzWtBVT@GOGHHkpzZyZGONPHcZUHMQaGBEgrIiYD3K@QnMCVQ1HKFhUCzw4JH7/Bppn8 "Python 2 – Try It Online") -40 bytes by making everything ternary -24, -18, -10 by removing unnecessary code -16 by using (label,position) rather than (position,label) -4, -4 thanks to @Arnauld -26, -8 thanks to @Chas Brown Not quite as competitive as @Arnauld's solution... probably a bit naive as its basically just logic. Very happy with how this progressed, thanks everyone for the suggestions! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 74 bytes ``` Sθ≔∨⊖S¹η⊞υ§θηSθ≔§⟦⌕θ4η⁰η⟧⊖Sζ⊞υ§θζ⊞υ§⁺⮌υ⟦§S²4⟧⊖S⊞υ§S§⟦η⁰ζζ⟧⊖SSθ⊞υ§υ⌕1243S↑υ ``` [Try it online!](https://tio.run/##fVBNi8IwEL37K4aeJhBh83FaT4IseFIUT8WDtMEWulnNR5H@@ThVXHYlSj6YvHl5b2aq5uCqn0OX0tKeYtgG19ojntlsMve@PVpcOVyYyplvY4Op8S@LMQ6CTkPsdfQNRg7zsLS1ueB5hAl/ofqglV@trUdyoYtRicMH3XsOrz2JNuQNB5bB1130uDG9cd5gpM/lI/NPloNktyr27K15xuFJ57e1ezMD7ff95Mb07EHhbVKFkFoVHDJVURzwc3fiENksJaGVBAlKCg20pFD00lIJEHdQpGnfXQE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `buttons#1 display#1 buttons#2 ... display#5`. Explanation: ``` Sθ ``` Input the first buttons. ``` ≔∨⊖S¹η ``` Decrement the first display to make it 0-indexed, but if that results in zero, increment it again. Save the result for steps 2 and 4. ``` ⊞υ§θη ``` Save the appropriately indexed button in the predefined empty list. ``` Sθ ``` Input the second buttons. ``` ≔§⟦⌕θ4η⁰η⟧⊖Sζ ``` Make a list of four elements: the index of "4" in the buttons; the index of the first button; `0` (representing the button in first position); the index of the first button. Get the element corresponding to the (decremented) second display. Save the result for step 4. ``` ⊞υ§θζ ``` Add the appropriately indexed button to the list. ``` ⊞υ§⁺⮌υ⟦§S²4⟧⊖S ``` Input the third buttons and make a list of four elements: the two buttons so far in reverse order, the button at index 2 (i.e. third position), and `4`. Index this using the (decremented) third display. Add the result to the list. ``` ⊞υ§S§⟦η⁰ζζ⟧⊖S ``` Input the fourth buttons, and index them from a list of four elements: the position used for the first button, `0` (representing the first button), and the position used for the second button (twice), first indexed using the (decremented) fourth display. Add the result to the list. ``` Sθ ``` Input the fifth buttons. ``` ⊞υ§υ⌕1243S ``` Input the fifth display, find its index into the string `1243`, and index that into the list so far, adding the result to the list. ``` ↑υ ``` Output the result. ]
[Question] [ The [Māori language](https://en.wikipedia.org/wiki/M%C4%81ori_language) has quite simple pronouns. It uses a single word for he/she/they/etc (`ia`), and the words for "you" and "me" are `koe` and `au` respectively. There are also words for groups of exactly two people: * `tāua` - You and me (we, `au` and `koe`) * `māua` - Me and them (we, `au` and `ia`) * `rāua` - Them (third person plural - two of them, `ia` and `ia`) * `kōrua` - You two (`koe` and `koe`) And for three or more people: * `tātou` - All of you and me (we, `au` and multiple `koe`) * `mātou` - Me and all of them (we, `au` and multiple `ia`) * `rātou` - All of them (third person plural, multiple `ia`) * `koutou` - All of you (multiple `koe`) Your challenge is to take a list of `ia`, `koe` and `au` and return the correct pronoun. You may assume that there is at most one `au` and that `ia` and `koe` will never both be in the input. You may take input in any reasonable format - An array of `ia`, `koe` and `au` or three distinct values (within reason) representing those, an array of the counts of each word, a dictionary containing the counts of each word, space-separated words etc. When there is only one word, you should output that. Note that some of the outputs contain Unicode (`ā` and `ō`). You may output these as they are or as double letters - `aa` and `oo`. For example, `ia ia` becomes `rāua` as it is two `ia`. `au ia ia ia ia` becomes `mātou` as it is one `au` and more than two `ia`. `koe koe` becomes `kōrua`. # Testcases ``` ia -> ia koe -> koe koe au -> tāua ia ia -> rāua koe koe koe koe koe -> koutou ia ia au ia -> mātou ia ia ia ia ia ia ia -> rātou ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 94 bytes ``` a=>(g=r=>!!a.match(r))` `?'krtm'[h=g`u`*2+g`i`]+(g` .* `?h?'aatou':'outou':h?'aaua':'oorua'):a ``` [Try it online!](https://tio.run/##dYzLCoMwEEX3/Yq4SqLURZdC9ENKYQarMfUxEpP@fpraVSXCDBfOnTkvfOPWWrO660LPLvQqoKqFVlbVWYbljK4dhJUSGDR8tG7m90Fp8JDfCg0GHoXQwMo81kPDER15XnHye@7E4xeQjSkrDC0tG01dOZEWveAmUnk5wJG6NGXoE4VBdqZhhz37juK049f@TzwLHw "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 121 bytes ``` x=>x[1]?'koutou0tātou0rātou0mātou0kōrua0tāua0rāua0māua'.split(0)[g=y=>x.includes(y+''),g`au`+g`ia`*2+4*!x[2]]:x[0] ``` [Try it online!](https://tio.run/##XVBLDsIgEN33FHVVsIrVuNJUD9I0gVQkWFoaWgwuPYC30nPVAVyZMPOGeW8@cGN3NjZGDtO61xc@X8vZlSdXbetz1mo7aVtM76cHE6GL0H5exjLPgTfBd95nZByUnFCBK1E@oBORfaPshY/okWcZXgnKLM0FlYwud/l@uXDVrq4Prirq@ZhAOl2fUsmSVnMfAYSQWX8L4xLQRFmYG@h/C5V@@58YymNJXP@X/TuxI9CUGD4o1nC0ITk6l8DgjVjBxzS6H7XiRGmBrsjFx9KUYoznLw "JavaScript (Node.js) – Try It Online") Tabling n>2, "ia" exist, and "au" exist [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes ``` ≔№θ η¿¬ηθ«≔⁺∧№θia²№θauζ¿ζ⁺§rtmζaa¿⊖ηkou¦koor¿⊖ηtou¦ua ``` [Try it online!](https://tio.run/##dY67DsIwDEXn9iusTIlUFlamChYW1F@IWkOjtonIA6Eivj3EhUAXBi/X9xy77aVtjRxjrJ1TF833JmjPrxUwYKKCXuxKdQZ@Mp73QkBjFa1TiqNDeJTFh2vG4Hitu5VASTJs0/wyGZhIwZwEBXnnrHzz/qg7vHNm/cSoRUSyUHu5R8gBW4sTao/d6iU2mKTOvW9mLMun/nB@4WCNBUnQM0YZYDCYp4yb2/gC "Charcoal – Try It Online") Link is to verbose version of code. Output uses double vowels. Explanation: ``` ≔№θ η ``` Count the number of spaces in the input. (Note that due to Charcoal's input format autodetection, you need a trailing newline in the input for this to work.) ``` ¿¬ηθ« ``` If there are no spaces, then just print the input. ``` ≔⁺∧№θia²№θauζ ``` Count `2` if `ia` is present, plus `1` if a (assumed single) `au` is present. ``` ¿ζ⁺§rtmζaa ``` If either are present then output `taa`, `maa` or `raa` as appropriate, ... ``` ¿⊖ηkou¦koor ``` ... otherwise output `kou` or `koor` depending on the number of words. ``` ¿⊖ηtou¦ua ``` Output `tou` or `ua` depending on the number of words. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 124 bytes ``` lambda n:[n,'rmkt'[2*('k'in n)+('u'in n)]+['ou','oa'['a'in n]*2][[*n].count('k')<3]+['ua','tou'][len(n.split())>2]][' 'in n] ``` [Try it online!](https://tio.run/##XVDBbsMgDL3nK6xeHNKoh/QyVWt/hKLKaxIVJTGIgLTt5zMI6apNwtjwnt8z2C//MHx8s27pz9dlpOmjJeCT5BrdNHiUTVXigJqBxb7EkCu1l2gC1mgIJdJ6qapGSVmxOtxNYJ@6xPsxMQNFpo98JceOSz7MdtS@FOLSKCURcvui2d5m7@AMiKipGEyXAigUmiBfwL/ISKQkPNd/V5Ta7PDKKIqi@7Td3XftzQRvg09ukZjkPFEgcOs@RNQEmIhScmt6CkWR3jiI49bwVIsn@Na23N7wAjYbcSrAOh2/pU8cUUfXGfyjg22MpLjDOqviDojbFf412Hh6xpe4WH4A "Python 3.8 (pre-release) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~110~~ 79 bytes ``` ^(?=(.*au)?)(?=(?<1>.*ia)?){2}\w+ \w+ $#1aaua T`d`ktmr ua .* tou kaa kou uu oru ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP07D3lZDTyuxVNNeE8S0tzG009PKTARyq41qY8q1FYCYS0XZMDGxNJErJCElIbskt4irNFFBT4urJL@UKzsxkSsbSJeWcuUXlf7/nwnipoKwQmIpV2aiAkRAAQ1DZIBKQPIQNioCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Output uses double vowels as those accented characters aren't in Retina's default code page. Explanation: ``` ^(?=(.*au)?)(?=(?<1>.*ia)?){2}\w+ \w+ ``` See whether the input contains `au`, matching as `$#1`, plus add two further matches to `$#1` if the input contains `ia`. Also delete two words from the input (this fails if the input only contains one word). ``` $#1aaua ``` Replace the first two words with the count of matches suffixed with `aaua`. ``` T`d`ktmr ``` Replace the count with the appropriate letter. ``` ua .* tou ``` If there were more than two words then change the `ua` to `tou`. ``` kaa kou ``` `kaatou` should be `koutou`. ``` uu oru ``` But `kouua` should be `koorua`. [Answer] # [Ruby](https://www.ruby-lang.org/) `-apl`, 71 bytes ``` k=$F[2]?:koutou: :kōrua;$_=!/a/?k:(/k/??t:/u/??m:?r)+?ā+k[3,3]if$F[1] ``` [Try it online!](https://tio.run/##KypNqvz/P9tWxS3aKNbeKju/tCS/1ErBKvtob1FporVKvK2ifqK@fbaVhn62vr19iZV@KZDKtbIv0tS2P9KonR1trGMcm5kG1G8Y@/9/ZiJXdn4qV2IpiFIAUomlChAxBZB4ZiISTwGqCg1DFClANELYqOhffkFJZn5e8X/dxIIcAA "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~57 52 51 49~~ 47 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “mtr”;€⁾aa;“kou“koor”⁽ñỌ,ḥ;Lị““ua“tou”Ɗ Ṣḣ3ÇḢḊ? ``` A monadic Link accepting a list of lists of characters that yields a list of characters, the pronoun. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5zckqJHDXOtHzWtedS4LzHRGiiUnV8KJvNBMo8a9x7e@HB3j87DHUutfR7u7gZKAVFpIpAoASmce6yL6@HORQ93LDY@3P5wB5DRZf////9o9cxEdR0FFDKxFMqOBQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw5zckqJHDXOtHzWtedS4LzHRGiiUnV8KJvNBMo8a9x7e@HB3j87DHUutfR7u7gZKAVFpIpAoASmce6yL6@HORQ93LDY@3P5wB5DRZf//4e4tD3dsAhp6uB1IRP7/n5nIlZ2fCsIKiaVcmYkKEAEFNAyRASoByUPYqAgA "Jelly – Try It Online"). ### How? ``` “mtr”;€⁾aa;“kou“koor”... - Link 1: list of lists of characters, X “mtr” - "mtr" ⁾aa - "aa" ;€ - concatenate each -> ["maa", "taa", "raa"] “kou“koor” - ["kou", "koor"] ; - concatenate -> domain = ["maa", "taa", "raa", "kou", "koor"] ...⁽ñỌ,ḥ;Lị““ua“tou”Ɗ - Link 1 (continued) ⁽ñỌ - 7932 , - pair ḥ - hash X with a salt of 7932 and our domain (from above) Ɗ - last three links as a monad - f(X): L - length (2 or 3) ““ua“tou” - ["", "ua", "tou"] ị - index into ; - concatenate Ṣḣ3ÇḢḊ? - Main Link: list of lists of characters, I Ṣ - sort I ḣ3 - keep up to the first three ? - if... Ḋ - ...condition: dequeue (i.e. is length > 1 ?) Ç - ...then: call Link 1 Ḣ - ...else: head of I ``` ]
[Question] [ So you want to create a haiku, but you're not sure if it follows the syllable rules for a haiku. I couldn't be bothered to write a proper blurb like I usually do, so you'll have to make do with this. Let's get stuck right in. ## Finding a haiku out in the wild For the purposes of this challenge, we will be checking if the given poem satisfies these criteria: * There are three lines. * The first line has 5 syllables. * The second line has 7 syllables. * The third line has 5 syllables. Each line is composed of one or more words, separated by groups of spaces. These words are not necessarily valid English words. Each word is split up into syllables, and then those syllables are counted to get the total syllable count of the line. A syllable has either 2 or 3 parts to it: the beginning, the end, and possibly the middle. Each part is either a group of consonsants (also known as a consonant cluster, such as `s`, `sk` or `spl`) or a group of vowels (such as `i`, `ea` or `oui`). If the beginning is a group of consonants, the middle will be a group of vowels and the end will be a group of consonants. If the beginning is a group of vowels, the end will be a group of consonants and there will be no middle. For example, the word `example` is made up of three syllables, `ex`, `am` and `ple`. `ple` has no ending as it was cut short by the end of the word. As another example, the word `syllable` also has three syllables, `syll`, `abl` and `e`, which also has no ending. For one final example, the word `word` has one syllable, `word`, which ends with a group of consonants. ## The challenge Given a string, list of strings, list of lists or any other [reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) representing a poem with at least one line, determine if it meets the criteria of a haiku outlined above and return the result. You may return the result in any of these formats: * A truthy value if the poem is a haiku and a falsy one otherwise. * A falsy value if the poem is a haiku and a truthy one otherwise. * A value from a finite range of values specified in the submission if the poem is a haiku and a value from a mutually exclusive finite range of values also specified in the submission. You may also assume the poem contains no non-alphabetical characters, but you may not assume that it is entirely in uppercase or lowercase. For the purposes of this challenge, `Y` is a vowel. ## Test cases ### Truthy ``` This is a haiku Yes it truly is one See what I did man ``` --- ``` I am so tired of writing this already when can I stop this ``` --- ``` Writing another Of these horrific things Come on please ``` --- ``` Consonant only Counts as one syllable ghjk tgh knmb wrts vbc ``` ### Falsy ``` oh boy writing non haiku is so much easier ``` --- ``` This is so good on my poor dear brain ``` --- ``` The syllables do not match at least I do not think so I have not checked ``` --- ``` It does not really matter these test cases will help At least I think they will ``` --- ``` I am done here This is enough Goodbye ``` ## Scoring Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") The shortest answer will win Good luck to you all [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to Erik the Outgolfer (use a list of lines as input) ``` e€Øy0;ŒgP€ ḲLÐfÇ€ḣ8µ€ḣ4 ``` A monadic link taking a list of lists of characters (the lines) and returning a list of lists of lists of zeros and ones. Valid haiku will be length 3 and once any of the deepest lists that are a single zero are replaced by a single one the sum of the flattened lists will be 5, 7, and 5 respectively. The formation (whether *runs* of letters are consonants and only taking the first 8 words of each of up to only 4 lines) ensures there are only finite of each of the valid and invalid ranges. **[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMqDayPTkoPALK5Hu7Y5HN4QtrhdiDn4Y7FFoe2Qhgm////j1YKycgsVgACCJkIIjISM7NLgUwUqKTDpaAUmQpSlVkCJEqKSnMqFRQQWhXy81LBipwV4KA8I7EEyvSEC6ZkpsDZuYl5SrEA "Jelly – Try It Online")** or see the (even more confusing!) [test-suite](https://tio.run/##RVGxSgNBFOzzFY/DMoKFhWAlFhIQFBTCESw2dy@3a/Z2w96e4VqbtJIqva2VIESwMuRD4o@cs3vRwHHsvpmdN2/eI2vdtC3/PL9tVs3J@XZZ3OLc263frzcvk80Cl9369ez7ozuctpvFdrn7XA1726@IHqUp/mnbjpJ7qSrCJ0gKNa2TfpIyCp68q3UTEGsY1TtmmkvhaUC5yqkUJnnoj5IBiZIqS145zkG7mdDcKa9MQT4oC@1Y5A2QoWRDmTAQqLydRThKDPd8YayX7DoRnComaZ1TE5UFsikqQJe2ZDiimWZRcXxvJY1t89/WWHMcRwne4aysM0kgK0gH@n5gaAEsrA2uIVgGjzNrHeUsHI2dUGbPZ6oarcVYI5jcooHH@D6TeIA8gpGYSocEp1P0BThApE8cq5nkbIqAYmQeXEiFOsLBLoOcj5N3Y3uGYob5KporrUmyngG8ODTruoDdRMZhFTm2Bb4LK/tbLRtbF8HtFaYdN0jtFw "Jelly – Try It Online") --- Here is a much easier to use **~~32~~ 30 byte** version, simply outputting 1 or 0: ``` e€Øy0;ŒgP€SȯL$ ḲLÐfÇ€Sµ€⁼5,7,5 ``` [Try this one](https://tio.run/##y0rNyan8/z/1UdOawzMqDayPTkoPALKDT6z3UeF6uGOTz@EJaYfbQSKHtgLJR417THXMdUz///8frRSSkVmsAAQQMhFEZCRmZpcq6XApKEWmgkQzS4BESVFpTqWCAkKpQn5eKliRswIclGcklkCZnnDBlMwUODs3MU8pFgA "Jelly – Try It Online") or see its [test-suite](https://tio.run/##RVHBSgMxFLz7FY@lxwpeigdP4kEKBYUKpRQP6e7rJjablGxq2aNeepWe@hGCIAgKPVkK/kb7I@skrRZCCG8m8@bNe2Ctq7rm3fPrelmdXWwW@S3e3Z@3TuNk@/neWb@M1vNQ@f7AvXtatZrnzVa9nm8W269l72SzinCj38fdr@tBcidVSTiCpFDjadJM@oyCJ@@mugqINYxql5lmUnhqU6YyKoRJ7puDpE2ioNKSV44z0G5GNHPKK5OTD8pCOxZZBaQn2VAqDARKbycRjhK9A18Y6yW7vQheJZO0zqmRSgPZ5CWgK1swHNFEsyg5/reShrb6b2usOY2jBO9wVkxTSSArSAf6YWBoAcytDa4hWASPE2sdZSwcDZ1Q5sBnKiutxVAjmMyigcf4PpX4gDyCkZjKHglOx@gLsI1IHzlWU8npGAHFyDy4kAp1hIONBjkfJ9@P7RmKKeYraaa0Jsl6AvDy2GzfBewqMo6ryLAt8F1Y2d9q2dhpHtxeY9phhdR@AQ "Jelly – Try It Online"). [Answer] # JavaScript (ES6), ~~84~~ 75 bytes Takes input as a list of lists of words. Returns `true` for haiku or `false` for non-haiku. ``` a=>a.map(s=>(s.map(w=>w.match(/[aeiouy]+/gi))+'').split`,`.length)=='5,7,5' ``` ### Test cases ``` let f = a=>a.map(s=>(s.map(w=>w.match(/[aeiouy]+/gi))+'').split`,`.length)=='5,7,5' console.log('[Truthy]'); console.log(f([ ["This","is","a","haiku"], ["Yes","it","truly","is","one"], ["See","what","I","did","man"] ])); console.log(f([ ["I","am","so","tired"], ["of","writing","this","already"], ["when","can","I","stop","this"] ])); console.log(f([ ["Writing","another"], ["Of","these","horrific","things"], ["Come","on","please"] ])); console.log(f([ ["Consonant","only"], ["Counts","as","one","syllable"], ["ghjk","tgh","knmb","wrts","vbc"] ])); console.log('[Falsy]'); console.log(f([ ["oh","boy","writing","non","haiku","is","so","much","easier"] ])); console.log(f([ ["This","is"], ["so","good"], ["on","my"], ["poor","dear","brain"] ])); console.log(f([ ["The","syllables","do","not","match"], ["at","least","I","do","not","think","so"], ["I","have","not","checked"] ])); console.log(f([ ["It","does","not","really","matter"], ["these","test","cases","will","help"], ["At","least","I","think","they","will"] ])); console.log(f([ ["I","am","done","here"], ["This","is","enough"], ["Goodbye"] ])); ``` [Answer] # [Retina](https://github.com/m-ender/retina), 49 bytes ``` i`[aeiouy]+ 1 T`lL`2 2*12+ 3 [12]+ 3 %M`3 ^5¶7¶5$ ``` [Try it online!](https://tio.run/##K0otycxL/P8/MyE6MTUzv7QyVpvLkCskIccnwYjLSMvQSJvLmCva0CgWRKv6JhhzxZke2mZ@aJupyv//IRmZxQpAlKiQkZiZXcoVmQrkliiUFJXmVILE8/NSuYJTUxXKMxJLFDwVUjJTFHIT8wA "Retina – Try It Online") Outputs `1` for haiku,`0` for non-haiku. [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ ~~125~~ ~~120~~ 121 bytes ``` lambda s:[len(split('\s+',sub('[aeiouy][^aeiouy ]+','X ',t,0,I).strip()))for t in s.split('\n')]==[5,7,5] from re import* ``` [Try it online!](https://tio.run/##ZZFRa9wwDICf51@hNydbVsagDAr3MAot97SHFrpxvYITK2dzjhVsZVl@/U1JrtuVQiCOZH2SvvQTO4pfT@3m@RRMV1sD@WYXMBa5D54L/Zw/6SoPdaF3Bj0N0373sh5gLxn9E3TF1ZdqW15lTr4vyrJsKQGDj5CvXilRl/vNZnddfauu96pN1EFC8F1PiT@eLLZwV@TyRn3ok48M@fXQSvR8Vuqu0Fo/Op9Bnj/gjD8O6hfKJwOnIUxznCKqB0QYnWHYgvUWOhOlsDwDtmA6yATsE1r1o4UxefbxADyTTUho7KSeHEZoTBREZuqX5AXk6VxjIrHDNGPknREcpeRb38wF8ZDVLXUoM0Ef0GS8IJCDmqZ/zSPFz8tC8w4yXTc0DqTEY7ooOi@v5MKByCoBd5PqSYRbNAnqZHx8cx8hTyGYOogmS9KGRQc3TomdeaTF0RqfJz5Kb7UVtb9xiTUOmyPaS30s9wU2Z0VVEOsCZHGwCmAUZiO7Zhh9COAw9Or7/2ZrF7k7Lfn3y0FDVpIHCq1a5helC9TEPGJaqaOP6l4MQBgaoRFMNMi/W3Gnvw "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 63 + 1 (`-p`) = 64 bytes ``` $a[$.]=()=/([aeiouy]+|\b[^aeiouy ]+\b)\s*/ig}{$\="@a"eq" 5 7 5" ``` [Try it online!](https://tio.run/##Jci9CsIwFEDhvU9xCRlaS38cglPA1cFJF2kq3NKLDdYmNilS1Fc3VoSzfMfS2IsQOFY8r2WcyCKukLSZ5jp9qaY6/wF1qppEuVWhL@8nV5JtkdGdgYANCBbCsdMOlhA61NcpOtFCD36c@vn3zUDRgQgeHXrYQatbuOHwMdZrM7iQ7UVersuQ2S8 "Perl 5 – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~162~~ ... 115 bytes ``` import StdEnv,StdLib @t=[sum[max(sum(map hd(group[sum[1\\v<-:"AaEeIiOoUuYy"|c==v]\\c<-w])))1\\w<-l]\\l<-t]==[5,7,5] ``` Defines the function `@`, taking `[[[Char]]]` (list of list of words), and giving `Bool`. Returns `True` when the input is a haiku, `False` otherwise. [Try it online!](https://tio.run/##LY8/a8MwFMT3fAqRxTZYQ4ZQKBaktBkCgQ6hQ5E1PMuqo0R/jCXbNfSzV1UVT797d/eG40qACdq2oxJIgzRB6t4OHl18ezRTGXGWzebgCXWjphq@88hcQ4@ubd4NduxTsKvrqcLP2xc4ipN8tx/j57L94YRMrK55hWdWFEUszRVW0VEV9owQui@fyj0LFw@D3xB0QJTS7NUaZw0Yn7GSZtaoJWNR/Qej8S654NZQJLpFKWiUWIvd9XZPvu8S7kY3SczD@j81PHZZ@OVfCjoX8Okc3hYDWvLH8Rj@Bw "Clean – Try It Online") [Answer] ## Mathematica 119 Bytes Here is a version that conforms to the given rules for syllables: ``` Tr/@Map[Length@StringCases[#,("a"|"e"|"i"|"o"|"u"|"y")..]/. 0->1&,(s=StringSplit)/@s[ToLowerCase@#,"\n"],{2}]=={5,7,5}& ``` Here is an 83 byte version that actually counts syllables: ``` Tr/@Map[Length@WordData[#,"Hyphenation"]&,(s=StringSplit)/@s[#,"\n"],{2}]=={5,7,5}& ``` e.g. ``` %@"This is a haiku Yes it truly is one See what I did man" ``` returns `False` since the second line has six syllables rather than the required seven. ]
[Question] [ (This is part 1 in a two-part challenge.) Your task is to solve a Hexasweep puzzle. A Hexasweep puzzle is set out on a grid of diamonds arranged in hexagonal shapes, of which the board looks like a hexagon, like so: ``` _____ /\ \ _____/ X\____\_____ /\ \ / XX /\ \ /X \____\/____/X \____\ \ X/ XX /\ \ X/ / \/____/ \____\/____/ /\ \ / X /\ \ / \____\/____/ \____\ \ / XX /\ \ / XX / \/____/ \____\/____/ \ X/ / \/____/ ``` The above image is composed of 7 hexagons (21 diamonds), and is thus a Hexasweep puzzle of size 2. * If you want to expand it, cover the current Hexasweep puzzle with more hexagons (so that there are 19 hexagons - that will make a Hexasweep puzzle of size 3). * The same goes for the other direction - to make a Hexasweep puzzle of size 1, remove the outermost layer of hexagons (so that there's 1 hexagon). Each diamond can contain 0, 1 or 2 "bombs", with bombs depicted as `X` above. With bombs filled out, this is the **final solution**. Numbers are marked on "intersection points", to show how many bombs are on the diamonds which are touching those intersection points - the intersection points of this grid are shown below using `O`. ``` _____ /\ \ _____/ OO___\_____ /\ \ OO /\ \ / OO___OO___OO OO___\ \ OO OO OO OO / \/___OO OO___OO____/ /\ OO OO OO \ / OO___OO___OO OO___\ \ OO OO OO OO / \/____/ OO___\/____/ \ OO / \/____/ ``` As you can see, there are two "types" of intersection points - those with 3 diamonds touching it, and those with 6 (the one that are touching the edge of the board aren't counted): ``` _____ /\ XX\ /X OO___\ \ XOO / \/____/ /\ _____/X \_____ \ XX \ X/ / \____OO____/ / XX OO X \ /____/ \____\ \ X/ \/ ``` The two intersections would be marked with `4` and `8` respectively. In the original Hexasweep puzzle above, the intersection numbers would be: ``` 3 4 5 4 2 2 1 3 2 4 1 2 1 ``` Which would be condensed to: ``` 3,4,5,4,2,2,1,3,2,4,1,2,1 ``` Given an input in this "condensed form", you must output the original puzzle, in "condensed form" (see above). The solved image (the first one, with the crosses) - which would be formed from the puzzle - would be read from top to bottom, starting from the left: ``` 2,0,0,2,0,2,1,0,1,0,2,0,1,0,0,2,0,0,0,0,2 ``` That is now the "condensed form" of the puzzle. If there is more than 1 answer (as in the condensed form above), the output must be `N`. ### Examples: ``` 0,0,4,3,1,3,4,7,1,4,3,6,1 -> 0,0,0,0,1,0,0,2,0,0,0,2,0,1,0,1,2,0,0,2,2 (size 2 Hexasweep) 6 -> 2,2,2 (size 1 Hexasweep) 0,1,5,3,1,4,4,7,2,5,3,6,1 -> N (multiple solutions) ``` ### Specs: * Any delimiter for the "condensed form" as input are allowed (it doesn't have to be `,` separating the numbers). * You may output a list, or a string with any delimiter. * Your program must be generalised: it must be able to solve Hexasweep puzzles of any size (at least from size 1 to size 4). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest amount of bytes wins! [Answer] # Javascript (V8), 1509 bytes ``` V=>{S=Math.sqrt(V[L="length"])/3+1|0;C=(Y=Array)(3**(W=12*(S-1)||2))[F="fill"]``.map(c=>Y(G=3*S*(S-1)+1)[F]``.map(h=>[N=-1,N,N])) O=[];R=Y(4*S-3)[F]``.map(r=>[]);for(r=0,c=1,m=S,i=0;i<G;++r>=m&&(r=0,m+=++c>S?N:1))R[r*2+(X=Math.abs)(S-c)][P="push"](i++,N) R=R.map(r=>(r.pop(t=Y(((T=2*S-1)-r[L]+1)/2)[F](N)),t.concat(r,t)));I=R.flat()[K="filter"](Q=r=>r+1);J=[[m=1,0]] if(S>1){for(i=0;i<S-1;i++)J[P]([m+=3,0]);for(i=0;i<S-1;i++)J[P]([m-1,2],[m,0]);for(i=0;i<S-1;i++)J[P]([m-=3,0])}M=[] J[K](j=>(t=j[1],Y(j[0])[F]``[K](_=>M[P](t++%3)))) z=0;g=p=>{for(j=0;j<R[L];j++)if(p<(t=R[j][K](Q))[L]){a=R[b=j].indexOf(t[p]);break}else p-=t[L]} M=M.map((v,i)=>v?(v<2?(g(z-1),[[I[z-1],1],[I[z-1],2],[R[b-1][++a],0],[R[b-1][a],2],[R[b+1][a],0],[R[b+1][a],1]]):(g(z),[[I[z],0],[R[b-1][a-1],2],[R[b+1][a-1],1]])):(x=[0,1,2].map(d=>[I[z],d]),z++,x)) C.map((c,i)=>{r=-2;s=_=>[...i.toString(3).padStart(W,0).substr(r+=2,2).split``.map(n=>+n),N];for(j=0;j<S;c[j++]=s()) t=S-1;for(j=1;j<S;j++)c[++t]=s(),c[t+=j+S-1]=s();for(j=S-2;j>0;j--)c[++t]=s(),c[t+=j+S-1]=s();if(S>1)for(j=0;j<S;j++)c[++t]=s()}) C.map(c=>{q=1;l:while(c.find(h=>h[0]<0|h[1]<0|h[2]<0))for(j=0;j<M[L];j++){t=M[j];if(t[K](Z=v=>!(c[v[0]][v[1]]+1))[L]==1){if((s=V[j]-t.reduce(U=(a,v)=>a+(c[v[0]][v[1]]+1||1)-1,0))<0||s>2){q=0;break l};r=t.find(Z);c[r[0]][r[1]]=s}}; M.map((t,j)=>{if(t.reduce(U,0)!=V[j])q=0}) q&&O[P](c)});if(O[L]>1)return"N";O=O[p=0];E=[];for(i=0;i<T;i++){a=T-X(S-i-1);for(j=0;j<a;j++)E[P](O[p+j][0]);for(j=0;j<a;j++)E[P](O[p][1],O[p++][2])}return E} ``` Wow. This was not as fun as I expected it would be. This is by far not an optimal solution. It's hard to golf something this big. I think you could save a hundred bytes or so by brute forcing the answer instead. However, my goal wasn't to be super competitive (yet!), but instead to provide a baseline for other answers to work off of. Seeing as this challenge hasn't been answered in the four years since it was asked, it obviously took a few days. The strategy I ended up using was to generate a list of all possible values for the outer ring of hexagons, and repeatedly fill in any diamonds whose values can be inferred from the vertexes near them. If any contradictions are found, that starting value is ignored and the next one is analyzed. This likely costs a few bytes compared to brute forcing, but it means it can finish running before the inevitable heat death of the universe. It takes less than a second for size one, about half a minute for size two, and based on the time complexity somewhere in the span of a few weeks to a few months for size three (haven't tested yet). My computer doesn't actually have enough memory for attempting higher than size two (gives me `invalid array length`), but with enough time and memory it's theoretically possible to use this approach for puzzles with millions of hexagons. If anyone wants to use this to develop a shorter or faster solution, here's the pre-golfed version of my code (it's not very pretty, but it works): ``` var hexasweep = function(vertexes) { var size = Math.sqrt(vertexes.length) / 3 + 1 | 0; var configs = new Array(3 ** (2 * (6 * (size - 1) || 1))).fill(0).map(c => new Array(3 * size * (size - 1) + 1).fill(0).map(h => [-1, -1, -1])); var solutions = []; var reference_array = new Array(4 * size - 3).fill(0).map(r => []); for (let r = 0, c = 0, m = size, i = 0; i < 3 * size * (size - 1) + 1; i++) { reference_array[r * 2 + Math.abs(size - c - 1)].push(i, -1); if (++r >= m) { m += (++c >= size ? -1 : 1); r = 0; } } for (let t, r, i = 0; i < reference_array.length; i++) { r = reference_array[i]; r.pop(); t = new Array(((2 * size - 1) - r.length) / 2).fill(-1); reference_array[i] = t.concat(r, t); } var reference = reference_array.flat().filter(r => r + 1); var m = 1, length_map = []; length_map.push([m = 1, 0]); if (size > 1) { for (let i = 0; i < size - 1; i++) { length_map.push([m += 3, 0]); } for (let i = 0; i < size - 1; i++) { length_map.push([m - 1, 2], [m, 0]); } for (let i = 0; i < size - 1; i++) { length_map.push([m -= 3, 0]); } } var vertex_map = []; for (let t, i = 0; i < length_map.length; i++) { t = length_map[i][1]; for (let j = 0; j < length_map[i][0]; j++) { vertex_map.push(t++ % 3); } } for (let v, z = 0, b, a, g, i = 0; i < vertex_map.length; i++) { v = vertex_map[i]; g = p => { for (let t, j = 0; j < reference_array.length; j++) { if (p < (t = reference_array[j].filter(r => r + 1)).length) { b = j; a = reference_array[j].indexOf(t[p]); break; } else { p -= t.length; } } } if (v == 0) { vertex_map[i] = [0, 1, 2].map(d => [reference[z], d]); z++; } else if (v == 2) { g(z); vertex_map[i] = [[reference[z], 0], [reference_array[b - 1][a - 1], 2], [reference_array[b + 1][a - 1], 1]]; } else { g(z - 1); vertex_map[i] = [ [reference[z - 1], 1], [reference[z - 1], 2], [reference_array[b - 1][a + 1], 0], [reference_array[b - 1][a + 1], 2], [reference_array[b + 1][a + 1], 0], [reference_array[b + 1][a + 1], 1] ]; } } for (let r, s, t, c, i = 0; i < configs.length; i++) { c = configs[i]; r = -2; s = _ => (i.toString(3).padStart(2 * (6 * (size - 1) || 1), 0).substr(r += 2, 2)).split("").map(n => +n).concat(-1); for (let j = 0; j < size; j++) { c[j] = s(); } t = size - 1; for (let j = 1; j < size; j++) { c[++t] = s(); c[t += j + size - 1] = s(); } for (let j = size - 2; j >= 1; j--) { c[++t] = s(); c[t += j + size - 1] = s(); } if (size > 1) { for (let j = 0; j < size; j++) { c[++t] = s(); } } } // Validate each for (let c, i = 0; i < configs.length; i++) { c = configs[i]; (_ => { while (c.find(h => h[0] == -1 || h[1] == -1 || h[2] == -1)) { for (let t, r, s, j = 0; j < vertexes.length; j++) { t = vertex_map[j]; if (t.filter(v => !(c[v[0]][v[1]] + 1)).length == 1) { if ((s = vertexes[j] - t.reduce((a, v) => a + (c[v[0]][v[1]] + 1 || 1) - 1, 0)) < 0 || s > 2) { return; } r = t.find(v => !(c[v[0]][v[1]] + 1)); c[r[0]][r[1]] = s; } } } for (let j = 0; j < vertexes.length; j++) { if (vertex_map[j].reduce((a, v) => a + (c[v[0]][v[1]] + 1 || 1) - 1, 0) != vertexes[j]) return; } solutions.push(c); })(); } if (solutions.length > 1) return "N"; // Convert to output list format var solution = solutions[0]; var result = []; for (let p = 0, a, i = 0; i < 2 * size - 1; i++) { a = 2 * size - 1 - Math.abs(size - i - 1); for (let j = 0; j < a; j++) { result.push(solution[p + j][0]); } for (let j = 0; j < a; j++) { result.push(solution[p][1], solution[p++][2]); } } return result; }; ``` This challenge would actually be really fun as [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"): I think there are a lot of byte-expensive shortcuts that could really speed this up that I didn't have time to explore. Thank you for a fun challenge. ]
[Question] [ # Task Define a *simple regex* as a non-empty regular expression consisting only of * characters `0` and `1`, * grouping parentheses `(` and `)`, * one-or-more repetition quantifier `+`. Given a non-empty string of `0`s and `1`s, your program should find the shortest simple regex matching the **full** input string. (That is, when matching a simple regex, pretend it’s bookended by `^` and `$`.) If there are multiple shortest regexes, print any or all of them.) [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins. # Test cases ``` 1 -> 1 00 -> 00 or 0+ 010 -> 010 1110 -> 1+0 01010 -> 01010 0101010 -> 0(10)+ or (01)+0 011111 -> 01+ 10110110 -> (1+0)+ 01100110 -> (0110)+ or (01+0)+ 010010010 -> (010)+ 111100111 -> 1+001+ or 1+0+1+ 00000101010 -> 0+(10)+ or (0+1)+0 1010110001 -> 1(0+1+)+ or (1+0+)+1 ``` [Answer] ## JavaScript (ES6), ~~488~~ 341 bytes ``` s=>[s.replace(/(.)\1+/g,'$1+'),...[...Array(60)].map((_,i)=>`(${(i+4).toString(2).slice(1)})+`),...[...Array(1536)].map((_,i)=>`${i>>10?(i>>8&1)+(i&2?'+':''):''}(${i&1}${i&4?i>>4&1:i&16?'+':''}${i&8?''+(i>>7&1)+(i&64?i>>5&1:i&32?'+':''):''})+${i&512?(i>>8&1)+(i&2?'+':''):''}`)].filter(r=>s.match(`^${r}$`)).sort((a,b)=>a.length-b.length)[0] ``` Explanation: Since six regexes can express all possible binary words, and the longest two are nine characters long, it suffices to check those and all shorter regexes. One candidate is obviously the string with "run length encoding" (i.e. all digit runs replaced with appropriate `+`s), but also strings with one set of `()`s need to be checked. I generate 1596 such regexes (this includes duplicates and useless regexes but they'll just be eliminated) and test all 1597 to see which is the shortest match. The generated regexes fall into two types: `\(\d{2,5}\)\+` (60 regexes) and `(\d\+?)?\(\d[\d+]?(\d[\d+]?)?\)(\d\+?)?` (1536 regexes as I avoid generating regexes with both leading and trailing digit). [Answer] # Pyth, 20 bytes ``` hf.x}z:zT1Zy*4"()01+ ``` This takes approximately 30 seconds to run, so it needs to be run offline. Explanation: ``` hf.x}z:zT1Zy*4"()01+ Implicit: z is the input string. "()01+ "()01+" *4 Repeated 4 times y All subsequences in length order hf Output the first one such that :zT1 Form all regex matches of z with the candidate string }z Check if the input is one of the strings .x Z Discard errors ``` I'm not completely sure that every shortest string is a subsequence of "()01+" \* 4, but 4 can be increased to 9 at no byte cost if needed. [Answer] # Pyth - ~~31~~ ~~30~~ 29 bytes Brute force! Can probably golf the iterator a little. ``` f=+Yf.x:zjY"^$")Z^"10+()"T1Y ``` [Test Suite](http://pyth.herokuapp.com/?code=+f%3D%2BYf.x%3AzjY%22%5E%24%22%29Z%5E%2210%2B%28%29%22T1Y&test_suite=1&test_suite_input=1%0A00%0A010%0A1110%0A01010%0A0101010%0A011111&debug=0). [Answer] # Ruby, 109 bytes It's the boring brute force approach. Works because no regex ever need be longer than 9 characters (as Neil notes) and no individual character needs to be repeated more than 4 times (trying it with `'01()+'.chars*9` made my CPU unhappy). ``` 10.times{|i|('01()+'.chars*4).combination(i).map{|s|begin /^#{s*''}$/=~$*[0]&&[puts(s*''),exit] rescue end}} ``` ``` $ for word in `grep -Po '^\S+' test_cases.txt`; do nice -n20 ruby sre.rb $word; done 1 0+ 010 1+0 01010 0(10)+ 01+ (1+0)+ (01+0)+ (010)+ 1+0+1+ 0+(10)+ 1(0+1+)+ ``` [Answer] # Python 3, 186 bytes I'm investigating whether there is an approach to this problem besides brute-forcing, but here is a Python brute-force solution for now. ``` import re,itertools def a(b): for z in range(10): for i in itertools.combinations("01()+"*4,z): j=''.join(i) try: if re.fullmatch(j,b)and len(j)<=len(b):return j except:1 ``` ]
[Question] [ Well, turns out [Doorknob's](https://codegolf.stackexchange.com/users/3808/doorknob) username on GitHub, Reddit, and other sites is [KeyboardFire](https://github.com/KeyboardFire). That gives me an idea... ## The task You work at KeyboardFire Inc., a company that makes special keyboards. And, by "special", I mean that, whenever you press a key, something in your house lights on fire! With the new KeyboardFire Doorknob series, the objects that light on fire are doorknobs. *However*, because of stupid government regulations, your users need to know which doorknobs in their house wil light on fire. Consider this ASCII art of a portion of a QWERTY keyboard: ``` 1|2|3|4|5|6|7|8|9|0 q|w|e|r|t|y|u|i|o|p a|s|d|f|g|h|j|k|l z|x|c|v|b|n|m ``` (The `|`'s represent the boundaries between keys.) We can treat this exact ASCII drawing as a "graph" of sorts, where each character in the range `[a-z0-9]` has an x (horizontal) and y (vertical) index, where `(0,0)` is `1`. For instance, the letter `d` has the coordinates `(2,6)` (pipes and spaces are included in the coordinate calculation). Now let's think about each user's house. Every house can be drawn top-down view as a 20x4 ASCII art (in this world where it's legal to sell destructive keyboards, every house is the same size). We can use `D`'s to mark the positions of each doorknob in the house. Here's an example: ``` D D D D D D D ``` We'll call this the "house map". (Yes, that's a lot of doorknobs!) Pressing any key will light the nearest doorknob on fire. For instance, if we take the previous coordinates of the letter `d`, the nearest doorknob (by Manhattan distance) is at the coordinates `(1,4)`. This is the doorknob that will light on fire when the letter `d` is hit. If we were to mark the flaming doorknob with an `F`, the result would be: ``` D D D D F D D ``` ## The specs Your program will take two inputs: * A string that matches the pattern `[a-z0-9]+`. * A house map. This can be a string, a list of strings, or something equivalent. You need to go through each letter of the string and light the respective doorknob on fire (change its letter to an `F`). If the nearest doorknob is already on fire, leave it as-is. If there is more than 1 doorknob that could be lit on fire using the this method, you can light whichever one you want. After the whole string is processed in this manner, you need to print the resulting house map. Code-golf, so shortest program wins. Standard loopholes banned as usual. ## Example String: ``` helloworld123 ``` House map: ``` D D D D D D D ``` Possible results: ``` F F F D F D F ``` Or: ``` F D F D F D F ``` Or: ``` F F D D F F F ``` Or: ``` F D D D F F F ``` **EDIT:** Uh...is there a reason I have one answer, even with a +50 bounty? If you find the directions complicated/vague, I'd be glad if you posted in the comments or something...or of I'm doing anything wrong... **EDIT 2:** Bounty expires in under a day! Post something else! Please! PLEASE!!!! :( [Answer] ## Ruby, 229 bytes ``` ->s,m{c=m.flat_map.with_index{|x,i|x.size.times.select{|j|x[j]==?D}.map{|y|[i,y]}} s.chars{|h|x='1234567890qwertyuiop*asdfghjkl*zxcvbnm'.index h x,y=(x%10)*2,x/10 a,b=c.min_by{|a,b|(y-a).abs+((y%2>0?x+1:x)-b).abs} m[a][b]='F'} m} ``` Not very good, but I just *had* to get the first answer in. Slightly ungolfed / commented version: ``` #!/usr/bin/ruby f = -> s, m { # get knob coords c = m.flat_map.with_index {|x, i| x.size.times.select{|j| x[j] == ?D }.map{|y| [i, y] } } # for each char in the string s.chars {|h| # note the asterisks to correct for offsets x = '1234567890qwertyuiop*asdfghjkl*zxcvbnm'.index h # get un-"staggered" x and y coords x, y = (x % 10) * 2, x / 10 # add one to x for every other row to fit keyboard x += 1 if y % 2 > 0 # find closest knob by Manhattan distance a, b = c.min_by{|a, b| (y - a).abs + (x - b).abs } # LIGHT IT ON FIRE! m[a][b] = 'F' } # return new map m } puts f['helloworld123', ['D D D D', ' D', '', ' D D']] ``` [Answer] # JavaScript (ES6), 204 bytes ``` (s,h)=>[...s].map(c=>(o="1234567890qwertyuiopasdfghjkl_zxcvbnm".search(c),y=o/10|0,x=o%10*2+y,n=a=Math.abs,h.map((k,i)=>k.match(/\s/)||(d=a(x-i%21)+a(y-i/21|0))>n||(n=d,p=i)),h[p]="F"),h=[...h])&&h.join`` ``` Fine, I'll answer it. ;) ## Explanation ``` (s,h)=> [...s].map(c=>( // iterate through each character of the input // Get X and Y coordinates of the character input o="1234567890qwertyuiopasdfghjkl_zxcvbnm".search(c), y=o/10|0, x=o%10*2+y, // Find the nearest doorknob n= // n = Manhattan distance to nearest doorknob a=Math.abs, h.map((k,i)=> // iterate through each character of the house k.match(/\s/)|| // do not check distance to whitespace characters (d=a(x-i%21)+a(y-i/21|0))>n|| // d = distance to the current doorknob (n=d, // set the nearest doorknob to this one p=i) // p = position of the doorknob ), h[p]="F" // update the doorknob to "F" in the house string ),h=[...h])&&h.join`` // return the house map as a string ``` ## Test ``` <input type="text" id="input" value="helloworld123" /><br /> <textarea id="house" rows="4" cols="20">D D D D D D D </textarea><br /> <button onclick='result.innerHTML=( (s,h)=>[...s].map(c=>(o="1234567890qwertyuiopasdfghjkl_zxcvbnm".search(c),y=o/10|0,x=o%10*2+y,n=a=Math.abs,h.map((k,i)=>k.match(/\s/)||(d=a(x-i%21)+a(y-i/21|0))>n||(n=d,p=i)),h[p]="F"),h=[...h])&&h.join`` )(input.value,house.value)'>Go</button> <pre id="result"></pre> ``` ]
[Question] [ ## Objective Write a routine that accepts a string of printable ASCII characters, *s*, and returns a string containing the same characters as *s*, reordered so that no two-character substring appears more than once. The program must process all benchmark strings (see below) in under one minute each on a [modern computer](http://www.iit.edu/ots/computer_vendor_info.shtml). I will also award a special bonus of **50 rep** to the lowest scoring answer that processes *any* valid 30-character string in under one minute. For example, given the input `Mississippi`, a valid output would be `issiMspiips` (no two-character substrings appear twice), while an invalid output would be `ipMsispiiss` (since the substring `is` appears twice). The routine may take the form of: * a complete program reading from `stdin` (or equivalent) or the command line, and outputting to `stdout` (or equivalent) * a function accepting a single string argument and returning a string You may assume that the input string always admits at least one valid output. ## The Challenge Your routine must comprise 5 or more lines of code separated by newlines. Empty lines (which includes lines containing only whitespace) are ignored in all contexts and do not count towards total line count. Swapping any two lines in your source code **must** produce a fatal error. By "fatal error", we refer to any of the following conditions: * the source code fails to compile, with the compiler/interpreter declaring a fatal error * the routine aborts with a runtime fatal error or an unhandled runtime exception * the routine is forced into an abrupt, abnormal program termination that produces no output of any kind except for a possible error message and/or stack dump **Alternatively**, contiguous blocks of code containing no newline characters may be used in place of lines. These blocks should each be displayed on their own line in the source file, with the understanding that newlines are stripped out before the source code is compiled/interpreted. For example, the code ``` aaaa bbbb cccc ``` would condense to ``` aaaabbbbcccc ``` before being evaluated. In this mode, the fatal error condition applies to swapping any two code blocks (and thus to swapping lines in the source code before newlines are stripped out). Hence in the above example the routines `aaaaccccbbbb`, `bbbbaaaacccc`, and `ccccbbbbaaaa` must all produce fatal errors, either at compiletime or runtime. Submissions using this alternative mode should declare its use. ## Scoring Let *n* be the number of non-empty textlines in your source file, with *n* ≥ 5. Let *c* be the number of bytes comprised by the **longest textline** (by byte length) in your source file, not counting any trailing newline. A submission's score is given by *c*(*n* + 10). The submission with the lowest score is the winner. Best of luck. ;) ## Benchmark Strings ``` Abracadabra Alacazam Is Miss. Mississauga Missing? Ask Alaska's Alaskans GGGGAAAATTTTCCCCgggaaatttccc A Man A Plan A Canal Panama ``` [Answer] # PHP, score = 289 (17×(7+10)) PHP's built-in functions make it quite easy to do this badly. The following code just shuffles the string until a valid result is obtained: ``` function f($s){ while(preg_match( '/(..).*?\1/',$s) +preg_match('/(.' .')\1\1/',$s))$s= str_shuffle( $s);return $s;} ``` --- ## Benchmarks Average and maximum execution times calculated using the following code: ``` $s = 'Mississippi'; $t_total = 0; $t_max = 0; for ($i=0; $i<10; $i++) { $t0 = microtime(true); echo f($s); $t = microtime(true) - $t0; printf(" %10.7f\n",$t); $t_total += $t; if ($t > $t_max) $t_max = $t; } printf("Avg: %10.7f secs; Max: %10.7f secs\n",$t_total/$i, $t_max); ``` **Results:** * Mississippi: Avg: 0.0002460 secs; Max: 0.0005491 secs * Anticonstitutionnellement: Avg: 0.0001470 secs; Max: 0.0002971 secs * Pneumonoultramicroscopicsilicovolcanoconiosis: Avg: 0.0587177 secs; Max: 0.1668079 secs * Donaudampfschiffahrtselektrizitatenhauptbetriebswerkbauunterbeamtengesellschaft\*: Avg: 9.5642390 secs; Max: 34.9904099 secs * baaacadaeafbbcbdbebfccdcecfdde†: Avg: 5.0858626 secs; Max: 9.8927171 secs \* I changed `ä` to `a` to avoid multi-byte issues † This was the hardest 30-character string I could come up with. It's actually the first 30 characters of the [De Bruijn sequence](http://en.wikipedia.org/wiki/De_Bruijn_sequence#Algorithm) for *k*='abcdef' and *n*=2, with the first 'b' moved to avoid an instant match. [Answer] ## Dyalog APL (11(5+10)=165) ``` f←{a←{⍴⍵} b←a⌸2,/⍵ c←b⊢⍵[?⍨a⍵] 1∨.≠b:∇c⋄⍵ } ``` Proof: * Lines 1 and 5 bound the function. Swapping any line for those would result in `⍵` occurring outside of a function, which is a `SYNTAX ERROR`. * Line 2 defines `b`, so it cannot be swapped for lines `3` or `4`, which depend on `b`. There would be a `VALUE ERROR`. (And it obviously can't be swapped with `1` or `5` either.) * Line 3 defines `c`, so it cannot be swapped for line `4`, which depends on `c`. (And we've already proven no other line can be swapped with line `3`.) * Line 4 depends on the variables from lines 2 and 3 and must therefore be last. [Answer] ## APL(Dyalog), 6(5+10) = 90 ``` {1∧.= +/∘.≡⍨ 2,/⍵:⍵ ⋄∇⍵[ ?⍨⍴⍵]} ``` I'm using the alternative, so: ``` {1∧.=+/∘.≡⍨2,/⍵:⍵⋄∇⍵[?⍨⍴⍵]} ``` This is the same old algorithm. --- **Explanation** `2,/⍵` gives an array of character pairs in the input string `+/∘.≡⍨` generates a numerical array of how many pairs does each pair equal (including itself) `1∧.=` checks if each element of that array equals 1, and logical AND the results together `:⍵` If that is true (`1`), return the input string `∇⍵[?⍨⍴⍵]` else scramble the input string and do a recursive call --- **Swapping** If line 1 is swapped with line 2, then you end up with `+/∘.≡⍨{...}` which is just a mess of functions and operators that gives `SYNTAX ERROR`. If line 1 is swapped with line 3 or 4, then you have `⍵` outside of a function definition, and that's a `SYNTAX ERROR`. If line 1 is swapped with line 5, unbalanced braces alone would cause `SYNTAX ERROR`, so don't worry about the other 4 syntax errors. If line 5 is swapped with line 2/3/4, again you have `⍵` outside of a function definition.(`SYNTAX ERROR`) If line 2 is swapped with line 3, you end up with `1∧.=2,/⍵:⍵`. This syntax is called a guard (think of it as a conditional). The guard condition must evaluate to `0` or `1` or a 1-element array of `0` or `1`. Here, it evaluates to something more complex than that (a scalar containing a 2-element array). So this is a `DOMAIN ERROR`. If line 2 is swapped with line 4, you get the statement `1∧.=`, which attempts to apply the function `∧.=` without the required left argument. (`SYNTAX ERROR`). If line 3 is swapped with line 4, again you get a mess of functions and operators (`1∧.=+/∘.≡⍨`) so you get `SYNTAX ERROR`. --- **Benchmarks** (numbers in milliseconds) ``` Abracadabra Alacazam 11 1 3 5 2 Avg: 4.4 Is Miss. Mississauga Missing? 1260 2000 222 117 111 Avg: 742 Ask Alaska's Alaskans 7 2 3 3 4 Avg: 3.8 GGGGAAAATTTTCCCCgggaaatttccc 31 15 24 13 11 Avg: 18.8 A Man A Plan A Canal Panama 377 2562 23 301 49 Avg: 662.4 ``` --- I am still thinking about different splittings. Also I have a deterministic, systematic way of doing the task. I just can't make it into an algorithm (take away the creative part of "making the numbers right") and can't make sure it works every time. [Answer] # Haskell, 129 = 3x(33 + 10) this uses the alternative mode. ``` imp ort Da ta. Lis t;a %[] =[[ ]]; a%s =[x :j| x<- s,n ot$ isI nfi xOf [la st a,x ]a, j<- (a+ +[x ])% (s\ \[x ])] ;g s=[ ]%s !!0 ``` or in a readable form: ``` import Data.List a%[]=[[]] a%s=[x:j|x<-s,not$isInfixOf[last a,x]a,j<-(a++[x])%(s\\[x])] g s=[]%s!!0 ``` Haskell is a very strict language. for example, the `import` must come first; the definitions of `s` must come together; all the types must agree and there is no way to cast between them, and so forth. this leads to having a non-fatal error almost impossible. in fact, having a runtime fatal error is too almost near impossible. note that if `g` is a valid function but has an the wrong type (any type different then `[a]->[a]` or `String -> String` and the like) than this is a fatal error because it's impossible to apply `g` to the inputs. outputs: ``` Abracadabar Alaazcma Is Miss. iMsiasusgsa sMniig?s Ask Alasak's lAaankss GGAGTGCAATACTTCCggagtaacttcc A Man AP la nAC aalnnaPama ``` ]
[Question] [ Imagine a countable infinite amount of empty rooms. When an infinite amount of guests come, they occupy the 1st, 3rd, 5th...(all odd) empty rooms. Therefore there's always an infinite amount of empty rooms, and occupied guests needn't move when new guests come. ``` - - - - - - - - - - - - - - - - - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 1 2 1 - 1 2 1 - 1 2 1 - 1 2 1 - 1 ``` Same group of guests would leave together, so if group 1 leave, it results in ``` - 2 - - - 2 - - - 2 - - - 2 - - - ``` Notice that some rooms turn empty, so if another group of infinite guests come, it results in ``` 3 2 - 3 - 2 3 - 3 2 - 3 - 2 3 - 3 ``` Now room 1,2,4,6,7,... are occupied while 3,5,8,... are empty. # Input Given a list of moves(aka. some group join or some group leave). All join requests are labeled 1,2,3,... in order. You can also choose to not read the joining label or not read join/leave value. # Output The shortest repeating pattern of occupied/empty. # Test cases ``` [] => [0] [+1] => [1,0] [+1,+2] => [1,1,1,0] [+1,+2,-1] => [0,1,0,0] [+1,+2,-1,+3] => [1,1,0,1,0,1,1,0] [+1,-1] => [0] ``` Shortest code wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` N;`⁹¬Tm2Ʋ¦A¬ẹ¦ʋƒ0ṠŒṖEƇḢḢ ``` A full program\* that accepts the register list and prints a Jelly representation of the pattern list. \* Only a full program to handle specifically `[] => [0]` for which the monadic Link would yield the integer `0` **[Try it online!](https://tio.run/##y0rNyan8/9/POuFR485Da0JyjY5tOrTM8dCah7t2Hlp2qvvYJIOHOxccnfRw5zTXY@0PdywCov///0drG@poG@noAknjWAA "Jelly – Try It Online")** Replacing `ŒṖ` with `sJ$` will be faster if you want to [try slightly longer inputs](https://tio.run/##y0rNyan8/9/POuFR485Da0JyjY5tOrTM8dCah7t2Hlp2qvvYJIOHOxcUe6m4Hmt/uGMREP3//z/aUMdIR9dQx1hH10jHRMdUx0xHF8g21dE1iwUA "Jelly – Try It Online"). ### How? The idea is to process the *moves* in turn maintaining a prefix that starts at `[0]` and doubles in length at each *move* either occupying every other empty room with a copy of *move* or removing all occurrences of the negative of *move*. Once this is done we can then find the shortest prefix that repeats to give the same. Actually, the implementation is a little more convoluted - rather than the "either or" above, we process negated values of the *moves*, always add these to every other unoccupied room, take absolute values and then always remove all occurrences of the negated *move* from all rooms. This saves some precious bytes. ``` N;`⁹¬Tm2Ʋ¦A¬ẹ¦ʋƒ0ṠŒṖEƇḢḢ - Main Link: list of moves, Moves N - negate {Moves} (vectorises) ƒ0 - start with 0 and reduce {that} by: ʋ - last four links as a dyad - f(Rooms, -Move) ;` - {Rooms} concatenate {Rooms} -> R2 ¦ - sparse application... Ʋ - ...to indices: last four links as a monad - f(R2): ¬ - logical NOT {R2} T - truthy indices of {that} -> I 2 - two m - {I} modulo-slice {2 -> indices of every other empty room ⁹ - ...apply: set to chain's right argument = -Move A - absolute value {that} (vectorises) ¦ - sparse application... ẹ - ...to indices: indices of {-Move} ¬ - ...apply: logical NOT Ṡ - signs {that} -> occupied or not indicators ŒṖ - partitions of {that} Ƈ - keep those {patitions} for which: E - all equal? -> repetitive partitions Ḣ - head {that} -> shortest repetitive partition Ḣ - head {that} -> shortest possible prefix ``` [Answer] # JavaScript (ES6), 100 bytes Returns a comma-separated binary string. ``` a=>/(.*?)(,\1)*$/.exec(a.reduce((b,x)=>[...b,...b].map(q=v=>x<0|v?v+x&&v:q^=x),[0]).map(x=>+!!x))[1] ``` [Try it online!](https://tio.run/##fc9LDoIwEAbgvaeAxJAOLYXqzlg4CNak1GI0yFObLrw7CtFoiNjJzOqbf9KzNLJT7am@BmV10H3Oe8njEFE/AUR2DPxlSLXVCkna6sNNaYQyYoHHKaU0I8MQ9CJr1HDDY7uN7iYx2Hqe2TR7boGkkYARWB5j17UAKRO9qsquKjQtqiPKUSqczwNwwtB5ri0mCDMxRYz8YgSvxIQNNUNJMOa@zw7wDyV4Lb5So1fPpAdMTD7VPwA "JavaScript (Node.js) – Try It Online") [99 bytes](https://tio.run/##fc9LDoIwEAbgvadgYUiHlpbqzlg4CNakQDEa5KlNF94dgWg0RJxJu@k3fzMXZVSXtuf65pdVpvtc9EqEDFEvAkQOHLw1o9rqFCna6uyeaoQSYkGEMaU0IeMl6VXVqBFGhHYfPExksHVds2uOwgKJAwkTsMMzswAxl31alV1VaFpUJ5SjWDqfAnAYc4ap1QxhLueIk1@M4I2csbEXKPGn3Pe3I/xDCd7Kr9TgdRbSfS5nS/VP) if we use `NaN` for unoccupied ### Commented ``` a => // a[] = input array /(.*?)(,\1)*$/ // a regular expression that looks for the shortest // prefix which, when repeated a whole number of // times with a leading comma, allows to reach the // end of the string .exec( // apply this to: a.reduce((b, x) => // for each element x in a[], // using the array b[] as the accumulator: [...b, ...b] // append b[] to itself .map(q = // initialize q to a NaN'ish value v => // for each element v in the resulting array: x < 0 | v ? // if x is negative or v is not 0: v + x && v // append 0 if v = -x, or v otherwise : // else: q ^= x // toggle q between 0 and x and append that ), // end of map() [0] // initialize the accumulator to [0] ) // end of reduce() .map(x => +!!x) // update each value to either 0 or 1 // implicit coercion to a string )[1] // end of exec(); return the prefix ``` [Answer] # [Python 3](https://docs.python.org/3/), 223 202 bytes Oh boy. Cool challenge, cant wait to see what everyone can do! slowly chipping away I guess... ``` def f(g,h=[0]): for q in g: if[q]<h:h=[w*(w-q)for w in h];continue h=h+h;p=1 for i,w in enumerate(h): if w<1:h[i]=p*q;p=1-p while h==h[:len(h)//2]*2:h=h[:len(h)//2] return[1-(i<1)for i in h] ``` [Try it online!](https://tio.run/##ZY7NDsIgEITvfYo9QqVR6q2WJyEcjIK7iVJKaIhPX0Fj4s9tZ@bb2Q33hJPfr@vZOnDsIlDpneFDA26KMAN5uBQB5PRsRhxKnFuWu5nXPNcczeE0@UR@sQVEhRs8BCXLXBEST8j65WbjMVmGtbwWQh7lgJqMCu1cN7rQQEa62lKiUA9X6wu93fam7cvhL6eBaNMSvZYdo1E@v6HXN2uI5BNzjHHOm7fQ0nwoJkXPf7SQ/47Y/3iVWR8 "Python 3 – Try It Online") # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 215 195 bytes stealing Ajax1234's walrus operator while loop o7 ``` def f(g,h=[0]): for q in g: if[q]<h:h=[w*(w-q)for w in h];continue h=h+h;p=1 for i,w in enumerate(h): if w<1:h[i]=p*q;p=1-p while h==(k:=h[:len(h)//2])*2:h=k return[1-(i<1)for i in h] ``` [Try it online!](https://tio.run/##ZU7NjsIgEL73KeY4dGlc6sVgeRLCweyCQ1RKCQ3x6StoTDbubb7f@eI90xz2h5i27dc6cHjmpPS3YbIDNydYwAc4VwDe6cVMJKtceizDwppemk7m@DOH7MNqq5EUfdExKlHvZvH8abJhvdl0yhaplbdCKJOQpL1RsV9aYogdFPJXW0sUXqQiLa821MRuNxrWj/X7pYNk85qCFgP6STxn@NeMLSYfMjpExlj3BlqYPwgFH9kH5uI/w/cfXPNsDw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` ⊞υ⁰Fθ¿‹ι⁰UMυ∧⁺ικκ«≔⁺υυυFΦ⌕Aυ⁰﹪λ²§≔υκι»≔⭆υ¬¬ιηW⁼ηײ÷η²≔÷η²ηη ``` [Try it online!](https://tio.run/##XY7NasMwEITP8VPscUUUaN2jT6Y/EGiKob2FHESkxEvWUmNJaaH02d1V3F56GK3YGX2jfW/GfTA8TV2OPWYNN6qpDmEEPCugA@CzixGp7BVszPt9GAbjbUm2MjrOV/ekilQDjqODr2rRxkhHP/uSzaqoqRZX9BNxcqMMb1vmuVXDJtjMAVlDraRsJrRp7a37LJmTBhLEd/XLfk0j@aP8qZgvIWERyVMNveQ@emIH@HjOhiP2Gt5ocBFrDWufHuhC1pVt6forw3/ODOqkJqHcpmm7Xd7qZa1Xct7tdtPqwj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⁰ ``` Start with one empty room. ``` Fθ ``` Loop over the input values. ``` ¿‹ι⁰ ``` If it is negative, then... ``` UMυ∧⁺ικκ« ``` Discard those values whose sum is zero, otherwise: ``` ≔⁺υυυ ``` Duplicate the list. ``` FΦ⌕Aυ⁰﹪λ² ``` Loop over alternate indices of the empty rooms. (Filtering is golfier than slicing alternate indices.) ``` §≔υκι ``` Fill the room at this index. ``` »≔⭆υ¬¬ιη ``` Convert the rooms to a binary string of occupancy. ``` W⁼ηײ÷η² ``` While the string equals half of itself repeated twice, ... ``` ≔÷η²η ``` ... halve the length of the string. ``` η ``` Output the final string. [Answer] # Python3, 227 bytes ``` def f(m): h=[0]*(2**sum(i>0for i in m)) for i in m: if i<0:h=[[0,l][l!=-i]for l in h] else: k=1 for j,a in enumerate(h):h[j]=[a,i][k%2 and 0==a];k+=a==0 while h==(k:=h[:len(h)//2])*2:h=k return[int(i>0)for i in h] ``` [Try it online!](https://tio.run/##bY/BbsMgEETv/ortoRLYRMHkEtFufwTtASkgiDGxiK2qX@9CD6mU9rSamTfS7PK1hls@nZey7xfnwbOZ6w4CGkk9U31/32YWP6S/FYgQM8ycd/CrKgvRQ3yXunaMFIlMesFDpMakxgSqjEt311iYcGynpVdhW@7yNrtiV8cC18FcCY0Vkcz0qsDmC0hES2/TgBZRdvAZYnJ1ILJJYzA6uVyLx6Mi3qs6YuqguHUr2cS8tun8sTbQvpTmemao/vEQw/gkxaD@OuIw/muK4fTs/5D7Nw) ]
[Question] [ We're graduating to a full site soon, and there's only one thing left to do before graduation: pull a senior prank! I think we should do a variation on the classic "fill a hallway with cups of water" gag. ## Challenge Your program will read in text and output that text, covered in upside-down cups of water. An upside-down cup of water looks like this: `/~\` These cups can only be placed in whitespace in the input, and can only be placed so that all three characters of the cup are directly above a non-whitespace character (otherwise the water would spill out!). Cups cannot be stacked on top of other cups. Cups must be placed in every available opening, and it is assumed that every input is surrounded by an infinite field of whitespace. You may assume that the input is padded to a rectangle with spaces. We need to pull the prank off quickly and without anyone noticing, so fewest bytes in each language wins. ## Test Cases Input: ``` ____________________________________________ / ___ / ___ / ______/ ________/ / /__/ / /__/ / / / /_______ / _______/ _______/ / / //__ / / / / / / /_____/ /___/ / /___/ /___/ /_________/___________/ ``` Output: ``` /~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\ ____________________________________________ / ___ / ___ / ______/ ________/ / /__//~\/ /__//~\/ / / /_______ / _______/ _______/ //~\ / //__ / //~\/ //~\/ //~\/_____//~\/___//~\/ /___/ /___/ /_________/___________/ ``` Input: ``` L LOL ROFL:ROFL:LOL:ROFL:ROFL L\\ ____I____ ======== | |[\ \___O==___) ___I_I__/ ``` Output: ``` L /~\/~\/~\/~\/~\/~\/~\ LOL ROFL:ROFL:LOL:ROFL:ROFL L\\/~\/~\ ____I____ ========/~\ | |[\ \___O==___) ___I_I__/ ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), 41 bytes Byte count assumes ISO 8859-1 encoding. ``` (?<=(.)*)(?=.*¶(?>(?<-1>.)*)\S{3}) /~\ ``` Note that the first line has three trailing spaces. Requires the input to be padded to a rectangle. [Try it online!](http://retina.tryitonline.net/#code=KD88PSguKSopKD89LirCtig_Pig_PC0xPi4pKilcU3szfSkgICAKL35c&input=IEwgICAgICAgICAgICAgICAgICAgICAgICAgIApMT0wgIFJPRkw6Uk9GTDpMT0w6Uk9GTDpST0ZMCiBMXFwgICAgICAgIF9fX19JX19fXyAgICAgICAKICAgID09PT09PT09ICAgIHwgIHxbXCAgICAgIAogICAgICAgICAgICBcX19fTz09X19fKSAgICAgCiAgICAgICAgICAgIF9fX0lfSV9fLyAgICAgICA) ### Explanation This is fairly standard vertical matching: ``` (?<=(.)*) ``` This counts the characters preceding the match by capturing that many characters into group `1`. ``` (?=.*¶(?>(?<-1>.)*)\S{3}) ``` This checks that there are three non-space characters on at the same position in the next line. This is done by popping from group `1` until its empty with `(?<-1>.)*` and preventing backtracking with the atomic group `(?>...)`. Finally we match the actual spaces. Those are simply replaced with the literal string `/~\`. Conveniently, matches are found from left to right and cannot overlap. [Answer] # JavaScript (ES6), 163 bytes ``` a=>(z=a.split` `,z.unshift(z[0].replace(/./g,' ')),z).map((b,i)=>b.replace(/ /g, (c,j)=>(!z[i+1]||!z[i+1][j+2]||/ /.test(z[i+1].slice(j,j+3))?c:'/~\\'))).join` ` ``` Quickly hacked together solution, can definitely be golfed down. Adds a blank line above, finds triple spaces, and replaces with a cup if the next line does not contain any spaces. Makes the allowed assumption that input will be rectangular. Any backspaces in the input need escaping (as one would expect with JS). [Answer] ## JavaScript (ES6), 109 bytes ``` s=>s.replace(/.*\n/,m=>(t=m).replace(/./g,' ')+m).replace(eval(`/ (?=[^]{${t.length-3}}[^ ]{3})/g`),"/~\\") ``` As well as requiring rectangular input, also assumes the first line ends with a newline, even if it is the only line of input. Uses a dynamically generated lookahead to ensure that it finds three spaces "above" three non-spaces, so as not to get confused by holes. ]
[Question] [ ## Background The [birthday paradox](http://en.wikipedia.org/wiki/Birthday_problem) is a popular problem in probability theory which defies (most people's) mathematical intuition. The problem statement is: > > Given *N* people, what is the probability that at least two of them have the same birthday (disregarding the year). > > > The problem is usually simplified by ignoring leap days entirely. In this case, the answer for *N = 23* is *P(23) ≈ 0.5072972* (as a common example). The linked Wikipedia article explains how to arrive at this probability. Alternatively, [this Numberphile video](https://www.youtube.com/watch?v=a2ey9a70yY0) does a really good job. However, for this challenge we want to do it right and *don't* ignore leap years. This is slightly more complicated, since now the 29th of February needs to be added, but this particular birthday is less likely than all the others. We'll also use the full [leap year](http://en.wikipedia.org/wiki/February_29#Leap_years) rules: * If a year is divisible by 400 it's a leap year. * Else, if a year is divisible by 100 it's not a leap year. * Else, if a year is divisible by 4 it's a leap year. * Else, it's not a leap year. Confused? It means that the years 1700, 1800, 1900, 2100, 2200, 2300 are not leap years, but 1600, 2000, 2400 are (as well as any other year divisible by 4). This calendar repeats every 400 years, and we will assume a uniform distribution of birthdays over those 400 years. The corrected result for *N = 23* is now *P(23) ≈ 0.5068761*. ## The Challenge Given an integer `1 ≤ N < 100`, determine the probability that among `N` people at least two have the same birthday under consideration of the leap year rules. The result should be a floating-point or fixed-point number, accurate to at least 6 decimal places. It is acceptable to truncate trailing zeroes. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and output the result via STDOUT (or closest alternative), function return value or function (out) parameter. Your solution must be able to produce output for all 99 inputs in a matter of seconds. This is mainly to rule out Monte Carlo methods with tons of samples, so if you're using a principally fast and exact algorithm in an excessively slow esoteric language, I'm willing to give leeway on this rule. ## Test Cases Here is the full table of results: ``` 1 => 0.000000 2 => 0.002737 3 => 0.008195 4 => 0.016337 5 => 0.027104 6 => 0.040416 7 => 0.056171 8 => 0.074251 9 => 0.094518 10 => 0.116818 11 => 0.140987 12 => 0.166844 13 => 0.194203 14 => 0.222869 15 => 0.252642 16 => 0.283319 17 => 0.314698 18 => 0.346578 19 => 0.378764 20 => 0.411063 21 => 0.443296 22 => 0.475287 23 => 0.506876 24 => 0.537913 25 => 0.568260 26 => 0.597796 27 => 0.626412 28 => 0.654014 29 => 0.680524 30 => 0.705877 31 => 0.730022 32 => 0.752924 33 => 0.774560 34 => 0.794917 35 => 0.813998 36 => 0.831812 37 => 0.848381 38 => 0.863732 39 => 0.877901 40 => 0.890932 41 => 0.902870 42 => 0.913767 43 => 0.923678 44 => 0.932658 45 => 0.940766 46 => 0.948060 47 => 0.954598 48 => 0.960437 49 => 0.965634 50 => 0.970242 51 => 0.974313 52 => 0.977898 53 => 0.981043 54 => 0.983792 55 => 0.986187 56 => 0.988266 57 => 0.990064 58 => 0.991614 59 => 0.992945 60 => 0.994084 61 => 0.995055 62 => 0.995880 63 => 0.996579 64 => 0.997169 65 => 0.997665 66 => 0.998080 67 => 0.998427 68 => 0.998715 69 => 0.998954 70 => 0.999152 71 => 0.999314 72 => 0.999447 73 => 0.999556 74 => 0.999645 75 => 0.999717 76 => 0.999775 77 => 0.999822 78 => 0.999859 79 => 0.999889 80 => 0.999913 81 => 0.999932 82 => 0.999947 83 => 0.999959 84 => 0.999968 85 => 0.999976 86 => 0.999981 87 => 0.999986 88 => 0.999989 89 => 0.999992 90 => 0.999994 91 => 0.999995 92 => 0.999996 93 => 0.999997 94 => 0.999998 95 => 0.999999 96 => 0.999999 97 => 0.999999 98 => 0.999999 99 => 1.000000 ``` (Of course, *P(99)* is only *1.0* due to rounding. The probability won't reach exactly *1.0* until *P(367)*.) [Answer] # Pyth, 31 ~~34~~ bytes ``` Jt.2425K366-1c.xX0rK-KQ*JQ^+KJQ ``` [Demonstration](https://pyth.herokuapp.com/?code=Jt.2425K366-1c.xX0rK-KQ*JQ%5E%2BKJQ&input=23&debug=0), [Test Harness](https://pyth.herokuapp.com/?code=FQr1%20100Jt.2425K366%25%22%25s%20%3D%3E%20%256f%22%2CQ-1c.xX0rK-KQ*JQ%5E%2BKJQ&input=%22Discarded%22&debug=0) This works similarly to the old version, except that instead of separately generating the (366 + n \* (.2425 - 1)) value and multiplying it on, it starts by generating a list which extends from 366 to 365 - n + 2, then modifies the 366 in place to become (366 + n \* (.2425 - 1)), and then takes the product of the list. Also, the constants 366 and -.7575 are used instead of 365 and .2425. --- Old version: Pyth, 34 bytes ``` J.2425K365-1c*+hK*QtJ.xrK-hKQ^+KJQ ``` There are two possible ways for there to be no pair of people with the same birthday: everyone to have different birthdays, and no one has a birthday on February 29th, and someone to have a birthday on the 29th, and everyone else to have different birthdays on normal days. The probability of the first occurring is (365 \* 364 \* ... 365 - n + 1) / (365.2425^n). The probability of the second occurring is (365 \* 364 \* ... 365 - n + 2) \* .2425 \* n / (365.2425^n) These can be written together as (365 \* 364 \* ... 365 - n + 2) \* (365 - n + 1 + .2425 \* n) / (365.2425^n) = (365 \* 364 \* ... 365 - n + 2) \* (365 + 1 + (.2425 - 1) \* n) / (365.2425^n). This is the probability of no pairs, so the probability of at least one pair is one minus the above number. ``` J = .2425 K = 365 .xrK-hKQ = (365 * 364 * ... 365 - n + 2) +hK*QtJ = (365 + 1 + n * (.2425 - 1)) ^+KJQ = (365.2425 ^ n) ``` [Answer] # Python, 179 178 144 143 140 136 135 133 ``` f=.2425 g=365+f a=lambda n:(n and(365-n)*a(n-1)or 365)/g b=lambda n:(n<2and f or(367-n)*b(n-1)+a(n-2)*f)/g p=lambda n:1-a(n-1)-b(n) ``` `p(n)` gives the result. Change `.2425` to `fractions.Fraction(97,400)` to get an exact result. [Answer] # Python ~~155~~ ~~153~~ ~~151~~ ~~142~~ 140 bytes ``` d=146097 b=d/400 c=97/d e=lambda n:n<2and 1-97/d or e(n-1)*(366-n)/b f=lambda n:n<2and c or f(n-1)*(367-n)/b+e(n-1)*c a=lambda n:1-e(n)-f(n) ``` Call `a(n)` for the result. For exact results, wrap `d` in a fraction. [Test here](http://ideone.com/O0R6zQ) Uses same technique as [here](http://www.efgh.com/math/birthday.htm), but with modified constants. [Answer] # 80386 machine code, 43 bytes Hexdump of the code: ``` 68 75 6e 33 3b 68 5a eb 07 3b 8b c4 49 d9 e8 d9 e8 d8 00 d9 e8 d9 40 04 de ea d8 c9 d9 00 de eb e2 f3 d8 ca d9 e8 d8 e1 58 58 c3 ``` I started from the following formula (for the complementary probability): ![\prod\limits_{i=0}^{k-2}(1-\frac{97+400*i}{d})*(1-\frac{303*(k-1)}{d})](https://i.stack.imgur.com/t4cS1.png) (here `d = 366 * 400 - 303` is the number of days in 400 years) Here is c++ code that implements it (it's already optimized a little): ``` double it_opt(int k) { double d = 366 * 400 - 303; // number of days in 400 years double result = 1; // probability of no coincidences const float const1 = float(400 / d); const float const2 = float(303 / d); double v1 = 1 + const2; double v2 = 1; for (int i = 0; i < k - 1; ++i) { v1 -= const1; result *= v1; v2 -= const2; } result *= v2; return 1 - result; } ``` The code is arranged so it requires the minimum number of constants - only two (`400 / d` and `303 / d`). I use the `float` type to represent them because it occupies less space (4 bytes per constant). In addition, I didn't want to multiply `const2` by `k - 1` (because that would require converting `k - 1` to `float`); the code subtracts `const2` repeatedly instead. Here is the assembly language listing: ``` ; // fastcall convention - parameter k is in ecx ; // result must be returned in st push dword ptr 0x3b336e75; // const1 = [esp + 4] push dword ptr 0x3b07eb5a; // const2 = [esp] mov eax, esp; // use [eax] instead of [esp] - 1 byte less dec ecx; // calculate k - 1 fld1; // initiaze result = 1 fld1; // initialize v1 fadd [eax]; fld1; // initialilze v2 myloop: fld dword ptr [eax + 4]; fsubp st(2), st; // update v1 fmul st, st(1); // update result fld dword ptr [eax]; fsubp st(3), st; // update v2 loop myloop; // loop fmul st, st(2); // update result by v2 fld1; fsub st, st(1); // complement result pop eax; // restore stack pop eax; // restore stack ret; // return ``` ]
[Question] [ The [major system](http://en.wikipedia.org/wiki/Mnemonic_major_system) is a [mnemonic](http://en.wikipedia.org/wiki/Mnemonic) device for converting numbers into words so they can be memorized more easily. It is based on how words sound phonetically, but to keep things simple for the challenge we'll only be concerned with how words are spelled. This means there will be some incorrect conversions, but that's alright. > > To convert a number into a word using our simplified major system: > > > * Replace each `0` with `s` or `z`. (Some could be `s` and some could be `z`. Same goes below.) > * Replace each `1` with `t` or `d` or `th`. > * Replace each `2` with `n`. > * Replace each `3` with `m`. > * Replace each `4` with `r`. > * Replace each `5` with `l`. > * Replace each `6` with `j` or `sh` or `ch`. > * Replace each `7` with `k` or `c` or `g` or `q`. > * Replace each `8` with `f` or `v`. > * Replace each `9` with `p` or `b`. > * Add the letters `aehiouwxy` anywhere in any amounts to make a real English word, *if possible*. > > **The only exception is that `h` may not be inserted after an `s` or `c`.** > > > The number may actually be any string of the digits 0-9 (no decimals or commas or signs). > > The word can only contain the lowercase letters a-z. > > > ## Examples The number `32` must be converted as `?m?n?`, where `?` represents any finite string made from the letters `aehiouwxy` (a string from the [free monoid](http://en.wikipedia.org/wiki/Free_monoid) if you prefer). There are many ways this could be made into a real English word: `mane`, `moon`, `yeoman`, etc. The number `05` could be converted as `?s?l?` or `?z?l?`. Some possibilities are `easily`, `hassle`, and `hazel`. The word `shawl` is not allowed because `h` may not be placed after `s`; it would be incorrectly read as `65`. # Challenge Write a program or function that takes in a string of the digits 0-9 and finds all the words that it could be converted into using the simplified major system mnemonic. Your program has access to a word list text file that defines what all the "real" English words are. There is one lowercase a-z word on each line of this file, and you may optionally assume it has a trailing newline. [Here is a list of real words you can use for testing.](http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt) You can assume this word list file is called `f` (or something longer) and lies in any convenient directory. For a 35 byte penalty (add 35 to your score) you may assume the word list is already loaded into a variable as a list of strings. This is mainly for languages that can't read files, but any submission may take advantage of it. Your program must output **all** the words in the word list that the input number can be converted to. They should be printed to stdout (or similar), one per line (with an optional trailing newline), or they can be returned as a list of strings if you chose to write a function. The word list is not necessarily alphabetized and the output doesn't need to be either. If there are no possible words then the output (or the list) will be empty. The output is also empty if the empty string is input. Take input via stdin, command line, or as a string argument to a function. The word list, or its file name, should not be part of the input, only the digit string. You are only matching single words in the word list, not sequences of words. The word `noon` would probably be one of the results for `22`, but the word sequence `no one` wouldn't. ## Test Cases Suppose this is the word list: ``` stnmrljkfp zthnmrlshqfb asatanamaralajakafapa aizxydwwwnhimouooraleshhhcavabe zdnmrlshcvb zdnmrlshchvb sthnmrlchgvb shthnmrlchgvb bob pop bop bopy boppy ``` The input `0123456789` should give all the long words except `zdnmrlshchvb` and `shthnmrlchgvb`: ``` stnmrljkfp zthnmrlshqfb asatanamaralajakafapa aizxydwwwnhimouooraleshhhcavabe zdnmrlshcvb sthnmrlchgvb ``` The input `99` should give: ``` bob pop bop bopy ``` (The output words may be in any order.) ## Scoring The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to the submission posted first. *Nifty related site: [numzi.com](http://numzi.com/numzi/).* [Answer] # Perl, ~~87~~ 84 ``` open A,f;"@ARGV"eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvb\0-z/0-90177789/dr&&print for<A> ``` Takes input in as the command line parameter: ``` $perl m.pl 23940 ``` Can be made somewhat shorter if the word list would be allowed on the standard input: ``` $perl -lnE'INIT{$;=pop}$;eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvba-z/0-90177789/dr&&say' 99 <f ``` [Answer] # Python 2, ~~215~~ 208 bytes This Python solution builds a regex from parts indexed by the command line argument, then tests each word with that (rather large) regex. ``` import re,sys a='[sz] (d|th?) n m r l (j|sh|ch) [kcgq] [fv] [pb]'.split() b=z='((?<![sc])h|[aeiouwxy])*' for i in sys.argv[1]:b+=a[int(i)]+z for d in open('f'): d=d.strip() if re.match('^'+b+'$',d):print d ``` Original source before the minifier: ``` import re,sys regexbits = '[sz] (d|th?) n m r l (j|sh|ch) [kcgq] [fv] [pb]'.split() regex = other = '((?<![sc])h|[aeiouwxy])*' for i in sys.argv[1] : regex += regexbits[int(i)] + other print regex # DEBUG for word in open('f'): word = word.strip() if re.match('^'+regex+'$', word) : print word ``` For example, the regex for the test `99` is: ``` ^((?<![sc])h|[aeiouwxy])*[pb]((?<![sc])h|[aeiouwxy])*[pb]((?<![sc])h|[aeiouwxy])*$ ``` The `(?<![sc])h` bit is a "look behind negative assertion" component that makes sure a `h` does not follow a `s` or `c` in the general filler parts. Thanks Calvin. This challenge motivated me to brush up on my rusty regex skills. [Answer] # Python 3, 170 ``` import sys,re t=str.maketrans('sztdnmrljkcgqfvpb','00112345677778899','aehiouwxy\n') for s in open('f'):re.sub('sh|ch','j',s).translate(t)!=sys.argv[1] or print(s,end='') ``` Readable version: ``` import sys, re table = str.maketrans('sztdnmrljkcgqfvpb', '00112345677778899', 'aehiouwxy\n') for line in open('f'): line = re.sub('sh|ch', 'j', line) if line.translate(table) == sys.argv[1]: print(line, end='') ``` The code makes use of the fact that `th` is redundant (since it maps to the same number as `t`, and `h` is a padding character). The static [`maketrans`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) function creates a table mapping the characters of the first argument to those of the second argument, and the characters of the third argument to `None` (which will result in those characters being deleted). The final code could be made a few bytes shorter by creating the table as a direct argument of `translate`. [Answer] # sed,paste,grep,cut - 109 ``` sed -e 's/[sc]h/6/g;s/[aehiouwxy]//g;y/sztdnmrljkcqgfvpb/00112345677778899/' w|paste w -|grep " $1$"|cut -f1 ``` Takes a file "w", converts each word to its number, paste back to the original, grep for the number and return the word matched. Note that the whitespace after the quote after grep is a tab, paste's default delimiter. I know Perl is way ahead, just wanted a better shell version as an example. Oh yeah, the $1 part means that this is supposed to be run from a shell script, (most shells should work), so it takes a command-line argument. [Answer] # Bash + coreutils, 216 ``` sed -n "$(sed 's/[aeiouwxy]//g :l s/\([^sc]\)h/\1/g tl'<w|grep -nf <(eval printf '%s\\n' `sed 's/0/{s,z}/g s/1/{t,th,d}/g y/2345/nmrl/ s/6/{j,sh,ch}/g s/7/{k,c,g,q}/g s/8/{f,v}/g s/9/{p,b}/g'<<<$1`)|sed s/:.\*/p/)" w ``` * The word list in a file called `w` * The innermost `sed` replaces digits with their possible replacements * The `eval printf` uses shell brace expansions to expand out all the possible substitutions * The second `sed` on the 1st line removes `aeiouwxy` and `h` (when not preceded by `[sc]`) from the word list * The grep prints out all matches, with line numbers * Since we have stripped out `aeiouwxy` and `h` from the word list, the last `sed` turns the results of grep (line numbers of each match) to another `sed` expression, which is processed by the outermost `sed` to reveal all possible words from the wordlist. ### Output: The word list file is specified as a command-line arg, followed by the number to mnemonicize: ``` ubuntu@ubuntu:~$ ./numzi.sh 99 bob pop bop bopy boppy $ ./numzi.sh 0123456789 stnmrljkfp zthnmrlshqfb asatanamaralajakafapa aizxydwwwnhimouooraleshhhcavabe zdnmrlshcvb sthnmrlchgvb $ ``` [Answer] **tr, sed, grep, xargs, sh, 77** ``` tr 0123456789 ztnmrljkfp|sed 's/ */[aehiouwxy]*/g'|xargs sh -c 'grep -x $0 f' ``` Expects the number in stdin and the word list should be stored in the file `f`. Does not uses all replacements (1 will always be z, 7 will always be k), so it may be called a lazy solution, but it finds at least one mnemonic for 95 numbers in [1-100]. ]
[Question] [ Consider an expression `2^2^...^2` with `n` operators `^`. Operator `^` means exponentiation ("to the power of"). Assume that it has no default assosiativity, so the expression needs to be fully parenthesized to become unambiguous. The number of ways to parenthesize the expression are given by [Catalan numbers](http://en.wikipedia.org/wiki/Catalan_number) `C_n=(2n)!/(n+1)!/n!`. Sometimes different parenthesizations give the same numeric outcome, for example `(2^2)^(2^2)=((2^2)^2)^2`, so the number of different possible numeric outcomes for a given `n` is less than `C_n` for all `n>1`. The sequence starts as `1, 1, 2, 4, 8, ...` as opposed to Catalan numbers `1, 2, 5, 14, 42, ...` The problem is to write the fastest program (or function) that accepts `n` as an input and returns the number of different possible numeric outcomes of the expression `2^2^...^2` with `n` operators `^`. The performance should not significantly deteriorate as `n` grows, so direct calculation of high power towers is probably a bad idea. [Answer] # Python 2.7 This approach takes advantage of the following considerations: Any integer can be represented as a sum of powers of two. The exponents in the powers of two can also be represented as powers of two. For example: ``` 8 = 2^3 = 2^(2^1 + 2^0) = 2^(2^(2^0) + 2^0) ``` These expressions that we end up with can be represented as sets of sets (in Python, I used the built-in `frozenset`): * `0` becomes the empty set `{}`. * `2^a` becomes the set containing the set representing `a`. E.g.: `1 = 2^0 -> {{}}` and `2 = 2^(2^0) -> {{{}}}`. * `a+b` becomes the concatenation of the sets representing `a` and `b`. E.g., `3 = 2^(2^0) + 2^0 -> {{{}},{}}` It turns out that expressions of the form `2^2^...^2` can easily be transformed into their unique set representation, even when the numerical value is much too large to be stored as an integer. --- For **`n=20`**, this runs in **8.7s** on CPython 2.7.5 on my machine (a bit slower in Python 3 and much slower in PyPy): ``` """Analyze the expressions given by parenthesizations of 2^2^...^2. Set representation: s is a set of sets which represents an integer n. n is given by the sum of all 2^m for the numbers m represented by the sets contained in s. The empty set stands for the value 0. Each number has exactly one set representation. In Python, frozensets are used for set representation. Definition in Python code: def numeric_value(s): n = sum(2**numeric_value(t) for t in s) return n""" import itertools def single_arg_memoize(func): """Fast memoization decorator for a function taking a single argument. The metadata of <func> is *not* preserved.""" class Cache(dict): def __missing__(self, key): self[key] = result = func(key) return result return Cache().__getitem__ def count_results(num_exponentiations): """Return the number of results given by parenthesizations of 2^2^...^2.""" return len(get_results(num_exponentiations)) @single_arg_memoize def get_results(num_exponentiations): """Return a set of all results given by parenthesizations of 2^2^...^2. <num_exponentiations> is the number of exponentiation operators in the parenthesized expressions. The result of each parenthesized expression is given as a set. The expression evaluates to 2^(2^n), where n is the number represented by the given set in set representation.""" # The result of the expression "2" (0 exponentiations) is represented by # the empty set, since 2 = 2^(2^0). if num_exponentiations == 0: return {frozenset()} # Split the expression 2^2^...^2 at each of the first half of # exponentiation operators and parenthesize each side of the expession. split_points = xrange(num_exponentiations) splits = itertools.izip(split_points, reversed(split_points)) splits_half = ((left_part, right_part) for left_part, right_part in splits if left_part <= right_part) results = set() results_add = results.add for left_part, right_part in splits_half: for left in get_results(left_part): for right in get_results(right_part): results_add(exponentiate(left, right)) results_add(exponentiate(right, left)) return results def exponentiate(base, exponent): """Return the result of the exponentiation of <operands>. <operands> is a tuple of <base> and <exponent>. The operators are each given as the set representation of n, where 2^(2^n) is the value the operator stands for. The return value is the set representation of r, where 2^(2^r) is the result of the exponentiation.""" # Where b is the number represented by <base>, e is the number represented # by <exponent> and r is the number represented by the return value: # 2^(2^r) = (2^(2^b)) ^ (2^(2^e)) # 2^(2^r) = 2^(2^b * 2^(2^e)) # 2^(2^r) = 2^(2^(b + 2^e)) # r = b + 2^e # If <exponent> is not in <base>, insert it to arrive at the set with the # value: b + 2^e. If <exponent> is already in <base>, take it out, # increment e by 1 and repeat from the start to eventually arrive at: # b - 2^e + 2^(e+1) = # b + 2^e while exponent in base: base -= {exponent} exponent = successor(exponent) return base | {exponent} @single_arg_memoize def successor(value): """Return the successor of <value> in set representation.""" # Call exponentiate() with <value> as base and the empty set as exponent to # get the set representing (n being the number represented by <value>): # n + 2^0 # n + 1 return exponentiate(value, frozenset()) def main(): import timeit print timeit.timeit(lambda: count_results(20), number=1) for i in xrange(21): print '{:.<2}..{:.>9}'.format(i, count_results(i)) if __name__ == '__main__': main() ``` (The memoization decorator's concept is copied from <http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/> .) Output: ``` 8.667753234 0...........1 1...........1 2...........1 3...........2 4...........4 5...........8 6..........17 [...] 19.....688366 20....1619087 ``` Timings for different `n`: ``` n time 16 0.240 17 0.592 18 1.426 19 3.559 20 8.668 21 21.402 ``` Any `n` above 21 results in a memory error on my machine. I'd be interested if anyone can make this faster by translating it into a different language. **Edit:** Optimized the `get_results` function. Also, using Python 2.7.5 instead of 2.7.2 made it run a bit faster. [Answer] ## C# This is a translation of flornquake's Python code to C# using a lower level addition routine which provides a moderate speedup over a direct translation. It's not the most optimised version I have, but that is quite a bit longer because it has to store the tree structure as well as the values. ``` using System; using System.Collections.Generic; using System.Linq; namespace Sandbox { class PowerTowers { public static void Main() { DateTime start = DateTime.UtcNow; for (int i = 0; i < 17; i++) Console.WriteLine("{2}: {0} (in {1})", Results(i).Count, DateTime.UtcNow - start, i); } private static IList<HashSet<Number>> _MemoisedResults; static HashSet<Number> Results(int numExponentations) { if (_MemoisedResults == null) { _MemoisedResults = new List<HashSet<Number>>(); _MemoisedResults.Add(new HashSet<Number>(new Number[] { Number.Zero })); } if (numExponentations < _MemoisedResults.Count) return _MemoisedResults[numExponentations]; HashSet<Number> rv = new HashSet<Number>(); for (int i = 0; i < numExponentations; i++) { IEnumerable<Number> rhs = Results(numExponentations - 1 - i); foreach (var b in Results(i)) foreach (var e in rhs) { if (!e.Equals(Number.One)) rv.Add(b.Add(e.Exp2())); } } _MemoisedResults.Add(rv); return rv; } } // Immutable struct Number : IComparable<Number> { public static Number Zero = new Number(new Number[0]); public static Number One = new Number(Zero); // Ascending order private readonly Number[] _Children; private readonly int _Depth; private readonly int _HashCode; private Number(params Number[] children) { _Children = children; _Depth = children.Length == 0 ? 0 : 1 + children[children.Length - 1]._Depth; int hashCode = 0; foreach (var n in _Children) hashCode = hashCode * 37 + n.GetHashCode() + 1; _HashCode = hashCode; } public Number Add(Number n) { // "Standard" bitwise adder built from full adder. // Work forwards because children are in ascending order. int off1 = 0, off2 = 0; IList<Number> result = new List<Number>(); Number? carry = default(Number?); while (true) { if (!carry.HasValue) { // Simple case if (off1 < _Children.Length) { if (off2 < n._Children.Length) { int cmp = _Children[off1].CompareTo(n._Children[off2]); if (cmp < 0) result.Add(_Children[off1++]); else if (cmp == 0) { carry = _Children[off1++].Add(One); off2++; } else result.Add(n._Children[off2++]); } else result.Add(_Children[off1++]); } else if (off2 < n._Children.Length) result.Add(n._Children[off2++]); else return new Number(result.ToArray()); // nothing left to add } else { // carry is the (possibly joint) smallest value int matches = 0; if (off1 < _Children.Length && carry.Value.Equals(_Children[off1])) { matches++; off1++; } if (off2 < n._Children.Length && carry.Value.Equals(n._Children[off2])) { matches++; off2++; } if ((matches & 1) == 0) result.Add(carry.Value); carry = matches == 0 ? default(Number?) : carry.Value.Add(One); } } } public Number Exp2() { return new Number(this); } public int CompareTo(Number other) { if (_Depth != other._Depth) return _Depth.CompareTo(other._Depth); // Work backwards because children are in ascending order int off1 = _Children.Length - 1, off2 = other._Children.Length - 1; while (off1 >= 0 && off2 >= 0) { int cmp = _Children[off1--].CompareTo(other._Children[off2--]); if (cmp != 0) return cmp; } return off1.CompareTo(off2); } public override bool Equals(object obj) { if (!(obj is Number)) return false; Number n = (Number)obj; if (n._HashCode != _HashCode || n._Depth != _Depth || n._Children.Length != _Children.Length) return false; for (int i = 0; i < _Children.Length; i++) { if (!_Children[i].Equals(n._Children[i])) return false; } return true; } public override int GetHashCode() { return _HashCode; } } } ``` ]
[Question] [ Your task is to make a quine, that is a non-empty computer program that prints it's own source without reading it. In addition if you remove any one byte from your original program the new program should print the source of your original program. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with fewer bytes being better. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~49~~ 45 bytes ``` <<H~Kla}\`q%2l}}ss2"<\ <<H~Kla}\`q%2l}}ss2"<\ ``` [Try it online!](https://tio.run/##S8/PScsszvj/38bGo847J7E2JqFQ1Sintra42EjJJoYLu/D//wA "Gol><> – Try It Online") [Verification!](https://tio.run/##fVHBUsIwFDw3X/HEcdIMWga8VbjoxRmPHoHRTJvSN5YkJikMB/z1@gIUPKi3vGR3s7vP7kJt9H2Ha2tcAOOZdWbl5Bpm4Djn3XT6/PXSyP3i/fNm0uz33k8G0wX7/bojxnyc342XJIM6pPxxFxQUptUh57fQKJ2e9DOlC1OqlEtfIHIhBGOlqsC1@q0xPrydcD1e5CzZYqjBWBLhkUuCfMsFSA8VvSZVtnUY1JnBEqdC6zSlyuyBVg3sMS@MjA2jlWkq9PXIu6I/Z3YHUXsgMqdkmZIr04ZYxl@@GEVVm6daOkJx/sBYZRwgoAYn9UqlP0KLmAIrOI1zXMLVDHp@DnANrx9oAUulAxayIS/aq6INuKEaCSOLoJynsP@7muckPbz8MxznS@ojOW6FuHGQ3qu486g067EH0DnPxSjrvgE) I did this in Gol><> rather than ><> because the former has the handy `K` operator that copies the top `n` items on the stack, which makes duplicating the clean copy of the source code easier. ### Explanation: This works by having two copies of the executing code, and redirecting to the second one if the first is damaged. This fails when the last `\` or the middle newline is removed, both of which are compensated for later. ``` << Redirect left <\ Switch to other source code if this line is irradiated " Push source with wrapping string literal ss2 Push quote }} Move "< to end q%2l If the length of the stack is not right \` Push an extra \ } Move the \ to the end a Newline Kl Duplicate the stack ~ Pop the extra newline H Halt and print stack ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, ~~73~~ 51 bytes ``` `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#` `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#` ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYCPElsOf4oKCOuG5mFEs4oCmK+G5mOG6jjc64bmYcWDhuZg64oKCw5/EliNgXG5gI8SWw5/igoI64bmYUSzigKYr4bmY4bqONzrhuZhxYOG5mDrigoLDn8SWI2AiLCIiLCIiXQ==) ``` `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` # push this string to the stack Ṙ: # reverse the string and push a copy ₂ßĖ # execute the top if the length is even # EXECUTION at this point the stack is [ qṘ:7ẎṘ+…,QṘ:₂ßĖ# ] Ṙq # quote and revert => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` ] Ẏ7: # get the 7 first char => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` , `#Ėß₂:Ṙ ] +Ṙ # revert and add => [`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`] Q,… # print, reprint and quit #Ėß₂:Ṙ # does nothing since the program ended # END OF EXECUTION #` # comment ``` When any char of the string is removed `₂ß` prevents the execution * if a ```` is removed, no code of the line will execute because the line will be either comented, either one single string either a mix of both and no execute fire * if `₂` is removed, the code will execute normally (as the deletion is not in the string) * if any of `Ṙ:ßĖ` is removed, the code will be either equal to `0`, `1`, a commented code or there will be no execution. This has no incidence and the code will executein the second line In any case the first execute will either have the string untouched or a string without incidence, in wich case, the second execute will have the string untouched. The program ends at the first sucessful execute since there is a quit instruction in the string [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 000, ~~196~~ ~~190~~ ~~176~~ ~~144~~ 138 bytes ``` <<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</ <<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</ ``` [Try it online!](https://tio.run/##rYxJCoAwDADv/iKe0gRrCU1pIVB9jAdR/P8tLm@QuQ3DHOe2X@5mrBr7C@ZKwlpISBsBCocOC/TAgkBNH1@UhWrGr4@qbDbaPPwycfeUkk/rDQ "Klein – Try It Online") ]
[Question] [ *This challenge is based on, and contains test cases from, [a programming course](http://mooc.aalto.fi/ohjelmointi/scala_2017.html) I took at Aalto University. The material is used with permission.* Two and a half years ago there was a challenge about [spoonerisms in English](https://codegolf.stackexchange.com/questions/69385/spoonerise-words). However, in Finnish spoonerisms are much more complicated. ## Spoonerisms in Finnish In Finnish, the vowels are `aeiouyäö` and the consonants are `bcdfghjklmnpqrstvwxz`. (`å` is technically part of Finnish, but is not considered here.) The most basic spoonerisms only take the first vowel of each word, and any consonants preceding them, and exchange the parts: ``` **he**nri **ko**ntinen -> **ko**nri **he**ntinen **ta**rja **ha**lonen -> **ha**rja **ta**lonen **fra**kki **ko**ntti -> **ko**kki **fra**ntti **o**vi **ke**llo -> **ke**vi **o**llo ``` ### Long vowels Some words contain two of the same consecutive vowel. In those cases, the vowel pair must be swapped with the other word's first vowel, shortening or lengthening vowels to keep the length same. ``` **haa**mu **ko**ntti -> **koo**mu **ha**ntti **ki**sko **kaa**ppi -> **ka**sko **kii**ppi ``` In the case of two *different* consecutive vowels this does not apply: ``` **ha**uva **ko**ntti -> **ko**uva **ha**ntti **pu**oskari **ko**ntti -> **ko**oskari **pu**ntti ``` Three or more of the same consecutive letter will **not** appear in the input. ### Vowel harmony Finnish has this lovely thing called [vowel harmony](https://en.wikipedia.org/wiki/Vowel_harmony#Finnish). Basically, it means that the *back vowels* `aou` and *front vowels* `äöy` should not appear in the same word. When swapping front or back vowels into a word, all vowels of the other kind in the rest of the word should be changed to match the new beginning of the word (`a <-> ä`, `o <-> ö`, `u <-> y`): ``` **kö***y*h*ä* **ko**ntti -> **ko***u*h*a* **kö**ntti **ha***u*v*a* **lää**h*ä*tt*ää* -> **lä***y*v*ä* **haa**h*a*tt*aa* ``` `e` and `i` are neutral and may appear with all other letters; swapping them into a word *must not* cause changes to the rest of the word. ### Special cases Vowel harmony does not apply to some words, including many loan words and compound words. These cases are not required to be handled "correctly". ## Challenge Given two words, output the words spoonerised. The input words will only contain the characters `a-z` and `äö`. You may choose to use uppercase or lowercase, but your choice must be consistent between both words and input/output. I/O may be done [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). (Words should be considered strings or arrays of characters.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins. ## Test cases ``` henri kontinen -> konri hentinen tarja halonen -> harja talonen frakki kontti -> kokki frantti ovi kello -> kevi ollo haamu kontti -> koomu hantti hauva kontti -> kouva hantti puoskari kontti -> kooskari puntti köyhä kontti -> kouha köntti hauva läähättää -> läyvä haahattaa frakki stressi -> strekki frassi äyskäri kontti -> kouskari äntti hattu sfääri -> sfätty haari ovi silmä -> sivi olma haamu prätkä -> präämy hatka puoskari sfääri -> sfäöskäri puuri puoskari äyskäri -> äöskäri puuskari uimapuku hajoa -> haimapuku ujoa ihme baletti -> bahme iletti uhka lima -> lihka uma osuma makkara -> masuma okkara makkara fakta -> fakkara makta lapsi laiva -> lapsi laiva firma hajoa -> harma fijoa dimensio bitti -> bimensio ditti flamingo joustava -> jomingo flaustava globaali latomo -> labaali glotomo trilogia fakta -> falogia trikta printti maksa -> mantti priksa riisi bitti -> biisi ritti sini riisi -> rini siisi aarre nyrkki -> nyyrre arkki laavu laki -> laavu laki kliininen parveke -> paaninen klirveke priimus kahvi -> kaamus prihvi spriinen lasta -> laanen sprista kliimaksi mammona -> maamaksi klimmona hylky hupsu -> hulku hypsy kehys fiksu -> fihys keksu levy huhu -> huvu lehu tiheys guru -> guheus tiru nyrkki heiluri -> herkki nyilyri latomo hajoa -> hatomo lajoa prisma lehti -> lesma prihti viina baletti -> baana viletti ``` [Answer] # JavaScript (ES6), ~~196~~ 175 bytes Takes the words as two strings in currying syntax `(a)(b)`. Returns an array of two arrays of characters. ``` a=>b=>[(e=/(.*?)([eiäaöoyu])(\2?)(.*)/,g=(a,[,c,v])=>[...c+v+(a[3]&&v)+a[4]].map(c=>(j=e.search(v),i=e.search(c))>9&j>9?e[i&~1|j&1]:c))(a=e.exec(a),b=e.exec(b),e+=e),g(b,a)] ``` [Try it online!](https://tio.run/##bVRLjuM2EN3PKQq9sMVptQeTZDMDyI1sAgQJkAM4XpTdtEmLEg1@NBEQ5DQ@Q19AB@sUP5LVdq9UfPVYqnpVxRN2aPdGnt1Tq1/426F6w2q9q9abgldfitXnZ1ZsuBwuOLzq3m9Z8fdPBK0@sy/lsSqw3JT7stsyurBarfaP3WOBm5@3i0XHHnHzy3a7avBc7Kt1car4ynI0e1F0rJTX056x9bfFaf3tmW/k4r@v/54WX7ffCS2QSPwfvi@QlbvR3rGSP1aclcdiVyLbvjluHVRAucCuBMMtg2oNe91arfhK6WP2LJ@e1ssSLHEPFJECxdx@BPaP1UnLtlguGcsWLFnkViEiPMOy@OsPtoTvZPz26@9/siX79Cn8uXgQvDXyoYSHWrdOtrzNtpFAroSwzHVoThj8ApXOVBEwcBkYmQeDdT2FddkiCMgTgZGpu@TkSulkdBJ0OIwMgdj421C68SDeRxLoO7zlEXTLO3ttazR32SUUzv4dux5eezFc7uIKBHJ9nIAaLsOFLjkXjIz03XChVFCgc4gfKGUd9cpOZhYrICOXgth6uNyn7lPqw@UmH@eicPYQ8kjXgu1cHzIxd12wUjUpYStjGxq8b8PZUIQ60YI9XJoQztX4ocS3Px9eUw0ktDcfd@Vdne9vJM54yUvaAV/7NIgnnYczo@ADMnKlaHhw71DxLNwOCQOZzlNMUacmUpT0JQD8TAltfXI11Do02Qwg6ASMzBnhgLUbjYBBE4GRqfCcWq9Q5iEKCKTjNCzSNHhTLCFwkPNKX2TDWyvjOu3kWGsG4UXOqz0obGR7jNwTzZHD9PeTjjCQP4PjjaPSO0SVk3W60cmKIJA3QtOTYSS9YfJWgogBOecanI0cR5rEsVnXAAG5AjAyjZRW3pRHCJh3tVnZRt/EpvgSbDyNHNoCE8ei7U3ew7bvCQOM52t/sPOp0DqXTgDE0/RUKEk/yO/iGU3Ha55MjDAQIYGzimXjbVxiFPklDHtmQ8UBmGoJ1BxaoXV5RDCEDT470zHkEQTMSjaNbrOWGOGQRwKn3e5V3cdx8mebtskrWiDRn21/jctFH3M9UDN8MgiBmofjpBTvciiRIwWduLgynBQ8BTp649NXcKrZSXNlXRsiuFTeZDOA0PZS9WbenXEOZ4sRIGrQfDOCUHmruUiDozghUe3Z5HSkNd49FtgidONr8fY/ "JavaScript (Node.js) – Try It Online") ### How? Each input word is passed through the regular expression **e**, which has 4 capturing groups: ``` e = /(.*?)([eiäaöoyu])(\2?)(.*)/ 1: leading consonants (or empty) [ 1 ][ 2 ][ 3 ][ 4] 2: first vowel 3: doubled first vowel (or empty) 4: all remaining characters ``` The helper function **g()** takes all capturing groups of the word to be updated as **a[ ]** and the first and second capturing groups of the other word as **c** and **v**. We apply basic spoonerism and take care of long vowels with: ``` c + v + (a[3] && v) + a[4] ``` To apply vowel harmony, we first coerce the regular expression **e** to a string by adding it to itself, which gives: ``` e = "/(.*?)([eiäaöoyu])(\2?)(.*)//(.*?)([eiäaöoyu])(\2?)(.*)/" ^^^^^^^^^^^^^^^^ 0123456789ABCDEF (position as hexa) ``` Vowels that need to be harmonized have a position greater than 9 in the resulting string. Furthermore, the expression was arranged in such a way that front vowels ***äöy*** are located at even positions, while back vowels ***aou*** are located at odd positions, next to their counterparts. Hence the following translation formula which is applied to each character **c** of the output word: ``` (j = e.search(v), i = e.search(c)) > 9 & j > 9 ? e[i & ~1 | j & 1] : c ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~235~~ ~~231~~ ~~225~~ ~~221~~ ~~217~~ 215 bytes ``` import re S=F,B='äöy','aou' def f(a,b,C=1): e,r,Q,W=re.findall(fr' ?(.*?([ei{B+F}]))(\2)?(\w*)'*2,a+' '+b)[0][2:6] for c in zip(*S*(W in B)+(B,F)*(W in F)):r=r.replace(*c) return[Q+W*len(e)+r]+(C and f(b,a,[])) ``` [Try it online!](https://tio.run/##XVNLbuM4EN3zFNxJsjXBdAaYRQB3gDSQfXcvskiCQTmmzIooUuBH3erB3MZnyAV8sEwVKSN2b2y@91jFVx@Nc9TO/vX@jsPofJReie@b@/ZuUx0Px7e5aitwqRI71cmuhnbbftl8am6EVK1vv7YPG6@uOrQ7MKbufCVv66vVbf2o8N@79f1/z01TP103t/XTj1VTra5bWFeyWm@bxz@fH69v/n4WsnNevki08heO9er7qn5gcNes67v2vlngfdPc@I2/8mo08KLq1UsjyGlM3j5@XT@sjLK1atb@eV1/kWB3ZHXbQvtI77//0GiU/ESW2f0/7Tdov203aMcU6@YqjAbpX8if7bzJBdJ59GhjLWvims2mzhFNWz3FqmXqXSvrUfbORrTKyj8@85kY4jMjIvhXkBqMW3SdiVgI0Xno@5IgYglnTDQTwk2kKWNclhQhR0BogCFdBDnCusRoSBNciIwXcUwu9OAvX1yoMeUrPc1aHw@XGTRlPL6d5Te0Ewe6FiMf@BYx80RHMqchRoBTcSF6FULOxMelPmIERYT@ePjNTip2jofluRiTDB0/40uSjp@d@SFfWhTQDMVEwNyjAZYejZ7u9kXj8/EwcGDs4aMVv@c@vi2mxpT8Wcs@3NLFy2v5gkg4wJh6nsSrgzLsE5WIEagHJbdg1FLrFpjAjEXSPbWV7udmIqNEdbhAv3KgToLP0gCZcZkQJ6GDPma5W4iBCWFgpM4bwKmk/YCiQz/AuVWGHbLPHQ7KBnRyiyenJ2bHjOgMDGj3Tr7StCKU5K@ucCQWUuyN2wIYfjG6wRUHhSGJKRE9GrfHiwIKQQpXkL9AMkH1hKX@jIknQnhEqujMJ0OfTQa0fMSyep5RYCRob7ySdva8iiTZeWYCGFPHYEpks0gfSPQGKQV/xSP4SfUq7xRA4UjNJPvFIQXZg57KQvMiBvZLhAisc4CBEJeZAGMWiMnPcK1c8TA4u9QMhSM1k0LPpqdNTmNIeXrJ8N7NY5hFr/QcaJJ9kTpk2CuCwqiJg/QSw6UpnURErejOPvks7JNW5DiiT2LpklZoUtl8rTJjZzSz537l0Z7tUcaGMTcj0FbRI2U8RjHkVtB8JmoEXH4OQMRUvof/AQ "Python 3 – Try It Online") --- Saved * -2 bytes, thanks to Lynn * -4 bytes, thanks to Zacharý [Answer] # Pyth, 84 bytes ``` .b++hY*W@N2JhtY2XW}JeA@DJc2"aouäöy"eNGH_Bmth:d:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"4 ``` [Try it online.](http://pyth.herokuapp.com/?code=.b%2B%2BhY%2aW%40N2JhtY2XW%7DJeA%40DJc2%22aou%C3%A4%C3%B6y%22eNGH_Bmth%3Ad%3A%22%5E%28%5B%5EA%2a%29%28%5BA%29%28%5C%5C2%29%2a%28.%2B%29%22%5CA%22aeiouy%C3%A4%C3%B6%5D%224&input=%5B%22hauva%22%2C%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D&test_suite_input=%5B%22henri%22%2C+%22kontinen%22%5D%0A%5B%22tarja%22%2C+%22halonen%22%5D%0A%5B%22frakki%22%2C+%22kontti%22%5D%0A%5B%22ovi%22%2C+%22kello%22%5D%0A%5B%22haamu%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22kontti%22%5D%0A%5B%22puoskari%22%2C+%22kontti%22%5D%0A%5B%22k%C3%B6yh%C3%A4%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D%0A%5B%22frakki%22%2C+%22stressi%22%5D%0A%5B%22%C3%A4ysk%C3%A4ri%22%2C+%22kontti%22%5D%0A%5B%22hattu%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22ovi%22%2C+%22silm%C3%A4%22%5D%0A%5B%22haamu%22%2C+%22pr%C3%A4tk%C3%A4%22%5D%0A%5B%22puoskari%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22puoskari%22%2C+%22%C3%A4ysk%C3%A4ri%22%5D%0A%5B%22uimapuku%22%2C+%22hajoa%22%5D%0A%5B%22ihme%22%2C+%22baletti%22%5D%0A%5B%22uhka%22%2C+%22lima%22%5D%0A%5B%22osuma%22%2C+%22makkara%22%5D%0A%5B%22makkara%22%2C+%22fakta%22%5D%0A%5B%22lapsi%22%2C+%22laiva%22%5D%0A%5B%22firma%22%2C+%22hajoa%22%5D%0A%5B%22dimensio%22%2C+%22bitti%22%5D%0A%5B%22flamingo%22%2C+%22joustava%22%5D%0A%5B%22globaali%22%2C+%22latomo%22%5D%0A%5B%22trilogia%22%2C+%22fakta%22%5D%0A%5B%22printti%22%2C+%22maksa%22%5D%0A%5B%22riisi%22%2C+%22bitti%22%5D%0A%5B%22sini%22%2C+%22riisi%22%5D%0A%5B%22aarre%22%2C+%22nyrkki%22%5D%0A%5B%22laavu%22%2C+%22laki%22%5D%0A%5B%22kliininen%22%2C+%22parveke%22%5D%0A%5B%22priimus%22%2C+%22kahvi%22%5D%0A%5B%22spriinen%22%2C+%22lasta%22%5D%0A%5B%22kliimaksi%22%2C+%22mammona%22%5D%0A%5B%22hylky%22%2C+%22hupsu%22%5D%0A%5B%22kehys%22%2C+%22fiksu%22%5D%0A%5B%22levy%22%2C+%22huhu%22%5D%0A%5B%22tiheys%22%2C+%22guru%22%5D%0A%5B%22nyrkki%22%2C+%22heiluri%22%5D%0A%5B%22latomo%22%2C+%22hajoa%22%5D%0A%5B%22prisma%22%2C+%22lehti%22%5D%0A%5B%22viina%22%2C+%22baletti%22%5D&debug=1) [Test suite.](http://pyth.herokuapp.com/?code=.b%2B%2BhY%2aW%40N2JhtY2XW%7DJeA%40DJc2%22aou%C3%A4%C3%B6y%22eNGH_Bmth%3Ad%3A%22%5E%28%5B%5EA%2a%29%28%5BA%29%28%5C%5C2%29%2a%28.%2B%29%22%5CA%22aeiouy%C3%A4%C3%B6%5D%224&input=%5B%22hauva%22%2C%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D&test_suite=1&test_suite_input=%5B%22henri%22%2C+%22kontinen%22%5D%0A%5B%22tarja%22%2C+%22halonen%22%5D%0A%5B%22frakki%22%2C+%22kontti%22%5D%0A%5B%22ovi%22%2C+%22kello%22%5D%0A%5B%22haamu%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22kontti%22%5D%0A%5B%22puoskari%22%2C+%22kontti%22%5D%0A%5B%22k%C3%B6yh%C3%A4%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D%0A%5B%22frakki%22%2C+%22stressi%22%5D%0A%5B%22%C3%A4ysk%C3%A4ri%22%2C+%22kontti%22%5D%0A%5B%22hattu%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22ovi%22%2C+%22silm%C3%A4%22%5D%0A%5B%22haamu%22%2C+%22pr%C3%A4tk%C3%A4%22%5D%0A%5B%22puoskari%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22puoskari%22%2C+%22%C3%A4ysk%C3%A4ri%22%5D%0A%5B%22uimapuku%22%2C+%22hajoa%22%5D%0A%5B%22ihme%22%2C+%22baletti%22%5D%0A%5B%22uhka%22%2C+%22lima%22%5D%0A%5B%22osuma%22%2C+%22makkara%22%5D%0A%5B%22makkara%22%2C+%22fakta%22%5D%0A%5B%22lapsi%22%2C+%22laiva%22%5D%0A%5B%22firma%22%2C+%22hajoa%22%5D%0A%5B%22dimensio%22%2C+%22bitti%22%5D%0A%5B%22flamingo%22%2C+%22joustava%22%5D%0A%5B%22globaali%22%2C+%22latomo%22%5D%0A%5B%22trilogia%22%2C+%22fakta%22%5D%0A%5B%22printti%22%2C+%22maksa%22%5D%0A%5B%22riisi%22%2C+%22bitti%22%5D%0A%5B%22sini%22%2C+%22riisi%22%5D%0A%5B%22aarre%22%2C+%22nyrkki%22%5D%0A%5B%22laavu%22%2C+%22laki%22%5D%0A%5B%22kliininen%22%2C+%22parveke%22%5D%0A%5B%22priimus%22%2C+%22kahvi%22%5D%0A%5B%22spriinen%22%2C+%22lasta%22%5D%0A%5B%22kliimaksi%22%2C+%22mammona%22%5D%0A%5B%22hylky%22%2C+%22hupsu%22%5D%0A%5B%22kehys%22%2C+%22fiksu%22%5D%0A%5B%22levy%22%2C+%22huhu%22%5D%0A%5B%22tiheys%22%2C+%22guru%22%5D%0A%5B%22nyrkki%22%2C+%22heiluri%22%5D%0A%5B%22latomo%22%2C+%22hajoa%22%5D%0A%5B%22prisma%22%2C+%22lehti%22%5D%0A%5B%22viina%22%2C+%22baletti%22%5D&debug=1) Proving that it's not *that* hard in golf languages. A stack-based language might do even better. Pyth uses ISO-8859-1 by default, so `äö` are one byte each. ### Explanation * `Q`, containing the input pair of words, is appended implicitly. * `m`: map each word `d` in the input to: + `:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"`: replace `A` with `aeiouyäö]` in the string to get the regex `^([^aeiouyäö]*)([aeiouyäö])(\2)*(.+)`. + `:d`: find all matches and return their capturing groups. + `h`: take the first (and only) match. + `t`: drop the first group containing the entire match. * `_B`: pair with reverse to get `[[first, second], [second, first]]`. * `.b`: map each pair of words `N, Y` in that to: + `hY`: take the beginning consonants of the second word. + `@N2`: take the long first vowel of the first word, or `None`. + `htY`: take the first vowel of the second word. + `J`: save that in `J`. + `*W`…`2`: if there was a long vowel, duplicate the second word's vowel. + `+`: append that to the consonants. + `c2"aouäöy"`: split `aouäöy` in two to get `["aou", "äöy"]`. + `@DJ`: sort the pair by intersection with the first vowel of the second word. This gets the half with the second word's first vowel in the end of the pair. + `A`: save the pair to `G, H`. + `e`: take the second half. + `}J`: see if the first vowel of the second word is in the second half. + `XW`…`eNGH`: if it was, map `G` to `H` in the suffix of the first word, otherwise keep the suffix as-is. + `+`: append the suffix. ]
[Question] [ ### Challenge Given a polynomial \$p\$ with real coefficients of order \$1\$ and degree \$n\$, find another polynomial \$q\$ of degree at most \$n\$ such that \$(p∘q)(X) = p(q(X)) \equiv X \mod X^{n+1}\$, or in other words such that \$p(q(X)) = X + h(X)\$ where \$h\$ is an arbitrary polynomial with \$ord(h) \geqslant n+1\$. The polynomial \$q\$ is uniquely determined by \$p\$. For a polynomial \$p(X) = a\_nX^n + a\_{n+1}X^{n+1} + ... + a\_m X^m\$ where \$n \leqslant m\$ and \$a\_n ≠ 0\$,\$a\_m ≠ 0\$, we say \$n\$ is the *order* of \$p\$ and \$m\$ is the *degree* of \$p\$. **Simplification**: You can assume that \$p\$ has integer coefficients, and \$a\_1 = 1\$ (so \$p(X) = X + \text{[some integral polynomial of order 2]}\$). In this case \$q\$ has integral coefficients too. The purpose of this simplification is to avoid the issues with floating point numbers. There is however a non-integral example for illustration purposes. ### Examples * Consider the Taylor series of \$\exp(x)-1 = x + x^2/2 + x^3/6 + x^4/24 + ...\$ and \$\ln(x+1) = x - x^2/2 + x^3/3 - x^4/4 + ... \$ then obviously \$\ln(\exp(x)-1+1)= x\$. If we just consider the Taylor polynomials of degree 4 of those two functions we get with the notation from below (see testcases) \$p = [-1/4,1/3,-1/2,1,0]\$ and \$q = [1/24, 1/6, 1/2, 1,0]\$ and \$(p∘q)(X) \equiv X \mod X^5\$ ![](https://i.stack.imgur.com/3BIF3.png) * Consider the polynomial \$p(X) = X + X^2 + X^3 + X^4\$. Then for \$q(X) = X - X^2 + X^3 - X^4\$ we get $$(p \circ q)(X) = p(q(X)) = X - 2X^5 + 3X^6 - 10X^7 +...+ X^{16} \equiv X \mod X^5$$ ### Testcases Here the input and output polynomials are written as lists of coefficients (with the coefficient of the highest degree monomial first, the constant term last): ``` p = [4,3,2,0]; q=[0.3125,-.375,0.5,0] ``` Integral Testcases: ``` p = [1,0]; q = [1,0] p = [9,8,7,6,5,4,3,2,1,0]; q = [4862,-1430,429,-132,42,-14,5,-2,1,0] p = [-1,3,-3,1,0]; q = [91,15,3,1,0] ``` [Answer] # Python 2 + sympy, 128 bytes We locally invert the polynomial by assuming that q(x) = x, composing it with p, checking the coefficient for x2, and subtracting it from q. Let's say the coefficient was 4, then the new polynomial becomes q(x) = x - 4x2. We then again compose this with p, but look up the coefficient for x3. Etc... ``` from sympy import* i=input() p=Poly(i,var('x'));q=p*0+x n=2 for _ in i[2:]:q-=compose(p,q).nth(n)*x**n;n+=1 print q.all_coeffs() ``` [Answer] # Mathematica, 45 bytes ``` Normal@InverseSeries[#+O@x^(#~Exponent~x+1)]& ``` Yeah, Mathematica has a builtin for that.... Unnamed function taking as input a polynomial in the variable `x`, such as `-x^4+3x^3-3x^2+x` for the last test case, and returning a polynomial with similar syntax, such as `x+3x^2+15x^3+91x^4` for the last test case. `#+O@x^(#~Exponent~x+1)` turns the input `#` into a power series object, truncated at the degree of `#`; `InverseSeries` does what it says; and `Normal` turns the resulting truncated power series back into a polynomial. (We could save those initial 7 bytes if an answer in the form `x+3x^2+15x^3+91x^4+O[x]^5` were acceptable. Indeed, if that were an acceptable format for both input and output, then `InverseSeries` alone would be a 13-byte solution.) [Answer] ## JavaScript (ES6), 138 bytes ``` a=>a.reduce((r,_,i)=>[...r,i<2?i:a.map(l=>c=p.map((m,j)=>(r.map((n,k)=>p[k+=j]=m*n+(p[k]||0)),m*l+(c[j]||0)),p=[]),c=[],p=[1])&&-c[i]],[]) ``` Port of @orlp's answer. I/O is in the form of arrays of coefficients in reverse order i.e. the first two coefficients are always 0 and 1. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes ``` p->Pol(serreverse(p+O(x^#p))) ``` [Try it online!](https://tio.run/##LYrLDoJQDER/pcFNG9tExBcL@QXdE0xYXAwJwUkxRL/@CsJq5pwZ1N7aE7GhK0VYcX91PAT3MAYfAmN7489jAxGJNdB9GWQFwdv@zfMXQslsEmpWFlEqy4NmutddNfV0iVwvetaTHnXZVm3pRJb9sZL4Aw "Pari/GP – Try It Online") ]
[Question] [ Create a bootloader that executes given Brainfuck program. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with least bytes wins. Being a bootloader, the size of the program is counted in non-zero bytes in the compiled code. ## Brainfuck 30000 8-bit overflowing cells. Pointer wraps over. Some notes about operations: * Input must be read in a way that all printable ASCII characters are correctly supported. Other keystrokes may either insert an arbitrary character or do nothing at all. * Reading user input must be character buffered, not line buffered. * Reading user input must echo inserted character. * Output must follow either the [code page 437](https://en.wikipedia.org/wiki/Code_page_437) or your built-in VGA adapters default codepage. ## Bootloader This is a x86 bootloader. A bootloader ends with the traditional `55 AA` sequence. Your code must run either on VirtualBox, Qemu or other well-known x86 emulator. ## Disk Executable Brainfuck is located at second disk sector, right after your bootloader, which is placed, as usually, in MBR section, the first sector on disk. Additional code (any code over 510 bytes) can be located at other disk sectors. Your storage device must be either a hard drive or a floppy disk. ## STDIO Of course, a bootloader cannot have an access to the operating system's IO capabilities. Therefore BIOS functions are used instead for printing text and reading user input. ## Template To get started, here is a simple template written in Nasm (intel syntax) assembly: ``` [BITS 16] [ORG 0x7c00] ; first sector: boot: ; initialize segment registers xor ax, ax mov ds, ax mov es, ax mov ss, ax ; initialize stack mov sp, 0x7bfe ; load brainfuck code into 0x8000 ; no error checking is used mov ah, 2 ; read mov al, 1 ; one sector mov ch, 0 ; cylinder & 0xff mov cl, 2 ; sector | ((cylinder >> 2) & 0xc0) mov dh, 0 ; head ; dl is already the drive number mov bx, 0x8000 ; read buffer (es:bx) int 0x13 ; read sectors ; fill sector times (0x200 - 2)-($-$$) db 0 ; boot signature db 0x55, 0xaa ; second sector: db 'brainfuck code here' times 0x400-($-$$) db 0 ``` Compiling this is pretty easy: ``` nasm file.asm -f bin -o boot.raw ``` And the run it. For example, with Qemu: ``` qemu-system-i386 -fda boot.raw ``` --- Addtional information: [OsDev wiki](http://wiki.osdev.org/Rolling_Your_Own_Bootloader), [Wikipedia](https://en.wikipedia.org/wiki/Booting#Boot_sequence) [Answer] # 171 bytes1 Wooohoooo! It took half the day, but it was fun... So, here it is. I think it conforms to the specs (wraparound of cell pointer, echo of characters on input, reading char by char, echo of input chars, ...), and it seems to actually work (well, I didn't try many programs, but given the simplicity of the language, the coverage isn't that bad, I think). ## Limitations One important thing: if your brainfuck program contains other chars than the 8 brainfuck instructions, or if the `[]` are not well-balanced, *it will crash on you, mouhahahaha!* Also, the brainfuck program can't exceed 512 bytes (a sector). But this seems conforming since you say *"executable Brainfuck is located at second disk sector"*. Last detail: I didn't explicitly initialized the cells to zero. Qemu seem to do it for me, and I'm relying on this, but I don't know whether a real BIOS on a real computer would do it (initialization would just take a few bytes more, anyway). ## The code (based on your template, and by the way, thanks for this, I would never have tried without it): ``` [BITS 16] [ORG 0x7C00] %define cellcount 30000 ; you can't actually increase this value much beyond this point... ; first sector: boot: ; initialize segment registers xor ax, ax mov ss, ax mov ds, ax mov es, ax jmp 0x0000:$+5 ; initialize stack mov sp, 0x7bfe ; load brainfuck code into 0x8000 ; no error checking is used mov ah, 2 ; read mov al, 1 ; one sector mov ch, 0 ; cylinder & 0xff mov cl, 2 ; sector | ((cylinder >> 2) & 0xc0) mov dh, 0 ; head ; dl is already the drive number mov bx, 0x8000 ; read buffer (es:bx) int 0x13 ; read sectors ; initialize SI (instruction pointer) mov si, bx ; 0x8000 ; initialize DI (data pointer) mov bh, 0x82 mov di, bx ; 0x8200 decode: lodsb ; fetch brainfuck instruction character .theend: test al, al ; endless loop on 0x00 jz .theend and ax, 0x0013 ; otherwise, bit shuffling to get opcode id shl ax, 4 shl al, 2 shr ax, 1 add ax, getchar ; and compute instruction implementation address jmp ax align 32, db 0 getchar: xor ah, ah int 0x16 cmp al, 13 jne .normal mov al, 10 ; "enter" key translated to newline .normal: mov byte [di], al push di jmp echochar align 32, db 0 decrementdata: dec byte [di] jmp decode align 32, db 0 putchar: push di mov al, byte [di] echochar: mov ah, 0x0E xor bx, bx cmp al, 10 ; newline needs additional carriage return jne .normal mov al, 13 int 0x10 mov al, 10 .normal: int 0x10 pop di jmp decode align 32, db 0 incrementdata: inc byte [di] jmp decode align 32, db 0 decrementptr: dec di cmp di, 0x8200 ; pointer wraparound check (really, was that necessary?) jge decode add di, cellcount jmp decode align 32, db 0 jumpback: pop si jmp jumpforward align 32, db 0 incrementptr: inc di cmp di, 0x8200+cellcount ; pointer wraparound check jl decode sub di, cellcount jmp decode align 32, db 0 jumpforward: cmp byte [di], 0 jz .skip push si jmp decode .skip: xor bx, bx ; bx contains the count of [ ] imbrication .loop: lodsb cmp al, '[' je .inc cmp al, ']' jne .loop test bx, bx jz decode dec bx jmp .loop .inc: inc bx jmp .loop ; fill sector times (0x1FE)-($-$$) db 0 ; boot signature db 0x55, 0xAA ; second sector contains the actual brainfuck program ; currently: "Hello world" followed by a stdin->stdout cat loop db '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.,[.,]' times 0x400-($-$$) db 0 ``` ## Tricks used Ok, I cheated a bit. Since you said *"being a bootloader, the size of the program is counted in non-zero bytes in the compiled code"*, I made the code smaller by allowing "holes" between the implementation of the eight brainfuck opcodes. This way, I don't need a big sequence of tests, a jump table, or anything: I just jump to the brainfuck "opcode id" (from 0 to 8) multiplied by 32 to execute the brainfuck instruction (worth to note that it means the implementation of the instructions can't take more than 32 bytes). Moreover, to get this "opcode id" from the brainfuck program character fetched, I noticed just a bit of bit shuffling was necessary. Indeed, if we just consider bits 0, 1 and 4 of the opcode character, we end up with the 8 unique combinations: ``` X XX 00101100 0x2C , Accept one byte of input, storing its value in the byte at the pointer. 00101101 0x2D - Decrement (decrease by one) the byte at the pointer. 00101110 0x2E . Output the value of the byte at the pointer. 00101011 0x2B + Increment (increase by one) the byte at the pointer. 00111100 0x3C < Decrement the pointer (to point to the next cell to the left). 01011101 0x5D ] Jump back after the corresp [ if data at pointer is nonzero. 00111110 0x3E > Increment the pointer (to point to the next cell to the right). 01011011 0x5B [ Jump forward after the corresp ] if data at pointer is zero. ``` And, lucky me, there is actually one opcode that requires more than 32 bytes to implement, but it's the last one (jump forward `[`). As there is more room after, everything is fine. Other trick: I don't know how a typical brainfuck interpreter works, but, to make things much smaller, I did not actually implement `]` as *"Jump back after the corresponding `[` if data at pointer is nonzero"*. Instead, I *always* go back to the corresponding `[`, and, from here, re-apply the typical `[` implementation (which then, eventually, goes forward after the `]` again if needed). For this, each time I encouter a `[`, I put the current "brainfuck instruction pointer" on the stack before executing the inner instructions, and when I encounter a `]`, I pop back the instruction pointer. Pretty much as if it was a call to a function. You could therefore theoretically overflow the stack by making many many imbricated loops, but not with the current 512-bytes limitation of the brainfuck code, anyway. --- 1. Including the zero bytes that were part of the code itself, but not those that were part of some padding ]
[Question] [ I define the method of combining a sequence to mean that every number in the sequence is concatenated as a string, then that result is made an integer. ``` [1, 2, 3] -> 123 ``` For every finite sequence of at least 3 consecutive integers, missing exactly one element in the sequence, and this missing element may not be the first or last element in the sequence, output the integer resulting from the combined sequence. I am referring to this as a "singly lossy integer". ``` [1, 2, 3] -> {1, 3} (missing an element) -> 13 ``` This sequence of singly lossy integers is the union of the following subsequences (partitions?): The first subsequence `{n, n+2}` is [A032607](https://oeis.org/A032607). ``` {n, n+2} -> 13, 24, 35, 46, 57, 68, 79, 810, 911, 1012, ... {n, n+1, n+3} -> 124, 235, 346, ... {n, n+2, n+3} -> 134, 245, 356, ... {n, n+1, n+2, n+4} -> 1235, 2346, 3457, ... {n, n+1, n+3, n+4} -> 1245, 2356, 3467, ... {n, n+2, n+3, n+4} -> 1345, 2456, 3567, ... ... for n ∈ ℕ (integers >= 1) ``` These integers must be printed in ascending order. **The first 25 singly lossy integers are below**: ``` 13, 24, 35, 46, 57, 68, 79, 124, 134, 235, 245, 346, 356, 457, 467, 568, 578, 679, 689, 810, 911, 1012, 1113, 1214, 1235, ... ``` [First 7597 Singly Lossy Integers](http://pastebin.com/Z7LPpfsU) Ungolfed reference implementations. I made it to be faster, rather than smaller. * [Ideone](http://ideone.com/Ux9LeY) * [TIO](https://tio.run/nexus/python2#lVXBbtswDD3XX8E5h9lYEiQFimLFgt123Gm3oDDUmLHVOrItKZ339RklWZbtpAN2aS2apB7fe3Quh4opBQWKJH2K7mJ6QMk0KmDQMK1RCjjWkk6Ki6L6A1WtFP3lSsfRXY5HyDIuuM6yRGF1ND3uFuZpbVJgB/vNErZLuH8eXpxYR/F7Ol/lPfugy9n6o3rjzfj8zqozUuBnLTACh0NgpwOGULZydfwIo1Y72JiscNkXlxUgrVnToMgTn5EOb3swQ@nqGte@s6R1wAWEIQlCB592AYcZV6I@S5dFk0Dk9LAsZw2T@loWdX5R2J5RHNDeokucisOFxgKluiXQkm5qRwxha0dpfUDQcfOfNAvP3qSIUCRxvH6tuUiUlglx7CYX6Ywcgyj9kAo3WmZHm5Px0ejgCbpNwRtiE@CbE@F9qesqsW/8C7qH4nY1Br4s90bhwaoszzOKhRwucjTuXd226zimXKeeWt9pZmJ7pbfjyBge49pKkrqOaX9K/6GXA9hrtqABtSXSZELJixLJqw4yKWQp9nZjIoffJT@UExNy/VlRqm3f@s1wCfuN4enEhXOZw0iRmQFsrl1IsyM9X992QIU22jfu7PO8G9gphgluIp8rMcbivwxG@/BRcPpMvgKO4P4@EovoqOkSOSbju2/YmlUiikPHYBTX4VS/Y18KurbgHYW9hLONiOI4hqgYHGko5GbOTjJRYLLdGIWLobiRtAxQONRLiJ/iJQWpfGShws9kBXkddXuwdmkCFNeu6dtF07PBFkULAqrtHpl5fklimv6XzIzp/X5iVMZ6dQ71qalQo/05icwyTJb9B6sUukG7EbTHh6@PBp1DoCb2X0Y2ern8BQ) (fastest, higher limits) ### Rules: * Shortest code wins * You may either (say which one): + Print the singly lossy integers forever + Given a positive integer *n*, print or return the first *n* elements as a list, or a comma- or whitespace- delimited string. * You should support arbitrarily large integers if your language allows it, especially if you're printing forever. [Inspired by / Related](https://codegolf.stackexchange.com/q/73305/34718) Note: There is not yet an entry in the OEIS for this sequence. Another note: I named them the "Singly Lossy Integers" so that there could in turn be "Doubly Lossy Integers", "N-ly Lossy Integers", "(N+1)-ly Lossy Integers", and the "Lossy Integers" (union of all of these). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 62 bytesSBCS ## Infinite printing full program, 63 bytes ``` s←⍎' '~⍨⍕ {⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t]}⍣≡⊂1 3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR24RHvX3qCup1j3pXPOqdylX9qG8qULD4UdeiRJBkV/Oj3q2PuluSgBxD7UQgqwQk3LFKI0kHpKWrOVFTI1EHpK5nb5Jmko7ho7bJEC0l0Y96u4sPrSiJrX3Uu/hR58JHXU2GCsb//wMA "APL (Dyalog Unicode) – Try It Online") This one is pretty fast. Theoretically can be made faster using a min heap, but the challenge is code golf after all. ### How it works: the concept If we denote each item in the sequence as a list of integers (`[1,3]` for 13, `[1,2,4]` for 124, and so on), observe that subsequent items can be derived from an existing item `x` in three ways: * Add 1 to all numbers in `x` * Add 1 to all numbers in `x`, and then prepend the first element of `x` * Append 1 plus the last element of `x` to `x` Therefore, the algorithm is to start with the single known value and infinitely run the following: * Extract the smallest item and print it * Derive three larger values from it and add them to the list of next candidate items ### How it works: the code ``` s←⍎' '~⍨⍕ ⍝ Helper function: concat a list of numbers ⍕ ⍝ Stringify entire array, which will contain blanks between items ' '~⍨ ⍝ Remove blanks ⍎ ⍝ Eval s← ⍝ Store the function to s ⍝ Main program: print all items in the sequence infinitely {⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t]}⍣≡,⊂1 3 {...}⍣≡⊂1 3 ⍝ Specify starting item and infinite loop ⊂1 3 ⍝ singleton array containing [1 3] {...}⍣≡ ⍝ Pass it to the infinite looping function ⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t] ⍝ Single iteration ⍵ ⍝ Sorted candidate items a←⊃⍵ ⍝ Take the first element and store to a ⎕←s⊢a ⍝ Concat and print it b←1+a ⍝ Add 1 to all items of a and store to b t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵ ⍝ Add next candidates 1↓⍵ ⍝ Remove the first item (already printed) (b,⍨⊃a)(a,⊃⌽b)b, ⍝ Prepend three candidates: b ⍝ 1+a (a,⊃⌽b) ⍝ append 1+last element of a to a (b,⍨⊃a) ⍝ prepend first element of a to 1+a t←∪ ⍝ Uniquify and store to t t[⍋s¨t] ⍝ t sorted with the key function s (concat'ed value) ``` ## Function returning first `n` values, 62 bytes ``` ⎕CY'dfns' ⊢↑∘{(⍋⊃¨⊂)⍵{a b c←⍵-1 0⍺⋄⍎dab⍕c↓a↓b~⍨⍳⍺}¨↓3cmat⍵}2+⊢ ``` [Try it online!](https://tio.run/##JVG7apZREOzzFNNFkcDZ@25tYyrB2Fj@SYhNvBBtJMRCJWjCH5QQsNUqnYXYWPoo34v8ntXiDMPZy8zurl4e7xy@WR2/eLrZLFc3959sHx49f7W9tVx8X86/LB@/nt5Z1pfLxfs/t8vFu7vL@tfpCvs4WM4/T75DGMv693L5YVlfHa72l/XNjFyv5tt/u6xvl/XPGT6btefXcvBs9XrWnPG92Xxz9K/D1dTcfdjtf0jrXd3sPbo/8fGD3b3NyUw5Wj59@2@EBKwQgzos4Iko0PwiUfD8ZzXIDIo5dGaoB2ymWSR85noWkgaKCDSIQTR7EtNs0fXUDUiooZmSg4wC5JSgoCmXPEDFBB7M4FkHZm59ngZanVuelRuaGQfYOcHBBU4Z4BKCDGEIiUBmHUSk3cu0396lzYtJQzOXhIQUJHVASgk6lKGkAmVVaHtW1Z5d5/A9ufbo6trQLLSgaQNaRrBhDCMTGJvCxAzWns2sN2dzdb0368VZWEOz9AErJ/hwhpMLnF3h4gZXd3h7dvfeu/fiY8ArCDGCERSC4FCEhCE0HGERiDYZMSWj7xSZE6pZJSFH8rxfCpJTkZKG1HSkZSA9E9n@Mmsg@8hZRahRPE9eguJSlJShtBxlFSivREXV1gmo3xh/AQ "APL (Dyalog Unicode) – Try It Online") Slower, but still can handle 100 items in around 5 seconds. ### How it works: the concept This solution uses a systematic way to generate all possible singly lossy integers from the list `1..n`. It is equivalent to selecting three members from `1..n`: * Select three distinct integers `a < b < c` from `1..n`. * Take the inclusive range `a..c` and discard `b`. ``` Original list: 1 2 3 4 5 6 7 8 9 Selection: ^ ^ ^ a b c Take a..c: 2 3 4 5 6 7 Discard b: 2 4 5 6 7 Result: 24567 ``` I use `dfns.cmat` to generate all 3-combinations, generate all singly lossy numbers, sort them and take first `n` elements. We need length `n+2` for the combinations because lower numbers won't give enough number of items. ### How it works: the code ``` ⎕CY'dfns' ⍝ Import dfns library, so that we can use cmat ⍝ Inner function: generate enough singly lossy integers {(⍋⊃¨⊂)⍵{a b c←⍵-1 0⍺⋄⍎dab⍕c↓a↓b~⍨⍳⍺}¨↓3cmat⍵} ⍝ Input: 2+n ⍵{...}¨↓3cmat⍵ ⍝ Generate all 3-combinations, and get singly lossy integers 3cmat⍵ ⍝ 3-combinations of 1..2+n ⍵{ }¨↓ ⍝ Map the inner function to each row of above, with left arg 2+n a b c←⍵-1 0⍺⋄⍎' '~⍨⍕c↓a↓b~⍨⍳⍺ ⍝ From 3-combination to a singly lossy integer a b c←⍵-1 0⍺ ⍝ Setup the numbers so that ⍝ "remove b, drop first a and last c elements" gives desired value ⍎dab⍕c↓a↓b~⍨⍳⍺ ⍝ Compute the target number c↓a↓b~⍨⍳⍺ ⍝ Remove b, drop first a and last c elements from 1..2+n ⍎dab⍕ ⍝ Concat the numbers (dab stands for Delete All Blanks) (⍋⊃¨⊂) ⍝ APL idiom for sorting ⊢↑∘{...}2+⊢ ⍝ Outer function; input: n ∘{...}2+⊢ ⍝ Pass 2+n to the inner function ⊢↑ ⍝ Take first n elements from the result ``` --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 49 bytesSBCS ``` ⊢↑∘{∧⍵{a b c←⍵-1 0⍺⋄⍎⌂dab⍕c↓a↓b~⍨⍳⍺}¨↓3⌂cmat⍵}2+⊢ ``` [Try it online!](https://tio.run/##JVE9bpVBDOw5xfQo0vrfrmlIhUS4wEteQhN@FFGAolAAikLgPYFQJFpoSEeBaChzlO8iYQ3FjkbesT22V8@Pd9avVsfPHu8cvnxx@HR9uL69XS6/L@efl4uvp8vFj2Xz@3SFfRws558m3yGMZfNn@fBu2WyXj2/Wq/1lczU/v6zm23@9bK6Xza@pOLu5ngGZkoMnqxcz84zvzsK3R//qbJft1e6D5fLtzU/pXturvYf3Jj66v7t3ezIlR8v7b/9NkIAVYlCHBTwRBZohEgXPOKtB5qeYQ6dCPWBTZpHwqfUsJA0UEWgQg2jWJKZZovOpC5BQQzMlBxkFyClBQbNd8gAVE3gwg2cemLn78zTQ3bnbs3JDM@MAOyc4uMApA1xCkCEMIRHIzIOItHuZ9tu7tHkxaWjmkpCQgqQOSClBhzKUVKCsCm3Pqtqz6xy@J9ceXV0bmoUWNG1Aywg2jGFkAmNTmJjB2rOZ9eZsrq73Zr04C2tolj5g5QQfznBygbMrXNzg6g5vz@7ee/defAx4BSFGMIJCEByKkDCEhiMsAtEmI2bL6DtF5oRqVknIkTzvl4LkVKSkITUdaRlIz0S2v8wayD5yVhFqFM@Tl6C4FCVlKC1HWQXKK1FRdecE1G/8BQ "APL (Dyalog Extended) – Try It Online") Simply uses extra built-ins provided in Extended version (dfns library pre-loaded as `⌂` functions, `∧` for ascending sort). [Answer] # Haskell, ~~131~~, ~~114~~, 106 bytes ``` iterate(\n->minimum[x|x<-[read(show=<<filter(/=k)[i..j])::Int|i<-[1..n],j<-[i+2..n],k<-[i+1..j-1]],x>n])13 ``` This is limited by the size of `Int`, but it can be easily extended by replacing `Int` with `Integer`. Less golfed: ``` concatInt x = read (concatMap show x) ::Int allUpToN n = [concatInt $ filter (/=k) [i..j] | i <- [1..n], j <- [i+2..n], k <- [i+1..j-1]] f n = minimum[x | x <- allUpToN, x > n ] iterate f 13 ``` 8 bytes golfed by @nimi. [Answer] # Mathematica, 101 bytes ``` Sort@Flatten@Table[FromDigits[""<>ToString/@(z~Range~x~Delete~y)],{x,3,#},{z,1,x-1},{y,2,x-z}][[1;;#]]& ``` Yay! For once I have the shortest answer! `Party[Hard]` [Answer] ## Python 3, ~~136~~ ~~127~~ ~~126~~ 122 bytes brute force solution, I don't even try n=7000 (it already take 10s for n = 100) ``` r=range f=lambda n:sorted(int(''.join(str(i+k)for i in r(1,j)if l-i))for k in r(n)for j in r(4,n)for l in r(2,j-1))[:n] ``` ## Explanation ``` # f=lambda n:sorted( int(''.join(str(i+k) for i in r(1,j) if l-i)) for k in r(n) for j in r(4,n) for l in r(2,j-1))[:n] # ──┬── ───────┬─────── ───┬── ──────┬────── ──────┬────── ────────┬──────── ─┬─ # │ │ │ │ │ │ └── selection of the n first numbers # │ │ │ │ │ └── loop to remove missing element # │ │ │ │ └── loop for the dimension of the list n to be sure we miss nothing xD # │ │ │ └── loop on the n in op description # │ │ └── Test to remove missing element # │ └── loop on {n, n+1 ...} in the op description # └──── sort the list ``` ## Results ``` >>> f(25) [13, 24, 35, 46, 57, 68, 79, 124, 134, 235, 245, 346, 356, 457, 467, 568, 578, 679, 689, 810, 911, 1012, 1113, 1214, 1235] >>> f(100) [13, 24, 35, 46, 57, 68, 79, 124, 134, 235, 245, 346, 356, 457, 467, 568, 578, 679, 689, 810, 911, 1012, 1113, 1214, 1235, 1245, 1315, 1345, 1416, 1517, 1618, 1719, 1820, 1921, 2022, 2123, 2224, 2325, 2346, 2356, 2426, 2456, 2527, 2628, 2729, 2830, 2931, 3032, 3133, 3234, 3335, 3436, 3457, 3467, 3537, 3567, 3638, 3739, 3840, 3941, 4042, 4143, 4244, 4345, 4446, 4547, 4568, 4578, 4648, 4678, 4749, 4850, 4951, 5052, 5153, 5254, 5355, 5456, 5557, 5658, 5679, 5689, 5759, 5789, 5860, 5961, 6062, 6163, 6264, 6365, 6466, 6567, 6668, 6769, 6870, 6971, 7072, 7173, 7274, 7375] ``` *Thanks to @mbomb007 and @FricativeMelon for their help* [Answer] # Python 3, ~~319~~, ~~270~~, 251 bytes ``` t,h,n,k,q*=range,input(),1,2, while h>len(q)or n*k<=len(str(q[h])): q+=[int("".join([str(c+s)for c in t(k+1)if c-y]))for s in t(10**~-n,10**n)for y in t(1,k)] if~-n:n*=k;k+=1 else:n,k=k+1,2 while n//k*k-n:k+=1 n//=k;q.sort() print(q[:h]) ``` Takes an `h` as input from STDIN and prints an array of the first `h` singly-lossy integers. It is very fast as well, taking only a few seconds for `h=7000`. **Explanation:** Note that, if we had infinite time, we could simply iterate over all `n,k` and for each pair drop each of `n+1,n+2,...,n+k-1` (`k-1` possibilities), and get all (infinitely many) values from those, then just sort the sequence in ascending order and truncate to `h` elements. Of course, we cannot actually do that, but if we can reach a point where the first sorted `h` elements can no longer change by adding the values of any future `n,k` pairs, we can just truncate then and be done, in finite time. For any `n,k` pair, it has at least `floor(log10(n)+1)*k` digits, possibly more. So lets group these pairs by the value `c(n,k)=floor(log10(n)+1)*k`, where we guarantee that if `c(a,b)<c(n,k)`, we process `a,b` before `n,k`. If we have the list sorted, and its last element has `d` digits, and `d<c(n,k)` for the next `n,k` we are going to process, we can stop, since we can no longer get a number with that many or fewer digits, since by our guarantee we should have already processed it then, and therefore no matter which numbers we would end up computing, the first `h` elements can not change, so we can just return them. So now we just need the function that guarantees the stated order on `c(n,k)`. For each `y` obtainable for `c(n,k)`, we must process all `(n,k)` such that `y=c(n,k)`. Let's say `L=floor(log10(n)+1)` for some `n`. Therefore `y=L*k` must hold. Start with `k=2,L=y/2`, then do `k=3,L=y/3;k=4,L=y/4...k=y,L=1`, skipping non-integer values of `L`. To generate the whole `c(n,k)` function, start with `(1,2)` with `y=2`, and increase `y` by 1 and start again whenever you get `L==1`. Now we have an enumeration of pairs `(L,k)`, and it satisfies our condition. However, we need to retrieve all possible `n` from `L`, which we do by enumerating all integers with `L` digits. Then for each of those `(n,k)` pairs, for each of the `k-1` possible dropped elements we must generate the lossy number we get as a result, and add it to our list, which starts empty. Then we sort the list and repeat on the next `(L,k)` pair, stopping when we have `d<c(n,k)` as stated before. Code breakdown (a little outdated): ``` t=range #shortens code def f(r,n,k): #helper function for s in t(10**~-n,10**n): #for the (L,k) pair, add value of (s,k,y) for y in t(1,k):r+=[(int("".join(map(str,[c+s for c in t(k+1)if c!=y]))))] if n>1: #case where L!=1 n*=k;k+=1 #multiply n (which is n'/k from prev iter), inc k else:n,k=k+1,2 #reset n and k while n//k*k-n:k+=1 #find next proper divisor of n return(r,n//k,k) #divide by that divisor and return def g(h): #main function q,a,b=[],1,2 #initial values while h>=len(q)or a*b<=len(str(q[h])):(q,a,b)=f(q,a,b);q.sort() return q[:h] #continues until at least h numbers and surpassed current max ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` ∞ʒ.œD0Å?_*€¥1cP2å ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//@KInsqSLsWTRDDDhT9fKuKCrMKlMWNQMsOl//8 "05AB1E – Try It Online") Prints the singly lossy integers forever. ]
[Question] [ # X Marks the spot Your goal is to add a cross-hair around the capital X: ## Example Input / Output Input: ``` mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss yyyhhhsosyhhmmmmdmmm mhyhhhy y ssyhoho o shhdmmmmdmmmm hhyyyh s oo syysyyhhdysso oyhdhhhmmmmm dhysyys sdysoXoyyyyhhso syshm mmm hhyhyo o osss y shhyyhd mmmmmm yyhyyyss o oyyyydmmdmmmmmmmmm mm ysyhyhhho s osy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ``` Output: ``` mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss | yyyhhhsosyhhmmmmdmmm mhyhhhy y |ssyhoho o shhdmmmmdmmmm hhyyyh s oo s|ysyyhhdysso oyhdhhhmmmmm dhysyys -----X-----hhso syshm mmm hhyhyo o | osss y shhyyhd mmmmmm yyhyyyss |o oyyyydmmdmmmmmmmmm mm ysyhyhhho s |sy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ``` --- Input: ``` 000000000000 000000000000 0000X0000000 0000000X0000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 ``` Output: ``` | 0000|00|0000 0000|00|0000 -----X--+--00 00--+--X----- 0000|00|0000 0000|00|0000 0000000|0000 000000000000 000000000000 000000000000 000000000000 000000000000 ``` --- Input: ``` 00000000000000000 00000000000000000 00000000000000000 00000X000X0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ``` Output: ``` 00000|000|0000000 00000|000|0000000 00000|000|0000000 ----+#+++#+----00 00000|000|0000000 00000|000|0000000 00000|000|0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ``` ## Crosshair Your cross-hair should be a 3-tall and 5-wide: ``` | | | -----X----- | | | ``` ### Input Input will be at least 12x12 characters in size and will consist of only ASCII characters. It can be taken in through STDIN or function argument. The input will not always contain an X. Input will be in any shape and have an arbitrary amount of whitespace. The input will not contain any of: `+`, `-`, `#`, and `|` ### Output Output can be through STDOUT or a function's return value. Output should be the input image with the cross-hair drawn. If there is not enough space to draw the crosshair, you must add lines / spaces to draw it. Overlapping spots should be replaced with a `+`. If the `|` or `-` of the crosshairs overlaps an `X`, instead of a `+`, an `#` should appear. Trailing whitespace is not allowed *except* for a single newline at the very end. --- This is code-golf so shortest code in bytes wins! [Answer] # CoffeeScript, ~~345~~ ~~336~~  327 bytes ``` Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ``` `X` is the function to call. ### Explained: ``` # get new char. s - old char. c - '|' or '-' Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)-> # leftmost and upmost positions l=u=0 # split input into 2D array o=(r.split ''for r in s.split '\n') # for every 'X' or '#' c in'X#'&&( # for positions to left and right i-x&&( # draw horisontal line o[y][i]=Z o[y][i],'-' # update leftmost position i<l&&l=i )for i in[x-5..x+5] # for positions above and below i-y&&( # add row if necessary and draw vertical line (o[i]?=[])[x]=Z o[i][x],'|' # update upmost position i<u&&u=i )for i in[y-3..y+3] )for c,x in r for r,y in o # concatenate into string, replacing empty chars with spaces ((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ``` ### Executable: ``` <script src="http://coffeescript.org/extras/coffee-script.js"></script> <script type="text/coffeescript"> Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ################################################################################ # tests follow s = [''' mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss yyyhhhsosyhhmmmmdmmm mhyhhhy y ssyhoho o shhdmmmmdmmmm hhyyyh s oo syysyyhhdysso oyhdhhhmmmmm dhysyys sdysoXoyyyyhhso syshm mmm hhyhyo o osss y shhyyhd mmmmmm yyhyyyss o oyyyydmmdmmmmmmmmm mm ysyhyhhho s osy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ''' ''' 000000000000 000000000000 0000X0000000 0000000X0000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 ''' ''' 00000000000000000 00000000000000000 00000000000000000 00000X000X0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ''' 'X' 'XX\nXX' ] document.write '<pre>' document.write '\n\n',X x for x in s </script> ``` [Answer] # Python 3, ~~577~~ ~~519~~ ~~515~~ ~~490~~ ~~475~~ ~~467~~ 454 bytes ``` def c(g,d): R,L,V,e,b=range,list,len,'-|+','#';t,g=(lambda g,d:sum([[(i,j)for j in R(V(L(g.split('\n')[i])))if g.split('\n')[i][j]==d]for i in R(V(g.split('\n')))],[]))(g,d),[L(i)for i in g.split('\n')] for a,r in t: for j in R(a-3,a+4): if V(g)>j>-1:n=g[j][r];g[j][r]='+'if n in e else'#'if n in(d,b)else'|' for j in R(r-5,r+6): if V(g[a])>j>-1:n=g[a][j];g[a][j]='+'if n in e else'#'if n in(d,b)else'-' return'\n'.join(''.join(l)for l in g) ``` I'm not sure how much farther I can golf this. ### Usage: ``` c(g, d) ``` Where `g` is the input grid and `d` is the crosshair-marking character. [Answer] # Perl, 370 bytes ``` sub r{$h=pop;($=[$n=pop].=$"x(1+"@_"-length$=[$n]))=~s!(.{@_})(.)!"$1".($2=~/[-|+]/?'+':$2=~/[X#]/?'#':$h)!e}map{chop;push@c,[$-,pos]while/X/g;$-++}@==<>;($x,$y)=@$_,3-$x>$a?$a=3-$x:0,$x+5-@=>$b?$b=$x+5-@=:0,6-$y>$c?$c=6-$y:0 for@c;@==($",@=)for 1..$a;$_=$"x$c.$_ for@=;map{($x,$y)=@$_;$_&&r$y+$c+$_-1,$x+$a,'-'for-5..5;$_&&r$y+$c-1,$x+$_+$a,'|'for-3..3}@c;print@=,$,=$/ ``` Usage, save above as `xmarks.pl`: `perl xmarks.pl <<< 'X'` I'm not sure how much smaller I can make this, but I'm sure I'll come back to it later! I might post an explanation if anyone is interested too. Handles input of `X` and non-square inputs as well now. [Answer] # Python 2, ~~755 706 699 694 678~~ 626 Bytes Expects input on stdin, with a trailing newline. The end of input is triggered with `cmd+d`. ``` import sys;a=sys.stdin.readlines();b=max;c=len;d=enumerate;e=c(b(a,key=lambda x:c(x)))-1;a=[list(line.replace('\n','').ljust(e))for line in a];R=range;f=lambda:[[i for i,x in d(h)if x=='X']for h in a+[[]]*4];q=lambda y,z:'#'if z=='X'else'+'if z in'|-+'else y;g=f();h=j=k=l=0 for m,n in d(g): if n:h=b(3-m,h);l=b(abs(n[0]-5),l);j=b(m-c(a)+4,j);k=b(n[-1]-e+6,k) o=[' ']*(l+k+e);a=[o for _ in R(h)]+[[' ']*l+p+[' ']*k for p in a]+[o for _ in R(j)];g=f() for m,x in d(a): for i in[3,2,1,-1,-2,-3]: for r in g[m+i]:x[r]=q('|',x[r]) for r in g[m]: for i in R(5,0,-1)+R(-1,-6,-1):x[r+i]=q('-',x[r+i]) for s in a:print''.join(s) ``` Full program: ``` import sys lines = sys.stdin.readlines() # pad all lines with spaces on the right maxLength = len(max(lines, key=lambda x:len(x))) - 1 # Subtract the newline lines = [list(line.replace('\n', '').ljust(maxLength)) for line in lines] def findX(): global xs xs = [[i for i, ltr in enumerate(line) if ltr == 'X'] for line in lines+[[]]*4] # add sufficient padding to the edges to prevent wrap findX() top,bottom,right,left=0,0,0,0 for ind, item in enumerate(xs): if item: top = max(3-ind, top) left = max(abs(item[0]-5), left) bottom = max(ind-len(lines)+4, bottom) right = max(item[-1]-maxLength+6, right) clear = [' '] * (left+right+maxLength) lines = [clear for _ in range(top)] + [[' ']*left + line + [' ']*right for line in lines] + [clear for _ in range(bottom)] findX() def chooseChar(expected, curr): return '#' if curr == 'X' else ('+' if curr in '|-+' else expected) for ind, x in enumerate(lines): # try: for i in [3, 2, 1, -1, -2, -3]: for elem in xs[ind+i]: x[elem] = chooseChar('|', x[elem]) for elem in xs[ind]: for i in [5, 4, 3, 2, 1, -1, -2, -3, -4, -5]: x[elem+i] = chooseChar('-', x[elem+i]) # except:f for line in lines: print(''.join(line)) ``` I'm sure that a lot more golfing could be done on this (since I'm still learning python), so any help is appreciated. ## Edits 1. Shaved about 50 bytes from `findX` by using for comprehensions 2. Saved 7 bytes thanks to @mbomb007's suggestion about using `range` instead of a literal array 3. Removed 5 bytes by changing `findX` to a lambda 4. Saved 15 bytes by extending `xs` by 4 and eliminating the `try-except` block 5. Shaved 2 more by using tabs instead of spaces 6. Removed 5 bytes by using `h=i=j=k=l=0` instead of `h,j,k,l=0,0,0,0` 7. Thanks to @mbomb007, I removed about 40 more bytes from `chooseChar` ]
[Question] [ In Dungeons and Dragons, some of the most important atributes of a character are the ability scores. There are 6 ability scores, for the six abilities. The abilities are Strength, Dexterity, Constitution, Intelligence, Wisdom and Charisma. When determining the scores for a character, I use the following procedure: Roll 4d6, drop the lowest, in any order. What this means is that I roll 4 six sided dice, ignore the lowest result, and sum the other 3. This is done 6 times. The resulting numbers are assigned to the abilities in any way I please. The system I use for assigning scores to abilities is to assign the highest score to my character's most important skill, which depends on my character's class, assign the second highest score to Constitution, since everyone needs Constitution, and assign the other four scores arbitrarily. Here's a table of the most important skills for various classes: ``` Bard - Charisma Cleric - Wisdom Druid - Wisdom Fighter - Stregth Monk - Wisdom Paladin - Charisma Rogue - Dexterity Sorcerer - Charisma Wizard - Intelligence ``` **Challenge:** I'll give you (as input) the first letter of my character's class (In uppercase). I'd like you to roll the abilities scores and assign them to the abilities as described above, and then output them in the order Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma. **Example:** ``` Input: R Rolls: 4316 3455 3633 5443 2341 6122 Scores: 13 14 12 13 9 10 Ordering: Highest goes to dexterity. Second goes to Constitution. Output: 13 14 13 12 9 10 or Output: 9 14 13 10 12 13 or etc. ``` Output may be given in any format where the numbers are clearly separated and in the proper order. Shortest code in bytes wins. Standard loopholes banned. [Answer] # CJam, ~~43~~ ~~41~~ 40 bytes ``` {6a4*:mr$0Zt:+}6*]$2m<"FRXWCDM"r#4e<3e\p ``` *Thanks to @Sp3000 for golfing off 1 byte.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B6a4*%3Amr%240Zt%3A%2B%7D6*%5D%242m%3C%22FRXWCDM%22r%234e%3C3e%5Cp&input=W). ### How it works ``` { }6* e# Repeat 6 times: 6a4* e# Push [6 6 6 6]. :mr e# Replace each six with a pseudo-randomly e# generated integer in [0 ... 5]. $ e# Sort the results. 0Zt e# Replace the lowest result by 3. :+ e# Add all four integers ] e# Wrap the 6 generated integers in an array. $ e# Sort. 2m< e# Rotate 2 units to the left to assign the e# second highest result to Constitution. "FRXWCDM" e# Push that string. r# e# Find the index of the input. e# The string doesn't contain B, P or S, so e# those push -1. 4e< e# Truncate the index at 4. This way, C, D e# M all push 4. 3e\ e# Swap the integer at that index with the e# one at index 3, i.e., the highest one. p e# Print. ``` [Answer] # Python 3, 137 bytes ``` from random import* S=sorted *L,c,h=S(3+sum(S(map(randrange,[6]*4))[1:])for _ in[0]*6) L[:"FRW BPS".find(input())]+=h, L[:2]+=c, print(L) ``` Outputs a list of integers, e.g. `[14, 9, 13, 12, 12, 13]` for `F`. The mapping from the input char to assignments turned out to be surprisingly nice. First we start by having `L` contain the lowest 4 rolls, after which we want to insert * The highest roll into the correct position based on the input, then * The second-highest roll into index 2, for Constitution. For each input, the indices we want for the highest rolls are: ``` Index Ability Input(s) ---------------------------------- 0 Strength F 1 Dexterity R 2 Intelligence W 3 Wisdom CDM 4 Charisma BPS ``` Amazingly, we only need `"FRW BPS".find(input())` for this, because: * `FRW` work as expected, giving their respective indices, * `CDM` are not present so `find` gives `-1`, which for a 4-element list is index 3, and * `BPS` give 4, 5, 6 respectively, but it doesn't matter if we overshoot because we can only append an element at the end. [Answer] # J, ~~100~~ 97 bytes ``` (0;0,b)C.^:(b>0)(0;1 2)C.\:~+/"1]1}."1/:~"1]1+?6 4$4$6[b=.('BCDFMPRSW'i.1!:1[1){5 4 4 0 4 5 1 5 3 ``` Takes input in `STDIN` [Answer] # C++ - 387 bytes First attempt here, more golfing required, particularly in determining what class is being used. Golfed: ``` #include<cstdlib> #include<cstdio> #include<time.h> int main(int c,char**v){char*o=*v,l=*v[1];int b=-1,s=-1,i=6,x=0,q=l>=67&&l<=68||l==77?4:l==70?0:l==87?3:l==82?1:5;srand(time(0));for(;i-->0;){int w=9,d=4,u=3,t;for(;d-->0;){t=rand()%6;if(t<w){u+=w<9?w:0;w=t;}else u+=t;}if(u>s){c=s;s=u;u=c;}if(s>b){c=s;s=b;b=c;}if(u>=0)o[x++]=u;}for(i=0;i<6;i++)printf("%d ",i==2?s:(i==q?b:o[--x]));} ``` Rather ungolfed: ``` #include<cstdlib> #include<cstdio> #include<time.h> int main(int c,char**v) { //name of program must be at least 4 chars char*others=*v,clas=*v[1]; int desired = clas>=67&&clas<=68||clas==77?4:clas==70?0:clas==87?3:clas==82?1:5; //TODO: srand(time(0)); int best=-1,second=-1,i=6,otherIndex=0; for(;i-->0;) { int lowest=9,diecount=4,sum=3; for(;diecount-->0;) { int loc=rand()%6; if (loc<lowest) { sum+=lowest<9?lowest:0; lowest=loc; } else { sum+=loc; } } if(sum>second) { c=second;second=sum;sum=c; } if(second>best) { c=second;second=best;best=c; } if(sum>=0) { others[otherIndex++]=sum; } } for(i=0;i<6;i++) { printf("%d ",i==2?second:(i==desired?best:others[--otherIndex])); } getchar(); } ``` ]
[Question] [ This image was made by overlaying 7 differently colored rectangles on top of each other: [![main image](https://i.stack.imgur.com/IVYvE.png)](https://i.stack.imgur.com/IVYvE.png) The black and maroon rectangles are *unobstructed*, that is, no other rectangles are above them. Write a program that takes in an image such as this and remove any single unobstructed rectangle, outputting the resulting image. > > ### Example > > > If you ran your program on the image above and kept re-running it on the output, it might progress like this. > > > Run 1 - Black removed (could have been maroon): > > > ![run 1](https://i.stack.imgur.com/a79qM.png) > > > Run 2 - Maroon removed (only choice): > > > ![run 2](https://i.stack.imgur.com/XBC68.png) > > > Run 3 - Yellow removed (only choice): > > > ![run 3](https://i.stack.imgur.com/77he7.png) > > > Run 4 - Blue removed (could have been green): > > > ![run 4](https://i.stack.imgur.com/s5fGy.png) > > > Run 5 - Green removed (only choice): > > > ![run 5](https://i.stack.imgur.com/R5Z8S.png) > > > Run 6 - Brown removed (only choice): > > > ![run 6](https://i.stack.imgur.com/ZO0fN.png) > > > Run 7 - Red removed (only choice): > > > ![run 7](https://i.stack.imgur.com/3Ice2.png) > > > Any additional runs should produce the same white image. > > > Hopefully Stack Exchange has not lossily compressed any of these > images. > > > The image will always have a white background and each rectangle will be a unique RGB color that isn't white. You can assume that the image can always be interpreted as a set of overlapping rectangles. Specifically, you can assume that, for a particular color, the pixel with that color closest to the top of the image is part of the top edge of that color's rectangle. The same holds for the bottom, left, and right edges. So, for example, in this image, the top edge of the red rectangle would be just below the bottom edge of the yellow rectangle, as the the orange rectangle covered the old red top edge: ![example 1](https://i.stack.imgur.com/jPwXT.png) In this image, the red rectangle could be removed first (along with black/maroon/orange/gray): ![example 2](https://i.stack.imgur.com/niI44.png) When the order of the lower rectangles is ambiguous, you can give them any order. For example, the left image here could become the middle or the right: > > ![example 3](https://i.stack.imgur.com/UDh6e.png) ![example 4](https://i.stack.imgur.com/s3u8d.png) ![example 5](https://i.stack.imgur.com/lb20w.png) > > > The output should not have paradoxical overlaps (so making it with the [painter's algorithm](http://en.wikipedia.org/wiki/Painter%27s_algorithm) should be possible). So in this image ([thanks user23013](https://codegolf.stackexchange.com/questions/48272/remove-an-unobstructed-rectangle#comment113498_48272)), it would have to be green under the orange rectangle: ![example 6](https://i.stack.imgur.com/7M4ty.png) ## Additional Details * The image and rectangles may have any dimensions. * The rectangles may touch the image border. * There may be up to 2563 - 1 rectangles. * If the input is entirely white, the output should be as well. * You may use image libraries. * The input should be the image file name or the raw image data. It can come from stdin or the command line. * The output can be written to the same or another image file, spewed raw to stdout, or simply displayed. * Any common lossless [truecolor](http://en.wikipedia.org/wiki/Color_depth#True_color_.2824-bit.29) image file format is allowed. The submission with the fewest bytes wins. [Answer] # CJam, 241 bytes (with newlines removed.) ``` rri:Hri:Vri:Q[q~]3/_Qa3*a+_|$W%:Pf{\a#}:AH/:B0ff* P,,[AHAW%HBz:+_W%V\V]2/ ff{~@@f=/::|1#}0Ua4*t:R; P0f< V{H{BI=J=_2$= 0R{"I>! I+V<J>! J+H<"4/+4/z{~~}%:&1$*\)}%);2$-|t }fJ}fI [P,{_La#\1$0t1$f-}*;;] {:TR=2/~\~V\-,>\f{\_3$=@~H\-,>{Tt}/t}~}/ :~Pf=:~ ~]S*N ``` It uses the ppm file format. Example usage (using ImageMagick): ``` convert IVYvE.png -compress none ppm:-| (time /path/to/cjam-0.6.4.jar 1.cjam) |display ``` Well, it is too long and too slow... Runs about a minute for the example. I resized the test cases (and added some others) to make testing easier. > > ![](https://i.stack.imgur.com/Unbio.png) ![](https://i.stack.imgur.com/UPWcX.png) ![](https://i.stack.imgur.com/zG2C8.png) > > > ![](https://i.stack.imgur.com/ZNGaS.png) ![](https://i.stack.imgur.com/PJWx5.png) ![](https://i.stack.imgur.com/8eDQ9.png) > > > ![](https://i.stack.imgur.com/aBLPf.png) ![](https://i.stack.imgur.com/uLv16.png) ![](https://i.stack.imgur.com/c54Sr.png) > > > ![](https://i.stack.imgur.com/9a6WF.png) ![](https://i.stack.imgur.com/4ixCi.png) ![](https://i.stack.imgur.com/xsoWC.png) > > > It seems the color space informations are lost so the colors are slightly different. [Answer] # Python, ~~690~~ ~~651~~ ~~610~~ ~~606~~ ~~594~~ 569 bytes The script reads the image name from stdin. It detects the edges of every rectangles, sort them by the number of different colors they contain (the unobstructed rectangles contains only 1 color, and then appear at the end of the list) This list is used to redraw an image. The redraw order is decided by choosing the permutation of the list that would generate an output image that have the least pixel difference with the input. ``` from PIL import Image as l,ImageDraw as D;from itertools import*;O,R,I,Z,k=[],range,l.open(raw_input()),{},lambda x:-x[1];(W,H),Q=I.size,I.load() for i,j in product(R(W),R(H)): c=Q[i,j] if c in Z:x,y,X,Y=Z[c];Z[c]=[x,y,max(X,i),max(Y,j)] else:Z[c]=[i,j,0,0] for n in permutations(sorted([(c,len({Q[g] for g in product(R(x,X),R(y,Y))})) for c,(x,y,X,Y) in Z.items()],key=k)[1:-1]):o=l.new(I.mode,I.size,0xFFFFFF);[D.Draw(o).rectangle(Z[c],fill=c) for c,_ in n];O+=[(o,sum(abs(a-b) for t,T in zip(I.getdata(), o.getdata()) for a,b in zip(t,T)))] max(O,key=k)[0].show() ``` [Answer] # Java - 1483 bytes I'm not a great code golfer, let that be clear; so the verbosity is not entirely Java's fault ;-) Nevertheless, this seemed like a really fun challenge. I've solved it in a way that - I think - is a bit boring and verbose, but hey. It works, it's (relatively) fast and, especially, it was fun! The idea is as follows: Check each pixel from starting at the top left corner all the way to bottom right. Is it a white pixel? Ignore. Is it coloured? Cool, let's keep track of it and try to determine its boundaries (top left, top right, bottom left, bottom right). Once that's done, check each rectangle's area. Does it contain a different colour than the rectangle's colour? Then find out what rectangle belongs to that colour and update that overlapping rectangle's z-index by 1. And finally, draw all rectangles while taking the z-indices into account. It works actually like a z-index you know from CSS and other 3D stuff. The rectangles with the lowest z-index are drawn first, the highest z-index last. ``` import java.awt.*;import java.awt.image.*;import java.io.File;import java.util.*;import java.util.List;import javax.imageio.*;class A{class R{public Color k=new Color(-1);public int z;public Point a;public Point b;public Point c;public Point d;}public static void main(String[]w)throws Exception{BufferedImage i=ImageIO.read(new File(w[0]));List<R>r=new Vector<R>();for(int y=0;y<i.getHeight();y++){for(int x=0;x<i.getWidth();x++){Color c=new Color(i.getRGB(x,y));if(c.getRGB()==-1){continue;}R t=null;for(R s:r){if(s.k.equals(c)){t=s;}}if(t==null){t=new A().new R();r.add(t);}if(t.a==null){t.a=new Point(x, y);t.b=new Point(x, y);t.c=new Point(x, y);t.d=new Point(x, y);t.k=new Color(c.getRGB());}if(x<t.a.x){t.a.x=x;t.c.x=x;}if(x>t.b.x){t.b.x=x;t.d.x=x;}t.c.y=y;t.d.y=y;}}for(R s:r){List<Color>b=new Vector<Color>();for(int y=s.a.y;y<=s.c.y;y++){for(int x = s.a.x;x<=s.b.x;x++){if(i.getRGB(x, y)!=s.k.getRGB()){Color a=new Color(i.getRGB(x,y));boolean q=false;for(Color l:b){if(l.equals(a)){q=true;}}if(!q){b.add(a);} else {continue;}R f=null;for(R k:r){if(k.k.equals(a)){f=k;}}f.z=s.z+1;}}}}Collections.sort(r,new Comparator<R>(){public int compare(R a, R b){return a.z>b.z?1:(a.z==b.z?0:-1);}});for(int ii=r.size();ii>0;ii--){BufferedImage d=new BufferedImage(i.getWidth(),i.getHeight(),2);Graphics2D g=(Graphics2D)d.getGraphics();for(R s : r.subList(0, ii)){g.setColor(s.k);g.fillRect(s.a.x,s.a.y,s.b.x-s.a.x,s.c.y-s.a.y);}ImageIO.write(d,"png",new File(r.size()-ii+".png"));}}} ``` The complete code which is a bit - and that's an understatement ;-) - written more clearly, can be found here: <http://pastebin.com/UjxUUXRp> Also, now that I see dieter's submission, I could have made some parts easier. It's not really necessary to find the rectangle whose colour is overlapping another rectangle. I could indeed just count the number of 'invading' colours. ]
[Question] [ ## Local periods Take a non-empty string **s**. The *local period* of **s** at index **i** is the smallest positive integer **n** such that for each **0 ≤ k < n**, we have **s[i+k] = s[i-n+k]** whenever both sides are defined. Alternatively, it is the minimal length of a nonempty string **w** such that if the concatenation **w w** is placed next to **s** so that the second copy of **w** begins at index **i** of **s**, then the two strings agree wherever they overlap. As an example, let's compute the local period of **s = "abaabbab"** at (0-based) index 2. * Try **n = 1**: then **s[2+0] ≠ s[2-1+0]**, so this choice is not correct. * Try **n = 2**: then **s[2+0] = s[2-2+0]** but **s[2+1] ≠ s[2-2+1]**, so this is also not correct. * Try **n = 3**: then **s[2+0-3]** is not defined, **s[2+1] = s[2-3+1]** and **s[2+2] = s[2-3+2]**. Thus the local period is 3. Here is a visualization of the local periods using the second definition, with semicolons added between the two copies of **w** for clarity: ``` index a b a a b b a b period 0 a;a 1 1 b a;b a 2 2 a a b;a a b 3 3 a;a 1 4 b b a b a a;b b a b a a 6 5 b;b 1 6 a b b;a b b 3 7 b a;b a 2 ``` Note that **w** is not necessarily a substring of **s**. This happens here in the index-4 case. ## The task Your input is a nonempty string **s** of lowercase ASCII characters. It can be taken as a list of characters if desired. Your output shall be the list containing the local period of **s** at each of its indices. In the above example, the correct output would be **[1,2,3,1,6,1,3,2]**. The lowest byte count in each language wins. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test cases ``` a -> [1] hi -> [1, 2] www -> [1, 1, 1] xcxccxc -> [1, 2, 2, 5, 1, 3, 2] abcbacb -> [1, 4, 7, 7, 7, 3, 3] nininini -> [1, 2, 2, 2, 2, 2, 2, 2] abaabbab -> [1, 2, 3, 1, 6, 1, 3, 2] woppwoppw -> [1, 4, 4, 1, 4, 4, 4, 1, 4] qwertyuiop -> [1, 10, 10, 10, 10, 10, 10, 10, 10, 10] deededeededede -> [1, 3, 1, 5, 2, 2, 5, 1, 12, 2, 2, 2, 2, 2] abababcabababcababcabababcaba -> [1, 2, 2, 2, 2, 7, 7, 7, 7, 2, 2, 2, 19, 19, 5, 5, 2, 5, 5, 12, 12, 2, 2, 2, 7, 7, 5, 5, 2] ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~89~~ 86 bytes ``` . $`¶$<'¶ /(^|.+)¶.+/_(Lw$`^(.+)?(.*)(.+)?¶(?(1)|(.*))\2(?(3)$) $2$3$4 G`. %C`. N` 0G` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X49LJeHQNhUb9UPbuPQ14mr0tDUPbdPT1o/X8ClXSYjTAPLtNfS0NMGMQ9s07DUMNWtAApoxRkCOsaaKJpeKkYqxigmXe4Iel6ozkPBL4DJwT/j/PzEpMTEpKTEJAA "Retina – Try It Online") Edit: Saved 3 bytes thanks to @MartinEnder. Explanation: ``` . $`¶$<'¶ ``` Split the input at each character, creating a pair of lines, one for the prefix and one for the suffix of the prefix. ``` /(^|.+)¶.+/_( ``` Run the rest of the script on each resulting pair. ``` Lw$`^(.+)?(.*)(.+)?¶(?(1)|(.*))\2(?(3)$) $2$3$4 ``` Find all overlapping matches and list the results. (See below.) ``` G`. ``` Discard the empty match. ``` %C`. ``` Take the length of each match. ``` N` ``` Sort numerically. ``` 0G` ``` Take the smallest. The matching works by splitting the prefix and suffix into three parts. There are four valid cases to consider: ``` AB|BC B matches B to the left and B to the right B|ABC AB matches [A]B to the left and AB to the right ABC|B BC matches BC to the left and B[C] to the right BC|AB ABC matches [A]BC to the left and AB[C] to the right ``` The regex therefore only allows A and C to match on one side at a time. [Answer] # Java 8, ~~167~~ ~~154~~ 152 bytes ``` s->{int l=s.length,r[]=new int[l],i=0,n,k;for(;i<l;r[i++]=n)n:for(n=0;;){for(k=++n;k-->0;)if(i+k<l&i+k>=n&&s[i+k]!=s[i-n+k])continue n;break;}return r;} ``` -2 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##fVNNb6MwEL3vr/ByiEAYlGyarbYukao9by89RhyMcRoH11DblEQRvz07GBoFml2Nv@fN8xvLs6cfNCorrvZ5cWaSGoP@UKFO3xASynK9pYyj527rDjYpYj7bUQ0LExA4bqFDM5ZawdAzUihBZxOtT4BGMjGx5OrV7jBEJIo3jkSmWCRzrHBBtqX2iXiURG9EGAIkUA/dmUrmhASnblkkYahIEUXrOQnE1hdh8ShnMK4TNZsZiCvS7wnMkYJVwEplhao5UiTTnBak1dzWWiFN2jPp1VZ1JkHtIPqjFDl6g6z9F6uFet2kNOgzttxY36Me/lSenhatS/vTtxMjJ/4xdjdNM/aDjREHdmDQJixgK8Aup3w0Yxll2Rh9h@@dLfFyjFait6/kF5vSU5plNJsGLEHLz1t6mrKqXJ8qusP96OZxzHvDtT3WoqwmTzP/VxvH55znfBhyPubohK4uz7f4X6Jg7Gq6Wt9@rvvB@t3iV9dW7rJuhKsW10jnaW9UiPtsTkT/2ZDBfV3xQ8WZ5fnw9YYiE6qqLZSUiW35G46etKZHf8ilD9Tc1LLDqJj5Dj@4X47G8re4rG1cwVVWKn8P5R7XVsjYEXWsvQy/ZwlCD/le@AXG32sqzQDCF6mhF3hDju35Lw) **Explanation:** ``` s->{ // Method with char-array parameter and int-array return-type int l=s.length, // Length of the input-array r[]=new int[l], // Result-array of the same size i=0,n,k; // Integers `i`, `n`, and `k` as defined in the challenge for(;i<l; // Loop `i` in the range [0, `l`): r[i++]=n) // After every iteration: Add `n` to the array n:for(n=0;;){ // Inner loop `n` from 0 upwards indefinitely for(k=++n;k-->0;) // Inner loop `k` in the range [`n`, 0]: // (by first increasing `n` by 1 with `++n`) if(i+k<l&i+k>=n) // If `i+k` and `i-n+k` are both within bounds, &&s[i+k]!=s[i-n+k])// and if `s[i+k]` is not equal to `s[i-n+k]`: continue n; // Continue loop `n` // If we haven't encountered the `continue n` in loop `k`: break;} // Break loop `n` return r;} // Return the result ``` [Answer] # JavaScript (ES6), 84 bytes Takes input as an array of characters. ``` s=>s.map((_,i)=>s.some(_=>s.every(_=>k<j|!s[k]|s[k-j]==s[k++]|k-i>j,++j,k=i),j=0)*j) ``` ### Test cases ``` let f = s=>s.map((_,i)=>s.some(_=>s.every(_=>k<j|!s[k]|s[k-j]==s[k++]|k-i>j,++j,k=i),j=0)*j) console.log(JSON.stringify(f([...'a']))) // [1] console.log(JSON.stringify(f([...'hi']))) // [1, 2] console.log(JSON.stringify(f([...'www']))) // [1, 1, 1] console.log(JSON.stringify(f([...'xcxccxc']))) // [1, 2, 2, 5, 1, 3, 2] console.log(JSON.stringify(f([...'abcbacb']))) // [1, 4, 7, 7, 7, 3, 3] console.log(JSON.stringify(f([...'nininini']))) // [1, 2, 2, 2, 2, 2, 2, 2] console.log(JSON.stringify(f([...'abaabbab']))) // [1, 2, 3, 1, 6, 1, 3, 2] console.log(JSON.stringify(f([...'woppwoppw']))) // [1, 4, 4, 1, 4, 4, 4, 1, 4] console.log(JSON.stringify(f([...'qwertyuiop']))) // [1, 10, 10, 10, 10, 10, 10, 10, 10, 10] console.log(JSON.stringify(f([...'deededeededede']))) // [1, 3, 1, 5, 2, 2, 5, 1, 12, 2, 2, 2, 2, 2] console.log(JSON.stringify(f([...'abababcabababcababcabababcaba']))) // [1, 2, 2, 2, 2, 7, 7, 7, 7, 2, 2, 2, 19, 19, 5, 5, 2, 5, 5, 12, 12, 2, 2, 2, 7, 7, 5, 5, 2] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~104~~ 102 bytes ``` ->s{l=s.size-1 (0..l).map{|i|n=0 loop{n+=1 (n-i..l-i).all?{|k|k<0||k>=n||s[i+k]==s[i-n+k]}&&break} n}} ``` [Try it online!](https://tio.run/##dVHrboMgFP7PUxB/NG2qRme7ZstoH8SYBZCmRIdMNLYTn90hXtomW77DuX3nAqGsya0/o947qjZHylf8h3khWAe@n2/8LyxbzbVAAciLQrZiiwwnPG5Yj298nOenVmc6@wi0zo5IaK1ivs0ShIz1hPG61YqUDGcdEF3XV0xVnxQrpiCCMYAwdrDjwjhMEtdGF25D92VONE0zZgzm3JVeqZGp0mBv2OjegwklmJKR37kHi8iNZl7wEfcBC@4jMCYEk7kkMhten7c0hZT2zHt27qitnau@G1ZWt5oXcnpG8J/MHSljKZtUysauYf1@eWr494UN6IN58J8fepgwRuHbIHs7ftBmePhYaZkkAQkA99/zGaYXmBZQcyHryoXsKhmtWKrNZUqm6rwyH3yOLZuYnCy5qBYGLfXwBJ21xEptoAPfjX/GPDf@0DKVAybS/hc) A lambda accepting a string and returning an array. -2 bytes: Swap range endpoints with index bound guards Ungolfed: ``` ->s{ l=s.size-1 # l is the maximum valid index into s (0..l).map{ |i| # i is the current index n=0 # n is the period being tested loop{ # Repeat forever: n+=1 # Increment n (n-i..l-i).all?{ |k| # If for all k where i+k and i-n+k are valid indexes into s k<0 || k>=n || # We need not consider k OR s[i+k]==s[i-n+k] # The characters at the relevant indexes match } && break # Then stop repeating } n # Map this index i to the first valid n } } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~33~~ 32 bytes *Saved 1 byte thanks to @Shaggy* ``` ¬Ë@¯E f'$iUtED ú.D r."($&|^)"}aÄ ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rMs7QK9FIGYnJGlVdEVYIPouWCByLiIoJCZ8XikifWHE&input=ImFiYWFiYmFiIg==) ### Explanation ``` ¬Ë@¯E f'$iUtED ú.D r."($&|^)"}aÄ Implicit: U = input string ¬Ë Split the input into chars, and map each index E to @ }aÄ the smallest positive integer D where ¯E the first E chars of U f matches the regex formed by UtED taking D chars of U from index E, ú.D padding to length D with periods, r."($&|^)" replacing each char C with "(C|^)", '$i and placing a '$' at the very end. ``` My first thought was to just compare each character in the left substring with the corresponding char in the right substring, as in the JS answer. That wouldn't work, however, as Japt's method to get a character just wraps to the other end of the string if the index is negative or too large. Instead, my solution builds a regex out of the second substring and tests it on the first substring. Let's take the 5th item in test-case `abaabbab` as an example: ``` abaabbab ^ split point -> abaa for testing regex, bbab for making regex slice regex matches abaa 1. b /(b|^)$/ no 2. bb /(b|^)(b|^)$/ no 3. bba /(b|^)(b|^)(a|^)$/ no 4. bbab /(b|^)(b|^)(a|^)(b|^)$/ no 5. bbab. /(b|^)(b|^)(a|^)(b|^)(.|^)$/ no 6. bbab.. /(b|^)(b|^)(a|^)(b|^)(.|^)(.|^)$/ yes: /^^ab..$/ ``` The main trick is that `^` can match infinitely, up until an actual character is matched. This lets us ignore any number of characters from the start of the regex, while ensuring that the rest are all matched consecutively, finishing at the end of the test string. I'm not sure I've explained this very well, so please let me know if there's anything you'd like clarified, or anything else that should be explained. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~143~~ ~~142~~ ~~140~~ ~~139~~ ~~128~~ ~~126~~ ~~123~~ 119 bytes * Saved a byte. Golfed `!b&&printf` to `b||printf`. * Saved two bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). Removed the `for` loop body parentheses by juggling the `printf` placement. * Saved a byte. Golfed `b+=S[i+k]!=S[i-n+k]` to `b|=S[i+k]-S[i-n+k]`. * Saved eleven bytes. Removed the need of `l=strlen(S)` by conditioning both string handling loop to break when reaching the string's end (a null byte `'\0'`). * Saved two bytes. Golfed `i-n+k>~0` to `i-n>~k`. * Saved three bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); `b||printf("|"),n++` is equivalent to `n+=b||printf("|")`. * Saved four bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` i,b,k,n;f(char*S){for(i=~0;S[++i];)for(b=n=1;b;n+=b||printf("%d,",n))for(b=0,k=i;k<n+i&&S[k];k++)b|=n>k?0:S[k]-S[k-n];} ``` [Try it online!](https://tio.run/##lVDLboMwEDwnf1GkRlAvEo/QqHXdfgTHJAfbQGOhGkqJSBXSX6fmociBcqhmvTae8eyy3H7nvGkEMEhB4sTkB1o8hNY5yQpTkB8Hh1uExB5b7QUjkriYYYkIq@u8ELJMTOM@AgOkNSgcSInA6YtEYrUKt@kepwhZrCbyNX1zntsbWyVb7vGl@aBCmtZ5uVA2lFHKGGWGhZeL/Fh@mcZOuuCBDy48quWDd7eTHd3Kb3UacxBjC42sqmrEKmj8iZ@4ikkTHgTTFhhnlI8bXsOmgw@@ppWixx/GV9xY/2sYVZbn3Zr0soY@d7v24rOKi/L7KLJ8PA5nLrTXURxH8ZCieOTQthhcR@bO/qAC1zbtPDOkzYD@y31qI@hKtVkVcnVlxwwVL80v "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` lambda s:[min(j+1for j in R(len(s))if all(s[k+~j]==s[k]for k in R(i,i-~j)if len(s)>k>j))for i in R(len(s))] R=range ``` [Try it online!](https://tio.run/##VcwxDoMwDAXQnVNkIxHt0I6VwiFYKYOjOK1DCCFQVSxcPQXRARbL/v/JYZ7evb8nI5/JQac0sPFRd@S5LW6mj8wy8qziDj0fhSDDwDk@1m2x2EbKdWk21e6KLnRd7KZ2X7alFWIDdHrTZJWM4F@YQiQ/McNzUABKgcpFdsqOt0bU@B8aj83wxTjNH@rDmqYf "Python 2 – Try It Online") ]