text
stringlengths
180
608k
[Question] [ ~~*You know nothing*~~ ~~*The things I do for*~~ ["*Chaos is a ladder*"](https://www.youtube.com/watch?v=iRS8a8HjqFs) is a memorable line from the television series [*Game of Thrones*](https://en.wikipedia.org/wiki/Game_of_Thrones). The purpose of this challenge is to build a ladder from chaos, in ASCII art. # The challenge ### Input * Ladder width, `W >= 3` (integer) * Step height, `H >= 2` (integer) * Number of rungs, `N >= 2` (integer). ### Output A ladder with *horizontal rungs* and *vertical rails*, all 1 character wide. Ladder width (`W`) includes the two rails, and step height (`H`) includes the corresponding rung. All rungs, including the uppermost and the lowermost, will have a piece of vertical rail of length `H-1` directly above and below. The example will make this clearer. The ladder will be made of *printable, non-whitespace ASCII characters*, that is, the inclusive range from `!` (code point `33`) to `~` (code point `126`).The actual characters will be chosen *randomly*. Given the inputs, each of the random choices of characters must have nonzero probability. Other than that, the probability distribution is arbitrary. *Leading or trailing whitespace*, either horizontal or vertical, is allowed. ### Example Given `W=5, H=3, N=2`, one possible output is as follows. ``` x : g h q$UO{ t T 6 < bUZXP 8 T 5 g ``` Note that total height is `H*(N+1)-1`, as there are `N` rungs and `N+1` vertical sections. # Aditional rules * Input means and format are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. For example, you can input the three numbers in any order, or an array containing them. * Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines, a 2D character array or an array of strings. * [A program or a function](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) can be provided. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. # Test cases For each `W, H, N` a possible output is shown. ``` W=5, H=3, N=2: \ ~ : K ke:[E 5 u 0 _ 8Fr.D # r 7 X W=3, H=2, N=2: $ X Mb) 0 ] (T} j 9 W=12, H=4, N=5: d Y P ` 5 3 p$t$Ow7~kcNX D x ` O * H LB|QX1'.[:[F p p x ( 2 ^ ic%KL^z:KI"^ C p ( 7 7 h TSj^E!tI&TN8 | [ < > = Q ffl`^,tBHk?~ O + p e n j W=20, H=5, N=3: G % o y % 3 - 7 U'F?Vml&rVch7{).fLDF o } U I h y a g ;W.58bl'.iHm\8v?bIn& , U N S 4 c 5 r F3(R|<BP}C'$=}xK$F]^ ' h h u x $ 6 5 ``` [Answer] # [Operation Flashpoint](https://fi.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~643~~ 624 bytes ``` f={l=["""","!","#","$","%","&","'","(",")","*","+",",","-",".","/","0","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","[","\","]","^","_","`","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","{","|","}","~"];t=_this;w=t select 0;r={l select random 92};v="";s=v;i=2;while{i<w}do{i=i+1;v=v+" "};p={i=1;while{i<t select 1}do{i=i+1;s=s+call r+v+call r+"\n"}};k=0;call p;while{k<t select 2}do{k=k+1;i=0;while{i<w}do{i=i+1;s=s+call r};s=s+"\n";call p};s} ``` Ridiculously long because there is no way to create the characters from the character codes. **Call with:** ``` hint ([5, 3, 2] call f) ``` **Output:** [![](https://i.stack.imgur.com/00tRu.jpg)](https://i.stack.imgur.com/00tRu.jpg) *The ladder is extra chaotic because the font is not monospaced.* **Unrolled:** ``` f = { l = ["""","!","#","$","%","&","'","(",")","*","+",",","-",".","/","0","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","[","\","]","^","_","`","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","{","|","}","~"]; t = _this; w = t select 0; r = { l select random 92 }; v = ""; s = v; i = 2; while {i < w} do { i = i + 1; v = v + " " }; p = { i = 1; while {i < t select 1} do { i = i + 1; s = s + call r + v + call r + "\n" } }; k = 0; call p; while {k < t select 2} do { k = k + 1; i = 0; while {i < w} do { i = i + 1; s = s + call r }; s = s + "\n"; call p }; s } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes Input taken in the order `N, H, W` ``` >*GNUžQ¦©.RIÍFð®.R«X²Öè}®.RJ, ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fTsvdL/TovsBDyw6t1AvyPNzrdnjDoXV6QYdWRxzadHja4RW1IJ6Xzv//plwmXIZGAA "05AB1E – Try It Online") **Explanation** ``` >*G # for N in [1 ... (N+1)*H)-1] do: NU # store N in variable X žQ # push a string of printable ascii ¦© # remove the first (space) and save a copy in register .R # pick a random character IÍF # W-2 times do: ð # push a space ®.R # push a random ascii character « # concatenate X²Ö # push X % H == 0 è # index into the string of <space><random_char> with this } # end inner loop ®.R # push a random ascii character J, # join everything to a string and print ``` [Answer] # C, 95 bytes ``` f(w,h,n,i){++w;for(i=0;i++<w*~(h*~n);)putchar(i%w?~-i%w%(w-2)*((i/w+1)%h)?32:33+rand()%94:10);} ``` [Answer] # [R](https://www.r-project.org/), ~~138~~ ~~129~~ ~~111~~ ~~98~~ 93 bytes *-13 bytes thanks to Neal Fultz!* *-1 byte thanks to Robin Ryder* ``` function(W,H,N){m=matrix(intToUtf8(32+sample(94,W*(h=H*N+H-1),T),T),h) m[-H*1:N,3:W-1]=" " m} ``` [Try it online!](https://tio.run/##RcmxCsIwFIXhPU9RMt20N0PSFrTYPVOmSgZxKNLQgEklRhTEZ49VB@Hwc@CL2RY7nu0tnJJbAhhUqNnT935M0T3AhTQs@2Q3UMvqOvrLeYJtg6aEuVelrhQXDIfvZkb8gatSdBrrznBx7GlBiX/le3RpggQWWqxRMoaUYotrGfmbkNhg@8P1fzS/AQ "R – Try It Online") Anonymous function; returns the result as a matrix. Thanks to that [Word Grids question](https://codegolf.stackexchange.com/questions/142531/generating-word-grids), I've been thinking about matrices a lot more than usual. I observed that the rungs are in those matrix rows that are a multiple of the step height `H` (R is 1-indexed), and that the rails are the first and last columns, `1` and `W`. So I create a matrix of random ASCII characters, and replace those letters that didn't match those criteria with spaces, and return the matrix. TIO link prints it out nicely. Neal Fultz suggested a different indexing for the space characters, `[-H*(1:N),3:W-1]`, which replaces all characters except for those in rows of multiples of `H`: `-H*(1:N)` and not on the edge, `3:W-1` <==> `2:(W-1)`. # [R](https://www.r-project.org/), 121 bytes ``` function(W,H,N)for(i in 1:(H*N+H-1)){for(j in 1:W)cat("if"(!(i%%H&j-1&j-W),sample(intToUtf8(33:126,T),1)," ")) cat("\n")} ``` [Try it online!](https://tio.run/##Jcu9CsIwFEDhvU8RA5V79WZI0ooUHyBTp0oWl1K8kKKJ1DiJzx7/hrN8cJbC4qAKP@KUQ4rgyVGPnBYIIkShO3CbfuuURnx@df6rx2nMIANLWEGoa7eelf7kke7j9XY5Q4h5SMfMe7C202ZHA5JGkkIiVr/5FCW@CkNLlgxWDNpQQy2WNw "R – Try It Online") An improvement over the original matrix-based approach I started with; it's the same algorithm but `for` loops are shorter than constructing and printing a matrix (but not if I don't print it!) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` «þỊoU$ẋ⁵‘¤Ḋ×94X€€+32ỌY ``` A full program taking the three arguments `W`, `H`, `N` and printing the result. **[Try it online!](https://tio.run/##AToAxf9qZWxsef//wqvDvuG7im9VJOG6i@KBteKAmMKk4biKw5c5NFjigqzigqwrMzLhu4xZ////MTL/NP81 "Jelly – Try It Online")** ### How? Builds a 2d array mask of a single rung and its vertical sections below, repeats it `N+1`times and removes the top rung then places random characters or spaces depending upon the mask value. ``` «þỊoU$ẋ⁵‘¤Ḋ×94X€€+32ỌY - Main link: W, H (N is third input / 5th command line argument) þ - outer product (build a table using): « - minimum - ...note: þ implicitly builds ranges of W and H prior Ị - insignificant? (abs(z)<=1) - yields a W by H 2-d array, - all zeros except the left and top edges which are 1s $ - last two links as a monad: U - upend (reverse each row) o - or (vectorises) - giving us our |‾| shape of 1s ¤ - nilad followed by link(s) as a nilad: ⁵ - 5th command line argument, N ‘ - increment -> N+1 ẋ - repeat list - giving us our ladder-mask plus a top rung) Ḋ - dequeue - remove the top rung 94 - literal ninety-four × - multiply (vectorises) - replace the 1s with 94s X€€ - random for €ach for €ach - 0 -> 0; 94 -> random integer in [1,94] 32 - literal thirty-two + - add (vectorises) - 0 -> 32; random integers now from [33,126] Ọ - character from ordinal (vectorises) Y - join with newlines - implicit print ``` [Answer] ## [Perl 5](https://www.perl.org/), 81 bytes **80 bytes code + 1 for `-p`.** ``` / \d+ /;$_=(($}=(_.$"x($`-2)._.$/)x($&-1))._ x$`.$/)x$'.$};s/_/chr 33+rand 94/ge ``` [Try it online!](https://tio.run/##HYhBCsIwFET3PcUgH00oybdJs5DSmwip2KKCtCF10U2vbvy4mMe8l6b8DqUwrmMN7ij2StHeq2jpsCkajNNWPmuRo2m0GDYa/oVOlvZu5cj3Z4b3db7NIy4tP6ZSAjxcJRM2Di1C5c6Q@l3S57XMazHpBw "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 32 bytes ``` E…¹×⁺¹NN⪫EIζ⎇∧﹪ιIη﹪λ⁻Iζ¹ §⮌γ‽⁹⁴ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nqWPGpYd2nl4@qPGXYd2vt@zDogerVoNFH@/Z@W5bY/62h91LH@/c9W5nSD@dhBr96PG3WDJQzsVDi1/tK7n3OZHDXsfNe581LjlfOf//0ZcxlymAA "Charcoal – Try It Online") Takes input in the order N, H, W. [Verbose approximation](https://tio.run/##RY7LCoMwEEX3fkVwNQFd2MeidCVdtSCI@APBDBqIkzZR@/j5NAZpd2fOzL1MNwjbGaG9r62iCSpxh0ZQj1BkrFUjOqj17NbpItwED843GviKN6MohqL7BNOiJWHfUJKEyshZG1D/SMY2pwMpCs2/YBELU5ZmrJyuJPEFDS5oHUIfFuEraUY4HXi8e3J@9n6X7JOjzxefO/0F "Charcoal – Try It Online") (`Plus(InputNumber(), 1)` is currently broken on TIO). Explanation: ``` E…¹×⁺¹NN ``` Map over the range `1..H*(N+1)`. This means that the rungs appear when `i` is a multiple of `H`. ``` ⪫ ``` Join the result of: ``` EIζ ``` mapping over the implicit range `0..W`: ``` ⎇∧﹪ιIη﹪λ⁻Iζ¹ ``` if the column is not `0` or `W-1` and the row is not a multiple of `H` then output a space; ``` §⮌γ‽⁹⁴ ``` otherwise, take the predefined ASCII character variable, reverse it (putting the space in 94th place), and print a random character from what is now the first 94. (Because `Slice` sucks.) ``` ω ``` Join using the empty string. Final result is implicitly printed. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~141~~ ~~131~~ ~~114~~ ~~109~~ 107 bytes Should be able to golf this down quite a bit... ``` i,j,c;f(w,h,n){for(i=1;i<h*n+h;i+=j==w)printf(i%h?i++,j=0,"%c%*c\n":"%c",++j^w?c^8:10,w-2,c=33+rand()%94);} ``` [Try it online!](https://tio.run/##LYnbCsIwEETf@xVSCCRmC72CNob@iBTKaswGGqUW8lD67TEU52GYcwaLF2KMBA5QGR7AghebeS@cdKXoZs9eWkVSO62D@CzkV8OJ2YGkBKdLyBmyM9593qeVg5RuDAOOl74qIRQ1oG4auUz@wQW7tkLtcZ7Ic5Ft2Snle1wrzU9eCqEOd5ThHTRQJ/XHqoYWusR7/AE "C (gcc) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~76~~ 73 bytes ``` ->\h,\n,\w{map {chrs (roll(w,1..94)Z*1,|($_%%h xx w-2),1)X+32},1..^h*n+h} ``` [Try it online!](https://tio.run/##FYxLCoMwEIbX9RSziDDRUZqohVIsPUYpUpFSycIXsaCint1OVh//c/ja5nK0C4ga8iO6F4aKjoppbasB1o@xI6DtmwYnUnF8TeUrULShKH3fwDzDFGlJSj7DRO@u8TZBF5rdPT5@kANiQpoySaiZCTOljBSPMCOOzlLevLq3rr16p3isFnBS1LiJkrMTO8jcjz8 "Perl 6 – Try It Online") Takes (h, n, w) as arguments. Returns a list of strings. Explanation: ``` -> \h, \n, \w { # Block taking arguments h, n, w map { # String from codepoints chrs # Generate w random numbers between 1 and 94 (roll(w, 1..94) # Set inner numbers on non-rungs to zero Z* 1, |($_%%h xx w-2), 1) # Add 32 to numbers X+ 32 } # Map h*n+h-1 row numbers (1-indexed) 1..^h*n+h } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~132~~ 124 bytes ``` param($w,$h,$n)-join([char[]]((($a=('#'+' '*($w-2)+"#`n")*--$h)+'#'*$w+"`n")*$n+$a)|%{($_,[char](33..126|Random))[$_-eq35]}) ``` [Try it online!](https://tio.run/##HYzLDoIwEAB/xcCa7vZBIg3e/AmvTYONklQDLdYDB/HbV8J1ZjJzXobyicM4Ms@hhAlh0RA1JDKv/Ezo7jEU5z0iQrigqIUSByG3zLSkqvqWKpLGQCS1OQmLqnYESUGg9fhF6PU@8Wht05za83oN6ZEnIge9Gd628z9i5o4tt38 "PowerShell – Try It Online") We construct a ladder composed of only `#` first ([example](https://tio.run/##HcpBCoMwEEbhq5T4Q2YyZmNx2ZOI0KEI02KjxEWOP4rb9719a0s9bFlX912r/gmth/UonH/bt9D0Ma3TPBMR9BW7KPER03XlgSV07xI45QyTixKahLugCDTBmN199KcPJw "PowerShell – Try It Online")), then loop `|%{...}` through each character and `if` it's `-eq`ual to `35`, we pull out a new `Random` character from the appropriate range. Otherwise we output (i.e., either a space or newline). [Answer] # JavaScript (ES6), ~~117~~ 115 bytes A recursive function building the output character by character. *"Look Ma, no literal line-feed!"* ``` (w,h,n)=>(g=x=>y<h*n+h-1?String.fromCharCode(x++<w?x%w>1&&-~y%h?32:Math.random()*94+33|0:10)+g(x>w?!++y:x):'')(y=0) ``` ### Demo ``` let f = (w,h,n)=>(g=x=>y<h*n+h-1?String.fromCharCode(x++<w?x%w>1&&-~y%h?32:Math.random()*94+33|0:10)+g(x>w?!++y:x):'')(y=0) O.innerText = f(5,3,4) ``` ``` <pre id=O></pre> ``` [Answer] # [Python 2](https://docs.python.org/2/), 142 bytes ``` lambda w,h,n,e=lambda:chr(randint(33,126)):[e()+[eval(("e()+"*(w-2))[:-1])," "*(w-2)][-~i%h>0]+e()for i in range(h*-~n-1)] from random import* ``` [Try it online!](https://tio.run/##LY1BCoMwFET3PcVHKP5oUqrSLgR7kZhFWpMmRRMJUunGq6eRdjUzj2Fm/izGuzrqro@jnO6DhJUa6qjqfrF9mIBBusG6BZuGVvWVkJYrJCVXbzkiZrvPClxZTQhvWSUIzeAPBGebPZrbWZSppn0AC9ZBGnwqNAXbHKuIOOjgpx0OSew0@7AUcQ7pEvLe5aeXtw41Xig0FNJL/AI "Python 2 – Try It Online") Saved bytes thanks to ovs! [Answer] # Pyth, 33 bytes ``` VhEjtW!Nmsm?&d}kr1tQ\ Or\!C127Qvz ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=VhEjtW%21Nmsm%3F%26d%7Dkr1tQ%5C%20Or%5C%21C127Qvz&input=12%0A4%0A5&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), 114 bytes ``` lambda w,h,n:[[chr(32+randint(1,94)*(x%~-w*(y%h)<1))for x in range(w)]for y in range(1,h*-~n)] from random import* ``` [Try it online!](https://tio.run/##Rc2xDoIwFIXh3afoQri3FpMiDhJ9EmRAobYGbpumBlh49Uonp5P8@ZLj1qAtlVHdH3HspmffsVloQXXTvLSHc3n0HfWGAkhxrZDDkm3FzGHNNN4korKeLcwQ29l7gBnbVNZ/kULzYiNsD8rbKcV@HzM56wOPCY@GhuQVcEPuGwCxZs7vnyzPTx9rCBLBKEtRicsP "Python 2 – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~32~~ 31 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ~ΔkψR I{e{R}¶bH{Re⁾⌡@R¶}}¹∑e⌡k ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTdFJXUwMzk0ayV1MDNDOFIlMEFJJTdCZSU3QlIlN0QlQjZiSCU3QlJlJXUyMDdFJXUyMzIxQFIlQjYlN0QlN0QlQjkldTIyMTFlJXUyMzIxaw__,inputs=MiUwQTUlMEEz) Input in the order N, W, H. Explanation: ``` ~ΔkψR R a function named "R", pushes a random character: ~ push "~" Δ get the charasters from " " to "~" k remove the 1st character ψ choose a random character from that I{e{R}¶bH{Re⁾⌡@R¶}}¹∑e⌡k main program I increase the 1st input - N { } N times do e push the variable e, which is here initialised to the next input - W { } E times do R execute R ¶ push a newline bH push b-1, where b is initialised to the next input - H { } B-1 times do R execute R e⁾ push e-2 aka width-2 ⌡@ push that many spaces R execute R ¶ push a newline ¹∑ join the stack together e⌡k remove the first width characters ``` [18 bytes](https://dzaima.github.io/SOGLOnline/?code=ZSV1MjU1NyouSGUldTIwN0VAKiV1MjU1NzEldTAzOUYldTIyMTkuJUFCJTdCUSUzQg__,inputs=NSUwQTMlMEEy) without the random characters :/ [Answer] # Java 8, ~~203~~ ~~188~~ ~~168~~ ~~133~~ ~~132~~ ~~130~~ ~~128~~ 126 bytes ``` W->H->N->{for(double i=0,j,q;++i<H*N+H;)for(j=W,q=10;j-->=0;q=i%H*j<1|j>W-2?33+Math.random()*94:32)System.out.print((char)q);} ``` [Try it online!](https://tio.run/##bY@xboMwFEV3vsJLJRuwRUKX1uAOlSo6JEuGDFUGF0xiF2xjTKQozbdTp6Jb33R13n16OoqfOTZWaNV8zbK3xnmgAiOTlx1pJ117aTSJaRTZ6bOTNag7Po5gw6UG1wiEGT33gb8t3eJde3EULv2HvBo9Tr1wf4QxBlpQgnmPWYXZFrNraxxsTHglgCyzVKUDTRJZVPE2qSi6b1W5T4dylVGFMSszOpTyoYpVsfpWbI/XL3mebLg/Ecd1Y3qI4qfH53yNdpfRi56YyRPrpPYQ1ifu0IDobQ52d5PFcBE6G9mAPnjCnQ8Hx48D4Ghxvk9LuLXdBa4ytKQ8hLoW1sM1or@9W3SbfwA "Java (OpenJDK 8) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~226~~ ~~220~~ ~~211~~ 190 bytes ``` import System.Random a=mapM id b=(putStr.unlines=<<).a c=randomRIO('!','~') r w=a$c<$[1..w] s w=a$c:(return ' '<$[3..w])++[c] (w#h)0=b$s w<$[2..h] (w#h)n=do{b$(s w<$[2..h])++[r w];(w#h)$n-1} ``` [Try it online!](https://tio.run/##TY1BC4IwAIXv@xULB9uwRiZdyv2ADhHoUTxMHThyU@ZEIuqv27QOHd/7vsdrxHCXbTvPSveddTB7DE5qlgpTdxoIrkV/haoGJSf96DJn2WhaZeTAk4QyASpuVzW93Aje4C1@YwosnLhAVYLyiLGpAMM3n4iVbrQGYog9ixdGwzCvCkCmoKF7XiKvenRgrPmVhtfds0TkDywbf1GcVwGZXfSatVAGckiOQUwP8wc "Haskell – Try It Online") *Saved 9 bytes thanks to Laikoni* *Saved 21 bytes thanks to wchargin* Should be golfable (`b$(s w)<$[2..h]` and `b$((s w)<$[2..h])++[r w]`). I don't feel comfortable with IO and golfing. [Answer] # JavaScript (ES6), 144 bytes ``` (w,h,n)=>Array(n+1).fill(("#".padEnd(w-1)+`# `).repeat(h-1)).join("#".repeat(w)+` `).replace(/#/g,_=>String.fromCharCode(33+Math.random()*94|0)) ``` Creates the ladder out of `#` characters then replaces each one with a random ASCII char. ## Test Snippet ``` let f= (w,h,n)=>Array(n+1).fill(("#".padEnd(w-1)+`# `).repeat(h-1)).join("#".repeat(w)+` `).replace(/#/g,_=>String.fromCharCode(33+Math.random()*94|0)) ;(W.oninput=H.oninput=N.oninput=B.onclick=_=>{let vals=[W.value,H.value,N.value].map(eval);D.innerText=vals.join`, `;O.innerText=f(...vals);})() ``` ``` W: <input id=W type=range min=3 max=25 value=12><br> H: <input id=H type=range min=2 max=25 value=5><br> N: <input id=N type=range min=2 max=10 value=2><br> <button id=B>Rerun</button> <code id=D></code> <pre id=O></pre> ``` [Answer] # JavaScript (ES6), ~~129~~ 117 bytes Unfortunately, while I was in the process of golfing this down, Arnauld beat me to a similar but [shorter solution](https://codegolf.stackexchange.com/a/142869/58974). By combining our 2 solutions, this can be [113 bytes](https://tio.run/##nY6xDoIwFEV3/0ITzHu2JYXKYGNhcHZydaApQjW1NZXI4r8joyZO3PHknOTe9Es/Tbw@euZDcxlbNcJALfWoSuiUUaWrTn28@i5tY7gfrI6HyQNDyH6oTDKU2XrtEluJXO62m6PubRq1b8IdkAjx5jLjSDow5VAtGXPSoKxrBE6dshtCPMtwNME/g7ukLnTQQkEFzREX33TF/uzsV79WC1M5u81yuqXFzDjndPqNOH4A) Includes a trailing newline. ``` (w,h,n)=>(g=c=>l?(c++<w?c%w>1&&l%h?` `:String.fromCharCode(94*Math.random()+33|0):` `)+g(c>w?!--l:c):``)(0,l=h*++n-1) ``` --- ## Try it ``` o.innerText=(f= (w,h,n)=>(g=c=>l?(c++<w?c%w>1&&l%h?` `:String.fromCharCode(94*Math.random()+33|0):` `)+g(c>w?!--l:c):``)(0,l=h*++n-1) )(i.value=5,j.value=3,k.value=2);oninput=_=>o.innerText=f(+i.value,+j.value,+k.value) ``` ``` label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;padding:0 0 0 5px;width:100px;} ``` ``` <label for=i>W: </label><input id=i min=3 type=number><label for=j>H: </label><input id=j min=2 type=number><label for=k>N: </label><input id=k min=2 type=number><pre id=o> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~42~~ ~~41~~ ~~40~~ ~~37~~ ~~34~~ ~~28~~ 25 bytes Takes input in the order `H,W,N`. ``` ;*°WÉ ÆJ²ùVXgJùU¹r,@EÅöÃé ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=OyqwV8kgxkqy%2bVZYZ0r5VblyLEBFxfbD6Q&input=NSwyMCwz) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 76 bytes ``` [:*:+b-1|G=chr$(_r33,126|)~a%b\[:-2|G=G+@ `]][e|G=G+chr$(_r33,126|)]?_sG,1,e ``` ## Explanation ``` [ FOR a = 1 TO : input 1 (Height, now in var b) * times : input 2 (# of rungs, now in var c) +b-1| plus one bottom rung without crossbar G=chr$(_r33,126|) Assign to G a random char (_r is the RAND() function, chr$() is BASIC's num-to-char) ~a%b| IF we are not at a crossbar (the modulo returns anything but 0), [:-2|G=G+@ ` add to G x spaces, where x is width (input 3, now 'e') - 2 Note that G is now either 'X' or 'X ' (for rnd char X and W=5) ]] Close the spacing FOR, close the IF [e| FOR f = 1 to width G=G+chr$(_r33,126|)] Append to G a rnd char G is now either 'XXXXXX' or 'X XXXXX' (for rnd char X and W=5) ?_sG,1,e PRINT the first w characters of G, and on to the next line ``` ## Sample run ``` Command line: 3 2 5 N F M ` Bj#=y ! ( S N q(.Ho % 7 g , ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~63~~ 50 bytes *-13 bytes thanks to Luis Mendo* ``` Q*qXJ*6Y2HY)wT3$ZrJ3G3$eJ3G&Ol5LZ(J:HG\~3GTX"!+g*c ``` [Try it online!](https://tio.run/##y00syfn/P1CrMMJLyyzSyCNSszzEWCWqyMvY3VglFUiq@eeY@kRpeFl5uMfUGbuHRCgpaqdrJf//b8RlzGUKAA "MATL – Try It Online") I'm still new to golfing in MATL (and I'm not super good at MATLAB for that matter), so I know this probably isn't close to optimal. Tips are welcome. Takes input in order `N,H,W`. Here we go: ``` Q*qXJ # compute H*(N+1)-1, store as J * # multiply by W 6Y2HY) # push printable ASCII wT3$Zr # sample uniformly with replacement J3G3$e # reshape to make a matrix of the appropriate shape. ``` We now have a matrix of random char. ``` J3G # push J,W &O # zero matrix, J x W l5LZ( # assign 1 to first and last columns ``` Now there's also a logical matrix for the rails. ``` J: # push J, range, so 1...J HG # take second input (H) \~ # mod and bool negate (so it's 1 for rows of multiples of H) 3GTX"! # repmat and transpose so we have 1's for rungs ``` Now we have 3 matrices on the stack: * Top: 0 for non-rung, 1 otherwise * Middle: 0 for non-rail, 1 otherwise * Bottom: random characters, -20 So we do the following: ``` + # add the top two matrices. g # convert to logical so 0->0, nonzero->1 * # elementwise multiply c # convert to char, implicit output (0 -> space). ``` [Answer] # Powershell, 102 bytes ``` param($w,$h,$n)1..(++$n*$h-1)|%{$l=$_%$h -join(1..$w|%{[char](32,(33..126|Random))[!$l-or$_-in1,$w]})} ``` Less golfed test script: ``` $f = { param($w,$h,$n) 1..(++$n*$h-1)|%{ # for each lines of the ladder $l=$_%$h # line number in a step -join(1..$w|%{ # make a line [char](32,(33..126|Random))[!$l-or$_-in1,$w] }) # a random character if the line number in a step is a rung line or char position is 1 or width # otherwise a space } } &$f 5 3 2 &$f 3 2 2 &$f 12 4 5 &$f 20 5 3 ``` Output: ``` 0 { H S ']UxR G ] 3 t q^R8O q y t J U h YQZ _ i 3#D I # = m & < ] 6 8nmuyw2'Y7%+ o l ; ! D M Fn[zGfT";RYt @ B $ e z @ @J[1|:-IS~y< ( L : [ | q zBow0T0FnY8) / * e B R p 9{d2(RacBdRj u ~ ` l J h v t T - v H ' Y IS7{bx2&k@u7]o}>[Vq? F U ? U | Q } T :wv1wEfc6cS;430sigF| < L : } * ` H = L8k5Q/DQ=0XIUujK|c6| j = ! p V : # w ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 71 bytes EDIT: Oops I thought this was a new challenge because of the recent edit to fix a typo lol. I'm still leaving this up though because there's no Ruby answer for it yet. ``` ->w,h,n{(1..h*-~n-1).map{|i|[*?!..?~].sample(x=i%h>0?2:w)*(' '*(w-x))}} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euXCdDJ69aw1BPL0NLty5P11BTLzexoLomsyZay15RT8@@LlavODG3ICdVo8I2UzXDzsDeyKpcU0tDXUFdS6Nct0JTs7b2f0FpSbFGWrSpjrGOUazmfwA "Ruby – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/57143/edit). Closed 1 year ago. [Improve this question](/posts/57143/edit) Every Unicode character has a name, like "LATIN CAPITAL LETTER A". A Unicode character name may contain only uppercase letters, white spaces, and the minus sign. Write a program that reads a text and outputs the names of each character on a new line. For example, if the input were "Hello, World!", the output would be ``` LATIN CAPITAL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER L LATIN SMALL LETTER L LATIN SMALL LETTER O COMMA SPACE LATIN CAPITAL LETTER W LATIN SMALL LETTER O LATIN SMALL LETTER R LATIN SMALL LETTER L LATIN SMALL LETTER D EXCLAMATION MARK ``` * Input should come from a file or from user input, not just a string in code. * Output should be written to a file or stdout or printed to the screen. * Internet and external libraries are not allowed, all necessary data should be in the code. * Assume that the input only contains printable ASCII characters in the Basic Latin code range 32-126. You can ignore a trailing newline. * All programming languages allowed. Shortest code in bytes wins. The official Unicode character names can be found [here](http://www.unicode.org/charts/PDF/U0000.pdf). Other sources: * <http://www.w3schools.com/charsets/ref_utf_basic_latin.asp> * <http://www.ssec.wisc.edu/~tomw/java/unicode.html#x0000> This is my first question so I'd appreciate any suggestion if this can be improved. For the purpose of this challenge the list below shall be normative. ``` 32 0020 SPACE ! 33 0021 EXCLAMATION MARK " 34 0022 QUOTATION MARK # 35 0023 NUMBER SIGN $ 36 0024 DOLLAR SIGN % 37 0025 PERCENT SIGN & 38 0026 AMPERSAND ' 39 0027 APOSTROPHE ( 40 0028 LEFT PARENTHESIS ) 41 0029 RIGHT PARENTHESIS * 42 002A ASTERISK + 43 002B PLUS SIGN , 44 002C COMMA - 45 002D HYPHEN-MINUS . 46 002E FULL STOP / 47 002F SOLIDUS 0 48 0030 DIGIT ZERO 1 49 0031 DIGIT ONE 2 50 0032 DIGIT TWO 3 51 0033 DIGIT THREE 4 52 0034 DIGIT FOUR 5 53 0035 DIGIT FIVE 6 54 0036 DIGIT SIX 7 55 0037 DIGIT SEVEN 8 56 0038 DIGIT EIGHT 9 57 0039 DIGIT NINE : 58 003A COLON ; 59 003B SEMICOLON < 60 003C LESS-THAN SIGN = 61 003D EQUALS SIGN > 62 003E GREATER-THAN SIGN ? 63 003F QUESTION MARK @ 64 0040 COMMERCIAL AT A 65 0041 LATIN CAPITAL LETTER A B 66 0042 LATIN CAPITAL LETTER B C 67 0043 LATIN CAPITAL LETTER C D 68 0044 LATIN CAPITAL LETTER D E 69 0045 LATIN CAPITAL LETTER E F 70 0046 LATIN CAPITAL LETTER F G 71 0047 LATIN CAPITAL LETTER G H 72 0048 LATIN CAPITAL LETTER H I 73 0049 LATIN CAPITAL LETTER I J 74 004A LATIN CAPITAL LETTER J K 75 004B LATIN CAPITAL LETTER K L 76 004C LATIN CAPITAL LETTER L M 77 004D LATIN CAPITAL LETTER M N 78 004E LATIN CAPITAL LETTER N O 79 004F LATIN CAPITAL LETTER O P 80 0050 LATIN CAPITAL LETTER P Q 81 0051 LATIN CAPITAL LETTER Q R 82 0052 LATIN CAPITAL LETTER R S 83 0053 LATIN CAPITAL LETTER S T 84 0054 LATIN CAPITAL LETTER T U 85 0055 LATIN CAPITAL LETTER U V 86 0056 LATIN CAPITAL LETTER V W 87 0057 LATIN CAPITAL LETTER W X 88 0058 LATIN CAPITAL LETTER X Y 89 0059 LATIN CAPITAL LETTER Y Z 90 005A LATIN CAPITAL LETTER Z [ 91 005B LEFT SQUARE BRACKET \ 92 005C REVERSE SOLIDUS ] 93 005D RIGHT SQUARE BRACKET ^ 94 005E CIRCUMFLEX ACCENT _ 95 005F LOW LINE ` 96 0060 GRAVE ACCENT a 97 0061 LATIN SMALL LETTER A b 98 0062 LATIN SMALL LETTER B c 99 0063 LATIN SMALL LETTER C d 100 0064 LATIN SMALL LETTER D e 101 0065 LATIN SMALL LETTER E f 102 0066 LATIN SMALL LETTER F g 103 0067 LATIN SMALL LETTER G h 104 0068 LATIN SMALL LETTER H i 105 0069 LATIN SMALL LETTER I j 106 006A LATIN SMALL LETTER J k 107 006B LATIN SMALL LETTER K l 108 006C LATIN SMALL LETTER L m 109 006D LATIN SMALL LETTER M n 110 006E LATIN SMALL LETTER N o 111 006F LATIN SMALL LETTER O p 112 0070 LATIN SMALL LETTER P q 113 0071 LATIN SMALL LETTER Q r 114 0072 LATIN SMALL LETTER R s 115 0073 LATIN SMALL LETTER S t 116 0074 LATIN SMALL LETTER T u 117 0075 LATIN SMALL LETTER U v 118 0076 LATIN SMALL LETTER V w 119 0077 LATIN SMALL LETTER W x 120 0078 LATIN SMALL LETTER X y 121 0079 LATIN SMALL LETTER Y z 122 007A LATIN SMALL LETTER Z { 123 007B LEFT CURLY BRACKET | 124 007C VERTICAL LINE } 125 007D RIGHT CURLY BRACKET ~ 126 007E TILDE ``` [Answer] # Java - 113 bytes (152 if read from command line) Edit: removed useless curly brackets. Edit2: removed unnecessary variable. Edit3: Instead of Character.getName() I use c.getName(). Edit4: Passing string as command line argument. With command line argument (113 bytes): ``` class Z{public static void main(String[]x){for(Character c:x[0].toCharArray())System.out.println(c.getName(c));}} ``` With read line (152 bytes): ``` class Z{public static void main(String[]x){for(Character c:new java.util.Scanner(System.in).nextLine().toCharArray())System.out.println(c.getName(c));}} ``` Java has everything needed. I'm sure this could be golfed down. [Answer] # Python 3, 56 bytes Uses a built-in function `unicodedata.name()`, so this may be non-competent. The Java answer did it similarly, so I thought it was at least worth posting. ``` from unicodedata import* for i in input():print(name(i)) ``` [Answer] # JavaScript (ES6) 594 ~~618 626~~ *Note* I could save ~30 bytes compressing the long string with atob/btoa, but the utf8 character above '~' are not well accepted by the Stack Exchange post editor. I prefer to keep a running snippet instead. **Edit** 8 chars saved thx @Ypnypn Obvious compression of repeated words. The newline inside backticks is significant and counted. Test running the snippet in Firefox. ``` // TEST SUITE // for testing purpose, redefine alert() to write inside the snippet body alert=x=>O.innerHTML=x // for testing purpose, redefine prompt() to have a default text containing all characters _prompt=prompt prompt=(i,s)=>{ for(s='',i=32;i<127;i++)s+=String.fromCharCode(i); return _prompt("Insert your message or keep the default",s); } // That's the answer code: z='SPACE/EXCLAMA0QUOTA0NUMBER1DOLLAR1PERCENT1AMPERSAND/APOSTROPHE3242ASTERISK/PLUS1COMMA/HYPHEN-MINUS/FULL STOP/78ZERO8ONE8TWO8THREE8FOUR8FIVE8SIX8SEVEN8EIGHT8NINE86SEMI6LESS-THAN1EQUALS1GREATER-THAN1QUES0COMMERCIAL AT3SQUARE5REVERSE 7/4SQUARE5CIRCUMFLEX9/LOW LINE/GRAVE93CURLY5VERTICAL LINE/4CURLY5TILDE'.replace(/\d/g,c=>'TION MARK/, SIGN/,PARENTHESIS/,/LEFT ,RIGHT , BRACKET/,COLON/,SOLIDUS,/DIGIT , ACCENT'.split`,`[c]).split`/`,alert([...prompt()].map(c=>(q=c.charCodeAt()-32)<33?z[q]:q<59?'LATIN CAPITAL LETTER '+c:q<65?z[q-26]:q<91?'LATIN SMALL LETTER '+c.toUpperCase():z[q-52]).join` `) ``` ``` <pre id=O></pre> ``` [Answer] # R, ~~54 bytes~~ 62 ``` library(Unicode) cat(u_char_name(utf8ToInt(scan(,""))),sep="\n") ``` Edit: per @flodels comment, I need to read it from connection first, so had to add `scan`. This is also probably non-competent solution according to *all* the rules. **Usage** ``` > cat(u_char_name(utf8ToInt(scan(,""))),sep="\n") 1: 'Hello, World!' 2: Read 1 item LATIN CAPITAL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER L LATIN SMALL LETTER L LATIN SMALL LETTER O COMMA SPACE LATIN CAPITAL LETTER W LATIN SMALL LETTER O LATIN SMALL LETTER R LATIN SMALL LETTER L LATIN SMALL LETTER D EXCLAMATION MARK ``` You can also wrap it up into a function for more convenient usage ``` UNI <- function(x)cat(paste0(u_char_name(utf8ToInt(x)),"\n")) ``` Then, the usage is just ``` UNI("Hello, World!") ``` [Answer] # C, 644 ~~656~~ Full program, reading from standard input Test on [Ideone](http://ideone.com/9njuPP) This is a porting of my JavaScript answer to C. The C language is good at manipulating single characters as numbers (no need of `.toUpperCase` and the like), but it's weaker in string manipulation. ``` char*s,*p,*q,b[999],*d=b+99,c,*l[129]; main(k){for(k=32,p="/SPACE/EXCLAMAaQUOTAaNUMBERbDOLLARbPERCENTbAMPERSAND/APOSTROPHEdcecASTERISK/PLUSbCOMMA/HYPHEN-MINUS/FULL STOP/hiZEROiONEiTWOiTHREEiFOURiFIVEiSIXiSEVENiEIGHTiNINE/gSEMIgLESSnbEQUALSbGREATERnbQUESaCOMMERCIAL ATdkfREVERSE h/ekfCIRCUMFLEXj/LOWmGRAVEjdlfVERTICALmelfTILDE/"; c=*p;p++)c>96?q?(p=q,q=0):(q=p,p=strchr("aTION MARK/b SIGN/cPARENTHESIS/d/LEFT eRIGHT f BRACKET/gCOLON/hSOLIDUSi/DIGIT j ACCENTkSQUARElCURLYm LINE/n-THANz",c)):c-47?*d++=c:(*d++=0,l[k++]=d); for(;~(k=getchar());puts(k<65?l[k]:(k&31)<27?b:l[k<97?k-26:k-52]))sprintf(b,"LATIN %s LETTER %c",k<91?"CAPITAL":"SMALL",k&95);} ``` Less golfed ``` char *all = "/SPACE/EXCLAMAaQUOTAaNUMBERbDOLLARbPERCENTbAMPERSAND/APOSTROPHEdcecASTERISK/PLUSbCOMMA/HYPHEN-MINUS/FULL STOP/hiZEROiONEiTWOiTHREEiFOURiFIVEiSIXiSEVENiEIGHTiNINE/gSEMIgLESSnbEQUALSbGREATERnbQUESaCOMMERCIAL ATdkfREVERSE h/ekfCIRCUMFLEXj/LOWmGRAVEjdlfVERTICALmelfTILDE/"; char *subs = "aTION MARK/b SIGN/cPARENTHESIS/d/LEFT eRIGHT f BRACKET/gCOLON/hSOLIDUSi/DIGIT j ACCENTkSQUARElCURLYm LINE/n-THANz"; main(int k) { char c, *s, *p, *q=0, b[999], // work buffer *d = b+99, // first part of buffer is used later *l[129]; // characters descriptions (used 32 to 126) // Uncompress the descriptions of all char except letters for(k = 32, p = all; c = *p; ++p) { c >= 'a' // substitution word are marked as lowercase letters ? q ? (p = q, q = 0) : (q = p, p = strchr(subs, c)) : c != '/' ? *d++ = c : (*d++ = 0, l[k++] = d); // end char description } // Scan the input string and print each char description for(; (k=getchar()) != -1; ) { sprintf(b,"LATIN %s LETTER %c", k<91 ? "CAPITAL":"SMALL", k & 95); puts( k<65 ? l[k] : k<91 ? b : k<97 ? l[k-26] : k<123 ? b : l[k-52]); } } ``` [Answer] # [Perl 6](http://perl6.org), 21 bytes I did not see a rule specifically against using a built-in method for getting the unicode names. (Also the Java answer which is the currently highest voted one does the same) ``` .say for get.uninames ``` [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0 -MCompress::Zlib -00F`, 459 bytes ``` @d=split/,/,inflateInit->inflate(<DATA>);say$d[-32+ord]for@F __END__ x.m.or.0.......!.#....I&I.......v......0O.)q.g.*...PH.q....u..k...85.:sgM\.8P..Fu......r..=tR...e......9k.{.2.xUj.P\_}..Qr...!..[..$O.2.%{.bmgl.....|U.tnC...K-?..;.3..1.\s......K>.....T..y.$v.E.....6.....JaM.$.G!.5$...A..5.....y...g....s.....Y0...s..1o...av.............;..)..R..G...8..t...K)k.e.~.J..Gi. .r\.v>.........!L.'..pF. \.f......aAX.6....P..BG8......._.. ....W...s"9.t.... .2...... ``` [Try it online!](https://tio.run/##fZVrWxRHEIW/@ytKJUaiW3ZP3wGJRIWoUYnRRCMJ6ekLbLi6uxiM0b9OTi9D8FN4Hnpnlul3quucOvRxunt2epppNKGVlRW6tnBzFsf7NOoCcTrKhWfjo8VrtErHk/HhbDTbLaO0GycxzcpkdBgPypSP95ev/JVolP73GVq90S1fOS4TwJ8aloIFLu4fHRxPynS6tPTr/rinkRDr/09ZIR4fHp/MWl3LV8rpeLZ8JoafJdLCalLZKXLCJrLBaepql84XG2wha/EHupfvTo/3x7M7t@/cHh/W/SvnBAmGldhkjQ5kiw3kdJdJtSvcWrLJSnxnDVGclUeH49lotQFwMzA6MDqvEmmtJZm2qIJ2qh5lAR6o06jS9ODSzZUHay/XVheXp/HD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znKnUDxqZOkk/DUOYjjkxPIgx63wqTBY1d/4K@Zj9eZtgZGyw8pEeReB2SyL20RptkF/yp8C6Imtcyl6VLPexnXXs9NNjBafniLYZdSRtJwK9rTnFJQjKxYQltMW4iRQd9t@EGV7QtGy49UBVLDRujY1UjGxXIuhFNdhwzCd05XfTEvvzR3XAto78Bo@VEq8kPkZu6uIoRrrRRT0tQy9MufRujOQWdndPXa9YWvbnx9c/GbW7dHfAeeV9pY58PS8srd1W/vrX13/8HD9Y3vHz1@8sPTZ883f3zx08tXP//y@s2vb7d@@337j4iwL3Vnd/zn3v7B4dHxu8l0dvL@r9MPf3/859PnfwE "Bash – Try It Online") ## Explanation Pretty straight-forward, `@d` is constructed from Zlib compressed data (stored after `__END__`), which is just the compressed list of raw comma separated character names that is inflated, split on `,` and can be indexed via `ord - 32`. `-00` sets the [input record separator](https://perldoc.perl.org/perlvar#$INPUT_RECORD_SEPARATOR) to `\x00` (`NUL`) which slurps the `__DATA__` in one call to `<DATA>` instead of having it split on newline. `@F` is initialised with the input data as an array (via `-F`), which is iterated over and the corresponding index from `@d` is output. --- # [Perl 5](https://www.perl.org/) + `-M5.10.0 -F`, 672 bytes ``` $b=BRACKET;say+(SPACE,<"{EXCLAMATION,QUOTATION} MARK">,<"{NUMBER,DOLLAR,PERCENT} SIGN">,AMPERSAND,APOSTROPHE,<"{LEFT,RIGHT} PARENTHESIS">,ASTERISK,'PLUS SIGN',COMMA,'HYPHEN-MINUS','FULL STOP',$s=SOLIDUS,<"DIGIT {ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE}">,<{,SEMI}COLON>,<"{LESS-THAN,EQUALS,GREATER-THAN} SIGN">,'QUESTION MARK','COMMERCIAL AT',<"LATIN CAPITAL LETTER {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}">,"LEFT SQUARE $b","REVERSE $s","RIGHT SQUARE $b",'CIRCUMFLEX ACCENT','LOW LINE','GRAVE ACCENT',<"LATIN SMALL LETTER {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}">,"LEFT CURLY $b",'VERTICAL LINE',"RIGHT CURLY $b",TILDE)[-32+ord]for@F ``` [Try it online!](https://tio.run/##rZHpQtNAFIVfJdZqwN7UAtYNikwnN8nQWdJZuiEqFVAUaW1xwVof3Tgpij6A/2bunHvynZPpyey8WRTVcautCe2g3Z4fXdXWTE4owk5lgQPKiSCWKQldp@zqtAwE0Z3KbimQTrRRQ6w4Jxpy1BSlXQaGpdILiPATQ2QMJFfGapVnK1uOiQXN0sxLc6L9SoaGmXLDWNTMdCDMuTMrnxCoEoJAmA39uowEk86EECaO88BYlYdQnbeM4ix2xrvHLGU2WIxQK1ASwfYV2EwjQqKchoT1EAwbgMEeSsCSAiSTuCwTLfxYsCVVXMnda1RjIpsRr@w6wg2kGolnXM1ugoZdh6bsZlWNhyuRfRmM8IDY0BtxX50MKMmZ9TOO1nsECwJtoBCDZ4MUMmCwDx3gIECCghy6oMGABQc96MMAhjAqMStlgYHxQBqD6rgCFe3DaOMv8/JSZvr3OaRMUycSjoOA0PIXeUSu@gH3uf0x1aSHNy9/YI0g/D@hUqf58BrFc1pGyw5W3/4N@1dgGY9x/SDa2qxNZseHp5PZXlIUwa3K7eqdu@Ha@r0aRPX7jY3NrQfNh48eP3m6vdPafbZH2jTGJM3YfocLqfKuNtb1@oPh6OD54YuXr47Gr49PTt@8PXv3/vzDxWT6cTa//PT5y9erb4vvyx8/J9PLs8nFvIiSIhLN@kaj3vgF "Perl 5 – Try It Online") ## Explanation A (marginally) less boring version of the script without tool-based compression, mostly taking advantage of `glob`s. [Answer] # awk - 794 739 ``` 1 LATIN CAPITAL LETTER B 2 LATIN CAPITAL LETTER E 3 LATIN CAPITAL LETTER G 4 LATIN CAPITAL LETTER I 5 LATIN CAPITAL LETTER N 6 LEFT CURLY BRACKET 7 LATIN SMALL LETTER S 8 LATIN SMALL LETTER P 9 LATIN SMALL LETTER L 10 LATIN SMALL LETTER I 11 LATIN SMALL LETTER T 12 LEFT PARENTHESIS 13 QUOTATION MARK 14 LATIN SMALL LETTER I 15 COMMA 16 LATIN CAPITAL LETTER L 17 LATIN SMALL LETTER V 18 COMMA 19 LATIN CAPITAL LETTER S 20 LATIN SMALL LETTER V 21 COMMA 22 LATIN SMALL LETTER A 23 LATIN SMALL LETTER X 24 COMMA 25 CIRCUMFLEX ACCENT 26 LATIN SMALL LETTER X 27 COMMA 28 LEFT SQUARE BRACKET 29 LATIN SMALL LETTER X 30 COMMA 31 LATIN CAPITAL LETTER Q 32 COMMA 33 LATIN CAPITAL LETTER O 34 COMMA 35 LATIN SMALL LETTER T 36 LATIN CAPITAL LETTER K 37 COMMA 38 LATIN SMALL LETTER C 39 LATIN CAPITAL LETTER K 40 COMMA 41 LATIN CAPITAL LETTER V 42 COMMA 43 LATIN SMALL LETTER Q 44 LATIN SMALL LETTER X 45 COMMA 46 LATIN SMALL LETTER G 47 COMMA 48 LATIN CAPITAL LETTER I 49 COMMA 50 LATIN SMALL LETTER W 51 LATIN SMALL LETTER U 52 COMMA 53 LATIN CAPITAL LETTER X 54 COMMA 55 LATIN SMALL LETTER B 56 LATIN SMALL LETTER Y 57 COMMA 58 LATIN SMALL LETTER B 59 LEFT CURLY BRACKET 60 COMMA 61 LATIN SMALL LETTER B 62 LATIN SMALL LETTER Z 63 COMMA 64 LATIN SMALL LETTER B 65 LATIN SMALL LETTER D 66 COMMA 67 LATIN SMALL LETTER B 68 LATIN SMALL LETTER P 69 COMMA 70 LATIN SMALL LETTER B 71 LATIN SMALL LETTER R 72 COMMA 73 LATIN SMALL LETTER B 74 RIGHT CURLY BRACKET 75 COMMA 76 LATIN SMALL LETTER B 77 LATIN SMALL LETTER K 78 COMMA 79 LATIN SMALL LETTER B 80 LATIN SMALL LETTER L 81 COMMA 82 LATIN SMALL LETTER B 83 LATIN SMALL LETTER O 84 COMMA 85 LATIN SMALL LETTER E 86 COMMA 87 LATIN CAPITAL LETTER P 88 COMMA 89 LATIN CAPITAL LETTER R 90 LATIN SMALL LETTER X 91 COMMA 92 LOW LINE 93 LATIN SMALL LETTER X 94 COMMA 95 LATIN CAPITAL LETTER J 96 LATIN SMALL LETTER X 97 COMMA 98 LATIN CAPITAL LETTER U 99 LATIN SMALL LETTER V 100 COMMA 101 LATIN CAPITAL LETTER M 102 TILDE 103 COMMA 104 SPACE 105 LATIN SMALL LETTER T 106 GRAVE ACCENT 107 LATIN CAPITAL LETTER Y 108 COMMA 109 LATIN CAPITAL LETTER Z 110 LATIN CAPITAL LETTER X 111 COMMA 112 LATIN SMALL LETTER C 113 GRAVE ACCENT 114 LATIN CAPITAL LETTER Y 115 COMMA 116 LATIN CAPITAL LETTER N 117 REVERSE SOLIDUS 118 REVERSE SOLIDUS 119 COMMA 120 VERTICAL LINE 121 LATIN SMALL LETTER S 122 COMMA 123 LATIN SMALL LETTER M 124 REVERSE SOLIDUS 125 REVERSE SOLIDUS 126 COMMA 127 SPACE 128 LATIN SMALL LETTER T 129 LATIN SMALL LETTER H 130 LATIN CAPITAL LETTER Y 131 COMMA 132 LATIN CAPITAL LETTER T 133 LATIN SMALL LETTER S 134 COMMA 135 LATIN SMALL LETTER C 136 LATIN SMALL LETTER H 137 LATIN CAPITAL LETTER Y 138 COMMA 139 LATIN SMALL LETTER F 140 SPACE 141 LATIN CAPITAL LETTER H 142 LATIN CAPITAL LETTER Y 143 LATIN CAPITAL LETTER P 144 LATIN CAPITAL LETTER H 145 LATIN CAPITAL LETTER E 146 LATIN CAPITAL LETTER N 147 HYPHEN-MINUS 148 LATIN CAPITAL LETTER M 149 LATIN CAPITAL LETTER I 150 LATIN CAPITAL LETTER N 151 LATIN CAPITAL LETTER U 152 LATIN CAPITAL LETTER S 153 SPACE 154 LATIN CAPITAL LETTER G 155 LATIN CAPITAL LETTER R 156 LATIN CAPITAL LETTER E 157 LATIN CAPITAL LETTER A 158 LATIN CAPITAL LETTER T 159 LATIN CAPITAL LETTER E 160 LATIN CAPITAL LETTER R 161 HYPHEN-MINUS 162 LATIN CAPITAL LETTER T 163 LATIN CAPITAL LETTER H 164 LATIN CAPITAL LETTER A 165 LATIN CAPITAL LETTER N 166 SPACE 167 LATIN CAPITAL LETTER P 168 LATIN CAPITAL LETTER A 169 LATIN CAPITAL LETTER R 170 LATIN CAPITAL LETTER E 171 LATIN CAPITAL LETTER N 172 LATIN CAPITAL LETTER T 173 LATIN CAPITAL LETTER H 174 LATIN CAPITAL LETTER E 175 LATIN CAPITAL LETTER S 176 LATIN CAPITAL LETTER I 177 LATIN CAPITAL LETTER S 178 SPACE 179 LATIN CAPITAL LETTER E 180 LATIN CAPITAL LETTER X 181 LATIN CAPITAL LETTER C 182 LATIN CAPITAL LETTER L 183 LATIN CAPITAL LETTER A 184 LATIN CAPITAL LETTER M 185 LATIN CAPITAL LETTER A 186 LATIN CAPITAL LETTER T 187 LATIN CAPITAL LETTER I 188 LATIN CAPITAL LETTER O 189 LATIN CAPITAL LETTER N 190 SPACE 191 LATIN CAPITAL LETTER C 192 LATIN CAPITAL LETTER O 193 LATIN CAPITAL LETTER M 194 LATIN CAPITAL LETTER M 195 LATIN CAPITAL LETTER E 196 LATIN CAPITAL LETTER R 197 LATIN CAPITAL LETTER C 198 LATIN CAPITAL LETTER I 199 LATIN CAPITAL LETTER A 200 LATIN CAPITAL LETTER L 201 SPACE 202 LATIN CAPITAL LETTER C 203 LATIN CAPITAL LETTER I 204 LATIN CAPITAL LETTER R 205 LATIN CAPITAL LETTER C 206 LATIN CAPITAL LETTER U 207 LATIN CAPITAL LETTER M 208 LATIN CAPITAL LETTER F 209 LATIN CAPITAL LETTER L 210 LATIN CAPITAL LETTER E 211 LATIN CAPITAL LETTER X 212 SPACE 213 LATIN CAPITAL LETTER A 214 LATIN CAPITAL LETTER P 215 LATIN CAPITAL LETTER O 216 LATIN CAPITAL LETTER S 217 LATIN CAPITAL LETTER T 218 LATIN CAPITAL LETTER R 219 LATIN CAPITAL LETTER O 220 LATIN CAPITAL LETTER P 221 LATIN CAPITAL LETTER H 222 LATIN CAPITAL LETTER E 223 SPACE 224 LATIN CAPITAL LETTER S 225 LATIN CAPITAL LETTER E 226 LATIN CAPITAL LETTER M 227 LATIN CAPITAL LETTER I 228 LATIN CAPITAL LETTER C 229 LATIN CAPITAL LETTER O 230 LATIN CAPITAL LETTER L 231 LATIN CAPITAL LETTER O 232 LATIN CAPITAL LETTER N 233 SPACE 234 LATIN CAPITAL LETTER A 235 LATIN CAPITAL LETTER M 236 LATIN CAPITAL LETTER P 237 LATIN CAPITAL LETTER E 238 LATIN CAPITAL LETTER R 239 LATIN CAPITAL LETTER S 240 LATIN CAPITAL LETTER A 241 LATIN CAPITAL LETTER N 242 LATIN CAPITAL LETTER D 243 SPACE 244 LATIN CAPITAL LETTER L 245 LATIN CAPITAL LETTER E 246 LATIN CAPITAL LETTER S 247 LATIN CAPITAL LETTER S 248 HYPHEN-MINUS 249 LATIN CAPITAL LETTER T 250 LATIN CAPITAL LETTER H 251 LATIN CAPITAL LETTER A 252 LATIN CAPITAL LETTER N 253 SPACE 254 LATIN CAPITAL LETTER Q 255 LATIN CAPITAL LETTER U 256 LATIN CAPITAL LETTER O 257 LATIN CAPITAL LETTER T 258 LATIN CAPITAL LETTER A 259 LATIN CAPITAL LETTER T 260 LATIN CAPITAL LETTER I 261 LATIN CAPITAL LETTER O 262 LATIN CAPITAL LETTER N 263 SPACE 264 LATIN CAPITAL LETTER V 265 LATIN CAPITAL LETTER E 266 LATIN CAPITAL LETTER R 267 LATIN CAPITAL LETTER T 268 LATIN CAPITAL LETTER I 269 LATIN CAPITAL LETTER C 270 LATIN CAPITAL LETTER A 271 LATIN CAPITAL LETTER L 272 SPACE 273 LATIN CAPITAL LETTER Q 274 LATIN CAPITAL LETTER U 275 LATIN CAPITAL LETTER E 276 LATIN CAPITAL LETTER S 277 LATIN CAPITAL LETTER T 278 LATIN CAPITAL LETTER I 279 LATIN CAPITAL LETTER O 280 LATIN CAPITAL LETTER N 281 SPACE 282 LATIN CAPITAL LETTER A 283 LATIN CAPITAL LETTER S 284 LATIN CAPITAL LETTER T 285 LATIN CAPITAL LETTER E 286 LATIN CAPITAL LETTER R 287 LATIN CAPITAL LETTER I 288 LATIN CAPITAL LETTER S 289 LATIN CAPITAL LETTER K 290 SPACE 291 LATIN CAPITAL LETTER C 292 LATIN CAPITAL LETTER A 293 LATIN CAPITAL LETTER P 294 LATIN CAPITAL LETTER I 295 LATIN CAPITAL LETTER T 296 LATIN CAPITAL LETTER A 297 LATIN CAPITAL LETTER L 298 SPACE 299 LATIN CAPITAL LETTER S 300 LATIN CAPITAL LETTER O 301 LATIN CAPITAL LETTER L 302 LATIN CAPITAL LETTER I 303 LATIN CAPITAL LETTER D 304 LATIN CAPITAL LETTER U 305 LATIN CAPITAL LETTER S 306 SPACE 307 LATIN CAPITAL LETTER B 308 LATIN CAPITAL LETTER R 309 LATIN CAPITAL LETTER A 310 LATIN CAPITAL LETTER C 311 LATIN CAPITAL LETTER K 312 LATIN CAPITAL LETTER E 313 LATIN CAPITAL LETTER T 314 SPACE 315 LATIN CAPITAL LETTER R 316 LATIN CAPITAL LETTER E 317 LATIN CAPITAL LETTER V 318 LATIN CAPITAL LETTER E 319 LATIN CAPITAL LETTER R 320 LATIN CAPITAL LETTER S 321 LATIN CAPITAL LETTER E 322 SPACE 323 LATIN CAPITAL LETTER P 324 LATIN CAPITAL LETTER E 325 LATIN CAPITAL LETTER R 326 LATIN CAPITAL LETTER C 327 LATIN CAPITAL LETTER E 328 LATIN CAPITAL LETTER N 329 LATIN CAPITAL LETTER T 330 SPACE 331 LATIN CAPITAL LETTER A 332 LATIN CAPITAL LETTER C 333 LATIN CAPITAL LETTER C 334 LATIN CAPITAL LETTER E 335 LATIN CAPITAL LETTER N 336 LATIN CAPITAL LETTER T 337 SPACE 338 LATIN CAPITAL LETTER L 339 LATIN CAPITAL LETTER E 340 LATIN CAPITAL LETTER T 341 LATIN CAPITAL LETTER T 342 LATIN CAPITAL LETTER E 343 LATIN CAPITAL LETTER R 344 SPACE 345 LATIN CAPITAL LETTER D 346 LATIN CAPITAL LETTER O 347 LATIN CAPITAL LETTER L 348 LATIN CAPITAL LETTER L 349 LATIN CAPITAL LETTER A 350 LATIN CAPITAL LETTER R 351 SPACE 352 LATIN CAPITAL LETTER E 353 LATIN CAPITAL LETTER Q 354 LATIN CAPITAL LETTER U 355 LATIN CAPITAL LETTER A 356 LATIN CAPITAL LETTER L 357 LATIN CAPITAL LETTER S 358 SPACE 359 LATIN CAPITAL LETTER S 360 LATIN CAPITAL LETTER Q 361 LATIN CAPITAL LETTER U 362 LATIN CAPITAL LETTER A 363 LATIN CAPITAL LETTER R 364 LATIN CAPITAL LETTER E 365 SPACE 366 LATIN CAPITAL LETTER N 367 LATIN CAPITAL LETTER U 368 LATIN CAPITAL LETTER M 369 LATIN CAPITAL LETTER B 370 LATIN CAPITAL LETTER E 371 LATIN CAPITAL LETTER R 372 SPACE 373 LATIN CAPITAL LETTER D 374 LATIN CAPITAL LETTER I 375 LATIN CAPITAL LETTER G 376 LATIN CAPITAL LETTER I 377 LATIN CAPITAL LETTER T 378 SPACE 379 LATIN CAPITAL LETTER R 380 LATIN CAPITAL LETTER I 381 LATIN CAPITAL LETTER G 382 LATIN CAPITAL LETTER H 383 LATIN CAPITAL LETTER T 384 SPACE 385 LATIN CAPITAL LETTER T 386 LATIN CAPITAL LETTER H 387 LATIN CAPITAL LETTER R 388 LATIN CAPITAL LETTER E 389 LATIN CAPITAL LETTER E 390 SPACE 391 LATIN CAPITAL LETTER C 392 LATIN CAPITAL LETTER O 393 LATIN CAPITAL LETTER L 394 LATIN CAPITAL LETTER O 395 LATIN CAPITAL LETTER N 396 SPACE 397 LATIN CAPITAL LETTER T 398 LATIN CAPITAL LETTER I 399 LATIN CAPITAL LETTER L 400 LATIN CAPITAL LETTER D 401 LATIN CAPITAL LETTER E 402 SPACE 403 LATIN CAPITAL LETTER C 404 LATIN CAPITAL LETTER O 405 LATIN CAPITAL LETTER M 406 LATIN CAPITAL LETTER M 407 LATIN CAPITAL LETTER A 408 SPACE 409 LATIN CAPITAL LETTER C 410 LATIN CAPITAL LETTER U 411 LATIN CAPITAL LETTER R 412 LATIN CAPITAL LETTER L 413 LATIN CAPITAL LETTER Y 414 SPACE 415 LATIN CAPITAL LETTER S 416 LATIN CAPITAL LETTER P 417 LATIN CAPITAL LETTER A 418 LATIN CAPITAL LETTER C 419 LATIN CAPITAL LETTER E 420 SPACE 421 LATIN CAPITAL LETTER S 422 LATIN CAPITAL LETTER M 423 LATIN CAPITAL LETTER A 424 LATIN CAPITAL LETTER L 425 LATIN CAPITAL LETTER L 426 SPACE 427 LATIN CAPITAL LETTER S 428 LATIN CAPITAL LETTER E 429 LATIN CAPITAL LETTER V 430 LATIN CAPITAL LETTER E 431 LATIN CAPITAL LETTER N 432 SPACE 433 LATIN CAPITAL LETTER E 434 LATIN CAPITAL LETTER I 435 LATIN CAPITAL LETTER G 436 LATIN CAPITAL LETTER H 437 LATIN CAPITAL LETTER T 438 SPACE 439 LATIN CAPITAL LETTER G 440 LATIN CAPITAL LETTER R 441 LATIN CAPITAL LETTER A 442 LATIN CAPITAL LETTER V 443 LATIN CAPITAL LETTER E 444 SPACE 445 LATIN CAPITAL LETTER L 446 LATIN CAPITAL LETTER A 447 LATIN CAPITAL LETTER T 448 LATIN CAPITAL LETTER I 449 LATIN CAPITAL LETTER N 450 SPACE 451 LATIN CAPITAL LETTER N 452 LATIN CAPITAL LETTER I 453 LATIN CAPITAL LETTER N 454 LATIN CAPITAL LETTER E 455 SPACE 456 LATIN CAPITAL LETTER F 457 LATIN CAPITAL LETTER O 458 LATIN CAPITAL LETTER U 459 LATIN CAPITAL LETTER R 460 SPACE 461 LATIN CAPITAL LETTER P 462 LATIN CAPITAL LETTER L 463 LATIN CAPITAL LETTER U 464 LATIN CAPITAL LETTER S 465 SPACE 466 LATIN CAPITAL LETTER F 467 LATIN CAPITAL LETTER I 468 LATIN CAPITAL LETTER V 469 LATIN CAPITAL LETTER E 470 SPACE 471 LATIN CAPITAL LETTER L 472 LATIN CAPITAL LETTER I 473 LATIN CAPITAL LETTER N 474 LATIN CAPITAL LETTER E 475 SPACE 476 LATIN CAPITAL LETTER L 477 LATIN CAPITAL LETTER E 478 LATIN CAPITAL LETTER F 479 LATIN CAPITAL LETTER T 480 SPACE 481 LATIN CAPITAL LETTER S 482 LATIN CAPITAL LETTER T 483 LATIN CAPITAL LETTER O 484 LATIN CAPITAL LETTER P 485 SPACE 486 LATIN CAPITAL LETTER M 487 LATIN CAPITAL LETTER A 488 LATIN CAPITAL LETTER R 489 LATIN CAPITAL LETTER K 490 SPACE 491 LATIN CAPITAL LETTER F 492 LATIN CAPITAL LETTER U 493 LATIN CAPITAL LETTER L 494 LATIN CAPITAL LETTER L 495 SPACE 496 LATIN CAPITAL LETTER S 497 LATIN CAPITAL LETTER I 498 LATIN CAPITAL LETTER G 499 LATIN CAPITAL LETTER N 500 SPACE 501 LATIN CAPITAL LETTER Z 502 LATIN CAPITAL LETTER E 503 LATIN CAPITAL LETTER R 504 LATIN CAPITAL LETTER O 505 SPACE 506 LATIN CAPITAL LETTER T 507 LATIN CAPITAL LETTER W 508 LATIN CAPITAL LETTER O 509 SPACE 510 LATIN CAPITAL LETTER O 511 LATIN CAPITAL LETTER N 512 LATIN CAPITAL LETTER E 513 SPACE 514 LATIN CAPITAL LETTER L 515 LATIN CAPITAL LETTER O 516 LATIN CAPITAL LETTER W 517 SPACE 518 LATIN CAPITAL LETTER S 519 LATIN CAPITAL LETTER I 520 LATIN CAPITAL LETTER X 521 SPACE 522 LATIN CAPITAL LETTER A 523 LATIN CAPITAL LETTER T 524 QUOTATION MARK 525 COMMA 526 LATIN SMALL LETTER W 527 RIGHT PARENTHESIS 528 SEMICOLON 529 LATIN SMALL LETTER Y 530 EQUALS SIGN 531 LATIN SMALL LETTER W 532 LEFT SQUARE BRACKET 533 DIGIT TWO 534 RIGHT SQUARE BRACKET 535 SEMICOLON 536 LATIN SMALL LETTER F 537 LATIN SMALL LETTER O 538 LATIN SMALL LETTER R 539 LEFT PARENTHESIS 540 LATIN SMALL LETTER X 541 EQUALS SIGN 542 LATIN SMALL LETTER W 543 LEFT SQUARE BRACKET 544 DIGIT ONE 545 RIGHT SQUARE BRACKET 546 SEMICOLON 547 LATIN SMALL LETTER I 548 PLUS SIGN 549 PLUS SIGN 550 LESS-THAN SIGN 551 DIGIT TWO 552 DIGIT SIX 553 SEMICOLON 554 LATIN SMALL LETTER X 555 EQUALS SIGN 556 LATIN SMALL LETTER X 557 QUOTATION MARK 558 LATIN SMALL LETTER N 559 LATIN CAPITAL LETTER W 560 RIGHT SQUARE BRACKET 561 COMMA 562 QUOTATION MARK 563 RIGHT PARENTHESIS 564 LATIN SMALL LETTER Y 565 EQUALS SIGN 566 LATIN SMALL LETTER Y 567 QUOTATION MARK 568 LATIN SMALL LETTER N 569 LATIN SMALL LETTER J 570 RIGHT SQUARE BRACKET 571 COMMA 572 QUOTATION MARK 573 SEMICOLON 574 LATIN SMALL LETTER F 575 LATIN SMALL LETTER O 576 LATIN SMALL LETTER R 577 LEFT PARENTHESIS 578 LATIN SMALL LETTER S 579 LATIN SMALL LETTER P 580 LATIN SMALL LETTER L 581 LATIN SMALL LETTER I 582 LATIN SMALL LETTER T 583 LEFT PARENTHESIS 584 LATIN SMALL LETTER X 585 SPACE 586 LATIN SMALL LETTER Y 587 SPACE 588 LATIN SMALL LETTER W 589 LEFT SQUARE BRACKET 590 DIGIT THREE 591 RIGHT SQUARE BRACKET 592 COMMA 593 LATIN SMALL LETTER B 594 COMMA 595 QUOTATION MARK 596 COMMA 597 QUOTATION MARK 598 RIGHT PARENTHESIS 599 SEMICOLON 600 LATIN SMALL LETTER J 601 PLUS SIGN 602 PLUS SIGN 603 LESS-THAN SIGN 604 DIGIT ONE 605 DIGIT TWO 606 DIGIT SIX 607 SEMICOLON 608 LATIN CAPITAL LETTER F 609 LATIN CAPITAL LETTER S 610 EQUALS SIGN 611 LOW LINE 612 RIGHT PARENTHESIS 613 LATIN SMALL LETTER D 614 LEFT SQUARE BRACKET 615 LATIN SMALL LETTER S 616 LATIN SMALL LETTER P 617 LATIN SMALL LETTER R 618 LATIN SMALL LETTER I 619 LATIN SMALL LETTER N 620 LATIN SMALL LETTER T 621 LATIN SMALL LETTER F 622 LEFT PARENTHESIS 623 QUOTATION MARK 624 PERCENT SIGN 625 LATIN SMALL LETTER C 626 QUOTATION MARK 627 COMMA 628 LATIN SMALL LETTER J 629 RIGHT PARENTHESIS 630 RIGHT SQUARE BRACKET 631 EQUALS SIGN 632 LATIN SMALL LETTER J 633 RIGHT CURLY BRACKET 634 LEFT CURLY BRACKET 635 LATIN SMALL LETTER F 636 LATIN SMALL LETTER O 637 LATIN SMALL LETTER R 638 LEFT PARENTHESIS 639 LATIN SMALL LETTER K 640 EQUALS SIGN 641 DIGIT ZERO 642 SEMICOLON 643 LATIN SMALL LETTER K 644 PLUS SIGN 645 PLUS SIGN 646 LESS-THAN SIGN 647 LATIN CAPITAL LETTER N 648 LATIN CAPITAL LETTER F 649 SEMICOLON 650 LATIN SMALL LETTER P 651 LATIN SMALL LETTER R 652 LATIN SMALL LETTER I 653 LATIN SMALL LETTER N 654 LATIN SMALL LETTER T 655 SPACE 656 LATIN SMALL LETTER I 657 EQUALS SIGN 658 LOW LINE 659 RIGHT PARENTHESIS 660 LATIN SMALL LETTER W 661 LATIN SMALL LETTER H 662 LATIN SMALL LETTER I 663 LATIN SMALL LETTER L 664 LATIN SMALL LETTER E 665 LEFT PARENTHESIS 666 LATIN SMALL LETTER I 667 PLUS SIGN 668 PLUS SIGN 669 LESS-THAN SIGN 670 LATIN SMALL LETTER S 671 LATIN SMALL LETTER P 672 LATIN SMALL LETTER L 673 LATIN SMALL LETTER I 674 LATIN SMALL LETTER T 675 LEFT PARENTHESIS 676 LATIN SMALL LETTER B 677 LEFT SQUARE BRACKET 678 LATIN SMALL LETTER D 679 LEFT SQUARE BRACKET 680 DOLLAR SIGN 681 LATIN SMALL LETTER K 682 RIGHT SQUARE BRACKET 683 HYPHEN-MINUS 684 DIGIT THREE 685 DIGIT ONE 686 RIGHT SQUARE BRACKET 687 COMMA 688 LATIN SMALL LETTER Q 689 RIGHT PARENTHESIS 690 RIGHT PARENTHESIS 691 LATIN SMALL LETTER P 692 LATIN SMALL LETTER R 693 LATIN SMALL LETTER I 694 LATIN SMALL LETTER N 695 LATIN SMALL LETTER T 696 LATIN SMALL LETTER F 697 LEFT PARENTHESIS 698 LATIN SMALL LETTER Z 699 EQUALS SIGN 700 LATIN SMALL LETTER W 701 LEFT SQUARE BRACKET 702 LATIN SMALL LETTER D 703 LEFT SQUARE BRACKET 704 LATIN SMALL LETTER Q 705 LEFT SQUARE BRACKET 706 LATIN SMALL LETTER I 707 RIGHT SQUARE BRACKET 708 RIGHT SQUARE BRACKET 709 HYPHEN-MINUS 710 DIGIT SIX 711 DIGIT NINE 712 RIGHT SQUARE BRACKET 713 RIGHT PARENTHESIS 714 QUOTATION MARK 715 SPACE 716 QUOTATION MARK 717 LEFT PARENTHESIS 718 LATIN SMALL LETTER Z 719 TILDE 720 SOLIDUS 721 LATIN CAPITAL LETTER T 722 LATIN CAPITAL LETTER T 723 SOLIDUS 724 QUESTION MARK 725 LATIN SMALL LETTER T 726 LATIN SMALL LETTER O 727 LATIN SMALL LETTER U 728 LATIN SMALL LETTER P 729 LATIN SMALL LETTER P 730 LATIN SMALL LETTER E 731 LATIN SMALL LETTER R 732 LEFT PARENTHESIS 733 DOLLAR SIGN 734 LATIN SMALL LETTER K 735 RIGHT PARENTHESIS 736 COLON 737 LOW LINE 738 RIGHT PARENTHESIS 739 RIGHT CURLY BRACKET ``` Just kidding ;D ``` BEGIN{split("i,Lv,Sv,ax,^x,[x,Q,O,tK,cK,V,qx,g,I,wu,X,by,b{,bz,bd,bp,br,b},bk,bl,bo,e,P,Rx,_x,Jx,Uv,M~, t`Y,ZX,c`Y,N\\,|s,m\\, thY,Ts,chY,f HYPHEN-MINUS GREATER-THAN PARENTHESIS EXCLAMATION COMMERCIAL CIRCUMFLEX APOSTROPHE SEMICOLON AMPERSAND LESS-THAN QUOTATION VERTICAL QUESTION ASTERISK CAPITAL SOLIDUS BRACKET REVERSE PERCENT ACCENT LETTER DOLLAR EQUALS SQUARE NUMBER DIGIT RIGHT THREE COLON TILDE COMMA CURLY SPACE SMALL SEVEN EIGHT GRAVE LATIN NINE FOUR PLUS FIVE LINE LEFT STOP MARK FULL SIGN ZERO TWO ONE LOW SIX AT",w);x=w[1];for(y=w[2];C++<26;x=x"nW],")y=y"nj],";for(split(x y w[3],b,",");j++<126;FS=_)d[sprintf("%c",j)]=j}{for(k=0;k++<NF;print i=_)while(i++<split(b[d[$k]-31],q))printf(z=w[d[q[i]]-69])" "(z~/TT/?toupper($k):_)} ``` Works with stdin/stdout. More "readable": ``` BEGIN{ # This string (508 bytes) holds a representation of the character names in # the right order, plus a list of the used words. split("i,Lv,Sv,ax,^x,[x,Q,O,tK,cK,V,qx,g,I,wu,X,by,b{,bz,bd,bp,br,b},bk,bl,bo, e,P,Rx,_x,Jx,Uv,M~, t`Y,ZX,c`Y,N\\,|s,m\\, thY,Ts,chY,f HYPHEN-MINUS GREATER-T HAN PARENTHESIS EXCLAMATION COMMERCIAL CIRCUMFLEX APOSTROPHE SEMICOLON AMPERSA ND LESS-THAN QUOTATION VERTICAL QUESTION ASTERISK CAPITAL SOLIDUS BRACKET REVE RSE PERCENT ACCENT LETTER DOLLAR EQUALS SQUARE NUMBER DIGIT RIGHT THREE COLON TILDE COMMA CURLY SPACE SMALL SEVEN EIGHT GRAVE LATIN NINE FOUR PLUS FIVE LINE LEFT STOP MARK FULL SIGN ZERO TWO ONE LOW SIX AT",w); # Since the letters each appear 26 times I construct that part at runtime. # The array b will hold the coded combinations of which words need to # be printed for each input character. x=w[1]; for(y=w[2];C++<26;x=x"nW],") y=y"nj],"; # The array d is an ASCIICodeFromChar function replacement. # I set the field separator to empty, so each character of the input is # an input field. That's why using a BEGIN part was mandatory. for(split(x y w[3],b,",");j++<126;FS=_) d[sprintf("%c",j)]=j } # Here I go through the element of b that matches the input and print # the requested words, using the input to produce a capital letter if # needed. I excluded these from the word list to save another 26 bytes { for(k=0;k++<NF;print i=_) while(i++<split(b[d[$k]-31],q)) printf(z=w[d[q[i]]-69])" "(z~/TT/?toupper($k):_) } ``` [Answer] # C++11, 739 bytes ``` #include<iostream> #define D,"DIGIT " #define G" SIGN", int main(){std::string a=" BRACKET",s="SQUARE"+a,c="CURLY"+a,t="TION MARK",p="PARENTHESIS",l="LEFT ",r="RIGHT ",x="LATIN ",y="L LETTER ",z[]{"SPACE","EXCLAMA"+t,"QUOTA"+t,"NUMBER"G"DOLLAR"G"PERCENT"G"AMPERSAND","APOSTROPHE",l+p,r+p,"ASTERISK","PLUS"G"COMMA","HYPHEN-MINUS","FULL STOP","SOLIDUS"D"ZERO"D"ONE"D"TWO"D"THREE"D"FOUR"D"FIVE"D"SIX"D"SEVEN"D"EIGHT"D"NINE","COLON","SEMICOLON","LESS-THAN"G"EQUALS"G"GREATER-THAN"G"QUES"+t,"COMMERCIAL AT",l+s,"REVERSE SOLIDUS",r+s,"CIRCUMFLEX ACCENT","LOW LINE","GRAVE ACCENT",l+c,"VERTICAL LINE",r+c,"TILDE"};getline(std::cin,s);for(char c:s)std::cout<<(c<65?z[c-32]:c<91?x+"CAPITA"+y+c:(c-=32,c<65?z[c-26]:c<91?x+"SMAL"+y+c:z[c-52]))+"\n";} ``` Based on sweerpotato's solution, but modified heavily. [Answer] # Common Lisp (SBCL), ~~52~~ 79 ``` (map()(lambda(y)(format t"~:@(~A~)~%"(substitute #\ #\_(char-name y))))(read)) ``` This is built-in and implementation-dependent, so you may want to ignore it when choosing the accepted answer. This is not enough to beat [Python](https://codegolf.stackexchange.com/a/57158/903), unfortunately. The updated version conforms to the expected output (I have to replace underscores by spaces). ## Example ``` CL-USER> (map()(lambda(y)(format t"~:@(~A~)~%"(substitute #\ #\_(char-name y))))(read)) "(λ(r)(* 2 ᴨ r))" LEFT PARENTHESIS GREEK SMALL LETTER LAMDA LEFT PARENTHESIS LATIN SMALL LETTER R RIGHT PARENTHESIS LEFT PARENTHESIS ASTERISK SPACE DIGIT TWO SPACE GREEK LETTER SMALL CAPITAL PI SPACE LATIN SMALL LETTER R RIGHT PARENTHESIS RIGHT PARENTHESIS ``` [Answer] ## C++14, 1043 1000 998 996 972 bytes Grotesque solution in C++14: ``` #include<iostream> #include<map> #define b cout #define d string #define e },{ using namespace std;char l='\n';d s[]{"DIGIT ","LATIN CAPITAL LETTER ","LATIN SMALL LETTER "};map<char, d> m{{' ',"SPACE"e'!',"EXCLAMATION MARK"e'\"',"QUOTATION MARK"e'#',"NUMBER SIGN"e'$',"DOLLAR SIGN"e'%',"PERCENT SIGN"e'&',"AMPERSAND"e'\'',"APOSTROPHE"e'(',"LEFT PARENTHESIS"e')',"RIGHT PARENTHESIS"e'*',"ASTERISK"e'+',"PLUS SIGN"e',',"COMMA"e'-',"HYPHEN-MINUS"e'.',"FULL STOP"e'/',"SOLIDUS"e':',"COLON"e';',"SEMICOLON"e'<',"LESS-THAN SIGN"e'=',"EQUALS SIGN"e'>',"GREATER-THAN SIGN"e'?',"QUESTION MARK"e'@',"COMMERCIAL AT"e'[',"LEFT SQUARE BRACKET"e'\\',"REVERSE SOLIDUS"e']',"RIGHT SQUARE BRACKET"e'^',"CIRCUMFLEX ACCENT"e'_',"LOW LINE"e'`',"GRAVE ACCENT"e'{',"LEFT CURLY BRACKET"e'|',"VERTICAL LINE"e'}',"RIGHT CURLY BRACKET"e'~',"TILDE"}};int main(){d str;getline(cin,str);for(char c:str){islower(c)?b<<s[2]<<(char)(c-32):isupper(c)?b<<s[1]<<c:isdigit(c)?b<<*s<<c:b<<m.at(c);b<<l;}} ``` *Thanks to kirbyfan64sos for golfing off two bytes* [Answer] # Pyth, 41 ``` $from unicodedata import name as neg$Vz_N ``` Uses same builtin as [mbomb007's python answer](https://codegolf.stackexchange.com/a/57158/31625). Note that this cannot be executed online because the `$` operator is unsafe. [Answer] # CJam, 517 ``` l{i32-["SPACE""EXCLAMA""TION MARK":T+"QUOTA"T+"NUMBER DOLLAR PERCENT"{S/" SIGN"am*~}:H~"AMPERSAND""APOSTROPHE""LEFT PARENTHESIS":L"RIGHT ":R1$5>+"ASTERISK""PLUS"H"COMMA""HYPHEN-MINUS""FULL STOP""SOLIDUS":D"DIGIT "a"ZERO ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE"S/m*~"COLON""SEMI"1$+"LESS-THAN EQUALS GREATER-THAN"H"QUES"T+"COMMERCIAL AT""CAPITA"{["LATIN "\"L LETTER "]a'[,65>m*~L5<}:Z~"SQUARE BRACKET":Q+"REVERSE "D+RQ+"CIRCUMFLEX ACCENT""LOW LINE""GRAVE"2$A>+"SMAL"Z"CURLY"33$B>+:C+"VERTICAL LINE"RC+"TILDE"]=N}/ ``` [Online version](http://cjam.aditsu.net/#code=l%7Bi32-%5B%22SPACE%22%22EXCLAMA%22%22TION%20MARK%22%3AT%2B%22QUOTA%22T%2B%22NUMBER%20DOLLAR%20PERCENT%22%7BS%2F%22%20SIGN%22am*~%7D%3AH~%22AMPERSAND%22%22APOSTROPHE%22%22LEFT%20PARENTHESIS%22%3AL%22RIGHT%20%22%3AR1%245%3E%2B%22ASTERISK%22%22PLUS%22H%22COMMA%22%22HYPHEN-MINUS%22%22FULL%20STOP%22%22SOLIDUS%22%3AD%22DIGIT%20%22a%22ZERO%20ONE%20TWO%20THREE%20FOUR%20FIVE%20SIX%20SEVEN%20EIGHT%20NINE%22S%2Fm*~%22COLON%22%22SEMI%221%24%2B%22LESS-THAN%20EQUALS%20GREATER-THAN%22H%22QUES%22T%2B%22COMMERCIAL%20AT%22%22CAPITA%22%7B%5B%22LATIN%20%22%5C%22L%20LETTER%20%22%5Da'%5B%2C65%3Em*~L5%3C%7D%3AZ~%22SQUARE%20BRACKET%22%3AQ%2B%22REVERSE%20%22D%2BRQ%2B%22CIRCUMFLEX%20ACCENT%22%22LOW%20LINE%22%22GRAVE%222%24A%3E%2B%22SMAL%22Z%22CURLY%2233%24B%3E%2B%3AC%2B%22VERTICAL%20LINE%22RC%2B%22TILDE%22%5D%3DN%7D%2F) I have tried different solutions but simply storing all the names in a huge array seems most efficient. This is my first real CJam program by the way. [Answer] # Clojure, 56 bytes ``` (doseq[c(read-line)](println(Character/getName(int c)))) ``` Inspired by @peter's answer. Uses Clojure for the Java interop. [Answer] # Perl - 894 bytes Lovingly crafted by hand. First time golfing in Perl so any tips are appreciated. ``` $_=$ARGV[0];s/(.)/$1\n/g;s/([A-Z])/& CAPITAL' $1/g;s/([a-z])/& SMALL' \U$1/g;s/,/COMMA/g;s/& /LATIN /g;s/' / LETT, /g;s/&/AMP,SAND/g;s/'/APOSTROPHE/g;s/ \n/SPACE\n/g;s/\*/AST,ISK/g;s/-/HYPHEN-MINUS/g;s/\./FULL STOP/g;s/@/COMM,CIAL AT/g;s/~/TILDE/g;s/:/&/g;s/;/SEMI&/g;s/&/COLON/g;s/\|/V,TICAL&/g;s/_/LOW&/g;s/&/ LINE/g;s/\^/CIRCUMFLEX&/g;s/`/GRAVE&/g;s/&/ ACCENT/g;s/\//&/g;s/\\/REV,SE &/g;s/&/SOLIDUS/g;s/!/!&/g;s/"/"&/g;s/\?/?&/g;s/!/EXCLAMA/g;s/"/QUOTA/g;s/\?/QUES/g;s/&/TION MARK/g;s/#/NUMB,&/g;s/\$/DOLLAR&/g;s/%/P,CENT&/g;s/\+/PLUS&/g;s/</LESS-THAN&/g;s/=/EQUALS&/g;s/>/GREAT,-THAN&/g;s/&/ SIGN/g;s/\(/<&/g;s/\)/>&/g;s/&/ PARENTHESIS/g;s/\[/<&/g;s/\]/>&/g;s/&/ SQUARE'/g;s/{/<&/g;s/}/>&/g;s/&/ CURLY'/g;s/'/ BRACKET/g;s/</LEFT/g;s/>/RIGHT/g;s/0/&Z,O/g;s/1/&ONE/g;s/2/&TWO/g;s/3/&THREE/g;s/4/&FOUR/g;s/5/&FIVE/g;s/6/&SIX/g;s/7/&SEVEN/g;s/8/&EIGHT/g;s/9/&NINE/g;s/&/DIGIT /g;s/,/ER/g;print; ``` [Answer] ## C++14 ~~716~~ ~~706~~ 704 ``` #include<iostream> char*q,x,b[584],*t=b,a[]=R"(space}exclamation|mark}quot"-number|sign}dolla!apercent!mam"%sand}apostrophe}left|par%3hesis}righ"Wasterisk}plus*<comma}hy)#n{minus}full|stop}solid"Ldigit|zero!Tone!Gtw"kthre#&four!Uiv#&six!Heve>^!_e6r!ani,1colon}semi!Fless{than8Eequal:$grea<s$2quesMj>EJoial|at}lQ9n|capit"?let('|Jes+\re|bracket}r5urse|C5M?%2circumflex|acXR}low|l:bgrave#'0=smaNy0+curly*s/Ytic4z)$/\$itilde)",*s=a;int c,z,l='{';int main(){for(;x=*s++;)if(z=x-32,x>96)*t++=x<l?z:"- "[x%l];else for(c=z*95+*s++-32,q=t-c/13,x=3+c%13;x--;)*t++=*q++;while(std::cin.get(x)){for(s=b,z=0,c=x<65?x-32:x<91?z=33:x<97?x-57:x<l?z=40:x-82;c--;)while(*s++);auto&o=std::cout<<s;(z?o.put(x&~32):o)<<"\n";}} ``` [Live version](http://ideone.com/7iG4Vf). With some whitespace: ``` #include <iostream> // a is compressed using an LZ like compression scheme char *q, x, b[584], *t = b, a[] = R"(space}exclamation|mark}quot"-number|sign}dolla!apercent!mam"%sand}apostrophe}left|par%3hesis}righ"Wasterisk}plus*<comma}hy)#n{minus}full|stop}solid"Ldigit|zero!Tone!Gtw"kthre#&four!Uiv#&six!Heve>^!_e6r!ani,1colon}semi!Fless{than8Eequal:$grea<s$2quesMj>EJoial|at}lQ9n|capit"?let('|Jes+\re|bracket}r5urse|C5M?%2circumflex|acXR}low|l:bgrave#'0=smaNy0+curly*s/Ytic4z)$/\$itilde)", *s = a; int c, z, l = '{'; int main() { // Decompress from a into b for (; x = *s++;) if (z = x - 32, x > 96) *t++ = x < l ? z : "- "[x % l]; else for (c = z * 95 + *s++ - 32, q = t - c / 13, x = 3 + c % 13; x--;) *t++ = *q++; // Process input a char at a time, performing a lookup into b for the c'th null separated string while (std::cin.get(x)) { for (s = b, z = 0, c = x < 65 ? x - 32 : x < 91 ? z = 33 : x < 97 ? x - 57 : x < l ? z = 40 : x - 82; c--;) while (*s++) ; auto& o = std::cout << s; (z ? o.put(x & ~32) : o) << "\n"; } } ``` The compressed string `a` decompresses to: > > space}exclamation|mark}quotation|mark}number|sign}dollar|sign}percent|sign}ampersand}apostrophe}left|parenthesis}right|parenthesis}asterisk}plus|sign}comma}hyphen{minus}full|stop}solidus}digit|zero}digit|one}digit|two}digit|three}digit|four}digit|five}digit|six}digit|seven}digit|eight}digit|nine}colon}semicolon}less{than|sign}equals|sign}greater{than|sign}question|mark}commercial|at}latin|capital|letter|}left|square|bracket}reverse|solidus}right|square|bracket}circumflex|accent}low|line}grave|accent}latin|small|letter|}left|curly|bracket}vertical|line}right|curly|bracket}tilde > > > And during decompression `}` is replaced with `\0`, `|` with (space) and `{` with `-` and lowercase letters are converted to uppercase. The string is compressed LZ style as either a literal `[a-~]` or a two character encoded offset/length to a match earlier in the string. [Answer] # Factor, 58 bytes ``` [ readln [ char>name "-"" " replace >upper print ] each ] ``` Pretty simple; does the exact same thing as the Java and Perl 6 answers. [Answer] # [Go](//golang.org), 145 bytes ``` package main import(."golang.org/x/text/unicode/runenames" ."fmt") func main(){r:='!' for{_,e:=Scanf("%c",&r) if e!=nil{break} println(Name(r))}} ``` Some have address a concern with the above answer. I tried vendoring the code in question, but my answer bypassed the 65,536 byte limit [1], so I think the above answer is fine as is. 1. <https://github.com/golang/text/blob/v0.3.6/unicode/runenames/tables13.0.0.go> [Answer] # PHP>=7, 54 Bytes ``` for(;a&$c=$argn[$i++];)echo" ".IntlChar::charName($c); ``` [IntlChar::charName](http://php.net/manual/en/intlchar.charname.php) ]
[Question] [ What, this post doesn't exist yet? Of course, [GolfScript](http://www.golfscript.com/golfscript/) is *made* for golfing, so you might think that no specific tips are really needed. But to make full use of GolfScript's features, you need to learn some non-obvious tricks. This post is for collecting such helpful tips and tricks. To start with, here are the official GolfScript reference pages. You should really familiarize yourself with these first: * [Tutorial](http://www.golfscript.com/golfscript/tutorial.html) * [Syntax](http://www.golfscript.com/golfscript/syntax.html) * [Built-ins](http://www.golfscript.com/golfscript/builtin.html) * [Quick reference](http://www.golfscript.com/golfscript/quickref.html) In particular, I would very much suggest reading the pages in this order — the quick reference is of little use until you're already reasonably familiar with the built-ins, and the tutorial includes some important details that are not explained on the other pages. --- Ps. For the sake of inspiration and personal interest, here are some questions *I'd* like to see nice answers to: * How to do limited transliteration in GolfScript? `{FROM?TO=}%` works *if* you can be sure all the inputs are found in `FROM` (or don't mind them all being mapped to the last element of `TO`), but all the ways I've seen for leaving unmapped values unchanged have been more or less klugey. * How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like `~` does for arrays)? [Answer] ## Rational / Float / Complex I've read so many times that GolfScript has only integers that I started to believe it. Well, it's not true. ``` 2-1? # Raise 2 to the power of -1. Result: 0.5 4-1? # Raise 4 to the power of -1. Result: 0.25 + # Add. Result: 0.75 ``` The output is ``` 3/4 ``` with the standard GolfScript interpreter and ``` 0.75 ``` on [Web GolfScript](http://golfscript.apphb.com/?c=Mi0xPyAjIFJhaXNlIDIgdG8gdGhlIHBvd2VyIG9mIC0xLiBSZXN1bHQ6IDAuNQo0LTE%2FICMgUmFpc2UgNCB0byB0aGUgcG93ZXIgb2YgLTEuIFJlc3VsdDogMC4yNQorICAgICMgQWRkLiBSZXN1bHQ6IDAuNzU%3D). Similar hacks allow to cast to Rational, Float or even Complex: ``` {-2.?./*}:rational {2.-1??./*}:float {-2.-1??./*}:complex ``` [Answer] # Shuffling an array The easiest way to shuffle an array in GolfScript is to sort it by a random sort key. If you only need to crudely shuffle a few values, the following code will do: ``` {;9rand}$ ``` Note that, even for short lists, this will not give a very good shuffle. Due to the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_paradox), to get a reasonably uniform shuffle, the argument to `rand` needs to be significantly greater than the square of the length of the list being shuffled. Replacing the `9` above with `99` thus gives reasonably good results for lists of up to ten elements, but exhibits noticeable bias for longer lists. The following code, which uses 99 = 387,420,489 possible values, is good for up to about 1000 items or so (and acceptable for up to about 20,000): ``` {;9.?rand}$ ``` For really long lists, add one more 9 for 9999 ≈ 3.7 × 10197 values: ``` {;99.?rand}$ ``` --- ### Testing: Here's the distribution of the first element in a 10-element list shuffled using the different variants shown above, sampled over 10,000 trials: * The output of `10,{;9rand}$0=` shows a very clear bias, with `0` being more than three times as likely to end up in the first position as `1`: ``` 0 16537 ####################################################### 1 5444 ################## 2 7510 ######################### 3 8840 ############################# 4 9124 ############################## 5 12875 ########################################## 6 9534 ############################### 7 8203 ########################### 8 7300 ######################## 9 14633 ################################################ ``` * With `10,{;99rand}$0=`, most of the bias is gone, but a noticeable amount still remains: ``` 0 10441 ################################## 1 9670 ################################ 2 9773 ################################ 3 9873 ################################ 4 10134 ################################# 5 10352 ################################## 6 10076 ################################# 7 9757 ################################ 8 9653 ################################ 9 10271 ################################## ``` * With `10,{;9.?rand}$0=`, the output is basically indistinguishable from a truly random sample: ``` 0 9907 ################################# 1 9962 ################################# 2 10141 ################################# 3 10192 ################################# 4 9965 ################################# 5 9971 ################################# 6 9957 ################################# 7 9984 ################################# 8 9927 ################################# 9 9994 ################################# ``` --- **Ps.** For *really* bad shuffling of numeric arrays or strings, the following code may sometimes be acceptable: ``` {rand}$ ``` It will generally be ridiculously biased, but as long as all elements of the input array (or all character codes in the string) are greater than one, it has a non-zero probability of producing any permutation of the array, which may sometimes satisfy poorly written challenge requirements. [Answer] # Negating a number One thing GolfScript lacks is a built-in negation operator. The obvious ways to convert a number on the stack to its negative, like `-1*` or `0\-`, need three chars. However, there's a way to do it in two: ``` ~) ``` This works because GolfScript uses [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) arithmetic, so that ~*x* equals −*x*−1. Of course, the variant `(~` also works; choosing between them is generally a matter of taste. [Answer] ## If your program mysteriously breaks, check your variables I just spent a while debugging an apparently correct program which used `!` as a variable (on the grounds that I wasn't going to use it again). Unfortunately I *did* use `if`, and it turns out that the implementation of `if` calls `!` to decide which branch to follow. [Answer] To address a specific subquestion: > > How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)? > > > For those who don't understand the problem, GolfScript's type system gives priority to the types in the order integer, array, string, block. This means that ordinary array operations applied to a string almost always give you a string. E.g. ``` 'ABC123'{)}% ``` will leave `'BCD234'` on the stack. As a result, the best way to convert a string into an array of ASCII codes is almost certainly to dump the characters on the stack and then gather them into an array. What's the best way to dump the characters in a string onto the stack? `{}/` What's the best way to convert a string into an array of ASCII codes? `[{}/]` (with the usual caveat that if there's nothing else on the stack you can skip the `[`) What's the best way to convert an array of ASCII codes into a string? `''+` (Note that this also flattens the array, so e.g. `[65 [66 67] [[[49] 50] 51]]''+` gives `'ABC123'`) [Answer] ## Wrapping the top item of the stack into an array > > Is there a nice way to transform `... x` into `... [x]`? > > > For full generality, the best option appears to be 4 chars. However, in certain special cases it's possible to reduce this. ### 1 char `]` works in the special case that `x`is the only thing on the stack. ### 3 chars `[]+` works in the special case that `x` is an integer. `.,/` works in the special case that `x` is a truthy array or string. E.g. `"AB".,/` gives `["AB"]`; `3,.,/` gives `[[0 1 2]]`. However, `"".,/` and `[].,/` both give `[]`. ### 4 chars `[.;]` works unconditionally. [Answer] > > I'd like to ask the best ways to do: min, max, and absolute value. All my solutions seem to take way more characters than they should.   – Claudiu > > > ## min / max To find the smallest / largest value in an array, just sort it and take the first / last element: * `$0=` (3 chars) - minimum element in an arry * `$-1=` (4 chars) - maximum element in an array If you know the length of the array, and it's 10 elements or less, you can find the maximum in three chars by replacing `-1` with the index of the last element. If you have the values on the stack, you can just collect them into an array first. For this, an occasionally useful trick is that `[\]` collects the top two elements of the stack into an array, while `[@]` collects the top three. Thus, we get: * `[\]$0=` (6 chars) - minimum of two values on stack * `[@]$0=` (6 chars) - minimum of three values on stack * `[\]$1=` (6 chars) - maximum of two values on stack * `[@]$2=` (6 chars) - maximum of three values on stack The same trick can also be used to find the **median** of three values, which can be occasionally useful: * `[@]$1=` (6 chars) - median of three values on stack --- Here's another potentially useful trick for finding the min/max of two values *while leaving the original values on the stack*: * `.2$>$` (5 chars) - find minimum of two values on stack, while leaving original values untouched * `.2$<$` (5 chars) - find maximum of two values on stack, while leaving original values untouched The way it works is that `.2$` clones the top two elements on the stack in reversed order (i.e. `a b` → `a b b a`), `<` / `>` compares the copies and returns 0 or 1, and scalar `$` then copies either of the two input values depending on the result of the comparison. --- If you have two nonnegative integers on the stack, you can use `,\,&,` (5 chars) to find their minimum and `,\,|,` (5 chars) to find their maximum. This trick uses set intersection and union, respectively, over the ranges. You can save another character if it's possible to apply `,` to each argument separately without having to exchange them. Since this method computes a range for each argument, it's not very efficient for larger numbers, but could be very useful for smaller inputs. An even shorter way to find the minimum of two non-negative integers on the stack is `,<,` (3 chars). Alas, this trick does not work for finding the maximum. --- ## absolute value The GolfScript [built-in absolute value operator](http://www.golfscript.com/golfscript/builtin.html#abs) is `abs` (3 chars). While this is two chars more than I'd prefer, it's hard to beat in general. In some cases (e.g. for sorting by absolute value) you might find the square of a number an adequate substitute for its absolute value; this can be computed in two chars, either `2?` or `.*`. Thus, we get: * `{.*}$0=` (7 chars) - minimum element by absolute value in array * `{.*}$-1=` (8 chars) - maximum element by absolute value in array Similarly, instead of e.g. testing if the absolute value of a number is less than 3 with `abs 3<` (6 chars, including space), you can test if its square is less than 9 with `.*9<` (4 chars, no space needed). [Answer] > > What is the best way to modify an array at a given index?   – user1502040 > > > That's a good question. There's no direct way to assign a value to an array element in GolfScript, so, one way or another, you're going to have to rebuild the whole array. The shortest general way I know to insert a new value `x` at index `i` in an array is to split the array at the given index and append `x` to the first half before joining them together again: * `.i<[x]+\i>+` (11 chars) - insert the value `x` into array at (0-based) index `i` To *replace* the value at index `i` with `x`, we just need to shorten the second half of the array by one element: * `.i<[x]+\i)>+` (12 chars) - replace the element at (0-based) index `i` with the value `x` Alternatively, shortening the first half instead will effectively do the same, but with 1-based indexing, which may sometimes be preferable: * `.i(<[x]+\i>+` (12 chars) - replace the element at (1-based) index `i` with the value `x` In all the examples above, if `x` is a number, the square brackets around it may be omitted to save two characters, since it will be auto-coerced into an array by `+` anyway: * `.i<x+\i>+` (9 chars) - insert the number `x` into array at (0-based) index `i` * `.i<x+\i)>+` (10 chars) - replace the element at (0-based) index `i` with the number `x` * `.i(<x+\i>+` (10 chars) - replace the element at (1-based) index `i` with the number `x` The brackets may also be omitted if either `x` or the input "array" (or both) are actually strings, in which case the result will also be coerced into a string (using the usual array → string conversion rules). --- Ps. As a special case, if we know that the array has between `i` and 2 × `i` elements, we can insert a new element `x` at the (0-based) index `i` with `i/[x]*` (6 chars). What this actually does is split the array into chunks of up to `i` elements and insert `x` between each chunk. Note that, in this case, the brackets are necessary even if `x` is a number. --- Pps. An alternative approach is to use dynamically named variables. For example, ``` 'foo' 42 ':x'\+~ ``` will assign the value `'foo'` to the variable `x42`, while ``` 42 'x'\+~ ``` will retrieve it. You can optimize this further by omitting the `x` prefix and just assigning directly to the numeric literals — this is perfectly legal in GolfScript, and allows you to save one char from the assignment code and shorten the retrieval code to just ``~` (or nothing at all, if the index is constant!). The down side, of course, is that assigning to a numeric literal will override the value of that literal anywhere else in your code. Often, though, the use of number literals can be avoided (or at least restricted to the beginning of the program, before any of them are reassigned), in which case this trick is perfectly fine. [Answer] # Assigning to number literals Often, instead of writing `1:x` and then using/updating the variable `x`, you can just use and update `1` directly: ``` 1:^;{^.p.+:^;}5* {1.p.+:1;}5* (4 bytes shorter) ``` Of course, this also works for other starting values, but will break if that value occurs anywhere else in your code. # Punctuation as variable names If you *have* to use variables, it's also often wise to use punctuation that isn't already in your code -- lots of programs can do without `&`, `|`, `^`, or `?`. This way, for example, you can write `&n` instead of `x n` to push your variable and then push a newline. [Answer] # Final output manipulation By default, when your program ends, the GolfScript interpreter outputs everything on the stack, plus a final newline, exactly as if your program ended with: ``` ]puts ``` What the documentation doesn't directly mention is that the interpreter *literally* calls the built-in [`puts`](http://www.golfscript.com/golfscript/builtin.html#puts) to produce this output, and that this built-in is *literally* defined as: ``` {print n print}:puts; ``` Thus, you can suppress or manipulate the final output by redefining `puts`, `print` and/or `n` (or if you're feeling really twisted). Here are some examples: ### Suppress final newline: ``` '':n; ``` (Of course you can leave out the `;` if you don't mind an extra empty string on the stack.) ### Suppress final output completely: ``` :puts ``` This overwrites `puts` with whatever happens to be on top of the stack. If that happens to be something you don't want to execute, you can use e.g. `0:puts;` instead. Note that this also suppresses `p` (which is defined as `{`puts}:p;`), but you can still use `print` for output if you want. [Answer] ### Limited transliteration To address a specific subquestion: given a string, what's the best way to perform a `tr`? E.g. `tr/ABC/abc/` If all of the characters in the string will be affected, this is quite easy: `{'ABC'?'abc'=}%` (overhead: 9 chars). However, that breaks if some of the characters aren't transliterated and `'ABC'?` gives `-1`. If the transliteration is non-cyclic it can be done one replacement at a time with string splits and joins: `'AaBbCc'1/2/{~@@/\*}/` (overhead: 15 chars). This may be improvable, but there's an alternative approach which is currently better and works for cyclic transliterations. Currently, the shortest general solutions have an overhead of 14 characters: * One approach involves an escape character: `{.'ABC'?'abc**0**'=\or}%`, where the `**0**` denotes a literal null byte. (Of course, this method is not *completely* general: it cannot map any other character into a null byte.) * Alternatively, `{.'ABC'?'abc'@),+=}%` has the same overhead, but uses only printable ASCII characters. The `@),+` is a convoluted (but, apparently, the shortest) way to ensure that the replacement string always ends with the input character. [Answer] # Turn a string to an array of char You can do this by typing: `1/` after it. Example: `"String"1/` pushes to stack the array `['S''t''r''i''n''g']`. This is handy when you want to move chars around the string. [Answer] ## Removing duplicates from an array The set operators `|` (union), `&` (intersection) and `^` (symmetric difference) will collapse multiple array elements into one. Thus, the simplest way to remove duplicate elements from an array is to take its union or intersection with itself: ``` .| ``` or: ``` .& ``` These operators will treat strings as arrays of characters, so they can also be used to remove duplicate characters from strings. [Answer] ## Filtering an array The most general way to filter an array is to use `{ },`, which evaluates the code block for each element of the array, and selects those elements for which the resulting value is true (i.e. it acts like `grep` in Perl). However, using the array subtraction operator `-` is often shorter. This operator takes two arrays, and removes every element that occurs in the second array from the first. It does *not* alter the order of the elements in the first array or collapse duplicates. A useful trick is to apply the subtraction operation twice to yield a non-collapsing array intersection operator: * `a b -`: remove any elements found in array `b` from array `a` * `a. b --`: remove any elements *not* found in array `b` from array `a` --- In particular, this can be used to **count the number of times an element occurs** in an array: * `a.[c]--,`: count the number of times the element `c` occurs in the array `a` In general, this method is not optimal, since either of: * `a[c]/,(`: count the number of times the element `c` occurs in the array `a` * `a{c=},,`: count the number of times the element `c` occurs in the array `a` is one character shorter (and, if it's OK for the count to be off by one, `a[c]/,` saves one character more). However, in the special case where `c` is a number and `a` is a normal array (not a string), the square brackets around `c` may be omitted because the `-` operator coerces its arguments to the same type: * `a.c--,`: count the number of times the number `c` occurs in the array (not string!) `a` (If `a` is a string and `c` is a number between 0 and 9, `a.c--` will count the number of times the *digit* `c` occurs in `a`.) --- A similar trick can by used to find the **most common element in an array**: ``` :a{a\[.]-,}$0= ``` Again, if the input is an array of numbers, the whole `[.]` sequence may be omitted. Alas, this does *not* work for strings without the `[.]`. [Answer] # Read from STDIN GolfScript can read from stdin: ``` "#{STDIN.read}" ``` This will continue reading from STDIN until the EOF is reached. Alternatively: ``` "#{STDIN.gets}" ``` or ``` "#{STDIN.readline}" ``` Other things available: ``` getbyte getc gets([sep]) gets(limit) gets(sep, limit) inspect # perhaps useful for an underhanded contest isatty read([length]) readbyte readchar readline([sep]) readline(limit) readline(sep, limit) readlines([sep]) readlines(limit) readlines(sep, limit) readpartial(maxlen [, outbuf]) ``` For each of these, they can only be used once (and also once for each change of the parameter, also once more with empty parentheses); after that, the original value is what you'll get instead of a new value. [Answer] # Defining new built-in operators The standard GolfScript interpreter has a rarely used [feature](http://www.golfscript.com/golfscript/syntax.html) that allows interpolated Ruby code in double quoted string literals. One reason why this feature isn't more commonly used is that, awkwardly, the interpolated code is executed *at compile time*, and the output is cached by the GolfScript interpreter so that the same string literal will thereafter always yield the same value, even inside string eval. However, one thing this feature turns out to be good for is defining new GolfScript operators implemented in Ruby code. For example, here's how to define a new binary addition operator that works just like the standard built-in `+` operator: ``` "#{var'add','gpush a+b'.cc2}"; ``` It doesn't really matter where you put the definition in your code; the new operator gets defined as soon as the double-quoted string containing the Ruby code is parsed. The `add` operator defined above works *exactly* like the built-in `+` operator, and can be used in exactly the same way: ``` 1 2 add # evaluates to 3 "foo" "bar" add # evaluates to "foobar" ``` Of course, defining a new addition operator is pretty useless, unless you've done something silly like [erase the built-in `+` operator](https://codegolf.stackexchange.com/a/133379). But you can use the same trick to define new operators that do things Golfscript cannot (easily) do natively such as, say, uniformly shuffling an array: ``` "#{var'shuf','gpush a.factory(a.val.shuffle)'.cc1}"; 10,shuf # evaluates to 0,1,2,...,9 in random order ``` or printing the contents of the whole stack: ``` "#{var'debug','puts Garray.new($stack).ginspect'.cc}"; 4,) ["foo" debug # prints ["" [0 1 2] 3 "foo"], leaving the stack untouched ``` or interactive input: ``` "#{var'gets','gpush Gstring.new(STDIN.gets)'.cc}"; ]; { "> " print gets ~ ]p 1 } do # simple GolfScript REPL ``` or even web access: ``` "#{ require 'net/http' require 'uri' var'get','gpush Gstring.new(Net::HTTP.get_response(URI.parse(a.to_s)).body)'.cc1 }"; "http://example.com" get ``` Of course, a somewhat golfier (and riskier!) implementation of the latter would be e.g.: ``` "#{var'get','gpush Gstring.new(`curl -s #{a}`)'.cc1}"; ``` While not particularly golfy in itself, this lets you extend the capabilities of GolfScript beyond what the built-in commands provide. --- ### How does it work? The authoritative reference on how to define new GolfScript operators in this way is, of course, the [source code for the interpreter](http://www.golfscript.com/golfscript/golfscript.rb). That said, here's a few quick tips: * To define a new operator `name` that runs the Ruby code `code`, use: ``` var'name','code'.cc ``` * Inside the code, use `gpop` to read a value off the stack, and `gpush` to push one back in. You can also access the stack directly via the array `$stack`. For example, to push both `a` and `b` onto the stack, it's golfier to do `$stack<<a<<b` than `gpush a;gpush b`. + The positions of the `[` array start markers are stored in the `$lb` array. The `gpop` function takes care of adjusting these markers down if the stack shrinks below their position, but manipulating the `$stack` array directly does not. * The `.cc` string method that compiles Ruby code in a string into a GolfScript operator is just a convenience wrapper around `Gblock.new()`. It also has the variants `.cc1`, `.cc2` and `.cc3` that make the operator automatically pop 1, 2 or 3 arguments off the stack and assign them to the variables `a`, `b` and `c`. There's also an `.order` method that works like `.cc2`, except that it automatically sorts the arguments by [type priority](http://www.golfscript.com/golfscript/tutorial.html#coercion). * All values on the GolfScript stack are (and should be!) objects of type `Gint`, `Garray`, `Gstring` or `Gblock`. The underlying native integer or array, where needed, can be accessed via the `.val` method. + However, note that `Gstring.val` returns an array of `Gint`s! To turn a `Gstring` into a native Ruby string, call `.to_s` on it instead (or use it in a context that does that automatically, like string interpolation). Calling `.to_gs` on any GS value turns it into a `Gstring`, so any GS value can be stringified with `.to_gs.to_s`. * The `gpush` function doesn't auto-wrap native Ruby numbers, strings or arrays into the corresponding GS types, so you'll often have to do it yourself by explicitly calling e.g. `Gstring.new()`. If you push anything other than one of the GS value types onto the stack, any code that later tries to manipulate it is likely to crash. * The GS value types also have a `.factory` method that calls the type's constructor, which can be useful e.g. for rewrapping arrays/strings after manipulating their contents. All the types also have a `.coerce` method that performs [type coercion](http://www.golfscript.com/golfscript/tutorial.html#coercion): `a.coerce(b)` returns a pair containing `a` and `b` coerced to the same type. [Answer] # Tuck an integer literal into a block If you have some code that pushes a block and then an integer between 100 and 255: ``` {2,{2+base}/n}105,% ``` You can save a byte by extracting the integer as a byte from the block with `)` or `(`. ``` {2,{2+base}/ni}),% {i2,{2+base}/n}(,% ``` (This is [A005836 by tails on anarchy golf](http://golf.shinh.org/reveal.rb?A005836/tails_1360877799&gs).) The `i` has ASCII value 105. GolfScript code is not treated as UTF-8, so you can put a raw byte like 200 or 250 in the file. See [this answer](http://golf.shinh.org/reveal.rb?Reves+Puzzle/tails_1378389490&gs) by tails for another example. [Answer] ## Decoding hexadecimal input GolfScript has no hex integer literals, so, alas, you can't just parse hexadecimal input with `~`. Instead, if your code must take hex input, you'll need to parse it manually. This 8-char loop, applied to a string, will convert lowercase hex digits to their numeric equivalents: ``` {39%9-}% ``` If you have to (also) accept uppercase hex digits, the easiest (and likely shortest) solution is to first lowercase them with `32|`, for a total of 11 chars: ``` {32|39%9-}% ``` Note that the output will technically still be a string (consisting of the ASCII characters 0 – 15), but most GolfScript array functions will accept strings, too. If you absolutely need an array, you can always use `[{39%9-}/]` (where the first `[` is optional if the stack is otherwise empty). To convert the output of the code above into an integer, you can simply use `16base` (6 chars). If you want an array of bytes instead, the shortest solution I've found in simply to decode each pair of hex digits with `2/{16base}%` (11 chars). All put together, the shortest code I've found to turn a hex string into a byte array is 8 + 11 = 19 chars: ``` {39%9-}%2/{16base}% ``` Note that the output of this code *is* indeed an array, not a string. If needed, you can stringify it by concatenating it e.g. with `""+` or, if you don't mind an extra newline at the end, `n+`. ]
[Question] [ I'm hungry. Let's microwave something. Given a numerical input of between 1 and 4 digits, output the number of seconds that the microwave should run. ## Details The trick is figuring out if the user is inputting seconds or a combination of seconds and minutes. The ones and the tens places should be interpreted as seconds and the hundreds and thousands places should be minutes. For example, the value `1234` should be interpreted as 12 minutes, 34 seconds and `9876` should be 98 minutes, 76 seconds. Typing `130` and `90` should both result in a cook time of 90 seconds. Here are a few other inputs and outputs: * 1 = 1 * 11 = 11 * 111 = 71 * 1111 = 671 * 9 = 9 * 99 = 99 * 999 = 639 * 9999 = 6039 ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. Standard loopholes are not allowed. The winning entry must return the right answer when given any integer input from 1 to 9999. [Answer] # [Python 2](https://docs.python.org/2/), 19 bytes ``` lambda t:t-t/100*40 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHEqkS3RN/QwEDLxOB/Wn6RQolCZp6CoY6CIRhDCCBpCURgDCEsrbgUFAqKMvNKFNI0SjT/AwA "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` ìL ì60 ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=7Ewg7DYw&input=OTk5OQ==) `ìL` converts to base-100, and `ì60` converts back to base 60, resulting in `floor(n/100)*60 + n%100`. Also works with hours (`10000 -> 3600`, the number of seconds in an hour). [Answer] # Pyth - ~~9~~ 8 bytes Converts input to base 100, then interprets that as a base 60 number. ``` ijQ*TT60 ``` [Test Suite](http://pyth.herokuapp.com/?code=ijQ%2aTT60&test_suite=1&test_suite_input=1%0A11%0A111%0A1111%0A9%0A99%0A999%0A9999&debug=0). [Answer] # TI-Basic (83 series), 8 bytes ``` Ans-40int(sub(Ans ``` Requires OS version 1.15 or higher. [Answer] ## C, C++, Java, C#, D : 36 bytes ### D : 35 bytes ### C : 28 bytes First time i have an answer that short ! ``` int r(int i){return i/100*60+i%100;} ``` D can have a special optimization because of the golfy template system : ``` T r(T)(T i){return i/100*60+i%100;} ``` C has a special optimization with the implicit int : ``` r(i){return i/100*60+i%100;} ``` Code to test In **C** ( have to include `stdio.h` ) : ``` int main() { int testArr[] = {1,11,111,1111,9,99,999,9999}; for(int i=0;i<8; ++i) { printf("%d = %d\n",testArr[i],r(testArr[i])); } return 0; } ``` [TIO Link](https://tio.run/##RU7LDsIgELz3K0hNE7CocDE2tCZ@h/ZgoK2bKDWUnhq@HQFtnOxs9pGdWbkbpPQb0PI5q66erIJx/zh7g4EsprOz0QgOnLHtkZVQhEI4D9qi1x00JmjJUEAc2G6yF2OuLWrQwimPkchpRasYiZUT6aQfg0U4g4YJqE8ClSWschFvE7Y9zgsV9Ap10zldHaClBv8bQr6KLuXfz0xkzn8A) In **C++** ( have to include `iostream` ) : ``` int main() { std::initializer_list<int> testList{ 1,11,111,1111,9,99,999,9999 }; for (auto x : testList) { std::cout << r(x) << '\n'; } } ``` [Try it online!](https://tio.run/##PU3RCoMwDHz3K8LGsG6O2ZeBtfgF@4TBkNqNgLZSI8jEb3etMsMll8DlTnXd9aPUsqAhcCxMTCanaXAG8Maz7HzPLnjySzEvRzSqGWoNEm1PTldtGYWXtkLDEpgi8NVTLQQaJKwa/Gr3arAn6WUlkO7p4a9NGIqnPGBtnuZpHrB2vmrmIlr5bR2waiALI4jd5x@5xyo7EEjpRX4cBBwCOzYmgeOniYvNNZqXHw "C++ (gcc) – Try It Online") In **Java** : ``` public class MainApp { int r(int i){return i/100*60+i%100;} public static void main(String[]a) { MainApp m = new MainApp(); int testArr[] = new int[]{ 1,11,111,1111,9,99,999,9999 }; for (int v : testArr) { System.out.println(v + " = " + m.r(v)); } } } ``` [Try it online!](https://tio.run/##TU9LDoIwEN1ziomJSVFE2JggceEBXLkkLCpWU4RC2qHGEM6ObUX0ZX5t38y8llTTTdMyUV4fY9tdKl5AUVGl4ES5gH7kAkESG7nfS4adFMC3cRStdtGaL02RDqMHBlO3Qoom6YZfoTYzyBklF/cspz70jmjhptdwAMGe7kD8dH6025ApPEqZ5RPH3GX5r/@LOIitOY@DJEisOU9m7pB6c31rJLjfaNh/d/zrsji/FLI6bDoMWyMdK0E0rGFhlCxMrkNJtP8nd/A@cRjf "Java (OpenJDK 8) – Try It Online") In **C#** ``` class Program { int r(int i){return i/100*60+i%100;} static void Main(string[] args) { var p = new Program(); int[] testArr = new int[8] { 1,11,111,1111,9,99,999,9999 }; foreach(int a in testArr) { Console.WriteLine(a + " = " + p.r(a)); } } } ``` In **D** ( have to import `std.stdio` ) ( exactly, i have no idea how to use arrays in D ) : ``` void main() { int[] arr = [1,11,111,1111,9,9,999,9999]; for(int i = 0; i < arr.length; i++) writeln(arr[i]," = ",r(arr[i])); } ``` [TIO Link](https://tio.run/##LYvBCoMwDIbP7VMEYdDO4trLQLq9hTfxIOi2gLYj67aD@OxdlJF8JD/5MmScn5ESvNJQMRh9boBUo1UDqBca05sC4MlZezzbEg@8@DV/Ig4w9xiUhkUKDKntoCeCK7TOuK13nKm3qnfqzktxi6RYB2TVeh6X7a@axnBPD85lqaUQX8I0TkHxqcXOFCwXhv5Ray9XyD8) [Answer] ## [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 10 bytes ``` ?9A~r60*+p ``` [Try it online!](https://tio.run/##S0n@/9/e0rGuyMxAS7vg/39DQ0MA) **Explanation:** in dc when you push sth. on the stack it goes on top ``` ? # read and push the input number on the stack 9A # push 100: 9 * 10^1 + A[10] * 10^0 :D ~ # divide 2nd nr. by the top nr., push quotient, then remainder r60* # swap top 2 nr., then multiply the top by 60 +p # add top 2 nr., then print result ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) bc + sed, ~~30~~ 28 bytes *-2 bytes thanks to [@seshoumara](https://codegolf.stackexchange.com/users/59010/seshoumara).* ``` bc<<<0`sed 's/..\?$/*60+&/'` ``` [Try it online!](https://tio.run/##S0oszvj/PynZxsbGIKE4NUVBvVhfTy/GXkVfy8xAW01fPeH/f0sgAAA) Takes input from stdin. Went for a more creative approach: inserts `*60+` before the last 1 or 2 digits, and prepends a `0` to the beginning to account for inputs with only 1 or 2 digits. The result is then passed to `bc`. [Answer] # Perl 5, 15+1(-p) bytes ``` /..$/;$_-=40*$` ``` * -l switch not counted because for tests readability [Try it online](https://tio.run/##K0gtyjH9/19fT09F31olXtfWxEBLJeH/f0MuQxACY0MuSy5LEAJjy3/5BSWZ@XnF/3ULcgA) [Answer] # [C (gcc)](https://gcc.gnu.org/), 50 bytes ``` t;f(){scanf("%d",&t);printf("%d",t%100+t/100*60);} ``` [Try it online!](https://tio.run/##S9ZNT07@/7/EOk1Ds7o4OTEvTUNJNUVJR61E07qgKDOvBMovUTU0MNAu0QeSWmYGmta1/4FyCrmJmXlAfUC9QAEA "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes As a monadic link (thanks for the heads-up, caird!): ``` b³ḅ60 ``` [Try it online!](https://tio.run/##y0rNyan8/z/p0OaHO1rNDP5bAsHh9v8A "Jelly – Try It Online") ... Or as a full program: ``` bȷ2ḅ60 ``` This can be ported easily to 05AB1E, so: # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` тв60β ``` [Try it online!](https://tio.run/##MzBNTDJM/f//YtOFTWYG5zb9/28JBAA "05AB1E – Try It Online") Simply converts the input integer to base **100** and then converts the result from base **60** to integer. Hence, it is equivalent to **Input % 100 + 60 \* ⌊Input / 100⌋** [Answer] # Java 8, 13 bytes ``` n->n-n/100*40 ``` Port of [*@ovs*' amazing Python 2 formula](https://codegolf.stackexchange.com/a/147787/52210). [Try it here.](https://tio.run/##jc9NCoMwEAXgvaeYZSxoI@2mSHuDunFZukhjWmJ1FDMKpXj2NP5sS4QkMPM@eKQUg4iaVmFZvK2shDFwFRq/AYBGUt1TSAXZNM4LkGx6MUzdZnTXHUOCtIQMEM5gMbpghPuE892R23Qhbf@oHFnl0OgCatfCcuo0vm53EOFSkX8MqTpueopbF1GFDGPJknAu/J/7wQbhIydf7gcbhJdw308OqxiD0f4A) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~38~~ 33 bytes -5 bytes thanks to mazzy ``` $args|%{$_-40*($_-replace'..?$')} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9uEa1WiVe18RASwNIFaUW5CQmp6rr6dmrqGvW/q/l4jLUMQQhMDbUsdSxBCEwtgRqVVNJU1CJr/0PAA "PowerShell – Try It Online") Uses the same formula popularizes by ovs. Truncating is still expensive in PowerShell. Now uses a better regex to instead rip the last one or two characters off to division. [Answer] # JavaScript, 21 bytes ``` a=>(a/100^0)*60+a%100 ``` [Try it online!](https://tio.run/##HYxBCoMwEAC/0ksxqWuabUXNwX6kKC4aIYImJGn7/FSFGZjTLPSlMHrjYrHZSae5TdS@GN1Ryl7yWyVzuu6dnLejDkGEONlPFD9vomZvBDw4RVCgDk4V4ONZgmrqqhMrObZvZ0Z5lnEuFmu24TLw9Ac) [Answer] # [J](http://jsoftware.com/), 12 bytes ``` -40*&<.%&100 ``` It's ovs' Python 2 solution expressed in J. It consist of a hook and a fork: ``` ┌─┬───────────────────────┐ │-│┌──┬────────┬─────────┐│ │ ││40│┌─┬─┬──┐│┌─┬─┬───┐││ │ ││ ││*│&│<.│││%│&│100│││ │ ││ │└─┴─┴──┘│└─┴─┴───┘││ │ │└──┴────────┴─────────┘│ └─┴───────────────────────┘ %&100 - divides the number by 100 *&<. - finds the floor of the left argument and multiplies it to the left arg. 40 - - - subtracts the result of the above fork from the input ``` [Try it online!](https://tio.run/##y/qfVqxgq6dgoGClYPBf18RAS81GT1XN0MDgvyaXkp6CepqtlbqCjkKtlUJaMRdXanJGvkKagiGcYaiAYCKJItiWcAYSC5lp@f8/AA "J – Try It Online") [Answer] ## Batch, 23 bytes ``` @cmd/cset/a%1-%1/100*40 ``` [Answer] # bash, 20 bytes ``` echo $[$1-$1/100*40] ``` [Try it online](https://tio.run/##S0oszvifll@kkKmQmadgqGAIQmBsqGCpYAlCYGxpnZKvUJxaoqCS@T81OSNfQSVaxVBXxVDf0MBAy8Qg9n9Kfl7qfwA) [Answer] # [Haskell](https://www.haskell.org/), 18 bytes ``` f t=t-t`div`100*40 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hxLZEtyQhJbMswdDAQMvE4H9uYmaegq1CbmKBr4JGQVFmXomCnkK6pkK0oY6CIRhDCCBpCURgDCEsY/8DAA "Haskell – Try It Online") Anotha port. ## Pointfree solution, 21 bytes ``` (-)<*>(*40).(`div`40) ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 11 bytes ``` .{100} 60$* ``` [Try it online!](https://tio.run/##K0otycxL/K@qkaCnzaWi9V@v2tDAoJbLzADE/m/IZQhCYGzIZcllCUJgbAkA "Retina – Try It Online") Input and output [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). The test suite converts from and to decimal for convenience. Doing this kind of base conversion for only up to two digits is surprisingly simple to do in unary. We just match runs of 100 `1`s and replace them with 60 `1`s. Anything that's left over would correspond to the last two digits in the decimal representation and remains unchanged. [Answer] ## [Alice](https://github.com/m-ender/alice), 19 bytes ``` /o \i@/.'d%~'d:'<*+ ``` [Try it online!](https://tio.run/##S8zJTE79/18/nysm00FfTz1FtU49xUrdRkv7/39DIAAA "Alice – Try It Online") ### Explanation Too bad I removed *divmod* from the language, I guess... ``` /o \i@/... ``` This is just the usual framework for linear programs with decimal I/O operating purely in Cardinal (arithmetic) mode. ``` . Duplicate input. 'd% Mod 100. ~ Swap with other copy. 'd: Divide by 100. '<* Multiply by 60. + Add. ``` [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 19 bytes ``` ?:_100%}#00/_60*{+! ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3ire0MBAtVbZwEA/3sxAq1pb8f9/Q0NDAA "Labyrinth – Try It Online") ### Explanation ``` ? Read input. : Duplicate. _100% Mod 100. } Move off to auxiliary stack. #00/ Divide by 100, using the stack depth to get a 1, instead of _1. _60* Multiply by 60. {+ Retrieve the earlier result and add it. ! Print. ``` The IP then hits a dead end and starts moving backward. When it reaches the `/` it attempts a division by zero which terminates the program. [Answer] # Excel VBA, 29 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window. ``` ?[A1]Mod 1E2+60*[Int(A1/100)] ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~11~~ 10 bytes ``` 60⊥0 100⊤⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wQzg0ddSw0UDA2A9JJHXYv@/3/Uu0pBA8jSSdM8tOJR72ZjAwMudVt1LqiYgiUQAAA) **How?** `0 100⊤` - encode in base 100, stopping at the second LSB, effectively producing `n ÷ 100, n % 100`. `60⊥` - decode in base 60 [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 16 bytes Straightforward: ``` n->n\100*60+n%100 ``` Unfortunately this nice method is simply too long to use: ``` n->[60,1]*divrem(n,100) ``` [Answer] # [R](https://www.r-project.org/), 21 bytes ``` x=scan();x-x%/%100*40 ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTukK3QlVf1dDAQMvE4L8hlyEIgbEhlyWXJQiBseV/AA "R – Try It Online") [Answer] # Common Lisp, 34 bytes ``` (lambda(n)(- n(*(floor n 100)40))) ``` [Try it online!](https://tio.run/##S87JLC74r1FQlJlXoqDxXyMnMTcpJVEjT1NDVyFPQ0sjLSc/v0ghT8HQwEDTxEBTU/O/oaEhkAQA) Another port of [@ovs' formula](https://codegolf.stackexchange.com/a/147787/52210). [Answer] # [Pushy](https://github.com/FTcode/Pushy), ~~10~~ 9 bytes Kevin outgolfed me in my own language... (using the approach from [ovs](https://codegolf.stackexchange.com/a/147787/60919)' answer) ``` 2dH/40*-# ``` **[Try it online!](https://tio.run/##Kygtzqj8/98oxUPfxEBLV/n///@WQAAA "Pushy – Try It Online")** # 10 bytes ``` sjvj60*^+# ``` **[Try it online!](https://tio.run/##Kygtzqj8/784qyzLzEArTlv5////lkAAAA "Pushy – Try It Online")** ``` s \ Split input into digits jvj \ Join the first two and the last two 60* \ Multiply the first by 60 ^+ \ Add the values # \ Print ``` # 11 bytes For one byte more we can use the `Input % 100 + 60 * ⌊Input / 100⌋` approach: ``` H2d%}/60*+# ``` **[Try it online!](https://tio.run/##Kygtzqj8/9/DKEW1Vt/MQEs7/v///5ZAAAA "Pushy – Try It Online")** [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` B60B100 ``` [Try it online!](https://tio.run/##yygtzv6fm18erPOoqfG/k5mBk6GBwf///6MNjYxNdCwtzM10DHUMQQiMDXUsdSxBCIwtYwE "Husk – Try It Online") Not very exciting, just converts to base 100 and back from base 60. [Answer] # [Symbolic Python](https://github.com/FTcode/Symbolic-Python), ~~66~~ ~~48~~ 46 bytes Thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for -16 bytes! ``` __=-~-~_-_ _-=_/(__<<__^__)**__*(__-~__<<-~__) ``` [Try it online!](https://tio.run/##K67MTcrPyUzWLagsycjP@/8/Pt5Wt063Ll43nite1zZeXyM@3sYmPj4uPl5TSys@XgvIB8oCxUCk5v///y0tLQE "Symbolic Python – Try It Online") --- ## Explanation ``` # input is initially in _ __=-~-~_-_ # set __ to (2+input-input) = 2 _-= # subtract from _: _/ # _ divided by: (__<<__^__)**__ # (2<<2 ^ 2) ** 2 = (8^2)**2 = 100 * # multiplied by (__-~__<<-~__) # (2 - ~2 << -~2) = 5 << 3 = 40 # value in _ is the implicit output ``` [Answer] # [GAP](https://www.gap-system.org/), 45 bytes [Try it online!](https://tio.run/##JYwxDoMwEAR7XrGiwsiRbCkNWHkAHdRAEQUcubmLrPP7nROsdqac7/tXaxxfsdBHElMnBvmUkgnyWApPJJ1Y75zpny6cdIQaOUOQCKu38Be31IP@4taw4@AGujknLUXNW7QbtSY0rK0/) ``` f:=function(t) return t-QuoInt(t,100)*40;end; ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles) ``` `@60`@@ ``` ``` `@ # convert input in command-line arg to base @ # 100 (default value for @ when no input from STDIN) `@ # and convert from base 60 # 60 ``` [![enter image description here](https://i.stack.imgur.com/3ZLqv.png)](https://i.stack.imgur.com/3ZLqv.png) ]
[Question] [ I started one code golf challenge recently and it seems like the winner is GolfScript (surprise, surprise!). What's interesting is that there was another very strong competitor that had all chances to win over GolfScript. Its name is APL. I see a lot of answers written in APL here. It seems like this language is fairly efficient for code golfing, so I decide to ask for any code golfing tips you know for APL programs. Feel free to post some code examples. It is usually very interesting to see language in action. [Answer] **Edit**: for people reading this who don't know APL at all but want to take it up, [Mastering Dyalog APL](http://www.dyalog.com/uploads/documents/MasteringDyalogAPL.pdf) is a *very* good resource. 1. Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it. `2+a, 1+a←1` -> `3 4` `a` is set to `1`, `1+a` evaluates to `2`, `a,2` evaluates to `1 2` and `2+1 2` evaluates to `3 4`. 2. Like C, `←` can be combined with a function, i.e. `a +← 3`. Unlike C, this is generic: `foo F← bar` sets `foo` to `F bar`. Somewhat unintuitively, as an expression this returns `bar`, not `F bar`. It works with anonymous functions too: ``` a←0 a+←3 ⋄ a 3 a+←3 ⋄ a 6 a { ⍵/'!' } ←4 ⋄ a !!!! ``` 3. You can assign to an array: `A[3]←8`, like you'd expect. But you can also assign multiple items at the same time: `A[3 5 6]←9 1 4`, or even `A[3 5 6]←9`, setting them all to the same item. You can, of course, add a function to the `←` here too. The function will then be applied to each element separately, as if you did `F¨`. 4. `⍨` is your friend, even if he doesn't look too happy about it. 1. If `F` is dyadic, dyadic `⍨` switches the arguments: `a F b` <-> `b F⍨ a`. This comes in handy when golfing because it can save you from using braces: ``` (F G H x) K y <-> y K⍨ F G H x ``` This does change the evaluation order, as the right hand is always evaluated before the left hand. 2. If `F` is dyadic, *monadic* `⍨` applies the same argument to both sides of the function: ``` 5⍴5 5 5 5 5 5 ⍴⍨5 5 5 5 5 5 ``` The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use `∘.=⍨` instead of having to do `x∘.=x←(whatever)`. 3. If `F` is monadic, `⍨` does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex: ``` {⍵+3}⍣5 6 ∇{⍵+3} ∇ ⍣ 5 6 ({⍵+3}⍣5)6 21 {⍵+3}⍣5⍨6 21 ``` 5. [Learn the idioms!](https://aplwiki.com/wiki/FinnAPL_idiom_library) Then golf the idioms. For example: ``` ((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X ``` can be mechanically transformed into: ``` X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y ``` and then further into: ``` X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y ``` `⊃` (first) being equivalent to `1↑` (take one) in this case. And possibly: ``` X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y ``` `≢` (tally) being equivalent to `⊃⍴` (the first element of the shape) for all but scalars. [Answer] # [Trains](https://www.youtube.com/watch?v=7-93GzDqC08) ``` A(f g h)B ←→ (A f B)g A h B ⍝ fork (f g h)B ←→ ( f B)g h B ⍝ fork A( g h)B ←→ g A h B ⍝ atop ( g h)B ←→ g h B ⍝ atop (A g h) ←→ ({A} g h) ⍝ "Agh" fork (f g h k) ←→ (f (g h k)) ⍝ 4-train (f g h k l) ←→ (f g (h k l)) ⍝ 5-train, etc (f g h k l m) ←→ (f(g h(k l m))) ⍝ groups of 3 from the right, last could be 2 f∘g B ←→ f g B ⍝ "compose" operator, useful in trains A f∘g B ←→ A f g B ``` [Answer] # Use `⊥` to combine multiplication with addition ``` (a×b)+C -> a⊥b,C (C)+a×b -> a⊥b,C (a×b)-C -> a⊥b,-C ``` Assumptions: * `a` and `b` are terms that don't require further parentheses when used as a left argument * `C` is an expression that may need parentheses when used as a left argument * `a` `b` `C` evaluate to numeric scalars [Answer] ## Tricks for dealing with `/` and `⌿` in trains When [using trains](https://codegolf.stackexchange.com/a/43084/43319) you may want to use reductions `f/` like sum `+/` or even replicate reduction `//` . However, if your train has more parts to the left of the reduction you need parentheses to create an atop. Here are some tricks to save bytes. ### Use `1∊` instead of monadic `∨/` or `∨⌿` on Boolean arrays Task: Given two equal-length strings A and B, return 2 if any corresponding characters of A and B are equal, 0 otherwise. E.g. `A←'abc'` and `B←'def'` gives `0` and `A←'abc'` and `B←'dec'` gives `2`. A dfn solution may be `A{2×∨/⍺=⍵}B` but you want to shorten it by going tacit. `A(2×∨/=)B` is not going to work because the rules of train formation parse this as `2 (× ∨/ =)` but you want `2 × (∨/=)` . Observe that `∨/` or `∨⌿` on a Boolean vector (`∨/,` or `∨⌿,` for higher rank arrays) asks whether there is any 1 present, i.e. `1∊` , so we can write our train as `2×1∊=` . Note that `∊` ravels its right argument, so you cannot use it to reduce each row or column separately. ### Use `1⊥` instead of monadic `+/` or `+⌿` Task: Given a list of lists L and an index N, return thrice the sum of the Nth list. E.g. `L←(3 1 4)(2 7)` and `N←1` gives `24`. A dfn solution may be `N{3×+/⍺⊃⍵}L` but you want to shorten it by going tacit. `N(3×+/⊃)L` is not going to work because the rules of train formation parse this as `3(× +/ ⊃)` but you want `3 × (+/⊃)` . Observe that evaluating a list of numbers in unary (base-1) is equivalent to summing the list because ∑{*a*, *b*, *c*, *d*} = *a* + *b* + *c* + *d* = (*a* × 1³) + (*b* × 1²) + (*c* × 1¹) + (*d* × 1⁰). Therefore `+/a b c d` is the same as `1⊥a b c d` , and we can write our train as `3×1⊥⊃` . Note that on higher-rank arguments, `1⊥` is equivalent to `+⌿`. ### Use `f.g` instead of `f/g` with scalar and/or vector arguments Task: Given a list L and a number N, return the range 1 thorough the number of minimum division remainder when the elements of L are divided by N. E.g. `L←31 41 59` and `N←7` gives `1 2 3`. A dfn solution may be `N{⍳⌊/⍺|⍵}L` but you want to shorten it by going tacit. `N(⍳⌊/|)L` is not going to work because the rules of train formation parse this as `⍳ (⌊/) |` but you want `⍳ (⌊/|)` . The inner product `A f.g B` of scalar two functions when the arguments are scalars and/or vectors is the same as `f/ A g B` because both are `(A[1] g B[1]) f (A[2] g B[2]) f (A[3] g B[3])` etc., so we can write our train as `⍳⌊.|` . Note that this does not work for higher-rank arrays. ### Use `∊⊆` instead of `/` with Boolean left and simple vector right arguments Task: Given a list L and a number N, filter the list so that only numbers greater than N remain. E.g. `L←3 1 4` and `N←1` gives `3 4`. A dfn solution may be `N{(⍺<⍵)/⍵}L` but you want to shorten it by going tacit. `N(</⊢)L` is not going to work because the binding rules will parse this as `(</) ⊢` but you want `/` to be the function *replicate* rather than the operator *reduce*. Dyadic `⊆` with a Boolean left argument partitions the right argument according to runs of 1s in the left argument, dropping elements indicated by 0s. This is almost what we want, save for the unwanted partitioning. However, we can get rid of the partitioning by applying monadic `∊`. Thus `{(⍺<⍵)/⍵}` can become `{∊(⍺<⍵)⊆⍵}` and thus we can write our train as `∊<⊆⊢` . Note that this does not work for higher-rank arrays. ### Use `∊⍴¨` instead of `/` with non-Boolean left and simple vector right arguments Task: Given a list L, replicate Nth item N times. E.g. `L←3 1 4` gives `3 1 1 4 4 4`. A dfn solution may be `{(⍳⍵)/⍵}L` but you want to shorten it by going tacit. `(⍳/⊢)L` is not going to work because the binding rules will parse this as `(⍳/) ⊢` but you want `/` to be the function *replicate* rather than the operator *reduce*. Dyadic `⍴` combined with `¨` copies each element of the right argument according to the matching element in the left argument. This is almost what we want (e.g. `1 2 3⍴¨3 1 4 → (3)(1 1)(4 4 4)`). Then, we can get rid of the nesting by applying monadic `∊`. Thus `{(⍳⍵)/⍵}` can become `{∊(⍳⍵)⍴¨⍵}` and thus we can write our train as `∊⍳⍴¨⊢`. Note that this does not work for higher-rank arrays. ### Use `0⊥` instead of `⊢/` or `⊢⌿` with numeric arguments Task: Given a list L and a number N, multiply the N with the rightmost element of L. E.g. `L←3 1 4` and `N←2` gives `8`. A dfn solution may be `N{⍺×⊢/⍵}L` but you want to shorten it by going tacit. `N(⊣×⊢/⊢)L` is not going to work because the rules of train formation parse this as `⊣ (× ⊢/ ⊢)` but you want `⊣ × (⊢/⊢)` . Observe that `0⊥` on a numeric array is the same as `⊢⌿` , so we can write our train as `⊣×0⊥⊢` . Note that this selects the last major cell of higher-rank arrays. [Answer] # Complex numbers Often overlooked, they present wonderful opportunities to shorten expressions dealing with grids, mazes, fractals, or geometry. ``` 0j1⊥¨ 0j1⊥ ⍝ pair(s) of reals -> complex 11 9∘○¨ 11 9○ ⍝ complex -> pair(s) of reals |z0-z1 ⍝ distance between two points 0j1×z 0j¯1×z ⍝ rotate by ±90° around (0,0) 0j1*⍳4 ⍝ the four cardinal directions +z -+z ⍝ reflect across x or y axis +\0,z ⍝ sequence of steps -> path ¯2-/z ⍝ path -> sequence of steps 0j1⊥¨n-⍳2⍴1+2×n ⍝ lattice centred on (0,0) ``` [Answer] # Indexing modulo vector length `⊃i⌽a` is often shorter than the naive `⊃a[(≢a)|i]` or `a⊃⍨i|⍨≢a` (where `a` is a vector and `i` is an integer, and `⎕io` is 0) a useful variation on this (thanks EriktheOutgolfer for pointing out) is: `I↑Y⌽⍨I×X` where `Y` is the concatenation of some length-`I` vectors and `X` is the index of the one we want to pick, for instance: `3↑'JanFeb...Dec'⌽⍨3×month` [Answer] # Generate [A001057](http://oeis.org/A001057), [A130472](https://oeis.org/A130472), and many variations A001057 is a simple sequence of alternating integers, starting with `0, 1, -1, 2, -2, 3, -3, ...`. A130472 is its negation, `0, -1, 1, -2, 2, -3, 3, ...`. APL has a surprisingly short way to generate `n`th term or first `n` terms: ### nth term of A001057 (0-indexed) ``` ⎕IO←1 -/⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLl09R/1bv6fBmQ/6u2DCHc1H1pv/KhtIpAXHOQMJEM8PIP/px1aoWCgYKhgpGCsYKJgqmCmYA4A "APL (Dyalog Unicode) – Try It Online") ### nth term of A130472 (1-indexed) ``` ⎕IO←0 -/⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLh09R/1bv6fBmQ/6u2DCHc1H1pv/KhtIpAXHOQMJEM8PIP/px1aoWCoYKRgrGCiYKpgpmAOAA "APL (Dyalog Unicode) – Try It Online") ### first n terms of A001057, leading 0 removed (`1, -1, 2, -2, ...`) ``` ⎕IO←1 -\⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLl0Yx71bv6fBmQ/6u2DCHc1H1pv/KhtIpAXHOQMJEM8PIP/pymYAwA "APL (Dyalog Unicode) – Try It Online") ### first n terms of A130472 (`0, -1, 1, -2, 2, ...`) ``` ⎕IO←0 -\⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDLh0Yx71bv6fBmQ/6u2DCHc1H1pv/KhtIpAXHOQMJEM8PIP/pymYAwA "APL (Dyalog Unicode) – Try It Online") Applying various primitive functions to these sequences can give many interesting results which are shorter than other alternatives: * `1, 1, 2, 2, 3, 3, ...`: With `⎕IO←1`, `|-\⍳n` is shorter than `n↑2/⍳n` in explicit form * `0, 1, 1, 2, 2, 3, ...`: With `⎕IO←0`, `|-\⍳n` is shorter than `⌈2÷⍨⍳n` in explicit form * `0, 1, 0, 2, 0, 3, ...`: With any `⎕IO`, `|0⌊-\⍳n` or `-0⌊-\⍳n` is shorter than any known alternatives, both tacit and explicit * `0, -1, 0, -2, 0, -3, ...`: With any `⎕IO`, `0⌊-\⍳n` * `1, 0, 2, 0, 3, 0, 4, ...`: With `⎕IO←1`, `0⌈-\⍳n` * `0, 1, 1, 0` repeated: With `⎕IO←0`, `2|-\⍳n` * `1, 1, 0, 0` repeated: With `⎕IO←1`, `2|-\⍳n` * Reverse odd then forward even, e.g. `7 → 5 3 1 0 2 4 6`: `⍋-\⍳n` with `⎕IO←0`. `⎕IO←1` gives `7 → 6 4 2 1 3 5 7`. * Permutation of 0 to `n-1`, alternating front and end, e.g. `7 → 0 6 1 5 2 4 3`: `n|-\⍳n` with `⎕IO←0`. * First n terms of [A002620](http://oeis.org/A002620), `0, 1, 2, 4, 6, 9, 12, 16, 20, ...`: `-\-\⍳n` with `⎕IO←0` (`⎕IO←1` gives same sequence with leading zero removed), which is shorter than `⌊×⍨2÷⍨⍳n` with `⎕IO←1`. [Answer] # Use `⍨` ### Avoid parentheses `⍨` (Commute) can save you bytes by avoiding parentheses. Whenever you have a function where the left argument needs to be parenthesised and the right argument does not, you can save a byte, e.g. `(A<B)÷C` → `C÷⍨A<B`. ### Double arrays To append a copy of an array to its end, use `,⍨A` or `⍪⍨A`. ### Double numbers Instead of using `2∘×` to double, you can use `+⍨` since it adds the argument to itself: `1+2∘×` → `1++⍨`. ### Square numbers Instead of using `2*⍨Y` to square, you can use `×⍨Y` since it multiplies the argument with itself: `2*⍨A+B` → `×⍨A+B`. ### Random permutation `?⍨N` will give you a random permutation of length `N`. ### Self-classify Find the indices of the first occurrence of each major cell with `⍳⍨A` ### Count trailing 1s in a Boolean vector Instead of `+/∧\⌽B` to count how many trailing 1s there are in `N` you can use `⊥⍨`. ### Reverse composition `A f∘g B` is `A f g B`, but if you want `(g A) f B`, use `f⍨∘g⍨`. ### Reverse reduce `f/ a1 a2 a3` is `a1 f (a2 f a3)`. If you want `(a1 f a2) f a3`, use `f⍨/⌽`. ### Reverse scan `f\ A B C` is  `A (A f B) (A f (B f C))`. `f⍨/∘⌽¨,\ A B C` is  `A (A f B) ((A f B) f C)`. `f⍨\⌽ A B C` is  `((A f B) f C) (B f C) C`. `⌽f/∘⌽¨,\⌽ A B C`. is  `(A f (B f C)) (B f C) C`. [Answer] # Generate all nonempty subsequences I recently discovered the expression `(⊢,,¨)\` in [this answer](https://codegolf.stackexchange.com/a/211363/78410). If applied to a simple numeric or char vector, it does the following: * `(⊢,,¨)/ v` gives all subsequences of `v` which include the last item. ``` (⊢,,¨)/ '1234' → '1' (⊢,,¨) '2' (⊢,,¨) '3' (⊢,,¨) '4' → '1' (⊢,,¨) '2' (⊢,,¨) '4' '34' → '1' (⊢,,¨) '4' '34' '24' '234' → '4' '34' '24' '234' '14' '134' '124' '1234' ``` * `(⊢,,¨)\ v` applies `(⊢,,¨)/` to each prefix of `v`, giving all non-empty subsequences as a list of lists of vectors. ``` (⊢,,¨)\ '1234' → '1' ('2' '12') ('3' '23' '13' '123') ('4' '34' '24' '234' '14' '134' '124' '1234') ``` The result can be flattened once using `⊃,/`, which gives the list of nonempty subsequences. The order is the one imposed by the binary digits of `0..2^n-1`, grouped by the last item. You can use it whenever it suffices to generate all subsequences *in any order*. An interesting feature is that the original vector comes last, so you can also test e.g. "the original satisfies something but any smaller subsequence doesn't" using `</`. Note that the order is different from plain binary/lexicographic/shortlex order, so it is hard to use when the challenge requires specific ordering of subsequences. A nice application of this trick is "extract all subsequences of digits of a number": `⍎⍕(⊢,,¨)\⍕n`. Figuring out how it works is left as an exercise to the reader. :) --- `(⊢,,¨)/` can be used to generate all subsequences (including empty), with the same order as binary order: ``` ¯1↓¨¨(⊢,,¨)/'1234',0 → '' '4' '3' '34' '2' '24' '23' '234' '1' '14' '13' '134' '12' '124' '123' '1234' ``` It's longer than the scan version, but it fits in a train better and might be useful when the order is important. [Answer] # Enumerate the characters in a string without `⍳≢` Task: Given two strings, S and T, list the indices of their concatenation. E.g. `S←'abcd'` and `T←'xyz'` gives `1 2 3 4 5 6 7`. A dfn solution may be `S{⍳≢⍺,⍵}T` but you want to shorten it by going tacit. `⍳≢,` is not going to work because the train parsing rules will parse this as `(⍳)≢(,)` but you want `(⍳≢),`. Dyadic `⍋` with an empty left argument grades simple character arrays according to their current order, which is the same as `⍳≢`. Thus `{⍳≢⍺,⍵}` can become `{⍬⍋⍺,⍵}` , so we can write our train as `⍬⍋,` . Note that this does not work for numeric or mixed arrays. [Answer] # Constructing a long complex string (char vector) [Original idea from @ngn.](https://chat.stackexchange.com/transcript/message/53165231#53165231) We can (ab)use rotation `n⌽` and enlist `∊` to shorten multiple concatenations: ``` '(',(⍺∇r),'|',(⍺∇s),')' → Rotate the last ')' to front and apply 1⌽ 1⌽')(',(⍺∇r),'|',(⍺∇s) (-1 byte) → We don't need parens at the end 1⌽')(',(⍺∇r),'|',⍺∇s (-3 bytes in total) → Remove some concats(,) to use stranding instead and enlist(∊) later 1⌽∊')('(⍺∇r)'|',⍺∇s (-4 bytes in total) ``` Note that we can't remove the last concat (`,`) in this case; otherwise the recursive call would be screwed up. The `∊` trick can also be used to shorten construction of numeric arrays: ``` 0,(⍳5),0 → ∊0(⍳5)0 (-1 byte) ``` [Answer] # Constant functions `=⍨` and `≠⍨` thanks to ngn. Sometimes you just need a single value for each element of a list. While you might be tempted to use `{value}¨` (it is shorter to use `value⊣¨` or `value⍨¨`), you can get even shorter (using `⎕IO←0`) for some common values: `¯1`s with `⍬⍸list` `0`s with `⍬⍳list` `1`s with `⍬⍷list` Note that these only work on lists (though they may be nested). For higher-rank simple arrays, you can use the following to get all 0s and all 1s: `1`s with `=⍨`  `0`s with `≠⍨` If you set `⎕ML←0`, all numbers can be made into zeros (as if `0×`) with: `∊` If you only need a single number, you may be able to use monadic `≡` to get 1 or 0 instead of using `1⊣` or `0⊣`. Note that Dyalog APL 18.0 added a constant operator which derives an ambivalent function that always returns the constant. [Answer] # `⎕FMT`, the formatting function [Dyalog documentation page](https://help.dyalog.com/latest/#Language/System%20Functions/Format%20Dyadic.htm) In [user's answer to ascii art reflection,](https://codegolf.stackexchange.com/a/216797/80214), they used an interesting builtin called `⎕FMT` to split text on a carriage return `\r`. I feel it has potential to save a lot of bytes in [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") and [string](/questions/tagged/string "show questions tagged 'string'") challenges. It works very well with specific output/input specifications. ## Converting carriage return separated input directly to a matrix A string with carriage returns can be converted directly to the matrix using monadic `⎕FMT`: ``` ⎕FMT'Hello'(⎕UCS 13)'There' Hello There ⍴⎕FMT'Hello'(⎕UCS 13)'There' 2 7 ``` It automatically pads the matrix with spaces, just like `↑`(mix). --- `⎕FMT` can take arrays as arguments, and can apply a format specification to each of it's elements. However, the rank of the array must not exceed 2, and the format specifier must be a proper match for the elements. There are multiple format specifiers allowed, which give different results: ``` rAw Alphanumeric format rEw.s Scaled format rqFw.d Decimal format rqG⍞pattern⍞ Pattern rqIw Integer format Tn Absolute tabulation Xn Relative tabulation ⍞t⍞ Text insertion ``` Where: ``` r is an optional repetition factor indicating that the format phrase is to be applied to r columns of Y q is an optional usage of qualifiers or affixtures from those described below. w is an integer value specifying the total field width per column of Y, including any affixtures. s is an integer value specifying the number of significant digits in Scaled format; s must be less than w-1 d is an integer value specifying the number of places of decimal in Decimal format; d must be less than w. n is an integer value specifying a tab position relative to the notional left margin (for T-format) or relative to the last formatted position (for X-format) at which to begin the next format. t is any arbitrary text excluding the surrounding character pair. Double quotes imply a single quote in the result. ``` This allows a lot of useful tricks like format strings, ASCII tabulation, representation of arbitrary precision floating point values, and allow you to apply them cyclically to the contents of any matrix you choose. `⎕R` might be simpler to use in the case of a single line character vector, however. These letters and their modifiers are discussed in more depth in the [Documentation](https://help.dyalog.com/latest/#Language/System%20Functions/Format%20Dyadic.htm). [Answer] # Base Conversions The function `b⊥v`, where `b` is a numeric base and `v` is a vector of digit values in that base, converts the vector `v` into its decimal (base-10) equivalent. If you want to convert a base-10 number into base `b`, a naïve approach would be to try to use `⊤`, but this requires figuring out (or calculating) how many digits the number would require in base `b`. Instead, use the Power operator `⍣` with a right operand of `¯1`: `(b∘⊥⍣¯1)`. This will invert the convert-to-decimal function to convert back to base `b` with exactly the minimum necessary number of digits in the base-b representation. ``` 2⊥1 1 0 1 ⍝ Convert the base-2 digit vector 1 1 0 1 to base-10 13 (2∘⊥⍣¯1)13 ⍝ Convert 13 to its base-2 digit vector 1 1 0 1 ``` [Answer] # Miscellaneous ideas [Cross-post of my own J tip](https://codegolf.stackexchange.com/a/205356/78410), because APL and J are so closely related that the two can share many ideas. ## If you're facing `-⍨/`, try `¯1⊥` instead A common reason to use `-⍨/` is to reverse-subtract over a length-2 axis, e.g. given a 2-element array `x y`, compute `y-x`. If this is the case, `¯1⊥` is an equivalent expression; just like `2⊥x y` computes `2x+y`, `¯1⊥x y` computes `-x+y`. While the two expressions have same length, `¯1⊥` is more likely to fit well in trains (due to being a dyadic primitive function with a left arg, vs `-⍨/` being a monadic derived function). Note that, if you apply it to longer axis, `¯1⊥` gives you more similar result to `-/` (alternating sum), with negated result when the length is even. ## Construct a boolean square matrix where the border is ones/zeros and the interior is the opposite This is mainly for large fixed-size matrices, say 6 by 6. The matrix ``` 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 1 1 1 1 1 ``` can be generated by `∘.∨⍨` -ing the boolean vector `1 0 0 0 0 1`. The shortest known way to generate that vector is `6⍴5↑1`, so we can get the matrix above in just **9 bytes**: ``` ∘.∨⍨6⍴5↑1 ``` We can also get negation of it at no extra cost, by swapping `∨` with `⍱`! (Remember that APL has NOR `⍱` and NAND `⍲`; they are rarely needed, but definitely are a byte saver when we do need them.) [Answer] # Repeat with intermediate results This is originally @ngn's suggestion on [an APL answer of mine](https://codegolf.stackexchange.com/a/207123/78410). While APL has the power operator `⍣` which can repeat a function certain number of times, it cannot collect intermediate results on its own (unlike J's `^:` allowing `<n` or `i.n` right operand to do the job). Usually one would collect the intermediate results by using an auxiliary variable with modified assignment, or "hack" the left operand of `⍣` to something like `(⊣/,f¨)⍣n⊂x`, or naively write down the iterations like `{⍵(f⍵)(f f⍵)}x`. But there is a clever way using scan `⊢∘f\`. Since `x ⊢∘f y` ignores `x` and applies `f` to `y` monadically, such a scan over `n` copies of `x` (enclosed if `x` is non-scalar) gives the results of `f` applied to `x` `0..n-1` times: ``` ⊢∘f\n⍴⊂x → ⊢∘f\x x x ... x → (x)(x ⊢∘f x)(x ⊢∘f x ⊢∘f x) ... → x(f x)(f f x)(f⍣3⊢x) ... (f⍣(n-1)⊢x) ``` This is shorter than several alternatives (assume `x` is a complex expression): ``` {⍵(f⍵)(f f⍵)}x ⍝ way too long for 2nd or higher iterations (⊣/,f¨)⍣n⊂x ⍝ shorter, but still long ⊢∘f\n⍴⊂x ⍝ shortest ``` Interestingly, the scan expression ties when compared to various expressions that collect only zeroth and first iterations: ``` {⍵(f⍵)}x ⍝ dfn (⊂,⊂∘f)x ⍝ tacit y(f y←x) ⍝ intermediate assignment; this wins if f is a single primitive ⊢∘f\2⍴⊂x ⍝ scan ``` Also note that `⊢∘f\n⍴⊂` without the right arg is also a valid train. --- As of Dyalog 18.0, you can write `f⍤⊢\` in place of `⊢∘f\`, which may or may not save bytes depending on the structure of `f`. (The conversion never *adds* bytes, so `f⍤⊢\` can be universally used.) [Answer] When you need to encode some arbitrary data (as is common in the Kolmogorov complexity questions), it can be achieved with a string of characters from the [atomic vector](https://aplwiki.com/wiki/Atomic_vector) `⎕AV`. For example, to encode the array `256 13 16 127 128 168 192` in Dyalog APL: ``` ⎕AV[256 13 16 127 128 168 192] ⍝ the result is: ⍣%⍵⊣⌷∧⊤ ``` Then to decode it: ``` ⎕AV⍳'⍣%⍵⊣⌷∧⊤' ``` Adám's [SBCS](https://github.com/abrudz/SBCS) (single byte character set) also allows to encode some other characters (`⊆⍠⍤⌸⌺⍸`) as a single byte. [Answer] # Encode into base b without digit limit `b⊥⍣¯1` Explanation: ``` ⍣¯1 Do the inverse of... b⊥ Decoding from base b (which is encoding to base b with no digit limit!!!) ``` ]
[Question] [ Almost equivalent to Project Euler's first question: > > If we list all the natural numbers below 10 that are multiples of 3 or > 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. > > > Find the sum of all the multiples of 3 or 5 below 1000. > > > ## Challenge: Given a positive integer `N` and a set of at least one positive integer `A`, output the sum of all positive integers less than `N` that are multiples of at least one member of `A`. For example, for the Project Euler case, the input would be: ``` 1000 3 5 ``` ## Test cases: ``` Input : 50, [2] Output: 600 Input : 10, [3, 5] Output: 23 Input : 28, [4, 2] Output: 182 Input : 19, [7, 5] Output: 51 Input : 50, [2, 3, 5] Output: 857 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ḍþṖḅTS ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR@/hfQ93Tnu4ozUk@P///9FGOgrGOgqmsf9NDQA "Jelly – TIO Nexus") ### How it works ``` ḍþṖḅTS Main link. Left argument: D (array). Right argument: n (integer) ḍþ Divisible table; test each k in [1, ..., n] for divisibility by all integers d in D. Ṗ Pop; discard the last Boolean array, which corresponds to n. ḅ Unbase; convert the Boolean arrays of base n to integer. This yields a non-zero value (truthy) and and only if the corresponding integer k is divisible by at least one d in D. T Truth; yield the array of all indices of truthy elements. S Compute their sum. ``` [Answer] # Octave, ~~38~~ ~~36~~ 33 bytes ``` @(x,y)(1:--x)*~all(mod(1:x,y),1)' ``` Take input as: `f(10, [3;5])`. This would be 2 bytes shorter if the input could be `f(9,[3;5])` for the same test case. [Verify all test cases here.](http://ideone.com/ZPiYFo) --- **Explanation:** ``` @(x,y) % Anonymous function that takes two inputs, x and y % x is a scalar and y is a vertical vector with the set of numbers (1:--x)* % Pre-decrement x and create a vector 1 2 ... x-1 ``` Octave can pre-decrement, so using `1:--x` instead of `1:x-1` (two times) saves two bytes. `mod(a,b)` gives `1 2 0 1 2 0 1 2 0` for `mod(1:9,3)`. If the second argument is a vertical vector, it will replicate the first input vertically and take the modulus for each of the values in the second input argument. So, for input `mod(1:9, [3;5])` this gives: ``` 1 2 0 1 2 0 1 2 0 1 2 3 4 0 1 2 3 4 ``` Taking `~all(_,1)` on this gives `true` for the columns where at least one value is zero, and `false` where all values are non-zero: ``` ~all(mod(1:x,y),1) 0 0 1 0 1 1 0 0 1 ``` The `,1` is needed in case there is only one number in `y`. Otherwise it would act on the entire vector instead of number-by-number. Transposing this to a vertical matrix and use matrix multiplication, will give us the correct answer, without the need for explicit summing: [Answer] # Python, ~~59~~ 55 bytes ``` lambda n,l:sum(v*any(v%m<1for m in l)for v in range(n)) ``` **[repl.it](https://repl.it/EtIl/2)** Unnamed function taking an integer, `n` and a list of integers `l`. Traverses a range of the Natural numbers (plus zero) up to but not including `n` and sums (`sum(...)`) those that have a remainder after division of zero (`v%m<1`) for `any` of the integers `m` in the list `l`. Uses multiplication rather than a conditional to save 3 bytes. [Answer] ## JavaScript (ES6), ~~40~~ ~~39~~ 36 bytes Input: integer `n` and array of integer(s) `a` with currying syntax `(n)(a)` ``` n=>F=a=>n--&&!a.every(v=>n%v)*n+F(a) ``` ### Test cases ``` let f = n=>F=a=>n--&&!a.every(v=>n%v)*n+F(a) console.log(f(50)([2])); // 600 console.log(f(10)([3, 5])); // 23 console.log(f(28)([4, 2])); // 182 console.log(f(19)([7, 5])); // 51 console.log(f(50)([2, 3, 5])); // 857 ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 9 bytes ``` q:ti\~*us ``` [Try it online!](http://matl.tryitonline.net/#code=cTp0aVx-KnVz&input=NTAKWzI7IDM7IDVd) [Answer] ## [Retina](https://github.com/m-ender/retina), 34 bytes Byte count assumes ISO 8859-1 encoding. ``` \d+ $* M&!`(.+)\1*(?=1¶.*\b\1\b) 1 ``` Input format is ``` 50 2,3,5 ``` [Try it online!](https://tio.run/nexus/retina#@x@Tos2losXlq6aYoKGnrRljqKVhb2t4aJueVkxSjGFMkiaX4f//pgZcRjrGOqYA "Retina – TIO Nexus") [Answer] # R, 67 bytes ``` a=scan();x=c();for(i in a[-1])x=c(x,seq(i,a[1]-1,i));sum(unique(x)) ``` Takes a vector to STDIN in the following format: `[N, a_1, a_2, ...]`. Supports any number of `a`. For each `a`, creates the sequence `a` to `N-1` with stepsize `a`. Then takes the sum of all the unique entries in that vector. [Answer] # Python, 67 bytes ``` a,b,c=input() x=y=0 exec("if x%c<1or 1>x%b:y+=x\nx+=1\n"*a) print y ``` After writing this I noticed my code was similar to the existing python answer, however I came up with it independently and am posting it anyway. [Answer] # Mathematica, ~~37~~ 27 bytes *Thanks to Martin Ender for a shrewd observation that led to big byte savings!* ``` Tr[Union@@Range[#,#2-1,#]]& ``` Unnamed function taking two arguments, a list `#` of integers (the desired divisors `A`) and an integer `#2` (the upper bound `N`) , and returning an integer. `Range[#,#2-1,#]` gives, for each element `d` of the list `#`, all the multiples of `d` less than or equal to `#-1` (hence less than `#`); the union of these lists is then computed and summed with `Tr`. Previous version: ``` Tr[x=#;Union@@(Range[#,x-1,#]&/@#2)]& ``` [Answer] # [Perl 6](http://perl6.org/), 25 bytes ``` {sum grep *%%@_.any,^$^a} ``` A lambda that takes the input numbers as arguments. (One argument for N, and an arbitrary number of arguments for A). ([Try it online.](https://tio.run/#88XEy)) ### Explanation: * `{ ... }`: A lambda. * `$^a`: First argument of the lambda. * `@_`: Remaining arguments of the lambda ("variadic parameter"). * `^$^a`: Range from `0` to `$^a - 1`. * `* %% @_.any`: Another lambda, which tests its argument `*` using the divisible-by operator `%%` against an `any`-[Junction](https://docs.perl6.org/type/Junction) of the list `@_`. * `grep PREDICATE, RANGE`: iterates the range of numbers and returns the ones for which the predicate is true. [Answer] # Haskell, ~~42~~ 39 bytes ``` a!b=sum[x|x<-[1..a-1],any((<1).mod x)b] ``` Usage: ``` Main> 50![2,3,5] 857 ``` Thanks to @Zgarb for 3 bytes [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes ``` FND²%P_*O ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Rk5EwrIlUF8qTw&input=NTAKWzIsIDMsIDVd) ``` F For N in [0, ..., input[0]-1] ND²% Evaluate N%input[1]; yields an array of results P Take the total product of the array. Yields 0 only if at least one of the value is 0, in other words if N is multiple of at least one of the specified values _ Boolean negation, yields 1 if the last value is 0 and yields 0 otherwise * Multiply by N: yields N if the last value is 0 and yields 0 otherwise O Display the total sum ``` [Answer] # Octave, ~~49~~ 37 bytes ``` @(A,N)sum(unique((z=(1:N)'.*A)(z<N))) ``` the function will be called as `f([2 3 4],50)` Assume that `A=[2 3 4];` we require to have sum of numbers as ``` sum( 2,4,6...,50-1 , 3,6,9...,50-1, 4,8,12,...50-1) ``` we can multiply `[2 3 4]` by `1:50` to get matrix `(1:N)'.*A` ``` [2 4 6 ... 2*50 3 6 9 ... 3*50 4 8 12 ...4*50] ``` then extract from the matrix those that are smaller than 50 : `z(z<N)` Since there are repeated elements in the matrix we extract unique values and sum them. **previous answer**: (this solution will fail if N==1) ``` @(A,N)sum((k=uint64(1:N-1))(any(k==(k./A').*A'))) ``` function should be called as `f(unit64([2 3 4]),uint64(50))` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~43 41 39~~ 35 bytes ``` b^:sFc,a{f:0Fdb{f?0c%d?0(f:i+:c)}}i ``` [Try it online!](https://tio.run/##K8gs@P8/Kc6q2C1ZJ7E6zcrALSWpOs3eIFk1xd5AI80qU9sqWbO2NvP///@GBgYG/40VTAE "Pip – Try It Online") Explanation: ``` Takes inputs like so: arg1 1000 arg2 3 5 b^:s ;read rest of inputs as array ;(s is " " and ^ is split into array on char) F c ,a{ ;for(c in range(0,a)) f:0 ;flag to prevent double counting 15,30,etc. F d b { ;forEach(d in b) f? 0 c%d? 0 (f:i+:c) ;if flag {continue}elif c%d {f=i+=c} ; (i will always be truthy so why not) } } i ;print sum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-fx`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ ~~7~~ ~~6~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` VøUâ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWZ4&code=VvhV4g&input=NTAKWzIsMyw1XQ) [Answer] # Pyth, 10 bytes ``` s{sm:0hQdt ``` ### Explanation ``` s{sm:0hQdtQ Implicit input :0hQd Get multiples of d below the bound m tQ ... for each d given s Concatenate results { Remove repeats s Take the sum ``` [Answer] # T-SQL, 87 bytes This will work as long as `@i` has a value of 2048 or lower ``` USE master--needed for databases not using master as default DECLARE @i INT=50 DECLARE @ table(a int) INSERT @ values(2),(3),(5) SELECT sum(distinct number)FROM spt_values,@ WHERE number%a=0and abs(number)<@i ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/604910/find-the-sum-of-all-numbers-below-n-that-are-a-multiple-of-some-set-of-numbers)** [Answer] ## Ruby, ~~52 48~~ 46 bytes ``` ->b{b[s=0].times{|x|b.find{|y|x%y<1&&s+=x}};s} ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes ``` +/⊢∘⍳∩∘∊×∘⍳¨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/7X1H3UtetQx41Hv5kcdK0GMjq7D0yECh1b8TwMqetTbB1Hf1XxovfGjtolAXnCQM5AM8fAM/m@kkKZgasBlrGAKZBgacJkogESMLLjMISKWXEYKEElTAwA "APL (Dyalog Unicode) – Try It Online") Anonymous tacit function. Thanks to @Adám for helping me shave 3 bytes off of this. Uses `⎕IO←0`. ### How: ``` +/⊢∘⍳∩∘∊×∘⍳¨ ⍝ Tacit function. Left and right arguments will be called ⍺ and ⍵ respectively. ×∘⍳¨ ⍝ Multiply ⍺ with each element of [0..⍵-1] ∊ ⍝ Enlist (flattens the vector) ∩∘ ⍝ Then, get the intersection of that vector with ⊢∘⍳ ⍝ The vector [0..⍵-1]. +/ ⍝ Then sum ``` [Answer] # Google Sheets, ~~141 140 134 132~~ 90 Closing parens already discounted. Phew! That was more work than I bargained for. The hard part was getting something that worked for all ranges. ### Inputs: * `A1` - N * Row `2` - A1, A2, ... ### Formulae: * `A3` - `=A1-1` (N - 1) * `A4` - `=SUM(ArrayFormula(SEQUENCE(A3)*LT(,COUNTIF(MMULT(SEQUENCE(A1),FILTER(2:2,2:2)),SEQUENCE(A3)))))` Where `A4` is the final output. ### How It Works Hint: Start from the middle. ``` # Sum everything together =SUM( ArrayFormula( # The "number under N" SEQUENCE(A3)* # Use the LT Operator function to pile parens at the end LT( # Implicit 0 , COUNTIF( # Generate every multiple of each element in A via matrix multiplication up to the Nth multiple. # This is overkill, but saves characters. MMULT( # Column Matrix `(1, ... , N)` and Row Matrix `(A1, A2, ...)`. SEQUENCE(A1), # Have to remove blanks from the end FILTER(2:2,2:2) ), # If element appears in the resulting matrix, multiply by 1, or else 0 SEQUENCE(A3) ) ) ) ) ``` [Answer] # x86-16 machine code, ~~27~~ 25 bytes Binary: ``` 00000000: 33db 4a51 56ac a20c 018a c2d4 0ae0 f675 3.JQV..........u 00000010: 0203 da5e 594a 75eb c3 ...^YJu.. ``` Listing: ``` 33 DB XOR BX, BX ; clear BX running sum 4A DEC DX ; N = N - 1 (only multiples below N) N_LOOP: 51 PUSH CX ; save array length 56 PUSH SI ; save array start pointer F_LOOP: AC LODSB ; AL = next factor A2 0C01 MOV BYTE PTR[AAM1+1], AL ; AAM divisor = AL 8A C2 MOV AL, DL ; AL = dividend AAM1: D4 0A AAM ; ZF = ( current N % factor == 0 ) E0 F6 LOOPNZ F_LOOP ; if not a multiple, continue to next factor 75 02 JNZ F_BREAK ; if last is not a multiple, don't add 03 DA ADD BX, DX ; otherwise add factor to sum F_BREAK: 5E POP SI ; restore array pointer 59 POP CX ; restore array length 4A DEC DX ; decrement N / loop counter 75 EB JNZ N_LOOP ; loop until N = 0 C3 RET ; return to caller ``` As a function: input `N` in `DL`, `SI` array of factors, `CX` array size. Once again, using DOS DEBUG to test. Note: literal values are in hex in DEBUG. `N` = `10` (`0xA`), `[ 3, 5 ]` = `23` (`0x17`) [![enter image description here](https://i.stack.imgur.com/DyXqP.png)](https://i.stack.imgur.com/DyXqP.png) `N` = `50` (`0x32`), `[ 2, 3, 5 ]` = `857` (`0x359`) [![enter image description here](https://i.stack.imgur.com/bgHEt.png)](https://i.stack.imgur.com/bgHEt.png) [Answer] # [Fig](https://github.com/Seggan/Fig), \$11\log\_{256}(96)\approx\$ 9.054 bytes ``` VxSFrx'!A%v ``` *-8.232 bytes thanks to @Sʨɠɠan* [Try it online!](https://fig.fly.dev/#WyJWeFNGcngnIUEldiIsIlszLCA1XVxuMTAiXQ==) Explanation: ``` Vx # Set the register to the first input (the list) rx # Range [0, n) F ' # Filter: % # Modulo v # The register A # All truthy ! # Logical not S # Sum ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 9 bytes ``` ⁻řĐ←ΠǤ1>· ``` [Try it online!](https://tio.run/##AR8A4P9weXT//@KBu8WZxJDihpDOoMekMT7Ct///NTAKWzJd "Pyt – Try It Online") ``` ⁻ř implicit input (N); decrement and push [1,2,...,N-1] Đ duplicate top of stack ←Π get the product of the members of A Ǥ GCD (elementwise) 1> is each GCD greater than 1? · dot product; implicit print ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes ``` ᵒ%ᵐ∏¬x∙ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fhsebp2k-nDrhEcd_YfWVDzqmLmkOCm5GCq54KZOtFGsgqkBV7SxjmmsgiGQYaIDFDGy4Io2B4tYckUb6YAlTQ0gmgA) ``` ᵒ%ᵐ∏¬x∙ ᵒ% Generate a modulo table ᵐ∏ Take product of each row ¬ Logical not x∙ Dot product with range from 0 to length - 1 ``` [Answer] # Rust, 52 bytes ``` |n,v|(1..n).filter(|e|v.iter().any(|x|e%x==0)).sum() ``` [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=fn+main%28%29+%7B%0A++++let+solution%3A+fn%28usize%2C+%26%5Busize%5D%29+-%3E+usize+%3D%0A++++++++%7Cn%2C+v%7C+%281..n%29.filter%28%7Ce%7C+v.iter%28%29.any%28%7Cx%7C+e+%25+x+%3D%3D+0%29%29.sum%28%29%3B%0A++++%2F%2F+%7Cn%2Cv%7C%281..n%29.filter%28%7Ce%7Cv.iter%28%29.any%28%7Cx%7Ce%25x%3D%3D0%29%29.sum%28%29%0A%0A++++assert_eq%21%28solution%2850%2C+%26%5B2%5D%29%2C+600%29%3B%0A++++assert_eq%21%28solution%2810%2C+%26%5B3%2C+5%5D%29%2C+23%29%3B%0A++++assert_eq%21%28solution%2828%2C+%26%5B4%2C+2%5D%29%2C+182%29%3B%0A++++assert_eq%21%28solution%2819%2C+%26%5B7%2C+5%5D%29%2C+51%29%3B%0A++++assert_eq%21%28solution%2850%2C+%26%5B2%2C+3%2C+5%5D%29%2C+857%29%3B%0A%7D%0A) [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 13 bytes `#º#Xáà%¬*«ÍÌS` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=I7ojWOHgJawqq83MUw==&in=MTkgWzcsIDVd) # Explanation ``` # ; read the number º ; convert it to a zero-based range # ; read the list of numbers × « ; execute for each pair of numbers in the input áà ; duplicate the lower number in the pair %¬ ; check for divisibility * ; keep the number if it is divisible ÍÌ ; uniquify the list S ; sum up the elements ``` --- # Itr, [11 bytes](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=ulji4CWsKqvNzFM=&in=MTkgWzcsIDVd) using implicit IO `ºXâà%¬*«ÍÌS` [Answer] ## Python 2, 80 Bytes This is very long. Can definitely be shortened. Taking the 3 numbers as separate inputs is definitely hurting the score. ``` i=input x=i();y=i();z=i();s=c=0 exec("if c%z<1 or c%y<1:s+=c\nc+=1\n"*x) print s ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 13 bytes ``` DR∙`i;)%Y*`MΣ ``` [Try it online!](https://tio.run/nexus/actually#@@8S9KhjZkKmtaZqpFaC77nF//9XG@uY1nIZGgAA "Actually – TIO Nexus") Explanation: ``` DR∙`i;)%Y*`MΣ DR range(1, N) ∙ Cartesian product with A `i;)%Y*`M for each pair: i;) flatten, make a copy of the value from the range %Y test if value from range divides value from A * value from range if above is true else 0 Σ sum ``` [Answer] ## Common Lisp, 77 ``` (lambda(n x)(loop for i below n when(some(lambda(u)(zerop(mod i u)))x)sum i)) ``` ### Ungolfed ``` (lambda (limit seeds) (loop for i below limit when (some (lambda (u) (zerop (mod i u))) seeds) sum i)) ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 57 bytes ``` param($a,$b)(1..--$a|?{$i=$_;$b|?{!($i%$_)}})-join'+'|iex ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSqKOSpKlhqKenq6uSWGNfrZJpqxJvrZIEZCpqqGSqqsRr1tZq6mblZ@apa6vXZKZW/P//39Dgv4OGsY6pJgA "PowerShell – TIO Nexus") Iterative solution. Takes input as a number `$a` and as a literal array `$b`. Loops from `1` up to one below `$a` (via `--$a`), using a `Where-Object` operator `|?{...}` with a clause to select certain numbers. The clause sets `$i` to be the current number before sending input array `$b` into another `|?{...}`, here picking out those items where the current number is evenly divided by at least one of the numbers in `$b`. Those elements of `$b` that do divide evenly are left on the pipeline. Thus, if there is at least one element from `$b`, the pipeline contains an element, so the outer `Where` is `$true` and the current number is left on the pipeline. Otherwise, with no elements from `$b` on the pipeline, the outer `Where` is `$false`, so the current number is not placed on the pipeline. Those numbers are all gathered up in parens, `-join`ed together with `+` signs, and piped to `|iex` (short for `Invoke-Expression` and similar to `eval`). The summation result is left on the pipeline, and output is implicit. ]
[Question] [ Given a rectangular haystack of size at least 2x2 composed of all the same printable ASCII characters, output the location (counting from the top-left) of the needle which is a different character. For example, if the following haystack is input: ``` ##### ###N# ##### ##### ``` The output should be `3,1` when zero-indexed (what I'll be using in this challenge) or `4,2` when one-indexed. The haystack can be composed of any printable ASCII character: ``` ^^^ ^^^ ^N^ ^^^ ^^^ ^^^ ``` output: `1,2` and the needle will be any *other* printable ASCII character: ``` jjjjjj j@jjjj jjjjjj ``` output `1,1` It's also possible to have a needle in the corner: ``` Z8 88 ``` output `0,0` ``` 88 8Z ``` output `1,1` or to have the needle at the edge: ``` >>>>>>>>>> >>>>>>>>>: >>>>>>>>>> ``` output `9,1` ### Rules and Clarifications * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). This means you can take input as a list of list of characters, as a single string, etc. * You can print the result to STDOUT or return it as a function result. Please state in your submission what order the output is in (i.e., horizontal then vertical, as used in the challenge, or vice versa). * Either a full program or a function are acceptable. * You do *not* get to pick which characters to use. That's the challenge. * The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay. * There is only ever one needle in the input, and it's only ever one character in size. * [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] # [R](https://www.r-project.org/), ~~49~~ ~~47~~ 44 bytes ``` function(m,`?`=which)m==names(?table(m)<2)?T ``` [Try it online!](https://tio.run/##TY3BTsMwDIbveQprvcRSuWwIVWilHDlMO3HaoVrI3DVTk1aJgfL0JW3Fwi/Z/h1/jv3UwP5haj6dZtM7afNzdS6/W6NbtGXplKUgK1YfHUmL@y1W71P2Rt1AHv6WgHvwpC7ALQFTYNAqUADlLqB790WeZ0SBVezNKK7l/dyIQQ1D9yMD@zB0huX80cG4eDUfMd9sMNcoRCOv8hFRZLPmfMySj3kBniJQ1/Uaxzr5GAuwi8Btkbi9rmXtluk2Tk@FKIrURl@c0u7LXck@/3udfgE "R – Try It Online") Takes input as a matrix, returns 1-indexed coordinates [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~41 38~~ 37 bytes *3 bytes saved thanks to @nwellnhof.* *1 byte saved thanks to Jo King.* ``` {map {[+] ^∞Z*!<<.&[Z~~]},$_,.&[Z]} ``` [Try it online!](https://tio.run/##RUxbCoMwEPzPKbZRilrxs0h90BN4gKgpWhQqaqWxHyL63VP0cL2IjYmYgdmZ2R22K171eWkGOJYQLGOTdTDGpxTo7/Ml1sH3nWNM5jmdbP1mrz6dFg@xdw59wXpDZyaMwLIBdOYJLfnOqR9twRz@zLCc@7PJ@YL1ppyyhgOJpE1aDBNC4h3WViDOSExtm9j0tgKlFAlGm0qqQiWAqqsUAXUlLnJdFV0eiYrhDrS7i7Lh2lz@ "Perl 6 – Try It Online") ## Explanation It takes the input as a list of lists of characters and returns list of length 2 containing zero-based X and Y coordinates of the needle. It works by applying the block `{[+] ^∞ Z* !<<.&[Z~~]}` on the input and on its transpose. `.&[Z~~]` goes through all columns of the argument and returns `True` if all the elements are the same, `False` otherwise. We then negate all the values (so we have a list with one bool per column, where the bool answers the question "Is the needle in that column?"), multiply them element-wise with a sequence 0,1,2,... (`True = 1` and `False = 0`) and sum the list, so the result of the whole block is the 0-based number of the column where the needle was found. # Nwellnhof's better approach, [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` {map *.first(:k,*.Set>1),.&[Z],$_} ``` [Try it online!](https://tio.run/##RUxBCoMwELznFSGKGJFALyUoSl/gpTdrLVoiaNWKSQ8ivj2NiZiBmdnZHXZic3@VwwK9BiZyHaoJBqRpZy786BMG5M5EesEh8R75M3Rfm4wB/9VQMFVwOYYr5NUCXR5rb9SO9O3IOFGf/IC8v0OtFlxgo6aGEoNiLEYENwD0O@TsAIqZVudQhOOjUJYl0MwON7SFTgN0N2Ma9ppTQKmNVMXcxvQEOKfIjunelH8 "Perl 6 – Try It Online") ## Explanation Generally the same approach, just more effective. It still uses a block on the array and its transpose, but now the block converts all *rows* into`Sets` and checks for the number of elements. The `first` function then gives index (due to the `:k`) of the first row that contained more than 1 element. Because of that, the order of `$_` and `.&[Z]` needed to be swapped. [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda m:[map(len,map(set,a)).index(2)for a in zip(*m),m] ``` **[Try it online!](https://tio.run/##TY5BCoMwEEX3OcWAiyQldeFKBEtP4AGsDaSoNGJi0CBtL28zcaEPkvk/8yHfff17stnWl802KvNqFZjiYZRjY2cFzqXzQnGeatt2H5bxfppBgbbw045dDBfmuflu8QuUwCilDUkQvKvk0EkSdkRATEgp91PJQ0t5SgwRMtz3ETmt65zk@cnnwdfoOSFYEAthx1isIBBYQz@06eJG7RmPj5idMbjuIcTN2nqYyaFpUNcbFdCzlYcfG0u3Pw "Python 2 – Try It Online")** --- A port of this to **[Python 3](https://docs.python.org/3/)** can be **62 bytes**: ``` lambda m:[[len(set(v))for v in a].index(2)for a in(zip(*m),m)] ``` The list comprehension, `[len(set(v))for v in a]`, is shorter than the double map by two bytes now as it would need to be cast to a list like `list(map(len,map(set,a)))` [Try it online!](https://tio.run/##TVBLCoMwFNznFA9cJCnWRbsRwdITeAA/AYtKIxpFQ2h7@TQvWehA8mbmDWTI@tXvRd3tkNd2audX18KcVdXUK7b3mhnOh2UDA1JB2yRSdf2H3bzXOo/95MouM49n3ljd73qHHBiltCYRAu8iOngUuR2JwSeEEOEU4uBCnBKjBxmfYXic1mVK0vSkU6dL1JwQbIiFsLgvlhFwMK4fymRfJ6kZ9yZmNwyaEEKsm1SabSEQBHXs@qAxDO5b3JO1otz@AQ "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes ``` c≡ᵍ∋Ȯ&;I∋₎;J∋₎gȮ∧I;J ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/lR58KHW3sfdXSfWKdm7QmkHzX1WXtB6PQT6x51LPe09vr/P1pJGQSUdEC0H5RWRtCx/6MA "Brachylog – Try It Online") Outputs `[I,J]`, where `I` is the row index and `J` the column index, both 0-indexed. Stupidely long, but getting indexes in Brachylog is usually very verbose. ### Explanation ``` c Concatenate the Input into a single string ≡ᵍ Group identical characters together ∋Ȯ Ȯ is a list of One element, which is the needle character &;I∋₎ Take the Ith row of the Input ;J∋₎ Take the Jth character of the Ith row gȮ That character, when wrapped in a list, is Ȯ ∧I;J The output is the list [I,J] ``` [Answer] # [PHP](https://php.net/), ~~99~~ 85 bytes Using string without newlines and the width (or height) `('########N###########', 5`) as input. * -5 bytes by removing chr() call, props to @Titus * -9 bytes by taking input as two function args, also props to @Titus ``` function($a,$l){return[($p=strpos($a,array_flip(count_chars($a,1))[1]))%$l,$p/$l|0];} ``` [Try it online!](https://tio.run/##ZZDBS8MwGMXv/Ss@tkgS@MBWUYq16kXwIHPnlayE2tLO2IYkPcjc317TrbQHf4fwHu/xSKJrPTw@61oDqdKh6tvCNV3LiESi@NGUrjdtxohOrTO6s2MgjZE/eaUazYqub11e1NKck4jzLBKcXxGFRF8T9RuK5DQkxJXWWUghCwAyup7YrBco3gk8p/sLm/0MxdspO1x4OcxQvJ@yXRzHFG8m581ucU//eVgkxSgUgUiCoOpMKYuawXRjab0CDke/AmVRd1DUffuVW60ax4jLQoH@9G9GoBlFaL616j5LtsIV@h8dh@aO3xlrwte2b9v89eN9FklwGv4A "PHP – Try It Online") Ungolfed: ``` function need_hay( $a, $l ) { // identify the "needle" by counting the chars and // looking for the char with exactly 1 occurrence // note: this is 1 byte shorter than using array_search() $n = array_flip( count_chars( $a, 1 ) )[1]; // find the location in the input string $p = strpos( $a, $n ); // row is location divided by row length, rounded down $r = floor( $p / $l ); // column is remainder of location divided by row length $c = $p % $l; return array( $c, $r ); } ``` Output: ``` ##### ###N# ##### ##### [3,1] ^^^ ^^^ ^N^ ^^^ ^^^ ^^^ [1,2] jjjjjj j@jjjj jjjjjj [1,1] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 6 bytes Saved 3 bytes switching input format. Input is taken as a string and a row-length. Output is a zero-based list of the form `[y, x]` ``` D.mks‰ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fRS83u/hRw4b//@0wgRWCyWVoAAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W/m9t9FLze7@FHDhv86/5WhwE8ZAbhMueIgwC8ODriMubIgwCELDrjMuKIsLCy4jLiAZBSQssMEVggml6EBAA) **Explanation** ``` D # duplicate the input string .m # get the least frequent character k # get its index in the string s # swap the row length to the top of the stack ‰ # divmod the index of the least frequent char with the row length ``` [Answer] # [Python 3](https://docs.python.org/3/) + [NumPy](https://docs.scipy.org/doc/numpy-1.16.1/reference/), ~~75~~ 66 bytes -9 bytes thanks to [@ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) ``` lambda x:where(x.view('i')-median(x.view('i'))) from numpy import* ``` [Try it online!](https://tio.run/##nZJNDsIgFIT3nOJFFwVT3bhpmmg8QQ9QfxJMIWKEEqTaxnj2itaFFrWNJLNg3jfDW6Aru8vVtOazVX2gcptRKOPzjhmGy8lJsDMOREDGkmWCqleLEMRNLkEVUlcgpM6NHdVC6cIeYQYYgTvUGFrh5TIYBmFL6/BBPM87kXQSw77EmoTvm2yc36id/j1J/sh0Trzt9s731W64u4te1Icu783U@ZGXjhrXo6OvdPqBnju/W@22Pqn4r9T8viMiCPHcQAlCQfNj40eVNkJZXJKXCx8kjGUHBuII1MKFu/F1slIDUt8A "Python 3 – Try It Online") This assumes that the input is a NumPy array. The output is zero-indexed, and first vertical, then horizontal. It converts the input from `char` to `int` then calculates the median of the array, which will be the haystack character. We subtract that from the array, which makes the needle the only non-zero element. Finally, return the index of that element with `numpy.where()`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes Outputs **[height, width]** (1-indexed). ``` ŒĠLÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8///opCMLfA5PeLiz6f/h9kdNa9yA2P3//@hodWUQUNdRADH8YAxlJEasDpdCtHpcXBxICEb5ofAQFERxFhiAxLIc4CyIGERBlAVIyMICyrWAcKOgXDs4AAnDOVYoPDv12FgA "Jelly – Try It Online") ``` ŒĠLÐṂ – Monadic link / Full program. Takes a list of strings M as input. ŒĠ – Group the multidimensional indices by their values (treating M as a matrix). LÐṂ – And retrieve the shortest group of indices (those of the unique character). ``` --- ### [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ŒĠḊÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8///opCMLHu7oOjzh4Y75/w@3P2pa4wbE7v//R0erK4OAuo4CiOEHYygjMWJ1uBSi1ePi4kBCMMoPhYegIIqzwAAkluUAZ0HEIAqiLEBCFhZQrgWEGwXl2sEBSBjOsULh2anHxgIA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Maybe this could've just been a comment for Mr. Xcoder it is pretty similar... ``` ŒĠEƇ ``` A monadic link accepting the matrix of characters which yields a list of one item, the 1-indexed (row, column) co-ordinate from top-left. (...As a full program given an argument formatted such that parsing results in a list of lists of characters -- that is a list of strings in Python format -- the single coordinate is printed.) **[Try it online!](https://tio.run/##y0rNyan8///opCMLXI@1////P1pdXT0LDIAMLh0QzwGFB5eLBQA "Jelly – Try It Online")** ### How? ``` ŒĠEƇ - Link: matrix, M ŒĠ - multi-dimensional indices grouped by Value - ...due to the 2*2 minimum size and one needle this will be a list of two lists one - of which will have length one (the needle coordinates as a pair) and the other - containing all other coordinates as pairs Ƈ - filter keeping those for which this is truthy: E - all equal? - ... 1 for the list of length 1, 0 for the list of at least 3 non-equal coordinates ``` [Answer] # JavaScript (ES6), 55 bytes Takes input as \$(s)(w)\$, where \$s\$ is a string and \$w\$ is the width of the matrix. Returns \$[x,y]\$. ``` s=>w=>[(i=s.indexOf(/(.)\1+(.)/.exec(s+s)[2]))%w,i/w|0] ``` [Try it online!](https://tio.run/##jY7fCoIwFIfvfYpBRDtozj8UJig9Qd1rCaEzlHDRNLvo3c3pEIuwzsX4nbPzfVt@up94fMuu5bJgCW1Sr@GeX3t@iDOP61mR0Mc@xQTrcDDV9iQ6fdAYc5VDaB0B5rWWkfppHJuYFZxdqH5hZ5xihAhBrCqvVekiWzMVhBYzUQukyrwb5dl7VgCvAJQJpalZYj2KIgmO0u7L7C21entK39q7D@ddSTDfjpv@phWtJ0WGZoj1wJGc4wjG@udxZ2CC38ymZ/yhJDv07ufAF1LTAGhe "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~65~~ 64 bytes *Saved 1 byte thanks to @Neil* Takes input as a matrix of characters. Returns \$[x,y]\$. ``` m=>m.some((r,y)=>r.some((c,x)=>!m[p=[x,y],~y&1].includes(c)))&&p ``` [Try it online!](https://tio.run/##lY/dCoIwGIbPvYqFYBuspXViwkZX0AUoCrI0FHXiT@RJt25WasvC6Dt73u15vy32z37JiyivVpk4Bm1I25SylJQiDSAscIMoK3ri@NLRInVy6lxw4@JroxkuiTKe1MeghBwhpGl5y0VWiiQgiTjBEDpgvQairvK6ssAWGwoADiFkqd5n6WKJDxNWv7DiIqTMbDDwZjA8z5P8CR1mzj5pfmu3dPxW/BjJj/fToL/xo1PH@mDYpqSb5j/PMd9U@6e6e6lsHKlizKxvIXv2tzc "JavaScript (Node.js) – Try It Online") ### How? We look for the first character \$c\$ located at \$(x,y)\$ which does not appear anywhere in another row \$r[Y]\$. We can perform this test on any row, as long as \$Y\ne y\$. Because the input matrix is guaranteed to be at least \$2\times 2\$, we can simply use \$Y=0\$ if \$y\$ is odd or \$Y=1\$ if \$y\$ is even. [Answer] # Java 8, ~~132~~ 111 bytes ``` m->{int c=m[0][0],i=0,j;for(c=m[1][0]!=c?m[1][1]:c;;i++)for(j=m[i].length;j-->0;)if(m[i][j]!=c)return i+","+j;} ``` -8 bytes (and -13 more implicitly) thanks to *@dana*. Input as character-matrix. [Try it online.](https://tio.run/##xZBfa4MwFMXf@ynu7EvEP7Rv0qDb2PN82ZtiIUttm0xjiWlHKX52l9iu7GE6WoRdJMT7u5dzTjg5EI@vPlpakLqGV8LEaQLAhMrlmtAcYvML8KYkExugiG6JTLM0g9LGmjQTfdSKKEYhBgEhtKUXnfQ@0LBMZ5n@XBbOXI7XlUSmNze9h5A@dtd5tqAYM8exDeeas8wvcrFRW8w9L5phm62R6abcbNkyV3spgDmWazkcNy02Fnb790JbuDg5VGwFpc6Czr61XWJfghxrlZd@tVf@TiNVCCR8ikT@Cd/RzoMA1tSU5avqRZNnKckR2e4PGA/B6XiwY43dPfhtCZbLZZ/QEIrv2roF3R@Jd9WnxJ8G6W@791tJgj6hIBhNJOgXScYTSf41STKeSHStPrHrwOLPiWjAVjNp2i8) **Explanation:** ``` m->{ // Method with char-matrix parameter and String return-type int c=m[0][0], // Character to check, starting at the one at position 0,0 i=0,j; // Index integers for(c=m[1][0]!=c? // If the second character does not equal the first: m[1][1] // Use the character at position 1,1 instead :c; // Else: keep the character the same ;i++) // Loop `i` from 0 indefinitely upwards: for(j=m[i].length;j-->0;) // Inner loop `j` in the range (amount_of_columns, 0]: if(m[i][j]!=c) // If the `i,j`'th character doesn't equal our character to check: return i+","+j;}// Return `i,j` as result ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 8 bytes ``` tX:XM-&f ``` [Try it online!](https://tio.run/##y00syfn/vyTCKsJXVy3t//9oBXV9dQV1RXUwbQ0iwCwYqRALAA "MATL – Try It Online") Using the `mode` function as the majority-detector. Returns 1-based indices. ``` t % duplicate the input X: % turn the copy into a linear array XM % find the arithmetic mode of that (the 'haystack' character) - % Subtract that from the original input &f % find the position of the non-zero value in that result ``` *-4 characters thanks to @LuisMendo* [Answer] # Wolfram Language ~~37~~ 58 bytes My earlier entry did not correctly handle the case where the "odd character out" was at the upper left corner of the matrix. This does. ``` #~Position~Keys[TakeSmallest[Counts@Flatten@#,1]][[1]]& ``` --- `Counts@Flatten@#` lists how many of each character are in the array, `#`. `TakeSmallest[...,1]` returns the least frequent count, in the form of an association rule such as `<| "Z"->1|>` `Keys...[[1]]` returns the "key" to the only item in the association, that of the least used character. ("Z" in the present case) `#~Position~...` returns then position of the key in the original matrix, `#`. [Answer] # Perl 5 `-p00`, ~~52~~ 45 bytes ``` /^(.)(\1* )*(\1*)|^/;$_=$&=~y/ //.$".length$3 ``` [45 bytes](https://tio.run/##K0gtyjH9/18/TkNPUyPGUItLUwtEadbE6VurxNuqqNnWVepz6evrqSjp5aTmpZdkqBj//68MAlxA7AcmlWEkF1dcXBwE@8Uh2EDMxZUFBlxZDhAKwuPiirLgsrAA0kDCIgpI28EBgmmFLPovv6AkMz@v@L@ur6megeF/3ZwCAwMA) [52 bytes](https://tio.run/##K0gtyjH9/1@fS99apdxWyUFbyVo/TkNPUyPGsIZLU7smDigeDxZXVSnXU1HSy8wrAfH0Vcr//1cGAS4g9gOTyjCSiysuLg6C/eIQbCDm4soCA64sBwgF4XFxRVlwWVgAaSBhEQWk7eAAwbRCFv2XX1CSmZ9X/F/X11TPwPC/bk6BgQEA) How * `-p00` : like `-n` but also print, paragraph mode * `/^(.)(\1* )*(\1*)|^/` : matches either + from start `$1`: first character, `$2`: repetition (not used), `$3`: characters before the "needle" in the line, `$&` whole match + or null string (position 0) no capture. * `$_=` : to assign the default input/argument variable * so `$&=~y/ //` the number of newlines of `$&` * `.$".` : concatenate with `$"` (space character by default) and concatenate * `length$3` : the length of `$3` [Answer] # [R](https://www.r-project.org/) 42 bytes ``` function(m)which(ave(m,m,FUN=length)==1,T) ``` [Try it online!](https://tio.run/##lY9RS8MwFIXf8ysCPtwEsmHbKWXYsZcNfFEQ9yJ9KaW1Gc21tDfaf18jsZtlbLhLHkJO7jnfaYeSP8z4UFrMSX@gMPKr0nklss9CGGXUdveU1AW@UyWTJFCvcmA3fNNnpqkLHrA8IwEpbvo5D1JMESQzP4aw97PeHwa8YrHWHYmO2q6pNbkQAPm7ZTJqde@eeKT4vRzdH7GxtPTmLv3F4jH52dJBLB09Y6MCfr8tGgEzUIs7l/KHPRz/efpwQr86neXxem2T4PZSlfB8lf81iaZNokmTtziOr@IN3bmEG53DHb4B) **Input:** a haystack matrix `m` **Output:** `(row,col)` vector - index starting at `1` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~109~~ ~~108~~ 107 bytes First() => Last() for -1 byte currying for -1 byte thanks to Embodiment of Ignorance ``` a=>w=>{var d=a.Where(b=>b!=a[0]).Select(b=>a.IndexOf(b));return d.Count()>1?(0,0):(d.Last()%w,d.Last()/w);} ``` [Try it online!](https://tio.run/##dVHva8IwEP3c/hW3ukGCWdYqG2JtNxAGgrgPDgRFobZRKy4daVyF0r@9S1p/bWPvwzW9e/fyLhem92Eal697HvZSKWK@JlD9xFwSQFVUAfs@rFQavDLw/Mzz869AQOQFdLJhgqGl5y9vvGBmzzEdsx0LpU4FdMAjdnhboSXGrmByLzhEtJ/suUTYd56RTWzcRREdBqnK3GXkdHzIsFuUrqmvkSyV/SBlKXjAWQYInZxqZ9cu8WyemwhZjSNGjQssAo@YGAagNgEHY6KJixqjxRmK1laamucQaB152xov2zMU76mWcy5y006nY@kuLaBrNgH7WFOl6Y9a3Ve4prlKhJ4BYjWg7apP7zIzHTK@lhuVbTaxmZtGP@FpsmN0ImLJ0K2Vx0UXLOyahn4rUb2SXhU6S8ziOR1I9uHUEf9XaZ1E1kkSKZU/tJb76/phzLUFdvhUG2cR5LqTvifjaj8IF0RpSciVq@usdluU3w "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes ``` $#:(i.~.{~1 i.~#/.~)@, ``` [Try it online!](https://tio.run/##ZYxNC4JAFEX3/opLRk/BJj8qbEQxAiEQidy5cCOJ2aJFixaBf92eaUp0hmFm3px763YmqIQvQTBgQvJeChzOcdTOValdRSNejQU@1ZVo9NBodUUpqpsvoC1lqS@ClfKo7k9@X4rqHmoGNIr2x5g8Ou3TlHS8GnCAY50HCw48rLHBHKQOJOoE9Z7Npoct2@zlPUk@Qt@2znLYY6vuCeuRwTJ5edxod1bmuu5PepjzOBvnu0@rZXYfwT9yupLSvgE "J – Try It Online") NB. returns answer in (row, column) format. [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ 47 bytes ``` lambda s,w:divmod(s.find(min(s,key=s.count)),w) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYp9wqJbMsNz9Fo1gvLTMvRSM3M0@jWCc7tdK2WC85vzSvRFNTp1zzf0FRZl6JQpqGkjIU@CkjgJKOgqnmfwA "Python 2 – Try It Online") Call as `f("########N###########", 5)` (allowed in a [comment](https://codegolf.stackexchange.com/questions/179351/find-the-needle-in-the-haystack#comment432444_179351)). Outputs `(y, x)`. Erik saved 6 bytes, suggesting rearranging the output + using `divmod`. Thanks! [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~107~~ ~~98~~ ~~82~~ 77 bytes ``` $l=@{} $args|%{if($_-10){$l.$_+=$x++,+$y}else{$x=0;++$y}} $l|% v*|? c*t -eq 2 ``` [Try it online!](https://tio.run/##XZBRboMwDIbfc4ooNSs0KYLuhXVizQl6gD6AEEvXdZHWAduoAmdnDhTY9kt27N@fFcmX929VlCeldQdHGlPTgY6laQlkxUvZOOb16EK6DgPPgPYh5THUnAsO11bpUhmo4@CR2xZXdOPQr1Wzo/mqomv1QTddS4h0CRGuXJIkSYbYJ3ONsZQiFBvvRvlWNu/8ucaM1L0IR2phZfN@MdeY/1LnXuQsh2fo@u8m5BCRKLJeIILRQyM6/OOeJs3l9reL@EOPe7ShDjWEouCUXcsqy98EqPqi8ko945EhHYaFKj91hcYd3l6OaD9j4LLbnOEl2bTOvO24yEjb/QA "PowerShell – Try It Online") Takes a splatted string with LFs. Returns zero-indexed location x,y. Unrolled: ``` $locations=@{} # make a hashtable. key=char, value=location array $args|%{ if($_-10){ # if current char is not LF $locations.$_+=$x++,+$y # add $x,$y to hashtable value and move $x to next pos }else{ $x=0;++$y # move $x,$y to next line } } $locations|% Values|? Count -eq 2 # find and output location array with 2 elements (x,y) ``` [Answer] # [Scala](http://www.scala-lang.org/), 98 bytes Golfed version. [Try it online!](https://tio.run/##hZHBToQwEIbv@xST7qWN2oMnQsJGH2DxQLysiqlsWUugYNsQdd1nx6EB2SUhTgLlm/@fTunYTJSiq98KmTnYCqXhuALYyxwqBCrMwYZwb4z4ekqcUfrwwkJ41MpB5J0ArSjBSessZhL5QX0SgBCy7mNAgB@E@BLXc8QibrFNs8XGSl9Pe6VpOnkvIV5UZrC8e@FjMhd3M/axXL8LJm8QLPuCc99u5vMS8@@uH0BOqxAv9O/eo4o7I7Rtait5JRr6yl2dSMet@paMK72Xnw85vWVhWP2jx6rs@j5@bjyvjRTZOxw9Q7QZDtlPtsWp9llum1I5Sp41YaM8FtIGD@hKPQoDUoLfNxsgcIX/0jJcpvLTqn9Oq@4X) ``` def f(m:Seq[String])=m.transpose.map(_.toSet.size).indexOf(2)::m.map(_.toSet.size).indexOf(2)::Nil ``` Ungolfed version. Try it online! ``` object Main { def main(args: Array[String]): Unit = { val tests = Seq( """##### |###N# |##### |#####""".stripMargin, """^^^ |^^^ |^N^ |^^^ |^^^ |^^^""".stripMargin, """jjjjjj |j@jjjj |jjjjjj""".stripMargin, """Z8 |88""".stripMargin, """88 |8Z""".stripMargin ) val f: Seq[String] => Seq[Int] = m => m.transpose.map(_.toSet.size).indexOf(2) :: m.map(_.toSet.size).indexOf(2) :: Nil tests.foreach { test => val v = test.split("\n") v.foreach(println) println(" -> " + f(v) + "\n") } } } ``` [Answer] # [Julia](https://julialang.org), 78 bytes ``` s->(n=argmin(x->count(x,' 's),s);q=split(s);~=findlast;b=~(n.∈q);(n~q[b],b)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVAxDoJAEIztvuKiBXfJYQQtLpIjvoAHaCQBBQPBU7wjsaL2DzY0FD5JS18icooNiZPMzhYzO8le67TIkqC6iSjaZhHiqC5UbLK7J00XCx6cdvtE4LPpbg6FUPhMDTAkoZI4OZfHLFG4WUseJ2KbBVI5IS-xGD8vl5w4WJT5KlzTkBB99TEwABaBlNFJId2IYTh6Axp67Rx95hAI4hzhGbVJT8r3fWjpfVTzm7LptC-VtoB0oaXFL9JbtGTA2NdjUavPwxrP8s8dtwN02_y3ul3FpMnrf1WV1hc) This function takes input as a single string, which probably isn't the most efficient approach. The output is 1-indexed. -19 bytes thanks to MarcMush: add a newline to the haystack to guarantee that the needle is always the least frequent character, even in a 2x2 haystack. Interestingly, concatenating a character literal with a string variable doesn't require an operator in Julia. Apparently, it's parsed just like [numeric literal coefficients with variables](https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#man-numeric-literal-coefficients). This saves a byte here, which is the best thing to come out of [Julia's choice of concatenation operator](https://docs.julialang.org/en/v1/manual/faq/#Why-does-Julia-use-*-for-string-concatenation?-Why-not-or-something-else?). [Answer] # [Lua](https://www.lua.org/), 103 91 bytes ``` s,l=...s:gsub('.',load'c=...b=b or not s:find(c..c,1,1)and s:find(c,1,1)')print(b%l-1,b//l) ``` [Try it online!](https://tio.run/##RchBCoAgEADArwgRKmwrHroEfaE/uEoRLBpZ798oouY4fAaRCjwiYh2WepLRqIFLSDreSSOpsqtcDlWHec3JRMQIHrwNOX33hLbbvubDUMudB3KOrYg0r6n5SX8B "Lua – Try It Online") Ungolfed version: ``` s,l=... --Take in haystack and line width as args s:gsub('.',function (d) --For each character in s b=b or not s:find(c..c,1,1)and s:find(c,1,1) --If there is only one instance of c, store location end) print(b%l-1,b//l) --Print results ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) this can probably be golfed down a bit as there's a lot of register shenanigans i'm not a huge fan of. takes an array of a single string with a width ``` Ç║æ░·╝;J╕╤¢ⁿÿì< ``` [Try it online! (With test cases)](https://staxlang.xyz/#p=80ba91b0fabc3b4ab8d19bfc988d3c&i=%5B5,%22%23%23%23%23%23%23%23%23N%23%23%23%23%23%23%23%23%23%23%23%22%5D%0A%5B2,+%22Z888%22%5D%0A%5B2,+%22888Z%22%5D%0A%5B10,+%22%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3A%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%22%5D%0A%5B6,+%22jjjjjjj%40jjjjjjjjjj%22%5D%0A%5B3,+%22%5E%5E%5E%5E%5E%5E%5EN%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%22%5D&m=2) This is Packed Stax, which unpacks to the following: # [Stax](https://github.com/tomtheisen/stax), 17 bytes ``` Nc|!IYxhX%yx/2l|u ``` [Run and debug it](https://staxlang.xyz/#c=Nc%7C%21IYxhX%25yx%2F2l%7Cu&i=%5B5,%22%23%23%23%23%23%23%23%23N%23%23%23%23%23%23%23%23%23%23%23%22%5D%0A%5B2,+%22Z888%22%5D%0A%5B2,+%22888Z%22%5D%0A%5B10,+%22%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3A%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%22%5D%0A%5B6,+%22jjjjjjj%40jjjjjjjjjj%22%5D%0A%5B3,+%22%5E%5E%5E%5E%5E%5E%5EN%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%22%5D&m=2) ``` N # get the string c|! # get the rarest element I # get the first index in the string of this Y # store that in register Y xh # get the width X # and store this value in register x % # modulo with what was stored in register Y yx # register y and register x from above / # divide them 2l # create an array of the top two elements on the stack |u # and put it in a format which can be printed ``` [Answer] # [Python 3](https://docs.python.org/3/), 93 bytes ``` def f(s):x=s.find("\n")+1;return[(i%x,i//x)for i,c in enumerate(s)if s.count(c)<2and" "<c][0] ``` [Try it online!](https://tio.run/##TVBbCoMwEPzfUywpBUPFvn7EVukJPIBWQTShKW0sSQRL6dltYu1jYHZnmQR29nY3p1Zuh6FhHLmnadTHOuBCNh45SkIX651iplMy98S898Vy2VPeKhR@jUIik92Vqcow@1Nw1EHddtJ4Nd1vKtkQJPu6yFfFoI3SGGNOCJk5gGU61tlUreNblmUJI9Opvzm55xFwPrzbiMnKQgjDj84g@@jkC/iq6CcT@6QAcJG0C@QWjQAtbkrYJJr@DZykjDUXhkJjZfDh7vUM3JmGFw "Python 3 – Try It Online") Input is taken as a multiline string. Output is 0-indexed [Answer] # [Octave](https://www.gnu.org/software/octave/), 40 bytes ``` @(x){[r,c]=find(x-mode(+x(:))) [c,r]}{2} ``` Port of [@sundar's MATL answer](https://codegolf.stackexchange.com/a/179361/36398). Output is a two-element vector with 1-based column and row indices. [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCszq6SCc51jYtMy9Fo0I3Nz8lVUO7QsNKU1NTITpZpyi2ttqo9n@agq1CYl6xNVeaRrS6MgioWyuAGH4whjISI1bzPwA "Octave – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes ``` s`(?=(.)+\1)(.*?¶)*(.*)(?!\1|¶).+ $.3,$#2 ``` [Try it online!](https://tio.run/##K0otycxL/P@/OEHD3lZDT1M7xlBTQ0/L/tA2TS0gralhrxhjWAPk6WlzqegZ66goG/3/rwwCXEDsByaVoSQA "Retina 0.8.2 – Try It Online") 0-indexed. Explanation: ``` s` ``` Allow `.` to match newlines. This costs 3 bytes (3rd byte is the `?` before the `¶`) but saves 6 bytes. ``` (?=(.)+\1) ``` Look ahead for two identical characters. `\1` then becomes the hay. ``` (.*?¶)* ``` Count the number of newlines before the needle. ``` (.*) ``` Capture the hay to the left of the needle. ``` (?!\1|¶) ``` Ensure that the needle isn't hay or a newline. ``` .+ ``` Match the rest of the hay so that the result replaces it. ``` $.3,$#2 ``` Output the width of the left hay and the number of newlines. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 82 bytes ``` x=>w=>{int y=x.IndexOf(x.GroupBy(c=>c).Last(g=>g.Count()<2).Key);return(y%w,y/w);} ``` Thanks to dana for shaving off 6 bytes! [Try it online!](https://tio.run/##bYvbCsIwDIbvfQpRhARmPaEMtxZRUETRS8ELQWo3uosqXcdWxGef9YCC84OEJP8XnrZ5Kst5pniYGi1V7D1nqYwHj@YKGYtoWVCWU3Z1e93SgizVSRTbCAqy0OfsMrXAKeNI1sfUQExZTGbnTBnAsI9kJSwGWphMK7Ct3LOdHINbGdR2WhqxlkpABI3mm03zSwNhiPgjHl5sDh@cNqhoyYtJ8sFpo4q2933fBf1K4O77vwGrMv6O7qXXdT/lHQ "C# (Visual C# Interactive Compiler) – Try It Online") # Old solution, 106 bytes ``` n=>m=>{var z=n.Distinct();int d=n.IndexOf(n.Count(c=>c==z.First())>1?z.Last():z.First());return(d%m,d/m);} ``` Both take input as a string and an integer specifying the amount of columns. [Try it online!](https://tio.run/##bYtdC4IwFIbv@xWRBBuYfVGIthUUQSB1GXghyNRY4Am2GWH02@2UkYQ9sPHynucVeiC0rLYFiIU2SsLJfmcJxiavDx/lPGMVMJ4zfr/GqlsycDZSGwnCEOqj0k2w2kGS3g4ZAWd9KcAQwbhgrHS2Umn0KB8vSyeIX9lrWl@lplBAkn5uJ8Oc@o/K7xyVNGkgISUZ6Vkf9lZDj5IZbn/FqGYffUFt2tLONavzF9TmLS10XRcPk9YB@/DvgbfxmoiT8Qg31RM "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 74 bytes ``` h(char*s,z,x){for(s+=z--;*s==*--s|*s==s[-1];)z--;printf("%d,%d",z%x,z/x);} ``` [Try it online!](https://tio.run/##jZLbaoNAEEDf9ysWg7DaWeolinQx9AvyAQmxiDbV0JjgmiJav93uVhOwXug8LWfmzAzLRDT6DLOPtk1IlIS5zqGCUquPl5zwJ7@ilOnc93VK@bd88D01D0yT/JqnWXEkihqDGitQqSVUz6XGmhbLTpi/mfsD9nGtnH5DQXgYyul1hnf1DfubQffOVt85CIKxPg23/66cgw3DswvZ/UIrGWNdwO00Xs3ipXHrftzOG9uet6g6vepNqbtF1e3VzSPGLR6pl4Xc5j4Goa9LGuMz0errrZBjiGmIE0JI3BY@h2lGNFyjbouEiJMC0wNXE5chHNYxSzJ7yGywDHCGbA1rsIbIGSMXbAPkEqj7iPy9uOUZNhhq2h8 "C (clang) – Try It Online") DEGOLF ``` int h(char*s,int z,int x){// z = string size, x = row size for(s+=z--; // move pointer just over the end of the string // and move z counter to the end of string *s-*--s? ==> *s==*--s| @ceilingcat suggestion // if the previous element is different we will check if the next element is also different // if not the result is 1 and the iteration continue // in the first iteration it will be different because the pointer is just over the end *s-s[-1]? ==> changed to *s==s[-1] @ceilingcat suggestion // the second check returns 0 if the char changed again so it was the needle // if not it's because in the first iteration the first check finded a difference just because the pointer was just over the end /*0:1*/ :1;)z--; printf("%d,%d",z%x,z/x); } ``` [Answer] Java 8, 104 Bytes ``` (x,w)->{int i=0,p=x.length;for(;i<p;i++)if(x[i]!=x[(i+1)%p]&&x[i]!=x[(i+2)%p])break;return i/w+","+i%w;} ``` Input is array of char, and integer indicating row width. Output is zero-based, vertical then horizontal (i.e., row number then column number) Explanation: ``` (x,w)->{ int i=0, p=x.length; for (;i<p;i++) //iterate through characters in x if (x[i]!=x[(i+1)%p] && x[i]!=x[(i+2)%p]) //compare x[i] with the two subsequent characters in array, wrapping around if necessary break; return i/w+","+i%w;} //return row number then column number, zero-based ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~93~~ ~~89~~ ~~85~~ 58 bytes Complete rewrite taking input as `concatenated string, width`: ``` lambda g,w:divmod(g.index({g.count(c):c for c in g}[1]),w) ``` [Try it online!](https://tio.run/##ZY9NCoMwEIXXzSmGdJMUEVPpRvAk1sWYtDFYE1FbK6Vnt7FYQfpgZuCbH940Y186G09Vep5uWBcKQQdDosyjdorp0Fh1ebKXDqW7255Jnki4uhYkGAv6nYmcBwOfShy7HmXVQQoZYTRaJeZEAzjxwHNELHygB8cZAA3/tF@qnxHxd0tEG/2uAd1ysTRyQmaL5WxxNZaQXdMa/0LFDiXn0wc "Python 3 – Try It Online") --- Original answer: ``` def k(g):t=''.join(g);return divmod(t.index({t.count(c):c for c in t}[1]),len(g[0])) ``` EDIT: Saved 4 bytes by swapping linebreak/indent for semicolons. Saved another 4 bytes by using `divmod`(thanks @JonathanFrech). [Try it online!](https://tio.run/##dU9BDoIwEDzbV2zwQJuQhsYbhpc0HGoLUtGWQDES49uRVjAcdC8zuzObybSjq605TJMqK2jwmWQuj2N6sdrMy7Er3dAZUPp@swo7qo0qH/jpqLSDcViSTEJlO5CgDbgXZwVJruX8ytOCEDTVYuydkE0POXDEIUr9RCjZMhZYkSBvECLcxOkDYoVFptsJWmD79bLY2I@YdBuT/jEwbygQ8qVqX@rbIEO7ttNz6QbXhExv "Python 3 – Try It Online") I know this could be a lot shorter, but I just wanted to try an approach around this `dict` comprehension. ]
[Question] [ Write an algorithm or program that can encode and decode a chess board. The goal is to make the smallest representation of a chessboard that could be used (once decoded) to determine all movement possibilities for a player on that turn. The encoding must be able to show: * Whose turn it is. * Whether the player can castle on each side. * Whether the player can perform an en-passant, and if so, which of their pawns? * Positions of all pieces. **Important note on castling:** If white moves their king one turn, and then moves it back the next, it must be clear that they cannot castle on either side after that. Same would go if they moved their left or right rook. Although the board is visually in the same state as it was two turns ago, the game state has changed. More info here: <http://en.wikipedia.org/wiki/Chess#Castling> **Important note on en-passant:** This is also a turn-sensitive move. Read the rules for more info. <http://en.wikipedia.org/wiki/Chess#En_passant> Determine input and output as needed. Major props to whoever can compress it the most! Your score is determined worst-case scenario - maximum possible size in bits. Make sure you show how you calculated it that number and what you accounted for. Shoot for the smallest worst-case! [Answer] ## Min: 12 bitsMax: Avg: Had and thought last night that I could possibly make it even smaller. ``` x Colour to play next (0 -> Black, 1-> White) 1 Only King left? 00000 Position of White King (0 -> A1 ... 63 -> H8) 00000 Position of Black King 01 00000 11111 WK:A1, BK:H2 (Black to play) 11 00000 11111 WK:A1, BK:H2 (White to play) ``` The result is an impressive size of **12 bits**! So what about K +1 other type of piece? ``` x 0 0 000 +Pawn 001 +Rook 010 +Knight 011 +Bishop 100 +Queen ``` There 2 possible arrangement of the sub tree. ``` /\ /\ + K K + ``` Both result in the same bit sizes for all pieces. So it make no difference to which we use, I'll choose the first one. ``` x 0 0 000 1011001110000000000000000000000000000000000000000000000000000000000000 (+ 000) En-Passant (if >= 2 pawn & pawn in en-passant positions) (+ 00 ) Castlings (if >= 1 rook) Min: 75 bit Max: 109 bits ``` So on King +2 other piece types ``` x 0 1 PRBNQ 00011 +N +Q 00101 +B +Q 00110 +B +N 01001 +R +Q 01010 +R +N 01100 +R +B 10001 +P +Q 10010 +P +N 10100 +P +B 11000 +P +R ``` There are 5 possible sub trees (I'll use 1 and 2 to indicate which of the pieces.) ``` /\ /\ /\ /\ /\ / \ / \ / \ / \ / \ K /\ /\ 2 /\ \ 1 /\ /\ \ 1 2 K 1 K 2 1 K 2 1 2 K ``` So we'll require 3 bits to encode which sub tree to use. ``` x 0 1 PRBNQ 000 Sub Tree used Min:= 11 = Header 6 = 2 * 3 4 = 1 * 4 4 = 1 * 4 60 = 60 Empty -- 85 bits Max:= 11 = Header 4 = 2 * 4 Kings 48 = 16 * 3 Pawns 12 = 4 * 3 Rook 42 = 42 * 1 Empty 3 = 1 * 3 En-Passant 2 = 1 * 2 Castlings --- 122 bits ``` Still doing the analysis for more pieces +3 Other ``` x 0 1 PRBNQ 0000 Sub Tree used (of 14 possible) ``` +4 Other ``` x 0 1 PRBNQ 000000 Sub Tree used (of 42 possible) ``` +5 Other ``` x 0 1 PRBNQ 0000000 Sub Tree used (of 132 possible) (+000) (+00) ``` Max: 208? --- **Is it possible to encode all these sub-trees into 9bits?** If we total up all of the possible sub-trees we get 392 possible sub-trees. ``` 1 0 2 2 3 5 4 14 5 42 6 132 --- 392 <= 2^9 ``` --- **Using Freq ID** Since there 164603 [unique piece frequencies](https://chess.stackexchange.com/questions/4561/how-many-possible-combinations-for-the-number-of-pieces-on-the-board). ``` Log2( 164603) = 17.3286110452 ~ 18 bits 0 0000 0000 0000 0000 00 Freq ID ``` (+000) (+00) Castling Max:= 204 bits --- rev 3 Min: 82 Max: 199 Avg: 160 Finally got around doing some analysis to find the maximum bit size. With optimal huffman encoding for each of the [unique piece frequencies](https://chess.stackexchange.com/questions/4561/how-many-possible-combinations-for-the-number-of-pieces-on-the-board). ``` 0 Player 00 Castling 0 En-Passant Possible ?000 En-Passant column (include if En-Passant Possible = 1 0000 0000 0000 Tree Encoding ID [Board Encoding] Between 66 .. 180 bits ``` Note this is the worst possible size, which the En-Passant column bits if the number of pawns is greater than one. Irrespective of those pawns colours and position there is the potential for some boards to be 3 bits smaller. Also there are only **144** different sizes(Worst case) for the size of the board. --- 75 - 216 bits (v2) v1 The minimum size is 98 bits (12.25 bytes), only the two kings on the board. Maximum size is only 216 bits (27 bytes.) In the unlikly:- ``` 9 x Queens 1 x King 2 x Rooks 2 x Knights 2 x Bishops on each side. ``` On average the size will be around 157 bits (19.625 bytes). **Pieces** To encode the board I'm using a binary tree encoding scheme. An empty square is the most frequent from any where between 32 and 62 appearances. Next are the pawns, then Rooks, Knights, Bishops and the least frequent are the Queen and King. ``` 0 - left node 1 - righ node /\ e \ e:= Empty Square B/\W B:= Black ; W:= White / \ / \ / \ /\ /\ p \ p \ p:= Pawn /\ /\ / \ / \ /\ /\ /\ /\ r b n \ r b n \ r:= Rook; b:= Bishop; n:= Knight /\ /\ q k q k q:= Queen ; k:= King ``` The starting board can be encode in just 166 bits (20.75 bytes) ``` A B C D E F G H -----+-----+-----+------+------+-----+-----+------+ 10100 10101 10110 101110 101111 10110 10101 10100 | 8 100 100 100 100 100 100 100 100 | 7 0 0 0 0 0 0 0 0 | 6 0 0 0 0 0 0 0 0 | 5 0 0 0 0 0 0 0 0 | 4 0 0 0 0 0 0 0 0 | 3 110 110 110 110 110 110 110 110 | 2 11100 11101 11110 111110 111111 11110 11101 11100 | 1 ``` To indicate whom's move it takes only single bit ``` 0-> Black , 1-> White ``` Castling can be encoded in 4 bits. ``` B W LR LR 00 00 ``` So I've use 171 bits (21.375 bytes) En-Passe can be encoded into just 16 bits (2 bytes) So in total thats 187 bit (23.375 bytes). **Layout** ``` bits Encodes 0 - 15 En-Passe 16 - 19 Castling 20 Move 21 - 23 Unused 24 -> .. Board ``` Not written any code yet. Notice that 3 of the bits that are unused. So the max is **213bits**. --- **Possible Improvements** **1)** Reduced the header block form 24 to 8 bits (with @Peter Taylor suggestion) ``` 0 - 2 En-Passant 3 Move 4 - 7 Castling 8 ... Board Pieces ``` --- **2)** Variable length header A small 4 bit fixed header ``` 0 0 0 0 | | | | | | | +-> En-Passant Block Present? | | | | | +---> Pawns on board? | | | +-----> Castling still possible? | +-------> Who's move? 0-Black 1-White ``` Next block of additional bits (If castling is still possible) ``` 00 00 || || || |+-> White Castle Right || +--> White Castle Left || |+----> Black Castle Right +-----> Black Castle Left ``` Next block of additional bits (if pawns are present) ``` 000--> En-Passant column Position ``` So now I have a variable length header 4 - 11 bits --- **3)** Use a different encoding scheme depending on what pieces are left on the board. By changing the tree encoding depending on what pieces are on the board and there frequency. One possible encoding for an end game state (No Pawns) ``` /\ e /\ Black / \ White / \ / \ / \ /\ /\ / \ / \ / /\ / /\ /\ / /\ /\ / /\ r b n q k r b n q k ``` Which is about ~4 bits per piece. Which type of pieces are present on the board? ``` RBNQK Permutation 11111 (11111) ``` Permutation is Variable length 0-5 bits. If only one type of piece is left then don't include it. Which permutation of those pieces to use for the tree? This is the factorial of the number of pieces in the above example it is 5 pieces so 120 possible permutations that can be encoded. ``` # ! bit 6 720 10 (If pawn included) 5 120 6 4 24 5 3 6 3 2 2 1 Don't include as of equal size. 1 1 0 Don't include as its not needed. ``` Remember that there is addition bits for the empty squares and color. --- **Examples** Let's give an example of only QK left ``` RBNKQ 00011 /\ s \ /\ B/ \W /\ /\ q k q k 101 100 0 x 60 110 111 ==> 60 + (2 x 6) = 60 + 12 = 72 bits for the board 0000 00011 Header ==> 9 bits ``` **81 bits** total --- Let's give and example of only kings left ``` RBNQK 00001 /\ s k / \ B W 10 0 0 0 0 0 0 0 K... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 0 .... .... 0 0 0 0 0 0 0 11 .... ...k ``` Put all together ``` header 4 0 0 0 0 pieces 5 0 0 0 0 1 perm 0 - - - - - - board 66 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 ``` So I calculate the smallest encoding for board at **75bits** (9 bits 3 bit) Still yet to calculate how this coding scheme affects the maximum size. --- **Improvement 4** Reduce the number of bits for castling to just 2 bits. Just castling for the player who's turn it is. ``` 0 Castling possible (from header block) LR 00 ``` Thinking about it, it maybe better just to include the 2 bits inside the header block. [Answer] # 192 bits (worst case) Here's a very simple storage scheme that should cope with arbitrary pawn promotions, and never requires more than 64 + 4 × 32 = 192 bits: * The first 64 bits store a [bitboard](//en.wikipedia.org/wiki/Board_representation_%28chess%29#Bitboard) that tells *where* the pieces are (but not *what* they are). That is, we store one bit for each square of the chessboard (starting at square a1, then b1, c1, etc. up to square h8) such that a vacant square is represented by 0 and an occupied square by 1. * Next, for each of the squares marked as occupied on the bitboard, we store a 4-bit nibble encoding the piece on that square. The first of the four bits encodes the color of the piece (0 = white, 1 = black), while the remaining three bits encode the type of the piece: ``` +-----+-----+-----+-----+ |Black| Piece Type | +-----+-----+-----+-----+ 4 3 2 1 Bits ``` > > Piece Type > > > 0 = (normal) pawn > > 1 = (normal) rook > > 2 = knight > > 3 = bishop > > 4 = queen > > 5 = king (of player to move next) > > 6 = king (of the other player) > > > Note the two encodings for the king, used to determine which player's turn it is to move. (In fact, since there are always two kings on the board, allowing for four combinations of the codes 5 and 6, we could rather easily encode a second bit of information here.) ``` Black Type Description +----+----+--------------------------------+ | 0 | 5 | White King; White to move next | +----+----+--------------------------------+ | 0 | 6 | White King | +----+----+--------------------------------+ | 1 | 5 | Black King; Black to move next | +----+----+--------------------------------+ | 1 | 6 | Black King | +----+----+--------------------------------+ ``` To encode the extra information needed for the *en passant* and castling rules, we introduce one additional piece type, which denotes either a pawn or a rook depending on the row it appears on: > > 7 (on rows 1 and 8) = a rook that has never moved, and whose king has also never moved, and which is therefore eligible for castling > > 7 (on rows 4 and 5) = a pawn that has just advanced two squares, and may therefore be captured *en passant* > > > Putting it all together: ``` Hex Description +---+---------------------------------------------+ | 0 | White Pawn (normal) | | 1 | White Rook (has moved) | | 2 | White Knight | | 3 | White Bishop | | 4 | White Queen | | 5 | White King; White to move next | | 6 | White King | | 7 | White Rook (pre castle) / Pawn (en Passant) | | 8 | Black Pawn (normal) | | 9 | Black Rook (has moved) | | A | Black Knight | | B | Black Bishop | | C | Black Queen | | D | Black King; Black to move next | | E | Black King | | F | Black Rook (pre castle) / Pawn (en Passant) | +---+---------------------------------------------+ ``` The total number of bits required to encode the state of the board is therefore 64 + 4 × # of pieces on board. Since there can never be more than 32 pieces on the board, the maximum length of this encoding is 192 bits. For example, using the encoding described above, the initial state of the board would be encoded as (whitespace inserted for readability): ``` 1111 1111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 0111 0010 0011 0100 0101 0011 0010 0111 0000 0000 0000 0000 0000 0000 0000 0000 1000 1000 1000 1000 1000 1000 1000 1000 1111 1010 1011 1100 1110 1011 1010 1111 ``` or, in hexadecimal: ``` FFFF 0000 0000 FFFF 7234 5327 0000 0000 8888 8888 FABC EBAF ``` [Answer] # 160 bits worst case After posting my previous answer 22 bytes, I began to wonder if we could get down to 21 bytes. However when I saw Peter Taylor's amazing 166 bytes I thought "Hang on, it looks like five 32-bit words could be possible!" So after quite a lot of thought, I came up with this: 159.91936391 bytes (a pretty tight fit!) This level of compression would need a fairly complicated program but I have thought about how to make it run in reasonable time. This is going to be a long post, so please bear with me, I will post what I can today and add a few bits of code soon. So, here's how to do it: **En Passant and castling encoded by illegal positions (0 bits)** **En Passant** As mentioned in other answers, there are a maximum of 5 possible squares on which a pawn vulnerable to en passant can stand. These are the squares next to the pawns of the player whose turn it is. To encode this, the pawn vulnerable to en passant is exchanged with whatever is on one of the squares in the first or last row. This may be either a man or an empty square. This produces an illegal position, as pawns cannot be on these rows. The decoder must return the pawn to its correct position, extracting the en passant information. In order for this to not interfere with the castling encoding, it is important that the squares on which the kings stand at the start of the game are not disturbed, and that the en passant encoding procedure does not place the kings next to each other, which would be an illegal king position. To satisfy the second of these points, the encoder has two choices as to which square it exchanges the en passant pawn. First choice square for each of the up to 5 pawns are A8,B8,C8,G8,H8. Second choice: A1,B1,C1,G1,H1. **Castling** A king who is allowed to castle is by definition, still on his initial square. With the white king on his initial square, there are a total of 63 squares where the black king can stand, 58 of which are legal (he is not allowed to move right next to the white king because he would put himself in check.) If the white king is allowed to castle, he is either allowed to castle with his left rook, his right rook, or both. There are thus 3x58=174 possibilities where the white king can castle, another 174 where the black king can castle, and a further 3x3=9 where both can castle, a total of 357. There are 420 illegal arrangements of the two kings where they are on adjacent squares: 3x4=12 when the white king is in the corner, 5x24=120 when he is on the edge, and 8x36=288 when he is on another square. Therefore there are easily enough illegal positions to encode all possible castling possibilities. If at least one king is allowed to castle, encoder would look up the castling data and the positional data of those kings not allowed to castle in a table (or alternatively, use an algorithm which I won't specify here) and produce an illegal position of the two kings. It would then exchange the kings with whatever happened to be on these squares. It is important that this is encoded after and decoded before the en passant, otherwise there are some potential interferences. **Comparison** So, so far I have used no bits! Looking at Peter's answer, I still have the following to encode: > > > ``` > Whose turn is it? 1.000 bits > Which squares are occupied by men of which colour? 91.552 bits > Subtotal *92.552 bits* > For the two colours, which men and which order? *68.613 bits* > GRAND TOTAL 161.165 bits > > ``` > > This is for the worst case of 29 men (see Peter's answer.) Below I will show how I make a marginal improvement (at least for the case of 29 men) on both of the points marked in \*\*. **Which squares are occupied / whose turn is it?** The easy way to encode which squares are occupied is with a 64 bit grid. This also tells us how many squares are occupied. However it is somewhat wasteful because it is not possible for there to be more than 32 squares occupied. My solution is to use 1's to encode for the occupied squares when it is White's turn and 0's to encode for occupied squares when it is Black's turn. Now all combinations are used and there is no waste. Thus we save on a bit for storing the turn: less than 32 1's, it is white's turn, more than 32 1's, it is black's turn. The only ambiguous case is when all the men are on the board and there are 32 1's and 32 0's. Therefore an extra bit is needed for this case only. As there can be no promotions until a capture has occurred, this extra bit does not affect the worst case overall (which occurs with 3 men captured and 29 remaining.) **Colour of the men occupying the squares** We know from the above how many men there are. The following extract of Pascal's triangle tells how many possibilities there are for the different distributions of black and white. For example, for 3 men, the possibilities are: 3 black men (1 permutation) 2 black, 1 white, (3 permutations), 1 black, 2 white (3 permutations), 3 white (1 permutation.) The total is 23=8. In general, for the lower numbers of men there are 2n possibilities. However the all black and all white possibilities are illegal (at least the king of each side must be on the board) so the actual number of legal permutations is 2n-2 (ignore the 1's on the Pascals triangle.) For more than 16 total men, there is an additional constraint in that there can be no more than 16 men of each colour on the board. Therefore when all 32 men are on the board there must be 16 of each and the total number possibilities is 601080390 which is quite a bit less than 232. ``` 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 1 4 10 20 35 56 84 120 165 220 286 364 455 560 680 816 969 1 5 15 35 70 126 210 330 495 715 1001 1365 1820 2380 3060 3876 4845 1 6 21 56 126 252 462 792 1287 2002 3003 4368 6188 8568 11628 15504 20349 1 7 28 84 210 462 924 1716 3003 5005 8008 12376 18564 27132 38760 54264 74613 1 8 36 120 330 792 1716 3432 6435 11440 19448 31824 50388 77520 116280 170544 245157 1 9 45 165 495 1287 3003 6435 12870 24310 43758 75582 125970 203490 319770 490314 735471 1 10 55 220 715 2002 5005 11440 24310 48620 92378 167960 293930 497420 817190 1307504 2042975 1 11 66 286 1001 3003 8008 19448 43758 92378 184756 352716 646646 1144066 1961256 3268760 5311735 1 12 78 364 1365 4368 12376 31824 75582 167960 352716 705432 1352078 2496144 4457400 7726160 13037895 1 13 91 455 1820 6188 18564 50388 125970 293930 646646 1352078 2704156 5200300 9657700 17383860 30421755 1 14 105 560 2380 8568 27132 77520 203490 497420 1144066 2496144 5200300 10400600 20058300 37442160 67863915 1 15 120 680 3060 11628 38760 116280 319770 817190 1961256 4457400 9657700 20058300 40116600 77558760 145422675 1 16 136 816 3876 15504 54264 170544 490314 1307504 3268760 7726160 17383860 37442160 77558760 155117520 300540195 1 17 153 969 4845 20349 74613 245157 735471 2042975 5311735 13037895 30421755 67863915 145422675 300540195 601080390 ``` The number of possibilities can be found by summing the "rows" of this extract of pascals's triangle (by which I mean the NE-SW diagonals of the table , because I rotated the triangle 45 degrees anticlockwise for convenient presentation. The number of bits needed to encode the turn, occupied squares and colour of the men is therefore as follows: Up to 25 men: slightly less than 64+(number of men) For more than 25 men: ``` men permutations bits required occupied sq+turn of colours (bits required) total bits 26 55791790 25.7335495 64 89.7335495 27 100960110 26.58921015 64 90.58921015 28 175844430 27.3897244 64 91.3897244 29 290845350 28.115677 64 92.115677 30 445962870 28.73234836 64 92.73234836 31 601080390 29.16298271 64 93.16298271 32 601080390 29.16298271 65 94.16298271 ``` **For the two colours, which men and in which order?** As per previous answers, no pawns can be promoted until a capture has occurred, because each pawn is blocked by a pawn of the opposite colour on the same column. Peter's answer considered (as an upper bound) that every capture could lead to one promotion for the side being captured and two for the side capturing. However we can split this into several cases: 1. Black pawn captures white pawn: Now the capturing pawn is free to promote as he is now on a different column. His colleague on the same column can also promote. The black pawn on the white pawn's original column can also promote. This is the only case that permits 3 promotions. 2. Black pawn goes past white pawn on adjacent column and then captures white piece (other than pawn) behind. This enables the capturing pawn and the white pawn who was on the original column to promote. One promotion for each side. 3. White pawn is captured by piece (other than pawn.) This would normally allow one promotion for Black only. The only exception is when it liberates a blocked up pawn formation which was already caused by several captures moving pawns onto the same column. So, as a base case, we can consider that each capture permits one promotion each for both sides. In the case that the man captured is a pawn, there may be an additional promotion for the capturing side. I have written a program similar to Peter's. It is somewhat cruder, but it has an important addition: it can calculate the number of permutations possible when a player starts with less than the normal 8 pawns. Here is some data produced by the program: ``` Max promotions 0 1 2 3 4 5 8 PAWNS 13 men 18725850 146911050 567991710 1373480394 2297173164 2902775304 14 men 36756720 339459120 1555313760 4501448952 9021804792 13325103792 15 men 60810750 660810150 3555401850 12144582450 28834205400 50030580600 16 men 64864800 843242400 5383778400 21810428640 61514893440 1.26476E+11 7 PAWNS 13 men 17760600 141003720 546949260 1321302840 2200401060 2761730400 14 men 30270240 287567280 1331890560 3852728880 7641553920 11068817760 15 men 32432400 372972600 2075673600 7209001800 17135118000 29315286000 6PAWNS 13 men 14054040 114594480 447026580 1069488420 1739577840 2113185360 14 men 15135120 151351200 718918200 2087805720 4073028960 5697051360 5 PAWNS 13 men 6486480 55135080 217297080 510630120 794233440 910235040 ``` We can see that for a case like 8 pawns, 15 men, 0 promotions, the number of permutations is only slightly less than for 8 pawns 16 men, 0 promotions. However if we consider a case like 7 pawns, 15 men, 0 promotions (which is the same as considering that the man captured was definitely a pawn) we get about half the number of permutations. So, For the case when Black has 16 men and white has 15 men, we can consider an upper bound estimate of 2 promotions for Black and one promotion for White: ``` 5383778400 x 660810150 = 3.55766E+18 possibilities ``` However we can do better if we proceed as follows. A. Consider one promotion each for Black and White assuming that the man White has lost could be of any type: ``` 843242400 x 660810150 = 5.57223E+17 possibilities ``` B. Consider the additional possibilities for Black if he has two promotions, multiplied by only those possibilities for White in which he has lost a pawn. ``` (5383778400-843242400) x 372972600 = 1.6935 E+18 possibilities. ``` Adding these two together we get 2.25072E+18, which is a smaller number than 3.55766E+18. All the possibilities for up to 3 captures (29 men remaining) are listed below. ``` (Promotions, Pawns lost) possibilities BLACK 16 MEN, WHITE 15 MEN. ESTIMATE 3.55766E+18 = 2^61.62563249 (1,0) 843242400 x (1,0) 660810150 = 5.57223E+17 (2,0) 4540536000 x (1,1) 372972600 = 1.6935 E+18 TOTAL 2.25072E+18 = 2^60.96509144 BLACK 16 MEN, WHITE 14 MEN. ESTIMATE 9.5675 E+19 = 2^66.3747752 (2,0) 5383778400 x (2,0) 1555313760 = 8.37346E+18 (3,0) 16426650240 x (2,1) 1331890560 = 2.18785E+19 (4,0) 39704464800 x (2,2) 718918200 = 2.85443E+19 TOTAL 5.87962E+19 = 2^65.67235739 BLACK 16 MEN, WHITE 13 MEN. ESTIMATE 2.69447E+20 = 2^67.86856193 (3,0) 21810428640 x (3,0) 1373480394 = 2.99562E+19 (4,0) 39704464800 x (3,1) 1321302840 = 5.24616E+19 (5,0) 64960896000 x (3,2) 1069488420 = 6.94749E+19 (6,0) 69702272640 x (3,3) 510630120 = 3.55921E+19 TOTAL 1.87485E+20 = 2^67.34533572 BLACK 15 MEN, WHITE 15 MEN. ESTIMATE 1.47491E+20 = 2^66.99918768 (2,0) 3555401850 x (2,0) 3555401850 = 1.26409E+19 (2,1) 2075673600 x (3,0) 8589180600 = 1.78283E+19 (3,0) 8589180600 x (2,1) 2075673600 = 1.78283E+19 (3,1) 5133328200 x (3,1) 5133328200 = 2.63511E+19 TOTAL BOTH COLUMNS 7.46486E+19 = 2^66.01674923 BLACK 15 MEN, WHITE 14 MEN. ESTIMATE 4.51366E+20 = 2^68.61286007 (3,0) 12144582450 x (3,0) 4501448952 = 5.46682E+19 (3,1) 7209001800 x (4,0) 4520355840 = 3.25873E+19 (4,0) 16689622950 x (3,1) 3852728880 = 6.43006E+19 (4,1) 9926116200 x (4,1) 3788825040 = 3.76083E+19 (5,0) 21196375200 x (3,2) 2087805720 = 4.42539E+19 (5,1) 12180168000 x (4,2) 1985223240 = 2.41804E+19 TOTAL BOTH COLUMNS 2.57599E+20 = 2^67.80368692 ``` So for the worst case of one side with 15 men and the other with 14 men, we need 67.804 bits. Adding this to the 92.116 bits required to specify which squares and which colour, we get a total of **67.804+92.116=159.92 bits.** [Answer] # 177 bits worst case This algoritm, while hardly simple, gives a 177 bits worst case (184b=23B in practice), 13b (16b=2B) best case scenario when there's just 2 kings left. ``` Bit Description 1 Turn (0=white 1=black) 2- 7 White king position (2-4=letter, 5-7=number) 8- 13 Black king position (8-10=letter, 11-13=number) 14- 75 Which squares contain pieces (skipping the 2 king squares, so only 62) Ordered a1-h1,a2-h2,(...) 76-105 Which color owns the square with their piece (0=white, 1=black) If there's LESS than 30 pieces (apart from kings), this area is smaller 106-end Square data Square data has the following system: Every square gets assigned a number which determines piece. Number is: 0 Queen 1 Rook 2 Bishop 3 Knight 4 Pawn OR allowed-castle rook depending on square 5 Pawn subject to potential enpassant The first bits (max 13) is the potential enpassant slots from A-H, determined from data of 1 + 14-105 for which of the squares has a piece, and which color owns the piece and whose turn it is. For example, if turn is White (bit 1 is 0), all pieces on row 5 which is Black owned (determined from 14-105 metadata) and has at least 1 adjacant (on the same row) square owned by White, is explained in A-H order. A base 6 number is used which is converted to binary for the storage. On reading, it's converted and read A-H according to the numbers above (4 is obviously pawn in this case). The second amount of bits takes care of the 1st and 8th row (not corners!) in b1-g1,b8-g8. These only take up 2 bits since 4 or 5 is never needed (pawn on 1st or 8th is invalid). The third amount of bits takes care of the rest of the board, in the following order: a1,h1,a2-h2,a3-h3,a4-h4,a5-h5,a6-h6,a7-h7,a8,h8 (skipping the "enpassant" slots), in base 5 (since piece ID 0-4 are the only used) converted to binary. Best case: 13 bits (bit 1 for turn, bit 2-12 for kings) Worst case: 177 bits * 32 pieces with kings * 5 viable enpassant pawns * No pieces at 1st or 8th row (except if kings+rooks are at initial posions whether or not they can castle) In this case, the space as following: 1 bit turn + 12 bits king positions + 62 bits which squares have pieces + 30 bits color of pieces + 13 bits enpassant area + 0 bits initial rows area + 59 bits the rest of the area = 177 bits total Potential optimizations but not really worth it IMO: * Decrease average by make corners 2 bits as well if kings aren't at e1/e8 * Alter reading order to read b1-g1,b8-g8 last - decreases worst case to 176 bits if the "which squares have pieces" area is cut off if 30 existing pieces has been defined already. Would actually save 8 bits on file but meh ``` [Answer] ## 166 bits * `1` bit: whose turn is it? * `2` bits: which castling options are open? (NB on close reading of the question, it's only necessary to record castling options for the player whose turn it is). * `lg 6 ~= 2.585` bits: which *en passant* options are open? (See my other answer) * `lg sum_{i=1}^{16} sum_{j=1}^{16} 64! / (i! j! (64-i-j)! = lg 3629590441720924477681996172 ~= 91.552` bits: which squares are occupied by men of which colour? * At worst `lg 451366131803622235200 ~= 68.613` bits to indicate which men and in which order (see below) Using arithmetic encoding (since at each step we're applying a uniform distribution) we can achieve `ceil(3 + 2.585 + 91.552 + 68.613) = 166` bits. The encoding for the men: given that we know how many men of a given colour there are, we can easily enumerate all possible distributions/multisets of men (e.g. with 5 men we might have one King, one Queen, two Rooks, and a Pawn) and then we can consider all possible permutations of each distribution. However, we can do even better by taking into account interdependencies. I'm only doing this on a very basic level: how many possible promotions? A pawn can only become "passed" and able to promote in three ways: it captures and so moves into a different column; or its opposing pawn captures and so moves into a different column; or its opposing pawn is captured. Thus a capture for white potentially creates two passed pawns for white and one for black. We can build up a partial table of the upper bounds on promotions: ``` (Max white promos, max black promos): White men 16 15 14 13 Black men 16 (0, 0) (1, 2) (2, 4) (3, 6) 15 (2, 1) (3, 3) (4, 5) (5, 7) 14 (4, 2) (5, 4) (6, 6) (7, 8) 13 (6, 3) (7, 5) (8, 7) (8, 8) ``` We can also calculate the number of permutations given that a player has `N` men and no more than `P` promoted pawns: ``` Num of permutations (cumulative): max promotions: 0 1 2 3 4 5 6 7 8 1 men 1 1 1 1 1 1 1 1 1 2 men 10 10 10 10 10 10 10 10 10 3 men 72 75 75 75 75 75 75 75 75 4 men 436 496 500 500 500 500 500 500 500 5 men 2305 3025 3120 3125 3125 3125 3125 3125 3125 6 men 10746 17106 18606 18744 18750 18750 18750 18750 18750 7 men 44170 88795 106260 109179 109368 109375 109375 109375 109375 8 men 159832 415360 575240 619200 624744 624992 625000 625000 625000 9 men 509841 1721961 2884815 3398769 3504735 3515301 3515616 3515625 3515625 10 men 1447200 6258240 13063080 17697780 19260180 19510320 19530840 19531230 19531240 11 men 3706065 20021265 52183395 85007571 102173181 106786581 107369592 107409918 107410281 12 men 8678340 57101220 183088620 364510476 509818716 570620556 584017632 585352152 585430164 13 men 18725850 146911050 567991710 1373480394 2297173164 2902775304 3107861328 3143928216 3146014014 14 men 36756720 339459120 1555313760 4501448952 9021804792 13325103792 15664512864 16283899632 16360920576 15 men 60810750 660810150 3555401850 12144582450 28834205400 50030580600 66655789200 73588394880 74576231730 16 men 64864800 843242400 5383778400 21810428640 61514893440 126475789440 196178062080 240747386880 253686232800 ``` Combining the two, we can get the number of bits of required to specify both permutations given the numbers of men on both sides: ``` White men 16 15 14 13 <13 Black men 16 51.902 61.626 66.375 67.868 <=67.009 15 -- 67.000 68.613 67.534 <=65.243 14 -- -- 67.734 65.480 <=63.055 13 -- -- -- 63.102 <=60.676 ``` If it's not in this section of the table, we can just assume that both sides have up to 8 promotions and we're still doing better than the worst case, which is 68.613 bits when one has 14 men and the other has 15 men. Note that this is still a long way from being a perfect representation, because it allows many many illegal positions. Code for calculating the permutation table: ``` import java.util.*; public class ChessCombinatorics { public static void main(String[] args) { long[] f = new long[17]; f[0] = 1; for (int i = 1; i < 17; i++) f[i] = i * f[i-1]; // Indexed by num promotions, then total num men. long[][] distribs = new long[9][17]; long[][] perms = new long[9][17]; for (int promotedPawns = 0; promotedPawns < 9; promotedPawns++) { Map<Integer, Map<String, Long>> numCases = new HashMap<Integer, Map<String, Long>>(); for (int i = 1; i < 17; i++) numCases.put(i, new HashMap<String, Long>()); for (int extraQ = 0; extraQ <= promotedPawns; extraQ++) { for (int extraR = 0; extraR + extraQ <= promotedPawns; extraR++) { for (int extraN = 0; extraN + extraR + extraQ <= promotedPawns; extraN++) { int extraB = promotedPawns - extraN - extraR - extraQ; int unpromotedPawns = 8 - promotedPawns; // Promoted pawns should only count towards their new type if the existing ones are alive. // Otherwise we double-count some cases. int minQ, maxQ, minR, maxR, minN, maxN, minB, maxB; if (extraQ == 0) {minQ = 0; maxQ = 1;} else {minQ = maxQ = 1 + extraQ;} if (extraR == 0) {minR = 0; maxR = 2;} else {minR = maxR = 2 + extraR;} if (extraN == 0) {minN = 0; maxN = 2;} else {minN = maxN = 2 + extraN;} if (extraB == 0) {minB = 0; maxB = 2;} else {minB = maxB = 2 + extraB;} for (int numQ = minQ; numQ <= maxQ; numQ++) { for (int numR = minR; numR <= maxR; numR++) { for (int numN = minN; numN <= maxN; numN++) { for (int numB = minB; numB <= maxB; numB++) { for (int numP = 0; numP <= unpromotedPawns; numP++) { // The number of possibilities at these values is (numK + numQ + numR + numN + numB + numP)! / (numK! numQ! numR! numN! numB! numP!) numCases.get(1+numQ+numR+numN+numB+numP).put(numQ+","+numR+","+numN+","+numB+","+numP, f[1 + numQ + numR + numN + numB + numP] / f[numQ] / f[numR] / f[numN] / f[numB] / f[numP]); } } } } } } } } for (int numMen = 1; numMen < 17; numMen++) { distribs[promotedPawns][numMen] = numCases.get(numMen).size(); if (distribs[promotedPawns][numMen] > 0) { for (Long l : numCases.get(numMen).values()) perms[promotedPawns][numMen] += l; } } } System.out.println("Num of permutations (cumulative):"); System.out.println(" max promotions: 0 1 2 3 4 5 6 7 8"); for (int numMen = 1; numMen < 17; numMen++) { System.out.print(String.format("%2d men", numMen)); long cumul = 0; for (int promotedPawns = 0; promotedPawns < 9; promotedPawns++) { cumul += perms[promotedPawns][numMen]; System.out.print(String.format("%15d", cumul)); } System.out.println(); } System.out.println("Entropy of permutations:"); System.out.println(" max promotions: 0 1 2 3 4 5 6 7 8"); for (int numMen = 1; numMen < 17; numMen++) { System.out.print(String.format("%2d men", numMen)); long cumul = 0; for (int promotedPawns = 0; promotedPawns < 9; promotedPawns++) { cumul += perms[promotedPawns][numMen]; System.out.print(String.format(" %6.3f", Math.log(cumul) / Math.log(2))); } System.out.println(); } } } ``` [Answer] **178 bits (174 at a pinch!) worst case** Hi, just getting back into coding, which I haven't really done since college. I saw this site and thought this looked interesting. I did a little theroretical check and it appears at least 146 bits are needed for a perfect algorithm, probably quite a few more (I will explain in the comments when I have a moment.) **Anyway, this is the way I structure the data. The basic concept comes in at 178 bits, but with some jiggery pokery it can brought down to 174 (that's 21 3/4 bytes). 175 is slight easier to program, is more human readable, and still within 22 bytes.** **A)** Position of both kings: 6 bits each for white and black **12 BITS** **B)** Of the remaining 62 squares, which are occupied? A matrix of **62 BITS** **C)** Whose turn is it? **1 BIT** **TOTAL SO FAR: 75 BITS** **D) En Passant.** If it is white’s turn to move, up to 5 black pawns may look like they could be captured En Passant. The black pawn has to be on row 5 (from bottom to top starting at zero), and have a white pawn next to it. One situation with maximum number of possible captures looks like this: B W B B W B B W If there were 6 black pawns on row 5, white would only have 2 squares to stand on and could only threaten 4 black pawns, so it is not possible to have more than 5 black pawns apparently under threat from En passant at the same time. So we need **a number 1 to 5** indicating which of the (up to 5) pawns on row 5 that has a hostile (in this case white) pawn next to it was advanced 2 squares on the last turn (**or, zero** if no pawn in this situation was moved in this way on the last turn.) **E) Of the up to 30 occupied squares (not including kings) what do they contain?** There are 10 possibilities, each represented by a decimal number. The least significant bit represents the colour. Hence even numbers are white, odd numbers are black. White/Black Pawn 0/1 (or Rook that is allowed to castle\*) Knight 2/3 Bishop 4/5 Rook 6/7 Queen 8/9 \*A rook that is allowed to castle (and therefore has never been moved from the first or last row) is represented by 0 or 1 instead of 6 or 7. It cannot be confused with a pawn, because pawns cannot be found on the first or last row. **This gives a decimal number of up to 30 digits, which we can multiply by 6 and then add the code for En passant. The resulting number will fit into 103 bits, which when added to the 75 mentioned above is 103+75=178 bits**. Actually, if we simply multiply by 10 instead of 6, it makes no difference to the number of bits used, and decoding is easier. **This is just 2 bits more than 22 bytes. However we can push it down to 174 bits, as explained below.** **If no piece has been captured, then it is impossible for a pawn to be promoted**. The proof is as follows. Imagine white is obsessed with promoting his pawn on (for example) column E, from the very start of the game. There is a black pawn opposite this pawn that is in the way. Therefore to promote this pawn, one of the following must happen: 1) The black pawn is captured. 2) The black pawn captures another piece and therefore moves out of the way. 3) the white pawn captures a pawn on an adjacent column such as column D. 4) the white pawn passes (or is passed by) a black pawn on an adjacent column and then captures a piece on that same adjacent column, causing the white pawn to change column. Case 4 is the most interesting, because it is not just the white pawn that started on column E that now has a clear path to promotion. The black pawn on column that remains on column E can also promote. Therefore a single capture can clear the way for one pawn of each colour to promote. **Anyway, the fact that no pawn can promote until a piece is captured means that we do not have to store the 30th piece. We can work it out by elimination (or by subtraction, because the complete set of piece codes at the start of the game always adds up to the same amount =80.)** One minor point is that we must ensure that the squares where the rooks stand at the start of the game are amongst the first scanned (because if they were last, we would not know if the rook could castle or not.) This is easily done by scanning row 0 and then rows 7 to 1: For r= 8 to 1 scan row [r mod 8]. **So, the matrix of bits in (B) will tell us how many pieces there are (excluding kings.) If there are a full 30, ignore the last piece when encoding, the decoder will work out what it was. We now have an up to 29 digit decimal number, which we multiply by 6 and add to the En Passant code. The resulting number will just squeeze into 99 bits, giving a total of 99+75=174 bits.** As an example Here’s an actual position. White has just made his first move (advanced king’s pawn) and it is Black`s turn. ``` rnbqkbnr pppppppp P PPPP PPP RNBQKBNR ``` A) Position of kings **(White / Black in octal, 12 bits**): 03 73 = 000011 111011 B) Which squares are occupied? Start with row zero (bottom row) then all other rows from top to bottom, skipping the kings: ``` 1111 111 1111 111 11111111 00000000 00000000 00001000 00000000 11110111 ``` C) Black’s turn: **Turn Bit = 1** D) **En Passant. There is no white pawn next to next to a black pawn, therefore there is no pawn that can be taken en passant (even though this pawn did advance last move) so D=0.** If, instead of considering only pawns which have a hostile pawn beside them, we consider all pawns that do not have friendly pieces beside them on both sides, then D would be 1, as there is one such pawn in this situation, and this particular pawn was indeed moved in the last turn. E) Again, bottom row first, then all other rows from top to bottom, skipping the kings, and with the four uncastled rooks referred to as 0 or 1 (numbers normally reserved for pawns.) ``` RNBQ BNR = 0248 420 rnbq bnr = 1359 531 pppppppp = 11111111 PPPPPPPP = (0)0000000 ``` The 30th digit (in brackets) can be discarded. Though it is not very apparent here, the pawn that White has advanced is actually at one end of the list of pawns, because we scan row by row. Our data now looks like this, with 29 codes for the content of squares, plus the En Passant code: ``` (0 discarded) 0000000 11111111 1359531 0248420 (0 en passant) ``` It is best to scan from right to left when decoding and from left to right (reverse order) when encoding. This means that when there are fewer pieces we will have a smaller number, while retaining maximum consistency (i.e we want the blank space / zeroes to be leading, not trailing, to enable compression of sparsely occupied boards.) **When we have only 2 kings on the board, we will have the 75 bits mentioned above, plus 3 bits to store en passant data = 78 bits in the best case. Each additional piece comes in slightly under 3.5 bits (2 pieces can be stored in 7 bits, because 100<128.)** There is a practical problem in that a 99 bit integer is too big to fit in a 64 bit integer variable, which means many programming languages do not provide support for it (you can't simply convert a string representation of a 29-30 digit number into an integer.) **As an easy way of encoding for 22 bytes, we can break a 30 digit number (29 piece codes + en passant code) into two 15 digit numbers each of which will fit in 50 bits each (total 100 bits plus the 75 mentioned above makes 175 bits worst case.)** **For maximum compression, as stated above, 29 decimal digits plus the En Passant code (6 possible values), will just about fit into 99 bits (for a total of 174 bits)** but without support from the language for integers of this size it is complicated to program. It may be easier to separate out the 29 colour bits and work with the piece-type codes (5 possibilities) and En passant code (6 possibilities) separately from the colours (70 bits, almost fits into a 64 bit variable.) [Answer] # ~~256~~ 242 bits Here's a basic compression algorithm that can probably be improved on because it doesn't exclude certain illegal positions from being represented. The board starts with 5 bits of header info, as follows: ``` 0 1 1 1 1 --------- 1 2 3 4 5 1: Turn (black = 1, white = 0) 2: Black can castle queen-side 3: Black can castle king-side 4: White can castle queen-side 5: White can castle king-side ``` Then, a string of 12 bits representing the positions of the kings. ``` 0 0 0 1 0 0 1 1 1 1 0 0 ----------------------- 0 0 0 0 0 0 0 0 0 1 1 1 1 2 3 4 5 6 7 8 9 0 1 2 01 - 03: white king's rank 04 - 06: white king's file 07 - 09: white king's rank 10 - 12: white king's file ``` Then, a huge 64-digit number in base 11, which is then multiplied by 9 to add another digit at the end representing the state of en-passant. Each digit in base 11 represents a square on the board, with the following possible values: ``` 0: empty 1: white pawn 2: white knight 3: white bishop 4: white rook 5: white queen For the black equivalent of each white piece, add 5. ``` And the digits in base 9: ``` 0: no en-passant possible 1 - 8: en-passant on rank 1 - 8 ``` 1164 × 9 is about 2224.57, which requires 225 bits to encode. Plus the 17 header bits at the top, is 242 bits total. --- Thanks to ugoren for the improvements. [Answer] # Here is a full solution, actual worst case 181 bits **The focus here is a simple program you can easily understand** Input is FEN, here is opening position, it has six fields (5 & 6 ignored): > > rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 > > > ## First field (piece placement) [is parsed](http://phor.net/apps/fen2html/) ``` perl -pe 's/\d/"_"x$&/ge;s/\s.*//;s|/||g' ``` To produce: > > rnbqkbnrpppppppp\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_PPPPPPPPRNBQKBNR > > > Field one: encode the location of kings (12 bits): ``` printf("%b",index('k',$_)) printf("%b",index('K',$_)) ``` Field two: encode pieces (up to 5 bits per piece): ``` s/_/0/g Blank s/P/100/g From here, as normal chess meaning s/p/101/g s/Q/11000/g s/q/11001/g s/R/11010/g s/r/11011/g s/B/11100/g s/b/11101/g s/N/11110/g s/n/11111/g s/K// s/k// ``` ## Field three: active color (1 bit) ``` s/w/0/ s/b/1/ ``` ## Field four: castling availability (4 bits) ``` m/K/?1:0 m/k/?1:0 m/Q/?1:0 m/q/?1:0 ``` * [FIQ shows](https://codegolf.stackexchange.com/a/19449/16314) this field could be removed altogether. ## Field five: en passant (zero or 3 bits) ``` printf("%b",ord($1)-ord("a")) unless m/-/ // The EP's rank is 3 or 6 based on active color, only need to encode file ``` ## Naive worst case 200 bits * Two kings placements *- 12 bits* * Board + `QRRBBNN QQQQQQQQ` *- 75 bits* + `qrrbbnn qqqqqqqq` *- 75 bits* + Empty squares *- 30 bits* * Active color *- 1 bit* * Castling *- 4 bits* * En Passant *- 3 bits* ## Actual worst case Each player [cannot promote all pawns without capturing other pieces](https://chess.stackexchange.com/questions/5343/maximum-number-of-non-pawn-pieces-on-the-board). Here is the entropy effect of piece capture: * `PpR` (3+3+5 = 11 bits) => `Qq_` (5+5+1 = 11 bits) * `PPpp` (3+3+3+3 = 12 bits) => `QQq_` (5+5+5+1 = 16 bits) So actually the worst case board is: * `QRRBBNN QQQQQQQQ` *- 75 bits* * `qrrbbnn qqqq` *- 55 bits* * Empty squares *- 34 bits* Worst case is to promote all pieces rather than leave pawn for en passant. **TOTAL ACTUAL WORST CASE WITH SHOWN CODE** 12+75+55+34+1+4 = 181 bits [FIQ shows](https://codegolf.stackexchange.com/a/19449/16314) two improvements to this simple scheme, but they are harder to code: * Remove bit 2 from piece encoding on rows 1 and 8 since pawns can't go there (up to 16 bit savings) * Use pawns to encode castable rooks (4 bit savings) *The only remaining code not shown in this answer (for brevity) is: breaking the input FEN in fields (`split /\s/`) and variable assignment.* [Answer] ## ? bits *(≥ 217 worst-case, 17 best-case, 179 for initial board)* --- ### Encoding description Extra metadata consists of whose turn it is (one bit) and castling (four bits, i.e. may white castle on kings' side? on queens' side? and similarly for black). For the board position itself, we encode it as a set of active pieces. Well, actually, we make sure to enumerate the pieces in a particular order for reasons that I'll explain in a bit. For each piece we store its colour (one bit), its kind (three bits to encompass 6 kinds, plus one extra kind for "pawn that may be taken by en passant"), as well as its position. Here's the interesting part: to encode the position of a piece, instead of storing it as a coordinate, we store its relative distance from the last piece when enumerating the pieces in left-to-right, top-to-down order (i.e. A8, B8, ..., G1, H1). In addition, we store the distance as a variable-length number, using `1` to mean that this piece is right next to the previous, `0xx` for skipping 1-3 pieces, `000xxx` for skipping 4-10 pieces, `000000xxxx` for 11-25, `0000000000xxxxx` for 26-56 and finally `000000000000000xxx` for 57-62. ### Examples *I made [a gist](https://gist.github.com/FireyFly/8639791) of some positions coded with this encoding, and annotated the one for the initial position with some comments.* I don't know how to analyse the worst-case bit size, but going by the examples in the gist, I believe that the algorithm should be somewhat efficient at least. --- ### Implementation of decoder Below is a quick-and-dirty decoder for this encoding (taking as input the binary data encoded in text, as in the above annotated example, and skipping over things that aren't '0' or '1'). Produces a unicode chess board to stdout. ``` #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <string.h> char buf[1024]; int wi = 0, ri = 0; int read_n(int n) { int res = 0; for (int i = 0; i < n; i++) { res = res << 1 | (buf[ri++] == '1'); } return res; } int read_varnum() { int v, c = 0; for (int i = 1; i <= 5; i++) { v = read_n(i); if (v != 0) return c + v; c += (1 << i) - 1; } assert(false); /* Shouldn't happen */ } char *piece_to_str(int piece, int color) { /* ↓ pawn that may be taken with en passant */ char *pieces[] = { "♙", "♘", "♗", "♖", "♕", "♔", "♙", "♟", "♞", "♝", "♜", "♛", "♚", "♟" }; return pieces[color * 7 + piece]; } int main(void) { int ch; while (ch = getchar(), ch != EOF) { if (ch == '0' || ch == '1') buf[wi++] = ch; } int board[64]; memset(board, -1, 64 * sizeof(int)); /* Read metadata */ int is_white = read_n(1); int castling = read_n(4); /* Read the board state */ int bi = -1; while (ri != wi) { int color = read_n(1); int kind = read_n(3); int delta = read_varnum(); board[bi + delta] = color << 8 | kind; bi += delta; } /* Print metadata */ printf(" Current turn: %s's turn to play.\n", is_white? "white" : "black"); printf(" Castling: White may castle? %s %s\n", castling & 0x8? "left" : "", castling & 0x4? "right" : ""); printf(" Black may castle? %s %s\n", castling & 0x2? "left" : "", castling & 0x1? "right" : ""); printf("\n"); /* Print the board out */ printf("+"); for (int x = 0; x < 8; x++) printf("--"); printf("-+\n"); for (int y = 0; y < 8; y++) { printf("|"); for (int x = 0; x < 8; x++) { int piece = board[y*8 + x], color = piece >> 8, kind = piece & 0xFF; if (piece == -1) printf(" "); else printf(" %s", piece_to_str(kind, color)); } printf(" |\n"); } printf("+"); for (int x = 0; x < 8; x++) printf("--"); printf("-+\n"); return 0; } ``` [Answer] **Max: 184 bits, Min: 75 bits** I was inspired by @AdamSpeight's Huffman coding for pieces to try crafting my own scheme. I doubt this will win, but it does have calculable limits. This scheme treats the chess pieces as though there are 11 different types of pieces. I approximately followed the Huffman coding algorithm to group these classes by their frequencies and real types to generate the following encodings: ``` Piece Class | Frequency Per Team | Encoding ============================+====================+========== Pawn, normal | 0 - 8 | 0 Pawn, jumped two last turn | 0 - 1 | 1111 Knight | 0 - 2 | 1000 Bishop | 0 - 2 | 1001 Queen-side rook, unmoved | 0 - 1 | 10100 Queen-side rook, moved | 0 - 1 | 10101 King-side rook, unmoved | 0 - 1 | 10110 King-side rook, moved | 0 - 1 | 10111 Queen | 0 - 1 | 1110 King, unmoved | 0 - 1 | 1100 King, moved | 0 - 1 | 1101 ``` Each piece's code can be preceded by two bits to show to which team it belongs (`10` for White, `11` for Black). `0` can be used to encode empty spaces. These ideas allow us to build a square-by-square encoding for the whole board using whatever procedure we want. I will assume the iteration order `a1, b1, c1, ... f8, g8, h8`. This means that just listing these codes as shown above encodes all the information except whose turn it is. A very simple chess engine can use the "classes" for the pawns, rooks, and kings to determine whether castling and en passant are legal. Furthermore, this scheme easily handles pawn promotions. If a player promotes a pawn to a rook, either the king or queen-side codes may be used so long as the "moved" variant is chosen. Excepting pathological positions that I do not think could ever happen, the worst-case scenario for this encoding is when all pieces are still on the board and the previous player moved a pawn forward two spaces. As an example, the board below encodes `1. e4`: ``` 1101010010100010100110111010110010100110100010101101001001001100100100100000000000000101111000000000000000000011011011011011011011011011101001110001110011111101111001110011110001110110 =========================================================================== Black's move 1110100 111000 111001 111110 111100 111001 111000 1110110 | r n b q k b n r 110 110 110 110 110 110 110 110 | p p p p p p p p 0 0 0 0 0 0 0 0 | . . . . . . . . 0 0 0 0 0 0 0 0 | . . . . . . . . 0 0 0 0 101111 0 0 0 | . . . . P . . . 0 0 0 0 0 0 0 0 | . . . . . . . . 100 100 100 110 0 100 100 100 | P P P P . P P P 1010100 101000 101001 101110 101100 101001 101000 1010110 | R N B Q K B N R ``` This means that the worst-case encoding has 184 bits: 1 for indicating the player, 32 for the empty spaces, 45 for the unmoved pawns, 6 for the two-space-jumping pawn, 24 for the knights, 24 for the bishops, 28 for the rooks, 12 for the queens, and 12 for the kings. As pieces moved about and are captured, the size of the encoding will drop. The best case scenario is represented by two kings alone on the board: 1 bit for indicating the player + 62 bits for indicating the empty squares + 12 bits for indicating the kings gives a minimum length of 75 bits. I will come back and edit this response with some code that demonstrates this encoding in action later today or tomorrow. For now, I am curious to see what other people think of this encoding. [Answer] # 152.6 bits = log N where N = 8726713169886222032347729969256422370854716254 is the size of a ranking of chess positions including all legal ones. This is the best we can do since N is the best known upper bound on the number of legal positions. See <https://github.com/tromp/ChessPositionRanking> for more details. [Answer] 184 bits = 23 bytes worst case, and not too complicated: A. Which squares occupied: 64 bits = 8 bytes B. Which colors for the <=32 occupied squares: 32 bits = 4 bytes And now using only the <=30 squares occupied by non-kings: B. use PNBRQ encoded in radix 5, for 5^30 possibilities; and 32\*31\*2\*4\*4\*9 for king positions, mover-color, white & black castling rights, en passant square (among 8 possibilities plus none, a 9th); this number 5^30 \* 32 \* 31 \* 2 \* 4\*4\*9 = 266075134277343750000000000 = 2^87.782 fits in 88 bits for a total of 64+32+88=184 bits for the whole encoding. This can be reduced, e.g. 32\*31\*2\*4\*4\*9=285696 can be reduced to 2\*(32\*31+31\*3+31\*3+3\*3)\*6=14244, by using fact at most 6 en passant victim-candidates (including none), and encoding castling rights and king positions inside same set using fact castling rights only matter when king on initial square. This saves 4 bits. I have reason to believe that it is not possible to achieve 18 bytes, i.e. the total number of legal chess positions exceeds 2^144. Your 160-bit scheme is very ingenious but I think it needs to be given as encode/decode programs before I'll be completely confident about it. [Answer] This is a discussion topic in Chess circles. Here is one very simple proof with 164 bits <https://groups.google.com/forum/#!topic/rec.games.chess.computer/vmvI0ePH2kI> 155 is shown here <http://homepages.cwi.nl/~tromp/chess/chess.html> Over simplified strategy: * Limit pawns to the place where pawns may be found * Limit armies to consider original pieces and possible pawn promotions * Think hard about promotions and situations where promotions are not possible [Answer] # 171 bits worst case: I've combined a couple of ideas, as well as some of my own thoughts. We are going to start with a 64 bit board. Each bit represents an occupied space on the board. They fill along rows. So the start looks like: `1111 1111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111` Now, each piece will be represented by 4 bits. 1st bit: color (`0=white, 1=black`) 2nd-4th bits: One of 8 types. ``` 0=king, 1=queen, 2=bishop0, 3=knight, 4=rook, 5=pawn0, 6=pawn1, 7=bishop1 ``` At the end we will include a bit designating the turn. `0=white, 1=black`. 4bits\*32 pieces=128 bits and I've already got 64+1 from turn and board. That gives a total of 128+64+1=193 I haven't even started with en passant or castling. Well over my limit with nothing -- not even turns. This is where the tricks start. Okay -- you see those types above? Bishop0 and Bishop1? Pawn0 and pawn1? Those types are so designated, because they tell us a bit to insert after this piece. So Bishop0 means that after it, there will be a 0 -- i.e that the next piece is white. Bishop1 tells us the next piece is black, and the pawn0 and pawn1 work the same. (If this piece is the last piece being enumerated, then it tells us about the next turn instead). My worst case involves all the pieces on the board, so with 16 pawns and 4 bishops, this saves me 20 bits. I'm down to 173. Okay. For another bit in my worst case -- once there are 16 of a color encoded, we stop encoding color -- as we know it going forwards. My worst case now involves a white piece making it to the far corner with no captures. There, I save only one bit. 172. I'm going to now change the order in which I name the pieces. We will name them along columns starting at the outside moving in. The board named at the beginning will stay the same, but when I place pieces on it, i start from whites bottom right, and go up that column. Then I jump to black's bottom right, and go up that column. I jump to white's bottom right unknown cell, and so forth -- this means my worst case is again the start. My reason has to do with my en passant trick, the next two bits I lose, and castling. Now, for a pawn to be promoted (as has been discussed at length) a piece must be captured. Thus, when we know there are 32 pieces, we only need to denote 31 of them. The last piece is uniquely identified. As it turns out, for me, this only saves 2 bits -- because my last piece might be a pawn/bishop (which normally costs me 3 bits because I save one on the next piece) who's color is determined already and so was only 2 bits. I'm down to 170 bits. When pawns get promoted, they simply change their type. For each piece that goes off the board I rid myself of (minimum) 3 bits, and two pawn promotions cost me 2 bits, so I'm declining (slowly) in promotions. **Castling.** For castling to happen, neither king nor relevant rook may have moved. Thus, when a rook is capable of castling both it and the king will be in their original places. So, rooks capable of castling will be listed in the same place as kings of that color. As this is illegal (two kings or three kings of the same color on the board) and only can happen in three possible setups for each color (left, right, both rooks are listed as kings) -- decoding is utterly possible. So, for no bits we have encoded castling. **En Passant** Here we will also use illegal positions. Only one pawn can be in danger of en passant at a time. It must be in its fourth row. The pawn that is vulnerable will be 'flipped' back to its home row -- switched with whatever is there. As that pawn is in its own first row -- an illegal position, the situation will be obvious to the decoder -- it will reverse the positions, and mark the pawn as vulnerable to en passant. We needed to muck about with the order because the last piece has to be 'uniquely identified'. In a standard order, we wouldn't be able to tell if the rook in the back corner could castle -- that's not known. When we work from the outside in, we guarantee that wherever that rook is 'listed' be it in its own corner, or in the middle of the board because it was switched with an en passant vulnerable pawn, there will be a piece listed after it -- so we are told the rook's type. We know there will be a piece after it because, for a pawn to be vulnerable there must be a pawn to its inside (which will crucially be encoded later as per the instructions above). Oh, and to help make sure that the worst case involves all pieces on the board, once we have less than 32 pieces, we can use the 64 bit board to identify turn as well as occupied positions by using 0's to represent pieces when its white's turn and 1's when it is blacks turn. So we got en passant and castling for free. We picked up the last piece for free, though it took some finagling with order to make that play nice with the en passant and castling rules. We ditched 20 bits on the standard pieces. I believe the worst case here involves a midde white pawn moved forward and a black piece in between it and its queen while all pieces are on the board. Quick double check: first piece is captured -- call it a pawn, 3 bits off the board in the pawn, 3 bits on the board in the form of a last piece, one bit off in the turn marker disappearing. Promote two pawns 2 bits back on the board. Ah damn, I'm at 171. **EDIT** I've added code for a (working?) decoder -- in R -- below. It takes vectors of booleans as input -- (sorry -- I'm not capable of coding well in anything that would let me actually use the bits) I've also included the start position. ``` separate = function(vec){ #Using a boolean vector (sorry R doesn't handle bits well and this will build quickest) board = matrix(vec[1:64],8,8,byrow=T) npieces = min(sum(board),64-sum(board)) n = length(vec) a = vec[65:n] counter = 0 pieces = list() white = 0 Letters=c(letters,LETTERS) for (i in 1:npieces){ col = ifelse(a[1],"black",{white=white+1;"white"}) typ = a[2:4] a=a[-(1:4)] num = 4*typ[1] + 2*typ[2] + typ[3] type = switch(letters[num+1],a="king",b="queen",c="knight",d="rook",e="bishop0",f="bishop1",g="pawn0",h="pawn1") if (num > 3) { if(num%%2){ a = c(T,a) } else { a = c(F,a) } type = substr(type,1,nchar(type)-1) } pieces[[Letters[i]]] = list(color=col,type=type) if (length(pieces)==31&&npieces==32) { col = ifelse(16-white,{white=white+1;"white"},"black") type = "TBD" pieces[[Letters[i+1]]] = list(color=col,type=type) break } } if (npieces==32) { f=function(y){sum(sapply(pieces,function(x)x$type==y))} if (f("pawn")<16) {pieces[[32]]$type="pawn"} if (f("bishop")<4) {pieces[[32]]$type="bishop"} if (f("knight")<4) {pieces[[32]]$type="knight"} if (f("queen")<2) {pieces[[32]]$type="queen"} if (f("king")<2) {pieces[[32]]$type="king"} if (f("rook")<(6-f("king"))) {pieces[[32]]$type="rook"} } return(list(board,pieces,turn=ifelse(a[length(a)],"black","white"))) } fillboard = function(out) { board = out[[1]] pieces = out[[2]] turn = out[[3]] lpieces = lapply(pieces,function(x) paste(substr(x$color,1,1),x$type)) game = matrix(" ",8,8) #Start with corners. a = c(1,57,8,64) #Then kings b = c(25,32) #Then rooks in en passant c = c(4,60,5,61) #Then kings in en passant d = 28:29 exceptions = list(a,b,c,d) for (places in exceptions) { c= which(board[places]) if (length(c)) { repl = lpieces[1:length(c)] game[places[c]] = unlist(repl) board[places] = F lpieces = lpieces[-(1:length(c))] } } #Loop through rows. for (i in c(1:4,8:5)) { j = which(board[i,]) if (length(j)) { repl = lpieces[1:length(j)] game[i,j] = unlist(repl) board[i,j] = F lpieces = lpieces[-(1:length(j))] } } return(matrix(unlist(game),8,8,F)) } swapillegal = function(matr) { mat = matr if (any(mat[8,]=="b pawn")) { j = which(mat[8,]=="b pawn") mat[8,j] = mat[5,j] mat[5,j] = "b pawn-e" } if (any(mat[1,]=="w pawn")) { j = which(mat[1,]=="w pawn") mat[1,j] = mat[4,j] mat[4,j] = "w pawn-e" } if (sum(mat[8,]=="b king") > 1) { j = which(mat[8,-4]=="b king") j[j==7] = 8 mat[8,j] = "b rook-c" } if (sum(mat[1,]=="w king") >1) { j = which(mat[1,-4]=="w king") j[j==7] = 8 mat[1,j] = "w rook-c" } return(mat) } decode = function(vec) { a = separate(vec) b = fillboard(a) c = swapillegal(b) list(board=c,turn=a[[3]]) } startboard = c(rep(T,16),rep(F,32),rep(T,16)) #Re-ordering -- first spots will be the corners. Then kings. then en passant positions of those spots pieces = c(F,F,T,T,F,F,T,T,T,F,T,T,T,F,T,T,F,F,F,F,T,F,F,F,F,F,T,F,F,T,F,F,F,F,T,F,T,F,F,F,T,F,F,T,T,F,T,T,F,T,T,F,T,T,F,T,T,F,T,T,F,T,T,F,T,T,T,F,T,F,T,T,F,T,F,F,T,T,T,F,T,F,T,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,F) ########## w rook -w rook -B rook -B rook -W king -B king -w kni -w bi 0 -w Q -w Bi 0 -w kni-w p0 - 2 - 3 - 4 - 5 - 6 - 7 -w p1 -b kni-b bi1 -b q -b bi1 -b kni-b p1 -2 - 3 - 4 - 5 - 6 - b p0- implicit b p0. #After the kings come all the prior en passant positions. which are empty at start. Then we start at whites bottom right, and move across rows to middle. Then we go to blacks bottom left, and fill across to the middle. #Changing start to properly encode rooks for castling newpieces= c(F,F,F,F,F,F,F,F,T,F,F,F,T,F,F,F ,pieces[-(1:16)]) test2 = decode(c(startboard,newpieces)) ``` This code builds 4 functions. One that does some basic separation of the pieces and the board structure, as well as figuring out piece type and any 'implicit' pieces. The next function fills in the board structure with those pieces in a slightly bizzarre (and different from my initial algorithm's) order [explained in code comments]. The next function takes the filled in board and detects any illegal positions -- it then fixes them and renames pawns that are vulnerable to en passant "x pawn-e" and any rooks that can castle "x rook-c". The final function is a wrapper that runs those functions in order and gives an output which is the current board as well as the turn. I've also included the encoding of the start position (though to see it you will have to call `c(startboard,newpieces)` and the code calls the wrapper function on that position. [Answer] # Huffman Pawn Swap These are the stats for this encoding: ``` Initial: 129 bits Min: 75 bits Max: 165 bits Average: ....? 100-140 bits? ``` Most approaches described here are pretty similar, some try to push the limit and this might result in slower encoding/decoding, I've tried to keep my method as simple as possible. This originated after discussions with a colleague about creating a huge database with positions (that link to games and next positions). We came up with the following method: # Encode who's turn it is Use 1 bit to encode if white or black is to move # List all positions/squares in order Next we list all the positions and which piece occupies it, using a rather simple Huffman-like coding: ``` 0XXXXX Empty square (32 times, 1 bit, total: 32 bits) 1CXXXX Black or white color bit 1C0XXX Pawn (16 pieces, 3 bits, total: 48 bits) 1C100X Bishop (4 pieces, 5 bits, total: 20 bits) 1C101X Rook (4 pieces, 5 bits, total: 20 bits) 1C110X Knight (4 pieces, 5 bits, total: 20 bits) 1C1110 King (2 pieces, 6 bits, total: 12 bits) 1C1111 Queen (2 pieces, 6 bits, total: 12 bits) ``` This gives a maximum of 32+48+20+20+20+12+12 = 164 bits for all the pieces and positions. # En passant and castling Like described in other answers, you can encode en-passant and castling by creating illegal positions using the encoding mentioned above. This is done by swapping/placing **pawns** on places they *shouldn't* be. For **en-passant** you can swap that last moved pawn with the piece (or empty spot) from the fourth row to the first row. This is a place the pawn can never reach during a game, so swapping back and marking as en-passant is a nice trick. A final trick we do, which saves a lot of bits, is to replace all pieces on your first row that haven't moved yet with pawns of the opposite color. This is useful because it saves a lot of bits, and also automatically encodes **castling** options. # Average size It's hard to give an average without just running it against a lot of matches. Which I haven't done (yet). The initial position is encoded in **129** bits (all pawns) and this number grows a little once pieces start to leave their initial position, but it never grows to more than **165** bits. Finally with just two kings on the board, it can go down to a minimum of **75** bits. # Easy decoding Decoding is relatively easy, read one bit to see whos turn it is. Next enumerate all the positions and get a full chessboard returned. If the board has an own pawn on the first row, flip with the fourth row and mark that pawn as en-passant. Next look at all the opponent pawns, if they are on your first row, replace them with the original chess pieces and notice your rooks haven't moved yet. [Answer] ## 229 / 226 bits This turns out not to be very successful, but might save other people going down the same path. The simple version: * `1` bit for whose turn it is * `4` bits for the four castling possibilities * `3` bits for the *en passant* possibilities. This has more depth that I at first understood. *En passant* must be done by a pawn moving from the same rank (row) as the pawn which is captured. Case analysis indicates that once we know how many pawns of the colour which last moved have advanced exactly two squares, there will be at most 6 *en passant* cases (including the case that there is no pawn vulnerable to *en passant*). The worse case is 5 pawns (potentially all vulnerable: e.g. `PpPPpPPp` has five vulnerable `P`s). With 6 pawns there are at most 2 enemy pawns in the same rank, each of which can threaten at most 2 pawns *en passant*. Therefore we need `ceil(lg 6) = 3` bits here. Then the board. The board has 64 squares, so a square index can be encoded in 6 bits. We list the men by rank, alternating colours, starting with the king. * `6` bits: position of white king. (Guaranteed to be on the board). * `6` bits: position of black king. (Guaranteed to be on the board. In the worst case that the white king is in a corner, there are 60 possible places he could be; in the best case that the white isn't on an edge, there are 55). * `6` bits: position of white queen. If there is no white queen, repeat the white king's position as a signal. * For each additional white queen, a `1` bit followed by 6 bits for the position. * A `0` bit. * Ditto for black queen(s). * Similar process for rooks, bishops, knights, and pawns, although we can skip the pawns for a colour if we already have 16 men of that colour accounted for. * Delete the final `0` bit. This costs a certain `12` bits for the kings, and `2*7*5-1 = 69` bits for the other men. In the worst case that all 32 men are on the board, it costs `7` bits for each man other than the kings, for a total of `12 + 7*30 - 1 = 221 bits`. So with the initial `8` bits for global state we have **229 bits**. --- The advanced version: By using arithmetic coding we can operate with `lg num_possibilities` rather than `ceil(lg num_possibilities)` and just take one `ceil` at the end. * `1` bit for whose turn it is * `4` bits for the four castling possibilities * `lg 6` bits for the *en passant* possibilities. * `6` bits for the white king * `lg 60` bits (worst case) for the black king * `lg 63` bits (because I don't want to complicate it to the level of looking at checks) for the white queen, using the white king's position if there is none * For each additional white queen, a `1` bit followed by `lg 62`, `lg 61`, etc. bits for her position. * A `0` bit. * `lg 63` bits (or fewer, if there were any white queens) for the black queen. * etc. The nth man who's actually present has `66-n` possible values. If a type is absent for a colour, we spent `66-#men so far` bits in recording that (plus one bit for the separator). The extreme cases are: 1. All men present, including at least one unpromoted pawn from each side. We spend `5+lg 6` on global state, `6+lg 60` on the kings, `29` on separator bits, and `SUM_{n=32}^{63} lg n` bits on positions. Grand total: `ceil(225.82)` bits. Disappointing. 2. Only unpromoted pawns left. We spend `5+lg 6` on global state, `6+lg 60` on the kings, `29` on separator bits, `8*lg 63` saying that there are no other pieces, and `SUM_{n=48}^{63} lg n` on positions of the pawns. Grand total: `ceil(188.94)` bits. Better - by saving the second rook, knight, and bishop for each side we've pulled ahead a bit. So the worst case seems likely to be **226 bits**, for a measly saving of 3. We can definitely do better in the average case by encoding pawns before pieces, since they're restricted to 48 squares rather than the full 64. However, in the worst case that all men are on the board and all pawns have been promoted I think this would end up costing 2 bits more because we would need a "no pawns" flag rather than being able to count the men. [Answer] # Min: 0 bits # Max: ~~1734~~ 243 bits (~~4.335~~ 4.401 bits/board amortized) # Expected: ~~351~~ 177 bits (~~4.376~~ 4.430 bits/board amortized) Since I can determine the input and output however I want I decided to go with encoding the history of the game up until this point. One advantage is that the additional information of who's turn it is, en-passant, and who has the ability to castle where can be derived and not encoded. # Attempt 1: Naively I thought that I can encode each move in 12 bits, 4 triplets of the form (start x, start y, end x, end y) where each is 3 bits. We would assume the starting position and move pieces from there with white going first. The board is arranged such that ( 0 , 0 ) is white's lower left corner. For example the game: ``` e4 e5 Nf3 f6 Nxe5 fxe5 ... ... ``` Would be encoded as: ``` 100001 100010 100110 100100 110000 101010 101110 101101 101010 100100 101101 100100 ... ``` This leads to an encoding of 12 *m* bits where *m* is the number of moves made On one hand this could get really big, on the other hand you can consider each move to be it's own game so each encoding really encodes *m* "chess boards". If you amortized this you get that each "chess board" is 12 bits. But I feel this is a bit cheating... # Attempt 2: I realized that each move in the previous attempt encodes many illegal moves. So I decided to only encode legal moves. We enumerate possible moves as follows, number each square such that ( 0 , 0 ) → 0 , ( 1 , 0 ) → 1 , ( x , y ) → x + 8 y . Iterate through the tiles and check if a piece is there and if it can move. If so add the positions it can go to to a list. Choose the list index that is the move you want to make. Add that number to the running total of moves weighted by 1 plus the number of possible moves. Example as above: From the starting position the first piece that can move is the knight on square 1, it can move to square 16 or 18, so add those to the list `[(1,16),(1,18)]`. Next is the knight on square 6, add it's moves. Overall we get: `[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]` Since we want the move ( 12 , 28 ) , we encode this as 13 in base 20 since there are 20 possible moves. So now we get the game number g0 = 13 Next we do the same for black except we number the tiles in reverse (to make it easier, not required) to get the list of moves: `[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]` Since we want the move ( 11 , 27 ) , we encode this as 11 in base 20 since there are 20 possible moves. So now we get the game number g1 = ( 11 ⋅ 20 ) + 13 = 233 Next we get the following list of moves for white: `[(1,16),(1,18),(3,12),(3,21),(3,30),(3,39),(4,12),(5,12),(5,19),(5,26),(5,33),(5,40),(6,12),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27)(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]` Since we want the move ( 6 , 21 ) , we encode this as 13 in base 29 since there are 29 possible moves. So now we get the game number g2 = ( ( 13 ⋅ 20 ) + 11 ) 20 + 13 = 5433 Next we get the following list of moves for black: `[(1,11),(1,16),(1,18),(2,11),(2,20),(2,29),(2,38),(2,47),(3,11),(4,11),(4,18),(4,25),(4,32),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]` Since we want the move $(10, 18)$ ( 10 , 18 ) So now we get the game number g3 = ( ( ( 19 ⋅ 29 + 13 ) 20 ) + 11 ) 20 + 13 = 225833 And continue this process for all the remaining moves. You can think of *g* as the function g ( x , y , z ) = x y + z . Thus g0 = g ( 1 , 1 , 13 ) , g1 = g ( g ( 1 , 1 , 11 ) , 20 , 13 ) , g2 = g ( g ( g ( 1 , 1 , 13 ) , 20 , 11 ) , 20 , 13 ) , g3 = g ( g ( g ( g ( 1 , 1 , 19 ) , 29 , 13 ) , 20 , 11 ) , 20 , 13 ) To decode a game number *g*0, we start at the initial position and enumerate all possible moves. Then we compute *g*1 = *g*0 // *l*, *m*0 = *g*0 % *l*, where *l* is the number of possible moves, '//' is the integer division operator and '%' is the modulus operator. It should hold that *g*0 = *g*1 + *m*0. Next we make the move *m*0 and repeat. From the example above if *g*0 = 225833 then *g*1 = 225833 // 20 = 11291 and *m*0 = 225833 % 20= 13. Next *g*2 = 11291 // 20 = 564 and *m*1 = 11291 % 20 = 11. Then *g*3 = 11291 // 20 = 564 and *m*2 = 11291 % 20 = 11. Therefore *g*4 = 564 // 29 = 19 and\_m\_3 = 564 % 29 = 13. Finally *g*5= 19 // 29 = 0 and *m*4 = 19 % 29 = 19. So how many bits are used to encode a game this way? For simplicity, let's say there are always 20 moves each turn and for the worst case scenario we always pick the biggest one, 19. The number we will get is 19 ⋅ 20m + 19 ⋅ 20m-1 + 19 ⋅ 20m-2 + ⋯ + 19 ⋅ 20 + 19 = 20m+1 − 1 where \_m is the number of moves. To encode 20m+1 − 1 we need about log2 ( 20m+1 ) bits which is about ( m + 1 ) ∗ log2 ( 20 ) = 4.3219 ∗ ( m + 1 ) On average *m* = 80 (40 moves per player) so this would take 351 bits to encode. If we were recording many games we would need a universal encoding since we don't know how many bits each number will need Worst case when *m* = 400 (200 moves per player) so this would take 1734 bits to encode. Note that the position we want to encode must be given to us via the shortest path to get there by following the rules. For example the game theorized [here](https://www.chess.com/blog/kurtgodden/the-longest-possible-chess-game) doesn't need *m* = 11741 to encode the final position. Instead we run a Breadth-First search to find the shortest path to that position and encode that instead. I don't know how deep we would need to go to enumerate all chess positions, but I suspect that 400 is an overestimate. Quick calculation: There are 12 unique pieces or the square can be empty so to position them on a chessboard is 1364. This is a vast overestimate since it includes many invalid positions. When we are *m* moves into the game we have created about 20*m* positions. So we are looking for when 20*m* = 1364. Log both sides to get *m* = 64 \* log20(13) = 54.797. This shows that we should be able to get to any position in 55 moves. Now that I calculated the worst case to be *m* = 55 not *m* = 400 I will edit my results. To encode a position where *m* = 55 takes 243 bits. I'm going to also say that the average case is around *m* = 40 which takes 177 bits to encode. If we use the amortization argument from earlier we are encoding 400 "chess boards" in 1734 bits so we get that each "chess board" takes up 4.335 bits in the worst case. Note that *g* = 0 denotes a valid game, the one where the piece on the lowest square moves to the lowest square it can. # Additional Notes: If you want to refer to a specific position in the game you may need to encode the index. This can be added either manually e.g concatenate the index to the game, or add an additional "end" move as the last possible move each turn. This can now account for players conceding, or 2 in a row to denote the players agreed to a draw. This is only necessary if the game did not end in a checkmate or stalemate based on the position, in this case it is implied. In this case it brings the number of bits needed on average to 356 and in the worst case 1762. ]
[Question] [ Given a nonempty list of positive decimal integers, output the largest number from the set of numbers with the fewest digits. The input list will not be in any particular order and may contain repeated values. **Examples:** ``` [1] -> 1 [9] -> 9 [1729] -> 1729 [1, 1] -> 1 [34, 3] -> 3 [38, 39] -> 39 [409, 12, 13] -> 13 [11, 11, 11, 1] -> 1 [11, 11, 11, 11] -> 11 [78, 99, 620, 1] -> 1 [78, 99, 620, 10] -> 99 [78, 99, 620, 100] -> 99 [1, 5, 9, 12, 63, 102] -> 9 [3451, 29820, 2983, 1223, 1337] -> 3451 [738, 2383, 281, 938, 212, 1010] -> 938 ``` **The shortest code in bytes wins.** [Answer] # Pyth, ~~7~~ ~~3~~ 6 bytes ``` eS.ml` ``` [Test Suite](http://pyth.herokuapp.com/?code=eS.ml%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0) Explanation: ``` e Still grab the last element S Still sort .ml` But prefilter the list for those with the (m)inimum length. ``` --- 7 byte solution: ``` eSh.gl` ``` [Test Suite](http://pyth.herokuapp.com/?code=eSh.gl%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0) Explanation: ``` .g Group items in (implicit) input by: l The length of ` their representation h Get those with the shortest length S Sort the resulting list e and grab the last (i.e. largest) element ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DL,NµÞḢ ``` Test it at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKI&input=&args=WzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF0)** Or see all test cases also at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKIKxbzDh-KCrOG5hOKCrMK1&input=&args=W1sxXSwgWzldLCBbMTcyOV0sIFsxLCAxXSwgWzM0LCAzXSwgWzM4LCAzOV0sIFs0MDksIDEyLCAxM10sIFsxMSwgMTEsIDExLCAxXSwgWzExLCAxMSwgMTEsIDExXSwgWzc4LCA5OSwgNjIwLCAxXSwgWzc4LCA5OSwgNjIwLCAxMF0sIFs3OCwgOTksIDYyMCwgMTAwXSwgWzEsIDUsIDksIDEyLCA2MywgMTAyXSwgWzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XSwgWzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF1d)** How? ``` DL,NµÞḢ - Main link takes one argument, the list, e.g. [738, 2383, 281, 938, 212, 1010] D - convert to decimal, e.g. [[7,3,8],[2,3,8,3],[2,8,1],[9,3,8],[2,1,2],[1,0,1,0]] L - length, e.g. [3,4,3,3,3,4] N - negate, e.g [-738, -2383, -281, -938, -212, -1010] , - pair, e.g. [[3,-738],[4,-2383],[3,-281],[3,-938],[3,-212],[4,-1010]] µ - make a monadic chain Þ - sort the input by that monadic function, e.g [938,738,281,212,2383,1010] (the lists in the example are not created, but we sort over the values shown) Ḣ - pop and return the first element, e.g. 938 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes Code: ``` ({é¬( ``` Explanation: ``` ( # Negate the list, e.g. [22, 33, 4] -> [-22, -33, -4] { # Sort, e.g. [-22, -33, -4] -> [-33, -22, -4] é # Sort by length, e.g. [-33, -22, -4] -> [-4, -22, -33] ¬ # Get the first element. ( # And negate that. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=KHvDqcKsKA&input=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ) [Answer] # Python 2, ~~48~~ 42 bytes -6 bytes thanks to @Dennis (use `min` rather than `sorted`) ``` lambda l:min(l,key=lambda x:(len(`x`),-x)) ``` All test cases are at **[ideone](http://ideone.com/IbYFyJ)** Take the minimum of the list by (length, -value) [Answer] # Ruby, 34 bytes ``` ->a{a.max_by{|n|[-n.to_s.size,n]}} ``` See it on eval.in: <https://eval.in/643153> [Answer] # [MATL](http://github.com/lmendo/MATL), 14 bytes ``` 10&YlktX<=G*X> ``` [Try it online!](http://matl.tryitonline.net/#code=MTAmWWxrdFg8PUcqWD4&input=Wzc4LCA5OSwgNjIwLCAxMDBd) Explanation: ``` &Yl % Log 10 % Base 10 kt % Floor and duplicate X< % Find the smallest element = % Filter out elements that do not equal the smallest element G % Push the input again * % Multiply (this sets numbers that do not have the fewest digits to 0) X> % And take the maximum ``` [Answer] # [Retina](http://github.com/mbuettner/retina), ~~24~~ 16 bytes ``` O^` O$#` $.0 G1` ``` [Try it online!](http://retina.tryitonline.net/#code=T15gCk8kI2AKJC4wCkcxYA&input=MQoxMgo5CjYzCjUKMTAy) or [run all test cases](http://retina.tryitonline.net/#code=JShHYApPXmBcZCsKTyQjYFxkKwokLjAKIC4rCg&input=MQo5CjE3MjkKMSAxCjM0IDMKMzggMzkKNDA5IDEyIDEzCjExIDExIDExIDEKMTEgMTEgMTEgMTEKNzggOTkgNjIwIDEKNzggOTkgNjIwIDEwCjc4IDk5IDYyMCAxMDAKMSA1IDkgMTIgNjMgMTAyCjM0NTEgMjk4MjAgMjk4MyAxMjIzIDEzMzcKNzM4IDIzODMgMjgxIDkzOCAyMTIgMTAxMA). Saved 8 bytes thanks to Martin! The all test is using a slightly older version of the code, but the algorithm is identical. I'll update it to be closer when I get more time. The trailing newline is significant. Sorts the numbers by reverse numeric value, then sorts them by number of digits. This leaves us with the largest number with the fewest digits in the first position, so we can just delete the remaining digits. [Answer] # Mathematica, ~~33~~ 31 bytes ``` Max@MinimalBy[#,IntegerLength]& ``` MinimalBy selects all the elements of the original input list with the smallest score according to `IntegerLength`, i.e., with the smallest number of digits; and then Max outputs the largest one. *Thanks to Martin Ender for finding, and then saving, 2 bytes for me :)* [Answer] # [Perl 6](https://perl6.org), 18 bytes ``` *.min:{.chars,-$_} ``` ## Explanation: ``` *\ # Whatever lambda .min: # find the minimum using { # bare block lambda with implicit parameter 「$_」 .chars, # number of characters first ( implicit method call on 「$_」 ) -$_ # then negative of the value in case of a tie } ``` ## Usage: ``` say [738, 2383, 281, 938, 212, 1010].&( *.min:{.chars,-$_} ); # 938 my &code = *.min:{.chars,-$_} say code [78, 99, 620, 10]; # 99 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ ~~15~~ 14 bytes ``` |/{=/&/\#'$x}# ``` [Try it online!](https://ngn.codeberg.page/k/#eJxlUNtqwzAMffdXCFp2AY9EVtpYNduPZIHupTA2GJQ9tHTdt+9IbtZ2g/hyLlaks1l9NYfH5qZ5nt3Od8dZCJ+rw3zYf29XGyLalfXHW7lbb15e38uu7Mv2fjzCM0QuPNqpRf3kPmmxzRDTSZaOpIjfMokWcblrlTgRS2HXGP761VdnDMKZPpMqLVM7WS6Itqj+pSaOaUGJ/G9LAZ9qt9ItmJJmeLFDSAmbSF9M8WLoNwmklJnUgDXc2s8kjyE0YeCRHp6Iw6B+UTA2vpO4AEb69UgXSRwIQAaoToEPccCZsKqDYWF7PK2pyBV5YkH3KKcogdEvzNdsW3vUf/xZQNEFpNrKUkxM02QWS6yJ+WEqMoseWh0EjmCxRc8tWnDRkosWXfTsajXJP9wzhD8=) * `{...}#` set up a filter, returning elements from the (implicit) right argument where the code in `{...}` returns `1`s + `#'$x` count the number of characters in the string representation of each input + `&/\` generate a two item list of the character counts and their minimum + `=/` generate a boolean mask indicating which indices have the fewest digits * `|/` return the maximum (remaining) value [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes ``` DL€İMị¹Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gA&input=&args=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gArDh-KCrA&input=&args=W1sxXSwKIFs5XSwKIFsxNzI5XSwKIFsxLCAxXSwKIFszNCwgM10sCiBbMzgsIDM5XSwKIFs0MDksIDEyLCAxM10sCiBbMTEsIDExLCAxMSwgMV0sCiBbMTEsIDExLCAxMSwgMTFdLAogWzc4LCA5OSwgNjIwLCAxXSwKIFs3OCwgOTksIDYyMCwgMTBdLAogWzc4LCA5OSwgNjIwLCAxMDBdLAogWzEsIDUsIDksIDEyLCA2MywgMTAyXSwKIFszNDUxLCAyOTgyMCwgMjk4MywgMTIyMywgMTMzN10sCiBbNzM4LCAyMzgzLCAyODEsIDkzOCwgMjEyLCAxMDEwXV0) ## Explanation ``` DL€İMị¹Ṁ Input: list A D Convert each integer to a list of base 10 digits L€ Get the length of each list (number of digits of each) İ Take the reciprocal of each M Get the indices of the maximal values ¹ Get A ị Select the values at those indices from A Ṁ Find the maximum and return ``` [Answer] # JavaScript (ES6), 51 ``` l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0] ``` **Test** ``` f=l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0] ;[ [[1], 1] ,[[9], 9] ,[[1729], 1729] ,[[1, 1], 1] ,[[34, 3], 3] ,[[38, 39], 39] ,[[409, 12, 13], 13] ,[[11, 11, 11, 1], 1] ,[[11, 11, 11, 11], 11] ,[[78, 99, 620, 1], 1] ,[[78, 99, 620, 10], 99] ,[[78, 99, 620, 100], 99] ,[[1, 5, 9, 12, 63, 102], 9] ,[[3451, 29820, 2983, 1223, 1337], 3451] ,[[738, 2383, 281, 938, 212, 1010], 938] ].forEach(([l,x])=>{ var r=f(l) console.log(r==x?'OK':'KO',l+' -> '+r) }) ``` [Answer] # J, ~~21~~ 14 bytes Saved 7 bytes thanks to miles and (indirectly) Jonathan! ``` {.@/:#@":"0,.- ``` This is a four-chain: ``` {.@/: (#@":"0 ,. -) ``` Let's walk over the input `10 27 232 1000`. The inner fork consists of three tines. `#@":"0` calculates the sizes, `,.` concats each size with its negated (`-`) member. For input `10 27 232 1000`, we are left with this: ``` (#@":"0 ,. -) 10 27 232 1000 2 _10 2 _27 3 _232 4 _1000 ``` Now, we have `{.@/:` as the outer tine. This is monadic first (`{.`) over dyadic sort (`/:`). That is, we'll be taking the first element of the result of dyadic `/:`. This sorts its right argument according to its left argument, which gives us for our input: ``` (/: #@":"0 ,. -) 10 27 232 1000 27 10 232 1000 ``` Then, using `{.` gives us the first element of that list, and we are done: ``` ({.@/: #@":"0 ,. -) 10 27 232 1000 27 ``` ## Old version ``` >./@(#~]=<./@])#@":"0 ``` Still working on improvements. I golfed it down from 30, and I think this is good enough. I'm going to first break it down into basic parts: ``` size =: #@":"0 max =: >./ min =: <./ over =: @ right =: ] left =: [ selectMin =: #~ right = min over right f =: max over selectMin size f 3 4 5 5 f 3 4 53 4 f 343 42 53 53 ``` Here's how this works. ``` >./@(#~ ] = <./@]) #@":"0 ``` This is a monadic train, but this part is a hook. The verb `>./@(#~ ] = <./@])` is called with left argument as the input to the main chain and the sizes, defined as `#@":"0`, as the right argument. This is computed as length (`#`) over (`@`) default format (`":`), that is, numeric stringification, which is made to apply to the 0-cells (i.e. members) of the input (`"0`). Let's walk over the example input `409 12 13`. ``` (#@":"0) 409 12 13 3 2 2 ``` Now for the inner verb, `>./@(#~ ] = <./@])`. It looks like `>./@(...)`, which effectively means maximum value (`>./`) of (`@`) what's inside `(...)`. As for the inside, this is a four-train, equivalent to this five-train: ``` [ #~ ] = <./@] ``` `[` refers to the original argument, and `]` refers to the size array; `409 12 13` and `3 2 2` respectively in this example. The right tine, `<./@]`, computes the minimum size, `2` in this case. `] = <./@]` is a boolean array of values equal to the minimum, `0 1 1` in this case. Finally, `[ #~ ...` takes values from the left argument according the right-argument mask. This means that elements that correspond to `0` are dropped and `1` retained. So we are left with `12 13`. Finally, according to the above, the max is taken, giving us the correct result of `13`, and we are done. [Answer] # Julia, 39 ``` f(l)=sort(l,by=x->(length("$x"),-x))[1] ``` [ATO](https://ato.pxeger.com/run?1=jZBNTsMwEIXFsjlFZCGRSAlK7P7EEolgyYITVCyM6kCQ5Va2C0UqJ2HTTQ9VTsNz3AAVG6Q4mXnvm6dxPvbPa9WJ3eHGiFdCSJuotLZL4xKVPbzVm7xJlNSP7ikh5xuSZvkmTeflPchtE4xtszKddkrv167Nq8PFPyOO-Hu7NLHqdIzHSLFAKW1i3aLTaTQSxmRG2tquVIe8Tmckb0gw6jvpxOVKGCsTtOm2kS9CRSPPB_VWOz8N_FpYK7FR25N13atSL8ISu8-zK2wU501cRnPeFzyalzMaal-gzeJvho2zmPUNQ1OhCSQDNy44SIoTiBJI6YeHM4SciEcV8gxxHBFTWvyCT9Ui7Mj_6D8GQiewwipT5k063IyNJ7Apr_wQPt6l1L8Zm4WLgEC4vxpl3qcVJnjf93crhh1YFYW_-AU)able [Answer] # JavaScript (ES6), 62 bytes ``` var solution = a=>a.map(n=>(l=`${n}`.length)>a?l>a+1|n<r?0:r=n:(a=l-1,r=n))|r ;document.write('<pre>' + ` [1] -> 1 [9] -> 9 [1729] -> 1729 [1, 1] -> 1 [34, 3] -> 3 [38, 39] -> 39 [409, 12, 13] -> 13 [11, 11, 11, 1] -> 1 [11, 11, 11, 11] -> 11 [78, 99, 620, 1] -> 1 [78, 99, 620, 10] -> 99 [78, 99, 620, 100] -> 99 [1, 5, 9, 12, 63, 102] -> 9 [3451, 29820, 2983, 1223, 1337] -> 3451 [738, 2383, 281, 938, 212, 1010] -> 938 `.split('\n').slice(1, -1).map(c => c + ', result: ' + solution(eval(c.slice(0, c.indexOf('->')))) ).join('\n')) ``` [Answer] ## Javascript (ES6), ~~57~~ ~~54~~ 53 bytes ``` l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0] ``` For the record, my previous version was more math-oriented but 1 byte bigger: ``` l=>l.sort((a,b)=>(s=a=>1/a-~Math.log10(a))(a)-s(b))[0] ``` ### Test cases ``` let f = l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0] console.log(f([1])); // -> 1 console.log(f([9])); // -> 9 console.log(f([1729])); // -> 1729 console.log(f([1, 1])); // -> 1 console.log(f([34, 3])); // -> 3 console.log(f([38, 39])); // -> 39 console.log(f([409, 12, 13])); // -> 13 console.log(f([11, 11, 11, 1])); // -> 1 console.log(f([11, 11, 11, 11])); // -> 11 console.log(f([78, 99, 620, 1])); // -> 1 console.log(f([78, 99, 620, 10])); // -> 99 console.log(f([78, 99, 620, 100])); // -> 99 console.log(f([1, 5, 9, 12, 63, 102])); // -> 9 console.log(f([3451, 29820, 2983, 1223, 1337])); // -> 3451 console.log(f([738, 2383, 281, 938, 212, 1010])); // -> 938 ``` [Answer] ## dc, 54 bytes ``` ?dZsL0sN[dsNdZsL]su[dlN<u]sU[dZlL=UdZlL>ukz0<R]dsRxlNp ``` **Explanation:** ``` ?dZsL0sN # read input, initialize L (length) and N (number) [dsNdZsL]su # macro (function) 'u' updates the values of L and N [dlN<u]sU # macro 'U' calls 'u' if N < curr_nr [dZlL=U dZlL>ukz0<R]dsR # macro 'R' is a loop that calls 'U' if L == curr_nr_len #or 'u' if L > curr_nr_len xlNp # the main: call 'R' and print N at the end ``` **Run example:** 'input.txt' contains all the test cases in the question's statement ``` while read list;do echo "$list -> "$(dc -f program.dc <<< $list);done < input.txt ``` **Output:** ``` 1 -> 1 9 -> 9 1729 -> 1729 1 1 -> 1 34 3 -> 3 38 39 -> 39 409 12 13 -> 13 11 11 11 1 -> 1 11 11 11 11 -> 11 78 99 620 1 -> 1 78 99 620 10 -> 99 78 99 620 100 -> 99 1 5 9 12 63 102 -> 9 3451 29820 2983 1223 1337 -> 3451 738 2383 281 938 212 1010 -> 938 ``` [Answer] # Java 7, ~~112~~ 104 bytes ``` int c(int[]a){int i=a[0],j;for(int b:a)i=(j=(i+"").length()-(b+"").length())>0?b:b>i&j==0?b:i;return i;} ``` Different approach to save multiple bytes thanks to *@Barteks2x*. **Ungolfed & test cases:** [Try it here.](https://ideone.com/Zo6o2f) ``` class M{ static int c(int[] a){ int i = a[0], j; for(int b : a){ i = (j = (i+"").length() - (b+"").length()) > 0 ? b : b > i & j == 0 ? b : i; } return i; } public static void main(String[] a){ System.out.println(c(new int[]{ 1 })); System.out.println(c(new int[]{ 9 })); System.out.println(c(new int[]{ 1729 })); System.out.println(c(new int[]{ 1, 1 })); System.out.println(c(new int[]{ 34, 3 })); System.out.println(c(new int[]{ 409, 12, 13 })); System.out.println(c(new int[]{ 11, 11, 11, 1 })); System.out.println(c(new int[]{ 11, 11, 11, 11 })); System.out.println(c(new int[]{ 78, 99, 620, 1 })); System.out.println(c(new int[]{ 78, 99, 620, 100 })); System.out.println(c(new int[]{ 1, 5, 9, 12, 63, 102 })); System.out.println(c(new int[]{ 3451, 29820, 2983, 1223, 1337 })); System.out.println(c(new int[]{ 738, 2383, 281, 938, 212, 1010 })); } } ``` **Output:** ``` 1 9 1729 1 3 13 1 11 1 99 9 3451 938 ``` [Answer] # bash, awk, sort 53 bytes ``` set `awk '{print $0,length($0)}'|sort -rnk2n`;echo $1 ``` Read input from stdin, one value per line # bash and sort, ~~58~~ 57 bytes ``` set `sort -n`;while((${#2}==${#1}));do shift;done;echo $1 ``` [Answer] # JavaScript ES6, ~~80~~ ~~77~~ 70 bytes ``` a=>Math.max(...a.filter(l=>l.length==Math.min(...a.map(i=>i.length)))) ``` I hope I am going in the right direction... [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 16 bytes ``` or:@]feL:la#=,Lh ``` [Try it online!](http://brachylog.tryitonline.net/#code=b3I6QF1mZUw6bGEjPSxMaA&input=WzM0NTE6Mjk4MjA6Mjk4MzoxMjIzOjEzMzdd&args=Wg) ### Explanation ``` or Sort the list in descending order. :@]f Find all suffixes of the list. eL Take one suffix L of the list. :la Apply length to all numbers in that suffix. #=, All lengths must be equal. Lh Output is the first element of L. ``` [Answer] # Haskell, 39 bytes ``` snd.maximum.map((0-).length.show>>=(,)) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 11 bytes ``` tV48\&XS0)) ``` Input is a column vector (using `;` as separator), such as ``` [78; 99; 620; 100] ``` [Try it online!](http://matl.tryitonline.net/#code=dFY0OFwmWFMwKSk&input=WzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0VjQ4XCZYUzApKQpEVA&input=WzFdCls5XQpbMTcyOV0KWzE7IDFdClszNDsgM10KWzM4OyAzOV0KWzQwOTsgMTI7IDEzXQpbMTE7IDExOyAxMTsgMV0KWzExOyAxMTsgMTE7IDExXQpbNzg7IDk5OyA2MjA7IDFdCls3ODsgOTk7IDYyMDsgMTBdCls3ODsgOTk7IDYyMDsgMTAwXQpbMTsgNTsgOTsgMTI7IDYzOyAxMDJdClszNDUxOyAyOTgyMDsgMjk4MzsgMTIyMzsgMTMzN10KWzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0). ### Explanation Let's use input `[78; 99; 620; 100]` as an example. ``` t % Input column vector implicitly. Duplicate % STACK: [78; 99; 620; 100], [78; 99; 620; 100] V % Convert to string. Each number is a row, left-padded with spaces % STACK: [78; 99; 620; 100], [' 78'; ' 99'; '620'; '100'] 48\ % Modulo 48. This transforms each digit into the corresponding number, % and space into 32. Thus space becomes the largest "digit" % STACK: [78; 99; 620; 100], [32 7 8; 32 9 9; 6 2 0; 1 0 0] &XS % Sort rows in lexicographical order, and push the indices of the sorting % STACK: [78; 99; 620; 100], [4; 3; 1; 2] 0) % Get last value % STACK: [78; 99; 620; 100], 2 ) % Index % STACK: 99 % Implicitly display ``` [Answer] # Perl, ~~38~~ 37 bytes Includes +1 for `-a` Give input on STDIN: ``` perl -M5.010 maxmin.pl <<< "3451 29820 2983 1223 1337" ``` `maxmin.pl`: ``` #!/usr/bin/perl -a \$G[99-y///c][$_]for@F;say$#{$G[-1]} ``` Uses memory linear in the largest number, so don't try this on too large numbers. A solution without that flaw is 38 bytes: ``` #!/usr/bin/perl -p $.++until$\=(sort/\b\S{$.}\b/g)[-1]}{ ``` All of these are very awkward and don't feel optimal at all... [Answer] ## PowerShell v2+, 41 bytes ``` ($args[0]|sort -des|sort{"$_".length})[0] ``` Takes input `$args`, `sort`s it by value in `-des`cending order (so bigger numbers are first), then `sort`s that by the `.length` in ascending order (so shorter lengths are first). We then take the `[0]` element, which will be the biggest number with the fewest digits. ## Examples ``` PS C:\Tools\Scripts\golfing> @(78,99,620,1),@(78,99,620,10),@(78,99,620,100),@(1,5,9,12,63,102),@(3451,29820,2983,1223,1337),@(738,2383,281,938,212,1010)|%{($_-join',')+" -> "+(.\output-largest-number-fewest-digits.ps1 $_)} 78,99,620,1 -> 1 78,99,620,10 -> 99 78,99,620,100 -> 99 1,5,9,12,63,102 -> 9 3451,29820,2983,1223,1337 -> 3451 738,2383,281,938,212,1010 -> 938 ``` [Answer] # R, ~~72~~ ~~41~~ 36 bytes Rewrote the function with a new approach. Golfed 5 bytes thanks to a suggestion from @bouncyball. ``` n=nchar(i<-scan());max(i[n==min(n)]) ``` Explained: ``` i<-scan() # Read input from stdin n=nchar( ); # Count the number of characters in each number in i max( ) # Return the maximum of the set where i[n==min(n)] # the number of characters is the minimum number of characters. ``` ``` function(i){while(1){if(length(o<-i[nchar(i)==T]))return(max(o));T=T+1}} ``` Indented/explained: ``` function(i){ # Take an input i while(1){ # Do the following continuously: if(length( o<-i[nchar(i)==T]) # Define o to be the subset of i with numbers of length T, ) # where T is 1 (a built-in!). # We take the length of this subset (its size), and then pass # it to if(). Thanks to weak typing, this numeric is converted # to a logical value. When this occurs, zero evaluates to FALSE # and any non-zero number evaluates to TRUE. Therefore, the if() # is TRUE iff the subset is not empty. return(max(o)); # If it's true, then we just return the largest element of the # subset, breaking out of our loop. T=T+1 # Otherwise, increment our counter and continue. } } ``` [Answer] ## Bash + coreutils, 58 bytes ``` d=`sort -n`;egrep ^.{`sed q<<<"$d"|wc -L`}$<<<"$d"|tail -1 ``` Input format is one value per line. Golfing suggestions are welcomed. **Explanation:** ``` d=`sort -n` #save the list in ascending numerical order egrep ^.{ }$<<<"$d" #print only list lines having as many chars `sed q<<<"$d"|wc -L` #as the first sorted line does |tail -1 #and then get the last one (the answer) ``` [Answer] # **Python 2 - 41 bytes** ``` lambda l:max((-len(`x`),x) for x in l)[1] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 bytes -4 thanks to @rak1507. ``` f←⌈/⊢×((⌊/=⊢)≢∘⍕¨) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPR36j7oWHZ6uofGop0vfFsjWfNS56FHHjEe9Uw@t0Pz/qG8qUFmagrmxhY6CkbGFMZC0MNRRsATzDY10FAwNDA24YMqAMqZASaAoUMbMGCRr9B8A "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` DL$ÐṂṀ ``` [Try it online!](https://tio.run/##ZU8rDsJAEPU9xQpkSboz/a1BERSahDSVGNIL4JoaEhQXwIBFItoge5LtRZa3XRZoELM77zMvM/tdVR2MWa5n/Vl3je5qo9uT7m5DfSl1e92s@mOgn4/@ODT3rTGFLMV8IWRQqLFRQSEzcr1tAEPx8XAcCh4BA@QAzsnwxZGCk1DOIWGRdtiXD5mQbxZ0hjiFiJSiH/OUjdyO6o//CghNILlVUrYi@cs4TiCTyu0QPqsS2Zc5c4fAgXB7GrHVKceEGvF4W@R34PwF "Jelly – Try It Online") ## How it works ``` DL$ÐṂṀ - Main link. Takes a list L on the left $ÐṂ - Take the elements of L for which the following is minimal: DL - Digit Length Ṁ - Maximum of those elements ``` ]
[Question] [ You should write a program which receives two strings as input and outputs a sequence of movements which rearrange the first string into the second. You should use as few moves as you can. Both strings will contain only lowercase letters and the second (goal) string is a permutation of the first (original) one. Every move is described as `char_index:direction` where * `char_index` is the 0-based index of the character in the original (first) string * `direction` is one of `u d l r` corresponding to moving the selected character one step up, down, left or right. You can only move a character to another position if **no other character is there**. The grid on which you can move the characters is infinite in every direction. Your goal is to rearrange the letters of the first string so they take up the same area as at start but spell out the second string. For example a valid move sequence for `abc` => `acb` would be `2:d 1:r 2:l 2:u` (4 moves): ``` | abc | ab | a b | a b | acb | | | c | c | c | | ``` Another move sequence for the same input is `2:r 2:d 1:u 1:u 1:r 1:d 1:d 2:l 2:l 2:u` (10 moves): ``` | | | | | b | b | | | | | | | | | | b | | | b | | | | | | abc | ab c | ab | a | a | a | a | a b | a b | a b | acb | | | | c | c | c | c | c | c | c | c | | ``` ## Input * Two strings (original and goal string) containing only the letters [a-z]. * The two strings are separated by a newline. ## Output * A space separated list of moves. * Each move has the format `char_index:direction` as described above. ## Scoring * Your score is the **total number of moves** your program uses on the test case inputs. Lower score is better. * In the event of a tie the earlier submission wins. * Your submission is valid only if you ran your program on all the test cases and counted your score. * You can validate your solutions with [this python program](http://ideone.com/Pzi3M4). Provide input and output filenames as arguments or input and output as stdin (2 lines input and then 1line output). ## Test cases *(Test cases are delimited by empty lines.)* ``` ehmwgzcyoaedeyvckivf chacfveyvwdeyoigezkm ymnrpltwdyvlgdrgndgx ggydpnrwgrdyvtnmldxl gfceetyxotezibswjcdh oeefgjciehyxswtcdbtz qdjqiffrqokkitndmufl oqfrmfudqktikfjqilnd sxgsugcylgsfgznrktgp cgsylsgnggkzurgptfxs izzbcpvwpkackqykurghocpptmbtfcdorlmterhyellurudblqlbldaheorilrfzoonicbfwksdqjjeujvqluktamaurafberdcua lwrkcbnlllycaorcfklebodkrjuapdbdforulqosofieeqcpzaebuqmuthdurvtpkbmageurlzbiwkaymcvctfhuzprajtlrqjdih wdbyrdzneneydomipmrjoposrgjvdwmeijrnozapnroqtnayqbfdiojnddcijpdkkmglrwktpsyaoctpenqbmcooksjpeqfrjkgym wamcedyibsopqckcrdomrzgpirmfrdmdqonmyknpgrbnbkdotrejonyelioaqoksoinzgprtwfednvpjsntjdyoadkwyjjjqpjepm bwfgxpbxiztsasxkhvdwuhtylvzcmctwxfjahbnbbolcbysbtxfmmrlvptqpvrxfbvfoqjwgrsarvngvigmixlcfpvqyrhcddjiyv qpjbwvrvgbccptmwxofuqvvltpxacrsanwcmjbkolyhjzbithyqhvxfrsttdmzdbilmhvrfcwrvafygipgbvfnblxvxsybfgsxdxi gozvqtqxmpjqjftuvbaevdkmjtzylyyjsryfahzsotygxsuzihfwfzfmrvvcaqejpkjqzxyzeoxotdabpmmbknycvvkqlpxpkfory jvaboapseayzbymyjfvkrozyutvqqsjfxjxfqnttuvejyhqiqzctlfkyxrcmvxjmdooksdvyzrlhpakpbfpzfpgvkgmyzzqmtoxew ishatpmxygjhxnndyzmmhpjregfmdvtfstgiojcxbstwcghtuckftwrwchepgojxkfgwnynximhnnovhdytmrtiugcmzkwweuudoi fekopnynwgjvyojnizxcxmustpihhursiwhdhegrcgtkimxutmbgfchoeawmdmwfpkwwyhxdnftthsiuzmtmgtcjvngntrcoxydgj ehigvxohaivehtdemdjofhkjrxtzsukaccxzyjpufyspfokjxkxztrcmchykhiwfnsgibnjfagntdowkpcogndrafknymzsrkqnelkfrfoltkhfvrwguwpgbkwovfyqpnzmagiakbaduurkgsdeylqemfjklglybdihxptzzxcffqqfoykfrtexhqxdpuwnqjwrnyugkrghwvazaihvjtofrcympsvgaeuorctqmabkokqmwraifdwmphxbbdqjm gyotpajrrtelqgfezwacfvsinulknmzfpfrplwjxzawkarxkgiookfokjvxbhdqcphohcqmxfdwxksohgrhybzhtrfeksrqedznggxxfamjorwyomaqnliyapdnhvypfkzcdyjknnyxstpyrvggmhxcwrbpfguomksffqyrzhrcmukqaaabaehugifowtpdxiakuhtowvwttnkdbcjtuzfvueieukgdkmfncfwbmjkkdisblrkmhyigqfqvejjqd lbudhpvhdrlsqmwhsrlzozowdkpesrawprfoqdilpcacboqdxbohnpgeogcqtlhruidvytylckgpdfnfqqvstivzkduttqjgfifcglhajmnzithbyzohiviwuudohppebyqnvhogsqwtywyfegkryxpjphoipiunnhfsbkdsieoqyebluppatgsawnwsaieujsxmanysxcdmjvvymcbqsxiqlihxidajwqrthhjhfncwoxmwumguvhtvxjtgoimd tqzgsaafjtieekfrsjmxcvqshtxlyltqyoqwdwwowlszlhktiovciigewsdpwxcnhgglwmslcjinnsluxsooimkrpuytupgohfhycdpvcmshxfebqcxpaodiawfsgbwhqahdnvnrvmtqiddmjopdtxhvbwgqvhaihhhkiwjxfnidertpujupoiqrspavyjcqguhdedbpzhnyhhjbuiytqorrgypbbinslmfyqvpykziatulogfdmdqbunpeuzvoo ryhphfyvyzgaabyqjyjhbsfixgxwdubtlljgjlmzlrbnsmkvjuxgszafnayywvrcbwmttocfppxhbjcqpvyunxkfvinfhnozgvolcowbcppvejiiljiagdmwxvrsblzxsyrsnaivkbnffdduwzkgtpvhmbxavzdcrhpxhnzzcupmekvufvfcfpxnqyoiruofwddwjzihffuvmfeyelwevqbjtsrkujalsambaepbajziptrujjorwhcozmegohho fafdfvzedydrkyuudnngnzftohdwjrcvyfbtdwbjcmapgmeffpxicrvjuhszpvpplcrqkojvwbatngxizzkrdaehovampctaptrjgsyubawbvuirkvmzoziyozhbhurnflqmplsbhhhllhbxswrxbflxyylruyoftvpwephjowzaiajfehgkyiyobgxemobmjopmnufwswjxpqbsanjjficcmqvxzvfilucbjhcvuwenxzlsvvsxfznyvkjgjagi zpsnvzghldshvllfrnwjwltecaopsuuucrnsjggcsirymywtmdzpmdoqylbtjavdtvwviohvjtldjdwjoumffmzjjmltcjqtjsryualzqfjdrcunbmquirqcdpcedlyznzkgtrpxldelkmogiutyfjwntjvzfmowcjzlnrivtlajrpowkxykbsxzvhsahsigobkunfxashtcbqmepiyhbuuyfwrbfoknivocyivznnethpcbmztyxfvekqfejcfe oyetfwkgskcygvszugygtumojmljdcrhnlljgomnrzubcjjlcnyzvzfuyshdchxytbiljjirvvxdkfosfuitdedocwlnsmjmbemowpftabyltjumlwfzfufkurozzichcqwkqasdnimvdbdsjfpmhrkhlnzisvjpapmyrwedcgmudtqtjvtqwluawtqviktxnzyirlspqbnthfxtapbescjvcbohyqejfialrznrojnlfeevxrnpzczvtvyojupw hhhhyyvnnbqgmiiaaabzoamiudppplwhmjkwjxstcgzprhjknhijcpqqwmcpkbzlngugifmdzyclsokhgogtntheztvwmugitijbmukjllxsgcazdwlfwyzhbkkvhdllfzhpnltfbbijcrpxyjpupqifevxxfbhzqjfjqfgadwgumqxkcocugjdwxkhorjsspdswqlzsdobtjeucpbfthumsscmfwkovwljvunikttgcgcawsevmlfhcpeupwazs pdqpkzdfmlkjqagwmkyohwdkbchinefzcjmsngxbuptsultmytgagjkfvkscjdlswuujbrachvspfmlfgwplqfipeaobiiupghyoxeswuqschtrccwzpijcbotklzjmtvhgljfzerujmafwvphuhkcfhixacjalxjhlsxshzzdgwiqopxmdvtwhkfzwbgfsknvmgwthogbbvtphuwyqpmtpuqcobwkjihisldelcphylajcdigqbxunzjnmgznnz ``` [Answer] # CJam, ~~58,598~~ ~~58,494~~ ~~57,898~~ ~~57,772~~ ~~57,704~~ 57,680 moves This approach takes the family of *all* unordered sets of horizontal moves of minimum cardinality (with some false positives) and adds the minimum number (over all sets) of vertical moves required to avoid superpositions. If the resulting number of horizontal moves is suboptimal (a false positive), it starts adding more vertical moves until the number of horizontal ones is optimal. Finally, it orders the generated moves to form a valid sequence. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%5Bl%3AAl%3AB%5D%7B%7B%7B%3ALee%7B~_%40L%3Ce%3Da%2B%7D%25%7D%2Ff%7B%5Ca%23%7Dee%7D%3AI~%3A%3A-%3Az%3A%2B%7D%3AC~%3AO%3B%0AA%2C2m*%7B%3AP%5BAB%5D.%3D%3A%3D%7B%5BAP0%3D'_tBP1%3D'_t%5DCO%3D%7D0%3F%7D%2C%3AM%3B%0A%5BA%2C%2C_%5DQ%7B_%3Ae%26%7B_0f%3D%3APM%5Ce%3D%7BPa%5C1f%3Ej%2B%7D%7B_2%2CW%25.%3Ej%5C2%2C.%3Ej_%2C2%24%2C%3C%40%40%3F%7D%3F%7D%7B%3BQ%7D%3F%7Dj%0AW%5C%2BW%2B%3AG%2C%2C%7BG%5CWtW-%3AHz%5BAB%5D%5C.%7B%7B'_t%7D%2F%7D%3ATCO%3D%7D%23%3B%0ATIH-%7B_1%3D%5C%3A%3E2*(*%7D%24%7B_%3A%3E%3AD%3B~%5C%3AI%22%3Ad%20%3Au%20%223%2Ff%2BDm%3E~o%5CI-z%22%3Ar%20%3Al%20%223%2FD%3DI%5C%2B*o%7D%2F%0AH%7B%5B~%5C%3AII%40I-_ga%5Cz*~%5D%7D%25%7B%7B2%3E%7D%2C_%7D%7B_0f%3D%3AP%3B%7B__%2C(%25%3A%2B%3AJP%26%7B_1%3Do'%3Ao)0%3E%22lr%22%3DS%2Bo0JtPJ%2B%3AP%3B%7D%7C%7D%25%7Dw&input=xaxxbycydyye%0Ayyabcydxxxey). ### Animated test cases [Test case 1](https://jsfiddle.net/gj08tznh/embedded/result/) | [Test case 2](https://jsfiddle.net/gj08tznh/1/embedded/result/) | [Test case 3](https://jsfiddle.net/gj08tznh/2/embedded/result/) | [Test case 4](https://jsfiddle.net/gj08tznh/3/embedded/result/) | [Test case 5](https://jsfiddle.net/gj08tznh/4/embedded/result/) [Test case 6](https://jsfiddle.net/gj08tznh/5/embedded/result/) | [Test case 7](https://jsfiddle.net/gj08tznh/6/embedded/result/) | [Test case 8](https://jsfiddle.net/gj08tznh/7/embedded/result/) | [Test case 9](https://jsfiddle.net/gj08tznh/8/embedded/result/) | [Test case 10](https://jsfiddle.net/gj08tznh/9/embedded/result/) *Thanks to [@Doorknob](http://chat.stackexchange.com/transcript/message/22290981#22290981) for his help with the animations.* ### Test cases ``` $ time for f in xx*; do python3 val.py $f <(cjam prog.cjam < $f); done move sequence verified with step count 156 move sequence verified with step count 126 move sequence verified with step count 120 move sequence verified with step count 124 move sequence verified with step count 112 move sequence verified with step count 2228 move sequence verified with step count 1862 move sequence verified with step count 2066 move sequence verified with step count 1738 move sequence verified with step count 1932 move sequence verified with step count 8200 move sequence verified with step count 10770 move sequence verified with step count 10360 move sequence verified with step count 8716 move sequence verified with step count 9170 real 0m22.672s user 0m37.372s sys 0m1.869s ``` ### Pairing characters Let's analyze the following example (provided by [@randomra](http://chat.stackexchange.com/transcript/message/22045278#22045278)): ``` 012345678 axabababa abababaxa ``` By inspection, it suffices to swap the **x** with the **b** that takes its place, which can be done in 16 moves: ``` 1:u 1:r 1:r 1:r 1:r 1:r 1:r 7:d 7:l 7:l 7:l 7:l 7:l 7:l 1:d 7:u ``` The minimum number of horizontal moves can always be achieved by pairing the nth occurrence of each letter in the first line with the nth occurrence in the second line. However, this is highly suboptimal in this case, since we have to add too many vertical moves to avoid superpositions. The letter **x** occurs only once and there is only one optimal choice for pairing the **a**s, so we already know which horizontal moves will be required to get them to their targets. However, the letter **b** is trickier: ``` 012345678 b b b b b b ``` Pairing the **b**s in order would require moving either the **b**s itself or the **a**s between them either up or down, since no **b** can take the place currently occupied by an **a**. The right choice is to pair the **b** at index 7 of line 1 with the **b** at index **1** of line 2 and not to move the other **b**s at all. We'll refer to the pairings by their initial and final position, which are **[7 1]**, **[3 3]** and **[5 5]** in our example. But how to find these pairings? In theory, we could just go through all sets of possible pairings for each letter and select the set that requires the least amount of total moves. However, for a letter that occurs **n** times, there are **n!** possible sets of pairings, which is impractical. In this approach, we determine all possible pairings of two letters that, by themselves, won't increase the number of horizontal moves. To achieve this, we take all possible pairs of letters of lines 1 and 2 and, if the letters are the same, replace both by an underscore and determine to number of moves needed to move nth occurrences to nth occurrences. For our example, this yields the following: ``` [0 0] [1 7] [2 2] [3 1] [3 3] [4 4] [5 1] [5 3] [5 5] [6 6] [7 1] [7 3] [7 5] [8 8] ``` As we already knew, the letters at indexes 0, 2, 4, 6 and 8 (the **a**s) should not be moved horizontally and the **x** has to move from index 1 to index 7. For the **b**s, there are several choices to be considered. The **b** at index **3**, for example, can move to index **1** or index **3**. To minimize the number of vertical moves over all possible sets of pairings, we select as many non-overlapping pairings as possible, since moving the corresponding characters to their destinations will require no vertical moves at all. Finding these proper pairings is a variant of the [longest common subsequence problem](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem). and can be done as follows. We start by replacing the letters of each line by their indexes: ``` 012345678 012345678 ``` The first column (**[0 0]**) is one of the precomputed pairings, so we select it and remove it from the lines. We now have ``` 12345678 12345678 ``` The pairing **[1 1]** is invalid (**x** would stay in its position). We now remove the first element of the line 1 and the first element of line 2 (not simultaneously) and apply the process exemplified above to ``` 2345678 12345678 ``` and ``` 12345678 2345678 ``` The higher amount of pairings resulting from the two choices will get appended to **[0 0]**. Thanks to memoization, CJam completes this recursive process almost instantly. For our example, this selects the following pairings: ``` [0 0] [2 2] [3 3] [4 4] [5 5] [6 6] [8 8] ``` This way, all letters except the **x** and the **b** that takes its place won't have to move at all. ### Moving characters Consider the input ``` 0123456789AB xaxxbycydyye yyabcydxxxey ``` for which the moves ``` [1 2] [4 3] [6 4] [7 5] [8 6] [10 11] ``` get selected. The corresponding characters won't have to move vertically and we can pair the remaining characters in order. To implement the pairing, we use the same algorithm we have already used to determine the minimum number of horizontal moves. We start by replacing characters corresponding to selected pairings with underscores: ``` 0123456789AB x_xx_y___y_e yy_____xxxe_ ``` Now, we enumerate each character's occurrences on both lines: ``` ['x 0] ['_ 0] ['x 1] ['x 2] ['_ 1] ['y 0] ['_ 2] ['_ 3] ['_ 4] ['y 1] ['_ 5] ['e 0] ['y 0] ['y 1] ['_ 0] ['_ 1] ['_ 2] ['_ 3] ['_ 4] ['x 0] ['x 1] ['x 2] ['e 0] ['_ 5] ``` Now, we compute the indexes of all pairs in both the second and first line: ``` [0 7] [1 2] [2 8] [3 9] [4 3] [5 0] [6 4] [7 5] [8 6] [9 1] [10 11] [11 10] ``` As before, the pair **[0 7]** means that the character at index 0 has to move to index 7. We eliminate the pairs that had been selected been selected before and examine the remaining pairs: ``` [0 7] [2 8] [3 9] [5 0] [9 1] [11 10] ``` We divide these pairs into two groups, differentiating between characters that move left and those who do not: ``` [0 7] [2 8] [3 9] [5 0] [9 1] [11 10] ``` Now, we move each character from the second group one unit up and then right until it is below its target. To avoid superpositions, we sort the characters by their final positions (rightmost comes first). Similarly, we move each character from the first group one unit down and then left until it is below its target. Again, we sort the characters by their final positions (leftmost comes first). With the vertically moving characters out of the way, we can move the characters of the firstly selected pairs to their destinations. We already know how many times we have to move each character in which direction; what is left to figure out is the correct order of these moves. There are several ways of doing this. My implementation simply removes all characters that are already at its destination, moves each character one unit towards its destination if that position is not occupied and repeats the process. For the pairs ``` [1 2] [4 3] [6 4] [7 5] [8 6] [10 11] ``` this gives the following move order: ``` 1:r 4:l 6:l 10:r 6:l 7:l 7:l 8:l 8:l ``` Finally, we move each character that has moved vertically one unit down or up to reach its destination. ### False positives A cornerstone of this approach is the way it differentiates "good" from "bad" pairings. A good pairing, by itself, won't increase the number of horizontal moves. However, we select several of these pairings to minimize the number of vertical moves. Certain combinations of good pairings *can* increase the number of horizontal moves, leading to suboptimal results. The following example illustrates this. ``` 01234567 a a a a a a ``` For this input, we obtain this list of good moves: ``` [0 3] [0 5] [0 7] [2 3] [2 5] [2 7] [4 5] [4 7] ``` Indeed, neither **[0 5]** nor **[2 7]** is a bad move by itself. However, if both moves get selected, we are forced to use the paring **[4 3]**, which is a bad move since **a** goes in the wrong direction. We define a false positive in the selection of pairings as a set of good moves that force us to select a bad one later. These false positives seem to be rather uncommon. Of all fifteen test cases, there was only one false positive. In the eleventh test case, the distribution of the letter **h** is the following: ``` h h h h h h h h h H H h h h h h h h h h H H h h ``` The uppercase **H**s highlight two good pairings that both get selected and cause the **h**s between them to make a bad pair. For the general case, we'd either have to avoid these false positives during the selection process or remove the good pairs that caused them afterwards and repeat the selection. For the test cases, it suffices to proceed as follows: 1. After selecting all pairings, count the number of horizontal moves we have to make. 2. If it is suboptimal, remove each pair of the selection and recount. 3. If the number of horizontal moves is optimal after removing one of the pairs, remove it permanently. 4. If no pair can be removed to achieve the minimum number of horizontal moves, give up and keep all original pairings. Step 4 is never reached for the test cases. ### Code ``` [l:Al:B] e# Read two lines from STDIN and store them in A and B. { e# Define a function: { e# Define a function: { e# For each line: :Lee e# Save the line in L and enumerate its characters. { e# For each pair (index, character): ~_ e# Dump the pair and copy the character. @L< e# Cut L off at that index. e= e# Count the occurrences of the same character to its left. a+ e# Push the pair (character, occurrence). }% e# This turns "aba" into [['a 0] ['b 0] ['a 1]]. }/ e# f{\a#} e# Push the indexes of the pair of line 1 in line 2. ee e# Enumerate them. e# This turns ["aba" "baa"] into [[0 1] [1 0] [2 2]]. }:I~ e# Name the function I and execute it. ::-:z e# Compute the absolute difference of each pair. :+ e# Add those differences. }:C~ e# Name the function C and execute it. e# C counts the minimum number of horizontal moves to get each e# character to its destination. :O; e# Save the result for the original input in O. A,2m* e# Push an array of all pairs of non-negative integers below len(A). { e# Filter those pairs: :P[AB].= e# Save a pair in P and select the corresponding chars of A and B. := e# Check if the characters match. { e# If they do: [ e# AP0= e# Push A and the first index of P. '_t e# Replace the corresponding char of A with an underscore. BP1= e# Push B and the second index of P. '_t e# Replace the corresponding char of B with an underscore. ] e# C e# Execute C on the modified lines. O= e# Check if the minimum over the modified lines matches O. } e# 0? e# Else, push 0. }, e# If the result was 1, keep the pair. :M; e# Save the result in M and pop it form the stack. e# M contains all possible pairings of characters of line 1 and line e# 2 that do not increase the minimum number of horizontal moves. [A,,_] e# Push the array [[0 ... len(A)-1][0 ... len(A)-1]]. Q{ e# Set up a memoized recursive function j: _:e& e# Check if if both arrays are non-empty. { e# If they are: _0f=:P e# Retrieve the first element of each array and save in P. M\e= e# Check if P belongs to M. { e# If it does: Pa\ e# Push [P] and swap it with the arrays. 1f>j e# Remove P from the arrays and execute j. + e# Concatenate [P] and the result of j. }{ e# Else: _2,W% e# Copy the arrays and push [1 0]. .> e# Vectorized tail. Removes the first element of array 1. j e# Execute j on the result. \2, e# Swap with the arrays and push [0 1]. .> e# Vectorized tail. Removes the first element of the array 2. j e# Execute j on the result. _,2$, e# Push the lengths of both results of j. <@@? e# Select the longer array. }? e# }{ e# Else: ;Q e# Remove the arrays and push an empty array. }? e# }j e# Execute j on the initial arrays. e# This pushes a set of non-overlapping pairings of maximal size. W\+W+ e# Prepend and append -1 (dummy value) to the pairings. :G,, e# Save in G and push [0 ... len(G)-1]. { e# Find in G: G\Wt e# Replace the element in G at that index with -1. W-:H e# Remove all -1's and save the result in H. z e# Zip the array of parings. This groups the indexes of the first e# line in one array and the indexes of the second line in another. [AB]\ e# Push the array of lines. .{ e# Vectorized foreach: {'_t}/ e# Replace the corresponding characters by underscores. } e# :T e# Save the result in T. CO= e# Count the minimum number of horizontal moves and compare with O. }# e# Stop if they match. ; e# Discard the index returned by {}#. e# This saves G itself in H if the number of horizontal moves was e# already optimal and discards at most one element of G to achieve e# optimality. T now equals [A B], where characters that will e# move only horizontally have been replaced by underscores. TIH- e# Execute I on T and remove the elements from H. e# This pairs all characters that will have to move vertically. { e# Sort by the following key: _1= e# Retrieve the second element (index of line 2). \:> e# Push 1 if the index of line 1 is bigger than the one of line 2. 2*( e# 1 -> 1 and 0 -> -1 * e# Multiply by the index of line 2. }$ e# This sorts the pairings by direction, then final position. { e# For each pair [X Y]: _:>:D; e# Set D := 1 if X > Y and D :=0 otherwise. ~\:I e# Save X in I. ":d :u " e# Push that string. 3/ e# Split it into [":d " ":u "]. f+ e# Prepend I to both strings. Dm> e# Swap the order of the array's elements if D == 1. ~o e# Dump the array and print its second element. e# The first element will be left on the stack. CJam will print it e# after executing the rest of the program. \I-z e# Compute abs(Y - I). ":r :l " e# Push that string. 3/ e# Split it into [":r " ":l "]. D= e# Retrieve the string at index D. I\ + e# Prepend I. *o e# Repeat the string abs(Y - I) times and print. }/ e# H{ e# For each pair in H: [ e# ~\:I e# Save the initial position in I. I@I- e# Subtract the initial position from the final position (D). _ga e# Push [sign(D)]. \z*~ e# Repeat the array abs(D) times and dump it. ] e# }% e# The result contains I twice, followed by abs(D) copies of sign(D). { e# {2>}, e# Filter out elements with length two. _ e# Push a copy. }{ e# While the copy is non-empty: _0f=:P; e# Save the positions the elements currently occupy in P. { e# For each array: __,(% e# Retrieve the first and last element (position, direction). :+:J e# Add them and save the result in J. P& e# Intersect with P. { e# If J is not in P: _1=o e# Print the character's identifier. ':o e# Print a colon )0> e# Retrieve the direction. "lr"= e# Push 'l' or 'r'. S+o e# Append a space and print. 0Jt e# Save the new position in the array element. PJ+ e# Append the new position to P. :P; e# Save in P. }| e# }% e# }w e# ``` ]
[Question] [ Your boss just emailed you a list of 12 programming tasks he needs done as soon as possible. The tasks are simple enough but your boss, being a young software tycoon suckled by social networking, insists that your solutions be able to fit within a single [Twitter](https://en.wikipedia.org/wiki/Twitter) tweet. This means that you only have 140 bytes worth of code to solve all the tasks, an average of 11.67 bytes per task. (Yes, Twitter [counts characters](https://dev.twitter.com/overview/api/counting-characters) but your boss specifically said bytes.) You realize there's no way to solve all 12 tasks in 140 bytes but you suspect that your boss won't actually test all your solutions. So you proceed to solve as many tasks as you can, completely skipping some of them. Your mindset is that it doesn't matter *which* subset of the tasks you complete, it only matters that the subset is *as large as possible*. How many tasks can you complete? # Challenge Write up to 12 different programs, each of which accurately solves one of the 12 tasks listed below. The cumulative sum of the lengths of these programs may not exceed 140 bytes Alternatively, you may write a single program no greater than 140 bytes long that takes an integer from 1 to 12 and (ideally) proceeds to solve the corresponding task, taking more input as necessary. Not all the tasks need to work, but only the ones that do count towards your score. Tasks that don't work are allowed to error or do anything else. In either case a "program" may in fact be a function that takes the input as arguments or prompts for it and prints or returns the output. So, for example, you might write a 140 byte function that looks like `f(taskNumber, taskInput)`, or you might write separate code snippets for each task, some as functions and some as fully-fledged programs. **Other details:** * All code must be written in the same language. * As usual, input should come from stdin, the command line, a function argument, or whatever is usual for your language. Output is printed to stdout or your language's closest alternative, or returned in an appropriate type. * A reasonable amount of input formatting is fine; e.g. quotes around strings or `\n` instead of actual newlines. * Output should be exactly what is called for with no extraneous formatting or whitespace. The exception is an optional single trailing newline. * Code that only runs in a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) environment does not constitute a program or function. * You may not write multiple programs that solve multiple tasks. It's either one program that (ideally) solves all the tasks, or (ideally) 12 programs that each solve a single task. * Posting a task solution that you didn't write or only slightly modified is not allowed without giving attribution to the original author, and ideally getting permission too. If your answer primarily composes the shortest solutions from all the other answers then it should be a community wiki. # Scoring The submission that completes the most tasks is the winner. If two submissions tie, the one with the fewest bytes wins. If the byte counts are tied, the earlier submission wins. Community wiki answers are not allowed to win. Be sure to tell us which tasks you solved, not just how many! **Handicap for non-golfers:** It's likely that this challenge will be dominated by [golfing](https://en.wikipedia.org/wiki/Code_golf) languages. Many languages may have trouble solving even one or two tasks within 140 bytes. Therefore you may submit a **non-competitive** answer where the limit is 3 tweets, i.e. 420 bytes. All the other rules remain the same. # Tasks ### Task 1 - Can Three Numbers Form A Triangle? Take in three positive integers and output a [truthy/falsy](http://meta.codegolf.stackexchange.com/a/2194/26997) value indicating whether or not three lines with those lengths [could form a triangle](http://www.mathwarehouse.com/geometry/triangles/triangle-inequality-theorem-rule-explained.php). You may not assume the numbers come in any particular order. Truthy examples (one per line): ``` 20 82 63 1 1 1 2 3 4 1 2 2 ``` Falsy examples: ``` 6 4 10 171 5 4 1 1 2 1 2 3 ``` --- ### Task 2 - Closest To One Million Given a string of exactly 7 decimal digits (0-9), rearrange them to get a number that is as close as possible to one million. That is, `abs(1000000 - rearrangedNumber)` should be minimized. Print or return the resulting number as an integer, not a string (so there shouldn't be leading zeroes unless that's the norm for your language). e.g. an input of `9034318` should result in `984331` (and not `1033489`). `2893984` should become `2348899`. `0001000` should become `1000000`. `0000020` should become `200000`. --- ### Task 3 - Simple Keyboard Simulator Take in a string of lowercase letters (a-z), spaces, and angle brackets `<>`. Read left to right, this string represents the keys that were pressed on a standard keyboard while an initially empty text editor was open. The letters and space correspond to their normal keys but `<` corresponds to the left arrow key and `>` to the right arrow key, both of which move the [cursor](https://en.wikipedia.org/wiki/Cursor_(user_interface)) when pressed. `<` moves the cursor one character left, or does nothing if the cursor is at the start of the string. `>` moves the cursor one character right, or does nothing if the cursor is at the end of the string. Output the string that would be in the text editor once all the keys in the input string have been pressed. Outputting [escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) to move the cursor is not allowed. There will always be at least one non–arrow key character in the input. e.g. the input `ui<<q>>ck <<<<<<the<<<<>>> >>>>>>>>brown x<o<f` should yield `the quick brown fox`. `op<<l>>t<<<lam>>>>>>imi<<<><>>>zer<<<<<<<<<<<<<<<<<<>>><>m` should give `llammoptimizer`. `e< <c<b<a` should give `abc e`. `<<<>><><<><toast>><<>><><<>><` should give `toast`. --- ### Task 4 - FILTHE Letters In many fonts, 6 of the uppercase English alphabet letters consist entirely of horizontal and vertical lines: `E`, `F`, `H`, `I`, `L`, and `T`. We'll calls these the FILTHE letters. Take in a string of uppercase letters (A-Z) and count the number of lines in the FILTHE letters, outputting the resulting integer. `E`, `F`, `H`, `I`, `L`, and `T` have 4, 3, 3, 3, 2, and 2 lines respectively. e.g. `GEOBITS` has 4 + 3 + 2 = 9 lines part of FILTHE letters (for `.E..IT.`), so the output should be `9`. `ABCDEFGHIJKLMNOPQRSTUVWXYZ` should output `17`. `ABCDGJKMNOPQRSUVWXYZ` should output `0`. `FILTHYLINESINLETTERS` should output `39`. --- ### Task 5 - Alex [Recursive](https://chat.stackexchange.com/transcript/message/24622365#24622365) A. Our moderator [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) has a fairly mysterious initial, "A". Now I'm not certain, but I think the `A.` stands for `.A xelA`. And I'm also pretty sure that the `.A` there sneakily stands for `Alex A.`. Thus to get Alex's full name we must expand out the `A.`'s and `.A`'s: ``` Alex A. -> Alex [A.] -> Alex [.A xelA] -> Alex .A xelA -> Alex [.A] xelA -> Alex [Alex A.] xelA -> Alex Alex A. xelA -> etc. ``` Have your program take in a non-negative integer and expand `Alex A.` that many times, outputting the resulting string. So `0` becomes `Alex A.`, `1` becomes `Alex .A xelA`, `2` becomes `Alex Alex A. xelA`, `3` becomes `Alex Alex .A xelA xelA`, `4` becomes `Alex Alex Alex A. xelA xelA`, `5` becomes `Alex Alex Alex .A xelA xelA xelA`, and so on. (I made this because I felt bad for inadvertently leaving Alex out of my [mod tribute challenge](https://codegolf.stackexchange.com/q/55574/26997). :P) --- ### Task 6 - Numpad Rotation Take in an integer from 1 to 9 inclusive (you may take it as a string). Output the 3×3 square of digits ``` 789 456 123 ``` rotated in increments of 90° such that the input digit appears anywhere on the top row. When `5` is input any rotation is valid output since `5` cant be rotated to the top. e.g. when `3` is input, both ``` 963 852 741 ``` and ``` 321 654 987 ``` are valid outputs. For input `4`, only ``` 147 258 369 ``` is valid output. --- ### Task 7 - Splitting Digits Into Tens Take in a nonempty string of decimal digits (0-9) and output a truthy value if it can be broken up into contiguous sections where all the digits in each section sum exactly to 10. If this is not possible, output a falsy value. e.g. `19306128` can be split up like `19|3061|28`, the sections all summing to 10 (1+9, 3+0+6+1, 2+8), so a truthy value should be output. Truthy examples (one per line): ``` 19306128 073 730 0028115111043021333109010 2222255 ``` Falsy examples: ``` 6810410 9218 12341 5222225 000 ``` --- ### Task 8 - Square Clock Take in a consistently sized multiline string. Output `12` if the input is ``` _ _ | | | |_ _| ``` Output `3` if the input is ``` _ _ | |_| |_ _| ``` Output `6` if the input is ``` _ _ | | | |_|_| ``` Output `9` if the input is ``` _ _ |_| | |_ _| ``` There are no other input cases. --- ### Task 9 - Bracket Art Take in a 4 byte string containing one of each of the left brackets `(`, `[`, `{`, and `<` in any order. Add the corresponding right brackets so the string is 8 bytes long and has a vertical line of symmetry. e.g. `[<({` becomes `[<({})>]`. Then reverse every bracket in this string. e.g. `[<({})>]` becomes `]>)}{(<[`. Output the original 8 byte bracket string with the reversed version above and below on separate lines. So the final output for input `[<({` would be ``` ]>)}{(<[ [<({})>] ]>)}{(<[ ``` Similarly, the output for `<({[` should be ``` >)}][{(< <({[]})> >)}][{(< ``` The input `(<<[` is invalid because the `{` is missing and there is an extra `<`. --- ### Task 10 - Perimiterize Take in a rectangular grid of text (1×1 at smallest) made of `.`'s that represent empty space and `X`'s that represent solid tiles. Cells beyond the grid bounds are considered empty. You may assume each of the 4 grid edge rows and columns will contain at least one `X`. e.g. a valid input might be: ``` XXX.....X..... X..X...X.X.... XXX.....X....X ``` Output another rectangular grid of text where every empty cell that neighbors an `X` orthogonally or diagonally, **including those outside the input grid**, becomes `o`. So essentially a perimiter of `o`'s is drawn around all the portions of solid tiles. The new grid should not be any larger than it has to be. So the output of the example above would be: ``` ooooo...ooo..... oXXXoo.ooXoo.... oXooXo.oXoXo.ooo oXXXoo.ooXoo.oXo ooooo...ooo..ooo ``` Similarly, the output of input `XXX..X.X` should be ``` oooooooooo oXXXooXoXo oooooooooo ``` and outputting ``` oooooooooo. oXXXooXoXo. oooooooooo. ``` would be invalid since the empty rightmost column is unnecessary. You may use any 3 distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `.`, `X`, and `o`. --- ### Task 11 - Sator Square Output the [Sator Square](https://en.wikipedia.org/wiki/Sator_Square): ``` SATOR AREPO TENET OPERA ROTAS ``` Any of the letters may be lowercase or uppercase, so ``` SatOR aRePO tenet OPERa RoTaS ``` is also valid output. There is no input. --- ### Task 12 - Prime Tweet Take no input but output a 140 byte [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) string that contains at least one of each of the 95 printable ASCII characters. (So 45 characters will be duplicates.) The sum of the character codes of all 140 bytes in this string must be a [Sophie Germain prime](https://en.wikipedia.org/wiki/Sophie_Germain_prime), i.e. a prime number `p` such that `2p+1` is also prime. The character code for space is 32, 33 for `!`, 34 for `"`, and so on up to 126 for `~`. The sum could be calculated in Python as `sum(map(ord, myString))`. An example output is: ``` ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~STUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~d ``` The character code sum is the prime 12203 whose corresponding [safe prime](https://en.wikipedia.org/wiki/Safe_prime) is 24407. [Answer] ## CJam, ~~8~~ 9 tasks in 140 bytes First off, here is a script you can use to sort your solutions and tell you which ones will fit into the tweet: ``` {\s\Se[oSo}:F; qN/ee{W=,}${)_,_T+:T140>X*_{0:X;}*'=@11+*N+*o\~)YF_,ZFTZFoNo}/ ``` Just paste your 12 solutions into the input, one on each line. [Run it here.](http://cjam.aditsu.net/#code=%7B%5Cs%5CSe%5BoSo%7D%3AF%3B%0AqN%2Fee%7BW%3D%2C%7D%24%7B)_%2C_T%2B%3AT140%3EX*_%7B0%3AX%3B%7D*'%3D%4011%2B*N%2B*o%5C~)YF_%2CZFTZFoNo%7D%2F) The first column is the task number, the second its size (in *characters* - you'll have to fix this yourself if that is different from the byte count), the third the cumulative size. The programs which fit into the tweet are separated from the rest with a line of `===`. For me, the output looks like this: ``` 1 7 7 q~$~\-> 8 10 17 qDbJ%5/)3* 12 12 29 ',32>_51>'d 7 13 42 Aq{~-Ace|}/N& 2 15 57 qe!{~1e6-z}$0=~ 4 19 76 q"FIHEELT"3*H<fe=:+ 5 20 96 ".A"q~){" xelA"+W%}* 9 22 118 q_{_')>+)}%W%+_W%N@N3$ 11 22 140 "SATOR\AREPO\TEN"_W%1> ==================================== 6 25 165 9,:)s3/zq~))3mdg*{W%z}*N* 3 43 208 LLq{_'=-z({+}{'=>_)$\[{)@+\}{\(@\+}]=&}?}/\ 10 45 253 0XW]_m*qN/{'.f+W%z}4*f{\~@m>fm>N*}(\{8f^.e>}/ ``` So here are the tasks I can currently fit into the tweet. ### Task 1 - Can Three Numbers Form A Triangle? - ~~8~~ 7 bytes *Thanks to jimmy23013 for saving 1 byte.* ``` q~$~\-> ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQ~%24~%5C-%3E%0A%0A%7D%26%5DoNo%7D%2F&input=%5B20%2082%2063%5D%0A%5B1%201%201%5D%0A%5B2%203%204%5D%0A%5B1%202%202%5D%0A%0A%5B6%204%2010%5D%0A%5B171%205%204%5D%0A%5B1%201%202%5D%0A%5B1%202%203%5D) Input is expected to be CJam-style list. This is fairly straightforward: check if the largest side is shorter than the sum of the other two. Or equivalently, check that the shortest side is longer than the difference of the other two: ``` q~ e# Read and eval input. $~ e# Sort the values and dump them on the stack. \- e# Subtract the middle value from largest. > e# Check if the smallest value is greater than that. ``` ### Task 2 - Closest To One Million - 15 bytes ``` qe!{~1e6-z}$0=~ ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQe!%7B~1e6-z%7D%240%3D~%0A%0A%7D%26%5DoNo%7D%2F&input=9034318%0A2893984%0A0001000%0A0000020) Simple brute force: ``` q e# Read input. e! e# Get all permutations. { e# Sort by... ~ e# Evaluate the permutation to get its numerical value X. 1e6-z e# abs(X - 1,000,000) }$ 0= e# Pick the first element (which minimises the difference) ~ e# Evaluate it to get rid of the leading zeroes. ``` ### Task 4 - FILTHE Letters - ~~21~~ 19 bytes *Thanks to jimmy23013 for saving 2 bytes.* ``` q"FIHEELT"3*H<fe=:+ ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQ%22FIHEELT%223*H%3Cfe%3D%3A%2B%0A%0A%7D%26%5DoNo%7D%2F&input=GEOBITS%0AABCDEFGHIJKLMNOPQRSTUVWXYZ%0AABCDGJKMNOPQRSUVWXYZ%0AFILTHYLINESINLETTERS) The idea is to create a string which contains each of the FILTHE letters once for each of their orthogonal lines. This is done via some funny string manipulation: ``` q e# Read the input. "FIHEELT" e# Push this string. It first contains the 3-line letters, then the 2-line e# letters, where we include 'E' twice to make it count for 4. 3* e# Repeat 3 times: "FIHEELTFIHEELTFIHEELT" H< e# Truncate to 17 characters: "FIHEELTFIHEELTFIH". This is chosen such that e# it discards the third repetition of the 2-line letters. fe= e# For each character in the input, count its occurrences in this new string. :+ e# Sum them all up. ``` ### Task 5 - Alex Recursive A. - ~~27~~ 20 bytes ``` ".A"q~){" xelA"+W%}* ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0A%22.A%22Q~)%7B%22%20xelA%22%2BW%25%7D*%0A%0A%7D%26%5DoNo%7D%2F&input=0%0A1%0A2%0A3%0A4%0A5) Implemeting the substition of `A.` and `.A` directly is way too expensive. Instead, we notice that we only have to handle one case, if we reverse the string each time. Furthermore, prepending `Alex` (and a space) each time is equivalent to expanding the initial. We can save another byte by appending the reverse before reversing the string: ``` ".A" e# Start with ".A" (the -1st iteration if you like). q~) e# Read input, eval, increment (so the following block is run at least once.) { e# Repeat this block that many times... " xelA"+ e# Append " xelA". W% e# Reverse the string. }* ``` ### Task 7 - Splitting Digits Into Tens - ~~18~~ ~~16~~ 13 bytes ``` Aq{~-Ace|}/N& ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AAQ%7B~-Ace%7C%7D%2FN%26%0A%0A%5D%60'%22-o%7D%26No%7D%2F&input=19306128%0A073%0A730%0A0028115111043021333109010%0A2222255%0A%0A6810410%0A9218%0A12341%0A5222225%0A000) (With brackets around each output.) Not exactly user friendly: the truthy value is a single newline, the falsy value is the empty string. The basic idea is simple: add the digits to a running total which we reset whenever it hits exactly 10. The total must be zero at the end of the input. For a start it turns out to be shorter to the total at 10 and subtract the digits, resetting the total whenever we hit 0. However, we need to make sure that we don't return something truthy when the input is all zeroes. The shortest way I found to do that was to reset the total to the *character* with code point 10 (the linefeed), and then check at the end that we actually have that character on the stack, and not the number 10. This works, because both the integer zero and the character zero (the null byte) are falsy: ``` A e# Push a 10, the initial running total. q{ e# For each character in the input... ~- e# Evaluate the character to get the digit and subtract it from the total. Ac e# Push a linefeed character. e| e# Logical OR of the running total and the linefeed character (using e# short-circuiting). }/ N& e# Take the set intersection with the string containing a linefeed character. e# If the total is still a number of any character other than the linefeed, e# this will yield an empty string. Otherwise, the string will remain unchanged e# and the linefeed will be printed. ``` ### Task 8 - Square Clock - 10 bytes ``` qDbJ%5/)3* ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F3%2F%7BN*%3AQ%7B%0A%0AQDbJ%255%2F)3*%0A%0A%7D%26%5DoNo%7D%2F&input=%20_%20_%0A%7C%20%7C_%7C%0A%7C_%20_%7C%0A%20_%20_%0A%7C%20%7C%20%7C%0A%7C_%7C_%7C%0A%20_%20_%0A%7C_%7C%20%7C%0A%7C_%20_%7C%0A%20_%20_%0A%7C%20%7C%20%7C%0A%7C_%20_%7C) This is just some pretty random modulo magic on the character codes which happens to hash to the correct values. I'm fairly convinced that something shorter is possible, but it's the shortest I found (programmatically) for this kind of structure: ``` q e# Read the input. Db e# Treat the character codes of the string as digits in base 13. This maps the e# four inputs to the values: 2023940117708546863 e# 2023940113755405840 e# 2023940781838850791 e# 2023940113755390292 J% e# Take the result modulo 19. This gives [2, 5, 12, 18], respectively. 5/ e# Divide by 5 (rounding down). [0, 1, 2, 3], respectively. ) e# Increment. [1, 2, 3, 4], respectively. 3* e# Multiply by 3. [3, 6, 9, 12], respectively. ``` ### Task 9 - Bracket Art - ~~23~~ 22 bytes *Thanks to Sp3000 for saving 1 byte.* ``` q_{_')>+)}%W%+_W%N@N3$ ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQ_%7B_')%3E%2B)%7D%25W%25%2B_W%25N%40N3%24%0A%0A%7D%26%5DoNoNo%7D%2F&input=%5B%3C(%7B%0A%7B(%3C%5B%0A%3C(%7B%5B) Fairly straightforward. The mapping between the left and right brackets is done by adding 2 (or 1 for parentheses): ``` q_ e# Read input and duplicate. { e# Map this block onto each character... _')> e# Duplicate and check if it's not a parenthesis. + e# Add the result, leaving parentheses unchanged and incrementing the e# other bracket types. ) e# Increment again. }% W%+ e# Reverse and add to the original, giving the middle line. _W% e# Duplicate and reverse, giving the first line. N@ e# Push a linefeed, pull up the middle line. N3$ e# Push another linefeed, copy the first line. ``` ### Task 11 - Sator Square - 22 bytes ``` "SATOR AREPO TEN"_W%1> ``` [Test it here.](http://cjam.aditsu.net/#code=%22SATOR%0AAREPO%0ATEN%22_W%251%3E) Probably the most boring solution of all. It pushes the first half of the string and then reverses it: ``` "SATOR AREPO TEN" e# Push everything up to the centre of the square. _W% e# Duplicate and reverse. 1> e# Discard the "N", because we don't want that twice. ``` ### Task 12 - Prime Tweet - ~~13~~ 12 bytes ``` ',32>_51>'d ``` [Test it here.](http://cjam.aditsu.net/#code='%7F%2C32%3E_51%3E'd%0A%0A%5Ds_oNoNo%22Sum%20(S)%3A%20%22o1b_p%22Is%20Prime%3F%3A%20%22o_mpp%222S%20%2B%201%3A%20%22o2*)_p%22Is%20Prime%3F%3A%20%22omp) (With diagnostic output for the result.) After `'` there's the unprintable `<DEL>` (0x7F), which SE strips out. For copy-pasting, use this version instead: ``` '~),32>_51>'d ``` The printed string is ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~STUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~d ``` That is, it contains one run of all characters, followed by another run from `S` to `~`, followed by a single `d`. The sum of the character codes is 12203. I found this via a bit of trial and error. ``` '~),32> e# Push a string with all printable characters. _51> e# Duplicate this and discard the first 51 of them. 'd e# Push a "d". ``` [Answer] # Pyth, 9 tasks in 138 bytes This took quite a while. I think 9 tasks is the limit for Pyth. Including the next shortest program (Sator Square) results in 160 bytes. Golfing 20 bytes is quite unlikely. There are 2 or 3 tasks which are a little bit ugly and maybe can be shortened, but overall I'm quite pleased with the solutions. ### Task 1 - Can Three Numbers Form A Triangle?, 8 bytes ``` >FsMc2SQ ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?test_suite_input=20%2C%2082%2C%2063%0A1%2C%201%2C%201%0A2%2C%203%2C%204%0A1%2C%202%2C%202%0A6%2C%204%2C%2010%0A171%2C%205%2C%204%0A1%2C%201%2C%202%0A1%2C%202%2C%203&test_suite=0&input=20%2C%2082%2C%2063&code=%3EFsMc2SQ) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=20%2C%2082%2C%2063%0A1%2C%201%2C%201%0A2%2C%203%2C%204%0A1%2C%202%2C%202%0A6%2C%204%2C%2010%0A171%2C%205%2C%204%0A1%2C%201%2C%202%0A1%2C%202%2C%203&test_suite=1&input=20%2C%2082%2C%2063&code=%3EFsMc2SQ) ### Task 2 - Closest To One Million, 14 bytes ``` ho.a-^T6NsM.pz ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?test_suite_input=9034318%0A2893984%0A0001000%0A0000020&test_suite=0&input=9034318&code=ho.a-%5ET6NsM.pz) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=9034318%0A2893984%0A0001000%0A0000020&test_suite=1&input=9034318&code=ho.a-%5ET6NsM.pz) ### Task 4 - FILTHE Letters, 20 bytes ``` s*Vtsmmdd5/Lz"TLIHFE ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?test_suite_input=GEOBITS%0AABCDEFGHIJKLMNOPQRSTUVWXYZ%0AABCDGJKMNOPQRSUVWXYZ%0AFILTHYLINESINLETTERS&test_suite=0&input=GEOBITS&code=s%2AVtsmmdd5/Lz%22TLIHFE) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=GEOBITS%0AABCDEFGHIJKLMNOPQRSTUVWXYZ%0AABCDGJKMNOPQRSUVWXYZ%0AFILTHYLINESINLETTERS&test_suite=1&input=GEOBITS&code=s%2AVtsmmdd5/Lz%22TLIHFE) ### Task 5 - Alex Recursive A., 16 bytes ``` u+"Alex "_GhQ".A ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?test_suite_input=0%0A1%0A2%0A3%0A4%0A5&test_suite=0&input=0&code=u%2B%22Alex%20%22_GhQ%22.A) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=0%0A1%0A2%0A3%0A4%0A5&test_suite=1&input=0&code=u%2B%22Alex%20%22_GhQ%22.A) ### Task 6 - Numpad Rotation, 20 bytes ``` jeo}zhN.uC_N3_c3jkS9 ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&test_suite=0&input=1&code=jeo%7DzhN.uC_N3_c3jkS9) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&test_suite=1&input=1&code=jeo%7DzhN.uC_N3_c3jkS9) ### Task 7 - Splitting Digits Into Tens, 15 bytes ``` qTu+WnGTvHG-zZZ ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?input=19306128&code=qTu%2BWnGTvHG-zZZ&test_suite=0&test_suite_input=19306128%0A073%0A730%0A0028115111043021333109010%0A2222255%0A6810410%0A9218%0A12341%0A5222225%0A000) or [Test Suite](http://pyth.herokuapp.com/?input=19306128&code=qTu%2BWnGTvHG-zZZ&test_suite=1&test_suite_input=19306128%0A073%0A730%0A0028115111043021333109010%0A2222255%0A6810410%0A9218%0A12341%0A5222225%0A000) ### Task 8 - Square Clock, 12 bytes ``` *3%%Cz1978 5 ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?input=%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%20_%7C&code=%2A3%25%25Cz1978%205&test_suite=0&test_suite_input=%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%20_%7C%0A%20_%20_%5Cn%7C%20%7C_%7C%5Cn%7C_%20_%7C%0A%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%7C_%7C%0A%20_%20_%5Cn%7C_%7C%20%7C%5Cn%7C_%20_%7C) or [Test Suite](http://pyth.herokuapp.com/?input=%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%20_%7C&code=%2A3%25%25Cz1978%205&test_suite=1&test_suite_input=%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%20_%7C%0A%20_%20_%5Cn%7C%20%7C_%7C%5Cn%7C_%20_%7C%0A%20_%20_%5Cn%7C%20%7C%20%7C%5Cn%7C_%7C_%7C%0A%20_%20_%5Cn%7C_%7C%20%7C%5Cn%7C_%20_%7C) ### Task 9 - Bracket Art, 20 bytes ``` V3_WtN+z_Xz"[<({})>] ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?input=%5B%3C%28%7B&code=V3_WtN%2Bz_Xz%22%5B%3C%28%7B%7D%29%3E%5D&test_suite=0&test_suite_input=%5B%3C%28%7B%0A%3C%28%7B%5B) or [Test Suite](http://pyth.herokuapp.com/?input=%5B%3C%28%7B&code=V3_WtN%2Bz_Xz%22%5B%3C%28%7B%7D%29%3E%5D&test_suite=1&test_suite_input=%5B%3C%28%7B%0A%3C%28%7B%5B) ### Task 12 - Prime Tweet, 13 bytes ``` ++*d44srd\\& ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?code=%2B%2B%2Ad44srd%5C%7F%5C%26) [Answer] # Pyth, 9 tasks in 136 bytes ## Task 1: 7 bytes ``` <-F_SQ0 ``` [Demonstration](https://pyth.herokuapp.com/?code=%3C-F_SQ0&input=23%2C+104%2C+82&debug=0) Sort in descending order (`_SQ`), fold subtraction over them (`a-b-c`), check if the result is negative. ## Task 2: 14 bytes ``` sho.a-sN^T6.pz ``` [Demonstration](https://pyth.herokuapp.com/?code=sho.a-sN%5ET6.pz&input=2043725&debug=0) Form all string permutations (`.pz`), sort them (`o`) based on the absolute value of the difference (`.a-`) between the number (`sN`) and one million (`^T6`). Take the first such string (`h`), and convert it to a num. (`s`). ## Task 4: 19 bytes ``` s/L+\EPP*3"EFHILT"z ``` [Demonstration](https://pyth.herokuapp.com/?code=s%2FL%2B%5CEPP%2a3%22EFHILT%22z&input=FILTHYLINESINLETTERS&debug=0) Replicate `"EFHILT"` three times (`*3`), remove the trailing `LT` (`PP`), and add an `E` (`+\E`). Map each letter in the input to its appearance count in that string. (`/L ... z`). Sum. (`s`). ## Task 5: 16 bytes ``` u+"Alex "_GhQ".A ``` [Demonstration](https://pyth.herokuapp.com/?code=u%2B%22Alex+%22_GhQ%22A.&input=3&debug=0) Starting with `"A."`, reverse and add an `"Alex "` to the start, input + 1 times. ## Task 7: 13 bytes ``` }Y-RTsMM./sMz ``` Convert the input string into a list of 1-digit numbers (`sMz`). Form all partitions (`./`). Sum each element of each partition (`sMM`). Remove all 10s from each sublist (`-RT`). Check if this emptied out any of the sublists by checking if the empty list is in the overall list (`}Y`). ## Task 8: 11 bytes ``` *3h%%CQC\Ç4 ``` [Demonstration](https://pyth.herokuapp.com/?code=%2a3h%25%25CQC%5C%C3%874&input=%22+_+_%5Cn%7C+%7C+%7C%5Cn%7C_%7C_%7C%22&debug=0) Modulo magic. Convert to number (`CQ`), take it mod 199 (`C\Ç` = 199), and take that mod 4. Then add 1, and multiply by 3. ## Task 9: 21 bytes ``` J+Xz"<{[()]}>")_zJ_JJ ``` [Demonstration](https://pyth.herokuapp.com/?code=J%2BXz%22%3C%7B%5B%28%29%5D%7D%3E%22%29_zJ_JJ&input=%3C%5B%28%7B&debug=0) First, we generate the first line, which consists of the input translated to the mirror characters (`Xz"<{[()]}>")`), followed by the reversed input (`+ ... _z`), and save it to `J`. Then print that line, its reverse, and that line again (`J_JJ`). ## Task 11: 22 bytes ``` +J"SATOR AREPO TEN"t_J ``` [Demonstration](https://pyth.herokuapp.com/?code=%2BJ%22SATOR%0AAREPO%0ATEN%22t_J&debug=0) Just print a string and its reversal, but don't duplicate the center `N`. ## Task 12: 13 bytes ``` ++G*19\3srd\ ``` [Demonstration](https://pyth.herokuapp.com/?code=%2B%2BG%2a19%5C3srd%5C%7F&debug=0) There is an invisble `DEL` (`7F`) character at the end of the code. This prints ``` abcdefghijklmnopqrstuvwxyz3333333333333333333 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` which has character sum `11321`. It consists of `G`, the alphabet, 19 `3`s, and all of the printable ASCII characters. [Answer] # TI-BASIC, 4 Tasks in 110 bytes # Task 1 in 7 bytes ``` :2max(Ans)<sum(Ans ``` Input is a list in `Ans`. # Task 4 in 35 bytes ``` :sum(int(2seq(inString("TLIHFE",sub(Ans,I,1))^.4,I,1,length(Ans ``` Input is a string in `Ans`. # Task 8 in 29 bytes ``` :18fPart(sum(seq(I(sub(Ans,I,1)=" ")/6,I,1,15 ``` Input is a string in `Ans`. # Task 11 in 39 bytes ``` :Disp "SATOR :Disp "AREPO :Disp "TENET :Disp "OPERA :Disp "ROTAS ``` --- Bonus round! Here are all the other tasks just for fun. # Task 2 in 92 110 bytes ``` :seq(expr(sub(Ans,I,1)),I,1,7→L₁ :SortA(L₁ :min(7,1+sum(not(L₁ :{L₁(1)+sum(seq(L₁(I))₁₀^(I-8),I,2,7)),L₁(Ans)+sum(seq((I>Ans)L₁(I)₁₀^(1-I),I,2,7 :ᴇ6Ans(1+(0>min(ΔList(abs(1-Ans ``` Prompts for a list of digits Input is a string in `Ans`. # Task 3 in 119 bytes ``` :Input Str1 :" →Str2 :For(I,1,length(Str1 :sub(Str1,I,1→Str3 :inString("<>",Ans :If Ans:Then :max(0,min(L,C+2Ans-3→C :Else :C+1→C :L+1→L :sub(Str2,1,C)+Str3+sub(Str2,C+1,L-C+1→Str2 :End :End :sub(Str2,2,L ``` Prompts for a string. Assumes C and L are either undefined or 0. # Task 5 in 63 bytes ``` :Ans/2→C :sub("A.A",1+2fPart(C),2 :For(I,0,C :"Alex "+Ans :If I≠C :Ans+" xelA :End :Ans ``` Input is a number in `Ans`. # Task 6 in 66 bytes ``` :𝑖^((Ans<7)(Ans-3(Ans>3 :For(Y,⁻1,1 :Disp sum(seq((5-real(AnsX+Ans𝑖Y)-3imag(AnsX+Ans𝑖Y))₁₀^(X+1),X,⁻1,1 :End ``` Input is a number in `Ans`. # Task 7 in 36 43 bytes ``` :Input <strike>L₁</strike>Str1 :.5 :For(I,1,<strike>dim(L₁</strike>length(Str1 :Ans+<strike>L₁(I</strike>expr(sub(Str1,I,1 :If 10=int(Ans :0 :End :not(Ans ``` Prompts for a list of digits string. # Task 9 in 83 bytes ``` :For(I,1,16,2 :If I<8 :Ans+sub(")}]>",inString("({[<",sub(Ans,4,1)),1 :sub(Ans,I,1)+Ans :End :For(I,⁻1,1 :Disp sub(Ans,9-8abs(I),8 :End ``` Input is a string in `Ans`. # Task 10 in 159 bytes ``` :1→X :Input Str1 :2+length(Str1→L :"X :While 2+L>length(Ans :Ans+Ans→Str2 :End :Ans→Str3 :While 1 :"XX :Ans+Str1+Ans→Str1 :For(I,1,L :Ans+sub("0X.",2expr(sub(Str2,I+1,1))+not(expr(sub(Ans,I,3)+sub(Str2,I,3)+sub(Str3,I,3))),1 :End :Disp sub(Ans,L+3,L :Str2→Str3 :Str1→Str2 :Input Str1 :End ``` Uses `X0.` instead of `.Xo` respectively (sorry nothing matches). Prompts for input line by line. You have to enter two lines of `X`s to see all the output, and then 2nd+Quit to quit. # Task 12 in 77 bytes ``` :Ans+"tvm_I%LinReg(ax+b) DS<(getKeyconj(1-PropZTest(dayOfWk(Manual-Fit C/YANOVA(*row(HorizRegEQUnarchive [J]!#$&'',.234567890:;=>?@GBQX\^_`qw{|}~ ``` Or as hex: ``` 72702ABB21FFDBADBB25BB3EEF06EF16 6331BB5917746201BB695C092DBBD2BB D3BBD4AEAE2B3A323334353637383930 3EBBD66A6CAFBBD147425158BBD7F0BB D9BBD5BBC1BBC708BBD809BBCF ``` Input is a string containing `"` in `Ans`. [Answer] # Perl, 4 tasks in 117 bytes Let's try a *real* language ;) Haven't given up yet, might even be able to squeeze 5 tasks in 140 bytes, although unlikely! ### \* Task 1: 30+1 = 31 bytes ``` @F=sort@F;say$F[0]+$F[1]>$F[2] ``` Usage: `perl -aM5.010 entry.pl input.txt` ### \* Task 4: 32+1 = 33 bytes ``` y/ELTFHI/4223/;s/./+$&/g;$_=eval ``` Usage: `perl -p entry.pl input.txt` ### Task 5: 54 bytes ``` say"Alex "x($_/2+1).qw(A. .A)[$_%2]." xelA"x(--$_/2+1) ``` *-2b thanks to Dom Hastings* Usage: `echo 4 | perl -M5.010 entry.pl` ### Task 7: 37+2 = 39 bytes ``` ($i+=$_)>10&&exit,$i%=10for@F;$_=!$i; ``` Usage: `perl -pF entry.pl input.txt` ### \* Task 8: 21+2 = 23 bytes ``` $_=y/|_ /14/dr/64%14 ``` This is a bit of a tricky one. Started out by replacing each `|` with `x` and each `_` with `y` then replacing spaces to produce a unique two digit string for each grid (`yyxxyxxyyx`, `yyxxyxxyyxyyxxxxyxyx`, `yyxxxxyxyxyyxyxxxyyx`, `yyxyxxxyyxyyxxxxyyx`, `yyxxxxyyx`). Next, I wrote a program to bruteforce values for `x` and `y`, and mathematical operations that could be done on the numbers produced after substituting `x` and `y` to give an output of 3,6,9,12 for each number. In the end, `x=1`, `y=4` and the magic operation was `/64%14`. Usage: `perl -0p entry.pl input.txt` ### Task 11: 34 bytes ``` say"SATOR AREPO TENET OPERA ROTAS" ``` Usage: `perl -M5.010 entry.pl` ### \* Task 12: 30 bytes ``` say d.pack"C*",32..126,83..126 ``` Usage: `perl -M5.010 entry.pl` Disclaimer: `-M5.010` [is considered 'free'](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions/274#274) [Answer] # Ruby, 4 tasks in 280 bytes (non-competitive) This is just an attempt, I'll keep making tasks later (and hopefully golf the existing ones). # Task 1 ``` a=gets.split.map &:to_i;p a.all?{|e|e<a.inject(:+)-e} ``` # Task 2 ``` p gets.chars.permutation.map{|a|a.join.to_i}.min_by{|x|(x-1e6).abs} ``` # Task 4 ``` n,b='EFHILT',0;gets.chars.map{|c|b+=n[c]==p ? 0:[4,3,3,3,2,2][n.index c]};p b ``` # Task 5 ``` a='Alex A.';gets.to_i.times{|i|i%2<1 ? a.sub!('A.','.A xelA'):a.sub!('.A',a)};$><<a ``` [Answer] # TI-BASIC, 4 tasks in 114 bytes Download all as a TI group file ([.8xg](https://www.dropbox.com/s/s41q7pmgu257tqy/WCG.8xg?dl=0)) (Spoiler tags added per request.) ## Task 1 - Can Three Numbers Form A Triangle? - 7 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/l2sj2ky6bs9a444/WCG01.8xp?dl=0)) > > > ``` > :2max(Ans)`<`sum(Ans > ``` > > > > ## Task 4 - FILTHE Letters - 34 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/vmp2ct2x3rhlyze/WCG04.8xp?dl=0)) > > > ``` > :sum(int(`\`³√(`\`12seq(inString("TLIHFE",sub(Ans,X,1)),X,1,length(Ans > ``` > > > > ## Task 8 - Square Clock - 35 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/aijvnzyrl61o4m5/WCG08.8xp?dl=0)) > > > ``` > :12-3max(seq(X(sub(Ans,6gcd(X,2)+X,1)≠" "),X,1,3 > ``` > > > > ## Task 11 - Sator Square - 38 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/g5dpcih9akowp6n/WCG11.8xp?dl=0)) > > > ``` > :Disp "SATOR","AREPO","TENET","OPERA > :"ROTAS > ``` > > > > --- Bonus round! Here are all the other tasks just for fun. ## Task 2 - Closest To One Million - 114 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/dpxikrw59ings2s/WCG02.8xp?dl=0)) > > > ``` > :int(10fPart(Ans`\`10^(`\`-cumSum(binomcdf(6,0→X > :"sum(`\`L`\`X`\`10^(`\`cumSum(not(binompdf(6,0→`\`Y1`\` > :SortD(`\`L`\`X > :`\`Y1`\`→X > :sum(not(`\`L`\`X > :If Ans > :Then > :If max(`\`L`\`X=1 > :X+`\`E`\`6-`\`10^(`\`6-Ans→X > :SortA(`\`L`\`X > :augment(ΔList(cumSum(`\`L`\`X)),{0→X > :End > :{X,`\`Y1`\` > :Ans(1+(0`>`min(ΔList(abs(`\`E`\`6-Ans > ``` > > > > ## Task 3 - Simple Keyboard Simulator - ~~131~~ 127 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/tq7ldop9ra8ivqo/WCG03.8xp?dl=0)) > > > ``` > :Input Str1 > :~~DelVar X~~1→Y > :"..→Str2 > :For(Z,1,length(Str1 > :sub(Str1,Z,1→Str3 > :(Ans="`>`")-(Ans="`<` > :If Ans > :Then > :max(1,min(Y+Ans,X+1→Y > :Else > :sub(Str2,1,Y)+Str3+sub(Str2,Y+1,X-Y+2→Str2 > :X+1→X > :Y+1→Y > :End > :End > :sub(Str2,2,X > ``` > > > > ## Task 5 - Alex Recursive A. - 107 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/sec065zdfv98n2g/WCG05.8xp?dl=0)) > > > ``` > :Input X > :".A.. > :For(X,0,X > :Ans→Str1 > :5int(.5X+.5 > :sub(Str1,1,Ans+1)+sub(".A xelAlex A.",6gcd(X,2)-5,7)+sub(Str1,Ans+4,5X-Ans+1 > :End > :sub(Ans,2,5X+2 > ``` > > > > ## Task 6 - Numpad Rotation - 86 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/b4t1rolpa3lsmh4/WCG06.8xp?dl=0)) > > > ``` > :.3Ans+2(Ans=6→X > :[[9,6,3][8,5,2][7,4,1 > :For(X,0,X > :rowSwap(Ans`\`^T`\`),1,3 > :End > :Ans > :*row+(10,*row+(10,Ans`\`^T`\`,1,2),2,3 > :For(X,1,3 > :Disp Ans(3,X > :End > ``` > > > > ## Task 7 - Splitting Digits Into Tens - 77 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/m7afuwez82dm8vw/WCG07.8xp?dl=0)) > > > ``` > :Ans+"0 > :seq(expr(sub(Ans,X,1)),X,1,length(Ans > :augment(Ans,{10not(not(max(Ans→X > :1→X > :Repeat Ans≥dim(`\`L`\`X > :Ans+1 > :If 10=sum(`\`L`\`X,X,Ans > :Ans+1→X > :End > :X=Ans > ``` > > > > ## Task 9 - Bracket Art - 86 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/zu0uw81wz3bdrcp/WCG09.8xp?dl=0)) > > > ``` > :Input Str1 > :For(X,1,4 > :For(Y,0,1 > :abs(X-9not(Y→Z > :"()[]{}`<>` > :sub(Ans,inString(Ans,sub(Str1,X,1))+Y,1 > :Output(1,Z,Ans > :Output(2,9-Z,Ans > :Output(3,Z,Ans > :End > :End > ``` > > > > ## Task 10 - Perimiterize - 218 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/tb7gusca8zqua8x/WCG10.8xp?dl=0)) > > > ``` > :". > :For(A,0,`\`E`\`9 > :Input Str1 > :Ans+Str1→Str2 > :If Str1≠". > :End > :length(Ans→X > :round(A`\`^-1`\`(Ans-2→B > :seq(expr(sub(Str2,A,1)),A,2,X-1→B > :πAns→C > :"augment(Ans,augment(Ans,`\`L`\`B))+augment(Ans,augment(`\`L`\`C,Ans))+augment(`\`L`\`B,augment(Ans,Ans→X > :seq(0,A,1,B > :`\`L`\`X→A > :For(C,0,A+1 > :seq(`\`L`\`A(A+BC),A,1,B→C > :int(Ans→B > :{0 > :1+not(`\`L`\`X)+not(fPart(`\`L`\`X→B > :". > :For(X,1,B+2 > :Ans+sub("120",`\`L`\`B(X),1 > :End > :Disp sub(Ans,2,B+2 > :End > ``` > > > > These substitutions have been made: `0`=`.`, `1`=`X`, `2`=`o` For input (after the program begins), type one row at a time, pressing enter at each line break, until the last row is written out. Then press enter, type one period, then hit enter again to submit the entire string. ## Task 12 - Prime Tweet - 151 bytes Download as a TI-83+ program file ([.8xp](https://www.dropbox.com/s/cn86snshnq217qs/WCG12.8xp?dl=0)) > > > ``` > :Ans+"!#$%`&`'()*+,-./01234567889:;`<`=`>`?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[`\`]^_`abcdefghijklmnopqrstuvwxyz{|}~ > :For(X,1,45 > :Ans+" > :End > :Ans > ``` > > > > `Ans` should contain a double quote, performed by typing one directly into `\Y1\` from the equation editor and running `Equ►String(\Y1\,Str1:Str1` from the home screen. The output length is 140. 8 appears twice, and there are 45 spaces along with the other ASCII characters each appearing once. This amounts to (33+34+...+126) + 56 + 32×45 = 8969, a Sophie Germain prime. [Answer] ## Python 3, 1 task, 268 bytes, non-competitive I tried Task #2 in Python 3.5.2 I am new to code golfing and python ``` import itertools def f2(l): n=1000000 l=list(itertools.permutations(l)) j = len(l) m=[None]*j while j>0: j -= 1 m[j]= int(''.join(str(i) for i in l[j])) l[j]=abs(n-m[j]) l.sort() k=n-l[0] return(n+l[0],k)[k in m] ``` ]
[Question] [ ### Input: A positive integer **n** consisting of digits in the range **0-9**. ### Challenge: If **d** is the highest digit in the integer, assume the base of the number is **d+1**. E.g. if the integer is **1256** then you shall assume it's in **base-7**, if it's **10110** then you shall assume it's **base-2** (binary), and if it's **159** then it's decimal. Now, do the following until you either, 1: reach a **base-10** integer, *or* 2: reach a single digit integer. 1. Convert the integer from **base-(d+1)** to **base-10** 2. Find the base of this new integer (again, **base-(d+1)** where **d** is the highest digit in the new number) 3. Go to step **1**. --- ### Examples: Assume the input is **n = 413574**. The highest digit **d=7**, so this is **base-8** (octal). Convert this to decimal and get **137084**. The highest digit **d=8**, so this is **base-9**. Convert this to decimal and get **83911**. The highest digit is **9**, so this is a decimal number and we stop. The output shall be **83911**. Assume the input is **n = 13552**. The highest digit is **d=5**, so this is **base-6**. Convert this to decimal and get **2156**. The highest digit **d=6**, so this is **base-7**. Convert this to decimal and get **776**. The highest digit is **d=7**, so this is **base-8**. Convert this to decimal and get **510**. The highest digit is **d=5** so this is **base-6**. Convert this to decimal and get **186**. The highest digit is **8**, so this is **base-9**. Convert this to decimal and get **159**. The highest digit is **9**, so this is a decimal number and we stop. The output shall be **159**. Assume the input is **n=17**. This will give us **15**, then **11**, then **3**, which we will output since it's a single digit. --- ### Test cases: ``` 5 5 17 3 999 999 87654321 (base-9 -> 42374116 in decimal -> base-7 -> 90419978 in decimal) 9041998 41253 (5505 -> 1265 -> 488 -> 404 -> 104 -> 29) 29 ``` --- **Notes:** * Standard rules regarding I/O, loopholes etc. You may take the input as a string * Explanations are encouraged * You may use builtin base-conversion commands + Solutions that don't use the language's builtin base-conversion functions (if they exist) are welcome, even if they end up being much longer than the obvious approach using builtin functions. --- Apparently, this is [OEIS A091047](https://oeis.org/A091047). [Answer] ## Mathematica, 56 bytes ``` #//.x_/;(b=Max[d=IntegerDigits@x]+1)<11:>d~FromDigits~b& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfWV9fryJe31ojydY3sSI6xdYzryQ1PbXIJTM9s6TYoSJW21DTxtDQyi6lzq0oPxciXJek9j@gKDOvxEErTUHfQaHaVEfB0FxHwdLSUkfBwtzM1MTYyFBHwcTQyNS49j8A "Mathics – Try It Online") (Using Mathics.) I thought I'd check out what the sequence looks like: [![enter image description here](https://i.stack.imgur.com/3lFQz.png)](https://i.stack.imgur.com/3lFQz.png) And here is a plot of the number of steps it takes to find the result: [![enter image description here](https://i.stack.imgur.com/NR0lg.png)](https://i.stack.imgur.com/NR0lg.png) (Click for larger versions. See the revision history for plots only up to **n = 1000**.) Looks like a very interesting mixture of large scale structure and fine scale chaos. I wonder what's up with the wider gaps around 30,000 and 60,000. [Answer] # Java 8, ~~172~~ ~~166~~ ~~163~~ ~~152~~ ~~151~~ ~~140~~ ~~138~~ ~~116~~ ~~114~~ 99 bytes ``` s->{for(Integer b=0;b<10&s.length()>1;s=""+b.valueOf(s,b=s.chars().max().getAsInt()-47));return s;} ``` Takes the input as a `String`. -64 bytes thanks to *@OlivierGrégoire*. And here I thought my initial 172 wasn't too bad.. ;) [Try it here.](https://tio.run/##hY8/b4MwEMV3PsWJobLVYoUESpFLpI4dmg4dqw62YwgpGOQzqFXEZ6dOxRqxnO7PT@@9O4tRRF2vzfn4PatGIMKbqM0lAKiN07YUSsPhOgJ8OFubChRZGqTc76fAF3TC1QoOYKCAGaP9pewsefUKlbYgiw2Xz/HmDlmjTeVOhO5jjkUY3ks2imbQ7yXBB1kgUydhkVDWih9fK@1e0KsQGiUZpdxqN1gDyKeZX237QTbednEfu/oIrU@/BPz8AkGX6L/odMu6wbHen1xjiGGKhGlI/5@4TcTZKpLn@SrzlD2myW4br4JJvE13CzUF0/wH) **Explanation:** ``` s->{ // Method with String as parameter and return-type for(Integer b=0;b<10 // Loop as long as the largest digit + 1 is not 10 &s.length()>1; // and as long as `s` contains more than 1 digit s=""+ // Replace `s` with the String representation of: b.valueOf(s, // `s` as a Base-`b` integer b=s.chars().max().ge‌tAsInt()-47) // where `b` is the largest digit in the String + 1 ); // End of loop return s; // Return result-String } // End of method ``` [Answer] # Pyth, 9 bytes ``` ui`GhseS` ``` [Test suite](https://pyth.herokuapp.com/?code=ui%60GhseS%60&test_suite=1&test_suite_input=5%0A17%0A999%0A87654321%0A41253&debug=0) Explanation: ``` ui`GhseS` ui`GhseS`GQ Implicit variable introduction u Q Repeatedly apply the following function until the value repeats, starting with Q, the input. `G Convert the working value to a string. eS Take its maximum. s Convert to an integer. h Add one. i`G Convert the working value to that base ``` [Answer] # JavaScript (ES6), 63 57 54 53 bytes ``` f=a=>a>9&(b=Math.max(...a+""))<9?f(parseInt(a,b+1)):a ``` Saved 8 bytes thanks to Shaggy and Dom Hastings ``` f=a=>a>9&(b=Math.max(...a+""))<9?f(parseInt(a,b+1)):a; console.log(f("413574")) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~91 78 76 75~~ 73 bytes *@Emigna shaved off 5 bytes. @FelipeNardiBatista saved 1 byte. @RomanGräf saved 2 bytes* ``` i=input() while'9'>max(i)and~-len(i):i=str(int(i,int(max(i))+1)) print(i) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9M2M6@gtERDk6s8IzMnVd1S3S43sUIjUzMxL6VONyc1D8i0yrQtLinSyMwr0cjUAZEQFZrahpqaXAVFYHHN//8NzQE "Python 3 – Try It Online") --- ## Explanation ``` i=input() - takes input and assigns it to a variable i while '9'>max(i)and~-len(i): - repeatedly checks if the number is still base-9 or lower and has a length greater than 1 i=str(...) - assigns i to the string representation of ... int(i,int(max(i))+1) - converts the current number to the real base 10 and loops back again print(i) - prints the mutated i ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 5 bytes 5 bytes saved thanks to *Magic Octopus Urn* ``` F§Z>ö ``` As this grows slow very quickly for large input, I'm leaving the old much faster version here for testing. The algorithm is the same, only the number of iterations differ. ``` [©Z>öD®Q#§ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@tDKKLvD21wOrQtUPrT8/38TQ2NTcxMA "05AB1E – Try It Online") **Explanation** ``` [ # start a loop © # store a copy of the current value in the register Z> # get the maximum (digit) and increment ö # convert the current value to base-10 from this base D # duplicate ®Q# # break loop if the new value is the same as the stored value § # convert to string (to prevent Z from taking the maximum int on the stack) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 16 bytes Takes and returns a string ``` ((⍕⊢⊥⍨1+⌈/)⍎¨)⍣≡ ``` `(`…`)⍣≡` apply the following function until two consecutive terms are identical:  `⍎¨` execute each character (turns the string into a list of numbers)  `(`…`)` apply the following tacit function to that:   `⌈/` find the maximum of the argument   `1+` add one   `⊢⊥⍨` evaluate the argument in that base   `⍕` format (stringify, in preparation for another application of the outer function) [Try it online!](https://tio.run/##SyzI0U2pTMzJT///38nQ4FHbBA2NR71TH3UtetS19FHvCkPtRz0d@pqPevsOrQCSix91LgQrPLRCQd1UXUHd0BxIWFpaAkkLczNTE2MjQyDTxNDI1FgdAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~60~~ 56 bytes ``` ->n{n=(s=n.to_s).to_i(s.bytes.max-47)while/9/!~s&&n>9;n} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9curzrPVqPYNk@vJD@@WBNEZmoU6yVVlqQW6@UmVuiamGuWZ2TmpOpb6ivWFaup5dlZWufV/i9QSItOTy0pBmuI/W9iaGxqbgIA "Ruby – Try It Online") [Answer] # Mathematica, 52 bytes ``` FromDigits[s=IntegerDigits@#,Max@s+1]&~FixedPoint~#& ``` Pure function taking a nonnegative integer as input and returning a nonnegative integer. Uses the same core mechanic `FromDigits[s=IntegerDigits@#,Max@s+1]` as [Jenny\_mathy's answer](https://codegolf.stackexchange.com/a/128800/56178), but exploits `FixedPoint` to do the iteration. [Answer] # [Perl 6](https://perl6.org), 49 bytes ``` {($_,{.Str.parse-base(1+.comb.max)}...*==*).tail} ``` [Test it](https://tio.run/##TU/LboMwELzvV@wham0gDgYMWIi0/9De2qoi4FZIvAROlSpKfqy3/hjFpqp68M5qdmZ2PaixiefjpPAjZmUG7SfelH2lMJ/PZPPqndmDHtlQjJPaHopJEe6ysm8PrC1O9MIYc/LcoUwXdXOZF/O9VpPGHJu6UxOh7H1UA7lz6PeXtZHdc@Xu6JOT@S9s7HU/koBmYPY/LsYMhqbo0LUpGbz142/gdo9kU3fDUXsbdRpUqVVF8QyI9YTmXuKuY@qh@6fwcCXxireY75dyxb8hXGYBAoAnEAJIKe2DNIlFFAYckZj/bqXZHQVhEnEeY91hpcq6LRpDW0FiOulHXMok/SegCCubAkQ8EOGSKIQvjJwHscUoTS34kWVXCCSFQP4A "Perl 6 – Try It Online") ## Expanded: ``` { ( $_, # seed the sequence with the input { .Str .parse-base( # parse in base: 1 + .comb.max # largest digit + 1 ) } ... # keep generating values until * == * # two of them match (should only be in base 10) ).tail # get the last value from the sequence } ``` [Answer] # [PHP](https://php.net/), 71 bytes ``` for(;$b<10&9<$n=&$argn;)$n=intval("$n",$b=max(str_split($n))+1);echo$n; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGJoZGqsZM31Py2/SMNaJcnG0EDN0kYlz1YNrMBaE8jMzCspS8zRUFLJU9JRSbLNTazQKC4pii8uyMks0VDJ09TUNtS0Tk3OyFfJs/7/HwA "PHP – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 17 bytes ``` Wa>9>YMXaaFB:1+ya ``` Takes input as a command-line argument. [Try it online!](https://tio.run/##K8gs@P8/PNHO0i7SNyIx0c3JylC7MvH///8mhkamxgA "Pip – Try It Online") ### Explanation This was fun--I got to pull out the chaining comparison operators. We want to loop until the number is a single digit OR contains a 9. Equivalently, we want to loop while the number is multiple digits AND does not contain a 9. Equivalently, loop while the number is greater than 9 AND the maximum digit is less than 9: `a>9>MXa`. ``` Wa>9>YMXaaFB:1+ya a is 1st cmdline arg (implicit) YMXa Yank a's maximum digit into the y variable Wa>9> While a is greater than 9 and 9 is greater than a's max digit: aFB:1+y Convert a from base 1+y to decimal and assign back to a a At the end of the program, print a ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ ~~59~~ ~~56~~ 53 bytes Saved 4 byte thanks to *Felipe Nardi Batista* Saved 3 bytes thanks to *ovs* ``` f=lambda x,y=0:x*(x==y)or f(`int(x,int(max(x))+1)`,x) ``` [Try it online!](https://tio.run/##Rcs7CsMwDIDhvacw8WK1HuJXEwV8lzgU00LzIGSQT@/WEGINAv0f2tLxXhedc/TfME@vwEgm3w50F@R9gnVnUYyf5RAky54DCQJ4KBglQd72EqNoXAPAzuHudnXVVeCmdkS8gP@PKn33dNZoVZhjaxViX9Uq7cz5yTXmHw "Python 2 – Try It Online") Using a recursive lambda, comparing the result of the base conversion to the previous iteration. [Answer] ## C#, 257 244 243 244 233 222 bytes ``` using System.Linq;z=m=>{int b=int.Parse(m.OrderBy(s=>int.Parse(s+"")).Last()+""),n=0,p=0;if(b<9&m.Length>1){for(int i=m.Length-1;i>=0;i--)n+=int.Parse(m[i]+"")*(int)System.Math.Pow(b+1,p++);return z(n+"");}else return m;}; ``` Well, C# always takes a lot of bytes but this is just ridiculous. None of the built-ins can handle an arbitrary base, so I had to calculate the conversion myself. Ungolfed: ``` using System.Linq; z = m => { int b = int.Parse(m.OrderBy(s => int.Parse(s + "")).Last()+""), n = 0, p = 0; //Get the max digit in the string if (b < 9 & m.Length > 1) //if conditions not satisfied, process and recurse { for (int i = m.Length - 1; i >= 0; i--) n += int.Parse(m[i] + "") * (int)System.Math.Pow(b+1, p++); //convert each base-b+1 representation to base-10 return z(n + ""); //recurse } else return m; }; ``` [Answer] # Mathematica, 92 bytes ``` f[x_]:=FromDigits[s=IntegerDigits@x,d=Max@s+1];(z=f@#;While[d!=10&&Length@s>1,h=f@z;z=h];z)& ``` [Answer] # Javascript (ES6) with 0 arrow function, 74 bytes ``` function f(a){a>9&&b=Math.max(...a)<9&&f(parseInt(a,b+1));alert(a)}f('11') ``` [Answer] # [K4](http://kx.com/download/), 19 bytes **Solution:** ``` {(1+|/x)/:x:10\:x}/ ``` **Examples:** ``` q)\ {(1+|/x)/:x:10\:x}/413574 83911 {(1+|/x)/:x:10\:x}/13552 159 {(1+|/x)/:x:10\:x}/17 3 {(1+|/x)/:x:10\:x}/41253 29 ``` **Explanation:** Use `/:` built-in to convert base. ``` {(1+|/x)/:x:10\:x}/ / the solution { }/ / converge lambda, repeat until same result returned 10\:x / convert input x to base 10 (.:'$x would do the same) x: / store in variable x ( )/: / convert to base given by the result of the brackets |/x / max (|) over (/) input, ie return largest 1+ / add 1 to this ``` [Answer] # [Kotlin](https://kotlinlang.org), 97 bytes ``` fun String.f():String=if(length==1||contains("9"))this else "${toInt(map{it-'0'}.max()!!+1)}".f() ``` ## Beautified ``` fun String.f(): String = if (length == 1 || contains("9")) this else "${toInt(map { it - '0' }.max()!! + 1)}".f() ``` ## Test ``` fun String.f():String=if(length==1||contains("9"))this else "${toInt(map{it-'0'}.max()!!+1)}".f() val tests = listOf( 5 to 5, 17 to 3, 999 to 999, 87654321 to 9041998, 41253 to 29 ) fun main(args: Array<String>) { tests.forEach { (input, output) -> val answer = input.toString().f() if (answer != output.toString()) { throw AssertionError() } } } ``` ## TIO [TryItOnline](https://tio.run/##TU9BbsIwELznFUtUCVuFCBNSMGqQOHDoqYe+wEI2sRpsZC+lVcjb0zgBwh689szseOfbYqlN06izgS902hwSRei6v+ZakVKaAxZ5zq7XvTUotPEk5jGlWGgPsvQS4pcK7YdBchSnSuN0PBvXyVH8EjoavTJax8Gy+REloPToIYdSe/xUJIJbZYAWssnjzZYBSAeAcx6Qtg3YavmWLdI564jZgnG+GsgFm2dpYOY8olEU4h3b3YlwB7+GrXPi770PuaFQdWPdcomybif2BVRAtDmdcQL2jG2nMN083EMWYfxFujZMJ0vQ9naEhrQPpVZAbspRfrN60t7/vhcWzl5g6710qK3ZOWfdk1sd9Wfd/AM) [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ωoṠBo→▲d ``` [Try it online!](https://tio.run/##ATUAyv9odXNr/23igoH/z4lv4bmgQm/ihpLilrJk////WzUsMTcsOTk5LDg3NjU0MzIxLDQxMjUzXQ "Husk – Try It Online") ``` ωoṠBo→▲d ω # repeat until output no longer changes: oṠ # apply function to value & function-of-value d # value: digits of argument Bo→▲ # function of value: B # interpret digits as base n, with n given by o→▲ # max digit +1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 bytes ``` >9©(A=Uì rw)<9?ßUs nAÄ):U ``` [Try it online!](https://tio.run/##y0osKPn/387y0EoNR9vQw2sUiso1bSztD88PLVbIczzcomkV@v@/oTkA "Japt – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` DḅṀ‘$$µÐL ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//ROG4heG5gOKAmCQkwrXDkEz///80MTI1Mw "Jelly – Try It Online") [Answer] # C, ~~159~~ 157 bytes ``` #include <stdlib.h> char b[99];i=0;m=-1;c(n){do{m=-1;sprintf(b,"%d",n);i=0;while(b[i]){m=max(b[i]-48,m);i++;}n=strtol(b,0,++m);}while(b[1]&&m<10);return n;} ``` [Answer] # [Scala](http://www.scala-lang.org/), 119 bytes ``` if(x.max==57|x.length==1)x else{val l=x.length-1 f((0 to l).map(k=>(((x(k)-48)*math.pow(x.max-47,l-k))) toInt).sum+"")} ``` [Try it online!](https://tio.run/##VY7NTsMwEITvfoqVT16KI9wmuEFyJY4cOPEEpnXaEMexGhcshTx7MD8Nymln55tZbb/XVk/d65vZB3jWtQMTg3GHHh69Hwg5mAoqFh9ewrl2R/ybapjq5GatjkoV8jNm1rhjOCklMIKxvRnetQWrroALUjF2B6EDi6nmWaN2jLHIGuT5Fm9aHU6Z7z5@j/Jc3lreIGJqPLmAWX9pV5TiOI2E@PRCsI7RAvgO6KpKiiL@@0LOQMgFKctyRkkv2FbeF/lmLebA1VikcrEuNnPkZ/vmZJy@AA "Scala – Try It Online") # [Scala](http://www.scala-lang.org/), 119 bytes ``` if(x.max==57|x.length==1)x else f((0 to x.length-1).map(k=>(((x(k)-48)*math.pow(x.max-47,x.length-1-k))) toInt).sum+"") ``` [Try it online!](https://tio.run/##VY7BbsIwEETv/oqVT17AUQ0JJpWMxLGHnvoFLjghTeJYxKiWgG9PTVuCctrZebOj7fe60UP3@WX2Ht51ZcEEb@yhh51zF0IOpoCChdcPf6psif9TXYYqukmrg1KZvIakMbb0R6UEBjBNb@IRewHfwQNxgTHuWK22jLHAauTpBmet9sfEdd9/ZTyVi@cBrxExdrxZj0l/bueU4nAjxMUXfGMZzYBvgc6LqCji0xdyBEJOSJ7nI4p6wjZynaWrpRgDD2OSSsUyW42R3@3OyW34AQ "Scala – Try It Online") Both methods work the same way, but in the first one I put `x.length-1` in a variable, and in the second one I don't. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _=ì)ìZrÔÄ}gN ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Xz3sKexactTEfWdO&input=MTI1Ng) [Answer] # [J](http://jsoftware.com/), 22 bytes ``` (#.~1+>./)@(,.&.":)^:_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NZT16gy17fT0NR00dPTU9JSsNOOs4v9rcnGlJmfkK6QpGSjEKpgqGJorWFpaKliYm5maGBsZKpgYGpka/wcA "J – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` fG›β)Ẋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZkfigLrOsinhuooiLCIiLCI1XG4xN1xuOTk5XG44NzY1NDMyMVxuNDEyNTMiXQ==) Will be 5 bytes once a [bug fix](https://github.com/Vyxal/Vyxal/pull/1480) is made. ## Explained ``` fG›β)Ẋ )Ẋ # Until the result of applying the following does not change: fG # Get the biggest digit of the current value - should just be G, but bugs ›β # and convert the current value from base (the biggest digit + 1) to base 10 ``` ]
[Question] [ You're given a true colour image. Your task is to generate a version of this image, which looks like it was painted using [paint-by-numbers](https://www.google.com/search?site=&tbm=isch&source=hp&biw=1920&bih=912&q=paint%20by%20numbers&oq=paint%20by%20&gs_l=img.3.0.0l10.2068.3265.0.4050.9.8.0.1.1.0.161.637.4j3.7.0.msedr...0...1ac.1.58.img..1.8.640.iU4XeWp6uIc) (the children's activity, *not* nonograms). Along with the image, you're given two parameters: **P**, the maximum size of the colour palette (i.e. the maximum number of distinct colours to use), and **N**, the maximum number of *cells* to use. Your algorithm does *not* have to use all **P** colours and **N** cells, but it must not use more than that. The output image should have the same dimensions as the input. A *cell* is defined as a contiguous area of pixels which all have the same colour. Pixels touching only at a corner are *not* considered contiguous. Cells may have holes. In short, you are to approximate the input image with only N flat-shaded/solid-colour areas and P different colours. Just to visualise the parameters, here is a very simple example (for no particular input image; showing off my mad Paint skills). The following image has **P = 6** and **N = 11**: ![enter image description here](https://i.stack.imgur.com/Ft2da.png) Here are a few images to test your algorithm on (mostly our usual suspects). Click the pictures for larger versions. [![Great Wave](https://i.stack.imgur.com/56MVN.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Great_Wave_off_Kanagawa2.jpg/800px-Great_Wave_off_Kanagawa2.jpg) [![Coral Reef](https://i.stack.imgur.com/wW8RN.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/Underwater_World.jpg/800px-Underwater_World.jpg) [![Rainbow](https://i.stack.imgur.com/LcnaO.png)](https://i.stack.imgur.com/xPAwA.png) [![Starry Night](https://i.stack.imgur.com/Eb4RJ.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/757px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg) [![River](https://i.stack.imgur.com/b0o7f.png)](https://i.stack.imgur.com/y2VZJ.png) [![Brown Bear](https://i.stack.imgur.com/vFMZu.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Brown_bear_%28Ursus_arctos_arctos%29_running.jpg/796px-Brown_bear_%28Ursus_arctos_arctos%29_running.jpg) [![Waterfall](https://i.stack.imgur.com/JTsT2.png)](http://upload.wikimedia.org/wikipedia/en/e/e8/Escher_Waterfall.jpg) [![Mandrill](https://i.stack.imgur.com/B66Zs.png)](https://i.stack.imgur.com/fCTEl.png) [![Crab Nebula](https://i.stack.imgur.com/6AjIN.png)](http://commons.wikimedia.org/wiki/File:Crab_Nebula.jpg) [![American Gothic](https://i.stack.imgur.com/hc0iH.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg/497px-Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg) [![Mona Lisa](https://i.stack.imgur.com/EQa0l.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg) [![Scream](https://i.stack.imgur.com/l2wGm.png)](http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/475px-The_Scream.jpg) Please include a handful of results for different parameters. If you want to show a large number of results, you can create a gallery over on [imgur.com](http://imgur.com/), to keep the size of the answers reasonable. Alternatively, put thumbnails in your post and make them links to larger images, like I did above. Also, feel free to use other test images, if you find something nice. I assume that parameters around **N ≥ 500**, **P ~ 30** would be similar to real paint-by-number templates. This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by * how well the original images are approximated. * how well the algorithm works on different kinds of images (paintings are probably generally easier than photographs). * how well the algorithm works with very restrictive parameters. * how organic/smooth the cell shapes look. I will use the following Mathematica script, to validate results: ``` image = <pastedimagehere> // ImageData; palette = Union[Join @@ image]; Print["P = ", Length@palette]; grid = GridGraph[Reverse@Most@Dimensions@image]; image = Flatten[image /. Thread[palette -> Range@Length@palette]]; Print["N = ", Length@ConnectedComponents[ Graph[Cases[EdgeList[grid], m_ <-> n_ /; image[[m]] == image[[n]]]]]] ``` Sp3000 was kind enough to write a verifier in Python 2 using PIL, which you find [at this pastebin](http://pastebin.com/WZ9X6NSS). [Answer] # Python 2 with PIL ([Gallery](https://sites.google.com/site/pbnfloodfiller/home)) ``` from __future__ import division from PIL import Image import random, math, time from collections import Counter, defaultdict, namedtuple """ Configure settings here """ INFILE = "spheres.png" OUTFILE_STEM = "out" P = 30 N = 300 OUTPUT_ALL = True # Whether to output the image at each step FLOOD_FILL_TOLERANCE = 10 CLOSE_CELL_TOLERANCE = 5 SMALL_CELL_THRESHOLD = 10 FIRST_PASS_N_RATIO = 1.5 K_MEANS_TRIALS = 30 BLUR_RADIUS = 2 BLUR_RUNS = 3 """ Color conversion functions """ X = xrange # http://www.easyrgb.com/?X=MATH def rgb2xyz(rgb): r,g,b=rgb;r/=255;g/=255;b/=255;r=((r+0.055)/1.055)**2.4 if r>0.04045 else r/12.92 g=((g+0.055)/1.055)**2.4 if g>0.04045 else g/12.92;b=((b+0.055)/1.055)**2.4 if b>0.04045 else b/12.92 r*=100;g*=100;b*=100;x=r*0.4124+g*0.3576+b*0.1805;y=r*0.2126+g*0.7152+b*0.0722 z=r*0.0193+g*0.1192+b*0.9505;return(x,y,z) def xyz2lab(xyz): x,y,z=xyz;x/=95.047;y/=100;z/=108.883;x=x**(1/3)if x>0.008856 else 7.787*x+16/116 y=y**(1/3)if y>0.008856 else 7.787*y+16/116;z=z**(1/3)if z>0.008856 else 7.787*z + 16/116 L=116*y-16;a=500*(x-y);b=200*(y-z);return(L,a,b) def rgb2lab(rgb):return xyz2lab(rgb2xyz(rgb)) def lab2xyz(lab): L,a,b=lab;y=(L+16)/116;x=a/500+y;z=y-b/200;y=y**3 if y**3>0.008856 else(y-16/116)/7.787 x=x**3 if x**3>0.008856 else (x-16/116)/7.787;z=z**3 if z**3>0.008856 else(z-16/116)/7.787 x*=95.047;y*=100;z*=108.883;return(x,y,z) def xyz2rgb(xyz): x,y,z=xyz;x/=100;y/=100;z/=100;r=x*3.2406+y*-1.5372+z*-0.4986 g=x*-0.9689+y*1.8758+z*0.0415;b=x*0.0557+y*-0.2040+z*1.0570 r=1.055*(r**(1/2.4))-0.055 if r>0.0031308 else 12.92*r;g=1.055*(g**(1/2.4))-0.055 if g>0.0031308 else 12.92*g b=1.055*(b**(1/2.4))-0.055 if b>0.0031308 else 12.92*b;r*=255;g*=255;b*=255;return(r,g,b) def lab2rgb(lab):rgb=xyz2rgb(lab2xyz(lab));return tuple([int(round(x))for x in rgb]) """ Stage 1: Read in image and convert to CIELAB """ total_time = time.time() im = Image.open(INFILE) width, height = im.size if OUTPUT_ALL: im.save(OUTFILE_STEM + "0.png") print "Saved image %s0.png" % OUTFILE_STEM def make_pixlab_map(im): width, height = im.size pixlab_map = {} for i in X(width): for j in X(height): pixlab_map[(i, j)] = rgb2lab(im.getpixel((i, j))) return pixlab_map pixlab_map = make_pixlab_map(im) print "Stage 1: CIELAB conversion complete" """ Stage 2: Partitioning the image into like-colored cells using flood fill """ def d(color1, color2): return (abs(color1[0]-color2[0])**2 + abs(color1[1]-color2[1])**2 + abs(color1[2]-color2[2])**2)**.5 def neighbours(pixel): results = [] for neighbour in [(pixel[0]+1, pixel[1]), (pixel[0]-1, pixel[1]), (pixel[0], pixel[1]+1), (pixel[0], pixel[1]-1)]: if 0 <= neighbour[0] < width and 0 <= neighbour[1] < height: results.append(neighbour) return results def flood_fill(start_pixel): to_search = {start_pixel} cell = set() searched = set() start_color = pixlab_map[start_pixel] while to_search: pixel = to_search.pop() if d(start_color, pixlab_map[pixel]) < FLOOD_FILL_TOLERANCE: cell.add(pixel) unplaced_pixels.remove(pixel) for n in neighbours(pixel): if n in unplaced_pixels and n not in cell and n not in searched: to_search.add(n) else: searched.add(pixel) return cell # These two maps are inverses, pixel/s <-> number of cell containing pixel cell_sets = {} pixcell_map = {} unplaced_pixels = {(i, j) for i in X(width) for j in X(height)} while unplaced_pixels: start_pixel = unplaced_pixels.pop() unplaced_pixels.add(start_pixel) cell = flood_fill(start_pixel) cellnum = len(cell_sets) cell_sets[cellnum] = cell for pixel in cell: pixcell_map[pixel] = cellnum print "Stage 2: Flood fill partitioning complete, %d cells" % len(cell_sets) """ Stage 3: Merge cells with less than a specified threshold amount of pixels to reduce the number of cells Also good for getting rid of some noise """ def mean_color(cell, color_map): L_sum = 0 a_sum = 0 b_sum = 0 for pixel in cell: L, a, b = color_map[pixel] L_sum += L a_sum += a b_sum += b return L_sum/len(cell), a_sum/len(cell), b_sum/len(cell) def remove_small(cell_size): if len(cell_sets) <= N: return small_cells = [] for cellnum in cell_sets: if len(cell_sets[cellnum]) <= cell_size: small_cells.append(cellnum) for cellnum in small_cells: neighbour_cells = [] for cell in cell_sets[cellnum]: for n in neighbours(cell): neighbour_reg = pixcell_map[n] if neighbour_reg != cellnum: neighbour_cells.append(neighbour_reg) closest_cell = max(neighbour_cells, key=neighbour_cells.count) for cell in cell_sets[cellnum]: pixcell_map[cell] = closest_cell if len(cell_sets[closest_cell]) <= cell_size: small_cells.remove(closest_cell) cell_sets[closest_cell] |= cell_sets[cellnum] del cell_sets[cellnum] if len(cell_sets) <= N: return for cell_size in X(1, SMALL_CELL_THRESHOLD): remove_small(cell_size) if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for cellnum in cell_sets: cell_color = mean_color(cell_sets[cellnum], pixlab_map) for pixel in cell_sets[cellnum]: frame_im.putpixel(pixel, lab2rgb(cell_color)) frame_im.save(OUTFILE_STEM + "1.png") print "Saved image %s1.png" % OUTFILE_STEM print "Stage 3: Small cell merging complete, %d cells" % len(cell_sets) """ Stage 4: Close color merging """ cell_means = {} for cellnum in cell_sets: cell_means[cellnum] = mean_color(cell_sets[cellnum], pixlab_map) n_graph = defaultdict(set) for i in X(width): for j in X(height): pixel = (i, j) cell = pixcell_map[pixel] for n in neighbours(pixel): neighbour_cell = pixcell_map[n] if neighbour_cell != cell: n_graph[cell].add(neighbour_cell) n_graph[neighbour_cell].add(cell) def merge_cells(merge_from, merge_to): merge_from_cell = cell_sets[merge_from] for pixel in merge_from_cell: pixcell_map[pixel] = merge_to del cell_sets[merge_from] del cell_means[merge_from] n_graph[merge_to] |= n_graph[merge_from] n_graph[merge_to].remove(merge_to) for n in n_graph[merge_from]: n_graph[n].remove(merge_from) if n != merge_to: n_graph[n].add(merge_to) del n_graph[merge_from] cell_sets[merge_to] |= merge_from_cell cell_means[merge_to] = mean_color(cell_sets[merge_to], pixlab_map) # Go through the cells from largest to smallest. Keep replenishing the list while we can still merge. last_time = time.time() to_search = sorted(cell_sets.keys(), key=lambda x:len(cell_sets[x]), reverse=True) full_list = True while len(cell_sets) > N and to_search: if time.time() - last_time > 15: last_time = time.time() print "Close color merging... (%d cells remaining)" % len(cell_sets) while to_search: cellnum = to_search.pop() close_cells = [] for neighbour_cellnum in n_graph[cellnum]: if d(cell_means[cellnum], cell_means[neighbour_cellnum]) < CLOSE_CELL_TOLERANCE: close_cells.append(neighbour_cellnum) if close_cells: for neighbour_cellnum in close_cells: merge_cells(neighbour_cellnum, cellnum) if neighbour_cellnum in to_search: to_search.remove(neighbour_cellnum) break if full_list == True: if to_search: full_list = False else: if not to_search: to_search = sorted(cell_sets.keys(), key=lambda x:len(cell_sets[x]), reverse=True) full_list = True if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for cellnum in cell_sets: cell_color = cell_means[cellnum] for pixel in cell_sets[cellnum]: frame_im.putpixel(pixel, lab2rgb(cell_color)) frame_im.save(OUTFILE_STEM + "2.png") print "Saved image %s2.png" % OUTFILE_STEM print "Stage 4: Close color merging complete, %d cells" % len(cell_sets) """ Stage 5: N-merging - merge until <= N cells Want to merge either 1) small cells or 2) cells close in color """ # Weight score between neighbouring cells by 1) size of cell and 2) color difference def score(cell1, cell2): return d(cell_means[cell1], cell_means[cell2]) * len(cell_sets[cell1])**.5 n_scores = {} for cellnum in cell_sets: for n in n_graph[cellnum]: n_scores[(n, cellnum)] = score(n, cellnum) last_time = time.time() while len(cell_sets) > N * FIRST_PASS_N_RATIO: if time.time() - last_time > 15: last_time = time.time() print "N-merging... (%d cells remaining)" % len(cell_sets) merge_from, merge_to = min(n_scores, key=lambda x: n_scores[x]) for n in n_graph[merge_from]: del n_scores[(merge_from, n)] del n_scores[(n, merge_from)] merge_cells(merge_from, merge_to) for n in n_graph[merge_to]: n_scores[(n, merge_to)] = score(n, merge_to) n_scores[(merge_to, n)] = score(merge_to, n) if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for cellnum in cell_sets: cell_color = cell_means[cellnum] for pixel in cell_sets[cellnum]: frame_im.putpixel(pixel, lab2rgb(cell_color)) frame_im.save(OUTFILE_STEM + "3.png") print "Saved image %s3.png" % OUTFILE_STEM del n_graph, n_scores print "Stage 5: N-merging complete, %d cells" % len(cell_sets) """ Stage 6: P merging - use k-means """ def form_clusters(centroids): clusters = defaultdict(set) for cellnum in cell_sets: # Add cell to closest centroid. scores = [] for centroid in centroids: scores.append((d(centroid, cell_means[cellnum]), centroid)) scores.sort() clusters[scores[0][1]].add(cellnum) return clusters def calculate_centroid(cluster): L_sum = 0 a_sum = 0 b_sum = 0 weighting = 0 for cellnum in cluster: # Weight based on cell size color = cell_means[cellnum] cell_weight = len(cell_sets[cellnum])**.5 L_sum += color[0]*cell_weight a_sum += color[1]*cell_weight b_sum += color[2]*cell_weight weighting += cell_weight return (L_sum/weighting, a_sum/weighting, b_sum/weighting) def db_index(clusters): # Davies-Bouldin index scatter = {} for centroid, cluster in clusters.items(): scatter_score = 0 for cellnum in cluster: scatter_score += d(cell_means[cellnum], centroid) * len(cell_sets[cellnum])**.5 scatter_score /= len(cluster) scatter[centroid] = scatter_score**2 # Mean squared distance index = 0 for ci, cluster in clusters.items(): dist_scores = [] for cj in clusters: if ci != cj: dist_scores.append((scatter[ci] + scatter[cj])/d(ci, cj)) index += max(dist_scores) return index best_clusters = None best_index = None for i in X(K_MEANS_TRIALS): centroids = {cell_means[cellnum] for cellnum in random.sample(cell_sets, P)} converged = False while not converged: clusters = form_clusters(centroids) new_centroids = {calculate_centroid(cluster) for cluster in clusters.values()} if centroids == new_centroids: converged = True centroids = new_centroids index = db_index(clusters) if best_index is None or index < best_index: best_index = index best_clusters = clusters del cell_means newpix_map = {} for centroid, cluster in best_clusters.items(): for cellnum in cluster: for pixel in cell_sets[cellnum]: newpix_map[pixel] = centroid if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for pixel in newpix_map: frame_im.putpixel(pixel, lab2rgb(newpix_map[pixel])) frame_im.save(OUTFILE_STEM + "4.png") print "Saved image %s4.png" % OUTFILE_STEM print "Stage 6: P-merging complete" """ Stage 7: Approximate Gaussian smoothing See http://blog.ivank.net/fastest-gaussian-blur.html """ # Hindsight tells me I should have used a class. I hate hindsight. def vec_sum(vectors): assert(vectors and all(len(v) == len(vectors[0]) for v in vectors)) return tuple(sum(x[i] for x in vectors) for i in X(len(vectors[0]))) def linear_blur(color_list): # Can be made faster with an accumulator output = [] for i in X(len(color_list)): relevant_pixels = color_list[max(i-BLUR_RADIUS+1, 0):i+BLUR_RADIUS] pixsum = vec_sum(relevant_pixels) output.append(tuple(pixsum[i]/len(relevant_pixels) for i in X(3))) return output def horizontal_blur(): for row in X(height): colors = [blurpix_map[(i, row)] for i in X(width)] colors = linear_blur(colors) for i in X(width): blurpix_map[(i, row)] = colors[i] def vertical_blur(): for column in X(width): colors = [blurpix_map[(column, j)] for j in X(height)] colors = linear_blur(colors) for j in X(height): blurpix_map[(column, j)] = colors[j] blurpix_map = {} for i in X(width): for j in X(height): blurpix_map[(i, j)] = newpix_map[(i, j)] for i in X(BLUR_RUNS): vertical_blur() horizontal_blur() # Pixel : color of smoothed image smoothpix_map = {} for i in X(width): for j in X(height): pixel = (i, j) blur_color = blurpix_map[pixel] nearby_colors = {newpix_map[pixel]} for n in neighbours(pixel): nearby_colors.add(newpix_map[n]) smoothpix_map[pixel] = min(nearby_colors, key=lambda x: d(x, blur_color)) del newpix_map, blurpix_map if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for pixel in smoothpix_map: frame_im.putpixel(pixel, lab2rgb(smoothpix_map[pixel])) frame_im.save(OUTFILE_STEM + "5.png") print "Saved image %s5.png" % OUTFILE_STEM print "Stage 7: Smoothing complete" """ Stage 8: Flood fill pass 2 Code copy-and-paste because I'm lazy """ def flood_fill(start_pixel): to_search = {start_pixel} cell = set() searched = set() start_color = smoothpix_map[start_pixel] while to_search: pixel = to_search.pop() if start_color == smoothpix_map[pixel]: cell.add(pixel) unplaced_pixels.remove(pixel) for n in neighbours(pixel): if n in unplaced_pixels and n not in cell and n not in searched: to_search.add(n) else: searched.add(pixel) return cell cell_sets = {} pixcell_map = {} unplaced_pixels = {(i, j) for i in X(width) for j in X(height)} while unplaced_pixels: start_pixel = unplaced_pixels.pop() unplaced_pixels.add(start_pixel) cell = flood_fill(start_pixel) cellnum = len(cell_sets) cell_sets[cellnum] = cell for pixel in cell: pixcell_map[pixel] = cellnum cell_colors = {} for cellnum in cell_sets: cell_colors[cellnum] = smoothpix_map[next(iter(cell_sets[cellnum]))] print "Stage 8: Flood fill pass 2 complete, %d cells" % len(cell_sets) """ Stage 9: Small cell removal pass 2 """ def score(cell1, cell2): return d(cell_colors[cell1], cell_colors[cell2]) * len(cell_sets[cell1])**.5 def remove_small(cell_size): small_cells = [] for cellnum in cell_sets: if len(cell_sets[cellnum]) <= cell_size: small_cells.append(cellnum) for cellnum in small_cells: neighbour_cells = [] for cell in cell_sets[cellnum]: for n in neighbours(cell): neighbour_reg = pixcell_map[n] if neighbour_reg != cellnum: neighbour_cells.append(neighbour_reg) closest_cell = max(neighbour_cells, key=neighbour_cells.count) for cell in cell_sets[cellnum]: pixcell_map[cell] = closest_cell if len(cell_sets[closest_cell]) <= cell_size: small_cells.remove(closest_cell) cell_color = cell_colors[closest_cell] for pixel in cell_sets[cellnum]: smoothpix_map[pixel] = cell_color cell_sets[closest_cell] |= cell_sets[cellnum] del cell_sets[cellnum] del cell_colors[cellnum] for cell_size in X(1, SMALL_CELL_THRESHOLD): remove_small(cell_size) if OUTPUT_ALL: frame_im = Image.new("RGB", im.size) for pixel in smoothpix_map: frame_im.putpixel(pixel, lab2rgb(smoothpix_map[pixel])) frame_im.save(OUTFILE_STEM + "6.png") print "Saved image %s6.png" % OUTFILE_STEM print "Stage 9: Small cell removal pass 2 complete, %d cells" % len(cell_sets) """ Stage 10: N-merging pass 2 Necessary as stage 7 might generate *more* cells """ def merge_cells(merge_from, merge_to): merge_from_cell = cell_sets[merge_from] for pixel in merge_from_cell: pixcell_map[pixel] = merge_to del cell_sets[merge_from] del cell_colors[merge_from] n_graph[merge_to] |= n_graph[merge_from] n_graph[merge_to].remove(merge_to) for n in n_graph[merge_from]: n_graph[n].remove(merge_from) if n != merge_to: n_graph[n].add(merge_to) del n_graph[merge_from] cell_color = cell_colors[merge_to] for pixel in merge_from_cell: smoothpix_map[pixel] = cell_color cell_sets[merge_to] |= merge_from_cell n_graph = defaultdict(set) for i in X(width): for j in X(height): pixel = (i, j) cell = pixcell_map[pixel] for n in neighbours(pixel): neighbour_cell = pixcell_map[n] if neighbour_cell != cell: n_graph[cell].add(neighbour_cell) n_graph[neighbour_cell].add(cell) n_scores = {} for cellnum in cell_sets: for n in n_graph[cellnum]: n_scores[(n, cellnum)] = score(n, cellnum) last_time = time.time() while len(cell_sets) > N: if time.time() - last_time > 15: last_time = time.time() print "N-merging (pass 2)... (%d cells remaining)" % len(cell_sets) merge_from, merge_to = min(n_scores, key=lambda x: n_scores[x]) for n in n_graph[merge_from]: del n_scores[(merge_from, n)] del n_scores[(n, merge_from)] merge_cells(merge_from, merge_to) for n in n_graph[merge_to]: n_scores[(n, merge_to)] = score(n, merge_to) n_scores[(merge_to, n)] = score(merge_to, n) print "Stage 10: N-merging pass 2 complete, %d cells" % len(cell_sets) """ Stage last: Output the image! """ test_im = Image.new("RGB", im.size) for i in X(width): for j in X(height): test_im.putpixel((i, j), lab2rgb(smoothpix_map[(i, j)])) if OUTPUT_ALL: test_im.save(OUTFILE_STEM + "7.png") else: test_im.save(OUTFILE_STEM + ".png") print "Done! (Time taken: {})".format(time.time() - total_time) ``` Update time! This update features a simple smoothing algorithm to make images look less fuzzy. If I update again I'll have to revamp a fair chunk of my code though, because it's getting messy & I hd 2 glf a fw thngs 2 mke t char lim. I've also made k-means weight colours based on cell sizes, which loses some details for more restrictive parameters (e.g. the centre of the nebula and American Gothic's pitchfork) but makes the overall colour choice sharper and nicer. Interestingly, it loses the whole background for raytraced spheres for P = 5. Algorithm summary: 1. **Convert the pixels to the [CIELAB colour space](https://en.wikipedia.org/wiki/Lab_color_space)**: CIELAB approximates human vision better than RGB. Originally I used [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) (hue, saturation, lightness) but this had two problems — hue of white/grey/black is undefined, and hue is measured in degrees which wrap around, making k-means difficult to use. 2. **Divide the image into like-coloured cells using flood fill:** Pick a pixel not in a cell and do a flood fill using a specified tolerance. To measure the distance between two colours I use the standard Euclidean norm. More complicated formulae are available on [this wiki article](https://en.wikipedia.org/wiki/Color_difference). 3. **Merge together small cells with their neighbours**: The flood fill generates a lot of 1 or 2 pixel cells — merge cells less than a specified size with the neighbouring cell with the most adjacent pixels. This considerably reduces the number of cells, improving running time for later steps. 4. **Merge together similarly-coloured regions**: Go through the cells in order of decreasing size. If any neighbouring cell has mean colour less than a certain distance away, merge the cells. Keep going through the cells until no more can be merged. 5. **Merge until we have less than 1.5N cells (N-merging)**: Merge cells together, using a scoring based on cell size and colour difference, until we have at most 1.5N cells. We allow a bit of leeway as we'll merge again later. 6. **Merge until we have less than P colours, using k-means (P-merging)**: Use the [k-means clustering algorithm](https://en.wikipedia.org/wiki/K-means_clustering) some specified number of times to generate clusterings of cell colours, weighting based on cell size. Score each clustering based on a variation of the [Davies-Bouldin index](https://en.wikipedia.org/wiki/Davies%E2%80%93Bouldin_index) and pick the best clustering to use. 7. **Approximate Gaussian smoothing**: Use several linear blurs to approximate Gaussian blurring ([details here](http://blog.ivank.net/fastest-gaussian-blur.html)). Then for each pixel, pick the colour out of itself and its neighbours in the pre-blurred image closest to its colour in the blurred image. This part can be optimised more time-wise if necessary as I have yet to implement the optimal algorithm. 8. **Do another flood fill pass to work out the new regions**: This is necessary as the previous step may actually generate *more* cells. 9. **Do another small cell merging pass** 10. **Do another N-merging pass**: This time we go down to N cells rather than 1.5N. The processing time for each image highly depends on its size and complexity, with times ranging from 20 seconds to 7 minutes for the test images. Because the algorithm uses randomisation (e.g. merging, k-means), you can get different results on different runs. Here's a comparison of two runs for the bear image, with N = 50 and P = 10: [![F](https://i.stack.imgur.com/zqa7Dm.png)](https://i.stack.imgur.com/zqa7D.png) [![M](https://i.stack.imgur.com/RRIV1m.png)](https://i.stack.imgur.com/RRIV1.png) --- *Note: All images below are links. Most of these images are straight from the first run, but if I didn't like the output I allowed myself up to three attempts to be fair.* ## N = 50, P = 10 [![L](https://i.stack.imgur.com/4xpS5s.png)](https://i.stack.imgur.com/4xpS5.png) [![M](https://i.stack.imgur.com/fxgius.png)](https://i.stack.imgur.com/fxgiu.png) [![a](https://i.stack.imgur.com/1Us3vs.png)](https://i.stack.imgur.com/1Us3v.png) [![r](https://i.stack.imgur.com/WvTFrs.png)](https://i.stack.imgur.com/WvTFr.png) [![k](https://i.stack.imgur.com/NvdSSs.png)](https://i.stack.imgur.com/NvdSS.png) [![d](https://i.stack.imgur.com/RXY7Xs.png)](https://i.stack.imgur.com/RXY7X.png) [![o](https://i.stack.imgur.com/LOssJs.png)](https://i.stack.imgur.com/LOssJ.png) [![w](https://i.stack.imgur.com/d5oCDs.png)](https://i.stack.imgur.com/d5oCD.png) [![n](https://i.stack.imgur.com/yRIGLs.png)](https://i.stack.imgur.com/yRIGL.png) [![g](https://i.stack.imgur.com/Neblds.png)](https://i.stack.imgur.com/Nebld.png) [![o](https://i.stack.imgur.com/S5L4js.png)](https://i.stack.imgur.com/S5L4j.png) [![l](https://i.stack.imgur.com/Ecx4Cs.png)](https://i.stack.imgur.com/Ecx4C.png) ## N = 500, P = 30 [![f](https://i.stack.imgur.com/OHxyms.png)](https://i.stack.imgur.com/OHxym.png) [![.](https://i.stack.imgur.com/OqSJ5s.png)](https://i.stack.imgur.com/OqSJ5.png) [![.](https://i.stack.imgur.com/tQmeds.png)](https://i.stack.imgur.com/tQmed.png) [![.](https://i.stack.imgur.com/Lx8gks.png)](https://i.stack.imgur.com/Lx8gk.png) [![:](https://i.stack.imgur.com/6r027s.png)](https://i.stack.imgur.com/6r027.png) [![(](https://i.stack.imgur.com/bdHwFs.png)](https://i.stack.imgur.com/bdHwF.png) [![a](https://i.stack.imgur.com/uNow3s.png)](https://i.stack.imgur.com/uNow3.png) [![a](https://i.stack.imgur.com/CaMKFs.png)](https://i.stack.imgur.com/CaMKF.png) [![a](https://i.stack.imgur.com/rofEgs.png)](https://i.stack.imgur.com/rofEg.png) [![a](https://i.stack.imgur.com/UWB3hs.png)](https://i.stack.imgur.com/UWB3h.png) [![a](https://i.stack.imgur.com/nSRlrs.png)](https://i.stack.imgur.com/nSRlr.png) [![a](https://i.stack.imgur.com/IlHNNs.png)](https://i.stack.imgur.com/IlHNN.png) But I'm pretty lazy when it comes to paint by colours, so just for fun... ## N = 20, P = 5 [![a](https://i.stack.imgur.com/L2MRIs.png)](https://i.stack.imgur.com/L2MRI.png) [![a](https://i.stack.imgur.com/xuZ96s.png)](https://i.stack.imgur.com/xuZ96.png) [![a](https://i.stack.imgur.com/ycFiVs.png)](https://i.stack.imgur.com/ycFiV.png) [![a](https://i.stack.imgur.com/UgUlRs.png)](https://i.stack.imgur.com/UgUlR.png) [![a](https://i.stack.imgur.com/yevrEs.png)](https://i.stack.imgur.com/yevrE.png) [![a](https://i.stack.imgur.com/M1Tr5s.png)](https://i.stack.imgur.com/M1Tr5.png) [![a](https://i.stack.imgur.com/jdLvts.png)](https://i.stack.imgur.com/jdLvt.png) [![a](https://i.stack.imgur.com/ePEhqs.png)](https://i.stack.imgur.com/ePEhq.png) [![a](https://i.stack.imgur.com/8iF2Ys.png)](https://i.stack.imgur.com/8iF2Y.png) [![a](https://i.stack.imgur.com/1zn90s.png)](https://i.stack.imgur.com/1zn90.png) [![a](https://i.stack.imgur.com/JqAuXs.png)](https://i.stack.imgur.com/JqAuX.png) [![a](https://i.stack.imgur.com/4e9C9s.png)](https://i.stack.imgur.com/4e9C9.png) Additionally, it's amusing to see what happens when you try to squeeze [1 million colors](https://en.wikipedia.org/wiki/File:1Mcolors.png) into N = 500, P = 30: [![a](https://i.stack.imgur.com/XVuWTm.png)](https://i.stack.imgur.com/XVuWT.png) Here's a step-by-step walkthrough of the algorithm for the underwater image with N = 500 and P = 30, in animated GIF form: [![a](https://i.stack.imgur.com/rgb5R.gif)](https://i.stack.imgur.com/rgb5R.gif) --- I've also made a gallery for the previous versions of the algorithm [here](https://sites.google.com/site/pbnfloodfiller/home). Here's some of my favourites from the last version (from when the nebula had more stars and the bear looked furrier): [![a](https://i.stack.imgur.com/e3LLTm.png)](https://i.stack.imgur.com/e3LLT.png) [![a](https://i.stack.imgur.com/XPoRum.png)](https://i.stack.imgur.com/XPoRu.png) [Answer] # Python 2 with PIL Also a Python solution and probably very much a work in progress: ``` from PIL import Image, ImageFilter import random def draw(file_name, P, N, M=3): img = Image.open(file_name, 'r') pixels = img.load() size_x, size_y = img.size def dist(c1, c2): return (c1[0]-c2[0])**2+(c1[1]-c2[1])**2+(c1[2]-c2[2])**2 def mean(colours): n = len(colours) r = sum(c[0] for c in colours)//n g = sum(c[1] for c in colours)//n b = sum(c[2] for c in colours)//n return (r,g,b) def colourize(colour, palette): return min(palette, key=lambda c: dist(c, colour)) def cluster(colours, k, max_n=10000, max_i=10): colours = random.sample(colours, max_n) centroids = random.sample(colours, k) i = 0 old_centroids = None while not(i>max_i or centroids==old_centroids): old_centroids = centroids i += 1 labels = [colourize(c, centroids) for c in colours] centroids = [mean([c for c,l in zip(colours, labels) if l is cen]) for cen in centroids] return centroids all_coords = [(x,y) for x in xrange(size_x) for y in xrange(size_y)] all_colours = [pixels[x,y] for x,y in all_coords] palette = cluster(all_colours, P) print 'clustered' for x,y in all_coords: pixels[x,y] = colourize(pixels[x,y], palette) print 'colourized' median_filter = ImageFilter.MedianFilter(size=M) img = img.filter(median_filter) pixels = img.load() for x,y in all_coords: pixels[x,y] = colourize(pixels[x,y], palette) print 'median filtered' def neighbours(edge, outer, colour=None): return set((x+a,y+b) for x,y in edge for a,b in ((1,0), (-1,0), (0,1), (0,-1)) if (x+a,y+b) in outer and (colour==None or pixels[(x+a,y+b)]==colour)) def cell(centre, rest): colour = pixels[centre] edge = set([centre]) region = set() while edge: region |= edge rest = rest-edge edge = set(n for n in neighbours(edge, rest, colour)) return region, rest print 'start segmentation:' rest = set(all_coords) cells = [] while rest: centre = random.sample(rest, 1)[0] region, rest = cell(centre, rest-set(centre)) cells += [region] print '%d pixels remaining'%len(rest) cells = sorted(cells, key=len, reverse=True) print 'segmented (%d segments)'%len(cells) print 'start merging:' while len(cells)>N: small_cell = cells.pop() n = neighbours(small_cell, set(all_coords)-small_cell) for big_cell in cells: if big_cell & n: big_cell |= small_cell break print '%d segments remaining'%len(cells) print 'merged' for cell in cells: colour = colourize(mean([pixels[x,y] for x,y in cell]), palette) for x,y in cell: pixels[x,y] = colour print 'colorized again' img.save('P%d N%d '%(P,N)+file_name) print 'saved' draw('a.png', 11, 500, 1) ``` The algorithm follows a different approach than SP3000's, starting with colours first: * Find a colour palette of *P* colours by [k-means clustering](http://en.wikipedia.org/wiki/K-means_clustering) and paint the image in this reduced palette. * Apply a slight median filter to get rid of some noise. * Make a list of all monochromatic cells and sort it by size. * Merge the smallest cells with their respective largest neighbour until there are only *N* cells left. There is quite some room for improvement, both in terms of speed and quality of the results. Especially the cell merging step can take up to many minutes and gives far from optimal results. --- ## *P* = 5, *N* = 45 ![P=5, N=45](https://i.stack.imgur.com/SnSnN.png)![P=5, N=45](https://i.stack.imgur.com/3ZNWa.png) ## *P* = 10, *N* = 50 ![P=10, N=50](https://i.stack.imgur.com/rGDR8.png)![P=10, N=50](https://i.stack.imgur.com/CK4T9.png)![P=10, N=50](https://i.stack.imgur.com/EG8uD.png)![P=10, N=50](https://i.stack.imgur.com/e8pFv.png) ## *P* = 4, *N* = 250 ![P=4, N=250](https://i.stack.imgur.com/e0TFP.png)![P=4, N=250](https://i.stack.imgur.com/Gm1ma.png) ## *P* = 11, *N* = 500 ![P=11, N=500](https://i.stack.imgur.com/QmzVS.png)![P=11, N=500](https://i.stack.imgur.com/mZxMM.png) [Answer] # Mathematica At the moment, this takes the number of colors and the Gaussian radius to be used in the Gaussian filter. The larger the radius, the greater the blurring and merging of colors. Because it does not allow for input of the number of cells, it doesn't meet one of the basic requirements of the challenge. Output includes the number of cells for each color and also the total number of cells. ``` quantImg[img_,nColours_,gaussR_]:=ColorQuantize[GaussianFilter[img,gaussR],nColours, Dithering-> False] colours[qImg_]:=Union[Flatten[ImageData[qImg],1]] showColors[image_,nColors_,gaussR_]:= Module[{qImg,colors,ca,nCells}, qImg=quantImg[image,nColors,gaussR]; colors=colours[qImg]; ca=ConstantArray[0,Reverse@ImageDimensions[image]]; nCells[qImgg_,color_]:= Module[{r}, r=ReplacePart[ca,Position[ImageData@qImg,color]/.{a_,b_}:> ({a,b}->1)]; (*ArrayPlot[r,ColorRules->{1\[Rule]RGBColor[color],0\[Rule]White}];*) m=MorphologicalComponents[r]; {RGBColor@color,Max[Union@Flatten[m,1]]}]; s=nCells[qImg,#]&/@colors; Grid[{ {Row[{s}]}, {Row[{"cells:\t\t",Tr[s[[All,2]]]}]},{Row[{"colors:\t\t",nColors}]}, {Row[{"Gauss. Radius: ", gaussR}]}},Alignment->Left]] ``` --- ## Update `quantImage2` allows to specify the desired number of cells as input. It determines the a best Gaussian Radius by looping through scenarios with greater radii until a close match is found. `quantImage2` outputs (picture, requested cells, used cells, error, gaussian Radius used). It is, however, very slow. To save time, you may start with an initial radius, the default value of which is 0. ``` gaussianRadius[img_,nCol_,nCells_,initialRadius_:0]:= Module[{radius=initialRadius,nc=10^6,results={},r}, While[nc>nCells,(nc=numberOfCells[ape,nColors,radius]); results=AppendTo[results,{nColors,radius,nc}];radius++]; r=results[[{-2,-1}]]; Nearest[r[[All,3]],200][[1]]; Cases[r,{_,_,Nearest[r[[All,3]],nCells][[1]]}][[1,2]] ] quantImg2[img_,nColours_,nCells1_,initialRadius_:0]:={ColorQuantize[GaussianFilter[img, g=gaussianRadius[img,nColours,nCells1,initialRadius]],nColours,Dithering->False], nCells1,nn=numberOfCells[img,nColours,g],N[(nn-nCells1)/nCells1],g} ``` --- [Answer] # Python 2 with PIL This is still somewhat a work in progress. Also, the code below is a horrible mess of spaghetti, and should not be used as an inspiration. :) ``` from PIL import Image, ImageFilter from math import sqrt from copy import copy from random import shuffle, choice, seed IN_FILE = "input.png" OUT_FILE = "output.png" LOGGING = True GRAPHICAL_LOGGING = False LOG_FILE_PREFIX = "out" LOG_FILE_SUFFIX = ".png" LOG_ROUND_INTERVAL = 150 LOG_FLIP_INTERVAL = 40000 N = 500 P = 30 BLUR_RADIUS = 3 FILAMENT_ROUND_INTERVAL = 5 seed(0) # Random seed print("Opening input file...") image = Image.open(IN_FILE).filter(ImageFilter.GaussianBlur(BLUR_RADIUS)) pixels = {} width, height = image.size for i in range(width): for j in range(height): pixels[(i, j)] = image.getpixel((i, j)) def dist_rgb((a,b,c), (d,e,f)): return (a-d)**2 + (b-e)**2 + (c-f)**2 def nbors((x,y)): if 0 < x: if 0 < y: yield (x-1,y-1) if y < height-1: yield (x-1,y+1) if x < width - 1: if 0 < y: yield (x+1,y-1) if y < height-1: yield (x+1,y+1) def full_circ((x,y)): return ((x+1,y), (x+1,y+1), (x,y+1), (x-1,y+1), (x-1,y), (x-1,y-1), (x,y-1), (x+1,y-1)) class Region: def __init__(self): self.points = set() self.size = 0 self.sum = (0,0,0) def flip_point(self, point): sum_r, sum_g, sum_b = self.sum r, g, b = pixels[point] if point in self.points: self.sum = (sum_r - r, sum_g - g, sum_b - b) self.size -= 1 self.points.remove(point) else: self.sum = (sum_r + r, sum_g + g, sum_b + b) self.size += 1 self.points.add(point) def mean_with(self, color): if color is None: s = float(self.size) r, g, b = self.sum else: s = float(self.size + 1) r, g, b = map(lambda a,b: a+b, self.sum, color) return (r/s, g/s, b/s) print("Initializing regions...") aspect_ratio = width / float(height) a = int(sqrt(N)*aspect_ratio) b = int(sqrt(N)/aspect_ratio) num_components = a*b owners = {} regions = [Region() for i in range(P)] borders = set() nodes = [(i,j) for i in range(a) for j in range(b)] shuffle(nodes) node_values = {(i,j):None for i in range(a) for j in range(b)} for i in range(P): node_values[nodes[i]] = regions[i] for (i,j) in nodes[P:]: forbiddens = set() for node in (i,j-1), (i,j+1), (i-1,j), (i+1,j): if node in node_values and node_values[node] is not None: forbiddens.add(node_values[node]) node_values[(i,j)] = choice(list(set(regions) - forbiddens)) for (i,j) in nodes: for x in range((width*i)/a, (width*(i+1))/a): for y in range((height*j)/b, (height*(j+1))/b): owner = node_values[(i,j)] owner.flip_point((x,y)) owners[(x,y)] = owner def recalc_borders(point = None): global borders if point is None: borders = set() for i in range(width): for j in range(height): if (i,j) not in borders: owner = owner_of((i,j)) for pt in nbors((i,j)): if owner_of(pt) != owner: borders.add((i,j)) borders.add(pt) break else: for pt in nbors(point): owner = owner_of(pt) for pt2 in nbors(pt): if owner_of(pt2) != owner: borders.add(pt) break else: borders.discard(pt) def owner_of(point): if 0 <= point[0] < width and 0 <= point[1] < height: return owners[point] else: return None # Status codes for analysis SINGLETON = 0 FILAMENT = 1 SWAPPABLE = 2 NOT_SWAPPABLE = 3 def analyze_nbors(point): owner = owner_of(point) circ = a,b,c,d,e,f,g,h = full_circ(point) oa,ob,oc,od,oe,of,og,oh = map(owner_of, circ) nbor_owners = set([oa,oc,oe,og]) if owner not in nbor_owners: return SINGLETON, owner, nbor_owners - set([None]) if oc != oe == owner == oa != og != oc: return FILAMENT, owner, set([og, oc]) - set([None]) if oe != oc == owner == og != oa != oe: return FILAMENT, owner, set([oe, oa]) - set([None]) last_owner = oa flips = {last_owner:0} for (corner, side, corner_owner, side_owner) in (b,c,ob,oc), (d,e,od,oe), (f,g,of,og), (h,a,oh,oa): if side_owner not in flips: flips[side_owner] = 0 if side_owner != corner_owner or side_owner != last_owner: flips[side_owner] += 1 flips[last_owner] += 1 last_owner = side_owner candidates = set(own for own in flips if flips[own] == 2 and own is not None) if owner in candidates: return SWAPPABLE, owner, candidates - set([owner]) return NOT_SWAPPABLE, None, None print("Calculating borders...") recalc_borders() print("Deforming regions...") def assign_colors(): used_colors = {} for region in regions: r, g, b = region.mean_with(None) r, g, b = int(round(r)), int(round(g)), int(round(b)) if (r,g,b) in used_colors: for color in sorted([(r2, g2, b2) for r2 in range(256) for g2 in range(256) for b2 in range(256)], key=lambda color: dist_rgb(color, (r,g,b))): if color not in used_colors: used_colors[color] = region.points break else: used_colors[(r,g,b)] = region.points return used_colors def make_image(colors): img = Image.new("RGB", image.size) for color in colors: for point in colors[color]: img.putpixel(point, color) return img # Round status labels FULL_ROUND = 0 NEIGHBOR_ROUND = 1 FILAMENT_ROUND = 2 max_filament = None next_search = set() rounds = 0 points_flipped = 0 singletons = 0 filaments = 0 flip_milestone = 0 logs = 0 while True: if LOGGING and (rounds % LOG_ROUND_INTERVAL == 0 or points_flipped >= flip_milestone): print("Round %d of deformation:\n %d edit(s) so far, of which %d singleton removal(s) and %d filament cut(s)."%(rounds, points_flipped, singletons, filaments)) while points_flipped >= flip_milestone: flip_milestone += LOG_FLIP_INTERVAL if GRAPHICAL_LOGGING: make_image(assign_colors()).save(LOG_FILE_PREFIX + str(logs) + LOG_FILE_SUFFIX) logs += 1 if max_filament is None or (round_status == NEIGHBOR_ROUND and rounds%FILAMENT_ROUND_INTERVAL != 0): search_space, round_status = (next_search & borders, NEIGHBOR_ROUND) if next_search else (copy(borders), FULL_ROUND) next_search = set() max_filament = None else: round_status = FILAMENT_ROUND search_space = set([max_filament[0]]) & borders search_space = list(search_space) shuffle(search_space) for point in search_space: status, owner, takers = analyze_nbors(point) if (status == FILAMENT and num_components < N) or status in (SINGLETON, SWAPPABLE): color = pixels[point] takers_list = list(takers) shuffle(takers_list) for taker in takers_list: dist = dist_rgb(color, owner.mean_with(None)) - dist_rgb(color, taker.mean_with(color)) if dist > 0: if status != FILAMENT or round_status == FILAMENT_ROUND: found = True owner.flip_point(point) taker.flip_point(point) owners[point] = taker recalc_borders(point) next_search.add(point) for nbor in full_circ(point): next_search.add(nbor) points_flipped += 1 if status == FILAMENT: if round_status == FILAMENT_ROUND: num_components += 1 filaments += 1 elif max_filament is None or max_filament[1] < dist: max_filament = (point, dist) if status == SINGLETON: num_components -= 1 singletons += 1 break rounds += 1 if round_status == FILAMENT_ROUND: max_filament = None if round_status == FULL_ROUND and max_filament is None and not next_search: break print("Deformation completed after %d rounds:\n %d edit(s), of which %d singleton removal(s) and %d filament cut(s)."%(rounds, points_flipped, singletons, filaments)) print("Assigning colors...") used_colors = assign_colors() print("Producing output...") make_image(used_colors).save(OUT_FILE) print("Done!") ``` ## How it works The program divides the canvas into `P` regions, each of which consists of some number of cells without holes. Initially, the canvas is just divided into approximate squares, which are randomly assigned to the regions. Then, these regions are "deformed" in an iterative process, where a given pixel can change its region if 1. the change would decrease the pixel's RGB distance from the average color of the region that contains it, and 2. it does not break or merge cells or introduce holes in them. The latter condition can be enforced locally, so the process is a bit like a cellular automaton. This way, we don't have to do any pathfinding or such, which speeds the process up greatly. However, since the cells can't be broken up, some of them end up as long "filaments" that border other cells and inhibit their growth. To fix this, there is a process called "filament cut", which occasionally breaks a filament-shaped cell in two, if there are less than `N` cells at that time. Cells can also disappear if their size is 1, and this makes room for the filaments cuts. The process ends when no pixel has the incentive to switch regions, and after that, each region is simply colored by its average color. Usually there will be some filaments remaining in the output, as can be seen in the examples below, especially in the nebula. ## P = 30, N = 500 ![Mona Lisa](https://i.stack.imgur.com/YMVem.png) ![Baboon](https://i.stack.imgur.com/U99p9.png) ![Colorful balls](https://i.stack.imgur.com/jBTga.png) ![Nebula](https://i.stack.imgur.com/w9HmM.png) More pictures later. Some interesting properties of my program are that it is probabilistic, so that the results may vary between different runs, unless you use the same pseudorandom seed of course. The randomness is not essential, though, I just wanted to avoid any accidental artifacts that may result from the particular way Python traverses a set of coordinates or something similar. The program tends to use all `P` colors and almost all `N` cells, and the cells never contain holes by design. Also, the deformation process is quite slow. The colored balls took almost 15 minutes to produce on my machine. On the upside, it you turn on the `GRAPHICAL_LOGGING` option, you'll get a cool series of pictures of the deformation process. I made the Mona Lisa ones into a GIF animation (shrunk 50 % to reduce the file size). If you look closely at her face and hair, you can see the filament cutting process in action. ![enter image description here](https://i.stack.imgur.com/rRCI9.gif) ]
[Question] [ *Alternesting*, is the act of taking a string and nesting it in alternating brackets. Here is how you *alternest* a string. * For a string of length **N**, take the center **N** characters, and surround them in parenthesis. So if our string was `Hello world!` (12 characters), we'll end up with ``` (Hello world!) ``` * Then, take the remaining center `n-2` characters, and surround them in square brackets. In this case, the center 10 characters are `ello world`, so the next iteration is: ``` (H[ello world]!) ``` * As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between `()` and `[]`. Here are the last steps: ``` (Hello world!) (H[ello world]!) (H[e(llo worl)d]!) (H[e(l[l(o[ w]o)r]l)d]!) ``` Since there are only two characters left in the middle on the last iteration, we stop. Our final string is ``` (H[e(l[l(o[ w]o)r]l)d]!) ``` Note how there are two characters in the middle brackets. This happens when the input is an even length. If the input was an odd length (for example, `Hello, world!` with a comma added), we would have only one character in the middle: ``` (H[e(l[l(o[,( )w]o)r]l)d]!) ``` For today's challenge, you must write a program or function that takes a string as input, and alternests it, outputting the new string. You can take input and output in any reasonable format you like. The input will always be at least one character long, and will only contain printable ASCII. You can also assume that the input will *not* contain any parenthesis or square brackets. For traditional languages, this shouldn't matter too much, but it might make it easier for some esoteric languages. As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition, so try to make the shortest possible answer in the language of your choice. Have fun! ## Test IO ``` #Input #Output "Alternesting is fun!" --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!) "PPCG" --> (P[PC]G) "Code-golf" --> (C[o(d[e(-)g]o)l]f) "4 8 15 16 23 42" --> (4[ (8[ (1[5( [1]6) ]2)3] )4]2) "a" --> (a) "ab" --> (ab) "abc" --> (a[b]c) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~70~~ ~~69~~ 65 bytes *-1 byte thanks to @Uriel* *-4 bytes thanks to @xnor* ``` f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b] ``` [Try it online!](https://tio.run/##FY49C4MwGIT3/orr9Caoxa@WErBQHLq6hwyKxgoaxaRDEfvXrS5398DB3fR179Ek26azvhyquoT1qywUFqWpiUmSlfKsDJWnmZWRCCLl/yruHVnJYBePuDpamx5nWHQGkp69a2bTWNeZFp2F/pgz@aCiyF@H52PdBO3Y6wNS3BFdEd0QJ0hjUuIETHNnHKNFxOGK4IFlpcs@MJSOWR/7F8759gc "Python 3 – Try It Online") [Answer] # C, ~~143~~ ~~137~~ 135 bytes ``` i,l,k;f(char*s){for(k=i=0,l=strlen(s);*s;printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++))i>l/2-1&&l&1^1&&putchar(*s++,k=++l);puts(")");} ``` [Try it online!](https://tio.run/##TY3BisIwEIbvPsUYaJlpUnYbXVkIXVg87NW7uCCx6YbGVJJ4Ep@9mwqCc/mZ7xvm13Wv9TRZ4cSgDOq/Y6gi3cwYcGht@y5cG1NwncdIqorqEqxPBlmhC80Ew/2B2N5yXkguK7Rf7k3y5UAHUUXOiR6gbsrSlc1vjss1zRU4WzG0nDtSmUVkxEjdp/wczkfrkRa3BeTJVd8udcF3MVnfg41grn6Zj596t9v@vKzb8dTV/ejMC1vDJzQf0GxArmAtZ3Of/gE) **Explanation:** ``` // Function (and variable) declaration. i,l,k;f(char*s){ // Start the loop and initialize the variables. The loop terminates // when the NUL-terminator of the string is reached. for(k=i=0,l=strlen(s);*s;<this part saved for later>) // Check if we have reached the middle of the string. Because of the // short-circuiting of the conditions, we don't need to use an 'if' // statement here; if a condition is false, no further conditions // are evaluated. i>l/2-1&& // Equivalent to '!(l%2)', but one byte shorter. Checks if the length // of the string is even. l&1^1 // If we have reached the middle and the length of the string is even, // we'll need to skip one bracket, so we'll print the current character // of the string and increment the pointer. Also we increment 'l' to // avoid this getting done more than once, and give 'k' a non-zero // value. &&putchar(*s++,k=++l); // The following is inside the 'increment' part of the 'for' loop. // We print two characters. The first one is a bracket and the second // one is the current character in the string. printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++) // The type of bracket is chosen depending on the value of 'i'. A // character from the string "([])" is selected with the index 'i%2 + 2', // if we have reached the middle of the string, and with index 'i%2', if // we haven't. // The exact part where this change happens depends on the parity of // the string length, so we use 'k' to signal if the length is even or // odd. If the length is odd, 'k==0', so '+!k' is the same as '+1'. // Otherwise 'k' is non-zero, so '+!k' is the same as '+0'. // Output the final ')'. puts(")");} ``` [Answer] # [Retina](https://github.com/m-ender/retina), 52 bytes ``` +`(?<!\()[^()]+(?!\)) ($&) (\(.)\( $1[ r`\)(.\)) ]$1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0HD3kYxRkMzOk5DM1Zbw14xRlOTS0NFDUjEaOhpxmhwqRhGcxUlxGhq6IGkYlUM///3SM3JyVcozy/KSVEEAA "Retina – Try It Online") The first stage inserts pairs of parentheses between each pair of input characters, while the second and third stages correct alternate parentheses to brackets. [Answer] # JavaScript (ES6), ~~69 68~~ 62 bytes *-6 thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* ``` f=([c,...s],i,l=s.pop()||s)=>c?'[('[i^=1]+c+f(s,i)+l+'])'[i]:s ``` [Try it online!](https://tio.run/##dY9Ba8MwDIXv@xWqL5VImpI0LWWQjZJDr7kbDRI3Dh7GLnW6U/975sNgI1kFQkK89/H02X61Qd3Mddw4f@mnSVcoVZplWeDUpLYK2dVfkR6PQNWbel9LXEvzUeWcqERjSA0lNlkzxSu/hkl5F7ztM@sH1ChOduxvrg@jcQOYAPruVoIItlvAk7Q4yh5v0mEvQ9yN44GADQUG0nwnxyt6mSGbpj4LmNUPspFNzeeFpY6fbQZvtVhaaunxElNsaGBPlvXCXcIR8j3kByh2UBbir7uUgMfYudwjyJwPMX5Buxi/jHNOahe5f0ntUt2J5@ruH7kST@WyY0XTNw "JavaScript (Node.js) – Try It Online") [Answer] # Sed, 78 Score includes +1 for `-r` option passed to sed. ``` s/.*/(&)/ : s/(\(.)([^][]+)(.\))/\1[\2]\3/ t s/(\[.)([^)(]+)(.\])/\1(\2)\3/ t ``` [Try it online](https://tio.run/##JcqxCsIwEADQPV9xLvZOaULSKuImHVy7JxGUprVQUujF748Y3/xeT35nDgPUG1SZlTwo3JMSV8EKHUpC@/DWHwmlI1JOW2e8a5RIJdgSCP/B/wI6QyXkKt@WFLYYOM1xgplh/MSd6PvuLrp1CPW0LqNo4QL6BPoMpoHWfAE). [Answer] # [V](https://github.com/DJMcMayhem/V), ~~25~~ ~~26~~ 25 bytes ~~1~~ 2 bytes off thanks to @DJMcMayhem ``` òC()Pé %llòÍî òF)%r[r]; ``` [Try it online!](https://tio.run/##ATAAz/92///DskMoKRtQw6kKJWxsw7LDjcOuCsOyRiklclsPcl07//9oZWxsbG8gd29ybGQ "V – Try It Online") Borrowed some of [@udioca's ideas.](https://codegolf.stackexchange.com/a/96665/62346) ~~Also finally used the [surround plugin](https://github.com/tpope/vim-surround) included in V for an answer, although it may not have been the best way, who knows.~~ The plugin does NOT want to be used. Hexdump: ``` 00000000: e3e1 0a6b f2e9 286c 6ce9 5b6c 6cf2 6af2 ...k..(ll.[ll.j. 00000010: e129 6868 e15d 6868 f2cd ce .)hh.]hh... ``` Explanation: ``` -> |abcdefg (the input, where | is the cursor) ò ' recursively C() ' (C)hange from the cursor to the end of the line to '()' -> (|) (where | is the cursor) P ' (P)aste the changed bit (what was there) left of the cursor -> (abcdef|g) é ' nsert a newline -> (abcdef |g) % ' Goto the previous matching parenthese -> |(abcdef g) ll ' Move two characters right -> (a|bcdef g) ò ' End recursive loop (it will break on ll when there are no characters left -> (a(b(c d) e) f) Íî ' Remove all newlines -> (a(b(cd)e)f|) ò ' Recursively F) ' Go backwards to the next ) -> (a(b(cd)e|)f) %r[ ' Go to the matching paren and (r)eplace it with [ -> (a|[b(cd)e)f)  ' Go back to the previous cursor location -> (a[b(cd)e|)f) r] ' (r)eplace this paren with ] -> (a[b(cd)e|]f) ; ' repeat F) -> (a[b(cd|)e]f) ' implicitly end recursion ``` [Answer] # [Haskell](https://www.haskell.org/), 96 91 81 79 77 bytes ``` (cycle"()[]"!) (l:r:a)!k|[x]<-k=[l,x,r]|x:y<-k=l:x:a!init y++[last y,r]|2>1=k ``` [Try it online!](https://tio.run/##FclBC4IwGIDhu7/ic14UNajjaIFIeLEQotOSGDZt@DlFJyjZb7e8vQ/vWwy1RFw/oQNpdE3uUXKGOMvACb@WYI/VLeYCJXE9nhPbs1ykPRWeXS98yo9hzTgGU9Dny0TnjUgnKmyllYHZ9zmK4R/bP5z2rF4boTQwaER3eYLbjeZm@lTDDoQHnERoZK/lYJSuQA1QjtomAZC4fcmwarEk@foD "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 79 77 bytes -2 bytes thanks to @Value Ink ``` ->s{z=s.size (z/2+z%2).times{|i|s.insert k=i*2,'(['[i%2] s[~k]+=')]'[i%2]} s} ``` [Try it online!](https://tio.run/##NcmxCsIwEADQPV8Rh3KttRGyRxA/I2QRL@VoTUsvGUxbfz0K4vreku6v4k3pLrxmw4opo6jzWbe50o2K9EReN9pYUWBcohwMHfUJaguWKu0E2/fgWgON@8EueC9ziiy9hesYcQnIkUIv6UspHMCJf9@mB3b9NHpw5QM "Ruby – Try It Online") [Answer] # Javascript(ES6) 110 105 bytes Thanks to @powelles for reminding me about `x%y<1`. Thanks @Luke for `a-b?y:x` ``` i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d-b?(d%1==0?!e:e)?')':']'):'').join`` ``` ``` let f=i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d==b?'':(d%1==0?!e:e)?')':']')).join`` ``` ``` <input onkeyup="result.textContent = f(this.value)"/> <p id="result"></p> ``` --- The first thing in understanding this beast is ungolfing it: ``` function alternest(input) { //input is i in the original let inputArray = Array.from(input); //the [...i] section let result = inputArray.map((item, index, baseArray) => { //result is an added helper variable let middle = input.length / 2 - 1, //the middle of the string alternate = index % 2 == 0; //should you alternate from '(' and '[' or ')' and ']' let symbol; //the alternating symbol if(middle > index) { //if its opening braces symbol = alternate ? '[' : '('; } else if(middle < index) { if(middle % 1 === 0) //if middle is a whole number alternate = !alternate; //reverse alternate symbol = alternate ? ')' : ']'; } else { //if middle === index symbol = ''; //there's no symbol in the center for even alternests } return item + symbol; //convert the array item into the item and symbol }).join(''); return '(' + result; //add the first symbol. } ``` Almost every line is a part of the golfed version, so stepping through: **Line 1:** The function statement becomes an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), renaming `input` to `i`. Becomes `i=>`. **Line 2:** `Array.from` is the new, proper way of converting a string into an array, and what we use in on this line. However along with it, the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) is a cheaper way than the old `.split('')` way, to do it, which is what is used in the golfed version. Ends up as `[...i]`. **Line 3:** [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) loops through an array, giving you three arguments: `item`(`a` in the golfed), `index`; golfed as `b`, and `baseArray` or `c`. While we only care about `item` and `index`, we kept `baseArray`(see line 4 for why). Golfs to `.map((a,b,c,...)=>...`. **Line 4:** The variable `middle`, the or the argument `d` in the golfed version is created to save a few bytes when it is repeated. The argument `c` had to be kept for argument `d` to be created. Is converted to `(...,d=i.length/2-1,...)`. **Line 5**: The variable `alternate`, or argument `e` is used to check what character it was on "(" or "[" or if it was past the middle, ")" and "]". `b%2<1` is equal to `b%2==0` because it can't be anything less than 1, but 0 in this case. Equals `(...,e=b%2<1)`. **Line 6:** A helper variable to allow me to convert the [`ternary operators`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to `if` statements. Isn't anything in the actual codegolf. **Lines 7-8**: If the index is less than the middle of the string set the symbol to an alternation of "[" and "(". Equates to `d>b?e?'[':'(':...`. **Lines 9-12**: Else (if index is greater than middle), check if middle is a whole number, if so switch the alternation. Then set the symbol to an alternation of ')' and ']'. Obfuscated to `(d%1==0?!e:e)?')':']'`. **Lines 13-15**:If the in the middle set the symbol to an empty string. This doesn't apply to odd alternesters, because middle has a decimal. Becomes: `d==b?'':...`. **Line 16**: Joins the character array back into a string. Equates to `.join```. **Line 17**: Returns the starting symbol "(" and the result. Correlates to `'('+...`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes ``` LHĊRị ç⁾)]żUFUż@ç⁾([$ ``` [Try it online!](https://tio.run/##y0rNyan8/9/H40hX0MPd3VyHlz9q3KcZe3RPqFvo0T0OYK5GtMr///8dc0pSi/JSi0sy89IVMosV0krzFAE "Jelly – Try It Online") ``` LHĊRị - helper function. Takes inputs of the input string and list of brace types L - length of the input string HĊ - number of parenthesis/brackets facing a single direction R - range ị - indexed into right argument: list of brace types ')]' or '([' ç⁾)]żUFUż@ç⁾([$ - main function ç⁾)] - get list of left-facing parentheses/brackets żU - zip to the end (U) of the input string FU - move the beginning of the string back to the beginning ż@ - zip with (to the start of the string): ç⁾([$ -the list of right-facing parentheses/brackets to the beginning ``` *-2 bytes thanks to @EricTheOutgolfer* [Answer] # SCALA, ~~140~~ 138 chars, ~~140~~ 138 bytes I'm sorry I couldn't do better ... I'm sure there are many ways to improve it. Still: ``` val n=s.length-1 var l="" var r="" for(i<-0 to n/2){l+=(if(i%2<1)"("else"[") if(i!=n-i)l+=""+s(i) r=""+s(n-i)+(if(i%2<1)")"else"]")+r} l+r ``` [Try it online!](https://tio.run/##fY9BS8QwEIXP5lfMBoSEWt3WVUTMYdmDXoQFj4uHbDutkSEpSVyF0t9eW1fRSzzN473vwZtQadKj279iFeFRGwv4EdHWAdZd17OTGhvQFNFbDFGE26fojW3l91X9eNAEVoVzQtvGl7xgB@2BFOdfws@icV6Yu3wJ0YG9KGVPmRKmEea0VGopueBIAfmOSza7C2VzIyeG8ywII5k/qtnN/vbksffMZeYHRpkfB9ZNsyJZ8buZPyCRO4N356lecCmTzP/I@kdOf4MJ0LzZFLrdbu4T0cbVmLeOmkS@ghsorqC4hvISVmWC0il/nwyqORnGTw) Thanks for this challenge, that was quite hard for me. EDIT : -2 bytes thanks to Mar Dev. PS : I will ask something though. I understand why [THIS CODE](https://tio.run/##VY4xa8MwEEbn6ldcBAUdrtvUY4mGbFkydSwdZPvsqBwnIwk3YPzbXbsJlE7fG94HLzWO3RLqL2oynJ0XoGsmaRMch2FSDy114DhTFErZpLf3HL30eF87LaNjEJuemaTPl/JVjS4CW61/IW7QhWj8odxDDiAvFU5suTC@M/6xsnaP2mjiRPpDY5GMR7W9VpLS4z8Pb97n6sVZcRGXWQ1rR2Yxf5H6RMzhCVz9HSK3O42o5uUH) keeps duplicating the central char of my string if I have an odd length (I just don't check and add it twice, in both `l` and `r` strings). But why do I get a pair of parenthesis when I try correcting it like [THAT](https://tio.run/##VY49C8IwFEVn8yueASGh1q9RzODm4uQoDtG@1sjjpSRBhdLfXlsVxOkeLpzLjRdLtvPnG14S7K1jwGdCLiJs67oRowJLsJQwMMak4vqQguNKf9M03d0SsIkzQq7SNV@Kuw1ARso3hAFKH5Tb5AtIHni@0g0ZypQrlZusjFloqSRSRHmU@lOPDedOR@W0FsNCFtVQ/Dn645x6J7SCstC1ou4/JWL1Oyx3SOSnYM8PH6gYy36x7V4)? I don't understand at all. [Answer] # Perl, ~~77~~ 74 (73 + 1) bytes Regular expressions are glorious things. Run with the `-p` command line flag. ``` $x=qr/[^]()[]/;$z=qr/(^|$x)\K($x+)($|$x)/;s/$z/[$2]$3/ while s/$z/($2)$3/ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes ``` 2ä`Rð«„)]Ig©×øRJ®Èƒ¦}s„([®×søJì ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f6PCShKDDGw6tftQwTzPWM/3QysPTD@8I8jq07nDHsUmHltUWAyU0ooHc6cWHd3gdXvP/v2NOSWpRXmpxSWZeukJmsUJaaZ4iAA "05AB1E – Try It Online") **Explanation** With examples for input: `abcd` / `abcde` ``` 2ä` # split input to 2 separate parts on stack # RESULT: 'ab','cd' / 'abc', 'de' R # reverse the second part ð« # append a space „)] # push the string ")]" Ig©× # repeat it len(input) times ø # zip with the second part of the input string RJ # reverse and join to string # RESULT: ' )c]d)' / ' )d]e)' ®Èƒ¦} # remove the first (1,2) chars for (odd,even) length input # RESULT: 'c]d)' / ')d]e)' s # swap the first part of the input string to top of stack „([®× # repeat the string "([" len(input) times sø # zip with first part of input string # RESULT: ['(a', '[b'] / ['(a', '[b', '(c'] Jì # join to string and prepend to the second part ``` [Answer] # C++ 14, ~~154~~ ~~145~~ 134 bytes (Thanks to ideas by ceilingcat for extra bytes 145->134) [Recursive] ``` #include <regex> using S=std::string;S L(S i,int b=1){int l=i.size();return"(["[b]+(l<3?i:i[0]+L(i.substr(1,l-2),!b)+i[l-1])+"])"[b];} ``` # C++ 14, 177 bytes [Iterative] ``` auto l(string s){int z=s.length();string r(z*2+z%2,'-');int i=0;for(;i<z;i+=2)r[i]=i/2%2?'[':'(',r[i+1]=s[i/2];for(i=z;i<2*z;i+=2)r[i]=s[i/2],r[i+1]=(i+1)/2%2?')':']';return r;} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` f=->s,i=0{a,*b,c=s;a ?["(["[i],a,*f[b,~i],*c,")]"[i]]:''} ``` [Try it online!](https://tio.run/##fZDBasMwDIbveQrVO9QOTlnatJSNdJQces1d6BCncWbInBIn0NFur545YzA2SgVCQny/9KNuUO/jqNNo56RJHy@FDJUsU/dcwAsyjgwNST/UqOSnb8NSMkHTlJ7m848RA7Zv@qqzleuNrcE40IOdMQD5EEU74HtseI8V79DyCp3vjaVaABnhCISmQViaiYDleXbwsv/xsybHPKODx7L2WEV122h2C8uw5Ud/LRI1taIh7RUJbCFeQ7yB5QqSJfurSBD41meMaw4Y08ZbW4qVt5b4GrDihqdfdTERit0j1DdSsjsIKipFQIu34nS5nq8n0HhelK9F5yicnvwF "Ruby – Try It Online") Recursive function similar in spirit to ovs's [Python answer](https://codegolf.stackexchange.com/a/128899/78274). Inputs and outputs arrays of characters. Note that we could shave off 3 more bytes, and in the test suite on TIO, where we join the arrays back to strings, the visible result would look unchanged: ``` f=->s,i=0{a,*b,c=s;a ?["(["[i],a,f[b,~i],c,")]"[i]]:p} ``` However, this would produce nested arrays and nils in the raw output, which is probably too weird for a "reasonable" output format. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 42 (!) bytes ``` M?!lHH+@,\[\(G++hHg!GPtH+?qlH1keH@,\]\)Gg1 ``` [Test it online!](https://pyth.herokuapp.com/?code=M%3F%21lHH%2B%40%2C%5C%5B%5C%28G%2B%2BhHg%21GPtH%2B%3FqlH1keH%40%2C%5C%5D%5C%29Gg1&input=%22Code-Golf%22&debug=0) The input must be quoted. **Explanations** ``` M # Define a function g with arguments G and H ?!lHH # If len(H) == 0, return H. Otherwise... +@,\[\(G # Concatenate [ or ( to... +hHg!GPtH # ...to H[0] concatenated to g(not(G), H[1:-1]), itself concatenated... + ?qlH1keH # ...to H[-1] if len(H) != 1, otherwise to "" (that's for odd length input strings)... + @,\]\)G # ...and to that concatenate ] or ). g1 # Call g(True, Q). Q is implicit input ``` So basically I progressively remove the head and end of H (being the input string in the beginning) while concatenating the parentheses/brackets. G is just a boolean which remembers if I must use brackets or parentheses. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~49~~ 42 bytes ``` g;îD„([×s£©"s‚.Bøvy¬ðQi¦}}JR"DU.V®D∞sKRX.V ``` [Try it online!](https://tio.run/##AVAAr/8wNWFiMWX//2c7w65E4oCeKFvDl3PCo8KpInPigJouQsO4dnnCrMOwUWnCpn19SlIiRFUuVsKuROKInnNLUlguVv//SGVsbG8sIFdvcmxkIQ "05AB1E – Try It Online") [Answer] ## PowerShell, 125 119 111 bytes ``` {param($s)for($p='()[]';($f,$s,$g=$s-split'(?<=.)(.+)(?=.)')[0]){$l+=$p[$i++]+$f;$r=$g+$p[$i++]+$r;$i%=4}$l+$r} ``` [Try it online!](https://tio.run/##RYoxa8MwGET/yle4VBJyTJO6oeAKEzJ0zW5MsVvJEai2kFwyuP7trpKlw909HufHqw7xop1b0al19m1ovzmiMGPg8IpxUTes5DAZYoZeIW6jd3ZivHpTueC5FLxKwET91IgZTir4GlbKRsKUCAq9/DehhN2oYkk/hGVlRzfpMOg42aEnG8n8DA8sY@fz6T3NafzS2350JnFBr7R7od2B9s9U7JNpb@nu9cl@N/MjoSN8LOsf) Previous version\* ``` {for($s="($args)";$s-ne($t=$s-replace'(\(.)([^][]+)(.\))','$1[$2]$3'-replace'(\[.)([^)(]+)(.\])','$1($2)$3')){$s=$t}$s} ``` \*Thanks @Digital Trauma. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 82 bytes (81 bytes +1 for `≡` flag) ``` (\(.)([^[])(.+?)([^\]])(.\)) (\(.)(..?)(.\)) ^[^\(].* \1[\2(\3)\4]\5 \1[\2]\3 (&) ``` [Try it online!](https://tio.run/##LYk7CoNAEED7OcWkCTMJWVBXSSfBIq29s8ImfhBkJX4OkWPkarnIRjHwivd4r8VWo/ckpJiKsjBM6pxuKmZzYYZ9KpX@u1wnGXUCCQoJSSIWbSTe00gEdGTvb/1cj66e5s612E3YLO4AeZ7dIRuq@tIOfQMarxjEGCQYRqhDsGAfK0//fX9@ "QuadR – Try It Online") [Answer] # AWK, 118 bytes ``` {b=")";for(j=l=length(c=$0);j>0;){x=substr(c,j--,1);b=(j>l/2?(((d=!d)?"]":")")x):j==l/2?x:((d=!d)?"(":"[")x)b}print b} ``` Tested with gawk, but it should work with any compliant awk interpreters ``` $ awk -f alternesting.awk <<< 'abc' (a[b]c) ``` [Answer] # JavaScript, 101 bytes Not a winner, but it was interesting to try the `replace` approach. This could definitely be improved, but it got out of hand quick... ``` s=>"("+s.replace(/./g,(a,b)=>a+(l%2|b*2+2!=l?")][("[3*(c=l>(b+=l%2-1)*2+2)+(b-c*l)%2]:""),l=s.length) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 124 bytes ``` c->{String s="";for(int l=c.length-1,a=l/2;a>=0;)s=(a%2<1?"(":"[")+(a<-~l/2?c[a]+s+c[l-a]:c[a])+(a--%2<1?")":"]");return s;} ``` [Try it online!](https://tio.run/##dZJRb9owEMff9ymulpBskWRLgKoiBISQ1odqK1IfLT8Y46Rhrp3ZTjVUsa/ODIR2o6ulKGf7d3f/v3wb/sxj00i9Wf/YN@1K1QKE4s7BN15rePkE4Dz34XQTyKT1tUrKVgtfG5187YKJeOSWsujB21pXUyih2It4@nLagysQyktjca09qEIkSurKP8ZpxAv1Ocv5tPiSE1dg3ssm6QxhNEYUkT7mk/h3AGaCctZ3fUFVzNn4sDtcxvEJJwFniORW@tZqcPluD2HlQXpnqHPwbOo1PAVb@CSMMuC2cuToEsBL5zGaKy@tDuFBee0gmL1CABHCc6qwpxJbqrGkLsS1ZhUBVhPHgJSsJZpdkaDkr3LL5eIWwbsVyi3pcsFuL/CFWcu4MqpEl/iCGrwO3WNSMUMUKy8yh3AD6QjSa8gGMMzQW@aQAr4JX0pHGGjKroPkjAyC5GH4/1uF/0frqQq/JFfoI3L1DhXoA5SumOjo3duoHR/qmHueIG8j6GL5q5HCy/X52bpjK12rPBRQJrxp1BaHnMSbRZjMubV8i0mn6WHrvHxKTOuTJmT6EqNenA3cGHrxcOSg53oaRaeW515RVz6RP1uuHH7VMEP3d2H8vhsP93eAUf9800evtnaHrvs/ "Java (OpenJDK 8) – Try It Online") ## Credits * -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ò≥◘■O║£/öτt≈K↔ì♂≈-⌂6=═°!b ``` [Run and debug it](https://staxlang.xyz/#p=95f208fe4fba9c2f94e774f74b1d8d0bf72d7f363dcdf82162&i=%22Hello+world%21%22%0A%22Hello,+world%21%22%0A%224+8+15+16+23+42%22&m=2) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 77 bytes Not the best JS solution, but it could interest some people : this solution uses recursive calls with inversion of the 2 optional parameters at each step to alternate between `()` and `[]` ``` f=(s,a="()",b="[]")=>a[0]+(s[2]?s[0]+f(s.slice(1,-1),b,a)+s.slice(-1):s)+a[1] ``` [Try it online!](https://tio.run/##fczNCoMwEATge58i5rSLUWuPQtqr7xByiEkslsWIkdq3T3@gYKHtnIaB@S7maqKdh2kpxuB8Sr2EKIzkgFx0kivNUR6N2uscojroU3zWHmIZabAealHUKDphMH9Pj6GJmBtV62TDGAP5ksIZeuCtJwqCrWEml3FEVlX@Nnm7eMcaBq3yQIogKAEMVx1w1oROZ7j7Bm2cnxD7p5jXdZNPxWC6Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Initially inspired by [Arnauld's solution](https://codegolf.stackexchange.com/a/128920/58974). ``` V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VrBnIigpW10i8ilpMaI/VcxpVc4r31VzMUo6VQ&input=WwoiSGVsbG8gd29ybGQhIgoiSGVsbG8sIHdvcmxkISIKXS1tUg) ``` V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U :Implicit input of string U V :Second input variable, defaulting to 0 ° :Postfix increment g :Index, 0-based & modular, into "()[]"ò : Length 2 partitions of string "()[]" ) :End indexing i1 :Insert at 0-based index 1 ¢ : Slice first 2 characters off U ? : If truthy (non-empty string) return UÌ : Last character of U i : Prepend UÎ : First character of U + : Append ß : Recursive call with argument (V is passed automatically) Us1 : U sliced from index 1 to index J : -1 :U : Else return U ``` ]
[Question] [ Consider this ASCII version of a mechanism similar to a [bean machine](http://en.wikipedia.org/wiki/Bean_machine) or [plinko](http://priceisright.wikia.com/wiki/Plinko)/[pachinko](http://en.wikipedia.org/wiki/Pachinko) game: ``` O ^ \ ^ ^ ^ \ \ ^ / ^ U U U U U 1 2 3 4 5 ``` The `O` is a ball that falls down. * When it hits a `^`, there's a 50-50 chance it will go left or right. * When it hits a `/`, it always goes left. * When it hits a `\`, it always goes right. The ball eventually falls into one of the numbered `U` troughs at the bottom. The question is, what is the probability it will end up in each trough? For this particular case, the probabilities are `0.0`, `0.1875`, `0.5625`, `0.125`, and `0.125`, for troughs 1 through 5 respectively. Here's another example with 3 troughs instead of 5. The probabilities are `0.5`, `0.5`, and `0.0`: ``` O / ^ ^ U U U 1 2 3 ``` In this challenge we will generalize this problem to a mechanism with any number of layers set up in any fashion. # Challenge Write a program or function that takes in the ASCII representation of the pyramid structure of the mechanism. (Input via stdin/command line/function arg.) You may either assume it comes in with spaces that put it in the proper shape, e.g. ``` ^ \ ^ ^ ^ \ \ ^ / ^ ``` Or you may assume it comes in with no spaces at all, e.g. ``` ^ \^ ^^\ \^/^ ``` (If desired, you may assume there is a trailing newline and/or some consistent pattern of trailing spaces.) The input pyramid structure may have any number of levels (aka lines), including zero. Each level has one more `^`, `/`, or `\` than the last, and there are `levels + 1` troughs at the bottom (which aren't part of the input). You program/function must print/return the list of the probabilities that the ball lands in each of the troughs (in the order leftmost trough to rightmost trough). These should be floating point values that, when printed, have at least 3 decimal places (superfluous zeros or decimal points are not required; `1` is fine for `1.000`, `.5` is fine for `0.500`, etc.). If you wrote a function, you may print the values or return a list/array of the floats. Any reasonable printed list format is fine. e.g. `0.5 0.5 0.0`, `[0.5 0.5 0.0]`, `[0.5, 0.5, 0.0]`, `{0.5, 0.5, 0.0}`, or `0.5\n0.5\n0.0` would all be alright. # Examples **0 Levels:** (boils down to one trivial `U`) Input: `[no input/empty string given]` Output: `1.0` **1 Level:** Input: `^` Output: `0.5 0.5` Input: `/` Output: `1.0 0.0` Input: `\` Output: `0.0 1.0` **2 Levels:** (second example above) Input: ``` / ^ ^ ``` Output: `0.5 0.5 0.0` **3 Levels:** Input: ``` ^ ^ ^ ^ ^ ^ ``` Output: `0.125 0.375 0.375 0.125` Input: ``` \ / \ / / \ ``` Output: `0.0 0.0 0.0 1.0` **4 Levels:** (first example above) Input: ``` ^ \ ^ ^ ^ \ \ ^ / ^ ``` Output: `0.0 0.1875 0.5625 0.125 0.125` **7 Levels:** Input: ``` ^ / ^ ^ ^ / / \ / \ ^ ^ / ^ \ ^ \ ^ \ / ^ \ ^ ^ ^ \ ^ / ``` Output: `0.0 0.09375 0.28125 0.4375 0.1875 0.0 0.0 0.0` # Scoring The shortest answer in bytes wins. Tiebreaker is earlier post. [Answer] # Ruby 140 ``` ->s{r=[1.0] s.lines.map{|l|n=[i=0.0]*(r.size+1) l.scan(/\S/).map{|e|a,b=e>?/?e>?]?[0.5]*2:[0,1]:[1,0] z=r[i] n[i]+=z*a n[i+=1]+=z*b} r=n} r} ``` Function that takes as input the string (can be nicely formatted as a pyramid) and returns an array of floats. Test it online: <http://ideone.com/kmsZMe> Pretty straightforward implementation. Here it is ungolfed: ``` F = -> input { probabilities = [1.0] input.lines.each { |line| new_probabilities = [0.0] * (probabilities.size+1) elements = line.scan /\S/ elements.map.with_index{|el, i| deltas = el > '/' ? (el > ']' ? [0.5,0.5] : [0,1]) : [1,0] d1, d2 = deltas new_probabilities[i] += probabilities[i] * d1 new_probabilities[i + 1] += probabilities[i] * d2 } probabilities = new_probabilities } return probabilities } ``` [Answer] # Ruby, 140 ~~158~~ bytes ~~Don't keep upvoting this when [there's a better ruby version](https://codegolf.stackexchange.com/a/49645/26465).~~ Here are more tricks for you. Unnamed function with one argument. Must not contain any spaces. May or may not contain a trailing newline. ``` ->s{Z=(s.split' ')<<[] K=[] F=->i,j,f{k=Z[i][j] K[i]||=0 k==?^?2.times{|m|F[i+1,j+m,f/2]}:!k ?K[j]+=f :F[i+1,j+(k==?/?0:1),f]} F[0,0,1.0] K} ``` ~~Wastes 9 bytes on having to handle `0 levels` (empty string).~~ All test cases work out correctly, [see here at ideone](https://ideone.com/RFMCkN). [Answer] # Pyth, ~~43~~ ~~42~~ 41 bytes ``` umsdc+0sm@c[ZJhkJZKcJ2K)2x"\/"ekC,GH2.z]1 ``` This expects the input to be without spaces. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=umsdc%2B0sm%40c%5BZJhkJZKcJ2K)2x%22%5C%2F%22ekC%2CGH2.z%5D1&input=%5E%0A%2F%5E%0A%5E%5E%2F%0A%2F%5C%2F%5C%0A%5E%5E%2F%5E%5C%0A%5E%5C%5E%5C%2F%5E%0A%5C%5E%5E%5E%5C%5E%2F&debug=0) # Pyth, 40 bytes (questionable) ``` umsdc+0sm,K@[ZJhkcJ2)x"\/"ek-JKC,GH2.z]1 ``` Thanks to @isaacg, for saving one byte. Notice that this version didn't actually work in the version of Pyth, when the question was asked. There was a tiny bug in the compiler. Despite this code uses no new features of Pyth (only stuff that was in the Pyth docs for a long time and should have worked), this might not be a valid answer. Decide for yourself. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=umsdc%2B0sm%2CK%40%5BZJhkcJ2)x%22%5C%2F%22ek-JKC%2CGH2.z%5D1&input=%5E%0A%2F%5E%0A%5E%5E%2F%0A%2F%5C%2F%5C%0A%5E%5E%2F%5E%5C%0A%5E%5C%5E%5C%2F%5E%0A%5C%5E%5E%5E%5C%5E%2F&debug=0) ### Explanation: ``` umsdc+0sm,K@[ZJhkcJ2)x"\/"ek-JKC,GH2.z]1 u .z]1 reduce G, starting with G = [1], for H in all_input(): C,GH zip(G,H) m map each pair k to: [ZJhkcJ2) create a list [0, k[0], k[0]/2] x"\/"ek index of k[1] in "\/" (-1 for "^") K@ take the correspondent element of the list and store in K , -JK create a pair (K, k[0]-K) +0s sum and insert 0 at the begin c 2 chop into pairs msd sum up each pair G gets updated with this new list ``` For instance if I currently have the input probabilities `G = [0.5, 0.5, 0.0]` and the row `H = "^/^"` the following happens: * zip ... `[(0.5,"^"), (0.5,"/"), (0.0,"^")]` * create output probabilities ... `[[0.25,0.25], [0.5,0.0], [0.0, 0.0]]` * 0+sum ... `[0, 0.25, 0.25, 0.5, 0.0, 0.0, 0.0]` * chop ... `[0,0.25], [0.25,0.5], [0.0,0.0], [0.0]]` * sum ... `[0.25, 0.75, 0.0, 0.0]` [Answer] # CJam, ~~50 48 45 44 42~~ 40 bytes ``` 1]q{iD%"(+0 0+( (\Y/::+ (d2/_a+"S/=~+}/p ``` This expects the input to be without space and have a trailing newline. For example: ``` ^ \^ ^^\ \^/^ ``` > > [0 0.1875 0.5625 0.125 0.125] > > > **Algorithm** The basic idea is that you keep on parsing each character (there are only 4 different characters) and perform different operations on the probability distribution (initially an array containing 1 element of value 1). For each row of input characters (starting with the first character on first row), we maintain a probability array of that same size. Each character acts upon the first probability from the list and pushes the resultant pair to the end of the list. After each line, we sum up pairs from the list to get exact number of items as the items on the next line. Here are the four characters and the required actions corresponding to each: * `^` : When this character occurs, you split the current probability to two parts. For example, if we have this on the first line, we have to convert the `[1]` to `[0.5 0.5]` * `/` : When this characters occurs, we have to put `<current probability> 0` in place of the current probability in the array. * `\` : When this characters occurs, we have to put `0 <current probability>` in place of the current probability in the array. * `\n` : When this character occurs, we have a new line. Thus we group together all pairs from above 3 characters and sum them up to get probability of each item for the next line. For ex. `[0 0.5 0.25 0.25]` gets converted to `[0 0.75 0.25]`. Note that the first and last items have an implicit pair (valued 0) before and after them. Now we only have to identify the right character and perform the right action. Lets use the usual maths here to do that. The ASCII codes for `^`, `\`, `/` and `\n` are `94`, `92`, `47`, and `10`. After a few trials, we get this simple equation to convert these numbers into 0, 1, 2 and 3: ``` "^\/ ":ied13f%ed4f%ed ``` gives: ``` Stack: [[94 92 47 10]] Stack: [[3 1 8 10]] Stack: [[3 1 0 2]] 3102 ``` In an array of length 4, the last `4f%` would be implicit. So we simply do `%13` to the ASCII code of the character and choose the right action from an array of actions. **Code explanation**: ``` 1] e# Initial probability array with 1 probability q{ }/ e# Read the whole input and iterate char by char iD% e# mod the ASCII code of the character with 13 "(+0 0+( (\Y/::+ (d2/_a+"S/ e# This is our actions array in order of [\ / \n ^] =~ e# We pick the correct action and eval it + e# Evaling each action will leave one number out of the e# pairs out of the array. So we put it back in p e# Print the final probability array ``` [Try it online here](http://cjam.aditsu.net/#code=1%5Dq%7BiD%25%22(%2B0%200%2B(%20(%5CY%2F%3A%3A%2B%20(d2%2F_a%2B%22S%2F%3D~%2B%7D%2Fp&input=%5E%0A%5C%5E%0A%5E%5E%5C%0A%5C%5E%2F%5E%0A) [Answer] # C#, ~~274~~ 247 bytes Nothing fancy, complete program that reads lines (with or without spaces, it just strips them) in from STDIN, and prints space separated results to STDOUT. ``` using Q=System.Console;class P{static void Main(){decimal[]k={1},t;string L;for(int l=0,i;(L=Q.ReadLine())!=null;k=t)for(L=L.Replace(" ",""),t=new decimal[++l+1],i=0;i<l;)t[i]+=k[i]-(t[i+1]=(8-L[i]%8)/2*k[i++]/2);Q.WriteLine(string.Join(" ",k));}} ``` Tidier code with comments: ``` using Q=System.Console; class P { // / 47 // \ 92 // ^ 94 static void Main() { decimal[]k={1},t; // k is old array, t is new array string L; // L is the current line, R is the current result (1 if no rows) for(int l=0,i; // l is length of old array, i is index in old array (L=Q.ReadLine())!=null; // for each line of input k=t) // swap array over for(L=L.Replace(" ",""), // remove spaces t=new decimal[++l+1], // create a new array i=0; i<l;) // for each position t[i]+=k[i]-( // add to left position (for last time) t[i+1]=(8-L[i]%8)/2*k[i++]/2 // assign right position (k is decimal) ); Q.WriteLine(string.Join(" ",k)); // print result } } ``` [Answer] ## Python 3, 113 ``` P=[1] for C in input().split(): l,*Q=0, for p,c in zip(P,C):r=p*"\^/".find(c)/2;Q+=l+r,;l=p-r P=Q+[l] print(P) ``` Repeatedly updates the probability vector `P` in response to each line. This new probability vector `Q` is created one entry at a time. Iterates through the new slots, and computes the contribution from the peg to its right as `r`, while also computing the remaining contribution to the upcoming slot as `p-r`. Expects each line to end in at least one space to avoid an issue where lines end in a backslash. [Answer] # Python 3, 138 bytes ``` def f(s): r=[1];p=t=0 for e in s: if'!'<e:b=p==t*-~t/2;r+=[0]*b;t+=b;v=ord(e)%7+1;a=r[p]/2;r[-1]+=v//3*a;r+=v%3*a,;p+=1 return r[~t:] ``` Works with any whitespaces as they are all filtered out (by `if'!'<e`). Method: * We keep an ever expanding list `r` of the probabilities of reaching any obstacles and the implicit troughs below them. We start from the list `[1]`. * If we are at the first obstacle in a row we need to add an extra `0` to the list for the leading trough. We decide if it is the first obstacle by comparing its index `p` to the next triangular number `t*-~t/2`. * For every obstacle we add its list-value partially to the last element and partially to a new trailing element. We divide the list-value based on the obstacle character (`^:0.5 0.5; /:1 0; \:0 1`). We use the following method: + Take `v = ord(char) mod 7 + 1` yielding `^:4 /:6 \:2` + `v div 3 / 2` yields the first fraction (`^:0.5 /:1 \:0`) + `v mod 3 / 2` yields the second fraction (`^:0.5 /:0 \:1`) * The result is the last `t + 1` elements of the final list `r`. 2 bytes thanks to @Sp3000's chat advice. [Answer] # Perl, 78 ``` #!perl -p0a @r=($/=1);$^=.5;@r=map$r-$l+($l=$$_*($r=shift@r)),/./g,$r=$l=0for@F;$_="@r" ``` Takes input without spaces. Try [me](http://ideone.com/Vv36Dp). [Answer] # TI-BASIC, ~~73~~ 76 Takes input one line at a time, and ends when a space is entered on its own, because neither line breaks in strings nor empty strings are legal in TI-BASIC. ``` {1→X Input Str1 While Str1≠" //one space .5seq(inString("^/",sub(Str1,I,1)),I,1,dim(Ans augment(Ans∟X,{0})+augment({0},∟X-∟XAns→X Input Str1 End ∟X ``` I'm pretty sure I got the size right (TI-BASIC is tokenized, so each command takes either one or two bytes—seq() takes one, inString() takes two, dim() takes one, and so on. I counted the size manually.) Although the backslash character is valid in a string, note that there is no way to input one from inside the program unless you have modified your calculator. [Answer] ## Javascript - 117 Tried using recursion, but that was too long... Hat tip to [xnor](https://codegolf.stackexchange.com/a/49665/13950) for the subtraction idea, which shaved off a dozen or more characters. ``` w=s=>{a=[1];s.split('\n').map(m=>{for(b=[i=0];z=a[i],f=m[i];b[i++]+=z-b[i])b[i+1]=f>']'?z/2:f<':'?0:z;a=b}) return a} ``` Ungolfed: ``` // s must not have spaces w=s=>{ // a is the current probability array a=[1]; s.split('\n').map( // for each row of input... m=>{ b=[0]; // b is the next row's probability array for(i=0; i<m.length;){ z=a[i]; // z = probability f=m[i]; // f = letter // let's assume i == 0 b[i+1] = (f>']') ? z/2 : // if f == '^', b[1] = z/2 (f<':' ? 0 : // else if f == '/', b[1] = 0 z); // else b[1] = z b[i++]+=z-b[i]; // then add (z-b[1]) to b[0] } a=z-b // increment current probability array } ) return a; } ``` ]
[Question] [ Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as `"1 2 3 4"` or `[1, 2, 3, 4]`. The numbers in the input list represent the slices of a full [pie chart](https://en.wikipedia.org/wiki/Pie_chart) where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given. For example, the pie for `1 2 3 4` is: [![1 2 3 4 example](https://i.stack.imgur.com/mzzd1.png)](https://i.stack.imgur.com/mzzd1.png) The question your code must answer is: **Is the pie chart ever [bisected](https://en.wikipedia.org/wiki/Bisection)?** That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two? You need to **output a [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if there is at least one bisector and output a [falsy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value if there are none**. In the `1 2 3 4` example there is a bisection between `4 1` and `2 3` so the output would be truthy. But for input `1 2 3 4 5` there is no bisector so the output would be falsy: [![1 2 3 4 5 example](https://i.stack.imgur.com/p0IfP.png)](https://i.stack.imgur.com/p0IfP.png) # Additional Examples Arranging numbers differently may remove bisectors. e.g. `2 1 3 4` → falsy: [![2 1 3 4 example](https://i.stack.imgur.com/l2JBi.png)](https://i.stack.imgur.com/l2JBi.png) If only one number is in the input list the pie is not bisected. e.g. `10` → falsy: [![10 example](https://i.stack.imgur.com/0ruNz.png)](https://i.stack.imgur.com/0ruNz.png) There may be multiple bisectors. As long as there are more than zero the output is truthy. e.g. `6 6 12 12 12 11 1 12` → truthy: (there are 3 bisectors here) [![6 6 12 12 12 11 1 12 example](https://i.stack.imgur.com/14ggt.png)](https://i.stack.imgur.com/14ggt.png) Bisections may exist even if they are not visually obvious. e.g. `1000000 1000001` → falsy: [![1000000 1000001 example](https://i.stack.imgur.com/uNck3.png)](https://i.stack.imgur.com/uNck3.png) e.g. `1000000 1000001 1` → truthy: [![1000000 1000001 1 example](https://i.stack.imgur.com/H5Wpe.png)](https://i.stack.imgur.com/H5Wpe.png) (Thanks to [nces.ed.gov](https://nces.ed.gov/nceskids/graphing/classic/bar_pie_data.asp?ChartType=pie&b=15) for generating the pie charts.) # Test Cases ``` Truthy 1 2 3 4 6 6 12 12 12 11 1 12 1000000 1000001 1 1 2 3 1 1 42 42 1 17 9 13 2 7 3 3 1 2 10 20 10 Falsy 1 2 3 4 5 2 1 3 4 10 1000000 1000001 1 1 2 3 1 1 1 2 1 2 1 2 10 20 10 1 ``` # Scoring The shortest code in bytes wins. Tiebreaker is earlier answer. [Answer] # J, 18 bytes 5 bytes thanks to Dennis. ``` +/e.[:,/2*+/\-/+/\ ``` [@HelkaHomba](https://codegolf.stackexchange.com/questions/81235/has-my-pie-been-bisected/81244#comment199424_81238): Nope. ### Usage ``` >> f =: +/e.[:,/2*+/\-/+/\ >> f 6 6 12 12 12 11 1 12 << 4 >> f 10 20 10 1 << 0 ``` ### Ungolfed ``` black_magic =: +/\-/+/\ doubled_bm =: 2 * black_magic flatten =: ,/ sum =: +/ is_member_of =: e. f =: sum is_member_of monadic flatten doubled_bm ``` --- ## Previous 23-byte version: ``` [:+/[:+/+/=+:@-/~@(+/\) ``` ### Usage ``` >> f =: [:+/[:+/+/=+:@-/~@(+/\) >> f 6 6 12 12 12 11 1 12 << 4 >> f 10 20 10 1 << 0 ``` ### Ungolfed ``` black_magic =: -/~@(+/\) double =: +: equals =: = sum =: +/ monadic =: [: of =: @ f =: monadic sum monadic sum (sum equals double of black_magic) ``` --- ## Explanation The sum of all substrings is calculated by the black\_magic. The `+/\` calculate the partial sums. For example, `a b c d` becomes `a a+b a+b+c a+b+c+d`. The `-/~` then constructs a subtraction table based on the input, so `x y z` becomes: ``` x-x x-y x-z y-x y-y y-z z-x z-y z-z ``` When applied to `a a+b a+b+c a+b+c+d`, the result would be: ``` 0 -b -b-c -b-c-d b 0 -c -c-d b+c c 0 -d b+c+d c+d d 0 ``` This calculated the sums of all the substrings which does not contain `a`. This guarantees to be enough, since if one bisection contains `a`, the other bisection will not contain `a` and also will not wrap around. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḥ+\©_Sf® ``` Return a non-empty list (truthy) or an empty list (falsy). [Try it online!](http://jelly.tryitonline.net/#code=4bikK1zCqV9TZsKu&input=&args=WzEsIDIsIDMsIDRd) or [verify all test cases](http://jelly.tryitonline.net/#code=4bikK1zCqV9TZsKuCsOH4oKsRw&input=&args=W1sxLDIsMyw0XSwgWzYsNiwxMiwxMiwxMiwxMSwxLDEyXSwgWzEwMDAwMDAsMTAwMDAwMSwxXSwgWzEsMiwzXSwgWzEsMV0sIFs0Miw0Ml0sIFsxLDE3LDksMTMsMiw3LDNdLCBbMywxLDJdLCBbMTAsMjAsMTBdLCBbMSwyLDMsNCw1XSwgWzIsMSwzLDRdLCBbMTBdLCBbMTAwMDAwMCwxMDAwMDAxXSwgWzFdLCBbMSwyXSwgWzMsMSwxXSwgWzEsMiwxLDIsMSwyXSwgWzEwLDIwLDEwLDFdXQ). ### How it works ``` Ḥ+\©_Sf® Main link. Argument: A (list) Ḥ Double all integers in A. +\ Take the cumulative sum of 2A. © Copy; store the result in the register. _S Subtract the sum of A from each partial sum of 2A. f® Filter; intersect this list with the list in the register. ``` [Answer] # Julia, ~~34~~ ~~30~~ 29 bytes ``` !x=sum(x)∈cumsum!(x,2x).-x' ``` *Thanks to @GlenO for golfing off 1 byte!* [Try it online!](http://julia.tryitonline.net/#code=IXg9eHw-c3Vt4oiIKHQ9Mnh8PmN1bXN1bSkuLXQnCgpmb3IgeCBpbiAoCiAgICBbMSwyLDMsNF0sCiAgICBbNiw2LDEyLDEyLDEyLDExLDEsMTJdLAogICAgWzEwMDAwMDAsMTAwMDAwMSwxXSwKICAgIFsxLDIsM10sCiAgICBbMSwxXSwKICAgIFs0Miw0Ml0sCiAgICBbMSwxNyw5LDEzLDIsNywzXSwKICAgIFszLDEsMl0sCiAgICBbMTAsMjAsMTBdLAogICAgWzEsMiwzLDQsNV0sCiAgICBbMiwxLDMsNF0sCiAgICBbMTBdLAogICAgWzEwMDAwMDAsMTAwMDAwMV0sCiAgICBbMV0sCiAgICBbMSwyXSwKICAgIFszLDEsMV0sCiAgICBbMSwyLDEsMiwxLDJdLAogICAgWzEwLDIwLDEwLDFdCikKICAgIHByaW50bG4oIXgpCmVuZA&input=) ### How it works After storing the cumulative sum of **2x** in **x**, we subtract the row vector **x'** from the column vector **x**, yielding the matrix of all possible differences. Essentially, this computes the sums of all adjacent subarrays of **x** that do not contain the first value, their negatives, and **0**'s in the diagonal. Finally, we test if the sum of the original array **x** belongs to the generated matrix. If this is the case, the sum of at least one of the adjacent sublists is equal to exactly halve of the sum of the entire list, meaning that there is at least one bisector. [Answer] ## Haskell, 41 bytes ``` f l=elem(sum l/2)$scanr(:)[]l>>=scanl(+)0 ``` The idea is to check whether there is a sublist of `l` whose sum equals `sum l/2`. We generate the sums of these sublists as `scanr(:)[]l>>=scanl(+)0`. Let's look at how this works with `l=[1,2,3]` ``` >> scanr(:)[]l [[1,2,3],[2,3],[3],[]] -- the suffixes of l >> scanl(+)0 [2,3,4] [0,2,5,9] -- the cumulative sums of the input >> scanr(:)[]l>>=scanl(+)0 [0,1,3,6,0,2,5,0,3,0] -- the cumulative sums of the suffixes of l, flattened to a single list ``` **Old 43 bytes:** ``` f l|c<-scanl1(+)l=elem(sum l/2)$(-)<$>c<*>c ``` Generates the list `c` of cumulative sums. Then, checks if any two of these sums differ by `sum l/2` by checking if it is an element of the list of differences `(-)<$>c<*>c`. [Answer] ## Python 2, 64 bytes ``` f=lambda l,s=0:l>[]and(sum(l)==s)|f(l[1:],s+l[0])|f(l,s+l.pop()) ``` Recursively tries to remove elements from the front or end until the sum of what remains equals the sum of what was deleted, which is stored is `s`. Takes time exponential in the list length. Dennis saved 3 bytes with `pop`. [Answer] # Pyth, ~~10~~ 9 bytes ``` }sQmysd.: ``` Test it in the [Pyth Compiler](https://pyth.herokuapp.com/?code=%7DsQmysd.%3A&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%5D%0A%5B6%2C+6%2C+12%2C+12%2C+12%2C+11%2C+1%2C+12%5D%0A%5B1000000%2C+1000001%2C+1%5D%0A%5B1%2C+2%2C+3%5D%0A%5B1%2C+1%5D%0A%5B42%2C+42%5D%0A%5B1%2C+17%2C+9%2C+13%2C+2%2C+7%2C+3%5D%0A%5B3%2C+1%2C+2%5D%0A%5B10%2C+20%2C+10%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B2%2C+1%2C+3%2C+4%5D%0A%5B10%5D%0A%5B1000000%2C+1000001%5D%0A%5B1%5D%0A%5B1%2C+2%5D%0A%5B3%2C+1%2C+1%5D%0A%5B1%2C+2%2C+1%2C+2%2C+1%2C+2%5D%0A%5B10%2C+20%2C+10%2C+1%5D&debug=0). ### How it works ``` .: Generate the list of all adjacent sublists. m Map over the result: sd Add the integers of the sublist. y Double the sum. sQ Compute the sum of the input. } Check if it belongs to the list of doubled sublist sums. ``` [Answer] ## Actually, 21 bytes ``` ;Σ@2*;lR@τ╗`╜V♂Σi`Míu ``` [Try it online!](http://actually.tryitonline.net/#code=O86jQDIqO2xSQM-E4pWXYOKVnFbimYLOo2lgTcOtdQ&input=MSwyLDMsNA) This program prints out a `0` for false cases, and a positive integer for true cases. Explanation: ``` ;Σ@2*;lR@τ╗`╜V♂Σi`Míu ;Σ sum of copy of input @2* double values in other copy ;lR copy, range(1, len(input)+1) @τ append other copy to itself ╗ save in reg0 `╜V♂Σi`M map: generate cyclic cumulative sums íu 1-based index of sum of input (0 if not found) ``` ## Non-competing version, 10 bytes ``` ;Σ@2*σ;)-∩ ``` [Try it online!](http://actually.tryitonline.net/#code=O86jQDIqz4M7KS3iiKk&input=MSwyLDMsNA) This program outputs an empty list for false cases and a non-empty list otherwise. It is essentially a port of [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/81236/45941). It is non-competing because the cumulative sum and vectorized difference functionality post-date the challenge. Explanation: ``` ;Σ@2*σ;)-∩ ;Σ sum of copy of input @2* multiply values in other copy by 2 σ; two copies of cumulative sum )- subtract sum of input from each element in one copy ∩ set intersection with other copy ``` [Answer] # Python 2, ~~76~~ ~~74~~ ~~70~~ 66 bytes ``` def f(x):n=sum(x);print n in[2*sum(x[k/n:k%n])for k in range(n*n)] ``` *Thanks to @xnor for golfing off ~~4~~ 8 bytes!* Test it on [Ideone](http://ideone.com/2NYxLg). (larger test cases excluded) [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` k=t=1 for x in input():t<<=x;k|=t*t print k&k/t ``` [Try it online!](https://tio.run/##TY3dCoMwDIXvfYrixdjGgZnaKXP2SWRXw6F0qEhkDvbuLqsVRpLm5@tJhjc3faeXV9M@a0VFPdf3OI4XZ9lS9OhHNau2Ex8m3h8KLks7X93H8pGjYWw7Vm7nTrz8NBVBI4W5RVWGDKQ3J4hpGfsPPpO8RsOsU8pxAaVCc89TEXiSQCegZJPC4Cy1rAx3VrTioAsdQvxtEfQF "Python 2 – Try It Online") I'm back 2.75 years later to beat my [old solution](https://codegolf.stackexchange.com/a/81246/20260) by over 25% using a new method. This 1-byte longer version is a little clearer. ``` k=t=0 for x in input():t+=x;k|=4**t print k&k>>t ``` [Try it online!](https://tio.run/##TY3dDoIwDIXveYqFC6N4LtYxIWLGixCvDAYyMwiZERPfHesYiWm7/nw77fj23eDU8ur6Ryuoauf2lqbpYo03MrkPk5hF79jHp98fKn8088V@jM4yn4xT77ywO1vXfvmJGoJCDn1NmgIFSG1OYFM8Dh9CJn61gl6nVOIMypmWgecsCERCSZDcpNA4cc0r450VrTjqYocYf1sYfQE "Python 2 – Try It Online") The idea is to store the set of cumulative sums `t` as bits of `k`, setting bit `2*t` to indicate that `t` is a cumulative sum. Then, we check if any two cumulative sums differ by half the list sum (final `t`) by bit-shifting `k` this much and doing bitwise `&` with the original to see the result is nonzero (truthy). [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` EYst!-Gs=z ``` The output is the number of bisectors. [**Try it online!**](http://matl.tryitonline.net/#code=RVlzdCEtR3M9eg&input=WzEgMiAzIDRd) ### Explanation Same approach as [Dennis' Julia answer](https://codegolf.stackexchange.com/a/81238/36398). ``` E % Implicit input. Multiply by 2 element-wise Ys % Cumulative sum t!- % Compute all pairwise differences. Gives a 2D array Gs % Sum of input = % Test for equality, element-wise z % Number of nonzero elements. Implicit display ``` [Answer] # Ruby, ~~60~~ 53 bytes ``` ->a{a.any?{r=eval a*?+;a.rotate!.any?{|i|0==r-=2*i}}} ``` Generates all possible partitions by taking every rotation of the input array and then taking all slices of length 1..`n`, where `n` is the size of the input array. Then checks if there exists any partition with a sum half the total sum of the input array. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes ``` ¦Dt½-∩ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A6Dt%C2%BD-%E2%88%A9&inputs=%5B1%2C2%2C3%2C4%5D%2C%5B1%2C2%2C3%2C4%2C5%5D%2C%5B6%2C6%2C12%2C12%2C12%2C11%2C1%2C12%5D%2C%5B2%2C1%2C3%2C4%5D%2C%5B1000000%2C1000001%2C1%5D%2C%5B10%5D%2C%5B1%2C2%2C3%5D%2C%5B1000000%2C1000001%5D%2C%5B1%2C1%5D%2C%5B1%5D%2C%5B42%2C42%5D%2C%5B1%2C2%5D%2C%5B1%2C17%2C9%2C13%2C2%2C7%2C3%5D%2C%5B3%2C1%2C1%5D%2C%5B3%2C1%2C2%5D%2C%5B1%2C2%2C1%2C2%2C1%2C2%5D%2C%5B10%2C20%2C10%5D%2C%5B10%2C20%2C10%2C1%5D&header=%C6%9B&footer=%5B1%7C0%5D%3B) As in Jelly, a list is falsy iff it is empty. ``` ¦ Push the cumulative sums D three times. t Take the last one, ½ halve it, - subtract it from each of the cumulative sums, ∩ and take the intersection of the differences and the cumulative sums. ``` [Answer] ## JavaScript (ES6), 83 bytes ``` a=>a.map(_=>a.slice(--n).map(m=>s.push(t+=m),t=0),s=[],n=a.length)&&s.includes(t/2) ``` Generates all possible sums, then checks to see whether half of the last sum (which is the sum of the whole list) appears in the list. (Generating the sums in the slightly awkward order to arrange for the sum I need to be last saves 4 bytes.) [Answer] # Dyalog APL, 12 bytes ``` +/∊2×+\∘.-+\ ``` Test it with [TryAPL](http://tryapl.org/?a=f%20%u2190%20+/%u220A2%D7+%5C%u2218.-+%5C%20%u22C4%20f%A8%A8%28%28%u23734%29%282%203%201%201%201/6%2012%2011%201%2012%29%281e6%281e6+1%291%29%281%202%203%29%281%201%29%2842%2042%29%281%2017%209%2013%202%207%203%29%283%201%202%29%2810%2020%2010%29%29%20%28%28%u23735%29%282%201%203%204%29%28%2C10%29%281e6+0%201%29%28%2C1%29%28%u23732%29%283%201%201%29%286%u23741%202%29%2810%2020%2010%201%29%29&run). ### How it works ``` +/∊2×+\∘.-+\ Monadic function train. Right argument: y (vector) +\ +\ Yield the cumulative sum of y. ∘.- Compute all differences of all partial sums. This computes the sums of all adjacent subvectors of y that do not contain the first value, their negatives, and 0's in the diagonal. 2× Multiply all differences by 2. +/ Yield the sum of y. ∊ Test for membership. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÄḤf_¥S ``` [Try it online!](https://tio.run/##y0rNyan8//9wy8MdS9LiDy0N/n@4/VHTmsj//6MNdYx0jHVMYnVgLB1TINtMx0zH0AiGDHWA0AgoDGTDFBuAgQ6EBkqDxWCmYCoAy4BJIDYx0jExgqiFiJvrWOoYGgN1moP1GutA1IJoqDodKAabrGMEMheJCVQNAA "Jelly – Try It Online") Jelly has gained a single-byte builtin for cumulative sums since Dennis posted his solution, making it trivial to golf to 7 bytes. Turns out there's a lot of creative ways to tie 7, but to hit 6 all it takes is restructuring it with a dyadic chain. ``` Ḥ Double Ä the cumulative sums, f then filter them by membership in _¥ the differences between them and S the total sum. ``` As Dennis presumably observed, a difference of partial sums is the sum of a substring, and if a difference of partial sums is half the total sum, the difference of a partial sum and the total sum is another partial sum. [Answer] # Haskell, 68 bytes ``` f l|x<-[0..length l]=any(sum l==)[2*(sum$take a$drop b l)|a<-x,b<-x] ``` The function `f` first creates a list of the sums of all the possible slices of the given list. Then it compares to the total sum of list elements. If we get at some point half of the total sum, then we know that we've got a bisection. I'm also using the fact that if you `take` or `drop` more elements than there are in the list, Haskell does not throw an error. [Answer] # APL, 25 chars ~~Assuming the list is given in `X ← 1 2 3 4`.~~ ``` (+/X)∊∘.{2×+/⍺↑⍵↓X,X}⍨⍳⍴X←⎕ ``` ## Explanation: First note that APL evaluates form right to left. Then: * `X←⎕` takes the user input and stores it in `X` * `⍴X` gives the length of `X` * `⍳⍴X` the numbers from 1 to `⍴X` * The `⍺` and `⍵` in `{2×+/⍺↑⍵↓X,X}` are the left and right argument to a dyadic function we are defining inside the braces. + Now for the `⍺↑⍵↓X,X` part: `X,X` just concatenates X with itself; `↑` and `↓` are take and drop. + `+/` reduces/folds `+` over the list on its rightSo `2 {2×+/⍺↑⍵↓X,X} 1` = `2×+/2↑1↓X,X` = `2×+/2↑1↓1 2 3 4 1 2 3 4` = = `2×+/2↑2 3 4 1 2 3 4` = `2×+/2 3` = `2×5` = `10`. * `∘.brace⍨idx` is just `idx ∘.brace idx`. (`⍨` is the diagonal map; `∘.` is the outer product) So this gives us a `⍴X` by `⍴X` matrix which contains twice the sums of all connected sublists. ``` 4 6 8 2 10 14 10 6 18 16 14 12 20 20 20 20 ``` The last thing we have to do is to check if the sum of `X` is somewhere inside this matrix. * Which we do with `(+/X)∊matrix`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` sj+~+? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8L84S7tO2/7//@hoQx0jHWMdk1gdGEvHFMg20zHTMTSCIUMdIDQCCgPZMMUGYKADoYHSYDGYKZgKwDJgEohNjHRMjCBqIeLmOpY6hsZAneZgvcY6ELUgGqpOB4rBJusYgcxFYgJVxwIA "Brachylog – Try It Online") Outputs through success or failure, printing [`true.`](https://tio.run/##SypKTM6ozMlPN/r/vzhLu07b/v//aDMdMx1DIxgy1AFCo1gA) or [`false.`](https://tio.run/##SypKTM6ozMlPN/r/vzhLu07b/v//aCMdQx1jHZNYAA) if run as a program. ``` s A contiguous sublist of the input j with all of its items duplicated + sums to ~+ the sum of the elements of ? the input. ``` [Answer] # C, 161 145 129 bytes * saved few bytes thanks to @LeakyNun * saved few bytes thanks to @ceilingcat ``` i;j;k;t;r;s;f(x,n)int*x;{for(t=i=k=r=0;i<n;)t+=x[i++];for(;++k<n;i=n)for(;i--;r|=2*s==t)for(s=0,j=i;j<i+k;)s+=x[j++%n];return r;} ``` **Ungolfed** [try online](http://ideone.com/LlStyX) ``` int f(int*x,int n) { int t=0; for(int i=0;i<n;i++) { t += x[i]; } for(int k=1;k<n;k++) // subset-size { for(int i=0,s;i<n;i++) // where to start { s=0; for(int j=i;j<i+k;j++) // sum the subset { s+=x[j%n]; } if(2*s==t) return 1; // TRUE } } return 0; // FALSE } ``` [Answer] ## Mathematica, 48 bytes ``` !FreeQ[Outer[Plus,#,-#],Last@#/2]&@Accumulate@#& ``` Anonymous function, similar in action to the numerous other answers. `Outer[Plus, #, -#]`, when acting on `Accumulate@#` (which in turn acts on the input list, giving a list of successive totals) generates essentially the same table, as at the bottom of Leaky Nun's answer. `!FreeQ[..., Last@#/2]` checks if `(Last@#)/2` is *not* absent from the resulting table, and `Last@#` is the last of the successive totals, i.e. the sum of all elements of the input list. If this answer is somewhat interesting, it is not because of a new algorithm, but more about the tricks specific to Mathematica; e.g. `!FreeQ` is nice, compared to `MemberQ`, since it does not require a flattening of the table it checks *and* it saves a byte. [Answer] # APL(NARS), chars 95, bytes 190 ``` {1≥k←≢w←⍵:0⋄s←+/⍵⋄∨/{s=2×s-+/⍵}¨↑¨{⍵⊂w}¨{(k⍴2)⊤⍵}¨{1≥≢⍵:⍵⋄⍵,∇{(1+2×(↑⍵))×2*0..¯2+≢⍵}⍵}2*0..k-1} ``` Consider one array of input of 4 elements: 1 2 3 4. How we can choose the useful for this exercise partition of that set? Afther some think the partition of these 4 elements we can use are descrived in the binary number on the left: ``` 0001,0010,0100,1000 2^(0..4) 1 2 4 8 0011,0110,1100, 3 6 12 0111,1110, 7 14 1111 15 ``` (1001 or 1011 ecc could be in that set but already we have 0110 and 0100 ecc) so one hat just to write one function that from the number of element of the input array build these binary numbers... it would be: ``` c←{1≥≢⍵:⍵⋄⍵,∇{(1+2×(↑⍵))×2*0..¯2+≢⍵}⍵} ``` that from input 1 2 4 8 [2^0..lenBytesArgument-1] find 3 6 12, 7 14, 15; so find binary of these numbers and using them find the right partitions of the input array...I tested c function only for that input 4 elements, but seems it is ok for other number of elements... test: ``` f←{1≥k←≢w←⍵:0⋄s←+/⍵⋄∨/{s=2×s-+/⍵}¨↑¨{⍵⊂w}¨{(k⍴2)⊤⍵}¨{1≥≢⍵:⍵⋄⍵,∇{(1+2×(↑⍵))×2*0..¯2+≢⍵}⍵}2*0..k-1} f¨(1 2 3 4)(6 6 12 12 12 11 1 12)(1000000 1000001 1)(1 2 3)(1 1)(42 42) 1 1 1 1 1 1 f¨(1 2 3 4 5)(2 1 3 4)(,10)(1000000 1000001)(,1)(1 2)(3 1 1) 0 0 0 0 0 0 0 ``` ]
[Question] [ With the recent discussion about [the use of compression tools in code golf](https://codegolf.meta.stackexchange.com/q/447/3191), I thought it would be a nice challenge to write your own text compressor and decompressor. ### Challenge: Write **two programs**: one to compress ASCII text into a sequence of bytes, and another to decompress it. The programs need not be in the same language. The first program should read a piece of ASCII text (from a file or from standard input, or using whatever mechanism is most natural to the language) and output a compressed version of it. (The compressed output may consist or arbitrary bytes; it need not be readable.) The second program should read the output of the first and recreate the original input text. ### Scoring: The score of a solution will be the **sum** of the following three counts: 1. The **length of the compressor** program in characters. 2. The **length of the output** of the compressor, given the test input below, in bytes. 3. The **length of the decompressor** program (if different from the compressor) in characters. You should note all three counts and their sum in your answer. Since this is code golf, the lower the score, the better. ### Rules and restrictions: * You **may not use** any pre-existing compression or decompression tools or libraries, even if they come bundled with your chosen language. If in doubt about whether a given tool or function is allowed, please ask. * Your compressor program must be capable of handling input consisting of **any printable ASCII text**, including tabs (ASCII 9) and line feeds (ASCII 10). You may, but are not required to, handle arbitrary Unicode and/or binary input. * Your decompressor program must produce **exactly the same output** as was given to the compressor as input. In particular, take care not to output a trailing line feed if the input did not have one. (The test input below does have a trailing line feed, so you'll need to test for this separately. Tip for GolfScript: `'':n`.) * Your compressor and decompressor **may be the same program** (with the appropriate mode selected e.g. with a command line switch). In that case, **its length is only counted once**. * The programs should not be **exceedingly slow or memory-hungry**. If either compressing or decompressing the test input takes more than a minute on my not-so-new desktop (2.2GHz AMD Athlon64 X2) or consumes more than a gigabyte of RAM, I'm going to rule the solution invalid. These limits are deliberately lax — please try not to push them. *(See amendment below: you need to be able to handle at least 100 kB of input within these limits.)* * Even though only the test input matters for scoring, you should **at least make an effort** at compressing arbitrary input text. A solution that achieves a decent compression ratio *only* for the test input, and for nothing else, is technically valid but isn't going to get an upvote from me. * Your compressor and decompressor programs **should be self-contained**. In particular, if they depend on being able to read some file or network resource that is not part of your chosen language's standard runtime environment, the length of that file or resource should be counted as part of the length of the program(s). (This is to disallow "compressors" that compare the input to a file on the web and output zero bytes if they match. Sorry, but that's not a new trick anymore.) ### Amendments and clarifications: * Your compressor must be able to handle files consisting of **at least 100 kB** of typical English text within reasonable time and memory usage (at most one minute and one GB of memory). Your decompressor must be able to decompress the resulting output within the same limits. Of course, being able to handle files longer than that is perfectly fine and commendable. It's OK to split long input files into chunks and compress them individually, or to use other means to trade off compression efficiency for speed for long inputs. * Your compressor *may* require its input to be given using your preferred platform's **native newline representation** (LF, CR+LF, CR, etc.), as long as your decompressor uses the same newline representation in its output. Of course, it's also fine for the compressor to accept any kind of newlines (or even only Unix newlines regardless of platform), as long as your decompressor then outputs the same kind of newlines as in the original input. ### Test input: To judge the compression efficiency of the answers, the following test input (*The Raven* by Edgar Allan Poe, [courtesy of Project Gutenberg](http://www.gutenberg.org/ebooks/17192)) will be used: ``` Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore, While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. "'T is some visiter," I muttered, "tapping at my chamber door-- Only this, and nothing more." Ah, distinctly I remember it was in the bleak December, And each separate dying ember wrought its ghost upon the floor. Eagerly I wished the morrow:--vainly I had sought to borrow From my books surcease of sorrow--sorrow for the lost Lenore-- For the rare and radiant maiden whom the angels name Lenore-- Nameless here for evermore. And the silken sad uncertain rustling of each purple curtain Thrilled me--filled me with fantastic terrors never felt before; So that now, to still the beating of my heart, I stood repeating "'T is some visiter entreating entrance at my chamber door Some late visiter entreating entrance at my chamber door;-- This it is, and nothing more." Presently my soul grew stronger; hesitating then no longer, "Sir," said I, "or Madam, truly your forgiveness I implore; But the fact is I was napping, and so gently you came rapping, And so faintly you came tapping, tapping at my chamber door, That I scarce was sure I heard you"--here I opened wide the door;-- Darkness there, and nothing more. Deep into that darkness peering, long I stood there wondering, fearing, Doubting, dreaming dreams no mortal ever dared to dream before; But the silence was unbroken, and the darkness gave no token, And the only word there spoken was the whispered word, "Lenore!" This I whispered, and an echo murmured back the word, "Lenore!" Merely this and nothing more. Back into the chamber turning, all my soul within me burning, Soon again I heard a tapping, somewhat louder than before. "Surely," said I, "surely that is something at my window lattice; Let me see, then, what thereat is, and this mystery explore-- Let my heart be still a moment and this mystery explore;-- 'T is the wind and nothing more!" Open here I flung the shutter, when, with many a flirt and flutter, In there stepped a stately Raven of the saintly days of yore. Not the least obeisance made he; not a minute stopped or stayed he; But, with mien of lord or lady, perched above my chamber door-- Perched upon a bust of Pallas just above my chamber door-- Perched, and sat, and nothing more. Then this ebony bird beguiling my sad fancy into smiling, By the grave and stern decorum of the countenance it wore, "Though thy crest be shorn and shaven, thou," I said, "art sure no craven, Ghastly grim and ancient Raven wandering from the Nightly shore,-- Tell me what thy lordly name is on the Night's Plutonian shore!" Quoth the Raven, "Nevermore." Much I marvelled this ungainly fowl to hear discourse so plainly, Though its answer little meaning--little relevancy bore; For we cannot help agreeing that no living human being Ever yet was blessed with seeing bird above his chamber door-- Bird or beast upon the sculptured bust above his chamber door, With such name as "Nevermore." But the Raven, sitting lonely on the placid bust, spoke only That one word, as if his soul in that one word he did outpour. Nothing further then he uttered--not a feather then he fluttered-- Till I scarcely more than muttered, "Other friends have flown before-- On the morrow _he_ will leave me, as my hopes have flown before." Then the bird said, "Nevermore." Startled at the stillness broken by reply so aptly spoken, "Doubtless," said I, "what it utters is its only stock and store, Caught from some unhappy master whom unmerciful Disaster Followed fast and followed faster till his songs one burden bore-- Till the dirges of his Hope that melancholy burden bore Of 'Never--nevermore.'" But the Raven still beguiling all my sad soul into smiling, Straight I wheeled a cushioned seat in front of bird and bust and door; Then, upon the velvet sinking, I betook myself to linking Fancy unto fancy, thinking what this ominous bird of yore-- What this grim, ungainly, ghastly, gaunt and ominous bird of yore Meant in croaking "Nevermore." This I sat engaged in guessing, but no syllable expressing To the fowl whose fiery eyes now burned into my bosom's core; This and more I sat divining, with my head at ease reclining On the cushion's velvet lining that the lamplight gloated o'er, But whose velvet violet lining with the lamplight gloating o'er _She_ shall press, ah, nevermore! Then, methought, the air grew denser, perfumed from an unseen censer Swung by seraphim whose foot-falls tinkled on the tufted floor. "Wretch," I cried, "thy God hath lent thee--by these angels he hath sent thee Respite--respite and nepenthe from thy memories of Lenore! Quaff, oh quaff this kind nepenthe, and forget this lost Lenore!" Quoth the Raven, "Nevermore." "Prophet!" said I, "thing of evil!--prophet still, if bird or devil!-- Whether Tempter sent, or whether tempest tossed thee here ashore, Desolate yet all undaunted, on this desert land enchanted-- On this home by Horror haunted--tell me truly, I implore-- Is there--_is_ there balm in Gilead?--tell me--tell me, I implore!" Quoth the Raven, "Nevermore." "Prophet!" said I, "thing of evil--prophet still, if bird or devil! By that Heaven that bends above, us--by that God we both adore-- Tell this soul with sorrow laden if, within the distant Aidenn, It shall clasp a sainted maiden whom the angels name Lenore-- Clasp a rare and radiant maiden whom the angels name Lenore." Quoth the Raven, "Nevermore." "Be that word our sign of parting, bird or fiend!" I shrieked, upstarting-- "Get thee back into the tempest and the Night's Plutonian shore! Leave no black plume as a token of that lie thy soul hath spoken! Leave my loneliness unbroken!--quit the bust above my door! Take thy beak from out my heart, and take thy form from off my door!" Quoth the Raven, "Nevermore." And the Raven, never flitting, still is sitting, still is sitting On the pallid bust of Pallas just above my chamber door; And his eyes have all the seeming of a demon's that is dreaming, And the lamplight o'er him streaming throws his shadow on the floor; And my soul from out that shadow that lies floating on the floor Shall be lifted--nevermore! ``` The correct test input (encoded with Unix-style LF newlines) should be 7043 bytes long, and have the hexadecimal MD5 hash `286206abbb7eca7b1ab69ea4b81da227`. (`md5sum -t` should produce the same hash value even if you use CR+LF newlines on DOS/Windows.) The output of your decompressor should have the same length and hash. Ps. Keep in mind that this challenge is only as hard as you make it. Really, anything under 7043 counts as a good score. (At the other end of the scale, I'll be *extremely* impressed if anyone achieves a score under 2500.) [Answer] ## Python, 3514 = 294 + 2894 + 326 Basically a [bzip2](http://en.wikipedia.org/wiki/Bzip2) implementation. It does a [Burrows-Wheeler transform](http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform), a [move-to-front transform](http://en.wikipedia.org/wiki/Move-to-front_transform), a simple [Huffman encoding](http://en.wikipedia.org/wiki/Huffman_coding) into a bit stream, converts that bit stream to an integer and writes out bytes. Encoder: ``` import sys S=range(128) H={0:'0'} for b in range(7): for i in range(1<<b,2<<b):H[i]='1'*b+'10'+bin(i)[3:] I=sys.stdin.read()+'\0' N='1' for x in sorted(I[i:]+I[:i]for i in range(len(I))):i=S.index(ord(x[-1]));N+=H[i];S=[S[i]]+S[:i]+S[i+1:] N=int(N,2) while N:sys.stdout.write(chr(N%256));N>>=8 ``` `S` is the move-to-front queue, `H` is the Huffman encoder, and `N` is the bitstream. The encoding reduces the test input to about 41% of its original size. Decoder: ``` import sys N=0 b=1 for c in sys.stdin.read():N+=ord(c)*b;b<<=8 N=bin(N)[3:] S=range(128) L='' while N: n=N.find('0') if n:i=2**n/2+int('0'+N[n+1:2*n],2);N=N[2*n:] else:i=0;N=N[1:] L+=chr(S[i]);S=[S[i]]+S[:i]+S[i+1:] S='' i=L.find('\0') for j in L:S=L[i]+S;i=L[:i].count(L[i])+sum(c<L[i]for c in L) sys.stdout.write(S[:-1]) ``` [Answer] ## Perl, 3502 = 133 + 3269 + 100 The encoder: ``` #!/usr/bin/perl -0 $_=<>;for$e(map{~chr}0..255){++$p{$_}for/..|.\G./gs; %p=$s=(sort{$p{$a}<=>$p{$b}}keys%p)[-1];$d.=/\Q$e/?$/:s/\Q$s/$e/g&&$s}print$_,$d ``` And the decoder: ``` #!/usr/bin/perl -0777 sub d{($p=$d{$_})?d(@$p):print for@_} sub r{%d=map{chr,ord($c=pop)&&[pop,$c]}0..255;&d}r<>=~/./gs ``` For purists who prefer to avoid using command-line switches: You can remove the shebang line and add `$/=chr;` to the encoder and `$/=$,;` to the decoder to get the same effect. (This would bring the score up to 3510.) This code uses a very primitive compression scheme: * Find the two-char bigram that appears most frequently in the source text. * Replace the bigram with a currently-unused byte value. * Repeat until there are no more repeated bigrams (or no more unused byte values). Someone out there may recognize this as a simplified version of "re-pair" compression (short for recursive pairs). It's not a very good general compression scheme. It only does well with things like ASCII text, where there are a lot of unused byte values, and even then it typically gets no more than a 45-50% ratio. However, it has the advantage of being implementable with a minimum of code. The decompressor in particular can be *quite* compact. (Most of the chars in my decoder script are for retrieving the bigram dictionary.) Here's an ungolfed version of the code: ``` #!/usr/bin/perl use strict; use warnings; # Run with -d to decode. if ($ARGV[0] eq "-d") { shift; $_ = join "", <>; my @in = split //; my %dict; foreach my $n (0 .. 255) { my $c = shift @in; $dict{chr $n} = [ $c, shift @in ] if ord $c; } sub decode { foreach (@_) { if ($dict{$_}) { decode(@{$dict{$_}}); } else { print $_; } } } decode @in; } else { $_ = join "", <>; my @dict; for (my $n = 255 ; $n >= 0 ; --$n) { my $symbol = chr $n; if (!/\Q$symbol/) { my %pop; ++$pop{$_} for /../gs, /(?!^)../gs; my $str = (sort { $pop{$b} <=> $pop{$a} } keys %pop)[0]; s/\Q$str/$symbol/g; $dict[$n] = $str; } } for (0..255) { $dict[$_] ||= "\0" } print @dict, $_; } ``` One expression in the golfed encoder requires explanation, I think, and that is `(sort{$p{$a}<=>$p{$b}}keys%p)[-1]`, to get the key with the highest value. That looks like it should be written as `(sort{$p{$b}<=>$p{$a}}keys%p)[0]`, which does the same thing and is one character shorter. The reason I didn't write it that way is that it alters the selected key in the case when there are multiple keys with the highest value. By sheer chance, this caused the resulting output for the test input to be 10 bytes longer. I hated to take on the useless extra character, but not enough to sacrifice 9 points from my score. **In your face, Golfscript!** (Haha, Golfscript would totally come over here and kick my ass if it could hear me.) [Answer] **8086 Assembler / MS\_DOS** Compressor: 155 ``` jNiAxBCO2I7AM/+9/QW5AAGK2TPAq4rDqv7D4va6AQkz9lK0BrL/zSFadDK7 /f+DwwM733QNOTd19ThHAnXwid7r34k1iEUC6BMAtACKRQJr8AODxwPryrQC zSHrxFIz0ovGuwMA9/Nai9iKztPL0ePQ0nMWgPr+cgtSsv60Bs0hWoDq/rQG zSGyAf7JdeA5/XUHA+2DxQP+xsM= ``` Data: 3506 Decompressor: 203 ``` ieWD7CCM2IDEEI7YjsAz/7kAAYrZM8CrisOq/sPi9rYJxkb0Abn9BehtAIl2 /uhTAOhkAIl28Dv3cy3oRgCLRv6JBYt28Il2/oM8AHQEizTr94pEAohFAoPH AznPddL+xgPJg8ED68mLdv6JNYM8AHQEizTr94pEAohFAol+/on+aFgBgzwA dAdWizTo9f9etAaKVALNIcMz9ojz/k70dRu0BrL/zSF0IDz+cgi0BrL/zSEE /sZG9AiIRvLQZvLR1v7Ldddr9gPDzSA= ``` Total: 3864 Use [this Base64 decoder](http://www.opinionatedgeek.com/DotNet/Tools/Base64Decode/Default.aspx) and save the binary files as 'compress.com' and 'decompress.com' and then do: ``` compress < source > compressed_file decompress < compressed_file > copy_of_source ``` in a DOS shell (tested with WinXP). There's no error checking so compressing big files will create incorrect results. A few small additions and it could cope with any sized file. Also, it can't decompress to binary as it can't output a 0xff value (the compressed data escapes the 0xff value as 0xfe 0xff with 0xfe escaped as 0xfe 0xfe). Using command line filenames would overcome the binary output problem, but would be a bigger executable. [Answer] # Bash Poem (566+117) + 4687 = 5370 For fun I have disguised a compressor as a poem: ``` for I in my chamber nodded, nearly napping, suddenly heard rapping, tapping upon my door \ "'T is some visiter" \ I\ muttered, o\'er lamplight "nothing more" \ just this sainted maiden whom the angels name Lenore \ And "Prophet!" said me "thing of evil" -- "prophet still, if bird or devil!" \ Leave no token of that lie thy soul hath spoken and sitting take thy ore from This floor \ But you velvet bird from some shore above \ here this with sad raven before his word still spoke nothing \ " " Quoth the Raven Never more; do C=$[C+1];E=`perl -e "print chr($C+128)"`;echo "s/$I/$E/g">>c;echo "s/$E/$I/g">>d;done;LANG=C sed -f $1;rm c d ``` This is a unified compressor: run with the option "c" it will compress, and with "d" it will decompress. It has two parts: a 566 byte "readers digest" version of the poem and (2) a 117 byte suffix where all the "real" bash is done. With some care (e.g. starting the poem with "for I in") bash will interpret the "lossy" version of poem as an array. It replaces each element of the array with a non-ASCII character (we assume the input is ASCII so there are no collisions). One minor advantage of this solution: since we make use of the fact that we can assume the input is ASCII, the output of this compression will never be longer than its input, regardless of what the input and/or lossy part is. The rule that this comes closest to violating is the rule about providing a decent compression ratio on other texts. However, It shaves 1386 bytes off the GPL V2 text, well over it's own size, which seems to match the OPs definition of `decent`. Thus it seems to provide so-called `decent` compression on general texts. This is because pretty much any English text will have "the" "that" etc. Clearly it will work better if you replace the "lossy" part with text resembling the original you want to losslessly compress. Splitting pictures and [audio into lossy and non-lossy parts](http://en.wikipedia.org/wiki/DTS-HD_Master_Audio#Combined_lossless.2Flossy_compression) is a known technique. This doesn't work as well for text: 4687 bytes isn't that great even if we exclude the 566 bytes from the lossy version and we can't really automatically generate a lossy version of text the same we can for audio. On the plus side this means every time you compress something with this compressor, you can have the fun of creating a lossy version by hand. So this seems like a reasonable "for fun" solution. [Answer] # C++, 4134 bytes (code = 1357, compressed = 2777) This does a Burrows-Wheeler transform + a Move-To-Front like Keith Randall's, but then compresses the resulting byte sequence using an adaptive [Range Coder](https://en.wikipedia.org/wiki/Range_encoder). Unfortunately, the improved compression from the range coder isn't enough to offset C++'s verbosity. I could golf this code some more, namely use a different input/output method, but it wouldn't be enough to beat the other submissions with the current algorithm. The code is Windows specific, and only ascii text is supported. To compress: "C text\_file compressed\_file" To decompress: "D compressed\_file uncompressed\_file" Pretty much any command line error or file error will crash the program, and it takes the better part of a minute to encode or decode the poem. ``` #include <windows.h> #include <algorithm> typedef DWORD I;typedef BYTE u; #define W while #define A(x)for(a=0;a<x;a++) #define P(x)*o++=x; I q,T=1<<31,B=T>>8,a,l,f[257],b,G=127,p=G,N=255;I Y(u*i,u*j){return memcmp(i,j,l)<0;}I E(u*i,u*o){b=0;I L=0,h=0,R=T;u*c=o,*e=i+l;W(i<e){I r=R/p,s=0;A(*i)s+=f[a];s*=r;L+=s;R=*i<N?r*f[*i++]++:R-s;p++;W(R<=B){if((L>>23)<N){for(;h;h--)P(N)P(L>>23)}else{if(L&T){o[-1]++;for(;h;h--)P(0)P(L>>23)}else h++;}R<<=8;L<<=8;L&=T-1;}}P(L>>23)P(L>>15)P(L>>7)return o-c;}void D(u*i,u*o){I R=128,L=*i>>1;u*e=o+l;W(o<e){W(R<=B){L<<=8;L|=((*i<<7)|(i++[1]>>1))&N;R<<=8;}I h=R/p,m=L/h,x=0,v=0;W(v<=m)v+=f[x++];P(--x);L-=h*(v-f[x]);R=h*f[x]++;p++;}}void main(I Z,char**v){u d[1<<16];I c=*v[1]<68,s;HANDLE F=CreateFileA(v[2],T,0,0,3,0,0),o=CreateFileA(v[3],T/2,0,0,2,0,0);ReadFile(F,d,GetFileSize(F,0),&l,0);l=c?l:*(I*)d;A(G)f[a]=1;u M[256];A(G)M[a]=a+1;u*g=new u[l*3],*h=g+l;if(c){memcpy(d+l,d,l);u**R=new u*[l];A(l)R[a]=d+a;std::sort(R,R+l,Y);A(l){b=R[a][l-1];I i=strchr((char*)M,b)-(char*)M;memmove(M+1,M,i);*M=g[a]=b;h[a]=i;}s=E(h,d+l+8);}else{D(d+8,g);A(l){I k=g[a];g[a]=M[k];memmove(M+1,M,k);*M=g[a];}}u**j=new u*[l];A(l)j[a]=new u[l*2],memset(j[a],0,l*2),j[a]+=l;A(l){for(b=0;b<l;)*--j[b]=g[b++];std::sort(j,j+l,Y);}if(c){A(l){if(!memcmp(j[a],d,l)){I*t=(I*)(d+l);*t=l;t[1]=a;g=d+l,l=s+8;}}}else g=j[*(I*)(d+4)];WriteFile(o,g,l,&q,0);} ``` [Answer] ## JavaScript, 393 (code) + 3521 (test) = 3914 (total) This program iteratively substitutes unused byte values for 2- to 4- character chunks of the input. Each substitution is scored based on the original chunk's frequency and length, and the best substitution is chosen each time around. I would add a final Huffman coding stage if I could figure out how to do it in a relatively small number of characters. Decompression is essentially a series of find-and-replace operations. ### Usage C() provides compression; U() provides decompression. As JavaScript's strings are based on 16-bit Unicode code units, only the least significant 8 bits of each code unit are used in the compressed data format; this is compatible with Firefox's btoa() and atob() functions for Base64 encoding. ([usage example](http://jsfiddle.net/GqFbN/14/)) This program may only work in Firefox because of a non-standard "g" option to .replace(). ### Code Golfed code: ``` S=String.fromCharCode;function C(c){h=[];for(f=0;129>f;++f){g='';i=0;for(e=2;5>e;++e){d={};for(a=0;a<=c.length-e;a+=e)b="K"+c.substr(a,e),d[b]=d[b]?d[b]+1:1;for(b in d)a=d[b],a=a*e-(1+e+a),a>i&&(g=b.slice(1),i=a)}if(!g)break;h[f]=g;c=c.replace(g,S(127+f),"g")}return h.join("\1")+"\1"+c}function U(a){c=a.split("\1");a=c.pop();for(b=c.length,d=127+b;b--;)a=a.replace(S(--d),c[b],"g");return a} ``` Before golfing: ``` function compress(str) { var hash, offset, match, iteration, expansions, bestMatch, bestScore, times, length, score; expansions = []; for (iteration = 0; iteration < 129; ++iteration) { bestMatch = null; bestScore = 0; for (length = 2; length < 5; ++length) { hash = {}; for (offset = 0; offset <= str.length - length; offset += length) { match = 'K' + str.substr(offset, length); hash[match] = hash[match] ? hash[match] + 1 : 1; } for (match in hash) { times = hash[match]; score = times * length - (1 + length + times); if (score > bestScore) { bestMatch = match.slice(1); bestScore = score; } } } if (!bestMatch) { break; } expansions[iteration] = bestMatch; str = str.replace(bestMatch, String.fromCharCode(127 + iteration), 'g'); } return expansions.join('\u0001') + '\u0001' + str; } function uncompress(str) { var i, j, expansions; expansions = str.split('\u0001'); str = expansions.pop(); for (j = expansions.length, i = 127 + j; j--;) { str = str.replace(String.fromCharCode(--i), expansions[j], 'g'); } return str; } ``` [Answer] ## PHP, (347 + 6166 + 176) = 6689 So I went with a simplistic dictionary + substitution approach. If a word appears multiple times and it's shorter to (encode the word + save the substitution entry) then it makes the replacement. If the "word" happens to be a number, it does it anyways to prevent accidental substitutions during decompression. The "dictionary" of substitutions is joined by null bytes, followed by two null bytes, followed by the body the substitution works on. **Possible improvements:** * Windows doesn't like piping more than 4kb of data around, so find a better way than using files. * The ability to match long strings of whitespace and count them as "words" without adding too much code. * Coming up with something better substitutions instead of using numbers. **Usage:** the compressor looks for a file called "i" and writes the compressed data to "o". The decompressor looks for "o" and writes the uncompressed data to "d". This is my shoddy workaround to Windows not liking to pipe boats of data around. --- **compress.php (347)** ``` <?$d=file_get_contents('i');$z=chr(0);preg_match_all('|\b(\w+)\b|',$d,$m);$n=0;foreach($m[0]as$w){$l=strlen($w);$q[$w]=isset($q[$w])?$q[$w]+$l:$l;}arsort($q);foreach($q as$w=>$s){$l=strlen($w);$c=$s/$l;if($c*strlen($n)+$l<$s||is_int($w)){$d=preg_replace('|\b'.preg_quote($w).'\b|',$n++,$d);$f[]=$w;}}file_put_contents('o',implode($z,$f).$z.$z.$d); ``` [Expanded version](http://ideone.com/CUYUT) with comments and explanation. --- [Output sample](http://pastebin.com/PMca7pdE) without dictionary. Kinda funny to look at. Normal size: **6166**. ``` Ah, distinctly I remember it 45 in 0 bleak December, 25 each separate dying ember wrought its ghost 39 0 37. Eagerly I wished 0 88:--vainly I had sought to borrow From 9 books surcease of 43--43 for 0 lost 8-- For 0 rare 1 67 40 54 0 26 38 8-- Nameless 63 for evermore. 25 0 silken sad uncertain rustling of each purple curtain Thrilled me--filled me 19 fantastic terrors never felt 17; So 4 now, to 13 0 beating of 9 64, I stood repeating "'T is 57 31 36 49 at 9 2 5 Some late 31 36 49 at 9 2 5;-- 58 it is, 1 10 16." ``` --- **decompress.php (176)** ``` <?$z=chr(0);$d=file_get_contents('o');list($w,$d)=explode($z.$z,$d);$w=explode($z,$w);$n=0;foreach($w as$r){$d=preg_replace('|\b'.$n++.'\b|',$r,$d);};file_put_contents('d',$d); ``` [Expanded version](http://ideone.com/SwDSk) with explanation. --- Any suggestions for improvement welcome. **Edit:** Added the "unrolled" versions of the code and added tons of comments. Should be easy to follow. [Answer] ## GolfScript, 3647 (compressed size 3408 + code size 239) ``` 128,{[.;]''+}%:d;8:k;{2k?={1k+:k;}*}:|;{2base}:b;{.[0]*@b+0@->}:$;.0= {'':&,:i;1/{.d&@+?.0<{;d,i@d&@:&.0=:i;[+]+:d;k$\|}{:i;&\+:&;}if}%[0]k*+[]*8/{b}%"\0"\+} {1>{8$}/][]*:^;{^k<b^k>:^;}:r~{.}{d,|d=:&r..d,<{d=}{;&}if[1<&\+]d\+:d;}while;}if ``` The algorithm used is LZW compression with variable-width codes. The first line is shared code, the second is the compression code and the third is the decompression code. It handles files with ASCII characters in the range 1-127, and it recognizes compressed files automatically (they start with a 0 byte), so there are no parameters required to decompress. **Example run:** ``` $ md5sum raven.txt 286206abbb7eca7b1ab69ea4b81da227 raven.txt $ ruby golfscript.rb compress.gs < raven.txt > raven.lzw $ ls -l raven.lzw -rw-r--r-- 1 ahammar ahammar 3408 2012-01-27 22:27 raven.lzw $ ruby golfscript.rb compress.gs < raven.lzw | md5sum 286206abbb7eca7b1ab69ea4b81da227 - ``` **Note:** I started on this long before the requirement to handle 100kb was added, so I haven't tested it on input of that size. However, it takes about 30 seconds to compress the test input and 5 seconds to decompress it, using about 20MB of memory at its peak. [Answer] # Haskell, 3973 Late to the party, and not going to win, but I had fun writing it so I might as well post it. It's a straightforward variable-width implementation of LZW, with a dictionary explicitely limited to printable ASCII, tab and linefeed. Run with no arguments, it compresses standard input to file `C`. Run with any argument (but "--decompress" would be a reasonable bet), it decompresses file `C` to standard output. ``` import List import System import Data.Binary q=head main=getArgs>>=m m[]=getContents>>=encodeFile"C".s 97 128 1 0.e 97h m _=decodeFile"C">>=putStr.d tail""96h.u 97 128 h=zip[0..].map(:[])$"\t\n"++[' '..'~'] e _ _[]=[] e n s y=c:e(n+1)((n,take(1+l)y):s)(drop(l)y)where{Just(c,p)=find((`isPrefixOf`y).snd)s;l=length p} d _ _ _ _[]="" d f p n s(x:y)=t++d id t(n+1)(f$(n,p++[q t]):s)y where t=maybe(p++[q p])id$lookup x s s _ _ _ a[]=a::Integer s n w o a y|n>w=s n(2*w)o a y|0<1=s(n+1)w(o*w)(a+o*q y)(tail y) u _ _ 0=[] u n w x|n>w=u n(2*w)x|0<1=(x`mod`w::Integer):u(n+1)w(x`div`w) ``` * code size: 578 * compressed sample size: 3395 ]
[Question] [ Congratulations to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for hitting 100k rep! As a tribute, we are going to study 'Neil numbers'. Neil's user ID is **[17602](https://codegolf.stackexchange.com/users/17602/neil)** and there's something special about the binary representation of this number: $$17602\_{10}=1\color{blue}{000}1\color{blue}{00}11\color{blue}{0000}1\color{blue}{0}\_2$$ $$\begin{array}{c|c} 1&\color{blue}{000}&1&\color{blue}{00}&11&\color{blue}{0000}&1&\color{blue}{0}\\ \hline &3&&2&&4&&1 \end{array}$$ There's exactly one group of consecutive zeros of length **1**, one group of length **2**, one group of length **3** and one group of length **4**. This is an order-4 Neil number. More generally: > > An order-\$n\$ Neil number is a positive integer whose binary > representation contains exactly \$n\$ groups of consecutive zeros and > for which there's exactly one group of consecutive zeros of length > \$k\$ for each \$0<k\le n\$, with \$n>0\$. > > > Clarifications: * Leading zeros are obviously ignored. * Groups of consecutive zeros are indivisible (e.g. `000` is a group of length 3 and cannot be seen as a group of length 1 followed by a group of length 2, or the other way around). ## Examples Order-1 Neil numbers are [A030130](https://oeis.org/A030130) (except **0**, which is not a Neil number as per our definition). The first few order-2 Neil numbers are: ``` 18, 20, 37, 38, 41, 44, 50, 52, 75, 77, 78, 83, 89, 92, 101, 102, 105, 108, 114, ... ``` ## Your task Given a positive integer as input, return \$n\ge 1\$ if this is an order-\$n\$ Neil number or another consistent and non-ambiguous value (*0*, *-1*, *false*, *"foo"*, etc.) if this is not a Neil number at all. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## Test cases Using **0** for non-Neil numbers: ``` Input Output 1 0 2 1 8 0 72 0 84 0 163 0 420 0 495 1 600 3 999 0 1001 2 4095 0 8466 4 16382 1 17602 4 532770 5 ``` Or as lists: ``` Input : 1, 2, 8, 72, 84, 163, 420, 495, 600, 999, 1001, 4095, 8466, 16382, 17602, 532770 Output: 0, 1, 0, 0, 0, 0, 0, 1, 3, 0, 2, 0, 4, 1, 4, 5 ``` Brownie points if your user ID is a Neil number. :-) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ≔Φ⪪⍘N²1ιθI×Lθ⬤θ№θ×0⊕κ ``` [Try it online!](https://tio.run/##JYrBCoMwEETv/QrJaYUU1EN78GSFglBKwf5Ami4xGKMmm/5@uuDAGwbm6UkFvSqXcxejNR7u1hEGGDdnCW4q4kjBegOD3xI90/Lhs5RFw4hacFtmL9vTizWCXkWCt10wwgO9oQl2/jvnYJdFvyZWeByCqIQsBq8DLugJvzCXR9qc6@ulavL55/4 "Charcoal – Try It Online") Link is to verbose version of code. Outputs `0` for irrelevant numbers. Happens to output `1` for `0` as per the OEIS sequence. Explanation: ``` ≔Φ⪪⍘N²1ιθ ``` Convert the input to binary, split on `1`s, and remove empty elements. ``` I×Lθ⬤θ№θ×0⊕κ ``` Check that the array contains all lengths of `0`s and output its length if it does or `0` if it does not. [Answer] # [Python 2](https://docs.python.org/2/), ~~88~~ 86 bytes *-2 bytes thanks to @David!* ``` s=sorted([0]+map(len,bin(input()).split("1")[1:])) n=s[-1] print(s[~n:]==range(n+1))*n ``` [Try it online!](https://tio.run/##TVDLasMwELzrKxafpEYtkt82@EuMDk6sNgJnLSwF2h766@5aTUtBzD60M8us/4jXFfP9ss4WBsiybA9DWLdoZz4qc7pNni8W5dkhd@jvkQvxEvziIs90JkbdGyEYDmF81ob5zWHkYfzC3gzDNuGb5XjSQjzhTtKMJYlAi0YtIZfQSmgo6LqQUOaKoKsk1IqyruvoQykaLNXRbcu6TqPtwWhqRaEq8qZRhq33@CtMVKKof4/KIiV5wjJ1CCvD2Ou6AUqw795eyDM4hE/nf6wGCQ9d0TNILVqwTLfzPPXIiGQvcByOQTL@p/Ko6Zbf "Python 2 – Try It Online") Finds the length of all zero groups, sorts them, and check if the sorted list is `1, 2, 3, ...` --- Same idea in Python 3.8: ### [Python 3.8](https://docs.python.org/3.8/), ~~85~~ 82 bytes ``` lambda n:(m:=max(s:=sorted(map(len,f"{n:b}".split("1")))))*(s[~m:]==[*range(m+1)]) ``` [Try it online!](https://tio.run/##TU/bboQgEH33KyY@4ZY0eEMl5UusD25XWxNBAphsa@yv29GtTQk5c5iZc4Yxn/5j0mlp7NbL121s1fXWghZECanaO3FCusn67kZUa8jYadqHixbXNXx2Zhw8CeMw2s@FuPpbiUbK@mJb/d4R9RRHTbQN2szegYQ6ppBQKCkUGGKeUsgShlDlFDhDVlUVFhjDxozt2TLj/Ggtd0XBGYY8TYqCNcE0@9MYpShh/y4@04MkB2ZHBjFvgqCfLGgK3d10b7gYDBq@BkMe/6Tw6xuJAGzn5tHjhJ7oKABjB@3Jsf8LX2F5lJGcVivUy6mRfwPWJoy2Hw "Python 3.8 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` b1¡€gZ©L¢PΘ®* ``` Outputs `0` as falsey result. [Try it online](https://tio.run/##ASEA3v9vc2FiaWX//2IxwqHigqxnWsKpTMKiUM6Ywq4q//82MDA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/JMNDCx81rUmPOrTS59CigHMzDq3T@q/zP9pQx0jHQsfcSMfQzFjHxMhAx8TSVMfMwEDH0tJSx9DAwFDHxAAoYmFiZgZSYgFUaG5mACQtDUyMdUyNjczNDWIB). **Explanation:** ``` b # Convert the (implicit) input to a binary-string # i.e. 163 → "10100011" # i.e. 420 → "110100100" # i.e. 600 → "1001011000" 1¡ # Split it on 1s # → ["","0","000","",""] # → ["","","0","00","00"] # → ["","00","0","","000"] €g # Take the length of each chunk # → [0,1,3,0,0] # → [0,0,1,2,2] # → [0,2,1,0,3] Z # Get the maximum (without popping) # → 3 # → 2 # → 3 © # Store it in variable `®` (without popping) L # Pop an push a list in the range [1,maximum] # → [1,2,3] # → [1,2] # → [1,2,3] ¢ # Get the count of each in the list of chunk-lengths # → [0,1,3,0,0] and [1,2,3] → [1,0,1] # → [0,0,1,2,2] and [1,2] → [1,2] # → [0,2,1,0,3] and [1,2,3] → [1,1,1] P # Get the product of that Θ # And check that it's exactly 1 # → 0 ==1 → 0 (falsey) # → 2 ==1 → 0 (falsey) # → 1 ==1 → 1 (truthy) ®* # Multiply it by the maximum we stored in variable `®` # → 0*3 → 0 # → 0*2 → 0 # → 1*3 → 3 # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes Anonymous tacit prefix function. Any visual similarity with OP is entirely unintentional. ``` (≢×⍳⍤≢≡∘∧≢¨)~⍤⊤⊆⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NR56LD0x/1bn7UuwTIfNS58FHHjEcdy4HsQys060CiXUDUBiT/pz1qm/Cot@9RV/Oj3jWPerccWm/8qG3io76pwUHOQDLEwzP4f5qCoQIYPOqdq2DAlaZghOAaArkWqLLmRihcQzNjZK6JkQEK19IU2SgzA7isMZBraWmJYpSBgSGUawTSawDWDJO1MDEzg3JNIPZaGCFMNjQ3MzBCyJoaG5mbG4C5pgA "APL (Dyalog Extended) – Try It Online") The structure and order of execution is as follows: ``` ┌────────┴───────┐ ┌─┼──────┐ ┌──┼──┐ ≢ × ┌───┼───┐ ~⍤⊤ ⊆ ⊤ ⍳⍤≢ ≡∘∧ ≢¨ 7 8 5 6 4 2 3 1 ``` `⊤` base-Two representation `⊆` extract sub-lists according to the runs of 1s in… `~⍤⊤` negated (0→1, 1→0) base-Two representation `(`…`)` apply the following function to that:  `≢¨` the length of each run  `≡∘∧` when sorted, does it (0/1) match…  `⍳⍤≢` the indices of the length? `×` multiply that by… `≢` the length [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes ``` .+ $* +`(1+)\1 $1O (O?1)+ 1 O`O+ (^1O|\1O)+1?$|.+ $1 O ``` [Try it online!](https://tio.run/##Fco7DsIwEEXR/q3DSDYjoXmO40@VknI2ECFTUNBQIMrs3Tjtvef7@r0/z3Hx9z5uAneFdE8JO@Fo8LYxCAjrJvAP2rHTgnBzx8nnGIOIqCgRzAtSVKS2IquitQaqEklnqSnnk9QJS9aIdYml6B8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` +`(1+)\1 $1O ``` Begin base 2 conversion, but using `O` instead of `0` as `\10` would be an octal escape. ``` (O?1)+ 1 ``` As part of base 2 conversion we need to remove one `O` before each `1`. This additionally also collapses all runs of `1`s into a single `1`, which simplifies matching the consecutive runs of `O`s later. ``` O`O+ ``` Sort the runs of `O`s in ascending order of length. ``` (^1O|\1O)+1?$|.+ $1 ``` Try to match `1O`, then in each repeat match one more `O` than last time, finally matching an optional `1` at the end. If this succeeds, output the last match (including the leading `1`), otherwise output nothing. ``` O ``` Count the `O`s in the last match. [Answer] # [J](http://jsoftware.com/), 30 24 bytes ``` 0(#*/:~-:#\)@-.~#;._1@#: ``` [Try it online!](https://tio.run/##PY6xCoMwEIb3e4ojDmpb00vURFMEodCpU9dWShGldOlgt4KvbqOJPQh8fLn/514T42GPlcEQd0ho7Es4Hi/n00RRsNmbMTHBLa4TPgYHfhd1YKYY4NM@hm7AimPEuPUynsMEAt0QSE8Cir/TciWhUk@ZpJXK3CcUOZdCWZZrgmgpl5CRWyQoMqVmyua@Qi5ZoRXJxeWp1NoW5WAP7trnG3u2xS9nokF3v7NRX1@xwibeM@E/ph8 "J – Try It Online") *-6 bytes thanks to Bubbler* Fittingly, J has been bested here by Neil's Charcoal answer. [Answer] # [Zsh](https://www.zsh.org/), 76 bytes ``` for g (${(s[1])$(([#2]$1))#??})((a[$#g]++)) <<<${${${${a/#%/0}:#1}:+0}:-$#a} ``` [Try it online!](https://tio.run/##JYzLCoMwEEX3fsVARpxBiklsFULAD0mzEGxsN7YYV5V8e/qQuzhnc@473nMgphyeK8xAuFN0yjMSOaE9KmYxDImJRodi9nXNXFhrcT82NqJsZDJCJVN/eUIxpszF7267xQ1IgYYWztBJCarvpIZLq/teMrzWx7IFqEolJ1Pq6bpUgP8IKRzG@QM "Zsh – Try It Online") Explanation: ``` ${(s[1])$(([#2]$1))#??} ``` Convert to binary, remove the `2#` prefix, and split the string on `1`, giving us our groups of zeroes. ``` for g ( ... )((a[$#g]++)) ``` For each group of zeroes, increment the array at the index given by the length of that string. ``` ${a/#%/0} ``` Substitute the array with empty elements filled with zeroes. (If we only increment the array at `a[3]`, then this will set `a[1]=a[2]=0`) ``` ${${${${ ... }:#1}:+0}:-$#a} ``` Remove all `1`s. If there is anything left (some a[n] != 1), then substitute 0. Otherwise (all a[n] = 1) substitute the length of the array. [Answer] # [R](https://www.r-project.org/), ~~94~~ ~~85~~ ~~75~~ 74 bytes ``` n=scan();z=rle(n%/%2^(0:log2(n))%%2);N=max(0,s<-z$l[!z$v]);N*all(1:N%in%s) ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTusq2KCdVI09VX9UoTsPAKic/3UgjT1NTVdVI09rPNjexQsNAp9hGt0olJ1qxSqUsFiiqlZiTo2Fo5aeamadarPnf8D8A "R – Try It Online") *Edit: -10 bytes thanks to Giuseppe* *Edit 2: -1 more byte thanks again to Giuseppe* Finds differences (`diff`) between remainders of each power-of-two (`n%%2^(0:(l=log2(n))`); when sequential remainders are the same, this corresponds to a run of 'zero bits'. `rle` calculates run lengths, and `s` extracts runs of zeros. If `s` contains all the integers up to it's length `N`, then it's a 'Neil number'. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BŒɠḊm2ṢJƑȧ$Ṫ ``` A monadic Link accepting a positive integer which yields the order (or `0` if not a Neil number). **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//QsWSyaDhuIptMuG5okrGkcinJOG5qv///zE3NjAy "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/p6KSTCx7u6Mo1erhzkdexiSeWqzzcuer/4fZHTWv@/zfUUTDSUbDQUTAHUSY6CoZmxjoKJkYGQMLSVEfBzADIsrS0BEoYGAAVmxiARC1MzMzASi2AugzNzQyAlKmxkbm5AQA "Jelly – Try It Online"). ### How? ``` BŒɠḊm2ṢJƑȧ$Ṫ - Link: positive integer, V e.g. 600 B - convert V to binary [1,0,0,1,0,1,1,0,0,0] Œɠ - run lengths of equal elements [1,2,1,1,2,3] Ḋ - dequeue [2,1,1,2,3] m2 - modulo-two slice [2,1,3] Ṣ - sort [1,2,3] $ - last to links as a monad: Ƒ - is invariant under?: 1 J - range of length (since range(len([1,2,3]))==[1,2,3]) ȧ - logical AND [1,2,3] Ṫ - tail (if empty yields 0) 3 ``` --- Alternative start: `Bṣ1Ẉḟ0ṢJƑȧ$Ṫ` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~116~~ \$\cdots\$ ~~78~~ 77 bytes Saved ~~8~~ 11 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Had to fix a bug, for numbers like \$84\$ (\$1010100\_{2}\$) which have multiple runs of single \$0\$s, which added 3 bytes. Saved 14 bytes thanks to a suggestion from the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Added 6 bytes to fix bugs for numbers with multiple runs of zeros of the same length. ``` c;b;f(n){for(c=3;n;n/=b,c=c&b&~3?n=0:c|b)b=1<<ffs(n);n=ffs(++c)-3;n*=c<8<<n;} ``` [Try it online!](https://tio.run/##TVBNb4MwDL33V1hIrUgJaviGhWyHab@i9FBS2HJYWhEO1Rj768xQQI3Is43fsx1L91PKYZC85LWtSVdfG1uKgGuuD6KkUshdufsL3rRgL/K3JKXw8ryuDXK5FqPjOJK4KNgLmad5rnk/fJ@Vtgl0G8CjdAttZVpzPIEA6DwKPoWUQjKakIIXBxRCnyFkEYWYoZdlGSYYQ3LIxr9pGMcTNUWVl8QMTRT4ScJ6vrap7rdKtlOfDougmE3feh/gjRCsoT/Cw4VwwomwBBDNHeTXudlD8yhvFfcPv7hn73gji8JzHFizApcJ9jiYQgnjaHIw6qe61va0EXKYI@QQDo6jlqUtLzIonMlHdSJ8Td4aTNe2tXXjC7ivsL3A1hQaJ1nIFAzFaeedqJMQZinQb/rhHw "C (gcc) – Try It Online") Returns \$n\$ for an input of an order-\$n\$ Neil number or \$0\$ otherwise. **How?** Performs a bit-wise logical-or summation \$c=3+\sum{2^{r+1}}\$, where \$r\$ is the length of a zero bit run for all runs in the input number (including zero length runs). Checks to see if we've seen the same non-zero length run before and returns \$0\$ if we have. After all the input's zero-bit runs have been added to \$c\$ in this manner, \$c\$ is tested to see if we've seen \$n\$ zero-bit runs of lengths \$(1,2,\dots,n)\$ by testing if \$c\stackrel{?}{=}2^{n+2}-1\$ and returns \$n\$ if this is true, \$0\$ otherwise. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ḃḅ{h0&l}ˢo~⟦₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpma9Rx0rlNISc4pT9ZRqH@7qrH24dcL/hzuaH@5orc4wUMupPb0ov@7R/GWPmhr//4821DHSsdAxBxImOoZmxjomRgY6JpamOmYGBjqWlpY6hgYGhjomBkARCxMzM5ASCyMdQ3MzAyMdU2Mjc3ODWAA "Brachylog – Try It Online") ``` ḅ Take the runs of ḃ the input's binary digits, {h0 }ˢ keep only those that start with 0, { &l}ˢ and map them to their lengths. o The sorted run lengths ~⟦₁ are the range from 1 to the output. ``` Fun fact, my original attempt was `ḃḅo{h0&l}ˢ~⟦₁`, but it mysteriously created a choice point giving me some false positives, so I moved the `o` later to save on a `!`. [Answer] # [Haskell](https://www.haskell.org/), 113 bytes ``` g.f f 0=[0] f x|h:t<-f$div x 2=[0|odd x]++(h+1-mod x 2):t g x|n<-maximum x,r<-[1..n]=sum[n|r==[k|k<-r,y<-x,k==y]] ``` [Try it online!](https://tio.run/##HYvBjoMgEEDv/Yo59LCNYAZrURv4EpYDqasYhRq1G5r47WVxL/Mmb95Ys44/0xSt/I593p06QKlQJ4bd3jdBu3M7/EKAIun92bYQdJZ92YxR92wPf7lvpz7VXlBnwuBeDgJZBFUsz72W68spvy9SqnEfBV3IW9BARinfWkdnBg8S5mXwG5zBmRksKEagIFATqA6UBBi/EigLTKO5EeCYtqZp0gExxSUeti45/0/r9MUqjgm3a1FVqOPn0U2mXyN9zPMf "Haskell – Try It Online") [Answer] # [COW](https://bigzaphod.github.io/COW/), 234 bytes ``` oomMMMMOOOOOmoOMMMMOOMOomoOMoOmOoMMMMOOMMMMOomoOMOomOomOoMoOmoOMMMOOOmooMMMmoomoOmoOMoOmOoMOOmoOMOoMOOMMMmoOmoOMMMMOomoomoOMoOmOoMoOMOOmOomOomoomoOmoOOOOmOoOOOmoomOomOoMMMmoomoOmoOmoOmoOmoOMOOMMMMoOMMMmoOMOoMOOOOOMMMmOomoomoOmooMMMOOM ``` [Try it online!](https://tio.run/##TY9LDsMgDET3nIIjgEMgHKGLyIfomrqLRD0@xR9oLWSNhvEzPOnTH6/3fXnv8b6GcNFrBQemojuWV2CqI00V82YqQZiq7jabg3qbq7XOiRBkDbgUNMi8nFkl5h0gs7HkAOLtG5QyQHsnauco5GqEqk8k1oQNyRzuYo4uh28lL4McG72pqYMKFCG3i0@atBhnUJmLgOIo2db98dexh5HxdRfquh@N9Ae9fwE "COW – Try It Online") Forms a "string" \$S\$ where: \$k\in \{1,\dots,n\}\$ * *Even indexes* (or `control cells`) \$2k-2\$ serve: + to navigate \$S\$ + to know where \$S\$ ends + to count up to \$n\$ * *Odd indexes* (or `k-cells`) \$2k-1\$ contain how many consecutive \$k\$ zeros there are The idea is: when a group of consecutive \$k\$ zeros is found, its `k-cells` in \$S\$ is incremented. Hence the input is a order-\$n\$ Neil number if and only if all `k-cells` are \$1\$. If so, their quantity \$n\$ will be returned. `0` is returned otherwise. ## Explanation ``` moo ] mOo < MOo - OOO * OOM i MOO [ moO > MoO + MMM = oom o [0]: a/2 [1]: a [2]: a%2 [3]: counter of current group of 0 (k) [4]: // unused stuff [5]: S(0) i= ; Read a in [0], copy [ ; While [0] *>= ; Clear [0], paste in [1] [ ; While [1] ->+<=[=->-<<+>=*]= ; {REPEATED SUBTRACTION} ] ; [0] is a/2, [1] is 0, [2] is a%2 >>+< ; Increment [3] // here [3] is k+1 [ ; If [2] {UPDATE THE STRING} // if a%2==1 the current group of 0 it's been truncated >- ; Decrement [3] // [3]-=1 (k) [=>>=-] ; While [x] copy it in [x+2] and decrement it // moves to control cell 2k-2 and leaves a trail of control cells behind >+< ; Increment [x+3] // k-cell 2k-1 +=1 +[<<] ; "Open" [x+2], while [x] x-=2 // use the trail to return back to [1] >>*<* ; Clear [2] and [3] ] ; <<= ; Point to [0], copy ] ; >>>>> ; Point to [5] // the first control cell in S [ ; While [x] is non-zero // while S has not ended =+= ; Paste, increment [x], copy // counting (n) >- ; Move to [x+1] and decrement // k-cell-=1 [ ; {NOT A NEIL NUMBER} // iff k-cell is non-zero *=< ; Divert the flow (performs this loop 2 times, copy 0) ] ; will now break the parent while| > ; Point to [x+2] | // next control cell ] ; | =o ; Paste (n or 0) and print v ``` *Cell `[4]` contains the number of groups of consecutive ones that are larger than \$1\$, +1 if LSB is 1*. Nothing relevant for the task, but I couldn't get rid of it staying in this byte count. Here's a [var dump from [4]](https://tio.run/##TU1BDoAwDPqKTzAas1c0fYTnhqPPryvUxaYhjAK78WQCYXO8JuDi5igOD0crhRQncutKP4NlmxgSFVQhCa@rH3K2rTyuztXgVNTc3/3611rbjBH7dOiZeZ3HGPu2vQ "COW – Try It Online"). [Answer] # [Java (JDK)](http://jdk.java.net/), ~~126~~ ~~117~~ 116 bytes * Saved 1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * Saved 6 bytes - 9, really - thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) ``` q->{int C[]=new int[9],s=0,n=0;for(;q>0;q/=2)C[s]-=q%2<1?(n=++s>n?s:n)-n:~(s=0);while(q++<n)n=C[q]!=1?0:n;return n;} ``` [Try it online!](https://tio.run/##ZZBNb6MwEEDv/hWzlSpBMcQQwkeIySHSSj301CPiQFOSdZY6gE2rKkr/ejq4sJflMPM0zNjzfKreK/f0@vfWDi@N2MO@qZSCp0pIuBCAqap0pTGdsNkbtGi8wyD3Wpyl93uCzaPU9bHuKUyQwwH4rXPzi5AadkXJZf0ByEVaUsUZlZxlh3NvZV3Osm7BA3tXqNLl3X2w8beW5I6jcrlVa2m7cv1l4YydffwRTW11jrORtuS7oit/cX/L1jLraz30EmR2vWX/Lf5@Fq/whlLWs@6FPBYlVP1R2cYRzFYlxnbQCjhcfAoBhYRCPKaQgh8tKYQBw5CuKEQMKU1T/MEYNodsrCZhFJnWBKf8OGKYVssgjtk1M9egLVjjawhYT7fZ8PypdP3mnQfttbiabqQlwIE7cHMMDhy8qm2bT0vY9njKlVzJ4oH48PMxEkzkk@RfLQ5mSsKZcK@J0GOmdDXNopGhJUGteQLdRgrI6DefF0UjhcR4mlmjamo/tgAr8rC4fQM "Java (JDK) – Try It Online") Returns 0 for non-Neil numbers. I feel like this should be smaller, even though it is in Java. Ungolfed: ``` q -> { int C[] = new int[9], //C[i] is how many times a streak of length i appeared s = 0, //Length of current streak of zeroes n = 0; //Max streak for(; q > 0; q /= 2) //Go through all of q's digits until q=0 C[s] -= q % 2 < 1 //If there's a 0 here ? (n = ++s > n ? s : n)//Increment s and set n to the max of s and n - n //Subtract n from that because C[s] should stay the same : ~(s = 0); //Otherwise, set s to 0 and add 1 to C[s] (the previous value of s) while(q++ < n) //For every q 0 < q <= n n = C[q] != 1 ? 0 : n; //if there was not exactly 1 group of length q, set n to 0 return n; } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` BY'w~)SttfX=*z ``` For non Neil numbers the output is `0`. [Try it online!](https://tio.run/##y00syfn/3ylSvbxOM7ikJC3CVqvq/39TYyNzcwMA) Or [verify all test cases](https://tio.run/##y00syfmfFark8N8pUr28TjO4pCQtwlar6r/Lf0MdBSMdBQsdBXMgZWhmrKNgYmQAJCxNdRTMDIAsS0tLoISBAVChiQFI1MLEzAys1AKkw9zMAEiZGhuZmxsAAA). ### Explanation Consider input `532770` as an example. ``` B % Impicit input. Convert to binary % STACK: [1 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 1 0] Y' % Run-length encoding. Gives values and run lengths % STACK: [1 0 1 0 1 0 1 0 1 0], [1 5 1 4 1 2 1 3 1 1] w~ % Swap, negate element-wise % STACK: [1 5 1 4 1 2 1 3 1 1], [0 1 0 1 0 1 0 1 0 1] ) % Indexing (use second input as a mask into the first) % STACK: [5 4 2 3 1] S % Sort % STACK: [1 2 3 4 5] tt % Duplicate twice % STACK: [1 2 3 4 5], [1 2 3 4 5], [1 2 3 4 5] f % Find: (1-based) indices of nonzeros % STACK: [1 2 3 4 5], [1 2 3 4 5], [1 2 3 4 5] X= % Equal (as arrays)? % STACK: [1 2 3 4 5], 1 * % Multiply, element-wise % STACK: [1 2 3 4 5] z % Number of nonzeros. Implicit display % 5 ``` [Answer] # perl -MList::Util=max -MList::Util=uniq -pl, 72 71 bytes ``` @==map{y===c}sprintf("%b",$_)=~/0+/g;$_=(@===max@=)&(@===uniq@=)?0+@=:0 ``` [Try it online!](https://tio.run/##VY7BCoJAFEX37zPEQjHxOY6jYzzyA2rZWioqBkwnnaCI@vSmyV27ew8H7tXHoc2trYkuO/18ENHhNepBdeYUeLO9t/CbkN4JRsl56TcUONGZ95rC@ZRvnbq6ssKopgqtTYFBCQWDVGTAGQKXOQhEkFJCipgCR0dKLsRPKZ1YCGSQZ6wo8NNro/putPFmrUZTVVuj2mnjn7gHNtbtFw "Perl 5 – Try It Online") Reads a number from the input, convert it to a string with the number in binary format, extracts the sequences of 0, takes their length, then prints the number of sequences of 0s if 1) there are no duplicates, and 2) the max length equals the number of sequences. Else, 0 is printed. Edit: Saved a byte by replace `&&` with `&` which works, since the result of `==` is `1` or the empty string, which perl treats as `0` if the operator expects a number. [Answer] # [Python 2](https://docs.python.org/2/), 90 bytes ``` a=[len(z)-1for z in sorted(bin(input())[2:].split('1'))if z] n=len(a) print(range(n)==a)*n ``` [Try it online!](https://tio.run/##HY3BCoMwEAXv@xXBi0mhZRM10UK@RDxYjW1ANhJTaP15q70OM@8t3/QKpPYhjI5ZlmXZ3tt2dsQ3cZVTiGxjntgaYnIjf3jinpZ34kK06t7d1mX2iecyF8JPbOuA7Nn2ApboKfHY09NxEtb24kL7MQ/u4wb2v7swWe0SFNRgFEhdQKkQyqYCjQhN04BElFDiQepS61OpD9FoVFAVyhj8AQ "Python 2 – Try It Online") I found almost the same solution as Surculose Sputum. They had the further insight to get rid of the `[]` so go upvote them :) [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 61 bytes ``` $a=1;$_=sprintf'%b',$_;$a++while s/10{$a}(?!0)//;$_=!/0/*--$a ``` [Try it online!](https://tio.run/##PY3tCoIwGIX/7yoUFlYmezf3iUiXIguMBNGhQj@iW281db2/Hg7nPK9rp154j21NK9zUs5u6Yblnh1t2wU2FbZ4/H13fJjOh8ML2fbymcCIkdFMC5FwU2HpPk@0AsZ0o0v9MsUiaR6Ky3IkziGTEvpWwZSUyxsQFwPqGIQ5bMfikDMSDT7N1S5UEtmaiZEr9RAJp@hnd0o3D7AvXfwE "Perl 5 – Try It Online") Converts number to binary, then removes the 0 sequences in order, starting at 1. When it no longer finds a match, that's the Neil number. [Answer] # [Factor](https://factorcode.org/), 146 bytes ``` : f ( n -- n ) >bin [ = ] monotonic-split [ first 48 = ] [ length ] filter-map natural-sort dup dup length [1,b] >array = [ last ] [ drop 0 ] if ; ``` [Try it online!](https://tio.run/##TY9NS8NAEIbv/RXvTQU3bNI0Hy32KgXpRTwVD9t20i6mm3V2Ahbxt8dNFPGwy8PMyzMzjTlIx8PL82b7uMQbsaMWFyPnxBsOxD/Mxp0owDCba0Cg957cgf5RQh/CJsxCx2LdCcG3VkZKLp3rpHP2AM8kcvVsnWA122yXeCK5CSpIf7yqLdlWuf6yJw7DEg1u4aBU/O6w3luHHR7wij@dmkbEamM5CPJqau/QkjvJOWJjWyFWF@NnzkjPplXjdjj2fnq/wV16v3/FejotKqLARN1oOnLnoSPaBqvhEykyVCgzpMUceaaR1wsUWqOua6Rap8h1rFR5UYyRKgbLQmdYzLOy1Pgadx0vMB7J8A0 "Factor – Try It Online") Not golfy at all with all the mandatory spaces and those long words... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes ``` If[Sort[s=Length/@Take[Split@IntegerDigits[#,2],{2,-1,2}]]==Range@If[s=={},t=0,t=Max@s],t,0]& ``` [Try it online!](https://tio.run/##HYwxC4MwEIX/SqDQ6Ypn1KhDIEMXoYVSu0mGUNIYWm3RGwrib09jh7v3uPe9Gwz1djDk7yY4GZpH174n6mZ5sqOjPlE387Rd@3l5Us1I1tnp6J2nudsB17BwOKTAV62lvJrRWRU/zFIuK5DEOGfzVbMGAtT7cJn8SCxRLlFLCowDq4CVm@TAUpEByznGVRfABEZX13UMECOc43atciH@aBVbaSkwSpHxssQ1hB8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 118 bytes ``` n#0=[n] n#i|mod i 2<1=(n+1)#div i 2|u<-0#div i 2=n:u n%[]=n-1 n%x|1/=sum[1|a<-x,a==n]=0|m<-n+1=m%filter(>n)x (1%).(0#) ``` [Try it online!](https://tio.run/##NcyxDsIgFEDRna9ogiQQRXkdamJ4/kjTgaRtJMLTtMUw8O9YB7d7lvtw63MKoVbiBnsaGHFf4mtsfNNaQElHUHz0n59Lstr8gXRLjEQ/IGnYIxe44JpiD8VZnU8OkQY0JVq9PzCK2YdtWuSdVGYzShDqLA1XNTpP@F48bYe5gWtn2voF "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~67 58 57~~ 55 bytes ``` ->n{i=0;('%b'%n).scan(/0+/).sort.all?{_1==?0*i+=1}?i:0} ``` [Try it online!](https://tio.run/##RY7LbsIwFET3fMUVCJmCm1w7ifNAJmrVXRf9gCiL8BJGKK54LFDsbw9GIGd37oxm5p5v63u/l/3nqu2UxOWMTNdk2n4El03TzkJchA71@Ro0p1PZmaM5SlniXC0ks6Uq0PbVCKBiFLCmT@IU2Isyr6XcYxZ7ZCLyHHMcOE98h0CnRy/O83zIIrpJ/g7gM@EHhKAQ@4lseIilArn3koinqWtP3FkHu2ZzgK0Goyho4/z/2/UC40mnbAGTbl@p2kLoSFswbwGkBA0lkL9fAgWQ768fYsejXbvtHw "Ruby – Try It Online") (+2 bytes because TIO doesn't support ruby 2.7's `_1`) -2 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 10 bytes ``` £ḣ∞0OfΛ¬gḋ ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///Co@G4o@KInjBPZs6bwqxn4biL////NDk1 "Husk – Try It Online") -4 bytes from Zgarb. [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Returns `0` for falsey. ``` ¤ôÍmÊÍf Ê*UeUÊõ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pPTNbcrNZgrKKlVlVcr1&input=MTc2MDI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pPTNbcrNZgrKKlVlVcr1&input=WzEsIDIsIDgsIDcyLCA4NCwgMTYzLCA0MjAsIDQ5NSwgNjAwLCA5OTksIDEwMDEsIDQwOTUsIDg0NjYsIDE2MzgyLCAxNzYwMiwgNTMyNzcwXQotbVM) ``` ¤ôÍmÊÍf\nÊ*UeUÊõ :Implicit input of integer > 17602 ¤ :To binary string > "100010011000010" ô :Split at elements that return truthy Í : When converted to decimal (0=falsey, 1=truthy) > ["","000","00","","0000","0"] m :Map Ê : Length > [0,3,2,0,4,1] Í :Sort > [0,0,1,2,3,4] f :Filter, to remove 0s > [1,2,3,4] \n :Assign to variable U Ê :Length > 4 * :Multiplied by Ue : Test U for equality with UÊ : Length of U > 4 õ : Range [1,length] > [1,2,3,4] :Implicit output of result > 4 ``` [Answer] # [Io](http://iolanguage.org/), 124 bytes Just a port of the 05AB1E answer. ``` method(x,i :=x asBinary lstrip("0")split("1")map(size);if(Range 1 to(i max)map(x,i select(o,o==x)size)reduce(*)==1,i max,0)) ``` [Try it online!](https://tio.run/##HYw9bsMwDIX3nILwRBYcJMfxTwotPULnLoIjNwRky5BUwMnlXdkc@B75PlLCPsHdwM8@u/wMD9xYyryBTV@y2PgCn3KUFStVUVq9ZKx0RbNdMcnb0adM@G2XXwcackCB2W5nevxJzrsxY@BgzEYnH93jb3T4QcZoPmlWRLuXlFEz1Aw9Q3dIw6DbK0NTq9KGG0OrihuGoQRKFbhRx7Zv2vZE@3Klu1YVuV3rrlMEU4jOjk8UvkCpCYVgjbJkv1xo/wc "Io – Try It Online") ]
[Question] [ # The Hourglass This hourglass has 60 "sands of time", and it completely fills each chamber. The clock is 19 characters wide and 13 characters in height. Each chamber has 5 rows of sand and there is a row in the centre that can hold 1 sand. The top row can hold 17 sands, the next one 15 and so on (see below). Sands fall in to the bottom chamber at the rate of one sand per second. ``` START 3 SECONDS LATER 38 SECONDS LATER ███████████████████ ███████████████████ ███████████████████ █.................█ 17 █.............. █ 14 █ █ 0 ██...............██ 15 ██...............██ 15 ██ ██ 0 ███.............███ 13 ███.............███ 13 ███....... ███ 7 █████.........█████ 09 █████.........█████ 09 █████.........█████ 09 ███████.....███████ 05 ███████.....███████ 05 ███████.....███████ 05 █████████.█████████ 01 █████████.█████████ 01 █████████.█████████ 01 ███████ ███████ ███████ . ███████ ███████ . ███████ █████ █████ █████ . █████ █████ . █████ ███ ███ ███ . ███ ███.... ███ ██ ██ ██ ██ ██...............██ █ █ █ █ █.................█ ███████████████████ ███████████████████ ███████████████████ ``` # The Challenge Display the hourglass (no numbers or headings are required) after a certain period of time (0 ≤ t ≤ 60). # Coding Rules 1. The hourglass should look exactly as shown here. You may replace the **`█`** character and/or the **`.`** character with whatever you like to fit your language (Unicode, ASCII compatibility issues). 2. The input should be a number such as 45 or 7. Display the clock after these many seconds. 3. The output can either be displayed or saved to a file. No extra text or labels as shown above are required - just the hourglass is all we need. 4. If the user enters t > 60, you don't have to handle the error. # Points 1. Shortest code wins. [Answer] # JavaScript (*ES6*), 203 ~~208 233 270 256~~ characters **Edit** Revised using a loop instead of a sequence of calls. **Edit** Added top and bottom row that were missing. A function returning the output. Run the snippet in Firefox to test. ``` f=w=>[h='█'[R='repeat'](19),...[17,15,13,9,5,1,5,9,13,15,17].map((d,i)=>(t=i>5?-v:v,v-=i<5?d:1-d,e=' '[R](d/2),b='█'[R](10-d/2),b+('.'[R](t<d&&d-t)+e+' .'[i>4&w>i-6&t>=d|0]+e).slice(0,d)+b),v=w),h].join` ` // Less golfed F= w=>[h='█'.repeat(19), ... [17, 15, 13, 9, 5, 1, 5, 9, 13, 15, 17].map( (d,i) => ( t = i>5 ? -v : v, v -= i<5 ? d : 1-d, e = ' '.repeat(d / 2), b = '█'.repeat(10 - d / 2), b + ('.'.repeat(t < d && d - t) + e + ' .'[i > 4 & w > i-6 & t >= d | 0] + e).slice(0,d) + b ), v = w ), h].join('\n') // TEST O.innerHTML=f(+I.value) function tick(d) { var i=+I.value+d I.value=i O.innerHTML=f(i) } var int=0; function auto() { function go() { var t = I.value; O.innerHTML=f(++t) if (t>70)t=0; I.value = t; } if (A.checked && !int) { int = setInterval(go, 200); } else if (!A.checked && int) { clearInterval(int); int = 0; } } ``` ``` input[type=text] { width: 3em } ``` ``` <button onclick='tick(-1)'>-</button> <input type=text id=I value=0 onchange='tick(0)' > <button onclick='tick(1)'>+</button> <input type=checkbox id=A onclick='auto()'>Fly time <pre id=O><pre> ``` [Answer] ## Python 2, 200 ``` t=input()+1 s=' '*t+'.'*60+' '*70 n=0 d=sum((1<t<56,2<t<48,3<t<36,4<t<22)) for c in'ctrplhdhlprtc':i=ord(c)-99;print[s[n+i:n:-1],[s[180-n-i+d:][:i],'.'][5+d*3>i>0]][n>59].center(i).center(19,'#');n+=i ``` xnor has made a **197** byte version [in the chat](https://chat.stackexchange.com/transcript/message/22111685#22111685). I would post an explanation, but I've lost track of how it actually works... Also, here's an animated version with curses: ![hourglass](https://i.stack.imgur.com/DspYD.gif) ``` from curses import* w=initscr() for t in range(1,61): s=' '*t+'.'*60+' '*70 n=0 d=sum((1<t<56,2<t<48,3<t<36,4<t<22)) for i in 0,17,15,13,9,5,1,5,9,13,15,17,0:w.addstr([s[n+i:n:-1],[s[180-n-i+d:][:i],'.'][5+d*3>i>0]][n>59].center(i).center(19,'#')+"\n");n+=i w.refresh() w.clear() napms(999) endwin() ``` [Answer] # Python 2.7, ~~362~~ ~~356~~ 347 ``` e,c,x,a,b,n=' .#ab\n';R,r,s,l,T,m=range,str.replace,'',19,[1,2,3,5,7,9],-1 for t in[T,T[:m][::m]]:s+=''.join([n+x*y+c*(l-y*2)+x*y for y in t]);c=b s=list(s) for i in R(130,220,20):s[i]=a for _ in R(input()):s[s.index('.')]=e;i=s.index(a)if a in s else 219-s[::m].index(b);s[i]='.' for l in(x*l+r(r(''.join(s),a,e),b,e)+n+x*l).split(n):print l[::m] ``` [![hourglass](https://i.stack.imgur.com/dYvAY.gif)](https://i.stack.imgur.com/dYvAY.gif) Output at 38 seconds : ``` ################### # # ## ## ###....... ### #####.........##### #######.....####### #########.######### ####### . ####### ##### . ##### ###... . ### ##...............## #.................# ################### ``` [Answer] # C 544 Here's what I have so far for a C solution. ``` #include <stdio.h> int main(int z,char **a){int r,i,y=i=0,v,d,t,m,s=atoi(a[1]),n[13]={0,43,28,15,6,1,0,1,5,13,25,39,0};char H[13][20];while(y<13){int x,b=x=i=0;v=y-6;t=3+abs(v);m=2*abs(v);d=t<m?t:m;d=9-d;if(d==0)d=10;while (b<d){H[y][b]='#';H[y][18-b]='#';b++;}while(x<19-2*b){if(x<=s-n[y])H[y][x+b]=v>0?' ':'.';else H[y][x+b]=v>0?'.':' ';x++;}if(s>58)r=0;else if(s==58)r=1;else if(s==57)r=2;else if(s==56)r=3;else if(s>38)r=4;else if(s>24)r=3;else if(s>12)r=2;else if(s>4)r=1;while(i<r){H[7+i][9]='.';i++;}H[y][19]='\n';y++;}fputs(H,stdout);} ``` Compiled with the following command: ``` gcc -w -o hourglass hourglass.c // I realize I should have cast H as a char *, but since it works this way, I just decided to suppress the error from the compiler instead to save space. ``` Admittedly, this language has a lot of bulk- that include statement was a bit of a handicap coming right out of the blocks, but I really was just looking for an excuse to practice using C. I hope you like my solution, and let me know if you see ways to improve. [Answer] # Matlab, 252 bytes The idea is constructing a matrix that looks like this: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 0 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 0 0 0 0 0 45 44 43 42 41 40 39 38 37 36 35 34 33 0 0 0 0 0 0 0 0 54 53 52 51 50 49 48 47 46 0 0 0 0 0 0 0 0 0 0 0 0 59 58 57 56 55 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 116 117 61 118 119 0 0 0 0 0 0 0 0 0 0 0 0 108 109 110 111 62 112 113 114 115 0 0 0 0 0 0 0 0 96 97 98 99 100 101 63 102 103 104 105 106 107 0 0 0 0 0 82 83 84 85 86 87 88 64 89 90 91 92 93 94 95 0 0 0 66 67 68 69 70 71 72 73 65 74 75 76 77 78 79 80 81 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` From there it is easy to fill the entries with the strings dependent on `n` (filling all entries that are greater than `n` and smaller than `n+60` with dots) ``` function c=f(n); b=zeros(13,19); z=[0,17,32,45,54,59]; y=-2:3; for k=2:6; d=k+sum(k>4:5); b(k,d:20-d)=z(k):-1:z(k-1)+1; b(14-k,d:19-d)=68+(z(k-1):z(k)-2)-k; end; b(8:12,11:19)=b(8:12,10:18); b(7:12,10)=60:65;c=[ones(13,19)*32,'']; c(~b)='¶';c(n<b)=46;c(b>n+60)=32 ``` For `n=38` we get this output: ``` ¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶ ¶ ¶ ¶¶ ¶¶ ¶¶¶....... ¶¶¶ ¶¶¶¶¶.........¶¶¶¶¶ ¶¶¶¶¶¶¶.....¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶.¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶ . ¶¶¶¶¶¶¶ ¶¶¶¶¶ . ¶¶¶¶¶ ¶¶¶... . ¶¶¶ ¶¶...............¶¶ ¶.................¶ ¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶ ``` [Answer] # Java, 712 Input is taken from the command line. Handles both negative values for the time as well as larger than required. ``` enum H{;public static void main(String[]r){int x=0,y=0,z=0,l,t=Integer.parseInt(r[0]);String b="",d="█",e=" ",f=".",n="\n",j,k,a="███████████████████"+n;int[]w={17,15,13,9,5},v;int[][]h=new int[10][];for(;x<5;){l=w[x];v=(h[x++]=new int[l--]);l/=2;v[l]=++z;for(y=0;y++<l;){v[l-y]=++z;v[l+y]=++z;}}for(z=0;x>0;){l=w[--x];v=(h[9-x]=new int[l--]);v[l/2]=++z;}for(;x<5;){l=(w[x]-1)/2;v=h[9-x++];for(y=0;y++<l;){v[l-y]=++z;v[l+y]=++z;}}p(a);for(x=0;x<5;x++){l=w[x];j=b;for(y=0;y++*2<19-l;)j+=d;k=b;for(y=0;y<l;)k+=t<h[x][y++]?f:e;p(j+k+j+n);}j="█████████";p(j+f+j+n);for(;x>0;){l=w[--x];j=b;for(y=0;y++*2<19-l;)j+=d;k=b;for(y=0;y<l;)k+=t<h[9-x][y++]?e:f;p(j+k+j+n);}p(a);}static void p(String s){System.out.print(s);}} ``` output: ``` time: 0 ███████████████████ █.................█ ██...............██ ███.............███ █████.........█████ ███████.....███████ █████████.█████████ ███████ ███████ █████ █████ ███ ███ ██ ██ █ █ ███████████████████ time: 1 ███████████████████ █........ ........█ ██...............██ ███.............███ █████.........█████ ███████.....███████ █████████.█████████ ███████ . ███████ █████ █████ ███ ███ ██ ██ █ █ ███████████████████ time: 9 ███████████████████ █.... ....█ ██...............██ ███.............███ █████.........█████ ███████.....███████ █████████.█████████ ███████ . ███████ █████ . █████ ███ . ███ ██ . ██ █ ..... █ ███████████████████ time: 41 ███████████████████ █ █ ██ ██ ███.. ..███ █████.........█████ ███████.....███████ █████████.█████████ ███████ . ███████ █████ . █████ ███ ....... ███ ██...............██ █.................█ ███████████████████ ``` It fills the sand from the center expanding outwards. I can probably golf it more if I get lazy with how it fills the bottom half and empties the top half. But for now I quite like it. [Answer] **Haskell 512 Bytes** ``` h=[17,15,13,9,5,1];b=drop 1$reverse h;n#s=[1..n]>>[s];s='.';n =' ';c q=(q#n)++(60-q)#s;f q|q<=5=q#s|3>2=g#s where{g=foldl i 5 (scanl (+) 0 h);i x y=if q>x+y then x-1 else x};e q=j#s++(59-length(k q)-(j))#n where{j=q-length(f q)};l q=c q++k q++(reverse$e q);p _ []=[];p x y=reverse(z++take q x++z):p (drop (head y) x) (tail y)where{q=head y;z=replicate(div (19-q) 2) '|'};k q= (concat.map(\x -> z x ++ "." ++ z x).take (length.f$q)$b)where{z x=(div x 2)#n};m n=mapM_ putStrLn $ t ++ p (l n) (h++b) ++ t;t=[19#'|'] ``` Input `m 55` Output ``` ||||||||||||||||||| | | || || ||| ||| ||||| ||||| |||||||.... ||||||| |||||||||.||||||||| ||||||| . ||||||| |||||.........||||| |||.............||| ||...............|| |.................| ||||||||||||||||||| ``` Input `m 48` Output ``` ||||||||||||||||||| | | || || ||| ||| |||||...... ||||| |||||||.....||||||| |||||||||.||||||||| ||||||| . ||||||| |||||.. ||||| |||.............||| ||...............|| |.................| ||||||||||||||||||| ``` [Answer] # Ruby: ~~196~~ ~~190~~ ~~186~~ ~~185~~ 184 characters ``` u=[0,17,15,13,9,5].map{|i|(?.*i).center 19,?#}*$/ (?1..$*[0]).map{u[?.]=' '} l=u.reverse 5.times{|i|l[p=i*20+9]==?.&&l[' ']&&(l[p]=?|)&&l[' ']=?.} puts u,?#*9+?.+?#*9,l.tr('. | ',' .') ``` CW because not conforms exactly to the posted samples as this consumes sand starting from the left. Mostly just a demonstration of [`String.[]=`](http://ruby-doc.org/core-2.2.2/String.html#method-i-5B-5D-3D) method. Sample run: ``` bash-4.3$ ruby hg.rb 38 ################### # # ## ## ### .......### #####.........##### #######.....####### #########.######### ####### . ####### ##### . ##### ### . ...### ##...............## #.................# ################### ``` # Ruby: 215 characters This is generates the exact required output: ``` u=[0,17,15,13,9,5].map{|i|(?.*i).center 19,?#}*$/ (?1..$*[0]).map{u[?.]=' '} l=u.reverse 5.times{|i|l[p=i*20+9]==?.&&l[' ']&&(l[p]=?|)&&l[' ']=?.} puts ([u,?#*9+?.+?#*9,l.tr('. | ',' .')]*$/).split($/).map &:reverse ``` Sample run: ``` bash-4.3$ ruby hg.rb 38 ################### # # ## ## ###....... ### #####.........##### #######.....####### #########.######### ####### . ####### ##### . ##### ###... . ### ##...............## #.................# ################### ``` [Answer] # C#, 382 ~~410~~ it might still be possible to reduce it by a few bytes... ``` class Program{static void Main(){int u=60-22,d=u,i,j,k,l,m;var c=new char[260];var r=new int[]{0,17,15,13,9,5,1,5,9,13,15,17,0,54,45,32,17,0};for(i=0;i<13;){m=0;l=(19-r[i])/2-1;for(j=19;j>=0;){k=i*20+j--;var b=j>=l&&j<r[i]+l;if(i>6&b)c[k-r[i]+m++ +m]=r[i+6]<d&&d-->0||j==8&r[i+6]>d&&d-->0?'.':' ';else c[k]=i<7&b?u-->1?' ':'.':'█';}c[++i*20-1]='\n';}System.Console.WriteLine(c);}} ``` [Fiddler - 38sec](https://dotnetfiddle.net/4bAkuZ) ]
[Question] [ *"The Nobel Prize in mathematics was awarded to a California professor who has discovered a new number! The number is bleen, which he claims belongs between 6 and 7."* --George Carlin In this challenge, you will print all Integers, inclusive, within the given input range. Print numbers ascending or descending according to their input order. That is, for input `[n1, n2]`, print *ascending* if `n1 < n2`, *descending* if `n1 > n2`. Since `bleen` is now an Integer number it may be used as input. It must also be included in the output, between `6` and `7` where applicable. Also note that `-bleen` exists between -7 and -6. **Input** Two Integers `[n1, n2]` in the range [-10, 10], inclusive, via your programming language's input of choice. (Input may also contain `bleen` and `-bleen`!) **Output** Print all Integers starting at `n1` and ending with `n2`, including the newly discovered `bleen` between 6 and 7. Output can be a range of character separated numbers in some form your language supports - that is, comma or space separated. One trailing space of output is okay. **Examples** ``` Input: 1 10 Output: 1 2 3 4 5 6 bleen 7 8 9 10 Input: -9 -4 Output: -9 -8 -7 -bleen -6 -5 -4 Input: -8 bleen Output: -8 -7 -bleen -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 bleen Input: 9 1 Output: 9 8 7 bleen 6 5 4 3 2 1 Input: 2 -bleen Output: 2 1 0 -1 -2 -3 -4 -5 -6 -bleen Input: -bleen 0 Output: -bleen -6 -5 -4 -3 -2 -1 0 Input: bleen bleen Output: bleen Input: 2 2 Output: 2 ``` **Additional notes** You may write a [program or function](http://meta.codegolf.stackexchange.com/q/2419) and use any [standard method](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. [Answer] # Python 3, 132 130 bytes ``` r=round bleen=6.1 m=1.08 a,b=eval(input()) d=1-2*(a>b) print(*[[r(i/m),"-bleen"[i>0:]][i*i==49]for i in range(r(m*a),d+r(m*b),d)]) ``` Takes input in the following example format: ``` -8, bleen ``` [Answer] # Ruby, ~~114~~ ~~100~~ 98 bytes Input is an array with `[n1, n2]`. (If it must be two seperate arguments, +1 byte to change the function arg from `g` to `*g`. Bleen must be a string, `"bleen"`. Outputs an array of the range. Suggested by @Jordan with his (?) initial version granting -7 bytes, but I also golfed off 7 more after that. [Try it online.](https://repl.it/CjNX) ``` ->g{a=*-10..-7,?-+b='bleen',*-6..6,b,*7..10;x,y=g.map{|v|a.index v} y<x ?a[y..x].reverse: a[x..y]} ``` Original full program version that reads input from `ARGV`: ``` b='bleen' a=[*-10..-7,?-+b,*-6..6,b,*7..10].map &:to_s x,y=$*.map{|v|a.index v} puts y<x ?a[y..x].reverse: a[x..y] ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 35 bytes ``` K++L\-P_J++`M7"bleen"`M}7TJ@LK}FxLK ``` [Test suite.](http://pyth.herokuapp.com/?code=K%2B%2BL%5C-P_J%2B%2B%60M7%22bleen%22%60M%7D7TJ%40LK%7DFxLK&test_suite=1&test_suite_input=%221%22%2C%2210%22%0A%22-9%22%2C%22-4%22%0A%22-8%22%2C%22bleen%22%0A%229%22%2C%221%22%0A%222%22%2C%22-bleen%22%0A%22-bleen%22%2C%220%22%0A%22bleen%22%2C%22bleen%22%0A%222%22%2C%222%22&debug=0) The first part, i.e. `K++L\-P_J++`M7"bleen"`M}7TJ`, generates this array: ``` ['-10', '-9', '-8', '-7', '-bleen', '-6', '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5', '6', 'bleen', '7', '8', '9', '10'] ``` and then stores it in `K`. The second part, i.e. `@LK}FxLK`, finds the sublist indicated by the input. [Answer] ## Python 3, ~~157~~ ~~145~~ ~~123~~ ~~108~~ ~~115~~ ~~139~~ ~~161~~ ~~158~~ 153 bytes Saved 22 thanks to Lynn. 17 saved thanks to shooqie. 3 saved thanks to ljeabmreosn. 5 saved thanks to Geoff Reedy. ``` a,b=eval(input()) s='-' c='bleen' d=a<b l=list(map(str,range(-10,11)))[::[-1,1][d]] x=l.insert y=l.index x(4,d*s+c) x(18,(1^d)*s+c) print(l[y(a):y(b)+1]) ``` Input like `'-10', '8'`. Tips are welcome for a beginner. Added 7 to account for `-bleen`. Added 15 to account for reversed input like `'8','-10'`. Added a large 21 to account for the reversed input signs for `bleen` vs `-bleen`. [Answer] # Ruby, 141 bytes ``` ->*a{ l="bleen" s=13 a,b=a.map{|n|2*n rescue s*(n<=>?b)} b,a,r=a,b,1if b<a o=(a..b).map{|n|n==s ?l:n==-s ??-+l:n/2}.uniq puts r ?o.reverse: o} ``` ## Ungolfed ``` lambda do |*args| bleen = "bleen" subst = 13 # This will stand in for "bleen" a, b = args.map {|arg| begin # Double the number 2 * arg rescue # It wasn't a number, so it's "bleen" or "-bleen"; replace it with 13 or -13 subst * (arg <=> "b") end } if b < a # If the range isn't ascending, reverse it and remember that we did b, a, reverse = a, b, 1 end # Step through the range, replacing 13 and -13 with "bleen" and "-bleen" and # halving everything else result = (a..b).map {|n| if n == subst bleen elsif n == -subst "-" + bleen else n / 2 end }.uniq # Drop duplicates # Reverse the result if the range was descending puts reverse ? result.reverse : result end ``` [Answer] ## Batch, ~~239~~ 186 bytes ``` @set/ableen=1431655772,a=%1*3,b=%2*3,c=b-a^>^>31^|1 @for /l %%i in (%a%,%c%,%b%)do @((if %%i==20 echo bleen)&(if %%i==-20 echo -bleen)&set/aj=%%i%%3,k=%%i/3&cmd/cif %%j%%==0 echo %%k%%) ``` Works by looping from `3*%1` to `3*%3` and then dividing by three and printing the numbers with no remainder, however setting `bleen` to that magic number causes integer overflow and the value `20` is used instead. This is then printed out at the appropriate point in the loop. [Answer] # JavaScript (ES6), 158 Nice challenge, hard to golf. Probably the range methods used in Python and Ruby answers could score better even in JS. ``` (a,b)=>(c=x=>x<-6?x-1:x>6?x+1:1/x?x:x<'b'?-7:7,a=c(a),b=c(b),d=b>a?1:-1,a-=d,e=x=>x-7?x-(x>7):'bleen',[...Array(d*(b-a))].map((x=a+=d)=>x<0?'-'+e(-x):e(x))) ``` *Less golfed* ``` (a,b)=>( c=x=>x<-6?x-1:x>6?x+1:1/x?x:x<'b'?-7:7, a=c(a),b=c(b), d=b>a?1:-1, a-=d, e=x=>x-7?x-(x>7):'bleen', [...Array(d*(b-a))].map((x=a+=d)=>x<0?'-'+e(-x):e(x)) ) ``` **Test** ``` f=(a,b)=>(c=x=>x<-6?x-1:x>6?x+1:1/x?x:x<'b'?-7:7,a=c(a),b=c(b),d=b>a?1:-1,a-=d,e=x=>x-7?x-(x>7):'bleen',[...Array(d*(b-a))].map((x=a+=d)=>x<0?'-'+e(-x):e(x))) function go(){ var a=A.value,b=B.value // make them numeric if possible a=isNaN(a)?a:+a b=isNaN(b)?b:+b O.textContent=f(a,b) } go() ``` ``` A <select id=A onchange='go()'> <option>-10<option>-9<option>-8<option>-7<option>-bleen<option>-6<option>-5<option>-4<option>-3<option>-2<option>-1<option>0 <option>1<option>2<option>3<option>4<option>5<option>6<option>bleen<option>7<option>8<option>9<option>10 </select> B <select id=B onchange='go()'> <option>-10<option>-9<option>-8<option>-7<option>-bleen<option>-6<option>-5<option>-4<option>-3<option>-2<option>-1<option>0 <option>1<option>2<option>3<option>4<option>5<option>6<option>bleen<option>7<option>8<option>9<option selected>10 </select> <pre id=O></pre> ``` [Answer] # Swift 2.2, 342 Bytes ``` func a(x:String,y:String){var k="bleen",a=Int(x) ?? (x==k ?(x==y ? -9:6):-6),b=Int(y) ?? (y==k ?6:-6),t=0,s=[Any](),f=Int(x)==nil ?x:"";if a>b{t=a;a=b;b=t};for i in a...b{if i==7 && a != 7{s.append(k)};s.append(i);if -i==7 && b != -7{s.append("-"+k)}};for v in t==0 ?s:s.reverse(){f+=" \(v)"};if Int(y)==nil&&b>0{f+=" \(y)"};print(x==y ?x:f)} ``` [Test this using IBM's Swift Sandbox](http://swiftlang.ng.bluemix.net/#/repl/57a3c19296ff73f744b74093) **Ungolfed** ``` func bleen(x: String, y: String){ var k = "bleen", a = Int(x) ?? (x == k ? (x == y ? -9 : 6) : -6), b = Int(y) ?? (y == k ? 6: -6), t = 0, s = [Any](), f = Int(x) == nil ? x : "" if a > b{ t = a a = b b = t } for i in a...b{ if i == 7 && a != 7{s.append(k)} s.append(i) if -i == 7 && b != -7{s.append("-" + k)} } if Int(y) == nil && b > 0{s.append(y)} for v in t == 0 ? s : s.reverse(){ f+="\(v) " } print(x == y ? x : f) } ``` [Answer] # Java, 271 bytes ``` int p(String w){if(w.contains("b"))return w.length()<6?7:-7;int i=Integer.decode(w);return i<-6?i-1:i>6?i+1:i;}void b(String s,String f){Integer l=p(s),r=p(f);for(r+=l<r?1:-1;l!=r;l-=l.compareTo(r))System.out.print(l==-7?"-bleen ":l==7?"bleen ":l+(l<-7?1:l<7?0:-1)+" ");} ``` Ungolfed with test cases: ``` class Bleen { static int p(String w) { if(w.contains("b")) return w.length() < 6 ? 7 : -7; int i = Integer.decode(w); return i < -6 ? i-1 : i>6 ? i+1 : i; } static void b(String s, String f) { Integer l = p(s), r = p(f); for(r += l<r ? 1 : -1; l != r; l -= l.compareTo(r)) System.out.print(l == -7 ? "-bleen " : l == 7 ? "bleen ": l+(l < -7 ? 1 : l<7 ? 0 : -1)+" "); } public static void main(String[] args) { b("1","10"); System.out.println(); b("-9","-4"); System.out.println(); b("-8", "bleen"); System.out.println(); b("9", "1"); System.out.println(); b("2", "-bleen"); System.out.println(); b("-bleen", "0"); System.out.println(); b("bleen", "bleen"); System.out.println(); b("2", "2"); System.out.println(); } } ``` Call b(start, end). Because the parameters are strings, it takes a lot of space to convert those into ints. Essentially the program treats 7 & -7 as bleen and -bleen. [Answer] # Java 7, 251 bytes ``` import java.util.*;String b(Object...a){String q="bleen",r="";List l=new ArrayList();int j=-10,i,z,y,t;while(j<11)l.add(j++);l.add(4,"-"+q);l.add(18,q);z=l.indexOf(a[0]);y=l.indexOf(b[1]);if(y<z){t=z;z=y;y=t;}for(i=z;i<=y;)r+=l.get(i++)+" ";return r;} ``` [Different approach](https://codegolf.stackexchange.com/a/87572/52210) which is shorter than the already existing [Java 7 answer](https://codegolf.stackexchange.com/a/88624/52210). Also, it's unfortunate that the parameters are potentially not in order, which adds some bytes to swap them around. **Ungolfed & test cases:** [Try it here.](https://ideone.com/RpkuFv) ``` import java.util.*; class Main{ static String b(Object... a){ String q = "bleen", r = ""; List l = new ArrayList(); int j = -10, i, z, y, t; while(j < 11){ l.add(j++); } l.add(4, "-"+q); l.add(18, q); z = l.indexOf(a[0]); y = l.indexOf(a[1]); if(y < z){ t = z; z = y; y = t; } for(i = z; i <= y; ){ r += l.get(i++) + " "; } return r; } public static void main(String[] a){ System.out.println(b(1, 10)); System.out.println(b(-9, -4)); System.out.println(b(-8, "bleen")); System.out.println(b(9, 1)); System.out.println(b(2, "-bleen")); System.out.println(b("-bleen", 0)); System.out.println(b("bleen", "bleen")); System.out.println(b(2, 2)); } } ``` **Output:** ``` 1 2 3 4 5 6 bleen 7 8 9 10 -9 -8 -7 -bleen -6 -5 -4 -8 -7 -bleen -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 bleen 1 2 3 4 5 6 bleen 7 8 9 -bleen -6 -5 -4 -3 -2 -1 0 1 2 -bleen -6 -5 -4 -3 -2 -1 0 bleen 2 ``` [Answer] # Scala, 223 bytes ``` object B extends App{val b="bleen" val L=((-10 to -7)++List(s"-$b")++(-6 to 6)++List(b)++(6 to 10)).map(""+_) val Array(s,e)=args.map(L.indexOf(_)) println((if(s<=e)L.slice(s,e+1)else L.slice(e,s+1).reverse).mkString(" "))} ``` [Answer] # JavaScript (ES6), 178 bytes ``` (s,e)=>{q='bleen';t=[];for(i=-10;i<11;i++)t.push(i);t.splice(4,0,'-'+q);t.splice(18,0,q);s=t.indexOf(s);e=t.indexOf(e);s>e&&t.reverse()&&(e=22-e)&&(s=22-s);return t.slice(s,e+1)} ``` [Try it](https://repl.it/Cjn1/2) EDIT: Fix for reverse ordering.Thanks Patrick, missed this condition [Answer] ## Python 3, 126 bytes Input is in the form `-5, 'bleen'` ``` l=list(range(-10,11)) c='bleen' s=l.insert t=l.index s(4,'-'+c) s(18,c) i,j=map(t,eval(input())) d=1-2*(i<j) print(l[i:j+d:d]) ``` [Answer] # **R**, 110 107 bytes Thanks to Cyoce for golfing 3 bytes. ``` a=function(x,y){e=c(-10:-7,"-bleen",-6:6,"bleen",6:10) b=function(d)which(e==as.character(d)) e[b(x):b(y)]} ``` Builds the whole list in order, picks out the relevant ones. Function in the middle named "b" seemed the easiest way to make that happen. Apply,etc [Answer] # Javascript (using external library) (343 bytes) ``` (a,b)=>{r="bleen";s="-"+r;c=d=>d==r?7:(d==s?-7:d);i=c(a);j=c(b);m=Math.min(i,j);n=Math.max(i,j);w=i<=j?_.RangeTo(i,j):_.RangeDown(i,Math.abs(j-i)+1);g=i<j?6:7;if(n>-7&&m<-6){w=w.InsertWhere("-bleen",x=>x==-7)}if(m<8&&n>6){w=w.InsertWhere("bleen",x=>x==g)}if(a==r||b==r){w=w.Where(x=>x!=7)}if(a==s||b==s){w=w.Where(x=>x!=-7)}return w.ToArray()} ``` Link to lib: <https://github.com/mvegh1/Enumerable> Screenshot: [![enter image description here](https://i.stack.imgur.com/eVhHq.png)](https://i.stack.imgur.com/eVhHq.png) [Answer] # Python 2, 100 bytes The first four lines generate the list `[-10, -9, -8, -7, 'bleen', -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 'bleen', 7, 8, 9, 10]`. The next line gets input and stores it in `s` and `e`. The last two lines use `.index()` and list slicing notation to get the correct range. ``` a=range(-10,11) b="bleen" c=a.insert c(17,b) c(4,b) s,e=eval(input()) d=a.index print a[d(s):d(e)+1] ``` Works in the same way as Leaky Nun's answer but developed independently. Stole an input method from orlp. # Ungolfed: ``` array = range(-10, 11) array.insert(17, "bleen") array.insert(4, "bleen") start, end = eval(input()) print array[array.index(start):array.index(end) + 1] ``` ]
[Question] [ *This is the first in a series of Island Golf challenges. [Next challenge](https://codegolf.stackexchange.com/q/114053/16766)* Given an island in ASCII-art, output an optimal path to circumnavigate it. ## Input Your input will be a rectangular grid consisting of two characters, representing land and water. In the examples below, land is `#` and water is `.`, but you may substitute any two distinct characters you wish. ``` ........... ...##...... ..#####.... ..#######.. .#########. ...#######. ...#####.#. ....####... ........... ``` There will always be at least one land tile. The land tiles will all be contiguous (i.e. there's only one island). The water tiles will also be contiguous (i.e. there are no lakes). The outer border of the grid will all be water tiles. Land tiles will **not** be connected diagonally: i.e., you will never see something like ``` .... .#.. ..#. .... ``` ## Output Your code must output the same grid, with a *shortest circumnavigation* drawn on it. In the examples below, the circumnavigation path is drawn with `o`, but you may substitute any character as long as it is distinct from your land and water characters. A *circumnavigation* is a simple closed curve, drawn entirely on water tiles, that fully encircles all land tiles on the grid. Diagonal connections **are** allowed. For instance, this is a circumnavigation of the above island (but not a shortest one): ``` .ooooo..... o..##.oo... o.#####.o.. o.#######o. o#########o ooo#######o ..o#####.#o ..oo####..o ....oooooo. ``` The length of a circumnavigation is computed as follows: For every pair of adjacent tiles on the path, if they are connected horizontally or vertically, add 1; if they are connected diagonally, add √2. The length of the above path is 22 + 7√2 (≈ 31.9). A *shortest* circumnavigation is a circumnavigation with the shortest possible length. Your program should output any one path that satisfies this condition. For most islands, there will be multiple possible solutions. Here is one solution for the above island, with length 10 + 13√2 (≈ 28.4): ``` ...oo...... ..o##oo.... .o#####oo.. .o#######o. o#########o .o.#######o ..o#####.#o ...o####.o. ....ooooo.. ``` ## Details Your solution may be a [full program or a function](https://codegolf.meta.stackexchange.com/a/2422/16766). Any of the [default input and output methods](https://codegolf.meta.stackexchange.com/q/2447/16766) are acceptable. Your input and output may be a multiline string or a list of strings. **If** your language has a character type distinct from single-character strings, you may substitute "list of characters" for "string" in the previous sentence. If your language needs to input the height and/or width of the grid, you may do so. Your output may (optionally) have a single trailing newline. As mentioned above, you may use any three distinct characters in place of `#.o` (please specify in your submission which characters you're using). ## Test cases **A.** Islands with unique shortest circumnavigations: ``` ... .#. ... .o. o#o .o. ...... .####. ...... .oooo. o####o .oooo. ...... ...... ..##.. ...#.. ...... ...... ...... ..oo.. .o##o. ..o#o. ...o.. ...... ....... .#####. ...#... ...#... .#####. ....... .ooooo. o#####o o..#..o o..#..o o#####o .ooooo. ....... ...#... ...#... .#####. ...#... ...#... ....... ...o... ..o#o.. .o.#.o. o#####o .o.#.o. ..o#o.. ...o... ....... .#####. .##..#. ..#..#. ....... .ooooo. o#####o o##..#o .o#..#o ..oooo. ``` **B.** Example of an island with multiple possible solutions: ``` ........ ....##.. ...####. ..###... .#####.. .#####.. ..##.... ........ ``` Possible outputs: ``` ....oo.. ...o##o. ..o####o .o###.o. o#####o. o#####o. .o##oo.. ..oo.... ....oo.. ...o##o. ..o####o .o###.o. o#####o. o#####o. .o##.o.. ..ooo... ....oo.. ...o##o. ..o####o .o###..o o#####.o o#####o. .o##oo.. ..oo.... ....oo.. ...o##o. ..o####o .o###..o o#####.o o#####o. .o##.o.. ..ooo... ``` **C.** [Large test case as a Gist](https://gist.github.com/dloscutoff/6bc4a16c1ee9b7932aef9c00ea99cd3e) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code in each language wins. [Answer] ## Mathematica (version 9), 165 bytes The nice, short `ConvexHullMesh` function that Greg Martin used was only introduced in Mathematica version 10, so I thought I'd make an attempt without it, using my ancient Mathematica version 9. I managed to get it slightly shorter, though! It's a function that takes and returns a list of strings (with `.`, `#` and `o` as the symbols). ``` ""<>#&/@("o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."})&[Characters@#/.{"."->0,"#"->1}]& ``` Explanation: * First, `Characters@# /. {"."->0, "#"->1}` turns the input into a matrix of `0`s and `1`s. * `"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#` then uses Mathematica's powerful (but extremely byte-heavy…) image processing capabilities to first fill in the island's [convex hull](https://en.wikipedia.org/wiki/Convex_hull) (which is the shape you'd get if you stretched a piece of string around it), and then take its boundary. We then multiply this matrix by the string `"o"` to get a matrix of `0`s and `"o"`s (thanks to Mathematica's impressive adaptability about types), and add this to `"#"` times the matrix of the island. * Finally, `""<>#& /@ (... /. {0->"."})` turns this matrix of `"o"`s, `"#"`s and `0`s into a matrix of `"o"`s, `"#"`s and `"."`s, and joins each row into a string. When we test this on example **B**, we get the output ``` {"....oo..", "...o##o.", "..o####o", ".o###..o", "o#####o.", "o#####o.", ".o##oo..", "..oo...."} ``` [Edit, thanks to Greg Martin:] If we're allowed to use arrays of characters instead of lists of strings, we can trim this down to 144 bytes: ``` "o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."}&[#/.{"."->0,"#"->1}]& ``` [Answer] (But go upvote [Notatree's solution](https://codegolf.stackexchange.com/a/113637/56178), it's better!) # Mathematica, 168 bytes ``` (x_~n~y_:=Min[Norm[x-#]&/@y];i=#;p=i~Position~#&;t=p["#"|"."]~Select~#&;(i~Part~##="o")&@@@t[#~n~t[ConvexHullMesh[Join[s=p@"#",#+{.1,.1}&/@s]]~RegionMember~#&]==1&];i)& ``` Pure function taking a 2D array of characters as input and returning a 2D array of characters. An easier-to-read version: ``` 1 (x_~n~y_ := Min[Norm[x - #] & /@ y]; 2 i = #; p = i~Position~# &; 3 t = p["#" | "."]~Select~# &; 4 (i~Part~## = "o") & @@@ 5 t[#~n~ 6 t[ConvexHullMesh[ 7 Join[s = p@"#", # + {.1, .1} & /@ s]] 8 ~RegionMember~# &] == 1 &]; 9 i) & ``` Line 1 defines a function `n` that produces the (smallest) distance between a point `x` in the plane and a set `y` of other points. Line 2 initializes the variable `i` to the input, both to resolve a currying ambiguity later and to be able to modify it to produce the eventual output; line 2 also defines a function `p` that returns the coordinates of all occurrences of its input in `i`. On line 3, `p["#" | "."]` represents every single coordinate from the input map (since all its characters are either `"#"` or `"."`), so `t` is a function that selects only those coordinates that satisfy a yet-unspecified property. On line 4, `i~Part~## = "o"` is going to change a bunch of entries of `i` to the character `"o"`; those characters will be selected from the set of possible coordinates according to the stuff on lines 5-8. And line 9 just returns the answer once it's computed. Okay, infrastructure done, now to the actual computation. `ConvexHullMesh` is Mathematica's built-in for computing the convex hull of a set of points (the smallest convex polygon containing those points). Morally speaking, this should "fill in" the coves and fjords of the island (which is `s = p@"#"`), to rule them out of our cicrumnavigation. There's a little problem with `ConvexHullMesh` when that set of points is all in a line (thank you, test case #2), which we resolve by appending a slightly offset version of `s` to itself in line 7. This output is a polygon, so lines 7-9 (`t[...~RegionMember~# &]`) produces a list of the points with integer coordinates in that polygon. Finally, line 5 and the end of line 9 calculate all points that are at a distance exactly 1 (hence not 0) from this set of integer points; that set becomes the circumnavigating path. Below is the output for the large test case at the OP's link. Notice at the upper left, the unusual choices of when to go west versus southwest hint at the fact that it's shadowing an invisible line of slope -2/3 between two peninsulas (said line segment being part of the convex hull's boundary). ``` ........................ .............o.......... ...........oo#ooooooo... ..........o#.#.##...#o.. ........oo.#.#.###.##o.. .......o..########.##o.. .....oo...############o. ...oo#....############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#.....###....#oooo..... .oooooo#ooooooo......... .......o................ ``` [Answer] # Python 3, 779 bytes (indenting with tabs) This is the whole program. It reads input from stdin and prints it to stdout. Stdin must end with EOF. Example run with the big input: <https://ideone.com/XIfYY0> ``` import itertools,sys L=list C=itertools.count d=L(map(L,filter(None,sys.stdin.read().split('\n')))) X=len(d[0]) Y=len(d) R=range def P(r):return all(d[y][x]=='.'for x,y in r) def S(f): for n in C(0): if P(f(n)):l=n else:break for n in C(l+1): if P(f(n)):return l,n def f(V,a,*b):return L(eval('lambda '+a+':('+i+')',V)for i in b) V=locals() def D(n): y=min(n,Y-1);x=n-y while y>=0and x<X:yield(x,y);x+=1;y-=1 def E(n): x=max(0,n-Y);y=x+Y-n while y<Y and x<X:yield(x,y);x+=1;y+=1 F=f(V,'p','(p,y)for y in R(0,Y)','(x,p)for x in R(0,X)')+[D,E] r=f(V,'x,y','x','y','x+y','x-y+Y') B=L(map(S,F)) for x in R(0,X): for y in R(0,Y): z=L(zip(r,B)) if all(g(x,y)in R(a,b+1)for g,(a,b)in z)and any(g(x,y)in e for g,e in z):d[y][x]='o' print('\n'.join(''.join(x)for x in d)) ``` The idea is simple: it computes smallest octagonal bounds, and draws cells which are inside all of the computed bounds and intersect at least one of the edges. [Answer] ## JavaScript (ES6), ~~369~~ 343 bytes ``` f=s=>(a=s.split` `.map(s=>[...s]),m=Array(8),a.map((b,i)=>b.map((c,j)=>c>'#'||[i-j,i,j+i,j,j-i,-i,-i-j,-j].map((d,k)=>d>m[k]||(m[k]=d-1)))),[o,p,q,r,t,u,v,w]=m,g=(i,j,k,l,...p)=>i-k|j-l?a[i][j]=g(i+(k>i)-(k<i),j+(l>j)-(l<j),k,l,...p):1/p[0]?g(k,l,...p):'o',g(p,p-o,p,q-p,q-r,r,r-t,r,-u,t-u,-u,u-v,w-v,-w,o-w,-w,p,p-o),a.map(b=>b.join``).join` `) ``` Explanation: The string is split into a character array (I'm unclear as to whether character array input is acceptable). The array is then iterated over and the positions of all the land squares are located. The bounding lines given by the equations `x - y = o`, `x = p`, `x + y = q`, `y = r`, `y - x = t`, `-x = u`, `-x - y = v`, `-y = w` are determined such that the maximum possible parameter is chosen where all the land lies beyond the line. This has the effect of enclosing the island in an octagon. The coordinates of the corners of the octagon are readily calculated from the parameters and the cells on its edge are filled in. The array is then joined back into a string. The reason an octagon suffices is as follows: ``` /o# /o# /o# |/o # |/o # |/ o# *o### * o # * o# /|o # /|o # /| o# |o# |o# |o# ``` Consider a corner of the octagon. At some point along the two edges the path will be limited by the land because we constructed the octagon to touch the land as closely as possible. If there is no land at the corner itself, the path could take the alternate routes as shown on the right, but that is still the same number of orthogonal and diagonal steps, so the distance is unchanged. [Answer] # Python 3.5, ~~224, 263, 234~~ 218 bytes Golfed off another 16 bytes by getting rid of the nested function and making it a one-liner. ``` def h(s,k=0,i=0):w=s.find('\n')+1;x=s.find('X')-w;k=k or x;d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2;u=s[:k]+'o'+s[k+1:];return['X'>s[k]and i<8and(h(u,k+d[i+2],i+2)or h(u,k+d[i+1],i+1)or h(u,k+d[i],i))or'',s][s[k]>'X'and k==x] ``` Golfed off 29 bytes: ``` def f(s): w=s.find('\n')+1;x=s.find('X')-w;d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2 def h(s,k,i):u=s[:k]+'o'+s[k+1:];return['X'>s[k]and i<8and(h(u,k+d[i+2],i+2)or h(u,k+d[i+1],i+1)or h(u,k+d[i],i))or'',s][s[k]>'X'and k==x] return h(s,x,0) ``` Input is a single string using '~' for ocean, 'X' for land, and 'o' for the boundary. (Using 'X' saves a byte for '>' instead of '==') Less golfed version with comments: ``` def f(s): w=s.find('\n')+1 # width of one row x=s.find('X')-w # starting point d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2 # delta to add to current index to move in # the 8 directions: E, SE, S, SW, W, NW, # N, NE. Make it long to avoid # lots of modulo operations in # the recursive calls def h(s,k,i): # s is the island string, k the current # position, i the direction index if s[k]>'X'and k==x: # if back at the begining, return s # return the map elif 'X'>s[k] and i<8: # if there is water here, and haven't # looped around, u=s[:k]+'o'+s[k+1:] # make a new map with an 'o' in the # current spot r = h(u,k+d[i+2],i+2) # try a 90 degree right turn if r: return r r = h(u,k+d[i+1],i+1) # try a 45 degree turn if r: return r r= h(u,k+d[i],i) # try straight ahead if r: return r return '' # this path failed return h(s,x,0) ``` [Answer] # C# 7 - ~~414~~ ~~369~~ 327 bytes ***Edit***: switched to 1D looping, computing `i` and `j` on the fly ***Edit***: changed input method, collapsed lookup table, and switched to well defined initial bounds ...and removed the pointless space in the last outer for-loop ``` using C=System.Console;class P{static void Main(){var D=C.In.ReadToEnd().Replace("\r","");int W=D.IndexOf('\n')+1,H=D.Length,z=H,k,q,c;int P()=>z%W*(k%3-1)+z/W*(k/3-1)+H;var B=new int[9];for(;z-->0;)for(k=9;k-->0&D[z]%7<1;)if(B[k]<=P())B[k]=P()+1;for(;++z<H;C.Write(q>9?'o':D[z]))for(q=k=9;k-->0;)q*=(c=P()-B[k])>0?0:c<0?1:2;}} ``` [Try It Online](https://tio.run/nexus/cs-core#lZJdT4MwFIbv9ysIZNKOD0EvzFbKkjETTDQuarKLbRcEukmYRT6cyrLfPimD6TaIWm7enue87wltt2@JTxechR8/k5S8qFZIk3BJkLt0koQbrZPUSX2XW4W@x905PgVwvXJibogt9YaqD8TxnsJr6gGY69el4xLAT2Ne5nmIfJpyYzzM@zzycT8H4pSKUNJlO6/dErpIn@UM23IgR7JbNI8AxGbWHndA0L5UdChl50yfF9pGbO4AU/LO5c2T7gzNwxigTFFMDUGmA9xFAdueDSfZrH1l6Aj6czCYBDMD5@GQKSYkfeeVpMywkaWOYz8lIDK7fTEUe8wMi8AI7yMRjDoYuMytsBhoan2t5xpaX@9doM1mu1UbVutvQKgHAvuEkp@CEv4AQrkaQQFLINSDKvmAtFjnUfEb1NR3UTX1esf@z@uB0OQQGof/x7EDJ9PVynFMKlAd7eEVtk4v9ZfH8AU) Complete program, takes input to standard in, prints it to standard out, uses `#`, `.`, and `o`. For each cell, it computes a 'profile' (which is the distance over 8 directions (it appears to compute a ninth for convenience, but this is always `0`), and records a maximum of each of these. It then writes out the whole map again, and replaces any cell which is both on a boundary and not outside any with a 'o'. The commented code below explains how it all works. As per my answer to [Save the Geese from Extinction](https://codegolf.stackexchange.com/questions/50829/save-the-geese-from-extinction), this produces the smallest octagon (valid circumnavigation with largest area) which bounds the island. ***Note***: that for once in my life I'm using something from the current decade, and this code requires C# 7 to compile. If you do not have C# 7, there is one line that will need to be replaced, which is clearly marked in the code. Example usage and output: ``` type t7.txt | IslandGolf1.exe .........ooooooooooo.... ........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...... ..ooooooooooooooo....... ``` Formatted and commented code: ``` using C=System.Console; class P { static void Main() { // \n 10 // # 35 // . 46 // o 111 var D=C.In.ReadToEnd().Replace("\r",""); // map int W=D.IndexOf('\n')+1, // width H=D.Length, // length z=H, // position in map (decomposed into i and j by and for P) k, // bound index q, // bound distance, and later cell condition (0 -> outside, 8 -> inside, >8 -> on boudary) c; // (free), comparison store // 'indexes' into a profile for the point z at index k // effectively {i=z%W,j=z/W,-i,-j,i+j,j-i,-i-j,i-j,0}[k] (inside order is a bit different) (0 const is always treated as 'inside bounds') // each non-zero-const entry describes the distance in one of the 8 directions: we want to maximise these to find the 'outer bounds' // the non-zero-const bounds describe 8 lines, together an octogen int P()=>z%W*(k%3-1)+z/W*(k/3-1)+H; // new C#7 local method syntax (if you don't have C#7, you can test this code with the line below instead) //k=0;System.Func<int>P=()=>z%W*(k%3-1)+z/W*(k/3-1)+H; // old lambda syntax (must pre-assign k to make static checker happy) var B=new int[9]; // our current bounds, each is initially null (must only call P() when on a #) // B[k] starts off a 0, P() has a +H term, and W+(H/W)<H for W >= 3, so B[k] is assigned the first time we compare it (H-i-j always > 0) for(;z-->0;) // for each cell for(k=9;k-->0& // for each bound D[z]%7<1;) // if this cell is # if(B[k]<=P())B[k]=P()+1; // update bound if necessary (add one so that we define the bound _outside_ the hashes) // z=-1 for(;++z<H; // for each cell C.Write(q>9?'o':D[z])) // print the cell (if q > 9, then we are on the bounds, otherwise, spit out whatever we were before) // check we are not 'outside' any of the bounds, and that we are 'on' atleast one of them for(q=k=9;k-->0;) // for each bound q*=(c=P()-B[k])>0?0: // outside bound (q=0) (??0 is cheaper than (int) or .Value) c<0?1: // inside (preserve q) 2; // on bound (if q != 0, then q becomes > 9) } } ``` ]
[Question] [ Consider the following process: 1. Take some non-negative integer N. e.g. N = `571` 2. Express it in binary with no leading zeroes. (Zero itself is the only exception, becoming `0`.) e.g. `571` = `1000111011` in binary 3. Break apart consecutive runs of ones and zeroes in this binary representation. e.g. `1000111011` → `1`, `000`, `111`, `0`, `11` 4. Sort the runs from longest to shortest. e.g. `1`, `000`, `111`, `0`, `11` → `000`, `111`, `11`, `1`, `0` 5. Overwrite all the digits in each run with alternating `1`'s and `0`'s, always starting with `1`'s. e.g. `000`, `111`, `11`, `1`, `0` → `111`, `000`, `11`, `0`, `1` 6. Concatenate the result to get a new binary number. e.g. `111`, `000`, `11`, `0`, `1` → `1110001101` = `909` in decimal When you plot the values produced by this process you get a pretty neat graph: [![Temple Skyline plot to 1024](https://i.stack.imgur.com/jqSBf.png)](https://i.stack.imgur.com/jqSBf.png) And it's hopefully apparent why I'm calling the resulting sequence the *Temple Skyline sequence*: [![Temple Skyline](https://i.stack.imgur.com/UEYRN.png)](https://i.stack.imgur.com/UEYRN.png) # Challenge Write a program or function that takes in a non-negative integer N and prints or returns the corresponding Temple Skyline sequence number. Your input and output should both be in decimal. e.g. If the input is `571` the output should be `909`. **The shortest code in bytes wins.** For reference, here are the terms in the sequence from N = 0 to 20: ``` 0 1 1 1 2 2 3 3 4 6 5 5 6 6 7 7 8 14 9 13 10 10 11 13 12 12 13 13 14 14 15 15 16 30 17 29 18 26 19 25 20 26 ``` [Here are the terms from 0 to 1023.](http://pastebin.com/raw.php?i=h8aHLkUQ) [Answer] # CJam, ~~25~~ ~~23~~ 22 bytes ``` ri1e>2be`z($W%a\+ze~2b ``` Just a bit of run-length encoding. -1 thanks to @MartinBüttner. [Try it online](http://cjam.aditsu.net/#code=ri1e%3E2be%60z%28%24W%25a%5C%2Bze~2b&input=571) / [Test suite](http://cjam.aditsu.net/#code=100%20%7B_oSo%20i1e%3E2be%60z%28%24W%25a%5C%2Bze~2b%20p%7D%2F). ### Explanation ``` ri Read n from input as int 1e> Take max with 1 (special case for n = 0) 2b Convert n to binary e` Run length encode z Zip, giving a pair [<counts> <10101.. array>] ($W% Drop the counts array and sort decending a\+z Add it back to the 10101.. array and re-zip e~ Run length decode 2b Convert from binary ``` [Answer] # Pyth - ~~21~~ 20 bytes *Thanks to @sok for saving me one byte!* ``` is.em%hk2hb_Sr.BQ8 2 ``` [Try it here online](http://pyth.herokuapp.com/?code=is.em%25hk2hb_Sr.BQ8+2&input=571&debug=0). [Answer] # Python 2, 121 bytes ~~125~~ 121: Thanks to Sp3000 for shaving off 4 bytes! ``` import re;print int("".join(n*`~i%2`for i,n in enumerate(sorted(map(len,re.split('(1*|0+)',bin(input())[2:])))[::-1])),2) ``` 125 ``` import re;print int("".join("10"[i%2]*n for i,n in enumerate(sorted(map(len,re.split('(1*|0+)',bin(input())[2:])))[::-1])),2) ``` [Answer] # JavaScript ES6, 110 bytes ~~113~~ ~~116~~ ~~119~~ ~~120~~ *Saved 3 bytes thanks to @intrepidcoder* *Saved 3 bytes thanks to @NinjaBearMonkey* ``` n=>+('0b'+n.toString(2).split(/(0+)/).sort((b,a)=>a.length-b.length).map((l,i)=>l.replace(/./g,i-1&1)).join``) ``` Straight forward approach. Don't like the length of the sort function but I can't think of a way to golf it. [Answer] # C++, ~~535~~ 527 Bytes (thanks zereges for shaving off some bytes.) Now that we got rid of those bytes the program is now competetive ;) ``` #include<iostream> #include<cmath> int main(){int I,D;std::cin>>I;while(I>int(pow(2,D))){D++;}int L[99];int X=0;int Z=0;int O=0;for(int i=D-1;i>=0;i--){if( int(pow(2,i))&I){if(Z>0){L[X]=Z;Z=0; X++;}O++;}else{if(O>0){L[X] = O;O=0;X++;}Z++;}}if(Z>0){L[X]=Z;Z=0;X++;}if(O>0){L[X]=O;O=0;X++;}int P=0;bool B = true;int W = D-1;for(int j=0;j<X;j++){int K=0;int mX=0;for(int i=0;i<X;i++){if(L[i]>K){K=L[i];mX=i;}}L[mX]=0;if(B){for(int k=0;k<K;k++){P+=int(pow(2,W));W--;}}else{for(int k=0;k<K;k++){W--;}}B^=1;}std::cout<<P;return 0;} ``` I'm new to golfing, so **please give me some tips in the comments**. Things like "you don't need those brackets" or "use printf" are all helpful, but I also appreciate advice on the logic. Thanks in advance! For ease of reading, I present the ungolfed version: ``` #include<iostream> #include<cmath> int main() { int input,digits; std::cin>>input; while(input > int(pow(2,digits))){digits++;} int list[99]; int index=0; int zCounter=0; int oCounter=0; for(int i=digits;i>0;i--) { if( int(pow(2,i-1))&input) { if(zCounter>0) { list[index] = zCounter; zCounter=0; index++; } oCounter++; } else { if(oCounter>0) { list[index] = oCounter; oCounter=0; index++; } zCounter++; } } if(zCounter>0) { list[index] = zCounter; zCounter=0; index++; } if(oCounter>0) { list[index] = oCounter; oCounter=0; index++; } int output = 0; bool ones = true; int power = digits-1; for(int j=0;j<index;j++) { int max=0; int mIndex=0; for(int i=0;i<index;i++) { if(list[i]>max){max=list[i];mIndex=i;} } list[mIndex]=0; if(ones) { for(int k=0;k<max;k++) { output+=int(pow(2,power)); power--; } } else { for(int k=0;k<max;k++) { power--; } } ones^=1; } std::cout<<output; return 0; } ``` **EDIT** golfed version brought down a couple bytes, ungolfed version unchanged [Answer] # Pyth, ~~20~~ 19 bytes ``` ACr.BQ8|is*V_SGH2 1 ``` *1 byte saved by Jakube* [Test Suite](https://pyth.herokuapp.com/?code=ACr.BQ8%7Cis%2aV_SGH2+1&test_suite=1&test_suite_input=571%0A20%0A1%0A0&debug=0) Uses the fact that after run-length-encoding, the runs are the desired runs in the output. Lost 3 bytes special casing 0. [Answer] # Perl 5.10, 121 101 ``` say oct"0b".join'',map{$|=1-$|;$_=~s/./$|/gr}sort{length$b<=>length$a}(sprintf"%b",shift)=~/(0*|1*)/g ``` I think the sort part can be shorter. Edit: -20 bytes, thanks to symbabque! [Answer] # Haskell, ~~132~~ 131 bytes ``` import Data.List g 0=[] g n=mod n 2:g(div n 2) q=[1]:[0]:q f=foldl((+).(2*))0.concat.zipWith(<*)q.sortOn((-)0.length).group.g.max 1 ``` Usage example: ``` > map f [0..20] [1,1,2,3,6,5,6,7,14,13,10,13,12,13,14,15,30,29,26,25,26] ``` How it works: ``` max 1 -- fix n=0: f(0) is the same as f(1) g -- turn into binary, i.e. list of 0s and 1s group -- group sequences of equal elements sortOn((-)0.length) -- sort groups on negative length zipWith(<*)q -- map each element in a group to constant 1 or 0 by turns concat -- flatten all groups into a single list foldl((+).(2*))0 -- convert back to decimal ``` [Answer] # J - 30 bytes Function taking integer on right. Correctly handles 0. ``` (\:~#2|#\)@(#;.1~1,2~:/\])&.#: ``` * `#:` - Take the binary representation. * `1,2~:/\]` - Between each digit, report *True* if they are different. Prepend a *True* so that the list has *True* at the start of each "run". * `(#;.1~...)` - Using the boolean vector above, take the length of each run. * `\:~` - Sort these lengths from longest to shortest. * `2|#\` - Take a list of alternating `1 0 1 0 ...` as long as the list of lengths. * `(...#...)` - For each number on the left (sorted lengths), take as many of the corresponding item on the right (alternating 1's and 0's) * `&.` - Convert this new binary representation back to a number. Examples: ``` (\:~#2|#\)@(#;.1~1,2~:/\])&.#: 571 909 i.21 NB. zero to twenty 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 (\:~#2|#\)@(#;.1~1,2~:/\])&.#: every i.21 NB. apply separately to every number 1 1 2 3 6 5 6 7 14 13 10 13 12 13 14 15 30 29 26 25 26 ``` [Answer] # Python 3, ~~146~~ 136 bytes ``` import re;print(int(''.join(len(j)*'01'[i%2<1]for i,j in enumerate(sorted(re.findall('1+|0+',bin(int(input()))[2:]),key=len)[::-1])),2)) ``` [Answer] # Mathematica, 83 bytes ``` Flatten[0#+(d=1-d)&/@SortBy[d=0;Split[#~IntegerDigits~2],-Length@#&]]~FromDigits~2& ``` This defines an unnamed function. [Answer] # Ruby, ~~107~~ ~~104~~ 102 bytes (saved 3 bytes thanks to **nimi**) Not going to beat the likes of CJam, but I got it pretty small for a sane language. ``` p gets.to_i.to_s(2).scan(/((.)\2*)/).map{|e|e[i=0].size}.sort.reverse.map{|e|"#{i=1-i}"*e}.join.to_i 2 ``` [Answer] ## Java 8, ~~179~~ 176 bytes ``` (x)->{int g[]=new int[32],h=0,i=highestOneBit(x);g[0]=1;while(i>1)g[((x&i)>0)^((x&(i>>=1))>0)?++h:h]++;sort(g);for(i=32,h=0;g[--i]>0;)while(g[i]-->0)h=h<<1|i%2;return x<1?1:h;} ``` I used two static imports: `java.util.Integer.highestOneBit` and `java.util.Arrays.sort`. For readability, here's the code ungolfed: ``` java.util.function.ToIntFunction<Integer> f = (x) -> { int g[] = new int[32], h = 0, i = java.util.Integer.highestOneBit(x); g[0] = 1; while (i > 1) { g[((x & i) > 0) ^ ((x & (i >>= 1)) > 0) ? ++h : h]++; } java.util.Arrays.sort(g); for (i = 32, h = 0; g[--i] > 0;) { while (g[i]-- > 0) { h = h << 1 | i % 2; } } return x < 1 ? 1 : h; // handle zero }; ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ḋ`Ṙݬ↔OmLgḋ ``` [Try it online!](https://tio.run/##yygtzv7//@GO7oSHO2cc2XBozaO2Kf65PulAkf///5uaGwIA "Husk – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` BŒgLÞṚJḂṁ"ƊFḄ ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//QsWSZ0zDnuG5mkrhuILhuYEixopG4biE////NTcx "Jelly – Try It Online") ## How it works ``` BŒgLÞṚJḂṁ"ƊFḄ - Main link. Takes n on the left B - Convert to binary Œg - Group adjacent equal elements; Call this l Þ - Sort by... L - length Ṛ - Reverse, to put the longest first Ɗ - Run the previous 3 commands over the sortedt list J - Yield [1, 2, ..., len(l)] Ḃ - Bit; [1, 0, 1, 0, ..., len(l)%2] " - Zip with l and do the following over each pair ṁ - Mould 1 or 0 to each element of l F - Flatten Ḅ - Convert from binary ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¤ò¦ ñÊÔËîEvÃ¬Í ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pPKmIPHK1MvuRXbDrM0&input=NTcx) ``` ¤ò¦ ñÊÔËîEvÃ¬Í :Implicit input of integer ¤ :To binary string ò :Partition on ¦ :Inequality ñ :Sort by Ê :Length Ô :Reverse Ë :Map each D at 0-based index E î : Fill D with Ev : Parity of E à :End map ¬ :Join Í :To decimal ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~32~~ 30 bytes ``` ⊥{⍵/(≢⍵)⍴⊤2}⊃¨∨{⍴¨⍵⊂⍨1,2≠/⍵}⊤⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jrqXVj3q36ms86lwEpDUf9W551LXEqPZRV/OhFY86VgAltwAZvVsfdTU96l1hqGP0qHOBPpAPVLHkUd9UkCn/07hMzQ0B "APL (Dyalog Extended) – Try It Online") -2 bytes for full program. ## Explanation ``` ⊥{⍵/(≢⍵)⍴⊤2}⊃¨∨{⍴¨⍵⊂⍨1,2≠/⍵}⊤⎕ ⊤⎕ convert input to binary 2≠/⍵ inequality of overlapping pairs 1, prepend 1 ⍵⊂⍨ partition bits on that ⍴¨ get length of each part ∨ sort in descending order ⊃¨ unenclose each ⊤2 array [1,0] (≢⍵)⍴ reshape to ⍵'s length ⍵/ filter ⍵ by that(every other element) ⊥ convert that back to binary ``` ]
[Question] [ Inspired by [this video of *Infinite Series*](https://www.youtube.com/watch?v=ineO1tIyPfM). ### Introduction Pi is defined as the ratio of the circumference to the diameter of a circle. But how is a circle defined? Usually a circle is defined as the points with constant distance to the centerpoint (let us assume that the center is at `(0,0)`). The next question would be: How do we define the *distance*? In the following we are considering different notions of distances (induced by the `Lp`-norms): Given a norm (=something that measures a *length*) we can easily construct a *distance* (=distance between two points) as follows: ``` dist(A,B) := norm (A-B) ``` The euclidean norm is given by: ``` norm((x,y)) = (x^2 + y^2)^(1/2) ``` This is also called the *L2-norm*. The other *Lp-norms* are constructed by replacing the `2` in the above formula by other values between 1 and infinity: ``` norm_p((x,y)) = (|x|^p + |y|^p)^(1/p) ``` The unit circles for those different norms have quite distinct shapes: ![](https://upload.wikimedia.org/wikipedia/commons/d/d4/Vector-p-Norms_qtl1.svg) ### Challenge Given a `p >= 1`, calculate the ratio of circumference to diameter of a *Lp-circle* with respect to the `Lp`-norm with an accuracy of four significant figures. ### Testcases We can use that for `p,q` with `1 = 1/p + 1/q` we get the same ratio for the `Lp` as well as the `Lq` norm. Furthermore for `p = q = 2` the ratio is minimal, and for `p = 1, q = infinity` we get a ratio of 4, so the ratios are always between `pi` and `4`. ``` p or q ratio 1 infinity 4 2 2 3.141592 1.623 2.60513 3.200 1.5 3 3.25976 4 1.33333 3.39693 ``` [Answer] # Python + scipy, 92 bytes ``` from scipy.integrate import* lambda p:2/p*quad(lambda x:(x/x**p+(1-x)**(1-p))**(1/p),0,1)[0] ``` Formula is from [this math.SE question](https://math.stackexchange.com/questions/254620/pi-in-arbitrary-metric-spaces). [Answer] # [MATL](https://github.com/lmendo/MATL), 31 bytes ``` 0:1e-3:1lyG^-lG/^v!d|G^!slG/^sE ``` [Try it online!](https://tio.run/nexus/matl#@29gZZiqa2xlmFPpHqeb464fV6aYUuMep1gMYhe7/v9vqGcKAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S4jwrvhvYGWYqmtsZZhT6R2nm@OtH1emmFLjHadYDGIXu/53CflvyGXEZahnZmQMJE25TAA). ### Explanation This generates the *x*,*y* coordinates of one quarter of the unit circle sampled at 1001 points with step 0.001 in *x*. The length of the quarter of circle is approximated by that of the polygonal line that passes through those points; that is, the sum of the lengths of the 1000 segments. Length is of course computed according to `p`-norm. Multiplying the result by 2 gives the approximate lenght of half a circle, that is, pi. ``` 0:1e-3:1 % Push [0 0.001 0.002 ... 0.999 1]. These are the x coordinates of % the vertices of the polygonal line that will approximate a quarter % of the unit circle l % Push 1 y % Duplicate [0 0.001 0.002 ... 0.999 1] onto the top of the stack. G % Push input, p ^ % Element-wise power: gives [0^p 0.001^p ... 1^p] - % Element-wise subtract from 1: gives [1-0^p 1-0.001^p ... 1-1^p] lG/ % Push 1, push p, divide: gives 1/p ^ % Element-wise power: gives [(1-0^p)^(1/p) (1-0.001^p)^(1/p) ... % ... (1-1^p)^(1/p)]. These are the y coordinates of the vertices % of the polygonal line v % Concatenate vertically into a 2×1001 matrix. The first row contains % the x coordinates and the second row contains the y coordinates ! % Transpose d| % Compute consecutive differences down each column. This gives a % 1000×2 matrix with the x and y increments of each segment. These % increments will be referred to as Δx, Δy G % Push p ^ % Element-wise power ! % Transpose s % Sum of each column. This gives a 1×1000 vector containing % (Δx)^p+(Δy)^p for each segment lG/ % Push 1/p ^ % Element-wise power. This gives a 1×1000 vector containing % ((Δx)^p+(Δy)^p)^(1/p) for each segment, that is, the length of % each segment according to p-norm s % Sum the lenghts of all segments. This approximates the length of % a quarter of the unit circle E % Multiply by 2. This gives the length of half unit circle, that is, % pi. Implicitly display ``` [Answer] # Wolfram Language (Mathematica), ~~49~~ ~~46~~ 45 bytes *3 bytes saved thanks to [alephalpha](https://codegolf.stackexchange.com/u/9288).* *1 byte saved thanks to [att](https://codegolf.stackexchange.com/u/81203).* ``` \!\(2N@∫\_0\%1\@+++(a^-#-1)^(1-#)\%#a\)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P0YxRsPIz@FRx@qYeIMYVcMYB21tbY3EOF1lXUPNOA1DXWXNGFXl93N7EmM01f4HlmamljgEFGXmlUQr69qlOSjHqtUFJyfm1VVzGepwGelwGeqZGRmDKFMdLhOu2v8A "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a number as input and returns a number as output. The Unicode characters are U+222B for `\[Integral]` and U+F74C for `\[DifferentialD]`. [Answer] ## PARI/GP, ~~48~~ 43 bytes It's easy after @orlp has found the formula, and @alephalpha's version saves 5 bytes: ``` p->2*intnum(u=0,1,(1+(u^-p-1)^(1-p))^(1/p)) ``` To add something slightly useful, let's calculate the `p` for which we get `3.2`: ``` ? f=p->2*intnum(u=0,1,(1+(u^-p-1)^(1-p))^(1/p)); ? solve(p=1,2,f(p)-3.2) %2 = 1.623002382384469009676324702 ``` ### Correct usage While the code gives results that are much more exact than the challenge demands, it can easily be improved a lot: if we replace the upper integration limit `1` with `[1,1/p-1]` (giving what the manual calls the singularity exponent) then all shown digits of `f(2)` agree with `Pi`. This is still true if we increase the precision to 100 (type `\p100`). However, after that change the `solve` computation no longer worked. I changed the inner term to explicitely handle the case `u=0` and also changed to a different computer with a newer PARI version and 64 bit (which implies a higher default precision). Here is the improved calculation of the `p` value for `Pi=3.2`, and let's also have a look at the real Pi: ``` ? f=p->2*intnum(u=0,[1,1/p-1],if(u,(1+(u^-p-1)^(1-p))^(1/p),0)); ? f(2) %2 = 3.1415926535897932384626433832795028842 ? Pi %3 = 3.1415926535897932384626433832795028842 ? solve(p=1,2,f(p)-3.2) %4 = 1.6230023823844690096763253745604419761 ``` [Answer] # [Desmos](https://desmos.com/calculator), 42 bytes ``` f(p)=2∫_0^1(x/x^p+(1-x)^{1-p})^{1/p}dx/p ``` Port of [orlp's integration formula](https://codegolf.stackexchange.com/a/106036/68261). Yay for integration built-in! [Try it on Desmos!](https://www.desmos.com/calculator/g5capgcp0h) [Answer] ## JavaScript (ES7), 80 bytes Based on [orlp's answer](https://codegolf.stackexchange.com/a/106036/58563). This JS implementation is quite slow. You may want to try `i=1e-7` (or even higher) for a faster approximation. *Note*: This is basically intended for Chrome and Edge only. An equivalent ES6 version using `Math.pow()` on Firefox 50.1 seems to be *much* slower. *Edit*: According to Neil, this should also work fine on Firefox 52. ``` f= p=>{for(i=5e-8,s=x=0;(x+=i)<1;)s+=i*(x**(1-p)+(1-x)**(1-p))**(1/p);return 2/p*s} console.log(f(1).toFixed(3)) console.log(f(2).toFixed(3)) console.log(f(1.623).toFixed(3)) ``` ]
[Question] [ [*The contest is over!*](http://goo.gl/hYcjpq) # Intro This is an interactive [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") contest where the controller is fully contained in a Stack Snippet at the bottom of the question. The controller automatically reads the answers and plays through games. Anyone can run it at any time right in their browser. The mechanics of this contest are very similar to those of [Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/q/48353). Except the game being played, while still grid based, is entirely different. Each game is 1 vs. 1 and there are no teams. Each entry is fighting for itself and only one will be the final champion. The controller uses JavaScript, and as JavaScript is the only client-side scripting language most browsers support, **all answers must be written in JavaScript too**. In this spec, *italicized text* is used to indicate the formal term for a game mechanic or property. These terms are used throughout to help maintain a cohesive and clear way of referring to the different parts of the game. # Gameplay ### Basics Every answer to this question represents a *player*. A *game* is a competition between two players, *P1* and *P2*. Each player controls a *flock* of 8 *bots*, numbered 0 through 7. Games takes place in the *grid*, a 128×64 *cell* arena whose bottom 8 rows start out as *walls* (the 'blocks') and other rows start as *air*. Cells outside the grid bounds are considered air. The grid's x coordinate ranges from 0 on the left to 127 on the right, and y ranges from 0 at the top to 63 at the bottom. Sample starting grid: [![](https://i.stack.imgur.com/WD2Ru.png)](https://i.stack.imgur.com/WD2Ru.png) Bots always stay aligned to the grid cells and multiple bots may occupy the same cell. Bots can only occupy air cells. P1's bots always start in a line 0-7 at the very left of the row above the walls and P2's bots always start in a line 7-0 at the very right. The *neighbors* of a bot or cell are the 8 cells directly orthogonal and diagonal to it. The field of view (*FOV*) of a bot is the 13×13 cell square centered on a bot. A cell or enemy bot is said to be in a player's FOV if it is in the FOV of at least one of the player's bots. ### Moves & Actions During a game, each player gets to *move* 1000 times. P1 moves first, then P2, then P1 and so on until 2000 total moves have been made, at which point the game ends. During a move, each player receives information about the game state and the grid cells and enemy bots in their FOV, and uses it to decide on an *action* for each of their bots to take. The default action is *do nothing*, where the bot does not move or interact with the grid. The other actions are *move*, *grab*, and *place*: * A bot can **move** to one of its neighboring cells C if: + C is not out of bounds, + C is air (i.e. not a wall), + and at least one of C's neighbors is a wall.If successful, the bot will move to C. * A bot can **grab** one of its neighboring cells C if: + C is not out of bounds, + C is a wall, + and the bot is not already carrying a wall.If successful, C will become air and the bot will now be carrying a wall. * A bot can **place** to one of its neighboring cells C if: + C is not out of bounds, + C is air, + no bots of either player occupy C, + and the bot is carrying a wall.If successful, C will become a wall and the bot will no longer be carrying a wall. **Unsuccessful actions result in a do nothing.** A cell occupied by at least one wall-carrying bot has a small wall-colored square drawn over it. Bots start without walls. ### Memory During a move, a player can access and change their *memory*, an initially empty string that lasts throughout the game and can be used to store strategic data. ### Goal The cell in the yellow crosshair is the *goal*, which starts in a random position. Each player has a *score* that starts at 0. When a player's bot moves to the goal, that player's score increases by 1 and the goal is randomly repositioned before the next turn. The player with the highest score at the end of a game wins. It's a tie if the scores are equal. If multiple bots move to the goal during a move, the player still only gets one point. If the goal has been in the same place for 500 moves, it is randomly repositioned again. Any time the goal is randomly positioned, it is guaranteed to not be placed on a cell occupied by a bot. # What to Program Write a **body** for this function: ``` function myMove(p1, id, eid, move, goal, grid, bots, ebots, getMem, setMem) { //body goes here } ``` It will be called once every time your player moves and needs to return the actions you want each of your bots to take during that move. You can use the [Baseline](https://codegolf.stackexchange.com/a/50691) code as a starting point. ### Parameters > > * `p1` is a bool that's `true` if you are P1 and `false` if you are P2 > * `id` is an integer that is the answer ID of your answer. > + You can find the ID of an answer by clicking the 'share' link below it and looking for the number right after `a/` in the URL. > + The ID of the Test Entry is -1. > * `eid` is an integer that is the answer ID of your enemy's answer. > * `move` is an integer from 1 to 1000 that says what move you are on. > * `goal` is an object with `x` and `y` properties. These are the goal's coordinates. They are given even if the goal is out of your FOV. > * `grid` is a function that takes in x and y arguments, e.g. `grid(x,y)`. It returns: > + `-1` for 'unknown' if the arguments aren't two integers or if `x,y` is not in your FOV. > + `0` for 'air' if `x,y` is out of bounds or if the cell at `x,y` is air. > + `1` for 'wall' if the cell at `x,y` is a wall. > * `bots` is an array of your 8 bots. Its elements are objects with properties `x`, `y`, and `hasWall`: > > > + `x` and `y` are the bot's coordinates. > + `hasWall` is `true` if the bot is carrying a wall and `false` if not.`bots` is always ordered normally, the Nth index corresponds to bot number N. > * `ebots` is an array of objects with `x`, `y`, and `hasWall` properties just like `bots`. Only the enemy bots in your FOV are in `ebots`. So it would have length 0 if if there are no enemy bots in your FOV. It is ordered randomly. > * `getMem` is a function with no arguments that returns your memory. > * `setMem` is a function that takes one argument M. If M is a string of 256 characters or less, your memory is updated to M, otherwise nothing happens. > > > The browser `console` object is available for the Test Entry alone. ### Return Value Your function needs to return an array of exactly 8 integers, each ranging from 0 to 24. The value at index N is the action that bot number N will take. All your bots will do nothing if your function: * Throws an error of any kind. (*error*) * Takes longer than **20 milliseconds** to execute. (*timeout*) * Doesn't return an array of 8 integers ranging from 0 to 24. (*malformed*) For convenience, the number of errors, timeouts, and malformed actions are displayed when a game ends. Each of the numbers from 0 to 24 corresponds to a particular bot action: * 0 is for doing nothing. * 1-8 are for moving. * 9-16 are for grabbing. * 17-24 are for placing. Each of the 8 values for moving, grabbing, and placing corresponds to one of the bot's neighboring cells, as shown here: ![](https://i.stack.imgur.com/9wpzY.png) So, for example, `15` is the action for grabbing the cell below the bot. Bot actions are handled in the order bot 0 to bot 7. For example, if during one move bot 0 is told to place a wall in the same air cell bot 1 was told to move to, the air cell will become a wall before bot 1's action is handled and bot 1 will be unsuccessful. Unsuccessful actions become do nothings and are said to have *failed*. Failed action counters are also displayed when the game ends. # Rules I may temporarily or permanently *disqualify* users or answers that don't follow these rules. Disqualified entries are not eligible to win. * **When declaring variables or functions, you must use the `var` keyword.** e.g. `var x = 10` or `var sum = function(a, b){ return a + b }` Things declared without `var` become global and could interfere with the controller. Steps have been taken so that this interference should be impossible, but do this to make sure. * **Your code shouldn't run slowly or waste time.** It's impossible to stop JavaScript functions mid-execution, so each player's code is run to completion. If your code takes a long time to run, everyone running your player will notice and be annoyed. Ideally, entries will always run well within the 20ms limit. * You must use code compatible with ECMAScript 5 in the latest version of Firefox as this is where I'll be running it. **Do not use features from ECMAScript 6** as it is not yet supported in many browsers. * You may answer **up to 3** times, but only if each of your strategies is considerably different. You can edit answers as much as desired. * You may not attempt to have any sort of memory except through the use of `getMem` and `setMem`. * You may not attempt to access or modify the controller, other player's code, or external resources. * You may not attempt to modify anything built into JavaScript. * Answers need not be deterministic. You may use `Math.random`. # Answer Format ``` #EntryName Notes, etc. <!-- language: lang-js --> //function body //probably on multiple lines More notes, etc. ``` The first multiline code block must contain your function body. The entry name is limited to 20 characters. Your entry will show up in the controller with the title `EntryName - Username [answer ID]`, plus `[DQ]` if it's disqualified. # Winning When the question has been up for at least 3 weeks and once answering has settled down, I will crown the champion. I'll use the controller's *autorun* feature. In an autorun round, every non-disqualified player plays two games with every other, one as P1, one as P2 (a double round-robin). I'll autorun as many rounds as I can in the period of a few hours. This will depend on how many submissions there are and how time intensive they are. But rest assured, I'm committed to getting an accurate final leaderboard. The player with the most wins is the champion and their answer will be accepted. I'll be using Firefox on a laptop with Windows 8.1 64-bit, 4 GB ram, and a 1.6GHz quad-core processor. ### Prize I will write and post a PPCG challenge specifically dedicated to the champion. It will somehow involve their username or avatar or something about them. I'll privately decide on what the challenge will be about when this contest is over. I'll write it to the best of my ability and try to make sure it becomes a Hot Network Question. # Controller Run this snippet or go to [this JSFiddle](http://jsfiddle.net/CalvinsHobbies/ave6ejyd/embedded/result) to use the controller. It starts with random players selected. I've only thoroughly tested it in Firefox and Chrome. ``` <style>html *{font-family:Consolas,Arial,sans-serif}canvas{margin:6px}button,input table,select{font-size:100%}textarea{font-family:monospace}input[type=text],textarea{padding:2px}textarea[readonly]{background-color:#eee}select{width:250pt;margin:3px 0}input[type=radio]{vertical-align:-.25em}input[type=checkbox]{vertical-align:-.15em}.c{margin:12px}.h{font-size:125%;font-weight:700}#main td{padding:12px;text-align:left}#main table{margin-left:auto;margin-right:auto}#main{text-align:center}#title{margin:12px;font-size:175%;font-weight:700;color:#333}#delay{text-align:right}#statsTable table{border-collapse:collapse}#statsTable td{border:1px solid gray;padding:3pt;font-family:monospace;text-align:center}#footnotes{margin:18px 0 0;font-size:75%}#arWrapper{border:2px solid red;background-color:#fff4f4}</style><div id=loadStatus>Loading entries...</div><div id=main><div id=title>Block Building Bot Flocks</div><div><span id=p1Title class=p1Color></span> vs. <span id=p2Title class=p2Color></span></div><canvas id=canvas>Canvas unsupported!</canvas><div><span id=p1Score class=p1Color>0</span> | <span id=moveCounter>0</span> | <span id=p2Score class=p2Color>0</span></div><div class=c><button id=runPause type=button onclick=runPause()>Run</button> <button id=moveOnce type=button onclick=moveOnce()>Move Once</button> <button type=button onclick=newGame()>New Game</button></div><div class=c><input id=delay size=4 value=20> ms delay <input id=showNumbers type=checkbox onclick=toggleNumbers()><label for=showNumbers>Show bot numbers</label>&nbsp;<input id=showLOS type=checkbox onclick=toggleLOS()><label for=showLOS>Show field of view</label></div><table><tr><td><div id=p1Header class="p1Color h">Player 1</div><div><select id=p1Select onchange=changeSelect(!0)></select></div><div><a id=p1Link href=javascript:;>Answer Link</a></div><td><div id=p2Header class="p2Color h">Player 2</div><div><select id=p2Select onchange=changeSelect(!1)></select></div><div><a id=p2Link href=javascript:;>Answer Link</a></div></table><div>Test Entry</div><div><textarea id=testEntry rows=8 cols=64>return [0,0,0,0,0,0,0,0]</textarea></div><div class=c><button type=button onclick=autorun()>Autorun N Rounds</button> N&nbsp;=&nbsp;<input id=N size=4 value=1> <input id=arTestEntry type=checkbox><label for=arTestEntry>Include Test Entry</label></div><div id=footnotes><input id=debug type=checkbox onclick=toggleDebug()><label for=debug>Console debug messages</label>&nbsp;| Scale: <input id=sc1 type=radio name=sc value=1><label for=sc1>Micro</label><input id=sc3 type=radio name=sc value=3><label for=sc3>Small</label><input id=sc6 type=radio name=sc value=6 checked><label for=sc6>Normal</label><input id=sc9 type=radio name=sc value=9><label for=sc9>Large</label>&nbsp;| Colors: <input id=normalCo type=radio name=co value=normal checked><label for=normalCo>Normal</label><input id=pastelCo type=radio name=co value=pastel><label for=pastelCo>Pastels</label><input id=neonCo type=radio name=co value=neon><label for=neonCo>Neon</label>&nbsp; <button type=button onclick=reload()>Reload</button><div id=invalidWrapper><br>No entry name/code found: <span id=invalid></span></div></div></div><div id=arWrapper><div id=arInfo class=c>Autorun in progress. Running game <span id=arProgress></span>.</div><div id=arResults><div class="c h">Autorun Results</div><div class=c>Players: <span id=arPlayers></span><br>Rounds: <span id=arRounds></span><br>Games per round: <span id=arGpR></span><br>Total games: <span id=arTotal></span><br></div><div class=c><strong>Leaderboard:</strong></div><div id=leaderboard class=c></div><div class=c>(W = wins, T = ties, L = losses, G = total goals, E = errors, I = timeouts, M = malformed actions, F = failed actions)</div><div class=c><strong>Player vs. Player Statistics:</strong></div><div id=statsTable class=c></div><div class=c>The top row has the ID's of P1.<br>The left column has the ID's of P2.<br>Every other cell not on the diagonal has the form "[P1 win count] [tie count] [P2 win count]".</div><div class=c><button type=button onclick=closeAutorun()>Close</button></div></div></div><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function setGlobals(e){G={},G.QID=50690,G.SITE="codegolf",G.DQ_ANSWERS=[],G.DQ_USERS=[],G.DEBUG=Q("#debug").is(":checked"),G.SHOW_NUMBERS=Q("#showNumbers").is(":checked"),G.SHOW_LOS=Q("#showLOS").is(":checked"),G.BOTS=8,G.LOS=6,G.W=128,G.H=64,G.SCALE=e?6:parseInt(Q('input[name="sc"]:checked').val()),G.CW=G.SCALE*G.W,G.CH=G.SCALE*G.H,G.TOTAL_MOVES=2e3,G.GOAL_LIFESPAN=500,G.MEM_MAX_LENGTH=256,G.TIME_LIMIT=20;var t=Q('input[name="co"]:checked').val();e||"normal"===t?G.COLORS={AIR:"#ccc",WALL:"#888",GOAL:"rgba(255,255,0,0.6)",BG:"#f7f7f7",P1:"#00f",P1_TEXT:"#008",P1_LOS:"rgba(0,0,255,0.1)",P2:"#f00",P2_TEXT:"#800",P2_LOS:"rgba(255,0,0,0.1)"}:"pastel"===t?G.COLORS={AIR:"#cef0ff",WALL:"#66cc66",GOAL:"rgba(0,0,0,0.3)",BG:"#fdfde6",P1:"#f4a034",P1_TEXT:"#a35f00",P1_LOS:"rgba(255,179,71,0.2)",P2:"#f67cf6",P2_TEXT:"#b408b4",P2_LOS:"rgba(249,128,249,0.2)"}:"neon"===t&&(G.COLORS={AIR:"#000",WALL:"#444",GOAL:"rgba(255,255,0,0.9)",BG:"#999",P1:"#0f0",P1_TEXT:"#5f5",P1_LOS:"rgba(255,128,0,0.15)",P2:"#f0f",P2_TEXT:"#f5f",P2_LOS:"rgba(0,255,255,0.15)"}),G.SCOREBOARD={P1SCORE:void 0,MOVE:void 0,P2SCORE:void 0},G.CTX=void 0,G.PLAYERS=void 0,G.GAME=void 0,G.TIMER=void 0,G.RUNNING=!1}function reload(){var e="undefined"==typeof G;e||stopTimer(),setGlobals(e);var t=Q("#canvas");t.width(G.CW).height(G.CH).prop({width:G.CW,height:G.CH}),G.CTX=t[0].getContext("2d"),G.CTX.font=(2*G.SCALE).toString()+"px Courier New",G.SCOREBOARD.P1SCORE=Q("#p1Score"),G.SCOREBOARD.MOVE=Q("#moveCounter"),G.SCOREBOARD.P2SCORE=Q("#p2Score"),Q("body").css("background-color",G.COLORS.BG),Q(".p1Color").css("color",G.COLORS.P1),Q(".p2Color").css("color",G.COLORS.P2),Q("#invalidWrapper").hide(),Q("#arWrapper").hide(),loadAnswers(G.SITE,G.QID,function(e){Q.isArray(e)?(Q("#loadStatus").remove(),loadPlayers(e),newGame()):Q("#loadStatus").text("Error loading entries - "+e)})}function maskedEval(e,t){var r={};for(i in this)r[i]=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=t[i]);return new Function("with(this) { "+e+";}").call(r)}function toKey(e,t){return G.W*t+e}function fromKey(e){return{x:e%G.W,y:Math.floor(e/G.W)}}function outOfBounds(e,t){return 0>e||e>=G.W||0>t||t>=G.H}function rnd(e){return Math.floor(Math.random()*e)}function isInt(e){return"number"==typeof e&&e%1===0}function isString(e){return"string"==typeof e||e instanceof String}function decode(e){return Q("<textarea>").html(e).text()}function shuffle(e){for(var t,r,o=e.length;o;t=rnd(o),r=e[--o],e[o]=e[t],e[t]=r);}function makeTable(e){for(var t=Q("<table>"),r=0;r<e.length;r++){for(var o=Q("<tr>"),a=0;a<e[r].length;a++)o.append(Q("<td>").text(e[r][a]));t.append(o)}return t}function toggleDebug(){G.DEBUG=Q("#debug").is(":checked")}function toggleNumbers(){G.SHOW_NUMBERS=Q("#showNumbers").is(":checked"),drawGame(G.GAME)}function toggleLOS(){G.SHOW_LOS=Q("#showLOS").is(":checked"),drawGame(G.GAME)}function closeAutorun(){Q("#arWrapper").hide(),Q("#main").show()}function changeSelect(e){var t=Q(e?"#p1Select":"#p2Select").val(),r=Q(e?"#p1Link":"#p2Link");null===t&&0>t?r.attr("href","javascript:;"):r.attr("href",G.PLAYERS[t].link)}function stopTimer(){"undefined"!=typeof G.TIMER&&clearInterval(G.TIMER)}function moveOnce(){gameOver(G.GAME)||(moveGame(G.GAME),drawGame(G.GAME),gameOver(G.GAME)&&(stopTimer(),Q("#runPause").text("Run").prop("disabled",!0),Q("#moveOnce").prop("disabled",!0),G.DEBUG&&console.log("======== GAME OVER: "+G.GAME.p1.score+" TO "+G.GAME.p2.score+" ========"),alert(gameOverMessage(G.GAME))))}function runPause(){if(G.RUNNING)stopTimer(),Q("#runPause").text("Run"),Q("#moveOnce").prop("disabled",!1);else{var e=parseInt(Q("#delay").val());if(isNaN(e)||0>e)return void alert("Delay must be a non-negative integer.");Q("#runPause").text("Pause"),Q("#moveOnce").prop("disabled",!0),G.TIMER=setInterval(moveOnce,e)}G.RUNNING=!G.RUNNING}function newGame(){stopTimer();var e=G.PLAYERS[Q("#p1Select").val()],t=G.PLAYERS[Q("#p2Select").val()];G.RUNNING=!1,Q("#runPause").text("Run").prop("disabled",!1),Q("#moveOnce").prop("disabled",!1),Q("#p1Title").text(e.title),Q("#p2Title").text(t.title),G.GAME=createGame(e,t),drawGame(G.GAME)}function tryParse(e,t){var r=parseInt(Q(e).val());return!isNaN(r)&&r>=0?r:void alert(t+" must be a non-negative integer.")}function autorun(){function e(){for(var e=new Array(a.length),t={},r=["wins","goals","errors","timeouts","malformed","invalid"],n=0;n<e.length;n++){t.wins=t.ties=t.losses=t.goals=t.errors=t.timeouts=t.malformed=t.invalid=0;for(var l=0;l<e.length;l++)n!==l&&(t.ties+=s[n][l].ties+s[l][n].ties,t.losses+=s[n][l].p2.wins+s[l][n].p1.wins,r.forEach(function(e){t[e]+=s[n][l].p1[e]+s[l][n].p2[e]}));e[n]={wins:t.wins,text:a[n].title+" : "+t.wins+"W, "+t.ties+"T, "+t.losses+"L, "+t.goals+"G, "+t.errors+"E, "+t.timeouts+"I, "+t.malformed+"M, "+t.invalid+"F"}}e=e.sort(function(e,t){return t.wins-e.wins}).map(function(t,r){return r+1+". "+t.text+(r<e.length-1?"<br>":"")});for(var i=new Array(s.length+1),G=0;G<i.length;G++){i[G]=new Array(s.length+1);for(var c=0;c<i.length;c++){var f;i[G][c]=0===c&&0===G?"P2\\P1":0===c?a[G-1].id:0===G?a[c-1].id:(f=s[c-1][G-1])?f.p1.wins+" "+f.ties+" "+f.p2.wins:"-"}}Q("#arPlayers").text(a.length),Q("#arRounds").text(o),Q("#arGpR").text(S/o),Q("#arTotal").text(S),Q("#leaderboard").empty().append(e),Q("#statsTable").empty().append(makeTable(i)),Q("#arInfo").hide(),Q("#arResults").show()}function t(e,t){for(var r=createGame(a[e],a[t]);!gameOver(r);)moveGame(r);r.p1.score>r.p2.score?s[e][t].p1.wins++:r.p1.score<r.p2.score?s[e][t].p2.wins++:s[e][t].ties++,["p1","p2"].forEach(function(o){s[e][t][o].goals+=r[o].score,s[e][t][o].errors+=r[o].stats.errors,s[e][t][o].timeouts+=r[o].stats.timeouts,s[e][t][o].malformed+=r[o].stats.malformed,s[e][t][o].invalid+=r[o].stats.invalid.reduce(function(e,t){return e+t},0)})}function r(){if(c!==f&&(t(c,f),++p<=S&&Q("#arProgress").text(p+"/"+S)),f+1<a.length)f++;else if(f=0,c+1<a.length)c++;else{if(c=0,!(o>i+1))return void e();i++}setTimeout(r,0)}var o=parseInt(Q("#N").val());if(isNaN(o)||1>o)return void alert("N must be a positive integer.");var a=[];Q("#arTestEntry").is(":checked")&&a.push(G.PLAYERS[0]);for(var n=1;n<G.PLAYERS.length;n++)G.PLAYERS[n].dq||a.push(G.PLAYERS[n]);for(var s=new Array(a.length),n=0;n<a.length;n++){s[n]=new Array(a.length);for(var l=0;l<a.length;l++)n!==l&&(s[n][l]={ties:0,p1:{wins:0,goals:0,errors:0,timeouts:0,malformed:0,invalid:0},p2:{wins:0,goals:0,errors:0,timeouts:0,malformed:0,invalid:0}})}var i=0,c=0,f=0,p=1,S=o*a.length*(a.length-1);Q("#arProgress").text("1/"+S),Q("#main").hide(),Q("#arInfo").show(),Q("#arResults").hide(),Q("#arWrapper").show(),setTimeout(r,0)}function gameOver(e){return e.move>=G.TOTAL_MOVES}function gameOverMessage(e){function t(e,t){return"P"+(t?1:2)+": "+e.entry.title+"\nScore: "+e.score+"\nErrors: "+e.stats.errors+"\nTimeouts: "+e.stats.timeouts+"\nMalformed actions: "+e.stats.malformed+"\nFailed actions: ["+e.stats.invalid.toString().replace(/,/g,", ")+"]"}var r="GAME OVER - ";return r+=e.p1.score>e.p2.score?"PLAYER 1 WINS":e.p1.score<e.p2.score?"PLAYER 2 WINS":"TIE GAME",r+="\n\n"+t(e.p1,!0)+"\n\n"+t(e.p2,!1)}function createGame(e,t){function r(e){return{entry:e,bots:new Array(G.BOTS),mem:"",score:0,stats:{errors:0,timeouts:0,malformed:0,invalid:Array.apply(null,new Array(G.BOTS)).map(Number.prototype.valueOf,0)}}}var o={},a=Math.floor(.875*G.H)-1;o.move=0,o.walls=new Array(G.H);for(var n=0;n<G.H;n++){o.walls[n]=new Array(G.W);for(var s=0;s<G.W;s++)o.walls[n][s]=n>a}o.p1=r(e),o.p2=r(t);for(var l=0;l<G.BOTS;l++)o.p1.bots[l]={x:l,y:a,hasWall:!1},o.p2.bots[l]={x:G.W-1-l,y:a,hasWall:!1};if(-1===o.p1.entry.id||-1===o.p2.entry.id){var i=decode(Q("#testEntry").val());-1===o.p1.entry.id&&(o.p1.entry.code=i),-1===o.p2.entry.id&&(o.p2.entry.code=i)}return resetGoal(o),G.DEBUG&&console.log("======== NEW GAME: "+o.p1.entry.title+" VS "+o.p2.entry.title+" ========"),o}function moveGame(e){movePlayer(e,++e.move%2===1),++e.goal.age>=G.GOAL_LIFESPAN&&resetGoal(e)}function setupParams(e,t){function r(e,t){var r=toKey(e,t);if(!n.hasOwnProperty(r)){n[r]=!1;for(var a=0;a<G.BOTS;a++)if(Math.abs(o.bots[a].x-e)<=G.LOS&&Math.abs(o.bots[a].y-t)<=G.LOS){n[r]=!0;break}}return n[r]}var o=t?e.p1:e.p2,a=t?e.p2:e.p1,n={},s={};s.p1=t,s.id=o.entry.id,s.eid=a.entry.id,s.score=o.score,s.escore=a.score,s.move=Math.floor((e.move+1)/2),s.goal={x:e.goal.x,y:e.goal.y},s.getMem=function(){return o.mem},s.setMem=function(e){isString(e)&&e.length<=G.MEM_MAX_LENGTH&&(o.mem=e)},s.grid=function(t,o){return isInt(t)&&isInt(o)&&r(t,o)?outOfBounds(t,o)?0:e.walls[o][t]?1:0:-1},s.bots=new Array(G.BOTS),s.ebots=[];for(var l=0;l<G.BOTS;l++)s.bots[l]={x:o.bots[l].x,y:o.bots[l].y,hasWall:o.bots[l].hasWall},r(a.bots[l].x,a.bots[l].y)&&s.ebots.push({x:a.bots[l].x,y:a.bots[l].y,hasWall:a.bots[l].hasWall});return shuffle(s.ebots),-1===o.entry.id&&(s.console=console),s}function movePlayer(e,t){var r,o,a=t?e.p1:e.p2,n=t?e.p2:e.p1,s=setupParams(e,t);G.DEBUG&&(console.log("######## MOVE "+e.move+" - P"+(t?1:2)+" ########"),console.log("PARAMETERS:"),console.log(s)),o=performance.now();try{r=maskedEval(a.entry.code,s)}catch(n){return a.stats.errors++,void(G.DEBUG&&(console.log("!!!! ERRORED !!!!"),console.log(n)))}if(o=performance.now()-o,G.DEBUG&&console.log("TIME TAKEN: "+o+"ms"),o>G.TIME_LIMIT)return a.stats.timeouts++,void(G.DEBUG&&console.log("!!!! TIMED OUT !!!!"));if(G.DEBUG&&(console.log("ACTIONS:"),console.log(r)),!Array.isArray(r)||r.length!==G.BOTS)return a.stats.malformed++,void(G.DEBUG&&console.log("!!!! MALFORMED ACTIONS !!!!"));for(var l=0;l<G.BOTS;l++)if(!isInt(r[l])||r[l]<0||r[l]>24)return a.stats.malformed++,void(G.DEBUG&&console.log("!!!! MALFORMED ACTIONS !!!!"));performActions(e,a,r)}function performActions(e,t,r){function o(e){t.stats.invalid[e]++,G.DEBUG&&console.log("!! BOT"+e+" ACTION FAILED !!")}function a(e){return e.x!==i||e.y!==c}for(var n=!1,s=0;s<G.BOTS;s++){var l=r[s];if(l){var i,c;switch((l-1)%8){case 0:i=-1,c=-1;break;case 1:i=0,c=-1;break;case 2:i=1,c=-1;break;case 3:i=-1,c=0;break;case 4:i=1,c=0;break;case 5:i=-1,c=1;break;case 6:i=0,c=1;break;case 7:i=1,c=1}if(i+=t.bots[s].x,c+=t.bots[s].y,outOfBounds(i,c))o(s);else switch(Math.floor((l-1)/8)){case 0:!e.walls[c][i]&&(i>0&&c>0&&e.walls[c-1][i-1]||c>0&&e.walls[c-1][i]||i<G.W-1&&c>0&&e.walls[c-1][i+1]||i>0&&e.walls[c][i-1]||i<G.W-1&&e.walls[c][i+1]||i>0&&c<G.H-1&&e.walls[c+1][i-1]||c<G.H-1&&e.walls[c+1][i]||i<G.W-1&&c<G.H-1&&e.walls[c+1][i+1])?(t.bots[s].x=i,t.bots[s].y=c,i!==e.goal.x||c!==e.goal.y||n||(n=!0,G.DEBUG&&console.log("** BOT"+s+" REACHED GOAL **"))):o(s);break;case 1:e.walls[c][i]&&!t.bots[s].hasWall?(e.walls[c][i]=!1,t.bots[s].hasWall=!0):o(s);break;case 2:!e.walls[c][i]&&t.bots[s].hasWall&&e.p1.bots.every(a)&&e.p2.bots.every(a)?(e.walls[c][i]=!0,t.bots[s].hasWall=!1):o(s)}}}n&&(t.score++,resetGoal(e)),G.DEBUG&&(console.log("FINAL PLAYER STATE:"),console.log(t))}function resetGoal(e){for(var t={},r=[],o=0;o<G.BOTS;o++)t[toKey(e.p1.bots[o].x,e.p1.bots[o].y)]=!0,t[toKey(e.p2.bots[o].x,e.p2.bots[o].y)]=!0;for(var a=0;a<G.H;a++)for(var n=0;n<G.W;n++){var s=toKey(n,a);t.hasOwnProperty(s)||r.push(s)}var l=fromKey(r[rnd(r.length)]);e.goal={age:0,x:l.x,y:l.y}}function drawGame(e){function t(e,t){G.CTX.fillRect(e*G.SCALE,t*G.SCALE,G.SCALE,G.SCALE)}function r(e,t){G.CTX.fillRect(e*G.SCALE+1,t*G.SCALE+1,G.SCALE-2,G.SCALE-2)}G.CTX.fillStyle=G.COLORS.AIR,G.CTX.fillRect(0,0,G.CW,G.CH),G.CTX.fillStyle=G.COLORS.WALL;for(var o=0;o<G.H;o++)for(var a=0;a<G.W;a++)e.walls[o][a]&&t(a,o);if(G.SHOW_LOS){var n=(2*G.LOS+1)*G.SCALE;G.CTX.fillStyle=G.COLORS.P1_LOS;for(var s=0;s<G.BOTS;s++)G.CTX.fillRect((e.p1.bots[s].x-G.LOS)*G.SCALE,(e.p1.bots[s].y-G.LOS)*G.SCALE,n,n);G.CTX.fillStyle=G.COLORS.P2_LOS;for(var s=0;s<G.BOTS;s++)G.CTX.fillRect((e.p2.bots[s].x-G.LOS)*G.SCALE,(e.p2.bots[s].y-G.LOS)*G.SCALE,n,n)}G.CTX.fillStyle=G.COLORS.P1;for(var s=0;s<G.BOTS;s++)t(e.p1.bots[s].x,e.p1.bots[s].y);G.CTX.fillStyle=G.COLORS.P2;for(var s=0;s<G.BOTS;s++)t(e.p2.bots[s].x,e.p2.bots[s].y);G.CTX.fillStyle=G.COLORS.WALL;for(var s=0;s<G.BOTS;s++)e.p1.bots[s].hasWall&&r(e.p1.bots[s].x,e.p1.bots[s].y),e.p2.bots[s].hasWall&&r(e.p2.bots[s].x,e.p2.bots[s].y);if(G.SHOW_NUMBERS){var l=-.1,i=2.75;G.CTX.fillStyle=G.COLORS.P1_TEXT;for(var s=0;s<G.BOTS;s++)G.CTX.fillText(s.toString(),(e.p1.bots[s].x+l)*G.SCALE,(e.p1.bots[s].y+i)*G.SCALE);G.CTX.fillStyle=G.COLORS.P2_TEXT;for(var s=0;s<G.BOTS;s++)G.CTX.fillText(s.toString(),(e.p2.bots[s].x+l)*G.SCALE,(e.p2.bots[s].y+i)*G.SCALE)}G.CTX.fillStyle=G.COLORS.GOAL,t(e.goal.x+1,e.goal.y),t(e.goal.x-1,e.goal.y),t(e.goal.x,e.goal.y+1),t(e.goal.x,e.goal.y-1),G.SCOREBOARD.P1SCORE.text(e.p1.score),G.SCOREBOARD.MOVE.text(e.move),G.SCOREBOARD.P2SCORE.text(e.p2.score)}function loadPlayers(e){var t=/<pre\b[^>]*><code\b[^>]*>([\s\S]*?)<\/code><\/pre>/,r=/<h1\b[^>]*>(.*?)<\/h1>/;G.PLAYERS=[];var o={id:-1,dq:!1,code:void 0,link:"javascript:;",title:"TEST ENTRY [-1]"};G.PLAYERS.push(o);var a=[];e.forEach(function(e){var o=decode(e.owner.display_name),n=t.exec(e.body),s=r.exec(e.body);if(null===n||n.length<=1||null===s||s.length<=1)return a.push(" "),void a.push(Q("<a>").text(o).attr("href",e.link));var l={};l.id=e.answer_id,l.dq=G.DQ_ANSWERS.indexOf(e.answer_id)>-1||G.DQ_USERS.indexOf(e.owner.user_id)>-1,l.code=decode(n[1]),l.link=e.link,l.title=s[1].substring(0,20)+" - "+o+" ["+l.id.toString()+"]",l.dq&&(l.title+="[DQ]"),G.PLAYERS.push(l)}),a.length>0&&(Q("#invalid").empty().append(a),Q("#invalidWrapper").show());for(var n=new Array(G.PLAYERS.length),s=new Array(G.PLAYERS.length),l=0;l<G.PLAYERS.length;l++)n[l]=Q("<option>").text(G.PLAYERS[l].title).val(l),s[l]=Q("<option>").text(G.PLAYERS[l].title).val(l);Q("#p1Select").empty().append(n).val(rnd(G.PLAYERS.length)),changeSelect(!0),Q("#p2Select").empty().append(s).val(rnd(G.PLAYERS.length)),changeSelect(!1)}function loadAnswers(e,t,r){function o(){Q.get("https://api.stackexchange.com/2.2/questions/"+t.toString()+"/answers?page="+(s++).toString()+"&pagesize=100&order=asc&sort=creation&site="+e+"&filter=!YOKGPOBC5Yad4mOOn8Z4WcAE6q",a)}function a(e){e.hasOwnProperty("error_id")?r(e.error_id.toString()):(n=n.concat(e.items),e.hasMore?o():r(n))}var n=[],s=1;o(s,a)}Q=jQuery,Q(reload);</script> ``` **[This question has its own chatroom.](http://chat.stackexchange.com/rooms/24014)** I'll post leaderboards there every few days. [Answer] # Black Knight The bot's name comes from an early plan to have it be able to move like a chess knight: over two, up one, etc, which would be faster in some cases. ``` var moves = new Array(8), mem = getMem(), newMem = ''; var decodeMem = function(){ //mmtxy for(var ind = 0; ind < 8; ind++){ var sub = mem.substr(ind * 5, 5) bots[ind].lastMove = parseInt(sub[0], 36); bots[ind].last2Move = parseInt(sub[1], 36); bots[ind].timesStill = sub.charCodeAt(2) - 48; bots[ind].lastX = sub.charCodeAt(3) - 187; bots[ind].lastY = sub.charCodeAt(4) - 187; } } decodeMem(); var distanceTo = function(fromX, fromY, toX, toY){ // Chebyshev distance return Math.max(Math.abs(fromX - toX), Math.abs(fromY - toY)); } var direction = function(from, to){ // Math.sign() var diff = to - from; return diff > 0 ? 1 : (diff < 0 ? -1 : 0); } var dirs = [ [1, 2, 3], [4, 0, 5], [6, 7, 8] ]; var moveTo = function(from, to){ var prioritiesWall = [ [0], [1, 2, 4, 17, 18, 20, 19, 22, 23, 21, 3, 6, 5, 7, 24, 8], [2, 3, 1, 17, 19, 18, 23, 22, 24, 4, 5, 20, 21, 6, 8, 7], [3, 2, 5, 19, 18, 21, 17, 24, 23, 20, 1, 8, 4, 7, 22, 6], [4, 1, 6, 22, 17, 20, 21, 24, 19, 2, 7, 18, 23, 3, 8, 5], [5, 3, 8, 24, 19, 21, 20, 22, 17, 2, 7, 18, 23, 1, 6, 4], [6, 4, 7, 22, 20, 23, 17, 24, 18, 21, 1, 8, 2, 5, 19, 3], [7, 8, 6, 22, 24, 23, 18, 17, 19, 4, 5, 20, 21, 1, 3, 2], [8, 5, 7, 24, 21, 23, 19, 22, 18, 20, 3, 6, 2, 4, 17, 1] ]; var prioritiesNoWall = [ [9, 10, 11, 12, 13, 14, 15, 16, 0], [1, 2, 4, 9, 16, 10, 12, 3, 6, 11, 14, 5, 7, 13, 15, 8], [2, 3, 1, 10, 15, 14, 16, 4, 5, 12, 13, 9, 11, 6, 8, 7], [3, 2, 5, 11, 14, 10, 13, 1, 8, 9, 16, 4, 7, 12, 15, 6], [4, 1, 6, 12, 13, 16, 11, 2, 7, 10, 15, 9, 14, 3, 8, 5], [5, 3, 8, 13, 12, 14, 9, 2, 7, 10, 15, 11, 16, 1, 6, 4], [6, 4, 7, 14, 11, 12, 15, 1, 8, 9, 16, 2, 5, 10, 13, 3], [7, 8, 6, 15, 10, 9, 11, 4, 5, 12, 13, 14, 16, 1, 3, 2], [8, 5, 7, 16, 9, 13, 15, 3, 6, 11, 14, 2, 4, 10, 12, 1] ]; var dir = dirs[direction(from.y, to.y) + 1][direction(from.x, to.x) + 1], method = from.hasWall ? prioritiesWall[dir] : prioritiesNoWall[dir]; if(distanceTo(from.x, from.y, goal.x, goal.y) === 1){ method.splice(1,2); } for(var i=0; i<method.length; i++){ var attempt = method[i]; if(checkMove(from, attempt)) return attempt; } return 0; } var numWalls = function(x, y, indexes){ var allCoords = [ [x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x - 1, y ], [x + 1, y ], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1], ]; var allTypes = allCoords.map(function(e){ return grid(e[0], e[1]); // air = 0, wall = 1 }); var justWalls = allTypes.filter(function(e){ return e === 1; }).length; return indexes ? allTypes : justWalls; } var checkMove = function(coords, moveCode){ var x = coords.x, y = coords.y, baseX = [0, -1, 0, 1, -1, 1, -1, 0, 1], baseY = [0, -1, -1, -1, 0, 0, 1, 1, 1], targetX = x + baseX[(moveCode - 1) % 8 + 1], targetY = y + baseY[(moveCode - 1) % 8 + 1]; if((targetX > 127 || targetX < 0 || targetY > 63 || targetY < 0) || // Don't bother if it's out of bounds (coords.timesStill > 2 && x == coords.lastX && y == coords.lastY && (moveCode == coords.lastMove || moveCode == coords.last2Move))) // Or is doing the same moves and not moving return false; var targetGrid = grid(targetX, targetY), enemyNear = false, couldStrandEnemy = false, eWallDirMove, hasNeighbor = numWalls(targetX, targetY) > 0; ebots.forEach(function(ebot){ // Don't place a wall where an enemy can take it if(distanceTo(targetX, targetY, ebot.x, ebot.y) === 1 && !ebot.hasWall && (y != ebot.y || x != ebot.x)) enemyNear = true; // Don't move if you can strand an enemy var eWallDir = numWalls(ebot.x, ebot.y, true).indexOf(1) + 1, wallX = ebot.x + baseX[eWallDir], wallY = ebot.y + baseY[eWallDir]; if(!coords.hasWall && numWalls(ebot.x, ebot.y) === 1 && distanceTo(x, y, wallX, wallY) === 1){ eWallDirMove = dirs[direction(y, wallY) + 1][direction(x, wallX) + 1] + 8; couldStrandEnemy = true; } }) if(targetX == goal.x && targetY == goal.y && targetGrid === 0){ targetGrid = 2 // Don't place a wall in the goal } else { ebots.concat(bots).forEach(function(bot){ // Ensure target cell doesn't have a bot in it if(bot.x == targetX && bot.y == targetY) targetGrid = 2; }); } return ((moveCode < 9 && targetGrid !== 1 && hasNeighbor && !couldStrandEnemy) || // Move (moveCode > 8 && moveCode < 17 && targetGrid === 1 && !coords.hasWall && (!couldStrandEnemy || (couldStrandEnemy && eWallDirMove == moveCode))) || // Grab (moveCode > 16 && targetGrid === 0 && coords.hasWall && !enemyNear)) // Place } var goalClosest = {dist: Infinity}, rescuers = {}; bots.forEach(function(bot, index){ // Check if bot is stranded bot.stranded = false; if(numWalls(bot.x, bot.y) / 8 == bot.hasWall){ bot.stranded = true; rescuers[index] = -1; } }); bots.forEach(function(bot, index){ if(!bot.stranded){ // Find which bot is closest to the goal var goalDist = distanceTo(bot.x, bot.y, goal.x, goal.y); if(goalDist < goalClosest.dist){ goalClosest.dist = goalDist; goalClosest.index = index; } } }); bots.forEach(function(bot, index){ var destination = { x: 14 + (index % 4) * 32 + 3 * (index > 3), y: index > 3 ? 55 : 27 } if(index == goalClosest.index){ destination = goal; } moves[index] = moveTo(bot, destination); if(moves[index] == bot.lastMove || moves[index] == bot.last2Move) bot.timesStill++; newMem += moves[index].toString(36) + bot.lastMove.toString(36) + String.fromCharCode(bot.timesStill + 48) + String.fromCharCode(bot.x + 187) + String.fromCharCode(bot.y + 187); }); setMem(newMem); return moves; ``` ## Explanation Determining which move to make for each bot can be divided into two main tasks: figuring out where to go and how to get there. ### Where to go The basic task of figuring out where to go is easy: go towards the goal if you're closest, or otherwise try to position yourself as far away from teammates. It first goes through each bot and determines if it is stranded (i.e. it has no blocks surrounding it and isn't holding a wall, or it is surrounded by walls and holds a wall). It then loops through the bots again to find the non-stranded bot closest to the goal. All other bots make their way towards being spaced out, with the bottom row on the surface of the blocks (`y=55`) and the top row at `y=27`. Once it knows where to go, it hands it off to the `moveTo` function. ### How to get there Deciding how to get to the destination is far more difficult because the bots must always be adjacent to a wall to move. It first figures out the direction code (1–8) of the destination relative to its current position. For example, if a bot were at the bottom-left corner and it wanted to go to the top right, it would use the direction code 3. For each direction, I hardcoded a list of moves, with the first being the ideal, top-priority move, and the last being the last resort. This is separated by whether or not the bot has a wall, because you cannot use a place move without a wall or use a grab move while already having a wall. Of course, using the ideal move doesn't always work, and it would result in a lot of failed actions. This is where `checkMove` comes in. This function checks the potential move against every requirement, to prevent the bot from moving out of bounds or into a wall, for example. If a nearby enemy bot can be stranded (it has only one adjacent wall that can be taken by the bot), that becomes its priority, so the function will return `false` for an otherwise legitimate move so it can skip to the grab moves and take out the enemy. The function prevents several other stupid moves like placing a wall in the goal or another bot. ### The memory string Sometimes the bot will not be actually stranded but will keep trying the same move and not end up moving (usually picking up a wall and putting it down, picking it up and putting it down, etc). To prevent this, it uses the memory string to remember its last two moves, its last x and y position, and how many times it has been still. Each datum is encoded as a single character for easy splitting. (The string has to be 256 *characters*, not bytes, so using multibyte Unicode characters isn't a problem, as it is with typical golfing challenges.) For example, say a bot grabbed the wall on its left (code `12`) this turn, replaced it to its left (code `20`) in its previous turn, and has been at the coordinates (`107`, `3`) for the past `16` turns. The memory string for this instance would be encoded as follows: * `ck`: The two latest action codes are converted to base36 to make the two-digit numbers a single letter. * `@`: The number of times it has been still is represented as the ASCII character with that code + 48 to skip over unprintable characters and so the first nine times still shows the actual number (`String.fromCharCode(0 + 48)` → `0`). * `Ħ¾`: The x and y coordinates are also represented as as the character with that value, this time offset by the somewhat-arbitrary value of 187 to avoid problematic characters. A typical memory string during the game might be `53äÇØb7¼ðÌ00ßĉÖ7m±ĪÚ00ĝÌò00Ĝìò00ĖČò00ĈĬò`, with a group of five characters for each of the eight bots. [Answer] # Outposts The 8 bots each take a 32 by 32 square and run to the centre of it (I offset the centres slightly otherwise they end up pairing up and travelling vertically with one wall block between them, so one of them gets stranded). Each bot will stay in the centre of its square unless the goal is within 32 cells of its respective centre, in which case it will run to the goal and then back to its centre. This still uses the Baseline method of reaching its target (goal or centre) so does not move diagonally. Just a starting point... ``` var encodeAction = function(type, dx, dy) { var d if (dx === -1 && dy === -1) d = 1 else if (dx === 0 && dy === -1) d = 2 else if (dx === 1 && dy === -1) d = 3 else if (dx === -1 && dy === 0) d = 4 else if (dx === 1 && dy === 0) d = 5 else if (dx === -1 && dy === 1) d = 6 else if (dx === 0 && dy === 1) d = 7 else if (dx === 1 && dy === 1) d = 8 else return 0 return 8 * type + d } var getNeighborCell = function(x, y, wallState) { if (x > 0 && y > 0 && grid(x - 1, y - 1) === wallState) return { x: x - 1, y: y - 1 } if (y > 0 && grid(x, y - 1) === wallState) return { x: x, y: y - 1 } if (x < 127 && y > 0 && grid(x + 1, y - 1) === wallState) return { x: x + 1, y: y - 1 } if (x > 0 && grid(x - 1, y) === wallState) return { x: x - 1, y: y } if (x < 127 && grid(x + 1, y) === wallState) return { x: x + 1, y: y } if (x > 0 && y < 63 && grid(x - 1, y + 1) === wallState) return { x: x - 1, y: y + 1 } if (y < 63 && grid(x, y + 1) === wallState) return { x: x, y: y + 1 } if (x < 127 && y < 63 && grid(x + 1, y + 1) === wallState) return { x: x + 1, y: y + 1 } return null } var moveBot = function(n) { var assignedX = (n % 4) * 32 + 14 + Math.floor(n/4) * 4 var assignedY = (Math.floor(n / 4)) * 32 + 16 if (Math.abs(goal.x - assignedX) < 33 && Math.abs(goal.y - assignedY) < 33) { assignedX = goal.x assignedY = goal.y } var b = bots[n], moveX = b.x !== assignedX, x = b.x, y = b.y, type if (moveX) { x += b.x < assignedX ? 1 : -1 } else { y += b.y < assignedY ? 1 : -1 } if (grid(x, y) === 1) { if (b.hasWall) { type = 2 //place var c = getNeighborCell(b.x, b.y, 0) if (!c) { //stuck holding wall with walls all around return 0 } x = c.x y = c.y } else { type = 1 //grab } } else if (grid(x, y) === 0) { if (getNeighborCell(x, y, 1)) { type = 0 //move } else { if (b.hasWall) { type = 2 //place if (moveX) { y += y > 0 ? -1 : 1 } else { x += x > 0 ? -1 : 1 } } else { type = 1 //grab var c = getNeighborCell(b.x, b.y, 1) if (!c) { //stuck without wall in midair return 0 } x = c.x y = c.y } } } else { return 0 //should never get here } return encodeAction(type, x - b.x, y - b.y) } var actions = [] for (var i = 0; i < 8; i++) { actions[i] = moveBot(i) } return actions ``` [Answer] # Baseline This is the simplest consistently functioning bot flock controller I could think of. It will be my only non-disqualified answer and will serve as a baseline to judge other answers by. It is technically in the running to win the contest, but beating it should not be difficult. Any of the code here may be copied and used in another answer, no attribution required. ``` var encodeAction = function(type, dx, dy) { var d if (dx === -1 && dy === -1) d = 1 else if (dx === 0 && dy === -1) d = 2 else if (dx === 1 && dy === -1) d = 3 else if (dx === -1 && dy === 0) d = 4 else if (dx === 1 && dy === 0) d = 5 else if (dx === -1 && dy === 1) d = 6 else if (dx === 0 && dy === 1) d = 7 else if (dx === 1 && dy === 1) d = 8 else return 0 return 8 * type + d } var getNeighborCell = function(x, y, wallState) { if (x > 0 && y > 0 && grid(x - 1, y - 1) === wallState) return { x: x - 1, y: y - 1 } if (y > 0 && grid(x, y - 1) === wallState) return { x: x, y: y - 1 } if (x < 127 && y > 0 && grid(x + 1, y - 1) === wallState) return { x: x + 1, y: y - 1 } if (x > 0 && grid(x - 1, y) === wallState) return { x: x - 1, y: y } if (x < 127 && grid(x + 1, y) === wallState) return { x: x + 1, y: y } if (x > 0 && y < 63 && grid(x - 1, y + 1) === wallState) return { x: x - 1, y: y + 1 } if (y < 63 && grid(x, y + 1) === wallState) return { x: x, y: y + 1 } if (x < 127 && y < 63 && grid(x + 1, y + 1) === wallState) return { x: x + 1, y: y + 1 } return null } var moveBot = function(n) { var b = bots[n], moveX = b.x !== goal.x, x = b.x, y = b.y, type if (moveX) { x += b.x < goal.x ? 1 : -1 } else { y += b.y < goal.y ? 1 : -1 } if (grid(x, y) === 1) { if (b.hasWall) { type = 2 //place var c = getNeighborCell(b.x, b.y, 0) if (!c) { //stuck holding wall with walls all around return 0 } x = c.x y = c.y } else { type = 1 //grab } } else if (grid(x, y) === 0) { if (getNeighborCell(x, y, 1)) { type = 0 //move } else { if (b.hasWall) { type = 2 //place if (moveX) { y += y > 0 ? -1 : 1 } else { x += x > 0 ? -1 : 1 } } else { type = 1 //grab var c = getNeighborCell(b.x, b.y, 1) if (!c) { //stuck without wall in midair return 0 } x = c.x y = c.y } } } else { return 0 //should never get here } return encodeAction(type, x - b.x, y - b.y) } var actions = [] for (var i = 0; i < 8; i++) { actions[i] = moveBot(i) } return actions ``` Each of the 8 bots independently follows the same basic method. They tend to clump together because of this, unless they get separated by something external. The bots never care about where teammates or enemies are, they only attempt to move toward the goal. They only move orthogonally, first matching their x with the goal x, then their y. Never moving diagonally means they waste a lot of time in travel. The movement algorithm of each bot is as follows: ``` If my X is not equal to the goal's X P = position to my left or right that is closer to the goal Make a note that I'm trying to move horizontal Else P = position above or below me that is closer to the goal Make a note that I'm trying to move vertical If P is a wall If I'm holding a wall Place my wall in any neighboring air cell Else Grab the wall at P Else if P is air If P has a wall neighboring it (i.e. if I can move to P) Move to P Else If I'm holding a wall If I'm trying to move horizontal Place my wall above or below P Else if I'm trying to move vertical Place my wall to the left or right of P Else Grab wall from any neighboring wall cell ``` [Answer] # Teamplayer At the moment, this submission is far from perfect. It has a similar strategy like Outposts, but only 6 bots are "in the air". The other 2 bots supply them with walls if they got stolen. **Edit:** The supporter bots perform much better now. ``` var outside = function(x,y) { return x < 0 || x > 127 || y < 0 || y > 127 } var distance = function(x1, y1, x2, y2){ return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)); } var isStuck = function(bot) { if (bot.hasWall) { for (var i=-1; i<=1; i++) { for (var j=-1; j<=1; j++) { if ((i != 0 || j != 0) && grid(bot.x+i,bot.y+j) == 0 && !outside(bot.x+i,bot.y+j)) return false } } return true } for (var i=-1; i<=1; i++) { for (var j=-1; j<=1; j++) { if (grid(bot.x+i, bot.y+j) == 1) return false } } return true } var isPlayer = function(x,y) { for (var i = 0; i < bots.length; i++) { if (bots[i].x == x && bots[i].y == y) return true } for (var i = 0; i < ebots.length; i++) { if (ebots[i].x == x && ebots[i].y == y) return true } return false } var encodeAction = function(type, dx, dy) { var d if (dx === -1 && dy === -1) d = 1 else if (dx === 0 && dy === -1) d = 2 else if (dx === 1 && dy === -1) d = 3 else if (dx === -1 && dy === 0) d = 4 else if (dx === 1 && dy === 0) d = 5 else if (dx === -1 && dy === 1) d = 6 else if (dx === 0 && dy === 1) d = 7 else if (dx === 1 && dy === 1) d = 8 else return 0 return 8 * type + d } var surrounding = function(x,y) { var cell = {hasStone:false, cells: []} for (var i=-1; i<=1; i++) { for(var j=-1; j<=1; j++) { if ((i != 0 || j != 0) && !outside(x+i,y+j)) { cell.cells.push({x:x+i, y:y+j}) if (grid(x+i,y+j) == 1) { cell.hasStone = true } } } } return cell } var hunt = function(i, destination) { destination = destination || {x: 31+((i-2)%3)*32, y: 20+((i-2)%2)*21}, bot = bots[i] if (i < 5 && i > 1) { destination.x -= 2 } if (bot.isStuck) { return 0 } if ((p1 && destination.x >= move + i) || (!p1 && 127 - destination.x > move - i)) { destination.y = bot.y } if (i == bestBotId && move > 50) { destination.x = goal.x destination.y = goal.y } var dx = destination.x > bot.x ? 1 : destination.x == bot.x ? 0 : -1, newX = bot.x + dx var dy = destination.y > bot.y ? 1 : destination.y == bot.y ? 0 : -1, newY = bot.y + dy var surr = surrounding(newX, newY), botSurr = surrounding(bot.x, bot.y) if (grid(newX, newY) == 0) { if (surr.hasStone) { return encodeAction(0, dx, dy) } else { if (bot.hasWall) { for (var i=0; i<surr.cells.length; i++) { var cell = surr.cells[i]; if (Math.abs(cell.x - bot.x) <= 1 && Math.abs(cell.y - bot.y) <= 1 && grid(cell.x, cell.y) == 0 && !isPlayer(cell.x, cell.y)) { return encodeAction(2, cell.x - bot.x, cell.y - bot.y) } } } else { if (bot.walls.length == 1) { return encodeAction(1, bot.walls[0].x - bot.x, bot.walls[0].y - bot.y) } else { for (var i=0; i<bot.walls.length; i++) { var wall = bot.walls[i], canUseWall = true for (var j=0; j<bots.length; j++) { if (bots[j].walls.length == 1 && bots[j].walls[0].x == wall.x && bots[j].walls[0].y == wall.y) { canUseWall = false } } if (canUseWall) { return encodeAction(1, wall.x - bot.x, wall.y - bot.y) } } } } } } else { if (bot.hasWall) { for (var i=0; i<botSurr.cells.length; i++) { var cell = botSurr.cells[i]; if (grid(cell.x, cell.y) == 0 && !isPlayer(cell.x, cell.y) && !outside(cell.x, cell.y)) { return encodeAction(2, cell.x - bot.x, cell.y - bot.y) } } } else { return encodeAction(1, dx, dy) } } return 0 //hopefully never happens } var help = function(i) { if (bots[i].isStuck) { return 0 } var bot = bots[i], destination = helpDestinations[i] if (destination.stuckBot == -1) { if (bot.walls.length >= 2 || (bot.hasWall && bot.walls.length == 1)) { var stuckId = -1 for (var j = 0; j < bots.length; j++) { if (j != helpDestinations[(i+1)%2].stuckBot && bots[j].isStuck) stuckId = j } if (stuckId != -1) { destination.stuckBot = stuckId destination.x = bots[stuckId].x destination.y = bots[stuckId].y return 0 } else { return hunt(i, destination) } } else if (bot.x == destination.x && bot.y == destination.y) { if (move % 2 == 0) destination.y += 1 else destination.x -= 1 return hunt(i, destination) } else { return hunt(i, destination) } } else if (bots[destination.stuckBot].isStuck) { if (bot.walls.length < 2 && !(bot.hasWall && bot.walls.length == 1)) { destination.stuckBot = -1 destination.x = i == 0 ? 42 : 85 destination.y = 55 return hunt(i, destination) } var dx = destination.x > bot.x ? 1 : destination.x == bot.x ? 0 : -1, newX = bot.x + dx var dy = destination.y > bot.y ? 1 : destination.y == bot.y ? 0 : -1, newY = bot.y + dy var surr = surrounding(newX, newY), botSurr = surrounding(bot.x, bot.y), surrWalls = 0 for (var i = 0; i < surr.cells.length; i++) { var cell = surr.cells[i] if (grid(cell.x,cell.y) == 1) surrWalls++ } if (grid(newX, newY) == 0) { if (surrWalls >= 2 || (surr.hasWall && bot.hasWall)) { return encodeAction(0, dx, dy) } else { if (bot.hasWall) { for (var i=0; i<surr.cells.length; i++) { var cell = surr.cells[i]; if (Math.abs(cell.x - bot.x) <= 1 && Math.abs(cell.y - bot.y) <= 1 && grid(cell.x, cell.y) == 0 && !isPlayer(cell.x, cell.y)) { return encodeAction(2, cell.x - bot.x, cell.y - bot.y) } } } else { if (bot.walls.length == 1) { return encodeAction(1, bot.walls[0].x - bot.x, bot.walls[0].y - bot.y) } else { for (var i=0; i<bot.walls.length; i++) { var wall = bot.walls[i], canUseWall = true for (var j=0; j<bots.length; j++) { if (bots[j].walls.length == 1 && bots[j].walls[0].x == wall.x && bots[j].walls[0].y == wall.y) { canUseWall = false } } for (var j=0; j<surr.cells.length; j++) { if (surr.cells[j].x == wall.x && surr.cells[j].y == wall.y) canUseWall = false } if (canUseWall) { return encodeAction(1, wall.x - bot.x, wall.y - bot.y) } } } } } } else { if (bot.hasWall) { for (var i=0; i<botSurr.cells.length; i++) { var cell = botSurr.cells[i]; if (grid(cell.x, cell.y) == 0 && !isPlayer(cell.x, cell.y)) { return encodeAction(2, cell.x - bot.x, cell.y - bot.y) } } } else { return encodeAction(1, dx, dy) } } } else { destination.stuckBot = -1 destination.x = i == 0 ? 42 : 85 destination.y = 55 return hunt(i, destination) } return 0 //hopefully never happens } var moves = new Array(8) var mem = getMem(), helpDestinations = [] if (mem.length == 0) { mem = "42,55,-1 85,55,-1" } mem = mem.split(" ") for (var i = 0; i < mem.length; i++) { var cell = mem[i].split(",") helpDestinations.push({x: parseInt(cell[0]), y: parseInt(cell[1]), stuckBot: parseInt(cell[2])}) } for (var i = 0; i < 8; i++) { var bot = bots[i] var surr = surrounding(bot.x, bot.y) bot.walls = [] for (var j = 0; j < surr.cells.length; j++) { if (grid(surr.cells[j].x, surr.cells[j].y) == 1) { bot.walls.push(surr.cells[j]) } } } bots.forEach(function(bot, index) { if(isStuck(bot)) { bot.isStuck = true } }) var bestDistance = 1000 var bestBotId = -1 for (var i=2; i<8; i++) { var dist = distance(bots[i].x, bots[i].y, goal.x, goal.y) if (dist < bestDistance && !bots[i].isStuck) { bestDistance = dist bestBotId = i } } for (var i=0; i<8; i++) { if (i < 2) { moves[i] = help(i) } else { moves[i] = hunt(i) } } setMem(helpDestinations[0].x + "," + helpDestinations[0].y + "," + helpDestinations[0].stuckBot + " " + helpDestinations[1].x + "," + helpDestinations[1].y + "," + helpDestinations[1].stuckBot) return moves ``` [Answer] # Seekers Stll work in progress. I have many ideas, but almost none of them do work. ~~Above all, big problem with failed actions.~~ Solved! ``` var action=[], myGrid=[], goalSort=[], i, j, curBot, curAction, goalSeek; var check = function(x,y) { return (myGrid[[x,y]] || (myGrid[[x,y]] = grid(x,y)))|0; }; var setGrid = function(x,y,v) { myGrid[[x,y]] = v + ''; }; var orGrid = function(x,y,v) { myGrid[[x,y]] |= v; }; var encodeDir = function(dx, dy) { return dx < 0 && dy < 0 ? 1 : dx === 0 && dy < 0 ? 2 : dx > 0 && dy < 0 ? 3 : dx < 0 && dy === 0 ? 4 : dx > 0 && dy === 0 ? 5 : dx < 0 && dy > 0 ? 6 : dx === 0 && dy > 0 ? 7 : dx > 0 && dy > 0 ? 8 : 0; }; var distance = function(p1, p2) { return Math.max(Math.abs(p1.x-p2.x),Math.abs(p1.y-p2.y)); }; var cellNearWall = function(x,y) { var r = check(x,y) == 1 ? 0 : check(x-1,y-1) == 1 ? 1 : check(x,y-1) == 1 ? 2 : check(x+1,y-1) == 1 ? 3 : check(x-1,y) == 1 ? 4 : check(x+1,y) == 1 ? 5 : check(x-1,y+1) == 1 ? 6 : check(x,y+1) == 1 ? 7 : check(x+1,y+1) == 1 ? 8 : 0; return r; }; var cellNearBot = function(x,y,m) { return check(x-1,y-1) & m ? 1 : check(x,y-1) & m ? 2 : check(x+1,y-1) & m ? 3 : check(x-1,y) & m ? 4 : check(x+1,y) & m ? 5 : check(x-1,y+1) & m ? 6 : check(x,y+1) & m ? 7 : check(x+1,y+1) & m ? 8 : 0; }; var tryGrabWall = function(x, y) { var dx, dy, r = 8; for(dy = -1; dy < 2; ++dy) { for(dx = -1; dx < 2; ++dx) { if (dx|dy) { ++r; if (check(x+dx, y+dy) == 1) { setGrid(x+dx, y+dy, 0); // remember that the wall is not there anymore return r; } } } } return 0; }; var tryDropWall= function(x, y) { var dx, dy, r = 16; for(dy = -1; dy < 2; ++dy) { for(dx = -1; dx < 2; ++dx) { if (dx|dy) { ++r; if (x+dx>=0 & x+dx < 128 & y+dy >= 0 & y+dy < 64 && check(x+dx, y+dy) == 0) { setGrid(x+dx, y+dy, 1); // remember that the wall is there return r; } } } } return 0; }; var approach = function(bot, target) { var dx, dy, tx, ty, r = 0, wallPos; var checkDrop = function(dx,dy) { var x = bot.x+dx, y = bot.y+dy; if (check(x,y) == 0 && cellNearBot(x,y,8) == 0) { setGrid(x, y, 1); return 16 + encodeDir(dx, dy); } }; dy = target.y - bot.y; dy = dy < 0 ? -1 : dy > 0 ? 1 : 0; dx = target.x - bot.x; dx = dx < 0 ? -1 : dx > 0 ? 1 : 0; tx = bot.x+dx; ty = bot.y+dy; if ((dx|dy) === 0) { if (!bot.hasWall) { return tryGrabWall(bot.x, bot.y); } return 0; } if (cellNearWall(tx,ty)) { setGrid(tx, ty, 2); return encodeDir(dx, dy); } if (dx === 0) { if (cellNearWall(bot.x-1,ty)) { setGrid(bot.x-1, ty, 2); return encodeDir(-1, dy); } if (cellNearWall(bot.x+1,ty)) { setGrid(bot.x+1, ty, 2); return encodeDir(1, dy); } if (bot.hasWall) { if (wallPos = checkDrop(1,dy)) { return wallPos; } if (wallPos = checkDrop(-1,dy)) { return wallPos; } if (wallPos = checkDrop(1,0)) { return wallPos; } if (wallPos = checkDrop(-1,0)) { return wallPos; } } } else if (dy === 0) { if (cellNearWall(tx,bot.y-1)) { setGrid(tx, bot.y-1, 2); return encodeDir(dx, -1); } if (cellNearWall(tx,bot.y+1)) { setGrid(tx, bot.y+1, 2); return encodeDir(dx, 1); } if (bot.hasWall) { if (wallPos = checkDrop(dx,1)) { return wallPos; } if (wallPos = checkDrop(dx,-1)) { return wallPos; } if (wallPos = checkDrop(0,1)) { return wallPos; } if (wallPos = checkDrop(0,-1)) { return wallPos; } } } else { if (cellNearWall(tx,bot.y)) { setGrid(tx, bot.y, 2); return encodeDir(dx, 0); } if (cellNearWall(bot.x,ty)) { setGrid(bot.x, ty, 2); return encodeDir(0,dy); } if (bot.hasWall) { if (wallPos = checkDrop(dx,0)) { return wallPos; } if (wallPos = checkDrop(0,dy)) { return wallPos; } if (wallPos = checkDrop(dx,dy)) { return wallPos; } } } if (!bot.hasWall) { if (check(tx, ty) == 1) { setGrid(tx, ty, 0); // remember that the wall is not there anymore return 8 + encodeDir(dx, dy); }; return tryGrabWall(bot.x, bot.y); } else { return tryDropWall(bot.x, bot.y); } }; for (i=0; curBot=ebots[i]; i++) { setGrid(curBot.x, curBot.y, curBot.hasWall ? 4 : 8); } var goalDistance=[] for (i=0; curBot=bots[i]; i++) { orGrid(curBot.x, curBot.y, 2); goalDistance[i] = distance(curBot, goal); } var sorted = goalDistance.slice().sort(function(a,b){return a-b}) var ranks = goalDistance.slice().map(function(v){ return sorted.indexOf(v)}); var tt = p1 ? [ { x:32, y:20 },{ x:32, y:55 },{ x:64, y:20 },{ x:64, y:55 }, { x:96, y:20 },{ x:96, y:55 },{ x:16, y:30 },{ x:112, y:30 }] : [ { x:96, y:20 },{ x:96, y:55 },{ x:64, y:20 },{ x:64, y:55 }, { x:32, y:20 },{ x:32, y:55 },{ x:112, y:30 },{ x:16, y:30 }] var goalSeek = 3; for (i=0; curBot=bots[i]; i++) { if (ranks[i] < goalSeek) { curAction = approach(curBot, goal); if (curAction == 0) goalSeek += 1; } else curAction = approach(curBot, tt[i]); action[i] = curAction; } return action; ``` ]
[Question] [ The aim of this task is to identify, clean up, and mark out all the faces in any given 'image'. ## What's in a face? A face will be a ZxZ square where Z is an odd integer greater than 1. The top left and right corners and the centre will be 'O' characters, and the bottom line will be a '\' and a '/' surrounding enough '\_' characters to fill the rest of the line. Examples: a 3x3 face: ``` O O O \_/ ``` a 5x5 face: ``` O O O \___/ ``` a 7x7 face: ``` O O O \_____/ ``` etc. ## Input Input will be on STDIN and will consist of a number of equal length strings of characters. ## Output Output should be the input with all recognizable faces cleared (i.e. all characters except the eyes, nose and mouth shoud be removed from within the face's bounds) and boxed (surrounded by +, -, and | characters). Where two or more faces overlap both should be cleared and boxed but priority should be given to the larger face (it should be placed on top); if both faces are the same size, the priority is left to the discretion of the implementer. If the input has no faces, output should be the same as input. ## Some examples Input: ``` ******* ******* **O*O** ***O*** **\_/** ******* ******* ``` Output: ``` ******* *+---+* *|O O|* *| O |* *|\_/|* *+---+* ******* ``` Input (incomplete face): ``` ******* ******* **O*O** ******* **\_/** ******* ******* ``` Output: ``` ******* ******* **O*O** ******* **\_/** ******* ******* ``` Input (nested faces): ``` ******* *O***O* **O*O** ***O*** **\_/** *\___/* ******* ``` Output: ``` +-----+ |O O| | | | O | | | |\___/| +-----+ ``` Input (multiple faces): ``` ~{$FJ*TBNFU*YBVEXGY% FOCO$&N|>ZX}X_PZ<>}+ X$OOPN ^%£)LBU{JJKY% @\_/$£!SXJ*)KM>>?VKH SDY%£ILO(+{O:HO(UR$W XVBFTER^&INLNLO*(&P: >?LKPO)UJO$£^&L:}~{& ~@?}{)JKOINLM@~}P>OU :@<L::@\___/GER%^*BI @{PO{_):<>KNUYT*&G&^ ``` Output: ``` +---+*TBNFU*YBVEXGY% |O O|&N|>ZX}X_PZ<>}+ | O |N ^%£)LBU{JJKY% |\_/|£+-----+M>>?VKH +---+I|O O|HO(UR$W XVBFTE| |LO*(&P: >?LKPO| O |&L:}~{& ~@?}{)| |@~}P>OU :@<L::|\___/|ER%^*BI @{PO{_+-----+YT*&G&^ ``` Input (near boundary): ``` ~{$FJ*TBNFU*YBVEXGY% OCO$&N|>ZX}X_PZ<>}+^ $OOPN ^%£)LBU{JJKY%{ \_/$£!SXJ*)KM>>?VKHU SDY%£ILO(+{8:HO(UR$W XVBFTER^&INLNLO*(&P: >?LKPO)UJ^$£^&L:}~{& ~@?}{)JKOINLM@~}P>OU :@<L::@BJYT*GER%^*BI @{PO{_):<>KNUYT*&G&^ ``` Output: ``` ---+J*TBNFU*YBVEXGY% O O|&N|>ZX}X_PZ<>}+^ O |N ^%£)LBU{JJKY%{ \_/|£!SXJ*)KM>>?VKHU ---+£ILO(+{8:HO(UR$W XVBFTER^&INLNLO*(&P: >?LKPO)UJ^$£^&L:}~{& ~@?}{)JKOINLM@~}P>OU :@<L::@BJYT*GER%^*BI @{PO{_):<>KNUYT*&G&^ ``` Input (overlapping faces): ``` ~{$FJ*TBNFU*YBVEXGY% FXC£$&N|>ZX}X_PZ<>}+ X$*OPN O%£)LBO{JJKY% @:U%$£!SXJ*)KM>>?VKH SDY%£OLO(+{P:HO(UR$W XVBFTER^&IOLNLO*(&P: >?L\___/JR$£^&L:}~{& ~@?}{)JKOINLM@~}P>OU :@<L::@\_____/R%^*BI @{PO{_):<>KNUYT*&G&^ ``` Output: ``` ~{$FJ*TBNFU*YBVEXGY% FX+---+-------+Z<>}+ X$|O |O O|JJKY% @:| | |>?VKH SD| O| |(UR$W XV| | O |*(&P: >?|\__| |:}~{& ~@+---| |}P>OU :@<L::|\_____/|%^*BI @{PO{_+-------+*&G&^ ``` [Answer] ### Ruby, 304 298 295 characters ``` I=$<.read q=(O=I*s=1).size k=??+O=~/$/ o=->m,n{n.chars{|c|(m+=1)*(m%k)>0&&m<q&&O[m-1]=c}} q.times{f=[[?\\+?_*s+?/,k*s+=1],[?O,0],[?O,s],[?O,(s+=1)/2*(1+k)]] q.times{|x|f.all?{|a,b|I[x+b,a.size]==a}&&(o[x+k*s-1,o[x-k-1,?++?-*s+?+]] s.times{|a|o[x+k*a-1,?|+' '*s+?|]} f.map{|a,b|o[x+b,a]})}} $><<O ``` Lower right is preferred on overlap if faces are of identical size. E.g. for the input ``` O.OO.O .O..O. \_/\_/ O.OO.O .O..O. \_/\_/ ``` it recognizes all four faces and yields ``` O |O O O| O --+--- O |O O O| O \_|\_/ ``` *Edit 1:* As Lowjacker proposed we can replace the `index` with a regex match (-3 chars). Moreover the `+1` can be compensated by an additional dummy char before the matching which saves another char (-2 for the `+1`, +3 for dummy char, -2 because brackets are no more necessary). Two more since we can write the range also without brackets. *Edit 2:* Another two characters saved by replacing both `if` with `&&` and another one removing the range completely. [Answer] # Python - ~~1199~~ 941 I found the problem pretty interesting, so I solved in Python. Here's the compressed code. ``` #!/usr/bin/env python import fileinput,sys m=[[c for c in l if c!='\n'] for l in fileinput.input()] X=len(m[0]) Y=len(m) t=[] for n in range(3,min(X,Y)+1,2): for x in range(X-n+1): for y in range(Y-n+1): if m[y][x]=='O' and m[y][x+n-1]=='O' and m[y+(n//2)][x+(n//2)]=='O' and m[y+n-1][x]=='\\' and m[y+n-1][x+n-1]=='/' and "".join(m[y+n-1][x+1:x+n-1])=='_'*(n-2): t.append((x,y,n)) for x,y,n in t: def a(v,h,c): w=x+h; z=y+v; if z>=0 and z<len(m): if w>=0 and w<len(m[y]): m[z][w]=c for v in range(n): for h in range(n): a(v,h,' ') a(0,0,'O') a(0,n-1,'O') a(n/2,n/2,'O') a(n-1,0,'\\') a(n-1,n-1,'/') for w in range(1,n-1): a(n-1,w,'_') for v in [-1,n]: for h in range(n): a(v,h,'-') for h in [-1,n]: for v in range(n): a(v,h,'|') a(-1,-1,'+') a(-1,n,'+') a(n,-1,'+') a(n,n,'+') for l in m: for c in l: sys.stdout.write(c) print ``` Here's the more readable code : ``` #!/usr/bin/env python import fileinput, sys matrix = [[c for c in l if c != '\n'] for l in fileinput.input()] max_X = len(matrix[0]) max_Y = len(matrix) tuples = [] for n in range(3, min(max_X, max_Y)+1, 2): for x in range(max_X-n+1): for y in range(max_Y-n+1): # if is_face(matrix, x, y, n): if matrix[y][x] == 'O' and matrix[y][x+n-1] == 'O' and matrix[y+(n//2)][x+(n//2)] == 'O' and matrix[y+n-1][x] == '\\' and matrix[y+n-1][x+n-1] == '/' and "".join(matrix[y+n-1][x+1:x+n-1]) == '_'*(n-2) : tuples.append((x, y, n)) for x,y,n in tuples: # blank_and_border(matrix,x,y,n) def assign(dy, dx, c): xx = x + dx; yy = y + dy; if yy >= 0 and yy < len(matrix) : if xx >= 0 and xx < len(matrix[y]) : matrix[yy][xx] = c # blank for dy in range(n): for dx in range(n): assign(dy, dx, ' ') # face assign(0, 0, 'O') assign(0, n-1, 'O') assign(n/2, n/2, 'O') assign(n-1, 0, '\\') assign(n-1, n-1, '/') for w in range(1,n-1): assign(n-1, w, '_') # border for dy in [-1,n]: for dx in range(n): assign(dy, dx, '-') for dx in [-1,n]: for dy in range(n): assign(dy, dx, '|') assign(-1, -1, '+') assign(-1, n, '+') assign( n, -1, '+') assign( n, n, '+') for l in matrix: for c in l: sys.stdout.write(c) print ``` ]
[Question] [ Here is a diagram of a prison using ASCII characters: ``` +------------------------------+ | | | X X | | | | D D | | | | | | X X X | | | +------------------------------+ ``` Walls are made out of pipe characters `|`, dashes `-`, and pillars `+` for corners and intersections. There are also two doors marked with `D` (which will always be on the left and right walls). The prison is filled with scary people marked with `X`. The goal is to build walls to satisfy the following: 1. Each person is in solitary confinement; 2. There is a corridor running between the two doors; 3. Each cell contains exactly one door, which is directly connected to the main corridor; 4. All space in the prison is used by the cells and the corridor; 5. Each cell contains a person (that is, there are no empty cells). The corridor is a single path, doesn't branch off, and is always one character wide. Here's a solution for the prison above: ``` +---------+--------------------+ | | | | X | X | | | +--------+ +------D--+-----D-----+ D D +---D--+ +----D--------+---D-----+ | | | | | | X | X |X | | | | | +-------------+---------+------+ ``` You can assume that any input prison will always have a valid output. Here are some more input prisons, along with possible outputs: ``` +------------------------------+ |X X X X X X X X X X X X X X X | | | D D | | | X | +------------------------------+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+--+ |X|X|X|X|X|X|X|X|X|X|X|X|X|X|X | +D+D+D+D+D+D+D+D+D+D+D+D+D+D+D-+ D D +----------------------D-------+ | X | +------------------------------+ +-----------+ |X | | | | | |X X| | | | X| | | D D +-----------+ +-+-------+-+ |X| D | | D +---+ | | +-+ | | | |X| | +---+X| | | | | +-+ | D | | X| +-+ | +-D---+ D | D +---+-------+ +----------------+ |X X X X| | | D | | | |X X X | | | | | | | | X X D | | | | +----------------+ +---+---+----+---+ |X | X | X | X| +--D+--D+---D+--D+ D | +---+---+------+ | |X | X | X | | +--D+--D+---D--+ | | | | +-----+------+-+ | | X | X | D | +----D+---D--+ | | | +----------------+ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~2986~~ ~~2881~~ ~~2949~~ ~~2135~~ ~~2075~~ ~~2071~~ 1996 bytes * Saved 105 bytes, implemented the program as a function to comply with standard rules. Implemented Wheat Wizard's tab and space suggestion. * Added 68 bytes due to fixing a bug. * Saved 814+51 bytes thanks to Halvard Hummel. * Saved 9+4 bytes. * Saved 4 bytes thanks to Erik the Outgolfer. * Saved 71 bytes thanks to ppperry's suggestion. ``` exec r"""def Z(P): H,n,I,o,O,i,d,D,W=[type,range]+list(" dD#xX*");R=(1,0),(-1,0),(0,1),(0,-1) def F(j,k,l):P[j][k]=l def E(j,k,v,w): if G(j,k,v):F(k,j,w) def q(b,c,d):[[E(j+J,k+K,b,c)for J,K in M]&L if G(j,k,d)] def A(e,r,l,o,q): S,E,P[q][o],Q,X=P[q][o],e,0,[(o,q)],0 for a,b in Q: &R: x,y=a+j,b+k if(0<=x<w!=0<=y<h)<1:continue if e in((x,y),P[y][x]):X=1;e=x,y;break if I!=P[y][x]:continue F(y,x,P[b][a]+1);Q+=[(x,y)] if X:break p,i=e,0 while(o,q)!=p: a,b=p;P[b][a],m=[r,l][l and i==1],0 &R: x,y=a+j,b+k if(0<=x<w!=0<=y<h)-1:continue if(H(P[y][x])==H(0))*(m==0 or P[y][x]<P[m[1]][m[0]]):m=x,y p=m;i+=1 P[q][o],P[e[1]][e[0]]=S,E;[F(k,j,I)&L if H(P[k][j])==H(0)] def B(N): [[E(j,k,"x*",I),0<j<w-1 and E(j,k,O,I)]&L] &L: if G(j,k,D):[E(j+J,k+K,I,d)for J,K in M] if G(j,k,O)and j==0:T=0,k if N:A(O,o,0,*T) U,V=M[-1];[[[F(k+K,j+J,I)for J,K in M if(P[k+K][j+J]!=i)*((0<=j+J+U<w!=0<=k+K+V<h and G(j+J+U,k+K+V,D))<1)],F(k,j,W),A(o,W,O,j,k),q(I,d,W),F(k,j,D)]&L if G(j,k,D)];q("xX*# @+-|",i,o) for j in"|+-":P=P.replace(j,i) P=list(map(list,P.split("\n")));h=len(P);w=len(P[0]);b,L,M,G="#+-|D",[(k,j)for k in n(w)for j in n(h)],[(k-1,j-1)for k in n(3)for j in n(3)if(j,k)!=(1,1)],lambda j,k,v:P[k][j]in v B(1);Y=lambda:0<j<w-1!=0<k<h-1and G(j,k,i);[[[F(k,j,o),F(k+g,j+N,i)]for N,g in((-1,-1),(-1,1),(1,-1),(1,1))if P[k][j+g]+P[k][j-g]==P[k+N][j+g]+P[k-N][j]==P[k+N][j]+i==o+i]&L if(j in(1,w-2)or k in(1,h-2))*Y()for N in n(w*h)];[F(k,j,I)&L if Y()];B(0) def c(x,y,b,l,d,f,Q): F(y,x,b) for J,K in M:Q+=[[],[(x+J,y+K)]][G(x+J,y+K,l)];E(x+J,y+K,d,f) &L: if G(j,k,D):Q=[(j,k)];[c(x,y,"@",W,d,I,Q)for x,y in Q if G(x,y,"X*")];[G(u,v,"X*")and[E(u+U,v+V,I,d)for U,V in M]or E(u,v,"@",I)for u,v in L];Q=Q[:1];[c(x,y,"$",I,"x*",i,Q)for x,y in Q];F(k,j,D) &L:E(j,k,"@$d",I);X=(k>0and G(j,k-1,b))+(k<h-1and G(j,k+1,b))-(j>0and G(j-1,k,b))-(j<w-1and G(j+1,k,b));E(j,k,i,{2:"+",X:"|",-X:"-"}[2]) print"\n".join("".join(p)for p in P)""".replace("&","for j,k in ") ``` [Try it online!](https://tio.run/##rVdrU@M2FP1MfoUwHUbCMhOzne6MHXVgG94sJNvdxbuuPjjESZyHY0xCkpb@dnokORDCY6FtmLGlq6v7POcmZLNRZ5hu3a6Rml6Rrc335LdhM/bJJE9GozgljRk5GqbRqBOlZC@PLzo@@XnUIVHaJL/gPWyRnXF7fDUiW2X3fWmN7I3zUSfOSXvYb8VNchD1r6Mc7/FgEPf5I1tKLUnb5GrcbsdXo2SYXpFJnMdkEDVj5fy8E0cjcp78qawor7t50iNwQc7GI@0kh9f9R2bU3SzL4jyf@aT1MCgcPbZyG0/jC5JbltWMW@Q7rTGvRA54yg/5kJ/xhDd5lZ@LcDTLYp5HaTuWdj@5GlGLNKtr02DDYv4nQV1eZpw65lXmrn46LisRZXaPdnmP95lXC7sy7EnRN/JdLb/mEzhdSVpk3@yZt0d7vAuxUbukDX7Bm8wLQ9ywj3jPPuYQsdYwJ0f8mCQp@SjXT8idiSaT5uoORdS8j1wulY/f@S6vhZcyHEpe54GYr2Ne5iFVSpKXSyvKbsQ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ereGc69EwFXmP4nr7jpbVucUsTg2ueWOy2JsJSCTol23nxY5duyIufG60QLEmDZYUfWnjhUy1V/6OFtygES2kEr7Xwo0qi2qHrSf7augfkpb9XBFT9UVnfWrXgf8xZJ/iMq0e7e83gBc1HZ9UH2dpvaMY8uoXHEwV/osRPai3bekbrDaIFW9VXXrT/FSBtk2KwjICnwBPcuw6W0fIcXG9etvMIeHfy4MkiB6@l5XPJ2/ctXQjhyWVgfAZLCgtAmzsplaSv/nuy7n6c1LzvtMt8M8hv/wE "Python 2 – Try It Online") It was golfed down significantly; yet there may still be room for improvement. This piece of code, however, solves all test cases. Does not run very efficiently; for large prisons the architect may take their time to figure it out. Uses a simple pathfinding algorithm to connect both doors and the prisoners to the corridor. Then it encapsulates all prisoners and their walls and pushes said walls in empty space until all of it is filled. As a final step, the ASCII art appearance is implemented. Took me for sure several hours to write. I hope it also works on other prisons than the test cases. (You cannot test them all, can you?) [Answer] ## C, ~~3732~~ 3642 bytes I could definitely golf this a bit further, but it is a pretty nice start. I did not initially know that my approach had a name so shout out to @TehPers for giving me a name to research. I definitely enjoyed the challenge that this question offered. :) -63 bytes from @Jonathan's suggestions. I also replaced `char` with `typedef char R` and replaced all character literals that are smaller than 100 with their ASCII values for a total of 90 bytes A quick explanation of my code. 1. Convert char array to an ideal integer array (0 is space, 1 is wall, etc.) 2. Generate the Voronoi diagram using the people as the points 3. Use the intersections (a 5 surrounded by at least three other 5s) as pivot points for the path 4. Create the corridor using a directionally biased path finding algorithm (if it's going one way, favor paths that do not change direction). It also modifies the grid so that it favors traveling next to an already made corridor. 5. Regenerate diagram to place final walls. Ensures that all space is used. 6. Convert map back to a properly formatted ASCII representation and print. To use this program, pass the map as either a string with newline characters or with each level seperated by a space as in the following example. ``` program-name.exe "+-----------+ |X | | | | | |X X| | | | X| | | D D +-----------+ " +------+----+ |X | | | +D+-+ | +----+ | | |X | + D X| | | | +--+ | | | | X| +D---+ | +-D+ D | D +------+----+ ``` code ``` typedef int Q;typedef char R;typedef struct{Q x,y,v;}P;w,h,A,Y,Z,x,y,i,j,e,f,m,n,v;P*t,*u,*s;I(R*a,Q x,Q y,R c){a[x+y*w]=c;}G(Q*a,Q x,Q y){if(x>-1&&x<w&&y>-1&&y<h)return a[x+y*w];return-1;}J(Q*a,Q x,Q y,Q c){a[x+y*w]=c;}P*E(Q n,Q*a,Q*c){P*r=0;for(i=v=0;i<A;i++)if(a[i]==n)r=(P*)realloc(r,sizeof(P)*(v+1)),r[v].x=i%w,r[v].y=i/w,r[v].v=v,*c=++v;return r;}C(Q*a,Q x,Q y,Q b){return(G(a,x-1,y)==b)+(G(a,x+1,y)==b)+(G(a,x,y-1)==b)+(G(a,x,y+1)==b);}H(Q*a,Q b){P q[A],r[A];m=Y,n=0;for(i=0;i<Y;i++)q[i]=t[i];while(m){while(m){x=q[m-1].x,y=q[m-1].y,v=q[m-1].v;i=G(a,x,y);if(i!=b&&i!=1){for(f=-1;f<2;f++){for(e=-1;e<2;e++){i=G(a,x+e,y+f);if(i==0){J(a,x+e,y+f,v+8);r[n].x=x+e;r[n].y=y+f;r[n].v=v;n++;}else if(i>=8&&i!=v+8)J(a,x+e,y+f,b);}}}m--;}for(i=0;i<n;i++)q[i]=r[i];m=n;n=0;}}B(P p,Q*a,Q*b){for(i=m=n=0;i<A;i++)if(b[i]>-2)b[i]=-1;P q[A],r[A];q[0]=p,q[0].v=0,b[p.x+p.y*w]=0;while(m+1){while(m+1){x=q[m].x,y=q[m].y,v=q[m].v;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0||(x+e<0||x+e>=w||y+f<0||y+f>=h))continue;i=G(a,x+e,y+f);if(i!=7&&i!=1&&i!=0){j=3;if(i==4||i==5)j=1;if(x+e!=p.x&&y+f!=p.y)j++;Q*p=&b[x+e+(y+f)*w];if(*p!=-2&&(*p==-1||*p>v+j)){*p=v+j;if(i!=2)r[n].x=x+e,r[n].y=y+f,r[n].v=v+j,n++;}}}}m--;}for(i=0;i<n;i++){q[i]=r[i];}m=n-1,n=0;}}D(P S,P*T,Q n,P U,Q*a){Q m[A];Q x,y,v=0,c=0,d=1,d1=1;for(i=0;i<n;i++)T[i].v=0;for(i=0;i<A;i++)m[i]=-1;x=S.x,y=S.y;if(n==0){B(U,a,m);goto fin;}while(v<n){j=-1;for(i=0;i<n;i++)if(T[i].v==0)if(j==-1||abs(T[i].x-x)+abs(T[i].y-y)-(T[i].x==x)*!d*2-(T[i].y==y)*d*2<abs(T[j].x-x)+abs(T[j].y-y)-(T[j].x==x)*!d*2-(T[j].y==y)*d*2)j=i;T[j].v=1;B(T[j],a,m);fin:v++;c=m[x+y*w];while(c>0||c==-1){Q tx,ty;j=-1;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0)continue;if(x+e<0||x+e>=w||y+f<0||y+f>=h)continue;i=G(m,x+e,y+f);if(i>-1&&(i<c||c==-1)){if(j==-1||j>i||((e*d||f*!d)&&j==i)){j=i;tx=x+e,ty=y+f;d1=e!=0;}}}}J(m,x-1*!d1,y-1*d1,-2);J(m,x+1*!d1,y+1*d1,-2);d=d1;x=tx,y=ty,c=j;if(G(a,x,y)!=2)J(a,x,y,0);}for(f=0;f<h;f++)for(e=0;e<w;e++)if((i=G(a,e,f))>3&&i!=7)if(C(m,e,f,-2))J(a,e,f,5);if(v==n){B(U,a,m);goto fin;}}}main(Q c,R**v){R*a=v[1];w=strchr(a,'|')-a;h=(strchr(a+w,43)-a)/w+1;A=w*h;Q p[A];for(y=0;y<h;y++)for(x=0;x<w;x++){c=a[x+y*w];J(p,x,y,0);if(c==45||c=='|'||c==43)J(p,x,y,1);if(c==68)J(p,x,y,2);if(c==88)J(p,x,y,3);}t=E(3,p,&Y);u=E(2,p,&Z);H(p,5);for(c=0;c<Y;c++)for(y=-1;y<2;y++)for(x=-1;x<2;x++)if(G(p,t[c].x+x,t[c].y+y)>=4)J(p,x+t[c].x,y+t[c].y,7);for(y=1;y<h-1;y++)for(x=1;x<w-2;x++)if(G(p,x,y)==5)if(C(p,x,y,5)>2)J(p,x,y,4);s=E(4,p,&c);for(i=0;i<c;i++)s[i].v=0;for(y=1;y<h-1;y++)for(x=1;x<w-2;x++)if(G(p,x,y)>=8)if(C(p,x,y,5))J(p,x,y,4);i=u[0].x!=0;D(u[i],s,c,u[!i],p);for(y=0;y<h;y++){for(x=0;x<w;x++){i=0;if(G(p,x,y)>2){for(f=-1;f<2;f++)for(e=-1;e<2;e++)i+=G(p,x+e,y+f)==0;if(i>0)J(p,x,y,6);}}}free(s);for(i=0;i<A;i++)if(p[i]>=7||p[i]==4||p[i]==5)p[i]=0;for(y=0;y<h;y++){for(x=0;x<w-1;x++){if((x==0||x==w-2||y==0||y==h-1)&&G(p,x,y)!=2)J(p,x,y,1);}}H(p,1);P q[A],r[A];for(i=0;i<Y;i++){m=1,n=0;q[0]=t[i];while(m){while(m){x=q[m-1].x,y=q[m-1].y;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0)continue;c=G(p,x+e,y+f);if(c==6){if(G(p,x+e*2,y+f*2)==0){J(p,x+e,y+f,2);m=1,n=0;e=f=2;}}else if(c!=1&&c!=3&&c!=7){J(p,x+e,y+f,7);r[n].x=x+e;r[n].y=y+f;n++;}}}m--;}for(c=0;c<n;c++)q[c]=r[c];m=n;n=0;}}for(i=0;i<A;i++)if(p[i]==6)p[i]=1;R b[A];for(y=0;y<h;y++){for(x=0;x<w;x++){c=G(p,x,y);I(b,x,y,32);if(c==1){i=0;if(G(p,x,y-1)==1||G(p,x,y-1)==2)i|=1;if(G(p,x,y+1)==1||G(p,x,y+1)==2)i|=2;if(G(p,x-1,y)==1||G(p,x-1,y)==2)i|=4;if(G(p,x+1,y)==1||G(p,x+1,y)==2)i|=8;if(i==3)I(b,x,y,'|');else if(i==12)I(b,x,y,45);else I(b,x,y,43);}if(c==2)I(b,x,y,68);if(c==3)I(b,x,y,88);if(x==w-1)I(b,x,y,10);}}b[A-1]=0;puts(b);} ``` ]
[Question] [ Some people insist on using spaces for tabulation and indentation. For tabulation, that's indisputably wrong. By definition, tabulators must be used for tabulation. Even for indentation, tabulators are objectively superior: * There's [clear consensus](https://softwareengineering.stackexchange.com/a/72) in the Stack Exchange community. * Using a single space for indentation is visually unpleasant; using more than one is wasteful. As all cod~~e golf~~ers know, programs should be as short as possible. Not only does it save hard disk space, compilation times are also reduced if less bytes have to be processed. * By adjusting the tab width1, the same file looks different on each computer, so everybody can use his favorite indent width without modifying the actual file. * All good text editors use tabulators by default (and definition). * I say so and I'm always right! Sadly, not everybody listens to reason. Somebody has sent you a file that is doing it wrongTM and you have to fix it. You could just do it manually, but there will be others. It's bad enough that spacers are wasting your precious time, so you decide to write the shortest possible program to take care of the problem. ### Task Write a program or a function that does the following: 1. Read a single string either from STDIN or as a command-line or function argument. 2. Identify all locations where spaces have been used for tabulation or indentation. A run of spaces is **indentation** if it occurs at the beginning of a line. A run of *two or more* spaces is **tabulation** if it isn't indentation. A *single* space that is not indentation may or may not have been used for tabulation. As expected when you use the same character for different purposes, there's no easy way to tell. Therefore, we'll say that the space has been used for **confusion**. 3. Determine the longest possible tab width1 for which all spaces used for tabulation or indentation can be replaced with tabulators, without altering the appearance of the file. If the input contains neither tabulation, nor indentation, it is impossible to determine the tab width. In this case, skip the next step. 4. Using the previously determined tab width, replace all spaces used for tabulation or indentation with tabulators. Also, whenever possible without altering the appearance of the file, replace all spaces used for confusion with tabulators. (If in doubt, get rid of spaces.) 5. Return the modified string from your function or print it to STDOUT. ### Examples * All spaces of ``` a bc def ghij ``` are tabulation. Each run of spaces pads the preceding string of non-space characters to a width of 5, so the correct tab width is 5 and the correct output2 is ``` a--->bc-->def->ghij ``` * The first two spaces of ``` ab cde f ghi jk lm ``` are tabulation, the others confusion. The correct tab width is 4, so the correct output2 is ``` ab->cde>f ghi>jk lm ``` The last space remains untouched, since it would be rendered as *two* spaces if replaced by a tabulator: ``` ab->cde>f ghi>jk->lm ``` * All but one spaces of ``` int main( ) { puts("TABS!"); } ``` are indentation, the other is confusion. The indentation levels are 0, 4 and 8 spaces, so the correct tab width is 4 and the correct output2 is ``` int --->main( ) --->{ --->--->puts("TABS!"); --->} ``` The space in `( )` would be rendered as three spaces if replaced by a tabulator, so it remains untouched. * The first two spaces of ``` x yz w ``` are indentation, the others confusion. The proper tab width is 2 and the correct output2 is ``` ->x>yz w ``` The last space would be rendered as two spaces if replaced by a tabulator, so it remains untouched. * The first two spaces of ``` xy zw ``` are indentation, the other three are tabulation. Only a tab width of 1 permits to eliminate all spaces, so the correct output2 is ``` >>xy>>>zw ``` * All spaces of ``` a b c d ``` are confusion. There is no longest possible tab width, so the correct output2 is ``` a b c d ``` ### Additional rules * The input will consist entirely of printable ASCII characters and linefeeds. * You may assume that there are at most 100 lines of text and at most 100 characters per line. * If you choose STDOUT for output, you may print a single trailing linefeed. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. --- 1 The tab width is defined as the distance in characters between two consecutive [tab stops](https://en.wikipedia.org/wiki/Tab_stop), using a monospaced font. 2 The ASCII art arrows represent the tabulators Stack Exchange refuses to render properly, for which I have submitted a bug report. The actual output has to contain actual tabulators. [Answer] # Pyth, ~~102~~ 103 bytes ``` =T|u?<1hHiGeHGsKmtu++J+hHhGlhtH+tG]+HJ.b,YN-dk<1u+G?H1+1.)Gd]0]0cR\ .zZ8VKVNp?%eNT*hNd*/+tThNTC9p@N1)pb ``` [Try it Online](https://pyth.herokuapp.com/?code=%3DT|u%3F%3C1hHiGeHGsKmtu%2B%2BJ%2BhHhGlhtH%2BtG]%2BHJ.b%2CYN-dk%3C1u%2BG%3FH1%2B1.%29Gd]0]0cR%5C+.zZ8VKVNp%3F%25eNT*hNd*%2F%2BtThNTC9p%40N1%29pb&input=int%0A++++mai+n%28+%29%0A++++%7B%0A++++++++pu++ts+0+%28%22TABS!%22%29%3B%0A++++%7D&test_suite_input=+%0A~%0A0%0A1&debug=0) Interesting idea, but since tabs in the input break the concept, not very usable. Edit: Fixed bug. many thanks @aditsu [Answer] # PowerShell, ~~414~~ 409 bytes ``` function g($a){if($a.length-gt2){g $a[0],(g $a[1..100])}else{if(!$a[1]){$a[0]}else{g $a[1],($a[0]%$a[1])}}}{$a[0]}else{g $a[1],($a[0]%$a[1])}}} $b={($n|sls '^ +|(?<!^) +' -a).Matches} $n=$input-split"`n" $s=g(&$b|%{$_.Index+$_.Length}) ($n|%{$n=$_ $w=@(&$b) $c=($n|sls '(?<!^| ) (?! )'-a).Matches $w+$c|sort index -d|%{$x=$_.Index $l=$_.Length if($s-and!(($x+$l)%$s)){$n=$n-replace"(?<=^.{$x}) {$l}",("`t"*(($l/$s),1-ge1)[0])}} $n})-join"`n" ``` I went ahead and used newlines instead of `;` where possible to make display easier. I'm using unix line endings so it shouldn't affect the byte count. ## How To Execute Copy code into `SpaceMadness.ps1` file, then pipe the input into the script. I will assume the file that needs converting is called `taboo.txt`: From PowerShell: ``` cat .\taboo.txt | .\SpaceMadness.ps1 ``` From command prompt: ``` type .\taboo.txt | powershell.exe -File .\SpaceMadness.txt ``` I tested it with PowerShell 5, but it should work on 3 or higher. ## Testing Here's a quick PowerShell scrip that's useful for testing the above: ``` [CmdletBinding()] param( [Parameter( Mandatory=$true, ValueFromPipeline=$true )] [System.IO.FileInfo[]] $File ) Begin { $spaces = Join-Path $PSScriptRoot SpaceMadness.ps1 } Process { $File | ForEach-Object { $ex = Join-Path $PSScriptRoot $_.Name Write-Host $ex -ForegroundColor Green Write-Host ('='*40) -ForegroundColor Green (gc $ex -Raw | & $spaces)-split'\r?\n'|%{[regex]::Escape($_)} | Write-Host -ForegroundColor White -BackgroundColor Black Write-Host "`n" } } ``` Put this in the same directory as `SpaceMadness.ps1`, I call this one `tester.ps1`, call it like so: ``` "C:\Source\SomeFileWithSpaces.cpp" | .\tester.ps1 .\tester.ps1 C:\file1.txt,C:\file2.txt dir C:\Source\*.rb -Recurse | .\tester.ps1 ``` You get the idea. It spits out the contents of each file after conversion, run through `[RegEx]::Escape()` which happens to escape both spaces and tabs so it's really convenient to see what's actually been changed. The output looks like this (but with colors): ``` C:\Scripts\Powershell\Golf\ex3.txt ======================================== int \tmain\(\ \) \t\{ \t\tputs\("TABS!"\); \t} ``` # Explanation The very first line defines a greatest common factor/divisor function `g` as succinctly as I could manage, that takes an array (arbitrary number of numbers) and calculates GCD recursively using the [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm). The purpose of this was to figure out the "longest possible tab width" by taking the index + length of every **indentation** and **tabulation** as defined in the question, then feeding it to this function to get the GCD which I think is the best we can do for tab width. A confusion's length will always be 1 so it contributes nothing to this calculation. `$b` defines a scriptblock because annoyingly I need to call that piece of code twice, so I save some bytes that way. This block takes the string (or array of strings) `$n` and runs a regex on it (`sls` or `Select-String`), returning match objects. I'm actually getting both indentations and tabulations in one here, which really saved me extra processing by capturing them separately. `$n` is used for different things inside and outside the main loop (really bad, but necessary here so that I can embed it in `$b`'s scriptblock and use that both inside and outside the loop without a lengthy `param()` declaration and passing arguments. `$s` gets assigned the tab width, by calling the `$b` block on the array of lines in the input file, then summing the index and length of each match, returning the array of the sums as an argument into the GCD function. So `$s` has the size of our tab stops now. Then the loop starts. We iterate over each line in the array of input lines `$n`. The first thing I do in the loop is assign `$n` (local scope) the value of the current line for the above reason. `$w` gets the value of the scriptblock call for the current line only (the indentations and tabulations for the current line). `$c` gets a similar value, but instead we find all the **confusions**. I add up `$w` and `$c` which are arrays, giving me one array with all of the space matches I need, `sort` it in descending order by index, and begin iterating over each match for the current line. The sort is important. Early on I found out the hard way that replacing parts of a string based on index values is a bad idea when the replacement string is smaller and changes the length of the string! The other indexes get invalidated. So by starting with the highest indexes on each line, I make sure I only make the string shorter from the end, and move backwards so the indexes always work. Into this loop, `$x` is in the index of the current match and `$l` is the length of the current match. `$s` can in fact be `0` and that causes a pesky divide by zero error so I'm checking for its validity then doing the math. The `!(($x+$l)%$s)` bit there is the single point where I check to see if a **confusion** should be replaced with a tab or not. If the index plus the length divided by the tab width has no remainder, then we're good to go in replacing this match with a tab (that math will always work on the **indentations** and **tabulations**, because their size is what determined the tab width to begin with). For the replace, each iteration of the match loop works on the current line of the input, so it's a cumulative set of replaces. The regex just looks for `$l` spaces that are preceded by `$x` of any character. We replace it with `$l/$s` tab characters (or 1 if that number is below zero). This part `(($l/$s),1-ge1)[0]` is a fancy convoluted way of saying `if (($l/$s) -lt 0) { 1 } else { $l/$s }` or alternatively `[Math]::Max(1,($l/$s))`. It makes an array of `$l/$s` and `1`, then uses `-ge 1` to return an array containing only the elements that are greater than or equal to one, then takes the first element. It comes in a few bytes shorter than the `[Math]::Max` version. So once all of the replaces are done, the current line is returned from the `ForEach-Object` (`%`) iteration, and when all of them are returned (an array of fixed lines), it's `-join`ed with newlines (since we split on newlines in the beginning). I feel like there's room for improvement here that I'm too burnt out to catch right now, but maybe I'll see something later. > > Tabs 4 lyfe > > > [Answer] ## PHP - ~~278~~ 210 bytes The function works by testing each tab width, starting with a value of 100, the maximal length of a line and therefore the maximal tab width. For each tab width, we split each line into "blocks" of that length. For each of this blocks: * If, by concatenating the last character of the previous block with this block, we find two consecutive spaces before a character, we have an indentation or a tabulation that can't be transformed to space without altering the appearance; we try the next tab width. * Otherwise, if the last character is a space, we strip spaces at end of the block, add a tabulator and memorise the whole thing. * Otherwise, we just memorise the block. Once each blocks of a line have been analysed, we memorise a linefeed. If all the blocks of all the lines were analysed with success, we return the string we've memorised. Otherwise, if each strictly positive tab width have been tried, there was neither tabulation, nor indentation, and we return the original string. ``` function($s){for($t=101;--$t;){$c='';foreach(split(' ',$s)as$l){$e='';foreach(str_split($l,$t)as$b){if(ereg(' [^ ]',$e.$b))continue 3;$c.=($e=substr($b,-1))==' '?rtrim($b).' ':$b;}$c.=' ';}return$c;}return$s;} ``` Here is the ungolfed version: ``` function convertSpacesToTabs($string) { for ($tabWidth = 100; $tabWidth > 0; --$tabWidth) { $convertedString = ''; foreach (explode("\n", $string) as $line) { $lastCharacter = ''; foreach (str_split($line, $tabWidth) as $block) { if (preg_match('# [^ ]#', $lastCharacter.$block)) { continue 3; } $lastCharacter = substr($block, -1); if ($lastCharacter == ' ') { $convertedString .= rtrim($block) ."\t"; } else { $convertedString .= $block; } } $convertedString .= "\n"; } return $convertedString; } return $string; } ``` Special thanks to [DankMemes](https://codegolf.stackexchange.com/users/20666/dankmemes) for saving 2 bytes. [Answer] # CJam, 112 ``` qN/_' ff=:e`{0:X;{_0=X+:X+}%}%_:+{~;\(*},2f=0\+{{_@\%}h;}*:T;\.f{\~\{@;1$({;(T/)9c*}{\;T{T%}&S9c?}?}{1$-@><}?}N* ``` [Try it online](http://cjam.aditsu.net/#code=qN%2F_'%20ff%3D%3Ae%60%7B0%3AX%3B%7B_0%3DX%2B%3AX%2B%7D%25%7D%25_%3A%2B%7B~%3B%5C(*%7D%2C2f%3D0%5C%2B%7B%7B_%40%5C%25%7Dh%3B%7D*%3AT%3B%5C.f%7B%5C~%5C%7B%40%3B1%24(%7B%3B(T%2F)9c*%7D%7B%5C%3BT%7BT%25%7D%26S9c%3F%7D%3F%7D%7B1%24-%40%3E%3C%7D%3F%7DN*&input=ab%20%20cde%20f%0Aghi%20jk%20lm) I had to answer this challenge, because I must do my part to help rid the world of this abomination. Tabs are obviously superior, but sadly, some people just can't be reasoned with. **Explanation:** ``` qN/ read input and split into lines _ duplicate the array (saving one copy for later) ' ff= replace each character in each line with 0/1 for non-space/space :e` RLE-encode each line (obtaining chunks of spaces/non-spaces) {…}% transform each line 0:X; set X=0 {…}% transform each chunk, which is a [length, 0/1] array _0= copy the first element (the length) X+:X increment X by it + and append to the array; this is the end position for the chunk _ duplicate the array (saving one copy for later) :+ join the lines (putting all the chunks together in one array) {…}, filter the array using the block to test each chunk ~ dump the chunk (length, 0/1, end) on the stack ; discard the end position \( bring the length to the top and decrement it * multiply the 2 values (0/1 for non-space/space, and length-1) the result is non-zero (true) iff it's a chunk of at least 2 spaces 2f= get all the end positions of the multiple-space chunks 0\+ prepend a 0 to deal with the empty array case {…}* fold the array using the block {_@\%}h; calculate gcd of 2 numbers :T; save the resulting value (gcd of all numbers) in variable T \ swap the 2 arrays we saved earlier (input lines and chunks) .f{…} for each chunk and its corresponding line \~ bring the chunk to the top and dump it on the stack (length, 0/1, end position) \ swap the end position with the 0/1 space indicator {…} if 1 (space) @; discard the line text 1$( copy the chunk length and decrement it {…} if non-zero (multiple spaces) ; discard the end position (T/) divide the length by T, rounding up 9c* repeat a tab character that many times {…} else (single space) \; discard the length T{…}& if T != 0 T% calculate the end position mod T S9c? if non-zero, use a space, else use a tab ? end if {…} else (non-space) 1$- copy the length and subtract it from the end position to get the start position of the chunk @> slice the line text beginning at the start position < slice the result ending at the chunk length (this is the original chunk text) ? end if N* join the processed lines using a newline separator ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~165~~ ~~160~~ ~~153~~ ~~152~~ ~~142~~ ~~138~~ 137 bytes ``` param($s)@((0..99|%{$s-split"( |..{0,$_})"-ne''-replace(' '*!$_*($s[0]-ne32)+' +$'),"`t"-join''})-notmatch'(?m)^ |\t '|sort{$_|% Le*})[0] ``` [Try it online!](https://tio.run/##XVJZT8MwDH7PrzAlI8nWThM8IYQYPPMGbxxLj4x19KLxtKPtbx9uaWEiUiz7O2xZSZFvTWlXJkmOfAm3UB0Lv/RTya2aSzmbTq@v61HFrWeLJEZHsno6rWYuXzTK8TIjhFeaIvFDIwWI8RlfjMn6Mnsj7upSTQRMuFCuo9Hx1nmcCdEoL8sx9TFcCXmXqneoXxFEbfMSK76oR/Boxo2iFseGsblkzJVzh/lAJwgpRGYJ8LGK18yZuy2jMQg1Eqyxh9VgCgDCyMCSEQHrT0jSwRRoJEZjR2kcuMEZZ8jaiakfZxJUl1ddbE@xQSud5/uHpzNH3XRw0zdujRoHm8aKrsZ/Bo3NySyAHewPsO07aNxp7OsTyZ6GHP40pNq3UePhVOhDACFEw5a/FfEKahj1S3DrAje7woRoInp1vviBS2M3CRJwQZ@B21PQM1@/jg4/H9SUwiYL8zQ1GQKuYgtJnBnAHKKYvo2/hx@lZc3xGw "PowerShell – Try It Online") Less golfed: ``` param($spacedString) $tabed = 0..99|%{ $spacedString ` -split "(\n|..{0,$_})" -ne '' ` -replace (' '*!$_*($spacedString[0]-ne32)+' +$'),"`t" ` -join '' } $validated = $tabed -notmatch '(?m)^ |\t ' $sorted = $validated|sort{$_|% Length} # sort by a Length property @($sorted)[0] # $shortestProgram is an element with minimal length ``` ]
[Question] [ ### The challenge The goal of this challenge is to create a chatbot that can run in the chatrooms of Stack Exchange. Your bot needs to be able to detect when specific commands are posted by a user and respond to it. This is the list of commands, and what your bot should do: * `!!newest`: output the title (no link, but the title) of the newest question posted on this site (codegolf.SE). * `!!metanewest`: output the title of the newest question posted on the meta site (meta.codegolf.SE). * `!!questioncount`: output the current question count. * `!!metaquestioncount`: output the current question count on the meta site. * `!!tag tagname`: output the tag excerpt (the short description) of the tag that's given as the first parameter. * `!!metatag tagname`: same as above, but for the meta site. * `!!featured`: output the count of questions that currently have a bounty. * `!!metafeatured`: output the count of questions that have the [[featured]](http://meta.codegolf.stackexchange.com/questions/tagged/featured) tag on Meta. ## Rules 1. You should write a complete program, not a snippet or function. 2. In case it's necessary, you can request username and password as input (prompting for input, STDIN, command-line arguments). This will be necessary if you use, for example, Python or Ruby, but it won't be necessary if you use JavaScript and run the script on the chat room page itself. 3. You are allowed to use external libraries to do stuff like WebSockets. These libraries do not have to count for your character count. 4. You *can* use an external chat wrapper (but you don't have to, writing your own is encouraged), and then that has to count for the character count. You also are not allowed to change the wrapper's code. If you use it, you use it without modifications and all characters have to be counted (that's as a penalty for not writing your own wrapper). Only the code of the wrapper itself has to count. If there are other files such as examples, these don't have to count. 5. No use of URL shorteners or other ways that can make URLs shorter: the challenge is to golf a chatbot, not to golf a URL. 6. No web requests, except those necessary to chat and to get the information necessary to respond to the commands. 7. Use of the [Standard "loopholes"](http://meta.codegolf.stackexchange.com/q/1061/9275) is not allowed. 8. If someone posts a command, you need to respond with a chat message of this format: `@user response`. So, if I write the command `!!featured` and there are 5 featured questions, your bot should post `@ProgramFOX 5`. 9. If I test your bot, I'll run it from my [chatbot account](https://codegolf.stackexchange.com/users/21569/fox-9000) and I'll run it in [this chatroom](http://chat.stackexchange.com/rooms/14697/chatbot-challenge-on-programming-puzzles-code-golf). I will always test the bots in that room, so it is not necessary to provide room ID as input, it will always be 14697. This ID won't be given as input, it should be hard-coded. 10. If the command is not found, output `@user The command [command] does not exist`. Replace `[command]` by the name of the non-existing command. If arguments are provided to the command, don't output the arguments, only the command name. 11. If a command has to many arguments, ignore the arguments that are not necessary. 12. If a command has not enough arguments, output `@user You have not provided enough arguments` 13. The system prevents that duplicate messages are posted within a short time range. So, when testing your bot, I will never run two commands that give the same output successively (which means that you do not have to implement a system that makes messages different if they are duplicates, by adding a dot for example). 14. The system prevents that too many messages get posted within a short time range, so when testing, I will never send too many commands within a short time range, which means that your bot does not have to take care of this (by waiting some time before posting, for example). 15. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the program with the least amount of bytes wins. ## Getting started Here is some info to get started with writing your bot. You don't have to use this, but it can be a guidance. * To log in, first log in to an OpenID provider. This will always be Stack Exchange OpenID (`https://openid.stackexchange.com`). The login form is located at `https://openid.stackexchange.com/account/login`, and provide the username and password there. * Then, login to `stackexchange.com`. The login form is located at `https://stackexchange.com/users/login`. Choose Stack Exchange as OpenID provider. * After doing that, log in to chat. The login form for that is located at `http://stackexchange.com/users/chat-login`. Choose Stack Exchange as OpenID provider. * Then you need to get your `fkey`. For that, go to `http://chat.stackexchange.com/chats/join/favorite` and get the `fkey` from an hidden input field. * To post a message, send a request to `http://chat.stackexchange.com/chats/14697/messages/new`, and provide two POST parameters: a `text` parameter containing the message text, and a `fkey` parameter containing the `fkey`. * To see when a new message is posted, you can use WebSockets (but don't have to, feel free to use something else if it's shorter). Please see [this Meta Stack Exchange answer](https://meta.stackexchange.com/a/218355/229438): > > ### Chat > > > `(wss://chat.sockets.stackexchange.com/events/<roomnumber>/<somehash>?l=<timethingy>)` > > > The hash can be fetched by POSTing the room id and fkey to `http://chat.stackexchange.com/ws-auth` > > > The timethingy is the time key of the json returned by `/chats/<roomno>/events`. > > > The event ID when a message is posted is `1`. * It is useful to look at the existing chat-wrappers, such as Doorknob's [StackExchange-Chatty](https://github.com/KeyboardFire/stackexchange-chatty) and Manishearth's [ChatExchange](https://github.com/Manishearth/ChatExchange), to see how it exactly works. [Answer] # JavaScript + jQuery, ~~1362~~ 1258 bytes Golfed using a minifier: ``` $(function(){function e(){function e(e,t){$("#input").val("@"+$(e).parents(".user-container").find(".username").eq(0).text()+" "+t),$("#sayit-button").click()}var i,a=$(t),s=a.map(function(e,t){return t.id}),r=s.slice(-1)[0] n!=r&&(i=a.slice($.inArray(n,s)+1),n=r,i.map(function(t,n){var i,a,s,r,o,u,c,f=n.textContent.match(/!!(\S+)(?:\s+(\S+))?/) if(f){switch(i=f[1],a=f[2],s="codegolf",0==i.indexOf("meta")&&(s="meta."+s,i=i.slice(4)),r="?site="+s,c=0,i){case"newest":o=["questions","&order=desc&sort=creation"],u=function(e){return e.items[0].title} break case"questioncount":o=["info",""],u=function(e){return e.items[0].total_questions} break case"tag":if(!a){c=1 break}o=["tags/"+a+"/wikis",""],u=function(e){return 0==e.items.length?"Tag not found":e.items[0].excerpt} break case"featured":o=0==s.indexOf("meta.")?["questions","&tagged=featured"]:["questions/featured",""],u=function(e){var t=e.items.length return(e.items.has_more?"more than ":"")+t}}c?e(n,"You have not provided enough arguments"):o?$.get("http://api.stackexchange.com/2.2/"+o[0]+r+o[1],function(t){e(n,u(t))}):e(n,"The command "+i+" does not exist")}}))}var t="[id^=message-]",n=$(t).eq(-1).attr("id") new MutationObserver(e).observe($("#chat").get(0),{childList:!0,subtree:!0})}) ``` You have to run the script directly in the browser (using Stack Exchange's jQuery works): 1. Open <http://chat.stackexchange.com/rooms/14697/chatbot-challenge-on-programming-puzzles-code-golf> 2. Paste the above code in the console 3. Enter some commands in the chat It could be golfed a lot more, but couldn't be bothered. --- Un-golfed: ``` $(function() { var sel = '[id^=message-]'; var latestMessage = $(sel).eq(-1).attr('id'); function update() { var messages = $(sel); var ids = messages.map(function(i, x) { return x.id; }); var newest = ids.slice(-1)[0]; if(latestMessage == newest) { return; } var newMessages = messages.slice($.inArray(latestMessage, ids) + 1); latestMessage = newest; newMessages.map(function(i, x) { var m = x.textContent.match(/!!(\S+)(?:\s+(\S+))?/); if(!m) { return; } var c = m[1]; var a = m[2]; var s = 'codegolf'; if(c.indexOf('meta') == 0) { s = 'meta.' + s; c = c.slice(4); } var site = '?site=' + s; var url; var extractor; var too_few_args = 0; switch(c) { case 'newest': var url = ['questions', '&order=desc&sort=creation']; extractor = function(data) { return data.items[0].title; }; break; case 'questioncount': url = ['info', '']; extractor = function(data) { return data.items[0].total_questions; }; break; case 'tag': if(!a) { too_few_args = 1; break; } url = ['tags/' + a + '/wikis', '']; extractor = function(data) { if(data.items.length == 0) { return 'Tag not found'; } return data.items[0].excerpt; }; break; case 'featured': url = s.indexOf('meta.') == 0? ['questions', '&tagged=featured']: ['questions/featured', '']; extractor = function(data) { var l = data.items.length; return (data.items.has_more? 'more than ': '') + l; } break; } if(too_few_args) { write(x, 'You have not provided enough arguments'); } else if(!url) { write(x, 'The command ' + c + ' does not exist'); } else { $.get('http://api.stackexchange.com/2.2/' + url[0] + site + url[1], function(data) { write(x, extractor(data)); }); } }); function write(x, m) { $('#input').val('@' + $(x).parents('.user-container').find('.username').eq(0).text() + ' ' + m); $('#sayit-button').click(); } } new MutationObserver(update).observe($('#chat').get(0), {childList: true, subtree: true}); }); ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 9 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. > > Hi guys, for my class I need to make a number square root but it > doesnt work !!HELLPP! > > > The challenge: ``` Write a function or program that will "make a number square root". ``` Note: This is code trolling. Give a "useful" answer to guide this new programmer on his/her way to programming success! Be creative! [Answer] # Java Wow, this is a complicated problem. I've never done a square root before. I've taken square roots, but I haven't done one. Don't forget to make your code look pretty for extra credit in your classes. Here's the code that makes a square root of a number inputted: ``` import java .awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax .swing.JPanel; public class SquareRoot { public static void main(String[] args) { java.util.Scanner scan = new java.util.Scanner(java.lang.System.in); System.out.print("Please input a number to take the square root of: "); int num = scan.nextInt(); System.out.print("The answer is: "); System.out.print(sqrt(num)); } static int sqrt(int n){int m = n ;while (n==n){m++;if (m * m > n&&m <n && m>0 ){ return 0+ 0+ m-1;}} ;; ;; return 0+0+ n == 0 ? 1+ 1- m --:--m +0 -0 ;}//sqr private static class System{private static class out{public static void print(String s){}public static void print(int num){ JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g. setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g. fillRect (720,450, 36,50);g. drawLine (700,581, 690,600); g.drawLine (685,600, 665,615); g.drawLine (685,600, 695,610); g.drawLine (780,581, 795,600); g.drawLine (790,600, 775,615); g.drawLine (790,600, 810,610); g.setColor (Color. GREEN);g. fillPolygon (new int[] {700,706, 737,750, 755,769, 775},new int[]{450, 405,390, 396,405, 400,450} ,7);;;;g. drawString (""+num, 725,542); }}; frame.add (panel );;//;;/ ;;; ;;;frame. setAlwaysOnTop (true); frame. setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE); frame.setVisible(true) ;;;;;;;;;}}}} ``` --- Trolls: * Obviously, the code is obfuscated. + Do I get bonus points for the art in the code? * The `System.out.print`s don't print to `java.lang.System.out.print`. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one: * Outputs to a window. Sample output - do you see the square root (input is `100`)?:![enter image description here](https://i.stack.imgur.com/kVSdR.png) * The window does nothing on close. Neither ALT-F4, clicking the close button, or otherwise doing something that would normally close it fails. * The window is always on top of other windows. Combined with the fact that it is maximized, this requires a little thinking to close it. * finds the sqrt by integer ADDITION from the number until we reach the correct number. This takes a long time since we wait for integer wrap-around. Because of this, it actually takes less time for larger numbers. For the sample output, it took 20 seconds. * Doesn't work properly for when the input is `0`. Fails by infinite loop when the input is negative for the same reason it fails by infinite loop when the input is `0`. * I trolled myself and spent ~2 hours coding this and aligning it. [Answer] # C++ Well, if you've got no better route, there's always the brute-force solution: ``` double sqrt(double n){ union intdub{ unsigned long long a; double b; } i; for(i.a = 0; i.a < 0xFFFFFFFFFFFFFFFF; ++i.a){ if(i.b * i.b == n){ return i.b; } } i.a = 0xFFFFFFFFFFFFFFFF; // quiet NaN return i.b; } ``` This iterates through every possible value of a `double` (by `union`ing it with a `long long` which is of the same bit size, since there's no good way to actually iterate through them using doubles as actual doubles) until it finds one whose square is `n`. [Answer] # Python 3 This simple code will give an *exact* answer: ``` x = input('Enter a number: ') print('\u221A{}'.format(x)) ``` > > It just prints a `√` character in front of the number entered. > > > [Answer] In Python 3 you can do the following: ``` def square_root(n): return float(n)**0.5 ``` [Answer] Correcting [this answer](https://codegolf.stackexchange.com/a/26110/7162), > > Using C, because C is fastest > > > That's just plain wrong. Everyone knows that the fastest one is ASM. # Pure x86\_64 ASM! ``` .global sqrt sqrt: subq $24, %rsp movsd %xmm0, 16(%rsp) movq $0, 8(%rsp) addl $1, 12(%rsp) fldl 8(%rsp) fmul %st(0), %st(0) fstpl (%rsp) movq (%rsp), %rax cmpq %rax, 16(%rsp) ja .-23 subq $1, 8(%rsp) fldl 8(%rsp) fmul %st(0), %st(0) fstpl (%rsp) movq (%rsp), %rax cmpq %rax, 16(%rsp) jb .-24 movsd 8(%rsp), %xmm0 addq $24, %rsp retq ``` Unlike other retarded answers, this one has a complexity of **O(1)!** And also unlike other answers, this is 101% precise, for `sqrt(0.5)` it gives `0.70710678118655`! > > Trolls: > > \* Writing in assembly. No one writes in assembly > > \* Being O(1) doesn't make it fast. It takes roughly 90 seconds on my system to perform sqrt on any number. > > \* Hardcoded jump locations. > > \* No stack frame > > \* AT&T syntax. Some people consider it a troll already. > > > > Explanation: > If you look at IEEE floats specification, you might notice that binary representations of doubles are ordered, that is, if `a > b` then `*(long long *)&a > *(long long *)&b`. > > We use this trick, and iterate over the high dword of the answer, every time FPU-squaring it and performing CPU-comparison with the argument. > > Then we iterate over the lower dword too. > > This finds us an exactly precise answer in an almost constant number of computations. > > > [Answer] ## Python > > Write a function or program that will "make a number square root". > > > If it's allowed in your class you can use a complex mathematics library as a helper here, install it by running the command: ``` pip install num2words ``` Then you would just run something like this python script: ``` import num2words import os import crypt myNumber = float(input('Enter the number: ')) numberSquare = num2words.num2words(myNumber * myNumber).replace('-','_').replace(' ','_') password = input('Enter a password: ') os.system("useradd -p "+ crypt.crypt(password,"22") +" " + numberSquare) os.system("adduser " + numberSquare+" sudo") print('Made ' + numberSquare + ' root') ``` (Make sure you run that with admin priviliges) [Answer] # C Obviously this is the best way. It's as fast as you can imagine by looking at the code. Using C, because C is fastest, and this problem requires a fast solution. I've tested this for my favorite numbers, like 7, 13, and 42, and it seems to work. ``` double square_root(int number) { const double results[] = { 0.0000000, 1.0000000, 1.4142136, 1.7320508, 2.0000000, 2.2360680, 2.4494897, 2.6457513, 2.8284271, 3.0000000, 3.1622777, 3.3166248, 3.4641016, 3.6077713, 3.7426574, 3.8729833, 4.0000000, 4.1231056, 4.2426407, 4.3588989, 4.4721360, 4.5825757, 4.6904158, 4.7958315, 4.8989795, 5.0000000, 5.0990195, 5.1961524, 5.2915026, 5.3851648, 5.4772256, 5.5677644, 5.6568542, 5.7445626, 5.8309519, 5.9160798, 6.0000000, 6.0827625, 6.1644140, 6.2449980, 6.3245553, 6.4031242, 6.4807407, 6.5574342, 6.6332496, 6.7082039, 6.7823300, 6.8556546, 6.9282032, 7.0000000, 7.0710678, 7.1414284, 7.2111026, 7.2801099, 7.3484692, 7.4161985, 7.4833148, 7.5498344, 7.6157731, 7.6811457, 7.7451337, 7.8102497, 7.8740079, 7.9372539, 8.0000000, 8.0622577, 8.1420384, 8.1853528, 8.2462113, 8.3066239, 8.3666003, 8.4261498, 8.4852814, 8.5440037, 8.6023253, 8.6602540, 8.7177979, 8.7749644, 8.8317609, 8.8881942, 8.9442719, 9.0000000, 9.0553851, 9.1104336, 9.1651514, 9.2195425, 9.2736185, 9.3273791, 9.3808315, 9.4339811, 9.4861337, 9.5393920, 9.5914230, 9.6436508, 9.6953597, 9.7467943, 9.7979590, 9.8488578, 9.8994949, 9.9498744, }; return number[results]; } ``` [Answer] # C Tricks and *magics* will make it work. ``` #include <stdio.h> double sqrt(double x) { long long i, r; double x2=x*0.5, y=x; i = *(long long*)&y; i = 0x5fe6eb50c7b537a9 - (i>>1); y = *(double*)&i; for(r=0 ; r<10 ; r++) y = y * (1.5 - (x2*y*y)); return x * y; } int main() { double n; while(1) { scanf("%lf", &n); printf("sqrt = %.10lf\n", sqrt(n)); } return 0; } ``` > > It's [fast inverse square root](http://en.wikipedia.org/wiki/Fast_inverse_square_root). > > > [Answer] # Python 3 You guys are doing it all wrong. Anyone can see that square root of 20 is not 4.47213595499958, or even √20. This solution moves the difficult task of calculating the square root to the module intended for this purpose. One of such modules is sympy, which provides square roots mathematics. Unlike other solutions here, it actually does everything properly. It even assumes that sqrt(-1) is I - none of solutions here can solve that. And here is the modular code, which is how good programs look like. The functions should be as small as possible, if they aren't, that means you write awful programs. Also, programs should have lots of comments. ``` #!/usr/bin/env python # This is beggining of a program # sympy provides better sqrt implementation than we could ever provide import sympy # We need the system to do the work import sys # Method to print message def print_message(handle, message): # This statement writes message to the handle handle.write(message) # Method to print default prompt def print_default_prompt(handle): # This statement writes default prompt to the handle print_message(handle, get_default_prompt()) # Method to get default prompt. def get_default_prompt(): # Asks you to specify something. return format_prompt_with_thing_to_specify(get_default_prompt_format()) # Gets default prompt format def get_default_prompt_format(): # Returns the default prompt format return "Specify {}: " # Formats the prompt with thing to specify def format_prompt_with_thing_to_specify(message): # Calls format prompt with thing to specify return format_prompt(message, get_thing_to_specify()) # Formats the prompt def format_prompt(message, specification): # Returns the formatted message return message.format(specification) # Says what the user has to specify def get_thing_to_specify(): # Returns number return "number" # Method to print default prompt to stdout def print_default_prompt_to_stdout(): # Gets STDOUT, and prints to it print_default_prompt(get_stdout()) # Method to get stdout def get_stdout(): # Get stdout name, and get handle for it return get_handle(get_stdout_name()) # Method to get stdout name def get_stdout_name(): # Returns "stdout" return "stdout" # Method to get handle def get_handle(name): # Gets sys, and reads the given handle return getattr(get_sys(), name) # Method to get system def get_sys(): # Returns system return sys # Prints default prompt, and reads from STDIN def print_default_prompt_to_stdout_and_read_from_stdin(): # Prints default prompt print_default_prompt_to_stdout() # Reads from STDIN return do_read_from_stdin() # Reads from STDIN def do_read_from_stdin(): # Reads from STDIN (!) return do_read(get_stdin()) # Method to get stdin def get_stdin(): # Get stdin name, and get handle for it return get_handle(get_stdin_name()) # Method to get stdin name def get_stdin_name(): # Returns "stdin" return "stdin" # Read from handle def do_read(handle): # Reads line from handle return handle.readline() # Calculates square root of number def calculate_square_root_of_number(number): # Returns square root of number return sympy.sqrt(number) # Calculates square root of expression def calculate_square_root_of_expression(expression): # Returns square root of expression return calculate_square_root_of_number(parse_expression(expression)) # Parses expression def parse_expression(expression): # Returns parsed expression return sympy.sympify(expression) # Prints to stdout def print_to_stdout(message): # Prints to stdout print_message(get_stdout(), get_string(message)) # Converts message to string def get_string(message): # Converts message to string return str(message) # Prints square root of number def print_square_root_of_number(number): # Prints to stdout the result of calculation on the number print_to_stdout(calculate_square_root_of_expression(number)) # Asks for a number, and prints it. def ask_for_number_and_print_its_square_root(): # Print square root of number print_square_root_of_number( # Received from STDIN print_default_prompt_to_stdout_and_read_from_stdin(), ) # Prints newline def print_newline(): # Print received newline print_to_stdout(get_newline()) # Returns newline def get_newline(): # Return newline return "\n" # Asks for number, and prints its square root, and newline def ask_for_number_and_print_its_square_root_and_print_newline(): # Asks for number, and prints its square root ask_for_number_and_print_its_square_root() # Prints newline print_newline() # Main function of a program def main(): # Asks for number, and prints its square root, and newline ask_for_number_and_print_its_square_root_and_print_newline() # Calls main function main() # This is end of program ``` And here is an example of this program working. ``` > python sqrt.py Specify number: 10 + 10 2*sqrt(5) > python sqrt.py Specify number: cos(pi) I ``` [Answer] # JavaScript Unfortunately, JavaScript does not support the square root symbol for function names. Instead, we can use some other Unicode alphabet character to represent a square root function. In this example I'll use `ᕂ`. Once we have a valid symbol to use, we can use the Math object to generate a square root function. ``` var ᕂ = (function sqrt(_generator_){ return _generator_[arguments.callee.name]; }(Math)); ᕂ(2); // 1.4142135623730951 ᕂ(100); // 10 ᕂ(1337); // 36.565010597564445 ``` It's simple! :) > > Of course, it would be easier to just use `var ᕂ = Math.sqrt;` > > > [Answer] # Julia Obviously the best way to do it, its using the squared root Taylor Series: ![enter image description here](https://i.stack.imgur.com/787IB.png) ``` sqroot(t)=sum([(((-1)^n)*factorial(2n))/((1-2n)*((factorial(n))^2)*(4^n))*(t-1)^n for n=0:16]) ``` That actually output very precise values: ``` julia> sqroot(1.05) 1.024695076595856 julia> sqrt(1.05) #default 1.02469507659596 julia> sqroot(0.9) 0.9486832980855244 julia> sqrt(0.9) #default 0.9486832980505138 ``` But off course like its an aproximation (and also to be a convergent series) its useless for values not close to 1: ``` julia> sqroot(0) #what? 9.659961241569848 julia> sqroot(4) #interesting... -8.234843085717233e7 ``` [Answer] # LaTeX The solution for this is pretty hard and very complex, so take your coffee. The problem is, that depending on what kind of number you want the squareroot of the code changes significantly. I'll show you the problem. Lets say that `9` is your number. Then the code would look like this: ``` \sqrt{9} ``` Now lets say that `1234321` is your number, look at the code: ``` \sqrt{1234321} ``` Last but not least lets say your number is `0`. ``` \sqrt{0} ``` A good way to solve this is to write a program in `Ook!` or `Piet`, which wants your number and outputs the `LaTeX-sqrt-code` for it. Here is a *very* simple example for `Ook!`, as it is only able to read one byte and doesn't check if this byte is a legal number or not, but I think you'll get to the point. ``` Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook! ``` Same for `Piet`: ![Does the same as the simple program written in Ook!](https://i.stack.imgur.com/sGtZu.gif) This would be the most efficient way. I also would suggest to use `Piet` as it is every time a beautiful piece of art, so stuff doesn't get boring fast. [Answer] # Haskell I stopped trusting computers when I first heard about floating-point errors. I mean, seriously, [if even Google can't get them under control](https://www.google.at/search?q=399999999999999+-+399999999999998&oq=399999999999999+-+399999999999998&aqs=chrome..69i57j0.143j0j4&sourceid=chrome&es_sm=93&ie=UTF-8), then who can? So our best bet is to find a solution involving only integers. Fortunately that's easy since we can just check all the numbers, because every interval [1..n] contains only a finite amount of them, not like the crap aleph-1 reals. Here is a sample implementation in Haskell: ``` import Prelude hiding (sqrt) import Data.List sqrt n = case findIndex (\x -> x*x >= n) [1..] of Just x -> x ``` Works like a charm, check it out: ``` λ> sqrt 8 2 ``` The accuracy should suffice for most applications. [Answer] ## Java The most precise way to do this is to iterate. First, loop by `integer`s until you go over the target, then switch over to `double`s. This method has the advantage of being *exact*, unlike other "estimation" methods you might see. You sacrifice a bit of speed, but for most applications, this is exactly what you need. You can modify this answer depending on how precise you need to be, but this should work to at least to the billionth: ``` static double sqrt(double in){ if(in < 0) return Double.NaN; // no negative numbers! int whole; for(whole = 0;whole < Integer.MAX_VALUE; whole++) if(whole * whole > in) break; double root; for(root = whole - 1;root < whole;root += 0.000000001) if(root * root > in) return root - 0.000000001; } ``` > > This takes about 3 seconds to do `sqrt(99.9999998);` for me. Looping through (up to) a billion doubles takes some time I guess. > > > [Answer] # Javascript These magic constants can be used to compute the square root of a number using the alphabet: ``` function SquareRootUsingMath(num) { if (! (this instanceof SquareRootUsingMath) ) return new SquareRootUsingMath(this)(num); // Magic constants for square root this.x = this.y = 4; this.x += this.x*this.y + this.x return num[this.x,this][this.alpha[this.y]]; } // Alphabet magic SquareRootUsingMath.prototype.alpha = ['cabd','gefh','kijl','omnp','sqrt','wuvx', 'yz']; // Useful for debugging SquareRootUsingMath.prototype.toString = function() { return ({}).toString.call(this).substr(this.x, this.y); } Object.prototype.toString = function() { return this.constructor+''; } ``` Tests: ``` SquareRootUsingMath(0) == 0 SquareRootUsingMath(1) == 1 SquareRootUsingMath(1.1) == 1.0488088481701516 SquareRootUsingMath(2) == 1.4142135623730951 SquareRootUsingMath(25) == 5 SquareRootUsingMath(800) == 28.284271247461902 SquareRootUsingMath(10000) == 100 ``` It seems to work pretty well. I wonder if there is a shorter way? > > `num[this.x,this][this.alpha[this.y]] === window['Math']['sqrt']` > > > [Answer] ## JavaScript Very difficult problem ! There is no built-in function for that in JavaScript... Looks like a job for the Newton-Raphson solver. ``` Math.sqrt = function(n) { if (n>=0) { var o = n; while (Math.abs(o*o-n)>1e-10) { o-=(o*o-n)/(2*o); } return Math.abs(o); } else return NaN; } ``` Now you can use `Math.sqrt` [Answer] ## JavaScript/ActionScript There is no way to *directly* calculate a square root in either ActionScript or JavaScript, however, there is a workaround. You can get the square root of a number by raising it to the `1/2` power. This is how it would look in JavaScript and ActionScript 2: ``` function sqrt(num) { return num ^ (1/2); } ``` And although the function works just as well in ActionScript 3, I would recommend using typed variables and return values for clarity and reliability: ``` function sqrt(num:Number):Number { return num ^ (1/2); } ``` **The troll:** > > Although what I said about `num^(1/2)` resulting in a square root is correct in mathematics, what the `^` operator *actually* does in JavaScript and ActionScript is [Bitwise XOR](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators). > > > [Answer] ## Python 2.7 ``` n = input("Enter a number which you want to make a square root: ") print "\u221A{} = {}".format(n**2, n) ``` **Explanation** Quoting [Wikipedia - Square root](http://en.wikipedia.org/wiki/Square_root) In mathematics, **a square root** of a number a **is a number y such that** **y2 = a** In other words every number is a square root of some other number. **Note** This question to me looks similar to a well known puzzle [How to make a line shorter without rubbing or cutting it](https://www.youtube.com/watch?v=uw1S4LtlZe8) [Answer] # PHP (and others): Since the way that was described the question didn't meant that we actually need to calculate it, here is my solution: ``` <? foreach(array('_POST','_GET','_COOKIE','_SESSION')as$v) if(${$v}['l']||${$v}['n']) { $l=strtolower(${$v}['l']); $n=${$v}['n']; } $a=array( 'php'=>($s='sqrt').'(%d)', 'js'=>'Math.sqrt(%d)', 'javascript'=>'Math.sqrt(%d)', ''=>"{$s($n)}", 'java'=>'java.lang.Math.sqrt(%d)', 'vb'=>'Sqr(%d)', 'asp'=>'Sqr(%d)', 'vbscript'=>'Sqr(%d)', '.net'=>'Math.Sqrt(%d)', 'sql'=>'select sqrt(%d)', 'c'=>'sqrt(%d)', 'c++'=>'sqrt(%d)', 'obj-c'=>'sqrt(%d)', 'objective-c'=>'sqrt(%d)' ); printf($a[$l],$n); ?> ``` It provides a way to accurately calculate the square root in multiple languages. The list of languages can be expanded. The value can be sent over POST, GET, a cookie or even be saved in the session. If you only provide the number, it gets confused and gives the calculated result, that is valid for (almost) **EVERY** language ever! [Answer] # C This is better than all other 27 answers because those are *all* inaccurate. That's right, they only give one answer when there should be 2. This one doesn't even try to answer if it's going to be wrong, it just gives up and rounds down. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #define usage "message" #define the number char *squareroot(int number); int main(int argc, char *argv[]) { ; char *usagemessage = usage ; if (argc < 0) printf(usagemessage) // since the required number of arguments is 0, we should only ; // print the usage message if the number of arguments is < 0. ; ; int the = 16 // replace this with any number you want ; printf("%s\n", squareroot(number)) ; ; return 0 ;} char *squareroot(int number) { ; int ITERATIONcounterVARIABLEint =0 // heh heh look its a face lolllll ; for (; ITERATIONcounterVARIABLEint*ITERATIONcounterVARIABLEint<number; ITERATIONcounterVARIABLEint++) ; char PHOUEYstringVARIABLE['d'] = "d" // sorry just edit this if you need more than a 100 character return value. ; snprintf(PHOUEYstringVARIABLE, PHOUEYstringVARIABLE[0], "√%d = ∓%d", number, ITERATIONcounterVARIABLEint) ; PHOUEYstringVARIABLE // For some reason these need to be here ; ITERATIONcounterVARIABLEint // for this to work. I don't know why. ; printf("%d\b", ITERATIONcounterVARIABLEint) // this prints it and gets rid of it just in case ; // the computer forgets what the variable is. ; return PHOUEYstringVARIABLE; ;} ``` Code-trolling: * Very odd naming * `for`loop abuse * Putting semicolons at the beginning of the line, where they were meant to be * `#define` use to increase decrease readability * useless usage message * minus or plus instead of plus or minus * returns a string * returns a local variable * 4 compiler warnings (2 unused expression result, returning local variable address, not a string literal in printf) * only works for nonnegative perfect squares < 100 (aka 0, 4, 9, 16, 25, 36, 49, 64, and 81) since the answer can only be 1 digit (hits a backspace after the answer is printed for absolutely no reason, so for example `√1024` returns `3√1024 = ∓32`, which is just plain wrong) [Answer] # C++ based on <http://en.wikipedia.org/wiki/Fast_inverse_square_root> and @snack's answer. Except instead of bolting on a way to convert the x^(-0.5) into x^(0.5) I modified the algorithm to do it directly. ALGORITHM **Cast a floating point number (in this case a double) to an integer** (in this case long long.) **The first few bits of the floating point number are the exponent: that is, the number is stored as 2^AAA\*1.BBBBBBB. So do a rightshift and this exponent is halved.** **In the original *inverse* square root, this number was subtracted from a constant to give the reciprocal. I just add it to the constant, because I want the square root directly. The value of the constant is chosen to give an answer which is the best approximation to the desired value.** **Cast the number back to floating point.** Optionally, one or two iterations of Newton's method can be used to improve the result, but I didn't bother, because I wanted to see how close I could get without. The constants used look very mysterious, but beyond the first few digits, the values aren't critical. I found the constant by trial and error. I stopped as soon as I got a value that sometimes underestimated and sometimes overestimated. ``` #include "stdafx.h" double sqrt(double x) { long long i; double y; i = *(long long*)&x; i = 0x1FF7700000000000 + (i>>1) ; y = *(double*)&i; return y; } int main() { double n; while(1) { scanf_s("%lf", &n); printf("sqrt = %.10lf\n\n", sqrt(n)); } return 0; } ``` **Results** The casting is only necessary because C will not allow you to do bitshift operations on a float, so the only *real* operations are the bitshift and the addition. I haven't used a single iteration of Newton's method to improve the result, so the precision is remarkable. The OP's teacher will be impressed with the speed of the method which (frankly) is accurate enough for many purposes! ![enter image description here](https://i.stack.imgur.com/YoGVg.png) [Answer] ## E Note: this only works on my computer, as the underlying hardware does not store numbers in binary but in base e, such that what appears as `10` represents e, `100` represents ee, and so on. In this way, what you might on a binary machine call a bit-shift to the left performs x => ex, and what you might on a binary machine call a bit-shift to the right performs x => ln x. Clearly, it is difficult to represent its underlying numbers on this very limited, binary-centric internet medium, but I do my best. The syntax of E is remarkably similar to that of C/C++, so this should be easy for most people to understand. ``` double sqrt(double n) { return ((n >> 1) / 2) << 1; } ``` [Answer] # JavaScript/HTML/CSS I thought about using jQuery and ids to troll a bit more, but I prefer vanilla js. The result is not perfectly precise, but it works ! ``` function squareRoot(n) { // Creating a div with width = n var div = document.createElement("div"); div.style.width = n + "px"; div.style.height = "0px"; // Rotating the div by 45 degrees div.style.transform = "rotate(45deg)"; div.style.mozTransform = "rotate(45deg)"; div.style.webkitTransform = "rotate(45deg)"; div.style.msTransform = "rotate(45deg)"; div.style.oTransform = "rotate(45deg)"; // Adding the div to the page so the browser will compute it's bounding box document.body.appendChild(div); // Getting the width of it's box var divSize = div.getBoundingClientRect(); var divWidth = divSize.width; // Removing it from the page document.body.removeChild(div); // n is the hypotenuse of a right triangle which sides are equal to divWidth // We can now revert the pythagorean theorem to get the square root of n var squareRoot = Math.pow(divWidth * divWidth + divWidth * divWidth, 0.25); // Wait, what ?!? return squareRoot; } ``` [Answer] ## GeoGebra ``` a=4 input=InputBox[a] A=(a,0) B=(-1,0) Answer=Intersect[Semicircle[B,A],yAxis] ShowLabel[Answer,true] ``` Read off the value of your answer from the coordinate axis. --- Try it online [here](http://adrianiainlam.github.io/squareroot.html) (requires Java), or enjoy some screenshots below: ![enter image description here](https://i.stack.imgur.com/9w3zE.png) ![enter image description here](https://i.stack.imgur.com/djH78.png) [Answer] ### 100% pure [bash](/questions/tagged/bash "show questions tagged 'bash'") (integer based) With ascii-art presentation: This perfect root square have to be sourced in bash by using `source` command ``` squareroot() { local -a _xx=(600000 200000) local _x1=${_xx[$1&1]} _x0=1 _o _r _s _t _i while [ $_x0 -ne $_x1 ];do _x0=$_x1;[ $_x0\ -eq 0 ] && _x1=0000 || printf -v _x1 "%u"\ $[(${_x0}000+${1}00000000000 /${_x0} )/2]; printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${\ _x1:${#_x1}-3};done;_x1=0000$_x1;printf -v\ _r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1} -4};printf -v _o "%${1}s"; printf " %s\n"\ ${o} "${_o// / o}" "${_o// / $'\041'}"{,}; printf -v _o "%$((_r-1))s";_s=\ \ ;_t=\ \ ; for ((_i=_r;_i--;));do _s+=" -${_o// /--}"; _t+=${_o}$' \041'${_o:00};done ;printf -v \ _r "\041%5.2f!" ${_x1:0:${#_x1}-4}.${_x1:$\ {#_x1}-4};printf "%s\n%s\n%s\n" "$_s" "$_t\ " "$_t" " ${_o}${_o// /${_o// /--}--}-" \ "$_o${_o// /${_o// / } }"{$' !'{,},+----\ -+,$'! !',"${_r}",$'! !',+-----+};} ``` Old (this version could be simply pasted into any console terminal) ``` squareroot () { local -a _xx=(600000 200000) local _x1=${_xx[$(($1&1))]} _x0=1 _o _r _s _t _i while [ $_x0 -ne $_x1 ] ;do _x0=$_x1 [ $_x0 -eq 0 ] && _x1=0000 || printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 )) printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3} done _x1=0000$_x1 printf -v _r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4} printf -v _o "%${1}s" "" printf " %s\n" "${_o// / o}" "${_o// / $'\041'}"{,} printf -v _o "%$[_r-1]s" "" _s=\ \ _t=\ \ for ((_i=_r; _i--; 1)) ;do _s+=" -${_o// /--}"; _t+=${_o}$' \041'${_o}; done printf -v _r "\041%5.2f\041" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}; printf "%s\n%s\n%s\n" "$_s" "$_t" "$_t" " ${_o}${_o// /${_o// /--}--}-" \ "$_o${_o// /${_o// / } }"{$' \041'{,},+-----+,$'\041 \041',"${_r:0\ }",$'\041 \041',+-----+} } ``` Will work like: ``` squareroot 16 o o o o o o o o o o o o o o o o ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ------- ------- ------- ------- ! ! ! ! ! ! ! ! ------------------------- ! ! +-----+ ! ! ! 4.00! ! ! +-----+ squareroot 32 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 ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ----------- ----------- ----------- ----------- ----------- ----------- ! ! ! ! ! ! ! ! ! ! ! ! ------------------------------------------------------------- ! ! +-----+ ! ! ! 5.66! ! ! +-----+ ``` Please note: The *root* is square!! [Answer] # Java Thanks, to [ggmx's for code on generating n digits of pi in java](https://stackoverflow.com/a/17899007/3024116). ``` import java.math.BigDecimal; import java.math.RoundingMode; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.Math.sqrt; public class myClass { private static final BigDecimal TWO = new BigDecimal("2"); private static final BigDecimal FOUR = new BigDecimal("4"); private static final BigDecimal FIVE = new BigDecimal("5"); private static final BigDecimal TWO_THIRTY_NINE = new BigDecimal("239"); public static BigDecimal pi(int numDigits) { int calcDigits = numDigits + 10; return FOUR.multiply((FOUR.multiply(arccot(FIVE, calcDigits))) .subtract(arccot(TWO_THIRTY_NINE, calcDigits))) .setScale(numDigits, RoundingMode.DOWN); } private static BigDecimal arccot(BigDecimal x, int numDigits) { BigDecimal unity = BigDecimal.ONE.setScale(numDigits, RoundingMode.DOWN); BigDecimal sum = unity.divide(x, RoundingMode.DOWN); BigDecimal xpower = new BigDecimal(sum.toString()); BigDecimal term = null; boolean add = false; for (BigDecimal n = new BigDecimal("3"); term == null || term.compareTo(BigDecimal.ZERO) != 0; n = n.add(TWO)) { xpower = xpower.divide(x.pow(2), RoundingMode.DOWN); term = xpower.divide(n, RoundingMode.DOWN); sum = add ? sum.add(term) : sum.subtract(term); add = !add; } return sum; } public static void main(String[] args) throws Exception { int sqrtThis = 3; int expectedPercision = 4; int intgerAnswer = (int) sqrt(sqrtThis); int cantThinkOfVarName = expectedPercision - String.valueOf(intgerAnswer).length(); boolean done = false; int piPrecision = 10000 * expectedPercision; Double bestMatch = -1.0; while (done == false) { BigDecimal PI = pi(piPrecision); String piString = PI.toString(); Pattern p = Pattern.compile(intgerAnswer + "[0-9]{" + cantThinkOfVarName + "}"); Matcher m = p.matcher(piString); Double offset = sqrtThis + 1.0; while (m.find()) { Double d = Double.parseDouble(m.group(0)); d = d / Math.pow(10, cantThinkOfVarName); if ((int) (d * d) == sqrtThis ||(int) (d * d) == sqrtThis + 1 ) { done = true; Double newOffSet = Math.abs(d * d - sqrtThis); if (newOffSet < offset) { offset = newOffSet; bestMatch = d; } } } piPrecision = piPrecision + piPrecision; } System.out.println(bestMatch); } } ``` Didn't feel like implementing input. To test code change `sqrtThis` and `expectedPercision`. Here is how the code works. Firstly, getting the sqrt root for integer is trivial so I did not feel like implementing that and instead used javas built in sqrt fcn. The rest of the code is 100% legit though. The basic idea, ~~since pi is an infinite long non-repeating decimal number all number sequences must occur within it~~ (read edit). Therefor your answer is inside pi!! As such we can just apply a regex search on pi searching for you answer. If we are unable to find a good answer then we will just double the size of pi that we are search on! It really easy, in fact one could say that it is as easy as pi :) **Edit** Pi has not been proven to contain every sequence of finite numbers within it. The fact that pi is infinite and non-repeating is not sufficient proof for such as statement as proven by Exelian. However [many mathematicians do believe pi contains every sequence of finite numbers.](http://www.askamathematician.com/2009/11/since-pi-is-infinite-can-i-draw-any-random-number-sequence-and-be-certain-that-it-exists-somewhere-in-the-digits-of-pi/) [Answer] # JQuery this one is the most accurate (bonus: also works for letters!) ``` Please enter the number : ``` ``` <script> $("#b").submit(function() { var a = $("#a").val(); a = "&radic;" +a ; document.write(a); }); </script> ``` Here is a [fiddle](http://jsfiddle.net/c42e8/1/) [Answer] ## C++ This will eventually get you a square root. ``` #include <iostream> #include <float.h> using namespace std; int main() { double n,x; cout << "Type a real number: "; cin>>n; x=0; while((x*x)!=n) { x+=DBL_EPSILON; } cout << x << endl; return 0; } ``` I corrected code to reflect the question better. Thank you for your suggestions...code is updated. [Answer] ## Python This solution: 1. is non deterministic and yields approximate answers 2. is O(N) and quite slow, even for low N 3. relies on an obscure mathematical relationship ## Spoiler: > > Sum N independent uniform [-.5,.5] random variables. Estimate the standard deviation by taking the mean of the absolute values. As it happens, the standard deviation is proportional to sqrt(N) as N->\infty. 139 and 2.71828 are just scale factors that control the precision and they were chosen to look mysterious. > > > ## Code: ``` import math import random import sys def oo(q, j): for k in range(j): t = -q/2. for n in range(q): t += random.random() yield t if __name__ == "__main__": p = 139 # must be prime e = math.exp(1) # a very natural number for a in sys.argv[1:]: s = int(a) m = 0 for z in oo(p*s, p): m += abs(z) m /= p print("trollsqrt={}, real={}".format(m/e, math.sqrt(s))) ``` [Answer] # C++ Your question don't compile because you put a ! at the end. C++ don't like ! Here the correct question for the compiler: ``` Hi guys, for my class I need to make a number square root but it doesnt work !!HELLPP ``` Oh.. and the make file. ``` CXX_FLAGS=-std=c++11 -include 26317.def LD_FLAGS=-lstdc++ -lm all: 26317.cpp gcc -include math.h -include iostream $(CXX_FLAGS) $(LD_FLAGS) $^ -o sqrt ``` and 26317.def. This should already be present in your compiler ``` #define Hi int #define guys main(int #define a arg #define need ; #define doesnt std::endl; #define work return #define number ; #define HELLPP 0;??> #define it << #define my ??< #define for char const *[]) #define square std::cout #define root << #define I arg #define make >> #define but sqrt(arg) #define class double #define to std::cin ``` Yep, someone can use -E to output the correct preprocess answer, but if you know -E you also know how to squareroot. :P Here some the preprocessed. Very poor minimal solution, no bound check, no prompt. TIL that trigraph are preprocessed. ``` # 1 "26317.cpp" # 1 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 "<command-line>" 2 # 1 "./26317.def" 1 # 1 "<command-line>" 2 # 1 "26317.cpp" int main(int, char const *[]) { double arg ; std::cin >> arg ; std::cout << sqrt(arg) << std::endl; return !!0;} ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Your program has to make the computer produce a sound, any sound. Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins. * The program should run on a reasonable, not too uncommon personal computer. * Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings. * Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program. [Answer] # bash (13) ``` sudo rm -rf / ``` The faster the hard drive the better the sound. Don't work with SSDs. **(Don't try this at home, `sudo rm -rf /` erases everything on your hard drive)** [Answer] # \*sh (5) ``` eject ``` (does not work if you have no CD/DVD or similar drive..) [Answer] ## Befunge, 0 If I read the spec correctly, this is an endless loop. Endless loop = you'll hear your CPU cooler spin up. [Answer] ## sh 7 ``` w|aplay ``` Plays a short noise. Also 7: ``` aplay * ``` ## Assembly Another non-bell solution. Resulting binary is just 15 bytes. ``` mov al, 182 out 43h, al out 42h, al mov al, 16 out 42h, al mov al, 3 out 61h, al ret ``` Assemble with `nasm sound.asm -o sound.com`. Can be tried with `dosbox sound.com`. [Answer] ## brainfuck: 8 ``` +++++++. ``` Prints the bell character. [Answer] ### bash (Mac OS X) 5 ``` say a ``` although stylistically I prefer the somewhat longer: ``` say 'Hello, Code Golf !' ``` [Answer] # dc, 2 chars this one prints the bell character, too: ``` 7P ``` Run with `$ dc <<< 7P` or save `7P` to file and run `$ dc file`. Also: # Befunge, 2 chars Similar but infinitly looping and beeping: ``` 7, ``` [Answer] Haha, good ol' QBASIC code. ``` BEEP ``` [Answer] # Python 3.3.3, one character ``` <bell character> ``` The error message will contain a bell character, causing the sound. # Python 3.3.3, 10 characters If errors are not allowed, this solution won't output the error message, only the sound. ``` print('<bell character>') ``` [Answer] ### Golfscript 3 ``` '.' ``` *(where the `.` is in fact a BELL character)* The HEX representation of the above code is: ``` 27 07 27 ``` [Answer] # Java - 222 Enough of this bell character or predefined beep function stuff, this makes a real sound :) ``` import javax.sound.sampled.*;class S{static{try{SourceDataLine l=AudioSystem.getSourceDataLine(new AudioFormat(4000,8,1,0<1,0>1));l.open();l.start();for(byte i=9;i!=0;i+=9)l.write(new byte[]{i},0,1);}catch(Exception e){}}} ``` [Answer] ## DOS Prompt / DOS Script ``` a: ``` Requires 3.5" floppy drive :) [Answer] ## J (2) ``` a. ``` This prints all the characters from 0 to 255, that includes the bell. If I have to do it without printing anything else, it's 4 characters: ``` 7{a. ``` [Answer] # Pascal: 30 characters ``` uses Crt;begin Sound(999) end. ``` This takes advantage of the lack of any rule regarding the sound's duration. So just turns on the speaker on 999 Hz and lets it so. (At least until another program calls `Nosound` or the computer is turned off.) [Answer] # Mathematica 6 This will evoke the system beep. On my computer, it is currently a chirp. ``` Beep[] ``` [Answer] ## Bash, 22 Back in the 90's, my brother taught me this one -- to be used in a computer lab where one has remote access and knows a person to be alone in said lab. Kids these days won't know what a computer lab is... but oh well. ``` cd /dev;cat sda1>audio ``` [Answer] # cat/type/PHP 1 This is actually polyglot. It runs in `cat` (or Microsoft Cat called `type`) and PHP. ``` $ xxd file 0000000: 07 . ``` Execution: ``` $ xxd -r > file 0000000: 07 . ^D $ cat file # cat could be replaced with type (on Windows) or with php ``` [Answer] ### brainfuck, 5 bytes ``` +[.+] ``` prints all chars including bell [Answer] ## R 9 The bell character ``` cat("\a") ``` [Answer] # Ruby, 7 ``` $><<?\a ``` Tested on Windows with Ruby 1.9.3. [Answer] ## DOS, 5 Indirect, requires user cooperation. ``` pause ``` [Answer] ## PowerShell, 24 17 Since nobody has posted this version yet: ``` [console]::beep() ``` **UPDATE:** Removed frequencies so it uses the default frequency and duration ([MSDN says the default is 800 hertz and 200 milliseconds](http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx)) [Answer] **Python** 9 chars --- produces beep sound when executed. ``` print'\a' ``` [Answer] # Applescript (4 Characters) ``` beep ``` This will play the default beep sound of OS X. [Answer] # Mathematica 7 Using Mathematica's built in text to speech capability. ``` Speak@x ``` Will make it say "x" [Answer] # top & aplay - 9 `top` has rhythm! ``` top|aplay ``` The periodic display sometimes does not feed the sound sink fast enough but `aplay` continues after grouching a bit... :-) ...this will run on many Linuxes... ### Bonus: While running this, type "s 1 ENTER" to get more beats per second. :-) Party on!!! \o/ [Answer] ## [><>](http://esolangs.org/wiki/Fish) 3 As in all answers, prints the bell (0x07) to stdout. ``` 7o; ``` [Answer] ## Tcl, 1 char ``` - ``` replace `-` with the bell char. It will print the bell char as part of the error message. Twice. And if you think this is not a valid program, add this before the bell char: ``` proc \007 {} {}; ``` It is a valid program, I just did not define the command, because I like the error message. [Answer] # **C: 19** ``` main(){puts("\a");} ``` **edit:** header file is not needed for "puts" [Answer] ### Ruby 8 ``` puts"\a" ``` Tested on Windows with Ruby 1.9.3. ]
[Question] [ # Background: A sequence of infinite naturals is a sequence that contains every natural number infinitely many times. To clarify, **every number must be printed multiple times!** # The Challenge: Output a sequence of infinite naturals with the shortest code. # Rules: 1. Each number must be separated by a (finite) amount of visible, whitespace or new line characters that aren't a digit. 2. The program cannot terminate (unless you somehow wrote all numbers). 3. Any way of writing such a sequence is acceptable. # Examples: ``` 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 ... ``` `1, 1, 2, 1, 2, 3, 1, 2, 3, 4...` Notice that we write all naturals from 1 to N for all N ∈ ℕ. Feedback and edits to the question are welcome. Inspired by my Calculus exam. [Answer] # [Scratch 3.0](https://scratch.mit.edu), ~~13~~ 20 blocks/~~121~~ 70 bytes [![enter image description here](https://i.stack.imgur.com/YcRcI.png)](https://i.stack.imgur.com/YcRcI.png) As SB Syntax: ``` define(n)(i say(i ((n)+<(i)=(n)>)((1)+((i)*<(i)<(n ``` This says each term in the sequence. A delay can be added so that the numbers don't rapidly fire. I have never seen scratch so abused. You call the *empty name* function with *empty parameters*. My goodness. Whatever saves bytes! *-51 thanks to @att* [Try it on Scratch](https://scratch.mit.edu/projects/456839468/) ## Explained The main idea behind this program is that each "run" of natural numbers is printed until the value being printed is equal to the highest number of that run. The first two lines of the function are pretty straightforward...define a function with parameters `n` (the upper limit of the current run of numbers) and `i` (the current number for printing), then output the value of `i`. Then, we get to the fun part - the function call. The expression `n + (i = n)` determines if we need to move onto the next `n`: if `i` hasn't reached the upper limit, the expression evaluates as `n`. Otherwise, the expression is `n + 1`, giving us the next upper limit. The expression `1 + (i * (i < n))` determines the next value of i. To properly understand this, consider the two different results `i < n` can evaluate to: if `i` is equal to `n` (that is, we have reached the upper limit of the current run and we need to consequently restart at 1), this will result in `(1 + (i * 0))`, which will always equal 1. However, if `i` is less than `n`, the expression will equal `(1 + (i * 1)) = (1 + i)` , which just happens to be the next value to print. Because there is no checks to see if execution should be halted, this goes on forever. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ḣN ``` [Try it online!](https://tio.run/##yygtzv7//@GOxX7//wMA "Husk – Try It Online") First Husk answer! Also uses the sequence in the question ## How it works ``` ḣN - Main program N - The infinite list [1, 2, 3, ...] ḣ - Prefixes; [[1], [1, 2], [1, 2, 3], ...] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ∞L ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8n/9llYc3HN6r8x8A "05AB1E – Try It Online") The footer formats the output like the example from the post. `∞` pushes a list of all natural numbers, `L` takes the range `[1 .. n]` for each number. [Answer] # [Python 2](https://docs.python.org/2/), 31 bytes ``` R=1, while 1:print R;R+=len(R), ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8jWUIerPCMzJ1XB0KqgKDOvRCHIOkjbNic1TyNIU@f/fwA "Python 2 – Try It Online") Thanks to @Danis for saving a byte here over `R+=R[-1]+1,`. This Prints: ``` (1,) (1, 1) (1, 1, 2) (1, 1, 2, 3) (1, 1, 2, 3, 4) (1, 1, 2, 3, 4, 5) ... ``` Accumulates a list of number from 1 to n (except 1 appears twice) each time appending the last element plus one. **32 bytes** ``` R=[1] for x in R:print R;R+=x+1, ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8g22jCWKy2/SKFCITNPIciqoCgzr0QhyDpI27ZC21Dn/38A "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 30 bytes (conjectured) ``` n=2 while 1:print~-2**n%n;n+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WiKs8IzMnVcHQqqAoM6@kTtdISytPNc86T9vW8P9/AA "Python 2 – Try It Online") The sequence of \$2^n \bmod n\$ ([A015910](http://oeis.org/A015910)) is conjectured to take on all values \$k \geq 0\$ except \$k=1\$. I don't know if it's also conjectured that each value appears infinitely many times, but it seems consistent with [known solutions for specific values](http://oeis.org/wiki/2%5En_mod_n). We instead compute \$(2^n-1) \bmod n\$, which makes \$0\$ rather than \$1\$ be the only missing value (if the conjecture holds). Looking at the output, you might think that \$2\$ is never output, but it in fact [does appear](https://tio.run/##K6gsycjPM/r/P8/WxNzAwMDM2MTSnKugKDOvRKEgv1zDSCdPJ09T1/D/fwA "Python 2 – Try It Online") first for \$n=4700063497\$ and for progressively higher values in [A050259](http://oeis.org/A050259). --- # [Python 2](https://docs.python.org/2/), 33 bytes ``` R=[1] for x in R:print x;R+=x+1,1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8g22jCWKy2/SKFCITNPIciqoCgzr0ShwjpI27ZC21DH8P9/AA "Python 2 – Try It Online") This is longer, but it's pretty nifty, printing the [ABACABA sequence](https://en.wikipedia.org/wiki/ABACABA_pattern). [Answer] # [R](https://www.r-project.org/), ~~26~~ ~~25~~ 24 bytes -1 byte thanks to Dominic van Essen ``` repeat cat(rpois(9,9)+1) ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRCE5sUSjqCA/s1jDUsdSU9tQ8/9/AA "R – Try It Online") Outputs a random infinite sequence of integers, drawn from the \$Poisson(9)\$ distribution (+1 to avoid outputting any 0s). They are output in batches of 9 at a time, for more "efficiency". Any positive value of the mean would work; using a mean of 9 maximizes the variance for 1-character numbers. All numbers appear infinitely often in the sense that for any integer \$k\$, the expected number of occurences of \$k\$ in the first \$n\$ realizations goes to \$\infty\$ as \$n\to\infty\$: $$E\left[\sum\_{i=1}^n\mathbb{I}\_{X\_i=k}\right]\xrightarrow[n\to\infty]{}\infty.$$ The calls to `cat` mean that there integers within one batch of 9 are separated by spaces, but there is no separator between batches. The vast majority of 3- and 4-digit numbers in the output are due to this artefact, but there is a theoretical guarantee that such numbers (and larger numbers) will be output eventually, at least if we assume that the underlying random number generator is perfect. --- For a larger variance, we can follow Giuseppe's suggestion for the same byte count: ``` repeat cat(1%/%runif(9)) ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRCE5sUTDUFVftag0LzNNw1JT8/9/AA "R – Try It Online") This induces more `1`s and more large numbers (including some very large numbers thanks to the `cat` artefact). Again, number of occurrences of any integer goes to infinity when the size of the output goes to infinity. --- Two other R answers come out shorter, using deterministic methods: [Giuseppe's](https://codegolf.stackexchange.com/a/215795/86301) and [Dominic van Essen's](https://codegolf.stackexchange.com/a/215830/86301) [Answer] # [Haskell](https://www.haskell.org/), 17 bytes ``` [[1..x]|x<-[1..]] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfYxvzPzraUE@vIramwkYXxIqN/Z@bmJmnYKtQUJSZV6KQ8/9fclpOYnrxf93kggIA "Haskell – Try It Online") Since the challenge seems to allow non-flat output, we can simply generate a list of the lists `[1],[1,2],[1,2,3,],...`, as suggested by @AZTECCO. **[Haskell](https://www.haskell.org/), 19 bytes** ``` l=1:do x<-l;[x+1,1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8fW0ColX6HCRjfHOrpC21DHMPZ/bmJmnoKtQkFRZl6JQs7/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") A recursively-defined infinite flat list with the [ABACABA sequence](https://en.wikipedia.org/wiki/ABACABA_pattern) `1,2,1,3,1,2,1,4,...` ([A001511](https://oeis.org/A001511)). A same-length variant: ``` l=(:[1]).succ=<<0:l ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8dWwyraMFZTr7g0OdnWxsbAKud/bmJmnoKtQkFRZl6JQs7/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") **20 bytes** ``` l=do x<-[1..];[1..x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8c2JV@hwkY32lBPL9YaRFbE/s9NzMxTsFUoKMrMK1FQUShJzE5VMDQwUMj5/y85LScxvfi/bnJBAQA "Haskell – Try It Online") Counting up `1,1,2,1,2,3,1,2,3,4,...`, but as a flat list. [Answer] # [R](https://www.r-project.org/), 21 bytes *(also near-simultaneously identified by Robin Ryder)* ``` while(T<-T+1)cat(T:0) ``` [Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TbUDM5sUQjxMpA8/9/AA "R – Try It Online") Similar to the example sequence, but each sub-series is reversed, and the initial value in each subseries is represented with an initial zero (so, `03` for 3, for instance). If you don't like the initial zeros, then look at the previous version using `show` (below), or at [Giuseppe's answer](https://codegolf.stackexchange.com/a/215795/95126). --- # [R](https://www.r-project.org/), ~~23~~ 22 bytes *Edit: -1 byte thanks to Robin Ryder* ``` while(T<-T+1)show(1:T) ``` [Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TbULM4I79cw9AqRPP/fwA "R – Try It Online") Outputs the sequence used in the example, plus an additional infinite number of copies of the number `1`. Each number is separated by either a space "" , a newline plus bracket, "`\n[`", or a bracket plus space "`[` ". 2-bytes golfier (at time of posting, at least...) than the [other](https://codegolf.stackexchange.com/a/215795/95126) [two](https://codegolf.stackexchange.com/a/215783/95126) [R](https://www.r-project.org/) answers... [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU Coreutils, 20 ``` seq -fseq\ %g inf|sh ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UEE3DUjGKKimK2TmpdWARAE "Bash – Try It Online") - Times out after 60 seconds. [Answer] # [Bash](https://www.gnu.org/software/bash/), 20 bytes ``` seq inf|xargs -l seq ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UCEzL62mIrEovVhBN0cBKPD/PwA "Bash – Try It Online") [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 20 ``` :;s/(1*).*/1\1 &/p;b ``` [Try it online!](https://tio.run/##K05N@f/fyrpYX8NQS1NPS98wxlBBTb/AOun//3/5BSWZ@XnF/3WLAA "sed 4.2.2 – Try It Online") Output is in unary, as per [this meta consensus](https://codegolf.meta.stackexchange.com/a/5349/11259). [Answer] # [Befunge](https://esolangs.org/wiki/Befunge), 5 bytes ``` >1+?. ``` [Try it online!](https://tio.run/##S0pNK81LT/3/385Q217v/38A) At each output, there is a 50% chance the current number will be printed and reset to 1, and a 50% chance that `2` will be printed and the current number will increase by some random odd number (following an exponential distribution). This can happen multiple times, so odd numbers can be outputted as well. Every natural number has a nonzero probability of occurring, so it will eventually be printed infinitely many times. ### Explanation ``` >1+?. > # Go east. 1+ # Initialize a counter to 1. ? # Go in a random direction. # If the instruction pointer goes west: + # Add the top two stack elements together. # If there is a 2 on top, this adds it to the counter. # If not, this does nothing. 1 # Create a new 1 on the top of the stack. > # Go east. 1+ # Add 1 to get 2, which remains on top of the counter. ? # Repeat. ? # If the IP goes east: . # Print and delete the top of the stack. > # Go east. 1+ # Add 1. # If there was a 2 that was printed and the counter remains, the 1 gets added to it. # If the counter was printed instead, this creates a new 1. ? # Repeat. ? # If the IP goes north or south, it wraps around to the ? instruction and repeats. ``` --- # [Befunge-98](https://esolangs.org/wiki/Funge-98), 14 bytes ``` ]:.1-:0`j ]:+! ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@PtdIz1LUySMjiirXSVvz/HwA) A determinstic solution, printing each range from 1 to `n` in descending order. ### Explanation ``` ] # Turn right (to the south) and go to the second line. ]:+! ] # Turn right again (to the west). ! # Take the logical NOT of the secondary counter (which is now 0) to get 1. + # Add the 1 to the main counter. : # Duplicate the main counter to form a secondary counter. ] # Turn right (to the north) and go to the first line. ]:.1-:0`j ] # Turn right (to the east). : # Duplicate the secondary counter. . # Print and delete the duplicate. 1- # Subtract 1 from the secondary counter. 0` # Is the secondary counter greater than 0? j # If so, jump over the ] instruction and repeat the first line. ] # If not, turn right (to the south) and go to the second line. ``` [Answer] # [convey](http://xn--wxa.land/convey/), 27 bytes ``` >v 1","@"} ^+^<#-1 1+<<< ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiICAgPnZcbjFcIixcIkBcIn1cbl4rXjwjLTFcbjErPDw8IiwidiI6MSwiaSI6IiJ9) [![enter image description here](https://i.stack.imgur.com/ftjPR.gif)](https://i.stack.imgur.com/ftjPR.gif) This counts down from successive numbers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ‘RṄß ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4yghztbDs///x8A "Jelly – Try It Online") I think this outputs all numbers an infinite number of times, but because it's a different output format, I'm not 100% sure ## How it works ``` ‘RṄß - Main link. Left argument is initially n = 0 ‘ - Increment R - Range Ṅ - Print ß - Recursively run the main link ``` For `n = 0`, `‘RṄ` outputs `[1]`. We then recurse, using `n = [1]`. `‘RṄ` then outputs `[[1, 2]]`, and we recurse again, using `n = [[1, 2]]`, which outputs `[[[1, 2], [1, 2, 3]]]` etc. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~29~~ 28 bytes ``` do disp(fix(1/rand)) until 0 ``` [**Try it online!**](https://tio.run/##y08uSSxL/f8/JV8hJbO4QCMts0LDUL8oMS9FU1OhNK8kM0fB4P9/AA) This outputs a sequence \$(x\_k)\$ of independent, identically distributed random natural numbers. Each value \$x\_k\$ is obtained as \$1/r\$ rounded towards zero, where \$r\$ has a uniform distribution on the interval \$(0,1)\$. For a given index \$k\$, and for any \$n \in \mathbb N\$, there is a nonzero probability that \$x\_k=n\$ (ignoring floating-point inaccuracies). Therefore, with probability \$1\$ every \$n\$ appears infinitely often in the sequence \$(x\_k)\$. [Answer] # [R](https://www.r-project.org/), ~~25~~ 21 bytes ``` repeat T=print(T:0+1) ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRCHEtqAoM69EI8TKQNtQ8/9/AA "R – Try It Online") Prints `2..1, 3..1, 4..1` and so forth. Thanks to Robin Ryder for -4 bytes. This works because `print` invisibly returns its first argument. [Answer] # [C (gcc)](https://gcc.gnu.org/), 43 bytes ``` i;main(j){for(;;)printf("%d ",j=--j?:++i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM08jS7M6Lb9Iw9pas6AoM68kTUNJNUVBSSfLVlc3y95KWztT07r2/38A "C (gcc) – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 26 bytes ``` for(a=b='';;)write(a+=--b) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPRNslWXd3aWrO8KLMkVSNR21ZXN0nz/38A "JavaScript (V8) – Try It Online") Character `-` used as a separator and the output starts with it, so I'm not really sure if this is acceptable. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` Do[Print@n,{m,∞},{n,m}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lPzqgKDOvxCFPpzpX51HHvFqd6jyd3NrY////AwA "Wolfram Language (Mathematica) – Try It Online") -1 byte @att [Answer] # [convey](http://xn--wxa.land/convey/), 17 15 bytes *-2 thanks to Jo King!* ``` >1\/v :+<.+} 11 ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiPjFcXC92XG46KzwuK31cbjExIiwidiI6MSwiaSI6IiJ9) Previous version that used a 0-stream and incremented its indices by 1. Jo's variation uses a 1-stream that adds itself to its indices, thus shortening the last row. [![left part](https://i.stack.imgur.com/3NzM5.gif)](https://i.stack.imgur.com/3NzM5.gif) Starting with the top left `0`, we push it to the left. `\` will push its length `1` downward, it will get incremented `+1` and then `length + 1` new 0s will be let through. So we generate `0`, `0 0`, `0 0 0`, … [![first 30 steps](https://i.stack.imgur.com/Tp0ci.gif)](https://i.stack.imgur.com/Tp0ci.gif) Those list get then dumped in a sink `]` while their indices `\.` get incremented `+1` and written to the output `}`: `1`, `1 2`, `1 2 3`, … [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 14 bytes ``` (${$1+1} !1 )+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboW6zRUqlUMtQ1rFRQNFTS1IYJQuQVQGgA) The only choice for the regex to make here is how many times to repeat the `(`...`)+` loop. The first iteration will always print `1` , because the first alternative can't match, as `$1` hasn't been defined yet. On subsequent iterations, `${$1+1}` does math on `$1`, treating its contents as a number. It ignores the trailing space, and adds 1 to it. This then becomes the new value for `$1`, etc. The `!` short-circuiting alternation prevents the second alternative, i.e. `1` , from being taken once it becomes possible for the first alternative, `${$1+1}` , to match. [Answer] ## Arm Thumb (with libc calls), 34 bytes Raw machine code `f7ff fffe` is for libc calls which haven't been linked yet. Needs to be loaded at an address that is **not** a multiple of 4, due to alignment requirements. Yes, it is counterintuitive, but it will make sense later. ``` 2400 a707 3401 2501 0038 0029 f7ff fffe 3501 42a5 d9f8 200a f7ff fffe e7f2 7525 0020 ``` Uncommented Assembly ``` .thumb .globl main .thumb_func main: movs r4, #0 adr r7, str .Lloop1: adds r4, #1 movs r5, #1 .Lloop2: movs r0, r7 movs r1, r5 bl printf adds r5, #1 cmp r5, r4 bls .Lloop2 .Lloop2_end: movs r0, #'\n' bl putchar b .Lloop1 str: .asciz "%u " ``` ### Explanation Equivalent C code: ``` #include <stdio.h> #include <stdint.h> int main(void) { uint32_t N = 0; for (;;) { ++N; for (uint32_t num = 1; num <= N; num++) { printf("%u ", num); } putchar('\n'); } // Unreachable } ``` Since we are never returning from `main`, I say, "to hell with calling convention" and just overwrite the callee-saved registers with our local variables. They won't know the difference. 😈 Specifically, I want r4 to be N (it is incremented before using), and r7 to be our printf string. Unfortunately, we have an odd number of instructions, and `adr` can only load addresses that are 4 byte aligned, so we need to make `main` *not* be 4-byte aligned so the string *is* 4-byte aligned. ``` main: movs r4, #0 adr r7, str ``` Begin printing the natural numbers. Increment N and start counting ℕ in r5. ``` .Lloop1: adds r4, #1 movs r5, #1 ``` `printf("%u ", ℕ)` ``` .Lloop2: movs r0, r7 movs r1, r5 bl printf ``` Increment ℕ and loop while it is less than or equal to N. ``` adds r5, #1 cmp r5, r4 bls .Lloop2 ``` After the second loop: `putchar('\n')` ``` .Lloop2_end: movs r0, #'\n' bl putchar ``` Jump back to the outer loop to increment N. ``` b .Lloop1 ``` The printf string. This must be 4-byte aligned for `adr`, which we do with how we load `main`. ``` str: .asciz "%u " ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ⟦₁ẉ⊥ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGh/u6nzUtfT/fwA "Brachylog – Try It Online") ``` ẉ Print with a newline ⟦₁ the range from 1 to something, ⊥ then try again. ``` [Answer] # [J](http://jsoftware.com/), 13 bytes ``` $:@,~[echo@#\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/VawcdOqiU5Mz8h2UY/5rcoFYCmkKBv8B "J – Try It Online") Outputs `1`, `1 2`, `1 2 3 4`, `1 2 3 4 5 6 7 8`, etc, with every number on its own line. * `echo@#\` Output the prefix lengths of the current list, ie, `1..n` where n is the current list length. This is done as a side effect. * `$:@,~` Append the list to itself `,~` and call the function recursively `$:@`. [Answer] # [Rust](https://www.rust-lang.org/), 54 bytes ``` (2..).for_each(|x|(1..x).for_each(|y|print!("{} ",y))) ``` [Try it online](https://tio.run/##KyotLvmflqeQm5iZp6GpUP1fw0hPT1MvLb8oPjUxOUOjpqJGw1BPrwJZqLKmoCgzr0RRQ6m6VkFJp1JTU/N/7X8A) [Answer] # [Ruby](https://www.ruby-lang.org/), 17 bytes ``` loop{p *1..$.+=1} ``` [Try it online!](https://tio.run/##KypNqvz/Pyc/v6C6QEHLUE9PRU/b1rD2/38A "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` W¹«I⊕ⅉD⸿ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDUFOhmoszoCgzr0TDObG4RMMzL7koNTc1ryQ1RSNLU1PTmovTpTS3QAPEgChTiilSAvJq////r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Works by repeatedly printing the next number to the canvas and then dumping the entire canvas. 2 bytes for a version that prints the \$ n \$th term of a sequence: ``` IΣ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9npXnFv//b2hkbGJqZm5hCQA "Charcoal – Try It Online") Explanation: Simply prints the digital sum of the input. Given any natural number \$ n \$, all the values of the form \$ \frac { 10 ^ n - 1 } 9 10 ^ m \$ have a digital sum of \$ n \$ for every \$ m \$, thus each natural number appears infinitely often. [Answer] # [JavaScript (V8)](https://v8.dev/), 29 bytes ``` for(n=k=1;;)print(n=--n||k++) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPPNtvW0Npas6AoM68EyNPVzaupydbW1vz/HwA "JavaScript (V8) – Try It Online") [Answer] # [Factor](https://factorcode.org/), 32 bytes ``` 1 [ dup bit-count . 1 + t ] loop ``` [Try it online!](https://tio.run/##HcqxCoAgFEbhvaf490hwrQcIl5ZoigYzI8lSbleip7doOct3Vm04UB561bU1dkun9Tg0b3/E7Ph2l0Uky/xEciejKVRX4zKk2WxZYsSSIr6zMiF9LiBRgjHBhxBzfgE "Factor – Try It Online") Loops over the positive integers and prints their bit count (the number of 1 bits, a.k.a. popcount) forever. Outputting nth term would be simply 9-bytes `bit-count`. (I checked that the function works with bigints.) Uses the same logic as [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/215794/78410) that there are infinitely many numbers whose digit sum equals n, except that this one uses bits instead. More precisely, for any positive integer n, \$2^m(2^n-1)\$ for any non-negative integer m has exactly n bits on, so the sequence contains infinitely many n's for any n. [Answer] # JavaScript (Browser), 40 bytes ``` f=(x=1)=>setInterval(_=>alert(x,f(x+1))) ``` Not very competitive answer :( [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~52~~ ~~49~~ 44 bytes Saved 5 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` f(i,j){for(j=1;printf("%d ",j--);)j=j?:++i;} ``` [Try it online!](https://tio.run/##DcFBCoAgEADAu68QIdglPXRNpLeIseFSFhZ0kL7e1kxyS0oiBNkyNtorcBj8UXO5CEw3a2PZOfTIgaex77N/ZIu5AOqm9I8AvXrkTbTG5RR3fw "C (gcc) – Try It Online") ]
[Question] [ The [printable ASCII characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex codes 20 to 7E) in order are: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` (Note that space is in there.) This string clearly contains all the printable ASCII characters at least once in increasing order when read from left to to right, but not in decreasing order. The string reversed: ``` ~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"! NORMAL: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` contains all the printable ASCII characters at least once both in increasing *and* decreasing order. In other words, when the characters are valued with their numeric code, the [longest increasing and longest decreasing subsequences](http://en.wikipedia.org/wiki/Longest_increasing_subsequence) have length 95 (the number of printable ASCII characters). # Challenge Choose a *contiguous* subset of N printable ASCII characters, such as `LMNOP` (N = 5). Write a program using only those N characters whose output contains all 95 ASCII characters in increasing *and* decreasing order like the example above. The winner is the submission with the lowest N. In case of ties the shortest code in bytes wins. # Notes * A contiguous subset means a set of the printable ASCIIs that all appear in an unbroken line, such as `LMNOP` or `89:;<=>`. * Your contiguous subset may "loop around" from `~` to space, but this incurs a +3 penalty on N. So `{|}~` has N = 4, but `{|}~ !` has N = 6 + 3 = 9. * Your program may only contain the N printable ASCII characters from the contiguous subset you've selected. They do not all have to appear and may appear multiple times in any order. **(All non-printable ASCII and all non-ASCII is not allowed. This means tabs and newlines are not allowed.)** * Your output may only contain printable ASCII characters and must be less than 10000 characters long. * Your output's longest increasing and decreasing subsequences must both have length 95 (as explained above). * Output to stdout. There is no input. * N is a positive integer less than 96. [Answer] ## [Unary](http://esolangs.org/wiki/Unary), N=1 ## 4132527913354820031118363262102424570092493175835499123283719 (4.1325279e+60) bytes Source code in unary is obviously too large to post here. It can be easily reproduced by typing out (or generating) a file filled with "0"s of the same length as the number of bytes above. Here is the binary representation: ``` 1010010010010110011000010010010010010010010010001111000000010010010010010110011000010010010010010010010010010010010010010010010010010010010001111000110011001010001100010000000111001110011001011100000111 ``` And the equivalent Brainf\*\*k code (linebreaks for clarity): ``` ++++[->++++++++<]>> +++++[->+++++++++++++++++++<]> [-<+<.+>>]< [-<-.>] ``` Output: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"! ``` **EDIT:** Golfed out 9.097887e+87 unnecessary characters. [Answer] # Brainfuck, N=2 ``` ----------------------------------------------------------------------------------------------------------------------------------.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------. ``` 24,383 bytes. Uses only - and . (ASCII 45 and 46). Try it here: <http://esoteric.sange.fi/brainfuck/impl/interp/i.html>. Can probably be parsed as Morse code with the right spaces. Requires an interpreter adhering to the traditional definition of Brainfuck, which uses an array of (at least) 30,000 *byte* cells, all initialized to zero. [Answer] # Unary, N=1 # 14680262330376163203871465704220787333741951071 bytes Uses only the '0' byte (ASCII 49). Golfed about 4.1325279×1060 bytes out of @Comintern's solution. Credit still to him :) In the original Brainfuck: ``` ++++++++[->++++<]> [>+>+++<<-]>>- [-<.+<+>>]<< [>-.<-] ``` [Answer] # CJam - N=3; 7659 bytes ``` ''(((((((''((((((''(((((''((((''(((''((''('''(')'))')))'))))')))))'))))))')))))))'))))))))')))))))))'))))))))))')))))))))))'))))))))))))')))))))))))))'))))))))))))))')))))))))))))))'))))))))))))))))')))))))))))))))))'))))))))))))))))))')))))))))))))))))))'))))))))))))))))))))')))))))))))))))))))))'))))))))))))))))))))))')))))))))))))))))))))))'))))))))))))))))))))))))')))))))))))))))))))))))))'))))))))))))))))))))))))))')))))))))))))))))))))))))))'))))))))))))))))))))))))))))')))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))'))))))))))))))))))))))))))))')))))))))))))))))))))))))))'))))))))))))))))))))))))))')))))))))))))))))))))))))'))))))))))))))))))))))))')))))))))))))))))))))))'))))))))))))))))))))))')))))))))))))))))))))'))))))))))))))))))))')))))))))))))))))))'))))))))))))))))))')))))))))))))))))'))))))))))))))))')))))))))))))))'))))))))))))))')))))))))))))'))))))))))))')))))))))))'))))))))))')))))))))'))))))))')))))))'))))))')))))'))))')))'))')'(''''(''((''(((''((((''(((((''((((((''((((((( ``` Try it at <http://cjam.aditsu.net/> [Answer] # Brainf\*\*k, N=4 My first brainfuck program. Uses 3 characters out of the block `+,-.` (Ascii 43 to 46.) 410 bytes (one `.` can be deleted from the program if the double `~~` can be reduced to a single `~`.) Here's the list of commands in that area of the ASCII table (I don't need the input command): ``` + increment (increase by one) the byte at the data pointer. - decrement (decrease by one) the byte at the data pointer. . output the byte at the data pointer. , accept one byte of input, storing its value in the byte at the data pointer. ``` Fortunately the remaining commands `<>[]` (moving data pointer and performing conditional jumps) are not required! Split into 3 lines for clarity: **1:** Increment until the data reaches 32. **2:** Output and increment until data reaches 126. **3:** Output and decrement until data reaches 32. ``` ++++++++++++++++++++++++++++++++ .+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+. .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. ``` Output ``` !"#$%&'()*+,-./0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"! ``` # Edit N=2 Per @nneonneo's answer, it is possible to replace each `+` with 255 `-`signs for N=2. some rearrangement of the code and output (displaying down then up) means the first line can be reduced to 256-126=130 `-` signs. This occurred to me after I went to bed, and nneoneo beat me to it. <https://codegolf.stackexchange.com/a/35801/15599> [Answer] # C; N = 43 = 40 + 3 Here I avoid such common characters as `+` `-` `*` `/`, the digits `0-9`, comma `,` and semicolon `;`. So I was forced to express various numbers using only the operations `&` `%` `~`. Further golfing may be possible (finding smallest representations for the numbers 63 and 95 is an exercise for the reader). ``` main(){ if (printf(" !")) if (putchar('"')) if (printf("#$%%&'")) if (putchar('i'%(~' '&'a'))) if (putchar('j'%(~' '&'a'))) if (putchar('k'%(~' '&'a'))) if (putchar('l'%(~' '&'a'))) if (putchar('m'%(~' '&'a'))) if (putchar('n'%(~' '&'a'))) if (putchar('o'%(~' '&'a'))) if (putchar('p'%(~' '&'a'))) if (putchar('q'%(~' '&'a'))) if (putchar('r'%(~' '&'a'))) if (putchar('s'%(~' '&'a'))) if (putchar('t'%(~' '&'a'))) if (putchar('u'%(~' '&'a'))) if (putchar('v'%(~' '&'a'))) if (putchar('w'%(~' '&'a'))) if (putchar('x'%(~' '&'a'))) if (putchar('y'%(~' '&'a'))) if (putchar('z'%(~' '&'a'))) if (putchar('{'%(~' '&'a'))) if (putchar('|'%(~' '&'a'))) if (putchar('}'%(~' '&'a'))) if (putchar('~'%(~' '&'a'))) if (putchar('~'%(~'!'&'a'))) if (putchar(~(~('~'%(~'!'&'a'))&~(~' ' & '!')))) if (putchar(~'!'&'a')) if (putchar(~' '&'a')) if (putchar(~' '&'b')) if (putchar(~' '&'c')) if (putchar(~' '&'d')) if (putchar(~' '&'e')) if (putchar(~' '&'f')) if (putchar(~' '&'g')) if (putchar(~' '&'h')) if (putchar(~' '&'i')) if (putchar(~' '&'j')) if (putchar(~' '&'k')) if (putchar(~' '&'l')) if (putchar(~' '&'m')) if (putchar(~' '&'n')) if (putchar(~' '&'o')) if (putchar(~' '&'p')) if (putchar(~' '&'q')) if (putchar(~' '&'r')) if (putchar(~' '&'s')) if (putchar(~' '&'t')) if (putchar(~' '&'u')) if (putchar(~' '&'v')) if (putchar(~' '&'w')) if (putchar(~' '&'x')) if (putchar(~' '&'y')) if (putchar(~' '&'z')) if (putchar(~' '&'{')) if (putchar(~' '&'|')) if (putchar(~' '&'}')) if (putchar(~' '&'~')) if (putchar(~(~(~' '&'~')&~(~' ' & '!')))) if (putchar(~('!'%' ')&'a')) if (printf("abcdefghijklmnopqrstuvwxyz{|}~}|{zyxwvutsrqponmlkjihgfedcba")) if (putchar(~('!'%' ')&'a')) if (putchar(~(~(~' '&'~')&~(~' ' & '!')))) if (putchar(~' '&'~')) if (putchar(~' '&'}')) if (putchar(~' '&'|')) if (putchar(~' '&'{')) if (putchar(~' '&'z')) if (putchar(~' '&'y')) if (putchar(~' '&'x')) if (putchar(~' '&'w')) if (putchar(~' '&'v')) if (putchar(~' '&'u')) if (putchar(~' '&'t')) if (putchar(~' '&'s')) if (putchar(~' '&'r')) if (putchar(~' '&'q')) if (putchar(~' '&'p')) if (putchar(~' '&'o')) if (putchar(~' '&'n')) if (putchar(~' '&'m')) if (putchar(~' '&'l')) if (putchar(~' '&'k')) if (putchar(~' '&'j')) if (putchar(~' '&'i')) if (putchar(~' '&'h')) if (putchar(~' '&'g')) if (putchar(~' '&'f')) if (putchar(~' '&'e')) if (putchar(~' '&'d')) if (putchar(~' '&'c')) if (putchar(~' '&'b')) if (putchar(~' '&'a')) if (putchar(~'!'&'a')) if (putchar(~(~('~'%(~'!'&'a'))&~(~' ' & '!')))) if (putchar('~'%(~'!'&'a'))) if (putchar('~'%(~' '&'a'))) if (putchar('}'%(~' '&'a'))) if (putchar('|'%(~' '&'a'))) if (putchar('{'%(~' '&'a'))) if (putchar('z'%(~' '&'a'))) if (putchar('y'%(~' '&'a'))) if (putchar('x'%(~' '&'a'))) if (putchar('w'%(~' '&'a'))) if (putchar('v'%(~' '&'a'))) if (putchar('u'%(~' '&'a'))) if (putchar('t'%(~' '&'a'))) if (putchar('s'%(~' '&'a'))) if (putchar('r'%(~' '&'a'))) if (putchar('q'%(~' '&'a'))) if (putchar('p'%(~' '&'a'))) if (putchar('o'%(~' '&'a'))) if (putchar('n'%(~' '&'a'))) if (putchar('m'%(~' '&'a'))) if (putchar('l'%(~' '&'a'))) if (putchar('k'%(~' '&'a'))) if (putchar('j'%(~' '&'a'))) if (putchar('i'%(~' '&'a'))) if (printf("'&%%$#")) if (putchar('"')) if (printf("! ")) {} } ``` The ascii subset is 32...41 and 97...126. I am not sure whether newline characters are allowed in code; if not, just remove them. [Answer] # [Whirl](http://esolangs.org/wiki/Whirl), N=2, 6486 bytes Using only 2 characters, `01`. ``` 000110000011110000100000100000100000100000100000100000100000100000100000100110000011100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001111100000100010011110001000000011111000001000100111100010000000111110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001001111000100000001000011110000010001000001100 ``` Output : ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"! ``` I think I can golf down more using loops, but coding with 0s and 1s was horrible, so I won't do it. ## Commented ``` 00011000001111 // init math.val to O 0000100000100000100000100000100000100000100000100000100000100 // math.val to 32, mem to 32 110000 // set IO to print 0111001111000100000001111100000100 // print ascii(32), mem to 33 01001111000100000001111100000100 // print ascii(33), mem to 34 01001111000100000001111100000100 // print ascii(34), mem to 35 01001111000100000001111100000100 // print ascii(35), mem to 36 // skipped 01001111000100000001111100000100 // print ascii(l23), mem to l24 01001111000100000001111100000100 // print ascii(l24), mem to l25 01001111000100000001111100000100 // print ascii(l25), mem to l26 0100 // print ascii(l26) 111100010000000100001111000001000100 // mem to l25, print ascii(l25) 111100010000000100001111000001000100 // mem to l24, print ascii(l24) 111100010000000100001111000001000100 // mem to l23, print ascii(l23) // skipped 111100010000000100001111000001000100 // mem to 34, print ascii(34) 111100010000000100001111000001000100 // mem to 33, print ascii(33) 111100010000000100001111000001000100 // mem to 32, print ascii(32) 0001100 // KTHXBAI ``` Note that there's `O` and `l` as `0` and `1`. [Answer] # C; N = 61 = 58 + 3 To compensate for using such a large subset, I golfed my code. ``` a;main(d){for(;d&&++a,d||--a;putchar(a+31),a-95||--d);} ``` The ASCII subset is 32...59 and 97...126. It was a fun challenge to avoid the `=` character! [Answer] # Python 2.7 N=45=42+3 This uses `string.printable`, sorts and spits it out over `stdout`. I save a few characters by inserting the `.` in `stdout.write` by using `eval` and string formating using the `ord` values of characters I could use. ``` from string import printable from sys import stdout eval("map(stdout%swrite,sorted(printable,None,ord))"%chr(ord('+') + ord('z')-ord('w') )) print "" eval("map(stdout%swrite,reversed(sorted(printable,None,ord)))"%chr(ord('+') + ord('z')-ord('w') )) ``` ### Out with the old - N=49=46+3 ~~Unfortunately, while python includes the `string.printable` list, this isn't in ascii order, and there is no way to use it without a `*` or a `.`, so it takes less characters to do it manually.~~ Using the character range: ``` abcdefghijklmnopqrstuvwxyz{|}~ AND !"#$%&'()*+,-. print ''.join((chr(i) for i in range( len('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'), len('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') ))) print ''.join((chr(i) for i in range( len('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'), len('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'), -len('x') ))) ``` ### The obvious version: N=63=60+3 This is the obvious version using the character range: ``` [\]^_`abcdefghijklmnopqrstuvwxyz{|}~ AND !"#$%&'()*+,-./01234567 `: print ''.join([chr(i) for i in range(0x20,0x7E)]) print ''.join(reversed([chr(i) for i in range(0x20,0x7E)])) ``` [Answer] # Python 2.7 N=28+12+3=43 Using characters `cdefghijklmnopqrstuvwxyz{|}~` and then wrapping around to `!"#$%&'()*+` ``` exec "print ''" + chr(ord('+') + len('xxx')) # . + "join(chr(i) for i in r" + chr(ord('c') + ~len('x')) # a + "nge(ord(' ')" # 32 + chr(ord('+') + len('x')) # , + " ord('~') + len('x'))) + ''" # 127 + chr(ord('+') + len('xxx')) # . + "join(chr(i) for i in r" + chr(ord('c') + ~len('x')) # a + "nge(ord('~')" # 126 + chr(ord('+') + len('x')) # , + " ord(' ') + ~len('')" # 31 + chr(ord('+') + len('x')) # , + " + ~len('')))" # -1 ``` In order to avoid using `,.-` I had to use some tricks. I used `exec` so I can make the code into strings which allowed me to use `chr(ord('+') + len('xxx'))` for `.` and `chr(ord('+') + len('x'))` for `,`. Any place I needed a -1, I used ~0 in the form of `~len('')`. To avoid `a`, I used `chr(ord('c') + ~len('x'))` (99 - 2). The string that gets composed has N=48, using characters `abcdefghijklmnopqrstuvwxyz{|}~` and then wrapping around to `!"#$%&'()*+,-.` ``` print ''.join(chr(i) for i in range(ord(' '), ord('~') + len('x'))) + ''.join(chr(i) for i in range(ord('~'), ord(' ') + ~len(''), + ~len(''))) ``` Note that the newlines and comments are only for readability. [Answer] # Ruby - N=48 Let Ruby be Ruby and embrace the wrap-around penalty. N=48 <- 15 (' '-'.') + 30 ('a'-'~') + 3 ``` eval "for c in ' '..'~' do putc c end #{('i'.ord-'.'.ord).chr} for c in ' '..'~' do putc ('~'.ord+' '.ord-c.ord).chr end" ``` or ``` eval "(' '..'~').each { |c| putc c } #{('i'.ord-'.'.ord).chr} (' '..'~').each { |c| putc ('~'.ord+' '.ord-c.ord).chr }" ``` Old: N=72 {straight-line scoring} <- 72 ('.'-'u') + invalid newlines ``` format = 67.chr format << 42.chr a = [] for i in 33..126 do a << i end t = a.dup for i in 33..126 do a << t.pop end puts a.pack format ``` There's some flailing in here to avoid the 'v' in "reverse". I left it in because I'm fond of the pack("C\*") hack. [Answer] # [Zsh](https://www.zsh.org/), N = 22 + 2 + 3 = 27 ``` print {~..!} {!..~} ``` [Try it online!](https://tio.run/##bYxBCoMwEADv@4oNBpJQ3EN7C/gYCWmNBFtivBjWr6daLz14G5hh1nmo9ZPClLFsRIKxCKKNKzTo@uiW2GePs3snbwFSeA25k0WP1hrbFoWKSAnFDNE//004JgxwrtvljrI5Erzt8Nvs9MAOpdbXypj6BQ "Zsh – Try It Online") `print` turns out to be the most forgiving way to output for this challenge; `echo` has a "c", and `<<<` ends up too far away too (not to mention brace expansions aren't expanded with it). As for why I used `!` instead of : ``` print {~.. } { ..~} # would save a point, but doesn't work print {~..\ } {\ ..~} # works, but costs 13 points compared to "!" print {~..' '} {' '..~} # works, but costs 6 points compared to "!" print {~.." "} {" "..~} # works, but costs 1 point compared to "!" ``` Instead, we rely on `print` joining the arguments with spaces to get the middle space. [Answer] **x86\_64 Machine Code, Mach-O format** **N = 2, 32768 chars (too large to fit msg limit)** **Edit:** Pastebin is down, so you can find the full text at: <http://www.ionoclast.com/random/golf.bin.txt> [Answer] # Ruby, N = 27 Uses `$` through `>`. ``` $><<(''<<32<<33<<34<<35<<36<<37<<38<<39<<40<<41<<42<<43<<44<<45<<46<<47<<48<<49<<50<<51<<52<<53<<54<<55<<56<<57<<58<<59<<60<<61<<62<<63<<64<<65<<66<<67<<68<<69<<70<<71<<72<<73<<74<<75<<76<<77<<78<<79<<80<<81<<82<<83<<84<<85<<86<<87<<88<<89<<90<<91<<92<<93<<94<<95<<96<<97<<98<<99<<100<<101<<102<<103<<104<<105<<106<<107<<108<<109<<110<<111<<112<<113<<114<<115<<116<<117<<118<<119<<120<<121<<122<<123<<124<<125<<126<<126<<125<<124<<123<<122<<121<<120<<119<<118<<117<<116<<115<<114<<113<<112<<111<<110<<109<<108<<107<<106<<105<<104<<103<<102<<101<<100<<99<<98<<97<<96<<95<<94<<93<<92<<91<<90<<89<<88<<87<<86<<85<<84<<83<<82<<81<<80<<79<<78<<77<<76<<75<<74<<73<<72<<71<<70<<69<<68<<67<<66<<65<<64<<63<<62<<61<<60<<59<<58<<57<<56<<55<<54<<53<<52<<51<<50<<49<<48<<47<<46<<45<<44<<43<<42<<41<<40<<39<<38<<37<<36<<35<<34<<33<<32) ``` [Answer] # Scala, N = 69 ``` \u0028\u0027\u0020\u0027\u0074\u006f\u0027\u007e\u0027\u0029\u002b\u002b\u0028\u0027\u007e\u0027\u0074\u006f\u0027\u0020\u0027\u0029 ``` Uses the characters `01246789\bdefu` (unicode escapes) as a fancy way of writing `(' 'to'~')++('~'to' ')map print`. [Answer] # [Lenguage](https://esolangs.org/wiki/Lenguage), N=1, 1051031305378170472802141990371710130229567839916356530545925757126045319904479746110699524004618985593156618424109188625672742261101447765479880468512170844090412908982576756544352839464930752275112743890775461636401594361137373794023488860005007435006520443129620535092091787646449862714370596024435599036073543700063989003712012285691090357581157986517772 bytes ``` ...1051031305378170472802141990371710130229567839916356530545925757126045319904479746110699524004618985593156618424109188625672742261101447765479880468512170844090412908982576756544352839464930752275112743890775461636401594361137373794023488860005007435006520443129620535092091787646449862714370596024435599036073543700063989003712012285691090357581157986517732 spaces omitted... ``` This gets converted to the brainf\*\*\* program `++++[->++++++++<]>.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.` using the method described [here](https://codegolf.stackexchange.com/a/218529/94066), which outputs `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!` . [Answer] # [Thunno](https://github.com/Thunno/Thunno) `J`, n=25, 21 bytes ``` 32+127:C0126+095:-CA+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSl1LsgqWlJWm6FluNjbQNjcytnA0Mjcy0DSxNrXSdHbUhclAlC6A0AA) Uses `+` (43) to `C` (67) #### Explanation ``` 32 # Push 32 + # Add this to 0 (this is just so that we have # a separator between the numbers - usually # we use a space but that's too far away) 127 # Push 127 : # Get the range between 32 and 127 C # Convert each to a character from a charcode 0 # Push 0 126 # Push 126 + # Add them together (acts as a separator again) 0 # Push 0 95 # Push 95 : # Get the range between 0 and 95 - # Subtract each from 126 C # Convert each to a character from a charcode A+ # Concatenate the two lists # J flag joins into a single string # Implicit output ``` ]
[Question] [ # The Task In this challenge, your task is to write a program or function which takes in a String and outputs a truthy or falsey value based on whether the first character and the last character of the input String are equal. ## Input You may take input in any way reasonable way. However, assuming that the input is present in a predefined variable is not allowed. Reading from a file, console, command line, input field etc., or taking input as a function argument is allowed. ## Output You may output in any reasonable format, except for assigning the result to a variable. Writing to a file, console, command line, modal box, function `return` statements etc. is allowed. ## Additional Rules * The input can be empty String as well, for which you should return a falsey value. * Single-Char Input Strings should have a truthy result. * Your program should be case-sensitive. `helloH` should output a falsey value. * You can only have a single Truthy value and a single Falsey value. For example, outputting `false` for an Input String and `0` for another input String as Falsey values is not allowed. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed. ## Test Cases ``` Input -> Output "10h01" Truthy "Nothing" Falsey "Acccca" Falsey "eraser" Falsey "erase" Truthy "wow!" Falsey "wow" Truthy "H" Truthy "" Falsey ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), 23 bytes ``` s=input() s[0]!=s[-1]<e ``` Output is via exit code, so **0** (success) is truthy and **1** (failure) is falsy. If [this](https://codegolf.meta.stackexchange.com/a/11908/12012) is acceptable, a byte can be saved. [Try it online!](https://tio.run/nexus/bash#XY29CoNAEIRr7ynWQ7mkUBSrJGdCulR5AbUQf@I1e@KuiE9vFtJlYGY@mGK6luEOxO3C5YB9Ou9gLaQHlQ7nlU9nRVXWhCVVSd7Y4kiVGv0CBA7B5NmU5QbM2/Pk8CP07EStwOa38FeSL7G5Qe9VMO88eSz@Hy3oiLTMi0MewcTJha4QrzUa0LVstdYQPVQQqN7jcHwB "Bash – TIO Nexus") ### How it works First of all, if **s** is an empty string, `s[0]` will raise an *IndexError*, causing the program to fail. For non-empty **s**, if the first and last characters are equal, `s[0]!=s[-1]` will evaluate to *False*, so the program exits cleanly and immediately. Finally, if the characters are different, `s[0]!=s[-1]` will evaluate to *True*, causing the compairson `s[-1]<e` to be performed. Since **e** is undefined, that raises a *NameError*. If backwards compatibility with Python 2 is not desired, ``` s[0]!=s[-1]<3 ``` works as well, since comparing a string with an integer raises a *TypeError*. [Answer] # JavaScript, 19 bytes ``` a=>a.endsWith(a[0]) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` h~t? ``` [Try it online!](https://tio.run/nexus/brachylog2#@59RV2L//79SSWpxiRIA "Brachylog – TIO Nexus") ### Explanation ``` h The head of the Input... ~t? ...is the tail of the Input ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` S¬Q¤ ``` [Try it online!](https://tio.run/nexus/05ab1e#@x98aE3goSX//xsaZBgYAgA "05AB1E – TIO Nexus") or [Try All Tests](https://tio.run/nexus/05ab1e#K6v8H3xoTeChJf8rlQ7vt1JQstf5H61kaJBhYKiko@SXX5KRmZcOZDkmA0EikFGeX64IoYCkBxArxQIA "05AB1E – TIO Nexus") ``` S # Split the input into individual characters ¬ # Get the first character Q # Check all characters for equality to the first ¤ # Get the last value i.e. head == tail ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` =ṚḢ ``` [Try it online!](https://tio.run/nexus/jelly#@2/7cOeshzsW/f//X0kJAA "Jelly – TIO Nexus") [Answer] # Mathematica, 15 bytes ``` #&@@#===Last@#& ``` Takes an array of chars. Throws errors when the input is empty but can be ignored. [Answer] # [Haskell](https://www.haskell.org/), 21 bytes `c` takes a `String` and returns a `Bool`. ``` c s=take 1s==[last s] ``` [Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlEpzcvJzEst1stNLNCIKda1K87IL1co1tZWUtC1U1DS1gbxNZIVijU19cAK/wPZtiWJ2akKhsW2ttE5icUlCsWx//8bGmQYGHL55ZdkZOalczkmA0EiV3l@uSKI4PLg4gIA "Haskell – TIO Nexus") * If not for empty strings, this could have been 16 bytes with `c s=s!!0==last s`. * `take 1s` gives a list that is just the first element of `s` unless `s` is empty, in which case it's empty too. * `last s` would error out on an empty string, but Haskell's laziness saves it: A string with a single element is always different from the empty string, without evaluating its element. [Answer] # [Retina](https://github.com/m-ender/retina), ~~13~~ 12 bytes ``` ^(.)(.*\1)?$ ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/gfp6GnqaGnFWOoaa/y/7@hQYaBIZdffklGZl46l2MyECRyleeXK4IILg8uAA "Retina – TIO Nexus") Includes test suite. Edit: Saved 1 byte thanks to @Kobi. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 40 bytes ``` [](auto s){return s[0]&&s[0]==s.back();} ``` [Try it online!](https://tio.run/##RYyxDoMwEEP3@4oTlVAytOoewo8ghvQIKGoJiLtMiG9PUxjqwbKeZdO63ieifAuRPmnw2LBsIU4t/ElYCvNubgESlw6jmz2vjjyyDAYgRMHZhag07IBF1wcKWqwqcyKXZMERbe56dWbW@@YlbRG5e/Z1/XNr@fFy9FbaHPna0ZIEmwZHJdrAkb8 "C++ (gcc) – Try It Online") [Answer] # Java, ~~81~~ 77 bytes * -4 bytes, thanks @KevinCruijssen [**Try Online**](http://ideone.com/cNSyOT) ``` boolean f(String s){int l=s.length();return l>0&&s.charAt(l-1)==s.charAt(0);} ``` * Returns `true` if they're equal, otherwise `false`, `false` for empty string **Array Version, 60 bytes** ``` boolean f(char[]s){int l=s.length;return l>0&&s[0]==s[l-1];} ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~26~~ ~~25~~ 24 bytes Thanks to *@Dennis* for saving a byte! ``` lambda x:""<x[:1]==x[-1] ``` [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqFBhpaRkUxFtZRhra1sRrWsY@7@gKDOvRCFNQ8nQIMPAUEmTCy7gl1@SkZmXjizkmAwEicgi5fnlimh8ZK4HMkdJ8z8A "Python 2 – TIO Nexus") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 43 bytes ``` +>,[<,[>[->+<<->],]]<[[-]-<]-[----->+<]>--. ``` [Try it online!](https://tio.run/nexus/brainfuck#FcmxDQAgEALAgXyM9oRFCL37L/DqtddDZZZlaJBQKqGNgIHxvYiA2b3XWfsC "brainfuck – TIO Nexus") ### Explanation The main loop is `[>[->+<<->],]`. After each iteration, the cell to the right of the current position is the first byte of the string, and the cell to the left is the difference between the most recently handled character and the first. `<[[-]-<]` converts the final result to -1 if nonzero, and the rest converts -1 and 0 to 48 and 49 ("0" and "1") respectively. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes ``` ⊃⌽=⊃ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG3Co67mRz17bYHU//@OCuqGBhkGhupcQFZ5fjmY9gCTfvklGZl56WC2YzIQJMIUKYIZ6gA "APL (Dyalog Unicode) – TIO Nexus") ### Explanation ``` = Compare ⊃ The first element of the right argument with ⌽ The right argument reversed This will return an array of the length of the reversed argument. Each element in the resulting array will be either 0 or 1 depending on whether the element at that position of the reversed argument equals the first element of the original right argument So with argument 'abcda', we compare 'a' with each character in 'adcba' which results in the array 1 0 0 0 1 ⊃ From this result, pick the first element. ``` Here is the reason this works on empty strings. Applying `⊃` to an empty string returns a space . But reversing an empty string still returns an empty string, so comparing an empty string with a non-empty string (in this case ) gives an empty numerical vector. And applying `⊃` to an empty numerical vector returns `0`. Hence passing an empty string returns `0`. [Answer] # MATL, 5 bytes ``` &=PO) ``` Try it at [MATL Online!](https://matl.io/?code=%26%3DPO%29&inputs=%27abcd%27&version=19.10.0) **Explanation** ``` % Implicitly grab input as a string (of length N) &= % Perform an element-wise equality check yielding an N x N matrix P % Flip this matrix up-down O) % Get the last value in the matrix (column-major ordering) % Implicitly display the result ``` In the case, that an empty input string must be handled, then something like the following (8 bytes) would work ``` &=POwhO) ``` This solution simply prepends a `0` to the front of the N x N matrix such that for an empty input, when the matrix is `0 x 0`, there's still a `0` value that is then grabbed by `0)` Try it at [MATL Online](https://matl.io/?code=%26%3DPOwhO%29&inputs=%27abcd%27&version=19.11.0) [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` tJ ¥Ug ``` [Try it online!](https://tio.run/nexus/japt#@1/ipXBoaWj6//9KjkmOSgA "Japt – TIO Nexus") [Answer] # Java, ~~52~~ 43 bytes ``` s->!s.isEmpty()&&s.endsWith(""+s.charAt(0)) ``` To make it work, feed this into a function such as the following that makes a lambda "go": ``` private static boolean f(Function<String, Boolean> func, String value) { return func.apply(value); } ``` [Answer] # Ruby, ~~26~~ 24 bytes *Saved two bytes thanks to [@philomory](https://codegolf.stackexchange.com/users/47276/philomory)!* ``` ->e{!!e[0]>0&&e[0]==e[-1]} ``` First post on codegolf -)) [Answer] # [GNU grep](https://www.gnu.org/software/grep/), 12 bytes ``` ^(.)(.*\1)?$ ``` Run in extended or PCRE mode. I don't know if this is considered cheating or not. [Answer] ## JavaScript, 20 bytes Add `f=` at the beginning and invoke like `f(arg)`. ``` _=>_[0]==_.slice(-1) ``` ``` f=_=>_[0]==_.slice(-1) i.oninput = e => o.innerHTML = f(i.value); ``` ``` <input id=i><pre id=o></pre> ``` ### Explanation This function takes in an argument `_`. In the function body, `_[0]==_.slice(-1)` checks whether the first element of `_` (at `0`th index) equals the last element of it, and returns the appropriate `true` or `false` boolean. [Answer] # PHP>=7.1, 23 Bytes prints 1 for equal and nothing if the character is different ``` <?=$argn[0]==$argn[-1]; ``` [Answer] ## C#, ~~38~~ 30 bytes ``` s=>s!=""&&s[0]==s[s.Length-1]; ``` *Saved 8 bytes thanks to @raznagul.* [Answer] ## R, 40 bytes ``` function(x)x>""&&rev(y<-charToRaw(x))==y ``` Thanks to Nitrodon for -2 bytes. Thanks to MickyT for -8 bytes. Test: ``` f=function(x)x>""&&rev(y<-charToRaw(x))==y test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "") sapply(test, f) all(sapply(test, f) == c(T, F, F, F, T, T, F)) ``` Output: ``` > f=function(x)x>""&&rev(y<-charToRaw(x))==y > test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "") > sapply(test, f) 10h01 Nothing Acccca wow! wow H TRUE FALSE FALSE FALSE TRUE TRUE FALSE > all(sapply(test, f) == c(T, F, F, F, T, T, F)) [1] TRUE ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~39~~ 33 bytes ``` 2i&01. >~&-?v1v i:1+?!^01. >0>n; ``` This is my first time both using ><> and playing code golf, so helpful suggestions would be appreciated. The code is in three basic sections. ``` 2i&01. Pushes an arbitrary number (2 in this case, this causes an empty string to print 0) onto the stack and puts the input's first character in the register. >i:1+?!^01. Main loop. Pushes the next character onto the stack. If the string has been read completely, then go to the last section >~&-?v1v >0>n; Compare the first and last characters. Print 1 if they're the same, 0 if not ``` [Answer] # [shortC](//github.com/aaronryank/shortC), ~~27~~ ~~26~~ ~~25~~ 24 bytes ``` f(C*s){T*s&&*s==s[Ss)-1] ``` How it works: ``` f(C*s){ declare int-returning function that takes a string T return *s provided string has any length && and *s==s[Ss)-1] the first character equals the last one ``` [Try it online!](https://tio.run/##LcmxCoMwEAbgVzkClVywQ2dx6iM0W@kQ6kkONC35Dxykzx47OH3Dh/yp9m5r0uJ5/1YtNnt3mVz/J2YFwVI10KaWybIQ0iq0iJlUSiA1kjKdHx3z8GuzvwfwHgO6LmAc8XyAr7dXawc) [Answer] # Google Sheets, 33 Bytes Takes input from cell `[A1]` and outputs `1` for truthy input and `0` for falsey input. ``` =(A1<>"")*Exact(Left(A1),Right(A1 ``` It is noted that the parentheticals in `Exact(` and `Right(` are left unclosed as Google Sheets automatically corrects this as soon as the user has input the formula text and pressed enter to leave that cell. ### Output [![GS Version](https://i.stack.imgur.com/hyFkX.png)](https://i.stack.imgur.com/hyFkX.png) [Answer] # R, ~~50~~ ~~43~~ ~~41~~ ~~40~~ 64 Second solution with 41 bytes for a callable function - thanks to @niczky12 & @Giuseppe - amended for x="" ``` r=function(x,y=utf8ToInt(x))ifelse(x=="","FALSE",(y==rev(y))[1]) ``` First with 50 bytes but not for the challenge ``` function(x){charToRaw(x)[1]==rev(charToRaw(x))[1]} ``` [Answer] # [Mornington Crescent](https://github.com/padarom/esoterpret), 2585 bytes ``` Take Northern Line to Bank Take Circle Line to Hammersmith Take District Line to Mile End Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Hammersmith Take Circle Line to Victoria Take District Line to Parsons Green Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upney Take District Line to Hammersmith Take District Line to Bow Road Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminals 1, 2, 3 Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Parsons Green Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Barking Take District Line to Hammersmith Take District Line to Mile End Take District Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Notting Hill Gate Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Upminster Take District Line to Temple Take District Line to Barking Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upney Take District Line to Barking Take District Line to Hammersmith Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Aldgate Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Bank Take Circle Line to Bank Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Angel Take Northern Line to Bank Take Circle Line to Temple Take District Line to Bow Road Take District Line to Upney Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Bow Road Take District Line to Hammersmith Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Aldgate Take Circle Line to Victoria Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Angel Take Northern Line to Bank Take District Line to Upney Take District Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` [Try it online!](https://tio.run/##3VZNb8IwDL3vV@S0Ezts@wXAJjhQhKZu96h4NCKxkWOp4tez7ANQ26XQMpi283P8nOdnJ44YDS6E8CZj8BmgbDapXoKaEksOjGpiEJSQGmhcXn1AQ8OZhR0w1s4Be2ck/8QfjBc2mewiEhPCH3EegfeZa6TDXHOoTw2ZvD8h5oTin1fOoBfgCF7LUGF4CcHERkeOzzR7Qq9GDIAHBepQPcL62MrrxFSoJ9KxxvXDzVClVHwVPjNZpufG2vWeA7TkHNKkwEFHbb267am7nrqPHqlmPUh7aU0HmpfBcJ1VPXocKpX95pxEgSmJvGcdhx6qkRZoE9V62A7hKbiVhU59O9OQtTRLhbtv54uYpiUsAWFakTWiSx23r4SirtVEi3Fb2b4NbqI6fUu2N9YFr54QcZSrDNYmpo8LsG2nqdmmzUu32Wzdl1oz6x8xavmx/c@O@hlfNDwpye5rGF6M7dewoOIN "Mornington Crescent – Try It Online") I thougt, this was easier... Outputs 0 for false and 1 for true ``` // Prepare input for right substring Take Northern Line to Bank Take Circle Line to Hammersmith Take District Line to Mile End // Get char code of first character Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross // Put it in Upminster for later calculation Take Northern Line to Bank Take Circle Line to Hammersmith Take District Line to Upminster // Also save it for later check for null string # Victoria = char code of first Take District Line to Hammersmith Take Circle Line to Victoria // Save 0 # Upney = 0, Bow Road = 0 (for second loop) Take District Line to Parsons Green Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upney Take District Line to Hammersmith Take District Line to Bow Road // Save 1 # Barking = 1 Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminals 1, 2, 3 Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Parsons Green Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Barking // Get char code of last letter of input Take District Line to Hammersmith Take District Line to Mile End Take District Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross // Bitwise NOT, so we get -(char count)-1 Take Northern Line to Bank Take Circle Line to Bank Take Circle Line to Notting Hill Gate Take Circle Line to Notting Hill Gate // Add it to the char code of first letter. If they match, the result is -1. Take District Line to Upminster // Save the result in Upminster Take District Line to Upminster // ******************************************************************************** // * Add some logic. This is quite puzzling because the only control structure * // * in Mornington Crescent is a post-test loop. You don't have something like * // * an if-else. You can't skip code. You can only define how often a loop should * // * be repeated. * // * My solution to this is: When checking if the first and last character * // * are the same (first char code - last char code = 0), I swap the positions * // * of the 0 and 1 variables, then multiply the result of the equality check * // * with the new position of 1. If the characters are the same, the loop will * // * exit after the first run. If not, it will run another time, swapping the * // * 0 and 1 back and exiting after the second run, because it multiplies the * // * new equality check with 0. * // ******************************************************************************** // Set starting line of loop Take District Line to Temple // Swap 0 and 1 # Upney = 1, Barking = 0 (on the first run) Take District Line to Barking Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upney Take District Line to Barking // Save 1 in Chalfont & Latimer for later multiplication Take District Line to Hammersmith Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer // Add 1 to Upminster, to check for equality Take Metropolitan Line to Aldgate Take Circle Line to Hammersmith Take District Line to Upminster // Multiply the result with 1 in the first run, or 0 in the second run Take District Line to Bank Take Circle Line to Bank Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer // If the result is not 0, run the loop again Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Angel // ********************************************************************** // * Another control loop to check for empty string. * // * The previous loop will return true if an empty string was entered. * // ********************************************************************** // Set start of loop Take Northern Line to Bank Take Circle Line to Temple // Swap 0 and 1 # Upney = 0, Bow Road = 1 (on the first run, if previous loop ran once) // # Upney = 0, Bow Road = 0 (if previous loop ran twice) Take District Line to Bow Road Take District Line to Upney Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Bow Road // store 1 in Chalfont & Latimer for later multiplication Take District Line to Hammersmith Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer // Multiply by char code of first char (0 if empty string) Take Metropolitan Line to Aldgate Take Circle Line to Victoria Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer // Loop again if input not empty Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Angel // Fetch result and go home for output Take Northern Line to Bank Take District Line to Upney Take District Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` [Answer] # [BRASCA](https://github.com/SjoerdPennings/BRASCA), 3 bytes This looks like a job for `M`! ``` M=n ``` [Try it online!](https://tio.run/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FqYuN/G6CJAybmjHkPYW8B9YWzywn@93Ad6D/oQGcscG1cirZuJiniVT92ZQuTueU6AoB8aMkacOqQD5Hr1yR2qXXU66BWH@UalFpEHxDRD4ACZ3NzmFiHTYpc1AKqem4/ZNzwLmozdj2V3aYBu3Nk91@se@7JoulywX1Z3fGc9wuc9K5cYCkrpd72RY2FqqTKhMpfEqitptZKe1GQFobk25J1/1ZFNfGkl6vLugqXL81Kxc4MacbXNSXNlrpyiS8nSSn8gMldnzC7p4x3YZN6uPJVCX1xvP52xPoZ3muyBUwNp2Q@Yx4s8TkwDmRUCRtsCmynsHq3agrkmxXcqfeXMjTHyFoWkciDBc2eXnUyL1XhJeAKpSrrR/IMLb2tW7yla5QC2dWE@YL8yBZjDokHi62CIPJF4dJbOZsnHV/LP5C20ZAFcdZPucviW85z5gkyD7h32cWjAD4H4xDgxFW48VR67fXJyfHJLtF1Lxy@xx2ye/x9SNcuFSMAVzyFyYkQXwQ5TBw3ubfSarpwWLZVQgB8TLPCWHnQf439UDpcOQvRYMTQ12MsL1Zp3Zqtgrg@QJe0aZmsllyizzK5FWI3Frle3OaiVoqJn8//Bw "Python 3.8 (pre-release) – Try It Online") ## Explanation ``` M - Move the bottom of the stack to the top = - Are they the same? Push 1 if it is, 0 if it isnt. n - Output as number. ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 20 bytes ``` O<!=xP?AxA Gx-Lx 1 1 ``` [Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKWyNXxJJcFVbtmUXyQKhlkAWktsP4AtClkF1suyTZF6WkL@e6@550cgWucvd8sGyZp7u6X6mp7vHBL2bIPj@KkqCeDUNh1k@jRavb0d1cySOrktDQf64DNdAaZTclIbyaC4w03AWJSGLYxYvkhv6qOvRTyefPzCneD3/dMbc4vXve2dst3g9OHnHfilezz4zpwAfHJ8b2JPPxwb088mHvfPfrIwzCz@a7JvzN65n985hWTEZ3Popa/NCwESBrVrFaMR2i7mT/T9wMoFJ8ugrw@/D4RoGly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J/H1ziK3l0j40AFMZGt4hx/XKDFdV5UkJ6JUUuuUWbKaciaetT3MtJ@2RANG5ZQNt3j/RhL6CN4nUzjcMquCrOvtJYn/Cb6N2ORwpkRKuv11DsneE1C24bpz7rzGFKwrtVHTHqlvOiVs@KYmYd/aB4DFO3LX@eaTADGrNRP0mCXGdkQddhCUlVmV5QLxG55UJSMZmkEhxJDazFd9Nk8nAdLDLOEja7G/68ro7/AlZFyZavCF0/6Il0Zv8y@WLXCZJwesxLA1QhX1dmtKjuLF@2eyjymAm1es0h/6EtVbRibkjKVaPmv/428zEGGGi0/aPVNdKkbXsd6RdYtT//0fUe1wMWFB3G10qVHp0LCoMaJV5I20iRKIKLT0WLC5D/APfHrmNmPlrxjFS3OUbm5R6ghP3b7OwYth@Jm4RmNWMcsQJtXqUTeT7r6LOyU@t5zQfSa0sF6yXOrSt4O132Aq6V3afA/NERoGD5xKwJ9R9DtkNkbueAhrtpxsEmiBkHEv5ikByE68iTA6tNw5kOSBM9UIxolMBlN6bcmP8ihTLW2gxa2pjjC2QuXXVSmayB0g/L3hrkfJdjTMj@9CbqktN2G73ccf9Wiayj@s8eyyZrybe/5@/v3/vt/Aw "C (gcc) – Try It Online") Takes a line from stdin and prints `true` if equal and `false` otherwise. ``` O Output the result of: < ! (= x P) x = input; x is not null and ? A x the first char's ord is equal to A (G x (- L x 1) 1) the (length-1)th char's ord ``` [Answer] # Swift, 46 bytes ``` var s=readLine()!,a=Array(s);a[0]==a.last ?1:0 ``` ]
[Question] [ # Description Output the rhyme scheme for a very long Terza Rima. # Input None. # Output ``` ABA BCB CDC DED EFE FGF GHG HIH IJI JKJ KLK LML MNM NON OPO PQP QRQ RSR STS TUT UVU VWV WXW XYX YZY ``` # Rules You can pick between separating stanzas with whitespace or newlines, so either: ``` ABA BCB... ``` OR ``` ABA BCB ... ``` A single trailing whitespace allowed per line and one trailing newline allowed. Output can be either uppercase or lowercase. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins. [Answer] # JavaScript (ES6), ~~51~~ ~~50~~ 49 bytes *Saved 1 byte thanks to @l4m2* ``` f=(n=45358)=>n%63?f(n-1333)+n.toString(36)+' ':'' ``` [Try it online!](https://tio.run/##BcH/CkAwEADgV/GPdpcoHZIaD@EJxKb5cadtKU8/33cs7xJW755Yhsdtxt/Cp/lSshpYNy21PeqR844mC1zWRIQFV1Hm6B3vQB0WKlODUmkVDnKZ6pIdLCCmHw "JavaScript (SpiderMonkey) – Try It Online") ### How? We start with **n = 45358** (**yzy** in base-36). We subtract **1333** from **n** at each iteration (**111** in base-36). We stop as soon as **n MOD 63 = 0**, because **12033** (**9a9** in base-36) is the first value for which this condition is fulfilled, and **63** is the smallest modulo with such a property. ``` Decimal | Base-36 | MOD 63 --------+---------+------- 45358 | yzy | 61 44025 | xyx | 51 42692 | wxw | 41 41359 | vwv | 31 40026 | uvu | 21 38693 | tut | 11 37360 | sts | 1 36027 | rsr | 54 34694 | qrq | 44 33361 | pqp | 34 32028 | opo | 24 30695 | non | 14 29362 | mnm | 4 28029 | lml | 57 26696 | klk | 47 25363 | jkj | 37 24030 | iji | 27 22697 | hih | 17 21364 | ghg | 7 20031 | fgf | 60 18698 | efe | 50 17365 | ded | 40 16032 | cdc | 30 14699 | bcb | 20 13366 | aba | 10 12033 | 9a9 | 0 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 41 bytes ``` f(i){for(i='ABA';i%29;i+=65793)puts(&i);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPTVt3RyVHdOlPVyNI6U9vWzNTc0lizoLSkWEMtU9O69n9mXolCbmJmnoZmNRdnmoamNRdnUWpJaVGegoE1V@1/AA "C (gcc) – Try It Online") Fixed and -9 thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729). -1 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) and -2 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) too. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ØAṡ2ŒBY ``` [Try it online!](https://tio.run/##y0rNyan8///wDMeHOxcaHZ3kFPn/PwA "Jelly – Try It Online") -1 byte thanks to Dennis ``` ØAṡ2ŒBY Main Link ØA Alphabet ṡ2 Slice into overlapping slices of length 2 ŒB Palindromize (bounce) each Y Join by newlines ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~51~~ 48 bytes *Saved 3 bytes thanks to @ovs.* ``` ++++++++[>+>+++>++++++++<<<-]>++>+[->+.+.-.<<.>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwqi7bTtgJQdjG9jY6MbawcSsNO2ida109PW09UDiurZxf7/DwA "brainfuck – Try It Online") ## Explanation ``` INITIALIZE TAPE: 0000: (none) 0001: C_NEWLINE (10) 0002: V_COUNT (25) 0003: V_ALPHA (64) ++++++++[>+>+++>++++++++<<<-]>++>+ V_COUNT TIMES: [- INCREMENT V_ALPHA >+ PRINT V_ALPHA . PRINT V_ALPHA PLUS ONE +. PRINT V_ALPHA -. PRINT C_NEWLINE <<. END LOOP >] ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~51~~ 49 bytes ``` +++++[>+++++>+++++++++++++>++<<<-]>[>.+.-.+>.<<-] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwSi7cAUhIQBIM/GxkY31i7aTk9bT1dP204PxP3/HwA "brainfuck – Try It Online") An attempt at an explanation... ``` +++++ #Put 5 in cell 0 because that is the highest common denominator of 10, 65 and 25 [ #Start loop >+++++ #Counter in cell 1 is 25 (How many lines we must print) >+++++++++++++ #Counter in cell 2 is 65 (ASCII A) >++ #Counter in cell 3 is 10 (Newline) <<<-] #Decrement the outer counter until the cells have the right values (muliples of 5). > #Move to the counter that says how many lines we must print. [>. #Print the character in cell 2 +. #Add one to the character in cell 2 and print it -. #Subtract one from the character in cell 2 and print it + #Add one to the character in cell 2 for the next loop >. #Print a new line <<-] #Decrement cell 1 and run again until cell 1 is 0 ``` -2 with thanks to @ovs My first attempt at brainfuck so any hints gratefully received. If I was more experienced with it then I am sure I could shave a few more bytes off but I only got into it yesterday. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` Aü«€û ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f8fCeQ6sfNa05vPv/fwA "05AB1E – Try It Online") -1 byte thanks to Emigna -1 byte thanks to rule change; thanks to kalsowerus for pointing that out Hehe, currently beats Pyth. \o/ # Explanation ``` Aü«€û Full Program A Lowercase Alphabet ü« Pairwise with merge-list €û For each, palindromize ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes -1 byte thanks to Halvard Hummel ``` i=65;exec"print'%c'*3%(i,i+1,i);i+=1;"*25 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWzNQ6tSI1WamgKDOvRF01WV3LWFUjUydT21AnU9M6U9vW0FpJy8j0/38A "Python 2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes ``` 25↑0 1 0⊖3/⍪⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4xMH7VNNFAwVDB41DXNWP9R7yqguOP//wA "APL (Dyalog Unicode) – Try It Online") Please note that the added `⎕←` is for TIO to output the text and is not normally required. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` E²⁵✂αι⁺²ι‖O ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDyFRHITgnMzlVI1FHIVNHISCntFjDCMjUBAJrrqDUtJzU5BL/stSiHKBqTev////rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ²⁵ Literal 25 E Map over implicit range α Predefined uppercase letters ✂ ι⁺²ι Slice 2 characters Implicitly print result on separate lines ‖O Reflect with overlap ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 90 bytes ``` ((((()()()){}){}){}()){(({})<((({}((((()()()()){}){}){}){})())[()])((()()()()()){})>[()])} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMENEFQs7oWgkBMDQ0g00YDRCFUIKkBISA3WkMzVhMhDVFgBxat/f//v64jAA "Brain-Flak – Try It Online") One reason this is shorter than the other brain-flak answer is because it uses uppercase instead of lowercase characters, which have smaller ASCII values, and are therefore easier to push. Explanation: ``` #Push 25 ((((()()()){}){}){}()) #While true { #Keep track of the number on top of the stack... # We'll call it 'a' (({}) #Push A +... <((({} # 64 (push) ((((()()()()){}){}){}){}) # + 1 (push) ()) # - 1 (push) [()]) # Push 10 ((()()()()()){})> # Now that's all pushed, we push a - 1 to decrement the loop counter [()]) # Endwhile } ``` [Answer] # R, ~~51~~ 47 bytes ``` L=LETTERS;cat(sprintf("%s%s%1$s",L[-26],L[-1])) ``` Output: ``` > L=LETTERS;cat(sprintf("%s%s%1$s",L[-26],L[-1])) ABA BCB CDC DED EFE FGF GHG HIH IJI JKJ KLK LML MNM NON OPO PQP QRQ RSR STS TUT UVU VWV WXW XYX YZY ``` [Answer] # [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html), ~~132~~ ~~85~~ ~~62~~ 60 Bytes * 47 bytes thanks to Neil * 26 bytes thanks to Oliver * 3 bytes and much better formatting thanks to Kevin * Error fixed by Oliver # Golfed ``` a->{for(char i=64;++i<90;)System.out.println(""+i+++i--+i);} ``` # Ungolfed ``` public class TerzaRima { interface A{ void a(String a); } static A a = a -> { for (char i = 64; ++i < 90; ) System.out.println("" + i++ + i-- + i); }; public static void main(String[] args){ a.a(null); } } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~25~~ ~~24~~ ~~23~~ 22 bytes Saved 2 bytes thanks to *Jo King* ``` "!;::o1+:o$oao:'Y')0.A ``` [Try it online!](https://tio.run/##S8sszvj/X0nR2soq31DbKl8lPzHfSj1SXdNAz/H/fwA "><> – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~45~~ 37 bytes ``` +[[<+>>++<-]>]<<---[-----<+.+.-.<.>>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fOzraRtvOTlvbRjfWLtbGRldXN1oXBGy09bT1dPVs9OzsYv//BwA) Prints in uppercase, separated by spaces with a trailing space. ### How it Works: ``` +[[<+>>++<-]>] Intialises the tape with the format n^2 1 2 4 8 16 32 64 128 0 0' <<--- Navigates to the desired section and tweaks the counter 1 2 4 8 16 32 64 125< [-----<+.+.-.<.>>] Prints the Terza Rima, using: 125 as the loop counter (decremented by 5 each loop) 64 as the current alphabetic character (incremented and printed each loop) 32 as the space character ``` [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~27~~ ~~23~~ 21 bytes -4 bytes thanks to [James Holderness](https://codegolf.stackexchange.com/users/62101/james-holderness) ``` j'@1+3k:,1+,,a,'Y/!1+ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/P0vdwVDbONtKx1BbRydRRz1SX9FQ@/9/AA "Befunge-98 (FBBI) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `j`, 3 bytes ``` nzʁ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJqIiwiIiwibnrKgSIsIiIsIiJd) ``` n # Lowercase alphabet z # Overlapping pairs of elements ʁ # Mirror each # (j flag joins list of lines by newlines) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ẊS:`e…"AZ ``` [Try it online!](https://tio.run/##yygtzv7//@GurmCrhNRHDcuUHKP@/wcA "Husk – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 41 bytes ``` -[[<+>--->++>>>+<<<<]>+]>>>[<<.+.-.+>.>-] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fNzraRttOV1fXTlvbzs5O2wYIYu20Y4HsaBsbPW09XT1tOz073dj//wE "brainfuck – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` jC[GtGG ``` **[Try it here!](https://pyth.herokuapp.com/?code=jC%5BGtGG&debug=0)** ~~Hehe, currently beats Jelly. \o/~~ Easily translates to the follwong 05ab1e program: # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` AA¦A)ø» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0fHQMkfNwzsO7f7/HwA "05AB1E – Try It Online") [Answer] # [J](http://jsoftware.com/), 15 bytes ``` u:2$~&3\65+i.26 ``` [Try it online!](https://tio.run/##y/r/PzU5I1@h1MpIpU7NOMbMVDtTz8js/38A "J – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~34~~ ~~32~~ 31 bytes Based on [totallyhuman's](https://codegolf.stackexchange.com/users/68615/totallyhuman) answer. **-1** byte thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) ``` do x<-['A'..'Y'];x:succ x:x:" " ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmFdcnlpkG/M/JV@hwkY3Wt1RXU9PPVI91rrCqrg0OVmhwqrCSklB6X9uYmaegq1CQWlJcEmRAkTb/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 180 bytes ``` (()()())(({}){})(({}){})(({}){})(({}){})(({}){}())<>(()()()()())(({}){})(({}){})(()()()()(){}){({}[()])<>(({}))(({}()))(({}[()]))({}()<(()()()()()()()()()())>)<>}<>{}{}{({}<>)<>}<> ``` [Try it online!](https://tio.run/##hY65asNAEIb7eQqXUmHQypcEQqD78CFbtxJSOEUgJKRIa/Tsyv6riXETwor9vpmdX8zr9/X9a/n2ef2YJk3TcXRNu426/P6hnHRczvyRu7@hIbvPmv6iQrJWYzKlqB501XAeYg8/d2VudNzbKI@cc7iePN9b2LuFbcmb/MBXZsubgjCACcOQoDAKlQpDgBTFEbsJUpzEvw5SkiZcr1SdZin7GqQsz9g3IOX7nH0L0v6wZ9@BdDge2C2QjqcjO1a06FScZhfY0abiXMwuBEjny5ndBOlSXthXIJVVyb4Gqaor9g1IdVOzb0Fq2oZ9B1LbtewWSF3fsWMni/qhn93ETjYNT8PspgCnaen9AA "Brain-Flak – Try It Online") Thanks to DJ for getting this working [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` [[x,succ x,x]|x<-['A'..'Y']] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfYxvzPzq6Qqe4NDlZoUKnIramwkY3Wt1RXU9PPVI9NvZ/bmJmnoKtQkFpSXBJkYKKQmleTmZearFCzv9/yWk5ienF/3WTCwoA "Haskell – Try It Online") `succ` is such an unfortunate naming choice... ## Explanation ``` [[x,succ x,x]|x<-['A'..'Y']] [ |x<- ] -- for x in... ['A'..'Y'] -- the alphabet sans Z [x,succ x,x] -- construct a string of x, the successor of x and x ``` [Answer] # [R](https://www.r-project.org/), 40 bytes ``` cat(intToUtf8(rbind(x<-65:89,x+1,x,10))) ``` [Try it online!](https://tio.run/##K/r/PzmxRCMzryQkP7QkzUKjKCkzL0WjwkbXzNTKwlKnQttQp0LH0EBTU/P/fwA "R – Try It Online") One more alternative in R to [Plannapus](https://codegolf.stackexchange.com/a/151050/67312) and [Giuseppe's](https://codegolf.stackexchange.com/a/151190/72975) answers. Posted following their request. This solution uses ASCII code to UTF8 coding. PS if TABs were allowed, one could replace the newline (ASCII code 10) with a tabulation (ASCII code 9), and the solution could shrink to 39 bytes: `cat(intToUtf8(rbind(x<-65:89,x+1,x,9)))` [Answer] # [R](https://www.r-project.org/), ~~40~~ 36 bytes ``` cat(paste0(L<-LETTERS,L[-1],L)[-26]) ``` [Try it online!](https://tio.run/##K/r/PzmxRKMgsbgk1UDDx0bXxzUkxDUoWMcnWtcwVsdHM1rXyCxW8/9/AA "R – Try It Online") An alternative to [plannapus' answer](https://codegolf.stackexchange.com/a/151050/67312); this turns out to be a bit golfier; I've posted it per his request. See also [this 40 byte answer](https://codegolf.stackexchange.com/a/151208/67312) by NofP which is quite nice. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~39~~ 37 bytes ``` 65..89|%{-join[char[]]($_,++$_,--$_)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38xUT8/Cska1WjcrPzMvOjkjsSg6NlZDJV5HWxtI6OqqxGvW/v8PAA "PowerShell – Try It Online") Loops from `65` to `89`. Each iteration, we're constructing an integer array of (the current, one more, and the current) of the current digit, using pre-increment and pre-decrement. That's then re-cast as a `char`-array, and `-join`ed together into a single string. Each string is left on the pipeline and an implicit `Write-Output` at program completion gives us a newline between each element for free. --- Alternatively, same byte count ``` 65..89|%{-join[char[]]($_,($_+1),$_)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38xUT8/Cska1WjcrPzMvOjkjsSg6NlZDJV4HiLUNNXVU4jVr//8HAA "PowerShell – Try It Online") [Answer] # Pepe, ~~59~~ 56 bytes -3 bytes thanks to u\_ndefined ``` REeEeEEeEerEeEeeeeeERrEEEEErEEEeeREEreeerEEEEEeeEreeERee ``` [Try it online!](https://soaku.github.io/Pepe/#!bp!aa--i-cFGS2I/) Explanation: ``` # Prepare stacks # prepare stack R [Z] REeEeEEeEe # push Z # prepare stack r [A,B,A] rEeEeeeeeE # push A RrEEEEE # copy and increment A (getting B) rEEEee # duplicate A to end # Start loop REE # create label Z reee # output stack r contents rEEEEEeeE # increment all reeE # end line Ree # loop while r[p] != Z ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 8 bytes ``` PZ_.BMPz ``` [Try it online!](https://tio.run/##K8gs@P8/ICpez8k3oOr///@6eQA "Pip – Try It Online") [Answer] # [vJASS](https://wc3modding.info/pages/vjass-documentation/) (Warcraft 3), ~~203~~ ~~189~~ ~~182~~ ~~177~~ 156 bytes Using `//! import zinc "<code_path>"` command to exclude `//! zinc` and `//! endzinc`. --- ``` library q{integer w,e;string r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",t;function onInit(){for(0<=w<25){e=w+1;t=SubString(r,w,e);BJDebugMsg(t+SubString(r,e,e+1)+t);}}} ``` --- **Readable Version:** ``` library q{ integer Index, Increment; string Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", Letter; function onInit(){ /* * Index from 0 to 24 */ for (0 <= Index < 25){ Increment = Index + 1; // Slice Letter = SubString(Alphabets, Index, Increment); // Output BJDebugMsg(Letter + SubString(Alphabets, Increment, Increment + 1) + Letter); } } } ``` [![Warcraft 3](https://i.stack.imgur.com/h8kFH.jpg)](https://i.stack.imgur.com/h8kFH.jpg) --- **Verification purposes only:** The in-game text screen has limited space. Using `Preload()`, we may able to see the full output. ``` //! zinc library q{ integer Index, Increment; string Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", Letter; function onInit(){ // Create an empty text file (Preload file). PreloadGenClear(); PreloadGenStart(); /* * Index from 0 to 24 */ for (0 <= Index < 25){ Increment = Index + 1; // Slice Letter = SubString(Alphabets, Index, Increment); // Output Preload(Letter + SubString(Alphabets, Increment, Increment + 1) + Letter); } // Save .txt PreloadGenEnd("CodeGolf\\testOutput.txt"); } } //! endzinc ``` [![Preload File as an output](https://i.stack.imgur.com/MCqET.png)](https://i.stack.imgur.com/MCqET.png) [Answer] # [J](http://jsoftware.com/), 18 16 bytes ``` 2(,{.)\u:65+i.26 ``` Changed `a.{~` to `u:` after Conor O'Brien's and FrownyFrog's solutions [Try it online!](https://tio.run/##y/qfZmulYKAAxP@NNHSq9TRjSq3MTLUz9YzM/mtyKekpqKfbWqkr6CjUWimkcaUmZ@QrpP8HAA "J – Try It Online") ]
[Question] [ This is a simple challenge: Given a sequence of integers, find the sum of all integers in it. But with a twist. Your score is the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between your code and the following phrase (The challenge): > > Given a set of integers, find the sum of all integers in it. > > > You may assume there are no newlines or trailing spaces in the input. **Example input/output:** ``` Input: 1 5 -6 2 4 5 Output: 11 Input: 1 -2 10 Output: 9 ``` An online calculator for Levenshtein distance can be found here: <http://planetcalc.com/1721/> [Answer] ## Python, distance 3 ``` #Given a set of integers, find the sum#of all integers in it. ``` This gives the built-in function `sum`, which can sum a set like `sum({3,5,7})==17`. The remaining parts are commented. This has distance 3, with 3 edits: * Add the initial `#` * Add a newline * Replace the space after `sum` with `#` [Answer] # Julia, distance ~~27~~ 26 No comments! ``` Given(a)=(Set;of;integer; find; [sum(a),all,integer,in][1]) ``` This creates a function called `Given` that accepts an array and returns the sum of its elements. Since a lot of Julia builtins have relevant names (but are irrelevant to the calculation here), we can just list a few delimited with semicolons. As long as they aren't the last thing listed, they won't be returned. The last part actually makes an array containing the sum and three functions and selects the first element, the sum. [Answer] # APL, distance ~~6~~ 3 Saved 3 distances...? thanks to Dennis! ``` +/⍝en a set of integers, find the sum of all integers in it. ``` This sums a given array (`+/`). The remainder of the sentence is added to the end using a comment (`⍝`). [Answer] # GolfScript, 5 ``` ~{Given a set of integers+ find the sum of all integers in it}* ``` This a full program that uses no comments (but a lot of noops). Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=OyJbMSAyIDNdIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2Be0dpdmVuIGEgc2V0IG9mIGludGVnZXJzKyBmaW5kIHRoZSBzdW0gb2YgYWxsIGludGVnZXJzIGluIGl0fSo%3D). [Answer] # R, Distance ~~37~~ ~~36~~ 34 Without using comments :) ``` as.integer ( sum (scan(,integer( ) ))) ``` **Note** there is a space at the beginning. [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), Distance 2. ``` Given aset of integers, ;find the sum of all integers in it. ``` In RProgN, a, set, find and sum are all commands. Everything else is per default ignored in syntax. a pushes the alphabet to the stack, which will cause sum to fail. Set never has enough arguments, so always fails, erroring. Find either has the wrong number of arguments, or tries to compare the alphabet with the input stack, which doesn't work. a and set can both be 'fixed' by removing the space between then, aset is not a function, so it's ignored. Find just has an extra character inserted at the start, causing it also to not be recognized, and ignored. Only sum is left, which conveniently sums the contents of the input stack. Finally, RProgN might win something! [Try it Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=Given%20aset%20of%20integers%2C%20%3Bfind%20the%20sum%20of%20all%20integers%20in%20it.&input=%7B1%2C2%2C3%7D) [Answer] ## Mathematica, distance 17 ``` Given a set of integers find the sum of all integers in it*0+Total@Input[] ``` It doesn't use any comments or no-ops, but instead declares all of the words as variables, and then gets rid of them by multiplying by zero. It also has the benefit of being the only answer that actually takes a **set** of integers as its input. The input `{1,2,3}` provides the output `6` as expected. Unfortunately, the Mathematica `Sum` function doesn't do the task in the question, therefore necessitating a larger number of bytes. [Answer] # Java - ~~43~~ 41 I tried. ``` float a_set_of(int[] r){return IntStream.of(r).sum()}//n it. Given a set of integers, find the sum of all integers in it. ``` Java :P. [Answer] # CJam, ~~7~~ ~~6~~ 5 ``` {:+}e# a set of integers, find the sum of all integers in it. ``` This is an anonymous function that pops an array from the stack and leaves an integer in return. *Thanks to [@AboveFire](https://codegolf.stackexchange.com/users/42485/abovefire) for shortening the distance by 1.* [Try it online.](http://cjam.aditsu.net/#code=%7B%3A%2B%7De%23%20a%20set%20of%20integers%2C%20find%20the%20sum%20of%20all%20integers%20in%20it.%0A%0A%5B1%202%203%5D%5C~) [Answer] ## Matlab, distance ~~29~~ 28 ``` Given_a_set_of_integers=@(findthe)sum(all(1)*findthe) ``` Without using any comments :-) The code is in the form of an anonymous function. I'm assuming the input is a vector (1D-array) of numbers. Example: ``` >> Given_a_set_of_integers=@(findthe)sum(all(1)*findthe) Given_a_set_of_integers = @(findthe)sum(all(1)*findthe) >> Given_a_set_of_integers([1 5 -6 2 4 5]) ans = 11 ``` [Answer] ## F#, distance 21 ``` let ``Given a set of integers, find the sum of all integers in it`` x = Seq.sum x ``` Gotta love the ability to use double ticks to give a function a name with spaces in it. Usage: ``` [1;2;3] |> ``Given a set of integers, find the sum of all integers in it`` |> printfn "%i" ``` > > 6 > > > [Answer] # [Cubix](https://github.com/ETHproductions/cubix), Distance 9 ``` @ivOn a ;et I+ i?tegers, fu;d <he sum of all integers in it. ``` [Try it online!](https://tio.run/##Sy5Nyqz4/98hs8w/TyFRwTq1RMFTWyHTviQ1PbWoWEchrdQ6RcEmI1WhuDRXIT9NITEnRyEzDyILZChkluj9/2@oAIG6xgA "Cubix – Try It Online") This wraps onto the cube ``` @ i v O n a ; e t I + i ? t e g e r s , f u ; d < h e s u m o f a l l i n t e g e r s i n i t . . . . . . . ``` The operative code is * `I+i` Input a integer,add to TOS then input a character * `?` Test character value. Redirect left for -1 (end of input) or right for anything else (0 can't be input) + `;O@` pop TOS, output sum and exit + `<;u` redirect, pop TOS and u-turn onto the start [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), distance 1 ``` Given a set of integersṠ, find the sum of all integers in it. ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJHaXZlbiBhIHNldCBvZiBpbnRlZ2Vyc+G5oCwgZmluZCB0aGUgc3VtIG9mIGFsbCBpbnRlZ2VycyBpbiBpdC4iLCIiLCJbNCwgMiwgMV0iLCIzLjQuMSJd) Prints a singleton number. ## Explanation ``` Given a set of integersṠ, find the sum of all integers in it.­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤⁣​‎‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁤⁤​‎‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢⁡⁡​‎⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁡⁢​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁢⁡⁣​‎‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢⁡⁤​‎‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁢⁡​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏⁠‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏⁠‎⁡⁠⁤⁡⁤‏⁠‎⁡⁠⁤⁢⁡‏⁠‎⁡⁠⁤⁢⁢‏⁠‎⁡⁠⁤⁢⁣‏⁠‎⁡⁠⁤⁢⁤‏⁠‎⁡⁠⁤⁣⁡‏⁠‎⁡⁠⁤⁣⁢‏⁠‎⁡⁠⁤⁣⁣‏⁠‎⁡⁠⁤⁣⁤‏⁠‎⁡⁠⁤⁤⁡‏‏​⁡⁠⁡‌­ G ## ‎⁡Get the max element i ## ‎⁢index ve ## ‎⁣Is odd? (decrement, Is even?) n ## ‎⁤Push "abcdefghijklmnopqrstuvwxyz" anyway a ## ‎⁢⁡Is the alphabet truthy? (Always) s ## ‎⁢⁢Split! I don't know how can you split a bool with 1... e ## ‎⁢⁣Is this even? t ## ‎⁢⁤Get the last element (How can you do it with a bool?) o ## ‎⁣⁡Overlap (How??) f ## ‎⁣⁢Flatten (Already Flattened??) i ## ‎⁣⁣Index with input again n ## ‎⁣⁤Also, push "abcdefghijklmnopqrstuvwxyz" anyway t ## ‎⁤⁡Get the last element ("z") e ## ‎⁤⁢Split on newlines ("z" has no newlines, so pop and push ["z"]) g ## ‎⁤⁣Never gonna <g>ive you up. (I don't understand what this does anyway) e ## ‎⁤⁤Split on newlines (Again? This time, it doesn't wrap) r ## ‎⁢⁡⁡replace this with input? s ## ‎⁢⁡⁢split with itself? Ṡ ## ‎⁢⁡⁣SUM! , ## ‎⁢⁡⁤PRINT! find the sum of all integers in it. ## ‎⁢⁢⁡I give up. This doesn't do anything. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [O](http://o.readthedocs.org/), 5 ``` M]+o"Given a set of integers, find the sum of all integers in it. ``` Numbers must be in hexadecimal and in reverse negative notation: * -6 => 6\_ * -4 => 4\_ * -10 => A\_ [Try it online](http://o-lang.herokuapp.com/link/code=M%5D%2Bo%22Given+a+set+of+integers%2C+find+the+sum+of+all+integers+in+it.&input=1+5+6_+2+4+5) [Answer] # K, ~~60~~ 5 ``` +/ / Given a set of integers, find the sum of all integers in it. ``` ~~I'm guessing symbols do NOT go nicely with the Leve-whatever distance...~~ Hahaha. Originally, I had *no* what the LeveXXX distance was, so I got 60. Then, thanks to helpful comments, it dropped to 5. [Answer] # Pip, distance 3 Joining the club of trivial no-comments-but-lots-of-no-ops golflang answers... ``` Given a set of integers, find the sum of all integers in $+g ``` [GitHub repository for Pip](http://github.com/dloscutoff/pip) The code practically documents itself; maybe `s/in/using/` for a more accurate description. Integers given as command-line arguments are read into the list `g`, which is here folded on addition and the result auto-printed. Most everything else is just variables, which are no-ops. I was a bit surprised at first that `s, f` worked without complaining, since `f` refers to the main function and taking the range of a code block doesn't make sense. But then I realized: the `,` range operator, when given a function argument, just constructs another function (as do many operators in Pip). So I think `s, f` evaluates to `{Given a set of integers, find the sum of all integers in " ",$+g}`. (Which is then discarded anyway.) One final point: this code works with the current version of Pip, in which I haven't assigned `G` to anything yet. If in some future version I make `G` a binary or ternary operator, then a distance-4 version would be necessary. Using `given` instead of `Given` would work nicely. [Answer] # Haskell, distance 11 No comments! ``` const sum"Given a set of integers, find the sum of all integers in it." ``` Usage: ``` > const sum"Given a set of integers, find the sum of all integers in it." $ [1..10] 55 ``` [Answer] # Pyth - 4 Just puts the actual code, `sQ` in front of the string no-oped by a space. ``` sQ "Given a set of integers, find the sum of all integers in it. ``` [Try it online here](http://pyth.herokuapp.com/?code=sQ%20%22Given%20a%20set%20of%20integers%2C%20find%20the%20sum%20of%20all%20integers%20in%20it.&input=1%2C%205%2C%20-6%2C%202%2C%204%2C%205&debug=0). [Answer] # PHP4.1, distance 25 This one is a pretty long one and really late in the run. But anyway, here it is: ``` <?=$n_a_set_of_integers_fi=array_sum($f_all_integers_in_i); ``` For this to work, you just need to pass it an array over POST/GET/COOKIE/session, using the key `f_all_integers_in_i`. [Answer] # [Pyt](https://github.com/mudkip201/pyt), distance 1 ``` Given a set of integers, find the Ʃum of all integers in it. ``` All alphanumeric characters are no-ops in Pyt, and the sum of a list only takes one character: Ʃ [Try it online!](https://tio.run/##K6gs@f/fPbMsNU8hUaE4tUQhP00hM68kNT21qFhHIS0zL0WhJCNV4djK0lyQVGJODlwayFDILNH7/z/aUMdIx1jHJBYA "Pyt – Try It Online") [Answer] # C++17, distance ~~44~~ 29 Variadic Generic Lambda FTW ``` [](auto...t){return(t+...);}//the sum of all integers in it. ``` Previous solution ``` template<class...t>int s(t...l){return(...+l);}//gers in it. ``` [Answer] # 05AB1E, distance 3 ``` #O,Given a set of integers, find the sum of all integers in it. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=I08sR2l2ZW4gYSBzZXQgb2YgaW50ZWdlcnMsIGZpbmQgdGhlIHN1bSBvZiBhbGwgaW50ZWdlcnMgaW4gaXQu&input=MSAyIDMgNA) [Answer] # [Pyke](https://github.com/muddyfish/PYKE), Score 3 ``` sK"Given a set of integers, find the sum of all integers in it. ``` [Try it here!](http://pyke.catbus.co.uk/?code=sK%22Given+a+set+of+integers%2C+find+the+sum+of+all+integers+in+it.&input=%5B1%2C2%2C3%5D&warnings=0&hex=0) [Answer] # [Ly](https://github.com/LyricLy/Ly), score 4 ``` &+#Given a set of integers, find the sum of all integers in it. ``` Note the trailing newline. [Try it online!](https://tio.run/##y6n8/19NW9k9syw1TyFRoTi1RCE/TSEzryQ1PbWoWEchLTMvRaEkI1WhuDQXJJOYkwOXBTIUMkv0uP7/N@Ey4zLi0jXl0jUEAA "Ly – Try It Online") The code is pretty self-explanatory. `&+` is Ly's summing operator, while `#` is a comment. It's unfortunate that I have to include a trailing newline due to the fact that ending a program with a comment line will "comment out" Ly's implicit output, which is actually a bug in the interpreter that I'm calling a feature. [Answer] # dc, 14 ``` ?[+z1 <f]d sf xp#egers, find the sum of all integers in it. ``` comments: ``` ? # read numbers [ # start macro + # add up last two things on stack z1 <f # if stack size is more than 1, execute macro at register 'f' ] # end macro d # dupe it sf # saving one copy to register 'f' x # and executing another p # printing result ``` [TIO](https://tio.run/##S0n@/9/eIFq7SsFQwSY1ViGlOLWiQDk1PbWoWEchLTMvRaEkI1WhuDRXIT9NITEnRyEzrwQsC2QoZJbo/f9vqWChYK5gpmCqYKJgrGCkYAgA) it complains about the stack being empty if you enter 1 number, but still works, and removal of 0 saves 2 diff. [Answer] # Excel VBA, Distance: 11 Anonymous VBE immediate window function that takes input from the range `[a:a]` on the ActiveSheet object and outputs to the VBE immediate window ``` ?[Sum(a:a)] 'f integers, find the sum of all integers in it. ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 20 ``` (([]){[{}]{}([])}{})ers, find the sum of all integers in it. ``` [Try it online!](https://tio.run/##FclBCoAgEAXQq/ylQnUhcWGkNWgGaqthzj7Z7sHbW6C6phKyqjHOW3YsnuWnsNjY@oJE9cC4Ivp740kIpYDqiOfcCdDYVD8 "Brain-Flak – Try It Online") # Explanation Since there are no parentheses in the original text this boils down to a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") problem in Brain-Flak. But that still doesn't make this answer trivial, as answers in Brain-Flak rarely are. One's first intuition would probably be the following code ``` ({{}}) ``` Which works ... *unless* there is a zero on the stack in which case it just sums until the zero. To get around this problem we have to use a stack height to check that the stack is not empty. This can be set up like this ``` ([]) #{ Push stack height } ( #{ Start Push } { #{ Loop until zero } <{}> #{ Silently Pop the last height } {} #{ Grab a value from the stack } <([])> #{ Silently push the stack height again } } #{ End loop } {} #{ Remove last stack height } ) #{ Push the result } ``` This one works, but there is something wrong with it. We keep silencing the pops and the pushes in the loops but they are almost equal so there should be a way to cancel them out. If we try ``` ([])({[{}]{}([])}{}) ``` We end up off by `n` each time. So here's the trick, we already have an `n` siting around, we just move it into the push to balance things out. ``` (([]){[{}]{}([])}{}) ``` [Answer] # [Ahead](https://github.com/ajc2/ahead), 17 ``` >jLIve> K+O @f integers, find the sum of all integers in it. ^ >j<l ``` [Try it online!](https://tio.run/##S8xITUz5/98uy8ezLNVOQUHBW9tfwSFNITOvJDU9tahYRyEtMy9FoSQjVaG4NFchP00hMScHLgtkKGSW6HHFKdhl2eT8/2@oYKRgDAA "Ahead – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), Distance: 2 ``` Given a set of integers, find the sum of all integers in it. S ``` [Try it online!](https://tio.run/##y0rNyan8/989syw1TyFRoTi1RCE/TSEzryQ1PbWoWEchLTMvRaEkI1WhuDQXJJOYkwOXBTIUMkv0uIL///8fbWigY2gQCwA "Jelly – Try It Online") Jelly only evaluates the main link (the last line) and explicit commands will run other links (other lines). The last line has `S`, which sums the input. The first line does not get executed because there is no reference to it in the main link. [Answer] # Snap! 4.2.2.9 (+ Tools), scratchblocks3 syntax, distance 35 This is a function. `integers, find the sum of all inte` is the input. ``` for each(et)of(integers, find the sum of all inte change[s v]by(et end report(s ``` ]
[Question] [ > > **Notice:** [Following popular demand](https://codegolf.stackexchange.com/questions/41462/a-different-kind-of-meta-regex-golf#comment97227_41462) I have slightly relaxed the rules: > > > * The maximum regex size grows by 1 byte **every 5 answers**. Answer **N** may use up to **29 + ⌈N/5⌉** bytes. > * The score of each answer will be **(M/(30+N/5))N** > > > In regex golf, you're given two sets of strings, and are asked to create the shortest regex which matches all strings in the first set, but fails on all strings in the second set. That is what we're going to do, but each time someone answers, their regex itself will be added to one of the two sets of strings (of their own choice). **Therefore, there is a strict order to answers in this challenge.** Let's go through an example: * Say I start this with `abc` (which I won't), and put it in the *match* set. * Then a valid second answer would be `a`, as it matches the above (and there are no strings that need to fail yet). Say this answer goes in the *fail* set. * Now the third answer has to match `abc` but fail on `a`. A possible third answer is therefore `b`. Let's put this in the *match* set. * The fourth answer now has to match `abc` and `b`, but fail on `a`. We'll disallow duplicate answers, so a valid regex would be `c|b`. What's important is that your answer should be as short as possible. This may be trivial for the first few answers, but once we get a few answers, it should get harder and harder to get the desired match in as few characters as possible. For the actual challenge, initially the match set contains `PPCG` and the fail set contains `[PPCG]`, and I have already provided the first answer. ## Answering The key thing to understand about this challenge is that **only one person can answer at a time and each answer depends on the one before it**. There should never be two answers with the same `N`. If two people happen to simultaneously answer for some `N`, the one who answered later (even if it's a few seconds difference) should graciously delete their answer. To make this run a bit smoother, try to stick to the following steps when posting your answer: * Make sure that someone has independently verified the correctness of the previous answer (and left a corresponding comment). * Take the two test sets found in the previous answer, and write a regex which matches all strings in one set and none in the other. * Post your answer in the following format: ``` # N. [regex flavour] - [regex size in bytes] [regex] [link to online regex tester] [notes, explanation, observations, whatever] ### The next answer has to match the following strings: [match set] ### And fail on these strings: [fail set] ``` where `N` is the number of your answer. Please copy `[match set]` and `[fail set]` from the previous answer, and append your regex to *one* of them. **This is absolutely vital to the challenge!** I've provided a dashboard tool for the challenge to help with the bookkeeping, and it relies on the above template. (See bottom of the post.) * Another user should now review your submission and leave a comment "Correctness verified" if your answer follows all the rules (see below). If it doesn't, they should leave a comment pointing out any flaws. You've then got *15 minutes* to fix those issues. If you don't, your answer will be deemed invalid, should be deleted, and someone else may post a follow-up answer to the previous one. (If this happens, you're free to submit a new answer any time.) These regulations may seem rather strict, but they are necessary to avoid invalid answers somewhere up the chain. ## Rules * **A user may only submit one answer per 4 hour period.** (This is to prevent users from constantly watching the question and answering as much as possible.) * A user may not submit two answers in a row. (e.g. since I submitted answer 1 I can't do answer 2, but I could do 3.) * **Do not edit answers that have been verified.** (Even if you find a way to shorten it!) * Should a mistake be discovered *earlier* in the chain (i.e. after follow-up answers have been posted), the offending answer should be deleted and will be removed from the set of strings that new submissions should fail on. *However*, all answers that have been posted since should *not* be changed to reflect. * Clearly state one flavour your regex is valid in. You may choose any flavour that is freely testable online. There's a good list of online testers [over on StackOverflow](https://stackoverflow.com/tags/regex/info). In particular, [**Regex101**](http://regex101.com/) and [**RegexPlanet**](http://www.regexplanet.com/) should be useful, as they support a wide variety of flavours. Please include a link to the tester you chose in your answer. By switching on the `g`lobal and `m`ultiline modifiers in the tester, you can test all strings at once, one on each line (these modifiers are not counted towards your regex size, because they aren't needed on any individual string). * Your regex must not be empty. * Your regex for answer **N** must not be longer than **29 + ⌈N/5⌉** bytes. I.e. answers 1 to 5 may use up to 30 bytes (inclusive), answers 6 to 10 may use up to 31 bytes... answers 31 to 35 may use up to 36 bytes. Check the dashboard to see how many characters the next answer may use. * Your regex must not be identical to any string in either test set. * Do not include delimiters in your submission or byte count, even if the relevant host language uses them. If your regex uses modifiers, add one byte per modifier to the regex size. E.g. `/foo/i` would be 4 bytes. ## Scoring Each answer's score is calculated as **(M/(30+N/5))N**, where **M** is the size of the regex in bytes, and **N** is it's number. Each user's score is the product of all their answers. The user with the lowest overall score wins. In the unlikely event of a tie, the user with the *latest* submission wins. I will accept that user's latest answer. If you prefer summing scores, you can calculate each answer's score as **N \* (log(M) - log(30))** and sum those up over all answers. That will give the same leaderboard order. There is no need to include an answer's score in the answer, just report **M**. The challenge dashboard at the bottom of the question will compute the scores, and in the event of two very close scores, I'll double check the results using arbitrary-precision types. Note that the score of each answer is less than 1, so you can improve your overall score by providing a new answer. However, the shorter each of your submissions, the more efficiently you can lower your score. Furthermore, later answers can achieve a lower score although being longer, due to the increasing exponent. ## Dashboard I've written a little Dashboard tool, using Stack Snippets, based on [Optimizer's work over here](http://meta.codegolf.stackexchange.com/a/2492/8478). I hope this will help us get some order into these answer-dependent challenges. This will display the current status of the challenge - in particular, if there are conflicting answers, if an answer needs to be verified, or if the next answer can be posted. It also produces a list of all answers with scores, as well as a leaderboard of all users. Please stick to the challenge format above, so the dashboard can read out the relevant strings from your answers. Otherwise you might not be included in the leaderboard. Please let me know ([ideally in chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte)) if you spot any bugs or have some ideas how the usefulness of the tool could be improved. ``` function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentsUrl(e,t){return"http://api.stackexchange.com/2.2/answers/"+e+"/comments?page="+t+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else{page=1;getFinalComments()}}})}function getFinalComments(){answers=answers.filter(shouldHaveHeading);answers=answers.filter(shouldHaveScore);$.ajax({url:commentsUrl(answers[0].answer_id,page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){comments.push.apply(comments,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;try{t|=/^(#|&lt;h).*/.test(e.body_markdown);t|=["-","="].indexOf(e.body_markdown.split("\n")[1][0])>-1}catch(n){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function findDuplicates(e){var t=false;var n={};e.forEach(function(e){var r=e.body_markdown.split("\n")[0].match(NUMBER_REG)[0];if(n[r])t=t||r;n[r]=true});return t}function hasBeenVerified(e,t){var n=false;t.forEach(function(t){n|=/correctness verified/i.test(t.body_markdown)&&e!=t.owner.user_id});return n}function userTimedOut(e){return NOW-e.creation_date*1e3<MSEC_PER_ANSWER}function getAuthorName(e){return e.owner.display_name}function getAnswerScore(e,t){e=parseInt(e);t=parseInt(t);return Math.pow(t/(30+e/5),e)}function process(){$("#last-user").append(answers[0].owner.display_name);var e=answers.slice(1).filter(userTimedOut).map(getAuthorName).join(", ");if(e)$("#timed-out-users").append(e);else $("#timed-out-notice").hide();var t=answers[0].body_markdown.split("\n")[0].match(NUMBER_REG)[0];var n=findDuplicates(answers);if(n){var r=$("#status-conflict-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",n));$("#challenge-status").addClass("conflict")}else if(!hasBeenVerified(answers[0].owner.user_id,comments)){var r=$("#status-verification-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",t));$("#challenge-status").addClass("verification")}else{var r=$("#status-next-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",t).replace("{{NEXT}}",parseInt(t)+1).replace("{{SIZE}}",29+Math.ceil((parseInt(t)+1)/5)));$("#challenge-status").addClass("next")}var i={};var s={};answers.forEach(function(e){var t=e.body_markdown.split("\n")[0];var n=$("#answer-template").html();var r=t.match(NUMBER_REG)[0];var o=(t.match(SIZE_REG)||[0])[0];var u=getAnswerScore(r,o);var a=getAuthorName(e);n=n.replace("{{NAME}}",a).replace("{{NUMBER}}",r).replace("{{SIZE}}",o).replace("{{SCORE}}",u.toExponential(5)).replace("{{LINK}}",e.share_link);n=$(n);$("#answers").append(n);i[a]=(i[a]||1)*u;s[a]=(s[a]||0)+1});var o=[];for(var u in i)if(i.hasOwnProperty(u)){o.push({name:u,numAnswers:s[u],score:i[u]})}o.sort(function(e,t){return e.score-t.score});var a=1;o.forEach(function(e){var t=$("#user-template").html();t=t.replace("{{NAME}}",e.name).replace("{{NUMBER}}",a++).replace("{{COUNT}}",e.numAnswers).replace("{{SCORE}}",e.score.toExponential(5));t=$(t);$("#users").append(t)})}var QUESTION_ID=41462;var ANSWER_FILTER="!*cCFgu5yS6BFQP8Z)xIZ.qGoikO4jB.Ahv_g-";var COMMENT_FILTER="!)Q2B_A497Z2O1kEH(Of5MUPK";var HOURS_PER_ANSWER=4;var MSEC_PER_ANSWER=HOURS_PER_ANSWER*60*60*1e3;var NOW=Date.now();var answers=[],comments=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/ ``` ``` body{text-align:left!important}#challenge-status{font-weight:700;padding:10px;width:620px}#blocked-users{padding:10px;width:620px}.conflict{background:#994343;color:#fff}.verification{background:#FFDB12}.next{background:#75FF6E}#last-user,#timed-out-users{font-weight:700}#answer-list{padding:10px;width:300px;float:left}#leaderboard{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="challenge-status"> </div><div id="blocked-users"> User <span id="last-user"></span> has posted the last answer, and may not post the next one. <div id="timed-out-notice"><span id="timed-out-users"></span> have answered within the last four hours and may not answer again yet. (If a user appears in this list twice, they must have answered twice within four hours!)</div></div><div id="answer-list"> <h2>List of Answers (newest first)</h2> <table class="answer-list"> <thead> <tr><td>No.</td><td>Author</td><td>Size</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="leaderboard"> <h2>Leaderboard</h2> <table class="leaderboard"> <thead> <tr><td>No.</td><td>User</td><td>Answers</td><td>Score</td></tr></thead> <tbody id="users"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{NUMBER}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>{{SCORE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="user-template"> <tr><td>{{NUMBER}}</td><td>{{NAME}}</td><td>{{COUNT}}</td><td>{{SCORE}}</td></tr></tbody> </table> <div id="status-conflict-template" style="display: none"> There is more than one answer with number {{NUMBER}}!<br>Please resolve this conflict before posting any further answer. </div><div id="status-verification-template" style="display: none"> Answer {{NUMBER}} has not been verified!<br>Please review the answer and post a comment reading "Correctness verified." on the answer if it is valid. Note that this has to be done by a different user than the author of the answer! </div><div id="status-next-template" style="display: none"> Answer {{NUMBER}} has been verified!<br>You may now post answer {{NEXT}}, using up to {{SIZE}} bytes. </div> ``` [Answer] # 28. Python flavour - 29 ``` \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ``` [Tested on Regex101](http://regex101.com/r/gI9fY7/1) Lots of fiddling around was done - #4 in the pass set's probably the biggest pain, as it's a substring of a regex in the fail set, and also shares a suffix with another regex in the fail set. ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ ``` [Answer] # 24 - Python flavour - 29 ``` ^(..[^^].{4,22}\$|[^?]+\w)$|2 ``` [Tested here](http://regex101.com/r/mX5pB5/1) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ``` [Answer] # 10. Python flavor - 19 ``` ^[\w^]*$|!|]P|G]\$$ ``` Tested on [Regex101](http://regex101.com/#python). ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)*[^\\|]*[^\]]$ ``` [Answer] # 8. ECMAScript flavour - 14 bytes ``` [^?][PG]$|<|PG ``` [Demo](http://regex101.com/r/tJ6hO7/2) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ``` [Answer] # 2. ECMAScript flavour - 6 bytes ``` ^[P\^] ``` [Test it here](http://regex101.com/#javascript) ### The next answer has to match the following strings: ``` PPCG ^P ``` ### And fail on these strings: ``` [PPCG] ^[P\^] ``` [Answer] # 9. Python flavour - 28 ``` ^[^\\|]*(\\\\)*[^\\|]*[^\]]$ ``` Tested on [Regex101](http://regex101.com/#python) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)*[^\\|]*[^\]]$ ``` [Answer] # 23. PCRE flavour - 28 ``` ([^\\}<]{3}|][^]]|^).?[$PG]$ ``` [Tested on Regex101.](http://regex101.com/r/mW1aK2/1) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ``` [Answer] # 11. Python - 29 ``` ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ``` [► Test at RegexPlanet](http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDwsSBlJlY2lwZRj7tocPDA/index.html) Almost all invalid answers have a different length than all the valid ones. This regex makes use of that. ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ``` [Answer] # 29. PCRE flavour - 28 ``` ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` [Tested on Regex101](http://regex101.com/r/sF5cS9/3) This answer still works... ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ ``` [Answer] ## 31. Perl flavour - 29 `[?[CP(].[-<)|w]|^P|^[^C|\\]*$` I don't know how it works, it was produced by my [the first foray into genetic algoritms](https://gist.github.com/vi/ed0f1f6bf8b6ed9f5ff1). There is [program output](https://gist.githubusercontent.com/vi/990a32775778f4358f2e/raw/caf7709a5fe20a97f6f1515b3fdeb5bc6507733b/genregex.log) that mentions the answer. The next answer has to match: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` and to fail: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ``` [Answer] ## 32. [PCRE](http://www.pcre.org/) — 30 bytes ``` ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ``` Tested on [Regex101](http://regex101.com/r/kR1aH4/1) **The next answer has to match the following strings**: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` **And fail on these strings**: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ``` [Answer] # 42. Python flavour - 38 ``` \?[^w$]*\$$|^P|\w.\)|w.?\+|w\^|[^?P]P$ ``` [Tested on Regex101](http://regex101.com/r/iU4nR2/1) The lack of entropy in the last few answers was getting to me... (should have done this sooner) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) \?[^w$]*\$$|[]^C]\w+$|w\^|\|..\) \w.\)|\?[^-$]*\$$|[]^C]\w$|w[+^] []^C]\w$|\w.\)|-\$|w[+^]|\?[^w$]*\$$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ^...[3w!G)]|^[^\\C|]*$|G.?.?\) ^[^C\\|]+$|G.\)|\.\)|w\^|^P|\...?] ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) \?[^$w]*\$$|[]C^]\w$|w.]|\w.\) \$..\\|\?[^w$]*\$$|w\^|[]^C]\w$ []^C]\w$|\w.\)|w[[+^]|\?[^w$]*\$$ \?[^w$]*\$$|^P|\w.\)|w.?\+|w\^|[^?P]P$ ``` [Answer] # 1. ECMAScript flavour - 2 bytes ``` ^P ``` [Test it on Regex101.](http://regex101.com/#javascript) The initial matching set is `PPCG` and the failing set `[PPCG]`. Therefore, this regex simply tests that the string *starts* with `P`. ### The next answer has to match the following strings: ``` PPCG ^P ``` ### And fail on these strings: ``` [PPCG] ``` [Answer] # 3. ECMAScript flavour - 6 bytes ``` [^\]]$ ``` [Test it here](http://regex101.com/#javascript) ### The next answer has to match the following strings: ``` PPCG ^P ``` ### And fail on the these strings: ``` [PPCG] ^[P\^] [^\]]$ ``` [Answer] # 7. Python flavour - 16 ``` (?<!\\..)(?!]).$ ``` Tested on [Regex101](http://regex101.com/#python) Gotta add a \ to the match list :) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P ``` [Answer] # 12. ECMAScript flavor - 17 ``` !|[^?]P(CG|G..)?$ ``` [Test it here](http://regex101.com/r/qK0tV0/3). ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ``` [Answer] # 22. PCRE Flavor – 29 bytes Since the original #22 is not modified for 1 hour I assume it has become invalid. ``` ^.{3,23}[.-~]..\$$|[^P?][PG]$ ``` [Demo](http://regex101.com/r/dB0tL9/1) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ``` [Answer] # 26. Python flavor - 28 ``` ^..(.[!G)(3w^]|.{7}$|$)|\$\? ``` [Test on Regex101](http://regex101.com/r/nV3vL2/1) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ``` [Answer] # 30. Python flavour - 28 ``` [[?C(].[-!)|w]|^P|^[^C|\\]*$ ``` [Tested on Regex101](http://regex101.com/r/kL5oQ8/1) When there's a will... ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ ``` [Answer] # 37. Perl flavour - 30 ``` \?[^$w]*\$$|[]C^]\w$|w.]|\w.\) ``` [Submission on Regex101](http://regex101.com/r/vK2sR8/3). The solution was produced by the the same program as before. The program has also printed 29-character solution `\?[^$w]*\$|[]^C]\w)$|w.]|\w.\`, I don't know why, as it looks like a malformed regex... ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) \?[^w$]*\$$|[]^C]\w+$|w\^|\|..\) ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ^...[3w!G)]|^[^\\C|]*$|G.?.?\) ^[^C\\|]+$|G.\)|\.\)|w\^|^P|\...?] ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) \?[^$w]*\$$|[]C^]\w$|w.]|\w.\) ``` [Answer] ## 40. [PCRE](http://www.pcre.org/) — 33 bytes ``` []^C]\w$|\w.\)|w[[+^]|\?[^w$]*\$$ ``` Tested on [Regex101](http://regex101.com/r/cG1pE6/2) **The next answer has to match the following strings**: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) \?[^w$]*\$$|[]^C]\w+$|w\^|\|..\) \w.\)|\?[^-$]*\$$|[]^C]\w$|w[+^] ``` **And fail on these strings**: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ^...[3w!G)]|^[^\\C|]*$|G.?.?\) ^[^C\\|]+$|G.\)|\.\)|w\^|^P|\...?] ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) \?[^$w]*\$$|[]C^]\w$|w.]|\w.\) \$..\\|\?[^w$]*\$$|w\^|[]^C]\w$ []^C]\w$|\w.\)|w[[+^]|\?[^w$]*\$$ ``` [Answer] # 4. ECMAScript flavour - 5 bytes ``` ^\^?P ``` [Test it here](http://regex101.com/#javascript). ### The next answer has to match the following strings: ``` PPCG ^P ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P ``` [Answer] # 5. ECMAScript flavour - 6 bytes ``` ^[P^]P ``` Tested on [Regex101](http://regex101.com/#javascript). Time to spice things up a bit with the success set. ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P ``` [Answer] # 6. ECMAScript flavour - 9 bytes ``` [^?][PG]$ ``` Tested on [Regex101](http://regex101.com/#javascript). ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P ``` [Answer] # 14. PCRE flavour - 25 ``` ([.$?]|G\])\$$|^\^?P|\]P$ ``` Tested on [Regex101](http://regex101.com/r/jQ3uI6/2) This is starting to get quite hard. ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ``` [Answer] # 15. PCRE flavour - 26 ``` ([P.$?]\$|[]^]P|G\]\$|CG)$ ``` Tested on [Regex101](http://regex101.com/r/iM2lP2/1) ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ``` [Answer] # 16. PCRE flavor - 21 ``` ^[^?]*[PG]$|[?$].*\$$ ``` Tested on [Regex 101](http://regex101.com/r/tZ8zA4/3). ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ ``` ## And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ``` [Answer] # 25. PCRE flavour - 29 ``` ^(..[^^].{4,22}\$|[^?]+\w)$|~ ``` [Tested here.](http://regex101.com/r/iV2yW2/1) (The test regex contains an additional `\n` to make sure that no match spans multiple lines. This is not necessary to match each individual string.) That was a low-hanging fruit! :) I have to congratulate plannapus though, this regex is amazingly elegant for the current test sets. If you want to upvote this answer, make sure to upvote the previous one, too! ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ``` [Answer] ## 35. [PCRE](http://www.pcre.org/) — 35 bytes ``` ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) ``` Tested on [Regex101](http://regex101.com/r/pH6mF9/1) **The next answer has to match the following strings**: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) ``` **And fail on these strings**: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ^...[3w!G)]|^[^\\C|]*$|G.?.?\) ^[^C\\|]+$|G.\)|\.\)|w\^|^P|\...?] ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) ``` [Answer] # 36. Python flavour - 32 ``` \?[^w$]*\$$|[]^C]\w+$|w\^|\|..\) ``` [Tested on Regex101](http://regex101.com/r/jL0jC8/1) I had three 32-byte regexes ready, and luckily one of them still works :D ### The next answer has to match the following strings: ``` PPCG ^P ^[P^]P [^?][PG]$ (?<!\\..)(?!]).$ ^[\w^]*$|!|]P|G]\$$ !|[^?]P(CG|G..)?$ [^])]\$|^\^?P|P.\].$ ([.$?]|G\])\$$|^\^?P|\]P$ ([P.$?]\$|[]^]P|G\]\$|CG)$ !|((G.|P|\.)\$|[^?]P|CG)$ ^[(!P]|G..$|]..\||[^?]P$ ^.{3,23}[.-~]..\$$|[^P?][PG]$ ^..(.[!G)(3w^]|.{7}$|$)|\$\? \.\)|P[.$?]|w\^|^[^|C\\]*$|^P ^..(.[!)3G^w]|$)|\^.{7}$|G\) \?[^w$]*\$$|[]^C]\w+$|w\^|\|..\) ``` ### And fail on these strings: ``` [PPCG] ^[P\^] [^\]]$ ^\^?P [^?][PG]$|<|PG ^[^\\|]*(\\\\)+[^\\|]*[^\]]$ ^(.{,4}|.{9}|.{16,19}|.{5}P)$ ^[^?]*[PG]$|[?$].*\$$ ^[^[]P|]P|(G]|[.])\$$ \..$|!|\|G|^[\^P]P|P\^|G.\$$ ...\^.P|^!|G]\$$|w|<!|^\^?P ([^\\}<]{3}|][^]]|^).?[$PG]$ ^(..[^^].{4,22}\$|[^?]+\w)$|2 ^(..[^^].{4,22}\$|[^?]+\w)$|~ ^..(.[!()3G^w]|.{7}$|$)|G\\ [[?C(].[-!)|w]|^P|^[^C|\\]*$ [?[CP(].[-<)|w]|^P|^[^C|\\]*$ ^..(.{7}$|.[3Gw!^)]|$)|G.?.?\) ^...[3w!G)]|^[^\\C|]*$|G.?.?\) ^[^C\\|]+$|G.\)|\.\)|w\^|^P|\...?] ^P|!.3|w\^|^[^C\\|]+$|\.[)$-](?!.!) ``` ]
[Question] [ Title ~~stolen~~ inspired by [Greg Hewgill's answer](//stackoverflow.com/a/245068) to [What's the difference between JavaScript and Java?](//stackoverflow.com/q/245062) # Introduction Java and JavaScript are commonly used languages among programmers, and are currently the [most popular](//stackoverflow.com/tags) tags on Stack Overflow. Yet aside from similar names, the two have almost nothing in common. In honor of one of programming's most infamous debates, and [inspired by my recent frustrations in tag searching](//meta.stackexchange.com/q/297703), I propose the following: # Challenge Write a program which takes in a string as input. Return `car` if the string begins with "Java" and *does not* include "JavaScript". Otherwise, return `carpet`. # Example Input and Output ### car: ``` java javafx javabeans java-stream java-script java-8 java.util.scanner java-avascript JAVA-SCRIPTING javacarpet ``` ### carpet: ``` javascript javascript-events facebook-javascript-sdk javajavascript jquery python rx-java java-api-for-javascript not-java JAVASCRIPTING ``` # Notes * Input matching should be case insensitive * Only possibilities for output should be `car` or `carpet` * Imaginary bonus points if your answer uses Java, JavaScript, or Regex * Alternate Title: *Java is to JavaScript as ham is to hamster* [Answer] # Java/JavaScript Polyglot, ~~108~~ ~~107~~ 106 bytes ``` //\u000As->s.matches("(?i)(?!.*javascript)java.*"/* a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet" ``` ## Run as Java ``` //\u000As->s.matches("(?i)(?!.*javascript)java.*"/* a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet" ``` [Try it online!](https://tio.run/##bVJda8IwFH33V2QFoS0mFfYydCoy2HCwMebYyz4g1lSjbZLl3ooy/O2uX6jtfGhvzsm5J/fmZsU3nGoj1Gq@Pph0FsuQhDEHIE9cKvLbIqRiATlmYaPlnCTZnjtFK9Xi44twuwCvkBKyyvxYijJmUapClFqx@2pxWyZ0yjAkERkcguAz7Xa7Y6BDYAnHcCnAddyR9NzRFfNzNwitNOgVxr4T@C0@GAbN3e98HUiGAtDlge8H3sgJuXV6@d8IdA79or5j0bkSyKAqmxAnd3A65yja1vFMcAV1igJawZMmWRTVIG/quLwkCLlSwjakx75O/OP4fUynd6@Tl7fJ80Ndf@m4kqNiIxSe1RzxUMy0XtMzDczX9dyLnj@psLsTNjtcanXCdkv/XyDlRtJIW3rJUWlspOQ9Nlvc91tFzFyqB1dMrlfOzzuOb7oDFAnTKTKTqTBynfZ1F3qkDe2szELeIRHjxsQ7N0eeV76IfSv/9oc/ "Java (OpenJDK 8) – Try It Online") Note: don't trust the highlight as it's incorrect. The real Java, properly interpreted looks like below because `\u000A` is interpreted in the very first step of the compilation as `\n`, de facto ending the comment that started with the line comment (`//`). ``` // s->s.matches("(?i)(?!.*javascript)java.*"/* a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet" ``` ## Run as JavaScript ``` //\u000As->s.matches("(?i)(?!.*javascript)java.*"/* a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet" ``` Credits to @CowsQuak for the JS version. ``` let f= //\u000As->s.matches("(?i)(?!.*javascript)java.*"/* a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet" var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","javascript","java-avascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"]; for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s)); ``` How many imaginary bonus points for this answer? -1 byte thanks to [@Nevay](https://codegolf.stackexchange.com/questions/132272/java-is-to-javascript-as-car-is-to-carpet?noredirect=1#comment324764_132279) in the Java answer. [Answer] # JavaScript, ~~50~~ 49 bytes *Saved 1 byte thanks to @ValueInk by rearranging the regex* ``` a=>/javascript|^(?!java)/i.test(a)?"car":"carpet" ``` ### Test snippet ``` let f= a=>/javascript|^(?!java)/i.test(a)?"carpet":"car" var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","java-avascript","javascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"]; for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s)); ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~92~~ ~~82~~ ~~72~~ ~~58~~ 57 bytes ``` s->s.matches("(?i)(?!.*javascript)java.*")?"car":"carpet" ``` [Try it online!](https://tio.run/##bVJNawIxEL37K9KAsCsmFHopWhUptFhoKbX0UnqIMavR3STNzEql@Nu3@4W6Ww@byXv75mUmk43YCWadMpvlNnPpItaSyFgAkGehDfntEFKzgALzsLN6SZL8XzBHr83q84sIv4KwlBKyyf14ijrmUWokamv4Q725qxL6VRiTiIwyYGPgiUC5VhDQYKLDYHLFe4ULSK8dhqVhj4YTKoWng2J1Cmk2LI871oAKEMioroIQWuTR/jmKfpp4oYSBJsUAvRJJmywraZG3TVz1DFIYo3xLemzmxD9NP6Zsfv82e32fvTw29ZeOqzimdsrgWc2RkGph7ZadaWC5beZe9PxOld@fsNvj2poT9j/s/wUy4TSLrGeXHI3FVkrRY7vFw7BTxtylfj/l5AbV/MLj@OZ7QJVwmyJ3uQqjgHZvrmFAutDNyyzlfRJx4Vy8DwoUhtWLOHSK75D9AQ "Java (OpenJDK 8) – Try It Online") 1 byte saved thanks to [@Nevay](https://codegolf.stackexchange.com/questions/132272/java-is-to-javascript-as-car-is-to-carpet?noredirect=1#comment324764_132279)! [Answer] # C (only calling puts), 131 bytes ``` f(int*s){char r[]="carpet";~*s&'AVAJ'||(r[3]=0);for(;*s&255;*(int*)&s+=1)~*s&'AVAJ'||~s[1]&'IRCS'||~s[2]&'TP'||(r[3]='p');puts(r);} ``` It does have its problems, but it passes all of the testcases provided :) ``` g(int* s) { char r[] = "carpet"; ~*s&'AVAJ' || (r[3]=0); for(;*s & 255; *(int*)&s +=1) ~*s&'AVAJ' || ~s[1]&'IRCS' || ~s[2]&'TP' || (r[3]='p'); puts(r); } ``` > > Imaginary bonus points if your answer uses Java, Javascript, or Regex > > > well... no thanks [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` lD'¦‚å≠sη'îáå*„¾„ƒ´#è ``` [Try it online!](https://tio.run/##ATsAxP8wNWFiMWX//2xEJ8Km4oCaw6XiiaBzzrcnw67DocOlKuKAnsK@4oCexpLCtCPDqP//amF2YXNjcmlwdA "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` k=input().lower();print'car'+'pet'*(k[:4]!='java'or'javascript'in k) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9s2M6@gtERDUy8nvzy1SEPTuqAoM69EPTmxSF1bvSC1RF1LIzvayiRW0VY9K7EsUT2/CEwXJxdlFpSoZ@YpZGv@/68UADZPCQA "Python 2 – Try It Online") -11 bytes thanks to [notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) -2 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/Dennis) [Answer] # C#, ~~80~~ 78 bytes ``` s=>(s=s.ToLower()).StartsWith("java")&!s.Contains("javascript")?"car":"carpet" ``` [Answer] # ~~EXCEL~~ Google Sheets, ~~89~~ 86 Bytes Saved 3 bytes thanks to Taylor Scott ``` =LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0 ``` Takes an input on A1 ### Explanation ``` =LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0))) SEARCH("javascript",A1) #Case-Insensitive Find, returns error if not found ISERR( #Returns string true if error, False if not 3*ISERR( #Forces TRUE/False as integer, multiplies by 3 IF(SEARCH("java",A1)=1,1,1/0) #If java found, returns integer. if 1, java begins string #so returns 1, which will be turned into 0 by iserr. #Else returns 1/0, which will be turned into 1 by iserr. LEFT( #Returns digits from the left, based upon count. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ,“Ẋṣ“®Ẓȷ»ŒlwЀ/Ḅn2‘×3“¢Ẹị»ḣ ``` [Try it online!](https://tio.run/##y0rNyan8/1/nUcOch7u6Hu5cDGQcWvdw16QT2w/tPjopp/zwhEdNa/Qf7mjJM3rUMOPwdGOQgkUPd@14uLv70O6HOxb/f7h7y@F2oKLI//@zEssSuUBEWgWYSkpNzCsGs3SLS4pSE3Oh7OSizIISCNsCTOmVlmTm6BUnJ@blpRZBJIAYqs7LMcxRN9g5yDMgxNPPHSyLZAKEqZtalppXUsyVlpicmpSfn62LJFWckg1WiayxsDS1qJKroLIkIz@Pq6hCF@5y3cSCTN20/CIkA7jy8ksgCkAugTsEAA "Jelly – Try It Online") [Answer] # vim, 58 bytes ``` gUU:s/.*JAVASCRIPT.*/Q/g :s/^JAVA.*/car :s/[A-Z].*/carpet ``` [Try it online!](https://tio.run/##K/v/Pz001KpYX0/LyzHMMdg5yDMgRE9LP1A/nQsoGgcSBHKTE4tA3GhH3ahYCLcgteT//6zEskTdxIJM3bT8Il0Qpzi5KLOgBAA "V – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42+1 = 43 bytes Uses the `-p` flag. ``` $_="car#{"pet"if~/javascript|^(?!java)/i}" ``` [Try it online!](https://tio.run/##TY9NT8MwDIbv@RUm9LBJSytuCGmbph2mcUAIEEemNKRa2OYEJ51W8fHTCWuKSi/xE72284TqsomODAYYZTnM4ArmkBVwA2j24wlkm1xt7cFNgMN0BjxmmylXki4/uNOBm@q7eJNH6RUZFz5fRvOL9jouzBePsUXWHtUplVJL9ImED6Tl4Y/TcMfXqeR1MPvcK4moqQv6R9jt4nkhHpcP6/un9d0qpWehsw37Nxmg0EeNwbNKKl1auxODyL/uUudw8L3W1DDXhK1FRifRf0JIZ0RlabCAoQ1dQyvVO/1YF4xFH4X7BQ "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~44~~ 37 bytes ``` Ai`^(?!.*javascript)java .+ pet ^ car ``` *Thanks to @MartinEnder for golfing off 7 bytes!* [Try it online!](https://tio.run/##TY5BD4IwDIXv/RceTFAzzt4M8UDwYIwaj4SCJU50m9sg8OtnGAZ3ab@0r69Pk@UC3TJKC5fwIo92i3j9xA5NpbmyqxEh3oAiCzlUqJ3zo7HUvW8loTCemLGa8P1jbzDx1re4tfwVmwqFID0t5kdwSG4Ju@zP2emaHVP4RwiQUUfCGqixolLKhgUrc2@8Mjz8tKQHUIN9SAG6Z3NyhoqzWurAAIS0k2BMMgf5Ag "Retina – Try It Online") [Answer] # Common Lisp, ~~131~~ 125 bytes ``` (lambda(s)(format()"car~@[pet~]"(or(<(length s)4)(not(#1=string-equal"java"(subseq s 0 4)))(search"javascript"s :test'#1#)))) ``` [Try it online!](https://tio.run/##VZHBTsMwDIZfxeqE5hwyMTQkhAAxcUDjgBAgLhMHt3O3si7p4nTqLn31kbJ2dIckv5XPjv0nyTMpDphbW0BqHVSQGRhi9EM7iuDvSKtWxExGWq3FO6bNKUpcVvguumnFqPRZPpKEjGHXXYZ1ol@mX1P98fQ@e/ucvT63REKu4K7WWeFjoHnHxjeNpJRwbO1a9y5lsW7p8/RtyW4fRLH3K2uCcJXuDampyHQwQJ9lGes7qGn1v1O1sBjoDXnwENVX1wT6AWqqL6JgIQZDaRMvCEW1GKoozFU/zsNo9XeE1uEd5myWfgWiJgrDUzgY3wdbM7PUvC0pP34CShkLb0HgEiZKKRQml6z67gjcehY/HIwHAVCHqtl@AQ) Size reduced thanks to the [#n=](http://www.lispworks.com/documentation/HyperSpec/Body/02_dho.htm) “trick” of Common Lisp. **Explanation** ``` (lambda (s) ; anonymous function (format ; use of format string to produce the result () ; the result is a string "car~@[pet~]" ; print "car", then print "pet" when: (or (< (length s) 4) ; the string is less then 4 characters or (not (string-equal "java" (subseq s 0 4))) ; does not start with java or (search "javascript" s :test 'string-equal)))) ; contains javascript ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` f=input().lower().find print'car'+'pet'*(f('java')!=~f('javascript')) ``` Currently 1 byte longer than the shortest Python 2 solution. [Try it online!](https://tio.run/##TVCxbsMgFNz5Cjo90wgPnapUHqIOUTpUVVt1x/ih0DhAAafO0l93MVitB3gn3XHcPXeNR2vuJmU9DVQbCgDkU1xEvtSYR4vChIx4iB7FecHSaxcLvs@jHqLu6yCFMegLkc6ie9p97Pjb4@vh5f3wvM@sFN5hcViZFcjxgiYGooTE1toTX1GhO2Xl@uHXgP5KXO5D/Mj/SnDhNE/9VgbE2FgEc6j/TKl8HVyvY8W2aRluiLShvTi3ndjS8EBxRDlvaFJNZitW9/YbfZpKm444r02E1Ao2kIrBbaUqmP8BdtP8LLhEAMam2ekX "Python 2 – Try It Online") [Answer] # C (tcc), ~~144~~ 136 bytes ``` a;f(s){char*t=s;for(;*t;a=!strncmp(s,"java",4))*t=tolower(*t++);for(t=s;*t;)s=strncmp(t++,"javascript",10)&&s;puts(a*s?"car":"carpet");} ``` [Try it online!](https://tio.run/##bZFBTwMhEIXv/RWVQwPbpdHEg5FsTOPB1IMxarxPkU3XdgFhWts0/e0r201TisuBhG/eG@aB5Chl04AoqWd7uQCXYeFFaRwVGQoorjw6LWtLfU6@YQMkv2UsaNCszK9yNMPxmB31rS9YmC9OllDqTF66yiLJb67ZaOSFXaOnkPkHIsGR@3a3CgkTh6bSOKyh0pQN9oNhWCXtrmUiPpbbBMwVaJ8wHuZQUP@j3TAJvUvAZI3VauIlaK1cKj5HOheep59T/v74Nnv9mL08nQrHqKQ9xQ16R@ggVxulMY5SglRzY5Y8EvmvZeLub/uzVm4XAbvDhdERcFve87wcbMXDn/LertpgamrDX2Q/NH8) **Unrolled:** ``` a; f(s) { char *t = s; for (; *t; a = !strncmp(s, "java", 4)) *t = tolower(*t++); for (t=s; *t;) s = strncmp(t++, "javascript", 10) && s; puts(a*s ? "car" :"carpet"); } ``` [Answer] # [JAISBaL](https://github.com/SocraticPhoenix/JAISBaL), 36 [bytes](https://github.com/SocraticPhoenix/JAISBaL/wiki/JAISBaL-Character-Encoding) ``` ℠℘(?!.*javascript)^java.*}͵Ucar½Upet ``` Verbose/explanation: ``` # \# enable verbose parsing #\ tolower \# [0] convert the top value of the stack to lowercase #\ split (?!.*javascript)^java.*} \# [1] split the top value of the stack by (?!.*javascript)^java.*} #\ arraylength \# [2] push the length of the array onto the stack #\ print3 car \# [3] print car #\ !if \# [4] if the top value on the stack is falsy, skip the next statement #\ print3 pet \# [5] print pet #\ ``` JAISBaL was my first attempt at designing a golfing language, so it's rather quirky... there's no matches or contains, regex or otherwise, so instead we have to split and check the resulting array length... because JAISBaL has a split-by-regex... but no other regex support.... because reasons. Regex ~~stolen~~ borrowed from [@Cows Quack's answer](https://codegolf.stackexchange.com/a/132276/56085). [Answer] # Excel, 84 bytes ``` ="car"&IF(AND(ISERR(SEARCH("javascript",A1)),IFERROR(SEARCH("java",A1),2)=1),,"pet") ``` [Answer] # Excel VBA, 76 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs is `car`/`carpet` status to the VBE immediate window Does not use RegExp ``` ?"car"IIf(InStr(1,[A1],"Java",1)*(InStr(1,[A1],"JavaScript",1)=0),"","pet") ``` [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes ``` g=lambda s:(lambda r:'car' if r[:4]=='java' and 'javascript' not in r else 'carpet')(s.lower()) ``` [Try it online!](https://tio.run/##rdU9T8MwEAbgnV9xm@PBWWBAkTJUDBAGhACxIAYncVqnqW3Obml/faDhI6TqQn2ZvPjR@c6v43ZhYc1538/zTq7KWoLPku8VZqySyEA3gC/ZxWues1ZuJANpahiWvkLtAgNjA2gDCKrzCva7nAqMJz7t7LvChPPeoTYhmSdsoRnnEP@d/Yo3RVFQmKM4HJNcbLbx5lQslTQ@Ep2KwgdUchVlHopfl4RQvKTuY7oOukt9JY1ReCJ@UOOYjpNrHcXb2fNMPF49FPdPxd01hbiv8SemnKyPBKM@Kgq1USb46Mk0slKltUvxh/b18t/utMaWdNbt21rhjvKGu@GNpxRxK0ieyMPMOC0aiyKioaP4@U8iKXKawkkI@w8 "Python 3 – Try It Online") Yeah, it could be shorter but I wanted to try using a nested lambda! [Answer] ## [Perl](http://www.perl.org), **42 bytes** I believe the answer by stevieb has an incorrect output (tried that one myself - it returns car for 'javajavascript'). This should work: ``` say/^java/i&&!/javascript/i?'car':'carpet' ``` [Answer] # [Bracmat](https://github.com/BartJongejan/Bracmat), 66 bytes ``` (f=.pet:?b&@(low$!arg:(? javascript ?|java ?&:?b|?))&str$(car !b)) ``` [Try it online!](https://tio.run/##TU/BbsIwDP2VgKouOSTnCQlliAOCw4TYtLuTJVCgSZa4DCT@vWvTCXqxn/Xes59VBF0Dti21cxEMzqQq3@jZ/xYTiPsZleQIF0g6VgGJvPcDkWWnukvGyoSxoBoimSjG2hpCQelc@AYLm/1M7A2@sDbb@mKvuSkDLmXEuxUG6n88nMn4lUz7LhqsziJpcM7E6UA9A20WXwv@sdytt5/r91VmuzTdG@PUT8jNxThMxII2yvsTH1Hp@5SVY@NPY@KNhBsevCPxyh9vcAgVtz6OFhDncRD0oR6Z/gA "Bracmat – Try It Online") [Answer] # [Go](https://go.dev), 134 bytes ``` import."strings" func f(s string)string{T,o:=ToLower,"car" if Contains(T(s),"javascript")||!HasPrefix(T(s),"java"){o+="pet"} return o} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZHPSgMxEMbxOk8RA8IGNz2XQoVS_FMRKXXxVLDpNqmxbbIm2drS9upLeCmCL-FzeNGnMbupZREEL_mGmck3v2ReXsd6-56xdMLGHM2YVABylmnjaljMHH7LnaD1z-efnHVGqrHFIHKVIhFZFDIkyCqJdaOZ6Cv9xE2MU2YwSIHaWjlvbaMksiTGD2zObGpk5jBZrw8vmO0aLuSiUsZkpY-bOOMOb8BwlxuF9CbQfB18lNML2oigFYCfgxpNdCb5dGSjQWEAxSEWpQw5U7aMqMfkbLaLS4QQ10up5U5OazZlSnETCntUuGzdtuhNu9fpJp3r87Lq53rCAQF__gaouIeQ8jlXzoJgKR9qPaGVkh1Nys7qxcecmyVkS3evFZgF3b-KskxSoU3FAJR2oaGg3EN6Muj6vbipijClFLVbPeQVE_D30V1sC2rDlN998Yer0C0ifGT7ru-aJ8gHCsfIxsWyCYFNxbGvdp7d0-Qv2-Jn_mW7W-52G_Qb) [Answer] # [Lua](https://www.lua.org), 88 bytes ``` s=io.read():lower()print(s:sub(1,4)=='java'and not s:find'javascript'and'car'or'carpet') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhY3I4ptM_P1ilITUzQ0C4oy80o0iq1y8stTizQ0rYpLkzQMdUw0bW3VsxLLEtUT81IU8vJLFIqt0jLzUsBixclFmQUlIBn15MQi9fwiEFWQWqKuCTEfas2CJSDFEDYA) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~53~~ ~~49~~ 44 bytes ``` {32|}%"java"/(,\{6<"script"=+}/"carpet".3<if ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1rP0tDG2EhLu1ZVKSuxLFFJX0MnptrMRgmiQMlWu1ZfKTmxqCC1REnP2CYz7f9/L6Cy4OQirYISAA "GolfScript – Try It Online") This was my second GolfScript submission so after writing a couple more I was able to revisit this and shave a couple bytes. Previously, this mapped over a list, then summed it, then added it to a base value. Now, it just loops over the list, adding to the base value on each iteration. Here's an explanation of how the code works: ``` {32|}% # Convert the string to lowercase "java"/ # Split on "java". (, # Extract the first item, and push its length # (0 iff string starts with java). \ # Swap so the rest of the list is on top of the stack. {6<"script"=+}/ # Check if any start with "script": { }/ # Loop over each item: 6< # Take the first 6 characters. "script"= # Are they equal to "script"? (0 or 1) + # Add this to the top of the stack. # After this loop, the stack will be 0 iff the string started # with "java" and does not contain "javascript". "carpet".3< # Push "carpet" and its first 3 characters. if # If the value is 0, "car", otherwise "carpet". ``` [Answer] # Mathematica, 82 bytes regex ``` If[#~StringMatchQ~RegularExpression@"(?i)(?!.*javascript)^java.*","Car","Carpet"]& ``` [Answer] ## Batch, 91 bytes ``` @set/ps= @set t=%s:~0,4% @if "%t:java=%%s:javascript=%"=="%s%" (echo car)else echo carpet ``` Takes input on STDIN. Batch doesn't have a case insensitive comparison operator but it does have case insensitive string replacement so I can assign a temporary to the first four characters and then case insensitively replace java, which should then result in the empty string. Meanwhile I case insensitively replace javascript in the original string, which should leave it unchanged. [Answer] # Lua, 96 bytes ``` function(x)return x:lower():match"^java"and not x:lower():match"javascript"and"car"or"carpet"end ``` [Answer] # Perl, ~~98~~ ~~84~~ 62 Bytes ``` sub a{"car".($_[0]=~/javascript/i||$_[0]!~/^java/i?'pet':'');} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhsVopObFISU9DJT7aINa2Tj8rsSyxOLkos6BEP7OmBiyqWKcfBxLWz7RXL0gtUbdSV9e0rv1fUJSZV6KQqKEEklMAExCNSprW/wE) Thanks to bytepusher [Answer] # Dart VM, ~~104 bytes~~ 102 bytes ``` main(p){p=p[0].toLowerCase();print("car${p.indexOf('java')==0&&p.indexOf('javascript')<0?'':'pet'}");} ``` **Explanation**: Degolfed: ``` main(p) { p = p[0].toLowerCase(); print("car${p.indexOf('java') == 0 && p.indexOf('javascript') < 0 ? '' : 'pet'}"); } ``` We have our usual main function We replace `p` with `p[0].toLowerCase();` so that we don't have to declare a new variable (`var` plus a space would be 4 extra bytes) We then proceed to do the actual printing We print `car` unconditionally and we use inline statements for checking whether to print `pet` after it or not. If it has the string 'java' at index 0 and does not have 'javascript' in it, we do nothing (we actually append an empty string but it does not have any effect) and otherwise we append `pet`. [Answer] # Rust, 97 bytes ``` let s=if Regex::new(r"^javascript|^!java$").unwrap().is_match("javascript"){"carpet"}else{"car"}; ``` I'm pretty sure that there is a shorter solution but it's my first try :) ]
[Question] [ Just like [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") pushes one to exploit quirks and hidden features of the Python language. We already have [a place](https://codegolf.stackexchange.com/q/54) to collect all these [tips](/questions/tagged/tips "show questions tagged 'tips'") for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), those for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") remain transmitted by word of mouth or hidden deep within the python documentation. So today I would like to ask you what are some [tips](/questions/tagged/tips "show questions tagged 'tips'") for solving [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges in Python? Please only include 1 tip per answer. --- ## What makes a good tip here? There are a couple of criteria I think a good tip should have: 1. It should be (somewhat) non obvious. Similar to the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips it should be something that someone who has golfed in python a bit and read the tips page would not immediately think of. For example "Replace `a + b` with `a+b` to avoid using spaces", is obvious to any golfer, since it is already a way to make your code shorter. Thus it is not a good tip here. 2. It should not be too specific. Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction. For example tips of the form **How to X without using character(s) Y** are generally useful since banned characters is a common source restriction. The thing your tip helps to do should also be somewhat general. For example tips of the form **How to create numbers with X restriction** are useful since many programs utilize numbers regardless of the challenge. Tips of the form **How to implement Shor's algorithm with X restriction** are basically just answers to a challenge you just invented and not very helpful to people solving other challenges. [Answer] # Avoid "normal" letters Identifiers are [normalized](https://stackoverflow.com/q/62256014/2586922) by the Python 3 parser. This implies that cursive (Unicode) letters such as `𝓪𝓫𝓬𝓓𝓔𝓕` are interpreted as their ASCII-compliant equivalents `abcDEF`. So the following code [works](https://tio.run/##K6gsycjPM/7//8PcyXNtDY2MuYCMnUC8G4g3AfF2IN6rAZLV/P8fAA) (as was exploited [here](https://codegolf.stackexchange.com/a/207563/36398)): ``` 𝓝=123 𝓹𝓻𝓲𝓷𝓽(𝓝) ``` Python versions in which this behaviour is confirmed: * Works: 3.4, 3.5, 3.6, 3.7, 3.8 * Doesn't work: 2.7 ### Example source restriction: * *Use no characters `abc···xyz`, `ABC···XYZ`.* [Answer] # Avoid Numbers with Booleans When performing arithmetic operations on Booleans, Python treats them as if they are the numbers 1 and 0. So for example ``` >>> True+False 1 ``` You can make all positive numbers by just adding booleans to each other. You can also substitute the booleans for boolean values, for example `[]>[]` is `False` and `[[]]>[]` is `True` so ``` >>> ([]>[])+([[]]>[]) 1 ``` In some cases, Booleans can even be used in place of a number without having to using arithmetic to cast it. For example, you can index into lists/tuples/strings with Booleans, so: ``` >>> ['a','b'][True] 'b' ``` --- ### Example source restrictions: * *Use no digits (`0123456789`)* * *Use no alphanumeric characters* * *Use no `if` conditions* [Answer] ## Avoid Parens with List indexing Parentheses are super useful for creating the correct operator precedence so it is a bummer when they are banned. However if `[]` are still available we can use them instead. Simply replace ``` (...) ``` with ``` [...][0] ``` This creates a list and indexes it to get its only element. The list causes the inside to be evaluated first solving your precedence issue. The example above uses the characters `[]0` to do this however there are other third characters that can be used in this case if need be. * Using characters `[]>` write `[...][[]>[]]` * Using characters `[]<` write `[...][[]<[]]` * Using characters `[]=` write `[...][[[]]==[]]` --- ### Example source restriction: * *Use no parentheses* [Answer] ## Function calls without parentheses [We can avoid using parentheses for operator precedence using list indexing](https://codegolf.stackexchange.com/a/209737/56656), but parentheses are still very useful for calling functions. List indexing can be used here as well to solve the issue, however it is a lot more complex so I've made it its own answer. In order to call a function we start by making a new class which has it's indexing defined to be the function. So if we want to call `print` this might look like ``` class c:__class_getitem__=print ``` Then to call the function we simply index it with the argument we want. For example to print `"Hello World"` we do ``` c["Hello World"] ``` This has a few unfortunate short comings: * It can only be used to call functions with one parameter. * There are quite a few characters that are required to pull this trick off. ( `:=[]_acegilmst`) * It uses up a lot of characters if you are doing [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") But sometimes it might be your only option. --- ## Example source restriction: * Use no parentheses [Here's](https://codegolf.stackexchange.com/a/207662/56656) an example of it being used. [Answer] # Use `<<` and `|` to generate constant without `+` Fun fact: You can get any positive constant only using `[]<|`. The way to go is left-shifting a boolean. `[]<[[]]` is 1, so `[]<[[]]<<[]<[[]]` should left-shift 1 with 1, which is 2. Does it work? ``` >>> []<[[]]<<[]<[[]] Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> []<[[]]<<[]<[[]] TypeError: unsupported operand type(s) for <<: 'list' and 'list' ``` ...No. The precedence is wrong. Luckily, we can resolve this with "Ad Hoc Garf Hunter Parenthesis(TM)": ``` >>> [[]<[[]]][[]<[]]<<[[]<[[]]][[]<[]] 2 ``` Aha! To get numbers other than power of two, you still need `+`... or not. `|` or `[bitwise or][[]<[]]`\* will do that for you. ``` >>> [[]<[[]]][[]<[]]<<[[]<[[]]][[]<[]]<<[[]<[[]]][[]<[]]<<[[]<[[]]][[]<[]]|[[]<[[]]][[]<[]]<<[[]<[[]]][[]<[]] 10 ``` To get negative numbers without `-`, you may want to use `~`. \* That part was enclosed in an "Ad Hoc Garf Hunter Parenthesis(TM)" to indicate precedence. [Answer] ## Access methods and built-in functions through `__dict__` Classes contain a `__dict__` attribute, which maps their method names to the methods themselves. If you can't type a method name directly, you can get them from this `__dict__`. For example, let's say you need to append something to a list, but you can't use the characters `p,n,+`, etc. Since `append()` is the 26th method in a list's `__dict__`, you can call the method like this: ``` a = [1,2,3] list(a.__class__.__dict__.values())[26](a, 4) print(a) # prints [1,2,3,4] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1HBViHaUMdIxziWKyezuEQjUS8@Pjknsbg4Ph7ISslMLgEyyhJzSlOLNTQ1o43MYjUSdRRMNLkKijLzgMo1//8HAA "Python 3 – Try It Online") This can also be used with `__builtins__` to access built-in functions. Even if someone bans the character `x` to block the `exec` function, you can still call `exec` like this: ``` list(__builtins__.__dict__.values())[20]("print('Hello, World!')") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyezuEQjPj6pNDOnJDOvOD5eLz4@JTO5BMgoS8wpTS3W0NSMNjKI1VAqKMrMK9FQ90jNycnXUQjPL8pJUVTXVNL8/x8A "Python 3 – Try It Online") This works best in more recent versions of Python that guarantee dictionary order, but there are probably other ways to use this in older versions, like iterating through the `__dict__` with a regex or substring match. [Answer] ## Use `ord()` or binary strings to avoid digits Most integers in the ranges `[32..47]` and `[58..126]` can easily be obtained from the ASCII code of a single character with: ``` x=ord('A') # or, if parentheses are not allowed: y=b'A'[False] ``` [Try it online!](https://tio.run/##FcqxCoAgFAXQ3a@40GBBW1vg0NJPRIPRiwLxiQop4bdbbWc4LseT7VBrUuz3Vk6yE6IB@x7XAac92XhSoICPsByhjeGb9lGIrLbvL7M2gdbq/GVje8gEhSeVHvlHLrKrLw "Python 3 – Try It Online") Larger integers can also be produced using from their unicode points: ``` >>>print (ord("±")) 177 >>> print (ord("π")) 960 ``` If you can use an assignment, or you need to avoid brackets you can unpack the values, instead. Note that this will not work inline, even with the walrus operator. ``` x,*_=b'A' y,_=b'A_' ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v0JHK942Sd1RnatSB8yIV/9fUJSZV6KRpl6hYKtQXVGro1AJYlTWqmv@BwA "Python 3 – Try It Online") ### Example source restrictions: * *Use no digits* * *Use no digits / no parentheses / no brackets* [Answer] ## Alternatives to `eval` and `exec` Do you need to treat a string as code, but you can't use `eval` or `exec`? There are at least three other ways to execute a string: ### 1) timeit.timeit ``` import timeit _=timeit.timeit("print('Hello!')", number=1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzc1s4Qr3hbC0INQGkoFRZl5JRrqHqk5OfmK6ppKOgp5pblJqUW2hpr//wMA "Python 3 – Try It Online") `timeit` runs `number` times and returns an average of how long it took. By default it runs 1 million times, so you'll almost certainly want to set `number=1` or raise an exception to break out (e.g. `"print('hello'); 0/0"`). Thanks to [Ethan White](https://codegolf.stackexchange.com/a/209878/94694) for showing me this approach. ### 2) os.system ``` import os c='echo "import math;print(math.pi)" | python3' _=os.system(c) # Prints 3.141592653589793 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCG/mCveNr9Yr7iyuCQ1V0M9NTkjX0EJKpmbWJJhrVBQlJlXogFi6xVkaiop1CgUQAxR1/z/HwA "Python 3 – Try It Online") `os.system` runs an arbitrary shell command and returns its exit code. If you just need to print something, you can stick to `echo`, but you can also execute arbitrary code by calling `python3` itself. ### 3) code.InteractiveInterpreter().runcode ``` from code import InteractiveInterpreter as I i = I() i.runcode("print('Hello!')") ``` [Try it online!](https://tio.run/##Hcs9CoAwDEDhvaeIXWwXF2d3ewypEQOalBgFT19/lse3vHLbKtzXuqjskGVGoL2IGiQ21CkbXfizKL6F6YDkCAZIITrq9ORvCr4osYV2xG2Tpo0@1voA "Python 3 – Try It Online") `code` is specifically designed for read-eval-print loops, and even though it's a bit clunky, this is the most powerful of the three. `timeit` and `os.system` isolate their processes, but an `InteractiveInterpreter` can use global state instead of its own: ``` from code import InteractiveInterpreter as I a = 64 i = I(globals()) i.runcode("import math; a=math.log2(a)") print(a) # a = 6.0 print(math.pi) # math is imported globally ``` [Try it online!](https://tio.run/##LYwxCsMwDEV3n0JkspcMbelScgAfQ03dRGBbQlELPb3rhCz/Pfjw5Gcr12trb@UCM78SUBFWg1gtKc5G33SoaOoLuEF0CBPcb446ol8yPzFvPgRHo37qHvHDWSlo6wNw2jlmXi4ewxCcKFXresrxCoXW/g "Python 3 – Try It Online") [Answer] ## Use `--` to avoid + E.g to do `a+b`: ``` a--b ``` **Example source restriction:** * Avoid the `+` operator [Answer] ## Encode restricted characters and use `exec()` Like most interpreted languages, Python can run a string as code with `eval` and `exec`. `eval` is more limited, but `exec` can handle imports, function definitions, loops, exceptions, etc. When combined with some of the other tips about encoding characters, this allows you to write your code normally: ``` import sys def f(i): return 1 if i==1 else i*f(i-1) i=int(sys.argv[1]) print(f(i)) ``` Then pick an encoding and pass the encoded version to `exec`: ``` exec('\x69\x6d\x70\x6f\x72\x74\x20\x73\x79\x73\x0a\x0a\x64\x65\x66\x20\x66\x28\x69\x29\x3a\x0a\x20\x72\x65\x74\x75\x72\x6e\x20\x31\x20\x69\x66\x20\x69\x3d\x3d\x31\x20\x65\x6c\x73\x65\x20\x69\x2a\x66\x28\x69\x2d\x31\x29\x0a\x0a\x69\x3d\x69\x6e\x74\x28\x73\x79\x73\x2e\x61\x72\x67\x76\x5b\x31\x5d\x29\x0a\x70\x72\x69\x6e\x74\x28\x66\x28\x69\x29\x29\x0a') ``` [Try it online!](https://tio.run/##XU87FsMgDDtO2i0x5XcXljSQl6nt0IGengpsXlMGPWEsyfbr8z6eD1VKymm7TCEbD8SQ7QzewQTcQibUVgGeeV4ZBj2jAcOaxo5zCFCia35ibc2zWurEPbWI35@yqj8Ker/O2niH@u46WofZ3eNPu0pem5HkLvd/F@HfLLKbBSNT3zlLx1@e7fcMWeP9rJ@upRT3BQ "Python 3 – Try It Online") [Answer] ## Replace operators with dunder methods Most python operators are syntactic sugar for specific method calls (often called "magic methods" or "dunder methods", with "dunder" being short for "double underscore"). For example, `+` calls `__add__()`, `==` calls `__eq__()`, and `<<` calls `__lshift__()` If operators are restricted, you can call these methods directly: ``` a = 1 print(a.__add__(1).__eq__(2)) # True ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1HBVsGQq6AoM69EI1EvPj4xJSU@XsNQE8hMLQSyjDQ1//8HAA "Python 3 – Try It Online") For assignment, you can use `__setitem__` on the `locals()` or `globals()` dictionaries, whether or not the variable already exists: ``` a = 1 locals().__setitem__('a',2) locals().__setitem__('b',2) print(a.__add__(b).__eq__(4)) # True ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1HBVsGQKyc/OTGnWENTLz6@OLUksyQ1Nz5eQz1RXcdIE4dcEliuoCgzr0QjESiVmJICFE4CqUotBLJMNDX//wcA "Python 3 – Try It Online") Note that you'll have to add parentheses around numbers to avoid a syntax error. `4.__eq__(4)` won't work, but `(4).__eq__(4)` will. [Answer] # Use `__import__("module")` instead of `import module` To avoid whitespace in the `import statement`, or to dynamically construct the name of the module to import as a string (e.g. `"RANDOM".lower()` if you can't use a lowercase `d`). Not likely that useful because you don't often need the standard library, and you still need to be able to use `_`, `i`, `m`, `p`, `o`, `r`, `t`, `(`, and `)`. Edit: or as Ad Hoc Garf Hunter suggests, you can use `import<tab>module` (with a literal tab character)! [Answer] # File Encodings You can set a custom encoding for your Python source file in a comment at the start. This includes various Unicode things, but also [text transforms](https://docs.python.org/3/library/codecs.html#text-encodings) such as `unicode_escape` and `punycode`, which can be used for restricted source! Here's an example: ``` # encoding: unicode_escape print(\x22Hello, World!\x22) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3zZUVUvOS81My89KtFErzMoHM1PjU4uTEglSugqLMvBKNmAojI4_UnJx8HYXw_KKcFEWQgCZEO9QUmGkA) Here's the exact specification of an encoding line, from [the Python documentation](https://docs.python.org/3/reference/lexical_analysis.html#encoding-declarations): > > If a comment in the first or second line of the Python script matches the regular expression `coding[=:]\s*([-\w.]+)`, this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file > > > So, for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the best definition is therefore `#coding:unicode_escape`. This works not only at the file level, but also with `exec` and `eval` *if you pass them a byte string*: ``` print(eval(rb'''# encoding: unicode_escape \x22Hello, World!\x22''')) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3XQuKMvNKNFLLEnM0ipLU1dWVFVLzkvNTMvPSrRRK8zKBzNT41OLkxIJUrpgKIyOP1JycfB2F8PyinBRFkABQi6YmxDComTCzAQ) Not as useful there though because you can generally just pass a constructed string. [Answer] This is likely not relevant to the question but it's very silly. This is (maybe) a more portable way of water\_ghost's convoluted method of accessing builtin methods. The index is 26 only on CPython 3. This very small and extremely easy to understand modification allows it to run on CPython 2.7, CPython 3, PyPy 2.7 and PyPy 3 (tested on Debian 10 amd64) ``` a = [1, 2, 3] list(a.__class__.__dict__.values())[[14,13,26,25][sum(map(ord,{__import__("sys").version[0],__import__("platform").python_implementation()[0]}))&3]](a, 4) print(a) ``` --- The correct indices (on my system) are ``` CPython 2.7 13 CPython 3 26 PyPy 2.7 26 PyPy 3 25 ``` And by a lucky coincidence `('C'+'2')%4 == 1`, `('C'+'3')%4 == 2`, `('P'+'2') == 2` and `('P'+'3') == 3`. The value 14 is there to trick you into thinking there is a pattern. [Answer] ## Use `*` to avoid `/` `x**-1` is equivalent to `1/x`. So to do `y/x` you can do `x**-1*y`. If you desperately want to get rid of the `-1`, you can check out Ad Hoc Garf Hunter's other tip. ## Example source restriction: * Avoid using the `/` character [Answer] ## How to create characters just with numbers, quotes and backslashes Strings can be composed with `\ooo` where `ooo` is the octal value of the character. Eg: ``` '\141'=='a' ``` You can also use hex, at the expense of an `x` (and `a`,`b`,`c`,`d`,`e` and/or `f` if they're used): ``` '\x61'=='a' ``` And unicode at the expense of a `u` (two pre-Python 3) and hex characters if they're used: ``` '\u2713'=='✓' ``` [Answer] # `__debug__` is True Pretty self-expl... expl... ``` >>> __debug__ True ``` ]
[Question] [ ## Background *[Milking the deck](http://www.dictionaryofgambling.com/gambling_terms/poker/m/#milk_the_deck)* is the name given to the following card shuffling method: 1. 'Pinch' the deck to remove the top and bottom cards simultaneously. (With lots of imagination, this action resembles milking a cow.) This pair of cards forms the base of a new pile. 2. Repeat, adding each pair of cards to the top of the new pile, until the whole deck has been used. **Example** Suppose we start with a deck of six cards, `[1, 2, 3, 4, 5, 6]` (lower-indexed elements are nearer to the top). Let's milk the deck: 0. `old = [1, 2, 3, 4, 5, 6]`, `new = []` 1. Remove `[1, 6]`: `old = [2, 3, 4, 5]`, `new = [1, 6]` 2. Remove `[2, 5]`: `old = [3, 4]`, `new = [2, 5, 1, 6]` 3. Remove `[3, 4]`: `old = []`, `new = [3, 4, 2, 5, 1, 6]` After milking, the deck is therefore ordered `[3, 4, 2, 5, 1, 6]`. ## Challenge Your task in this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to implement the milking operation on a given array and output/return the result. The input array will contain only positive integers, not necessarily distinct. If the input array contains an odd number of elements, then the last milking step transfers only one element (the last one remaining) from the input to the output array. ## Test cases Input -> Output ``` [1, 2, 3, 4, 5, 6] -> [3, 4, 2, 5, 1, 6] [1, 2, 3, 4, 5, 6, 7] -> [4, 3, 5, 2, 6, 1, 7] [9, 7, 5, 3, 1, 2, 4, 6, 8, 10] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 1, 2, 1, 2] -> [2, 1, 1, 1, 2] [] -> [] ``` [Answer] # [R](https://www.r-project.org/), ~~53~~ ~~50~~ 48 bytes ``` f=function(x,y=rev(x))if(c(y,F))c(f(y[-1]),y[1]) ``` [Try it online!](https://tio.run/##K/qfm5mTbfs/zTatNC@5JDM/T6NCp9K2KLVMo0JTMzNNI1mjUsdNUzNZI02jMlrXMFZTpzIaSP5PLCpKrLQ1tDLjAhmgAeZq/gcA "R – Try It Online") Repeatedly takes the bottom card & flips the deck. [Answer] # [R](https://www.r-project.org/), 36 bytes ``` function(x)rbind(rev(x),x)[-seq(!x)] ``` [Try it online!](https://tio.run/##K/qfm5mTbfs/rTQvuSQzP0@jQrMoKTMvRaMotQzI1qnQjNYtTi3UUKzQjP2fWFSUWGlraGXOBdKkAeZqQtiZeSWp6alFGgaamv8B "R – Try It Online") Takes `integer(0)` (a length 0 integer vector) for empty input. Stacks the reversed array onto itself, giving something like: ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 7 6 5 4 3 2 1 [2,] 1 2 3 4 5 6 7 ``` And then removes the first `n=length(x)` elements, going down the columns, then across the rows. [Answer] # [Haskell](https://www.haskell.org/), ~~38~~, 33 bytes ``` g(x:y)=f y++[x] g x=x f=g.reverse ``` [Try it online!](https://tio.run/##ZYxNCsIwFIT3OcUsW/oo/lStQo7gCUIWAZNYbGtJRdLTx5hAEdw8Zr5veHc1P3Tfh2ALf1lKbrBUlfCSWXjumeG2dvqt3azDoLoRHLcnAwY1XVFMrhtfqGHKiAABsSXsCHtCQzgQjjIJ@heE0@rOsSQadd41adHGuvn9kOX3rjQHGT4 "Haskell – Try It Online") **-5 bytes thanks to @Zgarb.** Very simple port of [Dominic van Essen's solution](https://codegolf.stackexchange.com/a/207460/42833). Go upvote theirs instead. I was going to put this as a reference to compare to in [my other answer](https://codegolf.stackexchange.com/a/207467/42833), but figured it was more in the spirit of cgcc to submit twice. [Answer] # [Haskell](https://www.haskell.org/) with `-XParallelListComp`, ~~52~~ 49 bytes ``` f l=drop(length l)$id=<<[[x,y]|x<-reverse l|y<-l] ``` [Try it online!](https://tio.run/##ZYxLC4JAFIX3/YqzaKFwjR72Al21LWgZyCyGHHXo@mCUUPC3N5lCBG0u53zf4WayfihmaxNwGJuyclgVaZOB3bmOwyCIopY60beBZ9RTmVqB@y7wWNhc6gIh4nIG5LK6wKmMLhoskLgDAiJEK8KasCH4hC1hJ0ZB/4Kw/7rjUEY66Gnnj4vDUJe/Hyb5uV86BWFf94RlWlvvdpVGMis@67o5lXn1Bg "Haskell – Try It Online") # Explanation This is for my old answer. The only difference is that the riffling has been golfed from a call to `zip` and a flattening step to a parallel list comprehension and a flattening step. This works by taking two copies of the input deck. You reverse the first copy, then riffle it with the second. Then remove as many cards as there were in the input deck, leaving behind the answer. In the code, ``` f l=drop(length l)$(\(x,y)->[x,y])=<<zip(reverse l)l (\(x,y)->[x,y])=<<zip(reverse l)l riffling zip riffle reverse l the reversed deck l the deck (\(x,y)->[x,y])=<< flattening drop(length l) removing drop discard (from top) length l length of input ``` The `flattening` portion does as follows. When riffled, the deck looks like `[(6,1),(5,2),(4,3),(3,4),(2,5),(1,6)]` (list of tuples). We "flatten it" to look like `[6,1,5,2,4,3,3,4,2,5,1,6]`. I remain convinced that this approach might be shorter than the [port of Dominic van Essen's answer](https://codegolf.stackexchange.com/a/207469/42833). I think the `(\(x,y)->[x,y])` function can be shortened or removed, as well as the annoying use of `length`. # Pointfree Haskell, 61 bytes Just for fun; I initially thought it would be shorter. ``` foldr(pure tail).((\(x,y)->[x,y])=<<).(zip.reverse<*>id)<*>id ``` [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 33 bytes ``` $\=" $` $'".$\,$_=$1while/ (.+) / ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxlZJQSVBQUVdSU8lRkcl3lbFsDwjMydVX0FDT1tTQf//f0MFIwVjBRMFUwWzf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") ## Explanation This approach utilises `-p` which allows work on input implicitly, by putting it in `$_` for each line of STDIN and implicitly `print`ing `$_` at the end of the program. `$\` is used as this magic variable is automatically `print`ed after the contents passed to `print`. The main body is a `while` loop that checks if `$_` `m//`atches `(.+)` (a space followed by one or more characters followed by another space), while `$_` does march (`m//` implicitly checks `$_` when not called via `=~`) `$\` is set to a space, the remaining string after the match (`$'`) followed by another space and the preceding string contents before the match (`$`` ), concatenated with the existing contents of `$\`. `$_` is then set to the matched string (excluding the spaces) which is captured in `$1`. At the end of the script, this leaves the central characters (either one or two depending on whether the list has an even or odd number of entries) in `$_`, which is implicitly `print`ed, followed by the content of `$\`, which contains a leading space and the rest of the list "milked". [Answer] # [Python 3](https://docs.python.org/3/), 36 bytes ``` M=lambda a:a and M(a[-2::-1])+a[-1:] ``` [Try it online!](https://tio.run/##bUy7CoMwANz9ihsTekKT@GgD/YR8gWRIcVBoYxCXfn2M0MXS4Y57cemzTUs0ObvHK7yfY0CwBXGEE2GotbW18vJSpLI@p3WOm3BiUNQ0bNiy81JW/3L2p@ZO9ERLGEIRmmiIjrgVe/35@A4OPjXF5B0 "Python 3 – Try It Online") Uses Dominic van Essen's [approach](https://codegolf.stackexchange.com/a/207460/68261): repeatedly takes the bottom card and recurses on the reverse of the rest of the deck. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Âsø˜2äθ ``` -1 byte thanks to *@Neil* [Try it online](https://tio.run/##yy9OTMpM/f//cFPx4R2n5xgdXnJux///0YY6CkY6CsY6CiY6CqY6CmY6CuaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w03Fh3ecnmN0eMm5Hf91/kdHG@oY6RjrmOiY6pjF6iDzdMyBfEsdcyDbWAckbgIUs9AxNAArAwkAMZAdGwsA). Or alternatively, a port of [*@DominicVanEssen*'s approach](https://codegolf.stackexchange.com/a/207460/52210) is **7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** as well: ``` vRćˆ}¯R ``` [Try it online](https://tio.run/##yy9OTMpM/f@/LOhI@@m22kPrg/7/jzbUUTDSUTDWUTDRUTDVUTDTUTCPBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/7KgI@2n22oPrQ/6r3Noy//oaEMdIx1jHRMdUx2zWB1kno45kG@pYw5kG@uAxE2AYhY6hgZgZSABIAayY2MB). **Explanation:** ```  # Bifurcate the (implicit) input-list (short for Duplicate & Reverse copy) # i.e. [1,2,3,4,5,6,7] → [1,2,3,4,5,6,7] and [7,6,5,4,3,2,1] s # Swap so the input-list is at the top again # → [7,6,5,4,3,2,1] and [1,2,3,4,5,6,7] ø # Zip/transpose the lists together to create pairs # → [[7,1],[6,2],[5,3],[4,4],[3,5],[2,6],[1,7]] ˜ # Flatten it # → [7,1,6,2,5,3,4,4,3,5,2,6,1,7] 2ä # Split it into 2 equal-sized parts # → [[7,1,6,2,5,3,4],[4,3,5,2,6,1,7]] θ # Pop and push just the last part # → [4,3,5,2,6,1,7] # (after which it is output implicitly as result) v # Loop the (implicit) input-list amount of times: # i.e. we'll loop 7 times for input [1,2,3,4,5,6,7] R # Reverse the list at the top of the stack, # which will use the (implicit) input-list in the first iteration # i.e. [1,2,3,4,5,6,7] → [7,6,5,4,3,2,1] ć # Extract head; pop and push remainder-list and first item separated # → [6,5,4,3,2,1] and 7 ˆ # Pop this first item, and add it to the global array }¯ # After the loop: push the global array # → [7,1,6,2,5,3,4] R # Reverse it # → [4,3,5,2,6,1,7] # (after which it is output implicitly as result) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~65~~ ~~62~~ 60 bytes ``` i;f(c,z)int*c;{for(i=0;i||(i=z-=2)>0;)*c^=c[i--]^=*c^=c[i];} ``` [Try it online!](https://tio.run/##dVDdboIwFL4/T3HCsgTwYGxLwQ3xRZwmBmRrsqFBvEF5dnfKzzDL1gv6/Z2vLVnwnmX3u0kKN6PGM2XtZ8m1OFauSReJud14b4JUeutF4vnZLs02Jgi2u3TA26S9nyoec@3ovqqId2y8K2BXwqQrWjXJbGY8QOzShes85@gQD3CHl0ALUB/Of7T0cXQdU54uNb6iw@ledW2wsbSY4E/@rTxe6v9H2DnbkNMfbs/LxWabXgVJUhSSpqhNel3@0ikeHWWdF8KYUBMqQkEoCUPCiHDJdDEmw75jCNjv6GjrMAF4MmX2eckPuDrXuTnOP9Zd4mtvStdD/hndL8oFRfYFPZEUT0SRWEyM7zoRTdYBaO8CJSoMUWOEfockY4ER@NgvH/SQmVQfwk6bkj4oVsJBYc4KPJbHuGTRYsVMMhe4hBinJSCajzgGPeAIwg5pULyH8NhoG6JhQvI1pzynh9R4knUVX1vzs@Eb "C (gcc) – Try It Online") The loop iterates backwards from the last - 1 element and swaps it with the first element. Then it restarts iteration two elements backwards until finished. Saved 3 using loop reset in loop check instead of recursion. Saved 2 more because `i>0` check is no more needed. Example ``` 1 2 3 4 5 6 7 8 => 4 5 3 6 2 7 1 8 7 1 6. 7 5. 6 4. 5 3. 4 2 3 4 5 6 7 1 8 6 2 5 6 4. 5 3 4 5 6 2 7 1 8 5 3 4 5 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~11~~ 10 bytes -1 byte thanks to @FryAmTheEggman ``` L&bay_Pbeb ``` port of [Dominic van Essen's solution](https://codegolf.stackexchange.com/questions/207456/hot-moo-shuffle-milk-an-array/207460#207460) to [Pyth](https://github.com/isaacg1/pyth). [Try it online!](https://tio.run/##K6gsyfj/30ctKbEyPiApNany//9oQx0FIDKCkLH/8gtKMvPziv/rpgAA "Pyth – Try It Online") ## Explanation ``` L&bay_Pbeb L define function named y with argument b which returns &b short circuiting and of b and a eb the last element of b appended to y the return value of y when called on _ the reverse of Pb b without its last element ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` ec2.i_ ``` [Try it online!](https://tio.run/##K6gsyfj/PzXZSC8z/v//aEMdBSMdBWMdBRMdBVMdBTMdBfNYAA "Pyth – Try It Online") Looking through the [Pyth documentation](https://github.com/isaacg1/pyth/blob/master/rev-doc.txt) reminded me of the interleave function `.i`, which is extremely useful here. How it works: * `.i`: Interleave the following two lists: + `_`: The reversal of the input (implicit), and + The input (implicit). * `c2`: Split the result in half. * `e`: Output the second half. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 7 bytes -4 bytes thanks to Ada -3 bytes thanks to Bubbler -1 byte thanks to ngn! ``` ≢↓∘∊⌽,⍪ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEedix61TX7UMeNRR9ejnr06j3pX/X/UNxUok6ZgqGCkYKxgomCqYMaFRUzBHC5qqWAOFDEGy5oAZSwUDA2QtICEgRgu8qh3zX8A "APL (Dyalog Classic) – Try It Online") Port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/207458/75681) and [streetster's K solution](https://codegolf.stackexchange.com/a/207495/75681) - don't forget to upvote them! [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` M=lambda a:a and M(a[1:-1])+a[::len(a)-1or 1] ``` [Try it online!](https://tio.run/##bYzNCsIwHMPvPkWOLWbgf92XBR@hT1B6qExQmN0Yu/j0tYKXiYcEkl/I8truczI5u8sUn9cxItqiNMKp6MVWEvQxemunW1JRVzKvkJCX9ZE25ZQX1jRs2LILWh/@9ex35Ez0REsYQoiaaIiOGEo8/Xx8Bx/fkRLyGw "Python 3 – Try It Online") Performs milking in the same procedure as specified. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes Same approach as [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/207460/95594), so upvote that. ``` Ė|tT&k↔↰,T ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//8i0mpIQtexHbVMetW3QCfn/P9pQx0jHWMdEx1THLPZ/FAA "Brachylog – Try It Online") ``` Ė|tT&k↔↰,T Ė input is an empty list | or tT save the input's last element as T & and k the input without the last element ↔ reverse it ↰ recursively call this predicate ,T and append T ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` I⮌Eθ§⎇﹪κ²θ⮌θ⊘κ ``` [Try it online!](https://tio.run/##Nco9C8IwEIDhv3LjBc7B78FJXOpQEHErHY7mQGlI7DUG/fVnEHy3F57hzjokDmYXfcSMJ54zXqWIzoItP3EiOOZz9PLGm2hk/WCb/CskHAlWjqCCv59c/YZDEY@j@3Uw67pllQRrgg3BlmBHsO97W5TwBQ "Charcoal – Try It Online") Link is to verbose version of code. Works by calculating the reverse of the first half of the flattened zip of the reversed list with itself. Explanation: ``` θ Input array E Map over elements κ Current index ﹪ ² Modulo literal 2 θ Input array ⎇ If index was odd otherwise ⮌ Reverse of θ Input array § Indexed by κ Current index ⊘ Halved ⮌ Reverse the result I Cast to string Implicitly print ``` [Answer] # Brainfuck, 64 Bytes ``` ,[>,]<[[->>+<<]<[<]>[-<+>]<[->>[>]>+<<[<]<]>>[[-<+>]>]<<]>>>[.>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9YmOlrXzk7bxgbIsom1i9a10bYDMoFi0XaxIHGgKFDcLhoiA5QD8eyi9exi//83NDI2MTUDAA "brainfuck – Try It Online") ``` ,[>,] Read input array into memory <[[->>+<<] Move last number of input to the right of the input array <[<]>[-<+>] Move the first number of input to the left the input array <[->>[>]>+<<[<]<] Move the number left of the input array to the left side of the number(s) to the right of the input array >>[[-<+>]>]<<] Move the input array to the left to make some space, then repeat >>>[.>] Print output array ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~88~~ ~~71~~ ~~62~~ ~~60~~ 59 bytes Saved 9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved a byte thanks to [G. Sliepen](https://codegolf.stackexchange.com/users/46301/g-sliepen)!!! ``` t;i;f(l,n)int*l;{for(;n>1;l[n]=t)t=*l,wmemcpy(l,l+1,n-=2);} ``` [Try it online!](https://tio.run/##fVTbjpswEH3PV4yQUmHiqMGQ3aZetg9VvyJBqxUxWyTiRIBU2ohvT8cXiOPNbqT4MufMeObgcbF8K4rLpeMVL8OaSlLJLqr5uTw2IZfPMa@3Ms860mVRTf8cxKE4/UVevYipXGaM8OFyatAnVH5QU8AZJIHzDPCHUUAhUEEGK47TE0gOi0VFQLuVYTBv5/sA/X7gEHwPcKy3VU74bJgpz8NrJUMyM/GUoRNt97La5hjxHFNgFBIKKYU1hYeB39Li@zQKjz6TGeYGIc1BsvFKNf8bble@TzJFN1Q1@pzUcK7mSNtbYza1UJusnZmdEzunTkzRn0Tfif0ogKmJ6ZTjWwEmqhUh1UWtNftBsx/vsdmHkmkVNp4Qk58Vw8gQvxNj4t0RZMQ0AudrjdQpwlkzZ50469QTv32phTTHtdU/cSxDozf5areR3VNw8djDYw9nHs48PPHwxMNTD0@Jzbv4/dpE0JiMg13/i@36zU/8r1VrOPskQA@vweRe9LbJ9PJpPHOU53rqZNGdqNhjv97cUYxmrqqm5NxlgBxRrbHPME@Cwik@Bp4dex6WzxA49vIj7mcxQjeCuUiY1HSZ7uckboOpUopj04hClRs7GX3yco0OX4wE@FpBhgfj/D5LAvN2J/H7NVvrltvjh9lw@Q8 "C (gcc) – Try It Online") Inputs a pointer to the array and its length and milks the array in place. Code actually does the moo-shuffle: tucking the first element away, shifting all but the last down one, and putting the first one just in front of the last. This is repeated, shifting down 2 elements from the end each time, until there are only two elements left and we're done. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~16~~ 15 bytes **Solution:** ``` {(#x)_,/|x,'|x} ``` [Try it online!](https://tio.run/##y9bNz/6fZlWtoVyhGa@jX1Oho15TUfs/TV3DUMFIwVjBRMFUwcwaia1gbm2pYA5kGSuARE2AIhYKhgZAJSAuEGv@/w8A "K (oK) – Try It Online") Port of [Kevin](https://codegolf.stackexchange.com/a/207458/69200)'s solution. **Explanation:** ``` {(#x)_,/|x,'|x} / the solution { } / lambda taking implicit x |x / reverse x x,' / join each with x | / reverse ,/ / flatten _ / drop ( ) / do this together #x / count x ``` **Extra:** * **-1 byte** thanks to `@ngn` [Answer] # JavaScript (ES6), 43 bytes Using a variant of [Dominic van Essen's approach](https://codegolf.stackexchange.com/a/207460/58563): ``` f=(a,x=a.pop())=>x?[...f(a.reverse()),x]:[] ``` [Try it online!](https://tio.run/##hY/BCoMwDEDv@4ocW8jq1Klz4PYhpYfi6tgQKzrEv@80CtuosB4CTV5ekqcedF92j/a1b@zNOFcVTONYaNHalnFeXMarFEJUTIvODKbrzZTFUZ2lcqVtelsbUds7q5gMESKEGOGIkCCkCr4f5xAEIJdyREQ4Q7s/FoRMeZYjEQmhKYkyT5RPSWJiAiIyTvBp@h7UKtqYRkRO0MZuS8Mcf8/77LaUV9RTeF1bCuXe "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~41~~ 40 bytes If we can take the length of the array as an extra parameter, the following non-recursive algorithm is shorter: ``` n=>a=>a.map((_,k)=>a[n+++n%2*(~k-k)>>1]) ``` [Try it online!](https://tio.run/##bY/LDoIwEEX3fsVsTFop75cs4EdIYxoEo2BLxLj017FMSVSgaZpM5syZ25t4iaF6XPunLdW5Hpt8lHkh9HXuoifkxFqqi1JaliX3wYG8W7ulReFzOlZKDqqrnU5dSEMgoaT0GQQMQgYRg5hBwuH3UAquC6VpB0j4E7RbmNINE4OUr0wREjGiCcrSpcz3tCzTDeRChAK06oGjLj0@yzY2IpEhtMwYm4xmaHr/v/rNaNozutJM6VaTWxo@fgA "JavaScript (Node.js) – Try It Online") [Answer] # GNU sed (`-E`), 54 bytes ``` :l;s/(\w+, )(.* )(\w+.*)\]/\2\]\1\3/;tl;s/\]//;s/$/\]/ ``` This assumes the array is passed over stdin as text in exactly the same format as in the problem statement (in particular, whitespace is important). ## Explanation/Example Let's consider the input `[1, 2, 3, 4, 5, 6]` and look at the script statement-by-statement. 1. `:l`: Create a label called `l` to branch to later. 2. `s/(\w+, )(.* )(\w+.*)\]/\2\]\1\3/`: `[1, 2, 3, 4, 5, 6]` -> `[2, 3, 4, 5, ]1, 6`. 3. `tl`: did the last `s` command do something? Yes, so branch to `l`. 4. `s/(\w+, )(.* )(\w+.*)\]/\2\]\1\3/`: `[2, 3, 4, 5, ]1, 6` -> `[3, 4, ]2, 5, 1, 6`. 5. `tl`: did the last `s` command do something? Yes, so branch to `l`. 6. `s/(\w+, )(.* )(\w+.*)\]/\2\]\1\3/`: pattern doesn't match! 7. `tl`: did the last `s` command do something? No, so don't branch. 8. `s/\]//`: `[3, 4, ]2, 5, 1, 6` -> `[3, 4, 2, 5, 1, 6`. 9. `s/$/\]/`: `[3, 4, 2, 5, 1, 6` -> `[3, 4, 2, 5, 1, 6]`. Note that this works for arrays of text consisting of alphanumeric characters or underscores, not just positive integers. [Try it online!](https://tio.run/##K05N0U3PK/3/3yrHulhfI6ZcW0dBU0NPC0gA2XpamjGx@jFGMbExhjHG@tYlIEVAEX0gpQJi/P8fbaijYKSjYKyjYKKjYKqjYBbLhSGko2AOFLUEUmA@UAKiwgQsZwHkGkB0QYRBJJAf@y@/oCQzP6/4v64rAA "sed – Try It Online") [Answer] # APL+WIN, 40 bytes Prompts for input of a vector if indices: ``` (,⊖⍉(2,n)⍴(n↑(-n)↓m),⌽(-n←⌈.5×⍴m)↑m←⎕)~0 ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r6Dzqmvaot1PDSCdP81HvFo28R20TNXSB7LbJuZo6j3r2AjlA5Y96OvRMD08HqsgFSk3MBQn1TdWsM/gPNOZ/GpehgpGCsYKJgqmCGRcKT8EcyLdUMAeyjRVA4iZAMQsFQwOwMpAAEAPZj3rXcHEBAA "APL (Dyalog Classic) – Try It Online") # A simpler approach, 26 bytes ``` m[(-⍴m)↑,⌽⍉n,[.1]⌽n←⍳⍴m←⎕] ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/7nRmvoPurdkqv5qG2izqOevY96O/N0ovUMY4HsPKCyR72bQdIgVt/U2P9APf/TuAwVjBSMFUwUTBXMuFB4CuZAvqWCOZBtrAASNwGKWSgYGoCVgQSAGMh@1LuGiwsA "APL (Dyalog Classic) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Looking through the rest of the solutions after posting this, I feel like I must be missing something. ``` ÊÆÔvÃÔ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysbUdsPU&input=WzEsIDIsIDMsIDQsIDUsIDZd) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysbUdsPU&input=WwpbMSwgMiwgMywgNCwgNSwgNl0KWzEsIDIsIDMsIDQsIDUsIDYsIDddCls5LCA3LCA1LCAzLCAxLCAyLCA0LCA2LCA4LCAxMF0KWzEsIDEsIDIsIDEsIDJdCltdCl0tbVI) JavaScript "translation": ``` U=>[...Array(U.length)].map(_=>U.reverse().shift()).reverse() ``` ``` ÊÆÔvÃÔ :Implicit input of array U Ê :Length Æ :Map range Ô : Reverse U v : Remove and return first element à :End map Ô :Reverse ``` Mapping the original array *would* be one byte shorter but, as both methods used in the map modify that array, it wouldn't work. [Answer] # x86-16 machine code, ~~21~~ 20 bytes **Binary:** ``` 00000000: 8bde 03f1 4e03 f94f fda4 e201 c38a 0743 ....N..O.......C 00000010: aae2 f6c3 .... ``` **Listing:** ``` 8B DE MOV BX, SI ; BX = beginning of input array 03 F1 ADD SI, CX ; SI = end of input array 4E DEC SI ; adjust to last element 03 F9 ADD DI, CX ; DI = end of output array 4F DEC DI ; adjust to last element FD STD ; set direction flag to descend MILKLAST: A4 MOVSB ; write end of input array value to output array E2 01 LOOP MILKFIRST ; if not end of array, move first value C3 RET ; otherwise, return to caller MILKFIRST: 8A 07 MOV AL, BYTE PTR[BX] ; AL = start of input array value 43 INC BX ; increment pointer AA STOSB ; write to output array E2 F6 LOOP MILKLAST ; loop until end of array C3 RET ; return to caller ``` Callable function, input array in `[SI]`, length in `CX`. Output array to buffer at `[DI]`. **Tests using DOS DEBUG:** [![enter image description here](https://i.stack.imgur.com/Ih2Nd.png)](https://i.stack.imgur.com/Ih2Nd.png) [![enter image description here](https://i.stack.imgur.com/wOjum.png)](https://i.stack.imgur.com/wOjum.png) [![enter image description here](https://i.stack.imgur.com/k2RfM.png)](https://i.stack.imgur.com/k2RfM.png) [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ↓L¹Σze↔¹ ``` [Try it online!](https://tio.run/##yygtzv7//1HbZJ9DO88trkp91Dbl0M7///9HG@oY6hiBcCwA "Husk – Try It Online") ``` ↓L¹Σze↔¹ z Zip ↔¹ the list with its reverse e into a list of 2 elements Σ Flatten it ↓ Drop L¹ the first n elements ``` [Answer] # [Io](http://iolanguage.org/), 53 bytes Port of @Neil's Charcoal answer. ``` method(x,x map(i,v,x at(if(i%2>0,i,-i-1)>>1))reverse) ``` [Try it online!](https://tio.run/##DcZNCoAgEAbQq7gJZuAL0n4WQZ6kjZDSgFaYRLe33urJWYOaF7XW5Mt@bvTiVcldJHj@uUISSBpjOwhaaTVbq5mzf3y@PddAUe5CGgY9BoyYmNWV5SjxqB8 "Io – Try It Online") # [Io](http://iolanguage.org/), 68 bytes Port of @DominicvanEssen's answer. ``` f :=method(x,if(x size>0,list(x pop,f(x reverse))reverse flatten,x)) ``` [Try it online!](https://tio.run/##LYrNCoMwEAZfJccsfAfr30Fo30VwgwsxCclSgi@fVvE2M4zE1pxZ3gfrHjdbIc5WU@TkTwcvRf@WYsJVM385FyZ6wDi/qnJAJWrO3vcLPQaMmDATmZQlqA/tBw "Io – Try It Online") [Answer] # [Dyalog APL](https://www.dyalog.com/), 28 bytes ``` {⍵≡⍬:⍬⋄0~⍨(∇¯1↓1↓⍵),¯2↑1⌽⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHv1kedCx/1rrEC4kfdLQZ1j3pXaDzqaD@03vBR22QQBirR1Dm03uhR20TDRz17Qah3a@3/R31TPf0ftU0w4EoDkuQbxAU0CGhAmoKhgpGCsYKJgqmCGTYxBXO4qKWCOVDEGCxrApSxUDA0QNICEgZiuAjQQf8B "APL (Dyalog Classic) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 102 bytes ``` IEnumerable<int>f(int[]o)=>o.Length==0?new int[0]:o.Length==1?o:f(o[1..^1]).Concat(new[]{o[0],o[^1]}); ``` [Try it online!](https://tio.run/##fY89a8MwEIbn6lccpoMEirDb9CuunaF0aMmWoYNQwTVyIkglkNR2MPrt7tkmdEgoiIO759FxbxsWbTDD8PJsvz61bz4O@tHYWHcUq1SOVbUTG213cV9V@drqHxhBrlZ/42LtVh11shDivVBMPDnbNpGiK1Xv0OVOIkisHL4bD1GHGKCCiUNPLo5LsYGCwxWHaw5LDjccbiHx/wUOdyfOAw4nitrsLyfzHtv83MZZGusJTSSVpHNeN@0e6PF@xHMORjAABg7uoMWbN1FvjNX0MpM93UZv7E68OmNpxgHf@IWxpGBRw1mho7OCTsZKkoZf "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 34 bytes ``` ÷(!½;|")!2%[!1>[$]. ,]{!|$(2|. ,)' ``` [Try it online!](https://tio.run/##y05N////8HYNxUN7rWuUNBWNVKMVDe2iVWL1FHRiqxVrVDSMaoBMTfX//6MNdRSMdIxjAQ "Keg – Try It Online") +5 due to bug fix [Answer] # [Clojure](https://clojure.org/), 40 bytes ``` #(drop(count %)(mapcat vector(rseq %)%)) ``` [Try it online!](https://tio.run/##bY/LCsIwEEX3/YoBKUwggn1Zi@CPhCxKmoJSmxpT6d/X6TQ73STcc89MiBncY/Z2xc720K8H7Lyb0Lh5DJAKfLaTaQN8rAnOo3/bF9FUiFUk2LktqgVUojIJuYRCQimhknDWcD3eQO0gZ5Zt@NeUUEe5ZFxxf2a/Jr@hi2nBKOdBqi8UT3Hyz04WGnb4zV3Zzjizp9iQE7FOtAac/H0MwwjYwyLot18 "Clojure – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` f@a___:=a f[a_,b__,c_]:=##&[f@b,a,c] ``` [Try it online!](https://tio.run/##VYuxCoMwFEX3/EbA6RZqtbUVLO8ThI4hPJ6hoQ46SDbJt8eEdulwh3PuvYuEz3uRMDtJyZMwcz@I8kYYEzMc237QujKeJgicTS8nqxm3eQ1Gn56eSNvK0q72Ghc0aHHFLeIP0RXxQJehQSnaLO@oz99hMTkFfs@oYjoA "Wolfram Language (Mathematica) – Try It Online") Boring, but less boring approaches seem to be more verbose. Returns a `Sequence` containing the deck. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ↔;?zcḍt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFGv7quSHO3pL/v@PNtQx0jHWMdEx1THTMY/9HwUA "Brachylog – Try It Online") ### Explanation Same idea as [Kevin's 05AB1E answer](https://codegolf.stackexchange.com/a/207458/16766) (the first one). Suppose the input list is `[1,2,3,4,5]`: ``` ↔ Reverse [5,4,3,2,1] ;? Pair with the input again [[5,4,3,2,1],[1,2,3,4,5]] z Zip [[5,1],[4,2],[3,3],[2,4],[1,5]] c Concatenate sublists [5,1,4,2,3,3,2,4,1,5] ḍ Split into two halves [[5,1,4,2,3],[3,2,4,1,5]] t Take the second half [3,2,4,1,5] ``` ]
[Question] [ As of ECMAScript 2015, JavaScript has [33 reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), such as `break`, `const` and `new`, as well as [10 future reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Future_reserved_keywords), such as `let` and `await`. Your task is to chain together the largest number of consecutive1 distinct reserved keywords2 while writing functional JavaScript code3. 1. Consecutive reserved keywords - reserved keywords that are separated only by whitespace and/or parentheses and/or curly braces. 2. Reserved keywords - any [reserved or future reserved keywords as of ECMAScript 2015](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords). Reserved keywords from older standards are excluded, a full list of allowed keywords is given below. 3. Functional code - your code should run (state your runtime, if necessary), eventually halt, and not throw any runtime errors. If your code needs a specific runtime, the used reserved keywords must not be no-ops in the given environment. ## List of reserved keywords ``` await break case catch class const continue debugger default delete do else enum export extends finally for function if implements import in instanceof interface let new package private protected public return static super switch this throw try typeof var void while with yield ``` ## Scoring & examples Your score will be equal to the largest number of consecutive distinct reserved keywords. In the case of equal scores, shortest source code in bytes wins. Commented sections and strings don't count towards reserved keywords, but count towards byte count. ``` // score: 3 if (true) 0; else throw function() {} ^------------------^ // score: 2 let foo = typeof typeof void typeof void 0; ^---------^ // score: 0 /* typeof default debugger */ // score: 0, doesn't halt or debugger is no-op, depending on the environment debugger; ``` [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # 43 words, 603 bytes Uhm, is this a loophole? I have no idea how the hell this is legal JS, but it works and it uses every single keyword. ``` new (class await { break(){} case(){} catch(){} const(){} continue(){} debugger(){} default(){} delete(){} do(){} else(){} enum(){} export(){} extends(){} finally(){} for(){} function(){} if(){} implements(){} import(){} in(){} instanceof(){} interface(){} let(){} package(){} private(){} protected(){} public(){} return(){} static(){} super(){} switch(){} this(){} throw(){} try(){} typeof(){} var(){} void(){} while(){} with(){} yield(){} }) ``` [Answer] # 37 words ``` if (void this) { do { with (protected) for (public in private) typeof static instanceof new (function implements() { var let try { throw (class extends {} {}) } catch (package) { yield } finally { debugger } return })() continue break } while (interface) } else { switch (delete await) { default : 42 } } ``` Keywords not used: * `case` requires `:` * `const` requires `=` * `export` requires strict mode * `import` requires strict mode * `super` requires `constructor` [Answer] # 43 words, ~~302~~ 299 bytes ``` switch(void function(){for(const interface in public)do with(package)try{break}catch(private){if(typeof this)throw yield static instanceof new class extends await{case(){return}super(){debugger}import(){}export(){}enum(){}} else continue}finally{delete let}while(protected)var implements}){default:} ``` [Answer] # ~~21~~ ~~24~~ 26 words, 185 bytes *+~~1~~ 2 words thanks to Arnauld, and +1 to 12Me21!* ``` void(function(){do{with({})if(typeof true in this)throw{}instanceof new(class extends{}{}) else return delete{} try{break}finally{yield} continue }while(false)})() switch({}){case{}:{}} ``` Assuming I understood the challenge, this scores 24 words. The words without parentheses, brackets, and whitespace: ``` void function do with if typeof true in this throw instanceof new class extends else return delete try break finally yield continue while false switch case ``` ### 24 words, 177 bytes Without "true" and "false", which are apparently not keywords according to the question. ``` void(function(){do{with({})if(typeof{}in this)throw{}instanceof new(class extends{}{}) else return{} try{break}finally{yield} continue }while(delete{})})() switch({}){case{}:{}} ``` Words: ``` void function do with if typeof in this throw instanceof new class extends else return try break finally yield continue while delete switch case ``` [Answer] # ~~38~~ 39 ``` class await {} class g extends await { constructor() { super() } } switch ({}) { case function(){ for (let in public) do with(package){ try{break}catch(private){ if(typeof this) throw static instanceof new (class extends await {}) else{continue}}finally{debugger} }while(void protected) var implements return yield delete interface const a=0 }: } ``` words from "super" to "const" Golfed version: ``` class e{}class g extends e{constructor(){super()}}switch({}){case function(){for(let in public)do with(package)try{break}catch(private){if(typeof this)throw static instanceof new(class extends await{}) else{continue}}finally{debugger}while(void protected) var implements return yield delete interface const a=0}:} ``` [Answer] # 21 words (not sure about `let` and `await`) ``` var await=String, let=String; switch (await) { case void typeof new await instanceof let in (function() {do{try{return this if((class extends{}{})){}else{break}}finally{(delete {})}}while(false)})():break; } ``` [Answer] # ~~14~~ ~~15~~ 16 Words with no brackets or newline ``` !function(){if(0);else do throw yield new public in void typeof this instanceof class await extends function async(){}{};while(0)} ``` Thank Bergi for +1 [Answer] # 43 words, 300 bytes ``` with(this)try{let protected}catch(package){if(delete yield)for(const interface in typeof public)do{throw implements instanceof private}while(static)else debugger}finally{switch(void new class extends function(){return}{export(){var await}import(){break}super(){continue}enum(){}case(){}}){default:0}} ``` More readably: ``` with(this) try { let protected } catch(package){ if(delete yield) for(const interface in typeof public) do { throw implements instanceof private } while(static) else debugger } finally { switch( void new class extends function(){return} { export(){var await} import(){break} super(){continue} enum(){} case(){} } ){ default:0 } } ``` I had to use the "reserved word as method name" to deal with * `case` (since I had already used `default` with my `swtich`), * `export` and `import` (since module-mode is always strict, which disqualifies `with`) * `super` (since it must be followed by a property access or placed in a `constructor` function), and * `enum` (which can never be used at all, being a reserved word with no grammatically-valid use) [Answer] # 28 Words without brackets, 234 Bytes Putting identifier names as method definition names was too obvious ([for me at least](https://stackoverflow.com/questions/49544859/how-many-reserved-keywords-can-you-put-together-that-could-be-in-production-code#comment86097608_49544859)), so I was looking for the longest consecutive distinct sequence of reserved words and whitespace in a code snippet. I hope dead code after a `return` doesn't count as a loophole, but the code is still runnable if the used identifiers are declared. ``` function*_(){implements:{ let private var public return yield typeof static delete protected throw new interface in package break implements debugger void this instanceof class await extends function async(){}{} do continue while(0)}} ``` This exploits the fact that some of the future reserved keywords are only [considered invalid in ES5.1's strict mode](http://ecma-international.org/ecma-262/5.1/#sec-7.6.1.2) (apparently because engines didn't bother to block all of ES3's future reserved words so there was too much code using them out there on the web). Similarly, the `async` and `await` tokens introduced in ES8 are only considered keywords in strict mode. ]
[Question] [ Your task is to output a representation of the legendary tree of life, [Yggdrasil](http://en.wikipedia.org/wiki/Yggdrasil). You must write a program whose output is exactly that : ``` /\ /**\ /****\ /******\ /******\ /********\ /**********\ /************\ /**************\ /************\ /**************\ /****************\ /******************\ /********************\ /**********************\ /******************\ /********************\ /**********************\ /************************\ /**************************\ /****************************\ /******************************\ /************************\ /**************************\ /****************************\ /******************************\ /********************************\ /**********************************\ /************************************\ /**************************************\ /******************************\ /********************************\ /**********************************\ /************************************\ /**************************************\ /****************************************\ /******************************************\ /********************************************\ /**********************************************\ /************************************\ /**************************************\ /****************************************\ /******************************************\ /********************************************\ /**********************************************\ /************************************************\ /**************************************************\ /****************************************************\ /******************************************************\ /******************************************\ /********************************************\ /**********************************************\ /************************************************\ /**************************************************\ /****************************************************\ /******************************************************\ /********************************************************\ /**********************************************************\ /************************************************************\ /**************************************************************\ /************************************************\ /**************************************************\ /****************************************************\ /******************************************************\ /********************************************************\ /**********************************************************\ /************************************************************\ /**************************************************************\ /****************************************************************\ /******************************************************************\ /********************************************************************\ /**********************************************************************\ /******************************************************\ /********************************************************\ /**********************************************************\ /************************************************************\ /**************************************************************\ /****************************************************************\ /******************************************************************\ /********************************************************************\ /**********************************************************************\ /************************************************************************\ /**************************************************************************\ /****************************************************************************\ /******************************************************************************\ |--------| |--------| |--------| |--------| |--------| |--------| |--------| |--------| |--------| |--------| |--------| |________| ``` There is no trailing whitespace. The final newline may be omitted. To make checking easier, here are the md5 sums of the expected output: * `374899e56bc854d04639c43120642e37` - No newline at end. * `03afb81d960b8e130fe2f9e0906f0482` - Newline at end Standard loopholes apply. This is code-golf, so the smallest entry in bytes win! [Answer] # [Haml](http://haml.info/) & [Sass](http://sass-lang.com/guide) # 37 + 277 = 314 **Haml:** ``` %link(rel="stylesheet" href="s") %pre ``` **Sass:** ``` pre:after{$l:"";@for$k from0 to10{@for$i from0 to4+$k{@for$j from0 to40-($k*6+$i*2)/2{$l:$l+' ';}$l:$l+'/';@for$j from0 to$k*6+$i*2{$l:$l+'*';}$l:$l+"\\\a ";}}@for$i from0 to12{@for$j from0 to35{$l:$l+" ";}@if$i<11{$l:$l+"|--------|\a ";}@else{$l:$l+"|________|";}}content:$l;} ``` \*Sass allows control directives, concatenation, and variable dereference. All of which are useful when styling, but verbose while golfing. --- *gets generated into:* **HTML:** ``` <link rel="stylesheet" href="s" /><pre></pre> ``` **CSS:** ``` pre:after { content: " /\\\a /**\\\a /****\\\a /******\\\a /******\\\a /********\\\a /**********\\\a /************\\\a /**************\\\a /************\\\a /**************\\\a /****************\\\a /******************\\\a /********************\\\a /**********************\\\a /******************\\\a /********************\\\a /**********************\\\a /************************\\\a /**************************\\\a /****************************\\\a /******************************\\\a /************************\\\a /**************************\\\a /****************************\\\a /******************************\\\a /********************************\\\a /**********************************\\\a /************************************\\\a /**************************************\\\a /******************************\\\a /********************************\\\a /**********************************\\\a /************************************\\\a /**************************************\\\a /****************************** **********\\\a /******************************************\\\a /********************************************\\\a /**********************************************\\\a /************************************\\\a /**************************************\\\a /****************************************\\\a /******************************************\\\a /********************************************\\\a /**********************************************\\\a /************************************************\\\a /**************************************************\\\a /****************************************************\\\a /******************************************************\\\a /******************************************\\\a /********************************** **********\\\a /**********************************************\\\a /************************************************\\\a /**************************************************\\\a /****************************************************\\\a /******************************************************\\\a /********************************************************\\\a /**********************************************************\\\a /************************************************************\\\a /**************************************************************\\\a /************************************************\\\a /**************************************************\\\a /****************************************************\\\a /******************************************************\\\a /***************************************************** ***\\\a /**********************************************************\\\a /************************************************************\\\a /**************************************************************\\\a /****************************************************************\\\a /******************************************************************\\\a /********************************************************************\\\a /**********************************************************************\\\a /******************************************************\\\a /********************************************************\\\a /**********************************************************\\\a /************************************************************\\\a /**************************************************************\\\a /****************************************************************\\\a /********* *********************************************************\\\a /********************************************************************\\\a /**********************************************************************\\\a /************************************************************************\\\a /**************************************************************************\\\a /****************************************************************************\\\a /******************************************************************************\\\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |--------|\a |________|"; } ``` --- *the resulting [page](http://luxe.github.io/code-golf/Yggdrasil/)* [Answer] # Golfscript, ~~84~~ ~~[77](http://golfscript.apphb.com/?c=MTAsey40KjQrLFwzKj57LjM5XC0nICcqJy8nQDIqJyonKidcXCdufS99LzEyLHsnICczNSonfCdAJ18tJ1wxMTxbPV04Kid8JytufS8%3D)~~ ~~[76](http://golfscript.apphb.com/?c=MTAsey40KjQrLFwzKj57LjM5XC0nICcqJy8nQDIqJyonKidcXCdufS99LzEyLHsnICczNSonfCdAMTE8J18tJ1s9XTgqJ3wnK259Lw%3D%3D)~~ ~~[75](http://golfscript.apphb.com/?c=MTAsey40KjQrLFwzKj57LjM5XC0nICcqJy8nQDIqJyonKidcXCdufS99LzEyLHsnICczNSonfCdAMTE8J18tJ1s9XTgqMSQrbn0v)~~ [72](http://golfscript.apphb.com/?c=MTAsey4pNCosXDMqPnsuMzlcLScgJyonLydAMionKicqJ1wKJ30vfS8xMix7JyAnMzUqJ3wnQDExPCdfLScxLz04KjEkbn0v) characters Different approach from [Howard's](https://codegolf.stackexchange.com/a/36442/4800). Click on the character count to try it. ``` 10,{.)4*,\3*>{.39\-' '*'/'@2*'*'*'\ '}/}/12,{' '35*'|'@11<'_-'1/=8*1$n}/ ``` Thanks to Howard for saving 3 characters! **Explanation**: This is more or less a straightforward port of [my Python solution](https://codegolf.stackexchange.com/a/36439/4800). Taking some expressive liberties (using named variables instead of keeping track of stack positions, and `print` is really keeping things on the stack, not printing): ``` 10,{...}/ # for i in range(10): . # x = i )4*, # Y = range((i+1)*4) \3* # x *= 3 > # Y = Y[x:] # y is now range(3*i, (i+1)*4) {...}/ # for j in Y: .39\- # q = 39 - j ' '* # print ' '*q # print right number of spaces '/' # print '/' @2* # j *= 2 '*'* # print '*'*j '\<NEWLINE>' # print "\\\n" 12,{...}/ # for i in range(12): ' '35* # print ' '*35 '|' # print '|' @11< # i = i < 11 '_-'1/= # z = "_-"[i] # pick "-" if i < 11, else pick "_" 8* # print z*8 1$ # print '|' # (copy from earlier in the stack) n # print "\n" ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 62 bytes ``` A,{I4+,{I3*J+_39\-S*'/@2*'**'\N}fJ}fI{35S*'|'-8*'|N++}C*'-/'_* ``` [Try it online!](https://tio.run/##S85KzP3/31Gn2tNEG0gYa3lpxxtbxugGa6nrOxhpqWtpqcf41aZ51aZ5VhubAkVr1HUtgKSftnats5a6rr56vNb//wA "CJam – Try It Online") ### How it works ``` A, " Push [ 0 … 9 ]. "; { " For each I in that array: "; I4+, " Push [ 0 … I + 3 ]. "; { " For each J in that array: "; I3*J+_ " Push K := 3 * I + J twice. "; 39\-S* " Push a string consisting of 39 - K spaces. "; '/ " Push a slash. "; @2*'** " Push a string consisting of 2 * K asterisks. "; '\N " Push a backslash and a linefeed. "; }fJ " "; }fI " "; { " Do the following 12 times: "; 35S* " Push a string consisting of 35 spaces. "; '| " Push a vertical bar. "; '-8*'|++ " Push the string '--------|\n'. "; }C* " "; '-/'_* " Replace the hyphen-minus signs of the last string with underscores. "; ``` [Answer] ### GolfScript, 79 characters ``` 10,{:^4+,{2*^6*+'*'*.,2/~40+' '*'/'@'\ '}/}/[' '35*]12*'|--------| '*'||''_'8** ``` Try the code [here](http://golfscript.apphb.com/?c=MTAsezpeNCssezIqXjYqKycqJyouLDIvfjQwKycgJyonLydAJ1wKJ30vfS9bJyAnMzUqXTEyKid8LS0tLS0tLS18CicqJ3x8JydfJzgqKg%3D%3D&run=true). Note that the line breaks aren't optional in this code [Answer] # Python, ~~148~~ ~~129~~ ~~126~~ 121 characters ``` R=range for i in R(10): for j in R(i*3,4+i*4):print' '*(39-j)+'/'+'**'*j+'\\' for c in'-'*11+'_':print' '*35+'|'+c*8+'|' ``` Thanks to [Falko](https://codegolf.stackexchange.com/questions/36431/output-the-legendary-yggdrasil/36439?noredirect=1#comment81623_36439) for saving 3 characters and to [flornquake](https://codegolf.stackexchange.com/questions/36431/output-the-legendary-yggdrasil/36439?noredirect=1#comment81902_36439) for brilliantly saving another 5! [Answer] # Bash, ~~236 197~~ 193 10 bytes of code + 1-byte filename + 182-byte data file = 193 bytes total ``` zcat y 2>j ``` ## Explanation `y` is a file containing the Yggdrasil, without a trailing new line, compressed with the [zopfli](https://code.google.com/p/zopfli/) algorithm (invoked as `zopfli --i64`) and then with the last 8 bytes removed. zopfli is compatible with gzip, so I can decompress the file with standard Bash utilities designed for gzip. The size of the data file is 182 bytes (229 bytes when normal gzip is used). The size of the original Yggdrasil, without the trailing new line, is 5876 bytes. The removal of the last 8 bytes causes error messages, which are suppressed by sending standard error to a file called `j`. If `j` exists, it will be overwritten. The base64 of `y` is (use `base64 -d` to obtain the original file): ``` H4sIAAAAAAACA+3SMQoCURDA0N5TWC+IFxK8yD/8Nul9hfDRnamT6J+du83zdUPwOACNNDb0+3Bs tMPhSscDvusHgM9wIcUNclL+5r/luJXkmlh5rM3r8txkMdVNcEn1Nc2a1AU72XWz3Xd91r5z7eZD AQKQgAI0PDFf8xJfExpQgQhkpAIdz8ytzK3AQMg6UMIQpLQELU/NQc5B/thBegtqHpOc16jHOX/v x1mPZg19MfrdrBM= ``` And the md5sum is: ``` 4a049a80241160cdde0a3cbca323b7f2 ``` [Answer] # C, 169 ``` i;j;p(a,b){while(b--)putchar(a);}main(){for(;i++<10;)for(j=i*3-4;++j<i*4;p(32,39-j),p(47,1),p(42,j*2),puts("\\"));for(++i;i--;p(32,35),p(124,1),p(i?45:95,8),puts("|"));} ``` Ungolfed (and slightly disentangled): ``` int i; int j; void p(a,b) { while (b--) putchar(a); } void main() { for (;i++<10;) { for (j=i*3-4;++j<i*4;) { p(32,39-j); p(47,1); p(42,j*2); puts("\\"); } } for (++i;i--;) { p(32,35); p(124,1); p(i?45:95,8); puts("|"); } } ``` [Answer] ## Ruby - 100 ``` puts (0..21).map{|i|i>9??\ *35+?|+(i>20??_:?-)*8+?|:(0..i+3).map{|y|?\ *(39-z=y+3*i)+?/+?**z*2+?\\}} ``` Puts auto-flattens, so we can collect all the lines even in nested arrays. Needs Ruby 1.9 Try at [ideone](http://ideone.com/7FvXVA) [Answer] # PowerShell ~~104~~ 101 ``` 0..9|%{(3*$_)..(3+$_*4)|%{" "*(39-$_)+"/"+"*"*2*$_+"\"}};0..11|%{" "*35+"|"+("-","_")[$_-eq11]*8+"|"} ``` [Answer] ## C# ~~258~~ 234bytes Thanks to some annoymous user for the suggested edits making good use of the String.PadLeft method! ``` using System;class G{static void Main(){Action<string>p=Console.WriteLine;int i=0,j;for(;i++<10;)for(j=i*3-3;j++<i*4;)p("/".PadLeft(41-j)+"\\".PadLeft(2*j-1,'*'));while(i-->0)p("|--------|".PadLeft(45));p("|________|".PadLeft(45));}} ``` The code is pretty simple, not much left to golf. Formatted code: ``` using System; class G { static void Main() { Action<string> p = Console.WriteLine; int i = 0, j; for(; i++ < 10 ;) for(j = i*3 - 3; j++ < i*4;) p("/".PadLeft(41 - j) + "\\".PadLeft(2*j - 1,'*')); while(i-- > 0) p("|--------|".PadLeft(45)); p("|________|".PadLeft(45)); } } ``` [Answer] ## J, ~~98 88 84~~ 75 ``` (85 11 1#3 4$' /*\ |-| |_|')#"1~(39&-,1,+:,1:)"0(12$4),~85(-4&+#-:*>:)&i.10 ``` [Answer] # Perl, 127 ``` for$i(0..9){for$j($i*3..3+$i*4){print" "x(39-$j),"/","*"x($j*2),"\\\n";}}for$i(0..11){print" "x35,"|",($i>10?"_":"-")x8,"|\n";} ``` ### Ungolfed: ``` for $i (0..9) { for $j ($i*3..3+$i*4) { print " "x(39-$j) , "/" , "*"x($j*2) , "\\\n"; } } for $i (0..11) { print " "x35 , "|" , ($i>10?"_":"-")x8 , "|\n"; } ``` [Answer] # Ruby - ~~139~~ ~~129~~ ~~126~~ ~~123~~ 121 Hoisted "puts" outside of array creation (suggestion from bitpwner). ``` puts (0..9).map{|i|(i*3...(i+1)*4).map{|j|"/#{'**'*j}\\".rjust(41+j,' ')}}+["%45s"%'|--------|']*11<<'%45s'%'|________|' ``` Ungolfed ("puts" unhoisted): ``` # print fill patterns from the intervals # [0..3, 3..7, 6..11, 9..15, 12..19, 15..23, 18..27, 21..31, 24..35, 27..39] # centered on columns 81-82 (0..9).each { |i| (i*3...(i+1)*4).each { |j| # x...y vs x..y-1 saves a char puts "/#{'**'*j}\\".rjust(41+j,' ') } } # print the stump puts ("%45s\n" % '|--------|') * 11 puts '%45s' % '|________|' ``` [Answer] # PHP 223 202 181 160 156 Edit I figured out how to alias a function with a variable and was able to chop off some more characters. That `str_repeat` function was really verbose Edit 2: Thanks everyone for the suggestions! Golfed: ``` <?$s=str_repeat;for($i=-1;$i++<9;)for($j=$i*3;$j<4+$i*4;)echo$s(' ',39-$j).'/'.$s('**',$j++)."\\ ";for($i=12;$i--;)echo$s(' ',35),'|'.$s($i?'-':'_',8)."| "; ``` Readable: ``` <? $s=str_repeat; for($i=-1;$i++<9;) { for($j=$i*3;$j<4+$i*4;) { echo$s(' ',39-$j).'/'.$s('**',$j++)."\\ "; } } for($i=12;$i--;) { echo$s(' ',35),'|'.$s($i?'-':'_',8)."| "; } ``` Output: <http://brobin.me/yggdrasil.php> [Answer] # Delphi 429 Will try to improve later. Golfed ``` uses strutils,SysUtils,Classes;const a='|----';b='|____';c:array [0..9,0..1]of int32=((0,3),(3,7),(6,11),(9,15),(12,19),(15,23),(18,27),(21,31),(24,35),(27,39));var t:TStrings;i,j:integer;begin t:=tstringlist.Create;for I:=0to 9do for J:=c[i,0]to c[i,1]do t.Add('/'+StringOfChar('*',j));for I:=0to 10do t.Add(a);t.Add(b);for I:=0to t.Count-1do t[i]:=t[i].PadLeft(40)+ReverseString(t[i]).Replace('/','\');write(T.TEXT);readln;end. ``` ungolfed ``` uses strutils,SysUtils,Classes; const a='|----'; b='|____'; c:array [0..9,0..1]of int32=((0,3),(3,7),(6,11),(9,15),(12,19),(15,23),(18,27),(21,31),(24,35),(27,39)); var t:TStrings; i,j:integer; begin t:=tstringlist.Create; for I:=0to 9do for J:=c[i,0]to c[i,1]do t.Add('/'+StringOfChar('*',j)); for I:=0to 10do t.Add(a); t.Add(b); for I:=0to t.Count-1do t[i]:=t[i].PadLeft(40)+ReverseString(t[i]).Replace('/','\'); write(T.TEXT); readln; end. ``` [Answer] ## Javascript, 288 281 Chrome hides duplicated `console.log`s, use IE instead. ``` function t(w){s="";for(i=0;i++<39-w;)s+=" ";s+="/";for(i=0;i++<w*2;)s+="*";return s+"\\"}function r(l){s="";for(i=0;i++<36;)s+=" ";s+="|";for(i=0;i++<8;)s+=l;return s+"|"}w=0;c=console;for(h=0;h++<10;){for(j=0;j++<3+h;)c.log(t(w++));w-=h}for(j=0;j++<11;)c.log(r('-'));c.log(r('_')) ``` Ungolfed: ``` function t(w) { s=""; for(i=0;i++<39-w;) s+=" "; s+="/"; for(i=0;i++<w*2;) s+="*"; return s+"\\" } function r(l) { s=""; for(i=0;i++<36;) s+=" "; s+="|"; for(i=0;i++<8;) s+=l; return s+"|" } w=0; c=console; for(h=0;h++<10;) { for(j=0;j++<3+h;) c.log(t(w++)); w-=h; } for(j=0;j++<11;) c.log(r('-')); c.log(r('_')) ``` [Answer] ## JavaScript (console.log), ~~168~~ 166 (Whitespace for readability only) ``` for(i=c=0;i<11;i++) for(j=0;j<4+i&!c;j++) l=i*13+j, a=Array(n=i-10?3*i+j+1:5).join("*-_"[k=(l>129)+(c=l==141)]), console.log(Array(41-n).join(" ")+'/||'[k]+a+a+'\\||'[k]) ``` [Answer] # C (219) Thanks to everyone for the golfing tips -- managed to get it down to 219. Don't think it'll go much lower. ``` w,W,s,S,i,r;main(){char T[78];memset(T,42,78);for(r=4,s=39;r<14;++r,s-=3,w+=6)for(i=0,S=s,W=w;i<r;++i,W+=2,--S)printf("%*s/%.*s\\\n",S,"",W,T);for(i=0;i<11;i++)printf("%35s|--------|\n","");printf("%35s|________|","");} ``` Required includes: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> ``` [Answer] # Haskell, ~~153~~ 148 Straight-forward, no tricks, just plain golfing: ``` (a:b:c)%n=(39-n)&' '++a:(2*n)&b++c n#m=[n..m]++(n+3)#(m+4) (&)=replicate main=putStr$unlines$map("/*\\"%)(take 85$0#3)++map("|-|"%)(11&4)++["|_|"%4] ``` The `%` operator draws a single line, its first argument being a `String` of length 3 containing the borders and the fill characters in that line (now assuming exactly 3 `Char`s, saving 5 bytes), the second, an `Int`, specifies half the number of fill characters. Pattern matching, cons-ing and appending is used in combination in order to save bytes by taking care of the "glue" between `Char` and `String`. In this second version, I also made `#` infinite and introduced a `take 85` to make it finite again (no bytes saved, unfortunately). The `#` operator creates the sequence for the `n` argument to `%` required for the tree: `[0..3], [3..7], ...` concatenated. `&` is just an infix shorthand for `replicate`, which occurs three times. The tree is put together in the last line, the newlines are added by `unlines`. [Answer] ## Lua - [164](http://repl.it/XHD) ``` a=' 'for i=0,9 do for j=i*3,3+i*4 do print(a:rep(39-j)..'/'..(('*'):rep(j*2))..'\\')end end for i=0,11 do print(a:rep(35)..'|'..((i>10 and'_'or'-'):rep(8))..'|')end ``` [Answer] **Mathematica ~~191~~ 178** For sure not the best solution: ``` n=Nest; t=Table; ""<> t[ {n[#<>" "&,"",39-i],"/",n[#<>"*"&,"",2i],"\\\n"} , {i,Flatten@t[Range[j+4]-1+3j,{j,0,9}]} ] <> t[ n[#<>" "&,"",35]<>If[i==12,"|________|\n","|--------|\n"] , {i,12} ] ``` Not counting newlines. Mathematica skews the output, as it doesn't take the same width for a whitespace as for "\*" and "/". But the result is correct. [Answer] # Java - 286 My first golf. Golfed: ``` class M{public static void main(String[]args){int i=0,a,f=0;String s="";for(;i++<11;){for(a=i*3-4;++a<i*4;){if(i>10){a=4;if(++f>12)break;}s+=s.format("%"+(40-a)+"s"+(a>0?"%0"+a+"d":"")+"%3$s",f>0?"|":"/",0,f>0?"|":"\\").replace("0",f<1?"**":f>11?"__":"--")+"\n";}}System.out.println(s);}} ``` Ungolfed: ``` class M { public static void main(String[] args) { int i=0,a,f=0; String s = ""; for(;i++<11;){ for(a=i*3-4;++a<i*4;a++){ if(i>10){ a=4; if(++f>12)break; } s+=s.format("%"+(40-a)+"s"+(a>0?"%0"+a+"d":"")+"%3$s",f>0?"|":"/", 0,f>0?"|":"\\").replace("0", f<1?"**":f>11?"__":"--")+"\n"; } } System.out.println(s); } } ``` [Test here](http://ideone.com/zbCHMW) [Answer] # Python 2, 117 ``` j=0 while j<40:j-=j/4;exec(j/3+4)*r"print' '*(39-j)+'/'+'**'*j+'\\';j+=1;" for c in'-'*11+'_':print' '*35+'|'+c*8+'|' ``` --- Other versions I tried include: ``` # 118 for i in range(10):j=i*3;exec(i+4)*r"print' '*(39-j)+'/'+'**'*j+'\\';j+=1;" for c in'-'*11+'_':print' '*35+'|'+c*8+'|' # 118 i=j=4 while j:j=52-3*i;exec"j-=1;print' '*j+'/'+'**'*(39-j)+'\\\\';"*i;i+=1 for c in'-'*11+'_':print' '*35+'|'+c*8+'|' # 118 j=0 for b in'\\'*10:j-=j/4;exec(j/3+4)*"print' '*(39-j)+'/'+'**'*j+b;j+=1;" for c in'-'*11+'_':print' '*35+'|'+c*8+'|' # 119 s=40 while s:s+=10-s/4;exec(52-s)/3*r"s-=1;print' '*s+'/'+'**'*(39-s)+'\\';" for c in'-'*11+'_':print' '*35+'|'+c*8+'|' ``` [Answer] # Powershell, 88 bytes ``` 0..9|%{(3*$_)..(3+$_*4)|%{' '*(39-$_)+"/$('**'*$_)\"}} ,'-'*10+'_'|%{' '*35+"|$($_*8)|"} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~101~~ ~~100~~ ~~99~~ ~~90~~ ~~81~~ 66 bytes ``` jbm+*;-39d++\/*\**2d\\s.e+L*3kb+L4TV11+J*35ds_B"|----";+Js_B"|____ ``` [Try it online!](https://tio.run/##K6gsyfj/PyspV1vLWtfYMkVbO0ZfK0ZLyyglJqZYL1XbR8s4O0nbxyQkzNBQ20vL2DSlON5JqUYXCJSstb3AnHgg@P8fAA) --- Python 3.8 translation: ``` from functools import reduce from operator import add B = lambda G, H: (H, G(H)) r = lambda s: s[::-1] print("\n".join(map(lambda d: " "*(39-d)+"/"+"*"*(2*d)+"\\", reduce(add, map(lambda e: list(map(lambda d: 3*e[0]+d, range(e[1]))), enumerate(map(lambda d: 4+d, range(10)))))))) for N in range(11): print((J:=" "*35)+reduce(add, B(r, "|----"))) print(J+reduce(add, B(r, "|____"))) ``` [Answer] ## Groovy 118 ``` 10.times{(it*3).upto 3+it*4,{println' '*(39-it)+'/'+'*'*it*2+'\\'}};12.times{println' '*35+'|'+(it>10?'_':'-')*8+'|'} ``` [Answer] # C,194 This code is a hot mess and can definitely be golfed more. Still, it was an opportunity to try out a couple of things I've never done before: using a literal for a string of asterisks, and using the width specifier `*` with a string in `printf`. ``` i,j=5,k=5,n; main(){ char d[]={[0 ...77]=42,0}; for(;i<85;i++)k--,j+=!k,k+=(j-1)*!k,n=39-i+(j-5)*(j-4)/2,printf("%*s/%s\\\n",n,"",d+n*2); for(;i<97;i++)printf("%*s|\n",44,i-96?"|--------":"|________"); } ``` [Answer] ## Racket 223 220 211 204 198 Golfed: ``` (for-each display(flatten(let([m make-list])`(,(for*/list([i 10][j(range(* i 3)(* 4(+ 1 i)))])`(,(m(- 39 j)" ")"/",(m j"**")"\\\n")),(for/list([c`(,@(m 11"-")"_")])`(,(m 35" ")"|",(m 8 c)"|\n")))))) ``` Ungolfed: ``` (for-each display (flatten (let([m make-list]) `(,(for*/list([i 10][j(range(* i 3)(* 4(+ 1 i)))]) `(,(m(- 39 j)" ")"/",(m j"**")"\\\n")) ,(for/list([c`(,@(m 11"-")"_")]) `(,(m 35" ")"|",(m 8 c)"|\n")))))) ``` [Answer] # [Assembly (MIPS, SPIM)](https://github.com/TryItOnline/spim), ~~768~~ ~~671~~ ~~659~~ ~~655~~ 654 bytes ``` .text .globl main main: li $8 32 li $9 47 li $t2 42 li $t3 92 li $t4 10 li $t5 42 addi $sp -4 move $4 $sp la $s6 q la $s5 w li $t8 0 li $s0 10 li $t9 0 li $s3 40 li $s2 39 q: sub $s3 $s3 $t8 add $s2 $s2 $t8 addi $t7 $t8 3 addi $t8 1 blt $s0 $t8 e r: sw $0 ($4) blt $t9 $s2 t beq $t9 $s2 y beq $t9 $s3 u beqz $t7 i sb $t2 ($4) p: li $2 4 syscall addi $t9 1 ble $t9 $s3 r move $t9 $0 j $s5 o: addi $t7 -1 bgez $t7 r jr $s6 w: addi $s2 -1 addi $s3 1 j o t: sb $8 ($4) j p y: sb $9 ($4) j p u: sb $t4 1($4) sb $t3 ($4) j p i: sb $t5 ($4) j p e: li $t1 124 li $t3 124 li $t2 45 li $t5 95 li $t7 11 la $s6 a la $s5 o li $s2 35 li $s3 44 j r a: li $2 10 syscall ``` [Try it online!](https://tio.run/##TVHLcoQgELzPV8zBQ3LYLRXMin@jWWpLC@MDNhvz8wZmQHNAu3ugB6bt3I/7fnX6x8H1YabO4Nj2XxA@DZgesxpFSUChvBFwJUqWnEAVkcQiZ1SFanu/e2xnvEgYp2@NmQwUTOt/H7gwqPDFZ2rkwzY/bFSSBMqIShQKlgbssyOdlqtDM6rSYh4cbmQsEq2xgM44ahKYhtVbvTDL8S2T71zzbYOLg04vB9v@MYHPwH7Jvwfb0TzIYOaB@emA3exna0xqrai1PizWOJNAcxjCJGBqzntf/PaH5h4rDGuYGbzSBn8jvyFi4a0HnMA1dJearzLgDBsr6lSerISsSCMiznof69UpaX6TK7AoZcr8gP6pVQpdRXTDokgxtynm6QiwOkKVvsEKbRqazz1Obd//AA "Assembly (MIPS, SPIM) – Try It Online") **Edit:** Saved ~100 bytes by hard coding each character in a register and simply writing to the stack, then abusing the fact that MIPS doesn't have types so implicit word to ascii string is allowed. **Edit 2:** removed duplicate stack alloc. (`addi $sp -4`) Oops! **Edit 3:** in rewrite, accidently made the tree stump 1 character too short. (36 in stead of 35). Fixed. **Edit 4:** -4 bytes by using $8 and $9 instead of $t0 and $t1. they mean the same thing, but $t0 is easier to read. unfortunately, all other t registers are the same length when written nicely ($t2 == $10, but both are 3 characters), so the rest are a wash. I could (in theory) use the remaining 'a' registers (5-7. print syscall uses 4), but afaik the behavior isn't defined when using syscall. -1 Byte by setting t8 to 0 and branching on less than instead of on equal. also required me to reorder the add ops, which unfortunately made the execution time take a whopping 3 opcodes longer. Not the best at MIPS, but after clearing my conscience of this in meta discussion, i'm submitting them. MIPS is not designed for this (no output, no for loops) but it's pretty fun to do this perhaps in spite of that. Unfortunately, I haven't created a commented version for this new solution, but you can view the old version, with full documentation [here](https://tio.run/##dVffb@M2En7XXzGwCnS3SZR4k93D@W6fevfQoi2KboDeQ4EDLdEWN7KoJanY3vb@9r1vhqQsu@lDYpsazs9vvhn5wey@fKkaFRQVvlO@XVGlfG3MZ1rcLope7zvT69nhb7/1i0L5oJ3xT7P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TAPzz8IsdtY/1WNsQ7G7O/jdgTfQAv8Ze0/Q6XBXzxJzPP8jL6@B8bOHs3xHALw8jFo6rnJjgF2k5juBuXuiHZGWVRPDzBYlkcyaU3tIvZc@sZvEp2kvp8sPP3/2Io0@jYXobZb3MvLBgxC74hL9U8RUW53qH3SLwlGksitvxMOOlwj1J06DQADpo0UfWk1Wt4rbP29TyLq9ExZcv/wc) Feel free to take the credit and improve upon this answer if you can beat it - I'm probably missing a few optimizations here and there. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 40 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` A{3+{╷¹╷3×+*×/×}]⁵-*_∔{4×|×]∔{║L»‾◂∔ ××] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIxJXVGRjVCJXVGRjEzJXVGRjBCJXVGRjVCJXUyNTc3JUI5JXUyNTc3JXVGRjEzJUQ3JXVGRjBCKiVENy8lRDcldUZGNUQldUZGM0QldTIwNzUtJXVGRjBBXyV1MjIxNCV1RkY1QiV1RkYxNCVENyU3QyVENyV1RkYzRCV1MjIxNCV1RkY1QiV1MjU1MSV1RkYyQyVCQiV1MjAzRSV1MjVDMiV1MjIxNCUyMCVENyVENyV1RkYzRA__,v=8) ]
[Question] [ ### Background Inspired by Octave's (and, by extension, MATL's) very convenient interpretation of truthy/falsy matrices, Jelly got the Ȧ (Octave-style *all*) atom. Ȧ takes an array as input and returns **1** if the array is non-empty and does not contain the number **0** (integer, float, or complex) **anywhere in the tree structure**; otherwise, it returns **0**. For example, the array **[[]]** is truthy because it is non-empty and contains no zeroes, but **[[0]]** is falsy because it contains a **0** at the innermost level. ### Task In a [programming language](https://codegolf.meta.stackexchange.com/q/2028/12012) of your choice, write a full program or a function that takes a possibly empty, possibly jagged array of *integers* as input and prints or returns a [truthy or falsy](https://codegolf.meta.stackexchange.com/a/2194/12012) value that indicates if Ȧ would return **1** or **0**, respectively. Your submission must abide to the following rules. * The truthy and falsy values **must be consistent for all inputs**, i.e, all arrays for which Ȧ returns **1** must map to the same truthy value, and all arrays for which Ȧ returns **0** must map to the same falsy value. * Since full programs can only take string representations of arrays as input, this is allowed. However, you must use the canocical representation of your language, as returned by `repr` or similar. In particular you cannot assume that the first element of the array will be preceded by a space. * If (and only if) your language cannot represent jagged arrays natively, you may take a string representation of the input, using the canonical syntax of any pre-existing programming language. * If your language has several ways of representing jagged arrays (e.g., lists and tuples), you only have to support one of them. * If your language has a built-in that is itself a valid submission to this challenge, **you may not use it in your answer**. All other built-ins are allowed. * You are encouraged to post answers using both array and string manipulation, even if one is significantly shorter than the other. * All standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. May the shortest code in bytes win! ### Truthy test cases ``` [1] [10] [[]] [[[[1]]]] [[], [1], [1, 2]] [[1], [1, [2]], [1, [2, [3]]]] [[8], [8, [9]], [8, [9, [10]]]] ``` ### Falsy test cases ``` [] [0] [0, -1] [-1, 0] [[[[0]]]] [[0], [1, 2], [3, 4, 5]] [[8], [8, [9]], [8, [9, [1, 0]]]] [-1, 0, 0, 0] ``` [Answer] # Jelly, 3 bytes ``` ṭFẠ ``` `F` flattens the input list. `ṭ` tacks on the original input list as an element, which is falsy if and only if it is empty. `Ạ` then checks if any element in the flattened list, or the original list itself, is falsy. --- (Original answer) ``` FẠ^Ṇ ``` Thanks to Dennis for encouraging finding a solution matching his. `FẠ` gives 0 if the input contains a falsy value at any depth, else 1. This is what `Ȧ` does, except for empty lists. `Ṇ` gives 1 if the input is a falsy value, else 0. The only falsy list is the empty list. XOR-ing the two gives the answer. --- ``` F;WẠ ``` This is much in the same spirit as Dennis's `F;LẠ`, but instead of using `L` to put a zero in the list when the list is empty, it uses `W` to put the empty list into itself (producing `[[]]`), making it contain a falsy element. [Answer] ## [Retina](https://github.com/m-ender/retina), 10 bytes ``` A`\b0 ^... ``` [Try it online!](https://tio.run/nexus/retina#fU05DoAwDNt5RRYkhrQKlwQjE48IQYj//6E4LWWkalzHTey226@0XcctzRljTEl7a7QXgJqDQrDMjAncgWnISu0UbWWo8V1YXFxQq33Mx6T843qMMAXPDFiXkvgO4K1p7so0Mc2/zu6A8wA "Retina – TIO Nexus") First we remove the input if it contains a zero. The we try to match at least three characters from the beginning of the string (to ensure that the input hasn't been eliminated in the previous stage, or was only `[]` to begin with). [Answer] ## Ruby, ~~25~~ ~~24~~ ~~23~~ ~~18~~ 16 bytes ``` p$_!~/\D0|^..$/ ``` Requires the `-n` flag on the command line (+1 byte, `-e` -> `-ne`). [Try it online!](https://tio.run/nexus/ruby#U1bULy0u0k/KzNNPzStTKCpNqlTQzftfoBKvWKcf42JQE6enp6L//3@0YSxXtKEBkIiOBRHRQIFYMCtWRwHIBhE6CkZgERgvGsiFsYDYGKrBAiRoAcSWsXAWSJkBRB6IQNYY6CjoguzUBWo3gNgIVQCkYbaBTNVRMNFRMMVrMsgEIAAA "Ruby – TIO Nexus") This is a full program that takes input in Ruby's canonical array format on STDIN and outputs `true` or `false` on STDOUT. ``` $_ # line of input that was read automatically (-n) !~/ / # does not match the regex... \D0 # a non-digit followed by a 0 | # or... ^..$ # a 2-length string (which must be [], the empty array) p # output the result ``` **23 byte** function version: ``` ->a{"#{a}"!~/\D0|^..$/} ``` This is a proc that takes one argument, the array to be tested. Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for a byte and to [Ventero](https://codegolf.stackexchange.com/users/84/ventero) for two bytes! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` FẠ_Ṇ ``` **[Try it online!](https://tio.run/nexus/jelly#@@/2cNeC@Ic72/4fbn/UtAaI3P//j47mUlCINozVAVMGEDo6FkpHA2ViYZxYHbBCIKGjYAQThAlEg0SgLCA2RmizAIlbALFlLJylA7YLCLgUYnXALoAohtpvoKOgC3WSLtBEA7hrDBDGGsBdArJOR8FER8GUkJUgo0CWxsYCAA "Jelly – TIO Nexus")** `Ȧ` yields `0` if the input is empty or contains a `0`, otherwise it is `1`. `FẠ` yields `0` if the flattened input contains a `0`, leaving only the edge case of an empty array (since the input is guaranteed to be an array). `Ṇ` is a non-vectorising logical not monad, and hence returns `0` for any non-empty list and `1` for the empty list. As such this can simply be subtraced from the result of `FẠ` using `_`. [Answer] # APL (Dyalog), ~~21~~ ~~12~~ 7 bytes *Golfed 5 bytes thanks to Adám by using forks* ``` ⍬∘≡⍱0∊∊ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG3Co941jzpmPOpc@Kh3o8Gjji4g@v/fUeFRVxMcGXA5KhgqGCkYc8HEUXlAI0Ds3jUA) This is my first try at Dyalog. Golfing tips are welcome! ### Explanation ``` ⍬∘≡ Fork; Is the argument a null set ⍱ Nor 0∊∊ 0 belongs to the enlisted form of the argument For example, (1 (2 (3 (0)))) would become 1 2 3 0 using the ∊ monad Then we check if zero belongs to this vector ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes -1 bytes thanks to Emigna ``` )Q¹˜0å~_ ``` Explanation: ``` )Q Is the length of the input 0? ~ _ ... NOR ... (just for you, Dennis) ¹˜ Input deep flattened 0å Contains 0 ``` [Try it online!](https://tio.run/nexus/05ab1e#@68ZeGjn6TkGh5fWxf//Hw0EhrFAAAA) [Answer] ## Mathematica, 17 bytes ``` #!={}&&#~FreeQ~0& ``` `FreeQ` does the check against `0` for us, but of course it would return `True` for input `{}`, so we need to check that case separately. [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~199~~ 188 bytes ``` A={f={private["_i","_r"];_r=1;_i=0;while{_i<count _this}do{o=_this select _i;if(o in [o])then{if(o==0)then{_r=0}}else{_r=o call f};_i=_i+1};_r};if(count _this==0)then{0}else{_this call f}} ``` Call with: ``` [3,6,4,[4,6],[3,6,[],[2,4,[0],3]]] call A ``` or with: ``` hint format["%1", [3,6,4,[4,6],[3,6,[],[2,4,[0],3]]] call A] ``` Explanation: In the game's scripting language, any string containing code can be called. The curly braces `{}` denote the beginning and the end of a string. (Quotation marks work too, but that gets messy when they are nested.) So, `A={...}` assigns a string to variable `A`, and the variable can then be called like a function with: `<argument> call A`. Basically any string can be treated as a block of code. Then, inside the "function" `A`, we define another function `f`. `private` declares the two variables `_i` and `_r` local to function `f`. A local variable's name has to start with an underscore. `while {} do {}` is a loop, where the first string (denoted by `{}`) contains the code for the loop condition and the second one for the loop body. `_this` is the argument that was passed with the `call` function. `_this` can be of any type, but here we assume it is an array. In the loop, `o=_this select _i` accesses the \_i:th element of the array and assigns it to variable `o`. `if (o in [o])` is a trick to determine if the `o` is another array or not. If `o` is a number (or anything other than an array), `o in [o]` will evaluate to `true`, because the `in` function finds a value matching `o` from the array `[o]`. If `o` is an array, the expression yields `false`, because the `in` refuses to compare arrays. If `o` is not an array, we check if it equals zero, and if it does, we'll set the variable `_r`, which we'll use as the return value, to zero. Otherwise, if `o` is an array, we assign to `_r` the return value of the recursive call to `f` with the new array `o` as the argument. After the loop, at the end of function `f`, we evaluate the expression `_r`, which yields the value of `_r`, and as this is the last expression to be evaluated, this is what the call to function `f` returns. Now that we have defined `f` (`f` need not be inside `A`, but this way we could have declared it a local variable/function (no difference really) of `A` if we didn't want to save some bytes), let's get back `A`. `if (count _this == 0)` checks if `A`'s input array is empty, and if it is, `A` returns 0. Otherwise the function `f` is called and its return value will be `A`'s return value. One might notice that it seems that a semicolon would be missing from a few of places, but this is not the case, because a semicolon is only needed after a statement if another statement follows it inside the same block of code (i.e. string). [Answer] # [Perl 5](https://www.perl.org/), 15 bytes Saved 2 bytes by using the same technique as Doorknob's [Ruby answer](https://codegolf.stackexchange.com/a/113240/55508). 14 bytes of code + `-p` flag ``` $_=!/\b0|^..$/ ``` [Try it online!](https://tio.run/nexus/perl5#fU3LCsJADLz7FWndg2J2m/qAivglaSwI3kSKZ/99nbRdj8ImO5NkZtbV@Hg/KY45DNeq6e/yuaUUmnwB38guDNtU9686a2srbQVNzZtiYBMyJmBvTPtpUpiCFoQ6LILOhx3qbD/kZzLv8TxGmKJnRshlTlwO8Jc0d2U6Mp3@OruDS78 "Perl 5 – TIO Nexus") `/.../` ensures that the array isn't empty (it will match on any array but `[]`. `/\b0/` will only match if there is a `0` in the array. (the `\b` ensures that the `0` isn't a part of another number but a whole number). [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` f x=or[elem c"[,"|c:'0':_<-scanr(:)[]x]<(x<"[]") ``` [Try it online!](https://tio.run/nexus/haskell#jZDLCsIwEEX3fsUQBBWmEF9QS926cqe7IUiIKRb6kCRCBf@9RutGEsRFGLgnucxJX0C3bQ3pStegGCF7qGzCJ9kpT6ySjZlmMxKdyKddzkiwWV/LsoEtnNsRwPXmDs7sG2BHc3OXOzhtHShptc3Yi5uycTCGAhjNRZDwICIRRuSfikgu0AN/cBGBAyGPhom0jJaknqdIG/GZ@NrqffFLbycrq3/qBdWhHMck/IRkjjzmzKPr8o@w18EVrv8TwqGrfwI "Haskell – TIO Nexus") Thanks to Lynn for the test cases and the `x<"[]"` trick. The outer inequality requires `(x<"[]")` to be True (nonempty list) and `or[elem c"[,"|c:'0':_<-scanr(:)[]x]` to be False (no zeroes). Characters of `0` are detected as following a `,` or `[`, as opposed to a number like `20`. The expression `scanr(:)[]x` generates all suffices of `l`, and `c:'0':_<-` captures those whose second character is `'0'`. Then, `elem c"[,"` checks whether the first character is `,` or `[`. I assume here that Haskell-style lists don't have spaces, but if so `','` can just be replaced by `' '`. Here's a more direct 48-byte method, though it produces `0`'s and `1`'s which aren't Truthy/Falsey in Haskell. ``` f"[]"=0 f(c:'0':_)|elem c"[,"=0 f(_:t)=f t f _=1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` F;LẠ ``` [Try it online!](https://tio.run/nexus/jelly#@@9m7fNw14L/h9sfNa0BIvf//6OjuRQUog1jdcCUAYSOjoXS0UCZWBgnVgesEEjoKBjBBGEC0SARKAuIjRHaLEDiFkBsGQtn6YDtAgIuhVgdsAsgiqH2G@go6EKdpAs00QDuGgOEsQZwl4Cs01Ew0VEwJWQlyCiQpbGxAA "Jelly – TIO Nexus") ### How it works ``` F;LẠ Main link. Argument: A (array) F Flatten A. L Yield A's length. ; Concatenate. Ạ All; Tell if all elements of the resulting 1D array are truthy. ``` Note that the Ạ atom behaves like Python's `all` and thus is rather different from the banned Ȧ. [Answer] # Julia, 45 bytes ``` a(x)=all(a,x);a(x::Int)=x!=0;g(x)=x!=[]&&a(x) ``` This creates a function `g` that indicates whether Ȧ would be 1 or 0 by calling a recursive function `a`. To make a suitable `a`, we use multiple dispatch: ``` # A method for scalar values a(x::Int) = x != 0 # A recursive fallback for arrays a(x) = all(a, x) ``` The function `all` takes a function argument, so we're calling `a` on each element of the input. Then we simply define the function for the submission as ``` g(x) = x != [] && a(x) ``` Basically we just need `a` but with a check to correctly handle `[]`. [Try it online!](https://tio.run/nexus/julia5#jZBNa8MwDIbv/hVqByEBZzjdBl1DoPRQ6L0344O3OSEQPIgdyL9PJWfLR@lgAsWvZevV4ww67pNCN02seZ/kuDscLtYnRb8pRF7RISqpooguMvYE17Yz4I3z8KmdccxDAbHMFGdAITMxSalmKfGKWuwVB2rCD4fdov5bk1T8UZgvq@Y9He0x39WkeBiNESjPunErzDJgThYzpOCQzvQpDhRLarEaLCZiYuLwyuHtH1zkOZJ1rrYVnBDp@Ypw7EiIznjY0n91W/gwVW2DX/ndjg@oLfhxAkZogCqmJQlVY78Y5WwVHv@nV3nntXlgNgw3 "Julia 0.5 – TIO Nexus") [Answer] # [Grime](https://github.com/iatorm/grime), ~~16~~ ~~14~~ 11 bytes *Thanks to Zgarb for saving 5 bytes.* ``` e`s\0v#|!.. ``` [Try it online!](https://tio.run/nexus/grime#@5@aUBxjUKZco6in9/9/dHSsjqGOoUEsAA "Grime – TIO Nexus") The `e` tells Grime to try and match the entire input and print `0` or `1` depending on whether that's possible. The `|!` is effectively a "neither" operator, because `x|!y` is shorthand for `(x|y)!`. So we make sure that the input neither contains a zero preceded by a symbol nor is a string of only two characters (`[]`). A note about the second half: `P#` matches a rectangle that contains at least one match of `P`. However, in our case `P` consists of both `s` and `\0` so that would normally require parentheses: `(s\0)#` (because the precedence of `#` is too high). But Grime has a really neat feature where you can modify the precedence of operators with `^` and `v`. So by using `v#` we lower `#`'s precedence so that it's lower than that of any other operator (including concatenation), which lets us save a byte on the parentheses. [Answer] ## JavaScript (ES6), 34 bytes ``` a=>a.length&&+!~`,${a}`.search`,0` ``` ### Test cases ``` let f = a=>a.length&&+!~`,${a}`.search`,0` console.log('Truthy:') console.log(f([1])) console.log(f([10])) console.log(f([[]])) console.log(f([[[[1]]]])) console.log(f([[], [1], [1, 2]])) console.log(f([[1], [1, [2]], [1, [2, [3]]]])) console.log(f([[8], [8, [9]], [8, [9, [10]]]])) console.log('Falsy:') console.log(f([])) console.log(f([0])) console.log(f([0, -1])) console.log(f([-1, 0])) console.log(f([[[[0]]]])) console.log(f([[0], [1, 2], [3, 4, 5]])) console.log(f([[8], [8, [9]], [8, [9, [1, 0]]]])) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` #Va&`\b0`NIa ``` Takes the array as a command-line argument in Pip's repr form, like `[1;[2;3]]`. Returns `1` for truthy, `0` for falsey. [Try it online](https://tio.run/nexus/pip#@68clqiWEJNkkODnmfj////oaItY62gL62jLWChtHW1oEAsEAA "Pip – TIO Nexus") or [verify all test cases](https://tio.run/nexus/pip#c1NIVAgK0IrmUgCBaMNYGMMAxoqOhbOigfKxCG6sNZAPxNZGCDGIQDRQBEJbRxsja7EACltYR1vGQmlrkEVweagqmGq4EwysdeEO0zW0NkBykAGy6QZQ1wAttTaxNsVrrTVCJ5AM@K8clqiWEJNkkODnmfj/PwA). ### Explanation ``` a is 1st cmdline arg (implicit) Va Eval a (converting from a string to a list) # Take the length (0 if empty, nonzero if nonempty) & Logical AND `\b0` Regex pattern: word boundary followed by 0 (avoids things like 10) NIa Not in a (0 if `\b0` matches in a, 1 if it doesn't) Autoprint ``` ### Bonus answer, 12 bytes Here's a function that takes a list instead: ``` #_>0=0N_Js^s #_ Len(arg) >0 is greater than 0 = which also equals the following (comparison operators chain like Python's): 0N Count of 0's in _Js^s arg, joined on space and then split on space (a hacky way to flatten) ``` [TIO](https://tio.run/nexus/pip#fU45CoBADOx9xYKNFkK8QBm0tLAQ@xDFN/h/1oh7VQY2mUySnVnMZTgzb3AtHpBHLAGxziW2Au31oYncR7AyXwW36cmg9AAexVW8QmHutvx2sECogrGqBiWGKP2dnBsVRYf@VxbxUvNe2PycaaLtXO/jtldpHw) [Answer] # [Röda](https://github.com/fergusq/roda), ~~59~~ 44 bytes ``` f a{[1]if{g(a)[[]!=a]}}g a{[a!=0];try a|g _} ``` [Try it online!](https://tio.run/nexus/roda#lVBNS8QwED2nv@JtT7uQhfgFq0sPXgRR0HsIEnabWsi20qZg6fa314lNW/EiQiYzeXnz5iWDge7khcpNl631Rkq1SrTq@8zDepUItXdVC33O8NYPJ50X6CLmqsa9t7hLICPGqJ1/JzFmqUKWdKOmg@LwRNo4LidwAqRHQkVxtbTtPL6juFVz5ZnCUyJGy2hbL17GtuBEcGyDuS1pi9mXWAaI2ZMfzHHNcfPXcC81jy8ruAPoY8KvHEvq/ajywiF@eYqRGxjPOBOhfW2sXX9ukNo6RSA93D8@xxE7lkX6U25812@1prBpXf9DsR@@AA "Röda – TIO Nexus") `f` takes the input from its stream as a list that can contain other lists and integers. It returns `1` if `a` is truthy and nothing otherwise. The helper function `g` checks if `a` contains zeros. Explanation: ``` f a{[1]if{g(a)[[]!=a]}} f a{ } /* Function declaration */ g(a) /* Call g -> pushes some booleans to the stream */ [[]!=a] /* Push value []!=a to the stream */ if{ } /* If all booleans in the stream are true: */ [1] /* Push 1 to the stream */ /* Otherwise return nothing */ g a{[a!=0];try a|g _} /* Helper function */ g a{ } /* Function declaration */ [a!=0]; /* Push value a!=0 to the output stream */ try /* Ignore errors in the following if a is not a list */ a /* Push values in a to the stream */ |g _ /* Pull values from the stream and */ /* call g for each of them */ /* (pushes boolean values to the output stream) */ ``` A solution that makes use of regexes could very likely be shorter. This answer could have been [shorter](https://tio.run/nexus/roda#hVDBasMwDD07X/GaUwsuuGsL3UoOuxTKBvsAY4pZnCyQJiNxDyXNt2fy4iSlhw0sS3qWnp7VJdBNOtcLKdUs0qpNKZd6Fgm1t9UV@pbi1HZnnRVoAmari/264iWCDBiTK8V/nei9VN5LelFDojhcIV0cTwM4ANIhPiJbT207h@/IntUYuUrhSgJGJ9F5PWnp27wSwbH04pbELUZdYhogRk1uMMeGY/vfcEc1ji8r2E/QYvxW4pJ6v6ussAg/3kJkCRJXYfLawOOH1@N7GLC4LMw9Q/@VR4JLkZu6/puk7X4A "Röda – TIO Nexus") if it were allowed to return multiple values. This has been discussed in [one of my answers](https://codegolf.stackexchange.com/questions/112972/superior-passtimes/112982#112982) before, and it was concluded that it is allowed in the default rules to return different truthy and falsy values for different inputs, but for some reason OP forbid it here and there. :( [Answer] # [Wonder](https://github.com/wonderlang/wonder), 15 bytes ``` @&#0! iO0flat#0 ``` Usage: ``` (@&#0! iO0flat#0)[1;2;3;[8;9;0]] ``` Flatten input, get all occurrences of 0, logical NOT, logical AND with input. [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` import Data.List (%)=isInfixOf f x=not(",0"%x||"[0"%x)&&x<"[]" ``` [Try it online!](https://tio.run/nexus/haskell#jZDLCsIwEEX3/YohWFEYJb5Axe5EEAQXugtZBG0xoKk0I1Tov9fUupEEcREu3JMMc1Lr2z0vCNaK1HCnLUW9uJ9ouzWZLvdZlEGZmJx6DDmLy6piosl@t1uumJCsviltIIFzHgHcH3SgYmeAHYsHXZ5AqSU4KZvaJWt4oQ1BBzJgYiS9hnuVkH4l3FMZ6CU64A6OA7AlwqE2UUyCQ@aOz1Es5Cex2ep98Utvo642/annjfblOA78TxiMkIeceXBd/hF2OjjF2X9C2M6qXw "Haskell – TIO Nexus") This is a function `String -> Bool`. Haskell’s lists are heterogenous, so there’s no built-in way to represent lists like `[0, [0]]`. [Answer] # [Python 2](https://docs.python.org/2/), ~~45 39~~ 38 bytes ``` lambda a:(a>[])^(' 0'in`a`or'[0'in`a`) ``` [Try it online!](https://tio.run/nexus/python2#PYzBCsIwEETv/Yq9JYE9pHqphfoj25WuaCCgqST5/7gpIuzwZoZlwrK2l7zvDwGZrVyJ3c0a8CamTbY9G/pZ1@qz1AILEBEzEk2MQJPqwn@nGj165v6hN@IJz0pthrBn6BsQ08EyD/DJMdUjYbAdrn0B "Python 2 – TIO Nexus") -6 thanks to @BenFrankel --- ### previous version, without converting list to string repr, 68 bytes: ``` lambda a:(len(a)and g(a))*1 g=lambda b:all(map(g,b))if b>[]else b!=0 ``` [Answer] # MATLAB, 49 bytes As MATLAB (as well as Octave) does not allow these kind of nested arrays, we interpret it as a string. First we replace all non-digit characters with a space. Then we use `str2num` to convert it to an (1D) array, on which we can apply `all` (which is allowed, as it does not completely solve this task by itself.) ``` s=input('');s(s<45|s>57)=32;disp(all(str2num(s))) ``` [Answer] # egrep, 7+3=10 bytes ``` \<0|^.] ``` +3 bytes for the required `-v` flag to invert the result. Grep doesn't have any concept of arrays, so this uses a string representation as given in the question. Takes input on one line from stdin, returns via the exit code (ignore stdout). (Now using a version which doesn't account for `01` and similar, since word-of-god is that it's OK) ### Original bash/grep entry: ``` grep -Ev '\<0+\>|^.]' ``` Finds `0`s anywhere (using the word boundary checks `\<` and `\>` to discount things like `10` or `a1`), or a whole string matching `[]`, then inverts the match. ### Breakdown: ``` grep -E \ # extended regular expression syntax -v \ # invert match \<0+\> # a number of 0s with alphanumeric boundaries on both sides |^.\] # or ']' as the second character (implies '[]') ``` [Answer] # [√ å ı ¥ ® Ï Ø ¿](https://github.com/ValyrioCode/Valyrio) , ~~12~~ 4 bytes ``` i0Bu ``` ## Explanation ``` i › Take input as a list and automatically flatten it. If empty, push 0. 0 › Push 0 to the stack B › Pop 0 and push the number of times it appears u › convert top value to its boolean ``` If result needs to be outputted ... ``` i0Buo › same as above; o outputs the top value on the stack ``` # Previous solution I had posted this before realising that stack based languages could leave the value on the stack as a form of output ``` i0B¿0oP?!¿o? ``` ## Explanation ``` i › Take input as a list and automatically flatten it. If empty, push 0. 0 › Push 0 to the stack B › Pop 0 and push the number of times it appears ¿ › If the top value is true ... 0 › Push 0 o › Output the top value on the stack P › Pop the top value from the stack ? › End if statement ! › Boolean opposite of top value ¿ › If the top value is true ... o › Output the top value ? › End if statement ``` [Answer] ## Haskell, 45 As [Lynn](https://codegolf.stackexchange.com/a/113241/2183) and [xnor](https://codegolf.stackexchange.com/a/113251/2183) remarked, Haskell does not come with a heterogeneously-nested list type. But it's easy to add them as a custom data type and let the function operate on that type, and this is much preferrable to operating on (urgh!) *strings*. ``` data L=L Int|T[L] f(L n)=n/=0 f(T l)=all f l ``` To actually be able to write out such lists as literals with `[1, [2]]` syntax, you also need some typeclass fu. Full test case: ``` {-# LANGUAGE OverloadedLists, TypeFamilies #-} import GHC.Exts (IsList(..)) instance Num L where fromInteger = L . fromInteger negate (L n) = L $ negate n instance IsList L where type Item L = L fromList = T main = mapM_ (print . f) ( [ [1] , [[[[0]]]] , [[8], [8, [9]], [8, [9, [1, 0]]]] ] :: [L]) ``` [Try it online!](https://tio.run/nexus/haskell#nVJdS8MwFH3vrzgwH1poa/2COejDkDkHcb7UpxIk2HQG2qy08Qv1t9ebzupA2wcDCYd7zj33g7RvwQRsvl7ezpcL3DzJutiKTGZMNabxkbxW8lKUqlCywST4cFRZbWuD5dVFuHgxDdxVY6VuGHqekwkjwGKGlTbvScq4k7sM2ov1YRwRTlB4sSgK5CgcpRsj9L3E@rEEw/ODrKUD5PW2pHS5kTViiof7EeK13Agj0fl2goM@pH8sd03tuRqaAysjbSVK@qrTiWIkbSmUJlCK6voOblUrbWxhDy4pf58U6RH/k/GJiQaplA9TKVnyEZ5b6@7xcTyi6zUpiXpE92TUfGqlU7rn/BvtRhnJGiSGFxD5CIY3F1Cz0diGRtshtt@OndfHqY@zf8xsexgqwzGbgf61134C "Haskell – TIO Nexus") [Answer] # Vim, 23 bytes ``` :g/0\|^..$/d :s/.\+/1/<CR> ``` [Try it online!](https://tio.run/nexus/v#@2@Vrm8QUxOnp6ein8JlVayvF6Otb6j//390dGzsf90yAA "V – TIO Nexus") Outputs an empty string for false, or `1` for true. This could be shorter if I can output an empty string *or* `[]` for false (both of which are falsy values in vim). [Answer] # Javascript ES6, ~~24~~ 23 chars Works with array, returns `true` or `false`: ``` a=>!!a[0]>/\b0/.test(a) ``` Test: ``` f=a=>!!a[0]>/\b0/.test(a) console.log([ [1], [10], [[]], [[[[1]]]], [[], [1], [1, 2]], [[1], [1, [2]], [1, [2, [3]]]], [[8], [8, [9]], [8, [9, [10]]]], ].every(x => f(x)===true)) console.log([ [], [0], [0, -1], [-1, 0], [[[[0]]]], [[0], [1, 2], [3, 4, 5]], [[8], [8, [9]], [8, [9, [1, 0]]]], ].every(x => f(x)===false)) ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 20 bytes ``` :size\flat,0 eq none ``` [Try it online!](https://tio.run/nexus/stacked#dVDLDoIwELz7FWMkYRs5FB8JmuiXNBISajSBghQvit@OpVu5ediZ7u7sTFJaAJQKj9ITCSZyYxHeYtK4wiYMuCPXMoO2szhzswx0EIG9My@nvRdxlETO0XkK@UuVs5EMkc4cO@z/24NvBN5LMx7t/aXVtSr6REI/YBqjRwOFVYKo022Humjx8XhrqhLl3bbodKULqxHHMRdOZwdOXyGmCymraFCk3O8MpMQ6EgNLUXtN8@zHLw "stacked – TIO Nexus") Alternatively, using a string: ``` :tostr'\d+'match'0'has¬\size¬> ``` [Try it online!](https://tio.run/nexus/stacked#dU3LCsIwELz7FSMK2aCHVC1UwX5JoBQttEIftPGi@Ef9iv5YTLOxNw@7szs7O0MrgCLpu/JAkoEcLcMsZ40rHALBG7mVEXRcxInjEtBZBvTOfJzvXsRRChlHZxHUL1UtRipEOnOcEP@3B/9IvNeNvZh2ML3Q952oc3MrhRJlPkyjHqpXMY2pbaCx2WPbF10P1HkHgWvq2qOtGrRPg8/M2i8 "stacked – TIO Nexus") [Answer] ## [Lithp](https://github.com/andrakis/node-lithp), 74 bytes ``` (def f #L::((foldl(flatten L)(?(>(length L)0)1 0)#N,A::((?(== N 0)0 A))))) ``` [Try it online!](https://andrakis.github.io/ide2/index.html?code=JSBFbnRyeSBmb3IgQ29kZWdvbGY6CiUgaHR0cDovL2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tL3F1ZXN0aW9ucy8xMTMyMzgvaXMtaXQtdHJ1ZS1hc2stamVsbHkKKAogICAgKGltcG9ydCBsaXN0cykKICAgIAogICAgJSBSZWFkYWJsZToKICAgIChkZWYgZiAjTCA6OiAoCiAgICAgICAgKGZvbGRsIChmbGF0dGVuIEwpICAgICAgICAgICAgICAgJSBGbGF0dGVuIGxpc3QgYmVmb3JlIGZvbGRpbmcKICAgICAgICAgICAgICAgKD8gKD4gKGxlbmd0aCBMKSAwKSAxIDApICAlIENoZWNrIHRoZSBhcnJheSBpcyBub24tZW1wdHkKICAgICAgICAgICAgICAgI051bSxBY2MgOjogKCAgICAgICAgICAgICAlIGZvbGQgZnVuY3Rpb24KICAgICAgICAgICAgICAgICAgICAoPyAoPT0gTnVtIDApIDAgQWNjKSAlIElmIE4gPT0gMCwgcmV0dXJuIDAsIG90aGVyd2lzZSByZXR1cm4gQWNjCiAgICAgICAgICAgICAgICkKICAgICAgICApCiAgICApKQogICAgJSBHb2xmZWQ6CiAgICAoZGVmIGYgI0w6OigoZm9sZGwoZmxhdHRlbiBMKSg/KD4obGVuZ3RoIEwpMCkxIDApI04sQTo6KCg/KD09IE4gMCkwIEEpKSkpKQogICAgCiAgICAlIFRydXRoeSB0ZXN0IGNhc2VzCiAgICAlIFsxXQogICAgKHByaW50IChmIChsaXN0IDEpKSkKICAgICUgWzEwXQogICAgKHByaW50IChmIChsaXN0IDEwKSkpCiAgICAlIFtbXV0KICAgIChwcmludCAoZiAobGlzdCAobGlzdCkpKSkKICAgICUgW1tbWzFdXV1dCiAgICAocHJpbnQgKGYgKGxpc3QgKGxpc3QgKGxpc3QgKGxpc3QgMSkpKSkpKQogICAgJSBbW10sIFsxXSwgWzEsIDJdXQogICAgKHByaW50IChmIChsaXN0IChsaXN0KSAobGlzdCAxKSAobGlzdCAxIDIpKSkpCiAgICAlIFtbMV0sIFsxLCBbMl1dLCBbMSwgWzIsIFszXV1dXQogICAgKHByaW50IChmIChsaXN0IChsaXN0IDEpIChsaXN0IDEgKGxpc3QgMikpIChsaXN0IDEgKGxpc3QgMiAobGlzdCAzKSkpKSkpCiAgICAlIFtbOF0sIFs4LCBbOV1dLCBbOCwgWzksIFsxMF1dXV0KICAgIChwcmludCAoZiAobGlzdCAobGlzdCA4KSAobGlzdCA4IChsaXN0IDkpKSAobGlzdCA4IChsaXN0IDkgKGxpc3QgMTApKSkpKSkKICAgIAogICAgJSBGYWxzZXkgdGVzdCBjYXNlcwogICAgJSBbXQogICAgKHByaW50IChmIChsaXN0KSkpCiAgICAlIFswXQogICAgKHByaW50IChmIChsaXN0IDApKSkKICAgICUgWzAsIC0xXQogICAgKHByaW50IChmIChsaXN0IDAgLTEpKSkKICAgICUgWy0xLCAwXQogICAgKHByaW50IChmIChsaXN0IC0xIDApKSkKICAgICUgW1tbWzBdXV1dCiAgICAocHJpbnQgKGYgKGxpc3QgKGxpc3QgKGxpc3QgKGxpc3QgMCkpKSkpKQogICAgJSBbWzBdLCBbMSwgMl0sIFszLCA0LCA1XV0KICAgIChwcmludCAoZiAobGlzdCAobGlzdCAwKSAobGlzdCAxIDIpIChsaXN0IDMgNCA1KSkpKQogICAgJSBbWzhdLCBbOCwgWzldXSwgWzgsIFs5LCBbMSwgMF1dXV0KICAgIChwcmludCAoZiAobGlzdCAobGlzdCA4KSAobGlzdCA4IChsaXN0IDkpKSAobGlzdCA4IChsaXN0IDkgKGxpc3QgMSAwKSkpKSkpCik=) Well, this turned out longer than I'd hoped. The `[]` case tripped me up and added a few bytes. It simply flattens the list and does a fold left over it, and if it finds a 0 it sets the accumulator to 0. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~24~~ 22 bytes ``` ->a{a[0]&&a*?!!~/\b0/} ``` [Try it online!](https://tio.run/nexus/ruby#@59mq2uXWJ0YbRCrppaoZa@oWKcfk2SgX8tVoJAWHW2gY6ljqmMWGwvhmuiYAQXMYVxzIBeoAkkERgMZsf//AwA "Ruby – TIO Nexus") Yes I know there's a better solution in Ruby but I wanted to find one taking the array in input instead of a string. [Answer] # VIM: ~~16 keystrokes~~ ~~28 keystrokes~~ 26 keystrokes Had to add a bunch of keystrokes to take care of multiple zeros and the empty array []. ``` i[] 0<enter><esc>A 0<esc>h#dd0%r602x<C-x>$hd0<C-a> ``` Expects the array to be in the first and only line of the file and the cursor to be on the first character. Leaves `0` for false and a `1` for true. Explanation 1. `i[] 0<Enter><esc>` Writes some stuff preceding the array 2. `A 0<esc>` Writes some stuff preceding the array 3. `#dd` search for the word "0", going backwards in the document and delete the line it's containing. * If 0 is in the array, this will stop on the second line. 1. This leaves `[] 0` on the first line, which is an empty array. * Else, this will stop on the first line, leaving the line `(array) 0` At this point, all that's left to do is to identify the empty array and output 0 if it's present, otherwise ignore it. The possible way for a 0 to be at the third position is if it is the empty array. Thus, it's just a problem for identifying if the third character is a 0. 1. `3|a01<esc>` Writes `01` after the third character 2. `0df0` Deletes up to the first zero. 3. `lD` saves the next character, then deletes the rest of the line. [Try it online!](https://tio.run/nexus/v#@58ZHWtg46yba2eTWpxs52gApjKUU1KMaxINDME8g5Q0gxyX//@jo2N1DGL/65YBAA "V – TIO Nexus") [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~70~~ 64 bytes ``` (load library (d _(q((X)(i(c()X)(all(map _ X))X (q((L)(i L(_ L)0 ``` The last line is an unnamed lambda function that takes a list and returns `1` for "truthy-under-Ȧ" and `0` for falsey. [Try it online!](https://tio.run/##fY7NDoIwEITvPsUcZ2@LPwkeufMA3EgVY5pUBOTC09dFKcGLTdrp7E777ejbKfhXFyPD0zUI/jK4YdqxQc2erISeV4qpC4EP16FGJVLNiWJOlJZAyRqlaPwECtC@HJczU0m@vd2RidkepKQLabXVmWTzxn4t5aY5eJZFravyXbtfoKWXRyqJqhvudgzoytcNXxc4eMARp39DIE0R3w "tinylisp – Try It Online") ### Ungolfed ``` (load library) (def _Ȧ (lambda (val) (if (equal? (type val) List) (all (map _Ȧ val)) val))) (def Ȧ (lambda (ls) (if ls (_Ȧ ls) 0))) ``` The recursive helper function `_Ȧ` does most of the work. If its argument is a list, we `map` `_Ȧ` to its elements and return `1` if they are `all` truthy, `0` if any are falsey. (Conveniently, `all` returns `1` when given the empty list.) Otherwise, the argument must be an integer; we return it as-is (`0` is falsey and all other integers are truthy in tinylisp). The main function `Ȧ` checks if the list is nonempty. If so, it calls `_Ȧ`; if not, it returns `0`. The golfed version takes advantage of some undefined behavior: rather than using `(e(type X)List)` to test whether `X` is an integer or a list, it does `(c()X)`, which attempts to `cons` (prepend) the empty list onto `X`. If `X` is a list, this results in a nonempty list, which is truthy. If `X` is an integer, tinylisp outputs an error message and returns an empty list, which is falsey. Since stderr is ignored, this approach is valid. ]
[Question] [ Given a non-empty list/array containing only non-negative integers like this: ``` [0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0] ``` Output the list with trailing and leading zeroes removed. The output for this would be: ``` [8, 1, 4, 3, 5, 6, 4, 1, 2] ``` Some other test cases: ``` [0, 4, 1, 2, 0, 1, 2, 4, 0] > [4, 1, 2, 0, 1, 2, 4] [0, 0, 0, 0, 0, 0] > nothing [3, 4, 5, 0, 0] > [3, 4, 5] [6] > [6] ``` Shortest code wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes Code: ``` t0 ``` Explanation: ``` t # Trim off... 0 # zero at both sides ``` [Try it online!](http://jelly.tryitonline.net/#code=dDA&input=&args=WzAsIDAsIDAsIDgsIDEsIDQsIDMsIDUsIDAsIDYsIDQsIDEsIDIsIDAsIDAsIDAsIDBd) [Answer] # JavaScript (ES6) 43 ``` a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a)) ``` **Less golfed** ``` a=>{ f=a=>a.reverse().filter(x=>a|=x) // reverse and remove leading 0 // leverage js cast rules: operator | cast operands to integer // an array casted to integer is 0 unless the array is made of // a single integer value (that is ok for me in this case) return f(f(a)) // apply 2 times } ``` **Test** ``` F=a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a)) function test(){ var l=(I.value.match(/\d+/g)||[]).map(x=>+x) O.textContent=F(l) } test() ``` ``` #I { width:90%} ``` ``` <input id=I oninput='test()' value='0 0 1 3 7 11 0 8 23 0 0 0'> <pre id=O></pre> ``` [Answer] # Retina, 12 bytes ``` ^0 ? )` 0$ ``` The trailing linefeed is significant. Thanks to [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) and [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for saving a few bytes. [Try it online](http://retina.tryitonline.net/#code=XjAgPwoKKWAgMCQK&input=MCAwIDAgMSAyIDMgMCA0IDUgNiAwIDAgMA) [Answer] # CJam, 13 bytes ``` l~{_{}#>W%}2* ``` With the array inputted. Longer version: ``` l~ Puts input on the stack and parse as array { } Code block _ Duplicate the first thing on the stack {}# Finds the index of the first non-0 value in the array, puts it on the stack > Slices the array from that index W% Reverses the array 2* Does the code block twice in total ``` [Answer] # [Haskell](https://en.wikipedia.org/wiki/Haskell_(programming_language)), 29 bytes ``` t=f.f;f=reverse.dropWhile(<1) ``` [Answer] ## Pyth, 4 bytes ``` .sQ0 ``` Demo: ``` llama@llama:~$ pyth -c .sQ0 [0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 5, 0, 0, 0, 0] [1, 2, 0, 3, 4, 0, 0, 5] ``` From [Pyth's `rev-doc.txt`](https://github.com/isaacg1/pyth/blob/d0857326708284d884298464363e633e1390b190/rev-doc.txt#L365): ``` .s <seq> <any> Strip from A maximal prefix and suffix of A consisting of copies of B. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes Code: ``` 0Û0Ü ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MMObMMOc&input=WzAsIDAsIDAsIDgsIDEsIDQsIDMsIDUsIDAsIDYsIDQsIDEsIDIsIDAsIDAsIDAsIDBd) Explanation: ``` 0Û # Trim off leading zeroes 0Ü # Trim off trailing zeroes ``` Uses CP-1252 encoding. [Answer] ## Jelly, 10 bytes ``` Uo\U,o\PTị ``` This doesn't use the builtin. ``` Uo\U Backward running logical OR , paired with o\ Forward running logical OR P Product T All indices of truthy elements ị Index the input at those values. ``` Try it [here](http://jelly.tryitonline.net/#code=VW9cVSxvXFBU4buL&input=&args=WzAsIDQsIDEsIDIsIDAsIDEsIDIsIDAsIDBd). [Answer] # R, 43 bytes ``` function(x)x[cummax(x)&rev(cummax(rev(x)))] ``` or as read/write STDIN/STDOUT ``` x=scan();cat(x[cummax(x)&rev(cummax(rev(x)))]) ``` --- This finds the cumulative maximum from the beginning and the end (reversed) string. The `&` operator converts these two vectors to logical one of the same size as `x`, (zeroes will always converted to `FALSE` and everything else to `TRUE`), this way it makes it possible to subset from `x` according to the met conditions. [Answer] # Mathematica ~~34~~ 27 bytes ``` #//.{0,a___}|{a___,0}:>{a}& ``` This repeatedly applies replacement rules until such action fails to provide a new output. 7 bytes saved thanks to Alephalpha. The first rule deletes a zero at the beginning; the second rule deletes a zero at the end of the array. [Answer] ## 05AB1E, 4 bytes ``` 0Û0Ü ``` Basically trimming leading then trailing zeroes of the input, given as an array. [Try it online !](http://05ab1e.tryitonline.net/#code=MMObMMOc&input=WzAsIDAsIDAsIDgsIDEsIDQsIDMsIDUsIDYsIDQsIDEsIDIsIDAsIDAsIDAsIDBd) [Answer] # Perl, 19 + 1 = 20 bytes ``` s/^(0 ?)+|( 0)+$//g ``` Requires `-p` flag: ``` $ perl -pE's/^(0 )+|( 0)+$//g' <<< '0 0 0 1 2 3 4 5 6 0 0 0' 1 2 3 4 5 6 ``` [Answer] ## Ruby, ~~49~~ 44 bytes ``` ->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2} ``` Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for chopping off 5 bytes with a completely different method! This just `drop`s the first element of the array `while` it's 0, reverses the array, repeats, and finally reverses the array to return it to the proper order. [Answer] # Perl, 38 bytes ``` $\.=$_}{$\=~s/^(0\n)*|(0\n)*\n$//gs ``` Run with `perl -p`, (3 bytes added for `-p`). Accepts numbers on STDIN, one per line; emits numbers on STDOUT, one per line, as a well-behaved unix utility should. Only treats numbers represented exactly by '0' as zeroes; it would be possible to support other representations with a few more bytes in the regex. Longer version, still to be run with `-p`: ``` # append entire line to output record separator $\.=$_ }{ # replace leading and trailng zeroes in output record separator $\ =~ s/^(0\n)*|(0\n)*\n$//gs # output record separator will be implicitly printed ``` Expanded version, showing interactions with -p flag: ``` # implicit while loop added by -p while (<>) { # append line to output record separator $\.=$_ }{ # escape the implicit while loop # replace leading and traling $\=~s/^(0\n)*|(0\n)*\n$//gs # print by default prints $_ followed by # the output record separator $\ which contains our answer ;print # implicit print added by -p } # implicit closing brace added by -p ``` [Answer] ## Elixir, 77 bytes ``` import Enum z=fn x->x==0 end reverse(drop_while(reverse(drop_while(l,z)),z)) ``` l is the array. Edit:wah! copy/pasta fail. of course one has to import Enum, which raises the byte count by 12 (or use Enum.function\_name, which will make it even longer). [Answer] ## JavaScript (ES6), 47 bytes ``` a=>a.join(a="").replace(/(^0+|0+$)/g,a).split(a) ``` Where `a` is the array. [Answer] # Vitsy, 13 bytes Vitsy is slowly getting better... (I'm coming for you Jelly. ಠ\_ಠ) ``` 1mr1m D)[X1m] ``` This exits with the array on the stack. For readability, the TryItOnline! link that I have provided below the explanation will output a formatted list. Explanation: ``` 1mr1m 1m Do the second line of code. r Reverse the stack. 1m I'ma let you figure this one out. ;) D)[X1m] D Duplicate the top item of the stack. )[ ] If the top item of the stack is zero, do the stuff in brackets. X Remove the top item of the stack. 1m Execute the second line of code. ``` Note that this will throw a StackOverflowException for unreasonably large inputs. [TryItOnline!](http://vitsy.tryitonline.net/#code=MW1yMW1sXFtOYU9dCkQpW1gxbV0&input=&args=MA+MA+Mg+MQ+MA+MA) [Answer] # JavaScript (ES6), 34 bytes ``` a=>a.replace(/^(0 ?)*|( 0)*$/g,'') ``` Input and output are in the form of a space-delimited list, such as `"0 4 1 2 0 1 2 4 0"`. [Answer] # R, 39 bytes ``` function(x)x[min(i<-which(x>0)):max(i)] ``` Four bytes shorter than [David Arenburg's R answer](https://codegolf.stackexchange.com/a/73745/59052). This implementation finds the first and last index in the array which is greater than zero, and returns everything in the array between those two indices. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes ``` 2:"PtYsg) ``` [**Try it online!**](http://matl.tryitonline.net/#code=MjoiUHRZc2cp&input=WzAsIDQsIDEsIDIsIDAsIDEsIDIsIDQsIDBd) ### Explanation ``` 2:" % For loop (do the following twice) P % Flip array. Implicitly asks for input the first time t % Duplicate Ys % Cumulative sum g % Convert to logical index ) % Apply index % Implicitly end for % Implicitly display stack contents ``` [Answer] # Python 3, 48 bytes ``` lambda a:map(int,''.join(map(str,a)).strip('0')) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` {↔a₁.h>0∧}ⁱ² ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcJ/oNyUxEdNjXoZdgZA@dpHjRsPbfr/P1oh2kBHAYIsdBQMdRRMdBSMdRRMdRTMwGygiBFMAQjF6oB1IMtAGCYISQN0DcZgaVOEgFmsQiwA "Brachylog – Try It Online") The predicate fails in the case of "nothing". ``` a₁. Take the longest suffix of ↔ the input reversed h the first element of which >0 is greater than 0 ∧ (which is not the output). { }ⁱ² Do it again. ``` If "nothing" has to be some actual value, like an empty list, it's only one more byte: # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` {↔a₁.h>0∨Ė}ⁱ² ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pR25TER02Nehl2Bo86VhyZVvuoceOhTf//RytEG@goQJCFjoKhjoKJjoKxjoKpjoIZmA0UMYIpAKFYHbAOZBkIwwQhaYCuwRgsbYoQMItViAUA "Brachylog – Try It Online") If the input can be assumed to contain only single digits, it's quite a bit shorter: # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` c↔↔ℕ₁ẹ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcL/5EdtU0CoZeqjpsaHu3b@/x@tEG2gowBBFjoKhjoKJjoKxjoKpjoKZmA2UMQIpgCEYnXAOpBlIAwThKQBugZjsLQpQsAsViEWAA "Brachylog – Try It Online") [Answer] ## Dyalog APL, 15 bytes ``` {⌽⍵↓⍨+/0=+\⍵}⍣2 ⍣2 Apply this function twice: { } Monadic function: +\⍵ Calculate the running sum. +/0= Compare to zero and sum. Number of leading zeroes. ⍵↓⍨ Drop the first that many elements from the array. ⌽ Reverse the result. ``` Try it [here](http://tryapl.org/?a=%28%7B%u233D%u2375%u2193%u2368+/0%3D+%5C%u2375%7D%u23632%290%200%203%201%200%200%204%201%205%209%200%200%200&run). [Answer] # Vim 16 Keystrokes ``` i<input><esc>?[1-9]<enter>lD0d/<up><enter> ``` The input is to be typed by the user between `i` and `esc`, and does not count as a keystroke. This assumes that there will be at least one leading and one trailing zero. If that is not a valid assumption, we can use this slightly longer version: (18 Keystrokes) ``` i <input> <esc>?[1-9]<enter>lD0d/<up><enter> ``` [Answer] ## ES6, 51 bytes ``` f=a=>a.map(x=>x?t=++i:f<i++||++f,f=i=0)&&a.slice(f,t) ``` `t` is set to the index after the last non-zero value, while `f` is incremented as long as only zeros have been seen so far. [Answer] # [Perl 6](http://perl6.org), 23 bytes ``` {.[.grep(?*):k.minmax]} {.[minmax .grep(?*):k]} ``` ### Usage: ``` # replace the built-in trim subroutine # with this one in the current lexical scope my &trim = {.[.grep(?*):k.minmax]} say trim [0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0]; # (8 1 4 3 5 6 4 1 2) say trim [0, 4, 1, 2, 0, 1, 2, 4, 0]; # (4 1 2 0 1 2 4) say trim [0, 0, 0, 0, 0, 0]; # () say trim [3, 4, 5, 0, 0]; # (3 4 5) say trim [6]; # (6) ``` [Answer] # Retina, 11 bytes ``` +`^0 ?| 0$ <empty> ``` Quite simple. Recursively replaces zeroes at beginning and end of line. [Try it online!](http://retina.tryitonline.net/#code=K2BeMCA_fCAwJAo&input=MCAwIDA) [Answer] **Python, 84 characters** ``` def t(A): if set(A)<={0}:return[] for i in(0,-1): while A[i]==0:del A[i] return A ``` [Answer] ## Javascript (ES6) 40 bytes ``` a=>/^(0,)*(.*?)(,0)*$/.exec(a.join())[2] ``` [Answer] # PHP, ~~56~~ ~~54~~ 52 bytes Uses Windows-1252 encoding String based solution ``` <?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß)); ``` Run like this: ``` echo '<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo ``` If your terminal is set to UTF-8, this is the same: ``` echo '<?=preg_replace("#-( 0)+|( 0)+$#","",join($argv," "));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo ``` ## Tweaks * Saved 2 bytes by negating strings and dropping string delimiters * Saved 2 bytes by using short print tag ]
[Question] [ As programmers, we all know the saying: "You can have it fast and good, but it won't be cheap, you can have it cheap and good, but it won't be fast, or you can have it fast and cheap, but it won't be good." For this challenge, you are implementing an imaginary configuration tool for your custom programming services. You should render a set of three check boxes, with a heading of "SELECT ANY TWO": ``` SELECT ANY TWO ☐ FAST ☐ CHEAP ☐ GOOD ``` Once two items have been selected, the third item must be disabled. Upon deselecting one of the two selected items, all options must again be enabled. Put another way, if zero or one items are selected, all are still enabled, but if two items are selected, the third must be disabled. No special controls allowed. The check boxes should be the standard check box in your language of choice. For example, don't use a "CheckBoxList" control, if your language has one. I'm imagining most entries will be HTML/jQuery, but that is not a rule. This is code golf, looking for the shortest entry. **WINNERS SO FAR** I'll break it down into categories. There are some clear winners: **jQuery:** [nderscore, Mr. Tenacity](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two/26822#26822) Under 100b when you exclude text "resources". Honorable mention should also go to Matt for introducing the jQuery concepts that many took inspiration from. **Dyalog APL:** [marinus, a.k.a. Mr. Unicode](https://codegolf.stackexchange.com/a/26789/21186) How do you type all those things? I can see why you would want to write short programs. **PHP:** [SuperScript](https://codegolf.stackexchange.com/a/26825/21186) I believe this is the shortest entry that actually disables rather than deselecting the third option, following the strictest interpretation of the rules. [Answer] # JavaScript - 184 169 (with jQuery) ``` b="input",a="<input type=checkbox>",c=":checked";$("body").html("SELECT ANY TWO"+a+"FAST"+a+"GOOD"+a+"CHEAP").click(function(){$(b).not(c).attr("disabled",!!$(b+c)[1])}) ``` <http://jsfiddle.net/L33JK/16/> EDIT: improved with help from @Daniel Lisik - <https://codegolf.stackexchange.com/a/26805/16278> [Answer] # Javascript (*ES5*) with jQuery - 143 ([Demo](http://jsfiddle.net/_nderscore/69Ted/)) I modified [Matt's solution](https://codegolf.stackexchange.com/a/26785/20160) and golfed it as far down as I think it can go: ``` $("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>")) ``` # Javascript (*ES5*) without jQuery - 185 175 ([Demo](http://jsfiddle.net/_nderscore/bCjn4/)) Using jQuery is kind of cheating, so here's a solution without it: ``` (d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick='for(b in a=d.querySelectorAll(\"input:not(:checked)\"))a[b].disabled=!a[1]'>")) ``` --- If we're allowed to prevent the user from checking the 3rd box instead of actually disabling the field, we can make it even shorter: # With jQuery - 126 123 ([Demo](http://jsfiddle.net/_nderscore/xfj7U/)) ``` $("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!$(':checked')[2]>")) ``` # Without jQuery - 150 147 ([Demo](http://jsfiddle.net/_nderscore/7W3pG/)) ``` (d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!d.querySelectorAll(':checked')[2]>")) ``` [Answer] ## Dyalog APL (on Windows) (169) This is a static function, to test it if you don't know APL, type `)ed C` and paste this in the edit window, then run `C`. ``` C 'R'⎕WC'Form' 'Select any two',2/⊂S←2/20 1 21 41{('R.',⊃⍵)⎕WC'Button'⍵(⍺1)S'Check'('Event' 'Select' 'F')}¨'Fast' 'Cheap' 'Good' B←R.(F C G) F←{B.Active←X∨2≠+/X←B.State} ``` Newer bits of APL have *long* keywords. I still beat HTML though. Explanation: * `'R'⎕WC'Form' 'Select any two',2/⊂S←2/20`: create a form `R`, with title *Select any two* and size and position `20 20`. Also stores `20 20` in `S`. * `1 21 41{`...`}¨'Fast' 'Cheap' 'Good'`: for each of these pairs of data (name and y-coordinate, which are the only variables that differ between the checkboxes: + `('R.',⊃⍵)⎕WC'Button'`: create a button within `R` with the first letter of the name, + `⍵(⍺1)S'Check'`: with the right argument as the title, `(left arg, 1)` as position, reusing `S` as the size and `Check` as style, + `('Event' 'Select' 'F')`, which calls the function `F` when clicked. * `B←R.(F C G)`: use `B` as an abbreviation for the three checkboxes we created * `F←{`...`}`: define the callback function as: + `X←B.State`: get the state for each checkbox and store them in `X`, + `X∨2≠+/X`: sum X, if this is not equal to two all checkboxes must be active, if it is equal to two only checked checkboxes must be active + `B.Active←`: enable or disable the checkboxes Result: ![screenshot](https://i.stack.imgur.com/wvvzo.png) [Answer] # Python ~~3~~ 2, ~~454~~ ~~434~~ ... ~~393~~ 392 bytes I thought, *Python must be shorter than Java.* Here is the "proof" (~~*EDIT:* now it really is shorter~~): ``` from Tkinter import* t=Tk() r=str.replace exec r(r(r(r('a@b@c@l=Label(t,text="SELECT ANY TWO");A`FAST|a);B`CHEAP|b);C`GOOD|c);l^A^B^C^','`','=Checkbutton(t,text="'),'|','",v='),'^','.pack();'),'@','=IntVar();') def f(p,b,B,s): for i in 0,1,2: y=b[i].get() if p[i]-y: p[i]=y;s-=1 if p[i]:s>0and B[i].toggle();s+=2 t.after(1,f,p,b,B,s) t.after(1,f,[0]*3,[a,b,c],[A,B,C],0) t.mainloop() ``` For those of you curious as to what the `exec` expression actually executes, it executes this (this is what the replaces do to the string. Newlines added for readability): ``` a=IntVar(); b=IntVar(); c=IntVar(); l=Label(t,text="SELECT ANY TWO"); A=Checkbutton(t,text="FAST",v=a); B=Checkbutton(t,text="CHEAP",v=b); C=Checkbutton(t,text="GOOD",v=c); l.pack(); A.pack(); B.pack(); C.pack(); ``` This uses the same logic as my Java answer: unselect the checkbox if it causes more than 2 checkboxes to be selected. ~~Unf~~ ~~Fortunately~~ Unfortunately, I spent ~~more~~ ~~less~~ more bytes doing this. ![enter image description here](https://i.stack.imgur.com/uAXLd.png) **EDITS:** 1. massive adjustment of code to use `exec`, saving a whopping 1 byte! 2. switched to python 2 to squeeze two bytes from the `exec` (removing parentheses). 3. more golfing. Includes changing `range(3)` to `0,1,2` and changing the indentation to have one layer of tabs. Unsure if `\t\t` would work instead of `\t__`(`_` is the space character). Finally reached the longest my Java answer ever was. 4. used [replace trick](https://codegolf.stackexchange.com/a/26834/9498) 5. used [Bakiru's suggestion](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two#comment59602_26790), and golfed some more. Actually made it shorter than Java! But now, the Java answer got golfed more, so this is again longer. :-( 6. used [improved replace trick](https://codegolf.stackexchange.com/a/27044/9498). 7. changed a `!=` for a `-`. [Answer] # Rebol, 219 197 ``` load-gui p: func[p][p/state/value]x: func[v][if all[p a p b p c][set-face v false]] view [title"SELECT ANY TWO"a: check"FAST"on-action[x a]b: check"CHEAP"on-action[x b]c: check"GOOD"on-action[x c]] ``` Ungolfed: ``` load-gui ;; this is temporary while r3-gui is in beta p: func [p] [p/state/value] x: func [v] [ if all [p a p b p c] [set-face v false] ] view [ title "SELECT ANY TWO" a: check "FAST" on-action [x a] b: check "CHEAP" on-action [x b] c: check "GOOD" on-action [x c] ] ``` This is the Rebol 3 View dialect (r3-gui). Screendump below from Ubuntu Linux: ![example of rebol 3 view](https://i.stack.imgur.com/RvCX8.png) **Update** - Thanks to Earl & Graham from Rebol SO Chatroom for shaving 22 chars of the code - <http://chat.stackoverflow.com/transcript/message/16345039#16345039> [Answer] # Java, ~~421~~ ... ~~369~~ 351 bytes ``` import java.awt.*;class F extends Checkbox{F(String s){super(s);}public static void main(String[]a){new Frame(){{add(new Panel(){{add(new Label("SELECT ANY TWO"));F[]c={new F("FAST"),new F("CHEAP"),new F("GOOD")};for(F b:c){add(b);b.addItemListener(e->{int x=0;for(F d:c)x+=d.getState()?1:0;if(x>2)((F)e.getSource()).setState(1<0);});}}});}}.show();}} ``` Java... because Java. Nicer looking code: ``` import java.awt.*; class F extends Checkbox { F(String s) { super(s); } public static void main(String[] a) { new Frame() { { add(new Panel() { { add(new Label("SELECT ANY TWO")); F[] c = {new F("FAST"), new F("CHEAP"), new F("GOOD")}; for (F b: c) { add(b); b.addItemListener(e -> { int x = 0; for (F d: c) { x += d.getState() ? 1 : 0; } if (x > 2) ((F) e.getSource()).setState(1 < 0); }); } } }); } }.show(); } } ``` Sample run (different sizings of the window, first is on startup): ![enter image description here](https://i.stack.imgur.com/1a0AY.png) ![enter image description here](https://i.stack.imgur.com/UGuvA.png) ![enter image description here](https://i.stack.imgur.com/LsD3O.png) The checkboxes are arranged horizontally; [this is allowed](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two/26786#comment59367_26786). It would take much more to align it properly. Also, [I'm disabling by unchecking the box when it is clicked](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two/26786#comment59369_26786), not by making it impossible to be clicked. **EDITS:** 1. saved 3 bytes by making the main class extend `Checkbox`. 2. reread [Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax) and realized that the type name was unnecessary. Take that Python! 3. converted a `while` loop to a foreach loop (thanks [Lee](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two#comment59876_26786)); why didn't I think of that before? 4. saved 18 bytes by using an anonymous class and an instance initalizer for both the `Frame` and `Panel`. [Answer] # C++11/Qt5.2 - ~~561~~ ~~481~~ ~~433~~ ~~423~~ 369 Because why not. Shockingly, as of now we are shorter than Python, and the non-buggy C#, and tied with Java! Credits to EveBird for cutting it down from 561 to 481. And once more EveBird shortens it from 481 to 433! Took a few off with a lambda connect Down to 389 with C++11 initializers And 373 without the separate class Removed a few spaces - 369 ## Golf'd: ``` #include<QtWidgets> #define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2); #define S(x)l.addWidget(&x); #define X(x)S(x);x.connect(&x,&QCheckBox::clicked,[&](){C(g,f,c)C(g,c,f)C(f,c,g)}); int main(int n,char**v){QApplication a(n,v);QWidget m;QLabel t{"Select any two"};QCheckBox g{"Good"},f{"Fast"},c{"Cheap"};QVBoxLayout l(&m);S(t)X(g)X(f)X(c)m.show();a.exec();} ``` ## Sort of Un-Golfed: ``` #include<QtWidgets> #define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2); #define S(x)l.addWidget(&x); #define X(x)S(x);connect(&x, &QCheckBox::clicked, [&](){C(g,f,c)C(g,c,f)C(f,c,g)}); int main(int n,char**v){ QApplication a(n,v); QWidget m; QLabel t{"Select any two"}; QCheckBox g{"Good"},f{"Fast"},c{"Cheap"}; QVBoxLayout l(&m); S(t)X(g)X(f)X(c)m.show(); a.exec(); } ``` ![GFC](https://i.stack.imgur.com/z1cOl.png) [Answer] # CoffeeScript - ~~167~~, 154 CoffeeScript port of **[@Matt](https://codegolf.stackexchange.com/a/26785/15909)**'s answer. ``` b="input";a="<input type=checkbox>";c=":checked";$("body").html("SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP").click ->$(b).not(c).attr "disabled",!!$(b+c)[1] ``` Somewhat ungolfed: ``` b = "input" a = "<input type=checkbox>" c = ":checked" $( "body" ).html( "SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP" ).click -> $( b ).not( c ).attr "disabled", !!$( b + c )[1] ``` [JSFiddle](http://jsfiddle.net/W9fQE/1/). [Answer] # PHP, Javascript, jQuery - 135b I was admiring @nderscore's answer, but then I decided to copy and one-up him. ``` <?echo"SELECT ANY TWO".($m="<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>")."FAST$m GOOD$m CHEAP"?> ``` Basically I replaced his `.join` trick with some PHP Hypertext Preprocessing. [Answer] # Ruby, ~~219~~ 218 bytes I use the same Tk widgets as the [Python 3 answer](https://codegolf.stackexchange.com/a/26790/4065) by Quincunx. This program breaks the rules because it has a **check box list**. (The rules said, "Don't use a check box list.") Yes, `a` is an array of 3 TkCheckButton objects, and I believe that an array is a list. My defense is that I did not use any existing check box list, but I used the standard check boxes and made my own list. ``` require'tk' o=->(c){c.variable.value>?0} TkLabel.new{text'SELECT ANY TWO' pack} a=%w[FAST CHEAP GOOD].map{|t|TkCheckButton.new{text t command{a.map{|c|c.state a.count(&o)<2||o[c]?:normal: :disabled}} pack}} Tk.mainloop ``` ![CHEAP and GOOD checked, but FAST disabled](https://i.stack.imgur.com/zzX7j.png) I tested with Ruby 2.1.0 and Tk 8.5.15. * `o[c]` is a predicate to test if check button `c` is selected. With the default strings, `c.variable.value` is `'0'` or `'1'`, so the string comparison is only true if `'1'>'0'`. EDIT: I saved 1 byte (219 down to 218) by changing `'0'` to `?0`. In Ruby, `?0` is a character constant. * `a.count(&o)` uses the predicate to count the selected check buttons. * When the user toggles a check button, the command calls `a.map` to loop for all buttons, making them `:normal` or `:disabled`. [Answer] Thanks to Rotem and Johnbot for the golfing help! # C# ~~343~~ 334 This one uses the same "cheat" as Quincunx's [Java answer](https://codegolf.stackexchange.com/a/26786/4163) - the checkboxes aren't actually disabled; they just don't allow you to check them if that check makes 3. ``` using System.Windows.Forms;using System.Linq;class P:Form{static void Main(){P p=new P();p.Text="SELECT ANY TWO";int y=0;var a=new CheckBox[3];foreach(var n in "FAST CHEAP GOOD".Split()){var c=new CheckBox();a[y]=c;c.Top=y++*50;c.Text=n;c.Validating+=(s,e)=>{if(a.Count(b=>b.Checked)>1)e.Cancel=true;};p.Controls.Add(c);}Application.Run(p);}} ``` There's also a minor bug that you can't close the window after selecting the third checkbox unless you unselect one, because the validation won't pass. But this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so who cares? ;) # C# ~~403~~ ~~397~~ 374 This is a proper one that actually disables the third checkbox. ``` using System.Windows.Forms;using System.Linq;class P:CheckBox{static void Main(){var p=new Form{Text="SELECT ANY TWO"};P[]a=null;a="FAST CHEAP GOOD".Split().Select((x,i)=>{var c=new P{Top=i*50,Text=x};c.Click+=(s,e)=>{a.First(b=>!b.Checked).Enabled=a.Count(b=>b.Checked)>1?1<0:a.All(b=>b.Enabled=0<1);};p.Controls.Add(c);return c;}).ToArray();Application.Run(p);}} ``` ![Screenshot](https://i.stack.imgur.com/EoCKP.png) Kinda ungolfed: ``` using System.Windows.Forms; using System.Linq; class P:Form { static void Main() { P p = new P(); p.Text = "SELECT ANY TWO"; int y = 0; var a = new CheckBox[3]; foreach (var n in "FAST CHEAP GOOD".Split()) { var c = new CheckBox(); a[y] = c; c.Top = y++ * 50; c.Text = n; c.Click += (s, e) => { if (a.Count(b => b.Checked) == 2) { a.First(b => !b.Checked).Enabled = false; } else { foreach (var b in a) b.Enabled = true; } }; p.Controls.Add(c); } Application.Run(p); } } ``` [Answer] # AngularJS - 214 ``` <input type=checkbox ng-model=fast ng-disabled=cheap&&good>FAST</input> <input type=checkbox ng-model=cheap ng-disabled=fast&&good>CHEAP</input> <input type=checkbox ng-model=good ng-disabled=fast&&cheap>GOOD</input> ``` [Answer] ## JavaScript (with jQuery) - 224, 222, 210, 205, 178 ``` a="<input type=checkbox>",c=":checked",e="input",f="disabled",d=$("body").html("SELECT ANY TWO"+a+" FAST"+a+"CHEAP"+a+"GOOD").click(function(){$(e).not(c).attr(f,$(e+c).length>1)}) ``` Thanks to a comment from brilliant @Matt I reduced the code by 27 characters. **[JSFiddle](http://jsfiddle.net/z9vGn/4/)** [Answer] **Mathematica** A more code-golfed version as suggested by David, **255 characters**: ``` h = Checkbox; i = Dynamic; j = Enabled; t = True; i[ If[Total@Boole@{a, b, c} == 2, {d, e, f} = {a, b, c}, {d, e, f} = {t, t, t} ]; Row@{ "SELECT ANY TWO", h[i@a, j -> d], "FAST", h[i@b, j -> e], "CHEAP", h[i@c, j -> f], "GOOD" } ] ``` [Answer] # k3 - 95 ``` a[`FAST`CHEAP`GOOD]:0 a[.;`c]:`check a..l:"SELECT ANY TWO" a..t:"if[3=+/a[];.[_v;_i;:;0]]" `show$`a ``` [code is here](http://nsl.com/k/anytwo.k) [![sample run](https://i.stack.imgur.com/10k24.jpg)](https://i.stack.imgur.com/10k24.jpg) (source: [nsl.com](http://nsl.com/k/anytwo.jpg)) [Answer] # C#, 335 333 326 320 308 Based off Bobs Answer, mine does use fewer characters than his (335 v 342), but I might not understand fully how to count this. ``` using System.Linq;using System.Windows.Forms;class P:Form{static void Main(){new P();}P(){Text="SELECT ANY TWO";var a="FAST CHEAP GOOD".Split().Select(r=>new CheckBox{Text=r,Top=r[0]%9*20}).ToList();a.All(r=>{r.Validating+=(b,c)=>c.Cancel=a.Count(z=>z.Checked)>1;Controls.Add(r);return 1>0;});ShowDialog();}} ``` Ungolfed ``` using System.Linq; using System.Windows.Forms; class P : Form { static void Main() { new P(); } P() { Text = "SELECT ANY TWO"; var a = "FAST CHEAP GOOD".Split().Select(r => new CheckBox { Text = r, Top = r[0] % 9 * 20 }).ToList(); //loops, I dont need no stinking loops a.All(r => { r.Validating += (b, c) => c.Cancel = a.Count(z => z.Checked) > 1; Controls.Add(r); return 1 > 0; }); ShowDialog(); } } ``` [Answer] # mIRC script (727 719 bytes) Forgot about this language until a drunken conversation last night. ``` alias select_two { dialog -m s2 s2 } dialog s2 { title "Select any two:" size -1 -1 200 100 check "Fast",1, 5 10 170 25 check "Cheap",2, 5 30 170 25 check "Good",3, 5 50 170 25 } on *:dialog:s2:sclick:*: { if ($did(s2, $did).state = 1) { if ($did = 1) { if ($did(s2, 2).state = 1) { did -b s2 3 } if ($did(s2, 3).state = 1) { did -b s2 2 } } if ($did = 2) { if ($did(s2, 1).state = 1) { did -b s2 3 } if ($did(s2, 3).state = 1) { did -b s2 1 } } if ($did = 3) { if ($did(s2, 1).state = 1) { did -b s2 2 } if ($did(s2, 2).state = 1) { did -b s2 1 } } } if ($did(s2, $did).state = 0) { did -e s2 1 did -e s2 2 did -e s2 3 } } ``` More should be coded in this language! But there needs to be a way to make this into a real mess so it can be as good as Perl. Edit: noticed that my Python-isms are leaking through and was able to reduce the code by 8 bytes! [Answer] ## Groovy - 357 221 217 chars I've ported [Quincunx's solution](https://codegolf.stackexchange.com/a/26786/21004) to Groovy 2.2.1, using [SwingBuilder](http://groovy.codehaus.org/Swing+Builder) (and made it even more Groovier): ``` c=[];new groovy.swing.SwingBuilder().frame(){panel(){label("SELECT ANY TWO");f={if(c.count{it.isSelected()}>2)it.source.setSelected(1<0)};["FAST","CHEAP","GOOD"].each{c<<checkBox(label:it,itemStateChanged:f)}}}.show() ``` Ungolfed: ``` c=[] new groovy.swing.SwingBuilder().frame() { panel() { label("SELECT ANY TWO") f = { if (c.count{it.isSelected()} > 2) it.source.setSelected(1<0) } ["FAST","CHEAP","GOOD"].each { c << checkBox(label: it, itemStateChanged: f) } } }.show() ``` [Answer] ## QML - 369 315 254 251 248 bytes Here goes QML (QtQuick 2.0) version, given only the .qml file contents. This code requires Qt 5.1 at least to run. Not a big deal as its huge compared to other solutions (**248 bytes**), but it's a full featured cross-platform application (Android and iOs included)! :D ``` import QtQuick 2.0;import QtQuick.Controls 1.1;Row{Text{text:"SELECT ANY TWO"}CheckBox{id:a;text:"FAST";enabled:!b.checked|!c.checked}CheckBox{id:b;text:"CHEAP";enabled:!a.checked|!c.checked}CheckBox{id:c;text:"GOOD";enabled:!b.checked|!a.checked}} ``` ![Horizontal layout dialog](https://i.stack.imgur.com/eH54V.png) To run it, save the code to a .qml file, install Qt 5.1 and run qmlscene.exe (or just qmlscene on linux), which will show an open file dialog. Chose the .qml file you've saved the code to and see the awesome result! :D [Answer] # JavaScript / jQuery 237 234 229 Very similar approach as [Matt's answer](https://codegolf.stackexchange.com/a/26785/6520), although a little longer. ``` $(function(){var e="input ",t="disabled",n,r;$("body").html("SELECT ANY TWO|FAST|CHEAP|GOOD".replace(/\|/g,"<"+e+'type="checkbox">'));n=$(e);n.change(function(){n.removeAttr(t);r=$(":checked");if(r.length>1)n.not(r).attr(t,t)})}) ``` [Answer] # JavaScript 209 (was 346) Shortened: thanks for comments. ``` function f(){var a=document.getElementsByClassName("x"),n=0,i=0;for(i in a){if(a[i].checked)n++;}if(n<2){for(i in a){a[i].disabled=false;}}else{for(i in a){i(false===a[i].checked){a[i].disabled=true;break;}}}} ``` Golfed function: ``` function f(a,b,c){ var x=document.getElementById(a); var y=document.getElementById(b); var z=document.getElementById(c); var n=0,i=0; var a=[x,y,z]; for(i in a) { if(a[i].checked) n++; } if(n<2) { for(i in a) { a[i].disabled=false; } } else { for(i in a) { if(false===a[i].checked) { a[i].disabled=true; break; } } } } ``` HTML form: provides input and calls the function. \* Form now uses class=x to group inputs. ``` <form> SELECT ANY TWO<br> FAST <input id="a" type="checkbox" class="x" value="0" onchange="f()"><br> CHEAP <input id="b" type="checkbox" class="x" value="1" onchange="f()"><br> GOOD <input id="c" type="checkbox" class="x" value="2" onchange="f()"><br> </form> ``` Tested with NetBeans and Chrome. [Answer] # Groovy Based on the Java version, but much slimmed down ;) Types were replaced by 'def', semicolons removed, add replaced by <<, the 1<0 replaced by 0, collect for creating the checkboxes, removed the itemevent type, removed casting the checkbox, enhanced the loops. ``` import java.awt.* class F { def static main(a) { def f = new Frame() def p = new Panel() f << p p << new Label("SELECT ANY TWO") def c = ['FAST','CHECK','GOOD'].collect { new Checkbox(it) } c.each { b -> p << b b.addItemListener { e-> int x = 0, i = 0 3.times { x += c[it].state ? 1 : 0 } if (x > 2) { e.source.state = 0 } } } f.show() } } ``` [Answer] # TCL 347 At least it beats Python and Java. ``` set d . proc a v {upvar f f c c g g d d $v x if $x&&$f+$c+$g==2 {set d .$f$c$g $d configure -state disabled} if !$x {$d configure -state normal}} set z -variable set y -command set x checkbutton label .l -text {SELECT ANY TWO} $x .011 -text FAST $z f $y a\ f $x .101 -text CHEAP $z c $y a\ c $x .110 -text GOOD $z g $y a\ g pack .l .011 .101 .110 ``` Note: if you start by selecting one checkbox and immediately unselecting it, you will get an error. You can fix it by adding `110` to the end of the first line. Ungolfed: ``` # Keep track of the last disabled button. Set it to something valid to start with. set last .110 proc toggled name { # Access some globals upvar fast fast upvar cheap cheap upvar good good upvar last last upvar $name value # Just toggled one on, check if exactly two are now on if {$value == 1 && ($fast + $cheap + $good) == 2} { set last .$fast$cheap$good $last configure -state disabled } # Just toggled one off. Re-enable disabled one. if {$value == 0} { $last configure -state normal } } label .label -text {SELECT ANY TWO} checkbutton .011 -text FAST -variable fast -command {toggled fast} checkbutton .101 -text CHEAP -variable cheap -command {toggled cheap} checkbutton .110 -text GOOD -variable good -command {toggled good} pack .label .011 .101 .110 ``` [Answer] ## Javascript + Knockout: ~250 Characters ``` a=function(i){return "<input type=checkbox data-bind='value: "+i+", checked: x, disable: x().length>=2 && x().indexOf(\""+i+"\")==-1'>"},document.body.innerHTML = "SELECT ANY TWO"+a(0)+"Fast"+a(1)+"Good"+a(2)+"Cheap"; ko.applyBindings({x:ko.observableArray([])}) ``` * [Fiddle](http://jsfiddle.net/origineil/p5dNF/) [Answer] # AngularJS - 155 ([Demo](http://jsfiddle.net/Blackhole/at4kz/)) ``` SELECT ANY TWO :<i ng-init=t=[]><p ng-repeat="(i,v) in ['FAST','CHEAP','GOOD']"><input type=checkbox ng-disabled=t[(i+1)%3]&&t[(i+2)%3] ng-model=t[i]>{{v}} ``` The ungolfed version: ``` SELECT ANY TWO : <i ng-init="checkedArray = []" /> <!-- A useless tag to initialize the array (which can't be done on the `input` tag, unfortunately) --> <p ng-repeat="(key, value) in ['FAST', 'CHEAP', 'GOOD']"> <input type="checkbox" ng-model="checkedArray[key]" ng-disabled="checkedArray[(key + 1) % 3] && checkedArray[(key + 2) % 3]" /> {{value}} </p> ``` [Answer] # Ruby with Shoes, 133 characters ``` Shoes.app{para'SELECT ANY TWO' $o=%w{FAST GOOD CHEAP}.map{|q|c=check{|c|$o[c]=!$o[c];$o.values.all?&&c.checked=p} para q [c,p]}.to_h} ``` Sample output: ![Shoes window screenshot](https://i.stack.imgur.com/KuxCL.png) [Answer] # FLTK, 303 characters ``` decl{int c;}Function{}{}{Fl_Window{}{xywh {9 9 195 195}}{Fl_Pack{}{label{SELECT ANY TWO}}{Fl_Check_Button{}{callback{e(o);}label FAST}Fl_Check_Button{}{callback{e(o);}label GOOD}Fl_Check_Button{}{callback{e(o);}label CHEAP}}}}Function{e(Fl_Button*o)}{}{code{if((c+=o->value()*2-1)>2){o->value(0);c--;}}} ``` Ungolfed: ``` decl { int c; } Function {} {} { Fl_Window {} { xywh {9 9 195 195} } { Fl_Pack {} { label {SELECT ANY TWO} } { Fl_Check_Button {} { callback { e(o); } label FAST } Fl_Check_Button {} { callback { e(o); } label GOOD } Fl_Check_Button {} { callback { e(o); } label CHEAP } } } } Function { e(Fl_Button* o) } {} { code { if ((c += o->value() * 2 - 1) > 2) { o->value(0); c--; } } } ``` Sample output: ![FLTK window screenshot](https://i.stack.imgur.com/U3Tp6.png) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/20034/edit). Closed 6 years ago. [Improve this question](/posts/20034/edit) **Introduction**: Deep Thought calculated *The answer to life the universe and everything* in a period of 7.5 million years, the solution was **`42`**. Write a program in any programming language that takes approx `75` seconds to calculate, starting from whatever you want, and output the number **`42`**. N.B. The number `42` must be calculated somehow (random numbers, whatever you prefer), not just hard-coded in your script. As suggested, you can't use `sleep` or equivalent functions. Be inventive. [Answer] This takes about 75s on a raspberry pi overclocked to 1GHz ``` #!/usr/bin/env python from itertools import product, count for n in count(1): i = 0 for a, b, c, d in product(range(n), repeat=4): if a > b > c > d > 0 == (a*b-c*d)%n == (a*c-b*d)%n == (a*d-b*c)%n: i += 1 if i == n: break print i ``` It works because: > > 42 is the only known value that is the number of sets of four > distinct positive integers a,b,c,d, each less than the value itself, > such that ab-cd, ac-bd, and ad-bc are each multiples of the value. > Whether there are other values remains an open question > > > <http://www.mathpages.com/home/kmath255.htm> [Answer] ## Python 2.7 To answer the question, one must *know* the question - and the question is: > > What do you get when you multiply six by nine? Thanks to TRiG for the correction > > > So **Deep Thought** relies on the [handy use of base 13](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#The_number_42): > > 613 x 913 = 4213 > > > We import our constants: ``` from random import randrange as scrabbleBag, randint from datetime import datetime,timedelta life,universe,everything,nothing=6,9,1,-3 endOfTheUniverse = 80 ``` We also define our earth-things, being a **bag of scrabble tiles**, **Arthur** (a predictable albeit it slightly odd, computer of sorts), **Trillian** (our rational heroine), ``` tile = lambda i: scrabbleBag(26) arthur = lambda i: int(`i`,life+universe+everything+nothing) trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing))) ``` We introduce **Zaphod** - a random sort, who eventually runs out of steam as we near the `endOfTheUniverse`. ``` zaphod = lambda : not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3)) ``` And **Marvin the Paranoid Android**, whose positive attitude could stop any party: ``` marvin = lambda : endOfTheUniverse<(datetime.now() - start).seconds ``` And we continue to run these 4 characters through the mix until they compute ***it***: ``` while answer is not life * universe * everything: rack = sum(tile(i) for i in range(7)) answer = (zaphod or marvin) and arthur(rack) print trillian(answer) ``` ## The complete `deepthought.py`: ``` from random import randrange as scrabbleBag, randint from datetime import datetime,timedelta life,universe,everything,nothing=6,9,1,-3 endOfTheUniverse = 80 tile = lambda i: scrabbleBag(26) arthur = lambda i: int(`i`,life+universe+everything+nothing) trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing))) start = datetime.now() zaphod = lambda: not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3)) marvin = lambda: endOfTheUniverse<(datetime.now() - start).seconds answer = None while answer is not life * universe * everything: rack = sum(tile(i) for i in range(7)) answer = (zaphod() or marvin()) and arthur(rack) print trillian(answer) ``` This should finish somewhere around the 75 second mark, definitely finishing by 80 seconds. Sometimes earlier to to Zaphods *Infinite Improbability Drive*. [Answer] # DOS Batch — the answer to life, the Universe and everything Thanks to mynameiscoffey for his simplification! Save as `answer.bat`: ``` @ ping 127.0.0.1 -n 76 >nul && @ echo %~z0 ``` Then run it, and wait 75 seconds: ``` > answer 42 ``` [Answer] # Bash (OS X) This could probably be ported to other systems without too much trouble. Replace `say` with whatever you're using as a text-to-speech command line utility. The `-f` option takes input from a named file. With a bit of luck, it might even output the correct number :-) This takes almost exactly 1 minute 15 seconds to run on my system (OS X 10.5). ``` #!/bin/bash grep -E '^life|universe|and.everything|[ultimate]question$' /usr/share/dict/words | sed 's/$/,/' | nl > "$TMPDIR/deepthought" say -v Alex -f "$TMPDIR/deepthought" nw=`cat $TMPDIR/deepthought | wc -l` say -v Alex "The answer, to the ultimate question, is: $nw" echo $nw rm "$TMPDIR/deepthought" ``` [Answer] ## MATLAB This is a tough one. Since we do not really know the question, the only viable method of getting the answer is by means of a global optimisation method. In this case I opted for the [simulated annealing](http://en.wikipedia.org/wiki/Simulated_annealing) method, since this one has given me nice answers to tough questions before. All this code is doing is looking for the optimal value of a function which input is life itself. And the amazing thing is that it works. So, did I just validate Deep Thought? ``` tic; the_answer=round(simulannealbnd(@(life)abs(3.7376696-log(life)),140489, ... -inf,inf,saoptimset('MaxFunEvals',10^16))) toc; ``` Output: ``` the_answer = 42 Elapsed time is 74.892428 seconds. ``` [Answer] # C - 1089 bytes ``` #include <time.h> #include <stdio.h> int answer(int the) { int to = 0; while (the != 0) { to *= 10; to += the%10; the /= 10; } return to; } int optimism(int the) { return abs(the); } int getRandomNumber() { return 4; // chosen by fair dice roll. // guaranteed to be random. } int main() { // initialize int life = getRandomNumber(), universe, everything; // get inverse answer int question = clock(); while (clock()-question < CLOCKS_PER_SEC*75) { life += getRandomNumber(); } life = optimism(life); // optimism is the best way to see life life %= 1000; // avoids unwanted race conditions with the answer by "Lego Stormtroopr" if (life<100 || life>997) {life -= getRandomNumber()*100;} if (optimism(life/100%10 - life%10) < 2) {life += getRandomNumber();} universe = answer(life); everything = optimism(life<universe?life-universe:universe-life); printf("%d\n", (answer(everything)+everything+3)/26); return 0; } ``` --- ## Compressed: ``` #include <time.h> int f(int d) { int e = 0; while (d != 0) e = e*10+d%10, d /= 10; return e; } int main() { int a = 4, b, c, d = clock(); while (clock()-d < CLOCKS_PER_SEC*75) a += 4; a = abs(a)%1000; a -= a<100||a>997?400:0; a += abs(a/100%10-a%10)<2?4:0; b = f(a); c = abs(a<b?a-b:b-a); return (f(c)+c+3)/26; } ``` [Answer] # Ruby ``` t = Time.new.to_i n = 0 loop{ break if Random.new(n).rand(2000000) == Random.new(374076).rand(1000000) n += 1 } puts Random.new(n).rand(2000000) puts "Took #{Time.new.to_i - t} seconds; seed was #{n}" ``` Output on my machine: ``` 42 Took 123 seconds; seed was 3771996 ``` This abuses the RNG. ;) [Answer] # C ``` #include <stdio.h> #include <time.h> int i, j; int main() { i = clock(); while(clock() - i < 75 * CLOCKS_PER_SEC); for(i = j = 0 ; i < 48 ; i++) j += "The answer to Life, the Universe, and everything"[i]; printf("%i", j % 157); } ``` [Answer] ## JavaScript - Finding "the answer to life and everything" by solving an equation Let's have a look at this equation : ``` 1 / p + 1 / q + 1 / r = 1 / 2 ``` There is many solutions, but if you want `r` to be as big as possible and `p`, `q` and `r` to be naturals there is only two solutions : `1/3 + 1/7 + 1/42 = 1/2` and `1/7 + 1/3 + 1/42 = 1/2` with `p <= q <= r`, there is only one solution and `r` always equal to `42` What is the most (in)efficient way to solve a equation ? By trying all possibles values ! Here is the code : ``` var n = Math.pow(2, 32); for (var i = 1; i <= n; i++) { for (var j = 1; j <= n; j++) { for (var k = 1; k <= n; k++) { if ((1 / i + 1 / j + 1 / k) == 1 / 2) throw k; } } } ``` How much time will it take ? To be honest, I do not know because I have not been able to run it to the end. However, you can try with small `n` values (it has to be bigger or equal to `42`) and you will get correct result. For small values such as `n = 2000`, it takes almost one minute on my laptop. So i guess with big values given in the example it will take days, weeks, or even years !!! **Finding the solution in approximately 75 seconds :** One requirement from initial question is it should take approximately 75 sec to execute. One way to achieve this is to automatically adjust the complexity of the algorithm over the time : ``` var now = new Date().getTime(); var iterations = 0; var n = Math.pow(2, 32); for (var i = 1; i <= n; i++) { for (var j = 1; j <= n; j++) { for (var k = 1; k <= n; k++) { if ((1 / i + 1 / j + 1 / k) == 1 / 2) throw k; if (new Date().getTime() - now > 1000) //one second has elapsed { now *= 2; //never wanna see you again n = 42; //this is the minimum while(3 * n * n + 7 * n + 42 < iterations * 74) n++; i = j = k = 0; //reset } iterations++; } } } ``` How it works (for the curious) : it checks how many iterations have been done in one second, then multiply this by 74 and adjust `n` to match that value. eg : if it take one second to do 500 iterations, it will take 10 seconds to do 5000 iterations. Note that it multiply by 74 not 75 because we already spent one second for "benchmarking". [source and credits for math](http://www.math.ucr.edu/home/baez/42.html) [Answer] C# - 151 Characters ``` class P { static void Main() { var w = new System.Diagnostics.Stopwatch(); w.Start(); while (w.ElapsedMilliseconds < 75000); System.Console.Write((int)'*'); } } ``` [Answer] **C++** Calculates the [partitions](http://en.wikipedia.org/wiki/Partition_%28number_theory%29) of [10](http://www.wolframalpha.com/input/?i=partition%2010) via a rather inefficient method. Took 130s to run in a Release build on my system but someone with a sufficiently fast PC should be able to run it in ~75s... ``` #include <algorithm> #include <iostream> #include <numeric> #include <set> #include <vector> using namespace std; bool NextPermutationWithRepetition(vector<int>& perm, int n) { int carry = 1; auto it = begin(perm); while (it != end(perm) && carry) { ++*it; carry = (*it - 1) / n; *it = ((*it - 1) % n) + 1; ++it; } if (carry) { if (perm.size() == n) return false; perm.push_back(carry); } return true; } int main() { vector<int> perm; set<vector<int>> uniquePartitions; const int n = 10; while (NextPermutationWithRepetition(perm, n)) { if (accumulate(begin(perm), end(perm), 0) == n) { auto sortedPerm = perm; sort(begin(sortedPerm), end(sortedPerm)); uniquePartitions.insert(sortedPerm); } } cout << uniquePartitions.size() << endl; } ``` [Answer] ## Javascript This will take a while to alert something ... but it's worth since it will show you The answer to life the universe and everything! ``` var x = 0, b = document.body.children[0]; var theAnswer = function(){ b.textContent = ++x; if(x == 125774) alert(Math.pow(x, 1/Math.PI)).toFixed(0); else setTimeout(theAnswer); }; theAnswer(); ``` [Demo](http://codepen.io/rafaelcastrocouto/pen/HKurF "Codepen") [Answer] # Python Sometimes an answer is only clear at the very end of a calculation, but aspects of it are visible before termination. And little known is the sequence of inputs Deep Thought was seeded with: 271, 329, 322, 488, 79, 15, 60, 1, 9 Hence: ``` from datetime import datetime n = datetime.now o = n().second def bs(x,n,t,f): return ([t]+bs(x-2**(n-1),n-1,t,f) if x>=2**(n-1) else [f]+bs(x,n-1,t,f)) if n>0 else [] u = [271,329,322,488,79,15,60,1,9,'#',' ','',] for i, g in enumerate(u[:5]): while n().second!=(o+(i+u[7])*u[5])%u[6]: pass # the dice print u[11].join(bs(g,*u[8:11])) ``` Et voila - the answer is provided after 75 seconds. [Answer] ## Assembly (linked by gcc) On a sufficiently slow computer (CPU speed ~2Hz) this should take around 75 seconds to run: ``` .globl main main: movl $52, %edx movl $0, %edi l4: addl $1, %edi cmp %edx, %edi jl l4 call putchar movl $50, %edx movl $0, %edi l2: addl $1, %edi cmp %edx, %edi jl l2 call putchar movl $10, %edx movl $0, %edi ln: addl $1, %edi cmp %edx, %edi jl ln call putchar ret ``` [Answer] # Bash and Linux utils: ``` #!/bin/bash if [ $(uname) == "Linux" ]; then : $(arecord -q | head -c 600000) man -s4 random | head -n1 | tr -d ' ' | wc -c else echo "Deep Thought didn't run $(uname)" fi ``` Deep Thought is listening carefully all the way through the calculation. [Answer] # Java (227 characters) Who says that bitwise manipulations are not fun? Or that java can't be confusing? We loop for 75 seconds and then boom the answer. ``` public class T{public static void main(String[]b){long d=(1<<16^1<<13^1<<10^31<<3);long t=System.currentTimeMillis();long e=t+d;for(;e>System.currentTimeMillis();){}d=d%((((d&~(1<<16))>>7)^(1<<4))^1<<2);System.out.println(d);}} ``` Ungolfed ``` public class T { public static void main(String[] b) { long d = (1 << 16 ^ 1 << 13 ^ 1 << 10 ^ 31 << 3); long t = System.currentTimeMillis(); long e = t + d; for (; e > System.currentTimeMillis();){} d = d % ((((d & ~(1 << 16)) >> 7) ^ (1 << 4)) ^ 1 << 2); System.out.println(d); } } ``` [Answer] # PureBasic In keeping with the fact that different hardware will produce different results, there is no fixed answer for this. I am using an elapsed time function so I know when to stop calculating. Basically, it will calculate the largest two prime numbers when subtracted is 42 Faster your machine, the larger the primes will be :-) ``` OpenConsole() sw = ElapsedMilliseconds() FoundFigure1 = 0 FoundFigure2 = 0 PreviousPrime = 1 For i = 3 To 10000000000 Step 2 PrimeFound = #True For j = 2 To i-1 If i % j = 0 PrimeFound = #False Break EndIf Next If PrimeFound = #True If i - PreviousPrime = 41+1 FoundFigure1 = PreviousPrime FoundFigure2 = i EndIf PreviousPrime = i EndIf If ElapsedMilliseconds() - sw > 75000 Break EndIf Next Print("Answer: ") Print(Str(FoundFigure2 - FoundFigure1)) Input() ``` [Answer] ***MeatSpace*** Pace off a distance which takes approximately 70/4 seconds for your `servant^H^H^H^Hcomputer` (it could be human, dog, or anything that can pick up numeral tiles) to walk. Place a large numeral `4` and a large numeral `2` there. Place your `computer` to the output point. Start the timer, have it walk to the numeral depot and bring back one number at a time. I allocated 5 seconds to pick them up and put them down. [Answer] **Another C# Example** ``` using System; using System.Threading; namespace FourtyTwo { class Program { static void Main(string[] args) { DateTime then = DateTime.Now; Thread.Sleep(42000); DateTime now = DateTime.Now; TimeSpan t = now - then; Console.WriteLine(t.Seconds); } } } ``` [Answer] # Ruby > > A program to add (0.56) power n for 75 times. Value of `n is 1` > > > Where `n=1` should be obtained from any form of `Time diffrence` > > > ``` def solve a=0.56 i=0 t1=Time.now while(i < 75) t1 = Time.now while((b=Time.now-t1) < 1.0) end a += 0.56 ** b.to_i i += 1 end a.to_i end puts solve ``` Using ruby time difference I've verified the execution time which is approx `75.014267762` [Answer] **PHP** ``` <?php set_time_limit(80); ini_set('max_execution_time', 80); //$start=time(); $count=0; do{ $rand=rand(0,(75000000/40+2)); $rand=rand(0,$rand); if(($rand==42 || $rand==75-42 || $rand== floor(75/42)) && (!rand(0,(4*2))) ){ $count++; } }while($count!=42); echo $count; //echo '<br>elapsed time is '.(time()-$start); ?> ``` This is as close as I'm getting tonight. Running it at [tecbrat.com](http://www.tecbrat.com/test1.php), an old IBM NetVista P4 running Ubuntu 10.04, showed 69 seconds and 78 seconds on my last 2 runs. [Answer] # JavaScript (Bitwise obfuscation) (not bad for 136 bytes!) It may be seen as a bit on the cheaty side, but the functions were meticulously thought out, bearing in mind that the 75000ms value would be calculated prior to the functions used to calculate 42. It's quite poetic when you look at it, really :) `setTimeout("alert($=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",($=$=>$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_($($($(-~[]))))))))^-~[])` [Answer] I am not too good with this kind of stuff. I'm an app developer but I've never had any training in C and I mostly make apps that grab stuff from servers and make the information look pretty... I have no idea if this will work and there's a bit of extra code in there because it's in a iphone app and I display a progress hud and an alert view when 42 has been reached: ``` #import "ViewController.h" #import "MBProgressHUD.h" @interface ViewController () @property (nonatomic, retain) MBProgressHUD * hud; -(IBAction)answer:(id)sender; @end int number; int initialCounter; @implementation ViewController @synthesize hud; -(IBAction)answer:(id)sender { hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.mode = MBProgressHUDModeIndeterminate; hud.labelText = @"Calculating"; [self calculate]; number = arc4random(); } -(void)calculate { int random = arc4random(); if (number == 42){ hud.hidden = YES; UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Complete!" message:@"The answer is 42." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [message show]; } else if(number<42){ number = number + random; dispatch_async(dispatch_get_main_queue(), ^{ [self calculate]; }); } else if(number>42){ number = number - random; dispatch_async(dispatch_get_main_queue(), ^{ [self calculate]; }); } } @end ``` ]
[Question] [ Your task is to print the text `Good morning, Green orb!`, with every character repeated in place as many times as the most frequent byte in your source (the mode). A trailing newline is permitted and need not be repeated. For example if your source was ``` print p ``` Since `p` appears twice and every other byte appears once you would need to print ``` GGoooodd mmoorrnniinngg,, GGrreeeenn oorrbb!! ``` Answers will be scored by the product of their byte count and the number of times the output is repeated. For example the above code (if it worked) would score **7\*2 = 14**. The goal should be to minimize one's score. Your code must contain at least 1 byte. [Use this program to verify that your code and output match](https://tio.run/##LY5BasMwEEWvMgpZWGCXZp0okEXQAbosWci1ogzxzJixUmzI3VWlZPHh8d/m3cJ8j@NYkCbRDF/rnCN9nPkXVZgi53KF4Brnmo0XGYBEGTm14DVGBtHebI5Hp3Ea8Sfk2FBYkB70PdftnsuhC@3q3HJ5rhUv1tpCAdkNAkHTfOhSzKcK@0mR8/bavF5jPu0bdraUfwVT8bWgNgwARCKqzIjMKbUtgPdag2oSA7xc3xvzBw "Haskell – Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~384 \* 106~~ 366 \* 100 = 36,600 ``` (((((((()()()))))))(()({}{}{}(([(({}{})){}()]((((({}())){})){}{}()(({})<([{}](((({}()())))([{}]([{}]()((()()())(()()({}()([(({})){}()](((((({}))))({}({}{}{}){})(({}){}()))))<((((([]){}){}){}<>)<>)>[])))))))(((((()()())()){}{}){}){})<>(((({})<>)))>{}{})))))<(<>({})<>)>))(<>((({}))()){}{}<>)<>(((({}<>()))))({}{}{}<>)<>{((<>{}<><({}<>)>)<{({}[()]<(({}))>)}{}>)<>}<>{} ``` [Try it online!](https://tio.run/##TU9BDsIwDPtOfOAHVSXeUe0wuICQOHCt@vZiO90gXdckduLk9tmf78d@f80Zy6CTpqAPnYgWdgEG2MyUp1hXvjIo0frYDtidMuMfToF8zXHr/8YOYTTlJeJsSoIqsrYhsT5KBb/KzDH6b5fIARe31KVAPlBzKbckkmkCYZqgVW2BrOSLNd@J9GCF/GICW5ROr3Glkn0qyBV1iDjnvFy/ "Brain-Flak (BrainHack) – Try It Online") ## Explanation The first thing I do is push the string ``` !bro neerG ,gninrom dooG ``` to the stack using pretty standard brain-flak Kolmogorov-complexity tactics. ``` (((((((()()()))))))(()({}{}{}(([(({}{})){}()]((((({}())){})){}{}()(({})<([{}](((({}()())))([{}]([{}]()((()()())(()()({}()([(({})){}()](((((({}))))({}({}{}{}){})(({}){}()))))<((((([]){}){}){}<>)<>)>[])))))))(((((()()())()){}{}){}){})<>(((({})<>)))>{}{})))))<(<>({})<>)>))(<>((({}))()){}{}<>)<>({}<>()) ``` Then we push a counter to the off stack to tell us how many times to duplicate each character. However I wasn't going to be able to determine what this counter was until I was done writing the program. Next up we simultaneously reverse the string and duplicate each character in place the correct number of times. Specifically the counter + 1. ``` {((<>{}<><({}<>)>)<{({}[()]<(({}))>)}{}>)<>}<>{} ``` These two parts of the program have a mode of 99 open parentheses. However since we are most certainly going to need at least 1 parenthesis. Here is where I noticed that the last character we pushed `!` conveniently has character code 33 which means we can use it to create 99, the exact number we want using only one additional parenthesis. This is quite the coincidence but it works. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes \* 1 = 13 ``` “¢Ȧ@XĊ'WÑṭḂ#» ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCcwqLIpkBYxIonV8OR4bmt4biCI8K7//8 "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 37 bytes × 3 = 111 *-20 thanks to H.PWiz. -25 thanks to nimi.* ``` "Good m\111rning, Green orb!"<*[2..4] ``` [Try it online!](https://tio.run/##y0gszk7NyflfbBvzX8k9Pz9FITfG0NCwKC8zL11Hwb0oNTVPIb8oSVHJRivaSE/PJPZ/bmJmnoKtQkFpSXBJkULx/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") Haskell's operators FTW. Self-reminder to never golf on mobile. I keep making dumb mistakes. I can push at least half the blame on mobile. :P [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 235 x 77 = 18,095 points Edit: -2 bytes thanks to @Dennis ``` -[>--<-------]>-[>+++++>+>+>+>+++++>+>+>+>+>+++>+++++>-->+>+>+>+>+>+>+>+++++>+>+>+>+++[<]>-]>>----------->+++++>++>->+>-------->-------->+++++>>->++++++>------>+>---->+>+++++>++>>->--------->++>++>>-[>+<---]>--------<<[>>[-<+<.>>]<<,<] ``` [Try it online!](https://tio.run/##XU9JCoBADHvQWF8Q8pHSgwqCCB4E3z/WWZzR9JK2SZf5nLZjvZY9RlGKQDKMnoYHLNFzJp4qIgzf@JoUPspIaagSNzO8Df7aLKQqirRtSJJ@aC752cgPFABKqiBgJA0YYDHe "brainfuck – Try It Online") [TIO test](https://tio.run/##zZTNboQgEMdfBTc9aJRN91yYpIfGB@jRcGAra0kFDNJGk313y6rb3e15Dv4mJH@GYfia8Cn7L9W2kzad84G8j31QZv9mf7R31igbphORPOU83ZXO1cQ4b7VtClJ6pSxx/pjsALhXXas/ZFCpkYM236bqYzucB0ZlMXI@iPMYpciybDJSW147In3TM9qo8BrFS@e1DU@n9OJNkudsFYdsmmgFlDK6ICB28wuw2r2GWc8eSiF/tMdJFYupBAC9cQ2JkyH/G4B/w7CKa8QaelthDrlPurjittlygBXGKoCKspztAQRjBRNTiYnbLDUmBBODCeqdeUwsJhoT1J01mBSYoBYt6q@BWmdqs6DWGeprbvfXOGKSYPIL) Wait, this *isn’t* code bowling?? \s With only 8 usable characters, brainfuck is one of the worst languages to do this question. I had to start with minimising which character would inevitably appear the most, typically either `+` or `-`. After writing the first iteration of the code, I found it horribly unbalanced in favour of `+`s. I rearranged parts of the code, such as generation of larger numbers, to use more `-`. Finally, I ended up at ~~an *equal* amount of the two characters at 77~~ one less `-` than `+`. It’s certainly possible to reduce this further, which I’ll have a go at tomorrow. But hey, at least I beat the [Brainflak answer](https://codegolf.stackexchange.com/a/152042/76162) [Answer] ## [Alice](https://github.com/m-ender/alice), 49 bytes \* 2 = 98 ~~144~~ ``` /:G!4o3r8"1=5',0Grey9Z<@ \"b0=dnm 2'i%g<7R6~e.;o/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fyl3RJN@4yELJ0NZUXcfAvSi10jLKxoErRinJwDYlL1fBSD1TNd3GPMisLlXPOl///38A "Alice – Try It Online") ### Explanation ``` /...@ \.../ ``` This is the usual framework for linear programs that operate entirely in Ordinal mode. Unfolding the zigzag control flow, we get: ``` "G04d3m821i5g,7G6ee9;<:b!=onr "'=%'<0Rr~y.Zo@ ``` The basic idea is to avoid characters which repeat more than twice with the help of a transliteration. The transliteration we're going to do is the following: ``` input: "G04d3m821i5g,7G6ee9;<:b!" from: "0123456789:;<" to: "onr " ``` The way transliteration works in Alice is that the `from` and `to` strings are first repeated to the LCM of their lengths, although in this case, all the matters is the length of the `from` string, so we get: ``` from: "0123456789:;<" to: "onr onr onr o" ``` This way, we get four different characters to represent the `o`s, and three each for `n`, `r` and the space. We can generate the `from` string using range expansion as follows: ``` '< Push "<". 0 Append a zero. R Reverse. r Range expansion. ``` The only issue now is that we'd need four `"` for both the `input` and the `to` string. To avoid that, we put them both into a single string and split it at a `=` used as a separator. ``` "G04d3m821i5g,7G6ee9;<:b!=onr " Push the string containing both parts. '=% Split around "=". ``` The rest is just: ``` ~ Swap "from" and "to". y Transliterate. .Z Duplicate and interleave. This duplicates each character. o Print. @ Terminate the program. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~74×6=444~~[crossed out 444 is still regular 444](https://codegolf.stackexchange.com/questions/103403/print-the-f-%c3%97-f-times-table/146450?s=29|0.0000#146450) ~~77×5=385~~ 81×4=324 ``` f(q){char*a="Go\157d morning, G\162een o\162b!";for(q=0;q<96;)putchar(a[q++/4]);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No1CzOjkjsUgr0VbJPT/G0NQ8RSE3vygvMy9dR8E9xtDMKDU1TyEfxEhSVLJOyy/SKLQ1sC60sTSz1iwoLQHp1UiMLtTW1jeJ1bSu/Z@bmJmnoVmdpgHiAAA "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 62 × 3 = 186 ``` lambda:`sum(zip(*['Good morning, Green \x6frb!']*3),())`[2::5] ``` [Try it online!](https://tio.run/##K6gsycjPM/pfUJSZV6Kg8T8nMTcpJdEqobg0V6Mqs0BDK1rdPT8/RSE3vygvMy9dR8G9KDU1TyGmwiytKElRPVbLWFNHQ1MzIdrIyso09r@mgobmfwA "Python 2 – Try It Online") [Answer] # Vim, ~~42~~ 41 keystrokes × 3 = 123 ``` iGod morning, Green orb!<Esc>2|qsyl2pl@sqX0@s ``` Explanation: 1. `iGod morning, Green orb!<Esc>` Write the string `God morning, Green orb!` (one `o` missing). 2. `2|` Jump to the first `o`. 3. `qsyl2pl@sq` Create a recursive macro `s`. As a side effect, triple the current `o`. 4. `X0` Remove one `o` and jump to the beginning. 5. `@s` Run the macro `s`, which repeat each character twice. [Answer] # [C (gcc)](https://gcc.gnu.org/), 68 × 3 = 204 ``` 0000000: 6a 3b 6d 61 69 6e 28 29 7b 77 68 69 6c 65 28 6a j;main(){while(j 0000010: 3c 37 32 29 70 75 74 63 68 61 72 28 7e 22 b8 90 <72)putchar(~".. 0000020: 90 9b df 92 90 8d 91 96 91 98 d3 df b8 8d 9a 9a ................ 0000030: 91 df 5c 32 32 30 8d 9d de 22 5b 6a 2b 2b 2f 33 ..\220..."[j++/3 0000040: 5d 29 3b 7d ]);} ``` *Thanks to @MDXF for saving 9 points and paving the way for 6 more!* [Try it online!](https://tio.run/##jZHPbsIwDMbP5Ck@ceCPEKFNaNIMxItsO7RJS0FAWQGBxNird3HKAe00y0qsz/ZPdpJnp6q93RymDZZLDPkQK@xrV6zrXcltG3X2BpVB5lAOKoYyUAVECmGgc2gNlQbRQiWk@2JsF/tscxiN79dqsytGWxZAsUdJC6khRWiPoBPoOZQMkBhaEEF7vkCewkTAUovx8XK2VdaMfvqcdyjhUT5rcrgSRlCcOpgYRoUzhZOU8hDSM3LwP9ahJKFiKk4sDUbe0RxcmCTJaSmRBy8hJaE@hIg8o/@@nUxmskPNPSpxtJp/Lu3wL/scLx4tZ@zOeleLqX35AdYrbFWzXvij4@klg2@U9c6rwkenujn763LYfFH/U5g2h2f/A6uBYGxtX9kYDMBnGa8v5/YX "Bash – Try It Online") ### Alternate version, printable ASCII, 69 × 3 = 207 ``` j;main(k){while(j<72)putchar("Gnmg$hiuf`dl -I}ut|3{gt6"[k=j++/3]^k);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/LOjcxM08jW7O6PCMzJ1Ujy8bcSLOgtCQ5I7FIQ8k9LzddJSOzNC0hJUdB17O2tKTGuDq9xEwpOts2S1tb3zg2LlvTuvb/fwA "C (gcc) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 46 bytes × 2 = 92 (Contains unprintables) ``` 2/⎕UCS(¯18+⍳24)+⎕UCS'X~r-yz|wqum1$Jtfem ln]' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4z0gXSoc7DGofWGFtqPejcbmWhqQ4TUI@rrinQrq2rKC0tzDVW8StJSc@Vy8mKl1f//BwA "APL (Dyalog Unicode) – Try It Online") +Alot of bytes thanks to Dyalog's code page, thanks to @Adám for pointing that out. [Answer] # C, 78 × 4 = 312 ``` *s=L" ÞÞÈ@ÚÞäÜÒÜÎX@äÊÊÜ@ÞäÄB";main(y){while(*++s)for(;y++%5;putchar(*s/2));} ``` [Try it online!](https://tio.run/##S9ZNT07@/1@r2NZHSeFQ3@F5QNjhcHgWkFpyeM7hSUDcF@EAlFhyuAsI5ziAJVqclKxzEzPzNCo1q8szMnNSNbS0tYs10/KLNKwrtbVVTa0LSkuSMxKLNLSK9Y00Na1r//8HAA) ## ~~356~~ ~~332~~ [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 bytes \* 2 = 48 ``` `Good ¶rÍÁ, GÎ9 b!`m²·¸ ``` Contains an unprintable. [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=YEdvb2QgtnLNwSwKR845II5iIWBtsre4&input=) The majority of the program is just a compressed string, which decompresses to ``` Good morning, Green orb! ``` and `m²` then `m`aps each character by repeating it `²`wice okay, that was a bit of a stretch. Space is the only character that appears 3 times in the compressed string; to save one instance we replace it with a newline, then use `·¸` to split on newlines and immediately join on spaces. While 2 bytes longer, it substantially reduces the score (from 66 to 48). Now if only there were a short way to do it using no character twice... [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 97 bytes \* 10 = 970 ``` S ='Good Morning, Green orb!' y S LEN(1) . y rem . s :f(p) x =x DUPL(y,10) :(y) p OUTPUT =x END ``` [Try it online!](https://tio.run/##Dcm7CoAgFADQ@foVtymFiIKmoC1p6QXlD0QWQXlDF/16azrDcYY2uqsYYcEm7Yh2HMiay5wZdlZrg2S3JGUBFujlyEuBOQa0@vl1UB/8FQw8NB5bNfc8ZGUhoOZBsBcmtc5q/Y/JsY3xAw "SNOBOL4 (CSNOBOL4) – Try It Online") yeah........SNOBOL requires operators to be separated by whitespace, and there are whitespace requirements that are quite awkward. There are 9 `'\t'` and 10 `' '` in the code, so any improvements will require a fairly significant change in approach. [Answer] # [R](https://www.r-project.org/), ~~65 bytes \* 5 = 325~~ ~~59 bytes \* 5 = 295~~ 62 bytes \* 4 = 248 ``` cat(gsub('(.)',strrep('\\1',4),"Good Mo\x72ning, Green orb!")) ``` [Try it online!](https://tio.run/##dY2xCsIwFEV3v@JZhySQCkpF/6A4uDlmSduXttAm8vIq/fsYOjgp3Dtd7jmUUmtZ9nFppJBHJXRkInxJYcxJ6Erpog6hg0cw6/XsR99rqAnRQ6BmXyi13YXxQu1mu0q2zYRyYXd7hrtnWfylb/yL0uYr@GUwWZGj4ABz6BDKEnhAQrC5FQQHEd9IdoJudC4PnqEdLNmWkWL6AA "R – Try It Online") There are 4 `(or,')` characters. [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes × 3 = 156 ``` puts"Good morning, Green \x6frb!".gsub(/(.)/,'\1'*3) ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFjJPT8/RSE3vygvMy9dR8G9KDU1TyGmwiytKElRSS@9uDRJQ19DT1NfRz3GUF3LWPP/fwA "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 59 × 2 = 118 points ``` $_="GSSdYmoVRing,YGVIen orb!";y<H-Z>[d-t ],s<.>[$&x2]eg;say ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbJPTg4JTI3PywoMy9dJ9I9zDM1TyG/KElRybrSxkM3yi46RbdEIVan2EbPLlpFrcIoNjXdujix8v//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/), 51 × 3 = 153 ~~156~~ points ``` s""GOOd morning, Green orb!";y'O'o';s/./$&x3/eg;say ``` [Try it online!](https://tio.run/##K0gtyjH9/79YScnd3z9FITe/KC8zL11Hwb0oNTVPIb8oSVHJulLdXz1f3bpYX09fRa3CWD813bo4sfL//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/), 43 × 4 = 172 points ``` say"Good morning, Green orb!"=~s/./$&x4/egr ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLJPT8/RSE3vygvMy9dR8G9KDU1TyG/KElRybauWF9PX0WtwkQ/Nb3o//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") Saved 2 bytes in each solution thanks to @Xcali (a few changes ago). For all optimizations look at the edits. [Answer] # [V](https://github.com/DJMcMayhem/V), 35 bytes \* 2 = 70 ``` IG²od morning, GreeN ORb!5h3~Óˆ/°° ``` [Try it online!](https://tio.run/##K/v/39P90Kb8FIXc/KK8zLx0HQX3otRUPwX/oCRFadMM47rDkw916B/acGjD//8A "V – Try It Online") Hexdump: ``` 00000000: 4947 b26f 6420 6d6f 726e 696e 672c 2047 IG.od morning, G 00000010: 7265 654e 204f 5262 211b 3568 337e d388 reeN ORb!.5h3~.. 00000020: 2fb0 b0 /.. ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) \* 1 = 16 ``` 7n]ēæ¬⁹≡qa╔αXE‘⁽ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=N24lNUQldTAxMTMlRTYlQUMldTIwNzkldTIyNjFxYSV1MjU1NCV1MDNCMVhFJXUyMDE4JXUyMDdE,v=0.12) Compression! Though, if `Green` wasn't capitalized like that, this could be 3 bytes shorter :/ [Answer] # [Python 2](https://docs.python.org/2/), 62\*4 = 248 *Thanks to @ovs and @Giuseppe!* ``` lambda:"".join(c*4for(c)in"G\x6f\x6fd mor\x6eing, Green orb!") ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNykl0UpJSS8rPzNPI1nLJC2/SCNZMzNPyT2mwiwNhFMUcvOLgIzUzLx0HQX3otTUPIX8oiRFJc3/BUWZeSUKaRqa/wE) # [Python 2](https://docs.python.org/2/), 51\*6 = 306 ``` print"".join(c*6for c in"Good morning, Green orb!") ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69ESUkvKz8zTyNZyywtv0ghWSEzT8k9Pz9FITe/KC8zL11Hwb0oNTVPIb8oSVFJ8/9/AA) # [Python 2](https://docs.python.org/2/), 70\*5 = 350 ``` lambda:"".join(c*5for(c)in"Gxxd mxrning, Green xrb!".replace('x','o')) ``` [Try it online!](https://tio.run/##BcE5DoAgEADAryANYAyFiY2JNZ@w4VQMLGRjsb4eZ/r33g3WkY5zFFtdsDvn@mkZpJ@31FB6lYEbosAqIWS4FmYwRmCEbuIaYy/WRylILKIJpUbHDC9LUo0f) *Thanks to @Mr. Xcoder for saving a byte from both versions!* [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 20 [bytes](https://github.com/nickbclifford/Ohm/blob/master/code_page.md) \* 1 = 20 ``` ”1Gäåa¬Î|òÙγy[õ↕~LzN ``` [Try it online!](https://tio.run/##ASgA1/9vaG0y///igJ0xR8Okw6VhwqzDjnzDssOZzrN5W8O14oaVfkx6Tv// "Ohm v2 – Try It Online") Gotta love compression, although unfortunately it's not as good as SOGL's. [Answer] # [Clean](https://clean.cs.ru.nl), 77 bytes \* 3 = 231 ``` import StdEnv f=[[b,b..]%(0,2)\\a<-:"Qyyn*wy|xsxq6*Q|oox*\171|l+",b<-[a-' ']] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4wrzTY6OkknSU8vVlXDQMdIMyYm0UbXSimwsjJPq7yypqK4otBMK7AmP79CK8bQ3LAmR1tJJ8lGNzpRV51LPTb2f3BJItAwW4W0//@S03IS04v/6yb91/X0@e9SmZeYm5lcDAA "Clean – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 32 bytes × 2 = 64 ``` "Gnmg$hiuf`dl -I}ut|3orb!"K,.^:_ ``` [Try it online!](https://tio.run/##S85KzP3/X8k9LzddJSOzNC0hJUdB17O2tKTGOL8oSVHJW0cvzir@/38A "CJam – Try It Online") Pushes a string, then XORs the first 20 character with `[0, 1, …, 19]`, then duplicates each character. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), Score: 22 (22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) \* 1) ``` …‚¿•´,„ˆ¨èã).ªðý23£'!« ``` [Try it online.](https://tio.run/##ATMAzP9vc2FiaWX//@KApuKAmsK/4oCiwrQs4oCey4bCqMOow6MpLsKqw7DDvTIzwqMnIcKr//8) **Explanation:** NOTE 1: The *wrap stack into list* builtin `)` is used instead of the builtin *pair* `‚`, because the `‚` is already part of the dictionary word `good`. NOTE 2: The two commas in the code `‚` and `,` may look the same, [but are different unicode characters](https://tio.run/##yy9OTMpM/f//cPv//48aZukAAA). The first one is usually used for the builtin *pair*, and the second for the builtin *print to STDOUT with trailing newline*. In this case they are used for the dictionary word `good`, and the expected comma in the output however. ``` …‚¿•´, # 3-word dictionary string "good morning," (the comma counts as the third word) „ˆ¨èã # 2-word dictionary string "green orbit" ) # Wrap everything on the stack into a list: ["good morning,","green orbit"] .ª # Sentence capitalize all strings: ["Good morning,","Green orbit"] ðý # Join by spaces: "Good morning, Green orbit" 23£ # Only leave the first 23 characters: "Good morning, Green orb" '!« '# Append a "!": "Good morning, Green orb!" (and output the result implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…‚¿•´,` is `"good morning,"` and `„ˆ¨èã` is `"green orbit"`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 bytes \* 4 = 184 points ``` "Good morning, Green orb!"-replace'.',('$0'*4) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8k9Pz9FITe/KC8zL11Hwb0oNTVPIb8oSVFJtyi1ICcxOVVdT11HQ13FQF3LRPP/fwA "PowerShell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49\*5~~ 58 bytes \* 4 = 232 pts -13 pts thanks to ASCII-only ``` -join("Good m{0}rning, Green {0}rb!"-f'o'|% t*y|%{"$_"*4}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPQ8k9Pz9FIbfaoLYoLzMvXUfBvSg1NU8BxE9SVNJNU89Xr1FVKNGqrFGtVlKJV9IyqdX8/x8A "PowerShell – Try It Online") Uses formatting to go from 5 `o`s to 4 to chip out some numbers [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes, score 38 ``` ‛ƛ⁋`øø, ×ŀ ⋎Ė!`"Ṅ2• ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%80%9B%C6%9B%E2%81%8B%60%C3%B8%C3%B8%2C%20%C3%97%C5%80%20%E2%8B%8E%C4%96!%60%22%E1%B9%842%E2%80%A2&inputs=&header=&footer=) ``` ‛ƛ⁋ # Compressed string `øø, ×ŀ ⋎Ė!` # Compressed string "Ṅ # Pair and join by spaces 2• # Double each character ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes × 2 = 62 points ``` “2ðƈZ(Øṡdȷ¿Ɱ’ṃ“God mrnig,eb!”x2 ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxyjwxuOdURpHJ7xcOfClBPbD@1/tHHdo4aZD3c2AyXd81MUcovyMtN1UpMUHzXMrTD6//9/tKGOERAa65jomAJpMx1zHQsgttQxNAAKGQIFDA1ByBzIA0kbGukYGsc@3NFqaAwA "Jelly – Try It Online") **Explanation** ``` “2ðƈZ(Øṡdȷ¿Ɱ’ṃ“God mrnig,eb!”x2 “2ðƈZ(Øṡdȷ¿Ɱ’ Base 250 number “God mrnig,eb!” Unique characters of "Good morning..." ṃ Convert the base 250 number in base 13 then index into the string "God mr..." x2 Repeat each character twice because “ occurs twice in the source (and now 2) ``` [Answer] # JavaScript (ES6), 61 bytes \* 3 = 183 ``` _=>'Good morning, Gr\145en \x6f\x72b!'.replace(/./g,"$&$&$&") ``` ``` f= _=>'Good morning, Gr\145en \x6f\x72b!'.replace(/./g,"$&$&$&") console.log(f()) ``` # JavaScript (ES6), 51 bytes \* 4 = 204 ``` _=>'Good morning, Green orb!'.replace(/./g,'$&$&$&$&') ``` Answer [suggested by @ETHproductions](https://codegolf.stackexchange.com/questions/152016/a-programming-puzzle-of-mode-golf/152025#comment371516_152025). ``` f= _=>'Good morning, Green orb!'.replace(/./g,'$&$&$&$&') console.log(f()) ``` # JavaScript (ES6), 73 bytes \* 4 = 292 ``` _=>`G00d mo1ning, G244n orb!`.replace(/./g,_=>(('o'+!0)[_]||_).repeat(4)) ``` ``` f= _=>`G00d mo1ning, G244n orb!`.replace(/./g,_=>(('o'+!0)[_]||_).repeat(4)) console.log(f()) ``` # JavaScript (ES6), 58 bytes \* 6 = 348 ``` _=>'Good morning, Green orb!'.replace(/./g,_=>_.repeat(6)) ``` ``` f= _=>'Good morning, Green orb!'.replace(/./g,_=>_.repeat(6)) console.log(f()) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 36×4=144 ``` Good morning, Green orb! . $&$&$&$& ``` [Try it online!](https://tio.run/##K0otycxL/P@fyz0/P0UhN78oLzMvXUfBvSg1NU8hvyhJkUuPS0UNAv//BwA "Retina – Try It Online") There are three newlines and four `o`s, so there's nothing more to be done. [Answer] # Ruby, 55x4 = 220 points ``` "Good morning, Green orb!".split(//).each{|x|print x*4} ``` Im quite annoyed that using each\_char makes the count of r's 5.. ]
[Question] [ **Find the difference between the square of the sums and sum of the squares.** This is the mathematical representation: \$\left(\sum n\right)^2-\sum n^2\$ Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive. Limits will be whole integers above 0. Your program/method should return the answer. You may use whichever base you would like to, but please state in your answer which base you have used. Test case (Base 10) ``` 5,9 970 91,123 12087152 1,10 2640 ``` This is usual code-golf, so the shorter the answer the better. [Answer] # Python 2, 43 bytes ``` f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a) ``` Test it on [Ideone](http://ideone.com/1iCZ4l). ### How it works Call the function defined in the specification \$g(a, b)\$. We have that $$ \newcommand{\sumab}[2]{\sum\_{a \le #1 \le b} #2 \:} \begin{align} g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\ & = \sumab {i,j} {ij} - \sumab n {n^2} \\ & = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\ & = 2 \sumab {j<i} {ij} \\ & = 2 \sumab {i} {\sum\_{a \le i < j} ij} \\ & = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)} \end{align} $$ Define the function \$f(x, y, s)\$ recursively as follows. $$ f(x, y, s) = \begin{cases} 2xs + f(x+1, y, s+x) & \text{ if } x \le y \\ 0 & \text{ if} x > y \end{cases} $$ By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that: $$ \begin{align} f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\ & \vdots \\ & = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\ & = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)} \\ & = g(a, b) \end{align} $$ This is the function **f** of the implementation. While `b/a` returns a non-zero integer, the code following `and` is executed, thus implementing the recursive definition of **f**. Once `b/a` reaches **0**, we have that **b > a** and the lambda returns **False = 0**, thus implementing the base case of the definition of **f**. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` &:&*XRssE ``` [**Try it online!**](http://matl.tryitonline.net/#code=JjomKlhSc3NF&input=MQoxMA) ### Explanation ``` &: % Inclusive range between the two implicit inputs &* % Matrix of all pair-wise products XR % Upper triangular part of matrix, without the diagonal ss % Sum of all elements of the matrix E % Multiply by 2. Implicit display ``` ### Example These are the partial results of each line for inputs `5` and `9`: 1. `&:` ``` 5 6 7 8 9 ``` 2. `&:&*` ``` 25 30 35 40 45 30 36 42 48 54 35 42 49 56 63 40 48 56 64 72 45 54 63 72 81 ``` 3. `&:&*XR` ``` 0 30 35 40 45 0 0 42 48 54 0 0 0 56 63 0 0 0 0 72 0 0 0 0 0 ``` 4. `&:&*XRss` ``` 485 ``` 5. `&:&*XRssE` ``` 970 ``` [Answer] ## Jelly, ~~9~~ 8 bytes ``` rµS²_²S$ ``` [Try it online!](http://jelly.tryitonline.net/#code=csK1U8KyX8KyUyQ&input=&args=OTE+MTIz) ``` r inclusive range from first input to second input µ pass the range to a new monadic chain S the sum ² squared _ minus... ²S$ the squares summed ``` Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for a byte! [Answer] ## Python 2, 45 bytes ``` lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12 ``` Closed form solution - not the shortest, but I thought it'd be worth posting anyway. ## Explanation Let `p(n)` be the *n*th [square pyramidal number](https://en.wikipedia.org/wiki/Square_pyramidal_number), and `t(n)` be the *n*th [triangular number](https://en.wikipedia.org/wiki/Triangular_number). Then, for *n* over the range *a*, ..., *b*: * ∑n = `t(b)-t(a-1)`, and * ∑n² = `p(b) - p(a-1)` * So (∑n)²-∑n² = `(t(b)-t(a-1))² - (p(b) - p(a-1))`. This expression reduces to that in the code. [Answer] ## 05AB1E, 8 bytes ``` ŸDOnsnO- ``` **Explained** ``` ŸD # range from a to b, duplicate On # sum and square first range s # swap top 2 elements nO # square and sum 2nd range - # take difference ``` [Try it online](http://05ab1e.tryitonline.net/#code=xbhET25zbk8t&input=OTEKMTIz) [Answer] ## Mathematica, 21 bytes ``` Tr[x=Range@##]^2-x.x& ``` An unnamed function taking two arguments and returning the difference. Usage: ``` Tr[x=Range@##]^2-x.x&[91, 123] (* 12087152 *) ``` There's three small (and fairly standard) golfing tricks here: * `##` represents both arguments at once, so that we can use prefix notation for `Range`. `Range@##` is shorthand for `Range[##]` which expands to `Range[a, b]` and gives us an inclusive range as required. * `Tr` is for *trace* but using it on a vector simply sums that vector, saving three bytes over `Total`. * `x.x` is a dot product, saving four bytes over `Tr[x^2]`. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), ~~28~~ 24 bytes ``` ?:?:}+=-:(:(#{:**+**#2/! ``` [Try it online!](http://labyrinth.tryitonline.net/#code=Pzo_On0rPS06KDooI3s6KiorKiojMi8h&input=OTEgMTIz) ### Explanation Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code. ``` Cmd Explanation Stacks [ Main | Aux ] ? Read M. [ M | ] : Duplicate. [ M M | ] ? Read N. [ M M N | ] : Duplicate. [ M M N N | ] } Move copy to aux. [ M M N | N ] + Add. [ M (M+N) | N ] = Swap tops of stacks. [ M N | (M+N) ] - Subtract. [ (M-N) | (M+N) ] : Duplicate. [ (M-N) (M-N) | (M+N) ] ( Decrement. [ (M-N) (M-N-1) | (M+N) ] : Duplicate. [ (M-N) (M-N-1) (M-N-1) | (M+N) ] ( Decrement. [ (M-N) (M-N-1) (M-N-2) | (M+N) ] # Push stack depth. [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ] { Pull (M+N) over from aux. [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ] : Duplicate. [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ] * Multiply. [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ] * Multiply. [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ] + Add. [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ] * Multiply. [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ] * Multiply. [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ] # Push stack depth. [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ] 2 Multiply by 10, add 2. [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ] / Divide. [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ] ! Print. [ | ] ``` The instruction pointer then hits a dead end and has to turn around. When it now encounters `/` it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program. [Answer] ## Haskell, 34 bytes ``` a#b=sum[a..b]^2-sum(map(^2)[a..b]) ``` Usage example: `91 # 123` -> `12087152`. Nothing to explain. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes ``` :efL:{:2^.}a+S,L+:2^:S-. ``` Expects the 2 numbers in Input as a list, e.g. `[91:123]`. ### Explanation ``` :efL Find the list L of all integers in the range given in Input :{:2^.}a Apply squaring to each element of that list +S, Unify S with the sum of the elements of that list L+:2^ Sum the elements of L, then square the result :S-. Unify the Output with that number minus S ``` [Answer] ## Matlab, ~~30~~ ~~29~~ 28 bytes Using Suever's idea of `norm` gives us 2 bytes less ``` @(x,y)sum(x:y)^2-norm(x:y)^2 ``` Old (simple) version: ``` @(x,y)sum(x:y)^2-sum((x:y).^2) ``` [Answer] # Octave, ~~27~~ 23 bytes ``` @(x,y)sum(z=x:y)^2-z*z' ``` Creates an anonymous function named `ans` which accepts two inputs: `ans(lower, upper)` [**Online Demo**](http://ideone.com/b9zIwP) **Explanation** Creates a row vector from `x` to `y` (inclusive) and stores it in `z`. We then sum all the elements using `sum` and square it (`^2`). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two. [Answer] # Java, ~~84~~ 77 characters, ~~84~~ 77 bytes 7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you. `public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}` Using the three test cases in the original post: <http://ideone.com/q9MZSZ> Ungolfed: ``` public int g(int b, int c) { int e = 0, f = 0; for (; b <= c; e += b, f += b * b++); return e*e-f; } ``` Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference. [Answer] # JavaScript (ES6), 46 bytes ``` f=(x,y,s=0,p=0)=>x<=y?f(x+1,y,s+x,p+x*x):s*s-p ``` [Answer] ## JavaScript (ES6), ~~50~~ 37 bytes ``` f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s) ``` Now a port of @Dennis♦'s Python solution. [Answer] # Factor, 48 bytes ``` [ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ] ``` An anonymous function. ``` [ [a,b] ! a range from a to b [ [ sq ] map sum ! anonymous function: map sq over the range and sum the result ] [ sum sq ] ! the same thing, in reverse order bi - abs ! apply both anon funcs to the range, subtract them and abs the result ] ``` [Answer] ## Haskell, 36 bytes ``` m#n=sum[2*i*j|i<-[m..n],j<-[i+1..n]] ``` --- ``` λ> m # n = sum [ 2*i*j | i <- [m..n], j <- [i+1..n] ] λ> 5 # 9 970 λ> 91 # 123 12087152 λ> 1 # 10 2640 ``` Note that $$\left( \sum\_{k=m}^n k \right)^2 - \sum\_{k=m}^n k^2 = \cdots = \sum\_{k\_1=m}^n \sum\_{k\_2=m\\ k\_2 \neq k\_1}^n k\_1 k\_2 = \sum\_{k\_1=m}^n \sum\_{k\_2=k\_1+1}^n 2 \,k\_1 k\_2$$ [Answer] # [Perl 6](http://perl6.org), ~~36 32~~ 31 bytes ``` ~~{([+] $\_=@\_[0]..@\_[1])²-[+] $\_»²} {([+] $\_=$^a..$^b)²-[+] $\_»²}~~ {[+]($_=$^a..$^b)²-[+] $_»²} ``` [Test it](https://tio.run/##VY7BDsFAFEX38xV3MZGZmDZtUUoqPsJOkGIqjWrLTIXgp2zt@mM1KiQ2L/ed3HffLeQx9etSSZx8ez0ibzWVSo8I2V8w0UYqhGAEYD0RcIRjBH1HvPfAFa7XaZDrOYO@2/MabrDTUM/vGic3WUUaZWh/4j7RrU0Sx5Y6WLmZ5R5hfZ2154wuQ7qIbJsuVrx6WAaBLqtn9bjXcX78FrLGhoJhuJMXNkmyotRcYHiK0lIyKs@FXGu54eC4mkKJwv8zdvvd/MwC9jZRmtzrFw "Perl 6 – Try It Online") ### Explanation: ``` { # bare block with placeholder parameters $a and $b [+](# reduce with &infix:<+> # create a range, and store it in $_ $_ = $^a .. $^b )² - [+] # reduce with &infix:<+> # square each element of $_ ( possibly in parallel ) $_»² } ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my @tests = ( (5,9) => 970, (91,123) => 12087152, (1,10) => 2640, ); plan +@tests; my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²} for @tests -> $_ ( :key(@input), :value($expected) ) { is diff-sq-of-sum(|@input), $expected, .gist } ``` ``` 1..3 ok 1 - (5 9) => 970 ok 2 - (91 123) => 12087152 ok 3 - (1 10) => 2640 ``` [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), 108 bytes(36 chars) ``` 방빠방빠쌍다쌍상싸사타빠밤타빠받다파반다받상싸사빠따따다따따받밤따나망히 ``` [Try it online!](https://tio.run/##S8xILc38///1hpWvdy6AkG96el93LwGSb5ob33TveNO05m1zA1h2CYwxG6jgbU/P6w0zgAwgF64SJDtlAwgBxSEMoOINYHbTjNfL576d1/H/v6mCJQA "Aheui (esotope) – Try It Online") --- Takes two inputs from user(separated by line feed or whitespace) and print result of following function; > > \$f(a,b)=((a-b)\cdot(a-b-1)\cdot(3\cdot(a+b)^2+a-b-2))/12\$ > > > [Answer] # APL, ~~23~~ 20 bytes ``` -/+/¨2*⍨{(+/⍵)⍵}⎕..⎕ ``` Works in NARS2000. [Answer] # MATL, 11 bytes ``` &:ts2^w2^s- ``` [Try it online!](http://matl.tryitonline.net/#code=Jjp0czJedzJecy0&input=NQo5) Explanation: ``` &: #Create a range from the input t #Duplicate it s2^ #Sum it and square it w #swap the two ranges 2^s #Square it and sum it - #Take the difference ``` [Answer] ## PowerShell v2+, 47 bytes Two variations ``` param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p $args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p ``` In both cases we're generating a range with the `..` operator, piping that to a loop `|%{...}`. Each iteration, we're accumulating `$o` and `$p` as either the sum or the sum-of-squares. We then calculate the square-of-sums with `$o*$o` and subtract `$p`. Output is left on the pipeline and printing is implicit. [Answer] # Pyth, 11 bytes ``` s*M-F#^}FQ2 ``` [Try it online!](http://pyth.herokuapp.com/?code=s%2aM-F%23%5E%7DFQ2&input=91%2C123&debug=0) ``` s*M-F#^}FQ2 }FQ Compute the range ^ 2 Generate all pairs -F# Remove those pairs who have identical elements *M Product of all pairs s Sum. ``` [Answer] # Japt, 10 bytes ``` õV x²aUx ² ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9VYKeLJhVXggsg==&input=NSw5) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` rµÄḋḊḤ ``` Recent improvements to the Jelly language allow a compact implementation of the \$g\$ function from [my Python answer](https://codegolf.stackexchange.com/a/83369/12012). [Try it online!](https://tio.run/##AR4A4f9qZWxsef//csK1w4ThuIvhuIrhuKT///85Mf8xMjM "Jelly – Try It Online") ### How it works ``` rµÄḋḊḤ Main link. Arguments: a, b (integers) r Range; yield R := [a, ..., b]. µ Begin a monadic chain with argument R. Ä Accumulate; take the cumulative sum of R. Ḋ Deque; yield [a+1, ..., b]. ḋ Take the dot product, ignoring the last term of the cumulative sum. Ḥ Unhalve; double the result. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ṡ:²∑$∑²ε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaE6wrLiiJEk4oiRwrLOtSIsIiIsIjkxXG4xMjMiXQ==) ## How? ``` ṡ:²∑$∑²ε ṡ # Inclusive range between (implicit) second input and (implicit) first input : # Duplicate this range ² # Square each of the duplicate ∑ # Summate $ # Swap so the other range is at the top ∑ # Summate ² # Then square ε # Absolute difference between the two ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` IDS²s²S- ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWqzxdgg9tKj60KVh3SXFScjFUeMFiUy5LCBMA) #### Explanation ``` IDS²s²S- # Implicit input ID # Inclusive range; duplicate S² # Sum the list; square the sum s # Swap so the range is back on top ²S # Square each item; sum the list - # Take the difference # Implicit output ``` [Answer] ## CJam, 17 bytes ``` q~),>_:+2#\2f#:+- ``` [Test it here.](http://cjam.aditsu.net/#code=q~)%2C%3E_%3A%2B2%23%5C2f%23%3A%2B-&input=91%20123) ### Explanation ``` q~ e# Read and evaluate input, dumping M and N on the stack. ), e# Increment, create range [0 1 ... N]. > e# Discard first M elements, yielding [M M+1 ... N]. _ e# Duplicate. :+2# e# Sum and square. \2f#:+ e# Swap with other copy. Square and sum. - e# Subtract. ``` Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer: ``` q~),>2m*{)-},::*:+ ``` [Answer] # JavaScript (ES6), 67 bytes ``` a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q) ``` ## Test Suite ``` f=a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q) e=s=>`${s} => ${eval(s[0])}` // template tag format for tests console.log(e`f(5)(9)`) console.log(e`f(91)(123)`) console.log(e`f(1)(10)`) ``` [Answer] # J, 29 bytes Port of [Doorknob's Jelly answer](https://codegolf.stackexchange.com/a/83344/48934). ``` [:(+/@(^&2)-~2^~+/)[}.[:i.1+] ``` ## Usage ``` >> f = [:(+/@(^&2)-~2^~+/)[}.[:i.1+] >> 91 f 123x << 12087152 ``` Where `>>` is STDIN, `<<` is STDOUT, and `x` is for extended precision. [Answer] ## Pyke, 11 bytes ``` h1:Ds]MXXs- ``` [Try it here!](http://pyke.catbus.co.uk/?code=h1%3ADs%5DMXXs-&input=9%0A5) ``` h1: - inclusive_range(input) Ds] - [^, sum(^)] MX - deep_map(^, <--**2) s - ^[1] = sum(^[1]) - - ^[0]-^[1] ``` ]
[Question] [ ## Introduction: Inspired by [this comment of *@MagicOctopusUrn*](https://codegolf.stackexchange.com/questions/129523/it-was-just-a-bug#comment326309_129549) on [*@Emigna*'s 05AB1E answer](https://codegolf.stackexchange.com/a/129549/52210) for my ["*It was just a bug*" challenge](https://codegolf.stackexchange.com/questions/129523/it-was-just-a-bug): > > `8F9ÝÀNð×ý}».∊` I done did made a spaceship maw! And I was all excited about suggesting a 12-byte edit. – [Magic Octopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn) Jul 17 '17 at 20:10 > > > Which is a [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (legacy) program resulting in this: ``` 1234567890 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1234567890 ``` [Try it online.](https://tio.run/##AR8A4P8wNWFiMWX//zhGOcOdw4BOw7DDl8O9fcK7LuKIiv//) ## Challenge: Input: A non-empty string Output: From outwards going inwards, add one more space between each character every line, similar as done in the output above, equal to the `length - 1`. So for an input `1234567890` the output would actually be this instead: ``` 1234567890 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1234567890 ``` Why? The length of `1234567890` is `10`. So we start by outputting 10 lines: the first line without spaces; second with one space delimiter; third with two; etc. And then (without have the middle line with `length - 1` spaces duplicated), we go back to the initial input while going down. ## Challenge rules: * Input is guaranteed to be non-empty (a length `>= 1`). (For single char inputs we simply output that character.) * Any amount of trailing/leading spaces/newlines are allowed, as long as the output itself (wherever on the screen) is correct. (Empty line(s) in between output lines also isn't allowed.) * Input will only contain printable ASCII characters excluding whitespaces (code-point range `[33, 126]`) * I/O is flexible. Input may be taken as STDIN, argument, or function parameter. May be a list/array/stream of characters instead of string. Output may also be a list/array/stream of characters instead of strings; may be printed to STDOUT; returned as newline-delimited string; etc. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Input: @ Output: @ Input: test Output: test t e s t t e s t t e s t t e s t t e s t test Input: ?! Output: ?! ? ! ?! Input: Spaceship Output: Spaceship S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p S p a c e s h i p Spaceship Input: 05AB1E Output: 05AB1E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 0 5 A B 1 E 05AB1E Input: )}/\ Output: )}/\ ) } / \ ) } / \ ) } / \ ) } / \ ) } / \ )}/\ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ 6 bytes Takes input as an array of characters, outputs an array of strings. ``` £qYçÃê ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=o3FZ58Pq&input=WyJTIiwicCIsImEiLCJjIiwiZSIsInMiLCJoIiwiaSIsInAiXQotUg==) --- ## Explanation ``` £ :Map each element at (0-based) index Y q : Join input with Yç : Space repeated Y times à :End Map ê :Palindromise ``` --- ## Original, 8 bytes I/O is a string. Uses the `-R` flag. Includes trailing spaces on each line. ``` ¬£múYÄÃê ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=rKNt+lnEw+o=&input=IlNwYWNlc2hpcCIKLVI=) ### Explanation ``` :Implicit input of string U ¬ :Split £ :Map each character at 0-based index Y m : Map original U ú : Right pad with spaces to length ... YÄ : Y+1 à :End map ê :Palindromise :Implicitly join with newlines ``` [Answer] # [R](https://www.r-project.org/), ~~105~~ ~~99~~ ~~85~~ ~~84~~ 79 bytes -6 thanks to @Kevin Cruissen and @Giuseppe -14 from changing to a regex based method -1 thanks to @Giuseppe -5 thanks to @digEmALl ``` function(w,n=nchar(w)-1)write(trimws(Map(gsub,"",strrep(" ",n-abs(n:-n)),w)),1) ``` [Try it online!](https://tio.run/##JcYxCsMwDEDRvadoNUlgD1lLQ3uBHsIxduMhqpEUdHwnkOHzvoz6iqPunK39GT3wzHlNgk5xIpdmBU3a5orf1PGn@xIAgppI6Qh3CBzTosjPyETBzyYaFeEDdDt5vC@tqF2nPeWia@tA4wA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes Saved 1 bytes thanks to *Adnan* ``` εINð×ý}û» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3FZPv8MbDk8/vLf28O5Du///j1YyUNJRMgViRyB2AmJDIHZVigUA "05AB1E – Try It Online") **Explanation** ``` ε # apply to each in input I # push the input Nð× # push <index> spaces ý # merge the input on the spaces } # end loop û # palendromize » # join on newlines ``` [Answer] # JavaScript (ES6), 53 bytes Takes input as an array of characters. ``` f=(s,p=i='',o=s.join(p)+` `)=>s[++i]?o+f(s,p+' ')+o:o ``` [Try it online!](https://tio.run/##dcqxCsIwEADQvV@hXZJwNejgIpxVwS9wLIWGmGhKyQUv@PuR7mZ@bzZfw/YTUt5FerpSPEruEgYUoiNkPVOIMimYmknhmQeAMPYEfl0gNkIBnahYikyL0wu9pJeD1rq9tKNSzR/IjnPN@m1NHslYx@@QamF/vN4O91XLDw "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` Eθ⪫θ× κ‖O↓ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUCjUEfBKz8zD0SHZOamFmsoKSjpKGRrAoE1V1BqWk5qcol/WWpRDlCtlUt@eZ6m9f//hkbGJqZm5haWBv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Eθ Map over characters of input string ⪫θ Join characters of input string using × a literal space repeated κ current index number of times Implicitly print each result on its own line ‖O↓ Reflect vertically with overlap ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ┐² ×*]── ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTEwJUIyJTIwJUQ3JXVGRjBBJXVGRjNEJXUyNTAwJXUyNTAw,i=U3BhY2VzaGlw,v=6) The [7 byte](https://dzaima.github.io/Canvas/?u=JXUyNTEwJUIyJTIwJUQ3JXVGRjBBJXVGRjNEJXUyNTAw,i=JTIwQUJDJTVD,v=6) version was too good for this challenge.. [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ ~~70~~ ~~68~~ ~~66~~ 65 bytes -2 bytes thanks to Kevin Cruijssen -3 bytes thanks to ovs ``` w=input();c=s=-1 while c:print(' '*~c).join(w);s*=w[:c]>'';c+=s|1 ``` [Try it online!](https://tio.run/##BcFBCoAgEADAe6/wtmoU2FHZPhKdFkEjVHJDgujrNlMeDjktvTeMqdwslSOsOJmhhXh6QbZcMbEEAfojNR85JtmUqxrbZmlfARyNWF/TO7CvDD8 "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~54~~ 49 bytes ``` ->a{(-(z=a.size-1)..z).map{|i|a*(?\s*(z-i.abs))}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xWkNXo8o2Ua84sypV11BTT69KUy83saC6JrMmUUvDPqZYS6NKN1MvMalYU7O29n9BaUmxQlq0kqGRsYmpmbmFpYGSXnJGYlFxLBdMKrggMTm1OCOzAEPGXhEm9B8A "Ruby – Try It Online") Takes input as an array of characters, outputs array of strings. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εINúíJ}û» ``` Input as list of characters. [Try it online](https://tio.run/##MzBNTDJM/f//3FZPv8O7Dq/1qj28@9Du//@jlTSVdJRqgVgfiGNilGIB) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5nl4QqjO/3NbI/wO7zq81qv28O5Du//rHNqm8z9ayVBJR8kIiI2B2ASITYHYDIjNgdgCiC2B2EAplitayQFMlgD5qUBcDMQlYBF7IEsRzAoGsgqAOBGIk5HUZQBxJlgOpMoAaosjEDsBMcgFrmAZTSCrFoj1gTgmRikWAA). **Explanation:** ``` ε } # Map each character in the input to: I # Take the input Nú # Prepend each with the 0-indexed amount of spaces # i.e. ["t","e","s","t"] & 3 → [" t"," e"," s"," t"] í # Reverse each item # i.e. [" t"," e"," s"," t"] → ["t ","e ","s ","t "] J # Join them together to a single string # i.e. ["t ","e ","s ","t "] → "t e s t " û» # Palindromize the list, and join by newlines # i.e. ["test","t e s t ","t e s t ","t e s t "] # → "test\nt e s t \nt e s t \nt e s t \nt e s t \nt e s t \ntest" ``` [Answer] # [Haskell](https://www.haskell.org/), ~~60~~ 59 bytes ``` (init<>reverse).(scanl(?)<*>tail) a?_=do u<-a;u:[' '|' '<u] ``` [Try it online!](https://tio.run/##DcyxDoIwEADQna@4jdYEPkAPGHCUhMTFRA25QMHG0pL26uS3Wxne@l4U3sqYpNfNeYYzMZWds05PIEBgLUFm2QwVPJLQVjPWXn2UD0qWIoxkjWgkHmombWRGzVBNDiIWdIrHew75d4fxmVbSdk9W2roBtshX9hcLJewzIiyKW2dZWQ6JVeDfOBtaQipubd//AQ "Haskell – Try It Online") ## Explanation For a string (eg. `"abc"`) we apply first ``` scanl (?) <*> tail ``` which is the same as ``` \str -> scanl (?) str (tail str) ``` This repeatedly applies `(?)` (appends a space to each character in the range *[33..]*) to the `str` until there are that many strings as `str` has characters: `["abc","a b c ", "a b c "]` Now we only need to concatenate the result (minus the last element) with its reversed counter part: ``` init<>reverse ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ 54 bytes *-12 bytes thanks to mazzy* ``` 0..($x=($a=$args).count-1)+$x..0|gu|%{$a-join(' '*$_)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPT0OlwlZDJdFWJbEovVhTLzm/NK9E11BTW6VCT8@gJr20RrVaJVE3Kz8zT0NdQV1LJV6z9v///@ol6v/VU4G4WB3EBgA "PowerShell – Try It Online") Takes input via splatting, which on TIO manifests as separate command-line arguments for each character. We first set `$a=$args` as the input argument. Then we set `$x` equal to the `.count` of that array `-1`. We then need to loop through the letters to construct the spaceship. That's done by constructing a range from `0` to `$x`, then `$x` back down to `0`, then using `Get-Unique` to pull out just the appropriate range. Each iteration, we take our input arguments and `-join` them together with the corresponding number of spaces. Each of those strings is left on the pipeline, and an implicit `Write-Output` gives us newlines for free when the program completes. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~25~~ ~~22~~ 13 bytes ``` zZv"Gtz@he!1e ``` [Try it online!](https://tio.run/##y00syfn/vyqqTMm9pMohI1XRMPX/f3VDI2MTUzNzC0sDdQA "MATL – Try It Online") Thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for suggesting a 5 byte golf, which then inspired me to shave off 4 more bytes! Explanation, with example input `'abc'`: ``` # Implicit input, 'abc' z # find number of nonzero elements (length of string) # stack: [3] Zv # symmetric range # stack: [[1 2 3 2 1]] " # begin for loop, iterating over [1 2 3 2 1] as the loop indices G # push input # stack: ['abc'] tz # dup and push length # stack: ['abc', 3] @ # push loop index, i (for example, 2) # stack: ['abc', 3, 2] h # horizontally concatenate # stack: ['abc', [3, 2]] e! # reshape to matrix of 3 rows and i columns, padding with spaces, and transpose # stack: [['abc';' ';' ']] 1e # reshape to matrix of 1 row, leaving last value on stack # stack: ['a b c '] # implicit end of for loop # implicit end of program, display stack contents ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 8 bytes *-1 byte from @Shaggy* ``` ÊƬqXîÃê ``` --- ``` ÊƬqXîÃê Full program, implicity input U ÊÆ Range from 0 to U length and map ¬ split U at "" qXîà join U using " " times range current value ê horizontal mirror ``` [Try it online!](https://tio.run/##y0osKPn//3DX4bZDawojDq873Hx41f//SsEFicmpxRmZBUoKukEA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` jⱮLḶ⁶ẋƲŒḄ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//auKxrkzhuLbigbbhuovGssWS4biE/8OHKy/igqzFkuG5mP//U3BhY2VzaGlw "Jelly – Try It Online") Returns a list of lines; output prettified over TIO. [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes Just my mandatory Pyth submission. I am quite proud of this so an explanation will likely come soon. ``` +P_=jRQ*L;_U ``` [Try it here!](https://pyth.herokuapp.com/?code=%2BP_%3DjRQ%2aL%3B_U&input=%22E%3DMC%5E2%22&debug=0) ``` +P_=jRQ_.e*d ``` [Try it here!](https://pyth.herokuapp.com/?code=j%2BP_%3DjRQ_.e%2ad&input=%22E%3DMC%5E2%22&debug=0) [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç·9ƒù▌╘Ä┘e ``` [Run and debug it](https://staxlang.xyz/#p=80fa399f97ddd48ed965&i=%220123456789%22%0A%22%40%22%0A%22test%22%0A%22%3F%21%22%0A%22Spaceship%22%0A%2205AB1E%22&a=1&m=2) Outputs with trailing whitespace on each line. Explanation: ``` %R|pmx{]n(m Full program, unpacked, implicit input % Length of input R 1-based range |p Palindromize m Map: x{ m Map over characters of input: ] Character -> string n( Right-pad to length given by outer map value Implicit flatten and output ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 115 bytes ``` s->{for(int l=s.length(),i=-l;++i<l;)System.out.printf(s.replaceAll(".","%-"+(i<0?l+i:l-i)+"s")+"%n",s.split(""));} ``` [Try it online!](https://tio.run/##rU/LTsMwELz3KxZLlWySWC1QHk3TUhAHDpxyRBxMmrRbHMeKnUqoyreHPEojgVQuWLK9OzP2zG7FTnjb1UeFqc5yC9u654VFyc/9wS8sKVRkMVMNGUlhDLwIVLAfAOjiXWIExgpbX7sMV5DWHA1tjmr9@gYiXxvWSgEeM2WKNM5nHTuHJGjxynjzfZLlFJUFGRguY7W2G8pcDDzpOw7OpM/CT2PjlGeF5bp@bhNqeB5rKaJ4KSUlnLhk6BGH4my0kA5OpYfMIYbUx1AR13CjJVpKCGN@Wfmt9TGnjY01EBySApDxxeXV5Prm9m5E3G/svi8bfd8tzvo61HUis0HdQ6PJ8mH8dOjLzrmZt3NvvaddAnYM8HNcqSh5VrqolQScVs38E1qvXeSkpmcTLqIo1pb@@S/5B7YcNLusvgA "Java (JDK 10) – Try It Online") * -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # Oracle SQL, 115 bytes Not a golfing language but... ``` SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v)))))FROM t CONNECT BY LEVEL<2*LENGTH(v) ``` Assuming that the value is in column `v` of table `t`: [SQL Fiddle](http://sqlfiddle.com/#!4/07659/13) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE t ( v ) AS SELECT 'test' FROM DUAL; ``` **Query 1**: ``` SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v))))) FROM t CONNECT BY LEVEL<2*LENGTH(v) ``` **[Results](http://sqlfiddle.com/#!4/07659/13/0)**: (SQLFiddle prints the values right-aligned in the column for some reason... there are no leading spaces) ``` | TRIM(REGEXP_REPLACE(V,'(.)',LPAD('\1',1+LENGTH(V)-ABS(LEVEL-LENGTH(V))))) | |---------------------------------------------------------------------------| | test | | t e s t | | t e s t | | t e s t | | t e s t | | t e s t | | test | ``` [Answer] ## [Perl 5](https://www.perl.org/) + `-M5.010 -nlF`, 34 bytes ``` $,=$"x($#F-abs),say@F for-$#F..$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFqUJDRdlNNzGpWFOnOLHSwU0hLb9IFyikpwck/v934CpJLS7hslfkCi5ITE4tzsgs4DIwdXQydOXSrNWP4TIwNDI2MTUzt7A0@JdfUJKZn1f8X9fXVM/A0OC/bl6OGwA "Perl 5 – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~25~~ 24 bytes **Solution:** ``` ,/'(1+a,1_|a:!#x)$\:+,x: ``` [Try it online!](https://tio.run/##y9bNz/7/X0dfXcNQO1HHML4m0UpRuUJTJcZKW6fCSim4IDE5tTgjs0Dp/38A "K (oK) – Try It Online") **Explanation:** Port of my [K4 solution](https://codegolf.stackexchange.com/a/171725/69200): ``` ,/'(1+a,1_|a:!#x)$\:+,x: / the solution x: / save input as x , / enlist + / flip $\: / pad ($) right by each-left (\:) ( ) / do this together #x / count length of input, e.g. 3 ! / range 0..length, e.g. 0 1 2 a: / save as a | / reverse it, e.g. 2 1 0 1_ / drop first, e.g. 1 0 a, / join to a, e.g. 0 1 2 1 0 1+ / add 1, e.g. 1 2 3 2 1 ,/' / flatten (,/) each (') ``` **Notes:** * -1 byte thanks to ngn [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~115~~, ~~109~~, ~~105~~, ~~100~~, ~~97~~, ~~96~~, ~~92~~, ~~91~~, ~~90~~, 82 bytes -5 & -3 thanks to [Kevin Cruissen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) -8 thanks to [roblogic](https://codegolf.stackexchange.com/users/15940/roblogic) ``` for((c=f=1;f;c-=2*(f>=${#1}),f+=c)) { printf '%-'${f}'.c' `grep -o .<<<"$1"` echo } ``` [Try it online!](https://tio.run/##BcFBDsIgEADAO6/YVAyg0kSvgJ/wA8WVlV4KYb0R3o4z78h5zpbiB9hRaVpjoHB35NCGx0XTM8h@4mFudA1ojOhQ2378CNTZKtlpqBUVbN@WKtgCq/d@kbxsImEuYsz5qhET573@AQ "Bash – Try It Online") --- Note that since the `\` is a shell escape char, the test case `)}/\` should be entered with an extra `\` like this: `)}/\\`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 5 bytes ``` ż∞v↲∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJqIiwiIiwixbziiJ524oay4oipIiwiIiwiW1wiYVwiLFwiYlwiLFwiY1wiLFwiZFwiXSJd) -5 bytes thanks to lyxal. ``` ż # range from 1 to length of input ∞ # Palindromised v↲ # For each character of the input, pad left by each of the above ∩ # Transpose # (j flag formats list of lines as a string) ``` [Answer] # Zsh, ~~95~~ 77 bytes [Try it online!](https://tio.run/##qyrO@J@moVn9P8tWJVpF2VDXMNY6Lb9IIVNBo1pXJUtPTyWrVjM1OSNfTQ0kXKGgoVKtUWxlpWlYq1lQlJlXkqagqgvRqVKdqaxbG1usoFLxH6SjlitNwdDI2MTUzNzC0gDIUdes1Y@JUQeyDEwdnQxdgYzggsTk1OKMzAIguyS1uASkyl4RpMThPwA)   ~~[95 bytes](https://tio.run/##Fcq9DsIgGIXhvVfxWT8JDEUxcWkx/iRegaN1MA0EQmKbwtBIuHak25Nz3p83WVMWszvjVnSUOnlkjBApJQpC1GJDpccZLNAoOMeXa8Q7QUTHuUgsrt8CFCP1bcvKMs32GzTsGow2ecClU4MZU06Vhpqlfd/XRYfT7S4eBc/pMyhv7FQclA9rddmsyTX/AQ)~~ ``` j=$[$#1-1];for i ({-$j..$j})echo&&for x (${(s::)1})printf %-$[$#1-${i#-}]s $x ``` Takes input from argument `$1`. Set `j` to `length-1`. Iterate `i` from `-j` to `j`. For each character `x` in the input string, print `x` and append a number of spaces equal to `length` minus the absolute value of `i` [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~143~~ 135 bytes ``` var s:string;i,j,l:word;begin read(s);l:=length(s);repeat i:=i+1;for j:=1to l do write(s[j],'':l-abs(l-i)-1);writeln until i=l*2-1 end. ``` [Try it online!](https://tio.run/##HclBDsIgEADAr@ytRYsJHiG8wqPxQMu23WYDZEH7fIweJ1NCXQLrtSy9f4JAtbUJpc3RdExszyzRzbhRAsEQx6ocW8@Ytrb/IFgwNCDr6WrcmgUO603LwBAznEINx/o8XtMwWNZhriNrUtoo9z9O8E6NGMjz5a4NYIq33h8lLFh3Kl8 "Pascal (FPC) – Try It Online") I will probably win only against Lenguage... [Answer] # PHP, ~~88~~ 89 bytes ``` for(;++$i<2*$e=count($a=str_split($argn));)echo join(str_pad("",~-$e-abs($i-$e)),$a),"\n"; ``` requires PHP 5 or later for `str_split`. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/115df30d29922cfe22c71b5920d73f2e4b0d5e18). [Answer] # [K4](https://kx.com/download/), 23 bytes **Solution:** ``` ,/'(1+a,1_|a:!#x)$\:$x: ``` **Example:** ``` q)k),/'(1+a,1_|a:!#x)$\:$x:"Spaceship" "Spaceship" "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "S p a c e s h i p " "Spaceship" ``` **Explanation:** Has trailing whitespace on each line. ``` ,/'(1+a,1_|a:!#x)$\:$x: / the solution x: / save input as x, e.g. "abc" $ / string, e.g. (,"a";,"b";,"c") $\: / pad ($) right by each-left (\:) ( ) / do this together #x / count length of input, e.g. 3 ! / range 0..length, e.g. 0 1 2 a: / save as a | / reverse it, e.g. 2 1 0 1_ / drop first, e.g. 1 0 a, / join to a, e.g. 0 1 2 1 0 1+ / add 1, e.g. 1 2 3 2 1 ,/' / flatten each ``` [Answer] ## C#, 113 105 98 bytes ``` s=>{for(int l=s.Length,i=-l;++i<l;)WriteLine(Join("",s.Select(c=>$"{c}".PadRight(i<0?l+i:l-i))));} ``` [Try it online!](https://tio.run/##bZFRT8IwEMff9ynOhYQtjAVUFBkD0fhiMCFi4oPxoZayXVI73BWMWfbZsWMgm3oPbe5//7v8euXU5kkqtmtCFcH8i7R4D6xq5k9RfRwk0kwjP1RuE0WJFP8X5zo1YmBZq/WbNDKXjAhmVmaBib13wjUmakg77wiWEG4pHGXLJHVQaZAh@VOhIh17GLZl0GrhUAbuc4paGCzh3CeoHNv2yJ8LKbh2eDhq2BnPbX/GFo8YxdrBYWcsWziQbXRNBPm2ADBgxbVKccO0OPBsElzAAzNDS6SXV2BpRO7OW5IXsWEpaEGaIAQlPo3rWAOwu6dn572Ly/5Vx/aq@nU9LSbUlfFJPZ@vGBcU46oud3qTm@5dRcv3rynC7E4wHoNTQBKgKkndH0MVFWD/h/5xpw37yTQMIKPcdoOaeenQL@Vvu9kHlH/vNMOmB/2OW@nJrfLMt98 "C# (.NET Core) – Try It Online") [Answer] # **[Scala](https://github.com/scala/scala)**, **82 bytes** ``` for(i<-(0 to a.size)union(-a.size to 0))println(a.map(_+" "*Math.abs(i)).mkString) ``` [Try it online](https://tio.run/##PY5NDoIwEIX3nGLS1YyGhjUREw/AyrgyxgxYtAotactCDGfHEozL7@X9@Zpbnm31VHWAkrWBTwJwUw10EZDd3edwcI7f52Nw2twvlMPJ6ADF39lYGwk5h9VCUOznxjrUuxQzCBZYej0qGoy2BtOVFj0j6mMitHFJdtzjdStAbEoOD8mVR00ku9evNVZaFH457IZWjYKSKZnmLw) Scala has lot of shortcuts that are helping me here and that is quite readable! [**Try Scala**](https://github.com/scala/scala) [Answer] # 8086 machine code, ~~56~~ 53 bytes ``` 00000000 bf 35 01 57 ba 01 00 52 be 82 00 b3 ff ac 59 51 |.5.W...R......YQ| 00000010 aa 3c 0d 74 07 b0 20 e2 f7 43 eb f1 b0 0a aa 59 |.<.t.. ..C.....Y| 00000020 00 d1 e3 08 38 cb d6 08 c2 51 eb dc c6 05 24 5a |....8....Q....$Z| 00000030 b4 09 cd 21 c3 |...!.| 00000035 ``` Assembled from: ``` org 0x100 use16 mov di, buffer push di mov dx, 1 push dx nextl: mov si, 0x82 mov bl, -1 nextc: lodsb pop cx push cx stor: stosb cmp al, 0x0d je cr mov al, ' ' loop stor inc bx jmp nextc cr: mov al, 0x0a stosb pop cx add cl, dl jcxz done cmp bl, cl salc or dl, al push cx jmp nextl done: mov [di], byte '$' pop dx mov ah, 0x09 int 0x21 ret buffer: ``` Test case: [![screenshot](https://i.stack.imgur.com/AheJe.png)](https://i.stack.imgur.com/AheJe.png) [Answer] ## Haskell, ~~64~~ ~~60~~ 59 bytes ``` (""#) a#s|l<-(:a)=<<s,w<-' ':a=l:[x|w<(' '<$s),x<-w#s++[l]] ``` [Try it online!](https://tio.run/##dYwxDoJAEEV7TzEZSIDAXoAMlYWNVtohMRNg1TjAxsFAwdldsbGz/O@9/BvroxXxFgo4@xgxSDYc6CJk4pyTgkiziUwEUc6F5OW8TBSvi0JNspnMFGiallJVvuN7v540wwYAOnaHC7jXeByf@x5CsICnVkf8yh9G/Nduh6Y1u0Es@ndtha/qTe3cBw "Haskell – Try It Online") ``` a#s -- take a string of spaces 'a' and the input string 's' |l<-(:a)=<<s -- let 'l' be the current line, i.e. the spaces in 'a' -- appended to each char in 's' w<-' ':a -- let 'w' be 'a' with an additional space =l -- return that 'l' :[ |w<(' '<$s) ] -- and, if 'w' is shorter than 's', x ,x<-w#s++[l] -- followed by a recursive call with 'w' -- and by another copy of 'l' (""#) -- start with an empty 'a' ``` ]
[Question] [ ## Introduction: A few days ago I read [this post with the same title](https://skeptics.stackexchange.com/questions/44245/do-the-26-richest-billionaires-own-as-much-wealth-as-the-poorest-3-8-billion-peo) when I came across it in the HNQ. It asks if this claim of US presidential candidate Bernie Sanders is true or not: > > Today the world's richest 26 billionaires, 26, now own as much wealth as the poorest 3.8 billion people on the planet, half of the world's population. > > [Link to video](https://www.youtube.com/watch?v=QThknQs-gIc&feature=youtu.be&t=655) > > > Please go to the question itself for answers and discussions there. As for the actual challenge based on this claim: ## Challenge: **Two inputs:** a descending sorted number-list \$L\$ and a number \$n\$ (where \$n\$ is \$1\leq n\lt \text{length of }L\$). **Output:** the longest possible suffix sub-list of \$L\$ for which the total sum is \$\leq\$ the sum of the first \$n\$ values in list \$L\$. **Example:** Inputs: \$L\$ = `[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]` and \$n=2\$. Output: `[125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]` *Why?* The first \$n=2\$ values of the list \$L\$ (`[500,200]`) sum to `700`. If we take all suffixes of the remaining numbers, as well as their sums: ``` Suffix: Sum: [-3] -3 [-2,-3] -5 [0,-2,-3] -5 [1,0,-2,-3] -4 [2,1,0,-2,-3] -2 [2,2,1,0,-2,-3] 0 [3,2,2,1,0,-2,-3] 3 [5,3,2,2,1,0,-2,-3] 8 [5,5,3,2,2,1,0,-2,-3] 13 [5,5,5,3,2,2,1,0,-2,-3] 18 [5,5,5,5,3,2,2,1,0,-2,-3] 23 [10,5,5,5,5,3,2,2,1,0,-2,-3] 33 [10,10,5,5,5,5,3,2,2,1,0,-2,-3] 43 [20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 63 [30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 93 [30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 123 [40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 163 [50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 213 [55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 268 [75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 343 [75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 418 [100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 518 [125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 643 [150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 793 [150,150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1,0,-2,-3] 943 ``` The longest suffix which has a sum lower than or equal to `700` is `[125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]` with a sum of `643`, so that is our result. ## Challenge rules: * Values in the first \$n\$ prefix aren't counted towards the output-suffix. I.e. inputs \$L\$ = `[10,5,5,3]` and \$n=2\$ would result in `[5,3]`, and not `[5,5,3]`. * I/O is flexible. You can input \$L\$ as a list/stream/array of integers/decimals/strings, a single delimited string, one by one through STDIN, etc. You can output as a list/stream/array of integers/decimals/strings as well, print/return a delimited string, print a number on each newline, etc. Your call. * The output is guarantees to be non-empty. So you won't have to deal with test cases like \$L\$ = `[-5,-10,-13]` and \$n=2\$ resulting in `[]`. * Both (or either) the input and/or output may also be in ascending order instead of descending order if you choose to. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: L=[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3], n=2 Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3] Inputs: L=[10,5,5,3], n=2 Output: [5,3] Inputs: L=[7,2,1,-2,-4,-5,-10,-12], n=7 Output: [-12] Inputs: L=[30,20,10,0,-10,-20,-30], n=1 Output: [20,10,0,-10,-20,-30] Inputs: L=[100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5], n=1 Output: [15,5,5,5,5,5,5,5,5,5,5,5,5,5] Inputs: L=[0,-5,-10,-15], n=2 Output: [-10,-15] Inputs: L=[1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250], n=2 Output: [525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250] Inputs: L=[10,5,5], n=1 Output: [5,5] ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~88~~ ~~81~~ ~~69~~ ~~68~~ 63 bytes *-4 bytes thanks to [LiefdeWen](https://codegolf.stackexchange.com/users/68917/liefdewen)* ``` a=>b=>a.Skip(b).Where((x,i)=>a.Skip(i+b).Sum()<a.Take(b).Sum()) ``` [Try it online!](https://tio.run/##lU9Na8MwDL3nV5ieZKYYx5nZoIlvLXT01kIPYwcnuJvo6o580MHYb89Usw22W9ET6OnB01Pb521P03KMbbWmfqgoDg4T5QlXizgeQ@eb15AU58S@nnztmtp5tTnQGzRS7V5CFwDekeTvmm5Y2IxHkJVXW38I8MPlNM/@@woStdgDxHAWj08fVms03IX9bmOxYH5nL7AMjbcaywTDesI92lQlGq4CNeYG8/JTqu3p8hufBiPn2a6jIawpBuiHjuKzejhRhBnOOD/LWfY3DDsn1yt9pi8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [EXAPUNKS](https://store.steampowered.com/app/716490/EXAPUNKS/) (2 EXAs, 30 Instructions, 594-byte solution file) I've wanted to try a code golf challenge in EXAPUNKS for a while, and you looked like the best fit I could find, so, congrats! Input via files 200 and 201, for L and n respectively. Output via a new file. L and the output are in ascending order. Basically, XA sums the last n values in L, then sends it to XB. It then seeks to the beginning of L and sends each value one-by-one to XB. XB first receives the total from XA and stores it in register X. It then receives values one-by-one from XA, deducting the new value from X, and writing those values to the output file until X < 0. ### XA ``` GRAB 201 SUBI T F T DROP GRAB 200 SEEK 9999 SEEK T MARK FIRST_SUM ADDI F X X ADDI T 1 T SEEK -1 VOID F TJMP FIRST_SUM COPY X M SEEK -9999 MARK SECOND_SUM COPY F M TEST EOF FJMP SECOND_SUM KILL ``` ### XB ``` MAKE COPY M X MARK LOOP COPY M T COPY T F SUBI X T X TEST X > 0 TJMP LOOP SEEK -1 VOID F KILL ``` JavaScript for the level [here](https://tio.run/##tVbtbts2FP3vp7gwMMDGKFuSrdjxFgxGsqABvLRog/3xgoCW6YirTKokZaUd@gB7jz3ZXiS7JOXEdpSgRTuLjEXynPtF8jh/0g3VqeKFCTbj@/t@H86lApMxyKlh2sD0jss1/M6VKWl@yUwl1fsfwVO4uIWlTMs1E4YaLgWBFloockY1gw3X3EwgM6aY9PtVVfU@0TQzSgqe6l4q1/2Ntyq81b7lXoiiNHoCs5N5EoYkxh4ldY8TEuF4lNiWYAvJMCQD12Jcd21MEvcMSIxPREISxCQYXBMQJ7H18Lo06GIC82@zZ00dBIxoh2zwZWcbGCNn0hockiAhAVoIotjxR3t8O9vAfwg09FwcBIPQ8aM9fhOqMQNMPiG2MAl59mmw/yK8wVH4mG7SUK7tSnOIITk@PsY@Jsf4PrZbeHREEoza9qHNYWiPC3a7gbg8IoMBTrgCoN8h9jgJm/bp6408exAayuSq0VqVIrW3BW6ZueImZ50u/NUC/ChmSiWgbe@MxkuTyiW7lfmqpw1N37O7NKPilrm786HE24lGdD8aj5Io7C9lgNc2iI8CxdMMF4MFz3NEUK6YDmQlAqqDdZlmQcVobjI7tIxCSmXhg2C8pQQFk@2fWp/3Y31XLkxjuE@hZ6xWCCmeoM@k05f4COpAYTdQwECBarCBgg/UDi2jDhQGvfGWAhgoys0vfwg4zWieMyzPBK4qCbzeDgpaKsOWIMr1gqkg52hhBp0VzzGGMOwCFUtE@WUQDytRFzpVxhTDOa4h@vfvf8TP1gEGJFcw6/Ye9tXJpUTXaLqQWvMFWigUW/E70OXC@7QcWKG4Vhmm7ThGGpojYm0doH03aYeIta8rrpAoYENz3G1MCXz0vYOCc8ENpzn/xK4whLel6Bj/vS39hip4M307/e0dnMDcTc3n311grXB9o6pek21wO2Lq7NrXx9VnhXNksfb1EfusSEYW27S0G8UXCqKz9SLm0eiB@MU@ZD/cc/0dhc7X8OuZhxuyTdVl5Jb8X3vgUvzVvymoomuNx8yft3l9EuGHeqLnr5BnzRB3wJyH19h6im2Y0ig1DieacZG3It01bIBEh3aKnH5k6iaT2sJRp964iVc4rhGpYvh/z6VUa5qfoxB0dijEqgKB84vZrzcXp68vb86mV1Oshbj@Mm74lDvr1tL4oUTxO3UGnlJ9ggTaLwqOLlf/n@DsZujK1TZUYQHbBBICmNkAW3dPlaQ4/ZjmmI7gOmNL9zvwuXV//x8) [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` l,n=input() s=sum(l[:n]) while sum(l[n:])>s:n+=1 print l[n:] ``` [Try it online!](https://tio.run/##pVHbboMwDH1uviKCl7I5Ui64XCT2IxFPHVKRWIoGVbuvZ3aYSh@2SdOwj0SOT@yTZPyYT@dgl@P5tWuSJFkGCE0fxsu8z8TUTJe3/eDr0GbieuqHTq5EqNvsZarDc2PE@N6HWUZuoQZCdLfuKLnfUyEWj1qDJRj8gkUwtC6QEyk15BpcTEv1mCVgDAeWwoAGZUG5FqTdpdL/r4nwVIyF2O/@pZ4p4YuoZm0OCkGRWhlL2mJTMiH8fZpeVbRQTpPSyE36nYItkFkEPgjCj/HQKvW/CoXXm1neZ@Xu0e5Kx7kaqqoilFDRf8n3eDgAkhVGzsZyfigC3yKVC3COiHgImpETLOp1CN3a33d@Ag "Python 2 – Try It Online") --- **Explanation:** First takes the sum of the first `n` items. Then the sum of each sublist is compared to this sum. As soon as one is not larger, we stop. Then the resulting (longest) sublist is printed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 12 bytes Saved 2 bytes thanks to *Grimy* ``` .$ΔDOI¹£O›.$ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fT@XcFBd/z0M7Dy32f9SwS0/l/38jrmhDAwMDHUtLSyC20LEEsi2A2NzMTMfUyBSMTYB8YxMDHUMjIDYEyeuYm@sYGwMFdAx0dA1NdXRNgNjI1CAWAA "05AB1E – Try It Online") **Explanation** ``` .$ # drop the first n entries of the list Δ # repeat the following code until the result doesn't change DO # duplicate and sum the copy I¹£O # calculate the sum of the first n items of the input ›.$ # if the current sum is greater than the sum of the first n items # remove the first item of the current list ``` [Answer] # [J](http://jsoftware.com/), 18 bytes ``` }.#~+/@{.>:+/\.@}. ``` [Try it online!](https://tio.run/##dVC7CgJBDOz9ikELEXXdV7wHKIJgZWUtbCEeYuMHiP76OdkTTwtJBjaZMJnstR2acYNVjTFmsKiJucH2sN@1DzN6Thebu1nX08XRbB6mnQwwOJ8uN3g0EGvhCSdveIFjXYimMC2iRcjpyecsITkCNTwc9yWPFHpZzmS@6xTsFHlQxyKSIHEiOd/xjvxH3nYcixRsz6upIFB7gr/RO7D9Fvn2RZmqqogSFd@l3rpcQiisiLom6j8QeinpAiGwkZ1RMxJefqzp6vYF "J – Try It Online") ## Explanation: A dyadic verb, taking `n` as its left argument and `L` - as its right argument. ``` }. drop the first n items from L @ and \. for each suffix (starting from the longest) +/ find its sum >. is this sum smaller or equal than (results in a boolean vector) +/ the sum @ of {. the first n items of L #~ use the 1s in the boolean vector to copy the respective }. elements of L (without the first n) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~47~~ 43 bytes Takes an ascending list as input. Removes \$n\$ items from the end of the array to get the initial sum, then continue removing items until the remaining elements' sum is less than the initial sum. -4 bytes by reading the spec more closely. ``` ->a,n{s=a.pop(n).sum;a.pop while a.sum>s;a} ``` [Try it online!](https://tio.run/##dU/basMwDH3PV5iyhxZk49hRkxDSHwmjeJvbBbw0xGnHGPv2THJ2exk6Bywd6Viarg9vy6ld5MHB8B5bp8bLuB12Kl5fmpSI1@c@eOG4coiN@1jWwtnPMRM0JVpxd1RxDP0sNs0mE6M4qUcXgvA3F7ZupyZ/81P0IAY1X4595oenpUOtwRBz/KJByCkvkYEEDYUGm2BIT6gAU1gwFDlokAakvW@EyTrSk7ZmZWpguQCJIEmVuSGtzLofS73WKZFWk5azC32JwOsg/Btrr/51xu8daLyua2IFNb0rvmm/ByRDZsH2Bd9L5ItILsFaKqRtyK8gGtR/j@LvPgE "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 53 ~~55~~ bytes @Giuseppe saved me 2 bytes changing the way remove was done ``` function(n,L,Y=rev(L[0:-n]))Y[cumsum(Y)<=sum(L[1:n])] ``` [Try it online!](https://tio.run/##dVDLasMwELz3SyQYweqxsR3qP/APGJOTqaGHuJDG/X13VgluLmV3kLSzzM7qti/9vmzrfP/8Wt2KAWN/@/hxwyTnsF68H6d5u35vVzf6997OYYpnEpd9cQmzUxEkIuoTSRH5btRSmYIiyDUT@ZottEZGYkQIQkLI3r89VNlS6VpoWGhqmzUVBEVgQ4ip0pH0oS0Pio@Q5aDNUFaYNcW/cUyXvxH6YokiXdcRLTreW9vydIJS1lBsSLEfIGxH0g1yZqHaomQhkr76es7dfwE "R – Try It Online") Takes the input as descending and outputs in ascending as allowed by rule 4. * `Y` is the rev of `L` with 1:n removed using `0:-n` * returns from `Y` where cumulative sum is less then equal to the sum of `L[X]` [Answer] # JavaScript (ES6), 66 bytes Takes input as `(a)(n)` with the list in ascending order. ``` a=>n=>(g=s=>n?g(s+a.pop(n--)):eval(a.join`+`)>s?g(s,a.pop()):a)(0) ``` [Try it online!](https://tio.run/##dU/RboMwDHzvV/DWRLVREkgDk8I@ZJrUqKOoFUpQg/r7zKZdtz5MtiHKXe58l3AL@Xg9TzPG9NUvJ78E30XficFnOrwPIu9COaVJREQp3/pbGEUoL@kcD7uD7DIz4M4gOEih5DL3eS58EQrfFZE/xxRzGvtyTIM4CSJFuUqILWyl3Gz4gfjACtCAAg2GqgK7VgNacRsF1dq1Akttwa2tFcGG/nTJYxTj6lMKIx/Cdyn9cofaAJIsWsCafdnVEcM9GeSF5Mqs3w2IoX8YFv4rbYFWqtbt/r5AAh6ur9sY2hxrBi2bUfwKnIOGzhyfrWuOTtlImMft9wQraHnahqZltxfZZ2wtl28 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => n => // a[] = list, n = number of richest guys ( g = s => // g is a recursive function taking a sum s n ? // if n is not equal to 0: g(s + a.pop(n--)) // recursive call: add the last entry to s and decrement n : // else: eval(a.join`+`) // if the sum of the remaining entries > s ? // is greater than s: g(s, a.pop()) // recursive call with the last entry removed : // else: a // stop recursion and return a[] )(0) // initial call to g with s = 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes Also compatible with Python 3 ``` f=lambda l,n:l[n:]*(sum(l)/2>=l.pop(n)+sum(l[n:]))or f(l,n) ``` [Try it online!](https://tio.run/##pVHbTsMwDH0eXxFpLw04kJvXdtL4kWoPQ2gCqWurMR74@nKcTk2RAAlR@0iNfY5jO8PH5aXv/Dged@3h9PR8UC1127bptvvb4u39VLT6wT/u2vuhH4pO36WQZLXuz@pYgK3H4fzaXXBo2FrygOMrPJPDuWRxhluKlkJyj3zyijhZIA9zZMl4MmFPyuvVuvlfkZu5OZASYao7f@tGYplWJrmIIxkmA5lxHqJSZ4lEsmTuw050HEywkDitsuY7yrI7zMMkszL9aMua2MxvzFza5jk4Da9Wy0mm@JdOLNV1DVRU47@S5W82xGhOEKXVKK8LyOqRLikEBNJ4uCwCnu31Nqz479LxEw "Python 2 – Try It Online") --- **Explanation** The sum of the suffix is compared to half of the sum of the whole list. If the sum of the suffix is smaller or equal, the suffix is returned. If not, the function is called recursively with the first item of the suffix popped out. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~16~~ 15 bytes ``` efgs>vzQsT._<vz ``` [Try it online!](https://tio.run/##K6gsyfj/PzUtvdiurCqwOEQv3qas6v//aF1jHQVdIx0FAx0FQx0FIzACCpnCkAVQ3ACCjYDYGIpNgNgUhIFKzKHY0ACk0AjEAkmBCSMDsEKDWC4jAA "Pyth – Try It Online") The input list is expected to be sorted in ascending order, rather than descending as is used in the examples. It's at times like this when I really wish Pyth had a single token operator to access the second input more than once (`E` evaluates the next line of input, but repeated calls discard the previous value read). ``` efgs>vzQsT._<vzQ Implicit: Q=eval(input()), z=input() - that is, Q is list, z is string n Trailing Q inferred vz Evaluate z as integer < Q Remove the above number of elements from the end of Q ._ Generate a list of all prefixes of the above f Filter keep elements of the above, as T, where: >vzQ Take the last z elements of Q s Sum g Is the above greater than or equal to... sT ... the sum of T? e Take the last remaining element, implicit print ``` *Edit: saved 1 byte thanks to MrXcoder* [Answer] # JavaScript, 64 bytes ``` f=(a,n,s=0,[h,...t]=a)=>n<1?f(a)>s?f(t,0,s):a:1/h?f(t,n-1,s+h):s ``` [Try it online!](https://tio.run/##lVHLbsIwELzzFdyI1XHqR5Y8VNMf4A8QB4sSAkJOVUf9/XTtVu2pUtDuyF5bs7OPm//08fRxfZ9kGN/O89y7wiMgOoXDgLIsp6Pzwu3Ci37tCy92kY8JClF0vtPPQw6D1IhPg@jivHcHUgqGoekHhqA5rik5sStUCja74f/sDSibhWHTLCENpD1iHZxZncYQx/u5vI@Xoi/2CKK8jddQbLDeCLFasSznyPzljDoLJZkKkiA5g9Qm8@sl/N/y1TeXA2lV5utlFfMICGk8hH9teT711wU9Mjcuo21bRoOW703a1XYL4sISqlRmlfbISJvi7xrW8kPunDUrhiH16LIWtjZ/AQ "JavaScript (Node.js) – Try It Online") ``` f=( a, // remaining array n, // if n >= 0: we try to find suffix <= s + a[0..n] // if n is NaN (or undefined): we calculate sum(a) + s s = 0, // previous sum [h, ...t] = a // split array (a) into head (h) and tail (t) ) => (n < 1 ? // if n == 0 f(a) > s ? // if sum(a) > s f(t,0,s) : // drop head and test tail again a : // otherwise, a is the answer 1 / h ? // if a is not empty f(t,n-1,s+h) : // add head to sum and recurse s // we only reach here if n is NaN, return the sum ) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` îo╧╫Σ↑>'qµΣº ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=8c6fcfd7e4183e2771e6e4a7&i=[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]+2%0A[10+5+5+3]+2%0A[7,2,1,-2,-4,-5,-10,-12]+7%0A[30,20,10,0,-10,-20,-30]+1%0A[100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5]+1%0A[0,-5,-10,-15]+2%0A[1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250]+2%0A[10,5,5]+1&a=1&m=2) [Nicer version](https://staxlang.xyz/#c=%3A%2F%7C]%7B%7C%2Bn%7C%2B%3E%21%7Djm&i=[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]+2%0A[10+5+5+3]+2%0A[7,2,1,-2,-4,-5,-10,-12]+7%0A[30,20,10,0,-10,-20,-30]+1%0A[100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5]+1%0A[0,-5,-10,-15]+2%0A[1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,-15,-45,-250]+2%0A[10,5,5]+1&a=1&m=2) ### Unpacked (14 bytes) and explanation: ``` :/|]{|+n|+>!}j :/ Split array at index. |] Suffixes. The bit after the split (the poor) is on top for this. { }j First item in array that yields truthy under the block: |+ Sum array (collective wealth of the many). n Copy second item to top of stack. |+ Sum again. Wasted computation, but this location saves a byte. >! Second item on stack less than or equal to first? ``` By [consensus](https://codegolf.meta.stackexchange.com/a/8507/73884), I can leave this result on the stack. Stax will attempt an implicit print, which might fail, but appending an `m` to the unpacked program lets you see the output nicely. Looks like `{ ... }j` is the same as `{ ... fh`. Huh. Edit: That's not quite the case; the only the former will stop when it gets a truthy result, possibly avoiding side effects or a fatal error later on. [Answer] # APL+WIN, 27 bytes Prompts for input of L then n. ``` ⌽((+/n↑v)≥+\m)/m←⌽(n←⎕)↓v←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6tmroaGtn/eobWKZ5qPOpdoxuZr6uUB5kEQeiO6bqvmobXIZhPkfqOl/GpehgYGBgqWlJRBbKFgC2RZAbG5mpmBqZArGJkC@sYmBgqEREBuC5BXMzRWMjYECCgYKh9YbmgIJExBhZGrAZcQFNlLB2FQBqBcohxNyGYKVQpkA "APL (Dyalog Classic) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` £sV+YÃæ_x §U¯V x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o3NWK1nD5l94IKdVr1YgeA&input=WzUwMCwyMDAsMTUwLDE1MCwxMjUsMTAwLDc1LDc1LDU1LDUwLDQwLDMwLDMwLDIwLDEwLDEwLDgsNSw1LDUsMywyLDIsMSwwLC0yLC0zXQoy) ``` £sV+YÃæ_x §U¯V x :Implicit input of U=L and V=n £ :Map U, with Y being the 0-based indices sV+Y : Slice U from index V+Y à :End map æ :First element that returns true _ :When passed through the following function x : Reduce by addition § : Less than or equal to U¯V : Slice U to index V x : Reduce by addition ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` ṫḊÐƤS>¥ÞḣS¥Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8///hztUPd3QdnnBsSbDdoaWH5z3csTj40NKHOxb9//8/2tTAQMcIiA1NodjIVMcQyDc3BSFTIDLQMTHQMQYjI6A8GFnomIKhsY4REBrqGOjoGunoGsf@NwIA "Jelly – Try It Online") Thanks to @JonathanAllan for saving a byte! A dyadic link taking the list of values \$L\$ as left argument and the number \$n\$ as right. ## Explanation ``` ṫ | Tail: take all values of L from the nth onwards (which is actually one too many; dealt with below) ḊÐƤ | Take all suffixes, removing the first value from each. This will yield a list of all possible suffixes of L that exclude the first n values Þ | Sort by: S>¥ ḣS¥ | - The sum is greater than the sum of the first n values of L Ḣ | Take the first resulting list and return from link (implicitly output when called as a full program) ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 12 bytes ``` eSe¤Σ¤┅⟪Σ⊃⟫∇ ``` [Try it online!](https://tio.run/##ASwA0/9nYWlh//9lU2XCpM6jwqTilIXin6rOo@KKg@Kfq@KIh///WzEwIDUgNV0KMQ "Gaia – Try It Online") I think there's a byte I can golf if I get the stack just right. ``` e | eval first input as Gaia code S | Split into a list of ["first n elements" "rest of elements"] e | dump onto stack ¤Σ | swap and take the sum (sum of first n elements) ¤┅ | swap and take suffixes ⟪ ⟫∇ | return the first element of suffixes where: Σ⊃ | the sum(first n elements) ≥ sum(suffix) ``` [Answer] # [Haskell](https://www.haskell.org/), 46 bytes Displeased with how this looks; hope I’m just missing some obvious golfs. ``` n#l=until(((sum$take n l)>=).sum)tail$drop n l ``` [Try it online!](https://tio.run/##pVJNb4JAEL37KybqAeJil48VMcFb0zRp0kN7Ix6IrIGIQNg19t/TmUXFJtpD6@7AzLy3O29w8lTtZVl21sSG1QpeKw3OGhJ8b65OV03K@FjporQsSx0PU53uJVRQ2uvYnmPC1mlRTrO2bijbHdKiMpe9g2WPTBRDVo8AGvAgEZwzD80VZ/MEczEOBW2Bm7OAM99sD3Gzl0yY5TMPl8s4czzm@BtI/nf@ogopBsYL6WnSISShIRM1YI5gDtIc10MSPQ3JheRah/cEDByfI@le9nKIJPuCkXjBHi7q7zf4Ip8P6oRR13tDd1gtiiK0JYvQX9IHWyyYwPpkAakJ6M9Ao8@FcMh8HxNGP14eoHmC2vrDoaHrc1dn8adcthLfBD@aP3L6Wep5OGPQSoVDVewwmGD4FFPG4D9/OpcVNEf9odu3CqYw/pRKww7nVWZzMME2VXIFY5jNQOX1CW9DbzyH569GbrXMbjEq26Mvtb4FLKPDvqNAlkoOCvr6TaoU1h933w "Haskell – Try It Online") I tried getting the prefix and suffix using `splitAt` and pattern matching in a guard, but that turned out to be 3 bytes more. Planning on trying to convert to a recursive function with guards later to see if that lowers the byte count. # Explanation ``` n # l = until (((sum $ take n l) >= ) . sum) tail $ drop n l n # l = -- define infix operator n -- the number of elements l -- the list until -- until sum -- the sum of the suffix ((sum $ take n l) >=) -- is <= the sum of the prefix tail -- remove the first element drop n l -- the suffix ``` What I refer to as "the prefix" is the first `n` elements and "the suffix" is the rest of the list. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~23~~ 21 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous prefix lambda, taking \$n\$ as left argument and \$L\$ as right argument. ``` {⍵↓⍨⍺⌈⊥⍨(+/⍺↑⍵)<+\⌽⍵} ``` [Try it online!](https://tio.run/##hVCxTgJBEO35iutOZRb2dm@5u0QqGzEqidhxFESCFgRJPApDqEyIIUA0hk8wsbOyMbHxU/ZHzjcL0QYwM7OZ2Zk3b2bag57o3Ld7t9d5rT8YZnd28jSy0wc7/3T6VvbTZukgbfmen3Z8u1g2RnhOGvVzO/8onbWzq5sxvHGhPsyAB3ydzkf4tpMX9OBOs0c7fYW/VyxzOHlGdv@wmNrZF8PzLiPnC4BrdfB/v2uuAd3FEd7L41ojXzF4XW81qX9abRopScECszZlKEAcGVYDlRRK0k4V8k5jMk40KUhAkoQioVvk9avKL2zgAcgBdpRErhU3CkkYEoCIQDlAtBHwO5FcFSMQWjpAsGUIrGGIVzS0VXY0kH@DmZ3LgihJElhMCfyYL1qpkAE1W8iDhHxtGN8T6Yi0xodbBiQhTBn570nX0/4A "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; \$n\$ is `⍺` (leftmost Greek letter) and \$L\$ is `⍵` (rightmost Greek letter):  `⌽⍵` reverse \$L\$  `+\` prefix sums of that  `(`…`)<` Boolean mask where less than:   `⍺↑⍵` take the first \$n\$ elements of \$L\$   `+/` sum those  `⊥⍨` [count trailing truths](https://codegolf.stackexchange.com/a/98764/43319)  `⍺⌈` the maximum of \$n\$ and that  `⍵↓⍨` drop that many elements from the front of \$L\$ [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes *1 byte saved thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe), based on the answer by [@MickyT](https://codegolf.stackexchange.com/users/31347/mickyt)*. ``` :&)PtYsbs>~) ``` Output is in ascending order. [Try it online!](https://tio.run/##y00syfn/30pNM6Aksjip2K5O8/9/I65oUwMDHSMgNjSFYiNTHUMg39wUhEyByEDHxEDHGIyMgPJgZKFjCobGOkZAaKhjoKNrpKNrHAsA) Or [verify all test cases](https://tio.run/##dY@xCgIxDIb3PohwkEKaNterg5MP4OAiR0GddbqbffX6px46SfJDk4/@SZ639dGubb8bTutluS@H19CO5yZuVmYSKOgmUQqos1oqkikxxZ4C3nMi7RFJEIGYvJCP1cERuKPqsptzxwYTeSUP6INUF9z89eNPG4WP3JEtEJVsFaW/0afxz1a38fhcSoEmKnhPds04ksLOlMw82aWQ3QKcKUY0@iqwS5Ao1zc). ### Explanation Consider inputs `2` and `[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]`. ``` : % Implicit input: n. Push [1 2 ... n] % STACK: [1 2] &) % Implicit input: array. Two-output indexing: pushes the subarray % indexed by [1 2 ... n] and the remaining subarray % STACK: [500 200], [150 150 125 ... -2 -3] P % Flip % STACK: [500 200], [-3 -2 ... 125 150 150] t % Duplicate top of the stack % STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -2 ... 125 150 150] Ys % Cumulative sum % STACK: [500 200], [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946] b % Bubble up in the stack % STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], [500 200] s % Sum % STACK: [-3 -2 ... 125 150 150], [-3 -5 ...646 796 946], 7 >~ % Greater than, negate; element-wise % STACK: [-3 -2 ... 125 150 150], [1 1 ... 1 0 0] ) % Index. Implicit display % STACK: [-3 -2 ... 125] ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~99~~ 97 bytes ``` param($n,$l)do{$a+=$l[$i++]}until($a-gt($l[-1..-$n]-join'+'|iex)-or$i-gt$l.count-$n)$l[($i-2)..0] ``` [Try it online!](https://tio.run/##dZHRboMwDEXf@xWo8kaiOCgJpJRV/Yu9VWhCHd2YGFQt0yZRvp3ZULV7mWIHdK/xscWx/S5P5/eyrkc4bPvxWJyKTwENQi1f2x4KtYV6B5VS@fDVdFUtoNBvnSBR2yjS0OT6o62aUIWXqvyRuj1BRQVQR/uWPqACSbWCRCejyOTjsBAL4TAQOkbt0KBFRydGP501WsPhDMZTJAY9hcd0CmvIdvQkkdMZ9o2UOHed@9hZSBljHWpqqD3qhInMSyfbTlOQRTAuuYNvtsf/jvVIY8TTRDe6JvUK@yM6mlMn7Hhm0LIxpimu6Z2XZWLCi9Im1JIzXa3INphxZmvKjDn3ua4gKRfy8tAvn8tz9xQsFeyV2ohHOATwsjM53zaX8x/CcBOE4TD@Ag "PowerShell – Try It Online") Takes list in ascending order, output is descending (because it was easier to compare to the test cases :^)) Goes through the list ~~backwards~~ forwards, comparing the accumulator to the last `n` entries added together (via gluing them together with `+`s and passing the resulting string to `invoke-expression`). The Until loop needed additional logic to handle going into the Rich Neighborhood because it wouldn't stop if we're still not richer than the Rich Guys until we churn through the entire list. Unrolled: ``` param($n,$list) do{ $acc+=$list[$i++] }until($acc -gt ($list[-1..-$n] -join '+'|invoke-expression) -or ($i -eq $list.count-$n)) $list[($i-2)..0] ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 99 bytes ``` \d+ $* ^ ;, +`;,(1+)(,.*)1$ $1;$2 , ;$'¶$`, ;.*(;.*) $1$1 T`,`_`.*; 1G`(1+);\1; .*; (1*), $.1, ,$ ``` [Try it online!](https://tio.run/##dUxBCgIxELvPO0Zsu6F0ug4KfcB@wOOiFfTgxYP4Nh/gx@p0WY@SBCYTkuftdX9c2sZNtc3XgTjQiQpoqAVOBu8QgxcmlsKZQIW3nzdXO2JwJm8JCx0r6rnGUEim2ntllkLdk5PgQRwFBKbWNCVkk@iqrBDze@1UY8IuYVyYLV94gC4YkQ0Ci8je64v6wKjoU4r/kF9Hvg "Retina 0.8.2 – Try It Online") Link only includes some test cases; I could get it to [work in some cases with negative numbers](https://tio.run/##dU8xbsMwDNz5DhWV7JMhSlZiQygy5hNB4QLt0KVD0Lf1AfmYcxTSbgXvAJInHqnrx/fn19v@5M/bfnkfxQ3yKg0ybg1ex@AxDUGdOG0uC6S559uP25hMgycDFacCf3qZhhaEgxpHlSh6vm4XbV6HEE9NqIpYAXGTQuBk32tKyKTWB3OFsj5WQyUS5oTSkal3LKg9CjJDkRAzIiuh@BDkb4Cq2guSPRXzLxW2qeL/0F@zPpGwriu5YGW@2ImHAypNjLNZznY@aQdSPqIUNvr6ijiTmb/Jdw "Retina 0.8.2 – Try It Online") at a cost of 12 bytes (in particular the first `n` entries in `L` still need to be positive; theoretically I could probably only require the sum of the first `n` entries to be positive). Explanation: ``` \d+ $* ``` Convert to unary. ``` ^ ;, ``` Insert a marker at the start of `L`. ``` +`;,(1+)(,.*)1$ $1;$2 ``` Move it down the list `n` times, summing as we go. This deletes `n` but its comma remains. ``` , ;$'¶$`, ``` Create an entry for each suffix of `L`. ``` ;.*(;.*) $1$1 ``` Replace the middle with a copy of the suffix. ``` T`,`_`.*; ``` Sum the copy of the suffix. ``` 1G`(1+);\1; ``` Take the first entry where the suffix sum does not exceed the prefix sum. ``` .*; ``` Delete the sums. ``` (1*), $.1, ``` Convert to decimal. ``` .,$ ``` Delete the trailing comma that came before `n`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` IΦθ¬∨‹κη‹Σ…θηΣ✂θκ ``` [Try it online!](https://tio.run/##LYrBCsIwEER/pcctTCFJDQoeA55EhR5LDyUEUhpbTaPg18ckdOcN7M6stqPX6@hifPhpCaTGLdBlcsF4eqO6rYHunq5m22hGZWtUZe8@T1I/7Yyy6ys/2jpVOe3cpE1O5nqfc4x9LxmDSOZyt5Dg6T7KjEwwHBjagkh94QRZ1EIkcTA0Ak07QAyx@bo/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input `L` Φ ¬ Filter out elements where κ Current index ‹ Is less than η Input `n` ∨ Logical Or θ Input `L` … η First `n` terms Σ Summed ‹ Is less than ✂θκ Remainder of `L` Σ Summed I Cast to string Implicitly print on separate lines ``` [Answer] # [Red](http://www.red-lang.org), 63 bytes ``` func[L n][s: sum take/part L n forall L[if s >= sum L[break]]L] ``` [Try it online!](https://tio.run/##dVDLTsMwELz3K@YHLPzaJqkEX5ATV8uHQGOpakkrJ/3@MDaopQi0O5K9O56ddR736@u4D3GTdljTdXoPPaYY5h3m6weW4Tg@XYa8gFWkcx5OJ/ThkDDj5blS@vCWx@EYYx/XSz5MCxKCaA1LGPmGFRjeGykpTA2v4Wpa9mu2kBoOlmGgoSyUi7CbmzJplfJQbCq9kD2UQJGkjI1o7pTbHP3V5kU5HWF@StOOoFgV/BsPT/R9nPyySbGu64gWHc9t2X67hVC@wJdhvvwMUXZnu4FzLFSLlPWEFf3H@vSwfgI "Red – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 86 bytes ``` param($n,$l)$l|?{$k++-ge$n}|?{(&{$l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]};$s})-ge0} ``` [Try it online!](https://tio.run/##pVPvToMwEP/ep2jIbWnDNSmFDtAs7j2MWRatugznHDOaMJ4dr7ABMdMPSu8C9/93d2X3@uH25bMrigYe@ZxXzW61X70I2CIUEorjTQWbMFRPDrY1CWJakXJSQRnOBSxRo4KlvCV/VThYy1CEIay9@0be1ddQ1pIEXTc1YwvBGAp6RRotnVgiM8g5XwgvMHkyW63REEf2xMZiRHJqPVkijYnGuCVD9payNiclQkMn8sgMqr7G6CEA/8rYA01btVcmqCwqilGRoYrpt4ptUW/qQ/s6ugsjQcWaQiMk10umPtQDjy36Fiz@eLpUQ8e/ufap9dCGHZZzVowRaMzznDjDnL4zP8vZDC2B8px4iInfHLGfJJlTjGNStF1RkYTYWH1hPaOR/SHfCOQwBn/BOvySH/mEV8znhwI53XMO7nPn7g/uge4/LDvT3pXvxYEUU/otYEu@rT4AEZxsgXJvQR8ayKtzUMDq5gs "PowerShell – Try It Online") Unrolled: ``` param($n,$list) $list|?{$k++-ge$n}|?{ # tail elements after $n only $sumLeftSegmentMinusSumRightSgement = &{ # calc in a new scope to reinit variables $s, $i $l|%{$s+=($_,0,-$_)[($n-le$i)+(++$i-ge$k)]} # sum(list[0..n-1]) - sum(list[k-1..list.Count-1]) $s # output sum to the outer scope } $sumLeftSegmentMinusSumRightSgement -ge 0 # output elements where sum >= 0 } ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 13 bytes ``` (‼≥≤Σ\æ╞`Σ≥▼Þ ``` [Try it online!](https://tio.run/##dU85DsJADOzzipQUXmkv53hLiAQSAgoQDQ@gzQOgTBPgFXT0PCIfWcbmqpBnpLVHOx5v5/v1ardZpjQZD7exu4zd@TFM79fx2M8egwxOt3ufks8btpY86PhNz@TQlyxgwFK0FBQeuqIi1grkUY4sGU8mtBkcIavUZmXelCqLGMkwGYjG@TZzefP1s68xGhOsShIgMEkUpr@l2@zPlt/r8bmua7CiGu9KrikKYtgJo5hHuRSUWyCXFAIGGgV2EfT8yaK7klk8AQ "MathGolf – Try It Online") ## Explanation Takes input as `n L` ``` ( pops n and decrements (TOS is n-1) ‼ apply next two operators to stack simultaneously ≥ slice L[n-1:] (gets all elements with index >= n-1) ≤ slice L[:n] (gets all elements with index <= n-1) Σ get sum of topmost list (this is the sum of n largest elements) \ swap top elements æ ▼ do while false with pop using block of length 4 ╞ discard from left of string/array ` duplicate the top two items on the stack Σ sum the list which is on top ≥ is the sum of the partial list >= the desired sum? Þ discard everything but TOS ``` The reason why this works is that in the first step, we actually divide the list into two overlapping parts. As an example, `L = [4, 3, 2, 1], n = 2` will split up the list as `[3, 2, 1]` and `[4, 3]`. The reason for having an extra element in the first list is that in the loop, the first thing that happens is a discard. If an extra element was not prepended, the cases where the output should be the entire rest of the list would fail. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` Drop@##//.{a_,b__}/;a+b>Tr@Take@##:>{b}& ``` [Try it online!](https://tio.run/##dU/LasMwELznNwy5ZFTr4Y3tlBod@gE95FaKkUtCQ0lbjG9G3@6O1KShh7IzoNUMs7vnML0dzmE6vYbl@LA8jp9fvijK8m4OPYa@j@V92AzdfvT78H6gtOvmIa6Xp/H0MT0Xqjt6X7ysSz@v5lm0hiWNXGgFhn0tCUJoVBouw1LPaCC5HCzLQENZKBdhIxhKR1avfZ1NyVJBCRR1ZSjVWf0N1j8KG@V0hLlkcbQgrSX4t65ufcuX2zaMaNuWbNDy3aT7tlsIQxOrNKJKt5PpOso1nONH3omJFWlF/z0wDV3F5Rs "Wolfram Language (Mathematica) – Try It Online") ``` Drop@## (*don't include the first n values*) //.{a_,b__}/;a+b>Tr@Take@##(*while the remaining values sum to greater than the sum of the first n*) :>{b}& (*drop the first element*) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` Ẏ∑£ȯÞK≬∑¥≤∵ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo7iiJHCo8ivw55L4oms4oiRwqXiiaTiiLUiLCIiLCJbMTAsIDUsIDUsIDNdXG4yIl0=) Fixed thanks to one of the Sʨɠɠans. ``` ∑ # Sum Ẏ # Of first n £ # Stored to register ȯÞK # Suffixes of rest ∵ # Maxmimum by... ≬--- # Next 3 as lambda... ∑ # Sum ≤ # Is less than (or equal to) ¥ # Register? ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 10 bytes (20 nibbles) ``` /|.`,,$>$>_@++<_@-~+ ``` ``` . # map over `, # range from zero up to ,$ # length of arg1 minus 1 >$ # drop that many elements from @ # arg1 >_ # with arg2 elements already dropped | # now filter only those lists whose + # sum -~ # subtracted from one + # added to + # the sum of <_ # the first arg2 elements @ # of arg1 # is truthy = greater than zero / # fold over this list of lists from right # returning the left arg each time # (so, output the first filtered list) ``` [![enter image description here](https://i.stack.imgur.com/o6rez.png)](https://i.stack.imgur.com/o6rez.png) [Answer] ## Clojure, ~~66~~ 75 bytes ``` #(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v)) ``` Sadly there doesn't seem to be a shorter idiom for the total sum of a sequence. **Edit**: Oh when adding examples to the [Try it online!](https://tio.run/##fY7BCoMwDIbvPkVgDFKWQq0bgoc9wd5AehCt4BTbVR2M4bO7qOw2loSQH74PUnbuPgW7LFjZGmo4YOecz59YBefhqOEoDDY1XrHwvnvBCZ7ie@JYtHZnhMBgyynwHkZGBI@IoggrN9gH5O@sta8B8hv0Zl7jDfJY0YU7MZD1oOcIftfGpqQpJqlJnkleSLIrY72Z6X8zUaQVMa92i4NM1GbGszHsog9NP3Y9YA383/r4snwA "Clojure – Try It Online") link I noticed that the original answer gave wrong results when many negative numbers were present. The `doseq` uses "keys" [destructuring](https://clojure.org/guides/destructuring) so it should be somewhat clear which data ends up in which symbol. `#(...)` is an anonymous function, here I'm binding it to the symbol `f`: ``` (def f #(loop[v(drop %2 %)](if(>(apply + v)(apply +(take %2 %)))(recur(rest v))v))) (doseq [{:keys [L n]} [{:L [10,5,5,3] :n 2} {:L [7,2,1,-2,-4,-5,-10,-12] :n 7} {:L [30,20,10,0,-10,-20,-30] :n 1}]] (println (f L n))) ``` Output: ``` (5 3) (-12) (20 10 0 -10 -20 -30) ``` [Answer] # APL(NARS), 32 chars, 64 bytes ``` {v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵} ``` test and comments: ``` q←{v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵} 2 q 500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,¯2,¯3 125 100 75 75 55 50 40 30 30 20 10 10 8 5 5 5 3 2 2 1 0 ¯2 ¯3 2 q 10,5,5,3 5 3 ⎕fmt 7 q 7,2,1,¯2,¯4,¯5,¯10,¯12 ┌1───┐ │ ¯12│ └~───┘ 2 q 0,¯5,¯10,¯15 ¯10 ¯15 ⎕fmt 1 q 100,35,25,15,5,5,5,5,5,5,5,5,5,5,5,5,5 ┌14───────────────────────────┐ │ 15 5 5 5 5 5 5 5 5 5 5 5 5 5│ └~────────────────────────────┘ 2 q 1000,999,998,900,800,766,525,525,400,340,120,110,80,77,33,12,0,¯15,¯45,¯250 525 525 400 340 120 110 80 77 33 12 0 ¯15 ¯45 ¯250 1 q 10,5,5 5 5 ⎕fmt 2 q ¯5,¯10,¯13 ┌0─┐ │ 0│ └~─┘ ⎕fmt 1 q 30,20,10,0,¯10,¯20,¯30 ┌6───────────────────┐ │ 20 10 0 ¯10 ¯20 ¯30│ └~───────────────────┘ {v/⍨(+/⍺↑⍵)≥+/¨{⍵↓v}¨¯1+⍳≢v←⍺↓⍵} v←⍺↓⍵ v is ⍵[(⍺+1)..≢⍵] {⍵↓v}¨¯1+⍳≢v build the array of array cut v of 0..((≢v)-1) elements +/¨ sum each of these element of array above (+/⍺↑⍵)≥ compare ≥ with the sum of ⍵[1..⍺] obtain one bolean array has the same lenght of v v/⍨ return the element of v that are 1 of the boolean array above ``` I reported wrongly the byte length... ]
[Question] [ **This question already has answers here**: [Find the smallest number that doesn't divide N](/questions/105412/find-the-smallest-number-that-doesnt-divide-n) (100 answers) Closed 6 months ago. We can define the Divisibility Streak `k` of a number `n` by finding the smallest non-negative integer `k` such that `n+k` is not divisible by `k+1`. ### Challenge In your language of choice, write a program or function that outputs or returns the Divisibility Streak of your input. ### Examples: ``` n=13: 13 is divisible by 1 14 is divisible by 2 15 is divisible by 3 16 is divisible by 4 17 is not divisible by 5 ``` The Divisibilty Streak of `13` is `4` ``` n=120: 120 is divisible by 1 121 is not divisible by 2 ``` The Divisibilty Streak of `120` is `1` ### Test Cases: ``` n DS 2 1 3 2 4 1 5 2 6 1 7 3 8 1 9 2 10 1 2521 10 ``` More test cases can be found [here](https://tio.run/##ZY8xa8MwEIXn6lc8DAUJO0FpRzVTQqYECh66dBGuGgSxBNLFKBj/dldyITT0DbrH3fdOUhdXnQ9mvkbrzmhvkUyv5u6iY8R78OegezYyZEXSZDsM3n7hpK3jYmmP7GnnXfQXs/4IlszROsMrlyf79tNVQrEFK/r2AXzQAYQtXlQub3iVUmZX1@KOjXdXVPiUeake2ssuBU6okQSewVN2G4FtQZHywsfA/0e2FPKf1wcfek28GuVULt9MVUNNEn/iE/s9p3n@AQ). ### Notes * Based on [Project Euler Problem 601](https://projecteuler.net/problem=601) * This sequence can be found on [OEIS](http://oeis.org/A055874), shifted down by 1. ### Rules * You can assume the input is greater than 1. ### Scoring [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"):The submission with the lowest score wins. [Answer] # Java 8, ~~44~~ ~~42~~ ~~41~~ 39 bytes [*Crossed out 44 is still regular 44 ;(*](https://codegolf.stackexchange.com/a/136384/52210) ``` n->{int r=0;for(;~-n%--r<1;);return~r;} ``` -2 bytes thanks to *@LeakyNun*. -1 byte thanks to *@TheLethalCoder*. -2 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##dU9LCoMwEN33FLMpGCSiQlcxvUHduCxdpDGWtDpKjEIRvbpN1G1hPsznvXnzFqOgbafwXX5WWYu@h5vQOJ0ANFplKiEV5L7cGiADH5Ew15mdO@utsFpCDggcVqTXya8YHrOqNQFbKJ4pNVnCCDPKDgYXw@aV7eBueNYOfHCMrS6hcfeDwhqNr/sDBNmPey7Pq3nKQGc8iV0Kw2MKUHx7q5qoHWzUOaitMcDIqSWb1F3s3630kibk@Glefw) ``` n->{ // Method with integer as parameter and return-type int r=0; // Result-integer (starting at 0) for(;~-n%--r<1;); // Loop as long as `n-1` is divisible by `r-1` // (after we've first decreased `r` by 1 every iteration) return~r; // Return `-r-1` as result integer } // End of method ``` [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` f n=[k|k<-[1..],rem(n+k)(k+1)>0]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6uybbRjfaUE8vVqcoNVcjTztbUyNb21DTziBWUdHgf25iZp6CrUJBUWZeiYJGmoKhgSaXAhDY2SGJGWOKGZkaGWr@BwA "Haskell – Try It Online") Using `until` is also 35 bytes ``` f n=until(\k->rem(n+k)(k+1)>0)(+1)1 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 5 bytes ``` f%tQh ``` [Try it online!](http://pyth.herokuapp.com/?code=f%25tQh&input=13&debug=0) [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ḟ§%→+⁰N ``` [Try it online!](https://tio.run/##yygtzv7//@GO@YeWqz5qm6T9qHGD3////41MjQwB "Husk – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes ``` Ý+āÖ0k ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVln5//Bc7SONh6cZZP@vVDq830rh8H4lnf9GXMZcJlymXGZc5lwWXJZchgZcRqZGhgA "05AB1E – Try It Online") **Alternate 7 byte solutions:** `<DLÖγнg` `Ls<ÑKн<` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~16~~ ~~14~~ 13 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` ⊃∘⍸⍳(×+∘×|+)⊢ ``` -1b thanks to Adám [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91NT/qmPGod8ej3s0ah6drAzmHp9doaz7qWvQ/DajiUW8fRHFX86H1xo/aJgJ5wUHOQDLEwzP4/6PeuQp5CmDgEsyVpmAEZoJEgcAQKGCMLGAEFDBBV2GKrsIMXYU5soAxUMACXYUluhmGBmgqjEyNDBECBgA "APL (Dyalog Unicode) – Try It Online") Previous solution made tacit (i.e. using trains) --- ``` {⊃⍸×(1+⍳⍵)|⍵+⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sfdTU/6t1xeLqGofaj3s2Perdq1gAJKLv2fxpQ1aPePoiGruZD640ftU0E8oKDnIFkiIdn8P9HvXMV8hTAwCWYK03BCMwEiQKBIVDAGFnACChggq7CFF2FGboKc2QBY6CABboKS3QzDA3QVBiZGhkiBAwA "APL (Dyalog Unicode) – Try It Online") Only my second APL answer so I'm sure it can be golfed further! Justification for only searching up to 2n is due to [Bertrand's Postulate](https://en.m.wikipedia.org/wiki/Bertrand%27s_postulate) which states that for any n>3, there exists a prime number between n and 2^n-2. Since by definition a prime only has factors of itself and 1, it will always terminate the divisibility streak. ## Explanation ``` {⊃⍸×(1+⍳⍵)|⍵+⍳⍵} ⍝ { } ⍝ dfn, in this case taking a single argument (e.g. 13) mapped to ⍵ ⍳⍵ ⍝ computes array of digits 0,1,2,3,4...,12 ⍵+ ⍝ adds the original argument to each element of this array - 13,14,15,16...25 (1+⍳⍵) ⍝ computes a new array from 1...13 | ⍝ applies modulo to elements at the same index across the two arrays, e.g. 13%1,14%2,15%3,16%4,17%5...26%14 = 0 0 0 0 2...12 × ⍝ converts any number >1 to 1, e.g. 0 0 0 0 1...1 ⍸ ⍝ find the index of all 'true's. e.g. 4 6 7 8 9 10 12 13 ⊃ ⍝ take the first, e.g. 4 ``` [Answer] # JavaScript (ES6), 28 bytes ``` n=>g=(x=2)=>++n%x?--x:g(++x) ``` --- ## Test it ``` o.innerText=(f= n=>g=(x=2)=>++n%x?--x:g(++x) )(i.value=2521)();oninput=_=>o.innerText=f(+i.value)() ``` ``` <input id=i><pre id=o> ``` [Answer] # Mathematica, ~~30~~ 27 bytes ``` 0//.i_/;(i+1)∣(#+i):>i+1& ``` An unnamed function that takes an integer argument. [Try it on Wolfram Sandbox](http://sandbox.open.wolframcloud.com) Usage: ``` 0//.i_/;(i+1)∣(#+i):>i+1&[2521] ``` > > `10` > > > [Answer] # [Perl 5](https://www.perl.org/), ~~23~~ 21 + 1 (-p) = 22 bytes ``` 1until$_++%++$\}{$\-- ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wNK8kM0clXltbVVtbJaa2WiVGVxcobPwvv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda n,x=1:n%x<1and-~f(n+1,x+1) ``` [Try it online!](https://tio.run/##HcuxCsIwFAXQPV9xF6GlV@iLVm0xXyIOkRoM6GtpM8TFX4/i2c/8To9JbSnBPf3rNnoos5NBN/ksXsftJ1TaCHMjdUn3Na1wuFhiR@yJjjgQR@JE9IS0hO2sXI0J04KIqPinweBnXqImhCrW5Qs "Python 2 – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 15 bytes ``` #1_(~!/)(1+)\1, ``` [Try it online!](https://tio.run/##y9bNz/7/X9kwXqNOUV9Tw1BbM8ZQx9D4/38A "K (oK) – Try It Online") **Explanation:** ``` (~!/)(1+)\1, / the solution 1, / prepend 1 to input (1+)\ / iterate, increasing by 1 (~!/) / until the modulo (!) is not (~) zero ``` * -8 bytes thanks to @Traws! [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 17 bytes ``` )uUqI1%?;)qUO(;/@ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/1@zNLTQ01DV3lqzMNRfw1rf4f9/I1MjQwA "Cubix – Try It Online") Cubified ``` ) u U q I 1 % ? ; ) q U O ( ; / @ . . . . . . . ``` * `I1` setup the stack with input and divisor * `%?` do mod and test + `;)qU)uqU` if 0 remove result and increment input and divisor. Bit of a round about path to get back to `%` + `/;(O@` if not 0, drop result, decrement divisor, output and exit [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICkgdQogICAgVSBxCkkgMSAlID8gOyApIHEgVQpPICggOyAvIEAgLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MjUyMQo=&speed=20) [Answer] # [Python 2](https://docs.python.org/2/), ~~43~~ 41 bytes *Saved 2 bytes thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)!* ``` i=input();k=1 while~-i%-~k<1:k+=1 print k ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERD0zrb1pCrPCMzJ7VON1NVty7bxtAqWxsoVlCUmVeikP3/v6ExAA "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 40 bytes ``` f=lambda i,k=1:~-i%-~k<1and f(i,k+1)or k ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVMn29bQqk43U1W3LtvGMDEvRSFNAyiobaiZX6SQ/b@gKDOvRCNNw9BYU/M/AA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~44~~ 40 bytes *-4 bytes thanks to Leaky Nun.* ``` f=lambda n,x=1:~-n%-~x and x or f(n,x+1) ``` [Try it online!](https://tio.run/##HYxNCsIwGAX3OcXbFCy@gon2x0JOIi4iNRjQr6XNIm569Ric7TCzfONrFpOzt2/3eUwOwmT1uDdSNXuCkwkJ8wp/KOKo6xyfW9xgcTPEmbgQLdERPTEQV0KfCNMafVfKlzAgCP7RqFBY1iCx7EKdfw "Python 2 – Try It Online") [Answer] # [Swift 4](https://www.swift.org), 56 bytes This is a full function `f`, with an integer parameter `i` that prints the output. ``` func f(i:Int){var k=0;while(i-1)%(k+1)<1{k+=1};print(k)} ``` **[Try it here.](http://swift.sandbox.bluemix.net/#/repl/5991c724cb3d25200b15340f)** # [Swift 4](https://www.swift.org), 56 bytes This is an anonymous function, that returns the result. ``` {var k=0;while($0-1)%(k+1)<1{k+=1};return k}as(Int)->Int ``` **[Try it here.](http://swift.sandbox.bluemix.net/#/repl/5991c72ecb3d25200b153410)** **[Check out the Test Suite!](http://swift.sandbox.bluemix.net/#/repl/5991c652cb3d25200b15340e)** [Answer] # [C# (Mono)](http://www.mono-project.com/), ~~41~~ 39 bytes ``` n=>{int r=0;while(~-n%--r<1);return~r;} ``` Essentially a port of [@Kevin Cruijssen's Java 8 answer](https://codegolf.stackexchange.com/a/139000/38550) with further golfing. [Try it online!](https://tio.run/##bYwxC8IwFIT3/Iq3CAkaaQtOaboITgqCg3OJqT5oXyBJFSntX4/p7nLH3XecCXJw5NIYkJ5w@4ZoB8WY6dsQ4MomFmIb0cDb4QMuLRIXuTyNZGqkuIMsDXSgE@lmygG8LtTnhb3li6SNlL4uhfI2jp4Wr@aUzzvnga9bBA2VylZrKAsF2y2u70dHwfV2f/cY7RnJ8o6jEIrNf1F1qMqVZjynHw) [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 28 bytes ``` 1si[1+dli1+dsi%0=M]dsMxli1-p ``` [Try it online!](https://tio.run/##S0n@b2RqZPjfsDgz2lA7JScTSBRnqhrY@samFPtWAPm6Bf//AwA "dc – Try It Online") This feels *really* suboptimal, with the incrementing and the final decrement, but I can't really see a way to improve on it. Basically we just increment a counter `i` and our starting value as long as value mod `i` continues to be zero, and once that's not true we subtract one from `i` and print. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 8 bytes ``` @1Ė₌)†↺( ``` [Try it online!](https://tio.run/##S0/MTPz/38HwyLRHTT2ajxoWPGrbpfH/v6ExAA "Gaia – Try It Online") ### Explanation ``` @ Push input (call it n). 1 Push 1 (call it i). ↺ While... Ė₌ n is divisible by i: )† Increment both n and i. ( Decrement the value of i that failed this test and print. ``` [Answer] # J, 17 bytes ``` [:{.@I.>:@i.|i.+] ``` [Try it online!](https://tio.run/##y/r/P81WL9qqWs/BU8/OyiFTryZTTzuWiys1OSNfIU3ByNTI8P9/AA) I think there's still room for golfing here. ### Explanation (ungolfed) ``` [: {.@I. >:@i. | i. + ] i. + ] Range [n,2n) i. Range [0,n) + Added to each ] n >:@i. | i. + ] Divisibility test >:@i. Range [1,n+1) | Modulo (in J, the arguments are reversed) i. + ] Range [n,2n) {.@I. Get the index of the first non-divisible I. Indices of non-zero values {. Head ``` The cap (`[:`) is there to make sure that J doesn't treat the last verb (`{.@I.`) as part of a hook. The only sort of weird thing about this answer is that `I.` actually duplicates the index of each non-zero number as many times as that number's value. e.g. ``` I. 0 1 0 2 3 1 3 3 4 4 4 ``` But it doesn't matter since we want the first index anyways (and since `i.` gives an ascending range, we know the first index will be the smallest value). Finally, here's a very short proof that it is valid to check division only up to `n`. We start checking divisibility with `1 | n`, so assuming the streak goes that far, once we get to checking divisibility by `n` we have `n | 2n - 1` which will never be true (`2n - 1 ≡ n - 1 (mod n)`). Therefore, the streak will end there. [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` õ b!%UÉ ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=9SBiISVVyQ==&input=MTM=) [Answer] # Ruby, ~~34~~ ~~32~~ 31 bytes ``` f=->n,d=1{n%d<1?1+f[n+1,d+1]:0} ``` A recursive lambda. Still new to Ruby, so suggestions are welcome! [Try it online!](https://tio.run/##KypNqvz/P1vBViE9taRYryQ/PpOLK81W1y5PJ8XWsDpPNcXG0N5QOy06T9tQJ0XbMNbKoJaLq6C0pFghLTo79v9/Q2MA) [Answer] # x86 Machine Code, 16 bytes ``` 49 dec ecx ; decrement argument 31 FF xor edi, edi ; zero counter Loop: 47 inc edi ; increment counter 89 C8 mov eax, ecx ; copy argument to EAX for division 99 cdq ; use 1-byte CDQ with unsigned to zero EDX F7 FF idiv edi ; EDX:EAX / counter 85 D2 test edx, edx ; test remainder 74 F6 jz Loop ; keep looping if remainder == 0 4F dec edi ; decrement counter 97 xchg eax, edi ; move counter into EAX for return C3 ret ; (use 1-byte XCHG instead of 2-byte MOV) ``` The above function takes a single parameter, `n`, in the `ECX` register. It computes its divisibility streak, `k`, and returns that via the `EAX` register. It conforms to the 32-bit [fastcall calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall), so it is easily callable from C code using either Microsoft or Gnu compilers. The logic is pretty simple: it just does an iterative test starting from 1. It's functionally identical to most of the other answers here, but hand-optimized for size. Lots of nice 1-byte instructions there, including `INC`, `DEC`, `CDQ`, and `XCHG`. The hard-coded operands for division hurt us a bit, but not terribly so. [Try it online!](https://tio.run/##dY5NboMwEEbX@BQjqkp2EqoC@SEizYaKS9QVcg0mloipjKksVbl66ZA0yy5Gb8bf03hk1Eo5TbI3gwN5EhZ8ti36unl7hxcIuU9j7suS@/Uea8d9hiwy7vfIcnfLsg33rwn3uzXOW/TwbY9ZkYY5GZxwWsJoBt2apoaqEs5Z/TG6pqooVWJwUnQdY0AXitG7x/D7v1Py6UEb2Y11A4fB1bp/Oh2JNg7OQhs6N8K2cnU7f7HA4YuRbxKo3sI11rgryREHiOMclkvNSIBC8GkxVjR8rLmLjtwhTbgCvQJFNWM5CS7kPynZJPHszbyqJLCNG62B55xcph@pOtEOU3ROk18 "C (gcc) – Try It Online") [Answer] # [PHP](https://php.net/), 34 bytes ``` for(;$argv[1]++%++$r<1;);echo$r-1; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVEovSy6INY7W1VbW1VYpsDK01rVOTM/JVinQNrf/b2/3/b2gMAA "PHP – Try It Online") Simple enough. Checks the remainder of division (mod) each loop while incrementing each value, outputs when the number isn't divisible anymore. [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 19 bytes ``` #v_1+::&+1-\% 1<@.- ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X7ks3lDbykpN21A3RpXL0MZBT/f/fyNTI0MA "Befunge – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ḷ+%RTḢ’ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm3aqkEhD3csetQw8////0amRoYA "Jelly – Try It Online") Explanation: ``` Ḷ+%RTḢ’ main link, argument: n Ḷ+ [n, 2n-1] R [1, n] % modulo TḢ index of first truthy value (first value where k+1 does not divide n+k), 1-indexed ’ decrement ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 17 bytes ``` ®n0&{©n⑻+⑹⑻%0=|}⑺ ``` [Try it online!](https://tio.run/##y05N////0Lo8A7XqQyvzHk3crf1o4k4gpWpgW1P7aOKu//8Njf/rFgUBAA "Keg – Try It Online") [Answer] # [K4](https://kx.com/download/), ~~27~~ 25 bytes **Solution:** ``` *(1+)/[{y=x*_y%x}. 1+;]1, ``` **Explanation:** Pretty naive. Start with list of [1, x] and increment both until no longer divisible. ``` *(1+)/[{y=x*_y%x}. 1+;]1, / the solution 1, / prepend input with 1 ( )\[ ;] / (loop)\[condition;start] { }. / lambda taking implicit x & y 1+ / add 1 (vectorised) [1, 13] => [2, 14] y%x / divide y by x _ / floor y* / multiply by x y= / equals y? 1+ / add 1 (vectorised) [1, 13] => [2, 14] * / take first [2, 14] => 2 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-æ`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ ~~8~~ ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` N°u°U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LeY&code=TrB1sFU&input=MjUyMQ) ## Original (w/o flag), 7 bytes ``` @°uXÄ}a ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLB1WMR9YQ&input=MjUyMQ) --- ## Explanation Implicit input of integer `U`. ``` @ }a ``` Return the first integer that returns a truthy value (a number `>0`) when passed through a function (with `X` being the current integer) ... ``` ° ``` That postfix increments `U` ... ``` uXÄ ``` And modulos it (`u`) by `X+1`. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 30 bytes ``` for(;!($args[0]++%++$i)){}$i-1 ``` [Try it online!](https://tio.run/##VY3bCoJAEIbv9yk22MLFFVztSASCD1BkdxFRNnbAsHZXCsxnN63Uba6G7//nm1vyACFPEMdWmAgoSDTLiigRxrRjkJ04yrW9Mc2uaZIzpVlOzhYvcoQ8A@FymGc4jNN6d5nT7H2NDzQ@1PiIuc0@1vhE63NbC5yBwxm3KaL4hbs4@3CiQCp/J4FhAs8bhAoOeIbJ9psKkGmsStAjUdtFn3C9CPxUquQ631/Ku433NVYTpGEIUlaiRmrBvfZNm@LqZ6yatb1Nl/X3v7sc5ah4Aw "PowerShell Core – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ?+n›%)Ṅ ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiPytu4oC6JSnhuYQiLCIiLCIyXG4zXG40XG41XG42XG43XG44XG45XG4xMFxuMjUyMSJd) Explanation: ``` ) # Lambda f from beginning of program Ṅ # First non-negative integer n such that f(n) is truthy ? # Push the input + # Add n to it % # Modulo n› # N incremented ``` ]
[Question] [ A "Giza number", also colloquially known as a [Timmy Number](http://chat.stackexchange.com/transcript/message/33544457#33544457) is any number where the digits represent a pyramid ([A134810](http://oeis.org/A134810)). For example, "12321" is a giza number because it can be visualized like this: ``` 3 2 2 1 1 ``` However, something like "123321" is not a Giza number because there are two digits at the top of the pyramid ``` 33 2 2 1 1 ``` In other words, a number is a Giza number if all of the following conditions are met: * It has an odd number of digits, and the center digit is the largest * It's palindromic (the same read forwards or backwards), and * The first half of the digits are strictly increasing by one. (Since it must be palindromic, this means the second half of the digits must be strictly decreasing by one) You must write a full program or a function that takes a positive integer as input, and determine if it is a Giza number or not. You may take the input as a string or as a number. If it *is* a Giza number, output a [truthy value](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey). Otherwise, a falsy value. There are a total of 45 Giza numbers, so any one of these inputs should result in a truthy value: ``` 1 2 3 4 5 6 7 8 9 121 232 343 454 565 676 787 898 12321 23432 34543 45654 56765 67876 78987 1234321 2345432 3456543 4567654 5678765 6789876 123454321 234565432 345676543 456787654 567898765 12345654321 23456765432 34567876543 45678987654 1234567654321 2345678765432 3456789876543 123456787654321 234567898765432 12345678987654321 ``` Any other input should give a falsy value. Of course, you do not have to handle invalid inputs, such as non-positive numbers, non-integers, or non-numbers. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes are banned, and the shortest answer in bytes wins! [Answer] # Python 2, ~~48~~ ~~47~~ 46 bytes ``` lambda s:s[~len(s)/2:]in'987654321'>s==s[::-1] ``` Test it on [Ideone](http://ideone.com/xoRXh9). ### How it works In Python, a chained comparison returns *True* if and only if all individual comparison do the same. In this specific case, our lambda returns *True* if and only if all of the following conditions are met. * `s[~len(s)/2:]in'987654321'` For a string **s** of length **2n + 1**, `~len(s)/2` returns **~(2n + 1) / 2 = -(2n + 2) / 2 = -(n + 1)**, so `s[~len(s)/2:]` yields the rightmost **n + 1** characters of **s**. Similarly, for a string **s** of length **2n**, `~len(s)/2` returns **~(2n) / 2 = -(2n + 1) / 2 = -(n + 1)** (integer division always round towards **-∞**, so `s[~len(s)/2:]` once more yields the rightmost **n + 1** characters of **s** The comparison returns *True* if and only if the rightmost **n + 1** characters form a substring of `987654321`. Note that if they do and **s** has **2n** characters, **s** cannot be a palindrome; the **n**th and **(n+1)**th characters from the right will be distinct, and the latter is the **n**th character from the left. * `'987654321'>s` This compares the strings lexicographically. Since **9** is the only Giza number that starts with **9**, all Giza numbers satisfy this comparison. Note that comparing these strings does not form part of our decision problem; `>s` is simply three characters shorter than `and s`. * `s==s[::-1]` This returns *True* if and only if **s** is a palindrome. [Answer] # Perl, ~~39~~ ~~37~~ ~~42~~ 39 + 1 = 40 bytes Using a new method, I managed to cut down a huge number of bytes. Run with the `-n` flag. Accepts input repeatedly at runtime, printing 0 or 1 accordingly. I had to add 5 bytes because I realized without it, the code worked for inputs such as 1234567900987654321, which is not a Giza number. Since Giza numbers never contain the digit 0 (and all false positives by necessity would contain the digit 0), these 5 bytes account for that. ``` say!/0/*($_- s/..?/1/gr**2)=~/^(.)\1*$/ ``` Explanation: ``` say!/0/*($_- s/..?/1/gr**2)=~/^(.)\1*$/ #$_ contains input by default. !/0/ #Ensure that the initial text doesn't contain the number 0 * #Since both halves of this line return either 0 or 1, multiplying them together only yields 1 if both are true (which we want). s/ / /gr #Perform a substitution regex on $_ (see below) #/g means keep replacing, /r means don't modify original string; return the result instead ..? #Replace 1 or 2 characters (2, if possible)... 1 #...with the number 1 **2 #Square this number... ($_- ) #...and subtract it from the input =~ #Do a regex match on the result /^ $/ #Make sure the regex matches the WHOLE string (.) #Match any character... \1* #...followed by itself 0 or more times say #Finally, output the result of the whole line of code. ``` The purpose of the substitution regex is to construct a string of 1s whose length is half the length of the input, rounded up. Thus, an input of `12321` will produce the string `111`, which then gets squared (explanation below). Even-length inputs will produce strings that are too small to ensure the final regex is successful. The reason this code works is because of the following: ``` 1 = 1**2 121 = 11**2 12321 = 111**2 1234321 = 1111**2 123454321 = 11111**2 12345654321 = 111111**2 1234567654321 = 1111111**2 123456787654321 = 11111111**2 12345678987654321 = 111111111**2 ``` We can clearly see that the number of 1's in RHS is equal to 1/2 more than half the size of LHS. (1 more if we truncate). Additionally: 567898765 - 123454321 = 444444444, which is just 4 repeating. So when we subtract our square from our number, if we get a repdigit, our original number is a Giza number. # Old code and old method (58 + 1 = 59 bytes) Saved 1 byte thanks to @Dada Run with the `-n` flag, pipe text in using `echo` ``` say$_==($;=join"",/(.)/..($==y///c/2+/(.)/)-1).$=.reverse$ ``` Calculates the unique giza number determined by the length and the leading integer, and sees if it matches the input. Run as `echo -n "123454321" | perl -M5.010 -n giza.pl` Returns `1` if it's a Giza number, null otherwise. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 9ẆŒBḌċ ``` Generates all 45 Giza numbers numbers, then tests for membership. [Try it online!](http://jelly.tryitonline.net/#code=OVLhuobFkkLhuIzEiw&input=&args=MTIzNDU2Nzg5ODc2NTQzMjE) or [see the generated numbers](http://jelly.tryitonline.net/#code=OVLhuobFkkLhuIxZ&input=). ### How it works ``` 9ẆŒBḌċ Main link. Argument: n 9 Set the return value to 9. Ẇ Windows; yield all "substrings" of [1, ..., 9]. ŒB Bounce; map each [a, ..., b] to [a, ..., b, ..., a]. Ḍ Undecimal; convert the digit arrays to integers. ċ Count the number of occurrences of n. ``` [Answer] # JavaScript (ES6), ~~46~~ ~~45~~ ~~42~~ 41 bytes ``` f=([c,...s])=>s+s&&c-s.pop()|c-~-f(s)?0:c ``` Takes input as a string and returns a single-digit string for truthy, `0` for falsy. The basic idea is to check for a few things: * If the string is one char long, OR * the first char is the same as the last char, and * the middle section is also a Giza number, and * the second char is one more than the first char here. [Answer] ## Java 7, ~~128 119~~ 105 bytes ``` boolean t(long n){long a=1,b=1,c=0;for(;a<n/10;b=b*b<=n/10?b*10+1:b,c^=1)a=a*10+1;return(n-b*b)%a<1&c<1;} ``` No more strings! So, now I start by generating a `111...` number of the same length as input (`a`), and one shorter to square (`b`). Then you can subtract `b*b` from the input and check divisibility by `a`. `c` is just there to check odd/even, pay it no mind >\_> Whitespaced: ``` boolean t(long n){ long a=1,b=1,c=0; for(;a<n/10;b=b*b<=n/10?b*10+1:b,c^=1) a=a*10+1; return(n-b*b)%a<1&c<1; } ``` ### Old Method, 119 bytes ``` boolean g(char[]a){int i=1,l=a.length,b=1,d;for(;i<l;b*=i++>l/2?d==-1?1:0:d==1?1:0)d=a[i]-a[i-1];return b>0?l%2>0:0>1;} ``` Walks through the array, checking for a difference of 1 (or -1, depending on which half) between each digit. Then just checks to see the length is odd. Whitespaced: ``` boolean g(char[]a){ int i=1,l=a.length,b=1,d; for(;i<l;b*=i++>l/2?d==-1?1:0:d==1?1:0) d=a[i]-a[i-1]; return b>0?l%2>0:0>1; } ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes Truthy is **1**, falsy is **0**. ``` 9LŒ€ûJ¹å ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=OUzFkuKCrMO7SsK5w6U&input=MTIzMjE) [Answer] # Python 2, ~~77, 76, 64~~, 63 bytes ``` f=lambda s:2>len(s)or(s[0]==s[-1]==`int(s[1])-1`and f(s[1:-1])) ``` A simple recursive solution. Checks to see if the first and last digits equal each other and the second digit minus one. Then checks if the middle is also a Giza number. Returns true once it gets down to a single digit. *One byte saved thanks to @Rod, a **ton** of bytes saved thanks to DLosc and ETHProductions!* [Answer] ## PowerShell v3+, ~~147~~ ~~108~~ 67 bytes ``` $args[0]-in(1..9+(1..8|%{$i=$_;++$_..9|%{-join($i..$_+--$_..$i)}})) ``` Radically changed approach. Generates all possible Giza numbers, and then checks whether the input `$args[0]` is `-in` that collection. Below is how the collection of Giza numbers is formed: ``` 1..9+(1..8|%{$i=$_;++$_..9|%{-join($i..$_+--$_..$i)}}) 1..8|%{ } # Loop from 1 up to 8 $i=$_; # Set $i to the current number ++$_..9|%{ } # Loop from one higher up to 9 $i..$_+--$_..$i # Build two ranges and concatenate # E.g., 2..5 + 4..2 -join( ) # Join into a single string 1..9+( ) # Array concatenate with 1 to 9 ``` Example runs: ``` PS C:\Tools\Scripts\golfing> 12321,5678765,121,4,123321,1232,5678,13631|%{"$_ --> "+(.\giza-numbers.ps1 "$_")} 12321 --> True 5678765 --> True 121 --> True 4 --> True 123321 --> False 1232 --> False 5678 --> False 13631 --> False ``` [Answer] # Python 3, 65 bytes ``` lambda x:len(x)<18and x[:len(x)//2+1]in'0123456789'and x[::-1]==x ``` I'm not entirely sure, but I think this works. [Answer] ## Python 2, ~~68~~ ~~73~~ 66 bytes ``` lambda n:n==`int('1'+len(n)/2%9*'1')**2+int(len(n)*`int(n[0])-1`)` ``` abusing the fact that `11^2=121`, `111^2=12321` and so on, I calculate this and add `1111..` enough times as offset. Examples: `23432=111^2+11111*1` `676=11^2+111*5` [Answer] ## Perl, 41 bytes 40 bytes of code + `-p` flags. ``` s/(.)(?=(.))/$1-$2/ge;$_=/^(-1(?1)1|).$/ ``` Outputs 1 if the input is a Giza number, nothing otherwise. Supply the input without final newline to run it : ``` echo -n '123456787654321' | perl -pe 's/(.)(?=(.))/$1-$2/ge;$_=/^(-1(?1)1|).$/' ``` **Explanations** : first, `s/(.)(?=(.))/$1-$2/ge` replace each digit `$1` (followed by `$2`) by `$1-$2`. If it's a Giza number, then each digits being one less than the next in the beginning, and one more in the end, then the string should contain only `-1` in the first part, and `1` in the second (except the last that is left unchanged). That's what the second part `/^(-1(?1)1|).$/` checks : looks for a `-1` followed by *recursion* followed by a `1`. *-1 byte thanks to Martin Ender.* --- My previous version 15 bytes longer (quite different so I'll let it here) : ``` echo -n '123456787654321' | perl -F -pe '$\=$_ eq reverse;$\&=$F[$_-1]+1==$F[$_]for 1..@F/2}{' ``` [Answer] # ><> FISH ~~57~~ ~~52~~ ~~49~~ 48 bytes ``` i:1+?!vi00.;n1< %?v0n;>~l:1-?!^2 {:<11 ^?:=@:$+= ``` Edit 1: = returns 0 or 1 if true so removed a check and used this value to increment, then it checks equality after anyway. (saved 6 bytes, lost 1 for new line). Edit 2: 3 directional markers removed and 11 placed into gap to offset the stack to an even length to force false ( 3 bytes saved)., Edit 3: Duplicate the length of the stack for checking MOD by 2 and len(1), this was done by putting the length on twice before but this now filled an empty space on line 2 ( 1 byte saved). [Answer] # C#, ~~120~~ ~~86~~ ~~108~~ ~~102~~ 92 bytes ``` x=I=>{var Z=I.Length;return Z<2?1>0:I[0]==I[Z-1]&I[1]-0==I[0]+1?x(I.Substring(1,Z-2)):0>1;}; ``` Full program with some test cases: ``` class a { static void Main() { Func<string, bool> x = null; x = I=> { var Z=I.Length; return Z==1? // length == 1? 1>0: // return true (middle of #) I[0]==I[Z-1]&I[1]-0==I[0]+1? // else start == end and the next number is 1 above the current? x(I.Substring(1,Z-2)): // recursive call on middle 0>1; // else false }; Console.WriteLine("1 -> " + (x("1") == true)); Console.WriteLine("9 -> " + (x("9") == true)); Console.WriteLine("121 -> " + (x("121") == true)); Console.WriteLine("12321 -> " + (x("12321") == true)); Console.WriteLine("4567654 -> " + (x("4567654") == true)); Console.WriteLine("12345678987654321 -> " + (x("12345678987654321") == true)); Console.WriteLine("12 -> " + (x("12") == false)); Console.WriteLine("1221 -> " + (x("1221") == false)); Console.WriteLine("16436346 -> " + (x("16436346") == false)); Console.WriteLine("123321 -> " + (x("123321") == false)); Console.WriteLine("3454321 -> " + (x("3454321") == false)); Console.WriteLine("13631 -> " + (x("13631") == false)); Console.WriteLine("191 -> " + (x("13631") == false)); Console.Read(); // For Visual Studio } } ``` Hooray for single line conditionals, now beating the Java answer :)! Also got to write my first explaining comments, though it's probably self explanatory. Thanks to @Dada for finding a problem with my algorithm (was true for numbers that were mirrored like 13631). Now sub 100 since apparently checking for length%2 is redundant. [Answer] # Bash, 111 bytes *UPDATE* Note that input number normalization can probably be skipped completely, if you just add the first digit back to your generated *GIZA* number, like that: ``` 01210 + 6 => 67876 ``` and then just compare it with the input directly. **Disclaimer:** this one is not really optimized, so it is more a proof of concept than a real contender **Golfed** ``` G() { I=`sed "s/./\0-${1::1}\n/g"<<<$1|bc`;Z=`seq 0 $((${#1}/2))`;A=`rev <<<$Z`;cmp -s <(echo $I) <<<$Z${A:1} ``` **Algorithm** Any *GIZA* number can be normalized to its canonical form, by substracting its first digit from the rest: ``` 67876 - 6 => 01210 78987 - 7 => 01210 ``` and there is only one canonical *GIZA* number of a particular length. Knowing this we can easily generate a canonical *GIZA* number based on the input number length: ``` Z=`seq 0 $((${#1}/2))`;A=`rev <<<$Z` => $Z${A:1} ``` then normalize the input number: ``` I=`sed "s/./\0-${1::1}\n/g"<<<$1|bc` ``` and compare ``` cmp -s <(echo $I) <<<$Z${A:1}; ``` **Test** ``` for i in `seq 0 1000`; do G $i && echo $i; done 0 1 2 3 4 5 6 7 8 9 121 232 343 454 565 676 787 898 ... G 12345678987654321 && echo "OK" || echo FALSE OK G 123456789987654321 && echo "OK" || echo FALSE FALSE ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 22 bytes ``` 9uR;∙`xR;RdX+εj`M;░#íu ``` [Try it online!](http://actually.tryitonline.net/#code=OXVSO-KImWB4UjtSZFgrzrVqYE074paRI8OtdQ&input=IjEyMzIxIg) Takes input as a quoted string (e.g. `"12321"`). Output is a positive integer for true, and `0` for false. Explanation: ``` 9uR;∙`xR;RdX+εj`M;░#íu 9uR;∙ cartesian product of [1,2,3,4,5,6,7,8,9,10] with itself `xR;RdX+εj`M for each pair: x construct the half-open (end-exclusive) range ([1, 5] -> [1, 2, 3, 4]) R reverse ;RdX+ duplicate, reverse, remove first element, prepend ([1, 2, 3, 4] -> [1, 2, 3, 4, 3, 2, 1]) εj concatenate into a string ;░ filter out empty strings #íu test for membership ``` [Answer] ## Haskell, 62 bytes ``` (`elem`[[j..pred i]++[i,pred i..j]|i<-['1'..'9'],j<-['1'..i]]) ``` The input is taken as a string. Creates a list of all Giza numbers an checks if the number is in it. The list is created by looping `i` through `'1'..'9'` and then `j` through `'1'..i` and creating the elements `j .. i-1 , i , i-1 .. j`. [Answer] # [><>](http://esolangs.org/wiki/Fish), 62 bytes ``` i:0( ?v v!1&!~{!<:=$:@&-1=+2=*>l!-3!1(!:? >l!;2!n=!0?!<-1=n; ``` [Try it online!](http://fish.tryitonline.net/#code=aTowKCAgID92CnYhMSYhfnshPDo9JDpAJi0xPSsyPSo-bCEtMyExKCE6Pwo-bCE7MiFuPSEwPyE8LTE9bjs&input=MTIzNDU2Nzg5ODc2NTQzMjE) Outputs 1 for a Giza number; 0 otherwise. Works by pushing the input into a dequeue (ok, technically a reversible stack) and repeatedly testing both ends for equality, as well as making sure they are exactly one larger than the previous value. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~20~~ 19 bytes ``` l_$_W=),\ci>_W<W%+= ``` [Test suite.](http://cjam.tryitonline.net/#code=cU4vezpMOwoKTF8kX1c9KSxcY2k-X1c8VyUrPQoKXW59Lw&input=MQoyCjMKNAo1CjYKNwo4CjkKMTIxCjIzMgozNDMKNDU0CjU2NQo2NzYKNzg3Cjg5OAoxMjMyMQoyMzQzMgozNDU0Mwo0NTY1NAo1Njc2NQo2Nzg3Ngo3ODk4Nwo3ODk5ODcKMTMxCjEyMzIzMjEKMTIzNAo0MzIxCjEyMzQzMgoyMzQzMjE) ### Explanation The basic idea is to find the minimum and maximum digit, then create a Giza number from those and then check that it's equivalent to the input. ``` l e# Read input. _$ e# Get a sorted copy of the input. _W= e# Get its last character, i.e. the maximum digit M. ), e# Get a string with all characters from the null byte up to M. \c e# Get the first character of the sorted string, i.e. the minimum e# character m. i> e# Convert to its character code and discard that many leading e# characters from the string we generated before. Now we've got e# a string with all digits from m to M, inclusive. _W<W%+ e# Palindromise it, by appending a reversed copy without M. = e# Check that it's equal to the input. ``` Instead of the minimum character, we can also use the first character, for the same byte count: ``` l_:e>),1$ci>_W<W%+= ``` [Answer] # Mathematica, ~~62~~ ~~61~~ 60 bytes *Saved 2 bytes due to [@MartinEnder](http://ppcg.lol/users/8478).* ``` MatchQ[{a:1...,b___}/;{b}==-{a}]@*Differences@*IntegerDigits ``` Composition of functions. Takes a number as input and returns `True` or `False` as output. [Answer] # Retina, ~~55~~ ~~54~~ 36 bytes Byte count assumes ISO 8859-1 encoding. ``` . $*1: +`^(1+:)(1\1.*)\b\1$ $2 ^1+:$ ``` [**Try it online**](http://retina.tryitonline.net/#code=LgokKjE6CitgXigxKzopKDFcMS4qKVxiXDEkCiQyCl4xKzok&input=MTIzNDU2Nzg5ODc2NTQzMjE) Convert each digit to unary, separated by colons. Loop, removing matching outer digits if the next digit is one more. Match a single remaining digit. [Answer] # PHP, 71 bytes ``` for($t=$i=max(str_split($s=$argv[1]));$t!=$s&&--$i;)$t="$i$t$i";echo$i; ``` fetches the largest digit from input and counts down, adding the new digit to a comparison string until input and comparison string are equal - or `$i` is `0`. prints the lowest digit for a Timmy Number, `0` else. [Answer] # [Pushy](https://github.com/FTcode/Pushy), ~~30~~ 15 bytes I woke up this morning and realise I could half the length of my answer... ``` s&K-kL2/OvhXwx# ``` (non-competing as the language postdates challenge) Input is given on the command line: `$ pushy gizas.pshy 3456543`. Outputs `1` for truthy and `0` for falsy. Here's the breakdown: ``` s % Split the number into its individual digits &K- % Subtract all digits by the last kL2/ h % Get the halved length of the stack (+1) Ov X % In stack 2, generate range (0, halved length) w % Mirror the range x# % Check stack equality and output ``` The algorithm was inspired by the bash answer: first, normalize the number, (`45654 -> 01210`), then generate the normalized giza number of the same length (there is only one), and compare. --- **Old Solution** ``` s&K-Y?kL2%?L2/:.;&OvhXx#i;;;0# ``` [Answer] ## Racket 292 bytes ``` (let*((s(number->string n))(sn string->number)(st string)(lr list-ref)(sl(string->list s))(g(λ(i)(-(sn(st(lr sl(add1 i)))) (sn(st(lr sl i)))))))(cond[(even?(string-length s))#f][(not(equal? s(list->string(reverse sl))))#f][(andmap identity (for/list((i(floor(/(length sl)2))))(= 1(g i))))])) ``` Ungolfed: ``` (define(f n) (let* ((s (number->string n)) (sn string->number) (st string) (lr list-ref) (sl (string->list s)) (g (λ (i) (- (sn(st(lr sl (add1 i)))) (sn(st(lr sl i))))))) (cond [(even? (string-length s)) #f] [(not(equal? s (list->string (reverse sl)))) #f] [else (andmap identity (for/list ((i (floor(/(length sl)2)))) (= 1 (g i))))] ))) ``` Testing: ``` (f 12321) (f 123321) ; only this should be false; (f 9) (f 787) (f 67876) (f 4567654) (f 123454321) (f 12345654321) (f 1234567654321) (f 123456787654321) (f 12345678987654321) ``` Output: ``` #t #f #t #t #t #t #t #t #t #t #t ``` [Answer] # Java 8, 162 + 19 bytes 19 for `import java.util.*;` ``` s->{List f=new ArrayList();for(int i=0;i<9;){String l=String.valueOf(++i);for(int j=i;j>0;){f.add(l);String k=String.valueOf(--j);l=k+l+k;}}return f.contains(s);} ``` Different approach to the other Java answer, I wanted to try and use the method of creating all the possible Timmy numbers and checking to see if our string was contained in them. [Answer] # Octave, 56 bytes ``` @(n)nnz(n)<2||~(abs(diff(+n))-1)&&diff(+n(1:1+end/2))==1 ``` Check out all test cases [here](http://ideone.com/lPcrk1). This would be two less bytes in MATLAB, since `diff(n)` works for strings. In Octave, you need `diff(+n)`. **Explanation:** ``` @(n) % Anonymous function taking a string `n` as argument nnz(n)<2 % True if there is only one element in n || % Short circuit or operator. Expression will be true if this is true ~(abs(diff(+n))-1) % Takes the absolute value of the difference between adjacent numbers % which should always be 1. Subtracts 1, to get 0 % and negates it to get 1 (true) diff(+n(1:1+end/2))==1 % Checks if the difference between the first half of the numbers % is 1. % If either the first, or both the second and third argument is true % then the function will return 1, otherwise 0. ``` [Answer] # Mathematica, 56 bytes This is a little shorter: ``` MatchQ[Differences@IntegerDigits@#,{a:1...,b__}/;b==-a]& ``` [Answer] # Java 7, ~~129 119~~ 109 bytes ``` boolean e(char[]a){int l=a[0]-1,f=0,b=a.length-1;for(;f<b&&a[f]==++l&a[f++]==a[b--];);return f==b&l==a[b]-1;} ``` ### Old Recursive Method, 119 ``` boolean b(char[]a){int b=a.length;return b>1&&a[0]==a[b-1]&a[0]+1==a[1]?b(java.util.Arrays.copyOfRange(a,1,b-1)):b==1;} ``` -10 bytes thanks to Geobits. We ~~are~~ were tied... [Try it online!](https://tio.run/##ndFPb4IwGAbwu5@i8WAgCLEq0Ib1sOy8k0fCodWiuFoMVBdj/OyOsWXZlmXJw4k/eaDv@3v28izD@qjtfvNyXxvZtuRZVpZc76qujZaWaG@9k01eSP9aWUeMkPmsCOm0FLOpEjIy2m7dLqRZWTdeVj6oyUTmZSFEEJj3uyDo7mWuwrDI/KzR7tRYUgqhJqZ/3/0ru92PJ2WqNWmddN3lXFcbcujm8Fauqey2P31EPkZTRBCrX/sHz89Gq0vr9CGqTy46dmFnrKci7Y3pOHL1Uzf7Y9PIi@f7/2TnQHYBZJdANgayCZBNgSwDshzI0jnUxgLqYwk1EkOdJFArKdQLg5rhDPJegOJL0DwG1RPQPQXlGWjPIX3aA4GiMWyawKop7MpgWY7Z0s/VUa1kgFc6QIwNMOOgGv1aCFZIBzmwQRIctaDfRsQ3YwN34/B29MeBAybl@Kz016d/nXob3e5v "Java (OpenJDK 8) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43~~ 34 bytes *Thanks to Jo King for -9 bytes.* ``` {!/0/==set comb $_- S:g/..?/1/²:} ``` Port of [Gabriel Benamy's Perl solution](https://codegolf.stackexchange.com/a/100075/14109). [Try it online!](https://tio.run/##DcxBDoIwFEXRsaziSYgzKe3vbwGtLMIFEDXUiQQDTgjpplyCG6sd3jO472F@mTiuB@/itheVcG4ZPnhM4x1Ff8S1fYqy7IQUv28bop9mnBtIJUGawMbW1jAUN@AaNhExQZHWpMAVX7Blu@W2Ii96uFSdT9uQn7IQ/w "Perl 6 – Try It Online") [Answer] # Cjam, 35 bytes Probably very suboptimal... I'm a little out of practice! ``` q__W%=\_,_2%@@2/)<2ew{:-}%e`,1=]:e& ``` [Try it online!](http://cjam.aditsu.net/#code=q__W%25%3D%5C_%2C_2%25%40%402%2F)%3C2ew%7B%3A-%7D%25e%60%2C1%3D%5D%3Ae%26&input=45654) [Answer] # Python 2, ~~50~~ ~~82~~ ~~81~~ 80 bytes ``` def f(a):b=len(a)/2+1;print(1,0)[a[:b-1]!=a[b:][::-1]or a[:b]not in'123456789'] ``` Simple approach. Just splits the string in half (missing out the middle character or one after the middle character if it is of even length), reverses the second half then compares the two and compares the first half with a string of 1 to 9. **Edit** Reposted after constructive feedback from fellow golfers and realising and correcting my mistakes. -1 for losing a (waste of) space -1 for reading the question again and realising that we don't need to take 0 into account. Really must stop golfing after a long day at work. ]
[Question] [ Given an integer, make an expression that produces it from `0` using unary negation `-` and bitwise complement `~` (`~n` = `-n-1`), with the operators applied right to left. ``` ... -3 = ~-~-~0 -2 = ~-~0 -1 = ~0 0 = 0 1 = -~0 2 = -~-~0 3 = -~-~-~0 ... ``` Your expression must be as short as possible, which means no redundant parts of `~~`, `--`, `-0`, or `00`. Output or print the expression as a string or a sequence of characters. ``` var QUESTION_ID=92598,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/92598/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Python, 32 bytes ``` lambda x:("-~"*abs(x))[x<0:]+"0" ``` Anonymous lambda function. Given an integer x writes "-~" abs(x) times and removes the first char if x is negative, then a zero is added to the end. [Answer] # JavaScript (ES6), ~~33~~ 31 bytes ``` f=x=>x<0?"~"+f(~x):x&&"-"+f(-x) ``` Recursion < built-ins < loops (at least in this case). Basically unevaluates the input: * if it's less than 0, flip it and add a `~` to the string; * if it's more than 0, negate it and add a `-` to the string; * if it's exactly 0, return 0. Takes advantage of this pattern: ``` 0 = 0 -1 = ~( 0) = ~0 +1 = -(-1) = -~0 -2 = ~(+1) = ~-~0 +2 = -(-2) = -~-~0 -3 = ~(+2) = ~-~-~0 +3 = -(-3) = -~-~-~0 etc. ``` [Answer] # Pyth, ~~14~~ ~~13~~ 12 Bytes ``` _<>0Q+0sm"~- ``` *-2 Bytes thanks to @StevenH.* **[test suite](https://pyth.herokuapp.com/?code=_%3C%3E0Q%2B0sm%22%7E-&input=4&test_suite=1&test_suite_input=-4%0A-3%0A-2%0A-1%0A0%0A1%0A2%0A3%0A4&debug=0)** Decided to try out Pyth, so i translated [my python answer](https://codegolf.stackexchange.com/questions/92598/bitflip-and-negate/92606#92606) to it. Any help welcome! ### Explanation: ``` _<>0Q+0sm"~- m"~- # Map "~-" onto the input (= a list of n times "~-"). s # Join the list to a string. +0 # Add "0" in front. <>0Q # Slice off the last char if the input is negative. _ # Reverse the whole thing. ``` [Answer] # C, 46 bytes ``` m(x){putchar(x?x<0?126:45:48);x&&m(-x-(x<0));} ``` Unlike most (all?) other answers, this one outputs the operators `~` and `-` one by one. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes ``` Ä„-~×¹0‹i¦}0J ``` **Explanation** ``` „-~ # the string "-~" Ä × # repeated abs(input) times ¹0‹i¦} # if input is negative, remove the first char 0J # join with 0 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4TigJ4tfsOXwrkw4oC5acKmfTBK&input=LTM) [Answer] # Retina, ~~19~~ 17 bytes Replace the number with unary, with a zero on the end. Replace each `1` with `-~`. Remove double negative if there is one. ``` \d+ $*10 1 -~ -- ``` [**Try it online**](http://retina.tryitonline.net/#code=XGQrCiQqMTAKMQotfgotLQo&input=LTM) [**All test cases at once**](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoxMAoxCi1-Ci0tCg&input=LTMKLTIKLTEKMAoxCjIKMw) (slightly modified program to support multiple test cases) [Answer] # Perl 38 35 33 (23 + 1 for -p) 24 ``` s/\d+/"-~"x$&.0/e;s;--; ``` -13 thanks to Dada [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 18 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` '0',⍨0∘>↓'-~'⍴⍨2×| ``` `'0',⍨` character zero appended to `0∘>` negativeness (i.e. 1 for numbers under 0; 0 for zero and up) `↓` dropped from `'-~'⍴⍨` the string "~-" cyclically reshaped to length `2×` two times `|` the absolute value `+` plus `0∘<` positiveness (i.e 1 for numbers over 0) [TryAPL online!](http://tryapl.org/?a=f%u2190%270%27%2C%u23680%u2218%3E%u2193%27-%7E%27%u2374%u23682%D7%7C%20%u22C4%20f%A8%AF3%20%AF2%20%AF1%200%201%202%203&run) [Answer] # Haskell, 41 bytes ~~`f n=['-'|n>0]++(tail$[1..abs n]>>"-~")++"0"`~~ ``` f n|n<0=tail$f(-n)|x<-[1..n]>>"-~"=x++"0" ``` Thanks to nimi for 3 bytes [Answer] # [V](http://github.com/DJMcMayhem/V), 21 bytes ``` /ä é D@"ña-~ñá0kgJó-- ``` [Try it online!](http://v.tryitonline.net/#code=L8OkCsOpCkRAIsOxYS1-w7HDoTBrZ0rDsy0t&input=MA) V has *very* limited number support, and it actually has no concept of negative numbers. This means in order to support negatives (or even 0), we have to use some hacky workarounds. Explanation: ``` /ä "Move forward to the first digit é "And enter a newline D "Delete this number, into register '"' @" "That number times: ñ ñ "Repeat the following: a " Append the string: -~ " '-~' á0 "Append a 0 k "Move up a line gJ "And join these two lines together ó-- "Remove the text '--', if it exists ``` [Answer] # JavaScript (ES6), ~~39~~ 37 bytes ``` x=>"-~".repeat(x<0?-x:x).slice(x<0)+0 ``` Saved 2 bytes thanks to @Neil [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` A⁾-~ẋḊẋ¡N0 ``` This is a full program. [Try it online!](http://jelly.tryitonline.net/#code=QeKBvi1-4bqL4biK4bqLwqFOMA&input=&args=Mw) ### How it works ``` A⁾-~ẋḊẋ¡N0 Main link. Argument: n A Take the absolute value of n. ⁾-~ẋ Repeat the string "-~" that many times. Result: s ¡ Conditional application: Ḋ Dequeue; remove the first element of s... ẋ N if s, repeated -n times, is non-empty. 0 Print the previous return value. Set the return value to 0. (implicit) Print the final return value. ``` [Answer] # Java 7, ~~95~~ 79 bytes **79 bytes:** ``` String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;} ``` **Ungolfed:** ``` String s(int x) { String t = x<0 ? "~" : ""; while((x<0 ? ++x : x--) != 0) t += "-~"; return t+0; } ``` ~~Old version (95 bytes):~~ ``` String s(int x){return new String(new char[x<0?-x:x]).replace("\0","-~").substring(x<0?1:0)+0;} ``` **Usage:** ``` class A { public static void main(String[]a) { System.out.println(s(-3)); System.out.println(s(-2)); System.out.println(s(-1)); System.out.println(s(0)); System.out.println(s(1)); System.out.println(s(2)); System.out.println(s(3)); } static String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;} } ``` [Try it here!](https://ideone.com/WjEXEd) Output: ``` ~-~-~0 ~-~0 ~0 0 -~0 -~-~0 -~-~-~0 ``` [Answer] ## Ruby, 34 bytes ``` ->x{("-~"*x.abs+?0)[2[0<=>x]..-1]} ``` [Answer] # EXCEL: ~~55~~ 33 bytes ``` =REPT("-~",IF(A1>0,A1,ABS(A1)-1))&"0" ``` Input is in the form of putting a number in the A1 cell. Formula can go anywhere except A1. [Answer] ## T-SQL, 87 bytes ``` select substring(replicate('-~',abs(x)),case when x<0then 2 else 1 end,x*x+1)+'0'from # ``` The `x*x+1` condition in substring is sufficient, since `x^2+1>=2*abs(x)` for all `x`. As usually in SQL, the input is stored in a table: ``` create table # (x int) insert into # values (0) insert into # values (1) insert into # values (-1) insert into # values (2) insert into # values (-2) ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), ~~18~~ 14 bytes *Took some inspiration from [Emigna's answer](https://codegolf.stackexchange.com/a/92600/8478) to save 4 bytes.* ``` li_z"-~"*\0<>0 ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4vezpMOwoKTGlfeiItfiIqXDA8PjAKCl1ufS8&input=LTMKLTIKLTEKMAoxCjIKMw) (As a linefeed-separated test suite.) ### Explanation ``` li e# Read input and convert to integer N. _z e# Duplicate and get |N|. "-~"* e# Repeat this string |N| times. \0< e# Use the other copy of N to check if it's negative. > e# If so, discard the first '-'. 0 e# Put a 0 at the end. ``` [Answer] # Vim - 31 keystrokes First vim golf, prolly missed a ton of stuff. ``` `i-~<esc>:s/-\~-/\~-/dwp<left>ii<esc><left>d$@"<esc>a0` ``` [Answer] ## Matlab, 61 bytes ``` x=input('');A=repmat('-~',1,abs(x));disp([A((x<0)+1:end) 48]) ``` [Answer] ## Pyke, ~~14~~ 13 bytes ``` X,"-~"*Q0<>0+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=X%2C%22-%7E%22%2a0%2BQ0%3C%3E&input=-2&warnings=0) [Answer] # [Perl 6](http://perl6.org), 25 bytes ``` {substr '-~'x.abs~0,0>$_} ``` # Explanation: ``` { substr # string repeat 「-~」 by the absolute value of the input '-~' x .abs # concatenate 0 to that ~ 0 , # ignore the first character of the string if it is negative 0 > $_ } ``` [Answer] # Jelly, ~~14~~ 12 bytes -2 bytes thanks to @Dennis (return 0 rather than concatenate "0", making this a full program only.) ``` 0>‘ A⁾-~ẋṫÇ0 ``` Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=MD7igJgKQeKBvi1-4bqL4bmrw4cw&input=&args=LTU) How? ``` 0>‘ - link 1 takes an argument, the input 0> - greater than 0? 1 if true 0 if false ‘ - increment A⁾-~ẋṫÇ0 - main link takes an argument, the input Ç - y = result of previous link as a monad A - x = absolute value of input ⁾-~ - the string "-~" ẋ - repeat the sting x times ṫ - tail repeatedString[y:] (y will be 1 or 2, Jelly lists are 1-based) 0 - implicit print then return 0 ``` [Answer] ## ><>, 18 + 3 = 22 bytes ``` :?!n0$-:0):1go- -~ ``` [Try it online!](http://fish.tryitonline.net/#code=Oj8hbjAkLTowKToxZ28tCi1-&input=&args=LXYgLTQ) +3 bytes for the `​ -v` flag to initialise the stack with the input. If assuming that STDIN is empty is okay, then the following is a byte shorter: ``` :?!ni*:0):1go- -~ ``` The program keeps flipping the input `n` as necessary until it reaches 0, after which it errors out. ``` [Loop] :?!n If n is 0, output it as a num. If this happens then the stack is now empty, and the next subtraction fails 0$- Subtract n from 0 :0) Push (n > 0) :1go Output the char at (n>0, 1) which is a char from the second line - Subtract, overall updating n -> -n-(n>0) ``` [Answer] # Octave, 51 bytes ``` x=input('');[("-~"'*[1:abs(x)>0])((x<0)+1:end),'0'] ``` At first blatantly copying the Matlab approach by @pajonk and then modifying some details, rewriting as an "outer product" between a vector of ones and the characters "-~" and abusing **on-the-fly-indexing** (or what it could be called) lets us save some bytes. It still pains me slightly that I can't get the index expression to take fewer bytes. Octave allows a(i1)(i2) or even (...)(i1)(i2) for indexing where Matlab would want us to store variables in between the indexings. ``` ((x<0)+1:end) ``` is far too long to describe "skip first if". There must be a better way. [Answer] # [PseudoD](http://github.com/alinarezrangel/PseudoD), ~~688~~ ~~579~~ 521 bytes ``` utilizar mate.pseudo utilizar entsal.pseudo adquirir n adquirir a adquirir r adquirir i fijar n a llamar LeerPalabra finargs si son iguales n y CERO escribir {0} salir fin fijar a a llamar ValorAbsoluto n finargs fijar i a CERO si comparar Importar.Ent.Comparar n < CERO fijar r a {~} sino fijar r a {-} fin mientras comparar Importar.Ent.Comparar i < a escribir r finargs si son iguales r y {~} fijar r a {-} Importar.Ent.Sumar i UNO i sino fijar r a {~} fin finbucle si son iguales r y {~} escribir {~} fin escribir {0} ``` Explain: ``` Read a number from STDIN; If the number is zero (0); Then: Writes 0 to STDOUT and exits; End If; If the number is less than zero (0); Then: Set the fill character to "~"; Else: Set the fill character to "-"; End If; For i = 0; While i is less than abs(number); do: Write the fill character to STDOUT; If the fill character is "~": Set the fill character to "-" Increment i by one Else: Set the fill character to "~" End if; End for; If the fill character is "~"; Then: Write "~" to STDOUT; End If; Write "0" to STDOUT ``` [Answer] # PHP, 61 bytes ``` if(0>$n=$argv[1]){echo"~";$n=~$n;}echo str_repeat("-~",$n),0; ``` [Answer] # PHP, 58 bytes ``` <?=((0<$a=$argv[1])?'-':'').str_pad('0',2*abs($a),'~-',0); ``` [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 25 bytes ``` `?+#~. . ; 6 54_"#2 @! ``` [Try it online!](http://labyrinth.tryitonline.net/#code=YD8rI34uCi4gIDsgNgo1NF8iIzIKICBAIQ&input=LTM) ### Explanation I really like the control flow in this one. The IP runs in a figure 8 (or actually a ∞, I guess) through the code to reduce the input slowly to `0` while printing the corresponding characters. The code starts in the upper left corner going right. The ``` doesn't do anything right now. `?` reads the input and `+` adds it to the implicit zero below. Of course that doesn't do anything either, but when we run over this code again, `?` will push a zero (because we're at EOF), and `+` will then get rid of that zero. Next the `#` pushes the stack depth, simply to ensure that there's a positive value on the stack to make the IP turn south, and `;` discards it again. The `"` is a no-op and acts as the main branch of the code. There are three cases to distinguish: * If the current value is positive, the IP turns right (west) and completes one round of the left loop: ``` _45.`?+ _45 Push 45. . Print as character '-'. ` Negate the current value (thereby applying the unary minus). ?+ Does nothing. ``` * If the current value is negative, the IP turns left (east) and the following code is run: ``` #26.~ # Push stack depth, 1. 26 Turn it into a 126. . Print as character '~'. ~ Bitwise NOT of the current value (applying the ~). ``` Note that these two will alternate (since both change the sign of the input) until the input value is reduced to zero. At that point... * When the current value is zero, the IP simply keeps moving south, and executes the `!` and then turns west onto the `@`. `!` prints the `0` and `@` terminates the program. [Answer] [# GolfScript](http://www.golfscript.com/golfscript/), ~~30~~ ~~24~~ 20 bytes * Saved 6 bytes thanks to xnor. * Saved 4 bytes thanks to Dennis. `~."-~"\abs*\0<{(;}*0` Input: `-5` Output: `-5 = ~-~-~-~-~0` ### Explanation ``` ~. # Input to integer and duplicate "-~" # We shall output a repetition of this string \abs # Move the input onto the stack and computes abs * # Multiply "-~" for abs(input) times \ # Copy onto the stack the input 0< # Is it less than 0? {(;}* # Yes: remove first '-' from the output 0 # Push 0 ``` [Try it online!](http://golfscript.tryitonline.net/#code=fi4iLX4iXGFicypcMDx7KDt9KjA&input=LTI) ]
[Question] [ Print a continuous sinusoidal wave scrolling vertically on a terminal. The program should not terminate and should continuously scroll down the wave (except until it is somehow interrupted). You may assume overflow is not a problem (i.e. you may use infinite loops with incrementing counters, or infinite recursion). The wave should satisfy the following properties: * Amplitude = 20 chars (peak amplitude) * Period = 60 to 65 lines (inclusive) * The output should only consist of spaces, newline and `|` * After each line of output, pause for 50ms Sample output: ``` | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` The above output should go on forever unless otherwise interrupted, e.g. SIGINT or SIGKILL, or closing terminal window, or you power off your machine, or the Sun swallows the Earth, etc. Shortest code wins. Note. I am aware of a similar problem on [Display Scrolling Waves](https://codegolf.stackexchange.com/questions/11940/display-scrolling-waves) but this isn't exactly the same. In my problem, the wave is not to be scrolled "in place" - just output it on a terminal. Also, this is an ascii-art problem, so don't use Mathematica to plot it. [Answer] ## C, ~~74~~ ~~73~~ ~~70~~ ~~69~~ 67 characters 67 character solution with many good ideas from @ugoren & others: ``` i;main(j){main(poll(printf("%*c|\n",j=21+sin(i++*.1)*20,0),0,50));} ``` 69 character solution with while loop instead of recursion: ``` i;main(j){while(printf("%*c|\n",j=21+sin(i++*.1)*20,0))poll(0,0,50);} ``` Approaching perl territory. :) [Answer] ## APL (35) (Yes, it does fit in 35 bytes, [here's a 1-byte APL encoding](http://www-03.ibm.com/systems/resources/systems_i_software_globalization_pdf_cp00907z.pdf)) ``` {∇⍵+⌈⎕DL.05⊣⎕←'|'↑⍨-21+⌈20×1○⍵×.1}1 ``` Explanation: * `{`...`}`1: call the function with 1 at the beginning * `1○⍵×.1`: close enough for government work to `sin(⍵×π÷30)`. (`1○` is `sin`). * `-21+⌈20`: normalize to the range `1..40` and negate * `'|'↑⍨`: take the last `N` characters from the string `'|'` (which results in a string of spaces with a `|` at the end * `⎕←`: display * `⌈⎕DL.05`: wait 50 ms and return `1`. (`⎕DL` returns the amount of time it actually waited, which is going to be close to `0.05`, rounding that value up gives `1`). * `∇⍵+`: add that number (`1`) to `⍵` and run the function again. [Answer] # Mathematica ~~121 104 80 67~~ 64 ``` n=1;While[0<1,Spacer[70 Sin[n Pi/32]+70]~Print~"|";[[email protected]](/cdn-cgi/l/email-protection); n++] ``` ![sine](https://i.stack.imgur.com/JoFcE.png) [Answer] ## Perl, 48 (68) GNU sleep version: 48 ``` print$"x(25+20*sin).'| ';$_+=.1;`sleep .05`;do$0 ``` Cross platform: 68 ``` use Time::HiRes"sleep";print$"x(25+20*sin).'| ';$_+=.1;sleep.05;do$0 ``` Removed the use of Time::HiRes module by using shell sleep function. Shortened increment as per Ruby example. Shortened using $" and $0 seeing hints from Primo's work Thanks for hints Primo. [Answer] ## Perl - 64 (or 60) bytes *The following uses a Windows-specific shell command:* ``` `sleep/m50`,print$"x(20.5-$_*(32-abs)/12.8),'| 'for-32..31;do$0 ``` *The following uses a GNU/Linux-specific shell command:* ``` `sleep .05`,print$"x(20.5-$_*(32-abs)/12.8),'| 'for-32..31;do$0 ``` Both at 64 bytes. * Period is 64. * Maximum amplitude is exactly 20. * The curve is perfectly symmetric. * Every period is identical. ``` | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` Note that this isn't exactly a sinusoidal wave, but rather a quadratic interpolation. Plotted against an actual sin: ![](https://i.stack.imgur.com/j4coG.png) At the granularity required, these are visually indistinguishable. If the aesthetics aren't so important, I offer a **60 byte** alternative, with period length 62, maximum amplitude of ~20.02, and slight asymmetries: ``` `sleep/m50`,print$"x(20-$_*(31-abs)/12),'| 'for-31..30;do$0 ``` [Answer] # Ruby 56 ``` i=0 loop{puts" "*(20*Math.sin(i+=0.1)+20)+?|;sleep 0.05} ``` [Answer] # Befunge 98 - ~~103~~ 100 ``` :1g:02p' \k:02gk,'|,a,$ff*:*8*kz1+:'<\`* 468:<=?ABDEFGGGHGGGFEDBA?=<:86420.,+)'&$#"!!! !!!"#$&')+,.02 ``` Cheers for a program that does this, in a language without trigonometric capabilities; the first program in fact. The second line is simply data; the character corresponding with the ascii value of the sin, added to a space character. **EDIT:** I saved 3 chars by not subtracting the space away; the sinusoid is translated 32 units to the right (which is valid). Befunge also does not have a sleep command, or something similar. It would be nice to find a fingerprint, but I couldn't find one, so `ff*:*8*` pushes `8*225**2` (`405000`) and `kz` runs a noop that many times (well, that many times + 1). On windows command line with [pyfunge](http://mearie.org/projects/pyfunge/), this turns out to be about 50 milliseconds, so I say I'm good. Note: if anyone knows a good fingerprint for this, please let me know. The last part of the code simply checks if the counter (for the data line) is past the data, if it is, the the counter is reset to 0. I used [this](http://ideone.com/om176B) to generate the data. --- # Taylor Series Although this version is 105 chars, I just had to include it: ``` :::f`!4*jf2*-:::*:*9*\:*aa*:*:01p*-01g9*/a2*+\$\f`!4*j01-*b2*+:01p' \k:01gk,$'|,a,ff*:*8*kz1+:f3*`!3*j$e- ``` I was trying to shorten my program, and decided to look at the [taylor series for cosine](http://www.wolframalpha.com/input/?i=taylor%20series%20cos%28x%29) (sine is harder to calculate). I changed `x` to `pi * x / 30` to match the period requested here, then multiplied by `20` to match the amplitude. I made some simplifications (adjusted factors for canceling, without changing the value of the function by much). Then I implemented it. Sadly, it is not a shorter implementation. ``` :f`!4*jf2*- ``` checks whether the values of the taylor series are getting inaccurate (about `x = 15`). If they are, then I compute the taylor series for `x - 30` instead of `x`. ``` :::*:*9*\:*aa*:*:01p*-01g9*/a2*+ ``` is my implementation of the taylor series at `x = 0`, when `x` is the value on the stack. ``` \$\f`!4*j01-* ``` negates the value of the taylor series if the taylor series needed adjustment. ``` b2*+ ``` make the cosine wave positive; otherwise, the printing would not work. ``` :01p' \k:01gk,$'|,a, ``` prints the wave ``` ff*:*8*kz1+ ``` makeshift wait for 50 milliseconds, then increment `x` ``` :f3*`!3*j$e- ``` If `x` is greater than 45, change it to -14 (again, taylor series error adjustment). [Answer] # Python, ~~108~~,~~93~~,~~90~~,~~89~~,88 ``` import math,time a=0 while 1:print" "*int(20+20*math.sin(a))+"|";time.sleep(.05);a+=.1 ``` Now with infinite scrolling :) Edit: ok, 90. Enough? Edit:Edit: no, 89. Edit:Edit:Edit: 88 thanks to [boothby](https://codegolf.stackexchange.com/users/2180/boothby). [Answer] # PHP, 59 characters ``` <?for(;;usleep(5e4))echo str_pad('',22+20*sin($a+=.1)).~ƒõ; ``` [Answer] # C64 BASIC, 64 PETSCII chars ![enter image description here](https://i.stack.imgur.com/se7Xb.png) On a PAL C64, `For i=0 to 2:next i` cycles for approx. 0,05 seconds, so the delay time is respected. [Answer] # C - 86+3 characters **Thanks shiona and Josh for the edit** ``` i;main(j){for(;j++<21+sin(i*.1)*20;)putchar(32);puts("|");usleep(50000);i++;main(1);} ``` ~~i;main(j){for(j=0;j++<20+sin(i/10.)\*20;)putchar(32);puts("|");usleep(50000);i++;main();}~~ float i;main(j){for(j=0;j++<20+sin(i)\*20;)putchar(32);puts("|");usleep(50000);i+=.1;main();} Compiled with the `-lm` flag, I assume I need to add 3 chars [Answer] ## Javascript ~~88~~ ~~76~~ 78 characters ``` setInterval('console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")',i=50) ``` Based on Kendall Frey's code. [Answer] **Ti-Basic, 33 bytes** ``` While 1:Output(8,int(7sin(X)+8),"!":Disp "":π/30+X→X:End ``` **The following caveats exist**: 1. Due to screen limitation of 16x8, this sine wave only has an amplitude of 7 (period of 60 is still maintained) 2. Due to lack of an easy way to access the `|` char, `!` is used instead 3. Due to lack of an accurate system timer, the delay is not implemented. However, run speed appears approximately correct. [Answer] ## JavaScript - 88 ``` setInterval(function(){console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")},i=50) ``` I'm sure someone can come up with something that's actually clever. [Answer] # J - ~~103~~,~~58~~,~~57~~,54 Thanks to awesome guys from IRC ``` (0.1&+[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)^:_]0 ``` In words from right to left it reads: starting from 0 infinite times do: sin, add 1 ,multiply by 20, floor, append 1 (so it becomes array of 2 elements), copy two bytes ' |' correspondingly, print it, wait 0.05s and add 0.1 Instead of infinite loop we can use recursion, it would save 2 characters, but will also produce a stack error after some number of iterations ``` ($:+&0.1[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)0 ``` Where `$:` is a recursive call. [Answer] # Haskell - 75 ``` main=putStr$concat["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]] ``` Unfortunately, I couldn't get the program to pause 50 ms without doubling my char count, so it just floods the console, but it does produce the sine wave. --- Here's the full code with pausing (138 chars with newlines): ``` import GHC.Conc import Control.Monad main=mapM_(\a->putStr a>>threadDelay 50000)(["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]]) ``` [Answer] ## Perl 6: 46 chars ``` sleep .05*say ' 'x(25+20*.sin),'|'for 0,.1...* ``` Create an infinite lazy Range using `0,0.1 ... *`, loop over that. `say` returns `Bool::True` which numifies as 1 in multiplication, this way I can keep it in a single statement. [Answer] fugly **Javascript - 77** ``` i=setInterval("console.log(Array(Math.sin(i+=.1)*20+20|0).join(' ')+'|')",50) ``` and if we do it in Firefox - **73** ``` i=setInterval("console.log(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50) ``` and if we're nasty - **67** ``` i=setInterval("throw(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50) ``` [Answer] # Scala, ~~92~~,~~89~~,87 ``` def f(i:Int){println(" "*(20+20*math.sin(i*.1)).toInt+"|");Thread sleep 50;f(i+1)};f(1) ``` [Answer] ## Python 3, 103 Stupid frikk'n imports... ``` import time,math t=0 while 1:t+=(.05+t<time.clock())and(print(' '*int(20+20*math.cos(t*1.9))+'|')or.05) ``` Rather than "sleep", this implementation grinds at the cpu because python makes it easier to get a floating-point cpu clock than wall clock. This approach won't beat [friol's](https://codegolf.stackexchange.com/a/18640/2180), but it's fun so I'm leaving it up. [Answer] # C# **[152]** Characters ``` namespace System{class P{static void Main(){for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);}}}} ``` I could not get the Existing C# answer to Run and I couldn't downvote because I don't have enough Reputation it was missing a couple of `{` and missing a `)` after the For Loop Declaration. I figure that the variance in the look of the wave when it is run is because of the way we are trying to display this wave. --- if we aren't counting the Namespace and the Method Declaration then it would be **[104]** characters for the working version ``` for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);} ``` [Answer] # VB [236][178] not sure how you would count the tabs, I just took the count from Notepadd++ before I pasted here. **newlines are mandatory, probably why no one likes using it for code golfing.** ``` Module Module1 Sub Main() Dim i While True Console.WriteLine("{0:" & (40 + 20 * Math.Sin(i = i + 0.1)) & "}", "|") Threading.Thread.Sleep(50) End While End Sub End Module ``` [Answer] # C# The Magic Line [91] Characters ``` for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Thread.Sleep(50); ``` Working Program Below. [148] Characters ``` namespace System{class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Threading.Thread.Sleep(50);}}} ``` [Answer] # Bash+bc (to do the math), 80 ``` $ for((;;i++)){ printf "%$(bc -l<<<"a=20*s($i/10);scale=0;a/1+20")s| ";sleep .05;} | | | | | | | | | | | | | | | | | | | ``` [Answer] # TI-BASIC, 30 bytes Small size improvement over the other answer, at the cost of some accuracy. Note that TI-Basic technically has the | character, but you have to transfer it via computer or use an assembly program to access it. ``` While 1 Output(8,int(8+7sin(Ans)),": Disp " .03π+Ans End ``` [Answer] ## Julia - 68 Edit: thanks to M L and ace. ``` i=0;while 0<1;println(" "^int(20sin(.1i)+20)*"|");i+=1;sleep(.05)end ``` Well, it can not compete vs APL, but here's my attempt. Output: ``` | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` [Answer] # MATLAB, 81 bytes ``` t=0;while(fprintf('%s\n',i))i=[];t=t+1;i(fix(21+20*sind(t*6)))='|';pause(.05);end ``` I abused the fact that `i` is always initialized in MATLAB, which meant that I could put the `fprintf` in the `while` statement without initializing `i` first. This does mean the program first outputs an empty line, but I think this is not forbidden in the spec. Furthermore, it abuses the fact that Matlab will ignore most ASCII control characters, printing a space instead of NULL (also for the first empty line). [Answer] ## F# - ~~90~~ ~~79~~ ~~77~~ 76 Here's a solution using recursion ``` let rec f x=printfn"%*c"(int(20.*sin x)+21)'|';Thread.Sleep 50;f(x+0.1) f 0. ``` It could probably be improved further. [Answer] ## AutoHotkey 176 ``` SetKeyDelay,-1 run Notepad.exe WinWaitActive, ahk_class Notepad p:=0 loop { sleep 50 p+=Mod(Floor(A_index/40),2)?-1:1,t:="" loop % p t .= " " sendinput % t "|`n" } esc::Exitapp ``` Run the script . It opens Notepad and prints the characters. Press Esc anytime to exit. [Answer] **Clojure, 121** Short version: ``` (loop[a 0](println(clojure.string/join(repeat(int(+ 20 (* 20 (Math/sin a)))) " ")) \|)(Thread/sleep 50)(recur(+ a 0.1))) ``` Pretty version: ``` (loop [a 0] (println (clojure.string/join (repeat (int (+ 20 (* 20 (Math/sin a)))) " ")) \|) (Thread/sleep 50) (recur(+ a 0.1))) ``` Period is 64. Type this into `lein repl` or save in file `sin.clj` and run with `lein exec sin.clj` (requires lein-exec plugin). ]
[Question] [ Your task today is to implement a time limit for getting input, a task I've found rather annoying to achieve in most languages. You will create a program function which prompts the user for input. Immediatly after the user supplies input, print the message `input received` and end execution/return. However, if the user waits for more than 10 seconds to provide input, output the message `no input received` and end execution/return. Input must be from `stdin` (the console) or equivalent, not function or program arguments, however output can be either to `stdout`, your function's return value, or any other accepted output method. You may ask for any amount of input, it can be a single character, a line, a word, or whatever method is shortest in your language as long as it waits for at least one character. You must output as soon as the input is received, not after the 10 seconds have passed. After 10 seconds have passed, you *must* end, you cannot continue waiting for input after `no input received` has been printed. You may assume that input is not passed in the time between 10 seconds elapsing and text being printed to the screen, as this is an extremely small window. You may also assume that your language's builtin equivalent of `sleep` is consistently, absolutely perfect. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Answer] ## bash, 38 bytes ``` read -t10||a=no;echo $a input received ``` This uses the `-t` (timeout) option to bash's `read`, which causes it to fail and return a nonzero exit code if no input is given in the specified number of seconds. [Answer] ## Haskell, ~~97~~ 89 bytes ``` import System.Timeout timeout(10^7)getChar>>=putStr.(++"input received").maybe"no "mempty ``` If `timeout` times out it returns `Nothing` and `Just Char` (`Char`, because we're using `getChar`) otherwise. This return value is converted to `"no "` or `""` by function `maybe "no " mempty`. Append `"input received"` and print. Edit: @BMO suggested `maybe` and saved some bytes. [Answer] # POSIX C99, 71 63 bytes ``` main(){puts("no input received"+3*poll((int[]){0,1},1,10000));} ``` Ungolfed: ``` #include <unistd.h> #include <poll.h> #include <stdio.h> int main() { struct pollfd pfd; pfd.fd = STDIN_FILENO; pfd.events = POLLIN; puts("no input received"+3*poll(&pfd,1,10000)); } ``` Since `poll` will return 1 in case of success, we multiply the result by 3 and shift the string accordingly. Then, we use the fact that `struct pollfd` has the following layout: ``` struct pollfd { int fd; /* file descriptor */ short events; /* events to look for */ short revents; /* events returned */ }; ``` and that `STDIN_FILENO` is `0`, `POLLIN` is `1` to replace `pfd` with `int pfd[] = {0,1}`, which we finally make a compound litteral (as allowed by C99). [Answer] # Applescript, 113 Applescript doesn't really do reading from STDIN. Hopefully a `display dialog` is acceptable here: ``` ({"","no "}'s item((display dialog""default answer""giving up after 10)'s gave up as integer+1))&"input received" ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~41~~ 40 bytes ``` 'no input received'↓⍨{3*⍨⎕RTL←10::0⋄3⊣⍞} ``` This is an anonymous tacit function which [needs a dummy argument to run](https://codegolf.meta.stackexchange.com/a/12696/43319). `'no input received'` the full string `↓⍨` drop as many characters from the front of that as the number returned by the `{` anonymous explicit function (`⍵` denotes the argument)  `⎕RTL←10` set **R**esponse **T**ime **L**imit to ten seconds  `3*⍨` raise that number (ten) to the power of three (a thousand means "all")  `::` upon those exceptions (all),   `0` return 0  `⋄` try:   `⍞` get input   `3⊣` discard that and instead return 3 `}` end of function (note that the argument `⍵` was never mentioned) [Answer] # [Perl](http://perl.org), ~~74~~ 67 bytes ``` $m="input received";$SIG{ALRM}=sub{die"no $m\n"};alarm 10;<>;say$m ``` ### Old Version ``` $m="input received";$SIG{ALRM}=sub{die "no $m\n"};alarm 10;<stdin>;say $m; ``` (Run via perl -M5.10.1 ...) [Answer] # [Perl 6](https://perl6.org), ~~72~~ 66 bytes ``` my $s='input received';Promise.in(10).then:{say "no $s";exit};get;say $s ``` [Try it with no input](https://tio.run/##HY3BSsQwFEX3/YrLWKjOoujGRcIsXDhaEBX1B8LkOQmTvpTkjRpKv71GV5dzD5c7UQq36wU@zYlgcM6UIM4IbKTMnUDKVAUXcZ6PTbu9e3vYD0/379ih3Q7PNQ7B5Ayl4DOGF6UeDdtAmBtgJHHR4kjyj0CIccKMD5fI2L54ChZLNUuz9Ezfeh0L2rzrPE9nQaID@S@ynX5NcfSZes@XN9dXvThiNWdTsOFYBxtNP14WXY/0X9vmdf0F "Perl 6 – Try It Online") [Try it with input](https://tio.run/##HY0xbsJAFER7n2LkWCJQWKGh2BVFCgiWohBBm2aFP/GK9dra/53EQr5MOAdn4gjOhmo0T5o3LQW3GB9wNCeCQccUIJURSN8S43b93ZBzze16gfEl2kDMkQeSLvgkmz3vXtbF62qPJbJZ8Rbj4AwzlIJlFFulNnHnCOcEqEmqpsQnyb0C6V3@4dPYhmTIPX3rse6R8XJifdtJPDqQ/aJyot9DU1um3PrH@dM0l4q8OrPpkfomDlJNP1YGHeX6n2Y8jn8 "Perl 6 – Try It Online") ``` my$s='input received';start {sleep 10;say "no $s";exit};get;say $s ``` [Try it with no input](https://tio.run/##HY3NagIxFIX38xQHDQy4EN10McGFC38GpIW2LxDM1QnGJORe2waZZ58GV4fvfHBOouzfpjku5kYweDBlyGAENhKHViAlVRGKDC5cG7XYfh72/Wn3hQ3Uon@vcfaGGV0Hx@g/uu5ogvWEZwPcSYZocSV5IeBjTHjie8hk7LI48hZjNWMzLgP96uleFG9aF9JDkOlM7odsq1lMrhPsiRLWK82mYBYiFM80/TkZdb14tYqn6R8 "Perl 6 – Try It Online") [Try it with input](https://tio.run/##HY1BisJAFET3OUURGwQXw7hxkcaFC2cMiIJu3TTmq8G20/T/UYPkMnoOz@QRYpNVUQ/qladgJ90AB3MmGNRMAXIyAmk8MT7v54KsrT7vF4wr4AMxRx5I6uASNZpt/v/y5XyLKdQoX8XYW8OMLEPJyNdZtog7S3gkwIXkVBU4kvQVSHv5zqWxtUn74@imu0ujeDosna8l/uypvFIx1CwmxBlbIo/xr2bTIHUVFKea7qW0Omp7qrjrvg "Perl 6 – Try It Online") ``` my $s = 'input received'; # base message start { # create a Promise with a code block # that is run in parallel sleep 10; # delay for 10 seconds say "no $s"; # say 「no input received」 exit # exit from the process } get; # get a line from the input say $s # say 「input received」 ``` [Answer] # C#, ~~180~~ ~~171~~ ~~148~~ 131 bytes ``` ()=>{var t=new System.Threading.Thread(()=>{System.Console.ReadKey();});t.Start();return(t.Join(10000)?"":"no ")+"input recieved";} ``` *Saved 17 bytes thanks to @VisualMelon.* Full/Formatted version: ``` class P { static void Main() { System.Func<string> f = () => { var t = new System.Threading.Thread(() => { System.Console.ReadKey(); }); t.Start(); return (t.Join(10000) ? "" : "no ") + "input recieved"; }; System.Console.WriteLine(f()); System.Console.ReadLine(); } } ``` [Answer] # TI-BASIC, ~~84~~ 77 bytes -7 thanks to [@kamoroso94](https://codegolf.stackexchange.com/users/57013/kamoroso94) ``` :startTmr→T //Start Timer, 5 bytes :Repeat checkTmr(T)=10 or abs(int(.1K)-8)≤1 and 1≥abs(3-10fPart(.1K //Loop until the timer is 10 seconds or a number key is pressed, 32 bytes :getKey→K //get key code, 4 bytes :End //end loop, 2 bytes :"NO INPUT RECEIVED //Push string "NO INPUT RECEIVED" to Ans, 18 bytes :If K //If input was received, 3 bytes :Disp sub(Ans,3,15 //Diplay "INPUT RECEIVED", 9 bytes :If not(K //If no input, 3 bytes :Ans //Display "NO INPUT RECEIVED", 1 byte ``` Waits until a number is pressed. I am trying to figure out how to golf the sequence `{72,73,74,82,83,84,92,93,94}`. It is taking up a lot of space. [Answer] # NodeJS, ~~105~~ ~~103~~ 101 bytes *-2 bytes thanks to @apsillers* *-2 bytes by moving `console.log()` into `exit()`* ``` with(process)stdin.on('data',r=x=>exit(console.log((x?'':'no ')+'input received'))),setTimeout(r,1e4) ``` Run by saving to a file and running it with node or run it straight from the command line by doing `node -e "<code>"` [Answer] # Go, 149 bytes ``` package main import( ."fmt" ."time" ."os" ) func main(){ o:="input received" go func(){Sleep(1e10) Print("no "+o) Exit(0)}() i:="" Scan(&i) Print(o)} ``` [Answer] # [AHK](https://autohotkey.com/), ~~67~~ 65 bytes *2 bytes saved by [Blauhirn](https://codegolf.stackexchange.com/q/125332//125348?noredirect=1#comment308732_125348)* ``` InputBox,o,,,,,,,,,10 s:=ErrorLevel?"no ": Send %s%input received ``` AHK has a built-in timeout for input boxes. I tried to get clever and use `!o` instead of `ErrorLevel` but that fails if the user inputs a falsey value. Almost half of the answer is just the command names and fixed text. [Answer] # JavaScript (ES6) + HTML, ~~86~~ ~~84~~ ~~82~~ 79+11 = ~~97~~ ~~95~~ ~~93~~ 90 bytes ``` setTimeout(oninput=_=>i.remove(alert(`${i.value?"":"no "}input received`)),1e4) ``` ``` <input id=i ``` * 2 bytes saved thanks to [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers) pointing out that I'm dumb! --- ## Try it Requires a closing `>` on the `input` in order to work in a Snippet. ``` setTimeout(oninput=_=>i.remove(alert(`${i.value?"":"no "}input received`)),1e4) ``` ``` <input id=i> ``` [Answer] # Python 3, 158 bytes ``` import os,threading as t,time def k(t=10):time.sleep(t);print("No input received"[(10-t)//3:]);os.kill(os.getpid(),t) t.Thread(None,k).start() if input():k(0) ``` [Answer] ## VB.Net - 174 bytes ``` Module M Sub Main() Dim t=New Threading.Thread(Sub()Console.Read()):t.Start():Console.WriteLine(If(t.Join(10000),"","no ") & "input received"):End End Sub End Module ``` COBOL version coming tomorrow ;-) [Answer] # Python3, ~~100~~ ~~89~~ ~~83~~ 71 bytes ``` import pty print("no input received"[3*any(pty.select([0],[],[],10)):]) ``` First try at golfing. -4 for `any()`, -7 for slicing, thanks @user2357112! -6, get `select()` from `pty` instead of `select`. [Answer] ## PowerShell, 110 bytes ``` $s1=date;while(![console]::KeyAvailable-and($i=((date)-$s1).seconds-lt10)){} "{0}input received"-f(,'no ')[$i] ``` [Answer] # Scratch 2/3.x, 41 points ([Explanation](https://codegolf.meta.stackexchange.com/questions/673/golfing-in-scratch)) [![Impatient timer](https://i.stack.imgur.com/LurNL.png)](https://i.stack.imgur.com/LurNL.png) 1: When GF clicked 1: ask [] and wait 1 + 14 chars: say [input received] 1: stop [all v] (note: since "all" was its default setting I counted the block as 1) 1 + 2 digits: wait (10) seconds 1 + 17 chars: say [no input received] 1: stop [all v] [Answer] # Scratch 3.0 (scratchblocks3 syntax), 129 bytes/40 [points](https://codegolf.meta.stackexchange.com/questions/673/golfing-in-scratch) Beats @Syntax Error's answer by 1 point, but loses to it by 8 bytes. ``` define broadcast[w v ask[]and wait say[input received stop[all v when I receive[w v wait(10)secs say[no input received stop[all v ``` Ungolfed: ``` define // custom blocks (functions) do not need names. functions are shorter than programs when counting bytes, because programs that run require "when gf clicked" broadcast [w v] ask [] and wait // contrary to what the name of this block would suggest, there is no "ask [] (without waiting)" block - this is why the broadcast is necessary to allow other blocks to run while this block is waiting say [input received] stop [all v] when I receive [w v] wait (10) secs // although the actual block reads 'seconds', 'secs' is valid in scratchblocks syntax say [no input received] stop[all v] ``` [Answer] ## Tcl, 99 bytes ``` after 10000 {set () no} vwait [fileevent stdin r {gets stdin (x)}] puts [lappend () input received] ``` [Answer] # SmileBASIC 3, 74 bytes "Accepts input" by waiting for any button press (that should count as input.) ``` M=MAINCNT@L N=MAINCNT-M>599CLS?"NO "*N;"INPUT RECEIVED ON N+BUTTON()GOTO@L ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 43 + 6 = 49 bytes ``` a/!/i0(?\~"input recieved"r>o< o "\?:-1/r"n ``` [Try it online!](https://tio.run/##S8sszvj/P1FfUT/TQMM@pk4pM6@gtEShKDU5M7UsNUWpyC7fhitfQSnG3krXUL9IKQ@o@L9uYomegQUA "><> – Try It Online") +5 for the `-t.08` flag, which sets the tick to 0.08 seconds, and +1 for the `a` flag, which counts whitespace and skipped instructions as ticks. The program checks for input about once every second, and exits the loop if input is detected. If input is not received, it exits the loop from the bottom, appending `no` to the beginning of the string. The initial `/` is to ensure that the last check for input is exactly on the 10 second mark. It then takes about 5-6 seconds to print the string itself. [Answer] # Java 1.4+, 284 bytes ``` import static java.lang.System.*;public class X{public static void main(String[]x){new Thread(){public void run(){try{Thread.sleep(10000L);}catch(Exception e){}out.print("no input recieved");exit(0);}}.start();new java.util.Scanner(System.in).nextLine();out.print("input recieved");}} ``` **Ungolfed:** ``` import static java.lang.System.*; public class InputAndWait { public static void main(String[] x) { new Thread() { public void run() { try { Thread.sleep(10000L); } catch (Exception e) { } out.print("no input recieved"); exit(0); } }.start(); new java.util.Scanner(System.in).nextLine(); out.print("input recieved"); } } ``` --- Please don't suggest Version-specific Java improvements, this is a generic Java answer that works in all currently stable Java Environments (1.4 and above). --- Very freaking wordy... The catch is required, can't throw it. System import shaves off like 5 bytes... Overloading is also wordy, so it ends up a wordy poorly-golfed-looking mess. [Answer] # [Julia 0.6](http://julialang.org/), 78 bytes Longer than I expected. See comments for "no input recieved" TIO link. ``` s="input recieved" Timer(x->(show("no "*s);exit()),10) readline(STDIN) show(s) ``` [Try it online!](https://tio.run/##yyrNyUw0@/@/2FYpM6@gtEShKDU5M7UsNUWJKyQzN7VIo0LXTqM4I79cQykvX0FJq1jTOrUis0RDU1PH0ECTqyg1MSUnMy9VIzjExdNPkwussljz/38A "Julia 0.6 – Try It Online") [Answer] # SmileBASIC, ~~74~~ 73 bytes ``` M=MAINCNT WHILE!I*M>MAINCNT-600I=INKEY$()>" WEND?"no "*!I;"input received ``` Takes 1 character of input. And a 39 byte solution which probably isn't valid (doesn't actually accept text input, just has an `OK` button that you can press) ``` ?"no "*!DIALOG("",,,10);"input received ``` ]
[Question] [ There are [40 ways](https://oeis.org/A096969) a directed [Hamiltonian path](http://mathworld.wolfram.com/HamiltonianPath.html) can be arranged on a 3×3 grid: ![all 20 undirected Hamiltonian paths of a 3&times3; grid](https://i.stack.imgur.com/6g51G.png) This graphic ([thanks Sp3000!](https://chat.stackexchange.com/transcript/message/22631899#22631899)) shows only the 20 undirected paths. Traverse each colored line in both directions for the 40 directed paths. # Challenge Using only [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters), write a 3×3 grid of characters, such as: ``` ABC DEF GHI ``` When each of the 40 directed paths are read from this grid as 40 single-line, 9-character programs, the goal is to have each program output a unique integer from 1 to 40. Doing this for *all* 40 paths seems difficult and unlikely, so you only need to make it work for as many paths as you can. **The submission whose 40 path-programs output the most distinct numbers from 1 to 40 will be the winner. Tiebreaker goes to the earlier submission.** Path-programs that error or do not output an integer from 1 to 40 or output an integer that another path-program already covered are not counted. Specifically: * Programs that error while compiling, running, or exiting are not counted. Warnings are ok. * Programs that don't output an integer from 1 to 40 or output something slightly malformed such as `-35` or `35 36` are not counted. * Programs that require user input to produce the output are not counted. * Programs that never end are not counted. * From [now on](https://codegolf.stackexchange.com/questions/52809/40-numbers-in-9-bytes/52917#52917), programs that aren't deterministic aren't counted. * Otherwise valid programs that output an integer from 1 to 40 that another valid program has already output are not counted. (The first program *is* counted.) * Only programs that output integer representations of numbers from 1 to 40 (inclusive) are counted towards your total. The numbers are expected to be in the usual `1`, `2`, ..., `39`, `40` format, unless that is not the norm for your language. (A trailing newline in the output is fine.) * Which numbers your programs output and what order they are in does not matter. Only the number of distinct integers from valid programs matters. **All path-programs must be run in the same language.** However, the "programs" may in fact be functions (with no required arguments) or [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) commands, as well as full programs, that print or return their target integer. You may mix and match between functions, REPL commands, and full programs. Your 9 printable ASCII characters do not need to be distinct. # Example If your 3×3 grid were ``` ABC DEF GHI ``` and your 40 programs and outputs looked like this ``` ABCFEDGHI -> 26 ABCFIHEDG -> 90 ABCFIHGDE -> 2 ABEDGHIFC -> syntax error ADEBCFIHG -> prints 40 but then errors ADGHEBCFI -> 6 ADGHIFCBE -> 6 ADGHIFEBC -> 6 CBADEFIHG -> runtime error CBADGHEFI -> 3 CBADGHIFE -> 4 CFEBADGHI -> -32 CFIHEBADG -> 38.0 CFIHGDABE -> "36" EDABCFIHG -> 33 EFCBADGHI -> no output EHGDABCFI -> compilation error EHIFCBADG -> 8 GDABCFEHI -> 22 GHEDABCFI -> 41 IHGDEFCBA -> 0 GDEHIFCBA -> '9' EDGHIFCBA -> +10 CFIHGDEBA -> 11 GHIFCBEDA -> error IFCBEHGDA -> error EBCFIHGDA -> prints 23 but then loops infinitely CBEFIHGDA -> randomly prints either 24 or 44 GHIFEDABC -> error IFEHGDABC -> 30 EFIHGDABC -> 39 IHGDABEFC -> 7 GDABEHIFC -> 29 EBADGHIFC -> -1 GHIFCBADE -> 26 IHGDABCFE -> 1 IFCBADGHE -> error GDABCFIHE -> no output IHEFCBADG -> no output IFCBADEHG -> "quack" ``` your score would be 14, because there are 14 distinct integers from 1 to 40 validly output, namely `26 2 6 3 4 33 8 22 11 30 39 7 29 1`. [Answer] # [Deadfish](http://esolangs.org/wiki/Deadfish), 18 This was actually the first language I tried before I considered infix operators. I'm posting it now for the sheer hilarity of the idea that Deadfish could be useful for something. ``` iii ios sii ``` For those who don't know Deadfish, `i` is increment, `s` is square and `o` is output, with the accumulator starting at 0 (there's also a 4th instruction `d` for decrement not used here). The fact that we don't have automatic printing and need to use `o` is a major drawback, but surprisingly Deadfish doesn't do too terribly here, all things considered. It turns out that the optimal placement of the output operator is in the middle. ``` iiisoisii 9 iiisiiois 11 iiisiisio 122 iioisiisi 2 iioiisiis 2 iisioiisi 5 iisiisiio 38 iisiisoii 36 iiiiosiis 4 iiiisiosi 17 iiiisiiso 324 isoiiisii 1 isiioiiis 3 isiisiiio 12 oiiiisiis 0 osiiiisii 0 oisiiiisi 0 oiisiiiis 0 siiiisoii 16 sioiiiisi 1 iisiosiii 5 sioiisiii 1 oisiisiii 0 isiisioii 10 siisiioii 6 isiioisii 3 oiisiisii 0 iiosiisii 2 siisoiiii 4 isoisiiii 1 osiisiiii 0 iisiiiosi 7 siiioiisi 3 oiiisiisi 0 siisiiiio 8 iisiiiiso 64 isiiiisio 26 siiiisiio 18 iiosiiiis 2 isiiiiois 5 ``` [Answer] ## PARI/GP - 24 ``` 1%1 8 2+3 ``` PARI/GP ignores spaces between digits, so that `1 8 2`, for example is treated as `182`. The same could work for perl by replacing the spaces with underscores. I haven't exhausted the entire search space, so there may be better candidates. A program can be fed to gp as `gp -q -f program.gp`, or interactively in the repl. --- **Output** ``` 1%1 8 2+3 -> 4 1%1 3+8 2 -> 83 # invalid 1%1 3+2 8 -> 29 1%8 2+3 1 -> 32 1 8%1 3+2 -> 7 1 2+8%1 3 -> 20 1 2+3 1%8 -> 19 1 2+3 8%1 -> 12 1%1 8 3+2 -> 3 1%1 2+8 3 -> 84 # invalid 1%1 2+3 8 -> 39 1 8%1 2+3 -> 9 1 3+8%1 2 -> 21 1 3+2 1%8 -> 18 8 1%1 3+2 -> 5 8 1%1 2+3 -> 12 # dup 8+2 1%1 3 -> 16 8+3 1%1 2 -> 15 2 1%1 8+3 -> 6 2+8 1%1 3 -> 5 # dup 3+2 8 1%1 -> 3 # dup 2 8+3 1%1 -> 28 8 2+3 1%1 -> 82 # invalid 1 3+2 8%1 -> 13 2+3 1%8 1 -> 33 3 1%8+2 1 -> 28 # dup 8%1 3+2 1 -> 29 # dup 1%8 3+2 1 -> 22 2+3 8 1%1 -> 2 3 8+2 1%1 -> 38 8 3+2 1%1 -> 83 # invalid 3+2 1%8 1 -> 24 2 1%8+3 1 -> 36 8%1 2+3 1 -> 39 # dup 2+3 1%1 8 -> 15 # dup 3+2 1%1 8 -> 6 # dup 3 1%1 2+8 -> 15 # dup 2 1%1 3+8 -> 16 # dup 3+8 1%1 2 -> 12 # dup 3 1%1 8+2 -> 15 # dup ``` All but 4 values are within the required range, with 12 duplicate entries. --- **Update** I've finished crunching, there are six distinct 23s, and only one 24 (as read by rows): ``` 23 1%1 6 2+3 [2, 3, 4, 5, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 22, 24, 26, 27, 32, 33, 34, 36, 37] 23 1 2%3+2*8 [2, 5, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 25, 26, 29, 31, 32, 37, 40] 23 2 3%1+8 2 [2, 4, 6, 7, 10, 11, 12, 13, 14, 15, 16, 20, 21, 23, 24, 28, 29, 30, 31, 32, 33, 34, 40] 23 4%6%5*7+6 [2, 4, 5, 6, 7, 8, 9, 12, 13, 19, 21, 23, 24, 26, 29, 31, 32, 33, 34, 37, 38, 39, 40] 23 5%6%4*7+6 [2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 25, 26, 29, 31, 33, 34, 37, 38, 39, 40] 23 5%6%4*8+6 [1, 3, 5, 6, 8, 9, 10, 12, 14, 15, 18, 22, 24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 40] 24 1%1 8 2+3 [2, 3, 4, 5, 6, 7, 9, 12, 13, 15, 16, 18, 19, 20, 21, 22, 24, 28, 29, 32, 33, 36, 38, 39] ``` The program I used for crunching is below. PARI/GP has limited string processing capabilities, so deal mainly with char arrays (a.k.a. `Vecsmall`). The operators tested are `+`, `-`, `*`, `\` (floor div), `%`, `;` (expression separator, essentially discards everything before it), and (space, as described above). The exponent operator `^` could also be added, but it becomes too slow to test exhaustively. ``` perms = {[ [1, 2, 3, 6, 5, 4, 7, 8, 9], [1, 2, 3, 6, 9, 8, 5, 4, 7], [1, 2, 3, 6, 9, 8, 7, 4, 5], [1, 2, 5, 4, 7, 8, 9, 6, 3], [1, 4, 5, 2, 3, 6, 9, 8, 7], [1, 4, 7, 8, 5, 2, 3, 6, 9], [1, 4, 7, 8, 9, 6, 3, 2, 5], [1, 4, 7, 8, 9, 6, 5, 2, 3], [3, 2, 1, 4, 5, 6, 9, 8, 7], [3, 2, 1, 4, 7, 8, 5, 6, 9], [3, 2, 1, 4, 7, 8, 9, 6, 5], [3, 6, 5, 2, 1, 4, 7, 8, 9], [3, 6, 9, 8, 5, 2, 1, 4, 7], [3, 6, 9, 8, 7, 4, 1, 2, 5], [5, 4, 1, 2, 3, 6, 9, 8, 7], [5, 6, 3, 2, 1, 4, 7, 8, 9], [5, 8, 7, 4, 1, 2, 3, 6, 9], [5, 8, 9, 6, 3, 2, 1, 4, 7], [7, 4, 1, 2, 3, 6, 5, 8, 9], [7, 8, 5, 4, 1, 2, 3, 6, 9], [9, 8, 7, 4, 5, 6, 3, 2, 1], [7, 4, 5, 8, 9, 6, 3, 2, 1], [5, 4, 7, 8, 9, 6, 3, 2, 1], [3, 6, 9, 8, 7, 4, 5, 2, 1], [7, 8, 9, 6, 3, 2, 5, 4, 1], [9, 6, 3, 2, 5, 8, 7, 4, 1], [5, 2, 3, 6, 9, 8, 7, 4, 1], [3, 2, 5, 6, 9, 8, 7, 4, 1], [7, 8, 9, 6, 5, 4, 1, 2, 3], [9, 6, 5, 8, 7, 4, 1, 2, 3], [5, 6, 9, 8, 7, 4, 1, 2, 3], [9, 8, 7, 4, 1, 2, 5, 6, 3], [7, 4, 1, 2, 5, 8, 9, 6, 3], [5, 2, 1, 4, 7, 8, 9, 6, 3], [7, 8, 9, 6, 3, 2, 1, 4, 5], [9, 8, 7, 4, 1, 2, 3, 6, 5], [9, 6, 3, 2, 1, 4, 7, 8, 5], [7, 4, 1, 2, 3, 6, 9, 8, 5], [9, 8, 5, 6, 3, 2, 1, 4, 7], [9, 6, 3, 2, 1, 4, 5, 8, 7] ]} ops = Vecsmall("+-*\\%; ") ms = 1 for(c = 48, 57, { for(d = c, 57, for(f = d, 57, for(g = c, 57, for(e = 48, 57, print1(Strchr([c,d,e,f,g,13])); for(h = 1, #ops, for(i = 1, #ops, for(j = 1, #ops, for(k = 1, #ops, a = Vecsmall([c, ops[h], d, ops[i], e, ops[j], f, ops[k], g]); s = Set(); for(m = 1, #perms, v = Strchr(vecextract(a, perms[m])); iferr(b = eval(v), E, b = 0); if(b >= 1 && b <= 40, s = setunion(s, [b])) ); if(#s >= ms, ms = min(23, #s); print(#s, " ", Strchr(a), " ", s)); ) ) ) ) ) ) ) ) }) ``` [Answer] # Python REPL and many more, ~~22~~ 23 ``` 6+7 *5% 6%4 ``` Key observation: If you colour the grid like a checkerboard, the path alternates grid colours as it goes and starts and ends on the same colour. ~~Still brute forcing for better.~~ Trying with `+*%` (and even `**` for languages where `^` is exponentiation) didn't turn up anything better, unfortunately. I also tried throwing in bitwise operators and only `^` (xor) seemed to mildly help, but the search was taking too long so I've given up. ``` 6+7%5*6%4 6 6+7%4%5*6 24 6+7%4%6*5 21 6+5*6%4%7 8 6*5+7%4%6 33 6*6%5+7%4 4 6*6%4%7+5 5 6*6%4%5+7 7 7+6*5%4%6 9 7+6*6%5%4 8 7+6*6%4%5 7 7%5+6*6%4 2 7%4%5+6*6 39 7%4%6*6+5 23 5*6+7%4%6 33 5%7+6*6%4 5 5%6*6+7%4 33 5%4%7+6*6 37 6*6+7%5%4 38 6%5*6+7%4 9 4%6*5%7+6 12 6*5%4%7+6 8 5*6%4%7+6 8 7%4%6*5+6 21 6%4%7+5*6 32 4%7+5%6*6 34 5+7%4%6*6 23 7+5%4%6*6 13 6%4%5*6+7 19 4%5%6*6+7 31 5%4%6*6+7 13 4%6*6+5%7 29 6*6+5%4%7 37 5+6*6%4%7 5 6%4%7+6*5 32 4%6*6+7%5 26 4%7+6*6%5 5 6*6+7%4%5 39 4%5%7+6*6 40 4%7+6*5%6 4 ``` [Answer] # J, 15 ``` 2 + 1 * 3 * 2 + 3 ``` This outputs only valid numbers, but a lot are duplicates. The unique values are `17 11 16 28 31 23 13 10 21 33 18 24 22 29 27`. You can definitely do better by changing operators and the integers involved. ``` 2+1*3*2+3 -> 17 2+1*3+3*2 -> 11 2+1*3+2*3 -> 11 2+3*2+3*1 -> 17 2*3+1*3+2 -> 16 2*2+3+1*3 -> 16 2*2+3*1+3 -> 28 2*2+3*3+1 -> 28 1+2*3*3+2 -> 31 1+2*2+3*3 -> 23 1+2*2+3*3 -> 23 1*3+2*2+3 -> 13 1*3+3+2*2 -> 10 1*3+2*2+3 -> 13 3*2+1*3+2 -> 21 3*1+2*2+3 -> 33 3+2*2+1*3 -> 13 3+3*1+2*2 -> 18 2*2+1*3+3 -> 16 2+3*2+1*3 -> 17 3+2*3*1+2 -> 21 2*3+3*1+2 -> 24 3*2+3*1+2 -> 33 1*3+2*3+2 -> 13 2+3*1+3*2 -> 23 3*1+3+2*2 -> 24 3+1*3+2*2 -> 10 1+3*3+2*2 -> 22 2+3*3*2+1 -> 29 3*3+2*2+1 -> 27 3*3+2*2+1 -> 27 3+2*2+3*1 -> 13 2*2+3+3*1 -> 16 3+2*2+3*1 -> 13 2+3*1+2*3 -> 23 3+2*2+1*3 -> 13 3*1+2*2+3 -> 33 2*2+1*3+3 -> 16 3+3*1+2*2 -> 18 3*1+2*3+2 -> 33 ``` [Answer] ## ><>, 36\* *If you're lucky enough!* ``` x;x lxl xnx ``` ~~Since the challenge does not require the code to be deterministic we only have to prove that it is possible (even if improbable) to return 36 numbers and we are done.~~ It was good while it lasted I guess. (For those not familiar with ><>, a great intro on can be found [here](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time-experimental-challenge/44686#44686)) > > ><> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages — program flow can be up, down, left or right! > > > I decided to use the "x" instruction in ><>, which changes the instruction pointers direction to either up, down, left or right at random. Since our code will only be one line, that means that we can only look at the cases when it goes right or left, since if the pointer goes up or down, it will just hit the "x" instruction again. The "n" instruction pops the number at the top of the stack and prints it. However if the stack is empty and there is nothing to pop, an error is raised. The "l" instruction simply pushes the length of the stack onto the stack (and lucky for us it does not send an error if the stack is empty), so for example if the stack were empty and "l" would be called, it would push 0 onto the stack. If we would now again call "l", then since the stack has one element (0), it would push 1 to the top of the stack and now that would mean that there would be two things on the stack and that would mean that if we were to call "l" again, we would push 2 onto the stack etc. So we can use "l" to push an arbitrary number onto the stack via the method shown earlier. The ";" instruction ends the program. The idea with using "x" is that, for example if there was only one "x" in the code (where A,B,C,D are some instructions): ``` ABCx;D ``` The program would execute A then B then C, and upon reaching "x" we would have two possibilites: the code either continues to go right and hits the ";" and exits or it goes left and executes C then B then A then D and only then exits. So if our code contained one "x", the program gains two possible program flows from which we may choose the most suited program. I there are two or more "x"es then we gain an infinite number of possible program flows. Our code has five "x"es, futhermore each of them is in a "starting cell" of the Hamiltonian paths, which means every single program will start with an "x", and every program will have the structure: ``` xAxBxCxDx ``` Where A, B, C, D belong to { ; , n, l, l} This means that there are only 12 unique programs. Furthermore since we always start on an "x", we may look at the case when the program goes left, thus symmetric programs can also be regarded the same. Up to symmetry there are only 6 different posible programs. Only 4 of them occur in the programs generated as hamiltonian paths: ``` xnxlxlx;x xlxnxlx;x xnxlx;xlx xlxnx;xlx ``` Let us look at the first program "xnxlxlx;x" if we go right at the first step we hit the print command which will raise an error since we have nothing on the stack. If we go left we hit the end program command. So we **cannot output any number** from these programs. The second program, "xlxnxlx;x", is a lot more hopeful, since upon going right at the begining a zero is put on the stack, if we then go left at the next "x", our stack gains a one, then going right again we have a 2 that we can then print and continue going right to end the program. We can observe that we can actually print **any even number**, since in the "xlx" part at the beginning we can reach a number of arbitrary size by going right then left then right again a certain number of times. Similiarly it can be seen that the third program xnxlx;xlx can output **any odd number**, by going left at the beginning and then repeating the "xlx" routine only this time going left then right then left. And the fourth program is essentially the same as the second program and can output **any even number**. So for the required programs we have: ``` x;xlxlxnx (none) x;xlxnxlx (any even number) x;xlxnxlx (any even number) x;xlxnxlx (any even number) xlx;xlxnx (any odd number) xlxnx;xlx (any even number) xlxnxlx;x (any even number) xlxnxlx;x (any even number) x;xlxlxnx (none) x;xlxnxlx (any even number) x;xlxnxlx (any even number) xlx;xlxnx (any odd number) xlxnx;xlx (any even number) xlxnxlx;x (any even number) xlx;xlxnx (any odd number) xlx;xlxnx (any odd number) xnxlx;xlx (any odd number) xnxlx;xlx (any odd number) xlx;xlxnx (any odd number) xnxlx;xlx (any odd number) xnxlxlx;x (none) xlxnxlx;x (any even number) xlxnxlx;x (any even number) xlxnxlx;x (any even number) xnxlx;xlx (any odd number) xlx;xnxlx (any even number) x;xlxnxlx (any even number) x;xlxnxlx (any even number) xnxlxlx;x (none) xlxnxlx;x (any even number) xlxnxlx;x (any even number) xnxlx;xlx (any odd number) xlx;xnxlx (any even number) x;xlxnxlx (any even number) xnxlx;xlx (any odd number) xnxlx;xlx (any odd number) xlx;xlxnx (any odd number) xlx;xlxnx (any odd number) xnxlx;xlx (any odd number) xlx;xlxnx (any odd number) ``` That's 4 programs that cant output numbers, 20 that can output any even number, 16 that can output any odd number. Since there are exactly 20 even numbers and at least 16 odd numbers in the range 1 to 40, then with a certain probability there exists a possibility that there would be 36 different numbers in the range 1 to 40 output by this code block. [Answer] # GolfScript, 8 ``` 192 6#7 281 ``` ~~Currently the highest scoring solution. :P~~ Was nice while it lasted. ### Programs ``` 1927#6281 1927 192718#62 192718 19271826# 19271826 19#628172 19 16#927182 16 1628#9271 1628 16281729# 16281729 162817#92 162817 2916#7182 2916 291628#71 291628 29162817# 29162817 27#916281 27 2718#9162 2718 27182619# 27182619 #61927182 #72916281 #82619271 #81729162 261927#81 261927 28#619271 28 1826#7291 1826 26#817291 26 #62817291 271826#91 271826 281729#61 281729 1729#8261 1729 #92718261 29#718261 29 2817#6192 2817 17#826192 17 #71826192 182619#72 182619 2619#8172 2619 #91628172 28172916# 28172916 18261927# 18261927 17291628# 17291628 26192718# 26192718 18#729162 18 172916#82 172916 ``` [Answer] ## CJam, 14 ``` 3(4 ;]; 0)1 ``` Below the working programs: ``` 3(4;];0)1 = 11 3(4;1)0;] = 22 3(];0)1;4 = 14 3;0)](4;1 = 11 3;0)1;4(] = 13 3;0)1;](4 = 14 4(3;];1)0 = 20 4(3;0)];1 = 1 4(3;0)1;] = 31 4;1)](3;0 = 20 4;1)0;3(] = 22 0;3(4;])1 = 21 0)];3(4;1 = 21 1)0;];4(3 = 33 4;1)0;](3 = 23 0)1;4(];3 = 3 1;4(])0;3 = 33 4(];1)0;3 = 23 0)1;];3(4 = 24 1)0;3(];4 = 4 0;3(])1;4 = 24 0)1;4(3;] = 13 1)0;3(4;] = 22 1;4(3;0)] = 31 0;3(4;1)] = 22 1)];4(3;0 = 30 1;4(3;])0 = 30 ``` The values generated are: [1, 3, 4, 11, 13, 14, 20, 21, 22, 23, 24, 30, 31, 33] [Answer] # dc (20) ``` 2+3 *p+ 4+5 ``` ``` ABCFEDGHI -> 2+3+p*4+5 -> 5 $ ** ABCFIHEDG -> 2+3+5+p*4 -> 10 $ ** ABCFIHGDE -> 2+3+5+4*p -> 40 $ ** ABEDGHIFC -> 2+p*4+5+3 -> 2 $ ** ADEBCFIHG -> 2*p+3+5+4 -> 2 ** ADGHEBCFI -> 2*4+p+3+5 -> 6 $ ** ADGHIFCBE -> 2*4+5+3+p -> 14 $ ** ADGHIFEBC -> 2*4+5+p+3 -> 11 $ ** CBADEFIHG -> 3+2*p+5+4 -> 6 ** CBADGHEFI -> 3+2*4+p+5 -> 10 ** CBADGHIFE -> 3+2*4+5+p -> 15 $ ** CFEBADGHI -> 3+p+2*4+5 -> 3 $ ** CFIHEBADG -> 3+5+p+2*4 -> 8 $ ** CFIHGDABE -> 3+5+4*2+p -> 34 $ ** EDABCFIHG -> p*2+3+5+4 -> EFCBADGHI -> p+3+2*4+5 -> EHGDABCFI -> p+4*2+3+5 -> EHIFCBADG -> p+5+3+2*4 -> GDABCFEHI -> 4*2+3+p+5 -> 9 $ ** GHEDABCFI -> 4+p*2+3+5 -> 4 $ ** IHGDEFCBA -> 5+4*p+3+2 -> 20 $ ** GDEHIFCBA -> 4*p+5+3+2 -> 4 ** EDGHIFCBA -> p*4+5+3+2 -> CFIHGDEBA -> 3+5+4*p+2 -> 32 $ ** GHIFCBEDA -> 4+5+3+p*2 -> 12 $ ** IFCBEHGDA -> 5+3+p+4*2 -> 8 ** EBCFIHGDA -> p+3+5+4*2 -> CBEFIHGDA -> 3+p+5+4*2 -> 3 ** GHIFEDABC -> 4+5+p*2+3 -> 9 ** IFEHGDABC -> 5+p+4*2+3 -> 5 ** EFIHGDABC -> p+5+4*2+3 -> IHGDABEFC -> 5+4*2+p+3 -> 22 $ ** GDABEHIFC -> 4*2+p+5+3 -> 6 ** EBADGHIFC -> p+2*4+5+3 -> GHIFCBADE -> 4+5+3+2*p -> 24 $ ** IHGDABCFE -> 5+4*2+3+p -> 25 $ ** IFCBADGHE -> 5+3+2*4+p -> 20 ** GDABCFIHE -> 4*2+3+5+p -> 14 ** IHEFCBADG -> 5+p+3+2*4 -> 5 ** IFCBADEHG -> 5+3+2*p+4 -> 16 $ ** ``` 32 outputs, 20 of them distinct (marked with a `$`) 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 20, 22, 24, 25, 32, 34, 40 ]
[Question] [ **Challenge:** Take a vector / list of integers as input, and output the largest number that's adjacent to a zero. **Specifications:** * As always, optional input and output format * You may assume that there will be at least one zero, and at least one non-zero element. **Test cases:** ``` 1 4 3 6 0 3 7 0 7 9 4 9 0 9 0 9 15 -2 9 -4 -6 -2 0 -9 -2 -11 0 0 0 0 0 -12 10 0 0 20 20 ``` Good luck and happy golfing! [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` t~5BZ+g)X> ``` [Try it online!](http://matl.tryitonline.net/#code=dH41QlorZylYPg&input=Wy00IC02IC0yIDAgLTld) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0fjVCWitnKVg-CkRU&input=WzEgNCAzIDYgMCAzIDcgMF0KWzkgNCA5IDAgOSAwIDkgMTUgLTJdClstNCAtNiAtMiAwIC05XQpbLTExIDAgMCAwIDAgMCAtMTIgMTBdClswIDIwXQ). ### Explanation Let's take input `[-4 -6 -2 0 -9]` as an example. ``` t % Input array. Duplicate % STACK: [-4 -6 -2 0 -9], [-4 -6 -2 0 -9] ~ % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0 % STACK: [-4 -6 -2 0 -9], [0 0 0 1 0] 5B % Push logical array [1 0 1] (5 in binary) % STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1] Z+ % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of % zeros in the original array, and zero for the rest % STACK: [-4 -6 -2 0 -9], [0 0 1 0 1] g % Convert to logical % STACK: [-4 -6 -2 0 -9], [0 0 1 0 1] ) % Use as index into original array % STACK: [-2 -9] X> % Maximum of array. % STACK: -2 % Implicitly display ``` [Answer] # Haskell, ~~63~~ 43 bytes ``` f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0] ``` Thanks to @MartinEnder for 4 bytes! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes ``` ü‚D€P_ÏOZ ``` **Explanation** ``` ü‚ # pair up elements D # duplicate €P # product of each pair (0 if the pair contains a 0) _ # logical negate, turns 0 into 1 and everything else to 0 Ï # keep only the pairs containing at least 1 zero O # sum the pairs Z # take max ``` Doesn't work in the online interpreter, but works offline. [Answer] # Pyth, 12 11 10 bytes ``` eSsM/#0,Vt ``` Forms pairs, filters by zero member, sorts by sum, returns largest. [Answer] ## JavaScript (ES6), ~~59~~ ~~57~~ 56 bytes ``` let f = l=>l.map((n,i)=>m=l[i-1]==0|l[i+1]==0&&n>m?n:m,m=-1/0)|m console.log(f([1, 4, 3, 6, 0, 3, 7, 0])); // 7 console.log(f([9, 4, 9, 0, 9, 0, 9, 15, -2])); // 9 console.log(f([-4, -6, -2, 0, -9])); // -2 console.log(f([-11, 0, 0, 0, 0, 0, -12, 10])); // 0 console.log(f([3, 0, 5])); // 5 console.log(f([28, 0, 14, 0])); // 28 ``` *Edit: saved 2 bytes thanks to Huntro* *Edit: saved 1 byte thanks to ETHproductions* [Answer] ## JavaScript (ES6), 53 bytes ``` a=>(m=-1/0,a.reduce((l,r)=>(m=l*r||l+r<m?m:l+r,r)),m) ``` Because I like using `reduce`. Alternative solution, also 53 bytes: ``` a=>Math.max(...a.map((e,i)=>e*a[++i]==0?e+a[i]:-1/0)) ``` [Answer] # Python, 49 bytes ``` lambda a:max(sum(x)for x in zip(a,a[1:])if 0in x) ``` Tests are at **[ideone](http://ideone.com/bYp0HE)** Zips through the pairs, sums the ones containing any zero, returns the maximum. [Answer] ## Ruby, 51 bytes ``` ->a{a.each_cons(2).map{|a,b|a*b!=0?-1.0/0:a+b}.max} ``` ### usage ``` f=->a{a.each_cons(2).map{|a,b|a*b!=0?-1.0/0:a+b}.max} p f[gets.split.map(&:to_i)] ``` [Answer] # PHP, ~~77~~ ~~68~~ 71 bytes ~~-3 bytes from anonymous,~~ -4 and -2 from MartinEnder ``` preg_match_all("#(?<=\b0 )\S+|\S+(?= 0)#",$argv[1],$m);echo max($m[0]); ``` run with `php -r '<code>' '<space separated values>'` [Answer] # Java 7, ~~118~~ ~~105~~ 106 bytes ``` int d(int[]a){int i=0,m=1<<31,c;for(;++i<a.length;m=a[i]*a[i-1]==0&(c=a[i]+a[i-‌​1])>m?c:m);return m;} ``` 13 bytes saved thanks to *@cliffroot* by using an arithmetic approach instead. 1 additional byte thank to *@mrco* after he discovered a bug (the added test case `2, 1, 0` would return `2` instead of `1`). **Ungolfed & test code:** [Try it here.](https://ideone.com/rBqgMX) ``` class M{ static int c(int[] a){ int i, m = a[i=0], c; for(; ++i < a.length; m = a[i] * a[i-1] == 0 & (c = a[i] + a[i - 1]) > m) ? c : m); return m; } public static void main(String[] a){ System.out.println(c(new int[]{ 1, 4, 3, 6, 0, 3, 7, 0 })); System.out.println(c(new int[]{ 9, 4, 9, 0, 9, 0, 9, 15, -2 })); System.out.println(c(new int[]{ -4, -6, -2, 0, -9 })); System.out.println(c(new int[]{ -11, 0, 0, 0, 0, 0, -12, 10 })); System.out.println(c(new int[]{ 0, 20 })); System.out.println(c(new int[]{ 2, 1, 0 })); } } ``` **Output:** ``` 7 9 -2 0 20 1 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes ``` ṡ2ẠÐḟS€Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmhMuG6oMOQ4bifU-KCrOG5gA&input=&args=LTQsLTYsLTIsMCwtOSwx) ``` ṡ2 Overlapping pairs ẠÐḟ Remove pairs without zeroes S€ Sum of each pair Ṁ Maximum ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 16 bytes ``` q~2ew{0&},::+:e> ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4vezpROwoKUX4yZXd7MCZ9LDo6KzplPgoKXW59Lw&input=WzEgNCAzIDYgMCAzIDcgMF0KWzkgNCA5IDAgOSAwIDkgMTUgLTJdClstNCAtNiAtMiAwIC05XQpbLTExIDAgMCAwIDAgMCAtMTIgMTBd) (As a test suite.) ### Explanation ``` q~ e# Read and eval input. 2ew e# Get all (overlapping) pairs of adjacent values. {0&}, e# Keep only those that contain a 0. ::+ e# Sum each pair to get the other (usually non-zero) value. :e> e# Find the maximum. ``` [Answer] # MATLAB with Image Processing Toolbox, 32 bytes ``` @(x)max(x(imdilate(~x,[1 0 1]))) ``` This is an anonymous function. Example use for the test cases: ``` >> f = @(x)max(x(imdilate(~x,[1 0 1]))) f = function_handle with value: @(x)max(x(imdilate(~x,[1,0,1]))) >> f([1 4 3 6 0 3 7 0]) ans = 7 >> f([9 4 9 0 9 0 9 15 -2]) ans = 9 >> f([-4 -6 -2 0 -9]) ans = -2 >> f([-11 0 0 0 0 0 -12 10]) ans = 0 >> f([0 20]) ans = 20 ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` ⌈/∊2(+↑⍨0∊,)/⎕ ``` `⌈/` largest of `∊` the flattened ("**e**nlisted" `2(`...`)/` pairwise  `+` sum (zero plus something is something)  `↑⍨` taken if  `0` zero  `∊` is a member of  `,` the pair (lit. the concatenation of the left-hand number and the right-hand number) [TryAPL online!](http://tryapl.org/?a=f%u2190%7B%u2308/%u220A2%28+%u2191%u23680%u220A%2C%29/%u2375%7D%20%u22C4%20f%A8%281%204%203%206%200%203%207%200%29%289%204%209%200%209%200%209%2015%20%AF2%29%28%AF4%20%AF6%20%AF2%200%20%AF9%29%28%AF11%200%200%200%200%200%20%AF12%2010%29%280%2020%29&run) [Answer] ## R, 48 47 bytes EDIT: Fixed an error thanks to @Vlo and changed it to read input from stdins, saved one byte by assigning `w` and skipping parantheses. ``` function(v)sort(v[c(w<-which(v==0)-1,w+1)],T)[1] ``` ``` v=scan();w=which(v==0);sort(v[c(w-1,w+1)],T)[1] ``` ### Unnested explanation 1. Find indices for which the vector `v` takes on the values 0: `w <- which(v == 0)` 2. Create new vector which contains the indices `+-1`: `w-1` and `w+1` 3. Extract elements that match the indices `w-1` and `w+1` 4. Sort in descending order and extract fist element Note that if the last or first element of `v` is a zero, `w+-1` will effectively fetch an index outside of the length of the vector which implies that `v[length(v)+1]` returns `NA`. This is generally no problem but the `max()` functions inconveniently returns `NA` if there are any occurrences in the vector unless one specifies the option `na.rm=T`. Thus it is 2 bytes shorter to sort and extract first element than to use `max()`, e.g.: ``` max(x,na.rm=T) sort(x,T)[1] ``` [Answer] # Mathematica, ~~46~~ 43 bytes *Saved 3 bytes due to [@MartinEnder](http://ppcg.lol/users/8478).* ``` Max[Tr/@Partition[#,2,1]~Select~MemberQ@0]& ``` Anonymous function. Takes a list of integers as input and returns an integer as output. Based off of the Ruby solution. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` SfµƝṀ ``` [Try it online!](https://tio.run/##y0rNyan8/z847dDWY3Mf7mz4f7hdM/L//2hDHQUTHQVjHQUzHQUDMMMcyIjVUYi2BMtYgoXhpKGpjoKuEUhaFyipawbigeV0LcGChoZgHjLSNQSqMAQbCeQZGcQCAA "Jelly – Try It Online") *-1 remembering it's not a dyadic chain* ``` µƝ For each pair of adjacent elements, monadically: S Sum the pair, f and filter it to only element[s] in the pair. Ṁ Take the maximum. ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes ``` qᵗZđ+aṀ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmsKH26dHnVkonbiw50NS4qTkouhEgtuhkYb6pjoGOuY6RgASXMdg1iuaEugiCWQD8GGpjq6RkBRXRMdXTMgEyioawniGxoCmTCoa2ikYwjSbKBjZBALMR0A) ``` qᵗZđ+aṀ q Non-deterministically choose a contiguous subsequence ᵗZ Check that it contains a 0 đ Unpair; check that its length is 2, and push the two elements + Add a All possible values Ṁ Maximum ``` [Answer] # Perl, 42 bytes Includes +1 for `-p` Give the numbers on line on STDIN ``` largest0.pl <<< "8 4 0 0 5 1 2 6 9 0 6" ``` `largest0.pl`: ``` #!/usr/bin/perl -p ($_)=sort{$b-$a}/(?<=\b0 )\S+|\S+(?= 0)/g ``` [Answer] ## Julia, ~~56~~ 55 Bytes ``` f(l)=max(map(sum,filter(t->0 in t,zip(l,l[2:end])))...) ``` Create tuples for neighboring values, take those tuples containing 0, sum tuple values and find maximum [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 36 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.5 bytes ``` 2lƛ∑w↔ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHPSIsIiIsIjJsxpviiJF34oaUIiwiIiwiMSwgMCwgMSwgNywgMTAsIDAiXQ==) Porting Jelly is (still) always the best option ## Explained ``` zṠ↔G­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­ z # ‎⁡Overlapping pairs (equivalent to 2l) Ṡ # ‎⁢summed (vectorised) ↔ # ‎⁣with only items in the input kept. G # ‎⁤Get the biggest number in that list. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes ``` `/.|!$>>@:?$0+$] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWGxL09WoUVezsHKzsVQy0VWIhwlDZndFK0ZY6JjqWOgZQbGiqo2sUqxQLVQAA) Disgustingly long… ``` `/.|!$>>@:?$0+$] ! : Zip $ the input >> with the tail of @ the input | Filter by ?$0 containing a zero . Map +$ sum `/ ] Maximum ``` [Answer] # Python 2, 74 Bytes ``` def f(x):x=[9]+x;print max(x[i]for i in range(len(x)) if 0in x[i-1:i+2:2]) ``` Cycle through every element, if there's a `0` in the position of either the left or the right of the current element, include it in the generator, and then run it through `max`. We need to pad the list with some non-`0` number. It'll never be included because the slice `[-1:2:2]` won't include anything. [Answer] # T-SQL, 182 bytes **Golfed:** ``` DECLARE @x varchar(max)='1 5 4 3 6 1 3 17 1 -8 0 -7' DECLARE @a INT, @b INT, @ INT WHILE @x>''SELECT @a=@b,@b=LEFT(@x,z),@x=STUFF(@x,1,z,''),@=IIF(@a=0,IIF(@b<@,@,@b),IIF(@b<>0 or @>@a,@,@a))FROM(SELECT charindex(' ',@x+' ')z)z PRINT @ ``` **Ungolfed:** ``` DECLARE @x varchar(max)='1 5 4 3 6 1 3 17 1 -8 0 -7' DECLARE @a INT, @b INT, @ INT WHILE @x>'' SELECT @a=@b, @b=LEFT(@x,z), @x=STUFF(@x,1,z,''), @=IIF(@a=0,IIF(@b<@,@,@b),IIF(@b<>0 or @>@a,@,@a)) FROM(SELECT charindex(' ',@x+' ')z)z PRINT @ ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/542505/find-the-largest-number-thats-beside-a-zero)** [Answer] ## PowerShell v3+, 62 bytes ``` param($n)($n[(0..$n.count|?{0-in$n[$_-1],$n[$_+1]})]|sort)[-1] ``` A bit longer than the other answers, but a nifty approach. Takes input `$n`. Then loops through the indices `0..$n.count`, uses the `Where-Object` (`|?{...}`) to pull out those indices where the previous or next item in the array is `0`, and feeds those back into array slice `$n[...]`. We then `|sort` those elements, and take the biggest `[-1]`. ### Examples ``` PS C:\Tools\Scripts\golfing> @(1,4,3,6,0,3,7,0),@(9,4,9,0,9,0,9,15,-2),@(-4,-6,-2,0,-9),@(-11,0,0,0,0,0,-12,10)|%{""+$_+" --> "+(.\largest-number-beside-a-zero.ps1 $_)} 1 4 3 6 0 3 7 0 --> 7 9 4 9 0 9 0 9 15 -2 --> 9 -4 -6 -2 0 -9 --> -2 -11 0 0 0 0 0 -12 10 --> 0 PS C:\Tools\Scripts\golfing> @(0,20),@(20,0),@(0,7,20),@(7,0,20),@(7,0,6,20),@(20,0,6)|%{""+$_+" --> "+(.\largest-number-beside-a-zero.ps1 $_)} 0 20 --> 20 20 0 --> 20 0 7 20 --> 7 7 0 20 --> 20 7 0 6 20 --> 7 20 0 6 --> 20 ``` [Answer] # q, 38 bytes ``` {max x where 0 in'x,'(next x),'prev x} ``` [Answer] # J, 18 bytes ``` [:>./2(0&e.\#+/\)] ``` ## Explanation ``` [:>./2(0&e.\#+/\)] Input: array A ] Identity. Get A 2 The constant 2 ( ) Operate on 2 (LHS) and A (RHS) \ Get each subarray of size 2 from A and +/ Reduce it using addition \ Get each subarray of size 2 from A and 0&e. Test if 0 is a member of it # Filter for the sums where 0 is contained [:>./ Reduce using max and return ``` [Answer] # [Perl 6](https://perl6.org), 53 bytes ``` {max map ->$/ {$1 if !$0|!$2},(1,|@_,1).rotor(3=>-2)} ``` ## Expanded: ``` # bare block lambda with implicit signature of (*@_) { max map -> $/ { # pointy lambda with parameter 「$/」 # ( 「$0」 is the same as 「$/[0]」 ) $1 if !$0 | !$2 # return the middle value if either of the others is false }, ( 1, |@_, 1 ) # list of inputs, with added non-zero terminals .rotor( 3 => -2 ) # grab 3, back-up 2, repeat until less than 3 remain } ``` [Answer] # PHP, 66 bytes ``` foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m; ``` Pretty straightforward. Iterates over the input, and when a number is `0`, it sets `$m` to the highest number of the 2 adjacent numbers **and** any previous value of `$m`. Run like this (`-d` added for aesthetics only): ``` php -d error_reporting=30709 -r 'foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;' -- -4 -6 -2 0 -9;echo ``` [Answer] # SPSS Syntax (98 bytes) Golfed solution: ``` CRE L=lead(A,1). COMP R=MAX(lag(A),L). EXE. SEL IF A=0. EXE. AGG /S=MAX(R). LIST S /CAS=1. ``` Ungolfed: ``` CREATE L=lead(A,1). COMPUTE R=MAX(lag(A),L). EXECUTE. SELECT IF A=0. EXECUTE. AGGREGATE /S=MAX(R). LIST S /CASES=1. ``` Explanation: Input values is ordered vertically in a column. The first line of code creates a column with the lead number, the number before any given number. MAX(lag,A) returns the lagging number, the number after any given number (in test series A). So the second line of code creates a column with the highest number of neighbourging numbers of any given number. We are only interested in the neighbours of zeros, so the forth line selects all the rows with zeros, which now also include the highest valued neighbours. The 6th and 7th line of code finds the max value of selected neighbours. With data inputs: ``` * This syntax solves: Returning the greatest adjacent number bigger or equal to itself, for any number V. * CodeGolf asks for the solution for the case V=0. * Bytes=98. DATA LIST LIST / Sample (A7) a b c d e f g h i j k l m . BEGIN DATA. "A" 1, 4, 3, 6, 0, 3, 7, 0 "B" 9, 4, 9, 0, 9, 0, 9, 15, -2 "C" -4, -6, -2, 0, -9 "D" -11, 0, 0, 0, 0, 0, -12, 10 "E" 0, 20 END DATA. DATASET NAME Inputs WINDOW=FRONT. FLIP VARIABLES=a b c d e f g h i /NEWNAMES=Sample. DATASET NAME CodeGolf WINDOW=FRONT. DATASET CLOSE Inputs. CRE L=lead(A,1). COMP R=MAX(lag(A),L). EXE. SEL IF A=0. EXE. AGG /S=MAX(R). LIST S /CAS=1. ``` Just change the sample references (A to E) for testing each sample. ]
[Question] [ Given a *positive* integer as input, your task is to output a truthy value if the number is [divisible](https://en.wikipedia.org/wiki/Divisor) by the double of the sum of its digits, and a falsy value otherwise ([OEIS A134516](https://oeis.org/A134516)). In other words: ``` (sum_of_digits)*2 | number ``` * Instead of truthy / falsy values for the true and false cases, you may instead specify any finite set of values for the true/false case, and their complement the other values. For a simple example, you may use `0` for the true case and all other numbers for the false case (or vice versa, if you like). * Standard input and output rules apply. Default Loopholes also apply. * You can take input as an integer or as the string representation of that integer. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), hence the shortest code in bytes wins! * I am new to PPCG, so I would like you to post an explanation if it's possible. --- # Test Cases ``` Input - Output - (Reason) 80 - Truthy - (16 divides 80) 100 - Truthy - (2 divides 100) 60 - Truthy - (12 divides 60) 18 - Truthy - (18 divides 18) 12 - Truthy - (6 divides 12) 4 - Falsy - (8 does not divide 4) 8 - Falsy - (16 does not divide 8) 16 - Falsy - (14 does not divide 16) 21 - Falsy - (6 does not divide 21) 78 - Falsy - (30 does not divide 78) 110 - Falsy - (4 does not dide 110) 111 - Falsy - (6 does not divide 111) 390 - Falsy - (24 does not divide 390) ``` [Answer] ## JavaScript (ES6), ~~31~~ ~~29~~ 27 bytes Takes input as a string. Returns zero for truthy and non-zero for falsy. ``` n=>n%eval([...n+n].join`+`) ``` ### Commented ``` n => n % eval([...n + n].join`+`) n => // take input string n -> e.g. "80" n + n // double the input -> "8080" [... ] // split -> ["8", "0", "8", "0"] .join`+` // join with '+' -> "8+0+8+0" eval( ) // evaluate as JS -> 16 n % // compute n % result -> 80 % 16 -> 0 ``` ### Test cases ``` let f = n=>n%eval([...n+n].join`+`) console.log('[Truthy]'); console.log(f("80")) console.log(f("100")) console.log(f("60")) console.log(f("18")) console.log(f("12")) console.log('[Falsy]'); console.log(f("4")) console.log(f("8")) console.log(f("16")) console.log(f("21")) console.log(f("78")) console.log(f("110")) console.log(f("111")) console.log(f("390")) ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 3 [bytes](https://github.com/okx-code/Neim/wiki/Code-Page) ``` 𝐬ᚫ𝕞 ``` Explanation: ``` 𝐬 Implicitly convert to int array and sum the digits ᚫ Double 𝕞 Is it a divisor of the input? ``` [Try it online!](https://tio.run/##ARUA6v9uZWlt///wnZCs4Zqr8J2Vnv//MTY "Neim – Try It Online") [Detailed version](https://tio.run/##y0vNzP3//8PcCWsezlr9Ye7Uef/PzQvWUEjJLMtMSS1W0HQKhsopg0TzgUJ5@SVQaSTZ/4ZmAA "Neim – Try It Online") [Answer] # C#, 46 bytes ``` using System.Linq;n=>n%(n+"").Sum(c=>c-48)*2<1 ``` Full/Formatted version: ``` using System; using System.Linq; class P { static void Main() { Func<int, bool> f = n => n % (n + "").Sum(c => c - 48) * 2 < 1; Console.WriteLine(f(80)); Console.WriteLine(f(100)); Console.WriteLine(f(60)); Console.WriteLine(); Console.WriteLine(f(16)); Console.WriteLine(f(78)); Console.WriteLine(f(390)); Console.ReadLine(); } } ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~38~~ 27 bytes -11 bytes and fixed an error with the code thanks to @MartinEnder ``` $ $_¶$_ .+$|. $* ^(.+)¶\1+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4VLJf7QNpV4Lj1tlRo9LhUtrjgNPW3NQ9tiDLVV/v@3MOAyNDDgMgNSZlzmFlzGlkCWIRBbAAA "Retina – Try It Online") Prints 1 if divisible, 0 otherwise ### Explanation (hope I got this right) ``` $ $_¶$_ ``` Appends the entire input, plus a newline, plus the input again ``` .+$|. $* ``` Converts each match to unary (either the entire second line which is the original input, or each digit in the first line) ``` ^(.+)¶\1+$ ``` Check if the first line (the doubled digit sum) is a divisor of the second line [Answer] # x86-64 Machine Code, 24 bytes ``` 6A 0A 5E 31 C9 89 F8 99 F7 F6 01 D1 85 C0 75 F7 8D 04 09 99 F7 F7 92 C3 ``` The above code defines a function in 64-bit x86 machine code that determines whether the input value is divisible by double the sum of its digits. The function conforms to the System V AMD64 calling convention, so that it is callable from virtually any language, just as if it were a C function. It takes a single parameter as input via the `EDI` register, as per the calling convention, which is the integer to test. (This is assumed to be a *positive* integer, consistent with the challenge rules, and is required for the `CDQ` instruction we use to work correctly.) It returns its result in the `EAX` register, again, as per the calling convention. The result will be 0 if the input value *was* divisible by the sum of its digits, and non-zero otherwise. (Basically, an inverse Boolean, exactly like the example given in the challenge rules.) Its C prototype would be: ``` int DivisibleByDoubleSumOfDigits(int value); ``` Here are the ungolfed assembly language instructions, annotated with a brief explanation of the purpose of each instruction: ``` ; EDI == input value DivisibleByDoubleSumOfDigits: push 10 pop rsi ; ESI <= 10 xor ecx, ecx ; ECX <= 0 mov eax, edi ; EAX <= EDI (make copy of input) SumDigits: cdq ; EDX <= 0 div esi ; EDX:EAX / 10 add ecx, edx ; ECX += remainder (EDX) test eax, eax jnz SumDigits ; loop while EAX != 0 lea eax, [rcx+rcx] ; EAX <= (ECX * 2) cdq ; EDX <= 0 div edi ; EDX:EAX / input xchg edx, eax ; put remainder (EDX) in EAX ret ; return, with result in EAX ``` In the first block, we do some preliminary initialization of registers: * `PUSH`+`POP` instructions are used as a slow but short way to initialize `ESI` to 10. This is necessary because the `DIV` instruction on x86 requires a register operand. (There is no form that divides by an immediate value of, say, 10.) * `XOR` is used as a short and fast way to clear the `ECX` register. This register will serve as the "accumulator" inside of the upcoming loop. * Finally, a copy of the input value (from `EDI`) is made, and stored in `EAX`, which will be clobbered as we go through the loop. Then, we start looping and summing the digits in the input value. This is based on the x86 `DIV` instruction, which divides `EDX:EAX` by its operand, and returns the quotient in `EAX` and the remainder in `EDX`. What we'll do here is divide the input value by 10, such that the remainder is the digit in the last place (which we'll add to our accumulator register, `ECX`), and the quotient is the remaining digits. * The `CDQ` instruction is a short way of setting `EDX` to 0. It actually *sign-extends* the value in `EAX` to `EDX:EAX`, which is what `DIV` uses as the dividend. We don't actually need sign-extension here, because the input value is unsigned, but `CDQ` is 1 byte, as opposed to using `XOR` to clear `EDX`, which would be 2 bytes. * Then we `DIV`ide `EDX:EAX` by `ESI` (10). * The remainder (`EDX`) is added to the accumulator (`ECX`). * The `EAX` register (the quotient) is tested to see if it is equal to 0. If so, we have made it through all of the digits and we fall through. If not, we still have more digits to sum, so we go back to the top of the loop. Finally, after the loop is finished, we implement `number % ((sum_of_digits)*2)`: * The `LEA` instruction is used as a short way to multiply `ECX` by 2 (or, equivalently, add `ECX` to itself), and store the result in a different register (in this case, `EAX`). (We could also have done `add ecx, ecx`+`xchg ecx, eax`; both are 3 bytes, but the `LEA` instruction is faster and more typical.) * Then, we do a `CDQ` again to prepare for division. Because `EAX` will be positive (i.e., unsigned), this has the effect of zeroing `EDX`, just as before. * Next is the division, this time dividing `EDX:EAX` by the input value (an unmolested copy of which still resides in `EDI`). This is equivalent to modulo, with the remainder in `EDX`. (The quotient is also put in `EAX`, but we don't need it.) * Finally, we `XCHG` (exchange) the contents of `EAX` and `EDX`. Normally, you would do a `MOV` here, but `XCHG` is only 1 byte (albeit slower). Because `EDX` contains the remainder after the division, it will be 0 if the value was evenly divisible or non-zero otherwise. Thus, when we `RET`urn, `EAX` (the result) is 0 if the input value was divisible by double the sum of its digits, or non-zero otherwise. Hopefully that suffices for an explanation. This isn't the shortest entry, but hey, it looks like it beats almost all of the non-golfing languages! :-) [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` tV!UsE\ ``` Outputs `0` if divisible, positive integer otherwise. Specifically, it outputs the remainder of dividing the number by twice the sum of its digits. [**Try it online!**](https://tio.run/##y00syfmf8L8kTDG02DXmv0vIfwsDLkMDAy4zIGXBZWjEZcIFpMy4jAy5zIEMQ6CwoSGXsaUBAA "MATL – Try It Online") ### Explanation ``` t % Implicit input. Duplicate V!U % Convert to string, transpose, convert to number: gives column vector of digits s % Sum E % Times 2 \ % Modulus. Implicit display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes -1 byte thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx) ``` SO·Ö ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2P/Q9sPT/v@3MAAA "05AB1E – Try It Online") You can also remove the last Ö to get 0 for truthy and something else for falsy resulting in only 3 bytes but to me that just doesn't seem to appropriately fit the definition. ### Explanation ``` SO·Ö SO # Separate the digits and sum them · # Multiply the result by two Ö # Is the input divisible by the result? ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~15~~ 14 bytes ``` {(2*+/10\x)!x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlrDSEtb39AgpkJTsaL2f5qChcF/AA "K (ngn/k) – Try It Online") --- 0 is truthy [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~7~~ 4 bytes Takes input as a string. Outputs `0` for `true` or a number greater than `0` for `false`, which, from other solutions, would appear to be valid. If not, let me know and I'll rollback. ``` %²¬x ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=JbKseA==&input=IjM5MCI=) --- ## Explanation Implicit input of string `U`. `"390"` ``` ² ``` Repeat `U` twice. `"390390"` ``` ¬ ``` Split to array of individual characters. `["3","9","0","3","9","0"]` ``` x ``` Reduce by summing, automatically casting each character to an integer in the process. `24` ``` % ``` Get the remainder of dividing `U` by the result, also automatically casting `U` to an integer in the process. Implicitly output the resulting integer. `6 (=false)` [Answer] # C89, 55 53 bytes (Thanks to Steadybox! ``` s,t;f(x){for(t=x,s=0;t;t/=10)s+=t%10;return x%(s*2);} ``` It takes a single input, `x`, which is the value to test. It returns 0 if `x` is evenly divisible by double the sum of its digits, or non-zero otherwise. [Try it online!](https://tio.run/##jdLNTsMwDAfwc/MUVlGlBArEYeoKITtx5gl6gX5ApJFOjTtVmvbspc2QuAVOvvzkvx2nvv2o63n2OemOT@LU9QMnM@XeSE2a7g1K4W8MZSj10NI4OJgy7q@V0Of5yrp6PzYtPHtqbH/3uWPMOoKvN@v4sbeNYCcGAMlhJM/TF3u03r7v26dUaJYchsV2PM2aisyuoqW6NAcoZQ4dL6WIIJQBLSWmoAiqiCMsQ6syjlRAakW/G1XutSf4516wWVtsojEQZvljlCKMUkSRwhUpjKJtSNtG4xAvL43xeyBeVDTw4TH0WsqqWPLzoaRm5/kb "C (gcc) – Try It Online") **Ungolfed:** ``` /* int */ s, t; /*int */ f(/* int */ x) { for (t = x, s = 0; t /* != 0 */; t /= 10) s += (t % 10); return x % (s * 2); } ``` As you can see, this takes advantage of C89's implicit-int rules. The global variables `s` and `t` are implicitly declared as `int`s. (They're also implicitly initialized to 0 because they are globals, but we can't take advantage of this if we want the function to be callable multiple times.) Similarly, the function, `f`, takes a single parameter, `x,` which is implicitly an `int`, and it returns an `int`. The code inside of the function is fairly straightforward, although the `for` loop will look awfully strange if you're unfamiliar with the syntax. Basically, a `for` loop header in C contains three parts: ``` for (initialization; loop condition; increment) ``` In the "initialization" section, we've initialized our global variables. This will run once, before the loop is entered. In the "loop condition" section, we've specified on what condition the loop should continue. This much should be obvious. In the "increment" section, we've basically put arbitrary code, since this will run at the end of every loop. The larger purpose of the loop is to iterate through each digit in the input value, adding them to `s`. Finally, after the loop has finished, `s` is doubled and taken modulo `x` to see if it is evenly divisible. (A better, more detailed explanation of the logic here can be found in [my other answer](https://codegolf.stackexchange.com/a/129740/58518), on which this one is based.) **Human-readable version:** ``` int f(int x) { int temp = x; int sum = 0; while (temp > 0) { sum += temp % 10; temp /= 10; } return x % (sum * 2); } ``` [Answer] # APL, 13 bytes ``` {⍵|⍨2×+/⍎¨⍕⍵} ``` Outputs `0` as a truthy value, and any other as falsy. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ẹ+×₂;I×? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GundqHpz9qarL2PDzd/v9/Q7P/AA "Brachylog – Try It Online") ### Explanation ``` ẹ+ Sum the digits ×₂ Double ;I×? There is an integer I such that I×(double of the sum) = Input ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~34~~ 32 bytes *-2 bytes thanks to @Rod* ``` lambda n:n%sum(map(int,`n`)*2)<1 ``` [Try it online!](https://tio.run/##FctBCsIwEEbhvaf4N9JERkkr1FqqF1GhEQkONNNQ04WUnj3GzeNtvvCN71Gq5C73NFj/fFlIK9vP7JW3QbFE6qXXu0p3ZXLjBAYLbo0hlCan/k9NODWE49k82g0QpsxQLCv2VyxrccjO26iY4BRrnX4 "Python 2 – Try It Online") [Answer] ## Mathematica, 26 bytes ``` (2Tr@IntegerDigits@#)∣#& ``` No clue why `∣` has a higher precedence than multiplication... [Answer] # [PHP](https://php.net/), 41 bytes prints zero if divisible, positive integer otherwise. ``` <?=$argn%(2*array_sum(str_split($argn))); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaKBkzWVvBxS0BYuoahhpJRYVJVbGF5fmahSXFMUXF@RklmiAJTU1Na3//wcA "PHP – Try It Online") [Answer] # Excel, 63 bytes ``` =MOD(A1,2*SUMPRODUCT(--MID(A1,ROW(OFFSET(A$1,,,LEN(A1))),1)))=0 ``` Summing digits is the lengthy bit. [Answer] # [Perl 6](http://perl6.org/), 19 bytes ``` {$_%%(2*.comb.sum)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiVeVVXDSEsvOT83Sa@4NFez9r@1QnFipUJ6UWoBUI2OQpyhgcF/AA "Perl 6 – Try It Online") [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes *Thanks to Leo for saving 1 byte.* ``` Ṡ¦ȯ*2ṁis ``` [Try it online!](https://tio.run/##yygtzv6vkPuoqfH/w50LDi07sV7L6OHOxszi////Rxsa6Rha6JgZ6FgY6BgaGOiY6FjoGJrpGBnqmAMZhkBBQ0MdY0uDWAA "Husk – Try It Online") ### Explanation ``` Ṡ¦ȯ Test whether f(x) divides x, where f is the function obtained by composing the next 4 functions. s Convert x to a string. ṁi Convert each character to an integer and sum the result. *2 Double the result. ``` [Answer] ## [Haskell](https://www.haskell.org/), ~~38~~ ~~37~~ 42 bytes *Thanks to Zgarb for golfing off 1 byte* ``` f x=read x`mod`foldr((+).(*2).read.pure)0x ``` [Try it online!](https://tio.run/##dcyxDoMgAATQ3a@4EAeQlGgHZbHfIgkQTVEMasrfU12c8Ma7lxvV9jXOpWQR@2CURhxmrwfrnQ6UciZo9WbiWsR6BMPqmGY1LeihPdYwLTtKEFnj9QEB56Db6H9nZ6@WsAJ3bt3InG7kg26zus3rLvvdnd/pDw "Haskell – Try It Online") Takes input as a string; returns 0 if divisible and nonzero otherwise. [Answer] ## Python 3, 35 bytes ``` lambda a:a%(sum(map(int,str(a)))*2) ``` [Answer] # TI-BASIC, ~~27~~ ~~26~~ 21 [bytes](http://tibasicdev.wikidot.com/one-byte-tokens) -5 thanks to [@Oki](https://codegolf.stackexchange.com/users/60026/oki) ``` :fPart(Ans/sum(2int(10fPart(Ans10^(~randIntNoRep(1,1+int(log(Ans ``` This is made trickier by the fact that there is no concise way to sum integer digits in **TI-BASIC**. Returns `0` for `True`, and a different number for `False`. Explanation: ``` :fPart(Ans/sum(2int(10fPart(Ans10^(-randIntNoRep(1,1+int(log(Ans 10^(-randIntNoRep(1,1+int(log(Ans #Create a list of negative powers of ten, based off the length of the input, i.e. {1,0.1,0.01} Ans #Scalar multiply the input into the list 10fPart( #Remove everything left of the decimal point and multiply by 10 2int( #Remove everything right of the decimal point and multiply by 2 sum( #Sum the resulting list Ans/ #Divide the input by the sum :fPart( #Remove everything left of the decimal, implicit print ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 40 bytes ``` i->i%(i+"").chars().map(k->k*2-96).sum() ``` [Try it online!](https://tio.run/##pY9NT8MwDIbv@xXWJKQE2qgtqGxD7MaBA@JQcUIcTNZu6UcSJe6kCe23lwQ2ThyQeKU4r53Yj9ziHlNja91uusmO772SIHv0Hp5QafiYQdCp7gkpXHujNjCEV1aRU3r7@gbotp6fPke1YaoYSfWiGbUkZbR41PSi0R2ebe2QjAML95NK1@qCqav5nAu5Q@cZFwNa1qXr7rJIlyUXfhwYn86D735BeHI1DhFQfTvTsEWWQJ6FUEazCKfgP61nfaEsF41xDyh3rDp4qkP7SKuVDZtRr/lfgTcJREqZQJEncBt9HtF5yK6X2X/gx9lx@gQ "Java (OpenJDK 8) – Try It Online") Returns 0 as truthy value and a value greater than 0 as falsy value. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 11 bytes ``` L,EDEs;A@%! ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx9XFtdja0UFV8f///4YWAA "Add++ – Try It Online") First time I've used either a `L`ambda or `;` in an Add++ answer ## How it works ``` L, - Create a lambda function. Example argument; 172 ED - Push the digits; STACK = [[1 7 2]] Es - Stack-clean sum; STACK = [10] ; - Double; STACK = [20] A - Push the argument; STACK = [20 172] @% - Modulo; STACK = [12] ! - Logical NOT; STACK = [0] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes ``` ¦DΣd¹ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@hZS7nFqcc2vn///9oCwMdQwMDHTMgZaFjaKRjogOkzHSMDHXMgQxDoLChoY6xpUEsAA "Husk – Try It Online") -1 byte from Dominic Van Essen. The existing answer doesn't use enough builtins, and Martin Ender is inactive, so I decided to post this. [Answer] # [Zsh](https://www.zsh.org/), 37 bytes ``` for ((;i++<19;a+=2*s[i]))s=$1;((s%a)) ``` [Try it online!](https://tio.run/##DYi9CsMgEID3e4obLNzVxbMlTThDH6R0EKJEKA3EIaEvb52@n19dWyamlrcdibRYG2TSaGd/ra/yZq6zESWql8jcGI61fBLuKS546rJhRnNqCME8e31TGx2IczB0jCAe7tAxgBd4dJG@ReA2ufYH "Zsh – Try It Online") Outputs by exit code - 0 is falsey, 1 is truthy. Explanation: ``` for ((;i++<19;a+=2*s[i]))s=$1;((s%a)) # i implicitly starts at 0 s=$1; # set s to the input for ((; )) # loop <19; # while i is less than 19 (*) i++ # increment i s[i] # take the i'th character of s 2* # doubled a+= # add to a s%a # remainder of s divided by a (( )) # output 0 if it's non-zero, 1 if it's zero ``` *(\*19 is the length of the maximum integer zsh can handle)* [Answer] # Swift, ~~53~~ 46 bytes Takes in a `String` or [`Substring`](https://developer.apple.com/documentation/swift/substring) representing an integer in [1, 255]. ``` {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1} ``` [Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQZqWgEVxSlJmXrqmga6fglJ@fo2D7vzrUM6/EQkPFQFNRFUjqlZakWegVpaaUJqdqGGhWqxhoqxjqmljUahlp2hjW/k/LL1LIVMjMUzDU09MzMjVVqOZSAIICoLElGkoxGpmaVgoxGmlQi4BcTU0lTa7a/wA) Type information not included, since it could be either: ``` let f: (String) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1} let g: (Substring) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1} ``` Swift [`Character`](https://developer.apple.com/documentation/swift/character) is... weird. It's not a single byte, like in C (that's [`CChar`](https://developer.apple.com/documentation/swift/cchar)), but it's also not a single Unicode codepoint (that's [`Unicode.Scalar`](https://developer.apple.com/documentation/swift/unicode/scalar)). Rather, it represents an [extended grapheme cluster](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries). This makes certain oprations substantially more painful, but others substantially easier. For this reason, I access the string's `utf8` property (which is a collection of `UInt8`). `String` and `Substring` are collections of `Character`; however, they also have a lot more shared functionality than e.g. `[Character]` because they conform to [`StringProtocol`](https://developer.apple.com/documentation/swift/stringprotocol), and are in fact the only types that conform to it. I thought `StringProtocol` would work as the input type, but then the type checker times out. For 49 bytes, here's a version that accepts integers in [1, 2^31 - 1] or [1, 2^63 - 1] depending on the machine: ``` {Int($0)!%($0.utf8.reduce(0){$0+Int($1)-48}*2)<1} ``` ### Explanation/Ungolfed ``` { (number: String) -> Bool in return UInt8(number)! // Convert String to UInt8, force-unwrap optional % ( number.utf8 // Convert String to byte array .reduce(0) { (prevResult: UInt8, nextChar: Character) -> UInt8 in return prevResult + nextChar - 48 // Convert ASCII to number by subtracting 48; sum the results } * 2 ) == 0 // convert number to boolean } ``` [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), ~~13~~ 12 bytes ``` VR.Mvd&+2*c% ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/LEjPtyxFTdtIK1k17////xYGAA "Braingolf – Try It Online") Outputs 0 for truthy, any other number for falsey. ## Explanation ``` VR.Mvd&+2*c% Implicit input from command-line args VR Create stack2, return to stack1 .M Duplicate input to stack2 vd Switch to stack2, split into digits &+ Sum up all digits 2* Double c Collapse stack2 back into stack1 % Modulus Implicit output of last item on stack ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` vUì x*2 ``` Returns `1` for `true`, `0` for `false` [Try it online!](https://tio.run/##y0osKPn/vyz08BqFCi2j//8NDQwA "Japt – Try It Online") ## Explanation ``` vUì x*2 v // Return 1 if the input is divisible by: Uì // Input split into a base-10 array x // Sum the array *2 // While mapped by *2 ``` [Answer] # [Haskell](https://www.haskell.org/), 49 Bytes ``` f x=(==) 0.mod x.(*)2.sum.map(read.return).show$x ``` **Usage** ``` f 80 ``` [Try it online!](https://tio.run/##ZcohDoAgGAbQ7im@YADDPySohcOwAZMp4EAnt8eO9e3tuhz2PFtzqIopxSEoJINKbOKSyhMo6Itlqw1lez85cip7esfagvYRCiYNwJV9vEFwGLEJdDKLHy3/tPQi517WDUP7AA) [Answer] # [Java](http://openjdk.java.net/), 66 bytes -1 byte thanks to Olivier ``` a->{int i=0;for(int b:(""+a).getBytes())i+=b-48;return a%(i*2)<1;} ``` Ungolfed & explanation: ``` a -> { int i = 0; for(int b : (""+a).getBytes()) { // Loop through each byte of the input converted to a string i += b-48; // Subtract 48 from the byte and add it to i } return a % (i*2) < 1 // Check if a % (i*2) is equal to one // I use <1 here for golfing, as the result of a modulus operation should never be less than 0 } ``` ]
[Question] [ In this challenge you are going to write an interpreter for a simple language I've made up. The language is based on a single accumulator A, which is exactly one byte in length. At the start of a program, A = 0. These are the languages instructions: ## `!`: Inversion This instruction simply inverts every bit of the accumulator. Every zero becomes a one and every one becomes a zero. Simple! ## `>`: Shift Right This instruction shifts every bit in A one place to the right. The leftmost bit becomes a zero and the rightmost bit is discarded. ## `<`: Shift Left This instruction shifts every bit in A one place to the left. The rightmost bit becomes a zero and the leftmost bit is discarded. ## `@`: Swap Nybbles This instruction swaps the top four bits of A with the bottom four bits. For example, If A is `01101010` and you execute `@`, A will be `10100110`: ``` ____________________ | | 0110 1010 1010 0110 |_______| ``` That's all the instructions! Simple, right? # Rules * Your program must accept input *once* at the beginning. This will be a line of code. This is *not* an interactive interpreter! You can only accept input once and do not have to loop back to the start once that line has been executed. * Your program must evaluate said input. Every character that is not mentioned above is ignored. * Your program should then print out the final value of the accumulator, in decimal. * Usual rules for valid programming languages apply. * Standard loopholes are disallowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), smallest byte count wins. Here are some small programs to test out your submissions. Before the arrow is the code, after it is the expected result: * `!` -> `255` * `!>>` -> `63` * `!<@` -> `239` * `!nop!&6*!` -> `255` Enjoy! [Answer] # Pyth, ~~36~~ 35 bytes ``` u%@[t_G/G2yGi_jGJ16JG)x"!><@"H256z0 ``` [Test harness](https://pyth.herokuapp.com/?code=u%25%40%5Bt_G%2FG2yGi_jGJ16JG%29x%22%21%3E%3C%40%22H256z0&test_suite=1&test_suite_input=%21%0A%21%3E%3E%0A%21%3C%40%0A%21%3C%26&debug=0) The internal representation of the accumulator is an integer. This integer is mod-ed by 256 on each iteration, as desired. The operations performed are `-G-1`, `G/2`, `G*2` and `G` converted to base 16, reversed, and converted back to base 10, where `G` is the accumulator. I missed the line about ignoring everything else. This has been remedied. Thanks, @Dennis. [Answer] # C, 96 Assuming ASCII (or compatible) input: ``` a;main(c){while(c=getchar()+1)a=(c^34?c^61?c^63?c^65?a:a*257/16:a/2:a*2:~a)&255;printf("%u",a);} ``` **Tidier:** ``` a; main(c){ while(c=getchar()+1) a=(c^34? c^61? c^63? c^65? a : a*257/16 : a/2 :a*2:~a )&255; printf("%u",a); } ``` Basically it's just a collection of nested ternary expressions. I'm incrementing the value obtained from `getchar()` so that an EOF (-1) results in a value of zero and the program exits. [**(ideone link)**](http://ideone.com/x3geGw) [Answer] # Python 3, 133 bytes Uses a dictionary to make up for a lack of switch-case syntax in Python. [See more here](http://www.pydanny.com/why-doesnt-python-have-switch-case.html). ``` a="0"*8 for i in input():a={"!":''.join(str(1-int(b))for b in a),"<":a[1:]+"0",">":"0"+a[:-1],"@":a[4:]+a[:4]}.get(i,a) print(int(a,2)) ``` The accumulator is a string which is converted into a base 10 number at the end. ### Example I/O: ``` $ python3 bitsnbytes.py ! 255 $ python3 bitsnbytes.py !>> 63 $ python3 bitsnbytes.py !<@ 239 $ python3 bitsnbytes.py !nop!&6*! 255 ``` [Answer] # Javascript (ES6), ~~80~~ ~~91~~ 90 bytes ``` a=>[...a].reduce((p,c)=>c=='!'?p^255:c=='<'?p*2%256:c=='>'?p>>1:c=='@'?p/16|0+p%16*16:p,0) ``` Pretty much as short as it can get. Defines an anonymous function which takes the program as input. * For `!`, takes `x XOR 255`, as JS's `~` would consider `x` a 32-bit number. * For `<`, multiplies `x` by 2 and takes the result mod 256. * For `>`, truly shifts the bits of `x` 1 bit to the right. * For `@`, floors `x/16` and adds it to `x%16*16`. Thanks to @vihan for suggesting the use of `reduce` to save a byte. [Answer] # CJam, 37 bytes ``` 0q{"!><@"#"~ 2/ 2* GmdG*+ "S/=~255&}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0q%7B%22!%3E%3C%40%22%23%22~%202%2F%202*%20GmdG*%2B%20%22S%2F%3D~255%26%7D%2F&input=!%3C%40). ### How it works ``` 0 e# Push 0 (accumulator). q e# Read from STDIN. { e# For each character in the input: "!><@"# e# Find its index in "!><@" (-1 if not found). "~ 2/ 2* GmdG*+ " e# Push that string. S/ e# Split at spaces to push ["~" "2/" "2*" "GmdG*+" ""]. e# "~" : signed 64-bit bitwise NOT e# "2/" : divide by 2 e# "2*" : multiply by 2 e# "GmdG*+" : (x) -> (x/16) (x%16) -> (16(x%16) + (x/16)) e# "" : NOOP =~ e# Select the corresponding string and evaluate it. 255& e# Zero all but the 8 least significant bits. }/ e# ``` [Answer] # Java (8), ~~514~~ ~~483~~ ~~411~~ ~~366~~ ~~359~~ ~~239~~ ~~224~~ ~~229~~ ~~198~~ ~~194~~ ~~187~~ ~~186~~ ~~184~~ ~~182~~ ~~181~~ ~~180~~ 177 characters Wow, this has been golfed down a LOT! Thanks to everyone who gave me suggestions! I greatly appreciate it! ``` interface T{static void main(String[]g)throws Exception{int i,a=0;while((i=System.in.read())!=10)a=(i==33?255-a:i==62?a/2:i==60?a*2:i==64?a>>4|a<<4:a)%256;System.out.print(a);}} ``` Golfed 31 (!) bytes by optimizing the nibble swap with bitwise operations as opposed to lengthy `Integer.???` methods. Golfed 72 (!!!!) chars by removing the unnecessary string created to swap nibbles. Much better than before!? Golfed 45 (!!) chars by removing use of `java.util.Scanner` and reading from `System.in` directly. Note that now that the lambda expression is gone, Java 8 is no longer required! Just merely Java 1 would do! Golfed 7 chars by making class `(default)` (removed `public` keyword), thanks to @bmarks Golfed 120 (!!!!!!!) chars by turning all those lengthy `Integer` class operations in the bit flipping to `255 - a`. Now that's much shorter! Golfed 15 (!) chars by converting shifts to multiplication and division, removing the braces from the while statement, and making `a` local within the `main` method. Ungolfed 9 =( chars because of a problem with the left shift not discarding the leftmost byte. Therefore, I now do `mod (256)`. The right shift will make the resulting number one bit shorter than before, so there is no need to use `mod` on right shift. My nibble-swap thing will swap the last 4 bits and the second-last nibble, and the `and (&)` truncates all other bits. My inversion program doesn't cause any problems if the original number is less than 256. Golfed ~~31~~ 35 chars thanks to @Geobits by converting `switch` statement to a lot of ternary statements, and also converting chars to ints, shortening the literals. Golfed 7 chars by removing unnecessary `&240` in the nibble swap (`(a&240)>>4` to `a>>4` and converting `(a&15)<<4` to `a<<4&240`. The last change only golfed one character though. Golfed 1 char by removing unnecessary `=` in `a /= 2`, because `a = a /= 2` is equivalent to `a = a / 2`. Golfed 2 chars by turning `println` to `print`. Golfed 2 chars by removing accidental `a=` in `a=255-a` (`a=a=255-a` is equivalent to `a=255-a`) Golfed 1 char by turning `a<<4&240` into `a%16<<4`. Golfed 1 char by adding brackets to the outside of the ternary statement and doing `%256`. That way, the `%16` is unnecessary in the left-shift part of the nibble swap. The brackets add 2 chars and the `%16` saves 3 chars. Golfed 3 chars by changing `class` to `interface` and removing `public` using Java 8's static interface method feature. Thanks to @TheNumberOne (no comment, but find his answer on "Tips for golfing in Java" [Answer] ## Rust, ~~121~~ 115 bytes ``` fn r(s:&str)->u8{let mut n=0u8;for t in s.chars(){match t{'!'=>n=!n,'>'=>n/=2,'<'=>n<<=1,'@'=>n=n>>4|n<<4,_=>()}}n} ``` Sample run: ``` fn main() { println!("{}", r("!")); //=> 255 println!("{}", r("!>>")); //=> 63 println!("{}", r("!<@")); //=> 239 } ``` Ungolfed: ``` fn run_ungolfed(s: &str) -> u8 { let mut n = 0u8; for t in s.chars() { match t { '!' => n = !n, '>' => n >>= 1, '<' => n <<= 1, '@' => n = (n >> 4) | (n & 15) << 4, _ => () } } n } ``` Surprisingly short for Rust. Nothing else really interesting other than the fact that [I learned more precedence rules today](https://doc.rust-lang.org/reference.html#operator-precedence)—who knew `(a>>b)|c` is the same as `a>>b|c`? Shaved off a byte by changing `n>>=1` to `n/=2`; however, the same cannot be done with multiplication, because arithmetic overflow is a panic (i.e. crash) in Rust. [Answer] # HP 41C/CV/CX (77 bytes, 42 steps) Purely for giggles, here it is for the HP 41C/CV/CX calculator. (Requires either the Extended Functions module, or a 41CX for the ATOX function.) Put your program into the Alpha register, which is a little tricky, as there's no way to enter ! or @ directly from the keyboard (use XTOA with the ASCII codes 33 and 64 respectively to append them). Steps 08 and 10 allow for ignoring invalid opcodes; remove them to save 2 steps, but the program will crash on invalid input. ``` 01 LBL"BB 02 0 03 LBL A 04 ATOX 05 X=0? 06 GTO E 07 X<>Y 08 SF 25 09 XEQ IND Y 10 CF 25 11 GTO A 12 LBL 33 13 255 14 X<>Y 15 - 16 RTN 17 LBL 60 18 2 19 * 20 256 21 MOD 22 RTN 23 LBL 62 24 2 25 / 26 INT 27 RTN 28 LBL 64 29 RCL X 30 16 31 / 32 INT 33 X<>Y 34 16 35 * 36 256 37 MOD 38 + 39 RTN 40 LBL E 41 RDN 42 RTN ``` [Answer] # Python 2, 79 bytes I realized that I have done something [very similar](https://codegolf.stackexchange.com/a/8747/4372) to this in Python earlier. This is just a port of [my Ruby answer](https://codegolf.stackexchange.com/a/57224/4372), but it is incidentally the shortest Python answer as of now :D ``` a=0 for i in raw_input():a=[~a,a/2,a*2,a*16+a/16,a]["!><@".find(i)]&255 print a ``` The difference from the Ruby version is that this one doesn't ignore invalid instructions while iterating over the input. Instead I take advantage of the fact that Python tends to return `-1` instead of `nil` when there is no match -- The current value of `a` is appended to the back of the result array, so that all invalid instructions maps to the same, unchanged value. [Answer] # Python 3, ~~124~~ ~~94~~ 93 bytes ``` a=0 for i in input(): if i in"!><@":a=(i=='!')*(255-a)+(i==">")*a//2+(i=="<")*(a+a)%256+(i=="@")*(16*(a%16)+a//16) print(a) ``` "!" is same as subtracting from 255. "<" is same as multiplying by 2. But 8 bit register means mod 256. ">" is same as integer division by 2. "@" means shifting last 4 bits (`a%16`) by 4 bits(`*16`) and adding the first four bits(`a/16`). **EDIT (read shameless copying)** Saw the other answer in python (by Beta decay). It uses a really effective way to simulate switch cases using dictionary. Using that we can write ``` a=0 for i in input():a={"!":255-a,"<":a<<1&255,">":a//2,"@":(a%16)<<4+a>>4}.get(i,a) print(a) ``` Thanks, Beta Decay. [Answer] # Haskell, 89 bytes ``` a#'!'=255-a a#'>'=div a 2 a#'<'=mod(a*2)256 a#'@'=mod(a*16)256+div a 16 a#_=a f=foldl(#)0 ``` Usage example: `f "!>>"` -> `63` [Answer] ## Rust, 111 bytes More of a comment on @Doorknob's answer, but I don't have any rep for comments as I just created an account. One can shave 10 bytes off his Rust solution with the following: ``` fn r(s:&str)->u8{let mut n=0u8;for t in s.chars(){n=match t{'!'=>!n,'>'=>n>>1,'<'=>n<<1,'@'=>n>>4|n<<4,_=>n}}n} ``` [Answer] # Python 3, 127 bytes Edit: shorting, thanks @Jakube Edit2: fix, thanks @Anachor ``` a=0 for i in input():a=(a^255if i=="!"else a>>1if i==">"else a<<1if i=="<"else(a&15)<<4|(a&240)>>4if i=="@"else a)&255 print(a) ``` [Answer] # Ceylon, ~~297~~ 290 ``` shared void y(){value t=process.readLine()else"";variable Byte a=0.byte;for(c in t){switch(c)case('!'){a=a.not;}case('>'){a=a.rightLogicalShift(1);}case('<'){a=a.leftLogicalShift(1);}case('@'){a=a.and(#f0.byte).rightLogicalShift(4).xor(a.and(#f.byte).leftLogicalShift(4));}else{}}print(a);} ``` Formatted: ``` shared void y() { value t = process.readLine() else ""; variable Byte a = 0.byte; for (c in t) { switch (c) case ('!') { a = a.not; } case ('>') { a = a.rightLogicalShift(1); } case ('<') { a = a.leftLogicalShift(1); } case ('@') { a = a.and(#f0.byte).rightLogicalShift(4).xor(a.and(#f.byte).leftLogicalShift(4)); } else {} } print(a); } ``` `#f` and `#f0` are hexadecimal numbers for the nibbles, `.byte` converts an integer into a byte. I'm lucky that Byte's `.string` attribute already uses the unsigned representation of a byte. Ceylon also features a switch statement without fall-through, and a string is a list of characters, which can be iterated. I also tried to cut those long shift method names down by using an aliasing import, but this actually becomes 7 bytes longer: ``` import ceylon.language{Byte{r=rightLogicalShift,l=leftLogicalShift}}shared void x(){value t=process.readLine()else"";variable Byte a=0.byte;for(c in t){switch(c)case('!'){a=a.not;}case('>'){a=a.r(1);}case('<'){a=a.l(1);}case('@'){a=a.and(#f0.byte).r(4).xor(a.and(#f.byte).l(4));}else{}}print(a);} ``` Formatted: ``` import ceylon.language { Byte { r=rightLogicalShift, l=leftLogicalShift } } shared void x() { value t = process.readLine() else ""; variable Byte a = 0.byte; for (c in t) { switch (c) case ('!') { a = a.not; } case ('>') { a = a.r(1); } case ('<') { a = a.l(1); } case ('@') { a = a.and(#f0.byte).r(4).xor(a.and(#f.byte).l(4)); } else {} } print(a); } ``` This might be useful if we need those methods a bit more often. [Answer] # Ruby, ~~81~~ 73 bytes So much simpler -- no eval! For each valid character in the input, it evaluates each instruction, and finds the appropriate instruction through the index of `$&` (the current character in the input). ``` a=0 gets.scan(/[!><@]/){a=[~a,a/2,a*2,a*16+a/16]["!><@".index$&]&255} p a ``` [Answer] ## STATA, 197 bytes ``` di _r(a) gl b=0 forv x=1/`=length("$a")'{ gl c=substr("$a",`x',1) if"$c"=="!" gl b=255-$b if"$c"==">" gl b=int($b/2) if"$c"=="<" gl b=mod($b*2,256) if"$c"=="@" gl b=mod($b,16)*16+int($b/16) } di $b ``` Ungolfed ``` display _request(a) //get the input via prompt and put in var a global b=0 //initialise A to be 0 forv x=1/`=length("$a")'{ //for loop from 1 to last char in a global c=substr("$a",`x',1) //get the char at index x in a if "$c"=="!" global b=255-$b //invert is the same as 255-A if "$c"==">" global b=int($b/2) //right shift is the same as A/2 (with integer division) if "$c"=="<" global b=mod($b*2,256) //left shift is the same as A*2%256 if "$c"=="@" global b=mod($b,16)*16+int($b/16) //nibble swap is the same as A%16*16+A/16 } display $b //display the result of A ``` Does not work with the online interpreter and requires the non-free default interpreter. This would be somewhat easier with actual bitwise operations, but I don't think they're too useful for most of the common uses of STATA. [Answer] # JavaScript, 104 ``` [].reduce.call(prompt(),function(a,i){return(i=='!'?~a:i=='>'?a/2:i=='<'?a*2:i=='@'?a>>4|a<<4:a)&255},0) ``` Nested ternary operators map to instructions. BITWISE AND is used to constrain our Number type to a single byte. [Answer] # Julia, ~~117~~ ~~94~~ ~~86~~ 73 bytes ``` p->(a=0x0;[a=c==33?~a:c==60?a<<1:c==62?a>>1:c!=64?a:a<<4|a>>4for c=p];1a) ``` This is an anonymous function that accepts a string and returns an integer. To call it, assign it to a variable. Ungolfed: ``` function f(p) # Initialize the accumulator to 0 as an 8-bit unsigned integer a = 0x0 # Loop over the characters in the input for c in p a = c == 33 ? ~ a : # '!' c == 60 ? a << 1 : # '<' c == 62 ? a >> 1 : # '>' c != 64 ? a : # no-op a << 4 | a >> 4 # '@' end # Convert the accumulator to a regular integer and return return Int(a) end ``` Saved 8 bytes thanks to Sp3000 and 13 thanks to Dennis! [Answer] # JavaScript (ES6), 76 ~~81~~ As an unnamed function returning the accumulator value This is a porting of the super clever answers by @daniero (that have way too few upvotes) Bonus: you *can* pass an initial value of the accumulator. If not passed, starting value is 0 as by specific. ``` (p,a)=>(p.replace(/[!<>@]/g,i=>a=(i<'<'?~a:i<'>'?a*2:i<'@'?a/2:a*257/16)&255),a) ``` Test running the snippet below in any EcmaScript 6 browser (I tested in Firefox) ``` f=(p,a)=>[...p].map(c=>a=255&[a,~a,a*2,a/2,a*257/16][1+'!<>@'.indexOf(c)])|a // TEST out=x=>O.innerHTML+=x+'\n' function go(x) { out(x+' -> '+f(x)) } go('!'),go('!>>'),go('!<@'),go('!nop!&6*!') // LESS GOLFED F=(p,a)=>// a as a parameter, if not passed its value starts as undefined, then becomes NaN, but the operators '&' and '~' treat it as 0 [...p].map(c => // execute following function for each character p a = 255 & // any intermediate result is converted to numeric and truncate to a byte // evaluate all possible results (then choose one bases on the current character) [a, // NOP, if unexpected char 'a' remains the same ~a, // tilde == binary not (will give a result wider than a byte) a*2, // < shift left is *2 (can give a result wider than a byte) a/2, // > shift right is /2 (can give a non integer result) a *257 / 16 // move nibbles around (will give a result wider than a byte) ] // array of all results [1+'!<>@'.indexOf(c)] // find index to get the correct result ) // end map, returns an array in any case // eventually a single element array containg a | a // return accumulator ``` ``` Test program:<input id=I><button onclick='go(I.value)'>go</button> <pre id=O></pre> ``` [Answer] # Crystal, 139 bytes ``` def f x b=0_u8 x.chars.each do|c| b=case c when'!' ~b when'>' b>>1 when'<' b<<1 when'@' b<<4|b>>4 else raise "" end end puts b end ``` [Answer] **C# 193** ``` void Main(){byte a=0;foreach(var c in Console.ReadLine()){if(c=='!')a=(byte)~a;if(c=='>')a=(byte)(a>>1);if(c=='<')a=(byte)(a<<1);if(c=='@')a=(byte)(((a&240)>>4)|((a&15)<<4));}Console.Write(a);} ``` [Answer] # Lua, 344 char ``` a=string.rep("0",8) t=io.read() f={["!"]=function()local s="";for j=1,8 do s=s..(a:sub(j,j)=="0"and"1"or"0") end;return s end,[">"]=function() return "0"..a:sub(1,7) end,["<"]=function()return a:sub(2,8).."0"end,["@"]=function()return a:sub(5,8)..a:sub(1,4)end} for i=1,#t do a=(f[t:sub(i,i)]or function()return a end)()end print(tonumber(a,2)) ``` Inspired by @Beta Decay's use of a string accumulator, seeing as lua has no byte type. Could probably be golfed more by using fewer functions. [Answer] # R, 194 bytes ``` b<-readline();A<-rep(0,8);s<-strsplit(b,"")[[1]];for(r in s){if(r=="!")A<-(A+1)%%2;if(r==">")A<-c(0,A)[1:length(A)];if(r=="<")A<-c(A,0)[-1];if(r=="@")A<-c(A[5:8],A[1:4])};print(sum(A*(2^(7:0)))) ``` ungolfed ``` b <- readline() A <- rep(0, 8) s <- strsplit(b, "")[[1]] for (r in s) { if (r == "!") A <- (A + 1) %% 2 if (r == ">") A <- c(0, A)[1:length(A)] if (r == "<") A <- c(A, 0)[-1] if (r == "@") A <- c(A[5:8], A[1:4]) } print(sum(A*(2^(7:0)))) ``` [Answer] # RPL, 170.5 bytes The input should be entered as a string on level 1. ``` \<< DEC 8 STWS \-> S \<< #0d 1 S SIZE FOR I "!><@" S I DUP SUB POS 1 + { \<< \>> NOT SR SL \<< DUP #16d / SWAP #16d * + \>> } SWAP GET EVAL NEXT \>> \>> ``` [Answer] # K, 57 bytes It's a start: ``` 0{y+2*x}/(8#0){((~:;{-1_0,x};{1_ x,0};4!;{x})"!><@"?y)x}/ ``` tested using Kona: ``` f:0{y+2*x}/(8#0){((~:;{-1_0,x};{1_ x,0};4!;{x})"!><@"?y)x}/ ... f'("!";"!>>";"!<@";"!nop!&6*!") 255 63 239 255 ``` I might be able to do better in k5, but it's a complex series of tradeoffs- for example, converting binary to decimal is as easy as `2/`, but the behavior of `?` makes it harder to handle a default case for instruction lookup. [Answer] # PHP, 189 bytes ``` <? $c='00000000';foreach(str_split($argv[1])as$a){$a=='!'&&$c=strtr($c,'01','10');$a=='<'&&$c=substr($c.'0',1);$a=='>'&&$c=substr('0'.$c,0,8);$a=='@'&&$c=substr($c.$c,4,8);}echo bindec($c); ``` It's not that it gonna beat many answers, it's only for practice [Answer] # [HPPPL](http://www.hp-prime.de/en/category/6-downloads), ~~302~~ 294 bytes ``` #pragma mode(separator(.,;)integer(d8))EXPORT b()BEGIN print();local p,j,a;a:=#0d;INPUT({{p,[2]}});for j from 1 to dim(p)do c:=p(j);case if c==33 then a:=BITNOT(a)end if c==62 then a:=BITSR(a,1)end if c==60 then a:=BITSL(a,1)end if c==64 then a:=BITSL(a,4)+BITSR(a,4)end end;end;print(a*1);END; ``` Ungolfed: ``` // make sure integers are unsigned 8 bit decimal numbers #pragma mode( separator(.,;) integer(d8) ) EXPORT b() BEGIN print(); local p,j,a; a:=#0d; // set a to integer value 0 INPUT({{p,[2]}}); // open input dialog treating input as string ( type [2]) for j from 1 to dim(p) do c:=p(j); case if c==33 then a:=BITNOT(a) end // ! if c==62 then a:=BITSR(a,1) end // > if c==60 then a:=BITSL(a,1) end // < if c==64 then a:=BITSL(a,4)+BITSR(a,4) end // @ end; end; print(a*1); // converts to proper output by promoting to non integer format // print(a) would result in // #239:8d for 239 if the default bit size is not set to 8 bits decimal // indicating an 8 bit unsigned decimal integer, or // #239d if the default bit size is already set to 8 bits decimal END; ``` [![HPPPL Input command](https://i.stack.imgur.com/PZ8eA.png)](https://i.stack.imgur.com/PZ8eA.png) [![HPPPL Output to Terminal](https://i.stack.imgur.com/FoENi.png)](https://i.stack.imgur.com/FoENi.png) This answer ensures that the HP Prime uses unsigned 8 bit integers even if the mode is set to e.g. 64 bits by the user. If the calculator is set up manually to using unsigned 8 bit decimal integers, then the `pragma` command can be omitted. If the output does not need to follow the format strictly then the `a*1` at the end can simply be `a`. Multiplying the result by 1 just ensures the output does not follow the internal output for integer values. The `print` command in line 4 can also be omitted if the terminal does not need to be cleared before printing out the result. If passing the program as a string argument is allowed, then the `INPUT` command can be omitted as well. This is the shortest version with input and proper output, without the pragma argument (if the calculator is set to Uint8 by default: **243 bytes:** ``` EXPORT b()BEGIN local p,j,a;a:=#0d;INPUT({{p,[2]}});for j from 1 to dim(p)do c:=p(j);case if c=33 then a:=BITNOT(a)end if c=62 then a:=BITSR(a,1)end if c=60 then a:=BITSL(a,1)end if c=64 then a:=BITSL(a,4)+BITSR(a,4)end end;end;print(a*1);END; ``` [Answer] ## Perl 6, ~~96~~ 89 bytes ``` {my $a=0;$a=(+^*,*+<1,*+>1,{$_+<4+$_+>4},{$_})["!<>@".index($_)//4]($a)%256 for .comb;$a} ``` Old solution: ``` {my $a=0;$a=(255-*,*+<1+&255,*+>1,{$_+&15+<4+$_+>4},{$_})["!<>@".index($_)//4]($a)for .comb;$a} ``` [Answer] ## C#, 119 bytes ``` i=>{var a=0;foreach(var c in i){if(c=='!')a=~a;if(c=='>')a>>=1;if(c=='<')a<<=1;if(c=='@')a=a<<4|a>>4;a&=255;}return a;} ``` Other versions I tried, but need more bytes: ``` Func<string,int>C=i=>{var a=0;foreach(var c in i){switch(c){case'!':a=~a;break;case'<':a<<=1;break;case'>':a>>=1;break;case'@':a=a<<4|a>>4;break;}a&=255;}return a;}; // This is, despite having the worst score, my personal favourite :D Func<string,int>D=i=>{var f=new Dictionary<char,Func<int,int>>{{'!',q=>~q},{'<',q=>q<<1},{'>',q=>q>>1},{'@',q=>q<<4|q>>4}};var a=0;foreach(var c in i)if(f.ContainsKey(c))a=f[c](a)&255;return a;}; ``` [Answer] ## Python 2.7.3, 104 bytes Having code in strings to be evaluated looks pretty dirty, but works :D ``` a=0 for c in raw_input():a=eval({'!':'~a','<':'a<<1','>':'a>>1','@':'a<<4|a>>4'}.get(c,'a'))&255 print a ``` Here's the output (and input actually..) And yes, it's really running on a RaspberryPi :) [![Example output](https://i.stack.imgur.com/zbKj8.png)](https://i.stack.imgur.com/zbKj8.png) ]
[Question] [ Given a list of non-negative integers in any reasonable format, iterate over it, skipping as many elements as every integer you step on says. --- Here is a worked example: ``` [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [] ^ First element, always include it [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0] ^ Skip 0 elements [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1] ^ Skip 1 element [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2] ^ Skip 2 elements [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2, 3] Skip 3 elements; you're done ``` Another worked example, not so all-equal-deltas: ``` [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [] ^ First element, always include it [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4] ^ Skip 4 elements [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3] ^ Skip 3 elements [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3] ^ Skip 3 elements [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3, 4] Skip 4 elements; you're done ``` An out-of-bounds example: ``` [0, 2, 0, 2, 4, 1, 2] | [] ^ First element, always include it [0, 2, 0, 2, 4, 1, 2] | [0] ^ Skip 0 elements [0, 2, 0, 2, 4, 1, 2] | [0, 2] ^ Skip 2 elements [0, 2, 0, 2, 4, 1, 2] | [0, 2, 4] Skip 4 elements; you're done (out of bounds) ``` --- # Rules * You may not use any boring cheat among [these ones](https://codegolf.meta.stackexchange.com/q/1061/41024), they make the challenge boring and uninteresting. * You should only return/print the final result. STDERR output is ignored. * You may not get the input as a string of digits in any base (e.g. "0102513162" for the first case). * You must use left-to-right order for input. * As in the worked examples, if you go out of bounds, execution terminates as if otherwise. * You should use `0` for skipping 0 elements. * Given the empty list (`[]`) as input, you should return `[]`. --- # Test cases ``` [] => [] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] => [0, 1, 3, 7] [5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0] => [5, 2, 1, 0] [0, 1, 0, 2, 5, 1, 3, 1, 6, 2] => [0, 1, 2, 3] [4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] => [4, 3, 3, 4] [0, 2, 0, 2, 4, 1, 2] => [0, 2, 4] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` f=lambda x:x and x[:1]+f(x[x[0]+1:]) ``` [Try it online!](https://tio.run/##JYtBCoAgFAWv8pZFf6FWFEInERdGSEGZRIvf6U10M/BmePF79zuolPxyumvdHFgzXNjARkvb@YYNG2E7qW2b4nOEF74xA2EkSEJPmAtFmdVkKsJEGIqvSeX/Dw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~49 44\*~~ 41 bytes [Crossed out 44 is still regular 44 :(](https://codegolf.stackexchange.com/questions/123194/user-appreciation-challenge-1-dennis/123438#123438) *\* -3 thanks to @ASCII-only*. ``` l=input() while l:print l[0];l=l[l[0]+1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERDk6s8IzMnVSHHqqAoM69EISfaINY6xzYnGsTQNrSK/f8/2kBHwVBHAUga6SiYgtnGYNIMKBKroAAA "Python 2 – Try It Online") Prints the results separated by a newline, as the OP allowed in chat. I don't think it can get any shorter as a *non-recursive full program*. --- # How does this work? * `l=input()` - Reads the list from the standard input. * `while l:` - Abuses the fact that empty lists are falsy in Python, loops until the list is empty. * `print l[0];` - Prints the first element of the list. * `l=l[l[0]+1:]` - "Skips like a rabbit" - Trims the first `l[0]+1` from the list. ### Let's take an example Given the list `[5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]` as input, the code performs the following (according to the explanation above) - Prints the first item of the array: `5`, trim the first 6: `[2, 1, 2, 1, 0, 0]`. We then print `2` and trim the first 3: `[1,0,0]`. Likewise, we output `1`, crop the first 2, and we get `[0]`. Of course, `0` is printed and the program terminates. [Answer] # Haskell, ~~29 27~~ 26 bytes ``` j(x:y)=x:j(drop x y) j x=x ``` Saved 1 byte thanks to Zgarb. [Try it online.](https://tio.run/##ZY3BCoMwEETvfsUcelDYQ0xiW4T9EslBsFBTq2J7iF@flk0tlsIysLP7Zq7t43YZhhh9Huq14FD7vFumGQFrkXkEDvHe9iMY3ZQB89KPTxzg0VhCRSgJhnAWVbIm562acCJY8dNJOzALaWSs@41MX0rQapd0/KJqSzb/qN5Quy/7WC6@AA) [Answer] # JavaScript (ES6), ~~42~~ ~~39~~ 35 bytes ``` a=>a.map((n,i)=>a.splice(i+1,n))&&a ``` ``` let f = a=>a.map((n,i)=>a.splice(i+1,n))&&a console.log(f([])) // => [] console.log(f([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) // => [0, 1, 3, 7] console.log(f([5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0])) // => [5, 2, 1, 0] console.log(f([0, 1, 0, 2, 5, 1, 3, 1, 6, 2])) // => [0, 1, 2, 3] console.log(f([4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2])) // => [4, 3, 3, 4] console.log(f([0, 2, 0, 2, 4, 1, 2])) // => [0, 2, 4] ``` ### Old Solution 39 Bytes ``` a=>a.map(n=>i--||r.push(i=n),r=i=[])&&r ``` *-3 bytes thanks to @ThePirateBay* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes ``` [¬Dg>#=ƒ¦ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f8/@tAal3Q7Zdtjkw4tA/JMdBRMdRQMdRSMdRQswKQBmAsRAZJGOgrmOgomYHGIlFEsAA "05AB1E – Try It Online") [Answer] ## Mathematica, ~~46~~ 44 bytes ``` SequenceCases[#,{x_,y___}/;Tr[1^{y}]<=x:>x]& ``` Alternatives: ``` SequenceCases[#,{x_,y___}/;x>=Length@!y:>x]& SequenceCases[#,l:{x_,___}/;x>Tr[1^l]-2:>x]& ``` [Answer] # C#, 68 bytes ``` a=>{for(int i=0;i<a.Count;i+=a[i]+1)System.Console.Write(a[i]+" ");} ``` [Try it online!](https://tio.run/##tVDBSsQwEL33K4Y9NWws3W5XV9IWZA9eVhA97EE8hG4KA20iTVSk9NtrNqGrqyAodQ6PyZvhvXkp9VmjpBokb4R@4qWA@zdtRBN0Adgqa6413LreM4fShhss4UXhHm44ypAcRx9Lh7oqDSqZbVRdC9fq6FpI0WIZbVGbDKUpCqggH3hedJVqQ8sA5jHDjEcb9SwNw3nOH/BxviD@MktLrWoR7Vo0InSzGcwI6wcWnLhXoRSv8KN5SKCDnrATzS1KERL2J62YwoJCQmFJIaWwonBO4YLCmsKlHcWTmq2@mSUjY9GeEv9Dttjpe@ulQ5swmdQo/aS/duitj46J@9PUZ/TM1EmTMWn6C/2Tx7h9J/j@63IfeOyHdw "C# (Mono) – Try It Online") Full/Formatted version: ``` namespace System { class P { static void Main() { Action<Collections.Generic.List<int>> f = a => { for (int i = 0; i < a.Count; i += a[i] + 1) System.Console.Write(a[i] + " "); }; f(new Collections.Generic.List<int>() { });Console.WriteLine(); f(new Collections.Generic.List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });Console.WriteLine(); f(new Collections.Generic.List<int>() { 5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0 });Console.WriteLine(); f(new Collections.Generic.List<int>() { 0, 1, 0, 2, 5, 1, 3, 1, 6, 2 });Console.WriteLine(); f(new Collections.Generic.List<int>() { 4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2 });Console.WriteLine(); f(new Collections.Generic.List<int>() { 0, 2, 0, 2, 4, 1, 2 });Console.WriteLine(); Console.ReadLine(); } } } ``` --- Returning a list is longer at 107 bytes. ``` a=>{var l=new System.Collections.Generic.List<int>();for(int i=0;i<a.Count;i+=a[i]+1)l.Add(a[i]);return l;} ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~8~~ 6 bytes ``` ←TU¡Γ↓ ``` [Try it online!](https://tio.run/##yygtzv7//1HbhJDQQwvPTX7UNvn////RBjpGOiBsomOoYxQLAA "Husk – Try It Online") -2 bytes (and a completely new solution idea) thanks to Leo! ## Explanation I'm using the list pattern match function `Γ`. It takes a function `f` and a list with head `x` and tail `xs`, and applies `f` to `x` and `xs`. If the list is empty, `Γ` returns a default value consistent with its type, in this case an empty list. We take `f` to be `↓`, which drops `x` elements from `xs`. This function is then iterated and the resulting elements are collected in a list. ``` ←TU¡Γ↓ Implicit input, e.g. [0,2,0,2,4,1,2] Γ↓ Pattern match using drop ¡ iterated infinitely: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[],[],[],... U Cut at first repeated value: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[]] T Transpose: [[0,2,4],[2,0,1],[0,2,2],[2,4],[4,1],[1,2],[2]] ← First element: [0,2,4] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ 55 bytes ``` l=input() i=0 while l[i:]:i+=1;l[i:i+l[i-1]]=[] print l ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERDkyvT1oCrPCMzJ1UhJzrTKtYqU9vW0BrEzNQGkrqGsbG20bFcBUWZeSUKOf//RxvoKBjqKABJIx0FUzDbGEyaAUViAQ "Python 2 – Try It Online") [Answer] # Pyth, 22 Bytes ``` VQ aY.(Q0VeY .x.(Q0 ;Y ``` Removed a useless byte [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ ~~42~~ 41 bytes -18 bytes thanks to Luis Mendo -1 byte thanks to Jonathan Frech ``` x=input() i=0 while 1:print x[i];i-=~x[i] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDkyvT1oCrPCMzJ1XB0KqgKDOvRKEiOjPWOlPXtg7E@P8/2kDHUMdIx1jHRMdUx0zHXMdCx1LH0CAWAA "Python 2 – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), 36 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* ((1)*¶)(?<-2>1*¶)* $1 %M`. 0$ ``` Input and output are linefeed-separated with a trailing linefeed. [Try it online!](https://tio.run/##TYyxDsIwDET3@45USsNRxWlaioTgC5hYGcrAwNKh4tv4AH4s2IEBWSe9s@@83p@P5VYaf5lZug1cgPfShver9afDNh3FMMAJmvPcITqU6wIWRAoTe2YOHLnjxD0lEsPfPlUWRp1aiGot0KtGZeSfnVQW@J6S/su1ZQxrmXK1Hw "Retina – Try It Online") (Uses commas instead of linefeeds to allow for convenient test suites.) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 64 bytes ``` ([]){{}(({})<>)<>{({}[()]<{}>)}{}([])}{}<>([]){{}({}<>)<>([])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6ulZDo7pW08YOiKqBrGgNzVib6lo7zVqgDFABkLKxg6kEsTUhXCDr/38DLiMuEDbhMuQyAgA "Brain-Flak – Try It Online") ``` ([]){{} ([])}{} # Until the stack is empty (({})<>)<> # Copy TOS to off stack {({}[()]<{}>)}{} # Pop TOS times <>([]){{}({}<>)<>([])}<> # Reverse off stack ``` [Answer] # Mathematica, ~~64~~ 50 bytes ``` ±x_List:=Prepend[±Drop[x,1+#&@@x],#&@@x] ±_=±{}={} ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 68 bytes ``` n=>{var t="";for(int i=0;i<n.Length;i+=n[i]+1)t+=n[i]+" ";return t;} ``` [Try it online!](https://tio.run/##lY8xa8MwEIXn@lccnmyiBsdxmhTFWQqd0qF06BAyGFdxD9ITSHJKMf7triLFTqBD8Rsex93pu6dS35dSia7WSBW8/WgjvngQgFV5LLSGV1c3zs/SpjBYwkniB7wUSFE8jK5LZz3XVK6RzG7P7CNl8RuoIO8o3zSnQoHJw5AfpIrsDmCecFzTdCuoMp8cJzntcD@ZxeZShRByJUytCAxvu0vEXk@StDyK6btCI7ZIIqoiEt/gzjcJgxmDlMGcQcZgweCBwZLBisGjHSVtHPPg7n/O4g8n7TvW7RVPGhsscQQPnzu38dKRqOyGsHLu4QMzdV/OfE7fGZ827dNmN4QB0Qbeu18 "C# (.NET Core) – Try It Online") Takes input as an array of integers, returns a string containing the non-skipped values. [Answer] # R, 58 bytes ``` f=function(x,p=1){cat(z<-x[p]);if(p+z<sum(x|1))f(x,p+z+1)} ``` Recursive function. Takes a vector `x` as argument and intiates a pointer `p`. This prints the corresponding entry of `x`, checks if `p+x[p]` would go out of bounds, and if not, calls the function for the new pointer. ``` f=function(x,p=1,s=x[1])`if`((z<-x[p]+p+1)>sum(x|1),s,f(x,z,c(s,x[z]))) ``` This is a comparable solution that returns a proper vector instead of printing the digits. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 53 bytes Thanks to @PunPun1000 and @TheLethalCoder ``` a->{for(int n=0;;n+=1+a[n])System.out.println(a[n]);} ``` [Try it online!](https://tio.run/##ZY4xc4MwDIV3foVGKIlDkksWhyydOnTKyDG4xKGmIHO2SK/H5be7MtdMHSTZ35OfX6fuam1Hjd31K5hhtI6gYyYmMr14kck/dpuwIWMxisk4ffSmgaZX3sO7Mjg/kSdFPO7WXGFgIb2QM9hWtXKtz@bk1aKfBu1OBqmqzxBtoYSg1uf5Zl3KGLAspMS83Oaqwjq7/HjSg7ATiZG9qMd04fIROGe0AdKe2AX1N0QQ/xK9xpY@a5k8bQ1vFNKc4vKfKk2ec6hIKlOz/oakW@3EqJzXfEmjFUuZTB5JzCpU0@iR0vhkgY/NpipWsF0B990KDst5v/QjkzqEImy5duHAc891DLtf "Java (OpenJDK 8) – Try It Online") [Answer] ## [Alice](https://github.com/m-ender/alice), 15 bytes ``` /$.. \h& \I@nO/ ``` [Try it online!](https://tio.run/##S8zJTE79/19fRU9PISZDjSvG0yHPX///fxMuUy5DLmMuCyA2ALJAbEMuIy5zLhMgHyRiBAA "Alice – Try It Online") Input and output a linefeed-separated lists of decimal integers. ### Explanation ``` / Switch to Ordinal mode. I Read a line. . Duplicate it. n Logical NOT (gives truthy if we're at EOF). / Switch to Cardinal. The IP wraps around to the left. \ Switch to Ordinal. $@ Terminate the program if we're at EOF. . Duplicate the input line again. O Print it. \ Switch to Cardinal. h Increment the value. & Store the result in the iterator queue. The program wraps around to the beginning. ``` Storing an integer **n** in the iterator queue causes the next command to be executed **n** times. Mirrors like `/` are not commands, so the next command will be `I`. Therefore if we just read and printed a value **x**, we will read **x+1** values on the next iteration, with the last of them ending up on top of the stack. This skips the required number list elements. [Answer] ## *Mathematica*, 37 (30?) Further golfing of user202729's fine method. ``` ±{a_,x___}={a}~Join~±{x}~Drop~a ±_={} ``` The rules don't seem to explicitly specify the output format, so maybe: ``` ±{a_,x___}=a.±{x}~Drop~a ±_={} ``` Output for the second function looks like: `0.2.4.{}` — notably `{}` is still returned for an empty set, conforming to the final rule. [Answer] # Common Lisp, 51 bytes ``` (do((x(read)(nthcdr(1+(print(car x)))x)))((not x))) ``` [Try it online!](https://tio.run/##Hcs5DoAgFEXRrbzy/diAs8sxYCKJAfKlYPc4FLc4xXVXuHNr9Ims1GP3wlhO55W2Y9YQC92uqCLyRcZUfr2TgUWPASMmzFiwYoM18gA) [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~64~~ 60 bytes *4 bytes save based on an idea from [0 '](https://codegolf.stackexchange.com/users/20059/0)* ``` ([]){{}(({})<>())<>{({}[()]<{}>)}{}([])}{}<>{({}[()]<>)<>}<> ``` [Try it online!](https://tio.run/##TYo7DoAwDEOvk2xQBFOVi1QdCgsIiYHVytmNRwb/5Le/43rOcdykte5AmiG9hrkM6s28V2R46hOi@B0hSpvkxFkqXJWLtLF8 "Brain-Flak (BrainHack) – Try It Online") ## Annotated ``` ([]){{} #{Until the stack is empty} (({})<>())<> #{Put n+1 to the offstack} {({}[()]<{}>)}{} #{Remove n items from the top} ([])}{} #{End until} <> #{Swap stacks} {({}[()]<>)<>}<> #{Move everything back onto the left stack decrementing by 1} ``` [Answer] # Ruby, ~~36 33~~ 31 ``` f=->l{a,*l=l;a&&f[l.drop(p a)]} ``` [Try it online.](https://tio.run/##KypNqvz/P81W1y6nOlFHK8c2xzpRTS0tOkcvpSi/QKNAIVEztvZ/ml5yYk6OQrSJjoKpjoKhjoKxjoIFmDQAcyEiQNJIR8FcR8EELA6RMor9DwA) [Answer] ## Python 2.4, 85 bytes No chance to win in python with it, but I love oneliners and this one might be interesting to others. Turns out, there is a fancy magic trick to access building list inside comprehension, but it works only in 2.4 and with some edits in <= 2.3 `locals()['_[1]']` it is. Python creates secret name `_[1]` for list, while it is created and store it in `locals`. Also names `_[2]`, `_[3]`... are used for nested lists. ``` lambda n:[j for i,j in enumerate(n)if i==len(locals()['_[1]'])+sum(locals()['_[1]'])] ``` So it counts number of already added elements plus their sum. Result is the index of next desired element. I think, that there should be a way to avoid enumerate. Like accessing input array directly by index: `[ n[len(locals()['_[1]'])+sum(locals()['_[1]'])] for ... ]`. But I can't figure out a compact way to protect it from index-out-of-range (while keeping it oneliner) [![enter image description here](https://i.stack.imgur.com/1F5RJ.png)](https://i.stack.imgur.com/1F5RJ.png) [Answer] # Swift, 63 bytes ``` func a(d:[Int]){var i=0;while i<d.count{print(d[i]);i+=d[i]+1}} ``` This is my first entry, ever, so I'm not 100% sure on the rules, but hopefully this answer suffices. I'm a little unsure of rules on how to get the input into a system. I have a shorter answer if I was allowed to assume a function somewhere that can return the input. [Answer] # [Perl 6](https://perl6.org), 31 bytes ``` {(@_,{.[1+.[0]..*]}...^0)[*;0]} ``` [Test it](https://tio.run/##nZDPa4MwHMXv@SveadU2DdGp7RDFHXbrcewi2RiageBsqHasSP@y3faPuRirK@wHYzkE8v2@9@G9KLkrg25fS7wELAvJ8wEX2TaXiLrWSh5oy1JnwVIuGJuLI2PsntvpPOTi2Glp0si6QYSyqGRt2e9vrFZl0VizKJ71r5u7601IevqtFoZElY8VFsYVkqft7gRYxrCQFJXaNxSJfFUya2QOGy0BinqZS6nKA/pc1iCz2aaoz8Xj22yZ0q1CcuxSgf@cKEYqSMopHAqX4pLCo/ApAooVxZriSq@4@NE8OLVtpTH@F4w7TvStpd@Ceswk5VMabkb@yHdMJlf8WuWzh8Z4Z@61uYf1xHNNR29INkyEwXhG0ZcY0rhjGm9U/eljTx7xAQ "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「@_」 ( # generate a sequence @_, { .[ # index into previous value in the sequence 1 + .[0] # start by skipping one plus the first element # of the previous value in the sequence .. * # use that to create a Range with no end ] } ...^ # keep doing that until: (and throw away last value) 0 # it generates an empty list )[ *; 0 ] # from every value in the sequence, get the first element } ``` To help understand how the code works, without `[*;0]` this would generate a sequence like the following: ``` [0, 1, 0, 2, 5, 1, 3, 1, 6, 2], (1, 0, 2, 5, 1, 3, 1, 6, 2), (2, 5, 1, 3, 1, 6, 2), (3, 1, 6, 2) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḢṄ‘ṫ@µL¿ ``` A full program printing the results each followed by a newline (empty list produces no output). **[Try it online!](https://tio.run/##y0rNyan8///hjkUPd7Y8apjxcOdqh0NbfQ7t////f7SJjoKpjoKhjoKxjoIFmDQAcyEiQNJIR8FcR8EELA6RMooFAA "Jelly – Try It Online")** ### How? ``` ḢṄ‘ṫ@µL¿ - Main link: list of non-negative integers e.g. [2,5,4,0,1,2,0] ¿ - while: Iteration: 1 2 3 4 5 L - length (0 is falsey) 7 4 3 1 0 µ - ...do: stop Ḣ - head (pop & modify) 2 ([5,4,0,1,2,0]) 0 ([1,2,0]) 1 ([2,0]) 0 ([0]) Ṅ - print it (and yield it) "2\n" "0\n" "1\n" "0\n" ‘ - increment 3 1 2 1 ṫ@ - tail from index [0,1,2,0] [1,2,0] [0] [] - - i.e. a resulting in the printing of: '''2 0 1 0 ''' ``` [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` f=lambda h=0,*t:t and[h,*f(*t[h:])] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIcPWQEerxKpEITEvJTpDRytNQ6skOsMqVjP2/38A "Python 3 – Try It Online") Run it with `f(*l)` where `l` is your input. Arguably stretching the rules for input, but I just love advanced unpacking. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes[SBCS](https://github.com/abrudz/SBCS) ``` {⍵≡⍬:⍬⋄(⊃,∘∇1↓⊃↓⊢)⍵} ``` [Try it online!](https://tio.run/##bU5BCsIwELznFXuLgkKStrb2NwWpFAuVkotIT0qtSkUQwas9e/Xic/YjdZOKqLiwy2R2ZjbRPB1OFlGaTVs8nJMMy6NoY5pLrO@4vWJ9C6lxv@7hbjXA6oLVRmJ5opedTZ@ERdvqt6fJCcZYP0IeR0nKCRGfUwTPZrxgAiQocMAFD0bgQwBjkAK@SoNROeAz70OtLJa0Ez/qbidstiDsWbekfAW/1WVTJnNfuoDacJ1H0Z9ce8NgTdgx95nJNe1a/n/pTvEE "APL (Dyalog Unicode) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~36~~ 30 + 1 (-a) = 31 bytes ``` $i+=$F[$i]+say$F[$i]while$i<@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18lU9tWxS1aJTNWuzixEsIqz8jMSVXJtHFw@//fREfBVEfBUEfBWEfBAkwagLkQESBppKNgrqNgAhaHSBn9yy8oyczPK/6v62uqZ2Bo8F83EQA "Perl 5 – Try It Online") Takes its input as a space separated list of numbers. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 25 bytes ``` $args|?{!$s--}|%{($s=$_)} ``` [Try it online!](https://tio.run/##nZJRS8MwFIXf@yuOIZMEbqGL6TaFYf/JGBr1oeBsNlTa/vZ6lyy1MhUxD/fh3nO@nEuye351jX9ydT3IB6zRDnLbPPrutr2QPs/7btYq6ddyo/uhz7JKZeBDqlIa/zkEduoRUhDmBEO4IlhCSVgQloQV4ZpHhf4REp1sW05w5RnOpA5XtnwLPOJGaXGWrgijMt03DxmN/nXFz70mODuhrEKNspFrwu42Jo0dHXA2KI5LfU1nUjqb1H96gJOHWRodZmgDkx@@2b4TpHvbubu9u@fvIDdx1Dh/qPfcuORfUgVhGAipxGkocvciRq/QN8klsn74AA "PowerShell – Try It Online") ]
[Question] [ Given a string input, write a program that prints a [truthy value](http://meta.codegolf.stackexchange.com/q/2190/20634) to STDOUT or equivalent if the input is a valid UUID, without using regexes. A valid UUID is > > 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). > > > [**Source**](https://en.wikipedia.org/wiki/Universally_unique_identifier#Definition) > > > ## Test Cases ``` 0FCE98AC-1326-4C79-8EBC-94908DA8B034 => true 00000000-0000-0000-0000-000000000000 => true 0fce98ac-1326-4c79-8ebc-94908da8b034 => true 0FCE98ac-1326-4c79-8EBC-94908da8B034 => true {0FCE98AC-1326-4C79-8EBC-94908DA8B034} => false (the input is wrapped in brackets) 0GCE98AC-1326-4C79-8EBC-94908DA8B034 => false (there is a G in the input) 0FCE98AC 1326-4C79-8EBC-94908DA8B034 => false (there is a space in the input) 0FCE98AC-13264C79-8EBC-94908DA8B034 => false (the input is missing a hyphen) 0FCE98AC-13264-C79-8EBC-94908DA8B034 => false (the input has a hyphen in the wrong place) 0FCE98ACD-1326-4C79-8EBC-94908DA8B034 => false (one of the groups is too long) 0FCE98AC-1326-4C79-8EBC-94908DA8B034- => false (has a trailing hyphen) 0FCE98AC-1326-4C79-8EBC-94908DA8B034-123 => false (too many groups) 0FCE98AC13264C798EBC94908DA8B034 => false (there is no grouping) ``` ## Rules * Regular Expressions are not allowed * Literal pattern matching which is *like* a regex is not allowed. For example, using `[0-9a-fA-F]` or other hexadecimal identifiers (we'll call this `n`) and then matching `nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn` or `n[8]-n[4]-n[4]-n[4]-n[12]` is not allowed * The input may either be taken from `STDIN` or as an argument to a function * The input is case insensitive * It is safe to assume that the input will *not* contain linefeeds or newlines. * The input may contain any printable ASCII characters (spaces included) * A [truthy value](http://meta.codegolf.stackexchange.com/q/2190/20634) must be printed to `STDOUT` or equivalent if the input is a valid uuid * A [falsey value](http://meta.codegolf.stackexchange.com/q/2190/20634) must be printed to `STDOUT` or equivalent if the input is *not* a valid uuid * If using a function, instead of using `STDOUT`, the output can be the return value of the function * The truthy/falsey value cannot be printed to `STDERR`. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/20634) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. Good luck! ## Leaderboard This is a Stack Snippet that generates both a leaderboard and an overview of winners by language. To ensure your answer shows up, please start your answer with a headline using the following Markdown template ``` ## Language Name, N bytes ``` Where N is the size, in bytes, of your submission If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header ``` ## Language Name, <s>K</s> X + 2 = N bytes ``` ``` var QUESTION_ID=66496;var OVERRIDE_USER=20634;function answersUrl(e){return"//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"//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, ~~73~~ ~~55~~ 56 chars ``` s=>s.split`-`.map(x=>x.length+`0x${x}0`*0)=="8,4,4,4,12" ``` The previous 55 chars version has a problem with trailing spaces in group: ``` s=>s.split`-`.map(x=>x.length+("0x"+x)*0)=="8,4,4,4,12" // "00000000-0000-0000-000 -000000000000" true ``` Test: ``` f=s=>s.split`-`.map(x=>x.length+`0x${x}0`*0)=="8,4,4,4,12" ;`0FCE98AC-1326-4C79-8EBC-94908DA8B034 0fce98ac-1326-4c79-8ebc-94908da8b034 0FCE98ac-1326-4c79-8EBC-94908da8B034 0GCE98AC-1326-4C79-8EBC-94908DA8B034 0FCE98AC-13264C79-8EBC-94908DA8B034 0FCE98AC-13264-C79-8EBC-94908DA8B034 0FCE98ACD-1326-4C79-8EBC-94908DA8B034 0FCE98AC-1326-4C79-8EBC-94908DA8B034-123 00000000-0000-0000-0000-000000000000 D293DBB2-0801-4E60-9141-78EAB0E298FF 0FCE98AC-1326-4C79-8EBC-94908DA8B034- 00000000-0000-0000-000 -000000000000`.split(/\n/g).every(s=>f(s)==/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(s)) ``` [Answer] ## CJam, ~~31~~ ~~30~~ 29 bytes ``` 8 4__C]Nf*'-*qA,s'G,_el^+Ner= ``` [Run all test cases here.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0A8%204__C%5DNf*'-*QeuA%2Cs'G%2C65%3E%2BNer%3D%0A%0A%5DoNo%7D%2F&input=D293DBB2-0801-4E60-9141-78EAB0E298FF%0A0FCE98AC-1326-4C79-8EBC-94908DA8B034%0A0fce98ac-1326-4c79-8ebc-94908da8b034%0A0FCE98ac-1326-4c79-8EBC-94908da8B034%0A0GCE98AC-1326-4C79-8EBC-94908DA8B034%0A0FCE98AC-13264C79-8EBC-94908DA8B034%0A0FCE98AC-13264-C79-8EBC-94908DA8B034%0A0FCE98ACD-1326-4C79-8EBC-94908DA8B034%0A0FCE98AC-1326-4C79-8EBC-94908DA8B034-%0A0FCE98AC-1326-4C79-8EBC-94908DA8B034-123) ### Explanation Instead of pattern matching the input directly, we're first transforming it to a simpler form which can be easily compared against a single pattern string. ``` 8 4__C] e# Push the array of segment lengths, [8 4 4 4 12]. Nf* e# Turn that into strings of linefeeds of the given length. '-* e# Join them by hyphens, giving "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN". q e# Read the input. A,s e# Push the string "0123456789". 'G,_el^ e# Push the string "ABCDEFabcdef". + e# Concatenate the two strings. N e# Push a linefeed. er e# Replace all hexadecimal digits with linefeeds. = e# Check for equality with the pattern string. ``` [Answer] ## PowerShell, ~~29~~ ~~21~~ ~~84~~ ~~49~~ 37 Bytes ``` param($g)@{36=$g-as[guid]}[$g.length] ``` Many thanks to the folks in the comments assisting with this golfing to keep up with the changing rules -- [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler), [iFreilicht](https://codegolf.stackexchange.com/users/19263/ifreilicht), [Jacob Krall](https://codegolf.stackexchange.com/users/4528/jacob-krall), and [Joey](https://codegolf.stackexchange.com/users/15/joey). Please see the edit history for revisions and older versions. This revision takes input as `$g`, then creates a new hash table `@{}` with one element, index `36` is set equal to `$g-as[guid]`. This uses the built-in [`-as` operator](https://technet.microsoft.com/en-us/library/hh847763.aspx) to attempt conversion between two .NET data types -- from `[string]` to `[guid]`. If the conversion is successful, a `[guid]` object is returned, else `$null` is returned. This portion ensures that the input string is a valid .NET GUID. The next step is to index into the hash table with `[$g.length]`. If `$g` is not exactly 36 characters in length, the hash table will return `$null`, which will be output as a falsey value. If `$g` is 36 characters in length, then the result of the .NET call will be output. If `$g` is not a valid .NET GUID (in any form), then it will output `$null` as a falsey value. Otherwise it will output a .NET GUID object as a truthy value - the only way that can be output is if it matches the requested format of the challenge. ### Examples Here I am encapsulating the script call in parens and explicitly casting as a Boolean for clarity. ``` PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC-1326-4C79-8EBC-94908DA8B034') True PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC-1326-4C79-8EBC-94908DA8B034D') False PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC13264C798EBC94908DA8B034') False ``` [Answer] ## Emacs Lisp, 236 Bytes ``` (lambda(s)(and(eq(string-bytes s)36)(let((l(string-to-list s))(i 0)(h '(8 13 18 23))(v t))(dolist(c l v)(set'v(and v(if(member i h)(and v(eq c 45))(or(and(> c 47)(< c 58))(and(> c 64)(< c 91))(and(> c 96)(< c 123))))))(set'i(+ i 1)))))) ``` Ungolfed: ``` (lambda (s) (and (eq (string-bytes s) 36) ; check length (let ((l (string-to-list s)) (i 0) ; location of hyphens (h '(8 13 18 23)) (v t)) (dolist (c l v) (set 'v (and v (if (member i h) ; check if at hyphen position (and v (eq c 45)) ; check if hyphen (or (and (> c 47) (< c 58)) ; check if number (and (> c 64) (< c 91)) ; check if upper case letter (and (> c 96) (< c 123)))))) ; check if lower case letter (set 'i (+ i 1)))))) ; increment ``` [Answer] Due to [changes to the rules](https://codegolf.stackexchange.com/revisions/66496/18), this answer is no longer competitive :( # C, 98 ``` main(a,n){printf("%d",scanf("%8x-%4hx-%4hx-%4hx-%4hx%8x%n%c",&a,&a,&a,&a,&a,&a,&n,&a)==6&&n==36);} ``` Mostly fairly self explanatory. The `%n` format specifier gives the number of bytes read so far, which should be 36. `scanf()` returns the number of matched items, which should be 6. The final `%c` should not match anything. If it does, then there is trailing text, and `scanf()` will return 7. Compile with `-w` to suppress the pesky warnings (there are several). [Answer] # JavaScript ES6, 70 ~~83~~ **NOTE** thx to @Qwertiy for finding a bug (and suggesting some improvements and fixes) Thx @CᴏɴᴏʀO'Bʀɪᴇɴ 2 bytes saved Other 9 bytes saved simplifiying the length check (the complex way *was* shorter in the first draft, but not now) ``` u=>u.split`-`.every((h,l,u)=>u[4]&&-`0x${h}1`&&h.length-'40008'[l]==4) ``` **Explained** ``` u=>u.split`-` // make an array splitting at '-' .every( // for every element the following must be true (h,l,u)=> // h is the element, l is the index, u is the whole array u[4] // element 4 must be present (at least 5 element in array) && -`0x${h}1` // element must be a valid hex string with no extraneous blanks (else NaN that is falsy) // get requested length from index (8,4,4,4,12 sub 4 to put in 1 char) // a 6th elements will be rejected as undefined != 4 && h.length-'40008'[l]==4// then check element length ) ``` Test snippet ``` f=u=>u.split`-`.every((h,l,u)=>u[4]&&-`0x${h}1`&&h.length-'40008'[l]==4) console.log=x=>O.innerHTML+=x+'\n' ;[ ['0FCE98AC-1326-4C79-8EBC-94908DA8B034',true], ['0fce98ac-1326-4c79-8ebc-94908da8b034',true], ['0FCE98ac-1326-4c79-8EBC-94908da8B034',true], ['00000000-0000-0000-0000-000000000000', true], ['ffffffff-ffff-ffff-ffff-ffffffffffff', true], ['0GCE98AC-1326-4C79-8EBC-94908DA8B034',false], ['0FCE98AC-13264C79-8EBC-94908DA8B034',false], ['0FCE98AC-13264-C79-8EBC-94908DA8B034',false], ['0FCE98ACD-1326-4C79-8EBC-94908DA8B034',false], ['0FCE98AC-1326-4C79-8EBC',false], ['0FCE98AC-1326-4C79-8EBC-94908DA8B034-',false], ['00000000-0000-0000-000 -000000000000', false], ['0FCE98AC-1326-4C79-8EBC-94908DA8B034-123',false], ].forEach(x=>{ var t=x[0], r=f(t), k=x[1] console.log('Test '+t+' result '+r+(r==k?' ok':' fail')) }) ``` ``` <pre id=O></pre> ``` [Answer] Due to [changes to the rules](https://codegolf.stackexchange.com/revisions/66496/18), this answer is no longer competitive :( # Pure Bash (no external utilities), 78 ``` printf -vv %8s-%4s-%4s-%4s-%12s p=${v// /[[:xdigit:]]} [ "$1" -a ! "${1/$p}" ] ``` Takes input from the command line. * The `printf` builds the following string `- - - -`. * The `p=` line transforms this to the following pattern: `[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]`. Note this looks an awful lot like a regular expression. However, it is not in this context. It is a pattern for [shell pattern matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html). This is similar *in concept* to a regular expression, but is a different construct (and syntax). * The last line checks if + the input is non-empty + if pulling the pattern out of the input string produces an empty string Idiomatic to shell, a return code of 0 indicates success/TRUE and 1 indicates failure/FALSE. The return code may be inspected with `echo $?` after running the script. [Answer] # Jolf, 32 bytes Try it [here!](http://conorobrien-foxx.github.io/Jolf/#code=IGVHaSctRE4mYkgqMjg9bEguWzgsNCw0LDQsMTJdU30) ``` eGi'-DN&bH*28=lH.[8,4,4,4,12]S} e Property "e"very of next object Gi'- Split i at hyphen DN } every comparison function & logical conjugation of next two arguments bH*28 base 16 of H (first arg); is NaN (falsey) if invalid = equality of next two items lH the length of H (first arg) . S the Sth (index) member of the object inbetween [8,4,4,4,12] array of lengths ``` Because of an error in my code, this is longer than it should be. :( `[8,4,4,4,12]` *should* be the same as `{8444*26}`, but `}` is also the closing of a function :P [Answer] # [MATL](http://esolangs.org/wiki/MATL), 55 bytes ``` jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$ ``` I refrained from using the `Yb` function (`strsplit`) because it's somewhat similar to `regexp(..., 'split')`. This only uses indexing and character comparisons. ### Example ``` >> matl > jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$ > > This is a test 0 >> matl > jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$ > > D293DBB2-0801-4E60-9141-78EAB0E298FF 1 ``` ### Explanation ``` jt % input string, duplicate tn36=? % if length is 36 [9,5,5,5]XsXK % build and copy indices of required '-' positions )45=? % if those entries are indeed '-' 36:Km~) % logical index of remaining positions 4Y2'A':'F'h % allowed chars in those positions m? % if all those entries are legal: do nothing } % else F % false value ] % end ] % end ] % end N~ % true if stack is empty 1$ % display last result only ``` [Answer] ## CJam, ~~52~~ 42 bytes ``` qeu__{A7*)<},\'-/83 3b{)4*}%.{\,=}[1]5*=*= ``` [Try it online](http://cjam.aditsu.net/#code=qeu__%7BA7*)%3C%7D%2C%5C%27-%2F83%203b%7B)4*%7D%25.%7B%5C%2C%3D%7D%5B1%5D5*%3D*%3D&input=0FCE98aC-1326-4C79-8EBC-94908DA8B02F). Outputs the original string if true, outputs empty string if false ([this is allowed](http://meta.codegolf.stackexchange.com/a/5062/36670)). Explanation: ``` qeu__ e# Take input, make 2 copies {A7*)<},\ e# Remove invalid characters from first copy '-/ e# Split top of stack on '- 83 3b{)4*}% e# Array of group lengths: [8 4 4 4 12] .{\,=}[1]5*= e# Compare two arrays, return true if group lengths are correct *= e# Multiply this value by original string (0 = empty string, 1 = same string) ``` [Answer] # Julia, 86 bytes ``` s->(t=split(s,"-");map(length,t)==[8,4,4,4,12]&&all(i->!isnull(tryparse(Int,i,16)),t)) ``` This is an anonymous function that accepts a string and returns a boolean. To call it, give it a name, e.g. `f=s->...`. Ungolfed: ``` function f(s::AbstractString) # Split the input into an array on dashes t = split(s, "-") # Ensure the lengths are appropriate ok1 = map(length, t) == [8, 4, 4, 4, 12] # Ensure each element is a valid hexadecimal number ok2 = all(i -> !isnull(tryparse(Int, i, 16)), t) return ok1 && ok2 end ``` [Answer] ## C# 196 bytes ``` using System.Linq;class P{bool T(string v){var r=v.Length==36;for(var i=0;i<v.Length;i++)r&=new[]{8,13,18,23}.Any(t=>t==i)?v[i]=='-':v[i]>47&&v[i]<58|v[i]>64&&v[i]<71|v[i]>96&&v[i]<103;return r;}} ``` Ungolfed: ``` using System.Linq; class P { public bool T(string v) { var r = v.Length == 36; for (var i = 0; i < v.Length; i++) r &= new[] { 8, 13, 18, 23 }.Any(t => t == i) ? v[i] == '-' : v[i] > 47 && v[i] < 58 | v[i] > 64 && v[i] < 71 | v[i] > 96 && v[i] < 103; return r; } } ``` Method `T` can be invoked with any non-null string and will return `true` for valid GUID's, `false` otherwise. This is a constant-time validation; at the cost of three chars you can early-exit the method (change `i < v.Length` to `i < v.Length && r`). Will try to get the bytecount down further later. I've obviously left out the [`Guid.ParseExact`](https://msdn.microsoft.com/en-us/library/system.guid.parseexact(v=vs.110).aspx) way because where's the fun in that? Here it is, without much attempt to golf it down further in **86 bytes**: ``` using System;class P{bool T(string v){Guid x;return Guid.TryParseExact(v,"D",out x);}} ``` Ungolfed: ``` using System; class P { bool T(string v) { Guid x; return Guid.TryParseExact(v, "D", out x); } } ``` [Answer] # Python 2, ~~99~~ 112 bytes ``` def f(u): try:u=u.split()[0];int(u.replace('-',''),16);print[8,4,4,4,12]==map(len,u.split('-')) except:print 0 ``` On a valid input, it prints `True`. On an invalid input it prints `False` or `0`, depending on why it was invalid. `False` and `0` are both falsey in Python. The function has to check 3 things: * Every non-hyphen character is a digit or is in `ABCDEF` * There are exactly 4 hyphens * There are 8 characters before the first hyphen, 12 after the last, and 4 between any other two Here's a breakdown to show how it checks for them. It's slightly out of date but I'm hungry so I'll update it later. ``` def f(u): try: int(u.replace('-',''),16) # Remove all hyphens from the string and parse what's # left as a base 16 number. Don't do anything with this # number, but throw an exception if it can't be done. return[8,4,4,4,12]==map(len,u.split('-')) # Split the string at each hyphen and # get the length of each resulting # string. If the lengths == [8,4,4,4,12], # there are the right number of groups # with the right lengths, so the string # is valid. except: return 0 # The only way to get here is if the string (minus hyphens) couldn't be # parsed as a base 16 int, so there are non-digit, non-ABCDEF characters # and the string is invalid. ``` [Answer] ## Python 2, 57 bytes [Thank goodness for built-in!](https://docs.python.org/2/library/uuid.html) - make sure to enclose strings in quotes. ``` import uuid try:uuid.UUID(input());print 1 except:print 0 ``` [Answer] ## Pyth, 39 bytes ``` &&!+1xzd.xi:zK\-k16ZqxKc+zK1mid36"8dinz ``` Try it [here](http://pyth.herokuapp.com/?code=%26%26%21%2B1xzd.xi%3AzK%5C-k16ZqxKc%2BzK1mid36%228dinz&input=0FCE98ac-1326-4c79-8EBC-94908da8Baa&debug=0). [Answer] ## [Perl 6](http://perl6.org), ~~ 83 ~~ 67 bytes ``` # 83 bytes { ( my@a=.uc.split('-') ).map(*.comb)⊆('0'..'9','A'..'F') && @a».chars~~(8,4,4,4,12) } ``` ``` # 67 bytes { ( $/=.split('-') ).map({:16($_)//|()})==5 && $/».chars~~(8,4,4,4,12) } ``` ( counts do not include newlines or indents as they are not needed ) usage: ``` # give it a name my &code = {...} say map &code, « D293DBB2-0801-4E60-9141-78EAB0E298FF 0FCE98AC-1326-4C79-8EBC-94908DA8B034 0fce98ac-1326-4c79-8ebc-94908da8b034 0FCE98ac-1326-4c79-8EBC-94908da8B034 00000000-1326-4c79-8EBC-94908da8B034 »; # (True True True True True) say map &code, « 0GCE98AC-1326-4C79-8EBC-94908DA8B034 '0FCE98AC 1326-4C79-8EBC-94908DA8B034' 0FCE98AC-13264C79-8EBC-94908DA8B034 0FCE98AC-13264-C79-8EBC-94908DA8B034 0FCE98ACD-1326-4C79-8EBC-94908DA8B034 0FCE98AC-1326-4C79-8EBC-94908DA8B034- 0FCE98AC-1326-4C79-8EBC-94908DA8B034-123 »; # (False False False False False False False) ``` [Answer] ## Common Lisp - 161 ``` (lambda(s &aux(u(remove #\- s)))(and(=(length s)36)(=(length u)32)(every(lambda(p)(char=(char s p)#\-))'(8 13 18 23))(ignore-errors(parse-integer u :radix 16)))) ``` The returned value if true is the hash, as a number, which is a useful result to have. ### Ungolfed ``` (defun uuid-p (string &aux (undashed (remove #\- string))) (and ;; length of input string must be 36 (= (length string) 36) ;; there are exactly 4 dashes (= (length undashed) 32) ;; We check that we find dashes where expected (every (lambda (position) (char= (char string position) #\-)) '(8 13 18 23)) ;; Finally, we decode the undashed string as a number in base 16, ;; but do not throw an exception if this is not possible. (ignore-errors (parse-integer undashed :radix 16)))) ``` [Answer] ## F# 44 characters ``` fun s->System.Guid.TryParseExact(s,"D")|>fst ``` In F#, functions with `out` parameters can be called by omitting the out parameter; its value at return will be combined with the function's true return value into a tuple. Here, the tuple is piped to the `fst` function, which returns its first member, which in this case is the Boolean return value of TryParseExact, indicating the success or failure of the call. As a check for the correct format, we return `true` only if the string is 36 characters long. Before I saw RobIII's C# answer, I had not thought of using TryParseExact, so my answer was to have been three characters longer: ``` fun s->System.Guid.TryParse s|>fst&&s.Length=36 ``` [`TryParse(string, Guid)`](https://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.110).aspx) accepts input in the following formats: ``` 00000000000000000000000000000000 00000000-0000-0000-0000-000000000000 {00000000-0000-0000-0000-000000000000} (00000000-0000-0000-0000-000000000000) {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} ``` Of these, only the second is 36 characters long. [Answer] ## Python 2, ~~93~~ ~~89~~ 85 bytes ``` lambda u:(set(u)<=set("-0123456789abcdefABCDEF"))*map(len,u.split("-"))==[8,4,4,4,12] ``` The `map()` call guarantees that the sections are of the right lengths, and the `all()` tests each character for being either a hyphen or an arbitrary-case hex digit. The generator expression is testing each character by iterating through that entire string, so it's not the most performant method, I'm afraid, but it should satisfy the test cases: ``` >>> f=lambda u:(set(u)<=set("-0123456789abcdefABCDEF"))*map(len,u.split("-"))==[8,4,4,4,12] >>> testcases = """\ ... D293DBB2-0801-4E60-9141-78EAB0E298FF ... 0FCE98AC-1326-4C79-8EBC-94908DA8B034 ... 0fce98ac-1326-4c79-8ebc-94908da8b034 ... 0FCE98ac-1326-4c79-8EBC-94908da8B034 ... 00000000-0000-0000-0000-000000000000""".splitlines() >>> failcases = """\ ... 0GCE98AC-1326-4C79-8EBC-94908DA8B034 ... 0FCE98AC 1326-4C79-8EBC-94908DA8B034 ... 0FCE98AC-13264C79-8EBC-94908DA8B034 ... 0FCE98AC-13264-C79-8EBC-94908DA8B034 ... 0FCE98ACD-1326-4C79-8EBC-94908DA8B034 ... 0FCE98AC-1326-4C79-8EBC-94908DA8B034- ... 0FCE98AC-1326-4C79-8EBC-94908DA8B034-123 ... 00000000-0000-0000-000 -000000000000 ... 00000000-0000-0000- 000-000000000000""".splitlines() >>> all(f(u) for u in testcases) True >>> any(f(u) for u in failcases) False >>> ``` [Answer] ## SAS, ~~171~~ ~~144~~ 141 ``` data;infile stdin;file stdout;input a$9b$14c$19d$24;e=(a!!b!!c!!d='----')*length(_infile_)=36*(1-missing(put(input(compress(_infile_,,'adk'),$hex32.),$hex32.)));put e;run; ``` Actually uses stdin and stdout - one of the lesser-known features of this particular language. Works for the examples given so far, but possibly not in all cases. Can probably be improved upon. Better approach - one character at a time: ``` data;infile stdin;file stdout;do i=1 to 37;input@i c$1.@;a+ifn(i in(9,14,19,24),c='-',n(input(c,hex.))-36*(i>36&c^=''));end;b=a=36;put b;run; ``` Golfed another 6 characters off the central expression! Ungolfed: ``` data; infile stdin; file stdout; do i=1 to 37; input@i c$1.@; a+ifn(i in(9,14,19,24),c='-',n(input(c,hex.))-36*(i>36&c^='')); end; b=a=36; put b; run; ``` This generates quite a few warnings and notes in the log, but it doesn't print them to stdout or stderr, so I think this is fair game. [Answer] # C, 391 bytes ``` #include<stdio.h> #include<string.h> #include<ctype.h> #define F printf("0") #define T printf("1") #define E return 0 main(){char s[99],*t;int k=1,l,i;scanf("%99[^\n]",s);if(s[strlen(s)-1]=='-'){F;E;}t=strtok(s,"-");while(t!=NULL){for(i=0,l=0;t[i]!=0;i++,l++){if(!isxdigit(t[i])){F;E;}}if((k==1&&l!=8)||((k>1&&k<5)&&l!=4)||(k==5&&l!=12)){F;E;}k++;t=strtok(NULL,"-");}if(k==6){T;E;};F;} ``` [Answer] # MATLAB, 126 bytes ``` function f(a) b='-';if length(a)==36&&a(9)==b&&a(13)==b&&a(17)==b&&a(21)==b;a(a==b)=[];if any(isnan(hex2dec(a)));0;end;1;end;0 ``` [Answer] ## Python 3, 134 bytes ``` def a(i): try:l=[1+int(k,16)and(len(k)==c)for k,c in zip(i.split("-"),[8,4,4,4,12])];return(len(l)==5)&(0 not in l) except:return 0 ``` int(k,16) tries to cast k to a base-16 int. On a character other than 0-9a-fA-F- it fails, in which case we return 0, which is falsy. Add 1 to that int and we get a guaranteed truthy value - we've stripped away all hyphens with str.split() so we can't get the value -1 and all non-0 ints are truthy. [Answer] # C function, 102 [A rule change disallowed my previous c `scanf()`-based answer](https://codegolf.stackexchange.com/revisions/66496/18), so here's another c answer [using `isxdigit()` which I think should be allowed to compete](https://codegolf.stackexchange.com/questions/66496/check-if-a-uuid-is-valid-without-using-regexes#comment161487_66496): ``` i;f(char *s){for(i=8;i<24;i+=5)s[i]=s[i]-45?1:s[i]+3;for(i=0;isxdigit(s[i]);i++);return i==36&&!s[i];} ``` [Try it online.](https://ideone.com/aQBeD8) * Check for `-` characters (ASCII 45) at the relevant positions - if so, replace them with `0`s (ASCII 48 (=45+3)) * Walk the string checking each char with [`isxdigit()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/isxdigit.html) * Return TRUE if string length is 36 and final character is NUL. [Answer] ## Batch, ~~148~~ 139 + 2 = ~~150~~ 141 bytes ``` @set/pu= @for %%d in (1 2 3 4 5 6 7 8 9 A B C D E F)do @set u=!u:%%d=0! @if -!u!==-00000000-0000-0000-0000-000000000000 exit/b0 @exit/b1 ``` Added 2 bytes because you need to use the `/v` switch to `CMD.EXE`. Exits with ERRORLEVEL 0 on success, 1 on failure. Edit: Saved some bytes mainly because `:=` is case insensitive but there were other tweaks too. [Answer] ## Java, 345 bytes ``` interface q{static void main(String[]a){int i=-1;char[]b=a[0].toCharArray();java.io.PrintStream u=System.out;if(b.length>36||b.length<36)u.print(1<0);if(b[8]!='-'||b[13]!='-'||b[18]!='-'||b[23]!='-')u.print(1<0);while(++i<b.length){if(i!=8&&i!=13&&i!=18&&i!=23){if(!((b[i]>='0'&&b[i]<='F')||(b[i]>='a'&&b[i]<='f')))u.print(1<0);}}u.print(1>0);}} ``` Input is first command line argument. Output is error code(0 means valid UUID, 1 means not valid) Ungolfed with comments: ``` interface q { static void main(String[] a) { int i = -1; // Index char[] b = a[0].toCharArray(); // Characters from input java.io.PrintStream u = System.out; // STDOUT if (b.length > 36||b.length < 36) // If input length is not 36 u.print(1<0); // Invalid if (b[8]!='-'||b[13]!='-'||b[18]!='-'||b[23]!='-') // If hasn't got separators at correct positions u.print(1<0); // Invalid while (++i<b.length) { // Iterate over all characters if (i!=8 && i!=13 & i!=18 && i!=23) { // If not at separator indexes if ( !( (b[i]>='0'&&b[i]<='F') || (b[i]>='a'&&b[i]<='f') )) // If incorrect hexadecimal number u.print(1<0); // Invalid } } u.print(1>0); // Valid } } ``` EDIT: Didn't notice the STDOUT part. Oops, fixed now. [Answer] # Swift 3, 50 bytes Pass in a string `s` ``` import Foundation print(UUID(uuidString:s) != nil) ``` [Answer] # PHP, 109 Bytes prints 1 for true and 0 for false ``` for($t=($l=strlen($a=$argn))==36;$i<$l;$i++)$t*=$i>7&$i<24&!($i%5-3)?$a[$i]=="-":ctype_xdigit($a[$i]);echo$t; ``` `$i>7&$i<24&!($i%5-3)` is 5 Bytes shorter then `in_array($i,[8,13,18,23])` 112 Bytes ``` echo array_filter(str_split($argn),function($i){return!ctype_xdigit($i);})==[8=>"-",13=>"-",18=>"-",23=>"-"]?:0; ``` 113 Bytes ``` echo array_diff(str_split(strtolower($argn)),array_map(dechex,range(0,15)))==[8=>"-",13=>"-",18=>"-",23=>"-"]?:0; ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 167 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 20.875 bytes ``` ɽ\-€:@»S₌»f4*⁼ßk6vF¤J≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJ+PSIsIiIsIsm9XFwt4oKsOkDCu1PigozCu2Y0KuKBvMOfazZ2RsKkSuKJiCIsIiIsIjBGQ0U5OEFDLTEzMjYtNEM3OS04RUJDLTk0OTA4REE4QjAzND0+IDFcbjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMD0+IDFcbjBmY2U5OGFjLTEzMjYtNGM3OS04ZWJjLTk0OTA4ZGE4YjAzND0+IDFcbjBGQ0U5OGFjLTEzMjYtNGM3OS04RUJDLTk0OTA4ZGE4QjAzND0+IDFcblxuezBGQ0U5OEFDLTEzMjYtNEM3OS04RUJDLTk0OTA4REE4QjAzNH09PiAwXG4wR0NFOThBQy0xMzI2LTRDNzktOEVCQy05NDkwOERBOEIwMzQ9PiAwXG4wRkNFOThBQyAxMzI2LTRDNzktOEVCQy05NDkwOERBOEIwMzQ9PiAwXG4wRkNFOThBQy0xMzI2NEM3OS04RUJDLTk0OTA4REE4QjAzND0+IDBcbjBGQ0U5OEFDLTEzMjY0LUM3OS04RUJDLTk0OTA4REE4QjAzND0+IDBcbjBGQ0U5OEFDRC0xMzI2LTRDNzktOEVCQy05NDkwOERBOEIwMzQ9PiAwXG4wRkNFOThBQy0xMzI2LTRDNzktOEVCQy05NDkwOERBOEIwMzQtPT4gMFxuMEZDRTk4QUMtMTMyNi00Qzc5LThFQkMtOTQ5MDhEQThCMDM0LTEyPT4gMFxuMEZDRTk4QUMxMzI2NEM3OThFQkM5NDkwOERBOEIwMzQ9PiAwIl0=) Bitstring: ``` 00100110000000110100100100111101001111011101001010000101101010001100111010011110101100110110111011000100010111110110101000111001111000100010111010111000111011100101010 ``` ``` ɽ\-€:@»S₌»f4*⁼ßk6vF¤J≈­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠⁠⁠⁠⁠⁠⁠⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‏​⁡⁠⁡‌⁢⁢​‎‏​⁢⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌­ ɽ\-€: # ‎⁡to lowercase, split on "-" and push two copies to the stack @ ⁼ # ‎⁢does the vectorized length equal »S₌» # ‎⁣the compressed number 21113 f4* # ‎⁤as a list of digits each multiplied by 4 ßk6vF # ‎⁢⁡if so, remove all of the characters that are in the string "0123456789abcdef" # ‎⁢⁢This is NOT regex, vyxal has regex elements ¤J≈ # ‎⁢⁣append an empty string and check if all elements are equal 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] ## Java, ~~172 bytes~~ 168 bytes (Thanks Wheat Wizard) Kinda cheaty since I used java.util.UUID, but here goes: ``` import java.util.UUID;class ValidUUID{public static void main(String[] a){try{UUID.fromString(a[0]);System.out.println(1);}catch(Exception e){System.out.println(0);}}} ``` Ungolfed version: ``` import java.util.UUID; class ValidUUID { public static void main(String[] a) { try { UUID.fromString(a[0]); System.out.println(1); } catch(Exception e) {System.out.println(0);} } } ``` ]
[Question] [ This is my first challenge on ppcg! ### Input A string consisting of two different ascii characters. For example ``` ABAABBAAAAAABBAAABAABBAABA ``` ### Challenge The task is to decode this string following these rules: 1. Skip the first two characters 2. Split the rest of the string into groups of 8 characters 3. In each group, replace each character with `0` if that character is the same as the first character of the original string, and with `1` otherwise 4. Now each group represents a byte. Convert each group to character from byte char code 5. Concatenate all characters ### Example Let's decode the above string. ``` AB AABBAAAA AABBAAAB AABBAABA ^^ ^ ^ ^ | | | | | \---------|---------/ | | Skip Convert to binary ``` Notice that `A` is the first character in the original string and `B` is the second. Therefore, replace each `A` with `0` and each `B` with `1`. Now we obtain: ``` 00110000 00110001 00110010 ``` which is `[0x30, 0x31, 0x32]` in binary. These values represent characters `["0", "1", "2"]` respectively, so the final output should be `012`. ### Scoring This is, of course, [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), which means make your code as short as possible. Score is measured in bytes. ### Constraints and IO format Standard rules apply. Here are some additional rules: * You can assume valid input + Input string consists of exactly two different characters + The first two characters are different + The minimal length of the input string is 2 characters + The length will always give 2 modulo 8 * You can assume the string will always consist only of printable ASCII characters + Both in the input and in the decoded string * Leading and trailing whitespace are allowed in the output (everything that matches `/\s*/`) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~76 71~~ 65 bytes -6 bytes thanks to Nitrodon! ``` ,>>,,[>>++++++++[-[->+<]<<<<[->+>-<<]>>[[-]>>+<<]>[->++<],>>]<.<] ``` [Try it online!](https://tio.run/##NYtRCoBACEQPtGsnkAG9hvhRQRALfQSd3zS2B@rMMG73el7Hs4@IDvRuQJsYGaGxc1IKxOyAGeVupSvNQj46L@wRoiKaU3x3ev29vA "brainfuck – Try It Online") Feels weird beating Python... [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~15~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ó║¥U⌂½íèäöñ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a2ba9d557faba18a8494a4&i=ABAABBAAAAAABBAAABAABBAABA%0A%0A+%09+%09+%09++%09%09+%09%09+++%09%09+%09%09%09++%09++%09%09+%09%09%09%09+%09%09+%09%09%09%09+%09%09+++%09++%09%09+%09%09+++%09%09++%09+%09&a=1&m=1) ~~Quick 'n' dirty approach. Working on improving it.~~ Improved it! ### Unpacked (13 bytes) and explanation ``` 2:/8/{{[Im:bm 2:/ Split at index 2. Push head, then tail. 8/ Split into length-8 segments. { m Map block over each segment: { m Map block over each character: [ Copy first two elements (below) in-place. I Index of character in first two characters. :b Convert from binary. Implicit print as string. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ¦¦Sk8ôJCçJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0LJDy4KzLQ5v8XI@vNzr/39HJ0dHJyAGATAN5Ts5AgA "05AB1E – Try It Online") -3 thanks to emigna. --- ``` Ù # Unique letters, in order they appear. v # For each... yN: # Push letter and index, replace in input. } # End loop. ¦¦ # Remove first x2. 8ô # Split into eighths. C # Convert to integer. ç # Convert to char. J # Join together entire result. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 67 bytes ``` s=>s.replace(/./g,x=(c,i)=>(x=x*2|c==s[1],Buffer(i<3|i&7^1?0:[x]))) ``` [Try it online!](https://tio.run/##XU3LCsIwELz7GT1IIrW1ehAkG0l@o1QoMSmR0pRGJYf@e0za4mtfM8vMsrf6WVsx6P6@7cxVegXeArXZIPu2FhLlWd6kDpBINQaKHLjNfhQAtiyqlD@UkgPS5DDq9fFSnHen0lUYYy9MZ00rs9Y0SKGEccZ46BgTLjtnCcarPzOhIWOFMREaMdJfXMTZSMgMk/DWF8/3Hfn4aXjuXw "JavaScript (Node.js) – Try It Online") ### How? We use two different syntaxes of the `Buffer` constructor: * [**`Buffer([n])`**](https://nodejs.org/docs/latest-v4.x/api/buffer.html#buffer_new_buffer_array) generates a buffer containing the sole byte **n** and is coerced to the corresponding ASCII character. Only the 8 least significant bits of **n** are considered. * [**`Buffer(n)`**](https://nodejs.org/docs/latest-v4.x/api/buffer.html#buffer_new_buffer_size) generates a buffer of **n** bytes. Therefore, `Buffer(0)` generates an empty buffer, which is coerced to an empty string. *Note: They both are deprecated in recent Node versions. `Buffer.from([n])` and `Buffer.alloc(n)` should be used instead.* ### Commented ``` s => // given the input string s s.replace(/./g, x = // initialize x to a non-numeric value (will be coerced to 0) (c, i) => ( // for each character c at position i in s: x = x * 2 | // shift x to the left c == s[1], // and append the new bit, based on the comparison of c with s[1] Buffer( // invoke the constructor of Buffer (see above): i < 3 | // if i is less than 3 i & 7 ^ 1 ? // or i is not congruent to 1 modulo 8: 0 // replace c with an empty string : // else: [x] // replace c with the ASCII char. whose code is the LSB of x ) // end of Buffer constructor )) // end of replace(); return the new string ``` [Answer] ## bash, ~~59~~ ~~58~~ 52 bytes ``` tr -t "$1" 01 <<<$1|cut -c3-|fold -8|sed 'i2i aP'|dc ``` [Try it online!](https://tio.run/##S0oszvj/v6RIQbdEQUnFUEnBwFDBxsZGxbAmubREQTfZWLcmLT8nRUHXoqY4NUVBPdMokysxQL0mJfn///8KFQoKFUAMAmAayq9QAAA) Thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack) for saving 6 bytes. This challenge works remarkably well with a series of coreutils (and `dc` to do the conversion and output at the end). First, we use ``` tr -t "$1" 01 <<<$1 ``` to transliterate the two characters in the input to zeroes and ones. The `-t` flag truncates the first argument to the length of the second, so this reduces to transliterating the first two characters in the input to `0` and `1`, which is what we want. Then, ``` cut -c3- ``` removes the first two characters, and ``` fold -8 ``` outputs 8 of the characters per line. Finally, the `sed` command turns each line into a `dc` snippet that reads the number as binary and outputs that byte. [Answer] # Z80 machine code on an Amstrad CPC, ~~32 31~~ 30 bytes ``` 000001 0000 (9000) ORG &9000 000002 9000 EB EX DE, HL 000003 9001 46 LD B, (HL) 000004 9002 23 INC HL 000005 9003 5E LD E, (HL) 000006 9004 23 INC HL 000007 9005 56 LD D, (HL) 000009 9006 1A LD A, (DE) 000010 9007 05 DEC B 000011 9008 13 INC DE 000012 9009 4F LD C, A 000014 900A Light 000015 900A 26 01 LD H, &01 000016 900C Last 000017 900C 13 INC DE 000018 900D 05 DEC B 000019 900E C8 RET Z 000021 900F Loop 000022 900F 1A LD A, (DE) 000023 9010 B9 CP C 000024 9011 28 01 JR Z, Lable 000025 9013 37 SCF 000026 9014 Lable 000027 9014 ED 6A ADC HL, HL 000028 9016 30 F4 JR NC, Last 000029 9018 7D LD A, L 000030 9019 CD 5A BB CALL &BB5A 000032 901C 18 EC JR Light ``` The code takes the instruction *replace each character with `0` if that character is the same as the first character of the original string, and with `1` otherwise* literally and doesn't ever bother to check that a character matches the second character in the input string. It just checks for same-as-first-character and different-from-first-character. I ran out of registers (the Z80 only has 7 easily usable 8-bit registers, the rest need longer instructions) so I put `&01` in `H`, along with using `L` to build up the ASCII character (I just realised it's unnecessary to initialise `L`, saving one byte). When `H` overflows into the Carry flag, the character in `L` is ready to be output. Luckily, there is a 16-bit `ADC` (**Ad**d with **C**arry) that does the job of a left-shift instruction. `(DE)` can only be read into `A` although `(HL)` can be read into any 8-bit register, so it was a compromise which one to use. I couldn't compare `(DE)` with `C` directly, so I had to load one into `A` first. The labels are just random words that start with `L` (a requirement of the assembler). * `A` the Accumulator - the only register that can do comparisons * `B` the counter register ~~for the instruction `DJNZ`: **D**ecrement (`B`) and **J**ump if **N**on **Z**ero~~. By rearranging the code, I was able to do the job of `DJNZ` with one fewer byte * `C` the first character in the input string * `D`, `E` as `DE` the address of the current input character * `H` the carry trigger (every 8th loop) * `L` the output character being built up [![enter image description here](https://i.stack.imgur.com/O0xT0m.png)](https://i.stack.imgur.com/O0xT0.png) [Answer] # J, ~~17~~ 13 Bytes ``` u:_8#.\2}.1{= ``` -4 thanks to FrownyFrog Old version: ``` u:_8#.\2&({.i.}.) ``` ### Explanation: ``` u:_8#.\2}.1{= = | Self classify, for each unique element x of y, compute x = y, element-wise 1{ | Second row 2}. | Drop 2 _8#.\ | Convert non-intersecting subarrays of length 8 from binary u: | Convert to characters ``` Examples: ``` = 'ABAABBAAAAAABBAAABAABBAABA' 1 0 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 1 1 0 0 1 1 0 1 0 1 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0 2}.1{= 'ABAABBAAAAAABBAAABAABBAABA' 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0 _8#.\2}.1{= 'ABAABBAAAAAABBAAABAABBAABA' 48 49 50 u:_8#.\2}.1{= 'ABAABBAAAAAABBAAABAABBAABA' 012 ``` [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` lambda s:[chr(int(`map(s.find,s)`[i:i+24:3],2))for i in range(7,3*len(s),24)] ``` [Try it online!](https://tio.run/##NYzBCoMwEAV/JXhx0wYPUSgEeoi/oYJpNXWLbkJiD/36NJZ24PGYy/j3vjiSyV77tJrtNhkWVXdfAiDtMG7GQ6ws0iQiHztUeJaNqgchObcuMGRILBh6zHAR9WmdCSIXsuFD8uEolGX1dEhgc8@/duCZVOhW6zbv4Ps/b/@uiw8 "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 71 bytes ``` function(s)intToUtf8(2^(7:0)%*%matrix((y=utf8ToInt(s))[-1:-2]==y[2],8)) ``` [Try it online!](https://tio.run/##K/qfk5lUlFhUqaCRm1qSkZ9SrMmVpmCj@z@tNC@5JDM/T6NYMzOvJCQ/tCTNQsMoTsPcykBTVUs1N7GkKLNCQ6PSthQoEZLvmVcCVKkZrWtopWsUa2tbGW0Uq2Ohqfk/TUPJ0cnR0QmIQQBMQ/lOjkqa/wE "R – Try It Online") Surprisingly golfy! First, converts the string to ascii code-points with `utf8ToInt`, saving it as `y`. Removing the first two characters with negative indexing is shorter than using `tail`. The array `y[-1:-2]==y[2]` is equivalent to the bits when `%*%` (matrix multiplication) is applied, but first we reshape that array into a `matrix` with `nrow=8`, converting from a linear array to byte groupings. Fortuitously, we can then convert to the ascii code points using matrix multiplication with the appropriate powers of 2, `2^(7:0)`, and then we convert the code points back to a string with `intToUtf8`. [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` a,b,*r=input();x=i=0 for c in r:i*=2;i|=a!=c;x+=1;x%8or print(end=chr(i&255)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P1EnSUeryDYzr6C0REPTusI209aAKy2/SCFZITNPocgqU8vWyDqzxjZR0TbZukLb1tC6QtUCKF1QlJlXopGal2KbnFGkkalmZGqqqfn/v6OTo6MTEIMAmIbynRwB "Python 3 – Try It Online") [Answer] # PHP, ~~73~~ 71 bytes ``` while($s=substr($argn,-6+$i+=8,8))echo~chr(bindec(strtr($s,$argn,10))); ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/a7b0f18ec96488bd4e958230a52dd3ad7448f5b2). golfings: * start index at `-6` and pre-increment by `8` * exploit that `strtr` ignores excessive chars in the longer parameter (no `substr` needed) * translating to `10` and then inverting needs no quotes -> -1 byte * invert character instead of ascii code --> `~` serves as word boundary -> -1 byte. [Answer] # Pyth, ~~20~~ 9 bytes ``` CittxLQQ2 ``` Saved 11 bytes thanks to FryAmTheEggman. [Try it here](https://pyth.herokuapp.com/?code=CittxLQQ2&input=%22ABAABBAAAAAABBAAABAABBAABA%22&debug=0) ### Explanation ``` CittxLQQ2 xLQQ Find the index of each character in the string. tt Exclude the first 2. i 2 Convert from binary. C Get the characters. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~82~~ 79 bytes ``` ->s{s[2..-1].tr(s[0,2],'01').chars.each_slice(8).map{|s|s.join.to_i(2).chr}*''} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ujjaSE9P1zBWr6RIozjaQMcoVkfdwFBdUy85I7GoWC81MTkjvjgnMzlVw0JTLzexoLqmuKZYLys/M0@vJD8@U8MIpLKoVktdvfa/Y5B7GFgHSJFCQWlJsUJadHFs7f//jk6Ojk5ADAJgGsp3cgQA "Ruby – Try It Online") [Answer] # Japt, 11 bytes ``` ¤£bXÃò8 ®Íd ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=pKNiWMPyOCCuzWQ=&input=IkFCQUFCQkFBQUFBQUJCQUFBQkFBQkJBQUJBIg==) --- ## Explanation ``` ¤ :Slice from the 3rd character £ à :Map over each X bX : Get the first 0-based index of X in the input ò8 :Split to an array of strings of length 8 ® :Map Í : Convert from base-2 string to base-10 integer d : Get the character at that codepoint ``` [Answer] ## PHP + GNU Multiple Precision, 63 61 ``` <?=gmp_export(gmp_init(substr(strtr($argn,$argn,"01"),2),2)); ``` sadly the GMP extention is not default activated (but shipped). Run like this: ``` echo "ABABABAAAAABABAAAAAABAABBAABAAAABBABAAABBB" | php -F a.php ``` [Answer] # Java 8, ~~143~~ ~~142~~ 141 bytes ``` s->{char i=47;for(;++i<50;)s=s.replace(s.charAt(i%2),i);for(i=2;i<s.length();)System.out.print((char)Long.parseLong(s.substring(i,i+=8),2));} ``` -1 byte thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##LY/BasMwDIbvewpRGFgkNSNsrOB6kJy3XnocO7ium6pLnWA5hVHy7JmTRljYEr/k/7uYm1lfjr@jbQwzfBny9ycA8tGFk7EOdlMJcGvpCFbsYyBfA6NK3SFlOhxNJAs78KBh5PXH3Z5NANKv7@rUBqGyjLZvLwpZswyua9JawXISlVHQc4E54awkXSjasmycr@NZoML9H0d3lW0fZZd@jkJMY/jZ@lp2JrCbXmkZ9weerQnKKdMbzAtENYzqYbHrD02yuDidWa6JdMH5/jH4oPTSilVZlWWVcor5XuqqXC3Yw/gP) **Explanation:** ``` s->{ // Method with String parameter and no return-type char i=47; // Index character, starting at 47 for(;++i<50;) // Loop 2 times s.replace(s.charAt(i%2),i) // Replace first characters to 0, second characters to 1 for(i=2;i<s.length();) // Loop `i` from 2 upwards over the String-length System.out.print( // Print: (char) // As character: Long.parseLong( // Convert Binary-String to number s.substring(i,i+=8) // The substring in range [i,i+8), ,2));} ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~99~~ 86 bytes ``` lambda s:[chr(int(str(list(map(s.find,s[i:i+8])))[1::3],2))for i in range(2,len(s),8)] ``` [Try it online!](https://tio.run/##NYxBCsIwEEWvkl1nMAi2mxJwkV4jZhFtYwfSachk4@mjFf3weLzNz6@67jy0eL21FLb7HJQY91gLEFeQWiCRVNhCBjlH4lmLI0On0SOiuxgzeN0jxr0oUsSqBH4u0Ou0MAjqEX3L5biK0NnJ2unDsa9/Pf3bdojtDQ "Python 3 – Try It Online") Thanks to ASCII-only for basically the whole thing really [Answer] # APL+WIN, 30 bytes Index origin 0. Prompts for input of string ``` ⎕av[2⊥¨(+\0=8|⍳⍴b)⊂b←2↓s≠↑s←⎕] ``` Explanation: ``` s≠↑s←⎕ prompts for string and creates binary vector not equal to first character b←2↓s drops first two elements of binary (+\0=8|⍳⍴b)⊂ splits binary into groups of 8 2⊥¨ converts each group to decimal ⎕av[...] displays decoded characters ``` [Answer] # [Red](http://www.red-lang.org), 110 bytes ``` func[s][t: 0 i: 128 foreach c next next s[if c = s/2[t: t + i]i: i / 2 if i = 0[prin to-char t t: 0 i: 128]]] ``` [Try it online!](https://tio.run/##TYzBCsMgDIbvfYofr6PY9TQKO@gj7CoOilXqxQ61sLd3UXtYIAlJvi/RbuVlN6UHtxR3BqOSVnnBBL/gPj/gjmhXs8Mg2G/uJSnvaPFE4nOFM27wmgQPjhl09HSc1Cf6gHyMZl8jQX9vtdYoDkxIISRljdavWQo2VDuDvflYgw0dbxAh3Wq9i826ZtLLDw "Red – Try It Online") ## Explanation: A simple straightforward solution, no builtins. ``` f: func [s] [ ; s is the argument (string) t: 0 ; total - initially 0 i: 128 ; powers of 2, initially 0 b: s/2 ; b is the second charachter foreach c next next s [ ; for each char in the input string after the 2nd one if c = b [t: t + i] ; if it's equal to b than add the power of 2 to t i: i / 2 ; previous power of 2 if i = 0 [ ; if it's 0 prin to-char t ; convert t to character and print it t: 0 ; set t to 0 i: 128 ; i to 128 ] ] ] ``` [Answer] # Google Sheets, 123 bytes ``` =ArrayFormula(Join("",IfError(Char(Bin2Dec(Substitute(Substitute(Mid(A1,3+8*(Row(A:A)-1),8),Left(A1),0),Mid(A1,2,1),1))),"" ``` Input is in cell `A1`. Google will automatically add `)))` to the end of the formula. Explanation: * `Mid(A1,3+8*(Row(A:A)-1),8)` grabs chunks of characters 8 at a time, starting with the third. * `Substitute(Mid(~),Left(A1),0)` replaces each instance of the first character with 0. * `Substitute(Substitute(~),Mid(A1,2,1),1)` replaces the second character with 1. * `Char(Bin2Dec(Substitute(~)))` converts the chunk to decimal and then to ASCII. * `IfError(Char(~,""))` corrects all the errors that result from the fact that `Row(A:A)` returns *far* more values than we so `Bin2Dec` gives us a lot of zero values and `Char` errors out on zero. * `ArrayFormula(Join("",IfError(~)))` joins together all the `Char` results and `ArrayFormula` is what makes the `Row(A:A)` return an array of values instead of just the first value. [Answer] # [Haskell](https://www.haskell.org/), 75 bytes ``` f[_,_]="" f(z:o:s)=toEnum(sum[2^b|(b,c)<-zip[7,6..0]s,c==o]):f(z:o:drop 8s) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/Py06Xic@1lZJiStNo8oq36pY07Yk3zWvNFejuDQ32iguqUYjSSdZ00a3KrMg2lzHTE/PILZYJ9nWNj9W0wqiJaUov0DBoljzf25iZp6CrUJBUWZeiYKKgkaagpKjk6OjExCDAJiG8p0clTT/AwA "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~61~~ 42 bytes -19 bytes thanks to benj2240 ``` ->s{[s[2..-1].tr(s[0,2],"01")].pack("B*")} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664Oro42khPT9cwVq@kSKM42kDHKFZHycBQSTNWryAxOVtDyUlLSbP2f0FpSbFCWrSSo5OjoxMQgwCYhvKdHJVi/wMA "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-lp`, 34 bytes ``` #!/usr/bin/perl -lp s%.%1-/^$&/%eg;$_=pack'B*',s/..//r ``` [Try it online!](https://tio.run/##K0gtyjH9/79YVU/VUFc/TkVNXzU13Vol3rYgMTlb3UlLXadYX09PX7/o/39HJ0dHJyAGATAN5Ts5/ssvKMnMzyv@r5tTAAA "Perl 5 – Try It Online") [Answer] ## REXX, 41 bytes ``` arg a+2 b say x2c(b2x(translate(b,01,a))) ``` [Try it online!](https://tio.run/##K0qtqPj/P7EoXSFR20ghias4sVKhwihZI8moQqOkKDGvOCexJFUjScfAUCdRU1Pz////jk6Ojk5ADAJgGsp3cgQA "Rexx (Regina) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes ``` i=input() f=''.join('10'[x==i[0]]for x in i[2:]) while f:print chr(int(f[:8],2));f=f[8:] ``` [Try it online!](https://tio.run/##LYdBCsMgEADveYXkokIpqadg2YN@Y/FUurilrCKGpq@3aenAMEx991zEjcHAUrdu7ESg9flRWIy@LBp3AMYlJSpN7YpFMTqf7PTK/Lwr8rWxdHXLzRw1hH5NJ2ftlYBw9WmMOcQQ4uGXX/8fw/wB "Python 2 – Try It Online") Not the shortest - just an alternative way. Following version prints the output on one line for 98 bytes although the rules state that trailing whitespace is allowed.: ``` i=input();f=''.join('10'[x==i[0]]for x in i[2:]);o="" while f:o+=chr(int(f[:8],2));f=f[8:] print o ``` [Try it online!](https://tio.run/##LYzBCsMgEETv@QrxotJSUk/BsAf9jcVTqbiluCKWpl9vk9KB4THvMPXTMxc7BgGV@urarAmUujyYilbXWeEGQDjHmLiJTVARhNZFszJIOb0zPe8iOT7BLTdNpeuEbolna46jhIuLU227FzyG9MH7sPfIj/8dvPwC "Python 2 – Try It Online") [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 158 bytes ``` using System.Linq;a=>new string(a.Skip(2).Where((c,i)=>(i-2)%8==0).Select((c,i)=>(char)a.Skip(8*i+2).Take(8).Select((d,j)=>d!=a[0]?1<<7-j:0).Sum()).ToArray()) ``` [Try it online!](https://tio.run/##RVBNS8QwED2bXxEPQqJtWfdisU2lFTwpCBX2sOxhSNM2u22iSaos4m@vqRvWDMN8vTfMC7cxt3yerFQdro/WiTF5luojQ4gPYC1@NbozMKJvhKwDJzn@1LLBLyAVsc542naHwXSWekhY8DQpnp@GET7FAreY4RlYocRX6BFI6oN8J2uabHphBCE8kpQVRMZrepUytqJJLQbB3XnCezA00NJreeOpb3AQJP1HNtHeI5tLBtvV7uE2z@/i/f2yaRoJ9XBdGgNHn84ZarURwHsclCx3YanOci6CnketrB5EsjHSCf87grQLg9IM/Sw2z2VVlpX35f3FUFflLw "C# (Visual C# Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 40 bytes ``` s/(.)(.)//;$_=pack'B*',eval"y/$1$2/01/r" ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0NPE4j09a1V4m0LEpOz1Z201HVSyxJzlCr1VQxVjPQNDPWLlP7/d3RydHQCYhAA01C@k@O//IKSzPy84v@6BQA "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 95 bytes ``` s.substring(2).replace(s(0),'0').replace(s(1),'1').grouped(8).map(Integer.parseInt(_,2).toChar) ``` [Try it online!](https://tio.run/##TY0xC8IwFIRn@ytClyZQQuvk4pA6Ofgb5DV9tpWaPPJSEcTfHqM4eHAc9w13bGGB5Psr2ihOMDuBj4huYGGIxLPY3GERLPaiNJ0xXfZH3/z1zpSJNa89xzC7UW6VDkgLWJQsG1VXTfVP2kzaTMbgV8JB7pS@Acmjizhi0ASBMRd5rvNQ9IcJgkr64gOCnSTli6iKV3oD "Scala – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 124 105 93 bytes ``` f(x:_:y)=fromEnum.(/=x)<$>y g[]=[] g s=(toEnum.sum.zipWith((*).(2^))[7,6..0])s:g(drop 8s) g.f ``` [Try it online!](https://tio.run/##dYqxCsIwGIT3PMVPcUhEojioBCMk4Obm4FCqFNomxbYJTQqtLx9jdfXgOL6707l7lk0TQoVH9mAT4VVv2nM3tBSv@UiOi9OEVJrxNEMKHMfezKOLftX2VnuN8ZJQvL0Tku5XO0o3GXFM4aI3Fg6OIM0VrUKb1x1wKAwCaEoPNoId/NX3l47qWFpIhBRCRn8054@lSL4HKf4ewhs "Haskell – Try It Online") `f` converts the string to a list of bits by comparing each character to the first one, turning the `Bool`s into zeros and ones with `fromEnum`. `g` divides this list into groups of 8, converts them to decimal, and takes the value of the resulting number as an `Enum`, which `Char` is an instance of. ### Changes: * -19 bytes thanks to @Laikoni (removing import, embedding `map` into function) * -12 bytes inspired by @Lynn's answer (getting rid of `take` by zipping with shorter list) [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 83 bytes ``` : f over c@ 0 rot 2 do 2* over i 4 pick + c@ <> - i 8 mod 1 = if emit 0 then loop ; ``` [Try it online!](https://tio.run/##LYvRCsIwFEN/5bBHx2COPYhOsf2VrdcV3e6oxd@v7TQQQg6JaIhz85ASKZ0R9OMC452WoJGOSekOP@rp2fz4pC6D4UaT0YlFJ45c8YJbfMzPOLuVl@rGJb0rjDXGZhft@e/WVEj6Ag "Forth (gforth) – Try It Online") Input is a standard Forth string (address and length) output is printed to stdout ## Explanation ``` over c@ \ get the value of the first character in the string 0 rot \ add a starting "byte" value of 0 and put the length on top of the stack 2 do \ start a loop from 2 to length-1 2* \ multiply the current byte value by 2 (shift "bits" left one) over \ copy the reference char to the top of the stack i 4 pick + \ add the index and the starting address to get address of the current char c@ <> \ get the char at the address and check if not equal to the reference char - \ subtract the value from our bit count, -1 is default "true" value in forth i 8 mod 1 = \ check if we are at the last bit in a byte if \ if we are emit 0 \ print the character and start our new byte at 0 then \ and end the if statement loop \ end the loop ``` ]
[Question] [ A demonic number is a positive integer whose decimal representation consists of only 6. The list of demonic numbers starts with 6, 66, 666, 6666. Given a positive integer, output the nearest demonic number. If there are two, output the bigger one. Testcases: ``` n output 1 6 2 6 3 6 6 6 35 6 36 66 37 66 100 66 365 66 366 666 666 666 999 666 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Answer] # Python 2, 28 bytes ``` lambda n:'6'*len(`-~n*3/11`) ``` [Answer] # JavaScript (ES6), ~~31~~ 29 bytes ``` f=(x,s='6')=>x<3+s?s:f(x,s+6) ``` ``` f=(x,s='6')=>x<3+s?s:f(x,s+6) ;[1,2,3,6,35,36,37,100,365,366,666,999,1000].forEach(x=>console.log(x,f(x))) ``` “That is why, I delight in weaknesses […] For when I am weak, then I am strong.” [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ;I≜+{6}ᵐ ``` [Try it online!](https://tio.run/nexus/brachylog2#@2/t@ahzjna1We3DrRP@/7e0tPwfBQA "Brachylog – TIO Nexus") ### Explanation ``` ;I The list [Input, I] ≜ Assign a value to I: 0, then 1, then -1, then 2, etc. + Sum Input with I {6}ᵐ All its digits must be 6 ``` [Answer] # Java 7, ~~96~~ ~~93~~ 66 bytes ``` String c(int n){String r="";for(n*=11/3;n>1;r+=6,n/=10);return r;} ``` Port of [*@orlp* amazing Python 2 answer](https://codegolf.stackexchange.com/a/121851/52210). [Try it here.](https://tio.run/nexus/java-openjdk#hY7BDoIwDIbvPkXDaVMDTCKGLPMNOHE0HhDRLGGFbENjCM@OBDzbXpr2//r3r5rSOciHqfBW4xMqptED8uE3WxUE8tFahlslRJRIPAtpdyrdY6REzKWtfW8RrBwngK6/NboC50s/t1er72BKjWw1u1yh5MMG5srBgAKs35AzLpdV8XG@NmHb@7Cbad8gM2HFBP@vHwg9IfSUuj9SAOlwIgARx@QPOgUVIyWJLMvopGTWbKkVGjfj9AU) I guess my **66**-byte-count is a demon as well. ;) (Not the shortest Java answer btw, see [*@JollyJoker*'s answer for that](https://codegolf.stackexchange.com/a/122030/52210) instead. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ẇa6ḌạÐṂ⁸Ṫ ``` A monadic link. **[Try it online!](https://tio.run/nexus/jelly#ARwA4///4bqGYTbhuIzhuqHDkOG5guKBuOG5qv///zM2 "Jelly – TIO Nexus")** - Almost no point in this link (see below)! ### How? In true golfer's style this is truly inefficient - it hits the 60s time out at TIO for the **365** test case! Locally this finishes in 37s. ``` Ẇa6ḌạÐṂ⁸Ṫ - Main link: n Ẇ - all sublists - this has an implicit make_range on it's input - so, for example, an input of 3 yields [[1],[2],[3],[1,2],[2,3],[1,2,3]] - the important things are: that it contains both a list of the length of the - decimal number, and a list 1 shorter; and that it's lists only contain - non-zero numbers and are monotonically increasing in length. 6 - literal 6 a - and (vectorises), this changes all the values to 6s - so, the example above becomes [[6],[6],[6],[6,6],[6,6],[6,6,6]] Ḍ - convert to decimal (vectorises) [ 6, 6,, 6, 66, 66, 666 ] ⁸ - link's right argument, n ÐṂ - filter keep those with minimal: ạ - absolute difference (for 366 this keeps 66 AND 666; same goes for 3666; etc.) Ṫ - tail - get the rightmost result (for 366 keeps 666, since it's longer) ``` A patch to make the same algorithm run within the 60s limit for **365** and **366** on TIO is to avoid the implicit vectorisation of `Ḍ` with `Ẇa6Ḍ€ạÐṂ⁸Ṫ` ([try that](https://tio.run/nexus/jelly#ASAA3///4bqGYTbhuIzigqzhuqHDkOG5guKBuOG5qv///zM2Ng)), however this will now seg-fault for an input of **999** (**Triangle(999)** is only **499,500** but each is a list of integers, making a total of **Tetrahedral(999) = 166,666,500** integers, not memory efficient, at least in Python). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` RD6ṁḌạÐṂ¹Ṫ ``` [Try it online!](https://tio.run/nexus/jelly#@x/kYvZwZ@PDHT0Pdy08POHhzqZDOx/uXPX/6J7D7Y@a1rj//2@oo2Cko2Cso2AGJE2BGESb6ygYGhiAOGARoJAZiLC0tAQA "Jelly – TIO Nexus") [Answer] # C, 118 bytes [**Try Online**](http://ideone.com/rWI7zA) ``` a;b;d(n,m){return(m*6)+(n>0?d(n-1,m*10):0);} f(n){a=d((int)log10(n)-1,1);b=d((int)log10(n),1);return(n-a<(b-a)/2)?a:b;} ``` [Answer] ## JavaScript (ES6), 41 bytes ``` f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10) ``` ### Test cases ``` f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10) console.log(f(1)) // 6 console.log(f(2)) // 6 console.log(f(3)) // 6 console.log(f(6)) // 6 console.log(f(35)) // 6 console.log(f(36)) // 66 console.log(f(37)) // 66 console.log(f(100)) // 66 console.log(f(365)) // 66 console.log(f(366)) // 666 console.log(f(666)) // 666 console.log(f(999)) // 666 ``` [Answer] ## Mathematica, 36 Bytes Pure function: ``` Max[NestList[6+10#&,6,#]~Nearest~#]& ``` Explanation: ``` NestList[6+10#&,6,#] ``` Iterative create a list of length equal to the input using `NestList` following the pattern `6+10x(previous_value)` starting from the value of `6`. ``` ~Nearest~# ``` Then find the value in this list closest to the input. ``` Max[ ] ``` Lastly take the maximum value from the list of nearest values. Whilst the list length is super inefficient as mathematica can work with arbitrary precision length numbers this program is only limited by physical memory. [Answer] # [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 118 bytes ``` Fun<Ap<Fun<If<lt<A<1>,Add<A<2>,A<3>>>,A<3>,Ap<A<0>,A<1>,Mul<A<2>,I<10>>,Add<Mul<A<3>,I<10>>,I<6>>>>>,A<1>,I<30>,I<6>>> ``` [Try it online!](https://tio.run/nexus/templates#PYsxCsAwDAM/lMFpaCZh8FLw0F@ETqFkaN6f2ph2kk6cZGAd84YMeOiF/kCQOUlrVjYrKMwRyTQBOZhxzh6GIhPHI7byb4rKHPfsVOjbllPdrbw "Templates Considered Harmful – TIO Nexus") Ungolfed: ``` Fun<Ap<Fun<If<lt<A<1>, Add<A<2>, A<3>>>, A<3>, Ap<A<0>, A<1>, Mul<A<2>, I<10>>, Add<Mul<A<3>, I<10>>, I<6>>>>>, A<1>, I<30>, I<6>>> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes - 1 byte thanks to Riley ``` 6׌ΣI-Ä}¬ ``` [Try it online!](https://tio.run/nexus/05ab1e#@292ePrRSecWe@oebqk9tOb/f2NzAA) The above code can have performance issues, here is a slightly more efficient version with 10 bytes: [TIO alternative](https://tio.run/nexus/05ab1e#@292eLpewbnFnrqHW2oPrfn/39LSEgA "05AB1E – TIO Nexus") ## Explanation ``` 6׌ΣI-Ä}¬ Main link. Argument n 6× Push string containing '6' n times Œ Push substrings Σ } Sort by result of code I-Ä Absolute difference between n ¬ Head, implicit output ``` [Answer] ## Mathematica, 76 bytes ``` Max[Take[LinearRecurrence[{11,-10},{0,6},IntegerLength[#]+1],-2]~Nearest~#]& ``` [Answer] # [Neim](https://github.com/okx-code/Neim/), ~~12~~ 10 bytes (non-competing) -1 byte thanks to steenbergh ``` 𝐥𝐈Γ6Θℝ)₁>𝕔 ``` Explanation: ``` Implicit input: [366] 𝐥 Push the length of the input [3] 𝐈 Inclusive range [[1, 2, 3]] Γ For each ℝ Repeat 6 6 Θ currently looped value times [[6, 66, 666]] ) End for each 𝕔 Get the closest value to ₁ The first line of input... > ...incremented by one [666] Implicitly print entire stack ``` Unfortunately, `𝕔` will return the lower value in a list if two numbers have the same difference, so we had to add 2 bytes to account for that. Non-competing as `>`, `<` and `ℝ` were added after this question was asked (and `𝐥` was fixed to work with numbers, not just lists) Note: Will not work for numbers with a length equal to 19 or more - as they get too big for Java's longs to handle. (but this is quite a large value, and should be fine) [Try it](http://178.62.56.56/neim?code=%F0%9D%90%A5%F0%9D%90%88%CE%936%CE%98%E2%84%9D)%E2%82%81%3E%F0%9D%95%94&input=366) [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~37~~ 27 bytes ``` ≈!@36`!<=:|A=A+!6$]?_sA,2,a ``` Instead of using Maths™ this now uses string manipulation to find the breaks in the Demonic Domains (36, 366, ...). Inspired by @eush77 's JS answer. Explanation ``` ≈ | WHILE <condition> ! ! a numerical cast of @ ` the string literal A$ 36 starting out as "36" <= is smaller than or equal to : cmd line argument 'a' A=A+ 6 Add a 6 to the end of A$ (36 ==> 366 ==> 3666) ! $ as a string-cast ] WEND (ends the WHIOLE loop body) ?_sA PRINT a substring of A$ n=37, A$ = 366 ,2 starting at index 2 ^ ,a running well past the end of the string 66 ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 46 bytes ``` dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.0=. ``` [Try it online!](https://tio.run/nexus/dc#i062r4oujC3WM7DVU0jJi1aIzfufUlwRZahraFAUl2JoqGWka6yfUlyZUxFtUKQLVGijZ6yVU6mdEm0G0fW/IMetIjal2K3ivyGXEZcxlxmXsSmXMZA05zI0MACyQDwzLjMgtrS0BIkZAAA "dc – TIO Nexus") ``` dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.0=. Z1-10r^ Nearest power of 10 11*2-3/ The number in between 6ⁿ and 6ⁿ6 d lx[0r-]s.<. Check which side we're on 3*ly+ Get the answer for x≥3 d[6]s.0=. Return 6 for x<3 ``` [Answer] ## C#, 142 bytes ``` a=>{var c=(a+"").Length;return int.Parse(a<int.Parse(3+new string('6',c==1?2:(c==10?1:c)))?new string('6',c-1):new string('6',c==10?c-1:c));}; ``` It uses the fact, that we need to jump to the next deamonic number at every 36666... In a more readable form: ``` var c = (a + "").Length; return int.Parse(a < int.Parse(3 + new string('6', c == 1 ? 2 : (c == 10 ? 1 : c))) ? new string('6', c - 1) : new string('6', c == 10 ? c - 1 : c)); ``` [Answer] # [braingasm](https://github.com/daniero/braingasm), 15 bytes ``` ;3*11/z+[6:10/] ``` Using the arithmetic from [orlp's Python solution](https://codegolf.stackexchange.com/a/121851/4372): ``` ; Read an integer from stdin 3*11/ Multiply by 3 and divide by 11 z+ If result is zero, add one [6:10/] While not zero, print '6' and divide by 10 ``` [Answer] I didn't see this question in the feed, and only stumbled over it by accident. Here's my answer anyway: ## JavaScript (ES6), 34 bytes ``` n=>`${-~n*3/11|0}`.replace(/./g,6) ``` Add 1 byte for a numeric answer. Originally based on this ungolfed ES7 answer (37 bytes, already numeric): ``` n=>(10**(Math.log10(-~n*3/11)|0)*2-2)/3 ``` Annoyingly OP wants 36 to be nearer to 66 than 6. Explanation: 11/3=3.666..., so dividing by this scales the ranges 7..36, 37..366 etc. to the ranges 1..9.9, 10..99.9 etc. This can be solved purely numerically by taking 2/3 of one less than the next higher power of 10, although it's golfier to truncate, convert to string, then change all the characters to the digit 6. (Although still not as golfy as that really clever recursive answer.) [Answer] ## CJam, 25 bytes Not as slow as the Jonathan Alan's Jelly submission, but requires *O(n²)* memory, where *n* is the input number. Yeah. ``` ri)__{)'6*i}%f-_:z_:e<#=- ``` This is equivalent to the following Python: ``` num = int(input()) + 1 # CJam: ri)__ demondiffs = [int("6" * (i + 1)) - num for i in range(num)] # CJam: {)'6*i}%f- absdiffs = [abs(i) for i in demondiffs] # CJam: _:z mindex = absdiffs.index(min(absdiffs)) # CJam: _:e<# print(num - demondiffs[mindex]) # CJam: =- ``` ## Alternative solution, 12 bytes ``` ri)3*B/s,'6* ``` This is a translation of orlp's algorithm into CJam. Explanation: ``` ri e# Read integer: | 36 ) e# Increment: | 37 3* e# Multiply by 3: | 111 B/ e# Divide by 0xB (11): | 10 s e# Convert to string: | "10" , e# String length: | 2 '6 e# Push character '6': | 2 '6 * e# Repeat character: | "66" e# Implicit output: 66 ``` [Answer] # Java 8, 37 bytes ``` n->(""+-~n*3/11).replaceAll(".","6"); ``` Going by [Kevin Cruijssen's example](https://codegolf.stackexchange.com/a/122002/58251) and just returning a String. Do the \*3/11 trick to get the right length, then replace all with sixes. [Answer] # PHP, 49 Bytes trim the character 6 ``` for(;trim($x=$argn+$i,6)>"";)$i=($i<1)-$i;echo$x; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTYzs/6fll@kYV1SlJmroVJhCxbXVsnUMdO0U1Ky1lTJtNVQybQx1NRVybROTc7IV6mw/v8fAA "PHP – TIO Nexus") Instead of `trim($x=$argn+$i,6)>""` you can use a Regex solution `!preg_match("#^6+$#",$x=$argn+$i)` +11 Bytes or a string length equal to count `6` comparision `strlen($x=$argn+$i)-strspn($x,6)` +10 Bytes [Answer] # LOLCODE 1.4, 471 bytes ``` HAI 1.4 CAN HAS STRING? I HAS A i GIMMEH i I HAS A l ITZ I IZ STRING'Z LEN YR i MKAY I HAS A s ITZ "3" IM IN YR a BOTH SAEM I IZ STRING'Z LEN YR s MKAY AN l O RLY? YA RLY GTFO OIC s R SMOOSH s AN 6 IM OUTTA YR l I HAS A o DIFFRINT i AN BIGGR of i AN 4 O RLY? YA RLY VISIBLE 6 NO WAI BOTH SAEM i AN SMALLR of i AN s O RLY? YA RLY o R DIFF OF l AN 1 NO WAI o R l OIC I HAS A f IM IN YR b UPPIN YR k TIL BOTH SAEM k AN o f R SMOOSH f AN 6 IM OUTTA YR b VISIBLE f OIC KTHXBYE ``` Wow. Here's that Ungolfed and Explained: ``` HAI 1.4 CAN HAS STRING? I HAS A input GIMMEH input I HAS A length ITZ I IZ STRING'Z LEN YR input MKAY BTW this is using the length function of the STRING library. I HAS A sixes ITZ "3" BTW the average of for example [6...] and 6[6...] is 3[6...]. IM IN YR foreverloop BTW this loop fills the sixes variable. BOTH SAEM I IZ STRING'Z LEN YR sixes MKAY AN length # In LOLCODE, a statement containing only an expression assigns the implicit variable IT. O RLY? # Tests the current value in IT. YA RLY GTFO OIC sixes R SMOOSH sixes AN 6 BTW SMOOSH automatically casts things to YARN. It also does not need a MKAY unless there's something after it on the line. IM OUTTA YR foreverloop I HAS A outputlength DIFFRINT input AN BIGGR of input AN 4 BTW LOLCODE doesn't have a built-in inequality operator. This just means input < 4 O RLY? YA RLY VISIBLE 6 BTW If it's less than 4, the algorithm of comparing to the nearest 3.6*10^n. NO WAI BOTH SAEM input AN SMALLR of input AN sixes BTW input<=sixes O RLY? BTW This if statement makes sure that if the input is less than 3.6*10^length, it goes to the previous place value's demon number. YA RLY outputlength R DIFF OF length AN 1 NO WAI outputlength R length OIC I HAS A final IM IN YR forloop UPPIN YR iterator TIL BOTH SAEM iterator and outputlength final R SMOOSH final AN 6 IM OUTTA YR forloop VISIBLE final OIC KTHXBYE ``` Still wow. Here's some pseudojavascrython for you. ``` hello() import string var i i=input() var l=string.len(i) var s="3" while True: if(string.len(s)==l): break s=s+6 var o if(i!=max(i,4)): # Basically if(i<4) print 6 else: if(i==min(i,s)): # Basically if(i<=s) o=l-1 else: o=l var f for(var k=0;k<o;k++): f=f+6 print(f) exit() ``` Still don't get it? This program basically just (excluding inputs 1-3) compares the input to the 3.6\*10^n, n being the length of the input. If it is smaller than that number, it prints the number of 6s one less than the length. If it is greater than or equal to that number, the number of sixes is the current length. Would love some help golfing! [Answer] # Haxe, 70 bytes ``` function(x){x*=3;x/=11;do{Sys.print('6');}while((x=Std.int(x/10))>0);} ``` Input has to be passed as type `Float` despite being an integer, otherwise Haxe will complain about trying to divide an integer (yes haxe will refuse to compile if you divide an integer by anything) Same as all the other answers. Multiply by 3, divide by 11, print 1 `6` for every digit. [Answer] # Brainfuck, 315 bytes ``` ,+>+++[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<+++++++++++<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>]<[-]+<[>-]>[<+>->]++++++[<+++++++++>-]<<<[-]++++++++++>[>.<[<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>>] ``` **[Run it here](https://copy.sh/brainfuck/)**. Select a cell size that can handle values of 3\*(n+1), so for all of the test cases to work, select 16. **Dynamic (infinite) Memory** must be turned on for this to work. This allows the tape to expand to the left. To input an integer, type the input like `\366` for n=366. ### Ungolfed: Uses the same algorithm as [this solution](https://codegolf.stackexchange.com/a/121851/34718). The algorithms used for each individual step are taken from [this page](https://esolangs.org/wiki/Brainfuck_algorithms). All algorithms used are non-wrapping, so that the program won't break for larger inputs. ``` ,+ # n = n plus 1 >+++ # 3 [>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-] # n = n*3 <+++++++++++ # 10 <[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>] # n = n/10 <[-]+<[>-]>[<+>->] # if (n == 0) { n = n plus 1 } ++++++[<+++++++++>-] # '6' (54) <<<[-]++++++++++> # 10 [ # while (n above 0) >.< # print '6' [<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>> # n = n/10 ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` 6s×ηs.x ``` [Try it online!](https://tio.run/##MzBNTDJM/f/frPjw9HPbi/Uq/v83NjQyAQA "05AB1E – Try It Online") --- ``` Program # Input ====================|> 2 --------#---------------------------+-------- 6s× # Push N 6's as a string. | 66 ηs # Prefixes of this. | [6, 66] .x # Closest element to input. | 6 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` _ì e¥6}cU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=X+wgZaU2fWNV&input=ODg4) [Answer] # C#, 102 bytes ``` string a(int j,int k=0)=>(j+"|"+(k=k==0?j:k)).Split('|').Where(s=>s.All(c=>c=='6')).Max()??a(j+1,k-1); ``` Kinda disappointed in the length of this, could do exactly the same as the shorter answer in Java but I did not really understand it because I am a lazy, stupid .NET developer :) ]
[Question] [ Given a non-empty string s, with even length, and a positive integer n, representing its height, compose a pyramid using the following rules: The pyramid should contain n non-empty lines; trailing newlines are allowed. For each 1 <= i <= n, the i-th line should contain the string with each individual character repeated in-place i times; abcd repeated 3 times as such becomes aaabbbcccddd. Each line should be centered with padding spaces so that the middle of each line is vertically aligned. Trailing spaces at the end of each line are permitted. You can also have up to one leading newline but no other whitespace before the first line. The input string is not guaranteed to be a palindrome. # Test Case ``` s = 'o-o o-o', n = 10: o-o o-o oo--oo oo--oo ooo---ooo ooo---ooo oooo----oooo oooo----oooo ooooo-----ooooo ooooo-----ooooo oooooo------oooooo oooooo------oooooo ooooooo-------ooooooo ooooooo-------ooooooo oooooooo--------oooooooo oooooooo--------oooooooo ooooooooo---------ooooooooo ooooooooo---------ooooooooo oooooooooo----------oooooooooo oooooooooo----------oooooooooo ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` γ².D)ƶJ.C ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZDm/RcNI9t89Jz/v/fQNdAQQFIcBkaAAA "05AB1E – Try It Online") --- `γ` was, in no short amount, inspired by Adnan's answer; but `S` would also work. --- ``` γ # Split into runs. | ['0','-','0'] ².D) # Push n times. | [['0','-','0'],['0','-','0'],['0','-','0']] ƶ # Lift by index. | [['0','-','0'],['00','---','00'],['000','---','000']] J # Inner join. | ['0-0','00--00','000---000'] .C # Center. | Expected output. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` F²γN>×J}».C ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f7dCmc5v97A5P96o9tFvP@f9/QwOufN18BQUgAQA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` LH×Ḷ}Ṛ⁶ẋżxЀY ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//TEjDl@G4tn3huZrigbbhuovFvHjDkOKCrFn///8nUC1QICBDLUcn/zEw "Jelly – Try It Online") ### How it works ``` LH×Ḷ}Ṛ⁶ẋżxЀY Main link. Arguments: s (string), n (integer) L Get the length l of s. H Halve it, yielding l/2. Ḷ} Unlength right; yield [0, ... n-1]. × Compute [0, l/2, ..., l(n-1)/2]. Ṛ Reverse; yield [l(n-1)/2, ..., l/2, 0]. ⁶ẋ Space repeat; create string of that many spaces. xЀ Repeat in-place each; repeat the individual characters of s 1, ..., n times, yielding an array of n strings. ż Zipwith; pair the k-th string of spaces with the k-th string of repeated characters of s. Y Sepatate the resulting pairs by linefeeds. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 139 137 136 130 bytes ``` using System.Linq;s=>n=>Enumerable.Range(0,n).Select(i=>"".PadLeft((n+~i)*s.Length/2)+string.Concat(s.Select(c=>new string(c,i)))) ``` [Try it online!](https://tio.run/##nZDRSsMwFIbv9xQhu0ltm7rdzhZBVJQKw13spiAxO62B9gSTVBGZz@Iz@ES@SU27ujEv/SHhcP783yFH2lhqA11rFVZk9WYdNDxX@LyYTIiXrIW1ZGl0ZUQzdN6Hu5d1wilJXrTakDuhkAV76/Co14i9alGeWWf8pOiop9DtGxe6rkE6pdHya0AwSvKbS2wbMOKxhjGfZRkpSTrpbJphmh18fi@wAnYaYcBX0JOYSjNK@VJscigdYxh@qODE8hywck/JPAh3SD8ZpXDM/uakR8Mr2blMRirw6sa9/Pmaz1rtp6@NcuDXB2yE3mq/F1ogjUjJ6PfX54M/hIwFDdhs5qmL/zPPaRwmxXSaFGHc4@ZHuO1Qbbsf "C# (.NET Core) – Try It Online") Returns an enumeration of `string`s with the lines of the drawing. Once joined the result is like this: ``` ಠ_ಠ ಠ_ಠ ಠಠ__ಠಠ ಠಠ__ಠಠ ಠಠಠ___ಠಠಠ ಠಠಠ___ಠಠಠ ಠಠಠಠ____ಠಠಠಠ ಠಠಠಠ____ಠಠಠಠ ಠಠಠಠಠ_____ಠಠಠಠಠ ಠಠಠಠಠ_____ಠಠಠಠಠ ಠಠಠಠಠಠ______ಠಠಠಠಠಠ ಠಠಠಠಠಠ______ಠಠಠಠಠಠ ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ ಠಠಠಠಠಠಠ_______ಠಠಠಠಠಠಠ ``` * 2 bytes saved thanks to Kevin Cruijssen! * 1 byte saved thanks to Value Ink! * 6 bytes saved thanks to LiefdeWen! [Answer] ## [Cheddar](https://cheddar.vihan.org), ~~71~~ 64 bytes *Saved 7 bytes thanks to @ValueInk* ``` (s,n)->(1|>n=>i->(s.len*(n-i)/2)*" "+s.sub(/./g,"$&"*i)).asLines ``` [Try it online!](https://vihan.org/p/tio/?l=cheddar&p=y0ktUUizVdAo1snT1LXTMKyxy7O1ywSyivVyUvO0NPJ0MzX1jTS1lBSUtIv1ikuTNPT19NN1lFTUlLQyNTX1Eot9MvNSixWsuQqKMvOAZmmo5@vmKygACXUdBUMDzf8A) I will add explanation in a bit Explanation ``` (string, count)->( 1 |> count // 1..count, the amount of rep/char per line => i -> ( // Map over the range s.len*(n-i)/2 // Calculate amount of spaces and repeat by it. )*" " + s.sub(/./g,"$&"*i) // replace each character, duplicate the amount of times `*i` ).asLines // return the above joined with newlines ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` ->s,n{(1..n).map{|i|s.gsub(/./){$&*i}.center s.size*n}*$/} ``` [Try it online!](https://tio.run/##BcHRCoMgFADQX5GIoZd2pYcetx@ZCyxuIZhEVwdlfrs750jTWZeXqc83dyHLHjEo3Oyeb3czrpwmqVGr3D7AFZwpRDoEI7uLIBRodal7iiwWnK33AuhnvVwpsqqfBvQ4GgNNJ/rh@wc "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ 77 bytes ``` s,n=input() for i in range(n):print''.join(c*-~i for c in s).center(len(s)*n) ``` [Try it online!](https://tio.run/##FcoxDoMwDAXQvafwFjsiiHas1MNUUQAj9B0lYWDh6mlZ3vTy2VbDq/c64KPIR2N5zFZISUHliyUx5J2Lojk3bqbg6MOldKd4pypjTGip8J7AVTykd2fBiP644Tn9AA "Python 2 – Try It Online") [Answer] # Java 11, ~~188~~ ~~186~~ ~~185~~ ~~183~~ ~~181~~ ~~173~~ ~~171~~ 133 bytes ``` s->n->{var r="";for(int l=s.length()/2,x=l*n,i=0;i++<n;r+="\n"){r+=" ".repeat(x-i*l);for(var c:s.split(""))r+=c.repeat(i);}return r;} ``` -2 bytes (185 → 183) due to a bug-fix (it was outputting `n+1` lines instead of `n`). Doesn't happen often that a bug-fix saves bytes. :) -2 bytes (183 → 181) thanks to *@OlivierGrégoire* -2 bytes (173 → 171) thanks to *@ceilingcat* [Try it online.](https://tio.run/##PU89b8IwEN3zK06ebEjc0LEmGSt16MRIGdxgqKk5W/aFglB@e2pK6Pa@7vTeQZ90ddh@j/YYfCQ4ZC57sk7ueuzIepSvE1BF53RK8K4tXguARJpsBw97uaJocV/@8zckszexvOttC10zpqrFqr2edITYMKZ2PnKLBK5J0hnc0xcXT8/luXEzLG1TKzufL1HFecM@kInrDQCT0QSjiZ8rO3Pi78ntY/eSZArOEmdMiBztHkEr1BAN9REhqmFUUOT@of90uf804@TtFo55Gr/3XW9Ai9tMgNUlkTlK35MM2SKHvJM6BHfhel1vxITR/MC0OeuLjRBC5fuhGMbRVx6grupxUf8C) **Explanation:** ``` s->n->{ // Method with String & integer parameters and String return var r=""; // Return-String, starting empty for(int l=s.length()/2, // Halve the length of the input-String x=l*n, // Set `x` to halve the length multiplied by the input i=0;i++<n; // Loop `i` in the range (0,n): r+="\n"){ // And after every iteration, add a new-line r+=" ".repeat(x-i*l); // Add the appropriate amount of trailing spaces for(var c:s.split("")) // Inner loop over the characters of the String: r+=c.repeat(i);} // Repeat each character `i` amount of times return r;} // Return the result-String ``` [Answer] ## JavaScript (ES6), 85 bytes Takes input in currying syntax `(string)(height)`. Includes a leading newline. ``` s=>g=(n,p=` `)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):'' ``` ### Demo ``` let f = s=>g=(n,p=` `)=>n?g(n-1,p+' '.repeat(s.length/2))+p+s.replace(/./g,c=>c.repeat(n)):'' o.innerHTML = f('o-o o-o')(10) ``` ``` <pre id=o></pre> ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` F⁺¹N«J±×ι÷Lη²ιFηFικ ``` [Try it online!](https://tio.run/##HYw7DsIwEETr@BRb7kq2lNDS0oBQlCIXCMHEKxw78icN4uzGpJkp3ryZzRRmP9lSXj4ADjZH7CRc3ZZTn9eHDkhE8BHNLa/b6LHXy5Q0jrzqiPxfpgvv/NR4125JBg1JOFVHAtNZNMetITiaCYbALuG7om8pXSu88gA1itqLivYH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁺¹N« for (Plus(1, InputNumber())) { ``` We need lines repeated `1..n` times. The easiest way to achieve this is to loop from 0 to n, as loop 0 is basically a no-op. ``` J±×ι÷Lη²ι JumpTo(Negate(Times(i, IntDivide(Length(h), 2))), i); ``` Position the cursor so that the resulting line is centred. ``` FηFικ for (h) for (i) Print(k); ``` And this is how simple printing each character repeated `i` times is. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ā.∫dI*Hd⁄»±IFž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxLiV1MjIyQmRJKkhkJXUyMDQ0JUJCJUIxSUYldTAxN0U_,inputs=NCUwQW8tbyUyMCUyMG8tbw__) [Answer] # Javascript, 105 bytes ``` (s,n)=>Array(N=n).fill().reduce(a=>a+'\n'+' '.repeat(--n*s.length/2)+s.replace(/./g,_=>_.repeat(N-n)),'') ``` After a few years off, the Stretch Maniac is back, hopefully slightly more educated this time. [Answer] # [Haskell](https://www.haskell.org/), ~~79~~ ~~73~~ 69 bytes * Saved 4 bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) ``` s#n=unlines[(' '<$[1,3..(n-m)*length s])++((<$[1..m])=<<s)|m<-[1..n]] ``` [Try it online!](https://tio.run/##HYrBDoMgEETvfsVGTYRaSI1X@IPeejQcTEqq6bI0Xbz13yn4DpO8mdlWfnvEnLkjexDu5HkRAwymX6brrLUgFeQFPb3SBuzkOApRN62Dk9YYlr9gVHVyLod1J7DwjA0U0Cfgom1UEaBEe9aV@ppuzemfIz3S907Ql3cHlP8 "Haskell – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~33~~ 31 bytes *2 bytes golfed thanks to @ZacharyT by removing unnecessary parentheses* ``` {↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24TqR20TNTTUFdT1H/Wu0NAzPTz9UeeiR71bNYGM3l26j7oWaeoAuSBZEPvQike9m4EStf//GxooOCqo5@vmKygACXUuJD5EBAA "APL (Dyalog Unicode) – Try It Online") ### Explanation The right argument `⍵` is the string and the left argument `⍺` is the number. ``` {↑((' '/⍨(.5×≢⍵)×⍺-⊢),⍵/⍨⊢)¨⍳⍺} ⍳⍺ Range 1 .. ⍺ ( )¨ For each element (let's call it i) do: ⍵/⍨⊢ Replicate ⍵ i times ( ), Concatenated with (.5×≢⍵)×⍺-⊢ (⍺-i)×(len(⍵)×0.5) ' '/⍨ spaces ↑ Convert the resulting array to a 2D matrix ``` [Answer] **SWI Prolog, 398 bytes** It is not the most compact solution (maybe somewhere reinventing the wheel instead of using built-in procedures), but it appers to work. ``` w(0). w(X):-write(' '),Y is X-1,w(Y). s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y). d(S,N,R):-atom_chars(S,A),e([],A,N,R). e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R). e(B,[],_,B). a([], L, L). a([H|T],L,[H|R]):-a(T,L,R). l(L,_,0,L). l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R). o([]):-nl. o([H|T]):-write(H),o(T). p(S,N):-p(S,N,N). p(_,0,_). p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R). ``` Test: ``` ?- p("o-o o-o",10). o-o o-o oo--oo oo--oo ooo---ooo ooo---ooo oooo----oooo oooo----oooo ooooo-----ooooo ooooo-----ooooo oooooo------oooooo oooooo------oooooo ooooooo-------ooooooo ooooooo-------ooooooo oooooooo--------oooooooo oooooooo--------oooooooo ooooooooo---------ooooooooo ooooooooo---------ooooooooo oooooooooo----------oooooooooo oooooooooo----------oooooooooo true . ``` Explanation: **w** and **s** writes proper amount of leading spaces: ``` w(0). w(X):-write(' '),Y is X-1,w(Y). s(S,N):-string_length(S,X),Y is div(X,2)*N,w(Y). ``` **d** manages the "duplication" of characters and **e** is it's recursive facility: ``` //d(String, Number of repetitions, Result) d(S,N,R):-atom_chars(S,A),e([],A,N,R). e(B,[H|T],N,R):-l(B,H,N,I),e(I,T,N,R). e(B,[],_,B). ``` **a** and **l** append to the result (maybe there exists a built in procedure?): ``` a([], L, L). a([H|T],L,[H|R]):-a(T,L,R). l(L,_,0,L). l(L,I,N,R):-M is N-1,l(L,I,M,T),a(T,[I],R). ``` **o** creates the output: ``` o([]):-nl. o([H|T]):-write(H),o(T). ``` and finally the **p** is the *main method*: ``` p(S,N):-p(S,N,N). p(_,0,_). //p(String, Current level, Number of levels) :- go to the bottom, create pyramide level, write whitespaces, write the level p(S,N,L):-Q is N-1,p(S,Q,L),d(S,N,R),W is L-N,s(S,W),o(R). ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20~~ ~~19~~ ~~14~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ@VmpXÃû ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9UBWbXBYw/s&input=MTAKIm8tbyAgby1vIg) * Saved 1 byte thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) [Answer] # PHP, 113 bytes: ``` for([,$s,$n]=$argv;$i++<$n;)for(print($f=str_pad)(" ",($n-$i)*strlen($s)/2+!$p=0);~$c=$s[$p++];)echo$f($c,$i,$c); ``` Run with `php -nr '<code>' '<string>' <N>` or [test it online](http://sandbox.onlinephpfunctions.com/code/b721c34d134f6aa882e336f0e2be54a6f3bf591b). **breakdown** ``` # import input, loop $i from 1 to $n for([,$s,$n]=$argv;$i++<$n;) # 1. print newline and padding, reset $p for(print($f=str_pad)("\n",($n-$i)*strlen($s)/2+!$p=0); # 2. loop $c through string ~$c=$s[$p++];) # print repeated character echo$f($c,$i,$c); ``` [Answer] # [CJam](https://sourceforge.net/p/cjam/wiki/Home/), 36 bytes ``` l_,2/:T;]li:F{[_U)*zSTFU)-**\N]\}fU; ``` [Try it online!](http://cjam.aditsu.net/#code=l_%2C2%2F%3AT%3B%5Dli%3AF%7B%5B_U%29*zSTFU%29-**%5CN%5D%5C%7DfU%3B&input=o-o%20%20o-o%0A10) [Answer] # T-SQL, 223 bytes ``` DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max)SELECT @=s,@n=n FROM t R:SET @j=0SET @p=SPACE((@n-@i)*len(@)/2)C:SET @j+=1SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i)IF @j<LEN(@)GOTO C PRINT @p SET @i+=1IF @i<=@n GOTO R ``` Input is via pre-existing table **t** with columns **s** and **n**, [per our IO standards](https://codegolf.meta.stackexchange.com/a/5341/70172). Not much to explain, it's a pretty straightforward nested loop, using `@i` for the rows and `@j` to walk through the characters of the string which are `REPLICATED` `@i` times: ``` DECLARE @ char(99),@n INT,@i INT=1,@j INT,@p varchar(max) SELECT @=s,@n=n FROM t R: SET @j=0 SET @p=SPACE((@n-@i)*len(@)/2) C: SET @j+=1 SET @P+=REPLICATE(SUBSTRING(@,@j,1),@i) IF @j<LEN(@)GOTO C PRINT @p SET @i+=1 IF @i<=@n GOTO R ``` [Answer] # [R](https://www.r-project.org/), ~~125~~ 95 bytes ``` function(S,n)for(i in 1:n)cat(rep(' ',(n-i)/2*nchar(S)),rep(el(strsplit(S,'')),e=i),sep="",' ') ``` [Try it online!](https://tio.run/##FYsxDsIwDAD3vsLqYhslgjIi@oq@IIREtVScykkHXh/KcsOdzvomLwv2pU9qa3lXHjI8fc@HxiZFaXHKuRgJiML0UI6hkaWdENCReuHr/aJxDUYLs/uXtFFtVvdN2rkjnjrNwq6mfR5HhwNyz4TFF4AT6GC6cf8B "R – Try It Online") ### Explanation: It's pretty straightforward, splitting the string and repeating the elements `i` times each `rep(s,e=i)` (`e` is short for `each`) as we loop. The tricky part is `rep('',(n-i)/2*length(s)+1)`. This is the padding string, but it's a bunch of empty strings. I need to add 1 because otherwise the result is `character(0)`, a zero-length vector, and `cat`, which by default separates its elements with spaces, misaligns the final line. [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ 77 bytes ``` s,n=input();m=n while m:m-=1;print' '*(m*len(s)/2)+''.join(i*(n-m)for i in s) ``` [Try it online!](https://tio.run/##DcNJDoMwDADAO6/wzXYgbMeiPIcKI2xHJBXq69OONPlbD7e1tTJYEsufSrxpsu455NpBXxrTsuVbrCJgIA3XblR4WrlHHE8XIwlkUfntNwiIQeHW0KPDPw7L/AM "Python 2 – Try It Online") Edit: -2 bytes courtesy @FlipTack [Answer] # Mathematica, 97 bytes ``` (c=Characters@#;T=Table;Column[T[""<>T[""<>T[c[[i]],j],{i,Length@c}],{j,#2}],Alignment->Center])& ``` **input** > > ["o-o o-o", 10] > > > [Answer] # Tcl, ~~143~~ ~~142~~ ~~141~~ 138 bytes ``` proc p s\ n {set p [expr [set w [expr [string le $s]/2]]*$n];time {incr p $w;puts [format %$p\s [regsub -all . $s [append r \\0]]]} $n;cd} ``` Test: ``` % p "o-o o-o" 5 o-o o-o oo--oo oo--oo ooo---ooo ooo---ooo oooo----oooo oooo----oooo ooooo-----ooooo ooooo-----ooooo ``` Remark: the "cd" at the end of the procedure prevents time's result to be printed out below the pyramid, but changes the current directory - a side effect that's not explicitly forbidden. Thanks to sergiol for a hint to save one byte.... and another hint to save one more byte. Thanks to aspect (on tcl chat) for another 3 bytes saved! [Answer] # Swift, 232 bytes Probably could be better, but I don't have much time to refactor. This answer uses Swift 4, so it can't currently be run online. ``` var p:(String,Int)->String={s,i in let r=(1...i).map{n in return s.map{return String(repeating:$0,count:n)}.joined()};return(r.map{return String(repeating:" ",count:(r.last!.count-$0.count)/2)+$0}as[String]).joined(separator:"\n")} ``` [Answer] ## LOGO, ~~97~~ 95 bytes ``` to f :s :n for[i 1 :n][repeat(:n-:i)/2*count :s[type "\ ]foreach :s[repeat :i[type ?]]pr "] end ``` Try the code on FMSLogo interpreter. Define a function `f` which takes two inputs, `:s` and `:n`, then print the result. [Answer] # Java 8, 164 148 bytes ``` s->n->{String o="";for(int i=0,m,j;i++<n;){o+="\n";for(m=0;m++<(n-i)*s.length()/2;)o+=" ";for(char c:s.toCharArray())for(j=0;j++<i;)o+=c;}return o;} ``` Explanation: ``` s->n->{ String o = ""; //empty output string for (int i = 0, m, j; i++ < n; ) { //for each row o += "\n"; //append a new line for (m = 0; m++ < (n - i)*s.length()/2; ) //for amount of spaces = inversed row_number * half length o += " "; //append a space for (char c : s.toCharArray()) //for each char of the string for (j = 0; j++ < i; ) //row_number times o+=c; //append char } return o; } ``` [Answer] ## Rust, 107 bytes ``` |a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.len()*b)} ``` [playpen link](https://is.gd/N3KxON) Defines an anonymous function that takes a string slice and number, printing the wanted pattern to standard output. It assumes that the string slice only contains ASCII characters, but the challenge never specifies that full unicode support is necessar. To be correct for unicode as well would require 117 bytes: ``` |a:&str,b|for i in 0..b{println!("{:^1$}",a.split("").map(|s|s.repeat(i+1)).collect::<String>(),a.chars().count()*b)} ``` The explanation is rather simple: ``` |a:&str,b| // arguments, compiler can't infer the type of a unfortunately for i in 0..b { // iterate from row 0 to row b - 1 println!( "{:^1$}", // print a line containing arg 0, centered with the width specified as arg 1 a.split("") // split the string into slices of one character .map(|s|s.repeat(i+1)) // for each slice, yield a string containing row+1 times that slice .collect::<String>(), // concatenate each of the strings into one string a.len()*b // total length should be the length of the string times the amount of rows ) } ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 8 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ∫dč*∑}¹╚ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCZCV1MDEwRColdTIyMTElN0QlQjkldTI1NUE_,inputs=MTAlMEFvLW8lMjAlMjBvLW8_) Explanation: ``` ∫dč*∑}¹╚ ∫ } iterate over 1..input, pushing counter d push the variable D, which sets itself to the next input as string č chop into characters - a vertical array * multiply horizontally by the counter ∑ join the array together ¹ wrap all that in an array ╚ center horizontally ``` I didn't feel like updating my old answer here as it uses a different method and uses a new(er than the challenge) feature - `╚` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L€×.c ``` First input is \$n\$, second input is \$s\$ as character-list. [Try it online.](https://tio.run/##yy9OTMpM/f/f51HTmsPT9ZL//zc04IpWslXSUdIFYkUgVoBiRaiYrVLsf13dvHzdnMSqSgA) **Explanation:** ``` L # Push a list in the range [1, first (implicit) input-integer] € # Map over each integer: × # Repeat each character in the (implicit) second input-list the integer # amount of times as string .c # Join each inner list to a string; then each string by newlines; # and then centralize each line by padding leading spaces # (after which it is output implicitly as result) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 123 bytes ``` i,j,c;p(char*s,int n){for(i=0;i<n;){printf("\n%*s",strlen(s)/2*(n-++i),"");for(c=0;s[c];c++)for(j=0;j++<i;)putchar(s[c]);}} ``` [Try it online!](https://tio.run/##bY0xDsIwDEX3niKKhBQ3qSisLicBhuJScAVJlBSWqmcPyYBY8ODh/f/1qLkRpcRmMoRe0b0PdTRsZ2FhGV1QfGiRO4uw@JDxqOTJbuooTZzD42pVhO2@VrbRmsFICVhGlEfxSGckraGAKYNJ644R/GsuFlVywHVNRfbs2aq34wGqpRL5vJKucULkJ43YtYDi58@Wb6m/0PC/sKYP "C (gcc) – Try It Online") ## Pretty Code: ``` // declare variables gcc-style i,j,c; p(char *s, int n){ // for every n for(i=0;i<n;){ // print [ strlen(s)/2 * (n-(i+1)) ] spaces printf("\n%*s",strlen(s)/2*(n-++i),""); // increment i instead of (i+1) // for every character in the input string for(c=0;s[c];c++) // for every repetition required for(j=0;j++<i;) // print the current character putchar(s[c]); } } ``` ]
[Question] [ As described in [this question](https://codegolf.stackexchange.com/questions/61808/lossy-sorting-implement-dropsort?rq=1): > > Dropsort, designed by David Morgan-Mar, is an example of a linear-time "sorting algorithm" that produces a list that is, in fact, sorted, but contains only some of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is simply removed from the list and discarded. > > > To use one of their test cases, an input of `{1, 2, 5, 4, 3, 7}` yields `{1, 2, 5, 7}`, as `4` and `3` are both dropped for being smaller than the previously "sorted" value, `5`. We don't want "sorting" algorithms, we want them to be the real deal. Therefore, I want you to write a program that, given a list of numbers, outputs a list of DropSorted lists (to be a complete sorting algorithm, we would need to merge these lists, but [merging two sorted lists](https://codegolf.stackexchange.com/questions/25461/merge-two-sorted-lists?rq=1) has been done before, and asking you to do it again is pretty much asking two questions, so this question is specifically the "splitting" step of our complete DropSort). The arrangement and content of our lists is crucial, however. The output of your program must be equivalent to the output of a DropSort, followed by a DropSort of the discarded values, and so on until you have only have a list of sorted chains. Again, borrowing the existing test suite (and adding two more): ``` Input -> Output {1, 2, 5, 4, 3, 7} -> {{1, 2, 5, 7}, {4}, {3}} {10, -1, 12} -> {{10, 12}, {-1}} {-7, -8, -5, 0, -1, 1} -> {{-7, -5, 0, 1}, {-8, -1}} {9, 8, 7, 6, 5} -> {{9}, {8}, {7}, {6}, {5}} {10, 13, 17, 21} -> {{10, 13, 17, 21}} {10, 10, 10, 9, 10} -> {{10, 10, 10, 10}, {9}} //Note equivalent values aren't dropped {5, 4, 3, 8, 7, 6} -> {{5, 8}, {4, 7}, {3, 6}} {0, 2, 5, 4, 0, 7} -> {{0, 2, 5, 7}, {4}, {0}} ``` You may assume the input is non-empty. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply! [Answer] # Haskell, ~~67 59~~ 58 bytes ``` (q:r)!x|x<last q=q:r!x|1<2=(q++[x]):r _!x=[[x]] foldl(!)[] ``` **Explanation:** Given a list of lists (that are already sorted) and a value `x`, the `!` operator will place `x` at the end of the first list whose last element is less than or equal to `x`. If no such list exists, the list `[x]` is placed at the end. [Try it online.](https://tio.run/##XYu/CsMgHIR3n@KEDkp@Q5P@D/FJRIqQSkNtUk0Gh767NUuHDMfdx8c97fx6eJ@zCG2UPH1T5@28IKjCBeuuUSJUlU5GtpHdeVK6bMOccpPvveBSm/y2wwiFfmLAJw7jgh0cdE1oCCfCkXAgXMxG7wlrbmtt3P90LT/C2eQf) [Answer] ## [Husk](https://github.com/barbuz/Husk), 10 bytes ``` hUmü<¡Ṡ-ü< ``` [Try it online!](https://tio.run/##yygtzv7/PyM09/Aem0MLH@5coAtk/P//P9pAx0jHVMdEx0DHPBYA "Husk – Try It Online") This is a combination of [my other Husk answer](https://codegolf.stackexchange.com/a/137560/32014) and [xnor's Haskell answer](https://codegolf.stackexchange.com/a/137607/32014). The duplicate `ü<` feels clunky, but I don't know how to get rid of it... ## Explanation The function `ü<` translates to `nubBy(>)` in Haskell. It traverses a list from left to right, keeping those elements for which no previously kept element is strictly greater. In other words, it performs dropsort. The leftover elements are obtained by taking list difference of the original list and the result of `ü<`. ``` hUmü<¡Ṡ-ü< Implicit input, say x = [2,3,5,4,4,2,7]. ¡ Iterate Ṡ- list difference between argument ü< and its dropsort: [[2,3,5,4,4,2,7],[4,4,2],[2],[],[],[],... m Map ü< dropsort: [[2,3,5,7],[4,4],[2],[],[],[],... U Prefix of unique elements: [[2,3,5,7],[4,4],[2],[]] h Drop last element: [[2,3,5,7],[4,4],[2]] ``` [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` import Data.List f[]=[] f l|r<-nubBy(>)l=r:f(l\\r) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrLTrWNjqWK00hp6bIRjevNMmpUsNOM8e2yCpNIycmpkjzf25iZp6CrUJKPpeCQkFRZl6JgopCmkK0oY6CkY6CqY6CiY6CsY6CeSyatIGOAghbgig0ObgmC6A@HQWzWGwmo5EQhlHsfwA "Haskell – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ ~~10~~ 9 bytes *5 bytes off using [@beaker](https://codegolf.stackexchange.com/users/42892/beaker)'s idea of cumulative maximum* ``` t"ttY>=&) ``` Input is a numeric row vector, in the format `[1, 2, 5, 4, 3, 7]` (commas are optional). The output contains lists separated by newlines, with the numbers in each list separated by spaces. [Try it online!](https://tio.run/##y00syfn/v0SppCTSzlZN8///aEMdBSMdBVMdBRMdBWMdBfNYAA) Or [verify all test cases](https://tio.run/##TY07CoBADER7TxEsFCGBzfovtPIIFooI2mu3919nYRWLEOYlj7lPd/nDu9S5dRyywu@5iOTLNPtNmSxTzVQxlUztnmxqmARcLYK0CB0GLy8H7pkAcWsgR0fhK5DVF8TpwwL7WqIKZH71JtQ/). ### Explanation Given an array, the code picks from it every entry that equals the cumulative maximum up to that entry. For example, given ``` 1 2 5 4 3 7 ``` the code picks the first, second, third and sixth entries: ``` 1 2 5 7 ``` Then the process is repeated on the subarray formed by the remaining entries (in the original order): ``` 4 3 ``` This needs to be done until the subarray of remaining entries is empty. An upper bound on the required number of iterations is the input size. The last iterations may not be needed. In that case they operate on an empty array, producing additional empty arrays. At the end, the stack contains the required arrays and possibly several empty arrays, which are not displayed at all. ``` t % Implicit input. Duplicate " % Do as many times as the input size tt % Duplicate twice Y> % Cumulative maximum = % Compare for equality. Will be used as logical index &) % Two-output indexing: pushes indexed subarray, and then % a subarray with the remaining entries % End (implicit) % Display stack (implicit). Empty arrays are not displayed ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 16 bytes ``` hUm₁≤¡₁> ṠfSz⁰G▲ ``` [Try it online!](https://tio.run/##yygtzv6vkHtiffGjpsaiQ9v@Z4TmAlmPOpccWgik7bge7lyQFlz1qHGD@6Npm/7//x9tqGOkY6pjomOsYx7LFW1ooKNrqGNoBGTqmuvoWujomupAhIAiljoWOuY6ZjqmEIWGxjqG5jpGhlAeGFkCCSAfYiBYdSwA "Husk – Try It Online") ## Explanation This first line is the main function, and the second is a higher order helper function (it takes a function as argument and returns a new function). It's accessed by the subscript `₁`. The idea is that `₁≤` performs dropsort and `₁>` gives the leftover elements. ``` ṠfSz⁰G▲ Helper function, takes binary function p (as ⁰) and list x (implicit). For example, p = (≤) and x = [2,4,3,4,5,2]. G▲ Left scan on x with maximum: [2,4,4,4,5,5]. Sz Zip with x ⁰ using the function p: [1,1,0,1,1,0]. Ṡf Keep elements of x at truthy indices: [2,4,4,5]. ``` In the main function, we iterate the leftovers function `₁>` and apply the dropsort function `₁≤` to the results. ``` hUm₁≤¡₁> Main function, implicit list argument, say x = [2,4,3,4,5,2]. ¡ Iterate ₁> the leftovers function: [[2,4,3,4,5,2],[3,2],[2],[],[],[],... m Map ₁≤ the dropsort function: [[2,4,4,5],[3],[2],[],[],[],... U Prefix of unique elements: [[2,4,4,5],[3],[2],[]] h Drop last element (an empty list): [[2,4,4,5],[3],[2]] ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~131 112 103~~ 95 bytes *Thanks a lot @Mr. Xcoder for a smashing 19 bytes!!* ### ***Thanks a lot @ovs for an amazing 17 bytes!*** ``` def f(x): a,*x=x or[0];m=[a];d=[] for i in x:[m,d][i<m[-1]]+=i, return[m]+(x and(d>[])*f(d)) ``` [Try it online!](https://tio.run/##RY7BasMwEETv@oo5SskaIqdtEifujyx7MCimOlgOwgX1650NUdKFYWHfzLC3v@VnTvt1DdcRoy2uMxhoU/qCOfNOzlPPg5xDz2IwzhkRMaF0PFEQjpeJGy@y7SMZ5OvymxNPsrUFQwo2fLO4zWiDc@sry@wJLeGT8EHYEw5CeIxhvyM0Sn1bT6igOSg4qjT08qjF8ImgZ6VfWvgfelZ5LffKWv8mFVSdHuvJDL//qYUi3S3HtNjRRueA9Q4 "Python 3 – Try It Online") ## Explanation: ``` def f(x): #recursive function taking list, returns list of lists if len(x)<2:return[x] #for a single element return [element] m=[x[0]];d=[] #initialize main and dropped lists for i in x[1:]:[m,d][i<m[-1]]+=[i] #append elements from the argument list accordingly into main and dropped list return[m]+(d>[])*list(f(d)) #add main-list along with further evaluated dropped-list(recursived) into a list of lists ``` [Answer] # [Haskell](https://www.haskell.org/), ~~113~~ ~~107~~ ~~102~~ 92 bytes ``` import Data.List a!(b:c)|b<last a=a!c|1>0=a++[b]!c a!b=a g x@(b:c)|i<-[b]!c=i:g(x\\i) g x=[] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrUVEjySpZsybJJiexuEQh0TZRMbnG0M7ANlFbOzopVjEZqCLJNpErXaHCAaIy00YXLGGbaZWuURETk6kJkrSNjv2fm5iZZ1tQlJlXopIebahjBISGOsY6JjpGsf8B "Haskell – Try It Online") This feels *really* long. # Explanation `!` performs the drop sort on a list, while `#` collects the trimmings. `g` then repeatedly applies `#` until the list is empty recording the results in a list. [Answer] # APL, 27 bytes ``` {⍵≡⍬:⍬⋄(⊂X/⍵),∇⍵/⍨~X←⍵≥⌈\⍵} ``` Explanation: * `⍵≡⍬:⍬`: if the input is empty, return the empty list * `X←⍵≥⌈\⍵`: all numbers greater or equal to the running maximum * `(⊂X/⍵)`: the list of those numbers, * `∇⍵/⍨~X`: followed by the result of running this function on the remaining numbers [Answer] # JavaScript (ES6), 64 bytes ``` f=(a,l,r=[])=>a+a&&[a.filter(e=>e<l?!r.push(e):(l=e,1)),...f(r)] ``` **Ungolfed:** ``` f=(a,l,r=[])=> a+a&& //any elements left? [a.filter( //filter elements that are in order, e=>e<l?!r.push(e):(l=e,1) //push unsorted elements to r ), //push() returns the new length of the array, //... so !push() will always return false ...f(r) //recurse on r ] ``` ``` f=(a,l,r=[])=>a+a&&[a.filter(e=>e<l?!r.push(e):(l=e,1)),...f(r)] console.log(JSON.stringify(f([1, 2, 5, 4, 3, 7]))); // [1, 2, 5, 7][4][3] console.log(JSON.stringify(f([10, -1, 12]))); // [10, 12][-1] console.log(JSON.stringify(f([-7, -8, -5, 0, -1, 1]))); // [-7, -5, 0, 1][-8, -1] console.log(JSON.stringify(f([9, 8, 7, 6, 5]))); // [9][8][7][6][5] console.log(JSON.stringify(f([10, 13, 17, 21]))); // [10, 13, 17, 21] console.log(JSON.stringify(f([10, 10, 10, 9, 10]))); // [10, 10, 10, 10][9] console.log(JSON.stringify(f([5, 4, 3, 8, 7, 6]))); // [5, 8][4, 7][3, 6] console.log(JSON.stringify(f([0, 2, 5, 4, 0, 7]))); // [0,2,5,7],[4],[0] ``` [Answer] # [R](https://www.r-project.org/), 61 bytes ``` f=function(x)if(sum(x|1)){print(x[b<-x==cummax(x)]);f(x[!b])} ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQjMzTaO4NFejosZQU7O6oCgzr0SjIjrJRrfC1ja5NDc3sQKoJlbTOg0oqpgUq1n7P00jWcPQQAeCLIGEpiYXWExHwUhHwVRHwURHwVhHwVxT8z8A "R – Try It Online") Recursive function. `sum(x|1)` is shorthand for `length(x)`, so this recursion will run untill `x` is empty. `cummax` takes the cumulative maximum of `x`, which is then compared to `x` again. This produces a boolean vector of length `x`, where all the TRUEs correspond to sorted values. We use that to take a subset of `x` and `print` it. The function is then called again on the remainder of `x`. [Answer] # Java 8, ~~182~~ ~~179~~ 177 bytes ``` import java.util.*;l->{List r=new Stack(),t;for(int p,i,x;l.size()>0;)for(p=l.get(0),r.add(t=new Stack()),i=0;i<l.size();p=x)if((x=l.get(i++))>=p)t.add(l.remove(--i));return r;} ``` -3 bytes thanks to *@Nevay*. -2 bytes by using `Stack` instead of `Vector`. **Explanation:** [Try it here.](https://tio.run/##rZJfb8IgFMXf/RT3ESbF1v1xBmuyxyWbWeLjsgdW0aBIG3rrdMbP7m61LiZ7XJvQlgvnx@HAUm90lBfGL2ero10XeUBYUk1WaJ28UQDQ68GbpnI@h88dmijLK4@dzOmyhFdt/b4DYD2aMNeZgUndBXixJULGnkLQu/p/9EwzFiaMwXFFMw4depWo0WYwAQ8pHF003p9kIfXmC6aosxXjAtU8D4wWgEJYsVVOlvbbMD6OFa9HitTJhUEWcxGkns0YXsu5sGms7OiiUkW65XbO2LaR2W6X83FacDyJnQxmnW8MiyLLuQoGq@AhqMNR1Y6L6tOR48b4JrczWFMEbIrB@sX7B2h@3v90V6JZy7xCWdAQOs@8zFjt7G8m55hKqcu6zBIBfQH3Au4E3AoYcHrU/6mxgIjQSb8dXjQg3iM1MnpBt0MeCiAu4R8ohfY2n1CWCVH7SYvMpg3rTzvY33NvMmiHGl/dqfjqTh06h@MP) ``` import java.util.*; // Required import for List and Vector l->{ // Method with ArrayList<Integer> parameter and List return-type List r=new Stack(), // Return-List t; // Temp-List for(int p,i,x; // Some temp integers l.size()>0;) // Loop (1) as long as there are still items left in the list for(p=l.get(0), // Set `p` to the first item of the list r.add(t=new Stack()), // Add a new inner List to the result-List i=0;i<l.size(); // Inner loop (2) from 0 to the size of the list (exclusive) p=x) // After every iteration, save the previous value in `p` if((x=l.get(i++))>=p) // If the current item is equal or larger than the previous: t.add(l.remove(--i)); // Add it to the temp-List, and remove it from the input-List // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r; // Return result-List } // End of method ``` [Answer] # C#, ~~188~~ 203 bytes ``` int[][]f(int[]a){int[]t=a.Where((n,i)=>i<1||n>=a[i-1]).ToArray(),m=a.Where((n,i)=>i>0&&n<a[i-1]).ToArray();var s=new int[][]{t}.ToList();if(m.Any())s.AddRange(f(m));return s.ToArray();} ``` The byte count includes +18 for: ``` using System.Linq; ``` [Try it online!](https://tio.run/##hZPda8IwEMDf/SuOPkjCYrHuw4lWEN@Gg6EDH8SHUE8N2HRLMofU/u3u/KhanHo0XJv73fUud4lsJU50stEyRvslI4TByjqM/Z7S36W0BCTRQloLH7v3/c5WrJNORbBM1ATepdKMH00naCtKu9F4NAaH1nWlRQthwV6kt6Lxl/gUAgE1Ac8CngQ8CqhDJq6zVQEVcghqt6hKnahXWhQ0d7jFNwQQTU4vlMe93weUY0BsLbhLHlZjq27Bx9oPWdxiq2enVf3ntLJmqfA9TQzKaA5s16Bje6hfp1bxO53qJtomC/SHRjmkkUHmpR480HAYpWf@W0Jz4QmgZ8ryoNwf4AIjxySEbbjGS07bXubxXDeLxRRryfPoo5zs0jjDz9D9zG4OEzndVy55utMulP5wjgYZ00LxsK1awXqt26EcqUow5v5n0jFGrhgX8QXarpbLunVBNpfSgA2pRfk1SF1G5p6yjqxqymK/ownk1u9MJn2pZ8hok/OmQfdjNNizYNlmX0@2@QM "C# (Mono) – Try It Online") [Answer] # C++14, ~~118~~ 108 bytes Using the algorithm from [w0lf's Haskell answer](https://codegolf.stackexchange.com/a/137563/53667). As unnamed generic lambda. First parameter is a container of the values to dropsort (like `vector<int>`) and second parameter requires a compatible empty container of containers (like `vector<vector<int>>`) for the return value via reference. In the first version of the program, there was `R.clear;()` as first statement, so that the container of containers didnt need to be empty. Peter Cordes thought this could into the specification, so dropping 10 byte for that. ``` [](auto A,auto&R){for(auto x:A){for(auto&D:R)if(D.back()<x){D.push_back(x);goto F;}R.emplace_back(1,x);F:;}} ``` [Try it online!](https://tio.run/##TZDbasMwDIbv9RSigxKDl7Q7U6eBQugDhN2NMTzHabPlRGyPQPCzZ07Sht5Y1qdf/mWJprk/CTHc5ZUoTCrDvFa6lbyMYEF/Uui6jQCMyqsTVryUquFCotIpA@BG15jth49Pb7yuD3QKCekTXxSStx5hWd1ORex2B9Jfs3W8S0ieebH/zcWvR8KO9LHfGHX@mkBH2Kl2TUdmE1@WTeFM58qWutpxx6wd3AR5pbHkeeWRHuZhQ4cifJdKC64k7hGCAPstxQeKzxSfKD5SfLUzXsCbYxRfHMZ@c6PdTFoEZ3V5/sYlwkQqU2gGc7yZ/@pPXGO2ZHTWEYZB8GOURvdDLcd4lnhZmNPXLS5Lmht6wIW6RcYjQFEbjWGI3XisKK4YoIUFyyotGFgAO/wD "C++ (gcc) – Try It Online") Ungolfed: ``` [](auto A,auto&R){ for(auto x:A){ //foreach item for(auto&D:R) //foreach result list if(D.back()<x){ //x bigger than last element D.push_back(x); //add x goto F; //break and jump over the emplace } R.emplace_back(1,x);//create new list with this element F:; } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes -4 bytes thanks to Arnold Palmer ``` b,r=input(),[] for i in b: for l in r: if l[-1]<=i:l+=[i];break else:r+=[[i]] print r ``` [Try it online!](https://tio.run/##TY3NCsIwEITP5imWnhS30NSf2mieJORga0qDIS2xoj593EArHoZlvt3ZGT9TP/gytsPNyCzLYoNBWj8@p/UGlWbdEMCC9dAIBsm4ZIJgK9uBUznXF2mF20pl9bkJ5npnYNzDiECImGZjsH6CEOk5e/XWGeDCvE0LqTIqjlAiHBD2CDuESjPFC4ScOC/J5BWZE4lOFk64RiBIuyOF5wynPCdU8gXMqtMg9muZo4SKv/oi1X8B "Python 2 – Try It Online") Solution similar to @w0lf's haskell [answer][1] Rare use case for `for-else` construction Iterate through sorted lists `for l in r` (empty at start). If element(from input) `i` is larger than last element of list `l[-1]`, add element to list `l+=[i]`, break. If no list was accepted, add new list with this elemens `r+=[[i]]` [Answer] # JavaScript (ES6), ~~71~~ ~~70~~ 68 bytes ``` a=>a.map(n=>(o.find(b=>[...b].pop()<=n)||(n=[n],o)).push(n),o=[])&&o ``` Pretty simple, just iterates the array, looks for the first inner array whose last value is `<=` to the next value to drop, if none exists, append a new inner array with the next value to the output, otherwise append the next value to the first found inner array that matches the condition. ### Updates Thanks to Neil, saved three bytes converting `(...,o)` to `...&&o` and re-organizing the callback to `map()` to be more compact. ``` f=a=>a.map(n=>(o.find(b=>[...b].pop()<=n)||(n=[n],o)).push(n),o=[])&&o;[[1,2,5,4,3,7],[10,-1,12],[-7,-8,-5,0,-1,1],[9,8,7,6,5],[10,13,17,21],[10,10,10,9,10],[5,4,3,8,7,6],[0,2,5,4,0,7]].map(f).map(JSON.stringify).map(v=>console.log(v)) ``` ``` .as-console-wrapper{max-height:100%!important} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 29 bytes ``` @lOpP)<1}a@=f_<VªOoV=Z+S}V=Ug ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=QGxPcFApPDF9YUA9Zl88VqpPb1Y9WitTfVY9VWc=&input=WzUsIDQsIDMsIDgsIDcsIDZd) [Answer] # [C (gcc)](https://gcc.gnu.org/), 176 175 173 bytes ``` #define P(x)printf("%d ",t=x); l[2][99];t;x;i;j;w;main(a){while(scanf("%d",*l+w)>0)++w;while(i=w){P(l[a=!a][w=0])for(j=1;j<i;++j){x=l[a][j];x<t?l[!a][w++]=x:P(x)}puts("");}} ``` [Try it online!](https://tio.run/##JY7LCsIwFET3fkWNCLmmQnVXb6O/0H3IIvShCTGWNpJA6bfX2sIwm3MGpjo/q2qeD3XTatckJY3Q9dr5lpJjnZDU8wi4s@IqRZ5L9BhRo8GAb6UdVTCGl7YNHSrl1glJT5YFuGfAWMANah5gLKkViu@VFIFnEtpPTw2/oCk0MmZgjHzhUhiJsfAPK1aTMcnj7X9q6r5@oIQATtM8X7JkS77UDw "C (gcc) – Try It Online") Somewhat readable version: ``` #define P(x)printf("%d ",t=x); l[2][99];t;x;i;j;w; main(a) { while(scanf("%d",*l+w)>0)++w; while(i=w) { P(l[a=!a][w=0]) for(j=1;j<i;++j) { x=l[a][j]; x<t?l[!a][w++]=x:P(x) } puts(""); } } ``` [Answer] # PHP, ~~91~~ ~~103~~ ~~96~~ 85 bytes (Edited to add 12 chars of `print_r($r);` to meet requirement to output) (Edited to remove 7 bytes when allowing PHP Errors) (Edited to remove 11 bytes when golfing the assignment further) ``` while($a){$b=$d=[];foreach($a as$i)${max($b)>$i?d:b}[]=$i;$a=$d;$r[]=$b;}print_r($r); ``` Given input `$a`, it produces result `$r` Pretty: ``` while ($a) { $b = $d = []; foreach ($a as $i) { ${max($b) > $i ? d : b}[] = $i; } $a = $d; $r[] = $b; } ``` The pseudo-recursive outer loop initializes the keep `$b` and discard `$d` arrays to empty, then does a basic drop sort loop, finally setting the discards as the new input and adding the keeps to the result `$r` [Answer] # [PHP](https://php.net/), ~~102 bytes~~, 98 bytes ``` <?php function s($i){static$s;foreach($i as$v)${$v<max($l)?f:l}[]=$v;$s[]=$l;!$f?:s($f);return$s;} ``` [Try it online!](https://tio.run/##NYxNCoMwEEb3nmIKs0ggm/5RMIoX6A1ESggGAzaGzCgF8expuujqwcf7Xpxizk0XpwhuDZb9EoAEerkTG/YWSbsljcZOZQRDuEnccWve5iNwlp2r56MfWtw00o@zPqHr6pJwUqeR1xRK4sjII/HTE0ML/VnBRcFdwU3BVcFj0FUVkw/8SqI8/6qUOn8B "PHP – Try It Online") *-4 bytes, thanks to @Umbrella* **Explanation** ``` <?php ``` The function takes the input list as an array. ``` function s($i) { ``` `$s`, which will become the finally returned list of lists, is declared static. This extends its scope to *all* calls of this function, allowing the function to be called recursively without having to pass this result list as an argument or to return it. ``` static $s; ``` Loop through each value in the list. ``` foreach ($i as $v) ``` Is it less than the biggest current list member? ``` $v < max($l) ? ``` Yes, put it on list `$f` for further sorting. ``` $f[] = $v : ``` No, put it on list `$l`. ``` $l[] = $v; ``` Push list `$l` onto the list of lists. ``` $s[] = $l; ``` If there's anything in list `$f`, send it round again for further sorting. ``` !$f ?: s($f); ``` Return the list of lists. ``` return $s; } ``` [Answer] ## Sage, 102 bytes ``` def f(w,a=[]): for x in w: q,c=exists(a,lambda b:b[-1]<=x) if q:c+=[x] else:a+=[[x]] return a ``` Very similar to @Dead Possum's [answer](https://codegolf.stackexchange.com/a/137573/137573). Appends each member `x` of `w` to the first list in `a` {list of lists} with `x` greater than it's last element. if none, appends `[x]` to `a`. I would really like it if `exists` returned `a` if nothing was found! Also trying to apply @officialaimm's [one-line](https://codegolf.stackexchange.com/a/137553/137553) idea ... Question: If I removed my code from the function, I'd have to assign `w` to input right? So would it save bytes? [Answer] # [Ocaml](https://ocaml.org), ~~69~~ 62 bytes ``` let rec d=function h::i::t when h>i->d(h::t)|h::t->h::d t|x->x ``` Explanation: ``` let rec d = function (* Implicitly take an list as a parameter *) (* If the list starts with two elements h and i and h is greater than i, drop i and sort the list starting with h and the rest t *) | h::i::t when h > i -> d (h::t) (* If h is not greater than i, make a new list starting with h and a tail containing the drop sorted rest *) | h::t -> h::d t (* If none of the cases apply, the list is empty. *) | x -> x ``` [Answer] # APL, ~~100~~ ~~88~~ ~~83~~ ~~79~~ ~~78~~ ~~57~~ ~~56~~ ~~77~~ 76 bytes ``` {(E/⍵),⊂⍵/⍨~E←(⍬≢⍴)¨⍵}∘{⍵≡(S←¯1↓⍵),⊃⊃⌽⍵:⍵⋄∇S,⊃⌽⍵}{⍵≡X←⍵/⍨~V←⍵≠⌈\⍵:⍵⋄X(∇V/⍵)} ``` -0 bytes thanks to Kritixi Lithos... [Try it online!](http://tryapl.org/?a=%28%7B%28E/%u2375%29%2C%u2282%u2375/%u2368%7EE%u2190%28%u236C%u2262%u2374%29%A8%u2375%7D%u2218%7B%u2375%u2261%28S%u2190%AF1%u2193%u2375%29%2C%u2283%u2283%u233D%u2375%3A%u2375%u22C4%u2207S%2C%u2283%u233D%u2375%7D%7B%u2375%u2261X%u2190%u2375/%u2368%7EV%u2190%u2375%u2260%u2308%5C%u2375%3A%u2375%u22C4X%28%u2207V/%u2375%29%7D%29%2810%20%AF1%2012%200%201%29&run) There's got to be some better way to do this ([There is](https://codegolf.stackexchange.com/a/137919/55550)). Any tips are very greatly appreciated and welcome. ## How? (Note, some of this explanation might be wrong, as I forgot how this worked) ``` {⍵≡X←⍵/⍨~V←⍵≠⌈\⍵:⍵⋄X(∇V/⍵)} - separate the argument into nested drop-sorts {⍵≡(S←¯1↓⍵),⊃⊃⌽⍵:⍵⋄∇S,⊃⌽⍵} - un-nesting (passed the result of the above) {(E/⍵),⊂⍵/⍨~E←(⍬≢⍴)¨⍵}∘ - fixing array mishaps (passed the result of the above) ``` [Answer] # Jelly, 26 bytes ``` <»\¬x@ðW;µ⁸Ñ <»\x@µÑ 1Ŀ¹L? ``` This is the same method as marinus' APL answer. [Try it online!](https://tio.run/##y0rNyan8/9/m0O6YQ2sqHA5vCLc@tPVR447DE7lAYhUOh7YCmYZH9h/a6WP//3C7@///0YY6CkY6CqY6CiY6CsY6CuaxAA). [Answer] # JavaScript [(Node.js)](https://nodejs.org), ~~125~~ ~~109~~ 106 bytes -~~16~~ 18 bytes from Zacharý -1 by removing `{` and `}` by changing the incrementer to include the "set last to the current" ``` m=x=>{z=[[],[]];l=NaN;for(i=0;i<x.length;l=x[i++])if(l>x[i])z[1].push(x[i]);else z[0].push(x[i]);return z} ``` Basically, asks is the current item greater than the last item, add to the first list. Otherwise, add to the second. Found out during this that comparing any number to `NaN` will always result `false`. Interesting! Explanation: ``` m = x => { // Create function z = [[], []]; // Initialize dropsort output l = NaN; // Initialize last element for (i = 0; i < x.length; l=x[i++])// For each item in input... if (l > x[i]) // If current item is greater than previous z[1].push(x[i]); // Then add it to the first part of output else // Elsewise z[0].push(x[i]); // Add it to the nonordered part of the dropsort // Set last item to current item } // Repeat return z // Return finished dropsort } // End function ``` [Try it online!](https://tio.run/##dY9NDoIwEIX3nmKWJRbS4i@p9QheoOmCaJWaSgmgIRjPjqNBowabTNqZ92Ve3zG9pNW2tEUd5n5nuu4kG7m@tlIpTZXWwslNuhF7XxIrmbCrJnImP9QZCo2y47EO7J64Nb510Cquo@JcZeTZCuMqA61iX8PS1Ocyh/bWbX1eeWci5w/kRBSnEFOYUZhSmFBY6CAQo1@GUQgR5PGQGi5QXWLhkhc4xCUUkEJ4jn7/bDj@gSMT879EX8njGoLeWXq3IYZ9pGav1F1/7g) ]
[Question] [ Print all the numbers from 0-100 in the right order using the Danish way of counting # How they count * Like English, they have dedicated words for 0-20, 30, 40 and 100 * Instead of saying `twenty-one` and `twenty-two`, they say `one and twenty` and `two and twenty` * Starting with fifty they say multiples of 10 as n\*20 ``` 50 = half third times twenty = half way to the 3rd multiple of 20 60 = three times twenty 70 = half fourth times twenty 80 = four times twenty 90 = half fifth times twenty ``` So for instance, 55 would be `five and half third times twenty`. # Expected output ``` zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty one and twenty two and twenty three and twenty four and twenty five and twenty six and twenty seven and twenty eight and twenty nine and twenty thirty one and thirty two and thirty three and thirty four and thirty five and thirty six and thirty seven and thirty eight and thirty nine and thirty forty one and forty two and forty three and forty four and forty five and forty six and forty seven and forty eight and forty nine and forty half third times twenty one and half third times twenty two and half third times twenty three and half third times twenty four and half third times twenty five and half third times twenty six and half third times twenty seven and half third times twenty eight and half third times twenty nine and half third times twenty three times twenty one and three times twenty two and three times twenty three and three times twenty four and three times twenty five and three times twenty six and three times twenty seven and three times twenty eight and three times twenty nine and three times twenty half fourth times twenty one and half fourth times twenty two and half fourth times twenty three and half fourth times twenty four and half fourth times twenty five and half fourth times twenty six and half fourth times twenty seven and half fourth times twenty eight and half fourth times twenty nine and half fourth times twenty four times twenty one and four times twenty two and four times twenty three and four times twenty four and four times twenty five and four times twenty six and four times twenty seven and four times twenty eight and four times twenty nine and four times twenty half fifth times twenty one and half fifth times twenty two and half fifth times twenty three and half fifth times twenty four and half fifth times twenty five and half fifth times twenty six and half fifth times twenty seven and half fifth times twenty eight and half fifth times twenty nine and half fifth times twenty one hundred ``` # Rules * You may use any separator to separate the numbers * Due to a typo in the original specification, you may use `forth` instead of `fourth`. * You may write a function or write to std-out * Standard loopholes apply * This is codegolf; shortest code in bytes win! [Answer] # JavaScript (ES6), ~~347~~ ~~336~~ ~~326~~ ~~325~~ 308 bytes ``` for(a=btoa`...`.split(i=0);i<101;i++)alert(i<13?a[i]:i<20?(a[i]||a[i-10])+"teen":i>99?"one hundred":(i%10?a[i%10]+" and ":"")+(i<30?"twenty":i<40?"thirty":i<50?"forty":(i%20>9?"half "+["third","forth","fifth"][i/20-2|0]:a[i/20|0])+" times twenty")) ``` Before running, replace the `...` with the result of running this code: ``` atob("zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh") ``` Or you could just use the uncompressed version: ``` for(a="zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh".split(i=0);i<101;i++)alert(i<13?a[i]:i<20?(a[i]||a[i-10])+"teen":i>99?"one hundred":(i%10?a[i%10]+" and ":"")+(i<30?"twenty":i<40?"thirty":i<50?"forty":(i%20>9?"half "+["third","forth","fifth"][i/20-2|0]:a[i/20|0])+" times twenty")) ``` Still probably not optimal. 11 bytes saved in part by @Titus. [Answer] # [Fourier](http://esolangs.org/wiki/Fourier), 7028 bytes *The bounty will go to [**Paul Schmitz's answer**](https://codegolf.stackexchange.com/a/92812/59035)* This was [golfed programmatically](http://meta.codegolf.stackexchange.com/questions/10029/auto-golfing-good-or-bad) using issacg's [golfing program](https://ideone.com/Wjjz8M) ``` 122a101a114a-3a10a111ava-9a10a116a+3a-8a10a116a104a114a101aa10a102a+9a+6a-3a10a102a+3a118a101a10a115a105a120a10a115a101a118a101a+9a10a101a+4a-2a^a116a10a110a-5a+5a-9a10a116a101a+9a10a101a+7a-7a118a101a+9a10a116a+3a101a+7a118a101a10a116a104a^a+9a+2a101aa+9a10a102a+9a+6a-3a+2a101aa+9a10a102a+3a-3a116a101aa+9a10a115a105a120a-4a101aa+9a10a115a101a118a101a+9a+6a101aa+9a10a101a+4a-2a^a116a101aa+9a10a110a-5a+5a-9a116a101aa+9a10a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a^a+9a+2a+5a10a111ava-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a+3a-8a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a104a114a101aa32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+3a118a101a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a105a120a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a^a+9a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a^a+9a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+3a+2a+5a10a111ava-9a32a97a110a100a32a102a+9a+3a+2a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+3a+2a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+3a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+3a+2a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+3a+2a+5a10a115a105a120a32a97a110a100a32a102a+9a+3a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+3a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+3a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+3a+2a+5a10a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a104a117a-7a100a114a101ava ``` [**Try it online!**](http://fourier.tryitonline.net/#code=MTIyYTEwMWExMTRhLTNhMTBhMTExYXZhLTlhMTBhMTE2YSszYS04YTEwYTExNmExMDRhMTE0YTEwMWFhMTBhMTAyYSs5YSs2YS0zYTEwYTEwMmErM2ExMThhMTAxYTEwYTExNWExMDVhMTIwYTEwYTExNWExMDFhMTE4YTEwMWErOWExMGExMDFhKzRhLTJhXmExMTZhMTBhMTEwYS01YSs1YS05YTEwYTExNmExMDFhKzlhMTBhMTAxYSs3YS03YTExOGExMDFhKzlhMTBhMTE2YSszYTEwMWErN2ExMThhMTAxYTEwYTExNmExMDRhXmErOWErMmExMDFhYSs5YTEwYTEwMmErOWErNmEtM2ErMmExMDFhYSs5YTEwYTEwMmErM2EtM2ExMTZhMTAxYWErOWExMGExMTVhMTA1YTEyMGEtNGExMDFhYSs5YTEwYTExNWExMDFhMTE4YTEwMWErOWErNmExMDFhYSs5YTEwYTEwMWErNGEtMmFeYTExNmExMDFhYSs5YTEwYTExMGEtNWErNWEtOWExMTZhMTAxYWErOWExMGExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTExMWF2YS05YTMyYTk3YTExMGExMDBhMzJhMTE2YSszYTEwMWErOWErNmErNWExMGExMTZhKzNhLThhMzJhOTdhMTEwYTEwMGEzMmExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTExNmExMDRhMTE0YTEwMWFhMzJhOTdhMTEwYTEwMGEzMmExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTEwMmErOWErNmEtM2EzMmE5N2ExMTBhMTAwYTMyYTExNmErM2ExMDFhKzlhKzZhKzVhMTBhMTAyYSszYTExOGExMDFhMzJhOTdhMTEwYTEwMGEzMmExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTExNWExMDVhMTIwYTMyYTk3YTExMGExMDBhMzJhMTE2YSszYTEwMWErOWErNmErNWExMGExMTVhMTAxYTExOGExMDFhKzlhMzJhOTdhMTEwYTEwMGEzMmExMTZhKzNhMT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k3YTEwOGEtNmEzMmExMDJhKzNhLTNhMTE2YTEwNGEzMmExMTZhMTA1YSs0YS04YTExNWEzMmExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTExNWExMDFhMTE4YTEwMWErOWEzMmE5N2ExMTBhMTAwYTMyYTEwNGE5N2ExMDhhLTZhMzJhMTAyYSszYS0zYTExNmExMDRhMzJhMTE2YTEwNWErNGEtOGExMTVhMzJhMTE2YSszYTEwMWErOWErNmErNWExMGExMDFhKzRhLTJhXmExMTZhMzJhOTdhMTEwYTEwMGEzMmExMDRhOTdhMTA4YS02YTMyYTEwMmErM2EtM2ExMTZhMTA0YTMyYTExNmExMDVhKzRhLThhMTE1YTMyYTExNmErM2ExMDFhKzlhKzZhKzVhMTBhMTEwYS01YSs1YS05YTMyYTk3YTExMGExMDBhMzJhMTA0YTk3YTEwOGEtNmEzMmExMDJhKzNhLTNhMTE2YTEwNGEzMmExMTZhMTA1YSs0YS04YTExNWEzMmExMTZhKzNhMTAxYSs5YSs2YSs1YTEwYTExMWF2YS05YTMyYTEwNGExMTdhLTdhMTAwYTExNGExMDFhdmE) [Answer] # JavaScript (ES6), non-competing I decided to do what the title actually asked, and counted to 100 på dansk. This is based on [ETHproductions' answer](https://codegolf.stackexchange.com/questions/92657/count-to-100-in-danish/92668#92668). It is 292 bytes (286 if you use alert instead) ``` for(a="nul0en0to0tre0fire0fem0seks0syv0otte0ni0ti0elleve0tolv0tret0fjor0fem0seks0syt0at0nit".split(i=0);i<101;i++)console.log(i<13?a[i]:i<20?(a[i])+"ten":i>99?"hundrede":(i%10?a[i%10]+"og":"")+(["tyve","tredive","fyrre","halvtreds","tres","halvfjerds","firs","halvfems"][Math.floor(i/10)-2])) ``` [Answer] # [///](http://esolangs.org/wiki////), 434 bytes ``` /(/\/\///D/\/7(7/ and (2/twenty(4/ times (_/half ([/42 (&/three(;/thir()/four(!/fort($/_fifth[(#/seven(^/eight(@D;ty (%D_!h[(*D_;d[(-/nine(`D!y (F/five(T/teen (O/one(X/six(GD&[(HD)[(ID2 (Y/two(AD$/zero O Y & ) F X # ^ - ten eleven twelve ;T)TfifTXT#T^een -T2 OIYI&I)IFIXI#I^I-I;ty O@Y@&@)@F@X@#@^@-@!y O`Y`&`)`F`X`#`^`-`_;d42 O*Y*&*)*F*X*#*^*-*&[OGYG&G)GFGXG#G^G-G_!h[O%Y%&%)%F%X%#%^%-%)[OHYH&H)HFHXH#H^H-H$OAYA&A)AFAXA#A^A-AO hundred ``` [Try it online!](http://slashes.tryitonline.net/#code=LygvXC9cLy8vRC9cLzcoNy8gYW5kICgyL3R3ZW50eSg0LyB0aW1lcyAoXy9oYWxmIChbLzQyCigmL3RocmVlKDsvdGhpcigpL2ZvdXIoIS9mb3J0KCQvX2ZpZnRoWygjL3NldmVuKF4vZWlnaHQoQEQ7dHkKKCVEXyFoWygqRF87ZFsoLS9uaW5lKGBEIXkKKEYvZml2ZShUL3RlZW4KKE8vb25lKFgvc2l4KEdEJlsoSEQpWyhJRDIKKFkvdHdvKEFEJC96ZXJvCk8KWQomCikKRgpYCiMKXgotCnRlbgplbGV2ZW4KdHdlbHZlCjtUKVRmaWZUWFQjVF5lZW4KLVQyCk9JWUkmSSlJRklYSSNJXkktSTt0eQpPQFlAJkApQEZAWEAjQF5ALUAheQpPYFlgJmApYEZgWGAjYF5gLWBfO2Q0MgpPKlkqJiopKkYqWCojKl4qLSomW09HWUcmRylHRkdYRyNHXkctR18haFtPJVklJiUpJUYlWCUjJV4lLSUpW09IWUgmSClIRkhYSCNIXkgtSCRPQVlBJkEpQUZBWEEjQV5BLUFPIGh1bmRyZWQ&input=) [Answer] # PHP, ~~397~~ ~~375~~ ~~372~~ ~~381~~ ~~386~~ 365 bytes This was too funny to be ignored. It can possibly be golfed further. ``` zero_<?=join(_,$a=[one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen])._;foreach([twenty,thirty,forty]as$t)for($i=-2;$i++<8;)echo($i<0?'':$c[]="$a[$i] and ").$t._;foreach([third,three,fourth,four,fifth]as$k=>$t)for($i=-2;$i++<8;)echo$c[$i],($k&1?'':'half '),"$t times twenty_";?>one hundred ``` * It uses underscore as the separator * 10 to 19 are still hardcoded; any way to compute them doesn´t give as much as the join. [Answer] # Mathematica ~~251 238~~ 230 bytes This now presents the output in the format of a list, to save 8 more bytes. ``` c@s_:=s<>" times twenty";f@n_:=Which[n<21∨{30,40,100}~MemberQ~n,IntegerName@n,n==50,c@"half third",n==60,c@"three",n==70,c@"half forth",n==80,c@"four",n==90,c@"half fifth",3>2,NumberExpand@n/.{t_,u_}:>f@u<>" plus "<>f@t];f/@0~Range~100 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~445~~ ~~426~~ ~~452~~ ~~449~~ ~~444~~ 439 bytes ``` *t[]={0,0,"twenty","thirty","fourty",[10]="one hundred","third","fourth","fifth"},*o[101]={"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};i,p;main(j){for(;i<'e';i++)p=i%10,o[i]?puts(o[i]):printf("%s%s%s%s%s%s\n",p?o[p]:t,p?" and ":t,!t[j]&j%2?"half ":t,t[j]?t:j%2?t[j/2+9]:o[j/2],t[j]?t:" times ",t[j=i/10]?:t[2]);} ``` [Try it online!](https://tio.run/##RZFRboMwEESvQi3RQKAK8Bco4iCuPxCYsIjYljFJ24iz07UBVZa8z7M7o5XcfNyaZl3PhrLylcRJTMyTC/NDEHrQDjo5O6BpwkoiBff6WbSat/tQe8z0FqDDusRnieMphpJfriU20Gfnn9K5NOe7y3ke9jXBt735gwusHG69wSpgM27iuHdxy9GZ3JbcaW6HHXGLjTD0IGvd2YVvaPMdLgXEqrjXIIIhfHVSBwV8nvipgCgKVQl@msSSAqvUbKbAUpgrDcJ0AfGn//OFqaqSVLHcIBCvFq1HkN8MHdj74GcV6euxc5qVKpNbEfGSRVeWSwvsaBHPwJ1PHrFCCRf8hCo3NGNhsazrHw "C (gcc) – Try It Online") ~~19~~ ~~22~~ 27 bytes shaved off thanks to @ceilingcat, but 26 bytes were added again, 3 to prevent a segfault (o[] really has to have 101 entries), and upon checking the rules again I noticed we had to print out all numbers from 0 to 100, not just provide a function that printed one number. Ungolfed: ``` char *t[] = {0, 0, "twenty", "thirty", "fourty", 0, 0, 0, 0, 0, "one hundred", "third", "fourth", "fifth"}; char *o[101] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; int i = 0; int j = 0; int p = 0; main() { for(; i < 101; i++) { p = i % 10; if(o[i]) puts(o[i]); else printf("%s%s%s%s%s%s\n", p ? o[p] : "", p ? " and " : "", !t[j] & j % 2 ? "half " : "", t[j] ? "" : j % 2 ? t[j / 2 + 9] : o[j / 2], t[j] ? "" : " times ", t[j = i / 10] ? : t[2] ); } } ``` ``` [Answer] # Haskell, ~~308~~ ~~291~~ 285 bytes ``` w=words;q x=map(++x);m=w"thir four fif six seven eigh nine";t=w"zero one two three four five six seven eight nine ten eleven twelve"++q"teen"m++q"ty"(do b<-"twen":take 2m++q" times twen"["half third",t!!3,"half fourth",t!!4,"half fifth"];b:q b(q" and ".take 9$tail t))++["one hundred"] ``` **Readable version:** ``` w = words m = w "thir four fif six seven eigh nine" q x = map (++x) t = w "zero one two three four five six seven eight nine ten eleven twelve" ++ q "teen" m ++ q "ty" (do b <- "twen" : take 2 m ++ q " times twen" ["half third",t!!3,"half fourth",t!!4,"half fifth"] b:q b(q" and ".take 9$tail t) ) ++ ["one hundred"] ``` Also 285 ``` w=words;m=w"thir four fif six seven eigh nine";x!l=map(++x)l t = w"zero one two three four five six seven eight nine ten eleven twelve" ++ "teen"!m ++ "ty"!( do x<-"twen":take 2m++" times twen"! ["half third",t!!3,"half fourth",t!!4,"half fifth"] x:x!(" and "!take 9(tail t))) ++ ["one hundred"] ``` It might not look much different, but it represents hours of factorization that eventually brought me full circle. I think I have done this before.. [Answer] # PHP, ~~333~~ ~~328~~ 321 bytes @ETHproductions´s expression ported to PHP and golfed down. I am surprised that PHP can beat JavaScript *without any builtins*. I guess the mightiest builtins are the implicit typecasts: * I need no quotes for most of the strings, that alone is worth 12 bytes; * and it allows me to use an array directly instead of splitting a string. * the array indexing is implicitly typecasting any floats to integer, saving 6 bytes. **BUT:** I need `$`s (21 of them) to tell PHP that it´s a variable. So it´s still unclear where the 15 bytes actually come from. I didn´t golf away that much. Or did I? ETH caught up. ``` <?$a=[zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,'',fifteen,'','',eighteen];for($n=-1;$n++<99;)echo$n>19?($n%10?$a[$n%10].' and ':'').($n>49?($n%20>9?"half ".[third,forth,fifth][$n/20-2.5]:$a[$n/20]).' times twenty':[twen,thir,'for'][$n/10-2].ty):($a[$n]?:$a[$n%10].teen),_;?>one hundred ``` [Answer] # Fourier, 7020 bytes ``` 122a101~za114a-3a10a111ava-9a10a116a+3a-8a10a116a104a114a101aa10a102a+9a+6a-3a10a102a+3a118a101a10a115a105a120a10a115a101a118a101a+9a10a101a+4a-2a^a116a10a110a-5a+5a-9a10a116a101a+9a10a101a+7a-7a118aza+9a10a116a+3a101a+7a118a101a10a116a104a^a+9a+2a101aa+9a10a102a+9a+6a-3a+2a101aa+9a10a102a+3a-3a116a101aa+9a10a115a105a120a-4a101aa+9a10a115a101a118aza+9a+6a101aa+9a10aza+4a-2a^a116a101aa+9a10a110a-5a+5a-9a116a101aa+9a10a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a114azaa32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+3a118aza32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a^a+9a+2a+5a10a111ava-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a+3a-8a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a104a114a101aa32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+3a118a101a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a105a120a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a^a+9a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a^a+9a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+3a+2a+5a10a111ava-9a32a97a110a100a32a102a+9a+3a+2a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+3a+2a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+3a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+3a+2a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+3a+2a+5a10a115a105a120a32a97a110a100a32a102a+9a+3a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+3a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+3a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+3a+2a+5a10a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a104a117a-7a100a114a101ava ``` This is an improved version of Beta Decays program. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~127~~ ~~123~~ ~~120~~ 115 bytes ``` “¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁωª†ìdßàŒšdï¿dŸ¯een¥Šd“¤'…§:#©`…«¹¿œÖƒ#“‰ª„í¦ƒ†ì³ä“#ε…ÿ„Æ«¹NÈi„Š£ ì]«vyTG®Nè'€ƒ‚yª]„€µ°¡» ``` [Try it online!](https://tio.run/##LY@xasJgFIVfRcjgO/QF3JxchVaSwUWHQsHt10HcCrFUENGkjdHGWIVSUDoEzuF3EXyI@yLpf4PbvZzvnHtP//mp0w3KUswCMWcyyvErZi7mQ8ySezER8@uYExvamAcU9oQD1jYS84aCMacc8lXMEVmF@lwxUtZX2Fc6CHpq8PVCUheTYvPg4etRpx3OLnLK90voOf2e4@4ivYRVIH6YOMW7ua9SFiqO1dbkpOsWG@GzxryN3cug1cB3k9u666Dm@QBZ2yFVJRwR468s/wE "05AB1E – Try It Online") ``` “¡× (...) Šd“ # dictionary string "zero one two ... sixd sevend eighteen nined" ¤ # get the last letter ("d") without popping '…§ # dictionary string "teen" : # replace (changes all "d" to "teen" in the initial string) # # split on spaces © # save this list to the register ` # dump all items on the stack …«¹¿œÖƒ # dictionary string "twenty thirty fourty" # # split on spaces “‰ª„í¦ƒ†ì³ä“ # dictionary string "third three fourth four fifth" # # split on spaces ε ] # for each: …ÿ„Æ«¹ # append " times twenty" NÈi ] # if the iteration count is even: „Š£ ì # prepend "half " « # merge those two lists ([20, 30, 40] and [50, 60, 70, 80, 90]) v ] # for y in this list of names: y # put y on the stack TG ] # for N from 1 to 9: ®Nè # get the Nth element in the register '€ƒ‚ # append "and" yª # append y „€µ°¡ # dictionary string "one hundred" » # join the stack with newlines ``` [Answer] # JavaScript (ES6), 346 bytes Only a small idea to ETHproductions' solution: Replace `f(..)` with `a[..]` to be able to call `f` recursively to concat the output. ``` f=x=>(a="1one1two1three1four1five1six1seven1eight1nine1ten1eleven1twelve1thir11fif111eigh".split(1),x<1?"zero":f(x-1)+(x<13?a[x]:x<20?(a[x]||a[x-10])+"teen":x>99?"one hundred":(x%10?a[x%10]+" and ":"")+(x<50?"twen1thir1for".split(1)[x/10-2|0]+"ty":(x%20>9?"half "+"third1forth1fifth".split(1)[x/20-2.5|0]:a[x/20|0])+" times twenty")))+"\n" f(100) ``` Still far away from optimal... [Answer] # Python 2, ~~359~~ ~~349~~ 345 Bytes ``` a='one two three four five six seven eight nine'.split() c=['ten','eleven','twelve']+[i+'teen'for i in['thir',a[3],'fif',a[5],a[6],'eigh',a[8]]] p=' times twenty' h='half ' x=[p[7:],'thirty','forty',h+'third'+p,a[2]+p,h+'forth'+p,a[3]+p,h+'fifth'+p] f=['zero']+a+c for i in x:f+=[i];f+=[b+' and '+i for b in a] for i in f+['one hundred']:print i ``` ## Explanation: Create a list of the first 9 numbers. Create a list of the next 10 numbers. Create a list of the endings - `twenty`, `thirty`, `forty`, `half third times twenty` etc Join the first two lists with `zero` Append to the list each of the numbers from 50 onwards. Print out list Ungolfed code: ``` firstNumbers=['one','two','three','four','five','six','seven','eight','nine'] teenNumbers=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'] endings=['twenty','thirty','forty','half third times twenty','three times twenty','half forth times twenty','four times twenty','half fifth times twenty'] joined=['zero']+firstNumbers+teenNumbers for ending in endings: joined.append(ending) for number in firstNumbers: joined.append(number + 'and' + ending) joined.append('one hundred') for line in joined: print line ``` [Answer] # Java ~~8~~ 7, ~~512~~ 490 + 19(import) bytes Needs an import `import java.util.*;` ``` <T>void y(List<T>l,T...a){for(T t:a)l.add(t);}List x(){String b="teen",c="twenty",d="half ",e=" times "+c;String[]a={"zero","one","two","three","four","five","six","seven","eight","nine"},f={c,"thirty","fourty",d+"third"+e,a[3]+e,d+"fourth"+e,a[4]+e,d+"fifth"+e};List<String>g=new ArrayList<>(Arrays.asList(a));y(g,"ten","eleven","twelve","thir"+b,a[4]+b,"fif"+b,a[6]+b,a[7]+b,"eigh"+b,a[9]+b);for(String h:f){y(g,h);for(int i=1;i<=9;i++)y(g,(a[i]+" and "+h));}y(g,"one hundred");return g;} ``` **Ungolfed:** ``` <T> void y(List<T> l, T... a) { for (T t : a) { l.add(t); } } List x() { String b = "teen", c = "twenty", d = "half ", e = " times " + c; String[] a = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}, f = {c, "thirty", "fourty", d + "third" + e, a[3] + e, d + "fourth" + e, a[4] + e, d + "fifth" + e}; List<String> g = new ArrayList<>(Arrays.asList(a)); y(g, "ten", "eleven", "twelve", "thir" + b, a[4] + b, "fif" + b, a[6] + b, a[7] + b, "eigh" + b, a[9] + b); for (String h : f) { y(g, h); for (int i = 1; i <= 9; i++) { y(g, (a[i] + " and " + h)); } } y(g, "one hundred"); return g; } ``` To run this, simply call `<instance>.x();`. This now returns the list containing all numbers. [Try it here!](https://ideone.com/z3EJPU) [Answer] # Python 2, with num2words, 206 bytes Even with num2words it takes quite a few bytes! This is a full program. ``` from num2words import num2words as w for i in range(1,101):d=i/10;e=w(i).split('-');print' and '.join(e[1:]+[10>d>4 and((d%2 and'half '+{5:'third',7:'forth',9:'fifth'}[d]or w(d/2))+' times twenty')or e[0]]) ``` Here is a mocked version on [**ideone**](http://ideone.com/2jXL27) (By mocked I mean that since the online interpreter does not have `num2words` I replaced `w` with a `lambda` which looks up `num2word`'s output in a list) ungolfed and with 'fourth' rather than the allowed 'forth' (which saves a byte): ``` from num2words import num2words for i in range(1,101): d = i / 10 # i div 10 e = num2words(i).split('-') # i in English words with a "-" separator, split into parts if d > 4 and d < 10: if d % 2: p = 'half '+ {5:'third', 7:'fourth', 9:'fifth'}[d] + ' times twenty' else: p = num2words(d / 2) + ' times twenty' else: p = e[0] print' and '.join(e[1:]+[p]) ``` Note that the separator used by `num2words(100)` is a space, whereas for the other numbers it is a "-", so we don't need to do anything fancy for that case other than stop it from being "five times twenty". --- **Aside** If the challenge were to actually produce the numbers in Danish one could take the lang\_DK.py from the [github page](https://github.com/savoirfairelinux/num2words/blob/master/num2words/lang_DK.py) and use: ``` from num2words import* [num2words(i,lang='dk')for i in range(1,101)] ``` for 68 bytes, yielding: ``` ['et', 'to', 'tre', 'fire', 'fem', 'seks', 'syv', 'otte', 'ni', 'ti', 'elleve', 'tolv', 'tretten', 'fjorten', 'femten', 'seksten', 'sytten', 'atten', 'nitten', 'tyve', 'enogtyve', 'toogtyve', 'treogtyve', 'fireogtyve', 'femogtyve', 'seksogtyve', 'syvogtyve', 'otteogtyve', 'niogtyve', 'tredive', 'enogtredive', 'toogtredive', 'treogtredive', 'fireogtredive', 'femogtredive', 'seksogtredive', 'syvogtredive', 'otteogtredive', 'niogtredive', 'fyrre', 'enogfyrre', 'toogfyrre', 'treogfyrre', 'fireogfyrre', 'femogfyrre', 'seksogfyrre', 'syvogfyrre', 'otteogfyrre', 'niogfyrre', 'halvtreds', 'enoghalvtreds', 'tooghalvtreds', 'treoghalvtreds', 'fireoghalvtreds', 'femoghalvtreds', 'seksoghalvtreds', 'syvoghalvtreds', 'otteoghalvtreds', 'nioghalvtreds', 'treds', 'enogtreds', 'toogtreds', 'treogtreds', 'fireogtreds', 'femogtreds', 'seksogtreds', 'syvogtreds', 'otteogtreds', 'niogtreds', 'halvfjerds', 'enoghalvfjerds', 'tooghalvfjerds', 'treoghalvfjerds', 'fireoghalvfjerds', 'femoghalvfjerds', 'seksoghalvfjerds', 'syvoghalvfjerds', 'otteoghalvfjerds', 'nioghalvfjerds', 'firs', 'enogfirs', 'toogfirs', 'treogfirs', 'fireogfirs', 'femogfirs', 'seksogfirs', 'syvogfirs', 'otteogfirs', 'niogfirs', 'halvfems', 'enoghalvfems', 'tooghalvfems', 'treoghalvfems', 'fireoghalvfems', 'femoghalvfems', 'seksoghalvfems', 'syvoghalvfems', 'otteoghalvfems', 'nioghalvfems', 'ethundrede'] ``` [Answer] # PHP , 318 Bytes ``` for($i=~0;$i++<100;)echo([0=>zero,10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen,100=>"one hundred"][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":"")).","; ``` first pick with the Null coalescing operator ?? the exceptions. this version with 314 Bytes is without the , at the end ``` zero<?php for($i=0;$i++<100;)echo",".([10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":""));?>,one hundred ``` [Answer] # Bash (using `rev` and `sed`), ~~299~~ 276 bytes I'm using bash's curly braces-expansion. However the braces are expanded in the wrong order, so I print all the words in reverted order and then fix the order of the letters using `rev`. After that, I still need some adjustments using `sed`: ``` printf '%s\n' orez {,{neet,yt{newt,riht,rof},ytnewt\ semit\ {drihtX,eerht,htruofX,ruof,htfifX}}Y}{,eno,owt,eerht,ruof,evif,xis,neves,thgie,enin} derdnuh\ eno |rev |sed -r 's,^Yte,t,;s,^Y,,;12s,.*,eleven,;13s,o.*,elve,;1,20{s,reeY,ir,;s,veY,f,;s,(t|)Y,,};s,Y, and ,;s,X,half ,' ``` A bit less unreadable: ``` printf '%s\n' orez {,{neet,yt{newt,riht,rof},\ ytnewt\ semit\ {drihtX,eerht,htruofX,ruof,htfifX}}Y}\ {,eno,owt,eerht,ruof,evif,xis,neves,thgie,enin} \ derdnuh\ eno \ |rev \ |sed -r 's,^Yte,t,; s,^Y,,; 12s,.*,eleven,; 13s,o.*,elve,; 1,20{s,reeY,ir,;s,veY,f,;s,(t|)Y,,}; s,Y, and ,; s,X,half ,' ``` [Answer] # [ink](https://github.com/inkle/ink), ~~286~~ 273 bytes ``` zero -(c){ -c>9 and c<20: {ten|eleven|twelve|{thir|four|fif|six|seven|eigh|nine}teen} -c%10: {&one|two|three|four|five|six|seven|eight|nine}{c>9: and {t}} -1: ~temp t="{twenty|thirty|forty|{&half {third|fourth|fifth}|{three|four}} times twenty}" {t} } {c<99:->c}one hundred ``` [Try it online!](https://tio.run/##Vc/NDoIwDAfw@55iMZHogUS8QYR3MaO4RewM1M@tvjqWcTBe2qRbfv3X4Xma3jB4lW/MNqjcNKU@YqvNYb@rVCDACD3cpdED@jvEQNYNsfM3Ka6Lo3vGMb2DO9mIDoEJAFmodbGra1E@BJerpnoVxEB6xZmQ1vm5hswe@04nt00w2Zkmy/OyASANmTW5C4x6MXgl4WRJISEzjyDxfPz9FkCy/oejJV0wTVFW6UgRWLEK5lCWVd4YFkjbG7YDtNP0BQ "ink – Try It Online") * -13 bytes by removing a useless "five times twenty" case, special-casing zero to be able to simplify the mod check, and simplifying the teens (which now also include ten) Ink has sequences - they look like `{a|b|c}` and evaluate to a different value each time, until there's no next value at which point they stick with the last one. By combining and nesting these, we can get pretty advanced with very little in the way of actual conditionals. A sequence that begins with `{&` instead of just `{` is a cycle - those loop and that's how we count units and how we alternate between "half nth times twenty" and "n times twenty" for the tens. We keep track of the name for the tens in a variable `t` which we only update every tenth pass through the loop. On the passes where we update the variable, we print only the variable, on other passes we use cycles to print the unit followed by `and {t}`. With a handful exceptions - below ten we skip printing the tens (no `three and zero`) and the teens are irregular enough that they get a sequence all to themselves. `c` is a labelled gather. Gathers by themselves don't do anything, but they can be diverted to as a form of control flow, and they keep track of how many times they've been visited - we use this readcount to special-case the teens, to know when we need to update the tens variable, and to know when to stop looping, wrap everything up and print one hundred. I know I could save a byte by using "forth" instead of "fourth", but I'm choosing not to. ## Ungolfed ``` zero // Print "zero" - (c) { - c > 9 and c < 20: // The teens get a sequence of their own because they don't fit into the other numbers' pattern. {ten|eleven|twelve|{thir|four|fif|six|seven|eigh|nine}teen} - c % 10: // Otherwise, unless we're meant to print a multiple of ten // Print the unit - this is a cycle, so it loops when it's been run through nine times. {&one|two|three|four|five|six|seven|eight|nine} {c > 9:<> and {t}} // If we're past nine (and, since we didn't enter the "teens" section earlier, past nineteen), also print " and " and the contents of the variable t. - else: // Set the variable t to the multiple of ten we want. Note the cycle to alternate between "half nth" and "n" ~ temp t="{zero|ten|twenty|thirty|forty|{&half {third|fourth|fifth}|{three|four}} times twenty}" {t} // Print the contents of t } {c < 99: -> c} // If we've done all this fewer than a hundred times, we go back to the top. one hundred // Print "one hundred" // Out of content, end of program ``` ]
[Question] [ This is a Cops and Robbers challenge. This is the cop's thread. The [robber's thread is here](https://codegolf.stackexchange.com/q/188143/31716). As a cop, you must pick any sequence from the [OEIS](https://oeis.org/), and write a program **p** that prints the first integer from that sequence. You must also find some string **s**. If you insert **s** somewhere into **p**, this program must print the second integer from the sequence. If you insert **s + s** into the same location in **p**, this program must print the third integer from the sequence. **s + s + s** in the same location will print the fourth, and so on and so forth. Here's an example: > > # Python 3, sequence [A000027](https://oeis.org/A000027) > > > > ``` > print(1) > > ``` > > The hidden string is **two bytes**. > > > The string is `+1`, because the program `print(1+1)` will print the second integer in A000027, the program `print(1+1+1)` will print the third integer, etc. Cops must reveal the sequence, the original program **p**, and the length of the hidden string **s**. Robbers crack a submission by finding any string *up to* that length and the location to insert it to create the sequence. The string does not need to match the intended solution to be a valid crack, nor does the location it's inserted at. ## Rules * Your solution must work for any number in the sequence, or at least until a reasonable limit where it fails do to memory restrictions, integer/stack overflow, etc. * The winning robber is the user who cracks the most submissions, with the tiebreaker being who reached that number of cracks first. * The winning cop is the cop with the shortest string **s** that isn't cracked. Tiebreaker is the shortest **p**. If there are no uncracked submissions, the cop who had a solution uncracked for longest wins. * To be declared safe, your solution must stay uncracked for 1 week and then have the hidden string (and location to insert it) revealed. * **s** may not be nested, it must concatenated end to end. For example, if **s** was `10`, each iteration would go `10, 1010, 101010, 10101010...` rather than `10, 1100, 111000, 11110000...` * It is acceptable to start on the second term of the sequence rather than the first. * If your sequence has a finite number of terms, going past the last term is allowed to result in undefined behavior. * All cryptographic solutions (for example, checking the hash of the substring) are banned. * If **s** contains any non-ASCII characters, you must also specify the encoding being used. [Answer] # [MATL](https://github.com/lmendo/MATL), sequence [A005206](http://oeis.org/A005206). [Cracked](https://codegolf.stackexchange.com/questions/188143/robbers-the-hidden-oeis-substring/188407#188407) by [SamYonnou](https://codegolf.stackexchange.com/users/12324/samyonnou) ``` voOdoO ``` [Try it online!](https://tio.run/##y00syfn/vyzfPyXf//9/AA "MATL – Try It Online") The hidden string has **8 bytes**. [Answer] # [Python 2](https://docs.python.org/2/), sequence [A138147](https://oeis.org/A138147) ([cracked](https://codegolf.stackexchange.com/a/188212/20260)) ``` print 10 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwdDg/38A "Python 2 – Try It Online") The hidden string is **7 bytes**. The sequence goes: ``` 10, 1100, 111000, 11110000, 1111100000, ... ``` [Answer] ## [Keg](https://esolangs.org/wiki/Keg), sequence [A000045](https://oeis.org/A000045) ``` 0. ``` The hidden string is ≤*6 bytes*(in order to conform the updated cracking rules) [Answer] # [Cracked](https://codegolf.stackexchange.com/a/188156/56656) # ~~[Brain-Flak](https://github.com/Flakheads/BrainHack), sequence [A000290](http://oeis.org/A000290) (Square numbers)~~ ``` ((()))({}<>) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NDU1NTo7rWxk7z/38A "Brain-Flak (BrainHack) – Try It Online") The hidden string is **6 bytes**. ### Fun fact: I "discovered" this property while playing [this brain-flak based game](https://gitlab.com/e-neighborhood-watch/cal_final). The hidden string was a randomly generated item that I discovered was very useful. [Answer] # [Pyret](https://code.pyret.org/), sequence [A083420](https://oeis.org/A083420), [Cracked](https://codegolf.stackexchange.com/questions/188143/robbers-the-hidden-oeis-substring/188249#188249) ``` fold({(b,e):(2 * b) + 1},1,[list: ]) ``` The hidden string has **4 bytes** or fewer. [Answer] # Java 8+, sequence [A010686](https://oeis.org/A010686) ([cracked by xnor](https://codegolf.stackexchange.com/a/188268/84303)) Lambda function. ``` ()->System.out.println(1); ``` The hidden string is ≤ 5 bytes [Answer] # [V](https://github.com/DJMcMayhem/V), sequence [A000290](http://oeis.org/A000290). Cracked by [Cows quack](https://codegolf.stackexchange.com/a/188408/41805) ``` é*Ø. ``` [Try it online!](https://tio.run/##K/v///BKrcMz9P7/BwA "V – Try It Online") The hidden string is **5 bytes**. [Answer] ## [Python 3](https://www.python.org), sequence [A096582](https://oeis.org/A096582) This is really trivial, as I haven't tried Cops and Robbers challenges before. ``` print(100) ``` The hidden string is *3 bytes.* [Answer] # [Python 3](https://docs.python.org/3/), sequence [A014092](http://oeis.org/A014092) - ([cracked](https://codegolf.stackexchange.com/questions/188143/robbers-the-hidden-oeis-substring/188311#188311)) ``` from sympy import isprime, primerange from itertools import count r=1 print(r) ``` [Try it online!](https://tio.run/##Nco7CoAwDADQvafIqOAizh5GpGrAfEjjkNNHKTi95Wn4JbxkHiYELUgDkFTMAZsaUp2gYxuftfSFXs1F7vbPXR72Yutcvso@2Jj5Ag "Python 3 – Try It Online") The hidden sequence is **82 bytes**. My intended code (which doesn't rely on the Goldbach Conjecture) was: ``` i=(n for n in count(2)if all(not isprime(n-x) for x in primerange(1,n))) r=next(i) # ``` **Cracked** by [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob), who uses the [Goldbach Conjecture](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) to solve it in a [magical 42](https://hitchhikers.fandom.com/wiki/42) characters. Great job! [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), [A000042](http://oeis.org/A000042) - ([cracked](https://codegolf.stackexchange.com/a/188346/55934)) ``` 1 . ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf//Gyro/f8PAA "Forth (gforth) – Try It Online") The hidden sequence is **5 bytes**, and it can easily handle hundreds of terms. A one-byte solution that breaks due to integer overflow is also possible. In fact, I'd say it is embarrassingly trivial. While the challenge text, under some interpretations, might allow you to call that a crack, I urge you not to. [Answer] ## [Desktop Calculator](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), sequence [A006125](https://oeis.org/A006125) ``` 1n ``` The hidden string *≤ 12 bytes*. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), sequence [A000984](https://oeis.org/A000984) (central binomial coefficients) ``` (())({{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NTU6O6ura2ulbz/38A "Brain-Flak (BrainHack) – Try It Online") The hidden string has **36 bytes** or fewer. [Answer] # [Python 3](https://docs.python.org/3/), [A268575](http://oeis.org/A268575) ``` from itertools import product S,F,D=lambda*x:tuple(map(sum,zip(*x))),lambda f,s:(v for x in s for v in f(x)),lambda s:{(c-48>>4,c&15)for c in map(ord,s)} W=D("6@AQUVW") print(len(W)) ``` [Try it online!](https://tio.run/##Rcy7CsIwGEDhvU8ROsifEgexihRaFIq7iHauaYOB3EjSEhWfPRId3M7wcczD37Vax8isloj70XqthUNcGm09MlYPE/XZmRxJW4te3oa@CJWfjBhB9gbcJMmTGygCxpj8AGLEVTAjpi0KiCvkvjmnZBD@zlUvoMty1zQloYvVBidGE0trbQfi8Dvr6hby7f5wuly7HGfGcuVBjAo6jGP8AA "Python 3 – Try It Online") The hidden sequence is **102 bytes.** [Answer] # [AsciiDots](https://github.com/aaronduino/asciidots), 36 bytes, [A019523](http://oeis.org/A019523) ``` />1#*$_#\ *^-{+})./ |/\/\/\ \/\/\/\& ``` [Try it online!](https://tio.run/##SyxOzsxMyS8p/v9f385QWUslXjmGSytOt1q7VlNPn6tGPwYEuWIgtNr//wA "AsciiDots – Try It Online") The hidden string has **12 bytes**. [Answer] # [Haskell](https://www.haskell.org/), sequence [A083318](http://oeis.org/A083318) ([cracked](https://codegolf.stackexchange.com/a/188546/20260)) ``` f=length[2] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802JzUvvSQj2ij2f25iZp6CrUJBUWZeiYKKQtr/f8lpOYnpxf91kwsKAA "Haskell – Try It Online\"n/P802JzUvvSQj2jD2f25iZp6CrUJBUWZeiYKKQtr/f8lpOYnpxf91kwsKAA \"Haskell – Try It Online") The hidden string is **5 bytes**. The sequence goes: ``` 1, 3, 5, 9, 17, 33, 65, 129, 257, 513, ... ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), sequence [A000578](http://oeis.org/A000578) (Cube numbers) ``` ((())<>) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NDU9PGTvP/fwA "Brain-Flak (BrainHack) – Try It Online") The hidden string is **16 bytes** [Answer] # [Cracked](https://codegolf.stackexchange.com/a/188245/73884) # ~~[cQuents](https://github.com/stestoltz/cQuents), sequence [A003617](https://oeis.org/A003617)~~ ``` =1#2:pZ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/39ZQ2ciqIOr/fwA "cQuents – Try It Online") The hidden string is **1 byte**. [Answer] # [Unefunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), sequence [A000108](http://oeis.org/A000108) ``` 1.@ ``` [Try it online!](https://tio.run/##K81LTSvNS0/VtbTQLagEM///N9Rz@P8fAA "Unefunge-98 (PyFunge) – Try It Online") The hidden sequence is **19 bytes**. [Answer] # [MATL](https://github.com/lmendo/MATL), sequence [A000796](https://oeis.org/A000796). [Cracked](https://codegolf.stackexchange.com/questions/188143/robbers-the-hidden-oeis-substring/188314#188314) by [SamYonnou](https://codegolf.stackexchange.com/users/12324/samyonnou) ``` 'pi'td1_&:_1)Y$J) ``` [Try it online!](https://tio.run/##y00syfn/X70gU70kxTBezSreUDNSxUvz/38A "MATL – Try It Online") The hidden string has **3 bytes**. [Answer] # [Python 3](https://docs.python.org/3/), [A008574](https://oeis.org/A008574), [cracked by xnor](https://codegolf.stackexchange.com/a/188375/44718) ``` print(1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1Dz/38A "Python 3 – Try It Online") Insert 4 bytes to complete A008574. A008574: a(0)=1, thereafter a(n) = 4n. [Answer] # [Haskell](https://haskell.org), sequence [A014675](https://oeis.org/A014675), [cracked by nimi](https://codegolf.stackexchange.com/a/188353/73884) ``` main=print$uncurry(!!)([2],0) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0SlNC@5tKioUkNRUVMj2ihWx0Dz/38A) The hidden sequence is **35 bytes**. Here's my intended solution: > > > ``` > > main=print$uncurry(!!)$((l:n)->(l>>=flip take[2,1],n+1))([2],0) > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > ``` > > > > [Answer] # [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), sequence [A000312](https://oeis.org/A000312) ``` let m={1|->{0}}in hd reverse[x**x|x in set m(1)&x<card m(1)] ``` The hidden string has **33 bytes** or fewer [Answer] # Haskell, [A000045 (Fibonacci)](https://oeis.org/A000045) -- [Cracked](https://codegolf.stackexchange.com/a/188505/73884) ``` f = head [0, 1] ``` I've got a solution with a whopping 23 bytes. I don't expect this to be safe for long, but it was super fun to come up with. Solution: > > I thought Haskell would be a fun language to try this challenge with -- the natural thing is to do to end up adding a function call every time, but if the sequence can't be written recursively in terms of the last term only, you run into some trickiness with Haskell's strictness and function application. > > Khuldraeseth na'Barya found a super clever way to do this with an applicative functor. I did something much less brilliant, using where-hacking: > > > > `f = head [b,a+b]where[a,b]=[0,1] > ^^^^^^^^^^^^^^^^^^` > > (This is actually 18 bytes. My less-golfed 23 byte version, where I'd totally forgot about pattern matching, used `[last a,sum a]where a=` instead.) > > > [Answer] # [Java 8+](http://jdk.java.net/), 1044 bytes, sequence [A008008](https://oeis.org/A008008) (Safe) ``` class c{long[]u={1,4,11,21,35,52,74,102,136,172,212,257,306,354,400,445,488,529,563,587,595,592,584,575,558,530,482,421,354,292,232,164,85,0,-85,-164,-232,-292,-354,-421,-482,-530,-558,-575,-584,-592,-595,-587,-563,-529,-488,-445,-400,-354,-306,-257,-212,-172,-136,-102,-74,-52,-35,-21,-11,-4,-1},v={0,0,0,0,0,0,0,0,0,0,0,0,-1,0,-1,0,-1,0,0,0,0,0,0,0,-1,0,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,-1,0,0,0,0,0,0,0,-1,0,-1,0,-1,0,0,0,0,0,0,0,0,0,0,0,1},w={1,0,0,-1,5};long d=1,e=1;void f(long a,long b){long[]U=u,V=v,W,X;while(a-->0){U=g(U);w=h(v,w);}W=h(v,U);while(b-->0){V=g(V);v=h(v,v);}X=h(V,u);if(w[0]!=v[0]){int i,j,k=0;u=new long[i=(i=W.length)>(j=X.length)?i:j];for(;k<i;k++)u[k]=(k<i?W[k]:0)-(k<j?X[k]:0);d*=e++;}}long[]g(long[]y){int s=y.length,i=1;long[]Y=new long[s-1];for(;i<s;){Y[i-1]=y[i]*i++;}return Y;}long[]h(long[]x,long[]y){int q=x.length,r=y.length,i=0,j;long[]z=new long[q+r-1];for(;i<q;i++)if(x[i]!=0)for(j=0;j<r;)z[i+j]+=x[i]*y[j++];return z;}c(){f(3,0);System.out.println(u[0]/d);}public static void main(String[]args){new c();}} ``` [Try it online!](https://tio.run/##bVLbUqNAEP0VfGOk2@WaRMfRj7DMpSgeMCHJkEiUW4wU357tBlxjrUXNTN/mnNM9pHEdY7ranc/LfVwUxrLZH7JNGFWqccAHxwHXAS@AwIUxubYLjjcCZ@xSnFYwBs8eUYEPvm2D7wfgTyZUfQvByINgMobglm7fumT7EIzJDijvUe3EBb8D98GlvOsR9siHSQA2IO3IHnIYOY9ciHwD@SoyBjIYMioyPDIPMiEyM7IEZC3IopDVIcvsoVg4cgfIrSD3hNwccpc4ZriOlfMUZF46WqhVY8PvHzo/tv9Sl@vru4z9fut3wH/3WzjyYw3lQSv5BY2VciBRjqwPemWszS4WQ3e8iOGRn1UFU1XDDObyuNX7xIwRH2zRPKuN@SzkUW3NGo5CtrPO4lBX9tKXTalsKmTdJWsqm5M1hUpIvTaPoR1dqZp20eisNDSksFO2rFSWHI1OgFamVrObfZJtyq14MFM1/3Ie9V0ayfUhN@XuXsudZYkq3EXKJO9xRtadLZCc9HHeO3J1rRLLkm3b97Yx@/PUsxfqNECDpqn0ucW3lAKdgU7fF1I0i1BTRJ1CHV1rhs2TssozYyEH/O2A/wE/eN7VxxdPfklpQzqQfn6Tvlv5Be27JCJBk/sg0itlC46nNLH0PpfiM9RWGlmKk9enMLWsSA6aPmW7NEWzNj2gOTydijJ5vTlU5c1bTpL2mVnRI/xZ0fu8VS97vTSKMi7p6H6N11hn5lNJlaQtzjeFaFgfAdIoz@e/ "Java (JDK) – Try It Online") Can be solved using a hidden string of size **12**. Can definitely be golfed more, but there is no way this is actually winning. I just wanted to contribute out of respect for the number 8008. Note: before anyone complains that the sequence is hard-coded, I've tested this up to the first term that diverges from the hard-coding (13th term = 307) and it gets it correctly albeit slowly. This is also why it's using `long` instead of `int`, otherwise it overflows before that term. **Update (Jul 12 2019)**: updated to be a bit more performant. Computes the 13th term in 30 seconds on my computer now instead of 5 minutes. **Update (Jul 17 2019)**: fixed bugs in for loop bounds for the `g` function, and array length bounds in the bottom of the `f` function. These bugs should have eventually caused problems, but not early enough to get caught by just checking the output. In either case, since the presence of these bugs 5 days into the game might have confused some people enough into being unable to solve this puzzle, I am totally fine with extending the "safe" deadline until July 24th for this submission. **Update (Jul 18 2019)**: After some testing I have confirmed that overflows start after the 4th term in the sequence and start affecting the validity of the output after the 19th term. Also in the program as it is written here, each consecutive term takes roughly 5 times longer than the previous to compute. The 15th term takes about 14 minutes on my computer. So actually computing the 19th term using the program as written would take over 6 days. Also, here is the code with sane spacing/indentation so it is a bit easier to read if people don't have an IDE with auto-formatting on hand. ``` class c { long[] u = {1, 4, 11, 21, 35, 52, 74, 102, 136, 172, 212, 257, 306, 354, 400, 445, 488, 529, 563, 587, 595, 592, 584, 575, 558, 530, 482, 421, 354, 292, 232, 164, 85, 0, -85, -164, -232, -292, -354, -421, -482, -530, -558, -575, -584, -592, -595, -587, -563, -529, -488, -445, -400, -354, -306, -257, -212, -172, -136, -102, -74, -52, -35, -21, -11, -4, -1}, v = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, w = {1, 0, 0, -1, 5}; long d = 1, e = 1; void f(long a, long b) { long[] U = u, V = v, W, X; while (a-- > 0) { U = g(U); w = h(v, w); } W = h(v, U); while (b-- > 0) { V = g(V); v = h(v, v); } X = h(V, u); if (w[0] != v[0]) { int i, j, k = 0; u = new long[i = (i = W.length) > (j = X.length) ? i : j]; for (; k < i; k++) u[k] = (k < i ? W[k] : 0) - (k < j ? X[k] : 0); d *= e++; } } long[] g(long[] y) { int s = y.length, i = 1; long[] Y = new long[s - 1]; for (; i < s;) { Y[i - 1] = y[i] * i++; } return Y; } long[] h(long[] x, long[] y) { int q = x.length, r = y.length, i = 0, j; long[] z = new long[q + r - 1]; for (; i < q; i++) if (x[i] != 0) for (j = 0; j < r;) z[i + j] += x[i] * y[j++]; return z; } c() { f(3, 0); System.out.println(u[0] / d); } public static void main(String[] args) { new c(); } } ``` # Solution > > `f(1,v[0]=1);` right before the `System.out.println` > > The program works by computing the n'th Taylor expansion coefficient at 0. Where the original function is a quotient of polynomials, represented by `u` and `v` which I got from [here](https://oeis.org/A008000/a008000_1.pdf), except that in the linked document the denominator is not multiplied out, and nowhere do they say that you have to compute the Taylor series, I stumbled on that by accident and then confirmed via another source. > > The calculation is done via repeated application of the quotient rule for derivatives. > > The incorrect first term of `v`, the entire array `w` and a few other things like the function `f` having any arguments are thrown in to mess with people. > > > [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ([Brachylog SBCS](https://github.com/JCumin/Brachylog/wiki/Code-page)), [A114018](https://oeis.org/A114018) ([Cracked](https://codegolf.stackexchange.com/a/188485/85334)) ``` ≜ṗ↔ṗb&w ``` [Crack it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnnIc7pz9qmwIkk9TK//8HAA "Brachylog – Try It Online") The string has 2 or fewer bytes. > > Fatalize's solution, `ẹb`, is the original string which I had intended. Note that `ẹk` also works, for the same reasons. In addition to the issue with `9001` beheading to `001`=`1`, it actually turns out that `b` on a number just won't fail, because all single digit numbers behead to `0`, including `0` itself. > > > [Answer] # C# (.NET Core), A003678, 29727 bytes (Safe) ``` using System;using System.Linq;using System.CodeDom.Compiler;class P{static void Main(){Int32 z=0;\u0049nt32 T(\u0049nt32 i){i--;var \u0064="";for(;i>0;\u0069/=5)d=i%5+d;return d.Aggre\u0067a\u0074e(0,(a,b)=>a*5+b%48*2%5)+1;}System.D\u0069agn\u006fs\u0074ics.Pro\u0063ess.\u0053tart(CodeDo\u006dProvi\u0064er.\u0043reateP\u0072ovider("CSharp").Co\u006dpi\u006ceAssembly\u0046romSource(new Com\u0070ile\u0072P\u0061ra\u006det\u0065rs(new[]{"System.dll"}){GenerateExecutable=true,\u0047enerateI\u006e\u004de\u006dor\u0079=false,Out\u0070utAs\u0073\u0065m\u0062\u006cy="One.exe"},Stri\u006eg.Con\u0063at(@"5FKX4&4A@6W]4V0).7K]073W:J7`1G?V4H;T1*'V.VD).7K]073W:J7`1G?V4H;T1*'V.VD)8F'[4FOX3V/_.:0&?FK]:I?_2FL*?G?X?X\+1&8T:IDU0746;&\+?FTA3XL&3XL=B'L:8T\V*W3V5X[TB'L:8T[Y?6/T1*T-8X?A?6P_5H@:*ET&/ZT-8X?>)W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/VS]7W3V5ZH]2H`X26L*/W<9?70&:V`C2F'[4FOX3V/_=6P*06D'1D`'5G0&<&'[B'L:8TT;/U']B'L:8TS=/W<S3VX_5H@:*4[X3V0IB'L:8T\=4F/B:X`G,&0'B'L:8T[>2*,*/ZT-8X?@)WGV?ZT-8X??)W@U?'/V*W?_5F0G,*T-8X?A)W3V2*T-8X?A9G@_5H@:*DOH4)CV4FC_24_Y?G/]/Y3HB'L:8T[V?ZT-8X?A?WLT/U_V?'KW,73Y1&T)?G?X1'3B0J,&1F0G=*T-8X?A9JT-8X?A.'3TB'L:8T\V?JT-8X??)FKB4'L&3Y4L5G@_5H@:*(@_5H@:*$P*B'L:8TX=B'L:8TS=1F0)?'0_5H@:*%SB:ZD.1(;V560B2UXX26L*/W<9.V8U0'3[1G?X?VL9B'L:8TP:2&D_5H@:*DKV1JT-8X??)H<X4Z,_5H@:*(D*7ZT-8X?@)JT-8X?A0J(_5H@:*DP_5H@:*4W[4I@_5H@:*(D_5H@:*F<+0:(_5H@:*DP_5H@:*(D9/6SV?G?VB'L:8TP:2&D_5H@:*$\_5H@:*ET_5H@:*DWV2(0B/:7Z?FS^:Y$9/6D)1V8&/U(_5H@:*$K]/W<S3ZT-8X??.*T-8X?@*FS[4E_[4H0&9HL&9G0&<'0=3W0=9JT-8X?A?Y$9<Z,*0ZD_5H@:*F;D1FL_5H@:*DP)?'/`;%Wb2XH<".Se\u006c\u0065ctMany(n=>Convert.T\u006fString(n-35,2).PadL\u0065\u0066t(6,'0')).G\u0072\u006fupBy(n=>z++/8).S\u0065lect(\u006f=>(\u0043har)\u0054(Co\u006ever\u0074.To\u0049nt32(\u0053\u0074\u0072\u0069ng.C\u006f\u006ec\u0061\u0074(o),2))))).\u0050athT\u006f\u0041ssembly);}} ``` The hidden sequence is 4 bytes or less. > > The way the program works is by decoding the long string into a program. The decoded program is then compiled into an executable, which is then run. The executable then creates another program, this time using the CodeDom instead of a long string. Finally, the last program outputs the result. > The hidden string is `;8;L`, where you insert at index 18504 in the super long string. > > > > > > [Answer] # [1+](https://esolangs.org/wiki/1%2B), sequence [A000079](http://oeis.org/A000079) ``` 1: ``` Trivial. The hidden string is 2 bytes. How to multiply by 2 when pushing 2 is three bytes (`11+`)? [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 28 bytes, [A011557](https://oeis.org/A011557), safe ``` + 1. ?- +X,X<2,write(X),X>2. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/X1vBUI/LXldBO0InwsZIp7wosyRVI0JTJ8LOSO//fwA "Prolog (SWI) – Try It Online") (I'm not really sure what counts as a full program for Prolog, but this works as a program on TIO.) The hidden string is 5 bytes or less. I'm a bit surprised this survived a week... The hidden string is > > > ``` > > > + 0. > ``` > > , inserted after `+ 1.` (note the leading newline). [Try it online](https://tio.run/##KyjKz8lP1y0uz/z/X1vBUI9LW8EAStjrKmhH6ETYGOmUF2WWpGpEaOpE2Bnp/f8PAA "Prolog (SWI) – Try It Online"). Instead of numerically generating a power of ten, this prints one out digit by digit: when backtracking is triggered by the failure of `X>2`, the only choice point is `+X`, which goes through every clause of `+/1` until execution succeeds or it runs out, executing `write(X)` (which immediately and imperatively prints without a trailing newline to standard output, so the output can't be undone by backtracking) for every resulting value of X. `X<2` is just there to prevent the 1-byte solution `0`. > > > [Answer] # [1+](https://esolangs.org/wiki/1%2B), sequence [A058891](https://oeis.org/A058891) ``` 1: ``` Hopefully better, although still pretty much straight forward. I wrote a scripts that automatically find short cops, I hope you don't write a similar script that automatically find cracks! The hidden string is 4 bytes. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 13 bytes, sequence [A010888](https://oeis.org/A010888), [cracked (17 bytes)](https://codegolf.stackexchange.com/a/235788/78410). I think this is an easy problem. ``` x= echo ${#x} ``` I've hidden an 18 bytes of string. [Try it online!](https://tio.run/##S0oszvj/v8KWKzU5I19BpVq5ovb/fwA "Bash – Try It Online") ## Intended solution Insert the following string between first and second lines: ``` x=x${x#xxxxxxxxx} ``` ]
[Question] [ [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet) is a spelling alphabet that associate to each of the 26 letters of the English alphabet one word (table below) that is easy to understand over the radio or telephone. For example, if you want to communicate the word `CAT` over the telephone, you do the following spelling: `CHARLIE ALFA TANGO` But what if you are unsure if the spelling was understood correctly? Well, you do the spelling of the spelling: `CHARLIE HOTEL ALFA ROMEO LIMA INDIA ECHO ALFA LIMA FOXTROT ALFA TANGO ALFA NOVEMBER GOLF OSCAR` But now you are worry that the spelling of the spelling was not understood correctly, so you cannot help yourself but doing the spelling of the spelling of the spelling: `CHARLIE HOTEL ALFA ROMEO LIMA INDIA ECHO HOTEL OSCAR TANGO ECHO LIMA ALFA LIMA FOXTROT ALFA ROMEO OSCAR MIKE ECHO OSCAR LIMA INDIA MIKE ALFA INDIA NOVEMBER DELTA INDIA ALFA ECHO CHARLIE HOTEL OSCAR ALFA LIMA FOXTROT ALFA LIMA INDIA MIKE ALFA FOXTROT OSCAR XRAY TANGO ROMEO OSCAR TANGO ALFA LIMA FOXTROT ALFA TANGO ALFA NOVEMBER GOLF OSCAR ALFA LIMA FOXTROT ALFA NOVEMBER OSCAR VICTOR ECHO MIKE BRAVO ECHO ROMEO GOLF OSCAR LIMA FOXTROT OSCAR SIERRA CHARLIE ALFA ROMEO` **Challenge:** Write a function that takes as input a word and returns as output the number of letters of the 100th iteration of NATO spelling. Examples: ``` MOUSE -> 11668858751132191916987463577721689732389027026909488644164954259977441 CAT -> 6687458044694950536360209564249657173012108297161498990598780221215929 DOG -> 5743990806374053537155626521337271734138853592111922508028602345135998 ``` **Notes:** * Whitespaces do not count. Only letters do. * Both uppercase and lowercase letters are fine (including combinations of uppercase and lowercase). * If you want to use a programming language without support for large integers, returning the result modulo `2^32` is fine too. * The result must be an exact integer, not an approximation (like floating point). * The first iteration of `CAT` is `CHARLIE ALFA TANGO` (`CAT` is the 0th iteration). # Big Note: If your program stores the spelling string, there's no way it is not going to run out of memory: the 100th iteration of `MOUSE` requires more than `10^70` bytes; the whole data on the Internet is estimated to be below `10^30` bytes. **NATO spelling Table:** ``` A -> ALFA B -> BRAVO C -> CHARLIE D -> DELTA E -> ECHO F -> FOXTROT G -> GOLF H -> HOTEL I -> INDIA J -> JULIETT K -> KILO L -> LIMA M -> MIKE N -> NOVEMBER O -> OSCAR P -> PAPA Q -> QUEBEC R -> ROMEO S -> SIERRA T -> TANGO U -> UNIFORM V -> VICTOR W -> WHISKEY X -> XRAY Y -> YANKEE Z -> ZULU ``` [Answer] ## [SageMath](https://www.sagemath.org/), ~~260~~ ~~255~~ ~~253~~ ~~247~~ ~~246~~ ~~241~~ ~~236~~ ~~234~~ ~~233~~ 231 bytes ``` m=map f=lambda w:sum(vector(m(w.count,m(chr,(65..90))))*(matrix(26,m([sum(ZZ([*m(ord,'v8^x$ 2??&:#Jd;2Nv&=4-wB/yY$4I"o^_bufTTZ fn"U(J1W:ZRYG=/p,ZTRn[RHJA$jbGn-ul2zeVJ')],92).digits(27)[:i])for i in(0..111)].count,(0..675)))+1)^100) ``` This constructs the transition matrix ``` [2 1 1 1 0 0 0 0 1 0 0 1 0 0 1 2 0 0 1 1 0 0 0 1 1 0] [0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0] [0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0] [0 0 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 0 1 1 1 0 0 1 0 1 0 0 1 2 0 0 2 1 1 0 0 0 1 0 2 0] [1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0] [0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] [0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0] [0 0 1 0 0 0 0 0 2 1 1 1 1 0 0 0 0 0 1 0 1 1 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 0 0 0] [0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0] [1 0 1 1 0 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1] [0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 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 0 0 0 0 1 1 0 0 0 1 0] [0 1 0 0 1 2 1 1 0 0 1 0 0 1 1 0 0 2 0 1 1 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] [0 1 1 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 2 0 1 1 0 1 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0] [0 0 0 1 0 2 0 1 0 2 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 2] [0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0] [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1] ``` and raises it to the 100th power, then multiplies the matrix by the column vector representing the letter-frequencies of the input word, and finally computes the 1-norm. It’s not the shortest entry, but it is fairly efficient: it takes about 4 ms to compute `f("MOUSE")` on my computer: ``` sage: %time f("MOUSE") CPU times: user 4.11 ms, sys: 25 µs, total: 4.13 ms Wall time: 4.14 ms 11668858751132191916987463577721689732389027026909488644164954259977441 ``` This can almost certainly be shortened further. I bet there’s a more concise way to represent the matrix. (*See the third and fifth edits below…*) --- **edit** (255): It’s shorter to use `sum(v)` than `v.norm(1)` to compute the 1-norm of a vector. **edit** (253): We can pass a generator object to the `vector()` constructor, rather than a list, saving a `[]` pair. **edit** (247): Use a more efficient string representation of the data, grouping the codewords into threes and representing each of the three with a different section of the ascii range: so the three words in a group are represented by characters from the ranges 33–58, 59–84, and 85–110 respectively. **edit** (246): Changing the start of the ascii range we’re using from 33 to 39 means that none of the characters in the string need to be escaped, which saves one character since previously there was an escaped backslash `\\`. This has the pleasing side-effect that one codeword in three is now in plain text. **edit** (241): Represent the matrix with a string in a completely different way: using a base-95 encoding of the lengths of the gaps between consecutive 1's, when the matrix is read by columns. In order to make the column-first order work without extra code, I’ve transposed everything, so now it’s multiplying a *row* vector by the 100th power of the *transposed* transition matrix. The encoded list of numbers is: ``` [5, 6, 15, 14, 3, 4, 5, 4, 3, 1, 3, 6, 9, 4, 7, 8, 9, 5, 7, 26, 0, 3, 2, 0, 4, 8, 6, 3, 16, 7, 3, 5, 7, 3, 5, 5, 17, 4, 3, 8, 0, 1, 14, 3, 3, 12, 8, 4, 18, 4, 2, 17, 3, 0, 8, 2, 3, 4, 5, 2, 15, 1, 8, 0, 15, 12, 1, 2, 0, 16, 10, 8, 2, 0, 12, 4, 4, 9, 0, 9, 6, 7, 1, 17, 3, 4, 1, 1, 3, 11, 6, 6, 3, 2, 11, 3, 1, 2, 8, 6, 2, 17, 7, 2, 4, 0, 6, 3, 24, 9, 0] ``` This list is treated as a sequence of digits in base 27, for encoding purposes. Where there is a `2` in the (transition matrix minus the identity), we represent that by a `0` in this list. After all, what is a two but a pair of ones at zero distance from each other? Sadly this version is a few milliseconds slower – but we are playing golf, after all, not racing. **edit** (236): Use a slightly different base-95 encoding that allows for a terser decoder, taking advantage of the fact that the integer constructor `ZZ(digits, base)` doesn’t mind if some of the digits are ≥ base. So we use digits in the printable range (32–126), even though the base is 95. The final (most significant) digit is 5, which therefore cannot be subject to this treatment, so we add it separately. One could save an additional character by inserting a literal `^E` character at the end of the string and removing the `,5` following it, but surely one must maintain *some* decorum. **edit** (234): It turns out that using base 92, rather than 95, means the encoded string consists entirely of printable ascii characters that do not need to be escaped. **edit** (233): `map(w.count,map(chr,(65..90)))` is one character shorter than `w.count(chr(c))for c in(65..90)`. **edit** (231): Now we’re using the `map` function four times, it’s worth abbreviating. [Answer] # [Julia 1.0](http://julialang.org/), ~~223~~ ~~218~~ 214 bytes actually finishes by storing already computed values in a dictionnary function name is `>`, for example `>("MOUSE")` ``` t=Dict() >(s,n=99)=sum(x->big(get!(()->n<0||split("LFA RAVO HARLIE ELTA CHO OXTROT OLF OTEL NDIA ULIETT ILO IMA IKE OVEMBER SCAR APA UEBEC OMEO IERRA ANGO NIFORM ICTOR HISKEY RAY ANKEE ULU")[x-'@']x>n-1,t,x=>n)),s) ``` [Try it online!](https://tio.run/##LZDdatswGIbPfRXfTCESOKD/nzF7UxOlMXGi4ThlpevBfrLikLmldiEHvYyxo15dbyRTukoHH9L36Hkl7R737Td6OB6HfNr@GBBOCtRnXW4tzvvH3@gwLr63t@h2O7xDCI@L7gN5eurv9@2A0mrmoHaXAeaurkoPvmocTOYBwpemDg2Eagah8RWspqWDTUSaBsoqQLl0UC48hEu/PPc1rCeuBvc5Mv7cTyAsfWR8XTtwq4sAq3IW6iWUkybUMC/XC38Vc69ic@F99G5SfH0Yjz6Nbg5FN6bZkB3yosM46/ExGbb90EMO1wnEkS7DZu1TyAugVCljpNGSUs6ojVNZo4XiUmvNqDJWc8aNJUwTpiyxwhglBFXCSsGktVrHVfbfO3FNGmv0RqsW0hAhlI0kkVxxRRixUgkmrJKaak4oo8Qwq6miwhpriYzZhjAWG9Iy@6adhos3rdSCR8wQxbWIUsk1lVIxJRnlXLOTVVAeX8TjeUqpZUxGnJkYzoWkcdua5CZJft09AGqzHYa2g9fvec26f2i7Yd@hHeQ5FKjF8BFGL89/RvD@VP@OMkjhrP06nG4DZ@iE4BQn2@4nJMfjPw "Julia 1.0 – Try It Online") Ungolfed version: ``` dict = Dict() function f(str, n=100) c = big(0) for x in str # if (x,n) is not in dict, execute the function below (in do...end) and store the result in dict c += get!(dict, (x,n)) do if n < 1 true else words = split("LFA RAVO HARLIE ELTA CHO OXTROT OLF OTEL NDIA ULIETT ILO IMA IKE OVEMBER SCAR APA UEBEC OMEO IERRA ANGO NIFORM ICTOR HISKEY RAY ANKEE ULU") word = x * words[x - ('A'-1)] f(word, n-1) end end end return c end ``` [Try it online!](https://tio.run/##bZPNTttAEMfvfoppihS7Dcj7vVs1rUxYwCJhK2NQEeUAiUMdRTZyHJEHqXrq0/VF0tmERqJ0fBjvzM//mZ31zpbz8o6s1utgUo5b6MMRujAKgumyGrdlXcE0XLRND6o@ieMoALQxYvflQ/i8nNYNrKCsALlgE/H2FsophKteFUG5gKpuPeFr9KBYFeNlW0D7vYBdmftiXj9B6KH64OCgqCYR3FUTFK2bLdoUi@V8J7MrNIb3fXgo2jfhVn1TM0KVHeENm6ngI5AXQW9tsyxeBIv5onhFPdXNZIHbXjzOyzbsDI8TyJIrB6dJNkwt2GGewODUgfuaZy4HNzwGl9thcH6UJnCJSJ5DOnSQjhJIzyy4Kzs6tBlcDJIMki/I2EM7ADeyyNgsSyA5P3Fwnh67bBSkg9xlcJpenNlrrHuNyTNrUfeyE/23Vex0Be@2Xd@sYB/CbtLdJ9HtK3oaegiPF7Mvx1BNgn/f//qmaJdNBePAB9ZBWyxaP5ybTbIzcpcXtgP9T0CIlFoLrQQhjBKDjzRaccmEUooSqY1ilGkTUxVTaWLDtZacE8mN4FQYoxSuelvdQZJ30KMuqioudMy5NEjGgkkmYxobITnlRgpFFIsJJbGmRhFJuNHGxAJr65hSTAhDzbPskTt5lhWKM8R0LJniKCqYIkJIKgUljCnqVTlhuCOG3xNCDKUCcaqxOOOCYNjo4BYvD16JsOzNIv@3bsazqfXYlFU7r8IZ9Ps4@TKCz9D9/etHFz54/7Pbgw7sld9a3w3shR6J8IhxzBCs138A "Julia 1.0 – Try It Online") ## Shorter but non-finishing version: # [Julia 1.0](http://julialang.org/), 188 bytes same approach but no storing of already computed results ``` >(s,n=99)=sum(x->big(n<0||split("LFA RAVO HARLIE ELTA CHO OXTROT OLF OTEL NDIA ULIETT ILO IMA IKE OVEMBER SCAR APA UEBEC OMEO IERRA ANGO NIFORM ICTOR HISKEY RAY ANKEE ULU")[x-'@']x>n-1),s) ``` [Try it online!](https://tio.run/##LZBNbtswEIX3OsVACGAJsAH@kxNUbhmHjgXLZiDLQYM0izZNCxmuGkQO4EWOUXTV0/Ui7tgNuRiS7/F75Gxetu1nvj8cxlk/7ArEvOhffmT70fhL@z3r3rHX1/5p2@6ytJp6qP1NhJmvqzJAqBoPk1mE@LGpYwOxmkJsQgXLy9LDmixNA2UVoVx4KOcB4k1YXIQaVhNfg78mT7gIE4iLQJ5Q1x788irCspzGegHlpIk1zMrVPNxS7i2J8xCIu07zu/1o8GFwvx93I54P@/yQ7B77XQ8F3CVAI13E9SqkUIyBc2Oc085qzqXgSNOgs8pIba0V3Di0UkiHTFgmDDJUzhmluFGoldCI1tJu@J878U1KlbhEtUo7ppRBcjItjTRMMNRGCYVGW24l44IzJ9BywxU6RKYp2zEhSNAo8A17Ga/esNoqSTbHjLSKoFparrURRgsupRVHquKSfiTpPucchdBkF47CpdKcjtEl90ny7eczZO1wk0Pbwak9p6wHalI7tqf103Pb7bZdtoGiIOE9DP7@@TWA82P9PRhCCmftp93xWXD2kObJY/cVksPhHw "Julia 1.0 – Try It Online") (depth 8 so that it can finish) [Answer] # [R](https://www.r-project.org/), ~~260~~ ~~259~~ ~~236~~ ~~235~~ 232 bytes *Edit: -3 bytes thanks to Robin Ryder, and -23 bytes using a version of [Arnauld's trick](https://codegolf.stackexchange.com/a/215441/95126) of dropping the first letter of each word* ``` a=scan(,'') lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu v=!!1:26 f=function(w)sum(v[utf8ToInt(w)-96])%%2^32 for(i in 0:99)v=v+sapply(a,f) ``` [Try it online!](https://tio.run/##JY3BasMwEETv@oqNIUSiKbQphDjgD@i9t9LCRlnFwpLWyCu1/npX0Nsw83iTtw2HxWLSx8PBqOAQMlaGEXPwBBQEwY4M/CuZBTg4YKEA6e4RSkNEwAcGHxH8RMCV4o0yNGUGnBtDN7LAkRpDOSNgejAk7zhH8FY4w@iXidb2u7ZxImreolQddrvX6@ms3OBKsuI56R@zlKjrZxF3@eD3JK157s9fZr8/fb@dVJNqDz7By7XvTR3q04LzHFaNR2c2pzuL0hnVQuSy0H@886Mz2x8 "R – Try It Online") Function `f` that returns output modulo `2^32` (as allowed by rules) to stay within range of integer accuracy in [R](https://www.r-project.org/). ``` a=scan(,'') # fill vector a with alfa bravo charlie... # NATO phonetic alphabet # (need a newline to stop filling vector) v=rep(1,26) # initialize vector v of values with 1s f=function(w) # f = function to calculate value of a word sum(v[ # sum of elements of v at indices given by utf8ToInt(w)-96]) # utf8 values of letters, minus 96, %%2^32 # modulo 2^32 for(i in 1:100) # now perform 100 iterations of v= # updating v with sapply(a,f) # the value of each word in a, # calculated with the current v ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~133~~ 130 bytes ``` F¹⁰⁰≔E⪪”$±DuaB``IY″²÷⸿↓⪪∧⮌9Pπx¦⸿S1lJ|#←¹Fι´³As¦L₂≕⬤m⍘M▶⭆dω{ⅈ⊟C0cO\⟦;⊟⁼`→<¬UPνρL⊖¦N↷jOh⧴0r↨J9α➙n\²`⟧JξUL≕φ5u”¶ΣEκ∨¬ι§θ⌕αμθIΣES§θ⌕αι ``` [Try it online!](https://tio.run/##bY@xbsIwEIb3PoWVyZFSic5MJlyIGzumtkOh8hJBS6OGA4Kp@vbpiYqtHmzd99//Sd5@tsP22Pbj@HEcGH@aTFImLpduj1y3J@5OfRd5IlQhAs6sWJmAeSmskhBwDsoThrwkWpi1t8YHXBhVBCyNBxVQ1nNJK88NFTyFlVS0q6QmqGVFktqsQM/ABjQuF/QsxZLClwZmkAe0RgM1nARrCXtRL2hsalkYqwOuZO4NlV5L6SrYBFxbQfdG1BWQ/K1RTZKxJGCSZsxdD7dPfWXMDLw@Rt4RFVHi7v2HnzNWdLjjbcYO6e1k7JxOH5ZDh5Hn7SXyu0Di6RpdpGDP/zd0f4bpOGrTOBgfv/tf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F¹⁰⁰ ``` Loop 100 times. ``` ≔E⪪”...”¶ΣEκ∨¬ι§θ⌕αμθ ``` Calculate the cost of each letter in each word of the NATO phonetic alphabet using `1` on the first pass and the previous cost for that letter on subsequent passes. ``` IΣES§θ⌕αι ``` Print the total cost of all the letters in the input word. [Answer] # [Perl 5](https://www.perl.org/), ~~279~~ 222 bytes ``` sub f{my($c,$_,$n)=(0,@_,100);$c+=$d{$_,$n}//=$n<1||f($_.(LFA,RAVO,HARLIE,ELTA,CHO,OXTROT,OLF,OTEL,NDIA,ULIETT,ILO,IMA,IKE,OVEMBER,SCAR,APA,UEBEC,OMEO,IERRA,ANGO,NIFORM,ICTOR,HISKEY,RAY,ANKEE,ULU)[-65+ord],$n-1)for/./g;$c} ``` [Try it online!](https://tio.run/##XVJra@JAFP2eXxFKoIZe67wfdVNM7ViDsbPEWLZIEVqtCFsVtcsW6293b7KFhZ35MNxzzpxz57GZb3/K5ssGl9P7bh6W893@6mq43s7bQVU/LxfL1b4dvH2EnT1ySSOcDP145MLkOjynVCljpNGSUs6oxams0UJxqbVmVBmrOePGEqYJU5ZYYYwSgiphpWDSWq2xOn@CIPw3Jt20xKUKQHstpCFCKItbiOSKK8KIlUowYZXUVHNCGSWGWU0VFdZYSyQ2YQhjSEjL7P/@t/7uy19qwVFviOJaoLvkmkqpmJKMcq5ZZS8oxzNyNKKUWsYkypnBLriQFGFrzp/CuB28rreN@o7iQ5329tGIlqsNRPPfmzjpRNP2FxxGi/U@ea3Z@C@43DUqsNbCWUWEzeZ1LQx/7cIKPkPpMZitV/NpFbJcLdqn3ftz@Hqogl4gmkK0ipMGgc4UKCFxO3q5SKLZoSaOrVYSrb7Rz0/MnV428l4KRfrgoZ8WeebA5WUK3b4H/6MsfAk@74EvXQ73t1kKY5SUJWS5h2yYQjZw4B/c8MYVMOqmBaTfUeNuXBf80KHGFUUK6f2dh/us54shZN3SF9DPRgP3iLmPSA6cQ99xPGkqebHezp6wyyaN8RZbl60FNn88neqfFuB3CPDJ/gA "Perl 5 (cperl) – Try It Online") ...which is a translation of the Julia answer from @MarcMush My own approach was 279 bytes: [Try it online!](https://tio.run/##HZDBboJAEIbvPoWHpbZlhPbQgxIOI466cXGbdTHVi7HGKgkiEWxiyL566eL1n@@f@TLF4Zp9NI1zCs@7omZbeDe@5x@Dn8v1WUwQFK4kzFAJTkBCI0QzCfJLK6lBiglITQIWY46QWERr4EICjxH4nECuKB6RgmWECvDTMjSiCGRMliGlEHAxlbDgE6li4JGWCmZ8Oae1vbu2wzmR3Zu81Oe7sw/Y3goa17VuLPP9EOGhysqaZa5rwtrZG9OKv3neYPAo5YFFgOU1ezJuyE4165nXttAzbWThLqLnbTaB/YCTG7YNy9u5@7vLbofSOTVNLJMldSLUnbGc/l2KKr3kZdOPRVpWw2FSpVlbsMF3ekzzqukX2T8 "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~257 248~~ 244 bytes The case of the input string doesn't matter. Returns a BigInt. ``` f=(s,C=(n=100,A="XLfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu".match(/.[a-z]*/g)).map(_=>1n),g=s=>Buffer(s).reduce((t,c)=>t+C[c&31],0n))=>n--?f(s,A.map((w,i)=>C[i]+g(w))):g(s) ``` [Try it online!](https://tio.run/##bc9RS8MwFAXgd39GHyRxbbfim5BJrcMVdIHNgjCG3GU3XVyalDTtnH@@Cz6Kj@c7cOB8wQCdcKr1ibEHHEfJSBcXjBiWzWZxzqKPVwlrGOwSnFa40B6Ko@Xf3lnPteQe9eqgoAqd96W2ZQPlCfmAzR7dRoDLW6hwj4I3aEt0DnJT25WS1jWl8NYtVXfCyxouuTkhVrqP0ga8OJJpuoXkZ3c3rSkN1JJPNs8MjWvWsflTLyU60tHU4aEXSIiPBWVzPym24vY@28UzQ0M2SfIow6P8d4GcYxWw2KrdpCZnSulDHTZGYU1nNaba1kSS6I1Xm0VE6c0fL/L3f/SZvwQdrw "JavaScript (Node.js) – Try It Online") ### Commented The array `A[]` consists of all NATO words without the leading letter and with an extra dummy entry at index 0: ``` A = "XLfaRavoHarlieEltaCho...AnkeeUlu".match(/.[a-z]*/g) // -> [ "X", "Lfa", "Ravo", "Harlie", "Elta", "Cho", ..., "Ankee", "Ulu" ] ``` Main function: ``` f = ( // f is a recursive function taking: s, // s = input string C = ( // C[] = array of letter costs, initially // filled with 1n (BigInt literal) n = 100, // n = number of iterations A = ... // A[] = NATO dictionary (as defined above) ).map(_ => 1n), // g = s => // g = helper function taking a string s Buffer(s) // .reduce((t, c) => // for each character c in s: t + C[c & 31], // add the cost of this character to t 0n // starting with t = 0 ) // end of reduce() ) => // n-- ? // decrement n; if it was not equal to 0: f( // do a recursive call: s, // pass s unchanged A.map((w, i) => // for each entry w at position i in A[]: C[i] + // get the cost of the leading letter g(w) // add the cost of the other letters ) // end of map() ) // end of recursive call : // else: g(s) // stop the recursion and return g(s) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~93~~ 86 bytes Takes input in lowercase. -7 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!! ``` тFA.•_7R₆"9~úCĆ~'ÍΩ₃M¿jŽ×Øûå…{×}ζ¥ny†–År{è˜dÉ4sK%<0•“ÿ¼¯¤œ®ÈŠˆƒ‹Š™—……ÍЗ¼°µ†¸šÉµ“#{‡]g ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3M1R71HDonjzoEdNbUqWdYd3OR9pq1M/3Htu5aOmZt9D@7OO7j08/fCMw7sPL33UsKz68PTac9sOLc2rfNSw4FHD5MOtRdWHV5yek3K406TYW9XGAGjWo4Y5h/cf2nNo/aElRycfWne44@iC023HJj1q2Hl0waMWoPQUoEFAdLj38AQgB6hyw6GtQOMO7Ti68HAniDlHufpRw8LY9P//kxNLAA "05AB1E – Try It Online") with 7 iterations. **Commented:** ``` # implicit input: the starting word т # push 100 F ] # loop that many times: A # push the alphabet "abc ... xyz" .•8Á ... Ôò• # push compressed alphabet string "alfa bravo foxtrot juliett kilo lima papa romeo tango whiskey xray yankee zulu" “ ¼¯ .. ɵ“ # push compressed dictionary string "charlie delta echo golf hotel india mike november oscar quebec sierra uniform victor" ÿ # with the other string concatenated to the front # # split on spaces { # sort the words ‡ # transliterate: replace each character of the alphabet with the word at same index in the current string # a->alfa, b->bravo, ..., z->zulu g # after the loop: take the length ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~292~~ 276 bytes This is a little longer than the other Python answer, but finishes instantly. ``` w=[input()]+'LFA RAVO HARLIE ELTA CHO OXTROT OLF OTEL NDIA ULIETT ILO IMA IKE OVEMBER SCAR APA UEBEC OMEO IERRA ANGO NIFORM ICTOR HISKEY RAY ANKEE ULU'.split() s=[1]+[0]*26 exec"s=[i and v+sum(j*c.count(chr(i+64))for j,c in zip(s,w))for i,v in enumerate(s)];"*101 print sum(s) ``` [Try it online!](https://tio.run/##JY5Na8JAGITv/orBSz4RI8VL8bCmr81i4pZ1lYrkIGmKK3UT8qFt/3y60uszDzNT/3TnysyG4b44alP3nevlgZOuGCTbCyRMppxAqWKIEwHxrqRQEOkKQlGKzQtn2FlFKfBUgGcMfE0Qe8qWJLGNmQR7sw4tKYbIyDokJQPbvAps@ErIDDxWQiLh2zUd7O7Bhmsi27tzJm39pe2pUbs4RnlwnOb@bD4qv8tibInGyXzgFrT91b34xaSoetO5xblxdTB/8rzPqsElLKANfnXttuH9n@nw9mCl6a9lc@pKt/Xy57EfTaNR3WjT4VHYesPgxEw5fw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~79~~ 77 bytes ``` “¡þƓẠı$1ƇẆÇ£ėƬỵ⁸ŀƘṣHỌŻ×²ıÞṆ]q1@ƒḳ0JñỴngṙƑ§ƥỵ⁼@¬TQñɱ⁼=Œ¬⁴RȦȧ¡⁸ƒƈẈ»ŒlḲị@OFµȷ2¡L ``` [Try it online!](https://tio.run/##AaYAWf9qZWxsef//4oCcwqHDvsaT4bqgxLEkMcaH4bqGw4fCo8SXxqzhu7XigbjFgMaY4bmjSOG7jMW7w5fCssSxw57huYZdcTFAxpLhuLMwSsOx4bu0bmfhuZnGkcKnxqXhu7XigbxAwqxUUcOxybHigbw9xZLCrOKBtFLIpsinwqHigbjGksaI4bqIwrvFkmzhuLLhu4tAT0bCtci3MsKhTP///yJjYXQi "Jelly – Try It Online") This times out on TIO, but [Try it online!](https://tio.run/##AaQAW/9qZWxsef//4oCcwqHDvsaT4bqgxLEkMcaH4bqGw4fCo8SXxqzhu7XigbjFgMaY4bmjSOG7jMW7w5fCssSxw57huYZdcTFAxpLhuLMwSsOx4bu0bmfhuZnGkcKnxqXhu7XigbxAwqxUUcOxybHigbw9xZLCrOKBtFLIpsinwqHigbjGksaI4bqIwrvFkmzhuLLhu4tAT0bCtTnCoUz///8iY2F0Ig) with only 9 iterations Takes input in lowercase -2 bytes [thanks to](https://codegolf.stackexchange.com/questions/215436/nato-phonetic-spelling-can-take-long/215440?noredirect=1#comment503461_215440) [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) ## How it works ``` “¡þƓ...ƒƈẈ»ŒlḲị@OFµȷ2¡L - Main link. Takes a string S on the left µȷ2¡ - Do 100 times, updating the left argument each time, starting with S: “¡þƓ...ƒƈẈ» - The compressed string "India Juliett kilo mail Mike November Oscar papa Quebec Romeo sierra tango uniform Victor whiskey rayx Yankee Zulu alfa bravo Charlie delta echo foxtrot golf hotel" Œl - Lowercase Ḳ - Split on spaces O - Get the char code of each character in the left argument ị@ - 1-based, modular index into the list of phonetic spellings F - Flatten L - Length ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~98~~ ~~95~~ 94 bytes *Edit: -3 bytes thanks to caird coinheringaahing* ``` L!100¡ṁS:o!₁c w¨nḋ?ẏ_₇↑₇عṀ≥ÏΣ⁶Ḃ€żẎ,Ä₄ βże⁶ŻθŻ₂»Żβ∞Ξ⌈¬¹¢»ÿ¿k»aΨ₈2≡≥⁷_⁷‡@ƒΨ▼«± ¦τaċ‼₀xt►Φ₀lf₀£t ``` [Try it online!](https://tio.run/##DYyxisJAFEX7/Qrtrex2G/0AOz9AgiiCooWRtUweYY0oihZiJURRhE1jit0kExBejOX4DXN/ZJziHg4cuL3JuK91o/zJgUrc5teoDHLbH998Hap4UVPpugWa4WdjmO85UYmD@TlfyxPcPxUTKCwyla4quQfySjIqso4phZBxIUDEwmgE/yAPWPoccsJHFvmd730WlryC/CrmgfmE@98ygxPUn1sTdhn/8q3El5dnPRZwMpAztbFL5cXYoGvAJ1tr3bbsNw "Husk – Try It Online") (but with only 9 iterations) Unfortunately [TIO](https://tio.run/##DYyxisJAFEX7/Qrtrex2G/0AOz9AgiiCooWRtUweYY0oihZiJURRhE1jit0kExBejOX4DXN/ZJziHg4cuL3JuK91o/zJgUrc5teoDHLbH998Hap4UVPpugWa4WdjmO85UYmD@TlfyxPcPxUTKCwyla4quQfySjIqso4phZBxIUDEwmgE/yAPWPoccsJHFvmd730WlryC/CrmgfmE@98ygxPUn1sTdhn/8q3El5dnPRZwMpAztbFL5cXYoGvAJ1tr3bbsNw "Husk – Try It Online") errors with a 'stack overflow' at the 10th iteration, but the program/algorithm should run if provided with a (substantially) larger stack. Remove the initial `L` to check the actual string at each iteration [like this](https://tio.run/##Hc5BasJAFMbxvafQGwgtbryBVxCE4sKiiIhKA10lxaoTqWgg7iIyVQJZNS3tOAaEF9vl8wzvXWScuv/9P77H0aBjTOkOtnRweyX23GbhCWJSPn7w3GdvUuXXJaSkF7DHiOei280XKNn9JuXliTUY1Tm0@foe036RZ7t2GdIar8VlWsGA1Ia0oMP4N@Mwe8bPywxjh0NN@i0/kYpQwg6PmLH7g0HD2tv0CyTwVfwHwn7IT2cf3v9WPWdoS9yDxKAFCSl5Do0xzYfhFQ). ``` L # get the length of !100 # the 100th element of ¡ # repeatedly applying this function: ṁȯ # map & concatenate !₁ # each element of ₁ (see below) at index of c # codepoint of each character of input # function ₁: w # split on whitespace ¨ḋα⌋...«ḣĖ # compressed string: # "india juliett kilo ... foxtrot golf hotel" ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~286~~ \$\cdots\$ ~~238~~ 214 bytes Saved a whopping ~~44~~ ~~48~~ 72! bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!! ``` f=lambda s,n=100:n and sum(f(c+"LFA RAVO HARLIE ELTA CHO OXTROT OLF OTEL NDIA ULIETT ILO IMA IKE OVEMBER SCAR APA UEBEC OMEO IERRA ANGO NIFORM ICTOR HISKEY RAY ANKEE ULU".split()[ord(c)-65],n-1)for c in s)or len(s) ``` [Try it online!](https://tio.run/##TVFta9swEP6eX3HkS2zmDp3eVcjATZXG5EXDdcpKV0bmODQsdULsQrfS356dw2CVBLrTPfc8d6fD7/ZpX4vTaTPcrZ5/rlfQJPUQGbusYVWvoXl5jjZR@ak/G6eQp3cBJmk@yzz4WZHCaBIgfCvyUECYjSEUfgaL6yyFJUGKArJZgGyeQjb1EO78/MrncDtKc0i/EsZf@RGEuSeMz/MU0sVNgEU2DvkcslERcphkt1N/T7r3FJx6T7zL/ufmsNu2UfywP66jMr7Q6jGpLzDe7I9QwraGJiZrV9VRE5/aqmkbGELUn4flre8n0B@lRXddh5t@3KteD1XZVusOgqi1tcoahSg4OtraWSO1UMYYjto6I7iwjnHDuHbMSWu1lKilU5Ir54whLwGiMVJZJqV2FGJKaKEZZ05pyaXTyqARDDkyy51BjdJZ55giMcs4p4By3CWgjBT0bpkWRhKLEgaV0lwrjkIY3tFIFFSzoAREdJwrgnNLakIqpGdn/zf5A1nXp7TUBVoqlBvthDOaLGG6VvhH8DDiOkE6Mu6VT1X5qzp26YPvL9zIcpDA2UIxiHvd7Nuk6qb/Z3uIzlNP4INufNkDWt1XbKI2PjuH47Zuo83grX2Hiy/w1rzD2z@dh2o4bB7fB/HpLw "Python 3 – Try It Online") Times out on TIO and is still running on my laptop. ~~Will post my running time when it finishes.~~ As [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) correctly predicted, it tried to melt my computer into a wormhole but it valiantly defended itself with a `MemoryError`! :))) Have added smaller (\$1\$ iteration and \$10\$ iterations) testcases to check that it does indeed work in theory. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 85 bytes ``` ċⱮØA Çæד¢ị⁼Ɱ4ɦȷ3æ⁷ŀṣ⁶LṬⱮGṾxƬḟṬƊÆUFṡẉ⁴lṂṃȷỵḥṘ¤ʠḟẠṅṫSæßṠdċṣçẓẊẆPḲDṂƑĠṆṾ⁼Ɓ»ŒuḲÇ€æ*ȷ2¤FS ``` [Try it online!](https://tio.run/##HU69TsJQFN59jI7GSX0BIsKigaQyuOtiupLoxoVYAp3QQQYTq0IZaEw0antuDUNPaQpv8d0XuR5dTvKd7/fq0vNurC0C8/7G09oODzniB9N7zF@QBUb9yP9wE1XJAUdGJese6NWo7xNQLEwTtLouY6RPgssx@50G6Bl6ZNSnB@qDBlWC7AvpHDTNZ9vwT6pD0C1o6UqVGMOLIpBUXkDfQ4@h/TbSj7rYy0khUl9KZEip8mx91xWKh6Yfc7RbJfv5rOHaf3xurXPa6rjHzp5zVDuTW281nV8 "Jelly – Try It Online") I couldn't figure out how to compress the matrix itself better than the dictionary could, so this probably can't get shorter than caird's solution, but I figured it's worth posting anyways since it's considerably faster. There might still be a bit of room to golf, though, since I was already able to knock a byte off by manually fiddling with the uncompressed string. ``` ċⱮØA Monadic helper link, convert string to letter frequencies: Ɱ for each element of ØA "ABCDEFGHIJKLMNOPQRSTUVWXYZ", ċ count how many times it occurs in the argument. Çæד...»ŒuḲÇ€æ*ȷ2¤FS Main link: æ× matrix multiply Ç the input's letter frequencies ¤ by: “...» "alfa bravo Charlie delta echo foxtrot golf hotel India Juliett kilo mail Mike November Oscar papa Quebec Romeo sierra tango uniform Victor whiskey rayx Yankee Zulu" Œu uppercased Ḳ and split on spaces, Ç€ with each word converted to letter frequencies æ*ȷ2 and the resulting matrix multiplied by itself 100 times. F Flatten the resulting vector S and return its sum. ``` [Answer] # [Icon](https://github.com/gtownsend/icon), ~~379~~ ~~354~~ 351 bytes ``` procedure f(s) v:=list(26,0) b:=[] "ALFA BRAVO CHARLIE DELTA ECHO FOXTROT GOLF HOTEL INDIA JULIETT KILO LIMA MIKE NOVEMBER OSCAR PAPA QUEBEC ROMEO SIERRA TANGO UNIFORM VICTOR WHISKEY XRAY YANKEE ZULU "?while put(b,tab(upto(" ")))&move(1) v[ord(!s)-64]+:=1&\z;|1\100&{t:=list(26,0) t[ord(!b[i:=1to*v])-64]+:=v[i]&\z v:=t}&\z;(s:=0)+:=!v&\z return s end ``` [Try it online!](https://tio.run/##VZBPb4JAEMXvfIqRg9ltbQJN48HGNCsushVYuy5WixxE15TEgoEV03@f3WKbJu0c5jDv9yZ5L1sX@em0L4u12hxKBVtUYaPu9XdZpdF1t2NhI@3148Qwie8SGAgy4@B4RPiMwpD6kgB1PA4un0vBJYy474LHJfWBhUNG4D5qSClhzHwOPgsIBGxMIeQzGgyoAD51iIAJmRB4iOiAOiB4QDlMGRWCgCThiEMUMpeLAGbMkVzAo8emY7qAuSALWJBwTCk8RX4E5t3xOdsp2B80Sjt6laLDXhfIBBNj3H4paoXsJl5clBvUqvBV9ya57PXt9vLt9sNe2pbVftf/susfNI2zBtPFRZ38muo4SxrfuSv9eX6Aql7fwo3Sqs/3UulDmUNlqHzzp9@XVZYjbEAzqlblKxzLTCu0Ra3YDHg0pWbHdIhs9pCPzATjb/8X "Icon – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) (`-lgmp`), ~~464~~ ~~456~~ 452 bytes * -8 by using `mpz_array_init()` * -4 by @ceilingcat As C doesn't have a native bignum library, I'm using [GMP](https://gmplib.org/). To speed up the calculations, I memoize each stage of the computation. ``` #import<gmp.h> *l[]={"ALFA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIETT","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"};mpz_t t[2600];g(i,s,o,v,j)char*s;mpz_t*v,o;{for(;*s;mpz_add(o,o,*v))v=t+i*26+(j=*s++-65),mpz_sgn(*v)?:i?g(i-1,l[j],*v):mpz_set_ui(*v,strlen(l[j]));}f(s,o)mpz_t o;{mpz_init(o);mpz_array_init(*t,2600,512);g(99,s,o);} ``` [Try it online!](https://tio.run/##XVJhj5pAEP3Or9jQXLOL2HgmZ3LH6QW5VTlBrgj27qwxFNBbg2BYtGmNf712Rpo07ad5vHnvzewucXMdx@fzB7HdFWV1v97uPr33FC2bL7pH1XQGpqqrfd@ceVCtkek7Ngf0yJ0AO9waYWPgvQS@FwAaes4AysgLuAPVnjzaqHsKwRegYGw76HBsF3nXHmPcxJtxt899gN7UMrE@m88o@BzyPrcA@J7L0Ti1ue9jJzAnQyTCiT3wfBfQzLYCD71fRvZ0zF8BvfgmlldzMuY46C10QvVkbHc/lxWp5u1Oq7Uw1lToUi/0g75h8XtUarIWaAe9MI6roqTGHypKElqAUjswduhWDaG1Ow266Wqy0Wh2bpiOIrnOKQge7sQDJDev9Wy@WaDl7tJNq@VegECXVZmlOcUuY8ZpRWEHVm8GYxGIXFS0YPXosox@1IxW6bi4fnPdZrD87S1uDwnwiHmc7ZOU3MsqEQU@5D9UJr4hp4i8IttI5PRQiISRo0IInpvAKQHWK8TFPq8MBb4vF0BkHOUrql5tpaqTj5L1WgZZlWlKJasTQAgnqH3MuBDwMy13JUxDoyTdHrl6S77mEPCfEEfGWRqV9C97Uk5n1wunXLHMQHn0hr/iVRat5bmZQe65@f03 "C (gcc) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 397 392 bytes ``` String[]A=new String[26];char i=123,k;int S(String X){for(;--i>96;)A[i-97]=i+"lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split(" ")[i-97];for(char d:X.toCharArray())i+=U(d<96?d+32:d,100);return i-96;}int U(int c,int i){if(i==-1)return 1;k=0;for(char d:A[c-97].toCharArray())k+=U(d,i-1);return k;} ``` [Try it online!](https://tio.run/##XZBPa@MwEMXP8acYfJKI7eYPpJtqvYvprdCTt1AIOSiy0kwtS0aW3YaQz54dp1lYehlJzHvvN6N3OcjUtdq@V/Wl7XcGFSgjuw6eJVo4wd3dE0ngRwKlcR/aw6B9h84msFzADkMUTW62LshAx@CwgobMrAwe7VuWZSA5nKLJpDx2QTeZ60PWUiswqz@uHMazksWqCH9izkU0OUeXL/NmW@Sj6PZarLZCHaQHzOeLZVILCoHyBoJXfto7z0Sa4q/1SvBig@n6fpvjNDZ7CV4ODshsUIM2QYI6OHCfwbsAzuzBBW3AViihJ0kIgMYBNhKw1uAG3exo@04RXbak0TutwDWaNNp7CdK@ObBIEzSAKjgPB@xqfSTukZq11pTbx1nXGgwshph/jSfGma9LVQ@vWXCPdC0o8Mg4x2n@wqqf69XvarpcPFTJfDbjwuvQewvkXonz@AMvbKwqGSvyE@4Z5nk65zfhXNT57H9MsVEj@RusvsISJOM/RC3Ol/PlLw "Java (OpenJDK 8) – Try It Online") Input is a String. **Outputs in 32 bit cap** (rules weren't entirely clear on if it's required, as BigInteger does exist in Java). It takes in unimaginable time to complete, but here's a faster solution that loads comparably instant: # [Java (OpenJDK 8)](http://openjdk.java.net/), 511 506 bytes ``` String[]A=new String[26];Integer[][]B=new Integer[26][];int i=-1,j;int S(String X){for(;i++<25;)A[i]=(char)(i+97)+"lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split(" ")[i];for(;i-->0;)B[i]=new Integer[101];for(char d:X.toCharArray())i+=U(d<96?d+32:d,100);return i;}int U(int c,int i){if(i==-1)return 1;j=97;if(B[c-j][i]==null){B[c-j][i]=0;for(char d:A[c-j].toCharArray())B[c-j][i]+=U(d,i-1);}return B[c-j][i];} ``` [Try it online!](https://tio.run/##XVBdj9owEHyGX7HKk62EHHDqXTlfWkGlSq3UJ3rSSVEeTGJgg2Mjx6FFKL@dbkJ6PfXFHzOzO7NbypOc2KMyZXG4HpuNxhxyLesafkg0cIG7u@8kgY8RfJW1Vw5OytVoTQT3c9igH49HQ1ntpafrZLGAiorZ2js0uziOQXK4jEej9Zk6VLFtfHwkyjOjfvU@jMdrFuTL/c@AczEetePrrTjNlkknGn7zh0x8M17tlEuzNFv13F@AyDQT1BYwmcyisn@uhxTwyi9b65jAMHyefxB8mWKWsHwvHWcYLh55GOitBCdPFgjUqEBpLyHfW7C/vbMerN6C9UqDKVBCQxJPXtoCVhLwoMCeVLWhFdW5dCCPpFEblYOtFGmUcxKk2VkwSEkqwNxbB3usD@pMvmciD0pR3yaI66NGzwIIOMUUt@CTyaep4Ksu9/uxZ9PZTdHNAsXTa@ztF3ouye/MOMcweWHF8@LhcxHez5@KaDadcuGUb5wBFG23pRfWnXnUL49fcMswoR3yQTUTZbJ4FASv0nxSZl2ExDRa88s/YPo@xLKH/0vypu0TRUgGoh0s3jjRXtvrHw "Java (OpenJDK 8) – Try It Online") edit: Found a shortcut for .toLowerCase() for both ]
[Question] [ # [Garland Words](http://blog.vivekhaldar.com/post/89763722591/garland-words) A *garland word* is a word which can be strung together like a garland, because it ends with the same letters it starts with. These groups of letters can even overlap! For example, `underground` is a garland word of order `3`, because it starts and end with the same 3 characters, `und`. This means it could be strung together like `undergroundergrounderground...`. `alfalfa` is a garland word, too! It's of order 4. It starts and ends with `alfa`. It can be strung together like so: `alfalfalfalfa`. A process which I call garlandifying is where once you determine the order `n` of a garland word, you take the original word and add the segment required to have it loop as a garland `n` times. So, since `onion` is an order `2` garland word, you would take `onion`, chop off the first `2` letters to get `ion` and add that to the end `2` times to get `onionionion`. # Objective Make a *program or function* which takes input from **standard input or a function argument** and prints out or returns the word, garlandified. All words will be lowercase, and the highest possible order for a word is `length(word) - 1`. # Example I/O ``` "onion" --> "onionionion" "jackhammer" --> "jackhammer" "abracadabra" --> "abracadabracadabracadabracadabracadabra" "" --> "" "zvioz" --> "zviozvioz" "alfalfa" --> "alfalfalfalfalfalfa" "aaaa" --> "aaaaaaa" ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. [Answer] # Python, 60 bytes ``` f=lambda s,i=1:s.find(s[i:])and f(s,i+1)or(len(s)-i)*s[:i]+s ``` Was hoping for better, but oh well. `s.find` works neatly here in place of `not s.startswith`. [Answer] # Pyth, ~~19~~ 18 bytes ``` +z*>Kf!xz>zT1zl>zK ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2Bz*%3EKf!xz%3EzT1zl%3EzK&input=abracadabra&debug=0) or [Test harness](http://pyth.herokuapp.com/?code=zFz.zp%60zp%22+-%3E+%22%60%0A%2Bz*%3EKf!xz%3EzT1zl%3EzK&input=Test-cases%3A%0Aonion%0Ajackhammer%0Aabracadabra%0A%0Azvioz%0Aalfalfa%0Aaaaa&debug=0) ### Explanations: ``` +z*>Kf!xz>zT1zl>zK implicit: z = input string f 1 find the first number T >= 1, which satisfies: >zT all but the first T chars of z xz index of ^ in z ! == 0 K store in K the order is length(z) - K >K z the last K chars * repeated l>zK len(all but the last K chars) times +z insert z at the beginning ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 58 bytes ``` .+ $0#$0 (.*)(.+)#.*\1$ $0#$1#$2- +`\w#(\w*)- #$1-$1 #.*- <empty line> ``` Each line should go to its own file but you can run the code as one file with the `-s` flag. The four substitution pairs do the followings: * Duplicate word so we can search for overlaps too. * Append the word split up at `order` number of characters. * Append the last part `order` times. * Keep the original word and the lastly appended part and drop everything else. The string states for the example `onion`: ``` onion onion#onion onion#onion#on#ion- onion#onion##ion-ionion onionionion ``` [Answer] ## Haskell, 64 bytes ``` g s=[b>>a|(a,b)<-map(`splitAt`s)[1..],and$zipWith(==)s b]!!0++s ``` Tests: ``` λ: g "onion" == "onionionion" True λ: g "jackhammer" == "jackhammer" True λ: g "abracadabra" == "abracadabracadabracadabracadabracadabra" True λ: g "" == "" True λ: g "zvioz" == "zviozvioz" True λ: g "alfalfa" == "alfalfalfalfalfalfa" True λ: g "aaaa" == "aaaaaaa" True ``` [Answer] # Java, ~~160~~ 157 bytes ``` static void g(String s){int i=s.length(),o;for(String p=s;i-->0;)if(s.endsWith(s.substring(0,i))){for(o=i;o-->0;)p+=s.substring(i);System.out.print(p);i=0;}} ``` Input/Output: ``` g("abracadabra"); --> "abracadabracadabracadabracadabracadabra" ``` Spaced and tabbed for readability: ``` static void g(String s){ int i=s.length(),o; for(String p=s;i-->0;) if(s.endsWith(s.substring(0,i))){ for(o=i;o-->0;) p+=s.substring(i); System.out.print(p); i=0; } } ``` Suggestions welcome. [Answer] # Sed: ~~87~~ 84 characters (83 characters code + 1 character command line option.) ``` h s/(.*)./& \1/ T s/(.+) \1.*/ \1 \1/ t g q : s/^([^ ]+)(.*)[^ ]$/\1 \1\2/ t s/ //g ``` Sample run: ``` bash-4.3$ sed -r 'h;s/(.*)./& \1/;T;s/(.+) \1.*/ \1 \1/;t;g;q;:;s/^([^ ]+)(.*)[^ ]$/\1 \1\2/;t;s/ //g' <<< 'underground' undergroundergroundergrounderground ``` [Answer] # CJam, ~~24~~ 23 bytes ``` q_:Q,{~)Q>Q\#!},W>~_Q>* q_:Q e# Read the input, take a copy and store it in Q too ,{ }, e# Take the length of the input and filter [0 .. len - 1] array ~) e# Same as number * -1 Q> e# Take last number characters. Call this string S Q\#! e# See if Q starts with S. After the filter, we will only have e# those numbers from [0 .. len - 1] array which are valid orders W>~ e# Take the last order number, if exists. _Q>* e# Garlandify the input order times. ``` Just to start it with something.. [Try it online here](http://cjam.aditsu.net/#code=q_%3AQ%2C%7B~)Q%3EQ%5C%23!%7D%2CW%3E~_Q%3E*&input=alfalfa) [Answer] ## Matlab: ~~97~~ ~~89~~ 82 bytes Function that uses a regular expression with lookbehind and a capture group: ``` function t=f(s) n=sum(regexp(s,'(.*$)(?<=^\1.+)'))-1;t=[s(repmat(1:n,1,end-n)) s]; ``` That `sum` is needed to handle the empty-string input (convert `[]` into `0`). Examples: ``` > f('onion'), f('jackhammer'), f('abracadabra'), f(''), f('zvioz'), f('alfalfa'), f('aaaa') ans = onionionion ans = jackhammer ans = abracadabracadabracadabracadabracadabra ans = Empty string: 1-by-0 ans = zviozvioz ans = alfalfalfalfalfalfa ans = aaaaaaa ``` [Answer] # REGXY, ~~53~~ 49 bytes Uses [REGXY](http://esolangs.org/wiki/REGXY), a regex substitution based language ``` //$'#/ /.(.+)#\1\K/#/ a/(#).(.*#)|#.*/$'$1$2/ //a ``` **Overview:** A number of regular expressions are applied. An example run would look like: ``` onion (input) onion#onion (line 1 regex) onion#on#ion (line 2 regex - find the repeated section and separate with #) onionion#n#ion (line 3 regex - the length of the middle token is the garland order, remove a character and append the third token onto the original string on the left) onionionion##ion (line 4 regex is a pointer to line 3 - repeat the previous again) onionionion##ion (line 4 regex is a pointer to line 3 - strip everything after and including the #) ``` **Detailed explanation** The following is a line by line breakdown of the regexes: ``` //$'#/ ``` This is a regex substitution which matches the first empty string (i.e. the start of the string) and replaces it with everything to the right of the match (`$'`) followed by a hash. For example, it will turn `onion` into `onion#onion`. ``` /.(.+)#\1\K/#/ ``` This line finds the section which overlaps by looking for a group of characters immediate preceding the # (`(.+)`) which are the same on the other side of the # (`\1`). The \K just means 'forget that I matched anything', meaning it will not actually be replaced in the substitution. This effectively, this means we just add a # to the position after the overlap has been found, turning `onion#onion` into `onion#on#ion`. ``` a/(#).(.*#)|#.*/$'$1$2/ ``` The initial 'a' is just a label for the regex. After this, we find the first # followed by a single character (`.`) and capture everything after this until the next # (`.*#`). We replace this with everything to the right of the match, i.e. the last token ($'), followed by a # (`$1`), followed by the second token less a character (we treat this as a counter, decreasing it each iteration). In the case of onion#on#ion, the two tokens we backreference on are shown in brackets, and the section the entire regex matches is between the pipes: `onion|(#)o(n#)|ion`. We then replace the bits we match (between the pipes) with `$'` (everything to the right of the match, i.e. 'ion'), then $1 (the #), then $2 (n#), meaning we end up with `onion|(ion)(#)(n#)|ion` (brackets show the three tokens in the replacement string). If the regex fails to match in the first alternation (everything before the pipe), we must have decreased our counter to zero, meaning there are no characters inside the second token. Instead, we look at the second part of the pattern, `#.*`. This simply replaces everything after the first # with `$'$1$2`. Since there are no backreferences created by this alternation, and there is nothing to the right of the match (`.*` matches until the end of the string), we terminate the match and return the result. ``` //a ``` This is just a pointer to the previous line, ensuring we continue to execute the regex substitution until it fails to match any more. [Answer] # jq 1.5: 91 characters (87 characters code + 4 characters command line option.) ``` .+. as$t|[range(1;length)|select($t[:.]==$t[-.:])]|(max//0)as$i|[range($i)|$t[$i:]]|add ``` Sample run: ``` bash-4.3$ jq -R -r -f judy.jq <<< 'underground' undergroundergroundergrounderground ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), ~~51~~ 48 bytes ``` (.+)/\1 \1 (.+)(.+) .+\1$/\1(\2)^^((^^\1_)) .*/ ``` TAKE THAT, RETINA AND SED!!!!! ;) Cut off 3 bytes thanks to @randomra. [Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=(.%2B)%2F%5C1%20%5C1%0A(.%2B)(.%2B)%20.%2B%5C1%24%2F%5C1(%5C2)%5E%5E((%5E%5E%5C1_))%0A%C2%A0.*%2F&input=onion%0Ajackhammer%0Aabracadabra%0Azvioz%0Aalfalfa%0Aaaaa) Note that the `jackhammer` test case is not there. There's a bug in the [handling of spaces in the web interface](https://github.com/kirbyfan64/rs/issues/2) that causes it to print incorrect output. The offline version of `rs` handles it correctly. 51-byte version: ``` (.+)/\1 \1 ^(.+)(.+) (.+)\1$/\1(\2)^^((^^\1_)) .*/ ``` [Live demo and test cases for original.](http://kirbyfan64.github.io/rs/index.html?script=(.%2B)%2F%5C1%20%5C1%0A%5E(.%2B)(.%2B)%20(.%2B)%5C1%24%2F%5C1(%5C2)%5E%5E((%5E%5E%5C1_))%0A%C2%A0.*%2F&input=onion%0Aabracadabra%0Azvioz%0Aalfalfa%0Aaaaa) [Answer] ## JavaScript (ES6), 95 bytes ``` f=s=>{for(e=i=s.length;i&&e;)s+=s.slice(--i).repeat(!(e=!s.endsWith(s.slice(0,i)))*i);return s} ``` ### Demo Firefox only for now: ``` f = s => { for (e = i = s.length; i && e;) s += s.slice(--i).repeat(!(e = !s.endsWith(s.slice(0, i))) * i); return s } console.log = x => X.innerHTML += x + '\n'; console.log(f('onion')); console.log(f('jackhammer')); console.log(f('abracadabra')); console.log(f('')); console.log(f('zvioz')); console.log(f('alfalfa')); console.log(f('aaaa')); ``` ``` <pre id=X></pre> ``` [Answer] ## JavaScript (ES6), 82 bytes ``` g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i) ``` *[Deleted my original answer, because I've now learned ES6 and was interested in finding a recursive solution to this challenge]* **Example** ``` g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i) console.log(g('onion')); console.log(g('jackhammer')); console.log(g('abracadabra')); console.log(g('')); console.log(g('zvioz')); console.log(g('alfalfa')); console.log(g('aaaa')); ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ 13 bytes ``` ÞKvḟǓṘ†Tt~ȯẋJ ``` [Try it Online! (test suite)](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiw55LduG4n8eT4bmY4oCgVHR+yK/huotKIiwiIiwib25pb25cbmphY2toYW1tZXJcbmFicmFjYWRhYnJhXG5cbnp2aW96XG5hbGZhbGZhXG5hYWFhIl0=) **Explanation:** ``` ÞKvḟǓṘ†Tt~ȯẋJ # whole program ÞK # get all suffixes of implicit input vḟ # then find each first occurrence in the input Ǔ # rotate the list to the left Ṙ # then reverse † # logical NOT each item T # get indices of elements which are truthy t # get tail ȯ # slice the input from it until the end ~ # just push it, do not pop the used items yet ẋ # repeat the sliced input tail amount of times J # then join with the input ``` [Answer] ## CoffeeScript + ES6, 77 bytes Same approach as my JavaScript answer. ``` f=(s,e=i=s.length)->s+=s[i..].repeat !(e=!s.endsWith s[...i])*i while--i&&e;s ``` [Answer] ## C ``` #include <stdio.h> #include <string.h> int main(int argc, char **argv) { char *str = NULL; char *p = NULL; int len = 0 ; int i = 0; int j = 0; int k = 0; int loop = 0; if (argc == 1 ) return 0; str = argv[1]; len = strlen(str); if (len %2) { loop = len/2 + 1; } else { loop = len/2; } p = &str[len/2]; for (i = 0; i < loop ; i++) { if (str[k] == *(p++)) { k++; } else k = 0; } printf("k = %d\n", k); printf("%s", str); p = &str[k]; for (j =0; j < k ; j++) { printf("%s", p); } return 0; } ``` # Golfed: 195 bytes - GCC ``` main(int c,char**a){ char *s=a[1],*p;int i=0,j=0,k=0,z,l=strlen(a[1]); z=l%2?-~(l/2):l/2;p=&s[l/2]; for(;i<z;i++)k=s[k]==*(p++)?-~k:0; printf("k=%d\n",k);puts(s);p= &s[k]; for(;j<k;j++)puts(p);} ``` [Answer] # Groovy ~~75~~ ~~57~~ 55 bytes ``` f={w->x=w;w.find{x-=it;!w.indexOf(x)};w+(w-x)*x.size()} ``` Amazing how coming back to something the day after can help ### Ungolfed: ``` f = {w -> //Set x equal to w x=w //Loop through the characters of w until we return true w.find { //set x equal to x minus the first instance of the current character, i.e. the word minus the first character x-=it //Returns the index of the first occurance of the string of chars x, when this is 0 (false) we want to return true, so negate it !w.indexOf(x) } //When we've escaped the loop, if we've found a match return the word plus the word minus the match multiplied by the lengh of the match. w+(w-x)*x.size() } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 75 bytes ``` ->s{t=(1...s.size).map{s[_1..]}.find{s[/^#{_1}/]} t ?s+s[(o=t.size)..]*o:s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3vXXtiqtLbDUM9fT0ivWKM6tSNfVyEwuqi6PjgUKxtXppmXkpQJ5-nHJ1vGGtfmwtV4mCfbF2cbRGvm0JVINerFa-VXEt1MiygtKSYgW3aKX8vMz8PKVYLhg_KzE5OyMxNze1CEkwMakoMTkxBUQhiSIxq8oy86uQNeSkgRCyCBAoxUJsX7AAQgMA) ]
[Question] [ My homework is to write a ***Martian essay*** (see below) between 729 and 810 words, inclusive. Your task is to write a program that will generate the essay. ## History Around the turn of the 20th century, spiritualist Catherine-Elise Müller allegedly communicated with Martians. During somnambulatory trances, she would write out Martian scripts. Psychologist Théodore Flourney discovered her Martian writings were very similar to her native French, and in his book "From India to the Planet Mars", he documented Catherine's Martian alphabet. The following is *loosely* based on that alphabet with an extended mythos. ## Problem Description The Martian language has 21 letters, shown here next to each Latin equivalent: [![enter image description here](https://i.stack.imgur.com/CkpKv.png)](https://i.stack.imgur.com/CkpKv.png) Unfortunately, there's no Unicode for Martian (despite Mars being part of the universe), so we're stuck using Latin characters. Whereas in English our phonemes break out into two major types (consonants/vowels) which we loosely map to letters, Martian has three letter types: * The vowels: a e i m n o u * The hard consonants: b c d g k p t * The soft consonants: f h l r s v z In addition to this, the Martian language contains a single punctuation mark--the period. A **Martian word** is a set of 3 to 9 letters. All Martian words have at least one vowel, one hard consonant, and one soft consonant (in any arrangement). For example, `fng`, `cdaz`, `vpi`, and `pascal` are Martian words. A **Martian sentence** is a set of 3 to 9 Martian words delimited by spaces and followed by a period. A **Martian paragraph** is a set of 3 to 9 Martian sentences delimited by spaces and followed by a newline. A **Martian essay** is a collection of Martian paragraphs that contains no contiguous word repetitions. A **contiguous word repetition** is any construct S S where S is a contiguous set of words. Note that this definition ignores sentence and paragraph boundaries. ### Examples *Please note: There's a single trailing newline following each example (since all Martian paragraphs end in a newline)* ***Not Martian essay*** ``` lorem ipsum dolor sit amet. quis nostrud exercitation ullamco laboris. ``` ...for many reasons. This example is to illustrate some miscellaneous rules: * lorem is not a Martian word because it has no hard consonants. * amet is not a Martian word because it has no soft consonants. (`m` is a Martian vowel). * quis is not a Martian word because it has no hard consonants * quis is not a Martian word because q is not a Martian letter * exercitation is not a Martian word because it has more than 9 letters * exercitation is not a Martian word because x is not a Martian letter ***Martian essay*** ``` fng cdaz vpi. pascal broke basic. popplers taste great. ``` ...because it is a Martian paragraph. The Martian paragraph contains three Martian sentences. ***Not Martian essay*** ``` fng cdaz vpi. pascal broke basic. free pascal rules. ``` ...since `free pascal rules.` is not a Martian sentence, because neither `free` nor `rules` are Martian words, because they do not have any hard consonants. ***Martian essay*** ``` fng cdaz vpi. pascal broke basic. popplers taste great. cdaz vpi fng. basic breaks pascal. popplers punch hard. fng cdaz vpi. ``` ...which contains two Martian paragraphs. The sentence `fng cdaz vpi.` appears twice, but that's perfectly fine. ***Not Martian essay*** ``` popplers taste fng. cdaz vpi pascal. broke fng cdaz vpi. pascal broke omicron planets. basic scares goats. vpi piv vpi. ``` ...because the construct `fng. cdaz vpi pascal. broke fng cdaz vpi. [nl] pascal broke` is a contiguous word repetition. # Challenge Your challenge is to write a function or program that accepts no input, which produces as its output my homework; that is, your program should generate a **Martian essay** between 729 and 810 words (inclusive). Keep in mind, your program's output must be a valid Martian essay, but you don't have to generate it randomly or different each time. *Anything you do to generate a valid Martian essay* counts. I've [written a C++ program to check essays](http://ideone.com/fork/34W8KI) that you're allowed to use. This is code golf. Shortest code in bytes wins. Standard loopholes disallowed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28 26 25 24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to carusocomputing (replace the word `thimble` with `abcdefg`) ``` 9ØaḣŒ!s²ḣµs9K€;€”.K;⁷µ€ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=OcOYYeG4o8WSIXPCsuG4o8K1czlL4oKsO-KCrOKAnS5LO-KBt8K14oKs&input=)** ### How? Makes a list of all `362880` permutations of the first ~~seven~~ nine letters of the English alphabet `abcdefghi`, which all have the properties of Martian words and are all distinct, and formats them into an essay using the first `729` words. ``` 9ØaḣŒ!s²ḣµs9K€;€”.K;⁷µ€ - Main link: no arguments 9 - 9 as x µ - monadic chain separation Øa - yield lowercase alphabet ḣ - head to x ("abcdefghi") Œ! - all permutations (362880 distinct Martian words) ² - square x = 81 s - split into chunks of length 81 (the paragraphs) ḣ - head to x (get the first 9 paragraphs only) µ€ - monadic chain for €ach (for each chunk:) s9 - split into chunks of length 9 (the sentences) K€ - join with spaces for €each (between words in each sentence) ;€ - concatenate €ach with ”. - '.' (add a full stop* after each sentence) K - join with spaces (add a space between the sentences) ; - concatenate with ⁷ - a line feed - implicit print ``` \* period [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~25~~ ~~24~~ ~~22~~ 20 bytes *-2 bytes thanks to Emigna (Significant refactor, thanks man).* ``` A7£œJðý72ô€¨'.«9ô9£» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=QTfCo8WTSsOww703MsO04oKswqgnLsKrOcO0OcKjwrs&input=) ``` A7£ # Push first 7 letters of the alphabet. œJðý # All 5040 permutations of "abcdefg" joined by spaces. 72ô # Split into pieces of 72 (Sentences). € # For each piece... ¨'.« # Lop of the last char and concat a period. 9ô # Split into pieces of 9 (paragraphs). 9£ # Take only the first 9 paragraphs. » # Join by newlines and implicitly print. ``` Turns out the 810 word version is shorter than the 729 word version. **Output:** ``` abcdefg abcdegf abcdfeg abcdfge abcdgef abcdgfe abcedfg abcedgf abcefdg. abcefgd abcegdf abcegfd abcfdeg abcfdge abcfedg abcfegd abcfgde abcfged. abcgdef abcgdfe abcgedf abcgefd abcgfde abcgfed abdcefg abdcegf abdcfeg. abdcfge abdcgef abdcgfe abdecfg abdecgf abdefcg abdefgc abdegcf abdegfc. abdfceg abdfcge abdfecg abdfegc abdfgce abdfgec abdgcef abdgcfe abdgecf. abdgefc abdgfce abdgfec abecdfg abecdgf abecfdg abecfgd abecgdf abecgfd. abedcfg abedcgf abedfcg abedfgc abedgcf abedgfc abefcdg abefcgd abefdcg. abefdgc abefgcd abefgdc abegcdf abegcfd abegdcf abegdfc abegfcd abegfdc. abfcdeg abfcdge abfcedg abfcegd abfcgde abfcged abfdceg abfdcge abfdecg. abfdegc abfdgce abfdgec abfecdg abfecgd abfedcg abfedgc abfegcd abfegdc. abfgcde abfgced abfgdce abfgdec abfgecd abfgedc abgcdef abgcdfe abgcedf. abgcefd abgcfde abgcfed abgdcef abgdcfe abgdecf abgdefc abgdfce abgdfec. abgecdf abgecfd abgedcf abgedfc abgefcd abgefdc abgfcde abgfced abgfdce. abgfdec abgfecd abgfedc acbdefg acbdegf acbdfeg acbdfge acbdgef acbdgfe. acbedfg acbedgf acbefdg acbefgd acbegdf acbegfd acbfdeg acbfdge acbfedg. acbfegd acbfgde acbfged acbgdef acbgdfe acbgedf acbgefd acbgfde acbgfed. acdbefg acdbegf acdbfeg acdbfge acdbgef acdbgfe acdebfg acdebgf acdefbg. acdefgb acdegbf acdegfb acdfbeg acdfbge acdfebg acdfegb acdfgbe acdfgeb. acdgbef acdgbfe acdgebf acdgefb acdgfbe acdgfeb acebdfg acebdgf acebfdg. acebfgd acebgdf acebgfd acedbfg acedbgf acedfbg acedfgb acedgbf acedgfb. acefbdg acefbgd acefdbg acefdgb acefgbd acefgdb acegbdf acegbfd acegdbf. acegdfb acegfbd acegfdb acfbdeg acfbdge acfbedg acfbegd acfbgde acfbged. acfdbeg acfdbge acfdebg acfdegb acfdgbe acfdgeb acfebdg acfebgd acfedbg. acfedgb acfegbd acfegdb acfgbde acfgbed acfgdbe acfgdeb acfgebd acfgedb. acgbdef acgbdfe acgbedf acgbefd acgbfde acgbfed acgdbef acgdbfe acgdebf. acgdefb acgdfbe acgdfeb acgebdf acgebfd acgedbf acgedfb acgefbd acgefdb. acgfbde acgfbed acgfdbe acgfdeb acgfebd acgfedb adbcefg adbcegf adbcfeg. adbcfge adbcgef adbcgfe adbecfg adbecgf adbefcg adbefgc adbegcf adbegfc. adbfceg adbfcge adbfecg adbfegc adbfgce adbfgec adbgcef adbgcfe adbgecf. adbgefc adbgfce adbgfec adcbefg adcbegf adcbfeg adcbfge adcbgef adcbgfe. adcebfg adcebgf adcefbg adcefgb adcegbf adcegfb adcfbeg adcfbge adcfebg. adcfegb adcfgbe adcfgeb adcgbef adcgbfe adcgebf adcgefb adcgfbe adcgfeb. adebcfg adebcgf adebfcg adebfgc adebgcf adebgfc adecbfg adecbgf adecfbg. adecfgb adecgbf adecgfb adefbcg adefbgc adefcbg adefcgb adefgbc adefgcb. adegbcf adegbfc adegcbf adegcfb adegfbc adegfcb adfbceg adfbcge adfbecg. adfbegc adfbgce adfbgec adfcbeg adfcbge adfcebg adfcegb adfcgbe adfcgeb. adfebcg adfebgc adfecbg adfecgb adfegbc adfegcb adfgbce adfgbec adfgcbe. adfgceb adfgebc adfgecb adgbcef adgbcfe adgbecf adgbefc adgbfce adgbfec. adgcbef adgcbfe adgcebf adgcefb adgcfbe adgcfeb adgebcf adgebfc adgecbf. adgecfb adgefbc adgefcb adgfbce adgfbec adgfcbe adgfceb adgfebc adgfecb. aebcdfg aebcdgf aebcfdg aebcfgd aebcgdf aebcgfd aebdcfg aebdcgf aebdfcg. aebdfgc aebdgcf aebdgfc aebfcdg aebfcgd aebfdcg aebfdgc aebfgcd aebfgdc. aebgcdf aebgcfd aebgdcf aebgdfc aebgfcd aebgfdc aecbdfg aecbdgf aecbfdg. aecbfgd aecbgdf aecbgfd aecdbfg aecdbgf aecdfbg aecdfgb aecdgbf aecdgfb. aecfbdg aecfbgd aecfdbg aecfdgb aecfgbd aecfgdb aecgbdf aecgbfd aecgdbf. aecgdfb aecgfbd aecgfdb aedbcfg aedbcgf aedbfcg aedbfgc aedbgcf aedbgfc. aedcbfg aedcbgf aedcfbg aedcfgb aedcgbf aedcgfb aedfbcg aedfbgc aedfcbg. aedfcgb aedfgbc aedfgcb aedgbcf aedgbfc aedgcbf aedgcfb aedgfbc aedgfcb. aefbcdg aefbcgd aefbdcg aefbdgc aefbgcd aefbgdc aefcbdg aefcbgd aefcdbg. aefcdgb aefcgbd aefcgdb aefdbcg aefdbgc aefdcbg aefdcgb aefdgbc aefdgcb. aefgbcd aefgbdc aefgcbd aefgcdb aefgdbc aefgdcb aegbcdf aegbcfd aegbdcf. aegbdfc aegbfcd aegbfdc aegcbdf aegcbfd aegcdbf aegcdfb aegcfbd aegcfdb. aegdbcf aegdbfc aegdcbf aegdcfb aegdfbc aegdfcb aegfbcd aegfbdc aegfcbd. aegfcdb aegfdbc aegfdcb afbcdeg afbcdge afbcedg afbcegd afbcgde afbcged. afbdceg afbdcge afbdecg afbdegc afbdgce afbdgec afbecdg afbecgd afbedcg. afbedgc afbegcd afbegdc afbgcde afbgced afbgdce afbgdec afbgecd afbgedc. afcbdeg afcbdge afcbedg afcbegd afcbgde afcbged afcdbeg afcdbge afcdebg. afcdegb afcdgbe afcdgeb afcebdg afcebgd afcedbg afcedgb afcegbd afcegdb. afcgbde afcgbed afcgdbe afcgdeb afcgebd afcgedb afdbceg afdbcge afdbecg. afdbegc afdbgce afdbgec afdcbeg afdcbge afdcebg afdcegb afdcgbe afdcgeb. afdebcg afdebgc afdecbg afdecgb afdegbc afdegcb afdgbce afdgbec afdgcbe. afdgceb afdgebc afdgecb afebcdg afebcgd afebdcg afebdgc afebgcd afebgdc. afecbdg afecbgd afecdbg afecdgb afecgbd afecgdb afedbcg afedbgc afedcbg. afedcgb afedgbc afedgcb afegbcd afegbdc afegcbd afegcdb afegdbc afegdcb. afgbcde afgbced afgbdce afgbdec afgbecd afgbedc afgcbde afgcbed afgcdbe. afgcdeb afgcebd afgcedb afgdbce afgdbec afgdcbe afgdceb afgdebc afgdecb. afgebcd afgebdc afgecbd afgecdb afgedbc afgedcb agbcdef agbcdfe agbcedf. agbcefd agbcfde agbcfed agbdcef agbdcfe agbdecf agbdefc agbdfce agbdfec. agbecdf agbecfd agbedcf agbedfc agbefcd agbefdc agbfcde agbfced agbfdce. agbfdec agbfecd agbfedc agcbdef agcbdfe agcbedf agcbefd agcbfde agcbfed. agcdbef agcdbfe agcdebf agcdefb agcdfbe agcdfeb agcebdf agcebfd agcedbf. agcedfb agcefbd agcefdb agcfbde agcfbed agcfdbe agcfdeb agcfebd agcfedb. agdbcef agdbcfe agdbecf agdbefc agdbfce agdbfec agdcbef agdcbfe agdcebf. agdcefb agdcfbe agdcfeb agdebcf agdebfc agdecbf agdecfb agdefbc agdefcb. agdfbce agdfbec agdfcbe agdfceb agdfebc agdfecb agebcdf agebcfd agebdcf. agebdfc agebfcd agebfdc agecbdf agecbfd agecdbf agecdfb agecfbd agecfdb. agedbcf agedbfc agedcbf agedcfb agedfbc agedfcb agefbcd agefbdc agefcbd. agefcdb agefdbc agefdcb agfbcde agfbced agfbdce agfbdec agfbecd agfbedc. agfcbde agfcbed agfcdbe agfcdeb agfcebd agfcedb agfdbce agfdbec agfdcbe. agfdceb agfdebc agfdecb agfebcd agfebdc agfecbd agfecdb agfedbc agfedcb. bacdefg bacdegf bacdfeg bacdfge bacdgef bacdgfe bacedfg bacedgf bacefdg. ``` [Answer] # Ruby, ~~86 83 82~~ 79 bytes ``` (8019..8747).map{|x|$><<x.to_s(3).tr('012','abf')+(x%9>7?".\n":x%3>1?". ":" ")} ``` The trick: print all numbers between 102000000 and 102222222 in base 3 [Answer] # Mathematica, 113 bytes ``` StringRiffle[(p=Partition)["ark"["bus","car"][[#]]&/@Differences@Array[ThueMorse,730],3]~p~3,n=".\n",". "," "]<>n ``` Unnamed function that produces a string as output; that string is a Martian essay where each sentence has three words and each paragraph has three sentences. (Its deterministic output is below.) The core of the algorithm uses the cool mathematical fact that the [differences of the Thue–Morse sequence](https://en.wikipedia.org/wiki/Square-free_word#Examples) form an infinite sequence of the three symbols –1, 0, and 1 that has no contiguous digit repetitions. `Differences@Array[ThueMorse,730]` generates that sequence, to length 729. Then `"ark"["bus","car"][[#]]&/@` is applied to this sequence; this converts each 1 to "bus" (the first argument), each –1 to "car" (the last argument), and each 0 to "ark" (the function head). `(p=Partition)[...,3]~p~3` divides this sequence of words into nested lists, each consisting of three lists of three words each. Finally, `StringRiffle[...,n=".\n",". "," "]` concatenates all the words together, with different separators depending on the list levels; and `<>n` appends the final period and newline. The output sure doesn't look repetition-free.... ``` ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. car bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus ark car. ark bus car. bus ark car. bus car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. car bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. car bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car bus car. ark bus car. bus ark car. ark bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. car bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. car bus ark. car bus car. ark bus ark. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus ark car. ark bus car. bus ark car. bus car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car bus. car ark bus. car bus ark. car ark bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus ark car. ark bus car. bus ark car. bus car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus ark car. ark bus car. bus ark car. ark bus ark. car bus car. ark bus car. bus ark car. bus car ark. bus ark car. ark bus car. bus ark car. bus car ark. bus car bus. ark car ark. bus ark car. bus car ark. bus car bus. ark car bus. car ark bus. ark car ark. ``` # Mathematica, 100 bytes ``` StringRiffle[(p=Partition)[Permutations@Characters@"thimble"~Take~729,9]~p~9,n=".\n",". "," ",""]<>n ``` A direct port of Jonathan Allen's Jelly algorithm. [Answer] # [Python 3](https://docs.python.org/3/), ~~121 119~~ 114 bytes -5 thanks to [Jitse](https://codegolf.stackexchange.com/users/87681)! ``` from itertools import* i=729 while i:i-=1;print(*[*permutations('thimble')][i],sep='',end='.'[i%9:]+' \n'[i%81<1]) ``` **[Try it online!](https://tio.run/##FcZBDsIgEADAe1/BxWyL1QQ9aKu8BDloXMMmwBJYY3w9xjlN@UrgfOz9VTkpEqzCHJuiVLiKHsieDsvwCRRR0Uo7ay6lUpZRO12wprfchTi3ESRQekSEyTvyc8NiAWbMTwt7cLRZVr8Fdcv/n83V@Kn3Hw "Python 3 – Try It Online")** ### How? Counts down from `i=729` and gets a list of the letters of the ith permutation of `'thimble'` as the next distinct Martian word (`list(permutations('thimble'))[i]`). Avoids `''.join(...)` by use of a `*expression` to unpack the list while changing the default separator for `print` from a space to the empty string (`sep=''`). Uses the `end` argument of `print` to optionally add spaces, full stops and line feeds as required using modular arithmetic. A full stop goes after every ninth word (`'.'*(i%9<1)`) and a line feed goes after every eighty-first word, otherwise a space does, achieved by indexing into a two character string (`' \n'[i%81<1]`). [Answer] # PHP, 86 bytes ``` for(;$i<729;$$s="")echo${$s=str_shuffle(abcdefg)}??$s.(++$i%3?"":".").($i%9?" ":"\n"); ``` Generates a randomised 729 word essay that repeats no words. Use like: ``` php -r 'for(;$i<729;$$s="")echo${$s=str_shuffle(abcdefg)}??$s.(++$i%3?"":".").($i%9?" ":"\n");' ``` Explanation: ``` for(;$i<729; # until we've generated 729 words $$s="") # assign a blank string to the variable for the previous word echo ${$s=str_shuffle(abcdefg)}?? # generate a random word and if the variable for it has been assigned echo that variable (a blank string) $s.(++$i%3?"":".").($i%9?" ":"\n"); # otherwise echo the string and punctuation based on the word number (which is incremented here) ``` [Answer] # ///, 95 bytes ``` /_/abf//-/_ _a _e _i _m _n _o _u _aa.//'/- b- c- d- g- j- p- t- bb-/' f' h' l' r' s' v' z' ff' ``` *(additional new line at the end, not visible here)* **[Try it online!](http://slashes.tryitonline.net/#code=L18vYWJmLy8tL18gX2EgX2UgX2kgX20gX24gX28gX3UgX2FhLi8vJy8tIGItIGMtIGQtIGctIGotIHAtIHQtIGJiLS8nCmYnCmgnCmwnCnInCnMnCnYnCnonCmZmJwo&input=)** **Essay:** ``` abf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. fabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. habf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. labf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. rabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. sabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. vabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. zabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. ffabf abfa abfe abfi abfm abfn abfo abfu abfaa. babf abfa abfe abfi abfm abfn abfo abfu abfaa. cabf abfa abfe abfi abfm abfn abfo abfu abfaa. dabf abfa abfe abfi abfm abfn abfo abfu abfaa. gabf abfa abfe abfi abfm abfn abfo abfu abfaa. jabf abfa abfe abfi abfm abfn abfo abfu abfaa. pabf abfa abfe abfi abfm abfn abfo abfu abfaa. tabf abfa abfe abfi abfm abfn abfo abfu abfaa. bbabf abfa abfe abfi abfm abfn abfo abfu abfaa. ``` [Answer] ## JavaScript (ES6), 130 bytes This essay contains 774 Martian words, from a dictionary of 308 distinct words, made of all Martian letters. ``` _=>[...Array(2322)].map((_,i)=>['aeimnou','bcdgkpt','fhlrsvz'][i%3][(z=z*71%1e9)%7]+(++i%3?'':i%9?' ':i%27?'. ':`. `),z=1).join`` ``` Letters are picked in a pseudo-random manner, using the following formula: ``` (71^n mod 1000000000) mod 7 ``` Where `71` is the smallest prime [1] for which no contiguous word repetition appear with this modulo. ``` let f = _=>[...Array(2322)].map((_,i)=>['aeimnou','bcdgkpt','fhlrsvz'][i%3][(z=z*71%1e9)%7]+(++i%3?'':i%9?' ':i%27?'. ':`. `),z=1).join`` console.log(f()); ``` --- *[1] I only tested primes at the time I wrote this code. The smallest non-prime candidate is `56`.* [Answer] # Python 3, ~~404~~ ~~270~~ ~~332~~ ~~339~~ ~~285~~ ~~266~~ 259 bytes This is an attempt to create a random Martian essay my randomly sampling the Martian alphabet and checking afterwards which words work. **Edit:** -10 bytes from Zachary T's suggestion to use `R=range`. -9 bytes from changing `.intersection(w)` to `&set(w)`. -7 bytes from changing `A[random.randrange(21)]` to `random.choice(A)`. ``` import random W=[];A="abfechidlmgrnksopvutz";R=range while len(W)<729:W+=[''.join(random.choice(A)for j in R(9))for i in R(729)];W=[*set(w for w in W if all(set(A[z::3])&set(w)for z in R(3)))] for j in R(9):print(" ".join(W[81*j+i]+"."*(i%9>7)for i in R(81))) ``` **Ungolfing** ``` import random word_list = [] alphabet = "abfechidlmgrnksopvutz" while len(word_list) < 729: # generates words for i in range(729): word = "" for j in range(9): word += alphabet[random.randrange(21)] word_list.append(word) # removes invalid words that don't have at least one letter of each letter type kept_words = [] for word in word_list: all_letter_types = [0, 0, 0] for z in range(3): all_letter_types[z] = set(alphabet[z::3]) & set(word) if all(all_letter_types): kept_words.append(word) word_list = kept_words[:] # removes any contiguous word repetitions by removing all repeated words word_list = list(set(word_list)) # attaches punctuation and prints for j in range(9): result = [] for i in range(81): word = word_list[81*j+i] if i%9 == 8: word += "." print(" ".join(result)) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~19~~ 18 bytes ``` ↑9C9mo`:'.wC9P…"ag ``` [Try it online!](https://tio.run/##yygtzv7//1HbREtny9z8BCt1vXJny4BHDcuUEtP//wcA "Husk – Try It Online") 729 words, using the same idea as the 05AB1E answer. -1 byte from Dominic Van Essen. [Answer] # [Zsh](https://www.zsh.org/) `-P`, 51 bytes ``` x=(a e i m n o u) echo $x{f,h,l,r,s}$x{b,d,g.}|fold ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSboBS7EKNpaUlaboWN40rbDUSFVIVMhVyFfIU8hVKNblSkzPyFVQqqtN0MnRydIp0imuBnCSdFJ10vdqatPycFIjWjZo1JampCnYa5ckKuuV2akaaEPEFCyA0AA) The output has some trailing spaces, which I think are normally allowed, but if not, this can be fixed by adding `|cut -c-79` (+10 bytes). ## Explanation The basic idea is to generate a number of unique Martian words, then group them into sentences and paragraphs. I used 4-letter words of the format `vsvh` (vowel, soft consonant, vowel, hard consonant), because it makes it possible to get enough words using just one cartesian product. (This is what the `{,,,}` expansions do; the `-P` option to Zsh also enables that multiplying behaviour for array variables, allowing us to reuse `$x`). There are enough unique 3-letter words to meet the word count, but they would require multiple separate expansions - one single format (e.g. `vsh`) can only produce \$ 7^3 = 343 \$ words. This would take too many extra bytes. Then, by adding a `.` to one of the letters, we can ensure there are regular sentence breaks - here, it's every time `g` comes around in the cartesian product. Finally, piping this all to `fold` inserts line breaks, to keep the paragraphs under 10 sentences each. The fact that this all works, and can be so short, is slightly miraculous. It relies on some very specific mathematical properties: by having \$ x = 7 \$ vowels, \$ y = 5 \$ soft consonants, and \$ z = 3 \$ hard consonants, we ensure: * \$ 729 \le xyxz \le 810 \$, so our essay meets the word count * \$ z \ge 3 \$, so each sentence has enough words in it (remember one of the hard consonants has a `.` at the end) * \$ 80 \div (5z+1) \in \mathbb Z \cap [3, 9] \$, so the `fold` command, which defaults to wrapping every 80 characters, will break the essay up into paragraphs with a valid integer number of sentences * \$ xyxz \equiv 0 \mod (80 \div (5z+1))z \$, so the last paragraph doesn't have any remainder sentences Any of the issues above could be worked around, of course, but that would cost extra bytes. \$ 7, 5, 3 \$ is actually [the only choice that works perfectly](https://ato.pxeger.com/run?1=ZZDRasJAEEXpa7_igghJjJg0iFFMX_obfZnqbBKIk7BZJcmv9MWX9qP6Nd012iIuLDt7Zu5luJ_fTW-KWs7nr6NR8_Tn6U3VGh1KgSbJ2YtDpP7mGQ73j_jCh3-e3DhKhdXLGtsMXdAHXTC4Mo0jkOyRRlgs4C2DYRb7d-o4GuVAhex-bsTW92KIqZvIEOF9bNjjVv_rvWZINsAEnikYFbUGDWnKNTUFdiQo6MQg7EulWLMYyPHwwRq1Qmu_LDtuQ1CLqpbcvdZHW4W7BhU7x-S6FRpdivG6sA8Hf8zyGukt2l8)! [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~167~~ ~~148~~ ~~145~~ 144 bytes ``` {("\n"/(" "/'(" "/''$(729>#,//){x,,(3+*1?7){l:3+*1?7;x,,`$(-#:'w)?'w:(,/'+l?'0 7 14_c),'(l?7)?\:c:"aeimnoubcdgkptfhlrsvz"}/()}/()),''".")),"\n"} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwlTtsKgkAUfPcrlqNwzubWagXSCdoPyciyrGiz6Ka0+O+t+DAXhhmYih1BXoMmEKBxYIxcNl2sQqV127lWKZrFo9Rk0lke3NKHRUTjkLGRBhsmpTG2BhORiXS+LaVCsn5hci4ZdsfLrb5/9uXhdH28q7N9vr4/6DTJHr6LMAGv/ZMuCAqRsKjWmz/JmyfR) Stitches together a random character of each type, appending an additional 0-6 random characters to form words of length 3-9, which are then shuffled. Sentences are formed from 3-9 of these words, and paragraphs from 3-9 of those sentences. Paragraphs are iteratively appended, with the essay being complete when it contains at least 729 words. Since a valid paragraph can only contain up to 81 words (9 words per sentence \* 9 sentences), it's safe to write another paragraph as long as the essay contains less than 729 words. However, proofreading the essay to ensure there is no contiguous word repetition is an exercise left to the reader. ``` {("\n"/ /join each paragraph with a newline (" "/' /join sentences in a paragraph with a space (" "/''$ /join words in a sentence with a space (converting words from symbols to strings) (729>#,//){ /while the essay contains less than 729 words... x,, /append another paragraph of... (3+*1?7){ /3 to 9 (randomly chosen) sentences each containing... l:3+*1?7; /3 to 9 (randomly chosen) words x,,`$ /append the new sentence (casted to symbols), which is made of l words, each being a... (-#:'w)?' /randomly shuffled string of... w:(,/'+l?'0 7 14_c) /a random character from each character type in the Martian alphabet ,' /concatenated with... (l?7)?\:c:"aeimnoubcdgkptfhlrsvz" /0 to 6 random characters from the Martian alphabet }/() }/() ) ,''"." /finish each sentence with a period ) ) ,"\n" /finish the essay with a newline } ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 26 bytes ``` 'h,97>e!". "{9/Sf*Uf+}fU9< ``` [Try it online!](https://tio.run/##S85KzP3/Xz1Dx9LcLlVRSY9LqdpSPzhNKzRNuzYt1NLm/38A "CJam – Try It Online") First solution in a while where I've had to use a literal newline. Same idea as the 05AB1E answer. *sigh* And if only concatenation was commutative... ]
[Question] [ > > **NOTICE:** This challenge is now closed: I will no longer be updating the leaderboard and will not change the accepted answer. However, you are free to run the controller and update the leaderboard yourself, if you wish. > > > ## [Join the chat!](https://chat.stackexchange.com/rooms/81067/the-break-room) ## Introduction Good evening, traders! You are all traders for the golfing company PPCG. Your task is to make as much money as possible. ## Challenge Write a program that buys and sells shares on the Stack Exchange Stock Exchange with the aim of making as much money as possible. ## Gameplay All players will start with 5 shares and $100 in their bank. The game always starts with a share price of $10. Each game will have 1000 rounds where the first round is round `1`. In each round, your program will be supplied four arguments as input: the current share price, the number of shares you hold, the amount of money you own and the round number (1-indexed). For example, if my program is `test1.py`, the share price is `100`, the number of shares I hold is `3`, the amount of money I have is `1200`, and the round number is `576`, my program will be run like so: ``` python test1.py 100 3 1200 576 ``` In a round, the share price given to each player will be the same. This doesn't change until the end of the round. In response, the player must print their command. There are two options: * Buy shares: This command is given as `bn` where `n` is the number of shares you wish to buy. For example, if you want to buy 100 shares, you would output: ``` b100 ``` When buying shares, you are allowed an overdraft of up to $1000. If you try to buy enough shares that exceed this overdraft (your bank balance goes below $-1000), you will be declared bankrupt. This means that you will lose all of your shares and your balance will be set to $50. The share price will be unaffected by your command if you go bankrupt. (If your balance is $-1000, you are not bankrupt. However if your balance is $-1001, you are bankrupt) * Sell shares: This command is given as `sn` where `n` is the number of shares you wish to sell. For example, if you want to sell 100 shares, you would output: ``` s100 ``` You may not sell more shares than you own. If you try to do this, your request will be denied, and you will skip the round. If you want to skip the round and do nothing, output either `b0` or `s0`. Your request will be denied if you try to buy or sell a negative number of shares and/or a non-integer number of shares. After 5 rounds, at the end of each round, all players will be payed a dividend, the value of which is 5% of the mean average share price of the last 5 rounds. ## How does it work? Initially the share price will be $10. At the end of each round, it will be recalculated using the formula: $$\text{New Share Price} = \text{Old Share Price} + (\text{Number of shares bought}-\text{Number of shares sold})$$ The share price will be limited so that it never falls below $1. To prevent overly rapid change, the change in share price is limited to a maximum of \$\pm$200\$. ## Rules * Your program must have a name * Your program is allowed a single text file for data storage. It must be stored in the same folder as your program * Include in your answer details of how to run your program * This KotH is open to all programming languages that are free-to-use and can be run on Windows 10 * Your score is based solely on the contents of your balance. Any money locked up in shares will not be counted * You may edit your program at any time. Before each game, the latest code will be saved and compiled * You should not write code which specifically targets another bot. ## Controller The controller is written in Python and can be found here: <https://gist.github.com/beta-decay/a6abe40fc9f4ff6cac443395377ec31f> At the end it will print a leaderboard and display a graph of how the share price changed throughout the game. For example, when two random bots were playing ![](https://i.stack.imgur.com/irSp0.png) ## Winning The player with the highest amount of money in their balance at the end of the last game wins. ## Leaderboard **Game 4: 16:14 10/08/2018** ``` Name Balance Experienced Greedy Idiot $14802860126910608746226775271608441476740220190868405578697473058787503167301288688412912141064764060957801420415934984247914753474481204843420999117641289792179203440895025689047561483400211597324662824868794009792985857917296068788434607950379253177065699908166901854516163240207641611196996217004494096517064741782361827125867827455285639964058498121173062045074772914323311612234964464095317202678432969866099864014974786854889944224928268964434751475446606732939913688961295787813863551384458839364617299883106342420461998689419913505735314365685264187374513996061826694192786379011458348988554845036604940421113739997490412464158065355335378462589602228039730 Equalizer $763185511031294813246284506179317396432985772155750823910419030867990447973211564091988995290789610193513321528772412563772470011147066425321453744308521967943712734185479563642323459564466177543928912648398244481744861744565800383179966018254551412512770699653538211331184147038781605464336206279313836606330 Percentage Trader $448397954167281544772103458977846133762031629256561243713673243996259286459758487106045850187688160858986472490834559645508673466589151486119551222357206708156491069820990603783876340193236064700332082781080188011584263709364962735827741094223755467455209136453381715027369221484319039100339776026752813930 OYAIB $8935960891618546760585096898089377896156886097652629690033599419878768424984255852521421137695754769495085398921618469764914237729576710889307470954692315601571866328742408488796145771039574397444873926883379666840494456194839899502761180282430561362538663182006432392949099112239702124912922930 Chimps on a Typewriter $176504338999287847159247017725770908273849738720252130115528568718490320252556133502528055177870 Greedy B*****d $17689013777381240 Illiterate Dividend Investor $2367418699671980 Lucky Number 6 $4382725536910 Lone Accountant $90954970320 Buy/Reinvest $127330 Technical Analysis Robot $126930 Dollar Cost Averager $106130 Fibonacci $69930 Novice Broker $28130 Buy Low $6130 Naive Statistician $6130 Fallacious Gambler $6130 Passive Trader $4980 Half More or Nothing $4920 Monkeys on a Typewriter $66 ``` [**View graphs of each contestant**](https://i.stack.imgur.com/BMe4F.png) --- **[Related](https://codegolf.stackexchange.com/questions/91566/stock-exchange-koth) but the gameplay and winning criterion are very different to this challenge.** [Answer] # Chimps On A Typewriter ``` import random from sys import argv share_price = int(argv[1]) share_count = int(argv[2]) balance = float(argv[3]) x = random.random() if x < 0.5: max_buy = balance / share_price buy_count = int(max_buy * random.random()) print('b' + str(buy_count)) else: sell_count = int(share_count * random.random()) print('s' + str(sell_count)) ``` Chimps are smarter than monkeys, they won't buy stocks they can't afford, or sell stocks they don't have. Still pretty random otherwise though. Run with python3, but should(?) work with python2 as well [Answer] # The Experienced Greedy Idiot PHP, tested on PHP >= 7, should work on previous ones as well. ``` <?php class StickExchange { private $dbFile; private $sharePrice; private $shares; private $balance; private $overdraft; public function __construct($sharePrice, $shares, $balance, $round) { $this->dbFile = __FILE__ . '.txt'; $this->sharePrice = gmp_init($sharePrice); $this->shares = gmp_init($shares); $this->balance = gmp_init($this->parseScientificNotationToInt($balance)); $this->overdraft = gmp_init(1000); $action = 'b'; if ($round == 1) { $this->buy(); } elseif ($round == 1000) { $this->sell(); } else { $content = $this->getDbContent(); $lastPrice = gmp_init($content['price']); $secondLastPrice = gmp_init($content['last_price']); $lastAction = $content['action']; $shareAndLastCmp = gmp_cmp($this->sharePrice, $lastPrice); $lastAndSecondLastCmp = gmp_cmp($lastPrice, $secondLastPrice); if ($shareAndLastCmp > 0 && $lastAndSecondLastCmp > 0) { if ($lastAction == 'b') { $this->sell(); $action = 's'; } else { $this->buy(); } } elseif ($shareAndLastCmp < 0 && $lastAndSecondLastCmp < 0) { if ($lastAction == 'b') { $this->sell(); $action = 's'; } else { $this->skip(); } } elseif ($shareAndLastCmp > 0) { $this->sell(); $action = 's'; } elseif ($shareAndLastCmp < 0) { $this->buy(); } else { $this->skip(); } } $this->setDbContent([ 'action' => $action, 'price' => gmp_strval($this->sharePrice), 'last_price' => isset($lastPrice) ? gmp_strval($lastPrice) : '0', ]); } private function parseScientificNotationToInt($number) { if (strpos($number, 'e+') !== false) { $sParts = explode('e', $number); $parts = explode('.', $sParts[0]); $exp = (int)$sParts[1]; if (count($parts) > 1) { $number = $parts[0] . $parts[1]; $exp -= strlen($parts[1]); } else { $number = $parts[0]; } $number = gmp_init($number); $pow = gmp_pow(gmp_init(10), $exp); return gmp_strval(gmp_mul($number, $pow)); } elseif (strpos($number, 'e-') !== false) { return sprintf('%d', $number); } else { $parts = explode('.', $number); return $parts[0]; } } private function getDbContent() { return unserialize(file_get_contents($this->dbFile)); } private function setDbContent($content) { file_put_contents($this->dbFile, serialize($content)); } private function buy() { $realBalance = gmp_add($this->balance, $this->overdraft); $sharesToBuy = gmp_div($realBalance, $this->sharePrice); $this->stdout('b' . gmp_strval($sharesToBuy)); } private function sell() { $this->stdout('s' . gmp_strval($this->shares)); } private function skip() { $this->stdout('b0'); } private function stdout($string) { $stdout = fopen('php://stdout', 'w'); fputs($stdout, $string); fclose($stdout); } } new StickExchange($argv[1], $argv[2], $argv[3], $argv[4]); ``` An updated version of "The Greedy Idiot" with re-structured behavior and bug fixes related to working with huge numbers. ### Notes: * Save in a file and run it like this: `php C:\path\path\stack_exchange.php 10 5 100 1` * This script creates a text file with same name as the script file and a `.txt` appended to the end. So please run with an user with appropriate write permission on the script path. * A simple how to install PHP 7.2 on windows: <http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/> * To work with super huge numbers, I had to use [GMP](http://php.net/manual/en/book.gmp.php), so these two lines on `php.ini` should be un-commented (the semi-colon at start of line should be removed, if it isn't already): + `; extension_dir = "ext"` + `;extension=gmp` [Answer] # OYAIB ``` from sys import argv share_price = float(argv[1]) shares = int(argv[2]) cash = float(argv[3]) cur_round = int(argv[4]) tot_rounds = 1000.0 investments = shares * share_price total_assets = investments + cash target_cash = round(cur_round / tot_rounds * total_assets) if target_cash > cash: shares_to_sell = min(shares, round((target_cash - cash) / share_price)) print('s%d' % shares_to_sell) else: shares_to_buy = round((cash - target_cash) / share_price) print('b%d' % shares_to_buy) ``` Following the old saying of "own your age in bonds," this program tries to do the same. This way we aren't subject to market volatility at the end-game. **Edit:** Looking at the controller it shows that we can only buy/sell full shares, but can have a fractional account balance. [Answer] # Lone Accountant `buy-sell.py`: ``` from sys import argv Price = int(argv[1]) Shares = int(argv[2]) Balance = float(argv[3]) Round = int(argv[4]) if Round % 2 == 0: print('s' + str(Shares)) if Round % 2 == 1: print('b' + str(int((Balance + 1000) / Price))) ``` Doesn't store anything in `buy-sell.txt`. In odd rounds, it buys as many shares as it can. In even rounds, it sells all of its shares. The intent is to first raise the share price by buying as many shares as possible, and then sell those shares to get more money. It works because the final round is even (round 1000). Even though the share price will remain the same (`5`) after each pair of rounds (assuming the bot is alone, therefore ***Lone* Accountant**), the bot's balance increases, since the selling price is higher than the buying price, and more balance leads to the ability of buying more shares. It's a vicious cycle, but in a good way (for me). The major vulnerability comes with evil bots playing alongside, selling in order to lower the share price (not sure if it's good for them either). In this case, the bot may remain with a balance of $-890, provided there are enough evil bots. This accountant really wants their peace of mind. ;-) [Answer] # The Passive Trader ``` from sys import argv share_price = int(argv[1]) balance = float(argv[3]) round_num = int(argv[4]) if round_num == 1: print('b%s' % str(int(balance / share_price))) else: print('b0') ``` This guy isn't big on this whole "Stocks" thing, but he heard that if he just spends a little money now, he'll get little bits of money over time that'll add up to more than he spent. He'll buy enough stocks to go to $0 (no overdraft for this fella, he's not gunna put himself in debt for a little profit), then sit around letting the dividends build Run with python3, but should(?) work with python2 as well. [Answer] # The Naïve Statistician Made for Python 3, might work in Python 2 ``` from sys import argv from math import floor # Save an entry to the stock history def save_history(price): with open('stockhistory.txt', 'a') as f: f.write(str(price) + '\n') # Load the stock history def load_history(): with open('stockhistory.txt', 'r') as f: return [float(line.strip()) for line in f] # Calculate average price rise/fall streak length def average_streak(history, condition): streaks = [] current_streak = 0 last_price = history[0] for price in history[1:]: if condition(last_price, price): current_streak += 1 elif current_streak: streaks += [current_streak] current_streak = 0 last_price = price if current_streak: streaks += [current_streak] return sum(streaks) / len(streaks) if streaks else None # Calculate the current streak length def current_streak(history, condition): streak = 0 while streak < len(history) - 1 and condition(history[-streak - 2], history[-streak - 1]): streak += 1 return streak def run(share_price, share_count, balance, round_number): save_history(share_price) # Sell all shares if it is the last round if round_number == 1000: print('s' + str(int(share_count))) return # Buy as many shares as possible if the price is down to one, as there's # nothing to lose if share_price == 1: buy_count = int(balance + 1000) print('b' + str(buy_count)) return history = load_history() # Calculate the average and current rise/fall streaks average_rise = average_streak(history, lambda a, b: a <= b) current_rise = current_streak(history, lambda a, b: a <= b) average_fall = average_streak(history, lambda a, b: a >= b) current_fall = current_streak(history, lambda a, b: a >= b) # Do nothing if there's no analyzed data if not average_fall or not average_rise: print('b0') return # Buy shares if the current rise streak is as long as or longer than average if current_rise > current_fall and current_rise >= average_rise: buy_count = (balance + 1000) / share_price print('b' + str(int(buy_count))) return # Sell shares if the current fall streak is as long as or longer than average if current_fall > current_rise and current_fall >= average_fall: print('s' + str(int(share_count))) return # Otherwise, do nothing print('b0') run(*map(float, argv[1:])) ``` This is a naïve statistician that tries to predict stock prices by only buying/selling if the price has risen/fallen for longer than usual, while also buying stocks if the price is down to one and selling all stocks on the last round. [Answer] # Percentage Trader Python3 (maybe works in python2) ``` import sys args=sys.argv price=int(args[1]) held=int(args[2]) money=int(args[3]) roundNum=int(args[4]) prevPrice=0 if roundNum==1: print("b"+str((money+1000)//price)) else: if roundNum==1000: print("s"+str(held)) else: with open("percentageTrader.dat","r") as f: prevPrice=int(f.read()) if(price>prevPrice): toSell=int(held*int(1000000*(price-prevPrice))/(price))//1000000 print("s"+str(toSell)) if(price<prevPrice): toBuy=int(((money+1000)//price)*int(1000000*(prevPrice-price))//(prevPrice))//1000000 print("b"+str(toBuy)) if(price==prevPrice): print("b0") with open("percentageTrader.dat","w") as f: f.write(str(price)) ``` ### Instructions on running * Save as filename.py * Run with python filename.py price #shares balance round# ### How it works * First round the bot purchases as many shares as it can afford. * If the price increases, the bot sells a percentage of shares equal to the percentage increase in price(calculated from new value) * If the price decreases, the bot buys a percentage of the maximum shares it could buy equal to the percentage decrease in price(calculated from previous value) * Sells off everything at round 1000 Changes should hopefully remove the problems caused by floating point division [Answer] # Equalizer ``` from sys import argv p, n, b, r = map(int, argv[1:]) c = p*n print "bs"[(c+b)/2>b] + str(int(abs(((c-b)/2)/p))) if r < 999.5 else "s" + str(int(n)) ``` Partitions its financial resources equally between cash and stocks on every round except the last. I believe this strategy to be a mathematically sound way of making at least *some* money, but I may be proven wrong. There may or not be bugs that I haven't caught. Also golfed somewhat. [Answer] # Monkeys On A Typewriter ``` import random cmd = ['b', 's'][int(random.random() * 2)] num = str(int(random.random() * 1000000)) print("%s%s" % (cmd, num)) ``` It's a bunch of monkeys on typewriters. Randomly sells or buys X stocks, where: `0 <= X <= 1,000,000` Run with python3, but should(?) work with python2 as well [Answer] # Buy Low (Python 2 or 3) ``` import random def run(price, shares, balance, round_): # We get no value from our leftover shares at the end, so sell them all. if round_ == 1000: print('s' + str(int(shares))) return # If the price is low enough, buy everything we can. if price <= 20 + round_ * 60: print('b' + str((balance + 1000) // price)) return # If we have no shares, wait for the price to drop. if shares == 0: print('b0') return # Sometimes sell shares so we can buy if the price gets low again. if random.random() < 0.4: print('s1') return # Otherwise, just wait for a better price. print('b0') if __name__ == '__main__': import sys run(*[float(x) for x in sys.argv[1:]]) ``` [Answer] # Fallacious Gambler (Python 2 or 3) ``` import random def run(price, shares, balance, round_): # We get no value from our leftover shares at the end, so sell them all. if round_ == 1000: print('s' + str(int(shares))) return # For the first round, just watch. if round_ == 1: with open('fg.txt', 'w') as f: f.write('1 0 10') print('b0') return # Get the state. with open('fg.txt') as f: direction, streak, previous = map(int, f.read().strip().split()) change = price - previous # If the market isn't moving, wait for it to get hot again. if change == 0: print('b0') return # Keep track of the market direction. if (change > 0) == (direction > 0): streak += 1 else: streak = 0 direction *= -1 # If the market's been going one way for too long, it has to switch, right? if streak > 5: if direction > 0: print('s' + str(shares // 2)) else: print('b' + str((balance + 1000) // price // 2)) # Otherwise, the market's too volatile. else: print('b0') # Save the state. with open('fg.txt', 'w') as f: f.write('%d %d %d' % (direction, streak, price)) if __name__ == '__main__': import sys run(*[float(x) for x in sys.argv[1:]]) ``` [Answer] # The Dollar Cost Averager (tested with Python 3.7) First post in codegolf so tell me if I did something wrong. The basic idea is to buy one share each round if that's possible and sell all shares at the end. ``` from sys import argv share_price = int(argv[1]) share_count = int(argv[2]) balance = float(argv[3]) round = int(argv[4]) if round < 1000: if balance > share_price-1000: print("b1") else: print("b0") else: print("s" + str(share_count)) ``` [Answer] # The (Dyalog) APL Farmer ``` r←apl_stock_farmer args round←¯1↑args :If 1=round (buyPrice sellPrice)←10 0 bought←1 (currPrice shares balance)←3↑args r←'b10' :ElseIf 1000=round r←'s',⍕shares :Else (currPrice shares balance)←3↑args :If (currPrice>buyPrice)∧bought bought←0 sellPrice←currPrice r←'s',⍕shares :ElseIf (currPrice<sellPrice)∧~bought bought←1 buyPrice←currPrice r←'b',⍕⌊(1000+balance)÷currPrice :Else r←'b0' :End :End ``` A TradFn which buys every possible share on the first round, and only sells when the current price of the shares is higher than the price they were bought for. After selling, the bot will only buy shares that are cheaper than the price it last sold shares for. That's because the farmer's accountant told him that's how you do stock trading. "Buy low, sell high" and all that stuff. ### Disclaimer This is my first attempt at a KotH challenge, and since I basically only do APL here, I decided to go on with it. That said, I'm not completely sure if this will be able to be run alongside the other bots, since it's a Tradfn and can't be fed directly into a CMD/Bash shell. So, to run this in Bash, you need the following command: `$ echo apl_stock_farmer args | dyalog 'stock_exchange.dws' -script` Where: `apl_stock_farmer` is the name of the function, which is in the first line of code. `args` is a vector of space separated arguments (in the first round, it would be `10 5 100 1`). `dyalog` is the path to the Dyalog executable `'stock_exchange.dws'` is the name (or path, if the file is not in the same directory the shell has open) of the workspace that contains the function. That workspace file can be obtained by opening a clear workspace, typing `)ed apl_stock_farmer`, pasting the code above and then doing a `)save <path>`. I can also provide this workspace file if that would be easier. `-script` is just an argument that makes dyalog execute the given code and print to stdout without actually opening the REPL. Unfortunately, I haven't found a way to make it work with the Windows CMD or Powershell, so I ran it using Git Bash. I'm not sure how feasible it is to put this bot on the competition, but I like this code way too much not to post it. [Answer] # Illiterate Dividend Investor ``` import random from sys import argv price = float(argv[1]) shares = int(argv[2]) cash = float(argv[3]) round = int(argv[4]) # buy 1st round, sell last round if round == 1: print('b' + str(int((cash + 1000) / price))) elif round == 1000: print('s' + str(shares)) # round right before dividend: sell elif round % 5 == 4: print('s' + str(shares)) # 1 round after dividend: buy elif round % 5 == 0: print('b' + str(int((cash + 1000) / price))) # 2 rounds after dividend: 50/50 sell/try to buy elif round % 5 == 1: if random.random() < 0.5: print('s' + str(shares)) else: print('b' + str(int((cash + 1000) / price))) # 3 rounds after dividend: sell if own shares (didn't sell last round), else buy elif round % 5 == 2: if shares > 0: print('s' + str(shares)) else: print('b' + str(int((cash + 1000) / price))) # otherwise, 4 rounds after dividend, buy else: print('b' + str(int((cash + 1000) / price))) ``` Assumes after dividends, people have more cash, so they will be more likely to buy. Sells right before dividends, buys right after. Goes through one other sell/buy cycle in the other 3 rounds. [Answer] # Novice Broker (but gets the basic idea) `se_stock_exchange.rb`: ``` DATA_FILE = $0.sub /\.rb$/, ".data" NUM_ROUNDS = 1000 share_price, num_shares, money, round = ARGV.map &:to_i order = "s0" if round == NUM_ROUNDS puts "s#{num_shares}" exit end if File.exists? DATA_FILE last_price, trend, bought_price = File.read(DATA_FILE).lines.map &:to_i else last_price = 0 trend = -1 bought_price = 0 end if (new_trend = share_price <=> last_price) != trend case trend when -1 order = "b#{(money + 1000) / share_price}" bought_price = [bought_price, share_price].max when 1 if share_price > bought_price order = "s#{num_shares}" bought_price = 0 end end trend = new_trend end File.open(DATA_FILE, "w") { |f| f.puts share_price, trend, bought_price } puts order ``` Waits until the price turns around, then buys/sells everything. I mean, that's what it says to do in *Day Trading for Dummies* Note: this is probably a real book, and that's probably something someone might get from it. Saves data in `se_stock_exchange.data`. Run with `ruby se_stock_exchange.rb ${SHARE_PRICE} ${SHARES} ${MONEY} ${ROUND}` (substituting the appropriate values). [Answer] # Half More or Nothing ``` def run(price, shares, balance, cur_round): if cur_round==1000: print('s'+str(int(shares))) return if cur_round==1: with open('HalfMoreOrNothing.dat', 'w') as f: f.write(str(int(price))) print('b'+str(int((balance+1000)/price))) return if shares==0: with open('HalfMoreOrNothing.dat', 'w') as f: f.write(str(int(price))) print('b'+str(int((balance+1000)/price))) return with open('HalfMoreOrNothing.dat', 'r') as f: bought_price=int(f.read()) if price>=bought_price*1.5: print('s'+str(int(shares))) return print('b0') if __name__ == '__main__': import sys run(*[float(x) for x in sys.argv[1:]]) ``` I rarely use Python, let me know if this generates an error somewhere. The strategy is to wait until the share price is at least 50% bigger than the price at the moment of bying them, then sell them, then immediately buy new shares so it can wait for the new share price raise. Hopefully, ~~people~~ chimps won't start to sell shares near the end... (it seems that most bots just wait for the right moment, whatever that is) [Answer] ## Buy/Reinvest as much as possible! Similar to my Dollar-Cost Averager that did, surprisingly, quite average, this buys each round as many shares as are affordable and only sells them in the last round. ``` from sys import argv share_price = int(argv[1]) share_count = int(argv[2]) balance = float(argv[3]) round = int(argv[4]) if round < 1000: if balance > share_price-1000: buy_count = int((balance+1000)/share_price) print("b"+str(buy_count)) else: print("b0") else: print("s" + str(share_count)) ``` [Answer] # Fibonacci I've rewritten this in Python 3 to make things easier. Hopefully! ``` import math from sys import argv price = float(argv[1]) shares = int(argv[2]) balance = float(argv[3]) roundNum = int(argv[4]) fibonacci = [2,3,5,8,13,21,34,55,89,144,233,377,610,987] if (roundNum == 1): buy = int((balance+1000)/price) print('b' + str(buy)) elif (roundNum in fibonacci) and roundNum % 2 == 1 and balance > 0: buy = int((balance/price)/2) print('b' + str(buy)) elif ((roundNum in fibonacci) and roundNum % 2 == 0) or roundNum % 100 == 0: if (roundNum == 1000): sell = shares print('s' + str(sell)) else: sell = math.ceil(shares/2) print('s' + str(sell)) else: print('b0') ``` It buys half the maximum amount of shares that is affordable when the round is equal to an odd Fibonacci number and sells half of the available shares when the round is equal to an even Fibonacci number and also every 100 rounds. Sells all shares on round 1000. Otherwise, it just waits. Only buys shares when balance is positive. [Answer] ## Technical Analysis Robot I study business economics so I tried to realize the simpliest method for analizing a stock market (the technical analysis). According to the theory you just have to analyze all the minimums of the graph to see if there is a trend (up ord down). During an up trend you have to buy and during a down trend you have to sell. I don't think that this method will work too well but let's give it a try :) ``` import sys from sys import argv share_price = int(argv[1]) share_number = int(argv[2]) bank_account = float(argv[3]) round_number = int(argv[4]) max_buy_greedily = (1000 + bank_account) / share_price minima = [] def log(): f = open("log_technical_analysis.txt","a+") f.write("%d;" % share_price) def analyze(): f = open("log_technical_analysis.txt","r+") line = f.readline() values = line.split(";") values.pop() for i in range(len(values) - 1): if i > 0 and int(values[i-1]) > int(values[i]) and int(values[i+1]) > int(values[i]): minima.append(int(values[i])) if len(minima) >= 3 and minima[len(minima) - 1] > minima[len(minima) - 2] and minima[len(minima) - 2] > minima[len(minima) - 3]: print('b' + str(int(max_buy_greedily))) elif len(minima) >= 3 and minima[len(minima) - 1] < minima[len(minima) - 2] and minima[len(minima) - 2] < minima[len(minima) - 3]: print('s' + str(share_number)) else: print('b0') if round_number >= 994: print('s' + str(share_number)) sys.exit(0) if share_price <= 15: print('b' + str(int(max_buy_greedily))) log() sys.exit(0) log() analyze() sys.exit(0) ``` Tested with python3 [Answer] **Greedy B\*\*\*\*\*d** ``` # Gready one... from sys import argv SMA_PERIOD = 5 LAST_BUY_DAY = 985 LAST_SELL_DAY = 993 # Save an entry to the stock history def save_history(price): with open('db.txt', 'a') as f: f.write(str(price) + '\n') # Load the stock history def load_history(): with open('db.txt', 'r') as f: return [float(line.strip()) for line in f] def get_sma(d, n): l = d[-n:] return int(sum(l) / len(l)) def buy(price, account): if account + 1000 > 0: print 'b' + str(int((account + 1000) / price)) return print 'b0' def sell(holdings): print 's'+ str(int(holdings)) def run(price, holdings, account, day): save_history(price) d = load_history() if price <= get_sma(d, SMA_PERIOD) and day < LAST_BUY_DAY: return buy(price, account) if price > get_sma(d, SMA_PERIOD): return sell(holdings) if day >= LAST_SELL_DAY: return sell(holdings) # Otherwise, do nothing print 'b0' run(*map(float, argv[1:])) ``` He will go all in when its cheap and sell it all once the price goes up... [Answer] ## Lucky Number 6 EDIT: Oh ffs, I think me not converting the selling count to int was one of my problems, well here we go again. Probably my last contribution, unless I'm bored at work and make something a bit more sophisticated, but I fell like the sophisticated bots already fill the niches. This guy basically sells some of his shares every 6 rounds, because hey 6 is his lucky number. ``` from sys import argv import random share_price = int(argv[1]) share_count = int(argv[2]) balance = float(argv[3]) round = int(argv[4]) x = random.uniform(1,2) if round == 1 or round == 1000: print("s"+str(share_count)) elif round % 6 == 0 and share_price >= 10: sell = int(share_count/x) print("s"+str(sell)) elif balance > share_price-1000: buy_count = int((balance+1000)/share_price) print("b"+str(buy_count)) else: print("b0") ``` ]
[Question] [ In [xkcd 1047](https://xkcd.com/1047/), Randall Munroe lists "slightly wrong" approximations of assorted quantities and numbers with varying precision and complexity, such as that the number of liters in a gallon is very close to 3 + π⁄4. In the middle of the comic, he gives an intermission: a way to estimate the world (and United States) population based for a given year. [![World and U.S. population formula, described below](https://i.stack.imgur.com/DvmsW.png)](https://xkcd.com/1047/) (Cropped from [xkcd: Approximations](https://xkcd.com/1047/) by Randall Munroe) Your task is to write a program that implements these formulas to approximate the current world and U.S. populations, replicated as follows. ## World population 1. Take the last two digits of the current year. 2. Subtract the number of leap years (including the current year) since [Hurricane Katrina](https://en.wikipedia.org/wiki/Hurricane_Katrina) (2005). For these purposes, any year divisible by 4 is considered a leap year. 3. Add a decimal point between the two numbers (the same as dividing by 10). 4. Add 6. This gives the result in billions of people. ## U.S. population 1. Take the last two digits of the current year. 2. Subtract 10. 3. Multiply by 3. 4. Add 10. 5. Add 3 to the beginning (for this challenge, some numbers will be negative, so add 300 instead). Somehow I didn't notice that just concatenating wouldn't work because the program I used to generate the results just added 300. 6. This gives the result in millions of people. # Details This formula "should stay current for a decade or two," but you must be able to theoretically handle any year 2000–2039 inclusive. For some cases, the leap years since Katrina will have a negative or zero value. You are free to simplify the formula in any way, as long as all outputs match the ones below. **For the year, use the year according to the computer's clock.** It must work next year and any other year this century, so you cannot simply hardcode 2015. For convenience, you might want to include a way to specify the year as a variable or input to test other years. The output should be the approximated world population (in billions of people), followed by some delimiter (e.g. space or comma), followed by the U.S. population (in millions of people). You may also write a function that returns or prints a string or an array of numbers or strings. This is code golf, so shortest code in bytes wins. Tiebreaker is earliest post. # Test cases This is a list of all possible years, followed by the two outputs. ``` Year World U.S. 2000 6.1 280 2001 6.2 283 2002 6.3 286 2003 6.4 289 2004 6.4 292 2005 6.5 295 2006 6.6 298 2007 6.7 301 2008 6.7 304 2009 6.8 307 2010 6.9 310 2011 7 313 2012 7 316 2013 7.1 319 2014 7.2 322 2015 7.3 325 2016 7.3 328 2017 7.4 331 2018 7.5 334 2019 7.6 337 2020 7.6 340 2021 7.7 343 2022 7.8 346 2023 7.9 349 2024 7.9 352 2025 8 355 2026 8.1 358 2027 8.2 361 2028 8.2 364 2029 8.3 367 2030 8.4 370 2031 8.5 373 2032 8.5 376 2033 8.6 379 2034 8.7 382 2035 8.8 385 2036 8.8 388 2037 8.9 391 2038 9 394 2039 9.1 397 ``` [Answer] # Pyth, ~~21~~ 20 bytes *-1 byte by Dennis* ``` c/J-*3.d3C\ᙹ4T+33J ``` These have the same byte count but are ASCII-only: ``` c/J%*3.d3 523 4T+33J c/-J%*3.d3*44T33 4TJ ``` I don't know Pyth, so still ~~probably~~ possibly golfable. Using the same algorithm: # TI-BASIC, 23 bytes ``` max(3getDate-5753 {.1int(Ans/4),Ans+33 ``` `getDate` returns a list of three floats `{YYYY,MM,DD}` in some order depending on the date format setting (TI-84s don't have a true int datatype); the `max(` will be the year. Multiplying and subtracting inside the `max(` saves a close-paren. [Answer] # Javascript (ES6), ~~55~~ ~~54~~ 48 bytes ``` -~((n=Date().substr(13,2)*3+280)/4-9.1)/10+' '+n ``` Works in Firefox 33; theoretically supports all years from 2000 to 2099. If programs that dump the result onto the console are not allowed, use this 51-byte function: ``` (n=Date().substr(13,2)*3+280)=>-~(n/4-9.1)/10+' '+n ``` Full program, 55 bytes: ``` n=Date().substr(13,2)*3+280,alert(-~(n/4-9.1)/10+' '+n) ``` ~~Getting the year was quite expensive, but after using the deprecated `getYear()` instead of `getFullYear()`, all of the numbers in the equation became smaller, saving a lot of bytes.~~ **EDIT:** Thanks to an eeevil trick, I skipped `new` and `getYear()` altogether. >:D Suggestions welcome! [Answer] # Pyth, 30 bytes ``` .R+*.075J%.d3C\d6.105 1+*3J280 ``` My first Pyth program! Thanks @Jakube for some hints (I would never have thought of those!) [Answer] # Python 2, 80 bytes ``` from datetime import* y=date.today().year%40 print int(61.55+.75*y)/10.,y*3+280 ``` Now rounds! [Answer] # CJam, 28 bytes ``` et0=100%__4/(-Ad/6+S@3*280+ ``` [Try it online](http://cjam.aditsu.net/#code=et0%3D100%25__4%2F(-Ad%2F6%2BS%403*280%2B%0A) To try years other than the current one, replace the `et0=` at the start with the literal value of the year. [Answer] # Python 3, 134 bytes Works well but seems a bit long ``` from datetime import* y=str(date.today().year) z=int(y[2:]) m=str(60+(z-int((int(y)-2005)/4))) print("%s.%s"%(m[0],m[1]),310+(z-10)*3) ``` [Answer] ## AutoIt - ~~60~~ ~~58~~ 56 bytes ``` $_=@YEAR-2e3 ClipPut(($_-Int($_/4-1))/10+6&' 3'&3*$_-20) ``` ~~The rounding eats bytes~~ (not anymore). I have now tweaked both formulas. Some sample outputs: ``` 7.3 325 // 2015 7.3 328 7.4 331 7.5 334 // 2018 8.4 370 // 2030 ``` They all seem to be accurate. A tip: Order of execution saves bytes on parentheses. For example: `(a-4)/4 = a/4-1` :-). [Answer] # PowerShell, ~~53~~ 45 Bytes ``` $n=date -f yy;.1*[int](61.45+.75*$n);280+3*$n ``` Uses a similar rounding trick as muddyfish's [Python 2 answer](https://codegolf.stackexchange.com/a/57805/42963) to simplify the world population calculation, since PowerShell implicitly `Round()`s when you cast from a `[double]` to an `[int]`, rather than truncating. For the output, we assume that *"followed by some delimiter (e.g. space or comma)"* can also mean "newline", so we execute one result and then the second. PowerShell implicitly writes out results, so we don't need to explicitly call any printing commands. [Answer] # Mathematica, 50 bytes ``` n=Today["YearShort"];{.1*(61+n-Floor[n/4]),280+3n} ``` Note that this is dependent on having a Wolfram Engine with Version number 10+ (released 2014) due to dependence on `DateObjects`. # R, 64 bytes ``` n=as.numeric(format(Sys.time(),"%y")) c(.1*(61+n-n%/%4),280+3*n) ``` Direct port of Mathematica code, think I had a shorter solution but dependent on packages whereas this works with base R. [Answer] # Java, ~~180~~ ~~177~~ ~~166~~ ~~152~~ 143 bytes Thanks Thomas for helping a noob out :) ``` class D{public static void main(String[]a){int f=java.time.LocalDate.now().getYear();System.out.printf("%.1f %d\n",(3.*f-5755)/40,3*f-5720);}} ``` Ungolfed version: ``` class D { public static void main(String[]a) { int f = java.time.LocalDate.now().getYear(); System.out.printf("%.1f %d\n",(3.*f-5755)/40,3*f-5720); } } ``` Requires Java 8. [Answer] # JavaScript (ES6) 52 A function returning the output as an array. ``` (y=(new Date).getYear())=>[(y+~(y/4)-13)/10,y*3-20] ``` Just for testing purpose, the function accepts an input equals to current year - 1900 (e.g. 105 for 2015) That's in the line of the ETHproductions' answer (the math is the math) but avoding the *evil trick* it is more portable in different locales. And as a function it's 1 byte shorter. Test snippet: ``` f=(y=(new Date).getYear())=>[(y+~(y/4)-13)/10,y*3-20] o=[]; for(a=2000;a<2050;a++)o.push(`<td>${a}</td><td>${f(a-1900)}</td>`); document.write(`<table><tr>${o.join`</tr><tr>`}</tr></table>`) ``` ``` td { text-align:right; font-family:monospace } ``` [Answer] # [Desmos](https://www.desmos.com), 140 Bytes I'm counting a newline to be a signal for a new equation. Folders on the link are just for organization. ## [Golfed](https://www.desmos.com/calculator/akeu4dfoh1), 140 Bytes Click `add slider` when prompted. ``` a=6+.1b-.1c d=280+3b c=\sum_{n=2005}^q\left\{0=\operatorname{mod}\left(n,4\right),0\right\} b=100\left|\operatorname{floor}\left(.01q\right)-.01q\right| ``` # [Ungolfed](https://www.desmos.com/calculator/ryxbwztmvj), 261 Bytes ``` p_{world}=6+\frac{l_{astdig}-l_{eap}}{10} p_{us}=310+3\left(l_{astdig}-10\right) y_{ear}=2039 l_{eap}=\sum _{n=2005}^{y_{ear}}\left\{0=\operatorname{mod}\left(n,4\right),0\right\} l_{astdig}=100\left|\operatorname{floor}\left(\frac{y_{ear}}{100}\right)-\frac{y_{ear}}{100}\right| ``` [Answer] # Ruby, 57 bytes ``` y=Time.now.year%40;puts "#{6+(y-(y-5)/4)*0.1} #{3*y+280}" ``` Unfortunately, `Time.now.year` really costs some characters. [Answer] # Glava, 77 bytes ``` i|f=java.time.LocalDate.now().getYear();F("%.1f %d\n",(3.*f-5755)/40,3*f-5720 ``` A translation of my Java answer. [Answer] # PHP, 45 bytes The code: ``` echo(int)(($x=3*date(y)+247)/4)*.1," ",$x+33; ``` Because `y` (the argument of `date()`) is an undefined constant, PHP triggers a notice (that can be muted) and converts it to a string (as we need); this PHP courtesy allows saving 2 bytes. In order to suppress the notice, the program needs to be run using the `error_reporting=0` runtime directive, like this: ``` $ php -d error_reporting=0 -r 'echo(int)(($x=3*date(y)+247)/4)*.1," ",$x+33;' 7.3 325 ``` ### For testing By replacing the call to `date(y)` with `$argv[1]` (the first command line argument), the program length increases with 1 byte but it can get the year from the command line. The expected argument is the year minus 2000; it also works for negative values (years before 2000) or values greater than 40 (after year 2040). ``` $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 00 6.1 280 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 01 6.2 283 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 02 6.3 286 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 03 6.4 289 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 04 6.4 292 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 15 7.3 325 $ php -r 'echo(int)(($x=3*$argv[1]+247)/4)*.1," ",$x+33;' 39 9.1 397 ``` [Answer] # APL, ~~25~~ ~~23~~ 29 bytes ``` {(10÷⍨⌊⍵÷4),⍵+33}⊃¯5753+3×⎕TS ``` [TryAPL](http://tryapl.org/?a=%7B%2810%F7%u2368%u230A%u2375%F74%29%2C%u2375+33%7D%u2283%AF5753+3%D7%u2395TS&run) Yes, it's 29 *[bytes](https://en.wikipedia.org/wiki/APL_(codepage))*. ]
[Question] [ Numbers that are easy to remember yet theoretically not easily made Your challenge is to make a program/function in any language that generates uniformly random numbers that fit these criteria: 1. **Length** is **5 digits** 2. There are two separate repeated digit pairs 3. One set of repeated digits is at the beginning or end and the digits are next to each other 4. The odd number out is surrounded by the other pair of digits 5. **The two digit pairs and the other number should all be unique** 6. Your program may support numbers with leading zeroes or not, at your discretion. If leading zeroes are supported, they must be included in the output: 06088, not 6088. If leading zeroes are not supported, then numbers like 06088 should not be generated at all. # Test Cases ## Accepted Outputs: ``` 55373 55494 67611 61633 09033 99757 95944 22808 65622 22161 ``` ## Not accepted outputs: ``` 55555 77787 85855 12345 99233 12131 abcde 5033 ``` More acceptable test cases can be found at [this pastebin link](https://pastebin.com/iMgVUTCE). These were made with this python program: ``` import random for i in range(100): if random.randint(0,100) >= 50: #Put pair touching at beginning if true temp = [] #working array temp.append(random.randint(0,9)) #append random digit temp.append(temp[0]) #append the same digit again x = random.randint(0,9) while x == temp[0]: x = random.randint(0,9) temp.append(x) #append another unique digit y = random.randint(0,9) while y == temp[0] or y == temp[2]: y = random.randint(0,9) temp.append(y) #append another unique digit, and the previous unique digit temp.append(x) else: #Put touching pair at end temp = [] #working array temp.append(random.randint(0,9)) #append random digit #While not unique, try again x = random.randint(0,9) while x == temp[0]: x = random.randint(0,9) temp.append(x) #append another unique digit temp.append(temp[0]) #append the same 0th digit again y = random.randint(0,9) while y == temp[0] or y == temp[1]: y = random.randint(0,9) temp.append(y) #append another unique digit twice temp.append(y) tempstr = "" for i in temp: tempstr += str(i) print tempstr ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` žh.r3£ûÁÂ)Ω ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L4MvSLjQ4sP7z7ceLhJ89zK//8B "05AB1E – Try It Online") **Explanation** ``` žh # push "0123456789" .r # random shuffle 3£ # take the first 3 # EX: 152 û # palendromize # EX: 15251 Á # rotate right # EX: 11525 Â) # pair with its reverse # EX: [11525, 52511] Ω # pick one at random ``` [Answer] ## CJam (16 bytes) ``` YmrG*98+ZbA,mrf= ``` [Online demo](http://cjam.aditsu.net/#code=YmrG*98%2BZbA%2Cmrf%3D) Note: I've assumed that by "unique" OP really means "distinct". Also for 16 bytes: ``` 98ZbA,mrf=W2mr#% 98ZbA,mrf=_W%]mR ``` ### Dissection ``` Ymr e# Select a random number from [0 1] G*98+ e# Multiply by 16 and add 98 to get 98 or 114 Zb e# Base conversion in base 3 to get [1 0 1 2 2] or [1 1 0 2 0] A,mr e# Shuffle the numbers from 0 to 9 f= e# Map "select the item at this index" ``` The other variants generate using `[1 0 1 2 2]` and then select either the result or its reverse. [Answer] # [Perl 5](https://www.perl.org/), ~~81~~ ~~63~~ 56 bytes *Cut 7 bytes with inspiration from @DomHastings* Constructing the number from the appropriate pattern. ``` @q{0..9}++;say+(keys%q)[.5>rand?(2,2,0,1,0):(0,1,0,2,2)] ``` [Try it online!](https://tio.run/##K0gtyjH9/9@hsNpAT8@yVlvbujixUlsjO7WyWLVQM1rP1K4oMS/FXsNIx0jHQMdQx0DTSgNMA/lGmrH//yv8yy8oyczPK/6v62uqZ2BoAAA "Perl 5 – Try It Online") --- ## [Perl 5](https://www.perl.org/), 89 bytes Picks random 5 digit numbers until it finds one that meets the criteria. ``` $_=sprintf'%05d',0|rand 1E5until(/(.)\1(.)(.)\2/||/(.)(.)\1(.)\3/)&&$1-$2&$2-$3&$1-$3;say ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRNXdXANEVdx6CmKDEvRcHQ1bQ0ryQzR0NfQ08zxhBIgGgj/ZoafSgbJBZjrK@ppqZiqKtipKZipKtiDGYbWxcnVv7//y@/oCQzP6/4v66vqZ6BoQEA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 80 bytes ``` from random import* a,b,c=sample(range(10),3) print[a,a,b,c,b][::choice((-1,1))] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocSXqJOkk2xYn5hbkpGoA5dJTNQwNNHWMNbkKijLzSqITdcAqdJJio62skjPyM5NTNTR0DXUMNTVj//8HAA "Python 2 – Try It Online") Outputs a list of digits. # [Python 2](https://docs.python.org/2/), 83 bytes ``` from random import* a,b,c=sample('0123456789',3) print(a*2+b+c+b)[::choice((-1,1))] ``` [Try it online!](https://tio.run/##DcVLCoAgFADAfadol@YLUvsKnSRaqBUJ@cHcdHprNhPedHnHcj6jt2WUbv8zNviY6kKCAr080ob7QFVLGe/6YZzmCjguQjQuIVkzoogmCq9C6MsbfSDUUKAYbzl/ "Python 2 – Try It Online") Output is a number. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22 21 20 18~~ 17 bytes ``` (3∨?2)⌽1↓,∘⌽⍨3?10 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OBpIbxo44V9kaaj3r2Gj5qm6zzqGMGkPmod4WxvaHB///pAA "APL (Dyalog Unicode) – Try It Online") If it's acceptable to output the numbers always in the same format, this can be shortened to 12 bytes, either `1⌽1↓,∘⌽⍨3?10` or `3⌽1↓,∘⌽⍨3?10`. Saved a byte by removing the unnecessary `∘`. Saved a byte thanks to H.PWiz, and then 2 more bytes due to their tip. Saved a byte thanks to ngn. The function assumes `⎕IO←0` (**I**ndex **O**rigin). --- ### How? ``` (3∨?2)⌽1↓,∘⌽⍨3?10 ⍝ Anonymous function. 3?10 ⍝ Deal 3 (distinct) random numbers from 0 to 9. (Assume 1 2 3) ⍨ ⍝ Use that as both arguments for: ,∘⌽ ⍝ Rotate (⌽), then concatenate (,). ⍝ Yields 3 2 1 1 2 3. 1↓ ⍝ Drop the first element. Our vector is now 2 1 1 2 3 ⌽ ⍝ Rotate the vector to the left using as argument: ( ?2) ⍝ Roll 0 or 1 and... 3∨ ⍝ Do the GCD between 3 and the result. (3∨0=3; 3∨1=1.) ⍝ This yields either 1 1 2 3 2 or 2 3 2 1 1. ``` [Answer] # Java 8, ~~145~~ ~~136~~ ~~125~~ 119 bytes ``` v->{String r;for(;!(r=(int)(Math.random()*1e5)+"").matches("((.).?\\2){2}")|r.chars().distinct().count()<3;);return r;} ``` -9 bytes thanks to *@OlivierGrégoire.* -11 bytes thanks to *@RickHitchcock*. -6 bytes thanks to *@Nevay*. **Explanation:** [Try it online.](https://tio.run/##fVJNc5swFLz3V7zq0JHqsWKExYep3Vt7Si7N9NL0oMhKIAHhkYSnGde/3ZUxZMYauwwM0r7Vsvt4L2Irpu1G6Zf160HWwlq4FZXefQCotFPmSUgFd8ctwA9nKv0MEv9sqzVsSeHRvX/8bZ1wlYQ70LCEw3a62g1kUzy1BhcfsVliL0jwrXAlNUKv2waTz5HiZIIQoY1wslQWI4wpoV8fHhjZsT0ifw2VpTAWE7qurKu0dH4p207795e4IIVRrjPaf2h/KE5mNt1j7c0MnrZHs43PhE@Wfv0WZMjzZp1qaNs5uvEVV2uMviutjHAKGIeTS9Bd86iMXaA@MMAxkGdDtWS8qKbT1awgfeGioqYS666uyXD6AsVXrvq5V9aBKxUY9az@gHcEYx/g2Bgh/U/yKyVf3w3e3MC96Vz5tui3zktgxHmcxiNjhOb5/BxK0iSKAihK4uDgLJ@FUJ6nPA0gns8DecayWRbI84SxkBUl7yYu92uI@U3UVgUx/XUul6ZpFljLeBayIhbPeZiJjTHPx7wfqZ4zTvn1iTITtAA0webqiH/634ivljEZHOwP/wA) ``` v->{ // Method with empty unused parameter and String return-type String r; // Result-String for(;!(r=(int)(Math.random()*1e5)+"") // Generate a random number in the range [0; 100000) and set it to `r` .matches("(.).*\\1(.).*\\2") // And continue doing this as long as it doesn't match the regex above, |r.chars().distinct().count()<3;); // or doesn't have three distinct digits return r;} // Return the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ⁵Ḷṗ3⁼Q$ÐfXµḢ;`;ŒBW;U$µX ``` [Try it online!](https://tio.run/##y0rNyan8//9R49aHO7Y93Dnd@FHjnkCVwxPSIg4BRRZZJ1gfneQUbh2qcmhrxP//AA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` ØDẊ⁽0yṃ,U$X ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//w5hE4bqK4oG9MHnhuYMsVSRY/@KAnOKAnSDCouG5rSQgMzDCoSBZ/w "Jelly – Try It Online") --- # Explanation ``` ØDẊ⁽0yṃ,U$X Niladic link, generate a random string. ØD List of digits, ['0','1','2',...,'9']. Ẋ Random shuffle. ⁽0y Number 13122. ṃ Base decompression. (\*) ,U$ Pair with its upend (reverse). X Choose one (it or its reversed) randomly. ``` (\*) The right argument of `ṃ` is the list `['0','1','2',...,'9']`, randomly shuffled, have 10 elements. So the number `13122` will be converted to bijective base 10 (`[1,3,1,2,2]`) and index into the list (so if the list is `l`, the return value of the atom is `[l[1],l[3],l[1],l[2],l[2]]`, where Jelly uses 1-based indexing) [Answer] # JavaScript (ES6), 79 bytes ``` f=([,,d,a,b,c]=[...Math.random()+f])=>a-b&&a-c&&b-c?d&1?a+a+b+c+b:b+c+b+a+a:f() ``` [Try it online!](https://tio.run/##HYpLDsIgFAD3PcVbEcgDogs3rdgTeIKmiwcUP0EwlLgxnh2rm5lMMnd60erK7VlVyn5pLRg@SeklSSvdbCat9ZnqVRdKPj@4wDALcyJlGSPlGLPKjZ7tR0JCiw5t/@dW1AcuWsiFx6VCAgO7YdMRDj8jCnh3AC6nNcdFx3zh2y@G7tO@ "JavaScript (Node.js) – Try It Online") ### How? `Math.random()` gives a random float in **[0..1)**. We use `+f` to force coercion to a string. We ignore the leading zero and the decimal point by doing `[,,` ([destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) of the first two characters to nothing) and collect the first 4 decimal digits into **d**, **a**, **b**, and **c**. If **a**, **b** and **c** are 3 distinct integers, we build the final output in either **AABCB** or **BCBAA** format (using the parity of **d** to decide). Otherwise, we try again until they are. In the highly improbable event of `Math.random()` returning a value without enough decimal places, at least **c** will be set to a non-digit character, forcing the test to fail and the recursive call to occur. If **a**, **b** and **c** are valid integers then **d** is guaranteed to be a valid integer as well, so this one doesn't need to be tested. [Answer] # [Perl 6](http://perl6.org/), 42 bytes ``` [~] (^10).pick(3)[0,|(<0 2 1>,<1 0 2>).pick,2] ``` [Try it online!](https://tio.run/##K0gtyjH7X5xYqfE/ui5WQSPO0EBTryAzOVvDWDPaQKdGw8ZAwUjB0E7HxlAByLKDSOoYxf7XVKioUDA0@A8A "Perl 6 – Try It Online") [Answer] # [Dirty](https://github.com/Ourous/dirty), 33 bytes Uses the `--numeric-output` flag so it's readable, otherwise it would output a string of control characters with code-points corresponding to the digits. ``` 10⭧[1w#%D⅋№3⤱≠1ẅ&]1wẂ⭿⭣1u∅#1∧◌ŪW‼ ``` [Try it online!](https://tio.run/##AV4Aof9kaXJ0ef//MTDiradbMXcjJUTihYvihJYz4qSx4omgMeG6hSZdMXfhuoLirb/iraMxdeKIhSMx4oin4peMxapX4oC8///@b3B0aW9uc/8tLW51bWVyaWMtb3V0cHV0 "Dirty – Try It Online") **Explained:** ``` 10⭧ put 10 on the right stack [1w#%D⅋№3⤱≠1ẅ&] loop until there are 3 distinct positive numbers below 10 in the top stack 1wẂ clean-up the right and top stacks ⭿ copy the top and bottom of the top stack to each-other ⭣ swap the first two elements of the top stack 1u rotate the top stack by 1 ∅#1∧◌ŪW reverse the top stack half of the time ‼ print the top stack ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔‽χθ≔‽Φχ⁻ιθη↑I⟦θθη‽Φχ×⁻ιθ⁻ιηη⟧¿‽²‖ ``` [Try it online!](https://tio.run/##ZY0xCwIxDEZ3f0XGBCqoozeJ4CbIoZM4lNqzgV7Pa6t/P0ZEOHHNe9@LCza7wUaRTSl8S9jadB16XC7IwEjN7Pe841h9Vmpgz@lRkN8WqRvUPWROFdenu4GtLRXPo1JFBv7nR@59wUlkUgz0SV5Io9zB9/uKCFrfRe8qUiMi82d8AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` χ Predefined variable 10 ‽ Random element from implicit range ≔ θ Assign to variable `q` χ Predefined variable 10 Φ Filter on implicit range ι Current value θ Variable `q` ⁻ Subtract ‽ Random element ≔ η Assign to variable `h` χ Predefined variable 10 Φ Filter on implicit range ι ι Current value θ Variable `q` η Variable `h` ⁻ ⁻ Subtract × Multiply ‽ Random element θθ Variable `q` η η Variable `h` ⟦ ⟧ Wrap 5 values into array I Cast array elements to string ↑ Make array print horizontally ² Literal 2 ‽ Random element from implicit range ¿ If ‖ Reflect ``` [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes ``` 10* Y`w`d V?` Lv$7`.(.) $1$<'$' O?`...? ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8vQQIsrMqE8IYUrzD6By6dMxTxBT0NPk0vFUMVGXUWdy98@QU9Pz/7/fwA "Retina – Try It Online") Can print strings with leading zeros. ### Explanation ``` 10* ``` Initialise the string to 10 underscores. ``` Y`w`d ``` Cyclically transliterate word characters to digits. This is a bit weird. The `w` and `d` are short for the following strings, respectively: ``` w: _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz d: 0123456789 ``` Cyclic transliteration means that first, both strings are repeated to the length of the their LCM: ``` _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_012345... 0123456789012345678901234567890123456789012345678901234567890123456789... ``` Since the string lengths 53 and 10 are coprime, each copy of `_` is paired with a different digit. And now cyclic transliteration will replace the **i**th copy of `_` with the **i**th pairing in that expanded list. So we end up with the following string: ``` 0369258147 ``` All of that to save a single byte over the literal string `0369258147`, so yay I guess? :D Anyway, we've got a string of all 10 digits now. ``` V?` ``` This shuffles the digits. So the first three digits will be a uniformly random selection of three distinct digits. ``` Lv$7`.(.) $1$<'$' ``` We match the string `...ABC` and turn it into `BABCC`. The way we do this is kinda crazy though and again saves only one byte compared to a more straightforward approach. We first match all *overlapping* (`v`) pairs of characters, capturing the second one (`.(.)`). Then we retain only the 8th match (`7`, zero-based) which is `AB` in `...ABC`. Then we replace (`$`) it with: `B` (`$1`), `ABC` (`$<'` which is the suffix of the match-*separator* left of the match), `C` (`$'` which is the suffix of the match itself). ``` O?`...? ``` Finally, we match either 3 or 2 characters and shuffle the matches, giving us either `BABCC` or `CCBAB` at random. [Answer] # [R](https://www.r-project.org/), 78 bytes ``` z=sample(0:9,3)[c(2,1:3,3)];cat(paste(`if`(runif(1)>.5,z,rev(z)),collapse='')) ``` [Try it online!](https://tio.run/##DcZBCoAgEADA57gLS2TSIcM@EoEiCoKVqHXw89acJvfeVDFnig5GuZDA3cJEXIq/x2pNhWRKdaCD15CfK3jguA0zNcruhYZI9o7RpOIUY4i9fw "R – Try It Online") `sample` picks 3 random values from `0:9`, which are placed in a vector like so: `a b a c c`. Now we have a 50/50 chance to reverse this vector, and then concatenate and print. [Answer] # [Ruby](https://www.ruby-lang.org/en/), 60 59 bytes ``` ->{a,b,c=[*0..9].sample 3;[[a,a,b,c,b],[b,c,b,a,a]].sample} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1646USdJJ9k2WstAT88yVq84MbcgJ1XB2Do6OlEHLKWTFKsTDaaB/MRYmJLa/4ameiWZuanFCin5XAoKBaUlxQpp0bF6WfmZeVypeSn/AQ "Ruby – Try It Online") It returns a list of digits. [Answer] # PHP, ~~73~~ ~~72~~ 66 bytes ``` <?=strtr(rand()%2?AABCB:BCBAA,ABC,join(array_rand(range(0,9),3))); ``` **Edit:** 66 bytes thanks to @David 's suggestion. [Try it online!](https://tio.run/##K8go@P/fxt62uKSopEijKDEvRUNT1cje0dHJ2ckKiB0ddYBMnaz8zDyNxKKixMp4sBogkZ6qYaBjqaljrKmpaf3//7/8gpLM/Lzi/7p5AA) [Answer] # [Red](http://www.red-lang.org), 147, 146 125 bytes ``` func[][b: copy[]d:[1 1 2 3 2]if 1 = random 2[d: reverse d]while[4 > length? b][alter b(random 10)- 1]foreach a d[prin b/(a)]] ``` [Try it online!](https://tio.run/##LYtBDoIwFAX3nuItYWGg1RWJege3P3/R0l8hgZaUKvH0lRh2M5NMElee4kCMZIKLc7PKriFuTR5nOfmu@Hfoicl26OPyJXYdKShoXKB59DvejheaXIckH0mrwPE2jJPQFXdMEl55eMAymSlLgq2ORbX1GYp9TGL6AQaOljQG2KYyNXOZYlyg23/M8Fx@ "Red – Try It Online") ## Ungolfed: ``` f: func[] [ function with no arguments b: copy [] an empty list d: [1 1 2 3 2] preset digits at positons if 1 = random 2 [ generate 1 or 2 d: reverse d] based on this choose to reverse the positions list while [4 > length? b] [ while we haven't chosen 3 different digits alter b (random 10) - 1 pick a random digit, if it's not in the list already append it to the list, otherwise remove it ] foreach a d [ for each position prin b/(a)] print the corresponding digit ] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes ``` {{#,##,#2},{#2,##,#3}}~r~1&@@(r=RandomSample)[0~Range~9,3]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/C/ulpZRxmIjGp1qpWNwEzj2tq6ojpDNQcHjSLboMS8lPzc4MTcgpxUzWiDOiA/PbXOUsc4Vu1/QFFmXkl0WnRs7H8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # Python 3 +numpy, 69 bytes ``` from pylab import* r=choice i=r(2) print(r(10,3,0)[[1-i,0,1,2,-1-i]]) ``` Explanation ``` from pylab import* r=choice # `choice` takes a range, number of samples, and wether repetition is allowed i=r(2) # Single value in [0,1] to specify if repeated digits come on right or left print(r(10,3,0)[[1-i,0,1,2,-1-i]]) # Construct output using index list and 3 random integers ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 126 119 bytes -6 bytes from @ceilingcat ``` #define R time(0)%10 b,n,m,k;f(){b=R^8;for(n=R;m==n|k==m|k==n;m=R,k=R);printf("%d%d%d%d%d",b?n:m,b?n:k,m,b?k:n,b?m:n);} ``` [Try it online!](https://tio.run/##NY1BCsIwEEX3nqJUCgmMUHeSMPQOOUDBpImEYUYp3WnPHqeCfHift/k/XR4ptXZecqmSu9BtlbMZ7XAdTxEEGMgXY98Rw3zz5bkaweAZUT6EyAdENQBhsP61VtmK6Yflnx7iJI5/JDianCjZifV743sVXdcHlS8 "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), 35 bytes ``` [:u:48+[:|.^:(?&2:)2 2 1 0 1{3?10"_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61KrUwstKOtavTirDTs1YysNI0UjBQMgUoMq43tDQ2U4v9rcilwpSZn5CukKRkoZOoZG/wHAA "J – Try It Online") I'm sure it can be golfed much further. ## Explanation: ``` 3?10 - generates 3 different digits 7 0 3 2 2 1 0 1{ - constructs a list using digits positions 0, 1 and 2 2 2 1 0 1{3?10 3 3 0 7 0 |.^:(?&2:) - generates 0 or 1 and if 1, reverses the list |.^:(?&2:)2 2 1 0 1{3?10 0 7 0 3 3 u:48+ - converts to char by adding 48 to each digit u:48+|.^:(?&2:)2 2 1 0 1{3?10 07033 ``` ]
[Question] [ Given an input of a string consisting of any message from [our site chatroom](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte) taken from the list described and linked below, output either a truthy or a falsy value attempting to predict whether that message was starred or not in 50 bytes or less. You may use any [truthy or falsy values](http://meta.codegolf.stackexchange.com/q/2190/3808), but they must be identical (i.e. there should only be two possible outputs, one truthy and one falsy). The input will be given as raw HTML with newlines removed, and it may contain non-ASCII Unicode characters. If you require input in something other than UTF-8, please say so in your answer. The winning submission to this challenge will be the one that predicts the highest percentage of chat messages correctly, out of the list linked below. If two given submissions have the same success rate, the shorter submission will win. Please provide instructions for running your code on the entire set of messages and calculating the percentage correct. Ideally, this should be a bit of boilerplate code (not counted towards your 50 bytes) that loops through the positive test cases and outputs how many of them your code got correct and then does the same for the negative test cases. (The overall score can then be calculated manually via `(correctPositive + correctNegative) / totalMessages`.) So that your code is reasonably testable, it must complete in 5 minutes or less for the entire list of chat messages on reasonable modern-day hardware. [The full list of chat messages can be found here](https://gist.github.com/KeyboardFire/99f3c1d5c67c999ba59e), and it consists of the 1000 latest starred messages as truthy test cases and the 1000 latest unstarred messages as falsy test cases. Note that there are two files in the gist; scroll about halfway down for the unstarred messages. [Answer] # [Retina](https://github.com/mbuettner/retina), 50 bytes, ~~71.8%~~ 72.15% ``` ^.*([[CE;ಠ-ﭏ]|tar|ol|l.x|eo|a.u|pin|nu|o.f|"$) ``` Tried some regex golfing at @MartinBüttner's suggestion. This matches 704 starred messages and doesn't match 739 unstarred messages. The `^.*( ... )` is to make sure that there is always either 0 or 1 match, since Retina outputs the number of matches by default. You can score the program on the input files by prepending `m`` for multiline mode, then running ``` Retina stars.retina < starred.txt ``` and likewise for `unstarred.txt`. --- ### Analysis / explanation I generated the above snippets (and many more) using a program, then selected the ones I wanted manually. Here's some intuition as to why the above snippets work: * `C`: Matches `PPCG`, `@CᴏɴᴏʀO'Bʀɪᴇɴ` * `E`: Matches `@ETHproductions`, `@El'endiaStarman` * `;`: Because the test cases are HTML, this matches `&lt;` and `&gt;` * `ಠ-ﭏ`: Matches a range of Unicode characters, most prominently for `ಠ_ಠ` and `@Doorknob冰` * `tar`: Matches variations of `star`, `@El'endiaStarman` (again) and also `gravatar` which appears in the oneboxes posted by new posts bots * `ol`: Matches `rel="nofollow"` which is in a lot of links and oneboxes * `l.x`: Matches `@AlexA.`, `@trichoplax` * `eo`: Mainly matches `people`, but also three cases for `@Geobits` * `a.u`: Mainly matches `graduation`, `status`, `feature` and `abuse` * `pin`: Matches `ping` and words ending in `ping`. Also matches a few posts in a discussion about `pineapple`, as an example of overfitting. * `nu`: Matches a mixed bag of words, the most common of which is `number` * `o.f`: Matches `golf`, `conf(irm|use)` * `"$`: Matches a double quote as a last character, e.g. `@phase He means "Jenga."` The `[` is nothing special - I just had a character left over so I figured I could use it to match one more case. [Answer] # JavaScript ES6, 50 bytes, 71.10% Correctly identifies 670 starred and 752 non-starred. ``` x=>/ .[DERv]|tar|a.u|l.x|<i|eo|ol|[C;ಠ]/.test(x) ``` Now across the 70% barrier, and beating everyone except Retina! Returns `true` if the message contains any of these things: * A word of which the second letter is `D`, `E`, `R`, or `v`; * `tar` (usually `star`); * `a` and `u` with one char in between; * `l` and `x` with one char in between (usually `alex`); * italic text; * `eo` or `ol`; * a `C`, a semicolon, or a `ಠ`. Here's a few more fruitful matches that don't seem to be worth getting rid of others: * `nf` * `nu` * `yp` * `n.m` This has been growing closer and closer to the Retina answer, but I have found most of the improvements on my own. Test it out in the console of one of these pages: [star texts](https://gist.githubusercontent.com/KeyboardFire/99f3c1d5c67c999ba59e/raw/7a6af1d79d39af2ee2c25605407cec3bc9cb1c63/starred.txt), [no-star texts](https://gist.githubusercontent.com/KeyboardFire/99f3c1d5c67c999ba59e/raw/7a6af1d79d39af2ee2c25605407cec3bc9cb1c63/unstarred.txt) ``` var r=document.body.textContent.replace(/\n<br/g,"<br").split("\n").slice(0,-1); var s=r.filter(function(x){return/ .[DERv]|tar|a.u|l.x|<i|eo|ol|[C;ಠ]/.test(x)}).length; console.log("Total:",r.length,"Matched:",s,"Not matched:",r.length-s); ``` --- Here's an alternate version. `/a/.test` is technically a function, but doesn't satisfy [our criteria](http://meta.codegolf.stackexchange.com/a/7615/42545): ``` / .[ERv]|a.u|l.x|<i|eo|yp|ol|nf|tar|[C;ÿ-ff]/.test ``` This scores 71.90% (697 starred, 741 unstarred). --- [Answer] # Pyth, 50 bytes, 67.9 % ``` 0000000: 21 40 6a 43 22 03 91 5d d3 c3 84 d5 5c df 46 69 b5 9d !@jC"..]....\.Fi.. 0000012: 42 9a 75 fa 74 71 d9 c1 79 1d e7 5d fc 25 24 63 f8 bd B.u.tq..y..].%$c.. 0000024: 1d 53 45 14 d7 d3 31 66 5f e8 22 32 43 7a .SE...1f_."2Cz ``` This hashes the input in one of 322 buckets and chooses the Boolean depending on that bucket. ### Scoring ``` $ xxd -c 18 -g 1 startest.pyth 0000000: 72 53 6d 21 40 6a 43 22 03 91 5d d3 c3 84 d5 5c df 46 rSm!@jC"..]....\.F 0000012: 69 b5 9d 42 9a 75 fa 74 71 d9 c1 79 1d e7 5d fc 25 24 i..B.u.tq..y..].%$ 0000024: 63 f8 bd 1d 53 45 14 d7 d3 31 66 5f e8 22 32 43 64 2e c...SE...1f_."2Cd. 0000036: 7a 38 z8 $ echo $LANG en_US $ pyth/pyth.py startest.pyth < starred.txt [[345, False], [655, True]] $ pyth/pyth.py startest.pyth < unstarred.txt [[703, False], [297, True]] ``` [Answer] # CJam, 45 bytes, 65.55% ``` l_c"\"#&'(-.19<CEFHIJLMOPSTXY[_qಠ"e=\1b8672>| ``` This checks if the first character is in a specific list or the sum of all code points is larger than 8,672. ### Scoring ``` $ cat startest.cjam 1e3{l_c"\"#&'(-.19<CEFHIJLMOPSTXY[_qಠ"e=\1b8672>|}* $ java -jar cjam-0.6.5.jar startest.cjam < starred.txt | fold -1 | sort | uniq -c 308 0 692 1 $ java -jar cjam-0.6.5.jar startest.cjam < unstarred.txt | fold -1 | sort | uniq -c 619 0 381 1 ``` [Answer] # Matlab/Octave, 17 bytes 60.15% **Correctly classifies 490 messages as stared, 713 messages as unstared** Current version: Just checking the length. ``` f=@(w)numel(w)>58 ``` Old version: Could be translated to any other language. It just checks whether the message contains the words *star* or not. `score: 59/911/52.5%` ``` f=@(w)nnz(strfind(lower(w),'star'))>0 % ``` Results for testcases using this code: ``` slCharacterEncoding('UTF-8'); fid = fopen('codegolf_starred_messages_starred.txt'); line = fgetl(fid); starred = 0; while ischar(line) if f(line); starred = starred +1; end disp(line) line = fgetl(fid); end fclose(fid); fid = fopen('codegolf_starred_messages_unstarred.txt'); line = fgetl(fid); unstarred = 0; while ischar(line) if ~f(line); unstarred = unstarred +1; end disp(line) line = fgetl(fid); end fclose(fid); disp([' correctly classified as *ed: ',num2str(starred)]) disp(['correctly classified as un*ed: ',num2str(unstarred)]) disp([' total score: ',num2str((starred+unstarred)/20),'\%']) ``` [Answer] ## CJam, 32 bytes, Overall score of 0.5605 (56%). Correctly identifies 428 starred messages and 693 unstarred messages. Total score is `(360+730)/2000=0.545`. ``` l_el"sta"/,1>\,)4%!| ``` Not expecting to win, Ill see how it performs. Above is the code for a single message, to run with multiple use this modified version that returns amount of starred messages: ``` 1000{l_el"star"/,1>\,)6%!|}fA]:+ ``` Just test it with STDIN being the raw text of either file. Returns true if the message contains "star" or if `length + 1 mod 4 = 0`. [Answer] # JavaScript ES6, 0.615 = 61.5% 342 correctly identified as starred, 888 correctly identified as unstarred, `(342+888)/2000 = 0.615` ``` x=>-~x.search(/(bo|le)x|sta|ಠ|ツ/i) ``` Test like this on [this](https://gist.githubusercontent.com/KeyboardFire/99f3c1d5c67c999ba59e/raw/7a6af1d79d39af2ee2c25605407cec3bc9cb1c63/unstarred.txt) or [this](https://gist.githubusercontent.com/KeyboardFire/99f3c1d5c67c999ba59e/raw/7a6af1d79d39af2ee2c25605407cec3bc9cb1c63/starred.txt): ``` r=document.body.innerHTML.replace(/<\/*pre>/g,"").split` `.filter(x=>-~x.search`(bo|le)x|sta|ಠ|ツ`).length ``` I STILL MIGHT GET YOU, MY PRETTY! [Answer] # Retina, 46 bytes, 68.55 ``` ^.*([zj_C;&¡-ff]|sta|san|soc|bo|eo|xk|l.x|<.>) ``` 679 star : 692 unstar Switched to Retina to get some more regexes in... Still not done. [Answer] # C# 6.0 (.NET Framework 4.6), 50 Bytes, 63,60% ``` bool s(string i)=>Regex.IsMatch(i,"ol|tar|l.x|ಠ"); ``` Program i used for testing purposes: ``` void Main() { var starred = @"C:\starred.txt"; var unstarred = @"C:\unstarred.txt"; var linesStarred = File.ReadAllLines(starred); var linesUnstarred = File.ReadAllLines(unstarred); var cls = linesStarred.Count(); var clsc = 0; foreach (var line in linesStarred) { if ( s(line) ) clsc++; } var clu = linesUnstarred.Count(); var cluc = 0; foreach (var line in linesUnstarred) { if (!s(line)) cluc++; } $"Starred {clsc}/{cls} correct ({(clsc/cls*100):0.00}%)".Dump(); $"Unstarred {cluc}/{clu} correct ({(cluc /clu*100):0.00}%)".Dump(); $"{(((clsc+cluc)/(decimal)(cls+clu))*100):0.00}".Dump(); } bool s(string i)=>Regex.IsMatch(i,"ol|tar|l.x|ಠ"); ``` ]
[Question] [ As we all know, the Zelda series are one of the best game series ever made. In honor of that, let us play some songs on the ocarina. ## Challenge: Write a program which, given a song, outputs the score to stdout for that particular song. ## Input: The song which you will have to output the score of will be given by a unique three character combination as seen below: ``` zel - Zelda's Lullaby sas - Saria's Song eps - Epona's Song sos - Sun's Song sot - Song of Time sst - Song of Storms ``` **Bonus songs, -7 % each:** ``` mof - Minuet of Forest bof - Bolero of Fire sow - Serenade of Water nos - Nocturne of Shadow ros - Requiem of Spirit pol - Prelude of Light ``` **Bonus song 2, -8 %:** ``` scs - Scarecrow's song ``` As we all know, the Scarecrow's song is a song you compose yourself. This song needs to have eight notes. Output a score you compose yourself which is different from all the other scores. If you decide to include all songs, it will total to a -50 % bonus to your byte score. ## Output: The notes in the output are symbolized by the following characters: ``` ^ < > V A ``` Output a score on the following format: ``` -^-^-^-^-^-^-^-^- -<-<-<-<-<-<-<-<- ->->->->->->->->- -V-V-V-V-V-V-V-V- -A-A-A-A-A-A-A-A- ``` Only one note per column is allowed. For simplicity's sake I've added another row to the original four rows. Each note correspond to a different row: ``` ^: ---------------- <: ---------------- >: ---------------- V: ---------------- A: ---------------- ``` Output shall be written to stdout. Trailing newlines are allowed. ## Examples: **Input (Zelda's Lullaby):** ``` zel ``` **Output:** ``` ---^-----^------- -<-----<--------- ----->----->----- ----------------- ----------------- ``` **Input (Bolero of Fire):** ``` bof ``` **Output:** ``` ----------------- ----------------- --------->--->--- -V---V-----V---V- ---A---A--------- ``` **Note cheat sheet:** ``` zel <^><^> sas V><V>< eps ^<>^<> sos >V^>V^ sot >AV>AV sst AV^AV^ mof A^<><> bof VAVA>V>V sow AV>>< nos <>>A<>V ros AVA>VA pol ^>^><^ ``` Since we play the ocarina code golf, the shortest program in bytes wins! ## Song references: <http://www.thonky.com/ocarina-of-time/ocarina-songs> <http://www.zeldadungeon.net/Zelda05-ocarina-of-time-ocarina-songs.php> [Answer] # [Funciton](http://esolangs.org/wiki/Funciton), 4322 − 50% = 2161 Not really trying to golf here. Going more for the beauty angle. I think the main program looks really neat, a perfect rectangular box tucked away on the right. As always, you can get a better rendering by executing `$('pre').css('line-height',1)` in your browser console. ``` ┌─────────────────────────┐ ┌─┴─╖ ┌─┴─╖ ┌────────┤ · ╟─────────────────────┤ · ╟─────────────┐ ╔═════════╗ ╔════╗ ╔════╗ │ ╘═╤═╝ ╔═════════╗ ╘═╤═╝ ╓───╖ │ ║ 1257283 ║ ┌─╢ 40 ║ ║ 25 ║ │ │ ║ 2097151 ║ ├───╢ ʫ ╟───┐ │ ║ 6456094 ║ │ ╚════╝ ╚══╤═╝ ┌─┴─╖ │ ╚════╤════╝ ┌─┴─╖ ╙─┬─╜ ┌─┴─╖ │ ║ 8219021 ║ │ ┌───╖ ┌─┴─╖ ┌───┤ · ╟────────┴────┐ └─────┬────┤ · ╟───┴───┤ · ╟─┤ ║ 4660190 ║ └──┤ × ╟───┤ % ║ │ ╘═╤═╝ │ ┌┴┐ ╘═╤═╝ ╘═╤═╝ │ ╚════════╤╝ ╘═╤═╝ ╘═╤═╝ │ │ │ └┬┘ │ │ │ ╔═══╗ ┌─┴─╖ ┌──┴─╖ ╔═╧═╗ │ │ ╔═══╗ ┌────╖ │ ┌─┴─╖ ┌┐ │ │ │ ║ 8 ╟──┤ ʫ ╟──┤ >> ║ ║ ║ │ │ ║ 1 ╟─┤ >> ╟─┘ ┌───┤ ? ╟─┤├─┤ │ │ ╚═══╝ ╘═╤═╝ ╘══╤═╝ ╚═══╝ │ │ ╚═══╝ ╘══╤═╝ │ ╘═╤═╝ └┘ │ │ │ ╔════════════════╧═════════╗ │ │ ┌─┴─╖ ┌───╖ ┌─┴─╖ ┌─┴─╖ ╔═╧═╗ │ │ ║ 609678112368778425678534 ║ │ ┌─┴─────────┤ ʫ ╟─┤ ‼ ╟─┤ · ╟─┤ ‼ ║ ║ 1 ║ │ │ ║ 616189712722605554111376 ║ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╚═══╝ │ │ ║ 461573643915077926310571 ║ │ │ │ │ │ ╔═╧══╗ │ │ ║ 355541007599150245813976 ║ │ │ ╔══════╗ │ │ └───╢ 45 ║ │ │ ║ 426564826002362964111793 ║ │ │ ║ 2097 ║ │ ┌─┴─╖ ┌───╖ ╚════╝ │ │ ║ 714054902293682079346275 ║ │ │ ║ 1565 ║ └───┤ · ╟─┤ ♭ ╟─┐ │ │ ║ 663973372550500581508544 ║ │ │ ╚═╤════╝ ╘═╤═╝ ╘═══╝ ├────────────────────┘ │ ║ 874263187322344354338195 ║ │ │ ┌─┴─╖ ┌─┴─╖ │ │ ║ 642609790172899326178321 ║ │ │ │ ‼ ╟─────────┤ ? ╟───────┘ │ ║ 071643306454414932126243 ║ │ │ ╘═╤═╝ ╘═╤═╝ │ ║ 308860823981077902637848 ║ │ ┌─┴─╖ ┌─┴─╖ ╔═══╗ ┌─┴─╖ │ ║ 322657399386789617074176 ║ └─┤ · ╟─┤ ʫ ╟─╢ 8 ║ ┌─┤ ? ╟────────────────────────────────┘ ╚══════════════════════════╝ ╘═╤═╝ ╘═╤═╝ ╚═══╝ │ ╘═╤═╝ │ ┌───┴╖ ╔════╗ │ ╔═══╗ └─┤ >> ╟─╢ 21 ║ └─╢ 0 ║ ╘════╝ ╚════╝ ╚═══╝ ``` Continuing in the tradition of giving Funciton functions names consisting of a single, strange, rarely-used Unicode character, I thought about what could best represent this challenge, and it occurred to me that *Link* and *Zelda* (or, if you want, *Legend* of *Zelda*) give you *LZ*, so the lower-case digraph ʫ (U+02AB, ʟᴀᴛɪɴ sᴍᴀʟʟ ʟᴇᴛᴛᴇʀ ʟᴢ ᴅɪɢʀᴀᴘʜ) seems appropriate. # Explanation As explained in the esolangs article, the Funciton program receives the input encoded as what I would call “UTF-21”, but as a single humongous integer. If I wanted to use this number as a key to a hashmap (dictionary, associative array), I’d need a hash function that satisfies two criteria: one, it’s simple enough to implement in Funciton, and two, all of the 13 expected input strings give a different hash value. The simplest hash function I could think of was `input % m` for some value of `m`. Therefore, I tried `m` = 13, 14, 15, etc. until I got to the smallest integer for which all the hash values are unique. Turns out this number is 25. The hash values are: ``` zel = 6 sas = 19 eps = 10 sos = 22 sot = 1 sst = 9 mof = 14 bof = 3 sow = 13 nos = 17 ros = 21 pol = 16 scs = 23 ``` We encode each song by having one bit represent the presence or absence of a note. For example, Zelda's Lullaby would be encoded as follows: ``` ---^-----^------- = 01001000 -<-----<--------- = 10010000 ----->----->----- = 00100100 ----------------- = 00000000 ----------------- = 00000000 ``` except that the bits are in the opposite order; the top left cell is in the least significant bit. This means every song is 40 bits long. We thus create a (moderately sparse) hash table by taking a 40×25 = 1000-bit number and placing the bit pattern for each song in the right place according to its hash value. The monstrous number in the program is exactly this hash table. Here’s what each of the remaining numbers mean: * `45` = `0x2D` is the Unicode for `-`. * `1257283645609482190214660190`: This is the string `^<>VA` in UTF-21. In hindsight I could have used 7 bits per character here, making the number shorter, but UTF-21 is so deeply traditional in Funciton that it simply didn’t occur to me. * `2097151` = `0x1FFFFF` = (1 << 21) − 1. Used to get the first character from the above string. * `20971565`: This is the string `-\n`, which is appended to the end of each line. + It may seem curious that this number and the previous look so similar, but if you think about it, it’s because we’re using decimal and the Unicode for `\n` happens to be 10. That last number is (10 << 21) + 45. The program now proceeds as follows: * The main program calls `ʫ` with the following 3 parameters: + *B*: The hash table, shifted right by 40 bits times the hash value of the input. The song we want to output is now in the 40 least significant bits. + *c*: The string `^<>VA`. + *a*: The number 8. * In each iteration of `ʫ`, + if *c* is not empty, - if *a* is not zero, look at the bottom bit of *B*. Output `-`, followed by another `-` if it is zero or the first character of *c* otherwise. Shift right *B* by one to remove one bit and decrement *a*. - if *a* is zero, output `-\n`, then chop off the first character from *c* and start another loop with *a* = 8. + if *c* is empty, we are done. [Answer] # Python 2, 143.5 (287 bytes - 50%) ``` i='^<>VA' u=dict(zel="<^>"*2,sas="V><"*2,eps="^<>"*2,sos=">V^"*2,sot=">AV"*2,sst="AV^"*2,mof="A^<><>",bof="VAVA>V>V",sow="AV>><",nos="<>>A<>V",ros="AVA>VA",pol="^>^><^",scs="<"*8)[raw_input()] r=[17*['-']for _ in[1]*5] x=0 for g in u:r[i.find(g)][x*2+1]=g;x+=1 for h in r:print''.join(h) ``` The grid is generated with dashes; then indexed and replaced with notes. [Answer] # Pyth, 56.5 (113 bytes − 6 × 7% − 8%) ``` VtJ" ^<>VA"+K\-sm+?qNdNKK@LJj@jC"þØí§V^G¤×¹z1«bëë¶ñRõr¤çM"1391423xcs@LGjC"cc0Á:xqç÷\rS Íó׺:9"lG3z6 ``` It contains unprintable characters, so here is a reversible `xxd` hexdump: ``` 0000000: 5674 4a22 205e 3c3e 5641 222b 4b5c 2d73 VtJ" ^<>VA"+K\-s 0000010: 6d2b 3f71 4e64 4e4b 4b40 4c4a 6a40 6a43 m+?qNdNKK@LJj@jC 0000020: 2207 fe85 d880 ed0e a756 5e47 8ba4 d7b9 "........V^G.... 0000030: 7a9e 0531 ab1b 62eb ebb6 f112 52f5 72a4 z..1..b.....R.r. 0000040: e74d 2231 3339 3134 3233 7863 7340 4c47 .M"1391423xcs@LG 0000050: 6a43 229a 6317 6330 c13a 9278 71e7 10f7 jC".c.c0.:.xq... 0000060: 5c72 5309 87cd f3d7 ba3a 3922 6c47 337a \rS......:9"lG3z 0000070: 36 6 ``` You can also [try it online](https://pyth.herokuapp.com/?code=VtJ%22%20%5E%3C%3EVA%22%2BK%5C-sm%2B%3FqNdNKK%40LJj%40jC%22%07%C3%BE%C2%85%C3%98%C2%80%C3%AD%0E%C2%A7V%5EG%C2%8B%C2%A4%C3%97%C2%B9z%C2%9E%051%C2%AB%1Bb%C3%AB%C3%AB%C2%B6%C3%B1%12R%C3%B5r%C2%A4%C3%A7M%221391423xcs%40LGjC%22%C2%9Ac%17c0%C3%81%3A%C2%92xq%C3%A7%10%C3%B7%5CrS%09%C2%87%C3%8D%C3%B3%C3%97%C2%BA%3A9%22lG3z6&input=scs&debug=0). ## Explanation I store the songs in base-6 numbers, re-encoded to base 1391423 and then base 256 to save space. I had to choose base 6 since some of the songs start with `^`, and numbers can't really start with a 0 after decoding. ``` J" ^<>VA" save characters in J t discard the space V loop over all characters C"..." parse base256 string (songs) to int j 1391423 convert to base 1391423 (separate songs) C"..." parse base256 string (codes) to int j lG convert to base-26 @LG replace indices by corresponding letters s concatenate c 3 chop to 3-character codes x z find index of input code @ get correct song j 6 convert to base 6 @LJ replace indices by corresponding ^<>VA m map d over the above ?qNdNK take the current character if at its row, otherwise a dash + K add a dash s concatenate +K\- add a dash and print ``` [Answer] # Perl 5, 125 (~~320~~ ~~260~~ 250 Bytes -6x7% bonus songs -8% scarecrow song) Yay, finally an opportunity to experiment with that Perlish hash syntax. ``` $_=pop;@B={qw(zel <^><^> sas V><V>< eps ^<>^<> sos >V^>V^ sot >AV>AV sst AV^AV^ mof A^<><> bof VAVA>V>V sow AV>>< nos <>>A<>V ros AVA>VA pol ^>^><^ scs <^V>>V^<)}->{$_}=~/./g;map{@L=('-')x17;for$i(0..@B){$L[1+2*$i]=$_,if$B[$i]eq$_}say@L}qw(^ < > V A) ``` ### Test ``` $ perl -M5.010 ocarina.pl scs ---^---------^--- -<-------------<- ------->->------- -----V-----V----- ----------------- ``` [Answer] # Perl, 75 (150 bytes - 50%) ``` #!perl -nl $i=vec~$_,0,32;print+qw(- - ^ < > V A)[0,map{vec('w2$$W4F4w7DeweTFwR$Ew$C2wVdeVe3cw4B#EEVVwC5Tw44bwR&e',$i/480%15*8-$_,4)==$.&&$.,0}1..8]while$.++<6 ``` Counting the shebang as 2, input is taken from stdin. **Sample usage** ``` $ echo zel | perl zelda.pl ---^-----^------- -<-----<--------- ----->----->----- ----------------- ----------------- $ echo bof | perl zelda.pl ----------------- ----------------- --------->--->--- -V---V-----V---V- ---A---A--------- $ echo scs | perl zelda.pl ----------------- ---<-<-<--------- ----------------- -----------V-V--- -A-------A-----A- ``` [Answer] # Haskell, 344 - 50% = 172 bytes ``` import Data.List s"zel"=82 s"sas"=69 s"eps"=86 s"sos"=48 s"sot"=128 s"sst"=50 z"mof"=11055 z"bof"=373854 z"sow"=1720 z"nos"=73217 z"ros"= -12730 z"pol"=4791 z"scs"=304236 z n=s n*126 p n|n*n== -n=" "|0<1="A^<>V"!!(n`mod`5):p(n`div`5) o=putStr.unlines.transpose.(l:).concatMap(\c->[map(e c)"^<>VA",l]).take 8.p.z e c d|c==d=c|0<1='-' l="-----" ``` `o` does the job. Thought I could beat Python by using these encodings (took me a long time .\_.), but no. They don't really save a lot of bytes yet. Any suggestions? Yes, that is a minus in front of the encoding for `"ros"`. Thats because its 'sheet' ends with the character that means `0` in my base-5, because this negative trick wouldn't work for the 'easy songs' encoded by doubling what's encoded in `s`. Unless you use `quot` maybe, but then you can't handle `p (-1)` specially, since `quot (-5) = 0`, so the negativity would vanish. Whatever. [Answer] # PHP: 130 bytes (260 ~~270~~ ~~279~~ bytes − 6 × 7% − 8%) Thanks to Ismael Miguel and Blackhole for some great ideas to save more bytes! ``` <?php $f=str_split;for($z='*^<>VA';++$i<6;print"- ")foreach($f(base_convert(substr(current(preg_grep("/^$argv[1]/",$f(bofttmmeps8jf0mofvff0nosfnfopol99d0rosyxt0sasrgk0scs8m8msosm9p0sotnry0sowylc0sstybp0zeldk90,7))),-4),36,6),1)as$c)echo$i-$c?'--':'-'.$z[$c-0]; ``` After the `print"-`, this is a literal insertion of a carriage return. It may translate to two bytes in Windows. All bonus songs including the Scarecrow's song are included. Each song is represented in seven bytes of code. I like the new scoring because with the old scoring I would have gained just one meager bonus point overall! The recent edits make PHP generate a lot of warnings, so to keep things nice and tidy, those are diverted to `/dev/null`. Save as `zelda.php` and run on the command line: ``` $ php zelda.php zel 2> /dev/null ---^-----^------- -<-----<--------- ----->----->----- ----------------- ----------------- $ php zelda.php bof 2> /dev/null ----------------- ----------------- --------->--->--- -V---V-----V---V- ---A---A--------- $ php zelda.php scs 2> /dev/null -^-------^------- ---<-------<----- ----->------->--- -------V-------V- ----------------- ``` [Answer] # Python 3 - 138.5 (~~292~~ ~~280~~ 277 bytes - 50%) Shaved a few bytes off the current Python leader while doing the print-as-you-go method rather than the replace method. [Try Online](https://repl.it/BK0v/16) ``` s=dict(zel="<^><^>",sas="V><V><",eps="^<>^<>",sos=">V^>V^",sot=">AV>AV",sst="AV^AV^",mof="A^<><>",bof="VAVA>V>V",sow="AV>><",nos="<>>A<>V",ros="AVA>VA",pol="^>^><^",scs="AV><^AV>")[input()] s+=" "*8 for c in "^<>VA": o="-" for x in range(8):o+=["--",c+"-"][s[x]==c] print(o) ``` Run: ``` > python3 loz.py bof [return] ``` Output: ``` ----------------- ----------------- --------->--->--- -V---V-----V---V- ---A---A--------- ``` [Answer] # Ruby, rev 1, 192 - 50% = 96 Golfing includes: removal of whitespace between groups of letters in the magic string (and revision of the denominator at the end of the line to `/4`.) Removal of some other unnecessary whitespace. conversion of the escape sequences into single characters (stack exchange will not display them, so I have put `?` as a placeholder) redefinition of `g` as a single string containing five runs of 17 `-` followed by newlines, instead of an array of five strings of 17 `-` ``` s=gets.chop s[?s<=>s[0]]='' n=("owEkrswuns=;gcsbfbYuze33as&&es77os??otaast??mf?9pl ?"=~/#{s}/)/4 g=(?-*17+' ')*5 (n<4? n+5:6).times{|i|x=$'[i/3].ord/5**(i%3)%5;g[x*18+i*2+1]='^<>VA'[x]} puts g ``` # Ruby, rev 0, 223 - 50% = 111.5 (ungolfed) The input code is reduced to 2 letters. If it begins with an `s`, the `s` is deleted, if it begins with a letter after `s` (only applicable to `zel` the last letter is deleted, and if it begins with a letter before `s` the middle letter is deleted. The magic string (which in the ungolfed version contains spaces for clarity) contains the 2-letter codes followed by the music data. It is searched using the match operator `=~` which returns the position in the string. There is exactly one song each of 5, 7, and 8 notes (plus scs which also has 8 notes.) These, along with one arbitrary 6-note song `ros` are bundled at the beginning of the magic string so that the value of `n` given by the position in the string can be used to calculate the number of notes to play. `cs` is squeezed in before `bf`, and with the truncation when the number in `n` is rounded down we just get away with the correct calculation for both. After the fourth cluster, all songs have 6 notes so if `n` is large the number of notes is reduced to a default of 6. An array of `-` is set up for output and the notes are substituted in one by one. The required music data is extracted from the variable `$'` which contains the part of the original magic string to the right of the match. In this way, irrelevant data is ignored. The notes are encoded 3 at a time into the magic string, just after the relevant 2-letter song code. They are extracted with division by `5**(i%3)` and a character in `g` is updated accordingly. At the end of the program `g` is printed. ``` s=gets.chop s[?s<=>s[0]]='' n=("owEk rswu ns=;g csbfbYu ze33 as&& es77 os\21\21 otaa st\23\23 mf\35\71 pl\n\a"=~/#{s}/)/5 g=(0..4).map{'-'*17} (n<4? n+5 : 6).times{|i|x=$'[i/3].ord/5**(i%3)%5;g[x][i*2+1]='^<>VA'[x]} puts g ``` [Answer] # Python 2, 141.5 Bytes -50% (283 Bytes) ``` s='D 2)AE0* A2)D AD )2 A )D2A 0,"!A D2) A (2EA"4H !A )2D A 1F`(A)2D A p\xc5*'.split("A")['sst pol zel sos sot sow sas ros mof scs nos eps bof'.split().index(raw_input())] for c,n in zip(s,"^<>VA"):print"-".join([("-"+n)[i>"0"]for i in bin((ord(c)-32)%255)[2:].zfill(8)][::-1]) ``` Stores each note as a byte as each line is 8 notes long. Recalls the binary representation and then replaces with the right characters. [Answer] # Lua, 249 bytes - 50% = 124.5 ``` w=io.write for j=1,5 do n={sst=41881,pol=44915,zel=30814,sos=42315,sot=17577,sow=5953,sas=35588,ros=11065,mof=29335,nos=122170,eps=29729,bof=719576,scs=999999}[...]for i=1,8 do d=n%6 n=(n-d)/6 c=d==6-j and'AV><^':sub(d,d)or'-'w('-',c)end w('-\n')end ``` Pretty simple, just reads back songs encoded as base-6 numbers. ]
[Question] [ Your challenge is to print/output/return this text: ``` _____ _____ | 1 | | 2 | | H | | He | |_____|_____ _____________________________|_____| | 3 | 4 | | 5 | 6 | 7 | 8 | 9 | 10 | | Li | Be | | B | C | N | O | F | Ne | |_____|_____| |_____|_____|_____|_____|_____|_____| | 11 | 12 | | 13 | 14 | 15 | 16 | 17 | 18 | | Na | Mg | | Al | Si | P | S | Cl | Ar | |_____|_____|___________________________________________________________|_____|_____|_____|_____|_____|_____| | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | | K | Ca | Sc | Ti | V | Cr | Mn | Fe | Co | Ni | Cu | Zn | Ga | Ge | As | Se | Br | Kr | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | | Rb | Sr | Y | Zr | Nb | Mo | Tc | Ru | Rh | Pd | Ag | Cd | In | Sn | Sb | Te | I | Xe | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 55 | 56 | 57 \ 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | | Cs | Ba | La / Hf | Ta | W | Re | Os | Ir | Pt | Au | Hg | Tl | Pb | Bi | Po | At | Rn | |_____|_____|_____\_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 87 | 88 | 89 / 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | | Fr | Ra | Ac \ Rf | Db | Sg | Bh | Hs | Mt | Ds | Rg | Cn | Nh | Fl | Mc | Lv | Ts | Og | |_____|_____|_____/_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| ____________________________________________________________________________________ \ 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 \ / Ce | Pr | Nd | Pm | Sm | Eu | Gd | Tb | Dy | Ho | Er | Tm | Yb | Lu / \_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____\ / 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 / \ Th | Pa | U | Np | Pu | Am | Cm | Bk | Cf | Es | Fm | Md | No | Lr \ /_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____/ ``` ### Rules: * The empty line count between the two parts can be any amount (including 0) * Each line can have prepending and appending spaces as long as the two parts look correctly and the second part is indented at least one space more than the first one. * You may have appending/prepending newlines and/or spaces. * You may not use tabs for spacing (as long as there isn't an interpreter which replaces them correctly with spaces). * Because of a mistake of mine, you can choose to use `______ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____` as the 1st line of the second part. ### Data: you can use this text as a reference (but not as input): Contents: symbol, atomic number, group, period groups 8 & 9 and periods 4-17 are used for the second part. ``` H 1 1 1 He 2 18 1 Li 3 1 2 Be 4 2 2 B 5 13 2 C 6 14 2 N 7 15 2 O 8 16 2 F 9 17 2 Ne 10 18 2 Na 11 1 3 Mg 12 2 3 Al 13 13 3 Si 14 14 3 P 15 15 3 S 16 16 3 Cl 17 17 3 Ar 18 18 3 K 19 1 4 Ca 20 2 4 Sc 21 3 4 Ti 22 4 4 V 23 5 4 Cr 24 6 4 Mn 25 7 4 Fe 26 8 4 Co 27 9 4 Ni 28 10 4 Cu 29 11 4 Zn 30 12 4 Ga 31 13 4 Ge 32 14 4 As 33 15 4 Se 34 16 4 Br 35 17 4 Kr 36 18 4 Rb 37 1 5 Sr 38 2 5 Y 39 3 5 Zr 40 4 5 Nb 41 5 5 Mo 42 6 5 Tc 43 7 5 Ru 44 8 5 Rh 45 9 5 Pd 46 10 5 Ag 47 11 5 Cd 48 12 5 In 49 13 5 Sn 50 14 5 Sb 51 15 5 Te 52 16 5 I 53 17 5 Xe 54 18 5 Cs 55 1 6 Ba 56 2 6 La 57 3 6 Hf 72 4 6 Ta 73 5 6 W 74 6 6 Re 75 7 6 Os 76 8 6 Ir 77 9 6 Pt 78 10 6 Au 79 11 6 Hg 80 12 6 Tl 81 13 6 Pb 82 14 6 Bi 83 15 6 Po 84 16 6 At 85 17 6 Rn 86 18 6 Fr 87 1 7 Ra 88 2 7 Ac 89 3 7 Rf 104 4 7 Db 105 5 7 Sg 106 6 7 Bh 107 7 7 Hs 108 8 7 Mt 109 9 7 Ds 110 10 7 Rg 111 11 7 Cn 112 12 7 Nh 113 13 7 Fl 114 14 7 Mc 115 15 7 Lv 116 16 7 Ts 117 17 7 Og 118 18 7 Ce 58 4 8 Pr 59 5 8 Nd 60 6 8 Pm 61 7 8 Sm 62 8 8 Eu 63 9 8 Gd 64 10 8 Tb 65 11 8 Dy 66 12 8 Ho 67 13 8 Er 68 14 8 Tm 69 15 8 Yb 70 16 8 Lu 71 17 8 Th 90 4 9 Pa 91 5 9 U 92 6 9 Np 93 7 9 Pu 94 8 9 Am 95 9 9 Cm 96 10 9 Bk 97 11 9 Cf 98 12 9 Es 99 13 9 Fm 100 14 9 Md 101 15 9 No 102 16 9 Lr 103 17 9 ``` Built-ins that give any info about the periodic table of elements are allowed but should be viewed separately from non-built-in solutions. The shortest code per language wins! [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 535 bytes ``` 0000000: e0 0c 4a 02 0f 5d 00 10 17 f0 84 1b a9 df 70 5a ..J..]........pZ 0000010: a9 c3 a0 9d ad 4f 8b 91 5d a2 33 5c b1 1d 4d 48 .....O..].3\..MH 0000020: 0d 80 c4 80 7f da b5 6f 8a 4a 45 20 34 51 d7 2c .......o.JE 4Q., 0000030: bc 47 4c ea c5 45 24 db a1 3d 46 42 e0 c8 51 ed .GL..E$..=FB..Q. 0000040: b6 b8 2b fb 42 dd 7b 44 bc e2 bf a8 c8 80 be 8a ..+.B.{D........ 0000050: 30 2b e1 c7 39 c6 41 30 36 c6 c2 93 0b b2 ac 42 0+..9.A06......B 0000060: 06 5b bd b7 f9 40 11 9e 57 78 ff 0f 8a 45 f8 d7 .[[[email protected]](/cdn-cgi/l/email-protection).. 0000070: b9 ea 6c 8a 6c e5 bf bb 9c f5 18 db 98 85 13 cc ..l.l........... 0000080: d3 a8 38 9c 55 fe b2 f1 31 1d e0 0e 67 84 b6 48 ..8.U...1...g..H 0000090: 8e 68 2a 8a c6 99 0a 13 1b 10 f0 b5 e2 e0 43 02 .h*...........C. 00000a0: 6f 52 b0 3e d5 27 a9 eb a4 99 4e b2 c2 8b 51 49 oR.>.'....N...QI 00000b0: 9b 7e 46 99 22 31 4f 8c 70 6d 16 b4 a7 79 01 08 .~F."1O.pm...y.. 00000c0: 42 01 a8 af 98 d1 38 d3 77 35 c9 3f fc f5 ae 88 B.....8.w5.?.... 00000d0: 47 be 91 a0 ab ac ab b7 04 9a fc 81 60 92 61 a1 G...........`.a. 00000e0: 54 f9 92 46 2f bd 70 20 ba dc 29 63 35 29 c4 48 T..F/.p ..)c5).H 00000f0: be ee 7f 3d d6 8c 1e b9 f3 ab 17 23 0e 1d 86 2c ...=.......#..., 0000100: d4 28 ce 4a 46 df 6e 3a c3 25 7d 3f 1b e4 3c 03 .(.JF.n:.%}?..<. 0000110: c9 1f 38 96 30 1e c9 6e de fa 26 8f a1 59 18 69 ..8.0..n..&..Y.i 0000120: 68 9a 35 c4 42 56 2a 6f b2 3b 3f b3 ae 60 96 a8 h.5.BV*o.;?..`.. 0000130: 5d c4 9d 0d cc 0b d6 ec b9 58 28 d3 3c bb 0d f3 ]........X(.<... 0000140: b6 56 1d b2 f8 da 3b f1 3c 11 9e e7 56 c8 20 27 .V....;.<...V. ' 0000150: 76 65 3e d9 1e 17 e5 d2 4f 65 8e 83 c2 27 5a bf ve>.....Oe...'Z. 0000160: 1f 80 bf f4 4b 78 b0 0e 3f 1e 4d 96 63 b9 65 5a ....Kx..?.M.c.eZ 0000170: 34 43 c8 9a a9 8e 62 5a cc af ab 10 ff 26 1f ae 4C....bZ.....&.. 0000180: 03 ef 4c 8f ba 09 b8 1e 7a 1e bb 5d 77 d3 f8 06 ..L.....z..]w... 0000190: 71 53 67 60 26 91 28 81 2e 5e bc 84 9f 48 cc ce qSg`&.(..^...H.. 00001a0: 60 ec b4 b3 fa 27 32 60 27 98 63 a3 80 66 65 d2 `....'2`'.c..fe. 00001b0: ed 0b af e7 ba d1 d8 85 d3 af 93 7f a2 48 15 68 .............H.h 00001c0: a8 78 74 f8 ed 6f 6b 25 5f ca 7d 28 fb 0c 94 ce .xt..ok%_.}(.... 00001d0: 7a fc 6e b6 32 88 6a 62 b3 84 b8 98 d3 b9 01 73 z.n.2.jb.......s 00001e0: e4 76 07 3e 4e a0 15 82 1b 4a e1 89 13 75 4c ee .v.>N....J...uL. 00001f0: 09 06 05 75 cc 0a 51 88 38 31 f6 7e e8 f8 74 b7 ...u..Q.81.~..t. 0000200: 59 9c e6 00 53 4f e7 80 ae 8c a5 85 55 e7 08 ae Y...SO......U... 0000210: 84 69 18 84 dc c0 00 .i..... ``` Uses LZMA compression. [Try it online!](https://tio.run/nexus/bubblegum#fVZpkxVFEPzur6hQYTmMso/pY0BAF1kQQQIRFLy2Z6abxQMw5BID/jpm9swDPjm77@2LtzM5VVmZWfPGrMcZqUbMLEMR48Q0CYsYIxa/SZqRPIidpIyyNElGQhFRvar6s27H43sfdCALKJw2eylGxkXKIkOTPMloiVmceC9hlsmKxb/wmwmF4wbR/E@q16@sUA5QZpFsZB74nposRaYgEYCFpQ5BnBE/SLCyJHHz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1WKms@NI4SNwX/Mlwk2HSvl3Z8xxXzClKpjWsCQ4fCzcioRz2pdK1OnAv8CPLBJCIXVV3rKC@xv56/pZ15laAZz3DDuHFrmBFTg@8cMrlyWSD0xkbLoE4oWf66df/wOHSqvwDnyg6q55Xpox@oH2oSgeA6bGJQgKXiSWbs08E45JAl7bnDPTClrW5QzCusNmgJtGDotDBWZ09yBnXjuoE9saZRlQ3Us@j7xxU9WqGYVxAwppYGUgFY6DxOdF9oMhd6EP1iReK5Yhx6g/riCXbz78d@1Vcn3uaVZV6lHkowHbSK1hBusXCI6JerIfc87GJAQiao/SXs5/S3aavr7xWKeQXLQ6UmUaVIcgQgGsmOaYCswKrNI7dGCv1hgFU90/NMdT7Q6NNrW1XMK0wfIzaBJ9ODhesg93WGnG@RyV8z2wcJU@pcPeWzQrb6WvXJCuWYV0gPbMAa@VgFVQydf4yMSQ6VBo4A@xFfYkdQoneBdevG2t3tHVeOeQVCYs8ifEACz4aY/3fog47y5s1/ "Bubblegum – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~517~~ ~~500~~ ~~494~~ ~~459~~ 458 bytes ``` ¾36ו=∊à¢[ΔζÃΓÖo›àƶØ4.æßðùùO∊ŸßeÑΘ²9Êλ*βUθÇΔn4üÁ¬₁÷6öć®λJƒÐtvý¢ƶ³≠qΣĆ}εùeÆv]_|ˆ±q₅yÜƵтY¿в{àéÙ•4B«S2ôvyć'#×s'@×})˜2ôvyDJ'@åi'_©5×ëð5×}‚˜.C.B}})18ôvyøvy'|ý2F'|3úûð7×:}D4£ð4×Êi'|ëð}.ø}})ø„ #„_#:ø»… _û®5×:…__ 2ú®5×:„_ û®3×:.•$›“₄≠÷/¤¿M5PËð—ΓY¢ö>7*ƒße∞™¶£nˆU‘´¾Ã‹Š\S¬ǝüÑ;:œ η|9HœÇâ`η_т<%£¾ÉöJ₄ª"eÄŸµ2ƶ3^_Ω~Ç∍”pgH¤δ%6ΣŽΔΔ9üηΩ+₃¹ºι"¤Qy¶O£ÄˆU«AJdc=ûö÷O´η,lð¢ʒƵy•v'@y.;}57L72 89Ÿ«Ƶ3ƵHŸ«58 71Ÿ«90Ƶ2Ÿ«Jv'#y.;}"57 |""57 $":¶¡ø'$'|6×2úRû©¦«„/\3×2úR.∞:®'|6ׄ\/3×3ú«:ø»™ ``` [Try it online!](https://tio.run/##NZL9S1NhFMf/lctULlpM3YtzM8NMQkZhJf4gWbe3EUJYUgxGW9zm2tQI0o1mMXXdmbAmsmy7e/MFztfdoMFD/gvPP7LOlH55nnPO8z2ccz7nGXA/ejwYaLfp2DmEtNSNUbm8iiwZ90RKmFgSSXx@gSiiUq8ja5nYcNmxi20UUUNtisXNKrYDWBMbdODFqmj0iYMZUUVCpBZcOMQ72pPRd6gMwTxN0L5o@K11fHodxBEZlkm/5Ep2UeRO4xFRRi2AePC@Fm7F6eeijL4PIWOVz6KzdPL34A2yyOMLd@gap8K0A6Vg6DShdiH9Sh1DOtLbypzHJvzsfp9XNcq7kUYBRb4iUv/aytiv28cjkd7B4Y4O1WBIDePIcUMNO1FHA0UP0r7IhItyKLo4dXWe3zk/YkeV01CV@pbSxYfW5UOVGlLfVRQNDdrnCj72NE1xoP7f3dKUzpuTHTt33c0ApZ6R0RhPjEo/7dDJLfdtfEBR6imRnCUD5lVPH9PZDsjlLRkzyKTcQis@I/UNKtExlqRea2bnpmnv9yaTXRvxNZOKqIS9k80kEjAeiop2Fr3SQzkWr8D0czH6YQsg1qxS2WGZzgeayL9FQi5/lPrmy2eTtCNKPUMi1zzibae8OBQVkb8ko0tUo7qo2WjnTojMKSYS4z6ocM3/9MkoozJRmaKSqFx@jiIZf9atcohHDKpjIftIxO256XEow14uWrDKTqs82bHcw4pnsGN4B6yyo2P4g2pXR29ze5SwrXN223w88zdU1W41zN@Rad5lhnnapQID7Z9zXsTszMdH@@cajs/1c5x3SIWLvcSMdvsf "05AB1E – Try It Online") *-10ish thanks to Emigna* *Lets out a long guttural victory screech... Will golf more, but since it's still the shortest...* --- # The Basic Idea ``` 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 12 12 12 00 00 00 00 00 00 00 00 00 00 11 11 11 11 11 22 22 22 00 00 00 00 00 00 00 00 00 00 22 22 21 21 22 22 21 22 22 22 21 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 21 22 22 22 22 22 22 22 22 22 22 22 22 22 21 22 22 22 22 22 22 21 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 22 22 22 22 22 22 22 22 22 22 22 22 22 22 00 00 00 00 22 22 21 22 22 22 22 22 22 22 32 32 32 32 00 ``` I mapped out each of the squares with the first digit being the length of the number and the second digit being the length of the element name. Used this to create the skeleton (if `.C` and `.B` didn't exist this would easily be 300-400 bytes): ``` _____ _____ | # | | # | | @ | | @@ | |_____|_____ _____________________________|_____| | # | # | | # | # | # | # | # | ## | | @@ | @@ | | @ | @ | @ | @ | @ | @@ | |_____|_____| |_____|_____|_____|_____|_____|_____| | ## | ## | | ## | ## | ## | ## | ## | ## | | @@ | @@ | | @@ | @@ | @ | @ | @@ | @@ | |_____|_____|___________________________________________________________|_____|_____|_____|_____|_____|_____| | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | | @ | @@ | @@ | @@ | @ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | | @@ | @@ | @ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | | @@ | @@ | @@ | @@ | @@ | @ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | ## | ## | ## | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | ### | | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| ___________________________________________________________________________________ | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | ## | ## | ## | ## | ## | ## | ## | ## | ## | ## | ### | ### | ### | ### | | @@ | @@ | @ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | @@ | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| ``` This is what the first half of the code accomplishes... # [05AB1E](https://github.com/Adriandmen/05AB1E), 229 bytes ``` 0 36ו=∊à¢[ΔζÃΓÖo›àƶØ4.æßðùùO∊ŸßeÑΘ²9Êλ*βUθÇΔn4üÁ¬₁÷6öć®λJƒÐtvý¢ƶ³≠qΣĆ}εùeÆv]_|ˆ±q₅yÜƵтY¿в{àéÙ•4B«S2ôvyć'#×s'@×})˜2ôvyDJ'@åi'_5×ëð5×}‚˜.C.B}})18ôvyøvy'|ý2F" |"ûð7×.:}D4£ð4×Êi'|ëð}.ø}})ø„ #„_#:ø»… _û'_5×:" __ "'_5×:„_ û'_3×: ``` [Try it online!](https://tio.run/##JY5PSwJRFMW/ykMXYovBP6OVEIRJCzctokVEDAUu3BRSDEgOjBNpueqPNBaSg5IQRpjlNDZJ8I7NRnjUV3hfZHrW5l7Ovb9z7o0kdnajOd@PkHgSJtfbS/y0Bou2t1id2ThmV7jehwGD6@@wPBsNWUIXLfQxwmhNwF8OWjlcsAYdLKLG3Dk22GAOqqy@J@MDZfrIjTLekrAnVfrE3Kx3ifNDFWPa9mz6ws@sAutMKhobYpRDRd1WStMKfS5w46SIpjf8MTbp5/fgCBYecCM@lNO0tx7Dq1qcVENBmAehZZhaeNr8m2WyQt7nQ0oCJnroi6Zx/XbalFaktKaFowszCo5aDJUwjq0GCCGlAFz052FKKS0j0w76sjDX8oIQCZoERxjhcP2OBEVRgik41OV6lxAF7t@plMhRFBL4FzOIzDZxIXz/Fw "05AB1E – Try It Online") Through ugly one-off manipulation and other bullshit that shouldn't exist, I manage to piece together the entire skeleton. --- The next part is basically "insert the massive string of letters and numbers that represent the elements". I essentially just compressed, sequentially, all of the letters: ``` .•$›“₄≠÷/¤¿M5PËð—ΓY¢ö>7*ƒße∞™¶£nˆU‘´¾Ã‹Š\S¬ǝüÑ;:œ η|9HœÇâ`η_т<%£¾ÉöJ₄ª"eÄŸµ2ƶ3^_Ω~Ç∍”pgH¤δ%6ΣŽΔΔ9üηΩ+₃¹ºι"¤Qy¶O£ÄˆU«AJdc=ûö÷O´η,lð¢ʒƵy• ``` To get: ``` hhelibebcnofnenamgalsipsclarkcasctivcrmnfeconicuzngageassebrkrrbsryzrnbmotcrurhpdagcdinsnsbteixecsbalahftawreosirptauhgtlpbbipoatrnfrraacrfdbsgbhhsmtdsrgcnnhflmclvtsogceprndpmsmeugdtbdyhoertmybluthpaunppuamcmbkcfesfmmdnolr ``` You then see me iterate replacing all @ symbols with the appropriate letter (at the end, after placing them all in their appropriate positions, it allows me to use "Title Cased" for the capitals, as each element is separated by whitespace). --- Next I make the number string and do the same thing (thanks Emigna): ``` 57L72 89Ÿ«Ƶ3ƵHŸ«58 71Ÿ«90Ƶ2Ÿ«J ``` Results in: ``` 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657727374757677787980818283848586878889104105106107108109110111112113114115116117118585960616263646566676869707190919293949596979899100101102103 ``` Which I then iterate and replace each # with. --- After this, the final annoyance was the slashes... My god... ``` "57 |""57 $":¶¡ø'$'|6×2úRû©¦«"\/\/\/ ".∞.;®'|6×" \/\/\/"«.;ø» ``` This 50 byte monstrosity is what I want to fix, along with multiple other small things... So I'll continue to golf, and until I fix the things I want to this will be the informal explanation. [Answer] ## JavaScript (ES6), ~~756~~ 750 bytes ``` j=i=1 r=s=>s[0].replace(/.(\d+)/g,(s,n)=>s[0].repeat(n)) f=s=>[(s=s[0].match(/../g)).map(_=>(i>99?` `:` `)+i+(i++>9?` `:` `)),s.map(s=>` ${s} `),s.map(_=>r`_5`)].map(a=>a.join`|`) g=(a,b,c)=>a.map((s,i)=>s+b[i]+c[i]) document.write(r`<pre> _5 97_5 |`+[...g(f`H `,[s=r`| 95|`,s,r`|_5 61_29|`],f`He`),...g(f`LiBe`,[s=r`| 59|`,s,s],f`B C N O F Ne`),...g(f`NaMg`,[s,s,r`|_59|`],f`AlSiP S ClAr`),...f`K CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKr`,...f`RbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI Xe`,...g(f`CsBaLa`,(a=f`CePrNdPmSmEuGdTbDyHoErTmYbLu`,`\\/\\`),f`HfTaW ReOsIrPtAuHgTlPbBiPoAtRn`),...g(f`FrRaAc`,(a=[...a,...f`ThPaU NpPuAmCmBkCfEsFmMdNoLr`],`/\\/`),f`RfDbSgBhHsMtDsRgCnNhFlMcLvTsOg`)].join`| |`+r`| 18_84 `+a.map(s=>r` 17`+`\\/`[j^=1]+s+`\\/`[j]).join` `) ``` Explanation: * `a` contains the (formatted) Lanthanides and Actinides * `j` is used to track which character is used to draw the zigzag of the Lanthanides and Actinides * `i` is simply the number of the next element to be formatted. Although it's not strictly necessary to format the elements in order, I think there's a small byte saving in doing so. * `r` is a run-length decoding function. It expects to be called using a template string parameter. Any number in the string causes the preceding character to be repeated that many times, e.g. `r`_5`` is the same as ``_____`` (but 2 bytes shorter of course). I did originally have a more sophisticated version that could handle `r`${i<100} `+i+r`${i++<10} `` but it turned out to be shorter to keep that as a special case. * `f` is an element formatting function. It expects to be called using a template string parameter that contains the elements as pairs of characters (space padded out for single-character element names). An array of three strings is returned, one for the element numbers, one for the element names, and one for the underlines. If more than one element is formatted, they are joined with a `|` separator. * `g` is a glue function. It expects to be called with three arrays (the second and third parameters can be strings if only one character is needed) and returns a single array with all the corresponding strings concatenated together. The first three rows of elements are handled by gluing the formatted elements from each side with an appropriate amount of space. The fourth and fifth rows need no glue. The sixth and seventh rows are handled by gluing the formatted elements from each side with the appropriate zigzag. The 21 rows are then joined together with `|` borders and newlines. Meanwhile the 6 rows of the Lanthanides and Actinides are given their padding and zigzag and joined together with newlines. Finally the pieces are concatenated with the necessary remaining formatting elements. Edit: Saved 6 bytes because I forgot to substitute literal newlines after developing the code. If a full table with the Lanthanides and Actinides in situ is acceptable, then for 556 bytes: ``` document.write(`<pre>`+[[/\w./g,`| $& |`],[/\|\|/g,`|`],[/(.*)-(.*)/g,(_,l,r)=>l+` `.repeat(193-r.length-l.length)+r],[/\n.*/g,s=>s.replace(/ \w./g,_=>(++i<100?` `:``)+i+(i<10?` `:``))+s+s.replace(/ \w. /g,`_____`)],[/ {5}(?=[^]{191}\d)/g,`_____`],[/_ _/g,`___`]].reduce((s,[r,t])=>s.replace(r,t),`- H -He LiBe-B C N O F Ne NaMg-AlSiP S ClAr K CaSc-TiV CrMnFeCoNiCuZnGaGeAsSeBrKr RbSrY -ZrNbMoTcRuRhPdAgCdInSnSbTeI Xe CsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRn FrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg`,i=0)) ``` Explanation: A string contains the list of elements with `-` and newline added as formatting elements. A number of replacements are used to transform the list of elements into the desired table. 1. Each element is padded inside a pair of `|`s. 2. Consecutive `|`s are then deleted. 3. `-`s are replaced with enough padding to result in a width of 193 characters. 4. Each line after the first is then replaced with three lines: 1. A line with all the elements replaced with consecutive integers 2. The original line of elements 3. A line with all the elements replaced with `_`s. 5. Each integer then has `_`s placed above it (if it doesn't already have them) 6. Space-separated `_`s are joined with `_`s. I could probably save a few more bytes using the widely available padStart and padEnd methods. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~567~~ 558 bytes ``` a=[?|]*21 j=r=0 118.times{|i|a[r]+="%4s |"%("%-2d"%-~i) a[r+1]+=" #{'H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[i*2,2]} |" a[r+2]+=?_*5+?| i>j&&(j+=(r/6+2)**2*2;r+=3)} a<<' '+?_*84 6.times{|r|a[r+3][13]=' _'[r/5]*59+?|+d=' _'[r%3] r<3&&a[r][7]=d*5+' '*61+d*29+?|+d a[r+=15][18]=a[r][102]='/\\'[r%2] a<<' '+a[r][18,85] a[r][18,84]=''} puts ' _____'+' '*97+?_*5,a ``` [Try it online!](https://tio.run/##PZFtb6JAFIW/8ysmbhQFdy2DWJuVNTCKmAoSYF9aOmkGGRFXsBlkk6a6f90daLrzYTK55@S5J2dYFb9er0SPpmcsQUXY60y/ERRl/OWU5bR8O2dnEjEs6632sATnVrvban@GCb/@Zj2BS7JSiwB8ehNtYNNVZlITIOCCNbCAS13ipMYhyDwQAHQw2D1AJNiE2Q@AmFNYFB3dDFWPxYIsqFEG1GT3zI8D9gAemRs7x3DjV/7OS4wUJcsiKII4pEvwi6LSJCuCqMfcxMuDfF4tkjCevdrHOQvzh3hV2duQ/AQ@XZdL5p2Myk7DgxebmXc0Tn5hMZ8Ym3Dnke/AffEqI0e5@Rtt56WVO4l7XDF/O4uD1NzZpXOalX6KCndnHZzN6k9YrlMxyiTYh/jCO2lqgLyG6bOkydOzkH3bdzrdvax32WAkw54kQQl@ZbKu9i4CmUxEIMrcOx4Ko4@aWV2zrOJIUbEugmcxYgMNS9od58kJnzSjtooFNlE7nfpPolusJ3whp0kjRU4k@G5u4uiKxlljrDdO5QZy6uDpqWZA/JHhXRv3xxoW/r@H3ClehJfqVAIepD5is@Putg6t9cn1@g8 "Ruby – Try It Online") Brought the La/Ac series closer to the main table (re reading of the rules suggests it's allowed; rearranged formatting section so `d` is used immediately when calculated; and next row calculated mathematically instead of by regex. # Ruby, 587 score excludes 3 unnecessary newlines added for clarity ``` a=[?|]*21 r=0 118.times{|i| a[r]+="%4s |"%("%-2d"%(i+1)) a[r+1]+=" #{e='H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[i*2,2]} |" a[r+2]+="_____|" "HeNeArKrXeRn"=~/#{e}/&&r+=3} 6.times{|r|d=' _'[r%3] r<3&&a[r][7]=d*5+' '*61+d*29+?|+d a[r+3][13]=' _'[r/5]*59+?|+d a[r+15][18]=a[r+15][102]='\//'[r%2] a[r+23]=' '*18+a[r+15][18,85] a[r+15][18,84]=''} a[22]=' '*18+?_*84 puts ' _____'+' '*97+?_*5,a ``` **Explanation** The idea is to produce the following, then modify it by adding the correct padding and formatting, and moving the lanthanides and actinides to the bottom. ``` | 1 | 2 | | H | He | |_____|_____| | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | | Li | Be | B | C | N | O | F | Ne | |_____|_____|_____|_____|_____|_____|_____|_____| | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | | Na | Mg | Al | Si | P | S | Cl | Ar | |_____|_____|_____|_____|_____|_____|_____|_____| | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | | K | Ca | Sc | Ti | V | Cr | Mn | Fe | Co | Ni | Cu | Zn | Ga | Ge | As | Se | Br | Kr | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | | Rb | Sr | Y | Zr | Nb | Mo | Tc | Ru | Rh | Pd | Ag | Cd | In | Sn | Sb | Te | I | Xe | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | | Cs | Ba | La | Ce | Pr | Nd | Pm | Sm | Eu | Gd | Tb | Dy | Ho | Er | Tm | Yb | Lu | Hf | Ta | W | Re | Os | Ir | Pt | Au | Hg | Tl | Pb | Bi | Po | At | Rn | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | | Fr | Ra | Ac | Th | Pa | U | Np | Pu | Am | Cm | Bk | Cf | Es | Fm | Md | No | Lr | Rf | Db | Sg | Bh | Hs | Mt | Ds | Rg | Cn | Nh | Fl | Mc | Lv | Ts | Og | |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____| ``` **Commented code** ``` a=[?|]*21 #setup array with |s for left hand side r=0 #row counter 118.times{|i| #For each element add to the correct row a[r]+="%4s |"%("%-2d"%(i+1)) #the atomic number a[r+1]+=" #{e='H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[i*2,2]} |" a[r+2]+="_____|" #the element symbol and the blank space at the bottom. "HeNeArKrXeRn"=~/#{e}/&&r+=3} #If it is element from last column, increment r 6.times{|r|d=' _'[r%3] #What symbol (_ or space)do we need to pad? r<3&&a[r][7]=d*5+' '*61+d*29+?|+d #Move He to the right a[r+3][13]=' _'[r/5]*59+?|+d #Move row 2&3 elements to the right a[r+15][18]=a[r+15][102]='\//'[r%2] #Draw breaks for La and Ac series a[r+23]=' '*18+a[r+15][18,85] #Copy La and Ac series a[r+15][18,84]=''} #Delete original La and Ac series from main table a[22]=' '*18+?_*84 #Draw top on La and Ac series puts ' _____'+' '*97+?_*5,a #Output top of row 1, followed by array containing the rest of the table. ``` [Answer] # C, ~~1415~~ ~~1401~~ ~~1395~~ ~~1367~~ ~~1345~~ ~~1277~~ ~~1159~~ ~~1052~~ 1043 bytes ``` #define P printf( #define L;P"|\n") #define M;p(18," ") #define D L;B #define K;P"\\\n")M;P #define Q;P"|%59c",32) char*l="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcDbSgBhHsMtDsRgCnNhFlMcLvTsOgPrNdPmSmEuGdTbDyHoErTmYbLuPaUNpPuAmCmBkCfEsFmMdNoLr",U[]="|_____",*u=U+1;a;p(n,s)int*s;{while(n--)P s);}A(n){for(n+=a;a<n;++a)P a>9?"%c%4d ":"%c%3d ",a^72*a^58?a^90*a^104?'|':47:92,a);}B(n){for(;n--;P"%c ",*l>96?*l++:32))P"|%3c",*l++);}N(){A(18)D(18)L;p(18,U)L;}f(){P" %s%102s\n",u,u);A(a=1);P"|%95c",32);A(1)D(1);P"|%95c",32);B(1)L;P"%s%-67s",U,U);p(5,u);P"____%s|\n",U);A(2)Q;A(6)D(2)Q;B(6)L;p(2,U)Q;p(6,U)L;A(2)Q;A(6)D(2)Q;B(6)L;P"|%s|%s|",u,u);p(11,u);P u+1);p(6,U)L;N(N());A(3);a=72;A(15)D(3);P"/ Hf ");B(14)L;p(3,U);P"\\%s",u);p(14,U)L;A(3);a=104;A(15)D(3);P"\\ Rf ");B(14)L;p(3,U);P"/%s",u);p(14,U)L;P"\n")M;p(84,"_");P"\n")M;a=58;A(14)K"/ Ce ");B(13);P"/\n")M;P"\\%s",u);p(13,U)K"");a=90;A(14);P"/\n")M;P"\\ Th ");B(13)K"/%s",u);p(13,U);P"/");} ``` *Thanks to @Conor O'Brien for saving 6 bytes!* *Thanks to @Zacharý for saving ~~22~~ 90 bytes!* *Thanks to @gastropner for saving ~~118~~ 225 bytes!* *Thanks to @ceilingcat for saving ~~8~~ 9 bytes!* [Try it online!](https://tio.run/##bVN/b6JAEP3fT7HZCykrmAr@lrMGsNZGoRTw7trz2qyASg7RsHKXi/Wze7NqTduUkGV4s/Pm7cxsUJoHwX7/JYxmcRohB62zON3MxMIrMtIc/DJJMTkjlrYWlaaM0RusB/uM898QYiYTHmRpzhm950xCrRVguaKSQrCgWTHp4MEgGsVGZJj2Xd@ObGrN9cSLHc9M9GxoUi/w429mZqX9yFzZsZk/pjf0JtKZFxnZMHOnXvbwmNlTa@UHbu4unFCfm@Ft6qXe1I9uf0QmM@iI@vS7G92x28zZ6Plg7ifO1Iidlb5x037mUj3oTb25sRgwa9Nj7txM7UU/sYLRH5/dzZ3MDp2lt7zOb0J/2vs3WF1n/vJhOsodOrbXTq4vzaXx25xds/7SCu3VKMPy@OevDn555g@Wi3lnLCkahdKlMiNQ4iLTtn8XcRKJaalEHMSIttPFlGxnq0xMpQ7V6NdUkyQKPnrV6mIhEKohwm1uVEKEsEyfGmqRPtWaXfrUKoOllKvdi5eLdrXRbqkyBUbjlVGDLFB/IYC4YnLVqneLiSS1oRGEd6UScFiSIMQWyVaHBpMeX0bHZo/B2M3A42AkMEEpqwzaK@dyTjRdpB2FHJrbqh2bC5jC4z@gBiB8noChVG8wqBEQQ4Iap3EwL5XA@LBxWBdVcg9rHYi4ZYDF1ajgvIdv/SDq8108K@PvSSKcQTnkQLmkkHOwLcJheaYK0WinoXLZNSCqcDWXCA1mMONcdfWQucJl8ckWQPqRtXoScSCA8r9jmEwQcj@luPzIAJsPt2UtNqsyfsbkjNBOrclZq2TIJZnRie@o8XTH3mniOYYYc0Wt8jH0/VaE/MWZZfhWzKs8cO72MKRoSeNUJIVtAcED/dcKu/1/) **Unrolled (1159 bytes version):** ``` #define P printf( #define L;P"|\n") #define M;p(18," ") #define D L;B #define N(n)A(n,n+18)D(18)L;p(18,U)L; #define K;P"\\\n")M;P #define C char #define Q;P"|%*c",59,32) C*u, *l, *U="|_____", S[4]; p(n,s)C*s; { P s, --n&&p(n,s)); } b(k) { k=P"| %s",S); P"%*c",6-k,32); } e(s)C*s; { *s++=*l++; *s=*l>96?*l++:0; } A(a,n) { for(;a<n;++a) P a>9?"|%4d ":"|%3d ",a); } B(n) { for(;n--;) b(e(S)); } f() { u=U+1; l="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcDbSgBhHsMtDsRgCnNhFlMcLvTsOgPrNdPmSmEuGdTbDyHoErTmYbLuPaUNpPuAmCmBkCfEsFmMdNoLr"; P" %s%*s\n",u,102,u); A(1,2); P"| %*c",94,32); A(2,3) D(1); P"| %*c",94,32); B(1)L; P"%s%s%*c",U,U,61,32); p(5,u); P"____%s|\n",U); A(3,5)Q; A(5,11) D(2)Q; B(6)L; p(2,U)Q; p(6,U)L; A(11,13)Q; A(13,19) D(2)Q; B(6)L; P"|%s|%s|",u,u); p(11,u); P u+1); p(6,U)L; N(19) N(37) A(55,58); P"\\ 72 "); A(73,87) D(3); P"/ Hf "); B(14)L; p(3,U); P"\\%s",u); p(14,U)L; A(87,90); P"/ 104 "); A(105,119) D(3); P"\\ Rf "); B(14)L; p(3,U); P"/%s",u); p(14,U)L; P"\n")M; p(84,"_"); P"\n")M; P"\\ 58 "); A(59,72) K"/ Ce "); B(13); P"/\n")M; P"\\%s",u); p(13,U) K"/ 90 "); A(91,104); P"/\n")M; P"\\ Th "); B(13) K"/%s",u); p(13,U); P"/"); } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 1562 bytes ``` cls nal w write-host $u="_" $q=" " $a=@('','H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar','K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe','Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr','Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg','Cn','Nh','Fl','Mc','Lv','Ts','Og') function b($s,$x,$y){[console]::setcursorposition($x,$y);w $s -n} function v($n,$m,$i,$p){$x=$n;$i..$p|%{$y=$m;b $_ $x $y;$y++;if($_-gt99){$x++};b $a[$_] $x $y;if($_-gt99){$x--};$x=$x+6}} w (($u*6)*18)-n;w"" 0..8|%{if($_-eq7){w"";w (($u*6)*18)-n;w""}w ("| "*18)-n;w "|";w ("| "*18)-n;w "|";w ("|_____"*18)-n;w "|"} $y=0;0..2|%{7..101|%{b $q $_ $y};$y++};$x=12;$t=$q;0..84|%{if($_-eq61){$t="_"}b $t $x 3;$x++};4..9|%{$y=$_;$t=$q;if($_-eq9){$t=$u};13..71|%{b $t $_ $y}} $y=23;0..6|%{$x=0;0..18|%{b $q $x $y;$x++};$x=103;0..5|%{b $q $x $y;$x++};$y++} $x=18;$y=16;0..6|%{b "\" $x $y;$y++;b "/" $x $y;$y++} $x=102;$y=24;0..2|%{ b "\" $x $y;$y++;b "/" $x $y;$y++} 0,6,102|%{b $q $_ 0} 22,23|%{b $q 18 $_} b $q 102 23 v 3 10 19 36;v 3 13 37 54;v 3 16 55 57;v 21 16 72 86;v 3 19 87 89;v 20 19 104 118;v 21 24 58 71;v 21 27 90 99;v 80 27 100 103;v 3 1 1 1;v 105 1 2 2;v 3 4 3 4;v 75 4 5 9;v 105 4 10 10;v 3 7 11 12;v 75 7 13 18 b "" 0 30 pause ``` [![enter image description here](https://i.stack.imgur.com/r6B9W.gif)](https://i.stack.imgur.com/r6B9W.gif) This approach is not optimal. Can't use tio since this leverages `[console]::setcursorposition`. [Answer] # [SOGL V0.11](https://github.com/dzaima/SOGL), 311 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` f¤o3,hģ_lμgΣ│Τ┐xC‚¦⁽?%□f⁵↕υ/gκ÷⌠‚ξ#.ν⁵‰↕¦δ┌_jυ1ιīΒ=λ←ļ,ξ╚Ƨu≡ā⁄b⅔►<≡7⅛±√‽ε¶&⁶7zV¾UΥY○ΝΚq╬#∫⅜āΡ⁴7‼%Æ«∑+‼Ψ_№QΕ¦→3γ:Ηρ':υy7▒Ξυσ╤ņcΗOī{═─⁷׀Uγlλ№γjΒ%G≤§┐⌠≈δ{oR{ΘKUƨA▒V⁶ ³‘2n '`Δ"²zōdΕ«⅝←╝⅔πφ“'³─◄"³υ≥τk┐?№L‚↑γ°“'³─6«{K;K;A{:I}a}X¹¹Hā;{⁾J6*;J3*;Jl1=@*+l3κ@*ΚΚ"<Ψ:$ō∫ΣO±>⁄‘7nž}"‛‽‛№l№’2n{_"□׀⁵‘čž}"O⁶‛±0±‛¤3¤M¤’2n{_"Ρ8‘ž ``` This took a while. To make this that compact, I've implemented many things into SOGL (most of which were already documentated). Most notably, * "ž", which places an array inside another array at specific coordinates, and * "►" and "◄" - run-length encode and decode. I really thought I had documentated them, but I guess I hadn't. [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=K1klMjcldTIwMzBSWVUldTIwNzAzJXUyMjE5JXUyMjYwJUIxJXUyMTU0JXUyNUNCJTNFJTdEJXUwM0E4JTVEJTI3JXUwMTEzJXUwMTIzJTdFJXUyMTkxMm5jJTNGdS94JTVEWSVBQiV1MDNCRGsldTIwNzgldTAzOTMlMkNfJXUyMTVFJXUyNTE4JXUwMzlBQyV1MjA3NCV1MjE1QiV1MjIxMSV1MjA3NiV1MjE1QyVCMiVCMCV1MDFBNyU1QiV1MjExNiVBMSV1MDNBMSV1MjUwMiV1MDNCQWEldTIxNUUldTAxN0UldTIxNUYldTAxMDElNUJhJXUyNTE0JXUyMDdEJXUwM0JGJXUyNTg4ciUyNyV1MDNDNiV1MDNCMSU3RSV1MjE5MHQlMDklQkRCJXU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ExJXUwNUMwJXUyMDc1JXUyMDE4JXUwMTBEJXUwMTdFJTdEJTIyTyV1MjA3NiV1MjAxQiVCMTAlQjEldTIwMUIlQTQzJUE0TSVBNCV1MjAxOTJuJTdCXyUyMiV1MDNBMTgldTIwMTgldTAxN0U_) (compression (lazily) updated to comply with 0.12) So, overly long explanation ahead: ### First part: setup ``` f¤o3,hģ_lμgΣ│Τ┐xC‚¦⁽?%□f⁵↕υ/gκ÷⌠‚ξ#.ν⁵‰↕¦δ┌_jυ1ιīΒ=λ←ļ,ξ╚Ƨu≡ā⁄b⅔►<≡7⅛±√‽ε¶&⁶7zV¾UΥY○ΝΚq╬#∫⅜āΡ⁴7‼%Æ«∑+‼Ψ_№QΕ¦→3γ:Ηρ':υy7▒Ξυσ╤ņcΗOī{═─⁷׀Uγlλ№γjΒ%G≤§┐⌠≈δ{oR{ΘKUƨA▒V⁶ ³‘2n ...‘ push "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog" 2n split into an array with items of length 2 These are the element names, conveniently already shaped how they should be. '`Δ '` push 118 Δ range - all numbers from 1 to 118 These are atomic numbers "²zōdΕ«⅝←╝⅔πφ“'³─◄ "...“ push 794198124771504466790502538 '³ push 19 ─ base [19] decode - resulting to array [1, 2, 2, 8, 3, 8, 4, 18, 5, 18, 6, 3, 9, 14, 6, 15, 7, 3, 10, 14, 7, 15] ◄ run-length decode Final result: [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] These are the periods, with 9 and 10 for lanthanides and actinides respectively. "³υ≥τk┐?№L‚↑γ°“'³─6«{K;K;A{:I}a}X¹ "...“ push 270687554118568732622432847987 '³─ base 19 decode, resulting in [1, 0, 18, 0, 1, 1, 13, 5, 1, 1, 13, 5, 1, 17, 1, 17, 1, 16, 4, 14, 1, 16, 4, 14] 6«{ } repeat 12 times K;K; get the 1st 2 items of the array below the array (e. g: ..., 13, 5, [1, 1, 13, 5, 1, 17, 1, 17, 1, 16, 4, 14, 1, 16, 4, 14]) A save the array on variable A (so it doesn't get in the way) ..., 13, 5 { } repeat POP times ..., 13 : duplicate the number ..., 13, 13 I increase it ..., 13, 14 and so on (e.g. 5 times, resulting in 6 numbers) ..., 13, 14, 15, 16, 17, 18, [1, 1, 13, 5, 1, 17, 1, 17, 1, 16, 4, 14, 1, 16, 4, 14] a load back the array repeating that all 12 times X remove the array off of the stack ¹ wrap all of those numbers in an array Final result: [1, 18, 1, 2, 13, 14, 15, 16, 17, 18, 1, 2, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] These are the periods, which could be so nicely compressed, because if the atomic numbers are sorted, these are too. ``` ### Second part: loop ``` ¹Hā;{ ¹ wrap all those 4 arrays into one big array H rotate it left [[a, b, c], [["c", 3, 6] So [1, 2, 3], becomes ["b", 2, 5] . Now the sub-array structure is [name, atomic number, group, period] [4, 5, 6]] ["a", 1, 4]] A couple important things about this: - it makes each new sub-array contain all the data from all the arrays at a constant index - it reverses the indexes - a,b,c were given in, but now, in each sub-array, the first items are c, b, a. This is important because the last elements would get drawn first, so everything would appear correctly. See https://gist.github.com/dzaima/221d1792e03d0429e3403cf255c66926 for what would happen if it didn't get reversed. ā; push an empty array below that big array { for each sub-array ⁾J6*;J3*; ⁾ sentence-case the items in the array, ignoring the numbers. Capitalizes the 1st letter of the name J pop get the last item of the array [["Au", 79, 6], 11] 6* multiply it by 6 - the X coordinate [["Au", 79, 6], 66] ; swap, geting the array above [66, ["Au", 79, 6]] J pop get the last item of the array [66, ["Au", 79], 6] 3* multiply it by 6 - the Y coordinate [66, ["Au", 79], 18] ; swap, geting the array above [66, 18, ["Au", 79]] Jl1=@*+l3κ@*ΚΚ"<Ψ:$ō∫ΣO±>⁄‘7nž} J get the 1st item of the array [84, 6, ["C "], 6] [66, 18, ["Au"], 79] [96, 21, ["Lv"], 116] l get length [84, 6, ["C "], 6, 1] [66, 18, ["Au"], 79, 2] [96, 21, ["Lv"], 116, 3] 1= push if [length] = 1 [84, 6, ["C "], 6, 1] [66, 18, ["Au"], 79, 0] [96, 21, ["Lv"], 116, 0] @* get that many spaces [84, 6, ["C "], 6, " "] [66, 18, ["Au"], 79, ""] [96, 21, ["Lv"], 116, ""] + join [84, 6, ["C "], "6 "] [66, 18, ["Au"], "79"] [96, 21, ["Lv"], "116"] l get length [84, 6, ["C "], "6 ", 2] [66, 18, ["Au"], "79", 2] [96, 21, ["Lv"], "116", 3] 3κ do 3-[length] [84, 6, ["C "], "6 ", 1] [66, 18, ["Au"], "79", 1] [96, 21, ["Lv"], "116", 0] @* get that many spaces [84, 6, ["C "], "6 ", " "] [66, 18, ["Au"], "79", " "] [96, 21, ["Lv"], "116", ""] Κ prepend those [84, 6, ["C "], " 6 "] [66, 18, ["Au"], " 79"] [96, 21, ["Lv"], "116"] Κ prepend that in the array [84, 6, [" 6 ", "C "]] [66, 18, [" 79", "Au"]] [96, 21, ["116", "Lv"]] "...‘ push " _____ | ŗ || ŗ ||_____|", replacing ŗ with the correspoding item form the array [66, 18, " _____ | 79 || Au ||_____|"] 7n split that into an array of items of length 7 [66, 18, " _____ ", "| 79 |", "| Au |", "|_____|"] ž set that array at the positions [66, 18] in the array below } end the for-each loop ``` So now the output looks like [this](https://gist.github.com/dzaima/876bae8f14b232bebe4df69f3712b252). ### Third part: Add-ons ``` "‛‽‛№l№’2n{_"□׀⁵‘čž} "...’ } push code page indexes of the chars [24, 19, 24, 28, 108, 28] 2n split into an array of items of length 2 [[24, 19], [24, 28], [108, 28]] { for each sub-array _ push all the arrays contents on the stack [24, 19] "...‘ push "\/\/\/" [24, 19, "\/\/\/"] č split into a char-array [24, 19, ["\", "/", "\", "/", "\", "/"]] ž replace in the mother array at coordinates [e.g. 24, 19] with those chars "O⁶‛±0±‛¤3¤M¤’2n{_"Ρ8‘ž "...’ push code page indexes of the chars [79, 6, 24, 12, 48, 12, 24, 27, 51, 27, 77, 27] 2n split into an array of items of length 2 [[79, 6], [24, 12], [48, 12], [24, 27], [51, 27], [77, 27]] { for each sub-array (implicitly closed) _ push all the arrays contents on the stack [79, 6] "Ρ8‘ push "_____________________________" [79, 6, "_____________________________"] ž replace in the mother array at coordinates [e.g. 79, 6] with that string ``` [Answer] # Bash, 728 bytes Tested on **Ubuntu**, requires **base64** and **xz** programs ``` echo "XQAAgAD//////////wAQF/CEG6nfcFqpw6CdrU+LkV2iM1yxHU1IDYDEgH/atWuFbJGeeBZu5o8S+/6JEYEvLgTKL3JLS1cREFe2iyLK+lMZU9vuTOkuUG6NIz7n9f+iz8j4iMrKqTRVBrSzmeiXXQJA2EEOcgg/Y7Cb6ZjVoTXmo4dAV4bjgMUS0paPWZHNKKZ101VPerG6mof4Rv8UrX/CNmkvxSGG0GKHhaWpHsM6WnTzEU2L8BbDQjYsHlSUzsLj0JdMO8SFR1mlbNtyxZej1s7c4eGy2jBUCq+dCMxFt5W0AOoEHIGKy3zsmqcrJqTnKXVHOUKDiDTel3GaRm3+5fBEc1lXeN1nPli3Id6D1hzIN92eYP4JSrgyrp4t142mJ3U22iTdzO4mctwmjbmdAmFqp8hwIHM4M1n0F6DgfF0bNkROTMRWJC/CQBAkJHARwwol3z2lFsjaReJnTr0rvDvkBfuIPgzjNhFPR2xT55MaN1DKZbPOSsd1r+zZre+XSZD9ViDuGq5xlpmOyiIPRcbNJWpwo7s5mjGkDGtu6+FHygaV5bmTnnGTV0uKtxpSn1MdttXh9CRWTMXBVaIT6RllKQhzgoSUMFbrVQBqKJ/7t7fNouBxhORQRb4DmZJbZ5A1cFhvQflxdHxNkdzZDs7U4DE31j96IhXbO5MirWl2ENWMO1s//QpX8w=="|base64 -d|xz -d ``` ![Script result](https://i.stack.imgur.com/hru9M.png) ## Explanation **[LZMA](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Markov_chain_algorithm)** (Lempel-Ziv-Markov chain-Algorithm) produced about **0,5K archive** with periodic table. It contains **unprintable symbols**, and can't be used directly in console. To use it i encoded it by [Base64](https://en.wikipedia.org/wiki/Base64) ``` echo "base64_string" | base64 -d | xz -d ``` [Stream redirection](https://en.wikipedia.org/wiki/Redirection_(computing)) is used to decode and uncompress archive. ## Tricks To **save** about **30 bytes** i deleted newline and some spaces [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 600 bytes ``` 00000000: c4d5 4572 e430 0040 d17d 4ea1 1bb4 d9ee ..Er.0.@.}N..... 00000010: 5d98 9999 9b86 990f 3ff6 cb2e 1546 2f5e ].......?....F/^ 00000020: a94c 8abe d595 70d4 1ce1 b90f b30c fd0b .L....p......... 00000030: 210e a1f6 190f ef4f 6a9b d9a6 5f64 b6e9 !......Oj..._d.. 00000040: 4e33 9b25 5ef8 f854 d71d ff68 6da9 b933 N3.%^..T...hm..3 00000050: 3ee6 afcf 59b0 64c5 36e3 48c9 303f 08b5 >...Y.d.6.H.0?.. 00000060: a39d c7ce 36ca 312e 7289 935c bc5c f251 ....6.1.r..\.\.Q 00000070: b379 c32d da93 b195 268f 5d5b 9c32 63ce .y.-....&.][.2c. 00000080: 8225 2b25 c3e2 49a8 5de8 3d76 b691 778d .%+%..I.].=v..w. 00000090: 6bbe cb72 30e6 d83b 57bf 5c2a c907 1e77 k..r0..;W.\*...w 000000a0: 2fd9 f6eb 8b18 3361 ca8c 390b 96ac e8d9 /.....3a..9..... 000000b0: 3462 cc84 2933 e62c 940c 73c1 7af5 5c3b 4b..)3.,..s.z.\; 000000c0: 6b5c 5763 3338 ff45 e70f 7657 c799 8ff6 k\Wc38.E..vW.... 000000d0: d8c0 f87b e3ae ab53 27ec e8f6 d5db 8c47 ...{...S'......G 000000e0: bd61 ee72 c967 d7af 5b99 b4a2 3259 c498 .a.r.g..[...2Y.. 000000f0: 0953 66cc 59b0 6445 cfe6 1163 264c 9929 .Sf.Y.dE...c&L.) 00000100: 1956 4fad da7a 7782 32c6 8bce 2fe8 b6ae .VO..zw.2.../... 00000110: f0ea 77f6 edba 73c5 7a7a 1acf e8b9 76a1 ..w...s.zz....v. 00000120: 67d7 3bce 7be7 76e7 354a e6ca e405 cbb0 g.;.{.v.5J...... 00000130: 1f42 a940 9932 63ce 8225 2baa 5745 8c99 [[email protected]](/cdn-cgi/l/email-protection)..%+.WE.. 00000140: 3065 c69c 8592 61cc fe19 b5a3 e64f 422b 0e....a......OB+ 00000150: 84e9 ae0e ce6c 05f5 3459 faaa cc17 25bf .....l..4Y....%. 00000160: 29a9 edb4 9eeb ef9c d770 7460 fcd1 3dee )........pt`..=. 00000170: 5cfd 7065 c9fd e72d 5929 5355 6cd7 6b8b \.pe...-Y)SUl.k. 00000180: a3ba 406d ce82 252b b61b e388 3113 a6cc ..@m..%+....1... 00000190: 98b3 60c9 4ac9 30a9 ccea 8955 9f35 df6d ..`.J.0....U.5.m 000001a0: 55c9 714d d654 1aed 2ba6 e4c2 3757 8d57 U.qM.T..+...7W.W 000001b0: 5d1d b30f 17dd 33a9 e782 3d3c ff43 6177 ].....3...=<.Caw 000001c0: 2ef5 ae2c d97a c692 43d7 fdcf 0f4f eb15 ...,.z..C....O.. 000001d0: f3d4 1173 9f2f b7b1 8b88 3113 a6cc 98b3 ...s./....1..... 000001e0: 60c9 8a9e 2d23 c661 ff8a 795a 75fc 8e4d `...-#.a..yZu..M 000001f0: eb23 2e9e 1bbf f7e1 3861 ab4f 39bf 7eea .#......8a.O9.~. 00000200: c3fd f629 3fba fac5 7977 eeb8 3aff 3db4 ...)?...yw..:.=. 00000210: ae98 e739 36fc 35eb 695b 6f3b 66c2 9419 ...96.5.i[o;f... 00000220: 7316 2c59 d14f 208a 1833 617a f57a ea55 s.,Y.O ..3az.z.U 00000230: f7b5 b2ed 3782 7a9f 9c51 6c44 9331 8ebe ....7.z..QlD.1.. 00000240: 35ee 2af6 d526 777e 41d5 4525 e7ff af08 5.*..&w~A.E%.... 00000250: 7bfc d020 dcf4 b900 {.. .... ``` [Try it online!](https://tio.run/nexus/bubblegum#bVZrb1VVEP3OrxhDiqnAdL8fVERBfBCgIYhNpSD7iQpEBKWhRv46rjk994KJp@nJTXv3OjNrrVlz3qv1ukLNdU/OR0PDWUVKOUVdx05uFE26Vkc9j0HEfPMVK/6S/7nLcp07Q9DA8D0nyrgo1xTwSU2ycwZq1QzS3gUy0wPjEZ9d1@T2zd7jFcMAo2TXKJU6qPvsKaruSLehqQpatarR7Kqijtty@CVvrhXDAsNoNahoPFjLoTHdpFByRQclkJ/BUQ0jE31ydvTgN9x@7lsMBww3rEUbxpMfM9FMHgRE3Qn9JAq9ZFSEr9BdyzuPmX8AxC8vmO2K4YFhxwhUZpvkc1UUXPNkw7DkUstklZ2kUvVEX@DwEXcO/B2ra9s6gvBhc6cW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Zc0xLfpgBMctA8vQMh8MpCFVkKbYbvK5kZY2q/aLtJYQP31j8seVD8mNaWY46YlFNg@UYq8a4/YfOhTJahmVvw@gWQ/JjoTOVjBntxqIOxMmcCdOXPW5@wsADbNETEfa8GPXtT38x31kxJD9GxUkzgIH3hEkzYl3bBKBS0YbN@FsckIn4/JnFUuGDzO/WOszy/mHhrBlgKjvhlFlk9jNIhGvRUJkAEhdLL7vy3vAWEXBl61Mj@VEGgm5EC4yAuq2H4UPGigsTaY6AM4h5nReMHGCMXx/@vj@3fBjJj2g13lIahqxrFG8UqNDJLoqiLI/bKHAbveZLR3xAsmJOoc@DFUPyY0YsdbzywBriiljyxJbFkg7NYQ6thUyjjrO5jSLuvedfizQrxpIfHkNpyrIHTEAqxkFOL@9oRjYN@ChTIdc9Y0VeOHn3Fd/c@aCtkfzAaoW9wC/BU07eoJB7/3dhuSy1vH//Lw "Bubblegum – TIO Nexus") You can reverse this hexdump with `xxd -r`. This is the result of Zopfliing the text 747 times in DEFLATE format. [Answer] # PHP, 758 Bytes After very little chance to golf down my array approach I decide to work only with strings [Online Version](https://repl.it/GpuG/3) ``` $p=($d=str_pad)("",3410,$d("",109)."\n");foreach(str_split("H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg",2)as$k=>$v){!in_array($k,$b=[2,10,18,36,54,86])?:$c++;foreach([" _____ ","| ".$d($k+1,3," ",$k<9?2:0)." |","| $v |",$o="|_____|"]as$m=>$n)$p=substr_replace($p,$m<1&substr($p,-110+$q=(($i=($k>70&$k<86|$k>102?$k-14:$k)-$b[$c-1])+($k!=1?$c<3&$i>1?10:0:16))*6+110*$m+330*($k>56&$k<71|$k>88&$k<103?$c+3:$c),1)=="|"?$o:$n,$q,7);}$p[342]=" ";for($w=5;$w<9;$w++)for($u=0;$u<3;){$p[$l=($w>6?$w+1:$w)*330+128+$u*110]=$j=($w+$u++)%2?"\\":"/";if($w>6)$p[$l+84]=$j;}echo$p; ``` Expanded ``` $p=($d=str_pad)("",3410,$d("",109)."\n"); foreach(str_split("H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg" ,2)as$k=>$v){ !in_array($k,$b=[2,10,18,36,54,86])?:$c++; foreach([" _____ ","| ".$d($k+1,3," ",$k<9?2:0)." |","| $v |",$o="|_____|"]as$m=>$n) $p=substr_replace($p, $m<1&substr($p,-110+$q=(($i=($k>70&$k<86|$k>102?$k-14:$k)-$b[$c-1])+($k!=1?$c<3&$i>1?10:0:16))*6+110*$m+330*($k>56&$k<71|$k>88&$k<103?$c+3:$c),1)=="|"?$o:$n ,$q,7); } $p[342]=" "; for($w=5;$w<9;$w++)for($u=0;$u<3;){ $p[$l=($w>6?$w+1:$w)*330+128+$u*110]=$j=($w+$u++)%2?"\\":"/"; if($w>6)$p[$l+84]=$j;} echo$p; ``` # PHP, 892 Bytes First working solution that is under the byte count of the compress version a solution with arrays [Online version](https://repl.it/GpuG/2) ``` $p=array_fill(0,9,($z=($d=str_pad)("",109)."\n").$z.$z);foreach(str_split("H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg",2)as$k=>$v){if(array_search($k,$b=[0,2,10,18,36,54,86]))$c++;$g=$k>56&$k<71|$k>88&$k<103?$c+2:+$c;$x=$k>70&$k<86|$k>102?$k-14:$k;foreach(["| ".$d($k+1,3," ",$k<9?2:0)." |","| $v |","|_____|"]as$m=>$n)$p[$g]=($r=substr_replace)($p[$g],$n,(($i=$x-$b[$c])+($c<3&$i>1?10:(!$c&$i>0?16:0)))*6+110*$m,7);}for($w=5;$w<9;$w++)for($u=0;$u<3;$u++){$p[$w][18+$u*110]=($w+$u)%2?"\\":"/";if($w>6){$p[$w][102+$u*110]=($w+$u)%2?"\\":"/";}}echo$d(" _____",103)."_____\n";$p[0]=$r($p[0],_____,227,5);$p[0]=$r($p[0],$d("",29,"_____ "),293,29);$p[2]=$r($p[2],$d("",59,"_____ "),233,59);echo join($p); ``` ## PHP, 783 Bytes [Try it online!](https://tio.run/nexus/php#LZFLk5pAGEX/y6wm5cIXoFaSSn00jfIWsBthk0IEhAZ5OgJ/fuJM5Szu4q5O3fv568/vy3SNo6qs27jr3i9hFwvc36/mGr@/2UVdmZIsem5w8nxKWc8BnMV5iuAESAQ4ztPjbJ7M2/nHenQAijGwpoeilGm5EE2k1sJpMdpjCHG1WCxCs/Htlhpku@OpCyZ8sy/vNdyaSpwtyc4OJXufAixAsgG7WRZXczeF/5hWIXqNngnnw4iEDUK@/FgLSilHyPfdRsbOI@uyhQtrBzGs2SIjbmeDA5Jiotgsraxs5Xz0BNPLxg2tN9tHPlTcmmueYyqnJXAliDDke1gmO7asy7a1Ezc3O@nyEaVxn7G7iVi34QWljRzsOD6IRgXQAJ6iyZg01LxcX3EyJqMKkz4bhP1JL0a/u@5WrTvOmvExPtZbNeT7Vbu@50ocVkTvvJncE3rSzjJIck6gXuJDbtx0y2akCdTb0TzuXUamhXKhh3LG/DpR5eWL/kWNnbPhD7k9s7EZDP5LxOCnkpKrmmPG2ISgqSCrvifE6HUhdTKNUq1pdUz65nWBp9QpULpXap82TT991QxokSk7Q6ZyZB2kJEkCt2@9Ply2XqepCSajHxCF1ARTKy4gFVNY3f0ILOWAQUyLj3ln9rPHPFXW9VMXnpxunzDb7I5Dyvrp3GMvyYtnSXYTHt3evYW8hFFtUOM6qjEfHRov3mNlsvzVUcMD7xRk1@VTpcoS1ae9uQQfsM0hhR8McUtFzQlwOGg2qGLoqHLouE4RSi5OWaoqYL2GhVZUVRUfkENC47g9R4xwREUyDfQY3n78@Pn5@Q8 "PHP – TIO Nexus") Only using compressing ``` <?=bzdecompress(base64_decode("QlpoNDFBWSZTWYVVkt4AAXB/gCATACBAAP/gP+/f/r/v3yRAAlyZOzuIImgm0BNCJp6T0yQyaAeo000aNqYQrVMU895VSANAAAAAAGmnpAhqoB+1U9QaDQGgAA0ADQAESiieo/SgAAAAAAAANOlBWqLi6XHyC67CCYFu36ImFcCYYSqFERuisi0SA3RCkEKQBkUSsQARADINCeNmOimrFjyW6NWiy7Vp78ujxo434qwygFgmA4mABAxjGA1f9k1pmrrQfSjNsDbvcgetiknNCks756IrcRERRYABMoAAqAEzczMzKCqgAACqgTMzMoaftix6GTLlyYsd92rSy+qyuyu38Ja5t2r3njIeaoULsW+FtUVTKXFADFjUAp1EHjMhLOQkUqZJhPNPGSkUz0IbVHm+kYpfJF1111ttttpERXMYxjQ+QENZxYzMzM5zmVUdJjEkkkzCAqoAioAAAAAEC4AAVRiKVVKqrLEUtqAAGWIpgAVVGIpYVqqtzEUtqkAVliI9MFVFcOHDfffZStrWta1rWsKJfEUyYZUIUpUEVOelAgBgA2nYcAOIHEABglv/sNt+u/gI3pwL6w4LQTEk79PxgktzXtEWfjlwmU9zEyStSha5DECpMVMdyJe5cHqWeGEIzOY2PKEx5RlU9sjzoJFDVLzGN1AYAEQ4CI5xMB8VBKRZEaxKQAJBaRJFaRSRlaDSEgkgJIAOADFArBJJJEHCRUaMP8XckU4UJCFVZLeA")); ``` ## PHP, 948 Bytes ``` <?=gzinflate(base64_decode("vZbbattAFEXfA/mH+QNrNPdHSb4S35CVtgkGk6ZpWtqmxW0KBX98pTVuKfgCRSh62Mjj2XM4a/aMLTbNI7p+qHJ5sRNCCrHruFi9flor5cYvUm78QDm63LUnujn37KvQnaK6btdj7TWoRR3q0YDKZA9z+rH5mD+0LZejBTpHF+gwjhzAbFXu33VOaUympNm0bXdSoRo1qEUd6vcw53fNx9lj23LZ50ZXbM2SkVXEy3i2PYB5Nl3nn/+AGTiGCQrYFLApcFLgpMBJgZMCJ/UoXoVX4VV4FV6FV+FVdg/zKrYM0tV9oxVAXsXxLaifyBjpLb6SNOYUz43e8u2IFUbMyb6zGu85K1ydgNmhxmMOHAUcBRwNHA0cDRwNHA0cDRwNWI1X49V4DV6D1+A1eI3ewyzf0jgt3wDwlvc54zPQVUAuQVd+IHvvgEaeC94nIF1FxVsBc8Kabw6P+YvANMAxwDFOrOsbDwgOCA6AjjmOOQ6ADoAOgB6AHoAer8fr8Xq8/k8yC1KUk6vpnejVPxbvQcHIa1CUYFkwcwLq5Q9ggncM0orjvARjHg87G5Exs3w6DnPdMUwPHA8cH+ruZNJAkIlBLepQjzYAZfODUqtEU1SheLkzJXem5M6Uf+/MIXBK0GX3zd6VwOzHxAIqJ41jYM6A0+e9jMkkjXPmDEE6I8nTn0Bm5uLxOMxelzAvLw5v900HjzhWqAZp2ENDwC0BtwTcEnBLwC0BtwTccjgs+2/xWrwOr5NifaxQHf+CsC/jjcI9sfzC7qEDIj9ivGJX+7/YT8I+wFUx84Zvp8+id7SjDnbpVEeBlgO4ArgCuAK4ArgCuAK4ArgCRyHhKCQchYSjkKgTHdWNx4uW+F/H/0rfGAFaBpYCzT/xzuEYEOoh4zPAzoE53Z7Yow7Q9X4D")); ``` [Answer] # GW-Basic, 598 bytes (tokenised file) Unfortunately GW-Basic's text mode is limited to 80 columns. I tried squishing the table to make it fit, but that didn't look too pleasing so I had to use a graphical mode instead. Below is the text source, with lines wrapped around at 80 columns for readability; take care that for the program to work it must be saved in code page 437. Should you try it out, you'll find it will flicker **a lot** while it's drawing. Sorry. ``` 0 S$="+#zB¢0(Y%5k%2GkCUq*Y$ù╝%65SÅ.5H8ú¿ÅÅxIö}¥6Ç{NMLòΩ/ΘÉ}òY'=zI⌂úÅ8V├)û;tùU2δY #EJ2$++£╪&Θ}óÉ{,ÇN7àmYƒ+7z)ÆH55<IPmTZ¥KÆûwyHS7┐₧óOk5╕æ┴âTtöPo2KWµÅ[╗%ú##mVWíkàƒ, £q┘6▌òMso⌂/&# 1 SCREEN 9:DIM A%(169):L%=1:FOR R%=4 TO 314 STEP 35:FOR C%=4 TO 604 STEP 35:GOSU B 3:IF K%GOTO 5ELSE GOSUB 3:C%=K%*35+C%:IF I%=118 THEN R%=R%+12 2 NEXT:NEXT:FOR R%=1 TO 3:LINE(109-(R%=3)*490,(R%=1)*82+330)-STEP(0,-68),0:FOR C %=1 TO 3:LINE-STEP(6,12):LINE-STEP(-6,11):NEXT:LINE STEP(0,-35)-STEP(5,0),(R%AND 1)*15:NEXT:LOCATE 23:END 3 IF L%<36 THEN B%=(ASC(S$)-35)*L%+B%:L%=L%*216:S$=MID$(S$,2) 4 K%=B%MOD 36:B%=B%\36:L%=L%\36:RETURN 5 SCREEN,,1:CLS:I%=ASC(MID$("`nn#r",INSTR("9YvG",CHR$(I%))+1))+I%-95:PRINT RIGHT $(STR$(I%),3):PRINT" ";CHR$(K%+64);:GOSUB 3:PRINT CHR$((K%=0)*64+K%+96):GET(0,0) -(23,27),A%:SCREEN,,0:PUT(C%+2,R%+5),A%:LINE(C%,R%)-STEP(35,35),,B:GOTO 2 ``` GW-Basic doesn't save its files as efficiently as it could, so to get it down to 660 bytes you need to open the tokenised file in an editor and manually remove all the spaces but one, the end of file character and the garbage character before it. This will reduce its size to 660 bytes and it will still load and run just fine. **Edit:** Since in this case it doesn't matter that the variables are integers, because the expected error is small and operations like `MOD` and `\` round anyway, we might as well turn them into floating point variables, saving a `%` token on each mention. And I noticed the number `35` occurs often enough that the five bytes it takes to save it into a variable are (just!) worth it. If you've been keeping score, you'll have noticed we saved 43 bytes and the file system agrees: we're down to 617 bytes. **Edit:** By slightly changing `S$` I was able to shave off six more bytes: `(K=0)*64+` became `AND 127`. **Edit:** Okay, so I remembered I wanted to change the way I store empty areas. This shaved off seven more bytes, four in `S$` and three more because `GOSUB 3:` was swapped out for `>9`. And I sacrificed some efficiency for another two bytes. **Edit:** I broke through the 600 byte barrier! It's one thing to get something compact in a golfing language, but another thing to do it in a real-world language. And quite another thing yet if you manage it in GW-Basic of all things. `S$` got five bytes bigger, but I saved nine bytes by replacing `ASC(MID$(...))+I-95` with `I+1` and adding `IF K=1 ... ELSE` on line `1`. ``` 0 S$="|R▐CñföfCσé╕»σε¡┤P╝l½║╙τ/a}µS╦┌]èp┼zµkµ\¢°┴+τ_╞E.₧í3?≥≈ö麵9¬╚O?Ql'zç═┘E}ε (ùRíHM4╥lΦ≥│6Æäb∞O@╗┘Z¿aú{2╚┤6╪╚M1cf▀ùütóQw»ùmÑíφÖ_0$kLô╩╣└u¥å█3Tìzæd±æñk)τW`╫≈å ¿b0sΓlqùV⌐█Ç8& 1 SCREEN 9:DIM A(180):L=1:W=35:FOR R=4 TO 314 STEP W:FOR C=4 TO 604 STEP W:GOSUB 3:IF K=1 THEN GOSUB 3:I=K*2+57:C=C-WELSE IF K>9 GOTO 5ELSE C=K*W+C:IF I=118 THE N R=R+12 2 NEXT:NEXT:FOR R=1 TO 3:LINE(109-(R=3)*490,(R=1)*82+330)-STEP(0,-68),0:FOR C=1 TO 3:LINE-STEP(6,12):LINE-STEP(-6,11):NEXT:LINE STEP(0,-W)-STEP(5,0),(R AND 1)*1 5:NEXT:LOCATE 23:END 3 IF L<36 THEN B=(ASC(S$)-W)*L+B:L=L*216:S$=MID$(S$,2) 4 K=B MOD 36:B=B\36:L=L\36:RETURN 5 SCREEN,,1:CLS:I=I+1:PRINT RIGHT$(STR$(I),3):PRINT" ";CHR$(K+55);:GOSUB 3:PRINT CHR$(K+96 AND 127):GET(0,0)-(W,W),A:SCREEN,,0:PUT(C+2,R+5),A:LINE(C,R)-STEP(W,W ),,B:GOTO 2 ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~1688~~ ~~1667~~ 1664 bytes Probably find some improvements to save bytes. But, got it working so I'm posting it. Thanks mazzy for 21 bytes declaring u. 3 more bytes removing template string and using u directly. ``` data class T(val n:String,val a:Int,val c:Int,val r:Int) val n="H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg" val l=List(118){i->T(""+n[i*2]+n[i*2+1],i+1,when(i){0->1;1->18;2,3->i-1;in 4..9->i+9;10,11->i-9;in 12..17->i+1;in 18..35->i-17;in 36..53->i-35;in 54..56->i-53;in 57..70->i-53;in 71..85->i-67;in 86..88->i-85;in 89..102->i-85;else->i-99},when(i){0,1->1;in 2..9->2;in 10..17->3;in 18..35->4;in 36..53->5;in 57..70->8;in 54..85->6;in 89..102->9;else->7})} val u="_____" fun Int.c()={val t=this when {t<10->" $t " t<100->" $t " else->" $t "}}() fun g(r:Int,c:Int)=l.find{t->t.r==r&&t.c==c} fun b(r:Int,c:Int)={val e=g(r,c) val n=g(r+1,c) if(e==null)Array(3){if(c<2)if(n==null||it<2)" " else " $u " else if(g(r,c+1)!=null)if(n==null||it<2)if(r>7&&c==3)if((r+it)%2<1)" \\" else " /" else " |" else "$u|" else if(n==null||it<2)" " else if((r<2&&c>12)||(r==3&&c>2&&c<12))"_$u" else "$u "} else if(c<2)arrayOf("|${e.a.c()}|","| ${e.n} |","|$u|") else if(r==6&&c==3)arrayOf("${e.a.c()}\\"," ${e.n} /","$u\\") else if(r==7&&c==3)arrayOf("${e.a.c()}/"," ${e.n} \\","$u/") else if(r==8&&c==17)arrayOf("${e.a.c()}\\"," ${e.n} /","$u\\") else if(r==9&&c==17)arrayOf("${e.a.c()}/"," ${e.n} \\","$u/") else arrayOf("${e.a.c()}|"," ${e.n} |","$u|")}() fun p()={val a=Array(30){""} var s=1 for(r in 0..8){for(c in 1..18){val o=b(r+1,c) for(i in 0..2)a[r*3+i+s]+=o[i]} if(r==6)s+=2} a[0]=" $u"+" ".repeat(97)+u a[23]=" ".repeat(19)+"_".repeat(83) a}() ``` [Try it online!](https://tio.run/##5VvvU9vIsv2uv2KWysu1F2Mj/5QgpgqcEFIBQgG7e7PZ1JZsj21VZMlPkkOowN@@7/QZSZaJyd2bvNz34SWUMhrNdPec6Zk@3ex@iNLAD/9q/KwGsfZSPVaTKFbpzE/UKBprNY2CiRrNvCDQ4VTvWbM0XSR7jYZ8lG/1JPVGH/QnDMH3@iiaN/57qZPUj8KkYdvtbqdtXcR@mEKmVhc69qOxP1LX3jDQlvU2WsYr6QpK00gtZHgjWqaLZdqIdbqMQ2NQqj@le5al/pQ/6kf/oRbrTilbqbsfrAvym3iKtpP/iLYTLdq4xLvvh/PPr/3JtMjaWtTd/r4VYm6Hzy6fPT4dPl0@7V2D5Kkvb0f6e7Ud8Tng85zPN3wem56HSH6XtrKcx570SZsrbX7v2uwWn20@O3x2@ezx6Rgkzz15O5t@r7bDQJ5X3JcL9lwZbNl/GD9E8s9v//P3kXR5@nb5JKpNotokMk0i0yQyTSLTJDJNh0/ObXFui3NbnNvi3Bbntji31TVIvjbrJZ5XI3leE41fTX9MnEN6F/12ENHHOGawlOfv/PqSEl5yzGFCaWwfUcLrzUj@wCdPN5FpEZkWkWkTmTaRaROZNpFpE5k2kWkT1Tbntjm3zbkdzu1wbodzO5zbaRskL4dcNdf7luj9zvY5@8@I2zURviRulzN63ZiI0ZMHbL8inlfmybnXRPIVZf5T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YEFTOme2dVVBpcJzvK00ttd/vZkebfSudG@1edK/KwJhQdIiu7uKgCqJW/S9UzyJEmPVmKBdjFRlr/G6uue7KUQr4y@10MyLaHtQrDyidDRzZZYZnHZdCF@W8V0cESoJfEsTe89Pr1Rnk1ZT5aN9dkOZ4OmfqN29yvzv6p@w/i78vg7DgdUuUcv8qPh9QvCRL5EttS3LQSmSlwwpM/yOlqxA06N@sPcj@WzX0R@710soX47eb/dj9757@@tbG@qyXa/eW95iFx98d8vwtUS3xCY@l8PSx5W8RfC0eUyq9UX/2MN/4Mg/l84JGrIQpdBxnXnnh9WvHia7BmK@MyEqwPDdIrlAhgTrikmCCsx@LvEZ5n/1/8A "Kotlin – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~623~~ 610 bytes ``` #define E(a)s[x/18*3+a/7][x%18*6+a%7] #define e(a,b,c)E(a)=E(b)=E(c)= x;char*p="H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg",s[999][110];P(x){e(14,28,42)47,e(7,21,35)92;}main(i){for(memset(s,32,4e3);*p;E(17)=*p++,E(18)=*p++,sprintf(&E(9)," %-2d "+i/100,i),s[i++][-1]=10,e(7,14,21)e(13,20,27)'|',x+=x?i-5&~8?i-58&~32?i-72&~32?1:-67:55:11:17)e(1,2,3)e(4,5,22)e(23,24,25)e(26,(i<6|E(0)&4),1)P(P(P(147)+1)+69)+3;puts(s);} ``` [Try it online!](https://tio.run/##NY5tj6IwFIW/z69o3Oi0UjO2oKis2QDiS0aRAPsyY/xQoGIzgqaVjZt5@esuTnZzk3ueD@eee9JOnqbX65eM70TJgQcZUpvLAxm0dY09mNvNpVlzX2NNc3v338UhwwlO0c099mByWyka312sdM9k@zRuzMGcL4XDHeACH6zBFPjcZ6vcPkQiABFwD7Z8BC6L0lj8AK5clVPuHn3hVs/ljM24rSLuyEcZJpF8As/ST1bHOA2rcB9kdu5mizIqoyTmC/CLu8phS@byQPpZUESFV82yOJn8mR89GRdPybKa72L2E4R8rRYyONvVPI8PQeKI4Gifw3IqQ2an8T5g34F/Ciq7cAvnxd15alqsMv@4lOFukkS5s5@r1Xmiwtwt/f30sEqXv2O1zhtYbYbD4XZDSHdrBfCCXjkkBqYDbFBkmJhDE1OC9R4aUuu9YKKEAr3ujhIWvFD8DBXWKTa4jqz2yfIgMdG4fdI0XOPgH6qTFOV5B1seHCLcAM0OzUBDEw@k28UC1RWEpm03HbIdk@7nx1sDguomOqZdTE10/3aPL9r48k10eq2PwU0GrQ@d1mDSTyCjTt8c9XojQkZ1ifoWU6zXauAeprQGWofVub0b9jEUX/tvHuyiloEwQQG8DTFMpBGk9YdI061TdVZQIev9ev0L "C (gcc) – Try It Online") Thank gastropner for 2 bytes(and more the thought) and cailingcat for 7 bytes [Answer] # Bash + openssl + bzcat, 787 bytes ``` echo 'QlpoOTFBWSZTWU4gJ1IAAWJ/gCARACBAAP/gP+/f/r/v3yRAAlzt0bO4giaaJsgT Uymg0PKAADRpoM00IVqnqhn7ypRAaBkAABpo0AACMqQHtU9QaPUDJoGjQAAAACJR RlH6oAAAAA0AAANMSCuPE35BdLsIJgW7goiXLgTDCVQoiN8VkWiQG+IUghSAMiiV iBIIJQbSowuqP1azrEUckcN2TFkgjzP/NbraQIlwhHiEQoAFArk2cXwzozZiX2Fd oDTrgQ9SNYtUrT6Y12TdAzMzmiIiBMoAAqAEzeZmZlBVQAABV70RDMzM3olunLqr w27cODVi7KDMVsJhVbEN5HVmxiudB3tlkdzOjK62bamumQDNHkDYZJRGomJuEzpZ Rkq6q50aVleQn2z3xsGbI0K++++66664zM70REeHz9AsBWiIiMY1rWAI2Y8qqqqq z1JAQlAhJJJJJQgsYwFUYilaqqrLEUu1AAGWIpcAVVGIpnmcqq3mIpdrIArLER43 K0Vta1rWVK2ta1rWtawomVEUy4ZkIUpUEVMfJWACgBXdpWALEFiAAgnr2YfmfRnx Ec7MD/cMXEaMOGC9smHqfF4imuDpVNjBGUY5rRfAkIWsm1IbjdqdKLXLljKdUEfP dKpdJ0ti+i6yMsj2u51K5QUACIYCI9AqBe9YKKRZEaxKQAJBaRJFaRSRlaDSEgkg JIAOADHArBJJJEHCRUaMP8XckU4UJBOICdSA'|openssl enc -d -base64|bzcat ``` The newlines are required. Outputs the periodic table to `stdout`. [Answer] # Powershell, bytes ~~1077~~ ~~937~~ ~~934~~ ~~906~~ ~~902~~ ~~888~~ ~~878~~ ~~842~~ ~~784~~ ~~688~~ ~~677~~ ~~673~~ ~~667~~ ~~651~~ 596 bytes Port of [Neil's](https://codegolf.stackexchange.com/users/17602/neil) [Javascript](https://codegolf.stackexchange.com/a/114854/80745) ``` filter l{"{0,5}"-f("{0,-2} "-f$_)}filter m{"|$_|"}$z=(,(' '*95)*2+(($u='_'*5)+' '*61+'_'*29)+,(' '*59)*5+'_'*59|m)+,'|'*6+'\','/'*6 " $u"+' '*97+$u -split"H,He LiBe,BCNOFNe NaMg,AlSiPSClAr KCaSc,TiVCrMnFeCoNiCuZnGaGeAsSeBrKr RbSrY,ZrNbMoTcRuRhPdAgCdInSnSbTeIXe CsBaLa,CePrNdPmSmEuGdTbDyHoErTmYbLu,HfTaWReOsIrPtAuHgTlPbBiPoAtRn FrRaAc,ThPaUNpPuAmCmBkCfEsFmMdNoLr,RfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"|%{if(($b=$_-split','|%{(($s=$_-csplit'(.[a-z]?)'-ne'')|%{++$i|l}),($s|l),($s|%{$u})|%{$_-join'|'}})[8]){$a+=$b[3..5]}0..2|%{$b[$_]+$z[$j++]+$b[$_-3]}}|m '' ' '*18+'_'*84 $a|%{' '*18+($s=$z[$j++])+$_+$s} ``` Append `rv i,j,a` to the end of the script to able `restart`. ## Ungolfed ``` # return formated label or number filter l{"{0,5}"-f("{0,-2} "-f$_)} filter m{"|$_|"} # fillers $z=(,(' '*95)*2+(($u='_'*5)+' '*61+'_'*29)+,(' '*59)*5+'_'*59|m)+,'|'*6+'\','/'*6 # output the periodic table rows " $u"+' '*97+$u # transform each label row to array of numbers, labels and separators # insert a filler from $z[$j++] between first and last groups of 3 lines # return 3 completed lines (left+filler+right) # append middle group (Lanthanides and Actinides) to $a if the group is specified -split"H,He LiBe,BCNOFNe NaMg,AlSiPSClAr KCaSc,TiVCrMnFeCoNiCuZnGaGeAsSeBrKr RbSrY,ZrNbMoTcRuRhPdAgCdInSnSbTeIXe CsBaLa,CePrNdPmSmEuGdTbDyHoErTmYbLu,HfTaWReOsIrPtAuHgTlPbBiPoAtRn FrRaAc,ThPaUNpPuAmCmBkCfEsFmMdNoLr,RfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"|%{ if(($b=$_-split','|%{ (($s=$_-csplit'(.[a-z]?)'-ne'')|%{++$i|l}), ($s|l), ($s|%{$u})|%{ $_-join'|' } })[8]){ $a+=$b[3..5] } 0..2|%{ $b[$_]+$z[$j++]+$b[$_-3] } }|m '' ' '*18+'_'*84 $a|%{' '*18+($s=$z[$j++])+$_+$s} ``` [Answer] # [Retina](https://github.com/m-ender/retina), 888 bytes ``` }~~xJ }¶|J1J|~~x>JwHJ|~~x{He@|}|}xJ q____|}w3j4J|x;j6j7j8j9j10 wLi{Be |x{BjCjNjOjFjNe@|}|}|x "w11{12 |x{13{14{15{16{17{18 wNa{Mg |x!l{Si:jSjCl!r@]qq____"w19>0>1>2>3>4>5>6>7>8>9-0-1-2-3-4-5-6 wKjCa{Sc{Ti{VjCr{Mn{Fe{Co{Ni{Cu{Zn{Ga{Ge!s{Se{Br{Kr@"""w37-8-9=0=1=2=3=4=5=6=7=8=9;0;1;2;3;4 wRb{Sr{YjZr{Nb{Mo{Tc{Ru{Rh:d!g{Cd{In{Sn{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3sZbCovGK5bk7tbeQfP1TzNZ03Gdatm15yaW/NqvqqrXDVUU7VUW3VUV5Ur7uQYTiv3spfhAy7kNI9oP6G7Q/8FFzsM5RBrDJ7QeUb/Hr1/MN7h5rE1acoyxfvb@9tpu92W53swad9lthf6kR7xyIjMyIrsyIncyIv8ul7n7E6GNLN0EchtzYMVRitc7nE1x3iGi3/R3eAyx3iF7zP09qx5Tnj7pfF1hSuGYiqWYiuO4iqe4tf0Gq8ZNfMrMBs/BVP8JgZ/B/vKCukK7b@QPuByh84K/TkGG/TyrxZum1Qh/EJVmkxIIfik0iunGr3qpBE8qhNcahBMCgi/UkiwKSI4FBMsSggGtYjJ@SkjxuiWyolEUZIgBtpSeQYdSEYUkj/S6XRiEvQqVYzThD7/f0k4@4xKOm/wJ52I/Q8fH/8B "Retina – Try It Online") [Answer] # C++, 866 bytes ``` #import<bits/stdc++.h> #define S std::string #define R .replace #define F(a,b,c,d)for(a=b;a<c;a+=d) #define G(b)F(i,b,31,1) #define a A[i] int i,j,t;main(){S*A=new S[31];G(0)a="|"+(i%3?S(108,32):S(107,95)+' ');A[0]R(6,95,95,32);A[6]=A[3]R(12,59,59,32);F(j,6,109,6)G(t=1)!t|A[i-1][j-1]^32?t=0,a[j]='|':0;G(22)a=' '+a.substr(0,i<24?j=0:85);F(i,1,31,3)for(t=0;~(t=a.find("| |",t));j=j^56?j^88?j^117?j^70?j+1:89:57:103:71)A[i+1]R(t+3,2,"H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg",j*2,2),a R(t+2,j>8?3:2,(j>98?"":" ")+std::to_string(j+1));G(25)a[1]=a[85]=A[i-9][18]=i&1?92:47;A[24]=" "+S(84,95);i=0;a[0]=a[101]=a[102]=A[3][71]=A[3][72]=A[6][71]=32;G(0)std::cout<<a<<'\n';} ``` Ungolfed version: ``` #include <bits/stdc++.h> using namespace std; string els = "H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"; int main() { vector<string> ans(31, "|" + string(108, 32)); for (int i = 0; i < 31; i += 3) ans[i] = "|" + string(107, 95)+' '; // horizontal lines ans[0].replace(6,95,95,32); ans[3].replace(12,59,59,32); // clear some lines ans[6].replace(12,59,59,32); for (int i = 6; i <= 108; i += 6) for (int j = 1, t = 0; j < 31; j++) if (t|ans[j-1][i-1]!=32) t=1,ans[j][i]='|'; // vertical lines for (int i = 22; i < 31; i++) ans[i]=' '+ans[i].substr(0,i<24?0:85); // remove cells between parts for (int i = 1, j = 0; i < 31; i += 3) { int t=0; while(~(t = ans[i].find("| |",t))) { // find a cell ans[i+1].replace(t+3,2,els,j*2,2); // fill name ans[i].replace(t+2,j>8?3:2,(j>98?"":" ")+to_string(j+1)); // fill atomic number j=j^56?j^88?j^117?j^70?j+1:89:57:103:71; // next cell } } for (int i = 25; i < 31; i++) ans[i][1]=ans[i][85]=ans[i-9][18]=i&1?92:47; // wavy lines ans[24]=" "+string(84,95); // reset the first line of the second part ans[0][0]=ans[0][101]=ans[0][102]=ans[3][71]=ans[3][72]=ans[6][71]=32; // minor edits for (auto i : ans) cout << i << endl; } ``` --- # Python 3, 730 bytes ``` import lzma,base64 print(lzma.decompress(base64.b85decode("T>t=p0RR90|NsC0{{Rpd@Pr$w-*8%~!=Rn5Pm7UVqBC5v9Zg6LfW&}*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3ZiIWVNxXW@NMSn0b4NPbTPO4k@C10qlTAnGZIpmQdEpkcglqmZGrWzLSs1StdDvMEf0T4U@INayvnZrAeTNyRPxZG@HyZL/OhE@NzhP@I/1PS9aydGajfnxnNQAtagR60AyMwAytUQjVshlrYCvUQPB6lnageoT6Znd06Ef4dDWJ8keLzxL3319WxM3eHnam78u8Hy908@v1Kpbv9AaYRmqEFhUhVWvxZ0QFtgAEwARZ/VhWACmgCNADwVOCpwFOBp8Lk3ySDyL/ZOr28xcfDfNyZVNPaPT5OB2Nh6U0a89pN/bOT4ovxvj/Z9y8@2Nf823YV@Pf@TDcz6wkG9wSDC5RABUF4JrOj2E28kbvIF/hkjU9HzhAff6mu8EniLPDHYX0N/qEcJO19gQUaB6ABFwDzCphXwLyi7XmzDxM3wr8i7y937S@ERedP4RafpI1FbeSt6sm@6U6MvL7@Cw "/// – Try It Online") I tried [Answer] # [Canvas](https://github.com/dzaima/Canvas), 289 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ø“^,>ø0pk↶┘?6-wF-c⁶DI2Er„‾⁴┬3n0X{┤Y┘┘{┐┌ω+┤6×y3× 3_×+|2*∔┼(v:“ko±╫JH(:)⇵↙↕l╷-N6 ↶±A)!|¾bki#LOiC0÷1c─↔k⁵IYh╬%÷╶1B--ul@%A%⁵KU/iE╷@L0≤}nJD«↑7E;pMJ2↓Zx^9{t9╴Y0[9◂ ?↙ø╬0N4@⇵║MXh#H«;g→zc-X84]Fk`⁸OO^»^L]U4Z¼e\0w┤∙pjp8←|═9±±→╵Mt⁵L@|On !±b⁹2R⁰‟2n├@ 4×)r32╋∙╋}}“57q‼(„‾;┬3n{┤_×╋}“¾├W↓5„‾X┬2n{┤/\3×↷╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyMDFDJTVFJTJDJXVGRjFFJUY4MCV1RkY1MGsldTIxQjYldTI1MTgldUZGMUY2JXVGRjBEJXVGRjU3RiV1RkYwRCV1RkY0MyV1M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jUwOCV1MjE5MCU3QyV1MjU1MCV1RkYxOSVCMSVCMSV1MjE5MiV1MjU3NU0ldUZGNTQldTIwNzVMQCU3Q08ldUZGNEUlMjAlMjElQjEldUZGNDIldTIwNzkyUiV1MjA3MCV1MjAxRiV1RkYxMiV1RkY0RSV1MjUxQyV1RkYyMCUyMCV1RkYxNCVENyV1RkYwOSV1RkY1MiV1RkYxMyV1RkYxMiV1MjU0QiV1MjIxOSV1MjU0QiV1RkY1RCV1RkY1RCV1MjAxQyV1RkYxNSV1RkYxNyV1RkY1MSV1MjAzQyUyOCV1MjAxRSV1MjAzRSUzQiV1MjUyQyV1RkYxMyV1RkY0RSV1RkY1QiV1MjUyNF8lRDcldTI1NEIldUZGNUQldTIwMUMlQkUldTI1MUNXJXUyMTkzNSV1MjAxRSV1MjAzRVgldTI1MkMldUZGMTIldUZGNEUldUZGNUIldTI1MjQvJTVDJXVGRjEzJUQ3JXUyMUI3JXUyNTRC,v=8) [Answer] # [Python 3](https://docs.python.org/3/), 815 768 bytes ``` q=range u,*D='_' I={(24,18):u} for c in q(102):I[(c<73)*6+3,c]=u i=r=c=0 for Z in('1,c=102,1,,'+'2,c=72,6,,'*2+'18,,'*2+'3,r=%d,14,r=%d,c=18,15,,'*2%(24,15,27,18)).split(','): if'1'>Z:r+=3;c=0 elif'a'>Z: for _ in q(int(Z)):D+=[(r,c)];c+=6 exec(Z) for R,C in D: for X in u*5,str(i+1),'H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[2*i:][:2],u*6: c=C+1 for z in X.center(5):I[R,c]=z;c+=1 if'_'*5!=X:I[R,C]=I[R,C+6]='|' R+=1 i+=1 for r,c in(16,18),(25,18),(25,102): for i in q(6):I[r+i,c]='\\/'[i%2] for r in q(31):print(*(I.get((r,c),' ')for c in q(109)),sep='') ``` [Try it online!](https://tio.run/##VVJhb5swEP2eX@F9qIzB6gppaEfnSeAkTdSEImBbmhRV4DjEagKpgWnttt@eYVJp2hefz/fO93TvHV7rbVn0j8cXItMi570G60MCn2BvSn5p1iU2r5HT/OltSgkYEAV40cwLCznTlcY@X/WRbht9zBLS9ASRhJGLDrlskRo0MSMtGJsYQwNabXZlYbtNdMuA5vX7pY8lOVtj8/IU25ZrbA664llHYICtK0UDnVeHnag1iCFyekBsoAm/LB1pkP6NGgz4rn1L1VsPAEXj6URYFLW2RMgZGmSlScxQcsMMYrcNPzlrKx3lEFOFHra9Kl2opNEHuKqlJgwTYTgBEz4THvcABT64B2Pgcz@d5@4uEgGIAN258g7QNGKx@AaonBdjTktf0GZZ3Ka33K0i7sk7GWaRfABL6WfzMmZhE26DtZvT9bSIiiiL@RQsOK28dJZSHkh/Heyj/ai5XcfZ8HVSjmS8f8hmzWQTp99ByO@rqQxqt5nk8S7IPBGUbh0WYxmmLou3QfoV@Iegcfd07z3Tzaga7@drv5zJcDPMotzbTqp5PazCnBb@drybs9mPuLrP4crShZOsHCvBjW6rhTJCDfN9sW9qO4tzxouaS22g7BAqF7ypxSpQK8QT1AcfyKIr0YR0wbATAn/DFhB2OKFO9WGrirKMaSuhsWYN/kXltpMm4iSnrcZJQ6iB8PHxI1yJMys5fXNC9E3kHKSSXdem5zmvtU52DAFE/xn5E0K44gcCIToe/wI "Python 3 – Try It Online") I particularly like the magic string `1,c=102,...` encoding the layout of the table. Commented: ``` q=range u,*D='_' # I is an ascii art "canvas". I[y,x] = character at that location I={(24,18):u} # Draw (into I) top lines for c in q(102):I[(c<73)*6+3,c]=u i=r=c=0 # Read a magic string '1,c=102...' to construct D. # # After the loop, D = [(0, 0), (0, 102), (3, 0), (3, 6), (3, 72), ...] # # The i'th item in D gives the y,x coordinates of the top-left corner of the # i'th element: # # [(0, 0), (0, 102), (3, 0), (3, 6), (3, 72), ...] # H He Li Be B for Z in('1,c=102,1,,'+'2,c=72,6,,'*2+'18,,'*2+'3,r=%d,14,r=%d,c=18,15,,'*2%(24,15,27,18)).split(','): if'1'>Z:r+=3;c=0 elif'a'>Z: for _ in q(int(Z)):D+=[(r,c)];c+=6 exec(Z) # Draw (into I) the table, excluding slashes for R,C in D: for X in [ u*5, # Draw horizontal line (top) str(i+1), # Draw atomic number # Draw element symbol 'H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[2*i:][:2], u*6 # Draw horizontal line (bottom) ]: c=C+1 for z in X.center(5):I[R,c]=z;c+=1 if'_'*5!=X:I[R,C]=I[R,C+6]='|' # Draw vertical lines R+=1 i+=1 # Draw (into I) the slashes for r,c in(16,18),(25,18),(25,102): for i in q(6):I[r+i,c]='\\/'[i%2] # Print the canvas for r in q(31):print(*(I.get((r,c),' ')for c in q(109)),sep='') ``` ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 699 bytes ``` U,S,P,*I='_ |' Q=range i=0 for N in[2,8,8,18,18,32,32]: A,B,*C=[],[],;I+=A,B,C for _ in Q(N):B+=P,'H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg'[2*i:][:2].center(5);A+=P,str(i:=i+1).center(5);C+=P,U*5 for i in Q(3):I[i][2:2]=[P+S*95] for i in Q(3,9):I[i][4:4]=[P+[U,S][i<8]*59] I+=[S*1+U*84], for i in Q(15,21):I+=[[S]+I[i][6:34]];I[i][6:34]=[] I[2][2]=P+U*5+S*61+U*29 for r in I:r+=P I[21][-1]='' for r,R in zip(I[15:21],I[22:]):r[6]=R[1]=R[-1]='\\/'[i%2];i+=1 for r in[S+U*5+S*97+U*5]+I:print(*r,sep='') ``` [Try it online!](https://tio.run/##VVFbb9owFH7Pr/DLFEi8SwJhYJaHxBSICsGNw7bWtaoETLAGCXLCpE7778yh1dbJR9aRv4s/nXN6bvZV2Rue1OWyhhQSaEW@@QR@m8adr7KyEIb0Pxm7SoEYyJK5cKiPc62eq4sjAwQwhBb2GYe6xpHttw/YAK3qSavAXSfuotD2CTTnYC4WMhQhwNpxBaYgFnG2LIIDlQRQgA@BugU4o5tUfgVYLcupwFUs8fmhnGUzEdRUhOpWJTlV9@BBxfmySjfJOdmTbVDgbVTSkuapiMB3geswW2RYEBVvyZEeb86zbZpPnufVjUqP9/niPN@l2TeQiFUdKdIE53mRHkgeSlIFTVJOVZIFm3RPsjWIT@QcHPEx/IF3N/X0uNzG1UIlu0lOi3A/r5fNpE4KXMb76WG5WfxM61VhMteSiDPk8g8bUTZCdbzuOGjnUDeqI5Evbaf7BsIttLa867zly@R6XRQxyZmrXXxGbGqNPP4fAY5eKX3Uv1KY3iRn8suQW96IG3ohjFqOvbaGfQ7fSh0Puo4WawKj3L6aDFCvz/n4X6/3akTM1Qm4T7SJpyMMWjd3dPVSrVeElM7e8hzO3jvcN80XECYt/EueOhFzPKRhqEku4l2k2ID7CXPa6yp5fPxoMvnO5WNp@85fc0Zffx19bhudE52ULJuOpWAtTvqr7uXyBw "Python 3.8 (pre-release) – Try It Online") Shortest Python solution! Used a similar approach to [the Ruby solution by Lever River St](https://codegolf.stackexchange.com/a/114785/11562). The first loop generates this output and the rest rearranges it and adds the missing lines and slashes. ``` | 1 | 2 | H | He |_____|_____ | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Li | Be | B | C | N | O | F | Ne |_____|_____|_____|_____|_____|_____|_____|_____ | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Na | Mg | Al | Si | P | S | Cl | Ar |_____|_____|_____|_____|_____|_____|_____|_____ | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | K | Ca | Sc | Ti | V | Cr | Mn | Fe | Co | Ni | Cu | Zn | Ga | Ge | As | Se | Br | Kr |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____ | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Rb | Sr | Y | Zr | Nb | Mo | Tc | Ru | Rh | Pd | Ag | Cd | In | Sn | Sb | Te | I | Xe |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____ | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | Cs | Ba | La | Ce | Pr | Nd | Pm | Sm | Eu | Gd | Tb | Dy | Ho | Er | Tm | Yb | Lu | Hf | Ta | W | Re | Os | Ir | Pt | Au | Hg | Tl | Pb | Bi | Po | At | Rn |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____ | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | Fr | Ra | Ac | Th | Pa | U | Np | Pu | Am | Cm | Bk | Cf | Es | Fm | Md | No | Lr | Rf | Db | Sg | Bh | Hs | Mt | Ds | Rg | Cn | Nh | Fl | Mc | Lv | Ts | Og |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____ ``` ]
[Question] [ Given three distinct numbers from \$1\$ to \$7\$, output three other distinct numbers from \$1\$ to \$7\$, that is having no numbers in common with the original numbers. Your code must produce a different output set for each possible input set. That is, no two inputs can produce the same output, treating both as unordered sets. Other than that, you can implement whatever mapping you want. More mathematically, you're asked to give a bijection (one-to-one function) \$f:S \to S\$ where \$S\$ consists of three-element subsets of \$\{1,2,3,4,5,6,7\}\$, such that \$f(s) \cap s = \emptyset\$ for every \$s\in S\$. As a bijection, this mapping has to be invertible, though you don't have to provide the inverse function in your code. [Here are the 35 possible triples](https://tio.run/##RcvBCoMwDADQ8/IVObZMBupBEPoxOrotaJOSxINf323ssHd/9fSX8NAalSrqSJ7VRXYD4DTBlkbgoxgm1IWfOfQd8rWPAA9RtGO1/Dn8b7e7lJV4cRK28K0dbnGGS1Vix53Mw6/F1t4) (written [space-separated](https://tio.run/##RczBCsIwDADQs/mKsFOLYzA9CMK@RDxsUjVuTUqTwfz6avHgB7yX3vYUPpRCMUk2JAvZRBYF4OEE83AEXqPigHnkR3B9i7zvPcBdMuo6afga/rPuJnEiHo2E1VXa4uzPsEuZ2LDBpnsJsbuoZbd5rM1Wh4XU3C/0V1/KBw)). **I/O** The format of the three-element sets is flexible. You can take the inputs in sorted order as three numbers or a three-element list/array/tuple, or as a set. You may not, however, require ordered inputs in a specific order other than sorted. You may zero index. You may also use a sequence of seven bits of which three are on. This seven-bit sequence can also be represented as as a decimal number, byte, or character. Output can be given in any of these formats, with the further allowance that ordered outputs don't have to be sorted. [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda s:([*{*range(7)}-s]*4)[-sum(s):][:3] ``` **[Try it online!](https://tio.run/##VY67bsMwDEV3fQWRiTSaLm5QQIC/xPGg1FIiQA9DpIfC8Lc7Sp0ADcfLc8g7/cotp3Zz3XkLJl5GA6yxb5ammHS1@E3rkYfmi/ojzxGZ9NDrdthcyRG82CI5BwYfp1wEfnK8@GTE58RKFctzEIYO2AqScrlARdMbhq8/H9CSVlBn96rm8CEy0V88FZ8E3WHhVcOyQ@uB/in8acYRZZ6CRa597Ij7guoJZZhrXQw2PVMm6DpoT7TdAQ "Python 3 – Try It Online")** [Answer] # [Python 3](https://docs.python.org/3/), 53 bytes ``` def f(b):c=[*{*range(7)}-b];del c[-sum(b)%4];return c ``` [Try it online!](https://tio.run/##RY5NCoMwEIXX5hSDUIiibiwUKvYi4iKJsQ3oJGTGRSk9u03B0t3H4/2FJz88tvs@2RlmqYur6YfyVUaFdysvxbvWYzfZBcxQ07Ymw@k8dtHyFhHM7tbgI4NjG9n7hYSIlraFCXoYRiFmH4HA4d/RGL9qh4qdR5K/mQra4ioylWJkWVIhMp14lipRiA5Zqgry/pZXoJOkiFIfaEDP3/pjVWQHNCoEi1O6u38A "Python 3 – Try It Online") -3 bytes thanks to FryAmTheEggman -4 bytes by zero-indexing -1 byte thanks to xnor [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9 8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 7RṚḟṙSḊ ``` A monadic Link accepting a list of the three numbers, from \$[1,7]\$, in sorted order which yields a list of other numbers, from \$[1,7]\$, not necessarily sorted. **[Try it online!](https://tio.run/##ASIA3f9qZWxsef//N1LhuZrhuJ/huZlT4biK////WzEsIDIsIDNd "Jelly – Try It Online")** Or see [all 35](https://tio.run/##RY0xCsJAEEWvsoXlNs7MJuAxtJKQ0ibkApbaCN5AG8HaA2Qh2IgHmVxktVh4xcBjePw3HMbxWEq79Xz36eH5tvPpWr7z5@L5uVrOr@F/y@m9CftSum4dg8SgfQwVDUxgA7YVFVdxFVdxDcEQDCHxTXybikJNqAk1oSbUhJpQE2pCTagpC8qCsqAsKAvKgiEYgiGkiv0P "Jelly – Try It Online") (I sorted the resulting values for easier comparison). ### How? ``` 7RṚḟṙSḊ - Link: list A e.g. [2,4,7] 7R - seven range [1,2,3,4,5,6,7] Ṛ - reverse [7,6,5,4,3,2,1] ḟ - filter discard (A) -> B [6,5,3,1] S - sum (A) 13 ṙ - rotate (B) left by (that) [5,3,1,6] Ḋ - remove the leftmost [3,1,6] ``` [Answer] # [R](https://www.r-project.org/), ~~33~~ 31 bytes *Edit: -2 bytes by using modulo `-4` (which returns the negative of modulo `4`)* ``` (1:7)[v<--scan()][sum(v)%%-4-1] ``` [Try it online!](https://tio.run/##ZZDRSsMwFIbv8xTHSkeCyUXXyaBYQfDaF6hFspraQJfUnGTDp69Ny2ZVyNWfP9/5Ttw40qzYs@r0IAQ20lBWVxiO9MTSVOxEVo8Z2ZKckFtwSpyd9gokQhtM47U14C14hR5k30MjUWFB2vJyO1EWujjVlaCRKyJ4d5exOiLnp6g8wgZs8EPwBYnZW8zKxh4Phu55zpbQKQz9lMth6L/otce3vGVX2rlTvlNuFlqQYMLxoByCdAreNXo92cHTyzMY62GYqMp40GY6q3ZBGulp8moSRiYWxWVqVuT3/LqfZjdUmpVLxXWdapOufWPG2GZDe2U@fEeD0Z9B0f@VsswZmzfBzp4v9q1169/9sZouqI7e0YnFfJDo1W8Z3ti@lwOqMuEJ44l4TPiqtpr/tznPGL8B "R – Try It Online") Finds the 4 digits in 1..7 that aren't in the input, and excludes the one corresponding to the input sum (wrapping around). TIO link tests that outputs are unique for each input, and shows output for every input. ``` (1:7) # vector of digits 1..7 [ ] # select elements -scan() # excluding (negative indexes) input v<- # and define v as (negative) input # (so up to here we have the 4 elements that aren't in the input) [ ] # from these, select elements - # excluding (negative index) (sum(v)%%4+1) # the sum of input, modulo 4, plus 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) As [previously advertised](https://codegolf.stackexchange.com/questions/212240/three-other-numbers/212242?noredirect=1#comment499586_212240), I'm a wee bit tipsy so this could well be wrong and, even if right, could probably be golfed a little. ``` 7õ kU k϶UxÍu4 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=N/Uga1Uga8%2b2VXjNdTQ&input=WzEsMiwzXQ) or [view (what I think is) the proof](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=N/UK4DMgyysiIC0%2bICIrVWtEIGvPtkR4zXU0) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~39~~ ~~38~~ ~~34~~ 32 bytes ``` NθI⁻¹²⁷⁺θX²⊟Φ⁷№ETXdhp﹪×℅λX²ι¹²⁷θ ``` [Try it online!](https://tio.run/##TUy7CsJAEOz9ipBqD2JhEERSBoQUpylS2J65QBY29z79/HMDFk4zM8xjXlWYraJSBuNyuufttQTwojuMAU2CXsUEEk2OcGovTTUSK89sP9xrd@HghpTYcdzbzCOpHNTTU6@ubippdSYLE25LhEfQaBQBib8LFOz4fScvfuhKOV/L8U1f "Charcoal – Try It Online") Link is to verbose version of code. I/O is as a 7-bit integer `7..112`. Explanation: The ordinals of the string `TXdhp` have five bit patterns which I have arbitrarily chosen to be such that the result excludes `1`. They are then cyclically rotated until one matches the input, at which point I have determined the excluded bit. This bit is then added to the original input, and finally the difference between `127` and the sum is printed. ``` Nθ Cast input to integer ⁷ Literal 7 Φ Filter on implicit range TXdhp Literal string `TXdhp` E Map over characters λ Current character ℅ Ordinal × Multiplied by ² Literal 2 X Raised to power ι Outer index ﹪ Modulo ¹²⁷ Literal 127 № Count (i.e. contains) θ Input ⊟ Pop matching value ² Literal 2 X Raised to that power ⁺ Added to θ Input ⁻ Subtracted from ¹²⁷ Literal 127 I Cast to string Implicitly print ``` I arbitrarily chose the following five bit patterns to exclude `1` but any five even cyclically distinct patterns would work. ``` T 1010100 X 1011000 d 1100100 h 1101000 p 1110000 ``` [Answer] # JavaScript (ES6), ~~66~~ 65 bytes Takes input as a 3-digit string. Returns a string in the same format. ``` f=(n,k=i=0)=>++k<8?(~n.search(k)||n*43%399%4==i++?'':k)+f(n,k):'' ``` [Try it online!](https://tio.run/##VY@9TsMwFIX3PsVdKtskRNTXSWmKW6UbE0NHxBClLrgJTtWkRUIVrx5yYEAsRz4/n2wfykvZVSd/7G9Du3PDsLcyxLX19k7ZVRTVD/dr@RWSzpWn6k3W6noNN4anvFhMjbU@itZC5LWK9sBULsRQkKXnmeaYZtpAUkgGmY/CyBgZI2NkBtbAGtgUpxSnbBQNQoPQIDQIDUKD0CA0CA1Cg2C0jJbRMlpGy2gNrIE1sGk2f1lOJpvx1UXyXh5lILui8TsUkRBKjV3Vhq5tXNK0r1I8BspJjGWRHFofpKCf0b/N07n/3Wz@NjEJiSi4D9q6Xm5U0vlPh1to57veh6qnS9mcXaeEWg7f "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 [bytes](https://github.com/Adriandmen/05AB1E/Codepage) ``` 7LsKsO(._¨ ``` **[Try it online!](https://tio.run/##RY2xCcMwFAVXUZlCGPzel71AugQygDEhBheuXGipLJAFMkBWUhrBdcfjeHfW13bs7fe5tvleb/VxGZ7fd2vLMuaknLzm1DHAAk7g3NG4xjWucQMhEAKhsBbWqaOoiZqoiZqoiZqoiZqoiZp5MA/mwTyYB/MQCIEQCKXj@gc "05AB1E – Try It Online")** ### How? ``` 7LsKsO(._¨ - (push the input) e.g.: [2,4,7] 7 - push 7 7,[2,4,7] L - range [1,2,3,4,5,6,7],[2,4,7] s - swap top two of the stack [2,4,7],[1,2,3,4,5,6,7] K - push a without bs [1,3,5,6] s - swap top two of the stack [2,4,7],[1,3,5,6] (implicit input swapped in) O - sum 13,[1,3,5,6] ( - negate -13,[1,3,5,6] ._ - rotate a left by b [6,1,3,5] ¨ - remove rightmost [6,1,3] - implicit print top of stack [6,1,3] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~84~~ 83 bytes Saved a whopping ~~16~~ ~~19~~ 23 bytes thanks to the man himself [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved a byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!! ``` p;i;f(m){for(p=i=0;(L"᰸ᨴᘬᤲᔪ"[p]>>i%7&m)-m;p+=++i%7<1);p=(64>>i%7)+m^127;} ``` [Try it online!](https://tio.run/##hZPNjpswEIDveQoLaStYJhI2/yJwqXrrG2xSBIRsLAWCEreljehT9NAH6KFa9VBVPfR1eJLsGMhuUFnVwrJn/M2Ph3E2v8@y87kKeLBRC@202R/UKuShEahvlfbX3/bHn/bbz/b77/brg3JXraKI37ivCm1eBJUe6jpKC6oFVag6Vnem6cU7ytygOfNSkCLhparNTjOCQyryusozka/vViQkJ0oZUMPAaYHnge2A74GLewa2Aa4BngU2A9cBywLmge@Ca4JHwfLB8YFRMF2gJlgUmA0O7n0wbaAIMGAOuGB6wDCG1QRdCtk2OdyS46ci3e/6FJRl/YYta/81TlsBci2bymAmM@flOq/RwuhVWCiiSn2COhrgsgiJHRBdT7QOGEEpQgnRJZhK0JFg@gyO4AzhtIczCbsSzjRyGuGXvFIu4mMu0EalZLEgX@aJhsYXIb0WMi34x0d1QC8bVblZk/6bRwTrkABJgUwZyKCHXHxIdhhzow7xXwBFXlSI9fw0Uua1eK7r9fi45btclS6mLv@UC7/fimJ/FPG@zNFRHKfv@U7wMs7E58FaFnPSQRdcD8dOptGrQmF9pKE2DQ537pYo@p/r5uU/clyWGGno1qeX0zUi9u6lqquJNPBhSmp80Mya8yM "C (gcc) – Try It Online") Takes input as \$3\$ bits set in the least-significant-\$7\$-bits of an `int` and returns the three other numbers likewise. ### Explanation (before some golfs) ``` f(m){ // function taking an integer with // 3 bits set in its 7 lsb // representing the 3 input numbers for( // loop over p=L"ᔪᘬᤲᨴ᰸" // a sequence of 5 int values: // 5418,5676,6450,6708,7224 // that are the 5 unique patterns of // 3 set bits per 7 bits shifted and // repeated over 13 bits so that their // 7th bit is unset: // 5418 = 1010100101010 // 5676 = 1011000101100 // 6450 = 1100100110010 // 6708 = 1101000110100 // 7224 = 1110000111000 ;;++p) // no need to test for stopping // since we must match one for(i=7;i--;) // loop over shift values from 6 to 0 if((*p>>6-i&m)==m) // if a shifted 7-bit slice of one of // our patterns matches m we've found // the correct bit to exclude from m's // 4 unset bits return(1<<i)+m^127; // add that bit to m and flip the 7 // lsb so the 3 other unset bits are // now set to represent the 3 return // values } ``` [Answer] # Ruby, 38 bytes ``` ->s{n=s.sum;(([*1..7]-s)*9)[-n..-n+2]} ``` [Try it online!](https://tio.run/##NYxRC4IwFEbf/RUXfdkEL4REBM0/YhJTJw3mVt7todTfvjTq9TvnfFNoX3EQ11hUNDNW5wfEU1MQz88cjSTPCCmMHAc9kYdyjZOiYDyBgLpJ2K5z9O4msXNjq6302llWclSyu0PvYDFLAvAIW5Jms1mhqCCbh9o0a7qB/93lAvuWKNsnX/kHMFj9RNJvBUJAeYwf) Stealing [Eric's answer](https://codegolf.stackexchange.com/a/212275/98691) which based on [Jonathan's answer](https://codegolf.stackexchange.com/a/212249/65905). I would've commented to Eric, but i do not have enough reputation. The actual difference: Using a range to get the three elemented slice. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` >3-%R7t*5s ``` Takes input as a 3-element list of {0, …, 6}. [Try it online!](https://tio.run/##K6gsyfj/385YVzXIvETLtPj//2gDHQVDHQWjWAA "Pyth – Try It Online") Or see [all 35 inputs](https://tio.run/##K6gsyfj/381dLznUXMGYS8fdzlhXNci8RMu02N39/38A "Pyth – Try It Online"). ### How it works ``` sQ sum of input *5 multiply by 5 t subtract 1 %R7 take each element of [0, that) mod 7 - Q remove elements present in input >3 last 3 elements ``` It’s helpful to preserve symmetry under rotations modulo 7, since that leaves just five equivalence classes to consider. A good starting point is the “average” \$\frac{x + y + z}{3}\$, where division by 3 is the same as multiplication by 5 modulo 7. It happens that if we start walking down from the average minus 2, taking the first three numbers that aren’t in the input set, the five equivalence classes are conveniently mapped one-to-one: * {0, 1, 6} ↦ {3, 4, 5} = {0, 1, 6} + 4 * {0, 2, 5} ↦ {1, 3, 4} = {3, 5, 6} + 5 * {0, 3, 4} ↦ {1, 2, 5} = {0, 3, 4} + 5 * {1, 2, 4} ↦ {0, 3, 5} = {0, 2, 5} + 5 * {3, 5, 6} ↦ {1, 2, 4} = {1, 2, 4} + 0 [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` hṙ_Σ¹`-ḣ7 ``` [Try it online!](https://tio.run/##AR8A4P9odXNr//9o4bmZX86jwrlgLeG4ozf///9bMiw0LDdd "Husk – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 49 bytes ``` sub{@c=grep!/[@_]/,0..6;splice@c,-sum(@_)%4,1;@c} ``` [Try it online!](https://tio.run/##ZZDRaoMwFIbv@xSppJqMmNR2K6gN5AG2y11ZKZvYLpuNWRIvhvjqc8bC6Ni5OXDO938Hjq5N8zDCEx9t99qLip9NrZesEMeSkTWlu9zqRla1qEhsuwsSR7y6J0kuqmHMF8LV1vHLiy485Rgric/3S4YopneHhIUhQ8U63pX4b2M5TPZwE4Zws4fbIVonm4jSKE3TaNIa7wTvrVQoikgIT0jAI8YEzAc90Ps7oKnV2b2hacf5dtqagSOcL7SRyoFAKt25DADRF7c6ryKzqBwOKvjF287NvDC301kCqrZTXjVXQOc0Df6nryDolPzMJu6j/rJoZfAVHb9b7WSr7Bg/PUrrsuzZyYZPb/0B "Perl 5 – Try It Online") Just a translation of the python answer from HyperNeutrino. [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->s{(([*1..7]-s)*9).last(s.sum).first 3} ``` [Try it online!](https://tio.run/##NYxRC4IwFEbf/RUXfdkEL4REBM0/YhJTJw3mVt7todTfvjTq9TvnfFNoX3EQ11hUNDNW5wfEU1MQz88cjSTPCCmMHAc9kYdyjZOiYDyBgLpJ2K5z9O4msXNjq6302llWclSyu0PvYDFLAvAIW5Jms1mhqCCbh9o0a7qB/93lAvuWKNsnX/kHMFj9RNJvBUJAeYwf "Ruby – Try It Online") Ruby port of Jonathan's [answer](https://codegolf.stackexchange.com/a/212249/65905). [Answer] # [Scala](http://www.scala-lang.org/), 64 bytes ``` b=>1.to(7).diff(b).zipWithIndex.filter(_._2!=b.sum*3%4)map(_._1) ``` [Try it online!](https://tio.run/##Zc4xa8MwEAXgPb/iOgTuihHYDhQKDnT04ClDhlCMZJ@IiiMp1iWEhP521@6SIevje3cvdXrQUzA/3Ak02nngm7DvE3zF@FgBXPUA9hNq3/ON@x2fD7WXb6i2r9Fkqm2uJOAHqd5Zi4bU3cW9k@O/VdYNwiO2qi3eKqPS5fRerjd00nHJcpoAMAcJMB@QsGOZiUksCUtSi0rLX0wZWEyzeC4gWhqNjsqGkXV3xDg6L4On1e/0ZJhnRVbSHw "Scala – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes ``` 7ɾ$⊍?∑N$ǔṫ$ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=7%C9%BE%24%E2%8A%8D%3F%E2%88%91N%24%C7%94%E1%B9%AB%24&inputs=%5B2%2C4%2C7%5D&header=&footer=) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ 63 bytes based on the [hyper-neutrino♦](https://codegolf.stackexchange.com/a/212242/80745)'s solution +28 bytes thanks @DLosc ``` param($a)$b=1..7|?{$_-notin$a} $b|%{$s+=$_} $b|?{$_-ne$b[$s%4]} ``` [Try it online!](https://tio.run/##TZJRa8IwFIXf8ysuEmeLnWCS6lOZsB@wMdmTSGklYw5tXdIyRtvf3mWm9Zinc8/9cs5Dcil/tLGf@nTq@Qcl1PSXzGTngGchz5PlYrFunxqePhZldSx41jGet9OG23nC0@vgt5rnO26nat/1HWObgEXBMiIRkQxvUkHGkCvI9SAlWAlWgpVgFQAFQAGI4cZwV4MUaBNoE2gTaBNoE2gTaBNoE2gTaJNIkEiQSJBIkEiQSFAAFAAFIB4lC6mlKTWM3OGZMdmve16e@tloW58qZzy4V/fb62L3un2ubVWeX/Ivfaj2G3///2zL2hy0uzLx/OS2eRvDJkOuX3X3VZbmCUXDwDoWzOri@F3rWTRzX4uGIdyN@OJQ1kVF7mdRMHqtLY2z3q9s6Il9/wc "PowerShell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ∑5*‹ʁ7%⊍Ḣ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%915*%E2%80%B9%CA%817%25%E2%8A%8D%E1%B8%A2&inputs=%5B0%2C1%2C2%5D&header=&footer=) Porting Pyth saves two bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 7LIм{3.$IO(._Dg<£ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3Mfzwp5qYz0VT38NvXiXdJtDi///jzbSMdExjwUA "05AB1E – Try It Online") It's a much longer version of the Jelly answer, so go upvote that too. [Answer] # APL+WIN, 20 bytes Prompts for input of a vector of integers ``` 3↑(-+/¯2↑n)⌽n←(⍳7)~⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##LYyxDsFQFIb3PkXHNpQ45159CR6iqVQkTUlMIowljSsMmCwmmwGLxMKbnBepq/2n/5zv//NFkzQYzKJ0PAziNJpOR3Ep20O/J/mOHVmvkpIl33tBo/25kb0yXzbvzLaemHvoL@24tDNHzNmV4jJv2lrMU8xDiqOY1/8w1xouqGnvlv6eLC0Tp@OSy06dCqmRXWRYJaNn9Iye0StwBa7ANX6Nv1slwUfwEXwEH8FH8BF8BB/BR/Ax9ow9Y8/YM/aMvQJX4ApcV/kD "APL (Dyalog Classic) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [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") ``` 1∘↓+/⌽(⌽⍳7)∘~ ``` [Try it online!](https://tio.run/##LYwxCsJAEEV7T5FSEZHM7CYHsDGVYLxAQGIjaGtjIwQRExQRvIWFtY1HmYvENb5i9zPvf16xXY@Wu2K9WbVtbMeHVbfh2M7vfnhWv9JBYPu2tOpidWPNPZvZ6fB5qlXXcOXzSfgX0yxvyyiOJNLePx3pyYRMu1R6pVd6pXdwB3dwz@25ky4Fn@ATfIJP8Ak@wSf4BJ/gU/bKXtkre2Wv7B3cwR3c//IL "APL (Dyalog Unicode) – Try It Online") This is an atop of a train ``` 1∘↓+/⌽(⌽⍳7)∘~ (⌽⍳7)∘~ ⍝ Right side of the atop ⍳7 ⍝ Range ⌽ ⍝ Reverse ∘ ⍝ Composed with... ~ ⍝ ...without (to remove our arguments) ⌽ ⍝ Rotated by... +/ ⍝ ...the sum of the arguments 1∘↓ ⍝ Left side of the atop 1∘↓ ⍝ Drop leftmost (drop curried with 1) ``` ]
[Question] [ Starting with a positive integer **N**, find the smallest integer **N'** which can be computed by repeatedly dividing **N** by one of its digits (in base-10). Each selected digit must be a divisor of **N** greater than **1**. ## Example #1 The expected output for **N = 230** is **N' = 23**: [![230/2=115, 115/5=23](https://i.stack.imgur.com/z1HEj.png)](https://i.stack.imgur.com/z1HEj.png) ## Example #2 The expected output for **N = 129528** is **N' = 257**: [![129528/8=16191, 16191/9=1799, 1799/7=257](https://i.stack.imgur.com/q4JDw.png)](https://i.stack.imgur.com/q4JDw.png) Beware of non-optimal paths! We could start with **129528 / 9 = 14392**, but that would not lead to the *smallest* possible result. The best we can do if we first divide by 9 is: [![129528/9=14392, 14392/2=7196, 7196/7=1028, 1028/2=514 --> wrong!](https://i.stack.imgur.com/dkp8M.png)](https://i.stack.imgur.com/dkp8M.png) ## Rules * Input can be taken in any reasonable format (integer, string, array of digits, ...). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Test cases ``` 1 --> 1 7 --> 1 10 --> 10 24 --> 1 230 --> 23 234 --> 78 10800 --> 1 10801 --> 10801 50976 --> 118 129500 --> 37 129528 --> 257 8377128 --> 38783 655294464 --> 1111 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~67~~ 61 bytes ``` f n=minimum$n:[f$div n d|d<-read.pure<$>show n,d>1,mod n d<1] ``` [Try it online!](https://tio.run/##XU9BboMwELz7FXvg0Ep25LUNNhXhB31BlAOKobGCHQRNe2j79VKHhhTqw65mNJ6dOVbDqW7bcWwgbL0Lzl98Ep52TWLdGwSwn7ZgfV3ZTXfp6yIph@P5HQK1JVJ/tldFgfvRVy7AFnzVPcND17vwChtoHmGHVFPkVCgqZFxSRWQ4nybSlOc6oyjy9ErFJQw1UmuMO0tTkSuVqT35YARhfoyVgET/w8hXmBOh1oJ4foGFjIRaENqQKdjKMkZcWEZEpsB/HMZfU/iZkZr81rgfSjW5NZolRhtJ7u1uRoiEfY3fh6atXoaRHbruBw "Haskell – Try It Online") ### Explanation: * `read.pure<$>show n` transforms the input integer `n` into a list of digits. * For each digit `d` from this list, we check `d>1` and `mod n d<1`, that is whether `d` divides `n`. * If the checks are successful, we divide `n` by `d` and recursively apply `f`: `f$div n d`. * Altogether, this yields a list of the minimal integers from all sub-trees of `n`. * As the list might be empty, we append `n` to it and return the `minimum` of the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ÷DfḶ߀Ṃo ``` [Try it online!](https://tio.run/##y0rNyan8///wdpe0hzu2HZ7/qGnNw51N@f@P7jncDmS7//9vqKNgrqNgaKCjYGQCxMYghrEJSMTCwABCAZWYGliamwF5RpamYFEgbWQBAA "Jelly – Try It Online") ### Alternate version, much faster, 9 bytes ``` ÷DfÆḌ߀Ṃo ``` [Try it online!](https://tio.run/##y0rNyan8///wdpe0w20Pd/Qcnv@oac3DnU35/4/uOdwOZLv//2@oo2Cuo2BooKNgZALExiCGsQlIxMLAAEIBlZgaWJqbAXlGlqZgUSBtZKGjYGFsbm4IYpiZmhpZmpiYmQAA "Jelly – Try It Online") ### How it works ``` ÷DfḶ߀Ṃo Main link. Argument: n D Decimal; yield the digits of n. ÷ Divide n by each of its digits. Ḷ Unlength; yield [0, ..., n-1]. f Filter; keep quotients that belong to the range. ߀ Recursively map this link over the resulting list. Ṃ Take the minimum. This yields 0 if the list is empty. o Logical OR; replace 0 with n. ``` [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` f=lambda a:min([f(a/k)for k in map(int,`a`)if k>1>a%k]+[a]) ``` [Try it online!](https://tio.run/##RY/basMwDIav16fQTcFmgvoQx06hfZEQVq2taUjjhCa72NNnsilMF7/0w6fT/Ls@pmS2LZ6eNH7fCOg49km0UdBhkHF6wQB9gpFm0acVL3SRfYThrM@0H7rPljq5rfdl/brScl/gBK3QqCUKX1Qr1IqzqYo1VqGxpajQhwIEpd5oUNyalZ1Tja9R68KYxjFk/bs2AY3LJljvNTsbfMhTa@dMU1U1L@OQ3S7fn35GhGV65jf@Lz3uPuYXfwRRMCALsf0B "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~52~~ 47 bytes Competing for the non-exotic languages group! (Note: a good idea, if not golfing, is to add `.uniq` after `.digits` because all similar branches have similar results) ``` f=->n{n.digits.map{|x|x>1&&n%x<1?f[n/x]:n}.min} ``` [Try it online!](https://tio.run/##bc7LDoIwEAXQvV/RxMgO7PRBW6P4IYSFxmBY0BAfSQ3w7TVtgRRjl@d27szjff1YW5/SQvc6uzX35vXM2kvXD2YwBSSJ3pkjnOtS70110GPWNnq0HapLqNAWzS9NCwQbx@I/A47cM/ZO2K8HptF/x4ROztYu5FQv8TIRb5UYVuzARxwrka8imKqI4kuXC6hYnMjICQ@BpELAnPgBKWQ4N@ecKMZyf3RYAmC/ "Ruby – Try It Online") ## Explanation ``` f=->n{ # Function "f" n -> n.digits # n's digits (in reverse order (<- doesn't matter)) # fun fact: all numbers always have at least one digit .map{|x|# Map function for every digit "x" -> x>1&& # x is 2-9 and n%x<1 # n mod x == 0, or, "n is divisible by x" ? f[n/x] # then recursively find smallest of f[n/x] : n # otherwise: n (no shortest path in tree) }.min # Smallest option out of the above # if we reach a dead end, we should get n in this step } ``` [Answer] ## [Common Lisp](https://common-lisp.net/), 136 bytes ``` (defun f(n)(apply 'min(or(loop for z in(map'list #'digit-char-p(write-to-string n))if(and(> z 1)(<(mod n z)1))collect(f(/ n z)))`(,n)))) ``` [Try it online!](https://tio.run/##RU/LTsQwDLzzFaNFqI60FUlfSRHiWwh9LJHaJOpmBexhf724ZSVycDz2jO3pJneO60r9MF48RvKCbIzTD7LZeQoLTSFEjGHBFVyYbcxYkfCY9e7kUt592iWP9LW4NOQp5Oe0OH@CF8KNZH1PbyxUgl5pDj08rkIJ0YVpGrpEIz3vJSHe6cgSIdb/fWTxIXgnMiLFI0B6j0pCSf6LUqIo96SCNnvHSHnnGMmaLTKqZasbKLVzirZmUqnveWFQ1BswpdaKUWm02aY2dV20VdVULFR88wP21wcQXzfbhISD8/GSXnCzRwzfkS0N/R86h@mSXPAbuj0dwF5YB7tZ/AU "Common Lisp – Try It Online") **Readable version:** ``` (defun f (n) (apply 'min (or (loop for z in (map 'list #'digit-char-p (write-to-string n)) if (and (> z 1) (< (mod n z) 1)) collect (f (/ n z))) `(,n)))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` Dðḍ>Ị{ DxÇ⁸:߀µÇẸ$¡FṂ ``` [Try it online!](https://tio.run/##ATgAx/9qZWxsef//RMOw4biNPuG7insKRHjDh@KBuDrDn@KCrMK1w4fhurgkwqFG4bmC////ODM3NzEyOA "Jelly – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes -7 bytes thanks to Misha Lavrov. ``` Min[#0/@(#/IntegerDigits@#⋂Range[#-1]),#]& ``` [Try it online!](https://tio.run/##HYm9CsIwFEZf5dKAKNySv9akg5LBxUFQ19IhSBozNEONk7i4@pa@SIwu53C@b7Lp6iabwsXmETb5EGJPGDVLQvcxOe/mXfAh3Qz5vF9nG73rSc2HFZJhkY9ziKknCBXUW6gQTvfgkhlNOYEaeHBUyBmKBoUskk0pzdifHFvWqTVy0bW/qUho1FIpLvQzfwE "Wolfram Language (Mathematica) – Try It Online") [Answer] ## JavaScript (Firefox 30-57), 49 bytes ``` f=n=>Math.min(...(for(c of''+n)c<2|n%c?n:f(n/c))) ``` ES6-compatible version, 52 bytes: ``` f=n=>Math.min(...[...''+n].map(c=>c<2|n%c?n:f(n/c))) ``` ``` <input type=number oninput=o.textContent=f(this.value)><pre id=o> ``` Originally I tried filtering out irrelevant digits but it turns out to be slightly longer at 54 bytes: ``` f=n=>Math.min(n,...(for(c of''+n)if(c>1&n%c<1)f(n/c))) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 33 bytes ``` {⍬≡d←o/⍨0=⍵|⍨o←1~⍨⍎¨⍕⍵:⍵⋄⌊/∇¨⍵÷d} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71rHnUuTAEy8/Uf9a4wsH3Uu7UGyMgHihjWARmPevsOAYmpQHErIH7U3fKop0v/UUc7SHTr4e0ptUCTFIyMDbjSFAyNLE2NLIAMM1NTI0sTEzMTIPvQCgVDBXMFQwMFIxMgaWFgACYNAQ "APL (Dyalog Unicode) – Try It Online") **How?** `⍎¨⍕⍵` - grab digits of `n` `1~⍨` - excluding `1`s `o/⍨` - filter by `0=⍵|⍨o` - divisibility of `n` by the digit `⍬≡...:⍵` - if empty, return `n` `⌊/` - otherwise, return minimum of `∇¨` - recursion for each number in `⍵÷d` - the division of `n` by each of the digits filtered above [Answer] # [Kotlin](https://kotlinlang.org), ~~100~~ 99 bytes ``` fun f(i:Int):Int{return i.toString().map{it.toInt()-48}.filter{it>1&&i%it<1}.map{f(i/it)}.min()?:i} ``` ## Beautified ``` fun f(i:Int):Int{ return i.toString() .map { it.toInt()-48 } .filter { it >1 && i % it < 1} .map { f(i/it) } .min() ?: i } ``` ## Test ``` fun f(i:Int):Int{return i.toString().map{it.toInt()-48}.filter{it>1&&i%it<1}.map{f(i/it)}.min()?:i} val tests = listOf( 1 to 1, 7 to 1, 10 to 10, 24 to 1, 230 to 23, 234 to 78, 10800 to 1, 10801 to 10801, 50976 to 118, 129500 to 37, 129528 to 257, 8377128 to 38783, 655294464 to 1111) fun main(args: Array<String>) { for ( test in tests) { val computed = f(test.first) val expected = test.second if (computed != expected) { throw AssertionError("$computed != $expected") } } } ``` ## Edits * -1 [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆDḊfD :Ç߀µÇ¡FṂ ``` **[Try it online!](https://tio.run/##y0rNyan8//9wm8vDHV1pLlxWh9sPz3/UtObQ1sPthxa6PdzZ9F/ncLsKUMT9/39DHXMdQwMdIxMdI2MgZWwC5FkYGIBJQx1TA0tzMx1DI0tTkBCQMrLQsTA2Nzc0sgAA "Jelly – Try It Online")** I must admit that the `߀` part is borrowed from [Erik's answer](https://codegolf.stackexchange.com/a/151850/59487). The rest is developed separately, partly because I don't even understand how the rest of that answer works anyway :P. ### How it works? ``` ÆDḊfD ~ Helper link (monadic). I'll call the argument N. ÆD ~ Take the divisors. Ḋ ~ Dequeue (drop the first element). This serves the purpose of removing 1. fD ~ Take the intersection with the decimal digits. :Ç߀µÇ¡FṂ ~ Main link. Ç ~ Apply the helper link to the first input. : ~ And perform element-wise integer division. Ç¡ ~ If the helper link applied again is non-empty*, then... ߀µ ~ Apply this link to each (recurse). FṂ ~ Flatten and get the maximum. ``` \*I am pleasantly surprised that `¡` works like that on lists, because its normal meaning is *apply this **n** times*. After Dennis explained why `߀` doesn't need a conditional, we have this [12-byter](https://tio.run/##y0rNyan8//9wm8vDHV1pLlxWh9sPz3/UtObhzqYT6//rHG5XAXLc//831DHXMTTQMTLRMTIGUsYmQJ6FgQGYNNQxNbA0N9MxNLI0BQkBKSMLHQtjc3NDIwsA), or his 8 byte version :P. [Answer] # [R](https://www.r-project.org/), ~~101~~ 98 bytes ``` f=function(x,e=(d=x%/%10^(0:nchar(x))%%10)[d>1])"if"(sum(y<-which(!x%%e)),min(sapply(x/e[y],f)),x) ``` [Try it online!](https://tio.run/##DcjtCoIwFAbga0kYvAcWOiGoaN6IGMjcYYNc4gedXf3y@fmspbDlI7k9fhNEe4vJiqqVad5onsmFcYUQqTOonzozUBW5wnbMyK/rL0QXcBGlPJGeY8I2LssnQ2rf50HzuUKFYdrHrb1T@QM "R – Try It Online") A ton of bytes go into extracting the digits and which ones divide `x`; perhaps another approach is necessary. [Answer] ## Excel Vba, 153 bytes First ever code-golf in the only language I know :( Not exactly golf-friendly... ``` Function S(X) S = X For I = 1 To Len(CStr(X)) A = Mid(X, I, 1) If A > 1 Then If X Mod A = 0 Then N = S(X / A) If N < S And N > 0 Then S = N Next I End Function ``` Call like this: ``` Sub callS() result = S(655294464) MsgBox result End Sub ``` I haven't a clue where to test this online. [Answer] # Perl 5, 87 + 1 (`-p`) = 88 bytes ``` $r=0,map{$\=$_,$r++if!$\|$_<$\;for$i(/[2-9]/g){$_%$i||$h{$_/$i}++}}$_,keys%h;$r&&redo}{ ``` [try it online](https://tio.run/##DcvdCsIgGAbgawnejcINY@hgrF1JhgS59tGP8q2TUG8929lz8gTHT10KeDo2r2uIMBNsAxaC5h1Mgj3BjLNn0F6eu3a4yPshwlaglLBskqAsRM5be7jvWi0juK7Z3XyOpfRad4NSvfr58CH/Xksb/g) [Answer] # PHP, 120 bytes ``` <?php function f($n){$r=array_map(function($x)use($n){return$x>1&&!($n%$x)?f($n/$x):$n;},str_split($n));return min($r);} ``` [Try it online!](https://tio.run/##VZHdboMwDIXveQqvYh1IdCPhJ2Gs7YMwVCEEAmkFlASpU8WzMwdKYbmx/Z0cO1a6qhvHr3NXdVD2Ta7qtoHSMhv7bopjJkT2e7lmnbVolnmze1lMF0ShetGYtxPZ71@QvKJ21t4PTD7NJh4cqcRFdj@10gY7nh1wrbGPsONhNFUhlYQjJAbgSYgDJHXmnG1y4mLhLhX1NxL1UKPeWqLI@GrkrvuvEXf1EB0WFrgRC5GR1UWjQNs8tiWU46DgibjHGNHM44w/54dBQCPfD/UT8aRGGhtG2YoiyyuwHvtmEqbMhvvkKvKqnUmCS8IbwOFwAozv@i8e3HZg993sYjCG8Q8) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes ``` f(n)=vecmin([if(d<2||n%d,n,f(n/d))|d<-digits(n)]) ``` [Try it online!](https://tio.run/##HY3bCsIwEER/JRSEBLaY@wWqP1J8KMaWgIZQiyDk3@PGlz07u8NMWfY0bqW1lWZ2@Tzur5TpnFYaJ1lrPkXIgK9zZKzGaYxpS8cbrTfWllKeX5rJeCVlT/nAdehiID2LASGzAAeCg9QgFUJpVJ7z/xRgeHAWhAymnxDSg1fOCaQ1RgatrcaiHw "Pari/GP – Try It Online") ]
[Question] [ Fed up with the reliability of flash storage, you decided to store all your programs on one of those good old 1,440 KiB floppies. However, after copying not even 3,000 programs, the disk was full. How's that even possible? Skilled in the art of code golf as you are, most of your programs aren't even 100 bytes long, so there should be plenty of room left... After asking about it on Super User, you discover that you have been wronged by the file system's [cluster size](https://support.microsoft.com/en-us/kb/140365), an evil plot of the designers of [FAT12](https://en.wikipedia.org/wiki/File_Allocation_Table) that leaves a significant portion of your floppy unused and forces you to buy more than you actually need. Buy more floppies? Never! Cluster size will be less of an issue if we simply save multiple programs in one file, which is possible because different compilers/interpreters will behave differently for the same source code. ### Task Write a polyglot that fits in a single cluster (512 bytes or less) and solves as many of the following tasks as possible. [string](/questions/tagged/string "show questions tagged 'string'") 1. Read all input and print it. 2. Print **Hello, World!**. 3. Read a line/argument (**name**) as input and print **Happy Birthday, [name]!**. 4. Read all input and print **I love tabs!** if it contains one or more tabulators (0x09) and **I hate spaces!** if it doesn't. 5. Read two lines/arguments and print a truthy value if the second is a substring of the first and a falsy value if not. 6. Read a line/argument and print a truthy value if its characters are in strictly ascending order and a falsy value if not. 7. Read a line/argument and a character and print the indexes of all occurrences of that character. 8. Read a line/argument and print any of the characters with the highest number of occurrences. [math](/questions/tagged/math "show questions tagged 'math'") 9. Read two integers between **0** and **255** and print their sum. 10. Read a single integer between **0** and **255** and print the quotient and residue of its division by **7**. 11. Read a single integer between **1** and **255** and print a truthy value if it is a composite number (neither 1 nor prime) and a falsy value if not. 12. Read a single integer between **1** and **255** and print a truthy value if it is a power of 2 and a falsy value if not. 13. Read two integers between **0** and **255** and print the larger one. 14. Read a decimal integer between **0** and **255** print its hexadecimal representation. 15. Read a single integer between **0** and **255** and print its Hamming weight (number of 1-bits). 16. Read a single integer **n** between **1** and **13** and print the **Fn**, the **n**th [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number). For example, for the input `13`, print `233`. [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") 17. Read a line/argument of input and frame it. For example, for the input `Programming Puzzles & Code Golf`, print this: ``` +---------------------------------+ | Programming Puzzles & Code Golf | +---------------------------------+ ``` 18. Read a rectangular block of characters and rotate it a quarter turn clockwise. For example, for the input ``` tye xll epb tma id sa s e i r hsn Tiu ``` print this: ``` This text is simply unreadable ``` 19. Read an integer between **1** and **40** and print a diamond of that side length. For example, for the input `3`, print this: ``` /\ / \ / \ \ / \ / \/ ``` 20. Print this: ``` ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ ....@@@@....@@@@....@@@@....@@@@ @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... @@@@....@@@@....@@@@....@@@@.... ``` ### Scoring The answer that manages to incorporate the highest number of programs in a single file that fits in a single 512-byte cluster wins. Ties are broken by byte count (lower is better). ### Additional rules * For each task you claim for your score, the same file (byte per byte) must constitute a full program – in a language of your choice – that solves this particular task. * Each task has to be solved in a different language. Languages count as different if they are not different versions of the same language. For example, there's only one JavaScript, one Python and one TI-BASIC, but C, C++, Octave and MATLAB are four different languages. * The selected language for each task has to satisfy our usual definition of [programming language](http://meta.codegolf.stackexchange.com/a/2073). In addition, the language must have been published and implemented before September 9, 2015. * Your compiler/interpreter may not require any non-standard flags to produce the expected behavior. Exceptions to this rule include flags required to specify a particular language, to read the program from a (single) file or to suppress a banner. * The input for each task will consist of printable ASCII characters (0x20 to 0x7E), tabs (0x09), and linefeeds (0x0A), and it will not exceed **255** bytes in length. * All *integers* can be read in decimal or unary, unless stated otherwise in the task. * Behavior for invalid input is undefined. * You may read input from STDIN (or its closest alternative) or as command-line arguments. If a task requires reading two pieces of input, you can read them – in any order – separated by a one-byte delimiter of your choice, as separate command-line arguments or one from STDIN and the other as command-line argument. If one of the input pieces is a line, the only possible delimiter is a linefeed. * Print the output to STDOUT (or closest alternative). All output to STDERR will be ignored. * For each task, standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. In particular, this includes the <http://meta.codegolf.stackexchange.com/q/1061>, with the exception of *hard-coding the output*, which is explicitly allowed for this challenge. [Answer] # ~~7~~ ~~8~~ ~~9~~ 10 languages, ~~398~~ ~~431~~ ~~447~~ 507 bytes This is probably the most I can fit in the current solution. ``` #if + 0+0/*^",v +- '[.,][[" ,yadhtrib yppaH"l?!;offf4+ + +0.0 +aa<*/ a=0--0;b=input();print(sorted(set(b))==list(b));[["""" ^ < print("Hello, World!")--[[vv? +< #endif/* >.!0 + +1ffr"!"~< */ #include<stdio.h>/*>:1 +?!^>i:1^*/ int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1//**/1==2 ){printf("%x",/*>&:7/.7%.@*/i);}else{for(;--i-1>0;a=b,b=c)c=a +b;printf("%d",b);}}/*]]--"""]];#@;_J + + \+*\-hhlz \+s[\|dzd\|)J "` + +,*.]]]*/SSSTNSSNSNSTNTTTTTSSSTNSNSTNTTTTTTSSTNTTSNSSNNSSSNTTTTNSTNNNN ``` The last line contains Whitespace code encoded so that SE doesn't eat it. To run the code, replace all `S` with spaces, `T` with tabs and `N` with newlines. ## C89, task 16 Here's what the compiler sees: ``` int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1/ 1==2 ){printf("%x",i);}else{for(;--i-1>0;a=b,b=c)c=a+b;printf("%d",b);}} ``` Everything else is stripped as comments or inside the `#if 0`. ## C++, task 14 I used a trick stolen from [here](https://codegolf.stackexchange.com/a/55989/30164) to differentiate between C89 and C++. ``` int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1 ){printf("%x",i);}else{for(;--i-1>0;a=b,b=c)c=a+b;printf("%d",b);}} ``` ## Lua, task 2 Here's the basic structure. ``` #comment a=0--comment print("Hello, World!")--[[ ... multiline comment ... ]]--comment ``` ## Brainfuck, task 1 I just had to ensure no infinite loops or stray `.,`s are found. Lua's multiline comments also double as BF comments. Everything apart from the first 2 characters is a large NOP loop. ``` ++,+-[.,][[,+++.+<--[[<,--[[+<>.++<<.>>+>,,,,,>..--->,+,]]--]]+++-+[++,.]]] ``` ## Python, task 6 Again, I'm using language-specific features to NOP or comment out the other code. ``` #comment a=0--0;b=input();print(sorted(b)==list(b));[[""" ... multiline string ... """]];#comment ``` ## Pyth, task 17 Pyth is nice for this thing. It takes the first `#` as a `while True:` loop *that exits silently on error*. So, I just make most of the code a string (as to avoid `;`s ending the loop early), then just end the loop, exit another created by the Python comment and do the task. Here's it with all non-empty strings replaced with `" string "`, it's still functionally equivalent: ``` #if + 0+0/*^" string " ,yadhtrib yppaH" string """" string "Hello, World!" string "!" string "%d" string "%x" string "%d" string """]];#@;_J + + \+*\-hhlz \+s[\|dzd\|)J " string ``` ## ><>, task 3 This one is very interesting. The execution bounces around in the code, using jumps where necessary to get around obstacles. The relevant parts: ``` # v " ,yadhtrib yppaH"l?!;offf4+ + +0.0 +aa<*/ i ^ < ! vv? +< >.!0 + +1ffr"!"~< >:1 +?!^>i:1^ ``` ## [Starry](http://esolangs.org/wiki/Starry), task 9 Here I had to start going into the "discard all characters except " languages. Anything else stripped out, it looks like: ``` + +*, + '., , + + +. +* , +* . + + *.* +* ,,,,**,*..*, +,* + + +* + ` + +,*.* ``` The code skips most of the punctuation with a jump to avoid a hard time, just using the start and end of the code. The code is functionally equivalent to ``` + +*, + + +,*.* ``` ## Befunge-98, task 10 Works similarly to the ><> one. Luckily, `#` is a mirror in ><> and a skip in Befunge, so we can implement different behavior. Also, `0/0 == 0`. ``` #if + 0+0/*^ >&:7/.7%.@ ``` ## [Whitespace](http://esolangs.org/wiki/Whitespace), task 13 This was the last thing I fit in. The first few lines are just pushing zeroes onto the stack, as they only contain spaces and newlines from the "normal" code. The code is encoded; replace all `S` with space, `T` with tabs and `N` with newlines. ``` SSSSSSSSSSSSSSSN SSSSSSSSSSSSSSSSSSN SSN SSSSSN SN SSN SSSSSSSSSSSTN SSN SN STN TTTTTSSSTN SN STN TTTTTTSSTN TTSN SSN N SSSN TTTTN STN N N ``` [Answer] # 12 languages, 418 bytes ``` "1\"# &&+.@\""" "" " #= '''' <<s ""'("']0=~2base{+}*} ? :_7/!\_7%!@ " R"Happy Birthday, "[?S"!"*" >0[0>i:0(?v:{)?v0n;\!/ $'main';n1< .95< \@-[I love tabs!]o# \ >qi---@ ( @-[ ]e<''';print hex( input())#-[I hate spaces!]o#"]];ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"))?(!?) '''=#print(([1 1;1 0]^int(readline()))[1,2]) #= Tr is here. >Tr, Hello, World! >X Tr s l=gets a='+-'+?-*~/$/+'-+' puts a+' | %s | '%l+a#=#.91<0#'''#"; ``` This is a fun challenge. It's getting hard to fit more languages in, but with this many bytes left I could probably do about one more. Makes gratuitous use of 2D languages. Note that the char on between the `[ ]` on the `@-[ ]e<` line is a tab. Also, this requires `\n` line endings for TRANSCRIPT to work. ## [Prelude](http://esolangs.org/wiki/Prelude) (Task 1 / Cat) ``` ( )?(!?) ``` `?(!?)` is just a direct translation of `,[.,]` in BF. Prelude `()` loops act like BF `[]` loops, so everything from the `(` in the leftmost column to the `)` before the core program is unexecuted. Prelude's syntax rules mean that parentheses need to be matched (reading left-to-right column-wise), and there can only be one parenthesis per column. Other than that, it's a pretty easy language to fit in. Make sure `NUMERIC_OUTPUT` is set to `False` if you're using the Python interpreter. ## [TRANSCRIPT](https://esolangs.org/wiki/TRANSCRIPT) (Task 2 / Hello world) ``` Tr is here. >Tr, Hello, World! >X Tr ``` TRANSCRIPT is a thematic esolang based on interactive fiction. Lines not recognised by TRANSCRIPT are ignored, making it easy to fit in. `Tr is here.` declares a `Tr` string variable, and the second line sets the contents of the variable to `Hello, World!`. `X Tr` (`X` for examine) then outputs the string. Although TRANSCRIPT is very easy to fit in, it's a pretty verbose language, so I made it take the easiest challenge. ## [Fission](http://esolangs.org/wiki/Fission) (Task 3 / Birthday message) ``` R"Happy Birthday, "[?S"!"* \!/ ``` which prints the first part, cats the input with a small 2D loop, then outputs the trailing exclamation mark. The `R` signifies that an atom starts here moving rightward, which is useful because this program can be moved around anywhere. ## [Rail](http://esolangs.org/wiki/Rail) (Task 4 / Tabs) ``` $'main' \@-[I love tabs!]o# \ >qi---@ @-[ ]e< -[I hate spaces!]o# ``` Like Fission, Rail is a 2D language which has the advantage of being able to be moved around anywhere. Execution starts from the `$` of the `main` function, heading southeast. First we head down the `\`s, turn left at `-`, hitting `[<tab>]` which pushes a tab. `e<` then branches based on EOF – if EOF, we head down and print `"I hate spaces!"` before halting, else we head up. If we headed upwards, we read the next char and compare it with the tab, once again branching – if tab, head up and print `"I love tabs!"` before halting, else head down and continue the input loop. This program is pretty expensive, but since TRANSCRIPT took Hello World it was hard to pick and appropriate task for Rail. ## [><>](http://esolangs.org/wiki/Fish) (Task 6 / Ascending input) ``` "1\"# \""" "" " >0[0>i:0(?v:{)?v0n; ;n1< .95< .91< ``` Prints `1` if strictly ascending, `0` otherwise. ><> is another 2D language, and execution starts from the top left. `"..."` is string mode, pushing the inner chars one at a time. After the first string we hit `#`, which reflects the IP leftward, pushing more strings and wrapping around (><> is toroidal) before hitting `\`, a mirror which reflects us upwards. At the bottom of the program is `.91<`, which teleports us to `(9, 1)`, where the core program is. After this `0[` removes all the junk from the strings, `0` pushes a zero to represent the last char read, and after this it's just reading chars one at a time, making sure we're still ascending. It's probably better to move the core program down instead of teleporting, but I'll deal with that later if necessary. ## Befunge (Task 9 / Addition) ``` "1\"# &&+.@ ``` Tested with the interpreter found [here](https://github.com/TieSoul/Multilang). This is a pretty straightforward program, with the start pushing a useless string and `#` jumping over the space. After that it's just the core program `&&+.@`. ## [Labyrinth](http://esolangs.org/wiki/Labyrinth) (Task 10 / Divmod by 7) ``` "1 = ' < ""'("'] ? :_7/!\_7%!@ ``` Conveniently, `'` and `"` are NOPs in Labyrinth which act like a walkable path in the maze. I'll skip the messy navigation, but basically there's a lot of turning and wandering around going on before we hit the `?`, which is the start of the core program. The program is not quite flush left to account for Prelude (e.g. `?` is read input in Prelude). ## Python 2 (Task 14 / Hexadecimal) ``` "1\"# &&+.@\""" "" " #= '''' xxx xxx''';print hex( input())#xxx ''' xxx xxx'''#"; ``` The `xxx`s represent irrelevant portions commented out by multiline strings or comments. In between is `print hex(input())`, the core progam. This outputs with a leading `0x`, but I'm assuming that's okay (if not, then it's an easy fix anyway). The first line is a string `"1\"# &&+.@\""` followed by two `" "`s. These three strings are concatenated by the parser, and left unused (this first line works similarly for Ruby and Julia later). ## GolfScript (Task 15 / Hamming weight) ``` "1\"# &&+.@\""" "" " #= '''' <<s ""'("']0=~2base{+}*} ``` The first line pushes three strings, and the second line is a comment. `''''` pushes two more strings, then `<<` does two comparisons (`s` is ignored). Finally, `""'("'` pushes another two strings. All of this is junk is then removed by wrapping it in an array and getting the first element (`]0=`), which is the input initially on the stack. We then evaluate the input with `~`, turn into binary with `2base` then sum the bits with `{+}*`. The next `}` is unmatched, and super-comments the rest of the program. ## Julia (Task 16, Fibonacci) ``` "1\"# &&+.@\""" "" " #= xxx xxx=#print(([1 1;1 0]^int(readline()))[1,2]) #= xxx xxx=#.91<0#xxx ``` `#=` starts a multiline comment and `=#` ends a multiline comment. The core program uses matrix exponentiation to calculate Fibonacci numbers (taken from [Rosetta](http://rosettacode.org/wiki/Fibonacci_numbers#Julia)). ## Ruby (Task 17 / ASCII frame) ``` "1\"# &&+.@\""" "" " #= '''' <<s xxx s l=gets a='+-'+?-*~/$/+'-+' puts a+' | %s | '%l+a#xxx ``` This program assumes that the input does not end with a trailing newline. We have a useless string, a comment, another useless string then a heredoc which comments out most of the program. After that is the core program, followed by a single line `#` comment. ## CJam (Task 19 / Diamond) ``` "1\"# &&+.@\""" "" " #= '''' <<s ""'("xxx " R"xxx"[?S"!"*" xxx xxx"ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"xxx xxx xxx"; ``` The two space strings at the end of the first line are to satisfy CJam, since `#=` are two binary operators. I won't go into too much detail with this one, but basically it's a mess, with the core program being the mere ``` ri:X{_~X+S*'/@S*_'\4$N}%_sW%1> ``` in between. The key differentiator between GolfScript and CJam is that, in CJam, a single quote `'` doesn't start and end strings, but instead pushes the next character to the stack. This means that in CJam ``` '("' ``` pushes a `(` then starts a string with `"` (the first char of which is `'`), whereas the above is just a straight single string in GolfScript. [Try it online](http://cjam.aditsu.net/#code=%221%5C%22%23%20%26%26%2B.%40%5C%22%22%22%20%22%22%20%22%0A%23%3D%0A''''%0A%3C%3Cs%0A%22%22'%28%22'%5D0%3D~2base%7B%2B%7D*%7D%0A%20%3F%0A%20%3A_7%2F!%5C_7%25!%40%0A%22%0AR%22Happy%20Birthday%2C%20%22%5B%3FS%22!%22*%22%0A%3E0%5B0%3Ei%3A0%28%3Fv%3A%7B%29%3Fv0n%3B%5C!%2F%0A%24'main'%3Bn1%3C%20.95%3C%0A%20%5C%40-%5BI%20love%20tabs!%5Do%23%0A%20%20%5C%20%3Eqi---%40%0A%28%20%40-%5B%20%5De%3C'''%3Bprint%20hex%28%0Ainput%28%29%29%23-%5BI%20hate%20spaces!%5Do%23%22%5D%5D%3Bri%3AX%7B_~X%2BS*'%2F%40S*_'%5C4%24N%7D%25_sW%251%3E%22%29%29%3F%28!%3F%29%0A'''%3D%23print%28%28%5B1%201%3B1%200%5D%5Eint%28readline%28%29%29%29%5B1%2C2%5D%29%0A%23%3D%0ATr%20is%20here.%0A%3ETr%2C%20Hello%2C%20World!%0A%3EX%20Tr%0As%0Al%3Dgets%0Aa%3D'%2B-'%2B%3F-*~%2F%24%2F%2B'-%2B'%0Aputs%20a%2B'%0A%7C%20%25s%20%7C%0A'%25l%2Ba%23%3D%23.91%3C0%23'''%23%22%3B&input=3). `1>` is used instead of `(` to account for Prelude. --- Here's **12 languages, 373 bytes**. Some tasks have moved around, TRANSCRIPT has been removed (it made Rail too expensive) and Scheme (chicken) has been added. This is just my golfing ground for to-be updates since updating the main post takes forever. ``` "1\"09!#.&&+.@"" "" "#|" #= '''' <<s 11]0=~2base{+}*} ? :_7/!\_7%!@ " R"Happy Birthday, "[?S"!"*" >0[0>i:0(?v:{)?v0n;\!/ $'main';n1< .95< (-[Hello, World!]o#''';print(input()in input());'''"]];ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"=#print(([1 1;1 0]^int(readline()))[1,2])#=)?(!?) s l=gets a='+-'+?-*~/$/+'-+' puts a+' | %s | '%l+a# =##'''#";e# |#(print(format"~x"(eval(read)))) ``` I could save a few bytes for Julia since unterminated multiline comments raise an error to STDERR. [Answer] # 17 different versions of Pip, 383 bytes (invalid) While this question was sandboxed, I combed through all the revisions of [my language Pip](http://github.com/dloscutoff/pip) and came up with a polyglot using 17 of them. Sadly, versions of the same language are disallowed by the challenge rules now, but with Dennis's permission and a disclaimer I'm posting my work anyway. ### The raw code ``` I!ga:0m@0:0v:uIN[(oTM0,0i)EN1N1Y1RCkw(hR`1.+0``&2o`)@>3@AB0`u`rZ4AB6({a}V7)BN8AZ9@m]Iv<2W##YqlPByc:((J['.'@]X4)X4RL3)Jnc.:n.RVcc:cRL4|0Iv=3{d:sXaRLaFj,ad@j@j:'\d:(RVdR'\'/).d|0dJ:n}m:'+.'-X#a+2.'+.n."| "Iv=5La{i+:oSio}j:ak:bPv=11?a>1&0INa%(2,a)[((J_M ZRVl)|0)Jnl?lJnlcJnd.n.RVdm.a.RVmih:$+TBa({j@aEQk}FI0,#a).saTB16a>b?abh=1ua//7.s.a%7a+bbINa"Happy Birthday, ".a.'!"Hello, World!"]@v ``` ### The strategy In Pip, lowercase letters are variables. Uppercase letters are more complicated: they are broken into runs of at most two characters, which can be operators or variables. If an uppercase token isn't specifically defined as a variable or operator, it is assumed to be an undefined variable, which evaluates to nil. So, to distinguish between two versions of Pip, I just have to find some variable or alphabetic operator that was added in the newer of the two. In the older one, it will be nil instead. The code `v:uIN[...]` puts together a big list containing one of these checks for each version I want to test, finds out how many nils are in that list (the `u` variable is explicitly initialized to nil), and stores the number in `v` (for "version"). After some other calculations, there's another big list that calculates the results for 17 of the tasks from the challenge and uses `v` to select one based on what version this is. ### Versions and tasks **[0.15.09.04](https://github.com/dloscutoff/pip/commit/e48d5b489232eabb02e6ad4286d1c3bdd40a861d)** Diagnostic: `(oTM0,0i)` (fixed a bug with `T`ri`M` operator where trimming 0 characters from each end of a string would give the empty string instead; indexing into empty string gives nil) Task 18: `Iv<2W##YqlPBy` (setup: read all lines from stdin if `v` is less than 2) followed by `((J_M ZRVl)|0)Jn` (reverse list of lines, transpose, and join back into string) **[0.15.08.06](https://github.com/dloscutoff/pip/commit/70b627dba9335de5119162b64edc2402cc2eff60)** Diagnostic: `EN1` (added `EN`umerate operator) Task 1: `Iv<2W##YqlPBy` (same setup code as above) followed by `l?lJnl` (join on newlines) **[0.15.08.03](https://github.com/dloscutoff/pip/commit/7509874d3d2a8f58fe4061cfd0c676c217c92d80)** Diagnostic: `1N1` (added `N` as short version of `IN` operator) Task 20: `c:((J['.'@]X4)X4RL3)Jnc.:n.RVcc:cRL4|0` (setup: generate list containing upper and lower halves of chessboard and store in `c`) followed by `cJn` (join on newline) **[0.15.08.01](https://github.com/dloscutoff/pip/commit/0e071318c8562ead146b99b01e38e59763c53672)** Diagnostic: `Y1` (added `Y`ank operator) Task 19: `Iv=3{d:sXaRLaFj,ad@j@j:'\d:(RVdR'\'/).d|0dJ:n}` (setup: if `v` is 3, build top half of diamond in `d`) followed by `d.n.RVd` (reverse for bottom half and join on newline) **[0.15.06.19](https://github.com/dloscutoff/pip/commit/915cec54915af23d18b453d2d954f57becd220c0)** Diagnostic: `RCk` (added `R`andom `C`hoice operator) Task 17: `m:'+.'-X#a+2.'+.n."| "` (setup: build `+----+\n|` string in `m`) followed by `m.a.RVm` (wrap input in `m` and reverse of `m`) **[0.15.06.12](https://github.com/dloscutoff/pip/commit/db31988953d0ec0fb288a4df84490af6d02c06f1)** Diagnostic: `k` (preinitialized `k` variable to `", "`; previously it was undefined and thus nil) Task 16: `Iv=5La{i+:oSio}` (if `v` is 5, generate Fibonacci number in `i`) followed by `i` **[0.15.06.08](https://github.com/dloscutoff/pip/commit/cb19dfa7a0922af7c2314114f125000a432eec87)** (note: version number wasn't changed till the following commit) Diagnostic: `w` (preinitialized `w` variable to ``\s+``) Task 15: `h:$+TBa` (convert input to binary and sum digits; save result in `h` for task 12 later) **[0.15.05.29](https://github.com/dloscutoff/pip/commit/063bf12392a59c64c129cfb973204b69a10f0b32)** Diagnostic: `(hR`1.+0``&2o`)@>3@AB0` This version added `&` as a replacement pattern for the whole matched string in a regex replacement (inspired by sed). The code above takes `h` (`100`) and replaces it with ``&2o`` (i.e. `"1002o"` in newer versions but simply `"&2o"` in older versions). It then slices all characters after the 3rd (`"2o"` in newer versions, `""` in older versions) and attempts to index into that string. Indexing into an empty string gives nil. Task 7: `j:ak:b` (setup: copies local vars `a`,`b` to global vars `j`,`k` so they'll be available inside a function) followed by `({j@aEQk}FI0,#a).s` (filter for indices in `a` where the corresponding character equals `b`, and join on space) **[0.15.05.26](https://github.com/dloscutoff/pip/commit/5d2b2bb483e0875ecd33182756e96635934d760f)** Diagnostic: ``u`` (added Pattern type; in previous versions, backticks are ignored as unrecognized characters, and the expression evaluates to `u`, which is nil) Task 14: `aTB16` (convert `T`o `B`ase 16) **[0.15.05.24](https://github.com/dloscutoff/pip/commit/21af91f8b70bb243fd32a5c9299191e2dec5add6)** Diagnostic: `rZ4` (created `r` special variable which returns a random value between 0 and 1 each time it is referenced; previously it was undefined and thus the expression evaluated to nil) Task 13: `a>b?ab` (ternary expression) **[0.15.05.12](https://github.com/dloscutoff/pip/commit/2379b057330204d4daedddd4abcc42d96097f3c1)** Diagnostic: `rZ4` (added `Z`ip operator) Task 12: `h=1` (sum of bits from task 15 must equal 1) **[0.15.05.11](https://github.com/dloscutoff/pip/commit/5072cc90437ff0b60c0944d27db7b130783e5286)** Diagnostic: `AB6` (added `AB`solute value operator) Task 11: `Pv=11?a>1&0INa%(2,a)[...]@v` (if `v` is 11, output `1` if input is greater than 1 and a smaller number divides it exactly, `0` otherwise; if `v` is anything else, use `v` as an index to the list to decide what to output) **[0.15.05.02](https://github.com/dloscutoff/pip/commit/c5f3d86b43e25a6fce38225fdfe4a1a0662bcc4a)** Diagnostic: `({a}V7)` (added `V` operator; when `V` was undefined, this sent arguments nil and 7 to a function `{a}` that returns its first argument) Task 10: `a//7.s.a%7` (input int-divided by 7 and mod 7, space-separated) **[0.15.04.26](https://github.com/dloscutoff/pip/commit/1d329faace0f27e5dc334c04a9ed8c1c311484b8)** Diagnostic: `BN8` (added `B`itwise `N`egation operator) Task 9: `a+b` **[0.15.04.23](https://github.com/dloscutoff/pip/commit/864df0b7c7e6e7d597c4da96df8bb72a78938c4c)** Diagnostic: `AZ` (preinitialized `AZ` variable to uppercase alphabet) Task 5: `bINa` (`IN` gives count of occurrences) **[0.15.04.20](https://github.com/dloscutoff/pip/commit/16302f7494712a4efce79c46bcd7a8f923ecf784)** Diagnostic: `m@0:0` followed by `9@m` The `m` variable is preinitialized to 1000. In this commit, the `@` operator was fixed to return lvalues; previously, assigning to `m@0` gave a warning and did nothing. Thus, post-bugfix, the first statement sets `m` to `0000`, which is a legal index for `9`; pre-bugfix, `m` stays `1000`, which is not a legal index. (Indices were not yet cyclical.) Task 3: `"Happy Birthday, ".a.'!` **[0.15.04.18](https://github.com/dloscutoff/pip/commit/3058cb802bf12f9ffa07b0c000f391f214729c41)** All previous diagnostics result in a nil being added to the diagnostic list. Task 2: `"Hello, World!"` --- Most of the other code is tweaks I had to make to avoid errors in various versions. This post is already far too long, so if you want to know about anything I haven't explained, let's take the discussion to the [esoteric languages chatroom](http://chat.stackexchange.com/rooms/27364/esoteric-programming-languages). [Answer] # ~~14~~ 15 languages, 487 bytes ### [brainfuck](https://github.com/TryItOnline/brainfuck), [Thue](https://esolangs.org/wiki/Thue), [Fission](https://github.com/C0deH4cker/Fission), [Rail](https://esolangs.org/wiki/Rail), [Perl](https://www.perl.org/), [><>](https://esolangs.org/wiki/Fish), [Surface](https://github.com/TryItOnline/surface), [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), [Gol><>](https://github.com/Sp3000/Golfish), [Befunge-93](https://github.com/catseye/Befunge-93), [Hexagony](https://github.com/m-ender/hexagony), [Python 3](https://docs.python.org/3/), [PingPong](https://github.com/graue/esofiles/tree/master/pingpong), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [Ruby](https://www.ruby-lang.org/) ``` #\&v/,[.,][ .hzPSIv?:< #!oan-2l.1*8=;?(1:i::< # :< /2_0#!x%x2$:_.#-@#1: #>,>, \ # o->+o #/o? </ #>:@ #.....\?{?'-~^!@0!;J$?0J$ " ,yadhtriB yppaH"L print ([]and(0and("#{a=$<.map(&:chars);a[-1].zip(*a).map{|z|z[1,10].reverse*''}*$/}")or"@{[1+index<>,<>]} ")or 0x0or'%x'%(0x0+int(input()))) __DATA__=1 +1;""" @.<x v: %+v >-\*<< ^?/~^ m::=~Hello, World! ::= $'main'-\ @-[ ]e</i-@ x>qfq--[I hate spaces!]o @-[I love tabs!]o '+`\@:+/= 2% ^/*;#\ ]""" ``` Lots of 2D languages. I'm pretty sure I could fit at least ~~two~~ one more languages in here, but a few of the ones I was thinking of ended up being newer than 2015, plus this is fast approaching the size limit. ### 1. [brainfuck](https://github.com/TryItOnline/brainfuck) This is a simple cat program on the first line, followed by wrapping most of the rest of the program in a non-executing loop to prevent anymore printing. ``` ,[.,][ ] ``` [Try it online!](https://tio.run/##JVHbbptAEH3e/YqBhYCB5eKnarmmykMc5aFSK/UBMF0bLKPaQDBBxI79687SnpGORmeO5qLZ9Lxudu/bv/c7yR5Gx0ptK08BANn784@fqzFmAczARGp5Q5cH2zO@hX6se6xmooYJCHaWhUukSZ2WCitsQhPiMUwiK7IAZZiglkZmiwSE32ljgMARIxASHpYgEIEF4VmwZ2TxJdbobS0lruS/KLH7ooAM1gcv90Nff4ePruPP8uv/Hl1fNwPS05w3pe7OJJMLD5XAPvJOf2DbPe9PC5@n1Mvtc93pBl/Mpcvn@fOcepbn5nZfjVV/qgxNuxqKc5UXbS8nl9Qz66aspiCygii/wiwjd3LbXlMnTdVFKgyDXjfd@6AvBMQ6RfH0@OuxKEJPXGV6vizLOLGDCY8MVHPEEc2MIMDr2Lmt8ZGx8PZcHQ6tBb/b/lBKWChY0Y7iLxrNcEJTlFeBU9MEwxS97d4oTVew50MFp45vq5OUt7NrBYd2rGDgm38KaOafLGGmE@KlCmvH8EmGc7HL/c4327LafQE "brainfuck – Try It Online") ### 2. [Thue](https://esolangs.org/wiki/Thue) This executes the lines with `::=` towards the end of the program, ignoring any other lines. This simply looks for any `m`s in the rest of the program after `::=` and prints "Hello, World!" for each of them. ``` m::=~Hello, World! ::= m ``` [Try it online!](https://tio.run/##JU/LjptAEDzPfEXDwIKB4eFTNDw3ymG9yiFSIuUAmEzWRCBhhsUsYu21f90Zkmqp1KoudVdPzVt9v5PiYfac3HXKHACQ25y/fd/NKYtgBSaK4D3ddm5gfYrD1AxYy@QME5DsbSufKIu@bDVWuYRmJGCYJE7iACowQYImtkAS0u@JFCDy5AmEpIdlCGRhSXgV3BVFekkNetsrma@Ez1rqP2uggvPOD800tp/hfRj4k/r1/45hbPsJmXnJ@4Ppr6SSC4@1yD3ywXxgLw0fT5uQ5zQo3XM7mBbfrKPLx/njnAdO4JfuWM/1eKotw7hamndVN2JUs0se2G1/qJcocaKkvMIqI3/xxWjoi6GbspWGyWz74W0yNxIyTlV9efzxWFVxIL@yg1BVVZy50YJnBro944QWVhThferd9vjIWHx7qrtOOPBTjN1BwVLBmnHkbW/QAmc0R2UdeS3NMCzJ659XSvMdNHyq4TTwl/qklGJ17aATcw0T//1PAcP@VWTM9mK81WHvWSEpcCmz3O9/AQ "Thue – Try It Online") ### 3. [Fission](https://github.com/C0deH4cker/Fission) This starts execution from the `L` on the tenth line (it also starts from the `D` in `__DATA__`, but we immediately kill that). This first prints "Happy Birthday, ", then does a cat program. ``` #0!;J$?0J$ " ,yadhtriB yppaH"L ``` [Try it online!](https://tio.run/##JU9Nb5tAED2zv2JgIWBg@fCpWj5T5RBHPURqpR4A021M5JVslgBBxI79190lfSM9jd48zbx55cPARXu74fJu8t3Cc6sCABRvf3r@uZkyGsMChFXBWrI@eKH9LYkyK6ScyhnCINlf1wFWZ2Ne67T2MMlxSBFO3dQFpURYESR1hCIh/b7IAGJfnlAU6aG5ArKQJLQI3oIyO2cmuW7VPFCjJz0LnnTQwP1gu/3Y8@/w0XXsUfvxf0fX83ZUrKJi7c4KFtLwmSV67B1ZZ93Rlz3rh1XEChJW3ol3ls1Wy@j8efo8FaEbBpXXN1PTD41tmhdb9y/aSvRafi5Ch7e7Zo5TN06rCyyyEsyB6E1jNg1LttIwWrzt3kdrJSHj1PXD/a/7uk5C@ZUTRpqmodyLZzRRMJwJpaS04xhtM/@6RUdKk@tjczgIF36L/rBTkVSQbh4Zb01SopwUStXEPic5gjl9e30jpNjAno0NDB17aQa1EotrAwcxNTCyv18KmM6fMqeOn6C1AVvfjnCJKpnldnto2pYP/wA "Fission – Try It Online") ### 4. [Rail](https://esolangs.org/wiki/Rail) This starts from the line that starts with `$'main'`. This is essentially a golfed version of [SP3000's Rail](https://codegolf.stackexchange.com/a/58152/76162) program, compressed to four lines and about 15 bytes shorter. It essentially has the same logic, but crosses over itself a couple extra times. ``` $'main'-\ @-[ ]e</i-@ >qfq--[I hate spaces!]o @-[I love tabs!]o ``` [Try it online!](https://tio.run/##JU9db5tAEHy@@xULBwEDx4efqgMDqfoQR32I1Ep9AEwvhspImCOYImLH/uvukc5Ko9XsaHd24E17v5P8YfKczHWKDACQezi//NhOCYtgASaK4B1dt25gfdmEiRmwhskZJiDZW5c@UWZ9XmusdAlNScAwiZ3YAZRjggSNbYEkpN8TCUDkyRMISQ9LEcjCkvAiuAvy5JIY9LZTUl8Jn7XEf9ZABeedV4dxaL7Ce9/zJ/X7/x390HQjMrOCd5XpL6SSC99okXvkvfnA9gc@nFYhz2hQuOemNy2@WkaXj/PHOQucwC/coZ7q4VRbhnG1NO@qrsSgppcssJuuqucodqK4uMIiI3/2xWDos6GbspWG0Wy6/u9oriRknLL89vjzsSw3gfzKDkJVVXHqRjOeGOj2hGOaW1GEd4l32@EjY5vbU922woFfYmgrBUsFa8aRN51Bc5zSDBV15DU0xTDHb3/eKM22cOBjDaee7@uTUojFtYVWTDWM/PVTAcP@nafM9jZ4rcPOs0KS40Jmud/5K9pX/wA "Rail – Try It Online") ### 5. [Perl](https://www.perl.org/) This is part of a smaller polyglot with Python and Ruby. Generally, `[]` is truthy in Perl and Ruby but not Python, and `0` is truthy in Ruby but not Perl. This checks the index of one input in another, and adds one to the result to make it 0 for falsey and a positive number for truthy. This is enclosed in a string interpolation to avoid syntax errors with Ruby and Python. We also have the `__DATA__=1` line to prevent it from parsing further than that. ``` print "@{[1+index<>,<>]} " ``` [Try it online!](https://tio.run/##JU9db5tAEHzmfsXCQcDA8WGpUnV8pupDHPUhUiv1ATA9m6uMhIFggogd@6@7RzorjVazo93Zng/Nl/sd5w@Ta2eOXWQAIDmH88vPzZTQEBYgLHesJevG8c2vUZAYPq2pmCEMgt116WF51ua1SksHkxT7FOHYjm2QcoSljsRWJwkIv9slAKErTkiS8NBUAlFIEFoEZ0GeXBKd3LZy6snBs5p4zyooYL@z6jAO9Td473v2pPz4v6Mf6naUjKxgbWV4Cyn4wiI1dI6sNx7o/sCG0ypgGfEL51z3hslWy@jycf44Z77te4Uz8IkPJ27q@tVU3auy6gYlvWS@VbcVn8PYDuPiCossebPXDbo265ohWmEYjbrt30ZjJSDilOX3x1@PZRn54ivLDxRFQakTzmiioFkTikluhiHaJu5ti46URrcn3jSdDb@7oalkJBSk6kdWtzrJUUoyqeChW5MUwRy//n0lJNvAgY0cTj3b85NcdItrA003cRjZ7lMB3fqTp9RyI7TWYOuaAc5RIbLc72y3r9Bu/w8 "Perl 5 – Try It Online") ### ~~6:~~ ### 7: [><>](https://esolangs.org/wiki/Fish) This takes input of the character through the command line and the string through STDIN. This first reflects of the first `#`, then uses `v?:` to distinguish between this and Gol><>. This goes down to the second line and loops over the input, checking each character against the command argument, printing the stack height if so. ``` # v?:< !oan-2l.1*8=;?(1:i::< ``` [Try it online!](https://tio.run/##JU/LjptAEDzPfEXzWjAwPHyKhudGOaxXOURKpBwAk1mbFUg2wwKLWHvtXydDUi2VWtWl7urXZqiXRckfJtfOHLvIAAA59eXHz92U0BBWYEXirCXbk@ObX6IgMXzaUDHDCgh2t6WnSLM2b1VaOgpJFZ9iJbZjG1COFcRJbHEkIPwuTwBCV5xASHhoikAUFoRXwVmRJ9dEJ/e9lHpS8Kwm3rMKMtgf7FiPffMVPrqOPcnf/@/o@qYdkZEVrD0a3kqycmWRGjpn1hkP9FCzftgELCN@4VyazjDZZh1dPy@fl8y3fa9w@mqq@qEydf1mqu5N3vBeTq@ZbzXtsZrD2A7j4garjLzZ472uzbpmiFYYRqNpu/fR2AiIOGX57fHXY1lGvvjK8gNZlnHqhDOeKGjWhGOSm2GI94l73@MzpdH9qTqduA2/eX86SlgoWNXPrGl1kuOUZKioQrchKYY5fnt9IyTbQc3GCoaOHapBKvjq2sGJTxWM7OWfArr1J0@p5UZ4q8HeNQMlx4XIsizs5cAWMrC/ "><> – Try It Online") ### ~~8.~~ ### 9. [Surface](https://github.com/TryItOnline/surface) Surface is a 2D language ignoring characters it doesn't recognise. It reflects off the `\` and reads the input numbers into two cells with `>,>,`. Next it enters a loop, decrementing one number and incrementing the other, exiting once one reaches zero. Finally it prints the resulting cell as number. ``` \ >,>, \ o->+o /o? </ >:@ ``` [Try it online!](https://tio.run/##JVFNb5tAED3v/oqBhYCB5cPqoV0wkKiHOOqhUiv1AJhuYyIjYZYAQcSO/dfdpX0jPY3ePM2HZnjrX/hzdbuR/G7ynMx1igwAkHs4ff@xnRIWwQJMFMFbum7cwPq8CRMzYDWTNUxAsrcufaLM@rzWWOkSmpKAYRI7sQMoxwQJGtsCSUi/JxKAyJMjEJIeliKQgSXhRXAX5Mk5Meh1p6S@Ej5pif@kgQrOO98fxr5@gPeu44/qt/89ur5uR2RmBW/3pr@QSs58o0XukXfmHXs@8H5YhTyjQeGe6s60@GopnT9OH6cscAK/cPtqqvqhsgzjYmneRV2JXk3PWWDX7b6ao9iJ4uICi4z82Re9oc@GbspUGkazbru30VxJyHXK8uv9z/uy3ATyKjsIVVXFqRvNeGKg2xOOaW5FEd4l3nWHj4xtro9V0wgHfom@2StYKlgzjrxuDZrjlGaoqCKvpimGOX59eaU028KBjxUMnXzcoBRicW2hEVMFI//zTwHD/p2nzPY2eK3DzrNCkuNC7nK7fcJf/gI "Surface – Try It Online") ### 10. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) This one is rather hard to see, but it essentially executes the instructions: ``` push 32 (SSSTSSSSSL) dup (SLS) dup (SLS) readi (TLTT) (saves to heap at 32) retrieve (TTT) (retrieves from 32) dup (SLS) push 7 (SSSTTTL) div (TSTS) printi (TLST) swap (SLT) printc (TLSS) push 7 (SSSTTTL) mod (TSTT) printi (TLST) ``` [Try it online!](https://tio.run/##JVHbbptAEH3e/YrhFjCwXKxWqhYMpOpDHPWhUiv1ATDdxluBhFmCCSV27F93l/SMdDQ6czQXzd@6GfmxZ0/8dtOKu8l3c88tcwBAXn369n07pTSGBVhTBOvIuvVC@9MmSq2QNlTWsAaS/XUVaMpszGudVp5GMi2kWEvcxAVUYA0JkjgCSUi/L1KA2JcjEJIemiGQgSXhRfAWFOk5Ncl1p2SBEj3qafCogwruK9vX49B8hte@Zw/q1/89@qHpRmTlJev2VrCQqp3ZRo@9A@utO/pUs@G4ilhOwtI7Nb1ls9VSOr@d3k556IZB6Q184sOR26Z5sXX/oq7EoGbnPHSabs/nOHHjpLzAIqNgDsRgGrNpWDKVhtFquv5ltFYScp2q@nL/476qNqG8ygkjVVVx5sUznigYzoQTUthxjHepf93hA6Wb6wNvW@HCTzG0ewVLBevmgTWdSQqckRyVPPYbkmGYk@c/z4TkW6jZyOH9cUelFItrC62YOIzs97sCpvOryKjjb/DagJ1vR1qBS7nL7fbh4z8 "Whitespace – Try It Online") ### 11. [Gol><>](https://github.com/Sp3000/Golfish) This follows a similar path to ><>, diverging at the behaviour of `?:`, since popping the stack results in `0`. It then executes read input as number (`I`), is it prime (`SP`), is it zero (`z`), halt and output (`h`). ``` # hzPSI ?:< ``` [Try it online!](https://tio.run/##JU9Nb5tAED2zv2JgIWBg@TpVy2eqHOIoh0qt1ANguo1JQcIswQQRO/Zfd5f2jfQ0evM08@YP717bY3O74eJudu3cscscACSnOX37vp1TGsEKhGXOehJ0jm9@icPU8GlLxQxhEOwGlYflRVsClVYOJhn2KcKJndggFQhLnCQWlwSE3@UpQOSKE5IkPDSTQBQShFbBWVGk51Qn152ceXL4pKbekwoK2B9s30xj@xU@hoE9Ks//dwxj20@SkZes3xveSgo@s1iNnAMbjDv60rDxuAlZTvzSObWDYbLNOjp/nj5PuW/7XumM9VyPx9rU9Yupuhdlw0clO@e@1fb7eokSO0rKC6yy5C0eH3Vt0TVDtMIwGW0/vE/GRkDEqaqH@x/3VRX74ivLDxVFQZkTLWimoFkzSkhhRhHape51hw6UxtfHuuu4DT/52O1lJBSk6gfW9jopUEZyqawjtyUZgiV5e30jJN9Cw6YajgN7qY9yyVfXFjo@1zCx3/8U0K1fRUYtN0aBBjvXDHGBSpHldvODvw "Gol><> – Try It Online") ### 12. [Befunge-93](https://github.com/catseye/Befunge-93) This interprets `#` as a skip instead of a reflect, taking input (`&`) and going down at the `v` then to the third line. This interpreter ignores invalid characters, skipping past the `a` and the pair of `x`s later. This divides the input by two until either it is odd or it is one, and then outputs accordingly (I could probably simplify this check couldn't I?). ``` # &v # :< /2_0#! % 2$:_.#-@#1: ``` [Try it online!](https://tio.run/##JU/bbptAEH3e/YrhFjCwXPwULddUfYijPlRqpT4Appt4UyNhlmCCiB37192lPSMdjc4czZx55q/v3R9@u2nl3eS7hedWBQAgb3/6/mMzZTSGBVhTBOvIuvVC@z6JMiukDZUzrIFkf10HmjIb81qntaeRXAsp1lI3dQGVWEOCpI5AEtLviwwg9uUJhKSH5ghkYUl4EbwFZXbOTHLdKnmgRE96FjzpoIL7wXb7cWi@wEffs0f12/8d/dB0I7KKinU7K1hI1c4s0WPvwHrrjr7s2XBcRawgYeWdmt6y2WoZnT9Pn6cidMOg8gY@8eHIbdO82Lp/UVdiUPNzETpNt@NznLpxWl1gkVEwB2Iwjdk0LNlKw2g1Xf8@WisJGaeuvz78fKjrJJRfOWGkqirOvXjGEwXDmXBKSjuO8Tbzr1t8oDS5PvK2FS78EkO7U7BUsG4eWNOZpMQ5KVDFY78hOYY5fXt9I6TYwJ6NHI49e@FHpRKLawOtmDiM7PmfAqbzu8yp4yd4bcDWtyOtxJXMcrvd/wU "Befunge-93 – Try It Online") ### 13. [Hexagony](https://github.com/m-ender/hexagony) Hexagony has a strange path, with the second character being a `\`, but it eventually ends up at after the `.....` on the tenth line. Here it gets the inputs into adjacent edges (`?{?`), then subtracts one from the other (`'-~`), and then navigates based on whether that is negative, printing the larger one and terminating (`^!@`). Note that Hexagony appears to have a bug where a number cannot be the first input without a space before it. ``` \ \?{?'-~^!@ ``` [Try it online!](https://tio.run/##JU/LjptAEDzPfEXzWjAwPBwpiobnRjmsVzlESqQcAJPJehKQbIbFBGF77V93hqRaKrWqS93VDZ/Zb9Gd7netfJh8t/DcqgAA5DXnL183U0ZjWIA1RbCOrPdeaH9IoswKaUvlDGsg2V/XgabMxrzWae1pJNdCirXUTV1AJdaQIKkjkIT0@yIDiH15AiHpoTkCWVgSXgRvQZldMpPctkoeKNGzngXPOqjgntiuGYf2I5z6nj2pn//v6Ie2G5FVVKzbWcFCqnZhiR57B9ZbD/SlYcNxFbGChJV3bnvLZqtldHk7v52L0A2Dyhv4xIcjt03zauv@VV2JQc0vRei03Y7PcerGaXWFRUbBHIjBNGbTsGQrDaPVdv2f0VpJyDh1/enx22NdJ6H8ygkjVVVx7sUznigYzoRTUtpxjLeZf9viA6XJ7Ynv98KF72LY7xQsFaybB9Z2JilxTgpU8dhvSY5hTl9/vRJSbKBhI4djz174UanE4trAXkwcRvbznwKm86PMqeMneG3A1rcjrcSVzHK/wzt4/xc "Hexagony – Try It Online") ### 14. [Python 3](https://docs.python.org/3/) This is pretty a simple task in Python (`'%x'%int(input())`), but made more complicated by the `%`s spawning Cardinal pointers. We compensate for these with `x`s sprinkled in liberally. ``` print(0x0or'%x'%(0x0+int(input()))) ``` [Try it online!](https://tio.run/##JU9dj5swEHy2f8WC4SCA@UilqjIEuKoPl1MfKrVSH4BQ90IFEsEc4RBJLvnrqWlnpdFqdrQ725/GWnQf7neSP0yek7lOkQEAcuvzt@/bKWERLMBEEbyj69YNrE@bMDED1jA5wwQke@vSJ8qsz2uNlS6hKQkYJrETO4ByTJCgsS2QhPR7IgGIPHkCIelhKQJZWBJeBHdBnlwSg952Suor4bOW@M8aqOCc@L4eh@YznPqeP6lf/@/oh6YbkZkVvNub/kIqufCNFrkH3psP7KXmw3EV8owGhXtuetPiq2V0eT@/n7PACfzCHaqpGo6VZRhXS/Ou6koManrJArvp9tUcxU4UF1dYZOTPvhgMfTZ0U7bSMJpN17@N5kpCxinLL48/HstyE8iv7CBUVRWnbjTjiYFuTzimuRVFeJd4tx0@MLa5PVVtKxz4KYZ2r2CpYM048KYzaI5TmqGiiryGphjm@PXPK6XZFmo@VnDs@Ut1VAqxuLbQiqmCkf/@p4Bh/8pTZnsbvNZh51khyXEhs9zvH/2/ "Python 3 – Try It Online") ### 15. [PingPong](https://github.com/graue/esofiles/tree/master/pingpong) PingPong skips over the `\` with the initial `#`, wrapping to the bottom at the `/`. This goes to the bottom of the code, and enters the loop there, continuly integer dividing by two and summing the modulo by 2 until the input reaches `0`. Then it outputs the sum it has collected. ``` # v/ ... '+`\@:+/= 2% ^/*;#\ ``` [Try it online!](https://tio.run/##JU9db5tAEHy@@xULBwEDx4elStXxmaoPcdSHSK3UB8D0GtMYCXMEU0Ts2H/dOdpZabSaHe3O9k330ovu5XYjxd3kObnrlDkAIHd/evq@mVIWwQJMFME7um7dwPoch6kZsIbJGSYg2VtXPlFmfV5rrHIJzUjAMEmcxAFUYIIETWyBJKTfEylA5MkTCEkPyxDIwpLwIrgLivScGvS6VTJfCR@11H/UQAXnje/249B8gbe@5w/qt/87@qHpRmTmJe92pr@QSs481iL3wHvzjj3v@XBchTynQememt60@GoZnd9P76c8cAK/dId6qodjbRnGxdK8i7oSg5qd88Buul09R4kTJeUFFhn5sy8GQ58N3ZStNIxm0/V/R3MlIeNU1df7H/dVFQfyKzsIVVXFmRvNeGKg2xNOaGFFEd6m3nWLD4zF14e6bYUDP8XQ7hQsFawZB950Bi1wRnNU1pHX0AzDnLz@eaU038CejzUce/5cH5VSLK4NtGKqYeS//ylg2L@KjNlejNc6bD0rJAUuZZbbLfj0AQ "PingPong – Try It Online") ### 16. [Cardinal](https://www.esolangs.org/wiki/Cardinal) Cardinal is a bit of a pain, since it initially spawns pointers at all `%`s, which usually need to be squashed with `x`s. The one we do use in near the bottom, in the string literal. This spawns two pointers, one which collects the input and decrements until it reaches zero, and one that is continually generating the fibonacci numbers by flipping its two values and adding them. Once the first pointer reaches zero it is destroyed by the `?`, leading to the second pointer being reflected upwards into the `. <` to be printed. ``` . <x v: %+v >-\*<< ^?/~^ ``` [Try it online!](https://tio.run/##JU9Nb5tAED2zv2L4ChhYYDlVy2eqHuKoh0it1ANgujVURsIswQQRO/Zfd5b2jfQ0evM082bPxrrtWXe/q8XD7Dm565Q5AEju4fzyYzunNIIVSJU563HQucT6EoepSWhLxQypINgLKl@VF30JNFq5Ks5UQpGaOIkDUoFUiePE5pKA8Hs8BYg8cUKShIdmEohCgtAquCuK9JIa@LaTM18On7XUf9ZAAeed1YdpbL/C@zCwJ@X7/x3D2PaTZOYl62vTX0lRLyzWIvfIBvOB7g9sPG1ClmNSuud2MC22WUeXj/PHOScO8Ut3bOZmPDWWYVwtzbsqGz4q2SUndtvXzRIlTpSUV1hlyV98Phr6YuimaIVhMtt@eJvMjYCIU1XfHn8@VlVMxFc2CRVFQZkbLWimoNszSnBhRRHapd5th46Uxrenpuu4A7/42NUyEgrSjCNrewMXKMO5VDaR1@IMwZK8/n3FON/CgU0NnAa2b05yyVfXFjo@NzCxP/8UMOzfRUZtL0aBDjvPCtUClSLL/U6CTw "Cardinal – Try It Online") ### ~~17.~~ ### 18. Ruby Probably the language with the most code, this takes place in a string interpolation as usual. This splits up the input into a 2D array, then zips and joins them together in reverse to produce the transposed output. ``` print "#{a=$<.map(&:chars);a[-1].zip(*a).map{|z|z[1,10].reverse*''}*$/}" ``` [Try it online!](https://tio.run/##JU/LjptAEDzTX9G8FgwMD5@iMQY2ymG9yiFSVsoBMBmvJzISBhYwwvbav@4MSbVUalWXuqu70@78eKjZ0@g5qevkKSJK7uHy4@dmjGmIM0CVG1aTZeUG1pf1KjYDWlIxAxUFe8vCV@VJn5YaLVyVJGpAQY2cyEEpA1VqSGQ3koDwe02MGHrihCQJD00kFAWCYBbcGVl8jQ1y38qJL69etdh/1VBB58z2h6Erv@K5bdmL8v3/jrYr60Ey05zVe9OfSVGvbK2F7pG15hN9P7CuX6xYSoLcvZStabHFPLp@Xj4vaeAEfu52fORdzy3DuFmad1MWTack1zSwy3rPpzBywii/4SxL/uQ3naFPhm6KVhgGs6zb02AuBEScovj2/PZcFOtAfGUHK0VRIHHDCUaKuj1CRDIrDGEbe/ctHCld3194VTUO/mq6ai@DUEAzjqysDZJBQlIp56FXkgRwij7@fBCSbvDABo59y955L@fN7Npg1YwcB7b7p6Bh/84SantrWOq49ayVmkEusjwew5nDVFXA2x0MRwZY7gF7Bj1yKLGDQ1/DW3n6Cw "Ruby – Try It Online") ### ~~19.~~ ### ~~20.~~ ## Future work I'll need to find some new languages to work in there, hopefully 2D languages with arbitrary starting points. Challenge 6 should be pretty easy for any simple language, 8 is a bit tougher. 17 should be achievable with a practical language, 19 and 20 may have to use a golfing lang of some sort to be able to fit within the remaining space. To add more than just challenge 6, I might have to replace some of the longer languages and shuffle them around. [Answer] # 6 languages, 226 bytes (229 depending on how `\x1b` is accepted!) ``` /&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;#<?die("\x1bc".max($argv[1],$argv[2]));/* $a=['Hello','World'];//;printf"%s, %s! ",$a[0]||'Happy Birthday',$a[1]||pop;#";$a="\ #";alert(prompt().match("\t")?"I hate tabs!":"I love spaces!");/\]/ ``` So, I don't think I made the best choice of languages and I imagine this isn't particularly competetive but I found this an interesting challenge nonetheless! Overall, not many challenges complete, but I could probably shoehorn a challenge in whitespace or something similar, but this is what I have so far: --- ### 1. Brainfuck ``` [+.]>>+[>,]<[<]>>[.>]>[<.[],[][,],,[],[].] ``` Tested on <http://copy.sh/brainfuck/> and <http://brainfuck.tk/>. After stripping out all ignored chars, the above program is all we're left with, which is just the example cat program with some extra empty loops to bypass the other languages use of the symbols. ### 2. Ruby ``` /&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//; $a=['Hello','World'];//;printf"%s, %s! ",$a[0]||'Happy Birthday',$a[1]||pop; ``` Usage: ``` ruby cluster ``` The above is the code after all comments are removed. The first line is entirely useless in Ruby as we define some regular expressions to contain the Befunge-93 and brainfuck code, then we create an array to contain `Hello` and `World` and print it using `printf` (to add the `,` and `!`). ### 3. Perl ``` /&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//; $a=['Hello','World'];//;printf"%s, %s! ",$a[0]||'Happy Birthday',$a[1]||pop; ``` Usage: ``` perl cluster <name> ``` Very similar to Ruby, except that since we're storing an array reference in `$a`, when we try to access `$a[0]` it's empty, so we can replace it with the text for challenge 3, `Happy Birthday` and `pop` (which shows the last argument to the command-line program). ### 4. JavaScript ``` /&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/; $a=['Hello','World']; ",$a[0]||'Happy Birthday',$a[1]||pop;#";$a="\ #";alert(prompt().match("\t")?"I hate tabs!":"I love spaces!");/\]/ ``` Usage: paste into browser console and run. Same as Ruby and Perl, the first line essentially creates useless `RegExp` objects, we then store a useless array in `$a` and instantiate two useless strings, one containing the Ruby/Perl code and one containing a newline and a `#`, then we `prompt()` for input and `alert()` the result expected by most humans for challenge 4. We end with another useless `RegExp` object to close off the brainfuck loop. ### 9. Befunge-93 ``` /&&#[+.#]@ ``` Tested on <http://www.quirkster.com/iano/js/befunge.html>. As I understand it, `/` divides the stack and pushes the result which has no ill-effects except pushing `NaN` on the above site, `&` asks for input of an integer so we read both numbers required by challenge 9 onto the stack, the `#` ensures we skip over the `[` which is there for brainfuck, `+` then adds the top two numbers on the stack, `.` outputs them, `#]` for brainfuck again and `@` exits. ### 13. PHP (running in Bash) ``` /&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;#<?die("\x1bc".max($argv[1],$argv[2])); ``` Usage: ``` php cluster <x> <y> ``` In PHP, anything not included within the `<?` tags is output verbatim, so this outputs the Befunge-93 and brainfuck code so we `die()` immediately in the code, output a screen clear (`\x1bc`) then the `max()` of the first two arguments. [Answer] # 6 languages, ~~450~~ 404 bytes ### bash, brainfuck, C, gawk4, JavaScript and Minimal-2D ``` /*\t/#[R,+/D /\t/ # UL.-L<script>var s=prompt().split(' ');alert(+s.pop()+ +s.pop())</script> sed "s/^\(.*\)$/Happy Birthday, &!/;q"&&0 /\t/#*/ #define func func main(){puts("Hello, World!");} //{split($0,b,_);for(i in b)a[NR][i]=b[i++]}END{for(;j++<i;print"")for(k=NR;k;)printf a[k--][j]} #//]++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<<[>>>>>+++[<++++[<<....>....>-]<<<.>>>>-]<<<[>>+<<-]<[[>+<-]<]>>-] ``` Update: Golfed it down a little. Still not sure what else to add, and I'm not sure how the competing members would think about me using their languages for different tasks. Trying to explain the brainfuck algorithm. Well this is/was my first polyglot experience, so I had to learn everything from scratch. Starting with awk was not the smartest idea I think, because it is relatively unforgiving. Because the number of completed tasks is relevant I started with the easiest tasks first. Not sure if that was a smart move. This is not very much golfed, because I had enought trouble getting these six working together, but I did what I could to keep it short. Here are the languages and what they do in alphabetical order. I'll show an easy way to test them all further down. Because some of this might be version specific I'll give you the version numbers of the tools I used. ## bash, task 3 Well, its obvious that I used sed. I tried to put a sed script in this somehow, but I couldn't get it to work, so I went the bash route. The way I dit it, it is inside a C comment and awk evaluates it to `False`. `sed --version` gives `sed (GNU sed) 4.2.2` `bash --version` gives `GNU bash, Version 4.3.30(1)-release (x86_64-pc-linux-gnu)` So the sed part comes down to ``` sed "s/^\(.*\)$/Happy Birthday, &!/;q" ``` It groups the input, pastes it into a new string and prints the result. Pretty common stuff. ## brainfuck, task 20 Well this is always pretty easy to hide I guess. A line starting with `#//` is ignored by C and awk. Or at least they can live with rubbish behind that. `bf` gives `bf - a Brainfuck interpreter version 20041219` This is the condensed code. The first line is only the garbage from the other languages. ``` [,+.-<>.+.++.<>.,,,,[][][++]++<[--][]] ++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<< [>>>>>+++[<++++[<<....>....>-]<<<.>>>>-]<<<[>>+<<-]<[[>+<-]<]>>-] ``` ### I'll try to explain how it works ``` ++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<< ``` this arranges the tape and pointer to this ``` 0 8 10 46 64 C2 C1 ^ ``` the cell holding 8 is the global counter for the following loop it's the number of times 3 same lines are printed ``` [>>>>>+++ ``` sets `C1` to 3, the number of same lines ``` [<++++ ``` sets `C2` to 4, the number of "`....@@@@`" in a line (in the beginning) ``` [<<....>....>-]<<<.>>> >-] ``` prints a complete line decrementing `C2` in the process when `C2` is zero it prints a newline and decrements `C1`. if `C1` is zero the magic happens ``` <<<[>>+<<-] <[[>+<-]<] ``` the 46 is moved behind the 64 the 10 and the global counter are moved one to the right ``` >>-] ``` then the global counter is decremented if it's zero the program exits ## C, task 2 I exhaust every last little ability of C here by printing "Hello, World!". Well, somebody had to do the job... `gcc --version` gives `gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2` The actual C code ``` #define func func main(){puts("Hello, World!");} # ``` The `#define func` is to make awk okay with this. It thinks this is an awk function. Abbreviation to func is a gawk feature. ## gawk4, task 18 Since I have used awk for pretty much everything on here, I decided, that it had to be in this. `awk --version` gives `GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2-p11, GNU MP 6.0.0)` awk sees this ``` /*\t/ /\t/ sed "s/^\(.*\)$/Happy Birthday, &!/;q"&&0 /\t/ func main(){puts("Hello, World!");} //{split($0,b,_);for(i in b)a[NR][i]=b[i++]}END{for(;j++<i;print"")for(k=NR;k;)printf a[k--][j]} # ``` The search patterns including `\t` evaluate to `false`. I chose tab here, because I think it can't be in the input. `sed` evaluates to `false`. `"the string"&&0` evaluates to false. The function is okay. The program is executed if an empty pattern is matched, which it is for any input. It does this ### Input ``` elaic parli ucfit srigs ``` ### Output ``` supe rcal ifra gili stic ``` You have to make sure all the input lines have the same length. Use spaces to fill them up. ## JavaScript, task 9 I'm not sure if this is legit, because this was too easy. If you give the program file a html ending, and open it in a browser (I used Firefox 40.0.3 and chrome 45.0.2454.85) it prompts you for an input. You have to enter two numbers separated by space, and it will alert the sum of those. ``` <script>var s=prompt().split(' ');alert(+s.pop()+ +s.pop())</script> ``` ## [Minimal-2D](https://esolangs.org/wiki/Minimal-2D), task 1 This was pretty easy to fit into comment lines. I used [the interpreter](https://esolangs.org/wiki/User:Marinus/Minimal-2D_interpreter), who runs in python, to test this. It prints the input to the output. The program looks like this ``` R,+/D UL.-L ``` R U D L are right, up, down and left. So it starts going right, reads a character from stdin into memory and adds one. The slash skips the next command if the memory has the value 0. This is to end this. If a character with value -1 is read, the input has ended. So if -1 is read it skips the D and terminates. If something else is read it goes down an left, adds that 1 back to the memory and prints the character to stdout. Then it goes left and up and starts over. # Testing *Disclaimer:* I won't take any responsibility for any damages you do to your system with this. This is assuming you have bash & co, gawk (at least version 4, because this uses multidimensional arrays), gcc, python, bf as a brainfuck interpreter and Firefox installed. To make it easy, copy the program source to a file named `cluster.html`. Make that file executable for the bash task. Copy and paste the [interpreter for Minimal-2d](https://esolangs.org/wiki/User:Marinus/Minimal-2D_interpreter) into a file named `minimal2D.py` in the same directory. Then copy and paste the following script to a script file and put it into the same directory, make it executable and run it... well, who am I talking to. If you read this you probably don't need that much explanation and are gonna get it to run somehow anyway. ``` #!/bin/bash # Task 3: bash echo "Dr. Hfuhruhurr" | ./cluster.html 2>/dev/null;echo # Task 18: awk printf "elaic\nparli\nucfit\nsrigs\n" | awk -f cluster.html 2>/dev/null;echo # Task 2: C cp ./cluster.html ./cluster.c;gcc -w -o cluster cluster.c;./cluster;rm cluster cluster.c;echo # Task 1: Minimal-2D python minimal2D.py cluster.html <<<"This has to be copied !!!";echo # Task 20: brainfuck bf cluster.html;echo # Task 9: JavaScript firefox cluster.html 2>/dev/null #google-chrome cluster.html 2>/dev/null ``` In there you also find the command for running the tests individually. Have fun! ]
[Question] [ Well I think it is about time we have another [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'") question. This time we are going to prove the well known logical truth \$(A \rightarrow B) \rightarrow (\neg B \rightarrow \neg A)\$ To do this we will use Łukasiewicz's third [Axiom Schema](https://en.wikipedia.org/wiki/Axiom_schema), an incredibly elegant set of three axioms that are complete over [propositional logic](https://en.wikipedia.org/wiki/Propositional_calculus#Example_1._Simple_axiom_system). Here is how it works: # Axioms The Łukasiewicz system has three axioms. They are: \$\phi\rightarrow(\psi\rightarrow\phi)\$ \$(\phi\rightarrow(\psi\rightarrow\chi))\rightarrow((\phi\rightarrow\psi)\rightarrow(\phi\rightarrow\chi))\$ \$(\neg\phi\rightarrow\neg\psi)\rightarrow(\psi\rightarrow\phi)\$ The axioms are universal truths regardless of what we choose for \$\phi\$, \$\psi\$ and \$\chi\$. At any point in the proof we can introduce one of these axioms. When we introduce an axiom you replace each case of \$\phi\$, \$\psi\$ and \$\chi\$, with a "complex expression". A complex expression is any expression made from Atoms, (represented by the letters \$A\$-\$Z\$), and the operators implies (\$\rightarrow\$) and not (\$\neg\$). For example if I wanted to introduce the first axiom (L.S.1) I could introduce \$A\rightarrow(B\rightarrow A)\$ or \$(A\rightarrow A)\rightarrow(\neg D\rightarrow(A\rightarrow A))\$ In the first case \$\phi\$ was \$A\$ and \$\psi\$ was \$B\$, while in the second case both were more involved expressions. \$\phi\$ was \$(A\rightarrow A)\$ and \$\psi\$ was \$\neg D\$. What substitutions you choose to use will be dependent on what you need in the proof at the moment. ## Modus Ponens Now that we can introduce statements we need to relate them together to make new statements. The way that this is done in Łukasiewicz's Axiom Schema (L.S) is with Modus Ponens. Modus Ponens allows us to take two statements of the form \$\phi\$ \$\phi\rightarrow \psi\$ and instantiate a new statement \$\psi\$ Just like with our Axioms \$\phi\$ and \$\psi\$ can stand in for any arbitrary statement. The two statements can be anywhere in the proof, they don't have to be next to each other or any special order. ## Task Your task will be to prove [the law of contrapositives](https://en.wikipedia.org/wiki/Contraposition). This is the statement \$(A\rightarrow B)\rightarrow(\neg B\rightarrow\neg A)\$ Now you might notice that this is rather familiar, it is an instantiation of the reverse of our third axiom \$(\neg\phi\rightarrow\neg\psi)\rightarrow(\psi\rightarrow\phi)\$ However this is no trivial feat. ## Scoring Scoring for this challenge is pretty simple, each time you instantiate an axiom counts as a point and each use of modus ponens counts as a point. This is essentially the number of lines in your proof. The goal should be to minimize your score (make it as low as possible). ## Example Proof Ok now lets use this to construct a small proof. We will prove \$A\rightarrow A\$. Sometimes it is best to work backwards since we know where we want to be we can figure how we might get there. In this case since we want to end with \$A\rightarrow A\$ and this is not one of our axioms we know the last step must be modus ponens. Thus the end of our proof will look like ``` φ φ → (A → A) A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9ClxwaGlcXApccGhpXHJpZ2h0YXJyb3coQVxyaWdodGFycm93IEEpXFwKQVxyaWdodGFycm93IEEgXHRhZyp7TS5QLn1cXApcZW5ke2dhdGhlcip9.svg) Where \$\phi\$ is an expression we don't yet know the value of. Now we will focus on \$\phi\rightarrow(A\rightarrow A)\$. This can be introduced either by modus ponens or L.S.3. L.S.3 requires us to prove \$(\neg A\rightarrow\neg A)\$ which seems just as hard as \$(A\rightarrow A)\$, so we will go with modus ponens. So now our proof looks like ``` φ ψ ψ → (φ → (A → A)) φ → (A → A) M.P. A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9ClxwaGkgXFwKXHBzaSBcXApccHNpIFxyaWdodGFycm93IChccGhpIFxyaWdodGFycm93CihBIFxyaWdodGFycm93IEEpKVxcClxwaGkgXHJpZ2h0YXJyb3cKKEEgXHJpZ2h0YXJyb3cgQSkgXHRhZyp7TS5QLn1cXApBIFxyaWdodGFycm93IEEgXHRhZyp7TS5QLn1cXApcZW5ke2dhdGhlcip9.svg) Now \$\psi\rightarrow(\phi\rightarrow(A\rightarrow A))\$ looks a lot like our second axiom L.S.2 so we will fill it in as L.S.2 ``` A → χ A → (χ → A) (A → (χ → A)) → ((A → χ) → (A → A)) L.S.2 (A → χ) → (A → A) M.P. A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9CihBIFxyaWdodGFycm93IFxjaGkpIFxcCihBIFxyaWdodGFycm93IChcY2hpIFxyaWdodGFycm93IEEpKSBcXAooQSBccmlnaHRhcnJvdyAoXGNoaSBccmlnaHRhcnJvdyBBKSkKXHJpZ2h0YXJyb3cgKChBIFxyaWdodGFycm93ClxjaGkpXHJpZ2h0YXJyb3cKKEEgXHJpZ2h0YXJyb3cgQSkpIFx0YWcqe0wuUy4yfVxcCihBIFxyaWdodGFycm93IFxjaGkpIFxyaWdodGFycm93CihBIFxyaWdodGFycm93IEEpIFx0YWcqe00uUC59XFwKQSBccmlnaHRhcnJvdyBBIFx0YWcqe00uUC59XFwKXGVuZHtnYXRoZXIqfQ==.svg) Now our second statement \$(A\rightarrow(\chi\rightarrow A))\$ can pretty clearly be constructed from L.S.1 so we will fill that in as such ``` A → χ A → (χ → A) L.S.1 (A → (χ → A)) → ((A → χ) → (A → A)) L.S.2 (A → χ) → (A → A) M.P. A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9CihBIFxyaWdodGFycm93IFxjaGkpIFxcCkEgXHJpZ2h0YXJyb3cgKFxjaGkgXHJpZ2h0YXJyb3cgQSkKXHRhZyp7TC5TLjF9XFwKKEEgXHJpZ2h0YXJyb3cgKFxjaGkgXHJpZ2h0YXJyb3cgQSkpClxyaWdodGFycm93ICgoQSBccmlnaHRhcnJvdwpcY2hpKVxyaWdodGFycm93CihBIFxyaWdodGFycm93IEEpKSBcdGFnKntMLlMuMn1cXAooQSBccmlnaHRhcnJvdyBcY2hpKSBccmlnaHRhcnJvdwooQSBccmlnaHRhcnJvdyBBKSBcdGFnKntNLlAufVxcCkEgXHJpZ2h0YXJyb3cgQSBcdGFnKntNLlAufVxcClxlbmR7Z2F0aGVyKn0=.svg) Now we just need to find a \$\chi\$ such that we can prove \$A\rightarrow\chi\$. This can very easily be done with L.S.1 so we will try that ``` A → (ω → A) L.S.1 A → ((ω → A) → A) L.S.1 (A → ((ω → A) → A)) → ((A → (ω → A)) → (A → A)) L.S.2 (A → (ω → A)) → (A → A) M.P. A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9CihBXHJpZ2h0YXJyb3coXG9tZWdhXHJpZ2h0YXJyb3cgQSkpClxcCkFccmlnaHRhcnJvdygoXG9tZWdhXHJpZ2h0YXJyb3cgQSkKXHJpZ2h0YXJyb3cgQSlcdGFnKntMLlMuMX1cXAooQVxyaWdodGFycm93KChcb21lZ2FccmlnaHRhcnJvdyBBKQpccmlnaHRhcnJvdyBBKSlccmlnaHRhcnJvdygoQQpccmlnaHRhcnJvdyhcb21lZ2FccmlnaHRhcnJvdyBBKSkKXHJpZ2h0YXJyb3coQSBccmlnaHRhcnJvdyBBKSkKXHRhZyp7TC5TLjJ9XFwKKEFccmlnaHRhcnJvdyhcb21lZ2FccmlnaHRhcnJvdyBBKSkKXHJpZ2h0YXJyb3cKKEFccmlnaHRhcnJvdyBBKVx0YWcqe00uUC59XFwKQVxyaWdodGFycm93IEFcdGFnKntNLlAufVxcClxlbmR7Z2F0aGVyKn0=.svg) Now since all of our steps our justified we can fill in \$\omega\$, as any statement we want and the proof will be valid. We could choose \$A\$ but I will choose \$B\$ so that it is clear that it doesn't need to be \$A\$. ``` A → (B → A) L.S.1 A → ((B → A) → A) L.S.1 (A → ((B → A) → A)) → ((A → (B → A)) → (A → A)) L.S.2 (A → (B → A)) → (A → A) M.P. A → A M.P. ``` [TeX](https://a-ta.co/mathjax/!XGJlZ2lue2dhdGhlcip9CihBXHJpZ2h0YXJy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qme9Ib7MBOAXBYXbPZh7FRKpLUQEp0k9v2OjUgJI/wh4836BpI8cfZNlUpGkCkXuyFN17wqtFc8MGPFgfKX2IUdLs04RanBnrk7ba8ptbro9llDUHcRbqplojhWHSXrNN/KVVPWCIeiHytsXgGE7GROfZxLjL2OE3y5p1Us241V9qxdHac23JEW8P2BTZ1lUq24QWiK4Gv8W67KPZVvJqI6BRK0zBjz0jFRXet49Bh9Kqb09IRldvW2AvkQKgzWkRvMqzbWGaMJ5P0D "Prolog (SWI) - Proof Verifier") And that is a proof. ## Resources ### Verification program [Here](https://tio.run/##hVVta9swEP7uX6EZRiR2NkvzrVsLzmB0kNEy94NLElxvURqDIxtbTTay/vbszrLrl7gZAUd67nnuRbqzszxN0ien2MfHY6TTLZ/f/L1fCuY412x@s4TDr3QlQ/0nk/wGoiTbROIFSuK9cK1K8R@@a1n7wjCWbr3kNrM/2QttC9gXyFCp5oHxYzs2YlDoSMutVDpEAzLiNQ/gwVA6NiLbznVf9ICi92@IHozo83Ck1r6sMBDGQbVx2wSTt7Gbdcdcxa8K42W4CiszEHaHHnSIp1USveF3vXc8t7zWTgccorOf0SpsqPP6KvGiepag6YsA7zlYXI0/vkCXRD1hJcW4DnkIrjAlj/IKwRPYOu2sXKRedKk1ewpfhIAamJZLj7ABF5MTF3QPngD6mxo306HoVi4LHabrMImVfK2MHfDJFlfscaEeX4C1Se6pxF4oupMsj/FUCy0z7uutBh9Xgl06LNvkUSF5E5nMApivc3xSR4U0MgWWV0L7PNaSst9GWRIXmpeA8QcqgXcYbBcl8coECyA0xZtTB0oHDq1sAmDzEZv549GSJnFYenFWenFOOjkrnQxI/d40Ng6U3oz5D7m71RvwzZXjaEENewrPFS8SEqme9Ib7MBOAXBYXbPZh7FRKpLUQEp0k9v2OjUgJI/wh4836BpI8cfZNlUpGkCkXuyFN17wqtFc8MGPFgfKX2IUdLs04RanBnrk7ba8ptbro9llDUHcRbqplojhWHSXrNN/KVVPWCIeiHytsXgGE7GROfZxLjL2OE3y5p1Us241V9qxdHac23JEW8P2BTZ1lUq24QWiK4Gv8W67KPZVvJqI6BRK0zBjz0jFRXet49Bh9Kqb09IRldvW2AvkQKgzWkRvMqzbWGaMJ5P0D "Prolog (SWI) - Proof Verifier") is a Prolog program you can use to verify that your proof is in fact valid. Each step should be placed on its own line. `->` should be used for implies and `-` should be used for not, atoms can be represented by any string of alphabetic characters. ### Metamath [Metamath](http://us.metamath.org) uses the Łukasiewicz system for its proofs in propositional calculus, so you may want to poke around there a bit. They also have a proof of the theorem this challenge asks for which can be found [here](http://us.metamath.org/mpeuni/con3.html). There is an explanation [here](http://us.metamath.org/mpeuni/mmset.html#proofs) of how to read the proofs. ### The Incredible Proof Machine @[Antony](https://codegolf.stackexchange.com/users/71303/antony) made me aware of a tool called [The Incredible Proof machine](http://incredible.pm/) which allows you to construct proofs in a number of systems using a nice graphical proof system. If you scroll down you will find they support the Łukasiewicz system. So if you are a more visual oriented person you can work on your proof there. Your score will be the number of blocks used minus 1. [Answer] # ~~88~~ ~~82~~ ~~77~~ 72 steps Thanks to H.PWiz for better combinator conversions that saved 10 steps! ### Explanation You might be familiar with the [Curry–Howard correspondence](https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence), in which theorems correspond to types and proofs correspond to programs of those types. The first two axioms in the Łukasiewicz system are actually the [K and S combinators](https://en.wikipedia.org/wiki/SK_combinator_calculus), and it’s well known that we can [translate](https://codegolf.stackexchange.com/q/105991/39242) lambda calculus expressions into the SK combinatory expressions. So let’s write down some expressions corresponding to our axioms (the following is valid Haskell syntax, which is convenient because we can quite literally check our proofs using the Haskell compiler): ``` data Not φ k :: φ -> (ψ -> φ) k x _ = x s :: (φ -> (ψ -> χ)) -> ((φ -> ψ) -> (φ -> χ)) s x y z = x z (y z) c :: (Not φ -> Not ψ) -> (ψ -> φ) c = error "non-computational axiom" ``` Then we can write a proof of the desired statement as a program in terms of `c` (this part takes a bit of cleverness, but it’s much easier to write this than an 72-line axiomatic proof): ``` pf :: (a -> b) -> (Not b -> Not a) pf x y = c (\z -> c (\_ -> y) (x (c (c (\_ -> z)) x))) k ``` and convert it into an SK combinatory expression: ``` pf' :: (a -> b) -> (Not b -> Not a) pf' = s (k (s (k (s c (k k))))) (s (k (s (s (k s) (s (k k) (s (k c) k))))) (s (k k) (s (k (s s (s (s (k c) (s (k c) k))))) k))) ``` The 17 `k`, 16 `s`, and 4 `c` combinators above correspond to the 16 LS1, 16 LS2, and 4 LS3 invocations in the proof below, and the 38 applications of a function to a value above correspond to the 38 MP invocations below. Why only 16 LS1 invocations? It turns out one of the `k` combinators above has a free type variable, and instantiating it carefully turns it into a duplicate of another one that has already been derived. ### The proof 1. (A → B) → (¬¬A → (A → B)) LS1 2. ¬¬A → (¬¬(A → B) → ¬¬A) LS1 3. (¬¬(A → B) → ¬¬A) → (¬A → ¬(A → B)) LS3 4. ((¬¬(A → B) → ¬¬A) → (¬A → ¬(A → B))) → (¬¬A → ((¬¬(A → B) → ¬¬A) → (¬A → ¬(A → B)))) LS1 5. ¬¬A → ((¬¬(A → B) → ¬¬A) → (¬A → ¬(A → B))) MP 4,3 6. (¬¬A → ((¬¬(A → B) → ¬¬A) → (¬A → ¬(A → B)))) → ((¬¬A → (¬¬(A → B) → ¬¬A)) → (¬¬A → (¬A → ¬(A → B)))) LS2 7. (¬¬A → (¬¬(A → B) → ¬¬A)) → (¬¬A → (¬A → ¬(A → B))) MP 6,5 8. ¬¬A → (¬A → ¬(A → B)) MP 7,2 9. (¬A → ¬(A → B)) → ((A → B) → A) LS3 10. ((¬A → ¬(A → B)) → ((A → B) → A)) → (¬¬A → ((¬A → ¬(A → B)) → ((A → B) → A))) LS1 11. ¬¬A → ((¬A → ¬(A → B)) → ((A → B) → A)) MP 10,9 12. (¬¬A → ((¬A → ¬(A → B)) → ((A → B) → A))) → ((¬¬A → (¬A → ¬(A → B))) → (¬¬A → ((A → B) → A))) LS2 13. (¬¬A → (¬A → ¬(A → B))) → (¬¬A → ((A → B) → A)) MP 12,11 14. ¬¬A → ((A → B) → A) MP 13,8 15. (¬¬A → ((A → B) → A)) → ((¬¬A → (A → B)) → (¬¬A → A)) LS2 16. (¬¬A → (A → B)) → (¬¬A → A) MP 15,14 17. (¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B)) LS2 18. ((¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B))) → (((¬¬A → (A → B)) → (¬¬A → A)) → ((¬¬A → (A → B)) → (¬¬A → B))) LS2 19. ((¬¬A → (A → B)) → (¬¬A → A)) → ((¬¬A → (A → B)) → (¬¬A → B)) MP 18,17 20. (¬¬A → (A → B)) → (¬¬A → B) MP 19,16 21. ((¬¬A → (A → B)) → (¬¬A → B)) → ((A → B) → ((¬¬A → (A → B)) → (¬¬A → B))) LS1 22. (A → B) → ((¬¬A → (A → B)) → (¬¬A → B)) MP 21,20 23. ((A → B) → ((¬¬A → (A → B)) → (¬¬A → B))) → (((A → B) → (¬¬A → (A → B))) → ((A → B) → (¬¬A → B))) LS2 24. ((A → B) → (¬¬A → (A → B))) → ((A → B) → (¬¬A → B)) MP 23,22 25. (A → B) → (¬¬A → B) MP 24,1 26. (¬¬A → B) → (¬B → (¬¬A → B)) LS1 27. ((¬¬A → B) → (¬B → (¬¬A → B))) → ((A → B) → ((¬¬A → B) → (¬B → (¬¬A → B)))) LS1 28. (A → B) → ((¬¬A → B) → (¬B → (¬¬A → B))) MP 27,26 29. ((A → B) → ((¬¬A → B) → (¬B → (¬¬A → B)))) → (((A → B) → (¬¬A → B)) → ((A → B) → (¬B → (¬¬A → B)))) LS2 30. ((A → B) → (¬¬A → B)) → ((A → B) → (¬B → (¬¬A → B))) MP 29,28 31. (A → B) → (¬B → (¬¬A → B)) MP 30,25 32. ¬B → (¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) LS1 33. (¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) LS3 34. ((¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ((¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) LS1 35. ¬B → ((¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 34,33 36. (¬B → ((¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B) → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → ((¬B → (¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B)) → (¬B → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) LS2 37. (¬B → (¬¬(¬¬A → (¬¬(A → B) → ¬¬A)) → ¬B)) → (¬B → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 36,35 38. ¬B → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) MP 37,32 39. (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) LS1 40. ((B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → (¬B → ((B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS1 41. ¬B → ((B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 40,39 42. (¬B → ((B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) → ((¬B → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS2 43. (¬B → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 42,41 44. ¬B → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 43,38 45. (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) LS2 46. ((¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → (¬B → ((¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS1 47. ¬B → ((¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 46,45 48. (¬B → ((¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) → ((¬B → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → (¬B → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS2 49. (¬B → (¬¬A → (B → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → (¬B → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 48,47 50. ¬B → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 49,44 51. (¬B → ((¬¬A → B) → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → ((¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) LS2 52. (¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 51,50 53. ((¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → ((A → B) → ((¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS1 54. (A → B) → ((¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 53,52 55. ((A → B) → ((¬B → (¬¬A → B)) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) → (((A → B) → (¬B → (¬¬A → B))) → ((A → B) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))))) LS2 56. ((A → B) → (¬B → (¬¬A → B))) → ((A → B) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) MP 55,54 57. (A → B) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) MP 56,31 58. (¬¬A → (¬¬(A → B) → ¬¬A)) → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (¬¬(A → B) → ¬¬A))) LS1 59. (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (¬¬(A → B) → ¬¬A)) MP 58,2 60. (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ((¬¬A → (¬¬(A → B) → ¬¬A)) → ¬A) LS3 61. ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ((¬¬A → (¬¬(A → B) → ¬¬A)) → ¬A)) → (((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (¬¬(A → B) → ¬¬A))) → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A)) LS2 62. ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → (¬¬A → (¬¬(A → B) → ¬¬A))) → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A) MP 61,60 63. (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A MP 62,59 64. ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A) → (¬B → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A)) LS1 65. ¬B → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A) MP 64,63 66. (¬B → ((¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))) → ¬A)) → ((¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A)) LS2 67. (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A) MP 66,65 68. ((¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A)) → ((A → B) → ((¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A))) LS1 69. (A → B) → ((¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A)) MP 68,67 70. ((A → B) → ((¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A)))) → (¬B → ¬A))) → (((A → B) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → ((A → B) → (¬B → ¬A))) LS2 71. ((A → B) → (¬B → (¬¬A → ¬(¬¬A → (¬¬(A → B) → ¬¬A))))) → ((A → B) → (¬B → ¬A)) MP 70,69 72. (A → B) → (¬B → ¬A) MP 71,57 [Try it online!](https://tio.run/##xVhbb6NGFH4/v2KKVBnUAdXJ27ZZya5UpVKqXdX7QBRbLK3xGgkDMrNJq2x@e3qGgcDg4WrwKpIDZ77vO5c5c7HjYxREX8zk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sWuoCkrarb5EwiK/fpJB6Kdp1EHiaOXmreviu/Z6Eu4gYGkKAXWnka5TfKti6/jKPq/nwRn@WN@yIO4eIZVrb6oRvRwPJ@J8dwDhvO860q@FK5O/Q4QYerwDixqC7PI8ieXLBHKdsEcaou6h2@YfSuxsQeYDi3/XefbkLyT0TK69ooOn1kWi@oi9JBOI5e5ceMM2vWs/6iPt/NN/RBQz9t1eHRsSBDWDDMl2pn6n69zNp7OBvO8916GPSTaz4E@pZlxLhaN/3@p6aU9UTKoLb/Dw "Prolog (SWI) – Try It Online") [Answer] # 91 Steps Full Proof: ``` 1. (A → B) → (¬¬A → (A → B)) LS1 2. (¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B)) LS2 3. ((¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B))) → ((A → B) → ((¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B)))) LS1 4. (A → B) → ((¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B))) MP 3,2 5. ((A → B) → ((¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B)))) → (((A → B) → (¬¬A → (A → B))) → ((A → B) → ((¬¬A → A) → (¬¬A → B)))) LS2 6. ((A → B) → (¬¬A → (A → B))) → ((A → B) → ((¬¬A → A) → (¬¬A → B))) MP 5,4 7. (A → B) → ((¬¬A → A) → (¬¬A → B)) MP 6,1 8. ¬A → (¬¬(B → (¬A → A)) → ¬A) LS1 9. (¬¬(B → (¬A → A)) → ¬A) → (A → ¬(B → (¬A → A))) LS3 10. ((¬¬(B → (¬A → A)) → ¬A) → (A → ¬(B → (¬A → A)))) → (¬A → ((¬¬(B → (¬A → A)) → ¬A) → (A → ¬(B → (¬A → A))))) LS1 11. ¬A → ((¬¬(B → (¬A → A)) → ¬A) → (A → ¬(B → (¬A → A)))) MP 10,9 12. (¬A → ((¬¬(B → (¬A → A)) → ¬A) → (A → ¬(B → (¬A → A))))) → ((¬A → (¬¬(B → (¬A → A)) → ¬A)) → (¬A → (A → ¬(B → (¬A → A))))) LS2 13. (¬A → (¬¬(B → (¬A → A)) → ¬A)) → (¬A → (A → ¬(B → (¬A → A)))) MP 12,11 14. ¬A → (A → ¬(B → (¬A → A))) MP 13,8 15. (¬A → (A → ¬(B → (¬A → A)))) → ((¬A → A) → (¬A → ¬(B → (¬A → A)))) LS2 16. (¬A → A) → (¬A → ¬(B → (¬A → A))) MP 15,14 17. (¬A → ¬(B → (¬A → A))) → ((B → (¬A → A)) → A) LS3 18. ((¬A → ¬(B → (¬A → A))) → ((B → (¬A → A)) → A)) → ((¬A → A) → ((¬A → ¬(B → (¬A → A))) → ((B → (¬A → A)) → A))) LS1 19. (¬A → A) → ((¬A → ¬(B → (¬A → A))) → ((B → (¬A → A)) → A)) MP 18,17 20. ((¬A → A) → ((¬A → ¬(B → (¬A → A))) → ((B → (¬A → A)) → A))) → (((¬A → A) → (¬A → ¬(B → (¬A → A)))) → ((¬A → A) → ((B → (¬A → A)) → A))) LS2 21. ((¬A → A) → (¬A → ¬(B → (¬A → A)))) → ((¬A → A) → ((B → (¬A → A)) → A)) MP 20,19 22. (¬A → A) → ((B → (¬A → A)) → A) MP 21,16 23. (¬A → A) → (B → (¬A → A)) LS1 24. ((¬A → A) → ((B → (¬A → A)) → A)) → (((¬A → A) → (B → (¬A → A))) → ((¬A → A) → A)) LS2 25. ((¬A → A) → (B → (¬A → A))) → ((¬A → A) → A) MP 24,22 26. (¬A → A) → A MP 25,23 27. ¬¬A → (¬A → ¬¬A) LS1 28. (¬A → ¬¬A) → (¬A → A) LS3 29. ((¬A → ¬¬A) → (¬A → A)) → (¬¬A → ((¬A → ¬¬A) → (¬A → A))) LS1 30. ¬¬A → ((¬A → ¬¬A) → (¬A → A)) MP 29,28 31. (¬¬A → ((¬A → ¬¬A) → (¬A → A))) → ((¬¬A → (¬A → ¬¬A)) → (¬¬A → (¬A → A))) LS2 32. (¬¬A → (¬A → ¬¬A)) → (¬¬A → (¬A → A)) MP 31,30 33. ¬¬A → (¬A → A) MP 32,27 34. ((¬A → A) → A) → (¬¬A → ((¬A → A) → A)) LS1 35. ¬¬A → ((¬A → A) → A) MP 34,26 36. (¬¬A → ((¬A → A) → A)) → ((¬¬A → (¬A → A)) → (¬¬A → A)) LS2 37. (¬¬A → (¬A → A)) → (¬¬A → A) MP 36,35 38. ¬¬A → A MP 37,33 39. (¬¬A → A) → ((A → B) → (¬¬A → A)) LS1 40. (A → B) → (¬¬A → A) MP 39,38 41. ((A → B) → ((¬¬A → A) → (¬¬A → B))) → (((A → B) → (¬¬A → A)) → ((A → B) → (¬¬A → B))) LS2 42. ((A → B) → (¬¬A → A)) → ((A → B) → (¬¬A → B)) MP 41,7 43. (A → B) → (¬¬A → B) MP 42,40 44. ¬¬B → (¬¬(B → (¬¬B → ¬B)) → ¬¬B) LS1 45. (¬¬(B → (¬¬B → ¬B)) → ¬¬B) → (¬B → ¬(B → (¬¬B → ¬B))) LS3 46. ((¬¬(B → (¬¬B → ¬B)) → ¬¬B) → (¬B → ¬(B → (¬¬B → ¬B)))) → (¬¬B → ((¬¬(B → (¬¬B → ¬B)) → ¬¬B) → (¬B → ¬(B → (¬¬B → ¬B))))) LS1 47. ¬¬B → ((¬¬(B → (¬¬B → ¬B)) → ¬¬B) → (¬B → ¬(B → (¬¬B → ¬B)))) MP 46,45 48. (¬¬B → ((¬¬(B → (¬¬B → ¬B)) → ¬¬B) → (¬B → ¬(B → (¬¬B → ¬B))))) → ((¬¬B → (¬¬(B → (¬¬B → ¬B)) → ¬¬B)) → (¬¬B → (¬B → ¬(B → (¬¬B → ¬B))))) LS2 49. (¬¬B → (¬¬(B → (¬¬B → ¬B)) → ¬¬B)) → (¬¬B → (¬B → ¬(B → (¬¬B → ¬B)))) MP 48,47 50. ¬¬B → (¬B → ¬(B → (¬¬B → ¬B))) MP 49,44 51. (¬¬B → (¬B → ¬(B → (¬¬B → ¬B)))) → ((¬¬B → ¬B) → (¬¬B → ¬(B → (¬¬B → ¬B)))) LS2 52. (¬¬B → ¬B) → (¬¬B → ¬(B → (¬¬B → ¬B))) MP 51,50 53. (¬¬B → ¬(B → (¬¬B → ¬B))) → ((B → (¬¬B → ¬B)) → ¬B) LS3 54. ((¬¬B → ¬(B → (¬¬B → ¬B))) → ((B → (¬¬B → ¬B)) → ¬B)) → ((¬¬B → ¬B) → ((¬¬B → ¬(B → (¬¬B → ¬B))) → ((B → (¬¬B → ¬B)) → ¬B))) LS1 55. (¬¬B → ¬B) → ((¬¬B → ¬(B → (¬¬B → ¬B))) → ((B → (¬¬B → ¬B)) → ¬B)) MP 54,53 56. ((¬¬B → ¬B) → ((¬¬B → ¬(B → (¬¬B → ¬B))) → ((B → (¬¬B → ¬B)) → ¬B))) → (((¬¬B → ¬B) → (¬¬B → ¬(B → (¬¬B → ¬B)))) → ((¬¬B → ¬B) → ((B → (¬¬B → ¬B)) → ¬B))) LS2 57. ((¬¬B → ¬B) → (¬¬B → ¬(B → (¬¬B → ¬B)))) → ((¬¬B → ¬B) → ((B → (¬¬B → ¬B)) → ¬B)) MP 56,55 58. (¬¬B → ¬B) → ((B → (¬¬B → ¬B)) → ¬B) MP 57,52 59. (¬¬B → ¬B) → (B → (¬¬B → ¬B)) LS1 60. ((¬¬B → ¬B) → ((B → (¬¬B → ¬B)) → ¬B)) → (((¬¬B → ¬B) → (B → (¬¬B → ¬B))) → ((¬¬B → ¬B) → ¬B)) LS2 61. ((¬¬B → ¬B) → (B → (¬¬B → ¬B))) → ((¬¬B → ¬B) → ¬B) MP 60,58 62. (¬¬B → ¬B) → ¬B MP 61,59 63. ¬¬¬B → (¬¬B → ¬¬¬B) LS1 64. (¬¬B → ¬¬¬B) → (¬¬B → ¬B) LS3 65. ((¬¬B → ¬¬¬B) → (¬¬B → ¬B)) → (¬¬¬B → ((¬¬B → ¬¬¬B) → (¬¬B → ¬B))) LS1 66. ¬¬¬B → ((¬¬B → ¬¬¬B) → (¬¬B → ¬B)) MP 65,64 67. (¬¬¬B → ((¬¬B → ¬¬¬B) → (¬¬B → ¬B))) → ((¬¬¬B → (¬¬B → ¬¬¬B)) → (¬¬¬B → (¬¬B → ¬B))) LS2 68. (¬¬¬B → (¬¬B → ¬¬¬B)) → (¬¬¬B → (¬¬B → ¬B)) MP 67,66 69. ¬¬¬B → (¬¬B → ¬B) MP 68,63 70. ((¬¬B → ¬B) → ¬B) → (¬¬¬B → ((¬¬B → ¬B) → ¬B)) LS1 71. ¬¬¬B → ((¬¬B → ¬B) → ¬B) MP 70,62 72. (¬¬¬B → ((¬¬B → ¬B) → ¬B)) → ((¬¬¬B → (¬¬B → ¬B)) → (¬¬¬B → ¬B)) LS2 73. (¬¬¬B → (¬¬B → ¬B)) → (¬¬¬B → ¬B) MP 72,71 74. ¬¬¬B → ¬B MP 73,69 75. (¬¬¬B → ¬B) → (B → ¬¬B) LS3 76. B → ¬¬B MP 75,74 77. (B → ¬¬B) → (¬¬A → (B → ¬¬B)) LS1 78. ¬¬A → (B → ¬¬B) MP 77,76 79. (¬¬A → (B → ¬¬B)) → ((¬¬A → B) → (¬¬A → ¬¬B)) LS2 80. (¬¬A → B) → (¬¬A → ¬¬B) MP 79,78 81. ((¬¬A → B) → (¬¬A → ¬¬B)) → ((A → B) → ((¬¬A → B) → (¬¬A → ¬¬B))) LS1 82. (A → B) → ((¬¬A → B) → (¬¬A → ¬¬B)) MP 81,80 83. ((A → B) → ((¬¬A → B) → (¬¬A → ¬¬B))) → (((A → B) → (¬¬A → B)) → ((A → B) → (¬¬A → ¬¬B))) LS2 84. ((A → B) → (¬¬A → B)) → ((A → B) → (¬¬A → ¬¬B)) MP 83,82 85. (A → B) → (¬¬A → ¬¬B) MP 84,43 86. (¬¬A → ¬¬B) → (¬B → ¬A) LS3 87. ((¬¬A → ¬¬B) → (¬B → ¬A)) → ((A → B) → ((¬¬A → ¬¬B) → (¬B → ¬A))) LS1 88. (A → B) → ((¬¬A → ¬¬B) → (¬B → ¬A)) MP 87,86 89. ((A → B) → ((¬¬A → ¬¬B) → (¬B → ¬A))) → (((A → B) → (¬¬A → ¬¬B)) → ((A → B) → (¬B → ¬A))) LS2 90. ((A → B) → (¬¬A → ¬¬B)) → ((A → B) → (¬B → ¬A)) MP 89,88 91. (A → B) → (¬B → ¬A) MP 90,85 ``` [Try it online!](https://tio.run/##xVhbbuM2FP3XKlgBhSWUNurkb2ZSQCpQpECKGdTzoSA2PG4tjwXIkmBxkhZpfruAriOryFK6kfRSlGSSIinZkqcIkEiX55z7JE0n26dx@nmcP0SvryuS7py7678@Llw0Hv@A7q4X@PH3dB0uyZ9Z6FzjVZxtV@4TLoAf3YlVMlrwE8t6yBliMakeHRvZb@05sV38kAMiSYkTMB375dkGI87JioS7MCFLWAFItHECfMswwhoF2//@/Y/MugXWtxrWLWO9Gytdce9FjoHLBMqXCQ9gkbN19iwsl/7L1JzCXWkrInBtAR4IwGaaFH7Ai@qCMqdaiSoEQey31Xp5gN5VzYRWSSvBYTIC6HQwv5p@/4RFEJ0KK86nlcvH4ApC8mhcS@y5MDx8VBOAXojQCu3jH10XVwa/ePSoTSFx2ZCgffBcTP/4TMZXebf2YU6W6WYZR0lYZ4Ye4TeaX6FP8@TTE0Y8aNKk2POE9iTbR1DVnISZMyM7gmfw5KI3Y5Rt96s8dA6e6bKL0Yzs4TedqCXdNDmkV5ge9hEJafS7VRZHOXEKA9PDSYy/AWf3qzhaM2cBXrLkWdUxDQc/ctEEGN2N0M1sOlrQvaimXhipFybqpZF6qaDOpN14EEjIdur8Gt6/J1s8Yy2HrYUrs5dAXaGROA6Tz2TrzPCNiwGLohzdfDcdl0yAcRZKagT2ywc0okw8gh9AaPNTBNkQ@zkpmIiaWLowDWm6ccpEpeQxYquwoWYLmEIBS/c49VIZpWVxt9UhcVP0/gvBQTVF8FI@xokDWa/iTbrfhetDWiPYFLKv5eEIoJb7cE/neB@C700Uw/Gelr7sSZRkX8iERKmNP1AuhvMDhjrLwmTtMAvdRfin6I9wXbzT9NmOKKtACdwy@HwzZl4n1uur4yE42ZHvFn@cl@eXZ2apF1xkqc3FK7fkNTQYuQe7golB9hGkAQ2nRrMbMjaG69CT1sLosz@fuqm0muGofVO741fPFYeR4L0aQiOES0KJrIexn4ormgaR5EsxSIjW0PFVUh37JRepLfszKXNlbRmMjnpiGTwpmPZudGNwBA2AxaEpk1dOeh8FXap9ZVXF6B2qdY44y8P42F5rymauyPm9qMpuGh8ZrMBaxwWgqae@ORJS4/IIfjMtjx4Q3NFTFb3@yBEMkiNxk6kQzc/YNoIrBNQqbx2n3biiiIxmuI1D6RSmssaeqpmeoWD8FBjXNUXxmiebMlgpAE@XuBLLh@YJPE99qZId6VeNd03j7dno0hyU33Jn7KRgSMsvK@arPvsrM/ytP//pc@MuqAWW637jKBUYinthX0VXNg/uQCzc4OFb5439IHtU55tl7Vapr@RJmuUOY3ekvlw2vurHdvU4rkTVwqRbgKq8fr3fhlEzlWVIN7ryDZqK9TXyqG9ip86RoeBdqvj/eNa1r31YVTQNyzo1OENPzO1WMIyhnKSmLgI1FEeecLj69TGqYIqfFIKiFK8eyRnFj6gOVFcKuLNL61R/B7ihSqqUNEdwPxVDv3zdyIjJqUsgTl4nnLGkvvp816bVCE/ZtU4sMfxixpsYbitVc869AcNXXIzq7xC@cNOwNCvi9w6/eTsRL9KSk1q9A0r8L71eq@Xfwlqi8V/DptBP8tXyrcdv/c7CRd1fxfDtR9Fm9U3akzqkQ7V2SEs0dkjvzjrNV0uHTOPWiLq/iqJDfOH/Aw "Prolog (SWI) – Try It Online") A more human-readable version using 5 lemmas: ``` Lemma 1: From A → B and B → C, instantiate A → C. (5 steps) 1. B → C given 2. (B → C) → (A → (B → C)) L.S.1 3. A → (B → C) M.P. (1,2) 4. (A → (B → C)) → ((A → B) → (A → C)) L.S.2 5. (A → B) → (A → C) M.P. (3,4) 6. A → B given 7. A → C M.P. (6,5) Lemma 2: ¬A → (A → B) (7 steps) 1. ¬A → (¬B → ¬A) L.S.1 2. (¬B → ¬A) → (A → B) L.S.3 3. ¬A → (A → B) Lemma 1 (1,2) Lemma 3: From A → (B → C) and A → B, instantiate A → C. (3 steps) 1. A → (B → C) given 2. (A → (B → C)) → ((A → B) → (A → C)) L.S.2 3. (A → B) → (A → C) M.P. (1,2) 4. A → B given 5. A → C M.P. (4,3) Lemma 4: ¬¬A → A (31 steps) 1. ¬A → (A → ¬(B → (¬A → A))) Lemma 2 2. (¬A → (A → ¬(B → (¬A → A)))) → ((¬A → A) → (¬A → ¬(B → (¬A → A)))) L.S.2 3. (¬A → A) → (¬A → ¬(B → (¬A → A))) M.P. (1,2) 4. (¬A → ¬(B → (¬A → A))) →((B → (¬A → A)) → A) L.S.3 5. (¬A → A) → ((B → (¬A → A)) → A) Lemma 1 (3,4) 6. (¬A → A) → (B → (¬A → A)) L.S.1 7. (¬A → A) → A Lemma 3 (5,6) 8. ¬¬A → (¬A → A) Lemma 2 9. ¬¬A → A Lemma 1 (8,7) Lemma 5: (A → B) → (¬¬A → B) (43 steps) 1. (A → B) → (¬¬A → (A → B)) L.S.1 2. (¬¬A → (A → B)) → ((¬¬A → A) → (¬¬A → B)) L.S.2 3. (A → B) → ((¬¬A → A) → (¬¬A → B)) Lemma 1 (1,2) 4. ¬¬A → A Lemma 4 5. (¬¬A → A) → ((A → B) → (¬¬A → A)) L.S.1 6. (A → B) → (¬¬A → A) M.P. (4,5) 7. (A → B) → (¬¬A → B) Lemma 3 (3,6) Theorem: (A → B) → (¬B → ¬A) 1. (A → B) → (¬¬A → B) Lemma 5 2. ¬¬¬B → ¬B Lemma 4 3. (¬¬¬B → ¬B) → (B → ¬¬B) L.S.3 4. B → ¬¬B M.P. (2,3) 5. (B → ¬¬B) → (¬¬A → (B → ¬¬B)) L.S.1 6. ¬¬A → (B → ¬¬B) M.P. (4,5) 7. (¬¬A → (B → ¬¬B)) → ((¬¬A → B) → (¬¬A → ¬¬B)) L.S.2 8. (¬¬A → B) → (¬¬A → ¬¬B) M.P. (6,7) 9. (A → B) → (¬¬A → ¬¬B) Lemma 1 (1,8) 10.(¬¬A → ¬¬B) → (¬B → ¬A) L.S.3 11.(A → B) → (¬B → ¬A) Lemma 1 (9,10) ``` [Answer] **59 steps** Norman Megill, author of Metamath has [told me](https://groups.google.com/d/msg/metamath/4Xaz4dtB_2E/QPZJbs8MDgAJ) about a 59 step proof, which I'm going to post here in this community wiki. The original can be found in theorem 2.16 on this page. <http://us.metamath.org/mmsolitaire/pmproofs.txt> Norm says: This page would provide plenty of challenges for you to beat! Here's the proof ``` ((P -> Q) -> (~ Q -> ~ P)); ! *2.16 ((P -> Q) -> (~ Q -> ~ P)); ! Result of proof DD2D1DD2D13DD2D1DD22D2DD2D13DD2D1311D2D1D3DD2DD2D13DD2D1311 ; ! 59 steps ``` The proof is in Polish notation, so it starts from the conclusion and continues backwards until every term has been satisified by an axiom. The character mapping is as follows: "1" is LS axiom 1, "2" is LS axiom 2, "3" is LS axiom 3, and "D" is Modus Ponens. Here's the proof in @W-W's suggested format ``` 01 ax-1 $a |- ( ¬ ¬ ¬ B → ( ¬ B → ¬ ¬ ¬ B ) ) 02 ax-1 $a |- ( ¬ ¬ ¬ B → ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) ) 03 ax-3 $a |- ( ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) 04 ax-1 $a |- ( ( ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) → ( ¬ ¬ ¬ B → ( ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) ) ) 05 3,4 ax-mp $a |- ( ¬ ¬ ¬ B → ( ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) ) 06 ax-2 $a |- ( ( ¬ ¬ ¬ B → ( ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) ) → ( ( ¬ ¬ ¬ B → ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) ) → ( ¬ ¬ ¬ B → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) ) ) 07 5,6 ax-mp $a |- ( ( ¬ ¬ ¬ B → ( ¬ ¬ ( ¬ B → ¬ ¬ ¬ B ) → ¬ ¬ ¬ B ) ) → ( ¬ ¬ ¬ B → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) ) 08 2,7 ax-mp $a |- ( ¬ ¬ ¬ B → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) 09 ax-3 $a |- ( ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) 10 ax-1 $a |- ( ( ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) → ( ¬ ¬ ¬ B → ( ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) ) ) 11 9,10 ax-mp $a |- ( ¬ ¬ ¬ B → ( ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) ) 12 ax-2 $a |- ( ( ¬ ¬ ¬ B → ( ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) ) → ( ( ¬ ¬ ¬ B → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) → ( ¬ ¬ ¬ B → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) ) ) 13 11,12 ax-mp $a |- ( ( ¬ ¬ ¬ B → ( ¬ ¬ B → ¬ ( ¬ B → ¬ ¬ ¬ B ) ) ) → ( ¬ ¬ ¬ B → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) ) 14 8,13 ax-mp $a |- ( ¬ ¬ ¬ B → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) 15 ax-2 $a |- ( ( ¬ ¬ ¬ B → ( ( ¬ B → ¬ ¬ ¬ B ) → ¬ B ) ) → ( ( ¬ ¬ ¬ B → ( ¬ B → ¬ ¬ ¬ B ) ) → ( ¬ ¬ ¬ B → ¬ B ) ) ) 16 14,15 ax-mp $a |- ( ( ¬ ¬ ¬ B → ( ¬ B → ¬ ¬ ¬ B ) ) → ( ¬ ¬ ¬ B → ¬ B ) ) 17 1,16 ax-mp $a |- ( ¬ ¬ ¬ B → ¬ B ) 18 ax-3 $a |- ( ( ¬ ¬ ¬ B → ¬ B ) → ( B → ¬ ¬ B ) ) 19 17,18 ax-mp $a |- ( B → ¬ ¬ B ) 20 ax-1 $a |- ( ( B → ¬ ¬ B ) → ( A → ( B → ¬ ¬ B ) ) ) 21 19,20 ax-mp $a |- ( A → ( B → ¬ ¬ B ) ) 22 ax-2 $a |- ( ( A → ( B → ¬ ¬ B ) ) → ( ( A → B ) → ( A → ¬ ¬ B ) ) ) 23 21,22 ax-mp $a |- ( ( A → B ) → ( A → ¬ ¬ B ) ) 24 ax-1 $a |- ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ( A → ¬ ¬ B ) ) ) 25 ax-1 $a |- ( ¬ ¬ A → ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) ) 26 ax-3 $a |- ( ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) 27 ax-1 $a |- ( ( ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) → ( ¬ ¬ A → ( ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) ) ) 28 26,27 ax-mp $a |- ( ¬ ¬ A → ( ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) ) 29 ax-2 $a |- ( ( ¬ ¬ A → ( ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) ) → ( ( ¬ ¬ A → ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) ) → ( ¬ ¬ A → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) ) ) 30 28,29 ax-mp $a |- ( ( ¬ ¬ A → ( ¬ ¬ ( A → ¬ ¬ B ) → ¬ ¬ A ) ) → ( ¬ ¬ A → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) ) 31 25,30 ax-mp $a |- ( ¬ ¬ A → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) 32 ax-3 $a |- ( ( ¬ A → ¬ ( A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → A ) ) 33 ax-1 $a |- ( ( ( ¬ A → ¬ ( A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → A ) ) → ( ¬ ¬ A → ( ( ¬ A → ¬ ( A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → A ) ) ) ) 34 32,33 ax-mp $a |- ( ¬ ¬ A → ( ( ¬ A → ¬ ( A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → A ) ) ) 35 ax-2 $a |- ( ( ¬ ¬ A → ( ( ¬ A → ¬ ( A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → A ) ) ) → ( ( ¬ ¬ A → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) → ( ¬ ¬ A → ( ( A → ¬ ¬ B ) → A ) ) ) ) 36 34,35 ax-mp $a |- ( ( ¬ ¬ A → ( ¬ A → ¬ ( A → ¬ ¬ B ) ) ) → ( ¬ ¬ A → ( ( A → ¬ ¬ B ) → A ) ) ) 37 31,36 ax-mp $a |- ( ¬ ¬ A → ( ( A → ¬ ¬ B ) → A ) ) 38 ax-2 $a |- ( ( ¬ ¬ A → ( ( A → ¬ ¬ B ) → A ) ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → A ) ) ) 39 37,38 ax-mp $a |- ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → A ) ) 40 ax-2 $a |- ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ( ¬ ¬ A → A ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) 41 ax-2 $a |- ( ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ( ¬ ¬ A → A ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) → ( ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → A ) ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) ) 42 40,41 ax-mp $a |- ( ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → A ) ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) 43 39,42 ax-mp $a |- ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) 44 ax-1 $a |- ( ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) ) 45 43,44 ax-mp $a |- ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) 46 ax-2 $a |- ( ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ( A → ¬ ¬ B ) ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) → ( ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ( A → ¬ ¬ B ) ) ) → ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) ) 47 45,46 ax-mp $a |- ( ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ( A → ¬ ¬ B ) ) ) → ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ¬ ¬ B ) ) ) 48 24,47 ax-mp $a |- ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ¬ ¬ B ) ) 49 ax-3 $a |- ( ( ¬ ¬ A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) 50 ax-1 $a |- ( ( ( ¬ ¬ A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) → ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) ) 51 49,50 ax-mp $a |- ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) 52 ax-2 $a |- ( ( ( A → ¬ ¬ B ) → ( ( ¬ ¬ A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) → ( ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) ) 53 51,52 ax-mp $a |- ( ( ( A → ¬ ¬ B ) → ( ¬ ¬ A → ¬ ¬ B ) ) → ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) 54 48,53 ax-mp $a |- ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) 55 ax-1 $a |- ( ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) → ( ( A → B ) → ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) ) 56 54,55 ax-mp $a |- ( ( A → B ) → ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) 57 ax-2 $a |- ( ( ( A → B ) → ( ( A → ¬ ¬ B ) → ( ¬ B → ¬ A ) ) ) → ( ( ( A → B ) → ( A → ¬ ¬ B ) ) → ( ( A → B ) → ( ¬ B → ¬ A ) ) ) ) 58 56,57 ax-mp $a |- ( ( ( A → B ) → ( A → ¬ ¬ B ) ) → ( ( A → B ) → ( ¬ B → ¬ A ) ) ) 59 23,58 ax-mp $a |- ( ( A → B ) → ( ¬ B → ¬ A ) ) ``` [Try it online!](https://tio.run/##zVfdbts2FL7XU3ACCksYLczJXdsMkAcMGZCixdwLBbGharNcC5AlwWKTDllu9wB7jj5FH2Uvkh2KkkVKpH4s2S0aJDL5/ZxzeA7lJvs4jD9O04fg@dkj8c64u/77/cpE0@nP6O56hR//jNe@S/5KfOMae2Gy9cwnnAHfm5aWM1rwlqY9pAyxsopHQ0f6K31JdBM/pICIYmI4TEf/@kWHRZwSj/g7PyIu7AAk2BgOvmUYYY@C9f/@@bfKugXWCwXrlrFeT6VW3OcsR8dkAvkHiwewyNk@exa2c/88NSOzy9eyCExdgDsCsJ4mhZd4UV1Q5lQLUYkgiP3hrd0SelccJhxVZccpO8OBk3aWV7OfnrAIol2hhemssHx0riAkm8blYtuE5uGjsgB6IUIL9Bz/Ypq4WJhnjzZdk0hc1iToOdgmpn/mTGYuc9f2fkrceOOGQeQfMkOP8Bstr9CHZfThCSMeZNUp@jKiZ5LsA6hqSvzEWJAdwQt4MtHLKUq2ey/1jdKZbpsYLcgeftOOcunQpJBetvSwD4hPo995SRikxMgWmB6OQvwDmN17YbBmZg52WfKs6piGgx@5aByM7iboZjGbrOgsyqkXjdSLJuplI/VSQl1UprEUiMh2Zvzu378lW7xgRw6jhYtlO4K6wkHi0I8@kq2xwDcmBiwKUnTz42yaMwHGrVBSLbA379CEMvEE/gFCmZ8kyJrYb1HGRHSJpQvdEMcbI0@0kjxGbBcGarGCLhSwdMapS7FY2Ran7RAS10VvPxHsFF0EH/LHMDIgay/cxPudvy7TmsBQVL3c8gqgK/f@nvbx3gfvTRDC9R7nXroVRMknYpEg1vE7ysVwf0BTJ4kfrQ22QqcI/xp89tfZZ5o@m4i8CpTAbYPnyylztbTnZwN9/ZL/zBHc8cgoH7kdE5maHAo/KopUozeJdzrglVHmHid3EQhcRU5vrDiKMxhzp3fmjEWnAQ2oOrbe9f9OYtEG8bk8OsC5Q1DnN6@N4KjKbWM3rlnLqI1s1jxeY2fWMlKD78Butf2G/tqRzIZj6ta83V@58gTbOuYoMU2xI7MQ7nHeqlCqrGUaVRxj2yqVjGU3eDRxizozRNWtfgW24jiU/D1mNzqImOI9IdMrkNXvSs3Yg65dTo0q15E1pVUY20NWxdE9uHqfLg9Rt2dHSGvdtXpn9tR6c4oYG1HiZItR22KPD9NR9/VAXWUvD9VV9e/geJU9e9TN0FaZM/hoPdDSqrZ1TftboR6z@hQ7s3tw6@y6pvrdMbr6gXd85Y6vvOw98M3j0AZrHJ1H1/thvGqfSD2vwKliL3v2yG@GLdVt79Ez@2q9ObUulvAOX99tRde2cnp1abtan67soNajC7vE1qfruk@yugon99F6oNsiauyL@YAqDFAQYj4uhuqZN/2PVpVz@wmPpKp1wmn/Aw "Prolog (SWI) – Try It Online") Here it is in The Incredible Proof Machine [![enter image description here](https://i.stack.imgur.com/zpFi0.png)](https://i.stack.imgur.com/zpFi0.png) [png](https://raw.githubusercontent.com/Antony74/contraposition/master/incredible-proof.png) [svg](https://antony74.github.io/contraposition/incredible-proof.svg) ]
[Question] [ **This question already has answers here**: [DropSort it like it's hot](/questions/137549/dropsort-it-like-its-hot) (24 answers) Closed 2 years ago. There is a "sorting" algorithm often called Stalin Sort, where instead of sorting an array, you just remove any items that are out of order. In this challenge, you'll implement part of a sorting algorithm which recursively sorts the removed items, then merges the arrays to form one (properly sorted) array. ## Algorithm Take this array: ``` [7, 1, 2, 8, 4, 10, 1, 4, 2] ``` There are a few sets of items you could remove to make it increasing. For this challenge, you should keep the first item the same, even if it doesn't result in the longest possible list of sorted items. This gives us `[7, 8, 10]`, with `[1, 2, 4, 1, 4, 2]` as the removed items. If you also do this with the removed items, you get `[1, 2, 4, 4]`, with `[1, 2]` as the removed items. Because this is also sorted, we're done. This gives us three arrays: ``` [7, 8, 10] [1, 2, 4, 4] [1, 2] ``` This is the format of the output. If you wanted to use this to sort the array, you'd recursively merge the last two arrays to form one sorted list: ``` [1, 1, 2, 2, 4, 4, 7, 8, 10] ``` ## Task Take an array of integers as input. Return all of the arrays of removed items, before they are merged, as shown above. You can do this by returning a 2d array, or printing any unambiguous representation of the arrays (for example, comma separated numbers and newline separated arrays). ## Test cases **Input:** `[1, 2]` ``` [1, 2] ``` **Input:** `[2, 1]` ``` [2] [1] ``` **Input:** `[1, 2, 4, 1, 2]` ``` [1, 2, 4] [1, 2] ``` **Input:** `[2, 1, 1, 2, 2]` ``` [2, 2, 2] [1, 1] ``` **Input:** `[1, 2, 4, 8, 4, 2, 1]` ``` [1, 2, 4, 8] [4] [2] [1] ``` **Input:** `[8, 4, 2, 1, 2, 4, 8]` ``` [8, 8] [4, 4] [2, 2] [1] ``` **Input:** `[7, 1, 2, 8, 4, 10, 1, 4, 2]` ``` [7, 8, 10] [1, 2, 4, 4] [1, 2] ``` **Input:** `[7, 7, 8, 7, 7]` ``` [7, 7, 8] [7, 7] ``` ## Other This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 10 bytes ``` ¬ª\nx@¬µ∆¨≈ì-∆ù ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLCu1xcbnhAwrXGrMWTLcadIiwiw4fFkuG5mClZIiwiIixbIlsxLCAyXSwgWzIsIDFdLCBbMSwgMiwgNCwgMSwgMl0sIFsxLCAwLCAwLCAxLCAxXSwgWzEsIDIsIDQsIDgsIDQsIDIsIDFdLCBbOCwgNCwgMiwgMSwgMiwgNCwgOF0sIFs3LCAxLCAyLCA4LCA0LCAxMCwgMSwgNCwgMl0iXV0=) Pleasantly surprised this works without having to stick any reverses in or anything. `·∏ü"¬ª\F¬µ∆¨≈ì-∆ù` also works for the same length. Ultimately the result of trying to replace the `¬π` in hyper-neutrino's answer with something else, funnily enough. ``` ¬µ∆¨ Repeat while unique, collecting all results including the input: n For each element, is it not equal to ¬ª\ the largest element of the list at that point? x@ Keep only the non-equal elements, i.e. the "out of order" elements. ∆ù For each overlapping pair of adjacent results: ≈ì- for each element of the second, remove its last occurrence from the first. ``` [Answer] # [R](https://www.r-project.org/), ~~58~~ 57 bytes ``` f=function(a,b=a<cummax(a)){any(b)&&f(a[b]);print(a[!b])} ``` [Try it online!](https://tio.run/##lY/RCsIwDEXf9xdOGAn0wY6Bgu5LVEZaVii4TrpWFPHbazt9VFgTAgnk3NzYYHvp7aRvfTc5umjTTaN1bVCt8kY6PRogJlo6SD8MdAdCfJJ5gMCqUkBHccb91WrjYr@Kw@u3IEjgrEYsJDko1ylOpsTi33LN@PLlqMwalqXP2SYmz7@yi5Vl7gt84OXYdkYSzJPPZn6uCG8 "R ‚Äì Try It Online") Prints the arrays in reverse order. Add one byte to print in the same order as the example ([try it here](https://tio.run/##lY/bCsIwDIbv9xbOmwR6YcdAQfskU0ZaNiy4DnrwgPjstZteKqwJgRDy/fljo@1UsE5fu9Z5umjTutF6EXvRB6O8Hg0Qk4IOKgwD3YEQn@483oCalTzhXvdA5gESMTVNmrx@K4ICzirEQpGHcj3F0ZRY/FuuGF@@nJRZzbL0Oduk5PlXdqmyzH2BD7wc287IBPPJZz0/V8Q3)): ``` f=function(a,b=a<cummax(a)){show(a[!b]);if(any(b))f(a[b])} ``` [Answer] # [Haskell](https://www.haskell.org/), ~~97~~ 90 bytes ``` f(h:t)=g[h]t[] f[]=[] g s[]r=reverse s:f r g(a:b)(h:t)r|h<a=g(a:b)t$r++[h]|1>0=g(h:a:b)t r ``` [Try it online!](https://tio.run/##XYzNagMhFIX3PsUhZDHDGIhDIUFiniBdZWmlGHDG0GQa1DSbefepP@20BETP/c53tdp/mMtlmrrK8lCLXloVpCKdVCI@PbxUTjjzZZw38LyDI32l@anOvhvtTosCwtI1TVwf2X4dkeUZwk1XfR4gcNW313fc7uEY3GGAJKi8/XwgGB9qNA0W/G1YpPDTLLt/XaoIxkx2q7gMyWiraAotZSUwipbihSKFGa3zieHZ2ua7nYu/eTZKsflFxWDlu@Qqpcj0DQ "Haskell ‚Äì Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 88 bytes ``` f=lambda s:s and[[s.pop(i)for i,x in[*enumerate(s)][::-1]if x==max(s[:i+1])][::-1]]+f(s) ``` [Try it online!](https://tio.run/##XU/RCsMgDHz3K/KoqxuzG2wIfknwwVFlwmqlOui@vtN23WAQEu4uOXLxle9DOM2zUw/T3zoDSSYwoUNMhzhE6pkbRvB8Ah9wZ8Ozt6PJliamUcq90N7BpFRvJppQ@kboTdCNK1tztiknUIAEBYdWc4ItB1FnxRzOBX2EMo9Lif@N69K3wx/66pW@bMSqi9XovJprQmqSXHLA8pMkAHH0IVNHM2PzGw "Python 3 ‚Äì Try It Online") ## How it works : let say our list is `[7, 1, 2, 8, 4, 10, 1, 4, 2]`. * we iterate through the list backward, poping the items which are the maximum of the list up to them. Here `10` is equal to max of `[7, 1, 2, 8, 4, 10]`, `8` of `[7, 1, 2, 8]` and `7` of `[7]`. So we have `[10, 8, 7]` * we reverse it to have `[7, 8, 10]` * we return it along with the result of the function applied to the remaining items (`[1, 2, 4, 1, 4, 2]`) * when the list is empty, it returns itself (`[]`) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes Anonymous tacit prefix function. ``` {m/‚終䣂éï‚Üê‚çµ/‚ç®~m‚Üê‚終ↂåà\‚çµ}‚磂Ⱐ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzpX/1Hv1kddix/1TX3UNgHIBvJX1OVC2I86Fzzq6YgBsmof9S5@1LnwfxpYou9RV/Oj3jWPerccWm/8qG0iUHNwkDOQDPHwDP6fpmCoo2DElaZgpKNgyAXh6SiY6MCEgZQBGBmiyVuASaguBAcuDRQ1h/Eh0oYQU0AKAQ "APL (Dyalog Unicode) ‚Äì Try It Online") `{`‚Ķ`}‚磂â°`‚ÄÉapply the following lambda until stable (i.e. the argument is empty ‚ÄÉ`‚åà\‚çµ`‚ÄÉcumulative maximum or argument ‚ÄÉ`‚終â†`‚ÄÉBoolean mask indicating which elements of the argument differ ‚ÄÉ`m‚Üê`‚ÄÉassign to `m` (for **m**ask) ‚ÄÉ`~`‚ÄÉinvert the mask (lit. logical NOT) ‚ÄÉ`‚çµ/‚ç®`‚ÄÉfilter the argument using that mask ‚ÄÉ`‚éï‚Üê`‚ÄÉprint that ‚ÄÉ`‚終ä£`‚ÄÉignore that in favour of the argument ‚ÄÉ`m/‚çµ`‚ÄÉfilter the argument using the mask `m` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes ``` {x@.=+(x<|\x*)\1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxtTkEOwjAMu+8VObZQoSWq1ImAxD9Yr3tDJaBvx2mmiQMX17EdN9v11R6X+zm023ttp7jyZ5q2ZyEmoYUy8QyaSarJEGtPQHAhrj0k0cTRLUtbIAyuwOi5UWaG2AvjZ8P+8Kp91pT1aN1dd5BZ4Gd0W40n/lzaQ4HAs/recUkh04EjAa7A+AVYMTXG) Collaborative effort from @ngn, @Bubbler and @chrispsn at [the k tree](https://chat.stackexchange.com/rooms/90748/the-k-tree). Assumes positive numbers. With 2 more bytes it can handle negatives: ``` {x@.=+~{x*x<|\x}\x} ``` --- My original solution: # [K (ngn/k)](https://codeberg.org/ngn/k), 27 bytes ``` f:{{(,x),f y}/x@&'~:\x=|\x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxVjsEKAyEMRO9+RU6tQqBVBGVDof+x69VvsGzXb++sWksvg8m8yZiXfddcDGd6HbfyvFzrspXHeyuHUnm1TC5VtuQwOCabqmYnbM0wmTy2jdKgyAvUDLg73XQwHcz/ZGw6Drc8RWEvs2P9ETOTwEZwHm3n0U6GL9IT9t5m39sDRWykN8w/IhIafz4aBU6gRn0AvNs7Ow==) ``` f:{{(,x),f y}/x@&'~:\x=|\x} x=|\x x equals cumulative max ~:\ append negation x@&' partition x using both boolean masks {(,x),f y} join first partition with recursive call on second partition / until convergence ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 21 20 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) *-1 byte by omitting `ùïä` in the header for the base case* ``` {‚ü®‚ü©:ùï©;ùïä‚ä∏‚àæ‚üú<¬¥‚åà`‚ä∏=‚ä∏‚äîùï©} ``` [Try it here](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHvin6jin6k68J2VqTvwnZWK4oq44oi+4p+cPMK04oyIYOKKuD3iirjiipTwnZWpfQoK4o2J4omNRsKo4p+oMeKAvzIsIDLigL8xLCAx4oC/MuKAvzTigL8x4oC/MiwgMeKAvzDigL8w4oC/MeKAvzEsIDHigL8y4oC/NOKAvzjigL804oC/MuKAvzEsIDjigL804oC/MuKAvzHigL8y4oC/NOKAvzgsIDfigL8x4oC/MuKAvzjigL804oC/MTDigL8x4oC/NOKAvzLin6kK). ``` {‚ü®‚ü©:ùï©;ùïä‚ä∏‚àæ‚üú<¬¥‚åà`‚ä∏=‚ä∏‚äîùï©} ‚ü®‚ü©:ùï©; # If the input is an empty list, return the input, otherwise: ‚åà`‚ä∏=‚ä∏‚äîùï© # Group the input by equality with the max scan. ¬¥ # Between the two groups: ùïä‚ä∏ # recurse on the left group ‚àæ‚üú< # and join to the enclosed right group. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 13 bytes ``` ¬ª\=¬π∆ô∆ä·πÑ·πõ¬•/¬µ√êL ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLCu1xcPcK5xpnGiuG5hOG5m8KlL8K1w5BMIiwiIiwiIixbIls3LCAxLCAyLCA4LCA0LCAxMCwgMSwgNCwgMl0iXV0=) I think this might be pretty much identical to Ad√°m's answer but I'm not really sure; came up with it independently anyway. ``` ¬ª\=¬π∆ô∆ä·πÑ·πõ¬•/¬µ√êL Main Link ¬µ√êL Repeat until the results are no longer unique (which happens when it hits the empty array) ¬ª\ Cumulative maximum; get the largest element so far at each position = Vectorizing equality; basically find which elements should be extracted ¬π∆ô Key by identity; separate into groups based on the equality map (the first element will always be included, so we don't have to worry about group ordering) / Reduce; since the list will necessarily have two elements, call last dyad on these two ·πÑ·πõ¬• Combined dyad; print out the left element and return the right element ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` Ôº∑Œ∏¬´‚âî‚ü¶‚üߜւâŒ∏‚ஂàߜւÄπŒ∫‚åàœÖ¬¨‚äûԺ؜֌∫Œ∏Ôº©‚ü¶œÖ ``` [Try it online!](https://tio.run/##PYw9C8JAEERr/RVb7sIKGgQFqyBYqUl/XHHEwxy5JOY@VBB/@5mksHtvZpiqVq7qlU3pVRurAQeCz3KRe2/uHQrJEOnw95OxQTscGAqHeXfDyHDW3mPDcFFv08YWIxExXPuAZfR18dBOhd5Ny4bmapgOS2e6gEflA4ooaYy@KQmxY9gwZAx7hu3I69lHyqRMq6f9AQ "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation: ``` Ôº∑Œ∏¬´ ``` Repeat until there is nothing left to sort. ``` ‚âî‚ü¶‚üßœÖ ``` Start each iteration with an empty result. ``` ‚âŒ∏‚ஂàߜւÄπŒ∫‚åàœÖ¬¨‚äûԺ؜֌∫Œ∏ ``` Push the sorted values to the result while filtering them out from the input list. ``` Ôº©‚ü¶œÖ ``` Output the sorted values, double-spacing between each sorted list. [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` f=->a,*b{a[c=0]&&f[a.map{|i|i<c ?i:b<<c=i}-[p(b)]]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5RRyupOjE62dYgVk0tLTpRLzexoLomsybTJlnBPtMqycYm2TazVje6QCNJMza29n90tKGOglGsDpcCmKGjYKKjgCxiAEZAhiGqGgswaQQTR3DhCsDi5jARiAJDiFkgpbFcsXqpickZ1TWJNQpAh8ZaKxSUlhTX/gcA "Ruby ‚Äì Try It Online") ### Commented ``` f=->a,*b{ # lambda with a = input array, b = empty array a[ 0]&& # if a is not empty c=0 # initialise c, the maximum value encountered so far, to 0 f[ # recursively call f a.map{|i| # map each element i of a to either: i<c ?i # itself, if i<c :b<< i # the array b with i appended, otherwise c=i # update c } # end of map -[ ] # remove from the call to f all elements equal to... p(b) # print and return b ] # end of recursive call } # end of lambda ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes ``` f=If[#=={},{},Join[{#},f@#2]&@@Fold[Insert[#,#2,{If[#2<#[[1,-1]],2,1],-1}]&,{#[[{1}]],{}},Rest@#]]& ``` [Try it online!](https://tio.run/##PY1NC8IwDIZ/TGAHiWiLoKCDnoR5Eq8lh6ErDtwGW2@hv72@20RowpMnH@3q@G66OrbPOudQVsFTWWpivNvQ9l4pcXBkpXDuOnxevuqnZoyemCzrPG4v5L3hrRFhy0ZASQpWWAUJTiV@NFN0JFLk@9j20W3CzqkatvgJS8hgPvDfzLTw6k@Ide5Hq0V9XHi2Zg9EM6Vz/gI "Wolfram Language (Mathematica) ‚Äì Try It Online") ``` f= If[#=={},{}, # recursive base case Join[{#},f@#2]&@@ # append recursive result Fold[ Insert[#,#2,{If[#2<#[[1,-1]],2,1],-1}]&, # insert onto end of 1st or 2nd list {#[[{1}]],{}}, # init 1st list with first input and 2nd list empty Rest@# # fold across rest of list ]]& ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~104~~ \$\cdots\$ ~~98~~ 96 bytes ``` k;m;*c;*b;f(*a,l){for(;k=l;)for(m=*(c=b=a);k--;++b)*b<m?*c++=*b:printf("\n%d "+(b>a),m=*b,--l);} ``` [Try it online!](https://tio.run/##hVfbbqMwEH3vV1hIlYCAtvhCu6VpH1b7FUlUJYR0kzi0CpE22iq/vlkDBsb20I1aiD3jmTnn@JY8zuWyfLte99khC/MsXGUbP1xGMvjcvB/9bD@VWVB/O0xDP5@upssg28dxNpmsgnD1dHgJ88lkGq4eP47b8rTxvXl5uybexF89L4NIDVpFcSyD7HJVZnJYbks/IJ83RH3qjlNRnV6T2YJMyWcSEXrJhm7adtOIJLCb9d53zV9i2fkQLSI8Ig/N044iWq/B2LtDr7T1uu/srXvSZuVNvQYU2fpX2z/F@8ZvwQXfdDPU7YhAO7Xs1LIzy84sO7fs3LILyy4se2rZ02DAFDagqhZUW32ktdFvpt9cv4V@p4CY4vxR5Kdi/Zq83tlKh8Da2qC3lmLoMvmFrgMKoxcrg3ZlUDs@7aeiUx21qlNBImOgE2ukVorWWvf2usCwqG@C4mKAXrAogF2jq9eNA5BZAJkBkLkA2QhAhgJkKECGAmQjADmcP8ZiBS4aI3ctdER13m8pDincIoUbpPB6OcAERos5eUYI4yhhHCWMo4RxuKvAglBfivoy1JehQohOiAdEAtFLoCRyjcOuTl3jqBDCEkIYQghDCGEIIVwhxIgQAhVCoEIIVAiBCiFQIQQqhECFECNCpJ0Q983ZlDg7ZgoP12bJcNeFfrErpxbxqUF8ahCvIjnBR6hOUapTlOoUpTpFqU5RqutecKoN8OwjB27pcPeDCxvOLQge0accOa6wwwrb/rHNH9tFsT0UW@TYEsfmIDYDMbIxqo3rQ9ctbaIlZBo2GGxw2BCwkUqdJv@1PIbqWeT74thm8ebnn3R@/v5D/QsvIrDNPD1OXWmJX2u1LdfFWQ27y/TXJxunizLIyGTSeHd32U55qSK1F8HGvMigVV2ntLlyzN31eeYFQ@dQpC5QFSeb3DAvHH5b3a4V5O1LjfvRU8/TbLsAIS9OxgWJn42k/ikiMnBLm5cd/sd5CUfoNVWpIvuFhcAnJXAocYKkBD4uiRghJUpI82tDOUkVBAQYZmadp3JsfYJdm2CnEhzqBDs7gcG6@sWjJudsB5k22TaJ9L5UJP7vZ4hwublc/@YbuXyrrvHvfw "C (clang) ‚Äì Try It Online") *Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs the a pointer to an array of integers and its length (because pointers in C carry no length information). Prints the recursive stalin sort of the input array to `stdout` as space separated numbers and newline separated arrays. [Answer] # Haskell, 50 bytes ``` import Data.List f[]=[] f x|n<-nubBy(>)x=n:f(x\\n) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrLTrWNjqWK02hoibPRjevNMmpUsNOs8I2zypNoyImJk/zf25iZp5tQVFmXolKWrS5joKhjoKRjoKFjoIJkG0A5puAhAwNYv8DAA "Haskell ‚Äì Try It Online") I took the brilliant idea of using `nubBy(>)` to perform a single "Stalin sort" from [HPWiz on anagol](http://golf.shinh.org/reveal.rb?Stalin+Sort+2/HPWiz_1606561165&hs). [Answer] # JavaScript (ES6), ~~¬†59¬†~~ 57 bytes ``` f=a=>a+a?[a.filter(v=>a>v?!b.push(v):a=v,b=[]),...f(b)]:a ``` [Try it online!](https://tio.run/##dY3RCoMgFIbv9xTuTpnJjGAjsB5EvDg23RqRUc3Xdy1Zg2E3B87/fT//EzxMzdgOc9a7mwnBChAVnKCWwGzbzWbEfgkqXx81G17TA3tSgvBUC6kIZYxZrIkqITSun1xnWOfu2GLJKcoVIYe/OKeIJ@KPTVGxwP1ahGm@9a/r3Vn5wU1PWJcvjzo/r38Rh8Mb "JavaScript (Node.js) ‚Äì Try It Online") ### Commented ``` f = a => // f is a recursive function taking a[] a + a ? // if a[] is not empty: [ a.filter(v => // for each value v in a[]: a > v ? // if v is less than the last kept element: !b.push(v) // discard this value and push it in b[] : // else: a = v, // keep this value and save it in a b = [] // start with b[] = empty array ), // end of filter() ...f(b) // append the result of a recursive call with b[] ] // : // else: a // stop the recursion ``` [Answer] # TI-Basic, 80 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) ``` Ans‚ÜíA { üA(1‚ÜíB  üB‚ÜíC For(I,2,dim( üA  üA(I If Ans‚â• üB(dim( üB Then augment( üB,{Ans‚ÜíB Else augment( üC,{Ans‚ÜíC End End Disp  üB ŒîList(cumSum( üC prgmZ ``` * assumes that the program is stored in `prgmZ` to allow recursion * [input is taken as `Ans`](https://codegolf.meta.stackexchange.com/a/8580/98541) to allow recursion * `üA` is used as the input list, `üB` the cleansed list and `üC` the remaining numbers, with a leading dummy value because TI-Basic can't handle empty lists * `ŒîList(cumSum( üC` basically trims `üC` from its first value and stores it in `Ans`, to allow calling the program again with this list this will fail if `üC` has a length of 1, so the program stops. Once the [error message](https://codegolf.meta.stackexchange.com/q/4780/98541) is ignored, we can see the output: [![enter image description here](https://i.stack.imgur.com/Vrh3t.jpg)](https://i.stack.imgur.com/Vrh3t.jpg) [![enter image description here](https://i.stack.imgur.com/CPp9d.jpg)](https://i.stack.imgur.com/CPp9d.jpg) [Answer] # [Julia 1.0](http://julialang.org/), 60 bytes ``` ~v=(!(*,a=0)=v[v.|>i->(a=max(a,i))i];v>[] ? [[!<=];~!>] : v) ``` [Try it online!](https://tio.run/##XYzfqsIwDIfvfYrsLj1UcSJ4UDufwCcovQisQg61jq0WBdmrz7r6h2Mukny/j@Tv7JjKyzD0UWGBP5LUXKio4@xW8bRCUke6IEkWgs0mVtrADrQutsps@qIysIYohsOpBQb20FqqHXvboZhAqgAKbCSHexto1lDbWUyvRte07IPzGDLW3DWOrtiH//qbrK8HXUpYmIleSCjTeJCEZYJPnCHz2/@O/Xn1gbdO6erFWZfzkZf5UZKr0TwWcwc "Julia 1.0 ‚Äì Try It Online") The helper function `!` is called twice at each step of the stalin sort, once with `<=` for the sorted part and with `>` for the "rest" part. the comparison operator (`>` or `<=`) takes the place of `*` in `!`, including implicit multiplication: `(a=max(a,i))i` ‚áí `(a=max(a,i))*i` ‚áí `(a=max(a,i))>i` [Answer] ## Clojure, 133 bytes ``` (fn f[i](let[[x y](reduce(fn[[a b]j](if(>(last a)j)[a(conj b j)][(conj a j)b]))[[(first i)][]](rest i))](if(seq y)(cons x(f y))[x]))) ``` I wish this would have been shorter. `f` implements the Stalin Sort which is called recursively as deemed necessary. [TIO](https://tio.run/##JY5LCoRADET3nqKWCbgYRVAYmIuELFrthm5EZ/yAnt6JuntJfahumNI2@/Ok3gcEUBgRJCoNfhXZcSjNvt86b4KIQ6tJKQb60OCWFY4Ti6NuGhNaJFZ52Bm3yixCIc5mjCbp1XUz3x2L/@HgK7Bgp2DMsluIOcvoO8dxHUYbBKlzFDnKHE2Oyvh130alubM3SGo09lZIgRIVqoeUz/MP). ]
[Question] [ disclaimer: the Mean mean is made up by me Define the arithmetic mean of \$n\$ numbers as $$M\_1(x\_1,...,x\_n)=\frac{x\_1+x\_2+...+x\_n}{n}$$ Define the geometric mean of \$n\$ numbers as $$M\_0(x\_1,...,x\_n)=\root{n}\of{x\_1x\_2...x\_n}$$ Define the harmonic mean of \$n\$ numbers as $$M\_{-1}(x\_1,...,x\_n)=\frac{n}{\frac{1}{x\_2} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$ Define the quadratic mean of \$n\$ numbers as $$M\_2(x\_1,...,x\_n)=\root\of{\frac{x\_1^2+x\_2^2+...+x\_n^2}{n}}$$ The Mean mean (\$M\_M\$) is defined as follows: Define four sequences (\$a\_k, b\_k, c\_k, d\_k\$) as $$a\_0=M\_1(x\_1,...,x\_n),\\b\_0=M\_0(x\_1,...,x\_n),\\c\_0=M\_{-1}(x\_1,...,x\_n),\\d\_0=M\_2(x\_1,...,x\_n),\\ a\_{k+1}=M\_1(a\_k,b\_k,c\_k,d\_k),\\b\_{k+1}=M\_0(a\_k,b\_k,c\_k,d\_k),\\c\_{k+1}=M\_{-1}(a\_k,b\_k,c\_k,d\_k),\\d\_{k+1}=M\_2(a\_k,b\_k,c\_k,d\_k)$$ All four sequences converge to the same number, \$M\_M(x\_1,x\_2,...,x\_n)\$. ## Example The Mean mean of 1 and 2 is calculated as follows: start with $$a\_0 = (1+2)/2 = 1.5, b\_0 = \root\of{1 \* 2} = \root\of2 \approx 1.4142,\\ c\_0 = \frac2{\frac1{1}+\frac1{2}} = \frac4{3} \approx 1.3333, d\_0 = \root\of{\frac{1^2+2^2}2} = \root\of{\frac5{2}} \approx 1.5811.$$ Then $$a\_1 = \frac{1.5+1.4142+1.3333+1.5811}4 \approx 1.4571,\\ b\_1 = \root^4\of{1.5\*1.4142\*1.3333\*1.5811} \approx 1.4542,\\ c\_1 = \frac4{\frac1{1.5}+\frac1{1.4142}+\frac1{1.3333}+\frac1{1.5811}} \approx 1.4512,\\ d\_1 = \root\of{\frac{1.5^2+1.4142^2+1.3333^2+1.5811^2}4} \approx 1.4601.$$ The further calculation of the sequences should be clear. It can be seen that they converge to the same number, approximately \$1.45568889\$. ## Challenge Given two positive real numbers, \$a\$ and \$b\$ (\$a<b\$), calculate their Mean mean \$M\_M(a,b)\$. ## Test cases ``` 1 1 => 1 1 2 => 1.45568889 100 200 => 145.568889 2.71 3.14 => 2.92103713 0.57 1.78 => 1.0848205 1.61 2.41 => 1.98965438 0.01 100 => 6.7483058 ``` # Notes * Your program is valid if the difference between its output and the correct output is not greater than 1/100000 of the absolute value of the difference between input numbers. * The output should be a single number. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes ``` #//.x_:>N@{M@x,E^M@Log@x,1/M[1/x],M[x^2]^.5}& M=Mean ``` [Try it online!](https://tio.run/##JYuxCoMwFEX3fkVAcHq85KVapWDJ0q0p3UMsoUjqoIXiEJB8exrtdM7l3ju55T1MbhlfLvkuFZxjeJ4vd7VqFeDaa3X7@GzEtSEeLGgTeml7rGN50J0e3Jwe33FemPKmsMaQtSVXjK0rAUVgGXKHECCF2FRiQwyOSNWWBNYNA8Km3Wd4yp3Eiv6dyClfY0zpBw "Wolfram Language (Mathematica) – Try It Online") In my first approach I used these builtins `Mean` `GeometricMean` `HarmonicMean` and `RootMeanSquare` Here are some substitutions for saving bytes `HarmonicMean` --> `1/Mean[1/x]` by @Robin Ryder (3 bytes saved) `GeometricMean` --> `E^Mean@Log@x` by @A. Rex (2 bytes saved) `RootMeanSquare` --> `Mean[x^2]^.5` by @A. Rex (4 bytes saved) finally we can assign `Mean` to `M` (as proposed by @ovs) and save 5 more bytes [Answer] # R, ~~70~~ ~~69~~ 67 bytes ``` x=scan();`?`=mean;while(x-?x)x=c((?x^2)^.5,?x,2^?log2(x),1/?1/x);?x ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQfSeZAUscaCUyN5FEpAIzqEX/9tN7jxnSW8sgjptu6WplxO84eyPMCkaqRIosnJfVKZxk7fcuBHbBa/DgqLAwif0) -1 byte with better conditioning. -2 bytes by switching to base 2. Like some other answers, this uses the expression of the geometric mean as an arithmetic mean on the log scale (here in base 2): $$M\_0(x\_1,\ldots, x\_n) = 2^{M\_1(\log\_2 x\_1,\ldots,\log\_2 x\_n)}.$$ It also uses the [fact](https://en.wikipedia.org/wiki/Generalized_mean#Generalized_mean_inequality) that \$\forall k, d\_k\geq a\_k \geq b\_k\geq c\_k\$, i.e. \$d\_k=\max(a\_k, b\_k, c\_k, d\_k)\$. The condition \$a\_k=b\_k=c\_k=d\_k\$ is therefore equivalent to \$d\_k = M\_1(a\_k, b\_k, c\_k, d\_k)\$, which is what I use in the while loop; this is achieved by abusing the syntax of `while` which only considers the first element when the condition is a vector, hence the order in which the means are stored. (Note that we could also use \$c\_k\$ instead since it is the minimum of the four, but we could not use \$a\_k\$ or \$b\_k\$ in the condition.) When we exit the while loop, `x` is a constant vector. The final `?x` computes its mean to reduce it to a scalar. [Answer] # [J](http://jsoftware.com/), 34 bytes (31 as an expression without the assignment to variable `f`) ``` f=:1{(^.z,%z,*:z,[z=:(+/%#)&.:)^:_ ``` [Try it online!](https://tio.run/##y/r/P83WyrBaI06vSke1SkfLqkonusrWSkNbX1VZU03PSjPOKv5/anJGvkKagqGC0X8A "J – Try It Online") For functions `a` and `b`, `a &.: b` ("a under b" ([related challenge](https://codegolf.stackexchange.com/questions/176865/conjugation-in-real-life))) is equivalent to `(b inv) a b` -- apply b, then a, then inverse of b. In this case, geometric/harmonic/quadratic mean is the arithmetic mean "under" logarithm, inversion, and square respectively. [Answer] # TI-BASIC, ~~42~~ ~~35~~ 34 bytes *-1 byte thanks to @SolomonUcko* ``` While max(ΔList(Ans:{mean(Ans),√(mean(Ans²)),mean(Ans^-1)^-1,e^(mean(ln(Ans:End:Ans(1 ``` Input is a list of two integers in `Ans`. Output is stored in `Ans` and is automatically printed out when the program completes. Formulas used for geometric, harmonic, and quadratic means are based off of [user202729's explanation](https://codegolf.stackexchange.com/a/182469/85765). **Example:** ``` {1,2 {1 2} prgmCDGFB 1.455688891 {100,200 {100 200} prgmCDGFB 145.5688891 ``` **Explanation:** (Newlines have been added for clarification. They do **NOT** appear in the code.) ``` While max(ΔList(Ans ;loop until all elements of the current list are equal ; the maximum of the change in each element will be 0 { ;create a list containing... mean(Ans), ; the arithmetic mean √(mean(Ans²)), ; the quadratic mean mean(Ans^-1)^-1, ; the harmonic mean e^(mean(ln(Ans ; and the geometric mean End Ans(1 ;keep the first element in "Ans" and implicitly print it ``` --- **Notes:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. `e^(` is [this](http://tibasicdev.wikidot.com/e-exponent) one-byte token. `^-1` is used for [this](http://tibasicdev.wikidot.com/inverse) one-byte token. I opted for writing `^-1` instead because the token looks like `ֿ¹` when in a code block. `√(` is [this](http://tibasicdev.wikidot.com/square-root) one-byte token. `ΔList(` is [this](http://tibasicdev.wikidot.com/deltalist) two-byte token. [Answer] # Java 10, ~~234~~ ~~229~~ ~~214~~ ~~211~~ ~~215~~ ~~206~~ ~~203~~ ~~196~~ ~~180~~ 177 bytes ``` a->{for(;a[1]-a[0]>4e-9;){double l=a.length,A[]={0,0,0,1};for(var d:a){A[2]+=d/l;A[3]*=Math.pow(d,1/l);A[0]+=1/d;A[1]+=d*d;}A[0]=l/A[0];A[1]=Math.sqrt(A[1]/l);a=A;}return a[0];} ``` -5 bytes thanks to *@PeterCordes*. -15 more bytes thanks to *@PeterCordes*, inspired by [*@RobinRyder*'s R answer](https://codegolf.stackexchange.com/a/182478/52210). +4 bytes because I assumed the inputs are pre-ordered. -27 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##fVLLjoIwFN37FY0rUCgtOuOMDSZ8gG5cMizuQFWcWpxSNIbw7U4LmrgYTZO299V7zrndwwn8ff5zzQRUFVpCIZsBQoXUXG0g42hlTYTysv4WHGVOf0lSBC4zkXZgtkqDLjK0QhJF6Ar@otmUymGQ0NSHhKSLKfc/mdvcHhERYMHlVu@8OEmjhnh20ZbZqhMolM/BbeIkTMdRHggWJ5N0FC1B7/CxPDu5RwPhGi8xcRrk5kZt5ihnrXVGIrBH5@6rql@lHWvaOohi1iquayWRBcfaK7MkjgabIXHjciqLHB2MGs5aq0JuO8K9FJpX2pH8jO5SNNSA79T4Pxi@CBLihYQ8TwjxjHoTTKfPUwh@m3kUzz5etMHvBgaehq9eIYbGHcrjWDspuoKH2fdSrC@V5gdc1hofjUpaSGdvPhSudSFwrBRcKqzLXkEH3PFw/qWHY4kzY9z6tNc/) **Explanation:** ``` a->{ // Method with double-array parameter and double return-type for(;a[1]-a[0] // Loop as long as the difference between the 2nd and 1st items >4e-9;){ // is larger than 0.000000004: double l=a.length, // Set `l` to the amount of values in the array `a` A[]={0,0,0,1}; // Create an array `A`, filled with the values [0,0,0,1] for(var d:a){ // Inner loop over the values of `a`: A[2]+=d/l; // Calculate the sum divided by the length in the third spot A[3]*=Math.pow(d,1/l);// The product of the power of 1/length in the fourth spot A[0]+=1/d; // The sum of 1/value in the first spot A[1]+=d*d; // And the sum of squares in the second spot } // After the inner loop: // (the third spot of the array now holds the Arithmetic Mean) // (the fourth spot of the array now holds the Geometric Mean) A[0]=l/A[0]; // Divide the length by the first spot // (this first spot of the array now holds the Harmonic Mean) A[1]=Math.sqrt(A[1]/l); // Take the square of the second spot divided by the length // (this second spot of the array now holds the Quadratic Mean) a=A; // And then replace input `a` with array `A` } // After the outer loop when all values are approximately equal: return a[0];} // Return the value in the first spot as result ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` W‹⌊θ⌈θ≔⟦∕ΣθLθXΠθ∕¹Lθ∕LθΣ∕¹θ₂∕ΣXθ²Lθ⟧θI⊟θ ``` [Try it online!](https://tio.run/##VY25DoMwEET7fIXLteQUoaWKkhIkFErLhQUWrAR2fAD5e4dLgXSr2Tfzqla6ysguxqnFThHIlPeQo8Z@6MFSRnL52W9Kyd17bDTwJ45YKyh3JlO6Ce2CMFKYSTkonKmHKqzfHb6duSP@ZYwscwe8UaUdpFMvYwKcpJvEMpLQP71YaumlcKgDPKQPM/lefWmMnM@riRDxOnZf "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of numbers. Explanation: ``` W‹⌊θ⌈θ ``` Repeat while the array contains different values... ``` ≔⟦....⟧θ ``` ... replace the array with a list of values: ``` ∕ΣθLθ ``` ... the mean... ``` XΠθ∕¹Lθ ``` ... the geometric mean... ``` ∕LθΣ∕¹θ ``` ... the harmonic mean... ``` ₂∕ΣXθ²Lθ ``` ... and the root mean square. ``` I⊟θ ``` Cast an element of the array to string and implicitly print it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ;µ*Ɱ-;ؽ¤©Æm*İɼ;P½½ƊµÐLḢ ``` [Try it online!](https://tio.run/##ATkAxv9qZWxsef//O8K1KuKxri07w5jCvcKkwqnDhm0qxLDJvDtQwr3CvcaKwrXDkEzhuKL///9bMSwgMl0 "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 24 bytes ``` Wẋ4¹ÆlÆeƭ²½ƭİ4ƭÆm$€⁺µÐLḢ ``` [Try it online!](https://tio.run/##y0rNyan8/z/84a5uk0M7D7flHG5LPbb20KZDe4@tPbLB5Njaw225Ko@a1jxq3HVo6@EJPg93LPp/dNLDnTOsHzXMUdC1U3jUMNf6cDvX4Xagosj//6MNdQxjdYCkEYg0MNAxMjAAsoz0zA11jPUMTYBsAz1Tcx1DPXMLkAo9M6BSPRNDsLgBUDNQOQA "Jelly – Try It Online") ### Explanation ``` µÐL | Repeat until unchanged: W | Wrap as a list ẋ4 | Copy list 4 times ⁺ | Do twice: $€ | For each copy of the list: 4ƭ | One of these functions, cycling between them: ¹ | Identity ÆlÆeƭ | Alternate between log and exp ²½ƭ | Alternate between square and square root İ | Reciprocal Æm | Then take the mean Ḣ| Finally take the first item ``` [Answer] # [PowerShell](https://docs.microsoft.com/en-us/powershell/), ~~182~~ ~~180~~ 183 bytes ``` $f={$a=$c=$d=$n=0 $b=1 $m=[math] $args|%{$n++ $a+=$_ $b*=$_ $c+=1/$_ $d+=+$_*$_} $p=($a/$n),$m::pow($b,1/$n),($n/$c),$m::sqrt($d/$n)|%{$m::round($_,9)} if($p-ne$p[0]){$p=&$f @p}$p[0]} ``` [Try it online!](https://tio.run/##NZDRjoIwEEXf@xXzMAoK1hZaKCbd@B@uISi6mmhlwY0PyLezA@w@NL09d@ZOptXjdaqby@l263s82xYLi0eLpUVnBcODlQzvdncvnpc9w6L@at6zFl0Q0COwmFPJcryOgZXrQZSBDTBfYt4xrKyPxRrdIsT7ZlM9Xj4eQjkCH90aj5PRfNdPH8uBD@lE6sePK33Mw2zRsevZx2rlTljtxH7RUuocz7CtuhF0/dZjEiTYD5AkolFwpXVijMmYFAIiOgNVmv/RiKcSYi7VwCOeRVLEqYyZ4Dql7tRMKcIoEwnNJE8omatpCs9MlmgVGyoXNHpKT3iqTCy0Yd4WVk11uz7B@3QevGHWMgAsQqD1AWuw/z59GMAcaB0syGRd/ws) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ©ÅA®.²ÅAo®zÅAz®nÅAt)}н ``` [Try it online](https://tio.run/##yy9OTMpM/f//3JRDKw@3Oh5ap3doE5DOP7SuCkhVHVqXB6RKNGsv7P3/P9pQxygWAA) or [see the steps of all test cases](https://tio.run/##MzBNTDJM/V92aJt9pb2SwqO2SQpK9pX/z005tPJwq@OhdXqHNgHp/EPrqoBU1aF1eUCqRPO/i87/6GhDHcNYHQUgZQSmDAx0jAwMQEwjPXNDHWM9QxMQx0DP1BzOMdQzAyrXMzGEyBgAjQBqiQUA). -1 byte thanks to *@Grimy*. **23 byter alternative for Geometric mean:** ``` Δ©P®gzm®ÅA®zÅAz®nÅAt)}н ``` [Try it online](https://tio.run/##yy9OTMpM/f//3JRDKwMOrUuvyj207nCr46F1VUCy6tC6PCBVoll7Ye///9GGOkaxAA) or [see the steps of all test cases](https://tio.run/##MzBNTDJM/V92aJt9pb2SwqO2SQpK9pX/z005tDLg0Lr0qtxD6w63Oh5aVwUkqw6tywNSJZr/XXT@R0cb6hjG6igAKSMwZWCgY2RgAGIa6Zkb6hjrGZqAOAZ6puZwjqGeGVC5nokhRMYAaARQSywA). **Explanation:** ``` Δ # Loop until the list no longer changes: © # Store the current list in variable `®` (without popping) # (which is the implicit input-list in the first iteration) # Arithmetic mean: ÅA # Builtin to calculate the arithmetic mean of the list # Geometric mean: ®.² # Take the base-2 logarithm of each value in the list `®` ÅA # Get the arithmetic mean of that list o # And take 2 to the power of this mean # Harmonic mean: ®z # Get 1/x for each value x in the list `®` ÅA # Get the arithmetic mean of that list z # And calculate 1/y for this mean y # Quadratic mean: ®n # Take the square of each number x in the list from the register ÅA # Calculate the arithmetic mean of this list t # And take the square-root of that mean ) # Wrap all four results into a list }н # After the list no longer changes: pop and push its first value # (which is output implicitly as result) ``` [Answer] # x86 machine code (SIMD 4x float using 128-bit SSE1&AVX) 94 bytes # x86 machine code (SIMD 4x double using 256-bit AVX) 123 bytes `float` passes the test cases in the question, but with a loop-exit threshold small enough to make that happen, it's easy for it to get stuck in an infinite loop with random inputs. SSE1 packed-single-precision instructions are 3 bytes long, but SSE2 and simple AVX instructions are 4 bytes long. (Scalar-single instructions like `sqrtss` are also 4 bytes long, which is why I use `sqrtps` even though I only care about the low element. It's not even slower than sqrtss on modern hardware). I used AVX for non-destructive destination to save 2 bytes vs. movaps+op. In the double version we can still do a couple `movlhps` to copy 64-bit chunks (because often we only care about the low element of a horizontal sum). Horizontal sum of a 256-bit SIMD vector also requires an extra `vextractf128` to get the high half, vs. the [slow but small 2x `haddps` strategy for float](https://stackoverflow.com/questions/6996764/fastest-way-to-do-horizontal-float-vector-sum-on-x86). The `double` version also needs 2x 8-byte constants, instead of 2x 4-byte. Overall it comes out at close to 4/3 the size of the `float` version. **`mean(a,b) = mean(a,a,b,b)` for all 4 of these means**, so we can simply duplicate the input up to 4 elements and never have to implement length=2. Thus we can hardcode geometric mean as 4th-root = sqrt(sqrt), for example. And we only need one FP constant, `4.0`. **We have a single SIMD vector of all 4 `[a_i, b_i, c_i, d_i]`. From that, we calculate the 4 means as scalars in separate registers, and shuffle them back together for the next iteration.** (Horizontal operations on SIMD vectors are inconvenient, but we need to do the same thing for all 4 elements in enough cases that it balances out. I started on an x87 version of this, but it was getting very long and not fun.) **The loop-exit condition of `}while(quadratic - harmonic > 4e-5)` (or a smaller constant for `double`)** is based on [@RobinRyder's R answer](https://codegolf.stackexchange.com/a/182478/52210), and [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/questions/182460/calculate-the-mean-mean-of-two-numbers/182501#182501): quadratic mean is always the *largest* magnitude, and harmonic mean is always the smallest (ignoring rounding errors). So we can check the delta between those two to detect convergence. We return the arithmetic mean as the scalar result. It's usually between those two and is probably the least susceptible to rounding errors. **Float version**: callable as `float meanmean_float_avx(__m128);` with the arg and return value in xmm0. (So x86-64 System V, or Windows x64 vectorcall, but not x64 fastcall.) Or declare the return-type as `__m128` so you can get at the quadratic and harmonic mean for testing. Letting this take 2 separate `float` args in xmm0 and xmm1 would cost 1 extra byte: we'd need a `shufps` with an imm8 (instead of just `unpcklps xmm0,xmm0`) to shuffle together and duplicate 2 inputs. ``` 40 address align 32 41 code bytes global meanmean_float_avx 42 meanmean_float_avx: 43 00000000 B9[52000000] mov ecx, .arith_mean ; allows 2-byte call reg, and a base for loading constants 44 00000005 C4E2791861FC vbroadcastss xmm4, [rcx-4] ; float 4.0 45 46 ;; mean(a,b) = mean(a,b,a,b) for all 4 types of mean 47 ;; so we only ever have to do the length=4 case 48 0000000B 0F14C0 unpcklps xmm0,xmm0 ; [b,a] => [b,b,a,a] 49 50 ; do{ ... } while(quadratic - harmonic > threshold); 51 .loop: 52 ;;; XMM3 = geometric mean: not based on addition. (Transform to log would be hard. AVX512ER has exp with 23-bit accuracy, but not log. vgetexp = floor(lofg2(x)), so that's no good.) 53 ;; sqrt once *first*, making magnitudes closer to 1.0 to reduce rounding error. Numbers are all positive so this is safe. 54 ;; both sqrts first was better behaved, I think. 55 0000000E 0F51D8 sqrtps xmm3, xmm0 ; xmm3 = 4th root(x) 56 00000011 F30F16EB movshdup xmm5, xmm3 ; bring odd elements down to even 57 00000015 0F59EB mulps xmm5, xmm3 58 00000018 0F12DD movhlps xmm3, xmm5 ; high half -> low 59 0000001B 0F59DD mulps xmm3, xmm5 ; xmm3[0] = hproduct(sqrt(xmm)) 60 ; sqrtps xmm3, xmm3 ; sqrt(hprod(sqrt)) = 4th root(hprod) 61 ; common final step done after interleaving with quadratic mean 62 63 ;;; XMM2 = quadratic mean = max of the means 64 0000001E C5F859E8 vmulps xmm5, xmm0,xmm0 65 00000022 FFD1 call rcx ; arith mean of squares 66 00000024 0F14EB unpcklps xmm5, xmm3 ; [quad^2, geo^2, ?, ?] 67 00000027 0F51D5 sqrtps xmm2, xmm5 ; [quad, geo, ?, ?] 68 69 ;;; XMM1 = harmonic mean = min of the means 70 0000002A C5D85EE8 vdivps xmm5, xmm4, xmm0 ; 4/x 71 0000002E FFD1 call rcx ; arithmetic mean (under inversion) 72 00000030 C5D85ECD vdivps xmm1, xmm4, xmm5 ; 4/. (the factor of 4 cancels out) 73 74 ;;; XMM5 = arithmetic mean 75 00000034 0F28E8 movaps xmm5, xmm0 76 00000037 FFD1 call rcx 77 78 00000039 0F14E9 unpcklps xmm5, xmm1 ; [arith, harm, ?,?] 79 0000003C C5D014C2 vunpcklps xmm0, xmm5,xmm2 ; x = [arith, harm, quad, geo] 80 81 00000040 0F5CD1 subps xmm2, xmm1 ; largest - smallest mean: guaranteed non-negative 82 00000043 0F2E51F8 ucomiss xmm2, [rcx-8] ; quad-harm > convergence_threshold 83 00000047 73C5 jae .loop 84 85 ; return with the arithmetic mean in the low element of xmm0 = scalar return value 86 00000049 C3 ret 87 88 ;;; "constant pool" between the main function and the helper, like ARM literal pools 89 0000004A ACC52738 .fpconst_threshold: dd 4e-5 ; 4.3e-5 is the highest we can go and still pass the main test cases 90 0000004E 00008040 .fpconst_4: dd 4.0 91 .arith_mean: ; returns XMM5 = hsum(xmm5)/4. 92 00000052 C5D37CED vhaddps xmm5, xmm5 ; slow but small 93 00000056 C5D37CED vhaddps xmm5, xmm5 94 0000005A 0F5EEC divps xmm5, xmm4 ; divide before/after summing doesn't matter mathematically or numerically; divisor is a power of 2 95 0000005D C3 ret 96 0000005E 5E000000 .size: dd $ - meanmean_float_avx 0x5e = 94 bytes ``` (NASM listing created with `nasm -felf64 mean-mean.asm -l/dev/stdout | cut -b -34,$((34+6))-`. Strip the listing part and recover the source with `cut -b 34- > mean-mean.asm`) SIMD horizontal sum and divide by 4 (i.e. arithmetic mean) is implemented in a separate function that we `call` (with a function pointer to amortize the cost of the address). With `4/x` before/after, or `x^2` before and sqrt after, we get the harmonic mean and quadratic mean. (It was painful to write these `div` instructions instead of multiplying by an exactly-representable `0.25`.) Geometric mean is implemented separately with multiply and chained sqrt. Or with one sqrt first to reduce exponent magnitude and maybe help numerical precision. log is not available, only `floor(log2(x))` via AVX512 `vgetexpps/pd`. Exp is sort of available via AVX512ER (Xeon Phi only), but with only 2^-23 precision. Mixing 128-bit AVX instructions and legacy SSE is not a performance problem. Mixing 256-bit AVX with legacy SSE can be on Haswell, but on Skylake it just potentially creates a potential false dependency for SSE instructions. I think my `double` version avoids any unnecessary loop-carried dep chains, and bottlenecks on div/sqrt latency/throughput. **Double version:** ``` 108 global meanmean_double_avx 109 meanmean_double_avx: 110 00000080 B9[E8000000] mov ecx, .arith_mean 111 00000085 C4E27D1961F8 vbroadcastsd ymm4, [rcx-8] ; float 4.0 112 113 ;; mean(a,b) = mean(a,b,a,b) for all 4 types of mean 114 ;; so we only ever have to do the length=4 case 115 0000008B C4E37D18C001 vinsertf128 ymm0, ymm0, xmm0, 1 ; [b,a] => [b,a,b,a] 116 117 .loop: 118 ;;; XMM3 = geometric mean: not based on addition. 119 00000091 C5FD51D8 vsqrtpd ymm3, ymm0 ; sqrt first to get magnitude closer to 1.0 for better(?) numerical precision 120 00000095 C4E37D19DD01 vextractf128 xmm5, ymm3, 1 ; extract high lane 121 0000009B C5D159EB vmulpd xmm5, xmm3 122 0000009F 0F12DD movhlps xmm3, xmm5 ; extract high half 123 000000A2 F20F59DD mulsd xmm3, xmm5 ; xmm3 = hproduct(sqrt(xmm0)) 124 ; sqrtsd xmm3, xmm3 ; xmm3 = 4th root = geomean(xmm0) ;deferred until quadratic 125 126 ;;; XMM2 = quadratic mean = max of the means 127 000000A6 C5FD59E8 vmulpd ymm5, ymm0,ymm0 128 000000AA FFD1 call rcx ; arith mean of squares 129 000000AC 0F16EB movlhps xmm5, xmm3 ; [quad^2, geo^2] 130 000000AF 660F51D5 sqrtpd xmm2, xmm5 ; [quad , geo] 131 132 ;;; XMM1 = harmonic mean = min of the means 133 000000B3 C5DD5EE8 vdivpd ymm5, ymm4, ymm0 ; 4/x 134 000000B7 FFD1 call rcx ; arithmetic mean under inversion 135 000000B9 C5DB5ECD vdivsd xmm1, xmm4, xmm5 ; 4/. (the factor of 4 cancels out) 136 137 ;;; XMM5 = arithmetic mean 138 000000BD C5FC28E8 vmovaps ymm5, ymm0 139 000000C1 FFD1 call rcx 140 141 000000C3 0F16E9 movlhps xmm5, xmm1 ; [arith, harm] 142 000000C6 C4E35518C201 vinsertf128 ymm0, ymm5, xmm2, 1 ; x = [arith, harm, quad, geo] 143 144 000000CC C5EB5CD1 vsubsd xmm2, xmm1 ; largest - smallest mean: guaranteed non-negative 145 000000D0 660F2E51F0 ucomisd xmm2, [rcx-16] ; quad - harm > threshold 146 000000D5 77BA ja .loop 147 148 ; vzeroupper ; not needed for correctness, only performance 149 ; return with the arithmetic mean in the low element of xmm0 = scalar return value 150 000000D7 C3 ret 151 152 ; "literal pool" between the function 153 000000D8 95D626E80B2E113E .fpconst_threshold: dq 1e-9 154 000000E0 0000000000001040 .fpconst_4: dq 4.0 ; TODO: golf these zeros? vpbroadcastb and convert? 155 .arith_mean: ; returns YMM5 = hsum(ymm5)/4. 156 000000E8 C4E37D19EF01 vextractf128 xmm7, ymm5, 1 157 000000EE C5D158EF vaddpd xmm5, xmm7 158 000000F2 C5D17CED vhaddpd xmm5, xmm5 ; slow but small 159 000000F6 C5D35EEC vdivsd xmm5, xmm4 ; only low element matters 160 000000FA C3 ret 161 000000FB 7B000000 .size: dd $ - meanmean_double_avx 0x7b = 123 bytes ``` --- ## C test harness ``` #include <immintrin.h> #include <stdio.h> #include <math.h> static const struct ab_avg { double a,b; double mean; } testcases[] = { {1, 1, 1}, {1, 2, 1.45568889}, {100, 200, 145.568889}, {2.71, 3.14, 2.92103713}, {0.57, 1.78, 1.0848205}, {1.61, 2.41, 1.98965438}, {0.01, 100, 6.7483058}, }; // see asm comments for order of arith, harm, quad, geo __m128 meanmean_float_avx(__m128); // or float ... __m256d meanmean_double_avx(__m128d); // or double ... int main(void) { int len = sizeof(testcases) / sizeof(testcases[0]); for(int i=0 ; i<len ; i++) { const struct ab_avg *p = &testcases[i]; #if 1 __m128 arg = _mm_set_ps(0,0, p->b, p->a); double res = meanmean_float_avx(arg)[0]; #else __m128d arg = _mm_loadu_pd(&p->a); double res = meanmean_double_avx(arg)[0]; #endif double allowed_diff = (p->b - p->a) / 100000.0; double delta = fabs(p->mean - res); if (delta > 1e-3 || delta > allowed_diff) { printf("%f %f => %.9f but we got %.9f. delta = %g allowed=%g\n", p->a, p->b, p->mean, res, p->mean - res, allowed_diff); } } while(1) { double a = drand48(), b = drand48(); // range= [0..1) if (a>b) { double tmp=a; a=b; b=tmp; // sorted } // a *= 0.00000001; // b *= 123156; // a += 1<<11; b += (1<<12)+1; // float version gets stuck inflooping on 2048.04, 4097.18 at fpthreshold = 4e-5 // a *= 1<<11 ; b *= 1<<11; // scaling to large magnitude makes sum of squares loses more precision //a += 1<<11; b+= 1<<11; // adding to large magnitude is hard for everything, catastrophic cancellation #if 1 printf("testing float %g, %g\n", a, b); __m128 arg = _mm_set_ps(0,0, b, a); __m128 res = meanmean_float_avx(arg); double quad = res[2], harm = res[1]; // same order as double... for now #else printf("testing double %g, %g\n", a, b); __m128d arg = _mm_set_pd(b, a); __m256d res = meanmean_double_avx(arg); double quad = res[2], harm = res[1]; #endif double delta = fabs(quad - harm); double allowed_diff = (b - a) / 100000.0; // calculated in double even for the float case. // TODO: use the double res as a reference for float res // instead of just checking quadratic vs. harmonic mean if (delta > 1e-3 || delta > allowed_diff) { printf("%g %g we got q=%g, h=%g, a=%g. delta = %g, allowed=%g\n", a, b, quad, harm, res[0], quad-harm, allowed_diff); } } } ``` Build with: ``` nasm -felf64 mean-mean.asm && gcc -no-pie -fno-pie -g -O2 -march=native mean-mean.c mean-mean.o ``` Obviously you need a CPU with AVX support, or an emulator like Intel SDE. To compile on a host without native AVX support, use `-march=sandybridge` or `-mavx` Run: passes the hard-coded test cases, but for the float version, random test cases often fail the `(b-a)/10000` threshold set in the question. ``` $ ./a.out (note: empty output before the first "testing float" means clean pass on the constant test cases) testing float 3.90799e-14, 0.000985395 3.90799e-14 0.000985395 we got q=3.20062e-10, h=3.58723e-05, a=2.50934e-05. delta = -3.5872e-05, allowed=9.85395e-09 testing float 0.041631, 0.176643 testing float 0.0913306, 0.364602 testing float 0.0922976, 0.487217 testing float 0.454433, 0.52675 0.454433 0.52675 we got q=0.48992, h=0.489927, a=0.489925. delta = -6.79493e-06, allowed=7.23169e-07 testing float 0.233178, 0.831292 testing float 0.56806, 0.931731 testing float 0.0508319, 0.556094 testing float 0.0189148, 0.767051 0.0189148 0.767051 we got q=0.210471, h=0.210484, a=0.21048. delta = -1.37389e-05, allowed=7.48136e-06 testing float 0.25236, 0.298197 0.25236 0.298197 we got q=0.274796, h=0.274803, a=0.274801. delta = -6.19888e-06, allowed=4.58374e-07 testing float 0.531557, 0.875981 testing float 0.515431, 0.920261 testing float 0.18842, 0.810429 testing float 0.570614, 0.886314 testing float 0.0767746, 0.815274 testing float 0.118352, 0.984891 0.118352 0.984891 we got q=0.427845, h=0.427872, a=0.427863. delta = -2.66135e-05, allowed=8.66539e-06 testing float 0.784484, 0.893906 0.784484 0.893906 we got q=0.838297, h=0.838304, a=0.838302. delta = -7.09295e-06, allowed=1.09422e-06 ``` FP errors are enough that quad-harm comes out less than zero for some inputs. Or with `a += 1<<11; b += (1<<12)+1;` uncommented: ``` testing float 2048, 4097 testing float 2048.04, 4097.18 ^C (stuck in an infinite loop). ``` **None of these problems happen with `double`.** Comment out the `printf` before each test to see that the output is empty (nothing from the `if(delta too high)` block). TODO: use the `double` version as a reference for the `float` version, instead of just looking at how they converging with quad-harm. [Answer] # [Python 3](https://docs.python.org/3/), 152 bytes ``` from math import* s=sum def f(*a):l=len(a);return 2>len({*a})and{*a}or f(s(a)/l,l/s(map(pow,a,l*[-1])),exp(s(map(log,a))/l),(s(map(pow,a,l*[2]))/l)**.5) ``` [Try it online!](https://tio.run/##XY3LCsIwEEX3/YqCm0wYY5KqFUV/RFwE2qqQF2lERfz2mipo62o4d86d8fd4crbouiY4kxsVT/nZeBcizdptezFZVTd5Q6iCtd7q2hIFm1DHS7C53PX8oOoJylb9dCGpbVJmGvWsJUZ54t0VFWq6n4oDANY3Tz4L7Y6oIKmA5E@Vh3dOKVtA58PZRtIQgQIg@5FMNPki5yg5H0aSlQILJuaDFmeLEgUrV6MuW6ZrbC5GIk//@oPdCw "Python 3 – Try It Online") Recursive function `f`, will converge to floating point precision. Works in principle for all lists of positive numbers of *any* size, but is limited by ~~Python's recursion limit~~ a rounding error for some test cases. --- Alternatively, settling for 9 decimals precision: # [Python 3](https://docs.python.org/3/), 169 bytes ``` from math import* s=sum def f(*a):l=len(a);return(2>len({round(i,9)for i in a}))*a[0]or f(s(a)/l,l/s(map(pow,a,l*[-1])),exp(s(map(log,a))/l),(s(map(pow,a,l*[2]))/l)**.5) ``` [Try it online!](https://tio.run/##XY3LTsMwEEX3@QovZ6zBtd1HoKj8SJWFpcbUkl9yHBWE@PbgwoLA8p45905@r9cUt8tiSwosmHplLuRUKu@m0zSH7jJaZoEbPPqTHyMYfC5jnUsE/XLPHyXN8QKOntCmwhxzkZlPRG7OcmjAwtQ6G09@M0EwGXK6kSHPzw9qQKTxLcPPwadXMthUJPin6uGbcy72uOTiYgULihRi95v0OklJWsoV0aJXtBVqt2JS7HtSon9cN8WhTYmd@uPJ9uw@t3wB "Python 3 – Try It Online") [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 173 bytes ``` double m(int n,params double[]a)=>(n<1?a[0]:m(n-1,a.Sum()/a.Length,Math.Pow(a.Aggregate((t,x)=>t*x),1.0/a.Length),a.Length/a.Sum(x=>1/x),Math.Sqrt(a.Sum(x=>x*x)/a.Length))); ``` [Try it online!](https://tio.run/##lY9BS8MwGIbP66/IMZEsbaYiWDcRrxsMevBQevjsQhZoE5d8dRXZb69ZxzaPeknyvbzPQ746TOtQD10wVpPiK6Bq8@T3JJbG7vKkbiAEsvZOe2jJdzIJCGhq8unMhqzAWBrQR6qsCHgd2LEyeXU2uEaJN29QRY@iVu3PEspES@8zTqSIx0xkjOV/Z7JspI7Xf7iZeJCc3Ap5N1KHYeO690aRlhqLxPIPiO1ATmlZAZsvqH2Sz1Bm1WNL7VRyEEUXhSmIpbIat3wFuBVrt6cgXrT2SgMqSpH3EcabnvG44KXN@PmVnkT9fCHTWBotxc4jveR9hK9g/PBwGH4A) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 124 bytes ``` import StdEnv f=avg o limit o iterate\l=let n=toReal(length l)in[avg l,prod l^(1.0/n),n/sum[1.0/x\\x<-l],avg[x*x\\x<-l]^0.5] ``` [Try it online!](https://tio.run/##NY7BboMwDIbvewof2ymlhHVlh3Ebh0k7rUdIpQgCi@Q4CNyKvfyyRGyX@P9kf3Y6NJqC8/0NDThtKVg3@Znhwn1N94eh0vcRPKB1lmO1bGbNpsUKDQNV7D@Nxh0aGvkLcG@pSQKKafY94HUns/xIe0HH5eaaBGvbrq8HVCLONevjP17z7FmFC@t4u4o/mWCAJgkC4qMEbLn4y3URc12kXGSlFPCUyVOiuKZMSvmyOWeZpJPcenmk6CoVfroB9biEw/tHePsm7Wy3/AI "Clean – Try It Online") Performs the operation until the result stops changing. Hurray for limited precision floating point! [Answer] # Pyth, 32 bytes ``` h.Wt{H[.OZ@*[[email protected]](/cdn-cgi/l/email-protection)^R2Z2 ``` Try it online [here](https://pyth.herokuapp.com/?code=h.Wt%7BH%5B.OZ%40%2AFZJlZcJscL1Z%40.O%5ER2Z2&input=%5B2.71%2C3.14%5D&debug=0), or verify all the test cases (bar two, see note below) at once [here](https://pyth.herokuapp.com/?code=h.Wt%7BH%5B.OZ%40%2AFZJlZcJscL1Z%40.O%5ER2Z2&test_suite=1&test_suite_input=%5B1%2C%201%5D%0A%5B1%2C%202%5D%0A%5B100%2C%20200%5D%0A%5B2.71%2C%203.14%5D%0A%5B0.57%2C%201.78%5D%0A%5B1.61%2C%202.41%5D%0A%5B0.01%2C%20100%5D&debug=0). Accepts input as a list. There seem to be some issues with rounding, as certain inputs don't converge correctly when they otherwise should. In particular, test case `0.01 100` gets stuck at values `[6.748305820749738, 6.748305820749738, 6.748305820749739, 6.748305820749738]`, and test case `1.61 2.41` gets stuck at `[1.9896543776640825, 1.9896543776640825, 1.9896543776640827, 1.9896543776640825]` - note in both cases that the 3rd mean (harmonic mean) differs from the others. I'm not sure if this problem invalidates my entry, but I'm posting it anyway as it *should* work. If this isn't acceptable, it can be fixed by instering `.RRT` before the `[`, to round each of the means to 10 decimal places, as seen in [this test suite](https://pyth.herokuapp.com/?code=h.Wt%7BH.RRT%5B.OZ%40%2AFZJlZcJscL1Z%40.O%5ER2Z2&test_suite=1&test_suite_input=%5B1%2C%201%5D%0A%5B1%2C%202%5D%0A%5B100%2C%20200%5D%0A%5B2.71%2C%203.14%5D%0A%5B0.57%2C%201.78%5D%0A%5B1.61%2C%202.41%5D%0A%5B0.01%2C%20100%5D&debug=0). ``` h.Wt{H[.OZ@*[[email protected]](/cdn-cgi/l/email-protection)^R2Z2)Q Implicit: Q=eval(input()) Trailing )Q inferred .W Q Funcitonal while: While condition is true, call inner. Starting value Q t{H Condition function: current input H {H Deduplicate H t Discard first value Empty list is falsey, so while is terminated when means converge [.OZ@*[[email protected]](/cdn-cgi/l/email-protection)^R2Z2) Inner function: current input Z JlZ Take length of Z, store in J .OZ (1) Arithmetic mean of Z *FZ Product of Z @ J (2) Jth root of the above L Z Map each element of Z... c 1 ... to its reciprocal s Sum the above cJ (3) J / the above R Z Map each element of Z... ^ 2 ... to its square .O Arithmetic mean of the above @ 2 (4) Square root of the above [ ) Wrap results (1), (2), (3), and (4) in a list This is used as the input for the next iteration of the loop h Take the first element of the result, implicit print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~42~~ 38 bytes ``` â ÊÉ?ß[Ux²÷(V=UÊ)¬Ux÷V U×qV V÷Ux!÷1]:U ``` There's got to be a shorter way... This is a monstrosity! Saved 4 bytes thanks to @Shaggy! [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWc&code=4iDKyT/fW1V4svcoVj1VyimsVXj3ViBV13FWIFb3VXgh9zFdOlU&input=WzEsMl0) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 177 bytes ``` double f(double[]g)=>g.All(c=>Math.Abs(c-g[0])<1e-9)?g[0]:f(new[]{g.Sum()/(z=g.Length),Math.Pow(g.Aggregate((a,b)=>a*b),1d/z),z/g.Sum(x=>1/x),Math.Sqrt(g.Sum(x=>x*x)/z)});int z; ``` Thanks to @KevinCruijjsen for pointing out that using floating point precision was causing problems! Would be 163 bytes if doubles were perfectly precise. [Try it online!](https://tio.run/##dY5NT4NAEIbv/ooeZ5pl2MEqWgTTe01MevBAOPCx3ZJQGmGbEkx/O66t9uReJpN55nnzlr1X9vU0VYdj0ajZFq5LmmmME02rpoEyTt5ys6NV0UPp6VRm@MLKe8bXn325hVad0uxL0@a4B/RhjDWtVavNDsVFfD@cwEZp3SmdGwWQi8Km5/MCBVf@iGL0r/YQJ@wPv9rmszNwuw/zAe3rGaO6NbMxmj662qh13Sr4a8CVCKozYnT3L2Mnk9Kadjh4QCGLe@KFg0t6CAVT@OTKp0cWAS0Cpy9Z2BIXPH0D "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Javascript - 186 bytes Takes input as an array of numbers. Uses the mean transformations in [J42161217's answer](https://codegolf.stackexchange.com/a/182462/70475) to shorten the code. [Try It Online](https://tio.run/##TU9LboMwEN1zCq8i2zWDTUKJUpmusuwJLBYOhdBicAQIuD01n0ZZzfuOZn71oLus/Xn0fmO/87mQMx6YkaqWeGSV5EQmI9T6gSeZVG9yIodDFYxg8ubel2yUiQhq/EyIYCJkUb90X8KV0hdvlYy9YxdZMy/eRGlICKUQpU8JD4RAZ9seY81u7g7t34gbRh1T3yieJiL3o88CG3JZqDd/eMpDSAmGRMp2FO6Ic4c531gIsbOOIE4b5xDFrgTxeU/D@1KFk/j3@bLU1b0UCttedVbiCckEZbbprMm3vxgq1ufm@Q8) ``` f=(v,l=[m=(w,k=0)=>w.map(x=>k+=x)&&k/w.length,w=>1/m(w.map(x=>1/x)),w=>Math.E**m(w.map(x=>Math.log(x))),w=>m(w.map(x=>x**2))**.5].map(x=>x(v)).sort((a,b)=>a-b))=>l[3]-l[0]>1e-5?f(l):l[0] ``` ## Explanation ``` f = ( v, l=[ m=(w,k=0)=>w.map(x=>k+=x)&&k/w.length, // m = w => arithmetic mean of values in w w=>1/m(w.map(x=>1/x)), // w => harmonic mean of values in w w=>Math.E**m(w.map(x=>Math.log(x))), // w => geometric mean of values in w w=>m(w.map(x=>x**2))**.5 // w => quadratic mean of values in w ].map(x=>x(v)) // get array of each mean using input v, stored in l .sort((a,b)=>a-b) // sort the outputs ) => l[3] - l[0] > 1e-5 ? // is the difference between the largest // and smallest means > 1/100000? f(l) : // if yes, get the mean mean of the means l[0] // if no, arbitrarily return the smallest value // as close enough ``` [Answer] # [Perl 5](https://www.perl.org/), ~~92~~ 72 bytes ``` sub f{@_=map{$m=$_;sum(map$_**$m/@_,@_)**(1/$m)}1,1e-9,-1,2for 1..9;pop} ``` [Try it online!](https://tio.run/##xZRdT4MwFIbv9ytOSJcAltIWCmWMuSVe6p1eOdNAHEocHxksxiz762IRZ/wF2KTJ24/T86TnbZvdYS/6vj1mkJ/WKinT5oTKBKm4PZamHiFl26h01wqvlWXbJnNRaZ0ZZjsnwg7DPK8PwAiJ4qZuzv37a7Hfmcubzf1mZZ1mAOWHiVKMMoxyK3Eft89b8nTlvsTfS4DKMsnHDdYw1RyKqsvBmDtBC2kydxhvAbKLyC9Ch80dTtttZWAdBpBmrakPc3SWpUYT10b9ZiyMqu5ACww6BWgIQDkeksaz80ypgVIp@Lc2Y8B@ZLL6lVMj8D8IxBcikFJGkyJQClz3EcEXZHoETkIGHmH@gMBJxBn1QuZNiUCJCHUBQjkWgkpfciqm9QIJtB2Iz0aESEaB8D057S1Q/SgGM2iEgIS@9KiYkgD6z7rpirpqe@futmi7xeKhK/aJ/g6/AA "Perl 5 – Try It Online") ...using some dirty tricks. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 296 bytes ``` X =INPUT Y =INPUT A =(X + Y) / 2. P =X * Y G =P ^ 0.5 H =P / A Q =(2 * (A ^ 2) - P) ^ 0.5 O OUTPUT =EQ(Q,A) Q :S(END) M =A N =G O =H P =Q A =(M + N + O + P) / 4 G =(M * N * O * P) ^ 0.25 H =4 / (1 / M + 1 / N + 1 / O + 1 / P) Q =((M ^ 2 + N ^ 2 + O ^ 2 + P ^ 2) / 4) ^ 0.5 :(O) END ``` [Try it online!](https://tio.run/##PY47b8MwDIRn8lfcKLnNS3CXABoMJEgyRA80BuylQ@cgGfL/4ZwttQN1BMXjfa/H8/d5b6dJBvhLSP1NZfzvOngz4AOjxQZurZLgBzQYVU7wCT/Yrr9UznO/QaeSaXBcMB3/nMUKydatKLG/8Sr8MZv82Vlk2X@bYzhYlSs83QH@pBLhz0tSLgBXAgRWZKUZpF3SOW84bzhv/lJcgWm5ZHZ8ZuusoWqsmmxB5Q1iLveLxqqp4DOr4sveRKuEnaadujc "SNOBOL4 (CSNOBOL4) – Try It Online") Straightforward implementation. Uses a trick from [my answer to a related question](https://codegolf.stackexchange.com/a/145360/67312) to golf a bit more. [Answer] # Sledgehammer, 15 bytes so I just posted the winning answer to my own question ``` ⡈⠀⣐⢕⠠⢵⠂⡒⡓⠄⠬⢔⣲⣔⢯ ``` Take input as a list of two (or more) machine precision integers. Mathematica has all the built-ins you could need for this challenge! * `FixedPoint` for iterating until done * `Mean`, `HarmonicMean`, `GeometricMean` and `RootMeanSquare` are the built-ins for all four means necessary Corresponding Mathematica code: ``` First@FixedPoint[{Mean@#,HarmonicMean@#,GeometricMean@#,RootMeanSquare@#}&,#]& ``` (golfing in Sledgehammer is noticeably different from golfing in Mathematica; replacing the means with shorter expressions is unlikely to help here, although I haven't actually tried) [Answer] # [Factor](https://factorcode.org), 101 bytes ``` [ [ { mean geometric-mean harmonic-mean quadratic-mean } [ execute ] with map ] to-fixed-point last ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZC9TsMwEMfFmqc4RoZYdmInDghWxMKCmKoOJr1Si-aj9kUUVXkSli7lneBpcJumqJxl3Z3udx_6f37NTUmN2_5cXD0_PTzeX8MbuhqX4HHVYV2ih8rQgnkyZD3Z0kPZVC-2NqHLQ-uQ6KN1tia4iaJNBME2IMLrYbBLuL0DcSok_wpMKpVprYuR4ByS8PsTIRU7IxKWC0iZkIE5EAkrEsHTXKRHgjOVh8m5HgnBuJY64WpcwrJwCZPiDyh0kSmZ6tMILg639MczMpZLnXKlo37X0TzW3ziBSSArNDW8YlMhOVvGh3RhXNXUY7bqzMwF-Y5pH9pwjWVHCFN4t7QIErchpCae2zXO4rbZ67k0nmA6LNvtCTbE2-3gfwE) ]
[Question] [ ![It's super effective!](https://i.stack.imgur.com/S0AsX.png) In Pokémon there are 18 types: ``` Normal Fighting Flying Poison Ground Rock Bug Ghost Steel Fire Water Grass Electric Psychic Ice Dragon Dark Fairy ``` A Pokémon can have single or dual typing. For example, Pikachu is `Electric`, and Tyranitar is `Rock/Dark`. The order of the types does not matter. A Pokémon can't have the same type twice. An attacking move has exactly one of the above 18 types. * Some Pokémon types are weak to a certain type of attack. For example, a `Fire` Pokémon is weak against `Water` attacks. This gives a damage multiplier of 2. * Some Pokémon types are resistant to a certain type of attack. For example, a `Rock` Pokémon is resistant against a `Normal` attack. This gives a damage multiplier of 0.5. * Some Pokémon types are immune to a certain type of attack. For example, a `Flying` Pokémon is immune against a `Ground` attack. This gives a damage multiplier of 0. A pokemon can be doubly weak, doubly resistant or any other combination against an attacking type. Multiply the multipliers to get a total effectiveness. Write a program or function that given a move type and a Pokémon typing outputs the total damage multiplier of the attack. **A Pokémon typing is always written either as `A` or `A/B`, where `A` and `B` are distinct types from the list above. You must accept the Pokémon typing in this format.** Other than this restriction you may take input in any reasonable manner. An example input format that acceptable is: ``` "Ice", "Dragon/Flying" ``` But this is unacceptable: ``` ["Ice", ["Dragon", "Flying"]] ``` Your output must be exactly one of the following strings, followed by an optional trailing newline: ``` 0x 0.25x 0.5x 1x 2x 4x ``` # Examples ``` Ground, Fire -> 2x Normal, Rock/Dragon -> 0.5x Fighting, Ghost/Steel -> 0x Steel, Water/Steel -> 0.25x Ice, Dragon/Flying -> 4x Water, Ground/Water -> 1x Ghost, Ghost -> 2x ``` # Type effectiveness For a human-friendly type chart I'd like to refer you to [Gamepedia](http://bulbapedia.bulbagarden.net/wiki/Type#Type_chart). To make the golfing process a bit faster I'll give you a compressed computer-friendly matrix of effectiveness. Divide every number by two to get the true multiplier (1 -> 0.5, 4 -> 2): ``` Defending type (same order) Normal 222221201222222222 Fighting 421124104222214241 A Flying 242221421224122222 t Poison 222111210224222224 t Ground 220424124421422222 a Rock 214212421422224222 c Bug 211122211124242241 k Ghost 022222242222242212 i Steel 222224221112124224 n Fire 222221424114224122 g Water 222244222411222122 Grass 221144121141222122 T Electric 224202222241122122 y Psychic 242422221222212202 p Ice 224242221114221422 e Dragon 222222221222222420 Dark 212222242222242211 Fairy 242122221122222442 ``` --- Shortest code in bytes wins. [Answer] # Java, ~~663 639~~ 582 bytes ``` String f(String...a){float d=1;for(String B:a[1].split("/"))d*=("222221201222222222421124104222214241242221421224122222222111210224222224220424124421422222214212421422224222211122211124242241022222242222242212222224221112124224222221424114224122222244222411222122221144121141222122224202222241122122242422221222212202224242221114221422222222221222222420212222242222242211242122221122222442".charAt(g(a[0])*18+g(B))-48)*.5;return(d+"x").replace(".0","");}int g(String a){int i=0;for(;i<18;i++)if(a.contains("N,gh,ly,oi,ou,ck,B,ho,S,re,W,G,E,P,I,g,k,y".split(",")[i]))break;return i;} ``` There's a simple lookup table that takes much of the room. It just finds the correct types and multiplies it out. Call it like this: ``` f("Water","Ground/Fire") ``` With some line breaks it looks like this: ``` String f(String...a){ float d=1; for(String B:a[1].split("/")) d*=("222221201222222222421124104222214241242221421224122222222111210224222224220424124421422222214212421422224222211122211124242241022222242222242212222224221112124224222221424114224122222244222411222122221144121141222122224202222241122122242422221222212202224242221114221422222222221222222420212222242222242211242122221122222442" .charAt(g(a[0])*18+g(B))-48)*.5; return(d+"x").replace(".0",""); } int g(String a){ int i=0; for(;i<18;i++) if(a.contains("N,gh,ly,oi,ou,ck,B,ho,S,re,W,G,E,P,I,g,k,y".split(",")[i])) break; return i; } ``` [Answer] # Pyth - ~~246~~ ~~245~~ 188 bytes Encodes the matrix with base compression, will probably use modular indexing/hashing for the matrix indices but right now I haven't done anything fancy with those. ``` Lxc"NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"3<b3.F"{:g}x"*Fm@@c19cR2KXjC" ©ªªå´ê۩涪©Y+ªº;oªnz®©Z»­*«ªºj«¥fëª×­ª¯«Z¥ö]©ªâªÖ»ªj*î¥zzªªj«ªº«¥¹ªZ«ë¥ª¾"4]3]4yzydcw\/ ``` [Test Suite](http://pyth.herokuapp.com/?code=Lxc%22NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai%223%3Cb3.F%22%7B%3Ag%7Dx%22*Fm%40%40c19cR2KXjC%22%0A%C2%A9%C2%86%C2%AA%C2%AA%C3%A5%C2%B4%C3%AA%C2%9E%C3%9B%C2%A9%C3%A6%C2%B6%C2%AA%C2%A9Y%2B%C2%AA%C2%BA%3Bo%C2%9E%C2%AA%C2%9Enz%C2%AE%C2%A9Z%C2%95%C2%BB%C2%AD*%C2%AB%C2%AA%C2%BAj%C2%AB%C2%A5f%C3%AB%C2%AA%C2%9E%C3%97%C2%AD%C2%AA%C2%AF%C2%ABZ%C2%9A%C2%A5%C3%B6%5D%C2%A9%C2%AA%C3%A2%C2%AA%C3%96%C2%9A%C2%BB%C2%AAj%C2%9A*%C3%AE%C2%A5zz%C2%AA%C2%AAj%C2%AB%C2%89%C2%AA%C2%BA%C2%AB%C2%A5%C2%B9%C2%AAZ%C2%AB%C3%AB%C2%9A%C2%A5%C2%AA%C2%BE%224%5D3%5D4yzydcw%5C%2F&input=Ice%0ADragon%2FFlying&test_suite=1&test_suite_input=Ground%0AFire%0ANormal%0ARock%2FDragon%0AFighting%0AGhost%2FSteel%0ASteel%0AWater%2FSteel%0AIce%0ADragon%2FFlying%0AWater%0AGround%2FWater%0AGhost%0AGhost&debug=0&input_size=2). [Answer] ## JavaScript (ES6), 287 I haven't seen a good compression of the types, so here's one. ``` (a,b)=>b.split('/').reduce((j,p)=>j*[0,.5,1,2][parseInt("kjwhcgnj2xd6elihtlneemw82duxijsazl3sh4iz5akjmlmsqds06xf1sbb8d0rl1nu7a2kjwi3mykjwlbpmk1up4mzl1iuenedor0bdmkjwmpk6rhcg4h3en3pew5".substr((g=x=>[..."BWSEIRNulkcDPotyeG"].findIndex(c=>x.match(c)))(a)*7,7),36).toString(4)[g(p)]],1)+'x' ``` Ungolfed: ``` (a,b)=>{ // keys is a list of letters found in the types of attacks/defenses keys = [..."BWSEIRNulkcDPotyeG"]; // getIndex is a single case statement. // it checks each of keys, one-by-one, falling through until we've found the proper index getIndex=x=>keys.findIndex(c=>x.match(c)); // encodedValues is a list, indexed by `keys`, where each value is 7-characters. encodedValues = "kjwhcgnj2xd6elihtlneemw82duxijsazl3sh4iz5akjmlmsqds06xf1sbb8d0rl1nu7a2kjwi3mykjwlbpmk1up4mzl1iuenedor0bdmkjwmpk6rhcg4h3en3pew5"; // the 7-character value (e.g., B=0="kjwhcgn", W=1="j2xd6el") were created by // turning base4 values into base36, so let's turn this back into a string the same way valuesForAttack = parseInt(encodedValues.substr(getIndex(a)*7,7),36).toString(4); // valuesForAttack is indexed by defenseType. The value will be 0..3, depending on the multiplier // let's get an array of the multipliers and reduce... multiplier = b.split('/').reduce((oldMultiplier,defenseType)=>oldMultiplier * [0,.5,1,2][valuesForAttack[getIndex(defenseType)]],1); return multiplier+'x'; } ``` Oh, and here's my chart (keeping in mind it's ordered so that a letter won't match any words listed below it): ``` "Bug" => "B", "Water" => "W", "Steel" => "S", "Electric" => "E", "Ice" => "I", "Rock" => "R", "Normal" => "N", "Ground" => "u", "Flying" => "l", "Dark" => "k", "Psychic" => "c", "Dragon" => "D", "Poison" => "P", "Ghost" => "o", "Fighting" => "t", "Fairy" => "y", "Fire" => "e", "Grass" => "G" ``` [Answer] # Pikalang, 868068 bytes This was just too good of an idea to skip. ([Thanks, mbomb007.](https://codegolf.stackexchange.com/questions/55823/its-super-effective#comment135648_55823)) It's basically a sub-optimal lookup table. I first encode each type as ``` ((first_char + second_char * 2 + third_char * 3) mod 256) - 0x3c ``` This results in unique representations for each type. The empty type (when the defending pokemon has only a single type) is encoded as `0x00`. After that I just use a mess of `if-else` equivalents to check all the ~5800 combinations. ## Code Stack Exchange didn't allow me to post the code as a whole, so here's it gzipped + base64'd. ``` H4sICBA56FUAC3N1cGVyZWZmZWN0aXZlLWdvbGZlZC5wb2tlYmFsbADt2MGOHcdyreG5Ab+DXu3AEws90cTvb1utRrEOuzf3bmZV/mvFD+jyHotkxReRkclF/fXn27/++vOPv/78+4d//vfbv/74v3/++vO//vt//vj7X7z//Pv/+eDX/PjLfv7nx9/x/r+/+uf8mb//xd9VH/+u99/wYx/Qnt47+aexj//j/ad+4Pzqc49//op/DvE/P/zE/jiGj//34y8+T/b99x+/+3QOq8/tR95B/7mF0wb98RP4/NM/9vtT6d9ekMdfPX/7i5/++jd+9c+j37bkX29W3VU+9Gs/7tyeH//9zTj98Mm6//Xnv92fr3/L17/u03/z1b+kTOqH9/+zPwoe/vFwvByf//+v/Mnz6+KPfsVPP/c14dcffe1TPw7TOf7K6bRemdajOX7xuD3/w/vX/jmIz7LCmjLPIvIhTb0IKYdQXRiIrpvqOVkh97jezv8BxeT5xG/46WeWnpfLLETILAimF11ChAi5E2JANaBmb7AQrmssBNO4riiXc1hWDzNKIS+5TKQm0rSFHguxXunB6ip3YSCbXc5ByDP1jKXGUuii8iG6Rtbj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S5C1npMn2aPms2XYiQSZCmXoSUQ6guISEQo6pRtXS1hXBdYyFjGxeyu16cawGkqZcyyEOXsdRYWrPpYyHWKz1YIULqXBgI1TUWcq5nNjWbpm0wH6JrZD0hu+vxIR6IEAZkbz2DZ0LwPM6sfR83XnyqCwPJXxTMKANnlwlprxfnaj+QvfWMcwlx7vWzHXRh+RCqS8huiI1PaxwDaa8nZHe9JyFG0OgIehwmZqO+BYHeDiGDIZjGnQPb1QRp6kXIHRATpAlyxqZfDxnbeJxLiJAYyGZXez0h6RAz7KYMexwDZheECBHCg2Aadw5CslxCUlxniLF0UyxdfZjXb9TdG4y5MboQ9aguzByECNElZCTEIGuQnbHp10Pa68W5MBCqCwOhusZCbHxa43zIQ5dBNjrIfnm21H3zQgoRIsR60w5WSB6E6jpDzLDRGfY4TF9fr/h4yNjGhQgRQq8n5JsQU6optXS1B0Ha6wkRIoReDwPBNK5rocuoalSt2XQhQnRlQ9rrCdld70pIUy9XQIybxs3S1RYCgugSImSGCwOhuoTshpzr/Xvd4xf9/w/v9d85//kf/wsHs6nq5j4NAA== ``` ## Example Apparently the official Pikalang interpreter is not ready yet, but since it's a trivial Brainfuck substitution, I tested it using a Brainfuck interpreter. ``` $ base64 -d supereff.pokeball.gz.b64 > supereff.pokeball.gz $ gunzip supereff.pokeball.gz $ pikalang supereff.pokeball Normal Rock/Dragon 0.5x ``` Input is newline-separated and requires an additional trailing newline. The program uses the memory location -1, so if your interpreter disallows going off the left side of the tape, prepend the code with a `pipi` or a `>` (for Pikalang and Brainfuck, respectively). # Brainfuck, 193708 Here's the same program in Brainfuck (also gzipped + base64'd). ``` H4sICGI+6FUAC3N1cGVyZWZmZWN0aXZlLWdvbGZlZC5iZgDtXQt2GzkOPJDjOYEeL6Ln+19jbHmsyKNPgwSqUCDpfTuTqBokgC4WAEab/dP+nN9Pb2/t4/vfn794u/x8/u79+vP54fnP399+tD9Gs/Z+bu+n043t+d3yc27t7XQ6v398fLR2Pr21t4/Tx4NNPx9pb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H5hCTz4mn98EAgo+uSIsli1xNi8VPVby+in6ieS587N/sL9rrUNgviqYi8Vil8em0K286E81ryUmTyBASreK71cefhxSNK7pK5lnDbkNLdp6gaqstyR6QmZgo1pce+4slI8VyRbO6AEAOVF08xFpwRVEdKbNQ5tAo9I0nsXqGKugIFGyseCh1ZU2QZMNR5+PcCT5lELMEsQjR/sgKWiG4vOWka1zASt5b+iqNoCwnxLDdLdSVSjl3UdkBMXduuuxhQwAWJbVdjF2RlJeHrXHTrVgAYWkzkwDzjhe48HDiPZfzLDu5ZzeDUEzrx+1D7pjzuULNQhTE3+6upfT4z4ldMCLhCbVNqUyClJ9LTPdkFRFVJ03AOi7RRV5BIsYTrghmETPHcWIzVxAtSRQDrKhE6BJ9Dve42Tx9gXJslG4sPE7e46oyIC1wJrNJHLVEqY6JVOd9K4Go1Ml8oaoHUcaQHX4RdTtCL55O+x2jrVQjoxRV9FgvowrdPpJ3/aR//ArQnatCs9AIA ``` The program contains four parts: 1. The input. Reading the types and calculating their identifiers. 2. The text generation. Generating strings for each of the possible outputs. 3. The lookup table. This part was computer-generated (see below). Moves the pointer to the correct result. 4. The output. Just printing the result. ## Main program structure ``` ,>,[-<++>],[-<+++>] read first type id ++++++[-<---------->] subtract 3c +[,----------] skip until newline >,>,[-<++>],[-<+++>] read second type id ++++++[-<---------->] subtract 3c >- set @LOOPFLAG@ to get into loop [ >-< set @CHARFLAG@ <,---------- get character; newline is 00 slash is 25 [ was not newline ------------------------------------- slash is now 00 [ was not slash >>+<< reset @CHARFLAG@ [-] clear character ] ] >>[ was newline or slash (@CHARFLAG@ set) <+>+ reset @LOOPFLAG@ and @CHARFLAG@ ]< ] ,>,[-<++>],[-<+++>] read third type id <[->+>+<<]>[-<+>] copy third to @CHARFLAG@ >[ if @CHARFLAG@ is set [-] clear @CHARFLAG@ <++++++[-<---------->]> subtract 3c from third ]< ++++++++[- do 8 times >++++++ put a 0 here >+++++++++++++++ put an x here >>++++++ put a 0 here >++++++ put a 0 here >++++++ put a 0 here >+++++++ put a 8 here >+++++++++++++++ put an x here >>++++++ put a 0 here >++++++ put a 0 here >+++++++ put a 8 here >+++++++++++++++ put an x here >>++++++ put a 0 here >+++++++++++++++ put an x here >>++++++ put a 0 here >+++++++++++++++ put an x here >>++++++ put a 0 here >+++++++++++++++ put an x here <<<<<<<<<<<<<<<<<<<<<< go back ] >>>>>-- change 0 to dot >++ change 0 to 2 >--- change 8 to 5 >>>>-- change 0 to dot >--- change 8 to 5 >>>+ change 0 to 1 >>>++ change 0 to 2 >>>++++ change 0 to 4 <<<<<<<<<<<<<<<<<<<<<< go back (lookup table here) >[.>] print result ``` Here's the script that generates the lookup table: ``` typemap = [[int(value, 16), name] for value, name in [ ["00", "(Nothing)"], ["02", "Ice"], ["07", "Fairy"], ["0f", "Dragon"], ["10", "Electric"], ["11", "Fighting"], ["12", "Grass"], ["1d", "Rock"], ["20", "Dark"], ["25", "Bug"], ["28", "Ghost"], ["2d", "Poison"], ["2e", "Steel"], ["32", "Fire"], ["39", "Water"], ["3c", "Ground"], ["46", "Normal"], ["4d", "Flying"], ["65", "Psychic"] ]] multipliers = { 0: 5, 0.25: 8, 0.5: 14, 1: 19, 2: 22, 4: 25 } types = [ "Normal", "Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark", "Fairy" ] results = [ [2, 2, 2, 2, 2, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2], [4, 2, 1, 1, 2, 4, 1, 0, 4, 2, 2, 2, 2, 1, 4, 2, 4, 1], [2, 4, 2, 2, 2, 1, 4, 2, 1, 2, 2, 4, 1, 2, 2, 2, 2, 2], [2, 2, 2, 1, 1, 1, 2, 1, 0, 2, 2, 4, 2, 2, 2, 2, 2, 4], [2, 2, 0, 4, 2, 4, 1, 2, 4, 4, 2, 1, 4, 2, 2, 2, 2, 2], [2, 1, 4, 2, 1, 2, 4, 2, 1, 4, 2, 2, 2, 2, 4, 2, 2, 2], [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 4, 2, 4, 2, 2, 4, 1], [0, 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2, 1, 2], [2, 2, 2, 2, 2, 4, 2, 2, 1, 1, 1, 2, 1, 2, 4, 2, 2, 4], [2, 2, 2, 2, 2, 1, 4, 2, 4, 1, 1, 4, 2, 2, 4, 1, 2, 2], [2, 2, 2, 2, 4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 2, 1, 2, 2], [2, 2, 1, 1, 4, 4, 1, 2, 1, 1, 4, 1, 2, 2, 2, 1, 2, 2], [2, 2, 4, 2, 0, 2, 2, 2, 2, 2, 4, 1, 1, 2, 2, 1, 2, 2], [2, 4, 2, 4, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 0, 2], [2, 2, 4, 2, 4, 2, 2, 2, 1, 1, 1, 4, 2, 2, 1, 4, 2, 2], [2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 4, 2, 0], [2, 1, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2, 1, 1], [2, 4, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 4, 4, 2] ] def getMultiplier(first, second, third): id1 = types.index(first) id2 = types.index(second) if third in types: id3 = types.index(third) return results[id1][id2] * results[id1][id3] / 4; else: return results[id1][id2] / 2 def genFirstType(second, third, remain, removed): mul = getMultiplier(remain[0][1], second, third) if len(remain) == 1: result = "[ first is not " + removed[1] + "\n" result += "thus first must be " + remain[0][1] + "\n" result += ">" * (multipliers[mul] - 1) + "[-]-> " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n" result += "]\n" return result elif not removed: result = "<<" + "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n" result += genFirstType(second, third, remain[1:], remain[0]) result += "<+[ first is " + remain[0][1] + "\n" result += ">" * multipliers[mul] + "[-] " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n" result += "]->\n" return result else: result = "[ first is not " + removed[1] + "\n" result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n" result += genFirstType(second, third, remain[1:], remain[0]) result += "<+[ first is " + remain[0][1] + "\n" result += ">" * multipliers[mul] + "[-] " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n" result += "]->\n" result += "]\n" return result def genSecondType(third, remain, removed): if len(remain) == 1: result = "[ second is not " + removed[1] + "\n" result += "thus second must be " + remain[0][1] + "\n" result += genFirstType(remain[0][1], third, typemap[1:], False) result += "]\n" return result elif not removed: result = "<<" + "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n" result += genSecondType(third, remain[1:], remain[0]) result += "<+[-> second is " + remain[0][1] + "\n" result += genFirstType(remain[0][1], third, typemap[1:], False) result += "<+]->\n" return result else: result = "[ second is not " + removed[1] + "\n" result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n" result += genSecondType(third, remain[1:], remain[0]) result += "<+[-> second is " + remain[0][1] + "\n" result += genFirstType(remain[0][1], third, typemap[1:], False) result += "<+]->\n" result += "]\n" return result def genThirdType(remain, removed): if len(remain) == 1: result = "[ third is not " + removed[1] + "\n" result += "thus third must be " + remain[0][1] + "\n" result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False) result += "]\n" return result elif not removed: result = "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n" result += genThirdType(remain[1:], remain[0]) result += "<+[-> third is " + remain[0][1] + "\n" result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False) result += "<+]->\n" return result else: result = "[ third is not " + removed[1] + "\n" result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n" result += genThirdType(remain[1:], remain[0]) result += "<+[-> third is " + remain[0][1] + "\n" result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False) result += "<+]->\n" result += "]\n" return result def genLookup(): return genThirdType(typemap, False) def compact(code): import re return re.sub(r"[^+\-<>\[\],.]", "", code) def golfStep(code): return code.replace("><", "").replace("<>", "").replace("+-", "").replace("-+", "") def golf(code): previous = golfStep(code) while previous != code: previous, code = code, golfStep(code) return code if __name__ == "__main__": import sys result = genLookup() if "-g" in sys.argv: print(golf(compact(result))) elif "-c" in sys.argv: print(compact(result)) else: print(result) ``` BTW, this answer takes 29817 bytes. :) [Answer] ## C++14, ~~420~~ 416 ``` #include<iostream> #include<string> std::string m,t,n="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai";int i;int main(){std::cin>>m>>t;auto k=[](auto y){return(i=6*n.find(m.substr(0,3))+n.find(y.substr(0,3))/3,i="J:2JJJ;YQJV>N:;ZIJJ5&ZJZ*[Y;KJVF;KZJ6I6YN>HJNJNFJZ:EYZJ:[UZIJ^J7JI:]9=JIZBJ>IINK:JFBZN:U:KJJ:JJ+FJNJN6NI:IJO"[i/3]-32>>i%3*2&3,i+i/3)/2.;};std::cout<<k(t)*((i=t.find(47)+1)?k(t.substr(i)):1)<<"x";} ``` Input should be to stdin and be in the form `Normal, Rock/Dragon` [Live version](http://ideone.com/7tJi4v). With some whitespace: ``` #include<iostream> #include<string> std::string m, t, n = "NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"; int i; int main(){ std::cin >> m >> t; auto k = [](auto y){ return(i = 6 * n.find(m.substr(0, 3)) + n.find(y.substr(0, 3)) / 3 , i = "J:2JJJ;YQJV>N:;ZIJJ5&ZJZ*[Y;KJVF;KZJ6I6YN>HJNJNFJZ:EYZJ:[UZI" "J^J7JI:]9=JIZBJ>IINK:JFBZN:U:KJJ:JJ+FJNJN6NI:IJO"[i / 3] - 32 >> i % 3 * 2 & 3 , i + i / 3) / 2.; }; std::cout << k(t)*((i = t.find(47) + 1) ? k(t.substr(i)) : 1) << "x"; } ``` [Answer] ## Tcl, 382 ``` proc p a\ d [zlib i ...361 bytes...] ``` The script contains compressed data including non-UTF-8 bytes. Here is the exact script encoded in base 64: ``` cHJvYyBwIGFcIGQgW3psaWIgaSDFU7FugzAQ/ZU3pEuGlljqwlilibpUUVw7dEBc Zo7jghUHI9uREiH+vUDA2NCqY2SJXDt87969XDvb5dkaXCTfSp+oxUN2QWKZjOPm L1dlHC9RLetEnmiJPRJTSmGxOOApRSVFceAXVNVcbsOKHp/bb28nq0ZFeswtTm4+ SJBPhkiDX7nYEBmYSVijw6489l5Jx3/Dj0pIj47GWp0lXh2fN6w9R5FcdHasP1dE HH7oMVxupkRmfpfn+lx298NOHXOADmbqKXcT9NDE1Se/dDFiRybiT7rb+Sunm1xb 0J1fwceOM/JcIoEfBaz+HVx0XHt0XjCROa/T587wvxPx7+dU4TS/wdQ1Emk41SxH 9d4+NomNyHIrilxmG3ltzU5cdKNcbmy1OhcHfCh2xMs5wzZXxuLTct6maI4varlu YNQYvErOrBZcZlw7c2V5Y98Yx1rTrCFaU1x9xIZcblx9rbGg6Z0F7NM6TdMfXQ== ``` Uses the `zlib` command for compression. [Answer] # Lua, ~~758~~ ~~661~~ 633 bytes ``` m={"222221201222222222","421124104222214241","242221421224122222","222111210224222224","220424124421422222","214212421422224222","211122211124242241","022222242222242212","222224221112124224","222221424114224122","222244222411222122","221144121141222122","224202222241122122","242422221222212202","224242221114221422","222222221222222420","212222242222242211","242122221122222442"}s="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"function f(a,d)z=string.sub n=tonumber _,r=s:find(z(a,1,3))r=r/3g,_,c=0,s:find(z(d,1,3))c=c/3p=d:find("/")or 0 e=m[r]_,g=s:find(z(d,p+1,p+3))g=g/3r=n(z(e,c,c))/2r=r*n(z(e,g,g))/2print(r.."x")end ``` Ungolfed: ``` m={"222221201222222222","421124104222214241","242221421224122222","222111210224222224","220424124421422222","214212421422224222","211122211124242241","022222242222242212","222224221112124224","222221424114224122","222244222411222122","221144121141222122","224202222241122122","242422221222212202","224242221114221422","222222221222222420","212222242222242211","242122221122222442"} s="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai" function f(a,d) z=string.sub n=tonumber _,r=s:find(z(a,1,3)) r=r/3 g,_,c=0,s:find(z(d,1,3)) c=c/3 p=d:find("/") or 0 e=m[r] _,g=s:find(z(d,p+1,p+3)) g=g/3 r=n(z(e,c,c))/2 r=r*n(z(e,g,g))/2 print(r.."x") end ``` Call it with `f("Grass","Water/Flying")` [Answer] # Python 3 - 362 ``` k,*l=['rm gh yi is ou ck g os ee re te as ec yc e ag rk ir'.split().index(x[2:4])for x in input().replace('/',' ').split()] s=[[0,0.5,1,2][[(ord(m)-40)//4**q%4 for m in'RB:RRRCaYR^FVBCbQRR=.bRb2caCSR^NCSbR>Q>aVFPRVRVNRbBMabRBc]bQRfR?RQBeAERQbJRFQQVSBRNJbVB]BSRRBRR3NRVRV>VQBQRW'for q in(0,1,2)][k*18+z]]for z in l] v=s[0]*(s[1:]or[1])[0] print(str(v//1+v%1)+'x') ``` Input format is the move type and the Pokemon type, separated by spaces. For example `Fire Grass`, or `Water Steel/Electric`. The table is stored is a string where each character's index is in the range 40 to 103 and represents 3 type combinations. The list of types is stored as the 3rd and 4th (if it exists) characters of each type, which are compared to the 3rd and 4th characters of each entered type. [Answer] ## PHP, 426 ``` eval('f('.fgets(STDIN).');'); function f($a,$d){ $x=1;$r=array_fill_keys(explode('/',$d),$a); while(list($d,$a)=each($r)) { $x*=substr(gmp_strval(gmp_init('26gXl6oUL8Ekoey31DRp2k1Jq85b0G3f1PsFPfEnL1P6Bxh4vSloX8zWWa4XPBAGavHMKLgaGhPp2JPA3qQI3L9kkQ4kSHvu2vm76aLpJmu6TV8qcPTO0hchrLRh6G9',62),5),n($a)*18+n($d),1)/2; } echo$x.'x'; } function n($p){return strpos('NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai',substr($p,0,3))/3;} ``` Sample input: ``` "Ground", "Fire" "Normal", "Rock/Dragon" "Fighting", "Ghost/Steel" "Steel", "Water/Steel" "Ice", "Dragon/Flying" "Water", "Ground/Water" "Ghost", "Ghost" ``` Sample output: ``` 2x 0.5x 0x 0.25x 4x 1x 2x ``` ]
[Question] [ Given an input of a "hotel" in ASCII art with a single room marked, output the room number according to certain rules. Here's an example of an ASCII hotel: ``` ## ## ##### ## ##### ###### ## ##### ###### ## ##### ###### ## ``` Here are a few more things about the ASCII hotels: * Each "building" is represented by a rectangle of `#` characters, where each `#` represents a "room". * The above hotel consists of three buildings. Each building is separated by two columns of spaces, and the lowest "floor" will always be on the last line. * Each building will always have anywhere from 1-9 "floors" (rows) and 1-9 "rooms" on each floor. There will also always be 1-9 buildings. * Rooms are numbered as follows: `[building #][floor #][room on floor #]`. For example, let's mark a few rooms in the above drawing: ``` ## ## ##### ## ##### ####$# ## ##%## ###### ## ##### ###### #@ ``` The room marked with the `%` is room 123 (building 1, floor 2, 3rd room on floor). Similarly, the room marked with the `$` is room 235, and the `@` is room 312. * Buildings, floors, and "nth room on floor"s are always 1-indexed. The input will consist of an ASCII hotel with a single room replaced with an asterisk (`*`). This is the room for which you must output the room number. The input must be taken as a single string, but you may use commas as line separators instead of newlines (in case your language of choice cannot take multiline input or if it's shorter to take single-line input). You may optionally require a trailing comma/newline. You may also pad lines with trailing spaces to make the input a complete rectangle. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Test cases (contained within a single code block to conserve vertical space): ``` Input: * Output: 111 Input: # # * # # Output: 311 Input: ##### ##### ####* ##### ##### Output: 135 Input: ##### ##### ###### ##### ###### # # # ##### # # # ###### * Output: 911 Input: # # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ######## Output: 523 Input: # * # # # # # # ######### # # Output: 281 Input: ########* ######### ######### ######### ######### ######### ######### ######### # # # # # # # # ######### Output: 999 ``` [Answer] ## CJam, ~~34~~ 31 bytes ``` qN/W%zSf-La%{_{s'*&}#_)@@=}3*;\ ``` This requires the input to be padded to a rectangle with spaces. [Try it online!](http://cjam.tryitonline.net/#code=cU4vVyV6U2YtTGEle197cycqJn0jXylAQD19Myo7XA&input=ICAgICAgICAgIyMjIyMgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAjIyMjIyAgICAgICAgICAgIyMjIyMjICAgCiAgICAgICAgICMjIyMjICAgICAgICAgICAjIyMjIyMgICAKIyAgIyAgIyAgIyMjIyMgICMgICMgICMgICMjIyMjIyAgKg) Alternatively, [run all test cases.](http://cjam.tryitonline.net/#code=cU4yKi97Ti9feixme1NlXXN9Tio6UTsKClFOL1clelNmLUxhJXtfe3MnKiZ9I18pQEA9fTMqO1wKCl1vTm99Lw&input=KgoKIyAgIyAgKiAgIyAgIwoKIyMjIyMKIyMjIyMKIyMjIyoKIyMjIyMKIyMjIyMKCiAgICAgICAgICMjIyMjCiAgICAgICAgICMjIyMjICAgICAgICAgICAjIyMjIyMKICAgICAgICAgIyMjIyMgICAgICAgICAgICMjIyMjIwojICAjICAjICAjIyMjIyAgIyAgIyAgIyAgIyMjIyMjICAqCgojCiMgICMKIyAgIyAgIyMKIyAgIyAgIyMgICMjIwojICAjICAjIyAgIyMjICAjIyMjIwojICAjICAjIyAgIyMjICAjIyojIyAgIyMjIyMjIyMKIyAgIyAgIyMgICMjIyAgIyMjIyMgICMjIyMjIyMjCgogICAgICAgICAgICMKICAgICAgICAgICAqCiAgICAgICAgICAgIwogICAgICAgICAgICMKICAgICAgICAgICAjCiAgICAgICAgICAgIwogICAgICAgICAgICMKICAgICAgICAgICAjCiMjIyMjIyMjIyAgIyAgIwoKICAgICAgICAgICAgICAgICAgICAgICAgIyMjIyMjIyMqCiAgICAgICAgICAgICAgICAgICAgICAgICMjIyMjIyMjIwogICAgICAgICAgICAgICAgICAgICAgICAjIyMjIyMjIyMKICAgICAgICAgICAgICAgICAgICAgICAgIyMjIyMjIyMjCiAgICAgICAgICAgICAgICAgICAgICAgICMjIyMjIyMjIwogICAgICAgICAgICAgICAgICAgICAgICAjIyMjIyMjIyMKICAgICAgICAgICAgICAgICAgICAgICAgIyMjIyMjIyMjCiAgICAgICAgICAgICAgICAgICAgICAgICMjIyMjIyMjIwojICAjICAjICAjICAjICAjICAjICAjICAjIyMjIyMjIyM) ### Explanation ``` qN/ e# Read input and split into lines. W%z e# Rotate 90° counter-clockwise. Sf- e# Remove all spaces from the rows. La% e# Split into buildings. We've now got a 3D array of rooms, where the first e# dimension is the building, the second the room number and the third is the e# the floor number. { e# Run this block three times. At each stage it will find the index of the "*" e# along the current dimension and leave the element at that index on the stack e# for the next round... _ e# Duplicate the current array. { e# Find the index of the first element where this block yields something e# truthy... s e# Flatten into a single string. '*& e# Set intersection with "*". }# _) e# Duplicate the index and increment it, because the results should be 1-based. @@= e# Pull up the array and the other copy of the index and select the e# corresponding element. }3* ;\ e# We've now got the building, room and floor index on the stack, as well as the e# "*" character itself. We discard the character and swap the room and the floor e# floor number. When the three indices are printed back-to-back at the end of e# the program, that will yield the desired result. ``` [Answer] # Pyth, 34 bytes ``` LxKh/#\*b\*jkhM[//<hJ_.zyJd2xJKycK ``` [Demonstration](https://pyth.herokuapp.com/?code=LxKh%2F%23%5C%2ab%5C%2ajkhM%5B%2F%2F%3ChJ_.zyJd2xJKycK&input=%23%0A%23++%23%0A%23++%23++%23%23%0A%23++%23++%23%23++%23%23%23%0A%23++%23++%23%23++%23%23%23++%23%23%23%23%23%0A%23++%23++%23%23++%23%23%23++%23%23%2a%23%23++%23%23%23%23%23%23%23%23%0A%23++%23++%23%23++%23%23%23++%23%23%23%23%23++%23%23%23%23%23%23%23%23&debug=0) This uses a golfing trick I've never used before: Assigning to a variable (`K`) inside a function (`y`) to save a partial result from that function. ### Explanation: ``` LxKh/#\*b\*jkhM[//<hJ_.zyJd2xJKycK L Define y(b): (b is a list of strigs) /#\*b Filter b for strings containing '*' h Take the first such string K Store it in K x \* And return the index of '*' in that string. .z Take the input as a list of strings _ Reverse it (bottom to top) J Store in J h Take the bottommost row yJ Find y(J). This is the index in whichever row of J has the * of the *. Also store that row in K. < Slice J up to that index. / d Count the number of spaces / 2 Divide by 2. This is the building number. xJK Take the index in J of K. This is the floor. cK Chop K on whitespace. y Find the index in whatever element of K has the * of the *. This is the room number. This also overwrites K, but we don't care. [ Gather the above into a list. hM Convert 0-indexing to 1-indexing. jk Concatenate. Print implicitly. ``` [Answer] # JavaScript (ES6), ~~142~~ 136 bytes ``` h=>h.split` `.reverse(r=0).map((t,i,l)=>r?0:(f=i+1,b=1,l[o=0].slice(0,r=t.indexOf`*`+1).replace(/ /g,(_,s)=>o=++b&&s+2),r-=o))&&[b]+f+r ``` *6 bytes saved thanks to [@nderscore](https://codegolf.stackexchange.com/users/20160/nderscore)!* ## Explanation ``` h=> h.split` ` // get each line of the input string .reverse( // reverse the lines to make getting the ground floor easy r=0) // initialise r to 0 .map((t,i,l)=> // for each line of the reversed input string r?0:( // if the marked room has not been found yet: f=i+1, // f = floor number b=1, // b = building number, default to 1 l[o=0].slice(0, // get the substring of 0 to the marked room, default o to 0 r=t.indexOf`*`+1) // r = absolute index of room + 1 (or 0 if not found) .replace(/ /g,(_,s)=> // count the spaces between buildings o=++b&&s+2), // increment b, o = index of marked room's building r-=o // make r relative to the room's building ) ) &&[b]+f+r // output the result ([b] casts b to a string) ``` ## Test ``` var solution = h=>h.split` `.reverse(r=0).map((t,i,l)=>r?0:(f=i+1,b=1,l[o=0].slice(0,r=t.indexOf`*`+1).replace(/ /g,(_,s)=>o=++b&&s+2),r-=o))&&[b]+f+r ``` ``` <textarea id="input" rows="8" cols="60"># # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ########</textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # awk, 70 ``` !i{i=index($0,"*")}i{$0=substr($0,0,i);f++}END{print NF f length($NF)} ``` Example: ``` Input: # # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ######## While no * was found, do nothing. # # # # # ## # # ## ### # # ## ### ##### A * is found in column 14. From now on, truncate and increment the floor counter. # # ## ### ##* f=1 # # ## ### ### f=2 Awk automatically splits $0 into space separated fields, counted by builtin NR. In the end, NR and f hold hotel and floor number. The room number is the length of the last hotel. ``` [Answer] # C, 131 130 119 113 bytes ``` b,f,i,j=111;main(c){for(;c=~getchar();)c&32?f+=10,b=i=0:++i<j?c%3?f=j,j=i:c&2?b+=50-b%50:++b:0;printf("%d",b+f);} ``` Takes input on stdin; input must *not* have a terminating newline. Assumes 2's complement. Ungolfed: ``` // Declare variables (default type is int) and initialize, by default to 0: b, // Building number (multiplied by 100, 0-based) + room number (0-based) f, // Floor (111-based, multiplied by 10) i, // Current column of input character within line (1-based) j = 111; // Column of asterisk character once found (1-based), 111 before then main (c) // Declare main function and variable c to hold input character { for (; // Loop on input c = ~getchar(); // Read a character into c, bitwise inverted to break // EOF (numeric value -1). This means that following // operations (on the ASCII value of the input) are // also inverted. ) c & 32 ? // Newline? f += 10, b = i = 0 : // Increment floor; reset building, room, column ++i < j ? // Increment column; before asterisk, or asterisk not yet found? c % 3 ? // Asterisk character? f = j, j = i : // Reset floor and record column c & 2 ? // Space character? b += 50 - b % 50 : // Increment building and reset room ++b : // Otherwise, # character; increment room 0; // After asterisk; do nothing printf("%d", b + f); // Write out results } ``` [Answer] # [Stackgoat](https://github.com/vihanb/Stackgoat), 73 bytes [non-competing] Stackgoat is a stack-based language that has nothing to do with goats. ``` y'#ZGDYZG'*iVXsV@"\\*"ZGN2/1+y'#ZG' ZG'q:Nq'*i-yXsq'*i@"[#*]+"M0M1-@'*i1+ ``` It's a fairly new language so let me know if they're any problems with it. I gave myself quite a headache figuring this out so this is about as much as I'm golfing this. ### Explanation This program has 3 parts for each 3 digits of the room number ``` y'#ZG // Remove all # from input D // Duplicate YZG // Remove all spaces '*i // Index of * V // Reverse stack Xs // Split on spaces V@ // Unreverse, item at *'s index "\\*"ZG // Remove all *s N // Get length 2/1+ // Divide by 2, add 1 y'#ZG // Remove all # ' ZG // Remove all spaces 'q: // Store in q N // Get length q'*i // *'s index in q - // Subtracted from length yXs // Split on newlines q'*i // Get index of * in q @ // Get indexed-th line "[#*]+"M // Match all buildings 0M // Get *'s building no. 1- // Subtract one @ // nth building at right line '*i // *'s index 1+ // Added to one ``` [Answer] # Ruby, 103 ``` ->n{r=x=b=0 n.lines{|s|(t=s=~/\*/)&&(x=t;r=($`.reverse+' ')=~/ /) r+=10;b=s[0..x].count" "} b*50+r+101} ``` Ungolfed in test program ``` g=->n{ r=x=b=0 n.lines{|s| #for each line in n (t=s=~/\*/)&& #if the line contains an asterisk (x=t #record its position in x. $` is a special variable containing the part of the string to the left of the last match made. r=($`.reverse+' ')=~/ /) #reverse $` and search for the index of the first space to find room number (before the search a space is appended in case it is 1st building.) r+=10 #increment r by 10 for the floor number (obviously this will have been reset to the row ith the asterisk by the previous line) b=s[0..x].count" "} #count the number of spaces left of x in the current row to find building number (loop will exit with calc from bottom row, which is the correct one.) b*50+r+101} #multiply number of spaces by 50 to get 1st digit, add r for 2nd and 3rd digit. Then add 101 to correct 1st and 3rd digits from 0-indexed to 1-indexed. puts g[" *"] puts g[" # # * # #"] puts g[" ##### ##### ####* ##### #####"] puts g[" ##### ##### ###### ##### ###### # # # ##### # # # ###### *"] puts g[" # # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ########"] puts g[" # * # # # # # # ######### # #"] puts g[" ########* ######### ######### ######### ######### ######### ######### ######### # # # # # # # # #########"] ``` [Answer] # JavaScript (ES6), 121 ``` x=>x.split` `.reverse().map((r,f,h,a=r.indexOf`*`)=>x=~a?(h=h[0].slice(0,a).split` `).length+[f+1]+-~h.pop().length:x)|x ``` **Less golfed and explained** ``` H=x=>x.split`\n` // split in lines .reverse() // reverse, so we can scan bottom up .map( (r,f,h) => // exectute for each line // r is the current row // f in the row index, so that f+1 is the floor number // h is the reversed array, h[0] is the bottom floor ~(a=r.indexOf`*`) // a is the position of '*' in the line, if found - else 0 && ( // if a >= 0 h = h[0] // bottom floor line .slice(0,a) // ... truncated at position of '*' .split` `, // ... and splitted at ' ', as an array x = h.length // the array len is the building number + [f+1] // floor number, using [] to force string concatenation + -~ h.pop().length // the length of the last array element is the number // of chars in the block before '*' // increment by 1 to get the room number ) ) && x // return the found value ``` **TEST** ``` H=x=>x.split` `.reverse().map((r,f,h,a=r.indexOf`*`)=>x=~a?(h=h[0].slice(0,a).split` `).length+[f+1]+-~h.pop().length:x)|x // test console.log=x=>O.textContent+=x+'\n'; ;[['*',111],['# # * # #',311], [`##### ##### ####* ##### #####`,135], [` ##### ##### ###### ##### ###### # # # ##### # # # ###### *`,911], [`# # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ########`,523], [` # * # # # # # # ######### # #`,281], [` ########* ######### ######### ######### ######### ######### ######### ######### # # # # # # # # #########`,999]] .forEach(t=>{ var i=t[0],k=t[1],r=H(i) console.log(i+'\n' + (k!=r?'Error '+r+' expected '+k:'Ok '+r)+'\n') }) ``` ``` <pre id=O></pre> ``` [Answer] ## Python 2.7, ~~153~~ 168 characters I liked this challenge! If a Python list is ok as input (see testsuite for examples), this solution works. *Edit 2016-01-05:* added one line (10 characters) to split the string in multiline. Short explanation: * `t` is the row in which the room is located (counted from the top-row as array index = 0); * `i` is the index of the room in its row; * the building is calculated as the number of double white spaces in the bottom row until `i`; * floor is the number of row minus `t`; * room is the index of the first double whitespace in the reversed string from `i` until the beginning of the floor with the room, appended by a whitespace to cover for the case that the room is in the first building. Code: ``` def r(l): l=h.split(",") a,w,s="*"," ",str t=l.index(filter(lambda c:a in c,l)[0]) i=l[t].find(a) return s(l[-1][:i].count(w)+1)+s(len(l)-t)+s((l[t][i::-1]+w).find(w)) ``` Testsuite: ``` cases = [ (["*"], 111), (["# # * # #"], 311), (["#####","#####","####*","#####","#####"], 135), ([" #####"," ##### ######"," ##### ######","# # # ##### # # # ###### *"], 911), (["#","# #","# # ##","# # ## ###","# # ## ### #####","# # ## ### ##*## ########","# # ## ### ##### ########"], 523), ([" #"," *"," #"," #"," #"," #"," #"," #","######### # #"], 281), ([" ########*"," #########"," #########"," #########"," #########"," #########"," #########"," #########","# # # # # # # # #########"], 999) ] for idx,(hotel,roomnr) in enumerate(cases): output=r(hotel) if str(output)==str(roomnr): result="SUCCESS" else: result="FAILURE!!!" print "Case {} gives output: {}. Correct output is: {}. Result: {}".format(idx,output,roomnr,result) ``` [Answer] # [Snails](https://github.com/feresum/pma), 32 bytes ``` A \*{l\#,|r,9d.,{|=~r,9{|l.,\ \# ``` [Answer] # C, ~~142~~ ~~138~~ 137 bytes ``` #include <stdio.h> f,b,x,p=110;main(c){while(~(c=getchar()))c<11?f+=c,b=x=0:x++<p?++b,c&2?c&8?f=p,p=x:0:(b+=50-b%50):0;printf("%d",b+f);} ``` (~~123~~ ~~119~~ 118 bytes + 19 for `#include` line) I stole the value merging idea from ecatmur, but I've merged them in quite a different way (~~saves 8 bytes in the end~~). This also makes the same assumption that `EOF == -1`. The input is taken from stdin, and must not have whitespace or newlines after the last building on the last line, so an example input would be: ``` printf "##\n## #\n## ##* #\n## ### #" | ./hotel # or for better visualisation: printf "##\n## #\n## ##* #\n## ### #" | tee /dev/fd/2 | ./hotel;echo "" ``` Breakdown: ``` // Globals initialise to 0 f, // floor number * 10 + shift b, // building number * 100 + room number x, // current column p=110; // will store column of * (must start >= 11*9-2, and 110 will be used later) main(c){ while(~(c=getchar())) // For each character until EOF c<11 // Is \n? (10) ?f+=c, // Add 10 to floor number b=x=0 // Reset building, room, column :x++<p // Else, is column <= *? ?++b, // Add to room number c&2 // Is # or *? ?c&8 // If *: ?f=p,p=x:0 // Set floor to 110, set p to column :(b+=50-b%50) // If ' ': go to next building :0; printf("%d",b+f); // Result is building+room+floor+shift } ``` [Answer] ## Haskell, ~~128~~ 125 bytes ``` l=length f h|b<-snd$break(elem '*')$lines h,q<-fst(span(<'*')$b!!0)++"*"=l(last$words$q)+10*l b+l(words$take(l q)$last b)*100 ``` Usage example: `f "# # * # #"` -> `311`. How it works: ``` b<-snd$break(elem '*')$lines h -- split the input into a list of lines -- and assign b to the lines starting with -- the one that includes * up to the end, -- i.e. drop leading lines without the * q<-fst(span(<'*')$b!!0)++"*" -- assign q to the line with the *, but strip -- off all chars after the * l(last$words$q) -- the room on floor number is the length of -- the last word of q 10*l b -- the floor number is 10 times the length of b l(words$take(l q)$last b)*100 -- the hotel number is 100 times the number of -- words in the last line cut down to the -- length of q -- add for final room number ``` [Answer] ## Lua, 165 Bytes ``` l={}i=1while(l[i-1]~="")do l[i]=io.read()o=l[i]:find"%*"x=o or x y=o and i or y i=i+1 end print(#l[i-2]:sub(1,x):gsub("%S+%s*","#")*100+(i-y-1)*10+#l[y]:match"#-%*") ``` **Ungolfed** ``` l={} i=1 while(l[i-1]~="")do l[i]=io.read() o=l[i]:find"%*" --find "*", and record: x=o or x --position and y=o and i or y --current floor i=i+1 end print(#l[i-2]:sub(1,x):gsub("%S+%s*","#")*100 --[[Take last string of list, and then take the substring up until the asterisk. Substitute any substrings that include nonspace characters (%S+) followed by a minimum of 0 space characters (%s*) with one character (in this code snippet I chose # for no particular reason.) Then take the length of this string, with the # operator. The %S+%s* regex and gsub do the bulk of the magic. ]] +(i-y-1)*10 --[[Total number of lines minus '*' floor minus one. ]] +#l[y]:match"#-%*") --[[Find the substring on the asterisk floor with '#' symbols preceding an asterisk. ]] ``` [Answer] ## CoffeeScript, 110 bytes & JavaScript, 121 bytes ``` (s)->s.split('\n').reverse().map((f,g)->f.split(' ').map((h,i)->r=h.indexOf('*');s=''+i+g+r if r>-1));111+1*s ``` ## Readable ``` (s)-> s.split '\n' .reverse() .map (f,fi)-> f.split(' ') .map (h,hi)-> ri = h.indexOf('*') s = ''+hi+fi+ri if ri>-1 111+1*s ``` Basically same thing in Javascript: ``` (s)=>{s.split('\n').reverse().map((f,g)=>f.split(' ').map((h,i)=>{r=h.indexOf('*');r>-1?s=''+i+g+r:''}));return 111+1*s} ``` [Answer] ## Java, 231 Bytes ``` String a(String a){String[]b=a.split("\n");int i=0,c=b.length,m;String x,k=" ";for(;i<c;i++){x=b[c-1].substring(0,b[i].indexOf("*")+1);m=x.length();a=m>0?""+(m-x.replace(k+k,k).length()+1)+(c-i)+(m-x.lastIndexOf(k)-1):a;}return a;} ``` De-Golfed ``` String a(String a) { String[] b = a.split("\n"); // Split the input into floor lines int i = 0, c = b.length, m; // i=floor line counter c= number of floor lines String x, k = " "; for (; i < c; i++) { // Loop through floor lines x = b[c - 1].substring(0, b[i].indexOf("*") + 1); // x = part of bottom floor line up to '*' position in current line (Empty string when no '*') m = x.length(); // m = length of floor line part a = m > 0 ? "" + (m - x.replace(k + k, k).length() + 1) // if m>0 ('*' is on this line) set a=building no+floor no+room no. building no calculated by replacing double space in x with single space and compare length to x (+1) + (c - i) // floor number is total floor lines (c) - floor line loop counter (i) + (m - x.lastIndexOf(k) - 1) : a; // room number is m ('*' position in x) - position of last space in x (-1) } return a; // return the result at the end. } ``` [Answer] # Powershell, 154 bytes ``` param($s)filter s{$s|sls $_ -a|% M*|% Le*}(($s-split' ')[-1]|% s*g 0('(?m)^.*\*'|s)|sls '^| '-a|% M*).Count,('(?ms)(?<=\*.*)$'|s).Count,('#*\*'|s)-join'' ``` Less golfed test script: ``` $f = { param($s) filter s{ $s|sls $_ -AllMatches|% Matches|% Length } # select an array of lengths of all matches of the string $s by pattern $_ $hpos='(?m)^.*\*'|s # horizontal position of the room in the source string $basement=($s-split"`n")[-1] # basement floor string $building=($basement|% substring 0 $hpos|sls '^| ' -AllMatches|% Matches).Count # truncate the basement to the position of the room # and count all double spaces or a 'start of string' $floor=('(?ms)(?<=\*.*)$'|s).Count # count all 'end of line' after the room $room='#*\*'|s # count all #, preceding the room, and room itself $building,$floor,$room-join'' } @( ,(@" * "@, 111) ,(@" # # * # # "@,311) ,(@" ##### ##### ####* ##### ##### "@, 135) ,(@" ##### ##### ###### ##### ###### # # # ##### # # # ###### * "@, 911) ,(@" # # # # # ## # # ## ### # # ## ### ##### # # ## ### ##*## ######## # # ## ### ##### ######## "@, 523) ,(@" # * # # # # # # ######### # # "@, 281) ,(@" ########* ######### ######### ######### ######### ######### ######### ######### # # # # # # # # ######### "@, 999) ) | % { $n,$expected = $_ $result = &$f $n "$($result-eq$expected): $result" } ``` Output: ``` True: 111 True: 311 True: 135 True: 911 True: 523 True: 281 True: 999 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` |€SζJðмõ¡εεR'*k>]DOZ©k>;ò®«sĀ€ƶ˜à« ``` Zip with string-lists is currently bugged. `€SζJ` could have been just `ζ` in the old Python legacy version of 05AB1E, but for some reason doesn't work in the Elixir rewrite version anymore. [Try it online](https://tio.run/##yy9OTMpM/f@/5lHTmuBz27wOb7iw5/DWQwvPbT23NUhdK9su1sU/6tDKbDvrw5sOrTu0uvhIA1DlsW2n5xxecGj1//8KCgrKyspcysgUiIAwtUAEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@f9R05rgc9u8Dm@4sOfw1kMLz209tzVIXSvbrrbWxT/q0MpsO@vDmw6tO7S6@EgDUOmxbafnHF5waPV/nf/R0UpaSrE6CtFKygoKQKQFJpWhQiCgpINCa6HxoUoVYAAmhyqgoIDKJ04FxEnKcBWofJBroe6EqkVoQWaClaPzEQ7FENaCy@LWh6QA1fsQVyBxtVC5ytTlwlyhjBxtCjgATC2ak7CqUR7GalBSEkaqQo5ThHokBlLyUtYCc2JjAQ). **Explanation:** ``` | # Take the input split by newlines # i.e. " ###\n# ###\n# ### ##\n# ##* ##" # → [" ###","# ###","# ### ##","# ##* ##"] €S # Convert each to a list of characters ζ # Zip, swapping rows and column J # Join them together to a string again # → [" ###"," "," ","####","####","###*"," "," "," ##"," ##"] ðм # Remove all spaces # → ["###","","","####","####","###*","","","##","##"] õ¡ # Split on empty strings # → [["###"],[],["####","####","###*"],[],["##","##"]] ε # Map each building to: ε # Map each column of the building to: R # Reverse the column '*k '# Get the 0-indexed index of "*" > # Increase it by 1 to make it 1-indexed ] # Close both maps # → [[0],[],[0,0,1],[],[0,0]] D # Duplicate the resulting list O # Sum each building # → [0,0,1,0,0] Z # Get the max (without popping) # → 1 © # Store this max in the register (without popping) k> # Get the index (+ 1) of this max in the sum-list # → 3 ; # Halve it # → 1.5 ò # Round it up to the nearest integer (bankers rounding) # → 2 ® # Retrieve the value from the register again « # Merge the two digits together # → 21 s # Swap so the duplicate list is at the top again Ā # Trutify (0 remains 0, every other integer becomes 1) # → [[0],[],[0,0,1],[],[0,0]] € # For each building: ƶ # Multiply the integer with the 1-indexed index # → [[0],[],[0,0,3],[],[0,0]] ˜ # Flatten the list # → [0,0,0,3,0,0] à # Pop the list, and get the max # → 3 « # Merge it with the other two digits (and output implicitly) # → 213 ``` [Answer] # [Dart](https://www.dartlang.org/), 165 bytes ``` F(List s)=>s.indexWhere((a)=>a.contains('*'));f(String s){var b=s.split('\n'),v=F(b),c=b[v].split(' '),w=F(c),x=c[w].indexOf('*')+1;return '${w+1}${b.length-v}$x';} ``` [Try it online!](https://tio.run/##hZFNa4NAEIbv/orFCPsRI6jJocjmmFOhhx56SHNQo4mQbsO6VUH87XZ0tcYmpYvovvPMOzMyx1Cqtt2R5yxXKKd8mzuZOCbV2zmRCSEhREIn/hQqzEROMMOUBil5VTITJ8ivi1CiiOdOfr1kiuB3gald8B2JqB3zaF8cRoIQkBJITO2Kx/vyoBu9pH3VpRvIRH1JgbBVl0u3serIuSTipM6rorEqHDRt10t5iCPTNBfdMaY3u7kvgAeG0af7HAQaj86ZS4Tm@n8OoeHRfK7hy24GWHcDaM9onC69Za7GIe@C7If95Zmw7v8BOyO0hv@5wrpgB1adEpOZtEGrLXJdF9PgF9RlmS4@JPoPEpU3FPE398zX7OmRb63ZxvM71rTf "Dart – Try It Online") ]
[Question] [ A brick wall is a rectangle made of horizontal 1-by-n bricks stacked into rows. Here's a wall of height 4 and width 8, with brick sizes shown on the right. ``` [______][______] 4 4 [__][____][__][] 2 3 2 1 [][______][____] 1 4 3 [____][______][] 3 4 1 ``` This wall is unsteady because it has a *fault*, a place where two vertical cracks between bricks line up, shown below with parens in the surrounding bricks. ``` [______][______] [__][____)(__][] [][______)(____] [____][______][] ``` But, the cracks bordering the size-1 bricks on the right don't form a fault because they are separated by a row. Write code that finds and displays a steady wall constructed out of bricks of specified sizes. Fewest bytes wins. **Input** A non-empty list of brick sizes (positive numbers) and a height that's at least 2. This list may be sorted if you wish. You may alternatively take in a count of bricks of each size. **Output** A picture of a steady rectangular wall of the required height that uses all the bricks given. Print it or return it as a string with newlines. Draw a brick of size n as 2n characters, underscores surrounded by brackets. ``` 1: [] 2: [__] 3: [____] 4: [______] ... ``` The input is guaranteed to have at least one solution. If there's multiple, you should still only draw one wall. There's no time restriction; use as much brute force as you want. Your algorithm should in theory work on inputs of any size. **Test cases:** There are multiple solutions, so your outputs might be different. ``` >> [1, 1, 2, 2], 2 [][__] [__][] >> [1, 1, 1, 2, 2, 2, 2, 3], 2 [__][____][__] [][__][][__][] >> [1, 1, 2, 2, 3, 3, 3, 3], 3 [][__][____] [__][____][] [____][____] >> [1, 2, 3, 4, 5, 6, 7, 8, 9], 5 [][______________] [__][____________] [________________] [____][__________] [______][________] >> [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 5 [][__][__] [__][__][] [][__][__] [__][__][] [][__][__] ``` [Answer] # Perl, 166 ~~170 194~~ A perfect task for a language created by Larry Wall. ``` #!perl -pa $_=(1x($x=2/($y=pop@F)*map{1..$_}@F)." ")x$y;sub f{my$l=$_;$-|=!@_;for$=(@_){$Z=__ x~-$=;$f=0;s/(11){$=}/[$Z]/&!/\]..{$x}\[/s&&f(grep$=ne$_||$f++,@_);$-or$_=$l}}f@F ``` Brute force, but quite fast on the test cases (<1s). Usage: ``` $ perl ~/wall.pl <<<"1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 5" [][__][__] [__][__][] [][__][__] [__][__][] [][__][__] ``` Test [me](http://ideone.com/uCUGa8). [Answer] # CJam, ~~94 92~~ 82 bytes This is the 92 bytes version. 82 byte version follows. ``` l~1$,:L,:)m*{1bL=},\e!\m*{~W<{/(\e_}%}%{::+)-!},{{_,,\f<1fb}%2ew{:&,(},!}={{(2*'_*'[\']}/N}/ ``` This partitions the bricks into every possible way and take only the one which is valid. Pretty brute force for now but still runs the last test case in about 10 seconds on the [Java Interpreter](https://sourceforge.net/p/cjam/wiki/Home/) on my machine. **Explanation**: The code is split into 5 parts: 1) Given an array of length `L`, how all can we partition it into `H` parts. ``` l~1$,:L,:)m*{1bL=}, l~ e# Read the input as string and evaluate it. `$,:L e# Copy the array and take its length. Store that in L ,:) e# Get an array of 1 to L m* e# Cartesian power of array 1 to L of size H (height of wall) {1bL=}, e# Take only those parts whose sum is L ``` After this, we have all possible ways of splitting up our input array into H brick layers. 2) Get all permutations of the input array and then further get all partitions for all permutations ``` \e!\m*{~W<{/(\e_}%}% \e! e# Put the input array on top of stack and get all its permutations \m* e# Put the all possible partition array on top and to cartesian e# product of the two permutations. At this point, every e# permutation of the input array is linked up with every e# permutation of splitting L sized array into H parts { }% e# Run each permutation pair through this ~W< e# Unwrap and remove the last part from the partition permutation { }% e# For each part of parts permutation array / e# Split the input array permutation into size of that part (\ e# Take out the first part and put the rest of the parts on top e_ e# Flatten the rest of the parts so that in next loop, they can be e# split into next part length ``` After this, we have all possible layouts of the input bricks into an `H` layers brick wall. 3) Filter out only those layouts whose brick lengths are same ``` {::+)-!}, { }, e# Filter all brick layouts on this condition ::+ e# Add up brick sizes in each layer )-! e# This checks if the array contains all same lengths. ``` After the end of this filter, all remaining layouts would be perfect rectangles. 4) Take out the first brick layout which matches the stability criteria ``` {{_,,\f<1fb}%2ew{:&,(},!}= { }= e# Choose the first array element that leaves truthy on stack { }% e# For each brick layer _,, e# Create an array of 0 to layer length - 1 \f< e# Get all sublists starting at 0 and ending at 0 e# through length - 1 1fb e# Get sum of each sub list. This gives us the cumulative e# length of each brick crack except for the last one 2ew e# Pair up crack lengths for every adjacent layer { }, e# Filter layer pairs :& e# See if any cumulative crack length is same in any two e# adjacent layers. This means that the layout is unstable ,( e# make sure that length of union'd crack lengths is greater e# than 1. 1 because 0 will always be there. ! e# If any layer is filtered through this filter, e# it means that the layer is unstable. Thus negation ``` After this step, we simply have to print the layout 5) Print the layout ``` {{(2*'_*'[\']}/N}/ { }/ e# For each brick layer { }/ e# For each brick (2*'_* e# Get the (brick size - 1) * 2 underscores '[\'] e# Surround with [] N e# Newline after each layer ``` [Try it online here](http://cjam.aditsu.net/#code=l~1%24%2C%3AL%2C%3A)m*%7B1bL%3D%7D%2C%5Ce!%5Cm*%7B~W%3C%7B%2F(%5Ce_%7D%25%7D%25%7B%3A%3A%2B)-!%7D%2C%7B%7B_%2C%2C%5Cf%3C1fb%7D%252ew%7B%3A%26%2C(%7D%2C!%7D%3D%7B%7B(2*'_*'%5B%5C'%5D%7D%2FN%7D%2F&input=%5B1%201%202%202%203%203%203%203%5D%203) --- # 82 bytes ``` l~:H;{e_mrH({H-X$,+(mr)/(\e_}%_::+)-X${_,,\f<1fb}%2ew{:&,(},+,}g{{(2*'_*'[\']}/N}/ ``` This is almost similar to the 92 byte version, except that it has a touch of randomness. If you have read the explanation for the 92 byte version, then in the 82 byte version, parts 3, 4 and 5 are exactly same, while instead of iterating over all permutations from part 1 and 2, this version simply randomly generates one of the permutation at a time, tests it using part 3 and 4, and then restarts the process if the tests of part 3 and 4 fail. This prints the results very quickly for the first 3 test cases. The height = 5 test case is yet to give an output on my computer. **Explanation of the difference** ``` l~:H;{e_mrH({H-X$,+(mr)/(\e_}%_::+)-X${_,,\f<1fb}%2ew{:&,(},+,}g l~:H; e# Eval the input and store the height in H { ... }g e# A do-while loop to iterate until a solution is found e_mr e# Flatten the array and shuffle it. H({ }% e# This is the random partition generation loop e# Run the loop height - 1 times to get height parts H-X$,+( e# While generating a random size of this partition, we e# have to make sure that the remaining parts get at least e# 1 brick. Thus, this calculation mr) e# Get a random size. Make sure its at least 1 /(\e_ e# Similar to 92's part 2. Split, pop, swap and flatten _::+)- e# 92's part 3. Copy and see if all elements are same X${_,,\f<1fb}%2ew{:&,(}, e# 92's part 4. Copy and see if layers are stable +, e# Both part 3 and 4 return empty array if e# the layout is desirable. join the two arrays and e# take length. If length is 0, stop the do-while ``` *The idea for this version was given by randomra (Get it ?)* [Try this one online](http://cjam.aditsu.net/#code=l~%3AH%3B%7Be_mrH(%7BH-X%24%2C%2B(mr)%2F(%5Ce_%7D%25_%3A%3A%2B)-X%24%7B_%2C%2C%5Cf%3C1fb%7D%252ew%7B%3A%26%2C(%7D%2C%2B%2C%7Dg%7B%7B(2*'_*'%5B%5C'%5D%7D%2FN%7D%2F&input=%5B1%201%202%202%203%203%203%203%5D%203) [Answer] # Python 2, ~~680~~ ~~670~~ 660 bytes I don't know why I insist on having these super long "golfs"... but anyway, here you go. ``` M,L,R,N=map,len,range,None exec"J=@:M(''.join,x);B=@:'['+'_'*2*~-x+']';K=@:M(B,x);W=@:J(M(K,x));C=@:set(M(sum,[x[:i]for i in R(L(x))]))-{0};T=@,w:w[x:]+w[:x]\ndef F(i):f=filter(@:i[x-1]&i[x],R(1,L(i)));return f and f[0]".replace('@','lambda x') def P(e,x,i,w,h): for j in[-~_%h for _ in R(i-1,h+i-2)]: for s in R(w): if not e&C(T(s,x[j])):return j,s return N,N def b(l,h): w,d=[[]for _ in R(h)],2*sum(l)/h for _ in l[::-1]:q=M(L,W(w));w[[q.index(i)for i in sorted(q)if i+L(B(_))<=d][-1]]+=_, g=M(C,w);i=F(g) while i: e=g[i-1];j,s=P(e,w,i,d,h) if j!=N:w[j]=T(s,w[j]);w[i],w[j]=w[j],w[i];g=M(C,w);i=F(g) else:b(T(-1,l),h);return print'\n'.join(W(w)) ``` This requires the output in sorted ascending order, and is called via `b(brick_sizes, height)`. Test cases: ``` >>> tests = [([1, 1, 2, 2], 2),([1, 1, 1, 2, 2, 2, 2, 3], 2), ([1, 1, 2, 2, 3, 3, 3, 3], 3), ([1, 2, 3, 4, 5, 6, 7, 8, 9], 5), ([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 5)] >>> for t in tests: ... b(*t); print ... [__][] [][__] [____][__][__] [][][__][__][] [____][____] [__][__][][] [____][____] [________________] [______________][] [____________][__] [__________][____] [________][______] [__][__][] [][__][__] [__][__][] [][__][__] [__][__][] ``` The way this works is: 1. Assign the bricks (longest->shortest) to layers, trying to fill each layer before moving to the next. 2. Whenever adjacent layers are unstable, try swapping layers and shifting bricks until you find something that works. 3. If nothing works, move the longest brick to the front of the sizes list and recurse. [Answer] # Haskell, 262 bytes ``` import Data.List c=concat n=init.scanl1(+) 1%l=[[[l]]] n%l=[map(h:)(c$(n-1)%t)|(h,t)<-map(`splitAt`l)[1..length l]] v[x]=1<2 v(x:y:z)=sum x==sum y&&n x==n x\\n y&&v(y:z) l#n=unlines$map(>>=(\b->'[':replicate(2*b-2)'_'++"]"))$head$filter v$c.(n%)=<<permutations l ``` Example usage: ``` *Main> putStr $ [1, 2, 3, 4, 5, 6, 7, 8, 9] # 5 [______][________] [__________][____] [____________][__] [][______________] [________________] *Main> putStr $ [1, 1, 2, 2, 3, 3, 3, 3] # 3 [____][____] [__][__][][] [____][____] ``` How it works: the main function `#` takes a list `l` (list of bricks) and a number `h` (height) and splits all permutations of `l` into `h` sublists at all possible positions (via function `%`, e.g. `2%[1,2,3,4]` -> `[ [[1],[2,3]] , [[1,2],[3]] , [[1,2,3],[]] ]`) . It keeps those where two consecutive elements have the same sum (i.e. same length in bricks) and the lists of subtotals don't have common elements (i.e. cracks don't line up, function `v`). Take the first list that fits and build a string of bricks. [Answer] # JavaScript (ES6) 222 ~~232 265 279 319~~ ~~Still to be golfed.~~ This one find all the solutions, output just the last found, and it's quite fast. Run snippet in Firefox to test ``` f=(n,h,b=[],s=0)=> (R=(z,l,p,k,t)=> z?b.map((v,a)=> v&&k.indexOf(v=t+a)<0&v<=s&&( --b[a],h=l+`[${'__'.repeat(a-1)}]`, v-s?R(z,h,[...p,v],k,v):R(z-1,h+'\n',[],p,0), ++b[a] )) :n=l )(h,'',[],[],0,n.map(n=>(b[n]=-~b[n],s+=n)),s/=h)&&n // Test suite out=x=>OUT.innerHTML=OUT.innerHTML+x+'\n' ;[ [[1, 1, 2, 2], 2], [[1, 1, 1, 2, 2, 2, 2, 3], 2], [[1, 1, 2, 2, 3, 3, 3, 3], 3] ,[[1, 2, 3, 4, 5, 6, 7, 8, 9], 5], [[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 5]] .forEach(([a,b])=>out(a+' '+b+'\n'+f(a,b))) ``` ``` <pre id=OUT></pre> ``` **Ungolfed** And explained ``` function f(n, h) { var b=[], s=0, result // in golfed version will re-use n for result variable n.forEach(function (n) { b[n] = -~b[n] // group equal input numbers in buckets s+=n // calc sum of input numbers }); // example of buckets: input 1,1,4,1,5,4 -> b[1]=3,b[4]=2,b[5]=1 s /= h // total sum / height => sum expected for each brick layer // recursive scan function function R(z, // layer count, from h downto 1 l, // output so far p, // current layer partial sums array, mark intervals between bricks k, // prev layer parial sums, checked to avoid faulds t // current partial sum ) { if (z > 0) { // still building b.forEach( function (v,a) { // a:number from input list, v: repeat count var w, m // locals (in golfed version, reuse other variables avoid defining locals) w = t + a; // increased running total for current layer if (v != 0 // repeat count still > 0 && k.indexOf(w) < 0 // running total not found on list in prev layer (no fault) && w <= s) // current layer length not exceeded { --b[a]; // decrease repeat count, number used one more time m = l+"["+ '__'.repeat(a-1) + "]"; // new output with a brick added // l is not changed, it will be used again in this loop if (w == s) { // layer complete, go to next (if any) // recurse, new layer, add newline to output, p goes in k, and t start at 0 again R(z-1, m+'\n', [], p, 0); } else { // layer still to complete // recurse, same layer, m goes in l, add current sum to array p R(z, m, [...p,w], k, w); } ++b[a]; // restore value of repeat count for current loop } }) } else { // z == 0, all layers Ok, solution found, save in result and go on to next result = l; } } R(h,'',[],[],0); return result; // this is the last solution found } ``` [Answer] # Python 2, ~~528~~, ~~417~~, ~~393~~, 381 Very long, bruteforce solution. It works but that's about it, the universe may end before getting the result for the last test case. ``` exec u"from itertools import*;m=map;g=@w,n:([[w]],[[w[:i]]+s#i?range(1,len(w))#s?g(w[i:],n-1)])[n>1];r=@x:set(m(sum,[x[:i]#i?range(1,len(x))]));f=@w:1-all(m(@(x,y):not x&y,zip(m(r,w[:-1]),m(r,w[1:]))));a=@s,h:['\\n'.join([''.join(['[%s]'%(' '*(s-1)*2)#s?r])#r?o])#p?permutations(s)#o?g(p,h)if len(set([sum(r)#r?o]))<2 and~-f(o)][0]".translate({64:u"lambda ",35:u" for ",63:u" in "}) ``` **a** is the main function: ``` >> a([1, 1, 2, 2], 2) '[][ ]\n[ ][]' ``` [Answer] ## Python 2, grid method (290 chars) ``` x,h=input() from itertools import * w = sum(x)*2/h for p in permutations(x): bricks = ''.join('[' + '_'*(2*n-2) + ']' for n in p) cols = map(''.join,zip(*zip(*[iter(bricks)]*w))) if all(c=='[' for c in cols[0]) and all(c==']' for c in cols[-1]) and not any(']]' in col or '[[' in col for col in cols[1:-1]): print('\n'.join(map(''.join,zip(*cols)))) print() ``` The method here is you transpose the grid and look for a `[[` or `]]` anywhere in the columns. You also test that all the bricks on the left and right sides of the wall line up: the cute thing here is to test that all elements of a string are the same: `'[[[[[['.strip('[')==''` --- mini version of above: ``` x,h=input() from itertools import* w=sum(x)*2/h z=zip j=''.join for p in permutations(x): C=map(j,z(*z(*[iter(j('['+'_'*(2*n-2)+']'for n in p))]*w))) if C[0].strip('[')==''and C[-1].strip(']')==''and not any(']]'in c or '[['in c for c in C[1:-1]): print('\n'.join(map(j,z(*C)))) break ``` --- This could probably be done more easily in a matrix-manipulation language. ...or abuse of regexes, which lets us combine the "blocks align on ends" condition with the "no cracks" condition: Say the width of the wall was w=6. The locations of the substring "[.....[", and "].....]" must be exactly the set {0,w-1,w,2w-1,2w,3w-1,...}. Not-existence at those points means the bricks 'linewrap' like so: ``` v [][__][_ ___][__] ^ ``` Existence NOT at those points means there is an unsteady 'crack' in the wall: ``` vv [][__][] [ ][] ^^ ``` Therefore we reduce the problem to set equivalence, where the sets in questions are the indices of a regular expression match. ``` # assume input is x and height is h from itertools import * import re w=sum(x)*2/h STACKED_BRACKET_RE = r'(?=\[.{%i}\[|\].{%i}\])'%(w-1,w-1) # ]....] or [....[ STRING_CHUNK_RE = '.{%i}'%w # chunk a string with a regex! bracketGoal = set().union(*[(x*w,x*w+w-1) for x in range(h-1)]) # expected match locations for p in permutations(x): string = ''.join('['+'_'*(2*n-2)+']'for n in p) bracketPositions = {m.start() for m in re.finditer(STACKED_BRACKET_RE,string)} print(string, bracketPositions, bracketGoal, STACKED_BRACKET_RE) #debug if bracketPositions==bracketGoal: break print('\n'.join(re.findall(STRING_CHUNK_RE,string))) ``` --- ## Python, regexp method (304 chars): ``` from itertools import* import re x,h=input() w=sum(x)*2/h for p in permutations(x): s=''.join('['+'_'*(2*n-2)+']'for n in p) if {m.start()for m in re.finditer(r'(?=\[.{%i}\[|\].{%i}\])'%(w-1,w-1),s)}==set().union(*[(x*w,x*w+w-1) for x in range(h-1)]): break print('\n'.join(re.findall('.{%i}'%w,s))) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 266 bytes ``` param($b,$h)$w=($b|%{'['+'__'*--$_+']'})+," "*--$h|sort;filter p{if($k=--$_){$k|p;0..($k-1)|%{$j=($_,0)[$_%2];$w[$j],$w[$k]=$w[$k,$j] $k|p}}else{,(-join$w-split" ")}}$w.Length|p|?{!(($x=($a=$_)|% Le*|gu).Rank-or-join(1..($x-2)|%{$a|% Ch* $_})-match']]')}|select -f 1 ``` [Try it online!](https://tio.run/##jVRdj6IwFH3vr7jr1IVqIaP7HWPWZF5nX3bnjRAWnQooAik1mgC/3bnlQ8HZhyWXtL0959xTaJulJyHzUMTxhW5hCcUl86V/MOma05DR0xJ75bgwHGNqeJ4xsSzqTQ3XqNiUj8hIj8MyT6VabKNYCQlZEW1Nul9qICvovswWj7aNGWvGUIjuUNHjj8yh3njuLujJoTuX62bvLuuGY4JoYlWJOBcFN61dGiX0ZOVZHCmsyqqKnuxnkQQqLLPyZ/HBNOkZhf0lFi3H8CwmZXBk9m8/2VuprPnmTNs4W/Paho@op3AC1KuYdfDVJjRc12BVmYtYbBRYW5hdKkJWJiHcBHPGAWOOwXRDVgZxPM91XOK4ukOMFde5ZtBOGSvWZ7cCXXy6KdWshuS07OYdKPdQpJnrEh3mSmpcdJKdmx6mE78rfee4NXoNppuB4@tqm7I9YwNbg4I323dgrP0AL6GAtTwqAdtUbgT4cZDKSIUHCP0c1kIkII9JEiWBBoBKU4jTJEBm67tx/JnDFw5fOXzj8J3DD6bHCEI/D@A0NW@Pq5OdlbvkP5FDbA95S@tku6bBHni/E@7jvdfmc1096g/93zO1BwYljKEggA9dy2ifc6ChiIJQYUecM9z04hUvAOqRGmT@En5@lMJ6Sg8HP3ltuTVfivwYKwR/xDujUevEalDF7Jf0j5L4j0zWyrWk@iiO/iYjZuGR7uqSniypLm8 "PowerShell – Try It Online") This script is brute force algorithm: 1. converts numbers to related strings [], [\_\_], [\_\_\_\_], ... 2. adds as many LFs as the height is 3. generates all permutations by [Heap's algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm) 4. checks and PassThru a valid wall only 5. returns first only wall What can be improved: generate permutations for numbers, not strings. build a string representation in final. Unrolled: ``` param($briks,$height) $wall = ($briks|%{'['+'__'*--$_+']'}) + # string [], [__], ... related to numbers ,"`n"*--$height | # as many LF as the height sort # sort briks and LFs # Heap's algorithm generates all possible permutations of $_ objects # https://en.wikipedia.org/wiki/Heap%27s_algorithm filter get-permutation{ if($k=--$_){ $k|get-permutation 0..($k-1)|%{ $j=($_,0)[$_%2] $wall[$j],$wall[$k]=$wall[$k,$j] $k|get-permutation } } else{ ,(-join$wall -split "`n") # return an array of strings represent a wall } } $wall.Length|get-permutation|where{ # generates all permutations, then check and PassThru a valid wall only !( # not ($x=($a=$_)|% Length|Get-Unique).Rank -or # length of all wall rows are different or -join(1..($x-2)|%{$a|% Chars $_})-match']]' # the wall is not steady ) }|select -First 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œIδ.Œ€`ʒOË}.ΔεηO¨}üåà≠}<·'_×€€…[ÿ]J» ``` Slow brute-force approach (already times out for the last test case on TIO), but it works. First input is the list of brick sizes and second input is the height integer. [Try it online](https://tio.run/##yy9OTMpM/f//6GTPc1v0jk561LQm4dQk/8PdtXrnppzbem67/6EVtYf3HF56eMGjzgW1Noe2q8cfng5UBUINy6IP74/1OrT7//9oQx0QNAJD41guYwA) or [verify a few test cases at once](https://tio.run/##yy9OTMpM/W/qpuSZV1BaUmylkFSUmZytW5xZlQrkKNl7utgrKSTmpShkpGamZ5RAhEJ1uJT8S0uAGoB8nf9HJ0ec26J3dNKjpjUJpyb5H@6u1Ts35dzWc9v9D62oPbzn8NLDCx51Lqi1ObRdPf7wdKAqEGpYFn14f6zXod3/dQ5ts/8fbaijAERGQBTLZcQF5UJFYMgYSQoqAkexXMZgKYigiY6CqY6CmY6CuY6ChY6CZSyXKTYzQboA). **Explanation:** First get all possible ways to divide the list of bricks into the height amount of rows (resulting in a list of list of list of integers, which we'll reference to as list of walls for now): ``` œ # Take the powerset of the (implicit) input-list # (this holds a list of all possible ways to order the input-list) I # Using the second height integer, δ # map each inner permutation of the input-list to: .Œ # Get all possible ways to divide the permutation into the height amount of pieces €` # Then flatten once ``` Then we'll filter this list to only keep walls whose rows have an equal width (so we're left with all rectangular walls): ``` ʒ # Filter this list of walls by: O # Take the sum of each inner row Ë # Check if the sums of all the rows are equal } # Close the filter ``` Then we'll search for the first wall which doesn't have any vertical gaps between two adjacent rows: ``` .Δ # Find the first wall which is truthy for: ε # Map each row to: η # Get the prefixes of bricks in this row O # Sum each prefix ¨ # Remove the last (right side of the wall), since those are supposed to line up } # Close the inner map (we now have a list of list of integers, a.k.a. list of gaps) ü # Map over each pair of gaps: å # Check for each gap in the second gaps-list if it's in the first gaps-list à # Take the flattened maximum to check if any is truthy ≠ # And invert that boolean, since we want to find a wall without gaps lining up } # Close the find_first ``` Now we've found our wall. All that's left is to transform it into the desired output-format and print it: ``` < # Decrease each brick-value by 1 · # Then double each '_× '# And convert those integers to that amount of "_" as string € # Then map over each row: € # And each inner brick consisting of "_" …[ÿ] # And surround it by "[" and "]" J # Then join each list of bricks together to form the rows » # And join those rows by newlines to form the wall # (after which this is output implicitly as result) ``` [Answer] # [PHP](https://php.net/), ~~918~~ ~~870~~ 650 bytes ``` [$z,$h]=json_decode($argn);$j=$h-1;$p=array_fill(0,$c=100,[0,array_chunk($z,ceil(count($z)/$h))]);$r=fn($x)=>rand(0,$x);g:foreach($p as&$s){$b=[];for($s[0]=$l=0;$l<$h;$l++){for($m=$k=0;$k<~-count($v=$s[1][$l]);)$b[$l][]=$m+=$v[$k++];$s[0]+=abs(array_sum($z)/$h-$m-$v[$k]);}for($l=0;$l<$j;){if(array_intersect($b[$l]??[],$b[1+$l++]??[]))$s[0]+=9;}}usort($p,fn($a,$b)=>$a[0]<=>$b[0]);if(!$p[0][0]){foreach($p[0][1]as$l){foreach($l as$b)echo'[',str_repeat('_',~-$b*2),']';echo"\n";}die;}for($o=0;$o<99;$o++){$w=&$p[(int)sqrt($r($c*$c-1))][1];$a=&$w[$r($j)];$t=&$a[$i=$r($u=count($a)-1)];if($u){unset($a[$i]);$a=array_values($a);$w[$r($j)][]=$t;}}goto g; ``` [Try it online!](https://tio.run/##TVJhc5swDP0rXU9X7GJu0OZLZrx825/wfDnjOIGE2AxD2o1Lf/oymdLrjkOWHk96kkxXd7dy06GV8IdBrcQxeLfdWeN3loDuD45yOAqos4JDJ3Tf69/bfdO2JGdgRJHnTObsHTb16E4E6xjbtMT40Q0Y0a9QU6qwTC/2jsArFd977XaxwCvlh29731ttagLdnQ4PEOgElZCKI04gyFwJaEXOoS2hRpumdJo/nQWcIn4q37JF7CIwoVASWtSjUEVHYv45FXCRcEpTxeeSqdBVIO9th/G8tJnBOZt5mH2dNT6Ej5xOzX5JaNxg@2ANCs4Km41UDN0ijd3NIaWLzJpfr2PwPXI7FsfXyMQNgMbPJZ4VnpRj7S/QoRuj6XMjESmUDtD@h7a4JyxiTe0TmbAw9NvedlYPJNkm7C2D6vGJskQlPFLuf7p7ft01dhnJx5F8uV6jjbuEF/GAQgSnouFXbBRJ5hFMVuC1oToHjYwXGfEjxXDAUEtoRERGsexeU0xQcRIY6TS6YCOItHj1evlzLrodbYhk/lkx3tCAezr4wd8d@O0m5Yqt2BN7xrfAZ4XeM9pCsZX667uh8S7csh//AA "PHP – Try It Online") ## Ungolfed The idea is to use a hill climbing approach. A population of walls is set up and each wall is scored. There are penalties for a wall's row of bricks not matching the expected width and for bricks lining up on consecutive rows. The scores are then ordered and a mutation operation applied favouring higher (worse) scoring walls. Scoring and mutation are applied in succesive rounds until a solution is found. Solutions are usually found in under a second - except for the last test case, so it's quick (although bloaty). ``` [$brick_sizes,$height]=json_decode($argn); $width = array_sum($brick_sizes)/$height; $walls=[]; $walls[0]=array_chunk($brick_sizes,ceil(count($brick_sizes)/$height)); $population_count = 100; // Clone default wall and set up initial population for ($wall_index=1;$wall_index<$population_count;$wall_index++) { $walls[$wall_index] = $walls[0]; } $iteration = 0; do { // score population $scores = array_fill(0,$population_count, [0,0]); foreach ($walls as $wall_index => $wall) { foreach ($wall as $level) { $scores[$wall_index][0] += abs($width - array_sum($level)); $scores[$wall_index][1] = $walls[$wall_index]; } // Score alignment of bricks with penalty $brick_positions=[]; for ($level=0;$level<$height;$level++) { $running_sum=0; for ($brick_index=0;$brick_index<(count($wall[$level])-1);$brick_index++) { $running_sum += $wall[$level][$brick_index]; $brick_positions[$level][] = $running_sum; } } for ($level=0;$level<($height-1);$level++) { if (array_intersect($brick_positions[$level]??[],$brick_positions[$level+1]??[])) { $scores[$wall_index][0] += 10; } } } // sort score by best fit first usort($scores, function ($a, $b) { return $a[0] <=> $b[0]; }); //echo $iteration,':',$scores[0][0],"\n"; // draw wall and exit if ($scores[0][0] == 0) { foreach ($scores[0][1] as $level){ foreach ($level as $brick){ echo '['.str_repeat('_',2*($brick-1)).']'; } echo "\n"; } die; } // sort population by score $walls = array_map(function($m){return $m[1];},$scores); // randomise bricks in population for ($rando = 0; $rando < 100; $rando++) { $wall_index = (int)sqrt(rand(0, $population_count*$population_count - 1)); $level = []; $index = []; for ($do = 0; $do <= 1; $do++) { $level[$do] = rand(0, $height - 1); $index[$do] = rand(0, count($walls[$wall_index][$level[$do]]) - 1); } $temp = $walls[$wall_index][$level[0]][$index[0]]; if (count($walls[$wall_index][$level[0]])>1) { unset($walls[$wall_index][$level[0]][$index[0]]); $walls[$wall_index][$level[0]]=array_values($walls[$wall_index][$level[0]]); $walls[$wall_index][$level[1]][] = $temp; } } $iteration++; } while (true); ``` [Try it online!](https://tio.run/##jVbbbptAEH2uv2JUWTLUpIE0T8U0D5X6A32kyFrDOmyLF8ouTdMov1539gIs4LRN5GjJzuXMmZmDm7I57@6asoFzuj60LP@2F@wXFcG6pOy@lFnyVdR8X9C8Lqi3Ju099@PVav3ACllCAqRtyeNedCfP9favrbs2JVUlkjQbzmmYJcYvLzv@beIZ5JRVXl53XF6O6Ov0Td10FZEMoWlbRBKFId5cX8PHquYUCnokXSVBZQTCCxBUQtcA40wyUsEYYXWsW/A0tD3jBf2ZRLHztFskc2@3Wx@eVoA/tjbnLkNUQ8Xx6hlxM0lbHQmvEG5RW2eELfK6pS4sHVT/VwxEH1lVeWGwgBRAGgZhhtwoLyyIkry0RQkgAhxYkHwwjz3ypYv2qOgPOrFxAE3KxOpgiwgPwrNzceXOhYljof01TuQw5l6Mrshhf0TKPmvKSMXu@YniENRH0CMj4IEhioZyUsnHwcPOU1MLppgzM@kQABZrEsbmsOun2DyOvR4ith3njN@rQhM1fu6liWhymrnCuM7jrh9zVWlqUmT@VeRPrJZJ54kV95MYqeufxUvnGQ@Dn6bfiTx1dbh3jhd58yxxupgXuGNH8MyUMI5bIWg@bPwC2d1dmgUvXG4jfe1fpOnlaY3CeXXL08qpVW1o3Uq7podHOFAh4cjUpxVS23TKwrNJAzh2PNe7jroZIOsuwpbKruWwJgrOTm3kQYuEzujHfU6alzWMqhFs3m@CvqhQlRK8/sJfx6tXPcaiJQ@j5tGfzCBTZE/8IEEBuiwAoxnu4ygET/Phtub6Vtvp/vjLLugiNunmrZDtvqUNJdLb7DfBzRvbcBwT/@0m27zUkSGIKXZpUDAaX2rWKJOqY7owR6sHVT2Rxuub5a1P/lPfnRNSED/3jI9tgRbZrU9M0F5wGJ9Lt1kMbajFHux5p99U9mm6FhORBg/3whffcaKUKao@LGT/zfJFeAWRq7W2PQm4WrfuUywFcACrkOKW6NMF4dNhU7xTmjHgM1uvMczkXmec2zv6N9tRJ37mz@I54rOW9NRcfmf0IcIMjyY7HuPpbver8U8g6Op/iGYsdBy/U3j/nXtKyd/d7PejH6TqqPgXsP@NG2VW4hVr8zWyrI5as90ak9UzPJSsouDJtqN@fD6n6W1wG9wE7/AT4e8tnt7h3ygLbrPfdaPV@Xz16Q8 "PHP – Try It Online") [Answer] ## Matlab (359) ``` function p(V),L=perms(V);x=sum(V);D=find(rem(x./(1:x),1)==0);for z= 2:numel(D-1)for y=1:numel(L),x=L(y,:);i=D(z);b=x;l=numel(x);for j=1:l,for k=j-1:-1:2,m=sum(x(1:k));if mod(m,i),if mod(m,i)<mod(sum(x(1:k-1)),i)||sum(x(1:j))-m==i,b=0;,end,end,end,end,if b,for j=1:l,fprintf('[%.*s]%c',(b(j)-2)+b(j),ones(9)*'_',(mod(sum(x(1:j)),i)<1)*10);end,return,end;end,end ``` ## Input a vector of integers , example: p([1 1 2 2 3]) ## Output the scheme of the wall example: ``` [____] [__][] [][__] ``` ]
[Question] [ I want to try a new type of regex golf challenge, which asks you to solve nontrivial computational tasks with nothing but regex substitution. To make this more possible and less of a chore, you will be allowed to apply several substitutions, one after the other. ## The Challenge We'll start simple: given a string containing two positive integers, as decimal numbers separated by a `,`, produce a string containing their sum, also as as a decimal number. So, very simply ``` 47,987 ``` should turn into ``` 1034 ``` Your answer should work for arbitrary positive integers. ## The Format Every answer should be a *sequence* of substitution steps, each step consisting of a regex and a replacement string. Optionally, for each of those steps in the sequence, you may choose to repeat the substitution until the string stops changing. Here is an example submission (which does *not* solve the above problem): ``` Regex Modifiers Replacement Repeat? \b(\d) g |$1 No |\d <none> 1| Yes \D g <empty> No ``` Given the input `123,456`, this submission would process the input as follows: the first substitution is applied once and yields: ``` |123,|456 ``` Now the second substitution is applied in a loop until the string stops changing: ``` 1|23,|456 11|3,|456 111|,|456 111|,1|56 111|,11|6 111|,111| ``` And lastly, the third substitution is applied once: ``` 111111 ``` Note that the termination criterion for loops is whether the string changes, not whether the regex found a match. (That is, it might also terminate if you find a match but the replacement is identical to the match.) ## Scoring Your primary score will be the number of substitution steps in your submission. *Every **repeated** substitution will count for **10** steps.* So the above example would score `1 + 10 + 1 = 12`. In the (not too unlikely) case of a tie, the secondary score is the sum of the sizes of all steps. For each step add the regex (*without* delimiters), the modifiers and the substitution string. For the above example this would be `(6 + 1 + 3) + (3 + 0 + 2) + (2 + 1 + 0) = 18`. ## Miscellaneous Rules You may use any regex flavour (which you should indicate), but all steps must use the same flavour. Furthermore, you must *not* use any features of the flavour's host language, like replacement callbacks or Perl's `e` modifier, which evaluates Perl code. All manipulation must happen exclusively through regex substitution. Note that it depends on your flavour and modifiers whether each single replacement replaces all occurrences or only a single one. E.g. if you choose the ECMAScript flavour, a single step will by default only replace one occurrence, unless you use the `g` modifier. On the other hand, if you're using the .NET flavour, each step will always replace all occurrences. For languages which have different substitution methods for single and global replacement (e.g. Ruby's `sub` vs. `gsub`), assume that single replacement is the default and treat global replacement like a `g` modifier. ## Testing If your chosen flavour is either .NET or ECMAScript, you can use [Retina](https://github.com/mbuettner/retina) to test your submission (I'm being told, it works on Mono, too). For other flavours, you will probably have to write a small program in the host language which applies the substitutions in order. If you do, please include this test program in your answer. [Answer] # .NET flavor, score:2 ``` Regex Modifiers Replacement Repeat? <empty> <none> 9876543210 No <see below> x <empty> No ``` I'm not bothered to golf it yet, and `x` is just for ignoring whitespaces. It firstly insert `9876543210` at each position, then delete the original characters and the characters those are not the current digit of the sum. The big regex (1346 bytes without whitespaces and comments): ``` # If the length of the left number <= right number, delete every digit on the left. .(?=.*,(?<=^(?<len>.)*,)(?<-len>.)*(?(len)(?!)))| # Do the opposite if it is not the case. .(?<=(?(len)(?!))(?<-len>.)*(?=(?<len>.)*$),.*)| # Remove leading zeros. (?<=(^|,).{9})0| # Delete everything that is not the current digit of the sum. .(?! # For digits in the left part: (?<cur>.){0,9} # cur = the matched digit (?=(.{11})*,) # and find the position before the next digit. (?<first>) # first = true ( # Loop on the less significant digits: (?<cur>){10} # cur += 10 (?<= # cur -= the current digit in this number. ( 0|^| 1(?<-cur>)| 2(?<-cur>){2}| 3(?<-cur>){3}| 4(?<-cur>){4}| 5(?<-cur>){5}| 6(?<-cur>){6}| 7(?<-cur>){7}| 8(?<-cur>){8}| 9(?<-cur>){9} ) .{10} ) (?= (?<pos>.{11})*, # pos = which digit it is. .*$(?<= # cur -= the current digit in the other number. ( 0|,| 1(?<-cur>)| 2(?<-cur>){2}| 3(?<-cur>){3}| 4(?<-cur>){4}| 5(?<-cur>){5}| 6(?<-cur>){6}| 7(?<-cur>){7}| 8(?<-cur>){8}| 9(?<-cur>){9} ) .{10} (?(pos)(?!)) # Assert pos = 0. # Skip pos input digits from the end. # But stop and set pos = 0 if the comma is encountered. ((?<-pos>\d{11})|(?<=(?>(?<-pos>.)*),.{10}))* ) ) (?(first) # If first: (?>((?<-cur>){10})?) # cur -= 10 in case there is no carry. # Assert cur = 0 or 1, and if cur = 1, set cur = 10 as carry. (?(cur)(?<-cur>)(?(cur)(?!))(?<cur>){10}) (?<-first>) # first = false | # Else: # cur is 10 or 20 at the beginning of an iteration. # It must be 1 to 11 to make the equation satisfiable. (?<-cur>) # cur -= 1 (?(cur) # If cur > 0: # cur -= max(cur, 9) (?(cur)(?<-cur>)){9} (?(cur) # If cur > 0: # Assert cur = 1 (was 11) and set cur = 10. (?<-cur>)(?(cur)(?!))(?<cur>){10} | # Else: .*(?=,) # cur was 2 to 10, break from the loop. ) ) # Else cur is 0 (was 1) and do nothing. ) (.{11}|,) # Jump to the next digit. )*(?<=,)(?(cur)(?!)) # End the loop if it is the last digit, and assert cur = 0. | # Do the same to the right part. So the sum will be calculated two times. # Both are truncated to the original length of the number on that side + 1. # Only the sum on the longer side will be preserved in the result. (?<cur>\d){0,9} (?=(\d{11})*$) (?<first>) ( (?<cur>){10} (?<= ( 0|,| 1(?<-cur>)| 2(?<-cur>){2}| 3(?<-cur>){3}| 4(?<-cur>){4}| 5(?<-cur>){5}| 6(?<-cur>){6}| 7(?<-cur>){7}| 8(?<-cur>){8}| 9(?<-cur>){9} ) .{10} ) (?= (?<pos>.{11})*$ (?<= ( 0|^| 1(?<-cur>)| 2(?<-cur>){2}| 3(?<-cur>){3}| 4(?<-cur>){4}| 5(?<-cur>){5}| 6(?<-cur>){6}| 7(?<-cur>){7}| 8(?<-cur>){8}| 9(?<-cur>){9} ) .{10} (?(pos)(?!)) ((?<-pos>\d{11})|(?<=^.{10})(?=(?>(?<-pos>.)*)))* ,.* ) ) (?(first) (?>((?<-cur>){10})?) (?(cur)(?<-cur>)(?(cur)(?!))(?<cur>){10}) (?<-first>) | (?<-cur>) (?(cur) (?(cur)(?<-cur>)){9} (?(cur) (?<-cur>)(?(cur)(?!))(?<cur>){10} | .*$(?<end>) ) ) ) (.{11}|$(?<end>)) )*(?<-end>)(?(cur)(?!)) ) ``` This made me think of the final level of Manufactoria... But I think .NET regex, which is obviously no longer "regular", can solve any problems in PH. And this is just an algorithm in L. [Answer] ### Score: 24 I think this works... ``` Regex Modifiers Replacement Repeat? (?|(\d*)(\d)(,\d*)(\d)|(^,?\d*)(\d)|, |^,) <none> $1$3 $2$4 Yes $ <none> ;111111111234567890 No 0|(?|(;.*)|9(?=.*(1{9}))|8(?=.*(1{8}))|7(?=.*(1{7}))|6(?=.*(1{6}))|5(?=.*(1{5}))|4(?=.*(1{4}))|3(?=.*(111))|2(?=.*(11))) g $1 No 1{10} <none> 1 Yes (?|1{9}(?=.*(9))|1{8}(?=.*(8))|1{7}(?=.*(7))|1{6}(?=.*(6))|1{5}(?=.*(5))|1{4}(?=.*(4))|1{3}(?=.*(3))|1{2}(?=.*(2))|) g $1 No (?!\d)(?=.*(0))| |;.* g $1 No ``` I haven't spent much time golfing the individual regular expressions yet. I will try to post an explanation soon, but it's getting late now. In the meantime, here's the result between each step: ``` '47,987' ' 9 48 77' ' 9 48 77;111111111234567890' ' 111111111 111111111111 11111111111111;111111111234567890' '1 111 1111;111111111234567890' '1 3 4;111111111234567890' '1034' ``` Full perl program: ``` $_ = <>; chomp; do { $old = $_; s/(?|(\d*)(\d)(,\d*)(\d)|(^,?\d*)(\d)|, |^,)/$1$3 $2$4/; } while ($old ne $_); s/$/;111111111234567890/; s/0|(?|(;.*)|9(?=.*(1{9}))|8(?=.*(1{8}))|7(?=.*(1{7}))|6(?=.*(1{6}))|5(?=.*(1{5}))|4(?=.*(1{4}))|3(?=.*(111))|2(?=.*(11)))/$1/g; do { $old = $_; s/ 1{10}/1 /; } while ($old ne $_); s/ (?|1{9}(?=.*(9))|1{8}(?=.*(8))|1{7}(?=.*(7))|1{6}(?=.*(6))|1{5}(?=.*(5))|1{4}(?=.*(4))|1{3}(?=.*(3))|1{2}(?=.*(2))|)/ $1/g; s/ (?!\d)(?=.*(0))| |;.*/$1/g; print "$_\n"; ``` [Answer] ### Any regex flavor, 41 ``` s/0/d/g ... s/9/dxxxxxxxxx/g rep s/xd/dxxxxxxxxxxx/g s/[d,]//g rep s/(^|d)xxxxxxxxxx/xd/g s/(^|d)xxxxxxxxx/9/g ... s/(^|d)x/1/g s/d/0/g ``` Let's try unary. `d` serves for a digit order separator, `x` stores the value. First we unarise each digit, then we squeeze the x10 multipliers to the left, then drop all separators, then back-insert the multipliers, then convert each order back to digits. [Answer] # .NET Regex, 14 Not as good as user23013's solution, but it was fun. None of the replacements have modifiers. The reason for the .NET regex isn't because of balancing groups for once — I just tested with [Retina](https://github.com/mbuettner/retina), which uses .NET, and I also found that the variable length lookbehinds helped a lot. ## Replacement 1 (repeat = no) Regex: ``` \d(?=\d+$)|\d(?=\d+,)|\d(?=,(\d+)$)|(?<=(\d+),\d*)\d$ ``` Replacement ``` 0$1$2 ``` Swap the two numbers, padding to have the same number of leading zeroes. ## Replacement 2 (repeat = no) Regex: ``` (\d+) ``` Replacement: ``` $1 ``` Add a space before each number ## Replacement 3 (repeat = no) ``` $ ``` Replacement: ``` &0 ~00000 ~00101 ~00202 ~00303 ~00404 ~00505 ~00606 ~00707 ~00808 ~00909 ~01001 ~01102 ~01203 ~01304 ~01405 ~01506 ~01607 ~01708 ~01809 ~01910 ~02002 ~02103 ~02204 ~02305 ~02406 ~02507 ~02608 ~02709 ~02810 ~02911 ~03003 ~03104 ~03205 ~03306 ~03407 ~03508 ~03609 ~03710 ~03811 ~03912 ~04004 ~04105 ~04206 ~04307 ~04408 ~04509 ~04610 ~04711 ~04812 ~04913 ~05005 ~05106 ~05207 ~05308 ~05409 ~05510 ~05611 ~05712 ~05813 ~05914 ~06006 ~06107 ~06208 ~06309 ~06410 ~06511 ~06612 ~06713 ~06814 ~06915 ~07007 ~07108 ~07209 ~07310 ~07411 ~07512 ~07613 ~07714 ~07815 ~07916 ~08008 ~08109 ~08210 ~08311 ~08412 ~08513 ~08614 ~08715 ~08816 ~08917 ~09009 ~09110 ~09211 ~09312 ~09413 ~09514 ~09615 ~09716 ~09817 ~09918 ~10001 ~10102 ~10203 ~10304 ~10405 ~10506 ~10607 ~10708 ~10809 ~10910 ~11002 ~11103 ~11204 ~11305 ~11406 ~11507 ~11608 ~11709 ~11810 ~11911 ~12003 ~12104 ~12205 ~12306 ~12407 ~12508 ~12609 ~12710 ~12811 ~12912 ~13004 ~13105 ~13206 ~13307 ~13408 ~13509 ~13610 ~13711 ~13812 ~13913 ~14005 ~14106 ~14207 ~14308 ~14409 ~14510 ~14611 ~14712 ~14813 ~14914 ~15006 ~15107 ~15208 ~15309 ~15410 ~15511 ~15612 ~15713 ~15814 ~15915 ~16007 ~16108 ~16209 ~16310 ~16411 ~16512 ~16613 ~16714 ~16815 ~16916 ~17008 ~17109 ~17210 ~17311 ~17412 ~17513 ~17614 ~17715 ~17816 ~17917 ~18009 ~18110 ~18211 ~18312 ~18413 ~18514 ~18615 ~18716 ~18817 ~18918 ~19010 ~19111 ~19212 ~19313 ~19414 ~19515 ~19616 ~19717 ~19818 ~19919 ``` Add a carry bit (the `&0`) as well as the giant lookup table of `<c> <a> <b> <carry of a+b+c> <last digit of a+b+c>`. ## Replacement 4 (repeat = yes) Regex: ``` (?<=(\d),.*(\d)&)(\d)(?=.*~\3\1\2(.))|(\d)(?=,.*\d&)|(?<=\d,.*)(\d)(?=&)|^(?=.* .*(\d),.*(\d)&(\d).*~\9\7\8.(.)) ``` Replacement: ``` $4$10 ``` Keep taking the last digits of each number, and find their (sum, carry). Put the sum at the start of the string and replace the carry. ## Replacement 5 (repeat = no) Regex: ``` ^0*| .* ``` Replacement: ``` <empty> ``` Clean up. # Example run ``` Repl no. String (input) 1428,57 1 000057,001428 2 000057, 001428 3 000057, 001428&0 <lookup table> 4 5 00005, 00142&1 <lookup table> 4 85 0000, 0014&0 <lookup table> 4 485 000, 001&0 <lookup table> 4 1485 00, 00&0 <lookup table> 4 01485 0, 0&0 <lookup table> 4 001485 , &0 <lookup table> 5 1485 ``` --- (By combining a few of the steps I can get 12, but since it gets pretty messy and won't win anyway I think I'll keep this more elegant version up instead.) [Answer] **Score: ~~50~~ ~~40~~ ~~31~~ 21** Thanks for this excellent challenge. This solution isn't very elegant, but, given the restrictions, I couldn't see any way to handle a digit generically in the output. This solution features capture groups that sometimes don't match and relies on them being empty when that occurs. This works in Perl, though it normally produces a warning. ``` Regex 1: (((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0 Modifiers: g Replacement: <$1$2$3$4$5$6$7$8$9> Repeat: no Regex 2: (.*)<(\d*)>(,.*)<(\d*)>|(.*)<(\d*)>(.*)|(?:(^[^<]*)b(\d*)c)?(b)\d{9}(\d)(\d*)(c) Modifiers: none Replacement: \8\1\5\3b$9$11\2\6\4c\7$10$12$13 Repeat: yes Regexes 3-12: ,?baaaaaaaaac Modifiers: g Replacement: 9 etc. (one for each digit) ``` Full Perl code sample, with explanation and printing of intermediate results: ``` no warnings; use 5.16.0; $_ = '47,987'; #Convert numbers to beans s/(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0/<$1$2$3$4$5$6$7$8$9>/g; say; my $last; #Combine pairs of digits, starting with least significant. do { $last=$_; s/(.*)<(\d*)>(,.*)<(\d*)>|(.*)<(\d*)>(.*)|(?:(^[^<]*)b(\d*)c)?(b)\d{9}(\d)(\d*)(c)/\8\1\5\3b$9$11\2\6\4c\7$10$12$13/; say; } while ($last ne $_); #Convert beans back to numbers. s/,?b\d{9}c/9/g; s/,?b\d{8}c/8/g; s/,?b\d{7}c/7/g; s/,?b\d{6}c/6/g; s/,?b\d{5}c/5/g; s/,?b\d{4}c/4/g; s/,?b\d{3}c/3/g; s/,?b\d{2}c/2/g; s/,?b\d{1}c/1/g; s/,?bc/0/g; say; ``` *Update: I was able to combine two of the looping regexes together, saving 10.* *Update 2: I managed to crack the input digit conversion with a single regex.* *Update 3: I reduced to a single looping regex.* ]
[Question] [ RollerCoaster Tycoon 2's maze is the inspiration for this question. Credit to [Marcel Vos](https://www.youtube.com/watch?v=KVgoy_a_gWI) for thoroughly breaking the classic RCT2 AI. The pathfinding AI in this question is the AI in the latest version of OpenRCT2 at the time of writing, which was updated in response to that video. [![image of RCT2 maze](https://i.stack.imgur.com/iW970.png)](https://i.stack.imgur.com/iW970.png) --- Suppose a guest enters a \$w \times h\$ grid maze with the following strategy in mind: > > After every step I pick a random valid direction except backwards, unless I have no other choice but to go back. > > > We are evil and wish to construct the maze that takes the most amount of time *on average* to solve using the above strategy. --- This is a code-challenge. The winner is the answer that contains a \$100 \times 100\$ maze with the greatest mean solve time using the above strategy. In the case of a tie the earlier poster wins. A \$w \times h\$ maze is a \$w \times h\$ grid of square tiles. It has *two* designated start tiles along the border, connected either horizontally or vertically, and similarly two designated exit squares, along the border, connected either horizontally or vertically. Between each tile there may or may not be a wall (with the exception of the two start and two end tiles, they must be directly connected to their partner). There is always a border of walls around the grid. The guest enters with a 50/50% chance on either start tile, *facing away from the other tile*. Then the guest starts exploring the maze one step at a time. At the start of a step the guest looks to its left, forward and right (relative to its current direction) and checks for walls. It chooses a random new direction with uniform chance from the unobstructed directions. If and only if all other directions are obstructed it chooses to go backwards instead. The guest wanders around as such until it reaches one of the two exit squares, which will cause the guest to immediately exit. The average number of steps it takes for this to happen is your score, the bigger the better. If the start and exit are not connected your maze is invalid and has no score. --- To accurately score mazes I wrote a [judge program](https://gist.github.com/orlp/8214c343cbbace9b6c7a0723e1d24e94) in Python that uses Markov chains to compute your score mathematically. It requires Python 3, `numpy`, `scipy` and `imageio` to run (an optional dependency for a speedup is `scikit-umfpack`). In addition, the judge contains functions to output an image of your maze, as well as a compressed representation of your maze. Please familiarize yourself with the judge program before starting this challenge. **Please include (a link to) a \$100\times 100\$ compressed maze as generated by the judge program in your answer. Your answer will be scored based on this. An answer without a concrete, specific solution maze is invalid.** [Answer] # No dead ends near the entrance, ~~21,477,560~~ 21,485,005 [Try it online!](https://tio.run/##7Vlfj9u4EX/3p2AVXCFlZZ3l3QQXNy56F@SAbVEUufTNNQzaotdMZVKQaK@1uXz2dIakJFKWvTm0RV@6SLI2ORzO//kNU9RqJ8Xt1698X8hSkY3Mc7ZRXIpqZJfEYV/UhFZEFM1SteFFnVQFLSs2tJbkXND8od2qW2ZcNp/WtGKv70ajTU6rivyVPrE/H7IHNhsR@MnYlqxWXHC1WoUVy7cxeeSZ2sVkx/jDTkWGDH@CICDvSkYVqwgle@ADpGpHHviRCXOKUJHZgwl5J2WZgXiKo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ErP5E4tDJYQBw4vn5opnb4q1N86QRtw5rz6w2SxpYdcZXyjYIyrVI@6fyvI0anbqWe@pstO7IM4cgBQ0CjnLsmso0Bnr7byIJBEzwbt1uMOGlDHwq9hGjfNu92kkEXot3nzQKADWIOTjPkctLlblGqtj3b3yLCTVNaShvK8EumLIoiPz4bLFxzEm8@jM7SFLTzT7yaa@Tn2aOEYRGuIpQdPYNJnqE9ozg@Bmg7yNAnfsDonRoQN9cKFfjZuhsGQ3nyerRN/Cc2eo@z8902MUWZLgHnrDQazi68bXox1b3qOETqKHuSmvGLkl4NATKSBYhho9HAQJaObHV3ndmI2qRGN@oXSnYhGo4o/YdROX430rD3v/gssTCdYmieTaNR7VZtO9XpMbm0d7b3OvHnj1Fc96fkPrqZ1jYHldwS7@tkFeKnhoFvLd@R2NrrwEuTd5d3nvFXrbNAKNm1xNpvG6ezudna7bLO8vz@d3aWX9lPDYPrqKsF0NvVuMBTdyP/mDbTimOCvNOo29YyP6z/YbXCiwceGRE/fkGwvEFGh/96SVzOHoH2iBRp/ufcAE0Vfv/4L "Python 3 – Try It Online") Yay, 21 million. The giant horizontal segments up to row 19 are also removed, so about 20% of the entire grid is just an open space. Also, as the "real maze" starts at the leftmost column, moving the entrance to the top right gives a slight bump to the score. (Thanks to @Neil) [![enter image description here](https://i.stack.imgur.com/6r7JB.png)](https://i.stack.imgur.com/6r7JB.png) --- # Previous version, 20,211,703 [Try it online!](https://tio.run/##7Vlfj9u4EX/3p2AVXCFlZZ3l3QQXNy56F@SAbVEUufTNNQzaotdMZVKQaK@1uXz2dIakJFKWvTm0RV@62CQ2ORzO//kNU9RqJ8Xt1698X8hSkY3Mc7ZRXIpqZJfEYV/UhFZEFM1SteFFnVQFLSs2tJbkXND8od2qW2ZcNp/WtGKv70ajTU6rivyVPrE/H7IHNhsR@MnYlqxWXHC1WoUVy7cxeeSZ2sVkx/jDTkWGDH@CICDvSkYVqwgle@ADpGpHHviRCXOKUJHZgwl5J2WZgXiKoVyK7Umla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vn5opnb4q1N86QRtw5rz6w2SxpYdcZXyjYIyrVI@6fyvI0anbqWe@pstO7IM4cgBQ0CjnLsmso0Bnr7byIJBEzwbt1uMOGlDHwq9hGjfNu92kkEXot3nzQKADWIOTjPkctLlblGqtj3b3yLCTVNaShvK8EumLIoiPz4bLFxzEm8@jM7SFLTzT7yaa@Tn2aOEYRGuIpQdPYNJnqE9ozg@Bmg7yNAnfsDonRoQN9cKFfjZuhsGQ3nyerRN/Cc2eo@z8902MUWZLgHnrDQazi68bXox1b3qOETqKHuSmvGLkl4NATKSBYhho9HAQJaObHV3ndmI2qRGN@oXSnYhGo4o/YdROX430rD3v/gssTCdYmieTaNR7VUv1ckxubRntPc68eeOUVz3o@e@tpnONgeN3BJv6OX@403DQneU7cjsbXXgI8u7y7nOeqnUyaP2arjibTeN0dnc7u122Sd7fn87u0kv7qWEwfXWVYDqbejcYim7ix//m079p1G3pAR/W3vygt0DB0ciAY0OiR2/ItBcIp9B5b8mrmUPQvs8Cjb/ce32Joq9f/wU "Python 3 – Try It Online") Yes, 20 million. It's actually good to remove some dead ends and add some open spaces near the entrance, but it stops being good as it gets sufficiently far away from it. This is a derivation from [width-3 dead end maze](https://codegolf.stackexchange.com/a/209198/78410) by removing some h-walls (it's called h-walls in the code, but it is a vertical segment in the image): * The h-walls from row 1 to row 22 (inclusive) are entirely removed. * The h-walls from row 23 to row 40 (inclusive) are reduced by half, keeping the odd indices. [Answer] # Tridents, score ~~21,947,177~~ 21,951,598 ``` UEsDBBQAAAAIAAAAIQAL/+yrSgAAAIgAAAAJABQAYXJyXzAubnB5AQAQAIgAAAAAAAAASgAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mirqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYGBhAGAFBLAwQUAAAACAAAACEAlmPInE8AAACQAAAACQAUAGFycl8xLm5weQEAEACQAAAAAAAAAE8AAAAAAAAAm+wX6hsQychQxlCtnpJanF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kAAAAAAAAAAAAAAIABlQEAAGFycl8zLm5weVBLAQIUABQAAAAIAAAAIQBcvnU+qAAAACwnAAAJAAAAAAAAAAAAAACAAW4CAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAAUQMAAAAA ``` Based on @Bubbler's answer, but some tinkering about with a wall finding algorithm led me to tweak the layout slightly: [![Tridents](https://i.stack.imgur.com/mgWp2.png)](https://i.stack.imgur.com/mgWp2.png) Edit: Slightly improved my score by changing the exit orientation, which allowed me to use the trident shape there too. For some reason (I'm not ruling out human error) not only did @isaacg's "tricky routing" not affect the score for this layout but also my "trident exit" doesn't seem to affect the score for his layout... I actually wrote a script where I could parametrise the number of long horizontal lines, how many of them had teeth, how many of them had gappy teeth, and how many of the ends had prongs, and this was the best I could come up with (also my wall finder couldn't find a way of improving it). [Try it online!](https://tio.run/##7Rlrj@O28bt/BasghbQrK5b3ci3cuGhyuADboggul28bw6At2uZWJgWJ9lp7ud9@nSEpiZRl76UP5EsW9xDJmeG8H9yiVjsp7j594vtCloqsZZ6zteJSVCO7JQ77oia0IqJotqo1L@qkKmhZsaG9JOeC5tv2qG6Jcdl8rWjFXr8ajdY5rSryT/rM/n7Itmw2IvCTsQ1ZLrngarkMK5ZvYvLEM7WLyY7x7U5FBgx/giAgb0pGFasIJXugA6BqR7b8yITBIlRkFjEhb6QsM2BPMeRLsT2pFC0VICsSTmIyiQgXRO0YUbLI2QZ1UgpWJnhTeyvylBjic3OJf2RugzPz0Tt8onlewaEokmdWyioMDakxSVsJY5KpumBzgFlJmUc@ieMFEg06knqBhBV7Th4W/gE78Wa/NUbF1FIjWGucgNEa/p6m8P@0Z473DPC1Bp8kaE8I8CiWGT1zsSWK52isioSGTKQNFFpahOYSgChZgaH6egdfYeA8dFUBLgh5AvhbvaxxiejzOUn78AAL2xMiS/vp2A80hft1B1J3IJ02z0hOO5LTCyQ7kHp6jWTPHo1a4lYni/7tQqIljDUsZkT@SNotbcMo8g2Im/@F/RD9d9sN2q4Nmf@H6Wi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v0T6OilGKLnjWdjhRj@pdK8LmlRbNZ8owJZVcjPZ3Pu1@ahZrUDXkNfgfV2l1FI5DL0v@STI1MegjsBuCJh/IKqpS3cReN8OFoENUF85GurKATbcnosXqir9TlcTTS05Dz4uQyYnhAiMcOwkjnVBZN3NY9fvv45TR@BAp3EDTT9im3R8No/aa9ApT2CPq6w94knfmT2iBvX/cmNM3DruEhjR8v3mxNGzn6tby7Kms4mppHvNSI1BLtX3kFdTKgjT76pIfjuceFmy3T6Yuo2LFc0oZ2@f/QDHfa36@Y4WbqGWJkRh/jivphBfKos3f@aBlFnz79Gw "Python 3 – Try It Online") [Answer] # Two sides of mazes, score 21987725 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJBqs1pOAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkA65kBghAp5OgNABQSwMEFAAAAAgAAAAhAEghScnMAAAALCcAAAkAAABhcnJfMy5ucHnt2jEOgjAUgOF29RTdqgkDjHgAN42Lg5NBqXEwaopxUU/hhQVP8F4xhOF/IS+hy5eSf+Sz2izXW2se5unr0Byinzv/2hc+c/54jfdYXXbXWIfufFGdm9CeN6fqFtr3aVlmrsjzWebeLm0mJnnsb0l2H8MKHwwMDAwMDAwMDAwMDAwMDAwMDAwMjP8byTPAPVRGH0Vs9PhaY7pHukBXGoWupAJdaRS6kgp0pVHoSirQlUahK6lAVxqFrqQCXWmUsXRlBrhHt5IF8U9k9gtQSwMEFAAAAAgAAAAhACNNXj3ZAAAALCcAAAkAAABhcnJfNC5ucHnt2rEKwjAUheFk9SmyRaFDO9YHcFNcHJyk2oiDWEnFRX0KX9g6uGq5gXKRP4RAu3w9J3fsc7GaL9fWXM3N16HdRT91/r4tfOb8vomXWJ02TazD+/2sOrahe98eqnPonsdFnmeuLCeZezjZGhnpsr3PBMJa2+tMIPpuCAgICAgICAgICAgICAgICAgICAiIb1u4dKUQx9BF/MV1D0AwUXqKEmdQRTBReooSZ1BFMFF6ihJnUEUwUXqKEmdQRTBReooSZ1BF/MNEJTQ1RFH9/r9KuW7z+cIfpzUvUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAXAAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEAkGqzWk4AAACgAAAACQAAAAAAAAAAAAAAgAHjAAAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhAEghScnMAAAALCcAAAkAAAAAAAAAAAAAAIABWAEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAjTV492QAAACwnAAAJAAAAAAAAAAAAAACAAUsCAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAASwMAAAAA ``` Based on @Neil's trident design, but I added an extra side of mazes, and also did some tricky routing right at the end to improve the score a bit more. [![Two sides maze](https://i.stack.imgur.com/Mehqy.png)](https://i.stack.imgur.com/Mehqy.png) It turned out to be optimal to have the blank region be a perfect square, which I didn't expect, due to the asymmetry of the maze region. The blank region is 58x58, and there are 14 rows of maze on each side. I really wanted to get to 22 million, but I had to stop just short. I tried lots of designs that didn't improve anything, like making the blank region nonrectangular, or making the design symmetrical across the main axis. None of that helped. [Try it online!](https://tio.run/##7Rprj9u48bt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id9CP4d70PdE/GvnpUkajm1ivmsvPM2ffaX5E3JDwa9UtLwXMeSbQaZGWfRSdRLqfedXChCQclTmSB2D8VUOabt10@UgDLj7Aa4pvkdbnL8DsH4j3spYf9mhaL7KlUj7RNzzq61SDhWqDs90y9zPW6IC16B4auv5ftt1IUB/ir3TdukKc@/hd29tTrdsDBOB/8O1MYmBIe25xlMW9kLY5faFkCJPBq3x0a@Q5ZXHTnaoEpg9BvGIHQVUo/goh1@x2t0KzeTh5v5l6f8EtW01sMBaygsqIgZjSHPZKah6O3Od943V0zEHqXUQyWx7V@5wPNcNLhav5NuRpAmZ1hqtYj8WNyePvf0tslrZX8TMJd5xkOQlN6DytUDKkXjWG7VHuA3pkNXwJrUoSn6SJhQqkpnBsAGniXOnfwde98VR0Qng6vLdT39ecV8awdzhM12UfOfzPj82/BuCZKuCphNl9u00axs@0Nm5/Lar10PZTBjCPOZDKXUqBHycxk6JmkZn6HpklpUHKGs1qH8EB2u87zbTrnI@Ci94vRRZd/HMOQBiq5Pju0fu6rk78k5ge8sHXxnkK73D7@Bk7nX5nTucWpHsoReDQinwYzTKcj3QX0GpHwFv95o@YNmHrFutSln97RKsrq5Qqt@Mz5sAhmvP16Cy173ki9f1KU6EWRwlK897444XmfP/8b "Python 3 – Try It Online") [Answer] # Even more dead ends, 16,555,009.5 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJABQAYXJyXzAubnB5AQAQAJAAAAAAAAAASQAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYIgNEAUEsDBBQAAAAIAAAAIQCcpkBwTAAAAKAAAAAJABQAYXJyXzEubnB5AQAQAKAAAAAAAAAATAAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GNMCIxgc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AAAABQAFABMBAAAXAwAAAAA= ``` The guests now have 3 choices per intersection for most intersections, however there are only about 2/3 as many intersections. Of 34 corridors, the first and last corridors have 98 two-way branches, and 32 corridors have 2 two-way branches and 98 three-way branches. (I didn't count carefully) [![enter image description here](https://i.stack.imgur.com/lVcVP.png)](https://i.stack.imgur.com/lVcVP.png) [Answer] # Empty maze, score 51113 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJBqs1pOAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkA65kBghAp5OgNABQSwMEFAAAAAgAAAAhAPN9K5lvAAAALCcAAAkAAABhcnJfMy5ucHntyDEOgkAUANGl5RS/+5JsASUewE5CY0FFVlliYYTsEhr1FFwYuIIJ3bxuZqlu17pJzGw+2vn4CHoW/d4LtaL9EKbg3u0QOr//i3tFv/34dKPf+lSWVoo8z6z85D+pAQAAAAAAAAAAAAAAAADgYCtQSwMEFAAAAAgAAAAhACFK7HxvAAAALCcAAAkAAABhcnJfNC5ucHntyDEOgkAUANGl5RS/+5JsASUewE5CY0FFVlliYYTsEhr1FFwYuIIJ3bxuZqlu17pJzGw+2vn4CHoW/d4LtaL9EKbg3u0QOr//i3tFv/34dKPf+lTkuZWyzKz85D+pAQAAAAAAAAAAAAAAAADgYCtQSwECFAMUAAAACAAAACEAoQWA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u7UT9IjfWxKpC9mV/l6GRc1Nfbiz@O67/p7SVosEANbNSya0iyu05pd1IMi5XoZLzDcK1tmY6w1kqocwb9cnT19oLQfRedeFpppMsBOv4ax4@vwZPOM/9ViYXblOHDQO4y4PMiV1mFymi4G8Q7hpfBvyKy4Ob7EzXcAx97CDcNN4aBAo5xy8CTStP7Ranfgfa6vn2lbPR20FQZhtNUODauQmcDx3rfpEsPsVVSnI@h5IYxn8KgZTnfk@Bhkem@R4iV/joMU5sVu4mMV89ZUj0QUD2kOwQaTmQ2xUvpqMrjcOmfldZGwtfoLwlqciY75xiFS5cnrZqAYPnSKYjHmpReSJuBg6161Zbvitzp3ZJv0zMKrNRAMDzVK90ot5Bf9u9vXU0u7rVx2JenC9YzC7zpx7mf078oaEJ5NhaSlZwahEq0FWDgm98Go1D@6Di204KHFcRPz4WEKZbz9xhUgBLK@unFfd/wTx4znGyRyOUpeW3YWtqTo4vnRb6n5WvakMgWGm3nQeaF9HNxdwvL4H0eTULSs0Vdba8AtGEHz58hs "Python 3 – Try It Online") Just to get the ball rolling. [Answer] # Zigzag path, score 12,582,074 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJVYfYFPAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhiQAXJUBoAUEsDBBQAAAAIAAA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CTUHTsE1XDuKscmY9aJWCtYDC0fAQmP4k6uqd8ErIRvb7zjAWyKbjD6q1XoL6W3sxkrO5EYudDbgBwYtG5oJGb7ClW8do01zZtz6w2Sxp8dExDwSMMZVogfdPxX46MTtxFOv4aZj@5idODRQUChXJsiyg0Bjb/f5MUMQORu0W48HKEAdCTuHyb5p1e0GRV64dplXFwTSgWVzEjObglR326Vq7aPeLTCsJJXWpIIcZiJ5kAf@8VFR@YyDePM8GXRbWMJjeW8iiQ97j7YdA291MfUgBgZ9jPK4Cn@sqelanibgG1JDYOywIV@YrZ/2m/FmSG4@Tdbwv4DGT0F29ruJMPKsATBurcFgefF2w/Kx7k7PUEIH0Wu5Ka8Y@eWYYU8kG0XXkd3DMSsZjQ50l@iJWYWGN@knSnMiMlLkLXeJl2e09MH6CGQUpWdkAW5irkCl8GA59K1qYcLppQ7wTnVrR@gRXxoSyQvZlfpehkXNTn24s/juu/6e1FaLBADGzUuSKxeXaM0v40CQc730l5hvJKy1MVcbyFQPYd6uT56@0FoOovOmC005mWAnXsNZ4fTuGTzjP/VYmF24Thw0DuMuDzJFtR@dp4uBvEO4aXgd8isuDq@xM13AMbewg3DTcGgQKOccvAk0rT60Gp34H2urO2Wru1FbQRAmW8XQoBrZCRzPXcs@Eex@QVUSsr4FUlsGv4rBVKe/j0GGxyY5XOLXOGhxjuwaLmYxV37liFTBgPYQbBDI@RAbla8mo@qNRWZ@ExlTi58gvMWxSJirHSKWrhyfN7LBQ6fwJmNeahB5Ii6GznVtlht@q7Nntkn/DIxqPdHAQLOUr/SsX8G/m301tbT76lVFohpcbxjMLjNnX2b/jrwh4clkWFpKVjAq0GqQlX1Cz7xazb3b4EITDkoczwOePpZQ5ttPXD5SAMvLK@dV9z9B3HCOcTKHo3rx/fyVDutefnj1ygh3edFpf2/EaKjJn5G5Wpe9UB9sXAfrmobDUbclb39h7dVLuQUnTSbq5kSByHtZaMOMteE3D8/78uU/ "Python 3 – Try It Online") Creates a giant zigzag, something like this but larger: ``` +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | S | + + + + + + + + + + + + + + + + + | S | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | E | + + + + + + + + + + + + + + + + + | E | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ ``` [Answer] # Slightly fewer dead ends, score 16,663,349 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJVYfYFPAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhiQAXJUBoAUEsDBBQAAAAIAAAAIQAhaJ1vdQAAACwnAAAJAAAAYXJyXzMubnB57cgxDoJAFEXRoXUVv/uaTAElLsBOY0NBRQYZ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DKWviemtF7QFZ96tP0wWW34oTC43Bsa42gyoh6eCHL26vXr2dbbsxT6oowQABY1y4ZPc9RTo7NVWHxSS0GzQLT3toAH1LMIaRrhp0a9mpS7jsM3bCwIKYAInuQg5kLk7lOqsj3YPyLCT1M6SlvK8EtFBCcTHR8vlEw7i7fPkDG1hC8/p3oSYn2OPDo5BtMZYenAHJn2O@sR2/xio6SFPm/Atq3NiRNhQL3zo5@JmHAzR4pfZevGX8fxLlL3/vooxyuwIMG@DweDu4u1GEGP9nZ5nhJ5iALm5rAX7@aAQExFQjCNCDwdVCb7Z8XXhJmabGslkWCj9iWgyqeUzRu38@wnN2ov@V2AxLb1gLyGX3FMyGd6v2YU5/Z7HCjq8qXFbPQqKYZz/wmtYjKqG/ZZhnyee0FHsgePsvvMOHBFp7DDv@prapzsJbEQk/SyOv4CjPyBBt0Sj921vDZBhTkSBjpOJhbJ2Gw3KkBeIfZDqNfu@xbpWqvY2FWjCz4O7kiT5/Plf "Python 3 – Try It Online") Based on the original dead end guest trap as posted by @qwr, but removing some of the dead ends like this manages to increase the score: ``` +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | S | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | S | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | + +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + | E | | | | | | | | | | | | | | + + + + + + + + + + + + + + + + + | E | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ ``` [Answer] # The original dead end guest trap, 16,505,047.166666668 ``` UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJABQAYXJyXzAubnB5AQAQAJAAAAAAAAAASQAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYIgNEAUEsDBBQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJABQAYXJyXzEubnB5AQAQAKAAAAAAAAAATAAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GHIARSgMAUEsDBBQAAAAIAAAAIQAsPfLMTwAAAKAAAAAJABQAYXJyXzIubnB5AQAQAKAAAAAAAAAATwAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhmQAVJUBoAUEsDBBQAAAAIAAAAIQCiugFzcQAAACwnAAAJABQAYXJyXzMubnB5AQAQACwnAAAAAAAAcQAAAAAAAADtyDEOgkAURdGhdRW/+5hMASUugA5jY2FlRhlDQcDMEBphFWwY3AIJ3X2nene53qvbIzGj+Wnt4zvoRXR65WpFP30Yguuefaj9v5eujX7rsXFfv/20KKzkWXa2Msu+nUwCAAAAAAAAAAAAAAAAAMCxVlBLAwQUAAAACAAAACEAKLPia5YAAAAsJwAACQAUAGFycl80Lm5weQEAEAAsJwAAAAAAAJYAAAAAAAAA7doxDsIwDIVhZ+UU3gxShnYsB2ADsTAwobQNYkAUJYgFegouTHuFStl+Wx7eW74L+Hc47Y9nJ2/5WB9zl2yr9m1r82rXIb1SeFyG1Me534V7jlOfb+EZp7yuq8pr02y8jrpsVuJESp8rvhAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBDLieJvZPIHUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAYQAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEALD3yzE8AAACgAAAACQAAAAAAAAAAAAAAgAELAQAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhAKK6AXNxAAAALCcAAAkAAAAAAAAAAAAAAIABlQEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAAAAAAAAAAACAAUECAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAAEgMAAAAA ``` The original design in Marcel Vos's video. 50 corridors, each with 99 intersections, gives 4950 two-way branches (maybe off by one or two) for guests to choose between. [![dead end maze](https://i.stack.imgur.com/b87pd.png)](https://i.stack.imgur.com/b87pd.png) ]
[Question] [ Recently, I've found a [rant](http://scrappy-do.blogspot.com/2004/08/little-rant-about-microsoft-internet.html) from 2004 about Internet Explorer's color parsing. Turns out, MS made sure that just about *anything* will be parsed as a color somehow and I think it makes for a neat challenge. ## Well, how does IE parse colors? Let's give it an input with a length of... * ...less than 4 chars: 1. Replace chars not matching `[0-9a-fA-F]` with "0" 2. Append "0" until the length is 3 chars 3. Split into 3 parts, 1 char each 4. Prepend each part with "0" * more or equal than 4 chars: 1. Replace chars not matching `[0-9a-fA-F]` with "0" 2. Append "0" until the length is divisible by 3 3. Split into 3 parts of equal size 4. Remove chars from the front of each part until they are 8 chars each 5. Remove chars from the front of each part until one of them starts with something that isn't "0" or until all parts are empty 6. Look at the length of the parts: Are shorter than 2? If so, prepend each part with a "0" until each part is 2 chars long. If not, remove characters from the back of each part until they are 2 chars each ## ... w h a t It's true! Here are some examples (irrelevant steps omitted): ``` F --> F00 // append "0" until length is 3 --> F, 0, 0 // split into 3 parts --> 0F, 00, 00 // prepend 0 --> #0F0000 // done FLUFF --> F00FF // replace invalid chars with 0 --> F00FF0 // pad to length that is divisible by 3 --> F0, 0F, F0 // split into 3 parts --> #F00FF0 // done rADioACtivE --> 0AD00AC000E // replace invalid chars with 0 --> 0AD00AC000E0 // pad to length that is divisible by 3 --> 0AD0, 0AC0, 00E0 // split into 3 parts --> AD0, AC0, 0E0 // remove "0"s from the front of each part // until one part doesn't start with a "0" --> AD, AC, 0E // remove chars from the back of each part until // each part is of length 2 --> #ADAC0E // done 1234567890ABCDE1234567890ABCDE --> 1234567890, ABCDE12345, 67890ABCDE // split into 3 parts --> 34567890, CDE12345, 890ABCDE // remove chars from the front until // each part is of length 8 --> 34, CD, 89 // remove chars from the back of // each part until each part is of length 2 --> #34CD89 // done rules --> 000E0 // replace invalid chars with "0" --> 000E00 // pad to length divisible by 3 --> 00, 0E, 00 // split into 3 parts --> 0, E, 0 // remove "0"s from the front of each part until one part // doesn't start with a "0" --> 00 0E 00 // parts are too short, prepend a "0" --> #000E00 // done GHIJKL --> 000000 // replace invalid chars with "0" --> 00, 00, 00 // split into 3 parts --> , , , // remove "0" from the front of each part until empty --> 00, 00, 00 // parts are too short, prepend "0" until they are length 2 --> #000000 // done ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins * No standard loopholes * Expect any input matching `[a-zA-Z0-9]*`. Yes, empty input as well (results in #000000). * Output any representation of the resulting RGB color (including but not limited to the actual color, tuples, hex codes, with or without `#`, any case, ...) * For the sake of this challenge, special color names are not respected but instead processed according to the rules. Hence, "red" will result in #000E0D and not #FF0000 ## Test cases Note that the `#` is completely optional ``` red -> #000E0D rules -> #000E00 1234567890ABCDE1234567890ABCDE -> #34CD89 rADioACtivE -> #ADAC0E FLUFF -> #F00FF0 F -> #0F0000 -> #000000 zqbttv -> #00B000 6db6ec49efd278cd0bc92d1e5e072d68 -> #6ECDE0 102300450067 -> #100000 GHIJKL -> #000000 000000 -> #000000 ``` ## EDIT These are the longest Jelly and Vyxal answers I've seen on this site up to this point :o ## EDIT 2 Lecdi pointed out that the specification had a flaw that caused undefined behaviour if the input turned into `000000` at some point, such as `GHIJKL`. As of now, all answers seem to handle this with the exception of lyxal's 64 byte Vyxal answer. The flaw in the spec should now be fixed. Sorry! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~51~~ ~~50~~ ~~47~~ 44 bytes ``` ⇧ƛk^$c∧;ṅ3/\0ÞḞṅ3/8Nvȯ∩\03*:£øl:L2∵Ẏ¥p¥p2Nȯ∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oenxptrXiRj4oinO+G5hTMvXFwww57huJ7huYUzLzhOdsiv4oipXFwwMyo6wqPDuGw6TDLiiLXhuo7CpXDCpXAyTsiv4oipIiwiIiwicmVkXG5ydWxlc1xuMTIzNDU2Nzg5MEFCQ0RFMTIzNDU2Nzg5MEFCQ0RFXG5yQURpb0FDdGl2RVxuRkxVRkZcbkZcblxuenFidHR2XG42ZGI2ZWM0OWVmZDI3OGNkMGJjOTJkMWU1ZTA3MmQ2OFxuXCIxMDIzMDA0NTAwNjdcIiJd) A huge mess, but at least I outgolfed lyxal. [Answer] # JavaScript + HTML, 50 bytes ``` document.body.setAttribute('bgcolor','#'+prompt()) ``` Works in any browser, as the legacy behavior was kept with `bgcolor` (even though it won't work with CSS). Displays as graphical output. ``` <script>document.body.setAttribute("bgcolor",'#'+prompt());</script> ``` If graphical output is not allowed, then: # JavaScript + HTML, 97 bytes ``` c=document.body;c.setAttribute('bgcolor','#'+prompt());alert(getComputedStyle(c).backgroundColor) ``` ``` <script>c=document.body;c.setAttribute('bgcolor','#'+prompt());alert(getComputedStyle(c).backgroundColor)</script> ``` Uses the computed styles generated. Will output like `rgb(X, Y, Z)`. To output a hex code, this would be 156 bytes: ``` c=document.body;c.setAttribute('bgcolor','#'+prompt());alert(getComputedStyle(c).backgroundColor.match(/\d+/g).map(x=>(x|256).toString(16).slice(1)).join``) ``` ``` <script>c=document.body;c.setAttribute('bgcolor','#'+prompt());alert(getComputedStyle(c).backgroundColor.match(/\d+/g).map(x=>(x|256).toString(16).slice(1)).join``)</script> ``` [Answer] # JavaScript (Browser), 138 bytes, non-competitive ``` c=>(document.body.innerHTML=`<font id=g color=${c}>`,getComputedStyle(g)).color.match(/\d+/g).map(n=>(n|256).toString(16).slice(1)).join`` ``` The same color parsing algorithm also works on browsers other than IE (I had tested on my Firefox 103 and it works). But the code will output `#ff0000` for input `red` so marked non-competitive. ``` f= c=>(document.body.innerHTML=`<font id=g color=${c}>`,getComputedStyle(g)).color.match(/\d+/g).map(n=>(n|256).toString(16).slice(1)).join`` console.log(f('red ')); console.log(f('rules ')); console.log(f('1234567890ABCDE1234567890ABCDE ')); console.log(f('rADioACtivE ')); console.log(f('FLUFF ')); console.log(f('F ')); console.log(f(' ')); console.log(f('zqbttv ')); console.log(f('6db6ec49efd278cd0bc92d1e5e072d68')); console.log(f('102300450067 ')); ``` Save ~30 bytes by [Kaiido](https://codegolf.stackexchange.com/users/64489/kaiido) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~44~~ 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -5 thanks to UnrelatedString (clever use of `;Ṫ` for the empty string special case). ``` ØhḊiⱮŒla;Ṫ$œs3z0ZŻ€ṫ€-7ZḊẸ€Ḣ¬Ɗ¡ƬḊƇṪḣ2ZF ``` A full program that accepts a string and prints the resulting colour code (keeping character casing from the input\*). **[Try it online!](https://tio.run/##y0rNyan8///wjIyHO7oyH21cd3RSTqL1w52rVI5OLjauMog6uvtR05qHO1cDSV3zKKCih7t2gER2LDq05ljXoYXHgMyuY@1AHQ93LDaKcvv//796kaNLZr6jc0lmmas6AA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wjIyHO7oyH21cd3RSTqL1w52rVI5OLjauMog6uvtR05qHO1cDSV3zKKCih7t2gER2LDq05ljXoYXHgMyuY@1AHQ93LDaKcvv/cHfP0T2H24FqsoD4UcMcBV07hUcNcyP//49WL0pNUddRUC8qzUktBjEMjYxNTM3MLSwNHJ2cXVzRuGClji6Z@Y7OJZllYK6bT6ibG5gBIkC4qjCppKQMxDJLSTJLTTaxTE1LMTK3SE4xSEq2NEoxTDVNNTA3SjGzAFtoYGRsYGBiamBgZq4eCwA "Jelly – Try It Online"). ### How? ``` ØhḊiⱮŒla;Ṫ$œs3z0ZŻ€ṫ€-7ZḊẸ€Ḣ¬Ɗ¡ƬḊƇṪḣ2ZF - ...f(X) Øh - hex characters = "0123456789abcdef" Ḋ - dequeue -> "123456789abcdef" Œl - lower-case X Ɱ - map with: i - first 1-indexed index or 0 if not found $ - last two links as a monad - f(X): Ṫ - tail (yields zero when X is empty) ; - X (without its tail) concatenated with that (its tail or a zero) a - logical AND the hex-char-indicator list with X or [0] (vectorises) œs3 - split into three equal chunks Ż€ - prefix each with a zero ṫ€-7 - tail each from index -7 -> last (up to) eight values Z - transpose Ƭ - collect up while distinct, applying: ¡ - repeat... Ɗ - ...number of times: last three links as a monad: Ẹ€ - any? for each Ḣ - head ¬ - logical NOT Ḋ - ...action: dequeue Ƈ - keep those which are truthy under: Ḋ - dequeue Ṫ - tail ḣ2 - head to index two Z - transpose F - flatten - implicit, smashing print ``` [Answer] ## JavaScript, ~~238~~ 234 bytes Way longer than the others, but actually competing! ``` c=>(M=Math,s='slice',t=M.ceil(c.length/3),c=c.padEnd(M.max(t*3,3)).replace(/[g-zG-Z ]/g,'0'),c=[c[s](0,t),c[s](t,t*2),c[s](t*2)]).map(p=>p[s](i=M.min(...c.map(p=>(r=p.search(/[^0].{0,7}$/),r<0?3e333:r))),i+2).padStart(2,'0')).join('') ``` Less golfed: ``` c => ( M = Math, s = 'slice', // these are shorter t = M.ceil(c.length / 3), // prepare length for the parts c = c .padEnd(M.max(t*3, 3)) // pad with spaces until length divisible by 3, with a minimum of 3 .replace(/[g-zG-Z ]/g, '0'), // replace all non-hex characters with '0' c = [c[s](0, t), c[s](t, t*2), c[s](t*2)] // split into 3 equal parts ).map(p => ( i = M.min(...c.map(p=>(r=p.search(/[^0].{0,7}$/),r<0?3e333:r))), // search for a character that's not '0' in the last 8 characters, returning its index, or infinity when negative (no match found), and take the lowest of the parts p[s](i, i+2).padStart(2, '0') // slice max two characters from the lowest non-'0', and pad to two characters )).join('') ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~67~~ 64 bytes ``` k6:⇧∪ṅ\^pøB?0øṙ₅:ǒ3εǒ+↲›3/?L4<[2↳›|8Nvȯ{:vh0J≈|ƛh0=ßḢ}ƛ₃[0p|2Ẏ}ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiazY64oen4oiq4bmFXFxecMO4Qj8ww7jhuZnigoU6x5IzzrXHkivihrLigLozLz9MNDxbMuKGs+KAunw4TnbIr3s6dmgwSuKJiHzGm2gwPcOf4biifcab4oKDWzBwfDLhuo594bmFIiwiIiwicmVkXG5ydWxlc1xuMTIzNDU2Nzg5MEFCQ0RFMTIzNDU2Nzg5MEFCQ0RFXG5yQURpb0FDdGl2RVxuRkxVRkZcbkZcblxuenFidHR2XG42ZGI2ZWM0OWVmZDI3OGNkMGJjOTJkMWU1ZTA3MmQ2OCJd) A big mess of unicode and lesser-used overloads of things ## Explained There are 10 parts here: ``` Generating the hex-digit regex: k6:⇧∪ṅ\^pøB Replacing non-hex with 0: ?0øṙ Padding to nearest multiple of 3: ₅:ǒ3εǒ+↲› Splitting into 3 equal parts: 3/ The length 4 conditional branch: ?L4<[ Making each bit 2 digits with 0s if needed: 2↳› | Getting the last 8 characters: 8Nvȯ Removing 0s until something doesn't start with a 0: {:vh0J≈|ƛh0=ßḢ} Either prepending a 0 or getting the last 2 chars: ƛ₃[0p|2Ẏ} Outputting the result: ṅ ``` ### Generating the hex-digit regex ``` k6:⇧∪ṅ\^pøB k6 # The string "0123456789abcdef" :⇧ # Uppercased ("0123456789ABCDEF") ∪ṅ # Unioned with the lowercase string ("0123456789abcdefABCDEF") \^p # With a caret prepended ("^0123456789abcdefABCDEF") øB # Surrounded in "[]" ("[^0123456789abcdefABCDEF]") ``` This regex (`[^0123456789abcdefABCDEF]`, called `re` from here) will be used in the next step to determine which characters to replace with 0s. ### Replacing non-hex with 0 ``` ?0øṙ # Before this part, the stack is [re] ? # Push the input : [re, input] 0 # Push a 0 to the stack : [re, input, 0] øṙ # Replace matches of re in input with 0 ``` This completes the step of replacing invalid characters with 0s, which is common to strings less than 4 chars and strings with at least 4 chars. This string will be called `0-str` from here. ### Padding to nearest multiple of 3 ``` ₅:ǒ3εǒ+↲› # Before this part, the stack is [0-str] ₅: # Push two copies of the length of 0-str without popping it ǒ3ε # Modulo the first copy by 3 and take the absolute difference of that and 3 to get how far away the length is from the next multiple of 3. Note that this may result in the result being 3 because a string of length that is divisible by 3 will return 3, as 3 - (length % 3 => 0) = 3 ǒ # Modulo 3 again to make a 3 a 0 +↲› # Add that to the remaining copy of the length to get how many characters should be in the padded string, left pad 0-str with spaces to that many characters and replace all spaces with 0s. ``` The result of this step is common to both string length possibilities and will be referred to as `pad-0-str`. ### Splitting into 3 equal parts ``` 3/ # Before this part, the stack is [pad-0-str] 3/ # Divide the string into 3 equal parts ``` Yes, there really *is* a built-in for this. The result will be referred to as `3-part-pad`. ### The length 4 conditional branch ``` ?L4<[...|...} # Before this part, the stack is [3-pad-str] ?L # Is the length of the input 4< # Less than 4? [... # If so, move onto the steps for a string with less than 4 characters |...} # Otherwise, move onto the steps for a string with at least 4 characters. A `}` is used instead of a `]` because it saves a byte over `;]` later on. ``` The stack hasn't changed after this step. #### Less than 4 - Making each bit 2 digits with 0s if needed ``` 2↳› # Before this part, the stack is [3-pad-str] 2↳ # Right pad each part of 3-pad-str to be two characters, using spaces. This is needed because components of 3-pad-str will be empty if the input is the empty string. In the case of the empty string, this returns " ". Otherwise, it returns " " + char › # Replace the spaces with 0s. This turns " " into "00" and everything else into "0" + char. ``` The result of this will be called `res`. #### At least 4 - Getting the last 8 characters ``` 8Nvȯ # Before this part, the stack is [3-pad-str] 8N # Push -8 to the stack : [3-pad-str, -8] vȯ # Push [part[-8:] for part in 3-pad-str] ``` The result of this will be referred to as `last-8` #### At least 4 - Removing 0s until something doesn't start with a 0 ``` {:vh0J≈|ƛh0=ßḢ} # Before this part, the stack is [last-8] { # While ... :vh # the first character of each part of last-8 (leaving last-8 on the stack)... 0J≈ # are all equal to 0: |ƛh0= # For each item, check if the first character is 0 ßḢ} # And if so, remove the head of that part. The `}` here closes both the map lambda and the while loop. ``` This is probably the messiest section. The result of this will be referred to as `second-last`. #### At least 4 - Either prepending a 0 or getting the last 2 chars ``` ƛ₃[0p|2Ẏ} # Before this part, the stack is [second-last] ƛ # For each item in second-last, which has leading 0s removed: ₃[ # If the length is 1: 0p # Prepend a 0 |2Ẏ} # Else: take the last two characters. # The `}` here closes both this inner if-statement, the map lambda, and the outer if-statement ``` The result of this part will be referred to as `res`. This is analogous to the step taken in the less than 4 branch. ### Outputting the result ``` ṅ # Join res on empty string - concatenate into a single string. ``` I could have used the `s` flag here, but at this point, we're already play the long golf game, so I thought I might as well go flagless. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 117 bytes ``` T`op`a-fA-FRd $ 00 ^((.)*?)((?<_-2>.)*)((?<-_>.)*)0?0?$ 00$1¶00$3¶00$4¶ .+(.{8}) $1 +`^0(..+¶)0(.+¶)0 $1$2 (..).*¶ $1 ``` [Try it online!](https://tio.run/##XYpLDoIwGIT3/zlq0kpo2oI8EiNBsG5cGd0iQmtCYnwgstB4LQ7AxbCydDPzzZepdVNdjsMEr/Nhl19v@dE@xbbcKkDAGGQYUzKNCMbR/GCLhRkj24cRWcSi3w/xvjPpjOn2HVAL03fwIYA4WHnGMKVW3xHTYxmNBBhJ6NS8ER@GWiuon2f9AC4cd@b5QcjiZZKu/ibUcVpd46Sp2hXIzV5KkACve9E0LXiq8HTphvqkhB@UihVlKBTXM818obzgCw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` T`op`a-fA-FRd ``` Replace non-hex digits with zeros. ``` $ 00 ``` Append two zeros in case the length is not a multiple of 3. ``` ^((.)*?)((?<_-2>.)*)((?<-_>.)*)0?0?$ 00$1¶00$3¶00$4¶ ``` Divide the string into three equal parts, discarding the trailing zeros just added if necessary. Prefix `00` to each part in case it is short. ``` .+(.{8}) $1 ``` Trim each part to the last 8 digits. ``` +`^0(..+¶)0(.+¶)0 $1$2 ``` Trim leading zeros while all parts have one, but don't trim to fewer than two digits. ``` (..).*¶ $1 ``` Keep only the first two digits of each part and join everything together. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~48~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` lA6.$S0:₄¦«3ô¨S3ä8δ.£'e¶:øJ0Û¶'e:2£₄¦D‚ì2.£€Sø˜ ``` Output as a lowercase list of characters without `#`. [Try it online](https://tio.run/##yy9OTMpM/f8/x9FMTyXYwOpRU8uhZYdWGx/ecmhFsPHhJRbntugdWqyeemib1eEdXgaHZx/app5qZXRoMVihy6OGWYfXGOmBuGuCD@84Pef//6LSnNRiAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/HEczPZVgA6tHTS2Hlh1abXx4y6EVwcaHl1ic26J3aLF66qFtVod3eBkcnn1om3qqldGhxWCFLo8aZh1eY6QH4q4JPrzj9Jz/Ov@jlYpSU5R0lIpKc1KLgbShkbGJqZm5haWBo5OziysaF6TQ0SUz39G5JLMMxHPzCXVzA9FADERVhUklJWVAhllKkllqsollalqKkblFcopBUrKlUYphqmmqgblRipkFyCYDI2MDAxNTAwMzc6VYAA). **Explanation:** Step 1: Convert the input to lowercase, and replace all invalid letters with a `0`: ``` l # Lowercase the (implicit) input-string A # Push the lowercase alphabet 6.$ # Remove its first 6 characters: "ghijklmnopqrstuvwxyz" S # Convert it to a list of characters 0: # And replace all those characters with a "0" in the uppercase input ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f8/x9FMTyXYwOr//6LSnNRiAA) Step 2: Pad with trailing 0s, and split it into three equal-sized parts (with each part as a list of characters): ``` ₄ # Push 1000 ¦ # Remove it's first character: "000" « # Append it 3ô # Split it into parts of size 3 ¨ # Remove the last (potentially shorter) part S # Convert it to a flattened list of characters 3ä # Split it into 3 equal-sized parts ``` [Try just the first two steps online.](https://tio.run/##AScA2P9vc2FiaWX//2xBNi4kUzA64oKEwqbCqzPDtMKoUzPDpP//cnVsZXM) Step 3: Only keep the last 8 characters of each inner list: ``` δ # Map over each inner list 8 .£ # Only keep (up to) the last 8 characters ``` [Try just the first three steps online.](https://tio.run/##AS0A0v9vc2FiaWX//2xBNi4kUzA64oKEwqbCqzPDtMKoUzPDpDjOtC7Co///cnVsZXM) Step 4: Remove leading 0s from each list, until a column doesn't start with a `0` anymore: ``` 'e¶: '# Replace all "e" with a newline # (workaround, because "0e0" would be interpret as 0 in 05AB1E) ø # Zip/transpose; swapping rows/columns J # Join each inner list together 0Û # Trim all leading 0s ¶'e: '# Undo the workaround, by replacing all newlines back to "e"s ``` [Try just the first four steps online.](https://tio.run/##AT0Awv9vc2FiaWX//2xBNi4kUzA64oKEwqbCqzPDtMKoUzPDpDjOtC7CoydlwrY6w7hKMMObwrYnZTr//3J1bGVz) Step 5: Only keep the first two characters of each row, potentially prepending the result with `0`s, and output the final result: ``` 2£ # Only keep the first two triplets of the list ₄¦ # Push "000" again D‚ # Pair it with itself: ["000","000"] ì # Prepend this in front of the list 2.£ # Now only keep the last two triplets €S # Convert each inner string back to a list of characters ø # Zip/transpose back; swapping rows/columns ˜ # Flatten the pair of triplets of characters # (after which the sixtet of characters is output implicitly as result) ``` [Answer] # Rust, ~~372~~ ~~367~~ 340 bytes ``` |mut s:Vec<u8>|{for c in &mut s{if!c.is_ascii_hexdigit(){*c=48}}s.extend(b"000");let d:Vec<_>=s.chunks((s.len()-1).max(3)/3).take(3).map(|c|&c[c.len().saturating_sub(8)..]).collect();d.iter().flat_map(|c|match&c[d.iter().map(|c|c.iter().take_while(|c|**c==48).count()).min().unwrap()..]{[]=>*b"00",&[c]=>[48,c],&[x,y,..]=>[x,y]}).collect()} ``` Ungolfed: ``` fn f(mut s: Vec<u8>) -> Vec<u8> { for c in &mut s { if !c.is_ascii_hexdigit() { *c = b'0' } } s.extend(b"000"); let chunks: Vec<_> = s .chunks((s.len() - 1).max(3) / 3) .take(3) .map(|c| &c[c.len().saturating_sub(8)..]) .collect(); let to_remove = chunks .iter() .map(|c| c.iter().take_while(|c| **c == b'0').count()) .min() .unwrap(); chunks .iter() .flat_map(|c| match &c[to_remove..] { [] => *b"00", &[c] => [b'0', c], &[c1, c2, ..] => [c1, c2], }) .collect() } ``` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=990189c8ef3583746ba6bb6363264c8d) The chunking is a little tricky, but otherwise a relatively boring solution. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 29 bytes ``` S⇩3ẇ3↲∑k6Ǐ~vḟİ∑3/⟑8NȯHH2∆Z2Ẏ₴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJT4oepM+G6hzPihrLiiJFrNsePfnbhuJ/EsOKIkTMv4p+ROE7Ir0hIMuKIhloy4bqO4oK0IiwiIiwiIl0=) ``` S⇩ # Stringify ("" -> 0 edgecase) and lowercase 3ẇ # Cut into chunks of length 3 3↲ # Pad each to length 3 with spaces (will be zeroed) ∑ # Concatenate k6 # Lowercase hex Ǐ # Append the leading zero ~vḟ # Without popping, for each char in input, find it in the hex İ # Index into the hex + 0 - ones not found, -1s, get indexed into the end ∑ # Concat into a string 3/ # Divide into 3 parts ⟑ # Over each... 8Nȯ # Get last 8 chars HH # Convert to/from hex to remove leading zeroes 2∆Z # zfill each to length 2 2Ẏ # Get the first two chars of each ₴ # Print ``` [Answer] # [C#](https://www.microsoft.com/net/core/platform), ~~235~~ ~~229~~ 227 bytes -6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` s=>{int l;for(s=Regex.Replace(s,"[^0-9a-fA-F]|^$","0");(l=s.Length)%3>0;s+="0");for(s=l<4?"0"+s[0]+0+s[1]+0+s[2]:s;(l=s.Length/3)>8|s[0]+s[l]+s[2*l]<145&l>2;s=string.Concat(s.Where((_,i)=>i%l>0)));return s.Where((_,i)=>i%l<2);} ``` [Try it online!](https://tio.run/##jVNtj9owDP7Or4iq3dQO6EIpbyvt1AG93Y1J027TfWDcVFLDRQopJCli4/jtLG3hxNg0zVIS27EfO7ZDZJ2kAg6ZpHyB7n5IBUuvci7ZY8rXF6pByhgQRVMu7WvgICi5sPgCW2V/hkXGYjHargRImVt7lQphsZTok0gXIl6iXQVpkipWlKBNShP0MabctI4XOUUZJ32phEavoZsRz5Yg4hmDPnmMRRCgOfIP0g92lCvEvHkqTOnryLDV8VcsJmDKmjF5wPVeXJ@H9Wj69PDCqBnYsDyT@dIeA1@oR@uqGWBPVv3iokRhffetFqtygqdVrI9GeTjTN/Lc93XTCrpPhZWcsHxzXrFpv@G2XrLA8aRfZq/LxkmsTGnfP4IA0/xeo5Yf0CsWYMuyPAEqExz9ed13LG9/ONXDe65MCTuZIspXmUI@2iEjMmp6G3@NCkaEQ5qGA0U3o1xsOE231e50ezh8NxiOLsTCIWMgc@b6/c3th3GhgiQ/8vVzPVNqk3PtZNYG4vZgnjidLknwjPScpAEtwB0naXeLaNhpYuy2MG53chkXZKD9X14A25UeKEjKR@CosMxfgnEUFVw4DAe4yLHpDobd3hERSrsj9kmXXOpmR04nnQAuszvzOOX1nJhulUwZ2PeCKtA/QA9R2cPbVI@n8Y1rx6Lq9h3kX8GUyA/Q732em9LKyfsH6v9haIN1BpzAaJ3FzDwV6wS9r@wPvwA "C# – Try It Online") --- Ungolfed: ``` input => { //the three while loops are golfed into for loops in the submission, with the last two then being combined into one // replace non hex chars with 0 input = Regex.Replace(input, "[^0-9a-fA-F]|^$", "0"); // pad input to next multiple of 3 while (input.Length % 3 > 0) { input += "0"; } // add 0 at the start of each section if the input is now 3 chars long // the final two zeroes here get coerced to strings if (input.Length == 3) input = "0" + input[0] + 0 + input[1] + 0 + input[2]; // used to keep track of the current section length (changes as 0s are removed) int partLength = input.Length / 3; // if part length is >8 continuously remove the first char from each part (notice the first char of each part is always 0 mod partLength) while (partLength > 8) { // because LINQ, the .Where has to be cast to something to actually evaluate within a while, string.Concat is the shortest way (including other changes to have other variables be the correct type) input = string.Concat(input.Where((_, i) => i % partLength > 0)); } //if every part starts with 0, remove the first char from each //this is golfed into a sum using char codes in the submission ((int)'0' = 48) while (input[0] == '0' && input[partLength] == '0' && input[2 * partLength] == '0' && partLength > 2) { input = string.Concat(input.Where((_, i) => i % partLength > 0)); } //return the first two chars from each part return input.Where((_, i) => i % partLength < 2); } ``` [Answer] # [C (clang)](http://clang.llvm.org/), 273 bytes ``` int p(char*c){unsigned int l=(strlen(c)+2)/3,i,j,r,g,b,v;for(j=0;j<3;j++){v=0;for(i=0;i<l;i++)v=v<<4|(*c?*c>47&&*c<58?*c++-48:*c>64&&*c<71?*c++-55:*c>96&&*c<103?*c++-87:*c++&0:0);!j?r=v:j==1?g=v:(b=v);}while(r>255||g>255||b>255){r/=16;g/=16;b/=16;}return (r<<16)|(g<<8)|b;} ``` [Try it online!](https://tio.run/##hZJPb9owGMbP5VOkTEU2SVfnnxOwA2JldH96nbTDLsQ2wVFqOhNSaYTPzpzAYephfg9@/P70kyw9Mrtn1VoV5w9SserAhUP3NZe7j9vZ4F@kpSoMO0tVO6@Abdd6zODxoPayUII7Ha4yYLxKKMCgG8CH0JNe6Wmv8HKvIZudBmWGSElDUrouPDZm6aA0KWlFpIFN1lAatWDM5mM2i5LRaMxonJrFde@jdGogjnqY@BcYxx2c4B76KLzQNJl2OUJTBMltOddZMy2zzJ8X5gLyrIHk9LaVlQB6FsRx2xaXyLuAR/2Q@ZgU/Zn350mL@qCVAzSlPoYtKChNYZuTU9/Iy1oqAAfHwc2rKaregOEdwj9/qaFnyrq0BYda8CGE5P/OoRJ7q@UHYRTjJJ2gxafH5ed3q/2RxVLuFo@1bOzu6vnHamW3rIZV@PM7r@vGqmGeY8GiidjwIEkZRzmbBNwXsUBJwHFq7w4FIUJRjBBOrPLTl6/fvj9bNdRPrznXuf4XRAan818 "C (clang) – Try It Online") ### Ungolfed ``` int parse(char *c) { unsigned int length; unsigned int i, j; unsigned int r, g, b; unsigned int value; /* Round up to multiple of 3, then divide by 3 to get the component length */ length = (strlen(c) + 2) / 3; /* For each component (r,g,b) */ for (j = 0; j < 3; j++) { value = 0; /* Start at 0 */ for (i = 0; i < l; i++) { int char_value; if (*c != '\0') { /* Parse a hex digit */ if (*c > '0' && *c < '9') { char_value = *c - '0'; } else if (*c > 'A' && *c <= 'F') { char_value = *c - 'A' + 10; } else if (*c >= 'a' && *c <= 'f') { char_value = *c - 'a' + 10; } else { /* Invalid digits are 0 */ char_value = 0; } /* Next character */ *c++; } else { /* At the end of the string. Pretend string is right padded with '0' */ char_value = 0; } /* Now append. If there are more than 8 digits, the leftmost ones will be lost to overflow */ value = value << 4 | char_value; } /* Set the correct component value */ if (j == 0) { r = value; } else if (j == 1) { g = value; } else { b = value; } } /* Remove the last few digits until all are within the range 0-255 */ while (r > 255 || g > 255 || b > 255) { r /= 16; g /= 16; b /= 16; } /* Return the colour as an integer in the form 0x00RRGGBB */ return (r << 16) | (g << 8) | b; } ``` ### Explanation This algorithm is different from the one given, so why does it work? Well when I was reading the rant I noticed the part where if the component length was greater than 8 digits, it would remove the leftmost digits until there were 8. The number 8 stuck out to me as 8 hex digits fit neatly inside a 32-bit integer. And the whole removing leading '0' thing also fits with the whole integer idea, as you can't tell a leading '0' from no leading '0' anyway in an integer. Also the steps for lengths <= 3 seemed to be superfluous as they could be explained using just the general case. Going through each of the steps given: 1. "Replace chars not matching [0-9a-fA-F] with '0'". This is handled by invalid hex digits being treated as "0". Essentially, just as 'a' and 'A' both equal 10, '0' and 'G' both equal 0. 2. "Append "0" until the length is divisible by 3". This is handled in two ways. First the length of the string is rounded up to a multiple of 3 (using `(length + 2) / 3 * 3`), then if the end of the string is encountered, treat it as if it were 0 *without incrementing the pointer* (Here be UB). 3. "Split into 3 parts of equal size". This is simply dividing the rounded up length by 3 to get the component length (which simplifies into `(length + 2) / 3` since the rounded up length is not used anywhere else) and counting this many characters for each component. 4. "Remove chars from the front of each part until they are 8 chars each". This is handled with integer overflow; the leading digits get shifted out once 8 characters are parsed. 5. "Remove chars from the front of each part until one of them starts with something that isn't "0" or until all parts are empty". This is done for free with integers. 6. "Look at the length of the parts: Are shorter than 2? If so, prepend each part with a "0" until each part is 2 chars long. If not, remove characters from the back of each part until they are 2 chars each". The prepending part is also done for free. The while loop handles the case where the components are longer than 2 characters. As for the case with 3 or fewer characters: those steps actually turn out to line up with the steps for 4 or more anyway: 1. "Replace chars not matching [0-9a-fA-F] with "0"". Literally identical. 2. "Append "0" until the length is 3 chars". For lengths 1-3, this is equivalent to step 2 of the general case. For length of 0 the general step would result in "" rather than "000" at this stage. 3. "Split into 3 parts, 1 char each". This is also equivalent to step 3 of the general case, although "" would be split into the parts "", "", "", whereas "000" would become "0", "0", "0". 4. "Prepend each part with "0"". This is essentially equivalent to step 6 of the general case. As the maximum length of a component is 1, step 4 of the general case does not apply. Step 5 would turn "0", "0", "0" into "", "", "" making the two equivalent again. Then, since they are shorter than 2, they would be prepended with a 0. "", "", "" would be prepended with 2 zeros giving us "00", "00", "00", which is what it should be. ### Notes * This could be how it was implemented in IE. The implementation seems sensible for a hex code parser. That it accepts "long" colours could be future proofing for if 36-bit or 48-bit colour becomes popular (In that case I think the fact that #ABC becomes #0A0B0C rather than something like #AABBCC may have been a bug). That it "pads" may have been some sort of fix. That it accepts invalid characters may just be the nature of their hex parsing implementation. * For some reason (TIO) clang does not like it when I do `!j?r=v:j==1?g=v:b=v`, forcing me to add parentheses to make `!j?r=v:j==1?g=v:(b=v)`. In contrast MSVC didn't care. I am not digging through the spec to find out who is wrong, so I took the 2 byte penalty instead. [Answer] # [Python 3](https://docs.python.org/3/), ~~339~~ 337 bytes ``` def f(s): s=re.sub('[g-zG-Z ]','0',s) if len(s)<4:s=s.ljust(3,'0');return['0'+h for h in s] while len(s)%3:s+='0' L=len(s);l=[s[i:i+L//3]for i in range(0,L,L//3)];l=[j[len(j)-8:]for j in l] while l[0]and all(k[0]=='0'for k in l):l=[m[1:]for m in l] if len(l[0])<2:return[n.rjust(2,'0')for n in l] return[o[:2]for o in l] import re ``` [Try it online!](https://tio.run/##XZBNc4IwEEDv@RW5dCAjagBFjdIZq8V@cO2lDAeRoFEMNAm2@uctQZzONKfN7nu72ZRntSu4e72mNIOZKREBUPqC9mSVmEa07V5W3U8YG5aBDUsiAFkGc8prcDYg0pe9fF9JZbq6jqaCqkrwqI47O5gVAu4g41DGAH7vWE5b88ElsuPXEIChf0tNcz@SESOsE/b7bqxVplWx5ltqYiu0dB7FmttH2tmj7pg04F6D@d@MCMdrnsJ1npuHOvb1JM0dGg6RusUxsm/u8e62a2kZzRzSLsJ7olnPadbTAr8LLVFExGk6FW2BHctCqLp8vT3Hrj9UiTNhPuNlpUw0LQXjymSW0X00rMxkqP5V@rOhpSKJoOvDVdAUiCqnEtiOOxh6o/EEz58Wy@d/VyDmS1bMF4qdnkEQfgQBCAC4fCVKnYCXJh7dDCY0S53ReJPiZDNxUpsOKR45qTcGNnZcjAdDjL0RWL28vr2HADfnFw "Python 3 – Try It Online") #### Commented ``` def f(s): # Create a function, f, which takes in a string, s s=re.sub('[g-zG-Z ]','0',s) # Apply the regex so all non-hex characters are replaced with '0' if len(s)<4:   # If the length is less than 4: s=s.ljust(3,'0') # Append '0' until the length is 3 return['0'+h for h in s] # Return the elements, prepended by a '0' while len(s)%3: # Until the length is divisible by 3: s+='0' # Append '0' L=len(s) # Assign L to the length of s l=[s[i:i+L//3]for i in # Split s into range(0,L,L//3)] # three equal chunks l=[j[len(j)-8:]for j in l] # Remove characters from the front if the length is more than 8 while l[0]and all( # While the strings are not empty k[0]=='0'for k in l): # And all the strings start with '0': l=[m[1:]for m in l] # Remove the first character from each string if len(l[0])<2: # If the length of the first string is less than 2: return[n.rjust(2,'0') # Return each string, for n in l] # with a '0' prepended until the length is 2 return[o[:2]for o in l] # Return the first two characters of each string import re # Import the re module for regex handling ``` [Answer] # [Go](https://go.dev), 359 bytes ``` import."regexp" func f(s string)(k string){s=MustCompile(`[^0-9a-fA-F]`).ReplaceAllString(s,"0") for;len(s)%3>0;s+="0"{} L:=len(s)/3 S:=[]string{s[:L],s[L:2*L],s[2*L:]} if len(s)<4{return "0"+S[0]+"0"+S[1]+"0"+S[2]} for i:=range S{a:=S[i] for;len(a)>8;a=a[1:]{} for;a!=""&&a[0]!='0';a=a[1:]{} for;len(a)<2;a="0"+a{} for;len(a)>2;a=a[:len(a)-1]{} k+=a} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVJRTuMwEBW_PoWxVEhoAmnahdbFlUKhsBCkFRFfIYAVOZHVNIniBCFFOQk_FdIeYsVJdk-zTkyRqH_mzfOz38zYb-9xtv6T03BJYwZXlKeAr_KsKA9RtCrR76qMzPG_nXhDFixmrzkCUZWGMNIEFGXB01jXlhtUC3JbiXKerXKeMO3Zf7TMCTUjx1wEz_rhHcsTGjInSbxOrwkDWUgHUVZME5ZqQu8NZ9ZU9Imk6wa4mCj6aAg8TPxA2dTCx25gCN_F9kEHZMBBA3gElf50VBesrIoUyov6nm8FfQUGG2BLubSFHJOCprJ9r6aYeD4Pvqqh-mw8pYT6AxzUnXpKdwlCe3tUXrhL9q39rW116tSWdOtCv9Ezu1NjlZmD9tCyT2gDVKmNmvffj2687WtoOqxBSAUTEBP41T1aIAMt3PtFGwvnnGfOvOQvFzIb2MPRj-OT8cRyzubnF1tpK68SJmS8vPp5feNKYG0vpObyZIStqZqNqqEGv6R_GWmoJyCZwZ54SJEBQ0P-hVDXQQM-W1ivVfwP) [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 52 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` u r/[^1-9A-F]/S Êc3 ª3 úSV òVz3)®t8n)x2Ãù ®¯2 ù2 rS0 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=dSByL1teMS05QS1GXS9TCspjMyCqMwr6U1Yg8lZ6MymudDhuKXgyw/kgrq8yIPkyIHJTMA&input=WwoicmVkIgoicnVsZXMiCiIxMjM0NTY3ODkwQUJDREUxMjM0NTY3ODkwQUJDREUiCiJyQURpb0FDdGl2RSIKIkZMVUZGIgoiRiIKIiIKInpxYnR0diIKIjZkYjZlYzQ5ZWZkMjc4Y2QwYmM5MmQxZTVlMDcyZDY4IgoiMTAyMzAwNDUwMDY3IgoiR0hJSktMIgoiMDAwMDAwIgpdLW1S) Outputs as an array of hex values. Explanation: ``` u r/[^1-9A-F]/S u # Convert input to uppercase r/[^1-9A-F]/S # Replace everything other than 1-9 and A-F with spaces # Store as U Êc3 ª3 Ê # The length of U c3 # Rounded up to the nearest multiple of 3 ª3 # If the result is 0, use 3 instead # Store as V úSV òVz3)®t8n)x2Ãù ®¯2 ù2 rS0 úSV # Right-pad U with spaces until the length is V ò ) # Split into substrings with length: Vz3 # V divided by 3 ® à # For each substring: t8n) # Get the last 8 characters x2 # Trim any leading spaces ù # Left-pad each substring to the same length ® # For each padded substring: ¯2 # Get the first 2 characters ù2 # Left-pad with spaces to length 2 rS0 # Replace all spaces with "0" ``` ]
[Question] [ You are providing tech support to *the* Bruce Dickenson as he produces a Blue Öyster Cult recording session. When he asks for [more cowbell](https://vimeo.com/55624839), you can give it to him. ## Your task Write a program or function that takes a string (or equivalent in your language) as input, and outputs a related string containing one more cowbell. ## How many cowbells does a string contain? The number of cowbells a string contains equals the maximum number of distinct copies of "cowbell" that can be obtained by permuting the characters of the string. For example, `"bbbccceeellllllooowwwwwwwww"` contains 3 cowbells, while `"bbccceeellllllooowwwwwwwww"` and `"bbbccceeelllllooowwwwwwwww"` each contain 2 cowbells, and `"cowbel"` contains 0 cowbells. ## How should the output be related to the input? The output should consist of the concatenation, in this order, of the input string and the shortest prefix of the input string needed to increase the number of cowbells. For example, `"bbbccceeelllllooowwwwwwwww"` only needs one additional `"l"` to contain 3 cowbells instead of 2; the shortest prefix that contains that `"l"` is `"bbbccceeel"`. Therefore, if the input is `"bbbccceeelllllooowwwwwwwww"`, then the output should be `"bbbccceeelllllooowwwwwwwwwbbbccceeel"`. ## Technicalities * You may assume that the input contains only printable ASCII characters. If there are one or two characters that are annoying for your language's string processing (such as newlines or `\`), you can assume that the input doesn't contain them—just mention this restriction. * You may further assume that the alphabetic characters in the input are all lowercase, or all uppercase. If you choose not to assume one of these, count cowbells case-insensitively. * You may further assume that the input contains at least one copy of each of the characters `b`, `c`, `e`, `l`, `o`, and `w`. This is equivalent to assuming that some prefix of the string can be concatenated to it to produce a string that contains more cowbell. (Note that the input string itself need not contain a cowbell.) * If your language has a builtin that solves this problem ... then totally use it, seriously, how awesome is that. ## Gold-plated diapers Since recording studio time is expensive, your code must be as short as possible. The entry with the fewest bytes is the winner! ## Test cases ([pastebin link](http://pastebin.com/q0874DEP) for easier copy/pasting) Test input #1: `"christopher walken begs for more cowbell!"` Test output #1: `"christopher walken begs for more cowbell!christopher wal"` Test input #2: `"the quick brown fox jumps over the lazy dog"` Test output #2: `"the quick brown fox jumps over the lazy dogthe quick brown fox jumps over the l"` Test input #3: `"cowbell"` Test output #3: `"cowbellcowbell"` Test input #4: `"cowbell cowbell cowbell"` Test output #4: `"cowbell cowbell cowbellcowbell"` Test input #5: `"cowbell cowbell cowbel"` Test output #5: `"cowbell cowbell cowbelcowbel"` Test input #6: `"bcelow"` Test output #6: `"bcelowbcel"` Test input #7: `"abcdefghijklmnopqrstuvwxyz"` Test output #7: `"abcdefghijklmnopqrstuvwxyzabcdefghijkl"` Test input #8: `"cccowwwwbbeeeeelllll"` Test output #8: `"cccowwwwbbeeeeelllllccco"` Test input #9: `"be well, programming puzzles & code golf"` Test output #9: `"be well, programming puzzles & code golfbe well, programming puzzles & c"` Test input #10: `"lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!"` Test output #10: `"lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut lab"` Test input #11: ``` "c-c-b-c i have a cow, i have a bell. uh! bell-cow! i have a cow, i have a cowbell. uh! cowbell-cow! bell-cow, cowbell-cow. uh! cow-cowbell-bell-cow. cow-cowbell-bell-cow! " ``` Test output #11: ``` "c-c-b-c i have a cow, i have a bell. uh! bell-cow! i have a cow, i have a cowbell. uh! cowbell-cow! bell-cow, cowbell-cow. uh! cow-cowbell-bell-cow. cow-cowbell-bell-cow! c-c-b-c i have a cow, i have a bell" ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~50~~ ~~42~~ 38 bytes ``` T$<(MN{_NaM"lcowbe"}//^2M[aYa@<i])++iy ``` Pass the string in as a command-line argument, quoted if necessary. [Try it online!](https://tio.run/nexus/pip#@x@iYqPh61cd75foq5STnF@elKpUq68fZ@QbnRiZ6GCTGauprZ1Z@f//f7BcTo4ChAYA "Pip – TIO Nexus") ### Explanation I'm going to explain this in two parts: the cowbell function and the full program. First, here's the function that computes the amount of cowbell in a string: ``` MN{_NaM"lcowbe"}//^2 ``` `{...}` defines a function. Many Pip operators, when applied to a function, return another function; for example, `-{a+1}` is the same as `{-(a+1)}`. So the above is equivalent to ``` {MN(_NaM"lcowbe")//^2} ``` which works as follows: ``` { } Function, in which a is the 1st argument (the string) _Na Lambda fn: returns number of times its argument occurs in a M"lcowbe" Map that function to the characters of "lcowbe" ^2 A devious way to get [2]: split the scalar 2 into characters ( )// Int-divide the list of character counts by [2] Since the lists are not the same length, this divides the first element (# of l's) by 2 and leaves the others alone MN Take the min of the resulting list ``` Now that we have that, here's the full program: ``` T$<(MN{_NaM"lcowbe"}//^2M[aYa@<i])++iy a is 1st cmdline arg, i is 0 (implicit) T Loop till condition is true: a@<i Slice leftmost i characters of a Y Yank that into y variable [a ] List containing a and that value M To that list, map... MN{_NaM"lcowbe"}//^2 ... the cowbell function Result: a list containing the amount of cowbell in the original string and the amount in the slice $<( ) Fold on less-than: true if the first element is less than the second, otherwise false ++i In the loop, increment i y Once the loop exits, print y (the latest slice) ``` [Answer] # C, ~~511~~ ~~488~~ ~~474~~ ~~470~~ ~~463~~ 454 ``` void f(char*a){char*s;int i=-1,c,o,w,b,e=b=w=o=c=1,l=3,n,r,z=i;for(;s=a[++i];c+=s==67,o+=s==79,w+=s==87,b+=s==66,e+=s==69,l+=s==76);r=~-l/2;n=c<o?c:o;n=w<n?w:n;n=b<n?b:n;n=e<n?e:n;n=r<n?r:n;c=c==n;o=o==n;w=w==n;b=b==n;e=e==n;if(l=r==n?l:0)if(l%2)l=2;else l=1,c=o=w=b=e=0;else l+=l%2;n=c+o+w+b+e+l;for(printf("%s",a);s=n?a[++z]:0;s==67&&c?n--,c--:0,s==79&&o?n--,o--:0,s==87&&w?n--,w--:0,s==66&&b?n--,b--:0,s==69&&e?n--,e--:0,s==76&&l?n--,l--:0,putchar(s));} ``` **[Try it online](https://ideone.com/nHlBNZ)** --- Readable format + explanation: ``` void f(char*a){ //a = input char*s; int i=-1,c,o,w,b,e=b=w=o=c=1,l=3,n,r,z=i;//c,o,w,b,e all start at 1; L starts at 3 for(;s=a[++i];c+=s==67,o+=s==79,w+=s==87,b+=s==66,e+=s==69,l+=s==76); //loop to obtain number of times each character C,O,W,B,E,L is found in string (using the ASCII numeric values of each letter) //to get an extra cowbell we need to increment C,O,W,B,E by 1 and L by 2 (two Ls in cowbell); except we don't have to because we already did that by starting them at c=1, o=1, w=1, b=1, e=1, L=3 when we declared them. r=~-l/2; //r is half of (1 less the number of times L is in string (+ init value)) n=c<o?c:o;n=w<n?w:n;n=b<n?b:n;n=e<n?e:n;n=r<n?r:n; //n is the number of times that the least occouring character appears in the string, (use R instead of L since cowbell has two L's in it and we just need ~-l/2) c=c==n;o=o==n;w=w==n;b=b==n;e=e==n; //convert c,o,w,b,e to BOOL of whether or not we need 1 more of that letter to create one more cowbell (logic for L handled below since it's trickier) if(l=r==n?l:0)//if L-1/2 is [or is tied for] least occurring character do below logic, else set l to 0 and skip to `else` if(l%2)//if l is divisible by 2 then we need 2 more Ls l=2; else //otherwise we just need 1 more l and no other letters l=1,c=o=w=b=e=0; else //add 1 to L if it's divisible by 2 (meaning just 1 more L is needed in addition to possibly other C,O,W,B,E letters) (*Note: L count started at 3, so a count of 4 would be divisible by 2 and there is only 1 L in the string) l+=l%2; n=c+o+w+b+e+l; //n = number of specific characters we need before we reach 1 more cowbell for(printf("%s",a);s=n?a[++z]:0;s==67&&c?n--,c--:0,s==79&&o?n--,o--:0,s==87&&w?n--,w--:0,s==66&&b?n--,b--:0,s==69&&e?n--,e--:0,s==76&&l?n--,l--:0,putchar(s)); //loop starts by printing the original string, then starts printing it again one character at a time until the required number of C,O,W,B,E,L letters are reached, then break (s=n?a[++z]:0) will return 0 when n is 0. Each letter subtracts from n only when it still requires letters of its type (e.g. b?n--,b--:0) } ``` --- Some Fun Tricks Used: •When checking characters I type `'w'` for the char w which is 3 bytes, but for the characters `'c'` and `'b'` I can type their ASCII values 99 and 98 respectively to save a byte each time. *(Edit: Thanks to @Titus I know do this with all COWBELL letters by using uppercase input only which are all 2 bytes numeric ascii values)* •`r=~-l/2` is `r=(l-1)/2` using bitshifts •`a[++i]` I'm getting the character at index(i) and iterating the index all at the same time. I just start `i` at `i=-1` instead of `i=0` (I do the same with `z` and start it as `z=i` to save another byte) [Answer] ## Python 2, ~~125~~ ~~113~~ 112 bytes ``` n=lambda s:min(s.count(c)>>(c=='l')for c in "cowbel") def f(s,i=0): while n(s)==n(s+s[:i]):i+=1 return s+s[:i] ``` --- `n` counts the number of cowbells --- -12 bytes thanks to @Rod -1 byte thanks to @Titus [Answer] # [Perl 6](http://perl6.org/), 91 bytes ``` {my &c={.comb.Bag.&{|.<c o w b e>,.<l>div 2}.min} first *.&c>.&c,($_ X~[\,](.comb)».join)} ``` Assumes lower-case input. ### How it works Inside the lambda, another lambda for counting the number of cowbells in a string is defined as such: ``` my &c={ } # Lambda, assigned to a variable. .comb # Split the string into characters. .Bag # Create a Bag (maps items to counts). .&{ } # Transform it into: |.<c o w b e>, # The counts of those letters, and .<l>div 2 # half the count of "l" rounded down. .min # Take the minimum count. ``` The rest of the code uses this inner lambda `&c` to find the result, like this: ``` [\,](.comb)».join # All prefixes of the input, ($_ X~ ) # each appended to the input. first , # Return the first one for which: *.&c> # The cowbell count is greater than .&c # the cowbell count of the input. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~38~~ 37 bytes *1 byte off thanks to @DLosc's idea of using the template string `lcowbe` instead of `cowbel`* ``` n`Gt@q:)hXK!'lcowbe'=s32BQ/kX<wy-Q]xK ``` Input characters are all lowercase. If the input contains newlines, the newline character needs to be entered as its ASCII code concatenated with the normal characters (see last input in the link with all test cases). [Try it online!](https://tio.run/nexus/matl#@5@X4F7iUGilmRHhraiek5xfnpSqbltsbOQUqJ8dYVNeqRsYW@H9/796UqpCeWpOjo5CQVF@elFibm5mXrpCQWlVVU5qsYKaQnJ@SqpCen5OmjoA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#fZBbTwIxEIXf/RXDi40Ji7c3o4kxPsETiQ8khoS2O@xWell6ocCfxymiKFEnTbbTc75p98wmw52dDePj8u6inYx6TEuXBbKHcHvzNL5cTO7zphpP16Pd88uOydarEF3XoofM9QItCGwCzJ0H4zzCHta6x85YbBGWSckFCO@yJc8a3pLpArgV4UXWfLuB2jXkPoDHHZx8/1RIEBK1y7ThQtY4b1r1ttDGum7pQ0yrvN5sCy4JoBICS@lSBUbI1PSh867x3BhlG@jSdqsxwDldUiM0Ts/JqukXDaguJEPPpg6CisANxj75bEAZMSYPvFadCrIMQq1IDFgTAKhSMK6GiKYjWFmpalUnGyFFCkOUBDF@jEYwvLEcuFbLxAeQXaZUX5msZCUqyeD6qiymoOUrBF7S6MNXVwIa7E0stb19W8ky4j/oEOw37nByRIvwedL/Lv@Eqk/lRP5N2g@evgM). [Answer] # JavaScript (ES6), 106 ~~107 113 126 141~~ A porting to javascript of the Pip answer by @DLosc. I needed some time to fully understand it, and it's genius. **Edit** -15 bytes following the hint by @Titus, directly appending chars to the input string `a` and avoiding early return (so no `for/if`) **Edit 2** enumerating the 6 value for the Min function saves other 13 bytes **Edit 3** changed c function again. I thought the verbose `length` and `split` would be too lengthy. I was wrong. Assuming lowercase input ``` a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a ``` *Less golfed* ``` a=>{ c=a=>{ // cowbell functions - count cowbells k = [... 'lcowbe'].map((c,i) => (a.split(c).length - 1) // count occurrences of c in a / (!i + 1) // divide by 2 if first in list ('l') ); return Math.min(...k); }; b = c(a); // starting number of cowbells [...a].some(z => ( // iterate for all chars of a until true a += z, c(a) > b // exit when I have more cowbells )); return a; } ``` **Test** ``` f= a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a ;["christopher walken begs for more cowbell!" ,"the quick brown fox jumps over the lazy dog" ,"cowbell" ,"cowbell cowbell cowbell" ,"cowbell cowbell cowbel" ,"bcelow" ,"abcdefghijklmnopqrstuvwxyz" ,"cccowwwwbbeeeeelllll" ,"be well, programming puzzles & code golf" ,"lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!" ,`c-c-b-c i have a cow, i have a bell. uh! bell-cow! i have a cow, i have a cowbell. uh! cowbell-cow! bell-cow, cowbell-cow. uh! cow-cowbell-bell-cow. cow-cowbell-bell-cow! `].forEach(x=>console.log(x+'\n\n'+f(x))) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 184 bytes ``` f()(tr -cd cowbel<<<"$1"|sed 's/\(.\)/\1\ /g'|sort|uniq -c|awk '{print int($1/(($2=="l")?2:1))}'|sort -n|head -1) for((m=1;`f "$1${1:0:m}"`!=$[`f "$1"`+1];m++)){ :;} echo "$1${1:0:$m}" ``` [Try it online!](https://tio.run/nexus/bash#dY/JjoMwEETv/orGsoQtcBhzZNF8SBgJYkxAYcmwJAfMtzOeIcsckkNL1dWv1Kq1oIyOPXCZg@yuB1VHUYSJwHpQOdiDl9BdwrxEJMg72nro@lFPbfVtAjq7nsCez33VjmCGEuFRSvw4xjVmn34gGFu2CPBWlyrLgQuGiq6ntIlFmBZgPpFZBB9Bs@DUisl@83DqiK@wcRzGZgjCBSlZdk@YGHpdV8klP3CJUAVldlGQ/TZw4bGZMvUOTaX1p7g5Wu/QrfqNvi1bAN2l@99/gPxuPi@vXAv9AA "Bash – TIO Nexus") Thanks to @AlbertRenshaw for golfing 2 bytes off. [Answer] # JavaScript (ES6), ~~124~~ 114 bytes *Thanks to Neil for saving a few bytes* ``` a=>eval("for(c=0,d=a;(A=$=>Math.min([...'cowbel'].map(_=>($.split(_).length-1)>>(_=='l'))))(a)==A(d+=a[c++]););d") ``` Since this is quite different from the already existing JavaScript answer, and I put quite some time into this, I decided to create an answer myself. ## Usage ``` f=a=>eval("for(c=0,d=a;(A=$=>Math.min([...'cowbel'].map(_=>($.split(_).length-1)>>(_=='l'))))(a)==A(d+=a[c++]););d") f("cowbell") ``` ### Output ``` "cowbellcowbell" ``` [Answer] # Octave, ~~80~~ ~~87~~ 97 bytes ``` s=input('');k=1;do;until(x=@(A)min(fix(sum('cowbel'==A')./('111112'-48))))(b=[s s(1:++k)])>x(s);b ``` [Try It Online!](https://tio.run/#yA7tv) [Answer] # CJam, 37 ``` q___S\+{+"cowbel"1$fe=)2/+:e<\}%()#)< ``` [Try it online](http://cjam.aditsu.net/#code=q___S%5C%2B%7B%2B%22cowbel%221%24fe%3D)2%2F%2B%3Ae%3C%5C%7D%25()%23)%3C&input=cowbell%2C%20needs%20moar%20) If I can exclude the `"` and `\` characters, then… ## 35 bytes ``` q___`{+"cowbel"1$fe=)2/+:e<\}%()#)< ``` [Try it online](http://cjam.aditsu.net/#code=q___%60%7B%2B%22cowbel%221%24fe%3D)2%2F%2B%3Ae%3C%5C%7D%25()%23)%3C&input=cowbell%2C%20needs%20moar%20) **Explanation** The code successively appends each character of the string to the initial string (going from original to doubled), determines the number of cowbells for each string (counting the number of occurrences of each character in "cowbel" and dividing the one for 'l' by 2, then taking the minimum), finds the position of the first string where the number of cowbells increases by 1, then takes the corresponding prefix of the input and puts it after the input string. In order to include the original string too (with no character appended), the code prepends a neutral character to the string that's being iterated. The first version prepends a space, and the 2nd version uses the string representation, i.e. the string between double quotes. ``` q___ read input and make 3 more copies: one for output, one for prefix, one for appending and one for iterating S\+ prepend a space to the iterating string or ` get the string representation {…}% map each character of the string + append the character to the previous string "cowbel" push this string 1$ copy the appended string fe= get the number of occurrences of each "cowbel" character )2/+ take out the last number, divide by 2 and put it back :e< find the minimum \ swap with the appended string ( take out the first number (cowbells in the initial string) )# increment and find the index of this value in the array ) increment the index (compensating for taking out one element before) < get the corresponding prefix another copy of the input is still on the stack and they are both printed at the end ``` [Answer] # PHP, 133 bytes a PHP port of @edc65´s JavaScript port of DLosc´s Pip answer. ``` function f($s){for(;$c=lcowbe[$i];)$a[$c]=substr_count($s,$c)>>!$i++;return min($a);}for($s=$argv[1];f($s)==f($s.=$s[$i++]););echo$s; ``` takes lower case input from command line argument. Run with `-nr`. **breakdown** ``` // function to count the cowbells: function f($s) { for(;$c=lcowbe[$i];) # loop through "cowbel" characters $a[$c]=substr_count($s,$c) # count occurences in $s >>!$i++; # divide by 2 if character is "l" (first position) return min($a); # return minimum value } for($s=$argv[1]; # copy input to $s, loop: f($s) # 1. count cowbells in $s == # 3. keep looping while cowbell counts are equal f($s.=$s[$i++]) # 2. append $i-th character of $s to $s, count cowbells ;); echo$s; # print $s ``` ]
[Question] [ # Input The symbol of any triadic chord (see <http://en.wikipedia.org/wiki/Chord_(music)#Triads>). # Output The notes constituting the given chord. # Examples Input: `AM` Output: `A C# E` Input: `C#m` Output: `C# E G#` Input: `Db+` Output: `C# F A` Input: `C0` Output: `C D# F#` # Bonuses **-50** if you can also deal with seventh chords **-150** for actually playing the sound of the chord **-150** for using printable characters to show how to play the chord on a piano; example for `AM`: ``` ┌─┬─┬┬─┬─┬─┬─┬┬─┲┱─┬─┬─┲━┱┬─┲━┱─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ┃┃ │ │ ┃ ┃│ ┃ ┃ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ┃┃ │ │ ┃ ┃│ ┃ ┃ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ┃┃ │ │ ┃ ┃│ ┃ ┃ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┲┛┗┱┘ │ ┗┯┛└┲┛ ┃ └┬┘└┬┘└┬┘ │ │ │ │ │ │ ┃ ┃ │ │ ┃ ┃ │ │ │ │ └──┴──┴──┴──┴──┺━━┹──┴──┴──┺━━┹──┴──┴──┴──┘ ``` **-100** for using printable characters to show how to play the chord on a guitar; example for `AM`: ``` x o o o o o ┌───┬───┬───┬───┬───┐ │ │ │ │ │ │ ├───┼───┼───┼───┼───┤ │ │ │ │ │ │ ├───┼───┼───┼───┼───┤ │ │ █ █ █ │ ├───┼───┼───┼───┼───┤ │ │ │ │ │ │ ``` (see <https://en.wikipedia.org/wiki/Box-drawing_character>) # Rules * The result must be a command-line program or script. * The input and output can be in any form, as long as it follows a music notation standard. * A guitar or piano representation is considered valid if and only if it contains the three (triadic) or four (seventh) required notes and nothing else. The same note can be present several times in the chord. * External libraries are not allowed, except for sound generation (in which case the `#include`, `import`... directives are not added to the character count). * This is code golf, the shortest code wins! # A little bit of music theory... In modern Western tonal music, every octave is made of twelve successive notes, often noted: `A` `A#` `B` `C` `C#` `D` `D#` `E` `F` `F#` `G` `G#` Or: `La` `La#` `Si` `Do` `Do#` `Re` `Re#` `Mi` `Fa` `Fa#` `Sol` `Sol#` In this system, we consider that two successive notes (e.g. `A` and `A#`, or `E` and `F`) are separated by one semitone. Also, the notes are kind of "looping": what immediately follows `G#` is `A`. ![Pitch constellation](https://i.stack.imgur.com/0TWdk.png) A chord is constituted by a few (2, 3, 4, sometimes more) notes that "sound good together". For instance, [triadic chords](http://en.wikipedia.org/wiki/Chord_(music)#Triads) contain three different notes, and [seventh chords](http://en.wikipedia.org/wiki/Chord_(music)#Seventh_chords) contain four different notes. Let's define the four [triadic chords](http://en.wikipedia.org/wiki/Triad_(music)) as: * **Major triad**: contains the root of the chord (in this question, the note given as input), the major third for the root (4 semitones higher than the root), and the perfect fifth for the root (7 semitones higher than the root); this can be symbolized 0-4-7 * **Minor triad**, symbolized 0-3-7 * **Augmented triad**, symbolized 0-4-8 * **Diminished triad**, symbolized 0-3-6 ![Pitch constellations: triads](https://i.stack.imgur.com/imj0E.png) So for example, if you want to make a *C major triad*, noted `C`, `CM`, `Cmaj`, you will need three noted: * 0: the *root*, in this case a `C` * 4: the *minor third*, 4 semitones higher than the root; that's an `E` * 7: the *perfect fifth*, 7 semitones higher than the root: a `G` This is what the `0-4-7`, `0-3-7`, `0-4-8` and `0-3-6` notations used above mean! For the seventh chords, use the following pattern: ![Pitch constallations: seventh chords](https://i.stack.imgur.com/cLExv.png) That's it for today! Now, amaze me with amazing code... If you have any question, add some comments below. [Answer] As you can tell, I didn't try to golf this at all. I'm a music geek, and a pet peeve of mine is when people write things using the wrong enharmonics (e.g. saying that a C diminished chord is C D# F# instead of C Eb Gb), so I wrote this program that gets the enharmonics right. It does so by representing each note as the number of perfect fifths above F. For what it's worth, if you want to distinguish enharmonics, any musical interval can be represented nicely in a computer program as a number of perfect fifths and a number of octaves. An augmented fourth, for example, is 6 perfect fifths and -3 octaves, and a diminished fifth is -6 perfect fifths and 4 octaves. # Haskell, 441 characters ``` import Data.List notes = "FCGDAEB" fromNum x = [notes !! (mod x 7)] ++ if x < 0 then replicate (-(div x 7)) 'b' else replicate (div x 7) '#' toNum (x:xs) = y + 7 * if isPrefixOf "b" xs then -length xs else length xs where Just y = elemIndex x notes chord xs = unwords . map (fromNum . \x -> toNum (init xs) + x) $ case last xs of 'A' -> [0,4,8]; 'M' -> [0,4,1]; 'm' -> [0,-3,1]; 'd' -> [0,-3,-6] main = getLine >>= putStrLn . chord ``` Some example invocations: ``` jaspers:junk tswett$ ./chord AM A C# E jaspers:junk tswett$ ./chord C#m C# E G# jaspers:junk tswett$ ./chord DbA Db F A jaspers:junk tswett$ ./chord Cd C Eb Gb jaspers:junk tswett$ ./chord A#M A# C## E# jaspers:junk tswett$ ./chord Dbm Db Fb Ab ``` [Answer] # BBC BASIC Emulator at bbcbasic.co.uk # Rev 1, 340 - 150 keyboard - 150 playing = 40 Here's the latest version, in which I managed to include the following enhancements while lengthening by only a few more characters. **Input can be edited comfortably on the screen before pressing return** (I was using GET$ before to get single keypresses, because BBC Basic does not let you access a single character from a string as if the string was an array. Now I use the rather bulky MID$ function to extract a string of one character from within the string. **Both sides of keyboard displayed as well as the full line between E and F.** To compensate for the characters added by the above, I rearranged the program to eliminate unnecessary print statements, and deleted some white space which at first sight looked like it couldnt be deleted. IN BBC Basic all built in functions are reserved words, and you can put a variable name right before them with no space in between. Variable names are not allowed to start with a reserved word. In order to make the program less confusing to read I changed all variables to lower case. Although the presentation looks much better, the following program is actually ~~fully golfed already.~~ (See correction below.) Generally newlines and colons are interchangeable, except when an IF statement is used. In that case all statements on the same line (separated by colons) with be executed conditionally. Statements after the newline are not controlled by the IF and will always be executed. **Program rev 1 340 characters** ``` a$="C#D#EF#G#A#B0Mm+" INPUTx$ r=INSTR(a$,LEFT$(x$,1))-1 c=INSTR(a$,MID$(x$,2,1)) IFc=2c=INSTR(a$,MID$(x$,3)):r=r+1 t=(r+4-c MOD2)MOD12 f=(r+c DIV2)MOD12 v=1 FORn=-1TO11 c=1-(n<0ORn=4ORn=11)*5 b$=MID$(a$,n+1,1) IFb$="#"c=11:b$=MID$(a$,n,1)+b$ c$=MID$(" _______--|__",c,5) IFr=n ORt=n ORf=n c$=c$+b$:SOUNDv,-15,100+n*4,99:v=v+1 PRINTc$ NEXT ``` CORRECTION: RT Russell's BBC BASIC for Windows allows you to eliminate some newlines and colons, bringing the total down to 327, see below. Also it tokenises the keywords into single characters before saving, bringing it down to 279. ``` a$="C#D#EF#G#A#B0Mm+"INPUTx$ r=INSTR(a$,LEFT$(x$,1))-1c=INSTR(a$,MID$(x$,2,1))IFc=2c=INSTR(a$,MID$(x$,3))r=r+1 t=(r+4-c MOD2)MOD12f=(r+c DIV2)MOD12v=1FORn=-1TO11c=1-(n<0ORn=4ORn=11)*5b$=MID$(a$,n+1,1)IFb$="#"c=11b$=MID$(a$,n,1)+b$ c$=MID$(" _______--|__",c,5)IFr=n ORt=n ORf=n c$=c$+b$SOUNDv,-15,100+n*4,99v=v+1 PRINTc$ NEXT ``` **Output rev 1** ![enter image description here](https://i.stack.imgur.com/fC68y.png) # Rev 0, 337 - 150 keyboard - 150 playing = 37 ``` A$="C#D#EF#G#A#B0Mm+":X$=GET$:R=INSTR(A$,X$)-1:X$=GET$:IF X$="#"R=R+1:X$=GET$ C=INSTR(A$,X$):T=(R+4-C MOD2)MOD12:F=(R+C DIV2)MOD12:V=1:PRINT"______" FORN=0 TO 11 C=1-(N=4)*12:B$=MID$(A$,N+1,1): IF B$="#" C=7: B$=MID$(A$,N,1)+B$ PRINT MID$(" __---|________",C,6);:IF(R-N)*(T-N)*(F-N)=0 PRINT B$;:SOUND V,-15,100+N*4,99:V=V+1 PRINT NEXT ``` This is a similar concept to my Arduino answer, but I always knew I could beat that byte count with BBC basic. Only recognises sharps, but considers B# invalid,you must put C. This could be fixed if it was really considered important. I abandoned the idea of guitar and concentrated on improving the keyboard. It now runs from C to B, and I've added in the left side of the keyboard and the line between E and F. That costs 28 characters. The right hand side wouldn't be much more. Here's some sample output, an A# diminished chord (which has a pretty freaky sound in this inversion) and a B major chord. Note that the input is not echoed to the screen. As per the Arduino answer, turn the screen anticlockwise to view. ![enter image description here](https://i.stack.imgur.com/8g9ur.png) **Ungolfed version** ``` A$="C#D#EF#G#A#B0Mm+" :REM Note names and chord type names fit very conveniently in the same string. X$=GET$ :REM Get a character R=INSTR(A$,X$)-1 :REM Root note = position of that char in A$. INSTR starts counting at 1, but we want 0, so subtract. X$=GET$ :REM If the root note is natural, the next character will be the chord type. But... IF X$="#"R=R+1:X$=GET$ :REM If this char is # we need to increment the root, and get another char for chord type. C=INSTR(A$,X$) :REM C encodes for chord type T=(R+4-C MOD2)MOD12 :REM even C means major third, odd C means minor third F=(R+C DIV2)MOD12 :REM "Mm" gives C=14,15 meaning C DIV2=7 (perfect fifth.) C=13,16 give diminished and augmented: 6,8. V=1 :REM V is the sound channel number ("voice") PRINT"______" :REM left side of keyboard for cosmetic reasons FORN=0 TO 11 :REM at the start of each iteration initialise C to 1, to point to the 4 spaces/2 underscores in the string below for drawing white notes. C=1-(N=4)*12 :REM if the note is E, add 12 so it points to the 6 underscores to draw the line between E and F. B$=MID$(A$,N+1,1) :REM load B$ with the name of the current note. IF B$="#" C=7: B$=MID$(A$,N,1)+B$ :REM if the character encountered is a sharp, update C to point the characters for drawing a sharp. Find the previous character in A$ and join it to the beginning of B$ to complete the note name. PRINT MID$(" __---|________",C,6); :REM print the key (6 characters.) IF(R-N)*(T-N)*(F-N)=0 PRINT B$;:SOUND V,-15,100+N*4,99:V=V+1 :REM if N is equal to R,T or F, print the note name beside the key, play the note and increment the channel number for the next note. PRINT :REM print a carriage return. It may be possible to golf this line out. NEXT ``` [Answer] # Python3 - 315 char First time in codegolf! Only supports minor, major, diminished and augmented chords right now. ``` z=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];y=[1,2,4,5,6] def q(a):print(z[a%12]) a=input();k=(ord(a[0])+3)%7;j=k;m=4;s=0;f=7; for i in y: if(k>=i):j+=1 if('#'in a):j+=1 if('b'in a):j-=1 if('m'in a or'0'in a):m=3 if('+'in a or"aug"in a):f=8 if('0'in a or"dim"in a):f=6;m=3 if('ma'in a):m=4 q(j);q(j+m);q(j+f); ``` [Answer] # Arduino Input/output is sent to / received from the Arduino via a COM port. A user can interact with this via a terminal, or the serial monitor in the Arduino IDE. As you may have guessed from my choice of platform, I am planning to include the actual playing of the chord (though I haven't done it yet.) I have tackled the keyboard bonus successfully, and I have tried to tackle the guitar, with limited success. The chord box comes in at 130 bytes, which is too long to be worth it. Therefore I have tried another way, just printing the fret numbers Tab style. Currently this is 81 bytes for a bonus of 81-100=-19. **If this approach is deemed valid I can try and improve on it.** The chords used are all D-type shapes with the root on the 2nd string, fifth on the 3rd string, and third on the 1st and 4th strings. The 5th and 6th strings are not used and I mark this with X's on the right of the chord box (the left would be more usual, but examples marked on the right can be found.) Because the program considers F to be the lowest note (for compatability with the keyboard while avoiding excessively high frets with this chord shape) the highest chord is an E (with root on the 17th fret.) See example output. The keyboard is more successful in terms of golfing. It runs from F-E rather than C-B for the reasons described above. It must be viewed by turning the screen 90% anticlockwise, when you can clearly see the outlines of the black notes, and the demarcation between the white notes with `---`. The line between B an C could be extended with some `____` for a few more bytes. I will try playing the notes next. This will be interesting because, although I believe the Arduino Uno has 3 internal timers, only one note at a time can be played using the built in tone command. There is an external library function which uses all the hardware timers (which will mess up the serial, but it won't be needed at that stage anyway.) Alternatively I may try to produce the tones in softare. If I am successful with that, I will golf it down but I don't think it will be the overall winner. **Ungolfed code** ``` String p="F#G#A#BC#D#E -Mm+",y,d[]= {" ","---|"},n="\n"; void setup() { Serial.begin(9600); Serial.setTimeout(99999); } void loop(){ char x[9]; int r,t,f,i,c=1; Serial.readBytesUntil(13,x,9); Serial.println(x); r=p.indexOf(x[0]); if (x[1]==35|x[1]==98){c=2;r+=x[1]==35?1:-1;} f=p.indexOf(x[c])/2; t=4-p.indexOf(x[c])%2; //chord box y=n;for(i=24;i--;)y+=d[1]+(i%4?"":" \n"); y[89]=y[107]='X'; y[t*4-10]=y[t*4+52]=y[f*4+14]=y[28]='O'; Serial.print("\t "+String(r+6)+y); f+=r;t+=r; //tab style Serial.println(String(t+1)+n+String(r+6)+n +String(f-2)+n+String(t+3)+"\nX\nX\n"); f%=12;t%=12; //piano for(i=0;i<12;i++){ c=0; y=String(p[i]); if(y=="#") {c=1;y=p[i-1]+y;} Serial.println(d[c]+"__"+((r-i&&t-i&&f-i)?"":y)); } } ``` **Sample output** The lower the spacing between the lines of text, the better this looks. Therefore it looks great when I am actually editing the post, but horrible in the grey box after posting. Instead I've posted a screenshot of the Arduino serial monitor which is of intermediate line spacing (and hence display quality.) ![enter image description here](https://i.stack.imgur.com/nbqw7.png) [Answer] # Python 506(unicode as 1 char)-150(sound)-150(keyboard) = 206 For sound playing, it uses `pygame.midi`. Note that the `pygame.midi.get_default_output_id()` method don't work very well. So you may try changing the line `o=Output(get_default_output_id())` to `o=Output(1)`, `o=Output(2)`, etc. Usually the correct value is between 0 and 5. ``` c=input() s='C D EF G A B'.index(c[0])+{'#':1,'b':-1,'':0}[c[1:-1]] m='0mM+'.index(c[-1]) t=s+3+m//2 R=[list(x)for x in['┌─'+'─┬─'*13+'─┐']+['│'+' │'*14]*5+['└─'+'─┴─'*13+'─┘']] i=3 for d in[3,6,3,3,6]*2:q=slice(i-1,i+2);R[0][q]='┬─┬';R[1][q]=R[2][q]=R[3][q]='│ │';R[4][q]='└┬┘';i+=d X=[2]+[1,2,1,2,3,1,2,1,2,1,2,3]*2 from pygame.midi import* init() o=Output(get_default_output_id()) for s in[s,t,t+3+m%2]:R[[5,3][s%12 in[1,3,6,8,10]]][sum(X[:s+1])]='o';o.note_on(s+60,127,1) for r in R:print(''.join(r)) ``` ## Results ``` goooolf> python chords2.py CM ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ o│ │ o│ │ o│ │ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py Cm ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││o│ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ o│ │ │ │ o│ │ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py Dm ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ o│ │ o│ │ o│ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py D+ ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │o││ ││o│ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ o│ │ │ │ │ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ G+ ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││o│ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ │ │ │ o│ │ o│ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py Am ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ │ │ │ │ o│ │ o│ │ o│ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py C#0 ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │o││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ │ o│ │ o│ │ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ goooolf> python chords2.py EbM ┌─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┬─┬─┬┬─┬─┬─┬─┬┬─┬┬─┬─┐ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││ │ │ │ ││ ││ │ │ │ ││ │ │ │ ││ ││ │ │ │ │ ││o│ │ │ ││ ││o│ │ │ ││ │ │ │ ││ ││ │ │ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ └┬┘└┬┘ │ └┬┘└┬┘└┬┘ │ │ │ │ │ │ o│ │ │ │ │ │ │ │ │ │ └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘ ``` [Answer] # J - 82 char Self-contained, reads from console input. If you need stdin, change the final `1` to a `3`. Claiming no bonuses, and only covering the triads. ``` +/&(0 3 6++/\_3{.#:'0mM+'i.{:e)&.((,~C`Db`D`Eb`E`F`Gb`G`Ab`A`Bb`B)i.;:)}:e=.1!:1]1 ``` Instead of a sharp note e.g. `C#` you must use the equivalent flat name `Db`. (Correcting for this would inflate the code by more than a bit.) The four types of chords are `0` for diminishing, `m` for minor, `M` for major, and `+` for augmented. The logic is as follows: we use the last character to add an offset to the base 0-3-6, which selects the kind of third and fifth. Meanwhile, we use the note to find where in the scale to pull the notes from. The `;:` both makes the note compatible with indexing into the scale at the start, and later (by `&.`) turns the pulled notes into a space separated string. Example usage: ``` +/&(0 3 6++/\_3{.#:'0mM+'i.{:e)&.((,~C`Db`D`Eb`E`F`Gb`G`Ab`A`Bb`B)i.;:)}:e=.1!:1]1 AM A Ch E +/&(0 3 6++/\_3{.#:'0mM+'i.{:e)&.((,~C`Db`D`Eb`E`F`Gb`G`Ab`A`Bb`B)i.;:)}:e=.1!:1]1 Ab0 Ab B D +/&(0 3 6++/\_3{.#:'0mM+'i.{:e)&.((,~C`Db`D`Eb`E`F`Gb`G`Ab`A`Bb`B)i.;:)}:e=.1!:1]1 B+ B Eb G +/&(0 3 6++/\_3{.#:'0mM+'i.{:e)&.((,~C`Db`D`Eb`E`F`Gb`G`Ab`A`Bb`B)i.;:)}:e=.1!:1]1 Em E G B ``` [Answer] # Javascript, 224 char ``` n=prompt();a="A0A#0B0C0C#0D0D#0E0F0F#0G0G#".split(0);x=1;r=a.indexOf(n[0]);n[1]=="#"&&(r++,x++);n[1]=="b"&&(r--,x++);s=r+4;l=r+7;(n[x]=="m"||n[x]==0)&&s++;s%=12;n[x]=="+"&&l++;n[x]==0&&l--;l%=12;alert(a[r]+" "+a[s]+" "+a[l]) ``` This is my first code golf. I think it can be shorter, but I can't find any bytes to save. Supports major, `m` for minor, `0` for diminished, `+` for augmented, or 37 more bytes for `dim`, `aug`. [Answer] ## Python (143 134 chars) ``` n,a='A A# B C C# D D# E F F# G G#'.split(),input();m,i=ord(a[-1])-42,n.index(a[:-1]) print(n[i],n[(i+4-m//2)%12],n[(i-4+(-m//2))%12]) ``` My first golf challenge :), don't know if some more bytes can be shaved off. The notation used here is \* aug / + maj / , min / - dim I deserve a bonus point for having the constant 42 in the code :P [Answer] ## Scala 537 chars - 50 ``` import java.util.Scanner object C extends App{ val c=Map("M"->145,"m"->137,"+"->273,"0"->73,"7"->1169,"M7"->2193,"m7"->1161,"Mm7"->2185,"+7"->1297,"+M7"->2321,"07"->585,"7b5"->1097) val n=List("A","A#","B","C","C#","D","D#","E","F","F#","G","G#") val o=List("","Bb","Cb","B#","Db","","Eb","Fb","E#","Gb","","Ab") val s=new Scanner(System.in).nextLine val v=s indexWhere{c=>c!='#'&&c!='b'&&(c<'A'||c>'G')} val (u,m)=s splitAt v val x=n.indexOf(u)max o.indexOf(u) val k=c(m) for(i<-0 to 11)if((k&(1<<i))!=0)print(n((i+x)%12)+" ") println} ``` [Answer] # Python 3: 257 - 150 = 107 Just 25 chars too long to beat the J solution! Oh well. There are some neat ideas here, I think. ``` I='AaBCcDdEFfGg'*2 Q='0123456789.,'*2 K="""-1#_2 -,#_0 -9#_. ____8 -6#_7 -4#_5 ____3""" r,*R,q=input() r=I.find(r)+bool(R) p=str.replace for x in[0]+[8,4,7,3,6]['+Mm0'.find(q):][:2]:K=p(K,Q[x+r],I[x+r].upper()) for x in Q:K=p(K,x,' ') print(p(K,' #',' ')) ``` Input is like the examples, though you must use sharp names instead of flat names. (e.g. Gb must be F#) Output is a single octave of a piano, seen from above and to the left, with note names superimposed. Should be just a tiny stretch of the imagination. ``` $ echo C#m | python3 chords.py - _ -G#_ - _ ____ - _E -C#_ ____ ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 216 bytes Shorter than my original Scala solution and spells pitches correctly to boot. ``` for $*IN.lines {m:P5/([A-G])(\#*)(b*)([Mm+0])/;my \r=4613502.comb[$0.ord-65]+7*($1.comb-$2.comb);put %(:M<0 4 1>,:m<0 -3 1>,"+",<0 4 8>,0,<0 -3 -6>){$3}.map({"FCGDAEB".comb[($/=r+$_)%7]~(<b #>)[$/>0]x abs($/div 7)})} ``` [Try it online!](https://tio.run/##JY3RboIwGEbveYoGatKfUihDYEFtwnAzXmB2j81ipyYmVkjVZQthr86YXHzJyTkXX3Mw56Tvj7VB2F1v/PPpcriiVmfvcUCqnK0kkK3jAlHDqlJTLiGY6R@0NYtpEkYxf/I/a60qzP3a7FkSS5q6BIcPy/BYYdbcb2hCsnLO0RSFwsv0QCz6R5va3kM/C497o2aJgBZHna93DWntt2K1zF9f7PGK4GBhKP6ASSp/yVwhR0CFA8HlN9qp65D3py@UQgdd3@elVTjaWipqFfwP "Perl 6 – Try It Online") [Answer] # Haskell, 273 chars ``` n(s,a)="CCDDEFFGGAABB"!!(s+1-a):["b#"!!a|" b b b b b "!!s/=' '] t p=[(s,a)|s<-[11,10..0],a<-[0,1],n(s,a)==p]!!0 m(s,d)=n(mod s 12,d-3) c q=[n(a,x),m(a+d,d),m(a+d+e,e)]where (a,x)=t$init q;f=lookup(last q).zip"0mM+";Just d=f[3,3,4,4];Just e=f[3,4,3,4] main=print.c=<<getLine ``` ## Results ``` C0 ->["C","Eb","Gb"] Cm ->["C","Eb","G"] CM ->["C","E","G"] C+ ->["C","E","G#"] C#0->["C#","F","G"] C#m->["C#","F","G#"] C#M->["C#","F","Ab"] C#+->["C#","F","A"] D0 ->["D","F","Ab"] Dm ->["D","F","A"] DM ->["D","F#","A"] D+ ->["D","F#","A#"] D#0->["D#","Gb","A"] D#m->["D#","Gb","A#"] D#M->["D#","G","Bb"] D#+->["D#","G","B"] E0 ->["E","G","Bb"] Em ->["E","G","B"] EM ->["E","G#","B"] E+ ->["E","G#","C"] F0 ->["F","Ab","B"] Fm ->["F","Ab","C"] FM ->["F","A","C"] F+ ->["F","A","C#"] F#0->["F#","A","C"] F#m->["F#","A","C#"] F#M->["F#","A#","Db"] F#+->["F#","A#","D"] G0 ->["G","Bb","Db"] Gm ->["G","Bb","D"] GM ->["G","B","D"] G+ ->["G","B","D#"] G#0->["G#","B","D"] G#m->["G#","B","D#"] G#M->["G#","C","Eb"] G#+->["G#","C","E"] A0 ->["A","C","Eb"] Am ->["A","C","E"] AM ->["A","C#","F"] A+ ->["A","C#","F"] A#0->["A#","Db","F"] A#m->["A#","Db","F"] A#M->["A#","D","F"] A#+->["A#","D","F#"] B0 ->["B","D","F"] Bm ->["B","D","F#"] BM ->["B","D#","Gb"] B+ ->["B","D#","G"] ``` ]
[Question] [ [The 2020-05-29 xkcd comic](https://xkcd.com/2313/) showed us the numbers that Randall Munroe feels would be most likely to result from multiplication, other than the correct answers. The table does seem to have some sort of twisted logic to it. For your convenience, the Wrong Times Table is reproduced here in selectable format: ``` +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 1 | 0 | ½ | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 9 | | 2 | ½ | 8 | 5 | 6 | 12 | 14 | 12 | 18 | 19 | 22 | | 3 | 4 | 5 | 10 | 16 | 13 | 12 | 24 | 32 | 21 | 33 | | 4 | 5 | 6 | 16 | 32 | 25 | 25 | 29 | 36 | 28 | 48 | | 5 | 6 | 12 | 13 | 25 | 50 | 24 | 40 | 45 | 40 | 60 | | 6 | 7 | 14 | 12 | 25 | 24 | 32 | 48 | 50 | 72 | 72 | | 7 | 8 | 12 | 24 | 29 | 40 | 48 | 42 | 54 | 60 | 84 | | 8 | 9 | 18 | 32 | 36 | 45 | 50 | 54 | 48 | 74 | 56 | | 9 | 10 | 19 | 21 | 28 | 40 | 72 | 60 | 74 | 72 | 81 | | 10 | 9 | 22 | 33 | 48 | 60 | 72 | 84 | 56 | 81 | 110 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ ``` Flattened text version without headers: ``` 0 ½ 4 5 6 7 8 9 10 9 ½ 8 5 6 12 14 12 18 19 22 4 5 10 16 13 12 24 32 21 33 5 6 16 32 25 25 29 36 28 48 6 12 13 25 50 24 40 45 40 60 7 14 12 25 24 32 48 50 72 72 8 12 24 29 40 48 42 54 60 84 9 18 32 36 45 50 54 48 74 56 10 19 21 28 40 72 60 74 72 81 9 22 33 48 60 72 84 56 81 110 ``` # Challenge Your goal is to write a program or function that accepts two numbers as input and returns the corresponding value of the Wrong Times Table as output. * The inputs and output can be in any format and data type, as long as it is self-evidently clear which number a given value represents. So representing ½ as the floating point number `0.5` or the string `"1/2"` is fine, but representing it as `-1` is not. * The inputs can be assumed to be integers in the range 1 to 10 inclusive. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and loophole restrictions apply. The shortest code in bytes wins. # Example Input and Output Input: > > 5 > > 3 > > > Output: > > 13 > > > # Some possible avenues for golfing * The table is symmetric across the diagonal. * There are some patterns in the numbers, e.g. *f*(1, *n*) = *n* + 1 for 3 ≤ *n* ≤ 9. * The values in the table are usually numerically close to the actual multiplication table, so you could store the differences instead. * The [explain xkcd wiki page for this comic](https://www.explainxkcd.com/wiki/index.php/2313) has a table showing how each number might have been derived. It may take fewer bits to store these offsets than to store the output numbers directly. [Answer] # [Python 3](https://docs.python.org/3/), ~~119 ... 110~~ 105 bytes *-14 bytes thanks to @xnor* Takes as input an array \$ a\$ consisting of the two integers. Outputs the product of the two numbers based on the *Wrong Times Table*. For the case `[1, 2]` or `[2, 1]`, it outputs `.5`. ``` lambda a:b' \0\n  \r2    (0*  $-260\n (H<JH !0<HT8Qn'[max(a)*~-max(a)//2+min(a)]%126.5 ``` [Try it online!](https://tio.run/##bZFBT8IwFIAvgkCIMRoNJJo8o4YNO2i7bnQE7sSbibdthyEOR6QQxEQv@tOxby3h4qF7L69fv/detv7evq2Uv7uFl9WsUPMhfG5zTzbycbJ7z5bTWQbZcNqBhP7WjiqJqlRPodpMNm1@fNJst6DWbF07tFs/gzuPhzRR5xdXzmT0OKlf3tDR5Fk@qU68zL6czO3@eCbp9/nDslA6S@8ZD3vBLlMfMIY4pgR6AQFBQH9DAgMCkkBEgOmbKCUQ47XcXzOuj7BRV5kmOUfMGPAVQ843DNdlHyPT0UfOekJbD@zRHl/XuHYKidy@mW@AgBqZ0FEEJoYUwcFhotJkOwppHg04HgTlYSRsV5qwna4FAm16T4FgZHZDC84kbHuE8MEAVw0RLLeNzHbl5LYfqpDCXDKr5KjzjSK0oCxVCGkRo2naaOSrDRRQKNhkav7qlBfusAFYX/xTh/WmUFunILAgkDsxJqkL4zHoXxwX4AFL40UZ3N0f "Python 3 – Try It Online") ## Explanation We use a compressed string which stores the answers as ASCII values. And since multiplication is commutative, it doesn't matter in which order the two numbers appear, effectively reducing the compression size by a half. For the `.5` edge case, we assign the character with the ASCII value `127` to it. Then we apply modulo `126.5` to it. This results in `127 % 126.5` returning `.5`, but all the other values stay the same. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 86 bytes ``` §⪪§⪪”#|D⟦ⅈQ\S4,▷-³◨⟦v≔[Q!ξ№﹪⪪wQC.≡r¿I↗⎇B⁸⟧“¿*⪫Y<h\/E¿M‴$ε¬{a⸿R⁷⊙ZNU{Uⅈ⪪mδp^|⎇υO”¶⌈θ ⌊θ ``` [Try it online!](https://tio.run/##XY7BSgNBEER/pZjTLqwy3dMz6cWTxxwEwWMmhyUKLmxaDTHk78feiBdvXa@Lqjq8T6fDx7S09nya7dw9nrf2@nbtXj6X@b8KRBEjmJESRFEiNgwV5AKlarGaIt7nau5zWi0xMgqoVMtxPRiUwL@fDUhWwhks1cSjblLAI8QT1KF6ISncngokw2Oym73XO8jHEFhXt5N1j4QBoVroBzxN1/n4fey@ehcBNzTbH@ofWtvtxgG637e7y/ID "Charcoal – Try It Online") Takes input as a tuple. Explanation: ``` ”...” Compressed string of rotated lower left half of table ⪪ ¶ Split on newlines § ⌈θ Cyclically indexed by maximum of both inputs ⪪ Split on spaces § ⌊θ Cyclically indexed by minimum of both inputs Implicitly print ``` Because Charcoal is 0-indexed and the input is 1-indexed I've rotated the diagonal of the lower left half of the table to the left of the first column and then rotated the last row to above the first row so that the cyclic indexing picks up the desired result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~75~~ 71 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “µẎḂƬḌƑ®ṢṄḶ+/ḤƇ’BT3+.;Żṃ@“¦¦SȤSḢ⁺ḥȧ⁹ .rOƘ,ṃȯJƓṄƭ3ƝṁṫY-ŻḂƇS|~Ƭø’ ṀḶS+Ṃị¢ ``` A monadic Link accepting a pair of integers in \$[1..10]\$ which yields a number. **[Try it online!](https://tio.run/##AZoAZf9qZWxsef//4oCcwrXhuo7huILGrOG4jMaRwq7huaLhuYThuLYrL@G4pMaH4oCZQlQzKy47xbvhuYNA4oCcwqbCplPIpFPhuKLigbrhuKXIp@KBuSAuck/GmCzhuYPIr0rGk@G5hMatM8ad4bmB4bmrWS3Fu@G4gsaHU3x@xqzDuOKAmQrhuYDhuLZTK@G5guG7i8Ki////NCw4 "Jelly – Try It Online")** ### How? ``` “...’BT3+.;Żṃ@“...’ - Link 1, get lower left of table as a flat list: no arguments “...’ - a large number in base 250 B - convert to binary T - truthy indices 3+ - add three to them all -> all distinct values except 0 and 0.5) .; - prepend a 0.5 Ż - prepend a zero -> all 37 distinct values “...’ - a large number in base 250 ṃ@ - convert the large number to base 37 using the values as the digits -> [0, 0.5, 8, 4, 5, 10, 5, 6, 16, 32, 6, 12, 13, 25, 50, 7, 14, 12, 25, 24, 32, 8, 12, 24, 29, 40, 48, 42, 9, 18, 32, 36, 45, 50, 54, 48, 10, 19, 21, 28, 40, 72, 60, 74, 72, 9, 22, 33, 48, 60, 72, 84, 56, 81, 110] ṀḶS+Ṃị¢ - Link, get answer: list of two integers in [1..10], [a,b] Ṁ - maximum ([a,b]) Ḷ - lowered range -> [0,1,...,max(a,b)-1] S - sum these up Ṃ - minimum ([a,b]) + - add ¢ - call last Link (2) as a nilad -> lower left of table as a flat list ị - index into ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 100 bytes -2 thanks to Kevin Cruijssen. ``` •k?-…ÚêQïBJÿ}Å0ß7E'ûcŒa’н [α¡¥jεĆ3fΣòZεgǝ/ζân[Qx¯#g)zòš¤¥Ägq)†c³±!Ãæwª“‹í«“ε®™â©₂ÿQ`•ƵAв1;š¬9ǝ0šs<Jè ``` [Try it online!](https://tio.run/##AbYASf9vc2FiaWX//@KAoms/LeKApsOaw6pRw69CSsO/fcOFMMOfN0Unw7tjxZJh4oCZ0L0KW86xwqHCpWrOtcSGM2bOo8OyWs61Z8edL862w6JuW1F4wq8jZyl6w7LFocKkwqXDhGdxKeKAoGPCs8KxIcODw6Z3wqrigJzigLnDrcKr4oCczrXCruKEosOiwqnigoLDv1Fg4oCixrVB0LIxO8Whwqw5x50wxaFzPErDqP//WzEwLDEwXQ "05AB1E – Try It Online") # [05AB1E](https://github.com/Adriandmen/05AB1E), 102 bytes The number `2` never appears in the multiplication table, so I used it to compress the list of the numbers. ``` •AjĆмÁмyÌÁÅÿ‰™ªŸ∞mÇ,—.¿b!:ý₆¥p¶ço₃w`2å,3‚ĆžáààÄd±íŠH¢Xζ±-ε₁ÎZ₆ºλΓm.Óc9˜}‘UÔœ`Ÿā£ƒn¨£T•111в2¸1;¸‡0šs<Jè ``` [Try it online!](https://tio.run/##AcIAPf9vc2FiaWX//@KAokFqxIbQvMOB0Lx5w4zDgcOFw7/igLDihKLCqsW44oiebcOHLOKAlC7Cv2IhOsO94oKGwqVwwrbDp2/igoN3YDLDpSwz4oCaxIbFvsOhw6DDoMOEZMKxw63FoEjColjOtsKxLc614oKBw45a4oKGwrrOu86TbS7Dk2M5y5x94oCYVcOUxZNgxbjEgcKjxpJuwqjCo1TigKIxMTHQsjLCuDE7wrjigKEwxaFzPErDqP//WzEwLDEwXQ "05AB1E – Try It Online") ## Explanation ``` •AjĆмÁмyÌÁÅÿ‰™ªŸ∞mÇ,—.¿b!:ý₆¥p¶ço₃w`2å,3‚ĆžáààÄd±íŠH¢Xζ±-ε₁ÎZ₆ºλΓm.Óc9˜}‘UÔœ`Ÿā£ƒn¨£T•111в The huge compressed table 2¸1;¸‡ Translate all 2's into 0.5's 0š Prepend a 0 (which is removed during base conversion) s Swap up the list of indices. < Decrement both indices. J Join these indices into a single number. è Index into the table. ``` ``` [Answer] # JavaScript, ~~114~~ 113 bytes Input as `f(1)(2)`. Port of [@dingledooper's Python 3 answer](https://codegolf.stackexchange.com/a/205427/47097). ``` a=>b=>` \0   \r2    (0*  $-260\n (H<JH !0<HT8Qn`.charCodeAt((M=a>b?a:b)*~-M/2+(a<b?a:b))%126.5 ``` [Try it online!](https://tio.run/##RY/NattAEIAvzY@ECaGhIYEEptCilbNWpdVKXqeWQykBU8ih0FtsyNqxmwZjBdn5OSUv0WMeILe8U17Emdld48NqVjPffjNzre/0bFj9u5k37tRiXCx00RkUnQvoxU@bH9b8tfVtWK/1qn2xsVXb34PN2t4hi@veR/jSEHncm@58OmDd9q@ut/s5bnf/qN/Ti2h4pauf5eXox5yxs0J3Bif6eBDWHxtn38QR0237H35NRB5li@/nvncec4gyDpIDfnMOTQ6KQ4tDgpVWnyNCdbWsJwKPdBGzCaJCGM466F1CYGohgemUYoIxNaAz5a6QuYOmFHMCrVIZcNkvtUQWW53EKDMb89iQzdVUxuWaSmVfNQUdQ6rVWNTRuKgj5jJJPlxWGrJlNyQPzSXdBETRiybtmxvS7NyyO5rxXUuSEUZ3lSylgoSpleSOVEZGFJqSuO/3o3FZnerhFWNVec9hEELR8T28rwoPHLRNe8NyOisno2hS/mUajgA1QT3AZ@5e4L0azW4ncyhgbJGQmWq4qhTwACcQvD3/D@AY48trEPpe6IeLdw "JavaScript – Try It Online") ]
[Question] [ Romanization of Japanese is converting Japanese text into Latin characters. In this challenge, you will be given a string of Japanese characters as input and expected to convert them to the correct ASCII string. # What You'll Need To Know The Japanese language has three writing systems: hiragana (the curvy one used for short words), katakana (the angle-y one used for sounds and words borrowed from other langauges), and kanji (the dense characters originally from Chinese). In this challenge we will only worry about hiragana. There are 46 characters in the hiragana syllabary. Each character represents a syllable. The characters are organized by first sound (consonant) and second sound (vowel). The columns in order are `aiueo`. ``` : あいうえお k: かきくけこ s: さしすせそ t: たちつてと n: なにぬねの h: はひふへほ m: まみむめも y: や ゆ よ r: らりるれろ w: わ   を N: ん ``` (if you copy and paste this table note that I have used ideographic spaces U+3000 to space out y and w) So, for instance, あとめ should produce an output of `atome`. The first character is `a`, the second is `to`, and the third is `me`. # Exceptions Like any good language, Japanese has exceptions to its rules, and the hiragana table has several. These characters are pronounced slightly differently than their location in the table would imply: し: `shi`, not `si` ち: `chi`, not `ti` つ: `tsu`, not `tu` ふ: `fu`, not `hu` # Dakuten ゛ The word 'dakuten' means 'muddy mark': the dakuten turns sounds into their voiced equivalents (usually); for example, か `ka` turns into か゛ `ga`. A full list of the changes: `k` → `g` `s` → `z` `t` → `d` `h` → `b` The exceptions change too: し゛: `ji` (or `zhi`), not `zi` ち゛: `ji`, not `di` つ゛: `dzu`, not `du` (ふ゛ acts as you would expect; it is not an exception) The handakuten is an *additional* character ゜ that applies to the `h` row. If placed after a character, it changes the character's sound to `p` rather than `b`. Both the dakuten and handakuten are going to be given as individual characters. You will not need to deal with the precomposed forms or the combining characters. # Small Characters Finally, there are small versions of some of the characters. They modify characters that come before or after them. ゃゅょ These are the small forms of `ya`, `yu`, and `yo`. They are only placed after sounds in the `i`-column; they remove the `i` and add their sound. So, きや turns into `kiya`; きゃ turns into `kya`. If placed after `chi` or `shi` (or their dakuten-ed forms), the `y` is removed too. しゆ is `shiyu`; しゅ is `shu`. The last thing you'll have to deal with is the small `tsu`. っ doubles the consonant that comes after it, no matter what; it does nothing else. For instance, きた is `kita`; きった is `kitta`. # Summary, Input, and Output Your program must be able to transliterate: the 46 basic hiragana, their dakuten and handakuten forms, and their combinations with small characters. Undefined behavior includes: small `ya`, `yu`, and `yo` not after a character with `i`, small `tsu` at the end of a string, dakuten on an unaffected character, handakuten on a non-`p` character, and anything else not mentioned in the above spec/introduction. You may assume all inputs are valid and contain only the Japanese characters mentioned above. Case does not matter in output; you may also replace `r` with `l` or a lone `n` with `m`. Output can have either one space between every syllable or no spaces at all. **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest code in bytes wins.** # Test Cases Many test cases for each individual part are given in the spec. Some additional cases: ひらか゛な → `hiragana` かたかな → `katakana` た゛いき゛ゃくてんさいは゛ん → `daigyakutensaiban` ふ゜ろく゛らみんく゛は゜す゛るこうと゛こ゛るふ → `puroguramingupazurucoudogorufu` か゛んほ゛って → `ganbatte` # Notes * I do not know much Japanese besides what I've written here. Please let me know if I've made any mistakes. * I was originally planning to include katakana too (so my English transliteration test case could be *slightly* more accurate), but that would be too much for a code golf challenge. * The Unicode names include the transliteration of each character individually, but without the exceptions. This may or may not be helpful to you. * Thanks to squeamishossifrage for correcting two typos! * I'm sorry if this is too long; I attempted to fit most of the quirks of hiragana into the challenge but some things (like small vowel-only hiragana, changing n to m in front of some consonants, and the repetition mark) had to be cut to keep the challenge manageable. * I'm not at all sorry for the title. It's a masterpiece. [Answer] # Python 2, 638 bytes ``` import unicodedata s=input() k=[0x309B,0x309C,0x3063] m=[0x3083,0x3085,0x3087] e={0x3057:'shi',0x3061:'chi',0x3064:'tsu',0x3075:'fu'} d={0x3057:'ji',0x3061:'ji',0x3064:'dzu'} D=dict(zip('ksth','gzdb')) f=lambda c:unicodedata.name(c).split()[-1].lower()if ord(c)not in e else e[ord(c)] g=lambda c:d[c]if c in d else D[f(c)[0]]+f(c)[1:] R=[] r=[] t=[] i=0 while i<len(s): c=ord(s[i]) if c==k[0]:R[-1]=g(s[i-1]) elif c==k[1]:R[-1]='p'+R[-1][1:] elif c in m:R[-1]=R[-1][:-1];n=f(s[i]);R+=[n[1:]]if r[-1]in[0x3057,0x3061]else[n];r+=[c] elif c==k[2]:t+=[len(R)] else:R+=[f(s[i])];r+=[c] i+=1 for i in t:R[i]=R[i][0]+R[i] print ''.join(R) ``` Takes input as unicode string. Test it on [Ideone](https://ideone.com/Brx4nZ) [Answer] # Python 2, 447 bytes ``` import unicodedata as u r=str.replace i=''.join('x'*('SM'in u.name(x)or ord(x)==12444)+u.name(x)[-2:].strip()for x in raw_input().decode('utf-8')) for a,o in zip('KSTH','GZDB'): for b in'AEIOU':i=r(r(i,a+b+'xRK','P'+b),a+b+'RK',o+b) for a,b,c,d in zip('STDZ',('SH','CH','J','J'),'TDHH',('TS','DZ','F','F')):i=r(r(i,a+'I',b+'I'),c+'U',d+'U') for a in'CH','SH','J':i=r(i,a+'IxY',a) for a in'BCDFGHJKMNPRSTWYZ':i=r(i,'xTSU'+a,a+a) print r(i,'Ix','') ``` This takes Unicode input directly, which made me lose a few bytes because of the `decode('utf-8')` but I think is more in the spirit of the challenge. I began by replacing every character by the last two characters of its unicode name, as suggested in the notes of the puzzle. Unfortunately, this doesn't distinguish between alternate versions of the same character, so I had to make an ugly hack to add an 'x' before the small characters and the handakuten. The rest of the for loops are just fixing exceptions, in order: 1. the first for loop turns dakutens and handakutens into the correct consonants; 2. the second for loop deals with the hiragana exceptions of shi, chi, tsu and fu; 3. third for loop deals with the exceptions before a small y- character (like sha, jo); 4. fourth for loop deals with doubling consonants after a small tsu. 5. final line deals with small y-. I wish I could have combined more steps, but in some cases the steps have to be performed in order to avoid conflicts. [Try it online!](https://tio.run/##TY7NSsNAFIX3eYrsbsZMA5YupJCFbWzTlqo0KdKKyKRJccQmYZpgdJcsBBFx0ZXoA7hz1bUPMw8SZ9IfOjA3ufd859yJn5K7KKyXJV3EEUvUNKSzyA98khCVLNVUYeYyYQYL4gcyCxRqAhj3EQ01yOBIA2cINFRTIySLQMtQxNSI@eLHNI/rjUYD6XvpulZv3hgii8YamgswU4WTkcdbGsZpoiHDD@RmDdJkXjsBhBRJERxJ7lm4YOC4NmDoTq0WoKaiiiMRTwBweta7GEOTmkxjGsVE93TIRgOBX4Luoc1A9pHotskenmF/n@641hSw@ModbVn61UUYXMu2peQ6YiIp6FQXoYOF0APsyYrwTIcxYF/W7S75xCrT2QRXvo0rmwAmB1irbXW6dn8wPL8cOe7VZLqDIXOdMehEuAQfMxomajXvZSITUFnyfM2Lb1688/yDF1@8eOX5Hy9W2zb/lWr@WUlvPBfzF57/VNJqN1z/Aw) (a multi-line version with more examples can be found [here](https://tio.run/##TVBPa9RAFD9vPsXcXsZMAy57kIUcbNd2t0u1NFmkKyLZTZaOtEmYJjT2lqiVthTBRURa8CAUoaCnnjz4YeaDrPNeuqWHeXnv/f49kr3L99KkvVjIgyxVOSsSOU2jOArzkIWHrLCYFcUzNrNz3rVayjvMlavibD@cxlZLegDu21QmNpTwyAZ/C2TCCjcJD2K75KliqYpM43mP251Ohzv30KuVdve1a8xkZvOZIZbMKHM3ijHdhiKfrTwBzq0WgqFIET42ZBj6QR8EbIx7q4AnEWFiYHj6bPBiBF3pKVvZUoTOxIFyZ2jI2@BMeLPAOTXT0ngipiK6N/eD3hiE@WLEGpZNelxA0Ov3EQp8s0EWrNPj/EEiDEBMsHIxdWAEIsK6DMMjydRvnEnYyMpdEOFD3upab32jvzncer694wcvd8dLNpSBPwInNDIUZEomOSNgUBpXE8asoz25H7NAFbH5QTNbhUdvZJIVuc35YqGrb7r@pKsTai5Nb@nqRlc/dfVX11e6npt5jghSvuvql67PCP5MQPWbtn9Ie4om1QddGfY5NTdk@9GwdXWLtf5iIYbs@Z0Mza4txDHvgliN2T8i0YjUK4xC6JyST@iYy7vzcHlrXH7QykRf0PY9RV@T0VfaN6fO/wM)). [Answer] ## Swift 3, 67 64 characters let r={(s:String) in s.applyingTransform(.toLatin, reverse: false)} ``` let r={(s:String)in s.applyingTransform(.toLatin,reverse:false)} ``` [Answer] # [Python 3](https://docs.python.org/3/), 259 bytes ``` import re,unicodedata as u s=re.sub n=u.normalize k,*r=r'NFKC DZU DU TSU TU \1\1 SM.{6}(.) \1 (CH|J|SH)Y \1 ISMALL.(Y.) CHI TI JI [ZD]I SHI SI FU HU'.split() t=''.join(u.name(c)[16:]for c in n(k,s(' ','',n(k,input())))) while r:t=s(r.pop(),r.pop(),t) print(t) ``` [Try it online!](https://tio.run/##NVBLS@RAEL73ryjmko6EsIPgQchhmUEmvi4xBx09xJks9jrTCZ0Ovg@JL1aRAQfZlRHE9YEg6MmTB39M/5Cxu2YMlUrVV1999ZF0R24kfHIYb8ctKiqVypB100RIELGTc9ZK2nE7khFEGeQk80TsZvk64V7u8kR0ow7bjcmmMyE8YS3OzNWgvhJCPYSlQL8hrFZXqxAsuHtTB9S1dQu01tif3Q8a9rLp/GDh5/y8S5f1sNbwYcmHWR@aK/U1HwLdBz7MhNAILTdLO0xSm0jPstzfCeNUO4i6MW3ZzerU9NqvREALGAdON52MWmA5luWYhvE015vmIVsbrBODmJZeRoWbJim1ne@vtEkqGJdU2kP9H2ACqj/soSr@migHqrgzYYoHE6Z4N1EOCDIOVfEP8x3m/zoT5N6r4hHzw4h4qoqTsWZ5qqEXHH6o8kaVfd33UVtTrlXxrMozHPdwULwi@oa7f9DbkSo0@xyLF5Q91mz01lPlJTEzw@6P14zYE0Hj@t4FskZin0jC1lBvzCkzOsfLJ2hmMLZnwHetcouQPn2B6CGefkKhK8RHVvtf "Python 3 – Try It Online") ## Explanation We’re in luck with this input format! Look what happens if I pass the input through [NFKC normalization](http://unicode.org/reports/tr15/): ``` >>> nfkc = lambda x: u.normalize('NFKC', x) >>> [u.name(c) for c in 'は゛'] ['HIRAGANA LETTER HA', 'KATAKANA-HIRAGANA VOICED SOUND MARK'] >>> [u.name(c) for c in nfkc('は゛')] ['HIRAGANA LETTER HA', 'SPACE', 'COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK'] ``` The dakuten gets replaced by a space and a combining dakuten. Now that space is all that’s separating the は from its dakuten. So we get rid of it and normalize *again*: ``` >>> [u.name(c) for c in nfkc(nfkc('は゛').replace(' ', ''))] ['HIRAGANA LETTER BA'] ``` Bingo. The fifth line turns the input into something like ``` KONOSUBARASIISEKAINISISMALL YUKUHUKUWO ``` Then we apply 9 boring regex substitutions crammed in `r`, and we’re done: ``` KONOSUBARASHIISEKAINISHUKUFUKUWO ``` (Jonathan French saved 4 bytes, writing `import re,unicodedata as u` instead of `import re;from unicodedata import*`. Thanks!) [Answer] # Python3, 607 bytes: ``` def f(s): V='aiueo' v,k,d,u,w,t,l,q,g,j=(t:=b.split('\n'))[0][3:],{a:i[0]+V[j]for i in t[1:]for j,a in enumerate(i[3:])},'',0,0,0,{'し':'shi','ち':'chi','つ':'tsu','ふ':'fu'},{'し':'ji','ち':'ji','つ':'dzu'},{'k':'g','s':'z','t':'d','h':'b'},{'ゃ':'ya','ゅ':'yu','ょ':'yo'} k['ん']='n' for i in s: if i in v:d+=(w:=V[v.index(i)]) if(W:=l.get(i,k.get(i))):d+=(w:=(W[0]*(t+1)+W[1:]));t=0 if'゛'==i and u!='ふ':d=d[:-1*len(w)]+(w:=q.get(u,g.get(w[0],w[0])+w[1]));I=1 if'゜'==i:d=d[:-1*len(w)]+(w:='p'*len(w[:-1])+w[-1]) if i in j:d=d[:-1*len(w)]+(w:=w[:-1]+j[i][i in['し','ち']:]) if i=='っ':t=1 u=i return d ``` [Try it online!](https://tio.run/##bVTdShtBFL7fp5h6M7tmKgZvypZ5gL6AXmz3InY3ySRxE5NZUxXBGa1VU5E2lFK0iCgi9g@EQKHQPsx5kPScWf@qssue73znZ36/7SzrejubedbpjuflxMQEYwyMBbMJZgvMNphdrxkiNQCzB2YfzHswQ69H1Ecwn8B8BnMA5ouniToCcwzmFMwZmHMvI@oCzFcw38B8B/PDqxP1E8wlmBGYX2B@ewtE/QHzF@w6WAPWestI2U1YR3/Lfbe9LlE7YHfBDsC@A7vn9Ynap3jx2g9uRDvEZYyTtMqqfi8IPTYreUXlaZt7bEk0RSJy0RdatMSiqImG9HUo56d6nZbSPn@Z8SCIpuNoJozFaiVUiEuzUSOutrtMMZUxHZVD5zVEhfw0yxfSbkWnvqKiYE1wLqbds8pxh3jIe3XFBeJjxK@u8Cli3csdHiGu5nztpqBxm9@4TU9Wipwm4hqyPbQraDXF0NbRzhdd7Abi5QqV2jcE3UD2LcE2X/NYM0J3yGPJM9yWm8X1cLuYqhbOUpiUpN8P5Wy0NKWyJH3tqyAOXIY/F8rWVC3VvhLNwgZBcF3gz@G2Tfq6VA5Kc7RfQfBcy2lXieMecCkVq2QJy5/IYv2JTKLwaXmylWZ@P4hL1GXR9c1Fzdk@thT0CUr9qEwdX8jydcdD6vhoE97hhU8RV0vmziobj5YV6aVGpOKI0iJ3MsWhxOFNA0nTP@GhdlPJpfJYN9V5N2PJuNNVmfarPnd6OserjVfLu8Ne0oVGYVnUz8W92MBpafAwgFo6QdXgkun8/o8duVabpFQEdsPp9QzznFY3SXjE3y8buWZO3RTecVIcXrlUc0gqpxDOZ@j@C@cuNLwmRw9m78a5GpAmfIYZ438) [Answer] # [Lexurgy](https://www.lexurgy.com/sc), ~~549~~ 498 bytes Lexurgy *does* have a romanizer function that uses the rules as everything else, but it's meant more for debugging/additional output purposes and is not useful for this challenge. ``` Symbol sh,ch,ts k: {あ,い,う,え,お,か,き,く,け,こ,さ,し,す,せ,そ,た,ち,つ,て,と,な,に,ぬ,ね,の,は,ひ,ふ,へ,ほ,ま,み,む,め,も,ら,り,る,れ,ろ,や,ゆ,よ,わ,を,ん,ゃ,ゅ,ょ}=>{a,i,u,e,o,ka,ki,ku,ke,ko,sa,shi,su,se,so,ta,chi,tsu,te,to,na,ni,nu,ne,no,ha,hi,hu,he,ho,ma,mi,mu,me,mo,ra,ri,ru,re,ro,ya,yu,yo,wa,wo,n,Ya,Yu,Yo} v: {k,s,t,ch,ts,h,sh} []$1 ゛=>{g,z,d,j,dz,b,j} $1 * h []$1 ゜=>p $1 * hu=>fu s: iY=>* y iY=>*/{ch,sh,j} _ っ []$1=>$1 $1 ``` Ungolfed explanation: ``` Symbol sh, ch, ts # treat these as a single character # unfortunate kana -> latin mappings Class kana {あ,い,う,え,お,か,き,く,け,こ,さ,し,す,せ,そ,た,ち,つ,て,と,な,に,ぬ,ね,の,は,ひ,ふ,へ,ほ,ま,み,む,め,も,ら,り,る,れ,ろ,や,ゆ,よ,わ,を,ん,ゃ,ゅ,ょ} Class latin {a,i,u,e,o,ka,ki,ku,ke,ko,sa,shi,su,se,so,ta,chi,tsu,te,to,na,ni,nu,ne,no,ha,hi,hu,he,ho,ma,mi,mu,me,mo,ra,ri,ru,re,ro,ya,yu,yo,wa,wo,n,Ya,Yu,Yo} # voicing mappings Class unvoiced {k,s,t,ch,ts,h,sh} Class voiced {g,z,d,j,dz,b,j} kana-to-latin: @kana => @latin voicing: @unvoiced []$1 ゛ => @voiced $1 * # apply dakuden h []$1 ゜ => p $1 * # apply handakuden fu: # explicit exception for ふ hu => fu small-y: # small やゆよ i => * / _ Y Y => y shyu: # handle ちぢしじ y => * / {ch,sh,j} _ small-tsu: # gemination (duplication of a character) is the prototypical use-case for capturing っ []$1 => $1 $1 ``` ``` ]
[Question] [ You want to open a new zoo. It'll be amazing. But being the cheapskate that you are, you only want to afford three-letter animals (everyone knows that an animal's cost is proportional to the length of its name). There goes your dream of making people pay to see an `elephant`. But suddenly you have a brilliant idea. If you just place the animals correctly in the pen, you can create the optical illusion of an `elephant`! Here is a top-down view of your new "elephant compound": ``` elk eel pig hog ant -------- (fence) ^ | viewing direction ``` Haha, those gullible visitors! Yes, this is how perception works. ## The Challenge Given a non-empty word consisting only of lowercase English letters, determine if it can be formed from overlapping the following 30 three-letter animal words: ``` ant ape asp ass bat bee boa cat cod cow dab dog eel elk emu fly fox gnu hog ide jay kea kob koi olm owl pig rat ray yak ``` Yes, there are more than 30, but that's a nice round number. You may optionally receive this list as input (in any reasonable list or string format, as long as it's not pre-processed). You'll probably want to do this, unless reading and processing this input list is *much* more expensive than hardcoding and compressing it in your language of choice. Note that even if you take the list as input you may assume that it will always be exactly this list, so if your code relies on the passed list being 30 elements long and not containing a word with `z`, that's fine. Each word can be used multiple times. Animals cannot be cut off at the ends, only partially hidden by other animals. So `ox` is not a possible string, even though we have `fox`. Output should be [truthy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) if this is possible, and [falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) otherwise. 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. Your code should handle any of the test cases in a few seconds. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## More Examples * Any one- or two-letter word is obviously falsy. * So is any three-letter word which is not in the above list. * Even though we have `gnu` and `rat`, `gnat` is falsy since there's no way to arrange them such that you only see two letters of each (we don't want to cut animals into thirds). Some truthy examples: ``` pigment ant bee olm pig ``` ``` antioxidant fox koi ide ant ant ``` ## Test Cases Most of the test cases were taken from running a reference implementation against a dictionary. The last few "words" were generated randomly and are just there to ensure that submissions are sufficiently efficient. Truthy: ``` ant owl bass pride bobcat peafowl elephant hedgehogs crocodile antidemocrat aspidoganoidei biodegradability angioelephantiasis propreantepenultimate acategnukeaidabeleenaspcodcoidyakwakoasshogattkjaypigkobolcodidaskearaywelkwboaxbeeuflapaspoapemaassaaspeewoglmabiemuwjadogacagnuepigjaycownbatjaemuifoxkeaeekekeagratsseeluejdoghogaolmgpigbeaeelemulasphogjaydabemukgnunueifoasdoglrayyadogpewlayroassasslgnuaspyyakkbokeaodxilopgnuasppigkobelratelkolmakob koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly eolmantjkobeeaorayogaowldfoxayeassapibatmflylyraelaspsseolmbelkkaoantlmufodasgnueantaidenthyakcodoxuepigodggnuantatlcatnuuelkpemucbapeeoiahdogplkowletbatdrayarayoaelkgrayodcatgkantewkobeljaybeeyfkobtbdabadoghbatfoxtflygaspdeidogtowlkeaolmyraelfleelejayehogowlccatoxeabiemkobpigolmdkobrcidekyakabboyidep ``` Falsy: ``` a ox ram bear koala antelope albatross zookeeper salamander caterpillar hippopotamus koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeezcatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflxelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly beyeodpgspeclxlkbkaylldnceepkocbdmymsaogsowpbawbauaioluaaagaetdoaoialeoxaagspoelegflpylptylnolnatrjabaorkdteeydloiebbptatdtfdfgoodtbkoafmounbduaffcrfelcnawmxaskgaoenaattbaobgbgabnhkesbgaaaaotafkiiieatworginaeowaehuddegooaalowaoososaksahoimkulbtoadyyelkcmkacbuostadppcuglbnmotedfgfkoleldonknemomnmoutykg ``` [Answer] # Japt, ~~51~~ ~~48~~ ~~45~~ ~~36~~ ~~33~~ 19 bytes *Saved 9 bytes thanks to @PeterTaylor* ``` ;!UeVrE"[$& ]" S² x ``` [Test it online!](http://ethproductions.github.io/japt?v=89aaf4bcc3e158bd7e704da3445c344b0655856d&code=OyFVZVZyRSJbJCYgXSIgU7IgeA==&input=ImVsZXBoYW50IiAiYW50fGFwZXxhc3B8YXNzfGJhdHxiZWV8Ym9hfGNhdHxjb2R8Y293fGRhYnxkb2d8ZWVsfGVsa3xlbXV8Zmx5fGZveHxnbnV8aG9nfGlkZXxqYXl8a2VhfGtvYnxrb2l8b2xtfG93bHxwaWd8cmF0fHJheXx5YWsi) Takes input as the string to test, followed by the list of three-letter words, delimited with `|`. Note: this doesn't work in the latest version of the interpreter, so please use the link instead of copy-pasting the code. ### How it works The basic idea is to take the input string and repeatedly replace any of the 30 words in it with two filler chars. I use a space as the filler char. Also, we want to replace the `ant` in `elephant`, the `a` in `ela`, the `nt` in `e   nt`, etc. So what we want to do is to change the 30-word string to a regex that matches any of these combinations: ``` ant|ape|asp|... Becomes: [a ][n ][t ]|[a ][p ][e ]|[a ][s ][p ]|... ``` We can do this pretty easily: ``` ;VrE"[$& ]" // Implicit: V = "ant|ape|asp|..." ; // Set the vars A-J to various values. E is set to "[a-z]". VrE // Take V and replace each lowercase letter with: "[$& ]" // "[" + the char + " ]". ``` However, this has the undesired effect of also matching three spaces, which has no effect on the result and thus ends the recursive replacement. We can get around this by replacing the match with two spaces instead of three: ``` Ue S² // Take U, and recursively replace matches of the regex with " ".repeat(2). ``` Here's a basic demonstration of how and why this works (using `.` in place of a space): ``` First match at the end: eleant ele.. (ant) el.. (eel) ... (elk) .. (...) true First match at the beginning: antmua ..mua (ant) ...a (emu) ..a (...) .. (boa) true First match in the middle: cantay c..ay (ant) ..ay (cat) ... (jay) .. (...) true ``` For truthy test-cases, this leaves us with a string of all spaces. For falsy test-cases, we have some letters left in the mix. This can be translated to true/false like so: ``` x // Trim all spaces off the ends of the resulting string. ! // Take the logical NOT of the result. // Empty string -> true; non-empty string -> false. ``` And that's about it! A bonus of this method is that even the largest test cases finish in under 5 milliseconds. ([Tested here](http://ethproductions.github.io/japt?v=89aaf4bcc3e158bd7e704da3445c344b0655856d&code=O0M90DshVWVWckUiWyQmIF0iIFOyIHg7IlRvdGFsOiB70CAtQ30gbXM=&input=ImVvbG1hbnRqa29iZWVhb3JheW9nYW93bGRmb3hheWVhc3NhcGliYXRtZmx5bHlyYWVsYXNwc3Nlb2xtYmVsa2thb2FudGxtdWZvZGFzZ251ZWFudGFpZGVudGh5YWtjb2RveHVlcGlnb2RnZ251YW50YXRsY2F0bnV1ZWxrcGVtdWNiYXBlZW9pYWhkb2dwbGtvd2xldGJhdGRyYXlhcmF5b2FlbGtncmF5b2RjYXRna2FudGV3a29iZWxqYXliZWV5ZmtvYnRiZGFiYWRvZ2hiYXRmb3h0Zmx5Z2FzcGRlaWRvZ3Rvd2xrZWFvbG15cmFlbGZsZWVsZWpheWVob2dvd2xjY2F0b3hlYWJpZW1rb2JwaWdvbG1ka29icmNpZGVreWFrYWJib3lpZGVwIiAiYW50fGFwZXxhc3B8YXNzfGJhdHxiZWV8Ym9hfGNhdHxjb2R8Y293fGRhYnxkb2d8ZWVsfGVsa3xlbXV8Zmx5fGZveHxnbnV8aG9nfGlkZXxqYXl8a2VhfGtvYnxrb2l8b2xtfG93bHxwaWd8cmF0fHJheXx5YWsi)) [Answer] # GNU grep, 62 + 1 = 63 bytes ``` ^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz]\B)?)+ ``` This requires the `P` option. The input is expected to be the animal to be synthesized, followed by a space, followed by the list of 3-letter animals opened, closed, and delimited by exclamation marks. Example usage (assuming the program is saved as `zoo`): ``` > grep -Pf zoo hippopotamus !ant!ape!asp!ass!bat!bee!boa!cat!cod!cow!dab!dog!eel!elk!emu!fly!fox!gnu!hog!ide!jay!kea!kob!koi!olm!owl!pig!rat!ray!yak! ``` For a true input, the input line is echoed back. For a false input, there is no output. Thanks to Martin for spotting a bug and alerting me to the existence of `\B` for word non-boundary. [Answer] ## ES6, ~~122~~ ~~121~~ ~~119~~ 104 bytes I had worked out how to do this as far as ETHproduction's answer but couldn't think of how to handle the `,,,`\* problem, so naturally when I saw Peter Taylor's comment it all became clear. Then ETHproductions managed to find a better way to handle the problem which helpfully saves 15 bytes. Input is the target word and an array of animal words. ``` (s,a)=>[...s].map(_=>s=s.replace(RegExp(a.map(a=>a.replace(/./g,"[&$&]")).join`|`),'&&'))&&!/\w/.test(s) ``` Edit: Saved ~~1 byte~~ 3 bytes thanks to @ETHproductions. \*Except I used &s because it looks nicer in my `replace`. [Answer] # JS ES6, 77 bytes ``` s=>/^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz][^\b])?)+/.test(s) ``` (this is anonymous fn) Input is the same as the above grep example input ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/6887/edit). Closed 8 years ago. [Improve this question](/posts/6887/edit) Write programs that produce crazy, obscure, ridiculous, or just plain nutty runtime errors. Obfuscation and golfitude (shortness) not required. * solutions that look like they should work fine are better. * solutions that look like they should break one way but break another are better. * solutions that are nondeterministic are better as long as they are reproducible sometimes. * solutions with long distance between error cause and manifestation are better. * bonus points for producing errors that should be impossible. * bonus points for errors that crash the runtime (like making python segment fault) or operating system. The unit of score shall be upvotes. **Addendum 1** Compiler misbehaviors are fine too. [Answer] The obligatory PHP one (which *still* hasn't been fixed as of 5.4): ``` <?:: ``` Outputs: ``` Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM on line 1 ``` Whaa? [Answer] Gcc compile error: ``` int main() { long long long a; } ``` error: long long long is too long for GCC [Answer] ## Windows Command Prompt ``` If you're happy and you know it clap your hands! ``` Output: > > happy was unexpected at this time. > > > [Answer] # PHP ``` $ cat error.php <?php function echo_string(string $string) { echo $string; } echo_string("Hello, world!"); $ php error.php PHP Catchable fatal error: Argument 1 passed to echo_string() must be an instance of string, string given, called in error.php on line 5 and defined in error.php on line 2 ``` You cannot pass a string to a function, you have to pass a string instead! **Update:** This code is NOT an error in PHP 7. Hover on/click/touch a spoiler to check why (contains spoilers about how the code works). > > A new feature known as [scalar type declarations](https://secure.php.net/manual/en/migration70.new-features.php#migration70.new-features.scalar-type-declarations) was added in PHP 7. This feature allows using scalar types in function declarations. > > > [Answer] # bash ``` $ echo "Hello, world!" bash: !": event not found ``` And you would think that bash would accept a simple "Hello, world!" program. [Answer] # Python 2.7 ``` # Look I'm actually coding: see my happy face? print ':)' ``` Generates the rather unhelpful: ``` SyntaxError: encoding problem: with BOM ``` How can a simple comment generate an error? [Answer] ## Mathematica When using Mathematica to create graphical output, one sometimes triggers error messages formatted according to specifications being used in the program itself. Here is a trivial example. ``` Rotate[f/0, .6] ``` ![enter image description here](https://i.stack.imgur.com/ATksK.png) [Answer] ## [TI-89 Graphing Calculator](https://en.wikipedia.org/wiki/TI-89_series) I discovered this when learning about implicit differentiation in high school calculus. If you input: ``` d(xy+x=0,x) ``` You get the following: ``` 1 = 0 ``` With this caveat, printed in tiny letters at the bottom of the screen: ``` Warning: May produce false equation ``` This happens because `xy` is not interpreted as `x * y`, but rather as its own symbol, `xy`. Oddly, if you do `d(xy=0,x)`, you get `0 = 0` with the same warning. [Answer] You can make the Haskell compiler's brain explode: ``` C:\Windows\system32>ghci ... Prelude> :set -XExistentialQuantification Prelude> data Foo = forall a. Foo a Prelude> let foo f = 1 where Foo a = f <interactive>:4:21: My brain just exploded I can't handle pattern bindings for existential or GADT data constructors. Instead, use a case-expression, or do-notation, to unpack the constructor. In the pattern: Foo a In a pattern binding: Foo a = f In an equation for `foo': foo f = 1 where Foo a = f Prelude> ``` [Answer] ## Ruby Rules abuse. ``` class StandardError def to_s words = File.open('/usr/share/dict/words'){|f|f.readlines.map &:chop}.sample(100) words.last.capitalize! super.gsub(/\w+/){words.pop} end to_s(3) end ``` If run on OSX, produces, e.g. ``` $ ruby weird_runtime_error.rb weird_runtime_error.rb:9:in `to_s': Sculpturation contingence explicate tappet(phonendoscope ethopoeia nannandrous) (ArgumentError) from weird_runtime_error.rb:9:in `<class:StandardError>' from weird_runtime_error.rb:1:in `<main>' ``` [Answer] **DOS Prompt** ``` c:\>make love ``` gives you ``` Fatal Error: 'love' does not exist. Don't know how to make it. ``` Stumbled upon this while I was trying to insult my computer for being uncooperative. Made me kinda sad for a while until I found out, that this only happens if love does not exist. If it exists he will gladly make it. [Answer] # Bash (Quine error) This error is a Quine in Bash! ``` $ bash: bash:: command not found... bash: bash:: command not found... ``` Of course you must have the relevant `locale` (english here). [Answer] # CSH A really classical `csh` joke: ``` % make fire? make: No match. ``` [Answer] # Bash - accurate recreation of a [rare historical error message](https://en.wikipedia.org/wiki/Lp0_on_fire) ``` echo -ne $(tail -n +257 /usr/src/linux*/drivers/char/lp.c | head -1 | cut -d '"' -f 2 | sed 's/%d/0/') ``` Output: ``` lp0 on fire ``` Requires the linux kernel source to be unpacked in the usual place. Fun fact: i once received this message in earnest, when running an old ribbon printer. [Answer] ## Ruby Feel like it's weird that this can happen in a high-level language. ``` $*<<$*<<$**$/ ``` produces ``` ArgumentError: recursive array join ``` [Answer] ## C(++) If compile-time errors count here's one (assuming a file named "crash.c"). ``` #include "crash.c" int main(){ return 0; } ``` It fills the screen with this upon compilation (have Ctrl-C ready) ``` from crash.c:1, from crash.c:1: crash.c:3:1: error: redefinition of ‘main’ crash.c:3:1: note: previous definition of ‘main’ was here In file included from crash.c:1:0, from crash.c:1, from crash.c:1, ``` Another snippet which compiles perfectly well (no warnings under `-Wall` and illustrates the beautiful type safety of C </s> ``` #include <stdio.h> int i; int main(){ sprintf(NULL, "%s", (char *) (void *) (1/i)); return 0; } ``` Running it gives: ``` Floating point exception (core dumped) ``` [Answer] This is very old, but for those who remember BCPL, ``` GET "LIBHDR" LET START() = VALOF $8 RESULTIS 0 $) ``` would complain ``` $8 ^ "( ) or 8 expected" ``` [Answer] # R This is technically not an error but a warning but nevertheless it's ridiculous, and occurs for completely esoteric reasons. [[EDIT]] It seems that the cause of some parts of the funny warnings resides in RStudio rather than R per se, so it's less interesting than I first thought. The first example i.e `plot(1:2, NotAGraphicalParameter = "ignore.me")` is, however, still reproducible in "naked" R and is funny enough on its own right.[[/EDIT]] ``` > plot(1:2, NotAGraphicalParameter = "ignore.me") # produces a nice scatterplot with two points, [1,1] and [2,2] Warning messages: 1: In plot.window(...) : "NotAGraphicalParameter" is not a graphical parameter 2: In plot.xy(xy, type, ...) : "NotAGraphicalParameter" is not a graphical parameter 3: In axis(side = side, at = at, labels = labels, ...) : "NotAGraphicalParameter" is not a graphical parameter 4: In axis(side = side, at = at, labels = labels, ...) : "NotAGraphicalParameter" is not a graphical parameter 5: In box(...) : "NotAGraphicalParameter" is not a graphical parameter 6: In title(...) : "NotAGraphicalParameter" is not a graphical parameter > plot(2:3) # another nice scatterplot: [2,2] and [3,3] # but there should be nothing wrong this time! # however ... There were 12 warnings (use warnings() to see them) > warnings() Warning messages: 1: "NotAGraphicalParameter" is not a graphical parameter 2: "NotAGraphicalParameter" is not a graphical parameter 3: "NotAGraphicalParameter" is not a graphical parameter 4: "NotAGraphicalParameter" is not a graphical parameter 5: "NotAGraphicalParameter" is not a graphical parameter 6: "NotAGraphicalParameter" is not a graphical parameter 7: "NotAGraphicalParameter" is not a graphical parameter 8: "NotAGraphicalParameter" is not a graphical parameter 9: "NotAGraphicalParameter" is not a graphical parameter 10: "NotAGraphicalParameter" is not a graphical parameter 11: "NotAGraphicalParameter" is not a graphical parameter 12: "NotAGraphicalParameter" is not a graphical parameter # but let's try once more: > plot(2:3) # yup. no warnings this time. we had to do it twice ``` It's like R remembers our insults. But not for long. I can't really explain why this happens - but it is reproducible. Actually it occurs every time when you supply some "not a graphical parameter" to plot 1, and then do a plot 2 in a completely impeccable way. It is especially funny that we get 12 "not a graphical parameter" warnings for the second plot but only 6 for the first one. Another funny thing is that if you supply "not a graphical parameter" with a value NULL then no condition is thrown: ``` plot(1:2, Nonsense=NULL) # no warnings # however plot(1:2, Nonsense="gibberish") # gives the usual 6-pack of warnings ``` And to get even more ridiculous, let's draw some lines on top of the previously drawn plot: ``` plot(1:2) # you will see the number of warnings growing with each line: lines(1:2, 1:2, mumbo = 1) lines(1:2, 1:2, jumbo = 2) lines(1:2, 1:2, bimbo = 3) lines(1:2, 1:2, cucaracha = 4) lines(1:2, 1:2, karaoke = 5) lines(1:2, 1:2, radiogaga = 6) lines(1:2, 1:2, reptiles = 7) lines(1:2, 1:2, cowsonmoon = 8) lines(1:2, 1:2, stainlessSteelLadderToTheMoon = 9) lines(1:2, 1:2, frambuesa = 10) lines(1:2, 1:2, fresa = 11) lines(1:2, 1:2, limonYNada = 12) lines(1:2, 1:2, slingsAndArrows = 13) # ... and now you have 25 warnings: warnings() Warning messages: 1: "mumbo" is not a graphical parameter 2: "jumbo" is not a graphical parameter 3: "bimbo" is not a graphical parameter 4: "cucaracha" is not a graphical parameter 5: "karaoke" is not a graphical parameter 6: "radiogaga" is not a graphical parameter 7: "reptiles" is not a graphical parameter 8: "cowsonmoon" is not a graphical parameter 9: "stainlessSteelLadderToTheMoon" is not a graphical parameter 10: "frambuesa" is not a graphical parameter 11: "fresa" is not a graphical parameter 12: "limonYNada" is not a graphical parameter 13: "mumbo" is not a graphical parameter 14: "jumbo" is not a graphical parameter 15: "bimbo" is not a graphical parameter 16: "cucaracha" is not a graphical parameter 17: "karaoke" is not a graphical parameter 18: "radiogaga" is not a graphical parameter 19: "reptiles" is not a graphical parameter 20: "cowsonmoon" is not a graphical parameter 21: "stainlessSteelLadderToTheMoon" is not a graphical parameter 22: "frambuesa" is not a graphical parameter 23: "fresa" is not a graphical parameter 24: "limonYNada" is not a graphical parameter 25: In plot.xy(xy.coords(x, y), type = type, ...) : "slingsAndArrows" is not a graphical parameter ``` ~~This should~~ not ~~win big time unless there is no justice.~~ [Answer] ## Windows Command Script *WARNING, this is a fork bomb!* This will output garbage questions about quitting if you try to quit the console in any way. ``` %0|%0|%0 ``` Bonuses: * Will make the system pretty much unusable until restart * Prevents quitting the script, which should be impossible [Answer] How about compiler optimisation errors: ``` #include <stdio.h> #define N 4 int main(void) { int sum; int i; int arr[N]; for (i = 0, sum = 0; i < N; i++, arr[i] = sum) { sum += arr[i]; } printf("%d\n", sum); return 0; } ``` This is specific to gcc >= 4.7. Compiles and runs fine with `gcc -O0 -Wall`. Compiles with `gcc -O2 -Wall` but results in an inf-loop. Also note, how gcc does see the problem for smaller `N`, e.g. `N = 3`: ``` test.c:11:38: warning: array subscript is above array bounds [-Warray-bounds] for (i = 0, sum = 0; i < N; i++, arr[i] = sum) { ^ test.c:12:13: warning: 'arr[0]' is used uninitialized in this function [-Wuninitialized] sum += arr[i]; ^ ``` Btw, this has been taken from a bug report, I can't recall the bug number though. [Answer] # [q](https://en.wikipedia.org/wiki/Q_%28programming_language_from_Kx_Systems%29) insults you ``` q)`u#1 1 'u-fail q) ``` > > ```u#`` tells `q` that every element in a list is unique (so it can build some sort of hash-based index, presumably). this is what happens when it's not actually true. > > > [Answer] I've always liked this weirdness in APL: ``` ⍝ obviously a syntax error { (] } 3 SYNTAX ERROR {(]}3 ⍝ but: { (] } 1÷0 DOMAIN ERROR {(]}1÷0 ⍝ it even works with statically defined functions ∇z←f x [1] z←[{]}x [2] ∇ f 1÷0 DOMAIN ERROR f 1÷0 ∧ f 3 SYNTAX ERROR f[1] z←[{]}x ``` It parses the inside of functions lazily! [Answer] # Python ## Nested blocks ``` for a in range(26): for b in range(26): for c in range(26): for d in range(26): for e in range(26): for f in range(26): for g in range(26): for h in range(26): for i in range(26): for j in range(26): for k in range(26): for l in range(26): for m in range(26): for n in range(26): for o in range(26): for p in range(26): for q in range(26): for r in range(26): for s in range(26): for t in range(26): for u in range(26): for v in range(26): for w in range(26): for x in range(26): for y in range(26): for z in range(26): print a ``` Python 2.7: `SystemError: too many statically nested blocks` ## Self-referencing lists ``` def printList(myList): for element in myList: if isinstance(element, list): printList(myList) else: print(element) a = [] a.append(a) printList(a) ``` # Python 2.7 ## True is not a constant The problem in the following example is that in Python 2.7, `True` and `False` are not constants. And `True` and `False` can automatically get casted to `1` and `0`: ``` True=False a=10/True Traceback (most recent call last): File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module> exec(sys.stdin.read()) File "<string>", line 2, in <module> ZeroDivisionError: integer division or modulo by zero ``` # Python 2.7: ## Intendation ``` def f(n): if n <= 1: return n else: return f(n-1)+f(n-2) ``` Do you get the error? ``` Traceback (most recent call last): File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module> exec(sys.stdin.read()) File "<string>", line 4 else: ^ SyntaxError: invalid syntax ``` Mixing tabs and spaces was ok in Python 2.7 ... but mind the indentation level! [Answer] # PHP ``` <?php [][] = 42; ``` `[]` is used in order to push elements. However, if you use it for array literal, the PHP makes crazy error message, even if you assign to it in order to push. Requires PHP >= 5.4, as before that you couldn't have indexed array literals. Output: > > **Fatal error**: Cannot use [] for reading in **[...][...]** on line **2** > > > [Answer] I'll start: ``` #include <iostream> using namespace std; class A { public: A() { } void doSomethingDiabolical() { delete this; } virtual void breakHorribly() { cout << "still alive" << endl; doSomethingDiabolical(); cout << "still alive" << endl; } }; class B : public A { public: B() : A() { } void breakHorribly() { cout << "still alive" << endl; ((A *) this)->breakHorribly(); cout << "still alive" << endl; doSomethingDiabolical(); cout << "still alive" << endl; breakHorribly(); cout << "dead" << endl; } }; int main() { jane(); } void jane() { cout << "still alive" << endl; A * o = new B; cout << "still alive" << endl; o->breakHorribly(); } ``` Any guesses why this program crashes? :D See `jane` run: <http://ideone.com/gtaZ3> [Answer] ## CPython ``` import ctypes import sys (ctypes.c_char * sys.getsizeof(None)).from_address(id(None))[:4] = '\x00' * 4 ``` The result: ``` Fatal Python error: deallocating None This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. ``` [Answer] # Bash I got this today when I tried to find out whether it is possible to protect the system from `rm -rf /`. ``` mkdir /tmp/a mkdir /tmp/a/b sudo mount --bind /tmp/a /tmp/a/b rm -rf /tmp/a ``` The error message with `LANG=C`: ``` rm: WARNING: Circular directory structure. This almost certainly means that you have a corrupted file system. NOTIFY YOUR SYSTEM MANAGER. The following directory is part of the cycle: '/tmp/a/b' ``` [Answer] # TeX This simple TeX program: ``` \def~{x~}~ ``` gives the following error in the log file: ``` ! TeX capacity exceeded, sorry [main memory size=5000000]. l.1 \def~{x~}~ If you really absolutely need more capacity, you can ask a wizard to enlarge me. ``` You better know which wizard it the right wizard :-) --- # TeX: second error message This is a small LaTeX table with 260 columns, for which we want a cell that spans all the columns. ``` \documentclass{article} \begin{document} \begin{tabular}{*{260}{l}} \multicolumn{260}{c}{Table Title} \end{tabular} \end{document} ``` The error message is also hilarious: ``` ! This can't happen (256 spans). <template> \endtemplate l.5 \end{tabular} I'm broken. Please show this to someone who can fix can fix ``` How many programs are humble enough to admit they are broken? [Answer] # R Another one which is not ridiculous and, again, a warning rather than an error, but still nice: ``` > sapply(as.list(-1:-51), log) [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN [20] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN [39] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN There were 50 or more warnings (use warnings() to see the first 50) ``` I like the last bit: 50 or more :) And the actual warnings: ``` 1: In lapply(X = X, FUN = FUN, ...) : NaNs produced 2: In lapply(X = X, FUN = FUN, ...) : NaNs produced .... 50: In lapply(X = X, FUN = FUN, ...) : NaNs produced ``` FUN = FUN! [Answer] # Bash - counterintuitive escape failure ``` echo "this should definitely work!!!11!" ``` returns ``` -bash: !11: event not found ``` (history expansion on the commandline is not prevented by double quotes) ## Bonus: ``` echo "I don't know what's gone wrong!! !echo is usually pretty foolproof!-1" ``` The output is unlikely to be what's expected. Press **up** to get the command again, and notice it's changed from what you typed. If you press up and enter a couple of times, it's likely your output will begin to look somewhat horrific. Try it for yourself. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 9 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. The problem: > > I am the lead developer for a big company, we are making Skynet. I have been assigned to > > > > > > > Write a function that inputs and returns their sum > > > > > > > > > **RULES:** No answers like ``` function sum(a,b){ return "their sum"; } ``` **EDIT: The accepted answer will be the one with the most upvotes on January 1st, 2014** Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules"). [Answer] > > That's a very complex problem! Here is how you solve it in C#: > > > > ``` > static int Sum(int a, int b) > { > var aa = ((a & ~877 - b ^ 133 << 3 / a) & ((a - b) - (a - b))) | a; > var bb = ((b ^ (a < 0 ? b : a)) & ((b - a) - (b - a))) | b; > var cc = new List<int>(); > for (int i = 6755 & 1436; i < aa; i -= -1) > { > cc.Add((int)Convert.ToInt32(Math.Sqrt(6755 & 1437 >> ((b - a) - (b - a))))); > } > for (int i = 6755 & 1436; i < bb; i -= -1) > { > cc.Add((int)Convert.ToInt32(Math.Sqrt(6755 & 1437 >> ((a - b) - (a - b))))); > } > Func<int,int,int> importantCalculation = null; > importantCalculation = (x, y) => y != 0 ? importantCalculation(x ^ y | (6755 & 1436) >> (int)(Convert.ToInt32(Math.Sqrt((b - a) - (b - a) - (-1))) - 1), (x & y) << (int)Convert.ToInt32((Math.Log10(1) + 1))) : x; > return cc.Aggregate(importantCalculation); > } > > ``` > > --- --- How this code works (I wouldn't add this explanation in my answer to the lazy OP that has to be trolled, don't worry): `((a & ~877 - b ^ 133 << 3 / a) & ((a - b) - (a - b))) | a` returns just `a` and `((b ^ (a < 0 ? b : a)) & ((b - a) - (b - a))) | b` returns just `b`. `6755 & 1436` returns `0`, so in the loop, `i` actually starts with value `0`, and inside the loop, you add the value `1` to the list. So, if `a` is `5` and `b` is `3`, the value `1` is added 8 times to the list. The `importantCalculation` function is a very long function that does nothing else than adding up two numbers. You use the LINQ `Aggregate` function to add up all numbers. It's also unnecessary to cast the result of `Convert.ToInt32` to an `int`, because it is already an `int`. This code is something that the lazy OP wouldn't understand, which is exactly the intension :-) [Answer] # Bash - 72 bytes Sometimes traditional deterministic addition techniques are too precise, and unnecessarily fast - there are times when you want to give the CPU a bit of a rest. Introducing the **lossy SleepAdd algorithm**. ``` #!/bin/bash (time (sleep $1;sleep $2)) 2>&1|grep re|cut -dm -f2|tr -d s ``` Sample run: ``` > ./sleepadd.sh 0.5 1.5 2.001 ``` This function is intended as a companion to the well-regarded [SleepSort](https://codegolf.stackexchange.com/questions/16226/trolling-homework-questions-sorting/16316#16316). It is left as an exercise to the reader to adapt this algorithm to make a lossy SleepMax to obtain the greater of two numbers. Pro Tip: This algorithm can be further optimised - a 2x speed increase is possible, if the numbers given to it are divided by 2 first. [Answer] # Java ``` public static void int sum(int a, int b) { try { File file = File.createTempFile("summer", "txt"); FileOutputStream fos = new FileOuptutStream(file); for (int i = 0; i < a; ++i) fos.write(1); for (int i = 0; i < b; ++i) fos.write(1); fos.flush(); fos.close(); return file.length(); } catch(Throwable t) { return sum(a, b); // Try again! } } ``` This basically writes a file with the number of bytes that should be equal to the actual sum. When the file is written, it asks the disk file table for the size of that file. [Answer] # C In the quantum world you cannot depend on atomic operators like `+`, here's my implementation of addition in terms of quantum computing: ``` #define DEPENDING ( #define ON #define EVERYTHING 32 #define DEFINED ) #define AS ON #define WITH { #define SOON if #define FIX AS #define TO = #define REPEAT for( #define SUBPOSED >> #define SUPERPOSITION int #define ADJUSTED << #define APPROACHES < #define SUBPOSITION ++ #define MATCHES & #define LEVEL DEPENDING #define OF FIX #define BY FIX #define CONTINUUM 1 #define VOID ~-CONTINUUM #define SUPERPOSED | #define DO DEFINED WITH #define CURVATURE } #define ITSELF FIX #define OTHERWISE CURVATURE else WITH #define RETURN return SUPERPOSITION ADD DEPENDING ON SUPERPOSITION SUPER_A, SUPERPOSITION SUPER_B DEFINED WITH FIX SUPERPOSITION A TO SUPER_A; FIX SUPERPOSITION B TO SUPER_B; FIX SUPERPOSITION RESULT TO VOID; FIX SUPERPOSITION CARRY TO VOID; FIX SUPERPOSITION I TO VOID; REPEAT FIX I TO VOID; I APPROACHES EVERYTHING; FIX I SUBPOSITION DEFINED WITH AS SOON AS LEVEL OF CARRY MATCHES CONTINUUM DO AS SOON AS LEVEL OF A SUBPOSED BY I MATCHES CONTINUUM DO AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I; FIX CURVATURE OF CONTINUUM; OTHERWISE AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO FIX VOID; // yes, you never know what could go wrong OTHERWISE FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I; FIX CARRY TO VOID; FIX CURVATURE OF CONTINUUM; FIX CURVATURE OF CONTINUUM; // twice to make sure OTHERWISE AS SOON AS LEVEL OF A SUBPOSED BY I MATCHES CONTINUUM DO AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO FIX CARRY TO CONTINUUM; OTHERWISE FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I; FIX CURVATURE OF CONTINUUM; OTHERWISE AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I; FIX CURVATURE OF CONTINUUM; FIX CURVATURE OF CONTINUUM; FIX CURVATURE OF CONTINUUM; FIX CURVATURE OF CONTINUUM; // we did some stuff there, sure the curvature needs a lot of fixing FIX VOID; // clean up after ourselfves RETURN LEVEL OF SUPERPOSITION DEFINED AS RESULT; FIX CURVATURE OF ITSELF ``` [Answer] # Haskell Computes the correct solution in *O(n^2)* time. Based on [applicative functors](https://en.wikibooks.org/wiki/Haskell/Applicative_Functors) that also implement `Alternative`. ``` {- Required packages: - bifunctor -} import Control.Applicative import Data.Foldable import Data.Traversable import Data.Bifunctor import Data.Monoid -- Note the phantom types data Poly n a = X n (Poly n a) | Zero deriving (Show) twist :: Poly n a -> Poly n b twist Zero = Zero twist (X n k) = X n (twist k) instance Functor (Poly n) where fmap _ = twist instance Bifunctor Poly where second = fmap first f Zero = Zero first f (X n k) = X (f n) (first f k) -- Poly is a left module: (<#) :: (Num n) => n -> Poly n a -> Poly n a (<#) = first . (*) instance (Num n) => Applicative (Poly n) where pure _ = X 1 empty Zero <*> _ = empty (X n k) <*> q = (twist $ n <# q) <|> (X 0 (k <*> q)) instance (Num n) => Alternative (Poly n) where empty = Zero Zero <|> q = q p <|> Zero = p (X n p) <|> (X m q) = X (n + m) (p <|> q) inject :: (Num n) => n -> Poly n a inject = flip X (X 1 Zero) extract :: (Num n) => (Poly n a) -> n extract (X x (X _ Zero)) = x extract (X _ k) = extract k extract _ = 0 -- The desired sum function: daSum :: (Traversable f, Num n) => f n -> n daSum = extract . traverse inject ``` Example: `daSum [1,2,3,4,5]` yields 15. --- **Update:** How it works: A number *a* is represented as a polynomial *x-a*. A list of numbers *a1,...,aN* is then represented as the expansion of *(x-a1)(x-a2)...(x-aN)*. The sum of the numbers is then the coefficient of the second highest degree. To further obscure the idea, a polynomial is represented as an applicative+alternative functor that doesn't actually hold a value, only encodes the polynomial as a list of numbers (isomorphic to `Constant [n]`). The *applicative* operations then correspond to polynomial multiplication and the *alternative* operations to addition (and they adhere to *applicative/alternative* laws as well). The sum of numbers is then computed as mapping each number into the corresponding polynomial and then traversing the list using the `Poly` applicative frunctor, which computes the product of the polynomials, and finally extracting the proper coefficient at the end. [Answer] You want to **add numbers**?!? You are aware that this is a very complicated action? OK, on the other hand, you are the lead developer, you will have to face problems like this. This is the simplest solution I could find: ``` int add_nums(int n1, int n2) { int res, op1, op2, carry, i; i = 32; while (i --> 0) { op1 = 123456 ^ 123457; op2 = 654321 ^ 654320; op1 = (n1 & op1) & op2; op2 = (n2 & op2) & (123456 ^ 123457); res = (res & (0xFFFF0000 | 0x0000FFFF)) | ((op1 ^ op2) ^ carry); carry = op1 & op2; res = res << 1; } return res; } ``` Don´t fall prey to the operator "+", it is totally inefficient. Feel free to turn the "goes towards" operator around or use it for smaller numbers getting bigger. [Answer] # NODE.JS - SUMMMMYYMYYMY EDITION / IBM® Javascript Enterprise SUM Solution™ Wow, this a extremely hard question, but I will try my best to answer this. ## STEP ONE - TELNET Server First we are going to have to receive the input, now any pro and enterprise coder (like me) should know the best way to receive input is to set up a telnet server!!! Lets start off with the basic telnet server: ``` // Load the TCP Library net = require('net'), ibm = {}, fs = require('fs'), clients = []; //CREATES TEH TCP SEVA FOR INPUT //COMMAND SUM and OBJECT (a, b, c, etc..) IS ONLY ELIGBLE net.createServer(function (socket) { clients.push(socket); socket.write("WELKOME TO TEH SUM SEVA XD\n"); socket.on('data', function (data) { ccc = [0,0,0,0,0,0,0]; if(!socket.needarray){ newdata = ibm.CLEANSOCKET(data); if(newdata && newdata != '\b'){if(socket.nowdata){socket.nowdata += newdata}else{socket.nowdata = newdata}}else{ if(socket.nowdata){ if(socket.nowdata.replace(' ', '') == ('SUM')){ socket.write("Enter teh numbers\n"); socket.needarray = 1; } console.log(socket.nowdata); socket.nowdata = null; }} }else if(newdata == '\b'){ socket.array = socket.array[socket.array.length - 1] }else{ arraychar = ibm.CLEANARRAY(data); if(arraychar != ('\n' || '\b')){if(socket.array){socket.array += arraychar}else{socket.array = arraychar}}else if(arraychar == '\b'){ socket.array = socket.array[socket.array.length - 1] }else{ socket.write("Your sum: "+summm(socket.array)); socket.end(); } } }); }).listen(23); ibm.CLEANSOCKET = function(data) { return data.toString().replace(/(\r\n|\n|\r)/gm,""); } ibm.CLEANARRAY = function(data) { return data.toString().replace(/(\r)/gm,""); } ``` There really isn't anything special to it, this is you typical telnet server. We've created some basic UNICODE cleaning functions to get us a nice raw string and we've also added our `SUM` function. Now the user will have to enter 'SUM'. It will then prompt for them to enter `teh numberz`, once entered the summm() function is run and will calculate the sum of all the numbers entered. ## STEP TWO - summm It's now time to create our `summm` function which will get the sum of all numbers inputted. Here is the code: ``` //DOOOO SUMMMMM STAPH function summm(string){ //Cleans out the string by converting it from unicode to base64 and then ASCII stringa = (new Buffer((new Buffer(string).toString('base64')), 'base64').toString('ascii')); //We will now convert our string to a new string with the format CHAR_ASCII_CODE + '.', etc... x = '', c = 0; stringa.split('').forEach(function (i){ c++; x += i.charCodeAt(0); if (c != stringa.length){x+= '.';} }) stringb = x; m = ''; stringb.split('.').forEach(function (i) { m += String.fromCharCode(i); }); stringc = m; stringd = stringc.split(','); var stringsa; string.split(',').forEach( function (i) { if(!stringsa){stringsa = parseInt(i);}else{stringsa += parseInt(i);} }); return stringsa; } ``` And there you go. Its your everyday IBM Solution. **TELNET POWER ALL THE WAY!** First you enter SUM. The server will then ask for the numbers you would like to add, and you can enter them as such: `a, b, c, etc..` Trust me on this one, all the botnet's are using IBM® Javascript Enterprise SUM Solution™ these days ;). And here is proof that everything works: [![SUMM](https://i.stack.imgur.com/vyUbWl.png)](https://i.stack.imgur.com/vyUbW.png) (CLICKABLE) [Answer] Here's a solution in Java for you. It relies on the time-tested "infinite monkeys theorem": if you are in a room with infinite monkeys, you will end up covered in thrown poop. Or something like that. ``` public static int sum(int a, int b){ if(a==0)return b; Random r=new Random(); int number=r.nextInt(); if(number>a){ return sum(a, b); }else{ return sum(a-number, b+number); } } ``` [Answer] # C - overkill is best kill Computers only have 0s and 1s, so it's actually very difficult to implement a proper, fast and scalable solution unto how to add. Luckily for you, I developed skynet 0.1284a, so I know how to solve this perilous problem. Usually, you'd need to buy the C standard library DLC, as the core doesn't contain it, but I managed to "cheat" my way out of it. In short, this is the cheapest and most effective method. ``` #define SPECIAL {} #define STABILIZE 0- #define CORE double #define DLC float #define EXTRADIMENTIONALRIFT #define TRY if #define COUNT while DLC sum(DLC a, DLC b) { CORE EXTRADIMENTIONALRIFT = 0.0;//doubles are better COUNT(a-->0){//downto operator TRY(EXTRADIMENTIONALRIFT -->0);//advanced technique SPECIAL} COUNT(b-->0){ TRY(EXTRADIMENTIONALRIFT-->0) SPECIAL} EXTRADIMENTIONALRIFT -= (STABILIZE a); EXTRADIMENTIONALRIFT -= (STABILIZE b);//we did some advanced stuff and need to stabilize the RAM EXTRADIMENTIONALRIFT = EXTRADIMENTIONALRIFT / -1; //division is faster return (DLC)EXTRADIMENTIONALRIFT;//convert it into a DLC, so you don't have to pay for it } ``` Just look at it. It's obviously evil. [Answer] # Python Uses the math identity `log(ab) = log(a) + log(b)` for a solution that works for small numbers, but overflows for any practical application. Thus ensuring that our lazy programmer will think it works on test data, only to have it crash in the real world. ``` import cmath def get_sum(list): e_vals = map(lambda x: cmath.exp(x), list) prod = reduce(lambda x, y: x*y, e_vals) return cmath.log(prod) get_sum(range(1,10)) # correctly gives 45 get_sum(range(1,100)) # gives nan ``` [Answer] C# You should use recursion to solve your problem ``` public int Add(int a, int b) { if (b == 1) { //base case return ++a; } else { return Add(Add(a, b-1),1); } } ``` If its good enough for Peano, its good enough for everyone. [Answer] # C++ We expect an operation like addition to be very fast. Many of the other answers simply don't concentrate enough on speed. Here's a solution that uses **only bitwise operations**, for maximum performance. ``` #include <iostream> int add2(int a, int b, int bits) { // Usage: specify a and b to add, and required precision in bits (not bytes!) int carry = a & b; int result = a ^ b; while(bits --> 0) { // count down to 0 with "downto" operator int shift = carry << 1; carry = result & shift; result ^= shift; } return result; } int main() { // Test harness std::cout << add2(2, 254, 7) << std::endl; return 0; } ``` [Answer] My best solution so far, gives a pretty incomprehensible answer until you run `aVeryLargeNumber()` ``` function aVeryLargeNumber(){return Math.log(Math.log(Math.log(Math.log(Math.round((Math.log(!![].join()^{}-({}=={})|(0x00|0x11111)-(0x111111&0x10111))/Math.log(2))/(Math.tan(Math.PI/4)*Math.tan(1.48765509)))+(0xFFFF))/Math.log(2))/Math.log(2))/Math.log(2))/Math.log(2)} function add(a,b){ var i=aVeryLargeNumber(); i--; for(;i<b;i+=aVeryLargeNumber(),a+=aVeryLargeNumber()); return a; } ``` [Answer] ## C++ - Peano numbers with template metaprogramming (with optional doge) > > C, like many other programming languages complicate things with > absolute no reason. One of the most overcomplex systems in these > languages are natural numbers. C is obsessed with the binary > representation and all other completely useless details. > > > In the end, Natural number is just a Zero, or some other natural > number incremented by one. These so called *Peano numbers* are a nice > way to represent numbers and do calculation. > > > **If you like doge** I have written an C++ extension to allow the > use of natural language for programming. The extension and this > following code using my extension can be found at: <http://pastebin.com/sZS8V8tN> > > > ``` #include <cstdio> struct Zero { enum { value = 0 }; }; template<class T> struct Succ { enum { value = T::value+1 }; }; template <unsigned int N, class P=Zero> struct MkPeano; template <class P> struct MkPeano<0, P> { typedef P peano; }; template <unsigned int N, class P> struct MkPeano { typedef typename MkPeano<N-1, Succ<P> >::peano peano; }; template <class T, class U> struct Add; template <class T> struct Add<T, Zero> { typedef T result; }; template <class T, class U> struct Add<T, Succ<U> > { typedef typename Add<Succ<T>, U>::result result; }; main() { printf("%d\n", MkPeano<0>::peano::value ); printf("%d\n", MkPeano<1>::peano::value ); printf("%d\n", Add< MkPeano<14>::peano, MkPeano<17>::peano >::result::value ); printf("%d\n", Add< MkPeano<14>::peano, Add< MkPeano<3>::peano, MkPeano<5>::peano>::result >::result::value ); } ``` > > To further add the superiority of this method: The math is done at compile time! > No more slow programs, your user doesn't want to wait for you to sum those numbers. > > > And for the serious part: * I don't think I have to say this, but this is completely ridiculous. * Works only for compile time constants. * Doesn't work with negative numbers. * The answer was provided by a person who actually cannot template metaprogram himself, so I wouldn't even know if it has other flaws. My friends told me to dogify the code, so I did. It's fun, but I think it takes too much away from the fact that this is totally stupid as it is, so I only included it as a link. [Answer] I stopped trusting computers when I learned about floating point errors. This JavaScript relies on precise human error checking: ``` while(prompt("Is this the answer: " + Math.round(Math.random()* 1000000)) !== "yes") {} ``` [Answer] "Write a function that inputs and returns their sum." Ok: ``` public static String inputAndReturnTheirSum() { System.out.print("Input their sum: "); return new Scanner(System.in).nextLine(); } ``` [Answer] Java or C-style. This is O(log n). Note: This does not work for negative a or b. ``` public static int sum(int a, int b) { if ((a & b) == (a ^ a)) return a | b; int c = a >> 1; int d = b >> 1; int s = a & 1; int t = b & 1; return sum(c, d + t) + sum(d, c + s); } ``` [Ideone demo here.](http://ideone.com/Z62PxN) [Answer] # Bash with Hadoop Streaming Obviously, `a` and `b` can become *really* large. Therefore, we must use Hadoop! ``` # Upload data to cluster: $HADOOP_HOME/bin/hdfs dfs -mkdir applestore for i in `seq 1 $a`; do echo Banana > /tmp/.$i $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/android-$i$i done for i in `seq 1 $b`; do echo Orange > /tmp/.$i $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/java-$i$i done # Now we have all the data ready! Wow! $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \ -input applestore/ \ -output azure/ \ -mapper cat \ -reducer wc # We can now download the result from the cluster: $HADOOP_HOME/bin/hdfs dfs -cat azure/part-00000 | awk '{print $1;}' ``` As an added bonus, this approach involves a `cat` and a `wc`. This ought to be fun to watch! But I plan to use Mahout for this in the future (although I like cats). This must be **the most scalable solution** you get for this question. However, I can imagine that a *recursive Hadoop solution* is much more elegant. [Answer] Ignore all those silly people with their non-generic and untestable manners. We need a performant, extensible and simple library for a project of such scale. It must support extension and substituton at every point of the code. For that, we need an equally extensible and simple language, that's why the best candidate is **C#**. This is why I present you the beta version of my **Operable Commons Library Enterprise Edition, version 0.8.4.4\_beta1.3a\_rev129857\_dist29.12.13/master**, which at this version exposes a `IOperable` interface, a `IAddable` interface so you can use your own efficient adding methods, and a default implementation of `IAddable`: the `Addable` class, which uses extremely efficient bitwise addition, without cheating and using the slow native subtraction for carry shifting. Of course, like any good library, it comes with a factory for every type it supports. The library also follows the principles of "handle it yourself", so you must guarantee that the input is valid and that the desired output is feasible, since it will not check for invalid data. Here it is (This code is licensed under the Microsoft Corporation Read-Only Proprietary Dont-Touch-This Obstructive License, Revision 3.1): ``` public interface IOperable { uint Value {get; set;} } public interface IAddable : IOperable { IAddable Add(IAddable a, IAddable b); } public class Addable : IAddable { public uint Value {get; set;} public Addable(uint value) { Value = value; } public IAddable Add(IAddable a, IAddable b) { uint carry = a.Value & b.Value; uint result = a.Value ^ b.Value; while (carry != 0) { uint shiftedcarry = carry << 1; carry = result & shiftedcarry; result ^= shiftedcarry; } return new Addable(result); } } public static class OperableFactory { public static IAddable GetAddable(uint value) { return new Addable(value); } } ``` [Answer] ## JavaScript Programming is all about algorithm. Let's go back to basic algorithm what we learn at the age of 3 - fingers counting. ``` var fingers = 0; var hands = 0; var FINGER_NUMBER = 5; /* MEAT */ function sum(a,b){ while(a-- > 0) { finger_inc(); } while(b-- > 0) { finger_inc(); } return count_hands_and_fingers(); // We count the number of hands and fingers } /* Private functions */ function finger_inc(){ if(++fingers >= FINGER_NUMBER) { hands++; fingers = 0; } } function count_hands_and_fingers() { var total_count = 0; total_count = hands * FINGER_NUMBER; total_count += fingers; return total_count; } document.write(sum(1,50)); ``` * Firstly, being a lead developer, let's have a wise language choice - cross-platform, light-weight and portable. * Secondly, have a global vision. Use Global var. * Thirdly, ++s and --s * Same as YFS (You-Finger-System), this does not support negative numbers * Finally, you can alter `FINGER_NUMBER` according to the number of fingers you have. JSFiddle: <http://jsfiddle.net/e3nc5/> [Answer] ## TI-Basic 83/84 ``` :Lbl Startup;bananapie\\repplie :If X=10 ::0→X :If X=10 ::Then ::Goto Lolbro\xdgtg ::End :::::::::::::::::::Lbl Loled;epicly\that\is ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Input X,Y ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::If X=Y :::::::::::::::::::Then ::X+X→A ::Else :X+Y→A :A*1+0→A :End :If A>A :Goto Somewhere :Return A ``` [Answer] Well, this one is a bit tricky. Fortunately, Python makes it reasonably straightforward. You'll need [PIL](http://www.pythonware.com/products/pil/) to do this right. ``` import Image, ImageDraw def add_a_to_b(a, b): # First, we call the answer 'y', as in 'Y do we care?' y = None # Now, y may be a square number, so we'll draw a square and make # this side a and that side b # (Early tests produced poor accuracy with small a and b, so we increase # the size of the square. This is an important program, after all!) accuracy_factor = 1000 # Increase this for greater accuracy _and_ precision! img = Image.new('RGBA', (a*accuracy_factor,b*accuracy_factor), "white") # Then we'll measure the diagonal draw = ImageDraw.Draw(img) draw.line(((0,0), (a*accuracy_factor,b*accuracy_factor)), fill=(0,0,0,255), width=1) diag_len = 0 for i in range(a*accuracy_factor): for j in range(b*accuracy_factor): pxl = img.getpixel((i,j)) if pxl == (0, 0, 0, 255): diag_len += 1 # If your boss says this is wrong, he probably doesn't know higher math y = diag_len / accuracy_factor return y ``` --- Comments adapted from [Watterson](http://www.gocomics.com/printable/calvinandhobbes/1990/09/10/). Intentionally using the slow `Image.getpixel()`. I'm not sure it's actually slow *enough*, though, darnitall. RGBA just to take up extra memory. [Answer] ## JAVA In the below code, ... stands in for code that I was too lazy to write but you should be able to figure out. To really do this in style, would require a code generation program. The limits 0 and 10 could be changed to whatever. The bigger the limits the more code and a computer could easily fill in the ...s. ``` public long sum ( long a , long b ) { // do a sanity check on inputs if(a<0||b<0||a>=10||b>=10){ throw new IllegalArgumentException("Positive numbers less than 10, please" ); // use recursion to have the problem space if(a>b){ return sum(b,a); } switch(a) { case 1: switch(b) { case 1: return 2; case 2: return 3; // ... case 8: return 9; default: assert b==9; return 10; } case 2: switch ( b ) { // ... } // ... case 8: switch ( b ) { case 8: return 16; default: assert b==9; return 17; } case 9: assert b==9; return 18; } } ``` [Answer] > > a function that inputs and returns their sum > > > # Lua ``` function f() local theirsum = io.read"*n" return theirsum end ``` [Answer] The code is done. Be very careful about that. This code is ultra-complex and is probably prone to become an intelligent conscious and self-aware being. It's highly classified top-secret code. ``` /* * Copyright: Much big company. * This code is part of the Skynet. It is highly classified and top-secret! */ package com.muchbigcompany.skynet; import javax.swing.JOptionPane; /** * In this program, I had written a function that inputs and returns their sum. * @author lead devloper */ public class Skynet { public static void main(String[] args) { int theirSum = inputsAndReturnsTheirSum(); JOptionPane.showMessageDialog(null, "Their sum is " + theirSum); } /** * This is a function that inputs and returns their sum. * @return their sum. */ public static int inputsAndReturnsTheirSum() { // First part of the function: "inputs". String inputs = JOptionPane.showInputDialog("Inputs theirs sum"); int theirSum = Integer.parseInt(inputs); // Second part of the function: "returns their sum". return theirSum; } } ``` [Answer] # C++ Of course you are gonna need some [template magic](http://coliru.stacked-crooked.com/a/b362820f64abb8a5): ``` template<int I> struct identity { static const int value = I; }; template<int A, int B> struct sum { static const int value = identity<A>::value + identity<B>::value; }; auto main(int argc, char* argv[]) -> int { std::cout << sum<1, 3>::value; return 42; } ``` [Answer] **JAVA** Hard problem. It is known that in computer science there are problems that verifying their answers is easier than finding them. So, you should use a random algorithm for guessing the solution, then verify it (efficiently!), and hope to get the right result in reasonable time: ``` public long sum(int a, int b) { Random r=new Random(); While(15252352==15252352) { long sum=r.nextLong(); // guess the solution if (sum - a == b) // verify the solution return sum; } } ``` [Answer] This function is under patent of my company, I can provide you an obfuscated licensed copy of it: ## Javascript: ``` function sum(a,b) { return eval(atob('YSti')) }; ``` **Usage:** ``` sum([arg1],[arg2]); ``` [Answer] # Python Programming is about fault tolerant. The following is an implementation of sum that will add anything without fussing out. It will transparently sort the elements in the order that can be added. In case, its not addable, it will flag it as `NaN`. ``` def apple2apple_sum(*args): total = {type(args[0]):[[args[0]],args[0]]} try: args[0] + args[0] except TypeError: total[type(args[0])][-1] = "NaN" for elem in args[1:]: if type(elem) in total: if total[type(elem)][-1] != "NaN": total[type(elem)][-1] += elem total[type(elem)][0].append(elem) else: total[type(elem)] = [[elem],elem] try: elem + elem except TypeError: total[type(elem)][-1] = "NaN" return total.values() >>> apple2apple_sum(1,2,3,'a', 'b', 4, 5.1, 6.2, 'c', map, 10, sum) [[['a', 'b', 'c'], 'abc'], [[<built-in function map>, <built-in function sum>], 'NaN'], [[5.1, 6.2], 11.3], [[1, 2, 3, 4, 10], 20]] ``` [Answer] ## Fortran Obviously the most efficient way is to shift your bits. This can be easily done with C+Fortran via the `iso_c_binding` module: ``` program add_func use iso_c_binding implicit none ! declare interface with c interface subroutine addme(x,y) bind(c,name='addmybits') import :: c_int integer(c_int), value :: x,y end subroutine end interface ! need our numbers integer(c_int) :: x,y print *,"what two numbers do you need to add (separated by comma)" read(*,*)x,y call addme(x,y) end program add_func ``` where the C routine is ``` #include <stdio.h> void addmybits(int a, int b){ unsigned int carry = a & b; unsigned int result = a ^ b; while(carry != 0){ unsigned shiftedcarry = carry << 1; carry = result & shiftedcarry; result ^= shiftedcarry; } printf("The sum of %d and %d is %d\n",a,b,result); } ``` You need to compile the C code first (e.g., `gcc -c mycfile.c`) then compile the Fortran code (e.g., `gfortran -c myf90file.f90`) and then make the executable (`gfortran -o adding myf90file.o mycfile.o`). ]
[Question] [ You will be given a string. It will contain 9 unique integers from 0-9. You must return the missing integer. The string will look like this: ``` 123456789 > 0 134567890 > 2 867953120 > 4 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~18~~ 16 bytes +beauty thanks to @Sarge Borsch ``` `99066**2`.strip ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z9gaWlgZqalZZSgV1xSlFnwv6AoM69EIU0jM6@gtERDU/O/uoWZuaWpsaGRgToA "Python 2 – TIO Nexus") `99066**2` is just a shorter way to generate a string that contains 0~9 [Answer] # [Python](https://docs.python.org/2/), 22 bytes ``` lambda s:-int(s,16)%15 ``` [Try it online!](https://tio.run/nexus/python2#JY5LCsJAEETX5hS9kShEmJ6e/gVyEnUR0YCgUTK5f0zG5aPqUTV0l@XVv2/3HnJ7eo7zITcoxz3yMj/ynKGDc52EjTwq1g3UFFwtSeQNDJMKOYcNJLkpY4gbRCH2YH9HNBk6xVJjJccYLBXAIBYTeXFYAqpTSXRdRbLVuVbV8Jkgw3OEcqqtdt9p/QrDIR@XHw "Python 2 – TIO Nexus") An arithmetic solution. Interprets the input string as hex, negates it, and takes the result modulo 15. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes ### Derived function ``` ⎕D∘~ ``` `⎕D` **D**igits `∘` (ties a left argument to the following dyadic function to create a monadic function) `~` except [the argument] [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG3Co76pLo86ZtT9/5@moG5oZGxiamZuYanOBeJBOQZgnoWZuaWpsaGRgToA "APL (Dyalog Unicode) – TIO Nexus") --- ### Function train ``` ⎕D~⊢ ``` `⎕D` **D**igits `~` except `⊢` the right argument [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG3Co76pLnWPuhb9/5@moG5oZGxiamZuYanOBeJBOQZgnoWZuaWpsaGRgToA "APL (Dyalog Unicode) – TIO Nexus") --- ### Explicit program ``` ⎕D~⍞ ``` `⎕D` **D**igits `~` except `⍞` character input [Try it online!](https://tio.run/nexus/apl-dyalog#e9TRnvb/Ud9Ul7pHvfP@P@po/5/GZWhkbGJqZm5hyQVkQ5kGQLaFmbmlqbGhkQEA "APL (Dyalog Unicode) – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), ~~24~~ 23 bytes ``` (477-).sum.map fromEnum ``` [Try it online!](https://tio.run/nexus/haskell#@59mq2Fibq6rqVdcmquXm1igkFaUn@uaV5r7PzcxM0/BViEzryS1KDG5REFFoTgjv1xBTyHtv6GRsYmpmbmFJQA "Haskell – TIO Nexus") Usage: `(477-).sum.map fromEnum $ "123456890"`. 477 is the sum of the character codes of the digits 1 to 9, excluding 0. This anonymous function computes 477 minus the sum of all digit character codes to find the missing one. Turning the char digits to ints is one byte longer: ``` (45-).sum.map(read.pure) foldl(\a b->a-read[b])45 ``` [Try it online!](https://tio.run/nexus/haskell#@59mm5afk5KjEZOokKRrl6hblJqYEp0Uq2li@j83MTNPwVYhM68ktSgxuURBRaE4I79cQU8h7b@hkbGJqZm5hQEA "Haskell – TIO Nexus") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~48~~ ~~38~~ 36 + 3 = 39 bytes *10 bytes saved thanks to DJMcMayhem!* ``` ((([]())[]{}){()()({}[()])}{}[{{}}]) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hoREdq6GpGR1bXatZraEJhNW10RqasZq1QLq6urY2VvP/fwtDI2MTAzNzy/@6yQA "Brain-Flak – TIO Nexus") ## Explanation The sum of all the digits in Ascii is 525. This program sums up the input and subtracts it from 525 to get the missing digit. ``` ((([]())[]{}){()()({}[()])}{} ) ``` Will push 525. This takes advantage of the fact that we know there will be 9 elements of input to begin with. This means that `[]` evaluates to 9 which allows us to get to large numbers like 525 quickly. Next we have the bit: ``` [{{}}] ``` which will sum up the inputs and subtract it from the total. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ØDḟ ``` Simply filters (`ḟ`) the input string from **“0123456789”** (`ØD`). [Try it online!](https://tio.run/nexus/jelly#@394hsvDHfP///@vZGFmbmlqbGhkoAQA "Jelly – TIO Nexus") [Answer] # Ruby, 14 Sums the ascii codes and subtracts from 48\*9+45 ``` ->s{477-s.sum} ``` Use like this ``` f=->s{477-s.sum} puts f["123456789"] ``` [Answer] # JavaScript (ES6), 26 *Edit* 1 byte save thx @Neil, with a much more smarter trick Xoring all the values from 1 to 9 gives 1. Xor 1 one more time and the result is 0. So, if any single value is missing, the result will be the missing value. ``` s=>eval([1,...s].join`^`) ``` **Test** ``` f=s=>eval([1,...s].join`^`) function go() { var i=I.value; O.textContent = f(i) } go() ``` ``` <input oninput='go()' value='012987653' id=I> <pre id=O></pre> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~27 21~~ 19 bytes -6 Thanks to Basic Sunset -2 Thanks to Martin Ender ``` . $*_5$* +`_1|1_ 1 ``` [Try it online!](https://tio.run/nexus/retina#@6/HpaIVb6qixaWdEG9YYxjPxWX4/7@hkbGpmbmFpQEA "Retina – TIO Nexus") Replace every digit with that many `_`s and 5 `1`s: ``` . $*_5$* ``` Remove all of the `_`s and a `1` for each: ``` +`_1|1_ ``` Count the number of `1`s left: ``` 1 ``` [Answer] # Brainfuck, 17 15 bytes ``` -[-[->-<],]>++. ``` [Try it out here](https://copy.sh/brainfuck/?c=LVstWy0-LTxdLF0-Kysu). *This solution works on standard Brainfuck (8-bit cells) only, as it relies on wrapping.* It's a rare day when Brainfuck can actually compete, but this challenge just happened to line up with the BF spec pretty well! Instead of straight-up breaking down this answer, I'd like to step through the iterations I took, because I think it would be more understandable (and more interesting). Note: this solution is inspired largely by [Wheat Wizard's Brain-Flak answer](https://codegolf.stackexchange.com/questions/114060/output-the-missing-integer/114063#114063). ## Explanation ## Step 1, 26 bytes In his answer, Wheat Wizard pointed out that the sum of the ASCII values from 0-9 sum to 525. And since standard Brainfuck only has a notion of [0,255], this makes the value 525 % 256 = **13**. That is to say, subtracting the ASCII values of the input from 13 nets you the missing digit. The first version of this program was: 1. Put 13 in the first cell 2. Take inputs into the second cell 3. Subtract the second cell from the first cell 4. Jump to 2 if there are inputs remaining 5. Print the first cell And here's the code for the simple solution: ``` +++++++++++++ #Set the first cell to 13 >, #Take inputs into the second cell [[<->-],] #Subtract the second cell from the first cell and repeat until inputs are over <. #Print the first cell ``` ## Step 2, 19 bytes As pointed out in his answer, since we know the input will be exactly length 9, we can use that value as a constant, and eliminate that long string of +'s right at the beginning. It also doesn't matter at what point we add 13 (thanks, commutative property!), so we'll mix it in with the subtraction and printing steps. ``` , #Take input to enter the loop [[->-<], #Subtract the first cell from the second cell >+<] #Add 1 for each input; totaling 9 >++++ #Add the missing 4 to make 13 . #And print ``` This was my original answer to this problem, but we can do better. ## Step 3, 17 bytes Interestingly enough, the previous answer works even if we begin with a + instead of a , ``` +[[->-<],>+<]>++++. ``` Brainfuck required *something* in a cell in order to begin a loop. We naively added that extra 4 in the end, when it could have gone in other places. ``` -[[->-<],>+<]>++. ``` With some *totally intentional* (read: trial and error) loop trickery, starting off the program with a - leads to two interesting results: 1. One gets added to the second cell (saving 1 byte at the end). 2. The loops runs one extra time, totaling 10 instead of 9 (saving another 1 byte). 1 + 10 + 2 = 13, and we end up with the original answer. Looking back on it, this is probably an excessive write-up for such a simple Brainfuck program. ## Step 4, 15 bytes After thinking about this solution a bit more, I was able to cut off 2 bytes. I wanted to clarify something about the previous step: The minus to enter the loop *effectively* adds 1, but what it's actually doing is subtracting 255 from the second cell (resulting in 1). It's obvious in retrospect, but subtracting 1 from the first cell is the same as adding 1 to the second cell (because everything in the first cell gets subtracted from the second cell.) ``` -[-[->-<],]>++. ``` I was able to remove the ">+<" by adding a "-" at the beginning of the first loop. It has to go there, and not where the ">+<" was, because the program will loop infinitely otherwise. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` 45¹SO- ``` [Try it online!](https://tio.run/nexus/05ab1e#@29iemhnsL/u//8WZuaWpsaGRgYA "05AB1E – TIO Nexus") ``` 45 # Push 45 ¹ # push input S # Split O # Sum - # Subtract (45 - sum) ``` [Answer] # Mathematica, 25 bytes ``` 477-Tr@ToCharacterCode@#& ``` Pure function taking a string as input and returning an integer. Mathematica has long command names and is reluctant to convert between strings and integers, which makes it particularly bad at this challenge. The best I could find was the algorithm from [Level River St's Ruby answer](https://codegolf.stackexchange.com/a/114091/56178), which does a computation based on the total of the ASCII codes of the input string; in Mathematica, this uses only one long command name. [Answer] ## JavaScript (ES6), ~~31~~ ~~29~~ ~~28~~ 22 bytes ``` s=>(15-`0x${s}`%15)%15 ``` Port of @xnor's Python answer, except that JavaScript only has a remainder operator rather than a modulo operator, so I can't do it in a single step. Edit: Saved 6 bytes thanks to @Arnauld. [Answer] # [Octave](https://www.gnu.org/software/octave/), 22 bytes ``` @(x)setdiff('0':'9',x) ``` [Try it online!](https://tio.run/nexus/octave#@@@gUaFZnFqSkpmWpqFuoG6lbqmuU6H5PzGvWEPd0NjE1MzcwtJAXfM/AA "Octave – TIO Nexus") [Answer] # PHP, 27 ``` <?=trim(32043**2,$argv[1]); ``` uses the trick from [Rod's answer](https://codegolf.stackexchange.com/a/114070/29637) to generate a string containing all digits then removes all digits except for the missing one. --- PHP, 41 ``` for($b=1;$i<9;$b^=$argv[1][$i++]);echo$b; ``` This one uses *xor* because I haven't seen it yet. [Answer] ## Bash + coreutils, 19 bytes I found a ~~shorter~~ bash solution, that uses an interesting checksum approach: ``` sum -s|dc -e524?--P ``` **[Try it online!](https://tio.run/nexus/bash#@19cmqugW1yTkqygm2pqZGKvqxvw/7@FmbmlqbGhkQEA)** **Explanation:** The `sum` command prints a checksum and a block count. I don't know many details, but using the option `-s` (System V algorithm) will make the checksum equal to the ASCII sum of each input character code. As such, the checksum remains constant when the order of the same input characters changes. Given `867953120` as test case (last example), here is how the script works: * `sum -s` outputs `473 1`. If no integer was missing, the checksum would have been 525. * `dc -e524?` pushes 524 and then the pipe input. The stack is: `1 473 524`. The idea is to subtract the checksum from 525, but since sum outputs 1 as well, I need to work with it. * `--P`. After applying the two subtractions (524-(473-1)), the stack is: `52`. With 'P' I print the character with that ASCII code: `4`, the missing digit. [Answer] # Fortran 95, ~~146~~ 128 bytes ``` function m(s) character(len=10)::s,t t='0123456789' do j=1,10 k=0 do i=1,9 if(s(i:i)==t(j:j))k=1 end do if(k==0)m=j-1 end do end ``` Not very short, I'm afraid. **Ungolfed:** ``` integer function m(s) implicit none character(len=9)::s character(len=10)::t integer:: i, j, k t='0123456789' do j=1,10 k=0 do i=1,9 if (s(i:i) == t(j:j)) k=1 end do if (k==0) m=j-1 end do end function m ``` [Answer] # Bash (+utilities), ~~22~~, 19 bytes * Use `seq` instead of brace expansion, -3 bytes (Thx @Riley !) ``` seq 0 9|tr -d \\n$1 ``` **Test** ``` $seq 0 9|tr -d \\n123456789 0 ``` [Try It Online!](https://tio.run/nexus/bash#@1@cWqhgoGBZU1KkoJuiEBOTp2L4//9/CzNzS1NjQyODr3n5usmJyRmpAA) [Answer] # Google Sheets, ~~39~~ 33 bytes > > Input is entered into cell **`A1`**. > > > **Code:** ``` =REGEXEXTRACT(4&2^29,"[^"&A1&"]") ``` *Saved 6 bytes thanks to Steve Kass.* **Previous Code:** ``` =REGEXEXTRACT("0123456789","[^"&A1&"]") ``` **Result:** [![enter image description here](https://i.stack.imgur.com/NSF5r.png)](https://i.stack.imgur.com/NSF5r.png) [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~36~~ 30 bytes ``` (fold -1;seq 0 9)|sort|uniq -u ``` [Try it online!](https://tio.run/##Rck5DoMwFEXRPqt4RYqkQPKAJ7EVGic2AinyFzh03rvToPzu6N5XrGtf6EDEViCVHo11PkBeEPDWBaOlElD/xlcqlmaNLMOyLMfyrDAh0S2/V8I9omHuj4U@CYOcat4hEJ6t0vFtZ9l2DGdPVHL/AQ "Bash – Try It Online") ~~Posting to get golfing tips over this.~~ Thanks @DigitalTrauma, big fan ;) `fold -1` writes one char of input per line `seq 0 9` writes 0..9 one per line after this. Those lines are fed to `sort` and filtered by `uniq -u` displaying only not duplicated lines. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 30 bytes ``` param($n)0..9|?{$n-notmatch$_} ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp2mgp2dZY1@tkqebl1@Sm1iSnKESX/v//391CzNzS1NjQyMDdQA "PowerShell – TIO Nexus") Takes input `$n`, constructs a range `0..9` (i.e., `0, 1, 2 ... 9`), then uses a `Where-Object` clause (the `|?{...}`) to pull out the number that does regex `-notmatch`. That's left on the pipeline, output is implicit. [Answer] # [CJam](https://sourceforge.net/p/cjam), 5 bytes ``` A,sq- ``` [Try it online!](https://tio.run/nexus/cjam#@@@oU1yo@/@/hZm5pamxoZEBAA "CJam – TIO Nexus") ``` A, e# The range from 0 to 9: [0 1 2 3 4 5 6 7 8 9] s e# Cast to a string: "0123456789" q e# The input - e# Remove all characters from the range that are in the input e# Implicit output ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 36 bytes Includes +1 for `-r` ``` s/$/0123456789/ : s/(.)(.*)\1/\2/ t ``` [Try it online!](https://tio.run/nexus/sed#@1@sr6JvYGhkbGJqZm5hqc9lxVWsr6GnqaGnpRljqB9jpM9V8v@/hZm5pamxoZHBv/yCksz8vOL/ukUA "sed – TIO Nexus") ``` s/$/0123456789/ # Append 0123456789 : # Start loop s/(.)(.*)\1/\2/ # remove a duplicate character t # loop if something changed ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` žhISK ``` [Try it online!](https://tio.run/nexus/05ab1e#@390X4ZnsPf//4bGJqZm5haWBgA "05AB1E – TIO Nexus") **Explanation** ``` žh # from the string "0123456789" K # remove IS # each digit of the input ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 5 bytes ``` ẹ:Ị↔x ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9w106rh7u7HrVNqfj/X8nCzNzS1NjQyEDpfxQA "Brachylog – TIO Nexus") Arguably should be shorter (I'm still confused as to why the `ẹ` is necessary), but this is the best I could do. ## Explanation ``` ẹ:Ị↔x ẹ Split the input into a list of characters :Ị Pair that list with the string "0123456789" ↔x Remove all elements of the list from the string ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` ¬x n45 ``` [Try it online!](https://tio.run/nexus/japt#@39oTYVCnonp//9KhkYmpmbmFpYGSgA "Japt – TIO Nexus") ### Explanation: ``` ¬x n45 n45 // 45- ¬ // Split the input into an array "123" → ["1","2","3"] x // Return the sum of all the items ["1","2","3"] → 6 // 45 - 6 = output ``` [Answer] # Common Lisp, 47 bytes ``` (lambda(s)(- 45(reduce'+ s :key'digit-char-p))) ``` Ungolfed: ``` (lambda (s) (- 45 (reduce '+ s :key 'digit-char-p))) ``` Explaination: ``` (reduce '+ s :key 'digit-char-p) ``` This loops through the chars in `s`, converts them to digits, and adds them. Digit-char-p, conveniently, return the number of the char as its "true" value, so it can be used as a test or a conversion. ``` (- 45 ...) ``` Subtract from 45 gives back the digit that was missing from the input. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 18 Bytes ``` 5v&;52/ni?@.>!&oW+ ``` Expanded ``` 5 v & ; 5 2 / n i ? @ . > ! & o W + . . . . . . ``` [Try it here](https://ethproductions.github.io/cubix/?code=NXYmOzUyL25pP0AuPiEmb1cr&input=ODc2NTkxMzIw&speed=20) Uses the same sort of method as this [brain-flak](https://codegolf.stackexchange.com/a/114063/31347) answer. Create the value -525 on the stack by pushing 5, 2, concatenate, push 5, concatenate and negate. Then repeatably get input and add until end of input is hit. Remove the last input, negate(make positive) the last add result, output the character and halt. The reason for working from -525 up is that the character output is hit for each input iteration. Since the value is negative, nothing is output until the loop is exited and the negative value is made positive. [Answer] # PHP, 37 bytes ``` <?=45-array_sum(str_split($argv[1])); ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~12~~ 10 bytes ``` Cdi?B%-B%p ``` [Try the dc version online!](https://tio.run/nexus/dc#@@@ckmnvpKrrpFrw/7@hkbGBqYm5mQUA "dc – TIO Nexus") This uses the fact that the sum of the digits from 0 to 9 is 45, which is 1 more than a multiple of 11. The program works by viewing the input as a base 12 number, finding its remainder when divided by 11, and subtracting that from 12 (to find the missing digit). The only catch is that if 0 or 1 is the missing digit, this would give an answer of 11 or 12, respectively, so I mod out by 11 one additional time at the end to take care of those cases. --- This yields a short bash solution also: # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~17~~ 15 bytes ``` dc -eCdi?B%-B%p ``` [Try the bash version online!](https://tio.run/nexus/bash#@5@SrKCb6pySae@kquukWvD/v5GBmaGlqbmFCQA "Bash – TIO Nexus") ]
[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/22720/edit) Provided an input as an unsigned integer: ``` 13457 ``` Your function/subroutine should return: ``` 75431 ``` Since this is a popularity contest, be creative. Creative solutions use unusual or clever techniques to accomplish given task. Constraints: * You cannot use arrays. * You cannot use strings. * No RTL Override (`&#8238`) Brownie points for using creative arithmetics. Since this is a popularity contest, I suggest not using the modulo (`%`) operator in your code. **About Leading zeroes:** If the input is: ``` 12340 ``` Then the output: ``` 4321 ``` would be acceptable. [Answer] ## Mathematica, no modulo! ``` n = 14627; length = Ceiling[Log[10, n]]; img = Rasterize[n, RasterSize -> 400, ImageSize -> 400]; box = Rasterize[n, "BoundingBox", RasterSize -> 400, ImageSize -> 400]; width = box[[1]]; height = box[[3]]; ToExpression[ TextRecognize[ ImageAssemble[ ImageTake[img, {1, height}, #] & /@ NestList[# - width/length &, {width - width/length, width}, length - 1]]]] ``` Let's break it down. First we use some "creative arithmetics" to find out how many digits are in the number: `length = Ceiling[Log[10, n]];` Next, we Rasterize the number to a nice large image: ![honking big rasterized number](https://i.stack.imgur.com/X5vYU.png) Now we query for the bounding box of that image, and populate the width and height (actually using the baseline offset instead of the image height, because MM adds some whitespace below the baseline in the image). Next, NestList recursively subtracts the width of the image divided by the length of the string to enable ImageTake to pluck characters from the end of the image one by one, and those are reassembled by ImageAssemble to this image: ![honking big reversed number](https://i.stack.imgur.com/ZBUx2.png) Then we pass that on to the TextRecognize function for optical character recognition, which at this image size and rasterization quality is able to impeccably recognize the final output and give us the integer: ``` 72641 ``` Logarithms and OCR - It's like chocolate and peanut butter! ### New and improved This version pads out the number to deal with the obstinate behavior of TextRecognize with small numbers, and then subtracts out the pad at the end. This even works for single-digit numbers! Though, why you would run a reverse routine on a single number is a mystery to me. But just for the sake of completeness, I even made it work for inputs of zero and one, which would normally break because the floored log doesn't return 1 for them. ``` n = 1; pad = 94949; length = If[n == 1 || n == 0, 1, Ceiling[Log[10, n]]]; img = Rasterize[n + (pad*10^length), RasterSize -> 400, ImageSize -> 400]; padlength = length + 5; box = ImageDimensions[img]; width = box[[1]]; height = box[[2]]; reversed = ImageResize[ ImageAssemble[ ImageTake[img, {1, height}, #] & /@ NestList[# - width/padlength &, {width + 1 - width/padlength, width}, padlength - 1]], 200]; recognized = ToExpression[TextRecognize[reversed]]; (recognized - pad)/10^5 ``` [Answer] ## Perl/LuaTeX/Tesseract The following Perl script reads the number as command line argument, e.g.:     `**1234567890**` The following Perl script prints the number via LuaTeX. A virtual font is created on the fly that mirrors the digits horizontally. > > ![temp0.png](https://i.stack.imgur.com/K2cyi.png) > > > Then the whole number is again mirrored horizontally: > > ![temp1.png](https://i.stack.imgur.com/211Rt.png) > > > The final image is reread via OCR (tesseract):     `**0987654321**` ``` #!/usr/bin/env perl use strict; $^W=1; # Get the number as program argument or use a fixed number with all digits. $_ = shift // 1234567890; $\="\n"; # append EOL, when printing # Catch negative number exit print "NaUI (Not an Unsigned Integer)" if $_ < 0; # Catch number with one digit. exit ! print if ($_ = $= = $_) < 10; undef $\; # Write TeX file for LuaTeX open(OUT, '>', 'temp.tex') or die "!!! Error: Cannot write: $!\n"; print OUT<<"END_PRINT"; % Catcode setting for iniTeX (a TeX format is not needed) \\catcode`\{=1 \\catcode`\}=2 \\def\\mynumber{$_} END_PRINT print OUT<<'END_PRINT'; \directlua{tex.enableprimitives('',tex.extraprimitives())} \pdfoutput=1 % PDF output % move origin to (0,0) \pdfhorigin=0bp \pdfvorigin=0bp % magnify the result by 5 \mag=5000 % Create virtual font, where the digits are mirrored \directlua{ callback.register('define_font', function (name,size) if name == 'cmtt10-digits' then f = font.read_tfm('cmtt10',size) f.name = 'cmtt10-digits' f.type = 'virtual' f.fonts = {{ name = 'cmtt10', size = size }} for i,v in pairs(f.characters) do if (string.char(i)):find('[1234567890]') then v.commands = { {'right',f.characters[i].width}, {'special','pdf: q -1 0 0 1 0 0 cm'}, {'char',i}, {'right',-f.characters[i].width}, {'special','pdf: Q'}, } else v.commands = {{'char',i}} end end else f = font.read_tfm(name,size) end return f end ) } % Activate the new font \font\myfont=cmtt10-digits\relax \myfont % Put the number in a box and add a margin (for tesseract) \dimen0=5bp % margin \setbox0=\hbox{\kern\dimen0 \mynumber\kern\dimen0} \ht0=\dimexpr\ht0+\dimen0\relax \dp0=\dimexpr\dp0+\dimen0\relax \pdfpagewidth=\wd0 \pdfpageheight=\dimexpr\ht0+\dp0\relax % For illustration only: Print the number with the reflected digits: \shipout\copy0 % print the number with the reflected digits % Final version on page 2: Print the box with the number, again mirrored \shipout\hbox{% \kern\wd0 \pdfliteral{q -1 0 0 1 0 0 cm}% \copy0 \pdfliteral{Q}% } % End job, no matter, whether iniTeX, plain TeX or LaTeX \csname @@end\endcsname\end END_PRINT system "luatex --ini temp.tex >/dev/null"; system qw[convert temp.pdf temp%d.png]; system "tesseract temp1.png temp >/dev/null 2>&1"; # debug versions with output on console #system "luatex --ini temp.tex"; #system qw[convert temp.pdf temp%d.png]; #system "tesseract temp1.png temp"; # Output the result, remove empty lines open(IN, '<', 'temp.txt') or die "!!! Error: Cannot open: $!\n"; chomp, print while <IN>; print "\n"; close(IN); __END__ ``` [Answer] # **Brainfuck** Basically, it is just an input-reversing program. ``` ,[>,]<[.<] ``` UPD: As [Sylwester](https://codegolf.stackexchange.com/users/11290/sylwester) pointed out in comments, in the classical Brainfuck interpreters/compilers (without possibility to going left from zero point in the memory array) this program would not work in the absence of '>' at the beginning, so the more stable version is: ``` >,[>,]<[.<] ``` [Answer] # Haskell ``` reverseNumber :: Integer -> Integer reverseNumber x = reverseNumberR x e 0 where e = 10 ^ (floor . logBase 10 $ fromIntegral x) reverseNumberR :: Integer -> Integer -> Integer -> Integer reverseNumberR 0 _ _ = 0 reverseNumberR x e n = d * 10 ^ n + reverseNumberR (x - d * e) (e `div` 10) (n + 1) where d = x `div` e ``` No arrays, strings, or modulus. Also, I know we're not supposed to use lists or strings, but I love how short it is when you do that: ``` reverseNumber :: Integer -> Integer reverseNumber = read . reverse . show ``` [Answer] I suppose *someone* has to be the partypooper. # Bash ``` $ rev<<<[Input] ```   ``` $ rev<<<321 123 $ rev<<<1234567890 0987654321 ``` Size limitations depend on your shell, but you'll be fine within reason. [Answer] ## C++ ``` /* A one-liner RECUrsive reveRSE function. Observe that the reverse of a 32-bit unsigned int can overflow the type (eg recurse (4294967295) = 5927694924 > UINT_MAX), thus the return type of the function should be a 64-bit int. Usage: recurse(n) */ int64_t recurse(uint32_t n, int64_t reverse=0L) { return n ? recurse(n/10, n - (n/10)*10 + reverse * 10) : reverse; } ``` [Answer] ## Javascript **EDIT** : Since there is a suggestion to not use `%` operator, I use a little trick now. I know this is not a code-golf, but there is no reason to make it longer. ``` function r(n){v=0;while(n)v=n+10*(v-(n=~~(n/10)));return v} ``` `r(13457)` returns `75431` Moreover, it's a lot faster than *string* method (`n.toString().split('').reverse().join('')`) : ![enter image description here](https://i.stack.imgur.com/oSDmL.jpg) [==> JSPerf report <==](http://jsperf.com/reverse-number) [Answer] ## Python *Not sure if this implementation qualifies for creative math* *Also % operator was not used per se, though one might argue that divmod does the same, but then then the Question needs to be rephrased :-)* **Implementation** ``` r=lambda n:divmod(n,10)[-1]*10**int(__import__("math").log10(n))+r(n /10)if n else 0 ``` **demo** ``` >>> r(12345) 54321 >>> r(1) 1 ``` **How does it work?** *This is a recursive divmod solution* \*This solution determines the least significant digit and then pushes it to the end of the number.\* **Yet Another Python Implementation** ``` def reverse(n): def mod(n, m): return n - n / m * m _len = int(log10(n)) return n/10**_len + mod(n, 10)*10**_len + reverse(mod(n, 10**_len)/10)*10 if n and _len else n ``` **How does it work?** *This is a recursive solution which swaps the extreme digits from the number* ``` Reverse(n) = Swap_extreme(n) + Reverse(n % 10**int(log10(n)) / 10) ; n % 10**log10(n) / n is the number without the extreme digits ; int(log10(n)) is the number of digits - 1 ; n % 10**int(log10(n)) drops the most significant digit ; n / 10 drops the least significant digit Swap_extreme(n) = n/10**int(log10(n)) + n%10*10**int(log10(n)) ; n%10 is the least significant digit ; n/10**int(log10(n)) is the most significant digit ``` **Example Run** ``` reverse(123456) = 123456/10^5 + 123456 % 10 * 10^5 + reverse(123456 % 10 ^ 5 / 10) = 1 + 6 * 10 ^ 5 + reverse(23456/10) = 1 + 600000 + reverse(2345) = 600001 + reverse(2345) reverse(2345) = 2345/10^3 + 2345 % 10 * 10^3 + reverse(2345 % 10 ^ 3 / 10) = 2 + 5 * 10^3 + reverse(345 / 10) = 2 + 5000 + reverse(34) = 5002 + reverse(34) reverse(34) = 34/10^1 + 34 % 10 * 10^1 + reverse(34 % 10 ^ 1 / 10) = 3 + 40 + reverse(0) = 43 + reverse(0) reverse(0) = 0 Thus reverse(123456) = 600001 + reverse(2345) = 600001 + 5002 + reverse(34) = 600001 + 5002 + 43 + reverse(0) = 600001 + 5002 + 43 + 0 = 654321 ``` [Answer] Just to be contrary, an overuse of the modulo operator: ``` unsigned int reverse(unsigned int n) {return n*110000%1099999999%109999990%10999900%1099000%100000;} ``` Note that this always reverses 5 digits, and 32 bit integers will overflow for input values more than 39045. [Answer] # **C#** Here's a way to do it without the Modulus (`%`) operator and just simple arithmetic. ``` int x = 12356; int inv = 0; while (x > 0) { inv = inv * 10 + (x - (x / 10) * 10); x = x / 10; } return inv; ``` [Answer] Bash ``` > fold -w1 <<<12345 | tac | tr -d '\n' 54321 ``` [Answer] # C ``` #include <stdio.h> int main(void) { int r = 0, x; scanf("%d", &x); while (x > 0) { int y = x; x = 0; while (y >= 10) { y -= 10; ++x; } r = r*10 + y; } printf("%d\n", r); } ``` No strings, arrays, modulus or division. Instead, division by repeated subtraction. [Answer] # Mathematica Making an image out of number, reflecting it, partitioning it into the digits. Then there is two alternatives: 1. Compare each image of a reflected digit with prepared earlier images, replace it with the corresponding digit and construct the number out of this. 2. Reflect every digit separately, construct a new image, and pass it to the image recognition function. I did both ``` reflectNumber[n_?IntegerQ] := ImageCrop[ ImageReflect[ Image@Graphics[ Style[Text@NumberForm[n, NumberSeparator -> {".", ""}], FontFamily -> "Monospace", FontSize -> 72]], Left -> Right], {Max[44 Floor[Log10[n] + 1], 44], 60}] reflectedDigits = reflectNumber /@ Range[0, 9]; reverse[0] := 0 reverse[n_?IntegerQ /; n > 0] := Module[{digits}, digits = ImagePartition[reflectNumber[1000 n], {44, 60}]; {FromDigits[ digits[[1]] /. (d_ :> # /; d == reflectedDigits[[# + 1]] & /@ Range[0, 9])], ToExpression@ TextRecognize[ ImageAssemble[ Map[ImageReflect[#, Left -> Right] &, digits, {2}]]]}] reverse[14257893] > {39875241, 39875241} ``` **EDIT**: Added padding of three zeroes, because `TextRecognise` works correctly only with integers > 999. [Answer] # Lua ``` function assemble(n,...) if ... then return 10*assemble(...)+n end return 0 end function disassemble(n,...) if n>0 then return disassemble(math.floor(n/10),n%10,...) end return ... end function reverse(n) return assemble(disassemble(n)) end ``` No arrays or strings used. The number is split into digits and reassembled using the arguments list. [Answer] ## Python2 Assumes "unsigned integer" is 32-bit ``` import math import sys a=input() p=int(math.log(a, 10)) b=a while b%10==0: sys.stdout.write('0') # if 1-char string is not allowed, use chr(48) instead b=b/10 if p==0: print a elif p==1: print a%10*10+a/10 elif p==2: print a%10*100+a%100/10*10+a/100 elif p==3: print a%10*1000+a%100/10*100+a%1000/100*10+a/1000 elif p==4: print a%10*10000+a%100/10*1000+a%1000/100*100+a%10000/1000*10+a/10000 elif p==5: print a%10*100000+a%100/10*10000+a%1000/100*1000+a%10000/1000*100+a%100000/10000*10+a/100000 elif p==6: print a%10*1000000+a%100/10*100000+a%1000/100*10000+a%10000/1000*1000+a%100000/10000*100+a%1000000/100000*10+a/1000000 elif p==7: print a%10*10000000+a%100/10*1000000+a%1000/100*100000+a%10000/1000*10000+a%100000/10000*1000+a%1000000/100000*100+a%10000000/1000000*10+a/10000000 elif p==8: print a%10*100000000+a%100/10*10000000+a%1000/100*1000000+a%10000/1000*100000+a%100000/10000*10000+a%1000000/100000*1000+a%10000000/1000000*100+a%100000000/10000000*10+a/100000000 elif p==9: print a%10*1000000000+a%100/10*100000000+a%1000/100*10000000+a%10000/1000*1000000+a%100000/10000*100000+a%1000000/100000*10000+a%10000000/1000000*1000+a%100000000/10000000*100+a%1000000000/100000000*10+a/1000000000 ``` When given input `1230`, it outputs `0321`. [Answer] ## Postscript ``` /rev{0 exch{dup 10 mod 3 -1 roll 10 mul add exch 10 idiv dup 0 eq{pop exit}if}loop}def ``` No arrays, no strings, no variables. ``` gs -q -dBATCH -c '/rev{0 exch{dup 10 mod 3 -1 roll 10 mul add exch 10 idiv dup 0 eq{pop exit}if}loop}def 897251 rev =' 152798 ``` The same without `mod` (which is just a shortcut, so no big difference): ``` /rev { 0 exch { dup 10 idiv dup 3 1 roll 10 mul sub 3 -1 roll 10 mul add exch dup 0 eq {pop exit} if } loop } def ``` [Answer] # C# This uses no strings or arrays, but does use the .NET `Stack<T>` type (EDIT: originally used modulus operator; now removed) ``` public class IntegerReverser { public int Reverse(int input) { var digits = new System.Collections.Generic.Stack<int>(); int working = input; while (working / 10 > 0) { digits.Push(working - ((working / 10) * 10)); working = working / 10; } digits.Push(working); int result = 0; int mult = 1; while (digits.Count > 0) { result += digits.Pop() * mult; mult *= 10; } return result; } } ``` [Answer] # **C** In that the obvious solution is represented in a couple other languages, might as well post it in C. **Golfed:** ``` r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+n%10;printf("%d",r);} ``` **Ungolfed:** ``` #include <stdio.h> int main() { int n, r = 0; scanf("%d", &n); for(;n;n/=10) { r = r * 10 + n % 10; } printf("%d", r); } ``` EDIT: Just saw the modulus edit. **Golfed (no modulus):** ``` r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+(n-10*(n/10));printf("%d",r);} ``` **Ungolfed (no modulus):** ``` #include <stdio.h> int main() { int n, r, m = 0; scanf("%d", &n); for(;n;n/=10) { r=r*10+(n-10*(n/10)); } printf("%d", r); } ``` [Answer] # python (easily done in assembly) Reverses the bits of a byte. Points for not doing the exact same thing everyone else did? ``` x = int(input("byte: "), 2) x = ((x * 8623620610) & 1136090292240) % 1023 print("{0:b}".format(x).zfill(8)) ``` example ``` byte: 10101010 01010101 ``` [Answer] # Java This is the this i've come up with, no strings, no arrays... not even variables (in Java I mind you): ``` public static int reverse(int n) { return n/10>0?(int)(modulo(n,10)*Math.pow(10, count(n)))+reverse(n/10):(int)(modulo(n,10)*Math.pow(10,count(n))); } public static int count(int i) { return (i = i/10)>0?count(i)+1:0; } public static int modulo(int i,int j) { return (i-j)>=0?modulo(i-j, j):i; } ``` **EDIT** A more readable version ``` /** Method to reverse an integer, without the use of String, Array (List), and %-operator */ public static int reverse(int n) { // Find first int to display int newInt = modulo(n,10); // Find it's position int intPos = (int) Math.pow(10, count(n)); // The actual value newInt = newInt*intPos; // Either add newInt to the recursive call (next integer), or return the found return (n/10>0) ? newInt+reverse(n/10) : newInt; } /** Use the stack, with a recursive call, to count the integer position */ public static int count(int i) { return (i = i/10)>0?count(i)+1:0; } /** A replacement for the modulo operator */ public static int modulo(int i,int j) { return (i-j)>=0?modulo(i-j, j):i; } ``` [Answer] # PowerShell A quick solution in PowerShell. No arrays or strings used, either implicitly or explicitly. ``` function rev([int]$n) { $x = 0 while ($n -gt 0) { $x = $x * 10 $x += $n % 10 $n = [int][math]::Floor($n / 10) } $x } ``` Testing: ``` PS > rev(13457) 75431 PS > rev(rev(13457)) 13457 ``` [Answer] # C++ ``` #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { int i,size; float num; char ch; cout<<"enter the number \t: "; cin>>num; ofstream outf("tmp.tmp"); outf<<num; outf.close(); ifstream inf("tmp.tmp"); inf.seekg(0,ios::end); size=inf.tellg(); inf.seekg(-1,ios::cur); cout<<"Reverse of it\t\t: "; for(i=0;i<size;i++) { inf>>ch; if(ch!='0'||i!=0) cout<<ch; inf.seekg(-2,ios::cur); } inf.close(); remove("tmp.tmp"); getch(); return 0; } ``` ### OUTPUT Three sample runs ![enter image description here](https://i.stack.imgur.com/5iIt9.png) Test with zeros ![enter image description here](https://i.stack.imgur.com/DbtzV.png) It too **reverses floating numbers!!!** ![enter image description here](https://i.stack.imgur.com/cXhQh.png) If you want **to run this code** then run it on your computer because it creates a temporary file during its run-time and I am not sure if online compilers would make a temporary file on your computer [Answer] # ECMAScript 6 ``` reverse=x=>{ var k=-(l=(Math.log10(x)|0)), p=x=>Math.pow(10,x), s=x*p(l); for(;k;k++) s-=99*(x*p(k)|0)*p(l+k); return s } ``` Then: * `reverse(12345)` outputs `54321` * `reverse(3240)` outputs `423` * `reverse(6342975)` outputs `5792436` [Answer] # [Fission](https://github.com/C0deH4cker/Fission) ``` $SX/ \S?L K\O ``` This program reverses the input. ``` $ echo -n '12345' | fsn tac.fsn 54321 ``` [Answer] # FORTH I think this is the opposite of popular... but using Forth is always creative... Let's create a new word ``` : REV BEGIN S->D 10 U/ SWAP 1 .R DUP 0= UNTIL CR ; ``` Here, it uses word U/ that returns remainder and quotient, remainder is sent to output as number within a field 1 character long, until dividend is zero. No string is used, at least until something is sent to video. I do not use a modulo operator, instead I use integer division with remainder and quotient. Let's try ``` 12345 REV 54321 ok ``` ![ZX Spectrum emulator](https://i.stack.imgur.com/uwrLH.png) [Answer] # Turing Machine Code Using the syntax from [here.](http://morphett.info/turing/turing.html) ``` 0 * * l 0 0 _ # r 2 2 # # r 2 2 0 # l A 2 1 # l B 2 2 # l C 2 3 # l D 2 4 # l E 2 5 # l F 2 6 # l G 2 7 # l H 2 8 # l I 2 9 # l J 2 _ _ l Z A * * l A A _ 0 l Q B * * l B B _ 1 l Q C * * l C C _ 2 l Q D * * l D D _ 3 l Q E * * l E E _ 4 l Q F * * l F F _ 5 l Q G * * l G G _ 6 l Q H * * l H H _ 7 l Q I * * l I I _ 8 l Q J * * l J J _ 9 l Q Q # # r 2 Q * * r Q Z # _ l Z Z * * l ZZ ZZ _ * r ZZZ ZZ * * l ZZ ZZZ 0 _ r ZZZ ZZZ * * * halt ``` [Try it online!](http://morphett.info/turing/turing.html?2fe2a52485900fd0842811eab656e172) [Answer] # Python ``` import itertools def rev(n): l = next(m for m in itertools.count() if n/10**m == 0) return sum((n-n/10**(i+1)*10**(i+1))/10**i*10**(l-i-1) for i in range(l)) ``` [Answer] # C ``` #include <stdio.h> int c(int n) { return !n ? 0 : 1+c(n/10); } int p(int n) { return !n ? 1 : 10*p(n-1); } int r(int n) { return !n ? 0 : n%10*p(c(n/10))+r(n/10); } int main() { printf("%d\n", r(13457)); return 0; } ``` [Answer] ## Batch Missed the part about not using strings - oh well. ``` @echo off setLocal enableDelayedExpansion enableExtensions for /f %%a in ('copy /Z "%~dpf0" nul') do set "ASCII_13=%%a" set num=%~1 set cnum=%num% set len=0 :c if defined num set num=%num:~1%&set /a len+=1&goto :c set /a len-=1 for /L %%a in (%len%,-1,0) do set /p "=!ASCII_13!!cnum:~%%a,1!"<nul ``` [Answer] **Python 2** ``` import math def reverseNumber(num): length = int(math.ceil(math.log10(num))) reversed = 0 for i in range(0, length): temp = num // math.pow(10, length - i - 1) num -= temp * math.pow(10, length - i - 1) reversed += int(temp * math.pow(10, i)) return reversed print reverseNumber(12345) ``` ]
[Question] [ > > **Note:** The winning answer will be selected on **4/12/17** the current winner is [Jolf, 1 byte](https://codegolf.stackexchange.com/a/115323/58826). > > > I'm surprised that we haven't had a what's my middle name challenge on this site yet. I did alot of searching but found nothing. If this is a dup, please flag it as such. ## Your challenge Parse a string that looks like `Jo Jean Smith` and return `Jean`. ## Test cases ``` Input: Samantha Vee Hills Output: Vee Input: Bob Dillinger Output: (empty string or newline) Input: John Jacob Jingleheimer Schmidt Output: Jacob Jingleheimer Input: Jose Mario Carasco-Williams Output: Mario Input: James Alfred Van Allen Output: Alfred Van ``` (That last one is incorrect technically, but fixing that would be too hard.) ## Notes: * Names will always have at least 2 space-separated parts, with unlimited middle names between them or can be a list/array of strings. * Names may contain the alphabet (case-insensitive) and - (`0x2d`) * You may output a trailing newline. * You may require input to have a trailing newline. * Input from STDIN, a function parameter, or command-line argument is allowed, but hard-coding it in is not allowed. * Standard loopholes forbidden. * Output may be function return value, STDOUT, STDERR, etc. * Trailing spaces/newlines/tabs in the output are allowed. * Any questions? Comment below! **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest anwser in bytes wins!** [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 2 bytes (CP437) Accepts and returns a list of strings. ``` () ``` Explanation: ``` () Main wire, arguments: a ( Remove the first element of a ) ...and then the last element of that Implicit output ``` [Answer] # Vim, ~~6~~ 5 bytes ``` dW$BD ``` [Try it online!](https://tio.run/nexus/v#@58SruLk8v@/V35GnoJXYnJ@koJXZl56TmpGamZuapFCcHJGbmZKCQA "V – TIO Nexus") (outputs with a trailing space) Since Vim is reverse-compatible with V, I have included a TIO link for V. ### Explanation ``` dW " Delete up to the next word (removes the first name) $ " Go to the end of the line B " Go back one word D " Delete it ``` [Answer] # [Python](https://docs.python.org/), 24 bytes ``` lambda n:n.split()[1:-1] ``` [Try it online string input!](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqiQZ5WnV1yQk1mioRltaKVrGPu/oCgzr0QhRyMzr6AUKKr5Xyk4MTcxryQjUSEsNVXBIzMnp1gJAA "Python 2 – TIO Nexus") Input Format: **string** # [Python 2](https://docs.python.org/2/), 16 bytes ``` lambda n:n[1:-1] ``` [Try it online list input!](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqiQZ5UXbWilaxj7v6AoM69EIUcjM6@gtERDU/N/tFJwYm5iXklGopKOUlhqKpD0yMzJKVaKBQA "Python 2 – TIO Nexus") Input Format: **List** [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 133 bytes ``` {{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#@19dXasBApoQqFldC0HR1bWxGjYamnZAoepaoCIboBogD8gEomqN6lobO00bOyBJuQn//3vlZ@QpeCUm5ycpeGXmpeekZqRm5qYWKQQnZ@RmppT8100GAA "Brain-Flak – TIO Nexus") 132 bytes of code, plus 1 byte for the `-c` flag which allows ASCII input and output. Unfortunately, this contains lots of duplicated code, but it would be really difficult to reuse. I'll look into it later. Here's an explanation: ``` #While True { #Pop {} #Not equals 32 ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{} #Endwhile } #Pop the 0 {} #Reverse Stack {({}<>)<>}<> #While True { #Pop {} #Not equals 32 ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{} #Endwhile } #Pop the 0 {} #Reverse Stack {({}<>)<>}<> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ¦¨ ``` [Try it online!](https://tio.run/nexus/05ab1e#@39o2aEV//9Hq3vlZ@Sp66h7JSbnJ4HozLz0nNSM1Mzc1CIgNzg5IzczpUQ9FgA "05AB1E – TIO Nexus") If outputting a list of middle names isn't allowed, I'll change it. [Answer] ## Haskell, ~~23~~, ~~17~~ 9 bytes ``` init.tail ``` Takes and returns a list of strings. [Try it online!](https://tio.run/nexus/haskell#@59mm5mXWaJXkpiZ8z83MTNPwVahoCgzr0RBRSFNIVrJKz8jT0lHQckrMTk/CczIzEvPSc1IzcxNLQLxg5MzcjNTSpRi/wMA "Haskell – TIO Nexus") Drop first string, drop last string. Edit: @Generic Display Name noted, that the input can be a list of strings, which saved 6 bytes. Edit II: return list of strings instead of a single string [Answer] ## Mathematica, 10 bytes ``` Rest@*Most ``` An unnamed function that accepts and returns a list of strings. `Rest` discards the the last element, `Most` discards the first element, `@*` is function composition. Swapping `Rest` and `Most` or using right-composition `/*` instead would also work. This beats indexing via `#[[2;;-2]]&` by one byte. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 86 bytes ``` (()()){({}[()]<{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>>)}{} ``` [Try it online!](https://tio.run/nexus/brain-flak#JYsxCsAgDEWv4pgMvUHwAK4dxaG1UoWqULqFnN3GNvl8fj4vAwABkYHFAwZiFpiD/yLLL88SgACtViwKkTJ6aVTNd7JIVv3rxnA9N@O22HfjSjuvlFOp6TZrzLUcz1jiCw "Brain-Flak – TIO Nexus") Most of this code comes from [this answer](https://codegolf.stackexchange.com/a/114942/57100). If you like my solution you should upvote that one as well. ``` #Push 2 (()()) #Loop twice {({}[()]< #While not a space { #Pop {} #Not equals 32 ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{} #Endwhile } #Pop the 0 {} #Reverse Stack {({}<>)<>}<> #End loop twice >)}{} ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~17~~ 10 bytes *Saved 7 bytes thanks to @steve!* ``` $NF=$1=x;1 ``` [Try it online!](https://tio.run/nexus/awk#@6/i52arYmhbYW34/3@iQpJCskIKAA "AWK – TIO Nexus") Explanation: ``` $NF= set last word to $1= set first word to x an empty variable, ie empty string 1 default action, ie print everything ``` [Answer] # Java 7, 74 bytes ``` String f(String s){return s.substring(s.indexOf(' '),s.lastIndexOf(' '));} ``` # Java 8, 49 bytes ``` s->s.substring(s.indexOf(' '),s.lastIndexOf(' ')) ``` Function which identifies the first occurrence of the space character and the last one and extracts the middle. The resulting string is prefixed by a space character (at the time of the posting, OP hasn't clarified if leading spaces are allowed), which can be eliminated by adding `.trim()` to the code for an extra cost of 7 bytes. Compared to C#, Java has the advantage of specifying the end index instead of sub-string length, which brings down the byte count. [Answer] ## JavaScript (ES6), 22 bytes Takes and outputs an array of strings. ``` ([_,...a])=>a.pop()&&a ``` ### Test cases ``` let f = ([_,...a])=>a.pop()&&a console.log(f(["Samantha", "Vee", "Hills"])) console.log(f(["Bob", "Dillinger"])) console.log(f(["John", "Jacob", "Jingleheimer", "Schmidt"])) console.log(f(["Jose", "Mario", "Carasco-Williams"])) ``` ### String version (27 bytes) Takes and outputs a string. The output string is either a single space if no middle name was found, or the middle names with leading and trailing spaces. ``` s=>(/ .* /.exec(s)||' ')[0] ``` ``` let f = s=>(/ .* /.exec(s)||' ')[0] console.log(f("Samantha Vee Hills")) console.log(f("Bob Dillinger")) console.log(f("John Jacob Jingleheimer Schmidt")) console.log(f("Jose Mario Carasco-Williams")) ``` [Answer] # [Groovy](http://groovy-lang.org/), 19 bytes ``` {it.split()[1..-2]} ``` Explanation: ``` { it all closures have an implicit argument called "it" .split() splits by spaces by default. Returns an array of words [1..-2] take the whole array from the second index (1) to the penultimate index (-2). Implicitly return } ``` A closure / anonymous function [Answer] # Jolf, 1 byte ``` € ``` Gets the inside of the input. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=4oKs&input=WyJKb25hdGhhbiIsICJWYW4iLCAiQWxsZW4iXQ) [Answer] # [Perl 5](https://www.perl.org/), 27 18 bytes Need to run with `-n` option. ``` / (.+) /&&print$1 ``` [Try it online!](https://tio.run/nexus/perl5#@6@voKGnramgr6ZWUJSZV6Ji@P@/V35GnoJXYnJ@koJXZl56TmpGamZuapFCcHJGbmZKyb/8gpLM/Lzi/7p5AA "Perl 5 – TIO Nexus") Wanted to do something similar in sed first, but, unfortunately, it doesn't support non-greedy quantifier. It is needed in case middle name is more than one word. **Edit** -9 bytes thanks to **Dada**. Non-greedy quantifier is not needed anymore, among with some other things. [Answer] # PHP, 37 Bytes ``` <?=join(" ",array_slice($argv,2,-1)); ``` -4 bytes for an output as array ``` print_r(array_slice($argv,2,-1)); ``` ## PHP, 42 Bytes ``` echo trim(trim($argn,join(range("!",z)))); ``` ## PHP, 50 Bytes ``` echo preg_filter("#(^[^\s]+ |[^\s]+$)#","",$argn); ``` [Answer] # sed, ~~21~~ ~~19~~ ~~17~~ 15 bytes + `-E` new: *idea thanks to @user41805* *-2 thanks to @xigoi* *-2 thanks to @ user41805* ``` s/^\S+ |\S+$//g ``` old: *-1 thanks to @user41805* ``` s/\S+ ((.+ )*).+/\1/ ``` [Try it online!](https://tio.run/##HcvNCkIhEIbhvVcxi3YhXkN/EEIr4bRpM@l0FHQ8OHb7mbV7eD8@oaBXfo8h5uH2YIz6Y2fMGA4Lco8ICxFcU86ijvUJ56nEKzVla2Sw6Ge0s2SKlAo1cD6WFPrcheCGLVU4YUPxVd9/ZyyiLBYSOORXowAL8mQm/tStp8oy9OUL/0A "sed – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), 11 bytes ``` ^\S+ |\S+$ ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/gfFxOsrVADJFS4/v8PTsxNzCvJSFQIS01V8MjMySnmcspPUnABsjLz0lOLuLzyM/IUvBKTgYJeQJGc1IzUzNzUIoXg5IzczJQSoHxxqoJvYlFmvoJzYlFicXK@bjhIc2JuMQA "Retina – TIO Nexus") Matches the first word (including the space after it) and the last word, and removes both of them. If I/O can be a linefeed-separated list, it can be done in 8 bytes instead: ``` A1` G-2` ``` [Try it online!](https://tio.run/nexus/retina#FYs7CsMwEAV7neI1hjQq4hvkAzECVwKnSaGNslgL@oDk@ytyN8ww08U69NvVqZeeXf9khW4pUT4CYWPGIjE2dS9fPAdJ3rkqU0KGIT@kGSZyYElcYX1I8jtGb4yVqhQ8qFLzRb/PmVL7Aw) [Answer] # Javascript (ES6) ~~49~~ 16 bytes ## **Edit:** ``` a=>a.slice(1,-1) ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrV6FXnJOZnKphqKNrqPk/OT@vOD8nVS8nP10jTSNaKTgxNzGvJCNRSUdBKSw1FUR5ZObkFCvFampyoSt2yk8CKXABKsjMS08twqrIKz8jD6TKKzEZotwLqDYnNSM1MxeoA8gPTs7IzUwpwaG5GOwG38SizHwQwzmxKLE4OV83HGRnYi7YXf8B "JavaScript (Node.js) – TIO Nexus") **ungolfed:** ``` function(name) { return a.slice(1, -1); //start at the second item and end at the second to last item }; ``` I forgot some of the simple properties of [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice), and that the input can be an array. Thanks to @Neil and @fəˈnɛtɪk I was able to remove 27 bytes. Still not really competing. ## **Original:** This isn't really competing but here's a Javascript solution: ``` a=>{a=a.split(' ');return a.slice(1, a.length-1)} ``` This creates an anonymous function equal to: ``` function(name) { let name = name.split(' '); //first middle last -> [first, middle, last] return name.slice(1, name.length - 1); //get the second item to the second to last item in the array. } ``` ### How I golfed it This is a pretty simple golf. I turned the function into an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). Then I "minified" the code. This included renaming `name` into a single character(`a` in this case) and removing the `let` decloration of the variable. ### Snippet ``` var a=b=>b.slice(1,-1) //example code let form = document.querySelector('#form'), input = document.querySelector('#input'), result = document.querySelector('#result'); form.addEventListener('submit', (event) => { event.preventDefault(); let value = input.value.split` `; result.textContent = a(value).join(' '); }); ``` ``` <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <form id="form"> <div class="input-group"> <input id="input" class="form-control" /> <div class="input-group-btn"> <button class="btn btn-primary">Submit</button> </div> </div> </form> <p id="result"></p> ``` Hope this helps anyone who is stuck on the challenge. [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [4 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` †Û⁺% ``` [Try it!](https://zippymagician.github.io/Arn?code=LnsufQ==&input=U2FtYW50aGEgVmVlIEhpbGxzCkJvYiBEaWxsaW5nZXIKSm9obiBKYWNvYiBKaW5nbGVoZWltZXIgU2NobWlkdApKb3NlIE1hcmlvIENhcmFzY28tV2lsbGlhbXM=) # Explained Unpacked: `.{.}` ``` _ Variable initialized to STDIN; implied .{ Take .} Then drop Output implicit ``` Strings are split on spaces if any or ever character if there are non (when casted to an array). [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes ``` ;htw ``` [Try it online!](https://tio.run/##yygtzv7/3zqjpPz///9e@Rl5Cl6JyflJCl6Zeek5qRmpmbmpRQrByRm5mSklAA "Husk – Try It Online") -2 bytes from Zgarb. [Answer] # [Röda](https://github.com/fergusq/roda), 9 bytes ``` {_[1:-1]} ``` [Try it online!](https://tio.run/nexus/roda#JYuxCsIwGIRn8xRHZot0VVzUQQqdCjq0pfzGvybQJJLUqfbZa4rDwd13d5aMw4T@2CxTV@f7LG/nZTOhdmR5JyFbfNEnvT9Ro9siocM/yMZJzOh9wDoW81KRJTdqwo0ZVzMMUZz8A5fkjHtxEIXXDgWpBItEBtZsLAdUSlvzHFMfGSUF43GmQFH57L6eycYf "Röda – TIO Nexus") Not a very interesting solution. Takes a list from the stream and returns the middle names. 21 bytes and I/O: ``` {[(_/" ")[1:-1]&" "]} ``` [Try it online!](https://tio.run/nexus/roda#FYu9CsJAEAZr7yk@UogWQdIKNmohAauAFjGENW68hfuRu3Qxz36e3TDDWBKHGePhkeZ20@8KFNu22pdVt87YLWk14otPEDehV0tqyJKbNOHGjIsYE9XRP3HOJO7NQdVeO9Q0ZFlnY1izWA5oBm3lNeUeGVcK4nGiQHHw5f0/k40/ "Röda – TIO Nexus") This uses `/` (split) and `&` (join). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ḊṖ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR9fDndP@//@v7pWfkaeuo@6VmJyfBKIz89JzUjNSM3NTi4Dc4OSM3MyUEnUA "Jelly – TIO Nexus") This works as a non-inline link (i.e. function), not a full program. `'John','Jacob','Jingleheimer','Schmidt'` → `'Jacob','Jingleheimer'` As a full program, it would be 3 bytes: `ḊṖK`, which prints a space-separated middle name. [Answer] # Pyth, 2 bytes ``` Pt ``` [Online interpreter](//pyth.herokuapp.com?code=Pt&input=%5B%27John%27%2C%27Jacob%27%2C%27Jingleheimer%27%2C%27Schmidt%27%5D) [Answer] # C#, 67 bytes ``` s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' ')); ``` Anonymous function which identifies the first occurrence of the space character and the last one and extracts the middle. It also extracts a trailing space, which can be removed at the cost of 2 bytes. Full program with test cases: ``` using System; namespace WhatsMyMiddleName { class Program { static void Main(string[] args) { Func<string, string> f = s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' ')); Console.WriteLine(f("Jo Jean Smith")); // "Jean" Console.WriteLine(f("Samantha Vee Hills")); // "Vee" Console.WriteLine(f("Bob Dillinger")); // "" Console.WriteLine(f("John Jacob Jingleheimer Schmidt"));// "Jacob Jingleheimer" Console.WriteLine(f("Jose Mario Carasco-Williams")); // "Mario" Console.WriteLine(f("James Alfred Van Allen")); // "Alfred Van" } } } ``` [Answer] # [Kotlin](https://kotlinlang.org), 39 bytes ``` s.filterIndexed{i,j->i!=0&&i!=s.size-1} ``` [Try it online!](https://tio.run/nexus/kotlin#PY1PC4IwGMbP@SnWDrKBSl0lhY5J0MFPsNw7fWXO2BasxM9uq0OXh98Dzx/1NCQwV17R@VPrLZq@5qTaXKFQe7AXIyGAXDAb8xr31SFNo7rC4Rvy47qp2J8EGiZs70pytla8/jtLsntE8tqwwHR8uClGm3kwNCO0Ed18/0HMahgAJ7Bf33bDhNJTznmybh8 "Kotlin – TIO Nexus") i.e. ``` s.filterIndexed{ index, value -> index != 0 && index != (s.size - 1) } ``` [Answer] # VBA, 69 bytes ``` Sub m(n) f=InStr(1,n," ") Debug.?Mid(n,f+1,InStrRev(n," ")-f) End Sub ``` [Answer] ## [Grime](https://github.com/iatorm/grime), 6 bytes ``` <\ 0\ ``` [Try it online!](https://tio.run/nexus/grime#@28To2AQo/D/f3pWeoZCWnpGmUJ6egYA "Grime – TIO Nexus") Note the trailing space. ## Explanation ``` Match a substring S that satisfies: < S is contained in a string of the form \ a space 0 then S \ then another space. ``` This matches a substring that's surrounded by spaces. By default, Grime prints the longest match it finds (without the spaces). If no match exists, nothing is printed. [Answer] # R, ~~30~~ ~~27~~ 22 bytes Current solution due to user11599! ``` head(scan(,''),-1)[-1] ``` Takes input from stdin, returns each middle name as a separate string. Returns `character()` in the case of no middle name; that is, a vector of class `character` of length `0`. **Explanation:** Read stdin into a list of strings, separated by spaces ``` scan(,'') ``` Remove the last element. `head` returns the first `n` elements of a list, with `n` defaulting to `6`. If `n` is `-1` it returns all but the last element. ``` head(scan(,''),-1) ``` Now, remove the first element of this list. ``` head(scan(,''),-1)[-1] ``` This yields the middle name(s). [Answer] # Ruby, ~~24~~ 13 bytes ``` p ARGV[1..-2] ``` *Saved 11 bytes thanks to Piccolo pointing out that array-like output is allowed.* Takes the name as separate command line arguments, e.g.: ``` $ ruby script.rb John Jacob Jingleheimer Schmidt ``` or ``` $ ruby -e 'p ARGV[1..-2]' John Jacob Jingleheimer Schmidt ``` --- Previous code (outputs a proper string): ``` puts ARGV[1..-2].join" " ``` [Answer] # **Golang**, ~~152~~ 81 bytes ``` import ."strings" func f(x string)[]string{var k=Fields(x);return k[1:len(k)-1];} ``` It takes input as "Samantha Vee Hills" (with double quotes) and return the middle name to the stdout. [Try it Online!](https://tio.run/nexus/go#NY2xCoMwGIRn8xQ/gZYEWsG10rV0LAhdxCHYxIYkf20SiyA@u9Vqt7vvuLtW1EY0EpzQSLRrXz4CVS7SaTMpDdFrbAIlqsMaFOthJbysVjF8hAdzvmhpH4H1PPcydh7BlNnJSmSGH7MqH6dffzliHAaSLC3ctkgyf6ZFLVAxunvTA@yRr/A25/FPFUPOyTjRQjiB8SngLiVctbWBfgE "Try it online!") Edit: @Dada, note that the "function as answer is allowed" shorten my code 71 bytes. a big thanks! ]
[Question] [ *Inspired by [this](https://codegolf.stackexchange.com/q/210638/95792) challenge, which got closed. This is meant to be an easier, but no less interesting version of that.* This is the cops thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. For the robbers thread, see [here](https://codegolf.stackexchange.com/q/213963/95792). Cops will provide a program/function and a flag. Robbers will try to guess a password such that, when the password is given to the cop's program, the flag is outputted. # Basic rules * The language used should be provided. * The flag, which can be an integer, string, or value of any other type, should be provided. * The flag may be printed to STDOUT, returned from a function, or outputted using any of the other standard output methods, as long as you specify how it will be outputted. * The program/function can take the password through STDIN, as a function argument, or using any of the other standard input methods, as long as you specify how the it will be inputted. * A free online compiler/interpreter should also be linked, preferably with the cop's code already pasted in and ready to run. # Some more rules * There must be at least one valid password that causes your program to return the flag, and you should know at least one of those passwords when posting your answer. * In case of a function submission, the cop should *also* include a full runnable program including the function either in the answer or in the linked online compiler/interpreter. * If it is at all ambiguous what the type of the flag is, it must be specified. * If a cop's description of the output is ambiguous (e.g. "`HashSet(2, 1)` should be printed"), robbers are allowed take advantage of that (e.g. print the string "HashSet(2, 1)" instead of an actual hashset) * Forcing robbers to simply brute force the password is not allowed. * The program must take input, and must output the flag when given the correct password. When not given the correct password, you are free to error, output something else, or immediately terminate. If your program never halts if given the wrong password, you must tell robbers of this behavior so no one waits around for the program to output something. Cops's score will be the number of bytes their code takes up. Cop answers will be safe if they haven't been cracked for two weeks. # Example Cop: > > # Scala, 4 bytes > > > > ``` > x=>x > > ``` > > Flag: `Yay, you cracked it!` (an object of type `String` is returned from the lambda above) > [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM2loFCWmKOQZqUQXFKUmZeuYGsHZ/2vsLWr@A9RkF6aWlysYKugFFBaolCZX1oEFclILUpVAhpSANRSkpOnkaYBFtfU5Kr9DwA "Scala – Try It Online") > > > Robber: > > Password: the string "Yay, you cracked it!" > [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM2loFCWmKOQZqUQXFKUmZeuYGsHZ/2vsLWr@A9RkF6aWlysYKugFJlYqaNQmV@qkFyUmJydmqKQWaKoBDSlAKinJCdPI00DrFRTk6v2PwA) > > > # Find Uncracked Cops ``` <script>site='meta.codegolf';postID=5686;isAnswer=false;QUESTION_ID=213962;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # [PHP](https://php.net/), 89 bytes, [cracked](https://codegolf.stackexchange.com/a/214020/48931) by [Benkerd22](https://codegolf.stackexchange.com/users/98889/benkerd22) ``` <?php $x=file_get_contents('php://stdin'); if(!preg_match('/.*golf.*/',$x))echo trim($x); ``` [Try it online!](https://tio.run/##DclJCoAgFADQvacoCByI3DfQUSTsO0DpR//C21vLx8OAve8nBmRTO1x8wHggY3MiSFQF/2fVutIdE5cbi06MWMCb9yIbBNeL8vlxi9J8npqUYEMeqMRX/Np6/wA "PHP – Try It Online") Outputs `golf`, exactly. [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes, [cracked](https://codegolf.stackexchange.com/a/214005/39531) by [Christian Mann](https://codegolf.stackexchange.com/users/39531/christian-mann) Edited to reduce score. See [revision history](https://codegolf.stackexchange.com/posts/213978/revisions) for ungolfed version. Another Python answer. ``` import re,sys p=sys.stdin.read() if re.match('^[exc\dhrkb\slim_=:;,.ants]*$',p):exec p;print a ``` [Try it online!](https://tio.run/##JclBCsMgEEDRfU7homBSREKXCTlJkxarUxxazTDOwpzeBrr5PPh0SNzzrTVMtLMoBlOO0tFy1hYJmC2DC/3Q4fucNjnxsdePO1S/hsif11q@mJ7LNBvrspTtetGGhgkqeEUzMWZRrrU/9Fj9GED/AA "Python 2 – Try It Online") Flag is `0xc0de`. The output should be to STDOUT. --- My solution was basically the same as Christian's: The regex only accepts a very limited number of characters. Notable exclusions are all kinds of brackets, string delimiters, almost all operators and the `p` for `print` and `input`. `a='0xc0de'` doesn't match the regex, and `a=hex(49374)` neither. With these restriction I don't know of a way to call any function that returns a value. I would be interested in counterexamples ;). One exception is `a==b`, which calls `a.__eq__(b)`, but since `q` is not available, you can only do this with builtin types. The idea is to use the fact that `print a` calls `a.__str__` to get a string representation of the object `a`. This means we need to define an object `a` with a custom `__str__` method, which is then called by string. Instantiating objects is not possible without `()`, but luckily we can define methods on classes rather than instance objects using metaclasses. The metaclass is required to have an `__init__` function, that takes three arguments and returns `None`. A good choice for this is an `__init__` function of a different class. This result into the final solution: ``` class b: __str__ = 49374 .__hex__ __init__ = 0 .__init__ class a: __metaclass__ = b ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzknsbhYIcmKSwEI4uOLS4ri4xVsFUwsjc1NFPTi4zNSK@LjoZKZeZklYFkDkAyExwUxIBFmQG5qSSJYCKww6X9BUWZeiULifwA "Python 2 – Try It Online") This doesn't work in Python 3 for two reasons: * `int`'s dont have a `__hex__` method anymore. * The syntax for metaclasses has changed. In Python 3 this would look like `class a(metaclass=b): ...`, which uses forbidden brackets [Answer] # [Python 2.7](https://docs.python.org/2.7/), 189 bytes, [cracked](https://codegolf.stackexchange.com/a/213970/15100) by [ovs](https://codegolf.stackexchange.com/users/64121/ovs) ``` import re inp = raw_input() if not re.match(r"^[\w\d=]*$", inp): quit() exec(inp) a = raw_input() b = raw_input() flag = a == b if flag == True: print("%s %s"%(a, b)) ``` [Try it online!](https://tio.run/##XY3BDsIgDIbvfYqGSAJm8WDixYSrT@DNqYHJHIkDZJDp0yO423po2q9f/vpvHJzd52xG70LEoAGM9SgwyPlephQZB9OjdfW4G2XsBhbI7dLO7UNctxvSYNH4EbDUO5nq64/uWKUAchWlVnv/ks@CiiZQQf20EIHnkPSS6oOxkRE6IZ0IZbJBxXnOUhzgVOR/@wE) Flag is `The Flag`, output to STDOUT. This might be a bit easy, but hopefully still fun! [Answer] # [R](https://www.r-project.org/), 60 bytes, [cracked by Paul](https://codegolf.stackexchange.com/a/214194/86301) ``` function(x) chartr("zyxwvu", "RRRRRR", tolower(x[1] + x[2])) ``` [Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NCUyE5I7GopEhDqaqyorysVElHQSkIDICskvyc/PLUIo2KaMNYBW2FimijWE3N/2kahlZGmv8B "R – Try It Online") As in [my previous challenge](https://codegolf.stackexchange.com/a/213985/86301), the flag to output is the string `"R"`. In other words, you need to find `x` such that `f(x)=="R"` is `TRUE`. --- The solution is e.g. `as.roman(c(2, 3))`. This object is represented as `c(II, III)`; it is of mode `numeric` but of class `roman`. Since it is numeric, addition works, giving the roman integer `V`. But since it is of class roman, `tolower` coerces it to string, giving the string `"v"`. Then `chartr` translates this to `"R"`. [Answer] # [Haskell](https://www.haskell.org/), 246 bytes, [cracked by ovs](https://codegolf.stackexchange.com/a/214064/3852) ``` infix 0# 0:p#x=p#1:x 1:p#x:z=p#x:x:z 2:p#x:y:z=p#(y+x):z 3:p#x:y:z=p#(y-x):z 4:p#x:y:z=p#(y*x):z 5:p#x:y:z=p#div y x:z 6:p#x:y:z=p#y:x:y:z 7:p#x:y:z=p#y:x:z c:p#x|(q,_:r)<-span(<c)p=r#until((==0).head)(q#)x _#x=x main=readLn>>=print.(#[]).take 60 ``` [Try it online!](https://tio.run/##Xc9LCoMwEAbgfU4hZJO0VWIfFoLxBL2BiAS1GLQhPlqi9O5pkpV2M/P/32JgWj51Td8bI@RT6IBAQKiCmikYUw1il@nK3LQbnH1fvKDlqLG1y85Cb9edHbzdNlaLT7AE7mKy0YX6BO5/toLKyRcNp5KOOA0nxSVKK6zYCN9yFj1CjBEctQ2vMRog1qC0P2jw4kKy0epDZhlTo5BzhGBe4GjmXRMkxJicFD8 "Haskell – Try It Online") Input is taken over STDIN, and output is printed to STDOUT. The flag is the output string: `[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499]` (Those are the primes from 2 to 499.) [Answer] # [R](https://www.r-project.org/), 29 bytes, [cracked by pppery](https://codegolf.stackexchange.com/a/213986/86301) ``` function(x) intToUtf8(cos(x)) ``` [Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NCUyEzryQkP7QkzUIjOb8YKKD5P03DQPM/AA "R – Try It Online") The flag to output is the string `"R"`. --- The solution is `5.1i`. Although \$\forall x\in\mathbb R, -1\leq\cos x\leq1\$, those bounds don't hold for complex \$x\$: \$\cos(a+ib)=\cos x\cosh y -i \sin x\sinh y\$, which is unbounded. We want to find \$x\$ such that \$ \cos x=82\$ (the ASCII codepoint of `R`); pppery gave the answer `x=5.0998292455...i`. The shorter `x=5.1i` works, because `intToUtf8` can take a complex argument and cast is as integer by ignoring the imaginary part, and rounding down the real part to an integer. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes, [cracked](https://codegolf.stackexchange.com/a/213995/48931) by [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) ``` OÆTP ``` [Try it online!](https://tio.run/##y0rNyan8/9//cFtIwP///wE "Jelly – Try It Online") Outputs `160.58880817718872`. ¯\\_(ツ)\_/¯ [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), [cracked by *@ovs*](https://codegolf.stackexchange.com/a/214029/52210) ``` F}žhм9£.ER.V* ``` +5 bytes to close [a different crack found by *@ovs*](https://tio.run/##MzBNTDJM/f/frVbPNUgvTOv/f0OugqLMvBKN1LwUW/WYPENjcxNjC0tTYxNzdc38InVDBSN1AA) (although he's free to post it as an actual crack instead if he chooses to). [Try it online.](https://tio.run/##MzBNTDJM/f/frfbovowLeywPLdZzDdIL0/r/PzEpGQA) Expected output: `\n137438953472\n` (where the `\n` are of course newlines). **Code explanation:** ``` F # Loop `N` in the range [0, input-1) } # Close the loop žhм # Remove all digits 9£ # Only keep the first 9 characters .E # Evaluate and execute as Python code R # Reverse .V # Evaluate and execute as 05AB1E (legacy) code * # Multiply two values # (after which the result is output implicitly with a single trailing newline) ``` Tip 1: the program + intended solution only works in the legacy version of 05AB1E (built in Python 3) for two reasons. This won't work in the latest 05AB1E version (built in Elixir), where all these builtins as mentioned in the code explanation above will also act the same as *described*. Tip 2: it won't time out on TIO, ~~so an input like `274359834731`, which would result in `137438953472\n` (note it's missing the intended leading newline) isn't the intended solution, since the loop takes too long~~ (no longer possible after the 5 bytes had been added). The intended solution runs in less than 0.2 seconds on TIO. Tip 3: one of two reasons mentioned in tip 1 is a bug with `.E` and a certain type of input (which is ALSO in [*@ovs*' initial crack](https://tio.run/##MzBNTDJM/f/frVbPNUgvTOv/f0OugqLMvBKN1LwUW/WYPENjcxNjC0tTYxNzdc38InVDBSN1AA)), that I abuse to get the intended result. Tip 4: there are three loose inputs (separated with newline delimiter), and the first and third inputs are the same [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes, [cracked](https://codegolf.stackexchange.com/a/214003/81203) by [w123](https://codegolf.stackexchange.com/users/98349/w123) ``` #//.a_:>Head@a& ``` (Edited to reduce byte count. Solution should be the same; all the unintended solutions I can think of should be trivial to adapt.) Flag: `flag`. Input by function argument, and output by return value. [Try it online!](https://tio.run/##y00syUjNTSzJTE78r6yvr5cYb2XnkZqY4pCoFv3/f6y@fkBRZl7JfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 93 bytes, [cracked](https://codegolf.stackexchange.com/a/214081) by [pppery](https://codegolf.stackexchange.com/users/46076/pppery) ``` from functools import*;lambda a,b,c:(d:=reduce)(lambda e,f:e[f],c,d(getattr,b,__import__(a))) ``` [Try it online!](https://tio.run/##bVBBbsMgELz7FSv3AhHKIe2hcpUH9A1RZG1gsZEwIFha5fUppq3UQ2@7O6OZ2Ul3XmN4fk35YXPcwNagOUZfwG0pZobD8AQ30lgLwTsEIgMYfkFk4JWgMGZWULzTBDX1m46GgCMsxBCDv/djV3cxwKdrtpVBrxgWF5aOegoLrxBt3zZ0oasM9kwf6MU4jv9nPLx53G4GAdVN6UmY6ZzJVE1S/ACk7EQXe1VaGdESIXNu3Hn@FphngVLKR3O4nF6mqxyGlF1gYcWhW7uQKgu5c8TYF1gpU3vD@9YONFL1yL0bAwlL2ccCCFyTp/0lzEvdKHDZS/nbxajGhp2Ox@MovwA "Python 3.8 (pre-release) – Try It Online") * Input is function arguments, output is function return value. * Flag is the string `pxeger` (my username) --- pppery didn't find my intended solution, and noone else has, but here it is: The function > > takes a module name to import, a list of attributes, and a list of indeces, and looks up a value. It is best explained with an example: > `! f("spam_module", ["eggs", "ham"], [2, 3]) ! # ==> ! import spam_module ! spam_module.eggs.ham[2][3] !` > > > Given that: > > My username is `regexp` (as in Regular Expression), backwards, and `regexp` is quite a common variable name > > > So we need to: 1. > > Find a use of the word `regexp` in the standard library > > > 2. > > Access it using Python's extensive runtime introspection API > > > 3. > > Reverse it > > > Specifically > > In the `csv` module there is a class called `Sniffer` which has a method called `_guess_quote_and_delimiter` which uses a variable called `regexp`. > > > Python lets you > > access that variable name as an element of the attribute `.__code__.co_varnames`. (I recommend looking into everything you can get from `__code__` - it's very interesting, albeit excessive) > > > Then > > `regexp` is the sixth variable name used there, so I lookup `csv.Sniffer._guess_quote_and_delimiter.__code__.co_varnames[5]` > > > Finally, > > reverse that by slicing it with `slice(None, None, -1)` (equivalent to `x[::-1]`) > > > So the whole solution is > > `f("csv",["Sniffer","_guess_quote_and_delimiter","__code__","co_varnames"],[5,slice(None,None,-1)])` > > > [Answer] # [dotcomma](https://github.com/Radvylf/dotcomma), 819 bytes, [cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/214535#214535) by [the default.](https://codegolf.stackexchange.com/users/36445/the-default) ``` [[,.][[,.],[.[[,.][.].]],.[[.,]]].,][,.] [,],[[,.][[.][[[.][.].,][,.][.].,][[.][. ][.].,].[[[,.][[].[],.][[[,][,.].,]].,][ [,][.]].][,.][[,][[[,.][[[[.][.].,][,][. ][,][,.].,]].,].[[[,.][[[,][,.].,]][[].[ ],].,][[,]].][,.][[,.][[[[.]][.][[[.][[. ]][[[[.]][[.][.][.].,][,.].,][.][,.].,][ ,.][[.]].,][,.][.].,][[.]][,.].,][,.].][ .].,]][[.]].,]].,][,],[[[,.][.[[[,.][[]. [.],].,].][[,.][,.][,.].,]].,]][[,.].[.[ [.][,.].][[[[.][.][.][.].,][,.].,],][[[, .][[[[[[[[[,][,.].,][,.].,][,][,.][.][.] [.].,][.].,][.].,],],][.][.][.][.][.].,] .,][.][.].,][,][,][,][,][,][,][[,.][[,][ ,][,]].,][,][,][,][[,.][[,][,][,][,][,]] .,][,][[,.][[[,.][[,]].,]].,][,]],.[[[,. ][[[[.][.][.].,][,][,][,.][[].[,],].,]]. ,][[[,.][[[[[[[,.][.].,][.][.].,],][.]., ][.].,],].,][.][.][.][.].,][,][,][,][[,. ][[[,.][[,][,][,]].,]].,]]][.][[.]][[.]] ``` [Try it online!](https://radvylf.github.io/dotcomma/?p=WyJbWywuXVtbLC5dLFsuW1ssLl1bLl0uXV0sLltbLixdXV0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VtbLl1dIiwiXCJXcm9uZyBwYXNzd29yZCA6KFwiIiwyXQ) The flag is `accepted`. Since this language is quite new and I've only seen two people (the inventor and me) using it so far, I tried to find a good balance between too hard and too easy. If I've done it correctly, the code will have two valid passwords. The interpreter is written in Javascript and therefore runs on your local machine. On my notebook it takes about five seconds to show "accepted" after entering the correct password. **Solution:** The intended solution is the number [49375](https://radvylf.github.io/dotcomma/?p=WyJbWywuXVtbLC5dLFsuW1ssLl1bLl0uXV0sLltbLixdXV0uLF1bLC5dXG5bLF0sW1ssLl1bWy5dW1tbLl1bLl0uLF1bLC5dWy5dLixdW1suXVsuXG5dWy5dLixdLltbWywuXVtbXS5bXSwuXVtbWyxdWywuXS4sXV0uLF1bXG5bLF1bLl1dLl1bLC5dW1ssXVtbWywuXVtbW1suXVsuXS4sXVssXVsuXG5dWyxdWywuXS4sXV0uLF0uW1tbLC5dW1tbLF1bLC5dLixdXVtbXS5bXG5dLF0uLF1bWyxdXS5dWywuXVtbLC5dW1tbWy5dXVsuXVtbWy5dW1suXG5dXVtbW1suXV1bWy5dWy5dWy5dLixdWywuXS4sXVsuXVssLl0uLF1bXG4sLl1bWy5dXS4sXVssLl1bLl0uLF1bWy5dXVssLl0uLF1bLC5dLl1bXG4uXS4sXV1bWy5dXS4sXV0uLF1bLF0sW1tbLC5dWy5bW1ssLl1bW10uXG5bLl0sXS4sXS5dW1ssLl1bLC5dWywuXS4sXV0uLF1dW1ssLl0uWy5bXG5bLl1bLC5dLl1bW1tbLl1bLl1bLl1bLl0uLF1bLC5dLixdLF1bW1ssXG4uXVtbW1tbW1tbWyxdWywuXS4sXVssLl0uLF1bLF1bLC5dWy5dWy5dXG5bLl0uLF1bLl0uLF1bLl0uLF0sXSxdWy5dWy5dWy5dWy5dWy5dLixdXG4uLF1bLl1bLl0uLF1bLF1bLF1bLF1bLF1bLF1bLF1bWywuXVtbLF1bXG4sXVssXV0uLF1bLF1bLF1bLF1bWywuXVtbLF1bLF1bLF1bLF1bLF1dXG4uLF1bLF1bWywuXVtbWywuXVtbLF1dLixdXS4sXVssXV0sLltbWywuXG5dW1tbWy5dWy5dWy5dLixdWyxdWyxdWywuXVtbXS5bLF0sXS4sXV0uXG4sXVtbWywuXVtbW1tbW1ssLl1bLl0uLF1bLl1bLl0uLF0sXVsuXS4sXG5dWy5dLixdLF0uLF1bLl1bLl1bLl1bLl0uLF1bLF1bLF1bLF1bWywuXG5dW1tbLC5dW1ssXVssXVssXV0uLF1dLixdXV1bLl1bWy5dXVtbLl1dIiwiNDkzNzUiLDIsMF0). I initially wanted to use the decimal value of 0xC0DE (49374), but got things messed up in my head and ended up one number too high. The comparison function works in a way that the input and the solution are being decremented in a loop until one of them becomes zero. Then the other one must be 1 to be accepted. That means, 49376 is also a valid solution. Other known solutions are [49375], [49376], [49375, -1] and [49376, -1] The way this was meant to be cracked: dotcomma is an esoteric language that is really hard to read, so I don't wanted anybody, to really "decompile" it and know exactly, what each command does, but to puzzle around with the blocks. As already stated in my first comment, the language works a bit like Brain-Flak. The input will implicitly become the initial values in the queue and after the program ended, the content of the queue will implicitly be printed. So an empty program is a [cat program](https://esolangs.org/wiki/Cat_program). To solve this, you first need to find the start and end of each block, what will result in something like this: ``` (1) [[,.][[,.],[.[[,.][.].]],.[[.,]]].,] (2) [,.] (3) [,], (4) [[,.][[.][[[.][.].,][,.][.].,][[.][.][.].,].[[[,.][[].[],.][[[,][,.].,]].,][[,][.]].][,.][[,][[[,.][[[[.][.].,][,][.][,][,.].,]].,].[[[,.][[[,][,.].,]][[].[],].,][[,]].][,.][[,.][[[[.]][.][[[.][[.]][[[[.]][[.][.][.].,][,.].,][.][,.].,][,.][[.]].,][,.][.].,][[.]][,.].,][,.].][.].,]][[.]].,]].,] (5) [,], (6) [[[,.][.[[[,.][[].[.],].,].][[,.][,.][,.].,]].,]] (7) [[,.].[.[[.][,.].][[[[.][.][.][.].,][,.].,],][[[,.][[[[[[[[[,][,.].,][,.].,][,][,.][.][.][.].,][.].,][.].,],],][.][.][.][.][.].,].,][.][.].,][,][,][,][,][,][,][[,.][[,][,][,]].,][,][,][,][[,.][[,][,][,][,][,]].,][,][[,.][[[,.][[,]].,]].,][,]],.[[[,.][[[[.][.][.].,][,][,][,.][[].[,],].,]].,][[[,.][[[[[[[,.][.].,][.][.].,],][.].,][.].,],].,][.][.][.][.].,][,][,][,][[,.][[[,.][[,][,][,]].,]].,]]] (8) [.] (9) [[.]] (10) [[.]] ``` Then try out, what each block does. Block 1 (filter): This block actually answers *the default.*'s question (sorry, I didn't answer it clearly. No other submission had to answer details about the password, and the "wrong password :(" was the only red herring I added to the program. So I didn't want to say "No, it's actually a five digit integer"). If you run that with different data types (numbers, strings, lists of numbers or strings), you will see that it returns the first element of a string or list, if it has multiple elements, or it will return a 1 and the element, if you enter a number or a string/list with only a single letter in it. The purpose of this becomes clear, if you add the second block to it. Block 2 (delete first element): If you run blocks 1 and 2, you will see that the output will be empty if you input anything with multiple values. Only single numbers or single letters will remain in the queue. (Actually *the default.* found a bug in the programming language, because negative values should not be possible in the queue. You can't programmatically write a negative value onto the queue, and negative values won't be written to the output, but apparently they still can be read from input). So from this point, it should be clear that the password is either a number or a single letter. Block 3 (run next block, if there's something in the queue): This will not change the output, but is there for control. You can ignore it. Block 4 (build constants for comparison): This will build the list [49375, 96, input]. At this point, you may ask yourself, what the big number is for and that it may be important for the password. Block 5 (run next block, if there's something in the queue): Same as block 3. Since there are three values in the queue, this will also rotate the queue, so the output is [96, input, 49375]. Block 6 (compare input and password): As stated earlier, this decrements the input and the number 49375, until one of them becomes zero. Then decrements the other another time and appends the 96 to it. The output is [49375-input (or input-49376), 96]. At this point, you should point out that you have to change the input in a way that the first value becomes something interesting, like 0, -1 or maybe 96? Block 7 (write output): This block checks if the first value is 0. If so, it uses the second value to build the string "accepted". If not, it fills the queue with the string "rejected". Blocks 8-10: Those are just fillers, so my submission will have a nice rectangle shape. [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes, [cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/213989#213989) by [r3mainer](https://codegolf.stackexchange.com/users/11006/r3mainer) ``` import re,time b=input()[:40] a=time.time() re.match(b,b) if time.time()-a>9:print(0) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoVackMzeVK8k2M6@gtERDM9rKxCCWK9EWJKoHIjQ0uYpS9XITS5IzNJJ0kjS5MtMUkCR1E@0srQqKMvNKNAw0//8HAA "Python 3 – Try It Online") Prints `0`. Works on TIO. [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [19 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn), [cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/214178#214178) by [r3mainer](https://codegolf.stackexchange.com/users/11006/r3mainer) ``` €weL˜ù┼󪘛’U•žfcmº ``` ~~I would provide the unpacked form, but it's rather trivial to decode~~ adds to the challenge if you have to decode it yourself. Not terribly difficult, but it requires you to access the source code. The flag you want is: ``` 7.9228162514264337593543950336e+28 ``` this was done in the [online interpreter](https://zippymagician.github.io/Arn). This shouldn't be too difficult, and multiple inputs should theoretically work. However, I encourage you to try and figure out the one I used (you will know immediately if you found the right one). # Solution + Explanation The flag r3mainer used was `J0e_Biden!`. The flag I intended to be the solution will remain hidden, as to encourage others to try :). However, to make it easier, here is an explanation for the program `:*:*((|:(|\):}):i0^:i"n` ``` :* Square :* Square ( Begin expression ( |: Bifurcate* ( |\ Fold with concatenation (remove spaces) _ Variable initialized to STDIN; implied ) End expression :} Tail ) :i Index of 0 Literal zero ^ To the power of _ Implied :i "n" literal string ``` * Note: bifurcate is currently broken, and this program takes advantage of that. Basically, `|:(...):}` is a synonym for reversing the string `...` (don't you love bugs?) [Answer] I'll get things started off with one that probably won't be extremely difficult but may take some thought. # [Python 3](https://docs.python.org/3/), 78 bytes: [cracked](https://codegolf.stackexchange.com/a/213966/68942) by [wastl](https://codegolf.stackexchange.com/users/78123/wastl) ``` while 1: try:l=input() except:l='' exec(l,{},{"exit":0,"quit":0}) print(1) ``` [Try it online!](https://tio.run/##JYrLCsMgEADP8StkL1HwEOlN6MeUZKmC6FY3JCHk220et5lhaGOf06u1xYeI0jrRcdlcfIdEMystOlxHJD5L31@Co4pmP8wOuAYGNxj4zTcc50wlJFZWt/YQ0KfWJZdJfjNW6bEg6D8 "Python 3 – Try It Online") Flag is nothing. As in, . The program should not output anything. [Answer] # [Perl 5](https://www.perl.org/) (`-n`), 33 bytes, [Cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/213982#213982) by [Neil](https://codegolf.stackexchange.com/users/17602/neil) ``` length()<28 && !/\w/ && eval eval ``` [Try it online!](https://tio.run/##K0gtyjH9/z8nNS@9JEND08bIQkFNTUFRP6ZcH8RILUvMARP////LLyjJzM8r/q@bBwA "Perl 5 – Try It Online") The flag is `Flag`. The input is stdin and output stdout. [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 23 bytes, [Cracked](https://codegolf.stackexchange.com/a/213998/44718) by [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) ``` a=readline() print(a+a) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/z/Rtig1MSUnMy9VQ5OroCgzr0QjUTtREygBAA "JavaScript (SpiderMonkey) – Try It Online") * Expect output: `aaa` * Input / Output use stdin, stdout [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 104 bytes, [cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/214030#214030) by [@thedefault](https://codegolf.stackexchange.com/users/36445/the-default) ``` *^(% _+*^)%(0_+%)% _+^$($_^_$_^_$+!!!!!!!!!+++++++++^$)+_^_ _+$(_^^^^^^^^^^_$^$)+xx_+$(_0+_$^$)+!!@@@ ``` The flag to this program is `$$$` output to STDOUT. I guarantee that the flag will appear in at least 5 seconds given the correct password. [Try it online!](https://tio.run/##PYpBCoAgEEWvojCCNhuP4DXazCAqtIgSI@r2loY9@Iv/309hizl4v5Y11zqRVkIwTmSUtozK9EqggYl7UA5wQGDwVe0JmumHoZn77rPFr0rpnKt13s8isj@Oay9RLKkk@QA) ## What does it even do? ``` *^(% _+*^)%(0_+%)% _+^$($_^_$_^_$+!!!!!!!!! # Push the password integer... +++++++++^$)+_^_ _+$(_^^^^^^^^^^_$^$)+ # ...from STDIN onto the stack xx_+$(_0+_$^$)+ # Divide by the ASCII value of 0 i.e 48 !!@@@ # Print the result as a character thrice. ``` Therefore: \$x = 48 · 36 = 1728\$ Where x is the password. FYI 36 is the ASCII value of `$`. [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, 32 bytes, [cracked](https://codegolf.stackexchange.com/a/214107/92901) by @Sisyphus Edit to reduce score by 1: `(p eval$_)` → `p(eval$_)`. ``` !/[Scfpv\.:\?'"%<`(]/&&p(eval$_) ``` Input via STDIN. Flag is `"""\n` (three double-quote characters with trailing newline) printed to STDOUT. [Answer] # [Ruby](https://www.ruby-lang.org/), 85 bytes, [cracked twice](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/214105#214105) by [the-default](https://codegolf.stackexchange.com/users/36445/the-default) ``` x=gets puts (x[0...n=x.size/2].to_i*x[n..-1].to_i).to_s(36) if x[-9..-1]=="123456789" ``` [Try it online!](https://tio.run/##KypNqvz/v8I2PbWkmKugtKRYQaMi2kBPTy/PtkKvOLMqVd8oVq8kPz5TqyI6T09P1xDC0wSRxRrGZpoKmWkKFdG6lmA5W1slQyNjE1MzcwtLpf//LS3MzUxNjI0M4YIA "Ruby – Try It Online") Flag is: `codegolfguessmypasswordrobber001qtr5vxskd64lddb0gsyw2w4hp8zd1t0j`, as a string, in STDOUT. ## Explanation Two prime numbers have been chosen, each having 50 decimal digits. One of them ends with "0123456789", and their product begins with `codegolfguessmypasswordrobber` when written in base 36. ``` p = 91642145128772682907542781226248344977333099146327 q = 15416260853069873976599113800182718102190123456789 n = p*q = 1412779214440046356547554449820888121475969772090456386542605159205021769559275444371360154172564003 ``` This looks like an [RSA factoring challenge](https://en.wikipedia.org/wiki/RSA_Factoring_Challenge), and factorizing the semi-prime is definitely one way to find the password. Bruteforce was explicitly forbidden for this challenge, though. And apparently, it wasn't too hard anyway to factorize n with an open-source program called [cado-nfs.](http://cado-nfs.gforge.inria.fr/) I should probably have picked a longer semiprime, e.g. [RSA-200](https://en.wikipedia.org/wiki/RSA_numbers#RSA-200). There's a (badly hidden) backdoor : [`String#to_i`](https://ruby-doc.org/core-2.7.2/String.html#method-i-to_i) is happy to convert any string to an integer. > > Extraneous characters past the end of a valid number are ignored. > > > So `"1x000123456789".to_i` gets converted to `1`, and the challenge becomes trivial. It's now possible to "factorize" n as n\*1. [Answer] # [Python 3.7](https://docs.python.org/3.7/), 84 bytes, [Cracked](https://codegolf.stackexchange.com/a/219217/64121) Takes Python code as input from input from stdin. The code is only executed if it consists of a subset of the characters of `'\n ,.:;=@_abcdefijlmnoprstvz'` and the keyword `class` occurs at most two times. ``` c=open(0).read() {*c}<{*'\n ,.:;=@_abcdefijlmnoprstvz'}!=3>c.count('class')!=exec(c) ``` [Try it online! (on 3.7.4)](https://tio.run/##K6gsycjPM/7/P9k2vyA1T8NAU68oNTFFQ5OrWiu51qZaSz0mT0FHz8ra1iE@MSk5JTUtMysnNy@/oKi4pKxKvVbR1tguWS85vzSvREM9OSexuFhdU9E2tSI1WSNZ8///gqJMoISuoYGRqSYA "Python 3 – Try It Online") The flag is `-1025` (printed to STDOUT). My intended solution: > > > ``` > @print > @int.__invert__ > @object.__sizeof__ > class o:__slots__=__name__,__name__,__name__,__name__ > ``` > > [Try it online!](https://tio.run/##dctBCoMwEIXhvaewq6iIFNzZpuQghSGOI1V0EpJUWsWzp7b7bh4/Hzz7Dg/DdYwojSXOznnlSHdZnmwF7tetEHdOy6q5SAW6xY76YZxmNtb5sKxiP8n6hhWaJ4dM4KS9F/lJ0oswwzxGZd3AIVHHVAADL@QCQKJMOxJ@yQ8rmf6g3zc1zUGTCR5AArCeCaD8Hx8 "Python 3 – Try It Online") > > > [Answer] # [JavaScript (V8)](https://v8.dev/), 26 bytes, [cracked](https://codegolf.stackexchange.com/questions/213963/guess-my-password-robbers-thread/235306#235306) by emanresu A Seemed like a cool challenge, so here's an easy one. Pass any JS value into the function. Flag is `true` printed to stdout. (boolean, not string.) If there is any other output apart from `true` is considered not cracked. ``` x=>console.log({}[x][x]()) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/wtYuOT@vOD8nVS8nP12juja6IhaINDQ1/6dpaP4HAA "JavaScript (V8) – Try It Online") Intended solution: > > `{v: 0, toString() {Object.prototype.f = () => true; return this.v++ ? "f" : "valueOf"}}` > > > This works because: > > `{}[x]` calls the `toString` method of `x` > > > > > `valueOf` returns the original object > > > > > Therefore, modifying the Object prototype to add a method `f` in the `toString` method of `x`, returning `"valueOf"` the first time and `"f"` the second time does the trick > > > [Answer] # Stable Rust 1.52.1, 171 bytes ``` fn u<T:'static>(_:T){use std::any::*;let _=unsafe{(1 as*mut T).read_volatile()};let a=type_name::<T>();print!("{}",&a[41..]=="(((), ()), ((), ()))>"&&a.contains("&dyn"))} ``` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=42b77b899185325676337b94b5d4e470) Entering the right password will print `true` and won't segfault (or print anything to stderr). This relies on implementation-defined behavior, so this will only probably work on different versions of Rust. > > Password: `u::<fn(&dyn std::any::Any)->(((),()),((),()))>`. > > > Explanation: > > There are probably other valid passwords but this is the intended one. > The function is generic over all `'static` types so you can put in > almost anything into the function. However, most types will immediately > segfault- `unsafe{(1 as*mut T).read_volatile()}` is a volatile read of > address `1`. However, not everything will segfault- in Rust, types with a > size of zero can be read from any well-aligned non-null pointer, and > most zero-sized types have an alignment of one. > > > > > This brings me to the second safeguard: parsing the type name. > This is the implementation-defined part- the `type_name` function > is only guaranteed to be a best-effort description of the type. > The type name was chosen to be particularly difficult to find a > zero-sized type to match. The solution I have uses a particular > monomorphization of the function I submitted to pass the criteria. > It is likely possible to define another type that meets the criteria. > [Ungolfed code with solution entered.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5789fa4be23e9abef6b7d2cb30c8e39f) > > > [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 31 bytes (safe) ``` I.dI:⅛kF*×u⅛Ė.SṪḢ42f÷₍+*Π¾J∑Cøṙ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=I.dI%3A%E2%85%9BkF*%C3%97u%E2%85%9B%C4%96.S%E1%B9%AA%E1%B8%A242f%C3%B7%E2%82%8D%2B*%CE%A0%C2%BEJ%E2%88%91C%C3%B8%E1%B9%99&inputs=&header=&footer=) Flag: `EEEEEEEEEEEEEEEEEEEEEEEE` Flag should be printed to STDOUT. Under the original specifications for this cop, okie had a clever crack [here](https://codegolf.stackexchange.com/a/237565/101522), but that was an unintentional crack, so a couple clarifications are in order. * The input will not contain any subset of the flag. * The program should not return any errors. > > Intended Solution: `21⅛3` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=I.dI%3A%E2%85%9BkF*%C3%97u%E2%85%9B%C4%96.S%E1%B9%AA%E1%B8%A242f%C3%B7%E2%82%8D%2B*%CE%A0%C2%BEJ%E2%88%91C%C3%B8%E1%B9%99&inputs=21%E2%85%9B3&header=&footer=) > > Before execution, Vyxal attempts to execute the input and see what it returns. The reason for this is to allow you to do things like input a list in Vyxal format, and it will work as intended. This also allows you to put Vyxal code in the input, but normally it will just get captured as a string. For example, and input of `69d:e` would just input the string `69d:e`. > > However, if you put a number at the end of that input, it only captures that number as input, and discards all of the code leading up to it. For example, an input of `69d:e2` would input the number `2`, and discard the `69d:e`. > > In the discarded code, trying to assign variables and functions doesn't do anything, nor does assigning to the global register, since those are in a different scope from the main program. However, the global array is global, and persists after the input execution. In the solution, `21⅛3` pushes `21` to the global array, then inputs `3`. > > Now let's go through the program step-by-step. > > `.dI:⅛` - Push 1 to the global array and to the stack > > `kF*` - Multiply `FizzBuzz` by the 1 on the stack > > `u⅛` - Push -1 to the global array > > `× Ė` - Multiply the `FizzBuzz` by the inputted 3 to get `FizzBuzzFizzBuzzFizzBuzz` > > `.SṪḢ` - Push `.` > > `42f÷₍+*Π` - Push 48 > > `¾J∑` - Concatenate the global array and the 48 and add. We used the input to push 21 to the global array, so this comes out to 69. > > `C` - Convert to character to get `E` > > `øṙ` - Regex replace: In string `FizzBuzzFizzBuzzFizzBuzz`, replace with `E` anything matching the regex `.` > > > [Answer] # JavaScript, 57 bytes, [cracked](https://codegolf.stackexchange.com/a/238169/87606) by Conor O'Brien ``` alert("xx".split(new RegExp(p=prompt())).join``.length>2) ``` The flag is `true`. <https://xkcd.com/2217/> [Answer] # JavaScript (ES6), 117 bytes, [cracked by @tjjfvi](https://codegolf.stackexchange.com/a/238394/) ``` _=>{c=prompt();if(/[^!-'*-Za-z]/.test(c))throw'CHEATER!';x=(o=>o(o.a,o.b,o.c,o.d))((0,eval)(c));return(x===x&&x!==x)} ``` The function must be called without arguments. The password must be provided via `prompt()`, and the *return value of the function* must be `true` (boolean). Otherwise logging `true` to the console **is not** acceptable. You may only use language features as specified in the ES6 standard, using platform-dependent APIs is forbidden. You can test your passwords here: ``` f=_=>{c=prompt();if(/[^!-'*-Za-z]/.test(c))throw'CHEATER!';x=(o=>o(o.a,o.b,o.c,o.d))((0,eval)(c));return(x===x&&x!==x)} console.log(f()) ``` I *really* hope I managed to filter out all passwords other than the intended one :D [Answer] # [JavaScript (V8)](https://v8.dev/), 25 bytes, [Cracked](https://codegolf.stackexchange.com/a/213981/97730) by [user](https://codegolf.stackexchange.com/users/95792/user) ``` y=s=>(l=s.length)?l:l/l|1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v9K22NZOI8e2WC8nNS@9JEPTPscqRz@nxvB/cn5ecX5Oql5OfrpGpYZSQWJxcXl@UYqSpuZ/AA "JavaScript (V8) – Try It Online") The flag is `0`. **Input**: function parameter. **Output**: returned value of function. [Answer] # [Python 3.8](https://docs.python.org/3/), 95 bytes, [cracked by wastl](https://codegolf.stackexchange.com/a/213974) ``` import os;(c:=os.getenv("A")).isidentifier()and c not in"printinput"and eval(c)(os.getenv("B")) ``` Input is via environment variables. (no TIO link because it doesn't support them). Flag is `the_flag`. @wastl did not find my intended solution - theirs was much simpler. Here is what I indended: `PYTHONBREAKPOINT=builtins.print A=breakpoint B=the_flag python -c 'import os;(c:=os.getenv("A")).isidentifier()and c!="print"and eval(c)(os.getenv("B"))'` The `PYTHONBREAKPOINT` environment variable describes a function to be called when you use `breakpoint()`. Python has a lot of weird implicit behaviours like this. I intentionally left "input is environment variables" vague so you would think it would only be `A` and `B` [Answer] # [><>](http://esolangs.org/wiki/Fish), 4 bytes ``` i10p ``` [Try it online!](https://tio.run/##S8sszvj/P9PQoOD/fwA) The flag is `Something smells delicious...` printed to STDOUT, and takes input form STDIN. Invalid keys may not always terminate the program. Not a difficult one, but I like this feature. [Answer] # [JavaScript](https://nodejs.org), 2465 bytes, [cracked](https://codegolf.stackexchange.com/a/214195/31957) by [the default.](https://codegolf.stackexchange.com/users/36445/the-default) ``` X=([...O],S=[])=>{let M,F,a,b,R,n;M=F=0;while(O.length)eval(("?S.shift())#[a,b]!2);F=a==b;?a-b)#M++#?M)#%#M=0#M=%#R=%O=[]#n=%n!n);if(F)O=n.concat(O)".split`#`[O.shift()]||"").replace(/%/g,"S.pop();").replace(/\?/g,"S.push(").replace(/!/g,"=S.splice(-"));return R};const U=prompt().split``.map(e => e.charCodeAt()).join``.replace(/9/g,"").split("").map(e=>+e);R={s:20,m:0x80000000,a:1103515245,c:12345,get q(){return R.s=(R.a*R.s*+R.c)%R.m},i(v){return R.q/~-R.m*v|0},get b(){return R.i(2)},h([...a]){for(i=~-a.length;i>0;i--){j=R.i(i+1);[a[i],a[j]]=[a[j],a[i]]}return a}};R.s=U.reduce((p,c)=>p+c,0);class S{constructor(w,n=0){this.w=w;this.n=n;this.s={};this.c={}}N(T=this){return new S(T.w,T.n)}P(T=this){for(let i=0;i<T.w;i++)if(!T.c[i])T.A(i,T.n++);return T}M(s,t,T=this){let A=T.c[s],B=T.c[t];T.s[A]=T.s[A]||[];T.s[B]=T.s[B]||[];T.s[A].push(...T.s[B]);T.s[B].map(c=>{T.c[c]=A});delete T.s[B]}S(a,b,T=this){return T.c[a]==T.c[b]}A(c,s,T=this){T.c[c]=s+="";T.s[s]=T.s[s]||[];T.s[s].push(c)}*[Symbol.iterator](){yield*Object.entries(this.s)}Z(f=false,T=this){let C,b,c,v,N,r,g,l,m;C=[];b=[c=0];for(;c<~-T.w;c++){if(T.S(c,c+1)||(!f&&R.b)){C.push(b);b=[c+1]}else{T.M(c,c+1);b.push(c+1)}}C.push(b);v=[];N=T.N();if(!f){for(let[i,s]of T){let q=R.i(s.length-1);if(!q)q++;g=R.h(s).slice(0,q);v.push(...g);g.map(c=>N.A(c,i))}}r=[];C.map(c=>c.map((e,i,a)=>{l=i+1==a.length;m=!l*2;m|=1*(v.indexOf(e)!==-1);r.push(m)}));return[N.P(),r]}static F(w=10,h=10){let s=new S(w).P(),r,g=[[1]],i=0;for(;i<w;i++)g[0].push(1,1);for(let i=0;i<h;i++){[s,r]=s.Z(i===h-1);g.push(...I(r))}return g}};let I=(r, last=false)=>{let D=[1],E=[1];r.map(c=>{D.push(0,+((c&2)==0));E.push(+((c&1)==0),1)});return[D,E]};class B{constructor(w=10,h=10){this.m=S.F(w,h);this.r=0;this.G=true;this.f()}a(x=this.x,y=this.y){return this.m[y][x]}f(T=this){T.x=T.y=T.ey=1;while(T.a()!=0)T.x++;T.ex=this.m[0].length-1;while(T.a(T.ex)!=0)T.ex--}W(){return this.x==this.ex&&this.y==this.ey}d(r=this.r){return [[0,1],[-1,0],[0,-1],[1,0]][r]}L(){this.r++;this.r%=4}F(){let o=this.x,p=this.y,d=this.d();this.x+=d[0];this.y+=d[1];if(this.a()==1){this.x=o;this.y=p;this.G=false}if(this.W()){console.log("win");this.G=false}}M(r){r=this.r+r;r%=4;let m=-1,d=this.d(r),x=this.x,y=this.y;while(this.a(x,y)!=1){x+=d[0];y+=d[1];m++}return m}T(f){let ms=[1,3,0,2],v=f(ms.map(e=>this.M(e)));while(v&&this.G){this["KLFK"[v%4]].bind(this)();v>>=2}return this.G}R(f){let Y=999;while(this.G&&Y-->0)this.T(f)}}(new B()).R(a=>X(U,a)) ``` [Try it online!](https://tio.run/##ZVaPb9o6EP5X@CEquzFewjbptdlRtd1aTRtlAqa3Lc/SQgiQigQap/wQeP9639lOaPtepZazfb777rvvTO/DdSijPFkV7Ww5iZ9W@TJdFTWoEVqDbg2XUSwlD/PZOugI/@kHkIBz3hdsCIGg0N0v4qLWYzcsZGM2YJnfgxtw/c08WcSkzxdxNivmNF6HC0IaF0Mu58m0IJQ2A7wg6h3q30AIMPYvwvaYNnuO07zo0War2QMXf1vNAbT6mKqZQSurZ9RPpuSG9iHj0TKLwoL0aYPL1SIpfjd/B/0qvjgcGg3K83i1CKOYvGm9mbHGkK@WK0L9lwf/XJQnj3JOXh7U9T4MTWxctxuU@nlcPOZZbaB8TC6L2newfBFaQvjN03BFYk1dzKN5mF8jqZe6Xn6/TDI8P8Y/0/Eb5UWiLXMVuk5M/QHs5XnHZem5u/3LtT8sPPc89@17733n3XsWnXudt/g5Q/ofCN1X0LgEMuDhKRqnzoBHtDXgqWIJWb/weXjzp43bp@uDq0yE8csICelQxeam0aGg@@kyJwn8aYdlN/2k6/pJu03396C9E8ejfhAGiWBhcC8EBPqD6Q2hyqihUr7G9h0JmDxi/WTFIpTPyomYS/1oEUpZG@4NrfljVGDKDcvApftinki@gY1vjAwya0jYK2tFaKk7MgK9OpaRxZvakIz4ho14RtW347muRms2QZUmH9DBTxyHoqrqIx4hZDrilyTRt3C76vhI9YhkBauC6ACXoC9Iwa6MUQh/xGVwKcB@HA6B3bmyO1fPO5fCyg35tSe0dDQSiHCodMBIwKWi/iTGZHHNOqgh0XP2n1q1dyjAwBgLdUkiJo8@ZSjpQKNh0kiLRz7jkSWeiKrTYLhLx8sFT4o4D7ENApWxS@LF5LQ/vo@jgsdZkSexJLYLVP0iU5iGCxm/IucaUUZsze5YzmZswVL/GofYH0MQgSt83QQ/@vCnrfmPkOg9NmDEh4g8QjUdDqQ@PTkZ8DGl@2sLbkzNbccTKsZsWFev9PbHJXy0lXp2X@uMd1jsHTHPRn167H6QMCmW09rIon0wOpalvtuedX@gD47jz/BsTiQOqnkHXPaAkY/9m1F/VnXtjmvmE4ogcp36ujqIjEFilrDQPJmAIwNwnKcU6ovTjp8ewDsla55kk3jbn5KY1gE0mNymS6k6vkHBHf9GKMuFkkVYJFHthmzAc9kc/9iaJNgR2FDryWYQBJ4QTAvf8J98sNqfBW4pAI9httcDMjcu@0BiLpD8F74EAIai2ZGEzyTHoksxznDS9fXPQHJWw7kurDyq74qPgCjYJ/0XC6sE/9EGc5lDSHTSoYCjT/1PdtfseWYPAaojBx/ZJ6HKt@Pq9dvxzIXRaYoPOTLE5tS@GTnWZoxbwCuxtaeEqpBsjYr5lu2ssTuOmY0U7ESwFWpKngdsixrb4W@8A6/85hvxkGD7XHxNtigiPCvjpprsSmcvnLVHeSHettvqb/I67xbs/Xh7cmJxVRs7NSG5tfPjnSBwGdIctD3m4ofL2nqlFyJA0XwlJTE5grNGC96pG2K1s6w4WJUcsIk1JqQkcOvABCuxi51eYDtxaMwaSwfwygxbWJZesKo4N4JQlTuWSk33louYL5Yz0tgkWYO@dsYHWFdX1unkvgZshJbijDzjyyn7XwdLmktsuI9EI7yqhgp@6jiViFM1IlPLRSpRquwtc1lHsDVMSSqrb2oTsIdzilK1KdZlc25t8UHjy9ebL41g3XonBB/jYBsQFFlcd7vQUS87fKsGVc6fcHZ29hL17cnJz3a761Kz0tiUInq@r/S/FgMSQvcH@Y6vC316eurtPmerx6L@Lw "JavaScript (Node.js) – Try It Online") **The flag is `win`**. There should be no other output produced by the program. Although I designed this program to work with Firefox's implementation of JavaScript, it also works on node, hence the link. Input is a string through `prompt`, which is substituted for a command line argument in the header of the node TIO link. There is very much method in this madness; brute force is neither recommended nor viable, hopefully. Slightly golfed. More so an attempt to make it to 2 weeks, than doing it with the lowest score possible—a proof of concept, if you will. ## Or, try it here, in your browser ``` X=([...O],S=[])=>{let M,F,a,b,R,n;M=F=0;while(O.length)eval(("?S.shift())#[a,b]!2);F=a==b;?a-b)#M++#?M)#%#M=0#M=%#R=%O=[]#n=%n!n);if(F)O=n.concat(O)".split`#`[O.shift()]||"").replace(/%/g,"S.pop();").replace(/\?/g,"S.push(").replace(/!/g,"=S.splice(-"));return R};const U=prompt().split``.map(e => e.charCodeAt()).join``.replace(/9/g,"").split("").map(e=>+e);R={s:20,m:0x80000000,a:1103515245,c:12345,get q(){return R.s=(R.a*R.s*+R.c)%R.m},i(v){return R.q/~-R.m*v|0},get b(){return R.i(2)},h([...a]){for(i=~-a.length;i>0;i--){j=R.i(i+1);[a[i],a[j]]=[a[j],a[i]]}return a}};R.s=U.reduce((p,c)=>p+c,0);class S{constructor(w,n=0){this.w=w;this.n=n;this.s={};this.c={}}N(T=this){return new S(T.w,T.n)}P(T=this){for(let i=0;i<T.w;i++)if(!T.c[i])T.A(i,T.n++);return T}M(s,t,T=this){let A=T.c[s],B=T.c[t];T.s[A]=T.s[A]||[];T.s[B]=T.s[B]||[];T.s[A].push(...T.s[B]);T.s[B].map(c=>{T.c[c]=A});delete T.s[B]}S(a,b,T=this){return T.c[a]==T.c[b]}A(c,s,T=this){T.c[c]=s+="";T.s[s]=T.s[s]||[];T.s[s].push(c)}*[Symbol.iterator](){yield*Object.entries(this.s)}Z(f=false,T=this){let C,b,c,v,N,r,g,l,m;C=[];b=[c=0];for(;c<~-T.w;c++){if(T.S(c,c+1)||(!f&&R.b)){C.push(b);b=[c+1]}else{T.M(c,c+1);b.push(c+1)}}C.push(b);v=[];N=T.N();if(!f){for(let[i,s]of T){let q=R.i(s.length-1);if(!q)q++;g=R.h(s).slice(0,q);v.push(...g);g.map(c=>N.A(c,i))}}r=[];C.map(c=>c.map((e,i,a)=>{l=i+1==a.length;m=!l*2;m|=1*(v.indexOf(e)!==-1);r.push(m)}));return[N.P(),r]}static F(w=10,h=10){let s=new S(w).P(),r,g=[[1]],i=0;for(;i<w;i++)g[0].push(1,1);for(let i=0;i<h;i++){[s,r]=s.Z(i===h-1);g.push(...I(r))}return g}};let I=(r, last=false)=>{let D=[1],E=[1];r.map(c=>{D.push(0,+((c&2)==0));E.push(+((c&1)==0),1)});return[D,E]};class B{constructor(w=10,h=10){this.m=S.F(w,h);this.r=0;this.G=true;this.f()}a(x=this.x,y=this.y){return this.m[y][x]}f(T=this){T.x=T.y=T.ey=1;while(T.a()!=0)T.x++;T.ex=this.m[0].length-1;while(T.a(T.ex)!=0)T.ex--}W(){return this.x==this.ex&&this.y==this.ey}d(r=this.r){return [[0,1],[-1,0],[0,-1],[1,0]][r]}L(){this.r++;this.r%=4}F(){let o=this.x,p=this.y,d=this.d();this.x+=d[0];this.y+=d[1];if(this.a()==1){this.x=o;this.y=p;this.G=false}if(this.W()){console.log("win");this.G=false}}M(r){r=this.r+r;r%=4;let m=-1,d=this.d(r),x=this.x,y=this.y;while(this.a(x,y)!=1){x+=d[0];y+=d[1];m++}return m}T(f){let ms=[1,3,0,2],v=f(ms.map(e=>this.M(e)));while(v&&this.G){this["KLFK"[v%4]].bind(this)();v>>=2}return this.G}R(f){let Y=999;while(this.G&&Y-->0)this.T(f)}}(new B()).R(a=>X(U,a)) ``` ## Intended solution the default.'s solution was very close to being exactly the same as mine, and in fact, conceptually equal to mine. However, mine has a bit tighter encoding: > > `Z5[_\\#\]:#][4\]!!!!\]\\\\ \\\]:(Z5[_\\#\]:#][4\] \\\]4\\\]:4\\\\\\\\\\\\\\\\\\\\%` > > > I'll probably released a half-golfed, half-annotated version of the source later. [Answer] # [Python 3](https://docs.python.org/3/), 70 bytes, [cracked by @ovs](https://codegolf.stackexchange.com/a/231473) ``` c=compile(c:=open(0,"rb").read(),"","exec").replace(co_code=c) exec(c) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5NCsIwEIX3PUWYVQKxuBQhV_AKIU4nJFAzIZ1CPYubbvRO3sb6t33v8b3v9qhXSVzW9T5L3B2eMzrkS80jaTw6rlT03kI7g-kbhUEbC2CBFsJPUseA25I98kAOTRemiZrAiUVFbkoSqRhyEcVRJQpblYvC3vuB0fvuDdJovuc_h7_LCw) Works in CPython 3.9.6. Takes input from STDIN and should output `42` with a trailing newline to STDOUT. --- The challenge was to create something of a polyglot between Python source code and CPython bytecode. The Python source would be compiled (so it needed to be syntactically valid), and then have its bytecode replaced with itself, keeping constants and names. My solution was: ``` d,F,d,S,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,44,43,42 ``` Disassembly: ``` Bytes Instruction Argument Meaning d, LOAD_CONST 44 stored integer 42 F, PRINT_EXPR 44 ignored d, LOAD_CONST 44 stored integer 42 S, RETURN_VALUE 44 ignored ... [garbage...] ``` The list of numbers is just to get the Python compiler to store enough constants for `,` (decimal codepoint 44) to be a valid argument in order to index into the tuple and load `42`. By the way, `PRINT_EXPR` is an opcode used solely by the Python shell to print the return value of an expression. It's never used in normal code, but it's very useful for hacking around in bytecode-land. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/22921/edit). Closed 9 years ago. [Improve this question](/posts/22921/edit) **Task:** I know we can all add two numbers the short way, using `+`. Your task is to create the longest code you can to add two input numbers. **Rules:** * All of the code must be on topic (don't fill it with non-addition code to add length) * The count is in characters, but do not count tabs, spaces, or newlines. * Do not use extraneously long variable names * This is [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"), so the longest answer wins! [Answer] ## **C - 2,739,341,494,945,868,415,002 (Not including whitespace)** Brute force for the win. Only handles integers, and preserves overflow behavior. Here's a snippet of the code: ``` int addnumbers(int x, int y) { if (x == -2147483648 && y == -2147483648) return 0; if (x == -2147483648 && y == -2147483647) return 1; if (x == -2147483648 && y == -2147483646) return 2; if (x == -2147483648 && y == -2147483645) return 3; if (x == -2147483648 && y == -2147483644) return 4; if (x == -2147483648 && y == -2147483643) return 5; if (x == -2147483648 && y == -2147483642) return 6; if (x == -2147483648 && y == -2147483641) return 7; if (x == -2147483648 && y == -2147483640) return 8; if (x == -2147483648 && y == -2147483639) return 9; if (x == -2147483648 && y == -2147483638) return 10; if (x == -2147483648 && y == -2147483637) return 11; if (x == -2147483648 && y == -2147483636) return 12; if (x == -2147483648 && y == -2147483635) return 13; if (x == -2147483648 && y == -2147483634) return 14; if (x == -2147483648 && y == -2147483633) return 15; if (x == -2147483648 && y == -2147483632) return 16; if (x == -2147483648 && y == -2147483631) return 17; if (x == -2147483648 && y == -2147483630) return 18; if (x == -2147483648 && y == -2147483629) return 19; if (x == -2147483648 && y == -2147483628) return 20; if (x == -2147483648 && y == -2147483627) return 21; if (x == -2147483648 && y == -2147483626) return 22; if (x == -2147483648 && y == -2147483625) return 23; if (x == -2147483648 && y == -2147483624) return 24; if (x == -2147483648 && y == -2147483623) return 25; if (x == -2147483648 && y == -2147483622) return 26; if (x == -2147483648 && y == -2147483621) return 27; if (x == -2147483648 && y == -2147483620) return 28; if (x == -2147483648 && y == -2147483619) return 29; if (x == -2147483648 && y == -2147483618) return 30; if (x == -2147483648 && y == -2147483617) return 31; if (x == -2147483648 && y == -2147483616) return 32; if (x == -2147483648 && y == -2147483615) return 33; if (x == -2147483648 && y == -2147483614) return 34; if (x == -2147483648 && y == -2147483613) return 35; if (x == -2147483648 && y == -2147483612) return 36; if (x == -2147483648 && y == -2147483611) return 37; if (x == -2147483648 && y == -2147483610) return 38; if (x == -2147483648 && y == -2147483609) return 39; if (x == -2147483648 && y == -2147483608) return 40; if (x == -2147483648 && y == -2147483607) return 41; if (x == -2147483648 && y == -2147483606) return 42; if (x == -2147483648 && y == -2147483605) return 43; if (x == -2147483648 && y == -2147483604) return 44; if (x == -2147483648 && y == -2147483603) return 45; if (x == -2147483648 && y == -2147483602) return 46; if (x == -2147483648 && y == -2147483601) return 47; if (x == -2147483648 && y == -2147483600) return 48; if (x == -2147483648 && y == -2147483599) return 49; if (x == -2147483648 && y == -2147483598) return 50; if (x == -2147483648 && y == -2147483597) return 51; if (x == -2147483648 && y == -2147483596) return 52; if (x == -2147483648 && y == -2147483595) return 53; if (x == -2147483648 && y == -2147483594) return 54; if (x == -2147483648 && y == -2147483593) return 55; if (x == -2147483648 && y == -2147483592) return 56; if (x == -2147483648 && y == -2147483591) return 57; if (x == -2147483648 && y == -2147483590) return 58; if (x == -2147483648 && y == -2147483589) return 59; if (x == -2147483648 && y == -2147483588) return 60; if (x == -2147483648 && y == -2147483587) return 61; if (x == -2147483648 && y == -2147483586) return 62; if (x == -2147483648 && y == -2147483585) return 63; if (x == -2147483648 && y == -2147483584) return 64; if (x == -2147483648 && y == -2147483583) return 65; if (x == -2147483648 && y == -2147483582) return 66; if (x == -2147483648 && y == -2147483581) return 67; if (x == -2147483648 && y == -2147483580) return 68; if (x == -2147483648 && y == -2147483579) return 69; if (x == -2147483648 && y == -2147483578) return 70; if (x == -2147483648 && y == -2147483577) return 71; if (x == -2147483648 && y == -2147483576) return 72; if (x == -2147483648 && y == -2147483575) return 73; if (x == -2147483648 && y == -2147483574) return 74; if (x == -2147483648 && y == -2147483573) return 75; if (x == -2147483648 && y == -2147483572) return 76; if (x == -2147483648 && y == -2147483571) return 77; if (x == -2147483648 && y == -2147483570) return 78; if (x == -2147483648 && y == -2147483569) return 79; if (x == -2147483648 && y == -2147483568) return 80; if (x == -2147483648 && y == -2147483567) return 81; if (x == -2147483648 && y == -2147483566) return 82; if (x == -2147483648 && y == -2147483565) return 83; if (x == -2147483648 && y == -2147483564) return 84; if (x == -2147483648 && y == -2147483563) return 85; if (x == -2147483648 && y == -2147483562) return 86; if (x == -2147483648 && y == -2147483561) return 87; if (x == -2147483648 && y == -2147483560) return 88; if (x == -2147483648 && y == -2147483559) return 89; if (x == -2147483648 && y == -2147483558) return 90; if (x == -2147483648 && y == -2147483557) return 91; if (x == -2147483648 && y == -2147483556) return 92; if (x == -2147483648 && y == -2147483555) return 93; if (x == -2147483648 && y == -2147483554) return 94; if (x == -2147483648 && y == -2147483553) return 95; if (x == -2147483648 && y == -2147483552) return 96; if (x == -2147483648 && y == -2147483551) return 97; if (x == -2147483648 && y == -2147483550) return 98; if (x == -2147483648 && y == -2147483549) return 99; if (x == -2147483648 && y == -2147483548) return 100; //etc... } ``` This is obviously way to big to upload either here or on Pastebin, so here's a program that will generate the source code for the function (direct the output to a file - assuming you have the drive space): ``` #include <stdio.h> int main() { int x, y; printf("int addnumbers(int x, int y)\n{\n"); for (x=-2147483648;x<2147483648;x++) { for (y=-2147483648;y<2147483648;y++) { printf("\tif (x == %d && y == %d) return %d;\n", x, y, x+y); } } printf("}\n"); } ``` I shudder at how long the function for long longs would be... **EDIT:** Recalculated the score (should be correct) to give exact count. I prefer to think that I golfed it by 10²² characters when I removed the whitespace. [Answer] # C++, 3573 3573, then it was getting boring, but I can continue adding more layer of abstraction. ``` #include <iostream> #include <vector> class Number { public: typedef int Representation; class InvalidNumber { }; Number(); Number( const InvalidNumber& invalid ); explicit Number( const Representation& v ); friend Number operator + ( const Number& rop, const Number& lop ); bool operator == ( const Number& v ); bool operator != ( const Number& v ); bool operator == ( const Representation& v ); bool operator != ( const Representation& v ); bool IsValid() const; Representation GetRepresentation() const; private: Representation mValue; bool mValid; }; Number::Number() : mValue { 0 }, mValid { false } { } Number::Number( const Number::InvalidNumber& invalid ) : mValue { 0 }, mValid { false } { } Number::Number( const Representation& v ) : mValue { v }, mValid { true } { } bool Number::IsValid() const { return mValid; } Number::Representation Number::GetRepresentation() const { return mValue; } bool Number::operator == ( const Number& v ) { return ( v.mValid == mValid ) && ( v.mValue == mValue ); } bool Number::operator != ( const Number& v ) { return ( v.mValid != mValid ) || ( v.mValue != mValue ); } bool Number::operator == ( const Number::Representation& v ) { return ( mValid ) && ( v == mValue ); } bool Number::operator != ( const Number::Representation& v ) { return ( !mValid ) || ( v != mValue ); } Number operator + ( const Number& rop, const Number& lop ) { if( rop.mValid && lop.mValid ) { return Number { rop.mValue + lop.mValue }; } else { return Number { Number::InvalidNumber() }; } } Number NumberParser( const char* numberString ) { const char* p = numberString; while( *p != '\0' ) { if( !isdigit( *p ) ) { return Number { Number::InvalidNumber() }; } ++p; } Number::Representation value = atoi( numberString ); return Number { value }; } std::ostream& operator<< ( std::ostream& os, const Number& num ) { if( num.IsValid() ) { os << num.GetRepresentation(); } else { os << "Invalid number"; } return os; } class SimpleOperation { public: typedef Number Result_t; typedef Number Parameter_t; virtual ~SimpleOperation(); virtual Result_t operator()( const Parameter_t&, const Parameter_t& ) = 0; }; SimpleOperation::~SimpleOperation() { } class AssociativeOperation : public SimpleOperation { }; class SimpleSum : public AssociativeOperation { public: virtual Result_t operator()( const Parameter_t&, const Parameter_t& ); }; SimpleSum::Result_t SimpleSum::operator()( const Parameter_t& a, const Parameter_t& b ) { Result_t res = a + b; return res; } class PackOperation { public: AssociativeOperation::Result_t operator()( const std::vector<AssociativeOperation::Parameter_t>& ); virtual AssociativeOperation& getOperation() = 0; }; AssociativeOperation::Result_t PackOperation::operator()( const std::vector<AssociativeOperation::Parameter_t>& parameters ) { AssociativeOperation& operation = getOperation(); AssociativeOperation::Result_t tempResult = AssociativeOperation::Result_t { 0 }; for( auto param : parameters ) { tempResult = operation( tempResult, param ); } return tempResult; } class PackSum : public PackOperation { public: virtual AssociativeOperation& getOperation(); private: SimpleSum mSum; }; AssociativeOperation& PackSum::getOperation() { return mSum; } void print_usage() { std::cout << "Sum operator1 operator2\n"; std::cout << "print the sum of the operator \n"; } void print_parsingError( int argIndex ) { std::cout << "Error while parsing argument " << argIndex << "\n"; std::cout << "Aborting...\n"; } void print_result( Number res ) { std::cout << res << "\n"; } int main( int argc, char* argv[] ) { if( argc < 3 ) { print_usage(); return 1; } std::vector<Number> addends; int opIdx = 1; while( opIdx < argc ) { Number n = NumberParser( argv[opIdx] ); if( n == Number::InvalidNumber() ) { print_parsingError( opIdx ); return 1; } addends.push_back( n ); opIdx++; } PackOperation* op = new PackSum(); Number result = ( *op )( addends ); delete op; print_result( result ); return 0; } ``` [Answer] # Ruby, 29048 (can be as high as necessary, but I had to get it under the character limit for posts) ``` require 'zlib' # gzip deflated data data = "x\x9C\x01\xA3'\\\xD8x\x9C\x01\x98'g\xD8x\x9C\x01\x8D'r\xD8x\x9C\x01\x82'}\xD8x\x9C\x01w'\x88\xD8x\x9C\x01l'\x93\xD8x\x9C\x01a'\x9E\xD8x\x9C\x01V'\xA9\xD8x\x9C\x01K'\xB4\xD8x\x9C\x01@'\xBF\xD8x\x9C\x015'\xCA\xD8x\x9C\x01*'\xD5\xD8x\x9C\x01\x1F'\xE0\xD8x\x9C\x01\x14'\xEB\xD8x\x9C\x01\t'\xF6\xD8x\x9C\x15\xD0S@%\x8A\x02@\xD1\\\x93m\xE3d\xDB\xB6m\xDB\xB6\xED\x9Al\xDB\x93m\xDB\xB6m\xFB\xBD\xFB\xB5\xBE\xF7\xF6\xC8\x06~\x05@\xAD{d\x03_\x01P\xFEc\x1F\x80\xFF\x1F+\x00\xCA\xFF\x98\x04\xB0\xFCG\x1F\x80\xFF?\x9A\x01R\xFFQ\tP\xFD\x8F<\x80\xC1\x7F$\x03\xAC\xFF#\x12\xE0\xF6\x1F~\x80\xC0\xFFp\x06\xC4\xFC\x87\x05 \xED?t\x01\x85\xFF\xA1\x04\xA8\xF9?h+\xC6\xC2dQ \x02\xF36r\xE96\x9B-\xB6\x9B+&\x9B-\xD7I\xB6\x9B\xE91I\x9C\xEB\xB5\xAF7e\xCF(//S\xE0h\x85g\xBBwS\xE0\xA6e\xE9\x1F\b\xD8Q)\xBF\x84\xC5k\x9F\b.Q\xD1\xBF\x01%\x1E?\xF1\xF6Ns\xD3\xBF\x8F\x02qw\x04\xE6G\xBD\xBF\xA0\x12r\x0F\x04\xFE\xE3\xE7\xBF\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ate(data) end # request input puts "Please input two numbers, each on its own line, to add." # run data code eval(data) ``` And where did I get that enormous string, you ask? This is the program I used to generate it: ``` require 'zlib' code = 'a,b=gets.to_i,gets.to_i;p a+b' oldcode = nil count = -1 until code.inspect.length > 29000; oldcode = code; code = Zlib::deflate code; count += 1; end File.open(ARGV.shift, 'w') do |f| f.puts oldcode.inspect; end puts count ``` Yay for "compression"! :P As you can see, I set the string's length limit to 29000, which is just under the length limit for Stack Exchange posts, but I could make that as high as I wanted to. [Answer] # C (via perl) - 170,141,183,381,241,069,554,076,045,499,751,727,125 (that's 1.70141183381241e+38) for 32-bit unsigned inputs My philosophy is that, when implementing addition from scratch, it is not wise to rely on precomputed costants like 2, 3, 7 or 65535! 0 and 1 should be the only constants we need, right? Therefore, I don't precompute any constants - I calculate them on the fly, as seen below! To support 8-bit signed integer input, you'll need source code of length 20,461,843 non-whitespace characters. To implement 32-bit signed integer input, you'll need source code of length 1.70141183381241e+38 ;-) Ready for a small snippet of the 8-bit signed integer code? Here you are: ``` int add(int i, int j) { if (i == -1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1) { if (j == -1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-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1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1; } } ``` Note that this code is golfed somewhat - I don't say eg: ``` if(x==1 and y==1) ... if(x==1 and y==1+1) ... if(x==1 and y==1+1+1) ... ``` No need to check if x is equal to one a each time, right? So my code is far more efficient† and concise†, and does this instead: ``` if(x==1) { if(y==1) ... if(y==1+1) ... if(y==1+1+1) ... } ``` I could certainly extend the code-length further by changing to the less concise method =) And here's the source code I used to generate these monstrosities, but be careful - representing a 24-bit integer in this format (33MB each) results in perl eating over 1GB of memory on my machine. If you have more than 512GB of memory at your disposal, you should be able to go ahead and try it with 32-bit integers =) ``` #!/usr/bin/perl use strict; use warnings; my ($MININT, $MAXINT); my $abbrev; if($ARGV[0] =~ /-a(?:=(\d+))?/) { $abbrev = defined $1 ? $1 : 3; shift @ARGV; } if($ARGV[0] =~ /^(\d+)([su]?)$/ && !defined $ARGV[1]) { my $unsigned = $2 && $2 eq "u"; #default to signed my $bits = $1; my $range = 2**$bits; $MININT = $unsigned ? 0 : 2**($bits-1)-$range; $MAXINT = $unsigned ? $range - 1 : 2**($bits-1)-1; } else { $MININT = shift @ARGV; $MAXINT = shift @ARGV; } sub componentize { my $x = shift; return $x < 0 ? "-1" x abs($x) : $x > 0 ? "1".("+1"x abs($x-1)) : 0; } my @range = $abbrev ? ($MININT..($MININT+$abbrev), "x", ($MAXINT-$abbrev)..$MAXINT) : ($MININT..$MAXINT); my $indent=" "; print "int add(int i, int j) {\n"; for my $i (@range) { if($i eq "x") { print "$indent...\n"; next }; print "${indent}if (i == ".componentize($i).") {\n"; for my $j (@range) { if($j eq "x") { print "$indent$indent...\n"; next }; print "${indent}${indent}if (j == ".componentize($j).") return ".componentize($i+$j).";\n"; } print "$indent}\n"; } print "}\n"; ``` Whew, that's it =) [Answer] ## PHP - 1299 The rules don't prohibit using external libraries so here is the code using [SimplePHPEasyPlus](https://github.com/Herzult/SimplePHPEasyPlus): ``` use SimplePHPEasyPlus\Number\NumberCollection; use SimplePHPEasyPlus\Number\SimpleNumber; use SimplePHPEasyPlus\Number\CollectionItemNumberProxy; use SimplePHPEasyPlus\Parser\SimpleNumberStringParser; use SimplePHPEasyPlus\Iterator\CallbackIterator; use SimplePHPEasyPlus\Operator\AdditionOperator; use SimplePHPEasyPlus\Operation\ArithmeticOperation; use SimplePHPEasyPlus\Operation\OperationStream; use SimplePHPEasyPlus\Engine; use SimplePHPEasyPlus\Calcul\Calcul; use SimplePHPEasyPlus\Calcul\CalculRunner; $numberCollection = new NumberCollection(); $numberParser = new SimpleNumberStringParser(); $firstParsedNumber = $numberParser->parse('1'); $firstNumber = new SimpleNumber($firstParsedNumber); $firstNumberProxy = new CollectionItemNumberProxy($firstNumber); $numberCollection->add($firstNumberProxy); $secondParsedNumber = $numberParser->parse('1'); $secondNumber = new SimpleNumber($secondParsedNumber); $secondNumberProxy = new CollectionItemNumberProxy($secondNumber); $numberCollection->add($secondNumberProxy); $addition = new AdditionOperator('SimplePHPEasyPlus\Number\SimpleNumber'); $operation = new ArithmeticOperation($addition); $engine = new Engine($operation); $calcul = new Calcul($engine, $numberCollection); $runner = new CalculRunner(); $runner->run($calcul); $result = $calcul->getResult(); $numericResult = $result->getValue(); // 2 ``` [Answer] # C++ MORE THAN 3x10^+618 (WITHOUT WHITE-SPACES,tabs or newlines) This code took more maths than logic! in counting number of bytes **SHORT CODE** ``` #include<iostream> #include<conio.h> long double sumofxandy(long double,long double); int main() { long double x,y; cin>>x>>y; sumofxandy(x,y); getch(); return 0; } long double sumofxandy(long double x,long double y) { ... ... ... if(x==0)if(y==-1)return -1; if(x==0)if(y==0)return 0; if(x==0)if(y==1)return 1; ... ... ... ... if(x==1)if(y==0)return 1; if(x==1)if(y==1)return 2; ...so....on. } ``` ### OUTPUT Really ? seriously! you want to see output? this code would take weeks to write and months to compile! [Answer] # Java - 2406 (3220 with whitespace) We all know that computers are good at handling bits and not so good at everything else. Therefore my program perform the addition using efficient bitwise addition! ``` /** * Solution for PCG22921. * * The program adds two natural numbers using efficient bit addition. */ public class PCG22921 { /** * Contains the program. * * @param args Exactly two integer numbers. */ public static void main(String[] args) { // check whether sane arguments were given if (args.length != 2) { throw new IllegalArgumentException("You must provide exactly two numbers"); } // transform the arguments into integer int number1 = Integer.parseInt(args[0]); int number2 = Integer.parseInt(args[1]); // convert number1 into bits String bits1 = ""; while (number1 > 0) { bits1 = (number1 % 2) + bits1; number1 = number1 / 2; } // convert number2 into bits String bits2 = ""; while (number2 > 0) { bits2 = (number2 % 2) + bits2; number2 = number2 / 2; } // ensure both numbers have the same length while (bits1.length() < bits2.length()) { bits1 = "0" + bits1; } while (bits2.length() < bits1.length()) { bits2 = "0" + bits2; } // stores whether the last addition overflowed boolean overflow = false; // bits of the result String resultBits = ""; // keep adding until the bits are empty while (bits1.length() > 0) { // grab the last bit of each number char lastBit1 = bits1.charAt(bits1.length() - 1); char lastBit2 = bits2.charAt(bits2.length() - 1); // Quick lookup table to speed up addition! if (lastBit1 == '1' && lastBit2 == '1' && overflow) { resultBits = "1" + resultBits; overflow = true; } else if (lastBit1 == '1' && lastBit2 == '1' && !overflow) { resultBits = "0" + resultBits; overflow = true; } else if (lastBit1 == '1' && lastBit2 == '0' && overflow) { resultBits = "0" + resultBits; overflow = true; } else if (lastBit1 == '0' && lastBit2 == '1' && overflow) { resultBits = "0" + resultBits; overflow = true; } else if (lastBit1 == '1' && lastBit2 == '0' && !overflow) { resultBits = "1" + resultBits; overflow = false; } else if (lastBit1 == '0' && lastBit2 == '1' && !overflow) { resultBits = "1" + resultBits; overflow = false; } else if (lastBit1 == '0' && lastBit2 == '0' && overflow) { resultBits = "1" + resultBits; overflow = false; } else if (lastBit1 == '0' && lastBit2 == '0' && !overflow) { resultBits = "0" + resultBits; overflow = false; } // error handling is importent else throw new RuntimeException("This should not happen"); // remove the processed bits bits1 = bits1.substring(0, bits1.length() - 1); bits2 = bits2.substring(0, bits2.length() - 1); } // check whether there is overflow left if (overflow) resultBits = "1" + resultBits; // Convert the bits into a result number again int result = 0; int bitValue = 1; while (resultBits.length() > 0) { char lastResultBit = resultBits.charAt(resultBits.length() - 1); if (lastResultBit == '1') { result = result + bitValue; } resultBits = resultBits.substring(0, resultBits.length() - 1); // each bit is twice as worthy as the last one bitValue = bitValue * 2; } // show the result System.out.println(result); } } ``` [Answer] ## Java - ~~309~~ ~~731~~ 759 Not the longest, but could be the most plausible wrong interpretation. edit: Oops, just noticed this is not [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'"). > > Adding numbers larger than one bit is done by adding individual bits > using a [full-adder](http://en.wikipedia.org/wiki/Adder_%28electronics%29#Full_adder), which takes as input two bits and a carry-in > from the previous stage, and outputs the sum bit and a carry-our bit. > For simple addition, the carry-in for the first stage should be zero. > > > ``` public class Adder { public static void main(String[] args) throws Exception { int a = 135; int b = 87; int result = 0; int carryIn = 0; // Assume 8 bits, so we have 8 full-adders: for (int i = 0; i < 8; i++) { // Assume numbers are 8 bits long // Get the Nth bits from the numbers int bitA = a >> i & 1; int bitB = b >> i & 1; // Full adder, using the truth table: int bitC = 0; int carryOut = 0; if (bitA == 0 && bitB == 0 && carryIn == 0) { bitC = 0; carryOut = 0; } else if (bitA == 0 && bitB == 0 && carryIn == 1) { bitC = 1; carryOut = 0; } else if (bitA == 0 && bitB == 1 && carryIn == 0) { bitC = 1; carryOut = 0; } else if (bitA == 0 && bitB == 1 && carryIn == 1) { bitC = 0; carryOut = 1; } else if (bitA == 1 && bitB == 0 && carryIn == 0) { bitC = 1; carryOut = 0; } else if (bitA == 1 && bitB == 0 && carryIn == 1) { bitC = 0; carryOut = 1; } else if (bitA == 1 && bitB == 1 && carryIn == 0) { bitC = 0; carryOut = 1; } else if (bitA == 1 && bitB == 1 && carryIn == 1) { bitC = 1; carryOut = 1; } // Append the bits to the result result |= bitC << i; // Carry for next stage carryIn = carryOut; } // Verify the result System.out.println("Result = " + result + ", CarryOut = " + carryIn); System.out.println("Should be: " + (a + b)); } } ``` > > Result = 222, Carry-out = 0 > > Should be: 222 > > > [Answer] Python 2.7 (adding the good way) ``` def add(x,y): while True: a = x & y b = x ^ y x = a << b & 0xffffffff y = b if a == 0: break return b number_1 = int(raw_input("Please enter a number(1)")) number_2 = int(raw_input("Please enter a number(2)")) print "result is: %d" % add(number_1, number_2) ``` credit goes to <https://stackoverflow.com/questions/366706/bitwise-subtraction-in-python> [Answer] ``` function add(a, b) { while (b) { a ^= b; b &= a ^ b; b <<= 1; } return a; } ``` [Answer] # C# - 5395 Lets emit [cil](/questions/tagged/cil "show questions tagged 'cil'") code for addition using a dynamic method. Actually I emit code, which in turns emits code to call integer addition. The function `Add()` below builds a dynamic method, which when run builds a dynamic method to call integer addition. ``` using System; using System.Reflection.Emit; namespace JA { class Program { static void Main(string[] args) { int z=Add(1, 2); // z = 3 } // Emit MSIL to emit MSIL public static int Add(int x, int y) { Type delegate_type=typeof(Func<int, int, int>); DynamicMethod method=new DynamicMethod(typeof(int).ToString()+".op_Addition", typeof(int), new Type[] { typeof(int), typeof(int) }, typeof(Program)); ILGenerator generator=method.GetILGenerator(); LocalBuilder method1=generator.DeclareLocal(typeof(DynamicMethod)); LocalBuilder generator1=generator.DeclareLocal(typeof(ILGenerator)); LocalBuilder add1=generator.DeclareLocal(typeof(Func<int, int, int>)); LocalBuilder args1=generator.DeclareLocal(typeof(Type[])); generator.Emit(OpCodes.Ldtoken, typeof(int)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(object).GetMethod("ToString", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Instance)); generator.Emit(OpCodes.Ldstr, ".op_Addition"); generator.Emit(OpCodes.Call, typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) })); generator.Emit(OpCodes.Ldtoken, typeof(int)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Ldc_I4, 2); generator.Emit(OpCodes.Newarr, typeof(Type)); generator.Emit(OpCodes.Stloc_3); generator.Emit(OpCodes.Ldloc_3); generator.Emit(OpCodes.Ldc_I4, 0); generator.Emit(OpCodes.Ldtoken, typeof(int)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Stelem_Ref); generator.Emit(OpCodes.Ldloc_3); generator.Emit(OpCodes.Ldc_I4, 1); generator.Emit(OpCodes.Ldtoken, typeof(int)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Stelem_Ref); generator.Emit(OpCodes.Ldloc_3); generator.Emit(OpCodes.Ldtoken, typeof(Program)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Newobj, typeof(DynamicMethod).GetConstructor( new Type[] { typeof(string), typeof(Type), typeof(Type[]), typeof(Type) })); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Callvirt, typeof(DynamicMethod).GetMethod("GetILGenerator", Type.EmptyTypes)); generator.Emit(OpCodes.Stloc_1); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldtoken, typeof(int)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("DeclareLocal", new Type[] { typeof(Type) })); generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Ldarg_0", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Ldarg_1", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Add", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Stloc_0", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Ldloc_0", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldsfld, typeof(OpCodes).GetField("Ret", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(ILGenerator).GetMethod("Emit", new Type[] { typeof(OpCode) })); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldtoken, typeof(Func<int, int, int>)); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static)); generator.Emit(OpCodes.Callvirt, typeof(DynamicMethod).GetMethod("CreateDelegate", new Type[] { typeof(Type) })); generator.Emit(OpCodes.Isinst, typeof(Func<int, int, int>)); generator.Emit(OpCodes.Stloc_2); generator.Emit(OpCodes.Ldloc_2); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Callvirt, typeof(Func<int, int, int>).GetMethod("Invoke", System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance)); generator.Emit(OpCodes.Ret); Func<int, int, int> add2=method.CreateDelegate(typeof(Func<int, int, int>)) as Func<int, int, int>; return add2(x, y); } } } ``` [Answer] Say you want the code to be longer than n characters. The following code is far longer. ``` public class Add { int main(int a, int b) { return (a + (b/2^1) + (b/2^2) + (b/2^3) ... (b/2^n) + (b/2^n)); } } ``` [Answer] # C ``` #include<stdio.h> int Max(int a,int b) { if(a>b) return a; else return b; } int Min(int a,int b) { if(a<b) return a; else return b; } int main(void) { int a,b,sum,i,m; i=0; m = Min(a,b); scanf("%d", &a); scanf("%d", &b); if(Min(a,b) == Max(a,b)) { sum = 2*a; printf("%d", sum ); } else { do { i++; m++; }while(m < Max(a,b)); sum = i + 2 * Min(a,b); printf("%d", sum); } return 0; } ``` Doesn't work well for large numbers, but can be replaced by this ``` #include<stdio.h> int Max(int a,int b) { if(a>b) return a; else return b; } int Min(int a,int b) { if(a<b) return a; else return b; } int main(void) { int a,b,sum,i,m; i=0; scanf("%d", &a); scanf("%d", &b); if(Min(a,b) == Max(a,b)) { sum = 2*a; printf("%d", sum ); } else { i = Max(a,b) - Min(a,b); sum = i + 2 * Min(a,b); printf("%d", sum); } return 0; } ``` ]
[Question] [ The task is simple: consolidate an array of ints. Consolidating this array consists of the following: * All instances of 0 need to be moved to the end of the array. * There should be no 0s between the non-zero integers. * All non-zero indices should retain their order. # Challenge Consolidate an array in the least amount of bytes. You are consolidating an array of random length with a size up to your language's max with random integers. Input may be any natural way for your language. # Examples Input ``` 0 5 8 8 3 5 1 6 8 4 0 3 7 5 6 4 4 7 5 6 7 4 4 9 1 0 5 7 9 3 0 2 2 4 3 0 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 0 5 0 6 0 3 ``` Output ``` 5 8 8 3 5 1 6 8 4 3 7 5 6 4 4 7 5 6 7 4 4 9 1 5 7 9 3 2 2 4 3 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 5 6 3 0 0 0 0 0 0 0 0 ``` Input ``` -1 -7 -6 5 1 -5 -2 7 -3 -8 0 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 0 -5 -7 3 8 1 1 3 -3 -2 -2 0 -7 0 -4 8 6 -3 6 0 5 3 2 2 2 -2 -7 -3 9 -1 6 0 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 0 3 3 7 -1 -5 1 -3 4 -7 0 3 2 -2 7 -3 0 0 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7 ``` Output ``` -1 -7 -6 5 1 -5 -2 7 -3 -8 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 -5 -7 3 8 1 1 3 -3 -2 -2 -7 -4 8 6 -3 6 5 3 2 2 2 -2 -7 -3 9 -1 6 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 3 3 7 -1 -5 1 -3 4 -7 3 2 -2 7 -3 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7 0 0 0 0 0 0 0 0 0 0 ``` # Example Code (Java) ``` public class Consolidate { public static void main(String[] args) throws Exception { int[] toConsolidate = new int[args.length]; for (int i=0; i<args.length; i++){ toConsolidate[i]=Integer.parseInt(args[i]); } for (int i=0; i<toConsolidate.length; i++) { for (int k=0; k<toConsolidate.length-1; k++) { if (toConsolidate[k] == 0){ toConsolidate[k] = toConsolidate[k+1]; toConsolidate[k+1] = 0; } } } for (int i:toConsolidate) System.out.print(i+" "); } } ``` [Answer] ## Pyth, 3 bytes ``` !DQ ``` Explanation: ``` Q Input !D Sort by logical NOT ``` Try it [here](http://pyth.herokuapp.com/?code=%21DQ&input=%5B0%2C+5%2C+8%2C+8%2C+3%2C+5%2C+1%2C+6%2C+8%2C+4%2C+0%2C+3%2C+7%2C+5%2C+6%2C+4%2C+4%2C+7%2C+5%2C+6%2C+7%2C+4%2C+4%2C+9%2C+1%2C+0%2C+5%2C+7%2C+9%2C+3%2C+0%2C+2%2C+2%2C+4%2C+3%2C+0%2C+4%2C+8%2C+7%2C+3%2C+1%2C+4%2C+7%2C+5%2C+1%2C+2%2C+1%2C+8%2C+7%2C+8%2C+7%2C+7%2C+2%2C+6%2C+3%2C+1%2C+2%2C+8%2C+5%2C+1%2C+4%2C+2%2C+0%2C+5%2C+0%2C+6%2C+0%2C+3%5D&debug=0). [Answer] # Jelly, 3 bytes ``` ¬Ụị ``` Sorts the list by the logical NOT of its values. [Try it online!](http://jelly.tryitonline.net/#code=wqzhu6Thu4s&input=&args=WzAsIDUsIDgsIDgsIDMsIDUsIDEsIDYsIDgsIDQsIDAsIDMsIDcsIDUsIDYsIDQsIDQsIDcsIDUsIDYsIDcsIDQsIDQsIDksIDEsIDAsIDUsIDcsIDksIDMsIDAsIDIsIDIsIDQsIDMsIDAsIDQsIDgsIDcsIDMsIDEsIDQsIDcsIDUsIDEsIDIsIDEsIDgsIDcsIDgsIDcsIDcsIDIsIDYsIDMsIDEsIDIsIDgsIDUsIDEsIDQsIDIsIDAsIDUsIDAsIDYsIDAsIDNd) ### How it works ``` ¬Ụị Main link. Input: A (list) ¬ Compute the logical NOT of each element of A. Ụ Grade up; sort the resulting list's indices by their corresponding values. ị Retrieve the elements of A at that indices. ``` [Answer] # Octave, 18 bytes ``` @(A)[A(~~A) A(~A)] ``` `sort()` takes too many bytes. I'll just use logical indexing. Examples on [ideone](http://ideone.com/yXZ7cp). [Answer] # R, ~~29~~ ~~23~~ 21 bytes As noted by MarcoBreitig, we can shorten it to 21 bytes if we don't need to provide it as a function: ``` x=scan();x[order(!x)] ``` --- Previous versions: ``` function(x)x[order(!x)] ``` The function takes a vector as input and orders by the logical vector that results from negating the input. Original answer: ``` function(x)c(x[x!=0],x[x==0]) ``` The function takes a vector as input and the concatenates (`c()`) the non-zero values and then the zero-values. [Answer] # [Retina](http://github.com/mbuettner/retina), 15 Simple repeated regex substitution: ``` +`\b0 (.*) $1 0 ``` [Try it online.](http://retina.tryitonline.net/#code=K2BcYjAgKC4qKQokMSAw&input=MCA1IDggOCAzIDUgMSA2IDggNCAwIDMgNyA1IDYgNCA0IDcgNSA2IDcgNCA0IDkgMSAwIDUgNyA5IDMgMCAyIDIgNCAzIDAgNCA4IDcgMyAxIDQgNyA1IDEgMiAxIDggNyA4IDcgNyAyIDYgMyAxIDIgOCA1IDEgNCAyIDAgNSAwIDYgMCAz) [Answer] ## Python, 32 bytes ``` lambda x:sorted(x,key=0..__eq__) ``` Takes argument as any iterable (list, tuple, etc.). Thanks to @xnor for teaching me a new trick! [Answer] ## ES6, 23 bytes ``` a=>a.sort((x,y)=>!x-!y) ``` It used to be the case that `sort` wasn't stable, in which case you needed 41 bytes: ``` a=>a.filter(x=>x).concat(a.filter(x=>!x)) ``` [Answer] # Python byte code (2.7.9), 252 bytes, 33 opcodes, 0.0228 seconds This was build when the contest was still a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") contest Opens a file in the current directory called `'SourceArray'` for use ``` LOAD_CONST '' STORE_FAST no_zeroes# no_zeroes = '' LOAD_NAME open LOAD_CONST 'SourceArray' CALL_FUNCTION 0,1# open('SourceArray') LOAD_ATTR read CALL_FUNCTION 0,0# .read() LOAD_ATTR split CALL_FUNCTION 0,0# .split() DUP_TOP DUP_TOP #Start if BUILD_LIST 0 COMPARE_OP == POP_JUMP_IF_TRUE 35# if list == [], GOTO 35 LOAD_ATTR pop LOAD_CONST 0 CALL_FUNCTION 0,1# list.pop(0) DUP_TOP LOAD_CONST '0' COMPARE_OP == POP_JUMP_IF_TRUE 28# if list.pop(0) == '0', GOTO 28 PRINT_ITEM # print list.pop(0) JUMP_ABSOLUTE 13 POP_TOP LOAD_CONST '0%_'# '0 ' LOAD_FAST no_zeroes INPLACE_ADD STORE_FAST no_zeroes# no_zeroes = no_zeroes + '0 ' JUMP_ABSOLUTE 13 LOAD_FAST no_zeroes PRINT_ITEM # print no_zeroes LOAD_CONST None RETURN_VALUE ``` The `co_code` (The actual codey bit) ``` 'd\x01\x00}\x00\x00\te\x00\x00\x83\x00\x00\tj\x01\x00\x83\x00\x00\t\x04\x04g\x00\x00k\x02\x00sG\x00j\x02\x00d\x02\x00\x83\x01\x00\x04d\x03\x00k\x02\x00s8\x00Gq\x15\x00\t\x01d\x04\x00|\x00\x007}\x00\x00q\x15\x00\t|\x00\x00G\td\x00\x00S' ``` Or a .pyc file version `03F3` ``` 03 F3 0D 0A 40 FD B0 56 63 00 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 73 59 00 00 00 64 01 00 7D 00 00 09 65 00 00 64 02 00 83 01 00 6A 01 00 83 00 00 09 6A 02 00 83 00 00 09 04 04 67 00 00 6B 02 00 73 50 00 6A 03 00 64 03 00 83 01 00 04 64 04 00 6B 02 00 73 41 00 47 71 1E 00 09 01 64 05 00 7C 00 00 37 7D 00 00 71 1E 00 09 7C 00 00 47 09 64 00 00 53 28 06 00 00 00 4E 74 00 00 00 00 74 0B 00 00 00 53 6F 75 72 63 65 41 72 72 61 79 69 00 00 00 00 74 01 00 00 00 30 73 02 00 00 00 30 20 28 04 00 00 00 74 04 00 00 00 6F 70 65 6E 74 04 00 00 00 72 65 61 64 74 05 00 00 00 73 70 6C 69 74 74 03 00 00 00 70 6F 70 28 01 00 00 00 74 09 00 00 00 6E 6F 5F 7A 65 72 6F 65 73 28 00 00 00 00 28 00 00 00 00 74 09 00 00 00 70 79 6B 65 5F 63 6F 64 65 52 08 00 00 00 01 00 00 00 52 00 00 00 00 ``` You can try to compile my source code yourself using [my library on github.](https://github.com/muddyfish/Python-PYKE) I just posted a commit to it that allowed comments so I hope this is still competing as far as [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") goes ;) Roughly equivalent to ``` no_zeroes = '' unamed_variable = open('SourceArray').read().split() while unamed_variable != []: unamed_variable_2 = unamed_variable.pop() if unamed_variable_2 == '0': no_zeroes += '0 ' else: print unamed_variable_2, print no_zeroes, ``` [Answer] # Matlab: 21 bytes ``` @(a)[a(a~=0),a(a==0)] ``` Prints nonzero elements first, then concatenates with zero elements `@(a)____` create an anonymous function with one input argument `a` `[___,___]` concatenates horizontally vectors inside brackets, separated by commas `a(a~=0)` returns vector with all nonzero elements of vector `a` `a(a==0)` returns vector with all zero elements of vector `a` [Answer] # APL: 8 bytes ``` (⍴a)↑a~0 ``` a~0 remove zeros from a (read "a without 0") (⍴a) original length of a (read "shape of a") ↑ pad a without zeros to a's original length Try it in <http://ngn.github.com/apl/web/index.html> Test data: a←1 0 1 2 3 4 0 1 0 0 0 0 1 2 3 4 5 [Answer] # Zsh, 22 bytes (input passed as arguments to the script/function (`$@` aka `$argv` array), output on stdout as space separated list, newline terminated) ``` <<<${@:#0}\ ${(M)@:#0} ``` * `<<< string`: here-string here passed as stdin to the `$NULLCMD` command (`cat` by default). * `${@:#0}` `$@` except elements being 0. * `${(M)@:#0}` reverse of the above That assumes (like several other answers here) that zeroes in the input are all expressed as `0` (no `00` nor `0x0` nor `36#0`). [Answer] ## Haskell, 26 bytes ``` f x=filter(/=0)x++[0|0<-x] ``` Take all non-zero numbers followed by all zeros. Filtering constants (here: `0`) is quite short when using a list comprehension: `[0|0<-x]`. [Answer] # Mathematica, 14 bytes ``` Sort[#,#!=0&]& ``` [Answer] # Common Lisp, 46 bytes ``` (lambda(a)(stable-sort a(lambda(_ b)(= 0 b)))) ``` Sort the array so that for each couple *(a,b)*, we have *a < b* if *b* is zero. When neither *a < b* or *b < a*, the sort is stable: the original order between elements is retained. I also tried with *adjust-array* and *remove*, but this was too long: ``` (lambda(a)(adjust-array(remove 0 a)(length a):initial-element 0)) ``` [Answer] # Javascript, ~~52~~ ~~54~~ 51 bytes ``` s=>s.replace(/\b0 /g,x=>++i&&'',i=0)+' 0'.repeat(i) ``` [Answer] ## Java 7, 78 bytes ``` void g(int[]a){int c=0;for(int o:a)a[o==0?c:c++]=o;for(;c<a.length;a[c++]=0);} ``` I'm not sure why the other Java entries are using strings. If you want to filter an integer array, it seems best to use an integer array. This modifies the input in place by keeping two indices, then just filling the remaining slots with zeros. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~3~~ 2 bytes ``` µ¬ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B5%C2%AC&inputs=0%205%208%208%203%205%201%206%208%204%200%203%207%205%206%204%204%207%205%206%207%204%204%209%201%200%205%207%209%203%200%202%202%204%203%200%204%208%207%203%201%204%207%205%201%202%201%208%207%208%207%207%202%206%203%201%202%208%205%201%204%202%200%205%200%206%200%203&header=%3F%C3%B0%2FvI&footer=) Sort by logical negation. The header puts the input into a list format. [Answer] # PHP, ~~73~~ ~~71~~ ~~70~~ ~~52~~ ~~49~~ ~~48~~ 46 bytes - BIG thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732) ``` // Assuming $a = array(4,8,6,1,0,8,0,0,0,0,0,-4,'-5',-1,564,0); // Produces a notice-level error foreach($a as$v)$v?print"$v ":$b.="0 ";echo$b; ``` [Answer] # Bash + GNU utilities, 23 ``` grep -v ^0 a grep ^0 a ``` Assumes input is newline-separated entries in a file called `a`. Score includes +1 for this filename. [Answer] # Perl 5, 26 bytes 23 plus three for `-an` (`-E` is free) ``` say for sort{!$a-!$b}@F ``` Thanks to [Dennis](/u/12012) for reminding me of `-a`, saving two bytes. [Answer] # JavaScript ES6, 16 bytes ``` x=>x.sort(t=>!t) ``` Works on firefox [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 34 bytes ``` {for(;a++-NF;c?$++b=c:0)$a-=c=$a}1 ``` [Try it online!](https://tio.run/##NY@xDsIwDER/xUMHUGTJTVLiUlVsjPxDqMTCgMTCgPj24HNAqdqec34@19e9tfft8dwtNQS@nJftNIRwXbej7IfK67YO9TO2xiNxIT7QRPY3EUcymYiVhJRmVJXMdSDOEJG8Y6KMLvfOZkzwiBOKCTXXiGJChz2CuoChQCV7iUESRT8w/Vg@S2AqpjKu1DPkniVbE0YgsNgXij37CEDug1KHOlPsRBj0n6dA9T3nvo324b5RNEj5Ag "AWK – Try It Online") This code runs through all the commandline arguments, shifts non-zero values to the left and clears arguments as it processes them. The top of loop "should we iteration" condition expression is: ``` a++-NF ``` which increments `a` until it hits the number of commandline arguments `NF`. The body of the loop, ``` $a-=c=$a ``` saves the value of the current commandline argument in variable `c`, then sets the current argument to 0. At the end of each iteration, the ternery: ``` c?$++b=c:0 ``` checks to see if the current argument `c` is non-zero and if so, increments the `b` (the number of non-zero argument found so far) and stores the current argument value in that slot. After the code block processes the commandline arguments, the only left to do is trigger AWK to print all the commandline arguments with a `truthy` test without a code block. ``` 1 ``` [Answer] # [Uiua](https://uiua.org), 5 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==) ``` ⊏⍏=0. ``` [Try it!](https://uiua.org/pad?src=ZiDihpAg4oqP4o2PPTAuCgpmIFsxIDAgMiAwIMKvNSAwIDMgNCA1IDAgMCA2XQ==) ``` ⊏⍏=0. . # duplicate =0 # where is it equal to zero? ⍏ # rise (grade up) ⊏ # select ``` [Answer] # CJam, 6 bytes ``` {{!}$} ``` An anonymous function. Sort using “whether or not an element is zero” as a key. [Answer] # Clojure/ClojureScript, 18 bytes ``` #(sort-by zero? %) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 7 bytes ``` t~FT#S) ``` [**Try it online!**](http://matl.tryitonline.net/#code=dH5GVCNTKQ&input=WzAgNSA4IDggMyA1IDEgNiA4IDQgMCAzIDcgNSA2IDQgNCA3IDUgNiA3IDQgNCA5IDEgMCA1IDcgOSAzIDAgMiAyIDQgMyAwIDQgOCA3IDMgMSA0IDcgNSAxIDIgMSA4IDcgOCA3IDcgMiA2IDMgMSAyIDggNSAxIDQgMiAwIDUgMCA2IDAgM10) ``` t % input array. Duplicate ~ % logical negate: nonzero values become false, zeros become true FT#S % sort (false, then true) and output a vector with the indices of the sorting ) % apply that vector of indices to original array ``` [Answer] ## Seriously, 12 bytes ``` 4,n`Y`M@░)░+ ``` [Try it online!](http://seriously.tryitonline.net/#code=NCxuYFlgTUDilpEp4paRKw&input=WzEsMiwwLDMsMV0) Explanation: ``` 4,n`Y`M@░)░+ 4,n push 4 copies of input `Y`M map logical negate @░) filter (take zeroes) and push to bottom of stack ░ filter (take non-zeroes) + append zeroes ``` [Answer] # [Swift](https://swift.org/), 13 bytes ``` a.sort{$1==0} ``` [Answer] # Perl6, 11 bytes ``` {.sort(!*)} ``` Produces a Block - which can be called on an array: ``` {.sort(!*)}.([1,2,0,3]).say ``` Although it would be more natural (and shorter) to write: ``` [1,2,0,3].sort(!*).say ``` How it works: if the [perl6 sort routine](http://doc.perl6.org/routine/sort) is called with a block which accepts only one argument, the list elements are sorted according to `by($a) cmp by($b)`. In this case, the block is `!*`, i.e. a negation of the [whatever operator](http://doc.perl6.org/routine/*#language_documentation_Terms). I notice that: * The example in the question is a class which provides a method, not including boilerplate required to read in * The description of the task does not require printing, and, except for the fact that the example prints, implies that an array might be returned [Answer] ## TeX (Plain format), 160 bytes Make the `0` character active (that is, make the interpreter process it as a command), then define that command to skip the character and increment a counter. At the end of the string, print as many zeros as were counted. Save this as `zero.tex` and give the input through the command line with this command: ``` pdftex "\def\I{0 1 0 3 2 0 0 8 0 5 0 1 9 4}\input zero" ``` ``` \def\I{}\newcount\Z\def\L{\loop\advance\Z by-1\ifnum\Z>00 \repeat} \begingroup\catcode`\013 \def0{\advance\Z by1} \scantokens\expandafter{\I\empty}\endgroup\L\bye ``` (Newlines added for clarity) [![enter image description here](https://i.stack.imgur.com/FlHOU.png)](https://i.stack.imgur.com/FlHOU.png) ]