text
stringlengths
180
608k
[Question] [ Coders are always trying to flatten arrays into boring 1-dimensional entities and it makes me sad. Your task is to unflatten an arbitrary string of characters, outputting a lovely city skyscape. Consider the string: `aaabbbbbccqrrssstttttttPPw` It looks much better like this: ``` tt tt bb tt bb tt aabb sstt aabbcc rrssttPP aabbccqqrrssttPPww ``` (Ok, yes, the letters are duplicated to make it look more city-skyline-ery). Take an input string, duplicate each subsection of matching characters (not necessarily alphabetic letters) and build me a city! Shortest code bytes win. I actually thought I had the requirements nailed, but to answer some questions: * it must be on the ground * you can have extra sky if you want (leading blank lines, surrounding blank space) - but not between the buildings * letters can be reused inside the string (same architecture, different location) * the letters are assumed to be ASCII, but more flair will be given to those supporting additional encodings (UTF8, etc) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` γ€DζR» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZHTWtczm0LOrT7///ExMQkEEhOLiwqKiouLi6BgICAcgA "05AB1E – Try It Online") In a version newer than the challenge, `ζ` has been added as a replacement fo `.Bø` # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` γ€D.BøR» ``` Explanation: ``` γ Convert into a list of consecutive equal elements €D Duplicate each element .B Squarify; pad each element with spaces so that they are the length of the longest element ø Transpose R Reverse (otherwise the city would be upside-down) » Join by newlines ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZHTWtc9JwO7wg6tPv//8TExCQQSE4uLCoqKi4uLoGAgIByAA "05AB1E – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` qe`::*:__:,:e>f{Se[}zN* ``` [Try it online!](https://tio.run/##S85KzP3/vzA1wcpKyyo@3krHKtUurTo4Nbq2yk/r///ExMQkEEhOLiwqKi4uLoGAgIByAA "CJam – Try It Online") Explanation: ``` qe`::*:__:,:e>f{Se[}zN* Accepts (multi-line?) input q Take all input e`::* Split into groups of equal elements :_ Duplicate each _:,:e> Push maximal length without popping f{Se[} Left-pad each to that length with space strings (NOT space chars, although not a problem here) z Zip N* Join with newlines ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Œgx'2z⁶ṚY ``` [Try it online!](https://tio.run/##y0rNyan8///opPQKdaOqR43bHu6cFfn////ExMQkEEhOLiwqKiouLi6BgICAcgA "Jelly – Try It Online") Explanation: ``` Œgx'2z⁶ṚY Main Link Œg Group runs of equal elements x Repeat ' the lists 2 twice without wrapping z⁶ Zip (transpose), filling in blanks with spaces Ṛ Reverse the whole thing so it's upside-down Y Join by newlines ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~155~~ ~~136~~ ~~134~~ 132 bytes *-19 bytes thanks to @LeakyNun* *-2 bytes thanks to @officialaimm* *-1 byte thanks to @Wondercricket* ``` s=input()+'+' k=' '*len(s) a=[] c=b='' while s: while c in b:b+=c;c,*s=s a+=b+k,b+k;b=c for r in[*zip(*a)][:0:-1]:print(*r,sep='') ``` [Try it online!](https://tio.run/##JYw7CsMwEAV7nUKdfg4kpJPZO7g3LqTFwcJGVnYVTHJ5xSEDD6Z4THnXZc/31hhSLq@qjVNOiRWUVHabs2YjAoyTQIiglDiWtM2SvZB/Q5myjD46wB47y8BCBgfRrd25PgKKx06SzttoP6loG8w0@qu/3CZfKOWqLXU8lzNuWgshxB@ITyJi5vpnGI4v "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 117 bytes ``` import re s=input() for l in zip(*[x+S*len(s)for x,_ in re.findall(r'((.)\2*)',s)for S in' '])[::-1]:print''.join(l) ``` [Try it online!](https://tio.run/##JcpBDoIwEEDRPafobqaITWRJ4h1IWCIxFSGOqdM6rRG9fJXwt@@HT7p5rnOmR/CSlExFPBKHV0JdzF6UU8TqSwHLftl1pZsYo15hqc4ryWRm4qt1DgUQjT7VpYZqe7r/AUrBoPum2R@GJghxAjB3T4xO5wzW2svaOD5FYoxpq23f8AM "Python 2 – Try It Online") [Answer] # Java 8, ~~412~~ ~~400~~ ~~330~~ ~~324~~ ~~312~~ 319 bytes -6 bytes thanks to VisualMelon -12 bytes thanks to Kevin Cruijssen but +19 bytes because I forgot to include the imports in the byte count. ``` import java.util.*;x->{Map m=new HashMap(),n;int l=x.length(),i=l,v,y,h=0,d=1;char c,k;for(;i-->0;m.put(c,d=m.get(c)!=null?d+1:1),h=d>h?d:h)c=x.charAt(i);for(y=h;y>0;y--){n=new HashMap(m);for(i=0;i<l;i++)if(n.get(k=x.charAt(i))!=null){v=(int)m.get(k);System.out.print((y>v?" ":k+""+k)+(i==l-1?"\n":""));n.remove(k);}}} ``` [Try it online!](https://tio.run/##VZDBcsIgEIbveQqaEzQJo1cpOr314owzHq0HJGgwhKSwiWYyefaUqId2L7DL7vcv/1V0IqsbZa95OemqqR2ga6jRFrSh7yySRniPtkLbIdIWlDsLqRAoD0PU1TpHDu/BaXtBd8KiMWrak9ESeRAQjkdHFYZfTYcjEu7iCRqiGYEA8emerYetaFDFrbqhL@GLkGGSWhb0kOF3apS9QBFKmpu0S/u04Is050smC@GQTEt2rh1mOsvWC1bRpgUsw3tFLyrcyBu3rTGbPFmuliTM5utik68KIgN6JnwC1uSB6HnB@sDos4wM9t8@1bND8wXTH4bpJCH6jO1DovwLesmRoeM4fIA8tygJ2/ceVEXrFmgTvACM@3W3iRGKV2USx0lJkoDnJltu4m8br@KYEGapU1XdqRkwjiObgDo8W3hYHB9@j9MkhDjNIeWPc957eMZud/sF) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~19~~ ~~18~~ ~~15~~ ~~13~~ ~~12~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Includes trailing spaces on each line. ``` ò¦ Õ®m²ÃÔ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=8qYg1a5tssPU&input=ImFhYWJiYmJiY2NxcnJyc3NzdHR0dHR0dFBQdyI) ``` ò¦ Õ®m²ÃÔ :Implicit input of string ò :Partition by ¦ : Inequality Õ :Transpose ® :Map m : Map ² : Duplicate à :End map Ô :Reverse :Implicit output joined with newlines ``` [Answer] # Mathematica, 150 bytes ``` (z=Characters[v=#];f=CharacterCounts[v][#]&/@(d=Union@z);Row[Column/@Map[PadLeft[#,Max@f,""]&,Table[Table[d[[i]]<>d[[i]],f[[i]]],{i,Length@d}],{1}]])& ``` [Answer] # [R](https://www.r-project.org/), 135 bytes ``` e=rle(sub('(.)','\\1\\1',strsplit(scan(,''),'')[[1]]));write(sapply(sum(e$l|1):1,function(x)ifelse(e$l>=x,e$v,' ')),'',sum(e$l|1),,'') ``` [Try it online!](https://tio.run/##RYw7CsMwEESv4sKwu7AE1CY4Z3Bvu5CFDAJFcbTyJ5C7KxIpMsxUw3sxZ9tFb1G2GQEvBAzjqEqBJUVZvUsoRgdkAKobBjVNRLcjulQwva7@XegH2tZ/FF0VL1swyT0DnuQW68XW696dbNudoWmAqoj/DFdv1lrPNca8YhSR9EvfH/kL "R – Try It Online") reads from stdin, writes to stdout (with a trailing newline). ### Explanation: * `rle` finds the lengths of the streaks of characters, the heights of each tower. * the `sub` expression replaces each character with its double (so I didn't have to muck about with setting adjacent indices together) * `sapply` returns an array (in this case a matrix): + `sum(e$l|1)` is the number of distinct characters; we go from top to bottom + `ifelse( ... )` is a vectorized `if...else` allowing us to build a matrix of towers and double spaces + `write` writes to console, with a few options to format. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` j_.tsC*2]*Mr8 ``` [Try it online!](http://pyth.herokuapp.com/?code=j_.tsC%2a2%5D%2aMr8&input=%22aaabbbbbccqrrssstttttttPPw%22&debug=0) [Answer] # [PHP](https://php.net/), 138 bytes ``` for(;~$s=&$argn;$s=substr($s,$r++%2*$i))for($i=0;$i<strspn($s,$c=$s[0]);$f[$i++][$r]=$c)a&$f[$i]?:$f[$i]=" ";krsort($f);echo join(" ",$f); ``` [Try it online!](https://tio.run/##JYpBDoIwFET3nII0I2kti8aln4aDkC6QiFQT2vyPW69eEVczee/lJZeuz0uuK4z8WL1yTlGZE2v6QHxzUNqfvG@ysYa0YGtPlzOiMb8O0TtC7HYreT2CyUMGFwxhHhCtDQM4eExmbA4S@ut/vaoVvVgSbxqzofu0pPqZ4qpVpdofKeUL "PHP – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` '(.)\1*'XXtvc!P ``` [**Try it online!**](https://tio.run/##y00syfn/X11DTzPGUEs9IqKkLFkxACiQmJiYBALJyYVFRcXFxSUQEBBQrg4A "MATL – Try It Online") ### Explanation ``` '(.)\1*' % Push string to be used as regexp pattern XX % Implicit input. Regexp matching. Pushes row cell array of matching substrings t % Duplicate v % Concatenate vertically c % Convert to char. This reads cells in column-major order (down, then across) % and produces a 2D char array, right-padding with spaces ! % Transpose P % Flip vertically. Implicitly display ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes: ``` A⟦⟦ω⟧⟧λFθ¿⁼ι§§λ±¹¦⁰⊞§λ±¹ι⊞λ⟦ι⟧FλF²↑⁺⪫ιω¶ ``` [Try it online!](https://tio.run/##dY2xDoIwFEVn@YqG6b2kJOooE4ODDobFCRlqKdCkKdJXxL@vRcLoXe5wb86RvXByECaEgkh3FqpqrmvODOZJOzgGIyY73TI4j5MwBJqzwl9soz6wteHspjrhFRwQOdsjIisn6v8ddCQqQ2o9xbHS9WYzyH59jAinrYfT/RWNTQPXQdvFPkdC@rApYh6CEOK5RMrROSLya8pyDtk7ZGS@ "Charcoal – Try It Online") Link is to verbose version of code. I originally tried a simple loop over the input string to print an oblong every time the letter changed, but I switched to this list-building method as it saved 5 bytes. Explanation: The variable `l` contains a nested list of the input letters. Characters that match the current last list elements get pushed onto the last list otherwise a new sublist is created for that character. It then remains to join the letters in each sublist so that they can be printed vertically twice. [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 15 + 1 = 16 bytes +1 byte for the `1` flag. ``` ⊖⍵ (.)\1* 2/⍪⍵M ``` [Try it online!](https://tio.run/##KyxNTCn@//9R17RHvVu5NPQ0Ywy1uIz0H/WuAvJ9//9PTExMAoHk5MKiouLi4hIICAgo/28IAA "QuadS – Try It Online") `⊖⍵` post-process by flipping upside down `(.)\1*` runs of identical characters `2/⍪⍵M` duplicate the columnified **M**atch The `1` flag causes the results to be merged together. [Answer] # [Ruby](https://www.ruby-lang.org/), 116 bytes ``` ->s{a=s.scan(/(.)(\1*)/).map{|x,y|[x,y.size+1]}.to_h m=a.values.max m.times{|i|puts a.map{|k,v|v+i<m ?' ':k*2}*''}} ``` [Try it online!](https://tio.run/##JYtLDoIwFAD3nKK78vMRXBqrV2CPxDwIxAaqyCsI0p69YpjFrGaGsVxcI9zhQisKAqrw6Sc@BP4tDYMkAIX9auZ4MfkmIPmto7SwoF/3h6cEwoTdWNOWzZ4CLVVNq5GmHzUx3Oc2nswUybNiV84YP7Xh0YacW@uanCNi@aeq3sNARHonyz68cD8 "Ruby – Try It Online") [Answer] # C, ~~259~~ 231 Bytes ## Golfed Code ``` #define v a[1][i i,k,l,x,h,w;main(char*s,char**a){for(;v];w+=2*!x,s=v++],h=x>h?x:h)x=(s==v])*(x+1);h++;s=malloc((x=h++*++w+1)+w);memset(s,32,h*w);for(i=k;v];s[x+1]=s[x]=k=v++],x=k==v]?x-w:(h-1)*w+l++*2+3)s[i*w]=10;printf("%s",s);} ``` ## Verbose Code ``` //Variable Explanations: //i - increment through argument string, must beinitialized to 0 //k - increment through argument string, must be initialized to 0 //l - record x coordinate in return value, must be initialized to 0 //x - record the actual character position within the return string //arrheight - the height of the return string //arrwidth - the width of the return string //arr - the return string //argv - the string containing the arguments #define v argv[1][i i,k,l,x,arrheight,arrwidth; main(char*arr,char**argv){ for(;v]; //For Length of input arrwidth+=2*!x, //increment width by 2 if this char is not the same as the last arr=v++], //set arr to current char arrheight=x>arrheight?x:arrheight //see if x is greater than the largest recorded height )x=(arr==v])*(x+1); //if this character is the same as the last, increment x (using arr to store previous char) arrheight++; //increment height by one since its 0 indexed arr=malloc((x=arrheight++*++arrwidth+1)+arrwidth); //create a flattened array widthxheight and set x to be the bottom left position memset(arr,32,arrheight*arrwidth); //fill array with spaces for(i=k;v]; //For Length of input arr[x+1]=arr[x]=k=v++], //set x and x+1 positions to the current character, store current character in i x=k==v]?x-arrwidth:(arrheight-1)*arrwidth+l++*2+3 //if next char is same as current move vertically, else set x to bottom of next column )arr[i*arrwidth]=10; //Add new lines to string at end of width printf("%s",arr); //output string } ``` Compiled with GCC, no special Flags ### Edit Saved 28 bytes thanks to adelphus. His change allowed me to create a define. And I made the while loops into for loops to save 2 bytes each by rearranging the loop. I also fixed an issue where the code would break when the last character in input wasn't singleton. The code will fail if there is only one unique letter but should work in all other cases. [Answer] # [Factor](https://factorcode.org/) + `grouping.extras sequences.repeating`, 94 bytes ``` [ [ ] group-by values dup longest length '[ _ 32 pad-head ] map 2 repeat flip [ print ] each ] ``` Modern Factor doesn't require a conversion to string before printing a sequence of code points, so have a screenshot of running the quotation in the listener: [![enter image description here](https://i.stack.imgur.com/tRPUy.png)](https://i.stack.imgur.com/tRPUy.png) Here's a TIO link with the extra `>string`: [Try it online!](https://tio.run/##RY07C8JAEIR7f8WQxsoUsVOwFRsJiFUQWS@bB553l92Lj18fT1I4xQwLO/M1ZKKX6Xw6HPcbtOLH0Ls253cUUpCqN4o7i2ML5WFkZ1jRyOd/5cKBKaYaNEoKRe@xXSwyIrr9ZMwgoqpxVlm@sqlChcsMXN0@eJId03A9BljvWtYIy66NHZYVrlgXCFSvOqY6tR4UUGDGorF9SFu7mY2QPKYfJtPhMhmydvoC "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a string as input and outputs to standard output. Assuming `"aaabbbbbccqrrssstttttttPPw"` is on the data stack when this quotation is called... * `[ ] group-by values` Split into groups of equal elements. **Stack:** `{ V{ 97 97 97 } V{ 98 98 98 98 98 } V{ 99 99 } V{ 113 } V{ 114 114 } V{ 115 115 115 } V{ 116 116 116 116 116 116 116 } V{ 80 80 } V{ 119 } }` * `dup longest length` Keep the 'city' on the stack but also find the length of the longest 'building.' **Stack:** `~city~ 7` * `'[ _ 32 pad-head ] map` Pad the city with whitespace to be a rectangular matrix. **Stack:** `{ V{ 32 32 32 32 97 97 97 } V{ 32 32 98 98 98 98 98 } V{ 32 32 32 32 32 99 99 } V{ 32 32 32 32 32 32 113 } V{ 32 32 32 32 32 114 114 } V{ 32 32 32 32 115 115 115 } V{ 116 116 116 116 116 116 116 } V{ 32 32 32 32 32 80 80 } V{ 32 32 32 32 32 32 119 } }` * `2 repeat` Repeat each row twice. * `flip` Transpose the matrix. * `[ print ] each` Print each row to standard output. [Answer] # [J](http://jsoftware.com/), 22 bytes ``` 2|.@|:@#[[;.1~1,2~:/\] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jWr0HGqsHJSjo631DOsMdYzqrPRjYv9rcnGlJmfkK6QpqCcmJiaBQHJyYVFRcXFxCQQEBJSr/wcA "J – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 22 bytes 21 bytes of code, +1 for `-l` flag. ``` Ya@`(.)\1*`RV:yWVyZDs ``` [Try it online!](https://tio.run/##K8gs@P8/MtEhQUNPM8ZQKyEozKoyPKwyyqX4////ujn/ExMTk0AgObmwqKi4uLgEAgICygE "Pip – Try It Online") ### Explanation ``` a is 1st cmdline arg; s is space (implicit) a@`(.)\1*` Using regex, create list of runs of same character in a Y Yank that into y variable yWVy Weave (interleave) y with itself to duplicate each item ZDs Zip to transpose, with a default character of space filling gaps RV: Reverse the resulting list (with the compute-and-assign meta-operator : being abused to lower the precedence) Auto-print, one sublist per line (implicit, -l flag) ``` [Answer] # Haskell, 144 bytes ``` f s=let x=groupBy(==)s;l=length;m=maximum(map l x)in concatMap(++"\n")$reverse$transpose$concat[[z,z]|z<-(map(\y->y++(replicate(m-(l y))' '))x)] ``` I'm pretty confident I can do better than this, but this is the best I can come up with for the time being. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 42 bytes ``` [rle toarr[...*chars]map FIX 2*tr rev out] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P7ooJ1WhJD@xqChaT09PKzkjsag4NjexQMHNM0LBSKukSKEotUwhv7Qk9r@DVRoXl3piYmISCCQnFxYVFRcXl0BAQEC5ukLafwA "Stacked – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 107 bytes ``` gets.gsub(/(.)(\1*)/,'\0 '*2).split(' ').map{|x|x.ljust($_.size).chars}.transpose.reverse.map{|x|puts x*""} ``` [Try it online!](https://tio.run/##LctNCsIwEEDhfU8hRcgPMlVP0gMUyiSEWqkaZyYatT17VPTbvNWj5B6lDEEYBk5ONxqM7nbWNBvVbStl9wY4TqNoVSkDJ4yvOc8ZpmNi0eseeHwGA/6AxAsI4ZnjhQNQuAX69D/EJLzKtq6XUhDRfXl/JWJm@Wnb@xs "Ruby – Try It Online") a full program which assumes there will be no newlines in the string. [Answer] # [JavaScript (V8)](https://v8.dev/), 98 bytes ``` x=>x.replace(/(.)\1*/g,y=>s=s.replace(/$/mg,_=>y[i]+y[i--]||' ',i=n),s=` `.repeat(n=x.length))&&s ``` [Try it online!](https://tio.run/##RYqxDoIwFAB3v4IQA62WEjeXxzewq5FnUyqmFuxrEBL@vUocvOGWuweOSMp3QyjGY2whTlBN0uvBotKsZJKfD7vSiBkqAvqHbfk04grVfOou@6@K4rIseZLkogPHBUGzadZbY2AOJmm1M@HOeZZRVL2j3mppe8NaliLibUWpl/dEFH7U9TvlPH4A "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), 100 bytes ``` x=>x.replace(/(.)\1*/g,(y,c)=>s=s.replace(/$/mg,_=>y[i--]?c+c:' ',i=n),s=` `.repeat(n=x.length))&&s ``` [Try it online!](https://tio.run/##RcpBDoIwEEDRvacgxECrpcSdMRm8Ans1UielYGrBToNw@hriwrf9/6kmRej7MRTTMbYQZ6hm6fVoFWpWMsmvh11pBFsEcqgI6B@35cuIO1TLpS@K2xn3eMqTJBc9OC4Imk2zvloF5mCWVjsTOs6zjCIOjgarpR0Ma1mqlHqsEN/eE1H4qetPynn8Ag "JavaScript (V8) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 37 bytes ``` {⊃,/⍵↑⍨¨-⌈/≢¨⍵}'(.)\1*'⎕S{2/⍪⍵.Match} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zmzpPJR24TqR13NOvqPerc@apv4qHfFoRW6j3o69B91Ljq0AihYq66hpxljqKX@qG9qcLURUN0qoKieb2JJckYtxAwF9cTExCQQSE4uLCoqLi4ugYCAgHJ1AA "APL (Dyalog Unicode) – Try It Online") [Answer] # q/kdb+, 53 bytes **Solution:** ``` {(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x} ``` **Example:** ``` q){(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x}"BBPPPPxxGGGGKKKKKKKkkkkEEeeEEEeeEEEEEOOO8####xxXXX" " KK " " KK " " KK EE " " PP GGKKkk EE ## " " PP GGKKkk EE EEOO ## XX" "BBPPxxGGKKkkEEeeEEeeEEOO ##xxXX" "BBPPxxGGKKkkEEeeEEeeEEOO88##xxXX" ``` **Explanation:** ``` {reverse flip raze (max count each c)$flip 2#enlist c:(where differ x)_x} / ungolfed function { } / lambda function (where differ x) / indices where x differs _ / cut at these points aabbbc -> "aa","bbb","c" c: / save in variable c enlist / put this list in another list 2# / take two from this list (duplicate) flip / rotate columns/rows (max count each c) / find the longest run of characters $ / whitespace pad lists to this length raze / reduce down lists flip / rotate columns/rows reverse / invert so buildings are on the ground ``` [Answer] # [Perl 5](https://www.perl.org/), 92 + 1 (-p) = 93 bytes ``` while(s/(.)\1*//){$a[$_].=($"x($i-length$a[$_])).$1x2for 1..length$&;$i+=2}say while$_=pop@a ``` [Try it online!](https://tio.run/##LYzRCsIgFEB/ZcQltPA6B3sKoR8I9l4xbKwmyDSvsEX06xm1zuM5cEIfXZ3zNFjXM5IM@UltpORPMEdoz6gZrGYGVrh@vKVhsZwjqLm6@lgoxH9Z78BudfUi8yh@O2h18GFvcjbGXL503T1GIkoLTTO9fUjWj5TFocZSlVmEDw "Perl 5 – Try It Online") ]
[Question] [ Some of you may be familiar with the way that a motorcycle shifts. But for those who don't, It looks like this 6 5 4 3 2 N 1 Now I want to know what gear I am in after performing a few up and down shifts. The program should work from neutral. Sample input: ``` V^^ ``` Sample output: ``` 2 ``` As you can see I downshifted once from N to 1 and upshifted twice to 2nd gear. This is a code golf. Shortest answer in bytes wins. Note: The input can be any 2 characters. Can be U and D for up and down or whatever you want **it has to be a string**. You cannot shift beyond 1st or 6th gear. If you are in 6th and upshift again it will stay in 6th. Good luck! [Answer] ## JavaScript (ES6), ~~49~~ ~~48~~ ~~47~~ 46 bytes Expects: * `1` for down * `7` for up ``` f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g ``` ### Formatted and commented ``` f = ( // f is a recursive function which takes: [c, // - c = next character in input string ...s], // - s = remaining characters g = 2 // - g = current gear, with default = neutral = 2 ) => // c ? // if there's still a character to process: f( // do a recursive call with: s, // - the remaining characters g - c & 7 || // - the updated gear if it is valid g // or the previous gear if not ) // : // else: '1N'[--g] || // decrement g and output '1' for g = 0, 'N' for g = 1, g // or simply the corresponding digit for other values ``` Gears are mapped as follows: ``` g MOD 8 = 0 1 2 3 4 5 6 7 --------------- gear = X 1 N 2 3 4 5 6 (where 'X' is an invalid state) ``` Which allows us to easily check the validity of the current gear with: ``` (g & 7) != 0 ``` ### Demo ``` f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g console.log(f('')) console.log(f('1')) console.log(f('11')) console.log(f('17777')) console.log(f('1777777771')) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 20 bytes ``` Îvy<+®‚Z5‚W}6LÀ'N¸ìè ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4r6zSRvvQukcNs6JMgUR4rZnP4QZ1v0M7Dq85vOL/fyMDMDBCADAfAA "05AB1E – TIO Nexus") **Explanation** ``` Î # push 0 (accumulator) and input v } # for each in input y<+ # decrement current element and add to accumulator ®‚Z # take maximum of current value and -1 5‚W # take minimum of current value and 5 6L # push the range [1 ... 6] À # rotate left 'N¸ì # prepend the letter "N" producing the list [N, 2, 3, 4, 5, 6, 1] è # index into this list with the value produced by the loop ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~20~~, 15 bytes ``` :sil!î¬61énÀxVp ``` [Try it online!](https://tio.run/nexus/v#@29VnJmjeHjdoTVmhodX5h1uqAgr@P//f05ORkYGAA "V – TIO Nexus") Input is a string of `h` (up) and `l` (down) characters. *Thanks to @nmjcman for saving 5 bytes and teaching me about a vim feature I never knew about!* If we could assume the input never goes out of bounds, it would simply be 9 bytes: ``` ¬61énÀxVp ``` But unfortunately that isn't allowed. Explanation: ``` :sil! " If the cursor goes out of bounds, ignore it and continue î " Run the following keystrokes as V code, rather than vimscript: ¬61 " Insert the string "654321". This will leave the cursor on the '1' én " Insert an 'n' À " Run the first arg as V code. This will move left and right a bunch of times x " Delete whatever character we ended up on V " Select this whole line, p " And replace it with the character we just deleted ``` [Answer] # Java 7, ~~106~~ ~~105~~ 103 bytes ``` char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);} ``` **Explanation:** ``` char c(String s){ // Method with String input and character return-type int r = 1; // Result-index (0-indexed and starting at 1) for(int c : s.toCharArray()){ // Loop over all characters in the input String r += c < 99 ? // If the current character is '^': 1 // Raise the result-index by 1 : // If it is 'v' instead: -1; // Decrease the result-index by 1 } return "1N23456".charAt( // Return the character based on the return-index: r < 0 ? // If the result-index is below 0 0 // Use 0 instead : r > 6 ? // Else-if the result-index is above 6 6 // Use 6 instead : // Else r); // Use the result-index } ``` **Test code:** [Try it here.](https://ideone.com/hRoYsq) ``` class M{ static char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);} public static void main(String[] a){ System.out.println(c("v^^")); System.out.println(c("^^^^^^^^")); System.out.println(c("vvvv^^^vvvv")); System.out.println(c("^v^v^v^v")); } } ``` **Output:** ``` 2 6 1 N ``` [Answer] # MATL, ~~32~~ ~~28~~ 23 bytes *5 bytes saved thanks to @Luis* ``` '234561N'j!Uq[aA]&Ys0)) ``` This solution uses `'2'` for up-shift and `'0'` for down-shift. Try it at [**MATL Online**](https://matl.io/?code=%27234561N%27j%21UqlFq5K%24Ys0%29%29&inputs=00002222&version=19.8.0) **Explanation** ``` '234561N' % Push the string literal to the stack j % Grab the input as a string !U % Convert the input to a numeric array based on the characters. q % Subtract 1 to turn '2' into 1 and '0' into -1 [aA] % Push the array [-1 5] to the stack &Ys % Compute the cumulative sum using the array [-1, 5] as % the upper and lower limits at each point 0) % Get the last value from the cumulative sum ) % Use this to index into the initial string literal. % Implicitly display the result ``` [Answer] # Haskell, ~~59~~ ~~53~~ 51 Bytes ``` ("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1 ``` Uses `0` for down and `2` for up. Usage example: ``` (("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1) "0002" ``` Thanks to @xnor for taking off 6 bytes! Also, turns out I don't need a function name or parentheses so that's another 2 bytes. [Answer] # JavaScript (ES6), ~~48~~ 58 bytes ``` s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?a+1:a-1:6:0)] ``` # Usage Assign it to a function, and then call it. Input is a string containing a `1` for an upshift, and a `0` for a downshift. ``` f=s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?++a:a--:6:0)] f("011") -> "2" f("0") -> "1" f("01") -> "N" ``` [Answer] # PHP 7.1, 71 bytes ``` for(;$c=$argv[1][$i++];))$g=max(-1,min($g+=$c<=>X,5));echo N234561[$g]; ``` shifts `$g` from -1 to 5, uses negative string offset for first gear. Run with `-nr`, provide shifting string as command line argument. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 14 bytes ``` 1;r2ị$¥/CỊ¡o”N ``` Uses `6` for up and`0` for down. [Try it online!](https://tio.run/nexus/jelly#@29oXWT0cHe3yqGl@s4Pd3cdWpj/qGGu3////9UNzMzUAQ "Jelly – TIO Nexus") ### How it works ``` 1;r2ị$¥/CỊ¡o”N Main link. Argument: s (string of 6's and 0's) 1; Prepend a 1 (integer) to the string/character array s. / Reduce the result by the following dyadic link. Let's call the arguments x and y. ¥ Create a dyadic chain of 2 links: r Construct the range [x, ..., y] (increasing or decreasing). y will be a character, but 'r' casts both argument to int. This is intended for use with floats, but it works just as well when the argument is a digit. $ Create a monadic chain of two links: 2ị Take the second element of the constructed range. When y = 6 > x, this gives x + 1. When y = 0 < x, this gives x - 1. When y = x, the range is a singleton array, so this gives x. ¡ Conditional application: Ị If the previous result is insignificant (0 or 1): C Subtract it from 1. This swaps 0 and 1 without affecting the other potential outcomes. o”N Logical OR with 'N', replacing 0 with that character. ``` [Answer] ## Ruby, 58 bytes ``` ->s{a=1;s.chars{|b|a-=[a<=>0,a<=>6][b<=>?v]};"1N23456"[a]} ``` Expected input is 'v' for a downshift and '^' for upshift [Answer] # Processing JS (modified) 121 bytes ``` var g="1N23456",a="",c=0; for(var i=0;i<a.length;i++){if(a[i]==="d"&&c>0){c--;}else if(c<6&&a[i]==="u"){c++;}}println(g[c]); ``` Ungolfed ``` var g=[1,"N",2,3,4,5,6],a="",c=0; for(var i=0;i<a.length;i++) {if(a[i]==="d"&&c>0) { c--; }else if(c<6&&a[i]==="u") { c++; } } println(g[c]); ``` [Try it online!](https://www.khanacademy.org/computer-programming/new-program/5820138749755392) I went with PJs since I know it well. The only problem is the version I use is *very* strictly typed. I can't leave out brackets and lots of other tricks. It is pretty simple. The input should go into the variable `a` and it takes lowercase `u d`. The program loops until it hits the end of the string and every iteration it checks to see if it is a u or a d. If it is and it won't try and "shift" past where you can it shifts. At the end I print the results! [Answer] # k, 25 bytes ``` "1N23456"@{6&0|x+y-92}/1, ``` It takes input as a string, and uses `[` for downshift, and `]` for upshift, because they're conveniently situated. ``` "1N23456"@ / the numbers 0 to 6 are used for the gears, / this turns them into the correct number/letter 1, / prepend 1 because this is our initial gear { }/ / fold the function through the list / x is before, y is the next character y-92 / subtract 92, which is between "[" and "]" / "[" becomes -1 and "]" becomes 1 x+ / add it to what we had before 6&0| / use max and min to set boundaries 6 and 0 ``` Examples: ``` shift:"1N23456"@{6&0|x+y-92}/1, shift"[]]" "2" shift"]]]]]]]]" "6" shift"[[[[]]][[[[" "1" shift"[][][][]" "N" shift"[[[[[[[[]" "N" shift"]]]]]]]][" "5" ``` [Answer] ## [GNU sed](https://en.wikipedia.org/wiki/Sed), ~~89~~ 87 + 1(r flag) = 88 bytes Because sed has no integer types or arithmetic operations, the solution is arrived at by using regular expressions only. ``` s:$:65432Nx1: : /6x/!s:^U(.*)(.)x:\1x\2: s:^D(.*)x(.):\1\2x: t s:U|D:: t s:.*(.)x.*:\1: ``` It works by sliding the pointer `x` based on each input shift, left (for `U`p) or right (for `D`own), along a non-wrapping tape that contains only the cells `65432N1`. The answer at the end is the value in the cell left of the pointer. **Example run:** or [**Try it online!**](https://tio.run/nexus/bash#K05NUdAtUlD/X2ylYmVmamJs5FdhaMVlxaVvVqGvWGwVF6qhp6WpoadZYRVjWBFjZMUFFHMBiVUABYFiMUYVVlwlQNHQGhcrCEtPC6ReTwsoa/Vf/X8oGLgAAA) ``` sed -rf gear.sed <<< "UUUUUUD" 5 ``` **Explanation:** ``` s:$:65432Nx1: # assign initial tape and pointer : # start loop /6x/!s:^U(.*)(.)x:\1x\2: # if shift 'U', slide `x` to left, but not past the edge s:^D(.*)x(.):\1\2x: # if shift 'D', slide `x` to right, -||- t # repeat s:U|D:: # if a shift couldn't be applied, delete it "manually", t # and jump to the start of the loop again s:.*(.)x.*:\1: # print value left of pointer `x` (answer) ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~76~~ 73 bytes Includes +1 for `-r` ``` s/$/1/ : /1{6}/!s/^U(.*)/\11/ s/^D(.*)1/\1/ t s/U|D// t s/^1$/N/ s/^$/1/ ``` Output is in unary except neutral, which is still `N` (see [this consensus](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top)). [Try it online!](https://tio.run/nexus/bash#K05NUdAtUlD/X6yvom@oz2XFpW9YbVarr1isHxeqoaelqR9jCBQG8lxAPEMgV5@rBMgPrXHRh7DiDFX0/cBKQCb8V/8fCgYuAA) This basically counts up and down in unary then converts 1 to N and 0 to 1. ``` s/$/1/ # add 1 to the end (the starting value) : # loop start /1{6}/!s/^U(.*)/\11/ # If the string starts with 'U' and doesn't have 6 ones, increment s/^D(.*)1/\1/ # If the string starts with 'D' decrement (but not past 0) t # if something changed loop back s/U|D// # if the U or D couldn't be applied, remove it. t # if something changed loop back s/^1$/N/ # replace 1 with N s/^$/1/ # if "0", replace with 1 ``` [Answer] # Rebol, 96 93 bytes ``` f: func[s][g: next"1N23456"parse s[any["D"(g: back g)|"U"(unless tail? x: next g[g: x])]]g/1] ``` Ungolfed: ``` f: func [s] [ g: next "1N23456" parse s [ any [ "D" (g: back g) | "U" (unless tail? x: next g [g: x]) ] ] g/1 ] ``` Example usage (in Rebol console): ``` >> print f "DUU" 2 >> print f "DDDUU" 2 >> print f "UUUUUUUUU" 6 >> print f "UUUUUUUUUD" 5 ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 35 bytes An enthusiastic piece of code that encourages you to drive above the speed limit. Accepts any two inputs whose code modulo 3 are 0 and 2, for example `0` and `2`. For extra fishiness, I recommend the use of `<` and `>`. ``` 1i:0(?;3%1-+:0(?0:6)?6:1go! 1N23456 ``` Explanation : ``` 1i:0(?;3%1-+:0(?0:6)?6:1go! 1 # initial position i # read the next char :0(?; # copies it, test copy against 0, if lower stops (EOF detection) 3%1- # map the char to -1 or 1 + # add it to the position :0(?0 # if the new position is lower than 0, set to 0 :6)?6 # if the new position is greater than 6, set to 6 :1go # output a character from line 1 at the position ! # loops and skip the position initialisation ``` You can [try it here](https://fishlanguage.com/) ! [Answer] # SpecBAS - 102 ``` 1 g=2: INPUT s$ 2 FOR i=1 TO LEN s$ 3 g+=(s$(i)="^" AND g<7)-(s$(i)="v" AND g>1) 4 NEXT i 5 ?"1N23456"(g) ``` Moves the index of the string depending on input and prints the relevant character. [Answer] # Pyth, 32 bytes ``` J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1 ``` Uses space and newline for down and up. Explanation ``` J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1 J1 Initialize J to 1 VQ ; For each character in the input +J-qNbqNd Increment or decrement J htS[06 Get the middle sorted value of [0,6,J] =J Assign it to J ?qJ1\N?JJ1 Change 1 to 'N' and 0 to 1 ``` There's almost certainly a better way to do the incrementing and the output. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~24~~ 22 bytes ``` "1N23456"1q{~0e>6e<}/= ``` Uses `(` for down and `)` for up. [Try it online!](https://tio.run/nexus/cjam#@69k6GdkbGJqpmRYWF1nkGpnlmpTq2/7/78mEGgggKYmAA "CJam – TIO Nexus") **Explanation** ``` "1N23456" e# Push the string containing all gears 1 e# Push 1, the initial index q e# Push the input { e# For each character in the input ~ e# Eval that character. ( is decrement and ) is increment. 0e> e# Take the maximum of (0, index) 6e< e# Take the minimum of (6, index) }/ e# (end of block) = e# Take that index of the string ``` [Answer] ## Batch, 144 bytes ``` @set/ps= @set g=1 :l @if %g% neq %s:~,1% set/ag+=%s:~,1%/3-1 @set s=%s:~1% @if not "%s%"=="" goto l @if %g%==1 (echo N)else cmd/cset/ag+!g ``` Takes input on STDIN, using `0` to go to a lower gear and `6` to go to a higher gear. These numbers were chosen to make it easy to ignore the current gear. Finally if the gear is `1` then `N` is printed otherwise `0` is converted to `1` and the gear is printed. [Answer] # Javascript ES6 nonstrict, ~~136~~ 120 chars ## 136 chars for `V^` ``` with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x') ``` ``` with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}}) f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x') console.log(f("V^^")) ``` ## 120 chars for `-+` ``` with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x') ``` ``` with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}}) f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x') console.log(f("-++")) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 65 bytes ``` ^ 1 N23456 +(` (.)?(\w*6)u $1 $2 )`(.)? (\w*6)d $1$2 .* (.).* $1 ``` Uses `u` and `d` for up and down. [Try it online!](https://tio.run/nexus/retina#@x/HZajgZ2RsYmrGpa2RoKChp2mvEVOuZaZZyqViqKBixKWZABJTgAimcCmoGAIF9bRAKvW0gGr@/08BgtJSAA "Retina – TIO Nexus") **Explanation** This program works by keeping `1N23456` behind the sequence of instructions. It keeps track of the current gear by having a space behind it. Then it takes one instruction at a time until there's no more. ``` ^ 1 N23456 ``` Start by putting `1 N23456` before the input. The space before `N` indicates that `N` is the current gear. ``` +(` (.)?(\w*6)u $1 $2 )`(.)? (\w*6)d $1$2 ``` These are two replacement stages, grouped together, and run until they stop changing the string: ``` (.)?(\w*6)u $1 $2 ``` The first one handles shifting the gear up. It will look for any number of gears after the space, followed by a `6`, then followed by `u` (`u` indicates the instruction to gear shift up). If there were characters before the 6, it swaps the space with the character immediately after it, deletes the `u`, and leaves the rest of the string intact. Since the `6` is mandatory in the match, it will only swap the space with any character before the `6`. It will never swap with the `6`. ``` (.)? (\w*6)d $1$2 ``` The second stage handles gear shifting down, and works similarly. It looks optionally for a character before the space, then some other gears after ending in `6`, followed by `d`. It swaps the space with the character before it, deletes the `d`, and leaves the rest intact. If the space was at the start of the string, there was no match for a character before the space, so no swap occurs. ``` .* (.).* $1 ``` After neither of the above replacements can be done anymore, all gear shifts have been completed. The line is cleared of everything except the gear immediately after the space. This is the final gear. [Answer] # Powershell, ~~112~~ ~~87~~ 85 bytes `$i=1;switch([char[]]$args[0]){'^'{if(5-gt$i){$i++}}'v'{if(1-le$i){$i--}}}'1N2345'[$i]` ungolfed ``` $i=1; # index which gear we are in switch([char[]]$args[0]){ # loop over all elements using a switch '^'{if(5-gt$i){$i++}} # if there is a ^ and we are not in sixth yet, shift up 'v'{if(1-le$i){$i--}} # if there is a v and we are not in first, shift down } '1N2345'[$i] # print the output ``` saved 25 bytes by reading the [powershell codegolf tips](https://codegolf.stackexchange.com/questions/191/tips-for-golfing-in-windows-powershell/) saved 2 bytes by flipping the gt/le operators [Answer] **Perl 6, 144 bytes** ``` my enum C <1 N 2 3 4 5 6>;my $n=prompt("");my $p=1;for split("",$n) ->$l {$l eq "u" && $p < 6 ?? ++$p !! 0;$l eq"d"&&$p>0 ?? --$p!!0};say C($p); ``` Works as it should, i believe. Improvements are welcome. First time using Perl for anything, but i loved the thought of the language, so i had to try. [Answer] # Clojure, 74 bytes ``` #((vec "1N23456")(reduce(fn[c s](max 0(min 6((if(= s \^)inc dec)c))))1 %)) ``` Folds over the shift string, maintaining an index as the accumulator. Each iteration it either increases or decreases the index, then clamps it to the range 0-6. Finally, a string holding the gears is indexed and returned. Returns a Clojure character representing the current gear. Gear 1 is returned as `\1`, and gear 'N' is returned as `\N`. Pre-golfed explanation. Follow the numbers, since it doesn't read well top-down. ``` ; Expects ^ for shift-up, and V (or anything else) for shift down ; Returns a character representing the current gear (defn shift [shift-str] ((vec "1N23456") ; 4. Then index the gear list with the calculated index, and return (reduce (fn [current-gear s] ; 1. Fold over the shift symbols (max 0 (min 6 ; 3. Clamp it to the range 0-6 so we don't overflow ((if (= s \^) inc dec) ; 2. If the shift is up, increase, else decrease current-gear)))) 1 shift-str))) ``` [Answer] # Python 3, ~~67~~ 63 bytes ``` k=1 for i in input():k+=[k<6,-(k>0)][i<'1'] print('1N23456'[k]) ``` Pretty straightforward solution. -4 bytes thanks to @ovs! ]
[Question] [ A little while back, data was frequently stored on punched card. A typical card would have 80 columns of 12 possible 'punch' positions. A plethora of encodings was used, each for their own specific purpose. These days we like to think of a byte as 8 bits. In this challenge, you're tasked to convert an 8-bit byte to a 12-bit word so that it may be stored on a punched card. Since too many holes per column would weaken a punched card considerably, your encoding must adhere to the following rules, * No more than 3 holes punched per column (i.e., no more than 3 bits set per 12-bit word) * No more than 2 holes punched consecutively in the same column (i.e., no more than 2 consecutive bits set in each word) There are [289 valid 12-bit punch cards](https://tio.run/##bdYxTgQxEAXRnLsg9bsTiGwTxPmBzNW73gjLdtvMTNev78@P96/Hz@//b/J7y98ykBlZJnukgFST0nKOHCo3kOu4341epwPrbjLojH1rGchMl3n652QgM7Ksezw/EBnIjCyTPS3g5YnKQGZkmeyRAq3m9f3IQGZkmeyRAlKtpV1evQxkRpbJHikg1aR0z3H7xGQgM7JM9kgBqSal5Zwe6vpdy0BmZJnskQJSTUrLOXJob@DSWdpZ7MbQxujA6hIZtDFOAW1abVptWrMKpGm1abVpWf1zDlVSKCmUFEoKJYWSQklh1qEhhZJCSaGkYLXmubXyTfmmfFO@Kd@Ub8o35ZvyTfmmfFO@mXXr8E35pnxTvinfWNg4z0AZr4xXxivjlfHKeGW8Ml4Zr4xXxivjlfHKeGW8Ml4Zr4w36xmE8cp4ZbwyXhmvjGcB8jxejVCNUI1QjVCNUI1QjVCNUI1QjVCNUI1QjVCNUI1QjVCNUI1QjVCNUI1QjVCNUI1QjVCzHm8iVCNUI1QjVCNUI1QjlJUy5zWqCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmpCakJqQmZ9RpjQmpCakJqQmpCakJqQmpCLCU4345atFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRatFq0WrRZ304sWi1aLVotWi1aLVotWi1aLTof7/wB), of which 1 has 0 holes, 12 have 1 hole, 66 have 2 holes, and 210 have 3 holes. Compare this to 256 8-bit sequences. You must create two programs/functions: one of which takes a 8-bit byte and converts it to a 12-bit word according to an encoding of your choice that follows the above rules; and one of which takes a 12-bit word according to your encoding and converts it back to an 8-bit byte. The latter program may exhibit undefined behaviour for any input which is not contained in your encoding. Input and output is flexible according to the defaults for I/O, and may even differ between your programs. Your score is the sum of the bytecount of both programs. The programs must work independently, so they may not 'share' code between them. [Answer] # JavaScript (ES6), ~~103~~ 100 bytes *See also [my other answer](https://codegolf.stackexchange.com/a/211106/58563) for less bitwise operations, more maths, and a closed-form expression* Both functions expect and return an integer. ## 8-bit → 12-bit (~~56~~ 53 bytes) ``` f=n=>n&&(w=f(n-1),w+=(x=w&w-1)&x-1?w-x:1)+(w&w/2&w/4) ``` [Try it online!](https://tio.run/##bY5NbsJADIX3nMKrxNYkU5LSLpoOHIJly2IECQQhTzSZdiJVcPXgwAIWXfjnWZ@f3tH@2n7r2y7k7Hb1ODaGzZKTBKNpkPOCsqgMDiYmUUQy5MUq5sNHQQrl9FJKLWhsnEcLBr42GbDMeSXjE8q3d1mUIvibAWwd9@5U65PbI@vg1sG3vEfSnd2tg/UBXwkUpHBZSlOAvu7FS2IQ/Ysv7jhOsLAPpnyCijKD@Q2klCqJYXX30x8mc5Hn2XOq9JsnL6uPrmVMM/mharwC "JavaScript (Node.js) – Try It Online") ### How? This is a recursive function that computes the next valid 12-bit word \$w\_{n+1}\$ directly from the previous valid word \$w\_n\$. **Step 1: Update `w` according to the total number of bits set** Given `w` from the previous iteration we first compute: ``` x = w & (w - 1) ``` which is `w` without its least significant bit. Likewise, we remove the least significant bit from `x` by doing: ``` x & (x - 1) ``` If the result is zero, we just increment `w`. If the result is non-zero, it means that there are already 3 bits set in `w` and we are not allowed to insert a 4th one. In that case, we add the least significant bit of `w` (which is `w - x`) to `w`. This results in at most as many bits set in the updated value than in the original one, or less in case of carry propagation. Examples: ``` 110010 + 10 -> 110100 101100 + 100 -> 110000 ``` **Step 2: Update `w` according to the number of consecutive bits set** We now have to make sure that there are not 3 consecutive bits set in `w`. We do that by adding the result of a bitwise AND between `w`, `w / 2` and `w / 4`. Example: ``` 01110 + (01110 & 00111 & 00011) -> 01110 + 10 -> 10000 ``` ## 12-bit → 8-bit (47 bytes) ``` f=w=>w&&!(w&w/2&w/4|(y=(x=w&--w)&x-1)&y-1)+f(w) ``` [Try it online!](https://tio.run/##bVTLbhsxDLz3K9SLuwuvXZESJS0C59YvyLHowUjiNEVgB47RTYCiv@5yRtcedgANKYqP4f7a/96/3Z@fXy@b4@nh8Xo97Jbd7bJafR6W1fJV/ct/ho/d8L5bVpvNMq7eNzKuPhzWh2EZrzff4xRkCjqFNIU8BZtCmUKbwuw8bG4Ut4qbxS1S/XOzuF3drrjsdvW76pfVfRKiuX9yLjmXwPm95Pey38l@J7tPdnsG57HMeXOuOFeQhN8pfqe4vbi9ur26vXrc6j4VWTrXPFZzvjnXkLbzs9@bkWNEATGjAhwVNSVwCVUlloW6kKggS0GagjwFiQoylGwAWJGsIEspsBZEKTzCD6kK8pIZ3IzIMwzISZGLxoYu4WgVwCM6iXiKeIp4inha2E44I7KiekX5ivoVDyk6oChbG6LMOOJxxZMJlScMKWFKCWNKSq5hQHBBMQm9Sw2DauAQLyFKjhyWcwYJGDRgApGIAWiogIbhcYICgDMeMqUB40XbDR03vGtorKGxlnmEH3IxNMJQm1VErjCgSkOShqwKmlgwngIhlUzVQDaIUozCgVIiZdIAEBAVRAPCVwoGBTbqICJfRyMWYiVSSJROpHZi96dwIpUTKZ2Yu9qESB/KJ1I10ehjjGlkqKFI6cRK/0a@8a2ZViopYprShSzKpaQIxRKRPON3XXYlSqPwubQUiiOXGevi2Nei7wWl39e8Sz5S6azLuBPGpTDWyOkJ5@XPNq4D94GyZb2O/EEYVW9CVGIi0pObwJ4oe6LsicYeh/qPXIDIDWCXfIf6JjFm6wz9uQfslQpqcUzETCTff1mYqXK5lQvrWInkW/zxaXs4nb/t738Ox7C7Dfen49vp5XH7cnoajtvL6e5yfj4@DeP2df9wd9mfL0Mewzp8CX9vHdbhMBzH/7qlcRxvrv8A "JavaScript (Node.js) – Try It Online") ### How? In this version, we decrement `w` at each iteration and increment the final result whenever `w` is a valid 12-bit word. We stop when `w = 0`. We use the following methods to test the validity of `w`. They are similar to the ones used above. * we compute `w & w / 2 & w / 4` to make sure that there are not 3 consecutive bits set * we compute a chain of three `w & (w - 1)` to make sure that there are no more than 3 bits set [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 + 22 = ~~62~~ 43 bytes ``` ⎕⌷⍋(+/+3∊3+/⊢)¨,⍳12/2 ``` and ``` ⎕⍳⍨⍋(+/+3∊3+/⊢)¨,⍳12/2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91tKdxAbmPerY/6u3W0NbXNn7U0WWsrf@oa5HmoRU6j3o3GxrpG3EB1YFwOlht7@ZHvSsIKf//H2hwVxNQxMjUDAA "APL (Dyalog Unicode) – Try It Online") Pretty much the same programs, with indexing into an array (`⌷`) of valid punch cards for the encoder and finding the index (`⍳⍨`) for the decoder. Both the encoder and the decoder take a number and output a number. ### Explanation ``` ,⍳12/2 ⍝ Create every combination of 12 bits ( )¨ ⍝ Map each to 3+/⊢ ⍝ Does the sum of each consecutive group of three bits 3∊ ⍝ Contain a 3 (1 if so, else 0) +/+ ⍝ Add that to the total digit sum ⍋ ⍝ And grade this list ascending ⍝ This outputs the indexes (which are the same as parsing the original bits in base 2) in order of the smallest value to the largest ⎕⌷ ⍝ Finally we either index the input into the list ⎕⍳⍨ ⍝ Or find the index of the input in the list ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 + 12 = 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ### 8-bit byte (integer) -> 12-bit word (list of 1-indexed set bits): ``` 3Ḋ12œcẎIÞṚị@‘ ``` **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//M@G4ijEyxZNj4bqOScOe4bma4buLQOKAmP///zE0 "Jelly – Try It Online")** ### 12-bit word (list of 1-indexed set bits) -> 8-bit byte (integer): ``` 3Ḋ12œcẎIÞṚḊi ``` **[Try it online!](https://tio.run/##y0rNyan8/9/44Y4uQ6Ojk5Mf7urzPDzv4c5ZQIHM////RxvpKBgaALFhLAA "Jelly – Try It Online")** [Here](https://tio.run/##y0rNyan8/9/o4Y5tD3dONzQKtjm09Fi7SYinyuF5D3fOeri72@FRw4z/RqZmQBVH9xxuf9S0RuXopIc7ZwAZQOT@HwA) is a map (`byte-integer word-as-12-bits word-as-1-indexed-set-bits`) using the first Link. ### How? Both Links create a list of all (\$286\$) ways to punch either two or three holes as lists of 1-indexed holes (e.g. `[3,7]` represents `001000100000`), sorts these by the incremental differences between those indices (i.e. `[3,7]` (`001000100000`) maps to `[4]` while `[2,3,4]` (`011100000000`) maps to `[1,1]`), and reverses that result (placing the \$11\$ of the form `0*110*` at the very end, preceded by the \$10\$ (invalid ones) of the form `0*1110*`, with \$265\$ usable patterns at the start). The first Link finds the 0-indexed entry, while the second finds the 1-indexed index of the representation of a word in a dequeued version of the list (this then gives us a `0` when the input is not found). ``` 3Ḋ12œcẎIÞṚ - niladic chain 3 - three Ḋ - dequeued -> [2,3] 12 - twelve œc - combinations (vectorises) -> [[[1,2]…[1,12],[2,3]…[11,12]],[[1,2,3],[1,2,4]…[10,11,12]]] Ẏ - tighten -> [[1,2]…[1,12],[2,3]…[11,12],[1,2,3],[1,2,4]…[10,11,12]] Þ - sort by: I - incremental differences -> [[1,2]…[11,12],[1,2,3]…[10,11,12],[1,2,4]…[1,12]] Ṛ - reverse -> [[1,12]…[1,2,4],[10,11,12]…[1,2,3],[11,12]…[1,2]] <- 265 valid -> <- 10 invalid -> <- 11 valid-> ị@‘ - rest of Link 1: byte (integer), b ‘ - increment -> b+1 @ - with swapped arguments: ị - (b+1) 1-indexed index into (the list above) Ḋi - rest of Link 2: word (list of hole indexes), w Ḋ - dequeue (the list above) - remove the first word (representing the zero byte) i - index of (w) (in that) - yields zero if not found ``` [Answer] # [Python 3](https://docs.python.org/3/), 160 bytes --- # [Python 3](https://docs.python.org/3/), 82 bytes ``` f=lambda b,n=0:0**b*f'{n:012b}'or f(b-(sum(map(bin(~n).count,('111','1')))<4),n+1) ``` [Try it online!](https://tio.run/##HdPLbhpREIThfT3F7JhxHOtUn7sVL51tNnkB44CMYgY0DEqsKHl1p9pIXHTUwPD9zfltfTnN8f1wPJ@Wdbi8XaD73WW3Lrvn63I5nObXw/Gwjgx@m973D69Px@2Pp2F7Oz@E@3Bzs73Zb/7M94G2/bs5LcN@3H4eL9fjeHw6j9vDPP6bp7vn03Veb8cNyc3thptpmr6k6Xb@xOn918vhdTd8X667ewzDurz50zAc5vPwoMd11KvrOk7Tx/F58aO9H36c7H4/787r8Pjt6@OynJb7Ybvsnn6@BxCGiISMgoqGDuqQoIERTGAGC1jBBnZYgOk9BouwBMuwAquwBuuIAZGI@siImBAzYkGsiA2xIwUkIhmSvjEhZaSCVJEaUkcOyEQ25IisC8rIBbkiN@SOElCIYigRJaHoegtKRWkoHTWgEtVQI2pCzaj6ORW1oXa0gEY0Q4toCS2jFTT92obW0QM60Q09oif0jF7QK7owXEMcQR5BIEEiQSRBJkEoQSpBLEFzH2yacziXczq3czzXcz75UYA099WcDClESpFipBwpSEqSoqQsGT2E5sRJeVKglChFSplSqJQqxcrkxTQnWYqWsqVwKV2Kl/KlgClhZk@rOSFTyhQz5UxBU9IUNWVNYbP4DmhO3hQ4JU6RU@YUOqVOsVPurL4smhM9ZU/hU/oUP@VPBaAKUAnYfKs0pwpUBqoDFYIqQaWgWlAxqBrsvn6@f1pA9TD1MPUw9TD1MPUw9TD1MPUw@qJqTj1MPUw9TD1MPUw9TD3M99kX@mOjNec77UvtW@1r7Xvti60eph6mHhZ99TWnHqYeph6mHqYeph6mHqYeph6W/D@iOfUw9TD1MPUw9TD1MPUw9TD1sOx/pvwf "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 78 bytes ``` [f'{i:012b}'for i in range(2181)if sum(map(bin(i).count,('111','1')))<4].index ``` [Try it online!](https://tio.run/##VdZNTxNhGEbhPb9idm0TYuZCF4bIErdu3KkLwAITpW3GNkKMvx3B1SkLPgqdvLzP/Zz77J7299vN2@e7i6/PX24Xf6bz0dn138Xtdh6mYdoM89Xmbr08895quh1@HR6WD1e75fW0WU6rNzfbw2Z/ulxgcbqwWK1WH959ezNtvq8fn3/fTz/Xw@f5sD4/GYb9/PT6ZXh55m64eP182C9X/1/ZzdNmv7xbvry2en1l/Xiz3u2Hy08fL@d5O58P1/P66sfzmI@TfC8/6G/kN/oefY@8Rx@tjzYe/VkerY@WR@tB9aB6UD2oHtR49LQcVA@qB5WD6lXpVelV6VXpVelV6VXpVelVGY9OkNvRC9EL0QuRO9Bp67R12jptnbZOW6et09Zp67R1wDpTnanO1Hj0L2RYOhIdiY5EpyB3rfHX@Gv8Nf4af42/xl/jr/HX@GviNeQacg255lrTqxnVjGpGNZbGowtJqjQuGheNiyZEcyADVtQoahQ1ihpFjaJGUaOoUdQoapQuChQFigJFGaKkUB4oD5QHigBddN1gXU1dTV1N3UbdOePRXWcxNOQacg255lrTq7GUiGl9aH1ofWh9aH1ofWh9aH1ofWh9aGNoSWhJaEloLyj9lfHKeGW8Yl3hrVRW3CpuFbdKWOWoAlJhp@BScCm4lFVKJEWN8Wim2XpdWl1aXVrdU91GXTNdGUm8eoh6iHqIeoh6iHqIeoh6iHqIeoiqh9qG2obahgqGaoTKgsqCyoL6gVqA1rv2tva29rZWtRayNq22pjagNqA2oJaeVpt2lvaP1ofSX@mv9FfgK9aV18pe41GQAjvFk@JJ8aREUu4oUBQOutuyjarUqtSq1KrUqtSq1KrUqtSq1KrUatEqzirOKs7qymrE6r3qveq9qroqtGqqqqCqoKqgap3qliqNKoAqcypzKnPZmPEf "Python 3 – Try It Online") The first function (8-to-12-bit) increments numbers resursively until the binary representation satisfies all criteria. The second function (12-to-8-bit) uses the `index` method of a filtered list. The list in the second function has a `__getitem__` method which could replace the first function, but this is 2 bytes longer. Thanks to ovs and xnor for saving 6 bytes in total. [Answer] # JavaScript (ES7), ~~167 144~~ 143 bytes ### 8-bit → 12-bit (~~120 97~~ 96 bytes) This answer is definitely not very competitive, but I was curious to see how the conversion could be done without any recursion nor trial-and-error. So here is a closed-form expression! Expects and returns an integer. ``` n=>n<5?n:1<<(k=(54*n-166)**.333/2.1+.17)|2**(q=((n+=~~k*~k*~-k/6-3)*8)**.5-1>>1)|2**(n+q*~q/2-2) ``` [Try it online!](https://tio.run/##bc7NTsMwDAfw@57CtzpJky7pWhD94CF2BA7R1m5dJ6dfcAH66iVlB3ZAsmJH@vkvX@yHHQ9D002S3LFa6mKhoqQ8eaYnnefYFpjsOEmdpoxzFcdxZJQWSj@wL8M59gUiiWKeW76WbKNUxow/rjiRuiz1zZHo@dxHRhq21G5ACwW8vIVAvm8z33IwSeoHIRh8bgAOjkZ3rdTVnZDU5PbT0NAJmerscT/ZYcKYgYAA5tI/AnCoRp9VIzH2L9/dOK7Y2z9j7pA2IWx/IQtY5s@wqnsfz2u4/35v7q8KXmnNsuriGsIg9DssW34A "JavaScript (Node.js) – Try It Online") ### How? This is based on the observation that the positions of the bits in a valid 12-bit word are correlated to tetrahedral and triangular numbers. If \$n\$ is less than \$5\$, we just return \$n\$. Otherwise, we go through the following steps: * We first figure out what is the lowest \$k\$ such that \$T(k-1)\ge n-3\$, where \$T(k)\$ is the \$k\$-th [tetrahedral number](https://oeis.org/A000292), defined as: $$T(k)=\frac{k(k+1)(k+2)}{6}$$ \$k\$ is the real root of the following cubic equation, rounded towards \$0\$: $$x^3 + 3x^2 + 2x - 6(n-3) = 0$$ Once solved with WolframAlpha's [Cubic Equation Solver](https://www.wolframalpha.com/widgets/view.jsp?id=578d50248844454e46e24e9ed230843d) and after a few approximations (safe for our operating range), we end up with: $$\cases{ t=\left(\sqrt{\strut729(n-3)^2-3}+27(n-3)\right)^{1/3}\\ k = \left\lfloor\dfrac{t}{2.08} + \dfrac{0.694}{t}\right\rfloor }$$ Fortunately, we don't need so much precision and it can be simplified to the following JS expression, which gives [the correct result](https://tio.run/##LU/RUoMwEHznK7YzDk3AYiEFZ0T02Qef/IFiAItlEgewMHbor@Nd6UOS27273c13fso73dY//cbYopznChkMshe6XBdiIFgJgw1CeY8BfgYxEjfApcMsFSMXeL0SI56Y9HmVRx4Q3d6ddJzKtiSWIU5J/xlRnFDh@xJnBxhsWyx2MiX4WfeEVEii73l/CHTzpyLBQ9Sm/pG6l4sQ8Q4ergmTRMLzsA2UUmwchJRjG4SPy0JdCdZcZTguhkB/aO2A/Zs55U1dgOLx53F3NtOeM0zO5GhrOtuUQWO/xPrjV@uy61Zrmc7zPw) for \$4<n<256\$: ``` k = ~~((54 * n - 166) ** 0.333 / 2.1 + 0.17) ``` * \$k\$ is the 0-indexed position of the leading bit in the punch card word. * We define: $$p=n-3-T(k-1)$$ * If \$p>0\$, the position of the 2nd bit in the punch card word is given by: $$q=\left\lfloor\dfrac{\sqrt{8p}-1}{2}\right\rfloor$$ which is based on the reverse formula for triangular numbers. The JS implementation uses a right-shift. It means that we actually get \$-1\$ if \$p=0\$, in which case there's no 2nd bit. * The position of the 3rd bit in the punch card word is: $$r=p-\frac{q(q+1)}{2}-2$$ There's no 3rd bit if \$r<0\$. We use `… | 2 ** expr` rather than `… | 1 << expr` so that negative bit positions are ignored as expected. ## Hybrid version (90 bytes) For the record, below is my first attempt which was still using a limited number of recursive calls (up to 12) to compute \$k\$. ``` n=>n<4?n:(k=0,g=n=>n<0?2**~-k|2**(q=(p*8)**.5-1>>1)|2**(p+q*~q/2-2):g(n-k*++k/2,p=n))(n-3) ``` [Try it online!](https://tio.run/##bY5NcoMwDIX3OYV2WLZxwEk6nRCTQ2TZduFJgBAytvlpN225OhV00Sy60dPTfHrSzX7Y/tzVYYidvxRTaSZncnfYHt2eNSaRlVl8ctScj3HzRcJawwJ/Rs7VLk7zPMVlGkTLx3atY437irm44UI0ay2DcYjkNziVvmMWDLy8SXCkSUZyAL17okYIhM8VwNm73t8LdfeUogZ/GrraVQxVsJfTYLuBbRAERDDmVASwrugpq2R05l98@4uzGSb2j9EPUKolJAuIEWb0hlXhvb/O4WS/V49fRa9uzrLq5mvHIkk7mE0/ "JavaScript (Node.js) – Try It Online") --- ## 12-bit → 8-bit (47 bytes) I didn't write a specific 12-bit to 8-bit converter for this answer. But because the sequence is exactly the same, we can just use [the one we already have](https://codegolf.stackexchange.com/a/211082/58563). ``` f=w=>w&&!(w&w/2&w/4|(y=(x=w&--w)&x-1)&y-1)+f(w) ``` [Try it online!](https://tio.run/##bVTLbhsxDLz3K9SLuwuvXZESJS0C59YvyLHowUjiNEVgB47RTYCiv@5yRtcedgANKYqP4f7a/96/3Z@fXy@b4@nh8Xo97Jbd7bJafR6W1fJV/ct/ho/d8L5bVpvNMq7eNzKuPhzWh2EZrzff4xRkCjqFNIU8BZtCmUKbwuw8bG4Ut4qbxS1S/XOzuF3drrjsdvW76pfVfRKiuX9yLjmXwPm95Pey38l@J7tPdnsG57HMeXOuOFeQhN8pfqe4vbi9ur26vXrc6j4VWTrXPFZzvjnXkLbzs9@bkWNEATGjAhwVNSVwCVUlloW6kKggS0GagjwFiQoylGwAWJGsIEspsBZEKTzCD6kK8pIZ3IzIMwzISZGLxoYu4WgVwCM6iXiKeIp4inha2E44I7KiekX5ivoVDyk6oChbG6LMOOJxxZMJlScMKWFKCWNKSq5hQHBBMQm9Sw2DauAQLyFKjhyWcwYJGDRgApGIAWiogIbhcYICgDMeMqUB40XbDR03vGtorKGxlnmEH3IxNMJQm1VErjCgSkOShqwKmlgwngIhlUzVQDaIUozCgVIiZdIAEBAVRAPCVwoGBTbqICJfRyMWYiVSSJROpHZi96dwIpUTKZ2Yu9qESB/KJ1I10ehjjGlkqKFI6cRK/0a@8a2ZViopYprShSzKpaQIxRKRPON3XXYlSqPwubQUiiOXGevi2Nei7wWl39e8Sz5S6azLuBPGpTDWyOkJ5@XPNq4D94GyZb2O/EEYVW9CVGIi0pObwJ4oe6LsicYeh/qPXIDIDWCXfIf6JjFm6wz9uQfslQpqcUzETCTff1mYqXK5lQvrWInkW/zxaXs4nb/t738Ox7C7Dfen49vp5XH7cnoajtvL6e5yfj4@DeP2df9wd9mfL0Mewzp8CX9vHdbhMBzH/7qlcRxvrv8A "JavaScript (Node.js) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 + 27 = 54 bytes ``` ∧{ḃs₃ᵇ+ᵐ≤ᵛ2&ḃ+≤3&≜}ᶠ²⁵⁶;?∋₎ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HH8uqHO5qLHzU1P9zarv1w64RHnUsebp1tpAYU1QayjdUedc6pfbhtwaFNjxq3PmrcZm3/qKP7UVPf//9Gpqb/owA "Brachylog – Try It Online") It's the same program! To decode `2240`, give it as an argument and set the input to `Z` like [here](https://tio.run/##SypKTM6ozMlPN/r//1HH8uqHO5qLHzU1P9zarv1w64RHnUsebp1tpAYU1QayjdUedc6pfbhtwaFNjxq3PmrcZm3/qKP7UVPf//9R/42MTAwA). ### How it works ``` ∧{ḃs₃ᵇ+ᵐ≤ᵛ2&ḃ+≤3&≜}ᶠ²⁵⁶;?∋₎ ∧{ }ᶠ²⁵⁶ get the first 256 values of … ḃ in the base 2 representation … s₃ᵇ every 3 consecutive elements … +ᵐ≤ᵛ2 has a sum ≤ 2 &ḃ+≤3 and the base representation has a sum ≤ 3 &≜ turn the constraints to a number ;?∋₎ the number at index (input) is the output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 + 21 = 42 bytes ### Encoder: ``` I§Φ׳φ››⁴Σ⍘ι²№⍘ι²111N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEw7HEMy8ltULDLTOnJLVIIyQzN7VYw1hHwdDAwEBTR8G9KDURJA6jTXQUgktzNZwSi1ODS4CmpGtk6igYaWoClTrnlwINRZfRUVAyNDRUAqvwzCsoLfErzU0CGgQUsP7/38jU9L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. ### Decoder: ``` I⌕Φ׳φ››⁴Σ⍘ι²№⍘ι²111N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zLwVI5JSkFmmEZOamFmsY6ygYGhgYaOoouBelJoLEYbSJjkJwaa6GU2JxanAJ0Ih0jUwdBSNNTaBS5/xSoInoMjoKSoaGhkpgFZ55BaUlfqW5SUCDgALW//8bGVoY/NctywEA "Charcoal – Try It Online") Link is to verbose version of code. The only difference between the two programs is the second byte, which is `§` (AtIndex) for the encoder and `⌕` (Find) for the decoder. Explanation: ``` φ Predefined variable 1000 ׳ Multiplied by 3 Φ Filter on implicit range ⁴ Literal `4` › Is greater than ι Current index ⍘ ² Convert to a binary string Σ Digital sum › And not ι Current index ⍘ ² Convert to a binary string № Count (contains) 111 Literal string `111` N Input as a number § Index into filtered results ⌕ Find index in filtered results I Cast to string Implicitly print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 64 + 64 = 128 bytes Saved ~~2~~ 6 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!! Saved 9 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ### Encode \$8\$-bit to \$12\$-bit ~~85~~ \$\cdots\$ ~~66~~ 64 bytes ``` i;e(n){for(i=1;n;)n-=__builtin_popcount(++i)<4&i/(i&-i)!=7;n=i;} ``` [Try it online!](https://tio.run/##bZHdboJAEIXveYopibAr3Sj@tGlX6EXTp1BD7LK2S9rBrJiYGJ6dDgUUazchw2TO@c4OKPGhVFUZqRny0za3zEShRMlRREnyfjBfhcFkl@9UfsCCBYHhi5lnRsx4wvC76FFiZGRZZTLtAFk0lkIQIgv@Q2ANwBFDT2ALyGTpOAYL@N4YZNw5OUBHfW7sEOxyDRGc3NXxbbI6Pr3SM3fvod9P3VL@OigdWM0p9L5IkHxj2b0vYDJ/kBAETc@hCanP2aHJoVkrkLfzlOZpM9d/5iq3VquCBJ0y6pI9r6PHMYSTejK@mHeW7FvmDqYpiBgGs6ZQx2jNBtFW3da0l31e2VB0GEowMX1@EPRzehteBSniMna5Eik9COEF/KEPz@CDz3sB5c1NOQz2KySIXbZbr1t96ZTVDw "C (gcc) – Try It Online") ### Decode \$12\$-bit to \$8\$-bit ~~85~~ \$\cdots\$ ~~68~~ 64 bytes ``` j;d(n){for(j=0;--n;)j+=__builtin_popcount(n)<4&n/(n&-n)!=7;n=j;} ``` [Try it online!](https://tio.run/##bVHrToMwFP7PUxxJBu2w2dhFo13xh/EptoXM0mmJFtKxZAnh2fEgsDFnk@b05Lv1tJJ9SFnXKU@IoeU@syQVU86Y4TQNRBy/H/VXoU2cZ7nMjqZA1mrhmQkxHjP0TjxyI1Je1Zqr3kCLkKPcsP/kQaAbAz0h2mO6M9C8chxtCvjeaUOoUzqAS37u7BjsegsCSndzepttTk@vuJfuPQz7uVvxXwWmA2l8CnUoYoO6Ke/PK5gtHzgEQdtTaEOadVYoVCjSEfgtniCetLj6g8vMWiULJPRM0Sd7Xu8eRRDOGmR6EecW5XvijuYJsAhGi7ZgR3DM1qKrqqvJIPs8ssboMOSgI/w/YPi2gwmvgiT6EnK5EjI9COEF/LEPz@CDTwcB1c1NKYwOG4Mmdt1Nve34lVPVPw "C (gcc) – Try It Online") ### Explanation Sequentially goes through integers starting at \$1\$ only counting ones with valid bit patterns and returns the \$n^{th}\$ valid integer from \$1\$ for encoding, \$e(n)\$, \$8\$-bit to \$12\$-bit. Counts the number of valid integers from \$1\$ up to \$n\$ for decoding, \$d(n)\$, \$12\$-bit to \$8\$-bit. ### GCC builtins used `__builtin_popcount(n)` returns the number of 1-bits in \$n\$. [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 + ~~19~~ 17 = ~~36~~ 34 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I'm not sure I've fully understood the challenge, but let's give it a go ... ## 8-bit to 12-bit, 17 bytes Input as an integer, output as a binary string. ``` gI²o¤fÈè1 §3«Xø#o ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z0myb6RmyOgxIKczq1j4I28&input=MjU1) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z0myb6RmyOgxIKczq1j4I28&footer=VnMg%2bTMgKyIgLT4ge/lDfSAoPSB7zXMg%2bTR9KQ&input=MjU2Ci1tUg) ## 12-bit to 8-bit, ~~19~~ 17 bytes Input as a binary string, output as an integer. ``` nI²o¤fÈè1 §3«Xø#o ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=bkmyb6RmyOgxIKczq1j4I28&input=IjEwMDAxMDAwMDEwMCI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&header=Z0myb6RmyOgxIKczq1j4I28&code=bkmyb6RmyOgxIKczq1j4I28&footer=%2bUMgKyIgKD0ge81zIPk0fSkgLT4gIitWcyD5Mw&input=MjU2Ci1tUg) ## Explanation ``` gI²o¤fÈè1 §3«Xø#o :Implicit input of integer (first programme) nI²o¤fÈè1 §3«Xø#o :Implicit input of binary string (second programme) g :Index into (first programme) n :Convert from base (second programme) I :64 ² :Squared o :Range [0,I²) ¤ :To binary strings f :Filter by È :Passing each X through the following function è1 : Count the "1"s §3 : Less than or equal to 3 « : AND NOT Xø : X contains #o : 111 à :End filter (second programme) bU :First 0-based index of U (second programme) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 (18 + 18) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) **8-bit (integer) to 12-bit (string of 0s/1s) (18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` T12ãʒ1¢4‹}ʒƵAå≠}Iè ``` [Try it online](https://tio.run/##ASkA1v9vc2FiaWX//1QxMsOjypIxwqI04oC5fcqSxrVBw6XiiaB9ScOo//8yMA) or [verify all test cases](https://tio.run/##AToAxf9vc2FiaWX/VDEyw6PKkjHCojTigLl9ypLGtUHDpeKJoH1VCuKChcaSTj8iCeKGkiAiP/9YTsOo/yz/). **12-bit (string of 0s/1s) to 8-bit (integer) (18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` T12ãʒ1¢4‹}ʒƵAå≠}Ik ``` [Try it online](https://tio.run/##yy9OTMpM/f8/xNDo8OJTkwwPLTJ51LCz9tSkY1sdDy991Lmg1jP7/39DAwNDIAYDAA) or [verify all test cases](https://tio.run/##ATsAxP9vc2FiaWX/VDEyw6PKkjHCojTigLl9ypLGtUHDpeKJoH1EVeKCgcKjCnZ5PyIg4oaSICI//1h5a/8s/w). The only difference is the last byte (`è` vs `k`). **Explanation:** ``` T # Push 10 12ã # Take the cartesian product of "10" and 12: # ["111111111111","111111111110","111111111101",...,"000000000000"] ʒ # Filter it by: 1¢ # Count the amount of 1s 4‹ # And check that this count is smaller than 4 }ʒ # Filter again: ƵA # Push compressed integer 111 å≠ # And check that the string does NOT contain "111" as substring }I # After the second filter: push the input è # (8-bit to 12-bit) Get the string at the 0-based input index k # (12-bit to 8-bit) Get the 0-based index of the input-string # (after which it is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵA` is `111`. [Answer] # [R](https://www.r-project.org/), 42 + 61 = 103 bytes **Encoder** ``` (a=combn(13,3)-1)[,a[1,]+2<a[3,]][,scan()] ``` [Try it online!](https://tio.run/##K/r/XyPRNjk/NylPw9BYx1hT11AzWicx2lAnVtvIJjHaWCc2NlqnODkxT0Mz9r@hgcF/AA "R – Try It Online") Input as decimal number; outputs 3 positions to punch holes, with zero indicating no hole to punch. **Decoder** ``` which(colSums(!((a=combn(13,3)-1)[,a[1,]+2<a[3,]]-scan()))>2) ``` [Try it online!](https://tio.run/##K/r/vzwjMzlDIzk/J7g0t1hDUUMj0TY5PzcpT8PQWMdYU9dQM1onMdpQJ1bbyCYx2lgnNla3ODkxT0NTU9POSPO/oYKZgsV/AA "R – Try It Online") Input as 3 positions of punched holes, in ascending order, prefixed with zero if only two holes are punched; outputs as decimal number. **How?** `a=combn(13,3)` generates all picks of 3 integers from `1..13`, without repetitions, in ascending order. We subtract 1 to get all 2- and 3-hole combinations. `a=a[a[1,]+2<a[3,]]` keeps only combinations where the lowest minus the highest position is less than 2, thereby removing any sets of 3 holes in a row. To encode `b`, we choose the `b`th combination. To decode `w`, we subtract `w` from each combination: the correct combination is now all-zero, so its logical inverse is all-TRUE, so we select the combination that sums to 3. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 + 14 = 28 bytes Encoding: ``` @sDoS.+N^U2 12 ``` Decoding: ``` xsDoS.+N^U2 12 ``` [Try encoding online!](https://tio.run/##K6gsyfj/36HYJT9YT9svLtRIwdDo/39DY2MA "Pyth – Try It Online") [Try decoding online!](https://tio.run/##K6gsyfj/v6LYJT9YT9svLtRIwdDo//9oAx0FIDIEk8gMBDcWAA "Pyth – Try It Online") Both programs rely on the snippet `sDoS.+N^U2 12`, which creates a list of all possible length-12 lists of `0`s and `1`s, whose first 256 entries are all valid punch cards. This can be verified with this program: [Verify it online!](https://tio.run/##K6gsyfj/P63GrjjEuDbXUMFYzyrE2KbYJT9YT9svLtRIwdBIwcjU7P9/AA "Pyth – Try It Online"). How the snippet works: ``` sDoS.+N^U2 12 ^U2 12 Generate all length-12 lists of 0s and 1s. o Sort by .+N The deltas of the length-12 list S sorted sD Sort by the sum of the length-12 list. ``` Sorting on the sorted deltas of the length-12 list moves lists with more alternations between runs of `0`s and `1`s to the front. This moves the lists with 3 `1`s in a row as their only `1`s to the back. Sorting on the sum of the length-12 list then brings the lists with 0, 1, 2, or 3 `1`s to the front. Pyth's sort is stable, so this ends up with the valid punch sequences at the front. I'm unsatisfied with the `^U2 12` part of the program to generate the base length-12 lists. If the rest of the program could handle strings, `^`T12` would save a character. If anyone can figure out how to save a character, I'd love to hear about it. ]
[Question] [ Your challenge is to expand some brackets in a program's input as shown: 1. Find a string *s* between two matching brackets `[` and `]`, with a single digit *n* after the closing bracket. 2. Remove the brackets. 3. Replace *s* with itself repeated *n* times. (If *n* is 0, simply remove *s*.) 4. Go to step 1 until there are no more matching brackets in the input. Additional rules and clarifications: * You will take input and give output via any allowed means. * A trailing newline in the output is allowed. * You only need to handle printable ASCII in the input. * You may assume that all brackets match, i.e. you will never receive the input `[]]]]` or `[[[[]`. * You may assume that each closing bracket `]` has a digit after it. Test cases: ``` Input -> Output [Foo[Bar]3]2 -> FooBarBarBarFooBarBarBar [one]1[two]2[three]3 -> onetwotwothreethreethree [three[two[one]1]2]3 -> threetwoonetwoonethreetwoonetwoonethreetwoonetwoone [!@#[$%^[&*(]2]2]2 -> !@#$%^&*(&*($%^&*(&*(!@#$%^&*(&*($%^&*(&*( [[foo bar baz]1]1 -> foo bar baz [only once]12 -> only once2 [only twice]23456789 -> only twiceonly twice3456789 [remove me!]0 -> before [in ]2after -> before in in after ``` As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in each language wins. Good luck! [Answer] # [Gema](http://gema.sourceforge.net/), 17 characters ``` [#]?=@repeat{?;#} ``` Sample run: ``` bash-4.4$ gema '[#]?=@repeat{?;#}' <<< '[three[two[one]1]2]3' threetwoonetwoonethreetwoonetwoonethreetwoonetwoone ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~24~~ ~~23~~ 22 bytes ``` +`\[([^][]*)](.) $2*$1 ``` [Try it online!](https://tio.run/##LYzNCsIwEITveYoUq7QVxG79vYkHX2LdYlq2WLBZCMGiL18T6mFh5pudcex7a8ppWj/umGFNSEVO2SZXKRRp4HgTwatxVBEoFMtUoh@FAP3TMVOlZhHhHBNEmFwWmC5rXBVZABDL2Inoxrhw3/BWxrnXR4ttQwv@zo99sFDt9ofj6azQ8SBv1gMntFUNd@JYY281gek8ux8 "Retina – Try It Online") This is practically a builtin in Retina 1. Edit: Saved 1 byte thanks to @Kobi. ~~47~~ 45 bytes in Retina 0.8.2: ``` ]. ]$&$*¶ {+`\[([^][]*)]¶ $1[$1] \[([^][]*)] ``` [Try it online!](https://tio.run/##TYxNCsIwEIX3OUWKaakVxKb@7sSFHmKc0lSmWLAdCMGi3ssDeLGaUhcuBt773rxnydWt6cP4VPQ4F6gilXze4jUrzhBDjoDJFD1QKagUxR8UfQ9HZjgYixlqAdwSpuA6Rg3uaokwE6MY4BijHmCwn4AKc4iS2AM9lKFilqWx/p7@LR3mbg/J7cW39M@5rvZWZ8vVerPdCbDU8J1kQwEuREkVW5JQtxK1qRzZLw "Retina 0.8.2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~101~~ 96 bytes ``` fst.(""%) infix 4% s%']':d:r=(['1'..d]>>s,r) s%'[':r|(t,q)<-""%r=s++t%q s%x:r=s++[x]%r s%e=(s,e) ``` [Try it online!](https://tio.run/##hZBvT4MwEMbf91N0OATcWKSb/4gsxhd@AV@eNcGtOCKsW1vddPrVxetAxgsTydFcf/c8l7suUv0iiqLKkocq02bkO44bkHyZ5Vs6cYl2Pe7F81glPniRNxrN@XSqhyqwFfBi9emb4Tq4DtGmEj0YGHeNpW28v8CWuwqvIvH1UARVmeZLmtDVq7k3ivZpRh24kxJuU8XHnDlkF5IuoL9fOKWIkdbRzQnIpeARmI3kDMxCCcHH1oAYmQ3LDgepRdZQWzmrDbVkI2ujPf8FBHo3R9B3H@H4xMc@bD8z9kKMFCFGm/wJCUAmJX1KFf4fOE3ULNyhdsfiHTea4bis8ygtZo3EbHLUsPHk7Pzi8qqV7PEha8oElCjlm6Cl6PHTTlsSflXfs6xIn3UVzlarHw "Haskell – Try It Online") Instead of using regular expression like most of the other answers, this implements a recursive parser. *-5 bytes thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo)!* [Answer] # [Perl 5](https://www.perl.org/), ~~34~~ ~~33~~ 29 + 1 (`-p`) = 30 bytes ``` s/.([^[]*?)](.)/$1x$2/e&&redo ``` [Try it online!](https://tio.run/##hZHdboMwDIXveQpXZRVFAkq67keTumkXu9sTWKlEO3dlKhiFdKx7@DFTKOVi0iInsr6cY9lJQWa/qMsI/GAZ@lH0/gBj@DiUFnZkCEqGimCT5LDh4gh2JyjJij1BmhcHW4oz9HCF2n@cai@cRm785aqIJhNDb1zX@MKMz4nRc63gvIIlCBbaxjB3kHPSMdqKtUK7M0R63hgEC2uiYZfDaUWNobVq1RpaScWtsTn/BQ6OnsboXq1w4ntSR516llqChQqU6JM/oYO4ZYZ1YmR/SzdxN/CANjPujzLRRtpVg0fpseoktkpFo@bXi5vbu/tecsKXrLt20FDGnwQZjfRsUNZZ05blLzHNQatka8n8cGFTzss6eF2Es3hWB8Uv "Perl 5 – Try It Online") Cut it down with some help from @Shaggy and @TonHospel. [Answer] # [Japt v2](https://github.com/ETHproductions/japt), ~~21~~ ~~20~~ 19 bytes *Saved 2 bytes thanks to @Shaggy* ``` e/.([^[]*?)](./@YpZ ``` [Test it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS8uKFteW10qPyldKC4vQFlwWg==&input=Ilt0aHJlZVt0d29bb25lXTFdMl0zIg==) `e` is recursive replace, which makes one replacement at a time until there are no more matches. In this case, matches of the regex `/\[([^[]*?)](\d)/g` are replaced with with <inner text> repeated <digit> times until there are no more matches. According to what I have planned ([here](https://github.com/ETHproductions/japt/issues/28)), this regex should eventually be at least ~~3~~ 2 bytes shorter: ``` ‹[“⁽[»₋”]“.› ``` [Answer] # JavaScript, ~~71~~ ~~67~~ 66 bytes I *had* a 54 byte solution but it got screwed over by the second test case! :( ``` f=s=>s!=(x=s.replace(/.([^[]*?)](.)/,(_,y,z)=>y.repeat(z)))?f(x):x ``` --- ## Test Cases ``` f=s=>s!=(x=s.replace(/.([^[]*?)](.)/,(_,y,z)=>y.repeat(z)))?f(x):x o.innerText=`[Foo[Bar]3]2 [one]1[two]2[three]3 [three[two[one]1]2]3 [!@#[$%^[&*(]2]2]2 [[foo bar baz]1]1 [only once]12 [only twice]23456789 [remove me!]0 before [in ]2after`.split`\n`.map(x=>x.padEnd(22)+`: `+f(x)).join`\n` ``` ``` <pre id=o></pre> ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~110~~ ~~93~~ 92 bytes ``` import re f=lambda s:f(re.sub(r'\[([^][]+)\](.)',lambda m:m[1]*int(m[2]),s))if'['in s else s ``` [Try it online!](https://tio.run/##hZLtSsMwFIb/7yoypjaZU7bUz4Ei/vAmzjJo3QkrLE1Jo2XefD392NINwXIa0vOc923z0mLvtzaP6zozhXWeORzpl11i0k3CyqXmDm/Lr5S7aAUc1grUtVgpvtqIaNZPmaWBhZpmuecGpBKzUohMRxBlOSsZ7kpkZV24hmsewYe18J44FSsZCTFhh@vmlREi0tVwPwpqm6NagK@skuC3DlHFrQupCVG/qaYfloG6fW7UnY@SQd3NV7ZzadZ/GwPj8dsELi7XcDXlZCqPRyNjQkQIUB03fzYHfqCtZWni6P6h71wckiK/ATnJZbenBD7pVCextrn0SJ7P@yojgYzv7h8en55DjgcUdv3IwMChsd/IDI7V/OyFYSpFbR0yoD9ByUR7dCGXnhGialn9Cw "Python 3 – Try It Online") -17 bytes thanks to pizzapants184 -1 byte thanks to Kevin Cruijssen [Answer] # [Scala](http://www.scala-lang.org/), 173 bytes ``` l.foreach{x=>def r(c:String):String={val t="""\[([^\[\]]*)\](.)""".r.unanchored;c match{case t(g,h)=>r(c.replaceAllLiterally(s"[$g]$h",g*h.toInt));case _=>c}};println(r(x))} ``` [Try it online!](https://tio.run/##XZDbSgMxEIbvfYo0VklKWWzquWyxXghCvfIym0qazh4kTZZs7MGyz76mq2hrIAS@L/PPMJWSWjZ2/g7KoxdZGAQbD2ZRoUlZot3JSmqkUYymReXJCWoP5k/W8kfpxFAw3P@l1oAYcL@2gnGfOwAxPLAt2dvvf4Id2c7DKe@ezfh5jwTDjnJ5ai2aSxfuZygcHLXUW2SNCoHsP/brInA2vLy6vrm9O7AOlnYFaAkdcfGH55BaB4iHFQgmUw8Ot4o2OtobqfLdJh4vIEWOqPtX7wqT0Z833u0X5WOMccIJnyU8EaJHE0EiGljkog8jjcpDzmKk0FL6kKZkBciTrJ/TeBwyIwellgomWk@L0F9qvSUV5t1MdHPcz3p55O2z8ZSO2tK3eKzqelSGAbw2xJENpXVTN18 "Scala – Try It Online") ### Expanded: ``` l.foreach { x => def remove(current: String): String = { val test ="""\[([^\[\]]*)\](.)""".r.unanchored current match { case test(g, h) => remove(current.replaceAllLiterally(s"[$g]$h", g * h.toInt)) case _ => current } } println(remove(x)) } ``` # Old solution # [Scala](http://www.scala-lang.org/), ~~219~~ ~~215~~ ~~213~~ ~~212~~ ~~199~~ bytes ``` l.foreach{x=>def r(c:String):String={"""\[([^\[\]]*)\](.)""".r.findFirstMatchIn(c).map{x=>val g=x.group(1);val h=x.group(2).toInt;r(c.replaceAllLiterally(s"[$g]$h",g*h))}.getOrElse(c)};println(r(x))} ``` [Try it online!](https://tio.run/##XZBda8IwFIbv/RUxcyMRCbPuWzrmYIKg7GKXaYRYTz9GTEqauTrxt3epG04XOASeJznv4ZSxVLI2i3eIHZrJXCOoHOhliUZFgbattVRIoRBN89KRFtofzMfG8GdpxUAEuHegRoPoc/dpRMBdZgHE4MjuSWN/3ongxLafznjnfM4vusSb4KQvT4xBC2l9ffmP/ZNItUFGx75h8B@7z9zzYHB1fXN7d39kLazMGtAK2uLyDy8gMRYQ9ysQgUwcWLxXtFasMTLOtlX4uIQEWRI/vDmb65T@3uEWYxxxwucRj4To0kgQRj1jliW5Xo5zW7qZdHE20SSmbCWLplmz3TSsWGrNR0H6dNiA7AACypyZaDf0gcxCoWQMI6WmuR9OKrUhJeadVHQy3Eu7GaU7loJ7tS@qBB@yGxZ@NKc0saTyst7V3w "Scala – Try It Online") ### Expanded: ``` l.foreach { x => def remove(current: String): String = { """\[([^\[\]]*)\](.)""".r.findFirstMatchIn(current).map { x => val g = x.group(1) val h = x.group(2).toInt remove(current.replaceAllLiterally(s"[$g]$h", g * h)) }.getOrElse(current) } println(remove(x)) } ``` Where l is the list of strings that we will process. Thanks Kevin Cruijssen for -1 byte Went from 212 to 199 by removing an unused parameter, didn't pay attention. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~39~~ 38 bytes *Saved 1 byte thanks to Shaggy, golfed the regex!* ``` ['\[([^[\]]+)](.)'{.y x:x#~y*}recrepl] ``` [Try it online!](https://tio.run/##LYxRT8JAEITf71dsA3oFI5ErKPJgGh/8E8uSXNu92Nh2yXEK1ehfr9fAwyQ7387MMdjyg6thQL3DFPe4I7qbUbqY6Z9FD@ftefLXz389l54PDQ351imNbyL4aj1lZBRKx7TEcBIyGN49M2Xqcozw8iYzwiSf4PRmj7fzNAIzltGJQGF91HeMLce5pgfpytgyVxdOdbQmW60fnzbPCj238sXQckIPqmAnngHrDshYF9jHVURLpqCspFVFa9bQ1B0fAXVeV3D/ArnTiXwGgtYehn8 "Stacked – Try It Online") Simply recursively replaces a regex `'\[([^[\]]+)](.)'` with the repetition rule. [Answer] # Python 3, ~~155~~ ~~148~~ ~~101~~ 97 bytes ``` def f(x): a=x.rfind('[') if~a:b=x.find(']',a);x=f(x[:a]+x[a+1:b]*int(x[b+1])+x[b+2:]) return x ``` [Try It Online](https://tio.run/##bY3dSgMxEEbv9ynSqt1NV6Wb9TdSEC98iWGEpJ3QgE1KiDb1wldfsy0ouzgwDHznzMzuEDfetVer4@y6NRlmqsRlwdQyXQdj3boqoeQFs@ZbSZ3DU4blpeJPaZltkArrBKpupMa5dTFHum6Q1/0UEvN2oPgRHEvdLvSCqabw6j28qIAtiinnxR/wjrCBuPcoIG4CEbZD4Rj2wklFMRYmz2dwfvEGs3mVoRg/AOM90yrk/srrzfj9@4F5t8qXxT8k7m1Gor25vbt/eBwKgbb@k9iWJrgYEE3GB2JgHUOhTKSQMfutovsB) Thanks to HyperNeutrino and Mego for -47 bytes and user202729 for -4 bytes. [Answer] # [JavaScript](https://developer.mozilla.org/bm/docs/Web/JavaScript) - ~~77~~ ~~75~~ 72 bytes ``` f=a=>a.replace(/(.*)\[([^[]*?)](.)(.*)/,(a,b,c,d,e)=>f(b+c.repeat(d)+e)) ``` Edit: updated regex with Shaggy's recommendation **Snippet:** ``` const test = ["[Foo[Bar]3]2", "[one]1[two]2[three]3", "[three[two[one]1]2]3", "[!@#[$%^[&*(]2]2]2", "[[foo bar baz]1]1", "[only once]12", "[only twice]23456789", "[remove me!]0", "before [in ]2after"]; const f=a=>a.replace(/(.*)\[([^[]*?)](.)(.*)/,(a,b,c,d,e)=>f(b+c.repeat(d)+e)) d.innerHTML=test.map(f).join("<br>"); ``` ``` <p id="d"> ``` [Answer] # [QuadR](https://github.com/abrudz/QuadRS) with the `≡` argument, ~~30~~ 28 bytes ``` \[[^[]+?]. ∊(⍎⊃⌽⍵M)⍴⊂1↓¯2↓⍵M ``` [Try it online!](https://tio.run/##KyxNTCn6/z8mOjouOlbbPlaP61FHl8aj3r5HXc2PevY@6t3qq/mod8ujribDR22TD603ApIgwf//o93y86OdEotijWONuKLz81JjDaNLyvNjjaJLMopSU2ONuSAMkCBEOtYIJKjooBytohoXraalARQwAmmOTsvPV0hKLALiKqAyQ5BxOZUK@XnJQF1GUF5JeSaQa2RsYmpmbmHJFV2UmptflqqQm6oYa8CVlJqWX5SqEJ2ZpxBrlJhWklr0/1HnQgA "QuadR – Try It Online") `\[[^[]+?].` replace "`[`non-`[` stuff`]`character" with `¯2↓⍵M` drop the last two characters of the **M**atch ("`]`digit") `1↓` drop the first character ("`[`") `⊂` enclose to be treated as a whole `(`…`)⍴` **r**eshape to length:  `⌽⍵M` reverse the **M**atch  `⊃` pick the first (the digit)  `⍎` evaluate `∊` **ϵ**nlist (flatten) `≡` repeat until no more changes happen --- The equivalent Dyalog APL function is 47 bytes: ``` '\[[^[]+?].'⎕R{∊(⍎⊃⌽⍵.Match)⍴⊂1↓¯2↓⍵.Match}⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wT1mOjouOhYbftYPfVHfVODqh91dGk86u171NX8qGfvo96ter6JJckZmo96tzzqajJ81Db50HojIAmXqX3Uu/hR50KgaQrq0W75@dFOiUWxxrFG6lwggfy81FjD6JLy/Fij6JKMotTUWGOIBJgDkoAoiTWCSSg6KEerqMZFq2lpAAWNYAZFp@XnKyQlFgFxFVC5Icz4nEqF/LxkoAlGSCIl5ZlAISNjE1MzcwtLiERRam5@WapCbqpirAFYJCk1Lb8oVSE6M08h1igxrSS1SB0A "APL (Dyalog Unicode) – Try It Online") [Answer] # Java 8, ~~250~~ ~~249~~ ~~241~~ 239 bytes ``` s->{for(;s.contains("[");)for(int i=0,j,k;i<s.length();)if(s.charAt(i++)==93){String t="",r=t;for(j=k=s.charAt(i)-48;j-->0;)t+=s.replaceAll(r="(.*)\\[([^\\]]+)\\]"+k+"(.*)","$2");s=k<1?t:s.replaceFirst(r,"$1$3").replace("",t);}return s;} ``` -2 bytes thanks to *@JonathanFrech* (code contains two unprintable ASCII characters now, which can be seen in the TIO-link below). Sigh... Java with regex is so damn limited.. I'll just quote myself from another answer here: > > *Replacing `WWWW` with `222W` is easy in Java, but with `4W` not..* If only Java had a way to use the regex capture-group for something.. Getting the length with `"$1".length()`, replacing the match itself with `"$1".replace(...)`, converting the match to an integer with `new Integer("$1")`, or using something similar as Retina (i.e. `s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1"))` or JavaScript (i.e. `s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))`) would be my number 1 thing I'd like to see in Java in the future to benefit codegolfing.. >.> I think this is the 10th+ time I hate Java can't do anything with the capture-group match.. > > [Quote from here.](https://codegolf.stackexchange.com/a/145775/52210) > > > **Explanation:** [Try it online.](https://tio.run/##jZNfb9sgFMXV134KyrIJ6j9K7G5rR@nWPfStfdkjoRJxcYPtQAQkVRf5s2c3qbu9LZGMhO89v8vhyG7UWmVuqW3z1G6rToWA7pWxm1OEjI3a16rS6GH3itCv6I19RhUZNoEyqPew4AlRRVOhB2QRR9uQ3Wxq5wkLeeVshImBYIEpo7sqTEaGj9MmbZm5Dnmn7XOcE@iamgAxV/42EpMklPOrkm6G8yLHOPU8st2Mhrf8n5RmF5esybKbMaMxgYbXyw6s33Yd8RyT/JxOp4KIx@lUygT2Eidtsq/jFI8KcBZ4ez35Hr/9Ze@MD5F4aE9ORiWm73WCT3AaKeu9jitvUWD9lr2FsFzNOghhyGLtzBNawN2HwIRUdEjyNUS9yN0q5kvoxM4Sm1eQ0J1z4qfyspRgaR/vf8TOajkR8cXJQsS511qWh6G9cAe94bI4Bjr78UGMPj6KT@cEgOIYc6J2Ds2Uh/Ubjpkcc53uFTlbgaviSHV8MSAvyovPX75eXh2GvF64tUYLfSbHB9UzDd@ZRsJYJAtVw88wIP1pv/0D) ``` s->{ // Method with String as both parameter and return-type for(;s.contains("[");) // Loop as long as the String contains a block-bracket for(int i=0,j,k;i<s.length();) // Inner loop over the characters of the String if(s.charAt(i++)==93){ // If the current character is a closing block-bracket: String t="",r=t; // Create two temp-Strings, starting empty for(j=k=s.charAt(i)-48;// Take the digit after the closing bracket j-->0;) // Loop that many times: t+=s.replaceAll(r="(.*)\\[([^\\]]+)\\]"+k+"(.*)","$2"); // Append `t` with the word inside the block brackets s=k<1? // If the digit was 0: t // Replace the input with an empty String as well : // Else: s.replaceFirst(r,"$1$3").replace("",t);} // Replace the word between brackets by `t`, // and remove the digit return s;} // Return the modified input-String as result ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 86 bytes ``` #//.s_:>StringReplace[s,"["~~x:Except["["|"]"]...~~"]"~~d_:>""<>x~Table~FromDigits@d]& ``` [Try it online!](https://tio.run/##RczbTsMwDAbgV/FSmBAqLcs4TlBVCHaNgDvLoLRzt0htM6URG6e8eslGJS4s2Z/tv1FuxY1yulR9BbfQR2madG@z7NlZ3S6feF2rkrGLBQrvt7OHbclrh2H6FiQoSRLvQ@P9IvwIcZNt/YsqavZza5p7vdSuyxc07h9DmsMoBgEnGYgYKoyIYAxpDl8C58bgnbI0JRl2Ak3LNEG3MSTRrSwzTfe@73f@d0Fy8FEe4cHhK46Pj4LJIQUrY6BQNtRnOJ4M0fUHmLYM7/If3EYHkdOz84vLq@u9W27MO0PDIzrdQcGVsQyoWyCpKsdW/PS/ "Wolfram Language (Mathematica) – Try It Online") [Answer] # C, ~~407~~ 368 bytes Thanks to Jonathan Frech for saving bytes. golfed (file bracket.c): ``` i,j,k,l,n;char*f(a,m)char*a;{for(i=0;a[i];++i){a[i]==91&&(j=i+1);if(a[i]==93){k=a[i+1]-48;if(!k){for(l=i+2;l<m;)a[++l-i+j-4]=a[l];a=realloc(a,m-3);return f(a,m-3);}for(l=j;l<i;)a[~-l++]=a[l];for(l=i+2;l<m;)a[++l-4]=a[l];m-=3;n=m+~-k*(i---j--);a=realloc(a,n);for(l=i;l<m;)a[l+++~-k*(i-j)]=a[l];for(m=0;m<k;++m)for(l=j;l<i;)a[l+++m*(i-j)]=a[l];return f(a,n);}}return a;} ``` ungolfed with program: ``` #include <stdlib.h> #include <stdio.h> // '[' = 133 // ']' = 135 // '0' = 48 i, j, k, l, n; char* f(a,m) char*a; { for (i=0; a[i]; ++i) { a[i]==91&&(j=i+1); if (a[i]==93) { k=a[i+1]-48; if (!k) { for (l=i+2; l<m; ) a[++l-i+j-4] = a[l]; a = realloc(a,m-3); return f(a,m-3); } for (l=j;l<i;) a[~-l++] = a[l]; for (l=i+2; l<m; ) a[++l-4] = a[l]; m -= 3; n = m+~-k*(i---j--); a = realloc(a,n); for (l=i; l<m; ) a[l+++~-k*(i-j)] = a[l]; for (m=0; m<k; ++m) for (l=j; l<i;) a[l+++m*(i-j)] = a[l]; return f(a,n); } } return a; } int main() { char c[]="[Foo[Bar]3]2"; char *b; char cc[]="[remove me!]0"; char *bb; char ccc[]="[only once]12"; char *bbb; b=malloc(13); bb=malloc(14); bbb=malloc(14); for (i=0; i<13; ++i) b[i] = c[i]; for (i=0; i<14; ++i) bb[i] = cc[i]; for (i=0; i<14; ++i) bbb[i]=ccc[i]; printf("%s\n", f(b, 13)); printf("%s\n", f(bb, 14)); printf("%s\n", f(bbb, 14)); return 0; } ``` Compiled with gcc 5.4.1, `gcc bracket.c` [Answer] # [Red](http://www.red-lang.org), 147 bytes ``` f: func[t][a: charset[not"[]"]while[parse t[any a some[remove["["copy h any a"]"copy d a](insert/dup v: copy""h to-integer d)insert v | skip]]][]t] ``` Ungolfed: ``` f: func [t][ a: charset [not "[]"] ; all chars except [ and ] while [ parse t [ ; repeat while parse is returning true any a ; 0 or more chars other than [ and ] some [ ; one or more block: remove ["[" copy h any a "]" copy d a] ; remove the entire block, store the ; substring between the [] in h, ; the digit into d (insert/dup v: copy "" h to-integer d) ; makes d copies of h insert v ; and inserts them in place | skip ] ; skip if no match ] ][] ; empty block for 'while' t ; return the modified string ] ``` I started learning Red's Parse dialect only yesterday, so I'm sure my code can be improved further. Parse is incomparably more verbose than regex, but is very clear, flexible and readable and can be freely mixed with the rest of the Red language. [Try it online!](https://tio.run/##ZZDLTsMwEEX3fMXUPFSQENTh2RViwQewHU0lNxmTiMYTOdNUQfx7cJsFqaqRF3PO9bXkyMXwyQUgDX4JfhtyVEK3hLx0sWXFIGqQDO3KasPY7CEoutCDg1Zqxsi1dIwGTS5NDyUcnKFxLcDRvAotR70rtg10qTlxY0pQua2C8hdHKK7HCHTwC@131RARktLQxBQBDwY/RPDdRcrImrN/LIFpgboTsqhlZKZsqg9or8cg2WM9ezvHi8vVCq9u5smlMTDR6EVg7WI6P@ny4vjhTQ8S8tRqT7juqiRs9vD49PzyOtXjb0HNM7qf8DV7iQxYBSDrvHI0wx8 "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes ``` œṡ”]µḢUœṡ”[ẋ€1¦Ṫ©Ḣ$FṚ;® Çċ”]$¡ ``` [Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz5qmBt7aOvDHYtCYdzoh7u6HzWtMTy07OHOVYdWAqVU3B7unGV9aB3X4fYj3SANKocW/v//Pzr6UdskMNoeawKlLQE "Jelly – Try It Online") --- ## Explanation. ``` œṡ”]µḢUœṡ”[ẋ€1¦Ṫ©Ḣ$FṚ;® Helper link 1, expand once. Assume input = "ab[cd]2ef". œṡ Split at first occurence of ”] character "]". µ Start new monadic chain. Value = "ab[cd","2ef". Ḣ **Ḣ**ead. "ab[cd" U **U**pend. "dc[ba" œṡ”[ Split at first occurence of "[". | "dc","ba". ẋ€ Repeat ... 1¦ the element at index **1**... by ... Ṫ Ḣ$ the **Ḣ**ead of the **Ṫ**ail of ... the input list ("ab[cd","2ef") (that is, 2) The command **Ḣ** also pop the head '2'. The remaining part of the tail is "ef". © Meanwhile, store the tail ("ef") to the register. Current value: "dcdc","ba" FṚ **F**latten and **Ṛ**everse. | "abcdcd" ;® Concatenate with the value of the register. "abcdcdef" Çċ”]$¡ Main link. ċ”]$ Count number of "]" in the input. ¡ Repeatedly apply... Ç the last link... that many times. ``` [Answer] # C,381 bytes Compact version: ``` while(1){int t=strlen(i);int a,c=-1;char*w;char*s;char*f;while(c++<t){if(i[c]==']'){int k=c-a;w=calloc((k--),1);memcpy(w,&i[a+1],k);s=calloc((t-c-1),1);memcpy(s,&i[c+2],t-c-2);i[a]=0;int r=i[c+1]-48;if(r==0){f=calloc(t,1);sprintf(f,"%s%s",i,s);}else{f=calloc((t+k),1);sprintf(f,"%s%s[%s]%d%s",i,w,w,r-1,s);}free(i);i=f;break;}else if(i[c]=='[')a=c;}free(w);free(s);if(c>=t)break;} ``` Full version: ``` #include <string.h> #include <stdio.h> #include <stdlib.h> void proceed(char* input) { while(1) { int t=strlen(input); int start,cursor=-1; char* word; char* suffix; char* final; while(cursor++<t) { if(input[cursor]==']') { int wordlength = cursor-start; word=calloc((wordlength--),sizeof(char)); memcpy(word, &input[start+1], wordlength ); suffix=calloc((t-cursor-1),sizeof(char)); memcpy( suffix, &input[cursor+2], t-cursor-2 ); input[start]='\0'; int rep=input[cursor+1]-'0'; if(rep==0) { final=calloc(t,sizeof(char)); sprintf(final,"%s%s",input,suffix); } else { final=calloc((t+wordlength+5),sizeof(char)); sprintf(final,"%s%s[%s]%d%s",input,word,word,rep-1,suffix); } free(input); input=final; break; } else if(input[cursor]=='[') start=cursor; } free(word); free(suffix); if(cursor>=t)break; } } int main() { char* input=calloc(256,sizeof(char)); sprintf(input,"a[[toto]2b]2[ana]3"); printf("in : %s\n",input); proceed(input); printf("out: %s\n",input); return 0; } ``` ]
[Question] [ Take a non-empty matrix / numeric array containing positive integers as input. Return, in this order, the sums of the first row and column, then the second row and column and continue until there aren't any more rows or columns. Suppose the input is: ``` 2 10 10 2 4 9 7 7 2 9 1 7 6 2 4 7 1 4 8 9 ``` Then the output should be: ``` 45, 33, 16, 17 ``` Because: `2+9+1+7+10+10+2+4=45, 7+7+1+7+2+9=33, 6+4+2+4=16, 8+9=17`. ## Test cases: Test cases are on the following format: ``` Input --- Output ``` ``` 5 --- 5 .......... 1 4 ---- 5 .......... 7 2 --- 9 .......... 8 3 7 10 3 7 10 1 10 7 5 8 4 3 3 1 1 6 4 1 3 6 10 1 2 3 8 2 8 3 4 1 --- 62 40 33 18 .......... 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 --- 320 226 235 263 135 26 20 .......... 7 10 1 4 4 2 6 3 4 1 4 10 5 7 6 --- 34 20 20 ``` As arrays: ``` [[5]] [[1,4]] [[7],[2]] [[8,3,7,10,3,7,10,1],[10,7,5,8,4,3,3,1],[1,6,4,1,3,6,10,1],[2,3,8,2,8,3,4,1]] [[30,39,48,1,10,19,28],[38,47,7,9,18,27,29],[46,6,8,17,26,35,37],[5,14,16,25,34,36,45],[13,15,24,33,42,44,4],[21,23,32,41,43,3,12],[22,31,40,49,2,11,20]] [[7,10,1],[4,4,2],[6,3,4],[1,4,10],[5,7,6]] ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in each language wins. [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` &n:w:!XlX:GX:1XQ ``` [Try it online!](https://tio.run/nexus/matl#@6@WZ1VupRiRE2HlHmFlGBH4/3@0kYKhAQgZKZhYWyqYA6GRgqW1IZA2A4uZKxgqmChYKFjGAgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#NY@9bgJBDIT7PMXQhArp7P29c5uKLlKKlRASD4BSJo9/fAui8Xq845nxbZz3z9/tfzuM@9jOY7Pxvf8djqfTcXz97Jdy/biYMrWFU7uSmmx5PxaUpqKuzCzNgSq90dcXw2m7XHOXD1QS@6tyhzUZq7xHQqEhtcogN/kauSIBCVCVilKLIkOiykEY4lTCcC1yIPqunJXDTU4cEOmfuTycIKBFGUMZjGXe9QrJkjzqjMgFeCx4NdXrAw). ### Explanation Consider, as an example, the input ``` 2 10 10 2 4 9 7 7 2 9 1 7 6 2 4 7 1 4 8 9 ``` The code `&n:w:!Xl` builds the column vector `[1; 2; 3; 4]` and the row vector `[1 2 3 4 5]`. Then `Xl` computes the minimum element-wise with broadcast, which gives the matrix ``` 1 1 1 1 1 1 2 2 2 2 1 2 3 3 3 1 2 3 4 4 ``` `X:` linearizes this matrix (in column-major order) into the column vector `[1; 1; 1; 1; 1; 2; 2; ... ; 4]`. This vector and the linearized input matrix, obtained as `GX:`, are passed as inputs to the `accumarray(... @sum)` function, or `1XQ`. This computes the sum of the second input grouped by values of the first input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ŒDS ``` [Try it online!](https://tio.run/nexus/jelly#@390kkvw////o6MVLHQUjHUUzHUMDZAYhrE6XArRIJa5joKpDkiRCVjaGCanYKijYAYWNQSLmiHpUzACCwE1GelAzQepi40FAA "Jelly – TIO Nexus") ## How it works ``` ŒDS ŒD diagonals S vectorized sum ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~23~~ 18 bytes ``` {[{(:+\z}h;]2/::+} ``` Anonymous block expecting the argument on the stack and leaving the result on the stack. [Try it online!](https://tio.run/nexus/cjam#K6z7Xx1drWGlHVNVm2Eda6RvZaVd@7@u4H90tIKFAhAYgwhzIDY0wMI1jOWKhrBAYgqmIAKszQSu2BimTsEQxDKDyxrCZc1QzFMwgkuAjTKCs4wRemNjAQ "CJam – TIO Nexus") ### Explanation ``` [ e# Begin working in an array. { e# Do: (:+ e# Remove the first row of the matrix and sum it. \z e# Bring the matrix back to the top and transpose it. }h e# While the matrix is non-empty. ; e# Discard the remaining empty matrix. ] e# Close the array. 2/ e# Split it into consecutive pairs of elements (possibly with a singleton on the end). ::+ e# Sum each pair. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 11 bytes ``` [ćOˆøŽ]¯2ôO ``` [Try it online!](https://tio.run/nexus/05ab1e#Fc25DQJBEETRhL4xfewcUWwAo0kHwsHBwMFhwSKopfD6P5XU53xf9@/leHye63Xz476f55xRiEF2DCvYwPtiRicbjYF1vOFDmJWKhspKbEQTblhiFVcnUclNaoFtuCBIJ5OUuuFBqI3UgflfnVAXUs8xbcpaPw "05AB1E – TIO Nexus") **Explanation** ``` [ Ž ] # loop until stack is empty ć # extract the head Oˆ # sum and add to global list ø # transpose ¯ # push global list 2ô # split into pairs O # sum each pair ``` [Answer] ## JavaScript (ES6), 60 bytes ``` a=>a.map((b,y)=>b.map((c,x)=>r[x=x<y?x:y]=~~r[x]+c),r=[])&&r ``` Naive solution, may be a better way. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~63~~ 60 bytes ``` @(A)(@(L)sum(triu(A,1)')(L)+sum(tril(A))(L))(1:min(size(A))) ``` [Try it online!](https://tio.run/nexus/octave#XVK9TsQwGNv7FNlIBEPz0/YOhHS38wahI0MljoFwCy9f8tnNV5UlSmzX8ee0vL6vF3t19mLfXLnf7M/3crfXJ@8eXEUeN@izSuTsrH@@LV@2LL8fArm12JyDMcb3bTFyNGnu8lk2ky7AzxX3Co0HPSCQSZYT9bPrumIHV5f6ZZqxmV4C8Zypi82TGf4dvdza67WD2icVx6ZjglFZr@x48GPuqFZBd3H/dm4pI2OhkgQVjTc/4OFUbSNzISfTGpCel7BJaTEhIoPyXk8SSMSMcZKg2HoGYuMkOTwnHaQhdgAykOQofCEgeKiA6IG9keSzAdmqDCJkRyQxacIwLMvTpteSjg@WtEaxGvdm2y@UIK@nYf@hqtf6Bw "Octave – TIO Nexus") The answer for this matrix: ``` 2 10 10 2 4 9 7 7 2 9 1 7 6 2 4 7 1 4 8 9 ``` is the vector of row sums of its upper triangular part: ``` 0 10 10 2 4 0 0 7 2 9 0 0 0 2 4 0 0 0 0 9 ``` plus the vector of column sums of its lower triangular part: ``` 2 0 0 0 0 9 7 0 0 0 1 7 6 0 0 7 1 4 8 0 ``` which is precisely what my answer is computing. [Answer] ## Mathematica, 60 bytes *Inspired by [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/121443/66104).* ``` Pick[#,Min~Array~d,n]~Total~2~Table~{n,Min[d=Dimensions@#]}& ``` Explanation: `Min~Array~Dimensions@#` constructs a matrix like the following: ``` 1 1 1 1 1 1 2 2 2 2 1 2 3 3 3 1 2 3 4 4 ``` Then `Pick[#,...,n]~Total~2` picks out the entries of the input matrix corresponding to the number `n` in the weird matrix above, and sums them. Finally `...~Table~{n,Min[d=Dimensions@#]}` iterates over `n`. This is 1 byte shorter than the naïve approach: ``` {#[[n,n;;]],#[[n+1;;,n]]}~Total~2~Table~{n,Min@Dimensions@#}& ``` [Answer] ## Haskell, ~~50~~ 49 bytes ``` f(a@(_:_):b)=sum(a++map(!!0)b):f(tail<$>b) f _=[] ``` [Try it online!](https://tio.run/nexus/haskell#ZYzNCoMwEITvPsUKHhLcg1FrgtTS9whLSCiBQP2htc@fbile2tPwfTNMjsJfhRudHIOcnq9Z@Lqe/SbKspFBjlHsPt3P1SXIIoKbLOXZpwUmuK0FwPZIyw4VRLBWYU/04zShbf@swQ41quYIxSsOjSc02LPtvgoHJsU0HKuWwWCLnweuiPIb "Haskell – TIO Nexus") If there's at least one row with at least one element, the result is the sum of the first row and the heads of all other rows followed by a recursive call with the tails of all other rows. In all other cases, the result is the empty list. Edit: Ørjan Johansen saved a byte. Thanks! [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~64~~ 52 bytes *Thanks to @StewieGriffin for saving 1 byte!* ``` @(x)accumarray(min((1:size(x))',1:rows(x'))(:),x(:)) ``` This defines an anonymous function. [Try it online!](https://tio.run/nexus/octave#NU/LasMwELz3K@YWCYLxrp72Ush/hBxMaCCHtOAQ6vbn3XGVXKQZaXZm9oJ3dF23Htzip/P5cZvmefpxt@unczLer78f/PC7vYzz1/fdLTvv3ej3Cw@/XtwxnfwbL0FsoJg2UBFQIP3rEuNRkFAR@Ra2B2RiIc5NoYQVim2WH80o0GJArBRuogFaLdCk0G2AUF@gg8VMF4pIMkJCKJYgdMlQMmYyLJkwOEFJGaGIEdFUoGxExjX@q6kpu5D1iAyEUNE/F2xVOQe1vBXlHozpGVeQT379Aw) ### Explanation The code is similar to my [MATL answer](https://codegolf.stackexchange.com/a/121443/36398) (see explanation there). Two bytes have been saved using `1:size(x)` instead of `1:size(x,1)`, exploiting the fact that `1:[a b]` behaves the same as `1:a`. Also, one byte has been saved using `1:rows(x')` instead of `1:size(x,2)`, thanks to Stewie. [Answer] # [R](https://www.r-project.org/), ~~63~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes *Edit: -4 bytes, and then -2, and then -1 more, thanks to Robin Ryder* ``` function(m,`+`=sum)while(+m)show(m+-{m=m[-1,-1,drop=F]}) ``` [Try it online!](https://tio.run/##jZBBCoMwEEX3cwxXCY7QaKzpwm0v0RYU26JgEomKhdKzp6NScNGFTBKG/D@fvDjfucYMlW2dnXL/HE01NNYwjUVY5P2o@VQ37YOFmve1nZgOo7fO9SUSSOvubJefbx/u6a4cXPNiFYMYTygwQxAHOjPq1@6IEkmcSyFIctHmKDls3sA0h6ocWHA1AQfY5KYcxU6roFCMd5ozcu5OBoXEIggBkgUpQcgwJRK1UKqfJklRs5asJtKSeZS@QOBS/8j9Fw "R – Try It Online") Repeatedly removes the first row & column (using negative indexing: `m[-1,-1]` is `m` without the first row & column), prints the difference between the sum of `m` and this, and keeps going if there's anything left. [R](https://www.r-project.org/) is very well-suited to this type of vectorized matrix operation, so this approach comes-out significantly shorter than [a looping approach](https://codegolf.stackexchange.com/a/121591/95126). [Answer] # oK, ~~19~~ 18 bytes -1 byte [thanks to coltim](https://codegolf.stackexchange.com/questions/121425/sum-of-first-row-and-column-then-second-row-and-column-and-so-on/121434?noredirect=1#comment504604_121434). ``` 1_--':+//'(1_+1_)\ ``` [Try it online!](https://tio.run/##XVG7DoMwENvvK7KRCBDcJTz7K5XYWBj6/xMFG1LUJSH2xbHNVn@2fV9nXeq6mMumKbwupS7hva@F9@ac0/Ze3Hl0SaZzG/ICdBLNQP@YBQAqncuI2SBVd8wn8dXwqiyIJxFvCT73d1ThDskuq6U8GjnF5/rMaeb6hxYNxixj@Sv@bh7OIq0gcwJPwUsHuI0S6QXe6NCBUoqzqEkSbNEcX1NSQCJSxUEYT2mCdZJiWGY7KmRiUEaK5lk@kKNlg2FjR6T4R4BctZkYGyGFdAkRWI1SpA1h/wI "K (oK) – Try It Online") Explanation: ``` (1_+1_) /a function that strips the top and leftmost rows of a matrix \ /apply this function as many times as possible, / saving each result as one element of a list +//' /for each result, get the sum of all numbers --': /subtract every right value from every left value 1_ /remove the extra 0 ``` [Answer] ## [Julia](https://julialang.org/), 62 bytes ``` f=x->1∈size(x)?sum(x):(n=f(x[2:end,2:end]);[sum(x)-sum(n);n]) ``` Works recursively by summing up the whole matrix and then subtracting off the sum of the next block. Probably not the most effective approach, but nicely intuitive. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` [ćOsø.g<NQ#])2ôO ``` [Try it online!](https://tio.run/nexus/05ab1e#Fc27DQIxEEXRYoiQrlaej38SNbAithxvARRBQwTkS19myOYePWnW@L725/nZjtv9cZlXPd/7WmNYwjreECQhHW2TYQ2vVDrS0Ir2QC8UYhhZsIzVwIw4UtBoxwqeQ8WQjAYYrrjjoSqoYdGCx4HoXxWLTng8R2KT5vwB "05AB1E – TIO Nexus") or [Try all tests](https://tio.run/nexus/05ab1e#NY9NCgIxFIMP40oIMn39HfAMDq5L1x5AEDyBF3LhfrzX@LUym74mTZO8x3Or39dyXz@n2/lyPbSjre9l01Zrja2pVqcwZuawcSvyynLTPhwkIyuqKMD6P6UEcqC0qwxQZOoOPA03j8@sUFB21Swr0B6njOUsx4csmyFDwgohMMlH@d4pymGVZGDCyYw9nA5RBkGSKQS2IN/JqAdmq9HTOkst8KRAuByaqbX2Aw "05AB1E – TIO Nexus") ``` [ # Start loop ć # Extract first element O # Sum sø # Transpose the input array (without the first N rows and columns) .g<NQ # Push if (stack height - 1 == loop count) #] # If they were equal break )2ô # Break stack into chunks of 2 O # Sum the chunks ``` [Answer] # Vim, ~~66~~, 52 bytes ``` qq^f j<C-v>}dkV}Jo<esc>p@qq@q:%s/\v> +</+/g|%norm C<C-v><C-r>=<C-v><C-r>"<C-v><cr><cr> ``` [Try it online!](https://tio.run/nexus/v#JY8xC8JADEb3jB26uAShU4f2ktS2olJw8wc4iZMoKFpPwcn@9mq/3PA43gvHZYzxeOZrOpxu@2HXz55djF1cZu/i8Nlwviry4vLNHv3rzts0WafJPCUaRy35f7SdaM1EDgB8gJeGFMlqDDiRArzASEu2QHIiBU8wWoE1MS7BQCTxBKMwVlFQDCCJJxgTEIaNBB8WJPUEYzDsjwgJknrCdoYVGD74I@UP "V – TIO Nexus") The wrong tool for the job... [Answer] # [Perl 6](http://perl6.org/), ~~63~~ 55 bytes ~~`{($_ Z [Z] $_).kv.map(->\a,\b{b.flatmap(*[a..*]).sum -b[0;a]})}`~~ ``` {($_ Z [Z] .skip).kv.map({$^b.flatmap(*[$^a..*]).sum})} ``` * `$_` is the matrix input to the anonymous function * `.skip` is the input matrix with its first row removed * `[Z] .skip` is the transpose of the input matrix with its first row removed; that is, the transpose without its first column * `$_ Z [Z] .skip` zips the input matrix with its transpose-sans-first-column, producing a list `((first-row, first-column-sans-first-element), (second-row, second-column-sans-first-element), ...)` * `.kv` prefixes each pair with its index * `map({...})` maps over the the pairs, using a function which takes its first argument (the index) in `$^a` and its second (the row/column pair) in `$^b` * `$^b.flatmap(*[$^a..*]).sum` strips off the first `$^a` elements of each row/column pair, then sums all the remaining elements After some thought I realized that stripping off the first column of the transpose before zipping was equivalent to subtracting the doubly-contributing diagonal elements, as in my first solution. That let me delete that subtraction, and using each argument to the mapping function only once made the `{...$^a...$^b...}` method of passing arguments to an anonymous function more efficient than the original `-> \a, \b {...a...b...}`. [Answer] # Java 10, ~~248~~ ~~245~~ ~~227~~ ~~223~~ ~~219~~ 218 bytes ``` a->{int l=a.length,L=a[0].length,b[][]=new int[l][L],i,j,x=0,s;for(;++x<l|x<L;)for(i=l;i-->x;)for(j=L;j-->x;)b[i][j]=x;var r="";for(;x-->0;r=s>0?s+" "+r:r)for(s=0,i=l*L;i-->0;)s+=b[i/L][i%L]==x?a[i/L][i%L]:0;return r;} ``` -8 bytes thanks to *@ceilingcat* [Try it online.](https://tio.run/##nVHLcptAELzrK7ZU5SoURgosT3m98g8QX3KkOKxkbC/ByLUghZTCtysNsmIRn6KLUE/vzHT3FGqv5sXjj@OmVHXNvildHSaM6arJzZPa5Oyhh4x9b4yuntnGApNmacbUTIDoJvipG9XoDXtgFZPsqOarAx6xUqpFmVfPzQslUqVOdkbrvl9W@c9@S1pmaZKRpoJa6VAtnrbGErbd3pW/27tEzHqsZSn0fL5qT7CQiShOcJ3qLC0y2Yq9MszI6fQ0oAXtCCPrlXNf21M2tc2tGZprbMG8L8kw0RGz2paY8jXJUn2TZFK29@oD3mJI3uxMxYzojqJ3@7Zbl3D7bnq/1Y/sFalZp4SGZN4j@1U3@etiu2sWb6CasrKqxcY6G0cIh7//D0HXzYZE/7PPJf/KzqijD8CvHBKTRxG5zvnjXg4FjiigmHzQ3j8chSi7KIef@jiqMXHqh@PNldI8iFqSH2NJv2BJPL5c4kFWBH1LcrErIr68ZP0QutCKekheQN4orYBc6AqJg4A3OAlG3uA1IA4G@jn5Pm50ac8ljjxA4HhDMHxEwz4Ih3xIJhePnWsv/ClZKKHRsrCPeHwXOHPGZiMKzwq6SXf8Aw) **General explanation:** Let's say the input array has dimensions of 4x6. The first part of the code will create a temp matrix and fills it as follows: ``` // 1. Fill the entire array with 0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // 2. Overwrite the inner part with 1 (excluding the first row & column): 0 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 // #. Etc. until we are left with this: 0 0 0 0 0 0 0 1 1 1 1 1 0 1 2 2 2 2 0 1 2 3 3 3 ``` And in the second part of the code it will loop over this temp matrix, and sums all values of the input-matrix for each of the distinct numbers in the temp matrix. **Explanation of the code:** ``` a->{ // Method with int-matrix parameter and String return-type int l=a.length, // Amount of rows L=a[0].length, // Amount of columns b[][]=new int[l][L], // New temp matrix to fill as explained above i,j,x=0,s; // Some temp integers //This is the first part of the code mentioned above: for(;++x<l|x<L;) // Loop `x` over the rows or columns (whichever is larger): for(i=l;i-->x;) // Inner loop over the rows: for(j=L;j-->x;) // Inner loop over the cells of this row: b[i][j]=x; // Set the value of the current cell to `x` //This is the second part of the code mentioned above: var r=""; // Result-String, starting empty for(;x-->0 // Loop over the unique numbers in the temp matrix: ; // After every iteration: r=s>0?s+" "+r:r) // If the sum is larger than 0: append it for(s=0, // Reset the sum to 0 i=l*L;i-->0;) // Inner loop over the cells: s+=b[i/L][i%L]==x? // If the current cell of the temp-matrix contains `x`: a[i/L][i%L]:0; // Add the input's value at this position to the sum return r;} // Return the result-String ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣ;Ḣ€SṄȧßS¿ ``` A full program that prints the values **[Try it online!](https://tio.run/nexus/jelly#@/9wxyJrIH7UtCb44c6WE8sPz3c7tP/////R0QoWOgrGOgrmOoYGSAzDWB0uhWgQy1xHwVQHpMgELG0Mk1Mw1FEwA4sagkXNkPQpGIGFgJqMdKDmg9TFxgIA)** ### How? ``` Ḣ;Ḣ€SṄȧßF¿ - Main link: list of lists a Ḣ - head a (pop the first row and yield it, modifying a) Ḣ€ - head €ach (do the same for each of the remaining rows) ; - concatenate S - sum (adds up the list that contains the top row and left column) Ṅ - print that plus a linefeed and yield the result ¿ - while: - ... condition: F - flatten (a list of empty lists flattens to an empty list which is falsey) - ... body: ß - call this link with the same arity (as a monad) i.e. Main(modified a) ȧ - logical and (when the sum is non-zero gets the modified a to feed back in) ``` [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes ``` f=lambda m:[reduce(lambda x,y:x+y[i],m[i:],sum(m[i][i+1:]))for i in range(min(len(m),len(m[0])))] ``` [Try it online!](https://tio.run/nexus/python2#RYrRCsIwDEV/JY8ty8MqQ13BLwl5qK6VwFqlOti@vnZVEHLJvYdTwmV28To5iJayn5abVz@w4mbXbiNhjCSW8bVEVRuTdMay1uGRQUASZJfuXkVJavZJRY3tUV8dzeWZJb0hKKIDgum/qXVgBBoRTu0qGHdg2jr@jboqGxDOu8G6fAA "Python 2 – TIO Nexus") [Answer] # Pyth, ~~16~~ 15 bytes ``` .es+>b+1k>@CQkk ``` Takes a python-style array of arrays of numbers, returns an array of sums. [Try it!](https://pyth.herokuapp.com/?code=.es%2B%3Eb%2B1k%3E%40CQkk&input=%5B%5B8%2C3%2C7%2C10%2C3%2C7%2C10%2C1%5D%2C%5B10%2C7%2C5%2C8%2C4%2C3%2C3%2C1%5D%2C%5B1%2C6%2C4%2C1%2C3%2C6%2C10%2C1%5D%2C%5B2%2C3%2C8%2C2%2C8%2C3%2C4%2C1%5D%5D&debug=0) ### Explanation ``` .es+>b+1k>@CQkk .e Q # Enumerated map over the implicit input (Q); indices k, rows b CQ # Take the transpose @ k # The kth column > k # cut off the first k elements >b+1k # cut off the first k+1 elements of the rows, so (k,k) isn't counted twice s+ # add the row and column together and sum ``` [Answer] # GNU APL 1.7, 123 bytes Solution requires two functions: one creates a global array and the calls the second, which recursively appends the sums to that array. ``` ∇f N R←⍬ g N R ∇ ∇g N →2+2×0∈⍴N R←R,(+/N[1;])+(+/N[;1])-N[1;1] g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N] ∇ ``` `∇` begins and ends the function. Both `f` and `g` take tables as arguments (essentially 2D arrays). These can be created with `X←rows cols ⍴ 1 2 3 4...`. `R←⍬` assigns an empty vector to global variable `R`. `g N` calls the second function with the same argument given to the first. `⍴N` gives the dimensions of `N`; when one of the dimensions is zero, there are no more rows/columns to add up. `0∈⍴N` returns 1 if there is a zero in the dimensions. `→2+2×0∈⍴N` branches to line number 2 plus 2 times the return value of the `∈` function: if there is no zero, `∈` returns 0 and the function branches to line 2 (the next line). If there *is* a zero, `∈` returns 1 and the function branches to line 4 (the end of the function, so `return` essentially). `/` is the reduce operator. It applies the left argument, which is an operator (`+`) to every element in the list given as the right argument. `N[1;]` gives the entire first row of the table and `N[;1]` gives the first column. `(+/N[1;])+(+/N[;1])-N[1;1]` sums the first row and column and subtracts the value in the upper left corner because it gets added both in the column sum and the row sum. `R←R,...` appends the newly calculated value to the global vector `R`. The function then calls itself (recurse until no more rows or columns). The `⊃` pick operator obtains the specified element from the list. `1⊃⍴N` gives the number of rows, `2⊃⍴N` the number of columns. `⍳` gives all numbers from 1 to the specified number. The `↓` drop operator removes elements from the beginning of the list. If you give multiple indices when accessing elements from a table or vector (e.g. `N[1 2 3]`), APL accesses each one. Therefore, `1↓⍳1⊃⍴N` gives the indices of each row excluding the first one (`2, 3, 4, ..., N`) and `1↓⍳2⊃⍴N` gives a similar vector but for the columns. `g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N]` calls the function again but without the first row or column. [Answer] # Python + NumPy, ~~75~~ 66 bytes Input is a 2D numpy array. ``` lambda L:[sum(L[i,i:])+sum(L[i+1:,i])for i in range(min(L.shape))] ``` [**Try it online**](https://tio.run/##bZBLboQwEET3cwovIVOKsPEHkHIDbkBYEGXIWAofeZgFpydlEjYRK6uqu6tfe16X@zSqrQ/TIMbnMK/CD/MUlpdL//a@fXfDx2cn6qp5PIekbjx81abXP3GVFXyb9lMQXvhRhG78uiWDH5P69XHv5luattsc/LiIPulC6NakaUzbpunlvyuhT33XolGnlQI5HGR2PJKdfBwMCmi6@a8FSyWp7NGlKAooxASWTtNz5pbQBSfjVAlVcDJnsuOKEpIBDqqkqS2j2UhpkRvkkdlAMtpCUROGDCbCkMlA0eBmBa15NXkkFHGp@Qs7t4ouMakzaC6HZE92/kPHWQxDHLTxrP1yEmQ7i4ONs9sP) *-9 bytes by Black Owl Kai* [Answer] # PHP, 76 Bytes ``` <?foreach($_GET as$k=>$v)foreach($v as$n=>$i)$r[min($k,$n)]+=$i;print_r($r); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjY420jE0ACEjHZNYLp1oSx1zIDTSsQRxDIFMM5iMuY6hjomOBVAm1vp/Wn5RamJyhgbYFIXEYpVsWzuVMk24cBlILA8olqmpUhSdm5mnoZKto5KnGattq5JpXVCUmVcSX6ShUqRp/f8/AA "PHP – TIO Nexus") [Answer] ## Mathematica, 116 bytes ``` l=Length;If[l@#==1||l@#[[1]]==1,Total@Flatten@#,Total/@Flatten/@Table[{#[[i]][[i;;]],#[[All,i]][[i+1;;]]},{i,l@#}]]& ``` Input form > > [{{5}}], [{{1},{4}}], [{{7,2}}] or [{{....},{....}...{....}}] > > > [Answer] ## Clojure, 98 bytes ``` #(vals(apply merge-with +(sorted-map)(mapcat(fn[i r](map(fn[j v]{(min i j)v})(range)r))(range)%))) ``` Iterates over the input with row and column indexes (in a very verbose manner), creates a hash-map with the minimum of `i` and `j` as the key, merges hash-maps with `+` into a sorted-map, returns values. [Answer] # R, 102 bytes ``` function(x)`for`(i,1:min(r<-nrow(x),k<-ncol(x)),{dput(sum(x[,1],x[1,-1]));x=matrix(x[-1,-1],r-i,k-i)}) ``` returns an anonymous function; prints the results to the console, with a trailing newline. I probably need a different approach. Iterates over the minimum of the rows and columns; prints the sum of `x[,1]` (the first column) and `x[1,-1]` the first row except for the first entry, then sets `x` to be a matrix equal to `x[-1,-1]` (i.e., `x` excluding its first row and column). Unfortunately, simply setting `x=x[-1,-1]` causes it to fail in the case of a square matrix, because when `x` is 2x2, the subsetting returns a vector rather than a matrix. [Try it online!](https://tio.run/nexus/r#NYzBCoMwEETv@Yocd2EDbq0W2volIiiWQLAmEiMNlH67TaS9zAxvmNHNrjc7BuMsROy18z0Y4utsLPi7st69EqcpxdE9U0R6P5YtwLrNEFvijmLLpLhDvMVmHoI3MRXqYOSVoUkZ/OAemwC/eh0HC0glVWmk06m4SCm5kFnFOdshJ1FnKw8g@M@5EFXOeSTr/Qs) [Answer] # Java 7, ~~280~~ 276 bytes ``` import java.util.*;String d(ArrayList l){String r="";for(;l.size()>0&&((List)l.get(0)).size()>0;l.remove(0))r+=s(l)+" ";return r;}int s(List<ArrayList<Integer>>l){int s=0,L=l.size(),i=1;for(;l.get(0).size()>0;s+=l.get(0).remove(0));for(;i<L;s+=l.get(i++).remove(0));return s;} ``` [Try it here.](https://tio.run/nexus/java-openjdk#tVPLbtswELz7KwgfArJaCBL1NGQZ6LGAe8qx6IGNWYOBHgZJO0gFfbu7lGI77SU8xLpIJGc4s7Mr1R56bcmzOInwaFUTfqkWT40whnwXqhvOj1arbk929KvW4nWrjCUNG952db1cVr97TasmNOqPpGwTPTxQ6mCsCffS0oix6xGitGz7k3S7OqgNbViwJMtKS3vUHdHVqDpLzMRfXwXX3zor91JvNqg8AeoItvVFElQdX0zMijdBE9TXzZv0jFbr7e1cBcE/iDdHphrPhByOvxr1RIwVFl@nXu1Ii@HQOYUfP4lgw4Lg4yIjLalJJ1@mBWXVdPD4aqxsw/5owwNybNPRNtxRB7uWSdkwiN3/m9OXCYWZVhlDb@PIPvnaGNL7XFy4az8C8ftol5BAAXF0ecU@XhBXQAYlpEhLPDmQIzxGeO6twxFdAgdnMp0pn59AgrWvIC3Rm/O1Al76eEuw@gJjWEGMFgvgKx9WmmP5KIX4HJIMEq/eZxBj@TnwzOWNOWZeiWNnMuDYI0yPQ5rO8/th6DFwVEECDvzUXu5Fw2YhIYIUE4QYL4nu9Ld4jw8WDF7eczdffkOMfYj8WlZA/j6AcTGe/wI) Alternative approach compared to [my previous answer](https://codegolf.stackexchange.com/a/121559/52210) with arrays, which is still shorter than this one in the end (so I kinda wasted time trying this alternative approach). **General explanation:** Inspiration from [*@Riley*'s amazing 05AB1E answer](https://codegolf.stackexchange.com/a/121440/52210) This answer uses a List and after every sum is calculated it removes the first column and first row from the List-matrix, like this: ``` // Starting matrix: 7 10 1 4 4 2 6 3 4 1 4 10 5 7 6 // After first iteration (result so far: "34 "): 4 2 3 4 4 10 7 6 // After second iteration (result so far: "34 20 "): 4 10 6 // After last iteration, result: "34 20 20 " ``` **Explanation of the code:** ``` import java.util.*; // Required import for List and ArrayList String d(ArrayList l){ // Method with ArrayList parameter and String return-type String r=""; // Return-String for(;l.size()>0&&((List)l.get(0)).size()>0; // Loop as long as the list still contains anything l.remove(0)) // And remove the first row after every iteration r+=s(l)+" "; // Append the sum to the result-String // End of loop (implicit / single-line body) return r; // Return result-String } // End of method int s(List<ArrayList<Integer>>l){ // Separate method with List-matrix parameter and integer return-type int s=0, // The sum L=l.size(), // The size of the input list i=1; // Temp integer for(;l.get(0).size()>0; // Loop (1) over the items of the first row s+=l.get(0). // Add the number to the sum remove(0) // And remove it from the list afterwards ); // End of loop (1) for(;i<L; // Loop (2) over the rows s+=l.get(i++). // Add the first number of the row to the sum remove(0) // And remove it from the list afterwards ); // End of loop (2) return s; // Return sum } // End of separate method ``` [Answer] # Python, 93 bytes Similar to mbomb007's answer, but without NumPy ``` f=lambda m:[sum(m[k][k:])+sum(list(zip(*m))[k][k+1:])for k in range(min(len(m),len(m[0])))] ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -n`, 48 bytes ``` @,=eval;say sum@{shift@,},map{shift@$_}@,while@, ``` [Try it online!](https://tio.run/##NY5BCsIwFESv4sLlVJLWtKGlkAPo0lUpkkWkgbQNJioivbrxi3b1ePM/w3hzdSIlhdbctWuCfm7CbVSvMNhLVFgwav@X7XlReAzWGYWUOokCFThbwXt0hAoCEntKi1@EkoyTletXTiKR49tAp/49@2jnKaTsKHaMM@LBhljXp2hdS3NSpqcP "Perl 5 – Try It Online") ]
[Question] [ There are 97 [ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) characters that people encounter on a regular basis. They fall into four categories: 1. Letters (52 total) ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` 2. Numbers or Digits (10 total) ``` 0123456789 ``` 3. Symbols & Punctuation (32 total) ``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` 4. Whitespace (3 total) Space , tab `\t`, and newline `\n`. (We'll treat newline variants like `\r\n` as one character.) For conciseness, we'll call these categories L, N, S, and W respectively. Choose any of the 24 permutations of the letters `LNSW` you desire and repeat it indefinitely to form a programming template for yourself. For example, you might choose the permutation `NLWS`, so your programming template would be: ``` NLWSNLWSNLWSNLWSNLWS... ``` **You need to write a program or function based on this template, where:** 1. Every `L` is replaced with any letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`). 2. Every `N` is replaced with any number (`0123456789`). 3. Every `S` is replaced with any symbol (`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`). 4. Every `W` is replaced with any whitespace character ( `\t\n`). Basically, your code must follow the pattern ``` <letter><number><symbol><whitespace><letter><number><symbol><whitespace>... ``` as the question title suggests, except you may choose a different ordering of the four character categories, if desired. **Note that:** * Replacements for a category can be different characters. e.g. `9a ^8B\t~7c\n]` validly conforms to the template `NLWSNLWSNLWS` (`\t` and `\n` would be their literal chars). * There are no code length restrictions. e.g. `1A +2B -` and `1A +2B` and `1A` and `1` all conform to the template `NLWSNLWSNLWS...`. **What your template-conformed code must do** is take in one unextended [ASCII](http://www.asciitable.com/) character and output a number from 0 to 4 based on what category it is a member of in the categorization above. That is, output `1` if the input is a letter, `2` if a number, `3` if a symbol, and `4` if whitespace. Output `0` if the input is none of these (a [control character](https://en.wikipedia.org/wiki/ASCII#Control_characters)). For input, you may alternatively take in a number 0 to 127 inclusive that represents the code of the input ASCII character. The input (as char code) and output pairs your code must have are precisely as follows: ``` in out 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 4 10 4 11 0 or 4 12 0 or 4 13 0 or 4 14 0 15 0 16 0 17 0 18 0 19 0 20 0 21 0 22 0 23 0 24 0 25 0 26 0 27 0 28 0 29 0 30 0 31 0 32 4 33 3 34 3 35 3 36 3 37 3 38 3 39 3 40 3 41 3 42 3 43 3 44 3 45 3 46 3 47 3 48 2 49 2 50 2 51 2 52 2 53 2 54 2 55 2 56 2 57 2 58 3 59 3 60 3 61 3 62 3 63 3 64 3 65 1 66 1 67 1 68 1 69 1 70 1 71 1 72 1 73 1 74 1 75 1 76 1 77 1 78 1 79 1 80 1 81 1 82 1 83 1 84 1 85 1 86 1 87 1 88 1 89 1 90 1 91 3 92 3 93 3 94 3 95 3 96 3 97 1 98 1 99 1 100 1 101 1 102 1 103 1 104 1 105 1 106 1 107 1 108 1 109 1 110 1 111 1 112 1 113 1 114 1 115 1 116 1 117 1 118 1 119 1 120 1 121 1 122 1 123 3 124 3 125 3 126 3 127 0 ``` Inputs 11, 12, and 13 correspond to characters that are [sometimes](https://docs.python.org/2/library/re.html#regular-expression-syntax) considered whitespace, thus their outputs may be `0` or `4` as you desire. **The shortest code in bytes wins.** [Answer] # [Haskell](https://haskell.org/) 300 bytes This code should have no trailing newline. The function `m1` takes the input as a `Char` and returns the answer as a `Char`. ``` f1 (l1 :n1 :p1 :y1 :l2 :n2 :p2 :y2 :r3 )x1 |y1 >p1 =b1 (x1 )y2 (f1 (r3 )x1 )y1 (n1 )n2 |p2 <p1 =b1 (x1 )y1 (n1 )p2 (f1 (p2 :y2 :r3 )x1 )l2 |p2 >p1 =b1 (x1 )p1 (l2 )l1 (n2 )n1 ;b1 (x1 )s1 (r1 )b1 (r2 )r3 |x1 <s1 =r1 |x1 >b1 =r2 |s1 <b1 =r3 ;m1 =f1 "d0 \t4 \r0 ~d3 {d1 `d3 [d1 @d3 :d2 /d3 !d4 \n0 ?d0 " ``` I couldn't resist a challenge that someone claimed was impossible for "conventional" languages. You may dispute whether Haskell counts, but the majority of keywords and identifiers are multiple characters and cannot be used. However, top level function definitions, lists, string literals, strict comparisons, pattern matching and branching with guards work, as long as letters come just before digits, and if symbols also come just before letters we have escape characters like `\t` and `\r`. Unfortunately the permutations that work for general programming don't allow numeric literals, so I couldn't get numbers in any useful way. # How it works: * The intervals of character classes are encoded in the string on the last line, with boundary characters at most of the symbol places and the results in most of the digit places, although some at the ends are padding. * The main function is `m1`. * `x1` is the character being analyzed. * The `f1` function breaks up the string with list pattern matching, and has three branches: for when the boundaries are symbols larger than space, for when the boundaries are escaped control characters smaller than space, and for handling the final comparison to space itself. The names of the list pieces are mnemonic for the first branch: Letter, Number, sPace, sYmbol, Remainder. * The `b1` function handles branching for two boundary characters `s1 < b1` at a time. [Try it online](https://tio.run/nexus/haskell#XVAxjsIwEOx5xYAo4iK6OKGChLsXXEUHBQk2IlJiLMenO3QRXw9jCAUUo9nd2Zm13Ja1KWrjtSsPHnO0pUUrEcf41lppBX@G@zHwp7pDHVijcuffTrvhKBE1EktDWOJCNCl7whIXwmUQfxI9tTV3iooe9oJaFPyjLqhHzBH09vTmL7ujZkfPW7ZoHp6XfBvellILXrKRk9VT68JdcugdNeb0nOecF5yHel2Fmrmc5fc6m6z4LwXvz1SCnV9g5xJcVYZ/JbEnb8lf5KVK8UGeKu6YBJ/cnw3DRnceMs2mNw "Haskell – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), 113 bytes *Letter, Number, Space, Symbol, Repeat* ``` T1 `a0 @a0 `b1 :D0 +T1 `d9 `a2 +T1 `a9 \n9 `a4 +T1 `l9 @L9 `a1 +T1 `d9 @p9 `d3 \b4 $n3 \b3 $n2 \b2 $n1 \b1 $n0 \n ``` [Try it online!](https://tio.run/nexus/retina#@x9iqJCQaKDgAMQJSYacVi4GXNogsRRLoLgRhJ1oyRmTB@KbQPg5lgoOPiC@IVytQwGQn2LMFZNkwqWSB6KNgbQRkDYC0oZA2hBIG3DF5P3/7wgA "Retina – TIO Nexus") [Test it on itself!](https://tio.run/nexus/retina#C0k4tC1BgSs4PoFLNUbDPeF/iKFCQqKBggMQJyQZclq5GHBpg8RSLIHiRhB2oiVnTB6IbwLh51gqOPiA@IZwtQ4FQH6KMVdMkgmXSh6INgbSRkDaCEgbAmlDIG3AFZP3n/5WAgA) Retina seems like a nice tool for this job: we can use all types of characters flexibly in stage configuration, and we have some predefined character classes that can be useful. I think this problem could be solved with either Replacement stages or Transliteration stages; I've chosen the Transliterations because they are more flexible and they have the most useful character classes. Regarding the pattern of the source, I was forced to put symbols right before letters in order to use `\n` for newlines (I actually had a shorter solution using the more practical ¶ for newlines, but non-ascii characters are banned). ### Explanation The first stages are transliterations. We use `+` and `1` as options to keep the pattern going but they won't affect the result of the stage. The syntax is `T`from`to` to map each character of `from` to the character in the same position in `to`. If `to` is shorter than `from`, its final character is repeated as much as needed. If `from` has repeated characters, only the first occurrence of each one is considered. Some letters correspond to character classes, e.g. `d` is equivalent to `0123456789`. ``` T1 `a0 @a0 `b :D0 ``` With this we map some characters to other characters of the same class in order to "make some room" for following transliterations. (`a`->`b`,`0`->`1`,`space`->`tab`,`@`->`;`). The final `:D0` is just a smiley :D0 ``` +T1 `d9 `a2 ``` We start with digits, `d` is the character class `0-9`, here we're transforming `0`->`a`,`1-9`->`2`,`space`->`2`: the transliterations for `0` and `space` are wrong, but those characters have been eliminated by the previous transliteration. ``` +T1 `a9 \n9 `a4 ``` Whitespace, transform `a`->`a`,(`9`,`tab`,`\n`,`space`)->`4`. `9` was already removed in the previous stage. ``` +T1 `l9 @L9 `a1 ``` Letters, here we use two different character classes (for lack of a more complete one): `l` for lowercase letters and `L` for uppercase letters. They all get mapped to `1`, along with some other characters which have been dealt with in the previous stages ``` +T1 `d9 @p9 `d3 ``` Symbols. Since every other class has been turned into a digit, here we map all digits to themselves with `d`->`d`, and then all printable characters to `3` with `p`->`3`. Digits are also among printable characters, but the first transliteration wins. Now we need to assign `0` to control characters, but I've found no valid way to explicitly address that class. Instead, we'll convert each digit to unary: control characters are not digits and so they are considered as the empty string, which equals `0` in unary. Unfortunately, the unary conversion command in retina is `$*`, which are two symbols near each other, so we'll instead convert "manually" using substitutions. ``` \b4 $n3 \b3 $n2 \b2 $n1 \b1 $n0 ``` Our unary digit is `$n`, which is a replacement pattern for newlines. `\b` matches a "boundary", where an alphanumeric word starts or ends: in our case this will always match before any number. We are basically replacing each number `n` with a newline plus `n-1`. ``` \n ``` In the end, we count the number of newlines and get the desired result. [Answer] # [Cardinal](https://esolangs.org/wiki/Cardinal) ~~2240~~ 2224 bytes Template used LSNW ``` a%1 a:1 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a+1 a.1 x.1 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a.0 a>0 a+1 a+1 a+1 a+1 a.1 x>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a.0 x>1 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a.0 x>1 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a>0 a+1 a+1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a+1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a.0 x>1 a>1 a>1 a>1 a>1 a>1 a>1 a+1 a+1 a+1 a.0 a>1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a>1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^1 a>1 a-1 J^1 a-1 J^1 a-1 J^1 a-1 J^0 a.0 ``` The code has a trailing newline. ## How it works: This code has a lot of characters that aren't used. % releases a pointer in all directions. 3 of them just hit the end of a line and die. The last pointer takes in an input at the : This input is then compared to each value from 0 to 127. Prints: 0 for 0-8 4 for 9-12 0 for 13-31 4 for 32 3 for 33-47 2 for 48-57 3 for 58-64 1 for 65-90 3 for 91-96 1 for 97-122 3 for 123-126 0 for 127 Operations used: J = Skip next operation if non-zero ^ = Change direction to up > = Change direction to left - = Decrement + = Increment : = Take input % = Create pointers at start of program x = Remove pointer 0 = Set active value of pointer to 0 [Try it online](https://tio.run/nexus/cardinal#@5@oasiVaGWokKhnQB1shwdrG6JiPUOFCj0q2k1NjMu9dgT8SAuM4gYDoBsMqW82ueZiddswweT4aaSHB6r/uUBiXnFAti6NaXR36NLJ3qHuXlq6gVJzh1J8kuO30fAgITzA9TLX//@GRuYA) [Answer] # [Perl 5](https://www.perl.org/), 293 bytes **291 bytes code + 2 for `-0p`.** *I have been advised the command-line flags are free, but I've added them here for visibility, as the TIO link doesn't include `-0`, for easier testing.* ``` y 0-a 1"a 1#a 1$a 1%a 1&a 1'a 1(a 1)a 1*a 1+a 1,a 1.a 1/a 1_a 1{a 1|a 1}a 1~a 0!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 1!a 0;s 0\s 0\t 0;s 0\d 0\r 0;s 0\w 0\n 0;y 1!a 9-a 1_a 0-Z 1;s 0\w 0\u 3\u 0;s 1\S 1\u 0\u 1;s 0\t 0\u 4\u 0;s 0\r 0\u 2\u 0;s 0\n 0\u 1\u 0 ``` [Try it online!](https://tio.run/##rc5LDoIwGATguNPZeYOKD3yhRWVBXHkAV@4MCZLowkSBAMYg6tGtYyGcwMWXzp/52zQ@JRdHqVxIKxC2QV3qUZ8GZNKQRjSmCU1pRnPyqaAnvegdCNnh@SdynQrppZBehjIfmZMq35lD5lzvulb5H2nthV33N7Gk377t7WD/MpV9pvtV1et3mRf1HOpZ31GqgSbaCHDFAxtssYeEAxcdHOCjgAETAi18ojg7R2GqrPgL "Perl 5 – Try It Online") This is a particularly tricky challenge to solve in almost any language, so I'm pretty happy I was able to (finally, lots of tinkering on and off for quite some time) get this working in Perl. Hopefully the additional whitespace before and after the number isn't an issue. Selecting the sequence order was particularly tricky, but forunately `s///` and `y///` can accept any other character as a delimiter so it was possible to use letter, space, number, symbol, which allows for `s 0...0...0;` and `y 0...0...0;`. The first thing required for the appraoch was to replace `_` with `!` so that `\w` would only match `[0-9a-zA-Z]`, then replace all whitespace (`\s`) with `\t`, all digits with `\r` and all remaining word characters (`\w`) with `\n` for easy matching later on. Then, using the `y///` operator, all remaining symbols are converted to word characters `!` to `_` and all other chars (between `9` and `a`) are shifted down 9 places, turning them into letters or numbers. These are then replaced via `\w` with `3` and the other, previously made substitutions are replaced with their numbered values. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 1332 bytes ``` Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! Y0! ``` Order is `1234`/`LNSW` (letter, digit, symbol, whitespace). [Try it online](https://tio.run/##vZMxCoAwDEXn5BTxBurkVRxFCroJCh4/Lg4xJJpWcQgttbw8f8k@zVtal2FMzH1dkShUK5x7MEre@3tPwo8M17szdBjyn0oZZOQJxj10vqPKW/bX/SDYT/I8Tk4GJTlAoRsZfhFWTmbwMrcv3ayKuHlzi858W@@Fyk0y8GEWtWuE8eSUw/IyzfUBJ7MLg7lpuwM) (input as integer representing the unicode of a character). **Explanation:** Whitespace is a stack-based language where every character except for spaces, tabs and new-lines are ignored. Here is the same program without the `YO!` (**333 bytes**): ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve][S N S _Duplicate_input(9)][S N S _Duplicate_input(10][S N S _Duplicate_input(32)][S N S _Duplicate_input(33-47)][S N S _Duplicate_input(48-57)][S N S _Duplicate_input(58-64)][S N S _Duplicate_input(65-90)][S N S _Duplicate_input(91-96)][S N S _Duplicate_input(97-122)][S N S _Duplicate_input(123-126)][S S S T S S T N _Push_9][T S S T _Subtract][N T S S N _If_0_Jump_to_Label_WHITESPACE][S S S T S T S N _Push_10][T S S T _Subtract][N T S S N _If_0_Jump_to_Label_WHITESPACE][S S S T S S S S S N _Push_32][T S S T _Subtract][S N S _Duplicate][N T S S N _If_0_Jump_to_Label_WHITESPACE][N T T S T N _If_negative_Jump_to_Label_NONE][S S S T T S S S S N _Push_48][T S S T _Subtract][N T T N _If_negative_Jump_to_Label_SYMBOL][S S S T T T S T S N _Push_58][T S S T _Subtract][N T T S S N _If_negative_Jump_to_Label_DIGIT][S S S T S S S S S T N _Push_65][T S S T _Subtract][N T T N _If_negative_Jump_to_Label_SYMBOL][S S S T S T T S T T N _Push_91][T S S T _Subtract][N T T T N _If_negative_Jump_to_Label_LETTER][S S S T T S S S S T N _Push_97][T S S T _Subtract][N T T N _If_negative_Jump_to_Label_SYMBOL][S S S T T T T S T T N _Push_123][T S S T _Subtract][N T T T N _If_negative_Jump_to_Label_LETTER][S S S T T T T T T T N _Push_127][T S S T _Subtract][N T T N _If_negative_Jump_to_Label_SYMBOL][N S N S T N _Jump_to_Label_NONE][N S S S N _Create_Label_WHITESPACE][S S S T S S N _Push_4][T N S T _Print_as_integer][N N N _Exit][N S S N _Create_Label_SYMBOL][S S S T T N _Push_3][T N S T _Print_as_integer][N N N _Exit][N S S S S N _Create_Label_DIGIT][S S S T S N _Push_2][T N S T _Print_as_integer][N N N _Exit][N S S T N _Create_Label_LETTER][S S S T N _Push_1][T N S T _Print_as_integer][N N N _Exit][N S S S T N _Create_Label_NONE][S S S N _Push_0][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online.](https://tio.run/##fY9BCoAwDATPm1fkCX5JpKA3QcHn12xaQypiWkqZTLb0WrezHPu8lFpVVWxBwLLb31aFUu2HOLChEbAcMZnUsq3PHqJnrJEUMCRg0DiKQCkMr7QPzSu09lvReEvgQPoXqQZ4pIRaaHacOKh1ugE) **Program in pseudo-code:** ``` If the input is 9, 10 or 32: call function WHITESPACE() Else-if the input is below 32: call function NONE() Else-if the input is below 48: call function SYMBOL() Else-if the input is below 58: call function DIGIT() Else-if the input is below 65: call function SYMBOL() Else-if the input is below 91: call function LETTER() Else-if the input is below 97: call function SYMBOL() Else-if the input is below 123: call function LETTER() Else-if the input is below 127: call function SYMBOL() Else (the input is 127 or higher): call function NONE() WHITESPACE(): Print 4 Exit program SYMBOL(): Print 3 Exit program DIGIT(): Print 2 Exit program LETTER(): Print 1 Exit program NONE(): Print 0 (Implicit exit with error: Exit not defined) ``` ]
[Question] [ Given two note names, you are to write a program that determines if the interval formed by these two notes is consonant or dissonant. # Introduction In Western music, there are only 12 "different" tones. Their names, sorted from lowest to highest, are these: `C, C#, D, D#, E, F, F#, G, G#, A, A#, B`. The sequence is cyclical, i. e. it continues with another `C` after the `B`, infinitely. The distance between two tones is called an *interval*. The interval between any two notes that are adjacent in the series above (e. g. `C — C#` or `E — F`) is called a *semitone*. The interval between more distant notes is defined as the number of semitone steps needed to get from the first to the second (while possibly wrapping around the sequence). Some examples: `D to E` = 2 semitones, `C to G` = 7 semitones, `B to D#` = 4 semitones (this wraps around the sequence).1 Now, these intervals are divided into two categories: *consonant* (pleasantly sounding if you play the two notes at once) and *dissonant* (not so much). Let's define the consonant intervals to be: 0, 3, 4, 5, 7, 8 and 9 semitones. The rest of them is dissonant, namely: 1, 2, 6, 10 and 11 semitones. # The Challenge Write a "program" (in the usual broad sense of the word: a function is perfectly OK) to do the following: * Take two note names (strings from the sequence above) as an input. You may take them however you like (from stdin, as arguments, separated by whatever you want, even feel free to take them as a list of characters (e. g. `["C","#"]`). However, you may not assign any other names to the notes (especially you may not number them from 0 to 11 and use the numbers). * For you music geeks out there, the notes will be specified without the octave. In this case, it also does not matter in which order the notes come and which is lower and which is higher. Finally, you don't need to handle any names not in the list above. No other enharmonics like `E#`, no flats, double-alterations and so on. * Pick any two different values. Your program must output one of them whenever the interval formed by the two notes in the input is consonant, and the other if they are not. (Could be `True` and `False`, but even π and e if you want :)) * This is a code-golf. The shortest program in bytes in each language wins. Have fun! # Examples and Test Cases ``` Note 1 Note 2 Output Interval [semitones] C D Dissonant 2 A# A# Consonant 0 G D Consonant 7 (wraparound) D# A Dissonant 6 F E Dissonant 11 A C Consonant 3 ``` I don't add more of them since there aren't any particularly treacherous cases in this. This is a first challenge of mine, so any constructive criticism is warmly welcome :—). If you find the theory explanation sloppy, feel free to ask questions. Finally, please do not tell me that this is a dupe of [this](https://codegolf.stackexchange.com/questions/76120/music-interval-solver) or [this](https://codegolf.stackexchange.com/questions/8523/the-major-minor-dichotomy). I made sure it's not. (The latter is quite similar but more complex. I thought that putting up a little simpler challenge will make it easier for people to join.) --- 1: I tried to simplify this explanation as far as I could. There's a lot more theory around intervals. Please don't bash me for leaving it out. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes Takes input as a list of two strings. Returns `0` for dissonant or `1` for consonant. ``` OḢ6×%21_Lµ€IA“¬ɠṘ’æ»Ḃ ``` [Try it online!](https://tio.run/##ATsAxP9qZWxsef//T@G4ojbDlyUyMV9MwrXigqxJQeKAnMKsyaDhuZjigJnDpsK74biC////WyJBIiwiRCMiXQ "Jelly – Try It Online") ``` OḢ6×%21_Lµ€IA“¬ɠṘ’æ»Ḃ - main link µ€ - for each note e.g. ["A#", "C"] O - convert to ASCII codes --> [[65, 35], 67] Ḣ - keep the first element --> [65, 67] 6× - multiply by 6 --> [390, 402] %21 - modulo 21 --> [12, 3] _L - subtract the length --> [12, 3] - [2, 1] = [10, 2] IA - absolute difference --> 8 “¬ɠṘ’ - the integer 540205 æ» - right-shift --> 540205 >> 8 = 2110 Ḃ - isolate the LSB --> 2110 & 1 = 0 ``` ### Making-of We first should note that the function **F** that we're looking for is commutative: for any pair of notes **(A, B)**, we have **F(A, B) = F(B, A)**. Since there are not too many possible inputs and only 2 possible outputs to deal with, it must be possible to find a rather simple hash function **H**, such that **|H(A) - H(B)|** produces a limited range of values and is collision-free for all possible pairs of notes **(A, B)** with respect to the expected output. We're going to test the set of functions **H(mul, mod)**, which are defined as: ``` H(mul, mod)(s) = ((ORD(s[0]) * mul) MOD mod) - LEN(s) ``` Where `ORD(s[0])` is the ASCII code of the first character of the note and `LEN(s)` is the length of the note (**2** if there's a `'#'` and **1** if not). Below is a commented version of the JS code that was used to find a couple of valid pairs ***(mul, mod)*** and the resulting bitmasks. There are many possible solutions, but `* 6 % 21` is the shortest one with this method. ``` // all 12 notes note = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']; // reference implementation that takes 2 notes // and returns 0 for dissonant or 1 for consonant F = (a, b) => +!~[1, 2, 6, 10, 11].indexOf((note.indexOf(a) - note.indexOf(b) + 12) % 12) for(mul = 1; mul < 100; mul++) { for(mod = 1; mod < 31; mod++) { // hash function H = s => s.charCodeAt() * mul % mod - s.length; table = {}; // for all possible pairs of notes (a, b) if(note.every(a => note.every(b => { // compute the table index idx = Math.abs(H(a) - H(b)); // and the expected result res = F(a, b); // if the slot is empty, store the correct value if(table[idx] === undefined) { table[idx] = res; return 1; } // else, make sure that the correct value is already there return table[idx] == res; }))) { // if all tests pass: translate the table into a binary mask for(n = 0, msk = 0; n < 31; n++) { msk |= (table[n] || 0) << n; } // and display the result console.log('mul ' + mul + ', mod ' + mod + ' --> ' + msk); } } } ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~62~~ 39 bytes Uses `⎕IO←0`; 0 is consonant, 1 is dissonant. Takes list of base note chars as left argument and list of sharps as right argument. ``` {⎕A[|-/('C D EF G A '⍳⍺)+⍵=⍕#]∊'BCGKL'} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZDWQ6xhdo6uvoe6s4KLg6qbgruCooP6od/Oj3l2a2o96t9o@6p2qHPuoo0vdydnd20e99v9/dWcXdYU0BXUFBXUudUdHMFtZGch2RxJ3gYqD2G6uSOqdYWwA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous function where `⍺` is the left argument and `⍵` is the right argument  `⎕A[`…`]∊'BCGKL'` is the **A**lphabet, indexed by the following, a member of the string?   `⍕#` format the root namespace (yields the sharp character)   `⍵=` are the right argument chars (the sharps) equal to that?   `(`…`)+` add the following:    `'C D EF G A '⍳⍺` indices of the left argument chars in the string   `-/` difference between those   `|` absolute value [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ ~~27~~ 26 bytes ``` ,j'DJEFPGIALBC'&mQs]ZP7Mdm ``` Inputs the two notes in different lines. Outputs `0` for consonant, `1` for dissonant. [Try it online!](https://tio.run/##y00syfn/XydL3cXL1S3A3dPRx8lZXS03sDg2KsDcNyX3/38XZS5HAA) Or [verify all test cases](https://tio.run/##y00syfmf8F8nS93Fy9UtwN3T0cfJWV0tN7A4NirA3Dcl979LyH9nLhcuR2UQcgeyXIAsLjcuVyDpDAA). ### Explanation The 11-character string ``` DJEFPGIALBC ``` encodes both the notes and the dissonant intervals, as follows. The program first *finds the 1-based indices of the input characters* in the above string. A non-sharp input like `D` will give `1`, `E` will give `3`, ..., `C` will give `11`. These numbers can also be considered 1×1 numeric arrays. A sharp input like `C#` will give the 1×2 array `[11 0]`, meaning that `C` was found at position `11` and `#` was not found. Observe that letters `JPIL` will never be present in the input. For now they are only used as placeholders, so that for example note `E` is *two* semitones above `D`. But they will also be useful to define dissonant intervals. The numbers in the first entry of the 1×1 or 1×2 array correspond to note pitch in semitones, not counting sharp symbols (yet). Observe that the scale defined by these numbers doesn't start at `C`; but that doesn't matter because we only want intervals, that is, *differences* between notes. Subtracting the obtained numbers would give either the interval or 12 minus the interval. But first we need to consider the sharp symbol. To consider sharp notes, a golfy way (in MATL) is to add `1` to each entry of the 1×1 or 1×2 array obtained previously and then sum the array (2 bytes). Thus non-sharp notes are increased by `1` and sharp notes by `2`. This makes sharp notes 1 semitone higher than non-sharp notes, as required. We are also adding an extra semitone to all notes, but that doesn't change the intervals between them. So now note `D` will give pitch number `2`, `D#` will give `3`, ..., `C` will give `12`, `C#` will give `13`. Dissonant intervals are `1`, `2`, `6`, `10`, or `11`. These have a *modulo-12 symmetry*: an interval between two notes is dissonant if and only if the interval with the notes in reverse order, modulo 12, is dissonant. If we compute the consecutive differences of the string `'DJEFPGIALBC'` we get the numeric vector ``` 6 -5 1 10 -9 2 -8 11 -10 1 ``` which contains precisely the dissonant intervals, in addition to some negative values, which will be neither useful nor harmful. Observe that it is the choice of additional letters `JPIL` in the string `'DJEFPGIALBC'` that defines (via consecutive differences) the dissonant intervals. To see if the two input notes are dissonant we take the *absolute difference* of their pitch numbers. For example, `C` and `D#` will give numbers `12` and `3` respectively, and the absolute difference is `9`. The actual difference would be `-9`, and the actual interval would be `3` (obtained as `-9` modulo 12). But thanks to the symmetry referred to above, we can consider `9` instead of `3`. Since `9` is not present in the vector of consecutive differences, the notes are consonant. [Answer] # JavaScript (ES6), ~~68~~ 64 bytes Takes the notes as two strings in currying syntax `(a)(b)`. Returns `0` for dissonant or `1` for consonant. ``` a=>b=>488055>>(g=s=>'C D EF G A'.search(s[0])-!s[1])(a)-g(b)+9&1 ``` ### Test cases ``` let f = a=>b=>488055>>(g=s=>'C D EF G A'.search(s[0])-!s[1])(a)-g(b)+9&1 console.log(f('C' )('D' )) // 0 (Dissonant) console.log(f('A#')('A#')) // 1 (Consonant) console.log(f('G' )('D' )) // 1 (Consonant) console.log(f('D#')('A' )) // 0 (Dissonant) console.log(f('F' )('E' )) // 0 (Dissonant) console.log(f('A' )('C' )) // 1 (Consonant) ``` ### Formatted and commented ``` a => b => // given the two notes 'a' and 'b' 488055 >> // 19-bit lookup bitmask: 1110111001001110111 (g = s => // we use g() to convert a note 's' into a semitone index 'C D EF G A'.search(s[0]) // position of the note: -1 for 'B' (not found) to 9 for 'A' - !s[1] // subtract 1 semitone if the '#' is not there )(a) // compute the result for 'a' --> [ -2 ... 9] - g(b) // subtract the result for 'b' --> [-11 ... 11] + 9 // add 9 --> [ -2 ... 20] & 1 // test the bitmask at this position (0 if negative or > 18) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` i@€ØAo.SḤ’d5ḅ4µ€ạ/“¢£©½¿‘ċ ``` A monadic link taking a list of the two notes (as lists of characters) and returning `0` for consonant and `1` for dissonant. **[Try it online!](https://tio.run/##AWQAm/9qZWxsef//aUDigqzDmEFvLlPhuKTigJlkNeG4hTTCteKCrOG6oS/igJzCosKjwqnCvcK/4oCYxIv//0MgQyMgRCBEIyBFIEYgRiMgRyBHIyBBIEEjIEL/WyJEIyIsICJHIyJd "Jelly – Try It Online")** or see all inputs in the [test-suite](https://tio.run/##y0rNyan8/z/T4VHTmsMzHPP1gh/uWPKoYWaK6cMdrSaHtgKFH@5aqP@oYc6hRYcWH1p5aO@h/Y8aZhzp/v9wx6ZDW49OOtJtHaoCZOw53A5UmwXEINQwR0Fb4VHD3CwoxwrEifzvrOCsrOCi4KKs4KrgpuCmrOCu4K6s4KjgqKzghFcSAA "Jelly – Try It Online"). ### How? ``` i@€ØAo.SḤ’d5ḅ4µ€ạ/“¢£©½¿‘ċ - Link: list of lists of characters, notes µ€ - for €ach note in notes: (call the resulting list x) ØA - yield the uppercase alphabet i@€ - first index of c in ^ for €ach character, c - ...note '#' is not there so yields 0 (A->1, B->2,...) . - literal one half o - or (vectorised) - e.g. "C#" -> [3, 0] -> [3, 0.5] S - sum Ḥ - double - that is ... C C# D D# E F F# G G# A A# B -> 6 7 8 9 10 12 13 14 15 2 3 4 ’ - decrement -> 5 6 7 8 9 11 12 13 14 1 2 3 5 - literal five d - divmod (e.g. 9 -> [1,4] or 11 -> [2,1]) 4 - literal four ḅ - convert from base (e.g. [1,4] -> 8 or [2,1] -> 9) -> 4 5 6 7 8 9 10 11 12 1 2 3 / - reduce x with: ạ - absolute difference (e.g. ["G#", "A"] -> [12, 1] -> 11) “¢£©½¿‘ - code-page indices = [1, 2, 6, 10, 11] ċ - count occurrences (1 if in the list, 0 if not) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes ``` O_65ị“¢[ḋṃ’b⁴¤+L$€Ḣ€ạ/e“cṾ’b12¤ ``` [Try it online!](https://tio.run/##y0rNyan8/98/3sz04e7uRw1zDi2Kfrij@@HO5kcNM5MeNW45tETbR@VR05qHOxaByF0L9VOBqpIf7twHUmBodGjJ////lRyVdBSU3JWVAA "Jelly – Try It Online") wheeeeee 32 bytes too long # Explanation ``` O_65ị“¢[ḋṃ’b⁴¤+L$€Ḣ€ạ/e“cṾ’b12¤ Main link O Cast each character to an int using Python `ord` _65 Subtract 65 (A is 0, G is 7) “¢[ḋṃ’b⁴¤ [2, 3, 5, 7, 9, 10, 0] “¢[ḋṃ’ 37058720 b Digits in base ⁴ 16 ị Index into this list; this creates the gaps for sharps € For each sublist +L$ Add the length to each element (Sharpens sharp notes) + Add L Length € For each sublist Ḣ Take the first element ạ/ Absolute difference between the two (unoctaved) pitches # It's convenient that every interval's inverse (?) has the same consonance/dissonance e Is the semitone difference in “cṾ’b12¤ [1, 2, 6, 10, 11]? “cṾ’ 25178 b base 12 12 ``` [Answer] # Mathematica, 55 bytes ``` function arguments bytes FreeQ[1|2|6|10|11]@Abs[#-#2&@@Sound`PitchToNumber/@#]& [{"C","F#"}] 55 ``` Map the internal built-in `Sound`PitchToNumber` on the input (list of two strings), take the absolute difference, then pattern match for dissonant interval numbers. --- ## Just for fun (non-competing) Here are some shorter functions that violate the restriction “you may not assign any other names to the notes.” The [rudimentary `Music`` package](http://reference.wolfram.com/language/Music/guide/MusicPackage.html) has predefined note constants (like `A4 = 440.`) and the function `HertzToCents` (which can be golfed). Instead of strings, we will use the note constants as arguments, but given in a different format for each function. ``` FreeQ[1|2|6|10|11]@Abs@@Round[.01HertzToCents@#]& [{C3,Fsharp3}] 50+9=59 FreeQ[1|2|6|10|11]@Abs@Round[17Log[#2/#]]& [C3,Fsharp3] 43+9=52 FreeQ[1|2|6|10|11]@Abs@Round[17Log@#]& [C3/Fsharp3] 39+9=48 ``` The package import `<<Music`;` takes 9 bytes. This function converts a string (like `"F#"`) into a note constant (like `Fsharp3`): ``` Symbol[StringReplace[#,"#"->"sharp"]<>"3"]& 44 ``` To accept intervals larger than an octave, replace `Abs[…]` with `Mod[…,12]`. --- Why are some intervals considered dissonant? An interval is a ratio of two frequencies. If the ratio has a “simple” numerator and denominator, it tends to be more consonant. In [5-limit tuning](https://en.wikipedia.org/wiki/Five-limit_tuning), ratios can be factored into integer powers of only prime numbers less than or equal to 5. No interval in equal temperament, besides the octave, is a [just interval](https://en.wikipedia.org/wiki/Just_intonation); they are merely close approximations using powers of the 12th root of 2. Instead of hard-coding which interval numbers are dissonant, we can find a rational approximation of the interval and then determine if its numerator and denominator are “simple” (meaning that the denominator is less than 5 and the ratio does not divide 7). This table shows each of the steps in that process. ``` Table[ Module[{compoundInterval,simpleInterval,rationalApprox,denomLeq5,div7,consonant}, compoundInterval = Power[2, i/12]; simpleInterval = 2^Mod[Log2[compoundInterval], 1]; rationalApprox = Rationalize[N@simpleInterval, 1/17]; denomLeq5 = Denominator[rationalApprox]<=5; div7 = Denominator[rationalApprox]>1 && rationalApprox\[Divides]7; consonant = FreeQ[1|2|6|10|11][Mod[i,12]]; InputForm/@{ i, simpleInterval, rationalApprox, denomLeq5, div7, denomLeq5 && !div7, consonant } ], {i, 0, 12} ] i sInterval ratio denomLeq5 div7 den&&!div | consonant? 0 1 1 True False True | True 1 2^(1/12) 17/16 False False False | False 2 2^(1/6) 9/8 False False False | False 3 2^(1/4) 6/5 True False True | True 4 2^(1/3) 5/4 True False True | True 5 2^(5/12) 4/3 True False True | True 6 Sqrt[2] 7/5 True True False | False 7 2^(7/12) 3/2 True False True | True 8 2^(2/3) 8/5 True False True | True 9 2^(3/4) 5/3 True False True | True 10 2^(5/6) 7/4 True True False | False 11 2^(11/12) 11/6 False False False | False 12 1 1 True False True | True ``` The rational approximation lies within `1/17` of the interval because that is the largest threshold that distinguishes between all 12 equal tempered intervals. We match rational numbers with the pattern `Rational[a_,b_]` (or just `a_~_~b_`) first, and then match integers with only `_`. This culminates in the following rather short function that determines if an arbitrary frequency ratio (greater than 1) is consonant or dissonant. ``` Rationalize[#,1/17]/.{a_~_~b_:>b<=5&&!a∣7,_->True}& [Fsharp3/C3] 51+9=60 ``` [Answer] # Mathematica, 118 bytes ``` FreeQ[{1,2,6,10,11},Min@Mod[Differences[Min@Position["C|C#|D|D#|E|F|F#|G|G#|A|A#|B"~StringSplit~"|",#]&/@{#,#2}],12]]& ``` **Input form** > > ["A#","D"] > > > **Outputs** ``` True->Consonant False->Dissonant ``` thanks @JonathanFrech -16 bytes [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ≔B#A#G#FE#D#C槔o∧⌈ς”⁻⌕ζ⮌θ⌕ζ⮌η ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DyUnZUdld2c1V2UXZWUlHoUrTmiugKDOvRMOxxDMvJbVCQ8nQwMDQ0BCMDZQUfDPzSos13DLzUjSqdBSCUstSi4pTNQo1NXUU0AUzNEHA@v9/F2Uux/@6Zf91i3MA "Charcoal – Try It Online") Link is to verbose version of code. Outputs 1 for consonant, 0 for dissonant. Explanation: ``` ≔B#A#G#FE#D#Cζ Store reversed note names in z θ First input ⮌ Reversed ⌕ζ Find index in z η Second input ⮌ Reversed ⌕ζ Find index in z ⁻ Subtract ”o∧⌈ς” Compressed string 100111011100 § Circularly index Implicitly print ``` [Answer] # J, 68 bytes ``` [:e.&1 2 6 10 11[:(12| -~/)(<;._1',C,C#,D,D#,E,F,F#,G,G#,A,A#,B')i.] ``` ## explanation A straightforward, not super golfed implementation in J: * Input is given as boxed itemized notes (produced using cut), in order. * Find their indexes in the range of notes: `(<;._1',C,C#,D,D#,E,F,F#,G,G#,A,A#,B')i.]` * Subtract the first from the second: `-~/` * Take the remainder when divided by 12: `12|` * Check if it's one of the dissonant notes: `e.&1 2 6 10 11` [Try it online!](https://tio.run/##bY9Na8JAEIbv@ysGFpoEpttMhAi2HtbdJLf@AREJftD0sBGj9FL61@PqaNQme1jm45n3nflu2@1UwXyyUS8ECaRAMRDNJyElv/D69xaFH@9qSQEaNBItWokZ5phLLLCQqFFLnAVRpRbic6aAoGpgXTVN7Up3QIjP@ap2nAtRud3xAN7xoio2q6/az0xhC9w5@9iA6/FT3ftoOdgpuolnJb@qHmzkmA1boAnE5Qww0D3L/@0mHyfMaNkxHJrbnT6OmSn@6zwyYwh/9uWu3NdHt454wD6I9oxTZvK7aNZjiK7b3SHTcx617Qk "J – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), ~~90~~ 88 bytes ``` /^/"\///^\/\///C^D/##"E/DD"F/E#"G/FD"A/GD"B/AD"#,#/,"B#^B/#"A#/#"A^G#^G^F#/#"F^E^D#^D/#/ ``` [Try it online!](https://tio.run/##ZczBCsIwDIDhu09RkovCIE5Bz@3S9iVGoDhBQTZZFR@/Nh6GsB7awNf8@ZHy7ZpLISHoiUh60qcTJkTwxAyBPEKkwGApMjiyDNggNeBQHCFY1EsiSpSgcxAvjJqgjTGmaxyy0TPcc57GNL7qfKhksZJFpcs0LrTXrbhs/dPZbD9zeqZ5eo/Drv7jX2JVP2kiVPIrals1W61b5Y@lfAE "/// – Try It Online") (all test cases at once) * Put the input after the code. * Separate the note names with `,B#` in each test case. * The output is `,` for consonant, `,#` for dissonant. * Support for double-alterations (`##`) or `E#` in some particular cases. Otherwise the output is `,` for consonant, `#,` for dissonant (thanks to modulo 12 symmetry) * Can handle multiple test cases at once (if separated reasonably) * Lowercase characters are printed exactly. [Answer] # [C (gcc)](https://gcc.gnu.org/), 91 bytes ``` g(char*s){return (s[1]&1|2**s&15)*4/5;}f(char*x,char*y){return (1952220<<g(x)>>g(y))&2048;} ``` call: `f("A#", "D")` Return value: * Consonant: 2048 * Dissonant: 0 Bonus: The function is case insensitive. [Try it online!](https://tio.run/##ZY/basMwDIbv/RQipcF20y02DWxzFtipe4i2F8U5NLA5I06hJcuzZ468MbbefJLMh35ZLyutx7Gi@rBvuWV9W3TH1gC1G7ELxafk3IYiYXx1naih9NopwnL@tcVtIqWM07SiJ5ZlFT0zFsp4daOGcVYb/XbMC0htl9fN1SEjpDYdvO9rQxnpCQCuA9N0hd3s4B56CB6CyGE28XHCEwLnZwS2LxPWCJxfEVMbw6CIW102LfirfYBw6zFIAcdZwWKBDXP2pS//@fLHl94H@Gjdb0oazKWFJTjewTzfGneDD/iuMoKS/n1hTJGBjF8 "C (gcc) – Try It Online") [Answer] # Python 2, ~~125 117 83 78~~ 77 bytes ``` a,b=map("C C#D D#E F F#G G#A A#B".index,input()) print chr(abs(a-b))in"" ``` Where the `""` at the end actually contains the characters `"\x02\x04\x0c\x14\x16"` [Try it Online!](https://tio.run/##LYzBCsIwEERBPBWP4nmZXBKogh6VHtqk7T/0ltZAAxpDrVi/vm7Fy77ZmZ2Nn7F/hNPcZAOA2aZtdrdRQpMWhowoqaJK1FSLnHJR4ODD1U2pD/E1SqWSOPgwUtcP0rZPafetUj5gtd5sd5j548VNrsO79zdHx/OyUMOBRgqDBLlgwSNB/XfMz2FRMcvlhKmZS6XAFw) (+3 because I forgot 11 or 22 in the list to begin with) -8 bytes from Jonathan Frech and switching to Python *2*. -34 bytes with suggestions from Jonathan Frech and using `str`'s index instead of `list`'s. -4 bytes from inlining `i` and Neil's reversing the string suggestion (only -2 really, as i forgot `()` around a generator) -5 bytes from un-inlining `i` & changing the input format -1 bytes from Jonathan Frech with `map()` and unprintables. Takes input in one line of stdin in the format: ``` 'C','C#' ``` `True` is dissonant, `False` is consonant. Old Explanation: ``` i='C C#D D#E F F#G G#A A#B'.index a,b=input() print abs(i(a)-i(b))in[2,4,12,20] ``` Python `str.index` returns the lowest (positive) starting index of a matching substring, so `"ABACABA".index("A") == 0` and `"ABACABA".index("BA") == 1`. Because of this, we can put the note names evenly spaced in a string, and as long as (for example) `A` comes before `A#`, the shared `A` won't be a problem. ``` i='C C#D D#E F F#G G#A A#B'.index ``` `i` is now a function that returns the index in `'C C#D D#E F F#G G#A A#B'` its argument (a note name) is, which is 2 \* (the number of semitones that note is up from `C`) ``` a,b=input() ``` Python 2's `input()` is (mostly) equivalent to `eval(input())` in Python3, so with a valid input of the format `'C#','F'` (for example), `a='C#'` and `b='F'` ``` print abs(i(a)-i(b))in[2,4,12,20] ``` If the disttance between the first note and the second note in the string is not 2, 4, 12, or 20 (since the note names are represented in 2 characters), then the interval is dissonant, print True, else it is consonant, print False. [Answer] # [C (gcc)](https://gcc.gnu.org/), 115 ~~117~~ ~~120~~ bytes ``` g(char*a){a=*a-65+!!a[1]*(7-*a/70-*a/67);}f(x,y)char*x,*y;{x="(pP$HL<lt<X"[g(x)]*32+"=ZukW-^h1F 6"[g(x)]>>g(y)&1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9dIzkjsUgrUbM60VYrUdfMVFtRMTHaMFZLw1xXK1Hf3ABEmplrWtemaVToVGqCVVfoaFVaV1fYKmkUBKh4@IjY5JTYRChFp2tUaMZqGRtpK9lGlWaH68ZlGLpxm0HF7ezSNSo11Qyta//nJmbmaWhyVXMVFGXmlaRpKKmmxOQp6QAZ7spKOkrOSpqa1jjkXPDIuYLlav8DAA "C (gcc) – Try It Online") Return 1/0 for consonat and dissonat. It is always interesting to do string manipulation with pure C. Take input as `f("A#", "C")` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 107 bytes ``` param($a,$b)[math]::abs(($x=-split'C C# D D# E F F# G G# A A# B').indexof($b)-$x.indexof($a))-in1,2,6,10,11 ``` [Try it online!](https://tio.run/##RcyxCsMgEADQXzlQOAUttUOHQIc0ifmI0uFCLRFMIjFQ//7areNbXt4@YS9zSIk5006LkmTkpB8LHfOzaWgqSsl6syWneGAHnYAeegEDePACRhgFtNAKuKM@xfUV6vZWv8DK@idpbePqzMVcjTsb55gZPTIO@AU "PowerShell – Try It Online") Outputs `True` for dissonant and `False` for consonant. Takes input `$a` and `$b`, the two notes, as strings. Performs a `-split` operation on the scale, which splits on whitespace, to create an array of the notes, stores that into `$x`. Finds the `.indexof` `$b` in that array, subtracts the index of `$a`, and then takes the `abs`olute value thereof. Checks whether that number is `-in` the dissonant ranges. [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda a,b,f='C C#D D#E F F#G G#A A#B'.find:3142>>(f(a)-f(b))/2%12&1 ``` [Try it online!](https://tio.run/##XcrRCoIwFMbx@57iwKhtYcWsixAU5qY@hHUxsdWgpohd9PSWeuGhm8Pv/PnaT/9ofDjY@DI8zauqDZigCmxMFSiiQZMMcshJAQWRIElK99b5OjqKU5gkzDLDd5ZVnB/CtQg3YrBNBw6ch874@42JM4@g7ZzvwbKt8@27Z5wPJVU0AKrpdVVSSUb/7vgUS9dzn5yPzOb5SDVR/ZMs1ogoZwtzRLQoEFGWiCin9PoF "Python 2 – Try It Online") Outputs: `1` is dissonant, `0` is consonant. [Answer] # SQL, 582 bytes [SQL Fiddle](http://sqlfiddle.com/#!6/e683f/1/0) I still have some golfing to do on it, but I wanted to get it down here before I end up breaking it completely. If the input is in a letter format, then putting those letters in a table with values is okay, right? ``` CREATE TABLE N(N char(2),v int) Insert Into N values('A',1),('A#',2),('B',3),('C',4),('C#',5),('D',6),('D#',7),('E',8),('F',9),('F#',10),('G',11),('G#',12); CREATE TABLE D(D char(9),v int) Insert Into D values('C',0),('D',1),('D',2),('C',3),('C',4),('C',5),('D',6); CREATE FUNCTION I(@A char(2),@B char(2)) RETURNS char(9) as BEGIN DECLARE @E int=(SELECT v from N where n=@A),@F int=(SELECT v from N where n=@B) DECLARE @C char(9) = (SELECT case D when 'D' then 'Dissonant' when 'C' then 'Consonant' END from D where v in(abs(@e-@f),12-abs(@e-@f))) RETURN isnull(@C,'NotANote') END ``` [Answer] # [Perl 5](https://www.perl.org/), 106 bytes ``` ("C,C#,D,D#,E,F,F#,G,G#,A,A#,B,"x2)=~/$F[0],(.*?)$F[1],/;$r=(1+($1=~y/,//))%12;say(grep/$r/,(0,3..5,7..9)) ``` [Try it online!](https://tio.run/##Dca7CsIwGAbQV5EmQqJf8yeVIFKC1PQy@QTSoUMRQWxIHezSRzd6phPG@LQpiczDM9SoGRq0aBk6dAwVKoYLsk8h3Uq8vekeQu3O8l/Tg0oenTB7wY1bFwKRlFtTlPOwiHscA/FIEBoHpSyOSp2kTMlvmu8U3o/pNaf8apU2OuXDDw "Perl 5 – Try It Online") Returns false for dissonant, true for consonant. ]
[Question] [ # Most of us know... that all primes `p>3` are of the form [![enter image description here](https://i.stack.imgur.com/3EjFI.gif)](https://i.stack.imgur.com/3EjFI.gif) But, how many are the **Plus Primes** (`6n+1`) and how many are the **Minus Primes** (`6n-1`) in a certain range? # The Challenge Given an integer `k>5` , count how many `primes<=k` are **PlusPrimes** and how many are **MinusPrimes**. # Examples for `k=100` we have `[5, 11, 17, 23, 29, 41, 47, 53, 59, 71, 83, 89]` **12 MinusPrimes** and `[7, 13, 19, 31, 37, 43, 61, 67, 73, 79, 97]` **11 PlusPrimes** for `k=149` we have `[5, 11, 17, 23, 29, 41, 47, 53, 59, 71, 83, 89, 101, 107, 113, 131, 137, 149]` **18 MinusPrimes** and `[7, 13, 19, 31, 37, 43, 61, 67, 73, 79, 97, 103, 109, 127, 139]` **15 PlusPrimes** # Rules Your code must output **2 integers**: one for the **MinusPrimes** and one for the **PlusPrimes** in any order you like (please specify which is which). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest answer in bytes wins! # Test Cases > > **Input** -> **Output** [**MinusPrimes**,**PlusPrimes**] > > > ``` 6->[1,0] 7->[1,1] 86->[11,10] 986->[86,78] 5252->[351,344] 100000->[4806,4784] 4000000->[141696, 141448] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes Saved 1 byte thanks to *Erik the Outgolfer* Outputs as `[PlusPrimes, MinusPrimes]` ``` LDpÏ6%5Ñ¢ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx6XgcL@ZqunhiYcW/f9vYQYA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVvnfx6XgcL@ZqunhiYcW/a9UOrzfSuHwfiWd/2Zc5lwWZlyWQGxqZGrEZWgAAgA) **Explanation** ``` L # push range [1 ... input] DpÏ # keep only primes 6% # mod each by 6 5Ñ # divisors of 5 [1, 5] ¢ # count ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` Zq6\!5lh=s ``` [Try it online!](https://tio.run/##y00syfn/P6rQLEbRNCfDtvj/fxMDMAAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@q0CxG0TQnw7b4v0vIfzMucy4LMy5LIDY1MjXiMjQAAS4TMGUAAA). ### Explanation ``` Zq % Implicitly input k. Push row vector of primes up to k 6\ % Modulo 6, element-wise ! % Transpose into a column vector 5lh % Push row vector [5, 1] = % Is equal?, element-wise with broadcast s % Sum of each column. Implicitly display ``` [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes -2 bytes thanks to Neil ``` lambda x:[sum(all(n%j for j in range(2,n))for n in range(i,x,6))for i in 7,5] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKrq4NFcjMSdHI081SyEtv0ghSyEzT6EoMS89VcNIJ09TEySWhxDL1KnQMYOIZoJEzXVMY/8XFGXmlSikaZhpcsGYFkhsS2SOqZGpkeZ/AA "Python 2 – Try It Online") ### Previous solution, ~~83~~ ~~81~~ 79 bytes -1 byte thanks to Mr. Xcoder -2 bytes thanks to Halvard Hummel ``` lambda x:map([all(n%i for i in range(2,n))*n%6for n in range(4,x)].count,[5,1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKjexQCM6MSdHI081UyEtv0ghUyEzT6EoMS89VcNIJ09TUytP1QwknocQN9Gp0IzVS84vzSvRiTbVMYzV/F9QlJlXopCmYabJBWNaILEtkTmmRqZGmv8B "Python 2 – Try It Online") Both output as [MinusPrimes,PlusPrimes] [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` s6ÆPSm4 ``` Plus, then minus. [Try it online!](https://tio.run/##y0rNyan8/7/Y7HBbQHCuyf/D7Y@a1rj//2@mo2Cuo2ABpCxBhKmRqZGOgqEBCAAA "Jelly – Try It Online") ### How it works ``` s6ÆPSm4 Main link. Argument: n s6 Split [1, ..., n] into chunks of length 6. ÆP Test all integers for primality. S Sum across columns. This counts the primes of the form 6k + c for c = 1, ..., 6. m4 Take every 4th element, leaving the counts for 6k + 1 and 6k + 5. ``` [Answer] # Mathematica, 51 bytes ``` (s=#;Mod[Prime~Array~PrimePi@s,6]~Count~#&/@{5,1})& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo9hW2do3PyU6oCgzN7XOsagosbIOzA7IdCjWMYutc84vzSupU1bTd6g21TGs1VT7D5TOK1FwSIs2i@WCs82R2BbIEpYg3v//AA "Mathics – Try It Online") @ngenisis golfed it down, saving 4 bytes # Mathematica, 47 bytes ``` sPrime~Array~PrimePi@s~Mod~6~Count~#&/@{5,1} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~15~~ ~~13~~ 11 bytes Output order is `[+,-]`. ``` õj ò6 yx ë4 ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=9Wog8jYgeXgg6zQ=&input=MTQ5Ci1R) * Took some inspiration from [Dennis' Jelly solution](https://codegolf.stackexchange.com/a/140960/58974) but, after golfing, it's closer to being a port. * 2 bytes saved thank to Oliver bringing the previously-unknown-to-me `ë` method for arrays to my attention. --- ## Explanation Implicit input of integer `U`. ``` õj ``` Generate an array of integers (`õ`) from 1 to `U` and check if each is a prime (`j`), giving an array of booleans. ``` ò6 ``` Partition the array into sub-arrays of length 6. ``` yx ``` Transpose (`y`) and sum the columns. ``` ë4 ``` Get every 4th element of the array and implicitly output them. --- ## Original, ~~19~~ ~~17~~ ~~16~~ 15 bytes ``` õ fj 5â £è_%6¥X ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SBmagpGcyCso+hfJTalWA==&input=MTQ5) * 1 byte thanks to an inspired suggestion from Oliver to use the divisors of 5 after I'd rested on my laurels splitting 15 to an array. [Answer] # [J](http://jsoftware.com/), 23 bytes ``` 1#.5 1=/6|_1 p:@i.@p:>: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6zkE6Pm7/DZX1TBUMbfXNauINFQqsHDL1HAqs7Kz@a3KlJmfkK6QpmMEYFnCWJYJpaAACMJ4JmGfwHwA "J – Try It Online") ``` 1#.5 1=/6|_1 p:@i.@p:>: input: y _1 p: number of primes >: less than y + 1 p:@i. prime range from 0 to that number 6| get residues modulo 6 5 1=/ table of values equal to 5 or 1 1#. sum of each (antibase 1) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~53~~ 51 bytes ``` .+ $* 1 $`1¶ G`1111 A`^(11+)\1+$ 1{6} *M`111 \b1\b ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEslwfDQNi73BEMg4HJMiNMwNNTWjDHUVuEyrDar5eLS8gVJccUkGcYk/f9vaGIJAA "Retina – Try It Online") Explanation: ``` .+ $* ``` Convert to unary. ``` 1 $`1¶ ``` Count from 1 up to `n`. ``` G`1111 ``` Delete numbers less than 4. ``` A`^(11+)\1+$ ``` Delete composite numbers. ``` 1{6} ``` Take the remainder modulo 6. ``` *M`111 ``` Print the number of numbers with a remainder between 3 and 5. ``` \b1\b ``` Print the number of numbers with a remainder of 1. [Answer] # Ruby, ~~61~~ 60 bytes ## (52 bytes + 8 for the `-rprimes` flag) ``` ->n{[1,5].map{|x|(4..n).count{|i|i.prime?&&i%6==x}}} ``` Returns an array of the form [plus primes, minus primes]. Saved 1 byte thanks to G B! [Try it online.](https://tio.run/##KypNqvyfZvtf1y6vOtpQxzRWLzexoLqmokbDRE8vT1MvOb80r6S6JrMmU6@gKDM31V5NLVPVzNa2ora29n@BQlq0WSwXiDKHUBZQrqGBAZRhYglhWMKkTI1MjeCKDGDqTAwgnP//8gtKMvPziv/rFoEtBAA) [Answer] # [Perl 6](https://perl6.org), 42 bytes *Saved 1 byte by removing a useless space...* *Saved 2 bytes by reorganizing the* `map` *call — thanks to @Joshua.* *Saved 3 bytes because* `.round` *equals* `.round: 1`. *Actually the complex exponential is cool but very expensive characterwise. Saved 10 bytes just by ditching it...* ``` {[+] map {.is-prime*($_%6-1??i!!1)},5..$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/Olo7ViE3sUChWi@zWLegKDM3VUtDJV7VTNfQ3j5TUdFQs1bHVE9PJb72vzWXhpmOgrmOggWQsgQRpkamRpp6QN1WCtUqaUBtmnrFiZW11v8B "Perl 6 – Try It Online") This was the version with the complex exponential. (I like it too much to delete it.) The new version works exactly in the same way, just the complex exponential is replaced by the much shorter ternary operator. ``` {[+] map {.is-prime*exp(π*($_%6-1)i/8).round},5..$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/Olo7ViE3sUChWi@zWLegKDM3VSu1okDjfIOWhkq8qpmuoWamvoWmXlF@aV5KrY6pnp5KfO1/ay4NMx0Fcx0FCyBlCSJMjUyNNPWABlkpVKukAbVq6hUnVtZa/wcA "Perl 6 – Try It Online") The output is a complex number `(PlusPrimes) + (MinusPrimes)i`. I hope it's not too much against the rules. --- Explanation: It's a function that takes one integer argument. We iterate over all integers from 5 to the argument (`(5..$_)`). For each of these, we evaluate `.is-prime` (this is called on `$_`, the argument of the mapped block), multiply it (if numified, `True == 1, False == 0`) with a complex exponential that's made to be either `exp(0) = 1` (for `$_%6 = 1`) or `exp(iπ/2) = i` (for `$_%6 = 5`), and finally round it to the nearest integer. Summing them up with `[+]` gives the result. Finally: it's really efficient, so I'm not sure if TIO won't time out before you get your output for higher numbers (for 1e5, it takes 26 sec on my machine, and TIO tends to be somewhat slower). [Answer] # [Actually](https://github.com/Mego/Seriously), 21 bytes ``` u5x`p░⌠6@%1=;`╖*ƒ⌡Ml╜ ``` [Try it online!](https://tio.run/##AS8A0P9hY3R1YWxsef//dTV4YHDilpHijKA2QCUxPTtg4pWWKsaS4oyhTWzilZz//zEwMA "Actually – Try It Online") Outputs the PlusPrimes first, followed by the MinusPrimes Explanation: ``` u5x`p░⌠6@%1=;`╖*ƒ⌡Ml╜ u5x range(5, n+1) `p░ primes in range ⌠6@%1=;`╖*ƒ⌡M for each prime: 6@% mod 6 1= equal to 1 ;`╖*ƒ execute ╖ if p%6==1 (add 1 to register 0, consuming p) l length of resulting list (MinusPrimes) ╜ push value in register 0 (PlusPrimes) ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 37 bytes ``` [~>$primeYES 6%5 1,$=table tr$summap] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P7rOTqWgKDM3NdI1WMFM1VTBUEfFtiQxKSdVoaRIpbg0NzexIPa/g1UaF5eGmYK5goWZgiUQmxqZGmkqRHMpAIG6Q2aKrl20Q1qsuqJCfmkJV6wCUNN/AA "Stacked – Try It Online") Rather slow, tests for primality for each **K** < **N**. Works similar to my J answer. [Answer] # MATLAB 2017a, 29 Bytes ``` sum(mod(primes(k),6)'==[5,1]) ``` Explanation: `primes(k)` gets all primes up to and including k. `mod(primes(k),6)'` takes the modulus 6 of all primes and transposes it so the sum runs along the correct dimension. `==[5,1]` sets all fives (minusPrimes) to 1 in the first column and all ones (plusPrimes) to 1 in the second column. `sum()` sums each column. This outputs `[minusPrime, plusPrime]` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 bytes *-2 bytes thanks to @Oliver* ``` õ_j ©Z%6 5â £è¥X ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=9V9qIKlaJTYKNeIgo+ilWA==&input=Nw==) Outputs in the format `[PlusPrimes, MinusPrimes]`. [Answer] # C#, ~~202~~ ~~179~~ 174 Bytes *-23 Bytes thanks to Mr. Xcoder* *-5 Bytes thanks to Cyoce* Function that returns an array of length 2, `[MinusPrimes, PlusPrimes]` Execute by calling `a(n)`. ``` int[]a(int n){int[]r={0,0};for(int i=5;i<=n;i++)if(i%2*b(i)>0)if(i%6<5)r[1]++;else++r[0];return r;}int b(int n){for(int i=3;i-2<Math.Sqrt(n);i+=2)if(n%i<1)return 0;return 1;} ``` Properly formatted code on Try It Online: [Here](http://jdoodle.com/a/5UP) [Answer] # [Haskell](https://www.haskell.org/), ~~81~~ 69 bytes ``` f n=(\r->sum[1|i<-[2..n],all((>0).rem i)[2..i-1],rem i 6==r])<$>[5,1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1YjpkjXrrg0N9qwJtNGN9pITy8vVicxJ0dDw85AU68oNVchUxMkmqlrGKsD5iqY2doWxWraqNhFm@oYxv7PTczMU7BVSMnn4iwoyswrUVBRSFMwQ@aYI3MsUKQsUbmmRqZG/wE "Haskell – Try It Online") First solution was: ``` r!l=sum[1|i<-l,rem i 6==r] f n|l<-[i|i<-[2..n],all((>0).rem i)[2..i-1]]=(5!l,1!l) ``` But I read w0lf's answer in Ruby... [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` /K%R6fP_TSQ5/K1 ``` **[Test Suite.](https://pyth.herokuapp.com/?code=%2FK%25R6fP_TSQ5%2FK1&input=986&test_suite=1&test_suite_input=6%0A86%0A986%0A5252&debug=0)** # [Pyth](https://pyth.readthedocs.io), 16 bytes ``` m/%R6fP_TSQd,1 5 ``` **[Test Suite.](https://pyth.herokuapp.com/?code=m%2F%25R6fP_TSQd%2C1+5&input=986&test_suite=1&test_suite_input=6%0A86%0A986%0A5252&debug=0)** --- # How? ### Explanation #1 ``` /K%R6fP_TSQ5/K1 - Full program. fP_TSQ - Filter the primes in the range [1...input]. %R6 - Mod 6 on each. K - Assign them to a variable K. / 5 - Count the occurrences of 5 in K. /K1 - Count the occurrences of 1 in K. - Implicitly output the result. ``` ### Explanation #2 ``` m/%R6fP_TSQd,1 5 - Full program. fP_TSQ - Filter the primes in the range [1...input] %R6 - Mod 6 on each. ,1 5 - Push the list [1, 5] m/ d - Count how many of each there are. - Implicitly output the result. ``` Alternatives: ``` /K%R6fP_TSQ5/KhZ (16 bytes) K%R6fP_TSQ/K5/K1 (16 bytes) m/%R6fP_TSQdj15T (16 bytes) m/%R6fP_TSQd[1 5 (16 bytes) m/%R6fP_TSQdsM`15 (17 bytes) m/%R6.MP_ZSQd,1 5 (17 bytes) m/%R6.MP_ZSQdj15T (17 bytes) m/%R6.MP_ZSQd[1 5 (17 bytes) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 11~~ 10 bytes Thanks to [@cairdcoinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) for some tips in chat. Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis?tab=profile) for saving one byte in chat. ``` ÆR%6ċЀ1,5 ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5Cq2ZHuwxMeNa0x1DH9//@/hRkA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ÆR%6µ1,5=þS ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5Cq2aGthjqmtof3Bf///9/CDAA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ÆR%6µċ5,ċ1$ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5Cq2aGtR7pNdY50G6r8///fwgwA "Jelly – Try It Online") --- # How does this work? ### Explanation #1 ``` ÆR%6ċЀ1,5 As usual, full program. ÆR Get all the primes in the range [2...input]. %6 Modulo each by 6. 1,5 The two-element list [1, 5]. ċЀ Count the occurrences of each of ^ in the prime range. ``` ### Explanation #2 ``` ÆR%6µ1,5=þS As usual, full program. ÆR Get all the primes in the range [2...input]. %6 Modulo each by 6. µ Chain separator. 1,5 The two-element list [1, 5]. = Equals? þ Outer product. S Sum. ``` ### Explanation #3 ``` ÆR%6µċ5,ċ1$ As usual, full program. ÆR All the primes in the range [2...input]. %6 Modulo each by 6. µ $ Some helpers for the chains. , Two element list. ċ5 The number of 5s. ċ1 The number of 1s. ``` [Answer] # Java 8, ~~141~~ ~~140~~ ~~138~~ ~~106~~ ~~101~~ ~~100~~ ~~96~~ ~~94~~ 81 bytes ``` n->{int r[]={0,0},c;for(;n-->4;r[n%6/4]+=c)for(c=n;c>1;c=c-1&~n%c>>-1);return r;} ``` Returns an integer-array with two values, in reversed order compared to the challenge description: `[plusPrime, minusPrime]`. Port of [*@Xynos*' C# answer](https://codegolf.stackexchange.com/a/140937/52210), after I golfed ~~39~~ ~~40~~ 42 bytes. Huge help from *@Nevay* for another whopping -55 bytes. **Explanation:** [Try it here.](https://tio.run/##lY9BboMwEEX3nGI2iUwBFyKStnKN1AM0mywRC8ch1bhgkDGRIsTZqQlddFksWyP/maf/R4mbiJq21OryPWHdNsaCchrtLVb0wxhx75gnK9F18ClQDx4Aaluaq5AlHOfvQ8gLkMRV0D5z2uieu50VFiUcQQOHSUfZMI@YvOBDHMZjiDwNVSjZtTGEYRC8a2Zy3Bye0yLguJX@3FBc8oSpJ@X6yHy55RFugkBlWZQwU9reaDBsnNji2fbnynn@Wt8avEDtgpOTNai/XE7hL6lP986WNW16S1vXspUmy77UNssw0VSSg@8/Vvo38LIWeF1t8bYe2e/2u7VMEs9nLZXGf7HRG6cf) (Final test case of `4000000` is exceeding the 60 sec time limit slightly.) ``` n->{ // Method with integer parameter and integer-array return-type int r[]={0,0}, // Return integer-array, starting at [0,0] c; // Temp integer for(;n-->4; // Loop (1) as long as the input is larger than 4 // and decrease `n` by 1 before every iteration r[n%6/4]+=c) // After every iteration, increase the plus or minus prime by `c` // (where `c` is either 0 or 1) for(c=n; // Reset `c` to `n` c>1; // And inner loop (2) as long as `c` is larger than 1 c= // Change `c` to: c-1&~n%c>>-1; // inverting the bits of `n`, [~n] // modulo-`c` that result, [%c] // then bit-shift right that by -1, [>>-1] // and then bitwise-AND that result with `c-1` [c-1&] ); // End of inner loop (2) // End of loop (1) (implicit / single-line body) return r; // Return result integer-array } // End of method ``` [Answer] # JavaScript (ES6), ~~83~~ ~~82~~ ~~80~~ ~~68~~ 66 bytes Turned out a fully recursive solution was *much* shorter than mapping an array! Output order is `[-,+]`. Craps out with an overflow error somewhere around 3490. ``` f=(n,a=[0,0])=>n>4?f(n-1,a,(g=y=>n%--y?g(y):y<2)(n)&&++a[n%6%5]):a ``` --- ## Try it ``` o.innerText=( f=(n,a=[0,0])=>n>4?f(n-1,a,(g=y=>n%--y?g(y):y<2)(n)&&++a[n%6%5]):a )(i.value=6);oninput=_=>o.innerText=i.value>5?f(+i.value):[0,0] ``` ``` <input id=i min=6 type=number><pre id=o> ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 19 bytes ``` ri){mp},6f%_5e=p1e= ``` Program that takes the input from STDIN, and outputs the two numbers separated by newline through STDOUT. [**Try it online!**](https://tio.run/##S85KzP3/vyhTszq3oFbHLE013jTVtsAw1fb/f0MDEAAA "CJam – Try It Online") ### Explanation ``` ri){mp},6f%_5e=p1e= ri Read integer k ) Add 1 , Filter the (implicit) array [0 1 ... k] ... {mp} ... on the function "is prime" f Map over the resulting array... % ... the function "modulus" ... 6 ... with extra parameter 6 _ Duplicate the resulting array e= Count occurrences ... 5 ... of number 5 p Print with newline e= Count occurrences ... 1 ... of number 1. Implicitly display ``` [Answer] # [R](https://www.r-project.org/) + [numbers](https://cran.r-project.org/web/packages/numbers/numbers.pdf), ~~66~~ ~~60~~ ~~58~~ 40 bytes *-16 bytes thanks to Jarko Dubbeldam!* I subsequently golfed another two bytes off. ``` cat(table(numbers::Primes(4,scan())%%6)) ``` Prints `PlusPrimes MinusPrimes` to stdout; reads from stdin. `table` tabulates the count of each occurrence of the values in its input vector, in ascending order of value. Hence, since there are only two values, namely `1` and `5` (mod 6), this is exactly the function we need, along with `numbers::Primes`, which returns all primes between `4` and the input. [Try it online!](https://tio.run/##K/r/PzmxRKMkMSknVSOvNDcptajYyiqgKDM3tVjDRKc4OTFPQ1NTVdVMU/O/oYnlfwA) # Base [R](https://www.r-project.org/), ~~97~~ ~~91~~ ~~89~~ ~~86~~ 65 bytes *a bunch of bytes saved by Jarko here, too* ``` function(n)table((5:n)[sapply(5:n,function(x)all(x%%2:x^.5))]%%6) ``` This is nearly identical to the above, except it calculates all the primes in base R rather than using a package, and it returns by function output rather than printing it out. You can see in the output that it returns a table with names `1` and `5`, with the counts below. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7MkMSknVUPD1CpPM7o4saAgpxLE1oGrqNBMzMnRqFBVNbKqiNMz1dSMVVU10/yfpmGuyZWmYWhiqfkfAA "R – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 41 bytes ``` n->vecsum([[i>3,i<3]|i<-primes([4,n])%6]) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P164sNbm4NFcjOjrTzlgn08Y4tibTRregKDM3tVgj2kQnL1ZT1SxW839iQUFOpUaegq6dAlAyrwTIVAJxlBTSNPI0NXUUos10FMx1FCyAlCWIMDUyNdJRMDQAAaB@AA "Pari/GP – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~151~~, ~~140~~, 131 bytes ``` n=>[...Array(n+1).keys()].splice(5).filter(a=>!/^1?$|^(11+?)\1+$/.test("1".repeat(a))).reduce((r,a)=>(a%6<2?r[1]++:r[0]++,r),[0,0]) ``` [Try it online!](https://tio.run/##DYzBCoJAFEW/JSl4j7GnExUUqbRtUYuWpjDYGFM2ypspEPp3m9U9cDj3qb7KNWwGv3SDuWt@9/alx6nNJpvlJREdmdUIVkikIBxgRW7oTKNhg9SazmsGleWzpJbF/FeDlKLAmxTzhLx2HiIZEetBKw8KEQPfPyEGjhVmOajF9rAquJSVEHsu0zAxY1ymcVrh1PTW9Z2mrn/A6Xo5k/Ns7MO0I7Qg17twOP0B "JavaScript (SpiderMonkey) – Try It Online") Thanks to shaggy for helping with a bug fix and golfing. Explanation: ``` n=> // Create a lambda, taking n [...Array(n+1).keys()] // Create a list from 0 to n+1 .splice(5) // remove first five elements .filter(a=> // filter the list to get primes !/^1?$|^(11+?)\1+$/.test("1".repeat(a))) // using the famous regex here: https://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex .reduce((r,a)=> // reduce the list (a%6<2?r[1]++:r[0]++,r), // by counting plus primes [0,0]) // and minus primes ``` ]
[Question] [ > > ...and real golf for my code friends. > > > This is a challenge based on [a one year old XKCD comic](https://www.xkcd.com/1645/) which consists mostly of toasts (parodies of the first in the comic) following a distinct pattern, but with some slight variation. Your task is to write a program (or function) that takes the first half of any toast from the comic (everything up to and including the `friends`) as input (via stdin or a function argument) and outputs (or returns) the precise text of the second half. You do not have to handle invalid input, standard loopholes apply, shortest code in bytes wins. ### Examples To help those who don't want to copy the toasts from anywhere else, here are all of them, separated into input and output. ``` Input: Champagne for my real friends Output: and real pain for my sham friends! Input: Pseudopods for my real friends Output: and real pods for my pseudo-friends! Input: Petticoats for my real friends Output: and real coats for my petty friends. Input: Loosestrife for my real friends Output: and real strife for my loose friends! Input: Ladybugs for my real friends Output: and real bugs for my lady friends! Input: Single-payer for my real friends Output: and RealPlayer for my single friends. Input: Tumbleweeds for my real friends Output: and real weed for my Tumblr friends! Input: Fauxhawks for my real friends Output: and real hawks for my faux friends! Input: Platonic solids for my real friends Output: and real solids for my platonic friends! ``` [Answer] # [Retina](https://github.com/m-ender/retina), 119 bytes The previous version didn't manage correctly the space in "platonic solids", this one works and is shorter :) ``` ew rw eds ed (\w+) ?([^oatr ]\w{3}.+)real and real $2$1 C S gne in o o- ti ty T`TL`Tl p\w+y.+ $&. s$ s! real -p RealPl ``` [Try it online!](https://tio.run/nexus/retina#dY7BSsQwEIbv8xQRqnQpLagP4GFhvfSwuL25Smc3024wzYQkJRbx2WvUa/YwzMA//8d3Wz73K0VwEUj6NFAeY7URT@XrO2Nw4u0Yvx6/m2rjCDWgkeL3EMVDcQ9bOMBoCJQBFsA1BAVhga7v2r7TYBNpaSoo7hrwBfgb@KvWFl7S3ut13V5wspgQYmAnpuWfPThFJsnsPc2SLUufjykEdU6S@bhl9uSDU0Oe3qJcTvOYLx@UGTXVFhdy2Ydunk6aItEVuR3OnxeMH1fUNQY26iw8a5Un/AA "Retina – TIO Nexus") This transforms the input into the output through a series of substitutions. The most interesting part is this substitution (kind of a regex golf): ``` (\w+) ?([^oatr ]\w{3}.+)real and real $2$1 ``` Which does almost all the job, by splitting the first word, placing its pieces in the right places, removing extra spaces, and building the structure of the output. To work correctly on the "Tumbleweeds" test case this depends on the previous substitution "eds"->"ed". The rest is mostly composed by substitutions that deal with special cases. Other interesting parts are: ``` T`TL`Tl ``` This turns everything except "T" (for Tumblr) to lowercase. ``` p\w+y.+ $&. s$ s! ``` This places a "." at the end of each sentence containing a word with a "y" some letters after a "p" ("petty" and "payer" in practice). Then places a "!" at the end of all sentences ending with an "s" (all the others). [Answer] # Python 2, 291 269 293 255 247 bytes *Thanks to `Erik the Outgolfer` for saving 22 bytes!* +24 bytes to account for some outputs ending in `.` instead of `!` ``` lambda x:'and '+['real '+'pain%ssham ,pods%spseudo-,coats%spetty ,strife%sloose ,bugs%slady ,weed%sTumblr ,hawks%sfaux ,solids%splatonic '.split(',')['noarsekc'.find(x[7])],'RealPlayer%ssingle ']['-'in x]%' for my '+x[-7:]+'!.'['-'in x or'tt'in x] ``` Simple solution to start things off. Checks the eighth letter of the input, as suggested in the comments, and looks up the corresponding output in a dictionary an array. [Try it Online!](https://tio.run/nexus/python2#hZExa8MwEIX3/orrYC4hctZAoVOhU4fQdnM9XKKzIyJLRpKJ8@vTs0I6FbSdeO/Eve/1rz83S8NBE8wvSE4DbhoMTFYGHMm4KsYTDaBGr2MVx8iT9rU6ekrLk1O6goopmI6raL2PDOow9aJZ0iJdmHUVv6fhYAOoE13OInU0zbLlrcl/WkremSPgVmaTVqhw3aDzFCKfj7jtjNOrudm161bhp9y2t3TlIJcZ11sGbBus0TiY2wqh8wGGq5w/N/Xupd3g8xYfOviAKd2ttzEYl6Bf4ZsEHKl3/NjN@btg2OmI66c/4z6nX0gUnQLGZEgl58fC7A6waBWiC9uS7ytjqccFUsmbm@GlpeK379JaLrAY/lHoveH/7bdf) [Answer] # [SOGL](https://github.com/dzaima/SOGL), 143 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` _╔x⅜²‘,8WWAa"⅞+1Tλ²⅞ƨ◄…χŗbdŗu8ņ∑Ι⅓I‼hzΔμō┘═q‼xΘ▼²ηpG⅔─┌¡↕+wd÷[≈┐α┌ļ○(‚δΦEΤα{‚φ▒k׀:╚s&⅛↑»‘ |Θwθ1w"ρ└⁸‘S∆∫⁴‘a1>*+oo"¤Ε○Φr‘o2w _@ŗo"æn‘o"χ}49⁶‘aWT ``` This uses this string as the main part. "|" are the splitters and "\_" are space placeholders so split would work correctly. ``` RealPlayer single_|weed Tumblr_|strife loose_|bugs lady_|pods pseudo-|pain sham_|solids platonic_|coats petty_|hawks faux_ ``` Input example: "Platonic solids for my real friends" Explanation: ``` ..‘,8WWAa"..‘ |Θwθ1w"..‘S∆∫⁴‘a1>*+oo"..‘o2w _@ŗo"..‘o"..‘aWT strings shortened ..‘ push "personcake" (the indexing string) ["personcake"] 8W get the 8-th char , from the input ["personcake", "c"] W get its in "personcake" (1-indexed) [7] Aa save on variable A [7] "..‘ push the long string [7, "RealPlayer...faux_"] |Θ split on "|" [7, ["RealPlayer single_", ..., "hawks faux_"]] w get the Ath item of the array [["..."], "solids platonic_"] θ split on spaces [["..."], ["solids", "platonic_"]] 1w get the 1st item [["..."], ["solids", "platonic_"], "solids"] "..‘ push "and " [["..."], ["solids", "platonic_"], "solids", "and "] S∆∫⁴‘ push "real " [["..."], ["solids", "platonic_"], "solids", "and ", "real "] a1>* multiply by A(index) > 1 [["..."], ["solids", "platonic_"], "solids", "and ", "real "] + join together [["..."], ["solids", "platonic_"], "solids", "and real "] o output [["..."], ["solids", "platonic_"], "solids"] o output (the 1st item of the array) [["..."], ["solids", "platonic_"]] "..‘o output " for my " [["..."], ["solids", "platonic_"]] 2w get the 2nd item of the array [["..."], ["solids", "platonic_"], "platonic_"] _@ŗ replace "_" with " " [["..."], ["solids", "platonic_"], "platonic "] o output that [["..."], ["solids", "platonic_"]] "..‘o output "friends" [["..."], ["solids", "platonic_"]] "..‘ push ".!!!!!!.!" [["..."], ["solids", "platonic_"], ".!!!!!!.!"] aW get the Ath item [["..."], ["solids", "platonic_"], "!"] T output, disabling implicit output [["..."], ["solids", "platonic_"]] ``` [Answer] # [Python 3](https://docs.python.org/3/), 788, 403, 359 396 bytes **Latest Version** This is now my fifth attempt. I've managed to half the size of my original program. It now includes the missing "-" and I believe is a complete solution. Still I suspect on the bulky side; but much closer to the goal. I've had **a lot of help**. Thanks for all the helpful guidance. ``` s=input() x=0 l= "Ch,pain,Sham,Ps,pods,psuedo-,Pe,coats,petty,Lo,strife,loose,La,bugs,lady,Si,RealPlayer,single,Tu,weed,Tumblr,Fa,hawks,faux,Pl,solids,platonic".split(",") a,b,c,d,e,f,g,h = " and real","for my","friends",".!","print(a,l[p+1],b,l[p+2]",",c+d[0])","+c+d[1])",",c+d[1])" for p in range(0,27,3): x+=1 if s[:2] == l[p]: if x == 2: eval(e+g) else: eval(e+f if x in(3,6) else e+h) ``` [Try it online!](https://tio.run/nexus/python3#bZGxbuMwEER7fcXGlQRNAtsBEsCAqgCpXAjxdYYKxlxJRGiSEKXE/nrfUs5dpYYc7iyGXL5brIwL05gX2aVaZ7ai1VuPoIzDoVdn1BHBa1nixNo/omacvBqlwON4xd4jjoNpGdb7yNgrfE5dhFX6ioPBBytbW3XlAdG4zjL@TPhh1rKfP@2Ad4Ve/XxFtGq6oLaI3pp0n1Wjd@a0eorBmjFfYVVkEo4TNBgtOvQkjyXlNA1yizS0fqDzNYnBsNNR1NODLGEwbswV7DGUm0Yyktg24uBU6uO6KUSWSW5miX8yS4mBjKNBuY7zNbaveC52GV3KapORaSked9uGqooksxEj1S7pvN0Rfyubc9kVUmYb@X@lvXcZlz/jpZg94rIvbrc3@fOgOsd0H2YejX7nyerIk/aJx7ItSMxMZ9HeJ0J3Wsu@MEvwFs3DTO8xJJSLDTNPTmiXA96F70x6@em/uOmOf6nnLw "Python 3 – TIO Nexus") --- **Original Posting** This is my first post on code golf so apologies in advance for my clumsy program. Can't see how a program could be made to convert "Champagne" to "pain", "sham" by parsing the words. However I would like to see someone else solve that. So, as my level of ability dictates that my program needs to know in advance that "Champagne" is "pain", "sham", there seemed little point in actually coding an input request. As a result I've left it out and been a bit literal with my print output. Hope that's ok : ) ``` phraseList= [ ("Champagne","pain","Sham"), ("Psudeopods","pods","psuedo-"), ("Petticoats","coats","petty"), ("Loosestrife","strife","loose"), ("Ladybugs","bugs","lady"), ("Single-payer","coats","petty"), ("Petticoats","RealPlayer","single"), ("Tumbleweeds","weed","Tumblr"), ("Fauxhawks","hawks","faux"), ("Platonic solids","real solids","platonic") ] for phrase in phraseList: print("Input: ",phrase[0], "for my real friends.") if "-" in phrase[2]: print("Output: and real", phrase[1], "for my", phrase[2]+ "friends!") else: print("Output: and real", phrase[1], "for my", phrase[2], "friends!") ``` [Answer] # [Röda](https://github.com/fergusq/roda), ~~299~~ ~~292~~ ~~288~~ 259 bytes *4 bytes saved thanks to @fergusq for using `,` instead of `..` in the `push` statements* *Bytes saved thanks to @fergusq showing me the way of `indexOf`* ``` h a{r=indexOf(a[7:8],"noarspekc")A="pain>pods>coats>strife>Player>bugs>weed>hawks>solids>sham >pseudo->petty >loose >lady >single >Tumblr >faux >platonic >!>!>.>!>!>.>!>!>!"/">";["and "];["Real"]if[r=4]else["real "];[A[r]," for my ",A[r+9],"friends",A[r+18]]} ``` [Try it online!](https://tio.run/nexus/roda#bVJNawIxEL37K8aclGqLUKi2GJBCT4VK29uyh2hm3WA2SZMsKuJvt7OxYg8hkMybN/mY93KuQRz9XBmJ@49qIIqn52k5YsYKHxxu12y4mDMnlOHOysDXVsTAQ/SqQr7U4oCer9pN4DtEyWux2xJrtaLSUIsGuAvYSjvmDmM8ANfWBqRFSAJBmY0m9N02K@2BV6Ld0w4tojVqDbxP4/7f3GcPjLOXggkjgZUUfKLQrFRV4eePJeqABfOUSuSi8NQIVNZDcwA2Inw3o0zlFRoZLonJtCxP54b6g2MPUrECAkXAn8FkNBuWIC0RAK7VGiLuY0L1LXRemcgYxdIa7J3Or9S4ExuD17vTk/6u7S2TIJ2YeZp0UknlLP3e6XeRP8@TsJ0fWfIr6T12nWvZgmQEdlbmD3gjg5LH@adfjbt8gFzNLw "Röda – TIO Nexus") So close to Python... so close.... ~~Your move, Python.~~ ### Explanation ``` h a{ r=indexOf(a[7:8],"noarspekc") /*Gets the index of the character in this string*/ /*Variable A contains all the unique words for each test case*/ A="pain>pods>coats>strife>Player>bugs>weed>hawks>solids>sham >pseudo->petty >loose >lady >single >Tumblr >faux >platonic >!>!>.>!>!>.>!>!>!"/">" ["and "] ["Real"]if[r=4]else["real "] /*RealPlayer*/ [A[r]," for my ",A[r+9],"friends",A[r+18]] /*Print everything using var A*/ } ``` [Answer] ## JavaScript (ES6), ~~230~~ ~~228~~ ~~221~~ 216 bytes ``` s=>'and '+((n='paonrsekc'.search(s[7]))?'real ':'')+'RealPl740s5 /450p3y /540p5-/pain0s3 /460l4 /340l3 /540T4r /350f3 /860p7 '.split`/`[n].replace(/\d\d?/g,n=>s.substr(n/10+1,n%10)||' for my ')+'friends'+'.!'[+(n>1)] ``` ### Test ``` let f = s=>'and '+((n='paonrsekc'.search(s[7]))?'real ':'')+'RealPl740s5 /450p3y /540p5-/pain0s3 /460l4 /340l3 /540T4r /350f3 /860p7 '.split`/`[n].replace(/\d\d?/g,n=>s.substr(n/10+1,n%10)||' for my ')+'friends'+'.!'[+(n>1)] console.log(f("Champagne for my real friends")); console.log(f("Pseudopods for my real friends")); console.log(f("Petticoats for my real friends")); console.log(f("Loosestrife for my real friends")); console.log(f("Ladybugs for my real friends")); console.log(f("Single-payer for my real friends")); console.log(f("Tumbleweeds for my real friends")); console.log(f("Fauxhawks for my real friends")); console.log(f("Platonic solids for my real friends")); ``` [Answer] # PHP, 202 220 204 203 bytes ``` and real <?=[pods,solids,hawks,strife,RealPlayer,pain,bugs,weed,coats][$q=md5($argv[1].LnI)%9].' for my '.[pseudo,platonic,faux,loose,single,sham,lady,Tumblr,petty][$q].' -'[!$q].friends.'.!'[!$q||$q&3]; ``` [Answer] # Perl, ~~173~~ 168 bytes Removing newlines and indentations, this becomes 173 bytes of Perl5 code. Shamelessly stole first regexp from Leo's Retina answer. (Mine was a few chars longer) ``` sub f{ my($_)=@_; s,(\S+[oieyxm ])(\S{4}.+)real,and real $2\l$1,; s,gne,in,; s,ch,sh,; s,ti,ty,; s,eds,ed,; s,tumble,Tumblr,; s,real -p,RealPl,; s,o ,o-,; s,c ,c,; /ng|tt/?"$_.":"$_!" } ``` For perl5 version >= 5.14 another 5 bytes can be shaved off with eval and the new /r regexp substitution modifier. Ending up with 168 bytes: ``` sub f{my($_)=@_;eval's,(\S+[oieyxm ])(\S{4}.+)real,and real $2\l$1Xgne,inXch,shXti,tyXeds,edXtumble,TumblrXreal -p,RealPlXo ,o-Xc ,c,;/ng|tt/?"$_.":"$_!"'=~s/X/,;s,/gr} ``` [Try it online!](https://tio.run/nexus/perl5#lZRdb5swFIbv9ytOLSSCakDtuq9EVSdN2tUuqnUXSKGKHDBgxdgMm7Uozf71rjMbRBomLgYSyOac53059jEAAJmsF@srDO6XgpQVyQW1r6BsoaaEQ1YzKlLl4jdwdrlEpH28IkwMgDIKA3DhPr4i62ujf69ok8pKpmqewRlQdRL@pMVba0G1Zokkep7FiKiMRjsgwcjixlh8k1JRpWuWzVunMcKtyvRSvbMmJG23TT6vinOAG4Fp@fdG/oGJnFO/Ii2t/9fiu4nf83NCdSrTK/XBuPxoyi2nT5TO3HBLDECnUU9X8tF4fCXNc0GedvMcRkRmJKYNPtmO4kRLwRJQkrOZhYyRalB69fL2J7JsF47ADjO3bLR3@9nZrE7BqmZCA7JDkxELO0BBtjATL0CxcASgf7OtDNCf0GfBHSC5iwWCJSAhNcgdNsdVNjyFLV122SbaixyOqtlCtl84G/MhmxX9Rbir8CJ@uFxLRtvnEh49M9vfHIJLz5aKTzU71zF3riLzF8FMREmBVRFphnUbmTbANI101xW439ioY/wK990VScDSjxLACV6FIn/ROrxDziZAS/O8QO7tbxVGIV4pHOb14Xj8I6SfkKSgfwE "Perl 5 – TIO Nexus") [Answer] # C, 367 bytes Didn't end up as short as it seemed it would. ``` i,j,c;f(char*s){c=s[7]-97;char t[9],u[200];char*r=s;s+=j=c&&c-17?c-10&&c-18?c-2?5:8:3:4;for(i=0;*++s-32;t[i++]=*s);t[c-4?i:i-1]=0;for(i=0;*r++-t[0];)u[i++]=*(r-1);u[i]=32;u[i+1]=0;u[0]+=32;u[c?i:i-1]=c?c-2?c-14?32:45:0:121;printf("and %s%s for my %sfriends%c",c-15?"real ":"RealPlayer",c-15?c-13?t:"pain":"",c-13?c-4?c-17?u:"loose ":"Tumblr ":"sham ",c&&c-15?33:46);} ``` [Answer] # Java 7, ~~585~~ 553 bytes ``` import java.util.*;String c(String s){Map m=new HashMap(){{put("Ch","pain");put("Ps","pods");put("Pe","coats");put("Lo","strife");put("La","bugs");put("Si","Player");put("Tu","weed");put("Fa","hawks");put("Pl","solids");put("Ch1","sham ");put("Ps1","pseudo-");put("Pe1","petty ");put("Lo1","loose ");put("La1","lady ");put("Si1","single ");put("Tu1","Tumblr ");put("Fa1","faux ");put("Pl1","platonic ");}};String r=s.substring(0,2);int c=r.charAt(1);return"and "+(c=='i'?"Real":"real ")+m.get(r)+" for my "+m.get(r+1)+"friends"+(c=='i'|c=='e'?'.':'!');} ``` -32 bytes thanks to *@Zircon*. Can definitely be golfed by using something different than a Map.. **Explanation:** ``` import java.util.*; // Import required for the Map & HashMap String c(String s){ // Method with String parameter and String return-type Map m=new HashMap(){{ // The Map put("Ch","pain");put("Ps","pods");put("Pe","coats");put("Lo","strife");put("La","bugs");put("Si","Player");put("Tu","weed");put("Fa","hawks"); // Add mapping from first two characters with first word put("Ch1","sham ");put("Ps1","pseudo-");put("Pe1","petty ");put("Lo1","loose ");put("La1","lady ");put("Si1","single ");put("Tu1","Tumblr ");put("Fa1","faux ");put("Pl1","platonic "); // Add mapping from first two characters + "1" with second word (+ space or '-' for edge-case `pseudo-friends`) }}; // End of Map initialization String r=s.substring(0,2); // Get the first two characters of the input String int c=r.charAt(1); // Get the second character return "and " // return "and " + (c=='i'?"Real":"real ") // + "Real" or "real " for edge-case `RealPlayers` + m.get(r) // + first word from Map + " for my " // + " for my " + m.get(r+1) // + second word from Map + "friends" // + "friends" + (c=='i'|c=='e' ? '.' // + '.' for edge-cases 'Petticoats' and 'Single-player : '!'); // or '!' for all other cases } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#nZM9b9swEIZ3/wqWi6Q6EeqOEYSgCBB0SACj8lZ0OEu0xZZf4Edcw/Vvd4@MlXDKIC0UH/J4L3nvXbg02nryG16gDp6L@nOz6AU4R55PC0KcB8970nnL1Z705fXHVadnMES2ih3Id3AjzsqqkbUJvqQPI72hBriib2jtItKDyxBD1GvwGXvSyBzm2LEMAsJt2Gf7Oo5oLeDI7DvcBIQHxoZ39BhDRzj8yfOKmEMLnot5GFeRjiBJLjpC41gY9G0uPGHm/ZHk0iMVWjuWU0gUhnxrx1MyfEiR792EiDdBboUl@R0i3kH4m0sTSYMArxXWBxeulbGtq13YujQrv9x8rRquPOlbW/cj2G@@XFWNZT5YRUENhC7Lvm0LXtzTHwwEvaMWBzxwKes986WtlpTstCUSbzCx5QrpznKm8A2nA/7FgRX3RV3cFZ@Kqjmjf@KHgwlbgTKvbnrRfCAS/XG1089fBKpT2t0dnWey1sHXBpe8UGUfqwPSwF6xSUnSOAmoquaD2HUqX7TenGAsMk8enRH8FL3wauY50eiZaPoZoV1y1q1J/TEjPlmQxU6ak/0RnZpabs57T4Z@7c8PTjgvzpfLfw) (ideone.com is bugged lately, so I'm using TIO now..) ``` import java.util.*; class M{ static String c(String s){Map m=new HashMap();m.put("Ch","pain");m.put("Ps","pods");m.put("Pe","coats");m.put("Lo","strife");m.put("La","bugs");m.put("Si","Player");m.put("Tu","weed");m.put("Fa","hawks");m.put("Pl","solids");m.put("Ch1","sham ");m.put("Ps1","pseudo-");m.put("Pe1","petty ");m.put("Lo1","loose ");m.put("La1","lady ");m.put("Si1","single ");m.put("Tu1","Tumblr ");m.put("Fa1","faux ");m.put("Pl1","platonic ");String r=s.substring(0,2);int c=r.charAt(1);return"and "+(c=='i'?"Real":"real ")+m.get(r)+" for my "+m.get(r+1)+"friends"+(c=='i'|c=='e'?'.':'!');} public static void main(String[] a){ System.out.println(c("Champagne for my real friends")); System.out.println(c("Pseudopods for my real friends")); System.out.println(c("Petticoats for my real friends")); System.out.println(c("Loosestrife for my real friends")); System.out.println(c("Ladybugs for my real friends")); System.out.println(c("Single-player for my real friends")); System.out.println(c("Tumbleweeds for my real friends")); System.out.println(c("Fauxhawks for my real friends")); System.out.println(c("Platonic solids for my real friends")); } } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 311 bytes Clear patterns, but so many exceptions. Still, there must be a better way than this! ``` f(char*s){char*t="\"5$#(=931",*r[]={"pain", "sham","pods","pseudo","coats","petty","strife","loose","bugs","lady","Player","single","weed","Tumblr","hawks","faux","solids","platonic"};int i=strchr(t,*s^s[2])-t;printf("and %s%s for my %s%cfriends%c",i^5?"real ":"Real",r[i*2],r[i*2+1],i^1?32:45,i^5&&i^2?33:46);} ``` [Try it online!](https://tio.run/##fZJNa8MwDIbPza8I2lbSLD00aQdLCD0MBoPByrZbP8BNnMQsdYLt0JXS395JbntcTq9svbZkPc7GZZadz4WXVUz5enS0alJYwez@zkufowkEvlqu0yO0TEgIXNAV20EAbZNrEs27vMEga5ixG9yYA6o2ShQcg7ppNOm2Kylfs5zSi5oduCKfkGVN@T3nOcp3t9vWlKjY/ocOFKz7JV9Ti0vFmplGigxOiZDGFSlWyirlmcDXG70M16OxSVqFucIDJnP3QT9ot2iUuztQnBVKcJljAIHYzOagOKtdiOETFQK1FH64vsjjZI2WyTwK4@mMzMOh2ITzKIqnT6PkdC7t3FwcnHN0Breab7LtTIylVvKjMzbGuelR4gwKzwruaQ9WEnBxchx6xg6n69lrSg9ecMQtKyW/tW1bvPZNh8i0sJMnDL0uxCEsmz7XOzG6EOu1ITvC2Of5sjzHLeHt81nOnKD3XveK9O1P6H3k9Uu4l0/yn/V0/gM "C (gcc) – Try It Online") ]
[Question] [ Since the first weekend of October is drawing near, let's have our own Oktoberfest! ## Background You and some other programmers have been hired by the local sausage guys in Munich, Germany. The sausage guys provide Oktoberfest with all the sausages the giant Volksfest needs. You manage to overhear your boss speaking to the other employees about why you and the others were hired without any previous sausage-related experience. You realize you were hired for your impeccable programming skills - and your boss apparently wants you to code a sausage analyzer. This year around, the sausage guys have decided to increase the variety of sausages at Oktoberfest - but they have no idea of how much they've imported. ## Challenge You need to help your boss figure out how much sausage of a certain kind they've actually imported. You will have to program a sausage analyzer which outputs the kind and number of every sausage the sausage guys have imported. Your boss has bought a special floppy drive for this occasion which, given a sausage, pipes it to `stdin`. ## Input A number of sausages on `stdin`, each sausage separated by one space. Sausages are given on the following format: **Prinskorv (P)** ``` ¤ | | | | | | ¤ ``` **Salchichón (S)** ``` l | | | | | | | | l ``` **Landjäger (L)** ``` \ / | | | | | | | | / \ ``` **Kabanos (K)** ``` . | | | | | . ``` **Cotechino Modena (C)** ``` ___ | | | | | | |___| ``` **Rød pølse (R)** ``` ^ | | | | | | | | v ``` ## Output The occurrences of a given sausage along with an identifier of which kind of sausage it is, separated by a space. The identifier is the first letter in the name of the sausage. Order is not important. Output shall be written to `stdout`, trailing newlines and spaces are allowed. ## Examples **Input** ``` ^ ^ ^ ^ . | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | v v v v | . ``` **Output** ``` 4R 1K ``` **Input** ``` \ / ___ l ¤ ¤ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |___| | | ¤ ¤ / \ l ``` **Output** ``` 1L 1C 1S 2P ``` **Input** ``` l ¤ l | | | | | | | | | | | | | | | | | | | | ¤ | | l l ``` **Output** ``` 2S 1P ``` The programmer with the shortest program in bytes gets paid by the sausage guys (wins)! # Sausage trivia > > > **Prinskorv** > > *Prinskorv which directly translates to "prince-sausage" is a small Swedish sausage which is often sold in links. Usually fried in a frying pan and served with a generous helping of mustard.* > > > > **Salchichón** > > *Salchichón is a Spanish summer sausage often made with pork, although some recipes use other meats including ox, veal or horse. The meat and fat are chopped in thin bits, seasoned with salt, pepper, nutmeg, oregano, and garlic and then inserted in thick natural pork intestines.* > > > > **Landjäger** > > *Landjäger is a semi-dried sausage traditionally made in Southern Germany, Austria, Switzerland, and Alsace. It is popular as a snack food during activities such as hiking. It also has a history as soldier's food because it keeps without refrigeration and comes in single-meal portions.* > > > > **Kabanos** > > *Kabanos is a Polish long thin dry sausage made of pork or kosher turkey. They are smoky in flavour, and can be soft or very dry in texture depending on freshness. Kabanosy are often seasoned only with pepper. Unlike other meats, these sausages are typically eaten alone as an appetiser and, except when kosher, often served with cheese.* > > > > **Cotechino Modena** > > *Cotechino Modena or Cotechino di Modena is a fresh sausage made from pork, fatback, and pork rind, and comes from Modena, Italy, where it has PGI status. Cotechino is often served with lentils or cannellini beans with a sauce alongside mashed potatoes, especially around the New Year.* > > > > **Rød pølse** > > *Rød pølse (red sausage) is a type of brightly red, boiled pork sausage very common in Denmark. Since hot dog stands are ubiquitous in Denmark, some people regard røde pølser as one of the national dishes.* > > > > *All sausage information shamelessly copied from Wikipedia* > > > [Answer] # Pyth, ~~36~~ ~~34~~ ~~32~~ 30 bytes ``` XjdsMrShM-czd\\8"¤_l/^.KRLSCP ``` Saved yet *another* 2 bytes thanks to...guess who? :D Ignores all the input except for the first line, removes all the `/`s and spaces, translates it to the target identifiers, sorts it, uses run-length encoding, and prints the result. [Live demo.](https://pyth.herokuapp.com/?code=XjdsMrShM-czd%5C%5C8%22%C2%A4_l%2F%5E.KRLSCP&input=%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l&test_suite=1&test_suite_input=+%5E+++%5E+++%5E+++%5E++.%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A+v+++v+++v+++v++%7C%0A++++++++++++++++.%0A%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l%0A%0A+l+++%C2%A4+++l%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C++%C2%A4++%7C+%7C%0A+l+++++++l%0A&debug=1&input_size=7) ## 32-byte version ``` XjdsMrS-hMfTczd\\8"¤_l/^.KRLSCP ``` [Live demo.](https://pyth.herokuapp.com/?code=XjdsMrS-hMfTczd%5C%5C8%22%C2%A4_l%2F%5E.KRLSCP&input=%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l&test_suite=1&test_suite_input=+%5E+++%5E+++%5E+++%5E++.%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A+v+++v+++v+++v++%7C%0A++++++++++++++++.%0A%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l%0A%0A+l+++%C2%A4+++l%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C++%C2%A4++%7C+%7C%0A+l+++++++l%0A&debug=1&input_size=7) Saved another 2 bytes thanks to @Jakube! ## 34-byte version ``` jdsMrSX-hMfTczd\\"¤_l/^.KRLSCP")8 ``` [Live demo.](https://pyth.herokuapp.com/?code=jdsMrSX-hMfTczd%5C%5C%22%C2%A4_l%2F%5E.KRLSCP%22%298&input=%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l&test_suite=1&test_suite_input=+%5E+++%5E+++%5E+++%5E++.%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A+v+++v+++v+++v++%7C%0A++++++++++++++++.%0A%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l%0A%0A+l+++%C2%A4+++l%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C++%C2%A4++%7C+%7C%0A+l+++++++l%0A&debug=1&input_size=7) Saved 2 bytes thanks to @Jakube! ## 36-byte version ``` jdsMrSX-hMfTczd\/"¤_l\\^.""PCSLRK"8 ``` [Live demo.](https://pyth.herokuapp.com/?code=jdsMrSX-hMfTczd%5C%2F%22%C2%A4_l%5C%5C%5E.%22%22PCSLRK%228&input=%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l&test_suite=1&test_suite_input=+%5E+++%5E+++%5E+++%5E++.%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A+v+++v+++v+++v++%7C%0A++++++++++++++++.%0A%5C+%2F++___+++l+++%C2%A4+++%C2%A4%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+++%7C+%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C___%7C+%7C+%7C++%C2%A4+++%C2%A4%0A%2F+%5C++++++++l%0A%0A+l+++%C2%A4+++l%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C+%7C+%7C+%7C+%7C%0A%7C+%7C++%C2%A4++%7C+%7C%0A+l+++++++l%0A&debug=1&input_size=7) [Answer] # Pyth, 30 bytes ``` jdm+hd@"SKLCRP"%Ced45rS-czd\/8 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jdm%2Bhd%40%22SKLCRP%22%25Ced45rS-czd%5C/8&test_suite_input=%20%5E%20%20%20%5E%20%20%20%5E%20%20%20%5E%20%20.%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%20v%20%20%20v%20%20%20v%20%20%20v%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.%0A%5C%20/%20%20___%20%20%20l%20%20%20%C2%A4%20%20%20%C2%A4%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C___%7C%20%7C%20%7C%20%20%C2%A4%20%20%20%C2%A4%0A/%20%5C%20%20%20%20%20%20%20%20l%0A%0A%20l%20%20%20%C2%A4%20%20%20l%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%20%C2%A4%20%20%7C%20%7C%0A%20l%20%20%20%20%20%20%20l%0A&input_size=7&test_suite=0&input=%5C%20/%20%20___%20%20%20l%20%20%20%C2%A4%20%20%20%C2%A4%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C___%7C%20%7C%20%7C%20%20%C2%A4%20%20%20%C2%A4%0A/%20%5C%20%20%20%20%20%20%20%20l) or [Test Suite](http://pyth.herokuapp.com/?code=jdm%2Bhd%40%22SKLCRP%22%25Ced45rS-czd%5C/8&test_suite_input=%20%5E%20%20%20%5E%20%20%20%5E%20%20%20%5E%20%20.%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%20v%20%20%20v%20%20%20v%20%20%20v%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.%0A%5C%20/%20%20___%20%20%20l%20%20%20%C2%A4%20%20%20%C2%A4%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C___%7C%20%7C%20%7C%20%20%C2%A4%20%20%20%C2%A4%0A/%20%5C%20%20%20%20%20%20%20%20l%0A%0A%20l%20%20%20%C2%A4%20%20%20l%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%20%C2%A4%20%20%7C%20%7C%0A%20l%20%20%20%20%20%20%20l%0A&input_size=7&test_suite=1&input=%5C%20/%20%20___%20%20%20l%20%20%20%C2%A4%20%20%20%C2%A4%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C___%7C%20%7C%20%7C%20%20%C2%A4%20%20%20%C2%A4%0A/%20%5C%20%20%20%20%20%20%20%20l) ### Explanation: As all other participants I only look at the first line of the input. Let's say the first line of the input is `\ / ___ l ¤ ¤ ____`. At first I split by spaces, which gives me the list ``` ['\\', '/', '', '___', '', '', 'l', '', '', '¤', '', '', '¤', '', '___'] ``` Now we want to get ride of `'/'`s and `''`s and sort the remaining thing. ``` ['\\', '___', '___', 'l', '¤', '¤'] ``` Now I can run-length-encode it. ``` [[1, '\\'], [2, '___'], [1, 'l'], [2, '¤']] ``` As it turns out, the order (ascii-value) of these chars or of the string `'___'` can be mapped nicely to the numbers `[0, 1, 2, 3, 4, 5]`. ``` char/string | l . \ ___ ^ ¤ ------------------------------------------- value | 108 46 92 6250335 94 164 value%45 | 18 1 2 15 4 29 (value%45)%6| 0 1 2 3 4 5 ``` And this can be used to map them directly to the letters `SKLCRP`. ``` jdm+hd@"SKLCRP"%Ced45rS-czd\/8 czd split the input string at spaces - \/ remove "/"s (and also ""s) S sort r 8 run-length-encode m map each pair d of ^ to: +hd d[0] + Ced convert d[1] to a number % 45 mod 45 @"SKLCRP" take the ^th element in the string (mod 6) jd join by spaces ``` [Answer] # Javascript (ES6), 105 ``` a=>[...'¤l/._^'].map((g,h)=>(f=(a.split(g).length-1)/'222261'[h],f?f+'PSLKCR'[h]:0)).filter(b=>b).join` ` ``` It's pretty simple but here's an explanation anyway: ``` input=> // list of all unique characters of the sausages [...'¤l/._^'].map((sausage_char, index)=>( // find all occurrences of the character in the string occurrences = (input.split(sausage_char).length - 1) / '222261'[index], // divide by the number of that character in its sausage // when dividing and multiplying by numbers in strings, JS automatically casts them occurrences ? // is there anything for this sausage? occurrences + 'PSLKCR'[index] : // add the sausage's letter and count 0 // return 0 so it can be filtered out )) // filter out the 0s .filter(b=>b) // return a space-separated string .join` ` ``` [Answer] # CJam, ~~38~~ ~~35~~ 33 bytes ``` l'_%'C*"l¤\^./""SPLRK "erS-$e`S* ``` [Test it here.](http://cjam.aditsu.net/#code=l'_%25'C*%22l%C2%A4%5C%5E.%2F%22%22SPLRK%20%22erS-%24e%60S*&input=%20l%20%20%20%C2%A4%20%20%20l%20%5C%20%2F%20%20___%20%20%20l%20%20%20%C2%A4%20%20%20%C2%A4%20%20%5E%20%20%20%5E%20%20%20%5E%20%20%20%5E%20%20.%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%20%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%7C%20%7C%20%20%C2%A4%20%20%7C%20%7C%7C%20%7C%20%7C___%7C%20%7C%20%7C%20%20%C2%A4%20%20%20%C2%A4%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%20%7C%0A%20l%20%20%20%20%20%20%20l%20%2F%20%5C%20%20%20%20%20%20%20%20l%20%20%20%20%20%20%20%20%20%20v%20%20%20v%20%20%20v%20%20%20v%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.) ## Explanation The first line of each type of sausage is unique, and since the sausages are aligned at the top, it's sufficient to count the relevant characters in that first line. Two types require special treatment: * **Landjäger (L)** have both `\` and `/`. We want to get rid of one of them, then we can count the other one like all the other characters. * **Cotechino Modena (C)** have three underscores, so we need to divide the underscore count by 3. However, it's actually shorter to treat underscores individually by simply replacing runs of them in the input (which will always belong to only one sausage) with the target character `C` right away. Now for the actual code: ``` l e# Read one line from STDIN. '_% e# Split on runs of underscores. 'C* e# Join back together by C's. "l¤\^./" e# Push a string with characters corresponding to each type, and a slash. "SPLRK " e# Push a string with the corresponding letters and a space. er e# Transliterate, turning each identifying character into the correct e# letter and all slashes into spaces. S- e# Remove spaces (which also gets rid of what used to be slashes). $ e# Sort the string to group each letter. e` e# Run-length encode. S* e# Join by spaces. ``` [Answer] # Mathematica 116 Some bytes could probably shaved off, but nothing to approach the golfing languages. ``` Row[Row/@Reverse/@Tally@ImportString[#,"Table"][[1]]/.{"¤"->"P","l"->"S","/"->"L","___"->"C","."->"K","^"->"R"}," "] & ``` `ImportString[#,"Table"][[1]]` returns a list of space-separated strings appearing in the top line of the input. The string may include any of the elements in the list, `{"¤","l","/","___",".","^"}`, including repeats. Each element is associated with a unique type of sausage. `Tally` counts the number of times each such string appears. `/.{"¤"->"P","l"->"S",...` replaces `¤` with `P`, `l` with `S` and so on. `Reverse` places each tally before the item it is associated with. The two `Row`s format the output. [Answer] # MATLAB, 113 Assuming that trailing spaces are allowed (yep they are), here is a MATLAB anonymous function: ``` @(a)arrayfun(@(p,m)fprintf([(m>32&&p)*'%d%c ' ''],p,m),histc(strtok(strrep(a,'___','_'),10),'./\^_l¤'),'K LRCSP') ``` And an explanation: ``` @(a) %Anonymous function, with an input a arrayfun(@(p,m) %Loop through the two input arrays (see later) fprintf( %Print to console [(m>32&&p)*'%d%c ' ''] %Essentially this means if p>0 and m>' ', print an integer followed by a char, then a space ,p,m) %The values from the array input is what is getting printed ,histc( %Make an array of how many times strtok(strrep(a,'___','_'),10), %Keep only the first line (as that is where the interesting bit is) and also replace ___ with _ for the 'C' './\^_l¤'), %these inputs appear (which will be passed in turn as the 'p' variable to cellfun) 'K LRCSP' %These are the characters to be printed with the count representing each sausage (it will be placed in the 'm' input of arrayfun) ) ``` Appears to work correctly. Still has the trailing space, but now handles all sausages correctly. [Answer] ## Perl, ~~84~~ 77 bytes Someone could probably shave a bit off of this... ## 84 bytes ``` ($s=<>)=~y|_^\.l\\¤|CRKSLP|d;$$_++for split//,$s;$C/=3;for(A..Z){print"$$_$_ "if$$_} ``` ## 77 bytes ``` $$_++for split//,<>=~y|_^\.l\\¤|CRKSLP|dr;$C/=3;for(A..Z){print"$$_$_ "if$$_} ``` Breakdown: Take first line of STDIN, transliterate values into letter codes, delete extra garbage. The `d` modifier shouldn't really be necessary, but I ran into weird unicode issues on the `¤` character without it. Use symbolic reference to create and/or increment variable for each character found. ``` $$_++ for split //, <> =~ y|_^\.l\\¤|CRKSLP|dr; ``` Divide C variable by 3, due to triple-underscore ``` $C /= 3; ``` Loop through alphabet and print single-letter capital variables along with letter *if* they have a value greater than zero ``` for (A..Z) { print "$$_$_ " if $$_; } ``` Test result: <http://ideone.com/alpUlI> **Edit**: Chop 7 bytes by having transliterate pass anonymous return value directly into `split`. [Answer] ## Perl, 172 bytes Daresay more can be sliced off this sausage still, but here's a starter for ten. ``` $a=<>;$a=~s/¤/h/g;$a=~s/_+/_/g;$a=~s/(\/| |\n)//g;$a=~s/\\/x/g;$h{$_}++ for split(//,$a);foreach (sort keys %h){print $h{$_};$_=~tr/^.hlx_/RKPSLC/;print "$_ ";}print "\n" ``` Ungolfed version ``` $a=<>; # get 1st line $a=~s/¤/h/g; # convert ¤ to h, avoid unicode hassles $a=~s/_+/_/g; # multiple consecutive _ to single _ $a=~s/(\/| |\n)//g; # strip / and spaces $a=~s/\\/x/g; # convert \\ to x to avoid regexp hassles # build hash that counts occurences of character $h{$_}++ for split(//,$a); # print the answers foreach (sort keys %h) { print $h{$_}; $_=~tr/^.hlx_/RKPSLC/; print "$_ "; } print "\n"; ``` Test results ``` $ perl meaty.pl <test1.txt 1K 4R $ perl meaty.pl <test2.txt 1C 2P 1S 1L $ perl meaty.pl <test3.txt 1P 2S $ ``` [Answer] ## Python 3, 120 bytes I'm pretty sure you can shorten this, but there wasn't already a Python solution so here we go: ``` x=input() a={z:x.count(y)for y,z in zip('¤l/.^_','PSLKRC')} a['C']//=3 print(' '.join(str(a[x])+x for x in a if a[x])) ``` ## Explanation It's pretty simple, some might even say readable, but here's a short explanation anyway: First one line of input is read, since each sausage can be determined from just the first line. Now `a={z:x.count(y)for y,z in zip('¤l/.^_','PSLKRC')}` is a dictionary comprehension that maps the identifier of each type of sausage (`z`) to the count of each type of sausage (`x.count(y)`, where `y` is the sausage defining character). We then divide the count of **Cotechino Modena (C)** sausages by 3 because of the triple underscore. Finally we print out the result: `print(' '.join(str(a[x])+x for x in a if a[x]))`. This creates the output count of each sausage one at a time, but only if that sausage was seen at least once (`a[x]` is not zero => Truthy). Each count string is joined by a space and printed out. ]
[Question] [ Write a program to calculate the first 500 digits of pi, meeting the rules below: * It must be less than 500 characters in length. * It cannot include "pi", "math.pi" or similar pi constants, nor may it call a library function to calculate pi. * It may not use the digits "3", "1" and "4" consecutively. * It must execute in a reasonable time (under 1 minute) on a modern computer. The shortest program wins. [Answer] ## Golfscript - 29 chars ``` 6666,-2%{2+.2/@*\/9)499?2*+}* ``` I will post analysis later [Answer] # Mathematica (34 chars): (without "cheating" with trig) `N[2Integrate[[1-x^2]^.5,-1,1],500]` So, to explain the magic here: `Integrate[function, lower, upper]` gives you the area under the curve "function" from "lower" to "upper". In this case, that function is `[1-x^2]^.5`, which is a formula that describes the top half of a circle with radius 1. Because the circle has a radius of 1, it does not exist for values of x lower than -1 or higher than 1. Therefore, we are finding the area of half of a circle. When we multiply by 2, then we get the area inside of a circle of radius 1, which is equal to pi. [Answer] # Python (83 chars) ``` P=0 B=10**500 i=1666 while i:d=2*i+1;P=(P*i%B+(P*i/B+3*i)%d*B)/d;i-=1 print'3.%d'%P ``` [Answer] ## Python3 136 Uses [Madhava's](http://en.wikipedia.org/wiki/Madhava_of_Sangamagrama#The_value_of_.CF.80_.28pi.29) formula. ``` from decimal import * D=Decimal getcontext().prec=600 p=D(3).sqrt()*sum(D(2-k%2*4)/3**k/(2*k+1)for k in range(1100)) print(str(p)[:502]) ``` ## Python3 164 Uses [this](http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula) formula. ``` from decimal import * D=Decimal getcontext().prec=600 p=sum(D(1)/16**k*(D(4)/(8*k+1)-D(2)/(8*k+4)-D(1)/(8*k+5)-D(1)/(8*k+6))for k in range(411)) print(str(p)[:502]) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~28~~ ~~25~~ 24 bytes ``` i*!500İ⁰ΣG*2mṠ/o!İ1→ḣ□70 ``` [Try it online!](https://tio.run/##AS0A0v9odXNr//9pKiE1MDDEsOKBsM6jRyoybeG5oC9vIcSwMeKGkuG4o@KWoTcw//8 "Husk – Try It Online") Calculates the value of pi as a rational number using the first 5000 terms of the infinite series `2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))`, and then extracts the first 500 digits. The code to calculate the value of pi from a specified number of terms is only 13 bytes (`ΣG*2mṠ/o!İ1→ḣ`): ``` ΣG*2mṠ/o!İ1→ḣ Σ # the sum of G*2 # the cumulative product, starting at 2, of m # mapping the following function to all terms of ḣ # series from 1 to ... (whatever number is specified) Ṡ/ # divide by x o! → # element at index -1 İ1 # of series of odd numbers ``` Unfortunately, we then need to waste 3 bytes specifying the number of terms to use: ``` □70 # 70^2 = 4900 ``` And then 8 more bytes converting the rational number (expressed as a fraction) into its digits in decimal form: ``` i*!500İ⁰ i # integer value of * # multiplying by !500 # 500th element of İ⁰ # series of powers of 10 ``` [Answer] # Java 10, ~~208~~ ~~207~~ ~~206~~ ~~193~~ ~~176~~ 155 bytes ``` n->{var t=java.math.BigInteger.TEN.pow(499).shiftLeft(1);var p=t;for(int i=1656;i>0;)p=t.add(p.multiply(t.valueOf(i)).divide(t.valueOf(i-~i--)));return p;} ``` -14 bytes thanks to *@ceilingcat*. -17 bytes thanks to *@jeJe*. [Try it online.](https://tio.run/##bZAxa8MwEIX3/IobpcFHA20gCGcIdCi06ZDSpXRQbdk5V5aFfFIJwf3rrkwzdOhycPfeg@9dp5MuuvpzrqweR3jS5C4rAHJsQqMrA4dlBeiyD3vNJ9xT@5DV1gSoxOtANSSpsmda5TGyZqrgAA5KmF2xuyQdgMv/4vhyf0A/fInb7VbieKKGH03DYi3VEvIlq2YIIqMAlevN3UbR7kbJfEdd18JjHy2Tt2fBmLSN5rkRJCXWlKg2f4/FNxWFlFIFwzE48Gqa1YLr44fNuFfqtJTp8wfEkQO59u0dtPytfzyPbHocIqPPElsnHFbCRWvltf00/wA) **Or as full program (203 bytes):** ``` interface M{static void main(String[]a){var t=java.math.BigInteger.TEN.pow(499).shiftLeft(1);var p=t;for(int i=1656;i>0;)p=t.add(p.multiply(t.valueOf(i)).divide(t.valueOf(i-~i--)));System.out.print(p);}} ``` [Try it online.](https://tio.run/##Tc49iwIxEMbxr5IyU@ygcCdIWAvB4kDvCu3EYjDJ7qz7ErKzOUT0q@/lOts//HiehhIVjb3NM/fioqerU4fHKCR8VWlgqzriXh8lcl@dLwSPRFFJ2WSHHUmNW66@Mq1cxNPuG8Pwqz/Wa8CxZi9750UvwfyjUIrxQ9R5SHG5XH2uDG8WBnJHslYH7KZWOLR3LZiondyP1wyAlhNb9x6LFxcFAJjjfRTX4TAJhvxQdADzfM7zHw) [Answer] ## Mathematica (17 bytes) ``` N[ArcCos[-1],500] ``` [Proof of validity](http://www.wolframalpha.com/input/?i=N%5BArcCos%5B-1%5D,%20500%5D%20==%20N%5BPi,%20500%5D&t=ff3tb01). [Answer] ## PARI/GP, 14 ``` \p500 acos(-1) ``` You can avoid trig by replacing the second line with ``` gamma(.5)^2 ``` or ``` (6*zeta(2))^.5 ``` or ``` psi(3/4)-psi(1/4) ``` or ``` 4*intnum(x=0,1,(1-x^2)^.5) ``` or ``` sumalt(k=2,(-1)^k/(2*k-3))*4 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 ``` u+/*GHhyHy^T500r^3T1Z ``` Uses this algorithm: `pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))` found in the comments of the Golfscript answer. [Answer] # [Raku](https://raku.org/), 44 bytes ``` (2.FatRat,{++$*$_/(2*++$+1)}...*)[^1658].sum ``` [Try it online!](https://tio.run/##K0gtyjH7X5xY@V/DSM8tsSQosUSnWltbRUslXl/DSAvI0jbUrNXT09PSjI4zNDO1iNUrLs39DySSikuKNAx0FEwNjDT/AwA "Perl 6 – Try It Online") A search for a series that quickly converges to pi led to [this](https://math.stackexchange.com/a/14116/16422) Math StackExchange answer, which I implemented in Raku. The series consists of FatRats, which is Raku's unlimited-precision rational number type. A little calculation and trial and error showed that 1,658 terms are sufficient to obtain 500 decimal places of accuracy. [Answer] # Fortran, ~~154~~ 144 bytes Mangled the [rosetta code](https://rosettacode.org/wiki/Pi#Fortran) solution. Saved lots of bytes using implicit integers `i j k l m n`, `print` instead of `write`, and shuffling things around. [Try it online!](https://tio.run/##NY3NCoQgFEb3PcXsUtPJW7hJ7nIW8xgDWZg/DRLh2ztJzObjcDjwLXs60ieKdbmhFBsPs5o0TScZRyUpDjojvJTeUOp5f0QEDhIqeqwFBy6gCZjZSTztLPPaYujJwLwAqqvEICz7CxPneW8c2j7rb7ruWvJWT0VbvnXuerHCsXxXdUv5AQ) ~~[154 bytes](https://tio.run/##NY3LDoMgFAX3fkV3BYQqGjaSu@yin9EENFd5NNQY/p5i2m5OJpNJzhzTnp5BLPMXSsGw28UmbtDb8MYYyDiqnk7TAYPOIO9Kr9A3Jl4CSC57qSs6OCMuuZCNh8wO4miLzGkE35GBOSGpPiV4gewvbDAmNhtgl/Ur1eMreaibole@tlt9QbGx/KvqlvIB)~~ ``` integer::v(3350)=2;x=1E5;j=0;do n=1,101;do l=3350,1,-1 m=x*v(l)+i*l;i=m/(2*l-1);v(l)=m-i*(2*l-1);enddo k=i/x;print'(I5.5)',j+k;j=i-k*x;enddo;end ``` [Answer] ## bc -l (22 = 5 command line + 17 program) ``` scale=500 4*a(1) ``` [Answer] # Mathematica - 50 ``` ½ = 1/2; 2/Times @@ FixedPointList[(½ + ½ #)^½~N~500 &, ½^½] ``` [Answer] # Axiom, 80 bytes ``` digits(503);v:=1./sqrt(3);6*reduce(+,[(-1)^k*v^(2*k+1)/(2*k+1)for k in 0..2000]) ``` for reference <https://tuts4you.com/download.php?view.452>; it would be an approssimation to 6\*arctg(1/sqrt(3))=%pi and it would use serie expansion for arctg ``` 3.1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 592307816 4 0628620899 8628034825 3421170679 8214808651 3282306647 0938446095 505822317 2 5359408128 4811174502 8410270193 8521105559 6446229489 5493038196 442881097 5 6659334461 2847564823 3786783165 2712019091 4564856692 3460348610 454326648 2 1339360726 0249141273 7245870066 0631558817 4881520920 9628292540 917153643 6 7892590360 0113305305 4882046652 1384146951 9415116094 3305727036 575959195 3 0921861173 8193261179 3105118548 0744623799 6274956735 1885752724 891227938 1 8301194913 01 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₄°·D.ΓN>*N·3+÷}O+₄;£ ``` Port of [my Java answer](https://codegolf.stackexchange.com/a/213932/52210) (with the `503` replaced with `1000` - anything \$\geq503\$ is fine to output the first 500 digits accurately with this approach). [Try it online](https://tio.run/##yy9OTMpM/f//UVPLoQ2HtrvonZvsZ6fld2i7sfbh7bX@2kBx60OL//8HAA) or [verify it's equal to the first 500 digits of PI using the builtin `žs`](https://tio.run/##yy9OTMpM/f//UVPLoQ2HtrvonZvsZ6fld2i7sfbh7bX@2kBx60OLbbmO7iuGML1suZQci1IVSjJSKxVSC0sTc@wVlOwDlfLyFSpTi5WUiw@v0Pn/HwA). **Explanation:** ``` ₄° # Push 10**1000 · # Double it to 2e1000 D # Duplicate it .Γ # Loop until the result no longer changes, # collecting all intermediate results # (excluding the initial value unfortunately) N> # Push the 0-based loop-index, and increase it by 1 to make it 1-based * # Multiply this 1-based index to the current value N· # Push the 0-based index again, and double it 3+ # Add 3 to it ÷ # Integer-divide the (index+1)*value by this (2*index+3) }O # After the cumulative fixed-point loop: sum all values in the list + # Add the 2e1000 we've duplicated, which wasn't included in the list ₄; # Push 1000, and halve it to 500 £ # Leave the first 500 digits of what we've calculated # (after which it is output implicitly as result) ``` [Answer] # APL (NARS2000), 20 bytes ``` {2+⍵×⍺÷1+⍨2×⍺}/⍳7e3x ``` I haven't been able to test this, but [here's](https://tio.run/##SyzI0U2pTMzJT////1Hf1ICAR20TDC24gEy3IBDTyML8//9qI@1HvVsPT3/Uu@vwdkMge4URmFOr/6h3s3mqMQA) a version in Dyalog APL. The only difference between them is the suffix "x", which is used for rational numbers in NARS2000 but is not available in Dyalog (or other variants available online, as far as I know). It's based on the `pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))` formula in the comments under the accepted Golfscript answer. [Answer] # [Scala 3](https://www.scala-lang.org/), ~~96~~ 84 bytes A port of [@Kevin Cruijssen's Java 10 answer](https://codegolf.stackexchange.com/a/213932/110802) in Scala. Saved 12 bytes thanks to @ceilingcat --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=LY7BagIxGITv-xSDp2RlbWNb0V0jKL300FNrLyIluu6SEpMQfxVZfJJevLSXPpFv04gyh4GZYfi-fzdLZdTD36yVWbdXwbbmZ-YWX6sl4VVpiyZJgJ0ysDn7cLqUo4muXyxxSPxsqcr65_dPOWouE5LXjol73vFuzx4HA552i50K8JKKygXoYQbRe-qBHAQWh0ygdJe27VN9x7qpbgte-OPt-xkoVxXWEYWpUG9yjENQh9kbBW3rOc8xtZoiSxMxAR9TMpZFbY3hPIbH5PZ1Ol39Hw) ``` _=>{val t=BigInt(10).pow(499)*2;var p=t;for i<- 1656 to 1 by-1 do p=t+p*i/(2*i+1);p} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=PVDLTsMwELznK0Y92aCUhkdFo6YSXCoOcEH0UlXIpGlY5DqR6zZCqF_CpRe48Av8SP-GdWLhg63ZnZn17Of3JldaXfzMe7GpGmVNb3GcVi9vRe5wr8jgI4oAZxU5PDAAn2WxQi52KWYVLWWKWyrvjOPW3nN3SsOkTM6-tm4VXx9_8YxsErS-65AFjUgGsl9XjbgcjSTGYySBZFEzyf0jYpQMr4ZtoXklXUAQJhjI4Buci7XXneOEFafBDZ0XY1FzI0wmibOWLwOJEGdBsW_v2icKGaZRF3vNKxHKlpsUN9aq9_mjs2TKBW_hyZAP1n2n5qrTRph-LsxWaynb9QS7w6F7_wA) ``` _ => { val t = BigInt(10).pow(499) << 1 var p = t var i = 1656 while (i > 0) { val temp = 2 * i + 1 p = t + (p * BigInt(i) / temp) i -= 1 } p } ``` [Answer] # APL(NARS), 213 chars ``` r2fs←{⎕ct←0⋄k←≢b←⍕⌊⍵×10x*a←⍺⋄k-←s←'¯'=↑b⋄c←{s:'¯'⋄''}⋄m←s↓b⋄0≥k-⍺:c,'0.',((⍺-k)⍴'0'),m⋄c,((k-⍺)↑m),'.',(k-⍺)↓m} r←P w;i;d;e;k r←i←0x⋄e←÷10x*w k←1+8×i⋄d←(+/4 2 1 1÷k,-k+3..5)×÷16*i⋄→3×⍳e>∣d⋄r+←d⋄i+←1⋄→2 {⍵r2fs P⍵}500 ``` 111+13+15+59+2+13=213 `p r2fs w`, return a string of the rational number in w seen as float with p digits afther the point. `P p`, would return a rational number enough to be traslated from `r2fs` to a float string with p digits of precision. Test (the last digit is always not rounded)- output: ``` 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066 470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337 867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153 643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799 6274956735188575272489122793818301194912 ``` ]
[Question] [ ## Winner found It seems as if we have a winner! Unless anyone plans on contesting the world's current fastest Sudoku solver, user 53x15 wins with the staggeringly fast solver Tdoku. For anyone still working on their solvers, I'll still benchmark new submissions when I have time. ## The challenge The goal of a game of Sudoku is to fill the board with the numbers 1-9, one in each cell, in such a way that each row, column and box only contains each number once. A very important aspect of a Sudoku puzzle is that there should only be one valid solution. The goal of this challenge is simple, you should solve a set of Sudoku puzzles as fast as possible. However, you won't just be solving any old Sudoku, you'll be solving the very hardest Sudoku puzzles in existence, the 17-clue Sudokus. Here's an example: [![Hard Sudoku](https://i.stack.imgur.com/6QWK7.png)](https://i.stack.imgur.com/6QWK7.png) ## Rules ### Language You're free to use any language. If I don't have a compiler installed for your language, **you should be able to provide a set of command line instructions needed to install an environment where your script can be run on Linux**. ### Benchmark machine The benchmark will be run on a Dell XPS 9560, 2.8GHz Intel Core i7-7700HQ (3.8GHz boost) 4 cores, 8 threads, 16GB RAM. GTX 1050 4GB. The machine runs Ubuntu 19.04. Here's the `uname` output, for anyone interested. ``` Linux 5.0.0-25-generic #26-Ubuntu SMP Thu Aug 1 12:04:58 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux ``` ### Input **The input will be given as a file. It can be found [here](https://raw.githubusercontent.com/maxbergmark/sudoku-solver/master/data-sets/all_17_clue_sudokus.txt)**. The file contains 49151 Sudoku puzzles. The first line of the file is the number of puzzles, and every line after that is 81 characters long and represents a puzzle. The unknown cells are `0`, and the known cells are `1-9`. **Your program should be able to take the filename as an argument, or have the file input from STDIN**, to facilitate manual checking of your solution. Please include an instruction for how your program takes input. ### Timing / scoring From discussions in the comments, and some reflection, the scoring criteria has been changed to be the time of your entire program. Your program should produce the output file with the correct hash even during official scoring. This doesn't interfere with any existing solution, and doesn't change the rankings as they stand now. Any thoughts on the scoring system are appreciated. If two solutions have similar scores for individual runs, I will run multiple benchmarks, and the average time will be the final score. If the average scores differ by less than 2%, I will consider it a draw. If your solution takes longer than an hour to run, it will not be officially scored. In those cases, you are responsible for reporting the machine on which it ran, and your score. For an optimized solver, this should not be an issue. **EDIT**: It was brought to my attention that while difficult, the problem set at hand is not the most difficult there is. If time is available, I'll try to benchmark the solutions presented here against the harder puzzle set, and add the score to each submission. However, this will not be an official scoring, and is just for fun. ### Verification Your solution will be verified by a MD5/SHA256 checksum. Your script should be able to generate a file containing all puzzles and their solutions. However, the file will also be manually inspected, so don't try to get a hash collision. Your output file should match: MD5: `41704fd7d8fd0723a45ffbb2dbbfa488` SHA256: `0bc8dda364db7b99f389b42383e37b411d9fa022204d124cb3c8959eba252f05` The file will be on the format: ``` <num_puzzles> <unsolved_puzzle#1>,<solved_puzzle#1> <unsolved_puzzle#2>,<solved_puzzle#2> ... <unsolved_puzzle#n>,<solved_puzzle#n> ``` with a single trailing newline. ### What's not allowed **You are in no way allowed to hard-code solutions**. Your algorithm should be applicable on any set of Sudoku puzzles, both easy and harder Sudokus. However, it is entirely fine if your solution is slow for easier puzzles. **You are not allowed to have a non-deterministic program**. You are allowed to use a random number generator, but the seed of the generator should be fixed. This rule is to ensure that measurements are more precise, and have less variance. (Thanks to Peter Taylor for the tip) **You are not allowed to use any external resources** or web requests during the runtime of your program. Everything should be self-contained. This does not apply to installed libraries and packages, which are allowed. ### Other info If you want another test set to check your solution, here are [10000 easier Sudokus](https://raw.githubusercontent.com/maxbergmark/sudoku-solver/master/data-sets/hard_sudokus.txt). Here are [their solutions](https://raw.githubusercontent.com/maxbergmark/sudoku-solver/master/data-sets/hard_sudokus_solved.txt). MD5: `3cb465ef6077c4fcab5bd6ae3bc50d62` SHA256: `0bc8dda364db7b99f389b42383e37b411d9fa022204d124cb3c8959eba252f05` If you have any questions, feel free to ask, and I'll try to clarify any misunderstandings. [Answer] # C++ - 0.201s official score Using [Tdoku](https://github.com/t-dillon/tdoku) ([code](https://github.com/t-dillon/tdoku/blob/master/src/solver_dpll_triad_simd.cc); [design](https://t-dillon.github.io/tdoku); [benchmarks](https://github.com/t-dillon/tdoku/tree/master/benchmarks)) gives these results: ``` ~/tdoku$ lscpu | grep Model.name Model name: Intel(R) Core(TM) i7-4930K CPU @ 3.40GHz ~/tdoku$ # build: ~/tdoku$ CC=clang-8 CXX=clang++-8 ./BUILD.sh ~/tdoku$ clang -o solve example/solve.c build/libtdoku.a ~/tdoku$ # adjust input format: ~/tdoku$ sed -e "s/0/./g" all_17_clue_sudokus.txt > all_17_clue_sudokus.txt.in ~/tdoku$ # solve: ~/tdoku$ time ./solve 1 < all_17_clue_sudokus.txt.in > out.txt real 0m0.241s user 0m0.229s sys 0m0.012s ~/tdoku$ # adjust output format and sha256sum: ~/tdoku$ grep -v "^:0:$" out.txt | sed -e "s/:1:/,/" | tr . 0 | sha256sum 0bc8dda364db7b99f389b42383e37b411d9fa022204d124cb3c8959eba252f05 - ``` Tdoku has been optimized for hard Sudoku instances. But note, contrary to the problem statement, that 17 clue puzzles are far from the hardest Sudoku. Actually they're among the easiest, with the majority requiring no backtracking at all. See some of the other benchmark datasets in the Tdoku project for puzzles that are actually hard. Also note that while Tdoku is the fastest solver I'm aware of for hard puzzles, it's not the fastest for 17 clue puzzles. For these I think the fastest is [this rust project](https://github.com/Emerentius/sudoku), a derivative of JCZSolve, which was optimized for 17 clue puzzles during development. Depending on the platform it might be 5-25% faster than Tdoku for these puzzles. [Answer] # [Node.js](https://nodejs.org), ~~8.231s~~ 6.735s official score Takes the file name as argument. The input file may already contain the solutions in the format described in the challenge, in which case the program will compare them with its own solutions. The results are saved in *'sudoku.log'*. ### Code ``` 'use strict'; const fs = require('fs'); const BLOCK = []; const BLOCK_NDX = []; const N_BIT = []; const ZERO = []; const BIT = []; console.time('Processing time'); init(); let filename = process.argv[2], puzzle = fs.readFileSync(filename).toString().split('\n'), len = puzzle.shift(), output = len + '\n'; console.log("File '" + filename + "': " + len + " puzzles"); // solve all puzzles puzzle.forEach((p, i) => { let sol, res; [ p, sol ] = p.split(','); if(p.length == 81) { if(!(++i % 2000)) { console.log((i * 100 / len).toFixed(1) + '%'); } if(!(res = solve(p))) { throw "Failed on puzzle " + i; } if(sol && res != sol) { throw "Invalid solution for puzzle " + i; } output += p + ',' + res + '\n'; } }); // results console.timeEnd('Processing time'); fs.writeFileSync('sudoku.log', output); console.log("MD5 = " + require('crypto').createHash('md5').update(output).digest("hex")); // initialization of lookup tables function init() { let ptr, x, y; for(x = 0; x < 0x200; x++) { N_BIT[x] = [0, 1, 2, 3, 4, 5, 6, 7, 8].reduce((s, n) => s + (x >> n & 1), 0); ZERO[x] = ~x & -~x; } for(x = 0; x < 9; x++) { BIT[1 << x] = x; } for(ptr = y = 0; y < 9; y++) { for(x = 0; x < 9; x++, ptr++) { BLOCK[ptr] = (y / 3 | 0) * 3 + (x / 3 | 0); BLOCK_NDX[ptr] = (y % 3) * 3 + x % 3; } } } // solver function solve(p) { let ptr, x, y, v, count = 81, m = Array(81).fill(-1), row = Array(9).fill(0), col = Array(9).fill(0), blk = Array(9).fill(0); // helper function to check and play a move function play(stack, x, y, n) { let p = y * 9 + x; if(~m[p]) { if(m[p] == n) { return true; } undo(stack); return false; } let msk, b; msk = 1 << n; b = BLOCK[p]; if((col[x] | row[y] | blk[b]) & msk) { undo(stack); return false; } count--; col[x] ^= msk; row[y] ^= msk; blk[b] ^= msk; m[p] = n; stack.push(x << 8 | y << 4 | n); return true; } // helper function to undo all moves on the stack function undo(stack) { stack.forEach(v => { let x = v >> 8, y = v >> 4 & 15, p = y * 9 + x, b = BLOCK[p]; v = 1 << (v & 15); count++; col[x] ^= v; row[y] ^= v; blk[b] ^= v; m[p] = -1; }); } // convert the puzzle into our own format for(ptr = y = 0; y < 9; y++) { for(x = 0; x < 9; x++, ptr++) { if(~(v = p[ptr] - 1)) { col[x] |= 1 << v; row[y] |= 1 << v; blk[BLOCK[ptr]] |= 1 << v; count--; m[ptr] = v; } } } // main recursive search function let res = (function search() { // success? if(!count) { return true; } let ptr, x, y, v, n, max, best, k, i, stack = [], dCol = Array(81).fill(0), dRow = Array(81).fill(0), dBlk = Array(81).fill(0), b, v0; // scan the grid: // - keeping track of where each digit can go on a given column, row or block // - looking for a cell with the fewest number of legal moves for(max = ptr = y = 0; y < 9; y++) { for(x = 0; x < 9; x++, ptr++) { if(m[ptr] == -1) { v = col[x] | row[y] | blk[BLOCK[ptr]]; n = N_BIT[v]; // abort if there's no legal move on this cell if(n == 9) { return false; } // update dCol[], dRow[] and dBlk[] for(v0 = v ^ 0x1FF; v0;) { b = v0 & -v0; dCol[x * 9 + BIT[b]] |= 1 << y; dRow[y * 9 + BIT[b]] |= 1 << x; dBlk[BLOCK[ptr] * 9 + BIT[b]] |= 1 << BLOCK_NDX[ptr]; v0 ^= b; } // update the cell with the fewest number of moves if(n > max) { best = { x : x, y : y, ptr: ptr, msk: v }; max = n; } } } } // play all forced moves (unique candidates on a given column, row or block) // and make sure that it doesn't lead to any inconsistency for(k = 0; k < 9; k++) { for(n = 0; n < 9; n++) { if(N_BIT[dCol[k * 9 + n]] == 1) { i = BIT[dCol[k * 9 + n]]; if(!play(stack, k, i, n)) { return false; } } if(N_BIT[dRow[k * 9 + n]] == 1) { i = BIT[dRow[k * 9 + n]]; if(!play(stack, i, k, n)) { return false; } } if(N_BIT[dBlk[k * 9 + n]] == 1) { i = BIT[dBlk[k * 9 + n]]; if(!play(stack, (k % 3) * 3 + i % 3, (k / 3 | 0) * 3 + (i / 3 | 0), n)) { return false; } } } } // if we've played at least one forced move, do a recursive call right away if(stack.length) { if(search()) { return true; } undo(stack); return false; } // otherwise, try all moves on the cell with the fewest number of moves while((v = ZERO[best.msk]) < 0x200) { col[best.x] ^= v; row[best.y] ^= v; blk[BLOCK[best.ptr]] ^= v; m[best.ptr] = BIT[v]; count--; if(search()) { return true; } count++; m[best.ptr] = -1; col[best.x] ^= v; row[best.y] ^= v; blk[BLOCK[best.ptr]] ^= v; best.msk ^= v; } return false; })(); return res ? m.map(n => n + 1).join('') : false; } // debugging function dump(m) { let x, y, c = 81, s = ''; for(y = 0; y < 9; y++) { for(x = 0; x < 9; x++) { s += (~m[y * 9 + x] ? (c--, m[y * 9 + x] + 1) : '-') + (x % 3 < 2 || x == 8 ? ' ' : ' | '); } s += y % 3 < 2 || y == 8 ? '\n' : '\n------+-------+------\n'; } console.log(c); console.log(s); } ``` ### Example output Tested on an Intel Core i7 7500U @ 2.70 GHz. [![output](https://i.stack.imgur.com/aYHGA.png)](https://i.stack.imgur.com/aYHGA.png) [Answer] # C - 0.045s unofficial score I got this time on my i7-9750H with 6 cores 12 threads @ 4Ghz. I'm aware that my cpu is faster than the i7-7700HQ so I think (hope) it would be closer to 0.080s if it were officially scored. Compile with: `gcc file.c -O3 -march=native -fopenmp` The program takes the input file name as argument. It generates an output.txt file containing all sudokus with their solution. It can be significantly slower when the output file already exists. This won't run on CPUs that don't support the SSE4.1 and AVX2 instructions set extensions. ``` #include <stdio.h> #include <omp.h> #include <stdbool.h> #include <intrin.h> // lookup tables that may or may not speed things up by avoiding division static const unsigned char box_index[81] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 3, 3, 3, 4, 4, 4, 5, 5, 5, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 6, 6, 6, 7, 7, 7, 8, 8, 8, 6, 6, 6, 7, 7, 7, 8, 8, 8 }; static const unsigned char column_index[81] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, }; static const unsigned char row_index[81] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; static const unsigned char box_start[81] = { 0, 0, 0, 3, 3, 3, 6, 6, 6, 0, 0, 0, 3, 3, 3, 6, 6, 6, 0, 0, 0, 3, 3, 3, 6, 6, 6, 27, 27, 27, 30, 30, 30, 33, 33, 33, 27, 27, 27, 30, 30, 30, 33, 33, 33, 27, 27, 27, 30, 30, 30, 33, 33, 33, 54, 54, 54, 57, 57, 57, 60, 60, 60, 54, 54, 54, 57, 57, 57, 60, 60, 60, 54, 54, 54, 57, 57, 57, 60, 60, 60 }; static void add_column_indices(unsigned long long indices[2], unsigned char i) { indices[0] |= 0x8040201008040201ULL << column_index[i]; indices[1] |= 0x8040201008040201ULL >> (10-column_index[i]); } static void add_row_indices(unsigned long long indices[2], unsigned char i) { switch (row_index[i]) { case 7: indices[0] |= 0x8000000000000000ULL; indices[1] |= 0xffULL; break; case 8: indices[1] |= 0x01ff00ULL; break; default: indices[0] |= 0x01ffULL << 9*row_index[i]; } } static void add_box_indices(unsigned long long indices[2], unsigned char i) { indices[0] |= 0x1c0e07ULL << box_start[i]; indices[1] |= 0x0381c0e0ULL >> (60-box_start[i]); } struct GridState { struct GridState* prev; // last grid state before a guess was made, used for backtracking unsigned long long unlocked[2]; // for keeping track of which cells don't need to be looked at anymore. Set bits correspond to cells that still have multiple possibilities unsigned long long updated[2]; // for keeping track of which cell's candidates may have been changed since last time we looked for naked sets. Set bits correspond to changed candidates in these cells unsigned short candidates[81]; // which digits can go in this cell? Set bits correspond to possible digits }; static void enter_digit(struct GridState* grid_state, signed char digit, unsigned char i) { // lock this cell and and remove this digit from the candidates in this row, column and box unsigned short* candidates = grid_state->candidates; unsigned long long* unlocked = grid_state->unlocked; unsigned long long to_update[2] = {0}; if (i < 64) { unlocked[0] &= ~(1ULL << i); } else { unlocked[1] &= ~(1ULL << (i-64)); } candidates[i] = 1 << digit; add_box_indices(to_update, i); add_column_indices(to_update, i); add_row_indices(to_update, i); to_update[0] &= unlocked[0]; to_update[1] &= unlocked[1]; grid_state->updated[0] |= to_update[0]; grid_state->updated[1] |= to_update[1]; const __m256i bit_mask = _mm256_setr_epi16(1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7, 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15); const __m256i mask = _mm256_set1_epi16(~candidates[i]); for (unsigned char j = 0; j < 80; j += 16) { unsigned short m; if (j < 64) { m = (unsigned short) ((to_update[0] >> j) & 0xffff); } else { m = (unsigned short) (to_update[1] & 0xffff); } __m256i c = _mm256_loadu_si256((__m256i*) &candidates[j]); __m256i u = _mm256_cmpeq_epi16(_mm256_and_si256(bit_mask, _mm256_set1_epi16(m)), _mm256_setzero_si256()); c = _mm256_and_si256(c, _mm256_or_si256(mask, u)); _mm256_storeu_si256((__m256i*) &candidates[j], c); } if ((to_update[1] & (1ULL << (80-64))) != 0) { candidates[80] &= ~candidates[i]; } } static long long guesses = 0; static struct GridState* make_guess(struct GridState* grid_state) { // Make a guess for the cell with the least candidates. The guess will be the lowest // possible digit for that cell. If multiple cells have the same number of candidates, the // cell with lowest index will be chosen. Also save the current grid state for tracking back // in case the guess is wrong. No cell has less than two candidates. unsigned long long* unlocked = grid_state->unlocked; unsigned short* candidates = grid_state->candidates; // Find the cell with fewest possible candidates unsigned long long to_visit; unsigned long guess_index = 0; unsigned long i_rel; unsigned short cnt; unsigned short best_cnt = 16; to_visit = unlocked[0]; while (_BitScanForward64(&i_rel, to_visit) != 0) { to_visit &= ~(1ULL << i_rel); cnt = __popcnt16(candidates[i_rel]); if (cnt < best_cnt) { best_cnt = cnt; guess_index = i_rel; } } to_visit = unlocked[1]; while (_BitScanForward64(&i_rel, to_visit) != 0) { to_visit &= ~(1ULL << i_rel); cnt = __popcnt16(candidates[i_rel + 64]); if (cnt < best_cnt) { best_cnt = cnt; guess_index = i_rel + 64; } } // Find the first candidate in this cell unsigned long digit; _BitScanReverse(&digit, candidates[guess_index]); // Create a copy of the state of the grid to make back tracking possible struct GridState* new_grid_state = (struct GridState*) malloc(sizeof(struct GridState)); memcpy(new_grid_state, grid_state, sizeof(struct GridState)); new_grid_state->prev = grid_state; // Remove the guessed candidate from the old grid because if we need to get back to the old grid // we know the guess was wrong grid_state->candidates[guess_index] &= ~(1 << digit); if (guess_index < 64) { grid_state->updated[0] |= 1ULL << guess_index; } else { grid_state->updated[1] |= 1ULL << (guess_index-64); } // Update candidates enter_digit(new_grid_state, (signed char) digit, (unsigned char) guess_index); guesses++; return new_grid_state; } static struct GridState* track_back(struct GridState* grid_state) { // Go back to the state when the last guess was made // This state had the guess removed as candidate from it's cell struct GridState* old_grid_state = grid_state->prev; free(grid_state); return old_grid_state; } static bool solve(signed char grid[81]) { struct GridState* grid_state = (struct GridState*) malloc(sizeof(struct GridState)); grid_state->prev = 0; unsigned long long* unlocked = grid_state->unlocked; unsigned long long* updated = grid_state->updated; unsigned short* candidates = grid_state->candidates; unlocked[0] = 0xffffffffffffffffULL; unlocked[1] = 0x1ffffULL; updated[0] = unlocked[0]; updated[1] = unlocked[1]; { signed char digit; unsigned short columns[9] = {0}; unsigned short rows[9] = {0}; unsigned short boxes[9] = {0}; for (unsigned char i = 0; i < 64; ++i) { digit = grid[i]; if (digit >= 49) { columns[column_index[i]] |= 1 << (digit-49); rows[row_index[i]] |= 1 << (digit-49); boxes[box_index[i]] |= 1 << (digit-49); unlocked[0] &= ~(1ULL << i); } } for (unsigned char i = 64; i < 81; ++i) { digit = grid[i]; if (digit >= 49) { columns[column_index[i]] |= 1 << (digit-49); rows[row_index[i]] |= 1 << (digit-49); boxes[box_index[i]] |= 1 << (digit-49); unlocked[1] &= ~(1ULL << (i-64)); } } for (unsigned char i = 0; i < 81; ++i) { if (grid[i] < 49) { candidates[i] = 0x01ff ^ (rows[row_index[i]] | columns[column_index[i]] | boxes[box_index[i]]); } else { candidates[i] = 1 << (grid[i]-49); } } } start: unlocked = grid_state->unlocked; candidates = grid_state->candidates; // Find naked singles { bool found; const __m256i ones = _mm256_set1_epi16(1); const __m256i bit_mask = _mm256_setr_epi16(1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7, 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15); do { found = false; for (unsigned char i = 0; i < 80; i += 16) { __m256i c = _mm256_loadu_si256((__m256i*) &candidates[i]); // Check if any cell has zero candidates if (_mm256_movemask_epi8(_mm256_cmpeq_epi16(c, _mm256_setzero_si256()))) { // Back track, no solutions along this path grid_state = track_back(grid_state); goto start; } else { unsigned short m; if (i < 64) { m = (unsigned short) ((unlocked[0] >> i) & 0xffff); } else { m = (unsigned short) (unlocked[1] & 0xffff); } __m256i a = _mm256_cmpeq_epi16(_mm256_and_si256(c, _mm256_sub_epi16(c, ones)), _mm256_setzero_si256()); __m256i u = _mm256_cmpeq_epi16(_mm256_and_si256(bit_mask, _mm256_set1_epi16(m)), bit_mask); int mask = _mm256_movemask_epi8(_mm256_and_si256(a, u)); if (mask) { unsigned long index, digit; _BitScanForward(&index, mask); index = (index >> 1) + i; _BitScanReverse(&digit, candidates[index]); enter_digit(grid_state, (signed char) digit, index); found = true; } } } if (unlocked[1] & (1ULL << (80-64))) { if (candidates[80] == 0) { // no solutions go back grid_state = track_back(grid_state); goto start; } else if (__popcnt16(candidates[80]) == 1) { // Enter the digit and update candidates unsigned long digit; _BitScanReverse(&digit, candidates[80]); enter_digit(grid_state, (signed char) digit, 80); found = true; } } } while (found); } // Check if it's solved, if it ever gets solved it will be solved after looking for naked singles if ((unlocked[0] | unlocked[1]) == 0) { // Solved it // Free memory while (grid_state) { struct GridState* prev_grid_state = grid_state->prev; free(grid_state); grid_state = prev_grid_state; } // Enter found digits into grid for (unsigned char j = 0; j < 81; ++j) { unsigned long index; _BitScanReverse(&index, candidates[j]); grid[j] = (signed char) index + 49; } return true; } // Find hidden singles // Don't check the last column because it doesn't fit in the SSE register so it's not really worth checking { const __m128i ones = _mm_set1_epi16(1); const __m128i bit_mask = _mm_setr_epi16(1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7); const __m128i shuffle_mask = _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1); for (unsigned char i = 0; i < 81; i += 9) { // rows __m128i row_mask = _mm_set1_epi16(0x01ff ^ candidates[i+8]); __m128i c = _mm_loadu_si128((__m128i*) &candidates[i]); for (unsigned char j = 0; j < 7; ++j) { // rotate shift (1 2 3 4) -> (4 1 2 3) c = _mm_shuffle_epi8(c, shuffle_mask); row_mask = _mm_andnot_si128(c, row_mask); } // columns __m128i column_mask = _mm_set1_epi16(0x01ff); for (unsigned char j = 0; j < 81; j += 9) { if (j != i) { column_mask = _mm_andnot_si128(_mm_loadu_si128((__m128i*) &candidates[j]), column_mask); } } // boxes aren't worth it __m128i or_mask = _mm_or_si128(row_mask, column_mask); if (_mm_test_all_zeros(or_mask, _mm_sub_epi16(or_mask, ones))) { unsigned short m; if (i < 64) { m = (unsigned short) ((unlocked[0] >> i) & 0xff); } else { m = (unsigned short) ((unlocked[1] >> (i-64)) & 0xff); } c = _mm_loadu_si128((__m128i*) &candidates[i]); __m128i a = _mm_cmpgt_epi16(_mm_and_si128(c, or_mask), _mm_setzero_si128()); __m128i u = _mm_cmpeq_epi16(_mm_and_si128(bit_mask, _mm_set1_epi16(m)), bit_mask); int mask = _mm_movemask_epi8(_mm_and_si128(a, u)); if (mask) { unsigned long index, digit; _BitScanForward(&index, mask); index = index/2; int can = ((unsigned short*) &or_mask)[index]; _BitScanForward(&digit, can); index = index + i; enter_digit(grid_state, (signed char) digit, index); goto start; } } else { // no solutions go back grid_state = track_back(grid_state); goto start; } } } // Find naked sets, up to 5 { bool found = false; // because this is kind of an expensive task, we are not going to visit all cells but only those that were changed unsigned long long *to_visit_n = grid_state->updated; to_visit_n[0] &= unlocked[0]; to_visit_n[1] &= unlocked[1]; for (unsigned char n = 0; n < 2; ++n) { while (to_visit_n[n]) { unsigned long i_rel; _BitScanForward64(&i_rel, to_visit_n[n]); to_visit_n[n] ^= 1ULL << i_rel; unsigned char i = (unsigned char) i_rel + 64*n; unsigned short cnt = __popcnt16(candidates[i]); if (cnt <= 5) { // check column unsigned long long to_change[2] = {0}; unsigned char s; __m128i a_i = _mm_set1_epi16(candidates[i]); __m128i a_j = _mm_set_epi16(candidates[column_index[i]+63], candidates[column_index[i]+54], candidates[column_index[i]+45], candidates[column_index[i]+36], candidates[column_index[i]+27], candidates[column_index[i]+18], candidates[column_index[i]+9], candidates[column_index[i]]); __m128i res = _mm_cmpeq_epi16(a_i, _mm_or_si128(a_i, a_j)); s = __popcnt16(_mm_movemask_epi8(res)) >> 1; s += candidates[i] == (candidates[i] | candidates[column_index[i]+72]); if (s > cnt) { grid_state = track_back(grid_state); goto start; } else if (s == cnt) { add_column_indices(to_change, i); } // check row a_j = _mm_load_si128((__m128i*) &candidates[9*row_index[i]]); res = _mm_cmpeq_epi16(a_i, _mm_or_si128(a_i, a_j)); s = __popcnt16(_mm_movemask_epi8(res)) >> 1; s += candidates[i] == (candidates[i] | candidates[9*row_index[i]+8]); if (s > cnt) { grid_state = track_back(grid_state); goto start; } else if (s == cnt) { add_row_indices(to_change, i); } // check box unsigned short b = box_start[i]; a_j = _mm_set_epi16(candidates[b], candidates[b+1], candidates[b+2], candidates[b+9], candidates[b+10], candidates[b+11], candidates[b+18], candidates[b+19]); res = _mm_cmpeq_epi16(a_i, _mm_or_si128(a_i, a_j)); s = __popcnt16(_mm_movemask_epi8(res)) >> 1; s += candidates[i] == (candidates[i] | candidates[b+20]); if (s > cnt) { grid_state = track_back(grid_state); goto start; } else if (s == cnt) { add_box_indices(to_change, i); } to_change[0] &= unlocked[0]; to_change[1] &= unlocked[1]; // update candidates for (unsigned char n = 0; n < 2; ++n) { while (to_change[n]) { unsigned long j_rel; _BitScanForward64(&j_rel, to_change[n]); to_change[n] &= ~(1ULL << j_rel); unsigned char j = (unsigned char) j_rel + 64*n; if ((candidates[j] | candidates[i]) != candidates[i]) { if (candidates[j] & candidates[i]) { candidates[j] &= ~candidates[i]; to_visit_n[n] |= 1ULL << j_rel; found = true; } } } } // If any cell's candidates got updated, go back and try all that other stuff again if (found) { goto start; } } } } } // More techniques could be added here but they're not really worth checking for on the 17 clue sudoku set // Make a guess if all that didn't work grid_state = make_guess(grid_state); goto start; } int main(int argc, char *argv[]) { if (argc != 2) { printf("Error! Pass the file name as argument\n"); return -1; } FILE *f = fopen(argv[1], "rb"); // test for files not existing if (f == 0) { printf("Error! Could not open file %s\n", argv[1]); return -1; } // find length of file fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); // deal with the part that says how many sudokus there are signed char *string = malloc(fsize + 1); fread(string, 1, fsize, f); fclose(f); size_t p = 0; while (string[p] != 10) { ++p; } ++p; signed char *output = malloc(fsize*2 - p + 2); memcpy(output, string, p); // solve all sudokus and prepare output file int i; #pragma omp parallel for shared(string, output, fsize, p) schedule(dynamic) for (i = fsize - p - 81; i >= 0; i-=82) { // copy unsolved grid memcpy(&output[p+i*2], &string[p+i], 81); memcpy(&output[p+i*2+82], &string[p+i], 81); // add comma and newline in right place output[p+i*2 + 81] = ','; output[p+i*2 + 163] = 10; // solve the grid in place solve(&output[p+i*2+82]); } // create output file f = fopen("output.txt", "wb"); fwrite(output, 1, fsize*2 - p + 2, f); fclose(f); free(string); free(output); return 0; } ``` The algorithm uses normal techniques humans use. Specifically looking for naked singles, hidden singles and naked subsets. If that doesn't work it uses the infamous Nishio technique (just backtracking). I added more techniques initially like looking for locked candidates, but they turned out to not really be worth it for these 17-clue sudokus. [Answer] # [Python 3](https://docs.python.org/3/ "Python docs") (with [dlx](https://pypi.org/project/dlx/ "PyPI")) 4min 46.870s official score (single core i7-3610QM here) Obviously beatable with a compiled language like C, and making use of threading, but it's a start... [`sudoku`](https://github.com/jjallan/sudoku "Git Hub") is a module I've placed on github (copied at the footer of this post) which uses [`dlx`](https://pypi.org/project/dlx/ "PyPI") under the hood. ``` #!/usr/bin/python import argparse import gc import sys from timeit import timeit from sudoku import Solver def getSolvers(filePath): solvers = [] with open(filePath, 'r') as inFile: for line in inFile: content = line.rstrip() if len(content) == 81 and content.isdigit(): solvers.append(Solver(content)) return solvers def solve(solvers): for solver in solvers: yield next(solver.genSolutions()) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Time or print solving of some sudoku.') parser.add_argument('filePath', help='Path to the file containing proper sudoku on their own lines as 81 digits in row-major order with 0s as blanks') parser.add_argument('-p', '--print', dest='printEm', action='store_true', default=False, help='print solutions in the same fashion as the input') parser.add_argument('-P', '--pretty', dest='prettyPrintEm', action='store_true', default=False, help='print inputs and solutions formatted for human consumption') args = parser.parse_args() if args.printEm or args.prettyPrintEm: solvers = getSolvers(args.filePath) print(len(solvers)) for solver, solution in zip(solvers, solve(solvers)): if args.prettyPrintEm: print(solver) print(solution) else: print('{},{}'.format(solver.representation(noneCharacter='0'), solution.representation())) else: setup = '''\ from __main__ import getSolvers, solve, args, gc gc.disable() solvers = getSolvers(args.filePath)''' print(timeit("for solution in solve(solvers): pass", setup=setup, number=1)) ``` ### Usage * Install Python 3 * Save `sudoku.py` somewhere on your path (from the git hub link or copy it from below) * Save the above code as `testSolver.py` somewhere on your path * Install dlx: ``` python -m pip install dlx ``` * Run it (by the way it consumes memory like it's going out of fashion) ``` usage: testSolver.py [-h] [-p] [-P] filePath Time or print solving of some sudoku. positional arguments: filePath Path to the file containing proper sudoku on their own lines as 81 digits in row-major order with 0s as blanks optional arguments: -h, --help show this help message and exit -p, --print print solutions in the same fashion as the input -P, --pretty print inputs and solutions formatted for human consumption ``` Pipe output as required in the challenge spec to a file if need be: ``` python testSolver.py -p input_file_path > output_file_path ``` --- sudoku.py (yes there are extra features here other than solving) ``` import dlx from itertools import permutations, takewhile from random import choice, shuffle ''' A 9 by 9 sudoku solver. ''' _N = 3 _NSQ = _N**2 _NQU = _N**4 _VALID_VALUE_INTS = list(range(1, _NSQ + 1)) _VALID_VALUE_STRS = [str(v) for v in _VALID_VALUE_INTS] _EMPTY_CELL_CHAR = '·' # The following are mutually related by their ordering, and define ordering throughout the rest of the code. Here be dragons. # _CANDIDATES = [(r, c, v) for r in range(_NSQ) for c in range(_NSQ) for v in range(1, _NSQ + 1)] _CONSTRAINT_INDEXES_FROM_CANDIDATE = lambda r, c, v: [ _NSQ * r + c, _NQU + _NSQ * r + v - 1, _NQU * 2 + _NSQ * c + v - 1, _NQU * 3 + _NSQ * (_N * (r // _N) + c // _N) + v - 1] _CONSTRAINT_FORMATTERS = [ "R{0}C{1}" , "R{0}#{1}" , "C{0}#{1}" , "B{0}#{1}"] _CONSTRAINT_NAMES = [(s.format(a, b + (e and 1)), dlx.DLX.PRIMARY) for e, s in enumerate(_CONSTRAINT_FORMATTERS) for a in range(_NSQ) for b in range(_NSQ)] _EMPTY_GRID_CONSTRAINT_INDEXES = [_CONSTRAINT_INDEXES_FROM_CANDIDATE(r, c, v) for (r, c, v) in _CANDIDATES] # # The above are mutually related by their ordering, and define ordering throughout the rest of the code. Here be dragons. class Solver: def __init__(self, representation=''): if not representation or len(representation) != _NQU: self._complete = False self._NClues = 0 self._repr = [None]*_NQU # blank grid, no clues - maybe to extend to a generator by overriding the DLX column selection to be stochastic. else: nClues = 0 repr = [] for value in representation: if not value: repr.append(None) elif isinstance(value, int) and 1 <= value <= _NSQ: nClues += 1 repr.append(value) elif value in _VALID_VALUE_STRS: nClues += 1 repr.append(int(value)) else: repr.append(None) self._complete = nClues == _NQU self._NClues = nClues self._repr = repr def genSolutions(self, genSudoku=True, genNone=False, dlxColumnSelctor=None): ''' if genSudoku=False, generates each solution as a list of cell values (left-right, top-bottom) ''' if self._complete: yield self else: self._initDlx() dlxColumnSelctor = dlxColumnSelctor or dlx.DLX.smallestColumnSelector if genSudoku: for solution in self._dlx.solve(dlxColumnSelctor): yield Solver([v for (r, c, v) in sorted([self._dlx.N[i] for i in solution])]) elif genNone: for solution in self._dlx.solve(dlxColumnSelctor): yield else: for solution in self._dlx.solve(dlxColumnSelctor): yield [v for (r, c, v) in sorted([self._dlx.N[i] for i in solution])] def uniqueness(self, returnSolutionIfProper=False): ''' Returns: 0 if unsolvable; 1 (or the unique solution if returnSolutionIfProper=True) if uniquely solvable; or 2 if multiple possible solutions exist - a 'proper' sudoku is uniquely solvable. ''' slns = list(takewhile(lambda t: t[0] < 2, ((i, sln) for i, sln in enumerate(self.genSolutions(genSudoku=returnSolutionIfProper, genNone=not returnSolutionIfProper))))) uniqueness = len(slns) if returnSolutionIfProper and uniqueness == 1: return slns[0][1] else: return uniqueness def representation(self, asString=True, noneCharacter='.'): if asString: return ''.join([v and str(_VALID_VALUE_STRS[v - 1]) or noneCharacter for v in self._repr]) return self._repr[:] def __repr__(self): return display(self._repr) def _initDlx(self): self._dlx = dlx.DLX(_CONSTRAINT_NAMES) rowIndexes = self._dlx.appendRows(_EMPTY_GRID_CONSTRAINT_INDEXES, _CANDIDATES) for r in range(_NSQ): for c in range(_NSQ): v = self._repr[_NSQ * r + c] if v is not None: self._dlx.useRow(rowIndexes[_NQU * r + _NSQ * c + v - 1]) _ROW_SEPARATOR_COMPACT = '+'.join(['-' * (2 * _N + 1) for b in range(_N)])[1:-1] + '\n' _ROW_SEPARATOR = ' ·-' + _ROW_SEPARATOR_COMPACT[:-1] + '-·\n' _TOP_AND_BOTTOM = _ROW_SEPARATOR.replace('+', '·') _ROW_LABELS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J'] _COL_LABELS = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] _COLS_LABEL = ' ' + ' '.join([i % _N == 0 and ' ' + l or l for i, l in enumerate(_COL_LABELS)]) + '\n' def display(representation, conversion=None, labelled=True): result = '' raw = [conversion[n or 0] for n in representation] if conversion else representation if labelled: result += _COLS_LABEL + _TOP_AND_BOTTOM rSep = _ROW_SEPARATOR else: rSep = _ROW_SEPARATOR_COMPACT for r in range(_NSQ): if r > 0 and r % _N == 0: result += rSep for c in range(_NSQ): if c % _N == 0: if c == 0: if labelled: result += _ROW_LABELS[r] + '| ' else: result += '| ' result += str(raw[_NSQ * r + c] or _EMPTY_CELL_CHAR) + ' ' if labelled: result += '|' result += '\n' if labelled: result += _TOP_AND_BOTTOM else: result = result[:-1] return result def permute(representation): ''' returns a random representation from the given representation's equivalence class ''' rows = [list(representation[i:i+_NSQ]) for i in range(0, _NQU, _NSQ)] rows = permuteRowsAndBands(rows) rows = [[r[i] for r in rows] for i in range(_NSQ)] rows = permuteRowsAndBands(rows) pNumbers = [str(i) for i in range(1, _NSQ + 1)] shuffle(pNumbers) return ''.join(''.join([pNumbers[int(v) - 1] if v.isdigit() and v != '0' else v for v in r]) for r in rows) def permuteRowsAndBands(rows): bandP = choice([x for x in permutations(range(_N))]) rows = [rows[_N * b + r] for b in bandP for r in range(_N)] for band in range(0, _NSQ, _N): rowP = choice([x for x in permutations([band + i for i in range(_N)])]) rows = [rows[rowP[i % _N]] if i // _N == band else rows[i] for i in range(_NSQ)] return rows def getRandomSolvedStateRepresentation(): return permute('126459783453786129789123456897231564231564897564897231312645978645978312978312645') def getRandomSudoku(): r = getRandomSolvedStateRepresentation() s = Solver(r) indices = list(range(len(r))) shuffle(indices) for i in indices: ns = Solver(s._repr[:i] + [None] + s._repr[i+1:]) if ns.uniqueness() == 1: s = ns return s if __name__ == '__main__': print('Some example useage:') inputRepresentation = '..3......4......2..8.12...6.........2...6...7...8.7.31.1.64.9..6.5..8...9.83...4.' print('>>> s = Solver({})'.format(inputRepresentation)) s = Solver(inputRepresentation) print('>>> s') print(s) print('>>> print(s.representation())') print(s.representation()) print('>>> print(display(s.representation(), labelled=False))') print(display(s.representation(), labelled=False)) print('>>> for solution in s.genSolutions(): solution') for solution in s.genSolutions(): print(solution) inputRepresentation2 = inputRepresentation[:2] + '.' + inputRepresentation[3:] print('>>> s.uniqueness()') print(s.uniqueness()) print('>>> s2 = Solver({}) # removed a clue; this has six solutions rather than one'.format(inputRepresentation2)) s2 = Solver(inputRepresentation2) print('>>> s2.uniqueness()') print(s2.uniqueness()) print('>>> for solution in s2.genSolutions(): solution') for solution in s2.genSolutions(): print(solution) print('>>> s3 = getRandomSudoku()') s3 = getRandomSudoku() print('>>> s3') print(s3) print('>>> for solution in s3.genSolutions(): solution') for solution in s3.genSolutions(): print(solution) ``` [Answer] # Python 3 + [Z3](https://pypi.org/project/z3-solver/) - 10min 45.657s official score about 1000s on my laptop. ``` import time start = time.time() import z3.z3 as z3 import itertools import datetime import sys solver = z3.Solver() ceils = [[None] * 9 for i in range(9)] for row in range(9): for col in range(9): name = 'c' + str(row * 9 + col) ceil = z3.BitVec(name, 9) solver.add(z3.Or( ceil == 0b000000001, ceil == 0b000000010, ceil == 0b000000100, ceil == 0b000001000, ceil == 0b000010000, ceil == 0b000100000, ceil == 0b001000000, ceil == 0b010000000, ceil == 0b100000000 )) solver.add(ceil != 0) ceils[row][col] = ceil for i in range(9): for j in range(9): for k in range(9): if j == k: continue solver.add(ceils[i][j] & ceils[i][k] == 0) solver.add(ceils[j][i] & ceils[k][i] == 0) row, col = i // 3 * 3, i % 3 * 3 solver.add(ceils[row + j // 3][col + j % 3] & ceils[row + k // 3][col + k % 3] == 0) row_col = list(itertools.product(range(9), range(9))) lookup = { 1 << i: str(i + 1) for i in range(9) } def solve(line): global solver, output, row_col, ceils, lookup solver.push() for value, (row, col) in zip(line, row_col): val = ord(value) - 48 if val == 0: continue solver.add(ceils[row][col] == 1 << (val - 1)) output = [] if solver.check() == z3.sat: model = solver.model() for row in range(9): for col in range(9): val = model[ceils[row][col]].as_long() output.append(lookup[val]) solver.pop() return ''.join(output) count = int(input()) print(count) for i in range(count): if i % 1000 == 0: sys.stderr.write(str(i) + '\n') line = input() print(line + "," + solve(line)) end = time.time() sys.stderr.write(str(end - start)) ``` Install dependency > > pip install z3-solver > > > Run > > python3 solve.py < in.txt > out.txt > > > I'm not sure how to improve its performance, since it just solved magically... [Answer] # C - ~~2.228s~~ 1.690s official score based on [@Arnauld's](https://codegolf.stackexchange.com/a/190814/24908) ``` #include<fcntl.h> #define O const #define R return #define S static #define $(x,y...)if(x){y;} #define W(x,y...)while(x){y;} #define fi(x,y...)for(I i=0,_n=(x);i<_n;i++){y;} #define fj(x,y...)for(I j=0,_n=(x);j<_n;j++){y;} #define fp81(x...)for(I p=0;p<81;p++){x;} #define fq3(x...)for(I q=0;q<3;q++){x;} #define fij9(x...){fi(9,fj(9,x))} #define m0(x)m0_((V*)(x),sizeof(x)); #define popc(x)__builtin_popcount(x) #define ctz(x)__builtin_ctz(x) #include<sys/syscall.h> #define sc(f,x...)({L u;asm volatile("syscall":"=a"(u):"0"(SYS_##f)x:"cc","rcx","r11","memory");u;}) #define sc1(f,x) sc(f,,"D"(x)) #define sc2(f,x,y) sc(f,,"D"(x),"S"(y)) #define sc3(f,x,y,z)sc(f,,"D"(x),"S"(y),"d"(z)) #define wr(a...)sc3(write,a) #define op(a...)sc3( open,a) #define cl(a...)sc1(close,a) #define fs(a...)sc2(fstat,a) #define ex(a...)sc1( exit,a) #define mm(x,y,z,t,u,v)({register L r10 asm("r10")=t,r8 asm("r8")=u,r9 asm("r9")=v;\ (V*)sc(mmap,,"D"(x),"S"(y),"d"(z),"r"(r10),"r"(r8),"r"(r9));}) typedef void V;typedef char C;typedef short H;typedef int I;typedef long long L; S C BL[81],KL[81],IJK[81][3],m[81],t_[81-17],*t;S H rcb[3][9],cnt; S V*mc(V*x,O V*y,L n){C*p=x;O C*q=y;fi(n,*p++=*q++)R x;}S V m0_(C*p,L n){fi(n,*p++=0);} S I undo(C*t0){cnt+=t-t0;W(t>t0,C p=*--t;H v=1<<m[p];fq3(rcb[q][IJK[p][q]]^=v)m[p]=-1)R 0;} S I play(C p,H v){$(m[p]>=0,R 1<<m[p]==v)I w=0;fq3(w|=rcb[q][IJK[p][q]])$(w&v,R 0)cnt--; fq3(rcb[q][IJK[p][q]]^=v);m[p]=ctz(v);*t++=p;R 1;} S I f(){$(!cnt,R 1)C*t0=t;H max=0,bp,bv,d[9][9][4];m0(d); fij9(I p=i*9+j;$(m[p]<0, I v=0;fq3(v|=rcb[q][IJK[p][q]])I w=v^511;$(!w,R 0)H g[]={1<<j,1<<i,1<<BL[p]}; do{I z=ctz(w);w&=w-1;fq3(d[IJK[p][q]][z][q]|=g[q]);}while(w); I n=popc(v);$(max<n,max=n;bp=p;bv=v))) fij9(I u=d[i][j][0];$(popc(u)==1,I l=ctz(u);$(!play( i*9+l ,1<<j),R undo(t0))) u=d[i][j][1];$(popc(u)==1,I l=ctz(u);$(!play( l*9+i ,1<<j),R undo(t0))) u=d[i][j][2];$(popc(u)==1,I l=ctz(u);$(!play(KL[i*9+l],1<<j),R undo(t0)))) $(t-t0,R f()||undo(t0)) W(1,I v=1<<ctz(~bv);$(v>511,R 0)fq3(rcb[q][IJK[bp][q]]^=v)m[bp]=ctz(v);cnt--;$(f(),R 1) cnt++;m[bp]=-1;fq3(rcb[q][IJK[bp][q]]^=v)bv^=v) R 0;} asm(".globl _start\n_start:pop %rdi\nmov %rsp,%rsi\njmp main"); V main(I ac,C**av){$(ac!=2,ex(2)) fij9(I p=i*9+j;BL[p]=i%3*3+j%3;KL[p]=(i/3*3+j/3)*9+BL[p];IJK[p][0]=i;IJK[p][1]=j;IJK[p][2]=i/3*3+j/3) I d=op(av[1],0,0);struct stat h;fs(d,&h);C*s0=mm(0,h.st_size,1,0x8002,d,0),*s=s0;cl(d); //in C*r0=mm(0,2*h.st_size,3,0x22,-1,0),*r=r0; //out I n=0;W(*s!='\n',n*=10;n+=*s++-'0')s++;mc(r,s0,s-s0);r+=s-s0; fi(n,m0(rcb);cnt=81;t=t_;$(s[81]&&s[81]!='\n',ex(3))mc(r,s,81);r+=81;*r++=','; fp81(I v=m[p]=*s++-'1';$(v>=0,v=1<<v;fq3(rcb[q][IJK[p][q]]|=v)cnt--)) s++;$(!f(),ex(4))fp81(r[p]=m[p]+'1')r+=81;*r++='\n') wr(1,r0,r-r0);ex(0);} ``` compile and run: ``` gcc -O3 -march=native -nostdlib -ffreestanding time ./a.out all_17_clue_sudokus.txt | md5sum ``` [Answer] # C++ with Minisat(2.2.1-5) - 11.735s official score This is nowhere near as fast as a specialized algorithm, but it's a different approach, an interesting point of reference, and easy to understand. $ clang++ -o solve -lminisat solver\_minisat.cc ``` #include <minisat/core/Solver.h> namespace { using Minisat::Lit; using Minisat::mkLit; using namespace std; struct SolverMiniSat { Minisat::Solver solver; SolverMiniSat() { InitializeVariables(); InitializeTriadDefinitions(); InitializeTriadOnnes(); InitializeCellOnnes(); } // normal cell literals, of which we have 9*9*9 static Lit Literal(int row, int column, int value) { return mkLit(value + 9 * (column + 9 * row), true); } // horizontal triad literals, of which we have 9*3*9, starting after the cell literals static Lit HTriadLiteral(int row, int column, int value) { int base = 81 * 9; return mkLit(base + value + 9 * (column + 3 * row)); } // vertical triad literals, of which we have 3*9*9, starting after the h_triad literals static Lit VTriadLiteral(int row, int column, int value) { int base = (81 + 27) * 9; return mkLit(base + value + 9 * (row + 3 * column)); } void InitializeVariables() { for (int i = 0; i < 15 * 9 * 9; i++) { solver.newVar(); } } // create an exactly-one constraint over a set of literals void CreateOnne(const Minisat::vec<Minisat::Lit> &literals) { solver.addClause(literals); for (int i = 0; i < literals.size() - 1; i++) { for (int j = i + 1; j < literals.size(); j++) { solver.addClause(~literals[i], ~literals[j]); } } } void InitializeTriadDefinitions() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 3; j++) { for (int value = 0; value < 9; value++) { Lit h_triad = HTriadLiteral(i, j, value); Lit v_triad = VTriadLiteral(j, i, value); int j0 = j * 3 + 0, j1 = j * 3 + 1, j2 = j * 3 + 2; Minisat::vec<Minisat::Lit> h_triad_def; h_triad_def.push(Literal(i, j0, value)); h_triad_def.push(Literal(i, j1, value)); h_triad_def.push(Literal(i, j2, value)); h_triad_def.push(~h_triad); CreateOnne(h_triad_def); Minisat::vec<Minisat::Lit> v_triad_def; v_triad_def.push(Literal(j0, i, value)); v_triad_def.push(Literal(j1, i, value)); v_triad_def.push(Literal(j2, i, value)); v_triad_def.push(~v_triad); CreateOnne(v_triad_def); } } } } void InitializeTriadOnnes() { for (int i = 0; i < 9; i++) { for (int value = 0; value < 9; value++) { Minisat::vec<Minisat::Lit> row; row.push(HTriadLiteral(i, 0, value)); row.push(HTriadLiteral(i, 1, value)); row.push(HTriadLiteral(i, 2, value)); CreateOnne(row); Minisat::vec<Minisat::Lit> column; column.push(VTriadLiteral(0, i, value)); column.push(VTriadLiteral(1, i, value)); column.push(VTriadLiteral(2, i, value)); CreateOnne(column); Minisat::vec<Minisat::Lit> hbox; hbox.push(HTriadLiteral(3 * (i / 3) + 0, i % 3, value)); hbox.push(HTriadLiteral(3 * (i / 3) + 1, i % 3, value)); hbox.push(HTriadLiteral(3 * (i / 3) + 2, i % 3, value)); CreateOnne(hbox); Minisat::vec<Minisat::Lit> vbox; vbox.push(VTriadLiteral(i % 3, 3 * (i / 3) + 0, value)); vbox.push(VTriadLiteral(i % 3, 3 * (i / 3) + 1, value)); vbox.push(VTriadLiteral(i % 3, 3 * (i / 3) + 2, value)); CreateOnne(vbox); } } } void InitializeCellOnnes() { for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { Minisat::vec<Minisat::Lit> literals; for (int value = 0; value < 9; value++) { literals.push(Literal(row, column, value)); } CreateOnne(literals); } } } bool SolveSudoku(const char *input, char *solution, size_t *num_guesses) { Minisat::vec<Minisat::Lit> assumptions; for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { char digit = input[row * 9 + column]; if (digit != '.') { assumptions.push(Literal(row, column, digit - '1')); } } } solver.decisions = 0; bool satisfied = solver.solve(assumptions); if (satisfied) { for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { for (int value = 0; value < 9; value++) { if (solver.model[value + 9 * (column + 9 * row)] == Minisat::lbool((uint8_t) 1)) { solution[row * 9 + column] = value + '1'; } } } } } *num_guesses = solver.decisions - 1; return satisfied; } }; } //end anonymous namespace int main(int argc, const char **argv) { char *puzzle = NULL; char solution[81]; size_t size, guesses; SolverMiniSat solver; while (getline(&puzzle, &size, stdin) != -1) { int count = solver.SolveSudoku(puzzle, solution, &guesses); printf("%.81s:%d:%.81s\n", puzzle, count, solution); } } ``` [Answer] # Java - 4.056s official score The main idea of this is to never allocate memory when it is not needed. The only exception are primitives, which should be optimized by the compiler anyway. Everything else is stored as masks and arrays of operations done in each step, which can be undone when the recursion step is completed. About half of all sudokus are solved completely without backtracking, but if I push that number higher the overall time seems to be slower. I'm planning om rewriting this in C++ and optimize even further, but this solver is becoming a behemoth. I wanted to implement as much caching as possible, which lead to some issues. For example, if there are two cells on the same row which can only have the number 6, then we have reached an impossible case, and should return to the backtracking. But since I calculated all options in one sweep, and then placed numbers in cells with only one possibility, I didn't double check that I had placed a number in the same row just before. This lead to impossible solutions. With everything being contained in the arrays defined at the top, the memory usage of the actual solver is about 216kB. The main part of the memory usage comes from the array containing all the puzzles, and the I/O handlers in Java. **EDIT**: I have a version which is translated to C++ now, but it isn't vastly faster. The official time is around 3.5 seconds, which isn't a huge improvement. I think the main issue with my implementation is that I keep my masks as arrays rather than bitmasks. I'll try to analyze Arnauld's solution to see what can be done to improve it. ``` import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.File; import java.io.PrintWriter; public class Sudoku { final private int[] unsolvedBoard; final private int[] solvedBoard; final private int[][] neighbors; final private int[][] cells; private static int[] clues; final private int[][] mask; final private int[] formattedMask; final private int[][] placedMask; final private boolean[][][] lineMask; final private int[] lineCounters; final private int[][] sectionCounters; final private int[][] sectionMask; private int easySolved; private boolean isEasy; private int totEasy; private int placedNumbers; public long totTime = 0; private boolean solutionFound; public long lastPrint; private boolean shouldPrint; private boolean isImpossible = false; public Sudoku() { mask = new int[81][9]; formattedMask = new int[81]; placedMask = new int[64][64]; lineMask = new boolean[64][81][9]; sectionCounters = new int[9][27]; sectionMask = new int[9][27]; lineCounters = new int[64]; neighbors = new int[81][20]; unsolvedBoard = new int[81]; solvedBoard = new int[81]; cells = new int[][] {{0 ,1 ,2 ,9 ,10,11,18,19,20}, {3 ,4 ,5 ,12,13,14,21,22,23}, {6 ,7 ,8 ,15,16,17,24,25,26}, {27,28,29,36,37,38,45,46,47}, {30,31,32,39,40,41,48,49,50}, {33,34,35,42,43,44,51,52,53}, {54,55,56,63,64,65,72,73,74}, {57,58,59,66,67,68,75,76,77}, {60,61,62,69,70,71,78,79,80}}; } final public long solveSudoku(int[] board, int clue) { long t1 = 0,t2 = 0; t1 = System.nanoTime(); System.arraycopy(board, 0, unsolvedBoard, 0, 81); System.arraycopy(board, 0, solvedBoard, 0, 81); placedNumbers = 0; solutionFound = false; isEasy = true; isImpossible = false; for (int[] i : mask) { Arrays.fill(i, 0); } for (boolean[][] i : lineMask) { for (boolean[] j : i) { Arrays.fill(j, false); } } for (int i = 0; i < 81; i++) { if (solvedBoard[i] != -1) { put(i, solvedBoard[i]); placedNumbers++; } } solve(0, 0); t2 = System.nanoTime(); easySolved += isEasy ? 1 : 0; if (solutionFound && placedNumbers == 81) { totTime += t2-t1; if (shouldPrint || t2-t1 > 5*1_000_000_000L) { System.out.print(String.format( "Solution from %2d clues found in %7s", clue, printTime(t1, t2) )); shouldPrint = false; if (t2-t1 > 1*1000_000_000L) { System.out.println(); display2(board, solvedBoard); } } } else { System.out.println("No solution"); display2(unsolvedBoard, solvedBoard); return -1; } return t2 - t1; } final private void solve(int v, int vIndex) { lineCounters[vIndex] = 0; int easyIndex = placeEasy(vIndex); if (isImpossible) { resetEasy(vIndex, easyIndex); resetLineMask(vIndex); return; } if (placedNumbers == 81) { solutionFound = true; return; } // if (true) { // return; // } // either get the next empty cell // while (v < 81 && solvedBoard[v] >= 0) { // v++; // } // or get the cell with the fewest options generateFormattedMasks(); int minOptions = 9; for (int i = 0; i < 81; i++) { int options = formattedMask[i] & 0xffff; if (options > 0 && options < minOptions) { minOptions = options; v = i; } if (options == 0 && solvedBoard[i] == -1) { isImpossible = true; } } if (!isImpossible) { for (int c = 0; c < 9; c++) { if (isPossible(v, c)) { isEasy = false; put(v, c); placedNumbers++; solve(v + 1, vIndex + 1); if (solutionFound) { return; } unput(v, c); placedNumbers--; } } } resetEasy(vIndex, easyIndex); resetLineMask(vIndex); } final private void resetEasy(int vIndex, int easyIndex) { for (int i = 0; i < easyIndex; i++) { int tempv2 = placedMask[vIndex][i]; int c2 = solvedBoard[tempv2]; unput(tempv2, c2); placedNumbers--; } } final private void resetLineMask(int vIndex) { if (lineCounters[vIndex] > 0) { for (int i = 0; i < 81; i++) { for (int c = 0; c < 9; c++) { if (lineMask[vIndex][i][c]) { enable(i, c); lineMask[vIndex][i][c] = false; } } } } isImpossible = false; } final private int placeEasy(int vIndex) { int easyIndex = 0; int lastPlaced = 0, tempPlaced = 0, easyplaced = 0; int iter = 0; while (placedNumbers > lastPlaced+1) { lastPlaced = placedNumbers; tempPlaced = 0; while (placedNumbers > tempPlaced + 5) { tempPlaced = placedNumbers; easyIndex = placeNakedSingles(vIndex, easyIndex); if (isImpossible) { return easyIndex; } } tempPlaced = 0; while (placedNumbers < 55*1 && placedNumbers > tempPlaced + 2) { tempPlaced = placedNumbers; easyIndex = placeHiddenSingles(vIndex, easyIndex); if (isImpossible) { return easyIndex; } } tempPlaced = 0; while (placedNumbers < 65*1 && placedNumbers > tempPlaced + 1) { tempPlaced = placedNumbers; easyIndex = placeNakedSingles(vIndex, easyIndex); if (isImpossible) { return easyIndex; } } if (iter < 2 && placedNumbers < 55*1) { checkNakedTriples(vIndex); } if (placedNumbers < 45*1) { checkNakedDoubles(vIndex); identifyLines(vIndex); } iter++; } return easyIndex; } final private int placeNakedSingles(int vIndex, int easyIndex) { generateFormattedMasks(); for (int tempv = 0; tempv < 81; tempv++) { int possibilities = formattedMask[tempv]; if ((possibilities & 0xffff) == 1) { possibilities >>= 16; int c = 0; while ((possibilities & 1) == 0) { possibilities >>= 1; c++; } if (isPossible(tempv, c)) { put(tempv, c); placedMask[vIndex][easyIndex++] = tempv; placedNumbers++; } else { isImpossible = true; return easyIndex; } } else if (possibilities == 0 && solvedBoard[tempv] == -1) { isImpossible = true; return easyIndex; } } return easyIndex; } final private int placeHiddenSingles(int vIndex, int easyIndex) { for (int[] i : sectionCounters) { Arrays.fill(i, 0); } for (int c = 0; c < 9; c++) { for (int v = 0; v < 81; v++) { if (isPossible(v, c)) { int cell = 3 * (v / 27) + ((v / 3) % 3); sectionCounters[c][v / 9]++; sectionCounters[c][9 + (v % 9)]++; sectionCounters[c][18 + cell]++; sectionMask[c][v / 9] = v; sectionMask[c][9 + (v % 9)] = v; sectionMask[c][18 + cell] = v; } } int v; for (int i = 0; i < 9; i++) { if (sectionCounters[c][i] == 1) { v = sectionMask[c][i]; if (isPossible(v, c)) { put(v, c); placedMask[vIndex][easyIndex++] = v; placedNumbers++; int cell = 3 * (v / 27) + ((v / 3) % 3); sectionCounters[c][9 + (v%9)] = 9; sectionCounters[c][18 + cell] = 9; } else { isImpossible = true; return easyIndex; } } } for (int i = 9; i < 18; i++) { if (sectionCounters[c][i] == 1) { v = sectionMask[c][i]; if (isPossible(v, c)) { put(v, c); placedMask[vIndex][easyIndex++] = v; int cell = 3 * (v / 27) + ((v / 3) % 3); placedNumbers++; sectionCounters[c][18 + cell]++; } else { isImpossible = true; return easyIndex; } } } for (int i = 18; i < 27; i++) { if (sectionCounters[c][i] == 1) { v = sectionMask[c][i]; if (isPossible(v, c)) { put(v, c); placedMask[vIndex][easyIndex++] = v; placedNumbers++; } else { isImpossible = true; return easyIndex; } } } } return easyIndex; } final private int getFormattedMask(int v) { if (solvedBoard[v] >= 0) { return 0; } int x = 0; int y = 0; for (int c = 8; c >= 0; c--) { x <<= 1; x += mask[v][c] == 0 ? 1 : 0; y += mask[v][c] == 0 ? 1 : 0; } x <<= 16; return x + y; } final private int getCachedMask(int v) { return formattedMask[v]; } final private void generateFormattedMasks() { for (int i = 0; i < 81; i++) { formattedMask[i] = getFormattedMask(i); } } final private void generateFormattedMasks(int[] idxs) { for (int i : idxs) { formattedMask[i] = getFormattedMask(i); } } final private void checkNakedDoubles(int vIndex) { generateFormattedMasks(); for (int i = 0; i < 81; i++) { int bitmask = formattedMask[i]; if ((bitmask & 0xffff) == 2) { for (int j = i+1; j < (i/9+1)*9; j++) { int bitmask_j = formattedMask[j]; if (bitmask == bitmask_j) { bitmask >>= 16; int c0, c1, k = 0; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c0 = k; bitmask >>= 1; k++; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c1 = k; for (int cell = (i/9)*9; cell < (i/9+1)*9; cell++) { if (cell != i && cell != j) { if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } } } } } } } for (int idx = 0; idx < 81; idx++) { int i = (idx%9)*9 + idx/9; int bitmask = formattedMask[i]; if ((bitmask & 0xffff) == 2) { for (int j = i+9; j < 81; j += 9) { int bitmask_j = formattedMask[j]; if (bitmask == bitmask_j) { bitmask >>= 16; int c0, c1, k = 0; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c0 = k; bitmask >>= 1; k++; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c1 = k; for (int cell = i % 9; cell < 81; cell += 9) { if (cell != i && cell != j) { if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } } } } } } } for (int idx = 0; idx < 9; idx++) { for (int i = 0; i < 9; i++) { int bitmask = formattedMask[cells[idx][i]]; if ((bitmask & 0xffff) == 2) { for (int j = i+1; j < 9; j++) { int bitmask_j = formattedMask[cells[idx][j]]; if (bitmask == bitmask_j) { bitmask >>= 16; int c0, c1, k = 0; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c0 = k; bitmask >>= 1; k++; while ((bitmask & 1) == 0) { k++; bitmask >>= 1; } c1 = k; for (int cellIdx = 0; cellIdx < 9; cellIdx++) { if (cellIdx != i && cellIdx != j) { int cell = cells[idx][cellIdx]; if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } } } } } } } } } final private void checkNakedTriples(int vIndex) { generateFormattedMasks(); for (int i = 0; i < 81; i++) { int bitmask = formattedMask[i]; if ((bitmask & 0xffff) == 3) { for (int j = i+1; j < (i/9+1)*9; j++) { int bitmask_j = formattedMask[j]; if (bitmask_j > 0 && bitmask == (bitmask | bitmask_j)) { for (int k = j+1; k < (i/9+1)*9; k++) { int bitmask_k = formattedMask[k]; if (bitmask_k > 0 && bitmask == (bitmask | bitmask_k)) { int bitmask_shifted = bitmask >> 16; int c0, c1, c2, l = 0; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c0 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c1 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c2 = l; for (int cell = (i/9)*9; cell < (i/9+1)*9; cell++) { if (cell != i && cell != j && cell != k) { if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c2]) { disable(cell, c2); lineMask[vIndex][cell][c2] = true; lineCounters[vIndex]++; } } } } } } } } } for (int idx = 0; idx < 81; idx++) { int i = (idx%9)*9 + idx/9; int bitmask = formattedMask[i]; if ((bitmask & 0xffff) == 3) { for (int j = i+9; j < 81; j += 9) { int bitmask_j = formattedMask[j]; if (bitmask_j > 0 && bitmask == (bitmask | bitmask_j)) { for (int k = j+9; k < 81; k += 9) { int bitmask_k = formattedMask[k]; if (bitmask_k > 0 && bitmask == (bitmask | bitmask_k)) { int bitmask_shifted = bitmask >> 16; int c0, c1, c2, l = 0; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c0 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c1 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c2 = l; for (int cell = i%9; cell < 81; cell += 9) { if (cell != i && cell != j && cell != k) { if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c2]) { disable(cell, c2); lineMask[vIndex][cell][c2] = true; lineCounters[vIndex]++; } } } } } } } } } for (int idx = 0; idx < 9; idx++) { for (int i = 0; i < 9; i++) { int bitmask = formattedMask[cells[idx][i]]; if ((bitmask & 0xffff) == 3) { for (int j = i+1; j < 9; j++) { int bitmask_j = formattedMask[cells[idx][j]]; if (bitmask_j > 0 && bitmask == (bitmask | bitmask_j)) { for (int k = j+1; k < 9; k++) { int bitmask_k = formattedMask[cells[idx][k]]; if (bitmask_k > 0 && bitmask == (bitmask | bitmask_k)) { int bitmask_shifted = bitmask >> 16; int c0, c1, c2, l = 0; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c0 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c1 = l; bitmask_shifted >>= 1; l++; while ((bitmask_shifted & 1) == 0) { l++; bitmask_shifted >>= 1; } c2 = l; for (int cellIdx = 0; cellIdx < 9; cellIdx++) { if (cellIdx != i && cellIdx != j && cellIdx != k) { int cell = cells[idx][cellIdx]; if (!lineMask[vIndex][cell][c0]) { disable(cell, c0); lineMask[vIndex][cell][c0] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c1]) { disable(cell, c1); lineMask[vIndex][cell][c1] = true; lineCounters[vIndex]++; } if (!lineMask[vIndex][cell][c2]) { disable(cell, c2); lineMask[vIndex][cell][c2] = true; lineCounters[vIndex]++; } } } } } } } } } } } final private void identifyLines(int vIndex) { int disabledLines = 0; int[][] tempRowMask = new int[3][9]; int[][] tempColMask = new int[3][9]; for (int i = 0; i < 9; i++) { for (int c = 0; c < 9; c++) { for (int j = 0; j < 3; j++) { tempRowMask[j][c] = 0; tempColMask[j][c] = 0; } for (int j = 0; j < 9; j++) { if (mask[cells[i][j]][c] == 0) { tempRowMask[j/3][c]++; tempColMask[j%3][c]++; } } int rowCount = 0; int colCount = 0; int rowIdx = -1, colIdx = -1; for (int j = 0; j < 3; j++) { if (tempRowMask[j][c] > 0) { rowCount++; rowIdx = j; } if (tempColMask[j][c] > 0) { colCount++; colIdx = j; } } if (rowCount == 1) { for (int j = (i/3)*3; j < (i/3 + 1)*3; j++) { if (j != i) { for (int k = rowIdx*3; k < (rowIdx+1)*3; k++) { int cell = cells[j][k]; if (!lineMask[vIndex][cell][c]) { disable(cell, c); lineMask[vIndex][cell][c] = true; lineCounters[vIndex]++; } } } } } if (colCount == 1) { for (int j = i % 3; j < 9; j += 3) { if (j != i) { for (int k = colIdx; k < 9; k += 3) { int cell = cells[j][k]; if (!lineMask[vIndex][cell][c]) { disable(cell, c); lineMask[vIndex][cell][c] = true; lineCounters[vIndex]++; } } } } } } } } final private boolean isPossible(int v, int c) { return mask[v][c] == 0; } final private int checkMask(int[][] neighbors, int v, int c) { int tempValue = 0; for (int n : neighbors[v]) { if (mask[n][c] > 0) { tempValue++; } } return tempValue; } final private void put(int v, int c) { solvedBoard[v] = c; for (int i : neighbors[v]) { mask[i][c]++; } for (int i = 0; i < 9; i++) { mask[v][i]++; } } final private void disable(int v, int c) { mask[v][c]++; } final private void unput(int v, int c) { solvedBoard[v] = -1; for (int i : neighbors[v]) { mask[i][c]--; } for (int i = 0; i < 9; i++) { mask[v][i]--; } } final private void enable(int v, int c) { // enables++; mask[v][c]--; } public String getString(int[] board) { StringBuilder s = new StringBuilder(); for (int i : board) { s.append(i+1); } return s.toString(); } public long getTime() { return totTime; } public static String printTime(long t1, long t2) { String unit = " ns"; if (t2-t1 > 10000) { unit = " us"; t1 /= 1000; t2 /= 1000; } if (t2-t1 > 10000) { unit = " ms"; t1 /= 1000; t2 /= 1000; } if (t2-t1 > 10000) { unit = " seconds"; t1 /= 1000; t2 /= 1000; } return (t2-t1) + unit; } public void display(int[] board) { for (int i = 0; i < 9; i++) { if (i % 3 == 0) { System.out.println("+-----+-----+-----+"); } for (int j = 0; j < 9; j++) { if (j % 3 == 0) { System.out.print("|"); } else { System.out.print(" "); } if (board[i*9+j] != -1) { System.out.print(board[i*9+j]+1); } else { System.out.print(" "); } } System.out.println("|"); } System.out.println("+-----+-----+-----+"); } public void display2(int[] board, int[] solved) { for (int i = 0; i < 9; i++) { if (i % 3 == 0) { System.out.println("+-----+-----+-----+ +-----+-----+-----+"); } for (int j = 0; j < 9; j++) { if (j % 3 == 0) { System.out.print("|"); } else { System.out.print(" "); } if (board[i*9+j] != -1) { System.out.print(board[i*9+j]+1); } else { System.out.print(" "); } } System.out.print("| "); for (int j = 0; j < 9; j++) { if (j % 3 == 0) { System.out.print("|"); } else { System.out.print(" "); } if (solved[i*9+j] != -1) { System.out.print(solved[i*9+j]+1); } else { System.out.print(" "); } } System.out.println("|"); } System.out.println("+-----+-----+-----+ +-----+-----+-----+"); } private boolean contains(int[] a, int v) { for (int i : a) { if (i == v) { return true; } } return false; } public void connect() { for (int i = 0; i < 81; i++) { for (int j = 0; j < 20; j++) { neighbors[i][j] = -1; } } int[] n_count = new int[81]; HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>(); for (int[] c: cells) { ArrayList<Integer> temp = new ArrayList<Integer>(); for (int v : c) { temp.add(v); } for (int v : c) { map.put(v,temp); } } for (int i = 0; i < 81; i++) { for (int j = (i/9)*9; j < (i/9)*9 + 9; j++) { if (i != j) { neighbors[i][n_count[i]++] = j; } } for (int j = i%9; j < 81; j += 9) { if (i != j) { neighbors[i][n_count[i]++] = j; } } for (int j : map.get(i)) { if (i != j) { if (!contains(neighbors[i], j)) { neighbors[i][n_count[i]++] = j; } } } } } public static int[][] getInput(String filename) { int[][] boards; try (BufferedInputStream in = new BufferedInputStream( new FileInputStream(filename))) { BufferedReader r = new BufferedReader( new InputStreamReader(in, StandardCharsets.UTF_8)); int n = Integer.valueOf(r.readLine()); boards = new int[n][81]; clues = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < 81; j++) { int x = r.read(); boards[i][j] = x - 49; clues[i] += x > 48 ? 1 : 0; } r.read(); } r.close(); } catch (IOException ex) { throw new RuntimeException(ex); } return boards; } private int getTotEasy() { return totEasy; } public String getSolution() { StringBuilder s = new StringBuilder(256); for (int i : unsolvedBoard) { s.append(i+1); } s.append(","); for (int i : solvedBoard) { s.append(i+1); } return s.toString(); } public static void main (String[] args) { long t0 = System.nanoTime(); Sudoku gc = new Sudoku(); File f; PrintWriter p; try { f = new File("sudoku_output.txt"); p = new PrintWriter(f); } catch (Exception e) { return; } if (args.length != 1) { System.out.println("Usage: java Sudoku <input_file>"); return; } int[][] boards = gc.getInput(args[0]); long tinp = System.nanoTime(); gc.connect(); long t1 = System.nanoTime(); p.println(boards.length); long maxSolveTime = 0; int maxSolveIndex = 0; long[] solveTimes = new long[boards.length]; for (int i = 0; i < boards.length; i++) { long tempTime = System.nanoTime(); if (tempTime - gc.lastPrint > 200_000_000 || i == boards.length - 1) { gc.shouldPrint = true; gc.lastPrint = tempTime; System.out.print(String.format( "\r(%7d/%7d) ", i+1, boards.length)); } long elapsed = gc.solveSudoku(boards[i], gc.clues[i]); if (elapsed == -1) { System.out.println("Impossible: " + i); } if (elapsed > maxSolveTime) { maxSolveTime = elapsed; maxSolveIndex = i; } solveTimes[i] = elapsed; p.println(gc.getSolution()); // break; } p.close(); long t2 = System.nanoTime(); Arrays.sort(solveTimes); System.out.println(); System.out.println("Median solve time: " + gc.printTime(0, solveTimes[boards.length/2])); System.out.println("Longest solve time: " + gc.printTime(0, maxSolveTime) + " for board " + maxSolveIndex); gc.display(boards[maxSolveIndex]); System.out.println(); System.out.println("Total time (including prints): " + gc.printTime(t0,t2)); System.out.println("Sudoku solving time: " + gc.printTime(0,gc.getTime())); System.out.println("Average time per board: " + gc.printTime(0,gc.getTime()/boards.length)); System.out.println("Number of one-choice digits per board: " + String.format("%.2f", gc.getTotEasy()/(double)boards.length)); System.out.println("Easily solvable boards: " + gc.easySolved); System.out.println("\nInput time: " + gc.printTime(t0,tinp)); System.out.println("Connect time: " + gc.printTime(tinp,t1)); try { Thread.sleep(10000); } catch (InterruptedException e) { } } } ``` [Answer] # Python3 - 2min 1.007s official score It takes around 100 seconds on my i5-9400F ``` import copy SUDOKU_VALUES = [1, 2, 4, 8, 16, 32, 64, 128, 256] SUDOKU_MAX = 511 OPTION_COUNT_CACHE = [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 5, 6, 6, 7, 6, 7, 7, 8, 6, 7, 7, 8, 7, 8, 8, 9 ] # Basically just .count_ones() class SudokuEmpty: def __init__(self): self.data = list(range(81)) self.pos = 81 def remove(self, index): self.pos -= 1 data = self.data data[index], data[self.pos] = data[self.pos], data[index] class Solver: def __init__(self, sudoku): self.to_explore = SudokuEmpty() self.options = [SUDOKU_MAX for _ in range(81)] for (i, item) in enumerate(sudoku): if item != 0: self.options[i] = SUDOKU_VALUES[item - 1] self.apply_number(i) def hidden_singles(self, square): options = self.options value = options[square] options[square] = 0 row_start = square // 9 * 9 column_start = square % 9 box_start = square // 3 % 3 * 3 + square // 27 * 27 needed = (SUDOKU_MAX - ((options[row_start + 8] | options[row_start + 7] | options[row_start + 6] | options[row_start + 5] | options[row_start + 4] | options[row_start + 3] | options[row_start + 2] | options[row_start + 1] | options[row_start]) & (options[column_start + 72] | options[column_start + 63] | options[column_start + 54] | options[column_start + 45] | options[column_start + 36] | options[column_start + 27] | options[column_start + 18] | options[column_start + 9] | options[column_start]) & (options[box_start + 20] | options[box_start + 19] | options[box_start + 18] | options[box_start + 11] | options[box_start + 10] | options[box_start + 9] | options[box_start + 2] | options[box_start + 1] | options[box_start]))) option_count = OPTION_COUNT_CACHE[needed] if option_count == 0: self.options[square] = value return True elif option_count == 1: if value & needed != 0: self.options[square] = value & needed return True else: return False else: return False def apply_number(self, square): options = self.options value = options[square] not_value = SUDOKU_MAX - value column_start = square % 9 row_start = square - column_start box_start = square // 3 % 3 * 3 + square // 27 * 27 options[row_start + 8] &= not_value options[row_start + 7] &= not_value options[row_start + 6] &= not_value options[row_start + 5] &= not_value options[row_start + 4] &= not_value options[row_start + 3] &= not_value options[row_start + 2] &= not_value options[row_start + 1] &= not_value options[row_start] &= not_value options[column_start + 72] &= not_value options[column_start + 63] &= not_value options[column_start + 54] &= not_value options[column_start + 45] &= not_value options[column_start + 36] &= not_value options[column_start + 27] &= not_value options[column_start + 18] &= not_value options[column_start + 9] &= not_value options[column_start] &= not_value options[box_start + 20] &= not_value options[box_start + 19] &= not_value options[box_start + 18] &= not_value options[box_start + 11] &= not_value options[box_start + 10] &= not_value options[box_start + 9] &= not_value options[box_start + 2] &= not_value options[box_start + 1] &= not_value options[box_start] &= not_value options[square] = value def process(self, routes): values = [] while 1: min_length = 20 min_pos = 0 min_pos_x = 0 x = 0 while x < self.to_explore.pos: pos = self.to_explore.data[x] if not self.hidden_singles(pos): return False option = self.options[pos] length = OPTION_COUNT_CACHE[option] if length < min_length: if length == 0: return False elif length == 1: for (i, item) in enumerate(SUDOKU_VALUES): if option == item: self.apply_number(pos) self.to_explore.remove(x) break else: min_length = length min_pos = pos min_pos_x = x x += 1 else: x += 1 if min_length != 20: values.clear() options = self.options[min_pos] for (i, item) in enumerate(SUDOKU_VALUES): if options & item != 0: values.append(i + 1) if not values: return False self.to_explore.remove(min_pos_x) item = values.pop() for value in values: clone = copy.deepcopy(self) clone.options[min_pos] = SUDOKU_VALUES[value - 1] clone.apply_number(min_pos) routes.append(clone) self.options[min_pos] = SUDOKU_VALUES[item - 1] self.apply_number(min_pos) else: return True def get_result(self): solution = [0 for _ in range(81)] for (i, option) in enumerate(self.options): for (x, value) in enumerate(SUDOKU_VALUES): if option == value: solution[i] = x + 1 break return solution def solve(sudoku): routes = [Solver(sudoku)] while routes: route = routes.pop() result = route.process(routes) if result: return route.get_result() raise Exception("Empty routes, but still unsolved") if __name__ == '__main__': with open('all_17_clue_sudokus.txt') as file: sudokus = file.read().splitlines() print(sudokus[0]) for sudoku in sudokus[1:]: solution = ''.join(map(str, solve(list(map(int, sudoku))))) print('%s,%s' % (sudoku, solution)) ``` The path to the sudokus is hardcoded, it has to be `all_17_clue_sudokus.txt` To run ``` time python3 lib.py > output sha256sum output ``` [Answer] # C - 12min 28.374s official score runs for about ~~30m~~ 15m on my i5-7200U and produces the correct md5 hash ``` #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/time.h> #define B break #define O const #define P printf #define R return #define S static #define $(x,y...) if(x){y;} #define E(x...) else{x;} #define W(x,y...) while(x){y;} #define fi(x,y...) for(I i=0,_n=(x);i<_n;i++){y;} #define fj(x,y...) for(I j=0,_n=(x);j<_n;j++){y;} typedef void V;typedef char C;typedef short H;typedef int I;typedef long long L; S C h[81][20]; //h[i][0],h[i][1],..,h[i][19] are the squares that clash with square i S H a[81] //a[i]: bitmask of possible choices; initially one of 1<<0, 1<<1 .. 1<<8, or 511 (i.e. nine bits set) ,b[81]; //b[i]: negated bitmask of impossible chioces; once we know square i has value v, b[i] becomes ~(1<<v) S I f(){ //f:recursive solver I p=-1; //keep track of the popcount (number of 1 bits) in a W(1,I q=0; //simple non-recursive deductions: fi(81,fj(20,a[i]&=b[h[i][j]]) // a[i] must not share bits with its clashing squares $(!(a[i]&a[i]-1),$(!a[i],R 0)b[i]=~a[i]) // if a[i] has one bit left, update b[i]. if a[i]=0, we have a contradiction q+=__builtin_popcount(a[i])) // compute new popcount $(p==q,B)p=q;) // if the popcount of a[] changed, try to do more deductions I k=-1,mc=10;fi(81,$(b[i]==-1,I c=__builtin_popcount(a[i]);$(c<mc,k=i;mc=c;$(c==2,B)))) //find square with fewest options left $(k==-1,R 1) //if there isn't any such, we're done - success! otherwise k is that square fi(9,$(a[k]&1<<i,H a0[81],b0[81]; //try different values for square k memcpy(a0,a,81*sizeof(*a));memcpy(b0,b,81*sizeof(*b)); // save a and b a[k]=1<<i;b[k]=~a[k];$(f(),R 1) // set square k and make a recursive call memcpy(a,a0,81*sizeof(*a));memcpy(b,b0,81*sizeof(*b)))) // restore a and b R 0;} S L tm(){struct timeval t;gettimeofday(&t,0);R t.tv_sec*1000000+t.tv_usec;} //current time in microseconds I main(){L t=0;I n;scanf("%d",&n);P("%d\n",n); fi(81,L l=0;fj(81,$(i!=j&&(i%9==j%9||i/9==j/9||(i/27==j/27&&i%9/3==j%9/3)),h[i][l++]=j))) //precompute h fi(n,S C s[82];scanf("%s",s);printf("%s,",s); //i/o and loop over puzzles fj(81,a[j]=s[j]=='0'?511:1<<(s[j]-'1');b[j]=s[j]=='0'?-1:~a[j]) //represent '1' .. '9' as 1<<0 .. 1<<8, and 0 as 511 t-=tm();I r=f();t+=tm(); //measure time only for the solving function $(!r,P("can't solve\n");exit(1)) //shouldn't happen fj(81,s[j]=a[j]&a[j]-1?'0':'1'+__builtin_ctz(a[j])) //1<<0 .. 1<<8 to '1' .. '9' P("%s\n",s)) //output fflush(stdout);dprintf(2,"time:%lld microseconds\n",t);R 0;} //print self-measured time to stderr so it doesn't affect stdout's md5 ``` compile (preferably with clang v6) and run: ``` clang -O3 -march=native a.c time ./a.out <all_17_clue_sudokus.txt | tee o.txt | nl md5sum o.txt ``` [Answer] # Typescript([Deno](https://deno.land/)) - 22min 12s unofficial score on an Lenovo G50-45 Laptop with 4cores and 4threads @1.5GHz reads from `all_17_clue_sudokus.txt` or first argument outputs to `output.txt` or second argument download and run with `deno run --allow-all https://raw.githubusercontent.com/RubenArtmann/sudoku-solver/master/mod.ts` with [Deno](https://deno.land/) installed [github page](https://github.com/RubenArtmann/sudoku-solver) solver.ts ``` const parse = (string: string)=>{ let sudoku = new Uint16Array(9*9); for(let i=0; i<string.length; i++) { let n = string.charCodeAt(i)-"1".charCodeAt(0); sudoku[i] = n>=0&&n<9?1<<n:511; } return sudoku; }; const bitCount = (n:number)=>{ n = n - ((n >> 1) & 0x55555555) n = (n & 0x33333333) + ((n >> 2) & 0x33333333) return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24 }; const forced = (sudoku:Uint16Array)=>{ for(let i=0; i<sudoku.length; i++) { let row = i%9; let column = Math.floor(i/9); // skip if already spread if(sudoku[i]&(1<<9)) continue; if(bitCount(sudoku[i]&511)===1) { for(let j=0; j<9; j++) { if(j!==column) sudoku[row+j*9] &= ~(sudoku[i]&511); if(j!==row) sudoku[j+column*9] &= ~(sudoku[i]&511); let xoff = row-row%3; let yoff = column-column%3; let x = xoff+j%3; let y = yoff+Math.floor(j/3); if(x!==row && y!==column) sudoku[x+y*9] &= ~(sudoku[i]&511); // set already spread bit sudoku[i] |= 1<<9; } } } }; const dump = (sudoku:Uint16Array)=>{ return [...sudoku].map(e=>{ let char = ""; for(let j=0; j<9; j++) { if(e&(1<<j)) char += j+1; } if(char.length!==1) { log(sudoku) throw new Error(""); } return char; }).join(""); }; const log = (sudoku:Uint16Array)=>{ for(let column=0; column<9; column++) { console.log([...sudoku.slice(column*9,column*9+9)].map((n,row)=>{ let string = ""; for(let j=0; j<9; j++) { string += sudoku[column*9+row]&(1<<j)?j+1:"."; } return string; }).join(" ")); } console.log("") }; let count = 0; const solve = (sudoku:Uint16Array)=>{ let sudokuBuf = new Uint16Array(9*9); let stack: Uint16Array[] = [sudoku]; let stack_length = 1; while(stack_length>0) { count++; // console.log(stack.length) stack_length--; let sudoku: Uint16Array = stack[stack_length] as Uint16Array; stack[stack_length] = sudokuBuf; sudokuBuf = sudoku; // do forced moves forced(sudoku); let solved = true; let invalid = false; for(let i=0; i<sudoku.length; i++) { let c = bitCount(sudoku[i]&511); if(c!==1) solved = false; if(c===0) { invalid = true; break; } } if(invalid) continue; if(solved) { // need to apply forced one more time and check for changes / empty cells forced(sudoku); let solved = true; for(let i=0; i<sudoku.length; i++) { let c = bitCount(sudoku[i]&511); if(c===0) solved = false; } if(solved) return sudoku; continue; } // choose cell to split on let splitIndex = -1; for(let i=2; i<=9; i++) { for(let j=0; j<sudoku.length; j++) { if(bitCount(sudoku[j]&511)===i) { splitIndex = j; i = 1000; break; } } } if(splitIndex<0) throw new Error(""); // branch/split for(let i=0; i<9; i++) { if(sudoku[splitIndex]&(1<<i)) { if(stack[stack_length]===undefined) stack[stack_length] = new Uint16Array(9*9); let newsudoku = stack[stack_length]; newsudoku.set(sudoku,0); newsudoku[splitIndex] = 1<<i; stack_length++; } } // log(sudoku); } throw new Error("Out of Options!") return new Uint16Array(9*9); }; const context: Worker = self as any; context.onmessage = (event)=>{ let result = dump(solve(parse(event.data.data))); // console.log(count) context.postMessage({ data: result, callback: event.data.callback }) }; ``` mod.ts ``` let callbacks = new Map(); let workers: any[] = []; let tasks: {data:any,callback:number}[] = []; for(let i=0; i<4; i++) { let worker = new Worker(new URL("solver.ts", import.meta.url).toString(),{ type: "module" }) as any; worker.tasks = 0; worker.onmessage = (event:{data:any})=>{ worker.tasks--; callbacks.get(event.data.callback)(event.data.data); callbacks.delete(event.data.callback); }; workers.push(worker); } const sleep = (time:number)=>{ return new Promise((resolve)=>{ setTimeout(resolve,time); }); }; const loadBalancer = async()=>{ while(true) { // console.log(workers.map(w=>w.tasks),tasks.length); let dispatches = 0; for(let i=0; i<workers.length; i++) { let worker = workers[i]; if(worker.tasks>=5||tasks.length<=0) continue; if(worker.taks<=0) console.log("running low!") let task = tasks.shift(); if(task === undefined) continue; worker.postMessage(task); worker.tasks++; dispatches++; } if(dispatches<=0) await sleep(100); } }; loadBalancer(); const dispatch = async(data:any)=>{ let random = Math.random(); tasks.push({ data: data, callback: random }); return new Promise((resolve)=>{ callbacks.set(random,resolve); }); }; // dispatch("030000000000001008700580000000024050040873900003600000900000002005002091200000704").then(console.log) // console.log(workers) let count = 0; let file = Deno.readTextFileSync(Deno.args[0]||"./all_17_clue_sudokus.txt"); // let file = Deno.readTextFileSync("./hard_sudokus.txt"); let sudokus = file.split("\n").slice(1); let promises = sudokus.map(async(e,i)=>{ let result = await dispatch(e); count++; console.log(count,"/",sudokus.length); console.log(e); console.log(result); return result; }); let solutions = await Promise.all(promises); console.log("done!"); workers.map(w=>w.terminate()); let output = ""; output += `${sudokus.length}\n`; for(let i=0; i<sudokus.length; i++) { output += `${sudokus[i]},${solutions[i]}\n`; } Deno.writeTextFileSync(Deno.args[1]||"./output.txt",output); Deno.exit(0) ``` [Answer] # Rust - 0.150s unofficial score <https://github.com/mstdokumaci/sudokumaci/tree/main/rust> Here is my attempt in Rust. For the list of sudoku puzzles above (`all_17_clue`), I get ~150ms on a MacBook Pro (16-inch, 2019, 2.3 GHz i9-9880H). I build the binary by this command: `cargo rustc --release -- -C target-cpu=native` I am not an expert on writing optimized code and I am coding in Rust for the first time. I believe the algorithm is at the sweet spot of human solutions and brute force, and it can be further optimized. I would appreciate it if anybody would like to suggest any improvements. ]
[Question] [ In the esoteric programming language Curly, programs consist solely of curly braces `{}` and semicolons `;`. Despite this humble toolset, Curly has literals that can represent any nonnegative integer. The format is a little hard for the uninitiated to read, though, so let's write some code to do the conversion for us. ## Format of numbers Curly numbers are structured according to the following rules: 1. Adding a semicolon adds one to the number. 2. A number enclosed in curly braces is multiplied by four. 3. Curly-brace groups may be nested but not concatenated. Braces must match properly. 4. Semicolons outside a set of curly braces must come afterward, not before. 5. To avoid ambiguity in parsing, a number must always start with a curly brace. Some examples: ``` {;;} 2*4 = 8 {{;};}; (1*4+1)*4+1 = 21 {};;; 0*4+3 = 3 ``` (Note that rule 5 means the numbers 0 to 3 must start with an empty pair of curly braces.) And some invalid examples: ``` {{;}{;;}} Curly brace groups side-by-side, not nested {;}} Unmatched brace {;{;}} Semicolon before curly-brace group ;;; Number does not start with curly brace ``` Here's a BNF grammar for Curly numbers: ``` <number> ::= "{" <inner> "}" <semis> <inner> ::= <semis> | <number> <semis> ::= ";" <semis> | "" ``` Numbers like `{;;;;}` (more than 3 semicolons in a row) or `{{};}` (unnecessary empty brace groups) are called *improper* Curly numbers. They obey the above grammar and can be evaluated in the usual way, but they are also capable of shorter representations (for the above examples, `{{;}}` and `{;}` respectively). ## The challenge Write a program or function that inputs/receives a string. If the string is a nonnegative decimal integer, output/return the *proper* (i.e. shortest possible) Curly representation for that integer. If the string is a Curly number, output/return its decimal representation. **Input** can be received via STDIN, command-line argument, or function parameter. It *must* be a string; that is, you may not write a function that accepts strings for Curly numbers but integers for decimal numbers. **Output** can be printed to STDOUT or returned from the function. A function *may* return an integer when appropriate, or it may return strings in all situations. Your program does not have to handle bad input (Curly numbers that break the formatting rules, floating point numbers, negative integers, random text), and it is **not** required to handle improper Curly numbers (but see below). Input will consist only of printable ASCII characters. ## Scoring The shortest code in bytes wins. If your program can do **both** of the following: 1. correctly handle improper Curly numbers, and 2. when given a Curly number, ignore any extra characters that aren't `{};` then subtract 10% from your score. (Integer input will never have extraneous characters, even for the bonus.) ## Test cases ``` Input Output {;;} 8 {{;};}; 21 {};;; 3 {{{{;}}};} 260 {} 0 4 {;} 17 {{;}}; 1 {}; 0 {} 96 {{{;};;}} ``` For the bonus: ``` {};;;;; 5 {{;;;;};;} 72 c{u;r;l}y;! 9 42{;} ;;;; 8 ``` Note: Curly is not yet implemented. But if this question does well, I may develop it further. [Answer] # Pyth, ~~35~~ 32 bytes - 10% = 28.8 ``` .x.U+jb`HZ*R\;.[Z2jsz4i/R\;cz\}4 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=.x%2B*%5C%7BtlK.[Z2jvz4j%5C%7D*R%5C%3BKi%2FR%5C%3Bcz%5C%7D4&input=%7B%7B%3B%7D%3B%7D%3B&test_suite_input=%7B%3B%3B%7D%0A%7B%7B%3B%7D%3B%7D%3B%0A%7B%7D%3B%3B%3B%0A%7B%7B%7B%7B%3B%7D%7D%7D%3B%7D%0A%7B%7D%0A4%0A17%0A1%0A0%0A96%0A%7B%7D%3B%3B%3B%3B%3B%0A%7B%7B%3B%3B%3B%3B%7D%3B%3B%7D%0Ac%7Bu%3Br%3Bl%7Dy%3B!%0A42%7B%3B%7D+%3B%3B%3B%3B&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=.x%2B*%5C%7BtlK.[Z2jvz4j%5C%7D*R%5C%3BKi%2FR%5C%3Bcz%5C%7D4&input=%7B%7B%3B%7D%3B%7D%3B&test_suite=1&test_suite_input=%7B%3B%3B%7D%0A%7B%7B%3B%7D%3B%7D%3B%0A%7B%7D%3B%3B%3B%0A%7B%7B%7B%7B%3B%7D%7D%7D%3B%7D%0A%7B%7D%0A4%0A17%0A1%0A0%0A96%0A%7B%7D%3B%3B%3B%3B%3B%0A%7B%7B%3B%3B%3B%3B%7D%3B%3B%7D%0Ac%7Bu%3Br%3Bl%7Dy%3B!%0A42%7B%3B%7D+%3B%3B%3B%3B&debug=0) edit: As it turned out, I accidentally can also handle improper Curly Numbers. Wasn't planned at all. ;-) ### Explanation: There are two expressions in the code. The first one converts a number into a Curly Number, and the second one converts a Curly Number into a regular number. `.x` handles, which expression gets printed. It will try to print the first expression. If there are any non-digits in the input, the first expression fails (via Exception). `.x` catches the Exception and prints the second one. ``` .U+jb`HZ*R\;.[Z2jsz4 # number to Curly Number sz read the input and converts it to an int j 4 convert to base 4 .[Z2 pad zeros on the left, until length is >= 2 *R\; convert each digit to ";"s lets call this list of ";"s Y .U reduce this list, start with b=Y[0], Z iterates over Y[1], Y[2], ..., update b in each step with: jb`H put b into curly brackets + Z and append Z i/R\;cz\}4 # Curly Number to regular number cz\} split the input by "}" /R\; count the ";"s in each string i 4 convert this list from base 4 to base 10 ``` [Answer] # CJam, ~~51~~ ~~47~~ ~~44~~ 41 bytes ``` r_'{-_@={i4bYUe[';f*{{}s@*\+}*}{'}/:,4b}? ``` Try it online: [sample run](http://cjam.aditsu.net/#code=r_'%7B-_%40%3D%7Bi4bYUe%5B'%3Bf*%7B%7B%7Ds%40*%5C%2B%7D*%7D%7B'%7D%2F%3A%2C4b%7D%3F&input=96) | [test suite](http://cjam.aditsu.net/#code=qN%2F%7BS%2F0%3D%0A%20%20%20%20_'%7B-_%40%3D%7Bi4bYUe%5B'%3Bf*%7B%7B%7Ds%40*%5C%2B%7D*%7D%7B'%7D%2F%3A%2C4b%7D%3F%0AN%7D%2F&input=%7B%3B%3B%7D%20%20%20%20%20%20%20%208%0A%7B%7B%3B%7D%3B%7D%3B%20%20%20%20%2021%0A%7B%7D%3B%3B%3B%20%20%20%20%20%20%203%0A%7B%7B%7B%7B%3B%7D%7D%7D%3B%7D%20%20260%0A%7B%7D%20%20%20%20%20%20%20%20%20%200%0A4%20%20%20%20%20%20%20%20%20%20%20%7B%3B%7D%0A17%20%20%20%20%20%20%20%20%20%20%7B%7B%3B%7D%7D%3B%0A1%20%20%20%20%20%20%20%20%20%20%20%7B%7D%3B%0A0%20%20%20%20%20%20%20%20%20%20%20%7B%7D%0A96%20%20%20%20%20%20%20%20%20%20%7B%7B%7B%3B%7D%3B%3B%7D%7D) ### How it works ``` r e# Read a token from STDIN. _'{- e# Remove all left curly brackets from a copy of the token. _@ e# Copy the modified token and rotate the original on top of it. = e# Check for equality. { e# If the strings were equal: i4b e# Convert to integer, then to base 4. YUe[ e# Left-pad the resulting array with zeroes to a length of 2. ';f* e# Replace each digit with that many semicolons. { e# For each string of semicolons but the first: {}s e# Push the string "{}". @ e# Rotate the first string or the result of the previous e# iteration on top of the stack. * e# Join, i.e., surround the string with curly brackets. \+ e# Append the current string of semicolons to the result. }* e# }{ e# Else: '}/ e# Split the modified input at right curly brackets. :, e# Replace each run of 0 to 3 semicolons by its length. 4b e# Convert from base 4 to integer. }? e# ``` [Answer] # Python 2, 167 bytes - 10% = 150.3 ``` d=lambda x:("{"+d(x//4)+"}"if x>3 else"")+";"*(x%4) c=lambda n:"{}"*(int(n)<4)+d(int(n))if n.isdigit()else reduce(lambda x,y:x*4+y,[x.count(";")for x in n.split("}")]) ``` In this implementation, `c` is the function that satisfies the requirements. It returns a string if given an nonnegative integer as input, or an integer if given a curly number as input. [Answer] # Python 266 bytes - 10% = ~~1268.1~~ ~~326.7~~ 239.4 bytes Boy am I not a code golfer yet =/, but that 10% helped *me* out a *lot* when my score was still over 1000! I have a fully fleshed out (and verbose) version of this code [here.](http://code.runnable.com/VfcrxGGPpBxlHJzA/curly-number-parser-for-python-and-puzzle "Curly Number Demo (verbose)") It will recognize the validity of curly numbers, and provide a looped interface to enter numbers for testing. (Comments just for clarification) [See this code in action](http://code.runnable.com/Vfg5e8EQ1X5ySF95/curly-number-parser-code-golf-for-python-and-puzzle "Curly Number Demo (golfed)") ``` def c(t): # curly to int function v=0 # int value of input for a in t: # for each character of input if a==';':v+=1 # if you find a ';', add one to total if a=='}':v*=4 # if you find a '}', multiply total by 4 print v # print value def i(t): # int to curly function v=int(t);f,b="{}"if v<4 else"","" # get integer value. initialize front (f) and back (b) strings while 1: # loop until stopped r,v=v%4,int(v/4) # get remainder of v/4 and int value of v/4 if r>0:b=';'*r+b # if remainder exists, prepend that many ';' to back string if v>0:f=f+'{';b='}'+b # if remaining value > 4, append '{' to front and prepend '}' to back if v<4:b=';'*v+b;break # if remaining value < 4, prepend that many ';' to back string and break print f+b # print result t=raw_input() # get raw input try:int(t);i(t) # use try block to determine which function to call except:c(t) # ``` Thanks to Erik Konstantopoulos for a major byte reduction! You could say... he really took a... byte... out of my code... \*self five\* [Answer] # CJam, ~~87 bytes~~ 80.1 score (89 bytes - 10% bonus) Update version that qualifies for the bonus while growing by 2 bytes: ``` l_'{#){VX@{";{}"#)" _@+\ 4* 4/"S/=~}/;}{i_4<{"{}"\';*}{{4md\_{F'{\+'}+}{;L}?\';*+}:F~}?}? ``` [Try it online](http://cjam.aditsu.net/#code=l_'%7B%23)%7BVX%40%7B%22%3B%7B%7D%22%23)%22%20_%40%2B%5C%204*%204%2F%22S%2F%3D~%7D%2F%3B%7D%7Bi_4%3C%7B%22%7B%7D%22%5C'%3B*%7D%7B%7B4md%5C_%7BF'%7B%5C%2B'%7D%2B%7D%7B%3BL%7D%3F%5C'%3B*%2B%7D%3AF~%7D%3F%7D%3F&input=%7B%7B%7B%7B%3B%7D%7D%7D%3B%7D) First time I used recursion in CJam! The whole thing may look kind of lengthy, but the two completely separate conversions add up. I used a completely separate case for converting numbers smaller than 4 to Curly. It's probably possible to avoid that, but folding the special case handling into the recursive function wouldn't be entirely trivial. And adding the extra `{}` as a post-processing step didn't really look any better, even though I should try again if it might be slightly shorter. [Answer] # C#, 173 - 10% = 155.7 ~~171.0, 177.3~~ This does no validation and only looks for `;` and `}` characters. It assumes all `{` characters come before any `;` characters. The hardest thing I found was to not insert a `{}` in the middle of a Curly number. Line breaks and indents for clarity: ``` string C(string a,int b=0){ int n; if(int.TryParse(a,out n)) a=(n>=b?"{"+C(""+n/4,4)+"}":"")+";;;".Remove(n%4); else foreach(int c in a) a=""+(c==59?++n:c==125?n*=4:n); return a; } ``` [Answer] # Java 326 bytes - 10% = 294 bytes It is complete program written in java, ``` public class a{static String c(long a,int v){if(a==0)return v==0?"{}":"";String x="";for(int i=0;i<a%4;i++)x+=";";return "{"+c(a/4,v+1)+"}"+x;}public static void main(String[]c){try{System.out.println(c(Long.parseLong(c[0]),0));}catch(Exception e){System.out.println(c[0].chars().reduce(0,(a,b)->b==';'?a+1:b=='}'?a*4:a));}}} ``` I'm sure it can be much shorter but i cant have much time now to optimize it [Answer] # GNU sed, 330 326 - 10% = 293.4 (I added one for the use of `-r` before claiming the bonus 10%; I hope that's correct) ``` /;/{ s/[^};]//g :c s/(;*)\}/\1\1\1\1/ tc :d /;/{ s/;;;;;/v/g s/vv/x/g /[;v]/!s/\b/0/2 s/;;/b/g s/bb/4/ s/b;/3/ s/v;/6/ s/vb/7/ s/v3/8/ s/v4/9/ y/;bvx/125;/ td } n } :u s/\b9/;8/ s/\b8/;7/ s/\b7/;6/ s/\b6/;5/ s/\b5/;4/ s/\b4/;3/ s/\b3/;2/ s/\b2/;1/ s/\b1/;0/ s/\b0// /[^;]/s/;/&&&&&&&&&&/g tu :v s/;;;;/v/g s/v+/{&}/ y/v/;/ tv ``` The full version shows that most of the above is conversion between decimal and unary: ``` #!/bin/sed -rf /;/{ # Delete non-Curly characters s/[^};]//g # Curly to unary :c s/(;*)\}/\1\1\1\1/ tc # unary to decimal :d /;/{ s/;;;;;/v/g s/vv/x/g /[;v]/!s/\b/0/2 s/;;/b/g s/bb/4/ s/b;/3/ s/v;/6/ s/vb/7/ s/v3/8/ s/v4/9/ y/;bvx/125;/ td } # done n } # Decimal to unary :u s/\b9/;8/ s/\b8/;7/ s/\b7/;6/ s/\b6/;5/ s/\b5/;4/ s/\b4/;3/ s/\b3/;2/ s/\b2/;1/ s/\b1/;0/ s/\b0// /[^;]/s/;/&&&&&&&&&&/g tu # Unary to Curly :v s/;;;;/v/g s/v+/{&}/ y/v/;/ tv ``` [Answer] # Perl, 183 177 This might not be the shortest Perl answer, but I think it's interesting enough to post (input in `$_`, output as return value): `sub f{if(/}/){s/[{}]/00/g;oct'0b'.s/00(;+)/sprintf'%02b',length$1/ger}else{$_=sprintf'%064b',$_;s/../oct"0b$&"/ge;s/^0+(?!$)//;$_='{'x length.$_;s/\d/'}'.';'x$&/ge;s/\Q{{}/{/r}}` We observe that Curly is simply quaternary (base-4) notation. We're slightly hampered by Perl's lack of native support for quaternary, but luckily, each quaternit is two bits in binary, and we can read and write binary. So we have the following: 1. Curly to decimal: convert each Curly digit to 2 binary digits, concatenate and convert to decimal 2. Decimal to Curly: print the number in binary (forcing an even number of digits), then convert each bit-pair to Curly. ### Expanded version ``` sub f { if (/}/) { s/[{}]/00/g; # digits are now 00 00; 00;; 00;;; # and opening braces become harmless leading zeros s/00(;+)/sprintf'%02b',length $1/ge; # convert semicolons to binary, leaving zeros alone oct "0b$_" # now to decimal } else { $_=sprintf'%064b',$_; # decimal to binary s/../oct"0b$&"/ge; # bit-pair to quaternit s/^0+(?!$)//; #/remove leading zeros $_='{'x length.$_; # prefix enough opening braces s/\d/'}'.';'x$&/ge; #/digit to semicolons s/{{}/{/r # first empty brace, unless $_ <= {};;; } } ``` [Answer] # JavaScript (ES6), 95 (105-10%) ``` f=(n,r='{}')=>-1-n?(n>3?'{'+f(n>>2,'')+'}':r)+';'.repeat(n&3):n.replace(/[;}]/g,c=>c>';'?n*=4:++n,n=0)&&n ``` Test running the snippet below ``` f=(n,r='{}')=>-1-n?(n>3?'{'+f(n>>2,'')+'}':r)+';'.repeat(n&3) :n.replace(/[;}]/g,c=>c>';'?n*=4:++n,n=0)&&n // Test function out(x) { O.innerHTML=x+'\n'+O.innerHTML; } function go() { out(I.value + ' --> ' + f(I.value)) } ;[ ['{;;}', 8] , ['{{;};};', 21 ] , ['{};;;', 3 ] , ['{{{{;}}};}', 260 ] , ['{}', 0 ] , [ 4, '{;}' ] , [ 17, '{{;}};' ] , [ 1,'{};' ] , [ 0, '{}' ] , [ 96, '{{{;};;}}' ] , ['{};;;;;', 5 ] , ['{{;;;;};;}' , 72 ] , ['c{u;r;l}y;!', 9 ] , ['42{;} ;;;;', 8 ] ].forEach(t => { r=f(t[0]) k=t[1] out('Test ' +(r==k?'OK':'Fail')+'\nInput: '+t[0]+'\nResult: '+r+'\nCheck: '+k+'\n') }) ``` ``` Custom test <input id=I><button onclick='go()'>-></button> <pre id=O></pre> ``` [Answer] # Ruby, ~~126.9~~ 129.6 (144 - 10%) Uses recursion to convert decimal into curly form. Removing the check for ignoring characters outside of `/[;{}]/` increases the score by `0.4` at the moment. ``` f=->s{s=~/^\d+$/?(n=s.to_i "{#{n<1?'':f[(n/4).to_s].gsub('{}','')}}#{?;*(n%4)}"):eval(s.tr("^{;}","").gsub(/./){|c|c<?A?"+1":c>?|?")*4":"+(0"})} ``` [Answer] # Perl 5, 154 (~~185~~ 170 Bytes - 10% + 1 Penalty) ``` $e=$/;if($_=~/{/){s/[^{};]//g;s/;/+1/g;s/{/+4*(/g;s/}/+0)/g;$b=eval}else{$r=$_;$b=$r<4?"{}":"";while($r>0){if($r%4>0){$r--;$e=";$e"}else{$b.="{";$e="}$e";$r/=4}}}$_=$b.$e ``` Regex & eval resolve the curlies. The generation of the curlies is done differently. ### Test Test file contains also the bonus cases ``` $ cat curlytestcases.txt {} {}; {};; {};;; {;;} {{;};}; {{{{;}}};} 0 1 2 3 4 17 96 {};;;;; 42{;} ;;;; c{u;r;l}y;! {{;;;;};;} $ cat curlytestcases.txt |perl -p curlies.pl 0 1 2 3 8 21 260 {} {}; {};; {};;; {;} {{;}}; {{{;};;}} 5 8 9 72 ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~69~~ 64 bytes ``` +`{(;*)} $1$1$1$1 ^\d+|^(;*) $*;$.1 +`(;+)\1\1\1 {$1} ^;|^$ {}$& ``` [Try Test Suite](https://tio.run/##JYlBCoNAEATv/Y6JrC6IA0EJ/QA/IcsKevCSQ8htnLdvdgkFBV39Ob/Xey@PNWSUmC1w6B2if5C2I96pRchAGRUxB8Z@0wZM1JF4J4G5dKUY6TCjV2oiq61t93Y4ntAFigmv@Qc "Retina – Try It Online") --- # Explanation ``` +`{(;*)} $1$1$1$1 ``` Decompose the innermost braces to just `;`s. Loop until no more braces. ``` ^\d+|^(;*) $*;$.1 ``` Convert between decimal and unary `;` ``` +`(;+)\1\1\1 {$1} ``` Find the longest run of `;` that is a multiple of 4 and nest into braces, loop until no more runs of 4+ exist. ``` ^;|^$ {}$& ``` If the resulting curly number begins with `;` or is empty string, add `{}` in front. [Answer] # [Python 2](https://docs.python.org/2/), 157 bytes -10% = 141.3 ``` lambda n:'{}'*(int(n)<4)+g(int(n))if n.isdigit()else sum((v==';')*4**n.count('}',i)for i,v in enumerate(n)) g=lambda n:'{%s}'%g(n/4)+';'*(n%4)if n>3else';'*n ``` [Try it online!](https://tio.run/##dZDtasMgGIV/L1fhCkFNQ9d8sVHnbiTrj6zVTDCmmKRQgteemSYw7Zgg@ry@5xz1cuu/W5VOnH5Osmq@zhVQBzgaGCGheqTwe4639brHggO1E91Z1KJHmMmOgW5oELpSCgnEUR5FandqB9sNDYwF5q0GIr4CoQBTQ8N01bPZKKipkxZ2BoY1Ui82y/pESIX5PesjmzPmkpokLY/B3W9205WqGUr2e3wIniTYUlBy1PUaCYz/a7to@wx7HSBLcYwBR/OKAwhhsBxxtEk2@BdSFzIXchfePE3x6mPhYpJmeeHZjoYQjwkxHttBjB3koUpsozMfNYtuOTTrXPgx/Y@YrCq3ehoHook0N/Ls/UNqQ8BiYf9x@gE "Python 2 – Try It Online") A more golfed Python 2 answer that handles the bonus cases. Didn't want to necro dead posts with this as a comment, so here it is. It works from the inside in on curly numbers, adding 4^(the number of end curly brackets left in the string) to the sum for each semicolon found. If the string is a number, then it recursively creates the curly number in the same way as the grammar provided. ]
[Question] [ # Gozinta Chains (Inspired by [Project Euler #606](https://projecteuler.net/problem=606)) A gozinta chain for n is a sequence `{1,a,b,...,n}` where each element properly divides the next. For example, there are eight distinct gozinta chains for 12: ``` {1,12}, {1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}. ``` ## The Challenge Write a program or function that accepts a positive integer (`n > 1`) and outputs or returns all the distinct gozinta chains for the given number. 1. Order in the chains matters (ascending), order of the chains does not. 2. On the off-chance it exists, you cannot use a builtin that solves the challenge. 3. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Edit: Removing `1` as a potential input. [Answer] # [Python 3](https://docs.python.org/3/), 68 65 bytes **Edit:** -3 bytes thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) ``` f=lambda x:[y+[x]for k in range(1,x)if x%k<1for y in f(k)]or[[x]] ``` [Try it online!](https://tio.run/##FcoxDoAgDADAr3QxodEF3Yy@hDBgtErQQohDeT3KfJfKe0WeaqX1ds@2O5DZlN6IpZghgGfIjs9D6UHQE0gXFt2oNCIV0MZs/m5ryp5fRUqPiPUD) # Explanation Each **gozinta chain** consists of the number `x` at the end of the chain, with at least one divisor to the left of it. For each divisor `k` of `x` the chains `[1,...,k,x]` are distinct. We can therefore for each divisor `k` find all of its distinct **gozinta chains** and append `x` to the end of them, to get all distinct **gozinta chains** with `k` directly to the left of `x`. This is done recursively until `x = 1` where `[[1]]` is returned, as all **gozinta chains** start with 1, meaning the recursion have bottomed out. The code becomes so short due to Python list comprehension allowing double iteration. This means that the values found in `f(k)` can be added to the same list for all of the different divisors `k`. [Answer] ## [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ufo=ḣ⁰…ġ¦ΣṖḣ⁰ ``` A somewhat different approach to that of [H.PWiz](https://codegolf.stackexchange.com/a/139158/32014), though still by brute force. [Try it online!](https://tio.run/##yygtzv7/vzQt3/bhjsWPGjc8alh2ZOGhZecWP9w5DSLy//9/QyMA "Husk – Try It Online") ## Explanation The basic idea is to concatenate all subsequences of `[1,...,n]` and split the result into sublists where each element divides the next. Of these, we keep those that start with `1`, end with `n` and contain no duplicates. This is done with the "rangify" built-in `…`. Then it remains to discard duplicates. ``` ufo=ḣ⁰…ġ¦ΣṖḣ⁰ Input is n=12. ḣ⁰ Range from 1: [1,2,..,12] Ṗ Powerset: [[],[1],[2],[1,2],[3],..,[1,2,..,12]] Σ Concatenate: [1,2,1,2,3,..,1,2,..,12] ġ¦ Split into slices where each number divides next: [[1,2],[1,2],[3],..,[12]] fo Filter by … rangified =ḣ⁰ equals [1,...,n]. u Remove duplicates. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ÆḌ߀Ẏ;€ȯ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28MdPYfnP2pa83BXnzWQOrH@////hkYA "Jelly – Try It Online") Uses a similar technique to my [Japt answer](https://codegolf.stackexchange.com/a/139168/42545), and therefore runs very quickly on larger test cases. ### How it works ``` ÆḌ߀Ẏ;€ȯ Main link. Argument: n (integer) ÆḌ Yield the proper divisors of n. ȯ If there are no divisors, return n. Only happens when n is 1. ߀ Otherwise, run each divisor through this link again. Yields a list of lists of Gozinta chains. Ẏ Tighten; bring each chain into the main list. ;€ Append n to each chain. ``` [Answer] ## Mathematica, 77 bytes ``` FindPath[Graph@Cases[Divisors@#~Subsets~{2},{m_,n_}/;m∣n:>m->n],1,#,#,All]& ``` Forms a `Graph` where the vertices are the `Divisors` of the input `#`, and the edges represent proper divisibility, then finds `All` paths from the vertex `1` to the vertex `#`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒPµḍ2\×ISµÐṀ ``` A monadic link accepting an integer and returning a list of lists of integers. **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//xZJQwrXhuI0yXMOXSVPCtcOQ4bmA////MTI "Jelly – Try It Online")** ### How? We want all the sorted lists of unique integers between one and N such that the first is a one, the last is N, and all pairs divide. The code achieves this filter by checking the pair-wise division criteria is satisfied over the power-set of the range in question, but only picking those with maximal sums of incremental difference (the ones which both start with one and end with N will have a sum of incremental differences of N-1, others will have less). ``` ŒPµḍ2\×ISµÐṀ - Link: number N ŒP - power-set (implicit range of input) = [[1],[2],...,[N],[1,2],[1,3],...,[1,N],[1,2,3],...] ÐṀ - filter keep those for which the result of the link to the left is maximal: µ µ - (a monadic chain) 2\ - pairwise overlapping reduce with: ḍ - divides? (1 if so, 0 otherwise) I - increments e.g. for [1,2,4,12] -> [2-1,4-2,12-4] = [1,2,8] × - multiply (vectorises) (no effect if all divide, - otherwise at least one gets set to 0) S - sum e.g. for [1,2,4,12] -> 1+2+8 = 11 (=12-1) ``` [Answer] # [Japt](https://github.cm/ETHproductions/japt), 17 bytes ``` ⬣ßX m+S+UR÷ª'1 ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=4qyj31ggbStTK1VSw7eqJzE=&input=MjQ=) Weirdly, generating the output as a string was way easier than generating it as an array of arrays... ### Explanation ``` ⬠£ ßX m+S+URà · ª '1 Uâq mX{ßX m+S+UR} qR ||'1 Ungolfed Implicit: U = input number, R = newline, S = space Uâ Find all divisors of U, q leaving out U itself. mX{ } Map each divisor X to ßX The divisor chains of X (literally "run the program on X") m R with each chain mapped to +S+U the chain, plus a space, plus U. qR Join on newlines. || If the result is empty (only happens when there are no factors, i.e. U == 1) '1 return the string "1". Otherwise, return the generated string. Implicit: output result of last expression ``` [Answer] # Mathematica, 60 bytes ``` Cases[Subsets@Divisors@#,x:{1,___,#}/;Divisible@@Reverse@{x}]& ``` Uses the undocumented multi-arg form of `Divisible`, where `Divisible[n1,n2,...]` returns `True` if `n2∣n1`, `n3∣n2`, and so on, and `False` otherwise. We take all `Subsets` of the list of `Divisors` of the input `#`, then return the `Cases` of the form `{1,___,#}` such that `Divisible` gives `True` for the `Reverse`d sequence of divisors. [Answer] ## Haskell, 51 bytes ``` f 1=[[1]] f n=[g++[n]|k<-[1..n-1],n`mod`k<1,g<-f k] ``` Recursively find gozinta chains of proper divisors and append `n`. [Try it online!](https://tio.run/##Dcw7DoAgDADQ3VN0cOOT1BlO0jSBREECVKOO3h19B3h7vOvW2hgJ0BMh85RAPGWlSPitzhBaKwZZS@jHGqpDnZ1JUHn0WAQ8nFeRB2b4i2V8 "Haskell – Try It Online") [Answer] # Haskell (Lambdabot), ~~92~~ 85 bytes ``` x#y|x==y=[[x]]|1>0=(guard(mod x y<1)>>(y:).map(y*)<$>div x y#2)++x#(y+1) map(1:).(#2) ``` Needs Lambdabot Haskell since `guard` requires `Control.Monad` to be imported. Main function is an anonymous function, which I'm told is allowed and it shaves off a couple of bytes. *Thanks to Laikoni for saving seven bytes.* **Explanation:** Monads are very handy. ``` x # y ``` This is our recursive function that does all the actual work. `x` is the number we're accumulating over (the product of the divisors that remain in the value), and `y` is the next number we should try dividing into it. ``` | x == y = [[x]] ``` If `x` equals `y` then we're done recursing. Just use `x` as the end of the current gozinta chain and return it. ``` | 1 > 0 = ``` Haskell golf-ism for "True". That is, this is the default case. ``` (guard (mod x y < 1) >> ``` We're operating inside the list monad now. Within the list monad, we have the ability to make multiple choices at the same time. This is very helpful when finding "all possible" of something by exhaustion. The `guard` statement says "only consider the following choice if a condition is true". In this case, only consider the following choice if `y` divides `x`. ``` (y:) . map (y *) <$> div x y#2) ``` If `y` does divide `x`, we have the choice of adding `y` to the gozinta chain. In this case, recursively call `(#)`, starting over at `y = 2` with `x` equal to `x / y`, since we want to "factor out" that `y` we just added to the chain. Then, whatever the result from this recursive call, multiple its values by the `y` we just factored out and add `y` to the gozinta chain officially. ``` ++ ``` Consider the following choice as well. This simply adds the two lists together, but monadically we can think of it as saying "choose between doing this thing OR this other thing". ``` x # (y + 1) ``` The other option is to simply continue recursing and not use the value `y`. If `y` does not divide `x` then this is the only option. If `y` does divide `x` then this option will be taken as well as the other option, and the results will be combined. ``` map (1 :) . (# 2) ``` This is the main gozinta function. It begins the recursion by calling `(#)` with its argument. A `1` is prepended to every gozinta chain, because the `(#)` function never puts ones into the chains. [Answer] # Haskell, 107 100 95 bytes ``` f n=until(all(<2).map head)(>>=h)[[n]] h l@(x:_)|x<2=[l]|1<2=map(:l)$filter((<1).mod x)[1..x-1] ``` Maybe there is a better termination condition (tried something like ``` f n=i[[n]] i x|g x==x=x|1<2=i$g x g=(>>=h) ``` but it's longer). The check for `1` seems prudent as scrubbing repeat `1`s or duplicates (`nub` not in `Prelude`) is more bytes. [Try it online.](https://tio.run/##DcwxCsQgEEDR3lNMkWKmWMGUomHvIbIIiSg7MSGrYJG7u6l@9X4Kv@/GPEa0rdTMGJjRzCT3cELawkq4LDaRbLKJZlE7TyIBv7HrD93dzNaxv9XTR6BmmmLmul2IRj2XY4VOTknZX8qPPeQCFtZDAJxXLhUmiKDm8Qc) [Answer] ## JavaScript (Firefox 30-57), 73 bytes ``` f=n=>n>1?[for(i of Array(n).keys())if(n%i<1)for(j of f(i))[...j,n]]:[[1]] ``` Conveniently `n%0<1` is false. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ḊṖŒP1ppWF€ḍ2\Ạ$Ðf ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//4biK4bmWxZJQMXBwV0bigqzhuI0yXOG6oCTDkGb///8xMg "Jelly – Try It Online") [Answer] # Mathematica, 104 bytes ``` (S=Select)[Rest@S[Subsets@Divisors[t=#],FreeQ[#∣#2&@@@Partition[#,2,1],1>2]&],First@#==1&&Last@#==t&]& ``` [Answer] # Mathematica, 72 bytes ``` Cases[Subsets@Divisors@#,{1,___,#}?(And@@BlockMap[#∣#2&@@#&,#,2,1]&)]& ``` ### Explanation ``` Divisors@# ``` Find all divisors of the input. ``` Subsets@ ... ``` Generate all subsets of that list. ``` Cases[ ... ] ``` Pick all cases that match the pattern... ``` {1,___,#} ``` Beginning with 1 and ending with `<input>`... ``` ?( ... ) ``` and satisfies the condition... ``` And@@BlockMap[#∣#2&@@#&,#,2,1]& ``` The left element divides the right element for all 2-partitions of the list, offset 1. [Answer] # TI-BASIC, 76 bytes ``` Input N 1→L1(1 Repeat Ans=2 While Ans<N 2Ans→L1(1+dim(L1 End If Ans=N:Disp L1 dim(L1)-1→dim(L1 L1(Ans)+L1(Ans-(Ans>1→L1(Ans End ``` # Explanation ``` Input N Prompt user for N. 1→L1(1 Initialize L1 to {1}, and also set Ans to 1. Repeat Ans=2 Loop until Ans is 2. At this point in the loop, Ans holds the last element of L1. While Ans<N While the last element is less than N, 2Ans→L1(1+dim(L1 extend the list with twice that value. End If Ans=N:Disp L1 If the last element is N, display the list. dim(L1)-1→dim(L1 Remove the last element, and place the new list size in Ans. L1(Ans)+L1(Ans-(Ans>1→L1(Ans Add the second-to-last element to the last element, thereby advancing to the next multiple of the second-to-last element. Avoid erroring when only one element remains by adding the last element to itself. End When the 1 is added to itself, stop looping. ``` I could save another 5 bytes if it's allowed to exit with an error instead of gracefully, by removing the Ans>1 check and the loop condition. But I'm not confident that's allowed. [Answer] ## Mathematica ~~86~~ 77 Bytes ``` Select[Subsets@Divisors@#~Cases~{1,___,#},And@@BlockMap[#∣#2&@@#&,#,2,1]&]& ``` Brute force by the definition. Wishing there was a shorter way to do pairwise sequential element comparison of a list. Thanks to @Jenny\_mathy and @JungHwanMin for suggestions saving 9 bytes [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ 16 bytes -1 byte, thanks to Zgarb ``` foEẊ¦m`Je1⁰Ṗthḣ⁰ ``` [Try it online!](https://tio.run/##yygtzv7/Py3f9eGurkPLchO8Ug0fNW54uHNaScbDHYuBzP///xsaAQA "Husk – Try It Online") [Answer] # PHP ~~147~~ 141 Edited to remove a redundant test ``` function g($i){$r=[[1]];for($j=2;$j<=$i;$j++)foreach($r as$c)if($j%end($c)<1&&$c[]=$j)$r[]=$c;foreach($r as$c)end($c)<$i?0:$R[]=$c;return$R;} ``` ## Explained: ``` function g($i) { ``` 15 chars of boilerplate :( ``` $r = [[1]]; ``` Init the result set to `[[1]]` as every chain starts with 1. This also leads to support for 1 as an input. ``` for ($j = 2; $j <= $i; $j++) { foreach ($r as $c) { if ($j % end($c) < 1) { $c[] = $j; $r[] = $c; } } } ``` For every number from 2 to `$i`, we're going to extend each chain in our set by the current number *if* it *gozinta*, then, add the extended chain to our result set. ``` foreach ($r as $c) { end($c) < $i ? 0 : $R[] = $c; } ``` Filter out our intermediate chains that didn't make it to `$i` ``` return $R; } ``` 10 chars of boilerplate :( [Answer] # Mathematica ``` f[1] = {{1}}; f[n_] := f[n] = Append[n] /@ Apply[Join, Map[f, Most@Divisors@n]] ``` Answer is cached for additional calls. ]
[Question] [ ### Background Celebrating [the release of Dyalog APL 16.0](https://www.dyalog.com/dyalog/dyalog-versions/160.htm), where the solution to this problem is `{⊢⌺(≢⍵)⊢⍵}`[Explanation](https://codegolf.stackexchange.com/a/129585/43319) ### Task Given a printable ASCII string **of odd length** *n*, make an *n* × *n* square with the string centered horizontally, duplicated to be centered vertically, and with acrostics of the same string in each row and column. Note that all but the centered strings will be cut off to keep the square's size *n* × *n*. Explanation of your code will be much appreciated. ### Rules 1. You may have trailing whitespace and newlines (this includes the lower-right triangle) 2. You may return a list of strings ### Example using the string `ABXCD`: * *n* is 5. First we draw the two centered strings, one horizontal and one vertical: ``` ┌─────┐ │ A │ │ B │ │ABXCD│ │ C │ │ D │ └─────┘ ``` (5 × 5 bounding box added for clarity) * Then we place all the possible acrostics, horizontally and vertically: ``` A AB ┌─────┐ │ ABX│CD │ ABXC│D │ABXCD│ A│BXCD │ AB│XCD │ └─────┘ CD D ``` * Finally, we return only what is inside the bounding box: ``` ABX ABXC ABXCD BXCD XCD ``` ### Test cases `World`: ``` Wor Worl World orld rld ``` `mississippi`: ``` missis mississ mississi mississip mississipp mississippi ississippi ssissippi sissippi issippi ssippi ``` `Pneumonoultramicroscopicsilicovolcanoconiosis`: ``` Pneumonoultramicroscopi Pneumonoultramicroscopic Pneumonoultramicroscopics Pneumonoultramicroscopicsi Pneumonoultramicroscopicsil Pneumonoultramicroscopicsili Pneumonoultramicroscopicsilic Pneumonoultramicroscopicsilico Pneumonoultramicroscopicsilicov Pneumonoultramicroscopicsilicovo Pneumonoultramicroscopicsilicovol Pneumonoultramicroscopicsilicovolc Pneumonoultramicroscopicsilicovolca Pneumonoultramicroscopicsilicovolcan Pneumonoultramicroscopicsilicovolcano Pneumonoultramicroscopicsilicovolcanoc Pneumonoultramicroscopicsilicovolcanoco Pneumonoultramicroscopicsilicovolcanocon Pneumonoultramicroscopicsilicovolcanoconi Pneumonoultramicroscopicsilicovolcanoconio Pneumonoultramicroscopicsilicovolcanoconios Pneumonoultramicroscopicsilicovolcanoconiosi Pneumonoultramicroscopicsilicovolcanoconiosis neumonoultramicroscopicsilicovolcanoconiosis eumonoultramicroscopicsilicovolcanoconiosis umonoultramicroscopicsilicovolcanoconiosis monoultramicroscopicsilicovolcanoconiosis onoultramicroscopicsilicovolcanoconiosis noultramicroscopicsilicovolcanoconiosis oultramicroscopicsilicovolcanoconiosis ultramicroscopicsilicovolcanoconiosis ltramicroscopicsilicovolcanoconiosis tramicroscopicsilicovolcanoconiosis ramicroscopicsilicovolcanoconiosis amicroscopicsilicovolcanoconiosis microscopicsilicovolcanoconiosis icroscopicsilicovolcanoconiosis croscopicsilicovolcanoconiosis roscopicsilicovolcanoconiosis oscopicsilicovolcanoconiosis scopicsilicovolcanoconiosis copicsilicovolcanoconiosis opicsilicovolcanoconiosis picsilicovolcanoconiosis icsilicovolcanoconiosis ``` ### Acknowledgements Thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima), [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun), [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for everything but the very idea of this challenge. [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` n=input();l=len(n) for i in range(l):print(l/2*' '+n)[i:l+i] ``` [Try it online!](https://tio.run/##FcKxCoAgFAXQva@QFjWHwNHwS6KhwerB6/pQG/p6o8ORt10ZvndEgjzN2IUjJxjY4chFkSKosuNMhm2QQmiGZz9ppR3sSoEdbb2PN9X6F6HxAw "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` nXyPGZ+c ``` [**Try it online!**](https://tio.run/##y00syfn/Py@iMsA9Sjv5/3/13MziYhAqKMhUBwA "MATL – Try It Online") ### Explanation ``` n % Implicit input. Number of elements Xy % Identity matrix of that size P % Flip vertically G % Push input again Z+ % 2D convolution, maintaining size c % Convert to char (char 0 is displayed as space). Implicitly display ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~70~~ 59 bytes ``` . $.'$* $_$.`$* ¶ (?=((....))+)(?<-1>.)+(.*?)(?<-2>.)+¶ $3¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fj0tFT11FS0ElXkUvAUgf2salYW@roaEHBJqa2poa9ja6hnZ6mtoaelr2YJ4RiAdUpmJ8aNv//@H5RTkpAA "Retina – Try It Online") Edit: Saved 11 bytes with some help from @MartinEnder. Explanation: The first stage repeats the input once for each character, padding it appropriately on each line to get the shear. The last stage then removes 25% from each side to produce the desired result. [Answer] # Java 8, ~~120~~ 103 bytes ``` s->{int l=s.length(),i=l/2;for(;i-->0;s=" "+s+" ");for(;++i<l;System.out.println(s.substring(i,l+i)));} ``` -17 bytes thanks to *@OlivierGrégoire*. **Explanation:** [Try it here.](https://tio.run/##jZBNa8MwDIbv@xUiJ5s02djVS2Ef15VBDxuMHVzH7dQ5lrGcwij57Zmb5LhDQTJYlvy8r476pCsK1h/bn9E4zQyvGv35BgB9snGvjYXN5QpwImzBiG2K6A/AUuXqkDMHJ53QwAY8NDBytT7naXAN1876Q/oWcoWNu71Xe4pCYVWt7xQ3BRQll/mUc70s8cGp7S8n29XUpzpkUnJecM39jieuwJUrUUqphlHN8NDvXIYvGiaVXfawCP38Ai1nA742onh8@nh@KSbxAP@wlpep952ia6/s7ZD5EiHglRNv3vYdeepdirpDE4kNBTSM2Q6dyBntyZBHyh8Xy7qH8Q8) ``` s->{ // Method with String parameter and no return-type int l=s.length(), // Length of the input-String i=l/2; // Temp index-integer (starting at halve the length floored) for(;i-->0; // Loop (1) from `l/2` to 0 (exclusive) s=" "+s+" " // Add spaces before and after the input-String ); // End of loop (1) // (If the input was "World", it is now " World ") for(;++i<l; // Loop (2) from 0 to `l` (exclusive) System.out.println( // Print: s.substring(i, // Substring of the modified input from `i` l+i) // to `l+i` (exclusive) ) // End of print ); // End of loop (2) } // End of method ``` [Answer] ## Haskell, ~~64~~ 62 bytes ``` f s|l<-length s=take l$take l<$>scanr(:)""(([2,4..l]>>" ")++s) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02huCbHRjcnNS@9JEOh2LYkMTtVIUcFQtmo2BUnJ@YVaVhpKilpaEQb6Zjo6eXE2tkpKShpamsXa/7PTczMU7BVSMnnUlBQyE0s8I1XKCgtCS4p8slTUFFIU1AKzy/KSVHCJZubWVwMQgUFmUr/AQ "Haskell – Try It Online") How it works: ``` l<-length s -- let l be the length of the input string ([2,4..l]>>" ") -- take l/2 spaces and ++s -- append s scanr(:)"" -- make a list of the inits of the above string, e.g. -- " world" -> [" world"," world","world","orld"...] take l <$> -- take the first l chars of each string take l -- and the first l strings ``` [Answer] ## SWI Prolog, 234 bytes ``` h(_,0,_,_,[]). h(T,N,S,L,[H|U]):-sub_string(T,S,L,_,H),M is N-1,A is S+1,h(T,M,A,L,U). s(T,R):-string_length(T,L),findall('_',between(1,L,_),A),string_chars(B,A), string_concat(B,T,C),string_concat(C,B,D),S is L-((L-1)/2),h(D,L,S,L,R). ``` Maybe try online here: <http://swish.swi-prolog.org/p/hEKigfEl.pl> NB. 1. The last line is one long line, I added a linebreak and spaces here just to avoid horizontal scrollbar in this answer. 2. The question involves spaces for padding, but Swish online doesn't show them cleanly because of HTML rendering interactions, you have to view source in browser dev tools to check they are present (they are). I've changed the padding to be `_` here, as it demonstrates it working and doesn't affect the byte count. Examples running in Swish: [![Test cases](https://i.stack.imgur.com/uL1k1.png)](https://i.stack.imgur.com/uL1k1.png) Approach, basically the first thing I could make work at all, and doubtless a skilled Prolog user could shorten it a lot: * Given a string of length L, the output will have L lines, and each line will be L characters long, so 'L' shows up a lot. Countdown from L to 0 for the number of lines, L for the substring length for each line. * Create a padding string of L spaces (underscores) long, add it to both ends of the input string, because that's a simple length which is definitely going to be enough padding. * Calculate a starting offset into this triple-length string and recurse, generating a substring each time, into a list of results. Explained and commented code (might not run), read from `superacrostic()` down, then `helper()` main body, then `helper()` base case: ``` % helper function recursive base case, % matches when counter is 0, other input has any values, and empty list 'output'. helper(_,0,_,_,[]). % helper function recursively generates substrings % matching a padded input Text, a line Counter % a substring starting Offset, a line Length, % and an output list with a Head and a Tail helper(Text, Counter, Offset, LineLength, [Head|Tail]):- sub_string(Text, Offset, LineLength, _, Head), % The list Head matches % a substring of Text starting % from Offset, of LineLength chars % and NextCounter is Counter-1, % decrement the Counter NextOffset is Offset+1, % increment the offset helper(Text, NextCounter, NextOffset, LineLength, Tail). % Recurse for list Tail % Result is a superacrostic for an input string Text, if superacrostic(Text, Result):- string_length(Text, Length), % Length is length of input, % Text = 'ABXCD', Length = 5 % and findall('_',between(1,Length,_),PaddingList), % PaddingList is a list of padding % chars Length items long, % ['_', '_', '_', '_', '_'] % and string_chars(PaddingString, PaddingChars), % PaddingString is the string from % joining up that list of chars % '_____' % and string_concat(PaddingString, Text, Temp), % Temp is Text input with a % padding prefix % Temp = '_____ABXCD' % and string_concat(Temp, PaddingString, PaddedText), % PaddedText is Temp with % a padded suffix % Temp = '_____ABXCD_____' % and S is Length - ((Length - 1) / 2), % Starting offset S for the substring % is just past the padding, % then half the input length back % '_____ABXCD_____' % | % to start the first line, % and helper(PaddedText, Length, S, Length, Result). % Result is the list generated from % the helper function, % to recurse Length times for that many output rows, S starting offset, % Length linelength, and Result 'output'. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` g;úIvDIg£,À ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/3frwLs8yF8/0Q4t1Djf8/5@bWVwMQgUFmQA "05AB1E – Try It Online") **Explanation** ``` g;ú # prepend len(input)/2 spaces to input Iv # for each char of input do D # duplicate current string Ig£ # take the first len(input) chars , # print À # rotate the string to the left ``` [Answer] ## JavaScript (ES6), 75 bytes ``` f=(s,k=1,l=s.length)=>k>l?'':(' '.repeat(l)+s).substr(l/2+k,l)+` `+f(s,k+1) console.log(f("World")) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 chars = 22 bytes ``` {⊢⌺(≢⍵)⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/hR24TqR12LHvXs0njUuehR71ZNEK93ay1QTkHd0SnC2UUdAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous function where the argument is represented by *⍵*  `⊢` provide the covered area when  `⌺(`…`)` sliding a stencil of size   `≢` length of   `⍵` the argument  `⊢` on  `⍵` the argument The way this works is by letting each character form the middle of a string with the same length as the input, padding left or right as needed. Take e.g. `ABXCD`: The string has five characters, so the stencil will have an "opening" that is five characters wide. `┌──↓──┐` stencil opening with middle marker `│ ABX│CD` let `A` be in the middle `│ ABXC│D` then `B` `│ABXCD|` etc. `A|BXCD |` `AB|XCD  |` `└──↑──┘` final stencil position [Answer] # [PHP](https://php.net/), 98 bytes ``` for(;~($a=$argn)[$i++];)$i&1?$t.=substr($a,$i/2)." ":$t=($s.=" ").substr($a,0,-$i/2)." $t";echo$t; ``` [Try it online!](https://tio.run/##RcxLCsIwEADQfU8hwyANrfGzNIZewb24iKHagTQTMqlLrx5FEPePl6ZUT0OaUoMuP6KFcxyXmSMvoWQ3k88snhN5oUCenxy8i@w5EgsJmHrn3JpXi85@A3VB6rqrUUjr/YBFW1luUvIH9Ejbg9LQwBGLbVG0hRUo/Qe7fvMzWMCMfmIsptY3 "PHP – Try It Online") [Answer] # JavaScript (ES8), ~~66~~ ~~63~~ 62 bytes Returns an array. ``` s=>[...s].map((_,x)=>s.padStart(l*1.5).substr(x,l),l=s.length) ``` --- ## Try it ``` o.innerText=(f= s=>[...s].map((_,x)=>s.padStart(l*1.5).substr(x,l),l=s.length) )(i.value="Pneumonoultramicroscopicsilicovolcanoconiosis").join`\n`;oninput=_=>o.innerText=f(i.value).join`\n` ``` ``` <input id=i><pre id=o> ``` --- ## Explanation ``` s=> ``` Anonymous function taking the string as an argument via parameter `s`. ``` [...s] ``` Split the string to an array of individual characters. ``` l=s.length ``` Get the length of the string and assign it to variable `l`. ``` .map((_,x)=> ) ``` Map over the array, passing each element through a function, where `x` is the index of the current element. ``` s.padStart(l*1.5) ``` For each element, return the original string with spaces prepended until it's length is 1.5 times that of it's original length. ``` .substr(x,l) ``` Get the substring of length `l` beginning from the current element's index. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~14~~, 11 bytes ``` òlÙxHÄ$x>>ê ``` [Try it online!](https://tio.run/##K/v///CmnMMzKzwOt6hU2NkdXvX/v0dqTk4@AA "V – Try It Online") 3 bytes saved thanks to @nmjmcman! Hexdump: ``` 00000000: f26c d978 48c4 2478 3e3e ea .l.xH.$x>>. ``` Original approach (18 bytes): ``` ø.. Duu@"ñLÙxHÄ$x> ``` Explanation: ``` ò " Recursively: l " Move one char to the right (this will break the loop if we move too far Ù " Duplicate this line down x " Delete the first character on this line H " Move to the first line Ä " Duplicate this line up $ " Move to the end of this line x " And delete a character >> " Put one space at the beginning of this line ê " And move to this column on the last line " (implicit) ò, end the loop. ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 68 bytes ``` 0..($L=($a="$args").Length-1)|%{-join(' '*($L/2)+$a)[($_..($_+$L))]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f/fQE9PQ8XHVkMl0VZJJbEovVhJU88nNS@9JEPXULNGtVo3Kz8zT0NdQV0LqEzfSFNbJVEzWkMlHqQtXlvFR1Mztvb///9KuZnFxSBUUJCpBAA "PowerShell Core – Try It Online") ### Ungolfed explanation ``` # Input string ABXCD # -> indexes 0,1,2,3,4 string indexing and num of output lines. # -> Pad with half-len of spaces __ABXCD. # -> sliding window array of chars: # __ABXCD # | | 0..4 # | | 1..5 # | | 2..6 # | | 3..7 (selecting indexes past the end returns $nulls, no error) # | | 4..8 # joining those chars into a line $Text = "$args" # script args array to string. $L = $Text.Length - 1 # useful number $Offsets = 0..$L # range array 0,1,2,3,.. to last offset $Offsets | ForEach-Object { # Offsets doubles as number of output lines $LinePadding = ' ' * ($L / 2) # lead padding string __ $PaddedText = $LinePadding + $Text # -> __ABXCD $Chars = $_..($_+$L) # windows 0..4, then 1..5, then 2..6, etc. $Line = $PaddedText[$Chars] #_,_,A,B,X then _,A,B,X,C then A,B,X,C,D etc. -join $Line # __ABX then _ABXC then ABXCD etc. } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~19~~ ~~17~~ 14 bytes *Saved 5 bytes thanks to @ETHproductions and @Shaggy* ``` ¬£iSp½*Ul¹tYUl ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rKNpU3C9KlVsuXRZVWw=&input=Im1pc3Npc3NpcHBpIgotUg==) `-R` flag added to join with newlines (visibility purposes) ## Explanation ``` ¬£iSp½*Ul¹tYUl U = Implicit input ¬ Split the input into an array of chars £ Map; At each char: i Insert: S Space " " p repeated( ½*Ul .5 * U.length times ¹ ) t Substring( Y Index, Ul U.length) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` A⁺¹÷Lθ²δFδ⟦✂θι⁺ιδ⟧F∕θ²C¹±¹ ``` [Try it online!](https://tio.run/##Nc09C8IwEMbx3U9x4x2kQ107iS6CSMHBQRxCEtODkJgXC3760xZdnunP7zGTLibpILKrlX3EMbwq9gqOsR14Zuvw5KJvE2ZSsKXvWBo2j1QALcFYODa8XQIbh1kBK1gBXjK6/8uflFcB9un5Xi7OzuvmsCcaRK6pBCvdLF0NHw "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` LH⁶ẋ;ṫJḣ€LY ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//TEjigbbhuos74bmrSuG4o@KCrExZ////QUJYQ0Q "Jelly – Try It Online") ## How it works ``` LH⁶ẋ;ṫJḣ€LY "ABXCD" L 5 H 2.5 ⁶ẋ " " ; " ABXCD" ṫJ [" ABXCD" " ABXCD" "ABXCD" "BXCD" "XCD] ḣ€L [" ABX" " ABXC" "ABXCD" "BXCD" "XCD] Y " ABX ABXC ABXCD BXCD XCD" ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 32 bytes ``` _L;|A=space$(a'\`2)+A[a|?_sA,b,a ``` Man, it's time for me to add `space$` to QBIC... ## Explanation ``` ; Read a cmd line parameter as A$ _L | And take its length as 'a' A=space$ Set A$ to a number of spaces (a'\`2) equal to its own length halved +A prepended to itself [a| FOR b= 1 to the length of A$ ?_sA,b,a Print a substring of our space-padded A$, starting at the b'th character, running for a chars ``` ## Sample run ``` Command line: acknowledgement acknowle acknowled acknowledg acknowledge acknowledgem acknowledgeme acknowledgemen acknowledgement cknowledgement knowledgement nowledgement owledgement wledgement ledgement edgement ``` [Answer] # Mathematica, 88 bytes ``` T=Table;Column@Reverse@T[T[" ",i]<>StringDrop[s=#,-i],{i,d=-⌊StringLength@s/2⌋,-d}]& ``` [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ 70 bytes This is (still) way too long, but thanks @bartavelle for reminding me that outputting a list of strings is acceptable too! ``` f s|m<-div(length s)2=take(2*m+1).(`drop`((*>)s" "++s))<$>[m+1..3*m+1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02huCbXRjcls0wjJzUvvSRDoVjTyLYkMTtVw0grV9tQU08jIaUovyBBQ0PLTrNYSUFJW7tYU9NGxS4aKKunZwxSFPu/uKRIwVZBKTy/KCdFiSs3MTMPyC0oLQkuKfLJU1BRKM7ILwdSQNtKiv4DAA "Haskell – Try It Online") [Answer] # Excel VBA, 68 Bytes ### Golfed Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window ``` l=[Len(A1)]:For i=Int(-l/2)+2To l/2+1:?Mid(Space(l-i)&[A1],l,l):Next ``` ### Ungolfed ``` Sub C(ByVal s As String) Let l = Len(s) For i = Int(-l / 2) + 2 To l / 2 + 1 Step 1 Debug.Print Mid(Space(l - i) & s, l, l) Next i End Sub ``` [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` a=input() c=len(a) b=a.center(c*2) for i in range(c):print(b[i:i+c]) ``` [Try it online!](https://tio.run/##BcExDoAgDADAnVcwtpo46EbCS4wDNFWakEJIHXw93vXPStNjzhRF@2uAjmJlhYQux7QRq/EAWnZ0dxtevKgfSR8GwtCHqEE@JchKF85ZuNb2Aw "Python 3 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~133~~ 119 bytes ``` $a="$args";$L=$a.Length;$m=($L+1)/2;$s=" "*($m-1)+$a+" "*($m-1);for($h=0;$h-lt$L;$h++){$r="";0..$L|%{$r+=$s[$_+$h]};$r} ``` [Try it online!](https://tio.run/##RcfBCsIgHAfgVwn5BVuytXUV38BD94gQsSmo/6FbHWrPbrt1@vhmettcnA2hVmjJoPNUmICS0L2yaVqcQJQNFB/b80WgSHZgpwaxG1sOzf8TT8oNnBwEXBcWqF3O2w@yZEwMfQ/1Pe7jEuWGB4e7bwJ5q7Wya7JrpERrWLKO3mQqhmZvig/e0IuC0YkMJU/FF/YD "PowerShell – Try It Online") **Ungolfed** ``` $a="$args" $L=$a.Length # the length of the input $m=($L + 1) / 2 # the midpoint of the input $s=" " * ($m-1) + $a + " " * ($m-1) # create a string using the input and padded on both sides with spaces for($h=0;$h -lt $L;$h++) { # the height, matching the length of the input $r="" # init/reset the output string 0..$L | % { # number range to represent each character in the string $r+=$s[$_+$h] # append the output string with the next character } $r # write the output } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~76 74~~ 73 bytes *-1 thanks to @FelipeNardiBatista* Of course, not as short as the other Python answer, but it's worth trying a completely different method: ``` n=input();x=len(n) for i in range(x):print((2*x-~i)*' '+n)[x+x/2:2*x+x/2] ``` [Try it online!](https://tio.run/##HcVBCoMwEAXQfU8R3GTGEIpZpngScaFtqgPyDSHCePoU@jYv33U/EVrDKMhXJX7peCQQ@PE9ixEjMGXBlkg55iKoROpIvfiBubfGOvCkTp8hhv7/3Fq3rO9P6n4 "Python 2 – Try It Online") (with the 74 byte version) This first generates the full String, and then slices it to fit the square. --- # Explanation ``` n=input(); - takes input and assigns it to a variable n x=len(n) - assigns the length of the input to a variable x for i in range(x): - iterates on the range 0...x, with a variable i print - outputs the result ((2*x-i-1)*' '+n) - creates the "diamond" string [x+x/2:2*x+x/2] - crops the string to fit the box ``` [Answer] # [J](http://jsoftware.com/), 19 bytes ``` |.!.' '"{~2%~#\-#\. ``` [Try it online!](https://tio.run/##y/r/P03B1kqhRk9RT11BXam6zki1TjlGVzlGj4srNTkjXyFNTc9OQd3RKcLZRV3BWkE9PL8oJwXMys0sLgahgoJM9f//AQ "J – Try It Online") ## Explanation ``` |.!.' '"{~2%~#\-#\. Input: string S #\ Length of each prefix of S, [1, 2, ..., len(S)] #\. Length of each suffix of S, [len(s), ..., 2, 1] - Subtract elementwise 2%~ Divide by 2 We now have a range [(1-len(S))/2, ..., -1, 0, 1, ..., (len(S)-1)/2] "{~ Use each value to operate on S |.!.' ' Perform a shift while replacing characters with ' ' ``` [Answer] # [Perl 5](https://www.perl.org/), 53 + 1 (`-n`) = 54 bytes ``` $t=$"x(($\=y%%%c)/2).$_;say substr$t,$_,$\for 0..$\-1 ``` [Try it online!](https://tio.run/##FcLRCYAgEADQVSJOMEjTwK9whDYQoqJAKBXPoJbvosdLWz4MERQL9c05OPswxtam6xsJ04DzU@G1YMlQWphacHvMlZISnNBEp0f8p@TfmIqPAUmMRiqtSIQP "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 44 bytes ``` puts (0...c= ~/$/).map{$_.center(c*2)[_1,c]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsgqWlJWm6Fjd1CkpLihU0DPT09JJtFer0VfQ19XITC6pV4vWSU_NKUos0krWMNKPjDXWSY2sheqBaF6zOzSwuBqGCgkyIEAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¬£îUûUÊÑ sY ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=rKPuVftVytEgc1k&input=IlBuZXVtb25vdWx0cmFtaWNyb3Njb3BpY3NpbGljb3ZvbGNhbm9jb25pb3NpcyI) ``` ¬£îUûUÊÑ sY :Implicit input of string U ¬ :Split £ :Map each element at 0-based index Y î : Slice the following to the length of U Uû : Centre pad U with spaces to length UÊ : Length of U Ñ : Multiplied by 2 sY : Slice from index Y :Implicit output joined with newlines ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 101 bytes ``` (a)=>{int L=a.Length,l=L/2;for(;l-->0;)a=" "+a+" ";for(;++l<L;)Console.WriteLine(a.Substring(l,L));}; ``` Basically @KevinCruijssen's answer. Saves 2 bytes because `string.Length` doesn't need () and another 2 bytes because the second argument of `string.Substring()` is length rather than end Index, but then loses 2 bytes because `Console.WriteLine()` is longer. I had a more naive implementation, but it was about twice as long so... [Answer] # [jq](https://stedolan.github.io/jq/), ~~41~~ 39 bytes ``` (length/2*" "+.)[./""|keys[]:][:length] ``` [Try it online!](https://tio.run/##yyr8/18jJzUvvSRD30hLSUFJW08zWk9fSakmO7WyODrWKjbaCiId@/@/kqNThLOLEpdSeH5RTgqQzs0sLgahgoJMIC8gL7U0Nz8vvzSnpCgxNzO5KL84Ob8gM7k4MyczOb8sPyc5MS8/OT8vMx@oSQkA "jq – Try It Online") ]
[Question] [ Inspired by [this Game of Life question](https://codegolf.stackexchange.com/questions/88783/build-a-digital-clock-in-conways-game-of-life). [Wireworld](https://en.wikipedia.org/wiki/Wireworld) simulates "electrons" flowing through "wires", simple arrangements of which produce typical logic gate behavior. I challenge you to build a digital clock in the Wireworld cellular automaton. **Your clock must count upwards from 00:00 to 23:59 in the usual fashion, or to 11:59 with an AM/PM indicator, then reset.** Your entry should be visibly divided into two parts. **Part A should contain all of the non-display logic, all of the parts involved in incrementing and looping the digits.** Part B will be the display and the logic that drives it. The only connection between these two parts should be 16 wires representing the four digits of the time in [BCD](https://en.wikipedia.org/wiki/Binary-coded_decimal) (with one optional wire for the AM/PM indicator, and one optional wire for a signal clock line if your signals aren't continuous). **(EDIT: always-zero wires can be omitted)** **The timing of the clock behavior should be consistent.** The simulation should take the same number of ticks for each of the 1440 transitions between states. Any electrons on the 16 wires should emitted from part A at the same time and start their trip in parallel. **This is a code-golf competition. Your score is the area of the axis aligned bounding box surrounding part A.** By analogy, if this were a textual language, your score would be the size of the clock-management function producing four 4-bit outputs, which contains a loop and the logic for 4 counters, not the function that decodes and prints that output. Your part B can be as large or small as you'd like. It is only required so that the output of your submission can be seen by someone running it, since there is no easy way to simply "debug" outputs from a wireworld circuit. There are multiple BCD->7segment circuits available online. Feel free to use whichever one you'd like, or make your own if you need a clocked signal line, and display your AM/PM indicator at some scale similar to the digits. EDIT: Part B is now optional. If you just have the BCD outputs from your part A, feel free to submit that. It will be more tedious to confirm the clock works, but I can read a row of bits just fine in a paused simulation. [Answer] # Latching Clock **Score - 53,508** (of which only 36,828 is actively used due to the L-shaped design) [![Clock Running](https://i.stack.imgur.com/Ry4uc.gif)](https://i.stack.imgur.com/Ry4uc.gif) High Quality recording - <https://1drv.ms/u/s!ArQEzxH5nQLKhvt_HHfcqQKo2FODLQ> Golly pattern - <https://1drv.ms/u/s!ArQEzxH5nQLKhvwAmwCY-IPiBuBmBw> Guiding Principles - * Since this was my first time using a cellular automaton I avoided stringing together large premade components. One valid approach I did not take would have been a binary adder starting at zero and continuously adding one to the last output, followed by a binary to BCD converter, display demultiplexer, 7-segment decoder and 7-segment display. * It should be possible to cold start the clock. I imposed on myself the additional restriction that a single electron head placed at a specific conductor cell should correctly start the clock. I did not want to require careful manual synchronisation of many disparate flip-flops and individual timing elements before beginning the simulation. # Part I: The Minute Counter ### Mathematics Counting from 0 to 9 in binary (for the least significant minutes digit) goes as follows - 0 - **0000** 1 - **0001** 2 - **0010** 3 - **0011** 4 - **0100** 5 - **0101** 6 - **0110** 7 - **0111** 8 - **1000** 9 - **1001** Reading that as columns, the least significant (2^0 units bit stream) goes 01010101, the 2^1 units stream goes 0011001100, the 2^2 units stream goes 0000111100 and the 2^3 units stream goes 0000000011. The first one's easy - just flip-flip 01 forever. The third is a stream of four 1s, six 0s, phase shifted by six zeros. The fourth is a stream of eight 0s and two 1s. The second is a bit harder as it's got a nasty asymmetry. However, I notice that (where . is concat operator): 0011001100 . 0011001100 = 0011001100 . NOT(1100110011) = 00110011001100110011 XOR 00000000001111111111 = 5(0011) XOR 00000000001111111111 (Incidentally, as alluded to later, the majority of my clock runs on a 60-beat ticker. The 00000000001111111111 double length wave is where the need for the 120-beat ticker comes in). ### Design The output streams from top to bottom go Units of Minutes (2^0, 2^1, 2^2, 2^3) then Tens of Minutes (2^0, 2^2, 2^1). Note that the bottom two wires are crossed. [![Minute Counter Annotated](https://i.stack.imgur.com/dLTQR.png)](https://i.stack.imgur.com/dLTQR.png) 1. 120-beat main clock. 2. Where to place an electron for a cold start. Without any electron tail it splits in two directions but the diode immediately above catches one of these giving a nice cycling electron going around and round the 120-beat loop. 3. 12-beat secondary clock. 4. Coil of conductor + diode starts the secondary 12-beat clock. Words cannot describe how fiddly this little piece was to sync. You have to sync the 120 and 60 beat clocks, then sync in the 12-beat and frequency halver 24-beat pseudo clocks, followed by tying back the 24-beat clock to the 120-beat clock otherwise the XOR gate doesn't work. 5. Phase shift. 6. Flip-flop. A single electron on the input hits the set line first then after a very specific amount of time, hits the reset line giving precisely one pulse in, one pulse out. 7. Adding humps here - on the reset line, increases the delay between set and reset on the flip-flop. Each extra hump gives an extra pulse. The flip-flop below has nine extra humps, so ten pulses between set and reset. 8. XOR gate for my tricky 2^1 units of minutes line. 9. AND-NOT gate and very specific part lengths means each electron pulse which comes past doubles back on itself and annihilates the electron behind. Frequency halver. Creates a 24-beat clock from the 12-beat secondary source. 10. 60-beat secondary clock, which actually does most of the work. It's just easier to start a fast clock from a slower one, so the slowest clock (120-beats) is the master, even though it's barely used. The 60-beat clock is the heart of this thing. 11. Feedback wire which carries electrons only when the 60-beat clock is ticking. It's used in conjunction with an AND-NOT gate to stop the clock being restarted repeatedly from the 120-beat master. Otherwise many horrible things happen & Ctrl-Z is saviour. 12. The diode where the 60-beat clock is started from. 13. This whole device is a flip flop, AND gate, and AND-NOT gate combined. It gives a latch. One pulse in starts it, one pulse in stops it. 14. Loop of wire to calibrate the latch to 10 pulses on, 10 pulses off for a one in ten pulse input. Without it we get 12 pulses on, 8 pulses off. These ten on ten off latches form the basic components of the ten minute blocks in the same way the 6-micron (1 pulse) flip-flops formed the basic components of the minute units. 15. The cold start initial pulse caused all sorts of problems including being two beats out of phase with the clocks it starts. This messes up the latches. This AND gate catches and disposes of out of sync pulses - in particular the starting pulse. 16. This is a part of the design I somewhat regret in retrospect. It takes an electron, splits it into five and annihilates the five electrons behind, taking 111111 to 100000. 17. This takes an electron and stitches it on the front. Two phases ahead to be precise. It takes 100000 and makes 101000. Combined with part 16 we get 111111 -> 100000 -> 101000. In retrospect I wish I'd done 111111 -> 101010 -> 101000; it would have achieved the same effect in less space. 18. The above patterns are then pushed into the bottom latch to achieve 20 on, 40 off. This is split, half is phase shifted by 20 units, and then these form the two high order bit streams of the tens of minutes. # Part II: The Hour Counter ### Explanation The input to the hour counter is a single electron pulse, once an hour. The first step is to reduce this to a single electron pulse, once every twelve hours. This is achieved using several "latch & catch" primitives. A "latch" is a 6-micron flip-flop connected to an AND-NOT and an AND gate to give a 6-micron on/off latch. A "catch" takes a continuous stream of electrons as input, allows the first through, then annihilates every other electron behind, until the stream ends at which point the catch resets. Placing a latch, followed by a catch, in series, results in one electron in -> turns on the latch, one electron out the other end (rest caught by catch). Then second electron in -> turns off latch, catch silently resets. Net effect: first electron passes through, second electron is annihilated, and so on and so forth, *irrespective of how long the delay is between those electrons*. Now chain two "latch & catch" in series, and you have only one in four electrons passing through. Next, take a third "latch and catch", but this time embed an entire fourth latch and catch on the flip-flop SET line, between the AND-NOT gate and the flip-flop SET. I'll leave you to think about how this works, but this time only one in three electrons passes through, *irrespective of how long the delay is between those electrons*. Finally, take the one in four electrons, and the one in three, combine them with an AND gate, and only one in twelve electrons pass through. This whole section is the messy squiggle of paths to the top left of the hour counter below. Next, take the electron every twelve hours and split back into one every hour, but output each onto a different conductor wire. This is achieved using the long coiled conductor with thirteen exit points. Take these electrons - one an hour down different conductors, and hit a flip-flop SET line. The RESET line on that same flip flop is then hit by the next hour's conductor, giving sixty pulses down each wire per hour. Finally - take these pulses and pass them into seven and a half bytes of ROM (Read-Only Memory) to output the correct BCD bitstreams. See here for a more detailed explanation of WireWorld ROM: <http://www.quinapalus.com/wires6.html> ### Design [![Hour Counter Annotated](https://i.stack.imgur.com/cMk18.jpg)](https://i.stack.imgur.com/cMk18.jpg) 1. One electron per hour input. 2. First latch. 3. First catch. 4. "Latch & catch" embedded on an outer "latch & catch" SET line. 5. AND gate. 6. AM/PM latch (turned on/off once every twelve hours). 7. Each loop of wire is 6x60=360 units long. 8. Flip/Flop turned on its side to create a smaller profile. 9. Seven and a half bytes of ROM. # Notes 1. Due to its one electron per minute, 6-micron design, run the simulation at six generations per minute (one generation every 10 seconds) for a real-time clock. 2. The AM/PM line is high (1) for AM, low (0) for PM. This might seem a slightly unusual way round to choose, but there is justification. During a cold start of the clock, the AM/PM line is naturally low (0) initially. As soon as the AM/PM line is pulled high (1), this indicates that the count has begun at 12:00AM. All output before this point should be disregarded, all output after this point is considered meaningful. # Useful Links * I learned the basics of WireWorld from <http://www.quinapalus.com/wi-index.html>. An excellent resource. * To create and simulate the cellular automaton I used Golly: <http://golly.sourceforge.net/> * I took the AND gate design from <http://mathworld.wolfram.com/WireWorld.html> * And I've only just found this webpage so didn't use it but it looks great: <http://karlscherer.com/Wireworld.html> [Answer] # Binary counter clock (score = ~~134×33 = 4422~~ 134×32 = 4288) As promised 2⅔ years ago. Actual building time from scratch was less than 3 days. I took inspiration from several sources, but in the end everything is custom made, and no cell is copied from any design by someone else. It makes royal use of the colors of [WireWorldMarked](https://github.com/gollygang/ruletablerepository/wiki/TheRules#wireworld-and-derivatives) (also by me, and supported by default by Golly). The colors are just eye-candy and don't change the rules of WireWorld. This uses 10 micron technology (electrons spaced 10 gens apart). This makes small loops (memory cells for example) larger, however it allows not only for easier calculations but also compact axis-aligned ROMs and decoders, and it's the maximum throughput of a 'cross' gate. Everything makes use of 'negative' logic, where the presence of electrons is a logical '0' and missing electrons are '1'. In this sense, an OR gate, for example, does A=0 OR b=0 -> output 0. The sole reason for this is that it makes the binary counters, and in particular, the reset logic, much less complex. The clock's real-time speed is 480 gens per minute (large green loop) ~~which translates to 0.125s per gen or 8 gens/s. The loop expands the bounding box by 1 in the vertical direction, but with any smaller number the carries propagate too slow and it never displays the correct time.~~ Unfortunately it will never be real-time in Golly because Golly only applies a delay *between* gens, and with a non-negligible duration of calculating a gen, it will run slow if you set the delay to 0.125. In fact, the speed appears to be non-constant and fluctuates by several percents. **[edit]** This is v2 in which I've synchronized the display segments. This way the maximum delay between the final change of the leftmost display and the next change of the rightmost display (between 24:00->0:00) is 170 gens. The V1 display update took 500 gens, longer than 480 gens (a 'minute'), oops. I was about to boast how good I am for squeezing a loop of 440 in a box 1 less tall, then choosing 400 gens because it divides a minute nicely, but I wanted a significantly higher number, and was done waiting until someone pointed out "hey why don't you just use a smaller loop and some dividers?". So I used three dividers and a loop of 150 gens for a rate of 1200 gens/min (20Hz). The squeezed loop is still visible in the explanation image below. ![Clock part A v2.png](https://i.stack.imgur.com/0Xg8p.png) ![Clock all v2.png](https://i.stack.imgur.com/390HG.png) [High-speed animation at 7200 gens/s](https://i.stack.imgur.com/udpT1.gif) (1.2MiB) [Real-time animation of only the display](https://i.stack.imgur.com/L7ODM.gif) (600KiB) (animations are of v1 but still give an impression of the clock) Extra explanations and some dividers before final space-optimizations: (the gray arrows point to cells in the middle of the machinery which are either present or absent, depending on if that bit should contribute to the reset logic.) ![Clock explanations.png](https://i.stack.imgur.com/q7332.png) Golly pattern with everything I made until now: [Clock (Mark Jeronimus).mc](https://www.dropbox.com/s/811inoyqaql53t7/Clock%20%28Mark%20Jeronimus%29.mc?dl=0) [Answer] ## Delay line memory - 51 x 2880 = 146880 ![Image](https://i.stack.imgur.com/2zbFo.png) Zoomed out: ![Image](https://i.stack.imgur.com/rdQiZ.png) Output comes out the top of each loop. I put all the states directly on the wire with this lua, letting `golly` step the electrons forward between bits so we don't have to follow the wire with a cursor. I used this naive method to set a bar and crash course wireworld, golly and lua. ``` local g = golly() local minutes_in_day = 1440 -- 60x24 local interval = 4 -- how often to send electrons local function bcd4(num) num=math.floor(num) local t={} for b=4,1,-1 do t[b]=math.floor(math.fmod(num,2)) num=(num-t[b])/2 end return table.concat(t) end local function makewire(x,y1,y2) for y1=1,y2 do g.setcell(x,y1,3) end end local function makeloop(x,y,size) local len = size/2 - 1 makewire(x,y+1,len); makewire(x+2,y+1,len) -- main wires g.setcell(x+1,y,3); g.setcell(x+1,y+len,3) -- endcape end local function paint(x,y,pattern) for v in string.gmatch(pattern,".") do if v=="1" then g.setcell(x, y, 1); g.setcell(x, y-1, 2) end x = x + 4 end g.show(pattern);g.update() -- slows things down but more interesting to watch for i=1,interval do g.step() end end for x=0,63,4 do makeloop(x,0,minutes_in_day * interval) end for hour = 0,23 do for minute = 0,59 do paint( 0, 2, bcd4(hour/10) .. bcd4(hour%10) .. bcd4(minute/10) .. bcd4(minute%10) ) end end ``` For testing I added these top wires and watched their tips. ![Imgur](https://i.stack.imgur.com/UVkT9.png) Here's the script to collect the 4 sets of 4 wire BCD to eyeball. ``` -- watches 16 wires spaced 4 apart starting at (0,-4) local ticks = 1440 -- set to match the length of your 24 hour loop local g = golly() local output = "" local nums = { ["0000"] = "0", ["0001"] = "1", ["0010"] = "2", ["0011"] = "3", ["0100"] = "4", ["0101"] = "5", ["0110"] = "6", ["0111"] = "7", ["1000"] = "8", ["1001"] = "9", ["1010"] = "A", ["1011"] = "B", ["1100"] = "C", ["1101"] = "D", ["1110"] = "E", ["1111"] = "F" } -- full set in case we have errors (i did) for i=0,ticks,1 do local text = "" for i=0,48,16 do -- set your X here, change the 0 and 48 local word = "" for j=0,15,4 do local bit = g.getcell(i+j,-4) -- set your Y here, change -4 if bit == 0 or bit == 3 then word = word .. "0" else word = word .. "1" end end text = text .. nums[word] end g.show(text); output = output..' '..text g.update(); g.step();g.step();g.step();g.step() end g.note(output) ``` *Final answer requires pruning the always-zero lines and routing the rest to their correct BCD inputs.* ]
[Question] [ ## CONGRATULATIONS to @kuroineko. Wins the bounty for excellent speed (672 moves) on the Gauntlet track. ### LEADER:\* Nimi scoring a lightweight 2129. Other entries are larger but showing some serious speed. \*Leader may change due to later entries. Your task is to write a small program that can drive a racing car fast. # Rules Your program will read in an image of the track. You can start your car on any yellow pixel, and you must finish by crossing any black pixel. The path of your car must be only on the grey ((c,c,c) where 30 <= c <= 220) track. Your car will move in a straight line each turn with velocity v made up of integers vx and vy (starting with (0,0)). At the start of each turn your program can change vx and vy such that: `abs(vx2-vx1) + abs(vy2-vy1) <= 15` *Update:* Increased maximum acceleration to 15. Your program will then plot a straight line from your current location to (location + v) in white with a blue dot at the start. If a pixel under this line is black, you have finished the race. Otherwise, if all the pixels under that line are grey or yellow, you may continue to the next turn. Your program must output the track image with your path in white and blue added. ## Additional Output (added 2015-01-15): *If you wish to compete for the win or the bonus*, your program should also output your list of points (the blue dots) for the City or Gauntlet respectively. Include the list of points with your answer (for verification). The points should look like: `(x0,y0), (x1,y1), ... (xn,yn)`. You can use white space freely including `'\n'` characters to fit the data on the page. You may use third party image reading and writing, line drawing and pixel access libraries. You can't use path-finding libraries. If you wish you can convert the PNG images into other graphics formats (such as GIF, JPG, BMP) if you need to. # A few tracks to drive on A simple track to start out: ![Simple Track](https://i.stack.imgur.com/ySeSZ.png) A Race Track: ![Race Track](https://i.stack.imgur.com/meqx5.png) An Obstacle Course: ![Obstacle Course](https://i.stack.imgur.com/w5vAi.png) The City: ![The City](https://i.stack.imgur.com/Q46YG.png) Nightmare Track: The Gauntlet (if the others are too easy) ![The Gauntlet](https://i.stack.imgur.com/ywgiV.png) # Scoring Your score will be based on your result on the City track. Points are equal to your program length in bytes plus 10 points for each turn your racing car took to finish. Lowest score wins. Please include your City track run image with your answer - we would like to see your driving style. Please use a title for your answer in the format: `<Racing Driver or Team Name> <Language> <Score>` eg: Slowpoke Perl 5329 Your program must be able to drive on any track image following the above rules. You must not hardcode the optimum path or any parameters of the test tracks. The other standard loopholes apply. # Similar challenges This is a similar puzzle to one posed by Martin: [To Vectory! – The Vector Racing Grand Prix](https://codegolf.stackexchange.com/questions/32622/to-vectory-the-vector-racing-grand-prix). This puzzle has a number of differences: * Driving through walls is not allowed. * You can use unlimited memory and time. * You do not have to run somebody else's code on your computer. * You do not have to download anything except one image. * The size of your code counts in scoring. Smaller is better. * You plot your solution on the track image. * You can easily create your own tracks with a paint package. * The higher resolution encourages more realistic braking and cornering. * Acceleration of 15 creates about 450 possibilities per turn. This makes BFS less feasible and encourages new interesting algorithms. This puzzle should inspire a new round of programmers to try solutions and allow programmers with old solutions to rethink them in the new environment. [Answer] # pighead PHP (5950+470 = 6420) Yet another (pigheaded) BFS variation, with some preprocessing to trim down down search space. ``` <?php define ("ACCEL_MAX", 15); define ("TILE_SIZE_MAX", 2*floor (ACCEL_MAX/2)-1); define ("TILE_SIZE_MIN", 1); class Point { function __construct ($x=0, $y=0) { $this->x = (float)$x; $this->y = (float)$y; } function add ($v) { return new Point ($this->x + $v->x, $this->y + $v->y); } } class Tile { public $center; private static $id = 0; public function __construct ($corner_x, $corner_y, $size, $type) { $this->type = $type; $this->id = ++self::$id; $half = round ($size/2); $this->center = new Point ($corner_x+$half, $corner_y+$half)); for ($x = 0 ; $x != $size ; $x++) for ($y = 0 ; $y != $size ; $y++) Map::$track[$x+$corner_x][$y+$corner_y] = 0; Map::$tile_lookup[$this->center->x][$this->center->y] = $this; } public function can_reach ($target) { if (isset($this->reachable[$target->id])) return $this->reachable[$target->id]; $ex = $target->center->x; $ey = $target->center->y; $ox = $this->center->x; $oy = $this->center->y; $sx = $ex - $ox; $sy = $ey - $oy; $range = max (abs ($sx), abs ($sy)); if ($range == 0) return false; $reachable = true; for ($s = 1 ; $s != $range ; $s++) if (!isset (Map::$track[$ox + $s/$range*$sx][$oy + $s/$range*$sy])) { $reachable = false; break; } return $this->reachable[$target->id] = $target->reachable[$this->id] = $reachable; } } class Node { public $posx , $posy ; public $speedx, $speedy; private $parent; public function __construct ($posx, $posy, $speedx, $speedy, $parent) { $this->posx = $posx; $this->posy = $posy; $this->speedx = $speedx; $this->speedy = $speedy; $this->parent = $parent; } public function path () { $res = array(); for ($node = $this ; $node != null ; $node = $node->parent) { array_unshift ($res, new Point ($node->posx, $node->posy)); } return $res; } } class Map { public static $track; // map of track pixels public static $tile_lookup; // retrieve tile from a position private static $tiles; // all track tiles private static $sx, $sy; // map dimensions private static $cell; // cells of the map private static $start; // starting point private static $acceleration; // possible acceleration values private static $img; // output image private static $output_name; const GOAL = 0; // terrain types const START = 1; const TRACK = 2; private static function create_tile ($cx, $cy, $size) { for ($x = $cx ; $x != $cx + $size ; $x++) for ($y = $cy ; $y != $cy + $size ; $y++) if (!isset (self::$track[$x][$y]) || !self::$track[$x][$y]) return false; for ($x = $cx ; $x != $cx + $size ; $x++) for ($y = $cy ; $y != $cy + $size ; $y++) self::$track[$x][$y] = 0; //Trace::msg ("track tile $cx $cy $size"); return new Tile ($cx, $cy, $size, self::TRACK); } public static function init ($filename) { // read map definition $img = imagecreatefrompng ($filename) or die ("could not read $filename"); self::$img = $img; self::$output_name = "_".$filename; self::$sx = imagesx ($img); self::$sy = imagesy ($img); for ($x = 0 ; $x != self::$sx ; $x++) for ($y = 0 ; $y != self::$sy ; $y++) { $color = imagecolorat ($img, $x, $y) & 0xFFFFFF; if ($color == 0) self::$tiles[] = new Tile ($x, $y, 1, Map::GOAL); else if ($color == 0xFFFF00) self::$tiles[] = self::$start[] = new Tile ($x, $y, 1, Map::START); else { $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; if ($r == $g && $r == $b && $r >= 30 && $r <= 220) @self::$track[$x][$y] = 1; } } for ($size = TILE_SIZE_MAX ; $size >= TILE_SIZE_MIN ; $size--) for ($x = 0 ; $x != self::$sx ; $x++) for ($y = 0 ; $y != self::$sy ; $y++) { $tile = self::create_tile ($x, $y, $size); if ($tile) self::$tiles[] = $tile; } self::$acceleration = array(); for ($x = -ACCEL_MAX ; $x <= ACCEL_MAX ; $x++) for ($y = -ACCEL_MAX ; $y <= ACCEL_MAX ; $y++) { if (abs ($x) + abs ($y) <= ACCEL_MAX) self::$acceleration[] = new Point ($x, $y); } } public static function solve () { $res = $border = $present = array(); foreach (self::$start as $start) { $border[] = new Node ($start->center->x, $start->center->y, 0, 0, null); $present[$start->center->x." ".$start->center->y." 0 0"] = 1; } while (count ($border)) { $node = array_shift ($border); $px = $node->posx; $py = $node->posy; $vx = $node->speedx; $vy = $node->speedy; $current = self::$tile_lookup[$px][$py]; foreach (self::$acceleration as $a) { $nvx = $vx + $a->x; $nvy = $vy + $a->y; $npx = $px + $nvx; $npy = $py + $nvy; @$tile = self::$tile_lookup[$npx][$npy]; if (!$tile || !$tile->can_reach ($current)) continue; if ($tile->type == self::GOAL) { $end = new Node ($npx, $npy, $nvx, $nvy, $node); $res = $end->path (); $ox = $res[0]->x; $oy = $res[0]->y; for ($i = 1 ; $i != count ($res) ; $i++) { $ex = $res[$i]->x; $ey = $res[$i]->y; imageline (self::$img, $ox, $oy, $ex, $ey, 0xFFFFFF); $ox = $ex; $oy = $ey; } for ($i = 0 ; $i != count ($res) ; $i++) { imagesetpixel (self::$img, $res[$i]->x, $res[$i]->y, 0xFF); } imagepng (self::$img, self::$output_name); printf (count($present)." nodes, ".round(memory_get_usage(true)/1024)."K\n"); printf ((count($res)-1)." moves\n"); return; } $signature = "$npx $npy $nvx $nvy"; if (isset ($present[$signature])) continue; $border[] = new Node ($npx, $npy, $nvx, $nvy, $node); $present[$signature] = 1; } } } } ini_set("memory_limit","1000M"); Map::init ($argv[1]); Map::solve(); ?> ``` ## Language choice PHP is pretty good at handling images. It also has native associative memory, which makes programming BFS node lookup a breeze. The downside is that the node identifiers hashing is not terribly time-efficient, so the result is anything but fast. From my experiments with the previous racing challenge, I have no doubt C++11 and its hash tables would perform way better, but the source code would at the very least double, plus the need for whatever external png library (even LodePNG) would make for a messy build. Perl and its more advanced offsprings would probably allow for a more compact and efficient code (due to better hashing performances), but I am not familiar enough with any of these to try a port. ## BFS core The search operates on a position+speed space, i.e. a node represents a given location visited with a given speed. This of course makes for a pretty huge search space, but yields optimal results provided all possible track locations are examined. Clearly, given the number of pixels on even a small image, an exhaustive search is out of the question. ## Cuts I chose to cut through the position space, by selecting only a subset of track pixels. The solver will consider all positions within reach, limited only by acceleration. The track is tiled with squares, whose maximal size is computed so that two adjacent squares can be reached with the maximal allowed acceleration (i.e. 14x14 pixels with the current speed limit). After packing the track with big squares, increasingly smaller tiles are used to fill the remaining space. Only the center of each tile is considered as a possible destination. Here is an example: ![track tiling example](https://i.stack.imgur.com/XEQE2.png) This heuristic choice is enough to make the solver fail on the nightmare map. I suppose one could try to reduce the max tile size until some solution is found, but with the current settings the solver runs for something like an hour and uses 600 Mb, so more accurate results would require an unreasonable amount of time and memory. As a second cut, squares of only 1 pixel might be left out. This will of course degrade the solution or even prevent the solver from finding any, but it improves computation time a lot and usually yields pretty close results on "simple" maps. For instance, on city, leaving out 1x1 pixel squares reduces the BFS tree nodes explored from 660K to about 90K for 47 vs 53 moves solutions. ## BFS vs A\* A\* needs more code and is not even guaranteed to produce faster results in the position/speed space, since evaluating the best next candidate is nothing as simple as in the classic position only space (which can easily be defeated with purpose-made cul-de-sacs anyway). Besides, though PHP has some priority queues of sort, that by the way support dynamic reordering contray to their C++ cousins, I doubt they would be enough for an efficient A\* implementation, and rewriting a binary heap or whatever dedicated A\* queue structure would require way too many lines of code. ## Wall check I did not use a Bresenham algorithm to check for wall collisions, so the trajectory might clip the odd wall pixel. It should not allow to cross through a wall, though. ## Performances This solver is sure no six-legged jackrabbit. Without the extra cut, a map can take over 10 minutes to solve on my middle-range PC. I suggest setting tile minimal size to 2 or 3 if you want to fiddle with the code without spending ages waiting for a result. Memory consumption is reasonable for this kind of algorithm and language: around 100 Mb or less except for nightmare that peaks above 600 Mb. ## Results and scoring Scores are given without the "minimal tile size" cut. As a careful reader may deduce from my general comments, I don't care much about the golfing part of this challenge. I don't see how running my code through an obfuscator or deleting some optimizations and/or debug routines to shrink the source would make this any more fun. Let just S be the source byte size for now : track S+1020 ![track result](https://i.stack.imgur.com/BlF8j.png) city S+470 ![city result](https://i.stack.imgur.com/07VXT.png) obstacles S+280 ![enter image description here](https://i.stack.imgur.com/jGoQZ.png) nightmare -> fails [Answer] ## FirstRacer Java (5825 + 305\*10 = 8875) Just to have a start. Needs 305 segments on City. This Java program does it pipelined: 1. read the image 2. A\* (A star) * 2.1 Build the A\* search landscape. * 2.2. Track back looking only for the best \*direct\* 8 neighbor cells (N,S,E,W,NE,NW,SE,SW). This finds the shortest track t0 pixelwise. 3. stay on t0 and optimize it for speed by eliminating pixels. Fullfilling the constraint by never be faster than 7 (this translates to keep at least every 7th pixel). 4. draw the track into the image 5. show the resulting image. ``` package race; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.WindowConstants; public class AStar { private static BufferedImage img; private static int Width; private static int Height; private static int[][] cost; private static int best=Integer.MAX_VALUE; private static Point pBest; public static void main(String[] args) throws IOException { String file = "Q46YG.png"; img = read(file); Width=img.getWidth(); Height=img.getHeight(); Vector<Point> track = astar(); track = optimize(track); draw(track); System.out.println(10 * track.size()); JFrame frame = new JFrame(file) { public void paint(Graphics g) { setSize(Width+17, Height+30+10); g.drawImage(img,8,30,null); } }; frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } private static Vector<Point> optimize(Vector<Point> track) { Vector<Point> opt=new Vector<Point>(); Point p0 = track.get(0); Point p1 = track.get(1); int v=0; opt.add(p0); int vx0=p1.x-p0.x, vy0=p1.y-p0.y; for (int i = 2; i < track.size(); i++) { Point p = track.get(i); if (v<7 && vx0==p.x-p1.x && vy0==p.y-p1.y) { v++; } else { v=0; opt.add(p1); vx0=p.x-p1.x; vy0=p.y-p1.y; } p1=p; } opt.add(p1); return opt; } private static void draw(Vector<Point> track) { Graphics2D g = img.createGraphics(); Point p0 = track.get(0); for (int i = 1; i < track.size(); i++) { Point p1 = track.get(i); g.setColor(Color.WHITE); g.drawLine(p0.x, p0.y, p1.x, p1.y); img.setRGB(p0.x, p0.y, 0xff0000ff); img.setRGB(p1.x, p1.y, 0xff0000ff); p0=p1; } } private static Vector<Point> astar() { Vector<Point> v0=findStart(); for(int i=0; ; i++) { Vector<Point> v1=next(v0); if (v1.size()==0) break; v0=v1; } Vector<Point> track=new Vector<Point>(); Point p0 = pBest; int x0=p0.x, y0=p0.y; int c0=cost[x0][y0]; while(true) { int x=x0, y=y0; track.add(0, new Point(x, y)); for (int x1 = x-1; x1 <= x+1; x1++) { for (int y1 = y-1; y1 <= y+1; y1++) { int i1=getInfo(x1, y1); if ((i1&2)==2) { int c=cost[x1][y1]; if (c0>c) { c0=c; x0=x1; y0=y1; } } } } if(x0==x &&y0==y) break; } return track; } private static Vector<Point> next(Vector<Point> v0) { Vector<Point> v1=new Vector<Point>(); for (Point p0 : v0) { int x=p0.x, y=p0.y; int c0=cost[x][y]; for (int x1 = x-1; x1 <= x+1; x1++) { for (int y1 = y-1; y1 <= y+1; y1++) { int i1=getInfo(x1, y1); if ((i1&2)==2) { int c1=c0+1414; if (x1==x || y1==y) { c1=c0+1000; } int c=cost[x1][y1]; if (c1<c) { cost[x1][y1]=c1; Point p1=new Point(x1, y1); v1.add(p1); if (i1==3) { if (best>c1) { best=c1; pBest=p1; } } } } } } } return v1; } private static Vector<Point> findStart() { cost=new int[Width][Height]; Vector<Point> v=new Vector<Point>(); for (int i = 0; i < Width; i++) { for (int j = 0; j < Height; j++) { if (getInfo(i,j)==1) { cost[i][j]=0; v.add(new Point(i, j)); } else { cost[i][j]=Integer.MAX_VALUE; pBest=new Point(i, j); } } } return v; } /** * 1: You can start your car on any yellow pixel, * 3: and you must finish by crossing any black pixel. * 2: The path of your car must be only on the grey ((c,c,c) where 30 <= c <= 220) track. * 0: else * * @param x * @param y * @return */ private static int getInfo(int x, int y) { if (x<0 || x>=Width || y<0 || y>=Height) return 0; int rgb = img.getRGB(x, y); int c=0; switch (rgb) { case 0xffffff00: c=1; break; case 0xff000000: c=3; break; default: int r=0xff&(rgb>>16); int g=0xff&(rgb>> 8); int b=0xff&(rgb>> 0); if (30<=r&&r<=220&&r==g&&g==b) c=2; } return c; } private static BufferedImage read(String file) throws IOException { File img = new File("./resources/"+file); BufferedImage in = ImageIO.read(img); return in; } } ``` ![The City](https://i.stack.imgur.com/LEV7v.png) I think the Race Track gives you a better impression how FirstRacer works. ![Race Track](https://i.stack.imgur.com/Aycqq.png) [Answer] ## SecondRacer Java (1788 + 72\*10 = 2508) ~~(2708) (2887) (3088) (3382) (4109 + 72\*10 = 4839) (4290 + 86\*10 = 5150)~~ Similar to FirstRacer. But different in steps 2.2 and 3. which results in driving farsighted and using the gear. 2. A\* (A star) * 2.1 Build the A\* search landscape. * 2.2. Find the best cell in \*sight\* and take the Euclidean distance into account. (Still looking only in directions N,S,E,W,NE,NW,SE,SW.) As a result SecondRacer finds a path with much less way points. 3. Optimization is much elaborate now. The idea is to partition the given lines between two way points into as less as possible turns, while not violating the acceleration constraint. ### Performance None of these tracks is a problem for A\*. Just some very few seconds (<10) to solve (even the "Nightmare Track: The Gauntlet") on my middle-range PC. ### Path Style I call it octopussy. By far not as elegant as the pighead solution (from kuroi neko). ### Code Style I entered into a moderate fighting mode keeping readability. But added a golfed version. ``` import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.*; import javax.imageio.*; import javax.swing.*; import static java.lang.Math.*; class AStar2 { BufferedImage img; int Width; int Height; int[][] cost; int best=Integer.MAX_VALUE; Point pBest; public static void main(String[] args) throws IOException { new AStar2().exec(args); } void exec(String[] args) throws IOException { img = ImageIO.read(new File(args[0])); Width=img.getWidth(); Height=img.getHeight(); draw(optimize(astar())); JFrame frame = new JFrame() { public void paint(Graphics g) { setSize(Width+17, Height+30+10); g.drawImage(img,8,30,null); } }; frame.setVisible(true); } Vector<Point> astar() { Vector<Point> v0=findStart(); while(v0.size()>0) v0=next(v0); for(Point p0 = pBest; p0!=null; p0=trackBack(p0)) v0.add(p0); return v0; } Vector<Point> findStart() { cost=new int[Width][Height]; Vector<Point> v=new Vector<Point>(); for (int i = 0; i < Width; i++) for (int j = 0; j < Height; j++) { if (getInfo(i,j)==1) { cost[i][j]=0; v.add(new Point(i, j)); } else { cost[i][j]=Integer.MAX_VALUE; pBest=new Point(i, j); } } return v; } Vector<Point> next(Vector<Point> v0) { Vector<Point> v1=new Vector<Point>(); for (Point p0 : v0) { int x=p0.x, y=p0.y,x1,y1,i1,c1, c0=cost[x][y]; for (Point p : n(new Point(x,y))) { x1 = p.x; y1 = p.y; i1=getInfo(x1, y1); if (i1/2==1) { c1=c0+(x1==x||y1==y?10:14); if (c1<cost[x1][y1]) { cost[x1][y1]=c1; Point p1=new Point(x1, y1); v1.add(p1); if (i1==3) { if (best>c1) { best=c1; pBest=p1; } } } } } } return v1; } Point trackBack(Point p0) { Point p1=null, t; int x=p0.x, y=p0.y, i; double c0=0, c; for (Point p : n(new Point(0,0))) { for (i = 1; getInfo((t= new Point(x+i*p.x, y+i*p.y)).x, t.y)>0; i++) { c=cost[t.x][t.y]-cost[x][y]+5*sqrt((x-t.x)*(x-t.x) + (y-t.y)*(y-t.y)); if (c0>c) { c0=c; p1= t; } } } return p1; } Vector<Point> n(Point p) { int [] c=new int[] {0, -1,-1, -1,-1, 0,-1, 1,0,1,1, 1,1, 0,1, -1}; Vector<Point> v=new Vector<Point>(); for (int i = 0; i < c.length; i+=2) v.add(new Point(p.x+c[i], p.y+c[i+1])); return v; } Vector<Point> optimize(Vector<Point> track) { Vector<Point> opt=new Vector<Point>(); Point p0 = track.get(0); opt.add(p0); for (int i = 1; i < track.size(); i++) segmentAcceleration(opt, track.get(i)); return opt; } boolean constraint(Point p0, Point p1, Point p2) { return abs(p2.x-p1.x-p1.x+p0.x) + abs(p2.y-p1.y-p1.y+p0.y) <= 15; } void segmentAcceleration(Vector<Point> opt, Point p1 ) { Point p0 = opt.lastElement(); int d=max(abs(p0.x-p1.x), abs(p0.y-p1.y)), x=(p1.x-p0.x)/d, y=(p1.y-p0.y)/d, start=opt.size(),i; for (i = 0; i <=d; i++) opt.add(new Point(p0.x+x*i, p0.y+y*i)); for(int success=1; success==1;) { success=0; for (int j = start; j < opt.size()-1; j++) { Point q=new Point(opt.get(j).x+x, opt.get(j).y+y); if (opt.get(j).x==opt.get(j+1).x && opt.get(j).y==opt.get(j+1).y) { opt.remove(j); success=1; } else if (j>1&&constraint(opt.get(j-2), opt.get(j-1), q) && constraint(opt.get(j-1), q, opt.get(j+1)) && (j>opt.size()-3 || constraint(q, opt.get(j+1), opt.get(j+2)))) { opt.set(j, q); success=1; } } } } void draw(Vector<Point> track) { Graphics2D g = img.createGraphics(); Point p0=track.get(0); for (Point p1: track) { g.setColor(Color.WHITE); g.drawLine(p0.x, p0.y, p1.x, p1.y); img.setRGB(p0.x, p0.y, 0xff0000ff); img.setRGB(p1.x, p1.y, 0xff0000ff); p0=p1; } } int getInfo(int x, int y) { if (x<0 || x>=Width || y<0 || y>=Height) return 0; int rgb = img.getRGB(x, y), r=0xff&(rgb>>16), g=0xff&(rgb>> 8), b=0xff&(rgb>> 0); switch (rgb) { case 0xffffff00: return 1; case 0xff000000: return 3; default: if (30<=r&&r<=220&&r==g&&g==b) return 2; } return 0; } } ``` ### golfed -> WARNING: it does in place replacement of the original file! ``` import java.awt.*;import javax.imageio.*;import static java.lang.Math.*;class A{class B{int C,D;}class E extends java.util.Vector<B>{};static java.awt.image.BufferedImage F;int G=F.getWidth(),H=F.getHeight(),I[][]=new int[G][H],J=-1>>>1,K,L,M=255,N;B O,P,Q;public static void main(String[]R)throws Exception{F=ImageIO.read(new java.io.File(R[0]));new A().S();ImageIO.write(F,"PNG",new java.io.File(R[0]));}void S(){E U=new E(),V=new E();for(K=0;K<G;K++)for(L=0;L<H;L++)if(W(K,L)==1)U.add(X(K,L));else I[K][L]=J;while(U.size()>0){P=U.remove(0);int C=P.C,D=P.D,Y,Z,a,b;for(N=0;N<9;N++)if(N!=4)if((a=W(Y=C+N/3-1,Z=D+N%3-1))>0&&I[Y][Z]>(b=I[C][D]+(Y==C||Z==D?10:14))){I[Y][Z]=b;U.add(X(Y,Z));if(a==3&&J>b){J=b;O=Q;}}}P=O;while(O!=null){U.add(O);J=O.C;L=O.D;double c=0,d;O=null;for(N=0;N<9;N++)if(N!=4)for(K=1;W(X(J+K*(N/3-1),L+K*(N%3-1)).C,Q.D)>0;K++)if(c>(d=I[Q.C][Q.D]-I[J][L]+5*sqrt((J-Q.C)*(J-Q.C)+(L-Q.D)*(L-Q.D)))){c=d;O=Q;}}Graphics2D e=F.createGraphics();V.add(P);for(K=1;K<U.size();K++){O=P;P=U.get(K);e.setColor(Color.WHITE);e.drawLine(O.C,O.D,P.C,P.D);int f=max(abs(O.C-P.C),abs(O.D-P.D)),C=(P.C-O.C)/f,D=(P.D-O.D)/f,start=V.size();for(L=0;L<=f;L++)V.add(X(O.C+L*C,O.D+L*D));while(f>0)for(f=0,L=start;L<V.size()-1;L++)if(V.get(L).C==V.get(L+1).C&&V.get(L).D==V.get(L+1).D)V.remove(L);else if(L>1&&g(V.get(L-2),V.get(L-1),X(V.get(L).C+C,V.get(L).D+D))&&g(V.get(L-1),Q,V.get(L+1))&&(L>V.size()-3||g(Q,V.get(L+1),V.get(L+2)))){V.set(L,Q);f=1;}}for(B h:V)F.setRGB(h.C,h.D,~0xffff00);}B X(int C,int D){Q=new B();Q.C=C;Q.D=D;return Q;}boolean g(B O,B P,B i){return abs(i.C-P.C-P.C+O.C)+abs(i.D-P.D-P.D+O.D)<16;}int W(int C,int D){if(C>=0&&C<G&&D>=0&&D<H){int j=F.getRGB(C,D),Q=j>>16&M,e=j>>8&M;if(j==~M)return 1;if(j==M<<24)return 3;if(30<=Q&&Q<=220&&Q==e&&e==(M&j))return 2;}return 0;}} ``` --- All images are shown on their A\* gradient landscape. Starting from light yellow to brown (=dark yellow). While - according to A\* - the resulting path is tracked backwards (here from brown to light yellow). Race Track S+175 ![Race Track](https://i.stack.imgur.com/jfaY8.png) Obstacle Course S+47 ![Obstacle Course](https://i.stack.imgur.com/VdIkA.png) City S+72 ![City](https://i.stack.imgur.com/YXnmF.png) Gauntlet S+1133 ![Gauntlet](https://i.stack.imgur.com/EmVec.png) [Answer] # Tutu - Haskell - (3460 2654 2476 2221 2060 1992 1900 + 50x10 = 2400) Strategy: 1. find A\* 2. bloat the path with it’s neighbors (distance 2) 3. find again A\*, but this time in the position+speed space, just like the pighead racer Golf: * left out most of the error checking, so the program assumes that there are always start and end points in the map and a path inbetween. * short variable names I’m not a Haskell golfer, so I don’t know how much can be further saved (Edit: turned out to be quite a bunch). Performance: The Gauntlet runs in 9:21min on my 1,7GHz Core i5 from 2011. The City takes 7.2sec. (used -O1 with ghc, -O2 makes the program awfully slow) Tweaking options are the thickness of the bloated path. For the smaller maps distance 3 saves one or two steps, but The Gauntlet runs too long, so I stay with distance 2. The race starts always at the first (i.e. top left) yellow pixel, optimizing by hand should save an additional step. Rule conformity: „You can't use path-finding libraries.“ - I do, but the source is included. The A\* search functions are slightly heavily golfed versions of Cale Gibbard’s Data.Graph.AStar library (see <http://hackage.haskell.org/package/astar>). The City - 50 steps ![The City - 50 steps](https://i.stack.imgur.com/8GrTx.png) The Gauntlet - 722 steps ![The Gauntlet - 722 steps](https://i.stack.imgur.com/HpGCL.png) Ungolfed: ``` import System.Environment import Data.Maybe (fromJust) import Graphics.GD import qualified Data.Matrix as M import qualified Data.List as L import qualified Data.Set as S import qualified Data.Map as Map import qualified Data.PSQueue as PSQ main = do trPNG <- loadPngFile =<< fmap head getArgs (sX, sY) <- imageSize trPNG px <- mapM (flip getPixel trPNG) [(x,y) | y <- [0..sY-1],x <- [0..sX-1]] let tr = M.fromList sY sX (map (rgbaToTok . toRGBA) px) let rt = findRt tr let vrt = findVRt (head rt) (last rt) (bloat rt tr) tr let wayPt = map ((\(a,b)->(b-1,a-1)) . fst) vrt mapM (\(p1,p2) -> drawLine p1 p2 (rgb 255 255 255) trPNG >> setPixel p1 (rgb 0 0 255) trPNG) (zip wayPt (tail wayPt)) savePngFile "out1.png" trPNG print $ length vrt - 1 findVRt p1 p2 rt tr = (p1, (0,0)) : fromJust (aStar nghb (\_ _ -> 100) (\(pos,_) -> fromJust $ Map.lookup pos rt) ((==) p2 . fst) (p1, (0,0))) where nghb ((y,x), (vy,vx)) = S.fromList [(newp, (vy+dy,vx+dx)) | dy <- [-15 .. 15], let ady = abs dy, dx <- [-15+ady .. 15-ady], not $ dy==0 && dx == 0 && vy == 0 && vx == 0, let newp = (y+vy+dy,x+vx+dx), Map.member newp rt, all ((/=) 1 . (M.!) tr) (bresenham (y,x) newp)] bloat rt tr = foldr (\(p,h) -> Map.insert p h) Map.empty (zip (reverse $ f $ f rt) [0..]) where f = concatMap (n8 tr) rgbaToTok (r, g, b, _) | r+g+b == 0 = 3 | r==255 && g==255 && b==0 = 2 | r==g && r==b && 30 <= r && r <= 220 = 0 | otherwise = 1 findRt tr = s : fromJust (aStar nghb cost (const 1) ((==) 3 . (M.!) tr) s) where cost (y1,x1) (y2,x2) = if (x1==x2 || y1==y2) then 408 else 577 nghb = S.fromList . n8 tr s = head [(y,x) | y <- [1..M.nrows tr], x <- [1..M.ncols tr], M.getElem y x tr == 2] n8 tr p@(y,x) = filter ((/=) 1 . (M.!) tr) (n8' y x) where n8' y x | y==1 || x==1 || y == M.nrows tr || x == M.ncols tr = [p] | otherwise = [ (y-1,x-1), (y-1,x), (y-1,x+1), (y,x-1), (y,x+1), (y+1,x-1), (y+1,x), (y+1,x+1) ] bresenham start@(y0,x0) end@(y1,x1) = walk start (el `div` 2) where walk p@(y,x) err | p == end = [p] | err-es < 0 = p : walk (y+sdy,x+sdx) (err-es+el) | otherwise = p : walk (y+pdy,x+pdx) (err-es) dx = x1-x0; dy = y1-y0; adx = abs dx; ady = abs dy sdx = signum dx; sdy = signum dy (pdx,pdy,es,el) = if adx > ady then (sdx,0,ady,adx) else (0,sdy,adx,ady) data AStar a c = AStar { vi :: !(S.Set a), wa :: !(PSQ.PSQ a c), sc :: !(Map.Map a c), mH :: !(Map.Map a c), ca :: !(Map.Map a a), en :: !(Maybe a) } deriving Show aStarInit s = AStar S.empty (PSQ.singleton s 0) (Map.singleton s 0) Map.empty Map.empty Nothing aStar graph dist heur goal start = let s = runAStar graph dist heur goal start in case en s of Nothing -> Nothing Just e -> Just (reverse . takeWhile (not . (== start)) . iterate (ca s Map.!) $ e) runAStar graph dist heur goal start = aStar' (aStarInit start) where aStar' s = case PSQ.minView (wa s) of Nothing -> s Just (x PSQ.:-> _, w') -> if goal x then s { en = Just x } else aStar' $ L.foldl' (expand x) (s { wa = w', vi = S.insert x (vi s)}) (S.toList (graph x S.\\ vi s)) expand x s y = let vi = sc s Map.! x + dist x y in case PSQ.lookup y (wa s) of Nothing -> link x y vi (s { mH = Map.insert y (heur y) (mH s) }) Just _ -> if vi<sc s Map.! y then link x y vi s else s link x y v s = s { ca = Map.insert y x (ca s), sc = Map.insert y v (sc s), wa = PSQ.insert y (v + mH s Map.! y) (wa s) } ``` Golfed: ``` import System.Environment;import Graphics.GD;import Data.Matrix;import qualified Data.Set as S;import qualified Data.Map as J;import qualified Data.PSQueue as Q j(Just x)=x;e(y,x)=(x-1,y-1);u=signum;q=J.empty;m=reverse;n=Nothing;z=255;s=abs;t=1<2;f(a,b)(c,d)|b==d||a==c=2|t=3;rT(r,g,b,_)|r+g+b==0=3|r==z&&g==z&&b==0=2|r==g&&r==b&&30<=r&&r<=220=0|t=5 main=do i:_<-getArgs;t<-loadPngFile i;(a,b)<-imageSize t;p<-mapM(flip getPixel t)[(x,y)|y<-[0..b-1],x<-[0..a-1]];let r=fromList b a$map(rT.toRGBA)p;s:_=[(y,x)|y<-[1..b],x<-[1..a],getElem y x r==2];c p@(y,x)=filter((<5).(!)r)$if y==1||x==1||y==b||x==a then[p]else[(a,b)|a<-[y-1..y+1],b<-[x-1..x+1],a/=y||b/=x];y=s:j(aS(S.fromList.c)f(\_->1)((==3).(!)r)s);l=concatMap c;w=map(e.fst)$fV(head y)(last y)(foldr(\(p,h)->J.insert p h)q$zip(m$l$l y)[0..])r mapM(\(c,d)->drawLine c d(rgb z z z)t>>setPixel c(rgb 0 0 z)t)$zip w$tail w;savePngFile"o.png"t fV c d r t=(c,(0,0)):j(aS l(\_ _->99)(\(q,_)->j$J.lookup q r)((==d).fst)(c,(0,0)))where l((y,x),(a,b))=S.fromList[(w,(a+c,b+d))|c<-[-15..15],d<-[s c-15..15-s c],any(/=0)[a,b,c,d],let w=(y+a+c,x+b+d),J.member w r,all((<5).(!)t)$br(y,x)w] br q@(i,j)r@(k,l)=w q$f`div`2where w p@(y,x)e|p==r=[p]|e-o<0=p:w(y+g,x+h)(e-o+f)|t=p:w(y+m,x+n)(e-o);a=s$l-j;b=s$k-i;h=u$l-j;g=u$k-i;(n,m,o,f)|a>b=(h,0,b,a)|t=(0,g,a,b) data A a c=A{v::S.Set a,w::Q.PSQ a c,k::J.Map a c,mH::J.Map a c,ca::J.Map a a,en::Maybe a}deriving Show aS g d h o u=b$en s where b Nothing=n;b(Just e)=Just(m.takeWhile(/=u).iterate(ca s J.!)$e);s=l$A S.empty(Q.singleton u 0)(J.singleton u 0)q q n;i x y v s=s{ca=J.insert y x$ca s,k=J.insert y v$k s,w=Q.insert y(v+mH s J.!y)$w s};l s=b$Q.minView$w s where b Nothing=s;b(Just(x Q.:->_,w'))|o x=s{en=Just x}|t=l$foldl(r x)(s{w=w',v=S.insert x$v s})$S.toList$g x S.\\v s;r x s y=b$Q.lookup y$w s where v=k s J.!x+d x y;b Nothing=i x y v$s{mH=J.insert y(h y)$mH s};b(Just _)|v<k s J.!y=i x y v s|t=s ``` ## Tutu siblings -TS#1 - (1764+43 = 2194) Edit: TS#1 now separate answer. Edit II: The path for The City is ``` [(6,7),(21,7),(49,5),(92,3),(126,4),(145,5),(149,6),(153,22),(163,47),(180,64), (191,73),(191,86),(185,107),(177,122),(175,130),(187,137),(211,147),(237,162), (254,171),(277,171),(299,175),(321,194),(345,220),(364,237),(370,252),(365,270), (360,276),(368,284),(387,296),(414,315),(438,330),(463,331),(484,321),(491,311), (498,316),(508,333),(524,354),(525,375),(519,404),(511,424),(508,434),(513,437), (533,440),(559,444),(580,458),(591,468),(591,482),(591,511),(598,532),(605,539), (606,537)] ``` In The Gauntlet Tutu moves as follows ``` [(99,143),(114,143),(137,150),(150,161),(149,173),(145,180),(141,197),(138,223), (135,234),(143,241),(166,248),(186,250),(192,251),(192,261),(192,279),(195,285), (209,287),(232,284),(248,273),(257,261),(272,256),(279,255),(284,245),(294,243), (309,231),(330,226),(354,233),(380,253),(400,265),(421,271),(436,268),(438,266), (440,269),(441,277),(450,278),(470,276),(477,276),(478,285),(481,307),(490,330), (486,352),(471,370),(449,384),(435,391),(433,401),(446,411),(462,430),(464,450), (459,477),(454,493),(457,514),(462,522),(472,523),(479,529),(491,531),(493,538), (496,547),(503,546),(516,545),(519,549),(524,566),(531,575),(531,581),(535,576), (538,557),(541,523),(545,475),(551,414),(559,342),(565,282),(570,236),(574,204), (575,184),(574,177),(572,179),(568,174),(568,158),(569,144),(572,143),(578,154), (585,160),(588,155),(593,140),(598,140),(605,153),(610,156),(611,170),(611,182), (608,182),(598,175),(594,171),(590,176),(587,195),(589,224),(593,266),(599,321), (605,376),(609,418),(612,446),(610,465),(615,478),(608,494),(605,521),(611,542), (618,549),(622,551),(621,563),(611,572),(614,581),(623,581),(630,581),(630,573), (636,556),(639,551),(642,531),(647,520),(640,511),(637,491),(639,461),(641,416), (643,356),(647,289),(650,235),(652,195),(647,163),(645,143),(645,136),(653,136), (670,138),(673,139),(676,155),(679,175),(681,181),(669,188),(662,194),(662,208), (665,234),(669,274),(674,328),(681,395),(687,457),(692,505),(696,540),(700,560), (703,566),(706,557),(707,535),(708,498),(711,448),(716,385),(720,325),(723,278), (726,246),(729,229),(732,227),(733,238),(733,263),(733,303),(733,358),(733,428), (733,483),(733,523),(732,549),(731,560),(728,558),(726,565),(726,575),(721,575), (720,586),(720,592),(716,594),(715,608),(715,619),(711,619),(692,619),(658,619), (609,619),(545,619),(466,619),(372,619),(285,619),(213,619),(155,619),(112,619), (84,619),(70,618),(70,616),(70,599),(70,567),(70,520),(70,458),(70,381), (70,300),(70,234),(70,183),(70,147),(70,126),(71,119),(80,119),(104,119), (143,119),(197,119),(266,119),(350,119),(449,119),(563,119),(681,120),(784,121), (873,121),(947,121),(1006,121),(1050,121),(1079,121),(1093,121),(1093,122), (1086,131),(1069,145),(1059,151),(1040,151),(1006,151),(973,150),(955,149), (950,150),(956,155),(977,160),(994,175),(1003,183),(1003,197),(993,214), (987,220),(993,223),(1011,223),(1044,223),(1079,229),(1104,240),(1124,242), (1134,239),(1134,231),(1134,221),(1139,218),(1156,218),(1177,217),(1183,216), (1191,202),(1208,182),(1231,154),(1249,135),(1259,123),(1264,121),(1264,129), (1264,152),(1264,190),(1264,243),(1264,311),(1264,393),(1264,460),(1264,512), (1264,550),(1264,573),(1263,582),(1256,582),(1234,582),(1197,582),(1160,575), (1132,562),(1118,548),(1113,538),(1107,541),(1099,549),(1102,561),(1113,570), (1110,578),(1095,583),(1073,581),(1066,579),(1060,566),(1063,559),(1075,554), (1072,549),(1065,542),(1051,539),(1043,528),(1023,520),(990,511),(970,500), (953,501),(935,516),(911,534),(899,551),(891,573),(883,580),(867,581),(859,575), (858,571),(843,566),(830,553),(832,540),(828,527),(819,520),(825,513),(839,506), (842,495),(843,474),(844,468),(854,468),(877,467),(891,460),(895,452),(901,452), (906,447),(909,443),(909,441),(915,435),(912,430),(914,429),(908,423),(904,421), (899,418),(893,417),(879,409),(854,400),(842,390),(842,377),(839,362),(836,362), (820,360),(812,352),(812,337),(812,307),(814,288),(815,282),(827,280),(834,284), (850,282),(873,277),(889,280),(891,284),(891,301),(897,320),(903,324),(916,320), (925,310),(935,314),(953,325),(967,337),(976,345),(981,346),(986,362),(999,378), (1006,385),(1007,387),(1008,387),(1015,382),(1017,382),(1018,381),(1022,386), (1021,401),(1008,413),(1009,425),(1014,426),(1031,425),(1038,429),(1047,425), (1053,429),(1067,426),(1076,425),(1090,427),(1099,424),(1113,426),(1134,427), (1147,431),(1150,430),(1152,437),(1147,438),(1128,438),(1105,443),(1093,450), (1089,453),(1085,449),(1075,452),(1064,460),(1055,458),(1052,462),(1049,460), (1042,464),(1025,463),(1015,463),(1010,470),(1013,471),(1021,472),(1027,476), (1033,477),(1042,484),(1052,480),(1059,486),(1076,487),(1099,497),(1134,510), (1169,523),(1191,535),(1205,540),(1210,539),(1210,528),(1210,502),(1210,461), (1209,409),(1208,372),(1207,349),(1206,341),(1192,335),(1165,327),(1132,310), (1084,293),(1045,273),(997,256),(961,240),(934,229),(922,218),(919,201), (917,197),(906,199),(892,212),(876,212),(845,212),(809,212),(781,219),(768,226), (768,235),(768,259),(768,298),(768,352),(768,421),(769,489),(769,543),(769,582), (769,606),(769,615),(775,615),(796,615),(832,615),(883,615),(949,615), (1030,615),(1110,615),(1175,615),(1225,615),(1261,614),(1282,613),(1288,612), (1296,598),(1296,577),(1296,541),(1296,490),(1296,424),(1296,343),(1296,264), (1296,200),(1296,151),(1296,116),(1296,96),(1295,90),(1285,90),(1260,90), (1220,90),(1165,90),(1095,90),(1010,90),(920,90),(844,90),(783,90),(737,90), (706,90),(690,90),(688,89),(689,86),(681,78),(671,82),(663,90),(648,90), (618,90),(573,90),(517,90),(476,90),(450,90),(438,89),(439,86),(431,78), (421,82),(413,90),(398,90),(381,88),(369,78),(357,83),(353,90),(341,90), (314,90),(297,88),(287,78),(277,82),(269,90),(254,90),(224,90),(179,90), (123,90),(82,90),(56,90),(43,92),(43,96),(43,115),(43,149),(43,198),(43,262), (43,341),(43,428),(43,500),(43,557),(43,599),(44,627),(45,640),(49,641), (67,641),(100,641),(148,641),(211,641),(289,641),(382,641),(490,641),(613,641), (750,641),(872,641),(979,641),(1071,641),(1148,641),(1212,640),(1261,639), (1295,638),(1315,636),(1321,633),(1321,621),(1321,594),(1321,552),(1321,495), (1321,423),(1321,336),(1321,254),(1321,187),(1321,135),(1321,98),(1321,75), (1320,66),(1313,66),(1291,66),(1254,66),(1207,67),(1175,68),(1157,68),(1154,68), (1154,75),(1146,75),(1123,75),(1102,74),(1096,73),(1096,69),(1091,66),(1074,66), (1042,66),(1007,66),(986,65),(980,64),(980,60),(975,57),(958,57),(926,57), (891,58),(871,59),(866,60),(865,66),(855,66),(830,66),(790,66),(735,66), (667,66),(614,66),(575,66),(550,65),(540,64),(540,60),(535,57),(518,57), (489,58),(474,60),(474,62),(472,66),(459,66),(431,66),(388,66),(330,66), (269,66),(223,66),(191,66),(174,66),(171,65),(168,56),(158,55),(150,61), (149,66),(138,66),(112,66),(98,63),(95,57),(83,57),(65,59),(61,62),(59,66), (46,66),(25,67),(18,69),(18,79),(18,104),(18,144),(18,199),(18,269),(18,354), (18,441),(18,513),(18,570),(18,612),(18,639),(19,652),(26,656),(38,663), (58,663),(93,663),(143,663),(208,663),(288,663),(383,663),(493,663),(618,663), (758,663),(884,663),(995,663),(1091,663),(1172,663),(1239,663),(1291,663), (1328,663),(1350,663),(1358,662),(1361,651),(1376,637),(1378,621),(1374,597), (1378,574),(1378,541),(1375,519),(1383,501),(1376,483),(1370,478),(1370,464), (1373,438),(1379,400),(1379,366),(1369,337),(1369,303),(1369,272),(1368,255), (1382,238),(1381,221),(1371,209),(1375,196),(1380,170),(1374,143),(1367,129), (1372,112),(1373,85),(1365,64),(1358,57),(1356,41),(1353,39),(1350,41), (1346,37),(1336,36),(1333,32),(1317,30),(1288,30),(1244,30),(1185,30),(1141,30), (1102,22),(1057,22),(1026,21),(1005,23),(993,21),(988,25),(975,22),(972,24), (959,21),(943,24),(937,29),(920,30),(889,30),(843,30),(788,30),(747,30), (706,39),(664,36),(629,38),(591,34),(559,34),(538,30),(506,30),(465,30), (431,22),(391,23),(356,22),(328,23),(308,30),(280,30),(237,30),(179,30), (106,30),(30,28)] ``` [Answer] # TS#1 - Haskell - 1699 + 430 = 2129 Tutu sibling #1 Very much the same as the original Tutu racer, except it uses a thickness of 3 for the bloated path and the 2nd A\* (speed-pos space) goes with a constant heuristic of `1`. The input picture is not passed as a command line argument anymore, it must be named `i`. The name of the output picture is `o`. The program prints the calculated points on the path as a list of x,y pairs (original output is a single line): ``` [(6,7),(20,6),(49,5),(92,5),(124,4),(141,3),(148,7),(155,26),(172,49), (189,70),(191,91),(179,111),(174,124),(184,137),(209,150),(244,168), (279,171),(302,176),(325,196),(350,221),(367,239),(369,257),(360,272), (363,284),(381,296),(408,314),(433,329),(458,329),(480,318),(492,312), (504,321),(519,341),(526,364),(523,392),(514,416),(507,427),(511,435), (529,442),(558,445),(581,456),(592,470),(592,488),(592,513),(606,537)] ``` I could save a lot of bytes when I start to remove all the map and set data structures and replace them with simple linked lists. Just the two import statements would save 60 bytes. However, it would slow down the program so that waiting for a result is pure pain. This versions takes over 45min for The City, compared to the 7s of the original. I’ll stop here trading bytes for executing speed. ``` import Codec.Picture import Codec.Picture.RGBA8 import Codec.Picture.Canvas import qualified Data.Map as M import qualified Data.Set as S import qualified Data.PSQueue as Q m(a,b)(c,d)|a==c||b==d=2|t=3;n=Nothing;q=PixelRGBA8;s=abs;t=1<2;u=signum;z=255;fl=S.fromList;(#)=M.insert main=do i<-readImageRGBA8"i";let(Right c)=imageToCanvas i;j=canvasWidth c-1;gY=canvasHeight c-1;v(x,y)|all(==0)[r,g,b]=3|r+g==510&&b==0=2|r==g&&r==b&&29<r&&r<221=0|t=1 where(PixelRGBA8 r g b _)=getColor x y c let s':_=[(x,y)|x<-[0..j],y<-[0..gY],v(x,y)==2];n8 p@(x,y)=filter((/=1).v)$if y*x==0||y==gY||x==j then[p]else[(a,b)|a<-[x-1..x+1],b<-[y-1..y+1],a/=x||b/=y];r=s':aS(fl.n8)m((==3).v)s';f=concatMap n8;p=head r;w=map fst$(p,(0,0)):aS(\((a,b),(h,i))->fl[(e,(h+j,i+k))|j<-[-15..15],k<-[s j-15..15-s j],not$all(==0)[j,k,h,i],let e=(a+h+j,b+i+k),S.member e(fl$f$f$f r),all((/=1).v)(br(a,b)e)])(\_ _->99)((==last r).fst)(p,(0,0)) writePng"o"$canvasToImage$foldl(\e((a,b),(c,d))->setColor a b(q 0 0 z z)$drawLine a b c d(q z z z z)e)c(zip w(tail w));print w br q@(i,j)r@(k,l)=w q$f`div`2where w p@(y,x)e|p==r=[p]|e-o<0=p:w(y+g,x+h)(e-o+f)|t=p:w(y+m,x+n)(e-o);a=s$l-j;b=s$k-i;h=u$l-j;g=u$k-i;(n,m,o,f)|a>b=(h,0,b,a)|t=(0,g,a,b) data A a c=A{a::S.Set a,h::Q.PSQ a c,k::M.Map a c,p::M.Map a a,w::Maybe a} aS g d o u=b$w s where b(Just j)=(reverse$takeWhile(/=u)$iterate(p s M.!)j);s=l$A S.empty(Q.singleton u 0)(M.singleton u 0)M.empty n;i x y v s=s{p=y#x$p s,k=y#v$k s,h=Q.insert y(v+1)$h s};l s=b$Q.minView$h s where b(Just(x Q.:->_,w'))|o x=s{w=Just x}|t=l$foldl(r x)(s{h=w',a=S.insert x(a s)})$S.toList$g x S.\\a s;b _=s;r x s y=b$Q.lookup y$h s where v=k s M.!x+d x y;b Nothing=i x y v s;b _|v<k s M.!y=i x y v s|t=s ``` The code needs the -XNoMonomorphismRestriction flag to compile. The City - TS#1 - 43 steps ![TS#1 - 43 steps](https://i.stack.imgur.com/aNccI.png) [Answer] # Star crossed racer - PHP - 4083+440 = way too heavy Ok, after 3 weeks without an Internet connection (that's what happens when one of the most ferocious competitor of your provider happens to be in charge of the building patch bay, or so it does in Paris, France at least) I can at last publish my next attempt. This time I used the A\* algorithm, and a more efficient waypoint distribution strategy. As an added bonus, I wrote some kind of PHP cruncher to address the golfing part of the challenge. And now that the solver works on all proposed maps, the line tracing bug has been fixed. No more wall clipping (though wall grazing still occurs, as it should :)). ## running the code give the code whatever name you fancy (`runner.php` for instance), then invoke it like so: ``` php runner.php track.png ``` After sitting silent for quite a while, it should produce a `_track.png` output showing the solution. As you can see on the output pictures, the code is ***really*** slow. You've been warned. Of course my own private version is full of traces and produces nice representations of various informations (including a periodic picture showing the A\* progress to help killing time), but there is a price to pay for golfing... ## golfed code ``` <?php define("_",15);define("a",1e3);class _{function _($a=0,$_=0){$this->a=$a;$this->_=$_;}function b(){return sqrt($this->a*$this->a+$this->_*$this->_);}function a(){$_=$this->b();if($_==0)$_=1;return new _($this->a/$_,$this->_/$_);}}class c{static$_=0;function c($_,$a,$b){$this->c=$b;$this->a=++c::$_;$this->_=new _($_,$a);a::$a[$_][$a]=$this;}function _($_){return(isset($this->b[$_->a]))?$this->b[$_->a]:$this->b[$_->a]=$_->b[$this->a]=a($_->_->a,$_->_->_,$this->_->a,$this->_->_);}}define("c",8/_);define("b",2/a);class d{function d($a,$b,$c=0,$d=0,$_=null){$this->a=$a;$this->_=$b;$this->f=$c;$this->e=$d;$this->d=$_;$this->b=$_==null?0:$_->b+a;$this->c=floor((sqrt(1+c*abs(a::$_[$a][$b]))-1)/b)-a;}}function a($c,$b,$g,$f){$e=$g-$c;$d=$f-$b;$_=2*max(abs($e),abs($d));if($_==0)return 1;$c+=.5;$b+=.5;for($a=1;$a<=$_;$a++)if(!isset(a::$_[$c+$a/$_*$e][$b+$a/$_*$d]))return 0;return 1;}class b{static$a,$_;function _($l,$_,$k){$g=log(.5)/log($l/$_);for($a=-$_;$a<=$_;$a++)for($b=-$_;$b<=$_;$b++){$d=sqrt($a*$a+$b*$b);if($d>=$_)continue;$j=pow(sin(M_PI*pow($d/$_,$g)),$k);$c=new _($a,$b);$i=$c->a();$c->b=$d;$c->d=$j*$i->a;$c->c=$j*$i->_;$h[]=$c;}usort($h,function($b,$a){$_=$b->b-$a->b;return($_>0)?1:(($_<0)?-1:0);});foreach($h as$e)b::$a[$e->b][]=$e;for($a=-$_;$a<=$_;$a++)for($b=-$_;$b<=$_;$b++){$e=new _($a,$b);$d=sqrt($a*$a+$b*$b);for($f=$_;$f>=$d;$f--)b::$_[$f][]=$e;}foreach(b::$_ as$g=>$m)usort(b::$_[$g],function($b,$a){$_=$b->b()-$a->b();return($_<0)?-1:(($_>0)?1:0);});}}b::_(2.5,6,8);class a{static$a,$_;static function _($S){$k=imagecreatefrompng($S);for($a=0;$a!=imagesx($k);$a++)for($_=0;$_!=imagesy($k);$_++){$n=0;$o=imagecolorat($k,$a,$_);if($o==0){$d_[]=new _($a,$_);$n=1;}else if($o==0xFFFF00){$e_[]=new _($a,$_);$n=2;}else{$m=($o>>16)&0xFF;$c_=($o>>8)&0xFF;$a_=$o&0xFF;if($m==$c_&&$m==$a_&&$m>=30&&$m<=220)$n=3;}if($n){$Z[$a][$_]=1;if($n!=3)$b_[]=new c($a,$_,$n);}}for($a=-_;$a<=_;$a++)for($_=-_;$_<=_;$_++)if(abs($a)+abs($_)<=_)$f_[]=new _($a,$_);$l_=array(new _(-1,0),new _(1,0),new _(0,-1),new _(0,1));foreach($d_ as$v){$c[]=new _($v->a,$v->_);a::$_[$v->a][$v->_]=0;}while(count($c)){$t=array_shift($c);$g_=a::$_[$t->a][$t->_]+1;foreach($l_ as$e){$f=$t->a+$e->a;$j=$t->_+$e->_;if(!isset($Z[$f][$j]))continue;if(isset(a::$_[$f][$j]))continue;a::$_[$f][$j]=$g_;$c[]=new _($f,$j);}}foreach(a::$_ as$a=>$g)foreach($g as$_=>$q){$i=0;$E=$H=0;foreach(b::$a as$n_=>$J){foreach($J as$b){if(!isset(a::$_[$a+$b->a][$_+$b->_])){$E+=$b->d;$H+=$b->c;$i++;}}if($i!=0){$E/=$i;$H/=$i;break;}}$W[$a][$_]=new _($E,$H);}foreach(a::$_ as$a=>$g)foreach($g as$_=>$q){$T=$W[$a][$_];$u=$T->a();$R=0;$i=0;foreach(b::$_[1]as$e){@$b=$W[$a+$e->a][$_+$e->_];if(!$b)continue;$V=$b->a();$d=$e->a();$R-=($u->a*$V->_-$u->_*$V->a)*($u->a*$d->_-$u->_*$d->a);$i++;}$p[$a][$_]=(12*$R/$i+1)*$T->b();}$m_=1;$Y=6;$x=0;foreach($p as$a=>$g)foreach($g as$_=>$q)$x=max($x,$q);$h_=($m_-$Y)/$x;foreach($p as$a=>$g)foreach($g as$_=>$q)$X[($Y+$h_*max($q,0))*1e5][]=new _($a,$_);ksort($X);foreach($X as$m=>$J)foreach($J as$b){$a=$b->a;$_=$b->_;if(!isset($p[$a][$_]))continue;$b_[]=new c($a,$_,3);unset($p[$a][$_]);$k_=0;foreach(b::$_[$m/1e5]as$U){$f=$a+$U->a;$j=$_+$U->_;if(a($a,$_,$f,$j))unset($p[$f][$j]);else if(++$k_==2)break;}}foreach($e_ as$s){$e=new d($s->a,$s->_);$c[$e->b+$e->c][]=$e;$y[$s->a." ".$s->_." 0 0"]=$e;}ksort($c);while(count($c)){reset($c);$z=key($c);$r=array_shift($c[$z]);if(empty($c[$z]))unset($c[$z]);$A=$r->a;$C=$r->_;$M=$r->f;$O=$r->e;$i_=a::$a[$A][$C];$l="$A $C $M $O";unset($y[$l]);$j_[$l]=1;foreach($f_ as$P){$B=$M+$P->a;$D=$O+$P->_;$G=$A+$B;$F=$C+$D;@$I=a::$a[$G][$F];if(!$I)continue;$l="$G $F $B $D";if(@$j_[$l]||@$y[$l])continue;if(!$I->_($i_))continue;$d=new d($G,$F,$B,$D,$r);$b=$d->b+$d->c;$__=!isset($c[$b]);$c[$b][]=$d;if($__)ksort($c);$y[$l]=$d;if($I->c==1){for($h=array();$d!=null;$d=$d->d)array_unshift($h,$d);$N=$h[0]->a;$K=$h[0]->_;for($w=1;$w!=count($h);$w++){$L=$h[$w]->a;$Q=$h[$w]->_;imageline($k,$N,$K,$L,$Q,0xFFFFFF);$N=$L;$K=$Q;}foreach($h as$b)imagesetpixel($k,$b->a,$b->_,0xFF);imagepng($k,"_".$S);return;}}}}}ini_set("memory_limit","3G");a::_($argv[1]); ``` ## ungolfed version ``` <?php define ("ACCEL_MAX", 15); // maximal acceleration value define ("MOVE_UNIT", 1000); // heuristic distance to goal precision class Point { function __construct ($x=0, $y=0) { $this->x = $x; $this->y = $y; } function norm () { return sqrt ($this->x*$this->x + $this->y*$this->y); } function normalized() { $n=$this->norm(); if ($n == 0) $n=1; return new Point ($this->x / $n, $this->y / $n); } } class Waypoint { static $id = 0; function __construct ($x, $y, $type) { // create waypoint $this->type = $type; $this->id = ++self::$id; $this->center = new Point ($x, $y); // update waypoint lookup map Map::$waypoint_lookup[$x][$y] = $this; } function can_reach ($target) { return (isset($this->reachable[$target->id])) ? $this->reachable[$target->id] : $this->reachable[$target->id] = $target->reachable[$this->id] = on_track ($target->center->x, $target->center->y, $this->center->x, $this->center->y); } } define ("L", 8/ACCEL_MAX); define ("M", 2/MOVE_UNIT); class Node { function __construct ($x, $y, $speedx=0, $speedy=0, $parent=null) { $this->x = $x; $this->y = $y; $this->speedx = $speedx; $this->speedy = $speedy; $this->parent = $parent; // previous moves $this->moves = $parent == null ? 0 : $parent->moves+MOVE_UNIT; // remaining moves heuristic estimation $this->dist = floor((sqrt (1+L*abs(Map::$dist_to_goal[$x][$y])) - 1)/M) - MOVE_UNIT; } } function on_track ($ox, $oy, $ex, $ey) { $sx = $ex - $ox; $sy = $ey - $oy; $range = 2*max (abs ($sx), abs ($sy)); if ($range == 0) return 1; $ox+=.5; $oy+=.5; for ($s = 1 ; $s <= $range ; $s++) if (!isset (Map::$dist_to_goal[$ox + $s/$range*$sx][$oy + $s/$range*$sy])) return 0; return 1; } class Border { static $circle, $area; function init ($dopt, $dmax, $erf) { $k = log (.5)/log($dopt/$dmax); for ($x = -$dmax ; $x <= $dmax ; $x++) for ($y = -$dmax ; $y <= $dmax ; $y++) { $d = sqrt ($x*$x+$y*$y); if ($d >= $dmax) continue; $i = pow(sin (M_PI*pow($d/$dmax,$k)),$erf); // a function that will produce a kind of asymetric gaussian $pt = new Point($x,$y); $pn = $pt->normalized(); $pt->d = $d; $pt->ix = $i * $pn->x; $pt->iy = $i * $pn->y; $points[] = $pt; } usort ($points, function ($a,$b) { $d = $a->d - $b->d; return ($d > 0) ? 1 : (($d < 0) ? -1 : 0); }); foreach ($points as $p) self::$circle[$p->d][] = $p; for ($x = -$dmax ; $x <= $dmax ; $x++) for ($y = -$dmax ; $y <= $dmax ; $y++) { $p = new Point ($x, $y); $d = sqrt ($x*$x+$y*$y); for ($r = $dmax ; $r >= $d ; $r--) self::$area[$r][] = $p; } foreach (self::$area as $k=>$a) usort (self::$area[$k], function ($a,$b) { $d = $a->norm()-$b->norm(); return ($d < 0) ? -1 : (($d > 0) ? 1 : 0); }); } } Border::init(2.5,6,8); class Map { static $waypoint_lookup, // retrieve waypoint from a position $dist_to_goal; // upper bound of distance to closest goal for each track point // also used to check if a point is on track /* const NONE = 0; // terrain types const GOAL = 1; const START = 2; const TRACK = 3; */ static function solve ($filename) { // read map definition $img = imagecreatefrompng ($filename);// or die ("could not read $filename"); $img_dx = imagesx ($img); $img_dy = imagesy ($img); // extract track pixels for ($x = 0 ; $x != $img_dx ; $x++) for ($y = 0 ; $y != $img_dy ; $y++) { $type = 0 /*Map::NONE*/; $color = imagecolorat ($img, $x, $y); if ($color == 0) { $goals [] = new Point ($x, $y); $type = 1 /*Map::GOAL*/; } else if ($color == 0xFFFF00) { $starts[] = new Point ($x, $y); $type = 2 /*Map::START*/; } else { $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; if ($r == $g && $r == $b && $r >= 30 && $r <= 220) $type = 3 /*Map::TRACK*/; } if ($type /* != Map::NONE */) { $track[$x][$y] = 1; // mark all track points if ($type != 3 /*Map::TRACK*/) $waypoints[] = new Waypoint ($x, $y, $type); // add start and goal positions as waypoints } } // compute possible acceleration values for ($x = -ACCEL_MAX ; $x <= ACCEL_MAX ; $x++) for ($y = -ACCEL_MAX ; $y <= ACCEL_MAX ; $y++) if (abs ($x) + abs ($y) <= ACCEL_MAX) $acceleration[] = new Point ($x, $y); // compute goal distance $neighbours = array (new Point (-1, 0), new Point (1, 0), new Point (0, -1), new Point (0, 1)); foreach ($goals as $goal) { $border[] = new Point ($goal->x, $goal->y); Map::$dist_to_goal[$goal->x][$goal->y] = 0; } while (count ($border)) { $pos = array_shift ($border); $dist = Map::$dist_to_goal[$pos->x][$pos->y] + 1; foreach ($neighbours as $n) { $nx = $pos->x + $n->x; $ny = $pos->y + $n->y; if (!isset ($track[$nx][$ny])) continue; if (isset (Map::$dist_to_goal[$nx][$ny])) continue; Map::$dist_to_goal[$nx][$ny] = $dist; $border[] = new Point ($nx, $ny); } } // compute wall distance vector field foreach (self::$dist_to_goal as $x=>$col) foreach ($col as $y=>$c) { $num = 0; $ix = $iy = 0; foreach (Border::$circle as $d=>$points) { foreach ($points as $p) { if (!isset (Map::$dist_to_goal[$x+$p->x][$y+$p->y])) { $ix += $p->ix; $iy += $p->iy; $num++; } } if ($num != 0) { $ix /= $num; $iy /= $num; break; } } $wall_vector[$x][$y] = new Point ($ix, $iy); } // compute local curvature and deduce desired waypoint density foreach (self::$dist_to_goal as $x=>$col) foreach ($col as $y=>$c) { $o = $wall_vector[$x][$y]; $oo = $o->normalized(); $curvature = 0; $num = 0; foreach (Border::$area[1] as $n) { @$p = $wall_vector[$x+$n->x][$y+$n->y]; if (!$p) continue; $pp = $p->normalized(); $nn = $n->normalized(); $curvature -= ($oo->x*$pp->y-$oo->y*$pp->x) * ($oo->x*$nn->y-$oo->y*$nn->x); $num++; } $waypoint_density[$x][$y] = (12*$curvature/$num + 1) * $o->norm(); // a wierd mix of curvature and wall distance } // compute track waypoints $rmin = 1; $rmax = 6; $c_max = 0; foreach ($waypoint_density as $x=>$col) foreach ($col as $y=>$c) $c_max = max ($c_max, $c); $ra = ($rmin-$rmax)/$c_max; foreach ($waypoint_density as $x=>$col) foreach ($col as $y=>$c) $placement[($rmax + $ra * max ($c, 0))*1e5][] = new Point ($x, $y); ksort($placement); //var_dump($placement);exit(0); foreach ($placement as $r=>$points) foreach ($points as $p) { $x = $p->x; $y = $p->y; if (!isset ($waypoint_density[$x][$y])) continue; $waypoints[] = new Waypoint ($x, $y, 3 /*Map::TRACK*/); unset ($waypoint_density[$x][$y]); $out=0; foreach (Border::$area[$r/1e5] as $delta) { $nx = $x+$delta->x; $ny = $y+$delta->y; if (on_track ($x, $y, $nx, $ny)) unset ($waypoint_density[$nx][$ny]); else if (++$out == 2) break; } } // unleash the mighty A* //$begining=microtime(true); foreach ($starts as $start) { $n = new Node ($start->x, $start->y); $border[$n->moves+$n->dist][] = $n; $open[$start->x." ".$start->y." 0 0"] = $n; } ksort ($border); while (count ($border)) { // get one of the most prioritary nodes reset ($border); $p_list = key ($border); $node = array_shift ($border[$p_list]); if (empty ($border[$p_list])) unset ($border[$p_list]); $px = $node->x; $py = $node->y; $vx = $node->speedx; $vy = $node->speedy; $current = Map::$waypoint_lookup[$px][$py]; // move node from open to closed list $signature = "$px $py $vx $vy"; unset ($open[$signature]); $closed[$signature] = 1; // try all possible accelerations foreach ($acceleration as $a) { $nvx = $vx + $a->x; $nvy = $vy + $a->y; $npx = $px + $nvx; $npy = $py + $nvy; // select waypoints within reach @$waypoint = Map::$waypoint_lookup[$npx][$npy]; if (!$waypoint) continue; // skip already know nodes $signature = "$npx $npy $nvx $nvy"; if (@$closed[$signature] || @$open[$signature]) continue; // check track geometry if (!$waypoint->can_reach ($current)) continue; // insert new node into priority list $nn = new Node ($npx, $npy, $nvx, $nvy, $node); $p = $nn->moves+$nn->dist; $resort = !isset($border[$p]); $border[$p][] = $nn; if ($resort) ksort ($border); $open[$signature] = $nn; // check termination if ($waypoint->type == 1 /*Map::GOAL*/) { for ($path=array() ; $nn != null ; $nn = $nn->parent) array_unshift ($path, $nn); $ox = $path[0]->x; $oy = $path[0]->y; for ($i = 1 ; $i != count($path) ; $i++) { $ex = $path[$i]->x; $ey = $path[$i]->y; imageline ($img, $ox, $oy, $ex, $ey, 0xFFFFFF); $ox = $ex; $oy = $ey; } foreach ($path as $p) imagefilledellipse ($img, $p->x, $p->y, 2, 2, 0xFF); imagepng ($img, "_".$filename); //echo (count($path)-1)." moves, ".count($waypoints)." waypoints, ".count($closed)."+".count($open)." nodes, ".(round((microtime(true)-$begining)*100)/100)."s, ".round(memory_get_usage(true)/1024)."K"; return; } } } } } ini_set("memory_limit","2G"); // just in case... Map::solve ($argv[1]); ?> ``` ## Results The pics are produced by a richer version that outputs the exact same solution with some statistics at the bottom (and draws the path with antialiasing). The city map is a pretty good example of why position-based algorithms are bound to find subpar results in many cases: shorter does not always mean faster. ![city](https://i.stack.imgur.com/w07gM.png) ![track](https://i.stack.imgur.com/x5Eix.png) ![obstacles](https://i.stack.imgur.com/jf40h.png) ![nightmare](https://i.stack.imgur.com/TFdUx.png) (672 moves if you don't want to zoom) ## A\* To my surprise, A\* performs rather well on the position-speed space. Better than BFS, at any rate. I had to sweat quite a bit to produce a working heuristic distance estimate, though. I had to optimize it somewhat too, since the number of possible states is huge (a few millions) compared with a position-only variant, which again requires more code. The lower bound chosen for number of moves necessary to reach a goal from a given position is simply the time needed to cover the distance to the nearest goal *in a straight line with zero initial speed*. Of course, the straight line path will usually lead directly into a wall, but this is about the same problem as using the euclidian straight distance for space-only A\* searchs. Just like the euclidian distance for space-only variants, the main advantage of this metric, besides being acceptable to use the most efficient A\* variant (with closed nodes), is to require very little topological analysis of the track. Given a maximal acceleration **A**, the number **n** of moves needed to cover a distance **d** is the smallest integer that satisfies the relation: **d <= A n(n+1)/2** Solving this for **n** gives an estimate of the remaining distance. To compute this, a map of distance to nearest goal is built, using a flood-fill algorithm seeded with goal positions. It has the pleasant side effect of eliminating track points from where no goal can be reached (as it happens in some areas of the nightmare track). The number of moves is computed as a floating point value, so that nodes nearer to the goal can be further discriminated. ## Waypoints As in my previous attempt, the idea is to reduce the number of track points to an as small as possible subsample of waypoints. The trick is to try and pick the most "useful" positions on the track. The heuristic starts with a regular repartition over the whole track, but increases the density in two types of areas : 1. the rim of the track, i.e. lanes running 1 or 2 pixels away from walls 2. zones of high curvature, i.e. the inner rim of sharp bends. Here is an example. High density areas are in red, low density in green. Blue pixels are the selected waypoints. Notice the clusters of waypoints on sharp bends (among a lot of useless blotches on slanted curves, due to insufficient filtering). ![waypoints density and placement](https://i.stack.imgur.com/luCuE.png) To compute lanes positions, the entire track is scanned for distance to nearest wall. The result is a field of vectors pointing toward the nearest track border. This vector field is then processed to produce a rough estimate of local curvature. Finally, curvature and distance to wall are combined to produce a desired local density, and a rather clunky algorithm tries to sprinkle waypoints over the track accordingly. A notable improvement over the previous strategy is that narrow lanes will (apparently) always get enough waypoints to drive through, which allows to navigate the nightmare map. As always, it is a matter of finding a sweet spot between computation time and efficiency. A 50% decrease in density will divide computation time by more than 4, but with coarser results (48 moves instead of 44 on city, 720 instead of 670 on nightmare). ## Golfing I still think golfing does harm creativity in this specific case: removing antialiasing from the output is enough to gain 30 points, and requires a lot less effort than going from 47 to 44 moves on the city map. Even going from 720 to 670 moves on nightmare would gain a mere 500 points, though I very doubt a position-only A\* would be able to go anywhere near that. Just for the fun of it, I decided to write my own PHP compressor anyway. As it appears, renaming identifiers efficiently in PHP is not an easy task. In fact, I do not think it is even possible to do it in the general case. Even with a full semantic analysis, the possibility to use strings or indirect variables to designate objects would require the knowledge of every function semantics. However, since the very convenient built-in parser allows to jump to semantic analysis right away, I managed to produce something that seems to work on a subset of PHP sufficient to write "golfable" code (stay away from $$ and don't use indirect function calls or other string access to objects). No practical use to speak of and nothing to do with the original problem, but a lot of fun to code nevertheless. I could have butchered the code further to gain an extra 500 characters or so, but since the names of PHP graphic library are unfortunately quite long, it's a kind of uphill struggle. ## Further developments The waypoint selection code is an horrendous mess, tuned by trial and error. I suspect doing more maths (using proper gradient and curl operators) would greatly enhance the process. I am curious to see if a better distance heuristic can be found. I did try to take speed into account in a couple of ways, but it either broke the A\* or produced slower results. It might be possible to recode all this in a faster language like C++, but the PHP version relies heavily on garbage collection to keep memory consumption reasonable. Cleaning up closed nodes in C++ would require quite a bit of work and a sizeable amount of extra code. Would the scoring have been based on performances, I would have eagerly tried to improve the algorithms. But since the golfing criterion is so overwhelming, there is no real point, or is it? [Answer] ## ThirdRacer Java (1224 + 93\*10 = 2154) Similar to SecondRacer. But switching focus from speed to code size (but still using Java). Optimizing the acceleration is much simplified now, sadly resulting in a slower car. ### Performance Better than SecondRacer. ### Path Style Like SecondRacer. ### Code Style I entered into a heavy fighting mode. ### golfed -> WARNING: it does in-place replacement of the original file! ``` import javax.imageio.*;class A{class B extends java.util.Vector<C>{};class C{int D,E;}C F(int D,int E){G=new C();G.D=D;G.E=E;return G;}static java.awt.image.BufferedImage H;int I=H.getWidth(),J=H.getHeight(),K[][]=new int[I][J],L,M,N,O,P=~0xffff00,Q,D,E,R,S,T,U,V=255,W,X,Y;C Z,G;public static void main(String[]a)throws Exception{java.io.File b=new java.io.File(a[0]);H=ImageIO.read(b);new A().c();ImageIO.write(H,"PNG",b);}void c(){B d=new B();for(L=0;L<I;L++)for(M=0;M<J;M++)if(e(L,M)!=1||!d.add(F(L,M)))K[L][M]=-1>>>1;while(M!=3)for(Z=d.remove(N=0),D=Z.D,E=Z.E;N<9;N++)if((M=e(T=D+N/3-1,U=E+N%3-1))>0&&K[T][U]>(L=K[D][E]+(T==D||U==E?10:14))&&d.add(F(T,U)))K[T][U]=L;for(D=G.D,E=G.E,R=D,S=E;M!=4;){H.createGraphics().drawLine(R,S,D,E);H.setRGB(R,S,P);N=0;T=2-M%2;U=0;for(L=0;L<Q;L++,N+=T)if((N+T)*(N+T)/30.0>Q-L+7||N-O>15-T){H.setRGB(R+L*(M/3-1),S+L*(M%3-1),P);U=L;O=N;N=0;}O=T*(U-Q);R=D;S=E;M=4;double f=0,g;for(N=0;N<9;N++)for(L=1;e(T=R+L*(N/3-1),U=S+L*(N%3-1))>0;L++)if(f>(g=K[T][U]-K[R][S]+5*java.lang.Math.sqrt((R-T)*(R-T)+(S-U)*(S-U)))){f=g;D=T;E=U;M=N;Q=L;}}H.setRGB(R,S,P);}int e(int D,int E){return D<0||D>=I||E<0||E>=J?0:(W=H.getRGB(D,E))==~V?1:W==V<<24?3:30<=(X=W>>16&V)&&X<=220&&X==(Y=W>>8&V)&&Y==(V&W)?2:0;}} ``` --- City S+93 ![City S+93](https://i.stack.imgur.com/1EeN2.png) [Answer] # Star crossed racer path on the nightmare map ## (as per popular request) *(code not updated since the modifications are trivial and the performance-only challenge is not golfed)* Sorry to post yet another entry, but I'm hitting the 30.000 characters limit on the previous one. Just say the word and I'll delete this one. ``` 1: 112 154 -> 127 154 2: 127 154 -> 142 154 3: 142 154 -> 151 161 4: 151 161 -> 149 171 5: 149 171 -> 143 190 6: 143 190 -> 131 208 7: 131 208 -> 125 219 8: 125 219 -> 132 230 9: 132 230 -> 147 243 10: 147 243 -> 169 249 11: 169 249 -> 185 248 12: 185 248 -> 190 251 13: 190 251 -> 190 263 14: 190 263 -> 194 282 15: 194 282 -> 201 289 16: 201 289 -> 219 299 17: 219 299 -> 240 297 18: 240 297 -> 256 289 19: 256 289 -> 271 267 20: 271 267 -> 283 241 21: 283 241 -> 297 228 22: 297 228 -> 315 226 23: 315 226 -> 343 229 24: 343 229 -> 370 246 25: 370 246 -> 393 263 26: 393 263 -> 415 270 27: 415 270 -> 435 267 28: 435 267 -> 454 251 29: 454 251 -> 464 240 30: 464 240 -> 468 238 31: 468 238 -> 472 247 32: 472 247 -> 475 270 33: 475 270 -> 481 302 34: 481 302 -> 489 323 35: 489 323 -> 489 343 36: 489 343 -> 476 365 37: 476 365 -> 455 380 38: 455 380 -> 437 389 39: 437 389 -> 432 398 40: 432 398 -> 437 405 41: 437 405 -> 450 411 42: 450 411 -> 462 430 43: 462 430 -> 465 454 44: 465 454 -> 457 482 45: 457 482 -> 453 503 46: 453 503 -> 460 523 47: 460 523 -> 469 530 48: 469 530 -> 485 530 49: 485 530 -> 505 526 50: 505 526 -> 514 522 51: 514 522 -> 523 533 52: 523 533 -> 526 552 53: 526 552 -> 527 572 54: 527 572 -> 531 581 55: 531 581 -> 535 577 56: 535 577 -> 539 559 57: 539 559 -> 542 527 58: 542 527 -> 544 481 59: 544 481 -> 550 425 60: 550 425 -> 558 356 61: 558 356 -> 565 296 62: 565 296 -> 572 250 63: 572 250 -> 575 213 64: 575 213 -> 575 188 65: 575 188 -> 565 168 66: 565 168 -> 567 147 67: 567 147 -> 569 141 68: 569 141 -> 574 144 69: 574 144 -> 582 158 70: 582 158 -> 587 160 71: 587 160 -> 592 148 72: 592 148 -> 593 139 73: 593 139 -> 597 141 74: 597 141 -> 605 151 75: 605 151 -> 616 165 76: 616 165 -> 616 177 77: 616 177 -> 609 181 78: 609 181 -> 599 174 79: 599 174 -> 592 168 80: 592 168 -> 591 171 81: 591 171 -> 589 188 82: 589 188 -> 591 216 83: 591 216 -> 595 257 84: 595 257 -> 599 312 85: 599 312 -> 605 367 86: 605 367 -> 611 408 87: 611 408 -> 614 438 88: 614 438 -> 609 461 89: 609 461 -> 597 477 90: 597 477 -> 594 499 91: 594 499 -> 604 520 92: 604 520 -> 605 536 93: 605 536 -> 598 556 94: 598 556 -> 598 569 95: 598 569 -> 610 580 96: 610 580 -> 622 581 97: 622 581 -> 629 582 98: 629 582 -> 636 568 99: 636 568 -> 642 541 100: 642 541 -> 645 526 101: 645 526 -> 645 517 102: 645 517 -> 634 505 103: 634 505 -> 636 493 104: 636 493 -> 639 467 105: 639 467 -> 641 427 106: 641 427 -> 644 373 107: 644 373 -> 648 309 108: 648 309 -> 651 258 109: 651 258 -> 652 218 110: 652 218 -> 652 190 111: 652 190 -> 647 167 112: 647 167 -> 645 147 113: 645 147 -> 645 138 114: 645 138 -> 655 134 115: 655 134 -> 670 137 116: 670 137 -> 675 142 117: 675 142 -> 676 156 118: 676 156 -> 679 168 119: 679 168 -> 680 178 120: 680 178 -> 667 188 121: 667 188 -> 661 195 122: 661 195 -> 663 208 123: 663 208 -> 667 233 124: 667 233 -> 671 271 125: 671 271 -> 676 322 126: 676 322 -> 681 386 127: 681 386 -> 687 445 128: 687 445 -> 693 492 129: 693 492 -> 695 530 130: 695 530 -> 698 554 131: 698 554 -> 701 565 132: 701 565 -> 704 564 133: 704 564 -> 707 548 134: 707 548 -> 709 518 135: 709 518 -> 710 474 136: 710 474 -> 716 420 137: 716 420 -> 720 355 138: 720 355 -> 724 305 139: 724 305 -> 724 266 140: 724 266 -> 726 239 141: 726 239 -> 727 225 142: 727 225 -> 729 224 143: 729 224 -> 732 235 144: 732 235 -> 734 260 145: 734 260 -> 734 296 146: 734 296 -> 734 347 147: 734 347 -> 734 413 148: 734 413 -> 734 479 149: 734 479 -> 734 533 150: 734 533 -> 735 573 151: 735 573 -> 735 599 152: 735 599 -> 732 616 153: 732 616 -> 729 618 154: 729 618 -> 713 618 155: 713 618 -> 683 618 156: 683 618 -> 638 618 157: 638 618 -> 578 618 158: 578 618 -> 503 618 159: 503 618 -> 413 618 160: 413 618 -> 320 618 161: 320 618 -> 242 618 162: 242 618 -> 179 618 163: 179 618 -> 131 618 164: 131 618 -> 98 618 165: 98 618 -> 80 618 166: 80 618 -> 72 617 167: 72 617 -> 69 606 168: 69 606 -> 69 585 169: 69 585 -> 69 549 170: 69 549 -> 69 498 171: 69 498 -> 69 432 172: 69 432 -> 69 351 173: 69 351 -> 69 276 174: 69 276 -> 69 216 175: 69 216 -> 69 171 176: 69 171 -> 69 141 177: 69 141 -> 69 126 178: 69 126 -> 75 118 179: 75 118 -> 87 118 180: 87 118 -> 114 118 181: 114 118 -> 156 118 182: 156 118 -> 213 118 183: 213 118 -> 285 118 184: 285 118 -> 372 118 185: 372 118 -> 474 118 186: 474 118 -> 591 118 187: 591 118 -> 701 120 188: 701 120 -> 800 120 189: 800 120 -> 884 120 190: 884 120 -> 953 120 191: 953 120 -> 1007 120 192: 1007 120 -> 1049 120 193: 1049 120 -> 1076 120 194: 1076 120 -> 1089 120 195: 1089 120 -> 1092 123 196: 1092 123 -> 1087 132 197: 1087 132 -> 1073 145 198: 1073 145 -> 1046 160 199: 1046 160 -> 1015 164 200: 1015 164 -> 986 156 201: 986 156 -> 964 150 202: 964 150 -> 954 147 203: 954 147 -> 951 151 204: 951 151 -> 959 156 205: 959 156 -> 981 162 206: 981 162 -> 996 169 207: 996 169 -> 1002 182 208: 1002 182 -> 997 194 209: 997 194 -> 986 208 210: 986 208 -> 988 222 211: 988 222 -> 995 226 212: 995 226 -> 1013 226 213: 1013 226 -> 1044 224 214: 1044 224 -> 1079 229 215: 1079 229 -> 1103 238 216: 1103 238 -> 1119 245 217: 1119 245 -> 1133 243 218: 1133 243 -> 1147 256 219: 1147 256 -> 1153 270 220: 1153 270 -> 1160 270 221: 1160 270 -> 1162 260 222: 1162 260 -> 1165 237 223: 1165 237 -> 1182 213 224: 1182 213 -> 1210 185 225: 1210 185 -> 1231 157 226: 1231 157 -> 1245 135 227: 1245 135 -> 1257 123 228: 1257 123 -> 1261 118 229: 1261 118 -> 1263 124 230: 1263 124 -> 1263 143 231: 1263 143 -> 1263 176 232: 1263 176 -> 1263 224 233: 1263 224 -> 1263 287 234: 1263 287 -> 1263 365 235: 1263 365 -> 1263 437 236: 1263 437 -> 1263 494 237: 1263 494 -> 1263 536 238: 1263 536 -> 1263 563 239: 1263 563 -> 1263 578 240: 1263 578 -> 1258 583 241: 1258 583 -> 1243 583 242: 1243 583 -> 1213 583 243: 1213 583 -> 1180 580 244: 1180 580 -> 1146 568 245: 1146 568 -> 1125 558 246: 1125 558 -> 1117 546 247: 1117 546 -> 1115 539 248: 1115 539 -> 1107 538 249: 1107 538 -> 1098 550 250: 1098 550 -> 1103 561 251: 1103 561 -> 1114 567 252: 1114 567 -> 1113 575 253: 1113 575 -> 1099 581 254: 1099 581 -> 1078 582 255: 1078 582 -> 1067 579 256: 1067 579 -> 1059 570 257: 1059 570 -> 1061 560 258: 1061 560 -> 1070 556 259: 1070 556 -> 1074 553 260: 1074 553 -> 1069 544 261: 1069 544 -> 1058 542 262: 1058 542 -> 1045 530 263: 1045 530 -> 1017 518 264: 1017 518 -> 990 509 265: 990 509 -> 972 501 266: 972 501 -> 955 500 267: 955 500 -> 938 514 268: 938 514 -> 914 528 269: 914 528 -> 902 543 270: 902 543 -> 895 562 271: 895 562 -> 893 572 272: 893 572 -> 880 581 273: 880 581 -> 869 579 274: 869 579 -> 858 571 275: 858 571 -> 844 567 276: 844 567 -> 834 558 277: 834 558 -> 830 553 278: 830 553 -> 832 540 279: 832 540 -> 829 529 280: 829 529 -> 821 522 281: 821 522 -> 819 517 282: 819 517 -> 831 512 283: 831 512 -> 838 506 284: 838 506 -> 843 488 285: 843 488 -> 843 473 286: 843 473 -> 844 469 287: 844 469 -> 856 469 288: 856 469 -> 883 469 289: 883 469 -> 906 458 290: 906 458 -> 918 449 291: 918 449 -> 924 433 292: 924 433 -> 920 418 293: 920 418 -> 904 406 294: 904 406 -> 883 404 295: 883 404 -> 859 402 296: 859 402 -> 844 394 297: 844 394 -> 843 385 298: 843 385 -> 841 366 299: 841 366 -> 838 361 300: 838 361 -> 828 363 301: 828 363 -> 813 356 302: 813 356 -> 807 343 303: 807 343 -> 805 321 304: 805 321 -> 810 298 305: 810 298 -> 813 285 306: 813 285 -> 821 282 307: 821 282 -> 842 280 308: 842 280 -> 868 278 309: 868 278 -> 887 280 310: 887 280 -> 898 288 311: 898 288 -> 898 300 312: 898 300 -> 895 314 313: 895 314 -> 901 324 314: 901 324 -> 909 324 315: 909 324 -> 917 318 316: 917 318 -> 921 311 317: 921 311 -> 930 314 318: 930 314 -> 947 322 319: 947 322 -> 956 329 320: 956 329 -> 962 339 321: 962 339 -> 970 337 322: 970 337 -> 973 338 323: 973 338 -> 978 334 324: 978 334 -> 992 326 325: 992 326 -> 1000 327 326: 1000 327 -> 1008 335 327: 1008 335 -> 1015 351 328: 1015 351 -> 1021 373 329: 1021 373 -> 1022 390 330: 1022 390 -> 1013 404 331: 1013 404 -> 1006 417 332: 1006 417 -> 1012 430 333: 1012 430 -> 1023 436 334: 1023 436 -> 1029 434 335: 1029 434 -> 1049 432 336: 1049 432 -> 1063 426 337: 1063 426 -> 1079 425 338: 1079 425 -> 1093 418 339: 1093 418 -> 1113 417 340: 1113 417 -> 1128 414 341: 1128 414 -> 1139 421 342: 1139 421 -> 1154 426 343: 1154 426 -> 1158 430 344: 1158 430 -> 1149 436 345: 1149 436 -> 1130 438 346: 1130 438 -> 1108 442 347: 1108 442 -> 1096 447 348: 1096 447 -> 1087 441 349: 1087 441 -> 1079 443 350: 1079 443 -> 1072 446 351: 1072 446 -> 1060 454 352: 1060 454 -> 1052 461 353: 1052 461 -> 1034 463 354: 1034 463 -> 1016 463 355: 1016 463 -> 1010 464 356: 1010 464 -> 1011 472 357: 1011 472 -> 1012 479 358: 1012 479 -> 1025 484 359: 1025 484 -> 1048 488 360: 1048 488 -> 1083 491 361: 1083 491 -> 1119 505 362: 1119 505 -> 1154 520 363: 1154 520 -> 1183 530 364: 1183 530 -> 1201 537 365: 1201 537 -> 1209 539 366: 1209 539 -> 1209 535 367: 1209 535 -> 1209 517 368: 1209 517 -> 1209 484 369: 1209 484 -> 1210 437 370: 1210 437 -> 1210 392 371: 1210 392 -> 1210 362 372: 1210 362 -> 1210 347 373: 1210 347 -> 1203 340 374: 1203 340 -> 1184 333 375: 1184 333 -> 1156 320 376: 1156 320 -> 1116 306 377: 1116 306 -> 1069 285 378: 1069 285 -> 1023 265 379: 1023 265 -> 985 249 380: 985 249 -> 955 235 381: 955 235 -> 933 227 382: 933 227 -> 923 221 383: 923 221 -> 923 211 384: 923 211 -> 917 195 385: 917 195 -> 901 176 386: 901 176 -> 881 159 387: 881 159 -> 848 144 388: 848 144 -> 815 144 389: 815 144 -> 788 153 390: 788 153 -> 769 169 391: 769 169 -> 764 185 392: 764 185 -> 766 209 393: 766 209 -> 767 247 394: 767 247 -> 769 299 395: 769 299 -> 769 362 396: 769 362 -> 769 440 397: 769 440 -> 769 503 398: 769 503 -> 769 551 399: 769 551 -> 769 584 400: 769 584 -> 769 605 401: 769 605 -> 770 613 402: 770 613 -> 780 616 403: 780 616 -> 801 616 404: 801 616 -> 837 616 405: 837 616 -> 888 616 406: 888 616 -> 954 616 407: 954 616 -> 1035 616 408: 1035 616 -> 1113 616 409: 1113 616 -> 1176 616 410: 1176 616 -> 1224 616 411: 1224 616 -> 1257 616 412: 1257 616 -> 1278 616 413: 1278 616 -> 1294 607 414: 1294 607 -> 1295 598 415: 1295 598 -> 1295 577 416: 1295 577 -> 1295 541 417: 1295 541 -> 1295 490 418: 1295 490 -> 1295 424 419: 1295 424 -> 1295 343 420: 1295 343 -> 1295 265 421: 1295 265 -> 1295 202 422: 1295 202 -> 1295 154 423: 1295 154 -> 1295 121 424: 1295 121 -> 1295 100 425: 1295 100 -> 1294 92 426: 1294 92 -> 1283 89 427: 1283 89 -> 1262 89 428: 1262 89 -> 1226 89 429: 1226 89 -> 1175 89 430: 1175 89 -> 1109 89 431: 1109 89 -> 1028 89 432: 1028 89 -> 938 89 433: 938 89 -> 860 89 434: 860 89 -> 797 89 435: 797 89 -> 749 89 436: 749 89 -> 716 89 437: 716 89 -> 698 89 438: 698 89 -> 690 94 439: 690 94 -> 682 102 440: 682 102 -> 673 100 441: 673 100 -> 661 89 442: 661 89 -> 646 89 443: 646 89 -> 616 89 444: 616 89 -> 571 89 445: 571 89 -> 517 89 446: 517 89 -> 478 89 447: 478 89 -> 454 89 448: 454 89 -> 442 92 449: 442 92 -> 432 102 450: 432 102 -> 423 100 451: 423 100 -> 411 89 452: 411 89 -> 396 89 453: 396 89 -> 381 92 454: 381 92 -> 371 102 455: 371 102 -> 362 100 456: 362 100 -> 349 89 457: 349 89 -> 334 89 458: 334 89 -> 309 91 459: 309 91 -> 298 92 460: 298 92 -> 288 102 461: 288 102 -> 279 100 462: 279 100 -> 267 89 463: 267 89 -> 252 89 464: 252 89 -> 222 89 465: 222 89 -> 177 89 466: 177 89 -> 123 89 467: 123 89 -> 84 89 468: 84 89 -> 60 89 469: 60 89 -> 48 89 470: 48 89 -> 42 97 471: 42 97 -> 42 112 472: 42 112 -> 42 142 473: 42 142 -> 42 187 474: 42 187 -> 42 247 475: 42 247 -> 42 322 476: 42 322 -> 42 409 477: 42 409 -> 42 484 478: 42 484 -> 42 544 479: 42 544 -> 42 589 480: 42 589 -> 42 619 481: 42 619 -> 42 634 482: 42 634 -> 47 640 483: 47 640 -> 59 640 484: 59 640 -> 86 640 485: 86 640 -> 128 640 486: 128 640 -> 185 640 487: 185 640 -> 257 640 488: 257 640 -> 344 640 489: 344 640 -> 446 640 490: 446 640 -> 563 640 491: 563 640 -> 690 640 492: 690 640 -> 816 639 493: 816 639 -> 930 639 494: 930 639 -> 1029 639 495: 1029 639 -> 1113 639 496: 1113 639 -> 1182 639 497: 1182 639 -> 1236 639 498: 1236 639 -> 1275 639 499: 1275 639 -> 1300 639 500: 1300 639 -> 1316 633 501: 1316 633 -> 1320 630 502: 1320 630 -> 1322 615 503: 1322 615 -> 1322 588 504: 1322 588 -> 1322 546 505: 1322 546 -> 1322 489 506: 1322 489 -> 1322 417 507: 1322 417 -> 1322 330 508: 1322 330 -> 1322 252 509: 1322 252 -> 1322 186 510: 1322 186 -> 1322 135 511: 1322 135 -> 1322 99 512: 1322 99 -> 1322 78 513: 1322 78 -> 1320 68 514: 1320 68 -> 1310 65 515: 1310 65 -> 1289 65 516: 1289 65 -> 1253 65 517: 1253 65 -> 1208 65 518: 1208 65 -> 1178 65 519: 1178 65 -> 1163 65 520: 1163 65 -> 1155 71 521: 1155 71 -> 1149 76 522: 1149 76 -> 1135 74 523: 1135 74 -> 1111 74 524: 1111 74 -> 1102 74 525: 1102 74 -> 1091 65 526: 1091 65 -> 1076 65 527: 1076 65 -> 1046 65 528: 1046 65 -> 1013 65 529: 1013 65 -> 992 65 530: 992 65 -> 986 65 531: 986 65 -> 975 56 532: 975 56 -> 960 56 533: 960 56 -> 930 56 534: 930 56 -> 899 58 535: 899 58 -> 878 58 536: 878 58 -> 870 59 537: 870 59 -> 864 65 538: 864 65 -> 849 65 539: 849 65 -> 819 65 540: 819 65 -> 774 65 541: 774 65 -> 714 65 542: 714 65 -> 651 65 543: 651 65 -> 603 65 544: 603 65 -> 570 65 545: 570 65 -> 552 65 546: 552 65 -> 546 65 547: 546 65 -> 535 56 548: 535 56 -> 520 56 549: 520 56 -> 492 58 550: 492 58 -> 478 59 551: 478 59 -> 472 65 552: 472 65 -> 457 65 553: 457 65 -> 427 65 554: 427 65 -> 382 65 555: 382 65 -> 322 65 556: 322 65 -> 265 65 557: 265 65 -> 223 65 558: 223 65 -> 193 65 559: 193 65 -> 178 65 560: 178 65 -> 170 71 561: 170 71 -> 164 76 562: 164 76 -> 156 74 563: 156 74 -> 145 65 564: 145 65 -> 130 65 565: 130 65 -> 109 65 566: 109 65 -> 103 65 567: 103 65 -> 92 56 568: 92 56 -> 77 56 569: 77 56 -> 65 59 570: 65 59 -> 57 68 571: 57 68 -> 46 67 572: 46 67 -> 29 65 573: 29 65 -> 20 68 574: 20 68 -> 17 80 575: 17 80 -> 17 104 576: 17 104 -> 17 143 577: 17 143 -> 17 197 578: 17 197 -> 17 266 579: 17 266 -> 17 350 580: 17 350 -> 19 435 581: 19 435 -> 19 507 582: 19 507 -> 19 564 583: 19 564 -> 19 606 584: 19 606 -> 19 633 585: 19 633 -> 19 648 586: 19 648 -> 33 662 587: 33 662 -> 48 664 588: 48 664 -> 76 664 589: 76 664 -> 118 664 590: 118 664 -> 175 664 591: 175 664 -> 245 664 592: 245 664 -> 328 664 593: 328 664 -> 423 663 594: 423 663 -> 532 661 595: 532 661 -> 654 661 596: 654 661 -> 784 662 597: 784 662 -> 900 662 598: 900 662 -> 1002 662 599: 1002 662 -> 1089 662 600: 1089 662 -> 1166 662 601: 1166 662 -> 1231 664 602: 1231 664 -> 1283 664 603: 1283 664 -> 1320 664 604: 1320 664 -> 1344 662 605: 1344 662 -> 1355 662 606: 1355 662 -> 1359 654 607: 1359 654 -> 1372 640 608: 1372 640 -> 1377 630 609: 1377 630 -> 1376 613 610: 1376 613 -> 1376 586 611: 1376 586 -> 1376 550 612: 1376 550 -> 1374 527 613: 1374 527 -> 1374 517 614: 1374 517 -> 1381 508 615: 1381 508 -> 1381 494 616: 1381 494 -> 1370 477 617: 1370 477 -> 1372 459 618: 1372 459 -> 1370 432 619: 1370 432 -> 1367 418 620: 1367 418 -> 1354 401 621: 1354 401 -> 1355 384 622: 1355 384 -> 1351 361 623: 1351 361 -> 1343 330 624: 1343 330 -> 1344 295 625: 1344 295 -> 1346 271 626: 1346 271 -> 1347 256 627: 1347 256 -> 1336 240 628: 1336 240 -> 1336 224 629: 1336 224 -> 1345 210 630: 1345 210 -> 1341 196 631: 1341 196 -> 1338 172 632: 1338 172 -> 1340 153 633: 1340 153 -> 1349 132 634: 1349 132 -> 1345 109 635: 1345 109 -> 1347 80 636: 1347 80 -> 1356 59 637: 1356 59 -> 1359 42 638: 1359 42 -> 1356 34 639: 1356 34 -> 1341 29 640: 1341 29 -> 1316 29 641: 1316 29 -> 1276 29 642: 1276 29 -> 1221 29 643: 1221 29 -> 1177 32 644: 1177 32 -> 1143 31 645: 1143 31 -> 1118 24 646: 1118 24 -> 1084 23 647: 1084 23 -> 1045 31 648: 1045 31 -> 1011 29 649: 1011 29 -> 991 26 650: 991 26 -> 972 19 651: 972 19 -> 953 22 652: 953 22 -> 934 31 653: 934 31 -> 909 31 654: 909 31 -> 872 29 655: 872 29 -> 822 29 656: 822 29 -> 775 31 657: 775 31 -> 742 32 658: 742 32 -> 713 37 659: 713 37 -> 683 36 660: 683 36 -> 650 40 661: 650 40 -> 619 35 662: 619 35 -> 577 34 663: 577 34 -> 547 32 664: 547 32 -> 505 32 665: 505 32 -> 455 25 666: 455 25 -> 401 23 667: 401 23 -> 346 22 668: 346 22 -> 296 31 669: 296 31 -> 240 32 670: 240 32 -> 172 31 671: 172 31 -> 91 31 672: 91 31 -> 14 25 ``` --- [Answer] # Sunday Driver, Python 2, 3242 Minified code = 2382 bytes Performance: city=86 obstacles=46 racetrack=188 gauntlet=1092 Here is my proof-of-concept program that was to demonstrate that a solution was possible. It needs some optimisation and better golfing. ### Operation * Create a data structure of distance rings out from the destination (simple A\* derivative, like flood fill) * Find the shorted series of straight lines to destination that do not cross non-track pixels. * For each straight line, accelerate and brake to minimise the turns taken. ### Golfed (minified) Code ``` import pygame as P,sys,random Z=255 I=int R=range X=sys.argv[1] pic=P.image.load(X) show=P.display.flip W,H=pic.get_size() M=P.display.set_mode((W,H)) M.blit(pic,(0,0)) show() U=complex ORTH=[U(-1,0),U(1,0),U(0,-1),U(0,1)] def draw(line,O): for p in line: M.set_at((I(p.real),I(p.imag)),O) def plot(p,O): M.set_at((I(p.real),I(p.imag)),O) def J(p): return abs(I(p.real))+abs(I(p.imag)) locs=[(x,y)for x in R(W)for y in R(H)] n={} for p in locs: O=tuple(M.get_at(p))[:3] if O not in n: n[O]=set() n[O].add(U(p[0],p[1])) z=set() for c in n: if c[0]==c[1]==c[2]and 30<=c[0]<=220 or c==(0,0,0)or c==(Z,Z,0): z|=n[c] first=next(iter(n[(0,0,0)])) ring=set([first]) s={0:ring} g={first:0} T=set() G=0 done=0 while not done: G+=1 T|=ring D=set() for dot in ring: for K in[dot+diff for diff in ORTH]: if K in n[(Z,Z,0)]: V=K;done=1 if K in z and K not in T: D.add(K);g[K]=G ring=D s[G]=ring def A(p1,p2): x1,y1=I(p1.real),I(p1.imag) x2,y2=I(p2.real),I(p2.imag) dx=x2-x1 dy=y2-y1 line=[] if abs(dx)>abs(dy): m=1.0*dy/dx line=[U(x,I(m*(x-x1)+y1+.5))for x in R(x1,x2,cmp(dx,0))] else: m=1.0*dx/dy line=[U(I(m*(y-y1)+x1+.5),y)for y in R(y1,y2,cmp(dy,0))] return line+[U(x2,y2)] def f(p1,p2): return all(p in z for p in A(p1,p2)) def a(j,G): l=list(s[G]) for F in R(150): w=random.choice(l) if f(j,w): return w return None def d(j): u=g[j] E=k=0 r=j while 1: w=a(j,k) if w: u=k;r=w else: E=k k=(u+E)/2 if k==u or k==E: break return r def h(p1,p2): if abs(p2-p1)<9: return p2 line=A(p1,p2) tries=min(20,len(line)/2) test=[line[-i]for i in R(1,tries)] q=[(p,d(p))for p in test] rank=[(abs(p3-p)+abs(p-p1),p)for p,p3 in q] return max(rank)[1] o=V path=[V] while g[o]>0: o=d(o) if o not in n[(0,0,0)]: o=h(path[-1],o) path.append(o) if o in n[(0,0,0)]: break def t(line,N): v=[] S=len(line)/2+2 base=i=0 b=0 while i<len(line): C=(i<S) Q=line[i]-line[base] accel=Q-N L=(J(accel)<=15) if L: b=1 if C: if b and not L: i-=1;v.append(i);N=Q;base=i;b=0 else: if b and J(Q)>13: v.append(i);N=Q;base=i;b=0 i+=1 v.append(i-1) return v,Q turns=0 vel=U(0,0) for V,stop in zip(path,path[1:]): line=A(V,stop) Y,vel=t(line,vel) turns+=len(Y) draw(line,(Z,Z,Z)) plot(line[0],(0,0,Z)) for m in Y: plot(line[m],(0,0,Z)) B=X.replace('.','%u.'%turns) P.image.save(M,B) ``` ### Examples ![city](https://i.stack.imgur.com/Wlk46.png) ![racetrack](https://i.stack.imgur.com/9rTTy.png) ![obstacles](https://i.stack.imgur.com/QBSO7.png) ![gauntlet](https://i.stack.imgur.com/OX0TR.png) ]
[Question] [ (Note: This is a spin-off of my previous challenge [Find the Swirling Words!](https://codegolf.stackexchange.com/questions/95507/find-the-swirling-words)) ### Definition of *Infinity Word*: 1. If you connect with curves all the characters of an *Infinity Word* on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below. 2. All the even connection must be *down*, all the odd connections must be *up*. 3. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case. 4. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols. 5. Each word must be exactly 5 characters. Words > 5 or < 5 are not valid. 6. If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN". 7. All the *Infinity Words* start and end with the same character. **Here there are some examples:** [![Infinity Words](https://i.stack.imgur.com/IAeGj.gif)](https://i.stack.imgur.com/IAeGj.gif) ### Task: Write a full program or function that will take a word from standard input and will output if is an *Infinity Word* or not. The output can be true/false, 1/0, 1/Null, etc. **Test cases:** ``` Infinity Words: ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW NOT Infinity Words: CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST, KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO ``` ### Rules: 1. Shortest code wins. ### Optional Task: Find, as a list, as many *Infinity Words* as you can in an English dictionary. You can take for example as reference the complete list of English words [here](https://github.com/dwyl/english-words). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~43 41 40 25 24 23 22 21 14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -7 bytes thanks to fireflame241 (`0ị=1ị$`->`=ṚḢ` and use of `IIA⁼2,2` to test for the 4 rotations) -1 Thanks to Kevin Cruijssen (use of previously unavailable nilad `Ø2` which yields `[2,2]`) ``` =ṚḢȧOIṠIIA⁼Ø2 ``` **[TryItOnline](https://tio.run/##ASgA1/9qZWxsef//PeG5muG4osinT0nhuaBJSUHigbzDmDL///8iQUxQSEEi "Jelly – Try It Online")** Or [all test cases](https://tio.run/##LY4xDsIwDEXv0pmJncG0LrEIcUkaKoQYWRAXYISFKyAmxMLCAUBiQ0hco1wk2BWD9eTh/f/Xq81mm9KgfZza@@VzZWofZyL47p6vYz@9n6/Dd38by81TWmRgKwNZL0MYWRQa8MEIHTl2wopcrIQ@WvTC2mBZCxsquBHmcUi5@h6C@qWNZSm0MEQrnHCBE/WhAPU9zbqc0FAImudj0LyxQ9R/GhG1d@SZZxrIzs61R4ZBXncudw2kGvva8H9eyJY/ "Jelly – Try It Online") (plus "RULES") ### How? An infinity word has: 1. the same first and last letter; 2. length 5; 3. no equal letters next to each other; 4. sum of its four alphabet deltas equal to zero; 5. sum of its four alphabet deltas signs equal to zero; 6. two positive alphabet deltas or two negative alphabet deltas in a row. All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of `[1,1,-1,-1]` (where the sign of `0` is `0`) fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in `[[2,2],[2,-2],[-2,2],[-2,-2]]` which may be tested by the absolute values being equal to `[2,2]`! ### How? ``` =ṚḢȧOIṠIIA⁼Ø2 - Main link: word Ṛ - reverse word = - equals? (vectorises) Ḣ - head (is the first character equal to the last?) ȧ - and O - cast word to ordinals I - increments - the alphabet deltas (or just [] if 1st != last) Ṡ - sign (vectorises) I - increments - deltas of those signs I - increments - deltas of those A - absolute value (vectorises) Ø2 - literal [2,2] ⁼ - equals? (non-vectorising version) ``` [Answer] # Java 8, ~~231~~ ~~193~~ ~~185~~ ~~122~~ ~~103~~ 78 bytes ``` s->s.length==5&&(s[1]-s[0])*(s[3]-s[2])<0&(s[2]-s[1])*(s[4]-s[3])<0&s[4]==s[0] ``` [Try it here.](https://tio.run/##fVBNT9tAEL3nV4x8QDY0Fh/tBepKi7PBVh079QdRFeWwOBswmHXk3VAhlN8eZoyRKAIu@2b2aebNe7fiQQybtVS3y7tdWQutYSIq9TQAqJSR7UqUEmJqAa6appZCQWmXN6KdL0A7Z0hsB/hoI0xVQgwKPNjp4S/t1lJdmxvP@7G3Z@v50WKo54cLZx/rE6qPF87PQ2KOqTt6Yb5TfdIx1HgezezOSGG9uapRoRd6aKol3OOldmbaSl3jNcJ5OXPVtP0n6E1ZSrnEMpfa@EJLOAUl/8Hr0JPFomnArG8WZxcRRwxYmgWIcRgnMeI0jIspYlpEPEXMAz7OEWfhKJlZ214TIHvURt67zca4a9xtamV/oH4A1ilYCMotP@Bd0/gYLWtb8Wg7ThcvBfyJQM@/MbwSVf2VW784D31ym7KM3I6jYjxGjNg5jxAnyYhPyC0bMXKbhped62wWZhm5T4uM3P@OOaf@T8E5pXSRJsklLUzi6C@CjzEyP@9mk04hSfMg6XOkya@je@/jv9zekZ@Hth1sd88) -38 bytes thanks to *@dpa97* for reminding me to use `char[]` instead of `String`. -63 bytes thanks to *@KarlNapf*'s derived formula. -25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer). **193 bytes answer:** ``` int c(char[]s){if(s.length!=5)return 0;int a=s[0],b=s[1],c=s[2],d=s[3],e=s[4],z=b-a,y=c-b,x=d-c,w=e-d;return e!=a?0:(z>0&y>0&x<0&w<0)|(z<0&y>0&x>0&w<0)|(z>0&y<0&x<0&w>0)|(z<0&y<0&x>0&w>0)?1:0;} ``` **Explanation:** * If the length of the string isn't 5, we return `false` * If the first character doesn't equal the last character, we return `false` * Then we check the four valid cases one by one (let's indicate the five characters as 1 through 5), and return `true` if it complies to any of them (and `false` otherwise): 1. If the five characters are distributed like: `1<2<3>4>5` (i.e. `ALPHA`) 2. If the five characters are distributed like: `1>2<3<4>5` (i.e. `EAGLE`, `HARSH`, `NINON`, `PINUP`) 3. If the five characters are distributed like: `1<2>3>4<5` (i.e. `RULER`) 4. If the five characters are distributed like: `1>2>3<4<5` (i.e. `THEFT`, `WIDOW`) These four rules can be simplified to `1*3<0 and 2*4<0` (thanks to [*@KarlNapf*'s Python 2 answer](https://codegolf.stackexchange.com/a/96569/52210)). [Answer] ## JavaScript (ES6), ~~91~~ ~~89~~ 87 bytes *Saved 2 bytes thanks to Ismael Miguel* ``` s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1) ``` ### How it works We build a 4-bit bitmask `k` representing the 4 transitions between the 5 characters of the string: ``` k += p > c ? 1<<i : 0 / (p < c) ``` * if the previous character is higher than the next one, the bit is set * if the previous character is lower then the next one, the bit is not set * if the previous character is identical to the next one, the whole bitmask is forced to `NaN` so that the word is rejected (to comply with rule #6) The valid bitmasks are the ones that have exactly two consecutive `1` transitions (the first and the last bits being considered as *consecutive* as well): ``` Binary | Decimal -------+-------- 0011 | 3 0110 | 6 1100 | 12 1001 | 9 ``` In other words, these are the combinations which are: * `k?` : greater than 0 * `!(k%3)` : **congruent to 0 modulo 3** * lower than 15 The other conditions are: * `!s[5]` : there's no more than 5 characters * `s[0]==s[4]` : the 1st and the 5th characters are identical **NB**: We don't explicitly check `k != 15` because any word following such a pattern will be rejected by this last condition. ### Test cases ``` let f = s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1) console.log("Testing truthy words..."); console.log(f("ALPHA")); console.log(f("EAGLE")); console.log(f("HARSH")); console.log(f("NINON")); console.log(f("PINUP")); console.log(f("RULER")); console.log(f("THEFT")); console.log(f("WIDOW")); console.log("Testing falsy words..."); console.log(f("CUBIC")); console.log(f("ERASE")); console.log(f("FLUFF")); console.log(f("LABEL")); console.log(f("MODEM")); console.log(f("RADAR")); console.log(f("RIVER")); console.log(f("SWISS")); console.log(f("TRUST")); console.log(f("KNEES")); console.log(f("QUEEN")); console.log(f("ORTHO")); console.log(f("GROOVE")); console.log(f("ONLY")); console.log(f("CHARACTER")); console.log(f("OFF")); console.log(f("IT")); console.log(f("ORTHO")); ``` ### Initial version For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters. ``` ([a,b,c,d,e,f])=>!f&&a==e&&!(((a>b)+2*(b>c)+4*(c>d)+8*(d>e))%3) ``` Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well: ``` ([a,b,c,d,e,f])=>!f&&a==e&&!((a>b)-(b>c)+(c>d)-(d>e)) ``` **Edit:** See [Neil's answer](https://codegolf.stackexchange.com/a/96568/58563) for the fixed/completed version of the above code. [Answer] ## JavaScript (ES6), 78 bytes ``` ([a,b,c,d,e,f])=>a==e&&!(f||/(.)\1/.test(a+b+c+d+e)||(a>b)-(b>c)+(c>d)-(d>e)) ``` Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart. * If the peak and the trough are the middle and first/last letters, then the first two comparisons and the last two comparisons cancel out * If the peak and the trough are the second and fourth letters, then the middle two comparisons and the outer two comparisons cancel out * Otherwise, something fails to cancel and the overall expression returns false Edit: Alternative 78-byte solution based on @KarlNapf's answer: ``` ([a,b,c,d,e,f],g=(a,b)=>(a<b)-(a>b))=>a==e&&!f&&g(a,b)*g(c,d)+g(b,c)*g(d,e)<-1 ``` [Answer] ## Python 2 exit code, 56 bytes ``` s=input() v,w,x,y,z=map(cmp,s,s[1:]+s[0]) v*x+w*y|z>-2>_ ``` Outputs via exit code: Error for False, and successful run for True. Takes the string `s` with characters `abcde`, rotates it to `bcdea`, does an elementwise comparison of corresponding characters, and assigns them to five variables `v,w,x,y,z`. The wrong length gives an error. The infinity words all have ``` v*x == -1 w*y == -1 z == 0 ``` which can be checked jointly as `v*x+w*y|z == -2`. The chained comparison `v*x+w*y|z>-2>_` short-circuits if this is the case, and otherwise goes on to evaluate `-2>_` which gives a name error. [Answer] # Python 2, ~~110~~ ~~87~~ 60 bytes Saving 1 byte thanks to Neil Requires input enclosed in quotes, e.g. `'KNEES'` `True` if it is an infinity word, `False` if not and it has length of 5 and prints error message if wrong length ``` s=input() a,b,c,d,e=map(cmp,s,s[1:]+s[0]) print a*c+b*d|e<-1 ``` Inspired by [xnor](https://codegolf.stackexchange.com/a/96571/53667)'s answer using `map(cmp...` ``` s=input() e=map(cmp,s,s[1:]+s[0]) print e[4]==0and e[0]*e[2]+e[1]*e[3]==-2and 5==len(s) ``` previous solution: ``` s=input() d=[ord(x)-ord(y)for x,y in zip(s,s[1:])] print s[0]==s[4]and d[0]*d[2]<0and d[1]*d[3]<0and 4==len(d) ``` Using the optimized logic of [Kevin Cruijssen](https://codegolf.stackexchange.com/a/96530/53667) [Answer] # PHP, 102 Bytes ``` for(;$i<strlen($w=$argv[1]);)$s.=($w[$i++]<=>$w[$i])+1;echo preg_match("#^(2200|0022|2002|0220)#",$s); ``` [Answer] ## Python 2, 71 bytes ``` lambda s:map(cmp,s,s[1:]+s[0])in[[m,n,-m,-n,0]for m in-1,1for n in-1,1] ``` Takes the string `s` with characters `abcde`, rotates it to `bcdea`, and does an elementwise comparison of corresponding characters. ``` a b cmp(a,b) b c cmp(b,c) c d cmp(c,d) d e cmp(d,e) e a cmp(e,a) ``` The result is a list of `-1, 0, 1`. Then, checks if the result is one of the valid sequences of up and downs: ``` [-1, -1, 1, 1, 0] [-1, 1, 1, -1, 0] [1, -1, -1, 1, 0] [1, 1, -1, -1, 0] ``` as generated from the template `[m,n,-m,-n,0]` with `m,n=±1`. The last `0` checks that the first and last letter were equal, and the length ensures that the input string had length 5. --- An alternative 71. Checks the conditions on comparisons while ensuring the right length. ``` def f(s):a,b,c,d,e=map(cmp,s,s[1:]+s*9)[:5];print a*c<0==e>b*d>len(s)-7 ``` [Answer] ## R, 144 bytes The answer is based off the logic of @Jonathan Allan. It could probably be golfed though. ``` s=strsplit(scan(,""),"")[[1]];d=diff(match(s,LETTERS));s[1]==tail(s,1)&length(s)==5&all(!rle(s)$l-1)&!sum(d)&!sum(sign(d))&any(rle(sign(d))$l>1) ``` [R-fiddle test cases](http://www.r-fiddle.org/#/fiddle?id=l4qFCfGW&version=2) (vectorized example but same logic) [Answer] # GNU Prolog, 47 bytes ``` i([A,B,C,D,A]):-A>B,B>C,C<D,D<A;i([B,C,D,A,B]). ``` Defines a predicate `i` which succeeds (infinitely many times, in fact) for an infinity word, thus outputting "yes" when run from the interpreter (as is usual for Prolog); fails for a candidate word whose first and last letters don't match, or isn't 5 letters long, thus outputting "no" when run from the interpreter; and crashes with a stack overflow if given a candidate word that isn't an infinity word, but which is five letters with the first and last two matching. (I'm not sure *why* it crashes; the recursive call should be treatable as a tailcall. Apparently GNU Prolog's optimizer isn't very good.) Succeeding is Prolog's equivalent of truthy, and failing the equivalent of falsey; a crash is definitely more falsey than truthy, and fixing it would make the solution substantially longer, so I hope this counts as a valid solution. The algorithm is fairly simple (and indeed, the program is fairly readable); check whether the letters form one of the four patterns that make an infinity word, and if not, cyclicly permute and try again. We don't need to explicitly check for double letters as the `<` and `>` operators let us implicitly check that at the same time that we check that the deltas match. [Answer] # [Actually](http://github.com/Mego/Seriously), ~~38~~ 27 bytes This answer was largely inspired by [Jonathan Allan's excellent Jelly answer](https://codegolf.stackexchange.com/a/96540/47581). There are probably several places where this can be golfed, so golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=Tztc4pmALWRZQOKZgnM0UmAwfjsxMSh7a2BNw611Yio&input=ImFscGhhIg) ``` O;\♀-dY@♂s4R`0~;11({k`Míub* ``` **Ungolfing** ``` Implicit input s. O Push the ordinals of s. Call this ords. ; Duplicate ords. \ Rotate one duplicate of ords left by 1. ♀- Vectorized subtraction. This effectively gets the first differences of ords. d Pop ord_diff[-1] onto the stack. This is ords[0] - ords[-1]. Y Logical negate ord_diff[-1], which returns 1 if s[0] == s[-1], else 0. @ Swap (s[0] == s[-1]) with the rest of ord_diff. ♂s Vectorized sgn() of ord_diff. This gets the signs of the first differences. 4R Push the range [1..4] onto the stack. `...`M Map the following function over the range [1..4]. Variable x. 0~; Push -1 onto the stack twice. 11 Push 1 onto the stack twice. ( Rotate x to TOS. { Rotate the stack x times, effectively rotating the list [1, 1, -1, -1]. k Wrap it all up in a list. Stack: list of rotations of [1, 1, -1, -1], sgn(*ord_diff) í Get the 0-based index of sgn(*ord_diff) from the list of rotations. -1 if not found. ub This returns 1 only if sgn(*ord_diff) was found, else 0. This checks if the word loops like an infinity word. * Multiply the result of checking if the word s loops and the result of s[0] == s[-1]. Implicit return. ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~16~~ 15 bytes ``` 0=16|3⊥×2-/⎕a⍳⍞ ``` [Try it online!](https://tio.run/##RY6xSgNBEIZ7n2K7rUKigl2Kyd1cdnGzc@7e5rA8kIgQiK2obYpAxCbkCQLpxRfQN9kXOWeusZmPYf75Zrrn9ejhpVtvHvv8cXja5O3npF9xfVVqMr28ebvOu9Pv8Wo05nGX9195/63Uu4Q5tPo5a3C1Aa00wtwh00CIhumtJ8@srU81MySHgdkYrBpma0tq9cW/qEgzW4goQBRR5VJVMR3M0DEXVOJCRFCCiIJdDsLY2hhFHFIU8a1HlP4uIcoD80C0FCF5d88o@EMommGXhgtW1ig0hnT/Bw "APL (Dyalog Unicode) – Try It Online") [Answer] # TI-BASIC, 81 bytes String to pass into the program is in Ans. Returns (and implicitly displays) 1 if the entered word is an Infinity Word, and 0 (or exits with an error message) if it isn't. ``` seq(inString("ABCDEFGHIJKLMNOPQRSTUVWXYZ",sub(Ans,A,1)),A,1,length(Ans min(Ans(1)=Ans(5) and {2,2}=abs(deltaList(deltaList(deltaList(Ans)/abs(deltaList(Ans ``` Errors on any repeated characters, or non-5-letter-words. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç¥DO_s.±¥¥Ä2DиQ* ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/96540/52210). [Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8OHwqVET19zLsKxwqXCpcOEMkTQuFEq//9SVUxFUg) or [verify all test cases](https://tio.run/##HY09asMwFMf3/ymMx1Ay9ALmxXq2RBU950mK6VQayNCpg6EQyFiaPXfwAbp1di7QM/Qirsn@@3gfXg9vx/n8carK4u/rWpTVab5dptHIy7CevqdxGm@fj@b3Z7eaH2bynSUwtZ5hSaNFcEECOhdyB82eFclyk9A7Iz0K1HnjarBSZDQ@Nw08bdhjK4a3UDKkULdfvNi7GJE0x4SnwByxy8wBrYrsGRL8M@plSnVaaFlKLkE0WbmP4z8). **Explanation:** ``` Ç # Convert the (implicit) input string to a list of unicode values # i.e. "RULES" → [82,85,76,69,82] ¥ # Take the deltas # i.e. [82,85,76,69,82] → [3,-9,-7,13] DO # Duplicate and take the sum # i.e. [3,-9,-7,13] → 0 _ # Check if that sum is exactly 0 # (which means the first and last characters are equal) # i.e. 0 and 0 → 1 (truthy) s # Swap so the deltas are at the top of the stack again .± # Get the sign of each # i.e. [3,-9,-7,13] → [1,-1,-1,1] ¥ # Get the deltas of those signs # i.e. [1,-1,-1,1] → [-2,0,2] ¥ # And then get the deltas of those # i.e. [-2,0,2] → [2,2] Ä # Convert them to their absolute values 2Dи # Repeat the 2 two times as list: [2,2] Q # Check if they are equal # i.e. [2,2] and [2,2] → 1 (truthy) * # Check if both are truthy (and output implicitly) # i.e. 1 and 1 → 1 (truthy) ``` ]
[Question] [ Write a function (using as few bytes as possible) that takes a bi-dimensional array of any number of columns and rows in which: * `0` represents empty block, * `1` represents snake block. The function must return the number of possible paths the snake traveled. **Example 1:** Input: ``` [ [1,1,1,1,1], [0,0,0,0,1], [0,0,0,0,1], ] ``` Output: `2` In the example above, the function will return `2` because the answer is either one of: [![enter image description here](https://i.stack.imgur.com/hzXbC.png)](https://i.stack.imgur.com/hzXbC.png) **Example 2:** Input: ``` [ [1,1,1,1], [0,0,1,1], [0,0,1,1], ] ``` Output: `6` In this example the function will return `6` because the answer is either one of: [![enter image description here](https://i.stack.imgur.com/Myx2r.png)](https://i.stack.imgur.com/Myx2r.png) **Note:** When assessing the input, you can assume that: * The arrays representing columns will always have the same sizes (so the arrays are rectangular); * There exists at least 1 valid path; * The snake cannot walk through the edges (as can happen in some versions of snake); * The snake will always have at least 2 blocks; * The snake cannot move diagonally; * The paths are directed. (so, two paths ending at different positions but otherwise looking exactly the same are not the same path, it’ll add up to the total) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16+83=99 bytes Library import statement (16 bytes): ``` <<Combinatorica` ``` Actual function body (83 bytes): ``` Length@HamiltonianCycle[MakeGraph[#~Position~1~Join~{1>0},##||Norm[#-#2]==1&],All]& ``` [Try it online!](https://tio.run/##bcixCsIwEIDhvU9RCHSKYJxbqXRQRKV7KXiW1B4mF4m3SNu8erTgKP/0/RZ40BYYO4gxzytnb0jAzn/HNemLk6Y7D@UBLBp2hEDVuzO6OcND7z08h0aE2r2Q0VFQ4eiQwqi261kKMU0X520jVmLTFoXKWrkzps1i7ZG47MsxSdNRyV@zXLiWS3@YzPED "Wolfram Language (Mathematica) – Try It Online") --- Note that the question just ask for the number of Hamiltonian path in the graph. However, (for some reason) the `HamiltonianPath` function doesn't really work with directed graph ([example](https://tio.run/##fY6xCsIwFEX3/kbBKUWaro1UHOqgUqVOIeCzfaTBJC0xLYj47THg7nrOgXsN@AENeNVBCOdZoedluRvNXVnwo4v4JhKZs9qpvnYwDZySQiQLa@dJ45NfwEpcV@9IPzGk7AgP/IULOY3O8DRLqWAsX0Vd/NGkfU2Yba62Vw47j71IGqes5we00g/VHozSfrQKbBNP85RstRaruC1zIimR8UAIXw)). So, I used the workaround described in [this Mathematica.SE](https://mathematica.stackexchange.com/questions/105196) question: * Add an vertex (called `True`) that is connected to all other vertices. * Count the number of Hamiltonian cycle on the resulting graph. The graph is constructed using `MakeGraph` (annoyingly there are no directly equivalent built-in), using the boolean function `##||Norm[#-#2]==1&`, which returns `True` if and only if one of the arguments is `True` or the distance between the two vertices are `1`. --- `Tr[1^x]` cannot be used instead of `Length@x`, and `<2` cannot be used instead of `==1`. --- `HamiltonianPath` can be used if the graph is undirected, with the function body takes **84** bytes (exactly 1 byte more than the current submission): ``` Length@HamiltonianPath[MakeGraph[#~Position~1,Norm[#-#2]==1&,Type->Undirected],All]& ``` [Try it online!](https://tio.run/##hY3BSsNAEIbv@xQDgaJlC8ZzIxEP9qASQU8x4NhMm6HZ2bA7QaSkrx6j9SIW5L/M9898jENtyKHyGsfHnknL5fLGuzcWVB@m9rWCszl8r4Aj9JFqUA@x77pAMcKkwzsGYdnC/NxsspfxjmSrTb5Cx616YZRi@lLe445uA3ZNmRwKH1nZyyG1Dz64Mlkkl1WWpTP79NHR4upZag60Vqore9221WwsAovmm3xvAPap/clgv/DCHvMHzWDM/@IJPCUeb34NZhg/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), ~~154~~ 134 bytes ``` m=>m.map((r,Y)=>r.map(g=(_,x,y,r=m[y=1/y?y:Y])=>r&&r[x]&&[-1,0,1,2].map(d=>r[r[x]=0,/1/.test(m)?g(_,x+d%2,y+~-d%2):++n,x]=1)),n=0)|n/4 ``` [Try it online!](https://tio.run/##jY3LCoMwEEX3foWbSoKjJtKVEP0OCaGIL1pMlCjFQOmvp8ZdaQWZxXC498w8qmc11/o@LZEam9Z2zEqWy1hWE0IaSsxyvUPP0A1WMKCZ5IbRxBQmK4XLg0DzVQQBjygQoJCK3Wi2iLuEEUhoEi/tvCCJi94dCptLCiZ8R9vGWRgq2HoUY1CM4JdKrrYe1TwObTyMPeoQ93yfU9hHgAMCbn5AYOydUf/AgXrQPqN@fT2ATbUf "JavaScript (Node.js) – Try It Online") ## How? ### Method Starting from each possible cell, we flood-fill the matrix, clearing all cells on our way. Whenever the matrix contains no more **1**'s, we increment the number **n** of possible paths. Each valid path is counted 4 times because of the direction chosen on the last cell, which actually doesn't matter. Therefore, the final result is **n / 4**. ### Recursive function Instead of calling the recursive function **g()** from the callback of the second **map()** like this... ``` m=>m.map((r,y)=>r.map((_,x)=>(g=(x,y,r=m[y])=>...g(x+dx,y+dy)...)(x,y))) ``` ...we define the recursive function **g()** *directly as the callback* of **map()**: ``` m=>m.map((r,Y)=>r.map(g=(_,x,y,r=m[y=1/y?y:Y])=>...g(_,x+dx,y+dy)...)) ``` Despite the rather long formula `y=1/y?y:Y` which is needed to set the initial value of **y**, this saves 2 bytes overall. ### Commented code ``` m => // given the input matrix m[][] m.map((r, Y) => // for each row r[] at position Y in m[][]: r.map(g = ( // for each entry in r[], use g() taking: _, // - the value of the cell (ignored) x, // - the x coord. of this cell y, // - either the y coord. or an array (1st iteration), // in which case we'll set y to Y instead r = m[y = 1 / y ? y : Y] // - r = the row we're currently located in ) => // (and update y if necessary) r && r[x] && // do nothing if this cell doesn't exist or is 0 [-1, 0, 1, 2].map(d => // otherwise, for each direction d, r[ // with -1 = West, 0 = North, 1 = East, 2 = South: r[x] = 0, // clear the current cell /1/.test(m) ? // if the matrix still contains at least one '1': g( // do a recursive call to g() with: _, // a dummy first parameter (ignored) x + d % 2, // the new value of x y + ~-d % 2 // the new value of y ) // end of recursive call : // else (we've found a valid path): ++n, // increment n x // \_ either way, ] = 1 // / do r[x] = 1 to restore the current cell to 1 ) // end of map() over directions ), // end of map() over the cells of the current row n = 0 // start with n = 0 ) | n / 4 // end of map() over the rows; return n / 4 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` ŒṪŒ!ạƝ€§ÐṂL ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7Vx2dpPhw18Jjcx81rTm0/PCEhzubfP4fbgfy/v@P5ormUlCINtSBwlgdENdABwKxcIEIWQdCARZOLFcsAA "Jelly – Try It Online") --- ## Explanation. ``` ŒṪ Positions of snake blocks. Œ! All permutations. For each permutation: ạƝ€ Calculate the absolute difference for each neighbor pair § Vectorized sum. Now we have a list of Manhattan distance between snake blocks. Each one is at least 1. ÐṂL Count the number of minimum values. Because it's guaranteed that there exists a valid snake, the minimum value is [1,1,1,...,1]. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~257~~ ~~246~~ ~~241~~ ~~234~~ ~~233~~ ~~227~~ ~~214~~ 210 bytes ``` lambda b:sum(g(b,i,j)for j,l in e(b)for i,_ in e(l)) e=enumerate def g(b,x,y):d=len(b[0])>x>-1<y<len(b);c=eval(`b`);c[d*y][d*x]=0;return d and b[y][x]and('1'not in`c`or sum(g(c,x+a,y)+g(c,x,y+a)for a in(1,-1))) ``` [Try it online!](https://tio.run/##dY7BbsMgEETvfMXeAvVGMj0mIT9CUQ0Gt44wjiiuzNe7xK5UqXW1Epq3zGjnntP7GJ6XTrwsXg/GajCnj2mgb9RgjzfWjRFu6KEP4KhZscfXDT1jxAkXpsFFnRyxroNHbsbMTlZ4F6iRtWLX@Xrkl3xZF@zcCvepPW1MU7S0T1mVZ1aiPkeXphjAgg4WjCwfsyqSHvghjKkcbdqmFNj6tThXulyqVom50ms7XWyU45EzxpZ77EOCjkoCIDl@j8IH1rjNDipGyF70x7kDf0L/@H6Fli8 "Python 2 – Try It Online") --- Saved * -8 bytes, thanks to Kevin Cruijssen * -14 bytes, thanks to user202729 [Answer] # Python 2, 158 bytes ``` E=enumerate g=lambda P,x,y:sum(g(P-{o},*o)for o in P if x<0 or abs(x-o[0])+abs(y-o[1])<2)+0**len(P) lambda L:g({(x,y)for y,r in E(L)for x,e in E(r)if e},-1,0) ``` [Try it online!](https://tio.run/##bYw9C4MwEIb3/Iob7/SE2KGD2LFbB3dxsDRaQRNJLUTE325jSqGUcje8z3084zzdjT5s2/mk9HNQtp6UaE99PVxvNRTseM4ezwFbLJLFrBwZaowFA52GAroGXC7BD@rrA11iSllRvOfZ57Si/ECxjKJeaSxINB/vJWtxQe8OspntrjvjJaBj9UZL3q9WTlKWtI220xM2WAqAMuVQFe8gWf6DihiOJH7@YO/3qU/yG8ImvKVH2l4) [Answer] # [Haskell](https://www.haskell.org/), 187 155 bytes ``` r=filter l=length (a,b)?(x,y)=abs(a-x)+abs(b-y)==1 l#x=sum[p!r(/=p)l|p<-x] p![]=1 p!l=l#r(p?)l f x|l<-[(i,j)|i<-[0..l x-1],j<-[0..l(x!!0)-1],x!!i!!j>0]=l#l ``` [Try it online!](https://tio.run/##dY/BbsMgEETvfAUoPYAKrp1cQ/whiANW7AZn4yLsSETyvzubOFIjlbKXmbc7I3Fy47kFWJaoOw9TGwloaIfv6US4k42oeZI3oV0zcqeS@HyIRiHRFYFN0uP1YgKL/EsHAXPYq2RJYMbiOjCs2kQeagGko2mGvTLcy17MHlVZFECTqqzsX44nxkrxICg8Y/2htNgAS@dbOFZUU0MoPlPJ11i5glKukwHoLSHPhu2fhvfzjH3L7n6z/xxnsxfnB0wef57LEP0w0Q/a0fVHObjNwd1yBw "Haskell – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 28 bytes ``` +/×/1=2(1⊥∘|-)/x[⌂pmat≢x←⍸⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@2/uHp@oa2RhqGj7qWPuqYUaOrqV8R/ainqSA3seRR56KKR20THvXueNQ3NRak4X8a16O2iUCeV7C/n4J6dLShDhTG6kQb6EAgKjtWnQuHJqgyVFasOgA "APL (Dyalog Extended) – Try It Online") A full program that accepts a matrix. ]
[Question] [ First, study [this puzzle](https://puzzling.stackexchange.com/questions/5573/continue-the-pattern-of-circles) to get a feel for what you will be producing. Your challenge is to write a program or function which will output a circular graphic like the ones from the puzzle, given a (base 10) number between 1 and 100 (inclusive). This is similar to [this challenge](https://codegolf.stackexchange.com/questions/4433/optimal-short-hand-roman-numeral-generator), except that you will be producing a graphic rather than roman numerals. The following circles represent the numbers 1-10, from left to right: ![circle pattern](https://i.stack.imgur.com/hJSY3.png) As the answer to the puzzle states, your graphic should read like a roman numeral from the inside-out, where the line thickness represents the roman numeral symbols and the entire graphic represents the number. For your reference, here are the line thicknesses which you will need. Each line should have a 3px padding between it and the next. ``` Number Roman Numeral Line Width 1 I 1px 5 V 3px 10 X 5px 50 L 7px 100 C 9px ``` Please post a sample or two of your output. Assume input is correct, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/), etc and so forth. This is code golf, so fewest bytes win. In the event of a tie, most votes win. Good luck! [Answer] ## Mathematica - ~~166~~ 181 bytes A bit more concise than the other Mathematica answer, thanks in part to a more point-free style. ``` c = Characters; r = Riffle; Graphics[r[{0, 0}~Disk~# & /@ Reverse@Accumulate[ l = {3} ~Join~ r[2 Position[c@"IVXLC", #][[1, 1]] - 1 & /@ c@IntegerString[#, "Roman"], 3]], {White, Black}], ImageSize -> 2 Total@l] & ``` All whitespace is for clarity only. This defines an anonymous function which returns the desired graphic. ## Animation ![Animated circles](https://i.stack.imgur.com/kn8mf.gif) Generating an animated GIF of the number circles is trivial in Mathematica, which has built-in functions for animating and exporting sequences of arbitrary objects. Assuming the above code has just been executed, ``` Table[Show[%@n, PlotRange -> {{-100, 100}, {-100, 100}}, ImageSize -> 200], {n, 1, 399, 1}]; Export["animcircles.gif", %] ``` ## Example Output ![Example output](https://i.stack.imgur.com/1j7PY.png) [Answer] # Common Lisp - ~~376~~ ~~331~~ 304 bytes ``` (use-package(car(ql:quickload'vecto)))(lambda(n o &aux(r 3)l p)(map()(lambda(c)(setf l(position c" I V X L C D M")p(append`((set-line-width,l)(centered-circle-path 0 0,(+(/ l 2)r))(stroke))p)r(+ r l 3)))(format()"~@R"n))(with-canvas(:width(* 2 r):height(* 2 r))(translate r r)(map()'eval p)(save-png o))) ``` # Examples ![enter image description here](https://i.stack.imgur.com/N9fL3.png) (1) ![enter image description here](https://i.stack.imgur.com/2kErP.png) (24) ![enter image description here](https://i.stack.imgur.com/KXKSq.png) (104) ![enter image description here](https://i.stack.imgur.com/yPXOj.png) (1903) ![enter image description here](https://i.stack.imgur.com/rAhUE.png) (3999) ## Animation For numbers from 1 to 400: ![New](https://i.stack.imgur.com/TaFd4.gif) **NB:** For the record, this animation is done as follows: I have a modified version of the code, named `rings` which returns the width of the produced image. Hence, the result of the the following loop is the maximum size, here **182**: ``` (loop for x from 1 to 400 maximize (rings x (format nil "/tmp/rings/ring~3,'0d.png" x))) ``` The whole loop takes 9.573 seconds. That gives approximately 24ms for each integer. Then, in a shell: ``` convert -delay 5 -loop 0 -gravity center -extent 182x182 ring*png anim.gif ``` ## Ungolfed ``` (ql:quickload :vecto) (use-package :vecto) (lambda (n o) (loop with r = 3 for c across (format nil "~@R" n) for l = (1+ (* 2(position c"IVXLCDM"))) for h = (/ l 2) collect `(,(incf r h),l) into p do (incf r (+ h 3)) finally (with-canvas(:width (* 2 r) :height (* 2 r)) (loop for (x y) in p do (set-line-width y) (centered-circle-path r r x) (stroke)) (save-png o)))) ``` ## Explanations * The function takes an integer `N` between 1 and 3999 and a filename * I use `(format nil "~@R" N)` to convert from decimal to roman. For example: ``` (format nil "~@R" 34) => "XXXIV" ``` The `~@R` [format control string](https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html) is specified to work for integers between 1 and 3999. That's why there is a limitation for the range of allowed inputs. * I iterate over the resulting string to build a list `P` containing `(radius width)` couples, for each numeral C. + The width is a simple linear mapping: I use the constant string "IVXLCDM" to compute the position of C in it. Multiplying by two and adding one, we obtain the desired value: ``` (1+ (* 2 (position c "IVXLCDM"))) ``` This is however done slightly differently in the golfed version: ``` (position c " I V X L C D M") ``` + The computation of each radius takes into account the width of each ring as well as empty spaces between rings. Without any speed optimization, computations remain precise because they are not based on floats, but rational numbers. *Edit*: I changed the parameters to comply with the padding rules. * Once this is done, I know the required size of the resulting canvas (twice the latest computed radius). * Finally, I draw a circle for each element of `P` and save the canvas. [Answer] ## HTML+JQuery, 288 **HTML** ``` <canvas> ``` **JS** ``` r=3;w=9;c=$('canvas').get(0).getContext('2d') for(i=prompt(),e=100;e-.1;e/=10){ if((x=Math.floor(i/e)%10)==4)d(w)+d(w+2) else if(x==9)d(w)+d(w+4) else{if(x>4)d(w+2) for(j=x%5;j;j--)d(w)} w-=4} function d(R){c.lineWidth=R c.beginPath() c.arc(150,75,r+=R/2,0,7) c.stroke() r+=R/2+3} ``` ``` r=3;w=9;c=$('canvas').get(0).getContext('2d') for(i=prompt(),e=100;e-.1;e/=10){ if((x=Math.floor(i/e)%10)==4)d(w)+d(w+2) else if(x==9)d(w)+d(w+4) else{if(x>4)d(w+2) for(j=x%5;j;j--)d(w)} w-=4} function d(R){c.lineWidth=R c.beginPath() c.arc(150,75,r+=R/2,0,7) c.stroke() r+=R/2+3} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <canvas> ``` [Fiddle](http://jsfiddle.net/3dg5ch42/) [Answer] # Java, 565 ``` import java.awt.*;class Z{public static void main(String[]s){int i=new Byte(s[0]),j=i/10,k=i%10;String t="",u;if(j>8)t="59";if(j>9)t="9";if(j==4)t="57";else if(j<9){t=j>4?"7":"";j-=j>4?5:0;if(j>0)t+="5";if(j>1)t+="5";if(j>2)t+="5";}if(k>8)t+="15";if(k==4)t+="13";else if(k<9){t+=k>4?"3":"";k-=k>4?5:0;if(k>0)t+="1";if(k>1)t+="1";if(k>2)t+="1";}u=t;Frame f=new Frame(){public void paint(Graphics g){g.setColor(Color.BLACK);int x=0;for(char c:u.toCharArray()){int z=c-48,q=x;for(;x<q+z;)g.drawOval(99-x,99-x,x*2,x++*2);x+=3;}}};f.setSize(200,200);f.setVisible(1>0);}} ``` ## Examples ### 15 ![15](https://i.stack.imgur.com/dDXsY.png) ### 84 ![84](https://i.stack.imgur.com/IsVtl.png) ### 93 ![93](https://i.stack.imgur.com/M2DEU.png) Formatted nicely: ``` import java.awt.*; class Z { public static void main(String[] s) { int i = new Byte(s[0]), j = i / 10, k = i % 10; String t = "", u; if (j > 8) t = "59"; if (j > 9) t = "9"; if (j == 4) { t = "57"; } else if (j < 9) { t = j > 4 ? "7" : ""; j -= j > 4 ? 5 : 0; if (j > 0) t += "5"; if (j > 1) t += "5"; if (j > 2) t += "5"; } if (k > 8) t += "15"; if (k == 4) { t += "13"; } else if (k < 9) { t += k > 4 ? "3" : ""; k -= k > 4 ? 5 : 0; if (k > 0) t += "1"; if (k > 1) t += "1"; if (k > 2) t += "1"; } u = t; Frame f = new Frame() { public void paint(Graphics g) { g.setColor(Color.BLACK); int x = 0; for (char c : u.toCharArray()) { int z = c - 48, q = x; for (; x < q + z;) { g.drawOval(99 - x, 99 - x, x * 2, x++ * 2); } x += 3; } } }; f.setSize(200, 200); f.setVisible(1 > 0); } } ``` [Answer] ## Mathematica 9 - 301 249 bytes :D It feels cheaty to use the built-in converting to Roman numerals, but hey. ``` l=Length;k=Characters;r@n_:=(w=Flatten[Position[k@"IVXLC",#]*2-1&/@k@IntegerString[n,"Roman"]];Show[Table[Graphics@{AbsoluteThickness@w[[i]],Circle[{0,0},(Join[{0},Accumulate[3+w]]+3)[[i]]+w[[i]]/2]},{i,Range@l@w}],ImageSize->{(Total@w+(l@w)*3)*2}]) ``` (When I did this last night I didn't have much time, but I realized it could be golfed down way more. And I also took some hints from David Zhang... :D Thanks!) A bit more clearly: ``` l=Length; k=Characters; r@n_:= ( w=Flatten[Position[k@"IVXLC",#]*2-1&/@k@IntegerString[n,"Roman"]]; Show[Table[Graphics@{AbsoluteThickness@w[[i]],Circle[{0,0},(Join[{0},Accumulate[3+w]]+3)[[i]]+w[[i]]/2]},{i,Range@l@w}],ImageSize->{(Total@w+(l@w)*3)*2}] ) ``` This is a function that you can call like this: ``` r[144] ``` ![enter image description here](https://i.stack.imgur.com/q8xdZ.png) Or, you can show the results from values **a** to **b** with: `Table[r[i],{i,a,b}]` *Note*: This only works for values up to 399. [Answer] # Python 2, ~~322~~ 296 The script reads the number to be converted from stdin, and outputs the image as SVG markup. .. I use 'red' instead of 'black', because it saves 2 chars :) Here are some samples : for 23 : <http://jsfiddle.net/39xmpq49/> for 42 : <http://jsfiddle.net/7Ls24q9e/1/> ``` i=input();r=9 def R(n,p): global r,i;i-=n;print '<circle r="{0}" stroke-width="{1}"/>'.format(r,p);r+=p+3 print '<svg viewBox="-50 -50 99 99" fill="none" stroke="red">',[[R(n,int(p)) for p in s*int(i/n)] for n,s in zip([100,90,50,40,10,9,5,4,1],'9/59/7/57/5/15/3/13/1'.split('/'))]and'','</svg>' ``` [Answer] # JavaScript ~~342~~ ~~334~~ 308 ``` function R(n){var v=document,o=[],x=1,c=v.body.appendChild(v.createElement('canvas')).getContext('2d') while(n)v=n%10,y=x+2,o=[[],[x],[x,x],[x,x,x],[x,y],[y],[y,x],[y,x,x],[y,x,x,x],[x,x+=4]][v].concat(o),n=(n-v)/10 v=3 while(x=o.shift())c.lineWidth=x,c.beginPath(),c.arc(150,75,v+x/2,0,7),c.stroke(),v+=x+3} for (var i = 1; i <= 100; i++) { R(i); } ``` ]
[Question] [ When it comes to eating candy, I hold myself to higher standards than the typical layperson. There is a delicate balance between "mixing it up" and "saving the best for last." In this challenge, you will be given a string of characters in which each character represents a piece of candy. Different characters (case-sensitive) represent different types of candy. Your program must then determine the correct order of candy consumption, based on the procedure below. You can write either a complete program (STDIN/STDOUT) or a named function to accomplish this task. Let's say that my candy stash is `oroybgrbbyrorypoprr`. First, I sort the candy into piles of the same type, with larger quantities at the top, using lower ASCII character values as a tie-breaker. ``` rrrrrr oooo bbb yyy pp g ``` Then, I take each row of candy and equally-space them along an interval. For example, if there are 3 pieces of candy, one is placed 1/3 of the way, 2/3 of the way, and at the end. ``` .r.r.r.r.r.r ..o..o..o..o ...b...b...b ...y...y...y .....p.....p ...........g ``` Then, I go down each column to create my final candy order, `rorbyroprbyorrobypg`. ## Input A string which contains the candy stash. The input for the above example could have been: ``` oroybgrbbyrorypoprr ``` ## Output A string containing the candy reorganized into the correct order of consumption. ``` rorbyroprbyorrobypg ``` ## Scoring This is code golf. The shortest answer in bytes wins. Standard code-golf rules apply. [Answer] # CJam, ~~78 68 61 45 42 39 31~~ 30 bytes ``` l$:L{L\/,~}${:DM+:MD/,LD/,d/}$ ``` Takes the input string via STDIN Inspired by recursive's approach, but a little different. No need of transpose or rectangle at all!. **How it works:** ``` l$:L "Sort the input line and store it in L"; { }$ "Sort the string based on this code block output"; L\/,~ "Sort based on number of occurrences of each"; "character in the full string"; { }$ "Sort the sorted string again"; :DM+:M "Store each character in D, add to M and update M"; D/, "Count occurrences of D in M"; LD/, "Count occurrences of D in L"; d/ "Sort string based on the ratio of two occurrences"; ``` (Sad that CJam can no longer complete with Pyth due to need of so much bloat as syntax) [Try it here](http://cjam.aditsu.net/) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 25 ``` shCoc/NhN/zhNm>o_/zZSzdUz ``` Uses an all new algorithm, inspired by [this answer](https://codegolf.stackexchange.com/a/41100/20080). ``` (implicit) z = input() (implicit) print s combine list of strings into one string h first list in C matrix transpose of (e.g. first characters in first list, etc.) o order_by(lambda N: c float_div( /NhN N.count(N[0]), /zhN z.count(N[0])), m map(lambda d: > slice_head( o order_by(lambda Z: _/zZ -1*z.count(Z), Sz sorted(z)), d d), Uz range(len(z)) ``` Step by step: 1. First, we sorted the characters by their commonness, ties broken alphabetically. This is `o_/zZSz`. `o` is the same as Python's `sorted(<stuff>,key=<stuff>)`, with a lambda expression for the key, except it keeps it as a string. 2. Then we generate a list of the prefixes of that string, from length `len(z)` to length 1. `>` is equivalent to python's `<stuff>[<int>:]`. 3. Then, we reorder this list of prefix strings by the fractional location, 0 being the left edge and 1 being the right, of the first character of the prefix on the rectangular layout seen in the question. `/NhN` counts how many times the first character in the prefix occurs in the prefix, while `/zhN` gives the number of occurrences of the first character in the prefix in the string as a hole. This assigns each prefix being led by each character in a group a different fraction, from `1/k` for the right most occurrence of that character to `k/k` for the left most. Reordering the prefix list by this number gives the appropriate position in the layout. Ties are broken using the prior ordering, which was first by count then alphabetical, as desired. 4. Finally, we need to extract the first character from each prefix string, combine them into a single string, and print them out. Extracting the first characters is `hC`. `C` performs a matrix transpose on the list, actually `zip(*x)` in Python 3. `h` extracts the first row of the resultant matrix. This is actually the only row, because the presence of the 1 character prefix prevents any other complete rows from being formed. `s` sums the characters in this tuple into a single string. Printing is implicit. **Test:** ``` $ pyth -c 'shCoc/NhN/zhNm>o_/zZSzdUz' <<< 'oroybgrbbyrorypoprr' rorbyroprbyorrobypg ``` Incremental program pieces on `oroybgrbbyrorypoprr`: ``` Sub-Piece Output Sz bbbgoooopprrrrrryyy o_/zNSz rrrrrroooobbbyyyppg (uses N because o uses N on first use.) m>o_/zNSzdUz ['rrrrrroooobbbyyyppg', 'rrrrroooobbbyyyppg', 'rrrroooobbbyyyppg', 'rrroooobbbyyyppg', 'rroooobbbyyyppg', 'roooobbbyyyppg', 'oooobbbyyyppg', 'ooobbbyyyppg', 'oobbbyyyppg', 'obbbyyyppg', 'bbbyyyppg', 'bbyyyppg', 'byyyppg', 'yyyppg', 'yyppg', 'yppg', 'ppg', 'pg', 'g'] oc/NhN/zhNm>o_/zZSzdUz ['roooobbbyyyppg', 'obbbyyyppg', 'rroooobbbyyyppg', 'byyyppg', 'yppg', 'rrroooobbbyyyppg', 'oobbbyyyppg', 'pg', 'rrrroooobbbyyyppg', 'bbyyyppg', 'yyppg', 'ooobbbyyyppg', 'rrrrroooobbbyyyppg', 'rrrrrroooobbbyyyppg', 'oooobbbyyyppg', 'bbbyyyppg', 'yyyppg', 'ppg', 'g'] Coc/NhN/zhNm>o_/zZSzdUz [('r', 'o', 'r', 'b', 'y', 'r', 'o', 'p', 'r', 'b', 'y', 'o', 'r', 'r', 'o', 'b', 'y', 'p', 'g')] shCoc/NhN/zhNm>o_/zZSzdUz rorbyroprbyorrobypg ``` --- Old answer: # [Pyth](https://github.com/isaacg1/pyth), 34 ``` ssCm*+t*u*G/zHS{-zd1]kd/zdo_/zNS{z ``` This program works by calculating how many times to replicate a certain sublist. The sub-list looks like `['', '', '', '', ... , 'r']`. The total length of this sub-list is the product of the number of occurrences of all of the other candies, which is `u*G/zHS{-zd1`. The full sublist is constructed by replicating the list of the empty string ,`]k`, that many times, then removing and element with `t` and add the candy name to the end with `+d`. Then, this sub-list is replicated as many times as that candy is found in the input, `/zd`, ensuring each candy's list is of equal length. Now, with this function mapped over all of the unique candies in proper sorted order (`o_/zNS{z`), we have a rectangle similar to the one in the question statement, but with empty strings instead of periods. Doing a matrix transpose (`C`) followed by two summations (`ss`) gives the final string. Verification: ``` $ pyth programs/candy.pyth <<< 'oroybgrbbyrorypoprr' rorbyroprbyorrobypg ``` [Answer] # Perl 5 - 62 61 code + 1 flag. ``` #!perl -n print map/(.$)/,sort map/(.$)/*$_/$$1.~$_.$1,map++$$_.$_,/./g ``` First split the input into character array - `/./g`. Add occurrence index to each letter leaving the counts in variables `$a`..`$z` with `map++$$_.$_`. Now the array is: ``` 1o 1r 2o 1y 1b 1g 2r 2b 3b 2y 3r 3o 4r 3y 1p 4o 2p 5r 6r ``` Then convert it to a sort key concatenating: ratio `$_/$$1`, count tie breaker `~$_` and ASCII value tie breaker `$_`. This will result in (here with added spaces for clarity). ``` 0.25 18446744073709551614 o 0.166666666666667 18446744073709551614 r 0.5 18446744073709551613 o 0.333333333333333 18446744073709551614 y 0.333333333333333 18446744073709551614 b 1 18446744073709551614 g 0.333333333333333 18446744073709551613 r 0.666666666666667 18446744073709551613 b 1 18446744073709551612 b 0.666666666666667 18446744073709551613 y 0.5 18446744073709551612 r 0.75 18446744073709551612 o 0.666666666666667 18446744073709551611 r 1 18446744073709551612 y 0.5 18446744073709551614 p 1 18446744073709551611 o 1 18446744073709551613 p 0.833333333333333 18446744073709551610 r 1 18446744073709551609 r ``` This can be sorted with lexicographical (default) order. In the end extract last character and print: `print map/(.$)/` [Answer] ## Python 3.x - 124 bytes ``` C=input() print("".join(s[1]for s in sorted(enumerate(C),key=lambda t:((C[:t[0]].count(t[1])+1+1e-10)/C.count(t[1]),t[1])))) ``` [Answer] ## Mathematica, ~~123~~ ~~119~~ 118 bytes ``` f=FromCharacterCode[s=SortBy;#&@@@s[Join@@(s[Tally@ToCharacterCode@#,-Last@#&]/.{x_,n_}:>({x,#/n}&~Array~n)),{Last}]]& ``` Defines a named function `f`. Ungolfed: ``` f = FromCharacterCode[ s = SortBy; # & @@@ s[ Join @@ ( s[ Tally@ToCharacterCode@#, -Last@# & ] /. {x_, n_} :> ({x, #/n} &~Array~n) ), {Last} ] ] & ``` Using built-in rational types seemed like a good idea for this. Of course, this is nowhere near CJam. Basically, I'm representing the grid shown in the challenge as a list of pairs. The first thing in the pair is the character code, the second is it's position as a fraction less than or equal to 1 (the final column being 1). Having made sure that the individual characters are already in the right order, I just need to sort this stably by said fraction to get the desired result. [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 45 ~~47 48 51~~ This could also almost certainly be golfed further ;) ``` Ko_/zNS{zFGK~Y]*+*t/u*GHm/zdK1/zG]k]G/zG)ssCY ``` Works by building a list of lists, where each inner list is a row of empty strings and the name of the candy. This list is transposed and then the inner lists are joined followed by these lists being joined. Thanks @isaacg for reminding me about sum! [Answer] **APL: 38** ``` v⌷⍨⊂⍋⌽(n/-n),⍪∊+\¨n⍴¨÷n←{≢⍵}⌸v←{⍵[⍋⍵]} ``` **Explanation:** ``` v←{⍵[⍋⍵]} orders input string n←{≢⍵}⌸v counts how many times each element appears in v ∊+\¨n⍴¨÷n makes incremental sums in each letter "group" ⍋⌽(n/-n),⍪ appends number of elements in letter group and orders the obtained matrix v⌷⍨⊂ orders vector v with computed indices ``` Can be tested on tryapl.org [Answer] # R - 166 characters ``` library("plyr");s=function(a){l=table(strsplit(a,s="")[[1]]);l=ldply(l[order(-l,names(l))],function(n)data.frame(seq_len(n)/n));paste(l[order(l[[2]]),1],collapse="")} ``` ungolfed version ``` library("plyr") s <- function(a) { tbl <- table(strsplit(a, split = "")[[1]]) tbl <- tbl[order(-tbl, names(tbl))] tbl <- ldply(tbl, function(n) {data.frame(seq_len(n)/n)}) paste(tbl[order(tbl[[2]]),1], collapse = "") } ``` Explanation: * Split into individual characters * Tabulate number of each character * Sort table into most frequent and then by lexical order * Index positions for selection at 1/n, 2/n, 3/n, ... n-1/n, 1 where n is the number of candies * Sort candy names by index (`order` is stable in sorting, so will maintain the most frequent/lexical naming order when a tie in the index, particularly important with the last candies) * Concatenate the candy names together to make the output string --- The matrix nature of the problem made me think R might have a shot at this, but the best literal interpretation of the algorithm I could do was 211 characters: ``` l=function(a){l=table(strsplit(a,s="")[[1]]);l=l[order(-l,names(l))];o=Reduce(`*`,l);m=matrix("",nc=o,nr=length(l));for(r in seq_along(l)){x=l[r];for(c in seq_len(x)*o/x){m[r,c]<-names(x)}};paste(m,collapse="")} ``` ungolfed: ``` l <- function(a) { tbl <- table(strsplit(a, split = "")[[1]]) tbl <- tbl[order(-tbl, names(tbl))] o <- Reduce(`*`, tbl) m <- matrix("", ncol = o, nrow = length(tbl)) for (r in seq_along(tbl)) { for (c in seq_len(tbl[r])*o/tbl[r]) { m[r,c] <- names(tbl[r]) } } paste(m, collapse="") } ``` [Answer] # Pyth, 29 bytes This is a direct translation of my [CJam answe](https://codegolf.stackexchange.com/a/40914/31414)r in Pyth ``` oc/|$Y.append(N)$YN/zNo_/zZSz ``` [Try it online here](http://isaacg.scripts.mit.edu/pyth/index.py) --- There is a rather long story behind this solution and @isaacg helped me a lot in understanding this new language. Ideally this is the exact word to word translation of my CJam code (**17 bytes**): ``` oc/~kNN/zNo_/zZSz ``` which means: ``` o order_by(lambda N: c div( / count( ~kN k+=N, #Update k (initially ""), add N N N), #Count N in updated k /zN count(z, N)), o order_by(lambda Z: _ neg( /zZ count(z, Z)), Sz sorted(z))) ``` But sadly Python does not return anything in a `+=` call, so that was not a valid Python code, thus an invalid Pyth code too as in Pyth, a lambda can only be a return statement. Then I looked into various methods and finally found that Python's `list.append` returns a `None` value, which I can use. Making the code to be (**19 bytes**): ``` oc/|aYNYN/zNo_/zZSz ``` which means: ``` o order_by(lambda N: c div( / count( |aYN (Y.append(N) or Y Y) #Update Y (initially []), append N N N), #Count N in updated Y /zN count(z, N)), o order_by(lambda Z: _ neg( /zZ count(z, Z)), Sz sorted(z))) ``` But sadly, support of `a` (append) was removed from Pyth and the version which do has the support, does not have the support for `o`. *Update : `a` support has been added back in Pyth now so the above 19 byte code will work in the online compiler. But since this is a new feature which was added after the OP, I am not putting it up as my score and letting the 29 byte code as my solution.* Therefore I had to rely on raw Python in that case, making the code to be ``` o order_by(lambda N: c div( / count( |$Y.append(N)$ (Y.append(N) or Y Y) #Update Y (initially []), append N N N), #Count N in updated Y /zN count(z, N)), o order_by(lambda Z: _ neg( /zZ count(z, Z)), Sz sorted(z))) ``` ]
[Question] [ Given a date as input in any convenient format, output a calendar with that date as the exact center of a five-week window. The header of the calendar must include the two-letter abbreviations for the days of the week (i.e., `Su Mo Tu We Th Fr Sa`). Three-letter or other abbreviations of the days are not allowed. For example, given `April 2 2019` as input, the output should be ``` Sa Su Mo Tu We Th Fr 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` so that the given date is the exact middle of the calendar. Given `February 19 2020`, output ``` Su Mo Tu We Th Fr Sa 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 1 2 3 4 5 6 7 ``` For `September 14 1752`, show the following: ``` Mo Tu We Th Fr Sa Su 28 29 30 31 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 1 ``` --- * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * The input is guaranteed non-empty and valid (i.e., you'll never receive `""` or `Feb 31` etc.). * Assume Gregorian calendar for all dates. * Leap years must be accounted for. * Input dates will range from `Jan 1 1600` to `Dec 31 2500`. * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately. * Leading zeros on the single-digit days are allowed, as are aligning the single-digit days to be left-aligned instead. * [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/), ~~77~~ 72 bytes ``` function(d,`~`=format)write(c(strtrim(d+-3:3~"%a",2),d+-17:17~"%e"),1,7) ``` [Try it online!](https://tio.run/##DctBCoQwDEDR/ZxCAkLCRG3roiDjzoNY1EIXKsSIO6/e6fI/@JJj9WuqHO9j0XQeuPL8zmM8ZQ9KjyTdcMFLRSXtuH6bfuhfqAOwIy5p/WB9gQ2ILXvKEcPVTqFs4IwznXGdNUD0yX8 "R – Try It Online") Fixed output to use 2 letter day abbreviations. -1 byte using `strtrim` thanks to [Aaron Hayman](https://codegolf.stackexchange.com/users/85453/aaron-hayman). Pads date numbers with leading 0s; takes input as a `Date`, which can be created by using `as.Date("YYYY/MM/DD")`. Weirdly short for an R [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") answer... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~175~~ ~~174~~ ~~172~~ ~~171~~ 160 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¦WΘ1š-1šVтFY`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVY})DJIJk18+£35.£¬.•4ιõ÷‡o‹ƶ¸•2ôs`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7%._s€нT‰J«7ô» ``` Input in the format `[day, month, year]`. Output with leading `0`s for single-digit days, and lowercase `mo` through `su` (+1 byte can be added if titlecase is mandatory). **[Try it online](https://tio.run/##yy9OTMpM/f//0LLwczMMjy7UBeKwi01ukQlGh7cYeJ/bYXJ4WqiLUWBmjJFFhPbh1Tbmqoc7jQ3Pbax91LAzM/LQGjuDw6sjDQ/tOz7X5XBrsYuhEUjczvDw6hhDl@NzDy2xM6qtPT43LLJW08XL0yvb0EL70OIgY1MgcWiN3qOGRSbndh7eenj7o4aF@UCdx7Yd2gEUBNpdnBB6eIIxUMjQSEvbztBYy/Tw9mIQP@LcxkMrLzapupgc3n5o3cUmILkSzDy0XUPT5Uh7MRD5m6vqxRc/alpzYW/Io4YNXodWmx/ecmj3///RhpY6RjpGBkYGsQA) or [verify all test cases](https://tio.run/##JY1RS8JQFMe/SghC6k127iZzEfPlImQPEqg5VLKgBwkymAY@DMYgoreeohcf1AhkIxLMKVEP51Z7G/kV9kXWteCcw@//g8O/a56cds7iq8T@xWW/t7uVKAxIotzv/QcyiPHpKHyAr9GO2NraKRptyufSQbhU@H2V0cNOk@brGe7uqUl@K0M4syJ71THQ0yXuGoAfwZDxa5MB3XgduNsEFgzxUaeWFQxrhpVipUHpHPIZnMi5LE7Qy0b2WAlX/JX7kT3qisfvBS6FFNVmu8rvZKGApjM6yOkc981NrocznK6dJFO4j89rR9zpH6K/nWKfN6aYsprMHpuR4/28VyL7pYSuyuf4FhNcFCrFphU3GpQohEqgtUgDNEIFU2nDCtEIqDkqmMoEKAFNklqtXw).** Holy shit.. This might be my new record for longest 05AB1E answer, and then I include some very complex [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenges I did... >.> [EDIT: Hmm ok, almost.. ;p](https://codegolf.stackexchange.com/a/170427/52210) **Important note:** 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds. So because of that, almost all of the code you see are manual calculations to calculated the previous and next days (including transition over years and keeping in mind the leap years), and calculating the day of the week by using [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence). Huge parts of the code are copied from [this earlier 05AB1E answer of mine](https://codegolf.stackexchange.com/a/173126/52210), which will also be relevant for the explanation below. **Explanation:** We start by going to the first day of the previous month: ``` ¦ # Remove the first item (the days) from the (implicit) input W # Get the minimum (without popping the list itself) # (since the year is guaranteed to be above 1599, this is the month) Θ # Check if its exactly 1 (1 if 1, 0 if in the range [2,31]) 1š # Prepend a 1 as list (so we now have either [1,1] or [1,0] - # Subtract this from the month and year 1š # And prepend a 1 for the day V # Pop and store this first day of the previous month in variable `Y` ``` Then I use that date as start date, and calculate the next 100 days: ``` тF # Loop 100 times: Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV # Calculate the next day in line # (see the linked challenge above for a detailed explanation of this) Y # And leave it on the stack }) # After the loop: wrap the entire stack into a list, which contains our 100 days ``` Then, with the input-date as the middle, I only leave the 17 before and 17 after that input-date from the list: ``` DJ # Duplicate the 100 dates, and join the day/month/year together to strings IJ # Push the input, also joined together k # Get the 0-based index of the input in this list # (the joins are necessary, because indexing doesn't work for 2D lists) 18+ # Add 18 to this index (18 instead of 17, because the index is 0-based) £ # Only leave the first index+18 items from the 100 dates 35.£ # Then only leave the last 35 items ``` Now we have our 35 days. Next step is to calculate the day of the week, and create the header of the output-table: ``` ¬ # Get the first date of the list (without popping the list itself) .•4ιõ÷‡o‹ƶ¸• # Push compressed string "sasumotuwethfr" 2ô # Split it into chunks of size 2 s # Swap to get the first date again `UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7% # Calculate the day of the week (sa=0; su=1; ...; fr=6) # (see the linked challenge above for a detailed explanation of this) ._ # Rotate the list of strings that many times ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•4ιõ÷‡o‹ƶ¸•` is `"sasumotuwethfr"`. Then we create the days to fill the table itself based on our earlier created list of dates. Which we'll merge together with the header. After which we can print the final result: ``` s # Swap to get the list of dates again €н # Only leave the first item of each date (the days) T‰ # Take the divmod 10 of each J # Join those divmod results together # (we now have leading 0s for single-digit days) « # Merge this list together with the header list 7ô # Split it into chunks of size 7 » # Join each inner list by spaces, and then each string by newlines # (and output the result implicitly) ``` [Answer] # JavaScript (ES6), ~~141~~ 126 bytes *Saved 15 bytes by borrowing `.toUTCString().slice(0,2)` from [Neil's answer](https://codegolf.stackexchange.com/a/182691/58563)* Takes input as a Date object. ``` f=(d,n=0)=>n<42?(D=new Date(d-864e5*(24-n)),n<7?D.toUTCString().slice(0,2):(i=D.getDate())>9?i:' '+i)+` `[++n%7&&1]+f(d,n):'' ``` [Try it online!](https://tio.run/##fc2xTsMwFIXhvU/hhdoX25FtuQRHTTOQiQGGlqmq1ChxIqPIrhoLxNOHpgMqomW@9//Oe/VRDfXRHSL3obHj2OakYT4XkK/8UquClLm3n6isoiUNf3zQdnFPlOYegPllWpRJDG@bp3U8Ot8RSIbe1ZYIpiAjLi@TzsZzC7AyhcswwtQB3c/Qfkupv0vnc7mj7bQJGcZjHfwQepv0oSM/u3DaeF6/vkz8oXeR4A2GrdghijAiMTTVF2CYXbbtRQ2/T1gJabjQXKjb0fTDkOaSIaSuCEqcci7Nf4ISDKlJkOaPINOF4sJwqW8L0w9D5izokzB@Aw "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~205~~ ~~152~~ 145 bytes ``` f= d=>`012345`.replace(g=/./g,r=>`0123456 `.replace(g,c=>`${new Date(d-864e5*(24-c-r*7))[+r?`getUTCDate`:`toUTCString`]()}`.slice(0,2).padStart(3))) ``` ``` <input type=date oninput=o.textContent=f(this.valueAsDate)><pre id=o> ``` [Try it online!](https://tio.run/##fc29bsIwFAXgnadAiMGGXGNfEsKPQgf6BpQJIdlyHCsoiiPHggHx7KnpgLq029U5n869qpvqta@7AK0rzVAVQ1nsJRe4TDPJvOkapQ2xxYItbOLf1Wr0q0x0zKeP1tzHnyoYUsJ6lZpsRjAFDX6WU3qe@w9pTTh9HV5EbmVw8T4GX7dWXgh9StY3dVzjCVLWqfIYlA9kSSkdtGt71xjWOEsq8n4zQS42IDggTiLbjf52yIEjiM3/TuQZAo@T6Y8bvgE "JavaScript (Node.js) – Try It Online") Takes input as JavaScript Date object or timestamp. Edit: Saved 1 byte thanks to @EmbodimentofIgnorance, which then allowed me to save a further 7 bytes by adding a trailing newline to the output. Saved 52 bytes when I discovered that I was working around behaviour that was not actually buggy in the first place... [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 87 bytes ``` {~rotate(<Th Fr Sa Su Mo Tu We>,.day-of-week),|comb 21,($_-17..$_+17)>>.day.fmt('%2d')} ``` [Try it online!](https://tio.run/##FYxdC4IwGIXv@xUvYrnRHG5YIpRX0V1XCt0EsnKjL10sRSTrr695dZ6HczgvaZ5rWw@wULC1n5/RrWgl2hRX2BvIBeQdHDQUHRxlRmglhlCrsJfygcl40fUZOCPIL0OWUOqXS5bgLJtmVNUtCua8CvDXvsUACu3cM21kj0a/xJje9a1B3qnxMIEpQGkzQzxiKYGYAMdkMh45JMDSSVmycux6FmP7Bw "Perl 6 – Try It Online") Takes a `Date` object, returns a list of lines. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~124~~ 120 bytes ``` n=>{for(int i=0;i<42;)Write($"{(i<7?$"{n.AddDays(i-3):ddd}".Remove(2,1):n.AddDays(i-24).Day+""),3}"+(++i%7<1?"\n":""));} ``` [Try it online!](https://tio.run/##TY5BCoMwFET3PYWEFn5IFE0tUhMVwROUQjfdiInwF0bQ0FLEs6fZFLqa4c1bzLDGw4q@HRzOVnW9M3ecTD1W3lb1Ns4LoHURVqlElQtJHws6A0eyAaqiCWmTVuuu/6yA8ZmWWuudJDczzS8Dgme0/BdETpNQGSGUn3fCgDE8FSpryNOSMlAqdy8PI1jzjn5nQKTZlef8Elb/BQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 123 bytes ``` (s=#;Grid@Join[{StringTake[ToString@DayName[s~d~#]&/@Range[-3,3],2]},Partition[Last@d[s,#]&/@Range[-17,17],7]])& d=DatePlus ``` [Try it online!](https://tio.run/##TcyxCsIwEIDh3acQCkXhxDYdikghQ0EQkaLdjgyHCTFoU2jOQUr76lFwcfzh4@@I76YjdjeKtoqrUCX7w@C0PPbO43jlwXnb0sNg2/9C1vQ@U2cwzHpOVLqVF/LW4KaAQoFQEzQ0sGPXezxRYKkxwL/LS8hLBaVS63Shq5rYNM9XiM33zktpcRSZyEBAvptUjB8 "Wolfram Language (Mathematica) – Try It Online") I don't know why `Grid` doesn't work on TIO but this code outputs this [![enter image description here](https://i.stack.imgur.com/tzGlX.png)](https://i.stack.imgur.com/tzGlX.png) @DavidC saved 1 byte [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~33~~ 31 bytes ``` YO-17:17+t7:)8XOO3Z(!1ew7XOU7e! ``` [Try it online!](https://tio.run/##y00syfn/P9Jf19DcytBcu8TcStMiwt/fOEpD0TC13DzCP9Q8VfH/f3W31KSi0sSiSgVDSwUjAyMDdQA "MATL – Try It Online") ### Explanation ``` YO % Implicit input. Convert to date number. This is a single number % that specifies the date -17:17 % Push [-17 -16 ... 16 17] + % Add to date number, element-wise. This gives a row vector of 35 % date numbers centered around the input date t % Duplicate 7: % Push [1 2 ... 7] ) % Index into the 35-element vector. This keeps the first 7 entries 8XO % Convert to day-of-week in 3 letters. Gives a 3-col char matrix O3Z( % Write char 0 (equivalent to space for display purposes) into the % 3rd column !1e % Tranpose and linearize into a row. This produces a string such as % 'Tu We Th Fr Sa Su Mo ', to be used as column headings w % Swap. This brings to top the row vector of 35 date numbers % computed from the input 7XO % Convert to day-of-month. Gives a 2-col char matrix U % Convert each row to number 7e! % Reshape into 7-row matrix and transpose % Implicit display. This prints the string with the headings and % the matrix. The latter has a minimum-one-space separation between % columns, so it is aligned with the headings ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 149 bytes ``` d->{d.add(5,-24);for(int i=0,w;i<42;d.add(5,1))System.out.printf("%c%2s",i%7<1?10:32,i++<7?"SaSuMoTuWeThFr".substring(w=d.get(7)%7*2,w+2):d.get(5));} ``` [Try it online!](https://tio.run/##jVFha9swEP2eXyEMASlRNFtLMInjltFuEFjXDw6MbYyhynKq1JGMda4pJb89s504jC6MfRCS7r27e@9uK57FZJs@HfSusCWgbfNnFeicjaLBX7GsMhK0NW9B0DvVxmQunEN3Qhv0OkCoqB5yLZEDAc31bHWKdg2GEyi12fz4iUS5caSjInRjjat2qlzeiFyZVJRXKEPxIZ1cvaZMpCme0QmfkiizJdYGkI59Wkd6OeVRjweEJC8O1I7ZCljRNIEMe0M55M6jehgug@vAX7znVI/Hy/DaS0RS3dl19VWtHz@VHnPVg@uk4TpO2UYBDskwHHFajzlZHCMzQqL9Ieokf7ZS5LcCVGMFlAOH4pOZPzBmM8z9YE6nlBN6GeU@5TSYX4aDcMbpnAbTE7w/Nm/ncOZ17RdHEe1AT3X6USLZP@JzrHWzMs1ujFSYRKeMnsicgnWzVWxUjdoOuK3NBCQgSrjPbsUL/m6NWqWtRO9Dszgtxbsvqv71zZZPHiEM7MfCysdESWtSTNAIBb7vN@Pr1b3dVW6wtzJF1Rjx0Lgzc9Z1iXtfQUv2zqSMCSlVAbh38a/0/8D2g/bsD78B "Java (JDK) – Try It Online") ## Credits * -13 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). [Answer] # [PHP](https://php.net/), ~~197~~ ~~189~~ 187 bytes ``` for($d=date_create($argn)->sub($i=new DateInterval(P17D)),$i->d=1;$x++<35;$h.=$x<8?substr($d->format(D),0,2).' ':'',$d->add($i))$o.=str_pad($d->format(j),3,' ',2);echo wordwrap($h.$o,20); ``` [Try it online!](https://tio.run/##TZBfS8MwFMXf@ynuQyAJy0bbOebssiFMURg48FGkZGtcK1sTbjM3ET97vfuj@Hbvuef8wokvfTue@tKDRXSYo/UOQ1WvRSyzKGLBNqEBDS8RAL/1WG0ghTRORlwdlXu7xJ3BT0hGpKbxWX22Ptjt0iIkV5AMBynJr0R7c2jNqhRwwZoGmMF1DRK@KMcOmpWaOc15Rqtdle58V7B4WOR3T/O/IWuJJVihCxNsviJssOLkld1Js1sKVuna7mFG@mMdLH6YjVgkw5mUilXdSaGTjB06nXF/kLGyp9lhfD2lXBOO1O6E6FsTxEyqWKWyx4HfcK6OF1MUBJeSuZ4md@5N8T/xLlVfkZ1S2anA3mGxR@MFPcOcSulb20u33y7Rd/sD "PHP – Try It Online") Input is `STDIN` as a date string. Run with `php -nF`. ``` $ echo April 2 2019|php -nF cal.php Sa Su Mo Tu We Th Fr 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` [Verify all test cases](https://tio.run/##TZBfS8MwFMXf@ynuQyAJy0bbOebssiFMURg48FGkZGtcK1sTbjM3ET97vfuj@Hbvuef8wokvfTue@tKDRXSYo/UOQ1WvRSyzKGLBNqEBDS8RAL/1WG0ghTRORlwdlXu7xJ3BT0hGpKbxWX22Ptjt0iIkV5AMBynJr0R7c2jNqhRwwZoGmMF1DRK@KMcOmpWaOc15Rqtdle58V7B4WOR3T/O/IWuJJVihCxNsviJssOLkld1Js1sKVuna7mFG@mMdLH6YjVgkw5mUilXdSaGTjB06nXF/kLGyp9lhfD2lXBOO1O6E6FsTxEyqWKWyx4HfcK6OF1MUBJeSuZ4md@5N8T/xLlVfkZ1S2anA3mGxR@MFPcOcSulb20u33y7Rd/sD "PHP – Try It Online") Or **[174 bytes](https://tio.run/##RZBdS8MwFIbv@yvORSAJy0ZbHXN22RCmKAwceCkysiWuha0Jp5mbiL@9nn2od8lz3vfhJKEM7WgSygAO0eMCXfAYq3otUlkkCYuuiQ1oeE0A@F3AagM55Gk25OpIHtwSdwY/IRsSzdMzfXEhuu3SIWTXkA36OeE3sr17dGZVCrhoTQPM4LoGCV/UYwfNSs285rygq1uV/jxXMH@cL@6fZ3@HoiWXYFZbE91iRdroxCkru@NmtxSs0rXbw5T4Ux0dfpiNmGeDqZSKVd2x1VnBDp3O6KpfsLKn2WF0M6FeE4/W7pjsWxPFVKpU5bLHgd9yro4TYy3JpWSeWv9JewoVp533Hu0eTRBkZl7l9JPt5Tm/6yff7Q8)** with zero-padded single digits. [Answer] # Excel VBA, ~~190~~ 159 bytes Thanks @TaylorScott ``` Function z(i) Dim d(5,6) v=DateValue(i)-17 For x=1To 5 For y=0To 6 d(0,y)=Left(WeekdayName(Weekday(v+y)),2) d(x,y)=day(v+y+(x-1)*7) Next y,x z=d() End Function ``` Takes input in the form of a valid date string for Excel VBA (e.g. February 19, 2020; 2/19/2020; 19-Feb-2019), and returns an array with the given calendar centered on it. [Answer] # [Red](http://www.red-lang.org), ~~153~~ 131 bytes ``` func[d][s: d - 24 loop 7[prin[""copy/part system/locale/days/(s/10) 2]s: s + 1]loop 5[print""loop 7[prin pad/left s/4 3 s: s + 1]]] ``` [Try it online!](https://tio.run/##Vc2xDsIgAIThnae4MGkMoWCbpt1cfAAdCQMWSEywEKhDnx6buuj6J99ddrbenFWa@LH69zwpq1UZYcEgW4QYE3qV8nNWlE4xrTyZvKCsZXEvHuJkguPWrIUfChfNEVKXkRScIPSOux0vlP5MIRnLg/PbDm9xxvb3FVpXD8kuKTPZiIHsFMETDzGwq3tsWTZ/uWV3l5joO1k/ "Red – Try It Online") [Answer] # T-SQL, 203 bytes ``` DECLARE @f date='2020-02-19' ,@ char(20)=0,@d char(105)=0SELECT @=left(format(d,'D'),2)+' '+@,@d=right(d,2)+char(32-n%7/6*19)+@d FROM(SELECT dateadd(d,number-17,@f)d,number n FROM spt_values WHERE'P'=type)x ORDER BY-n PRINT @+' '+@d ``` The online version is slightly different, this posted version works in MS-SQL Studio Management. It saves 1 bytes compared with the online version, but doesn't give the correct result online **[Try it online](https://data.stackexchange.com/stackoverflow/query/1023956/today-is-the-center)** [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` from datetime import* d=input() for i in range(42):print(d+timedelta(i-24)).strftime('%'+'da'[i<7])[:2]+i%7/6*'\n', ``` [Try it online!](https://tio.run/##Fc3LCsMgEEDRfb5iNkGN9iXS0NB@SZqFoLYD8YGdLvr1FrcXDrf86J2Tbi3UHMFZ8oTRA8aSK02De2AqX@JiCLkCAiaoNr08N1ospWIi7mQXzu9kOR60EeL4oRp65GxkkjnLVrzPm1gXvUkc59N1Ys/EVGv9x/X5clNgFGjxBw "Python 2 – Try It Online") Not sure if this is allowed... takes input from STDIN in the form `date(year, month, day)`. This can also be represented as `__import__('datetime').date(year, month, day)`. These are really `__import__('datetime').date` objects. ]
[Question] [ My teacher always gives me the most complicated set of math problems for homework. Like: `pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even`. And I want to know in advance how much time to set aside for my homework, but I don't want to have to figure all that out. That's why its your task to program it for me. ## Specifications * You will get a string detailing the problems that I have to complete as args, stdio, etc. * They will be comma separated (possibly `comma-space` separated) * It will include single problems in the form of just a number (e.g. `79`) * And ranges in the form `17-18` (again, you have to deal with optional spaces) * The ranges are inclusive of both ends * The ranges will optionally be suffixed by `odd` or `even`, which you have to take into account. * A set of ranges/pages will be prepended by a page number in the form `pg. 545:` , again having to deal with optional spaces. You can safely ignore these, as you need to get the problems over all the pages * The text may be in uppercase or lowercase, but will not be both. * Return, stdout, etc. the number of problems I have to do for homework. * Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! ## Test Cases ``` pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even -> 27 pg. 34: 1 -> 1 PG. 565: 2-5,PG.345:7 -> 5 pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80 -> 70 pg.492: 2-4 odd,7-9 even -> 2 ``` [Answer] # CJam, ~~61~~ ~~58~~ ~~51~~ ~~48~~ ~~46~~ ~~43~~ ~~41~~ 38 bytes ``` leuS-',/{':/W>:~_2*2<~z),>1f&\,5--~}%, ``` Verify the test cases in the [CJam interpreter](http://cjam.aditsu.net/#code=%7BleuS-'%2C%2F%7B'%3A%2FW%3E%3A~_2*2%3C~z)%2C%3E1f%26%5C%2C5--~%7D%25%2Cp%7D5*&input=pg.%20546%3A%2017-19%2C%2022%2C%2026%2C%20pg.%20548%3A%2035-67%20odd%2C%2079%2C%2080-86%20even%0Apg.%2034%3A%201%0APG.%20565%3A%202-5%2CPG.345%3A7%0Apg.%20343%3A%205%2C8%2C13%20-%2056%20even%2Cpg.%20345%3A%2034%20-%2078%2C80%0Apg.492%3A%202-4%20odd%2C7-9%20even). ### How it works ``` leuS- e# Read a line from STDIN, convert to uppercase and remove spaces. ',/ e# Split at commas. { e# For each chunk: ':/W> e# Split at colons and only keep the last chunk. :~ e# Evaluate the string inside the array. _2* e# Copy the array, repeated twice. 2< e# Keep only the first two elements. e# In all possible cases, the array now contains exactly two e# integers, which are equal in case of a single problem. ~ e# Dump the array on the stack. z), e# Push [0 ... -N], where N is the second integer. > e# Discard the first M elements, where M is the first integer. 1f& e# Replace each element by its parity. \, e# Push L, the length of the original array. e# EVEN and ODD all push elements, so L is 1 for single problems, e# 2 for simple ranges, 5 for odd ranges and 6 for even ranges. 5-- e# Discard all elements equal to L - 5 from the array of parities. e# This removes 0's for odd ranges, 1's for even ranges, -3's for e# other ranges and -4's for single problems, thus counting only e# problems of the desired parities. ~ e# Dump the resulting array on the stack. }% e# Collect the results in an array. , e# Compute its length. ``` [Answer] ## Perl - 47 Bytes ``` #!perl -p054 {map$\+=($_%2x9^lc$')!~T,$&..$'*/\d+ ?-/}}{ ``` Amended to pass the new test case. --- **Original** ## Perl - 36 Bytes ``` #!perl -p054 $\+=/\d+ ?-/*($'-$&>>/o|e/i)+1}{ ``` Counting the shebang as 4, input is taken from stdin. --- **Sample Usage** ``` $ echo pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even | perl math-problems.pl 27 $ echo pg. 34: 1 | perl math-problems.pl 1 $ echo PG. 565: 2-5,PG.345:7 | perl math-problems.pl 5 $ echo pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80 | perl math-problems.pl 70 ``` --- **Caveats** For even/odd ranges, it is expected that at least one of the endpoints matches the parity of the range. For example, `11-19 odd`, `11-20 odd`, and `10-19 odd` will all be correctly counted as 5, but `10-20 odd` will be over-counted as 6. [Answer] # Python 2, ~~259~~ ~~253~~ ~~249~~ 239 bytes [**Try it here**](http://repl.it/q86/3) This can probably still be golfed more. Edit: Fixed a bug that caused mine to not work for `2-4 even` as I had expected. Then made an adjustment for that fix. That fix saved me four bytes! Edit: Now uses `input()` and **+2 bytes** for the two quotation marks the user must surround input with. ``` import re c=0 for x in re.sub(r'..\..*?:','',input()).replace(' ','').split(','): y=x.split('-') if len(y)<2:c+=1 else: a,b=y[0],y[1];d=int(re.sub('[A-z]','',b))-int(a)+1 if b[-1]>':':d=d/2+d%2*(int(a)%2==ord(b[-3])%2) c+=d print c ``` ### Less golfed (with comments! :D): I hope these comments help some. I'm still not quite sure if I explained that last complex line correctly or not. ``` import re def f(s): c=0 l=re.sub(r'..\..*?:','',s).replace(' ','').split(',') # remove pg #'s and split for x in l: y=x.split('-') if len(y)<2: # if not a range of numbers c+=1 else: a,b=y[0],y[1] # first and second numbers in range d=int(re.sub('[A-z]','',b))-int(a)+1 # number of pages if b[-1]>':': # if last character is not a digit # half the range # plus 1 if odd # of pages, but only if first and last numbers in the range # are the same parity # ord(b[-3])%2 is 0 for even (v), 1 for odd (o) d=d/2+(d%2)*(int(a)%2==ord(b[-3])%2) c+=d print c ``` [Answer] # Pyth, ~~43~~ ~~42~~ ~~44~~ 42 bytes ``` lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\, ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=lsm-%25R2%7DhKvMc-ecd%5C%3AG%5C-eK%3F%7D%5Ced%7DedGYc-rzZd%5C%2C&input=PG.492%3A+2-4+ODD%2C7-9+EVEN&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=zFz.z%0Alsm-%25R2%7DhKvMc-ecd%5C%3AG%5C-eK%3F%7D%5Ced%7DedGYc-rzZd%5C%2C&input=Test+cases%3A%0Apg.+546%3A+17-19%2C+22%2C+26%2C+pg.+548%3A+35-67+odd%2C+79%2C+80-86+even%0Apg.+34%3A+1%0APG.+565%3A+2-5%2CPG.345%3A7%0Apg.+343%3A+5%2C8%2C13+-+56+even%2Cpg.+345%3A+34+-+78%2C80%0APG.492%3A+2-4+ODD%2C7-9+EVEN&debug=0) I think I can still chop one or two bytes. ### Explanation ``` lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\, implicit: z = input string rzZ convert z to lower-case - d remove all spaces from z c \, and split by "," m map each part d to: cd\: split d by ":" e and only use the last part (removes page number) - G remove all letters (removes odd/even) c \- split by "-" vM and evaluate all (one or two) numbers K and store the result in K }hK eK create the list [K[0], K[0]+1, ..., K[-1]] %R2 apply modulo 2 to each element - and remove: }\ed "e" in d (1 for in, 0 for not in) ? }edG if d[-1] in "abcde...z" else Y dummy value s combine all the lists l print the length ``` [Answer] # JavaScript (Spidermonkey console) - 139 It's just easier to test on the command line. ``` for(r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi,m=readline(z=0);f=r.exec(m);z+=!b||((p=b-a)%2||!c|a%2^/e/i.test(c))+p/(2-!c)|0)[,a,b,c]=f print(z) ``` Ungolfed: ``` // any number set after "pg:" or a comma // \1 is FROM, \2 is TO, \3 is odd/even r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi; m=readline(); z=0; // this is the sum. while(f=r.exec(m)){ [,from,to,oddEven]=f; if(!to) { z++; } else { if((to-from)%2) { // if to and from are not the same parity, add 1 z++; } else { // if to and from are not the same parity... if(!oddEven) { // and we don't have a parity marker, add one z++; } else if(a%2 != /e/i.test(c)) { // if we do have a parity marker, // AND the parity of from and to matches the // parity of the oddEven sign, then add 1 z++; } } // then add the difference between to-from and // if oddEven exists, divide by two and round down z+=(to-from)/(oddEven?2:1)|0; } } print(z); ``` [Answer] ## Factor - 488 bytes: ``` USING: arrays ascii kernel math math.parser math.ranges pcre sequences ; IN: examples.golf.homework : c ( a -- b ) >lower "(?:[,:]|^) *(\\d+) *(?:- *(\\d+) *(e|o)?)?" findall [ rest [ second dup string>number swap or ] map dup length 1 = [ drop 1 ] [ dup length 2 = [ first2 swap - 1 + ] [ first3 "o" = [ [a,b] [ odd? ] count ] [ [a,b] [ even? ] count ] if ] if ] if ] map sum ; ``` [Answer] # Bash 344 315 306 294 262 252 242 240 ``` IFS=, o(){ R=0;for ((i=$1;i<=$2;R+=i++%2));do : done } e(){ q=$R;o $*;((R=q-R)) } for c in ${1,,};do c=${c#*:} m=${c##* } l=${c%-*} l=${l// } h=${c#*-} [[ a< $m ]]&&h=${h% *} h=${h// } ((R=h-l+1)) eval "${m::1} $l $h" ((t+=R)) done;echo $t ``` I don't think I've golfed this as much as is possible but not bad for a first submission. Commented version below. ``` IFS=, # Setup IFS for the for loops, We want to be able to split on commas o(){ # Odd R=0 # Reset the R variable # Increments R for each odd element in the range # $1-$2 inclusive for ((i=$1;i<=$2;R+=i++%2));do : # Noop command done } e(){ # Even # Save R, it contains the total number of elements between low # and high q=$R # Call Odd, This will set R o $* # Set R = total number of elements in sequence - number of odd elements. ((R=q-R)) } # This lowercases the firs arg. IFS causes it to split on commas. for c in ${1,,};do c=${c#*:} # Strips the page prefix if it exists m=${c##* } # Capture the odd/even suffix if it exists l=${c%-*} # Capture low end of a range, Strips hyphen and anything after it l=${l// } # Strips spaces h=${c#*-} # Capture high end of a range, Strips up to and including hyphen # If we have captured odd/even in m this will trigger and strip # it from the high range variable. [[ a< $m ]]&&h=${h% *} h=${h// } # Strip Spaces # Give R a value. # If we are in a range it will be the number of elements in that range. # If we arent l and h will be equal are R will be 1 ((R=h-l+1)) # Call the odd or even functions if we captured one of them in m. # If we didnt m will contain a number and this will cause a warning # to stderr but it still works. eval "${m::1} $l $h" # Add R to total ((t+=R)) done # Print result echo $t ``` Run the test cases: ``` bash math.sh "pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even" bash math.sh "pg. 34: 1" bash math.sh "PG. 565: 2-5,PG.345:7" bash math.sh "pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80" bash math.sh "pg.492: 2-4 odd,7-9 even" ``` Depending on how I read the rules it could be possible to save another 4 bytes. If even/odd is always lowercase `${1,,}` can be changed to `$1` [Answer] # JavaScript (*ES6*), 149 Run snippet in Firefox to test ``` F=s=>s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig,(_,c,v,o,e)=> c=='-'?(t+=1+(o?(v-(r|1))>>1:e?(v-(-~r&~1))>>1:v-r),r=0) :c!='.'&&(t+=!!r,r=v) ,r=t=0)&&t+!!r // Less golfed U=s=>{ var r = 0, // value, maybe range start t = 0; // total s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig, // execute function for each match (_ // full match, not used , c // separator char, match -:,. , v // numeric value , o // match first letter of ODD if present , e // match first letter of EVEN if present )=> { if (c == '-') // range end { t++; // in general, count range values as end - start + 1 if (o) // found 'odd' { r = r | 1; // if range start is even, increment to next odd t += (v-r)>>1; // end - start / 2 } else if (e) // found 'even' { r = (r+1) & ~1; // if range start is odd, increment to next even t += (v-r)>>1; // end - start / 2 } else { t += v-r; // end - start } r = 0; // range start value was used } else if (c != '.') // ignore page numbers starting with '.' { // if a range start was already saved, then it was a single value, count it if (r != 0) ++t; r = v; // save value as it counld be a range start } } ) if (r != 0) ++t; // unused, pending range start, was a single value return t } // TEST out=x=>O.innerHTML+=x+'\n'; test=["pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even", "pg. 34: 1", "PG. 565: 2-5,PG.345:7", "pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80"]; test.forEach(t=>out(t + ' --> ' + F(t))) ``` ``` <pre id=O></pre> ``` [Answer] # C++ ~~226~~ ~~224~~ 222 I know I'm kinda late for the party, but this seemed like a fun problem and lack of entries using C-family languages bothered me. So here's a C++ function using no regexp or string substitution, just some simple math: ``` void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;} ``` **Ungolfed**: ``` void f() { char c; int o=0,i,j; while(cin>>c) c=='p'||c==80?cin.ignore(9,58):cin.unget(), cin>>i>>c&&c==45? cin>>j>>c&&(c=='e'||c=='o')? cin.ignore(9,44), c=='e'? i+=i&1,j+=!(j&1) :(i+=!(i&1),j+=j&1), o+=(j-i)/2 :o+=j-i :0, ++o; cout<<o; } ``` I didn't say it would be readable, now did I? :) Ternary operators are hell. I tried my best to (sort of) format it, though, so I hope it helps at least a little bit. **Usage**: ``` #include <iostream> using namespace std; void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;} int main() { f(); } ``` [Answer] ## **Python 2 - 163 bytes:** [Try it here](http://repl.it/q86/4) Input must be given inside quotes ``` import re print len(eval(re.sub('([^,]+:|) *(\d+) *-? *(\d*)(?=.(.)).*?,',r'[x for x in range(\2,\3+1 if \3.0 else \2+1)if x%2!="oe".find("\4")]+',input()+',[]'))) ``` **Explanation:** The general approach is to convert the existing input into valid python, then evaluate this. Each comma separated value is converted to an array, which are then all appended together and the length gives the final result. For example, with the input `12-15 odd,19`, before evaluation the regex substitution will produce: ``` [x for x in range(12,15+1 if 15.0 else 12+1)if x%2!="oe".find("o")] +[x for x in range(19,+1 if .0 else 19+1)if x%2!="oe".find("[")] +[] ``` To break this down further: * `15+1 if 15.0 else 12+1` This bit will make sure the second argument of range() is correct depending if there is a range or a single value given (if \3 is empty, \3.0 will evaluate to false). * `if x%2!="oe".find("o")` Depending on the value found two characters away from the final digit in the range (`(?=.(.))` in the regex - lookahead two characters without consuming them), there are three possible outcomes: + `x%2!="oe".find("o")` evaluates to `x % 2 != 0` (only odd matched) + `x%2!="oe".find("e")` evaluates to `x % 2 != 1` (only even matched) + `x%2!="oe".find("[")` evaluates to `x % 2 != -1` (this character could be multiple things as it's just two characters away from the last digit, but will only be o or e if odd/even is intended) * The seemingly random +[] on the end is to ensure that the last token in the comma-separated list has a character two away from the last digit, but also allows us to append something to the end to use up the last '+' which would have been trailing otherwise. [Answer] # [Go](https://go.dev), 358 bytes ``` import(."fmt";."regexp";."strings") func f(s string)(O int){C:=Contains for _,m:=range MustCompile(`pg\.\d+:`).Split(ReplaceAll(ToLower(s)," ",""),-1){for _,r:=range Split(m,",") {if r==""{continue} l,h,e,o:=0,0,C(r,"even"),C(r,"odd") Sscanf(r,`%d-%d`,&l,&h) h=max(h,l) h++ for i:=l;i<h;i++{if e&&i%2<1{O++}else if o&&i%2>0{O++}else if !e&&!o{O++}}}} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVLbbptAEFVf-YrJSrYWMSDfMBhnI0Vu1Je2iWK_1VWNYLFRuRXWaSrEl_TFqtSXql_Ur-kAdpUiod09e-bMzNn5_mOfn34XfvDZ30tI_Tj7eVSR6f55FcVpkZeKWyxKFVtarJR7-Vy0u0qVcbavmK5FxyyAiFfQQzq_hzhTer3yxCrPFMlVWpSX8AlTT5R-RjneHSu1ytMiTiTfFfuttQ0Nb6db6yKJFX-UReIH8jZJ-CZ_m3-VJa90ZMCQMR3NsV73cuVFrg9LkQg61HEEpRCM1QFlj7OjbLQEDygx98QIR7jiJTL5JDMS6_Z5GFIb6yrws4jOu0FoDsIdDhMcHnTtIFL_mR8woa1hdJ3EnkiW8fVhGRtGm04Oh_Fgcj2u7w2jkUklgcC8A29G_4FXRL3KO4g-rZTqWGbNxe5f6lshYdMaeQwUdZIVZ1OXQLa3tjbak1-CkpWqQMCHj5taq1mxt8CezT0YO-Z4gTCZ0D9H6HHXg6ltzh2gPhEcundHpjuHzgIiOg2eNaYzkiBo3CEPbyh6bnswMW2kw3Rmew7d2i_4Uw9sdHE8BZO4nST2NxQ3nRHquOiOKMoZXcJmi0mrOevqcczFv0KI0PTT1M4gp6fUHqh5lWScCSHWm9vHDa3tyHXvr8AT0E9Ab0it-UEHRlxZZJ6ukeUtdCVAWa2DNXSKEWeDLyBuYBACH4T6ts3fhWDLx56tQ0MFvSzh7v3rvoDzk51O_foX) Does some input preprocessing (to lowercase, remove spaces), then splits on the pages. After that, for each problem range (matches split on commas), add to the problem count. If it's even only count on even indexes, and the same for odds. If neither, count on each index. ]
[Question] [ Given positive integer `n > 2`. We convert it to an array as follows: 1. If it is equal to `2` return an empty array 2. Otherwise create array of all `n`'s prime factors sorted ascending, then each element replace with its index in prime numbers sequence and finally convert each element to array For example, lets convert number `46` to array. Firstly, convert it to array of its prime factors: ``` [2, 23] ``` Number `23` is `9`th prime, so replace `2` with empty array and `23` with `[9]`. Array now becomes: ``` [[], [9]] ``` Prime factors of `9` are `3` and `3`, so: ``` [[], [3, 3]] ``` Do the same for both `3`: ``` [[], [[2], [2]]] ``` And finally: ``` [[], [[[]], [[]]]] ``` Now, to encode it, we simply replace each open bracket with `1` and each closing bracket with `0`, then remove all ending zeros and drop one `1` from the end. This is our binary number. Using the above example: ``` [ ] [ [ [ ] ] [ [ ] ] ] | | | | | | | | | | | | | | | | | | | | | | | | V V V V V V V V V V V V 1 0 1 1 1 0 0 1 1 0 0 0 ``` Now simply drop the last three zeros and the last `1`. The number becomes `10111001` which is `185` in decimal. That is the expected output. Notice that in array to binary conversion brackets of the main array are not included. ## Input Positive integer `n` greater than `2`. ## Output Encoded integer `n`. ## Rules and IO format * Standard rules apply. * Input can be string or number (but in case of string it must be in base 10). * Output can be string or number (but in case of string it must be in base 10). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins! ## Test cases More test cases upon request. ``` 3 ---> 1 4 ---> 2 5 ---> 3 6 ---> 5 7 ---> 6 8 ---> 10 9 ---> 25 10 ---> 11 10000 ---> 179189987 10001 ---> 944359 10002 ---> 183722 10003 ---> 216499 10004 ---> 2863321 10005 ---> 27030299 10006 ---> 93754 10007 ---> 223005 10008 ---> 1402478 ``` ## [Sandbox](https://codegolf.meta.stackexchange.com/a/13680/72349) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~35~~ ~~31~~ ~~30~~ ~~29~~ ~~26~~ ~~25~~ ~~24~~ ~~22~~ ~~20~~ ~~19~~ 15 bytes -7 bytes thanks to @Zgarb! Saved an extra 4 bytes, indirectly, thanks to [Zgarb](https://codegolf.stackexchange.com/questions/150144/encode-factor-trees#comment367068_150159) ``` ḋhΣhgφṁȯ`Jḋ2⁰ṗp ``` [Try it online!](https://tio.run/##yygtzv7//@GO7oxzizPSz7c93Nl4Yn2CF1DA6FHjhoc7pxf8///fxAwA) ### Explaination ``` φ -- Define a recursive function which calls itself ⁰ and is applied to an Integer ṁ p -- map then concatenate over its prime factors ṗ -- return their indices into the primes ⁰ -- and then recur, applying ⁰ to that number ȯ`Jḋ2 -- then surround it between the list [1,0] (binary 2) g -- group adjacent equal elements h -- drop last element (trailing 0s) Σ -- concatenate h -- drop the last element ḋ -- interpret as base 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (tail zeros from both sides, `t`, rather than from the right `œr`) ``` ÆfÆC$ÐLŒṘO%3ḟ2Ḋt0ṖḄ ``` A monadic link taking an integer greater than 2 and returning an integer greater than 0 (2 would return 0 as per the original spec too). **[Try it online!](https://tio.run/##ATAAz/9qZWxsef//w4Zmw4ZDJMOQTMWS4bmYTyUz4bifMuG4inQw4bmW4biE////MTAwMDg "Jelly – Try It Online")** ### How? This almost exactly replicates the description given, just with some ordinal manipulation for the creation of the binary array... ``` ÆfÆC$ÐLŒṘO%3ḟ2Ḋt0ṖḄ - Link: number n (>=2) ÐL - loop until no more changes occur: $ - last two links as a monad: Æf - prime factorisation (includes duplicates & vectorises) ÆC - count primes less than or equal (vectorises) - ...note for entries of 2 this yields [1] - then for entries of 1 it yields [], as required ŒṘ - get a Python representation - just like in the OP, - something like: "[[], [[[]], [[]]]]" (for an input of 46) O - convert to ordinals e.g. [91,91,93,44,32,91,91,91,93,93,44,32,91,91,93,93,93,93] %3 - modulo by 3 e.g. [ 1, 1, 0, 2, 2, 1, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 0, 0] ḟ2 - filter discard twos e.g. [ 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0] Ḋ - dequeue e.g. [ 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0] t0 - strip zeros e.g. [ 1, 0, 1, 1, 1, 0, 0, 1, 1] Ṗ - pop e.g. [ 1, 0, 1, 1, 1, 0, 0, 1] Ḅ - binary to decimal e.g. 185 ``` [Answer] # [Python 2](https://docs.python.org/2/), 212 177 bytes ``` lambda n:int(g(n).rstrip("0")[1:-1],2) g=lambda n:"1%s0"%"".join(map(g,p(n))) def p(n,i=0,j=1): while n>1: j+=1;P=q=1;exec"P*=q*q;q+=1;"*~-j;i+=P%q while n%j<1:yield i;n/=j ``` [Try it online!](https://tio.run/##PU/RioMwEHz3K5aAkGhq3RYK1abf4PvdQb0z2g02JtHjri/9dS@FcvMwzAwzLOvuy3Wyu7VX7@vY3j67FmxFduEDt6II8xLIcVYy8YbVBj/kTiSD@i8yTOeSpYwVZiLLb63jg3RxKUTS6R6ilKRKaRSKKoGfK40a7BmjBpMrrBvlI@tf/cWaTPnM1/4Zs@yxMTXlqkl9rL52qTlhdSc9dkC13Sqz9lMAArIQWjtovpeAKCB/WSwjYhT5@DzvQnwMLnQpRvM9L/wgJPScxPoH "Python 2 – Try It Online") The lack of prime builtins really hurts the byte count, and it times out on TIO with larger primes. Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [primality check.](https://codegolf.stackexchange.com/a/58114) --- # [Python 2](https://docs.python.org/2/) + [gmpy2](https://github.com/BrianGladman/gmpy2), 175 bytes ``` lambda n:int(g(n).rstrip("0")[1:-1],2) g=lambda n:"1%s0"%"".join(map(g,p(n))) def p(n,i=0,j=1): while n>1: j+=1;i+=is_prime(j) while n%j<1:yield i;n/=j from gmpy2 import* ``` [Try it online!](https://tio.run/##PU3bSsQwFHzvVxwChcRma08Fwa7xR1TcSpPsCc2FNIv062uExXkYZoYZJu3lGsN4GPVxrLP/XmYIE4XCLQ@iz1vJlDgbmHjH6YSfchSNVf9Fhu02sJax3kUK3M@JW5nqUohm0QaqlKQG6RSKqYGfK60awhtWDa5TeKZO0faVMnnNnajpvdK6V5x20usCdA6PyjUmRw/Wp30E8inm8nCYmIGAAuQ5WM2fJCAK6O4Wh4oaVX75O68nocCFLv3qblvhz0KC4SSOXw "Python 2 – Try It Online") This version does not time out on the larger test cases (i.e. 10000 - 10008). [Answer] # Mathematica, ~~125~~ 119 bytes ``` Flatten[#//.{{1}->{1,0},a_/;a>1:>{1,List/@PrimePi[Join@@Table@@@FactorInteger@a],0}}]/.{1,d__,1,0..}:>{d}~FromDigits~2& ``` Uses a slightly different approach; converts prime indices to `{1, index, 0}`, and 2 to `{1, 0}`. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) **Usage:** ``` f = Flatten[ ... f[10008] ``` > > `1402478` > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` ÆfẎW€ÆC2,“”y¹ß€Ṇ? ÇŒṘḊ⁾][iЀḟ0t1Ṗ’Ḅ ``` [Try it online!](https://tio.run/##AVIArf9qZWxsef//w4Zm4bqOV@KCrMOGQzIs4oCc4oCdecK5w5/igqzhuYY/CsOHxZLhuZjhuIrigb5dW2nDkOKCrOG4nzB0MeG5luKAmeG4hP///zQ2 "Jelly – Try It Online") [Answer] # J, ~~74~~ ~~73~~ 66 bytes ``` 3 :'#.(}.~ >:@i.&1)&.|.2+}.;<@(_2,~_1,[:>:[:_1&p:q:) ::<"0@;^:_ y' ``` [Try it online!](https://tio.run/##DcE7CoQwFAXQ3lVcHIgJyiPRyuuH7EMwhYyMNmopqFvPeM4a49wJKjD7iL7lQU@/iHJGySVlfkvTeh3K4gmuGNhzYHBq50EDsk2tb0YGnFmSfKffhjm10M6@kGOR2sT4Bw) This is a real mess that certainly is in need of further golfing (e.g. removal of the explicit function definition). I think that the boxing I've been doing is especially what's bringing up the bytecount since I really don't know what I'm doing there (it's been a lot of trial and error). Also, I'm *pretty* sure that there are some built-ins I'm forgetting about (e.g. I feel like `_2,~_1,` probably has a built-in). # Explanation (ungolfed) ### Preamble Sit back tight, because this is not going to be a short explanation. Ironically, a terse language has been paired with a verbose person. I'll be splitting this into a few functions ``` encode =. 3 : '<@(_2,~_1, [: >: [: _1&p: q:) ::<"0@;^:_ y' convert =. 3 : '2 + }. ; y' drop =. (}.~ >:@i.&1)&.|. decode =. #. ``` * `encode` encodes the integer using \_1 and \_2 instead of [ and ] * `convert` converts a list of \_1 and \_2 into a list of 1 and 0 * `drop` drops the last 1 and trailing zeroes * `decode` converts from a binary list to a number I'll be walking through a sample call for 46, which expressed in the ungolfed format is done ``` decode drop convert encode 46 185 ``` ### Encode There's a lot to explain here. ``` 3 : '<@(_2,~_1, [: >: [: _1&p: q:) ::< "0@;^:_ y' ^:_ Do until result converges ; Raze (remove all boxing) "0 For each q: Factorize _1&p: Get index of prime >: Add 1 (J zero-indexes) _1, Prepend -1 _2,~ Append -2 < Box resulting array :: If there is an error < Box the element ``` Note that the explicit function definition `3 : '[function]'` evaluates the function as if it were on the REPL with the right argument replacing every instance of `y` (this means that I can avoid having to use caps (`[:`), atops (`@`), and ats (`@:`) at the cost of a few bytes). Here's what it looks like for each successive iteration on the input of 46 ``` ┌─────────┐ ┌──┬─────┬─────────┬──┐ ┌──┬──┬──┬──┬───────┬───────┬──┬──┐ │_1 1 9 _2│ => │_1│_1 _2│_1 2 2 _2│_2│ => │_1│_1│_2│_1│_1 1 _2│_1 1 _2│_2│_2│ => └─────────┘ └──┴─────┴─────────┴──┘ └──┴──┴──┴──┴───────┴───────┴──┴──┘ ┌──┬──┬──┬──┬──┬─────┬──┬──┬─────┬──┬──┬──┐ │_1│_1│_2│_1│_1│_1 _2│_2│_1│_1 _2│_2│_2│_2│ => the final iteration is just every └──┴──┴──┴──┴──┴─────┴──┴──┴─────┴──┴──┴──┘ value in its own box ``` This function makes use of adverse (`::`) in order to nest the values in "brackets" (the brackets used here are -1 and -2). Basically, every time we factorize and convert to prime number indices, \_1 is prepended and \_2 is appended, which act as brackets. When the function is called on those elements, it just returns them as-is since `q:` will error on trying to factorize a negative number. It's also fortunate that `q:` does *not* error on trying to factorize 1 and instead returns the empty array (as desired). ### Convert ``` 3 : '2 + }. ; y' ; Raze (remove boxing) }. Behead (remove head) 2 + Add 2 ``` Convert is a lot simpler. It just removes all the boxing, as well as the first element, and then converts everything to 1s and 0s (simply by adding 2) ### Drop ``` (}.~ >:@i.&1)&.|. &.|. Reverse, apply the left function, and then undo }.~ >:@i.&1 Drop the leading zeroes and first 1 i.&1 Index of first one >: Add 1 }.~ Drop ``` This reverses the list, finds the first one and then drops all the values up to that one, then reverses the list again. ### Decode Decode is the built-in function `#.` which takes a list of 1s and 0s and converts it to a binary number. [Answer] # [Retina](https://github.com/m-ender/retina), ~~244~~ ~~227~~ 225 bytes ``` +%(G` \d+ $*0¶$&$* +`^00(0+) 0$1¶$0 A`^(00+?)\1+$ ^0+ $0;1 +`(1+)¶0+(?=¶) $0;1$1 +`¶(11+?)(\1)*$ ¶$1¶1$#2$*1 1$ m`^11$ [] m`^1+ [¶$.0$*0¶] +s`(0+);(1+)(.+¶)\1¶ $1;$2$3$2¶ 0+;1+¶ )`1+ $.0 T`[]¶`10_ 10+$ 1 01 +`10 011 ^0+ 1 ``` [Try it online!](https://tio.run/##HY47TgRBEENzX4MCdU9JK3uW5aMRWhFxAbL50CtBQAABcLY5QF9sqJ6kquR@dvvn4@/z@7Jdp5eyeZuY3h3Wsa52Yx28LGSiZ9AUGvFclkT6OU9yw8KgOSjAJM91pafzU13zrlrT65qk4NOk3BkiJIJkV711ggz4Kotij/N@OcZADtw7zPDf0r4fWno6eCRPYYdpsN6O1sdNHxQPQC7hDiteyzjXtYhvEKMlBLYqYmztpaFtO@IWJ9zhHg94DBInxuQ/ "Retina – Try It Online") This is a straight forward approach following the algorithm demonstrated in the question. The prime index generation is exponential complexity so it will time out for larger inputs ### Explanation: ``` +%(G` Repeatedly apply on each line: \d+ If the line is a number, convert it to unary 0s and 1s $*0¶$&$* +`^00(0+) Generate all prefixes of the zeros greater than 1 0$1¶$0 A`^(00+?)\1+$ Remove non-prime strings of zeros ^0+ Index the first zero set (00) as 1 $0;1 +`(1+)¶0+(?=¶) Index the rest of the zeroes as their prime index $0;1$1 +`¶(11+?)(\1)*$ Compute prime factors of input value ¶$1¶1$#2$*1 1$ Remove the 1 factor (not really prime) m`^11$ Turn all 2 prime factors to [] [] m`^1+ Surround all non-2 prime factors in brackets [¶$.0$*0¶] +s`(0+);(1+)(.+¶)\1¶ Convert non-2 prime factors to their index $1;$2$3$2¶ 0+;1+¶ Remove the list of primes )`1+ Return all primes back to decimal ready to be repeated $.0 T`[]¶`10_ Then convert all [ to 1 and ] to 0, and remove linefeeds 10+$ Remove the final 1 and trailing zeroes 1 Convert from binary to unary 01 +`10 011 ^0+ 1 Convert from unary to decimal ``` [Answer] # [Haskell](https://www.haskell.org/), ~~162~~ ~~160~~ 155 bytes ``` sum.zipWith((*).(2^))[0..].tail.snd.span(<1).(r%) r=zip[1..][x|x<-[2..],all((>0).mod x)[2..x-1]] _%1=[] ((i,q):p)%n|mod n q<1=r%div n q++0:r%i++[1]|1<3=p%n ``` [Try it online!](https://tio.run/##FYrRDoIgAEXf/QoeYoNUBvXmpN/ogagxzWQhIVhjzW@P8D6d3XNGFZ53Y9LALym8J/LV7qyXEaE9JuhwxVhQQiRZlDYk2J4EpyxqWZYe4sLz3AuWCxHX2NbikLFSxiB0ophMrx5EvJ2xZlIWN8i4kAVCuppx4zC065ZYMLeMe9jrz8ZlSRsPdVkKJlfWHrmDNk1KW8CB89ouYAcGwGhe@nWDUY@Q6s65Pw "Haskell – Try It Online") **Explanation:** `r=zip[1..][x|x<-[2..],all((>0).mod x)[2..x-1]]` defines an infinite list of tuples of primes and their indices: `[(1,2),(2,3),(3,5),(4,7),(5,11),(6,13), ...]`. The function `(%)` takes this list `r` and a number `n` and converts the number into the reversed factor-array representation. This is done by stepping through `r` until we find a prime which divides `n`. We then recursively determine the representation of the index of this prime and enclose it in `0` and `1` and prepend the representation of `n` divided by that prime. For `n=46`, this yields the list `[0,0,0,1,1,0,0,1,1,1,0,1]` from which then the leading zeros (`snd.span(<1)`) and the next `1` (`tail`) are dropped. Afterwards the list is converted to a decimal number by element-wise multiplying with a list of powers of two and summing up the resulting list: `sum.zipWith((*).(2^))[0..]`. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 209 bytes ``` (load library (d [(q((N)(map(q((P)([(length(filter prime?(1to P))))))(reverse(prime-factors N (d B(q((L)(c 1(insert-end 0(foldl concat(map B L (d T(q((N)(if(mod N 2)(/ N 2)(T(/ N 2 (q((N)(T(from-base 2(t(B([ N ``` The last line is an unnamed function that computes the specified encoding. [Try it online!](https://tio.run/##LY@xbsMwDET3fsWNp8FonKZpOxUwkC0wMnjzpFhSK0CWXIkokK93KydceACP70jx8RZ8WdaVIWmD4K9Z59sTDUb@kL3irJeqLoojg41f8k3ng9iMJfvZfrKVhIvaitn@2lwst1Hj9CQpF/SV11XKWXFCSx@LzdLYaLCjS8EETClOWmoaOpzrwvA4wDvOyaDHXvH53oa7qK7TwzXQ5TQ3V10s9hR2HNGvG@8E/v8oeMEBrzjiDe/4QLvD4ajU@gc "tinylisp – Try It Online") ### Pre-golfing version This is the code I had before I started golfing it down: ``` (load library) (def prime-index (lambda (P) (length (filter prime? (1to P))))) (def to-list (lambda (N) (map to-list (map prime-index (reverse (prime-factors N)))))) (def to-bits (lambda (L) (cons 1 (insert-end 0 (foldl concat (map to-bits L)))))) (def trim (lambda (N) (if (mod N 2) (div2 N 2) (trim (div2 N 2))))) (def encode (lambda (N) (trim (from-base 2 (tail (to-bits (to-list N))))))) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` ΔÒ.Ø>}¸»Ç3%2K0ܨ2β ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JTDk/QOz7CrPbTj0O7//42NzM3MAQ "05AB1E – Try It Online") Explanation: ``` Δ } # loop until a fixed point Ò # replace each number with its prime factorization .Ø> # replace each prime with its 1-based index ¸» # after the loop: join to a string Ç # get ASCII value of each character 3% # modulo 3 (maps '[' to 1, ']' to 0, ' ' to 2, ',' to 2) 2K # remove 2s 0Ü # trim trailing 0s ¨ # remove the last 1 2β # parse as base 2 ``` [Answer] # JavaScript, 289 bytes The bytes are the sum of the JavaScript code without linebreaks after the commas (which are inserted only for better formatting and readability) (256 bytes) and the additional characters for the command line switch, which is required when using Chrome (33 bytes). ``` 'use strict' var f=(n,i=2,r=[])=>n>1?n%i?f(n,i+1,r):f(n/i,i,r.concat(i)):r, c=(p,r=1,i=2)=>i<p?f(i)[1]?c(p,r,i+1):c(p,r+1,i+1):r-1?f(r).map(h):[], h=a=>c(a), s=a=>a.reduce((r,e)=>r+s(e),'1')+' ', o=i=>+('0b'+s(f(i).map(h)).trim().replace(/ /g,'0').slice(1,-1)) ``` And a longer, better readable version: ``` 'use strict'; const f = (n,i=2,r=[]) => n>1 ? n%i ? f(n,i+1,r) : f(n/i,i,r.concat(i)) : r; const c = (p,r=1,i=2) => i<p ? f(i)[1] ? c(p,r,i+1) : c(p,r+1,i+1) : r-1 ? f(r).map(h) : []; const h = i => c(i); const s = a => a.reduce((r,e) => r+s(e),'1')+' '; const o = i => +('0b'+s(f(i).map(h)).trim().replace(/ /g,'0').slice(1,-1)); ``` Some brief explanations: `f` is a purely functional tail-recursive factorization algorithm. `c` counts at which place `r` the prime number `p` occurs in the sequence of prime numbers and returns either `[]` (if `p=2` and `r=1`) or factorizes and further processes `r` by means of recursion. `h` is a small helper function which unfortunately is necessary as `map` calls the supplied function with `numberOfCurrentElement` as the second and `wholeArray` as the third argument, thus overriding the default values provided in `c` if we would pass this function directly (it took me some time to get after this pitfall; replacing `h` by its definition would be a few bytes longer). `s` transforms the generated array to a string. We use `blank` instead of `0` so that we can use `trim()` in `o`. `o` is the function to be called with the input value `i` which returns the output. It generates the binary string representation required by the specification and converts it to a (decimal) number. **Edit:** Chrome must be started with `chrome --js-flags="--harmony-tailcalls"` to enable optimization of tail-recursion (see <https://v8project.blogspot.de/2016/04/es6-es7-and-beyond.html>). This also requires using strict mode. The following test shows that the computation is a bit slow for some values (the longest is more than six seconds for `10007`on my computer). Interestingly, without optimization of tail-recursion the computation is much faster (about factor 5) when there is no stack overflow. ``` for (let i=3; i<=10008; i==10 ? i=10000 : ++i) { let time = new Date().getTime(); let val = o(i); time = new Date().getTime() - time; document.write(i + ': ' + o(i) + ' (computed in ' + time + ' ms)<br>'); } ``` ]
[Question] [ Of course, the SE network is very knowledgeable about how to be respectful in the restroom, but for those of you who need a recap, being respectful means flushing the toilet, etc. Most importantly, though, it means using the stall as far away from others as possible. **The challenge** Given a blueprint of a set of stalls with indications of which ones are in use as a string, you must return or print from a function or program where the most respectful place to do your business is. **The input** ``` 0 1 2 3 4 5 <- The stall number which is not actually visible in the input. | | |-| |-|-| <- the stalls ``` The stalls are numbered in ascending order from left to right. There will always be at least one empty stall. There can be up to 50 stalls in an input. You can also take the input as an array or string of `0`s and `1`s or booleans if you prefer to do so. Stalls in use have `-` in them (in between the pipes). **The output** The most respectful stall to go to is the one that is on average farthest away from the ones in use. The distance between two stalls is the absolute value of the difference of the numbers above them. Just to be clear: you are finding the average distance from *all* of the stalls—not just the neighboring ones. You must output the lowest number of the most respectful stall to go to **that is empty**. **Examples** ``` Input: |-| |-| OR 101 Output: 1 Input: | | |-| |-|-| OR 001011 Output: 0 Input: |-| |-| | | | |-|-| OR 101000011 Output: 1 Input: |-| | | | | |-|-| | | | | OR 100000110000 Output: 11 Input: |-|-|-|-| | | | | | |-| OR 11110000001 Output: 9 Input: |-| | OR 10 Output: 1 Input: |-| | |-| OR 1001 Output: 1 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! You can use 0 or 1 based indexing in your answer — whichever you prefer; if you use 1 based indexing, then you must say so explicitly in your answer. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` JạþTS׬MḢ ``` Uses 1-based indexing. [Try it online!](http://jelly.tryitonline.net/#code=SuG6ocO-VFPDl8KsTeG4og&input=&args=WzEsMCwwLDAsMCwwLDEsMSwwLDAsMCwwXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=SuG6ocO-VFPDl8KsTeG4ogrDh-KCrEc&input=&args=WzEsMCwxXSwgWzAsMCwxLDAsMSwxXSwgWzEsMCwxLDAsMCwwLDAsMSwxXSwgWzEsMCwwLDAsMCwwLDEsMSwwLDAsMCwwXSwgWzEsMSwxLDEsMCwwLDAsMCwwLDAsMV0sIFsxLDBdLCBbMSwwLDAsMV0). ### How it works ``` JạþTS׬MḢ Main link. Argument: A (array of Booleans) J Yield all indices of A. T Yield all truthy indices of A. ạþ Compute the table of absolute differences. S Compute the sums of all columns. For each index, this yields the sum of all distances to occupied stalls. ׬ Multiply each sum by the logical NOT of the corresponding Boolean in A. This zeroes sums that correspond to occupied stalls. M Maximal; yield an array of all indices of maximal sums. Ḣ Head; extract the first index. ``` [Answer] # Swift, ~~158, 157, 128,~~ 100 Bytes Takes input from the `Array<Bool>` variable `i`, returns answer from the last expression. ``` let e=i.characters.map{$0>"0"}.enumerate() e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0 ``` Edit 1: Saved a byte by converting to bools via string comparison ``` let e=i.characters.map{$0=="1"}.enumerate() e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0 ``` Edit 2: Reworked my algorithm: ``` let e=i.characters.map{$0=="1"}.enumerate() e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0 ``` Edit 3: Took advantage of new rule that allows taking input directly from a boolean array. ``` let e=i.enumerated() e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0 ``` Ungolfed: ``` // for the sake of easier copy/pasting of input, take it as string let s = "100000110000" // convert input to true for taken, false for free // this is the input the golfed version actually uses let input = s.characters.map{$0>"0"} // Returns an array of tuples storing the array values (vacancy of the stall) and their index (their location) let valueIndexPairs = bools.enumerated() // Returns an array of pairs of locations and their avg distance to others let locationDistancePairs = valueIndexPairs.map{(valueIndexPair: (Int, Bool)) -> (Int, Int) in let averageDistance = valueIndexPairs.reduce(0) {partialSum, otherStall in let otherStallIsTaken = otherStall.1 if otherStallIsTaken { //don't let other stalls effect average if they're taken return partialSum } else { let thisStallLocation = valueIndexPair.0 let otherStallLocation = otherStall.0 let distanceToOtherStall = abs(thisStallLocation - otherStallLocation) return partialSum + distanceToOtherStall } } //if this stall is taken, treat its average distance to others as 0 let thisStallsLocation = valueIndexPair.0 let isThisStallTaken = valueIndexPair.1 return (thisStallsLocation, isThisStallTaken ? 0 : averageDistance) } //find location where average distance is maxiumum let bestLocationIndexPair = locationDistancePairs.max{$0.1 < $1.1}! let bestLocation = bestLocationIndexPair.0 print(bestLocation) ``` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 1-indexed. ``` ³Tạ⁸S JUÇÞḟTṪ ``` [Try it online!](http://jelly.tryitonline.net/#code=wrNU4bqh4oG4UwpKVcOHw57huJ9U4bmq&input=&args=WzAsMSwwLDEsMCwwXQ) ### Algorithm Naive implementation of the question. [Answer] # Java "only" ~~270 200 196 187 196 138 148~~ 146 bytes! saved ~~4 13~~ countless bytes thanks to Leaky Nun! ~~1 byte thanks to Micheal~~ Golfed ``` int m(boolean[]b){int r=0,l=b.length,i,j,k=0,z=r;for(i=0;i<l;i++){if(b[i])for(j=0,k=0;j<l;j++)if(!b[j])k+=i>j?i-j:j-i;if(k>z){r=i;z=k;}}return r;} ``` Ungolfed ``` int m(int[] s) { int l=s.length,i,j=0,k=0; boolean[] b = new boolean[l]; int[] a = new int[l]; //see what stalls are open for (i = 0; i < s.length; i++) { if (s[i] == 0){ b[i] = true; } } //assign the sum of distance to the a[] for (i = 0; i < l; i++) { if (b[i]) { for (j = 0; j < l; j++) { if (!b[j]) { a[i]+= Math.abs(i - j); } } } } //find the stall the greatest distance away breaking ties based on the furthest left for (i = 0; i < l; i++) { if (b[i] && (a[i] > k || k == 0)) { k = a[i]; j=i; } } //return the index return j; } ``` input as an boolean array where true implies an open stall. [Answer] # Ruby, ~~79~~ ~~78~~ 76 + `n` flag = 77 bytes Output is 0-based indexing. Input is STDIN line of 0's and 1's. ``` p (r=0...~/$/).max_by{|i|k=0;$_[i]>?0?0:r.map{|j|k+=$_[j]<?1?0:(j-i).abs};k} ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` ~ftGf!-|Xs&X>) ``` [**Try it online!**](http://matl.tryitonline.net/#code=fmZ0R2YhLXxYcyZYPik&input=WzEgMCAxIDAgMCAwIDAgMSAxXQ) Output is 1-based. ### Explanation ``` ~f % Implicitly take input. Compute row vector with indices of zeros t % Duplicate that Gf! % Push input again. Compute column vector of indices of ones -| % Absolute differences with broadcast. Gives 2D array with all combinations Xs % Sum of each column &X> % Arg max. Gives the index of the first maximizer if there are several ) % Index into row vector of indices of zeros. Implictly display ``` [Answer] ## Perl 84 + 3 (`-alp` flags) = 87 bytes ``` for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]} ``` Needs `-alp` flags to run. Takes a string of 1 and 0 separated by spaces as input. For instance : ``` perl -alpe '$m=0;for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]}' <<< "1 0 1 0 0 1 0 1 1 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 0" ``` Note that I added `$m=0` at the begining, but that's only to test it on multiple entries. [Answer] ## Matlab, 87 bytes ``` n=input('');k=numel(n);[a b]=ndgrid(1:k);[x y]=max(sum(abs(a-b).*repmat(n,k,1)').*~n);y ``` Takes array of ones and zeros; uses 1-based indexing. Like some other answers maximises total not average distance. Probably there's some more golfing possible... [Answer] ## JavaScript (ES6), ~~87~~ ~~86~~ ~~82~~ 75 bytes ``` a=>a.map((u,i)=>u||(a.map((v,j)=>u+=v*(i>j?i-j:j-i)),u>x&&(x=d,r=i)),x=0)|r ``` Takes a boolean array (true/false or 1/0). No point calculating the average distance since they're all using the same common factor, so just calculating the total distance for each stall and finding the first index of the highest one. Edit: Saved 1 byte by using `*` instead of `&&`. Saved 5 bytes by finding the highest distance manually based on a comment by @Dendrobium. Saved 7 bytes by reusing `u` as the pseudo-reduce accumulator based on a comment by @edc65. [Answer] # J, 27 bytes ``` (#{:@-.~]/:[:+/]|@-/~#)i.@# ``` [Online interpreter](http://tryj.tk/). [Answer] # Ruby, ~~87~~ 76 bytes Threw this first draft quickly together, but in the meantime [Value Ink](https://codegolf.stackexchange.com/a/89255/4372) had already posted an 80 byte Ruby answer... edit: took off some bytes with help from Value Ink: ``` ->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}} ``` It's an anonymous function that takes an array of truthy/falsy values, like for instance so: ``` f=->->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}} # Test case number 5: p f[[1, 1, 1, 1, nil, nil, nil, nil, nil, nil, 1]] # => 9 ``` [Answer] # Mathematica, 53 bytes ``` MaximalBy[a=PositionIndex@#;a@0,Tr@Abs[#-a@1]&][[1]]& ``` Uses 1-based indexing and takes input as a list of 0s and 1s. [Answer] # Javascript ES6 - ~~98~~ ~~95~~ ~~91~~ ~~86~~ ~~84~~ 88 bytes Edit: Seems that the leftmost-stall should be used in the case of a tie. Squared distances no longer work, reverted to absolute distance. ``` (r,x=0,f=g=>r.reduce(g,0))=>f((p,o,i)=>x<(o=f((p,c,j)=>p+c*!o*Math.abs(i-j)))?(x=o,i):p) ``` Ungolfed: ``` (r, // string input x=0, // current max distance f=g=>r.reduce(g,0))=> // iterator function f((p,o,i)=> // for each stall x<(o=f((p,c,j)=> // iterate through all stalls and p+c*!o*Math.abs(i-j)))? // calculate sum of distances from current stall (x=o,i): // if total dist is greater than x, update x, return index p) // else return previous max index ``` Test runs: ``` f=(r,x=0,f=g=>r.reduce(g,0))=>f((p,c,i)=>x<(c=+c?0:f((p,c,j)=>p+c*Math.abs(i-j)))?(x=c,i):p) f([1,0,1]) // 1 f([0,0,1,0,1,1]) // 0 f([1,0,1,0,0,0,0,1,1]) // 1 f([1,0,0,0,0,0,1,1,0,0,0,0]) // 11 f([1,1,1,1,0,0,0,0,0,0,1]) // 9 f([1,0]) // 1 ``` [Answer] # Lua, 165150 Byes ``` n=arg[1]n=n:gsub("%|%-","1"):gsub("%| ","0")i=0 for s in n:gmatch("0+")do i=(i<#s)and(#s)or(i)end n,l=n:find(("0"):rep(i))print(n+math.floor((l-n)/2)) ``` This cheats a little using the fact that generally, lua passes a table called arg containing any command line inputs to it. I'm a bit disappointed that I used a for in loop, but I couldn't think of a smaller way to pull it off. Also, Because lua, 1 based indexing was used. Edit Snipped 15 bytes from a wasteful gsub. [Answer] # C#, 127 bytes ``` public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();} ``` # Test Bed ``` public static void Main() { var respectful = new Respectful(); foreach (var kvp in testCases) { $"{kvp.Key}: Expected {kvp.Value} Actual {respectful.G(kvp.Key.ToCharArray())}".Dump(); } } public static readonly List<KeyValuePair<string, int>> testCases = new List<KeyValuePair<string, int>> { new KeyValuePair<string, int>("101", 1), new KeyValuePair<string, int>("001011", 0), new KeyValuePair<string, int>("101000011", 1), new KeyValuePair<string, int>("100000110000", 11), new KeyValuePair<string, int>("11110000001", 9), new KeyValuePair<string, int>("10", 1), new KeyValuePair<string, int>("1001", 1), }; public class Respectful { public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();} } ``` ]
[Question] [ ## Introduction: [![enter image description here](https://i.stack.imgur.com/9RDww.png)](https://i.stack.imgur.com/9RDww.png) > > Inspired by a discussion that is already going on for many years > regarding the expression \$6÷2(1+2)\$. > > > With the expression \$6÷2(1+2)\$, mathematicians will quickly see that the correct answer is \$1\$, whereas people with a simple math background from school will quickly see that the correct answer is \$9\$. So where does this controversy and therefore different answers come from? There are two conflicting rules in how \$6÷2(1+2)\$ is written. One due to the part `2(`, and one due to the division symbol `÷`. > > > Although both mathematicians and 'ordinary people' will use [*PEMDAS*](https://en.wikipedia.org/wiki/Order_of_operations#Mnemonics) (Parenthesis - Exponents - Division/Multiplication - Addition/Subtraction), for mathematicians the expression is evaluated like this below, because \$2(3)\$ is just like for example \$2x^2\$ a monomial a.k.a. "*a single term due to implied multiplication by juxtaposition*" (and therefore part of the `P` in `PEMDAS`), which will be evaluated differently than \$2×(3)\$ (a binomial a.k.a. two terms): > > > $$6÷2(1+2) → \frac{6}{2(3)} → \frac{6}{6} → 1$$ > > > Whereas for 'ordinary people', \$2(3)\$ and \$2×(3)\$ will be the same (and therefore part of the `MD` in `PEMDAS`), so they'll use this instead: > > > $$6÷2(1+2) → 6/2×(1+2) → 6/2×3 → 3×3 → 9$$ > > > However, even if we would have written the original expression as \$6÷2×(1+2)\$, there can still be some controversy due to the use of the division symbol `÷`. In modern mathematics, the `/` and `÷` symbols have the exact same meaning: divide. Some rules pre-1918*†* regarding the division symbol `÷`*††* state that it had a different meaning than the division symbol `/`. This is because `÷` used to mean "*divide the number/expression on the left with the number/expression on the right*"*†††*. So \$a ÷ b\$ then, would be \$(a) / (b)\$ or \$\frac{a}{b}\$ now. In which case \$6÷2×(1+2)\$ would be evaluated like this by people pre-1918: $$6÷2×(1+2) → \frac{6}{2×(1+2)} → \frac{6}{2×3} → \frac{6}{6} → 1$$ *†: Although I have found multiple sources explaining how `÷` was used in the past (see ††† below), I haven't been able to find definitive prove this changed somewhere around 1918. But for the sake of this challenge we assume 1918 was the turning point where `÷` and `/` starting to mean the same thing, where they differed in the past.* > > *††: Other symbols have also been used in the past for division, like `:` in 1633 (or now still in The Netherlands and other European non-English speaking countries, since this is what I've personally learned in primary school xD) or `)` in the 1540s. But for this challenge we only focus on the pre-1918 meaning of the obelus symbol `÷`.* > > *†††: Sources: [this article in general](https://slate.com/technology/2013/03/facebook-math-problem-why-pemdas-doesnt-always-give-a-clear-answer.html). And the pre-1918 rules regarding `÷` are mentioned in: [this](https://www.jstor.org/stable/2972726?seq=1#page_scan_tab_contents)* The American Mathematical Monthly *article from February 1917; this German* Teutsche Algebra *book from 1659 [page 9](https://books.google.co.uk/books?id=ZJg_AAAAcAAJ&hl=nl&pg=PA9#v=onepage&q&f=false) and [page 76](https://books.google.co.uk/books?id=ZJg_AAAAcAAJ&hl=nl&pg=PA76#v=onepage&q&f=false); [this](http://www.gutenberg.org/files/13309/13309-pdf.pdf?session_id=0cee2845b0701c91a6f32df9f80cc32ea90f50e0)* A First Book in Algebra *from 1895 page 46 [48/189].* > > > Slightly off-topic: regarding the actual discussion about this > expression: **It should never be written like this in the first > place!** The correct answer is irrelevant, if the question is unclear. > *\*Clicks the "close because it's unclear what you're asking" button\**. > > And for the record, even different versions of Casio > calculators don't know how to properly deal with this expression: > > [![enter image description here](https://i.stack.imgur.com/DIBInm.jpg)](https://i.stack.imgur.com/DIBInm.jpg) > > > ## Challenge: You are given two inputs: * A (valid) mathematical expression consisting only of the symbols `0123456789+-×/÷()` * A year And you output the result of the mathematical expression, based on the year (where `÷` is used differently when \$year<1918\$, but is used exactly the same as `/` when \$year\ge1918\$). ## Challenge rules: * You can assume the mathematical expression is valid and only uses the symbols `0123456789+-×/÷()`. This also means you won't have to deal with exponentiation. (You are also allowed to use a different symbols for `×` or `÷` (i.e. `*` or `%`), if it helps the golfing or if your language only supports ASCII.) * You are allowed to add space-delimiters to the input-expression if this helps the (perhaps manual) evaluation of the expression. * I/O is flexible. Input can be as a string, character-array, etc. Year can be as an integer, date-object, string, etc. Output will be a decimal number. * You can assume there won't be any division by 0 test cases. * You can assume the numbers in the input-expression will be non-negative (so you won't have to deal with differentiating the `-` as negative symbol vs `-` as subtraction symbol). The output can however still be negative! * You can assume `N(` will always be written as `N×(` instead. We'll only focus on the second controversy of the division symbols `/` vs `÷` in this challenge. * Decimal output-values should have a precision of at least three decimal digits. * If the input-expression contains multiple `÷` (i.e. \$4÷2÷2\$) with \$year<1918\$, they are evaluated like this: \$4÷2÷2 → \frac{4}{\frac{2}{2}} → \frac{4}{1} → 4\$. (Or in words: *number \$4\$ is divided by expression \$2 ÷2\$, where expression \$2 ÷2\$ in turn means number \$2\$ is divided by number \$2\$*.) * Note that the way `÷` works implicitly means it has operator precedence over `×` and `/` (see test case \$4÷2×2÷3\$). * You can assume the input-year is within the range \$[0000, 9999]\$. ## 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: ``` Input-expression: Input-year: Output: Expression interpretation with parenthesis: 6÷2×(1+2) 2018 9 (6/2)×(1+2) 6÷2×(1+2) 1917 1 6/(2×(1+2)) 9+6÷3-3+15/3 2000 13 ((9+(6/3))-3)+(15/3) 9+6÷3-3+15/3 1800 3 (9+6)/((3-3)+(15/3)) 4÷2÷2 1918 1 (4/2)/2 4÷2÷2 1900 4 4/(2/2) (1÷6-3)×5÷2/2 2400 -3.541... ((((1/6)-3)×5)/2)/2 (1÷6-3)×5÷2/2 1400 1.666... ((1/(6-3))×5)/(2/2) 1×2÷5×5-15 2015 -13 (((1×2)/5)×5)-15 1×2÷5×5-15 1719 0.2 (1×2)/((5×5)-15) 10/2+3×7 1991 26 (10/2)+(3×7) 10/2+3×7 1911 26 (10/2)+(3×7) 10÷2+3×7 1991 26 (10/2)+(3×7) 10÷2+3×7 1911 0.434... 10/(2+(3×7)) 4÷2+2÷2 2000 3 (4/2)+(2/2) 4÷2+2÷2 1900 2 4/((2+2)/2) 4÷2×2÷3 9999 1.333... ((4/2)×2)/3 4÷2×2÷3 0000 3 4/((2×2)/3) ((10÷2)÷2)+3÷7 2000 2.928... ((10/2)/2)+(3/7) ((10÷2)÷2)+3÷7 1900 0.785... (((10/2)/2)+3)/7 (10÷(2÷2))+3×7+(10÷(2÷2))+3×7 1920 62 (10/(2/2))+(3×7)+(10/(2/2))+(3×7) (10÷(2÷2))+3×7+(10÷(2÷2))+3×7 1750 62 (10/(2/2))+(3×7)+(10/(2/2))+(3×7) 10÷2/2+4 2000 6.5 ((10/2)/2)+4 10÷2/2+4 0100 2 10/((2/2)+4) 9+6÷3-3+15/3 9630 13 9+(6/3)-3+(15/3) 9+6÷3-3+15/3 0369 3 (9+6)/(3-3+(15/3)) ``` [Answer] # [R](https://www.r-project.org/), ~~68~~ 66 bytes ``` function(x,y,`=`=`/`)eval(parse(t=`if`(y<1918,x,gsub('=','/',x)))) ``` [Try it online!](https://tio.run/##hdDJDsIgEAbgu09hvJStgRmkLYnzLlVjjYlR45b69JW44YrD8ZsZ4N92DXXNYTXdL9Yr1qqTqikcXfPZcbxkm/F2N2N7qhdNzU4j8FCpVs13hwnLKFOZzlTLQ3UNGxSEgoFEPlD9WGig6vPeTw8ry6t7WZDNrQSnbWxBY0zKobr7kJDwZfdtf5X2@zwDKnLLhSPUsQ@HaYeHg0BywuXgni8J/3cphxL8zY1GaUX5@kTwHtIOD6c/85ScD/nIz4Ri/t895hc8/NC@uQ@VcnPZ350B "R – Try It Online") Expects equality sign `=` instead of `÷` and `*` instead of `×`. The code makes use of some nasty operator overloading, making advantage of the fact that `=` is a right-to-left operator with very low precedence (the exact behavior that we want from pre-1918 `÷`), and R retains its original precedence when it is overloaded. The rest is automatically done for us by `eval`. As a bonus, here is the same exact approach implemented in terser syntax. This time our special division operator is tilde (`~`): # [Julia 0.7](http://julialang.org/), 51 bytes ``` ~=/;f(x,y)=eval(parse(y<1918?x:replace(x,'~','/'))) ``` [Try it online!](https://tio.run/##jdHLCsIwEAXQvV8hbppHSzIT0zY@8FuKVFCKlPpAN/PrNaBQbQpm1idzyZ3TrTlWRd/TVq0P7JE@@ba@Vw1rq@5Ss@cGHJS7x6qr26ba1x4klKSJSjjnfdsdz9fmzA5skRMKBhL5Ip0PgxrKOeezv9CnFCPoZE4mMxKsMoNFrXUUhDKAS0LCn9hPdBkJg40MKM8MF5ZQDQ9wGQkhhCCQrLAZ2O9836ONglCAG0OtUBpR/P4HnINICCGk2I0Ut9EXLsPKJ249DScu46EvyIyg8xMF9Tu6fwE "Julia 0.7 – Try It Online") [Answer] # JavaScript (ES6), ~~130 129~~ 120 bytes *Saved 9 bytes thanks to [@ScottHamper](https://codegolf.stackexchange.com/users/85744/scott-hamper)* Takes input as `(year)(expr)`. Expects `%` and `*` instead of `÷` and `×`. ``` y=>g=e=>(e!=(e=e.replace(/\([^()]*\)/,h=e=>eval(e.split`%`.reduceRight((a,c)=>y<1918?`(${c})/(${a})`:c+'/'+a))))?g:h)(e) ``` [Try it online!](https://tio.run/##vZTdbtpAEIXv@xTUqpVZb7z/a@OoJu/Q26YVluMAFQoo0EhRlefggXgwOmucYvxDfJOukJCXnY/jM2f2V/acbfKnxXobPq7ui8NDenhJJ7O0SCdQfE6hSAv2VKyXWV4Av4PvP4H8CO4Iv567I8VztoSCbdbLxXbqT/Hk/e@8@LaYzbcA2XVO0snLV5nI8e0UvvzJXwnHr@yVTG9yesWvaEZw3c5u5gQKcshXj5vVsmDL1QweQAk5JuBFvgpAUkW8UcciZMT5KKlvQcQV2e/Kmk/nSFQSD0TK@lbEQVXEJlIJIRCZ0MjXoabScu31IXVdJSQUlWpCQk0ouLqW2vFgtD4zACvQaNAncocRzlvjK191mtBjBBj0lqsWrRQ6hGbqWwZt5a0mKVPSQPoRvkBgfTzjddNCzayRUcQYc46C5JGzc7@znTKHgyWLKmrZKsnBlTgw6dYspEW0DJRvAxtK6/U6ENZj4DTvd6jVlmwsbGqOZTIQLJiqgY9YAFtx2wlIpAMLrqgOYu9Cz1RUT4CrwFjp/S7uSNUHMCud/gfofJ8pmNHmLQiIBFUhe@4BnAHaPwVdw2pKmR2ZOk3Vu0TVmCpU6fLfJCa4jkSMk75IlExrfRoAU16pyNQNJP4qBiJ1S@SR2OMkTgb2h@CHar/Vo@q9WaLGtTEV5di7rvO4x84hWMHisT1hT1xNeNzCquOlInzANhHiEkXPH70jNlKNfJZdf8sobe20rgL7n/6p6oAzCifZXJqPiNn6bfbPKdPMiRyMPAuzU1pKpYYc/gI "JavaScript (Node.js) – Try It Online") ## How? ### Processing leaf expressions The helper function \$h\$ expects a leaf expression \$e\$ as input, processes all `%` symbols according to the rules of the year \$y\$ (defined in the parent scope) and evaluates the resulting string. If \$y<1918\$, we transform `X%Y` into `(X)/(Y)`, to enforce low precedence and repeat this process for the entire string from right to left to enforce right-to-left associativity. Examples: * `8%2` becomes `(8)/(2)`, whose simplified form is `8/2` * `2+3%3+2` becomes `(2+3)/(3+2)` * `8%2%2` becomes `(8)/((2)/(2))`, whose simplified form is `8/(2/2)` If \$y\ge 1918\$, each `%` is simply turned into a `/`. ``` h = e => // e = input string eval( // evaluate as JS code: e.split`%` // split e on '%' .reduceRight((a, c) => // for each element 'c', starting from the right and // using 'a' as the accumulator: y < 1918 ? // if y is less than 1918: `(${c})/(${a})` // transform 'X%Y' into '(X)/(Y)' : // else: c + '/' + a // just replace '%' with '/' ) // end of reduceRight() ) // end of eval() ``` ### Dealing with nested expressions As mentioned above, the function \$h\$ is designed to operate on a leaf expression, i.e. an expression without any other sub-expression enclosed in parentheses. That's why we use the helper function \$g\$ to recursively identify and process such leaf expressions. ``` g = e => ( // e = input e != // compare the current expression with ( e = e.replace( // the updated expression where: /\([^()]*\)/, // each leaf expression '(A)' h // is processed with h ) // end of replace() ) ? // if the new expression is different from the original one: g // do a recursive call to g : // else: h // invoke h on the final string )(e) // invoke either g(e) or h(e) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~324~~ ~~310~~ 306 bytes ``` lambda s,y:eval((g(s*(y<1918))or s).replace('%','/')) def g(s): if'%'not in s:return s l=r=j=J=i=s.find('%');x=y=0 while j>-1and(x:=x+~-')('.find(s[j])%3-1)>-1:l=[l,j][x<1];j-=1 while s[J:]and(y:=y+~-'()'.find(s[J])%3-1)>-1:r=[r,J+1][y<1];J+=1 return g(s[:l]+'('+g(s[l:i])+')/('+g(s[i+1:r])+')'+s[r:]) ``` [Try it online!](https://tio.run/##rZLdkpowFMfvfYrMdJjkEPlIAijspg/gK7BcuBW7OFQdsK3c9NXtibiKwOhMpxkvQs75//yfj31z@Nht1Xxfndb67VQuf7yvlqSeNkn@a1ky9p3VNmteRSzmALuK1OBW@b5cfssZteiUehRgssrXBBMhmZBijc/b3YEUW1InVX74WeFlQkpd6Y1e6ELX7rrYrowaXo660f6E/P4oypxsvjpiiZFjoo/8j0OB0Ta1TjcZWMoRgBlJqdNyusnS46vIXjaOFp/6Ol0kmQE0iW4MgMEVsOgAKp1W0wUXWdoYxIIbxMUpVpEmZcYpo9zcy6TIgFPwLt8FR/35hfI6rZIMTvuq2B7YmtHIkjYTXAIl7ZkS6WPb2qs59O0Qk@uhGPlCCIs8Ca1w8oiFI5jds8SAFXnsouuwYh5h7YqL0FP005fv91hq4IvFHL0pAEcBZ0b9GCrmfagaFos6bCZTN2YHGljSkvQmaqueP6uaBdhBTz7h9M0FA06A3fO6U2DCitCoHVr4TtvOBX2Oo9wwEK7rdjrHhBfBWdlzNkIUA6Jwoyg6A29E4TEjRCX0XQpbWqEdOiKknb0Ley5vA@64tNFdaJgofggUMxHfA31X9oFnHGNhy@s69D3JlT2j3XnE4h4oo8FcjQ7XBJXPYOKfYdb/dGY9d@a7gQruhossJlsWTO6WmJs1vjiC8YjoR3B2alxzjZw13Z30LYY8gLP5oXYkoY8wKRLwx5U1ihgmPHTB@//52NNIusGf/gI "Python 3.8 (pre-release) – Try It Online") Takes `%` instead of `÷` and `*` instead of `×` [Answer] # Perl 5, ~~47~~ ~~97~~ 95 bytes ``` / /;$_="($`)";$'<1918?s-%-)/(-g:y-%-/-;$_=eval ``` ``` $_="($F[0])";1while$F[1]<1918&&s-\([^()]+\)-local$_=$&;s,%,)/((,rg.")"x y,%,,-ee;y-%-/-;$_=eval ``` [TIO](https://tio.run/##hY9RT4MwFIXf@RWE7JKW0tHbrgOCvvrmL9jQEEN0SePIMOr@vHjLFEEfbPrQ7/T0ntOuPTk7DKv764itbnaq5lGFb08H1xJhfYUlFnHcyz3b3TFeiz2X7vjQOHqwiqs@hZRnjKWnx3XEo/fwTEIq27Y6S5CZrMjWvjZuGLagE4ZC81ArLIIfpIA8KMUWjDQCbWbIoNRSwYKUDWjQ3l5MR1IZwlYanljQmQ715o@EXsJEg02sROvj7ZwxxzJAlWlhkpxmljgn9ASLO5jdURHhq4yVv2HsRUAZJixpTaC8jTE/g9MWBvLL01/a188UMJrHuc8TSySL/teSWzX2pd9sLjkTKVTq49i9HI7P/SCbzg3y1q4VfgI) [Answer] # Rust - ~~1066~~ ~~860~~ ~~783~~ ~~755~~ 740 bytes ``` macro_rules! p{($x:expr)=>{$x.pop().unwrap()}}fn t(s:&str,n:i64)->f64{let (mut m,mut o)=(vec![],vec![]);let l=|v:&Vec<char>|*v.last().unwrap();let z=|s:&str|s.chars().nth(0).unwrap();let u=|c:char|->(i64,fn(f64,f64)->f64){match c{'÷'=>(if n<1918{-1}else{6},|x,y|y/x),'×'|'*'=>(4,|x,y|y*x),'-'=>(2,|x,y|y-x),'+'=>(2,|x,y|y+x),'/'=>(5,|x,y|y/x),_=>(0,|_,_|0.),}};macro_rules! c{($o:expr,$m:expr)=>{let x=(u(p!($o)).1)(p!($m),p!($m));$m.push(x);};};for k in s.split(" "){match z(k){'0'..='9'=>m.push(k.parse::<i64>().unwrap() as f64),'('=>o.push('('),')'=>{while l(&o)!='('{c!(o,m);}p!(o);}_=>{let j=u(z(k));while o.len()>0&&(u(l(&o)).0.abs()>=j.0.abs()){if j.0<0&&u(l(&o)).0<0{break;};c!(o,m);}o.push(z(k));}}}while o.len()>0{c!(o,m);}p!(m)} ``` Rust does not have anything like 'eval' so this is a bit tough. Basically, this is a bog-standard Djisktra shunting-yard infix evaluator with a minor modification. ÷ is an operator with a variable precedence: lower than everything else (but parenthesis) in <1918 mode, higher than everything else in >=1918 mode. It is also 'right associated' (or left?) for <1918 to meet the 4÷2÷2 specification, and association is 'faked' by making ÷ precedence negative, then during evaluation treating any precedence <0 as associated. There's more room for golfing but this is a good draft i think. [Ungolfed at play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=012c163818ba57917facd55dcfd3e125) ]
[Question] [ ## Challenge Given an input integer `n > 0`, output the number of primes (*other* than `n`, if `n` itself is prime) that can be produced by altering one digit in the decimal expansion of n (without changing the number of digits). ## Examples For example, `n = 2`. By altering one digit in the decimal expansion of `2`, we can come up with three additional prime numbers, `3, 5, 7`, so `a(n) = 3`. For another example, `n = 13`. By altering one digit, you can get primes `11, 17, 19, 23, 43, 53, 73, 83`, so `a(13) = 8`. For a final example, `n = 20`. By altering one digit, you can get primes `23, 29`, so `a(20) = 2`. ## Sequence Here are the first 20 terms to get you started. This is OEIS [A048853](http://oeis.org/A048853). `4, 3, 3, 4, 3, 4, 3, 4, 4, 4, 7, 4, 8, 4, 4, 4, 7, 4, 7, 2` ## Rules * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Ignore leading zeros (for example, `03` is not a prime number under this formulation). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [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] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ ~~14~~ 11 bytes ``` ā°`<Ÿʒ.L}pO ``` Explanation: ``` ā Push inclusive range from 1 to the length of the input ° Raise 10 to the power of each element ` Push each element to the stack < Decrement the topmost element Ÿ Inclusive range For 13, this creates an array like [10 11 12 13 14 .. 98 99] ʒ.L} Only keep elements with a levenshtein distance to the input of exactly one p Check each element for primality O Sum ``` [Try it online!](https://tio.run/##MzBNTDJM/f//SOOhDQk2R3ecmqTnU1vg//@/oTEA "05AB1E – Try It Online") or [up to 100](https://tio.run/##MzBNTDJM/e9TVmmvpKBrp6BkX/n/SOOhDQk2R3ecmlSp51Nb4P9f57@hgQEA "05AB1E – Try It Online"). [Answer] # [Python 2](https://docs.python.org/2/), ~~146 136 127 121~~ 118 bytes Thanks to @Mr.Xcoder for suggestions ``` lambda I:sum(all(i%v for v in range(2,i))*sum(z!=x for z,x in zip(I,`i`))==1for i in range(1+10**~-len(I),10**len(I))) ``` Explanation: Generate numbers with length equal to input length, skipping first (1,10,100,1000,... ) ``` for i in range(1+10**~-len(I),10**len(I)) ``` Check that generated number differs from input by only one digit ``` sum(z!=x for z,x in zip(I,`i`))==1 ``` Check for prime ``` all(i%v for v in range(2,i)) ``` Count ``` sum(...) ``` [Try it online!](https://tio.run/##tVHRSsMwFH3PV1yR0qTLoEk7LYX4Ij4UBj746IarWF2gTUubzdkHf72alGzVgW/C5XBzzr03cE7zobe14sNSrIYyr55fcsjSblfhvCyx9PbwWrewB6mgzdVbgTmVhARmoL8QB6v29GD0XjY4oxu5IUQIZgR5WmMzFgbB57wsFM4INY@xJWT4PUo5IymCppVKg6T@/ManS2wOI3R/lz2AgMeYQmQr/oljXVtMzphv5A6vLPIJs5hgMlEXbiayW5HrowmT/MPlxPF/X2aWZ5ZhrmLHmyac2rFGun7SRaeNjaOtcJaAycZYTWaMrBEao/BX6raumrwt4F3qLdgsdg3oGi69LvW94xaF4x/Cjg08/AI) [Answer] # Javascript (ES6) 148 bytes Takes the input as a string and returns as a number ``` n=>(n.replace(/./g,"$`a$' ").split` `.map(s=>s&&[..."0123456789"].map(d=>r+=+(t=s.replace(/a/,d))[0]&&t^n&&(p=v=>t>1&(--v<2||t%v&&p(v)))(t)),r=0),r) ``` **Example code snippet:** ``` f= n=>(n.replace(/./g,"$`a$' ").split` `.map(s=>s&&[..."0123456789"].map(d=>r+=+(t=s.replace(/a/,d))[0]&&t^n&&(p=v=>t>1&(--v<2||t%v&&p(v)))(t)),r=0),r) for(var k=1;k<=20;k++) o.innerText+=f(""+k)+" " ``` ``` <pre id=o></pre> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~18~~ 15 bytes 3 bytes thanks to Dennis. ``` æḟ⁵æR×⁵$DnDS€ċ1 ``` [Try it online!](https://tio.run/##y0rNyan8///wsoc75j9q3Hp4WdDh6UBaxSXPJfhR05oj3Yb///83NAYA "Jelly – Try It Online") or [Verify all testcases](https://tio.run/##y0rNyan8///wsoc75j9q3Hp4WdDh6UBaxSXPJfhR05oj3Yb/jQwOtwOZ/wE). [Answer] # Mathematica, 105 bytes ``` F=Count[Range[f=IntegerDigits;g=10^Length@f@#/10,10g],n_/;PrimeQ@n&&MatchQ[f@n-f@#,{x=0...,_,x}]&&n!=#]&; ``` [Try it online!](https://tio.run/##Jc3BCsIgGADgV1kMPNnUriIIjUFQ0LqKDRn662F/sBkMomc3ofsH3@JyTPNWyqDOrzdm83AI3gR1wezBr32ClDcJSvDn1SPkqINumeBUcLAUJybva1r8qJGQm8tzHE3QeKyIfnbFu66jE92/lhA8qNYSWaqvz9Aw3fyzE7e2/AA "Mathics – Try It Online") `Function` which expects a positive integer `#`. Sets `f` equal to the function `IntegerDigits` which returns the list of digits of its input. We take the `Range` from `g` to `10g` (inclusive), where `g=10^Length@f@#/10` is the largest power of `10` less than or equal to the input `#`, then `Count` the `n` such that `PrimeQ@n&&MatchQ[f@n-f@#,{x=0...,_,x}]&&n!=#`. `PrimeQ@n` checks whether `n` is prime, `MatchQ[f@n-f@#,{x=0...,_,x}]` checks whether the difference between the list of digits of `n` and `#` is of the form `{0..., _, 0...}`, and `n!=#` ensures that `n` and `#` are `Unequal`. [Answer] # JavaScript (ES6), ~~153~~ ~~142~~ 139 bytes ``` n=>([...n].map((c,i,[...a])=>[...''+1e9].map((u,j)=>s+=j+i&&j!=c?p((a.splice(i,1,j),a.join``)):0),s=0,p=q=>eval('for(k=q;q%--k;);k==1')),s) ``` Accepts input as a string. Undefined behavior for invalid input, though it should terminate without error on any string I can think of. Not necessarily before the heat-death of the universe though, particularly for long strings. ### Demo ``` f= n=>([...n].map((c,i,[...a])=>[...''+1e9].map((u,j)=>s+=j+i&&j!=c?p((a.splice(i,1,j),a.join``)):0),s=0,p=q=>eval('for(k=q;q%--k;);k==1')),s) console.log([...''+1e19].map((_,i)=>f(i+1+'')).join()) i.onchange=()=>console.log(f(i.value)) ``` ``` <input id=i> ``` ### Improvements Saved 11 bytes by refactoring the `reduce()` calls into `map()` calls, and by implicitly copying the array `a` in the function parameter, instead of in within the context of the `splice()` call. Saved 3 bytes thanks to [@Neil](https://codegolf.stackexchange.com/questions/137195/primes-other-than-optimus/137270#comment336215_137270)'s suggestion to convert `[...Array(10)]` to `[...''+1e9]`. ### Unminified code ``` input => ( [...input].map( (char, decimal, [...charArray]) => [...'' + 1e9].map( (unused, digit) => sum += digit + decimal && digit != char ? prime( ( charArray.splice(decimal, 1, digit) , charArray.join`` ) ) : 0 ) , sum = 0 , prime = test => eval('for(factor = test; test % --factor;); factor == 1') ) , sum ) ``` ### Explanation The function uses a two-level `map()` to sum the amount of permutations that pass the primality test, which was borrowed and modified from [this answer](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/91309#91309). ### (Original answer) ``` reduce((accumulator, currentValue, currentIndex, array) => aggregate, initialValue) ``` So for example, to calculate the sum of an array, you would pass an `initialValue` of `0`, and return an `aggregate` equal to `accumulator + currentValue`. Modifying this approach slightly, we instead calculate the number of permutations that pass the primality test: ``` reduce( (passedSoFar, currentDecimal, currentIndex, digitArray) => isValidPermutation() ? passedSoFar + prime(getPermutation()) : passedSoFar , 0 ) ``` That is essentially the inner `reduce()`, which iterates all the permutations of the `digitArray` by changing each `decimal` to a specific `permutatedDigit`. We then need an outer `reduce()` to iterate all possible `permutatedDigit`'s with which to replace each `decimal`, which is just `0-9`. ### Abnormalities in implementation `[...''+1e9].map((u,j)=>...` was the shortest way [@Neil](https://codegolf.stackexchange.com/questions/137195/primes-other-than-optimus/137270#comment336215_137270) could think of to iterate an argument `0` through `9`. It would be preferable to do so with `u`, but `u` is not useful for each element in the array, in this case. `i+j` in the ternary condition checks to ensure that `0` is not a possible permutation of the leading digit, as per the challenge specification. `j!=c` ensures that the original `n` is not a candidate to go through the primality test. `(a.splice(i,1,j),a.join``)` is kind of a mess. `splice()` replaces the digit at `decimal == i` with the `permutatedDigit == j`, but since `splice()` returns the removed elements (in this case, would be equal to `[a[i]]`) instead of the modified array, we must use the comma operator to pass the modified array `a` to the primality test, but not before `join()`ing it into a number string. Lastly, the `eval()` is to save a byte since, compared to the more canonical approach, it is shorter: ``` q=>eval('for(k=q;q%--k;);k==1') ``` ``` q=>{for(k=q;q%--k;);return k==1} ``` The reference to the prime test `p` is initialized in an unused argument to the `map()` call. [Answer] # [Python 2](https://docs.python.org/2/), 134 bytes ``` lambda x,r=range,l=len:sum(~-f*(~-l(x)==sum(`f`[t]==x[t]for t in r(l(x))))and all(f%v for v in r(2,f))for f in r(10**~-l(x),10**l(x))) ``` [Try it online!](https://tio.run/##JU5BCsIwELz7ir1Ik7IFm2MhfkSFRNpoYJuWGEu9@PWYNXMYdnZmll0/6bkElUlfM9n5PlrYMepow2NC0jSF4fWexbdzbSESu9SaF8aZS7ppvRd2S4QEPkAUHCiwYQRLJNxxA3a36ip0UrJ2Vfentq1Hkcdazhzw/wA/IXpUvRwOULBGHxIYbxCa7twgkChC5h8 "Python 2 – Try It Online") More elegant, longer version: ``` lambda x,r=range,l=len:l(filter(lambda f:(~-f*(~-l(x)==sum(`f`[t]==x[t]for t in r(l(x)))))*all(f%v for v in r(2,f)),r(10**~-l(x),10**l(x)))) ``` The input is taken as a String. --- # Explanation (older version) * `lambda x,r=range,l=len:` - Defines a lambda with a String parameter `x` and two constant parameters `r=range` and `l=len`. * `sum(1...)` - Get the length, which saves 1 byte over `len([...])`. * `for f in r(10**~-l(x),10**l(x))` - Generates absolutely all the numbers with the same order of magnitude as the input (expect for `0`). For instance, an input of `3`, would result in `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. * `sum(1for t in r(l(x))if`f`[t]==x[t])==~-l(x)and f>1` - Checks if the current number is exactly 1 digit away from the input, and that it is higher than 1. * `all(f%v for v in r(2,f))` - Checks if the current number is prime. [Answer] # [Husk](https://github.com/barbuz/Husk), 32 bytes ``` Lof§&ȯ=1Σzo±≠d⁰o=Ld⁰L↑o≤Ld⁰Lmdİp ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxf998tMOLVc7sd7W8NziqvxDGx91Lkh51Lgh39YHRPk8apuY/6hzCYSTm3JkQ8H///@NDAA "Husk – Try It Online") ### Ungolfed/Explanation ``` İp -- get all primes md -- and convert them to list of digits ↑o≤ L -- take as long as the lenghth of these digit lists are ≤ .. Ld⁰ -- .. the number of digits of input of -- from those primes filter: o=Ld⁰L -- same number of digits as input §& -- and Σz -- the number of.. o±≠d⁰ -- .. digits that differ from input digits .. ȯ=1 -- .. must be one L -- finally count them ``` [Answer] # JavaScript (ES6), 137 bytes ``` i=(a=prompt()).length;s=0;while(i--)for(j=0;j<=9;j++){(b=[...a]).splice(i,1,j);k=b=b.join('');while(b%--k);s+=i+j&&a[i]!=j&&k==1}alert(s) ``` Adapts [my other answer](https://codegolf.stackexchange.com/a/137270/42091) into a full-program submission using the Web API methods `prompt()` and `alert()`. [Answer] # [Bean](https://github.com/patrickroberts/bean), 126 bytes ``` 00000000: a64d a065 8050 80a0 5d20 8001 a64d a06f ¦M e.P. ] ..¦M o 00000010: 8025 39b5 cb81 2065 27a6 4da0 6680 2581 .%9µË. e'¦M f.%. 00000020: 0035 cb81 2066 27a6 53d0 80cd a05e 8043 .5Ë. f'¦SÐ.Í ^.C 00000030: cf20 5d00 2080 82a0 65a5 3a20 66a6 4da0 Ï ]. .. e¥: f¦M  00000040: 6780 4da0 5e80 53d0 80a0 5e20 807b 2300 g.M ^.SÐ. ^ .{#. 00000050: b5cc a05e 8f4b c120 6728 264d a06f 814e µÌ ^.KÁ g(&M o.N 00000060: cecc a065 8b20 6681 4cd0 84a0 5d20 6581 ÎÌ e. f.LÐ. ] e. 00000070: 2066 814c a067 8025 3a26 206f b130 f.L g.%:& o±0 ``` [Try it online!](https://tio.run/##RZE7UsMwEIZ7TrEzTALVjqyXlbSUEIYZ6jAjyXK65ABU1DyP4AZ6ilxAPpjZVeSgwl6N7G@//RWS30@TqGsN3uoOvLAGnDCCHl6A6SRXojmf9gD5Z5OHhA@Yhy0glu3h4oRpCOSENKBWwUAMrgHJSNl6C7ojpLVOgDR0ALhY5eP4ipCuCqTHBVaOJI4Q6h9hTwijOhaK7GISVVoRxzCkJ8jj@IXjex6e8KaCFIFiL3kUQX0FNXeSNYwnSS9ZaFaD8RO2yCMNKX@voS9WFaQJZFv6vXxqElVVpmxLTm0AqagN7HDDEqxDb8Dny3kwQ5hgYqz@vQ4QG7ZopQN5Dtk1OlHSx/GNObfjC@yul5wz3leQ5cFSAfGVhTIJZaUjS@n58mxJevxgUKKQ8K44bSHNRi2BSsDUs9DaeoNeWj7oITSKZjotAuRhh4v1Eg75V0yT@QM "Bean – Try It Online") An adaption of [my full-program JavaScript submission](https://codegolf.stackexchange.com/a/137280/42091). ### JavaScript Equivalent ``` i=a.length s=0 while(i--){ j=10 while(j--){ (b=[...a]).splice(i,1,j) k=b=b.join('') while(b%--k); s+=i+j&&a[i]!=j&&k==1 } } s ``` ### Explanation `a` is implicitly initialized as the first line of input as a string and the last statement `s` is implicitly output, which contains the sum of prime permutations. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~28~~ 23 bytes *-5 bytes thanks to @ETHproductions.* ``` ¬x@AÇ|Y©+UhYZsÃâ kUn)èj ``` Takes a string as input. [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=rHhAQcd8WakrVWhZWnPD4iBrVW4p6Go=&inputs=IjEi,IjIi,IjMi,IjQi,IjUi,IjYi,Ijci,Ijgi,Ijki,IjEwIg==,IjExIg==,IjEyIg==,IjEzIg==,IjE0Ig==,IjE1Ig==,IjEwMCI=,IjE1MCI=,IjIwMCI=) [Answer] # [PHP](https://php.net/), ~~151~~ ~~147~~ ~~141~~ ~~140~~ ~~136~~ ~~134~~ ~~129~~ 128 bytes *-6 bytes thanks to @Einacio; -1 byte thanks to @Titus* ``` <?php for($i=$m=10**strlen($n=$argv[1]);$i-->$m/10;)if(levenshtein($n,$i)==$f=$t=1){while($t<$i)$f+=$i%$t++<1;$c+=$f==2;}echo$c; ``` [Try it online!](https://tio.run/##FcpNDsIgEAbQq7j4TKDYyLilowcxLgwBmaQ/hJK6MJ4d7fbl5ZRbG2455UNcioIwJibbdWstY5gVZsazvLY7PbSD9P0V05ms0xLVGLYwr6kG2d8JopkRGZVJf95JxqBQhz8jGoYcUY0ZyMGbvfHFfYNPC7xrrZGlHw "PHP – Try It Online") Formatted, with comments: ``` <?php // Work through each integer with the same number of digits as the input $argv[1]. for ($i = $m = 10 ** strlen($n = $argv[1]); $i-- > $m / 10;) // Is it exactly one digit different from the input? if (levenshtein($n, $i) == $f = $t = 1) { // Count its factors. while ($t < $i) $f += $i % $t++ < 1; // If there are exactly 2 factors then it's a prime, so increment the counter. $c += $f == 2; } // Print the final count. echo $c; ``` To keep it as short as I could, I've: * combined assignments `$f = $t = 1`; * snook in a `++` increment as part of another expression `$f += $i % $t++ == 0` (the increment is executed *after* the modulus operation and so does not affect its result); * and rather than using an `if` statement for a conditional increment have utilised the fact that boolean true when cast as an integer becomes 1, using `$c += $f == 2;` rather than `if ($f == 2) $c++;`. [Answer] # [Perl 6](http://perl6.org/), 83 bytes ``` {+grep &is-prime,m:ex/^(.*)(.)(.*)$/.map:{|map .[0]~*~.[2],grep *-.[1],?.[0]..9}} ``` [Try it online!](https://tio.run/##HYtLCoMwGAav8iNBNI2fj0WhFtuDhFRcJEUwNMRNJY1XT2s3M4thnPbLOdmNckNDCqen147yea2cn60Wttfv@lGAlwXKQ6yGnVwfPj8SZKN2vkN2SvxHXkG2StyPAFxiTOu0UcZGGm4UDLExZmRenlqga67pCw "Perl 6 – Try It Online") [Answer] # PHP, 100+1 bytes ``` for(;~($a=$argn)[$i];$i++)for($d=-!!$i;$d++<9;$c+=$k==1)for($a[$i]=$d,$k=$a;--$k&&$a%$k;);echo$c-$i; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/13a9bfa8ff90bc831f210f4ad3c3aac66e4d5f17). **breakdown** ``` for(;~($n=$argn)[$i];$i++) # loop through argument digits, restore $n in every iteration for($d=-!!$i; # loop $d from 0 (1 for first digit) $d++<9; # ... to 9 $c+=$k==1 # 3. if divisor is 1, increment counter ) for($n[$i]=$d, # 1. replace digit $k=$n;--$k&&$n%$k; # 2. find largest divisor of $n smaller than $n ); echo$c-$i; # print counter - length ``` [Answer] # Java 8, ~~201~~ 194 bytes ``` n->{String s=n+"";int r=0,i=0,j,k,t,u,l=s.length();for(;i<l;i++)for(j=0;++j<10;r+=n==u|t<2?0:1)for(u=t=new Integer(s.substring(0,i)+j+(i<l?s.substring(i+1):"")),k=2;k<t;t=t%k++<1?0:t);return r;} ``` **Explanation:** [Try it here.](https://tio.run/##bVGxbsMgEN37FSekSiCIZXsMppk7NEvGqoPj0BTbwREcqao03@6e7QyVWokD3T3uHe/R1pd6NZytbw/d2PR1jPBSO399AHAebXivGwvbKZ0L0PBp90JT5UZBK2KNroEteDAw@tXTdYfB@SNE4yVjemoIJleOolWdQpVUb2LWW3/EDy70@xC4dlWvnZRiSlqTaynbqsh1kMYbk76xKjf5upjhZNB4@wnP9MCjDTxmMe3jPJPTGCFbyYlu87vuZCHWjAmhOlPqrkKNBh87KauCeFHoYDEFD0HfRr3oOqd9T7ru8i6DO8CJrOGLutc3qMXiy/SmSaQzhQZXmTKng6QsKMDuK6I9ZUPC7EytyH1GNgqQwBSw2crFzL9Xe8/v@D8IK/N8DYx4JkJKxP1bbuMP) ``` n->{ // Method with integer as parameter and return-type String s=n+""; // String representation of the input-int int r=0, // Result-integer i=0,j,k, // Index-integers t,u, // Temp integers l=s.length(); // Length of the String for(;i<l;i++) // Loop (1) from 0 to `l` (exclusive) for(j=0;++j<10; // Inner loop (2) from 1 to 10 (exclusive) r+= // And after every iteration, raise the result by: n==u // If the current number equals the input |t<2? // or it is not a prime: 0 // Add nothing to the result-counter : // Else: 1) // Raise the result-counter by one for( // Inner loop (3) u=t= // First set both `u` and `t` to: new Integer( // Convert the following String to an integer: s.substring(0,i) // Get the substring from 0 to `i` (exclusive) +j // + `j` +(i<l? // + If `i` is smaller than the String-length: s.substring(i+1) // The substring from 0 to `i` (inclusive) : // Else: "")), // Nothing k=2; // And start `k` at 2 k<t; // Continue looping as long as `k` is smaller than `t` t=t%k++<1? // If `t` is divisible by `k`: 0 // Change `t` to 0 : // Else: t // Leave `t` as is ); // End of inner loop (3) // (`t` remained the same after loop 3? -> It's a prime) // End of inner loop (2) (implicit / single-line body) // And of loop (1) (implicit / single-line body) return r; // Return the result-counter } // End of method ``` `new Integer(s.substring(0,i)+j+(i<l?s.substring(i+1):"")` will result in these integers: For `0-9`: `1, 2, 3, 4, 5, 6, 7, 8, 9`. For `10`: `10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19`. For `11`: `11, 21, 31, 41, 51, 61, 71, 81, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19`. etc. [Answer] # JavaScript (ES7), 118 bytes Takes input as a string. ``` n=>[...2**29+'4'].map(d=>n.replace(/./g,c=>s+=d+i>0&(P=k=>N%--k?P(k):N-n&&k==1)(N=p+d+n.slice(++i),p+=c),i=p=0),s=0)|s ``` [Try it online!](https://tio.run/##DYvBjoIwFEX3fkUXCn0@qGCchTqv8wfE/WQSmwKmA742dOIG@Xamm3PP4p5f8zLRTi78lezbbu1pZdLfSqnjfn88Y37Kf9TTBNmSZjV1YTS2kwd1eBSWdERq0ekqkzcaSDe7shy@bnKAS1Nylg1ENciGArbIKo4upYgOioBkoXAUqIIiJrzj2vtJsiBRXwWLz7TVRzJEEPNGCOs5@rFTo3/Iu5HbmRdI5@3cpwhFnsNyh@tmWf8B "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = input number (as a string) [...2**29 + '4'] // generate "5368709124" (all decimal digits) .map(d => // for each digit d in the above string: n.replace(/./g, c => // for each digit c in n: s += // increment s if the following code yields 1: d + i > 0 & ( // if this is not the first digit of n or d is not "0": P = k => // P = recursive function taking k and using N: N % --k ? // decrement k; if k is not a divisor of N: P(k) // do recursive calls until it is : // else: N - n && // return true if N is not equal to n k == 1 // and k is equal to 1 (i.e. N is prime) )( // initial call to P ... N = // ... with N defined as: p + // the current prefix p d + // followed by d n.slice(++i), // followed by the trailing digits // (and increment the pointer i) p += c // append c to p ), // end of initial call i = p = 0 // start with i = p = 0 ), // end of replace() s = 0 // start with s = 0 ) | s // end of map(); return s ``` [Answer] # [Ruby](https://www.ruby-lang.org/) with `-rprime`, 101 bytes `-rprime` imports the Prime module into Ruby. Get all primes up to \$10^{floor(log\_{10} n)+1}\$ and count how many have the same number of digits from \$n\$ and are also 1 digit off. ``` ->n{d=n.digits;Prime.each(10**l=d.size).count{|x|d.zip(e=x.digits).count{|a,b|a==b}==l-1&&e.size==l}} ``` [Try it online!](https://tio.run/##PY1LCsIwFAD3PYULKbWY0NalPM/gXqWkTaoPahLygdomVzd@EJfDMIzx3SMNcE7kIBcOknK8orP7o8G7oIL1t6KuynIETi3OYkN75aVbwhQ4nVEXAqZf8lds2wUG0EWAkdR5Lr7lG2JM2ju7Gk7rljrV4iU1Wb3LmuqptEMlbSIyEaM/7xc "Ruby – Try It Online") ]
[Question] [ In the game [Tetris](http://en.wikipedia.org/wiki/Tetris), there are 7 types of bricks or *Tetr**i**minoes*, which are mathematically known as [tetr**o**minoes](http://en.wikipedia.org/wiki/Tetromino) because they are all made with 4 square segments: [![Tetris bricks](https://i.stack.imgur.com/YcgOC.png)](http://en.wikipedia.org/wiki/File:Tetrominoes_IJLO_STZ_Worlds.svg) The have the names I, J, L, O, S, T, and Z, that correspond to their approximate shapes. Counting 90° rotations, there are 19 unique shapes in total: ``` I I I I IIII J J JJ JJJ J JJ J J J JJJ L L LL L LLL LL L L LLL L OO OO SS SS S SS S TTT T T TT T T TTT T TT T ZZ ZZ Z ZZ Z ``` # Challenge Write a rectangular block of code that acts as the base segment these 19 shapes are made from. When this code is arranged into one of the shapes, a program should be formed that outputs the single uppercase letter associated with that shape. This must work for all 19 shapes. The leading empty areas present in some of the 19 shapes are filled in entirely with spaces (). The trailing empty areas are not filled with anything (so the programs are not always exactly rectangular). ## Example Suppose this was your code block: ``` ABC 123 ``` Then either arrangement of the block into the S Tetris piece would be a program that prints `S`: ``` ABCABC 123123 ABCABC 123123 ``` ``` ABC 123 ABCABC 123123 ABC 123 ``` (Notice that all leading empty space is filled with space characters, and that no lines have any trailing spaces.) The same idea applies to all 6 other pieces and their respective rotations. ## Notes * All 19 final programs are to be run in the same programming language. * If desired, you may add a single trailing newline to *all* programs (not just some, all or none). * Your code block may contain any characters (including spaces) that aren't [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode). * Output the letter to stdout (or your language's closest alternative) with an optional trailing newline. ## Scoring The submission whose code block has the smallest area (width times height) wins. This essentially means the shortest code wins, which is why this is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Tiebreaker goes to the *highest voted* answer. The `ABC\n123` example has area 3×2 = 6. ## Snippet Given a code block, this snippet will generate all 19 programs: ``` <script>function drawShape(X,n,v){for(var t="",e=0;e<v.length;e++)for(var l=0;l<n.length;l++){for(var r=0;r<v[e].length;r++)t+="X"===v[e][r]?n[l]:X[l];t+="\n"}return t}function go(){var X=document.getElementById("input").value;if(0!=X.length){var n=X.replace(/./g," ").split("\n");X=X.split("\n");for(var v="I (v1):|I (v2):|J (v1):|J (v2):|J (v3):|J (v4):|L (v1):|L (v2):|L (v3):|L (v4):|O:|S (v1):|S (v2):|T (v1):|T (v2):|T (v3):|T (v4):|Z (v1):|Z (v2):".split("|"),t="X\nX\nX\nX|XXXX| X\n X\nXX|XXX\n X|XX\nX\nX|X\nXXX|X\nX\nXX| X\nXXX|XX\n X\n X|XXX\nX|XX\nXX| XX\nXX|X\nXX\n X|XXX\n X|X\nXX\nX| X\nXXX| X\nXX\n X|XX\n XX| X\nXX\nX".split("|"),e="",l=0;l<v.length;l++)e+=v[l]+"\n\n"+drawShape(n,X,t[l].split("\n"))+"\n";e=e.substring(0,e.length-2),document.getElementById("output").value=e}}</script><style>html *{font-family: monospace;}</style>Code Block:<br><textarea id='input' rows='8' cols='64'>ABC&#010;123</textarea><br><button type='button' onclick='go()'>Go</button><br><br>All 19 Programs:<br><textarea id='output' rows='24' cols='64'></textarea> ``` [Answer] # <>< (Fish) - 12 \* 32 = 384 I was planning to go for a more elegant solution, but I somehow ended up with this, which is pretty brute-force: ``` c 0 g84*%\ c2*0 g84*%\ 0 84*g84*%\ c 84*g84*%\ c2*84*g84*%\ 0 88*g84*%\ c 88*g84*%\ ?v \ ;>?v~~?vv "L" o; > "S" o; >~?v "T" o; > ; >~?v"L"o ; >"J"o ?v \ >~?v~~?vv "I" o; > "J" o; > \~~?vv "T" o; > "Z" o; > ?v \ >?v"J"o; >?v"Z"o; "L"o;>?!v "J"o; >?v "T"o; > ?v?v"I"o; > >"L"o; >?v"T"o; >?v"O"o; >"S"o; ``` It's pretty simple, it checks the code in a 3x3 square for text and uses the results to see which tetrimino corresponds to the code's shape. I didn't take a lot of effort to golf it yet. Try the code [here](http://fishlanguage.com/playground) (after using the snippet to shape it like a tetrimino) [Example of code in shape Z (v1) here](http://fishlanguage.com/playground/BXmaj54BnPRyutjPL) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~26x20 = 520~~ ~~25x19 = 475~~ 23x17 = 391 ``` #ifndef M // #define M(a,b)a##b // #define W(z,x)M(z,x) // char*s,*S[]={"!!!!c",// "8M !7! M8 878","77",// "7!!MO887","788OM!!7"// ,"N7!78","7N87!"},r[5// ],*p=r;i=7;main(){for// (;i--;)strstr(S[i],r)// &&putchar("ITOJLSZ"[i// ]);} // #endif // __attribute__(( // constructor(__LINE__)// ))W(f,__LINE__)(){s= // " \ ";*p++=strlen(s)+12;}// ``` I was recently informed of GNU's function attributes, and most interestingly the `constructor` attribute, which allows for a more terse implementation of what I was doing in a more roundabout way in my earlier approach to this problem. The thrust of the idea is the same as before: Build a string and search for it in a list to identify which tetris block the code is laid out as. This is done by calling functions, each one adding a character to the string. The complication was and remains that the number of functions varies. Defining a function with `attribute((constructor(x)))` makes it so that the function is run before `main()` is entered, with the optional `x` being the priority (lower means it is run earlier). This removes the need for function pointers, which allows us to drop a macro, some declarations, and the calling chain. Using `__LINE__` for priority is iffy, since priority levels 0-100 are reserved. However, it does not result in errors, only warnings, and those are plentiful when golfing, so what's a few more? It would have helped shave another column off to not use priorities at all, but the order of execution does not seem to be defined. (They are reversed in this case, but other tests are inconclusive.) [Example of L v2 here](https://tio.run/##pZRBS8MwFIDv71c0GYykyxgKkkDo0cNk3Q4TBOsIXddqQLuRdiCO/fbaKYig7/C2UHr4oB8vSfmK8XNRdF1EWgNf1ZuyitLfcDIBoqVX@LqMUpGrtcwHg/Ullgfxod5l@vWmW4qXPMSNipfZKjlw1q@CK7KFmzRimkWpiYw2XHGtz7FoxtKFMfokMGaRMqY52aL4XLPvIeZGM35UIbshW1Yq3iXB@kTbt9zXQh6qbSBbhPXjsZVNG/pHLDO/UkGSLcPhbt@eLkrw6f3ibrZ85Jmn70ja4x9I/@vKeuOrSy3O5W0b/Hrfls4Jcaal2Nb9se6LdhuEc7Pp/NY5@ulK@SAq9fN9f9NNQp@F/0ufqBYb70ajpN/Va1mLRo6uru2xnwXpDg0D0h0aBqQ7NAxId2gYkO7QMCDdoWFAukPDgHSHhgHpDg0D0h0aBqQ7NAxId2gYkO7QMCDdoWFAukPDgHSHhgHpDg133Sc "C (gcc) – Try It Online") ## Older, more portable, approach ``` #ifndef M // #define M(a,b) a##b // #define W(z,x)M(z,x) // #define F W(f,__LINE__)// #define A W(a,__LINE__)// char r[5],*S[]={"####k"// ,";<<US##;",";##SU<<;",// ";;",";T<;#","<S #;# S"// "< <;<","T;#;<"},*s,*p=// r;i;typedef(*T)();T a17// ,a36,a55,a74;main(){for// (a17(),a36&&a36(),a55&&// a55(),a74&&a74();i--;) // strstr(S[i],r)&&putchar// ("ILJOZTS"[i]);}i=7; // #endif // F();T A=F;F(){s= // " \ ";*p++=strlen(s)+12;} // ``` One of my favourite problems I've solved on this site. I began by figuring each block would divine its own coordinates somehow. Rows are easy with `__LINE__`, and the number of horizontally adjacent blocks could be found by using the length of a string literal, like so: ``` char*s=//char*s=// " "" " ; ; ``` Take the length of the resulting string and and divide by a proper number and you have the width. Sadly, any empty space before the block is invisible by this method. I still suspected strings would be the solution, since whitespace only has meaning outside of strings very rarely, in things like `a+++b` vs. `a+ ++b`. I briefly considered something like that, but could not come up with anything useful. Another possibility would have been to let identifiers be "glued" together where blocks met: ``` A BA B ``` I would not be surprised if this could still make for an interesting solution. Despite its simplicity, it took me quite some time to find the string solution, which is based on this block fragment: ``` s=// " \ ";// ``` If the fragment has no horizontal neighbours, the newline on the second line is escaped by the backslash, creating a string of length 2. If, however, it does have a neighbour, the backslash will instead escape the quotion mark at the start of line 2 of the next block: ``` s=//s=// " \" \ ";//";// ``` This will create the string " \" " of length 5. More crucially, this also allows for detection of empty space before the block: ``` s=// " \ ";// ``` Again, the newline is escaped, and the whitespace of the empty block to the left is included in the resulting string " " of length 6. In total there are seven different configurations of blocks on a row that we need to worry about, and they all make strings of unique lengths: ``` 2 " " --- s=// " \ ";// 5 " \" " --- s=//s=// " \" \ ";//";// 6 " " --- s=// " \ ";// 9 " \" " ---- s=//s=// " \" \ ";//";// 10 " " --- s=// " \ ";// 8 " \" \" " --- s=//s=//s=// " \" \" \ ";//";//";// 11 " \" \" \" " ---- s=//s=//s=//s=// " \" \" \" \ ";//";//";//";// ``` The final blocks will of course not have such short length, but the principle is the same regardless of block size. This also has the bonus that a separate mechanism for detecting width is unnecessary. By adding a character corresponding to the length of this string to a results string, each of the 19 configurations yields a unique string, that needs only be compared to a suitable list once all the blocks have been run. Once this was sorted, the next big problem was how to "visit" each row of blocks. In C, we are very limited to what can be done outside of functions. We also need `main()` to appear, but only once. The latter is easily achieved by some `#define`s, but if we want the code of subsequent blocks to be inside of `main()`, the problem of how to know when to put the final closing curly bracket. After all, we don't know how many rows of blocks will actually be used. So we need to have `main()` static and somehow the rest to be dynamic. If the other block-rows are to be self-contained, they need to be functions, but we need to make sure each function has a name that is unique, while also being predictable enough to be callable from `main()`. We also need a mechanism for knowing which functions are actually there to be called. Generating unique names is solved by helper macros: ``` #define M(a,b) a##b // #define W(z,x)M(z,x) // #define F W(f,__LINE__) // #define A W(a,__LINE__) // ``` Calling `F` will create an identifier whose name begins with an f and ends with the line number. `A` does the same but with a as prefix, which is used for the second part of the solution, which is function pointers. We declare four such pointers: ``` typedef(*T)();T a17,a36,a55,a74; ``` Since these are declared as global variables, they are conveniently set to NULL. Later on, each block-row will have the following piece of code: ``` F();T A=F;F() ``` This will first declare a function, define the appropriate function pointer to point to that function (we can only define globals once, but the earlier declaration did not count as a definition, even if it did initialise to NULL), and then define the actual function. This allows `main()` to call any function pointer that is non-NULL (a17 will never be NULL): ``` a17(),a36&&a36(),a55&&a55(),a74&&a74() ``` Doing so will build the string `r`, which is then looked for in the table of strings and if found, the appropriate letter is output. The only remaining trick is that the list of strings to match against were shortened whenever ambiguity could be avoided, or overlapping strings could be conflated. [Example of L v2 here](https://tio.run/##pZRBa9swFIDv71cICYzkKJSu8XyQfOhhgZZmPdhlsCwENbVbs9YNTgbtQn57@pJbKe/wZBNsoQ9/yI78rcaPq9XhINiHapvuoW7E7PP02RlEuFDUdrWY6WDvjQhK3Q92/dL/7ZuZnc5DXVO0NXa5vLn6@WO5NINcl@gKA12rp9CLfp4tbFrOF8VOKjz@yiiXlc77u1IpJ3GoVHnnPQ6jXNKdJJV3Cq@@FMopUcatS3rhnUdN5RRe9zbd2HRdRLl617rt@7rGv0CnldHGVSKc53HvK1x8tyHLbMgn7iW0nTa75rWPcmlchDZHY5Lg6TjMsiSJcuGdx/vzCaryCT5iOx47E7fvN9sef7qctwvbmyRZ/9set1zcM8qrm@vb31Up0Wbcvi1yF/091t1D23yZjnJNT7vgspg6HO02xRCXJOb/RH1D6Xo0KvD9P9ed3pjR@Te3P62LLC4fAFlcPgCyuHwAZHH5AMji8gGQxeUDIIvLB0AWlw@ALC4fAFlcPgCyuHwAZHH5AMji8gGQxeUDIIvLB0AWlw@ALC4fAFlcPgCyuHxwOHwA "C (gcc) – Try It Online") [Answer] # x86 opcode(.com), ~~86~~ 82 bytes Tester: ``` org 100h macro e { db $F6,$04,$DF,$78,$13,$75,$08,$00,$C0,$40,$83,$C6,$52,$EB,$F1,$88 db $C2,$00,$D0,$00,$D0,$46,$EB,$E8,$05,$02,$40,$73,$ED,$E8,$26,$00 db $50,$08,$43,$4D,$2C,$0C,$1C,$15,$A5,$14,$10,$13,$3F,$27,$20,$0F db $51,$1D,$29,$49,$49,$4A,$4A,$4A,$4A,$4C,$4C,$4C,$4C,$4F,$53,$53 db $54,$54,$54,$54,$5A,$5A,$5F,$AE,$75,$FD,$8A,$55,$12,$B4,$02,$CD db $21,$C3 } macro n { db 82 dup $20 } macro s { db 10 } n e s n e s e e ``` Source: ``` BOF: ;mov bx, 100h p: test [si], byte $DF js _a ; exist jnz _b ; newline _z: add al, al inc ax q: add si, EOF-BOF jmp p _b: mov dl, al add al, dl add al, dl inc si jmp p _a: add ax, 4002h jnc q call y db 80,8,67,77,44,12,28,21,165,20,16,19,63,39,32,15,81,29,41 db 'IIJJJJLLLLOSSTTTTZZ' y: pop di scasb jnz y+1 mov dl,[di+18] mov ah,2 int $21 ret EOF: ``` Run in win7dos where init AX=0, SI=100, BX=0 [References](http://www.fysnet.net/yourhelp.htm) ]
[Question] [ Your task is to write some code in Python 2 or 3 such that this expression: ``` (a+b)(c+d) == a*c + b*c + a*d + b*d ``` will evaluate to `True` without raising any exceptions. To clarify, I will copy your code into a file, then `from` the file `import *`. Then I will type the expression into the console and verify that it is `True`. This is code-golf, so the answer with the shortest length (in bytes) wins. [Answer] ## ~~54~~ ~~52~~ ~~50~~ ~~49~~ ~~48~~ ~~45~~ 39 bytes Removed 4 bytes thanks to Dennis. The latest version is inspired by the "some reason" in xnor's answer. ``` class t(int):__add__=type a=b=t() c=d=0 ``` [Answer] ## 54 bytes ``` class m(int):__call__=__add__=lambda*x:m() a=b=c=d=m() ``` Make an object that inherits from `int`, except adding or calling just returns a copy of itself. Same length: ``` class m(int):__call__=__add__=lambda a,b:a a=b=c=d=m() ``` I thought `min` or `{}.get` would work in place of `lambda a,b:a`, but for some reason they act only on the second argument. [Answer] # ~~81~~ 66 bytes ``` class e:__mul__=lambda*o:0;__add__=lambda*o:lambda x:0 a=b=c=d=e() ``` [Answer] ### 68 bytes While it cannot really compete with the existing answers, this one actually performs the calculation in question: ``` from sympy.abc import* type(a+b).__call__=lambda x,y:(x*y).expand() ``` Explanation: * SymPy is a module for symbolic computations. * `sympy.abc` contains all single-letter symbols, in particular ones named `a`, `b`, `c`, and `d`. * `a+b` is an `Add` object, which represents a general sum. * `type(a+b).__call__= […]` monkey-patches the `Add` class to give it evaluation capabilities, in this case enabling it to work like a multiplication of caller and callee. * `expand` is necessary to make the expressions actually equal (since SymPy only performs thorough equality checks on demand). ]
[Question] [ **Overview** Write a program that prints out simple fractal patterns given a bit pattern encoding the fractal, plus the per-generation scale factor of the fractal and number of generations. **Explanation** Here is an ASCII representation of the [Sierpinski Carpet](https://en.wikipedia.org/wiki/Sierpinski_carpet): Generation 0: ``` # ``` Generation 1: ``` # # # # # # # # ``` Generation 2: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Generation n+1 of the ASCII Sierpinski Carpet is made up of a 3x3 grid containing 8 copies of generation n, with the central element of the grid missing. So, because it is defined using a 3x3 grid and gets 3 times bigger in width and height each generation, we can say it has a scale factor of 3. We could define a bit pattern for the Sierpinski carpet by numbering the elements in the 3x3 grid from 0 to 8, top-to-bottom, left-to-right, and setting the corresponding bit of an integer if generation n+1 contains a copy of generation n at that grid position: ``` bit: place value: bit pattern: bit value: 0 1 2 1 2 4 1 1 1 1 2 4 3 4 5 8 16 32 1 0 1 8 0 32 6 7 8 64 128 256 1 1 1 64 128 256 integer value = 1 + 2 + 4 + 8 + 32 + 64 + 128 + 256 = 495 ``` For a scale factor of 2, the bit pattern would be arranged like this: ``` 0 1 2 3 ``` and so on. Your task is to write a program that accepts a bit pattern in this form, a scale factor (e.g. 3 for the Sierpinski Carpet) and a generation number and outputs an ASCII fractal. **Input** Your program should accept 3 integers in the following order: a bit pattern, a scale factor (ranging from 2 to 5, inclusive) and a generation count (ranging from 0 to 5, inclusive). You do not need to perform any input validation on these values and it's perfectly fine if the program works for values larger than the ranges specified. The inputs can be passed in any form (tuples, comma/space-separated list, etc) **Output** The program should output a fractal made up of the `#` character followed by a space in positions where the fractal is defined, double-spaces where it is not, and a newline character at the end of each line, either printing them out or returning a string from a function. **Examples** Input: ``` 495,3,3 ``` Output (Sierpinski Carpet generation 3): ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Input: ``` 7,2,5 ``` Output ([Sierpinski Triangle](https://en.wikipedia.org/wiki/Sierpinski_triangle)): ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Input: ``` 325,3,3 ``` Output ([Cantor Dust](http://mathworld.wolfram.com/CantorDust.html)): ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Input ``` 186,3,3 ``` Output ([Vicsek fractal](https://en.wikipedia.org/wiki/Vicsek_fractal)): ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Input: ``` 279,3,3 ``` Output (example of an asymmetrical fractal): ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` etc. **Notes:** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins * Your program can be either a stand-alone or a function that is called with the 3 input parameters and returns (or prints) a string * Generation 0 is defined as `#` (a `#` followed by a space) even for a bit pattern of 0. * A trailing newline on the last line is optional but permitted, as is any amount of trailing white-space on each line. [Answer] # Common Lisp, ~~248~~ 242 bytes ``` (lambda(n r g &aux(s(expt r g)))(labels((f(g x y s)(or(= g 0)(#2=multiple-value-bind(q x)(floor x s)(#2#(p y)(floor y s)(if(logbitp(+ q(* p r))n)(f(1- g)x y(/ s r))))))))(#3=dotimes(y s)(#3#(x s)(princ(if(f g x y(/ s r))"# "" ")))(terpri)))) ``` ## Ungolfed ``` (defun fractal (n r g &aux (s (expt r g))) (labels((f(g x y s) (or(= g 0) (multiple-value-bind (px x) (truncate x s) (multiple-value-bind (py y) (truncate y s) (and (logbitp (+ px (* py r)) n) (f (1- g) x y (/ s r)))))))) (fresh-line) (dotimes(y s) (dotimes(x s) (princ (if (f g x y(/ s r)) "# " " "))) (terpri)))) ``` ## Explanation * Input: + *N* is the encoded pattern + *R* is the size of the pattern + *G* is the generation * The output is an implicit square matrix of length *S=R**G* * We iterate over each row *y*, column *x* (nested `dotimes`) and compute whether each cell should be drawn (raycasting-like approach). This is done by recursively looking inside the fractal with the `f` auxiliary function. * If the fractal at position *(x,y)* shall be drawn, print `"# "`, or else print `" "`. Of course we also print newlines at the end of each row. For example, Sierpinsky's triangle is represented by `S=7` and `R=2`. At generation 3 the square size is 23=8. For each cell *(x,y)*, the following happen: * `f` is called with *x*, *y*, *g* bound to 3 and *s* bound to 4 (8/2) * We truncate *x* by *s*, in order to know if *x* belongs to the left or right side of the implicit matrix. `truncate` returns both the quotient and the remainder, which are bound respectively to *px* and *x* (we reuse the same symbol *x*, but this not a problem). * The same goes for *y* which gives *py* and new *y*. * In this example, *px* and *py* can be either 0 or 1 (because the pattern is a square of length 2). They identify where is *(x,y)* in the fractal's pattern: when the bit at position *py.R + px* of *N* is 0, *x* and *y* represent a position where nothing should be drawn. * Otherwise, we must "zoom" into the corresponding part of the fractal and we call `f` recursively with the new bindings for *x* and *y*. Those are now the relative position inside the inner fractal. We pass *G-1* for the generation and *s/2* to represent the half-length of the fractal. * The base case of the recursion is encountered when *G* is zero, in which case the current *(x,y)* position should be drawn. ## Example ``` (fractal 186 3 3) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Computing the 8th generation of the Sierpinski Carpet using `(fractal 495 3 8)` takes 24.7 seconds and generates an output text file of 83 MB. I wrote a slightly modifed version which outputs an image. For the same parameters, the GIF file weights 1.5MB (same computation time): [![Sierpinsky's Carpet, generation 8](https://i.stack.imgur.com/JPUDg.gif)](https://i.stack.imgur.com/JPUDg.gif) Vicsek (click to see original size): [![Vicsek fractal](https://i.stack.imgur.com/7hlzk.gif)](https://i.stack.imgur.com/7hlzk.gif) [Answer] # Pyth, 38 bytes ``` VJ^UQvwjdm@" #".A@L_.[0^Q2jvz2+V*RQNdJ ``` Try it online: [Regular Input / Test Suite](http://pyth.herokuapp.com/?code=VJ%5EUQvwjdm%40%22%20%23%22.A%40L_.%5B0%5EQ2jvz2%2BV*RQNdJ&input=186%0A3%0A3&test_suite_input=495%0A3%0A3%0A7%0A2%0A5%0A325%0A3%0A3%0A186%0A3%0A3&debug=0&input_size=3) Explanation follows later. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 37 bytes[SBCS](https://github.com/abrudz/SBCS) ``` '# '{⊃⍪/,/⍺\⍤1⊂⍉⍪⍉⍵}⍣⎕⍨(2⍴⎕)⍴⌽⎕⊤⍨99⍴2 ⎕ ⍝ input the bit pattern ⊤⍨99⍴2 ⍝ decode 99 binary digits from it ⍝ (53 is the limit for floating point) ⌽ ⍝ reverse, least significant bit goes first ⎕ ⍝ input the scale factor (2⍴ ) ⍝ twice, to use as dimensions of a matrix ⍴ ⍝ reshape bit pattern into such a matrix ⎕ ⍝ input the number of generations '# '{ }⍣ ⍨ ⍝ apply that many times, starting from '# ' ⍉⍪⍉⍵ ⍝ make sure the argument is a matrix ⊂ ⍝ enclose ⍺\⍤1 ⍝ expand using rows of bit-pattern matrix ⍝ (1 for identical copy, 0 for zeroed out) ⊃⍪/,/ ⍝ concat all horizontally and vertically ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tP@qysrqFc/6mp@1LtKX0f/Ue@umEe9SwwfdTU96u0EioHJrbWPehcD9T3qXaFh9Kh3C5CpCaJ69oIEu5YAxS0tgQJG/4FG/k/jMrE05TIGQl2uNC5zLiMuUzDL2AghamhhBmcbmVuC2AA "APL (Dyalog Unicode) – Try It Online") [Answer] # Ruby,154 Score is for the function only. Presented ungolfed below in test program. The only golfing I'm claiming at the moment is removal of comments and indents. I will golf later. At the moment, I'm having fun playing with the program. The function takes six arguments, but on the initial call only the first 3 are provided per the spec. This causes the three remaining arguments to be set to default values, and in particular the string `a` where the output is stored is created and initialized to lines of spaces terminated by newlines. As a side effect the global variable `$w` is also created, indicating the number of symbols per line. When the function calls itself recursively, it provides all six arguments, including the string `a` and the x and y coordinates of the top left corner of the next recursion The rest of the program is pretty straightforward, as indicated in the comments. ``` #function f=->b,s,g,x=0,y=0,a=(' '*(-1+2*$w=s**g)+' ')*$w{ #accept arguments, if x,y,a are not provided create them. $w = number of symbols per row v=s**g/s #v=width of blocks for this recursion depth if g==0 a[2*y*$w+2*x]=?# #if g==0 plot a # else #else iterate s*s times through the bits of b, and recurse as necessary (s*s).times{|i|b>>i&1>0&&f.call(b,s,g-1,x+i%s*v,y+i/s*v,a)} end a } #test program (requires 3 input numbers separated by newlines) b=gets.to_i s=gets.to_i g=gets.to_i #get return value and output to stdout puts f.call(b,s,g) ``` **Output** Here's a set of fractals loosely based on the form of the letters of the word GOLF. More realistic letters could be achieved with larger bitmaps. As the last example shows, the most interesting fractals are discovered by accident. ``` 63775,4,2 (G) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 495,3,3 (O, sierpinski carpet) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 457,3,3 (L) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 7967,4,2 (F) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 1879,3,3 (skull and crossbones discovered by accident) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] # CJam, 45 ``` 3aaq~@2b2$_*0e[W%@/a*{ffff*:.+:.+}/' ff+Sf*N* ``` Implementation of my first idea. [Try it online](http://cjam.aditsu.net/#code=3aaq~%402b2%24_*0e%5BW%25%40%2Fa*%7Bffff*%3A.%2B%3A.%2B%7D%2F'%20ff%2BSf*N*&input=279%203%203) Basically, it starts with a 1\*1 matrix containing 3 (the difference between '#' and ' '), then repeatedly multiplies each number in the matrix with the bit pattern (0/1 matrix), and combines the resulting matrices into one bigger matrix. At the end, it adds a space to each number, and joins with spaces and newlines. **2nd idea, 49** ``` q~@2bW%2$/z@@m*_,\_m*:z@f{3@@f{\~@==*}~' +}/Sf*N* ``` [Try it online](http://cjam.aditsu.net/#code=q~%402bW%252%24%2Fz%40%40m*_%2C%5C_m*%3Az%40f%7B3%40%40f%7B%5C~%40%3D%3D*%7D~'%20%2B%7D%2FSf*N*&input=279%203%203) This generates all the coordinates of the output matrix as arrays of <generation count> pairs of numbers smaller than the scale factor (all such combinations), then for each pair of numbers it gets the corresponding bit from the pattern, and for each coordinate array it multiplies the bits and multiplies by 3. The final processing is the same. There's probably room for more golfing. [Answer] # C, 316 bytes ``` main(a,_,b,s,g,i,w,o,z,x,y)char**_,*o;{b=atoi(_[1]);s=atoi(_[2]);g=atoi(_[3]);w=1;for(i=0;i<g;++i){w*=s;}o=malloc(w*w);for(i=0;i<w*w;++i)o[i]=35;z=w/s;while(z){for(y=0;y<w;++y)for(x=0;x<w;++x)if(!((b>>((y/z)%s*s+(x/z)%s))&1))o[y*w+x]=32;z/=s;}for(y=0;y<w;++y){for(x=0;x<w;++x)printf("%c ",o[y*w+x]);printf("\n");}} ``` ### Un-golfed: ``` #include <stdio.h> int main(int argc, char *argv[]) { int bitpattern; int scale; int generation; bitpattern = atoi(argv[1]); scale = atoi(argv[2]); generation = atoi(argv[3]); int i; int width = 1; for (i=0; i<generation; ++i) {width*=scale;} char *out=malloc(width*width); for (i=0; i<width*width; ++i) out[i]='#'; int blocksize = width/scale; for (i=0; i<generation; ++i) { int x,y; for (y=0; y<width; ++y) { for (x=0; x<width; ++x) { int localX = x/blocksize; localX %= scale; int localY = y/blocksize; localY %= scale; int localPos = localY*scale+localX; if (!((bitpattern>>localPos)&1))out[y*width+x]=' '; } } blocksize/=scale; } int x,y; for (y=0; y<width; ++y) { for (x=0; x<width; ++x) printf("%c ",out[y*width+x]); printf("\n"); } return 0; } ``` [Answer] # Scala ~~293~~ 299 ``` (e:Int,s:Int,g:Int)=>{def b(x:Int,y:Int)=(1<<x*s+y&e)>0;def f(n:Int):Seq[Seq[Char]]=if(n<1)Seq(Seq('#'))else if(n<2)Seq.tabulate(s,s)((i,j)=>if(b(i,j))'#'else' ')else{val k=f(n-1);val t=k.size;Seq.tabulate(t*s,t*s)((i,j)=>if(b(i/t,j/t))k(i%t)(j%t)else' ')};f(g).map(_.mkString(" ")).mkString(" \n")} ``` ungolfed: ``` //create an anonymous function (encoded: Int, size: Int, generation: Int) => { // method will return true if coords (x,y) should be drawn as '#' def isBlackInPattern(x: Int, y: Int): Boolean = (1 << x * size + y & encoded) > 0 // recurse until generation is 1 def fillRecursively(gen: Int): Seq[Seq[Char]] = { // this is just to satisfy OP requirements. // if the stopping condition were generation = 1, // I could have spared this line... if(gen < 1) Seq(Seq('#')) //actual stopping condition (generation 1). // fill a matrix of characters with spaces // and hashes acording to the pattern. else if(gen < 2) Seq.tabulate(size, size)((i, j) => if (isBlackInPattern(i,j)) '#' else ' ' ) // recurse, and use previously created fractals to fill // the current generation according to the `isBlackInPattern` condition else { val previousGeneration = fillRecursively(gen-1) val previousSize = previousGeneration.size // create the current matrix and fill it Seq.tabulate(previousSize*size,previousSize*size)((i,j)=> if(isBlackInPattern(i/previousSize,j/previousSize)) previousGeneration(i%t)(j%t) else ' ' ) } } // call to recursive function and format matrix of characters to string fillRecursively(generation).map(_.mkString(" ")).mkString(" \n") } ``` examples: ``` val f = (e:Int,s:Int,g:Int)=>{def b(x:Int,y:Int)=(1<<x*s+y&e)>0;def f(n:Int):Seq[Seq[Char]]=if(n<1)Seq(Seq('#'))else if(n<2)Seq.tabulate(s,s)((i,j)=>if(b(i,j))'#'else' ')else{val k=f(n-1);val t=k.size;Seq.tabulate(t*s,t*s)((i,j)=>if(b(i/t,j/t))k(i%t)(j%t)else' ')};f(g).map(_.mkString(" ")).mkString(" \n")} f: (Int, Int, Int) => String = <function3> scala> println(f(495,3,3)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # scala> println(f(7,2,5)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # scala> println(f(18157905,5,2)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` first cut, probably can be golfed a bit further... [Answer] # Matlab, 115 bytes The Kronecker `kron` product makes everything much easier: ``` function f(p,f,g);z=nan(f);z(:)=de2bi(p,f*f);x=3;for k=1:g;x=kron(x,z);end;disp([reshape([x;0*x],f^g,2*f^g)+32,'']) ``` ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] **C, 158 bytes** ``` f(p,s,g,h,i,j,c){for(j=1;g--;j*=s);for(h=j;h;){h--;for(i=j;i;){i--;for(c=35,g=j/s;g;g/=s)c=!((p>>((h/g)%s*s+(i/g)%s))&1)?32:c;printf("%c ",c);}printf("\n");}} ``` [Answer] # K5, 70 bytes It's a start: ``` {,/'(" ";"# ")$[z;(z-1){,/'+,/'+x@y}[(0*t;t)]/t:(2#y)#|(25#2)\x;,,1]} ``` In action: ``` {,/'(" ";"# ")$[z;(z-1){,/'+,/'+x@y}[(0*t;t)]/t:(2#y)#|(25#2)\x;,,1]}[186;3]'!4 (,"# " (" # " "# # # " " # ") (" # " " # # # " " # " " # # # " "# # # # # # # # # " " # # # " " # " " # # # " " # ") (" # " " # # # " " # " " # # # " " # # # # # # # # # " " # # # " " # " " # # # " " # " " # # # " " # # # # # # # # # " " # # # " " # # # # # # # # # " "# # # # # # # # # # # # # # # # # # # # # # # # # # # " " # # # # # # # # # " " # # # " " # # # # # # # # # " " # # # " " # " " # # # " " # " " # # # " " # # # # # # # # # " " # # # " " # " " # # # " " # ")) ``` ]
[Question] [ ## Scoreboard Here are the raw scores (i.e. domino counts) for VisualMelon's submission. I'll turn these into the normalised scores described below, when more answers come in. The existing solution can now solve all circuits in the benchmark: ``` Author Circuit: 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 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- VisualMelon 39 45 75 61 307 337 56 106 76 62 64 62 182 64 141 277 115 141 92 164 223 78 148 371 1482 232 107 782 4789 5035 1314 3213 200 172 1303 3732 97596 156889 857 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Legend: I - invalid circuit B - circuit too big W - circuit computes wrong function T - exceeded time limit ``` ## The Challenge [It](http://en.wikipedia.org/wiki/Domino_computer) [is](https://www.youtube.com/watch?v=SudixyugiX4) [possible](https://www.youtube.com/watch?v=lNuPy-r1GuQ) to build simple logic gates from dominoes. Hence, by combining these or otherwise, arbitrary binary functions can be computed with dominoes. But of course, everyone who has played with dominoes (except Robin Paul Weijers) has experienced the disappointment when running out of them. Hence, we want to use our dominoes as efficiently as possible, so we can do some really interesting computations with the material we have. Note, that you cannot produce non-zero output from zero input per se, so we'll need to add a "power line", which falls along your setup, and which you can pull `1`s from at any time. ## Your task Given a boolean function with `M` inputs and `N` outputs (`f: {0,1}^M --> {0,1}^N` for the mathematically inclined), produce a domino circuit with as few dominoes as possible which computes that function. You'll be using the symbols `|`, `-`, `/`, `\` to represent dominoes in various orientations. ### Input You'll be given input via command-line arguments: ``` [command for your solver] M N f ``` where `M` and `N` are positive integers and `f` is the comma separated truth table in canonical order. That is, `f` will contain `2^M` values of length `N`. E.g. if `M = N = 2` and the first bit in the output was the AND function while the second bit was the OR function, `f` would read ``` 00,01,01,11 ``` ### Output Write to STDOUT an ASCII grid representing the domino setup. Your setup has to fit in the following framework ``` /////...///// ????...???? I????...????O I????...????O ............. ............. I????...????O I????...????O I????...????O ``` * The top row consists entirely of `/`, and the leftmost domino is guaranteed to be toppled over at the beginning - this is your power line. * The leftmost column consists of your inputs. Each `I` may either be a space or a `|`, such that there are exactly `M` `|`s. * The rightmost column consists of your outputs. Each `O` may either be a space or a `|`, such that there are exactly `N` `|`s. * Note that there is at least one blank before the first `|` in the input or output. * The `.` indicate that the grid can be arbitrarily large. * You can fill `?` in any way you want. Note that the bottom input is the fastest-varying while you go along the truth table, while the top input is the `0` for the first half of the outputs and `1` for the second half. ## Rules Dominoes propagate as specified in [Golfing for Domino Day](https://codegolf.stackexchange.com/questions/34875/golfing-for-domino-day). In short, if we represent the falling directions as letters ``` Q W E A D Z X C ``` then these are all unique combinations which can propagate (as well as their rotations and reflections): ``` D| -> DD D\ -> DE D/ -> DC C| -> CD C/ -> CC C -> C C -> C C -> C | D - X / C ``` All of the above rules are applied simultaneously at each time step. If two of those rules are in conflict (i.e. a tile is pushed into two *valid* opposite directions at the same time), the affected tile will *not* fall, and will effectively be locked into position for the rest of the simulation. ## Restrictions * `M` and `N` will never exceed 6. * Your solver must produce a circuit within ***N \* 2M* seconds**. * Your solver must not use more than **1 GB of memory**. This is a soft limit, as I will be monitoring this manually and kill your process if it significantly/continuously exceeds this limit. * No circuit is permitted to contain more than **8,000,000 cells** or **1,000,000 dominoes**. * Your submission must be **deterministic**. You are allowed to use pseudo-random number generators, but they must use a hardcoded seed (which you are free to optimise as much as you care to). ## Scoring For each circuit, let `D` be total number of dominoes in your circuit and `B` the lowest number of dominoes this circuit has been solved with (by you or any other participant). Then your score for this circuit is given by `10,000 * B / D` rounded down. If you failed to solve the circuit, your score is 0. Your overall score will be the sum over a benchmark set of test cases. Circuits that have not yet been solved by anyone will not be included in the total score. Each participant may add one test case to the benchmark (and all other submissions will be re-evaluated including that new test case). The benchmark file [can be found on GitHub](https://github.com/mbuettner/ppcg-domino-circuits/blob/master/benchmark.txt). ## Examples Here are some non-optimally solved examples. **Constant 1** ``` 1 1 1,1 /////// / | ||| ``` Domino count: 12 **OR gate** ``` 2 1 0,1,1,1 /////////// |||||/ ||||| |||||\ ``` Domino count: 28 **AND gate** ``` 2 1 0,0,0,1 /////////////////// \-/ - - |||||/|\ /|||/ / - - \- \- \ - |||||\ / \ / |\ ||||| ``` Domino count: 62 **Swap lanes** ``` 2 2 00,10,01,11 //////////// ||||/ \|||| /\ \/ ||||\ /|||| ``` Domino count: 36 ## Additional Notes The propagation rules are such, that diagonal lanes *can* cross using a diamond shape (see last example) even if one falls before the other (unlike with real dominoes). As a starting point, you can use the (not minimised) logical gates in [this gist](https://gist.github.com/mbuettner/5706712d9caacc00ed5f) and try combining as few of these as possible. For a simple (non-optimal) way to build arbitrary boolean functions from AND, OR and NOT gates, have a look at [Conjunctive](http://en.wikipedia.org/wiki/Conjunctive_normal_form) and [Disjunctive](http://en.wikipedia.org/wiki/Disjunctive_normal_form) Normal Forms. There is a verifier [this GitHub repository](https://github.com/mbuettner/ppcg-domino-circuits) to test your code, which will also be used to score all submissions. This outputs the raw scores (domino counts) and saves them to a file to be processed by a separate scorer (also in that repository) to obtain the final scores. General documentation can be found within the two Ruby files, but the `controller.rb` takes two command line switches before the benchmark file: * `-v` gives you some more output, including the actual circuits produced by your solver. * `-c` lets you select a subset of the benchmark you want to test. Provide the desired circuits as a comma-separated list of 1-based indices. You can also use Ruby ranges, so you could do something like `-c 1..5,10,15..20`. Please include in your answer: * Your code * A command to (compile and) run your code. I'll ask you where to obtain the necessary compilers/interpreters if I don't have them. * An additional truth table with a name, to be added as a test case to the benchmark. (This is optional, but strongly encouraged.) I'll be testing all submissions on Windows 8. [Answer] ## C# - Massive, Slow, and inefficient solution *Confession: wrote this solution some time ago when the question was still in the sandbox, but it's not very good: **you can do better!*** *Edit: replaced the boring solving with a less boring, more flexible, and generally better method* You run the program by compiling with `csc dominoPrinter.cs` and then passing arguments to the executable, for example (the 4-bit prime checker): ``` dominoPrinter.exe 4 1 0,0,1,1,0,1,0,1,0,0,0,1,0,1,1,1 ``` Explanation: The "Domino Printer" is a 3-stage program: **Stage 1**: The "solver" generates an expression tree of "ifnot" and "or" binary operations with the given inputs, and a "1" from the powerline, there are 2ways this is done, depending on the number of inputs: * If there are fewer than 4 inputs the program brutes a solution of the fewest number of operations * If there are 4 or more inputs the program brutes each 8bit chunk of output and then combines the results to give the desired output. The bruted bits if flexible: the more bruted bits, the smaller the solution, but the longer the run-time. The "solver" is what takes all the time (or at least it used to), and is also most of the code. I *believe* there is a well documented, fast, not so memory hungry, and probably optimal solution to this problem, but where would the fun be in looking it up? The (bruted) expression tree for the 4-bit prime checker is ``` ((2 or 1) ifnot (((0 ifnot 1) or ((1 ifnot 0) or (0 ifnot 2))) ifnot 3)) ``` where the numbers are the indexes of the inputs. **Stage 2**: The "organizer" takes the expression tree as input and assembles a "skeleton" layout, which precisely describes a domino layout made from some a set of 4x5 overlapping cells. Below is the skeleton for the bruted 4-bit prime checker (you'll need to change the `bruteBase` integer variable on line 473 to 4 (or larger) to get this result). ``` 18 9 I ___ _ _______ O v _ X X ____ uu I X X X u UU/ v X X v ___/// I X X \ u // v X \ v __// I_X \ \_u / \ \ ___/ \_U ``` This output is effectively made up to two parts, the "evaluator" on the right, which is created from the expression tree from stage 1, and the "switchboard" on the left, which swaps and splits the inputs so that they arrive in the right places for the "evaluator" to handle. There is considerable scope for compacting the layout at this point, but the program currently does very little such work. The code for this stage is horrible, but pretty simple underneath (see the "orifnot" method). The output is passed to stage 3. **Stage 3**: The "printer" takes the output from the "organizer" and prints the corresponding 4x5 overlapping "cells" along with the power line. Below is an animation of the bruted 4-bit prime checker checking whether 5 is prime. ![Apparently 5 is prime](https://i.stack.imgur.com/RX6mC.gif) Code *the lack of indenting is to avoid going over the SE 30k character limit which it would otherwise*: ``` using System; using System.Collections.Generic; namespace dominoPrinter { class Program { static string bstring(bool[] barr) { string str = ""; foreach (bool b in barr) str += b?1:0; return str; } public static void Main(string[] args) { int inputCount; val[] vals = resolveVals(args[0], args[1], args[2], out inputCount); System.IO.StringWriter sw = new System.IO.StringWriter(); orifnot(inputCount, vals, sw); System.IO.StringReader sr = new System.IO.StringReader(sw.ToString()); printDominoes(sr, Console.Out, args.Length > 3 && args[3] == "quite"); } public abstract class val { public int size; public bool[] rs; public abstract string strness(); } public class baseVal : val { public bool b; public int id; public baseVal(int idN) { id = idN; size = 1; } public override string strness() { return id.ToString(); } } public abstract class biopVal : val { public val a, b; public biopVal(val aN, val bN) { a = aN; b = bN; size = a.size + b.size; } public bool buildCheckApply(nodev ntree) { nodev cur = ntree; rs = new bool[a.rs.Length]; bool notOK = true; for (int i = 0; i < rs.Length; i++) { bool r = rs[i] = go(a.rs[i], b.rs[i]); if (notOK) { if (r) { if (cur.a == null) notOK = false; else { cur = cur.a; if (cur == nodev.full) return false; } } else { if (cur.b == null) notOK = false; else { cur = cur.b; if (cur == nodev.full) return false; } } } } ntree.apply(this, 0); return true; } public abstract bool go(bool a, bool b); } public class ifnotVal : biopVal { public override bool go(bool a, bool b) { return a ? false : b; // b IF NOT a, else FALSE } public ifnotVal(val aN, val bN) : base(aN, bN) { } public override string strness() { return "(" + b.strness() + " ifnot " + a.strness() + ")"; } } public class orval : biopVal { public override bool go(bool a, bool b) { return a || b; // a OR b } public orval(val aN, val bN) : base(aN, bN) { } public override string strness() { return "(" + b.strness() + " or " + a.strness() + ")"; } } static bool boolCompare(bool[] a, bool b) { for (int i = 0; i < a.Length; i++) { if (a[i] != b) { return false; } } return true; } static bool boolFlat(bool[] a) { bool p = a[0]; for (int i = 1; i < a.Length; i++) { if (a[i] != p) return false; } return true; } static bool boolCompare(bool[] a, bool[] b) { if (a.Length != b.Length) return false; // let's do this proeprly for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return false; } } return true; } // solver // these is something VERY WRONG with the naming in this code public class nodev { public static nodev full = new nodev(); public nodev a, b; public nodev() { a = null; b = null; } public bool contains(bool[] rs) { nodev cur = this; if (cur == full) return true; for (int i = 0; i < rs.Length; i++) { if (rs[i]) { if (cur.a == null) return false; cur = cur.a; } else { if (cur.b == null) return false; cur = cur.b; } if (cur == full) return true; } return true; } public bool contains(val v) { nodev cur = this; if (cur == full) return true; for (int i = 0; i < v.rs.Length; i++) { if (v.rs[i]) { if (cur.a == null) return false; cur = cur.a; } else { if (cur.b == null) return false; cur = cur.b; } if (cur == full) return true; } return true; } // returns whether it's full or not public bool apply(val v, int idx) { if (v.rs[idx]) { if (a == null) { if (idx == v.rs.Length - 1) { // end of the line, fellas a = full; if (b == full) return true; return false; } else { a = new nodev(); } } if (a.apply(v, idx + 1)) a = full; if (a == full && b == full) return true; } else { if (b == null) { if (idx == v.rs.Length - 1) { // end of the line, fellas b = full; if (a == full) return true; return false; } else { b = new nodev(); } } if (b.apply(v, idx + 1)) b = full; if (a == full && b == full) return true; } return false; } } public static void sortOutIVals(baseVal[] ivals, int rc) { for (int i = 0; i < ivals.Length; i++) { ivals[i].rs = new bool[rc]; ivals[i].b = false; } int eri = 0; goto next; again: for (int i = ivals.Length - 1; i >= 0; i--) { if (ivals[i].b == false) { ivals[i].b = true; goto next; } ivals[i].b = false; } return; next: for (int i = ivals.Length - 1; i >= 0; i--) { ivals[i].rs[eri] = ivals[i].b; } eri++; goto again; } public static val[] resolve(int inputCount, int c, bool[][] erss, out baseVal[] inputs) { val[] res = new val[erss.Length]; List<List<val>> bvals = new List<List<val>>(); nodev ntree = new nodev(); List<val> nvals = new List<val>(); baseVal tval = new baseVal(-1); baseVal fval = new baseVal(-2); baseVal[] ivals = new baseVal[inputCount]; inputs = new baseVal[inputCount + 2]; for (int i = 0; i < inputCount; i++) { ivals[i] = new baseVal(i); // value will change anyway inputs[i] = ivals[i]; } inputs[inputCount] = fval; inputs[inputCount + 1] = tval; sortOutIVals(ivals, c); for (int i = 0; i < inputCount; i++) { nvals.Add(ivals[i]); } tval.rs = new bool[c]; fval.rs = new bool[c]; for (int i = 0; i < c; i++) { tval.rs[i] = true; fval.rs[i] = false; } nvals.Add(tval); nvals.Add(fval); // ifnot and or do nothing with falses bvals.Add(new List<val>()); foreach (val v in nvals) { ntree.apply(v, 0); if (!boolFlat(v.rs)) bvals[0].Add(v); // I trust these are distinct.. } Func<biopVal, bool> checkValb = (v) => { if (!v.buildCheckApply(ntree)) { return false; } bvals[v.size-1].Add(v); return true; }; Action<biopVal, List<val>> checkVal = (v, li) => { if (checkValb(v)) li.Add(v); }; int maxSize = 1; again: for (int i = 0; i < erss.Length; i++) { bool[] ers = erss[i]; if (res[i] == null && ntree.contains(ers)) { // there is a reason this is separate... I'm sure there is.... foreach (val rv in nvals) { if (boolCompare(rv.rs, ers)) { res[i] = rv; break; } } } } for (int i = 0; i < erss.Length; i++) { if (res[i] == null) goto notoveryet; } return res; notoveryet: maxSize++; bvals.Add(new List<val>()); // bvals[maxSize-1] always exists nvals.Clear(); long cc = 0; List<val> sbvals = bvals[maxSize - 2]; // NOTs have a habit of working out, get it checked first for (int i = sbvals.Count - 1; i >= 0; i--) { // also known as nvals, but let's ignore that val arv = sbvals[i]; checkVal(new ifnotVal(arv, tval), nvals); cc += 1; } for (int s = 1; s < maxSize; s++) { List<val> abvals = bvals[s - 1]; int t = maxSize - s; if (t < s) break; List<val> bbvals = bvals[t - 1]; for (int i = abvals.Count - 1; i >= 0; i--) { val arv = abvals[i]; int jt = t == s ? i : bbvals.Count - 1; for (int j = jt; j >= 0; j--) { val brv = bbvals[j]; checkVal(new ifnotVal(brv, arv), nvals); checkVal(new ifnotVal(arv, brv), nvals); checkVal(new orval(brv, arv), nvals); // don't technically need ors, but they are good fun cc += 3; } } } int bc = 0; foreach (List<val> bv in bvals) bc += bv.Count; goto again; } public static val[] resolveVals(string mStr, string nStr, string erStr, out int inputCount) { int ic = int.Parse(mStr); int oc = int.Parse(nStr); inputCount = ic; int bruteBase = 3; if (inputCount <= bruteBase) return resolveVals(ic, oc, erStr); else return resolveValFours(bruteBase, ic, oc, erStr); } public static val joinVals(val low, val high, baseVal inp, baseVal tval, baseVal fval) { val lowCut = low == fval ? (val)fval : low == tval ? (val)new ifnotVal(inp, tval) : (val)new ifnotVal(inp, low); val highCut = high == fval ? (val)fval : high == tval ? (val)inp : (val)new ifnotVal(new ifnotVal(inp, tval), high); if (highCut == fval) return lowCut; if (lowCut == fval) return highCut; return new orval(highCut, lowCut); } public static val resolveValFour(int n, int m, int inputCount, bool[] ers) { // solves fours int fc = ers.Length / m; bool[][] fours = new bool[fc][]; for (int i = 0; i < fc; i++) { fours[i] = new bool[m]; for (int j = 0; j < m; j++) { fours[i][j] = ers[i*m+j]; } } baseVal[] inputs; val[] fres = resolve(n, m, fours, out inputs); baseVal tval = inputs[inputs.Length - 1]; baseVal fval = inputs[inputs.Length - 2]; for (int i = 0; i < n; i++) { inputs[i].id += inputCount - n; } // assemble for (int i = 0, c = 1; c < fc; c *= 2, i++) { for (int j = 0; j + c < fc; j += c * 2) { fres[j] = joinVals(fres[j], fres[j+c], new baseVal((inputCount - n - 1) - i), tval, fval); } } return fres[0]; } public static val[] resolveValFours(int n, int inputCount, int outputCount, string erStr) { int m = 1; for (int i = 0; i < n; i++) m *= 2; val[] res = new val[outputCount]; string[] data = erStr.Split(','); for (int i = 0; i < outputCount; i++) { bool[] ers = new bool[data.Length]; for (int j = 0; j < data.Length; j++) ers[j] = data[j][i] == '1'; res[i] = resolveValFour(n, m, inputCount, ers); } return res; } public static val[] resolveVals(int inputCount, int outputCount, string erStr) { val[] res; string[] data = erStr.Split(','); bool[][] erss = new bool[outputCount][]; for (int i = 0; i < outputCount; i++) { bool[] ers = new bool[data.Length]; for (int j = 0; j < data.Length; j++) ers[j] = data[j][i] == '1'; erss[i] = ers; } baseVal[] inputs; // no need res = resolve(inputCount, data.Length, erss, out inputs); return res; } // organiser public class vnode { private static vnode[] emptyVC = new vnode[0]; public static vnode oneVN = new vnode('1'); public static vnode noVN = new vnode(' '); public static vnode flatVN = new vnode('_'); public static vnode moveUpVN = new vnode('/'); public static vnode moveDownVN = new vnode('\\'); public static vnode inputVN = new vnode('I'); public static vnode outputVN = new vnode('O'); public static vnode swapVN = new vnode('X'); public static vnode splitDownVN = new vnode('v'); public int size; public vnode[] children; public char c; public int id = -3; public vnode(char cN) { c = cN; children = emptyVC; size = 1; } public vnode(val v) { biopVal bv = v as biopVal; if (bv != null) { children = new vnode[2]; children[0] = new vnode(bv.a); children[1] = new vnode(bv.b); size = children[0].size + children[1].size; if (bv is orval) c = 'U'; if (bv is ifnotVal) c = 'u'; } else { children = emptyVC; size = 1; c = 'I'; id = ((baseVal)v).id; } } } public class nonArray<T> { public int w = 0, h = 0; Dictionary<int, Dictionary<int, T>> map; public nonArray() { map = new Dictionary<int, Dictionary<int, T>>(); } public T this[int x, int y] { get { Dictionary<int, T> yd; if (map.TryGetValue(x, out yd)) { T v; if (yd.TryGetValue(y, out v)) { return v; } } return default(T); } set { if (x >= w) w = x + 1; if (y >= h) h = y + 1; Dictionary<int, T> yd; if (map.TryGetValue(x, out yd)) { yd[y] = value; } else { map[x] = new Dictionary<int, T>(); map[x][y] = value; } } } } public static int fillOutMap(nonArray<vnode> map, vnode rn, int y, int x) { if (rn.children.Length == 0) { map[y,x] = rn; return 1; } else { map[y+1,x] = rn; for (int i = 0; i < rn.children.Length; i++) { if (i == 0) { fillOutMap(map, rn.children[i], y, x + 1); } if (i == 1) { int ex = x + rn.children[0].size; for (int j = 1; j < ex - x; j++) map[y - j + 1,ex - j] = vnode.moveUpVN; fillOutMap(map, rn.children[i], y, ex); } y += rn.children[i].size; } } return rn.size; } public static void orifnot(int inputCount, val[] vals, System.IO.TextWriter writer) { // step one - build weird tree like thing of death nonArray<vnode> map = new nonArray<vnode>(); int curY = 0; foreach (val v in vals) { vnode vnt = new vnode(v); map[curY, 0] = vnode.outputVN; curY += fillOutMap(map, vnt, curY, 1); } // step two - build the thing to get the values to where they need to be // find Is List<int> tis = new List<int>(); for (int y = 0; y < map.w; y++) { for (int x = map.h - 1; x >= 0; x--) { vnode vn = map[y,x]; if (vn != null && vn.c == 'I') { tis.Add(vn.id); if (vn.id > -2) { for (;x < map.h; x++) { map[y,x] = vnode.flatVN; } } goto next; } } tis.Add(-2); next: continue; } // I do not like this piece of code, it can be replaced further down for the better if you get round to thinking about it // add unused Is for (int z = 0; z < inputCount; z++) { if (!tis.Contains(z)) { int midx = tis.IndexOf(-2); if (midx != -1) { tis[midx] = z; map[midx,map.h-1] = vnode.noVN; } else { tis.Add(z); map[map.w,map.h-1] = vnode.noVN; } } } int curX = map.h; MORE: for (int y = 0; y < map.w; y++) { if (y == map.w - 1) { if (tis[y] == -2) map[y,curX] = vnode.noVN; else map[y,curX] = vnode.flatVN; } else { int prev = tis[y]; int cur = tis[y + 1]; if (cur != -2 && (prev == -2 || cur < prev)) { // swap 'em map[y,curX] = vnode.noVN; if (prev == -2) map[y+1,curX] = vnode.moveDownVN; else map[y+1,curX] = vnode.swapVN; int temp = tis[y]; tis[y] = tis[y + 1]; tis[y + 1] = temp; y++; // skip } else { if (/*thatThingThat'sAThing*/ prev == cur && cur != -2) { map[y,curX] = vnode.noVN; map[y+1,curX] = vnode.splitDownVN; int temp = tis[y]; tis[y+1] = -2; y++; // skip } else { if (prev == -2) map[y,curX] = vnode.noVN; else map[y,curX] = vnode.flatVN; } } } } // check if sorted for (int y = 0; y < map.w - 1; y++) { int prev = tis[y]; int cur = tis[y + 1]; if (cur != -2 && (prev == -2 || cur < prev)) goto NOTSORTED; } goto WHATNOW; NOTSORTED: curX++; goto MORE; WHATNOW: tis.Add(-2); // this is to avoid boud checking y+2 // so... it's sorted now, so add the splits morePlease: curX++; for (int y = 0; y < map.w; y++) { if (y == map.w - 1) { if (tis[y] == -2) map[y,curX] = vnode.noVN; else map[y,curX] = vnode.flatVN; } else { int prev = tis[y]; int cur = tis[y + 1]; int next = tis[y + 2]; if (cur != -2 && prev == cur && cur != next) { // split map[y,curX] = vnode.noVN; map[y+1,curX] = vnode.splitDownVN; tis[y + 1] = -2; y++; // skip } else { if (prev == -2) map[y,curX] = vnode.noVN; else map[y,curX] = vnode.flatVN; } } } // check if collapsed for (int y = 0; y < map.w - 1; y++) { int prev = tis[y]; int cur = tis[y + 1]; if (cur != -2 && prev == cur) goto morePlease; } // ok... now we put in the Is and 1 curX++; map[0, curX] = vnode.oneVN; int eyeCount = 0; int ly = 0; for (int y = 0; y < map.w; y++) { if (tis[y] > -1) { map[y, curX] = vnode.inputVN; eyeCount++; ly = y; } } // step three - clean up if we can // push back _ esq things to _ // _/ / // this /shouldn't/ be necessary if I compact the vals properlu for (int y = 0; y < map.w - 1; y++) { for (int x = 1; x < map.h; x++) { if (map[y, x] != null && map[y+1, x] != null && map[y+1, x-1] != null) { char uc = map[y+1, x-1].c; if (map[y, x].c == '_' && map[y+1, x].c == '_' && (uc == 'U' || uc == 'u')) { map[y, x] = vnode.noVN; map[y, x-1] = vnode.flatVN; map[y+1, x] = map[y+1, x-1]; map[y+1, x-1] = vnode.noVN; } } } } // step four - write out map writer.WriteLine(map.h + " " + map.w); for (int y = 0; y < map.w; y++) { for (int x = map.h - 1; x >= 0; x--) { vnode vn = map[y,x]; if (vn != null) writer.Write(vn.c); else writer.Write(' '); } writer.WriteLine(); } } // printer static string up1 = @" / / / /"; static string input = @" |||||"; static string output = @" | "; static string flat = @" |/ \ /|\ "; static string splitDown = @"|// / /\ |\/ / "; static string splitUp = @" \ |/\ \ \/|\\ "; static string moveDown = @"|// / / / "; static string moveUp = @" \ \ \ |\\ "; static string swap = @"|/ | /\ /\ \/ |\ |"; static string orDown = @"|/ / |/ \ /|\ "; static string orUp = @"|/ / \ |\ \ |\ "; static string ifnotDown = @"|/ / - \/ |\ |"; static string ifnotUp = @"|/ | /\ - \ |\ "; public static void printDominoes(System.IO.TextReader reader, System.IO.TextWriter writer, bool moreverbosemaybe) { string line; string[] data; line = reader.ReadLine(); data = line.Split(' '); int w = int.Parse(data[0]); int h = int.Parse(data[1]); int ox = 0; int oy = 0; int cx = 5; int cy = 5; char[,] T = new char[ox + w * cx, oy + h * (cy - 1) + 1]; Action<int, int, string> setBlock = (int x, int y, string str) => { for (int i = 0; i < cx; i++) { for (int j = 0; j < cy; j++) { char c = str[i + j * cx]; if (c != ' ') T[ox + x * cx + i, oy + y * (cy - 1) + j] = c; } } }; // read and write for (int j = 0; j < h; j++) { line = reader.ReadLine(); for (int i = 0; i < w; i++) { if (line[i] != ' ') { switch (line[i]) { case '1': setBlock(i, j, up1); break; case '_': setBlock(i, j, flat); break; case '^': setBlock(i, j, splitUp); break; case 'v': setBlock(i, j, splitDown); break; case '/': setBlock(i, j, moveUp); break; case '\\': setBlock(i, j, moveDown); break; case 'X': setBlock(i, j, swap); break; case 'U': setBlock(i, j, orUp); break; case 'D': setBlock(i, j, orDown); break; case 'u': setBlock(i, j, ifnotUp); break; case 'd': setBlock(i, j, ifnotDown); break; case 'I': setBlock(i, j, input); break; case 'O': setBlock(i, j, output); break; } } } } // end for (int i = 0; i < T.GetLength(0); i++) { T[i, 0] = '/'; } // writeout w = T.GetLength(0) - cx + 1; h = T.GetLength(1); if (moreverbosemaybe) writer.Write(w + " " + h + " "); for (int j = 0; j < T.GetLength(1); j++) { for (int i = 0; i < T.GetLength(0) - cx + 1; i++) { char c = T[i, j]; writer.Write(c == 0 ? ' ' : c); } if (!moreverbosemaybe) writer.WriteLine(); } } } } ``` An additional test case: ``` 4 1 0,0,0,1,0,0,1,1,0,0,0,1,1,1,1,1 ``` This checks whether two adjacent (non-wrapping) bits are both 1s (e.g. true for 0110, but false for 0101 and 1001) ]
[Question] [ *Inspired by [this question on Math.SE](https://math.stackexchange.com/q/1399055/50421).* Starting with `1` you can repeatedly perform one of the following two operations: * Double the number. **or** * Rearrange its digits in any way you want, except that there must not be any leading zeroes. Taking an example from the linked Math.SE post, we can reach `1000` via the following steps: ``` 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 125, 250, 500, 1000 ``` Which numbers can you reach with this process and what is the shortest solution? ## The Challenge Given a positive integer `N`, determine the shortest possible sequence of integers to reach `N` with the above process, if possible. If there are several optimal solutions, output any one of them. If no such sequence exists, you should output an empty list. The sequence may be in any convenient, unambiguous string or list format. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. This is code golf, so the shortest answer (in bytes) wins. ## Test Cases Here is a list of all reachable numbers up to and including 256. The first column is the number (your input), the second column is the optimal number of steps (which you can use to check the validity of your solution) and the third column is one optimal sequence to get there: ``` 1 1 {1} 2 2 {1,2} 4 3 {1,2,4} 8 4 {1,2,4,8} 16 5 {1,2,4,8,16} 23 7 {1,2,4,8,16,32,23} 29 10 {1,2,4,8,16,32,23,46,92,29} 32 6 {1,2,4,8,16,32} 46 8 {1,2,4,8,16,32,23,46} 58 11 {1,2,4,8,16,32,23,46,92,29,58} 61 6 {1,2,4,8,16,61} 64 7 {1,2,4,8,16,32,64} 85 12 {1,2,4,8,16,32,23,46,92,29,58,85} 92 9 {1,2,4,8,16,32,23,46,92} 104 15 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104} 106 14 {1,2,4,8,16,32,64,128,256,265,530,305,610,106} 107 14 {1,2,4,8,16,32,23,46,92,29,58,85,170,107} 109 18 {1,2,4,8,16,32,23,46,92,184,368,386,772,277,554,455,910,109} 116 12 {1,2,4,8,16,32,23,46,92,29,58,116} 122 7 {1,2,4,8,16,61,122} 124 16 {1,2,4,8,16,32,23,46,92,29,58,85,170,107,214,124} 125 11 {1,2,4,8,16,32,64,128,256,512,125} 128 8 {1,2,4,8,16,32,64,128} 136 18 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158,316,136} 140 15 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,140} 142 16 {1,2,4,8,16,32,23,46,92,29,58,85,170,107,214,142} 145 17 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,145} 146 18 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,146} 148 11 {1,2,4,8,16,32,23,46,92,184,148} 149 16 {1,2,4,8,16,32,64,128,182,364,728,287,574,457,914,149} 152 11 {1,2,4,8,16,32,64,128,256,512,152} 154 17 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,154} 158 16 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158} 160 14 {1,2,4,8,16,32,64,128,256,265,530,305,610,160} 161 13 {1,2,4,8,16,32,23,46,92,29,58,116,161} 163 18 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158,316,163} 164 18 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,164} 166 20 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,154,308,616,166} 167 17 {1,2,4,8,16,32,23,46,92,184,148,296,269,538,358,716,167} 169 23 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,461,922,229,458,916,169} 170 13 {1,2,4,8,16,32,23,46,92,29,58,85,170} 176 17 {1,2,4,8,16,32,23,46,92,184,148,296,269,538,358,716,176} 182 9 {1,2,4,8,16,32,64,128,182} 184 10 {1,2,4,8,16,32,23,46,92,184} 185 16 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,185} 188 23 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,185,370,740,470,940,409,818,188} 190 18 {1,2,4,8,16,32,23,46,92,184,368,386,772,277,554,455,910,190} 194 16 {1,2,4,8,16,32,64,128,182,364,728,287,574,457,914,194} 196 23 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,461,922,229,458,916,196} 203 16 {1,2,4,8,16,32,64,128,256,265,530,305,610,160,320,203} 205 13 {1,2,4,8,16,32,64,128,256,512,125,250,205} 208 16 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208} 209 19 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,145,290,209} 212 8 {1,2,4,8,16,61,122,212} 214 15 {1,2,4,8,16,32,23,46,92,29,58,85,170,107,214} 215 11 {1,2,4,8,16,32,64,128,256,512,215} 218 9 {1,2,4,8,16,32,64,128,218} 221 8 {1,2,4,8,16,61,122,221} 223 14 {1,2,4,8,16,32,23,46,92,29,58,116,232,223} 227 20 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158,316,361,722,227} 229 20 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,461,922,229} 230 16 {1,2,4,8,16,32,64,128,256,265,530,305,610,160,320,230} 232 13 {1,2,4,8,16,32,23,46,92,29,58,116,232} 233 22 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,154,308,616,166,332,233} 235 19 {1,2,4,8,16,32,23,46,92,184,148,296,269,538,358,716,176,352,235} 236 19 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158,316,632,236} 238 19 {1,2,4,8,16,32,64,128,256,512,125,250,205,410,104,208,416,832,238} 239 25 {1,2,4,8,16,32,23,46,92,184,368,736,376,752,257,514,154,308,616,166,332,233,466,932,239} 241 16 {1,2,4,8,16,32,23,46,92,29,58,85,170,107,214,241} 244 8 {1,2,4,8,16,61,122,244} 247 21 {1,2,4,8,16,32,23,46,92,184,148,296,592,259,518,158,316,632,362,724,247} 248 17 {1,2,4,8,16,32,23,46,92,29,58,85,170,107,214,124,248} 250 12 {1,2,4,8,16,32,64,128,256,512,125,250} 251 11 {1,2,4,8,16,32,64,128,256,512,251} 253 19 {1,2,4,8,16,32,23,46,92,184,148,296,269,538,358,716,176,352,253} 256 9 {1,2,4,8,16,32,64,128,256} ``` If you want even more test data, [here is the same table up to and including 1,000](http://pastebin.com/D9U2uH3y). Any number not appearing on these tables should yield an empty list (provided the number is in the range of the table). [Answer] # Pyth, 43 bytes ``` ?}QKhu?Jf}QTGJsm+Ld+yedsMfnhT\0.p`edGQ]]1KY ``` [Demonstration.](https://pyth.herokuapp.com/?code=%3F%7DQKhu%3FJf%7DQTGJsm%2BLd%2ByedsMfnhT%5C0.p%60edGQ%5D%5D1KY&input=122&debug=0) This is starts by generating all possible double or rearrange sequences. However, since I actually wanted to see it finish, I added a short circuit. It either runs until it finds a solution, or for a number of iterations equal to the input, at which point it gives up and returns `[]`. --- This is guaranteed to be enough iterations. First, we know that this many iterations is enough for all n <= 1000, thanks to the example results. For larger numbers, the following argument holds: First, each step of the process must either maintain or increase the number of digits. Second, three numbers that are all rearrangements of one another can never all appear in a shortest sequence, because it would have been quicker to just do a single rearrangement from the first to the last. Third, all multiples of 3 are unreachable, because neither doubling nor rearrangement can produce a multiple of 3 from a non-multiple of 3. Thus, the longest possible sequence ending at a given number is equal to the sum of twice the number of sets of digits with less than or equal to as many digits as the input, and where the digits do not sum to a multiple of 3. The number of such digit sets for each number of digits: ``` 4 - 474 5 - 1332 6 - 3330 ``` In addition, we know from the examples that no shortest sequence ending with a 3 digit number is of length greater than 26. Thus, an upper bound of the sequence lengths is: ``` 4: 474 * 2 + 26 = 974 5: 974 * 2 + 1332 = 3638 6: 3330 * 2 + 3638 = 10298 ``` In each case, the upper bound is lower than any number with the number of digits The number of digit sets cannot grow by more than a factor of 10 when the number of digits is increased by one, because the new numbers can be separated into groups by last digit, each of which cannot have more sets than there were with one fewer digit. Thus, the upper bound will be lower than any number with that many digits for all possible numbers of digits greater than or equal to 4, which completes the proof that a number of iterations equal to the input is always enough. [Answer] # SWI-Prolog, 252 bytes ``` a(N,Z):-findall(X,b(N,[1],X),R),sort(R,[Z|_]);Z=[]. b(N,[A|T],Z):-n(A,C),n(N,M),length(C,L),length(M,O),L=<O,((A=N,reverse([A|T],Z));(A\=N,(B is A*2;permutation(C,D),\+ nth0(0,D,48),n(B,D),\+member(B,[A|T])),b(N,[B,A|T],Z))). n(A,B):-number_codes(A,B). ``` Example: `a(92,Z).` outputs `Z = [1, 2, 4, 8, 16, 32, 64, 46, 92]` I haven't checked yet that this works for N > 99 because of the time it takes, but I see no reason why it wouldn't work. [Answer] # Julia, ~~306~~ ~~245~~ 218 bytes Still working on golfing this. Will provide an ungolfed version once I'm done. ``` s->(M=s=[s];while 1∉s C=0;for i=1:size(s,1) p=2;for j=permutations(dec(s[i])) j[1]>48&&j[end]%2<1&&(l=int(j);l=l÷p;l∉M&&(M=[M,l];S=[l s[i,:]];C==0?C=S:C=[C;S]));p=1end;end;C==0&&return [];s=C;end;sortrows(s)[1,:]) ``` [Answer] # Haskell, 246 bytes I am not entirely sure if this works, it does iff the sequence that first diverges lower (as to be sorted lower) is always shorter, as for example `[1,2,4,8,16,32,64,128,256,512,125,250,500,1000]` is shorter than `[1,2,4,8,16,32,64,128,256,512,251,502,250,500,1000]` which i tested to be true up to 1000. ``` import Data.List h l|mod(e l)2==0=l:h(div(e l)2:l)|0<1=[l] s l=map((:l).read)(filter((/='0').e)(permutations$show$e l)) e=head m=map e n f=m.groupBy(\a b->e a==e b).sort.concatMap f w l|e(e l)==1=[nub$e l]|m x/=m l=w x|0<1=[[]] where x=n h(n s l) ``` [Answer] # C# 655 bytes ``` List<int> C(int i,List<int> x,int a){x.Add(a);if(a==i)return x;List<int> o=null;string s=a.ToString(),m=i.ToString();var res=G(s,s.Length);foreach (var r in res)if (r.First()!='0'){var l=int.Parse(new String(r.ToArray()));if(!x.Contains(l)&&l.ToString().Length<=m.Length){var n=C(i,x.ToList(),l);if(n!=null&&(o==null||o.Count()>n.Count()))o=n;}}if ((a*2).ToString().Length>m.Length)return o;var p = C(i, x.ToList(), a * 2);if (p!=null&&(o==null||o.Count()>p.Count()))o=p;return o;}IEnumerable<IEnumerable<T>> G<T>(IEnumerable<T> l,int i){return i==1?l.Select(t =>new T[]{t}):G(l,i-1).SelectMany(t=>l.Where(e=>!t.Contains(e)),(a,b)=>a.Concat(new T[]{b}));} ``` Call with (LinqPad): ``` var i = 64; C(i,new List<int>(),1).Dump(); ``` Haven't tested numbers above 99. If you have time -> good luck ;-) edit: ungolfed version: ``` List<int> C(int i, List<int> x, int toAdd, bool removeLast) { x.Add(toAdd); if ( toAdd == i ) { return x; } else { List<int> shortest = null; if ( toAdd > 9 ) { var res = G(toAdd.ToString(), toAdd.ToString().Length); foreach ( var r in res ) { if ( r.First () != '0' ) { var resi = int.Parse(new String(r.ToArray())); if ( !x.Contains(resi) && resi.ToString().Length <= i.ToString().Length ) { var resPerm = C(i, x.ToList(), resi, false); if ( resPerm != null ) { if ( shortest == null || shortest.Count() > resPerm.Count() ) { shortest = resPerm; } } } } } } if ( (toAdd * 2).ToString().Length > i.ToString().Length ) { return shortest; } var resDouble = C(i, x.ToList(), toAdd * 2, false); if ( resDouble != null ) { if ( shortest == null || shortest.Count() > resDouble.Count() ) { shortest = resDouble; } return shortest; } return shortest; } } IEnumerable<IEnumerable<T>> G<T>(IEnumerable<T> l,int i) { return i==1?l.Select(t => new T[]{t}):G(l,i-1).SelectMany(t=>l.Where(e=>!t.Contains(e)),(a,b)=>a.Concat(new T[]{b})); } ``` [Answer] # CJam, 83 ``` ri:N_1a:Xa:Y;{X,{XI=__se!{c~},:i^\2*|NA*,&X-_YI=f+Y\+:Y;X\+:X;}fI}*X#_){Y=W%}{;L}?p ``` [Try it online](http://cjam.aditsu.net/#code=ri%3AN_1a%3AXa%3AY%3B%7BX%2C%7BXI%3D__se!%7Bc~%7D%2C%3Ai%5E%5C2*%7CNA*%2C%26X-_YI%3Df%2BY%5C%2B%3AY%3BX%5C%2B%3AX%3B%7DfI%7D*X%23_)%7BY%3DW%25%7D%7B%3BL%7D%3Fp&input=23) I've been sitting on this for a long time, it's not very short nor fast, and I'm not sure I have the energy/motivation to improve it, so I'm just posting it. ]
[Question] [ As we all know, [meta](http://meta.codegolf.stackexchange.com/questions/185/language-handicap) [is](http://meta.codegolf.stackexchange.com/questions/1946/headers-in-verbose-languages) [overflowing](http://meta.codegolf.stackexchange.com/questions/7887/are-golf-languages-finally-drowning-us) [with](http://meta.codegolf.stackexchange.com/questions/1478/creating-a-language-conversion-table) [complaints](http://meta.codegolf.stackexchange.com/questions/88/on-golfscript-and-language-bigotry) [about](http://meta.codegolf.stackexchange.com/questions/8176/proposal-of-new-measure-for-byte-count-in-code-golf) [scoring](http://meta.codegolf.stackexchange.com/questions/2249/on-byte-count-and-language-preprocessing) [code-golf](http://meta.codegolf.stackexchange.com/questions/1416/1-on-1-language-mappings-legal) [between](http://meta.codegolf.stackexchange.com/questions/546/fair-size-comparison-across-languages-with-different-source-alphabets) [languages](http://meta.codegolf.stackexchange.com/questions/260/should-executable-binaries-be-considered-a-reasonable-solution-for-code-golf) (yes, each word is a separate link, and these may be just the tip of the iceberg). With so much jealousy towards those who actually bothered to look up the Pyth documentation, I thought it would be nice to have a little bit more of a constructive challenge, befitting of a website that specializes in code challenges. --- The challenge is rather straightforward. As **input**, we have the **language name** and **byte count**. You can take those as function inputs, `stdin` or your languages default input method. As **output**, we have a **corrected byte count**, i.e., your score with the handicap applied. Respectively, the output should be the function output, `stdout` or your languages default output method. Output will be rounded to integers, because we love tiebreakers. Using the most ugly, hacked together query ([link](http://data.stackexchange.com/codegolf/query/432202/get-code-golf-language-and-score) - feel free to clean it up), I have managed to create a [dataset (zip with .xslx, .ods and .csv)](https://www.dropbox.com/s/a35cfyk2ml3dlwf/QueryResults.zip?dl=1) that contains a snapshot of **all** answers to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") questions. You can use this file (and assume it to be available to your program, e.g., it's in the same folder) or convert this file to another conventional format (`.xls`, `.mat`, `.sav` etc - but it may only contain the original data!). The name should remain `QueryResults.ext` with `ext` the extension of choice. --- Now for the specifics. For each language, there is a Boilerplate \$B\$ and Verbosity \$V\$ parameters. Together, they can be used to create a linear model of the language. Let \$n\$ be the actual number of bytes, and \$c\$ be the corrected score. Using a simple model \$n=Vc+B\$, we get for the corrected score: $$c = \frac{n-B}V$$ Simple enough, right? Now, for determining \$V\$ and \$B\$. As you might expect, we're going to do some linear regression, or more precise, a least squares weighted linear regression. I'm not going to explain the details on that - if you're not sure how to do that, [Wikipedia is your friend](https://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)#Weighted_linear_least_squares), or if you're lucky, your language's documentation. The data will be as follows. Each data point will be the byte count \$n\$ and the question's average bytecount \$c\$. To account for votes, the points will be weighted, by their number of votes plus one (to account for 0 votes), let's call that \$v\$. Answers with negative votes should be discarded. In simple terms, an answer with 1 vote should count the same as two answers with 0 votes. This data is then fitted into the aforementioned model \$n=Vc+B\$ using weighted linear regression. --- **For example**, given the data for a given language $$ \begin{array} \\ n\_1=20, & c\_1=8.2, & v\_1=1 \\ n\_2=25, & c\_2=10.3, & v\_2=2 \\ n\_3=15, & c\_3=5.7, & v\_3=5 \end{array}$$ Now, we compose the relevant matrices and vectors \$A\$, \$y\$ and \$W\$, with our parameters in the vector $$ A = \left[\begin{matrix} 1 & c\_1 \\ 1 & c\_2 \\ 1 & c\_3 \\ \end{matrix}\right] y = \left[\begin{matrix} n\_1 \\ n\_2 \\ n\_3 \\ \end{matrix}\right] W = \left[\begin{matrix} 1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 5 \\ \end{matrix}\right] x = \left[\begin{matrix} B \\ V \\ \end{matrix}\right] $$ we solve the matrix equation (with \${}^T\$ denoting the matrix transpose) $$A^TWAx=A^TWy$$ for \$x\$ (and consequently, we get our \$B\$ and \$V\$ parameter). --- Your **score** will be the output of your program, when given your own language name and bytecount. So yes, this time even Java and C++ users can win! **WARNING: The query generates a dataset with a lot of invalid rows due to people using 'cool' header formatting and people tagging their [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") questions as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The download I provided has most of the outliers removed. Do NOT use the CSV provided with the query.** Happy coding! [Answer] # Mathematica, 244.719 (245 bytes) ``` f[l_,n_]:=x/.Solve[d=Rest@Import@"QueryResults.csv";LinearModelFit[#.#2/Tr@#&@@{#~Max~-1&/@#4+1,#3}&@@Thread@#&/@{#,#~Cases~{_,l,__}}&/@d~GroupBy~Last/@#[[;;,1,5]],x,x,Weights->Tr/@#[[;;,;;,4]]]&[d~Cases~{_,l,_,v_/;v>=0,_}~GatherBy~Last]@x==n,x] ``` --- **Test case** ``` f["mathematica", n] (* { .820033 (n + 53.4263) } *) f["mathematica", 245] (* { 244.719 } *) ``` What about other languages? ``` f["c++", n] (* { .821181 (n - 79.5437) } *) f["java", n] (* { .717579 (n - 56.0858) } *) f["cjam", n] (* { 2.21357 (n + 2.73772) } *) f["pyth", n] (* { 4.52194 (n - 8.82806) } *) ``` --- ## **Alternative model**: \$\log(c)=\log\left(\frac{n-B}V\right)\$ One notable feature of code golf (and probably other coding problems) is that the distribution of the lengths of programs tends to be exponential distribution (in contrast to uniform distribution). Hence model \$\log(n)=\log(Vc+B)\$ is much more likely to balance the influences between points with large \$c\$ and small \$c\$. As we can see in the graphs below, the distribution of points are suitable for fitting in logarithmic scale. [![ ](https://i.stack.imgur.com/U0hA6.png)](https://i.stack.imgur.com/U0hA6.png) --- **Results of the new model** ``` Language V B Python 1.365 -19.4 Javascript 1.002 1.6 Ruby 0.724 1.7 Perl 1.177 -32.7 C 1.105 1.5 Haskell 1.454 -24.5 Mathematica 1.319 -39.7 PHP 1.799 -62.0 Java 1.642 4.4 C# 1.407 4.5 CJam 0.608 -12.5 Pyth 0.519 -11.4 Golfscript 0.766 -18.0 J 0.863 -21.4 APL 0.744 -17.7 K 0.933 -23.3 Retina 1.322 -37.9 MATL 0.762 -13.3 Jelly 0.965 -23.8 ``` We have found two exceptional language - Ruby with \$V=0.72\$` and Retina with \$V=1.322\$, and a criterion of being a popular golfing language - having a large negative boilerplate. [Answer] # Python3, 765.19 (765) bytes Probably some room for golfing here. Requires numpy for matrix stuff. Reads from stdin, formatted as follows: [lang] [bytes/n]. Stops when you send q. ``` import numpy as n,csv L={};Q={};X={};D=n.dot;f=open('QueryResults.csv',encoding="utf8");R=csv.reader(f);f.readline();Z=list.append;M=n.matrix for r in R: if r[1] not in L:L[r[1]]=[] if r[4] not in Q:Q[r[4]]=[] Z(L[r[1]],r);Z(Q[r[4]],r) for l in L: b=[];a=[];v=[];t=[] for r in L[l]: if int(r[3])>-1: Z(b,int(r[2]));o=[] for q in Q[r[4]]:Z(o,int(q[2])) Z(a,sum(o)/len(o));Z(v,int(r[3])+1) for k in a:Z(t,[1,k]) if len(t)<1:continue A=M(t);T=A.transpose();W=n.diag(v);y=M(b).reshape((len(b),1));e=D(D(T,W),A) if n.linalg.det(e)==0:continue i=n.linalg.inv(e);X[l]=D(i,D(D(T,W),y)) p=input() while(p!="q"): S=p.split() if S[1]=='n':print("(n-("+str(X[S[0]].item(0))+"))/"+str(X[S[0]].item(1))) else:print(str((int(S[1])-X[S[0]].item(0))/X[S[0]].item(1))) p=input() ``` ### Results I might have done something wrong at some point; I get different results than the Mathematica answer: ``` python3 808 -> 765.19 python3 n -> (n-(32.41))/1.01 c++ n -> (n-(71.86))/1.17 cjam n -> (n-(-14.09))/0.51 java n -> (n-(18.08))/1.64 pyth n -> (n-(1.42))/0.28 jelly n -> (n-(-4.88))/0.34 golfscript n -> (n-(-0.31))/0.44 ``` ]
[Question] [ # Introduction Everyone knows that the possibility of successfully navigating an asteroid field is approximately 3,720 to 1. But despite your warning, Han Solo is still willing to try his luck. Fearing for your artificial life, you decide to code, in the ship's peculiar dialect (*read: your preferred Code Golf language*), **an asteroid avoidance program that will decide which path to take in an asteroid field ASCII maze.** # Input The Millenium Falcon has an asteroid field mapping program, that gives data similar to this: ``` | ##### ######### | | ###### # ### # | | # # # # #### # | @ ## #### |# # # ### ## | |## ## #### # # | |#### ##### # ## | ``` Top rows are left of the Falcon, bottom rows are right of the Falcon, and columns represent what is in front of the ship. * Each `#` is an obstacle. * Each space is empty space that the ship can fly in. * The input is always 7 characters high. This is the asteroid mapping width limit. * The input is always 32 characters long (30 for the field itself and 2 for the start and end limits). This is the asteroid mapping depth limit. Vertical bars `|` mark the beginning and the end of the mapping. * `@` is the Falcon. It is always in the middle row (4th row) and first column in the input. * The space left in the vertical bars on the last column is the place the ship must arrive at. It is always in the middle row (4th row) and last column in the input. The input can be taken as a multi-line string, an array of strings, from STDIN or a function parameters, or read from a file. # Possible maneuvers You are pursued by TIE-Fighters, therefore you must always go forward. There are thus three ways the ship can fly at each step: * `-` Forward * `/` Forward and turn left * `\` Forward and turn right For example, these are valid paths: ``` @--- -- / \ / @ - - / \ / \ @ \ ``` As you can see, there is always exactly one move per column. The Falcon is a piece of junk, therefore it cannot do violent turns. Which means moves such as `/\` or `\/` are **disallowed**. There must be atleast one pure forward `-` between two opposite turns. On the other hand, turning one way for multiple steps in a row is possible, as seen above. The Falcon crashes if one move leads the ship to be in a spot where an obstacle is. For example, these moves lead to crashes: ``` @-# @ \ # # / @ ``` Note that this is not a crash: ``` @-# \ - ``` # Output You must output the same asteroid field ASCII, with a valid path to the end. The Falcon must be printed at the end spot instead of the start spot. For example, a valid output for the input example given before would be: ``` | ##### ######### | | ###### #-------- ### # | | # # #/ # ####\ # | --------- ## \ #### ----@ |# # # ### \ ## / | |## ## #### \ #/ # | |#### ##### #-- ## | ``` Your path only needs to not crash the falcon. It doesn't need to be the shortest path possible. You can assume that there will always be at least one possible path to the end. You can output to STDOUT, in a file or any equivalent as long as the asteroid field is printed exactly like they are in this post (e.g. outputting a list of coordinates for the path is not valid). # Test cases * A normal asteroid field ``` | ##### ######### | | ###### # ### # | | # # # # #### # | @ ## #### |# # # ### ## | |## ## #### # # | |#### ##### # ## | ``` Possible output ``` | ##### ######### | | ###### #-------- ### # | | # # #/ # ####\ # | --------- ## \ #### ----@ |# # # ### \ ## / | |## ## #### \ #/ # | |#### ##### #-- ## | ``` * Hyperregular asteroid field ``` |# # # # # # # # # # # # # # # | | # # # # # # # # # # # # # # #| |# # # # # # # # # # # # # # # | @ # # # # # # # # # # # # # # |# # # # # # # # # # # # # # # | | # # # # # # # # # # # # # # #| |# # # # # # # # # # # # # # # | ``` Possible output ``` |# # # # # # # # # # # # # # # | | # # # # # # # # # # # # # # #| |# # # # # # # # # # # # # # # | -# #-# #-# #-# #-# #-# #-# #--@ |#\#/#\#/#\#/#\#/#\#/#\#/#\#/# | | #-# #-# #-# #-# #-# #-# #-# #| |# # # # # # # # # # # # # # # | ``` * Death star's core ``` | # # # # | | # # # | | # # # # # | @ # # # # # | # # # # | | # # # # # | | # # # # | ``` Possible output ``` | # # # -- # | | --- # # / #\ - | | / #\ # # / # \ /#\ | - # \ # #/ # - # ----@ | # \ # ---- # # | | # \#/ # # # | | # - # # # | ``` * Death star trench ``` |##############################| |##############################| |##############################| @ |##############################| |##############################| |##############################| ``` Output ``` |##############################| |##############################| |##############################| ------------------------------@ |##############################| |##############################| |##############################| ``` * Asteroid cave ``` |### ##########################| |## # ############### ## ######| |# ### ######## ### ## # #####| @ ###### ###### ### ## ### |######## ### ### ## #########| |########## # ### ## ##########| |########### #####| ``` Possible output ``` |###-##########################| |##/#\############### ##-######| |#/###--######## ### ##/#\#####| -######\###### ### ##/###-----@ |########--### ### ##/#########| |##########\# ### ##/##########| |###########-------- #####| ``` # Scoring R2D2 is busy swimming in swamps, so you're going to have to program the Falcon's controller by yourself, which is tedious. Therefore the **shortest code wins**. [Answer] # JavaScript (ES6), 186 ~~201~~ ``` f=([...s])=>(g=(i,l,c=k=" ")=>s[i]!=k&&s[i]!="@"?0:(i-130)?(s[i]=c,([..."/-\\"].some((c,j)=>!((--j&l&&j!=l)||!g(i+33*(l||j)+1,j,c)))||!(s[i]=k))):(s[i]="@",!console.log(s.join(""))))(99) ``` Runnable snippet: ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textarea cols="33" rows="7" id="t"></textarea><br><button><b>Solve &gt;&gt;&gt;</b></button><hr><button id="1">Normal</button> <button id="2">Hyperregular</button> <button id="3">Death Star core</button> <button id="4">Death Star trench</button> <button id="5">Asteroid cave</button><script>f=(function($__0){var $__2,$__3,$__4,$__5;s = $__4 = $__0.split("");return (g = (function(i, l) {var c = arguments[2] !== (void 0) ? arguments[2] : k = " ";return s[i] != k && s[i] != "@" ? 0 : (i - 130) ? (s[i] = c, ("/-\\".split("").some((function(c, j) {return !((--j & l && j != l) || !g(i + 33 * (l || j) + 1, j, c));})) || !(s[i] = k))) : (s[i] = "@",$("#t").val(s.join("")));}))(99);});$("button").click(function() {this.id?$("#t").val(inputs[this.id]):f($("#t").val());});inputs = [,`| ##### ######### |\n| ###### # ### # |\n| # # # # #### # |\n@ ## #### \n|# # # ### ## |\n|## ## #### # # |\n|#### ##### # ## |`,`|# # # # # # # # # # # # # # # |\n| # # # # # # # # # # # # # # #|\n|# # # # # # # # # # # # # # # |\n@ # # # # # # # # # # # # # # \n|# # # # # # # # # # # # # # # |\n| # # # # # # # # # # # # # # #|\n|# # # # # # # # # # # # # # # |`,`| # # # # |\n| # # # |\n| # # # # # |\n@ # # # # # \n| # # # # |\n| # # # # # |\n| # # # # |`,`|##############################|\n|##############################|\n|##############################|\n@ \n|##############################|\n|##############################|\n|##############################|`,`|### ##########################|\n|## # ############### ## ######|\n|# ### ######## ### ## # #####|\n@ ###### ###### ### ## ### \n|######## ### ### ## #########|\n|########## # ### ## ##########|\n|########### #####|`];$("#t").val(inputs[1]);</script ``` This function accepts a single string with newlines. The function splits the string into an array using the `...` operator and gets the index for `(x,y)` coordinates by `(33 * y) + x`. The function runs recursively, testing out different possible moves for each space. When it encounters an obstacle, it returns a falsy value, and when it reaches the end goal space, it returns `true`. (In the golfed code, this `true` is created by `!console.log(...)`.) Note that this code does not use long runs of right-turn moves, but punctuates them with straight moves. That is, it does the second option below, not the first: ``` \ \ \ (<= not this!) - (<= yes this!) \ \ ``` This seems to be legal, since `-` can legally come before or after a turn, so why not both at once? That looks especially strange at the end, when the final move is `\` but is displayed as `@`: ``` | --# # # ------# - | | / \ # # / # \ / \ | |/ #- # # / # #- -| # \ # #/ # # @ | # - # ---- # # | | # \#/ # # # | | # - # # # | ``` My favorite nasty golf hack here is default argument abuse with `c=k=" "`. The arguments `(i,l,c=" ")` would say "use the string `" "` for `c` if `f` is not supplied a third argument". However, by doing `c=k=" "`, we say "if `c` is not supplied, store `" "` in the global variable `k` and then store that value in `c` as well". Since the recursion begins with only a single argument, `k` is always initialized at the first function call. Mildly ungolfed: ``` // `i` - index in the string we're working on // `l` - move character for this space (`/`, `\`, or `-`) search = (i,l,c)=>{ // not an open space; nip this recursive branch if(s[i]!=" "&&s[i]!="@") { return 0; } // we made it! the 130th space is (31,3) if(i==130) { s[i]="@"; console.log(s.join("")); return true; } // fill in space with move character or a blank // (the space is only to blank out the initial `@`) s[i] = c || " "; // iterate through the 3 options and recursively explore the map return ['/','-','\\'].some((c,j)=>{ --j; // if last move was sideways, and this is the opposite move, skip it if(l && j && j!=l) { return 0; } // recursively call search function on space pointed to by this move or the last move return search(i+33*(l||j)+1, j, c); }) // if the `some` call is false (i.e. all options fail for this space) // then blank out this space and return false || !(s[i]=" "); } ``` [Answer] # C (complete program), 249 247 235 bytes This is a complete program reading the input from a file and outputting the result to stdout. The name of the file is passed as a parameter to the program. ``` char f[7][33];g(i,j,c){return(i<0|i>6|f[i][j]%32?0:j<31?c%45-2?g(i,j+1,c)||g(i+1,j+1,92)||g(i-1,j+1,47):g(i+c/30-2,j+1,c)||g(i+c/30-2,j+1,45):1)?f[i][j]=j?j-31?c:64:32:0;}main(int p,char**v){read(open(v[1],0),f,231);g(3,0,45);puts(f);} ``` Ungolfed: ``` /* the field */ char f[7][33]; /* i - row * j - col * c - movement */ g(i,j,c) { return /* if we're in bounds and not on an obstacle */ (i >= 0 & i<7 & f[i][j] % 32 == 0 ? /* if we haven't reached the end */ j < 31 ? /* are we going straight ahead? */ c%45-2 ? /* try to go straight */ g(i,j+1,c) /* try to turn right */ || g(i+1,j+1,92) /* try to turn left */ || g(i-1,j+1,47) /* turning */ : /* try to keep turning */ g(i+c/30-2,j+1,c) /* try to go straight */ || g(i+c/30-2,j+1,45) /* done */ :1 /* replace this with c==45 to better represent the last move being a turn */ /* invalid move, fail */ :0) /* add the correct movement to the field */ ? f[i][j] = j ? j - 31 ? c : 64 : 32 /* no path, much sads :( */ :0; } main(int p,char*v[]) { /* read input file */ read(open(v[1],0),f,231); /* calculate the path */ g(3,0,45); /* print it out */ puts(f); } ``` Output: ``` $ ./a.out test.inp | ##### ######### | | ###### # ### # | | # # # # #### # --| ------------- ##----#### / @ |# # # \ /### \ ## / | |## ## - #### \ # /# | |#### ##### #---## | $ ./a.out test2.inp |# # # # #-# # # # # #-# # # # | | # # # #/#\# # # # #/#\# # # #| |# # # #/# #\# # # #/# #\# # # | -# # #/# # #\# # #/# # #\# # @ |#\# #/# # # #\# #/# # # #\# #/| | #\#/# # # # #\#/# # # # #\#/#| |# #-# # # # # #-# # # # # #-# | $ ./a.out test3.inp | # # # ------# | | - # # / # \ | | /#\ # # / # #\ | --- # \ # #/ # # \ @ | # \ # / # # \ /| | # \# /# # # - | | # ---- # # # | $ ./a.out test4.inp |##############################| |##############################| |##############################| ------------------------------@ |##############################| |##############################| |##############################| $ ./a.out test5.inp |###-##########################| |##/#\############### ##-######| |#/###--######## ### ##/#\#####| -######\###### ### ##/###-----@ |########--### ### ##/#########| |##########\# ### ##/##########| |###########-------- #####| ``` [Answer] # Common Lisp, 303 bytes Had lots of fun with this challenge, it's the first codegolf task I did. Basically there's a simple recursive function that tries every viable move until the end position is reached. ## Golfed/Minified ``` (let((s(open "i"))(n nil)(f(make-string 231)))(read-sequence f s)(labels((r(p s u d)(and(< 0 p 224)(find(aref f p)" @")(setf(aref f p)(cond((= 130 p)#\@)((or(unless d(r(- p 32)#\/ t n))(unless u(r(+ p 34)#\\ n t))(r(+ p(cond(u -32)(d 34)(t 1)))#\- n n))s)((return-from r)))))))(r 99 #\- n n)(princ f))) ``` Reads input from a file **i** in working directory. I'm pretty sure there's still room for improvement. ## Plain code ``` (defun run-test (file) (let ((stream (open file)) ;;should use with-open-file for autoclose.. (no nil) ;; alias for brevity (field (make-string 231))) (read-sequence field stream) (labels ((doit (pos sym going-up going-down) (and (< 0 pos 224) (find (aref field pos) " @") (setf (aref field pos) (cond ((= 130 pos) #\@) ((or (unless going-down (doit (- pos 32) #\/ t no)) (unless going-up (doit (+ pos 34) #\\ no t)) (doit (+ pos (cond (going-up -32) (going-down 34) (t 1))) #\- no no)) sym) ((return-from doit))))))) (doit 99 #\- no no) (princ field) nil))) ``` ## Sample output ``` | ##### -- ######### | | ###### # / \ ### # - | | # # # # /####\ # / \| -- - / ## \#### / @ |#\ /#\ # / ### \ ## / | |##- \ ##/ #### \ #/ # | |#### --- ##### #-- ## | | --# # # -- #- | | / \ # # / #\ / \ | |/ #\ # # / # \ /# \ | - # \ # #/ # - # \ @ | # \ # ---- # # -| | # \#/ # # # | | # - # # # | |# #-# # # # # #-# # # # # #-# | | #/#\# # # # #/#\# # # # #/#\#| |#/# #\# # # #/# #\# # # #/# #\| --# # #\# # #/# # #\# # #/# # @ |# # # #\# #/# # # #\# #/# # # | | # # # #\#/# # # # #\#/# # # #| |# # # # #-# # # # # #-# # # # | ``` [Answer] # ActionScript 3, 364 bytes I split this into two functions; one to change the array into an array of arrays, and one recursive one to compute the flight path. ``` function m(f){for(var i=0;i<f.length;i++){f[i]=f[i].split("");}n(f,0,3,0);return f;}function n(f,x,y,m){var P=f[y][x],X=x+1,A=y-1,B=y,C=y+1,T=true,F=false,E='-';if (y<0||y>6||P=='#'||P=='|')return F;if (x==31){f[y][x]='@';return T;}if(m<0&&y>0){B=A;C=9;E='/';}else if(m>0&&y<6){A=9;B=C;E='\\';}if (n(f,X,B,0)||n(f,X,A,-1)||n(f,X,C,1)){f[y][x]=E;return T;return F;} ``` Ungolfed version in a program with one sample asteroid field defined: ``` package { import flash.display.Sprite; public class AsteroidNavigator extends Sprite { var field:Array; public function AsteroidNavigator() { field = [ "| ##### ######### |", "| ###### # ### # |", "| # # # # #### # |", "@ ## #### ", "|# # # ### ## |", "|## ## #### # # |", "|#### ##### # ## |"]; m(field); printField(); } function m(f){ for(var i=0;i<f.length;i++){ f[i]=f[i].split("");\ } n(f,0,3,0); return f; } private function n(field,x,y,m) { var C = field[y][x]; if (x > 31 || C == '#' || C == '|') { return false; } if (x == 31 && y == 3) { field[y][x] = '@'; return true; } if (m == 0) { if (n(x+1, y, 0) || ((y>0) && n(x+1, y-1, -1)) || ((y<6) && n(x+1, y+1, 1))) { field[y][x] = '-'; return true; } } else if ((m<0) && (y>0)) { if ((n(x+1, y-1, -1) || n(x+1, y-1, 0))) { field[y][x] = '/'; return true; } } else if ((m>0) && (y<6)) { if ((n(x+1, y+1, 1) || n(x+1, y+1, 0))) { field[y][x] = '\\'; return true; } } return false; } private function printField() { var sb = ""; for each (var row:Array in field) { sb += row.join("") + "\n"; } trace(sb); } } } ``` ]
[Question] [ Given a [POSIX](http://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended) [Extended Regular Expression](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended) as input, output its complement (also a POSIX ERE). If the given regular expression matches a string, its complement should not match it, and the regex: `(regex given)|(complement)` should match any string. In other words, negate the regex. The regex for format input and for output, POSIX ERE, is basically regex without character classes, lookarounds, backreferences, etc. You can assume that we only care about ASCII characters. Also, assume that character classes do not contain `-` for use as ranges (no `[a-d]` as input; instead, the input would be `[abcd]`). Further assume that `?` and `+` and `{}` will not be used in the input as metacharacters. `x?` will be shown with `x|` and `x+` by `xx*` where x is an arbitrary regular expression. The variations of `{m,n}` will be similarly written out (e.g.: instead of `x{1,4}`, you'll get `x|xx|xxx|xxxx`). Sample Input: ``` ^([helo][world])([helo][world])*$ ``` Possible Output (Thanks [Peter Taylor](http://chat.stackexchange.com/transcript/message/14223416#14223416)): ``` ^(([helo]([world][helo])*)?$|([helo][world])*[^helo]|[helo]([world][helo])*[^wo‌​rld]) ``` Please post a few sample Input/Outputs [Answer] # JavaScript, 1563 bytes ``` m=>`^${((l,n={s:{[e(l[0])]:""}})=>((t=s=>n[x=e(s)]=n[x]||(n[x]={},r.reduce(((r,o,c)=>(c=l[2](s)(o),t(c),r[x=e(c)]=(r[x]||"[]")[$](0,-1)+("\\"==o||"]"==o?"\\":"")+o+"]",l[1](s)||(r.e=""),r)),{})))(l[0]),(g=Object.keys)(n)[h]((e=>"s"!=e&&(c=n[e],d=c[e],delete c[e],delete n[e],g(n)[h]((l=>(s=n[l][e])!={}.x&&delete n[l][e]&&g(c)[h]((e=>(o=s+(d?`(${d})*`:"")+c[e],n[l][e]=n[l][e]!={}.x?`(${n[l][e]}|${o})`:o)))))))),n.s.e||"[]"))((a=e=>e===e+""?e?[0,e=>1==e,l=>t=>[t==e?1:2,2,2][l]]:[0,e=>!e,e=>e=>1]:[([e])=>[0,l=>!l||l.some((l=>e[1](l))),t=>r=>l((t||[e[0]]).flatMap((l=>[x=e[2](l)(r),...e[1](x)?[e[0]]:[]])))],e=>[e[h]((e=>e[0])),l=>l.some(((l,t)=>e[t][1](l))),l=>t=>l[h](((l,r)=>e[r][2](l)(t)))],([e,t])=>[[e[0],e[1](e[0])?[t[0]]:[]],e=>e[1].some((e=>t[1](e))),r=>s=>[x=e[2](r[0])(s),l([...e[1](x)?[t[0]]:[],...r[1][h]((e=>t[2](e)(s)))])]],l=>[0,e=>1==e,l=>t=>[e[1].includes(t)?1:2,2,2][l]]][e[0]](e[1][h](a)))((f=e=>e.length?e.reduce(((e,l)=>[2,[e,l]])):"")(m[$="slice"](1,-1).split(/(\\.|[^\\])/).filter((e=>e)).reverse(e=JSON.stringify,l=l=>[...new Set(l[h](e))].sort()[h](JSON.parse),r=[...Array(95)][h](((e,l)=>String.fromCharCode(l+32))),h="map")[u="reduceRight"](p=(e,l,t,s)=>e&&{[l]:t=>[...e,l[$](-1)],".":l=>[...e,[3,r]],"*":l=>e.concat([[0,[e.pop()]]]),"[":l=>[...e,((e,l)=>[3,e?r.filter((e=>!l.includes(e))):l])(n="^"==s[t-1],s.splice(s.lastIndexOf("]"),s.length)[$](1,-n||{}.x)[h]((e=>e[$](-1))))],")":l=>(i=e,0),"(":l=>[...e,(s[u](p,[]),[1,i.reduce((([e,...l],t)=>1==t?[[],e,...l]:[[...e,t],...l]),[[]])[h](f)])],"|":l=>[...e,1]}[s.pop()](),[]))))}$` ``` [Try it online!](https://tio.run/##XVRNb@M2EP0rMWEYw5jh2gl6qAraKPbUAm2AzZFmYFWmP7a0ZJBMNoHl354@UnLsrXSQOJw3b97MkN/L1zJUfneId3Wzsh@vpb/Z/lY1dWicla7ZEH3s1Wz5PDwSOVGrYyiO2pLTE8NNwdjpxNWMKKqgZrV@U5YCNwp/pm0pfdTxJLz0dvVSWSLyohFVglTK6XsDb2q4iFRx4TO8Apx8xjNtGNdDQxNxN@VjYosFU6rBhknfeVojBT5uxrAIp6cpHni9tAp24TkXxxPnvMtX0EY9/vPdVlH@a9/BXHO9NURWzVhgA2VHI6RVa2vESlX5Y52N9ub6P29vzlAHJQEQZ2DmA4iVb6PRp2s2j0YbqDozUaPCmFbzJQ2PqxO/XWYFmaH3P4fromXH3nJqh8fmxJdFw/tH1DJI25eKE5UKFFYpZceMze1cTwQMU6wFUo1qpiP@59PiXuA1CGuKzmdgRYbOprBQUgPnSUINXNs6GZq9zXptKrNL3Ajn1cyh@22rLSpsuFy7Mv5VHrJn6mfqsePkuZBSZugbn3fOhQaAc5N4Yenrk7YQG/AzJ@Yu8rQRzSd1J8ZlEPZ93vemZ4s5LESImGVkPpHZc/i5jucEsmhs9FxYxeyWSCAuXFT4hMR8CUf6Wss5VBLoYTwLiQlkEwLJcDC5XND/tSNz7@rKvaxsQOI/tcZ0hSLbhy3TKNM691g6W2/idm4vZwtBk9p7AeEu1TaNFu31ULHgdpVlhqbpJMlwcLtIX2ixkK1@XiwM/4LO7Vy0vusB54j6an2wWP759Pi3DNHv6s1u/S62iu3LA46bSoIgurY/bp5spNwNQFMtfaQ88Rl7KBEolTN5/@59@U6//sK7QvVJP@Xwcu2b/ddt6b/iLiI3frhPM65fFOs0ftttthEqDirBRBQh9X00OqJYReyywUa6MiDTCCZZ4c5m/SA8usBus81KXHJVGUmjJ9rKQ3MgNAmXBNNXoM@iPgg799c1GrhL29K0FA7TUSv2jKsp6Hg3NSLkQqM1QboyxD/qlX17XBPuKo69rn/5fkNX6rZNp51fjkEnIk8y4zkl2mFuJsiQrjMM@gUVERqp66nYXcYBUwAPZ/LpwczFucaU9sZCd/BoujXA6Tgm@nUaV8HaK5KpOenQ14h44sJzGi4/OLFn0lvrGqN/NN6tUISfl7dDXEwf/wE "JavaScript (Node.js) – Try It Online") ## Input/Output Examples The challenge was to golf the source, not the output ¯\\_(ツ)\_/¯ ``` Input: ^([helo][world])([helo][world])*$ Output: ^(((((((((|[ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdfgijkmnpqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)|[ehlo])|[ehlo][ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcefghijkmnpqstuvxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)|[ehlo][dlorw][ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdfgijkmnpqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)|[ehlo][dlorw][ehlo])|[ehlo][dlorw][ehlo][ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcefghijkmnpqstuvxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)|[ehlo][dlorw][ehlo][dlorw][ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdfgijkmnpqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)|[ehlo][dlorw][ehlo][dlorw][ehlo](|[ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcefghijkmnpqstuvxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*))|[ehlo][dlorw][ehlo][dlorw][ehlo][dlorw]([ehlo][dlorw])*([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdfgijkmnpqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*|[ehlo](|[ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcefghijkmnpqstuvxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)))$ Input: ^.*$ Output: ^[]$ # Empty character set matches nothing Input: ^[]$ Output: ^(|[ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)$ Input: ^(|[ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~]([ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~])*)$ Output: ^[]$ ``` ## ~~Ungolfed~~ Less Golfed ``` let input = "^([helo][world])([helo][world])*$" const star = 0 const union = 1 const concat = 2 const group = 3 const charset = [...Array(95)].map((_, i) => String.fromCharCode(i + 32)); input = `.*${input}.*`.replace(/\.\*\^|\$\.\*/g, ""); const makeConcat = x => x.length ? x.reduce((a, b) => [concat, [a, b]]) : ""; const regex = makeConcat(input .split(/(\\.|[^\\])/) .filter(x => x) .reverse() .reduceRight(_parseRegex = (acc, char, i, arr) => ( acc && { [char]: _ => [...acc, char.slice(-1)], ".": _ => [...acc, [group, charset]], "*": _ => acc.concat([[star, [acc.pop()]]]), "[": _ => [...acc, ((i, a) => [group, i ? charset.filter(x => !a.includes(x)) : a] )( invert = arr[i - 1] == "^", arr .splice(arr.lastIndexOf("]"), arr.length) .slice(1, -invert || {}.x) .map(x => x.slice(-1)) )], ")": _ => (result = acc, null), "(": _ => [...acc, ( arr.reduceRight(_parseRegex, []), [union, result.reduce(([a, ...b], char) => ( char == union ? [[], a, ...b] : [[...a, char], ...b] ), [[]]).map(makeConcat)] )], "|": _ => [...acc, union], }[arr.pop()]() ), [])) const str = JSON.stringify; const set = x => [...new Set(x.map(str))].sort().map(JSON.parse) const initial = 0; const accept = 1; const next = 2; const dfa = (regexToDfa = re => re === re + "" ? re ? [0, x => x == 1, x => c => [c == re ? 1 : 2, 2, 2][x]] : [0, x => !x, x => c => 1] : [ // star ([sub]) => [ 0, state => !state || state.some(substate => sub[accept](substate)), state => char => set((state || [sub[initial]]).flatMap(substate => [ x = sub[next](substate)(char), ...sub[accept](x) ? [sub[initial]] : [] ])) ], // union subs => [ subs.map(sub => sub[initial]), state => state.some((substate, i) => subs[i][accept](substate)), state => char => state.map((substate, i) => subs[i][next](substate)(char)), ], // concat ([a, b]) => [ [a[initial], a[accept](a[initial]) ? [b[initial]] : []], state => state[1].some(x => b[accept](x)), state => char => [ x = a[next](state[0])(char), set([ ...a[accept](x) ? [b[initial]] : [], ...state[1].map(substate => b[next](substate)(char)) ]) ] ], // group _ => [ 0, state => state === 1, state => char => [re[1].includes(char) ? 1 : 2, 2, 2][state], ] ][re[0]](re[1].map(regexToDfa)) )(regex) const testDfa = i => dfa[accept]([...i].reduce((a, b) => dfa[next](a)(b), dfa[initial])) const invertDfa = dfa => [dfa[initial], x => !dfa[accept](x), dfa[next]] const dfaToString = (dfa, paths = { s: { [str(dfa[initial])]: "" } }) => ( (visitState = (state) => paths[x = str(state)] = paths[x] || (paths[x] = {}, charset.reduce((obj, char, nextState) => ( nextState = dfa[next](state)(char), visitState(nextState), obj[x = str(nextState)] = (obj[x] || "[]").slice(0, -1) + (char == "\\" || char == "]" ? "\\" : "") + char + "]", dfa[accept](state) && (obj.e = ""), obj ), {}) ))(dfa[initial]), Object.keys(paths).map(removeState => removeState != "s" && ( obj = paths[removeState], selfPath = obj[removeState], delete obj[removeState], delete paths[removeState], Object.keys(paths).map(a => ( initialPath = paths[a][removeState]) !== {}.x && delete paths[a][removeState] && Object.keys(obj).map(b => ( path = initialPath + (selfPath ? `(${selfPath})*` : "") + obj[b], paths[a][b] = paths[a][b] != {}.x ? `(${paths[a][b]}|${path})` : path )) ) )), paths.s.e || "[]" ) console.log(`^${dfaToString(invertDfa(dfa))}$`) ``` ## Explanation The program executes the following process: 1. Parse the regex into a tree structure 2. Convert the tree structure into a DFA 3. Invert the accepted/rejected states of the DFA 4. Convert the DFA into a (stringified) regex In the parsed regex tree, the leaves are characters, and the branches are operations. For example, `^a[bc](d|e*)$` would look like ``` [2 /* concat */, [ [2 /* concat */, [ "a", [3 /* character group */, [ "b", "c", ]], ]], [1 /* union */, [ "d", [0 /* star */, [ "e", ]], ]], ]] ``` A DFA is represented as a 3-tuple: ``` [ initial /* state */, accept /* state => bool */, next /* state => char => bool */, ] ``` States are numbers or deep arrays of numbers. To convert this parsed regex into a DFA, the tree is processed bottom-up. Single characters and character groups become 3-state DFAs (start, accept, and dead). Operations compose their DFA operands in various ways; for example, union tracks the state of each operand, and accepts any state where one of the operands is accepting. The DFA is then inverted by negating the `accept` function. To convert the inverted DFA into a regex, it is encoded into a JS object that represents a `(state, state) -> string`. Each string will be a regex that accepts the set of strings that will move the DFA from one state to another. Initially, the strings are simply character classes containing all of the characters between the two states in the DFA. This is what the object would look like initially for the regex `^[ab]$`, if the alphabet was limited to `abc`. ``` { s: { 0: "" }, 0: { 1: "[ab]", 2: "[c]" }, 1: { e: "", 2: "[abc]" }, 2: { 2: "[abc]" }, } ``` The special keys `s` and `e` represent the start and end, respectively. In this case, the state `2` is a dead state, where no progress can be made. The leaf values are referred to "arrows"; for example, the `01` arrow goes from `0` to `1` and has a regex of `[ab]`. Any non-existent arrows have a regex of `[]`, a regex that matches nothing. This object now needs to be distilled to a singular regex. Then, each of the states is removed iteratively. When removing states, the arrows associated with those states must be combined with the other regexes. If there are states `A` and `B` (not necessarily distinct), and a state `X` which is being removed, arrow `AB` will be upserted to be ``` <AB>|<AX><XX>*<XB> ``` Note that: * If there is no `XX` arrow, the `AB` arrow will become `<AB>|<AX><XB>`, as `[]*` is equivalent to `()` (the regex that matches the empty string). * If there is no `AB` arrow, there will be a new arrow that is `<AX><XX>*<XB>`. * If there is no `AX` arrow or no `XB` arrow, the `AB` arrow will be unchanged. Thus, the object evolves as follows: ``` // Original { s: { 0: "" }, 0: { 1: "[ab]", 2: "[c]" }, 1: { e: "", 2: "[abc]" }, 2: { 2: "[abc]" }, } // After removing 0 { s: { 1: "[ab]", 2: "[c]" }, 1: { e: "", 2: "[abc]" }, 2: { 2: "[abc]" }, } // After removing 0 and 1 { s: { e: "[ab]", 2: "[c]|[ab][abc]" }, 2: { 2: "[abc]" }, } // Final { s: { e: "[ab]" }, } ``` In the end, the object will be `{ s: { e: <regex> } }` or `{ s: {} }`. If it's the latter, there was no path from `s` to `e`, so the final regex is `[]`. Interestingly, this process is far from lossless; running a regex through without inverting it often still explodes the size: ``` Input: ^a[bc](d|e*)$ Output (not inverted): ^((([a][bc]|[a][bc][d])|[a][bc][e])|[a][bc][e][e]([e])*)$ ``` ]
[Question] [ This challenge is about the game Tic Tac Toe, but it's played on a torus. # How to play To create the necessary game board, you start out with a regular Tic Tac Toe game board. First fold it into a cylinder by joining the left and the right edge. Then fold it into torus by joining the top and the bottom edge. Here's a simple visualization of such a game board with a few moves played (Sick Paint skills!). ![Tic Tac Torus](https://i.stack.imgur.com/Wm0ln.png) The rules of Tic Tac Toe on a torus are the same as regular Tic Tac Toe. Each Player place alternating Xs and Os. The first one with 3 same symbols in a row, a column or a in a diagonal wins. Since a torus is quite hard to visualize, we simply project the board back onto a paper. Now we can play the game as regular Tic Tac Toe. The only difference is, that you can also win with 3 same symbols in a broken diagonal. For instance Player 1 (X) wins the following board. You can see this easily by changing the view on the torus a little bit. ![Player 1 (X) wins because of 3 Xs in one broken diagonal](https://i.stack.imgur.com/8xoVD.png) If your interested, you can play Tic Tac Toe on a Torus at [Torus Games](http://www.geometrygames.org/TorusGames/). There's a Windows, Mac and Android version. # Optimal Games In this challenge were interested in optimal games. An optimal game is a game, where both players play an optimal strategy. On a regular Tic Tac Toe board optimal games always end in a draw. Fascinatingly on a torus board always the first player wins. In fact a game on a torus board can never end in a draw (also if the players play not optimal). The optimal strategy is really easy: * If you can win by placing your symbol, do it. * Otherwise if your opponent has two symbols in one row/column/điagonal, try to block him. Otherwise, do what you want. * Otherwise do what you want. Every optimal game consists of exactly 7 moves and these moves can be described in the following way: 1. Player 1 places a X anywhere on the board (9 choices) 2. Player 2 places an O anywhere on the board (8 choices) 3. Player 1 places a X anywhere on the board (7 choices) 4. Player 2's move may be forced (1 choice), if not, he places the O anywhere (6 choices) 5. Player 1's move is forced (1 choice) 6. Player 2 is caught in a fork (Player 1 can win in two different ways), so Player 2 has to block Player 1 in one way (2 choices) 7. Player 1 places the his last move and wins (1 choice) There are 9\*8\*1\*6\*1\*2\*1 + 9\*8\*6\*1\*1\*2\*1 = 1728 different optimal games on our projected board. Here you can see one typical optimal game: ![Example of an optimal game](https://i.stack.imgur.com/mC9s2.png) If we label each cell of the board with the digits `0-8`, we can describe this game by the digits `3518207`. First a X is places in the cell 3 (middle row, left column), than an O in cell 5 (middle row, right column), than a X in cell 1 (upper row, middle column), ... Using this digit notation we automatically generated an order. Now we can sort all of the 1728 optimal games and we get the list: ``` Game 0000: 0123845 Game 0001: 0123854 Game 0002: 0124735 Game 0003: 0124753 Game 0004: 0125634 ... Game 0674: 3518207 ... Game 1000: 5167423 Game 1001: 5167432 Game 1002: 5168304 ... Game 1726: 8765034 Game 1727: 8765043 ``` # Challenge This list is part of your job. You will receive one number `k` between 0 and 1727 and you have to return the `k`th game in digit notation of that sorted list. Write a function or a program, that receives the number `k` (integer) computes the correspondent game. You can read the input via STDIN, command-line argument, prompt or function argument and print the result (7 digits) in a readable format (e.g. `0123845` or `[0, 1, 2, 3, 8, 4, 5]`) or return it using an string (human readable format) or an integer (containing all digits in base 10), or in any array/list format. The challenge type is code-golf. Therefore the shortest code wins. [Answer] # JavaScript (ES6), 266 ~~308 317 334 341~~ A function returning a string. **Edit** Found an arithmetic solution for function M (at last!) ``` F=(n,x=[],M=(a,b,t=-a-b)=>(a-b)%3?a<3&b<3?3+t:a>5&b>5?21+t:12+t:9+t+a%3*3)=> [for(a of z='012345678')for(b of z)for(c of z)for(d of z) a-b&&c-a&&c-b&&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c)&&( f=M(c,e=M(b,d)),g=M(a,e),g<f?[f,g]=[g,f]:0,r=a+b+c+d+e,x.push(r+f+g,r+g+f))] &&x[n] ``` Very naive ~~, it can be shortened in many ways~~. It simply enumerates all the possible legal values and returns what find at place n. The M function returns the position in between two cells, that is the mandatory move to block an opposite player. *More readable* ``` F=(n,x=[], M=(a,b,t=-a-b)=>(a-b)%3? a<3&b<3? 3+t // first row :a>5&b>5? 21+t // last row :12+t // middle row and diags :9+t+a%3*3 // columns )=> [for(a of z='012345678') // enumerate the first 4 moves for(b of z) for(c of z) for(d of z) a-b&&c-a&&c-b // avoid duplicates &&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c) // and check if d must block a-c or it's free &&( e=M(b,d), // forced to block b-d f=M(c,e),g=M(a,e),g<f?[f,g]=[g,f]:0, // f and g could be in the wrong order r=a+b+c+d+e, // start building a return string x.push(r+f+g,r+g+f) // store all values in x )]&&x[n] // return value at requested position ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 73 [bytes](https://github.com/abrudz/SBCS) ``` ⎕⊃z/⍨(∧/{⍵[4⍪3 2⍴5 6 1 3]∊⍨∘{3⊥3|-+/3 3⊤⍵}¨⍥↓⍵[1 3⍪3 2⍴0 4 2]},≠)¨z←,⍳7⍴9 ``` [Try it online!](https://tio.run/##lVFNa9tAEL3rV8xRix0s7a4@XOihl5YeQgo9tFB8UBs5FXWsEps4jupTwVUMCgkh0EshAYeaXNv8Af@U@SPuzEp2nI8egthl582bt2@foq@dje1h1El3Fnh8/noLxyeOhcUveOM@g6g7HHyO92Kwm6IE5ToYikeYbs0XdXAhaUN8kPT6SXeHxuBjJ/30pQdJ/xEdX0C6VzJIzHZvZStMrjC5xNJuDGmbSD2w5e3AIOky19QVZTfdj6XZ9dIFF26Nd2WYfPLWm9I09arpk9ttcwqWtErdNlqmpYSZ8izMf7Q5TZx8P2xgMbMx/93IsLj5oLG4ViCx@OuBTyGpFuYTYmD@M1M4uVLfNmoNBXScEn00n2FxheMzHiXyatgBDbI1quPRhZjPDumf1bH4E1CnuaDL2fZu1Cc4szO@2/6PeKmsK03JhsBog24JcnaPwm1NH3un1TL@bkSD1TKbdjy6pJdgfr3WWDmznmDp4WPv2nkQ4xOttF9GPTZDf4hYZGxBro7PR1hMHSYJHh@fGtp8Rpm4lIkfaHAdx@GNsgpkYJUNBSGnslZ5oKtKQ0CIZ9GiOiTEgcDis08djlpVVViGb4WEc778brXYfPH@3dvn7qt/ "APL (Dyalog Unicode) – Try It Online") A full program, and takes way too much time and memory to complete for any input. Also, the code includes some 18.0 features that aren't yet available on TIO. The TIO link includes a faster version using only features up to 17.1, so that the output can be checked. ### Winning or blocking position Given two positions, extract their row and column numbers. For each dimension (row/column), if the numbers are the same, so is the result; otherwise, the result is the third number. In both cases, the result coordinates can be found with the following property: ``` n1 n2 res -(n1+n2)%3 0 0 0 0 0 1 2 2 0 2 1 1 1 0 2 2 1 1 1 1 1 2 0 0 2 0 1 1 2 1 0 0 2 2 2 2 ``` The resulting code is as simple as the following. ``` {3⊥3|-+/3 3⊤⍵} ⍝ ⍵←two positions 3 3⊤⍵ ⍝ Convert the numbers to base 3, each number → column +/ ⍝ Sum of each row 3|- ⍝ Negate and modulo 3 3⊥ ⍝ Convert from base 3 to integer ``` ### How the code works ``` z←,⍳7⍴9 ⍝ Create an array of 7-tuples of 0..8 z/⍨(...)¨z ⍝ Filter the tuples by the following condition: ∧/{...},≠ ⍝ Check that Unique Mask (≠) is all ones AND it is an optimal TTT game: ⍵[...] ... ⍵[...] ⍝ Extract certain indexes of the given tuple as matrices ⍥↓ ⍝ Downrank both sides into four 2-tuples ∘{...}¨ ⍝ For each tuple of the right side, 3⊥3|-+/3 3⊤⍵ ⍝ Compute the cell that completes a line in TTT ∊⍨ ⍝ And check that the right side appears in ⍝ the matching tuple on the left side ⎕⊃ ⍝ Take input n from stdin and pick the nth 7-tuple ------------------- Left side idxs ≡ ↓4⍪3 2⍴5 6 1 3 ≡ (4 4)(5 6)(1 3)(5 6) Right side idxs ≡ ↓1 3⍪3 2⍴0 4 2 ≡ (1 3)(0 4)(2 0)(4 2) Left Right Meaning 1 3 2 0 Turns 1 and 3 (by P1) are blocked by either Turn 2 or 4 4 4 1 3 Turns 2 and 4 (by P2) are blocked by Turn 5 5 6 0 4 Turn 6 blocks one of Turns 1,5 or Turns 3,5, and Turn 7 completes the other 5 6 4 2 ↑ ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 72 bytes ``` g←{⍵,⍨1⌽@(∊∘⍺)¨⍵} 7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9 ``` [Try it online!](https://tio.run/##lZC/SsNQFMZn8xRnTDCFe/O/gqCTOIiCg67VJjFYEmkLbREXhZpGr9RBcXGwDgZXdRFc8ijnReJJGm2HIjjk5J7f@b6Pe27jpFVrDhqtyK@5/a4bNt1mjjd3m9s4HDMJxSPs8BVohIPekdt2Qa4rU6jNQ0dZoOTLlqICh8ADtx90ukHokw0OWtHhcQeC7oIcS4GoPVVQmMxnsRXTfpn2w6LQhcgjUQdkbWboBWGpjS@93KddTlF8qChSjtdfazLGCcYPKD6VLKXBmWTj8JbWxuQC4xcUV1lqguWrWSpjco7iTVfI84rJRCV/lqqY3Jd1UsQUREHxjKMnDrpPDh10FO@UZoAFjj/NqOd0m3zJk5hEhRdFK4plGyVgjFX/EnNbsyVGD6iBDg4YYM51JhhVZ4BNxJToo94hwsCWirNFE6PQV51DOkY@h7hFajrTDEeTf@5YvAz8vejW@v7e7irf@AY "APL (Dyalog Extended) – Try It Online") Decided to post as a separate answer, because the approach is drastically different. Inspired from [orion's comment](https://codegolf.stackexchange.com/questions/48824/optimal-games-of-tic-tac-torus/206815#comment115295_48824), this one generates all optimal games by transforming a single game board in various ways. The 3x3 toroidal board is *very very* permissive on its transformations; the three-in-a-rows are preserved through reflection, rotation (e.g. cycling the top row to the bottom), and [shear](https://en.wikipedia.org/wiki/Shear_mapping) (e.g. cycling elements of each row 0, 1, 2 units to the right respectively). With this information, I could identify *four* seed boards that have distinct topology (using 0 to 6 to denote the seven moves made in sequence): ``` P2#4 not forced 0 1 2 0 1 2 3 6 5 3 5 6 x x 4 x x 4 P2#4 forced 0 3 2 0 3 2 1 6 5 1 5 6 x x 4 x x 4 ``` Then I tried various combinations of the transformations to find a short one that generates all 1728 boards. And I noticed that even the seed boards can be generated from *one* board, by swapping the positions of 1-3 (decides whether the 4th move is forced) and 5-6 (swap a block and a win). ### How it works ``` ⍝ Helper function g←{⍵,⍨1⌽@(∊∘⍺)¨⍵} 1⌽@(∊∘⍺)¨⍵ ⍝ Cycle the positions of ⍺s in each of ⍵ ⍵,⍨ ⍝ Prepend the above to ⍵ ⍝ Main program 7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9 3 3⍴⊃4 6 8g⊂⍳9 ⍝ Generate the seed board: 0 1 2 3 6 5 8 7 4 5 6g 1 3g ⍝ Generate four seed boards from the above, ⍝ by swapping the numbers 1-3 and 5-6 (⊂⍳3)(...)⍣≡ ⍝ Repeat certain transformations until all are found: ⊢∘⌽¨ ⍝ Reverse the order of columns: a b c c b a d e f → f e d g h i i h g ⊖¨, ⍝ Join with vertical shear: a b c a e i d e f → d h c g h i g b f ⌽¨, ⍝ Join with horizontal shear: a b c a b c d e f → e f d g h i i g h ∪⊢, ⍝ Join with original and take unique results ⍋¨,¨ ⍝ Flatten each 3x3 matrix and extract where each number is ∧ ⍝ Ascending sort ⎕⊃ ⍝ Take input n and pick nth result 7↑ ⍝ Take first 7, since the last two are garbage ``` [Answer] # Octave, 467 369 363 309 297 characters **297:** ``` global t=0*(1:9)m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48 a; function g(s,p)global a t m; if nnz(s)<8&&any((t==1)*m>2)a=[a;s];return;end;q=t==3-p; (r=sort(~q.*(1:9)*m(:,find([3 1]*([q;t==p]*m)==6)')))||(r=find(~t)); for i=r t(i)=p;g([s i+47],3-p);t(i)=0;end;end;g('',1);f=@(n)a(n+1,:); ``` The only relevant change is that **we never check if the current player can win, only check the opponent's possibility to win the next turn**. As **the only turn the player 1 can win is turn 7**, this is the only place when the algorithm would produce game that is not optimal, but it's very easy to filter such a situation out. We simply verify each game generated if it's won by player 1 - if it was not, the move in turn 7 was incorrect, so we don't add this game to optimal games table. (Exactly half the games generated by this rule are false *ie.* in the 7th turn the player 1 always has two possibilities to block player two, but only one will make him win instantly). Use: ``` $ octave octave:1>> source script.m octave:2>> f(634) ans = 3270148 ``` The ungolfed code looks like: ``` global t=0*(1:9); global m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48; global allgames; allgames=[]; function r=canbewon(by) global t m q=[t==by;t==(3-by)]*m; g=(find([3 1]*q==6))'; r=sort((~(t==by).*(1:9)) * m(:,g)); end function games_starting_with(s) global allgames t; if 7==numel(s) && any((t==1)*m==3) # it's 7th move and first player won allgames=[allgames;s]; return; end; poss=(find(~t)); # for now all free slots are possible player=1+mod(numel(s),2); moves = canbewon(3-player); if numel(moves) poss=moves; end; # ... no, we must block the other player for i=poss t(i)=player; games_starting_with([s char(i+47)]); t(i)=0; end end games_starting_with(''); f=@(n)(allgames(n+1,:)); ``` ]
[Question] [ I need to go to the bank and withdraw some money. I need to withdraw $30, $22 to pay my roommate for the internet and $8 for laundry. Since neither of these can make change, I need my $30 to be split into two partitions of the two sizes. That means when the teller asks me how I want my $30 I am going to have to make a request. I could tell them I want it in a twenty, a fiver, and five ones. But I want to make my request as simple as possible as to avoid having to repeat myself. To make my request simpler I could ask that my cash contain a twenty and at least 2 ones because the 8 is implied by the total, but better yet I could simply request that one of the bills I receive be a one dollar bill (If you are not convinced of this just try to make 29 dollars without making 8). So that's all fine and dandy but I need to do this calculation every time I go to the bank so I thought I would write a program to do this (have you write a program to do this for me). Your program or function should take a list of integers representing all the payments I need to make and a set of integers representing the denominations of bills available at the bank, and you must output the smallest list of denominations such that every way to make the total that includes that list of denominations can be cleanly divided into the list of payments. **Extra rules** * You may assume that the denomination list will always contain a `1` or you may add it to each list yourself. * Some inputs will have multiple minimal solutions. In these cases you may output either one. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. ### Test Cases ``` Payments, denominations -> requests {22,8} {1,2,5,10,20,50} -> {1} or {2} {2,1,2} {1,5} -> {1} {20,10} {1,2,5,10,20,50} -> {} {1,1,1,1} {1,2} -> {1,1,1} {20,6} {1,4,5} -> {1} {2,6} {1,2,7} -> {2} {22, 11} {1, 3, 30, 50} -> {1, 3} {44, 22} {1, 3, 30, 50} -> {1, 3, 3, 30} ``` [Answer] # JavaScript (ES6), ~~485~~ 476 bytes Alright ... this is a monster. :-( But it's a rather fast monster that solves all test cases almost instantly. I may attempt some more advanced golfing later, but I've already spent far too much time on it. ``` f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L]) ``` ### Test cases ``` f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L]) console.log(JSON.stringify(f([22,8], [1,2,5,10,20,50]))) console.log(JSON.stringify(f([2,1,2], [1,5]))) console.log(JSON.stringify(f([20,10], [1,2,5,10,20,50]))) console.log(JSON.stringify(f([1,1,1,1], [1,2]))) console.log(JSON.stringify(f([20,6], [1,4,5]))) console.log(JSON.stringify(f([2,6], [1,2,7]))) console.log(JSON.stringify(f([22,11], [1,3,30,50]))) console.log(JSON.stringify(f([44,22], [1,3,30,50]))) ``` ### How? *NB: This is not matching the current version anymore, but is much easier to read that way.* ``` // b = list of payments, a = list of bills, // L = list from which the requested bills are chosen f = (b, a, L = [...a]) => ( // U = helper function that computes the sum of an array U = a => ~~eval(a.join`+`), // P = function that computes the summed Cartesian products of arrays of integers // e.g. P([[[1,2],[3,4]], [[10,20],[30,40]]]) --> [[33,44], [13,24], [31,42], [11,22]] P = (e, C = [], R = []) => e[0].map(v => R = (c = v.map((x, i) => x + (C[i] | 0)), e[1]) ? [...P(e.slice(1), c), ...R] : [c, ...R] ) && R, // G = function that takes a target amount and a list of requested bills and returns // all combinations that contain the requested bills and add up to this amount; // each combination is translated into a list of number of bills such as [2,0,0,1,0] G = (n, l) => ( S = [], g = (n, l) => n ? a.map(x => x < l[0] | x > n || g(n - x, [x, ...l])) : S = [l.map(v => s[a.indexOf(v)]++, s = [...a].fill(0)) && s, ...S] )(n, l) && S, // compute X = list of possible bill combinations to process all payments X = P(b.map(a => G(a, []))), // compute the powerset of L and sort it from shortest to longest list L.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]]) .sort((a, b) => a[b.length] || -1) .find(L => ( // compute Y = list of possible combinations to reach the total amount, // using the requested bills Y = G(U(b) - U(L), L.sort((a, b) => a - b)), // exit if Y is not empty and all combinations in Y allow to generate all payments Y[0] && !Y.some(a => X.every(b => b + '' != a))) ) // if no solution was found, enlarge the set of requested bills and try again || f(b, a, [...a, ...L]) ) ``` [Answer] # [Python 2](https://docs.python.org/2/), 456 455 bytes **Extremely, extremely, extremely slow!!!!** Should work correctly on all the input examples given enough time **Edit:** Saved 1 byte thanks to [@Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) ``` def F(p,d):v=sum(p);E=enumerate;l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x];Q=l(v,d);m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p;f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v;print-(all(map(m,Q))-1)*min(map(f,Q),key=len) ``` [Try it online!](https://tio.run/##TZDNbsMgEIRfheMSr6s6Ui9Y5JbcIx8RqmiNFWwgluNE8PQuOM3PbWdY5hsY43w6@@2ytLojBxixpezGL1cHI633XPur05OadW25Ve6nVSRgZFFUTCrfQtjxKMoqz2IoxDrL7jyRgRhPLIRytTBSWSSFUbAkaVp4U0kKUclNkPWRW7ilDrV7w3HxKTdW@1SJBZJQxKkADkJugUIVIS@A4bynmW1QZfoeEnU1evx@GBkdOR/r7gU4cSEfwcaDaMg95XK/FNaMJotTIS4Su0RmRiasKXKD1aWmI8pacGoEh52xs57gHzGwfDJ8/J6vfoae7njznNd@ObuheKSUShx05Om1@VfSp9zqcTJ@LuEVntbKim5y12x0yXheWg4gtljhViIRFX5JuvwB) ## Explanation ``` p,d=input() # Read input v=sum(p) # Save a byte by keeping track of the total money withdrawn E=enumerate # We use enumerate a lot # Generates the possible combinations of denominators that add up to the withdrawn amount l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x] # We use the list generated by l quite a few times Q=l(v,d) # Checks if we can divide a list of denominators x in such a way that we get the wished division of the money m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p # For a list of denominators, it tries all possible combinations of the denominators as input to the teller, selecting the one with minimum length f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v # Call f with all possible lists of denominators, and check if saying nothing to the teller will work print-(all(map(m,Q))-1)*min(map(f,Q),key=len) ``` ]
[Question] [ # Introduction Given an ASCII tower and the force of the wind, write a program or function to determine if the tower will balance or which way it will fall. For example the first tower balances but the second falls over toward the left. ``` # # # # ### ### ### ### # # # # ##### ##### ### ### ### # ``` This is my first challenge. I hope you enjoy it. # Directions The tower consists of connected blocks represented by `#` and forms a [rigid object](https://en.wikipedia.org/wiki/Rigid_body). Each block is a square with a width and height of one unit and has a constant density. There are two forces that act on the tower, its weight and the wind force. All forces act on each block individually and pass through the center of the block. * Due to its weight, each block has a downward force of one unit acting on it. * Also, each block *that does not have another block adjacent to it on its windward side* has a force on it acting horizontally in the direction of the wind. The magnitude of this force is given as an input. * The direction of the wind is indicated by an ASCII flag somewhere in the input. There will be a flag in the input if and only if the wind is not zero. The flag does not affect any forces. The flag will look exactly as it appears below. ``` Flag design and corresponding wind direction: o~~ ~~o |~~ ~~| ---> <--- ``` To clarify, the tower is a solid object and will not break apart and is not attached to the ground. However, your program should calculate the forces for each block individually to determine whether the tower balances. # Example ``` o~~ |~~ # # > > ### >## ### >## # # > > ##### >#### ### >## ### >## Wind force: 1 Wind direction: ---> ``` The wind is blowing right and will push on the blocks shown with a `>` on the above right. Note that the wind acts on the inside of holes. Assume the lower left corner of the tower has coordinates `(0,0)`. The moment around the left base of the tower at `(0,0)` is 71 units clockwise so the tower will not fall left. The moment around the right base of the tower at (0,3) is 8 units clockwise so the tower will fall right. If the wind was blowing toward the left, the respective moments would be 2 units clockwise and 61 units counterclockwise at the same points, so the tower would balance. # Input * Your program or function must take two inputs, a decimal number and a newline-separated string. * The decimal number will be greater than zero and represents the force exerted by the wind on each exposed block as in the example. * The string will represent the tower from top to bottom and may contain spaces, `#|o~` characters, and newlines. You may optionally assume a trailing newline and/or pad the tower with trailing spaces to form a rectangle. * The tower will have at least one `#` on the bottom row. * You may input the number and string in either order. * If the magnitude of the wind force is non-zero, there will be a flag somewhere in the input, either on the ground or connected to the tower. The flag will have the exact form shown above. * The `#` blocks will form a connected shape that may contain holes. In other words, all blocks will be adjacent to another other block unless there is only one block. # Output * One of the characters `B`, `L`, or `R`, depending on whether the tower will balance, fall towards the left (counterclockwise), or fall towards the right (clockwise). * The output may have an optional trailing newline. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); standard rules and loopholes apply. # `B` Test Cases: ``` Wind: 1 ~~o ~~| # # ### ### # # ##### ### ### Wind: 0 ## # ## ### Wind: 1.7 o~~ |~~ # ## Wind: 0.768 o~~ |~~ # # ### ### # # ##### ### ### Wind: 0.1 # # # # # # o~~ # |~~ Wind: 0 # Wind: 0 ############ Wind: 144 o~~ ############ |~~ Wind: 0 ####### ## # ## Wind: 0 ############ ############ ############ ############ ############ ############ ############ Wind: 41 ############ ############ ############ ############ ############ ############ ~~o ############ ~~| ``` # `L` Test Cases: ``` Wind: 0 ##### # Wind: 42 ############ ############ ############ ############ ############ ############ ~~o ############ ~~| Wind: 4 ######## ### ~~o# ## ~~|# # Wind: 3 ######## ### o~~# ## |~~ # ``` # `R` Test Cases: ``` Wind: 1 o~~ |~~ # # ### ### # # ##### ### ### Wind: 2 o~~ |~~ # Wind: 0.001 ############ ############ ############ ############ ############ ############ o~~ ############ |~~ Wind: 145 o~~ ############ |~~ Wind: 1 # # # # # # o~~ # |~~ Wind: 0.26 ####### ## # o~~ ## |~~ ``` # Reference Solution (JavaScript) [Try it online.](https://jsfiddle.net/intrepidcoder/jfqLeoL8/) ``` function balanced(tower, wind) { var rows = tower.split('\n').reverse(); // Reverse so row index matches height of row. var height = rows.length; var leftEdge = rows[0].indexOf('#'); // Find bottom left corner of tower. var rightEdge = rows[0].lastIndexOf('#') + 1; // Find bottom right corner of tower. var leftMoment = 0, rightMoment = 0; // Moments around the bottoms corners of tower. wind *= tower.indexOf('~o')>-1 ? -1 : 1; // Find direction of the wind. // Sum the moments for each block in the tower. for (var i = height - 1; i >= 0; i--) { rows[i].split('').map(function(ch, index, arr) { if (ch=='#') { // If there's not a block toward the windward side of the current one. if ((wind < 0 && arr[index-1] != '#') || (wind > 0 && arr[index+1]!='#')) { // Add moments from wind. leftMoment += (i+0.5)*-wind; rightMoment += (i+0.5)*-wind; } leftMoment += leftEdge - (index + 0.5); rightMoment += rightEdge - (index + 0.5); } }, 0); } if (leftMoment > 0) return 'L'; else if (rightMoment < 0) return 'R'; else return 'B'; } ``` # Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=62673,OVERRIDE_USER=45393;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # JavaScript (ES6), 239 bytes I golfed down my reference implementation. I was able to save bytes by changing the for loop to a `map`, using `&&` and `||` to short-circuit if statements, and using the `,` operator to fit everything on one statement so as to avoid an explicit return in the function. ``` (a,b)=>((c=a.split` `.reverse(),d=c[f=g=0].indexOf`#`,e=c[0].lastIndexOf`#`+1),a.match`o~`&&(b*=-1),c.map((h,i)=>h.replace(/#/g,(j,k,l)=>(b>0&l[k-1]!='#'|b<0&l[k+1]!='#'&&(f+=(i+=0.5)*b,g+=i*b),f+=d-k-0.5,g+=e-k-0.5))),f>0?'L':g<0?'R':'B') ``` It might still be possible to golf this more. Suggestions are welcome. [Answer] # JavaScript ES6, ~~297~~ 293 bytes Basically a compressed version of the given implementation. ``` b=(n,e)=>{r=n.split` `.reverse(),t=r.length,a=r[0].indexOf`#`,f=r[i=l=0].lastIndexOf`#`+1;e*=n.indexOf`~o`>-1?-1:1;for(d=t-1;d>=0;d--)r[d].split``.map((n,r,t)=>{(j="#")==n&&((0>e&&j!=t[r-1]||e>0&&j!=t[r+1])&&(i+=(d+.5)*-e,l+=(d+.5)*-e),i+=a-(r+.5),l+=f-(r+.5))},0);return i>0?"L":0>l?"R":"B"} ``` Semi-expanded: ``` b = (n, e) => { r = n.split ` `.reverse(), t = r.length, a = r[0].indexOf `#`, f = r[i = l = 0].lastIndexOf `#` + 1; e *= n.indexOf `~o` > -1 ? -1 : 1; for (d = t - 1; d >= 0; d--) r[d].split ``.map((n, r, t) => { (j = "#") == n && ((0 > e && j != t[r - 1] || e > 0 && j != t[r + 1]) && (i += (d + .5) * -e, l += (d + .5) * -e), i += a - (r + .5), l += f - (r + .5)) }, 0); return i > 0 ? "L" : 0 > l ? "R" : "B" } ``` ]
[Question] [ Your task is simple, write a single code snippet that when executed in one language outputs only the string `'abc'` and when executed in another language outputs only the string `'cba'`. The program should take no input. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. [Answer] # MATLAB / Octave, 41 bytes ``` disp(flip('abc',size(randsample(2,2),2))) ``` In MATLAB `randsample(2,2)` gives a 2×1 vector, so `size(...,2)` is `1`. Thus `flip` is applied along the first dimension, which is a singleton, so the original string `'abc'` is displayed: [![enter image description here](https://i.stack.imgur.com/WDtXr.gif)](https://i.stack.imgur.com/WDtXr.gif) In Octave `randsample(2,2)` gives a 1×2 vector, so `size(...,2)` is `2`. Thus `flip` is applied along the second dimension, that is, the string is flipped from left to right: [![enter image description here](https://i.stack.imgur.com/I9I05.gif)](https://i.stack.imgur.com/I9I05.gif) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) / [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` _"abc ``` **[Try 05AB1E online!](https://tio.run/##MzBNTDJM/f8/XikxKfn/fwA "05AB1E – Try It Online")** **[Try Pyth online!](https://tio.run/##K6gsyfj/P14pMSn5/38A "Pyth – Try It Online")** **[This also works in Pyke, outputting `cba`.](https://tio.run/##K6jMTv3/P14pMSn5/38A)** **[This also works in Recursiva, outputting `cba`.](https://tio.run/##K0pNLi0qzixL/P8/XikxKfn/fwA)** [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) and [Bash](https://www.gnu.org/software/bash/), 57 bytes ``` echo cba ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgZNTAURyKXCBCAgbLITG5@RKTc7IV1BITkrk4uL6/x8A "Whitespace – Try It Online") [Answer] # 25 bytes ``` print(1/2and'cba'or'abc') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69Ew1DfKDEvRT05KVE9v0g9MSlZXfP/fwA "Python 2 – Try It Online") ([Python 2](https://docs.python.org/2/)) [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1DfKDEvRT05KVE9v0g9MSlZXfP/fwA "Python 3 – Try It Online") ([Python 3](https://docs.python.org/3/)) [Answer] # Vim / Notepad.exe, 10 bytes ``` cbaabc<esc><backspace><backspace><backspace> ``` [Answer] -1 byte if I make `==0` into `>0` but that's already another answer # [Python 2](https://docs.python.org/2/), 26 bytes ``` print('acbbca'[1/2==0::2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQz0xOSkpOVE92lDfyNbWwMrKKFbz/38A "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 26 bytes ``` print('acbbca'[1/2==0::2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQz0xOSkpOVE92lDfyNbWwMrKKFbz/38A "Python 3 – Try It Online") `1/2` gives `0` (floordiv) in Python 2 and `0.5` (truediv) in Python 3. Thus, `1/2==0` gives 1 in Python 3 and 0 in Python 2 (actually, booleans, but those are just integers), so `'acbbca'[1::2] => 'cba'` is given for Python 3 and `'acbbca'[0::2] => 'abc'` is given for Python 2. [Answer] # Excel / Google Sheets, ~~41~~ ~~28~~ ~~27~~ 24 Bytes Anonymous worksheet formula that takes no input and outputs `"ABC"` to the calling cell in Excel and `"CBA"` to the calling cell in Google Sheets ``` =IfError(M("CBA"),"ABC") ``` In Google Sheets, `M(...)` is an alias for and autoformatted to `T(...)` (short for `Text()`). This call returns the text value of the passed variable, `"CBA"`. `"CBA"` is not caught as an error, so `"CBA"` is returned by `IfError(...,"ABC")` In Excel, there is no `M(...)` function, and `M(...)` is not an alias and therefore `M("CBA")` returns the formula not found error, `#NAME?`. This is caught by `IfError(...,"ABC")`, which in turn returns `"ABC"`. --- ## Previous Versions, 27, 28, 41 Bytes See edits for explanations ``` =If(IsErr(A()),"ABC","CBA") ``` ``` =If(IsErr(GT()),"ABC","CBA") ``` ``` =IfError(If(Info("NUMFILE"),"ABC"),"CBA") ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/) / [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` "abc"R ``` Try it online: * [CJam](https://tio.run/##S85KzP3/XykxKVkp6P9/AA); * [05AB1E](https://tio.run/##MzBNTDJM/f9fKTEpWSno/38A). ### How it works in CJam ``` "abc" Push this string R Push variable R, predefined to the empty string Implicitly display stack ``` ### How it works in 05AB1E ``` "abc" Push this string R Reverse Implicitly display top of the stack ``` [Answer] With apologies to @HyperNeutrino for stealing most of his answer (I don't have the reputation to comment yet) # [Python 2](https://docs.python.org/2/), 25 bytes ``` print('acbbca'[1/2>0::2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQz0xOSkpOVE92lDfyM7AysooVvP/fwA "Python 2 – Try It Online") # [Python 3](https://docs.python.org/3/), 25 bytes ``` print('acbbca'[1/2>0::2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQz0xOSkpOVE92lDfyM7AysooVvP/fwA "Python 3 – Try It Online") [Answer] # JavaScript (NodeJS) and PHP, 46 bytes ``` <!-- strrev=console.log//--><?= strrev("abc"); ``` Prints `abc` in JS and `cba` in PHP. [Try the JS online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f/fRlFXl6u4pKgotcw2OT@vOD8nVS8nP11fX1fXzsbeFiqloZSYlKykaf3/PwA) [Try the PHP online!](https://tio.run/##K8go@P/fRlFXl6u4pKgotcw2OT@vOD8nVS8nP11fX1fXzsbeFiqloZSYlKykaf3/PwA) (note that TIO doesn't hide the HTML comments (`<!--`...`-->`) [Answer] # [Python 2](https://docs.python.org/2/) and Python 3, 42 bytes ``` try:exec("print'abc'") except:print('cba') ``` [Try it online! (Python 2)](https://tio.run/##K6gsycjPM/r/v6So0iq1IjVZQ6mgKDOvRD0xKVldSZMrtSI5taDECiymoZ6clKiu@f8/AA "Python 2 – Try It Online") [Try it online! (Python 3)](https://tio.run/##K6gsycjPM/7/v6So0iq1IjVZQ6mgKDOvRD0xKVldSZMrtSI5taDECiymoZ6clKiu@f8/AA "Python 3 – Try It Online") Thought I'd try something different... [Answer] # Excel/Google Sheets, 28 bytes Inspired by @TaylorScott, who used a function that only exists in Excel, I found an even shorter function that only exists in Google Sheets. Conveniently, it is designed to return strings: ``` =iferror(join(,"cba"),"abc") ``` **How it works** In Google Sheets, `join([arg1], arg2, arg3,...argk)` will concatenate *arg2* -> *argk*, optionally using the separator specified in *arg1*. In this case, it successfully returns "cba." Excel has no `join` function, so `iferror` sees a problem and returns "abc" [Answer] # Python / Befunge, ~~20~~ 18 bytes *2 bytes saved thanks to @karhell* ``` print("abc")# ,,,@ ``` [Try it online! for Python](https://tio.run/##K6gsycjPM/7/v6AoM69EQykxKVlJU1lBR0fH4f9/AA) Python sees `print("abc")` then a comment. [Try it online! for Befunge](https://tio.run/##S0pNK81LT/3/v6AoM69EQykxKVlJU1lBR0fH4f9/AA) Befunge, removing all nops and useless commands sees `"abc",,,@` which puts `a`, `b` and `c` on the stack and then prints them (last in - first out). [Answer] # Python 2 / Python 3, 28 bytes ``` print('abc'[::int(1/2*4)-1]) ``` In Python 2 `int(1/2*4)-1` evaluates to `-1` and so prints `cba`. - [TiO](https://tio.run/##K6gsycjPM/r/v6AoM69EQz0xKVk92soKxDbUN9Iy0dQ1jNX8/x8A) In Python 3 it evaluates `1` so prints `abc`. - [TiO](https://tio.run/##K6gsycjPM/7/v6AoM69EQz0xKVk92soKxDbUN9Iy0dQ1jNX8/x8A) [Answer] # [R](https://www.r-project.org/)/[Cubix](https://github.com/ETHproductions/cubix), 20 bytes ``` cat("abc")#u@o;o;o(; ``` [R - Try it online!](https://tio.run/##K/r/PzmxREMpMSlZSVO51CHfGgg1rP//BwA "R – Try It Online") [Cubix - Try it online!](https://tio.run/##Sy5Nyqz4/z85sURDKTEpWUlTudQh3xoINaz//wcA "Cubix – Try It Online") For R, `cat("abc")` then shameless abuse of comments. For Cubix ``` c a t ( " a b c " ) # u @ o ; o ; o ( ; . . . . ``` * `"abc"` Pushs a, b ad c onto the stack * `)#` Increment the c, pushs number of element in stack * `u` U-turn to the right * `;(` Remove the count, Decrement the c * `o;o;o@` Output cba and exit Pushs the number on in stack [Answer] # [CJam](https://sourceforge.net/p/cjam) and [Gaia](https://github.com/splcurran/Gaia), 8 bytes ``` 'c'b'a]$ ``` [Try it in CJam!](https://tio.run/##S85KzP3/Xz1ZPUk9MVbl/38A "CJam – Try It Online") [Try it in Gaia!](https://tio.run/##S0/MTPz/Xz1ZPUk9MVbl/38A "Gaia – Try It Online") ### Explanation In both languages this defines a list of characters. In CJam, `$` is sort, so it becomes `abc`. In Gaia, `$` joins the list into one string, giving `cba`. [Answer] # Java 8 & C, 95 bytes ``` //\ interface a{static void main(String[]s){System.out.print("abc"/* main(){{puts("cba"/**/);}} ``` [Try it in Java 8 - resulting in "abc".](https://tio.run/##HcpBCoAgEADAe68QTxqUD@gZHavDZhZrpJJbEOLbLboOY@GGxgfj7LKXotRYoSNzrqANgxQJCDW7PS7sAHSipxPdNkxRpv6JZI7WX9SGD0lwmDVXdfVHmVK4KAquZ/iwVrLLuZQX) [Try it in C - resulting in "cba".](https://tio.run/##HcpBCoAgEADAe68QTxqUD@gZHqvDupkslEVuQUhvt@g6DDa4QAylGDNUFNkfM6AXkBMDE4pro0msQFFZPiiGfkw62zuxX9vt5Hb/kJUEh9LU1R91zvvJSUl08GFtdPc8pbw) **Explanation:** ``` //\ interface a{static void main(String[]s){System.out.print("abc"/* main(){{puts("cba"/**/);}} ``` As you can see in the Java-highlighted code above, the first line is a comment due to `//`, and the C-code is a comment due to `/* ... */`, resulting in: ``` interface a{static void main(String[]s){System.out.print("abc");}} ``` --- ``` //\ interface a{static void main(String[]s){System.out.print("abc"/* main(){{puts("cba"/**/);}} ``` Not sure how to correctly enable C-highlighting, because `lang-c` results in the same highlighting as Java.. But `//\` will comment out the next line, which is the Java-code, resulting in: ``` main(){{puts("cba");}} ``` [Answer] # C and C++, ~~115~~, ~~78~~, ~~58~~, 56 bytes ``` #include<stdio.h> main(){puts(sizeof('x')>1?"abc":"cba");} ``` 78 bytes, thanks to [challenger5](https://codegolf.stackexchange.com/users/61384/challenger5). 58 bytes, thanks to [aschepler](https://codegolf.stackexchange.com/users/18653/aschepler). 56 bytes, thanks to [hvd](https://codegolf.stackexchange.com/users/16385/hvd) [Try it - C++!](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCXVprgkJTNfL8OOKzcxM09Ds7qgtKRYozizKjU/Tb1C3c7QXikxKVnJSik5KVFJ07r2/38A "C++ (gcc) – Try It Online") [Try it - C!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djis3MTNPQ7O6oLSkWKM4syo1P029Qt3O0F4pMSlZyUopOSlRSdO69v9/AA "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) 2.0/JavaScript, ~~11~~ 10 bytes ``` "abc" //Uw ``` [Japt 2.0](https://ethproductions.github.io/japt/?v=2.0a0&code=ImFiYyIKLy9Vdw==&input=) outputs `cba` [JavaScript](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@18pMSlZiUtfP7T8f3J@XnF@TqpeTn66RprmfwA) outputs `abc` [Answer] # [Vyxal/Hexagony](https://github.com/Lyxal/Vyxal), 19 bytes ``` ka3wiṘ,Qλa;b@;<λ;c/ ``` [Try it Online! (Vyxal)](https://lyxal.pythonanywhere.com?flags=&code=ka3wi%E1%B9%98%2CQ%CE%BBa%3Bb%40%3B%3C%CE%BB%3Bc%2F&inputs=&header=&footer=) [Try it Online! (Hexagony)](https://hexagony.net/#lzN4Igxg9gJgpiBcIDWBDAzAdwJaA08ANAIqDdwCgNwBGAAqQDxGlgD0IeIWAdgA4CuALgiACMAJjQAWAKwA2AOwAOAJws2XPgFlocRCgBOAcxABfIA===) The program is split into two main parts, `ka3wiṘ,Q` and `λa;b@;<λ;c/`. The first half is just basic Vyxal to print "cba" (though I cannot use `cba` because it messes with Hexagony's layout). The second part worked out really nicely, because in order to print in Hexagony, a semicolon is required, but in Vyxal, an unmatched semicolon gives an error. So to fix this, I use lambdas in order to match them, and it just so happened to fit into an exact 3x3 hexagon. Luckily, in Hexagony almost any character that isn't special is taken as its codepoint, so the lambda character is quickly overwritten by anything else that comes after it. [![](https://i.stack.imgur.com/elqLs.png)](https://i.stack.imgur.com/elqLs.png) The lambdas are placed so each one proceeds a semicolon, even if they aren't used in the hexagony code (as indicated by the blue trail). [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` print('abc'[::-(1/2>0)|1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQz0xKVk92spKV8NQ38jOQLPGMFbz/38A "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), 26 bytes ``` print('abc'[::-(1/2>0)|1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQz0xKVk92spKV8NQ38jOQLPGMFbz/38A "Python 2 – Try It Online") [25-byte version with `exit` instead](https://tio.run/##K6gsycjPM/r/P7Uis0RDPTEpWT3aykpXw1DfyM5As8YwVvP/fwA), which outputs to STDERR instead. This is basically the same as `print('abc'[::[1,-1][1/2>0]])`, just that it's golfed. [Answer] # [Python 2](https://docs.python.org/2) and [Foo](https://esolangs.org/wiki/Foo), 16 bytes ``` print"abc"[::-1] ``` ## Python 2 ``` print"abc"[::-1] ``` [Try Python 2 online!](https://tio.run/##K6gsycjPM/r/v6AoM69EKTEpWSnaykrXMPb/fwA "Python 2 – Try It Online") ### Explanation ``` print"abc"[::-1] print # print... (duh) "abc" # the string "abc"... [::-1] # backwards ``` ## Foo ``` "abc" ``` [Try Foo online!](https://tio.run/##S8vP//@/oCgzr0QpMSlZKdrKStcw9v9/AA "Foo – Try It Online") ### Explanation ``` "abc" "abc" print the string "abc" ``` [Answer] # C (gcc) C++ (g++), 59 bytes ``` #include<stdio.h> main(){puts("abc\0cba"+(sizeof(' ')&4));} ``` [Answer] # [Fission](https://github.com/C0deH4cker/Fission) / [><>](https://esolangs.org/wiki/Fish) , 11 bytes ``` !R"abc"ooo; ``` [Try Fission Online](https://tio.run/##S8ssLs7Mz/v/XzFIKTEpWSk/P9/6/38A) In Fission, a particle starts at `R` and prints `abc`. [Try ><> Online](https://tio.run/##S8sszvj/XzFIKTEpWSk/P9/6/38A) In ><>, the IP starts at the top-left. `!` skips the next instruction, and `"abc"` pushes [a,b,c] on the stack. `ooo` then pops and prints three times, giving `cba`. Both programs end at `;` [Answer] # [Ly](http://esolangs.org/wiki/Ly) / [><>](https://esolangs.org/wiki/Fish), ~~20~~ 19 bytes ``` "abc"&&ov ; oo< ``` [Try it with ><>!](https://tio.run/##S8sszvj/XykxKVlJTS2/jMtaAQTy823@/wcA) [Try it with Ly!](https://tio.run/##y6n8/18pMSlZSU0tv4zLWgEE8vNt/v8HAA) These languages are very similar, as Ly is based off ><>. However, Ly does not have 2D execution and interprets `&` differently, which I took advantage of here. Both languages will start by pushing `abc` to the stack. For ><>, the `&` instruction moves values to and fro the register. Two in a row will push a value to the register and then take it straight back, essentially a NOP. For Ly, `&` is a modifier that makes an instruction perform its function on the entire stack. `o` means the same thing for both languages, but since it is modified by `&` in Ly, it will print the whole stack, outputting `abc`. In ><>, it will only output `c` (as it is printed from the top down) `v` is a NOP in Ly, which skips it and goes straight to `;`, ending execution. ><> will instead treat it as a pointer, sending the IP downwards. It then hits another arrow, sending the IP left. Here, it meets two `o` signs, outputting `b` and `a`. EDIT: Saved a byte (and fixed ><> crashing) [Answer] # CJam and ><>, 12 bytes ``` "ooo;abc "4> ``` ## What CJam sees: ``` "ooo;abc " ``` String literal, which pushes the string `ooo;abc` (with a trailing newline) to the stack. ``` 4> ``` Slice off the first four characters of the string, leaving `abc`, which is output. ## What ><> sees: ``` " ``` Begins a string literal. ``` ooo;abc ``` Forms the contents of the string literal. The character codes of the characters in the string are pushed to the stack in reverse order (so `c` is on the top). ``` " ``` The IP wraps around, hitting the `"` a second time, which ends the string literal. ``` ooo ``` Outputs the top three characters on the stack: `cba` ``` ; ``` Terminates the program. Neither the `abc` nor any part of the second line is executed. ## Solution with Error: 8 bytes ``` "abc"oo< ``` What CJam sees ([Try it online!](https://tio.run/##S85KzP3/XykxKVkpP9/m/38A "CJam – Try It Online")): ``` "abc" ``` Push a string literal to the stack. ``` o ``` Output that string literal. ``` o ``` Try to output again. The stack is empty, so the program crashes. ## What ><> sees: ``` "abc" ``` Push three characters onto the stack in reverse order. ``` o ``` Print one character: `c` ``` o ``` Print another character: `b` ``` < ``` Start moving backwards. ``` o ``` Print the last character: `a` ``` o ``` Try to print another character. Since the stack is empty, the program errors. [Answer] # [J](http://jsoftware.com/)/[K (Kona)](https://github.com/kevinlawler/kona), 30 bytes ``` NB. :`0:"ABC" {}[] /.echo'CBA' ``` [TIO - J](https://tio.run/##y/r/389JT8EqwcBKydHJWYmrujY6VkFfLzU5I1/d2clR/f9/AA "J – Try It Online") & [TIO - K kona](https://tio.run/##y9bNzs9L/P/fz0lPwSrBwErJ0clZiau6NjpWQV8vNTkjX93ZyVH9/38A "K (Kona) – Try It Online") [Answer] ## Javascript / Ruby, 27 bytes ``` 0?print('abc'):alert('cba') ``` A shorter version without prints for interpreters (**14 bytes**) : ``` 0?'abc':'cba' ``` \*\*Explanation\*\* *NEW VERSION* `0` is falsy for Javascript but truthy for Ruby, thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) *OLD VERSION*: `''` is falsy for Javascript, but truthy for Ruby. *OLD VERSION*: For Javascript, `[]+[] = ""` as a string concatenation, since the `+` operand is only defined for numbers and strings, and the empty string is evaluated as `false` Meanwhile, in Ruby, you can concatenate array using the `+` operand, and it is evaluated as `true` (first participation in PCG ! :)) [Answer] # [Julia](http://julialang.org/) and [Python 3](https://docs.python.org/3/), 23 bytes ``` print(["abc","cba"][1]) ``` [Try Julia online!](https://tio.run/##yyrNyUw0rPj/v6AoM69EI1opMSlZSUcpOSlRKTbaMFbz/38A "Julia 1.0 – Try It Online") [Try Python online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI1opMSlZSUcpOSlRKTbaMFbz/38A "Python 3 – Try It Online") Julia uses 1-based indexing while Python uses 0-based indexing [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) and [2sable](https://github.com/Adriandmen/2sable), 6 bytes ``` …CBAžR ``` Prints `ABC` (OP said it was allowed) in 05AB1E and `CBA` in 2sable, using the fact that 2sable was similar to 05AB1E but the `žR` was added to 05AB1E after 2sable was abandoned. [Try it online! (05AB1E)](https://tio.run/##MzBNTDJM/f//UcOy5KTEo/uC/v8HAA "05AB1E – Try It Online") [Try it online! (2sable)](https://tio.run/##MypOTMpJ/f//UcOy5KTEo/uC/v8HAA "2sable – Try It Online") ]
[Question] [ Your task: given a number `n`, generate a '+' sign that is `n` characters away from its center. If this is confusing, check out the test cases. Standard methods of input: output must be a string or printed. Standard loopholes apply. ``` Input: 1 Output: + ] 1 away from center `+`. Input: 2 Output: + ] 2 away from center `+`. +++ ] 1 away from center `+`. + Input: 3 Output: + ] 3 away from center `+`. + +++++ + + ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` P+×+N ``` [Try it online!](https://tio.run/nexus/charcoal#@/9@zwbtw9O13@9Z9/@/MQA "Charcoal – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` n=2*input()-1;C='+'.center for c in C(n):print C(n,c) ``` [Try it online!](https://tio.run/nexus/python2#@59na6SVmVdQWqKhqWto7Wyrrq2ul5yaV5JaxJWWX6SQrJCZp@CskadpVVCUmVcCYuoka/7/bwwA "Python 2 – TIO Nexus") [Answer] # JavaScript (ES6), ~~67~~ ~~65~~ ~~63~~ ~~60~~ 59 bytes ``` x=>(v=(` `[r=`repeat`](--x)+`+ `)[r](x))+`+`[r](x*2)+`+ `+v; ``` * 2 bytes saved by replacing two occurrences of `x-1`, the first with `--x` and the second with `x`. * 2 bytes saved thanks to [Kritixi Lithos](https://codegolf.stackexchange.com/users/41805/kritixi-lithos), replacing `"\n"` with ``[newline]``. * 3 bytes saved thanks to [user2428118](https://codegolf.stackexchange.com/users/13486/user2428118), finally helping me to figure out a way to alias the `repeat` in a way that reduced the size. (With honourable mention to [Marie](https://codegolf.stackexchange.com/users/67066/marie) for her efforts, too) * 1 byte saved indirectly thanks to Herman. --- ## Try It ``` f= x=>(v=(` `[r=`repeat`](--x)+`+ `)[r](x))+`+`[r](x*2)+`+ `+v; oninput=_=>o.innerText=f(+i.value) o.innerText=f(i.value=3) ``` ``` <input id=i min=1 type=number><pre id=o> ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` tZv=&+g43*c ``` [Try it online!](https://tio.run/nexus/matl#@18SVWarpp1uYqyV/P@/MQA "MATL – TIO Nexus") ### Explanation with example Consider `n = 3`. ``` t % Implicitly input n. Duplicate % STACK: 3, 3 Zv % Symmetric range % STACK: 3, [1 2 3 2 1] = % Equal, element-wise % STACK: [0 0 1 0 0] &+ % All pair-wise additions. Gives a 2D array % STACK: [0 0 1 0 0; 0 0 1 0 0; 1 1 2 1 1; 0 0 1 0 0; 0 0 1 0 0] g % Logical: convert non-zero to one % STACK: [0 0 1 0 0; 0 0 1 0 0; 1 1 1 1 1; 0 0 1 0 0; 0 0 1 0 0] 43* % Multiply by 43 (ASCII for '+'), element-wise % STACK: [ 0 0 43 0 0; 0 0 43 0 0; 43 43 43 43 43; 0 0 43 0 0; 0 0 43 0 0] c % Convert to char. Char 0 is displayed as space. Implicitly display. % STACK: [' + '; ' + '; '+++++'; ' + '; ' + '] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 13 bytes ``` Nα×+α←↑×+α‖O↘ ``` [Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzGw9P1z638VHbhEdtEyHMhmnv96x/1Dbj/39jAA "Charcoal – TIO Nexus") Uses a different approach from the other Charcoal answer. ### Explanation ``` Nα # Take input and store it in variable α ×+α # α times write a + ← # Go left ↑×+α # α times write a + upwards ``` Now the top left corner is complete, it will look something like this: ``` + + +++ ‖O↘ # Reflect-overlap it in a SE direction ``` The last step is the key to this program, it uses the top-left part of the plus to generate the rest of the plus by reflecting it in the southeast direction (rightwards and downwards). [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~749~~ ~~743~~ ~~666~~ 625 bytes ``` N.Puck,.Page,.Ford,.Ajax,.Act I:.Scene I:.[Enter Puck and Ford]Puck:Listen tothy!Ford:You is the difference betweena cat I.Scene V:.[Exeunt][Enter Page and Ajax]Ajax:You is the difference betweena cat Ford.Scene X:.Page:You is the product ofPuck I.Is you as big as zero?If soyou is the sum oftwice the sum oftwice twice the sum ofa big big cat a cat a cat a cat.If notyou big big big big big cat.Speak thy!Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene X.Page:You is twice the sum ofa big big cat a cat.Speak thy![Exit Page][Enter Puck]Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene V. ``` [Try it online!](https://tio.run/##rVHBasMwDP0V7R582S2XsUMHgTIKhbJRfHAdpfXa2cGWSbOfzywnZVl22A47WLZk6b0nKbSXYXgWm6jPhdioIxbiyfm6EI9v6pqsJqhKsdVokR/7lSX0wOmgbA2cK9kr1yYQWiBHp/6Ow@Wri2AC0AmhNk2DHq1GOCB1iFaBVgl6Qt4x8hWjJXljSFIyA@uQbP6Cx7wT5EuZ25lXtd7VMTXkmqy/ElWAPn2rAAdz5OsDvXuoGgiu/yoL8T2VUGcS2w9/EVUZiQ/LUUsrErZ1xOC3vPnhjG2L6gw8xGXTI0MWPGKN6jvnA@bOR@VrJIhhGsL3GfwudkafFmIo70HOti7/QdVODMP9Jw "Shakespeare Programming Language – Try It Online") With added newlines: ``` N. Puck,. Page,. Ford,. Ajax,. Act I:. Scene I:. [Enter Puck and Ford] Puck:Listen tothy! Ford:You is the difference betweena cat I. Scene V:. [Exeunt] [Enter Page and Ajax] Ajax:You is the difference betweena cat Ford. Scene X:. Page:You is the product ofPuck I.Is you as big as zero? If soYou is the sum ofTwice the sum ofTwice twice the sum ofA big big cat a cat a cat a cat. If notyou big big big big big cat.Speak thy! Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene X. Page:You is twice the sum ofa big big cat a cat.Speak thy! [Exit Page] [Enter Puck] Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene V. ``` Golfed 6 bytes because scene numbers don't have to be consecutive. Golfed some more bytes by applying the tips in the new answers to the [Shakespeare tips question](https://codegolf.stackexchange.com/questions/48855/), **though these golfs aren't reflected in the explanation**. ## (Slightly outdated) explaination SPL is an esolang designed to look like Shakespeare plays. Positive nouns have the value of 1 (here **cat** is used) and negative nouns have the value of -1 (none were used but **pig** is one of them). Adjectives modify a constant by multiplying it by 2. ``` N. ``` Everything until the first dot is the title and doesn't matter. ``` Puck,. row counter Page,. column counter Ford,. input Ajax,. temp ``` The characters are integer variables, each of them also has a stack but I did not need to use that feature. ``` Act I:. Scene I:. ``` Acts and scenes are used as goto labels ``` [Enter Puck and Ford] ``` It's only useful if exactly two characters are on the stage at the same time. ``` Puck:Listen to thy heart! ``` Reads a number and makes Ford remember it. ``` Ford:You is the difference between a cat and I. ``` As you can see Engrish is valid in SPL. This makes Puck's value "the different between a cat and I". But what does it mean? `cat` is a positive noun, so it's `Puck = 1 - Ford`. ``` Scene II:. [Exeunt] ``` Exeunt is just a plural of "exit", and without arguments means that everyone on the stage exits. ``` [Enter Page and Ajax] Ajax:You is the difference between a cat and Ford. ``` It's also `Page = 1 - Ford` but it's spoken by a different actor so `I` would be wrong. Since it's a loop, I can't just copy the value of `Puck`. ``` Scene III:. Page:You is the product of Puck and I. ``` Pretty straightforward by now. `Ajax = Puck * Page`. ``` Is you as big as zero? ``` "as [adj] as" is the `==` operator. ``` If so,you is the sum of the sum of the sum of a big big big big big cat and a big big big cat and a big cat and a cat. ``` If Ajax == 0... "cat" is 1, "big cat" is 2, "big big cat" is 4 and so on. After substituting the simple constants we get "the sum of the sum of the sum of 32 and 8 and 2 and 1" -> "the sum of the sum of 40 and 2 and 1" -> "the sum of 42 and 1" -> "43", which is the ASCII for +. ``` If not,you fat fat fat fat fat cat. ``` else it's just "fat fat fat fat fat cat", so Ajax gets the value of 32, the ASCII for a space. ``` Speak thy mind! ``` This is the command for outputting a character. ``` Ajax: You sum you and cat.Is you as big as Ford?If not,let us return to Scene III. ``` This is a loop construct. "You sum you and cat" increments Page, and `if(Page != Ford) goto Scene III`. The rest of the program uses the same components, so here is a more readable pseudocode version: ``` Scene1: input = [input number]; row = 0 - input + 1; Scene2: col = 0 - input + 1; Scene3: temp = row * col; if(temp == 0){ temp = '+'; }else{ temp = ' '; } putchar(temp); Page = Page + 1; if(Page != Ford) goto Scene3; Ajax = 10; putchar(Ajax); Puck = Puck + 1; if(Puck != Ford) goto Scene2; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṬŒB»þ`ị⁾+ Y ``` [Try it online!](https://tio.run/nexus/jelly#ARkA5v//4bmsxZJCwrvDvmDhu4vigb4rIFn///8z "Jelly – TIO Nexus") [Answer] ## Mathematica, 39 bytes ``` Print@@@(CrossMatrix[#-1]"+"/. 0->" ")& ``` `CrossMatrix` is a built-in that generates a matrix of the required shape with `1`s instead of `+`s and `0`s instead of spaces. If we multiply that matrix by `"+"`, that replaces the `1`s with `+`s while leaving the `0`s unchanged (obviously... `0*x = 0` and `1*x = x`, right?). Then we replace the zeros manually with spaces using `/. 0->" "`. Finally, we print each line of the matrix with `Print@@@(...)`. [Answer] # C, 69 bytes Not very interesting... Loops over the square, printing out the appropriate character. ``` r,c;f(n){for(r=-n;++r<n;puts(""))for(c=-n;++c<n;putchar(r*c?32:43));} ``` [Answer] # Ruby, ~~41~~ 40 bytes ``` ->x{puts k=[?\s*(r=x-1)+?+]*r,?+*r+=x,k} ``` [Try it online!](https://tio.run/nexus/ruby#S7ON@a9rV1FdUFpSrJBtG20fU6ylUWRboWuoqW2vHatVpGOvrVWkbVuhk137X8NQT89UUy83sUBBLe0/AA "Ruby – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` n=input()-1 p=(' '*n+'+\n')*n print p+'++'*n+'+\n'+p ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioalryFVgq6GuoK6Vp62uHZOnrqmVx1VQlJlXolAAFNCGi2sX/P9vDAA "Python 2 – TIO Nexus") A 53-byte alternative ([TIO](https://tio.run/nexus/python2#@59nm5lXUFqioalryJWWX6SQrJCZp66grpWnrQ6CIJZVQVFmXolCMlQMSP//bwwA "Python 2 – TIO Nexus")): ``` n=input()-1 for c in' '*n+'+'+' '*n:print c*n+'+'+c*n ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~104~~ 99 bytes -5 thanks to [seshoumara](https://codegolf.stackexchange.com/users/59010/seshoumara) Includes +1 for `-r` ``` s/1//;h;:;s/(.*)1/ \12/;t;s/( *2)2(2*)/\1\n\1\2/ t;G;s/1+/&&1/;s/(.*)(\n1*)/&\n\1/;/1/!c+ y/12/++/ ``` Takes input in [unary.](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top) [Try it online!](https://tio.run/nexus/sed#LYw7DoMwEER7TgEN8kdkNFtmD5BLWDQ0UMRE2A2Xj7MRFFOM5s1rBQR01acWuEfwRJ8o0Gp9dn0QL06CR2LKFsG7q/qykRHjSNw3lzIvSv4c1LTDErsTJosRrZH87p@67bm06fgB "sed – TIO Nexus") ``` s/1// # Subtract 1 from input h # Hold onto input : # Start loop s/(.*)1/ \12/ # Remove a 1, prepend a space, and append a 2 t # Loop until all 1s are 2s # Start Loop (uses the previous label) s/( *2)2(2*)/\1\n\1\2/ # Shift all but the first 2 from the last line to a new line # E.g. " 2" " 2" # " 222" -> " 2" # " 22" t # Loop until all 2s are on their own line G # Append a newline and input s/1+/&&1/ # Double the number of 1s and append an extra s/(.*)(\n1*)/&\n\1/ # Copy all of the lines with 2s to the end /1/!c+ # If there aren't any 1s print a '+' y/12/++/ # Convert all 1s and 2s to +s ``` [Answer] **R, 54 bytes** Shaving off 7 bytes thanks to @Jarko Dubbeldam: ``` function(n){a=matrix("",y<-n*2-1,y);a[n,]=a[,n]="x";a} ``` previous answer: ``` f=function(n){a=matrix("",n*2-1,n*2-1);a[n,]="x";a[,n]="x";a} ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes ``` param($n)($x=,(" "*--$n+"+")*$n);'+'*(1+2*$n);$x ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6mhUmGro6GkoKSlq6uSp62kraSpBRS2VtdW19Iw1DYCc1Qq/v//bwIA "PowerShell – TIO Nexus") Takes input `$n`. Starts by constructing a string of `--$n` spaces, concatenated with `+`. That's converted into an array using the comma operator, (newly-decremented) `$n` times. That array is stored in `$x` and encapsulated in parens to place a copy on the pipeline. We then do the middle section, which is `+` string multiplied out the appropriate number of times. That's left on the pipeline. Finally, we put `$x` on the pipeline again. Those are all left on the pipeline at program completion, and the implicit `Write-Output` inserts a newline between elements. [Answer] # Python 2, 65 bytes ``` lambda n:('g+\n'*~-n+'+'*~-(2*n)+'\ng+'*~-n).replace('g',' '*~-n) ``` [Try it Online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ6Whnq4dk6euVaebp62uDaI1jLTyNLXVY/LSwdw8Tb2i1IKcxORUoFJ1HXUFiOD/gqLMvBKFNA1jTS4Y01TzPwA) [Answer] # Lua ~~113~~, 90 bytes ``` r,w,p=string.rep,io.read(),io.write;s=r(' ',w-1)p(r(s..'+'..'\n',w-1))p(r('+',w*2-1)..'\n')p(r(s..'+'..'\n',w-1)) ``` ``` r,w=string.rep,io.read()d=w*2-1;for a=1,d do print(a~=w and r(' ',w-1)..'+'or r('+',d))end ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` ri_(S*'++a\2*(*_z..e>N* ``` [Try it online!](https://tio.run/nexus/cjam#@1@UGa8RrKWurZ0YY6SloRVfpaeXauen9f@/KQA "CJam – TIO Nexus") ### Explanation This feels a bit suboptimal, but the idea is to superimpose the following two grids: ``` + + + + + ``` ``` +++++ ``` Which gives the desired result. ``` ri e# Read input and convert to integer N. _( e# Duplicate and decrement. S* e# Get a string of N-1 spaces (indentation of the vertical bar). '++ e# Append a + (the vertical bar). a e# Wrap the line in an array. \2*( e# Swap with the other copy of N and compute 2N-1. * e# Repeat the line that many times. _z e# Duplicate the grid and transpose it. ..e> e# Pairwise maximum between the two grids. This superimposes them. N* e# Join with linefeeds. ``` [Answer] # [Perl 5](https://www.perl.org/), 45 bytes 44 bytes of code + `-p` flag. ``` $_=join"+ ",@%=($"x--$_)x$_,"+"x($_*2),@%,"" ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8Sb5uVn5mnpM2lpOOgaquholShq6sSr1mhEq@jpK1UoaESr2WkCZTSUVL6/9@Qy5jLlMsSAA "Perl 5 – TIO Nexus") --- Some similar (but still different) approaches: 48 bytes (47+`-p`): ``` $_=join"+"x($_*2-1).$/,(~~($"x--$_."+\n")x$_)x2 ``` 50 bytes (49+`-n`): ``` $,="+"x($_*2-1).$/;print+(~~($"x--$_."+\n")x$_)x2 ``` [Answer] # CJam, 17 ``` ri(S*_]'+*_ffe>N* ``` [Try it online](http://cjam.aditsu.net/#code=ri(S*_%5D'%2B*_ffe%3EN*&input=3) **Explanation:** ``` ri( read n, convert to int and decrement S* make a string of n-1 spaces _] duplicate it and put the 2 strings in an array '+*_ join the strings with a '+' and duplicate the result ffe> for each pair of characters from the 2 (identical) strings, get the larger character (results in a matrix) N* join the rows with newlines ``` [Answer] # Octave, ~~36~~ 31 bytes Inspired by @LuisMendo 's MATL answer. ``` @(n)' +'(((a=1:n*2-1==n)|a')+1) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaeprqCtrqGhkWhraJWnZaRraGubp1mTqK6pbaj5PzGvWMNU8z8A "Octave – TIO Nexus") Previous answer: ``` @(n)' +'(1+((a=padarray(1,n-1))|a')) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaeprqCtrmGoraGRaFuQmJJYVJRYqWGok6drqKlZk6iuqfk/Ma9Yw1TzPwA "Octave – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 12 bytes ``` F'+}¹·<×)û.c ``` [Try it online!](https://tio.run/nexus/05ab1e#@@@mrl17aOeh7TaHp2se3q2X/P@/MQA "05AB1E – TIO Nexus") **-2 thanks to Emigna.** [Answer] # [Python 2](https://docs.python.org/2/), ~~60,~~56 bytes ``` n=input()-1 z=(' '*n+'+\n')*n print z+'+'*(2*n+1)+'\n'+z ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioalryFVlq6GuoK6Vp62uHZOnrqmVx1VQlJlXolAFFFDX0jACyhhqaqsD5bSr/v83BgA "Python 2 – TIO Nexus") * -4 bytes - thanks to math junkie! [Answer] # JS (ES6), ~~88~~ ~~74~~ 73 bytes ``` x=>(x--,y=y=>(" ".repeat(x)+`+ `).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``) ``` Probably can be golfed more. ``` Snippetify(x=>(x--,y=y=>(" ".repeat(x)+`+ `).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``)) ``` ``` <script src="https://programmer5000.com/snippetify.min.js"></script> <input type = "number"> <pre data-output></pre> ``` [Answer] ## JavaScript (ES6), 60 bytes ``` f= n=>(r=([s,t])=>(s=s.repeat(n-1))+t+s+` `)([r(` +`),r(`++`)]) ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` Outputs two trailing newlines. Alternative formulation, also 60 bytes: ``` n=>(r=a=>(s=a[0].repeat(n-1))+a[1]+s+` `)([r(` +`),r(`++`)]) ``` [Answer] ## Batch, 108 bytes ``` @set p=+ @set l=@for /l %%i in (2,1,%1)do @ %l%call set p= %%p%% %l%echo %p% @echo %p: =+% %l%echo %p% ``` Note: Line 3 ends in a space. [Answer] # PowerShell, 48 Doesn't seem to get shorter than that (and pretty much the same approach as the other solution): ``` ($a=,(' '*($n="$args"-1)+'+')*$n) '+'+'++'*$n $a ``` or ``` ($a=(' '*($n="$args"-1)+'+ ')*$n)+'++'*$n+"+ $a" ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~19~~ ~~18~~ 15 bytes *Golfed 3 bytes thanks to @nmjcman101 by using `.` and `Ò+`* ``` Àé r+À«Ä.MgJxÒ+ ``` [Try it online!](https://tio.run/nexus/v#@3@44fBKhSLtww2HVh9u0fNN96o4PEn7////xgA "V – TIO Nexus") [Answer] ## REXX, 81 bytes ``` arg a b=a*2-1 do i=1 to b if i=a then say copies('+',b) else say right('+',a) end ``` [Answer] # PHP, 68 Bytes ``` for(;$i<$c=-1+2*$m=$argn;)echo"\n".str_pad("+",$c," +"[$m==++$i],2); ``` 83 Bytes ``` for(;$i<($c=($n=$argn)*2-1)**2;)echo$i%$c?"":"\n".!++$k," +"[$k==$n|$i++%$c==$n-1]; ``` [Answer] # MUMPS, 48 ~~50~~ ~~53~~ bytes ``` F i=1-n:1:n-1 W ! F j=1-n:1:n-1 W $C(i&j*-11+43) ``` ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/19269/59642) **Definition:** A positive integer `n` is *almost-prime*, if it can be written in the form `n=p^k` where `p` is a prime and `k` is also a positive integers. In other words, the prime factorization of `n` contains only the same number. **Input:** A positive integer `2<=n<=2^31-1` **Output:** a truthy value, if `n` is *almost-prime*, and a falsy value, if not. **Truthy Test Cases:** ``` 2 3 4 8 9 16 25 27 32 49 64 81 1331 2401 4913 6859 279841 531441 1173481 7890481 40353607 7528289 ``` **Falsy Test Cases** ``` 6 12 36 54 1938 5814 175560 9999999 17294403 ``` Please do not use standard loopholes. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins! [Answer] # [Sagemath](https://www.sagemath.org/), 2 bytes ``` GF ``` Outputs via [exception](https://codegolf.meta.stackexchange.com/a/11908/48931). [Try it online!](https://sagecell.sagemath.org/?z=eJxtjc0KwkAMhO-FvsNeRIU5bDbJ_hS86kOoB9EWBKlSK-jbG1Hx4lwymXxJusWmrlbLuqqr7jy43h17tw5gCDIKKCIoQgIHSEG0lEDMhCCeLCJGzFoMKVkIyiRWiBKLkSkX_6riWTn6hKQhh2yHQPYkQgVUOEMzmUuq0aO8ZW0oYpvbpq6caRweH_dSN-vnv-4yHPtxNp0cGsNu7dRN3Hfc3vftZWz-st3udP3AT22yOJg=&lang=sage&interacts=eJyLjgUAARUAuQ==) --- The Sagemath builtin \$\text{GF}\$ creates a [Galois Field](https://en.wikipedia.org/wiki/Finite_field) of order \$n\$. However, remember that \$\mathbb{F}\_n\$ is only a field if \$n = p^k\$ where \$p\$ is a prime and \$k\$ a positive integer. Thus the function throws an exception if and only if its input is not a prime power. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` f=lambda n,p=2:n%p and f(n,p+1)or p**n%n<1 ``` [Try it online!](https://tio.run/##ZcuxCsIwGEXhPU9xKRSa2sHGLZhXcOjmGGmjAb35iVl8@lgRBXE8cD55lEuiqTW4q7@dZg8O4oxlK/CcEbq1N6NOGdL3bLkf6@Sy53npzLDbaqUkRxY0x@XeqLB@RCQmqxDDi2uL98HP@iWH9C@Yyq@qTw "Python 2 – Try It Online") Since Python doesn't have any built-ins for primes, we make do with checking divisibility. We find the smallest prime `p` that's a factor of `n` by counting up `p=2,3,4,...` until `n` is divisible by `p`, that is `n%p` is zero. There, we check that this `p` is the only prime factor by checking that a high power of `p` is divisible by `n`. For this, `p**n` suffices. As a program: **43 bytes** ``` n=input() p=2 while n%p:p+=1 print p**n%n<1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vA1oirPCMzJ1UhT7XAqkDb1pCroCgzr0ShQEsrTzXPxvD/fzMA "Python 2 – Try It Online") This could be shorter with exit codes if those are allowed. **46 bytes** ``` lambda n:all(n%p for p in range(2,n)if p**n%n) ``` [Try it online!](https://tio.run/##ZcuxCsIwGEXhPU9xKRSS4iB1C/QVHLoJLpE2Gog3P2kWnz5apEJxPZxPXuWR2Fc/XGt0z9vkQOti1GwFPmUIApEd77PuDzTBQ7qOLU0dhy2fjkYpyYEFzWVeGrVCrnC0Ch/iNY3F9@C2/sg5/Qumslf1DQ "Python 2 – Try It Online") [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 329 bytes ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page] Ajax:Listen tothy. Page:You cat. Scene V:. Page:You is the sum ofYou a cat. Is the remainder of the quotient betweenI you nicer zero?If soLet usScene V. Scene X:. Page:You is the cube ofYou.Is you worse I?If soLet usScene X. You is the remainder of the quotient betweenYou I.Open heart ``` [Try it online!](https://tio.run/##hZDLCsIwEEV/ZT6gBEQ3diMuXAQKCoIo4iJNpzZiE00m@Pj5mLQFhS7cTS7nzknibtcQMra8iGfGNuKMcZYEPGdbiRrTcFxpQgsJAaErSNQpnfJCOUINZKh5deX8YDxIQUN5l39T5YAaBOdbMHUKRAfyPrbYCqWrqDF1F9y9IYWaoER6IGoOr9jRSkbkjdYseA3OFEjg3SAbpPuxVPoSe2vypUUPY1183HjLnv30/t4qsZytb/ETGhSWQpjNJ9MP "Shakespeare Programming Language – Try It Online") Outputs `0` if the input is almost prime, and a positive integer otherwise. I am not sure this is an acceptable output; changing it would cost a few bytes. Explanation: * Scene I: `Page` takes in input (call this `n`). Initialize `Ajax = 1`. * Scene V: Increment `Ajax` until `Ajax` is a divisor of `Page`; call the final value `p` This gives the smallest divisor of `Page`, which is guaranteed to be a prime. * Scene X: Cube `Ajax` until you end up with a power of `p`, say `p^k` which is greater than `n`. Then `n` is almost-prime iff `n` divides `p^k`. [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` Yf&= ``` * For almost-primes the output is a matrix containing only `1`s, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398). * Otherwise the output is a matrix containing several `1`s and at least one `0`, which is [falsy](https://codegolf.stackexchange.com/a/95057/36398). [Try it online!](https://tio.run/##y00syfn/PzJNzfb/fxMDY1NjMwNzAA) Or [verify all test cases](https://tio.run/##bY47T8QwEIT7@RVuIJcmyvoR2wWiOZDoKK6hQCICh1g4D8WJ0BX89mByEroTbLPe8bcz29VzWF/Yb12x/VAUxWfrg1ufmuub9fb886FBdpiWuT1m2/y4xJbNrY8szpPv3/F1Tt@F6JDd1yFu@H/88wXfv7Gdb3LsLw7ycQz1EYdz8WQ0LY7tNruu/nAxOTu2nc7CMIzM943v/exysD8xG5anuG4M/tXP@cohIGFgQRW4AtcQHNKiSiqBhCBwWVKSSKAyyibEGklQgmRqRFrIRGpjy58uS6FEVWpoxQ03yQiUQiooCbLCQBlKL61UVcKeKo3cyrT5DQ), including truthiness/falsihood test. ### How it works ``` % Implicit input Yf % Prime factors. Gives a vector with the possibly repeated prime factors &= % Matrix of all pair-wise equality comparisons % Implicit output ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` PrimePowerQ ``` [Try it online!](https://tio.run/##JU1LCoNQELtKDxDwze@9mUXBI9gjSBHrwhZE6KL07Hak2SQTksw67o9pHfflPh7z9Ri2ZZ2G13vabqd@7peun7v@wxAoHAGqYAM3CEMDNV0CiRBYC6VFguoWGQlXgglpElETzWTzKCdrEZNaGpqxs@cQKJ9UmIJCHOaUqpnVgvgjTw7N5vc4fg "Wolfram Language (Mathematica) – Try It Online") @Sisyphus saved 1 byte [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ÒË ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8KTD3f//mxgYmxqbGZgDAA "05AB1E – Try It Online") ### Commented: ``` Ò -- Are all the primes in the prime decomposition Ë -- Equal? ``` [Answer] # [R](https://www.r-project.org/), ~~36~~ ~~32~~ 29 bytes *-3 bytes by outputting a vector of booleans without extracting the first element* ``` !(a=2:(n=scan()))[!n%%a]^n%%n ``` [Try it online!](https://tio.run/##K/r/X1Ej0dbISiPPtjg5MU9DU1MzWjFPVTUxNg5I5v03tPgPAA "R – Try It Online") Outputs a vector of booleans. In R, a vector of booleans is truthy iff the first element is `TRUE`. First, find the smallest divisor `p` of `n`. We can do this by checking all integers (not only primes), as the smallest divisor of an integer (apart from 1) is always a prime number. Here, let `a` be all the integers between `2` and `n`, then `p=a[!n%%a][1]` is the first element of `a` which divides `n`. Then `n` is almost prime iff `n` divides `p^n`. This fails for any moderately large input, so here is the previous version which works for most larger inputs: # [R](https://www.r-project.org/), ~~36~~ 33 bytes ``` !log(n<-scan(),(a=2:n)[!n%%a])%%1 ``` [Try it online!](https://tio.run/##K/r/XzEnP10jz0a3ODkxT0NTRyPR1sgqTzNaMU9VNTFWU1XV8L@RuaWFieF/AA "R – Try It Online") Compute the logarithm of `n` in base `p`: this is an integer iff `n` is almost prime. This will fail due to floating point inaccuracy for certain (but far from all) large-ish inputs, in particular for one test case: \$4913=17^3\$. [Answer] # [C (gcc)](https://gcc.gnu.org/), 43 bytes ``` f(n,i){for(i=1;n%++i;);n=i<n&&f(n/i)^i?:i;} ``` [Try it online!](https://tio.run/##LU/bTsMwDH3GXxFN6pSoQcv9QlbxIWNIU0eRH8jQ6BNVv704QCTHzjnHJ/b4@D6O2zbxKlEs0@3OcdCldn2PRZQ64LHu98QeULzi8xOWdfu4YOViAawzm09nNrAFjAQrwUlIErIEHSQYTxEJJ84RFhqribOWbuOUbrimtpB8btqcHGHeatey1tG61hBTVr@FU9bboMgzepNMaqaka39T9uSvs6UBfNKtjt4HReP8nQaY7MgD1gK0KONtARxUweMXfr/dJj6Lw39FlCjY9wIePu/0mPiuy1fWXV/qTs4nPEtSUxKiwLr9AA "C (gcc) – Try It Online") Returns `p` if `n` is almost-prime, and `1` otherwise. ``` f(n,i){ for(i=1;n%++i;); // identify i = the least prime factor of n n=i<n&&f(n/i)^i // if n is neither prime nor almost-prime ? // return 1 :i; // return i } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) ``` ⊢∊⍳∘.∧⍳ ``` [Try it online!](https://tio.run/##JYw9CsJgEET7nGIuoHy7m5ikFsRUgnqBgKhFQPGnSC2EEIhoIdjY2Ghn4Q08yl4krqYZBubNS9dZZ5an2WrR6PGSjLQ4uUaru5aV1m8tr10tH9aauS1aH7U6fF6ixdnoybhvOR0mk0brG6ab/W6Ze/PPEwyBjwAhIsQgAgmoBwpBMVjAATgExxCC8P9CYp19R97PNUizbauylwMxyAcFoAjswEayweAeOII4iLSSWAwInfsC "APL (Dyalog Unicode) – Try It Online") Uses `⎕IO←0`. Returns 0 if the input is almost-prime, 1 otherwise. ### How it works ``` ⊢∊⍳∘.∧⍳ ⍝ Input: integer n ≥ 2 ⍳∘.∧⍳ ⍝ Generate a table of LCMs over 0..n-1 ⊢∊ ⍝ Does the table contain n? ``` The LCM of two numbers is equivalent to taking the maximum of powers in their prime factorizations. If `n = p^k`, any numbers smaller than `n` cannot have `p^k` in their prime factorization, so the LCM table does not contain `n`. Otherwise, we can find a pair of coprime numbers under `n` that multiplies to `n`, so the LCM table is guaranteed to contain at least one copy of `n`. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~33~~ ~~31~~ 26 bytes ``` {⍵∊∊(((⊢~∘.×⍨)1↓⍳)⍵)∘*¨⍳⍵} ``` -5 bytes from Kevin Cruijssen's suggestion. *Warning:* Very, very slow for larger numbers. ## Explanation ``` {⍵∊∊(((⊢~∘.×⍨)1↓⍳)⍵)∘*¨⍳⍵} ⍵=n in all the following steps ⍳⍵ range from 1 to n ∘*¨ distribute power operator across left and right args (((⊢~∘.×⍨)1↓⍳)⍵) list of primes till n ∊ flatten the right arg(monadic ∊) ⍵∊ is n present in the primes^(1..n)? ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHv1kcdXUCkoaHxqGtR3aOOGXqHpz/qXaFp@Kht8qPezZpAFZpAUa1DK4A8IKf2f9qjtgmPevsedTU/6l3zqHfLofXGj9omPuqbGhzkDCRDPDyD/6cpGHGlKRgDsQkQmwGxIVjADAA) [Answer] # [J](http://jsoftware.com/), 9 8 bytes ``` 1=#@=@q: ``` [Try it online!](https://tio.run/##NU1BCgIxELv3FUEPi6Cl05lpOwuFBcGTJ78ginhY8bivX0fEQEgmJMxz3cThjj5iwB4Jo/MQcbycTyv17dSn97juwtJjBkPQYKCCrMgVnCGG4imBmAlZEnlEjNLUvGJNCMokLkSVxZu1WfqqJFYuqaJqbrlZmHssIP9ToAIybtBG7qpqSbAf/MwmPg7hdn28cMfyN3NYPw "J – Try It Online") *-1 byte thanks to xash* Tests if the [self-classify](https://code.jsoftware.com/wiki/Vocabulary/eq#monadic) `=` of the prime factors `q:` has length `#` equal to one `1=` [Answer] ## [Setanta](https://try-setanta.ie/), ~~61~~ 59 bytes ``` gniomh(n){p:=2nuair-a n%p p+=1nuair-a n>1 n/=p toradh n==1} ``` [Try it here](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgIDAzs2RCg) Notes: * The proper keyword is `gníomh`, but Setanta allows spelling it without the accents so I did so to shave off a byte. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` !t{P ``` [Try it online!](https://tio.run/##K6gsyfj/X7GkOuD/f3MjSwA "Pyth – Try It Online") Explanation: ``` P - List of prime factors { - Remove duplicate elements t - Removes first element ! - Would return True if remaining list is empty, otherwise False ``` *-1 byte, thanks to hakr14* [Answer] # JavaScript (ES6), 43 bytes ## Without BigInts Returns a Boolean value. ``` f=(n,k=1)=>n%1?!~~n:f(n<0?n/k:n%++k?n:-n,k) ``` [Try it online!](https://tio.run/##bZG9bsJAEIT7vAUFsk@EcOv78Z2FcccTpCMpLIITsLWOMERKw6sbUJoks1d@N9qd2TnUX/WwPe4/T3Pu33bj2JQpP7YlqXLFU6omlwsXTcpLXfGiLXg6m7UVF/ObRo3bnoe@2z11/XuabJ6P59PH92uiHn7zJs3Uf2KAWCABSARCHlDmEOVoAD1ZHO8FV4QmjEGYWU3CCsLkPrgoWI7B4gBnyAo4D1FbwZnVxhmv7/H//CQvvFnX3SB0hQcloT5UOTwVRYMdukCCMnfOa@z75wnyLNpbNqXGKw "JavaScript (Node.js) – Try It Online") A recursive function that first looks for the smallest divisor \$k>1\$ of \$n\$ and then divides \$-n\$ by \$k\$ until it's not an integer anymore. (The only reason why we invert the sign of \$n\$ when \$k\$ is found is to distinguish between the two steps of the algorithm.) If \$n\$ is almost-prime, the final result is \$-\dfrac{1}{k}>-1\$. So we end up with \$\lceil n\rceil=0\$. If \$n\$ is not almost-prime, there exists some \$q>k\$ coprime with \$k\$ such that \$n=q\times k^{m}\$. In that case, the final result is \$-\dfrac{q}{k}<-1\$. So we end up with \$\lceil n\rceil<0\$. --- # JavaScript (ES11), 33 bytes ## With BigInts With BigInts, using [@xnor's approach](https://codegolf.stackexchange.com/a/210174/58563) is probably the shortest way to go. Returns a Boolean value. ``` f=(n,k=1n)=>n%++k?f(n,k):k**n%n<1 ``` [Try it online!](https://tio.run/##bdDJDoJAEATQu/9BYEANzTAsRvTmF3hDDwTBBdJjAE38elxO6tT1pZOqrktxL/qyO1@HGetDNY515vC0yYhFtmLL85p1/QaxaFyXLV7SWGrudVvNW3107Hzb3YbTY2@LybfXTsDin6RJoUmJSalJFJkWKGAx6AG6hSAjQu0IdJESaBD6hHIIzBAl6pP/w/aO803R9mBc8DyhwcGdAk9RKsHqKiF0GysV@S8fnw "JavaScript (Node.js) – Try It Online") [Answer] # Regex (ECMAScript), ~~35~~ ~~33~~ 32 bytes *-2 bytes thanks to H.PWiz; the explanation for why this worked was more complicated* *-1 bytes by returning to the original algorithm (with its simple explanation), by actually constructing values of \$a\$ not divisible by \$b\$ (32 bytes) instead of asserting \$a\$ is not divisible by \$b\$ (35 bytes); this is slower, but not exponentially so* ``` ^(?!(((x+)x+)(?=\2+$)\2*\3)\1+$) ``` [Try it online!](https://tio.run/##TY/LbsIwEEV/BaIKZkgTElp1gWtYdcGGRbtsWsmCwZnWOJZtHuXx7WlYVKp0F1c6V7o6X2qvwsqzi1lwvCa/bew3/bReWjr0Xkm/HB3ASc7Go/YT5n0AOKbYBeaymqR3WE1G1QNWZVfb0fiEeWzeomerAfNgeEXwdJ89IoogC3Go2RCAkZ7U2rAlQOxLuzMGz1qaPDjDEYbZEAVvAKzUuSGrY42zyeXCYamWwNIpH2hhI@j34gPxD9B/YGflvJzeMMbaN4dkYffK8LrnldU07SWpEZvGg@BnSYLTFLvD5JjknhypCIz5VsVVDR7xHAYD1ylFuFmUwu1iiL6biOu1LbOyKIpf "JavaScript (SpiderMonkey) – Try It Online") The 35 byte version was [written in 2014](https://gist.github.com/Davidebyzero/9090628#gistcomment-1177373) by teukon and me. This works by asserting that there do not exist any \$a\$ and \$b\$, both proper divisors of \$n\$ where \$a>b\$, for which \$a\$ is not divisible by \$b\$. This will always be true when \$n\$ is of the form \$p^k\$ (a prime power), because we will have \$a=p^c\$ and \$b=p^d\$ where \$k > c > d \ge 0\$, thus \$a\$ will always be divisible by \$b\$. But if \$n\$ is not of the form \$p^k\$, there will always be at least one counterexample \$a,b\$ such that \$a\$ is not divisible by \$b\$. Trivially we can choose two different prime factors of \$n\$, and they will not be mutually divisible. This algorithm is similar to that used by [Original Original Original VI's answer](https://codegolf.stackexchange.com/a/220047/17216). ``` # For the purpose of these comments, the input number will be referred to as N. ^(?! # Assert that the following cannot match ( # Capture \1 to be the following: ((x+)x+) # Cycle through all values of \3 and \2 such that \2 > \3 > 1 (?=\2+$) # such that \2 is a proper divisor of N \2*\3 # Cycle through all values of \1 > \2 that aren't divisible # by \2, by letting \1 = \2 * A + \3 where A >= 0 ) \1+$ # where \1 is a proper divisor of N ) ``` --- Bonus: Here is a 28 (27🐌) byte regex that matches numbers of the form \$p^k\$ where \$0 \le k \le 2\$: `^(?!((x+)x+)(?!\1*\2+$)\1+$)`, exponential slowdown 🐌 version: `^(?!((x+)+)(?!\1*\2+$)\1+$)` (`(x+)+)` is equivalent to `(x+)x*` but exponentially slower) [Try it online!](https://tio.run/##TY9PawIxFMS/ii5F33O760ZKD6bRUw9ePLTH2kLQZ/a1MRuS@KdqP/t2PRQKwzDwGxjmUx90XAf2qYieNxR2jfui7zYoR8feC5nnkwc4q9l41H7AvA9wyrFTF1ditJrkd7gSnbWj8RnL1LymwM4AltHymuDxvnhAlFFV8lizJQCrAumNZUeA2Fduby1ejLJl9JYTDIshSt4COGVKS86kGmeT65XjUi@Bldch0sIlMG/VO@IfoP/AzcRcTG8YUx2aY7ZwB2150wvaGZr2stzKbRNA8pMiyXmO3WB2yspAnnQCxnKn07qGgHiJg4HvLiW4vRDS71NMoavIn59WFKKqql8 "JavaScript (SpiderMonkey) – Try It Online") This is interesting because if I'd set out to implement that function intentionally, I would have come up with something like [`^(?=(x?x+?)\1*$)((?=(x+)(\3+$))\4)?\1$`](https://tio.run/##TY/NTsJAFEZfBRsC91JbWiUuGIeuXLBhoUuqyQQu7dVhOpkZoPLz7BVMTFx@OV9ycj7VXvmVYxsSb3lNbtuYL/runDR06L1S9dJagKOcjUfdBxQS2qKNCyzzUR/hd8cI5WPcRywnWJR5vxuNj5iG5i04NhVg6jWvCJ7ukwmi8DITh5o1AWjpSK01GwLEO2l2WuOpkjr1VnOAYTJEwRsAI6tUk6lCjbOH85n9Qi2ApVXO09wEqJbZO@IfoP/AzPIin94whto1h2hu9krzuueUqWjai2ItNo0Dwc@SBMcxXoVRG6WOLKkAjOlWhVUNDvHkBwN7TQpwq8iF3QUf3PUiLpcuS/Isy34A "JavaScript (SpiderMonkey) – Try It Online") (38 bytes), which is 10 bytes longer. It was inspired by the algorithm used by [Bubbler's APL answer](https://codegolf.stackexchange.com/a/220062/17216). The full prime power version of that would be: [`^(?!((x+)(?=\2+$)x+)(?!\1*\2+$)\1+$)`](https://tio.run/##TY9Lb8IwEIT/CkQV7JImJKjqAddw6oELh/ZYWsmCxdnWOJZtHuXx29OAhNTLaEbfSKP5VjsVlp5dzILjFflNbX/ot/HS0r7zRvr14ACOcjIcNF8w7QIcUoSpXIzSB7zZ7qIc3NKibKUZDI@Yx/o9erYaMA@GlwTPj9kTogiyEPuKDQEY6UmtDFsCxK60W2PwpKXJgzMcoZ/1UfAawEqdG7I6VjgZnc8c5moOLJ3ygWY2gv4oPhHvgP4DOymn5fiKMVa@3iczu1OGVx2vrKZxJ0mNWNceBL9IEpym2A4mhyT35EhFYMw3Ki4r8Iin0Ou59lKE64tSuG0M0bcVcbk0ZVYWRfEH "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript, 36 bytes [`^(?!((x+)x+)\B(?>\1*?(?<=^\2+))$)`](https://tio.run/##ZVBNaxsxEL3nV8imYE33g11DL1Vkhyw9BBIS6kAPdQPqeuIIZO2i0bqKN/ntrryb5JJBl@G90fuoKasbh0erdkitqpGtnsnjru9I2y2rZNVYagyKcb/H4POfuO2Mcj9C65BIR4KojSJiu5688rpm@0Zv2I3SlnHo98oxkhfT4wNfTjgPCcS3vuTLxbr8uuTLc/mwnicAX@A4FSeykxb/saiCgVO@6v6Sd1Gclynl12i3/imbQzrgt60/6edVs2u1wQ2IkcuMeGwc19YzKwvBjayibbW51hY5wETazhhhZQm9fuR2UUCV/3La40gYbLTS5KvWaM9n2QzE6S@dojiLB@2bj8X85WUSgfzePd8pR8jb38WftOkiFT5D72dZOXIQ3mX59MrulYmtOWW3@J31xes0NSDQEA4NhqGU1djELMxSDR8RDzGiPpcodJKkIZERhujS5Vd0o3z9xAMMOQ@fch5kKT4sDJrhzSOI12GOZfatKP4D) - .NET, 33 bytes [`^(?!((x+)+)\B(?>\1*?(?<=^\2+))$)`](https://tio.run/##ZZBPT@MwFMTv@yncCql@mz9qKnHBuF1txAEJtGiLxIEukkkfxZLrRH5OMQ189q6bABd8s2bs@c1UlFW1w4NVW6RGVciWr@Rx27Wk7YaVsqwt1QbFcL/F4PO/uGmNchehcUiko0FURhGxbUdeeV2xXa3X7Fppyzh0O@UYyV/jwwNfjDgPCSSw@s0X81Xxc8EX5/JhNUsATuAwFkevkxZfWAzBwClfto/kXczmRUr5FdqNf85mkPb6n8Yf4/Oy3jba4BrE4GVGPNWOa@uZlVPBjSwjtVpfaYscYCRta4ywsoBOP3E7n0KZ3zntcTD0GI00@bIx2vNJNgFx/EunKH7EB80Hx3z29jaKQn7rXm@UI@TN/fRfWrfRCt@lz2dZMXgQPmP5@NLulImjOWU3eMa66fs4NSDQEPYDhn6U5bDEJExSDV8V97GiPpcodJKkIZFRhkjp8ku6Vr565gH6nvtvPfeyEF8IfWb4YATx3p9Dkc1O/wM) - .NET, 32 bytes, 🐌 exponential slowdown And [user41805's APL answer](https://codegolf.stackexchange.com/a/220353/17216) ported to regex is: [`^(?!(xx+)\1*(?=\1*$)x(xx+)\2*$(?<=^\2+))`](https://tio.run/##TY7BbsIwEER/pY2QvEuIFXOMMTn1wIVDeyxFWIkJW7lOahuIBHx7GlpV4rIa7ZvdmU990qHy1MXMtbUZgsqlV6@meek7eIueXMO9Pu@GLZTP0PcpbsQUSjXOCfZ/i/l0AuVCbTfzFHHY8WCpMiBmmUCU3nwfyRtg3ujakjMMeTXqaFYuGr/Xo/VCrjvGovNtZULgIdbkbshbB@z3YmbV8tIoy0NnKQLLGEraAzjVcGtcEw@4nF@vFNZ6DaQ67cP9OzTv@QfiPzCPwC1FKYo7xnjw7TlZuZO2VD957RpTPCWplfvWg6SFMpLSFMfApE@4N91YHgj5l47VATzi5aF4e4z87CkagFCyjWMFY5gSyqCEvN1wEJnI8/wH "JavaScript (Node.js) – Try It Online") - ECMAScript 2018, 40 bytes `^(?!(?*(xx+)\1*$)(xx+)\2*(?=\2*$)x\1*$)` - ECMAScript + `(?*)`, 39 bytes The algorithm used by 10+ of the other answers (that all the prime factors are the same / there is only one prime factor), ported to regex is: [`^(?=(xx+?)\1*$)(?!(\1x+)(?<!^\3+(xx+))\2*$)`](https://tio.run/##Tc69bsIwFAXgV4Goku9tiBXTLcZk6sDC0I5NEVZiwq1cJ7UNRAKenYZKldiO9N2f86WPOtSe@pi5rjG3oHLp1ZtpX4ce3qMn13KvT9vbBkoFw5CWWInnJ4RyCpUY0jEsppvqJb0bYjUf7bblwVJtQMwygSi9@TmQN8C80Y0lZxjyeszRrFw0fqfH0TO5/hCL3ne1CYGH2JC7Iu8csL@NmVXLc6ssD72lCCxjKGkH4FTLrXFt3ONyfrlQWOs1kOq1D/fr0H7kn4j/YB7BLUUpijtj3PvulKzcUVtqJl671hSTJLVy13mQtFBGUpri@DAZEu5NP5YHQv6tY70Hj3h@KN4dIj95igYglKxyrGAMU0IZlJDXK97mmcjz/Bc "JavaScript (Node.js) – Try It Online") - ECMAScript 2018, 43 bytes # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~41~~ ~~39~~ 38 bytes ``` .+ $* ^(?!(((1+)1+)(?=\2+$)\2*\3)\1+$) ``` [Try it online!](https://tio.run/##DYoxCsMwEMB2/aKQwDmGwN05bjyUjPmECc2QoUuH0v87Bg1C6Hf9P9@zjbK/2xwZJg7ZHiKiMXRke1WLQ6g2VQ9Vu7ZmOImVgmZswZ64kQq5V0XdlYz2LbMktPh6Aw "Retina 0.8.2 – Try It Online") [Answer] # GAP 4.7, 31 bytes `n->Length(Set(FactorsInt(n)))<2` This is a lambda. For example, the statement `Filtered([2..81], n->Length(Set(FactorsInt(n)))<2 );` yields the list `[ 2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19, 23, 25, 27, 29, 31, 32, 37, 41, 43, 47, 49, 53, 59, 61, 64, 67, 71, 73, 79, 81 ]`. [Try it online!](https://tio.run/##S08s@B9QlJlXouGWmVOSWpSaohFtpKdnYRir8z9P184nNS@9JEMjOBUon5hckl9U7AlUmqepqWlj9F9T0/o/AA) [Answer] # [Factor](https://factorcode.org/), 35 bytes ``` : f ( n -- ? ) factors all-equal? ; ``` [Try it online!](https://tio.run/##VU@7TsNAEOznK7aEwpb33ucUKVGaNIgKUVjm7ERcbGM7BYr4drOAKNhmZkcz@@iadh3n7enxcHyo6S3NQ8o0zWldP6b5PKx0adZTKfSSlrL7MS/Uz@N1Og89Len9moY2LbTD4VhTO76mfszdVlNHdzRQUdCe7ukv2ORcSKTJe9ptN1LQMAiIYAdloTy0golwojJYa4YyFYvEGi7YKJYYDMNqNgLMXhtx@hCrbzSVttpVHt6qoEKkT3qWS17ki4lK4EYOLFsdrAFHHWADC/PWugrxt6RV0cio/@ntCw "Factor – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` f n=mod(until((<1).mod n)(+1)2^n)n<1 ``` [Try it online!](https://tio.run/##DcdBCoAgEADAr@yhgxKJeq6XRIGYlrRuYvb9tuY2h7vPgMgcgaZ8beKhllCI0Uj1F0iK3ki7kqTRcHaJYIJSEzXoICZsoUKE2SpltF749RHdfvPgS/kA "Haskell – Try It Online") **36 bytes** ``` f n=and[mod(gcd d n^n)n<2|d<-[1..n]] ``` [Try it online!](https://tio.run/##BcExDoAgEATAr2xhoQUErfUlBBPCiRLhJGjp2z1nDn@fW84iEbx4Jlsu6vdAIPDKA8/TS7Oyo9bsnBSfGAtqS/ygQ0z52Roi7KT1aIyTL8Ts91tUqPUH "Haskell – Try It Online") **39 bytes** ``` f n=all((`elem`[1,n]).gcd n.(^n))[2..n] ``` [Try it online!](https://tio.run/##FclBCoAgEADAr@yhg0KJdvclYiSmJm2LpO9vo7nOGfqVEJkzkA2IQuwJ0707M5OXqsQDSImNpHSrUuT5DpXAQnsqDZggVxzpgQx/G609vzFjKJ2X2NoH "Haskell – Try It Online") **39 bytes** ``` f n=mod n(n-sum[1|1<-gcd n<$>[1..n]])<1 ``` [Try it online!](https://tio.run/##DcgxDoAgDADAr3Rw0AFincGPEAaCoESoRHTz7VZvvM21PeTMHIF0ORagnkS7i8EHlVj9H6qbDUpJ1g4KubhEoKGeiS7oIKZ8hRMimElKHEfLr4/ZrY2Fr/UD "Haskell – Try It Online") **40 bytes** ``` f n=and[mod(p^n)n<1|p<-[2..n],mod n p<1] ``` [Try it online!](https://tio.run/##FcpBDkAwEAXQq/yFBQmi1u1JpJKGlkaNCV06u8H25a3u2nxKIgFkHM3Dfswlj1SRVjfrZujblmz9KQislZXdRYIBn5EyCoSYsj8R8E/VdVaeKSS3XNJMzC8 "Haskell – Try It Online") [Answer] # [Io](http://iolanguage.org/), 48 bytes Port of @RobinRyder's R answer. ``` method(i,c :=2;while(i%c>0,c=c+1);i log(c)%1==0) ``` [Try it online!](https://tio.run/##nY1NDoMgGAX37xSExARSF36AVmvoEXoCN5ZiJcGfqE2PbzlD3@7NYiYs58BulnXn5I9xeYmQu/RV@x1D9CJk7l7kzroLyTawuLyFkxlZW8iTK2gY1GhAFVQJdYVWMA2qRAmkNUGZghIizdm@xnAI3s1csqlfRb8/PtPTb5INy@Z7N6Y2WNoggmTrFuYjzpDgFSilKpQG1OgaZU3mb935Aw "Io – Try It Online") ## Explanation ``` method(i, // Take an input c := 2 // Set counter to 2 while(i%c>0, // While the input doesn't divide counter: c=c+1 // Increment counter ) i log(c)%1==0 // Is the decimal part of input log counter equal to 0? ) ``` [Answer] # [Assembly (MIPS, SPIM)](https://github.com/TryItOnline/spim), 238 bytes, 6 \* 23 = 138 assembled bytes ``` main:li$v0,5 syscall move$t3,$v0 li$a0,0 li$t2,2 w:bgt$t2,$t3,d div$t3,$t2 mfhi$t0 bnez$t0,e add$a0,$a0,1 s:div$t3,$t2 mfhi$t0 bnez$t0,e div$t3,$t3,$t2 b s e:add$t2,$t2,1 b w d:move$t0,$a0 li$a0,0 bne$t0,1,p add$a0,$a0,1 p:li$v0,1 syscall ``` [Try it online!](https://tio.run/##fY/BDsIgDIbvfYodduwBUKPyNiCoJDBJIFv05bFlusSLh6bN369/25JDai2ZMOkYxlngAcqzXEyMkB6zH@sOSQXqGYE9V4UKFm1vlUsGHLgwd7IqSNc7MQLs5F@U0YNxjoc5JBT9l92aK2CHAl6zQV@lyMAOCzi93tZNt9vIhSWJ@Xdl/nwmv5@1po7n016@AQ "Assembly (MIPS, SPIM) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes Are all prime factors equal? ``` ḋ= ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GObtv//w2NjQ0B "Brachylog – Try It Online") [Answer] # [APL (Dyalog Unicode) 17.0](https://www.dyalog.com/), 7 bytes ``` ⍸2⌊/⊢∨⍳ ``` [Try it online!](https://tio.run/##JU07TkNBDOw5xVwAsV7bu@u0NNASLhAJ5TWRoEWIChShBxtBQUkDTToKhESdo/giDwem8Fjz0SyuVocX14vV5TBN3n@yP41HPr77w9b71zT4@tn7xse73Sf7@sU3r/Oz47jnJ6fzaRnuDdFslvzxnnz8GLx/3x4sd9sMhqDBQAVZkSs4QwwlVAIxE7IkCokYpalFxJoQlEmCiCpLJGuz9MeaW24G72@SWLmkut8poJgqUAEZN2ij@KpqSbB/7CtUs0n0fgE "APL (Dyalog Unicode) – Try It Online") Uses a different approach from [Bubbler's answer](https://codegolf.stackexchange.com/a/220062), but only works for Dyalog 17.X. Errors with a domain error on non-prime powers, and doesn't error on truthy inputs. The train is decomposed as the following ``` ┌─┬─────────────────┐ │⍸│┌─┬─────┬───────┐│ │ ││ │┌─┬─┐│┌─┬─┬─┐││ │ ││2││⌊│/│││⊢│∨│⍳│││ │ ││ │└─┴─┘│└─┴─┴─┘││ │ │└─┴─────┴───────┘│ └─┴─────────────────┘ ``` First a range from 1 to the right argument is created using `⍳`. ``` (⍳) 10 1 2 3 4 5 6 7 8 9 10 ``` Then each value in this list is [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor)ed `∨` with the right argument `⊢`. ``` (⊢∨⍳) 10 1 2 1 2 5 2 1 2 1 10 ``` Then the pairwise minimum is taken, with the pairs overlapping, so `2⌊/1 3 2` is equivalent to `(1⌊3)(3⌊2)`. ``` (2⌊/⊢∨⍳) 10 1 1 1 2 2 1 1 1 1 ``` Monadic `⍸` in Dyalog 17.0 is a function that finds the indices of truthy values given a binary array, but this function of it is irrelevant for this solution. If the input is not a prime power, it will have at least one number greater than 1 when the above is performed (proof below). Otherwise if it is a prime power, the above will result in a list with only 1s. So applying `⍸` on a non-prime power will cause the function to error because its argument is not a binary array, whereas on a prime power it won't error because the argument would binary consisting only of 1s. In Dyalog 18.0 `⍸` has been extended to also accept non-binary arrays, so the above won't work. Instead, using 'unique' `∪` in place of `⍸` will return the 1-length vector consisting only of 1 for truthy values, and a longer vector for falsey values. [Bubbler](https://codegolf.stackexchange.com/users/78410) gave the following proof as to why `2⌊/⊢∨⍳` does not give a vector of 1s for falsey values. Consider the Diophantine equation \$p\_1a-p\_2b=1\$, where \$p\_1\$ and \$p\_2\$ are distinct prime factors of a non-prime tower \$N\$ and \$a,b>0\$. This equation has solutions, a proof of which can be found in the following [Wikipedia article](https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity). What this equation means is that you will have a situation where a multiple of \$p\_1\$ occurs as the number immediately following a multiple of \$p\_2\$. Since each prime factor divides the input \$N\$, their multiple, when GCDed with the input, will result in a value greater than 1. The fact that these multiples are less than \$N\$ is left as an exercise to the reader. So the two multiples of prime numbers following one another and that these multiples are less than \$N\$ mean that you have a situation where `2⌊/⊢∨⍳` will have a number greater than 1 in it. This situation does not occur for prime powers because given any two prime factors \$p^m\$ and \$p^n\$ where \$n>m\$, there will never be a situation where \$p^na-p^mb=1\$ because that would imply \$p(p^{n-1}a-p^{m-1}b)=1\$, i.e. that \$p\$ divides 1 which is false. [Answer] # Java, ~~69~~ 64 bytes ``` n->{int f=0,t=1;for(;n%++t>0;);for(;n>1;n/=t)f|=n%t;return f<1;} ``` -5 bytes thanks to *@Deadcode*. [Try it online.](https://tio.run/##LVDBjoIwEL37FRMTEwijS2kLrV38g/Xi0XioCBtcLAaqm43Lt7PDag@dvtfXN69ztne7PJ@@xqKxfQ8ftnaPGUDtfNlVtihhO0GAY9s2pXVQBHQFLjTEDjPaem99XcAWHOQwuuXmMQmqPEafM1O1XWDcIor8JjbhC26YcW@5D6vf3C286Up/6xxU78wMo5k8r7djQ54v63tbn@BCwYKd72r3uT@ADZ@pJr@pXb125fcUen94JMhRoEKNLMVEYpIhT1BoTIllyDhnmIiYEcU4pkpqkmglGErOBBXGMi5ImSkdT1XEXPI0zjCTiUoUGSGjJilKgUxzhVIxOmVSpjHq5yKYaEEvh/A/KMDup/flZdXe/OpKv/CNC@povoZ55FY01PA10WH8Aw) **Explanation:** ``` n->{ // Method with integer parameter and boolean return-type int f=0, // Flag-integer `f`, starting at 0 t=1; // Temp integer `t`, starting at 1 for(;n%++t>0;);// Increase `t` by 1 before every iteration with `++t`, // And continue looping until the input `n` is divisible by `t` for(;n>1; // Then start and continue a second loop as long as `n` is not 0 or 1: n/=t) // After every iteration: divide `n` by `t` f|= // Bitwise-OR the flag by: n%t; // `n` modulo-`t` return f<1;} // After both loops, return whether the flag is still 0 ``` --- If we would be allowed to ignore floating point inaccuracies, a port of [*@RobinRyder*'s R answer](https://codegolf.stackexchange.com/a/210175/52210) would be **64 bytes** as well: ``` n->{int m=1;for(;n%++m>0;);return Math.log(n)/Math.log(m)%1==0;} ``` [Try it online.](https://tio.run/##PVDLbsIwELzzFatKSImypPErsYnCH5QLR8TBhEBDEwclhqpC@Xa6Kag@eB@enRnv2d7s4nz4epSNHQb4sLW7zwBq56v@aMsK1lMJsO@6prIOyoCewIU5dccZXYO3vi5hDQ4KeLjF6j4B2oLlx64PcjePonaV5GHeV/7aO1Lwn3HTnQIXvv/nbThnRZHk4yOfOC/XfUOcL@pbVx@gJWPBxve1O213YMOnq0likquXrvqeTG93d44CJWo0yFLkCnmGgqM0mFKXIROCIZcJoxYTmGplCGK0ZKgEkxQYy4QkZKZNMkWZCCXSJMNMcc01ESEjkRSVRGaERqUZZZlSaYLmeajkRtLkGP4ZBdj8DL5q4@7q4wv9wjcuqKO3JbxFLqalhq@Njo9f) **Explanation:** ``` n->{ // Method with integer parameter and boolean return-type int m=1; // Minimum divisor integer `m`, starting at 1 for(;n%++m>0;); // Increase `m` by 1 before every iteration with `++m` // And continue looping until the input `n` is divisible by `m` return Math.log(n)/Math.log(m) // Calculate log_m(n) %1==0;} // And return whether it has no decimal values after the comma ``` But unfortunately this approach fails for test case `4913` which would become `2.9999999999999996` instead of `3.0` due to floating point inaccuracies (it succeeds for all other test cases). A potential fix would be **71 bytes**: ``` n->{int m=1;for(;n%++m>0;);return(Math.log(n)/Math.log(m)+1e9)%1<1e-8;} ``` [Try it online.](https://tio.run/##PVDBbsIwDL3vKywkpFY1rG6SNqGDP4ALR8QhQGFlbYrawDShfjtzB1oOsf3y7Pfis73Zyfnw9dhXtutgaUt3fwMonS/ao90XsBpKgF3TVIV1sA/4CVyYM9q/8dV568s9rMDBHB5usrgPhHpO@bFpg9yNo6hexHmYt4W/ti5YWv85rZpT4ML3/7wOIypMOKYPKiY67x/5MPpy3VU8@qVwa8oD1OwvWPu2dKfNFmz4NDcoDarlzBXfg/fN9p6gQIkaDVKKicIkQ5GgNJgySkhCECYyJoZIYKqVYYrRklAJkhyIMiGZmWkTD1HGQok0zjBTiU40D0JikRSVRDJCo9LEWaZUGqN5Hi4TI7mzD/@MAqx/Ol/U0@bqpxf@ha9cUEajGYwiN@Xdhq/F9o9f) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~50~~ 43 bytes ``` .+ $* ^(?=(11+?)\1*$)((?=(1+)(\3+$))\4)*\1$ ``` [Try it online!](https://tio.run/##HYsxDkIhEAX7dw5MdiEx/7ELQmF@@S9BjBYWNhbG@yOxnJnM5/l9vR/zJMd9nhNCxE32q5Bp18EYVP6YVIaloDpc42CYM8PgaOhgRS7IF1iGd9RlCZoR2TcuRUNtZRVwXRXFwW4NpdF/ "Retina 0.8.2 – Try It Online") Link includes faster test cases. Originally based on @Deadcode's answer to [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/q/19262/17602), but saved 7 bytes thanks to @Deadcode by improving the basic algorithm. Explanation: ``` .+ $* ``` Convert the input to unary. ``` ^(?=(11+?)\1*$) ``` Start by matching the smallest factor `p` of `n`. (`p` is necessarily prime, of course.) ``` (?=(1+)(\3+$)) ``` Find `n`s largest proper factor `m`, which is equivalent to `n` divided by its smallest prime factor `q` (which will be equal to `p` on the first pass). ``` \4 ``` The factorisation also captures `n-m`, which is subtracted from the current value of `n`, effectively dividing `n` by `q` for the next pass of the loop. ``` (...)*\1$ ``` Repeat this division by the smallest prime factor until `n` becomes `p`, which is only possible if `n` is a power of `p`. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╒g¶mÉk╒#─╧ ``` Port of [*@Razetime*'s APL (Dyalog Classic) answer](https://codegolf.stackexchange.com/a/210173/52210), so make sure to upvote him as well! [Try it online.](https://tio.run/##y00syUjPz0n7///R1Enph7blHu7MBrKUH01peDR1@f//RlzGXCZcFlyWXIZmXEamXEbmXMZGXCaWXGZAUUMuMy5DoAozLlMTAA) **Explanation:** ``` ╒ # Push a list in the range [1, (implicit) input-integer) g # Filter it by: ¶ # Check if it's a prime m # Map each prime to, É # using the following three operations: k╒ # Push a list in the range [1, input-integer) again # # Take the current prime to the power of each value in this list ─ # After the map, flatten the list of lists ╧ # And check if this list contains the (implicit) input-integer # (after which the entire stack joined together is output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I feel like this should be 1 or 2 bytes shorter ... ``` k ä¶ × ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayDktiDX&input=WzIKMwo0CjgKOQoxNgoyNQoyNwozMgo0OQo2NAo4MQoxMzMxCjI0MDEKNDkxMwo2ODU5CjI3OTg0MQo1MzE0NDEKMTE3MzQ4MQo3ODkwNDgxCjQwMzUzNjA3Cjc1MjgyODkKNgoxMgozNgo1NAoxOTM4CjU4MTQKMTc1NTYwCjk5OTk5OTkKMTcyOTQ0MDMKXS1t) - includes all test cases [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ÆfE ``` [Try it online!](https://tio.run/##JY6xDQIxDEV7z@Iiju3EGQAxBKKE4nQLXEsByzAC3YlFWCR8Q6TE1vv5/l4u67rNud@vh/l@7Y/P7Xmc80SVSZmMKZgGkzSm6rgdHJqBtVQFmireakWSC2wtfOTfEQbmKpZVpKuloccov8aKuraCmd1r1ICJECQZjuoIkKHYwEOy7@6tYJ//SVCHYQjT@Qs "Jelly – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytes ``` ∨/1~⍨⊢∨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHHSv0Dese9a541LUIyH7Uu/n/f/WQotKSjEorda40BSMgNgZiEyC2AGJLIDY0A0mYgghzkDRIjQlIwgysyhCkxNjYkItL3S0xpxhiDkiLIdgwEMsUpNDQ0hhkoqmFoQkA "APL (Dyalog Unicode) – Try It Online") Outputs 1 if it isn't almost-prime, some other positive integer otherwise. ``` ∨/1~⍨⊢∨⍳ ⊢∨⍳ ⍝ All divisors 1~⍨ ⍝ Remove 1 ∨/ ⍝ GCD ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 4 bytes ``` ϼŁ1= ``` [Try it online!](https://tio.run/##K6gs@f///J6jjYa2//8bAgA "Pyt – Try It Online") ``` ϼ Implicit input; get unique ϼrime factors Ł Łength of array 1= equals 1?; implicit print ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~18 16 13~~ 11 bytes *Thanks to [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu) for -7 bytes* ``` ƛ?$Ḋ$æ∧;∑1= ``` [Run it](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGmz8k4biKJMOm4oinO+KIkTE9IiwiIiwiMjUiXQ==) Explanation: ``` ƛ ; # map over the input with this code: ? # get input $ # swap Ḋ # divisible? $ # swap æ # is the item prime? ∧ # logical and ∑ # sum 1= # is 1? ``` ]
[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 6 years ago. [Improve this question](/posts/21666/edit) Write a program that starts itself again when finishes. There should be no more than one instance of the program running at same time. Not even for a slightest moment of time. You can ignore any instance that is manually started by user during your cycle. But your code should not do it in your restart cycle. Program can start after any amount of time, as long as it is guaranteed that it starts again. The only way to stop the cycle is to kill the process. Your solution should not involve restarting of the environment (in which program is running, includes OS, machine, VM, shell etc). Only your program is allowed to restart. [Answer] # Bash script, 3 chars (Shortest, possibly the most elegant, though admittedly controversial) ``` $0& ``` Simply places a new instance of itself in the background (new process), then quits. The new instance likely will remain in the scheduler run-queue until the previous instance is done. ### Warning - this is hard to `kill`, as the PID is continually changing. Temporarily renaming the script file is probably the simplest way to break the cycle. A single-core system is assumed. Of course this is not realistic with Linux on modern bare-metal hardware, but it is easily configurable when running in a VM. We could probably achieve a similar trick using `taskset`, but that would reduce the impact of the 3-char solution. This answer bends the rules a little bit in that it applies a specific meaning of "running". There will be moments when the new process has been `fork()`ed and the old process is still alive - i.e. it may be possible to observe more than one PID. However the new process will be placed on the Linux scheduler run-queue to wait for CPU cycles, while the existing process will continue to execute. At this point all that needs to be done by the existing process is for `bash` itself to `exit()`. This does take a finite amount of time, though I'm fairly confident that it will be done way before the current timeslice/scheduler quantum is done. Supporting evidence is the fact that `bash` starts up and shuts down in 2ms on my VM: ``` $ time bash -c : real 0m0.002s user 0m0.000s sys 0m0.000s $ ``` Further supporting evidence that the new process does not actually run until the previous process is done can be seen in `strace` output: ``` strace -f -tt -o forever.strace bash -c ./forever.sh ``` In the output, we see the original process has PID 6929. We can see the `fork()` call (actually `clone()`), which returns a new PID of 6930. At this point there are 2 PIDs, but only 6929 is currently running: ``` 6929 12:11:01.031398 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2f83ac49d0) = 6930 6929 12:11:01.031484 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 6929 12:11:01.031531 rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0 6929 12:11:01.031577 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0 6929 12:11:01.031608 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0 6929 12:11:01.031636 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0 6929 12:11:01.031665 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0 6929 12:11:01.031692 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0 6929 12:11:01.031726 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0 6929 12:11:01.031757 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 6929 12:11:01.031803 rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0 6929 12:11:01.031841 read(255, "", 4) = 0 6929 12:11:01.031907 exit_group(0) = ? 6930 12:11:01.032016 close(255) = 0 6930 12:11:01.032052 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 ``` [Full `strace` output here.](http://pastebin.com/csEm1eZs) We can see that 6930 does not issue any system calls until 6929 is completely done. It is reasonable to assume that this means 6930 does not run at all until 6929 is done. The `perf` utility would be the ultimate way to prove this. [Answer] # Solution 1 ### PHP, 32 chars It sends the header and then it stops. After 3 seconds, the page gets reloaded. **file a.php** ``` header("Refresh: 3; url=a.php"); ``` This can be stopped by terminating the execution of the page before the headers are sent, or simply by killing the browser. --- # Solution 2 ### PHP, 2 pages Let's consider the two files two different programs. The two files are in the same folder. **file a.php** ``` header("Location:b.php"); ``` **file b.php** ``` header("Location:a.php"); ``` Terminating one of the pages before the headers are sent terminates the program (killing the browser works, too). Here's the same program in ### ASP.NET **file a.aspx** ``` Response.Redirect("b.aspx") ``` **file b.aspx** ``` Response.Redirect("a.aspx") ``` [Answer] # sh ``` echo $PWD/$0 | at tomorrow ``` This will work on any Posix-compliant system. To kill it, delete the file or use `atrm`. [Answer] # bash ``` exec "$0" ``` `exec` replaces the shell without creating a new process. This makes sure that there cannot be a second instance. [Answer] # Windows Task Scheduler (Native) C++. A nightmare of COM programming. Meets all challenge requirements. ``` #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <taskschd.h> #include <comutil.h> #pragma comment(lib, "taskschd.lib") #pragma comment(lib, "comsuppw.lib") static void timeplus (int seconds, char timestr[30]); int main () { CoInitializeEx(NULL, COINIT_MULTITHREADED); CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL); const char *name = "Restarter"; char path[MAX_PATH + 1]; GetModuleFileNameA(NULL, path, sizeof(path)); path[sizeof(path) - 1] = 0; // workaround for xp ITaskService *taskman; CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void **)&taskman); taskman->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); ITaskFolder *root; taskman->GetFolder(_bstr_t("\\"), &root); // Delete the task. root->DeleteTask(_bstr_t(name), 0); // pause for 5 seconds to give user a chance to kill the cycle fprintf(stderr, "If you want to kill the program, close this window now.\n"); Sleep(5000); fprintf(stderr, "Sorry, time's up, maybe next time.\n"); // Create the task for 5 seconds from now. ITaskDefinition *task; taskman->NewTask(0, &task); IPrincipal *principal; task->get_Principal(&principal); principal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN); ITaskSettings *settings; task->get_Settings(&settings); settings->put_StartWhenAvailable(VARIANT_TRUE); settings->put_DisallowStartIfOnBatteries(VARIANT_FALSE); settings->put_StopIfGoingOnBatteries(VARIANT_FALSE); ITriggerCollection *triggers; task->get_Triggers(&triggers); ITrigger *trigger; triggers->Create(TASK_TRIGGER_TIME, &trigger); char when[30]; ITimeTrigger *trigger_time; trigger->QueryInterface(IID_ITimeTrigger, (void **)&trigger_time); trigger_time->put_Id(_bstr_t("TimeTrigger")); timeplus(10, when); trigger_time->put_StartBoundary(_bstr_t(when)); timeplus(300, when); trigger_time->put_EndBoundary(_bstr_t(when)); IActionCollection *actions; task->get_Actions(&actions); IAction *action; actions->Create(TASK_ACTION_EXEC, &action); IExecAction *action_exec; action->QueryInterface(IID_IExecAction, (void **)&action_exec); action_exec->put_Path(_bstr_t(path)); IRegisteredTask *regtask; root->RegisterTaskDefinition(_bstr_t(name), task, TASK_CREATE_OR_UPDATE, _variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(""), &regtask); regtask->Release(); action_exec->Release(); actions->Release(); trigger_time->Release(); trigger->Release(); triggers->Release(); settings->Release(); principal->Release(); task->Release(); root->Release(); taskman->Release(); CoUninitialize(); } // outputs current utc time + given number of seconds as // a string of the form YYYY-MM-DDTHH:MM:SSZ static void timeplus (int seconds, char timestr[30]) { SYSTEMTIME when; FILETIME whenf; LARGE_INTEGER tempval; GetSystemTimeAsFileTime(&whenf); tempval.HighPart = whenf.dwHighDateTime; tempval.LowPart = whenf.dwLowDateTime; tempval.QuadPart += seconds * 10000000LL; // 100 nanosecond units whenf.dwHighDateTime = tempval.HighPart; whenf.dwLowDateTime = tempval.LowPart; FileTimeToSystemTime(&whenf, &when); sprintf(timestr, "%04hu-%02hu-%02huT%02hu:%02hu:%02huZ", when.wYear, when.wMonth, when.wDay, when.wHour, when.wMinute, when.wSecond); } ``` Compile with MSVC (or MinGW GCC if you have all dependencies). Program will start and register a one-time task with the Windows task scheduler to start itself 5 seconds later (Control Panel -> Administrative Tools -> Task Scheduler to view, task is named "Restarter"). Program will pause for 5 seconds to give you a chance to kill it before it creates the task. Challenge Requirements: * **Starts itself again when finishes.** Yes. Task is scheduled just prior to program exit. * **No more than one instance of the program running at same time.** Yes. Program exits fully and does not run for 5 seconds. It is started by the scheduler. * **You can ignore any instance that is manually started by user during your cycle.** Yes, as a side-effect of using a constant task name. * **As long as it is guaranteed that it starts again.** Yes, provided that Task Scheduler is running (it is in a standard Windows configuration). * **The only way to stop the cycle is to kill the process.** Yes, the process can be killed during the 5 second window while it is running. The program deletes the task prior to the 5 second delay, killing it at this time will not leave a stray task in the scheduler. * **Your solution should not involve restarting of the environment** Yes. By the way, if anybody ever wondered why Windows applications used to be so unstable (before the advent of .NET and C#), this is one reason why. The amount of error handling required (had I included it), resource management, and verbosity sets up very error-prone situations if a programmer is even the slightest bit lazy (the above code is extremely lazy). A much easier and shorter alternative is to invoke schtasks.exe. I have submitted [a version with that in a .BAT script](https://codegolf.stackexchange.com/a/21733/16504) as well. [Answer] # BBC BASIC - a tribute to Snow Patrol Emulator at bbcbasic.co.uk This one's a little different. It prints a verse of the song "Run" and plays an arpeggio of the chords so you can sing along. It was inspired by the fact that the command to execute (and therefore the last line of the program) is of course RUN. All variables are cleared at the start of the program, so it takes the screen colour left behind by the previous iteration to decide what verse to print next. ``` 5 C=POINT(0,0) MOD 4 10 COLOUR 129+C 15 CLS 20 RESTORE 110+C 25 READ A$ 30 PRINT A$ 35 FORK = 1 TO 4 40 RESTORE K+100 45 READ P 50 FORM= 1 TO 8 55 SOUND 1,-15,P,7 60 SOUND 1,-15,P-20,7 65 NEXT 70 NEXT 101 DATA 100 102 DATA 128 103 DATA 136 104 DATA 120 110 DATA Light up light up - As if you have a choice - Even if you can not hear my voice - I'll be right beside you dear. 111 DATA Louder louder - And we'll run for our lives - I can hardly speak - I understand - Why you can't raise your voice to say. 112 DATA Slower Slower - We dont have time for that - All I want is to find an easier way - To get out of our little heads. 113 DATA Have heart my dear - We're bound to be afraid - Even if its just for a few days - Makin' up for all of this mess. 120 RUN ``` **OUTPUT (montage of 4 different screen shots)** ![enter image description here](https://i.stack.imgur.com/8u5xn.png) [Answer] # HTML/JavaScript: ``` <form /><script>document.forms[0].submit()</script> ``` The code triggers the destruction of the page it is running on, then the re-creation of another instance of itself when the browser loads the page anew. AFAIK, the only way out is to kill the tab the page is running in. EDIT: as per popular request, a valid HTML5 code: ``` <!doctype html><meta charset=utf-8><title> </title><form></form> <script>document.forms[0].submit()</script> ``` [Answer] ## C This program acts like a lot of malware. Just before it closes, it creates a shell script in the /tmp directory. It forks to start the shell script, which lets the original program close and cancel the original PID. After a brief period of time (2 seconds) the shell script starts a new process with the program. For brevity, the program location is hard-wired as '/tmp/neverend/'. ``` #include <stdio.h> #include <stdlib.h> #include <fcntl.h> void rebirth(){ char t[] = "/tmp/pawnXXXXXX"; char* pawnfile = mktemp(t); if(pawnfile){ int fd = open(pawnfile, O_RDWR|O_CREAT); const char msg[]="sleep 2\n/tmp/neverend\n"; if(fd>0){ int n = write(fd, msg, sizeof(msg)); close(fd); pid_t pid = fork(); if(pid==0){ char* args[3] = {"bash", pawnfile, NULL}; execvp(args[0], args); } } } } int main(int argc, char* argv[]){ printf("Starting %s\n", argv[0]); atexit(rebirth); printf("Exiting %s\n", argv[0]); } ``` There is only ever one 'neverend' process running at a time. Each new process gets a new PID. The easiest way to kill this is to delete the executable. If you wanted to make it more malignant, you could copy both the executable and the script to make sure there are multiple copies on the program on disk at any time. [Answer] ## Perl ``` `perl -e"kill 9,$$"|perl $0` ``` The script issues a system command to kill itself, and pipe the result into another instance of itself. The Perl interpreter is used to do the killing, for cross platform reasons. Stop the madness by deleting the script. [Answer] # Atari 8-bit Basic ``` 1L.:R. ``` Tokenizes to: ``` 1 LIST : RUN ``` Internally it is clearing the internal structures, essentially wiping out the program, before running it again from the listing. This is fundamentally different from: ``` 1L.:G.1 ``` Which tokenizes to: ``` 1 LIST : GOTO 1 ``` This is a basic infinite loop. When you run them, you see the difference in speed (first is slower). [Answer] On an IBM Mainframe running z/OS, you run a utility which copies a dataset (file) to another dataset (file). The input is the source of the JCL (Job Control Language) that you have submitted to cause it to run. The output is the Internal Reader (INTRDR). You will also need to ensure that your system does not allow the running of multiple identical jobnames. Good to use a job-class which only has one initiator (place where a JOB can run in batch). There are no PIDs involved (in z/OS), so fails the challenge set. You halt the process by draining and/or flushing. If something has gone wrong, by draining and/or flushing, swearing, kicking, attempting a warm-start and finally by a cold-start or hitting the Big Red Button (and shooting the programmer). I may have exaggerated along the way, but don't try this at work... Example using SORT. Details on the JOB card are very site-dependant. Site policy may either forbid or prevent the use of INTRDR. A specific class may be required to use the INTRDR. If your site policy forbids its use ***do not use it*** unless you want to take your belongings for a walk in a cardboard box. Although there are good uses for the INTRDR, ***do not use it for this purpose***. You won't even have a chance to get your box. ``` //jobname JOB rest is to your site standards //* //STEP0100 EXEC PGM=SORT //SYSOUT DD SYSOUT=* //SORTOUT DD SYSOUT=(,INTRDR) minimum required, site may require more //SYSIN DD * OPTION COPY //SORTIN DD DISP=SHR,DSN=YOUR.LIBRARY.WITHJOB(JOBMEMBR) ``` Other utilities are available. A quick program would be easy to do as well, just read a file, write a file. If you want an example of this going wrong, try: <http://ibmmainframes.com/viewtopic.php?p=282414#282414> The traditional way to copy a dataset is to use the IBM utility IEBGENER, as ugoren alludes in their comment. However, these days, many sites will have IEBGENER "aliased" to ICEGENER. ICEGENER will, if it can, use IBM's DFSORT (or its rival SyncSort) to do a copy, because the SORT products are much more hihgly optimised for IO than IEBGENER is. I'm just cutting out the middle-man by using SORT. If you work at an IBM Mainframe site, you know the format of the JOB card that you should use. The minimal JOB card is as I have shown, without the comment. The comment will be important, because you may be supposed to be supplying accounting information, for instance. The jobname will likely have a site-specific format. Some sites ban, or prevent, the use of the INTRDR. Be aware. Some sites allow multiple jobs with the same name to run at the same time. Be aware. Although unless you are a System's Programmer you can't set up such a class, you should look for a class which allows only one initiator. With that, the process is fairly safe - but be absolutely sure about that the class is working as described. Test. Not with this job. If you are a System's Programmer, you know not to do anything outside of your remit. 'nuff said. With one job with the same name allowed at the same time and a single initiator, this will be a constant stream of job start/finish next job start/finish - until you fill the spool (another bad thing to do) with the output from thousands of jobs (or run out of job numbers). Watch a JES Console for warning messages. Basically, don't do this. If you do do it, don't do it on a Production machine. With a little brushing up, I'll consider another Answer for how to do it on another IBM Mainframe operating system, z/VSE... z/VSE uses JCL. z/OS uses JCL. They are different :-) [Answer] # Windows Task Scheduler (.BAT) Windows batch script. Meets all challenge requirements. As far as I can see this is the only Windows solution so far that meets all requirements and has no nonstandard dependencies (my other solution is similar but requires compilation). ``` @ECHO OFF SETLOCAL schtasks /Delete /TN RestarterCL /F ECHO Close this window now to stop. TIMEOUT /T 5 FOR /f "tokens=1-2 delims=: " %%a IN ("%TIME%") DO SET /A now=%%a*60+%%b SET /A start=%now%+1 SET /A starth=100+(%start%/60)%%24 SET /A startm=100+%start%%%60 SET /A end=%now%+3 SET /A endh=100+(%end%/60)%%24 SET /A endm=100+%end%%%60 schtasks /Create /SC ONCE /TN RestarterCL /RI 1 /ST %starth:~1,2%:%startm:~1,2% /ET %endh:~1,2%:%endm:~1,2% /IT /Z /F /TR "%~dpnx0" ENDLOCAL ``` Program behaves similarly to [my C++/COM answer](https://codegolf.stackexchange.com/a/21726/16504). Program will start and register a one-time task with the Windows task scheduler to start itself up to 60 seconds later (Control Panel -> Administrative Tools -> Task Scheduler to view, task is named "Restarter"). Program will pause for 5 seconds to give you a chance to kill it before it creates the task. Makes use of command line Task Scheduler interface `schtasks.exe`. Arithmetic in script is to compute time offsets while keeping the time valid and in HH:MM format. Challenge Requirements: * **Starts itself again when finishes.** Yes. Task is scheduled just prior to program exit. * **No more than one instance of the program running at same time.** Yes. Program exits fully and does not run for ~60 seconds. It is started by the scheduler. * **You can ignore any instance that is manually started by user during your cycle.** Yes, as a side-effect of using a constant task name. * **As long as it is guaranteed that it starts again.** Yes, provided that Task Scheduler is running and schtasks.exe is present (both true in default Windows configurations). * **The only way to stop the cycle is to kill the process.** Yes, the process can be killed during the 5 second window while it is running. The program deletes the task prior to the 5 second delay, killing it at this time will not leave a stray task in the scheduler. * **Your solution should not involve restarting of the environment** Yes. Note: Due to limited command line interface, restart time must be specified in minutes and *the task will not restart on laptops without the AC adapter plugged in* (sorry). [Answer] # Python (72 bytes) ``` import os os.system('kill -9 %s && python %s' % (os.getpid(), __file__)) ``` Could be make smaller I guess. First, by hardcoding the name of the file (instead of using `__file__`). But here, you can put this code in a file and run it, whatever its name is :) [Answer] ## Unix shell I haven't seen many solutions yet that rely on an unrelated program to restart it. But this is exactly what the `at(1)` utility was made for: ``` echo "/bin/sh $0"|at now + 1 minute ``` It's hard to actually catch the program running, since it only runs once per minute and exits so quickly. Fortunately the `atq(1)` utility will show you that it's still going: ``` $ atq 493 Fri Feb 21 18:08:00 2014 a breadbox $ sleep 60 $ atq 494 Fri Feb 21 18:09:00 2014 a breadbox ``` And `atrm(1)` will allow you to break the cycle: ``` $ atq 495 Fri Feb 21 18:10:00 2014 a breadbox $ atrm 495 $ atq ``` You can replace `1 minute` with `1 hour`, or `1 week`. Or give it `1461 days` to have a program that runs once every 4 years. [Answer] **PowerShell** I am abusing (and possibly breaking) my own rule. ``` [System.Threading.Thread]::Sleep(-1) ``` It takes infinite amount of time to restart itself. It can be killed by killing the host process. Just wait and see ;) [Answer] # Bash ``` echo -e "$(crontab -l)\n$(($(date "+%M")+1)) $(date '+%H %e %m * /repeat.sh')" | crontab - ``` Save this as repeat.sh in the / directory and give it execute permission. It can be killed by deleting the file This works by putting an entry in the crontab to run it 1 minute later. [Answer] # Visual Base 6 :) ``` Sub Main:Shell "cmd ping 1.1.1.1 -n 1 -w 500>nul&&"""&App.Path &"\"&App.EXEName& """":End Sub ``` To run, create a new project, add a module with this code, set the start-up object to "Sub Main", compile, and then run the executable. --- ## More readable version: ``` Sub Main() Call Shell("cmd ping 1.1.1.1 -n 1 -w 3000 > nul && """ & App.Path & "\" & App.EXEName & """") End Sub ``` [Answer] # JavaScript Without "going to the network" when not necessary :-) JavaScript's event loop scheduling allows us to write programs that fulfill the given requirements very easily: ``` (function program() { // do what needs to be done setTimeout(program, 100); })(); ``` This "restarts" the `program` function at a 10-times-per-second pace. It is guaranteed by JavaScript's nature that only a single task will be running at the same time, and it does not "restart the environment" as in "reload the page". [Answer] **HTML / JAVASCRIPT** HTML FILE a.html ``` <script>window.location = "a.html"</script> ``` [Answer] ## **Bash** Longer than it has to be, but I'm tired, and don't care :) ``` while true; do sleep 1; done; bash $0; ``` You said that it has to restart itself when it finishes, you didn't specifically say that it had to do so repeatedly, or indefinitely. Also, you said that it should never have two instances running at once... it never will. ;) There are any great number of ways to do this. My personal favorite, would be to do something like send a packet somewhere distant, and then (via any number of methods), have the response trigger the process. [Answer] **Android:** An alarm will restart the Activity after 1 second ``` public class AutoRestart extends Activity { @Override public void onCreate() { finish(); } @Override public void onDestroy() { Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass()); restartServiceIntent.setPackage(getPackageName()); PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmService.set( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent); super.onDestroy(); } } ``` [Answer] # C + MPI Environment mpifork.c: ``` #include <stdio.h> main(int argc, char * argv[]) { srand(time(NULL)); int host = rand()%(argc-1)+1; FILE * logFile = fopen("mpifork.log", "a"); if(logFile == NULL){ fprintf(stderr, "Error: failed to open log file\n"); } else { fprintf(logfile, "Jumping to %s\n", argv[host]); char * args[argc+5]; args[0] = "mpirun"; args[1] = "-H"; args[2] = argv[host]; args[3] = argv[0]; for(host = 0; host < argc-1; host++) args[host+4] = argv[host+1]; args[argc+3] = NULL; execvp("mpirun", args); fprintf(stderr, "exec died\n"); perror("execvp"); } } ``` You must have OpenMPI or some other MPI implementation installed. Compile with ``` mpicc -o mpifork mpifork.c ``` Now that I think about it, there's no reason you have to use mpicc - gcc or whatever compiler will work. You just have to have mpirun. ``` gcc -o mpifork mpifork.c ``` To run it, you should probably include the full path name, and include a list of hosts. For example, I added some entries in /etc/hosts that all pointed to localhost, and ran it like this: ``` /home/phil/mpifork localhost localhost1 localhost2 localhost3 localhost4 ``` The executable must be in the same directory on any machine that you want to run this on. --- Essentially, this takes a list of hosts provided on the command line, selects one of the hosts, and launches the executable on the target host with the same arguments. If everything goes perfectly, mpirun will call itself over and over on different machines (or the same machine if you only provide 'localhost'. The executable itself (mpifork) does terminate - after calling `execvp`, it is no longer executing on the first machine. If you wanted to be evil, you could instead make this launch on *every* machine, by including the full list of hosts that is provided on the command line in `args`. That would re-spawn a copy of itself on every machine, over and over - a cluster forkbomb. However, in this form, I'm pretty sure this satisfies the rules. [Answer] # x86 Assembly Not entirely sure this fits your criteria as it doesn't spawn a new process, but here it is anyway. The program will show a message box, allocate some memory, copy its own code section into the allocated memory, and then jump to that location starting the cycle over. It should run until malloc fails. ``` format PE GUI 4.0 entry a include 'include/win32a.inc' section '.text' code readable executable a: push 0 push _caption push _message push 0 call [MessageBoxA] push b-a call [malloc] push b-a push a push eax call [memcpy] call eax b: section '.data' data readable writeable _caption db 'Code challenge',0 _message db 'Hello World!',0 section '.idata' import data readable writeable library user,'USER32.DLL',\ msvcrt,'msvcrt.dll' import user,\ MessageBoxA,'MessageBoxA' import msvcrt,\ malloc,'malloc',\ memcpy,'memcpy' ``` Compiled with fasm. [Answer] # Linux upstart init Given the strictest reading of the question, I think this is impossible. In essence it is asking for a program to spontaneously start with the help of no other running programs. There are some `at` and `chron`-based answers, but with the strictest reading, `atd` and `anacron` are supplementary programs which are running all the time, so they may be disqualified. A related approach, but a little lower level is to use Linux's `init`. As root, add this .conf file to `/etc/init/`: ``` description "forever" start on runlevel [2345] stop on runlevel [!2345] respawn exec sleep 10 ``` Then have `init` re-read its .conf files: ``` sudo telinit 5 ``` This will start a `sleep` process which will live for 10 seconds, then exit. `init` will then respawn the `sleep` once it detects the previous one has gone away. Of course this is still using `init` as a supplementary program. You could argue that `init` is a logical extension of the kernel and will *always* be available in any Linux. If this is not acceptable, then I guess the next lower-level thing to do would be to create a kernel module which respawns a userspace process (not sure how easy that is). Here it can be argued that the kernel is not a process, and therefore not a program (supplementary). On the other hand, the kernel is a program in its own right, from the point of the CPU. [Answer] # TI-BASIC: 5 characters call it `prgmA` ``` :prgmA ``` ]
[Question] [ So, I wrote myself a one-liner which printed out a snake on the console. It's a bit of fun, and I wondered how I might condense my code... Here's a (short) example output: ``` + + + + + + + + + + + + + + + + + + + + ``` Here's the specs: * In each line, a single non-whitespace character (whichever you like) is printed to the console, initially with 29 to 31 spaces padding to the left of it. * Each iteration, a random decision is made between these three actions + The amount of padding decreases by 1 + The amount of padding remains the same + The amount of padding increases by 1 Do this 30 times, to print 30-segment long a snake to the console. The shortest answer in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes ``` 30DF2Ý<+ΩD0sú, ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f2MDFzejwXBvtcytdDIoP79L5/x8A "05AB1E – Try It Online") Uses `0`. ### Explanation ``` 30DF2Ý<+ΩD0sú, 30D # Push 30 to the stack (One for the amount of iterations we are going to perform and one for the initial padding) F # Pop one of the 30s and perform the following that many times... 2Ý # Push [0,1,2] ... < # and create [-1,0,1] from that + # Add the last padding to every entry (e.g. 30 in the beginning resulting in [29,30,31] Ω # Pick one of the results at random ... D # and push it to the stack twice 0 # Push 0 (Any character will work fine here) ... sú # and pad it with the randomly chosen amount of spaces in the front , # Finally print the result with a trailing newline ``` [Answer] # [Random Brainfuck](https://github.com/TryItOnline/brainfuck), ~~123 122~~ 121 bytes ``` +[--[<]>>+<-]>+[->+>+>+<<<]++++++++++>>++<[>>[->+<<.>]>[-<+>]>?>+++<[>->+<[>]>[<+>-]<<[<]>-]>-->,<[-<<<+>>>]<<<<+.-<<.>-] ``` [Try it online!](https://tio.run/##PYxBCsMwDAQfpK5fsGwfYnRIGwIl1AVD3u@sLpUOkmbEzm3svy9ec/uM43qfa0UHOlMKIuVLUU0y41@2wS6VJZvSG8PjaVGmeC9siiQr0XGAHvQrjSVzLw2VgFzrBg "Random Brainfuck – Try It Online") Random Brainfuck is an extension of brainfuck, with the helpful addition of the `?` command, which sets the current cell to a random byte. This prints a snake made of `!`s, which looks more like footsteps than a snake funnily enough. ### How It Works: ``` +[--[<]>>+<-]>+ Create the value 30 [->+>+>+<<<] Copy it three times ++++++++++ Create a newline cell >>++< Adds 2 to the second copy to make it a space and move to the counter [ While counter >>[->+<<.>]>[-<+>] Print out the padding cell number of spaces ?>+++<[>->+<[>]>[<+>-]<<[<]>-] Get 3-(random byte%3) >-->,<[-<<<+>>>] Add (result-2) to the padding cell <<<<+.-< Print an exclamation mark <<. Print a newline >- Decrement counter ] end loop ``` Another solution that sticks to the *letter* of the question, rather than the spirit. ### 87 bytes ``` +[--[<]>>+<-]>+[->+>+>+<<<]++++++++++>++>[>[->+<<<.>>]>[-<+>]?[,<+>]?[,<->]<<<+.-<.>>-] ``` [Try it online!](https://tio.run/##PYlRCoAwDEMPVLMTlHiQ0o@pCCJOGHj@2n1oEkja12vb7gtLr0fbn/WMEANMnRSFMy/KsKq6/GLGOFj@C@m5VeizTV@BnkwKBodHvA "Random Brainfuck – Try It Online") This one is heavily biased towards leaving the padding alone, but increasing or decreasing the padding are both equally possible. Each one has a slightly less than 1 in 256 chance to happen. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~61~~ ~~58~~ 56 bytes Answer edited to reflect rules changes... ``` i;f(s){for(s=i=31;--i;printf("%*d\n",s+=1-rand()%3,8));} ``` [Try it online!](https://tio.run/##HclBCoAgEEDRfacQQZiphMJNIN6kjWjGLLJQd9LZTVp9@M/J07nWSAfIWMOdIBsyatVSkn4SxRKAi9Hvkc95MqtMNnpAoeYNUb/tshQBWR0Yyz8Vug5YuvUToOdtHw "C (gcc) – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes ``` 30* + -29{¶<`^ S,2@1` ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8vYQEtBm0vXyLL60DabhDguBa5gHSMHw4T//wE "Retina – Try It Online") ### Explanation ``` 30* + ``` Initialise the working string to the first line, i.e. 30 spaces and a `+`. ``` -29{¶<`^ ``` There's a space on the second line. `-29{` wraps the remainder of the program in a loop, which is run 29 times. `¶<` prints the working string at the beginning of each loop iteration with a trailing linefeed. The atomic stage itself inserts a space at the beginning of the string (the basic idea is to insert one space, and then randomly remove 0–2 spaces, because that's a byte shorter than randomly choosing between deletion, inserting and no-op). ``` S,2@1` ``` This matches the empty regex against the input, which gives us every position between characters (and the start and end of the string). Then `,2` keeps only the first three matches, i.e. the matches after zero, one and two spaces. `@` selects a random one of those three matches. Then the split stage (`S`) splits the input around that match. And the `1` tells it to keep only the second part of the split. In other words, we discard everything up to our random match. The 30th line, which is the result of the final loop iteration, is printed implicitly at the end of the program. [Answer] # JavaScript (ES8), ~~63~~ ~~62~~ 60 bytes Includes a trailing newline. `*2-1` could be replaced with `-.5` for a 1 byte saving but the chances of each line being the same length as the previous line would be greatly increased. Of course, as "random" isn't defined in the challenge, the RNG *could* be replaced with `new Date%3-1` for a total byte count of [55](https://tio.run/##BcFBCoAgEADAe6/oEuwiStEt2LrUP1bSohCNlLLX28ypHx3X@7iS9MHYsgYfg7PKhR2gbASZPupbpDFPzOrSZvEGPkHevvWsk2162aFgUbHYQMqMA3NBQCw/). ``` f=(x=y=30)=>x?``.padEnd(y+=Math.random()*2-1)+`+ `+f(--x):`` ``` Saved a byte thanks to someone who deleted their comment before I could catch the name. I'd actually tried it this way with `repeat` and `padStart` but didn't think to try `padEnd` - don't know why! ``` o.innerText=( f=(x=y=30)=>x?``.padEnd(y+=Math.random()*2-1)+`+ `+f(--x):`` )() ``` ``` <pre id=o> ``` --- ## Bonus For the same number of bytes, here's a version that takes the number of starting spaces & iterations as input. ``` f=(x,y=x)=>x?``.padEnd(y)+`+ `+f(--x,y+Math.random()*2-1):`` ``` ``` o.innerText=( f=(x,y=x)=>x?``.padEnd(y)+`+ `+f(--x,y+Math.random()*2-1):`` )(i.value=30);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] # VBA, ~~60~~ ~~59~~ 49 Bytes ``` For l=1To 30:?Spc(30+i)"+":i=i+Sgn(Rnd()-.5):Next ``` Paste it in the Immediate window and hit enter. (Make sure explicit declaration is turned off!) *Far* more likely to move than to stay in a line (i.e. actions are not equally weighted) but that was not a specified requirement (Fortunately!) **{EDIT}** *Saved 1 byte by removing the space between `=1` and `To`* **{EDIT2}** *Saved **10** bytes thanks to remoel's comment* Old Versions: ``` 'V1 i=30:For l=1 To 30:?String(i," ")&"+":i=i+Sgn(Rnd()-.5):Next 'V2 i=30:For l=1To 30:?String(i," ")&"+":i=i+Sgn(Rnd()-.5):Next ``` [Answer] # C# (.NET Core), ~~112~~ ~~110~~ ~~106~~ ~~100~~ ~~99~~ 98 bytes ``` v=>{var r="";for(int t=30,i=t;i-->0;r+="+\n".PadLeft(t+=new System.Random().Next(3)-1));return r;} ``` -1 byte thanks to *@raznagul*. -1 byte thanks to *@auhmaan*. **Explanation:** [Try it online.](https://tio.run/##TY6xqsJAEEV7v2JItUtMUCzXTSNYPR@ihY3NupnISpyF2UlUJN8eY/HgtZdzD8enwkfG0bcuJdi9ZwBJnAQPfQw17Fwgpb8rwPGVBO/ltiO/jpcbeplPLAe6VtCAhbG31bt3DGyzzDSRVSABsavFPFgxoSiqheHcZvmZsnLv6h9sREluCR9/8oOjOt6VLn/xKWqli6XWhlE6JmAzjN8O879mEynFFssTB0HVKOradrpMyDAbxg8) ``` v=>{ // Method with empty unused parameter and no return-type var r=""; // Result-string, starting empty for(int t=30, // Temp-integer, starting at 30 i=t;i-->0; // Loop 30 times r+= // Append the result-String with: "+\n" // The character and a new-line, .PadLeft( // left-padded with `t` spaces, t+=new System.Random().Next(3)-1)); // after `t` first has been changed with -1, 0, or 1 randomly return r;} // Return the result-string ``` [Answer] # C, 56 bytes ``` n;f(p){n>29?n=0:f(printf("%*d\n",n++?p-rand()%3:31,0));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/POk2jQLM6z87I0j7P1sAKyCvKzCtJ01BS1UqJyVPSydPWti/QLUrMS9HQVDW2MjbUMdDUtK79D1SkkJuYmaehyVXNpQAExWA1JZm5qRogFWCxNA0go/Y/AA) **Explanation:** ``` n; // As a global variable, n is initialized to zero. f(p) { // Call the function recursively until n > 29. n > 29 // At the end, set n back to zero. ? n=0 // On the first iteration, n == 0 and p has an indeterminate value. // 'n++ ? p-rand()%3 : 31' returns 31 (without reading p), and thus // 30 spaces get printed. printf() returns the number of characters // printed, 32 (30 spaces + '0' + '\n'). // On subsequent iterations, p has the value the previous printf // call returned, which is the padding on last iteration + 2. Also, // n > 0, so the same expression now returns p-rand()%3, and thus // the padding changes either by -1, 0, or 1 spaces. The function // is again called with the value of the current line's padding + 2. : f(printf("%*d\n", n++ ? p-rand()%3 : 31, 0)); } ``` # [C (gcc)](https://gcc.gnu.org), 55 bytes ``` n;f(p){n=n<30&&f(printf("%*d\n",n++?p-rand()%3:31,0));} ``` Depends on **f** "returning" the value assigned to **n** in the function, which is undefined behaviour, but works consistently with gcc when no optimizations are enabled. [Try it online!](https://tio.run/##S9ZNT07@/z/POk2jQLM6zzbPxthATQ3IKcrMK0nTUFLVSonJU9LJ09a2L9AtSsxL0dBUNbYyNtQx0NS0rv0PVKSQm5iZp6HJVc2lAATFYDUlmbmpGiAVYLE0DSCj9j8A) [Answer] # Java 8, ~~89~~ 87 bytes First golf, I'm sure it could be much better.. Edit: Fixed first line thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox). ``` l->{for(int a=31,b=a;--a>0;){System.out.printf("%"+b+"c\n",'+');b+=2-Math.random()*3;}} ``` [Try it online!](https://tio.run/##NY5PD4IwDMXvfoqGxLiJIyrHBY/cOJl4UQ9lMEXHRmCYGMJnx/qvafPSpnnvd8MHCteU9lbcJ2Ww6yDDyg4zgMr6stWoSkjfK9XDVQUodniL4ZKOIw1159FXClLQkMBkxG7QrmVkAJjEm1WeoBQCd2vJh/2z82Udud5HTUsfmgXzIMzDQJ1ssFqECy7zMNmKDP01atEWrmZ8GctxnOQ3rOlzQ2G/zA9TTchs78nvcjwj/@LqSDHbmz/oOL0A "Java (OpenJDK 8) – Try It Online") ``` l->{ //Begin lambda for(int a=31,b=a;--a>0;) //Initialise vars, loop through 30 lines { System.out.printf("%"+b+"c\n",'+'); //Print result b+=2-Math.random()*3; //Change padding by -1, 0, or 1 } ``` [Answer] # [Python 2](https://docs.python.org/2/) , ~~83~~ ~~65~~ 64 bytes Straightforward approach: ``` import os k=30 exec"print' '*k+'+';k+=ord(os.urandom(1))%3-1;"*k ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocWXbGhtwpVakJisVFGXmlagrqGtla6trq1tna9uClALFNHQNdQw1rZW0sv//BwA "Python 2 – Try It Online") Thanks to @Rod for saving some bytes! Thanks to @ovs for -1 byte! Edit: changed variable name and output string to the letter 's' # More snake-like output for 88 bytes: ``` from random import* s=[30,0] exec"print' '*sum(s)+'(S)'[s[-1]+1];s+=[randint(-1,1)];"*30 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 20 bytes *1 byte saved thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn)* ``` ↑'+'↑⍨¨-+\30,2-?29⍴3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEx61TVTXVgeSj3pXHFqhqx1jbKBjpGtvZPmod4vx//8A "APL (Dyalog Unicode) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~14~~ 11 bytes ``` × ³⁰Fⅈ✳~‽³+ ``` [Try it online!](https://tio.run/##JcoxCoAwDADA3VeETgkqCI5u4iwiDq6lVgy0DdSiz4@DN5@7bHZig@qSORXcOPobDZgG@o5oqE7JgDsSwR8mzt4VloQjl5dvP0vB1aZDIvZE1ICpDQ2q2j7hAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` × ³⁰ Print 30 spaces (forces the desired indentation) Fⅈ Repeat the same number of times ✳~‽³ Move a random downward direction after printing + Print a `+` ``` Would be only ~~10~~ 8 bytes if there was no initial indentation requirement. [Answer] # PHP, 61 bytes ``` for($p=32;$i<30;$i++)echo str_pad("+ ",$p+=rand(-1,1),' ',0); ``` [Try it online!](https://tio.run/##K8go@P/fxr4go4CLKy2/SEOlwNbYyFol08bYAEhqa2umJmfkKxSXFMUXJKZoKGlzKemoFGjbFiXmpWjoGuoYauqoK6jrGGha//8PAA "PHP – Try It Online") [Answer] # Perl, 36 bytes ``` perl -E '$#a=29;map{$#a+=rand(3)-say"@a -"}@a' ``` [Answer] # Java 8, ~~131~~ ~~129~~ ~~127~~ ~~126~~ ~~119~~ ~~108~~ 101 bytes ``` v->{String r="";for(int i=30,j,t=i;i-->0;r+="+\n")for(j=t+=Math.random()*3-1;j-->0;r+=" ");return r;} ``` **Explanation:** [Try it online.](https://tio.run/##PY/BasMwDIbvewrhk73UoaNH475Bexns0u2gOe5mN5GDowRKybNnDg0D6SDpR//3R5xQp95TbG6La3EY4ISBHi8AgdjnKzoP53UEeOcc6Aec/EihgUmZsp1LlxoYOTg4A4GFZdLHxybOVghzTVmWbxDsYb@LO7bBBK2Pe5MrK6pPEmpVRMuVPSH/1hmpSZ1Urwf9ZuK/EoQy2fOYCbKZF/O07sfvtlhvBNOK1pUE8glw@UK10d8H9l2dRq77cmFJtZM0tq3agszLHw) ``` v->{ // Method with empty unused parameter and String return-type String r=""; // Result-String, starting empty for(int i=30,j,t=i; // Two index integers, and a temp integer (starting at 30) i-->0; // Loop 30 times: r+="+\n") // After every iteration: Append the character and a new-line for(j=t+=Math.random()*3-1; // Change `t` with -1, 0, or 1 randomly j-->0;r+=" "); // And append that many spaces to the result-String return r;} // Return the result-String ``` **Old 119 byte answer:** ``` v->{String s="",r=s;int i=90,t=30;for(;i-->t;s+=" ");for(;i-->0;t+=Math.random()*3-1)r+=s.substring(t)+"+\n";return r;} ``` **Explanation:** [Try it online.](https://tio.run/##RY/BasMwEETv/YpFJ6mOhEtORSh/kFwCubQ9KLLSKrUlo10ZSvC3u0pjKOwedmYZ3lztZGUafbx234vrLSLsbYi3J4AQyeeLdR4O9xPgSDnET3D8lEIHk9BVnevWQbIUHBwggoFlkrvb@oyGsU02qGsaBPPabshsW31Jmesg5Y40NoYBE/9Sq6kxe0tfKtvYpYGL5618EbkxqLCc8S@Yk2hY8x6Zzp5KjpD1vOgHzFjOfYVZmaY77FA78QfS24cVa58fJD@oVEiN1SEeleOx9L1Yq83LLw) ``` v->{ // Method with empty unused parameter and String return-type String s="", // Temp-String, starting empty r=s; // Result-String, starting empty int i=90,t=30; // Temp integer, starting at 30 for(;i-->t;s+=" "); // Fill the temp String with 60 spaces for(;i-->0; // Loop 30 times: t+=Math.random()*3-1// After every iteration: Change `t` with -1, 0, or 1 randomly r+=s.substring(t) // Append the result with `60-t` amount of spaces +"+\n"; // + the character and a new-line return r;} // Return the result-String ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` 30:(kɽ℅+:×꘍, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=30%3A%28k%C9%BD%E2%84%85%2B%3A%C3%97%EA%98%8D%2C&inputs=&header=&footer=) ``` 30: # Push 30 twice ( # Iterate over one copy (30 times) + # Increment the number on the stack (initially 30) by... ℅ # A random choice from kɽ # [-1, 0, 1] : # Duplicate ×꘍ # Prepend that many spaces to an asterisk , # And output, leaving the number on the stack ``` [An alternative](https://lyxal.pythonanywhere.com?flags=j&code=30%3A%C6%9B3%CA%81%E2%80%B9%E2%84%85%3B%C2%A6%2B%C3%97%EA%98%8D&inputs=&header=&footer=) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs an array of lines. The first line can be removed, saving 3 bytes, to allow the number of starting spaces & iterations to be taken as input. ``` 30 °ÆQùU±Ó3ö ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MzAKsMZR%2bVWx0zP2&input=LVI) or [try it with input](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sMZR%2bVWx0zP2&input=MzAKLVI) ``` 30\n°ÆQùU±Ó3ö 30\n :Assign 30 to variable U ° :Postfix increment U Æ :Map the range [0,30) Q : Quotation mark ù : Left pad with space to length U± : Increment U by Ó : Bitwise NOT of the negation of (i.e., decrement) 3ö : Random integer in the range [0,3) ``` [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~69~~ 67 bytes ``` cat(sprintf(paste0("% ",cumsum(c(30,sample(3,29,T)-2)),"s"),"+\n")) ``` Thanks to [Zahiro Mor](https://codegolf.stackexchange.com/users/65449) for 2 extra bytes! [Try it online!](https://tio.run/##K/r/PzmxRKO4oCgzryRNoyCxuCTVQENJVUFJJ7k0t7g0VyNZw9hApzgxtyAnVcNYx8hSJ0RT10hTU0epWAlIaMfkKWlq/v8PAA "R – Try It Online") [Answer] # [Swift](https://developer.apple.com/swift/), 101 bytes ``` import UIKit var g=29;for _ in 0...g{print((0..<g).map{_ in" "}.joined(),0);g+=Int(arc4random()%3)-1} ``` ## Explanation A full program. This uses a rather odd trick: `arc4random()` is a member of the `Darwin` module, but `UIKit` also comes with this function installed, so it saves a byte :) Also uses one of my [Swift golfing tips](https://codegolf.stackexchange.com/a/137931/59487) for repeating strings an arbitrary number of times. ``` import UIKit // Imports the UIKit module, necessary for the RNG. var g=29; // Declares an integer variable g by assigning it to 30. for _ in 0 ... g { // Execute the code block 30 times (for each integer in [0; g]): print( // Output the following: (0..<g).map // For each integer in [0; g)... {_ in" "} // ... return a literal space character. .joined() // ... And join the result to a single string. ,0 // Also print a "0" preceded by a single space (g starts from 29). ); g+= // Increment the variable g by... arc4random()%3 // ... A random integer, modulo 3... Int(...)-1 // ... Casted to an integer (yes, this is needed!) and decremented. } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` 1ŒRX+ 30ǒС⁶ẋ;€0Y ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//McWSUlgrCjMww4figJnDkMKh4oG24bqLO@KCrDBZ//8 "Jelly – Try It Online") The chosen character is **0**. If returning a list of list of characters is allowed, then the `Y` can be dropped and the submission can be turned into a niladic chain for **[17 bytes](https://tio.run/##AS0A0v9qZWxsef//McWSUlgrCjMww4figJnDkMKh4oG24bqLO@KCrDD/wqLFkuG5mP8)**. [Alternative](https://tio.run/##ASgA1/9qZWxsef//M1hD4oCYKwozMMOH4oCZw5DCoeKBtuG6izvigqwwWf//). ## How it works ``` 30ǒС⁶ẋ;€0Y | Niladic main link. 30 | Starting from 30... ǒС | ... Repeat the helper link 29 times and collect the results in a list. | (This list includes the first 30, so there are actually 30 numbers). ⁶ẋ | Repeat a space that many times, for each item in the list. ;€0 | Append a 0 to each. Y | And join by newlines. -------------+ 1ŒRX+ | Monadic helper link. Alternatively, you can use µ1ŒRX+µ instead of the Ç. 1 | The literal one. ŒR | Symmetric range from –1 to 1. X+ | Choose a random number therein and add it to the argument. ``` # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes Combining mine, Erik’s and Jonathan’s solutions, we can golf this down to 16 bytes. The chosen character is **1**. ``` ’r‘X 30ǒСṬ€o⁶Y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8yiRw0zIriMDQ63AzmHJxxa@HDnmkdNa/IfNW6L/P8fAA "Jelly – Try It Online") Thanks to Jonathan Allan for the heads-up (on `Ṭ€o⁶`). [Answer] # R, ~~54~~ 53 bytes ``` cat(sprintf(' %*s',cumsum(c(30,sample(3,29,T)-2)),0)) ``` Similar idea [as above](https://codegolf.stackexchange.com/a/156250/1710), but with shortened `sprintf` code and a shorter character string literal. Instead of `\n` (two bytes) I’m using a literal line break (one byte). `[Try it online!](https://tio.run/##K/r/PzmxRKO4oCgzryRNQ51LVatYXSe5NLe4NFcjWcPYQKc4MbcgJ1XDWMfIUidEU9dIU1PHQFPz/38A)` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~45~~ 39 bytes ``` x=30 x.times{puts' '*(x+=rand(3)-1)+?S} ``` [Try it online!](https://tio.run/##KypNqvz/v8LW2ICrQq8kMze1uLqgtKRYXUFdS6NC27YoMS9Fw1hT11BT2z649v9/AA "Ruby – Try It Online") Modifying `x` during the loop does not affect the loop counter. I chose S as a particularly snakelike output character. -6 bytes: Use `rand(3)-1` instead of `[-1,0,1].sample`. *Thanks, [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil)!* [Answer] # [SenseTalk](http://sensetalk.com), 237 198 Bytes This is a language that I came to know and love about a decade ago. It's the scripting language that drives the automated testing tool [Eggplant Functional](https://www.testplant.com). I was an avid user of the tool for many years before joining the company for a while. It's not the most golf-capable language, but I find it very enjoyable to write in. Golfing in it is actually quite challenging as the language is meant to be verbose and English-like... took me quite a while to get it down to 237 bytes. ``` set s to " +"&lf set p to s repeat 30 set a to random(0,2) if a equals 0 delete first char of p else if a equals 1 put " " before p end if put p after s end repeat put s ``` ## Ungolfed/Explanation ``` set the_snake to " +"&lf #assign the first line of the snake set previous_line to the_snake #set up for the loop repeat 30 times #loop 30x set action to random(0,2) #random add/subtract/stay the same if action equals 0 delete the first character of previous_line #SenseTalk really shines at string manipulation else if action equals 1 put " " before previous_line #insert a character at the beginning end if put previous_line after the_snake #plop the new segment into the string end repeat #close the loop put the_snake #print to standard out ``` Edit: Saved 36 bytes thanks to @mustachemoses [Answer] # [J](http://jsoftware.com/), 23 bytes ``` echo(8":~+/)\31,1-?29$3 ``` [Try it online!](https://tio.run/##y/r/PzU5I1/DQsmqTltfM8bYUMdQ197IUsX4/38A "J – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes ``` 1..($l=30)|%{" "*$l+"x";$l+=-1,0,1|Random} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPT0Mlx9bYQLNGtVpJQUlLJUdbqULJGkjZ6hrqGOgY1gQl5qXk59b@/w8A "PowerShell – Try It Online") Loops from `1` to `$l=30`. Each iteration we put `$l` spaces plus an `x` onto the pipeline as a string, then `+=` either of `-1, 0, 1` based on `Get-Random` into `$l` for the next loop. Those strings are gathered from the pipeline and an implicit `Write-Output` gives us a newline-separated list for free. [Answer] # Bash, 53 * 3 bytes saved thanks to @Dennis ``` for((i=p=30;i--;p+=RANDOM%3-1));{ printf %${p}s+\\n;} ``` [Try it online](https://tio.run/##S0oszvj/Py2/SEMj07bA1tjAOlNX17pA2zbI0c/F31fVWNdQU9O6WqGgKDOvJE1BVaW6oLZYOyYmz7r2/38A). [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~53 51 50~~ 49 bytes ``` printf('%*d\n',[a=31+cumsum(randi(3,1,30)-2);~a]) ``` [Try it online!](https://tio.run/##y08uSSxL/f@/oCgzryRNQ11VKyUmT10nOtHW2FA7uTS3uDRXoygxLyVTw1jHUMfYQFPXSNO6LjFW8/9/AA "Octave – Try It Online") Saved 1 byte by no longer doing any looping. Saved another as Octave has `printf` as well as `fprintf`. This new code creates an array of 30 random integers in the range `-1:1`. It then cumulatively sums the array and adds 30, which gives the desired sequence. The result is printed using `fprintf` with a format that says "A decimal number, padded to a specified width, followed by a new line. The width will be the first value input, and the decimal number will be the second value input. If the number of values input is more than this, Octave will keep repeating the print automatically to get the desired output. To achieve the looping then, we need only interleave zeros between the sequence array so the `fprintf` function uses each value in the sequence as a width, and each zero as the digit to be printed. Prints an output like: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` --- The above code doesn't always print exactly 30 spaces on the first line. It will be either 29, 30, or 31. To correct that, you would use this 53 byte version: ``` x=31;for i=2:x;fprintf('%*d\n',x,0);x+=randi(3)-2;end ``` [Answer] ## Lua, ~~81~~ 75 bytes ``` n=30;for i=1,n do print(("%-"..n.."s+"):format(" "))n=n-2+math.random(3)end ``` In `for i=1,n ...` the *to\_exp* `n` is evaluated only once before entering the loop, saving one byte. -6 thanks to @user202729 [Try it online!](https://tio.run/##DcpRCoAgDADQq4xBMDFH5V/hYQSLhJxhdf7l54N3fVFVgp@2ozbIYR4FUoW7ZXmJcHDILMz4WDRrLyW@hIDGSBC32M6TW5RUC3mzS1L9AQ) [Answer] # [Python 3.6](https://python.org), ~~84~~ ~~73~~ 69 bytes ``` from random import* x=30 exec("print(' '*x+'+');x+=randint(-1,1);"*x) ``` Thanks to @WheatWizard for -11 bytes. Thanks to @JoKing for -4 bytes. [Answer] # ES5, ~~97~~ ~~95~~ 81 bytes ``` for(p=i=30;i--;)console.log(Array(p).join(" ",r=Math.random()*3|0,p+=r>1?-1:r)+0) ``` **ES5, ~~112~~ 98 bytes** if function format is needed: ``` function a(){for(p=i=30;i--;)console.log(Array(p).join(" ",r=Math.random()*3|0,p+=r>1?-1:r)+0)}a() ``` ]
[Question] [ Write a program that takes 2 strings as input, and returns the longest common prefix. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the shortest amount of bytes wins. ``` Test Case 1: "global" , "glossary" "glo" Test Case 2: "department" , "depart" "depart" Test Case 3: "glove", "dove" "" ``` [Answer] # Python 3, 54 bytes Thanks Python for having a built-in function for this task! :D ``` import os;print(os.path.commonprefix(input().split())) ``` Takes input as two words separated by a space such as `glossary global`. [Answer] ## Haskell, 29 bytes ``` (c:x)%(d:y)|c==d=c:x%y;_%_="" ``` Usage: ``` >> "global"%"glossary" "glo" ``` Recursively defines the binary function `%` by pattern matching. On two strings with equal first letters, takes that first letters, and prepends it to the function of the remainder of the strings. On anything else, gives the empty string. [Answer] # Pyth, ~~8~~ 7 bytes ``` e@F._MQ ``` Thanks @isaacg for 1 byte off Takes input quoted and comma separated, like `"abc", "acc"`. This exits on an error (but leaves stdout empty) when the result is the empty string. If that is unacceptable, add 2 bytes for `#e@F._MQq` [Test Suite](http://pyth.herokuapp.com/?code=e%40F._MQ&input=%22global%22%2C%22glossary%22&test_suite=1&test_suite_input=%22global%22%2C%22glossary%22%0A%22department%22%2C%22depart%22%0A%22glove%22%2C%22dove%22&debug=0) ### Explanation ``` e@F._MQ : implicit Q = eval(input) ._MQ : Map the prefix operator onto both inputs @F : Fold the setwise intersection operator over those lists e : Take the last such element, the prefixes are always made from shortest : to longest, so this always gives the longest matching prefix ``` [Answer] ## C++, ~~101~~ ~~100~~ 99 bytes ``` #include<iostream> int i;main(){std::string s,t;std::cin>>s>>t;for(;s[i]==t[i];std::cout<<s[i++]);} ``` Reads two strings from `stdin`, prints the character at the current position from one of the strings while the character at the current position is equal to the character at the same position in the other string. Thanks to [Zereges](https://codegolf.stackexchange.com/users/43365/zereges) for saving one byte. [Answer] ## Haskell, 38 bytes ``` ((map fst.fst.span(uncurry(==))).).zip ``` Usage example: `( ((map fst.fst.span(uncurry(==))).).zip ) "global" "glossary"` -> `"glo"`. Zip both input string into a list of pairs of characters. Make two lists out of it: the first one with all pairs from the beginning as long as both characters are equal, the second one with all the rests. Drop the second list and extract all characters from the first list. [Answer] # CJam, ~~12~~ ~~11~~ 9 bytes ``` l_q.-{}#< ``` This reads the strings on two separate lines with Unix-style line ending, i.e., `<string>\n<string>\n`. *Thanks to @MartinBüttner for -1 byte, and to @jimmy23013 for -2 bytes!* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l_l.-X%2B%7B%7D%23%3C&input=department%0Adepart). ### How it works ``` l_ e# Read a line (w/o trailing LF) from STDIN and push a copy. q e# Read another line from STDIN (with trailing LF). e# The trailing linefeed makes sure that the lines are not equal. .- e# Perform vectorized character subtraction. This yields 0 for equal e# characters, a non-zero value for two different characters, and the e# characters themselves (truthy) for the tail of the longer string. {}# e# Find the index of the first truthy element. < e# Keep that many characters from the first string. ``` [Answer] # APL, 13 ``` {⊃↓K/⍨=⌿K←↑⍵} ``` This is a function that takes an array of two strings, and returns the prefix: ``` {⊃↓K/⍨=⌿K←↑⍵}'glossary' 'global' glo {⊃↓K/⍨=⌿K←↑⍵}'department' 'depart' depart ``` [Answer] # AppleScript, 215 Bytes And I tried so hard... ;( ``` set x to(display dialog""default answer"")'s text returned set a to(display dialog""default answer"")'s text returned set n to 1 set o to"" repeat while x's item n=a's item n set o to o&x's item n set n to n+1 end o ``` I wanted to see how well AppleScript could pull this off, and *man* is it not built for string comparisons. [Answer] # sed, 18 I had something much longer and more complicated in mind, so credit for [this idea goes to @kirbyfan64sos](https://codegolf.stackexchange.com/a/62779/11259). ``` s/(.*).* \1.*/\1/ ``` Includes +1 for the `-r` option to sed. [Answer] ## C#, ~~201~~ 147 bytes ``` using System.Linq;class a{static void Main(string[]a){a[0].Take(a[1].Length).TakeWhile((t,i)=>a[1][i]==t).ToList().ForEach(System.Console.Write);}} ``` I know it isn't terribly competitive. I just wanted to see what it would look like. EDIT: Thanks Ash Burlakzenko, Berend, and Dennis\_E [Answer] # [rs](https://github.com/kirbyfan64/rs), 14 bytes ``` (.*).* \1.*/\1 ``` [Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%28.*%29.*%20%5C1.*%2F%5C1&input=global%20glossary%0Adepartment%20depart%0Aglove%20dove) This is pretty simple. It just matches the...longest common prefix and removes the rest of the string. If there is no longest common prefix, it just clears everything. [Answer] # CJam, 12 8 26 ``` r:AAr:B.=0#_W={;;ABe<}{<}? ``` [Try it Online.](http://cjam.aditsu.net/#code=r%3AAAr%3AB.%3D0%23_W%3D%7B%3B%3BABe%3C%7D%7B%3C%7D%3F&input=glowing%20glow) (Got idea to use .= instead of .- after looking at Dennis's answer.) With all the edge cases, it became to hard for a CJam beginner like me to keep it short. Hopefully, this at least works for all cases. [Answer] ## Common Lisp, 39 ``` (lambda(a b)(subseq a 0(mismatch a b))) ``` Takes two string arguments, determines the index *i* where they differ, and returns a substring from 0 to *i*. [Answer] # Javascript ES6, 52 bytes ``` f=(a,b)=>[...a].filter((e,i)=>e==b[i]?1:b='').join`` ``` Usage: ``` >> f("global","glossary") "glo" ``` [Answer] ## Perl 5, ~~20~~ ~~19~~ 18 bytes 19 bytes, plus 1 for the `-E` flag instead of `-e`: ``` say<>=~/^(.*).* \1/ ``` This is copied shamelessly from [Digital Trauma](/u/11259)'s [sed answer](/a/62806). It assumes the input is a couple of words without spaces in them (or before the first) and with one space between them. --- Update: [ThisSuitIsBlackNot](/u/31388) suggested using `-pe` as follows, to save a byte (thanks!): ``` ($_)=/^(.*).* \1/ ``` And then [Luk Storms](/u/42827) suggested using `-nE` as follows to save another byte (thanks!): ``` say/^(.*).* \1/ ``` (I'm counting `-E` as one byte instead of the standard `-e`, but `-n` or `-p` as two. My impression is that that's SOP around here.) [Answer] # Python 3, 72 31 bytes saved thanks to FryAmTheEggman. 8 saved thanks to DSM. ``` r='' for x,y in zip(input(),input()): if x==y:r+=x else:break print(r) ``` [Answer] ## Python 3, 47 ``` def f(w):[print(end=c[c!=d])for c,d in zip(*w)] ``` A function that takes a list `w` of two words, and prints the common prefix before terminating with an error. Python 3's `print` function lets you prints strings flush against each other with `print(end=c)` (thanks to Sp3000 for saving 3 bytes with this shorter syntax). This repeatedly take two letters from the words, and prints the first of the letters. The indexing `c[c!=d]` gives an out-of-bounds error where `c!=d`, terminating the execution when two unequal letters are encountered. An explicit for loop is one char longer than the list comprehension: ``` def f(w): for c,d in zip(*w):print(end=c[c!=d]) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 9 bytes ``` y!=XdYpf) ``` [Try it online!](https://tio.run/##y00syfn/v1LRNiIlsiBN8/9/9ZTUgsSiktzUvBJ1LignNUUdAA "MATL – Try It Online") *(-2 bytes thanks to Giuseppe)* ``` y % implicitly input the two strings, then duplicate the % first one into the stack again % stack: ['department' 'deported' 'department'] ! % transpose the last string into a column vector = % broadcast equality check - gives back a matrix comparing % every letter in first input with the letters in the second Xd % diagonal of the matrix - comparison result of each letter with % only corresponding letter in the other string % stack: ['department' [1; 1; 1; 0; 1; 1; 0; 0;]] Yp % cumulative product (so only initial sequence of 1s remains % 1s, others become 0) % stack: ['department' [1; 1; 1; 0; 0; 0; 0; 0;]] f % find the indices of the 1s ) % index at those elements so we get those letters out % (implicit) convert to string and display ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 14 bytes Uses the same idea as [kirbyfan64sos](https://codegolf.stackexchange.com/a/62779/34718). Unfortunately, despite Martin's claim that eventually Match mode will feature a way to print capturing groups, it hasn't been implemented yet. Otherwise, `(.*).* \1` could be used along with 2 bytes or so for some not-yet-existing configuration string option. ``` (.*).* \1.* $1 ``` Each line would go in its own file, with 1 byte added per additional file. Alternatively, run in a single file with the `-s` flag. [Answer] # K, 24 bytes ``` {(+/&\=/(&/#:'x)#'x)#*x} ``` Find the minimum of the length of each string. (`(&/#:'x)`). Trim each string to that length (`#'x`). Then compare, smear and sum the resulting sequence: ``` =/("globaa";"glossa") 1 1 1 0 0 1 &\=/("globaa";"glossa") 1 1 1 0 0 0 +/&\=/("globaa";"glossa") 3 ``` Finally, take that many characters from the first of the strings provided (`#*x`). In action: ``` f: {(+/&\=/(&/#:'x)#'x)#*x}; f'(("global";"glossary") ("department";"depart") ("glove";"dove") ("aaa";"aaaaa") ("identical";"identical") ("aca";"aba")) ("glo" "depart" () "aaa" "identical" ,"a") ``` [Answer] ## Powershell, 65 bytes Compare the strings, shrinking the first until it either matches (print and exit) or the string is null and the loop terminates. ``` param($a,$b)while($a){if($b-like"$a*"){$a;exit}$a=$a-replace".$"} ``` [Answer] # Julia, 62 bytes ``` f(a,b)=(c="";for(i,j)=zip(a,b) i!=j?break:(c*=string(i))end;c) ``` Ungolfed: ``` function f(a::AbstractString, b::AbstractString) # Initialize an output string c = "" # Iterate over the pairs of characters in a and b, # truncated to the shorter of the two lengths for (i, j) in zip(a, b) if i == j # If they match, append to the output string c *= string(i) else # Otherwise stop everything! break end end return c end ``` Fixed an issue (at the hefty cost of 14 bytes) thanks to xnor! [Answer] ## C99, 73 bytes ``` main(int c,char *a[]){for(char *x=a[1],*y=a[2];*x==*y++;putchar(*x++));} ``` Similar to [this answer](https://codegolf.stackexchange.com/a/62967/7464), but shorter and meets spec (takes input from stdin). [Answer] ## MATLAB, ~~50~~ 40 bytes Defines a function that accepts 2 strings as input, outputs to command window ``` function t(a,b);a(1:find([diff(char(a,b)) 1],1)-1) ``` This solution will work for any string, outputs ``` ans = Empty string: 1-by-0 ``` if no match is given. Can be golfed by using a script instead of a function (using local variables a, b) (-16 bytes). so getting 34 Bytes ``` a(1:find([diff(char(a,b)) 1],1)-1) ``` The function style (which seems to be the accepted style), yields ``` @(a,b)a(1:find([diff(char(a,b)) 1],1)-1) ``` (Thanks @Stewie Griffin) [Answer] # [Perl 6](http://perl6.org), 28 bytes I came up with two that take their values from STDIN which are based on the Perl 5 answer. ``` lines~~/(.*).*' '$0/;say ~$0 ``` ``` lines~~/:s(.*).* $0/;say ~$0 ``` The first requires exactly one space between the inputs, while the other requires at least one whitespace character between the inputs. --- That is quite a bit shorter than the first thing I tried which takes the values from the command line. ``` say [~] map ->($a,$b){$a eq$b&&$a||last},[Z] @*ARGS».comb # 58 bytes ``` or even the lambda version of it: ``` {[~] map ->($a,$b){$a eq$b&&$a||last},[Z] @_».comb} # 52 bytes ``` Though this is much easier to adjust so that it accepts any number of input strings, at the cost of only one stroke. ``` {[~] map ->@b {([eq] @b)&&@b[0]||last},[Z] @_».comb} # 53 bytes # ┗━┛ ┗━━━━━━━┛ ┗━━━┛ ``` ``` my &common-prefix = {[~] map ->@b {([eq] @b)&&@b[0]||last},[Z] @_».comb} say common-prefix <department depart>; # "depart" say common-prefix; # "" say common-prefix <department depart depot deprecated dependant>; # "dep" # This code does not work directly with a single argument, so you have # to give it an itemized List or Array, containing a single element. say common-prefix $('department',); # "department" # another option would be to replace `@_` with `(@_,)` ``` [Answer] # Japt, 27 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` Um$(X,Y)=>$A&&X==VgY ?X:A=P ``` (The strings go into the Input box like so: `"global" "glossary"`) This code is exactly equivalent to the following JS: ``` A=10;(U,V)=>U.split``.map((X,Y)=>A&&X==V[Y]?X:A="").join`` ``` I have not yet implemented anonymous functions, which is what the `$...$` is for: anything between the dollar signs is left untouched in the switch to JS. After I add functions, this 21-byte code will suffice: ``` UmXY{A&&X==VgY ?X:A=P ``` And after I implement a few more features, it will ideally be 18 bytes: ``` UmXY{AxX=VgY ?X:AP ``` Suggestions welcome! --- So it turns out that this program is only 15 bytes in modern Japt: ``` ¡A©X¥VgY ?X:A=P ``` [Try it online!](https://tio.run/nexus/japt#@39ooeOhlRGHloalRyrYR1g52gb8/6@UnpOflJijpABiFBcnFlUqAQA "Japt – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø€ËγнÏ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8I5HTWsOd5/bfGHv4f7//9Nz8pMSc7iAVHFxYlElAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCy9EF/w/veNS05nD3uc0X9h7u/6/zPzpaKT0nPykxR0kHxCguTiyqVIrViVZKSS1ILCrJTc0rAcpAOGBxoKKyVJAQiAIJlGRkFisAUaJCSWoxSDFcIC@/JCO1CCIMUpmYlGyYkmppkQZUBGQbpaRamKcpxcYCAA). Or alternatively: ``` ηR.ΔÅ? ``` Might be invalid, since it outputs `-1` instead of an empty string if the strings have no common prefix. [Try it online](https://tio.run/##yy9OTMpM/f//3PYgvXNTDrfa//@fnpOflJjDBaSKixOLKgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9z24P0zk2JKD7cav@/Vud/dLRSek5@UmKOkg6IUVycWFSpFKsTrZSSWpBYVJKbmlcClIFwwOJARWWpICEQBRIoycgsVgCiRIWS1GKQYrhAXn5JRmoRRBikMjEp2TAl1dIiDagIyDZKSbUwT1OKjQUA). **Explanation:** ``` ø # Zip the two (implicit) inputs together, creating pairs # i.e. "abc1de98f" and "abc2de87f" # → ["aa","bb","cc","12","dd","ee","98","87","ff"] €Ë # Check for each if all inner items (the two characters in this case) are the same # → [1,1,1,0,1,1,1,0,0,1] γ # Split it into parts, grouping the same subsequent values together # → [[1,1,1],[0],[1,1],[0,0],[1]] н # Pop and only leave the first item # → [1,1,1] Ï # Only leave the characters at the truthy indices in the (implicit second) input # i.e. "abc2de87f" and [1,1,1] → "abc" # (after which the result is output implicitly) η # Get the prefixes of the first (implicit) input # i.e. "abc1de98f" # → ["a","ab","abc","abc1","abc1d","abc1de","abc1de9","abc1de98","abc1de98f"] R # Reverse this list # → ["abc1de98f","abc1de98","abc1de9","abc1de","abc1d","abc1","abc","ab","a"] .Δ # Then find the first item in this list which is truthy for: # (which will result in -1 if none are found) Å? # Check if the second (implicit) input starts with the current prefix # i.e. "abc2de87f" and "abc1d" → 0 (falsey) # i.e. "abc2de87f" and "abc" → 1 (truthy) # (after which the result is output implicitly) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes ``` →¤nḣ ``` [Try it online!](https://tio.run/##yygtzv7//1HbpENL8h7uWPz///@U1ILEopLc1LwSKLO0KBUA "Husk – Try It Online") -2 bytes from Dominic Van essen. [Answer] ## Clojure/ClojureScript, 51 ``` (defn f[[a & b][c & d]](if(= a c)(str a(f b d))"")) ``` Pretty straightforward. Unfortunately the spaces around the parameter destructuring are necessary (that's the `[a & b]` stuff). Not the shortest but I beat some other answers in languages that like to brag about their terseness so I'll post it. [Answer] ## ed, sed, 19 bytes ## ex, 18 bytes ## vim, 20 bytes ``` s/\(.*\).* \1.*/\1/ ``` This also works with ex/vi (heirloom ex 050325), and the trailing slash is not required. Oddly, this *should* work in vim, but mysteriously fails. It works if I add another unused capture group, something which should not change the semantics of the regex at all: ``` s/\v(.*)(.* \1.*)/\1 ``` It fails and gives garbage answers in nvi and the results are downright mysterious: ``` :1 global glossary :s/\(.*\)\(.*\) \1\(.*\)/\1{\2,\3}/ global{,ry} ``` NOTE: This expects the words on the current [last in the file] line [or every line for the sed script] separated by a space, and containing no space. To operate on every line in ex/vim, add % to the beginning. I don't think I'm the only program here to have constraints like these. ]
[Question] [ On 4chan, a popular game is get. Every post on the site gets a sequential post ID. Since you can't influence or determine them, people try to guess (at least a part of) their own post number, usually the first few digits. Another version of the game is called dubs, and it's goal is to get repeating digits at the end of the number (i.e 1234555). Your task, if you wish to accept it, is to write a program that takes a post id as input (standard integer, you can assume below 2^32), and returns how many repeating digits are on the end. # Rules * Standard loopholes are **disallowed**. * The program can be a function, full program, REPL command, whatever works, really, as long as no external uncounted code/arguments are needed to run it. * Input can come from STDIN, function arguments, command line argument, file, whatever suits you. # Test Cases ``` Input: 14892093 Output: 1 Input: 12344444 Output: 5 Input: 112311 Output: 2 Input: 888888 Output: 6 Input: 135866667 //Post number I got on /pol/ few days ago, rip Output: 1 ``` [Answer] ## Mathematica, 29 bytes How about an arithmetic solution? ``` IntegerExponent[9#+#~Mod~10]& ``` I'm very pleased to see that this beats the straight-forward Mathematica approach. ### Explanation The code itself computes **9\*n + n%10** and then finds the largest power of **10** that divides the input, or in other words, counts the trailing zeros. We need to show if **n** ends in **k** repeated digits, that **9\*n + n%10** has **k** trailing zeros. Rep-digits are most easily expressed mathematically by dividing a number like **99999** (which is **105-1**) by **9** and then multiplying by the repeated digit. So we can write **n = m\*10k + d\*(10k-1)/9**, where **m ≢ d (mod 10)**, to ensure that **n** doesn't end in *more* than **k** repeated digits. Note that **d = n%10**. Let's plug that into our formula **9\*n + n%10**. We get **9\*m\*10k + d\*(10k-1) + d**. The **d** at the end is cancelled, so we're left with: **9\*m\*10k + d\*10k = (9\*m + d)\*10k**. But **9 ≡ -1 (mod 10)**, so **9\*m + d ≡ d - m (mod 10)**. But we've asserted that **m ≢ d (mod 10)** and hence **d - m ≢ 0 (mod 10)**. In other words, we've shown that **9\*m + d** is not divisible by **10** and therefore, the largest power of **10** that divides **9\*n + n%10 = (9\*m + d)\*10k** is **k**, the number of trailing repeated digits. As a bonus, this solution prints the correct result, `∞`, for input `0`. [Answer] ## [Retina](https://github.com/m-ender/retina), 9 bytes ``` &`(.)\1*$ ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/ivlqChpxljqKXy/7@hiYWlkYGlMZehkbEJEHAZAhmGhlwWYMBlaGxqYQYE5goA "Retina – TIO Nexus") Counts the number of overlapping matches of `(.)\1*$` which is a regex that matches a suffix of identical characters. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ẹḅtl ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9w186HO1pLcv7/NzQyNgGB/1EA "Brachylog – TIO Nexus") ### Explanation ``` ẹ Elements: split to a list of digits ḅ Blocks: group consecutive equal digits into lists t Tail: take the last list l Length: Output is the length of that last list ``` If `ḅ` worked directly on integers (and I'm not sure why I didn't implement it so that it does), this would only be 3 bytes as the `ẹ` would not be needed. [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ 41 bytes ``` lambda s:len(`s`)-len(`s`.rstrip(`s%10`)) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbJWTmqeRUJygqQtl6BUVlxRlFgCZqoYGCZqa/wuKMvNKFNI0MvMKSks0gAKGhkbGhoYA "Python 2 – TIO Nexus") ### 36 bytes - For a more flexible input ``` lambda s:len(s)-len(s.rstrip(s[-1])) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbJWTmqdRrKkLpvSKikuKMgs0iqN1DWM1Nf8XFGXmlSikaWTmFZSWaAAF1A0NjYwNDdUB "Python 2 – TIO Nexus") [Answer] ## Javascript (ES6), ~~55~~ ~~52~~ ~~32~~ 30 bytes ``` a=>a.match`(.)\\1*$`[0].length ``` * Saved **19** bytes thanks to @MartinEnder by replacing the regex * Saved **2** bytes thanks to @user81655 using tagged templates literals --- Using a regex to match the last group of the last digit *Note: First time posting. Do not hesitate to make remarks.* ``` f=a=>a.match`(.)\\1*$`[0].length console.log(f("14892093"));//1 console.log(f("12344444"));//5 console.log(f("112311"));//2 console.log(f("888888"));//6 console.log(f("135866667 "));//1 ``` [Answer] # [Perl 5](https://www.perl.org/), 22 bytes 21 bytes of code + `-p` flag. ``` /(.)\1*$/;$_=length$& ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtyPmvr6GnGWOopaJvrRJvm5Oal16SoaL2/79nXkFpiZWCoYmFpZGBpTGXoZGxCQhwGQJZhoZcFmDAZWhsamEGBOYA "Perl 5 – TIO Nexus") `/(.)\1*$/` gets the last identical numbers, and then `$_=length$&` assigns its length to `$_`, which is implicitly printed thanks to `-p` flag. [Answer] # C, ~~62~~ ~~56~~ ~~48~~ 47 bytes *Saved a byte thanks to @Steadybox!* ``` j,k;f(n){for(k=j=n%10;j==n%10;n/=10,k++);k-=j;} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@lk22dppGnWZ2WX6SRbZtlm6dqaGCdZQuh8/RtDQ10srW1Na2zdW2zrGv/5yZm5mloVhcUZeaVpGkoqabE5KFiJR2uNA1DEwtLIwNLY00wx8jYBAQgHCDP0BDMtAADiKixqYUZEJhragLtAAA "C (gcc) – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), ~~38~~ 32 bytes ``` f=lambda n:0<n%100%11or-~f(n/10) ``` *Thanks to @xnor for saving 6 bytes!* [Try it online!](https://tio.run/nexus/python2#HczBCsIwEIThsz7FXJY2kOJuUzUp6rtUQqCgWwmeffW4@p3@uUwr18fyvOcFOvNFSZhJZKvDp/R6EHatbBWKVSFTTCOn4CFjmH6sLEU84p/tcIwnc573u1dd9Y2OUsZwA@UOhF497Ni59gU "Python 2 – TIO Nexus") [Answer] # PHP, 47 45 40 bytes ``` while($argn[-++$i]==$argn[-1]);echo$i-1; ``` Run with `echo <n> | php -nR '<code>` seems a loop is still smaller than my first answer. simply count the chars that are equal to the last. This uses negative string offsets of *PHP 7.1*. *-5 bytes* by Titus. Thanks ! --- Old answer: ``` <?=strlen($a=$argv[1])-strlen(chop($a,$a[-1])); ``` removes from the right every character matching the rightmost character and calculates the difference in the length. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` .¡¤g ``` [Try it online!](https://tio.run/nexus/05ab1e#@693aOGhJen//xsaGZsAAQA "05AB1E – TIO Nexus") or as a [Test suite](https://tio.run/nexus/05ab1e#qymr/K93aOGhJen/K5UO77dSOLxfSee/oYmFpZGBpTGXoZGxCRBwGQIZhoZcFmDAZWhsamEGBOYA) **Explanation** ``` .¡ # group consecutive equal elements in input ¤ # get the last group g # push its length ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` re`W=0= ``` [Try it online!](https://tio.run/nexus/cjam#K/TTr7YKsv4flJoQbmtg@z82r1b/v6GJhaWRgaUxl6GRsQkQcBkCGYaGXBZgwGVobGphBgTmAA "CJam – TIO Nexus") ### Explanation ``` r e# Read input. e` e# Run-length encode. W= e# Get last run. 0= e# Get length. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` DŒgṪL ``` [Try it online!](https://tio.run/nexus/jelly#@@9ydFL6w52rfP7//29oZGwCBAA "Jelly – TIO Nexus") **Explanation** ``` D # convert from integer to decimal Œg # group runs of equal elements Ṫ # tail L # length ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~32~~ 29 bytes ``` f(x){x=x%100%11?1:-~f(x/10);} ``` This is a port of [my Python answer](https://codegolf.stackexchange.com/a/114241/12012). This work with gcc, but the lack of a `return` statement is undefined behavior. [Try it online!](https://tio.run/nexus/c-gcc#HYzRCoJAFESfd79iEBZ2baW9aqaJ9SHVQ6CSUEuEkCD263a38zQzzMza68nMUzMpck4RneiQfDnbkjP1sg5@xPM2eG3kLEVw47m4osFMeVmlrsosKM3yACuWRBblH/bZriyY/WIRe16NtZTicx8eHXTsjRTi9ebTXkeqapEcodqLj0LZog8NY@GxaUC1XNYf "C (gcc) – TIO Nexus") [Answer] # Cubix, ~~24~~ 19 bytes ``` )uO)ABq-!wpUp)W.@;; ``` # Note * Actually counts how many of the same characters are at the end of the input, so this works for really big integers and really long strings as well (as long as the amount of same characters at the end is smaller than the maximum precision of JavaScript (around 15 digits in base-10). * Input goes in the input field, output is printed to the output field [Try it here](http://ethproductions.github.io/cubix/?code=KXVPKUFCcS0hd3BVcClXLkA7Ow==&input=MTM1ODY2NjY3) # Explanation First, let's expand the cube ``` ) u O ) A B q - ! w p U p ) W . @ ; ; . . . . . ``` The steps in the execution can be split up in three phases: 1. Parse input 2. Compare characters 3. Print result ## Phase 1: Input The first two characters that are executed are `A` and `B`. `A` reads all input and pushes it as character codes to the stack. Note that this is done in reverse, the first character ends up on top of the stack, the last character almost at the bottom. At the very bottom, `-1` (`EOF`) is placed, which will be used as a counter for the amount of consecutive characters at the end of the string. Since we need the top of the stack to contain the last two characters, we reverse the stack, before entering the loop. Note that the top part of the stack now looks like: `..., C[n-1], C[n], -1`. The IP's place on the cube is where the `E` is, and it's pointing right. All instructions that have not yet been executed, were replaced by no-ops (full stops). ``` . . . . A B E . . . . . . . . . . . . . . . . . ``` ## Phase 2: Character comparison The stack is `..., C[a-1], C[a], counter`, where `counter` is the counter to increment when the two characters to check (`C[a]` and `C[a-1]`) are equal. The IP first enters this loop at the `S` character, moving right. The `E` character is the position where the IP will end up (pointing right) when `C[a]` and `C[a-1]` do not have the same value, which means that subtracting `C[a]` from `C[a-1]` does not yield `0`, in which case the instruction following the `!` will be skipped (which is a `w`). ``` . . . . . S q - ! w E . p ) W . . ; ; . . . . . ``` Here are the instructions that are executed during a full loop: ``` q-!;;p) # Explanation q # Push counter to the bottom of the stack # Stack (counter, ..., C[a-1], C[a]) - # Subtract C[a] from C[a-1], which is 0 if both are equal # Stack (counter, ..., C[a-1], C[a], C[a-1]-C[a]) ! # Leave the loop if C[a-1]-C[a] does not equal 0 ;; # Remove result of subtraction and C[a] from stack # Stack (counter, ..., C[a-1]) p # Move the bottom of the stack to the top # Stack (..., C[a-1], counter) ) # Increment the counter # Stack (..., C[a-1], counter + 1) ``` And then it loops around. ## Phase 3: Print result Since we left the loop early, the stack looks like this: `counter, ..., C[a-1]-C[a]`. It's easy to print the counter, but we have to increment the counter once because we didn't do it in the last iteration of the loop, and once more because we started counting at `-1` instead of `0`. The path on the cube looks like this, starting at `S`, pointing right. The two no-ops that are executed by the IP are replaced by arrows that point in the direction of the IP. ``` ) u O ) . B . . . S p U . ) . . @ . . . > > . . ``` The instructions are executed in the following order. Note that the `B)` instructions at the end change the stack, but don't affect the program, since we are about to terminate it, and we do not use the stack anymore. ``` p))OB)@ # Explanation p # Pull the counter to the top # Stack: (..., counter) )) # Add two # Stack: (..., counter + 2) O # Output as number B) # Reverse the stack and increment the top @ # End the program ``` [Answer] ## Python 2, 51 bytes Takes integer as input. [Try it online](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqgQbBVdYWubEJwQrWsYm5ZfpFChkJkH4lpZAQW01evUY/Uy81JSKzQMNP8XFGXmlSjkaBgaGWtyIXGMkbggzn8A) ``` lambda S:[x==`S`[-1]for x in`S`[::-1]+'~'].index(0) ``` 48 bytes for string as input. [Try it online](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqgQbBVdYWsbHK1rGJuWX6RQoZCZpxAcbWUF5GurG6jH6mXmpaRWaBho/i8oyswrUcjRUDc0MlbX5ELmGqMIgLn/AQ) ``` lambda S:[x==S[-1]for x in S[::-1]+'~'].index(0) ``` [Answer] ## [C#](http://csharppad.com/gist/fc79ad57ba18c5c26e3ba6f50965bca5), ~~63~~ 62 bytes --- **Golfed** ``` i=>{int a=i.Length-1,b=a;while(a-->0&&i[a]==i[b]);return b-a;} ``` --- **Ungolfed** ``` i => { int a = i.Length - 1, b = a; while( a-- > 0 && i[ a ] == i[ b ] ); return b - a; } ``` --- **Ungolfed readable** ``` i => { int a = i.Length - 1, // Store the length of the input b = a ; // Get the position of the last char // Cycle through the string from the right to the left // while the current char is equal to the last char while( a-- > 0 && i[ a ] == i[ b ] ); // Return the difference between the last position // and the last occurrence of the same char return b - a; } ``` --- **Full code** ``` using System; namespace Namespace { class Program { static void Main( String[] args ) { Func<String, Int32> f = i => { int a = i.Length - 1, b = a; while( a-- > 0 && i[ a ] == i[ b ] ); return b - a; }; List<String> testCases = new List<String>() { "14892093", "12344444", "112311", "888888", "135866667" }; foreach( String testCase in testCases ) { Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" ); } Console.ReadLine(); } } } ``` --- **Releases** * **v1.1** - `- 1 byte` - Thanks to [Kevin's](https://codegolf.stackexchange.com/questions/114146/get-your-dubs-together/114188#comment278413_114188) comment. * **v1.0** - `63 bytes` - Initial solution. --- **Notes** Nothing to add [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~6~~ 5 bytes *1 byte saved thanks to @Luis* ``` &Y'O) ``` Try it at [**MATL Online**](https://matl.io/?code=%26Y%27O%29&inputs=%2712344444%27&version=19.8.0) **Explanation** ``` % Implicitly grab input as a string &Y' % Perform run-length encoding on the string but keep only the second output % Which is the number of successive times an element appeared O) % Grab the last element from this array % Implicitly display ``` [Answer] ## Batch, 91 bytes ``` @set s=-%1 @set n=1 :l @if %s:~-2,1%==%s:~-1% set s=%s:~,-1%&set/an+=1&goto l @echo %n% ``` The `-` prevents the test from running off the start of the string. [Answer] # Powershell, 41 Bytes ``` for($n="$args";$n[-1]-eq$n[-++$a]){};$a-1 ``` straightforward loop backwards until a char doesn't match the last char in the string, return the index of that char -1. -3 thanks to @AdmBorkBork - using a for loop instead of a while. [Answer] # JavaScript (ES6), 34 bytes ``` f=(n,p)=>n%10-p?0:1+f(n/10|0,n%10) ``` Not shorter than the regex solution. Recursive function which evaluates the digits from right-to-left, stopping when a different digit is encountered. The result is the number of iterations. `p` is `undefined` on the first iteration, which means `n%10-p` returns `NaN` (falsy). After that, `p` equals the previous digit with `n%10`. When the current digit (`n%10`) and the previous (`p`) are different, the loop ends. [Answer] # [Röda](https://github.com/fergusq/roda), 12 bytes ``` {count|tail} ``` [Try it online!](https://tio.run/nexus/roda#RYvBDoIwDIbP61M0PUGi0TLUccAnISELbAmJbgbmCfDV5/Ag36Hp/3/tUw8OZxC2buLc@bcLS9DDY43C@hGDmULb6clg70GIPX5qpMbRAYlSn/3FiSjHBW22zdc4uLC7dIzHO6anNgfRe2dgjVyqqjhXEriQ5QZw2phB/QCWF3VN3L4 "Röda – TIO Nexus") This is an anonymous function that expects that each character of the input string is pushed to the stream (I think this is valid in spirit of [a recent meta question](https://codegolf.meta.stackexchange.com/questions/11871/when-to-allow-flexible-input-output)). It uses two builtins: `count` and `tail`: 1. `count` reads values from the stream and pushes the number of consecutive elements to the stream. 2. `tail` returns the last value in the stream. [Answer] ## T-SQL, 238 214 Bytes ``` declare @ varchar(max) = '' declare @i int=0, @e int=0, @n int=right(@,1), @m int while (@i<=len(@)) begin set @m=(substring(@,len(@)-@i,1)) if (@n=@m) set @e=@e+1 else if (@i=0) set @e=1 set @i=@i+1 end select @e ``` Or: ``` declare @ varchar(max) = '12345678999999' declare @i int = 0, @e int = 0, @n int = right(@,1), @m int while (@i <= len(@)) begin set @m = (substring(@,len(@)-@i,1)) if (@n = @m) set @e = @e + 1 else if (@i) = 0 set @e = 1 set @i = @i + 1 end select @e ``` [Answer] # Java 7, 78 bytes ``` int c(int n){return(""+n).length()-(""+n).replaceAll("(.)\\1*$","").length();} ``` [Try it here.](https://tio.run/nexus/java-openjdk#fY1LDoIwEED3nGLSuGj9NPJRIaw8gCuW4qLWBpuUQspgYghnR1ASd7zFJJN5eSONaBq4dB5AgwK1hEFbBEmnaVnnFLbOUkI2lnGjbIFPynbz7lRthFRnYyihnOW5v16RLSF/M@0HgLq9mzE891@VfkAptKUZOm2L602w6T1A9m5QlbxqkdfjBY2lkvpRnAT7JGQsXZCCMJpYlkbL9xeV@MtyJTzEx5HTz@q9fvgA) I tried some things using recursion or a loop, but both ended up above 100 bytes.. [Answer] ## Mathematica, ~~33~~ 30 bytes *Thanks to Greg Martin for saving 3 bytes.* ``` Tr[1^Last@Split@Characters@#]& ``` Takes input as a string. Gets the decimal digits (in the form of characters), splits them into runs of identical elements, gets the last run and computes the length with the standard trick of taking the sum of the vector `1^list`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 34 bytes ``` sed s/.*[^${1: -1}].//<<<x$1|wc -c ``` [Try it online!](https://tio.run/nexus/bash#@1@cmqJQrK@nFR2nUm1opaBrWBurp69vY2NToWJYU56soJv8//9/YzAAAA "Bash – TIO Nexus") [Answer] # [C (clang)](http://clang.llvm.org/), 41 bytes ``` f(x){return x&&x%10-x/10%10?1:f(x/10)+1;} ``` There are already 2 other C solutions, but they both depend on loops. This uses recursion. If the last 2 digits are different then it's 1, otherwise you do 1+ the number of consecutive digits of the number with the last digit removed. [Try it online!](https://tio.run/nexus/c-clang#@5@mUaFZXZRaUlqUp1ChplahamigW6FvaACk7Q2tgLJAtqa2oXXtf@XMvOSc0pRUm@KSlMx8vQw7rsy8EoXcxMw8Dc1qLs6CIiA3TUNJNSUmT0knTcPQxMLSyMDSWFPTGoukkbEJCGCXBMoaGmKVsgAD7LqMTS3MgMAcLAv1kYE1V@1/AA "C (clang) – TIO Nexus") [Answer] # JavaScript (ES6), ~~39~~ ~~38~~ ~~37~~ 27 bytes ``` f=n=>n%100%11?1:1+f(n/10|0) ``` Maybe not shorter than the regex-based solution, but I couldn't resist writing a solution entirely based on arithmetic. The technique is to repeatedly take `n % 100 % 11` and divide by 10 until the result is non-zero, then count the iterations. This works because if the last two digits are the same, `n % 100 % 11` will be `0`. [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` f(h:t)=sum[1|all(==h)t]+f t f _=0 ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkWFVomlbXJobbViTmJOjYWuboVkSq52mUMKVphBva/A/R8FWIdrQxMLSyMDSWEfB0MjYBASALCDT0FBHwQIMgHxjUwszIDCP5cpNzMwDastNLPBVKCjKzCtRUAFxFNKgdHFGfrlCzn8A "Haskell – TIO Nexus") Takes string input. Repeatedly cuts off the first character, and adds 1 if all characters in the suffix are equal to the first one. [Answer] # R, 35 bytes ``` rle(rev(charToRaw(scan(,''))))$l[1] ``` Brief explanation ``` scan(,'') # get input as a string charToRaw( ) # convert to a vector of raws (splits the string) rev( ) # reverse the vector rle( )$l[1] # the first length from run length encoding ``` [Answer] # [Befunge-98](https://github.com/catseye/FBBI), 19 bytes ``` 01g3j@.$~:01p-!j$1+ ``` [Try it online!](https://tio.run/nexus/befunge-98#@29gmG6c5aCnUmdlYFigq5ilYqj9/7@hiYWlkYGlMRD8BwA "Befunge-98 – TIO Nexus") This could be made shorter if I managed to only use the stack. How it works: ``` 01g3j@.$~:01p-!j$1+ 01g ; Get the stored value (default: 32) ; 3j ; Skip to the ~ ; ~ ; Get the next character of input ; :01p ; Overwrite the stored value with the new char ; -! ; Compare the old value and the new ; j$ ; Skip the $ when equal, else pop the counter ; 1+ ; Increment the counter ; ; When the input runs out, ~ reflects the IP and we run: ; @.$ $ ; Pop the extraneous value (the stored value) ; @. ; Print the number and exit ; ``` ]
[Question] [ ## Challenge Given a single word as input, determine if the word is odd or even. ## Odd and Even words Assume the general rules: ``` odd + odd = even even + odd = odd odd + even = odd even + even = even ``` In the alphabet, the odd letters are: ``` aeiou ``` And the even letters are: ``` bcdfghjklmnpqrstvwxyz ``` The same applies to capital letters (`AEIOU` are odd and `BCDFGHJKLMNPQRSTVWXYZ` are even). You then 'add' each of the letters in the word together. For example, the word `cats` is equivalent to: ``` even + odd + even + even ``` Which simplifies to: ``` odd + even ``` Which simplifies further to: ``` odd ``` So the word `cats` is odd. ## Examples ``` Input: trees Output: even ``` --- ``` Input: brush Output: odd ``` --- ``` Input: CAts Output: odd ``` --- ``` Input: Savoie Output: even ``` --- ``` Input: rhythm Output: even ``` ## Rules All input will be a single word which will only contain alphabetical characters. If the word is odd, output a truthy value. If the word is even, output a falsey value. ## Winning The shortest code in bytes wins. [Answer] # EXCEL, 79 bytes: ``` =MOD(SUMPRODUCT(LEN(A1)-LEN(SUBSTITUTE(LOWER(A1),{"a","e","i","o","u"},""))),2) ``` **input:** This function can be placed anywhere **EXCEPT A1** Put your word in question into A1. Output: 0 if even, 1 if odd. [Answer] ## JavaScript (ES6), ~~34~~ ~~41~~ ~~33~~ 32 bytes Saved 1 bytes thanks to Arnauld: ``` s=>~s.split(/[aeiou]/i).length&1 ``` * Odd word : returns `1` * Even words : returns `0` --- Previous solutions: 33 bytes thanks to Arnauld: ``` s=>s.split(/[aeiou]/i).length&1^1 ``` * Odd word : returns `1` * Even words : returns `0` Another way without bitwise operators: ``` s=>++s.split(/[aeiou]/i).length%2 ``` 41 bytes: ``` (s,a=s.match(/[aeiou]/ig))=>a&&a.length%2 ``` * Odd word : returns `1` * Even words with odd letters : returns `0` * Even words with no odd letters : returns `null` 42 bytes to return `0` instead of `null`: ``` (s,a=s.match(/[aeiou]/ig))=>a?a.length%2:0 ``` 34 bytes, breaks on words with no odd letters: ``` f=s=>s.match(/[aeiou]/ig).length%2 ``` Saved 2 bytes thanks to Shaun H ``` s=>s.match(/[aeiou]/ig).length%2 ``` [Answer] # C, 42 bytes ``` f(char*s){return*s&&2130466>>*s&1^f(s+1);} ``` This works with GCC 4.x on a x86-64 CPU. Results may vary with different setups. Test it on [repl.it](https://repl.it/DePi). At the cost of 5 more bytes, undefined behavior can be avoided, so the code should work as long as *int*s are at least 32 bits wide. ``` f(char*s){return*s&&2130466>>(*s&31)&1^f(s+1);} ``` ### How it works Modulo **32**, the character codes of all odd letters are **1**, **5**, **9**, **15**, and **21**. **2130466** is the 32-bit integer that has set bits at these positions and unset bits at all others. When **f** is called on a string, it first checks if the first character of the string is a null byte (string terminator). If it is, `*s` yields **0** and **f** returns **0**. Otherwise, `*s` yield the character code of a letter and the right argument of the logical AND (`&&`) is executed. For `>>`, GCC generates a shift instruction. On a x86-64 CPU, the corresponding instruction for a 32-bit integer ignores all but the lower 5 bits of the right argument, which avoids reducing `*s` modulo **32**. The right shift and the following bitwise AND with **1** extracts the bit of **2130466** that corresponds to the letter, which will be **1** if and only if the letter is odd. Afterwards, we increment the pointer **s** (effectively discarding the first letter), call **f** recursively on the beheaded string, and take the bitwise XOR of the result from above and the result of the recursive call. [Answer] # sed 44 (42 + 1 for -n) 43 -1 thanks to Neil ``` s/[aeiou][^aeiou]*[aeiou]//gi /[aeiou]/Ico ``` Prints `o` for odd and nothing for even [Answer] ## Python, 41 bytes ``` lambda s:sum(map(s.count,"aeiouAEIOU"))%2 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~206~~ ~~196~~ ~~192~~ 178 + 3 = 181 bytes [Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdPHsoe31bKCgoKCgoKCkoKSgpKSl7fSl7fSl7fSl7fSl7fSgpXSl7KHt9Wyh7fSgpKV0peyh7fVsoe30pXSl7KHt9Wyh7fSgpKCkpXSl7KHt9Wyh7fSldKXsoe308PikoPD4pfX19fX17fXt9fT48PltbXV08PigpKCkpeygoe31bPD4oKCkpPD4oKSgpXSkpe3t9KHt9KCkpKCg8Pik8Pil9e319e308Pih7fTw-KQ&input=aGVsbG8gZWFydGgh&args=LWE) ``` ([]<{({}[((((((()()())){}){}){}){}){}()]){({}[({}())]){({}[({})]){({}[({}()())]){({}[({})]){({}<>)(<>)}}}}}{}{}}><>[[]]<>()()){(({}[<>(())<>()()])){{}({}())((<>)<>)}{}}{}<>({}<>) ``` This requires the `-c` flag to run in ASCII mode adding an extra 3 bytes to the length of the program. ## Ungolfed ``` ([]< {({}[(((((()()()){}){}){}){}){}()]) { ({}[()()()()]) { ({}[()()()()]) { ({}[(()()()){}]) { ({}[(()()()){}]) { ({}<>) (<>) } } } } } {} } ><>[[]]<>) (<(()()<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>) ``` ## Explanation First store the stack height for future purposes ``` ([]<...> ``` Then while the stack is not empty (assumes that none of the characters is zero) ``` {...} ``` Subtract ninety seven (and store 3 for later optimizations) ``` ({}[((((((()()())){}){}){}){}){}()]) ``` If it is not zero (i.e. not a) ``` {...} ``` Subtract 4 (and store 4 for later optimizations) ``` ({}[({}())]) ``` If it is not zero (i.e. not e) ``` {...} ``` Subtract 4 (and store 4 for later optimizations) ``` ({}[({})]) ``` If it is not zero (i.e. not i) ``` {...} ``` Subtract 6 (and store 6 for later optimizations) ``` ({}[({}()())]) ``` If it is not zero (i.e. not o) ``` {...} ``` Subtract 6 (store 6 because the program expects one later) ``` ({}[({})]) ``` If it is not zero (i.e. not u) ``` {...} ``` Move the remainder to the other stack and put a zero on the active stack to escape all of the ifs ``` ({}<>)(<>) ``` Once all of the ifs have been escaped remove the zero and the six ``` {}{} ``` Once all the characters have been processed subtract the height of the offset from the originally stored height. ``` ...<>[[]]<>) ``` Mod by two ``` {(({}[<>(())<>()()])){{}({}())((<>)<>)}{}}{}<>({}<>) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes ``` lžMÃgÉ ``` **Explanation** ``` l # convert to lower case žMÃg # count odd letters É # true if odd else false ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bMW-TcODZ8OJ&input=U2F2b2lF) [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~524, 446~~, 422 bytes ``` {(<((((()()()()){}){}){}<>)>)<>{({}[()])<>(({}[({})]())){{}(<({}({}))>)}{}<>}{}<>([(((({}<{}<>>))))]()){(<{}>)<>({}[()])<>}<>({}())<>{}([{}]()()()()()){(<{}>)<>({}[()])<>}<>({}())<>{}(((()()())){}{}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{}(((()()()()())){}{}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{}((((()()()){}())){}{}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{}}(<(()())>)<>{({}[()])<>(({}[({})]())){{}(<({}({}))>)}{}<>}{}<>({}<{}<>>) ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eyg8KCgoKCgpKCkoKSgpKXt9KXt9KXt9PD4pPik8Pnsoe31bKCldKTw-KCh7fVsoe30pXSgpKSl7e30oPCh7fSh7fSkpPil9e308Pn17fTw-KFsoKCgoe308e308Pj4pKSkpXSgpKXsoPHt9Pik8Pih7fVsoKV0pPD59PD4oe30oKSk8Pnt9KFt7fV0oKSgpKCkoKSgpKXsoPHt9Pik8Pih7fVsoKV0pPD59PD4oe30oKSk8Pnt9KCgoKCkoKSgpKSl7fXt9W3t9XSl7KDx7fT4pPD4oe31bKCldKTw-fTw-KHt9KCkpPD57fSgoKCgpKCkoKSgpKCkpKXt9e31be31dKXsoPHt9Pik8Pih7fVsoKV0pPD59PD4oe30oKSk8Pnt9KCgoKCgpKCkoKSl7fSgpKSl7fXt9W3t9XSl7KDx7fT4pPD4oe31bKCldKTw-fTw-KHt9KCkpPD57fX0oPCgoKSgpKT4pPD57KHt9WygpXSk8Pigoe31bKHt9KV0oKSkpe3t9KDwoe30oe30pKT4pfXt9PD59e308Pih7fTx7fTw-Pik&input=SGFsbG8&args=LWE) Ungolfed, more readable version: ``` {((((()()()()){}){}){})(<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>)((((({}))))) (()) ({}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{} (()()()()()) ({}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{} (()()()()()()()()()) ({}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{} (()()()()()()()()()()()()()()()) ({}[{}]){(<{}>)<>({}[()])<>}<>({}())<>{} (()()()()()()()()()()()()()()()()()()()()()) ({}[{}]) {(<{}>)<>({}[()])<>}<>({}())<>{}}<>(()())(<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>){{}([()]) (<><>)}({}{}()) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to @Luis Mendo (use `Ḃ` to replace `%2`) -1 byte thanks to @Dennis (use a string compression) ``` Œlf“¡ẎṢɱ»LḂ ``` All test cases are at **[TryItOnline](http://jelly.tryitonline.net/#code=xZJsZuKAnMKh4bqO4bmiybHCu0zhuIIKxbzDh-KCrEvigqxZ&input=&args=InRyZWVzIiwiYnJ1c2giLCJDQXRzIiwiU2F2b2llIiwicmh5dGhtIg)** How? ``` Œlf“¡ẎṢɱ»LḂ - Main link takes an argument - s Œl - lowercase(s) “¡ẎṢɱ» - string of lowercase vowels (compression using the words a and eoui) f - filter - keep only the vowels L - length - the number of vowels Ḃ - Bit (modulo 2) ``` --- **Non-competing, 5 bytes** (since I just added the function `Øc`) ``` fØcLḂ ``` Test cases also at **[TryItOnline](http://jelly.tryitonline.net/#code=ZsOYY0zhuIIKxbzDh-KCrEvigqxZ&input=&args=InRyZWVzIiwiYnJ1c2giLCJDQXRzIiwiU2F2b2llIiwicmh5dGhtIg)** Same as above, but `Øc` yields the Latin alphabet's vowels, `'AEIOUaeiou'` [Answer] # Python, 42 bytes ``` lambda s:sum(c in"aeiouAEIOU"for c in s)%2 ``` Not a whole lot to explain here. An unnamed function that returns 0 or 1. [Answer] # Haskell, ~~38~~ 37 bytes ``` odd.length.filter(`elem`"aeiouAEIOU") ``` Thanks to Angs for one byte! [Answer] # Python 3, 53 Bytes This can probably be golfed further: ``` lambda n:[x in 'aeiou' for x in n.lower()].count(1)&1 ``` [Answer] **C 52 bytes** ``` h(o){o=strpbrk(o,"aeiouAEIOU");return o?1^h(o+1):0;} ``` the main and the result: ``` main() {int k; char *a[]={"trees","brush","CAts","Savoie","rhythm", 0}; for(k=0;a[k];++k) printf("[%s]=%s\n", a[k], h(a[k])?"odd":"even"); } /* 91 [trees]=even [brush]=odd [CAts]=odd [Savoie]=even [rhythm]=even */ ``` [Answer] # Pyth, 14 bytes ``` %l@"aeiou"rQ02 ``` [Try it Online!](http://pyth.herokuapp.com/?code=%25l%40%22aeiou%22Q2&input=%22caaeeiiit%22&debug=0) Explanation: ``` @"aeiou" Grab only the vowels rQ0 From lowercased input l Get the length of this % 2 And mod 2 to check for oddness ``` [Answer] # Ruby, 30 bytes ``` ->w{w.scan(/[aeiou]/i).size%2} ``` [Answer] # Vim, ~~32, 31~~, 29 keystrokes ``` :s/[^aeiou]//gi C<C-r>=len(@")%2<cr> ``` Since the V interpreter is backwards compatible, you can [try it online!](http://v.tryitonline.net/#code=OnMvW15hZWlvdV0vL2dpCkMSPWxlbihAIiklMgo&input=SGVsbG9v) right here. *~~One~~ Three bytes saved thanks to m-chrzan!* [Answer] **Java, 73** ``` boolean f(String s){return s.replaceAll("(?i)[^aeiou]","").length()%2>0;} ``` saw a couple other java answers, otherwise wouldn't have shared. Thanks to Phaeze for saving a byte. [Answer] # [dimwit](https://github.com/MCMastery/dimwit), 14 bytes (non-competing) ``` ar[aeiou]}et}T ``` I thought this would be a fun, simple challenge to start with for a new language. ### Explanation * `a` - push a new array to the matrix * `r[aeiou]}` - count occurrences of all values matching the regex "[aeiou]" in the first array (since the first array contains the input), ignoring case, and push that value to the end of the last array. * `e` - if the last number in the last array is even (which we set to the number of occurrences), perform the next operations up until a closing bracket ("}") * `t` - stop execution, clear the matrix, and set the first value to be false * `}` - end of `e` code block * `T` - stop execution, clear the matrix, and set the first value to be true ### [Try it online!](http://dgrissom.com/dimwit/index.html?ar[aeiou]%7Det%7DT) Use the Input field to enter the word. I'll soon add documentation... [Answer] # [Bash](https://www.gnu.org/software/bash/), 36 bytes ``` x=${1,,//[aeiou]/} ((1&${#1}&${#x})) ``` [Try it online!](https://tio.run/##S0oszvj/v8JWpdpQR0dfPzoxNTO/NFa/lktDw1BNpVrZsBZEVtRqav7//98jNScnv9y/KCdFEQA "Bash – Try It Online") # [Zsh](https://www.zsh.org/), 30 bytes ``` ((1&$#1&${#${1:l}//[aeiou]/})) ``` [Try it online!](https://tio.run/##qyrO@P9fQ8NQTUUZiKuVVaoNrXJq9fWjE1Mz80tj9Ws1Nf///@@RmpPjX@5flJMCAA "Zsh – Try It Online") Accepts input as its first argument. Exits with nonzero if even, exits zero if odd. We *barely* beat out the bash+coreutils solution! ``` x=${1,,//[aeiou]/} # lowercase first argument, then remove all [aeiou] ((1&${#1}&${#x})) 1& & # bitwise-and 1 with ${#1} ${#x} # length of first parameter and length of stripped parameter (( )) # if nonzero, exit 0 (truthy in shell) ``` The Zsh solution is very similar, but uses the ability to nest parameter expansions to save an assignment. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` =/^"aeiou"?_: ``` [Try it online!](https://ngn.codeberg.page/k/#eJx1j8FKAzEQhu/zFCF40MM2LYLQBBHx5KmHHku1cXe2CW0zbTKpu4g+u21KLYje5uf7Z/im1ffqRVr0lOXDqwZg/XE167+iboUQnVnQylwvWuvXpjO9iTfzz0NnJjkiJmlG82N4izk5aYYlPD1yOs9TuyeP51p0PbtNSaDAMW+TVqqmBpe0bgeJbb3CrnY2LHFQ00btMib2FJIa346Hd8qnynNlQ0VNU71TbACewzazFqL4wCRzibjHcGFF74cddi/oKPs3Oan/c/H0yS8I8A2FOmuS) Returns `1` for "even" inputs and `0` for "odd" ones. * `_:` lowercase the (implicit) input * `^"aeiou"?` generate a bitmask indicating which characters in the (lowercased) input are *not* vowels * `=/` do an equals-reduce; if there are an even number of `0`s (i.e. vowels), this returns `1`. if there are an odd number, it returns `0` [Answer] ## [Retina](http://github.com/mbuettner/retina), 19 bytes ``` Mi`[aeiou] [13579]$ ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApNaWBbYWVpb3VdClsxMzU3OV0k&input=dHJlZXMKYnJ1c2gKQ0F0cwpTYXZvaWU) (The first line enables a linefeed-separated test suite.) The first line counts the vowels in the input. The second line checks that the result is odd. [Answer] # Java 7, 88 ``` boolean f(char[]s){int x=0;for(char c:s)if("aeiouAEIOU".indexOf(c)>=0)++x;return x%2>0;} ``` Ungolfed: ``` boolean f(char[] s) { int x = 0; for (char c : s) { if ("aeiouAEIOU".indexOf(c) >= 0) { ++x; } } return x % 2 > 0; } ``` [Answer] ## PowerShell v2+, ~~45~~ 42 bytes ``` ($args[0]-replace'[^aeiouAEIOU]').Length%2 ``` Takes input `$args[0]`, sends it through `-replace` to remove all non-vowel characters, takes the resulting `.length`, and `%2` to check whether it's odd/even. ### Examples ``` PS C:\Tools\Scripts\golfing> 'trees','brush','CAts','Savoie','rhythm'|%{"$_ --> "+(.\is-it-an-odd-word.ps1 $_)} trees --> 0 brush --> 1 CAts --> 1 Savoie --> 0 rhythm --> 0 ``` [Answer] # J, 20 bytes ``` 2|+/@e.&'aeiouAEOIU' ``` Straight-forward approach ## Explanation ``` 2|+/@e.&'aeiouAEOIU' Input: string S e.&'aeiouAEOIU' Test each char in S for membership in 'aeiouAEOIU' +/@ Sum those values 2| Take it modulo 2 and return ``` [Answer] # Japt, 7 bytes ``` 1&Uè"%v ``` [**Test it online!**](http://ethproductions.github.io/japt/?v=master&code=MSZV6CIldg==&input=InRyZWVzIg==) Outputs 1 for odd, 0 for even. ### How it works ``` // Implicit: U = input string Uè // Count the number of matches of the following regex in the input: "%v // /[AEIOUaeiou]/g 1& // Take only the first bit (convert 1, 3, 5, etc. to 1, and others to 0) // Implicit output ``` [Answer] # Octave, 34 bytes ``` @(s)mod(nnz(~(s'-'aeiouAEIOU')),2) s'-'aeiouAEIOU' % Creates a 2D-matrix where each of the odd letters are % subtracted from the string s ~(s'-'aeiouAEIOU') % Negates that array, so the all zero elements become 1 nnz( .... ) % Counts all the non-zero elements (the odd letters) mod(nnz( ....),2 % Takes this sum modulus 2 ``` This is 6 bytes shorter than the traditional approach using `ismember`, `@(s)mod(sum(ismember(s,'aeiouAEIOU')),2)`, and two bytes shorter than the regex approach: `@(s)mod(nnz(regexpi(s,'[aeiou]')),2)`. [Test it here](https://ideone.com/DfHDIN). [Answer] # PHP, 41 bytes ``` <?=count(spliti("[aeiou]",$argv[1]))%2-1; ``` This outputs -1 for truthy and 0 for falsey. [Answer] ## Mathematica, 44 bytes ``` OddQ@StringCount[#,Characters@"aeiouAEIOU"]& ``` Gives True for an odd string and False for an even one. [Answer] # q, 29 bytes ``` {mod[sum x in "aeiouAEIOU";2]} ``` [Answer] # C# ~~64~~ ~~62~~ ~~56~~ 50 Bytes ``` s=>1>s.Split("aeiouAEIOU".ToCharArray()).Length%2; ``` * ~~We are already using linq, so Contains saves 2 bytes over IndexOf~~ * ~~Using the method overload of Count saves 6 bytes~~ * Thanks to @Milk for suggesting a neat method and saving 6 more bytes An anonymous function that takes a string and counts the odd letters then returns true if there is an odd number of them or false if there is not. This new solution splits the string on any of the characters in the given char array. The mechanics of this flip the meaning of the `%2` result; 0 is now odd and 1 even hence the `1>`. [Try it online here!](https://dotnetfiddle.net/xWOl7z) ]
[Question] [ Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement: ``` 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 ``` It's the title of [this book](https://rads.stackoverflow.com/amzn/click/com/0262018462), and will simply print a sequence of `/` and `\` characters, alternating between the two randomly, resulting in a pattern similar to this: ![enter image description here](https://i.stack.imgur.com/waWtz.png) *(Image borrowed from <http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/>)* Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this: ``` while(1) { echo chr(47 + 45 * rand(0,1)); } ``` `chr(47)` is a `/` character, and chr(92) is a `\`. So the statement `echo chr(47 + 45 * rand(0,1));` will randomly alternate between the two, ad nauseam. In a language of your choosing, write the shortest program or function to output an infinite random sequence of `\` and `/` characters, where each character has an equal probability of being chosen. [Answer] Since this has been migrated to codegolf... ### PHP 30 bytes ``` <?for(;;)echo rand(0,1)?~Ð:~£; ``` The `Ð` is character 208, and the `£` is character 163. Sample usage (on a Windows box): ``` color 18 & php maze.php ``` Produces something similar to: ![](https://i.stack.imgur.com/SEW7W.png) It works best with a monospace font that is exactly square (here I've chosen the standard system font 8x8). To go back to your default color, you can type `color` again without any parameters. [Answer] # Mathematica 157 bytes Lacking PETSCII, I rolled my own "\" and "/". No cigar for brevity here. ``` Graphics[{Thickness[.005],RGBColor[0.73,0.55,1.],Line/@Flatten[Table[RandomChoice[{{{x,y},{x+1,y+1}},{{x+1,y},{x,y+1}}}],{x,40},{y,25}],1]},Background->Blue] ``` ![blue maze](https://i.stack.imgur.com/q9lJv.png) [Answer] The `goto` operator was added to PHP from version 5.3.0 so you could use the same method as you would in BASIC: ``` a: echo chr(47 + 45 * rand(0,1)); goto a; ``` [Answer] # Brainfuck - 534 ``` >+[->>>>>>[<<<<<<+>>>>>>-]>[<<<<<<+>>>>>>-]<<<<+++++++[<+++++++++++>-] <[<<[>>>>>>+<<<+<<<-]>>>[<<<+>>>-]<<[>>>>>+<<<+>+<<<-]>>>[<<<+>>>-]<[> >>>+[<<<+>+>>-]<<[>>+<<-]+<[>-<[-]]>[>+<-]<<-]<-]++++++[>++++++++<-]>- [<<[>>>>>+<<<<+<-]>[<+>-]>-]<<<[-]>[-]+++++[<+++++>-]<[>>>>>>>+[<<<<<< +>+>>>>>-]<<<<<[>>>>>+<<<<<-]+<[>-<[-]]>[>>>>+<<<<-]<<-]++++++[>>>>>>+ ++++++++<<<<<<-]>>>>>>[<<<<<<<+>+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]++<[->- [>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<[<<+>+>-]<<[>>+<<-]+>>[-]<[++++[>+ +++<---]>.[-]<<->]<[[>+<+++++]>----.[-]<]>+] ``` My prng (from [here](http://esolangs.org/wiki/Brainfuck_algorithms#x_.3D_pseudo-random_number)) is both large and extremely slow. Perhaps a simpler LFSR or similar would suffice, but this works: ![enter image description here](https://i.stack.imgur.com/XgPdb.png) [Answer] # Befunge, ~~12~~ ~~9~~ ~~8~~ 7 Bytes Edit: [James Holderness](https://codegolf.stackexchange.com/users/62101/james-holderness) figured out an insane solution that uses three quotes instead. ``` ?\","/" ``` Overflows the stack with a lot of excess characters for each symbol, but who cares when you can golf that 1 byte? ### Old version ``` "/\"?>,# ``` ~~(Note the trailing space)~~ Trailing space apparently not needed (thanks MercyBeaucou) [Try It Online](https://tio.run/##S0pNK81LT/3/X0k/RsneTkdZ4f9/AA) ``` "/\" Adds both / and \ to the stack ? Chooses a random direction to go in. Both up and down loop back around to the ? so it's 50% chance to go in either direction. Going left "/\" >,# Adds \ and / to the stack but only print the second, the / before heading back Going right >,# Prints the top of the stack, the \ before heading back ``` This does start to fill up the stack, with one extra symbol for every symbol printed. [Answer] ## C, 39 chars (38 on MSVC) ``` main(){while(putchar(rand()%2?47:92));} ``` ![enter image description here](https://i.stack.imgur.com/HOTCgm.png) [See it run.](http://ideone.com/CqYHL7) On MSVC, we can replace `putchar()` with `_putch()` and save a byte, but it doesn't work in IDEOne. ``` main(){while(_putch(rand()%2?47:92));} ``` [Answer] ## Common Lisp, 33 ``` (loop(princ(elt"/\\"(random 2)))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ø^XȮß ``` [Try it online!](https://tio.run/##y0rNyan8///wjLiIE@sOz///HwA "Jelly – Try It Online") `XØ^ß` is a byte shorter, but prints a `0` before the slashes. ``` X Choose a random element from Ø^ "/\", Ȯ print it, ß then call this link again. ``` [Answer] `print` has a return value of 1, so if you use that you can just wrap the whole expression in the `while`: `while(print chr(47 + 45 * rand(0,1));` You can probably golf it further too. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` {k/℅₴ ``` No trying it online It was a smart choice adding all of the two byte constants of 05ab1e and Jelly. [Answer] # [C (gcc)](https://gcc.gnu.org/), 47 bytes ``` main(){while(putchar(47+45*(rand()/(1<<30))));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6PCMzJ1WjoLQkOSOxSMPEXNvEVEujKDEvRUNTX8PQxsbYQBMIrGv//wcA "C (gcc) – Try It Online") [Answer] ## Python 3, ~~59~~ 51 bytes Using only 1 line (in the spirit of the original 10 PRINT): ~~`from random import*;exec("while 1:print(end=choice('\/'))")`~~ ``` while 1:from random import*;print(end=choice('\/')) ``` Or (possibly not that random) using hash for just 47 bytes (but on 2 lines): ``` x=0 while 1:x=hash(str(x));print(end='\/'[x%2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8LWgKs8IzMnVcHQqsI2I7E4Q6O4pEijQlPTuqAoM69EIzUvxVY9Rl89ukLVKFbz/38A "Python 3 – Try It Online") [Answer] ## ruby, 27 23 chars ``` loop{$><<"/\\"[rand 2]} ``` `$><<` is 'print to stdout'. [Answer] # C++, 45 Chars ``` int main(){for(;;)cout<<(rand()%2?"/":"\\");} ``` Not going to win any awards for shortness, but I had already written this when I heard about the mentioned book, so I just golfed it. The putchar trick also works in C++, getting you down to 43, but you can't avoid declaring the return type on main. [Answer] i try create using css style, and it's work ``` <style> body { font-family: monospace; line-height:75%; letter-spacing:-3px; } </style> ``` this php code : ``` <?php $i=10000; while($i) { if($i%200 == 0) echo '<br/>'; echo chr(47 + 45 * rand(0,1)); $i--; } ?> ``` [Answer] # Common Lisp - 68 ``` (defun s(l)(elt l(random(length l))))(loop do(format t"~a"(s"/\\"))) ``` [Answer] ## Python, 68 In the "my language sucks at this" category, we've got Python! ``` import random,sys while 1:sys.stdout.write(random.choice('/\\')) ``` Thanks to Ivo for a few chars on imports and `choice`. [Answer] ## 16-bit x86 assembly code, 10 bytes I don't remember if this one ended up in the book. ``` init: scasb ;read from where ES:DI points and compare to AL ;this sets flags similar to a subtraction salc ;set mask in AL to 00 or FF and al,'\'-'/' ;begin choosing character (AL is 00 or 2D) add al,'/' ;finish choosing character writec: int 29h ;write char in AL jmp init ;loop endlessly ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ["/\"Ω? ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/Wkk/RuncSvv//wE "05AB1E – Try It Online") ``` ["/\"Ω? - Full program [ Start an infinite loop "/\" ... Push the string "/\" on the stack Ω ... Pick a character from the top of the stack, at random ? ... Print without a newline ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 7 bytes ``` ? '/,\' ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3V1DX14lR//8fAA "Befunge-98 (PyFunge) – Try It Online") the `?` sends the IP either left or right, so either `/` or `\` is pushed before printing with `,`. When executing the `'/` or `\'` in the wrong order after printing, it just does things to the stack (divides or swaps), and then pushes an irrelevant character before repeating. [Answer] # PHP, ~~26~~ 31 bytes ~~eight~~ three bytes shorter than yours (without whitespace or braces)~~, two bytes shorter than [primo´s solution](https://codegolf.stackexchange.com/a/9170/55735) (without the tag)~~. PHP 5.4.9 was the current version in December 1012, so ... ``` for($s="\/";;)echo$s[rand()%2]; ``` ~~requires PHP 5.5 or later for literal string indexing.~~ Run with `-r` or [try it online](http://sandbox.onlinephpfunctions.com/code/f622d0f9cdb06e92357a2c243fe5aca069d1875f). [Answer] ## [Keg](https://esolangs.org/wiki/Keg#Command_Glossary), 12 bytes You do not have to worry about the evenness 0f the output, because the range is 0 to 32767, and 32767+1 = 32768; it is an even number. ``` {~2%[\\|\/], ``` [Answer] # HTML+JS, 186 ``` <pre style="letter-spacing:-3.5px;line-height:9px;;white-space: pre-wrap;line-break: anywhere;" onclick="setInterval(_=>this.innerHTML+='/\\'[2*Math.random()|0])">C l i c k m e !</pre> ``` [Answer] Not much better. Needs php 5.5+ for the array dereferencing feature. ``` while(1) { echo ['/', '\\'][rand(0, 1)]; } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 14 bytes I was hoping I could restrict it to a 3\*3 square but didn't succeed. ``` "/\ ~x/ o</ ! ``` You can try it [here](https://fishlanguage.com/playground). [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 12 bytes ``` D<^<!"/\"B!o ``` **[View in the online interpreter!](https://ethproductions.github.io/cubix/?code=RDxePCEiL1wiQiFv&input=&speed=50)** This maps out to the following cube net: ``` D < ^ < ! " / \ " B ! o . . . . . . . . . . . . ``` ## Explanation **Setup:** The IP begins heading east at the first `!`. This is the 'skip if truthy' command, which is False when there is nothing on stack, so no commands are skipped. `"/\"` enters stringmode and appends these two character codes to the stack. `B!o` is mostly a no-op here, only reversing the stack. The IP now loops back around to the first `!`. However, there are now positive integers on stack, so the first `"` is skipped. This means `/` is no longer a character, but a mirror, sending the IP north into the main loop. **Main Loop:** The `D` command is the only source of randomness in Cubix. It sends the IP in a random direction. By blocking off South and East with arrows, we make sure the IP has a 50% chance of heading North, and a 50% chance of heading West. If it heads West, the stack is reversed. If it heads North, the top character is printed. This creates the random sequence of slashes, as desired. [Answer] # SmileBASIC, 20 bytes ``` ?"/\"[RND(2)]; EXEC. ``` [Answer] # [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/overview), ~~108~~ ~~90~~ ~~86~~ ~~54~~ ~~53~~ ~~37~~ 36 bytes ``` for(){Write-Host "\/"[(Random 2)]-n} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEOzOrwosyRV1yO/uERBKUZfKVojKDEvJT9XwUgzVjev9v9/AA "PowerShell – Try It Online") [Answer] # Java 8, ~~60~~ ~~59~~ ~~54~~ 53 bytes ``` v->{for(;;)System.out.write(Math.random()<.5?47:92);} ``` -1 byte thanks to *@BenjaminUrquhart* by replacing `print` with `write`, so `'/'` can be `47`. **Explanation:** [Try it online](https://tio.run/##ZY49D4IwFEV3f8Ub24EORmO0fkyOspi4GIdnKVKFlrQP1BB@O4K4ubybl9yce@5YY3RPHp3KMQQ4oLHNBMBY0j5FpSEeXoDamQQUOw1Rc6DMu2eA/Uvpkoyzsi@1k/4EQjIKYrCwga6Otk3qPJOSH9@BdCFcReLpDWl2QMqER5u4gvG1mO9mi9VyymXbyQFUVte8B/143/mil2NH8sbezhf8lxhNrVDMVnnOR6e2@wA) (times out after 60 sec). ``` v->{ // Method with empty unused parameter and no return-type for(;;) // Loop indefinitely System.out.write( // Print: Math.random()<.5? // If the random decimal value in range [0,1) is below 0.5: 47 // Print forward slash : // Else: 92);} // Print backward slash ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 10 bytes ``` Du\'^>o$/; ``` [Watch it run](https://ethproductions.github.io/cubix/?code=RHVcJ14+byQvOw==&input=&speed=20) ``` D u \ ' ^ > o $ / ; . . . . . . . . . . . . . . ``` Was an interesting one to do as i haven't played with the random direction generator much. * `^D` redirect to the random direction pointer Directed north * `o\>` loops around the cube, print empty stack and redirecting back into the print commands (stack is empty) Directed west * `^` redirected back into the random direction pointer Directed south * `\'/>` reflected to the east, push / onto the stack and redirect into the print commands Directed east * `u'\>` uturn to the right, push \ onto the stack and redirect into the print commands Print commands * `o$/;^` output top of stack, skip over the reflect, pop from the stack and redirect into the random direction pointer ]
[Question] [ Inspired by [this](https://stackoverflow.com/q/33787939/509868) question: Make a function (or a full program) that receives a list of numbers and outputs the list rearranged, so that even-indexed numbers appear first, and odd-indexed numbers follow. The values of the numbers themselves don't affect ordering - only their indices do. All indices are zero-based. For example: Input: `[0, 1, 2, 3, 4]` Output: `[0, 2, 4, 1, 3]` Another example: Input: `[110, 22, 3330, 4444, 55555, 6]` Output: `[110, 3330, 55555, 22, 4444, 6]` Use most natural representation for lists that your language has. There are no limitations on complexity (e.g. allocating a temporary list is OK - no need to do it in-place). P.S. It should work for the empty list (empty input => empty output). [Answer] ## Python, 23 bytes ``` lambda x:x[::2]+x[1::2] ``` [Try it online](http://ideone.com/fork/CFl1vm) [Answer] # Pyth, 5 ``` o~!ZQ ``` [Try it online](http://pyth.herokuapp.com/?code=o~%21ZQ&input=%5B1%2C2%2C3%2C4%2C5%5D&debug=0), or run a [Test Suite](http://pyth.herokuapp.com/?code=o~%21ZQ&input=%5B1%2C2%2C3%2C4%2C5%5D&test_suite=1&test_suite_input=%5B%5D%0A%5B1%5D%0A%5B0%2C1%2C2%2C3%5D%0A%5B0%2C1%2C2%2C3%2C4%5D%0A%5B110%2C%2022%2C%203330%2C%204444%2C%2055555%2C%206%5D&debug=0) ### Explanation ``` o~!ZQ ## implicit: Z = 0; Q = eval(input) o Q ## sort Q using a supplied function ~!Z ## Use the old value of Z, then set Z to be not Z ## This assigns a weight to each number in the list, for example given [0,1,2,3,4] ## This will give (value, weight) = [(0,0), (1,1), (2,0), (3,1), (4,0)] ## The values are sorted by weight and then by index ## This happens because Pyth is written in Python, which performs stable sorts ``` [Answer] ## CJam, 7 bytes ``` {2/ze_} ``` Pushes a block (the closest thing to an unnamed function) which transforms the top stack element as required. [Test it here.](http://cjam.aditsu.net/#code=%7B2%2Fze_%7D%3AF%3B%0A%0A%5B110%2022%203330%204444%2055555%206%5D%0AFp) ### Explanation The explanation assumes that the top of the stack is the array `[0 1 2 3 4]`. The actual values don't affect the computation. ``` 2/ e# Split the array into chunks of two: [[0 1] [2 3] [4]] z e# Zip/transpose, which works on ragged arrays: [[0 2 4] [1 3]] e_ e# Flatten the result: [0 2 4 1 3] ``` [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), ~~28~~ ~~25~~ ~~24~~ ~~23~~ 22 bytes ``` " > ?!?:|}\{@ @\?"":)! ``` This was mad fun! :) That is by far the most densely compressed Labyrinth program I've written so far. I had so many versions at 20 and 21 bytes which *almost* worked that I'm still doubting this is optimal... This takes input as a list of *positive* integers (with an arbitrary delimiter), and prints the result to STDOUT as linefeed-delimited integers. **The hunt for 20/21 bytes:** I've checked all programs of the form ``` " XX ?!?X}\{@ @\?XX)! ``` where `X` is any reasonable character by brute force, but didn't find any valid solutions. Of course that doesn't mean that a shorter solution doesn't exist, but it's not possible to force 20-byte programs without a decent amount of assumptions on its structure. ### Explanation *(The explanation is slightly outdated, but I'm still not convinced the solution is optimal, so I'll wait with updating this.)* So, normally Labyrinth programs are supposed to look like mazes. While the instruction pointer is in a corridor, it will follow that corridor. When the IP hits any kind of junction, the direction is determined based on the top value of Labyrinth's main stack (Labyrinth has two stacks, with an infinite amount of zeroes at the bottom). That normally means that any non-trivial loop will be quite expensive, because if you have non-wall cells all over the place *everything* is a junction, and in most cases the top of the stack won't have the right value for the IP to take the path you would like it to take. So what you do is you enlarge the loops such that they have a whole in the centre with only one well-defined entry and exit point each. But this time I was really lucky and everything fit so well together, that I could squash it all into one big clump. :) Control flow starts at the `_` going South. The `_` pushes a zero onto the main stack. That may seem like a no-op, but this increases the (non-implicit) stack depth to `1` which we'll need later. `?` reads an integer from STDIN. If there are no more integers to be read, this pushes zero. In that case, the IP keeps moving South and `@` terminates the program right away (because the input list is empty). Otherwise, the IP turns East. We're now entering a very tight loop with two exit points: ``` !?; \? ; ``` `!` prints the integer back to STDOUT, leaving only a zero on the stack. The IP keeps moving East, and `?` reads the next integer. If that is non-zero, we take a right and move South. `?` reads another one (the next even index). Again, if that is non-zero, we take a right and move West. Then `\` prints a linefeed without changing the stack, so we take another right, moving North. `!` prints that next even-index integer. Since now there is at least one (positive) odd-index integer on the stack, we keep turning right and the loop repeats. Once either of those `?` hits the end of the list, they push a zero and move straight onto the corresponding `;`, which discards that zero. In the case that there was only a single element in the list, we're done (because we've printed that right away), so the IP would keep moving East all the way to the `@`, again terminating the program (printing a trailing linefeed on the way). Otherwise, we need to print the odd-index integers as well. In that case the two paths (from the two exit points of the first loop) merge on the middle `"`, turning East in either case. `_` pushes a zero to avoid taking a left into the `@`, and `;` discards that zero. Now we enter a new loop: ``` "} "" ``` The IP enters this on the bottom-left cell, moving North, going around the loop in a clockwise sense. The `}` shifts the top of the main stack over to the auxiliary stack. While there is still an element on the stack, the IP keeps doing its thing. Once everything has been shifted to the auxiliary stack (and reversed in the process), the IP keeps moving East instead, entering the last loop: ``` \{@ #! ``` `\` prints a linefeed again, `{` moves an item from the auxiliary stack back to main. If that was still an item of the list, it will be positive, and the IP turns South, where the item is printed with `!`. Then `#` pushes the stack depth (and now this is where the initial `_` is important, because this `#` ensures a positive stack depth), so that the IP still turns right, through the `\` and `{` again. After we've printed everything, `{` pulls a zero from the bottom of the auxiliary stack, the IP continues East, and `@` terminates the program. [Answer] # MATLAB, 24 ``` @(x)x([1:2:end 2:2:end]) ``` similar to the python one. Thanks @LuisMendo for saving 2 bytes! [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` concat.foldr(\x[l,r]->[x:r,l])[[],[]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802OT8vObFELy0/J6VII6YiOkenKFbXLrrCqkgnJ1YzOjpWJzo29n9uYmaegq1CQVFmXomCikKaQrShnp5l7H8A "Haskell – Try It Online") The `foldr` recursively builds up the even list and odd list. Prepending an element to the list is updated by prepending it to the odd list and calling it the new even list, and calling the previous even list the new odd list. Then, the pair `[l,r]` is concaternated to `l++r`. Thanks to Ørjan Johansen for saving 5 bytes using two-element lists in place of tuples. --- **42 bytes:** ``` f l=[x|p<-[even,odd],(i,x)<-zip[0..]l,p i] ``` Adds indices to the list `l` and filters either the even or the odd ones. --- ``` g(a:_:l)=a:(g l) g l=l f l=g l++(g$drop 1 l) ``` Yet another format, for 44. The function `g` takes every even-indexed element. The odd indices are gotten by first dropping an element, then applying `g`. If `l` was guaranteed non-empty, we could safely just do `tail` for 41 ``` g(a:_:l)=a:(g l) g l=l f l=g l++g(tail l) ``` [Answer] ## J, 8 bytes ``` /:0 1$~# ``` This is a monadic (one-argument) verb, used as follows: ``` (/:0 1$~#) 110 22 3330 4444 55555 6 110 3330 55555 22 4444 6 ``` ## Explanation ``` /: Sort the input array according to 0 1 the array 0 1 $~ repeated enough times to be of length # length of input ``` [Answer] ## PowerShell v3+, ~~75~~ ~~67~~ ~~49~~ 47 bytes ``` $l=,@()*2 $args|%{$l[($f=!$f)]+=$_} $l[0] $l[1] ``` [Try it online!](https://tio.run/##bZDRaoQwEEXf8xWz2bEk3SkYtT4UBP9jkUW60RZCa9XSgvrt7kS3Fpa9D8PMvWcGkubzx7bdm3VuxgoyGGZ0GeVKP0YCy7buxmBAd1RYZTusdHHI8DQJdsLCV1PMkxC5EsAilauQwBBEBLEmCJfO@OEOQJBsTHKLGeMDj8UxdwmL4NmLIOW1JV@zq@vhFUv/zzDJRQsNIwQwLD6WhPa3sa@9PfOL8bS6re2@Xc/GA39EXsIeusaVff/@US@ARCWvkHyyX3K7IfXL37YU03wB "PowerShell – Try It Online") Expects input via splatting, as shown on the TIO link. Creates an matrix `$l` as an array of arrays, then pipes the input `$args` into a loop `|%{}`. Each time through the loop, we add an element to one of the two child arrays of `$l` by flip-flopping the `$f` variable using Boolean logic. The first time through, `$f` is `$null`, the `!` of which is `$true`, or `1` when indexing into an array. This means the first element gets put into the second array of `$l`, so that's why `$l[1]` gets output first. *Props to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) for the golfing assistance and this variation.* *-2 bytes thanks to mazzy.* --- ### Caveats Going strictly as the question is written, this is technically invalid, as PowerShell doesn't have a concept of "lists" as pseudo-immutable objects, only arrays or hash tables (aka dictionaries). So, I'm treating the question's line "*Use most natural representation for lists that your language has*" as asking about arrays, as that's the closest PowerShell has. Additionally, output is one element per line, since that's the default PowerShell way to write out an array. This means an input of `(0,1,2,3,4)` will output `0\r\n2\r\n4\r\n1\r\n3\r\n`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 3 bytes ``` ŒœF ``` [Try it online!](https://tio.run/##y0rNyan8///opKOT3f4fbn/UtObopIc7ZwDpyP//ow0NDXQUjIx0FIyNjYEsEyDQUTAFAR0Fs1gdhWigoCFQBVABUBYkEAsA "Jelly – Try It Online") ## How it works ``` ŒœF - Main link. Argument: L (a list) e.g. Œœ - Odd-even; Group elements at even and odd indices F - Flatten ``` [Answer] # F#, ~~79~~ ~~77~~ 56 ``` fun x->List.foldBack(fun x (l,r)->x::r,l)x ([],[])||>(@) ``` Based on one of the Haskell answer ``` fun x->x|>List.indexed|>List.partition(fst>>(&&&)1>>(=)0)||>(@)|>List.map snd ``` We first index the list, then partition it with criteria : first item (the index) anded with 1 equal 0. That gives us a pair of list of pairs ; first list will contains all indexed evens and the other the indexed odds. From that we reassemble the two list with append operator and finally discard the index. *Edit : missed an obvious one there is no need to name the arg "xs" (habits) so can reduce to a 1-letter name* --- I also have a potential 76 bytes one which is basically the same one but defined as function composition. Problem is it doesn't compile **as a value** but will effectively work with any list argument given so unsure if it's ok or not : ``` List.indexed>>List.partition(fst>>(&&&)1>>(=)0)>>fun(e,o)->e@o|>List.map snd ``` --- *Note: List.indexed is only available from F#4.0 despite not being documented in MSDN yet* [Answer] # JavaScript (ES6), 52 bytes It also does it in one pass ``` x=>x.map((v,i)=>x[(i*=2)>=(z=x.length)?i-z+--z%2:i]) ``` ``` F=x=>x.map((v,i)=>x[(i*=2)>=(z=x.length)?i-z+--z%2:i]) input.oninput = setValue; function setValue() { var arr = input.value.match(/\d+/g) || []; unsorted.innerHTML = arr.join(', '); sorted.innerHTML = F(arr).join(', '); } setValue(); ``` ``` * { font-family: monospace } th { text-align: right; padding-right: 0.5em; } ``` ``` <input id="input" type="text" value="0 1 2 3 4 5 6"/> <hr/> <table> <tr> <th>Unsorted:</th> <td id="unsorted"></td> </tr> <tr> <th>Sorted:</th> <td id="sorted"></td> </tr> </table> ``` [Answer] # [convey](http://xn--wxa.land/convey/), 16 bytes ``` { "\`0 |@&;`} 2} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoie1xuXCJcXGAwXG58QCY7YH1cbjJ9IiwidiI6MSwiaSI6IjAgMSAyIDMgNCJ9) [![test run](https://i.stack.imgur.com/Ld8fv.gif)](https://i.stack.imgur.com/Ld8fv.gif) Get the input `{` at the top, copy `"` down and left. The list mod `|` 2 chooses `@` if the elements go down straight into the output `}` or right into the queue `&`. After the last element has passed through `\`, the length `n` of the list gets pushed to `:`, where `n` elements from the queue then gets passed through. [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ``` ó ``` [Try it online!](https://tio.run/##y0osKPn///Dm//@jDXQUDHUUjHQUjHUUTGIB "Japt – Try It Online") [Answer] # Julia, 23 bytes ``` i->i[[1:2:end;2:2:end]] ``` [Answer] ## [Perl 6](http://perl6.org), 25 bytes This is the shortest lambda I could come up with. ``` {|.[0,2...*],|.[1,3...*]} # 25 byte "Texas" version {|.[0,2…*],|.[1,3…*]} # 25 byte "French" version ``` ``` say {|.[0,2…*],|.[1,3…*]}( ^5 ); # (0 2 4 1 3)␤ say ((0..4),('m'..'q'),(5..9)).map: {|.[0,2…*],|.[1,3…*]} # ((0 2 4 1 3) (m o q n p) (5 7 9 6 8))␤ # bind it as a lexical sub my &foo = {|.[0,2…*],|.[1,3…*]} say foo [110, 22, 3330, 4444, 55555, 6]; # (110 3330 55555 22 4444 6)␤ say [~] foo 'a'..'z' # acegikmoqsuwybdfhjlnprtvxz␤ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes ``` ñÏu ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c91&input=WzExMCwgMjIsIDMzMzAsIDQ0NDQsIDU1NTU1LCA2XQotUQ==) ``` ñÏu :Implicit input of array ñ :Sort by Ï :Passing the 0-based index of each through a function u : Modulo 2 of index ``` --- ``` ó c ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8yBj&input=WzExMCwgMjIsIDMzMzAsIDQ0NDQsIDU1NTU1LCA2XQotUQ==) ``` ó c :Implicit input of array ó :Split into 2 arrays of every 2nd item c :Flatten :Implicit output ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ΣTC2 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@5xSHORv///4@ONtAx1DHSMdYxidWJNjQ00DECcoyNDXRMgEDHFAR0zGJjAQ "Husk – Try It Online") ``` C2 # split list into 2-element sublists T # transpose Σ # flatten list of lists ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 30 bytes ``` s/\S+\K( \S+)( ?)/$\.=$1;$2/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZYO8ZbQwFIaWoo2Gvqq8To2aoYWqsY6aen/v9voGCoYKRgrGCiYKpgpmCuYKFgqWBo8C@/oCQzP6/4v66vqZ6BocF/3QIA "Perl 5 – Try It Online") Input and output are space separated. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ι˜ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3M7Tc/7/jzY0NNBRMDLSUTA2NgayTIBAR8EUBHQUzGIB "05AB1E – Try It Online") ## How it works ``` ι˜ - Program. Push the input L to the start ι - Uninterleave L ˜ - Flatten ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes ``` {t,x^t:x@&(0=2!)'!#x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6ou0amIK7GqcFDTMLA1UtRUV1SuqOXiSos2UDBUMFIwVjCJBXIMDQ0UjIA8Y2MDBRMgUDAFAQWzWAAXng7R) *Down 2 bytes thanks to ngn* # [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes ``` {t:x@&(0=2!)'!#x;t,x^t} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6ousapwUNMwsDVS1FRXVK6wLtGpiCup5eJKizZQMFQwUjBWMIkFcgwNDRSMgDxjYwMFEyBQMAUBBbNYADmdD4A=) The old solution is kept because of the explanations. Explanations: ``` {t:x@&(0=2!)'!#x;t,x^t} Main function. Takes x as input ! Create a range from 0 to #x Length of x - 1 ' For each number in the range (i) ( ) Check if 2! i mod 2 0= is equal to 0 & Where (get indices of truthy values) x@ x at each indices t: ; Assigned to variable t t, t concat with x^t x without the elements in t ``` [Answer] # [Fig](https://github.com/Seggan/Fig), \$2\log\_{256}(96)\approx\$ 1.646 bytes ``` fy ``` [Try it online!](https://fig.fly.dev/#WyJmeSIsIlsxMTAsIDIyLCAzMzMwLCA0NDQ0LCA1NTU1NSwgNl0iXQ==) ``` fy y # Uninterleave f # Flatten ``` [Answer] ## Mathematica, 40 bytes ``` #[[;;;;2]]~Join~If[#=={},#,#[[2;;;;2]]]& ``` `{}[[2;;;;2]]` will throw an error. [Answer] ## Burlesque, 12 Bytes ``` J2ENj[-2EN_+ ``` Usage as in: ``` blsq ) {0 1 2 3 4}J2ENj[-2EN_+ {0 2 4 1 3} blsq ) {110 22 3330 4444 55555 6}J2ENj[-2EN_+ {110 3330 55555 22 4444 6} ``` **Explanation:** ``` J -- duplicate 2EN -- every 2nd element j -- swap [- -- tail 2EN -- every 2nd element _+ -- concatenate parts ``` Although once the new update is released you can do this with the new *Unmerge* built-in (which does the opposite of the merge `**` built-in): ``` blsq ) {110 22 3330 4444 55555 6}J2ENj[-2EN** {110 22 3330 4444 55555 6} ``` [Answer] # K, 10 bytes ``` {x@<2!!#x} ``` Based on the 5-byte Pyth answer. [Answer] # Perl, ~~35~~ 33 bytes ``` perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"' ``` 31 bytes + 2 bytes for `-ap`. Reads a space-delimited string from STDIN: ``` $ echo 0 1 2 3 4 | perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"' 0 2 4 1 3 $ echo 110 22 3330 4444 55555 6 | perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"' 110 3330 55555 22 4444 6 ``` When the input is empty, prints a single space, which I would consider equivalent to an empty list. If not, can be fixed at a cost of 4 bytes with: ``` perl -anE 'push@{$|--},$_ for@F;$,=$";say@0,@1' ``` (requires Perl 5.10+, prints a trailing newline) or at a cost of 5 bytes with: ``` perl -ape 'push@{$|--},$_ for@F;$_=join$",@0,@1' ``` (no trailing whitespace) ## How it works This solution uses the `-a` flag, which splits the input on whitespace and puts the results in the `@F` array. The real magic happens in the `push`: ``` push@{$|--},$_ ``` The [`$|` variable](http://perldoc.perl.org/perlvar.html#%24%7C) is normally used to force output flushing, but it has another interesting property: when decremented repeatedly, its value toggles between 0 and 1. ``` perl -E 'say $|-- for 0..4' 0 1 0 1 0 ``` Taking advantage of the fact that [there are no restrictions on identifiers specified via symbolic dereferencing](https://stackoverflow.com/a/4800711/176646), we alternately push array elements onto the `@0` and `@1` arrays, so `@0` ends up with all the even-indexed elements and `@1` with the odds. Then we simply concatenate the stringified arrays to get our output. [Answer] ## C, 70 Nothing special, just a index mapping function. ``` a=0;main(int c,int** v){for(c--;a<c;)puts(v[1+a*2%c+!(a++<c/2|c%2)]);} ``` **Less golfed** ``` a=0; main(int c, int** v) { for(c--; a<c;) puts(v[1 + a*2%c + !(a++ < c/2 | c%2) ]); } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes ``` {⍵[⍒2|⍳≢⍵]} ``` Alternatively: ``` {⍵[⍒≠\=⍨⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71box/1TjKqedS7@VHnIiA3thYopWBoaKBgZKRgbGxsoGACBAqmIKBgBgA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` {⍵[⍒2|⍳≢⍵]} ⍳≢⍵ ⍝ indices from 1 to the length of the input vector. 2| ⍝ their divisibility by two; essentially generate 1 0 1 0... ⍒ ⍝ grade down: put odd indices first before even indexed indices. ⍵[ ] ⍝ pick from the input ``` [Answer] # JavaScript, 49 bytes ``` n=>[...(x=f=>n.filter((a,b)=>b%2==f))(0),...x(1)] ``` Explanation: Creates a list composed of the results of spreading arrays filtered by the index of each element modulo 2. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~53~~ ~~36~~ 30 bytes ``` ->a{i=0 a.sort_by{[i%2,i+=1]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhb7dO0SqzNtDbgS9Yrzi0rikyqrozNVjXQytW0NY2trIYpuhhcouEVHG-gY6hjpGOuY6JjqmOmYx8YqKCvY2ikAxY2AYmZAWWOgjHksF6Zq7GpjIcYvWAChAQ) ## Ruby, 24 bytes This appears to work but could fail *in theory* because "the ordering of equal elements is indeterminate and [may be unstable](https://ruby-doc.org/core-3.1.2/Enumerable.html#method-i-sort_by)." Sorting by `[i%2,i+=1]` above [solves this instability](https://8thlight.com/blog/will-warner/2013/03/26/stable-sorting-in-ruby.html). ``` ->a{i=1 a.sort_by{i^=1}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY7dO0SqzNtDbkS9Yrzi0rikyqrM-NsDWtrIdI3wwsU3KKjDXQMdYx0jHVMdEx1zHTMY2MVlBVs7RSA4kZAMTOgrDFQxjyWC1M1drWxEOMXLIDQAA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` y"f ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwieVwiZiIsIiIsIlswLCAxLCAyLCAzLCA0XVxuWzExMCwgMjIsIDMzMzAsIDQ0NDQsIDU1NTU1LCA2XSJd) Uninterleave, pair the results and flatten ]
[Question] [ On most [new-years](/questions/tagged/new-years "show questions tagged 'new-years'") challenges when it is currently not the corresponding year of the challenge, It says this in the front. > > It's [current year] already, folks, go home. > > > You have to output this text with the current year substituted. --- # I/O **Input:** None. **Output**: `It's [current year] already, folks, go home.` [Answer] # bash + date, 40 bytes ``` date +"It's %Y already, folks, go home." ``` [Try it online!](https://tio.run/nexus/bash#@5@SWJKqoK3kWaJerKAaqZCYU5SamFKpo5CWn5NdrKOQnq@QkZ@bqqf0/z8A "Bash – TIO Nexus") [Answer] # C (gcc), 58 bytes ``` f(){printf("It's%s already, folks, go home.",__DATE__+6);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 20 bytes Saved a byte thanks to *Erik the Outgolfer* ``` žg“It's ÿˆ§,¹Ò,‚œ€¨. ``` [Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//xb5n4oCcSXQncyDDv8uGwqcswrnDkizigJrFk@KCrMKoLv// "05AB1E – TIO Nexus") [Answer] # TeX (44 bytes) ``` It's \the\year\ already, folks, go home.\bye ``` [Answer] # PHP, 42 bytes ``` It's <?=date(Y)?> already, folks, go home. ``` [Answer] # Bash, 45 characters ``` printf "It's %(%Y)T already, folks, go home." ``` Bash's built-in `printf` in version 4.2 got the `%(fmt)T` format specifier and since version 4.3 it defaults to current timestamp in absence of argument. Sample run: ``` bash-4.3$ printf "It's %(%Y)T already, folks, go home." It's 2017 already, folks, go home. ``` [Answer] ## Batch, 45 bytes ``` @echo It's %date:~6% already, folks, go home. ``` Batch is actually reasonably competitive for once. [Answer] ## Mathematica, 53 bytes ``` Print["It's ",Now[[1,1]]," already, folks, go home."] ``` [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` import time print"It's",time.gmtime()[0],"already, folks, go home." ``` [Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbylVQlJlXouRZol6spAMS0EvPBVEamtEGsTpKiTlFqYkplToKafk52cU6Cun5Chn5QEVK//8DAA "Python 2 – TIO Nexus") [Answer] # x86 machine code on DOS - 62 bytes ``` 00000000 b4 04 cd 1a bf 23 01 88 c8 24 0f 00 05 4f c1 e9 |.....#...$...O..| 00000010 04 75 f4 ba 1b 01 b4 09 cd 21 c3 49 74 27 73 20 |.u.......!.It's | 00000020 30 30 30 30 20 61 6c 72 65 61 64 79 2c 20 66 6f |0000 already, fo| 00000030 6c 6b 73 2c 20 67 6f 20 68 6f 6d 65 2e 24 |lks, go home.$| 0000003e ``` Even though the input from the BIOS is in BCD (as opposed to the plain 16 bit value got from the equivalent DOS call), decoding it to ASCII turned out to be almost as long as base-10 printing a register. Oh well. ``` org 100h section .text start: mov ah,4 int 1ah ; get the date from BIOS; cx now contains the year in packed BCD mov di,placeholder ; put di on the last character of placeholder lop: mov al,cl and al,0xf ; get the low nibble of cx add [di],al ; add it to the digit dec di ; previous character shr cx,4 ; next nibble jnz lop ; loop as long as we have digits to unpack in cx mov dx,its mov ah,9 int 21h ; print the whole string ret its: db "It's 000" placeholder: db "0 already, folks, go home.$" ``` [Answer] ## Ruby, 52 bytes ``` puts"It's #{Time.now.year} already, folks, go home." ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 38 bytes ``` "It's "et0=" already, folks, go home." ``` [Try it online!](https://tio.run/nexus/cjam#@6/kWaJerKCUWmJgq6SQmFOUmphSqaOQlp@TXayjkJ6vkJGfm6qn9P8/AA "CJam – TIO Nexus") [Answer] # Mathematica, 58 bytes ``` "It's "<>ToString@#<>" already, folks, go home."&@@Date[]& ``` Anonymous function. Takes no input and returns a string as output. No, I'm not going to make a REPL submission, post it yourself if that one byte is so important. [Answer] # [Perl 6](https://perl6.org), ~~53~~ 51 bytes ``` say "It's {Date.today.year} already, folks, go home." ``` [Try it](https://tio.run/nexus/perl6#@1@cWKmg5FmiXqxQ7ZJYkqpXkp@SWKlXmZpYVKuQmFOUmphSqaOQlp@TXayjkJ6vkJGfm6qn9P8/AA "Perl 6 – TIO Nexus") ``` say "It's {now.Date.year} already, folks, go home." ``` [Try it](https://tio.run/nexus/perl6#@1@cWKmg5FmiXqxQnZdfrueSWJKqV5maWFSrkJhTlJqYUqmjkJafk12so5Cer5CRn5uqp/T/PwA "Perl 6 – TIO Nexus") [Answer] # TI-Basic (TI-84 Plus CE with OS 5.2+), 64 bytes ``` getDate "It's "+toString(Ans(1))+" already, folks, go home. ``` TI-Basic is a tokenized language. Some commands (`getDate`, `toString(`, etc.), and all lowercase letters are two-bytes and everything else used here is one byte each. Explanation: ``` getDate # 3, store {Y,M,D} in Ans "It's "+toString(Ans(1))+" already, folks, go home. # 61, implicitly return required string with Y from getDate ``` # TI-Basic (TI-84 Plus CE with OS 5.1), 108 bytes ``` {0,1→L1 getDate Ans(1)L1→L2 LinReg(ax+b) Y1 Equ►String(Y1,Str0 sub(Str0,1,length(Str0)-3→Str0 "It's "+Str0+" already, folks, go home. ``` TI-Basic is a tokenized language. The more complicated user variables (`Y1`, `L1`, `L2`, `Str0`), some commands (`LinReg(ax+b` , `getDate`, `sub(`, `Equ►String(`, `length(`), and all lowercase letters are two-bytes and everything else used here is one byte each. OS 5.2 added a `toString(` command, which obsolesces about half of this submission, which is based off of [this algorithm](http://tibasicdev.wikidot.com/number-to-string). Explanation: ``` {0,1→L1 # 8 bytes getDate # 3 bytes, store {Y,M,D} list in Ans Ans(1)L1→L2 # 10 bytes, multiply L1 by the year and store in L2 LinReg(ax+b) Y1 # 5 bytes, take a linear regression of the points specified by each pair of corresponding coordinates in L1 and L2 and store it in Y1 Equ►String(Y1,Str0 # 8 bytes, convert Y1 to a string sub(Str0,1,length(Str0)-3→Str0 # 18 bytes, remove the "X+0" from LinReg "It's "+Str0+" already, folks, go home. # 56 bytes, implicitly return the required output ``` [Answer] # JavaScript ES6, 56 bytes ``` _=>`It's ${Date().split` `[3]} already, folks, go home.` ``` ### Try it online! ``` const f = _=>`It's ${Date().split` `[3]} already, folks, go home.` console.log(f()) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 31 bytes ``` `It's {Ki} alÎ%y, folks, go Êà. ``` [Try it online!](https://tio.run/nexus/japt#@5/gWaJerFDtnVmrkJhzuE@1UkchLT8nu1hHIT1f4XDX4QV6//8DAA "Japt – TIO Nexus") [Answer] ## PowerShell 3.0, 44 bytes ``` "It's $(date|% y*) already, folks, go home." ``` PowerShell is competing quite well today! [Answer] # R, ~~62 59~~ 62 bytes ``` cat("It's",format(Sys.time(),"%Y"),"already, folks, go home.") ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~39~~ 27 bytes ``` `It's % ×ġ, ṗḊ, go λ∵.`kðt% ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSXQncyAlIMOXxKEsIOG5l+G4iiwgZ28gzrviiLUuYGvDsHQlIiwiIiwiIl0=) Surely golfable? [Answer] # C#, 58 bytes ``` ()=>"It's "+DateTime.Now.Year+" already, folks, go home."; ``` Anonymous function which returns the required string. Full program: ``` using System; public class Program { public static void Main() { Func<string> f= ()=>"It's "+DateTime.Now.Year+" already, folks, go home."; Console.WriteLine(f()); } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 38 bytes ``` s["It's ".d3" already, folks, go home. ``` [Online interpreter.](//pyth.herokuapp.com?code=s%5B%22It%27s+%22.d3%22+already%2C+folks%2C+go+home.) [Answer] # [Haskell](https://www.haskell.org/), 113 bytes ``` import Data.Time.Clock f=do t<-getCurrentTime;putStr$"It's "++(fst.span(>'-').show)t++" already, folks, go home." ``` [Try it online!](https://tio.run/nexus/haskell#FcxBDoMgEADAe1@xISZoUD7Q2oteerYf2FRQIrAE1jR9PW3Pk0x1IVFmmJFRP10wevL0Oi52XAn4NmyGpzNnE/mP13TywrkRD5YFhFKtLaxLwtje5SA7XXZ6d6yUAPTZ4PrpwZI/Sg8bwU6/XtSALsIItn4B "Haskell – TIO Nexus") Replace `f` with `main` for a full program. The function `getCurrentTime` returns a `UTCTime` object which looks something like `"2017-04-02 10:22:29.8550527 UTC"` when converted to a string by `show`. `fst.span(>'-')` takes the leading characters while they are larger than `'-'`, that is the current year. For the next 7972 years `take 4` would work for 8 bytes less, but we want our code to work correctly for ever and ever. As far as I see build-in functions to get the current year require a `import Data.Time.Calendar`, so extracting the year from the string should be the shortest option. [Answer] # JavaScript, ~~77~~ ~~71~~ ~~67~~ 63 bytes ``` alert("It's "+Date().split(' ')[3]+" already, folks, go home.") ``` Thanks to @programmer5000 for the spaces! # JavaScript ES6 ~~66~~ 60 bytes ``` alert(`It's ${Date().split` `[3]} already, folks, go home.`) ``` [Answer] # [Befunge-98](https://github.com/catseye/FBBI), ~~57~~ 55 bytes ``` "emoh og ,sklof ,ydaerla@ s'tI"4k,y\4*:*/"&2"*+.f7+k,@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/Xyk1Nz9DIT9dQac4Oyc/TUGnMiUxtSgn0UFEoVi9xFPJJFunMsZEy0pLX0nNSElLWy/NXDtbx@H/fwA "Befunge-98 (FBBI) – Try It Online") Thanks to James Holderness for pointing out my mistake with the sysinfo instruction. `"emoh og ,sklof ,ydaerla@ s'tI"` pushes the sentence to the stack where `4k,` prints the first word. `y` is the sysinfo instruction. When passed 20 (the unprintable in the string), it returns `256*256*(year-1900) + 256*month + day of month`. `\4*:*/"&2"*+.` takes just the year from the value and prints it and`f7+k,` prints the rest of the sentence. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 48 bytes ``` "It's #{Time.new.year} already, folks, go home." ``` [Try it online!](https://tio.run/nexus/golfscript#@6/kWaJerKBcHZKZm6qXl1quV5maWFSrkJhTlJqYUqmjkJafk12so5Cer5CRD1Sh9P8/AA "GolfScript – TIO Nexus") Yes, this is string interpolation. [Answer] # [MATL](https://github.com/lmendo/MATL), 42 bytes ``` 'It''s '1&Z'V' already, folks, go home.'&h ``` [Try it online!](https://tio.run/nexus/matl#@6/uWaKuXqygbqgWpR6mrpCYU5SamFKpo5CWn5NdrKOQnq@QkZ@bqqeulvH//9e8fN3kxOSMVAA "MATL – TIO Nexus") ``` 'It''s ' % Push this string 1&Z' % Push current year V % Convert to string ' already, folks, go home.' % Push this string &h % Concatenate all stack contents horizontally % Implicitly display ``` [Answer] # Python 3, ~~73~~ 68 bytes ``` import time print(time.strftime("It's %Y already, folks, go home.")) ``` Very basic answer. The "%Y" gets the current year. *Thanks to @ovs for removing 5 bytes* [Answer] ## IBM/Lotus Notes Formula, 54 bytes Not exactly challenging but here we go anyway... ``` "It's "+@Text(@Year(@Now))+" already, folks, go home." ``` [Answer] **VBScript, 53 bytes** ``` msgbox"It's "&year(now())&" already, folks, go home." ``` ]
[Question] [ Make a Windows style Loading bar by the following instructions. (notice that this is different than [Loading... Forever](https://codegolf.stackexchange.com/questions/101289/loading-forever)) Your output should start by `[.... ]`. Every tick, you should wait 100 ms, then move each dots by one character right. if the dot is on the tenth character, move it to the first. Notice that you should clear the screen before outputting again. The output is ordered as the following: ``` [.... ] [ .... ] [ .... ] [ .... ] [ .... ] [ .... ] [ ....] [. ...] [.. ..] [... .] ``` ..Then it loops forever. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins I doubt I would even accept a winning answer tho * Please provide a gif file of the loading bar in action if possible. [Answer] # V, ~~17~~ ~~16~~ 15 bytes ``` i[´.¶ ]<esc>ògó$X|p ``` `<esc>` is `0x1b`. And the hexdump: ``` 00000000: 695b b42e b620 5d1b f267 f324 587c 70 i[... ]..g.$X|p ``` ### Explanation ``` i " Insert [ " a [ ´. " 4 .s ¶<space> " 6 spaces ]<esc> " and a ]. Then return to normal mode ò " Recursively do: gó " Sleep for 100 milliseconds $ " Go to the ] X " Delete the character to the left of the ] | " Go to the [ p " And paste the deleted character right after the [ " Implicit ending ò ``` [![gif](https://i.stack.imgur.com/mgkcN.gif)](https://i.stack.imgur.com/mgkcN.gif) [Answer] ## CSS/HTML, ~~202~~ ~~190~~ 186 + 45 = ~~247~~ ~~235~~ 231 bytes ``` pre{position:relative}x{position:absolute;display:inline-block;width:10ch;height:1em;overflow:hidden}x>x{width:14ch;left:-10ch;animation:1s steps(10,end)infinite l}@keyframes l{to{left:0 ``` ``` <pre>[<x><x>.... ....</x></x> ] ``` Edit: Saved ~~12~~ 14 bytes thanks to @Luke. [Answer] # PowerShell, ~~67~~ 66 Bytes ``` for($s='.'*4+' '*6;$s=-join($s[,9+0..8])){cls;"[$s]";sleep -m 100} ``` -1 by using shortened constructor thanks to Beatcracker replaces the string with a copy of the string where the last char is put in front of the remaining chars, clears the screen, prints it, and then sleeps for 100 ms. saved a lot of bytes by using the for loop constructor rather than wrap the logic inside the string. [![enter image description here](https://i.stack.imgur.com/NbSVi.gif)](https://i.stack.imgur.com/NbSVi.gif) [Answer] # [Python 3](https://docs.python.org/3/), ~~99~~ ~~93~~ ~~85~~ 83+2 ([-u flag](https://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print/230780#230780)) bytes -12 bytes thanks to ovs -2 bytes thanks to totallyhuman ``` import time s=4*'.'+6*' ' while 1:print(end='\r[%s]'%s);time.sleep(.1);s=s[9]+s[:9] ``` [Try it online!](https://tio.run/nexus/python3#FctBCoAgEADAu6/wEqsJghCBii8xby0kmIkr9Hyjuc/Md3v64CPfyChsK2hQ@woc2Hvlgty41nMdAusZ4OhxoQQLSf8HTQWxCW2kp0DRJkXR2TTnBw "Python 3 – TIO Nexus") [Answer] # Windows batch , ~~201~~ 181 bytes *Turns out using the old-school method actually saves bytes!* ``` @for %%p in (".... " " .... " " .... " " .... " " .... " " .... " " ...." ". ..." ".. .." "... .")do @echo [%%~p]&timeout 0 >nul&cls @%0 ``` --- Note: ``` get-screenrecorder.level - low grade get-gpu.level - horrible if get-screenrecorder.level == low grade || get-gpu.level == horrible { say("GIF may not be accurate"); } ``` [![GIF!](https://i.stack.imgur.com/3udtf.gif)](https://i.stack.imgur.com/3udtf.gif) Please note that my GIF recorder skipped a few frames, making the loading bar jumps `:(` [Answer] # Javascript (ES6), 86 bytes ``` setInterval('with(console)clear(),log(`[${x=x[9]+x.slice(0,9)}]`)',100,x='... .') ``` [Answer] ## Mathematica, ~~67~~ 77 Bytes +10 Bytes as I forgot the square brackets. ``` Animate["["<>".... "~StringRotateRight~n<>"]",{n,1,10,1},RefreshRate->10] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~126~~ ~~125~~ ~~124~~ ~~123~~ ~~122~~ ~~121~~ ~~119~~ ~~118~~ ~~117~~ ~~114~~ 115 bytes This one uses a bitmask to keep track of where the dots are. I had to add another byte as I was only outputting 5 spaces before. ``` m=30;f(i){usleep(3<<15);system("clear");for(i=1;i<1920;i*=2)putchar(i^1?i&m?46:32:91);m+=m&512?m+1:m;f(puts("]"));} ``` [Try it online!](https://tio.run/nexus/c-gcc#FYxBCoMwEAD/koPsVgpurAWzBl/SQggRA66K0YNIn92ztccZhjnFlgV3EPHY0hDCDGXTUIWc9rQGAeWH4BaF3E0LREscG6p1wfFmNc7b6nt3@Te1MZP28TSlNjUhS24lq0i3kpOR63@lCdRLIfLnFBdHwKODP3zH6e6d78MP "C (gcc) – TIO Nexus") [![enter image description here](https://i.stack.imgur.com/jfdf2.gif)](https://i.stack.imgur.com/jfdf2.gif) [Answer] # JavaScript (ES6) + HTML, ~~104~~ ~~85~~ 83 bytes ``` f=(s=".... ")=>setTimeout(f,100,s[9]+s.slice(0,9),o.value=`[${s}]`) <input id=o ``` * Saved 2 bytes thanks to [Johan](https://codegolf.stackexchange.com/users/55822/johan-karlsson)'s suggestion that I use an `input` instead of a `pre`. --- ## Try It Requires a closing `>` on the `input` tag in order to function in a Snippet. ``` (f=(s=".... ")=>setTimeout(f,100,s[9]+s.slice(0,9),o.value=`[${s}]`))() ``` ``` <input id=o> ``` [Answer] # [Noodel](https://tkellehe.github.io/noodel/), ~~16~~ ~~15~~ ~~14~~ 13 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html) ~~[ CỤ‘Ṁ~ððÐ]ʠḷẸḍt~~ ~~]ʠ[Ð.×4¤×6⁺ḷẸḍt~~ ~~]ʠ⁶¤⁴.ȧ[ėÐḷẸḍt~~ [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%5D%CA%A0%E2%81%B6%C2%A4%E2%81%B4.%C8%A7%5B%C4%97%C3%90%E1%B8%B7%E1%BA%B8%E1%B8%8Dt&input=&run=true) --- ## How it works ``` ]ʠ⁶¤⁴.ȧ[ėÐḷẸḍt ]ʠ⁶¤⁴.ȧ[ėÐ # Set up for the animation. ] # Pushes the literal string "]" onto the stack. ʠ # Move the top of the stack down by one such that the "]" will remain on top. ⁶¤ # Pushes the string "¤" six times onto the stack where "¤" represents a space. ⁴. # Pushes the string "." four times onto the stack. ȧ # Take everything on the stack and create an array. [ # Pushes on the string literal "[". ė # Take what is on the top of the stack and place it at the bottom (moves the "[" to the bottom). Ð # Pushes the stack to the screen which in Noodel means by reference. ḷẸḍt # The main animation loop. ḷ # Loop endlessly the following code. Ẹ # Take the last character of the array and move it to the front. ḍt # Delay for a tenth of a second. # Implicit end of loop. ``` --- ## Update ``` [Ð]ıʠ⁶¤⁴.ḷėḍt ``` [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%5B%C3%90%5D%C4%B1%CA%A0%E2%81%B6%C2%A4%E2%81%B4.%E1%B8%B7%C4%97%E1%B8%8Dt&input=&run=true) Don’t know why this took me a while to think of. Anyways, this places it at **13 bytes**. ``` [Ð]ıʠ⁶¤⁴.ḷėḍt [Ð]ıʠ⁶¤⁴. # Sets up the animation. [ # Push on the character "[" Ð # Push the stack as an array (which is by reference) to the screen. ] # Push on the character "]" ı # Jump into a new stack placing the "[" on top. ʠ # Move the top of the stack down one. ⁶¤ # Push on six spaces. ⁴. # Push on four dots. ḷėḍt # The main loop that does the animation. ḷ # Loop the following code endlessly. ė # Take the top of the stack and put it at the bottom. ḍt # Delay for a tenth of a second. ``` ``` <div id="noodel" code="[Ð]ıʠ⁶¤⁴.ḷėḍt" input="" cols="12" rows="2"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # PHP, 67 bytes ``` for($s="... .";$s=substr($s.$s,9,10);usleep(1e5))echo"\r[$s]"; ``` no comment [Answer] # C#, 162 157 bytes ``` ()=>{for(string o="[.... ]";;){o=o.Insert(1,o[10]+"").Remove(11,1);System.Console.Write(o);System.Threading.Thread.Sleep(100);System.Console.Clear();}}; ``` or as whole program for 177 bytes ``` namespace System{class P{static void Main(){for(string o="[.... ]";;){o=o.Insert(1,o[10]+"").Remove(11,1);Console.Write(o);Threading.Thread.Sleep(100);Console.Clear();}}}} ``` [Answer] # Pure bash, 68 ``` s=${1:-.... } printf "[$s]\r" sleep .1 exec $0 "${s: -1}${s%?}" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṙ©-j@⁾[]ṭ”ÆȮœS.1®ß 897ṃ⁾. Ç ``` [![Example run](https://i.stack.imgur.com/Esfsi.gif)](https://i.stack.imgur.com/Esfsi.gif) ### How? ``` ṙ©-j@⁾[]ṭ”ÆȮœS.1®ß - Link 1, the infinite loop: list of characters s ṙ - rotate s left by: - - -1 (e.g. "... ." -> ".... ") © - copy to the register and yield ⁾[] - literal ['[',']'] j@ - join with reversed @rguments ”Æ - literal '\r' ṭ - tack (append the display text to the '\r') Ȯ - print with no newline ending .1 - literal 0.1 œS - sleep for 0.1 seconds then yield the printed text (unused) ® - recall the value from the register ß - call this link (1) again with the same arity 897ṃ⁾. Ç - Main link: no arguments 897 - literal 897 ⁾. - literal ['.',' '] ṃ - base decompression: convert 897 to base ['.',' '] = "... ." ``` [Answer] # C (gcc), ~~202~~ ~~198~~ ~~196~~ ~~189~~ ~~96~~ ~~99~~ ~~88~~ ~~86~~ ~~79~~ ~~77~~ ~~75~~ ~~74~~ 73 bytes Saved ~~7~~ 8 bytes thanks to [Digital Trauma](/a/120322/61563). ``` f(i){usleep(dprintf(2,"\r[%-10.10s]",".... ...."+i%10)<<13);f(i+9);} ``` Or, if your system's `stdout` doesn't need to be flushed after every write without a newline: # C (gcc), 70 bytes ``` f(i){usleep(printf("\r[%-10.10s]",".... ...."+i%10)<<13);f(i+9);} ``` ### How it works * `usleep(` sleeps for the next return value in microseconds. * `dprintf(2,` prints to file descriptor 2, or `stderr`. This is necessary because while `stdout` is line-buffered (meaning output will not show until it prints a newline), `stderr` is character-buffered (all output is shown immediately). * `"\r` prints a carriage return (clears the current line). * `[%-10.10s]"` is the `printf` format specifier for a string with exact length 10 (no matter what string provided the output will always be a string with length 10), padded with spaces to the right if necessary. This will be enclosed with brackets. * `".... ...."` is the loading bar. * `+i%10` offsets the loading bar by the current index modulo 10. For example, if `i == 3`, `i % 10` is equal to 3. Offsetting the loading bar by 3 makes it equal to `". ...."`. * When the offset-ed string is passed to the `printf` format specifier, it limits to a length of 10 if necessary and adds spaces to the end if necessary. Therefore, the loading bar will always be between `[.... ]` and `[. ...]`. [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` `1&Xx'['897B@YS46*93hhDT ``` Try it at [**MATL Online!**](https://matl.io/?code=%601%26Xx%27%5B%27897B%40YS46%2a93hhDT&inputs=&version=19.10.0) Or see a gif from the offline compiler: [![enter image description here](https://i.stack.imgur.com/e9D9Z.gif)](https://i.stack.imgur.com/e9D9Z.gif) ### Explanation ``` ` % Do...while 1&Xx % Pause for 0.1 s and clear screen '[' % Push this character 897B % Push [1 1 1 0 0 0 0 0 0 1] @ % Push current iteration index, 1-based YS % Circularly shift the array by that amount 46* % Multiply by 46 (code point of '.') 93 % Push 93 (code point of ']') hh % Concatenate horizontally twice. Numbers are interpreted as chars % with the corresponding code points D % Display T % Push true. Used as loop condition. Results in an infinite loop % End (implicit) ``` [Answer] # Java 7, ~~139~~ 124 bytes ``` String s=".... ";void c()throws Exception{System.out.print("["+s+"]\r");s=(s+s).substring(9,19);Thread.sleep(100);c();} ``` * Mentioning of `\r` thanks to *@Phoenix*. The carriage return `\r` resets the 'cursor' back to the begin of the line, which can then be overwritten. Unfortunately, online compilers nor the Eclipse IDE doesn't support this, so I've added a gif at the end of this answer to show it from Windows Command Prompt. [Try it here.](https://tio.run/nexus/java-openjdk#bY@xboMwGIR3nuLkpbZIHaKqQ@QydOiYKd3SDA52iyWwEb8JiSKenTp0TG856aQ7fVc1mgi7WwY4H@HKYtXqS/nyqrBe490Ya0AB1zDABP8UUeuzhUZ0rX0OQ5z3sXf@B1QymYRFTJ2DM6i4iHUfRsLHpbJddMHf9leKtpWpKbtUjJwdWE45O371TCgqOeUkJA0nWnb5drXZCvVZ91YbSY21Hd8UhVCZ@@Yuz98SrHggHf8jzRKOmmagG06Nq0BRx2QLaaud539PDkdogQfu7P7L2xE7LuR9KQVTNs2/) (Slightly modified so you won't have to wait for the time-out before viewing the result. Also, the TIO doesn't support carriage returns, so every line is printed without overwriting the previous line.) **Explanation:** ``` String s=".... "; // Starting String ".... " on class level void c() // Method without parameter nor return-type throws Exception{ // throws-clause/try-catch is mandatory for Thread.sleep System.out.print("["+s+"]\r"); // Print the String between square-brackets, // and reset the 'cursor' to the start of the line s=(s+s).substring(9,19); // Set `s` to the next String in line Thread.sleep(100); // Wait 100 ms c(); // Recursive call to same method } // End of method ``` **Output gif:** [![enter image description here](https://i.stack.imgur.com/QgUUd.gif)](https://i.stack.imgur.com/QgUUd.gif) [Answer] # [Python 2](https://docs.python.org/2/), ~~81~~ 78 bytes -1 byte (noticing I missed use of `%s` when Rod submitted an [almost identical Python 3 version](https://codegolf.stackexchange.com/a/120236/53748) at the same time!) -2 bytes (using [totallyhuman's idea](https://codegolf.stackexchange.com/questions/120216/loading-forever-windows-style/120235#comment295545_120236) - replace `s[-1]+s[:-1]` with `s[9]+s[:9]`) ``` import time s='.'*4+' '*6 while s:print'\r[%s]'%s,;s=s[9]+s[:9];time.sleep(.1) ``` [![Example run](https://i.stack.imgur.com/9wqCb.gif)](https://i.stack.imgur.com/9wqCb.gif) [Answer] # [Go](https://golang.org/), ~~150~~ ~~145~~ ~~132~~ ~~129~~ 124 bytes *-5 bytes thanks to sudee.* I feel like I don't see enough Go here... But my answer is topping C so... pls halp golf? ``` package main import(."fmt" ."time") func main(){s:=".... ";for{Print("\r["+s+"]");Sleep(Duration(1e8));s=(s+s)[9:19];}} ``` [Try it online!](https://tio.run/nexus/go#Hcq7CsMgFADQ3a8Id/IiFbI1kWz9gEDHNIPItZXWB2qmkM/ubEvOfFrS5q2f1HntAnM@xVy5BOsrMAnVeQJkdgvmDBz3Mk4g/7oTKBvzPmcXKodHXkAUASugun@IEr9tWVcXA@/piqjKxIsouAxjP6zqOFr7hngx2rzoBw "Go – TIO Nexus") [Answer] # VBA 32-bit, ~~159~~ ~~157~~ ~~143~~ ~~141~~ 134 Bytes VBA does not have a built in function that allows for waiting for time periods less than one second so we must declare a function from `kernel32.dll` **32 Bit Declare Statement (41 Bytes)** ``` Declare Sub Sleep Lib"kernel32"(ByVal M&) ``` **64 Bit Declare Statement (49 Bytes)** ``` Declare PtrSafe Sub Sleep Lib"kernel32"(ByVal M&) ``` Additionally, we must include a `DoEvents` flag to avoid the infinite loop from making Excel appear as non-responsive. The final function is then a subroutine which takes no input and outputs to the VBE immediate window. **Immediate Window function, 93 Bytes** Anonymous VBE immediate window function that takes no input and outputs to the range `A1` on the ActiveSheet ``` s="... .... .":Do:DoEvents:Sleep 100:[A1]="["&Mid(s,10-i,10)&"]":i=(i+1)Mod 10:Loop ``` ### Old Version, 109 Bytes Immediate window function that takes no input and outputs to the VBE immediate window. ``` s="... .... .":i=0:Do:DoEvents:Sleep 100:Debug.?"["&Mid(s,10-i,10)&"]":i=(i+1) Mod 10:Loop ``` **Ungolfted and formatted** ``` Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal M&) Sub a() Dim i As Integer, s As String s = "... .... ." i = 0 Do Debug.Print [REPT(CHAR(10),99]; "["; Mid(s, 10 - i, 10); "]" DoEvents Sleep 100 i = (i + 1) Mod 10 Loop End Sub ``` *-2 Bytes for removing whitespace* *-30 Bytes for counting correctly* *-14 Bytes for converting to immediate window function* **Output** *The gif below uses the full subroutine version because I was too lazy to rerecord this with the immediate window function.* [![VBA loading Gif](https://i.stack.imgur.com/zCSuM.gif)](https://i.stack.imgur.com/zCSuM.gif) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` '.4×ð6×J[D…[ÿ],Á¶т×,т.W ``` [Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//Jy40w5fDsDbDl0pbROKAplvDv10sw4HCttGCw5cs0YIuV/// "05AB1E – TIO Nexus") **Explanation** ``` '.4×ð6×J # push the string ".... " [ # forever do: D # duplicate …[ÿ], # interpolate the copy between brackets and print Á # rotate the remaining copy right ¶т×, # print 100 newlines т.W # wait 100ms ``` [Answer] # Batch, ~~99~~ 98 bytes *Saved 1 byte thanks to SteveFest!* (I could remove `\r` from the code, but in the spirit of batch golfing, I won't.) ``` @SET s=.... :g @CLS @ECHO [%s%] @SET s=%s:~-1%%s:~,-1% @ping 0 -n 1 -w 100>nul @GOTO g ``` [![Recorded with LICEcap](https://i.stack.imgur.com/H2nrN.gif)](https://i.stack.imgur.com/H2nrN.gif) There are four spaces after the first line. The main logic is modifying the string. `%s:~-1%` is the last character of `%s%` and `%s:~0,-1%` is all but the last character of `%s%`. Thus, we are moving the last character to the front of the string, which rotates the string. [Answer] # Ruby, ~~57~~ 56 bytes ``` s=?.*4+' '*6;loop{$><<"[%s]\r"%s=s[-1]+s.chop;sleep 0.1} ``` Heavily influenced by other answers here. Saved a byte thanks to @manatwork. Also apparently I have trouble counting characters -- I use ST3 and apparently it will include newlines in the count of characters in the line if you're not attentive. [Answer] # Perl, 69 bytes *-3 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings).* ``` $_="....".$"x6;{print"\ec[$_] ";select$a,$a,!s/(.*)(.)/$2$1/,.1;redo} ``` That `select undef,undef,undef,.1` is the shortest way to sleep less than 1 second in Perl, and it takes a lot of bytes... --- Slightly longer (79 bytes), there is: ``` @F=((".")x4,($")x6);{print"\ec[",@F,"]\n";@F=@F[9,0..8];select$a,$a,$a,.1;redo} ``` [Answer] # Bash, ~~93~~ ~~90~~ 96 bytes ``` s="... .... ." for((;;)){ for i in {0..9};do printf "\r[${s:10-i:10}]";sleep .1;done;} ``` [view here](https://asciinema.org/a/4b02bns85e01zev7jqdhx6vdx) couldn't get nested { } in for syntax [Answer] # Groovy, 72 bytes ``` s="*"*4+" "*6 for(;;){print("["+s+"]"+"\n"*20);s=s[9]+s[0..8];sleep 100} ``` **Explaination** ``` s="*"*4+" "*6 //creates the string "**** " for(;;){ //classic infinite loop print("["+s+"]"+"\n"*20) //prints the string with [ at the beginning and ] at the end. After that some newlines s=s[9]+s[0..8] //appends the final char of the string to beginning, creating a cycling illusion sleep 100 //100 ms delay } ``` [Answer] # Haskell (Windows), 159 bytes ``` import System.Process import Control.Concurrent main=mapM id[do system"cls";putStrLn('[':[".... "!!mod(i-n)10|i<-[0..9]]++"]");threadDelay(10^5)|n<-[0..]] ``` Explanation ``` mapM id sequentially perform each IO action in the following list [ start a list comprehension where each element is... do an IO operation where system "cls"; we clear the screen by calling the windows builtin "cls" putStrLn( then display the string... '[': with '[' appended to [ a list comprehension where each character is... ".... "!! the character in literal string ".... " at the index mod(i-n)10 (i - n) % 10 |i<-[0..9]] where i goes from 0 to 9 ++"]" and that ends with ']' ); threadDelay(10^5) then sleep for 100,000 microseconds (100 ms) |n<-[0..]] where n starts at 0 and increments without bound ``` Haskell's purity made generating the cycling dot pattern somewhat complex. I ended up creating a nested list comprehension that generated an infinite list of strings in the order they should be output, then went back added the appropriate IO operations. [Answer] # Ruby, 61 bytes If the spec were for the dots to scroll left instead of right, it would save 1 byte because `rotate!` with no arguments shifts the array once to the left. ``` s=[?.]*4+[' ']*6 loop{print ?[,*s,"]\r";s.rotate!9;sleep 0.1} ``` [Answer] # GNU sed (with exec extension), 64 Score includes +1 for `-r` flag. ``` s/^/[.... ]/ : esleep .1 s/[^. ]*(.+)(.)].*/\c[c[\2\1]/p b ``` [Answer] # c, 100 ``` char *s=".... .... ";main(i){for(i=0;;i=(i+9)%10)dprintf(2,"[%.10s]\r",s+i),usleep(3<<15);} ``` ]
[Question] [ ## Intro/Background I was looking at "You Had One Job" pictures lately, and noticed an old favourite of mine: [![SHCOOL](https://i.stack.imgur.com/P8PwA.jpg)](https://i.stack.imgur.com/P8PwA.jpg) And I said to myself: "I need a program that can generate text like that". So I devised a set of rules for character swapping and wrote a CGCC challenge! ## The Challenge Given a single string as input, output a string with its inner characters swapped. This can be done by: * Leaving the first letter as is * Swapping each pair of characters thereafter * Leaving the last letter as is. If the string is of an odd length (i.e. the length of the string mod 2 is 1), leave the last two letters as they are. ## Example Inputs/Outputs ``` School -> Shcool Somebody -> Smobedoy Character -> Cahartcer CGCC -> CCGC Stack Exchange! -> SatkcE cxahgne! Never gonna give you up -> Nvereg noang vi eoy uup ``` Walkthrough on swapping ``` School (Length: 6) S hc oo l Shcool Somebody (Length: 8) S mo be do y Smobedoy Character (Length: 9) C ah ar tc er Cahartcer Stack Exchange! (Length: 15) S at kc E cx ah gn e! SatkcE cxahgne! ``` ## Rules * Input/output can be taken/given in any convenient format * The input will not contain newlines * Minimum input length is 4 * Input will only contain printable ASCII characters ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the lowest bytes wins. *Sorry about the last test case everyone. It's fixed now* [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` f(a:b:c:d:e)=a:c:f(b:d:e) f x=x ``` [Try it online!](https://tio.run/##JYy7DgIhEEX7/YqRWKyJX0BCZSyttjTGDOwgZHkFKNCfR1y7c@5JrsGykXO96xm55IqvnE4CB@hZ7jJpaKL1SqUWcWeLMjE6dmZL9CTj@h54MZhRVcq/uaLa4NqUwfCiA3tMHm0QHtPtCSnbUOEIH5tgPxw8Cui/9S8 "Haskell – Try It Online") Avoids having to special-case omitting the first character by having extracting it be part of the recursive definition. [Answer] ## brainfuck, 28 bytes ``` ,.,[>,>,[<.[-]<.>>>]<<[.>]>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fR08n2k7HTifaRi9aN9ZGz87OLtbGJlrPLtYu9v//4JLE5GwF14rkjMS89FRFAA) First, we print the first character. Then we read the second character and enter the main loop. (`,.,[`) When entering the main loop, we expect the first character of a pair to be in the current cell, and we read the next two into the next two cells (`>,>,`). The tape then looks like this: ``` [pair1] [pair2] [nextpair1] [0] ^ ``` Then, if `nextpair1` exists, we know there's going to be at least one character after the current pair, so we can output the two characters in this current pair in reverse (`[<.[-]<.>>>]`) – the triple `>` at the end moves us to the location after `nextpair1` to break out of the loop. Otherwise, we're at the end of the string, so we go back to `pair1` (`<<`) and print as many characters as we received in order (`[.>]`). The main loop will end here if this was the end of the string (`>]`). If not, recall that we ended at the `[0]` in the diagram above after the check to see if `nextpair1` existed. So the `<<[.>]` would have brought the pointer to `pair2` (which was cleared) instead of `pair1`, and then `>]` restarts the main loop, but with the cursor pointing at `nextpair1`, which is exactly what we want. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes ``` V`^.|..(?=.) ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8sIU6vRk9Pw95WT/P//@DkjPz8HK7g/NzUpPyUSi7njMSixOSS1CKugABnd67gksTkbAXXiuSMxLz0VEUuv9Sy1CKF9Py8vESF9MyyVIXK/FKF0gIA "Retina – Try It Online") Link includes test cases. Explanation: `V` reverses each match. The first character is matched separately, then characters are matched in pairs as long as there is still one character left that is unreversed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` Ḣ,Ṫjṭ2/ ``` [Try it online!](https://tio.run/##AXUAiv9qZWxsef//4biiLOG5qmrhua0yL/874oCcIC0@IOKAnTvDhwrhu7TDh@KCrFn//3NjaG9vbApzb21lYm9keQpjaGFyYWN0ZXIKQ0dDQwpTdGFjayBFeGNoYW5nZSEKTmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXA "Jelly – Try It Online") A full program taking a string as its argument and printing the swapped string. Thanks to @JonathanAllan for saving a byte! ## Explanation ``` Ḣ | Head ,Ṫ | Paired with tail j | Join with: ṭ2/ | The remainder, pair wise reduced by tacking the left item in the pair to the end of the right ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` f=lambda s:s[3:]and s[:3:2]+f(s[1:5:2]+s[4:])or s ``` [Try it online!](https://tio.run/##FcixDoIwEIDh3ae4dILoIuhyiZNxdWFsGI7SUiL0mrYQePoKy58vv9@TZVflbF4TzV1PEDHKGltyPUSJNVbt1RRR3vF5MsoHtiUHiNkc3WB0IBplmSdxEw3PuuN@P/i2FEglHc6dSP3gsylLbtDH@OpVBxjYOYJhXDXsvMDiBV7Ah9GlwhRbWeY/ "Python 2 – Try It Online") Based off my [Haskell answer](https://codegolf.stackexchange.com/a/197489/20260). I tried a more direct port using splatted input, but it was clunky: **57 bytes** ``` f=lambda a,b,c,*d:d[1:]and a+c+f(b,*d)or a+b+c+''.join(d) ``` [Try it online!](https://tio.run/##Fci9DoIwFEDh3ae46UILjYmOJE7G1YXRONz@0Sr0kqYQePpat3O@5cie4rUUd5twVgYBpZJatqY3r0v/xmgAO905rqoJSvVU/aY5fyhEbkRxFXcIEdigPdHEJBtotorMUfPuMaHONv05o/7CY9ce42grPO1mE4wUI8IYNgsHrbAurD/BkkLM3PF2F6L8AA "Python 2 – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~27~~ 20 [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 tacit prefix function. Requires `⎕IO←0`. ``` ⊢⊇⍨∘⍋≢⌊1+⍳∘≢+2×2|⍳∘≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91LXrU1f6od8WjjhmPersfdS561NNlqP2odzNIoHORttHh6UY1cO7/NKCuR719EAO6mg@tN37UNhHICw5yBpIhHp7B/9MU1IOTM/Lzc9S5QMz83NSk/JRKMMc5I7EoMbkktQjCc3d2hqgpSUzOVnCtSM5IzEtPVQSL@aWWpRYppOfn5SUqpGeWpSpU5pcqlBaoAwA "APL (Dyalog Extended) – Try It Online") Explanation and walk-through for `"Somebody"` and `"Character"`: `⍳∘≢` the indices of the length; `[0,1,2,3,4,5,6,7]`, `[0,1,2,3,4,5,6,7,8]` `2|` two-mod of that; `[0,1,0,1,0,1,0,1]`, `[0,1,0,1,0,1,0,1,0]` `2×` twice that; `[0,2,0,2,0,2,0,2]`, `[0,2,0,2,0,2,0,2,0]` `⍳∘≢+` add the indices of the length to that; `[0,3,2,5,4,7,6,9]`, `[0,3,2,5,4,7,6,9,8]` `1+` increment that; `[1,4,3,6,5,8,7,10]`, `[1,4,3,6,5,8,7,10,9]` `≢⌊` the minimum of the length and that; `[1,4,3,6,5,8,7,8]`, `[1,4,3,6,5,8,7,9,9]` `⍋` the grade (the indices that would sort it) of that; `[0,2,1,4,3,6,5,7]`, `[0,2,1,4,3,6,5,7,8]` `⊢⊇⍨∘` use that to reorder the string; `"Smobedoy"`, `"Cahartcer"` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, 26 bytes ``` s:g[^.||)>..$||..]=$/.flip ``` [Try it online!](https://tio.run/##K0gtyjH7/7/YKj06Tq@mRtNOT0@lpkZPL9ZWRV8vLSez4P//4OSM/PwcruD83NSk/JRKLueMxKLE5JLUIq7gksTkbAXXiuSMxLz0VMV/@QUlmfl5xf91CwA "Perl 6 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` f=->s{s[/(.)(.)(.)(.+)/]?$1+$3+f[$2+$4]:s} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1664ujhaX0NPE4a0NfVj7VUMtVWMtdOiVYy0VUxirYpr/0crBSdn5OfnKOkoBefnpiblp1QCmc4ZiUWJySWpRSDhksTkbAXXiuSMxLz0VKCAX2pZapFCen5eXqJCemZZqkJlfqlCaYFSrF5uYkF1TUVNgUJadEVs7X8A "Ruby – Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~48~~ 40 bytes ``` ({}<{({}<({}<>)>)<>}<>{{({}<>)<>}{}}<>>) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7rWphpEgLCdpp2mjR2Qrq6GcIGc6logw07z////SiGpxSUKwSVFmXnpikr/dR0B "Brain-Flak (BrainHack) – Try It Online") This doesn't work for strings that contain null bytes (unless the null byte is the first byte of the string). ## Explanation ``` ({}<...>) Store the first element for later {({}<({}<>)>)<>}... Move the stack over in twos (preserving the order of each pair moved) <>{...{}}<> {({}<>)<>} Move everything back in ones ``` The one complex part is the `<>{...{}}<>`. Since moving over in twos can pick up an extra zero from the bottom of the stack we need to removing when bringing things back. Conveniently our main loop will stop when it hits a zero, so when it hits a zero we destroy that zero and, if the next thing is not zero we try again. This means we will only stop if there are two zeros in a row, which since the input cannot contain zeros, will only occur at the bottom of the stack. In the process we will get rid of any zeros that are present, which fixes our extra zero issue. # Works for all inputs, ~~114~~ 112 bytes ``` ({}<([](())){({}[()]<(()[{}])>)}({}{}<([]){{}({}<({}<>)>)<>([])}>{}<>){(<{}({}<{}>)>)}{}([]){{}({}<>)<>([])}<>>) ``` [Try it online!](https://tio.run/##TYsxCoBADAS/olZJ4Q9CwDdod1xxiqgIFmoX8vaY80Astpid3fFM27GmaTcDUYIQARBRHAJgJKcgGpFRvSoLFNF37GE3xLlUflGAihXNzi@/x7clZjSzZpivu@rvczuWurG2ewA "Brain-Flak (BrainHack) – Try It Online") Nearly all of the code is devoted to making this work for even length inputs. [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~117~~ ... ~~82~~ 80 bytes ``` #import<map> #define f(s)for(int i=1;i<s.size()-2;)s[i++]^=s[i++]^=s[i+1]^=s[i]; ``` [Try it online!](https://tio.run/##TU/LbsIwELznK7ZGQnYpqPSYOPRQ9doLx5ZKxtkEq8S2/KCliG@njqMifPCuxzOzs9LaudwL3V0uE9Vb4wLvhV0VkwZbpRFa6llrHFU6gKqXleJ@4dUvUjZ/qph/V7PZ5rO@rcuxbqpkqOU@Ngj8gDIYl1yviDI@OBT9qhice6E0ZXAqIB0fmrIcFTz3ial0t4KAPnio4UTWcmfMnjyQtelxa5pjal92wgkZ0A1wEPILXn/kLm2GCXjDAzrojNYCOnVAOJoI0d7KYP0trE2DyLnKOdLaQEUMZponQzkG@I@ZKXSA2PWd40oTA3AOdJpldzVM77NyscUu7/kM5EOTZEgIG5jD7zjznG@HIToNj1VxvvwB "C++ (clang) – Try It Online") Saved 11 bytes thanks to @AZTECCO!!! Saved 2 bytes thanks to @ceilingcat!!! [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda x:x[0]+re.sub("(.)(.)",r"\2\1",x[1:-1])+x[-1] import re ``` [Try it online!](https://tio.run/##FYixCoMwFAB3v@KRKUErtd2ETqVrF0d1iDEaqeaF1yjx69MUDu44d3qD9h6nRxdXuQ2jhFCH9trnpMvvPnDGS5FgBbHu1lWsCG1VX6pe5KFNypbNIXkgHSckCLBYYI0yiCsrWIObHnA8Uz6NJKm8pv/2Un3gFZSRdtZpvPWhCWa0VsK8HBpO3GF3rM7A0WI9n3gQIv4A "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ¦¨2ô€RJ¹θ¹н.ÁJ ``` [Try it online!](https://tio.run/##ATEAzv9vc2FiaWX//8Kmwqgyw7TigqxSSsK5zrjCudC9LsOBSv//U3RhY2sgRXhjaGFuZ2Uh "05AB1E – Try It Online") ``` ¦¨2ô€RJ¹θ¹н.ÁJ ¦¨ # Delete the first and last letter 2ô # Break into groups of 2 €R # Reverse each of them J # Join it back together ¹θ¹н # Push the last and first letter of the input .Á # Rotate stack, so the first letter is first J # Join the items in the stack ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` h1Ué ¤ò mÔq ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=aDFV6SCk8iBt1HE&input=IkNoYXJhY3RlciBTd2FwcGluZyI) ``` h1Ué ¤ò mÔq :Implicit input of string U h1 :Overwrite from the 1st (0-indexed) character on with Ué : Rotate U to the right ¤ : Slice off the first 2 characters ò : Split into pairs m : Map Ô : Reverse q : Join ``` [Answer] # [Ruby](https://www.ruby-lang.org/) -pl, 27 bytes ``` gsub /^.|..(?=.)/,&:reverse ``` [Try it online!](https://tio.run/##FcuxCgIxDADQvV@RSRS0twviIK4u3YW0hvbwbEraHhb8diO@/Un3QzXW7mG624@12/PJ7qb95ii0klRSdSExL8bxizw/hrkkFAyNxLiG4QnXd0iYI5nbf0DknBHivBIM7tCL@XJpM@eqh7L8AA "Ruby – Try It Online") **Alternate solution with the same bytecount, but a regex nobody else has used yet:** ``` gsub /(^|.)(.(?=.))/,'\2\1' ``` [Try it online!](https://tio.run/##BcGxDsIgEADQ/b7itkKiNLobB@PahbUxAbxAY@UIhUYSv118L1fbevdbtTiKx1dJocT1oqQcD8N8nk9D79oF5hU0v8nys8EtmGxcoQy6GPfC@8cFEz3BRDtl9ByjQb/shI0r1gQ/TmXhuPVjWv8 "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` f(a:b:c:d)=b:a:f(c:d) f x=x g(a:b)=a:f b ``` [Try it online!](https://tio.run/##JYy7CgIxFET7fMU1WOyCXxBIJZZW2onITTYvNi@yKVZ/PiZazZkzMBa3VXnfmp6QCSbZMnPBkOlpINGw852Ysc28WxCtqq1u/EHvI@mJ3qRNyQ9IQYm0vDueLRaUVZWhK8oVLru0GI060CcJ6CIPmK8vyMXFCkf4uAy/4859AfNv7Qs "Haskell – Try It Online") xnor has [a shorter version of this answer](https://codegolf.stackexchange.com/a/197489/56656) that combines `f` and `g` into a single function. [Answer] # [J](http://jsoftware.com/), ~~24~~ 19 bytes ``` C.~[:}:_2<@|.\#\@}. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/nfXqoq1qreKNbBxq9GKUYxxq9f5rcqUmZ@QrpCmoJyYlp6ij8FLRuGlIfGQpFGXqXP8B "J – Try It Online") Creates the boxed indexes representing the cyclic form of the permutation we need (bookeeping), and then applies it `C.` to the input. [Answer] # [Gema](http://gema.sourceforge.net/), 15 characters ``` \A?=? ??\P?=$2? ``` The only interesting point here is the use of > > `\P`       Position -- leave input stream here after the template matches > > > Sample run: ``` bash-5.0$ echo -n 'School' | gema '\A?=?;??\P?=$2?' Shcool ``` [Try it online!](https://tio.run/##S0/NTfz/P8bR3taey94@JsDeVsXI/v//4OSM/PwcAA "Gema – Try It Online") | [Try all test cases online!](https://tio.run/##lVDBbsIwDD2TrzBVR@CAkJB2mqoOVWjahU3jCNUUUtNWQFKlKaJi@/bOSSW2w3bYxXnxe7afvRN10WUoj8IgTBdgsbbvUtQYjdlgw9ey0PrI04ivC@mQT@oT7nTW@vRJ7zDTrSeSQhghLRrHJIJ@VtLHU09J4rME@iZWyAMsL7IQKseh7yXsQS5BXkSRK0o52QrPaCDXSgnIyzNCqxtoKidfEYM5KE0N4FwC6hYaotiEscqUyu6Bf8DddH5fwy/vnOJWceDPqmosvW9YN0cHlpcKaYuM4MuBM7bXBkonoghBeB3ejrR5TD@DB8g0GxhfHQXhGJCOBlMn9VUBTZvpys5yPIlZbaQHwLvtIo5iFsfb1zgK53HHYRIwNviH99uEIOznO3T9ttfT5BGcr83mhy6K/pKmKYxG/RJuf2cq0wq7Lw "Bash – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 40 bytes ``` f=s=>s[3]?s[0]+s[2]+f(s[1]+s.slice(3)):s ``` [Try it online!](https://tio.run/##fYvLDoIwEADvfgVyakMkKjcNejB@AceGw7qUtli7hG18fH3VqyHeJpmZAe7AOLkxrgJ1OqW@5vrAqmqPrNZtwWrbFr1gtflwyd6hFpWUO05Igcnr0pMRvcgZLZHPpdwvfkxDN32h7jXnThYmwKin2TECXrPzEy0Eo5d//6x5wDi6YL5VegM "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), ~~41~~ 40 bytes -1 bytes thanks to Arnauld ``` s=>s.replace(/(?!^)(.)(.)(?=.)/g,"$2$1") ``` [Try it online!](https://tio.run/##fYvLCsIwEADvfkUbekhAU/QqtQfxC3oX1u02qY3ZkBQfXx/RoxRhbjNzhTskjGOYN557ykOTU3NIOlJwgCRr2ZZnJfWXttGqNmtR7aqtUBnZJ3akHRs5SJHQMjuh1H71Yzq@0YX715I7WoiAM8XFcQacitMTLXhD5d@/6B4QwujNp8pv "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` def f(s):s[1:-2:2],s[2:-1:2]=s[2:-1:2],s[1:-2:2];return s ``` [Try it online!](https://tio.run/##PcmxDoMgFEDRvV/xwiI0OGg3mk5N1y6OpgPFh5BaIIBGv57axe3k3rBl492llAE1aJqYSH0j6la0L576VtTNrtshftxrxDxHB6loH2EF64B0yng/EU46/8W3H7addyOjVBnjP2epPvBYlZFuxD08ccEIo3dOwmgXhM3PMAciThCidZmeNZ1synRljCcMt6pi5Qc "Python 3 – Try It Online") Accepts a list and returns a list. The idea is to simply take the alternating slices and swap them. Do let me know if the boilerplate stuff can be shortened in Python submissions. [Answer] # [C (clang)](http://clang.llvm.org/), ~~51~~ 48 bytes ``` f(char*s,z){*++s^=*s^=s[1]^=*++s;z>5&&f(s,z-2);} ``` [Try it online!](https://tio.run/##ddDPa8IwFAfwe/6KNw/S1AhLk46N4C4ydhvCjuIgy9Japon0h0zFv71LbGNlsEPg5Us@7yVRU7WRJm/bLFJrWcYVOeJTPJlUH7PYrWpJV65ye3F8TsfjLHIHpgkW57YwNWxlYSDCJwQeg1yuZqN3tbZ2MxIIdk1dRRK7KoskecDCB9AlQdALsVv9ab8OA6K9ouTxynwWWOLZ3JVS1boMzh1KepiQpw52UXDMu8Vi/jqMYr1ghAfBbgS/XLCW6hteflxkcn03YN5jTmgaNL/Rqddveq9LyK0xEvJir@FgG2h2Q5e075KShIUuPkOlrpvSwL1A57b7VxT@Cl1fj/x70J8ron@G/gI "C (clang) – Try It Online") A recursive solution that modifies the original string Saved 3 thanks to @ceilingcat suggestion to use `^=` [Answer] # x86-16 machine code, 13 bytes Unassembled listing: ``` 46 INC SI ; skip first char 8B FE MOV DI, SI ; point DI to string D1 E9 SHR CX, 1 ; divide counter by 2 with round down 49 DEC CX ; skip last char CLOOP: AD LODSW ; load next two chars 86 E0 XCHG AH, AL ; reverse chars AB STOSW ; store next two chars E2 FA LOOP CLOOP ; keep looping C3 RET ; return to caller ``` Input/output string in `[SI]`, length in `CX`. **PC-DOS test program output:** [![enter image description here](https://i.stack.imgur.com/IplqC.png)](https://i.stack.imgur.com/IplqC.png) [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 17 bytes ``` rt2cog_j)<-++.+RT ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/qMQoOT89PkvTRldbW087KOT/f@eMxKLE5JLUIgA "Burlesque – Try It Online") ``` rt # Rotate the string left 2co # Split into chunks of 2 g_j # Take pair of first and last out )<- # Reverse each chunk ++.+# Join everything back together RT # Rotate the string right ``` For even length input only you can shave a single character: ``` RT2col_)<-++.+RT ``` [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 125 bytes ``` character(99)a,b(99) read('(a)'),a j=len_trim(a) b=[a(1:1),(a(i+1:i+1),a(i:i),i=2,j-1,2),a(j:j)] print*,(b(i)(1:1),i=1,j) end ``` [Try it online!](https://tio.run/##JYtBCoMwEEX3OUV2nWnHRdwZ8Aq9QCll1GgntFGGKPT0qeLi8z6P/8dZs3KqpvEspfRvVu5zUGgaZOoOGA08wAUYL0hsYvsJ6ZVVvrsxXftgcN4hAYPcnN@zr0C8IElbU6wc1YeJPuLTLCopXwk6EDx/0jqKaEIaSrmHLaid5pTYTrIF@5tXuy5/ "Fortran (GFortran) – Try It Online") Shame string manipulation in Fortran is so wordy as every substring needs two references. The main magic is mapping a to a character array via: ``` [a(1:1), ! Prepend first char (a(i+1:i+1),a(i:i), ! Swap a(i+1) for a(i) i=2,j-1,2) ! For i in 2..n-1 ,a(j:j)] ! Append last char ``` [Answer] # [J](http://jsoftware.com/), 48 bytes Man, I love J ``` (1{.]),([:,[:(|."1)_2[\1}.]}.~_1-2|#),]{.~_1-2|# ``` [Try it online!](https://tio.run/##y/r/P83WSsOwWi9WU0cj2kon2kqjRk/JUDPeKDrGsFYvtlavLt5Q16hGWVMnthrG/p@anJGvkKag7pdallqkkJ6fl5eokJ5ZlqpQmV@qUFqg/h8A "J – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~74~~ 71 bytes Found a more idiomatic `Zsh` solution. [Try it online!](https://tio.run/##LcpBC4IwGIDh@37F0h0UCpnHQiIk6NLJbrLDnN9cpE50MEv87WtG8B6ew/uZlJvA6MFgmA30NdRNqysko3hxNiP0NIzP3khMbEkZWWyZ7kloD5QlSRR2cXTeSsj98shvZcr@oGz17/F3rg6E0itCEhceut2gO6h0/fbMFR@5MDB6B4Xh4oWvs1C8b2AXIPcF) ``` w=$1;printf $w[1]${w[2,$#w-1]//(#m)(?)(?)/$MATCH[2]$MATCH[1]}${w:$#w-1} ``` [74 bytes:](https://tio.run/##qyrO@J@moVn9v9xWxdC6oCgzryRNQaU82jDWOi2/SCFTQaPaSE9PJVpFuVzXKFZPz6hWE6EoU9swFkTFWtvY2KhUl1upAEVq/9dycaUpBCdn5OfngBj5ualJ@SmVQKZzRmJRYnJJahGQrRRckpicreBakZyRmJeeqqjE9R8A "Zsh – Try It Online") `w=$1;printf $w[1];for i ({2..$[$#w-2]..2})printf $w[i+1]$w[i];<<<${w:$i+1}` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` §θ⁰F⪪✂θ¹±¹¦¦¦²⮌ι§θ±¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCo1BHwUBT05orLb9IQSO4ICezRCM4JzM5FSRhqKPgl5qeWJKqYaipqaNgpKmpANEclFqWWlScqpEJ0olhHkKPpvX//8ElicnZCq4VyRmJeempilz/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Works with strings of at least 2 characters. Explanation: ``` §θ⁰ ``` Print the first character of the string. ``` F⪪✂θ¹±¹¦¦¦² ``` Split the inner slice of the string into 2-character substrings. ``` ⮌ι ``` Print each substring reversed. ``` §θ±¹ ``` Print the last character of the string. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 104 bytes ``` P =LEN(1) INPUT P . F REM . S S S P . X P . Y REM . S F =F Y X GT(SIZE(S),2) :S(S) O OUTPUT =F S END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/XyFAwdbH1U/DUJNLwdMvIDQEKKCn4KYQ5OoLpIO5ghWCwSIRYDISLg5UYusG5EdwKbiHaAR7RrlqBGvqGGkqWAUDGVz@Cv6hISDTgIqCuVz9XP7/d85ILEpMLkktAgA "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~95~~ 76 bytes ``` func[s][prin take s t: take/last s foreach[a b]s[prin any[b""]prin a]prin t] ``` [Try it online!](https://tio.run/##LY3BDoIwEETP9ivG/oB3r8R486DHpoelbCkBW9IWkK9HC@5l3kxespGb7cmN0sJeNzt5o5JWY@w8MvWMhHzd6TJQykjChshknCLUOh0i@VXVUuqjHJH19jexQImTfBkXwiALhTfXoVkLV44imcxxL/eq2oVMpsftYxz5ls9levDMEW3wntB2M2MNE6ZRCq0Efld@ZlgsQm9f "Red – Try It Online") Directly prin(t)s the characters instead of returning a string. [Answer] # [Java (JDK)](http://jdk.java.net/), 43 bytes ``` s->s.replaceAll("(?<=.)(.)(.)(?=.)","$2$1") ``` [Try it online!](https://tio.run/##TY9Na8MwDIbv/RWaacEZqWE79pNRtp22S49jB9V1UreObWwlLIz@9ixfdAUbWXpeSa/PWOH8fLw0uvAuEJzbXJSkjchKK0k7Kx6XE2kwRvhAbeF3AuDLg9ESIiG1oXL6CEXL@J6CtvnXN2DIY9JLAd7GOauBpkPYQAbrJs43UQTlDUr1YgxnfLtai4QPZ9s@Wcqmz9MnljTLftptBalIEdbjEgC2lyfnDEtvuSvUwR3r/8ruhAElqXBXet/t7loI5QVef@QJba4e/sGnqlSA3FmLkOtKQe1KKD3r@XVwlrnAKwy9scVgL7m560Ck0PrNBHpvat4JkuWI93UkVQhXkvDt/yjjbBYXMIszy9J@Vtq1j/rrpLvX5g8 "Java (JDK) – Try It Online") # Without much API, 60 bytes ``` s->{for(int i=1;i<s.length-2;)s[i]^=s[++i]^(s[i]=s[i++-1]);} ``` [Try it online!](https://tio.run/##TZBNa4NAEIbv@RVTIaA1LqTHGANFSk/tJUexsFlXs4nuyu5oK8HfblcjJodleeedj2fmQlsaXLLrIKpaaYSL1aRBUZK8kQyFkuQ1XLGSGgNfVEi4rQDq5lQKBgYp2q9VIoPKeu4RtZBFkgLVhfGmVIBYSdNUXO/ZmeokPUAO0WCCwy1X2hUSQUTbUOwNKbks8By8hZ5JRPoTmcT37e@Oygrh@8E29cJ@CKe@yzDkBg1E8zgA58jOSpXOZtGq4ieVdY9IbFEoQ66fQp9x/FSClF3h488yy4K/PIxv3nINhZKSQiFaDp1qoKmdye/vZONiLdUT2O6O5y109yvY22mLPHoE1YjzrjXtXC@c03JCGeM1ujZxCR47g7wiqkFS2@Uxd5212cHarKWzmZptQPLf@TRT6Vzbr8bXD/8 "Java (JDK) – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 16 bytes (SBCS) The same program as below, with extra simplifying-ops added. ``` ,(!½!2%¬-|$,,)(, ``` [Try it online!](https://tio.run/##y05N//9fR0Px0F5FI9VDa3RrVHR0NDV0/v8PTs7Iz8/5r5tZBAA "Keg – Try It Online") # [Keg](https://github.com/JonoCode9374/Keg) `-ir`, 18 bytes You know, Jono's challenges are *definitely* easily doable in Keg. ``` ,(!2/1!2%--|$,,)(, ``` [Try it online!](https://tio.run/##y05N//9fR0PRSN9Q0UhVV7dGRUdHU0Pn///gksTkbAXXiuSMxLz0VMX/uplFAA "Keg – Try It Online") ## Explanation ``` # Take an input from STDIN , # Step 1. Output the first item. (!2/ # Repeat half of the length-of-stack times 1!2%-- # subtract by 1 if that's odd |$,, # Swap & output the two items )(, # Output the remaining items ``` ]
[Question] [ [Wikipedia: Zeno's Dichotomy Paradox](https://en.wikipedia.org/wiki/Zeno%27s_paradoxes#Dichotomy_paradox) > > An infinite number of mathematicians walk into a bar. The first one orders a beer. The second one orders half a beer. The third one orders a fourth of a beer. The bartender stops them, pours two beers and says, "You're all a bunch of idiots." > > > [Reddit](https://www.reddit.com/r/Jokes/comments/1423a4/an_infinite_number_of_mathematicians_walk_into_a/) > > > Print the following series for as long as the program runs, with the denominator of each item being multiplied by two each time: `1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + ...` As `n` approaches infinity, the sum of this sequence approaches `2`. # Rules No, you may not print `2`. You may not print `1/1` as the first item. You may remove spaces `1+1/2+...` or add spaces `1 + 1 / 2 + ...` as you need. You may use newlines instead of spaces as a delimiter due to popular demand. You may append a `.` plus a constant number of `0`s to the denominator if need be. "Infinitely" means no unnecessary delays, and for as long as possible limited by the current (variable) system's specs, but not limited by your current language. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) apply. 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), ~~10~~ 9 bytes Saved 1 byte thanks to *Erik the Outgolfer* ``` [No…+1/J? ``` [Try it online!](https://tio.run/nexus/05ab1e#@x/tl/@oYZm2ob6X/f//AA "05AB1E – TIO Nexus") **Explanation** ``` [ # loop over N infinitely [0 ...] No # calculate 2^N …+1/J # join with the string "+1/" ? # print without newline ``` [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes -5 thanks to Erik the Outgolfer ``` i=1 while 1:print i,'+1/';i*=2 ``` [Try it online!](https://tio.run/nexus/python2#@59pa8hVnpGZk6pgaFVQlJlXopCpo65tqK9unalla/T/PwA "Python 2 – TIO Nexus") [Answer] # [C (gcc)](https://gcc.gnu.org/), 60 bytes ``` f(){for(long long n=1;n;n*=2)printf(&"+1/%llu"[n^1?0:3],n);} ``` Goes up the the unsigned 64bit limit. [Try it online!](https://tio.run/nexus/c-tcc#LYzLDoIwEEX/pQmm00eEpiTFOvgjbmojoQkCgXFl/GzXWIzLe8/J2Qa0PvpHSCNP8Oqmhcc@LIKQieutkszPT1p5QgIlpCS0zg8Y1nlJI3X8QIpVx2JliiTu/GwbgL2S96CN15ra5EFQW5tLrgoSpqidjCqi2GFt1O8urMukKqVtTvwvaptFySOWAP69bZ9x0jHE/v4F "C (tcc) – TIO Nexus") This one goes on forever; (it's as small as it's going to get) # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~312~~ ~~264~~ ~~255~~ ~~251~~ ~~233~~ ~~231~~ ~~208~~ ~~204~~ ~~195~~ ~~190~~ ~~188~~ 170 bytes ``` l=4;c;main(i){for(char*t="*\b1+";puts(i=t),*++t=48;l=asprintf(&t,"1/%s",t+=*++t<49))for(t+=l-2;--t>i;)*t>52?*t=*t*2%58+c,c=*--t>52,*t=*t%48*2%10+49:(*t=*t*2-48+c+(c=0));} ``` [Try it online!](https://tio.run/nexus/c-tcc#LYzLDoIwEEX/pQmm00eEpiTFOvgjbmojoQkCgXFl/GzXWIzLe8/J2Qa0PvpHSCNP8Oqmhcc@LIKQieutkszPT1p5QgIlpCS0zg8Y1nlJI3X8QIpVx2JliiTu/GwbgL2S96CN15ra5EFQW5tLrgoSpqidjCqi2GFt1O8urMukKqVtTvwvaptFySOWAP69bZ9x0jHE/v4F "C (tcc) – TIO Nexus") Here's the not so golfed version; ``` c;l=4;main(i){ for(char*t="*\b1+";puts(i=t),*++t=48;l=asprintf(&t,"1/%s",t+=*++t<49)) for(t+=l-2;--t>i;) *t>52?*t=*t*2%58+c,c=*--t>52,*t=*t%48*2%10+49:(*t=*t*2-48+c+(c=0)); } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ‘;“+1/”ȮḢḤ’ß ``` [Try it online!](https://tio.run/nexus/jelly#AR0A4v//4oCYO@KAnCsxL@KAnciu4bii4bik4oCZw5///w "Jelly – TIO Nexus") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` .V0^2b"+1/ ``` [Try it online!](https://tio.run/nexus/pyth#@68XZhBnlKSkbaj//z8A "Pyth – TIO Nexus") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes More fun if `⎕FR` (**F**loating-point **R**epresentation) is `1287` (128 bit decimal) and `⎕PP` (**P**rint **P**recision) is 34. ``` {∇2×⊃⎕←⍵'+1/'}1 ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9Q31S3oUdsEQyMLc65HHe1RqXn5/6uBjPJHXYsf9c4DSqlrG@qr6zzqnVoO5Bgdnv6od2stRMbwP1Dhf5AWAA "APL (Dyalog Unicode) – TIO Nexus") `{`…`}1` apply the following function on the number 1:  `⎕←⍵'+1/'` print the argument and the the string  `⊃` pick the first one (i.e. the argument)  `2×` double that  `∇` tail call recursion on that (optimised, so it can be infinitely repeated) [Answer] # [Bash](https://www.gnu.org/software/bash/), 33 bytes ``` echo 1;yes|awk '{print"+1/"2^NR}' ``` [Try it online!](https://tio.run/nexus/bash#@5@anJGvYGhdmVpck1ieraBeXVCUmVeipG2or2QU5xdUq/7/PwA "Bash – TIO Nexus") Change `print` for `printf` and `echo` for `printf` to avoid newline [Answer] # dc, ~~19~~ 18 bytes ``` 1[rdp+[+1/]Prdx]dx ``` ## Explanation We push `1` and `[rdp+[+1/]Prdx]` onto the stack. We then duplicate and execute `[rdp+[+1/]Prdx]`. The first thing it does is to rotate the stack (`r`) so that the value is on top. `dp+` prints the value and adds itself (to multiply by 2). `[+1/]P` prints the invariant `+1/`, then we rotate the arguments so the saved macro definition is at the top, duplicate it and start again. ## Notes GNU `dc` will normally wrap at 70 columns. To override that and get an infinite line, add `DC_LINE_LENGTH=0` to your environment variables. ## Output (partial) ``` 1 +1/2 +1/4 +1/8 +1/16 +1/32 +1/64 +1/128 +1/256 +1/512 +1/1024 +1/2048 +1/4096 +1/8192 +1/16384 +1/32768 +1/65536 +1/131072 +1/262144 +1/524288 +1/1048576 +1/2097152 +1/4194304 +1/8388608 ``` ... ``` +1/1042962419883256876169444192465601618458351817556959360325703910069443225478828393565899456512 +1/2085924839766513752338888384931203236916703635113918720651407820138886450957656787131798913024 +1/4171849679533027504677776769862406473833407270227837441302815640277772901915313574263597826048 +1/8343699359066055009355553539724812947666814540455674882605631280555545803830627148527195652096 +1/16687398718132110018711107079449625895333629080911349765211262561111091607661254297054391304192 +1/33374797436264220037422214158899251790667258161822699530422525122222183215322508594108782608384 ``` ... ``` +1/395087429607039737016990582493211473623084548479366958355967894445617992237751193831383393115316177621785336292974757702861456280882511441699391271295733513512496264566385933380947965261723454959331220707759295808360415615991592990777778282040705827434949633856633176265789944580636935948031966453153742439217291986581128250733429493898120451931770274751229567569237843273729615827100381825373339221412595529512989073039623048380802736380367607801160720048450955272332555885534822792967746973597821924656959979423188656952212441297346660701518718326620774081406711639289159232374325676221430645461061339419517215005226454502285089841722594900476336947000733101279737598704985318796279216595068894677898277722179745279389210632125609476578229717704884251829483656808483833708957351468743071618868390065369478551657766868765417931368111672635805713040939576059856661966901849284974427853607640934780174510177467344954981530954324587346785943498033783853652888777144814836577685249298036748395273293867889213776236596621464513866240966454560881624123468744072759399999977952917047275150817022801141959157607304299710040536803961941539248511838228140896285208917844516516354328828341895189859625184919137459427696083645173496443173168837863941880276763158758023006149415211675330687766377148229974279566049003264864600191840267483777843342674487811516073311635515312490178552895957423373899881643180029114753167161849015185102165069678102141792645820016416047568386145306495107877487105159701033434133879076295235543592729076137504220533421618969333525966517622043110194920864084904515587227955524573123041514933277200135397957913967801292194452638091786561237904399020102666362253691989299390107684868894715745836877407032377238840608843413131092703960427769853699078374834491936996044463254349297156213103279673169178505184701872144900045771102435610296184197209227529288007415067046022722582981596269522005749627981773526366438220575437177263889604130699335432595226257543492333263422050922067270179224260275144056594379835114406083447004727056013389366056869669871721247387721885160070482303207498193981625368149767105925975387341377059500273590145880590627076202552189658057673577965137474478445230279151378408213456608653443746420052642315479741917201353741316367530727339674720984684319607014456047714106368632178729336223365487529774958557802515621876807522117219692963254636001726226095376131918803784811313633676500693288681886899229878108736316145573597053282102794465392580102681361770473681924380592794825281026389925319284295575976905371805098869309557779427667880257736023553969079065990247752442478709560271890544575319753044785213713815214853531493050977096589318122209182622944866896029727456835427297057238010067400316328458733735151924868494740318125717480345439976856588095695103557933254518724035147790867900860802490856266882895272405233909349503100342835778128113450704055933916580251051242513114247923234285375218348330984968499261151666279876934252251642210658880406798177100551493117002184732295738827350073267361848262282761987958004309963517948938698786164969644086580797555934352507402669257430636696930339621666387272089588481086182797065416819524024244039514527278555283258634786254208521110348742241263325816002709937195402337679130173170319173019473143013813053957781486624112400998612123509635383191611221055251405429574982431605111210811909998737934637009821942743916100790356493781569074043021092914565490511459722069379412568362070588905824887062692251966557571063144913628359617852782242850667347243493635423170856735991445443417871593754841930126545261100978250334790401134417708085254996280546469054953434698740338004535923304134925010294666195488077033498408573400230908456372758784275514839518209197168385986800728708864486555574751038959875865944573232904382772174165469240721191260083414343513721167588202103644839217795869540476457367497547061295275817063645407861999254441068513089288941238387198872484274061935238732418142521129602424711571463536885701004481109813887972526424268833936301999940489737888191570936888484964073548401260573294755586807219169314540668429632835157545851763722427756273879072731431505757610169922077517245770967529970605394054778171352769192297060429577138791870011615935227225671201093581479973265123899759178588060627003483624484718952553536175080141557411018195112843918387330586945434704681386712037849132186150132261042825792865372648754304087311364485783913995232206503295131703588146450037893765442335625163597434960232164031867939806213034434955304659392517248083742743104580255027984810817258473711668510466293353159230682507713356536346933373222621074069493621551732890007902642898203729353535541505055230646447927335528957518174124051240324790069803454443268705032437412987085956986231654396653945449361791419385673388462153863206838157383577706049673416137197255949136605805960826652037358130882947815724836422987739828579124410515444240566417712451706437934444715054112852437374620837818318965333233036720725057182268814289785426876890730560232557019341916693475054757150722335726164285001394620207185098209060247075408696040161086332399037926647184391403995691066367778171562567400295434214765373073532471221761418214238803246752363904522571261072568011082281025572468893579252790734242527127778212414258417151636760753113090140644900683087184729743937692882688781682528416310850143754232086010450547458252820624921499276046395019090380887163852054555145431526258731837552253081278815739277412689465695941457195947520449547528479195654921291630947757961099209920460560771007698446991318388178005121886864829789281989687868033416542896922010329803510712241486910230176578077334774066133073728498756538589509813926190053693968878600638282582915610844019713891397117761984470765139228094313389312619025293455644485019485659751869296503689550132880058360683768191850360853185346730443998577670217447676572006007846832281428067265029500735963006405097225737892017644266262369462412574469988693558883982457143609025342185734610083070158152370952984896142295431884162794373897052159892645389273308325006511838982963210612512322440419463781685703879460818754246754737940067675306280339905099665753185624213049959974358988865877958103529903146946530778345631329029194118707823987745182366133711832776917746326752560414432248765580001690261776455186768733481157296158946100861665048300648945542904325905584298490513362292415753190834332376223017933102895303381625772236869056493905619864331052324553111223626084907937012036147356323467349271564345943614252673724659330963224126235367389507942684619417763187571792457049977423564605600407492739749810469638764253641886550627347410736476168235036323056296424076410773881349066193975356477998788704088168252906853359434516247984743194831348262718121306661583008435884810496549588343058262321647390735264606206072011103907091768882769468469548172289382501112430456154299134997391379920716169599617338345446024206416533732905022779643316661925667780044405263747380549446190984315096751598520871084659561682150880941631909886116710336501837005063103142970019870229280161913535898896273821723701749825424198801867406788183134913924263719112061721504776882103064064359808662664627132885266814050508776452910137134270723647297071012906850061114810029573681278211481183908305090518470607821191868530182355469879320671285317749034490711147615749836523756450457907560809808180752736277635732973149879636046843370244031978388137905356568834841691405960511052920098099303117458443459752992376005588918461949244074455720525010639887497443006893435915417651916819463649597517491710312592729976616519543890099530933526832155577274386878813332226092536388499227272797049735342204092718218399418943214483876032335170210620818582577397681191807311146697580973912033655792648256970866595194893815163653986467309514803085649995372052311880524198806710857097759813038371950266290297264677343705141037392715602877631695706464175624716337179764939952510203992806290410817066938678282725721991737936771618886658531530432671336707243253399686635114284033467196647570867723924592346710336310499837157847001000657477981583545401290986926236963825871995956812647720239548464931532537453731179201219809243551668681899320550475784370849798950308066492614030400947685348077036376906960967572117048503094709377111019534286030732015239027627742931733097540469889785438409079499563218182778062136770448874634337602252200785481498083800414471627026908575019040813241133085007748236210770824190826032543188084102056377610344497047314070899072279218186771810995166773473114538521089207373662535516843804894247865222415416567979253467876905240369631759382670743540819101472322524971913190038014207087495403005280426785325932475391049960936934038679922250485974423425021273852536322945163397389403648570637150505325367515540775710473683840127830499238530870104153509651904712990936272485771980487060597330426352158711289651715205689049260499430924095066894960045670014855252638636173892541721664064657257545484662281992727145339820179787932300136239018814532042680306206506846252926868289215506270940648380151080863903543873800421024947008029227493253733743659931460789009603522492213592492048391771760673166705432907234322574655099086321398830175703899404965151123193886696442296349071654094637032308306856955288952171834242794325316103826542731616585851913306273167685606136686470354702529673355285989172690078260014657789396032732932707667614838197171927208752920806753147947753042162645589267309328014049843059474903297455903512702132260588248559475081881636853227563097955967083889828222963665998878755153458074282990405836509465604418489946220280072051695243646682126417012619626420434704676470720900405053137991022528724677776185782640188543273087475178910478479476375475107166115050700098469965773154824987334911488998504643031126617426087742334881528986730831286510376127857270260065953591254351135389978509155685077650175013516418689843888963267814029997035174397017156131402312672241612206597456154522391107951335408620230202536389665726663417780482765640799333938105922754878613702760187032743689376707408517940178159467558086798870508509302008010853150053660329410964652409126276870654180681874881929746118180582577305743743952810779398262012426174907734327106136327201729744548683488487099663898103452434942210300833833130143850134675972327857405316343100019819653706594138235142730877703690741728508059492138642914276288984044042099728558960754700526065507631173050607164329771213342522618716881636690451903407693545135452815509580836160948812037959966193150381363591325661363476282370880535386441056486977358792737573438415565582362150808790336607040072093996865509619115356670599413230372818843108462117192738018820456322869946146303496007938903379241735817413492283835977534999446414774242209937016102619721220743544264050400097257089329412409254182040067187294506795767071674839385327568309523275288224086341778500123181829914635212704885959073672849205647176312287693211208290617090697646296209359258826200442497277991265116001163923419756327042484575648575021801534747270301153864412881912695313170393490767798464601324811063517942109518188821662675241828342647930010935849739305511205479557635171775009458846115428296418509860882903797249010462815241310630703763917719343099389989212618131651857779639943520010464854895769226125734400676226305595574413150903275614989606378324476097633897174939587875967658516048531378475872344597620732910259889372637316612851578821200108167426224067862632022377346659611324512681594932786190395749866081212126765942648631311170725777632375318331458676692976060778353923365207931601783140329977239640697677390642952067751304225189275891914656263416947084450120234441671746028997201191323195215386733714871687707800672016820227681962426204834017171078741804363016905452036367437049026691141558129758797699640194324162736418976728910597423824473007553073364103514575141561781882871644975070955229562369626756867869338986838760342284146441315204683418587181558372435743877156433485354976428152730039744389279516110761771426764201299330794471271711515888964165405659366091810847151036007173905114063582213623053963744257889874028150526901847782612540828524150747603549047215293759454581158155329597162690004775971455898321404025294368662413692106436456898487879798453482089212957398027468299542185050952024424434257748368440629523534889927058704389099405555033480560657504105905182439365431354241976084762913941805532894762520886571190102966212136887152569491150928851182909057450691899990027643415972827215164457661126843197212359209124565023629842753704005053902959730902144697324536284243222516487451881162143985260026576702277354398701943268311327348278723577644934801132856940314800246225039733533484807420506534462368695104335500466194188432862110475125223174190441086648726124829278566262264102582145477455790001229962128988151514777487437037270487153943987721550211938223551105161674656128149829492208549801379399145307479176248550539143187103073739912305990874163539516471346476299608693068764303029104908023285789101921870714244184682024700760361462663101570206457539892273492121502188312469283565918477771845191345920751263742268857954344987825767697329023593992910217713704972512065484949552264125935161622986929633713130569797577128578214458329586269690647799782014649930675405127944876912350950231416318397349447230393724491695757547080501396519382299957816346147421987910768628451509475789472047213399478200233594932011006341697414362898632815522642132016614650400350428923555620918057200926864089035767073332791867816685434096971239607592477801325642486235952866653992824568229542798606247131414859323219085694179902810098535657962013883197934894815206949876469106535355971101217848490155179261164663801145917802217034896618411596621165894170862154553621702226207363854759575529806758207708865406552630203012980490505941247406029120385466493805043607084819136763318505396587786149987409414795363172301089051894908740418011869835127044174788340738050919777596148274325858751879060573875387047962263073964078212858407556731801896720172173402451609345514653369843948925865731285026645995919856979876708543976520293377113985661155885697067770340963454255462317778374708234636608739119582761909701893485235072604937207880557091958509260575756938640165512270322212561952906328322017549014849215824787611893951617083671247652355225313571195438343636594795213938009780362376632674524801606712889751259220696409500370952911456813275349818073892021046409289255786132787385187019129176514080173483822613572793996361788110041096484931301484233630238022334653847275796035554791678720054505018864099939754669651544296841730613206450101627744726143047203934946454579761956034246397049238954525292315292293731998279977819953334814618383443186382455045395596531660361384999262672019010927022846744105110180629489154477796693814515782860555654300726449058256946453431271071240673715129993027272108615147743053163012016539090192335094681890199309163850322423174196757401200305496025245970076637786182016385654479388672 +1/790174859214079474033981164986422947246169096958733916711935788891235984475502387662766786230632355243570672585949515405722912561765022883398782542591467027024992529132771866761895930523446909918662441415518591616720831231983185981555556564081411654869899267713266352531579889161273871896063932906307484878434583973162256501466858987796240903863540549502459135138475686547459231654200763650746678442825191059025978146079246096761605472760735215602321440096901910544665111771069645585935493947195643849313919958846377313904424882594693321403037436653241548162813423278578318464748651352442861290922122678839034430010452909004570179683445189800952673894001466202559475197409970637592558433190137789355796555444359490558778421264251218953156459435409768503658967313616967667417914702937486143237736780130738957103315533737530835862736223345271611426081879152119713323933803698569948855707215281869560349020354934689909963061908649174693571886996067567707305777554289629673155370498596073496790546587735778427552473193242929027732481932909121763248246937488145518799999955905834094550301634045602283918315214608599420081073607923883078497023676456281792570417835689033032708657656683790379719250369838274918855392167290346992886346337675727883760553526317516046012298830423350661375532754296459948559132098006529729200383680534967555686685348975623032146623271030624980357105791914846747799763286360058229506334323698030370204330139356204283585291640032832095136772290612990215754974210319402066868267758152590471087185458152275008441066843237938667051933035244086220389841728169809031174455911049146246083029866554400270795915827935602584388905276183573122475808798040205332724507383978598780215369737789431491673754814064754477681217686826262185407920855539707398156749668983873992088926508698594312426206559346338357010369403744289800091542204871220592368394418455058576014830134092045445165963192539044011499255963547052732876441150874354527779208261398670865190452515086984666526844101844134540358448520550288113188759670228812166894009454112026778732113739339743442494775443770320140964606414996387963250736299534211851950774682754119000547180291761181254152405104379316115347155930274948956890460558302756816426913217306887492840105284630959483834402707482632735061454679349441969368639214028912095428212737264357458672446730975059549917115605031243753615044234439385926509272003452452190752263837607569622627267353001386577363773798459756217472632291147194106564205588930785160205362723540947363848761185589650562052779850638568591151953810743610197738619115558855335760515472047107938158131980495504884957419120543781089150639506089570427427630429707062986101954193178636244418365245889733792059454913670854594114476020134800632656917467470303849736989480636251434960690879953713176191390207115866509037448070295581735801721604981712533765790544810467818699006200685671556256226901408111867833160502102485026228495846468570750436696661969936998522303332559753868504503284421317760813596354201102986234004369464591477654700146534723696524565523975916008619927035897877397572329939288173161595111868705014805338514861273393860679243332774544179176962172365594130833639048048488079029054557110566517269572508417042220697484482526651632005419874390804675358260346340638346038946286027626107915562973248224801997224247019270766383222442110502810859149964863210222421623819997475869274019643885487832201580712987563138148086042185829130981022919444138758825136724141177811649774125384503933115142126289827256719235705564485701334694486987270846341713471982890886835743187509683860253090522201956500669580802268835416170509992561092938109906869397480676009071846608269850020589332390976154066996817146800461816912745517568551029679036418394336771973601457417728973111149502077919751731889146465808765544348330938481442382520166828687027442335176404207289678435591739080952914734995094122590551634127290815723998508882137026178577882476774397744968548123870477464836285042259204849423142927073771402008962219627775945052848537667872603999880979475776383141873776969928147096802521146589511173614438338629081336859265670315091703527444855512547758145462863011515220339844155034491541935059941210788109556342705538384594120859154277583740023231870454451342402187162959946530247799518357176121254006967248969437905107072350160283114822036390225687836774661173890869409362773424075698264372300264522085651585730745297508608174622728971567827990464413006590263407176292900075787530884671250327194869920464328063735879612426068869910609318785034496167485486209160510055969621634516947423337020932586706318461365015426713072693866746445242148138987243103465780015805285796407458707071083010110461292895854671057915036348248102480649580139606908886537410064874825974171913972463308793307890898723582838771346776924307726413676314767155412099346832274394511898273211611921653304074716261765895631449672845975479657158248821030888481132835424903412875868889430108225704874749241675636637930666466073441450114364537628579570853753781461120465114038683833386950109514301444671452328570002789240414370196418120494150817392080322172664798075853294368782807991382132735556343125134800590868429530746147064942443522836428477606493504727809045142522145136022164562051144937787158505581468485054255556424828516834303273521506226180281289801366174369459487875385765377563365056832621700287508464172020901094916505641249842998552092790038180761774327704109110290863052517463675104506162557631478554825378931391882914391895040899095056958391309842583261895515922198419840921121542015396893982636776356010243773729659578563979375736066833085793844020659607021424482973820460353156154669548132266147456997513077179019627852380107387937757201276565165831221688039427782794235523968941530278456188626778625238050586911288970038971319503738593007379100265760116721367536383700721706370693460887997155340434895353144012015693664562856134530059001471926012810194451475784035288532524738924825148939977387117767964914287218050684371469220166140316304741905969792284590863768325588747794104319785290778546616650013023677965926421225024644880838927563371407758921637508493509475880135350612560679810199331506371248426099919948717977731755916207059806293893061556691262658058388237415647975490364732267423665553835492653505120828864497531160003380523552910373537466962314592317892201723330096601297891085808651811168596981026724584831506381668664752446035866205790606763251544473738112987811239728662104649106222447252169815874024072294712646934698543128691887228505347449318661926448252470734779015885369238835526375143584914099954847129211200814985479499620939277528507283773101254694821472952336470072646112592848152821547762698132387950712955997577408176336505813706718869032495969486389662696525436242613323166016871769620993099176686116524643294781470529212412144022207814183537765538936939096344578765002224860912308598269994782759841432339199234676690892048412833067465810045559286633323851335560088810527494761098892381968630193503197041742169319123364301761883263819772233420673003674010126206285940039740458560323827071797792547643447403499650848397603734813576366269827848527438224123443009553764206128128719617325329254265770533628101017552905820274268541447294594142025813700122229620059147362556422962367816610181036941215642383737060364710939758641342570635498068981422295231499673047512900915815121619616361505472555271465946299759272093686740488063956776275810713137669683382811921022105840196198606234916886919505984752011177836923898488148911441050021279774994886013786871830835303833638927299195034983420625185459953233039087780199061867053664311154548773757626664452185072776998454545594099470684408185436436798837886428967752064670340421241637165154795362383614622293395161947824067311585296513941733190389787630327307972934619029606171299990744104623761048397613421714195519626076743900532580594529354687410282074785431205755263391412928351249432674359529879905020407985612580821634133877356565451443983475873543237773317063060865342673414486506799373270228568066934393295141735447849184693420672620999674315694002001314955963167090802581973852473927651743991913625295440479096929863065074907462358402439618487103337363798641100951568741699597900616132985228060801895370696154072753813921935144234097006189418754222039068572061464030478055255485863466195080939779570876818158999126436365556124273540897749268675204504401570962996167600828943254053817150038081626482266170015496472421541648381652065086376168204112755220688994094628141798144558436373543621990333546946229077042178414747325071033687609788495730444830833135958506935753810480739263518765341487081638202944645049943826380076028414174990806010560853570651864950782099921873868077359844500971948846850042547705072645890326794778807297141274301010650735031081551420947367680255660998477061740208307019303809425981872544971543960974121194660852704317422579303430411378098520998861848190133789920091340029710505277272347785083443328129314515090969324563985454290679640359575864600272478037629064085360612413013692505853736578431012541881296760302161727807087747600842049894016058454986507467487319862921578019207044984427184984096783543521346333410865814468645149310198172642797660351407798809930302246387773392884592698143308189274064616613713910577904343668485588650632207653085463233171703826612546335371212273372940709405059346710571978345380156520029315578792065465865415335229676394343854417505841613506295895506084325291178534618656028099686118949806594911807025404264521176497118950163763273706455126195911934167779656445927331997757510306916148565980811673018931208836979892440560144103390487293364252834025239252840869409352941441800810106275982045057449355552371565280377086546174950357820956958952750950214332230101400196939931546309649974669822977997009286062253234852175484669763057973461662573020752255714540520131907182508702270779957018311370155300350027032837379687777926535628059994070348794034312262804625344483224413194912309044782215902670817240460405072779331453326835560965531281598667876211845509757227405520374065487378753414817035880356318935116173597741017018604016021706300107320658821929304818252553741308361363749763859492236361165154611487487905621558796524024852349815468654212272654403459489097366976974199327796206904869884420601667666260287700269351944655714810632686200039639307413188276470285461755407381483457016118984277285828552577968088084199457117921509401052131015262346101214328659542426685045237433763273380903806815387090270905631019161672321897624075919932386300762727182651322726952564741761070772882112973954717585475146876831131164724301617580673214080144187993731019238230713341198826460745637686216924234385476037640912645739892292606992015877806758483471634826984567671955069998892829548484419874032205239442441487088528100800194514178658824818508364080134374589013591534143349678770655136619046550576448172683557000246363659829270425409771918147345698411294352624575386422416581234181395292592418718517652400884994555982530232002327846839512654084969151297150043603069494540602307728825763825390626340786981535596929202649622127035884219036377643325350483656685295860021871699478611022410959115270343550018917692230856592837019721765807594498020925630482621261407527835438686198779978425236263303715559279887040020929709791538452251468801352452611191148826301806551229979212756648952195267794349879175751935317032097062756951744689195241465820519778745274633225703157642400216334852448135725264044754693319222649025363189865572380791499732162424253531885297262622341451555264750636662917353385952121556707846730415863203566280659954479281395354781285904135502608450378551783829312526833894168900240468883343492057994402382646390430773467429743375415601344033640455363924852409668034342157483608726033810904072734874098053382283116259517595399280388648325472837953457821194847648946015106146728207029150283123563765743289950141910459124739253513735738677973677520684568292882630409366837174363116744871487754312866970709952856305460079488778559032221523542853528402598661588942543423031777928330811318732183621694302072014347810228127164427246107927488515779748056301053803695565225081657048301495207098094430587518909162316310659194325380009551942911796642808050588737324827384212872913796975759596906964178425914796054936599084370101904048848868515496736881259047069779854117408778198811110066961121315008211810364878730862708483952169525827883611065789525041773142380205932424273774305138982301857702365818114901383799980055286831945654430328915322253686394424718418249130047259685507408010107805919461804289394649072568486445032974903762324287970520053153404554708797403886536622654696557447155289869602265713880629600492450079467066969614841013068924737390208671000932388376865724220950250446348380882173297452249658557132524528205164290954911580002459924257976303029554974874074540974307887975443100423876447102210323349312256299658984417099602758798290614958352497101078286374206147479824611981748327079032942692952599217386137528606058209816046571578203843741428488369364049401520722925326203140412915079784546984243004376624938567131836955543690382691841502527484537715908689975651535394658047187985820435427409945024130969899104528251870323245973859267426261139595154257156428916659172539381295599564029299861350810255889753824701900462832636794698894460787448983391515094161002793038764599915632692294843975821537256903018951578944094426798956400467189864022012683394828725797265631045284264033229300800700857847111241836114401853728178071534146665583735633370868193942479215184955602651284972471905733307985649136459085597212494262829718646438171388359805620197071315924027766395869789630413899752938213070711942202435696980310358522329327602291835604434069793236823193242331788341724309107243404452414727709519151059613516415417730813105260406025960981011882494812058240770932987610087214169638273526637010793175572299974818829590726344602178103789817480836023739670254088349576681476101839555192296548651717503758121147750774095924526147928156425716815113463603793440344346804903218691029306739687897851731462570053291991839713959753417087953040586754227971322311771394135540681926908510924635556749416469273217478239165523819403786970470145209874415761114183917018521151513877280331024540644425123905812656644035098029698431649575223787903234167342495304710450627142390876687273189590427876019560724753265349049603213425779502518441392819000741905822913626550699636147784042092818578511572265574770374038258353028160346967645227145587992723576220082192969862602968467260476044669307694551592071109583357440109010037728199879509339303088593683461226412900203255489452286094407869892909159523912068492794098477909050584630584587463996559955639906669629236766886372764910090791193063320722769998525344038021854045693488210220361258978308955593387629031565721111308601452898116513892906862542142481347430259986054544217230295486106326024033078180384670189363780398618327700644846348393514802400610992050491940153275572364032771308958777344 +1/1580349718428158948067962329972845894492338193917467833423871577782471968951004775325533572461264710487141345171899030811445825123530045766797565085182934054049985058265543733523791861046893819837324882831037183233441662463966371963111113128162823309739798535426532705063159778322547743792127865812614969756869167946324513002933717975592481807727081099004918270276951373094918463308401527301493356885650382118051956292158492193523210945521470431204642880193803821089330223542139291171870987894391287698627839917692754627808849765189386642806074873306483096325626846557156636929497302704885722581844245357678068860020905818009140359366890379601905347788002932405118950394819941275185116866380275578711593110888718981117556842528502437906312918870819537007317934627233935334835829405874972286475473560261477914206631067475061671725472446690543222852163758304239426647867607397139897711414430563739120698040709869379819926123817298349387143773992135135414611555108579259346310740997192146993581093175471556855104946386485858055464963865818243526496493874976291037599999911811668189100603268091204567836630429217198840162147215847766156994047352912563585140835671378066065417315313367580759438500739676549837710784334580693985772692675351455767521107052635032092024597660846701322751065508592919897118264196013059458400767361069935111373370697951246064293246542061249960714211583829693495599526572720116459012668647396060740408660278712408567170583280065664190273544581225980431509948420638804133736535516305180942174370916304550016882133686475877334103866070488172440779683456339618062348911822098292492166059733108800541591831655871205168777810552367146244951617596080410665449014767957197560430739475578862983347509628129508955362435373652524370815841711079414796313499337967747984177853017397188624852413118692676714020738807488579600183084409742441184736788836910117152029660268184090890331926385078088022998511927094105465752882301748709055558416522797341730380905030173969333053688203688269080716897041100576226377519340457624333788018908224053557464227478679486884989550887540640281929212829992775926501472599068423703901549365508238001094360583522362508304810208758632230694311860549897913780921116605513632853826434613774985680210569261918967668805414965265470122909358698883938737278428057824190856425474528714917344893461950119099834231210062487507230088468878771853018544006904904381504527675215139245254534706002773154727547596919512434945264582294388213128411177861570320410725447081894727697522371179301124105559701277137182303907621487220395477238231117710671521030944094215876316263960991009769914838241087562178301279012179140854855260859414125972203908386357272488836730491779467584118909827341709188228952040269601265313834934940607699473978961272502869921381759907426352382780414231733018074896140591163471603443209963425067531581089620935637398012401371343112512453802816223735666321004204970052456991692937141500873393323939873997044606665119507737009006568842635521627192708402205972468008738929182955309400293069447393049131047951832017239854071795754795144659878576346323190223737410029610677029722546787721358486665549088358353924344731188261667278096096976158058109114221133034539145016834084441394968965053303264010839748781609350716520692681276692077892572055252215831125946496449603994448494038541532766444884221005621718299929726420444843247639994951738548039287770975664403161425975126276296172084371658261962045838888277517650273448282355623299548250769007866230284252579654513438471411128971402669388973974541692683426943965781773671486375019367720506181044403913001339161604537670832341019985122185876219813738794961352018143693216539700041178664781952308133993634293600923633825491035137102059358072836788673543947202914835457946222299004155839503463778292931617531088696661876962884765040333657374054884670352808414579356871183478161905829469990188245181103268254581631447997017764274052357155764953548795489937096247740954929672570084518409698846285854147542804017924439255551890105697075335745207999761958951552766283747553939856294193605042293179022347228876677258162673718531340630183407054889711025095516290925726023030440679688310068983083870119882421576219112685411076769188241718308555167480046463740908902684804374325919893060495599036714352242508013934497938875810214144700320566229644072780451375673549322347781738818725546848151396528744600529044171303171461490595017216349245457943135655980928826013180526814352585800151575061769342500654389739840928656127471759224852137739821218637570068992334970972418321020111939243269033894846674041865173412636922730030853426145387733492890484296277974486206931560031610571592814917414142166020220922585791709342115830072696496204961299160279213817773074820129749651948343827944926617586615781797447165677542693553848615452827352629534310824198693664548789023796546423223843306608149432523531791262899345691950959314316497642061776962265670849806825751737778860216451409749498483351273275861332932146882900228729075257159141707507562922240930228077367666773900219028602889342904657140005578480828740392836240988301634784160644345329596151706588737565615982764265471112686250269601181736859061492294129884887045672856955212987009455618090285044290272044329124102289875574317011162936970108511112849657033668606547043012452360562579602732348738918975750771530755126730113665243400575016928344041802189833011282499685997104185580076361523548655408218220581726105034927350209012325115262957109650757862783765828783790081798190113916782619685166523791031844396839681842243084030793787965273552712020487547459319157127958751472133666171587688041319214042848965947640920706312309339096264532294913995026154358039255704760214775875514402553130331662443376078855565588471047937883060556912377253557250476101173822577940077942639007477186014758200531520233442735072767401443412741386921775994310680869790706288024031387329125712269060118002943852025620388902951568070577065049477849650297879954774235535929828574436101368742938440332280632609483811939584569181727536651177495588208639570581557093233300026047355931852842450049289761677855126742815517843275016987018951760270701225121359620398663012742496852199839897435955463511832414119612587786123113382525316116776474831295950980729464534847331107670985307010241657728995062320006761047105820747074933924629184635784403446660193202595782171617303622337193962053449169663012763337329504892071732411581213526503088947476225975622479457324209298212444894504339631748048144589425293869397086257383774457010694898637323852896504941469558031770738477671052750287169828199909694258422401629970958999241878555057014567546202509389642945904672940145292225185696305643095525396264775901425911995154816352673011627413437738064991938972779325393050872485226646332033743539241986198353372233049286589562941058424824288044415628367075531077873878192689157530004449721824617196539989565519682864678398469353381784096825666134931620091118573266647702671120177621054989522197784763937260387006394083484338638246728603523766527639544466841346007348020252412571880079480917120647654143595585095286894806999301696795207469627152732539655697054876448246886019107528412256257439234650658508531541067256202035105811640548537082894589188284051627400244459240118294725112845924735633220362073882431284767474120729421879517282685141270996137962844590462999346095025801831630243239232723010945110542931892599518544187373480976127913552551621426275339366765623842044211680392397212469833773839011969504022355673847796976297822882100042559549989772027573743661670607667277854598390069966841250370919906466078175560398123734107328622309097547515253328904370145553996909091188198941368816370872873597675772857935504129340680842483274330309590724767229244586790323895648134623170593027883466380779575260654615945869238059212342599981488209247522096795226843428391039252153487801065161189058709374820564149570862411510526782825856702498865348719059759810040815971225161643268267754713130902887966951747086475546634126121730685346828973013598746540457136133868786590283470895698369386841345241999348631388004002629911926334181605163947704947855303487983827250590880958193859726130149814924716804879236974206674727597282201903137483399195801232265970456121603790741392308145507627843870288468194012378837508444078137144122928060956110510971726932390161879559141753636317998252872731112248547081795498537350409008803141925992335201657886508107634300076163252964532340030992944843083296763304130172752336408225510441377988189256283596289116872747087243980667093892458154084356829494650142067375219576991460889661666271917013871507620961478527037530682974163276405889290099887652760152056828349981612021121707141303729901564199843747736154719689001943897693700085095410145291780653589557614594282548602021301470062163102841894735360511321996954123480416614038607618851963745089943087921948242389321705408634845158606860822756197041997723696380267579840182680059421010554544695570166886656258629030181938649127970908581359280719151729200544956075258128170721224826027385011707473156862025083762593520604323455614175495201684099788032116909973014934974639725843156038414089968854369968193567087042692666821731628937290298620396345285595320702815597619860604492775546785769185396286616378548129233227427821155808687336971177301264415306170926466343407653225092670742424546745881418810118693421143956690760313040058631157584130931730830670459352788687708835011683227012591791012168650582357069237312056199372237899613189823614050808529042352994237900327526547412910252391823868335559312891854663995515020613832297131961623346037862417673959784881120288206780974586728505668050478505681738818705882883601620212551964090114898711104743130560754173092349900715641913917905501900428664460202800393879863092619299949339645955994018572124506469704350969339526115946923325146041504511429081040263814365017404541559914036622740310600700054065674759375555853071256119988140697588068624525609250688966448826389824618089564431805341634480920810145558662906653671121931062563197335752423691019514454811040748130974757506829634071760712637870232347195482034037208032043412600214641317643858609636505107482616722727499527718984472722330309222974975811243117593048049704699630937308424545308806918978194733953948398655592413809739768841203335332520575400538703889311429621265372400079278614826376552940570923510814762966914032237968554571657105155936176168398914235843018802104262030524692202428657319084853370090474867526546761807613630774180541811262038323344643795248151839864772601525454365302645453905129483522141545764225947909435170950293753662262329448603235161346428160288375987462038476461426682397652921491275372433848468770952075281825291479784585213984031755613516966943269653969135343910139997785659096968839748064410478884882974177056201600389028357317649637016728160268749178027183068286699357541310273238093101152896345367114000492727319658540850819543836294691396822588705249150772844833162468362790585184837437035304801769989111965060464004655693679025308169938302594300087206138989081204615457651527650781252681573963071193858405299244254071768438072755286650700967313370591720043743398957222044821918230540687100037835384461713185674039443531615188996041851260965242522815055670877372397559956850472526607431118559774080041859419583076904502937602704905222382297652603613102459958425513297904390535588699758351503870634064194125513903489378390482931641039557490549266451406315284800432669704896271450528089509386638445298050726379731144761582999464324848507063770594525244682903110529501273325834706771904243113415693460831726407132561319908958562790709562571808271005216900757103567658625053667788337800480937766686984115988804765292780861546934859486750831202688067280910727849704819336068684314967217452067621808145469748196106764566232519035190798560777296650945675906915642389695297892030212293456414058300566247127531486579900283820918249478507027471477355947355041369136585765260818733674348726233489742975508625733941419905712610920158977557118064443047085707056805197323177885086846063555856661622637464367243388604144028695620456254328854492215854977031559496112602107607391130450163314096602990414196188861175037818324632621318388650760019103885823593285616101177474649654768425745827593951519193813928356851829592109873198168740203808097697737030993473762518094139559708234817556397622220133922242630016423620729757461725416967904339051655767222131579050083546284760411864848547548610277964603715404731636229802767599960110573663891308860657830644507372788849436836498260094519371014816020215611838923608578789298145136972890065949807524648575941040106306809109417594807773073245309393114894310579739204531427761259200984900158934133939229682026137849474780417342001864776753731448441900500892696761764346594904499317114265049056410328581909823160004919848515952606059109949748149081948615775950886200847752894204420646698624512599317968834199205517596581229916704994202156572748412294959649223963496654158065885385905198434772275057212116419632093143156407687482856976738728098803041445850652406280825830159569093968486008753249877134263673911087380765383683005054969075431817379951303070789316094375971640870854819890048261939798209056503740646491947718534852522279190308514312857833318345078762591199128058599722701620511779507649403800925665273589397788921574897966783030188322005586077529199831265384589687951643074513806037903157888188853597912800934379728044025366789657451594531262090568528066458601601401715694222483672228803707456356143068293331167471266741736387884958430369911205302569944943811466615971298272918171194424988525659437292876342776719611240394142631848055532791739579260827799505876426141423884404871393960620717044658655204583671208868139586473646386484663576683448618214486808904829455419038302119227032830835461626210520812051921962023764989624116481541865975220174428339276547053274021586351144599949637659181452689204356207579634961672047479340508176699153362952203679110384593097303435007516242295501548191849052295856312851433630226927207586880688693609806437382058613479375795703462925140106583983679427919506834175906081173508455942644623542788271081363853817021849271113498832938546434956478331047638807573940940290419748831522228367834037042303027754560662049081288850247811625313288070196059396863299150447575806468334684990609420901254284781753374546379180855752039121449506530698099206426851559005036882785638001483811645827253101399272295568084185637157023144531149540748076516706056320693935290454291175985447152440164385939725205936934520952089338615389103184142219166714880218020075456399759018678606177187366922452825800406510978904572188815739785818319047824136985588196955818101169261169174927993119911279813339258473533772745529820181582386126641445539997050688076043708091386976420440722517956617911186775258063131442222617202905796233027785813725084284962694860519972109088434460590972212652048066156360769340378727560797236655401289692696787029604801221984100983880306551144728065542617917554688 ``` ... [Answer] # [JavaScript (ES6)](https://babeljs.io/), ~~36~~ 34 bytes ``` for(a=1;;a*=2)console.log(a+'+1/') ``` [Try it online!](https://tio.run/nexus/javascript-babel-node#TcsxDoAgDADAr7i1FVODg0vlLzSkujRiMPH76Oh@Z4865r7XhpqiiI5poVLPu7qx1wM1QIgzUM/c7HIthiAC0wCiW7RVgEj@AZj54y8 "JavaScript (Babel Node) – TIO Nexus") Inspired by [Jake Taylor's answer](https://codegolf.stackexchange.com/a/120839/69074). Note that this is limited by language since `a` is a floating-point variable, not an integer. -2 bytes thanks to [@Stefnotch](https://codegolf.stackexchange.com/users/33160/stefnotch). [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 19 bytes ``` 1{.'+1/'+puts.+.}do ``` [Try it online!](https://tio.run/nexus/golfscript#@29Yraeubaivrl1QlJlXoqetV5uS//8/AA "GolfScript – TIO Nexus") [Answer] # [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` 1{_o"+1/"o2*}h ``` [Try it online!](https://tio.run/nexus/cjam#@29YHZ@vpG2or5RvpFWb8f8/AA "CJam – TIO Nexus") [Answer] # [><>](https://esolangs.org/wiki/Fish), 14 bytes ``` 1:n"/1+"ooo2*! ``` [Try it online!](https://tio.run/nexus/fish#@29olaekb6itlJ@fb6Sl@P8/AA "><> – TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ 25 bytes ``` a=1;a*=2while$><<a<<'+1/' ``` [Try it online!](https://tio.run/nexus/ruby#@59oa2idqGVrVJ6RmZOqYmdjk2hjo65tqK/@/z8A "Ruby – TIO Nexus") [Answer] # Pyth, 10 bytes ``` #h~hyZ"+1/ ``` `Z` starts out as zero. `~hyZ` post-assigns the value of `2*Z+1` to `Z`. Thus, `Z` becomes `0, 1, 3, 7, 15, ...` over successive iterations. `h` then prints out the value one greater. `#` runs the infinite loop, and `"+1/` gets the formatting right. [Answer] # Vim, ~~22~~, 21 bytes/keystrokes ``` qqyiwA+1/<esc>p@"<C-a>@qqxX@q ``` While testing this, you might run into issues with the current register values. To fix this, run ``` :let @q='' :let @"='' ``` before running this, or by launching vim with ``` vim -u NONE -i NONE ``` [Answer] # R, ~~35~~ 34 bytes ``` cat(i<-1);repeat cat("+1/",i<-i*2) ``` Spacing is a bit werid but I understand that's ok. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~37~~32 bytes ``` BEGIN{for(;;)printf 2^i++"+1/"} ``` [Try it online!](https://tio.run/nexus/awk#@@/k6u7pV52WX6RhbV2hZWukWVCUmVeSplBhr6RtqK9UYVVha1j7/z8A "AWK – TIO Nexus") Could remove the `BEGIN` and save 5 bytes if input were allowed. Using exponents definitely cheaper byte-wise than multiplication. :) Hopefully 2^1023 is close enough to infinity (on my work computer). Unfortunately the TIO link truncates earlier than that (around 921). But 17726622920963562283492833353875882150307419319860869157979152909707315649514250439943889552308992750523075148942386782770807567185698815677056677116184170553481231217950104164393978236130449019315710017470734562946173533283208371259654747728689409291887821024109648618981425152 does seem pretty close to infinity. :) [Answer] # Powershell, 34 bytes ``` for([bigint]$i=1;;$i*=2){"$i+1/"} ``` [Try it online!](https://tio.run/nexus/powershell#@5@WX6QRnZSZnplXEquSaWtoba2SqWVrpFmtpJKpbaivVPv/PwA "PowerShell – TIO Nexus") [Answer] # [Go](https://golang.org/), ~~102~~ 100 bytes Go can be almost as bad as Java, apparently. ``` import(."fmt" ."math/big") func main(){n:=NewInt(1);for{Print(n.String()+"+1/");n.Mul(n,NewInt(2))}} ``` [Try it online!](https://tio.run/nexus/go#K0hMzk5MT1XITczM@5@ZW5BfVKKhp5SWW6LEpaeUm1iSoZ@Uma6kyZVWmpcMVqShWZ1nZeuXWu6ZV6JhqGmdll9UHVCUCeTk6QWXABnpGpraStqG@kqa1nl6vqU5Gnk6UNVGmpq1tf//f83L101OTM5IBQA "Go – TIO Nexus") (*Would be a good idea to avoid running any of these locally.* :P) [Answer] # Java, ~~107~~ 102 bytes ``` ()->{for(java.math.BigInteger z=null,o=z.ONE,n=o;;n=n.add(n))System.out.print(n.max(o)==o?1:"+1/"+n);} ``` `z=null` exists to shorten the `o=java.math.BigInteger.ONE` into `z=null,o=z.ONE`, saving 12 bytes. `z.ONE` will not throw a `NullPointerException` because we access a static member and not an instance one. Using `int` shortens the code, but fails to comply after 32 iterations. ## Saves * 107 -> 102 bytes: `n.compareTo(o)>0` turned into `n.max(o)==o`, thanks to an idea given by @Shufflepants [Answer] # C#, ̶6̶8̶ 154 bytes ``` void A(int b=1){System.Console.Write($"1{(b>1?"/"+b:"")}+");A(b*2);} ``` Here is a version not constrained by int ``` using System.Numerics;BigInteger b=new BigInteger(1);void A(){System.Console.Write($"1{(b>1?"/"+b:"")}+");b=BigInteger.Multiply(new BigInteger(2),b);A();} ``` [Answer] # JavaScript (ES6), ~~45~~ ~~43~~ 42 bytes Saved 2 bytes, thanks @DanielM ! Saved 1 byte, thanks @eush77 for pointing it out. ~~*=console.log;a=1;*(1);for(;;)\_(`+1/${a*=2}`)~~ ~~*=console.log;*(a=1);for(;;)\_(`+1/${a*=2}`)~~ ``` _=console.log;for(_(a=1);;)_(`+1/${a*=2}`) ``` My first go at Codegolf, go easy! [Answer] # PHP, 32 Bytes ``` for(;;)echo bcpow(2,$i++)."+1/"; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/898c95a59617927db2bb412aebfe4c75eec5522b) -6 Bytes if values like `9.2233720368548E+18` are allowed ``` for(;;)echo 2**$i++."+1/"; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTJQsv6fll@kYW2tmZqcka9gpKWlkqmtraekbagPlPoPAA "PHP – TIO Nexus") [Answer] # Befunge 93: 14 bytes ``` 1:.2*"/1+",,,# ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` o©1“+1/”Ḥɼß ``` [Try it online!](https://tio.run/##AR0A4v9qZWxsef//b8KpMeKAnCsxL@KAneG4pMm8w5///w "Jelly – Try It Online") ## How it works Jelly's parsing rules are very complicated and depend on the arities of the link. Usually, links are composed of collections of: * Dyad-nilad pairs (arities `2, 0`) such as `÷4` (divide by 4) * Nilad-dyad pairs (arities `0, 2`) such as `3<` (greater than 3) * Monads (arity `1`) such as `L` (length) * Dyad-monad and monad-dyads (arities `2, 1` and `1, 2`) such as `+H` or `H+` (both \$n + \frac n2\$) However, sometimes (very rarely), the arity patterns don't make sense. This is referred to an "unparseable" link. One such example is ``` 4 H 5 Ḥ ``` [Try it online!](https://tio.run/##y0rNyan8/99EwUPBVOHhjiX//wMA "Jelly – Try It Online") The arities here are `0, 1, 0, 1`, and the second nilad doesn't fit into any of the patterns. In this case, `5` is called an "unparseable nilad", and it causes the program to output the previous value (`4H`, or `2`) and discard it, using the `5` as the new link value. This causes the program about to output `210` (`4H` outputs `2` and `5Ḥ` outputs `10` at the end of the program) The arities of the program above are `2, 0, 0, 0, 1`. The pattern `0, 0, 0` is unparseable, meaning that the third and fourth links (`“+1/”` and `Ḥɼ`) are unparseable nilads ``` o©1“+1/”Ḥɼß - Main link f(n). Initially n = 0 o 1 - Replace 0 with 1 © - Save this value into the register “+1/” - Unparseable nilad; Output 1 and use "+1/" as the argument Ḥɼ - Unparseable nilad; Output "+1/" and use the below result as the argument: ɼ - Run the previous command on the register, then save the result back into the register: Ḥ - Unhalve; Yield 2n ß - Recurse, yielding f(2n) ``` [Answer] # [Aceto](https://github.com/aceto/aceto), 20 bytes ``` pL* pd12< p"M" 1+1/ ``` Prints the sequence without any spaces. When run, you won't see anything for a little while, because of buffering, run with `-F` to immediately see everything. 1. Pushes and prints a 1, then stores "+1/" in quick storage (the register). 2. Pushes a 1. 3. Multiplies by two, loads from the register, prints, duplicates, and prints. 4. GOTO 3. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 18 bytes ``` ?1{q=q*2?@+1/`';`q ``` Prints each term on a new line. Explanation: ``` ?1 Prints 1 { Infinite loop q=q*2 Doubles q, starts at 1*2=2 ?@+1/` Prints the string +1/ ';` without tabs, newlines or other terminators (code literal, ; is a QBIC function) q Also prints q The infinite loop is auto-closed by QBIC at EOF. ``` We can save a byte with a more liberal output format: ``` {?q,A,┘q=q*2#+1/ ``` [Answer] # Mathematica, 25 bytes ``` 1//.n_:>(n~Print~"+";n/2) ``` [Answer] ## `Haskell` - ~~66~~ ~~62~~ ~~60~~ ~~51~~ 49 chars ``` import Data.List main=print$intercalate" + 1/"$map(show.(2^))[0..] ``` This prints the string constructed by printing the string representations of the powers of two starting from 1, separated by the string `" + 1/"`. The code itself is 49 bytes, the import and newline push it up to 66 ## Edit: (62) Shaved 4 bytes by cutting out the import and defining intercalate with a much shorter name ``` f(x:xs)s=x++s++xs`f`s main=print$map(show.(2^))[0..]`f`" + 1/" ``` ## Edit 2: (60) Shaved 2 more characters by realizing I didn't need to use the (x:xs) list convention: ``` f(x:y)s=x++s++y`f`s main=print$map(show.(2^))[0..]`f`" + 1/" ``` ## Edit 3: (51) Reimplemented the definition of f and the map as the body of a fold to save 9 more characters ``` main=print$foldr((++).(++" + 1/").show.(2^))""[0..] ``` ## Edit 4: (49) As was pointed out by Laokoni, I can remove the spaces to cut down 2 more bytes off the total: ``` main=print$foldr((++).(++"+1/").show.(2^))""[0..] ``` [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), ~~41~~ 37 bytes *Saved 4 bytes because I realised I don't need the spaces, always read the spec thoroughly kids* ``` 1!_V"+/">!@R.[<!_>2*v<!@>R!_v!@R<1+>] ``` [Try it online!](https://tio.run/nexus/python3#1Rpdb9u69d2/gsmWWWps1@7dk@NkBYYWuA/DhmIoBrheoEqUzVWWPFF2HWzYX8/OISnySKISu8USrEBbkzw8318k9ZiWxZbJB8nEdleUFYvK9eFmoGbTfR5XRZHZtZIn@5ib1bjIMh5XosjtesL/uYdlMyrkZBdVGzfe8TKqitJOiIqXCr@dKaM8KbY3g0GcRVIyqRAG6t9wPmBAIGX392tewdbt/X0geZaOmMgTflTrjImUCSlyWUV5zAO1MmIyEzE3AAykqPZlzqqHHVcIwsAyMhEKlOKdAKqycoNi537zXRgOCErF6KSPwcEAUMXfJLtly9XNIN6XpZqA8fRmwPMEfnyMMgka3JVc8vLA3Uxc5Adg0k2UHMaSQMiqFPnajbmMox1Z3@6zSuwAhiCR38TOjURKWJAi4xQ0zRToX0u0cFYUZN@65Dx5cGNcVVrTkimacbFX2C4vDSfxJirNeIBmRatVgVRWqsoHY001RVWM9GHMjzHfVexzlO35h7IsyjkFUnxotNrpeFA734ilAtQOPsFBpYkiZ3bVIEETwvAHNlXWOkRZoH6MWG2lEWA4KEzgffVkgyG1YTldIQDAMg78mcnxDHyBqZnulsmu2GU8rYKwuxPXAg938kn2wKh6PWR3bGZjpsk1Y0gUrPM834pjsd446JkX@p2BdnI2iZwiqYfaadsc0X5Rm0JM@9nt0Nc0jNkChBppoLZxAmWEdVZ8jTK9XZKdemJp08LK7Ibw2fL7NIJUXMog14YE@u/gfzOrMgoMv28gaGHxDfxd3LLcypyzKyZqOQS7vmWzjng5e/v2lgkzMpgn0W4HmSkQ4cAgsl7TgshDJ4pZMvxHkKaCuEh0BlbZIBj@BWYxXV3JIfCmVlEXKvTqrGjSv1owrovVCT33F8ODAweZcHH5y3xF4B0A7prqXYaFX/PdvpobDpY4JUKWFiUoSOQUNdaUleLiqDOax4j6V60MQpZAW9OSOYAmo9o36Sad@MmMyfwNNjD1U6wq95MJl/zpNsj@ZAjpny6q/E8msACQISZ5MtQ1oLWuikBDvLoStFnDanBjPfjIFsp61mmMfkH7LpZ0gMYwh2DLo4nYo/JuiB3lH2DNB7QmNBZrHkxHLv3ZdgCsq2P@ARKXZHlRYdmpV5lbvNXlyAxDQwK3gx4JNmDplg3/PWRAXP@eDwm6RsmtZxulV0@B4SuRY7Wt6aBKO3RWBLcVBTK29XYqBcyPlXbcArp0w1b6D80MKvk1Kn4Lr8vCbqnLvvNBIoQu@3HoaJF2ASwZ@zD6WKwbDETnUIQ641uMqjrMqN6VwbWzU3lNjhhO/lGIPFjGmzIQil9wzdls9vvZ7J1GNiU5QyvZ@dhYEZ2vVuEIA/12OAw7pNvlyCqVlgJbl@Zt5KrYatkWtLjrMkgSqP7jawKdyO2m0/LT6gU9pjKdnPVCTEgdX70cMmjwldg6Q9Eoa3avDVWgIyyLMmkkaJs3Vi3xSGdZO4rl4MuXZrj4WGHMts662/W5m6PknFTT0fm6htTxYcoCihCHIYnwZk/fYnbu1AX5wWL8Rhrx1o7LoaNr9OmFux8S2yB@nb6deNBHkmTb1/NiGQpPDibA4gmDc72uaYZm6FGavczU7Jwk3E8zTJR@@5zSNV@dTkSngNCvAKGOjdObhkZkZffJrh0uryR2PZfQ9eABecQ8FFdhSLM8UrluFI72ma8l6/vnZG0kov4wQzduxPJTJlfAGI5PJOsfz786ly5XJ7mC1jQy5PGgZ3T3G6s7lyC8UfyfobvSqC8DvIC/dWmhdlEv3Og5q/UcII1hsOntHoysUtVx@ol1mikVrv5lezT3@0xP9XRWNPpK6l7wZNv8zmrIAno1ORl6C4A9OoedHf@yO@zth468nWpq4KgSNJ0X5hrax25zg3HRWvDVoA0Vud3qNcDHM6dlfefy4c8fyY1L/wYiW@bXBmnGO1sSu@UHSlFfXHbuzNqqg4DFMhX2yKZa1Y2H29IvoL7OnOB/9QHkNEHCTqRN2wnsLBkJq5LGuCPxk6W/PxP26NymGCDQ63zT070U0SHni1pTHjf83LSSPa3XbbJrzMjVrFWRDNm4roAE6cFla7LL/b5ms1rUWhWKPwcxdnUVsdr5uwZxctJpXhx7di7o2e8cYWKvc0iV6lUvapHNT6rHKhFPV@4WqdXYy0nJt8WBB@6upFdGwuafnmDz5R0558eq1@7UKIRTcFgdz22FLC02qzVMSB0VbP8PVDBuq8CmMa8fnq@ET1QJHtd82ot2P1dixJbjxWvzetaxSQOjKCvoNfSW3trSFW9vGcz5d9@l6FPhp9pffZllt9PgrOe6senrn2roDo9Hf@Xbiv7S/reeLdGxd8sffsZUqldSx88Qb8Wnnbs4evyor@Lo3I@W2qXl2tyeUaT0kezY2Xp9wgFdNhUhT4ntZivYehubREkyqnUllzO8trKjKRwJT0gSnlacHJ7kfmtsvDq95377KrpIwUBlIg7/W4XoF3Uf1bPV9OZV1ATn@JfVkCJ4tnLGr6Icuf/6sspRBM9Wzt9fRTm74vvLKkcRPFs5V68TVkXywmGFBM9QTvvdpntO9pTxC6tLwrT3/mTR6hHKokL9@C4X7vygHsgbC6k/ttGUB97HqfOfk7wXzr5npJMejMIG0vYlpbVmz6OQ3tz32OP3mO7tdf0@kif03Zxc3/XdUqjbzkHjyX6hn@zt0zt4skjwxV5e6KtRs/LHoix5XLG9jNYcr6nZIs2i9R1byGJfxvyOLfUPtXf1JUfGDMicfRDVhpdsnOLb6zie4C@RJyIGj5Cs2kSVwyMki1iKz81Vwb5yCNEoYfhl28i8Qo/jp/Z@LSORr4ssVc/PNY59PsGvCdSXCFMdSPwo1NXdYItw5isF/HjGyGFm8AMZVJmGwpKVDqnGmNwU@yxBEsAM11QF/gZmUIz6SwaN1nxNAQaItkhDzxqrmi/zJkIiRFCDmWD@DkrEj6HArhoVi4CCdb2a63SCGqsPIvorD0LbpR8jwUfU6ZV@YE/BS5ML5NbSNtFaK0uFrdNF/IQuQH5Uhkf@FlM1Sy0nROcxTmjIPz4@juPH2cX958vrt5d3F@8/TZaLi/u7d28Oi4v3d58u7g8wt5hd363@Cw "Python 3 – TIO Nexus") Can probably be golfed better, but it works. ]
[Question] [ # Background Euler's [totient](https://en.wikipedia.org/wiki/Euler%27s_totient_function) function `œÜ(n)` is defined as the number of whole numbers less than or equal to `n` that are relatively prime to `n`, that is, the number of possible values of `x` in `0 < x <= n` for which `gcd(n, x) == 1`. We've had [a](https://codegolf.stackexchange.com/questions/83046/golf-the-repeated-totient-function) [few](https://codegolf.stackexchange.com/questions/63710/calculate-phi-not-pi) [totient](https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function)-[related](https://codegolf.stackexchange.com/questions/79082/draw-a-phi-triangle) [challenges](https://codegolf.stackexchange.com/questions/67773/co-primality-and-the-number-pi) before, but never one which is just calculating it. The mapping of the totient function onto the whole numbers is [OEIS A000010](http://oeis.org/A000010). # Challenge Given an integer `n > 0`, calculate `œÜ(n)`. You may take input through command-line arguments, standard input, function arguments, or anything else reasonable. You may give output through standard output, return values, or anything else reasonable. Anonymous functions are acceptable. You may assume that the input will not overflow your natural method of storing integers, e.g. `int` in C, but you **must** support inputs up to 255. **If your language has a built-in totient function, you may not use it.** # Examples ``` œÜ(1) => 1 œÜ(2) => 1 œÜ(3) => 2 œÜ(8) => 4 œÜ(9) => 6 œÜ(26) => 12 œÜ(44) => 20 œÜ(105) => 48 ``` Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer. [Answer] ## Mathematica, ~~27~~ 22 bytes ``` Range@#~GCD~#~Count~1& ``` An unnamed function that takes and returns an integer. Not much to explain here, except that `@` is prefix notation for function calls and `~...~` is (left-associative) infix notation, so the above is the same as: ``` Count[GCD[Range[#], #], 1] & ``` [Answer] # J, 9 bytes ``` (-~:)&.q: ``` This is based on the Jsoftware's [essay](http://code.jsoftware.com/wiki/Essays/Totient_Function) on totient functions. Given *n* = *p*1*e*1 ‚àô *p*2*e*2 ‚àô‚àô‚àô *p**k**e**k* where *p**k* is a prime factor of *n*, the totient function œÜ(*n*) = œÜ(*p*1*e*1) ‚àô œÜ(*p*2*e*2) ‚àô‚àô‚àô œÜ(*p**k**e**k*) = (*p*1 - 1) *p*1*e*1 - 1 ‚àô (*p*2 - 1) *p*2*e*2 - 1 ‚àô‚àô‚àô (*p**k* - 1) *p**k**e**k* - 1. ## Usage ``` f =: (-~:)&.q: (,.f"0) 1 2 3 8 9 26 44 105 1 1 2 1 3 2 8 4 9 6 26 12 44 20 105 48 f 12345 6576 ``` ## Explanation ``` (-~:)&.q: Input: integer n q: Prime decomposition. Get the prime factors whose product is n ( )& Operate on them ~: Nub-sieve. Create a mask where 1 is the first occurrence of a unique value and 0 elsewhere - Subtract elementwise between the prime factors and the mask &.q: Perform the inverse of prime decomposition (Product of the values) ``` [Answer] # MATL, 7 bytes ``` t:Zd1=s ``` You can [TryItOnline](http://matl.tryitonline.net/#code=dDpaZDE9cw&input=MTA1). Simplest idea, make a vector 1 to N, and taken gcd of each element with N (`Zd` does gcd). Then, find which elements are equal to 1, and sum the vector to get the answer. [Answer] ## Haskell, 28 bytes ``` f n=sum[1|1<-gcd n<$>[1..n]] ``` Uses Haskell's [pattern matching of constants](https://codegolf.stackexchange.com/a/83103/20260). The tricks here are fairly standard for golfing, but I'll explain to a general audience. The expression `gcd n<$>[1..n]` maps `gcd n` onto `[1..n]`. In other words, it computes the `gcd` with `n` of each number from `1` to `n`: ``` [gcd n i|i<-[1..n]] ``` From here, the desired output is the number of `1` entries, but Haskell lacks a `count` function. The idiomatic way to `filter` to keep only `1`'s, and take the resulting `length`, which is much is too long for golfing. Instead, the `filter` is simulated by a list comprehension `[1|1<-l]` with the resulting list `l`. Usually, list comprehensions bind values onto variable like in `[x*x|x<-l]`, but Haskell allows a pattern to be matched against, in this case the constant `1`. So, `[1|1<-l]` generating a `1` on each match of `1`, effectively extracting just the `1`'s of the original list. Calling `sum` on it gives its length. [Answer] ## Python 2, 44 bytes ``` f=lambda n,d=1:d/n or-f(d)*(n%d<1)-~f(n,d+1) ``` Less golfed: ``` f=lambda n:n-sum(f(d)for d in range(1,n)if n%d<1) ``` Uses the formula that the Euler totients of the divisors of `n` have a sum of `n`: [![enter image description here](https://i.stack.imgur.com/k7xiE.png)](https://i.stack.imgur.com/k7xiE.png) The value of `œï(n)` can then be recursively computed as `n` minus the sum over nontrivial divisors. Effectively, this is doing [M√∂bius inversion](https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula) on the identity function. I used the same method in a [golf to compute the M√∂bius function](https://codegolf.stackexchange.com/a/70024/20260). Thanks to Dennis for saving 1 byte with a better base case, spreading the initial value of `+n` into `+1` for each of the `n` loops, done as `-~`. [Answer] # Jelly, 4 bytes ``` Rgƒã1 ``` [Try it online!](http://jelly.tryitonline.net/#code=UmfEizE&input=&args=NDQ) ### Explanation ``` Rgƒã1 Main monadic chain. Argument: z R Yield [1 2 3 .. z]. g gcd (of each) (with z). ƒã1 Count the number of occurrences of 1. ``` ## With built-in ``` √Ü·π™ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4bhuao&input=&args=NDQ) ### Explanation ``` √Ü·π™ Main monadic chain. Argument: z √Ü·π™ Totient of z. ``` [Answer] # Regex (ECMAScript), 131 bytes *At least -12 bytes thanks to Deadcode (in chat)* ``` (?=((xx+)(?=\2+$)|x+)+)(?=((x*?)(?=\1*$)(?=(\4xx+?)(\5*(?!(xx+)\7+$)\5)?$)(?=((x*)(?=\5\9*$)x)(\8*)$)x*(?=(?=\5$)\1|\5\10)x)+)\10|x ``` [Try it online!](https://tio.run/##TY5BT4MwGIb/CiNL@D4YbCxj6rBw8rCLBz2Kh4Z1pVoKKXXDib8dO5Il3t6@z/vk6wc90a7UojVh14oD03WjPtn3qIliZ@eF8ae@BbiQbOmPkBOAvg/QhmIdzHGweXrZ2s@nOvbnU1Fs7NBWReJDPpus4s4qRYL5/KZMRlI8WKe303sfbfCv8NrbcTxYHK8stXq8GvrRX14wMs2r0UJxwKiTomSwXYQbxPRcCckAJNGMHqRQDBBnRH1JiT@cyKhrpTDghR6m4gigCI8kU9xUmK2HQXTP9BkEaanu2F4Z4G@rd8QbYP@ByuI83l0xmko3Z3evTlSKg6Op4mznuIFMj42GVDwSloogQHuwJm7vRpq1jBoQGNXUlBVoxLJRXSNZJBsOYuF4YeYtnNpev30v/R3jcJ1s/wA) Output is the length of the match. ECMAScript regexes make it extremely hard to count anything. Any backref defined outside a loop will be constant during the loop, any backref defined inside a loop will be reset when looping. Thus, the only way to carry state across loop iterations is using the current match position. That‚Äôs a single integer, and it can only decrease (well, the position increases, but the length of the tail decreases, and that‚Äôs what we can do math to). Given those restrictions, simply counting coprime numbers seems impossible. Instead, we use [Euler‚Äôs formula](https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler%27s_product_formula) to compute the totient. Here‚Äôs how it looks like in pseudocode: ``` N = input Z = largest prime factor of N P = 0 do: P = smallest number > P that‚Äôs a prime factor of N N = N - (N / P) while P != Z return N ``` There are two dubious things about this. First, we don‚Äôt save the input, only the current product, so how can we get to the prime factors of the input? The trick is that (N - (N / P)) has the same prime factors > P as N. It may gain new prime factors < P, but we ignore those anyway. Note that this only works because we iterate over the prime factors from smallest to greatest, going the other way would fail. Second, we have to remember two numbers across loop iterations (P and N, Z doesn‚Äôt count since it‚Äôs constant), and I just said that was impossible! Thankfully, we can swizzle those two numbers in a single one. Note that, at the start of the loop, N will always be a multiple of Z, while P will always be less than Z. Thus, we can just remember N + P, and extract P with a modulo. Here‚Äôs the slightly more detailed pseudo-code: ``` N = input Z = largest prime factor of N do: P = N % Z N = N - P P = smallest number > P that‚Äôs a prime factor of N N = N - (N / P) + P while P != Z return N - Z ``` And here‚Äôs the commented regex: ``` # \1 = largest prime factor of N # Computed by repeatedly dividing N by its smallest factor (?= ( (xx+) (?=\2+$) | x+ )+ ) (?= # Main loop! ( # \4 = N % \1, N -= \4 (x*?) (?=\1*$) # \5 = next prime factor of N (?= (\4xx+?) (\5* (?!(xx+)\7+$) \5)? $ ) # \8 = N / \5, \9 = \8 - 1, \10 = N - \8 (?= ((x*) (?=\5\9*$) x) (\8*) $ ) x* (?= # if \5 = \1, break. (?=\5$) \1 | # else, N = (\5 - 1) + (N - B) \5\10 ) x )+ ) \10 ``` And as a bonus‚Ķ ## Regex `üêù` (ECMAScript 2018, number of matches), 23 bytes ``` x(?<!^\1*(?=\1*$)(x+x)) ``` [Try it online!](https://tio.run/##DY3BCoJAFEV/5SWB76U@ctGmMmnRD9TSDIdpGC1TGYcawX@32dwDhwP3Jb5ilKYZbNL1T7UYyOCq9MUNeLOm6TQb8asWh/lx9binG8wzv2tCFzmipeKxbaTCNE5SiiHUIR0KZj4bIybcbYnfahqRSv6IAR1kJ5B9N/at4rbXXkQQ7iH0wMAFbNSghEVHPreyRkMwz1CUxK3qtK394x8) Output is the number of matches. ECMAScript 2018 introduces variable-length look-behind (evaluated right-to-left), which makes it possible to simply count all numbers coprime with the input. It turns out this is independently the same method used by [Leaky Nun's Retina solution](https://codegolf.stackexchange.com/a/83550/17216), and the regex is even the same length ([and interchangeable](https://tio.run/##DcrBCoJAEIDhV5kk2JnUIQ9dKpMOvUAd1WixZbVMZXepFXx38/TDx/@SX2kr0wwu7vqnmg2kcFX64ge8OdN0mo38PWbMVuh9SEWyWWN2TO9FEhL5@cG2bSqFSRQnFIHQgg45M5@NkSPutsRvNVqkkj9yQA/pCaq@s32ruO31AiGIPYglGPiAjRqUdOhp2V1VoyGYJshL4lZ12tVE8x8)). I'm leaving it here because it may be of interest that this method works in ECMAScript 2018 (and not just .NET). ``` # Implicitly iterate from the input to 0 x # Don‚Äôt match 0 (?<! ) # Match iff there is no... (x+x) # integer >= 2... (?=\1*$) # that divides the current number... ^\1* # and also divides the input ``` [Answer] ## Pyke, 5 bytes ``` m.H1/ ``` [Try it here!](http://pyke.catbus.co.uk/?code=m.H1%2F&input=105&warnings=0) ``` count(map(gcd, range(input)), 1) ``` [Answer] # J, 11 bytes ``` +/@(1=+.)i. ``` ## Usage ``` >> f =: +/@(1=+.)i. >> f 44 << 20 ``` where `>>` is STDIN and `<<` is STDOUT. ## Explanation ``` +/ @ ( 1 = +. ) i. ‚îÇ ‚îå‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îÄ‚îĂîê +/@(1=+.) i. ‚îÇ ‚îå‚îĂîÄ‚îÄ‚îê +/ @ 1=+. ‚îå‚îĂîÄ‚îê 1 = +. >> (i.) 44 NB. generate range << 0 1 2 3 4 ... 43 >> (+.i.) 44 NB. calculate gcd of each with input << 44 1 2 1 4 ... 1 >> ((1=+.)i.) 44 NB. then test if each is one (1 if yes, 0 if no) << 0 1 0 1 0 ... 1 >> (+/@(1=+.)i.) 44 NB. sum of all the tests << 20 ``` [Answer] # Python >=3.5, ~~76~~ ~~64~~ 58 bytes *Thanks to LeakyNun for golfing off 12 (!) bytes.* *Thanks to Sp3000 for golfing off 6 bytes.* ``` import math lambda n:sum(math.gcd(n,x)<2for x in range(n)) ``` I love how readable Python is. This makes sense, even through the golfedness. [Answer] # Ruby, 32 bytes ``` ->n{(1..n).count{|i|i.gcd(n)<2}} ``` a lambda that takes an integer n, and returns the counts of how many integers in the range (1..n) are coprime with n. [Answer] # [Perl 6](http://perl6.org), ~~¬†26 24¬†~~ 22 bytes ``` ~~{[+] (^$^n Xgcd $n) X== 1} {+grep 2>\*,(^$\_ Xgcd$\_)}~~ {[+] 2 X>(^$_ Xgcd$_)} ``` ### Explanation: ``` { [+] # reduce using &infix:<+> 2 X[>] # crossed compared using &infix:¬´>¬ª ( ^$_ # up to the input ( excludes input ) X[gcd] # crossed using &infix:<gcd> $_ # the input ) } ``` ### Example: ``` #! /usr/bin/env perl6 use v6.c; my &œÜ = {[+] 2 X>(^$_ Xgcd$_)}; say œÜ(1) # 1 say œÜ(2) # 1 say œÜ(3) # 2 say œÜ(8) # 4 say œÜ(9) # 6 say œÜ(26) # 12 say œÜ(44) # 20 say œÜ(105) # 48 say œÜ 12345 # 6576 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` :{:1e.$pdL,?$pd:LcCdC}fl. ``` ### Explanation Brachylog has no GCD built-in yet, so we check that the two numbers have no prime factors in common. * Main predicate: ``` :{...}fl. Find all variables which satisfy predicate 1 when given to it as output and with Input as input. Unify the Output with the length of the resulting list ``` * Predicate 1: ``` :1e. Unify Output with a number between Input and 1 $pdL L is the list of prime factors of Output with no duplicates , ?$pd:LcC C is the concatenation of the list of prime factors of Input with no duplicates and of L dC C with duplicates removed is still C ``` [Answer] # Python 2, 57 bytes ``` f=lambda n,k=1,m=1:n*(k>n)or f(n-(n%k<m%k)*n/k,k+1,m*k*k) ``` Test it on [Ideone](http://ideone.com/RhBbpO). ### Background By [Euler's product formula](https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler.27s_product_formula), ![Euler's product formula](https://i.stack.imgur.com/0Adtc.png) where **φ** denotes Euler's totient function and **p** varies only over prime numbers. To identify primes, we use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem): ![corollary of Wilson's theorem](https://i.stack.imgur.com/ordYr.png) ### How it works At all times, the variable **m** will be equal to the square of the factorial of **k - 1**. In fact, we named arguments default to **k = 1** and **m = 0!2 = 1**. As long as **k ≤ n**, `n*(k>n)` evaluates to **0** and the code following `or` gets executed. Recall that `m%k` will yield **1** if **m** is prime and **0** if not. This means that `x%k<m%k` will yield **True** if and only if both **k** is a prime number and **x** is divisible by **k**. In this case, `(n%k<m%k)*n/k` yields **n / k**, and subtracting it from **n** replaces its previous value with **n(1 - 1/k)**, as in Euler's product formula. Otherwise, `(n%k<m%k)*n/k` yields **0** and **n** remains unchanged. After computing the above, we increment **k** and multiply **m** by the "old" value of **k2**, thus maintaining the desired relation between **k** and **m**, then call **f** recursively with the updated arguments. Once **k** exceeds **n**, `n*(k>n)` evaluates to **n**, which is returned by the function. [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` lambda n:sum(k/n*k%n>n-2for k in range(n*n)) ``` This uses the same method to identify coprimes as [my answer to ‚ÄúCoprimes up to N‚Äù](https://codegolf.stackexchange.com/a/104681/12012). [Try it online!](https://tio.run/##FcyxDoIwGEXhWZ/iLg2F/EYpaJQEnsSlplZJ5UIqDj59tdvJN5zluz5nmuTR45pedro5C3bvz6TDnlVQHLgzfo4IGIlo@bhrVizLlJEZdS0wgkZwFlz@fRK0raA@HMtuu1niyBWFahz6Acq4AgqaAq/z5gc "Python 2 ‚Äì Try It Online") [Answer] # Julia 1.x, 22 bytes ``` !n=sum(gcd.(1:n,n).<2) ``` This is the same as the old solution, but using newer features of the language, as the original solution dates back to something like Julia 0.4. This solution uses function broadcasting to achieve the result more efficiently. --- # Julia, 25 bytes ``` !n=sum(i->gcd(i,n)<2,1:n) ``` It's simple - the `sum` function allows you to give it a function to apply before summing - basically the equivalent of running `map` and then `sum`. This directly counts the number of relatively prime numbers less than `n`. [Answer] # Pyth, 6 bytes ``` smq1iQ ``` [Try it online!](http://pyth.herokuapp.com/?code=smq1iQ&input=44&debug=0) ``` /iLQQ1 ``` [Try it online!](http://pyth.herokuapp.com/?code=%2FiLQQ1&input=44&debug=0) ## Explanation ``` smq1iQ input as Q smq1iQdQ implicitly fill variables m Q for d in [0 1 2 3 .. Q-1]: iQd gcd of Q and d q1 equals 1? (1 if yes, 0 if no) s sum of the results /iLQQ1 input as Q iLQQ gcd of each in [0 1 2 3 .. Q-1] with Q / 1 count the number of occurrences of 1 ``` [Answer] ## PowerShell v2+, 72 bytes ``` param($n)1..$n|%{$a=$_;$b=$n;while($b){$a,$b=$b,($a%$b)};$o+=!($a-1)};$o ``` PowerShell doesn't have a GCD function available to it, so I had to roll my own. This takes input `$n`, then ranges from `1` to `$n` and pipes those into a loop `|%{...}`. Each iteration we set two helper variables `$a` and `$b` and then execute a GCD `while` loop. Each iteration we're checking that `$b` is still non-zero, and then saving `$a%$b` to `$b` and the previous value of `$b` to `$a` for the next loop. We then accumulate whether `$a` is equal to `1` in our output variable `$o`. Once the for loop is done, we place `$o` on the pipeline and output is implicit. As an example of how the `while` loop works, consider `$n=20` and we're on `$_=8`. The first check has `$b=20`, so we enter the loop. We first calculate `$a%$b` or `8%20 = 8`, which gets set to `$b` at the same time that `20` gets set to `$a`. Check `8=0`, and we enter the second iteration. We then calculate `20%8 = 4` and set that to `$b`, then set `$a` to `8`. Check `4=0`, and we enter the third iteration. We calculate `8%4 = 0` and set that to `$b`, then set `$a` to `4`. Check `0=0` and we exit the loop, so the *GCD(8,20)* is `$a = 4`. Thus, `!($a-1) = !(4-1) = !(3) = 0` so `$o += 0` and we don't count that one. [Answer] # Factor, 50 bytes ``` [ dup iota swap '[ _ gcd nip 1 = ] filter length ] ``` Makes a range (*iota*) **n**, and *curries* **n** into a function which gets **gcd x n** for all values of **0 <= x <= n**, tests if the result is **1**. *Filter* the original range on whether the result of **gcd x n** was **1**, and take its *length*. [Answer] # Japt `-mx`, ~~7~~ 5 bytes ``` yN ¬•1 ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=eU4gpTE=&input=MTA1Ci1teA==) -2 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~67~~ 65 bytes ``` f(x,a,b,y,z){for(z=y=x;a=y--;z-=b>1)for(b=x;a^=b^=a^=b%=a;);x=z;} ``` [Try it online!](https://tio.run/##bcyxCsIwEIDh3ccoFO4gAaMVlON8klJIIpEORikdkpQ@e0pmb/mHb/i9fntfa4CkrHIqq4Jb@C5QOHMiy1lrKprd02Bj13BiN3Frz5aQEhfa68fOEXA7/ZY5rgG6/jXGTgUwiPSHFwmvEt4lfIjPQdJBVHO@Nd7rAQ "C (gcc) ‚Äì Try It Online") Edit: Removed temp variable. Edit2: -1 thanks to [@HowChen](https://codegolf.stackexchange.com/questions/77270/greatest-common-divisor/152046#152046) Slightly less golfed ``` f(x,a,b,y,z){ // counts y NOT coprime with x and subtract for(z=y=x;a=y--;z-=b>1) // compute GCD for(b=x;a^=b^=a^=b%=a;); x=z; } ``` [Answer] # Retina, ~~36~~ 29 bytes 7 bytes thanks to Martin Ender. ``` .+ $* (?!(11+)\1*$(?<=^\1+)). ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKD8hKDExKylcMSokKD88PV5cMSspKS4&input=MTA1) ## Explanation There are two stages (commands). ### First stage ``` .+ $* ``` It is a simple regex substitution, converting the input to that many ones. For example, `5` would be converted to `11111`. ### Second stage ``` (?!(11+)\1*$(?<=^\1+)). ``` This regex tries to match the positions which satisfy the condition (co-prime with input), and then return the number of matches. [Answer] ## 05AB1E, 7 bytes ``` Lvy¬π¬øi¬º ``` **Explained** ``` Lv # for each x in range(1,n) y¬π¬ø # GCD(x,n) i¬º # if true (1), increase counter # implicitly display counter ``` [Try it online](http://05ab1e.tryitonline.net/#code=THZ5wrnCv2nCvA&input=MTA1) [Answer] **Common Lisp, 58 bytes** ``` (defun o(x)(loop for i from 1 to x if (=(gcd x i)1)sum 1)) ``` This is a simple loop which counts up 1 to the given n and increments the sum if gcd = 1. I use the function name o since t is the true boolean value. Not nearly the shortest but fairly simple. [Answer] # MATLAB / Octave, 21 bytes ``` @(n)sum(gcd(n,1:n)<2) ``` Creates an anonymous function named `ans` which can be called with the integer `n` as the only input: `ans(n)` [**Online Demo**](http://ideone.com/yghvhv) [Answer] # APL, 7 bytes ``` +/1=‚䢂ஂç≥ ``` This is a monadic function train that takes an integer on the right. The approach here is the obvious one: sum (`+/`) the number of times the GCD of the input and the numbers from 1 to the input (`‚䢂ஂç≥`) is equal to 1 (`1=`). [Try it here](http://tryapl.org/?a=f%20%u2190%20+/1%3D%u22A2%u2228%u2373%20%u22C4%20f%20105&run) [Answer] # Haskell, ~~31~~ 30 bytes ``` \n->sum[1|x<-[1..n],gcd n x<2] ``` *1 byte saved, thanks to @Damien.* Selects values with gcd = 1, maps each to 1, then takes the sum. [Answer] # JavaScript (ES6), 53 bytes ``` f=(n,k=n)=>k--&&(C=(a,b)=>b?C(b,a%b):a<2)(n,k)+f(n,k) ``` [Try it online!](https://tio.run/##dc3BDsIgDIDhu0/BxaWN4AbiMo3oYU8CcxjdAsYZXx@HkYMknprma/rf9EtP3eN6fzLnz30IVoGjg3KojgNjRQGtAk3NvJpTC4bqpcG9PgiMZ7iynxE67yY/9uvRX8ACRySElCXhi18Q/2CTQGTQJJAZ7BLUeaOOEhv5Lym/IqpMeLWdKVaa8AY "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Brachylog v2](https://github.com/JCumin/Brachylog), 16 bytes ``` {>‚Ñï‚âú;?·∏ãÀ¢{‚äá·µõ!}ƒñ}·∂ú ``` [Try it online!](https://tio.run/##AVgAp/9icmFjaHlsb2cy/3t3IiAtPiAidz/ihrDigoLhuol94bWQ/3s@4oSV4omcOz/huIvLonviiofhtZshfcSWfeG2nP//WzEsMiwzLDgsOSwyNiw0NCwxMDVd "Brachylog ‚Äì Try It Online") ``` { }·∂ú Count the number of possible ways that: ‚Ñï‚âú some non-negative integer > less than the input ;? and the input ·∏ãÀ¢ have prime factorizations {‚äá·µõ!} the largest shared subset of which ƒñ is empty. ``` # [Brachylog v2](https://github.com/JCumin/Brachylog), 16 bytes ``` ‚ü®‚ü¶‚ÇÖzg‚ü©{·∏ãÀ¢‚äá·µõ!ƒñ}À¢l ``` [Try it online!](https://tio.run/##AVsApP9icmFjaHlsb2cy/3t3IiAtPiAidz/ihrDigoLhuol94bWQ/@KfqOKfpuKChXpn4p@pe@G4i8ui4oqH4bWbIcSWfcuibP//WzEsMiwzLDgsOSwyNiw0NCwxMDVd "Brachylog ‚Äì Try It Online") ``` z Cycling zip ‚ü¶‚ÇÖ the range from 0 to one less than the input ‚ü® g‚ü© with a list containing only the input. { }À¢ Map where possible over the pairs: ·∏ãÀ¢ the prime factorizations' ‚äá·µõ! largest shared subset ƒñ is empty. l For how many pairs did it succeed? ``` A nuance that my explanations fail to capture is that `·∏ã` fails given an input of 1, so if `·∏ãÀ¢` is given a list containing 1, the 1 is essentially discarded and ignored--so the `‚äá·µõ!` (which is really "find any common subset, then discard all of this predicate's choice points", hence the braces in the first solution) of the remaining single number is its entire prime factorization, decidedly not empty, unless the list was nothing but 1s in which case everything is empty. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ·πÅo=1‚åã¬π·∏£ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxYYGBv8f7mzMtzV81NN9aCdQ5P9/AA "Husk ‚Äì Try It Online") ``` ·πÅo=1‚åã¬π·∏£ ·πÅ ·∏£ # sum of function applied to 1..input o # join 2 functions: ‚åã¬π # greatest common divisor with input =1 # equals 1 ``` ]
[Question] [ I was expecting to post something more complex as my first puzzle in PCG, but a particular, uh... [homework question on Stack Overflow](https://stackoverflow.com/q/26623488/1461424) inspired me to post this. They want to: > > print the following pattern for any given word that contains **odd** number of letters: > > > > ``` > P M > R A > O R > G > O R > R A > P M > > ``` > > [c++](/questions/tagged/c%2b%2b "show questions tagged 'c++'") > > > --- > > Notice that letters are a knight's move apart in the pattern you need to print. So, every other column is empty. -- (Thanks [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for pointing this out.) > > > ## Rules 1. Using C++ is prohibited. As I may link this question there. 2. You may use `stdout`, or any means of quickly outputting a string (e.g. `alert()` in JavaScript). 3. As always, shortest code wins. [Answer] ## APL (~~37~~ ~~35~~ ~~34~~ 27) ``` ↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞ ``` It takes input from the keyboard, like so: ``` ↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞ CODE-GOLF C F O L D O E G - E G D O O L C F ``` [Answer] # Python 2 - ~~94 90 89~~ 88 ``` s=input() L=len(s) R=range(L) for i in R:print" ".join([s[j]," "][j!=i!=L+~j]for j in R) ``` **Input:** ``` "CODE-GOLF" ``` **Output:** ``` C F O L D O E G - E G D O O L C F ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 ``` Vzjdm?@zd}N,dt-lzd\ Uz ``` Test: ``` $ pyth -c 'Vzjdm?@zd}N,dt-lzd\ Uz' <<< "CODE-GOLF" C F O L D O E G - E G D O O L C F ``` Explanation: ``` (Implicit) z = input() (Implicit) d = ' ' Vz for N in range(len(z)): jd print(d.join( m map(lambda d: ?@zd z[d] if }N N in ,dt-lzd (d,len(z)-d-1) else \ " ", Uz range(len(z))))) ``` [Answer] ## Python 3: 75 chars ``` s=input() i=n=len(s) while i:i-=1;a=[" "]*n;a[i]=s[i];a[~i]=s[~i];print(*a) ``` For line `i`, we start with a list of spaces and set the entries `i` from the front and back to be equal to the letters of the input string. Then, we print the result. Python strings are immutable, so `a` must be a list of characters instead. The list `a` must be initialized inside the loop or the modifications will carry over between loops. We use `print(*a)` to print each character in the list, space separated, which requires Python 3. The output lines are symmetrical, so we can have `i` count down rather than up using a while loop. ``` >>> CODE-GOLF C F O L D O E G - E G D O O L C F ``` It also works for an even number of letters. ``` >>> CODEGOLF C F O L D O E G E G D O O L C F ``` [Answer] # CJam, ~~27~~ 25 bytes ``` l_,S*:Sf{W):W2$tW~@tS}zN* ``` [Try it online.](http://cjam.aditsu.net/) ### Example run ``` $ cjam <(echo 'l_,S*:Sf{W):W2$tW~@tS}zN*') <<< CROSS; echo C S R S O R S C S ``` As the example in the answer, each line has trailing whitespace. ### How it works ``` " N := '\n'; R := []; S = ' '; W := -1 "; l " Q := input() "; _,S*:S " S := len(Q) * S "; f{ } " for each C in Q: "; " T := S "; W):W " W += 1 "; 2$t " T[W] := C "; W~@t " T[~W] := C "; " R += [T] "; S " R += [S] "; z " R := zip(R) "; N* " R := N.join(R) "; " print R "; ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 5 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` \\:⇵n ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNDJXVGRjNDJXVGRjFBJXUyMUY1JXVGRjRF,i=JTIyUFJPR1JBTSUyMg__,v=8) Explanation: ``` \ create a diagonal of the input \ create an even steeper diagonal of that :⇵ reverse a copy of it vertically n overlap the two ``` [Answer] # Pure Bash, 94 bytes ``` l=${#1} for((;t<l*l;t++));{ ((x=t%l))||echo ((x-t/l&&x+t/l+1-l))&&printf \ ||printf ${1:x:1} } ``` [Answer] # [R](https://www.r-project.org/), ~~99~~ ~~98~~ ~~93~~ 89 bytes ``` m=ifelse(diag(l<-length(w<-el(strsplit(scan(,''),'')))),w,' ') write(pmax(m,m[,l:1]),1,l) ``` [Try it online!](https://tio.run/##FcNLCoAgEADQq7SbGZgWbvucJFpYTiaMESrY7a0evNRanMMhmgVdsB516lUuX06sUy@KuaR8ayiYd3shA9D/w5WhAxprCkXwjvbByHFhHcxKbFipgd12J9Be "R – Try It Online") Line 1 reads input string, splits it into characters, stores its length and creates a matrix with the word on its main diagonal – letters of the word are superposed on an identity matrix (and repeated by default to match its length) and only those matching 1's are retained, others being replaced by spaces. Line 2 prints a matrix formed by elements of either the diagonal matrix or its horizontally mirrored version, whichever are greater. *−2 + 1 = −1 byte thanks to [JayCe](https://codegolf.stackexchange.com/users/80010/jayce)* *−4 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)* [Answer] # Java - 168 A simple nested loop, there's nothing really special going on here. ``` class C{public static void main(String[]a){int b=-1,c=a[0].length()-1,d;for(;b++<c;)for(d=-1;d++<c;)System.out.print((b==d|b==c-d?a[0].charAt(d):" ")+(c==d?"\n":""));}} ``` With line breaks: ``` class C{ public static void main(String[]a){ int b=-1,c=a[0].length()-1,d; for(;b++<c;) for(d=-1;d++<c;) System.out.print( (b==d|b==c-d?a[0].charAt(d):" ")+ (c==d?"\n":"")); } } ``` [Answer] # Ruby, 64 ``` f=->w{x=w.size x.times{|i|y=" "*x y[i],y[~i]=w[i],w[~i] puts y}} ``` ## Explanation * Input is taken as the argument to a lambda. It expects a `String`. * In a loop that loops trough every character in the word (`n` in total): + Create a String consisting of `n` spaces. + Replace the `i`th and `n-i`th (`~i`, thanks xnor) space with the `i`th and `n-i`th character of the input. + Print the line [Answer] # JavaScript (E6) 101 ~~95 129 136~~ **Edit** Wrong letter spacing. Fixed. **Edit** Simpler and shorter using classic for loops As a function, output via popup. ``` F=a=>{ for(l=a.length+1,i=s=o='';++i<l;s='\n') for(j=0;++j<l;) o+=s+((s=' ')+a)[j==i|i+j==l&&j] alert(o) } ``` *Previous version* using .map ``` F=a=>alert([...a].map((c,p)=> --q<p ?B(q)+a[q]+B(p-q-1)+c :B(p)+c+(p-q?B(q-p-1)+a[q]:'') ,B=n=>' '.repeat(n),q=a.length).join('\n')) ``` **Test** In FireFox/FireBug console ``` F('Java-Script') ``` *Output* ``` J t a p v i a r - c S - c a r v i a p J t ``` [Answer] # Befunge-93, ~~68~~ 71 ``` :~:84*-!#@#v_\:2*\4+p1+ ::+\4+g:!| >$1+0:>p1-:: 00+4\*2:\<>0p#:- ^#2g ``` You can test it [here](http://www.bedroomlan.org/tools/befunge-93-playground). It'll come up with an input dialog box on each pass through `~`; enter your word one character at a time (it does say the input is 'klunky' after all), ending with a space. It won't print to the console; this wouldn't be Befunge without a hint of self-modification, after all! Instead it will modify its own grid to display the message. After it's done, the grid will look something like this: ``` ~:84*-!#@#v_\:2*\4+p1+ ::+\4+g:!| >$1+0:>p1-:: 00+4\*2:\<>0p#:- ^#2g c f o l d o e g - e g d o o l c f ``` (Note the noble sacrifice of the cell at (0,0), after we know the pointer won't go there anymore, for the purpose of storing a piece of data.) It also works with inputs of even length. Note that, since Befunge-93 is limited to an 80x25 grid, the input size is limited to 21 characters if you run it in a Befunge-93 interpreter. Running it as Befunge-98 should remove this limit. *Edit* - Now it works more along the lines of the intended output, at the expense of only three characters of length. [Answer] # Javascript 102 84 85 *Edit: Had to fix spacing. Not so small anymore.* ``` function p(s){for(i in s){o='';for(n in s)o+=(n==i?s[n]:n==s.length-1-i?s[n]:' ')+' ';console.log(o)}} p('Thanks-Dennis') T s h i a n n n k e s D - s D k e n n a n h i T s ``` [Answer] ## CJam, ~~38~~ ~~36~~ ~~35~~ ~~34~~ 32 bytes ``` l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N} ``` [Test it here.](http://cjam.aditsu.net/) This reads the input word from STDIN. It also works for an even number of characters. This prints a trailing column of spaces, but I don't see anything in the rules against that. Explanation ``` l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N} l:I "Read input and store it in I."; , "Get string length."; ,_ "Turn into range and duplicate."; f{ } "Map block onto first range, with second range on the stack."; f{ } "Map block onto second range, with first iterator in stack. Each invocation of this block will start with grid coordinates y and x on the stack (x on top)."; _2$= "Duplicate x, duplicate y, check for equality."; @2$+ "Pull up y, duplucate x, add,"; I,(= "Check if that's one less than the string length."; | "Bitwise or between conditions."; \ "Swap condition and x."; I= "Take x'th character from the string."; S? "Push a space and select character depending on condition."; S "Push another space."; N "Push a line feed."; ``` The contents of the stack are printed automatically at the end of the program. [Answer] # C, 105 two slightly different ways of doing it. ``` c,i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;)putchar((c=v[1][i++])?i-1-j&&l-i-j?32:c:(i=0,j++,10));} i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;i++)putchar((l-i)?i-j&&l-i-j-1?32:v[1][i]:(i=-1,j++,10));} ``` If you want to add extra spaces, replace `putchar(` with `printf(" %c",` for an extra 5 characters. [Answer] ## J - 36 30 bytes: *Edit:* 6 characters shorter, credits go to [@algorithmshark](https://codegolf.stackexchange.com/users/5138/algorithmshark) . ``` (1j1#"1' '&,({~](*>.*&|.)=)#\) ``` eg: ``` (1j1#"1' '&,({~](*>.*&|.)=)#\) 'Code-Golf' C f o l d o e G - e G d o o l C f ``` Bonus: works with even length strings too: ``` (1j1#"1' '&,({~](*>.*&|.)=)#\) 'CodeGolf' C f o l d o e G e G d o o l C f ``` [Answer] # Prolog - 240 bytes ``` :-initialization m. +[]. +[H|T]:-(H=' ';!),+T. +[H|T]+I+X:-0=:=I,X=H;+T+(I-1)+X. +L+I+C+S:-L=:=I;S=[D|E],+C+I+B,+C+(L-I-1)+B,+B+2*I+D,+L+(I+1)+C+E,+B,writef('%s\n',[B]). -X:-get_char(C),(C='\n',X=[];X=[C|Y],-Y). m:- -X,length(X,L),+L+0+_+X. ``` Invocation: ``` $ echo "Code-Golf" | swipl -qf c.pl C f o l d o e G - e G d o o l C f ``` Readable: ``` :- initialization(main). vars_to_spaces([]). vars_to_spaces([' '|T]) :- vars_to_spaces(T). vars_to_spaces([_|T]) :- vars_to_spaces(T). get_index([Head|_], Index, Result) :- 0 =:= Index, Result = Head. get_index([_|Tail], Index, Result) :- get_index(Tail, Index-1, Result). print_loop(Length, Index, Board, String) :- Length =:= Index; String = [FirstChar|RestString], get_index(Board, Index, Line), get_index(Board, Length-Index-1, Line), get_index(Line, 2*Index, FirstChar), print_loop(Length, Index+1, Board, RestString), vars_to_spaces(Line), writef('%s\n', [Line]). get_line(Line) :- get_char(C), ( C = '\n', Line = []; Line = [C|More], get_line(More)). main :- get_line(String), length(String, Length), print_loop(Length, 0, _, String). ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` LḶḤ⁶ẋ;"µ»ṚY ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//TOG4tuG4pOKBtuG6izsiwrXCu@G5mln///9QUk9HUkFN "Jelly – Try It Online") [Answer] # Powershell, 78 bytes +8 bytes thanks @[streetster](https://codegolf.stackexchange.com/users/69200/streetster) ``` param($s)$s|% t*y|%{$r=,' '*$s.length;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '} ``` Explaned test script: ``` $f = { param($s) # declare a parameter $s stores a word $s|% t*y|%{ # split $s into chars https://codegolf.stackexchange.com/a/168174/80745 $r=,' '*$s.length # create an array of spaces with length equal length of the word $r[$i++]=$_ # set first char $r[-$i]=$s[-$i] # set last char $r-join' ' # join the array to string } } &$f PROGRAM '' &$f sword '' &$f uhm '' &$f o '' &$f codegolf # It works with word that contains even number of letters ``` # Powershell, 70 bytes (if a word can be represented by an array of chars) +8 bytes thanks @[streetster](https://codegolf.stackexchange.com/users/69200/streetster) ``` ($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '} ``` Test script: ``` $f = { ($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '} } &$f P R O G R A M '' &$f s w o r d '' &$f u h m '' &$f o '' &$f c o d e g o l f # It works with word that contains even number of letters ``` Output for both cases: ``` P M R A O R G O R R A P M s d w r o w r s d u m h u m o c f o l d o e g e g d o o l c f ``` [Answer] ## C# (~~214~~ 212) (Certainly badly) Golfed version: ``` using System;class A{static void Main(){char[]a,w=Console.ReadLine().ToCharArray();int l=w.Length,i=0;for(;i<l;i++){a=new string(' ',2*l-1).ToCharArray();a[2*i]=w[i];a[2*l-2*i-2]=w[l-i-1];Console.WriteLine(a);}}} ``` Ungolfed version: ``` using System; class A { static void Main() { char[] a, w = Console.ReadLine().ToCharArray(); int l = w.Length, i = 0; for (; i < l; i++) { a = new string(' ', 2 * l - 1).ToCharArray(); a[2 * i] = w[i]; a[2 * l - 2 * i - 2] = w[l - i - 1]; Console.WriteLine(a); } } } ``` Any hints, tips, tricks or remarks are very welcome, as this is my first attempt at CodeGolf. I just wanted to try it, even though I know my C# byte length won't even come close to double the best solutions ;) And how do you guys count your bytes? I just posted the above into a Quick Watch window and did `.Length`. I could write a small program to count bytes for me, but I bet there is an easier way that I don't yet know. [Answer] # JavaScript (ES6) - ~~185~~ ~~177~~ ~~175~~ 170 bytes ``` f=n=>{return s=' ',r='repeat',n=[...n],l=n.length,j=l/2-.5,[...h=n.slice(0,j).map((c,i)=>s[r](i)+c+s[r](l-2-(i*2))+' '+n[l-i-1]),s[r](j)+n[j],...h.reverse()].join('\n')} ``` Put this in the Firefox console and run as `f('PROGRAM')`: ``` P M R A O R G O R R A P M ``` `f("CODE-GOLF")`: ``` C F O L D O E G - E G D O O L C F ``` [Answer] # Mathematica, 149 bytes ``` FromCharacterCode@Flatten[Append[Riffle[#,32],10]&/@MapThread[Max,{#,Reverse@#,ConstantArray[32,Dimensions@#]},2]&@DiagonalMatrix@ToCharacterCode@#]& ``` Input passed as parameter to the function; function returns the output string. There is a trailing newline at the end of the output. Explanation: We create a diagonal matrix with the string, then we create a copy of it vertically flipped using `Reverse@#` to reverse the rows. Then we have a third matrix of the same dimensions containing only 32 (ascii space). We use `MapThread` to take the element-wise max of these 3 matrices. Finally, we `Riffle` spaces into each row, `Append` a newline at the end, and `Flatten` the result. [Answer] # Perl - 90 It might be possible to squeeze some more characters out of this: ``` ($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":" "for split//,($_ x y///c) ``` `89` + `1` for `-n`. Run with: ``` echo "program" | perl -nE'($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":" "for split//,($_ x y///c)' ``` Output: ``` p m r a o r g o r r a p m ``` [Answer] ## T-SQL: 180 Taking the input from variable @i ``` DECLARE @s VARCHAR(MAX)=REPLICATE(' ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A ``` This stuffs single characters in/decrementing from the start and end into a string of spaces. Test Result ``` DECLARE @i VARCHAR(MAX)='Super Large' DECLARE @s VARCHAR(MAX)=REPLICATE(' ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A S e u g p r e a r L r L e a p r u g S e ``` [Answer] # PowerShell ~~118~~ ~~102~~ 97 ``` ($x=[char[]]"$args")|%{$i++;$y=[char[]]" "*$x.Count;$y[$i-1]=$x[$i-1];$y[-$i]=$x[-$i];$y-join' '} ``` Outputs: ``` PS C:\PowerShell> .\cross.ps1 SWORD S D W R O W R S D ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` f=s=>[...s].map((_,i,a)=>a.map((c,j)=>j==i|j==s.length+~i?c:' ').join` `).join` ` ``` **EDIT**: -1 Thanks Joe King. I didn't see the TIO gives preformatted direct paste for CG. [Try it online!](https://tio.run/##LcdBCsIwEEDRvaco3TTBOAdQph5ExAxpWhNipmSK3RSvHgu6@fwX6U3iSpiXU@bB1zqiYH8DALnDi2alHiYY0tjTj87EHRExbHsEks/T8jx@wtWdu6bTEDlk29j/HGx1nIWTh8STGlW7chlcYZFW60v9Ag "JavaScript (Node.js) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â┤▼iS╙£≥»u5V╓ ``` [Run and debug it](https://staxlang.xyz/#p=83b41f6953d39cf2af753556d6&i=%22PROGRAM%22&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` { begin block for mapping characters of input ]i^) left-pad each character to length (i+1) where i is the index m map using block r reverse the array; this produces the southwest-northeast diagonal m map using the rest of the program, implicitly output result i iteration index xi@ get the i'th character of the original input, where i is the iteration & assign element to array at index 0\ join with spaces ``` [Run this one](https://staxlang.xyz/#c=%7B+++++%09begin+block+for+mapping+characters+of+input%0A++]i%5E%29%09left-pad+each+character+to+length+%28i%2B1%29+where+i+is+the+index%0Am+++++%09map+using+block%0Ar+++++%09reverse+the+array%3B+this+produces+the+southwest-northeast+diagonal%0Am+++++%09map+using+the+rest+of+the+program,+implicitly+output+result%0A++i+++%09iteration+index%0A++xi%40+%09get+the+i%27th+character+of+the+original+input,+where+i+is+the+iteration%0A++%26+++%09assign+element+to+array+at+index%0A++0%5C++%09join+with+spaces&i=%22PROGRAM%22&a=1&m=2) [Answer] # [R](https://www.r-project.org/), 88 bytes ``` n=ncol(m<-diag(u<-utf8ToInt(scan(,""))-32));diag(m[,n:1])=u;write(intToUtf8(m+32,T),1,n) ``` [Try it online!](https://tio.run/##K/r/P882Lzk/RyPXRjclMzFdo9RGt7QkzSIk3zOvRKM4OTFPQ0dJSVNT19hIU9MarCI3WifPyjBW07bUurwosyRVIzOvJCQ/FKhJI1fb2EgnRFPHUCdP839AkL97kKPvfwA "R – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` \:↶n * ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNDJXVGRjFBJXUyMUI2JXVGRjRFJTIwJXVGRjBB,i=UFJPR1JBTQ__,v=8) # Explanation ``` \ Create a diagonal with the input : Duplicate the diagonal ↶ Rotate left n Simple overlap * Insert spaces on every line ``` [Answer] # Zsh, ~~90~~ 82 bytes Kudos to @pxeger for saving 8 bytes. ``` for i ({1..$#1})(for z (${(s::)1}){((i==++j||j+i==$#1+1))||z=\ printf $z\ } echo) ``` [Attempt this Online](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3g9LyixQyFTSqDfX0VJQNazU1QAJVChoq1RrFVlaaQJFqDY1MW1tt7ayamixtIAuoTNtQU7Ompso2RoGroCgzryRNQaUqRqGWKzU5I18TYjLUgvXRSpHOHkH-vv7B_r6uSrFQYQA)   ~~[90 bytes](https://tio.run/##qyrO@J@moVn9Py2/SCFTQaPaUE9PRdmwVrMaJJCFLKChkWlrm1VTk6UNpIFC2oaammpqVbYq1YbRWbG1NTVVtjEKXAVFmXklaQoqVTEKtVypyRn5tf9rudIUIp09gvx9/YP9fV3/AwA)~~ ]
[Question] [ *EDIT (Jan 19, 2022, 18:00 UTC): This challenge is now over. The winner is [Citty](https://codegolf.stackexchange.com/users/75429/citty) with [this Pyth answer](https://codegolf.stackexchange.com/a/223147/58563). Congratulations!* --- This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge where each answer must take an integer \$N\$ as input and return the **1-indexed ID** of the answer which was written by the user whose ID is \$N\$. You may want to [sort by oldest](https://codegolf.stackexchange.com/questions/217748/which-answer-did-this-user-write?answertab=oldest#tab-top) to get the answers in the logical order. ## Rules 1. I will post the first answer. 2. You are only allowed to post one answer, so that a user ID is linked to one and only one answer ID. 3. You are only supposed to support user IDs that were used in the previous answers and your own user ID. (So your code may return anything or crash when given an unknown user ID.) 4. **The maximum code size is set to 50 bytes**. So the challenge will end when nobody is able to add a new ID without exceeding this size. 5. You may use any language, no matter which ones were used before. It is recommended to use verbose languages early in the chain, while they still have a chance to compete. 6. The last valid answer in the chain on January 19, 2022 at 18:00 UTC wins the challenge. Please include in your post the list of ID pairs, updated with your new entry: ``` [your_user_ID] -> [your_answer_ID] ``` Also make sure to include the ID of your answer in the header. ## Examples The first answer is written by user **Arnauld (58563)**: ### 1. JavaScript (ES6), 4 bytes ``` _=>1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1s7wf3J@XnF@TqpeTn66RpqGqYWpmbGm5n8A "JavaScript (Node.js) – Try It Online") Updated list: ``` 58563 -> 1 ``` This code returns **1** when given **58563** ([my user ID](https://codegolf.stackexchange.com/users/58563/arnauld)) ... or any other input. That's fine because **1** is the only possible output at this point (see rule #3). The second answer is written by user **JohnDoe (123456)** (who actually doesn't exist yet): ### 2. Python 2, 14 bytes ``` lambda n:2-n%2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPykg3T9Xof0FRZl6JQpqGoSYXjGmh@R8A "Python 2 – Try It Online") Updated list: ``` 58563 -> 1 123456 -> 2 ``` This code returns **1** when given **58563** or **2** when given **123456**. [Answer] # 7. [Julia](http://julialang.org/), 17 bytes works due to `Int64` overflowing to negative numbers ``` x->(x-8479)^6%5+5 ``` [Try it online!](https://tio.run/##DcZBCoMwEAXQ/T/FbARDUYxmMjOLeBFpoRvBEqSIQm4ffav3u/L29aWuqZZubkunQcx9YsMvrpkSLWDlOEGH0QcYi41Qs2mARh8EJspCMOXg8Qb@x7afee/bTH2aaX3iXL0B "Julia 1.0 – Try It Online") **Updated list:** ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 ``` **I found those numbers by guessing and brute-forcing :** ``` for i in Iterators.product(-9999:9999,1:20,1:20) d = diff(((L.+i[1]) .^ i[3]) .% i[2]) if all(==(-1), d) || all(==(1),d) println(i) println(((L.+i[1]) .^ i[3]) .% i[2]) break end end ``` [Try it online!](https://tio.run/##hY3BCoMwEETv@xV7KURqxaipieAHFPoHYsEahW0lljRCD/13G5WeeuiDHWaHgblNAzX8NbejeTo8Y4kVCCmOKcg44RkokasEpFJpDPLIsxxULkWOoKTIONRzP1okJIMn19nGjfYZPeyop9axg/IUi4S8SOJVAkCP9jua@p4xdo72VPE6wOiCVKWL2XmT1FuTemyGgZUlO/AgRB3g@/1NfKC31sLDknGDYfQb/V1ZuNquua9fZzT4m@cP "Julia 1.0 – Try It Online") [Answer] # 2. [Ruby](https://www.ruby-lang.org/), 11 bytes ``` ->x{1+~x%2} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166i2lC7rkLVqPZ/gUJatKmFqZlxLBeIaWFgZGgS@x8A "Ruby – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 ``` [Answer] # 1. JavaScript (ES6), 4 bytes ``` _=>1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1s7wf3J@XnF@TqpeTn66RpqGqYWpmbGm5n8A "JavaScript (Node.js) – Try It Online") Updated list: ``` 58563 -> 1 ``` [Answer] # 6. [Zsh](https://www.zsh.org/), ~~26~~ 25 bytes ``` a=80596 <<<$a[(i)${1[2]}] ``` [Try it online!](https://tio.run/##qyrO@J@moanB9T/R1sLA1NKMy8bGRiUxWiNTU6XaMNootjb2vyYXV5qCqYWpmTGQtjAwMjQB0pam5pZGIL6lpbEBiDYzNDEHiZtbmJr/BwA "Zsh – Try It Online") Boring. *-1 by @GammaFunction* Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 ``` [Answer] # 8. [J](http://jsoftware.com/), 46 bytes Last time this works, here to grab the boring answer! ``` 1+58563 80214 95792 89930 86147 97857 98541&i. ``` `95594` doesn't need to be included as J's index-of-operator `i.` returns the length of the array in the case the item was not found. But as it is 0-based, the index gets incremented `1+`. [Try it online!](https://tio.run/##jYu9DkAwFEZ3T/HF4CdoWnr1XmKSmEx2k2iweP@p@giGc5aT84RU5R7TgBw1NIZIozBv6xJMRUx9B9atsRBy0oJFOg3ujXUQxxTNZE12q1AmyXlcL4rRl6nGvv@@YyWx4QM "J – Try It Online") Update list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 ``` [Answer] # 9. [Perl 5](https://www.perl.org/) `-p`, ~~46~~, 37 bytes ``` $_=(a74a298635=~/./g)[$_%26%20%12]||1 ``` [Try it online!](https://tio.run/##DcmxCsJADADQPd/RAx20l1xySYZ@iUi5QUQo9lDH4qcbu7zl9dtrkYhhng5NuZFbLTJ9x/N4P16GOVFNlBPSddswQkxqAcuEDC7qBOZeMlhFVnA12TVh3FecQbOy/Nb@eazPd5za0v8 "Perl 5 – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 ``` Explanation: ``` $_=$_%26%20%12 gives 58563 -> 11 80214 -> 4 95792 -> 8 89930 -> 2 86147 -> 9 97857 -> 7 98541 -> 1 95594 -> 6 70745 -> 5 (a74a298635=~/./g) because shorter than (a,7,4,a,2,9,8,6,3,5) ``` [Answer] # 13. [Python 3](https://docs.python.org/3/), 45 bytes ``` lambda n:ord('ehlkacfbdgimj'[n%209%80%13])-96 ``` [Try it online!](https://tio.run/##LY7NboMwEITvPMVekG0JJBv/o5IXSXIgYAJNMJEhhwrRV6cm6l5mv9WsZl4/Sz95vnfVZX/W462twZdTaDFy/fNRN92tvQ/jNzr7tKA2NTRl/Epyq/ahnaECLI1UPANDCyYysFLbIpK1nEZRTOh41EYeYqRgh0Xa6NRUC5mBkIrFdyuoUpGEZuYgw0jS9K55uHCEoMu70KJBGXw2xhFJuimAy8DD4MH59@hCvTgcW5EygThHuw578oFXGPyCO7T68iQ3yE@wzuVXscH6n3LOf11VzdcNkf0P "Python 3 – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 ``` [Answer] # 15. [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes This is based on the Chinese remainder theorem. Since all divisors need to be pairwise coprime, we use the `n`th prime for each user id `n`. ``` •3hy₁Ω=”Ó6™≠ò“êS’>₄?Θ¢9?Âγ”J4 %œ~ª‰fÃα•IØ% ``` [Try it online!](https://tio.run/##DYwtDgIxEEavgsGN6Gyn7VTAarBIgoAEAgqBwpCyYNAYSCAh61jFzw22we4h5iJLzZeXvJdvvZnOVvO2lVDq5VaKffPsSbjHs5VjKadH/Ei4xWok4dqX4pg3l7r0eSyab6qG1On@zru6kvBaxEPzTi@DeOm27diwsRpYZUjgjfMZsPdaAVskB96xScuGMFnjCZxyZICMRQ2elLVA5JATM4JjzDRYwgwnfw "05AB1E – Try It Online") `•3hy...fÃα•` is the large compressed integer `1369130535064223821413376960561972089702936948491908270885271972462351716275011314738309`. `I` pushes the input, `Ø` takes the n-th prime and `%` takes the large compressed integer modulo the prime number. The big constant is generated with the [ChineseRemainder](https://reference.wolfram.com/language/ref/ChineseRemainder.html) builtin from the Wolfram Language: [Try it online!](https://tio.run/##DY6xCsMwDET3foX3arBsyZYLhUJ/oGQNGUxjGg/xkHgr/XZXy/HgHtztuW9lz72@8xh1Pc3tbr4sHDyIdUiQOCYHkpK3IAEpQorCmsKE2nIiiDYSA3FAD4lsCEAUUZQFIQo6D4HQ4e/yOmrr5mGeW23lLJNO17aWY55y@5QZeQGjzq5orkb/LMsYfw "Wolfram Language (Mathematica) – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 ``` --- By using the closest prime to `n/349` instead of the `n`th prime this can be golfed to 24 bytes: ``` •1RMζ)šÙ&KxγŸÏäí•IƵù/Ån% ``` [Try it online!](https://tio.run/##DcktCkJBFEDh1SgIF5w7c3@XIA@LVQwKBosGi9FiNht9WE2iaB6e8S3CjYxTDge@3X652qxL@R1bnE3716i75suwOfSP7p3P@ZbvVSbfZ/6M82k7KGXOxpLAQkQCZ/UI5p4CmCApuBrXGhNWZSfQoMRALJjAKYgAkaLVNwQ1jAmEMOLiDw "05AB1E – Try It Online") ``` •1R...äí• # compressed integer 5437583563235532232480395276083021 I # push the input Ƶù/ # divide by 349 Ån # find the nearest prime % # modulo the large integer with the prime ``` [Answer] # 20. [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` I⁺²⌕⪪”)¶q⁹1&¡⍘DλK⟦l∧NHz¿”²…⮌S² ``` [Try it online!](https://tio.run/##Fc3RCoMgFIDhV4mujuDAc1IrdikMdhfrCcTJEsTCLNjTu/Vff/C7xWa32ljrlEMqYOxeYIrHDsSbR0hvmLcYCrQSaRRdL3uFUo5Kdqj1gDh0hKS0wFGTItHyhhhvzNdFb5Z1g5c/fd49PNN2lLn8Hx9g7FJX91qx14Lq7Yw/ "Charcoal – Try It Online") Link is to verbose version of code. Works by taking the last two digits of the user ID and looking it up in a table generated by splitting a compressed string into pairs of characters. (Taking the first two digits doesn't work because there are several repeats.) A few variants are possible by spending an extra byte or two on the table which are offset by the saving from not having to offset the resulting index. Unfortunately there are overlaps between adjacent user IDs which means that the string has to be split into pairs of characters to find the index accurately, although one byte of this is offset by not having to halve the resulting index. Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 52210 -> 17 91569 -> 18 3852 -> 19 17602 -> 20 ``` [Answer] # 3. [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ``` 4|∘⍎3⊃⍕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/1R2wSTmkcdMx719hk/6mp@1DsVKKhgamFqZsyVrmBhYGRoAqQtTc0tjQA "APL (Dyalog Unicode) – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 ``` Explanation: ``` 4|∘⍎3⊃⍕ ⍕ ⍝ Convert to string 3⊃ ⍝ Pick the third digit (5, 2, or 7) ⍎ ⍝ Execute (make the digit a number again) 4| ⍝ Mod 4 ``` [Answer] # 12. [C (gcc)](https://gcc.gnu.org/), 50 bytes ``` int f(int n){return"DJHABILFCGKE"[n%60%50%12]-64;} ``` [Try it online!](https://tio.run/##RY1da8IwFIbv@ytCJdCAHUnNyQcOYZvVTb2zd@qFNK0GtmzUFgrib@/qRuPNgYf3Pe@Tx6c87zrralRG9@vItSrqpnLhfPX@8vqxWbwt12m4c1hQDBSz5BALPr11I@vyz8YU6PlSG/v9dJ4FI1OU1hUoS7dZ1BL0U/WLZRRig@IZwmbvwjFqx72pJSS4276O1kXkGvx9gAIxIdN/UDRhfAANUic@0XpCPQjGpa9JBQ9QwNljALRfk1RyGICDYF6qORXCJ1wy1cOt@wU "C (gcc) – Try It Online") This code could be golfable. But this question is not taged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). So let's leave it warning free. ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 ``` [Answer] # 21. [Pyth](https://github.com/isaacg1/pyth), 49 50 bytes `(answer ID & 753) % 38` happens to be unique for every answer so I just use that to make a lookup table. ``` C@" \r          "%.&753Q38 ``` The string in python repr format: `' \r\x14\x01\x02\t\x04\x06 \n \x05\x0b\x0f\x13 \x08 \x10 \x12\x0c \x03 \x11 \x0e \x07'` Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 52210 -> 17 91569 -> 18 3852 -> 19 17602 -> 20 75429 -> 21 ``` +1 byte because Python doesn't like carriage returns on their own apparently [Try it online!](https://tio.run/##K6gsyfj/39lBSSGmSISRiZOFTQEEuBRYufmFFTgUFAQUhHgUmBUEFRT4FNiVVPXUzE2NA40t/v@3NLEwBAA "Pyth – Try It Online") [Answer] # 17. [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L196), ~~41~~ 40 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ☼+░╞╪2<W48R087`9H4957V6984♂Y☻5405]y2/├=) ``` [Try it online.](https://tio.run/##DYo9DoFBFAD7dxNR2Pf2/Sb0agVRSGhQEI1G6wYSn3wScQBX4DR7kbXNZJKZ4@a8350O21pL/xuWx61079J9aLxgnyW3dUw5xOYazuV5XZb@K5xkdaFRub8mg1rFRTN4ImRoZxB4RE7gimwQ5tLowtiqBIMlYwEWxQzBSRWYDb25I5gjZVBGQmAUFRAiTH8) Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 52210 -> 17 ``` **Explanation:** ``` ☼+ # Add 100000 to the (implicit) input-integer ░ # Convert it to a string ╞ # Remove the first digit (the 1) # (the `☼+░╞` is used to convert the input 9481 to "09481", # and at the same time convert any other input-integer to a string) ╪ # Rotate it once towards the right 2< # Leave only the first two characters W48R087`9H4957V6984♂Y☻5405 # Push the following integers to the stack # (where ` duplicates the top two items, thus 8,7): # 35,4,8,29,0,8,7,8,7,9,19,4,9,5,7,34,6,9,8,4,10,37,16,5,4,0,5 ]y # Wrap the stack in a list, and join it together 2/ # Split it into parts of size 2 ├ # Pop the left item from the list, and push it to the stack # (which is the value we calculated at first) = # Get its 0-based index in the list ) # And increase it by 1 to make it a 1-based index # (after which the entire stack is output implicitly as result) ``` [Answer] # 4. [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 16 bytes ``` n=>2-n%2+n%100%7 ``` [Try it online!](https://tio.run/##LY/BasMwDIbP9VPoEkhYsiZOszZkyWWw0waDHXooPRjXyQStDZZbKCXPntnedBB86PuRJKmQxqrlSqgn@L6TU5eOybMggi9rJisu8GArcsKhhJvBE3wK1Ck56wOHIwg7URYU1M4jngh6eDS75qXOYVfyapND22xb7qlt63Lu2Gq9hihAMUAVMYoBecQYCFj/TUMw4IbBf71ftXz1K3PwbYAR@kX3Ay90wp90UpVlsl06NvrXhPyB1EuAXg33xWvfjCZzVs97i059oFbpmGKWdWye5@UX "C# (.NET Core) – Try It Online") ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 ``` Lucky coincidence that * All IDs except the first are even * Last 2 digits of the first 2 IDs are divisible by 7 * Last 2 digits of the second 2 IDs are 1 and 2 mod 7 respectively [Answer] # 5. [Zsh](https://www.zsh.org/), 25 bytes ``` <<<$[$1&7?(4+${1:4})%6:3] ``` [Try it online!](https://tio.run/##qyrO@J@moanB9d/GxkYlWsVQzdxew0RbpdrQyqRWU9XMyjj2vyYXV5qCqYWpmTGQtjAwMjQB0pam5pZGIL6lpbEBiDYzNDH/DwA "Zsh – Try It Online") `(4 + ${1:4}) % 6` works for every ID but 95792. But, 95792 is the only ID divisible by 8, so a ternary with `$1 % 8` as the condition works. ``` 58563 -> 3 ? (4 + 3) % 6 : 3 -> 7 % 6 -> 1 80214 -> 6 ? (4 + 4) % 6 : 3 -> 8 % 6 -> 2 95792 -> 0 ? (4 + 2) % 6 : 3 -> 3 89930 -> 2 ? (4 + 0) % 6 : 3 -> 4 % 6 -> 4 86147 -> 3 ? (4 + 7) % 6 : 3 -> 11 % 6 -> 5 ``` The more boring **24 byte** answer, based off of [@pxeger's](https://codegolf.stackexchange.com/a/217759/86147) ``` a=8059 <<<$a[(i)${1[2]}] ``` [Answer] # 18. [05AB1E](https://github.com/Adriandmen/05AB1E), 45 bytes ``` •1ααāš®‚wA%|ʒη¦%áY攀…FKΘćRɱnG’*AÂÉζ•5ôíÌskÌ ``` [Try it online!](https://tio.run/##FYqxagJBEED7@QoRbCSBnb2Z3ZlGsTGFXbqUCaQIgVgIimCx2ohglSoRLLSwSgIHIelvTZNiP2J/5HJpHg/eG09u7x7u68V03m@3Lnutdn9e53DEVKbyvPw5VB857GaDzuL3OX1Xp0483KSvHPZ59ZbDaThKL@f1ddxU5dNVDq/dQVzFzf9w5PgZ3@N28hi39UXNwq4AMRYJlL1aENXCgDgkD@qFGwoTNpWVwBtPDMQOC1AyzgGRR2lcELygLcARWgRCdgxsLRrQxvUP "05AB1E – Try It Online") ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 52210 -> 17 91569 -> 18 ``` The compressed number is each user ID minus 2, reversed, and joined together (except `9481` which is changed into `97490`, and `58563` which is not included). `5ô` splits it, `εR}` reverses it, `sk` returns the index of the input in the list, and `Ì` adds 2. [Answer] # 14. [Stax](https://github.com/tomtheisen/stax), 48 bytes ``` "&,R>&N_QbmO.%:VUVh5m@x~|LVju(bWJij<$"%98542|EI^ ``` [Run and debug it](https://staxlang.xyz/#c=%22%26,R%3E%26N_QbmO.%25%3AVUVh5m%40x%7E%7CLVju%28bWJij%3C%24%22%2598542%7CEI%5E&i=58563%0A80214%0A95792%0A89930%0A86147%0A97857%0A98541%0A95594%0A70745%0A45613%0A94066%0A44718%0A+9481%0A78123&a=1&m=2) You thought the time for trivial solutions was over? Fool! Well, maybe not entirely trivial. But the nontrivial part was generated by Stax's array literal generator. The only thing I added is the `I^`, which means "find the index of the input number in the array and increment it". The code could be packed, but this is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 ``` [Answer] # 16. [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 47 bytes Not creative... just a basic mapping. Constants came from experimentation ``` x=>" +$Q2('%OINFA;4@0".IndexOf((char)(x%49+35)) ``` [Try it online!](https://tio.run/##NZJRb4IwEMef9VNczMwgolJsSxun2bLExGSbW/awh2UPBFCbKCSAm4vhs7ve0fFQ8vtfOX5HSetxWlb59VSbYgfvv3WTH@f99JDUNbxW5a5KjnDp9@omaUwK36XJ4Dkxhedj2vtOKjBZDQso8p/PL8p6Qgk5C0CFEeMBaBHryJLWszAArCvJeGwLsRJ4U4Iz3CY07@pxGHMRABeS2Taah1Ja4jFTAZY1V3Y/xIpFtiw5iyxyJqTAcju3y3QKJAHjJbCOyQY56pi0kGeujn7I3DFKIgu3H22RpWPURo7/@1l/ZNUxDYGsO6ZpyCd0D@BcFDhDmpACpwg4KQXOkUamwEnS8BQ4S/oMFMg@uKu3OhXpnSmaAOyyhC0srufFcgCjm7fIux1u1i@rhzm/DweTdZHl583W89J9Uvneecj1aCZ8/4ofdWt/kyTdg9cdum2GR@/jkTyWRV0e8slHZZr8yRS5N7iEgWjR5MLagX1zFsDWM5nv21Ztv73@AQ "C# (.NET Core) – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 ``` [Answer] # 10. [Python 3](https://docs.python.org/3/), 44 bytes ``` lambda x:'973.84.612..5a'[int(x[0]+x[4])%15] ``` [Try it online!](https://tio.run/##FYvNCoMwEITvfYpcikohJGY32Qh9kjSHlGIr1B@iFH36bbwMwzffLMf2mSfDw7jMeRPrsV76@4O/aXy@kti7yjsjCaTVrZSYqjBMW70HFW97gNhcNUbu5yxSfothOv@y1F/QXezEkk@7rwtpGmYktIZJtRrYo/Mtk/dGMVkNjr0jLEkIuqzogZ1ygAxotfkD "Python 3 – Try It Online") Input is taken as a decimal string and returned as a hexadecimal string Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 (displayed as `a` in this case) ``` ## Explanation Takes the first and last digits, mod 15 and indexes into a string lookup table. This approach won't work for too much longer, but could probably be stretched to 20 or so in a language with more flexible string->int conversion, like Javascript, PHP, or Perl. [Answer] # 11. [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` •γ¤š×Pγ…þiðþ– çô&`)½c©2è•5ôsk> ``` [Try it online!](https://tio.run/##AUMAvP9vc2FiaWX//@KAos6zwqTFocOXUM6z4oCmw75pw7DDvuKAkwrDp8O0JmApwr1jwqkyw6jigKI1w7Rzaz7//zk0MDY2 "05AB1E – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 ``` --- ``` •...•5ôsk> # trimmed program k # get 0... > # plus 1... k # -based index of... s # implicit input... k # in... •...• # 5856380214957928993086147978579854195594707454561394066... ô # split in pieces of... 5 # literal # implicit output ``` [Answer] # 19. [Befunge-93](https://github.com/catseye/Befunge-93), 45 bytes ``` "0$>K"&\%\%\%\%1g\-.@ /1C274=B8?A5>:/@;3</96 ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X8lAUsXOW0ktRhUCDdNjdPUcuPQNnY3MTWydLOwdTe2s9B2sjW30Lc3@/ze2MDUCAA "Befunge-93 – Try It Online") Updated list: ``` 58563 -> 1 80214 -> 2 95792 -> 3 89930 -> 4 86147 -> 5 97857 -> 6 98541 -> 7 95594 -> 8 70745 -> 9 45613 -> 10 94066 -> 11 44718 -> 12 9481 -> 13 78123 -> 14 64121 -> 15 41565 -> 16 52210 -> 17 91569 -> 18 3852 -> 19 ``` There's a raw low-ASCII byte (decimal 25) between the `0` and the `$`. This computes `str[input%75%62%36%25] - '0'`, where `str` is the string on the second line of the program. ]
[Question] [ Jelly has an "untruth" atom: `Ṭ`. This takes a non-empty array of positive integers and returns a Boolean array with **1**s at the indexes in the input. For example: ``` [1,3,5,6]Ṭ ⁼ [1,0,1,0,1,1] [5]Ṭ ⁼ [0,0,0,0,1] [2,1,1,2]Ṭ ⁼ [1,1] [5,4,3]Ṭ ⁼ [0,0,1,1,1] [1]Ṭ ⁼ [1] ``` [Try it online!](https://tio.run/##y0rNyan8///hzjX/D7c/alpzdNLDnTP@/4821DHWMdUxi9VRiDYFEUY6hkBoBObrmOgYgxiGsQA "Jelly – Try It Online") Note that Jelly uses 1-indexing, and that duplicate values in the array have no effect. Your job is to take a non-empty array of positive integers and output the result of applying `Ṭ` on the array. If your language has a builtin with this exact behaviour, you may not use it. You may also choose to use zero indexing if you wish (so the above examples become `[0,2,4,5], [4], [1,0,0,1]` etc) and take non-negative integers in the input array. You may use your language’s `true` and `false` values instead of `1` and `0`, so long as they are the Boolean values rather than general truthy and falsey values (e.g. `0` and non-zero integers). You may also take input as a set if your language has that type. The input is not guaranteed to be sorted and may be in any order. The output may not have trailing zeros (or any other "trailing" values). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 3 bytes ``` ׯ⍸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn///D0Q@sf9e74n/aobcKj3r5HXc2H1hs/apv4qG9qcJAzkAzx8Az@n6ZgqGCsYKpgxpWmYArERkC@oYIRAA "APL (Dyalog Extended) – Try It Online") A tacit function. Banning only the *exact* built-in actually gives APL a massive advantage! ### How it works ``` ׯ⍸ ⍸ ⍝ Takes a vector v and gives another vector containing v[i] copies of i ⍝ for each index i ¯ ⍝ Inverse of the above, which counts occurrences of i which becomes v[i] × ⍝ Signum of each number, converting any positive count to 1 ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) ``` ⊢∊⍨∘⍳⌈/ (⍳⌈/)∊⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXokcdXY96VzzqmPGod/Ojng59Lg0oQxMk07Xof9qjtgmPevsedTUfWm/8qG3io76pwUHOQDLEwzP4f5qCoYKxgqmCGVeago4pkDACChgqGAEA "APL (Dyalog Unicode) – Try It Online") Non-Extended solution. Works exactly like the [3-byte Jelly solution](https://codegolf.stackexchange.com/a/216740/78410). # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) ``` ∨⌿-↑⍤0× ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHikc9@3UftU181LvE4PD0/2mP2iY86u171NV8aL0xSLhvanCQM5AM8fAM/p@mYKhgrGCqYMaVpqBjCiSMgAKGCkYA "APL (Dyalog Unicode) – Try It Online") A fun way to do the job. For each number `n`, create a length-`n` vector that has a 1 at the end and 0 for the rest. Then promote the entire array to a matrix (padding as necessary) and take the logical OR of the rows. [Answer] # [Python 3](https://docs.python.org/3/), ~~42~~ 41 bytes *-1 thanks to @ovs* ``` lambda a:[i+1in a for i in range(max(a))] ``` [Try it online!](https://tio.run/##DcYxDoAgDADAr3QskcWoi4kvQYcaQZtAJQSNvr560@W3Hqd0GqZZI6V1I6DRcdOyAEE4CzD8LSS7x0QPkjGL5sJSMaC/KSJLviqan7rB9rZbPg "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {~l,1}ᵐz₁⌉ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/qv@6ip8eHWCYc2VZcrKejaKSiV2z9q2/Coqenhrs5aoMT/6rocHUMQqwqo8lFPJ0jsf3S0oY6xjqmOWaxOtCkQG@kYAqFRbCwA "Brachylog – Try It Online") It's certainly interesting to consider what approach is the best in a language without a concept of a Boolean. 0-indexed. For some reason the unbound variables that are *pretty much* 0 are actually displaying as variables, so tack a `≜` onto the end if that's a problem. ``` { }ᵐ For each element of the input: ,1 append 1 to ~l something that long. z₁ Ragged zip. (i.e. non-cycling, doesn't stop until all lists are exhausted) ⌉ᵐ Take the maximum of each column. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` SparseArray[#->1^#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ggsag41bGoKLEyWlnXzjBOOVbtf0BRZl4JiKtRZJvmoKypo6Rgq6Ck45NZXOLgUBSrVhecnJhXV81VbahjrGOqY1arw1VtCiKMdAyB0AjM1zHRMQYxDGu5av8DAA "Wolfram Language (Mathematica) – Try It Online") Returns a `SparseArray`. [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` f a=map(`elem`a)[1..maximum a] ``` [Try it online!](https://tio.run/##XU7NisIwEL7nKeYgmMDYbfw7iNmbB2FPegwBpzS6YZtY2gpefZ99AcGX0Rfp9kcWcYZhYL6/@abyx2ZZXe@BlKec72xm/Y6EllHk6ez8yQOZ2pMLKj0y0JzQxcIsR7ywlJaLxaZZW70OlRHLwefBVl8uWAaZrSBRLScqQzoocwr8Qw31ULiYQV64UPEmEPbF0a/CyfPmA6FUgoSJYNAG1lriBGc4N/frLzwuN2gOMfYjDdOzDuirg2PsuwXHLQnHr9pOg1OcPHX/Gvk0lO@G0vwB "Haskell – Try It Online") The relevant function is `f`, which takes as input a list of integers `a` (1-indexed) and returns a list of `Bool`s. [Answer] # [Neim](https://github.com/okx-code/Neim), 5 bytes ``` 𝐠𝐈Γ₁𝕚 ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCQuAuOPc5EdNjR/mTp31/3@0oYKxgqmCWSwA "Neim – Try It Online") Explanation: ``` 𝐠 # Get Greatest element 𝐈 # Inclusive range: (0 .. n] Γ # For each element in range do: ₁ # 1st input line 𝕚 # Check that the int is in the list ``` [Answer] # [Factor](https://factorcode.org/), 35 bytes ``` [ 0 [ 2^ bitor ] reduce make-bits ] ``` [Try it online!](https://tio.run/##NY29CoNAEIR7n2JeIKImlYG0wcZGUomBy2aD4s@ZvbMQ8dnNYhK2mBlm2O9lyFvZbkWWX1O0LAN3cOwdeuNrde@JB@JvDB@NFqOw9/MozeBhRMzscA6yPIUjMZ7qYAmABQmOOGHd/V9jRHrxL0Wq61aqlkju0OdWUEH4ORErsOXDDqx0c9lJCLUn24/WMdhQDerYyPYB "Factor – Try It Online") Takes a sequence of 0-based indices and returns a virtual boolean sequence of `t` (true) and `f` (false). ### How it works ``` [ 0 [ 2^ bitor ] reduce ! Reduce all 2^n bitmasks by bitwise OR ! for each n in the sequence make-bits ! Create a virtual sequence of bits from the integer ] ``` [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 33 bytes ``` ->a,n=[0]*a.max{a.map{n[_1]=1};n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ8822iBWK1EvN7GiGkQWVNdk1uRFZ8baGtZa59X@L1BIi4420DHSMdExjY3lAnNNYAxDHQMgNIRxTYGKjGEcg9jY/wA "Ruby – Try It Online") Uses the 0-indexing. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes. [Answer] # [Java (JDK)](http://jdk.java.net/), 82 bytes ``` a->{int m=0,r[];for(int i:a)m=i>m?i:m;r=new int[m];for(int i:a)r[i-1]=1;return r;} ``` [Try it online!](https://tio.run/##bZBNboMwEIX3OcXIUiRoDQpp00UoqbrprqssEQuXQOQUGzQeUkURN@oFepyehJqfNKlSIWOP37z5xrMTe@HtNu@tVFWJBDsb@zXJwr8JJ1d3ea1TkqXuxLQQxsCrkBqOE4CqfitkCoYE2W1fyg0oqzlrQqm3cQICt8btUwFexjqPUlOc8P6/ghyiVnirow1BRTOOcRLmJTpdLJfCVZFcqSe5VCFGOvuAzqb@pmAsvSCJghAzqlEDhk0b9sieYdugzJCBaGwE4BjwO77gDw0/XSzOxzkP7De/0Pg9vzuHwXhsBobtBJy9wB6yHFDuL@kk2IlY/jOiOBifymFATqe4PmZVIdLMYcA4MObCLbDvr08WXtTAzNQF2RK5L6qqOAzW64z/OYN2TTr51wdDmfLLmvzKGih32NSbz7qRTc1U2@TxDfyMGc3NpFtN@wM "Java (JDK) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` v1i( ``` [Try it online!](https://tio.run/##y00syfn/v8wwU@P//2hDHWMdUx2zWAA) Or [verify all test cases](https://tio.run/##y00syfmf8L/MMFPjv0vI/2hDHWMdUx2zWK5oUyA20jEEQiMQT8dExxhIG8YCAA). ### Explanation ``` v % Concatenate stack contents vertically. Gives an empty array 1 % Push 1 i % Take input ( % Assignment indexing: write 1 into the array at the input positions. % This automatically extends the array and fills with 0 % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Ṁe€ ``` [Try it online!](https://tio.run/##y0rNyan8///hzobUR01r/h9uB5KR//9HG@oY65jqmMXqRJsCsZGOIRAaxQIA "Jelly – Try It Online") This does seem somewhat difficult to outdo. ``` € Map over (the range from 1 to) Ṁ the largest element of the input: e is it in the input? ``` Silly, 0-indexed bonus: # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` 2*BUo/ ``` [Try it online!](https://tio.run/##y0rNyan8/99Iyyk0X///o4aZh9sfNa2J/P8/2lDHWMdUxyxWJ9oUiI10DIHQKBYA "Jelly – Try It Online") ``` 2* For each element of the input, raise 2 to that power. B Convert to binary U and reverse each, / then reduce by o vectorizing logical OR. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` mo±€¹ḣ▲ ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//9tb8Kx4oKswrnhuKPilrL///9bMCwyLDQsNV0 "Husk – Try It Online") I feel like I'm missing a way to do this with `η`. ## Explanation ``` mo±€¹ḣ▲ ḣ▲ range 1..max(input) mo map each to €¹ whether it's present in the input(index if present, 0 if not) ± and take the sign of that ``` [Answer] # [Scala](https://www.scala-lang.org/), 19 bytes ``` i=>1 to i.max map i ``` [Try it online!](https://scastie.scala-lang.org/MgwzKES7QeG56E8pB0d5qg) Returns a `Seq` of `Boolean`s. Takes a `Set[Int]` as input, since sets are also predicates in Scala. If a list is taken as input, `i.contains` would have to be used instead. [Answer] # [J](http://jsoftware.com/), 12 bytes ``` e.~1 i.@+>./ ``` [Try it online!](https://tio.run/##DcZBCkBAGEDhvVO8LJgJP4OxMJFSVlauIMLGDVx9TK@v3uNjSU@GnpScij4ohHlbF3/IZ7hlykYpvY6Ijv16Ue7UiYwoQ4Olc1hHjQnV4WlpHEb7Hw "J – Try It Online") 0-indexed; similar to Bubbler's APL solution # [K (oK)](https://github.com/JohnEarnest/ok), ~~14~~ 12 bytes -2 bytes thanks to coltim ``` {~^x?!1+|/x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qui6uwl7RULtGv6L2f5q6hqGCsYKpgpm1ho6pprWRgiEQGlmbKpgoGAOFDDU1/wMA "K (oK) – Try It Online") 0-indexed [Answer] # [Octave](https://www.gnu.org/software/octave/), 17 bytes ``` @(x){y(x)=1,y}{2} ``` Anonymous function that takes a row (or column) vector as input and produces a row vector as output. Uses the last trick on [this list](https://codegolf.stackexchange.com/a/104753/36398) to effectively include several statements in an anonymous function. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzuhJI2BrqVNZWG9X@T9OINlQwVjBVMIvV5AJyTCGUkYIhEBpBxRRMFIwhTMNYzf8A) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 45 bytes 1-indexed, which felt weird to do in a 0-indexed language. Accepts only non-negative integers; negative indexing in powershell is 1-based, so this answer breaks down for negative cases. ``` $a=,0*($args|sort)[-1];$args|%{$a[$_-1]=1};$a ``` [Try it online!](https://tio.run/##hVBNT4NAEL3zKyabrYBdTKl6qSFprFVPPaiJB0IapGMlpYC7S6qh/HZcQFpMQ5w97Hy8ffP2pckOufjAKCrpexYHMkxiRwMVeUl9h43ODerztdiLhEvTtWzvpqkHOfVdulQNxy5Uryw0KlHImS9QgANTo2aZ5vVVRRinmaySamizMbs2DzP8SjGQuKpnxAYbRurYpEEUrJeml@Lfp2N2ya76nqvd1WlJNLP7uT0MIK/rRbZ9Q64MaHbQegED2iGjy4umq5K23YA5iiySCnJ2cB6mNbaZiywIUFRekl8sAQs/VdXykBr4ykOJ1mMiJBD3RamCjjYPCJyGtUgWuIvCGE8ZqGHo934YZRx1pj83InTTbfV4pke6DGDd@sFmzZMsXs2SKOGgCO58vnnClSKosgeOGP@hOFk7geMf@8UpbQTceevuwQiPMFdIHsZrbzKZb1P53V1GoDH06MpwqBXlDw "PowerShell – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~25~~ 21 bytes ``` x->1:max(x...).∈[x] ``` [Try it online!](https://tio.run/##bY5NCoNADIX3OUWQLkZIxdG2i4JexM5C6gyMWCs6hTmC@0JXPZ0XsY4/4KIJWSTve4@Ur0rn3I4KExztMeXXR26ZDYLAD4a@z6wYjexMN8kZZJxiOtNFYJLitIS0DBcE2VngUk4LaelZiRxC0eZaaDpRLHY033L4PsddBACoZ4tMU@mjrnF@CMAxSk@PKab9edNqPiRYwpqBTatrU9XMG75v9Ai1i1UrL6tO/iM/O5LQuxkmbSPvRhZ4KH1vNdcFTDP@AA "Julia 1.0 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~32~~ ~~25~~ 24 bytes ``` function(x)1:max(x)%in%x ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQtPQKjexAkirZuapVvxP00jWMNQx1jHVMdPU5ErTMAURyRpGOoZAaKQJ4ZnqmOgYg9mGmv8B "R – Try It Online") Taking advantage of `%in%` operator and abusing weird precedence. *-1 thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* ### 21 bytes using `scan` ``` 1:max(x<-scan())%in%x ``` [Try it online!](https://tio.run/##K/r/39AqN7FCo8JGtzg5MU9DU1M1M0@14r@hgrGCqYLZfwA "R – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~24~~ 23 bytes *Edit: -1 byte thanks to pajonk* ``` F[scan()]=1;F&!is.na(F) ``` [Try it online!](https://tio.run/##K/r/3y26ODkxT0Mz1tbQ2k1NMbNYLy9Rw03zv7GCmYL5fwA "R – Try It Online") A different approach to [pajonk's R answer](https://codegolf.stackexchange.com/a/216763/95126). Shorter at time of posting, but this is a precarious situation, as it would be longer in a fair 'apples-with-apples' comparison (using `scan()` for both approaches). [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~45~~ 44 bytes ``` a=>a.map(b=>c[b]=1,c=[])&&[...c].map(d=>d|0) ``` [Try it online!](https://tio.run/##dY4xDoMwDEX3niITSiQ3xJSOzkWiDCGBqhUlCKpOvXtKYQAhalte/P/zf7i3G/1w71/nLoY6NZQcaSefrucVaW8qSwiejBVZZqSU3s63QDp8lEg@dmNsa9nGG2@4UVBACVcrBMtzZhgCU7BuZPa0c5Q/7VKzQ8E6B3IENTVuHxxB4QLFAt5A8V8GtcswSdIX "JavaScript (Node.js) – Try It Online") This implementation uses zero indexing and returns an array of `0`s and `1`s. I think the code isn't very difficult to understand. Here's a summary explanation: * `c=[]`: create the output array. * `a.map(b=>c[b]=1 )`: for each value of the input array, set 1 at the respective index in the output array. * `[...c].map(d=>d|0)`: convert the output array into a non-sparse array, then map each element to a 32-bit integer. This will map `1` to `1` and `undefined` to `0`. Thanks to [Neil](https://codegolf.stackexchange.com/users/17602) for -1 byte. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes ``` ZLå ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/yufw0v//o410DIHQKBYA) Yes it is just a port of every other answer. ## Explained ``` ZLå ZL # Push the range: [1, max(input)] å # Vectorise: is item in input? over that range ``` [Answer] ## x86\_64 (zero indexed, length given), 19 16 bytes Raw machine code: ``` 31 c0 57 f3 aa 5f 89 d1 8d c6 04 07 01 e2 f9 c3 ``` Uncommented assembly: ``` .intel_syntax noprefix .globl untruth untruth: xor eax, eax push rdi rep stosb byte ptr [rdi] pop rdi mov ecx, edx .Lloop: lodsd dword ptr [rsi] mov byte ptr [rdi + rax], 1 loop .Lloop .Lend: ret ``` ### Explanation I'm not too good at x86, so I am pretty sure there is a better way to do this. C signature: ``` // System V ABI (rdi, rsi, rdx, rcx) void untruth(bool *out, const uint32_t *indices, uint32_t indices_len, uint32_t out_len); ``` It's my function, I can order the parameters however I please. 😏 First: `memset(out, 0, out_len)` using `rep stosb`. Since we need to save the pointer and `stosb` clobbers it, we `push` and `pop` it. The standard calling conventions say that the direction flag is always cleared when calling, so we know this will be a forwards operation. ``` untruth: xor eax, eax push rdi rep stosb byte ptr [rdi] pop rdi ``` Using the fancy `loop` instruction, loop through each index in the array, storing 1 to `out[index]` ``` mov ecx, edx .Lloop: lodsd dword ptr [rsi] mov byte ptr [rdi + rax], 1 loop .Lloop ``` At the end of the loop, return. ``` .Lend: ret ``` Note: It also happens to be x86-compatible on the binary level. Thanks to Neil for the -3 bytes (using lodsd)! ## x86\_64 (zero indexed, calculates max), 28 bytes Raw machine code: ``` 31 c0 57 51 af 0f 42 47 fc e2 f9 91 56 56 5f f3 aa 5f 59 5e ad c6 04 07 01 e2 f9 c3 ``` Assembly: ``` .intel_syntax noprefix .globl untruth # void untruth(const uint32_t *indices{rdi}, char *out{rsi}, uint32_t indices_len{rcx}) untruth: xor eax, eax push rdi push rcx .Lfind_max: scasd eax, dword ptr [rdi] cmovb eax, dword ptr [rdi - 4] loop .Lfind_max .Lfind_max.end: xchg ecx, eax push rsi push rsi pop rdi rep stos byte ptr [rdi], al pop rdi pop rcx pop rsi .Lloop: lodsd eax, dword ptr [rsi] mov byte ptr [rdi + rax], 1 loop .Lloop .Lloop_end: ret ``` This version will check for the maximum itself, *but the output buffer provided must be large enough.* Probably many things here can be optimized. ## Explanation Note that the parameters are different than the first: `indices` is in `rdi`, `out` is in `rsi`, `rdx` is unused, and `indices_len` is in `rcx`. I don't know why `scasd` uses `rdi` but whatever. This is a simple max loop. It compares each dword in `indices`, and sets `eax` to the maximum. This seems to be smaller than doing something with `lodsd`, although that 4 byte `cmovb` is pretty yucky. ``` untruth: xor eax, eax push rdi push rcx .Lfind_max: scasd eax, dword ptr [rdi] cmovb eax, dword ptr [rdi - 4] loop .Lfind_max ``` Since we know `ecx` will be zero due to the loop condition, we can set `ecx` to the maximum *and* set `eax` to zero in one byte. ``` .Lfind_max.end: xchg ecx, eax ``` Unfortunately, our output array is in `rsi`, not `rdi`. We `push` and `pop` twice to mov without the `REX` tax and save a copy, then do a `memset` with `rep stosb`. ``` push rsi push rsi pop rdi rep stos byte ptr [rdi], al pop rdi ``` Now we need to get `indices` and `indices_len` from the stack. Note that this time, we put `indices` into `rsi`. ``` pop rcx pop rsi ``` For each dword in indices, `out[indices[i]]` to 1 using `lodsd` and `loop` ``` .Lloop: lodsd eax, dword ptr [rsi] mov byte ptr [rdi + rax], 1 loop .Lloop ``` Return. ``` .Lloop_end: ret ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 49 bytes ``` a=>Enumerable.Range(1,a.Max()).Select(a.Contains) ``` [Try it online!](https://tio.run/##pY49C8IwFEX3/opHpwSegSh16cciCkpddHBOQyyB@gJNioL422NE0F250@UeDlf7mfY2bibSVWt9qCyFBmG7puliRtUNpuqcG5oGzgmBGqKqm@8oDop6wyQqsVc3xrk4msHowJRYOQrKkuexzLJUvEv4abTBtJYM82G01Iuds8RyzPGlZ2Su8HnBONxBIiwQCoQlPDjn5e@m4l@BxHmKfGviEw "C# (Visual C# Interactive Compiler) – Try It Online") Saved 3 bytes thanks to caird Saved 1 byte thanks to didymus Saved 2 bytes thanks to NonlinearFruit [Answer] # [Nim](http://nim-lang.org/), 60 58 bytes ``` func t[S](n:S):S= for i in 1..n.max:result.add int i in n ``` [Try it online!](https://tio.run/##y8vM/f8/rTQvWaEkOjhWI88qWNMq2JZLIS2/SCFTITNPwVBPL08vN7HCqii1uDSnRC8xJQUoXAKRzPufmpyRr@AQbaijYKyjYKqjYBarV8IFFTRFYhvpKBiCkRGyAh0FE6BGJBFDIPs/AA "Nim – Try It Online") [Answer] # [Uiua](https://uiua.org), 4 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` >0⍘⊚ ``` [Try it!](https://uiua.org/pad?src=ZiDihpAgPjDijZjiipoKCmYgWzAgMiA0IDVdCmYgWzRdCmYgWzEgMCAwIDFdCmYgWzQgMyAyXQpmIFswXQo=) 0-indexed ``` >0⍘⊚ ⍘⊚ # inverse where (occurrences) >0 # where is it greater than zero? ``` [Answer] # [Perl 5](https://www.perl.org/), `-pa` 33 bytes ``` @r[@F]=(1)x@F;map$_+=0,@r;$_="@r" ``` [Try it online!](https://tio.run/##K0gtyjH9/9@hKNrBLdZWw1CzwsHNOjexQCVe29ZAx6HIWiXeVsmhSOn/f0MFAyA0/JdfUJKZn1f8X9fXVM/A0OC/bmJBDgA "Perl 5 – Try It Online") `0` indexed. Input and output are space separated. [Answer] # JavaScript (ES6), 50 bytes ``` a=>a.map(g=(x,i)=>x&&g(--x,g,o[x]|=++i/i),o=[])&&o ``` [Try it online!](https://tio.run/##bY1BDoIwEEX3noJV04YpUBB35SJNFw1CU4MMAWO68O7VpjFGZSaz@Mmb9y/mbrZ@dcuNz3gewiiDkZ0prmahVlIPjsnOE2Ip5x4soPL6IfPclY4BSqUZIRh6nDechmJCS0eqBDTQwkkzlpVl9ooVpBP68IO2EUoT0QrS/oN1fIf649xxwRGa5Hu7xG6p@C4VOjwB "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map( // for each ... g = (x, i) => // ... value x at position i in a[]: x && // if x is not equal to 0: g( // do a recursive call: --x, // decrement x g, // force i to a non-numeric value o[x] |= // update o[x]: ++i / i // set it to 1 if i is numeric (≥ 0) // or just coerce it to a number otherwise // (i.e. undefined values are turned into 0's) ), // end of recursive call o = [] // start with o[] = empty array ) && o // end of map(); return o[] ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 9 bytes ``` L,dbMR$€e ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJyXJN0jlUdOa1P8qOYm5SSmJCoZ20YYKxgqmCmaxXP5cXEjCpugCRgqGQGgEFP4PAA "Add++ – Try It Online") Given that no-one besides me really uses Add++, I figured I wouldn't be sniping anyone ## How it works ``` L,dbMR$€e - Anonymous lambda function L, - Define the lambda function. Takes l as input d - Duplicate; STACK = [l l] bM - Maximum; STACK = [l max(l)] R - Range; STACK = [l [1 2 ... max(l)]] $ - Swap; STACK = [[1 2 ... max(l)] l] € - Over each: e - In l? ``` [Answer] # [Zsh](https://www.zsh.org/), 25 bytes ``` for x;a[x]=1 <<<${a/#%/0} ``` [Try it online!](https://tio.run/##qyrO@P9w5xoNTY3/aflFChXWidEVsbaGXDY2NirVifrKqvoGtf81ubiAahQMFYwVTBXMwGxTMGkEFDNUMIKIKJgoGEPU/QcA "Zsh – Try It Online") The `#` and `%` in globs act like the regex `^` and `$` anchors, but for full words instead of lines. Altenatively, `<<<${a:///0}` works. --- [Very similar Zsh solution to another question](https://codegolf.stackexchange.com/a/194813/86147) [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` rÔõ!øU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ctT1IfhV&footer=bSsw&input=WzEsMyw1LDZdCi1R) ``` ÍÌÆøXÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zczG%2bFjE&footer=bSsw&input=WzEsMyw1LDZdCi1R) ]
[Question] [ # Backstory Meet my friend Jimmy: ``` /o\ ``` Jimmy is a little character who likes to stand on platforms. Here's Jimmy safely standing on a platform: ``` /o\ ------------- ``` Now, Jimmy has a good sense of balance, so he can safely stand with one leg off of the platform, like so: ``` /o\ ------------------- ``` Although if he stands with two or more body parts off of the platform, he will fall. Both of these are examples where Jimmy will fall: ``` /o\ /o\ ---------- ---------------------- ``` # The challenge Your challenge is to write a program to determine, given a string with Jimmy's platform and position, if Jimmy can stand on the platform without falling off. * Input: Two lines showing Jimmy's position and the position of the platform under him. This can be from two separate inputs, a single input, or an array of some sort. 1. You may take input through any reasonable form, includings functions and standard input. Only resort to hard-coding if your language does not support the other input methods. * Output: The boolean values true and false, or the integers 1 or 0 to represent true/false respectively. 1. The boolean value is based off of whether Jimmy can stay on the platform or not - true if Jimmy can stay on the platform, or false if he will fall off. * The platform size is arbitrary and can be changed at will. Your program should account for that. 1. The platform cannot be a length of zero, and the platform must be complete (no holes in the platform). 2. Remember that Jimmy falls off when two of his body parts are hanging off the platform. A body part is one ASCII character of his body. 3. Trailing whitespace at the end of the platform is not required, but your program should account for both situations, where there is whitespace after the platform and where there is not. * Be mindful of the [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/) that are forbidden. # Test cases ``` /o\ ✔️ TRUE ------------- /o\ ✔️ TRUE ---------- /o\ ❌ FALSE ------------------ /o\ ❌ FALSE ------- /o\ ❌ FALSE - ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` n⁶Sċ2Ẓ ``` [Try it online!](https://tio.run/##y0rNyan8/z/vUeO24CPdRg93Tfr//3@0un5@TIy6joK6gq56LAA "Jelly – Try It Online") Explanation: ``` n⁶Sċ2Ẓ args: z (e.g. [['/', 'o', '\\'], [' ', '-']] => 0) implicit return value: z ([['/', 'o', '\\'], [' ', '-']]) n⁶ dyad-nilad pair ([[1, 1, 1], [0, 1]]) ⁶ 4th command-line argument or space [4th CLA assumed absent] (' ') n vectorized inequality ([[1, 1, 1], [0, 1]]) S reduction by addition with base case 0 ([1, 2, 1]) ċ2 dyad-nilad pair (1) 2 literal (2) ċ number of occurrences of right in left (1) Ẓ primality (0) ``` [Answer] # JavaScript (ES6), 38 bytes Takes input as `(a)(b)`. Returns \$0\$ or \$1\$. ``` a=>b=>b[a.search`o`]=='-'&/--/.test(b) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i4JiKIT9YpTE4uSMxLyE2JtbdV11dX0dXX19UpSi0s0kjT/J@fnFefnpOrl5KdrpHEpKGgoKcCAfn5MjAICKGlCpXWRAZKsJhemYWhmYBiGaRAew7AZBLIAu8tgphJnGNyh6IZhuJsSw/BoR/EIEOhCLPsPAA "JavaScript (Node.js) – Try It Online") ### How? We look for the position of the middle part `"o"` of Jimmy's body in the first string and test wether there's a dash in the second string at the same position. ``` b[a.search`o`] == '-' ``` The only case where Jimmy would be unsafe in this situation is with a single-dash platform: ``` /o\ - ``` So we additionally make sure that the platform has a width of at least \$2\$: ``` /--/.test(b) ``` --- # JavaScript (ES6), 36 bytes Alternate version if we assume that there's always either dashes or spaces below Jimmy (i.e. the input is rectangular). ``` a=>b=>b[a.search`o`]!=0&/--/.test(b) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i4JiKIT9YpTE4uSMxLyE2IVbQ3U9HV19fVKUotLNJI0/yfn5xXn56Tq5eSna6RxKShoKCnAgH5@TIwCAihpQqV1kQGSrCYXpmFoZmAYhmkQHsOwGQSyALvLYKYSZxjcoeiGYbgbl2EoLgECXYjq/wA "JavaScript (Node.js) – Try It Online") Takes advantage of the fact that the coercion to a numeric value is \$0\$ for a space and *NaN* for a dash. [Answer] ## Python 3, ~~88~~ 43 bytes Input is given in the form of a list containing two strings: the first string is the first line; the second string is the second line. ``` lambda a:sum(1-(" "in i)for i in zip(*a))>1 ``` [Try it online!](https://tio.run/##bY5BCsIwEEX3PcWnqxkxSHBX0ItYFxENHWiTUFNELx8LVoyat5lZvD/zwz123m2TxQ5t6s1wOhuY5joNpBXVqMVB2PoRgnl9SKCVYd7rdOukv0A3CKO4SJYO4sIUidfLPDInvNn4Ft9UgMqp/pXMzbyS8Mr@niz6@ZtPoCqXXKQZ9QQ) Another version, tying for 43 bytes (I haven't been able to get it shorter than 43): ``` lambda a,b:b[a.find("/"):][:3].count("-")>1 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIVEnySopOlEvLTMvRUNJX0nTKjbayjhWLzm/NK9EQ0lXSdPO8H95RmZOqoKhlUJBUSZQNE0jM6@gtERDUwdKa2r@V4AB/fwYBVTApaCgiwy4MJUgqUVSh00BRC@6kVjVI1uD0MCF3ZFQRUCgCwA) Down by 42 bytes thanks to a tip from Jo King. Old Version: ``` lambda s:sum((s.split("\n")[1]+" "*len(s))[i]=="-"and s[i]!=" "for i in range(len(s)))>1 ``` -2 bytes thanks to Sriotchilism O'Zaic. This works by taking two separate inputs, then pairing up corresponding letters. It counts the number of pairs where neither character is a space, then returns True if that number is greater than 1. [Answer] # Excel, ~~67~~ ~~45~~ 44 bytes ``` =(MID(A2,FIND("o",A1),1)="-")*(TRIM(A2)>"-") ``` Put Jimmy in `A1`, on a platform in `A2`. 2 conditions checked: * Is Jimmy's torso (`o`) on the platform? * Is the platform more than just `-`? [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ 37 bytes ``` lambda j,p:'--'in p[j.find('/'):][:3] ``` [Try it online!](https://tio.run/##fYxBCsMgEEXX8RSzG4WaQLsTss0lYhYJVmpIjUQ3Pb0VjNCA9O2G99@4T3jt9h51L@M2vxc1w3pzAjlHY8GNa6uNVRQ7ZGIaxWOK6qlhoJ4J0rjD2ACeNCmBHnzr3WYCRWmRFatpkuUiZKCICIVul5IA8F@SZ3mWbc1Ahdqv/9m1uM5Ol8gifgE "Python 2 – Try It Online") 5 bytes thx to [negative seven](https://codegolf.stackexchange.com/users/86422/negative-seven) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes ``` {?/''B|Bq/}o&[~^] ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2l5fnUndqcapUL82Xy26Li72vzVXWn6RQk5mXmqxXlF@SX6RhpGmQjWXAhAUJ1YqpGnUqMRrctX@V4AB/fwYBVQAVKyLDLgwlSCpRVKHTQFEL7qRWNUjW4PQwIXdkVBFQKALAA "Perl 6 – Try It Online") Takes a two parameters and returns a boolean of whether Jimmy will stay on the platform. This works by XORing the two lines together and checking if either part of Jimmy is still on the platform. ### Explanation: ``` &[~^] # String XOR operator { }o # Combined with the anonymous function ?/ / # That checks for the regex match ''B # Unprintable, B, which is "/o" ~^ "--" |Bq # Or B, q, which is "o\" ~^ "--" ``` [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` a#b=[1|(p,'-')<-zip a b,p>' ']>[1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTbasEajQEddV13TRrcqs0AhUSFJp8BOXUE91i7aMPZ/bmJmnm1BUWZeiYqSfn5MjJKykoKu0n8A "Haskell – Try It Online") I got this one by combining my below technique with [the other haskell answer](https://codegolf.stackexchange.com/a/187599/56656). # [Haskell](https://www.haskell.org/), 45 bytes ``` x#'-'|x/=' '=1 x#y=0 (((>1).sum).).zipWith(#) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0JZXVe9pkLfVl1B3daQq0K50taAK81WQ0PDzlBTr7g0V1NPU68qsyA8syRDQ1nzf25iZp5tQVFmXolKmpJ@fkyMkoKSgq7SfwA "Haskell – Try It Online") This counts the number of body parts (non-space characters) that are on top of the platform and then checks it is greater than 1. The reason we count body parts on the platform rather than body parts off is that `zipWith` will chop the top line to be the length of the bottom and thus can chop off Jimmy's body parts. This prevents us from having to do something like `cycle" "` to pad the list. [Answer] # [///](https://esolangs.org/wiki////), ~~85 93~~ 87 bytes ``` /~/\/\///\/o\\/(o)~ / ~ ~/ (o) /(o)~ (o)-/(o)~- -/--~(o) - ~/) ~/)-~/o~/(-/1~-~/(~/)~ ``` [Try it online!](https://tio.run/##JYmxCsBADEL3fEXGu0Gk/5OlQ6FDIcPt/nqaaxHlqes5132tKorRYjsjOHLKjSYTvYv/Swc@goOA9gMX5zbEFAd4qHH0Iq96AQ "/// – Try It Online") Output's a 1 if Jimmy is safe. Otherwise outputs nothing. (Unary 1 and 0.) Because there is no other way to take input in ///, it needs to be hard-coded: ``` /~/\/\///\/o\\/(o)~ / ~ ~/ (o) /(o)~ (o)-/(o)~- -/--~(o) - ~/) ~/)-~/o~/(-/1~-~/(~/)~ //<INPUT HERE> ``` For example: ``` /\/o\\/(o)// / // /// (o) /(o)// (o)-/(o)//- -/--//(o) - ///) ///)-///o///(-/1//-///(///)// /o\ ------------- ``` ([Try it online!](https://tio.run/##TU0xCsAwENrzCsdkEOl/snQodChkyP@5ek0LlTtR8bh57fM8ZoS6Ru@qo0koKsoR7PGGZi5JUKTSgHCtPeREw1upzaVUGfv0g1@UpfgHIm4 "/// – Try It Online")) Note the space after the `<INPUT HERE>`. **Explanation:** NOTE! The explanation code cannot be run due to the comments. The comments are enclosed in curly braces. Also, the original code uses a golf where `//` is replaced with `~`. This code is omitted from the explanation. ``` /\/o\\/(o)/ {replace Jimmy with a Jimmy with curvy arms, because slashes are hard to manipulate in this language} / / / {remove unneeded spaces after Jimmy, but before the floor} / // {get rid of the line break / (o) /(o)/ {remove all the spaces before both Jimmy and the floor} / (o)-/(o)/ {for each floor tile, remove it and one space before Jimmy. This detects whether Jimmy lines up with the floor.} {If Jimmy is before the floor, then there will be extra floor.} {If Jimmy is behind the floor, then there will be extra spaces before Jimmy.} /- -/--/ {Handle the case where there is a hole beneath Jimmy but he is still well-supported} /(o) - // {Handle the case where only Jimmy's head is on the floor. The space at the end of the code is necessary for this.} /) // {The rest of the substitutions clean up the result and handle each of the possible results that could exist at this point} /)-// /o// /(-/1/ /-// /(// /)// /o\ -- {there is a space right before this comment. The comment is only here to make the space visible and explain itself.} ``` --- * +8 bytes to fix a bug * -6 bytes by applying a standard `///` golf trick. [Answer] # [///](https://esolangs.org/wiki////), 57 bytes ``` /|/\/\///\/o\\/J| J/J*| /|* /| -/ | /|*-/|--/!|-/|*/|J| ``` [Try it online!](https://tio.run/##LYuhDcBADAP5T@HSSJH3yAwhBZUevFQQ6t3TgNo6@Yjr3LWf6qaYUw5vJkMIhmlRBgpwAhozp9x5adaoUAOYy4L/6Q8 "/// – Try It Online") Append the input to the end of the program in order to run. Returns the empty string if Jimmy falls off the platform, a string of exclamation points otherwise. * `/|/\/\//` replaces `|` with `//`, which makes the code both shorter and more readable (`|` is used to demarcate each replacement) * `/\/o\\/J| J/J*/` replaces Jimmy with `J` for brevity and changes the space to the left of him to `*` to the right of him * The next replacement gets rid of newlines. * `/* /| -/ | //` cancels out `*`s and with the space to the left of the platform. If there are two or more spaces left, Jimmy is falling off to the left, and the platform is deleted. This part also removes any whitespace to the right of the platform. * `/*-/|--/!/` cancels out `*`s and with length of the platform. If there are at least two `-` left, Jimmy isn't falling off to the right, so they are replaced with a `!`. * `/-/|*/|J//` deletes every remaining character that isn't `!` [Answer] # Dyalog APL Extended, ~~11~~ ~~10~~ 8 bytes ``` 2≤1⊥∧⌿⍤< ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3@hR5xLDR11LH3Usf9Sz/1HvEpv/aY/aJjzq7XvUN9XT/1FX86H1xo/aJgJ5wUHOQDLEwzP4f5oCUEhdQUE/P0ZBQV1BXRcC1LnQJRQUgMJAFlYJBewSCrh0AGVwGKWA0yhcEiA5dQA "APL (Dyalog Extended) – Try It Online") Explanation: ``` 2≤1⊥∧⌿⍤< a monadic train < Compare the input with the implicit prototype element - a space. Returns a boolean matrix of characters that are greater than 0x20 ∧⌿⍤ and-reduce that, i.e. places where both Jimmy and a platform is 1⊥ base 1 decode, aka sum - the amount of body parts over the platform 2≤ is that greater-or-equal to 2? ``` -2 thanks to Adám. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~6~~ 14 bytes ``` `^@╞^αmÆû-oñ╧╙ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z8hzuHR1Hlx5zbmHm47vFs3//DGR1OXP5o68/9/dQUY0M@PiQFS6kCooIsM1LnUoXIwAFKDIq@ABYD0YBqGQwe6YqgKuDAQwNwB5APl/wMA "MathGolf – Try It Online") 8 bytes had to be added to account for the edge case presented by Nick Kennedy. Checks if `"-o-"` is a substring of the zipped string of both lines, and the zipped string where the first input line has the first character removed. Takes input as two separate strings, with the only change being that the character is input as `/o\\`, since `\\` is the correct way to input a backslash in a string in MathGolf. ## Explanation ``` ` duplicate the top two items ^ zip top two elements on stack @ rrot3 ╞ discard from left of string/array ^ zip top two elements on stack α wrap last two elements in array mÆ explicit map using 5 operators û-oñ push "-o" and palindromize to make "-o-" ╧ pop a, b, a.contains(b) map block ends here ╙ max of list ``` [Answer] # [chevron](https://ch.superloach.xyz/?inp=&src=PiA-XmoKMD5eaQpeaSsxPj5eaQpeaixeaX5jPj5eaAotPisyPz9eaD0vCi0-LTMKPiA-XnEKXnF-cz4-XnMKLT4rNT9eaT5ecwpeX3A-XnMKXnFec15zLF5pLDN-Yz4-XnAKLT4rMj8_XnNec15zfl5zXnBecwo-PDEKPjww) - 126 bytes not an improvement over my old answer (at all), but rewritten after a rewrite of chevron itself. ``` > >^j 0>^i ^i+1>>^i ^j,^i~c>>^h ->+2??^h=/ ->-3 > >^q ^q~s>>^s ->+5?^i>^s ^_p>^s ^q^s^s,^i,3~c>>^p ->+2??^s^s^s~^s^p^s ><1 ><0 ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ζðм2ùgp ``` -1 byte thanks to *@Mr.Xcoder* with the approach of `ðм2ù`. Input as a list of two strings. Only works in the legacy version of 05AB1E, because `ζ` can transpose a list of strings as well as a 2D list of characters, whereas the `ζ` in the new 05AB1E version only works with the 2D list of characters. [Try it online](https://tio.run/##MzBNTDJM/V/z/9y2wxsu7DE6vDO94P9/BSxAPz@GS0FBFwMAAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9W@f/ctsMbLuwxOrwzveC/zv/oaCUFGNDPj4lR0gHydZGBUqxOtBJMCk1YAQvAbgpOPejKUa1Tio0FAA). **Explanation:** ``` ζ # Zip/transpose; swapping rows/columns, with space as default filler ðм # Remove all spaces from each string 2ù # Only leave strings of size 2 g # Count how many there are left p # Check if this is a prime (2 or 3) # (after which the result is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 28 bytes ``` ->a,b{!(/--/!~b[a=~/\//,3])} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laUUNfV1dfsS4pOtG2Tj9GX1/HOFaz9n@FrY1NBZcCDOjnx8QAebrIgAsiiCSggAVg04lVNapCLiQhINDlquCq0MvJzEst1ktNTM6IL87JTE7VMNKsrimqKSgtKVYo0kmL1iqKrf0PAA "Ruby – Try It Online") [Answer] # Excel, 36 bytes ``` =LEN(TRIM(MID(A2,FIND("/",A1),3)))>1 ``` Jimmy in `A1`, on a platform in `A2`. Finds the position of Jimmy, and takes the 3 bytes of the platform and trims off spaces. If the resulting platform length is long enough, Jimmy stands. [Answer] # EXCEL, ~~94~~ 71 bytes . ~~VBA (Excel), 87 bytes~~ `A1` = Jimmy , `A2` = platform -23 bytes. Thank you @Wernisch. ``` =(FIND("-",A2)-FIND("/",A1)<2)*(FIND("\",A1)-LEN(A2)<2)*(TRIM(A2)<>"-") ``` ~~?`[(FIND("-",A2)-FIND("/",A1)<2)*(FIND("\",A1)-LEN(A2)<2)]*(len(replace([A2]," ",""))>1)`~~ [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ¬εδ#& ``` [Try it online!](https://tio.run/##yygtzv6f6/aoqfH/oTXntp7boqz2////aA0lBRjQz4@JUdIB8nWRgZKmjoYSTApNWAELwG4KTj3oyuFq4BJAABSNBQA "Husk – Try It Online") This function takes the two lines as separate arguments. `δ#&` zips the two strings together and counts the number of pairs in which both characters are truthy, i.e., neither is a space character, and `¬ε` tests that the count is greater than 1. [Answer] # [R](https://www.r-project.org/), 35 bytes ``` function(x)sum(colSums(x!=" ")>1)>1 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrO4NFcjOT8nuDS3WKNC0VZJQUnTzhCI/qdpFCVl5qVoJGsAxXTgWB@I84E4JkZJUwcopwtko2OgGZqa/wE "R – Try It Online") Based on [@EriktheOutgolfer’s excellent Jelly answer](https://codegolf.stackexchange.com/a/187589/42248) so please upvote that one too! Input is a 2-d matrix of characters. [Answer] # Haskell, 59 bytes ``` f a b=sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']<2 ``` [Try it online!](https://tio.run/##hY/dCoJAEIXvfYrDImioSF67b9AbZODfqEvr@rddFL27qaGEBZ2LgTnfGWamSoYrSTmOBRKkXJIqdXW2W7c7PJcaeg/RIjFTx8numSQG5rYxSapj5jdRxNyOcwvWJQzGOhEKHHljYJI8IvRQkj4JRW8n2DuimGM@ByOVM@iK1Do@q@2F0jCxpGSw@fOipSE5EHrSt17BPowrx3TZxL1PGZu9A9/4L/8ZWKhnTI@8AA "Haskell – Try It Online") The function is called like so: `f "/o\\ " " -- "` How it works (for `f "/o\\" " -"`): `b++cycle" "` - Adds an infinite number of spaces after `b` to ensure that Jimmy is always above a `-` or (`" -"` → `" - ..."` `zip a$b++cycle" "` - Zips the two strings together (`[('/',' '), ('o','-'), ('\\',' ')]`) `(p,q)<-zip a$b++cycle` - For each pair in the zipped list `[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']` - Generates a list of `1`s, whose length is the number of pairs satisfying the conditions: `elem p"/o\\"` - The character in the top string is one of Jimmy's body parts. (Satisfied by all three pairs in this example) `q==' '` - The character in the bottom string is a space. (Satisfied by `('/', ' ')` and `('\\', ' ')`) So, the pair has to be one where one of Jimmy's body parts is above a space. Because in this example, two pairs satisfy both conditions, the list is `[1,1]` `sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']` - Take the sum of those `1`s (i.e. the length of the list), which in this example is `2`. `sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']<2` - Check if the number of body parts above a space is less than 2. In this example, it's not, so Jimmy will fall off. :( [Answer] # [C (gcc)](https://gcc.gnu.org/), 73 bytes ``` f(s,t,c)char*s,*t;{for(t=strchr(s,c=10);*s%5**t;)c-=*++t%2**s++%8;c=c<0;} ``` [Try it online!](https://tio.run/##lY1BCsIwEEX3nmIIBJJJilUQCjE3yaaM1HZhKkl2pWePAS2IBNG3Gua/P0PNlSjnQUSdNEka@4BRYzLLMAeRbEyBxlBSsodWGoz8hCWV1FhUKvEjYlSKd4YsnVuz5sknuPWTFxKWHcA9lMUgGL84zzSUCTb2s3POAzTvMClNtfayfzChQvXXX2c@LnytbW7hKa75AQ "C (gcc) – Try It Online") [Answer] # Kotlin, 60 bytes ``` fun String.c(b:String)=zip(b){i,j->i>' '&&j>' '}.count{it}>1 ``` Explanation: ``` fun String.c # Define an extension function on string, so we don't have to provide a first argument (and we also have string method calls for free) (b:String) # Pass the second string as argument = # Shorthand syntax for fun body zip(b) # Essentially a.zip(b). Creates a List<Pair> by joining both arrays. # Takes care of trailing whitespace, because it will be the size of the smaller array {i,j-> # Declare a transformer lambda as second function argument i>' '&&j>' '} # This essentially translates to: If i!=' ' and j=='-' .count{it} # Count the true values >1 ``` [Answer] # [Julia 1.0](http://julialang.org/), ~~42~~ 40 bytes ``` y(a,b)=strip(b[findfirst("/o\\",a)])>"-" ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v1IjUSdJ07a4pCizQCMpOi0zLyUts6i4RENJPz8mRkknUTNW005JVwmokEsBCJRABEgKxNaBC@mCgYISl6ZCjZ1CQVFmXklOHhd@PRBdJOiB2AFmouohbBGmpv8A) [Answer] # [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 13 bytes ``` j:<R>o<T>\-\- ``` SnakeEx does well because it's a 2D pattern-matching language, but not too well because it wasn't designed to be very golfy. [Try it here!](http://www.brianmacintosh.com/snakeex/) ### Explanation ``` j: Define the main snake, j (for Jimmy) <R> Pivot right (i.e. downward, since the snake starts out moving to the right) o Match Jimmy's torso (or is it his head?) and move down <T> Turn either left or right \-\- Match two platform characters ``` This will match if there are two platform characters under Jimmy, or fail to match if there are not. We don't need to consider the case where there are platforms only under his legs, since the platform cannot have holes. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` Õ·kèS Êz ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1bdr6FMgyno&input=Ii9vXAogLSI) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes ``` (.*¶). $1 ¶ ?-- ``` [Try it online!](https://tio.run/##K0otycxL/H9oG1c8V3y8NheQoaoRnBD/X0FDT@vQNk09LhVDoKCCva7u//8KMKCfH8OloKCLDLi4wILIAgpYABad2FWjKITIQoSAQBcA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` +`^ (.*¶). $1 ``` While there is still a space on the first line, and both lines still have more than one character, delete the space and the first character of the next line. Note: This assumes that there is no trailing space after Jimmy. +1 byte needed if trailing space needs to be allowed. ``` ¶ ?-- ``` Check that there are at least two pieces of platform under Jimmy. [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 42 bytes ``` /o/g;$_=(($_=<>)=~/./g)[-1+pos]eq'-'&&/--/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18/Xz/dWiXeVkMDSNjYadrW6evpp2tG6xpqF@QXx6YWquuqq6np6@rq//@voKCgnx@jAAJcQKyrq/svv6AkMz@v@L@ur6megaHBf92CHAA "Perl 5 – Try It Online") [Answer] # Ruby 2.5.3, 44 bytes ``` ->a,b{a.zip(b).map(&:join).grep(/\S-/).size>1} ``` Input taken as two arrays. Definitely not the most golf-friendly approach (see G B's answer), but I like any excuse to use the `zip` function. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~63..55~~ 53 bytes -1 byte thanks to mazzy ``` param($j,$f)''+($f|% t*y|?{$j[$i++]-gt32})-match'- -' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlS0clTVNdXVtDJa1GVaFEq7LGvlolK1olU1s7Vje9xNioVlM3N7EkOUNdV0FX/b9KFpdKGpe6OlctF5eaSpqCkgIM6OfHgDhKushACaIILKekgCGugAmgShV0MQCaWbiNIMEUZCf9BwA "PowerShell – Try It Online") Takes input as two lines. Unrolled: ``` param($j,$f) #Take $jimmy and $floor ''+ #Implicitly converts next part to string ($f |% ToCharArray #Convert $f to a char[] and... |?{ #Only take the chars where... $j[$i++]-gt32 #The same indexed char in $j's ASCII # is > ' ' i.e. only get /o\ } )-match'- -' #Arrays.ToString are joined with a space and we need 2 -'s ``` [Answer] # 40 column Commodore BASIC (C64, C16/+4, C128, PET, C64Mini) - non-competing`*` - 98 tokenized and BASIC bytes used ``` 0a=rN(.)*36:b=rN(.)*39:c=-rN(.)*(b-39):fOi=0tob:a$=a$+"-":nE:?tAa)"/o\ 1?tAc)a$:?-(a>c-2anda<c+b+2) ``` Here is the unobfuscated listing for explanation purposes ``` 0 let a=rnd(0) * 36 1 let b=rnd(0) * 39 2 let c=-rnd(0) * (b - 39) 3 for i=0 to b 4 let a$=a$+"-" 5 next i 6 print tab(a);"/o\" 7 print tab(c);a$ 8 print -(a>c - 2 and a<c + b + 2) ``` The variable `a` is used for positioning Jimmy (using `PRINT TAB(A)` which is zero-indexed). The varaible `b` is used for the length of the platform. And finally the variable `c` is used for the position of the platform. The loop in lines 3 through to 5 inclusive builds the platform for Jimmy, with line 6 printing Jimmy at his pre-determined position, and 7 for the pre-determined position of the platform. Finally, `1` or `0` is outputted to represent our `TRUE` or `FALSE` value. Note, the listing includes keyword abbreviations to ensure we break the 80 character limit per line on standard Commodore C64 BASIC. [![enter image description here](https://i.stack.imgur.com/Q2ZTp.png)](https://i.stack.imgur.com/Q2ZTp.png) `* Assumed non-competing because PETSCII is not ASCII. Jimmy looks better in PETSCII though, of course.` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~44~~ ~~40~~ 39 bytes *-4 bytes thanks to Jo King* ``` a=>b=>a.Zip(b,(x,y)=>x>y?y:0).Sum()>109 ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXroPMTsrPz7GzU0hTsP2faGuXZGuXqBeVWaCRpKNRoVOpaWtXYVdpX2lloKkXXJqroWlnaGD535qLK7wosyTVJzMvVSNNQ0kBBvTzY2KAlJImlwICgOR1kYGSpuZ/AA "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ Consider the following number sequence: > > \$ 0, \frac{1}{2}, \frac{1}{4}, \frac{3}{4}, \frac{1}{8}, \frac{3}{8}, \frac{5}{8}, \frac{7}{8}, \frac{1}{16}, \frac{3}{16}, \frac{5}{16}, \frac{7}{16}, \frac{9}{16}, \frac{11}{16}, \frac{13}{16}, \frac{15}{16}, \frac{1}{32}, \frac{3}{32}, \frac{5}{32}, \dots \$ > > > It enumerates all binary fractions in the unit interval \$ [0, 1) \$. (To make this challenge easier, the first element is optional: You may skip it and consider the sequence starts with 1/2.) ### Task Write a program (complete program or a function) which... Choose one of these behaviors: * Input n, output nth element of the sequence (0-indexed or 1-indexed); * Input n, output first n elements of the sequence; * Input nothing, output the infinite number sequence which you can take from one by one; ### Rule * Your program should at least support first 1000 items; * You may choose to output decimals, or fractions (built-in, integer pair, strings) as you like; + Input / Output as binary digits is not allowed in this question; * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest codes win; * Standard loopholes disallowed. ### Testcases ``` input output 1 1/2 0.5 2 1/4 0.25 3 3/4 0.75 4 1/8 0.125 10 5/16 0.3125 100 73/128 0.5703125 511 511/512 0.998046875 512 1/1024 0.0009765625 ``` These examples are based on 0-indexed sequence with the leading 0 included. You would need to adjust the input for fitting your solution. ### Read More * **[OEIS A006257](https://oeis.org/A006257)** + Josephus problem: \$ a\_{2n} = 2a\_n-1, a\_{2n+1} = 2a\_n+1 \$. (Formerly M2216) + 0, 1, 1, 3, 1, 3, 5, 7, 1, 3, 5, 7, 9, 11, 13, 15, 1, 3, 5, ... * **[OEIS A062383](https://oeis.org/A062383)** + \$ a\_0 = 1 \$: for \$ n>0 \$, \$ a\_n = 2^{\lfloor log\_2n+1 \rfloor} \$ or \$ a\_n = 2a\_{\lfloor \frac{n}{2} \rfloor} \$. + 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32, ... * > > [A006257](https://oeis.org/A006257)(n)/[A062383](https://oeis.org/A062383)(n) = (0, 0.1, 0.01, 0.11, 0.001, ...) enumerates all binary fractions in the unit interval [0, 1). - Fredrik Johansson, Aug 14 2006 > > > [Answer] # [Haskell](https://www.haskell.org/), 25 bytes ``` pred.until(<2)(/2).(+0.5) ``` [Try it online!](https://tio.run/##BcExDoAgDADAr3RwgBgrkrjJS9SBICgRSCP4fevdZevtU@JgNqbHH/iWFpNYtBSjlih6hbPkbGMBA/TE0qCDbAkCrBOiVjt/LiR7Vh4c0Q8 "Haskell – Try It Online") Outputs decimals, one-indexed without the initial zero term. Adds 0.5 to the input, then halves until the results is below 2, then subtracts 1. Using a pointfree expression saves 1 bytes over ``` f n=until(<2)(/2)(n+0.5)-1 ``` [Answer] # Java 10, ~~68~~ 64 bytes First try at code golf! Option 1: find the *n*-th element (1-indexed) -4 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` n->{int x=0;for(;n>>++x!=1;);return((~(1<<x)&n)*2.+1)/(1<<x+1);} ``` This is an anonymous method that finds the *n*-th term by removing the most significant bit from *n*, doubling it and adding one, then dividing by the next highest power of 2. [Try it online!](https://tio.run/##XZCxTsMwEIb3PsWRAdlYDYSBASd5A7p0RAwmcSuX9BLZlyqoCq8ezqkXWHw@@/f3/76TuZjtqf1ams6EAG/G4XUD4JCsP5jGwi62AG0/fnYWGsE3gFLz4bzhJZAh18AOECpYcFtfo2CqnvSh90JjXSs13VWFltpbGj0K8SOKspzkPcqH51wV8nHteaPnRUfmwFbMTOhL71o4cy6xJ@/w@P4BRt5CRYto59i70FxKKF64KpUEAGQDCbfmjYn/pl7RN0Wk4DBSerj/DmTPeT9SPrApiSz@L1OrRmWvkCXkf2GHAvM4pchKY5qXXw) Code walkthrough: ``` n->{ // builds anonymous function with input n int x=0; // stores floor of log(n) (base 2) for most significant digit for(;n>>++x!=1;); // calculates floor of log(n) by counting right shifts until 1 return((~(1<<x)&n) // removes most significant digit of n *2.+1) // multiplies 2 and adds 1 to get the odd numerator /(1<<x+1);} // divides by the next highest power of 2 and returns` ``` Will edit if it's necessary to print the final value instead of returning it. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes ``` ╫\╨] ``` [Try it online!](https://tio.run/##y00syUjPz0n7///R1NUxj6auiP3/39TQEAA "MathGolf – Try It Online") ## How it would look like with the operator working correctly ``` ╫\)╨] (")" adds 1 to TOS, making rounding behave as expected) ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z/70dTVQLwi9v9/U0NDAA "MathGolf – Try It Online") ## Explanation ``` ╫ Left-rotate all bits in input \ Swap top two elements on stack, pushing the input to the top ╨ Round up to nearest power of 2 ] Wrap in array (just for pretty printing) ``` I took my inspiration from [this question](https://codegolf.stackexchange.com/questions/83817/ninja-assassins-which-ninja-stays-alive) to solve the problem, my "own" solution was around 10-12 bytes I think. I had intended for the round up to closest power of 2 to return the number itself if it was a number of two, but due to a mistake it rounds to the next power of two (e.g. 4 -> 8 instead of 4 -> 4). This will have to be fixed later, but now it saves me one byte. [Answer] # Java 10, ~~89~~ ~~85~~ ~~70~~ ~~69~~ 68 bytes ``` v->{for(float j,t=2;;t*=2)for(j=1;j<t;j+=2)System.out.println(j/t);} ``` Port of [*@Emigma*'s 05AB1E answer](https://codegolf.stackexchange.com/a/172172/52210), so outputs decimals indefinitely as well. -15 bytes thanks to *@Arnauld*. [Try it online.](https://tio.run/##LY5BDoIwEEX3nGKWrQpGthVvIBsSN8ZFLWBaS0vo0MQQzl5bZTOTeZn8/xT3PFftOwjNnYMrl2bJAKTBbuq56KBOJ4C3sgVBbml5yiJbszgccpQCajBQQfD5ZentRHptOYI6YFUyhruqpImq6sTUGZnaR9B8HHZDYWcsxim2aUPUESlbA0u54/zUMXeL/5UPUY00GJ9f9wdw@vcyhSBm1npTWsMX) **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type for(float j,t=2;; // Loop `t` from 2 upwards indefinitely, t*=2) // doubling `t` after every iteration for(j=1;j<t; // Inner loop `j` in the range [1, `t`), j+=2) // in steps of 2 (so only the odd numbers) System.out.println( // Print with trailing new-line: j/t);} // `j` divided by `t` ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {($_+.5)/2**.msb-1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlXlvPVFPfSEtLL7c4Sdew9n9xYqVCGlBcUy8tt0RDXVXP0CBNXVMhLb9IwVBHwUhHwVhHwURHwdAAhIGEqaEhiDCy/g8A "Perl 6 – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 30 bytes ``` n->(n+.5)/n.highestOneBit(n)-1 ``` [Try it online!](https://tio.run/##NU7BSsNAEL3nK4ZCYNc0KxX0YNpCiwgexEO9SQ9rsptOTGaX3UmhSL89bq0ehjePefPe6/RRl13zNeHgXWDoElcjY6/sSDWjI3VTZXWvY4RXjfSdAfjxs8caImtOcHTYwJBOYscBqf3Ygw5tlHCRAry7J5f05vnPbvlCbFoT1mBhBROVa0GFupe3pA7YHkzkNzJbZEGyXEzVr4d1QSAxYPpYVAmWCR/SUhT/MQC7U2QzKDey8qkHWzGjVX7XPEIec5rNAedglfa@P23itZNAKa8J5@wy5@kH "Java (JDK 10) – Try It Online") Returns the nth item in the sequence. This answer is originally a succession of golfs of [TCFP's Java answer](https://codegolf.stackexchange.com/a/172204/16236). In the end, the golfs didn't look like the original answer anymore (though the math used is the same) so I decided to post the golfs as a separate answer instead of simply commenting on the TCFP's answer. So if you like this answer, go upvote [TCFP's answer](https://codegolf.stackexchange.com/a/172204/16236) as well! ;-) Intermediate golfs were: ``` n->{int x=0;for(;n>>++x!=1;);return((~(1<<x)&n)*2.+1)/(1<<x+1);} // 64 bytes (TCFP's answer when I started golfing) n->{int x=0;for(;n>>++x!=1;);x=1<<x;return((~x&n)*2.+1)/x/2;} // 61 bytes n->{int x=n.highestOneBit(n);return((~x&n)*2.+1)/x/2;} // 54 bytes n->{int x=n.highestOneBit(n);return((~x&n)+.5)/x;} // 50 bytes n->((n&~(n=n.highestOneBit(n)))+.5)/n // 37 bytes n->(n-(n=n.highestOneBit(n))+.5)/n // 34 bytes n->(n+.5)/n.highestOneBit(n)-1 // 30 bytes, current score ``` [Answer] # [Python 3](https://docs.python.org/3/), 33 bytes ``` lambda n:(8*n+4)/2**len(bin(n))-1 ``` [Try it online!](https://tio.run/##DcdBDkAwEAXQq8xypoi0LETiJFi0oTThk8bG6Ye3e/f77BcajcOkhz/D4gk9dwZFK7Uz5ljBIYEhUlm9c8JDPMb/FK9MoATKHtvKtnRWZtEP "Python 3 – Try It Online") Outputs decimals, one-indexed without the initial zero term. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes Saved 3 bytes thanks to *Kevin Cruijssen*. ``` ∞oDÅÉs/˜ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8fJfDrYc7i/VPz/n/HwA "05AB1E – Try It Online") **Explanation** ``` ∞ # start an infinite list [1... o # calculate 2**N D # duplicate ÅÉ # get a list of odd numbers up to 2**N s/ # divide each by 2**N ˜ # flatten ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Bṙ1Ḅ,æċ2$ ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//QuG5mTHhuIQsw6bEizIk/8OH4oKsR///cmFuZ2UoMTAwKQ "Jelly – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes ``` for($i=2;;$i*=2){1..$i|?{$_%2}|%{$_/$i}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl09bI2lolU8vWSLPaUE9PJbPGvlolXtWotkYVSOurZNbW/v8PAA "PowerShell – Try It Online") Outputs the infinite sequence as decimal values. Given language limitations, will eventually run into precision problems, but easily handles the first 1000 entries. Starts by setting `$i=2`, then enters a `for` loop. Each iteration, we construct a range from `1..$i` and pull out the odd values with `|?{$_%2}`. Those are fed into their own inner loop, where we divide each to get the decimal `|%{$_/$i}`. Those are left on the pipeline and output when the pipeline is flushed after every `for` iteration. Each iteration we're simply incrementing `$i` by `$i*=2` to get the next go-round. [Answer] ## Haskell, ~~35~~ 32 bytes Edit: -3 bytes thanks to @Delfad0r. ``` [(y,2^x)|x<-[1..],y<-[1,3..2^x]] ``` This is an infinite list of integer pairs. [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzP1qjUscorkKzpsJGN9pQTy9WpxLE0DHW0wMKx8b@z03MzFOwVSgoyswrUVBRKEnMTlUwMlBI@/8vOS0nMb34v25yQQEA "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` s=(1,2):[(i*2+u,j*2)|(i,j)<-s,u<-[-1,1]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v9hWw1DHSNMqWiNTy0i7VCdLy0izRiNTJ0vTRrdYp9RGN1rXUMcwNvZ/bmJmnoKtQm5igW@8QkFRZl6JgopCSWJ2qoKhgYFC8X8A "Haskell – Try It Online") Infinite sequence as pairs of integers (starting from `(1,2)`). Quite a bit longer than [@nimi's answer](https://codegolf.stackexchange.com/a/172176/82619), but the approach is completely different, so I decided to post it anyway. This solution is based on the following observation. Consider the infinite sequence $$ \left\{\frac{1}{2},\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$ and apply the following steps. * Replace every number \$\frac{i}{j}\$ in the sequence with the list \$\left\{\frac{2i-1}{2j},\frac{2i+1}{2j}\right\}\$: $$ \left\{\left\{\frac{1}{4},\frac{3}{4}\right\},\left\{\frac{1}{8},\frac{3}{8}\right\},\left\{\frac{5}{8},\frac{7}{8}\right\},\left\{\frac{1}{16},\frac{3}{16}\right\},\ldots\right\} $$ * Join all the lists into a single sequence: $$ \left\{\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$ * Add \$\frac{1}{2}\$ at the beginning of the sequence: $$ \left\{\frac{1}{2},\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$ Notice how you get back to the sequence you started with! The solution exploits this fact (together with Haskell's laziness) to compute the sequence `s`. [Answer] # [R](https://www.r-project.org/), ~~42~~ 41 bytes ``` function(n)2*c(y<-2^(log2(n)%/%1),n-y+.5) ``` [Try it online!](https://tio.run/##DYnRCsIwDAB/JWwMEu3UFnwZ/slQGLObhZmWLg769TVwD8ddroL7lNJW0A72Zury41lCZGRypxnLo3cv3OLqNHTXzpLhvpwvd6pE7WjcYJ/QQvbfeHiQj4cl5F00SYTVCwSF1Rs27wbSpLf@AQ "R – Try It Online") *-1 byte thanks to Robin Ryder* Returns a pair `Denominator,Numerator`. Uses the formula \$\begin{equation}N = 2\times\left(n-2^{\lfloor \log\_2(n)\rfloor}\right)+1\end{equation}\$ from the Josephus sequence and \$\begin{equation}D = 2^{\lfloor \log\_2(n)\rfloor+1}\end{equation}\$ from the other sequence. Happily we are able to re-use the denominator as the two formulas have quite a lot in common! [Answer] # Python 2 - ~~68~~ 66 bytes *-2 bytes thanks to Kevin* ``` from math import* def g(n):a=2**floor(log(n,2));print(n-a)*2+1,2*a ``` [Try it Online!](https://tio.run/##DcgxDoMwDADAnVd4tF0Y8AjiMZFKgiViR1aWvj7Njdd@/XGTMXJ4hZr6A1qbR@fle2coaHSkS5jz6x74@pxViM4Wah1tS8Ty2VfhNLIHKKhBJCs3ztzpWGAqqDT@) [Answer] # [Python 3](https://docs.python.org/3/), ~~53~~ 51 bytes * Saved two bytes thanks to [mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion); reusing default parameters to reset `n`. ``` def f(m=2,n=1):n<m and print(n/m)&f(m,2+n)or f(m+m) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI9fWSCfP1lDTKs8mVyExL0WhoCgzr0QjTz9XUw0oq2OknaeZXwRSqJ2r@T9NQ/M/AA "Python 3 – Try It Online") [Answer] # [Racket](https://racket-lang.org/), ~~92~~ 91 bytes ``` (define(f k(m 2)(n 1))(if(> k 0)(if(=(+ n 1)m)(f(- k 1)(+ m m))(f(- k 1)m(+ n 2)))(/ n m))) ``` [Try it online!](https://tio.run/##RcxLDsIwDATQq4zEAlsItU5bPgu4S4AERamjqmXD6YubDbvxG9uzf@bwWXejL2/MdWgefgkrvUJMJVBEJoVjKhBmSpHuyGhrutEBGytTpKOxsIlC@Q9adxwbNRasYvudlmn0X5D6CRF7aiFw6NBjwAlnXHCFGArEQTpIDxm20x8 "Racket – Try It Online") * Saved a byte thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) -- removing superfluous whitespace. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` BnWGEy-Q ``` [Try it online!](https://tio.run/##y00syfn/3ykv3N21Ujfw/39TQ0MA "MATL – Try It Online") Returns Numerator, then Denominator. Uses the same method as [my R answer](https://codegolf.stackexchange.com/a/172213/67312), although it's a bit more efficient. Explanation, with input `5`: ``` # implicit input 5 B # convert to array of bits # STACK: [[1 0 1]] n # length (place of Most Significant Bit) # STACK: [3] W # elementwise raise 2^x # STACK: [8] G # paste input # STACK: [8, 5] E # double # STACK: [8, 10] y # copy from below # STACK: [8, 10, 8] - # subtract # STACK: [8, 2] Q # increment # STACK: [8, 3] # implicit end of program, display stack contents ``` [Answer] # [Factor](https://factorcode.org/), 52 bytes ``` { 1/2 } [ dup stack. dup 1 v+n append 2 v/n t ] loop ``` [Try it online!](https://tio.run/##HckxCsJAEAXQq/w@kJCUegCxSSNWYjFsRpRsZsfZyUIInn1FuwfvQcGT1evlPJ4OmNmEIxbyZ1v4Nxlq7L6pvcSR@b2yBM441h19N@CDG6ZVkZ3C3P7ZozQCUmWZMKB0AscdMSWtITJZ/QI "Factor – Try It Online") Prints each fraction on its own line forever. Keeps track of the array of all terms with equal denominator. ``` { 1/2 } ! Push the initial array [ ... t ] loop ! Loop forever: dup stack. ! Print all fractions separated by a newline dup 1 v+n ! Copy and add 1 to all fractions append 2 v/n ! Join and halve all fractions ``` [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 426 bytes ``` ,.Ajax,.Ford,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:You be the sum ofyou a cat.Ford:You cat.Scene V:.Ford:Is twice you nicer I?If solet usScene X.You be twice you.Let usScene V.Scene X:.Ford:Remember twice you.You be the sum oftwice the remainder of the quotient betweenI you a cat.Open heart.You big big big big big cat.Speak thy.Recall.Open heart.You be twice the sum ofa cat a big big cat.Speak thy.Let usAct I. ``` [Try it online!](https://tio.run/##bZFNasMwEIWvMgcIOoA3IYsUBIVCAiElZKHIz4lbW3KlEUlO7@onxgV3IZifN9/MQ37oxnElNl/qsRJv1tUx1kyyEnsNgxSctg8Ew@fT1jAcJSkpU1NSn1NWfdpAFxDfQD70ZJtnLCjSijMy91NSkIeqVKUnvrcalNQmBo7kWjbkbQem4Iv6KCb6pBXvf9qHF/T4gu7Qo79E1CxfXFdaKXfoVWvqKLdNLvwEyy0MxwG@A0bSbOVjgKEblOOCbK@Ll00OUN8R9hQ7aNV1i7nJynxQ5sct/2OK3fwrYhx/AQ "Shakespeare Programming Language – Try It Online") Outputs the sequence infinitely as both numbers separated by a space, with each item being separated by a newline. [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` def f(n):m=2**len(bin(n))/4;return 2*n-m+1,m ``` [Try it online!](https://tio.run/##DcdBCoAgEAXQq8xSzQglCIoOU6Q1kL8YbNHpp97u3W89LkTVLWXKBnYsc3TuTDAr47/t@klSfQQUHdrSBF80X0JMDJIFezLBh8GOtzAqsc@GreoH "Python 2 – Try It Online") Function returns a tuple of (numerator, denominator). An input of 0 is not handled (it was optional). [Answer] # Excel ~~48~~ 28 Bytes Saved 20 bytes (!) thanks to tsh ``` =(A1+0.5)/2^INT(LOG(A1,2))-1 ``` ~~=MOD(A1+0.5,2^(INT(LOG(A1,2))))/2^INT(LOG(A1,2))~~ Assumes value in A1, output is in decimal. If you want the output to be in fraction, you can create a custom format for the output cell as "0/###0" and it will show it as fraction. **Explanation:** Difficult to explain, since there is a shortcut taken to get to this formula. Basically the numerator is a bit shift left of the input, and the denominator is the next power of 2 higher than the number input. I originally started with Excel built in functions for BITLSHIFT and BITRSHIFT, but they will shift the entire 48 bits which is not what you want. The functions DEC2BIN (and BIN2DEC) have a limit of -512 to 511 (10 bits) so this wouldn't work. Instead I had to rebuild the number with a modulus of the original number, then times two, then add 1 (since the left digit would always be 1 before a shift). ``` =MOD(A1 Use MOD for finding what the right digits are +0.5 this will later add the left "1" to the right digits ,2^INT(LOG(A1,2)))) Take Log base 2 number of digits on the right this creates the numerator divided by 2 (explained later) / 2^INT(LOG(A1,2)) The denominator should be 2^ (Log2 + 1) but instead of adding a 1 here, we cause the numerator to be divided by 2 instead This gives us a fraction. In the numerator, we also added .5 instead of 1 so that we wouldn't need to divide it in both the numerator and denominator Then tsh showed how I could take the int/log out of the mod and remove it from numerator/denominator. ``` Examples: [![enter image description here](https://i.stack.imgur.com/509Xa.png)](https://i.stack.imgur.com/509Xa.png) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes ``` 2^Mod[Log2[2#+1],1]-1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfKM43PyXaJz/dKNpIWdswVscwVtdQ7b9LfnRAUWZeSXSegq6dQlp0XmysjkJ1no6CIRAZGNTG/gcA "Wolfram Language (Mathematica) – Try It Online") [Answer] ## C++, ~~97~~ ~~75~~ 71 bytes -26 bytes thanks to tsh, ceilingcat, Zacharý ``` float f(int i){float d=2,n=1;while(--i)n=d-n==1?d*=2,1:n+2;return n/d;} ``` Testing code : ``` std::cout << "1\t:\t" << f(1) << '\n'; std::cout << "2\t:\t" << f(2) << '\n'; std::cout << "3\t:\t" << f(3) << '\n'; std::cout << "4\t:\t" << f(4) << '\n'; std::cout << "10\t:\t" << f(10) << '\n'; std::cout << "100\t:\t" << f(100) << '\n'; std::cout << "511\t:\t" << f(511) << '\n'; std::cout << "512\t:\t" << f(512) << '\n'; ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ṁz*İ1zR:1İ2ݽ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxiqtIxsMq4KsDI9sMDqy4dDe//8B "Husk – Try It Online") Abuses the built in sequences to the fullest. Outputs an infinite list. ## Explanation ``` ṁz*İ1zR:1İ2ݽ ݽ powers of ½ :1İ2 powers of 2, with 1 prepended zR zip replicate the second by the first z* then zip multiply that with: İ1 odd numbers ṁ map to each of the power arrays, and concatenate into single list ``` [Answer] # [Factor](https://factorcode.org/), ~~68~~ 66 bytes Saved 2 bytes thanks to @chunes ``` [ 1 2 [ 2dup / . [ 2 + ] dip 2dup > [ 2 * 1 swap ] when t ] loop ] ``` [Try it online!](https://tio.run/##JYyxCsJAEER/ZWqFiCkVbMXGRqyCxXFZTXDdW@82BL/@XGMzzLwZ5h6ipVyvl9P5uMOTshBDM5l9NI9iKPSeSCIVcIqBC17BhkWaHOThfF87bNGiQ9tPig2an8UaN/Sj/uFhQSvflTmoN/NAAnPDKXmufs31Cw "Factor – Try It Online") Outputs the sequence infinitely. ``` [ 1 2 ! First numerator and denominator [ ! Loop body 2dup / ! Divide to get next element of sequence . ! Print the element [ 2 + ] dip ! Add 2 to the numerator 2dup > ! If numerator > denominator [ 2 * ! Multiply denominator by 2 1 swap ! Set numerator to 1 ] when ! Functions like an if statement t ! Push true on the stack so the loop doesn't stop ] loop ! Run while top of stack is true (which is forever) ] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 63 bytes No input, prints infinite sequence: ``` f(i,j){for(i=1,j=2;;i+=2,i>j&&(j*=2,i=1))printf("%d/%d ",i,j);} ``` [Try it online!](https://tio.run/##FctLCoAwDADRvacIgpJoRey21Ct4BqlEUvyh7sSrG3U3PJhQjSGoMoqJdPG6o/jGRG@dk9JbI23Mc4zFn74h2nZZTsY0G@psgNT8m7v1Q5h7WZDgSgAYySW3PoGnfjy06uwL "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), 44 bytes Returns the \$n\$-th term, 1-indexed. ``` f=(n,p=q=1)=>n?f(n-1,p<q-2?p+2:!!(q*=2)):p/q ``` [Try it online!](https://tio.run/##DYwxDsIwDAB3XuFKDDZpoMlYavqVRqVBoMpOWsSCeHvIdDec7hU@YZ@3Z3pb0ftSSmSUNnFmR3yTMaJY16YhWz8m4/umwXxiT9SnSy5RNxRgcFcQGCq7rpoxdACYVXZdl/OqD5wCHr/yo5pOYKBOicof "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` 1.step{|i|(1..x=2**i).step(2){|j|p [j,x]}} ``` [Try it online!](https://tio.run/##KypNqvz/31CvuCS1oLoms0bDUE@vwtZISytTEyymYaRZXZNVU6AQnaVTEVtb@/8/AA "Ruby – Try It Online") Prints integer pairs infinitely, starting from 1/2. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes ``` f=(n,d=.5)=>d>n?n/d:f(n-d,d*2) ``` [Try it online!](https://tio.run/##JY5BDoIwFET3nGJ2bbVQW0ANpho3JibegLAglIqGtASM18cii5m8@ZNM/rv@1lMzvoZP7Lxp59lq6rjRSc702ZzdxQlTWOpiw81Gsdn6EbRvPygdR1fBW5RRKTmkUBWPSrVQtlDKka6ULbfjQnLHkQu5XzmEQyqk@le5DCPBRC7Vmv9TcqeyqmIR0Hg3@b5Nev@kxFKCLVwQYdCEI7zIVofW6HABGeppIihAbtf7g7DT/AM "JavaScript (Node.js) – Try It Online") 0-indexed. Started out as a port of my Batch answer but I was able to calculate in multiples of \$\frac{1}{2}\$ which saved several bytes. [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes ``` ->x{(2r*x+1)/2**x.bit_length-1} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iWsOoSKtC21BT30hLq0IvKbMkPic1L70kQ9ew9n@0oY6RjrGOiY6hARAZ6JgaGgKxUaxebmJBdU1FDVeBQnSFTlp0RWwsV@1/AA "Ruby – Try It Online") ]
[Question] [ Take a string of binary characters separated by a space, and convert it to an ASCII string. For example... ``` 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 ``` Would convert to... ``` Hello World ``` **This is a code-golf challenge so the shortest solution wins.** [Answer] # JavaScript (ES6) 49 ~~55 56 64~~ ``` s.replace(/\d+./g,x=>String.fromCharCode('0b'+x)) ``` **Edit** Accepting @bebe suggestion - thanks **Edit2** Didn't know about binary numeric literal - thanks @kapep **Edit3** Wow 6 ~~not 4~~ bytes saved thx @ETHproductions **Explanation** as requested in comments `String.replace` can take 2 arguments: * regular expression `/\d+./g` : one or more digits followed by one different character - the g flag specify to search the pattern more than once * a function, here specified in arrow format, where the argument (x) wil be the found string (the sequence of digits eventually followed by a space) and the value of the function is what is replaced (in this case, the single character from the code). It's worth noting that the at the end of the string the regexp matches the sequence of digits without a trailing space, in this case the dot matches the last digit. Try '123'.match(/(\d+)./) to verify. (Still) one of the more verbose pieces of javascript ever... (Assignment to string s not counted) ``` var s='1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100' var x= s.replace(/\d+./g,x=>String.fromCharCode('0b'+x)) console.log(x) ``` [Answer] # Ruby, ~~36~~ 32 ``` s.split.map{|x|x.to_i(2).chr}*"" ``` ## Or 31 ``` s.gsub(/\w+ ?/){$&.to_i(2).chr} ``` Optimizations thanks to Chron [Answer] # Bash+common linux utils, 25 bytes ``` dc<<<2i$s[Pz0\<m]dsmx|rev ``` ### dc explanation * push 2 to the stack; pop and use as input radix * push input string to stack (all values at once) * Define recursive macro `m` to: + pop, then print value as ASCII + push stack depth to stack + push 0 to stack + pop top 2 stack values; compare and call `m` macro if stack non-empty * duplicate top of stack (macro definition) * pop and save macro to `m` register * pop and execute macro Because we push the whole binary string to the stack first, when we pop each value, we end up with the string reversed. So we use the `rev` utility to correct that. ### Example usage: ``` $ s="1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100" $ dc<<<2i$s[Pz0\<m]dsmx|rev Hello World $ ``` [Answer] ## PowerShell, 49 ``` -join(-split$s|%{[char][convert]::toint32($_,2)}) ``` EDIT: Didn't see the other PowerShell answer. But there is essentially only one way of solving this. [Answer] # C - ~~57~~ ~~43~~ 38/31 38 Byte version: ``` for(int*x=s;putchar(strtol(x,&x,2));); ``` Or only 31 bytes if s is a pointer: ``` while(putchar(strtol(s,&s,2))); ``` I don't think this is exactly how for and while loop are supposed to be used... but it works. [Answer] ## Mathematica, 52 bytes Ah, Mathematica's lovely function names ``` f=FromCharacterCode[#~FromDigits~2&/@StringSplit@#]& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 ``` smCv+"0b"dPZ ``` Note that s is not a legal variable in Pyth, so I used Z instead. Explanation: ``` print( s sum( m map(lambda d: C chr( v eval( +"0b"d "0b"+d)), P split( Z Z)))) ``` Example: ``` =Z"<the binary string from above>"smCv+"0b"dPZ Hello World ``` [Answer] ## x86 machine code on DOS - 22 bytes ``` 00000000 30 d2 b4 08 cd 21 2c 30 72 06 d0 e2 08 c2 eb f2 |0....!,0r.......| 00000010 b4 02 cd 21 eb ea |...!..| ``` Since there are no real string variables in machine code (and in particular, no variables named "`s`") I settled for stdin as input. NASM input: ``` org 100h section .text start: xor dl,dl loop: mov ah,8 int 21h sub al,'0' jb print shl dl,1 or dl,al jmp loop print: mov ah,2 int 21h jmp start ``` [Answer] ## Powershell (52 49) ``` -join(-split$s|%{[char][convert]::ToInt16($_,2)}) ``` Simple loop over binary string in $s. Having to include the [convert] kills my score though. EDIT: There really is only one way of pulling this off in Powershell, wowie. Joey and I both got pretty much the same answer working independently! Input: ``` 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 ``` Output: ``` Hello World ``` [Answer] ## Perl 33 32 Edit: Updated solution, 32. ``` say$s=~s/\d+ ?/chr oct"0b$&"/rge ``` Previous solution (33): ``` $_=$s;say map{chr oct"0b$_"}split ``` or ``` say map{chr oct"0b$_"}split/ /,$s ``` Test: ``` perl -E '$s="1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100";$_=$s;say map{chr oct"0b$_"}split' ``` [Answer] ## J (23) ``` u:;(#.@:("."0))&.>cut s ``` Test: ``` s=:'1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100' u:;(#.@:("."0))&.>cut s Hello World ``` Explanation: ``` cut s NB. split S on spaces ( )&.> NB. for each element ("."0) NB. evaluate each character @: NB. and #. NB. convert bitstring to number ; NB. unbox each number u: NB. convert to ASCII ``` [Answer] # Golfscript - 21 ``` ' '/{1/{~}%2base}%''+ ``` You can test it [here](http://golfscript.apphb.com/?c=IjEwMDEwMDAgMTEwMDEwMSAxMTAxMTAwIDExMDExMDAgMTEwMTExMSAxMDAwMDAgMTAxMDExMSAxMTAxMTExIDExMTAwMTAgMTEwMTEwMCAxMTAwMTAwIgonICcvezEve359JTJiYXNlfSUnJysgcA%3D%3D). [Answer] ## Python shell  44  40 chars ``` ''.join(chr(int(x,2))for x in s.split()) ``` Thanks for the help [Griffin](https://codegolf.stackexchange.com/users/2501/griffin). [Answer] ## APL (15) ``` ⎕UCS{2⊥⍎¨⍕⍵}¨⍎s ``` Test: ``` s←'1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100' ⎕UCS{2⊥⍎¨⍕⍵}¨⍎s Hello World ``` Explanation: * `⍎s`: evaluate `s`, turning it into an array of integers. Arrays are written as numbers separated by spaces, so this splits `s`. * `{`...`}¨`: for each element: + `⍕⍵`: turn the number back into a string + `⍎¨`: evaluate each individual digit, giving a bitstring + `2⊥`: base-2 decode, giving the numbers * `⎕UCS`: get the character for each number [Answer] # PHP (61) ``` <?=join(array_map('chr',array_map('bindec',explode(' ',$s)))) ``` [Answer] ## [Bacchus](https://sites.google.com/site/bacchuslanguage/), 25 bytes ``` S,' 'j:A=(Ö,2,10b:c),A¨ ``` Explanation: `S,' 'j` split the String S by the empty space and converts it to a block (some sort of array). `:A=` get the previous Block and assing it to A variable. `(),A¨` for Each element in A `Ö,2,10b` Read the current element (represent by `Ö`) in base 2 and transform it to base 10. `:c` get the previous value and print as char [Answer] ## GolfScript 23 ``` ' '/{[{49=}/]2base}%''+ ``` Online test [here](http://golfscript.apphb.com/?c=OycxMDAxMDAwIDExMDAxMDEgMTEwMTEwMCAxMTAxMTAwIDExMDExMTEgMTAwMDAwIDEwMTAxMTEgMTEwMTExMSAxMTEwMDEwIDExMDExMDAgMTEwMDEwMCcKCicgJy97W3s0OT19L10yYmFzZX0lJycrCg%3D%3D&run=true). [Answer] # C - 63 since C has no base 2 converter in standard library: [test here](http://codepad.org/gS0u5sN3) edit: there is, i'm just too stupid to know about it ``` r;f(char*s){for(;*s;(*s|32)-32||(putchar(r),r=0))r=2*r|*s++&1;} ``` [Answer] # Run Length Encoded Brainfuck, 49 bytes Since there are no variables in Brainfuck, I just used standard input and output instead. The code `32+` should be interpreted as 32 `+`s by the interpreter. Just replace them manually if your interpreter doesn't support RLE. ``` >,[32->+<[16-<[>++<-]>[<+>-]>-<]>[<<.[-]>>-]<,]<. ``` Expanded (non-RLE) version: (91 bytes) ``` >,[-------------------------------->+<[----------------<[>++<-]>[<+>-]>-<]>[<<.[-]>>-]<,]<. ``` The code assumes that EOF is encoded as 0. ## Explanation The following layout is used: ``` +---+---+------+ | x | a | flag | +---+---+------+ ``` Where `x` is the ASCII byte to be printed, `a` is the a character from standard input and `flag` is 1 if `a` was a space. ``` >, Read a character a into the second cell [ While not EOF: 32- Decrease a by 32 (a -= ' ') >+< Set the flag to 1 [ If a was not a space: 16- Decrease by 16 more ('0' == 32+16) <[>++<-] a += 2*x >[<+>-] Move it back (x = a) >-< Reset the flag, it was not a space. ]> [ If a was a space (flag == 1): <<.[-] Print and reset x >>- Reset the flag ] <, Read the next caracter a ] <. Print the last character x ``` [Answer] # Java 8 : 60 bytes Using lambdas in Java 8 (75 bytes): ``` Arrays.stream(s.split(" ")).reduce("",(a,b)->a+(char)Byte.parseByte(b,2)); ``` And if you allow static imports (which some here used) it is (61 bytes): ``` stream(s.split(" ")).reduce("",(a,b)->a+(char)parseInt(b,2)) ``` A tiny bit shorter version using for loop (60 bytes): ``` for(String n:s.split(" ")){out.print((char)parseInt(n,2));} ``` [Answer] # Clojure 63 (or 57) The all-Clojure impl: ``` (apply str(map #(char(read-string(str"2r"%)))(re-seq #"\d+"s))) ``` With Java interop: ``` (apply str(map #(char(Long/parseLong % 2))(.split s" "))) ``` REPL session: ``` golf> (def s "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100") #'golf/s golf> (apply str(map #(char(read-string(str"2r"%)))(re-seq #"\d+"s))) "Hello World" golf> (apply str(map #(char(Long/parseLong % 2))(.split s" "))) "Hello World" ``` [Answer] # QBasic, 103 ``` s$=s$+" ":FOR i=1 TO LEN(s$):c$=MID$(s$,i,1):IF c$=" "THEN n=0:r$=r$+CHR$(n)ELSE n=n*2+VAL(c$) NEXT:?r$ ``` What? We have no fancy binary-to-decimal functions here. Do it yourself! I'm counting the newline (which I think is necessary to get the if-then-else without an `END IF`) as one byte, per [this meta post](http://meta.codegolf.stackexchange.com/a/168/16766). I don't know whether QB64 on Windows would accept a code file that way or not. Probably doesn't much matter. [Answer] **NodeJS** – **62** ``` Buffer(s.split(' ').map(function(a){return parseInt(a,2)}))+'' ``` **PHP** – **75** ``` array_reduce(explode(' ', $b),function($a,$b){return $a.chr(bindec($b));}); ``` [Answer] # JavaScript 111 This does the number conversion without parseInt or eval. Reading the string backwards and counting bits it set's bit x if it's a one. When a space is found a the number is converted to a char and a new 0 number is started for setting bits. ``` x=n=0,w='',s=' '+s for(i=s.length;i--;){m=s[i] if(m==1)n|=1<<x x++ if(m==' ')w=String.fromCharCode(n)+w,n=x=0 } ``` [Answer] # Groovy 64 ``` {it.split(" ").collect{Integer.parseInt(it,2) as char}.join("")} ``` [Answer] # CJam, 11 bytes ``` NS/{:~2bc}/ ``` **s** isn't a legal variable name in CJam, so I chose **N** instead. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Example run ``` $ cjam <(echo ' > "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100" > :N; > NS/{:~2bc}/ > '); echo Hello World ``` ### How it works ``` NS/ " Split N at spaces. "; { }/ " For each chunk: "; :~ " Evaluate each character ('0' ↦ 0, '1' ↦ 1). "; 2b " Convert from base 2 array to integer. "; c " Cast to character. "; ``` [Answer] # Haskell -- 48 (+13 imports (?)) Here's my first golf attempt in Haskell. ``` map(chr.foldl1((+).(*2)).map digitToInt)$words s ``` You need to import Data.Char usage (in ghci): ``` Prelude> :m +Data.Char Prelude Data.Char> let s = "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100" Prelude Data.Char> map(chr.foldl1((+).(*2)).map digitToInt)$words s "Hello World" ``` Explanation: ``` map(chr.foldl1((+).(*2)).map digitToInt)$words s $words s -- split s on spaces into a list map digitToInt -- convert each digit in input string to int ((+).(*2)) -- a function that multiplies its first -- argument by 2, then adds the second argument foldl1((+).(*2)).map digitToInt -- fold the above over the list of ints: -- in other words this is a function that reads strings as binary and gives the value as int (chr.foldl1((+).(*2)).map digitToInt) -- cast to character map(chr.foldl1((+).(*2)).map digitToInt)$words s -- map our function over the list of words ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 3 bytes ``` vBC ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwidkJDIiwiIiwiW1wiMTAwMTAwMFwiLFwiMTEwMDEwMVwiLFwiMTEwMTEwMFwiLFwiMTEwMTEwMFwiLFwiMTEwMTExMVwiLFwiMTAwMDAwXCIsXCIxMDEwMTExXCIsXCIxMTAxMTExXCIsXCIxMTEwMDEwXCIsXCIxMTAxMTAwXCIsXCIxMTAwMTAwXCJdIl0=) ## How? ``` vBC vB # Vectorized convert to decimal C # Convert character codes to list of characters # S flag concatenates result ``` ## If we *have* to receive input separated by spaces, then: # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes ``` ⌈vBC ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4oyIdkJDIiwiIiwiMTAwMTAwMCAxMTAwMTAxIDExMDExMDAgMTEwMTEwMCAxMTAxMTExIDEwMDAwMCAxMDEwMTExIDExMDExMTEgMTExMDAxMCAxMTAxMTAwIDExMDAxMDAiXQ==) [Answer] # [Zsh](https://www.zsh.org/), ~~27 26~~ 22 bytes *-1 from roblogic, -4 from a new strategy using an array and `${a/b/c}` replacement.* ``` printf %s ${(#)@/#/2#} ``` ~~[Try it online!](https://tio.run/##qyrO@J@moVn9Py2/SCGZKzU5I19BpVpDWdNK1yhGWSW5NiYm@X8tF1eagqGBARAZKBiCGYYgGsREpQ0NQerAygzAfIQwRB@ycpB5//8DAA "Zsh – Try It Online") [Try it online!](https://tio.run/##qyrO@J@moVn9Py2/SCGZq6AoM68kTUGlWkNZ00rXKEZZJbn2fy0XV5qCoYEBEBkoGIIZhiAaxESlDQ1B6sDKDMB8hDBEH7JykHn//wMA "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##qyrO@J@moVn9v6AoM68kTUG1WEGlWkNZ00FfWd9IufZ/LRdXmoKhgQEQGSgYghmGIBrERKUNDUHqwMoMwHyEMEQfsnKQef//AwA "Zsh – Try It Online") The `(#)` flag causes arithmetic expansion to be done to the contents of the parameter. Flags are parsed *after* the replacement. `#` matches the start of a string when at the start of a `${ / / }` pattern. So each parameter is `#` prefixed with `2#`, which Zsh recognizes as a base 2 number when `(#)` arithmetic expansion is done. --- This relies on flexible I/O, each group of bits in its own parameter. This is what the pure bash answer does as well. To parse a single string, **+4 bytes** are needed: ([Example](https://tio.run/##qyrO@J@moVn9Py2/SCGZKzU5I19BpVpDWdNK1yhGWSW5NiYm@X8tF1eagqGBARAZKBiCGYYgGsREpQ0NQerAygzAfIQwRB@ycpB5//8DAA)) ``` printf %s ${(#)${=1}/#/2#} ``` [Answer] # GNU Sed, 19 bytes Inspired by an [excellent](https://codegolf.stackexchange.com/a/35119/61904) @Digital Trauma answer. **Golfed** ``` s/\w*/dc -e2i&P;/eg ``` **Test** ``` echo 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100|\ sed 's/\w*/dc -e2i&P;/eg' Hello World ``` ]
[Question] [ The [infinite monkey theorem](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) states that, given infinite time, a machine sending an endless stream of random characters will always type any given text. That sounds to me like a great idea for a challenge. ## Process In order to monkey-ize a string A, the following steps should be taken: 1. Take an empty string. We will call this string B. 2. Pick a uniformly random printable ASCII character (characters in the range `0x20` to `0x7E`) and add that character to B. 3. If A is a substring of B, B is our monkey-ized string. Otherwise, repeat step 2 until A is a substring of B. This process is only an example, easier methods may exist depending on your language. You do not need to follow this method exactly, as long as the same distribution of outputs is achieved. ## The challenge Write a program or function that, given a non-empty string in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), returns a monkey-ized version of that string. Your program only has to practically work for inputs of length 3 or less. For longer inputs, it is allowed to terminate early with or without outputting anything. ## Example Unfortunately, it's kind of hard to create examples for this question due to the random nature of it and the large outputs. However, I can supply [a single example](https://hastebin.com/racimekuti) for the input `hi`, on Hastebin. ## Scoring Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the submission with the fewest bytes wins. [Answer] # C, 192 bytes ``` i;g(s,b,i,n,j)char*s,*b;{for(b[i+1]=0;b[n+j];++n)s[n]-b[n+j]&&(n=-1,++j);return n;}f(char*s){char*b=calloc(strlen(s),1);for(i=0;s[i];)i=(b[i]=putchar(rand()%95+32))-s[i]?i?g(s,b,i,0,0):0:i+1;} ``` [Try it online!](https://tio.run/##NY7BisMwDETv/YpQaJFqB5xdetgK0w8JPsTepFVI1cV2TyHfniYpq4sYoXkzobyFMM9MN0jaa9aiewz3Jp6SPnkau2cEX7OqnDXka1G9I6UEUy2u/OjjEcSWlVaqR4ptfkUphKYOPhgct@1taIbhGSDlOLQCCXWFtOJ5IaeaHSHbNcvZv1dePRAb@QU8/JzV9xdiuT5d@frf1GiDF3NZutE0s@Ti0bAA7sZdsUzazJkfLRhE2m4d7O@8X8Q0vwE) It's a mess now, but at least it [works even for the corner cases](https://tio.run/##ZZBRa8IwEIDf@ytqGZJrUozsQdasyHBzAx3IHvZSymhjtSc1bk180OJv79IWx8a@e8hdjnw5TgZbKRtZpJW7jhM3cr3BIE2zNiT/SzzHn7xA/g9POKPRb9P5tHqY3b@Fr48vp@f56nz3dTM5fEyKcqneF4vl7OmU421PcU0s1tNZfGMla9Gg2BLNMoZMsR20LV8zPxP15lCRLEY6TiIusljRXSIoVaBjlQR9PRwSFQVjRukORJWbY6VcJS4b0mug7s4skmlZHiTRpipzRTSwMYhWj9asY0wEYNT@lUSfR9O@Ib6hFCBom1OcXifkjEPIQzuTuDSojLtPURFwase16CpVa2JwnxMOILq7DfG6ZXu2vjTf)... --- # ~~C, ~~63~~ ~~62~~ 61 bytes~~ *Thanks to @Jonathan Frech for saving a byte!* ``` i;f(char*s){for(i=0;s[i=putchar(rand()%95+32)-s[i]?0:i+1];);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jOSOxSKtYszotv0gj09bAujg607agtAQkrFGUmJeioalqaaptbKSpC5SJtTewytQ2jLXWtK79n5lXopCbmJmnoclVzaUABMVg9SWZuakaBpqa1mCxNA2ljEwlIKf2PwA) [Answer] # [Python](https://docs.python.org/3/), 79 bytes ``` f=lambda x,s='':x in s and s or f(x,s+chr(randint(32,126))) from random import* ``` [Try it online!](https://tio.run/##FYo7DoAgEAV7T7EdrNIIiYUJh0EJgUQ@WSjw9IjNvGTelLf5nNQYTj8mXtZAF1UzdnYICSqYZCczgePz2G5PnKYLqXElxS4PRFwc5Qi/nhNiydTWUehvHGeGIY4P "Python 3 – Try It Online") This is theoretically sound, but will crash early due to python's recursion limits (you can set them further to get longer results) # Python, 84 bytes ``` from random import* x,s=input(),'' while x not in s:s+=chr(randint(32,126)) print(s) ``` [Try it online!](https://tio.run/##Fcs9DoAgDEDhnVN0E5RFTRxMOIzxJzSRQkqNeHrU6eUbXnrERxprPTgG4IW2LxhSZGlVsdkhpUu0sU2jbo/nDgUoCiBBnnPnVs/6v5BEj4Pth8kYlfhnNrV6fAE "Python 3 – Try It Online") This one is ought to work for relatively longer strings, since it doesn't rely on recursion, at the cost of 5 bytes. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 10 bytes ``` Ý£D³ε‽α@§↔ ``` [Try it online!](https://tio.run/##AR4A4f9vaG0y///DncKjRMKzzrXigL3OsUDCp@KGlP//aGk "Ohm v2 – Try It Online") Explanation: ``` Ý£D³ε‽α@§↔ Main wire, arguments: a (string) Ý Push empty string to top of stack £ Start infinite loop D³ε‽ If a is a substring of the ToS, break out of the loop α@§ If not, select a random printable ASCII character... ↔ ...and concatenate it with the ToS ``` [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 64 bytes ``` s=>{S=""whileS::sub((#S)-#s)!=s S+=S.char(math.random(32,126))S} ``` This uses a few tricks I've been wanting to use in Funky, like a variable name after a keyword as in `whileS`, and using the fact that strings implicitly parent to the `string` library. ## Ungolfed ``` function monkey(target){ monkeyCode = "" while (monkeyCode::sub((#monkeyCode)-#target)!=target){ monkeyCode += string.char(math.random(32,126)) } monkeyCode } ``` [Try it online!](https://tio.run/##SyvNy678n2b7v9jWrjrYVkmpPCMzJzXYyqq4NElDQzlYU1e5WFPRtlghWNs2WC85I7FIIzexJEOvKDEvJT9Xw9hIx9DITFMzuPZ/QVFmXolGmoZSRqaSpuZ/AA "Funky – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 100 bytes ``` import System.Random s#(a:b)|and$zipWith(==)s$a:b=s|1>0=a:s#b m a=(a#).randomRs(' ','~')<$>newStdGen ``` [Try it online!](https://tio.run/##HcuxCsMgFEDRPV8hMaBCCe0afFm7dIpD5xciKI1GfJbSEvrrNnS8B65Deth1rdWHtOXCzJuKDf2EcdlCQ1ziMKv9qO7j090XJwEUdYcC7ZfxDDgQn5vAECRy1ef/OJEUTJzEVyjdjdG@TFmuNtaAPkJ6FlPyLYLWgbXOt/UH "Haskell – Try It Online") Basic idea is to generate an infinite list of characters with `randomRs` and stop it once we find the string. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 86 bytes ``` a=>{var b="";for(var r=new Random();!b.Contains(a);b+=(char)r.Next(32,127));return b;} ``` I don't really like how much creating the `Random` instance takes, but I don't think there's a way around it. [Try it online!](https://tio.run/##PY6xTsMwEIZ3P8WRyRYlUsvA4LoLElOLEAzMZ9dJLSU2Ol9KUZVnD06DmH7d/d/pO5cfXCI/DTnEFj5@MvteC/E12C44cB3mDG@UWsIexFUA/DWZkUucUzjCAUOUCko5AwBnJGCk1jMYqE6h0v/rxkT/DS9DdNvMVJSrJXZyQrO7zog1VaWbRHIe6Ma/YzymXip9Z@vnFLn4skSl7b2R7oSkqH71F5aPm9V686SUJs8DRbB6nNQiL2c5db7@pMB@H6KXjVx@VDdiFOP0Cw "C# (.NET Core) – Try It Online") [Answer] ## [GNU sed](https://www.gnu.org/software/sed/) + coreutils, 75 + 1(r flag) = 76 bytes ``` h : s:.*:shuf -i32-126|dc -e?P:e H;g s:\n::2g /^(.+)\n(.*)\1/{s::\2\1:;q} b ``` [Try it online!](https://tio.run/##K05N@f8/g8uKq9hKT8uqOKM0TUE309hI19DIrCYlWUE31T7AKpXLwzodqCAmz8rKKJ1LP05DT1szJk9DT0szxlC/utjKKsYoxtDKurCWK@n/fzOdf/kFJZn5ecX/dYsA) (It takes a lot of runs to get an answer for a length 2 input, because most of the time you run out of allowed TIO computation time.) **Explanation:** ``` h # copy input string 'A' to hold space : # start loop s:.*:shuf -i32-126|dc -e?P:e # run shell script: shuf outputs a rnd permutation #of the set of numbers from 32 to 126, and '?P' in #dc converts the 1st read decimal to an ASCII char H;g # append char to hold space ('A\n.'), then copy #result back to pattern space s:\n::2g # remove all '\n's from pattern space, but first /^(.+)\n(.*)\1/{ # if pattern is 'A\n.*A' (A substring of B), then s::\2\1:;q # search previous regex used and leave only '.*A', #then quit (implicit printing before exit) } b # repeat loop ``` **Benchmark:** approximate, for scaling purposes only * input length: 1, 10 random inputs (runs), average time: < 1 s * input length: 2, 10 random inputs (runs), average time: 90 s * input length: 3, 10 random inputs (runs), average time: lots of hours! [Answer] # Perl 5, 31 +2 (-pa) bytes ``` }{$_.=chr 32+rand 95until/\Q@F/ ``` [Try it online](https://tio.run/##K0gtyjH9/7@2WiVezzY5o0jB2Ei7KDEvRcHStDSvJDNHPybQwU3////Kkn/5BSWZ@XnF/3ULEgE) [Answer] # [Japt](https://github.com/ETHproductions/japt), 26 bytes ``` @(PbU >-1}a@P+=(Mq95 +32 d ``` [Try it online!](https://tio.run/##y0osKPn/30EjIClUwU7XsDbRIUDbVsO30NJUQdvYSCHl/3@lCiUA "Japt – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~79~~ ~~76~~ 75 bytes *-3 bytes thanks to [MickyT](https://codegolf.stackexchange.com/users/31347/mickyt) for changing the random sampler* *-1 byte thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for tweaking the random sampler again* ``` function(S){G="" while(!grepl(S,G))G=paste0(G,intToUtf8(32+95*runif(1))) G} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNYs9rdVkmJqzwjMydVQzG9KLUgRyNYx11T0922ILG4JNVAw10nM68kJD@0JM1Cw9hI29JUq6g0LzNNw1BTU5PLvfZ/moZSRqaS5n8A "R – Try It Online") [Answer] ## Charcoal, ~~15~~ ~~14~~ 12 bytes ``` W¬№ωθ≔⁺ω‽γωω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDL79Ewzm/NK9Eo1xHoVBTU1PBsbg4Mz1PIyCntBgkFpSYl5Kfq5GuqamjUK5pzRVQlAlSrGn9/39G5n/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes due to a subsequent bug fix in Charcoal. Explanation: ``` θ Input string ω Predefined variable `w` № Count number of occurrences ¬ Logical not W Loop while true ω Predefined variable `w` ⁺ Concatenated with γ Predefined printable characters ‽ Random element ≔ ω Assign to predefined variable `w` ω Predefined variable `w` Implicitly print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->w,s=""{s+=[*" "..?~].sample;s[w]?s:redo} ``` [Try it online!](https://tio.run/##DYs5DsIwEEV7TvFlOhYfABRyAQr6KIVJfmSLbJqxFSEEVzdu3yLp@c5Dlc@37aSVMR89Vs3BwFhb/1qrblpHXrXZ2lovwn755j0eI50SL3JFmDGFuUf0LiKGxUqaERQO6l0ZINQlSUeLe5hCaTzLtKYITyHiUoiQ6EruukhRuytWMTTGmzb/AQ "Ruby – Try It Online") [Answer] # Pyth - 14 bytes ``` .W!}zH+ZOrd\k ``` [Try it online here](http://pyth.herokuapp.com/?code=.W%21%7DzH%2BZOrd%5C%7Fk&input=a&debug=0). [Answer] # Mathematica, 65 bytes ``` ""//.x_/;x~StringFreeQ~#:>x<>RandomChoice@CharacterRange[32,126]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/BfSUlfX68iXt@6oi64pCgzL92tKDU1sE7Zyq7Cxi4oMS8lP9c5Iz8zOdXBOSOxKDG5JLUIKJqeGm1spGNoZBar9j8AqKtEwSEtWikjUyn2PwA "Wolfram Language (Mathematica) – Try It Online") *-3 bytes from Jonathan Frech* [Answer] # [Lua](https://www.lua.org), ~~99~~ 102 bytes * Saved a bug thanks to [ATaco](https://codegolf.stackexchange.com/users/58375/ataco), which added three bytes. ``` function f(B)s=string S=""while not(s.find(S,B,1,1))do S=S..s.char(math.random(32,126))end print(S)end ``` [Try it online!](https://tio.run/##TcxBCsMgEEDRq4irGZABU@gum1zBE0jUKsSx6ITucnWb7rr7i8c/Tj9nOnmX0lgl2HCsQ3rhl3Kr1p9cjqi4CQxKhQM4sxlrLGJoN3BEg/bsO1Qvmbrn0Co8FmOXJ2LkoN73SsD9ev6ZEWOANkhKjYCYQF@kcX4B "Lua – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes ``` ''`6Y2TZrhtGXfn~ ``` [Try it online!](https://tio.run/##y00syfn/X109wSzSKCSqKKPEPSItrw4oYmKkrgAA "MATL – Try It Online") -1 byte thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) [Answer] # [Octave](https://www.gnu.org/software/octave/), 62 bytes ``` t=input(o="");while(~nnz(regexp(o,t)))o=[o,randi(95)+31];end;o ``` [Try it online!](https://tio.run/##y08uSSxL/f@/xDYzr6C0RCPfVklJ07o8IzMnVaMuL69Koyg1PbWiQCNfp0RTUzPfNjpfpygxLyVTw9JUU9vYMNY6NS/FOv//f/WMTHUA "Octave – Try It Online") Explanation: ``` t=input(o=""); % get stdin and define output while(~nnz(regexp(o,t))) % while no matches o=[o,randi(95)+31]; % concatenate string with ascii char end; o % output result ``` Many thanks to Luis Mendo for the edits! [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;_øU}a@P±Eö ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O1/4VX1hQFCxRfY&input=Ijgi) ``` ;_øU}a@P±Eö :Implicit input of string U _ :Function taking a string as argument øU : Contains U } :End function a@ :Get the first result of the following function that returns true P± : Append to P (initially the empty string) ; E : ASCII ö : Random character ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 21 bytes ``` /U!?"$~dr@ \idwz K"o/ ``` [Try it online!](https://tio.run/##S8zJTE79/18/VNFeSaUupciBKyYzpbxKwVspX////8QkAA "Alice – Try It Online") ### Explanation ``` /...@ \.../ ``` This is framework for mostly linear programs that operate entirely in Ordinal (string-processing) mode. The IP bounces diagonally up and down through the program twice, which means that the actual code is a bit weirdly interleaved. The commands in the order they're actually executed are: ``` i!w" ~"rUd?z$Kdo ``` Let's go through this: ``` i Read all input. ! Store the input on the tape for later. w Push the current IP address onto the return address stack. This marks the beginning of the main loop. " ~" Push this string. r Range expansion. Turns the string into " !...}~", i.e. a string with all printable ASCII characters. U Random choice. Picks a uniformly random character from this string. This will remain on the stack throughout the rest of the program and will form part of the resulting string. d Join stack. This takes all strings on the stack and joins them into a single string and pushes that (it does this without actually removing any elements from the stack). ? Retrieve the input from the tape. z Drop. If the joined string contains the input, everything up to and including the input will be discarded. Otherwise, nothing happens to the joined string. This means that the result will be an empty string iff the joined string ends with the input. $K If the top of the stack is not empty, jump back to the w to continue with another iteration of the main loop. d Join the stack into a single string once more. o Print it. ``` [Answer] # [Perl 6](http://perl6.org/), 39 bytes ``` {("",*~(" ".."~").pick...*~~/$_/)[*-1]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNJSUerTkNJQUlPT6lOSVOvIDM5W09PT6uuTl8lXl8zWkvXMLb2v7VCcWKlQpqGeoS6pvV/AA "Perl 6 – Try It Online") `(...)[*-1]` returns the last element of the sequence defined by `...`, of which: * `""` is the first element; * `* ~ (" " .. "~").pick` generates the next element by appending a random character in the appropriate range to the previous element; and * `* ~~ /$_/` is the ending condition, which is that the current element matches the main function's input argument `$_` as a literal substring. [Answer] # Java 8, ~~81~~ ~~79~~ 78 bytes ``` a->{String b="";for(;!b.contains(a);b+=(char)(32+Math.random()*95));return b;} ``` -1 byte thanks to *@OlivierGrégoire* for pointing me to a (big >.<) mistake I've made.. **Explanation:** [Try it here.](https://tio.run/##LY7PbsIwDMbvPIXpKRkiB9AOU9S9AVx2RBycNKwB6lSJi4RQn73zRCRb8t/v@13xgds0Brp2t8XfsRQ4YKTXCiASh3xBH@D43wL8cI70C17VArWV@SwpURg5ejgCQQsLbr9f9cq1TWMvKSu7dsYnYpEvSn7dplW@x6zVfrc5IPcmI3VpUPrj61NrmwNPmcDZebFvj3Fyd/GoVo8UOxhErfKczkJUSZ@Fw2DSxGaUFSsyXjV9bHRFnpc/) ``` a->{ // Method with String as both parameter and return-type String b=""; // Result-String, starting empty for(;!b.contains(a); // Loop as long as the result does not contain the input b+=(char)(32+Math.random()*95) // Append a random character to `b` ); // End of loop return b; // Return the result-String } // End of method ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes (-1 @ Emigna) ``` [žQΩJD¹å# ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@ui@QL0gL5dDOw8vVf7/PxEA "05AB1E – Try It Online") --- [Do the monkey with me.](https://i.stack.imgur.com/ZWh1z.gif) --- ``` [ | Loop forever. žQ | Push 0x20-0x7E as a single string. .R | Pick from it randomly. J | Join stack (B) with new char. D | Duplicate (B). ¹å | Push input (A) and check if input (A) is in (B). # | If the previous statement is true, break loop. ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 33 bytes ``` ≈instr(Z,;)<1|Z=Z+chr$(_r32,126|) ``` ## Explanation ``` ≈instr( , )<1| WHILE InStr() can't find ; the input (cmd line string argument) as part of Z the output (Z$, which is printed automatically on exit) Z=Z+ add to the output chr$( ) an ASCII character _r32,126| with a random codepoint between 32 and 126 (incl) ``` ## Sample run: ``` Command line: hi `;7L3f$qy )H99tZ@>(-Z1efL|Q-5'BE=P8BdX?Lem/fp|G#~WY[ Q4s9r~Af*T})P4`4d$#ud3AiuTwQPFS@8c7_59C$ GlJ%iJ[FA(rNt<y>Hl=r,wSbBB%q!8&#*CixWbnwE."wrZ:R53iKJkN*@hpQt aMj6Mw<KfT@hkik>_k'_>$~3)jl|J!S`n\Yw|lXi:WAKWp?K"F.cAGI/:~uR8*[;Die{]B*]@;Vhjv,$9]Ys:AIdy!j{aXlr:0=txCP-n{/3lgq,;jXaP\]u}.Zl/7eKF+N54[J9^r:>%/.e~*9aK%de>^TW%p%(_uJPvuV%d<&]zu`t;vkEPC>7pofok0Kj}j?9G{TUxSccth)[)J>@'E)NMzA(i!UV7%;$.Z#j3q@#9Q%}<" &VsbL*<SrG-$NC MAQ\`iIT+.P|5}nv )FZl5_.Kc*AUV9u&fvk.USt3Y!s7^UEL{|D$k#k8.9Fgqn#3dgr(0G.gw1#j$HfU3a|)3-O(d<)<A|`%pJ^/\{[w[H4N/>8J@z/YNsU,zY4o*X+h\Dy!~)Xr8.3"%.39v0d5_-8QBYR".Z]MZ}N>9e?f@hj#hor1IhJ[krrHOamRPxQC>^'dOh,cF_e2;8R@K**Jsx_~t9r~4J$Y;kPsb)8w~:o-`@MwP]OA{8yD%gL(=&M>$nTKw] R[}rS|~}&*gD 'g|gRSDLld+`,,}(1=]ao3Z%2*?wlqU$7=$8q$Fig:7n&+XKQ LV/Aq?BYl_*Ak-PqI$U_>`/`-yD5.3|Zg>,mC"RC`IV^szu:I;0ntn(l'/ZnK}T&i)9!zkd?7Ec/X+IN=-5wwsSV@^<?:K=9m%*@C;zDjc%:d>/E@f7@0NVt4Vz/E;8*0A25F1:JUQ/G#2)un9hQI>2^}&+cY+JP*-#$p+cFs}R|>E;w#q>pN"Jkv<>E_ZtCvV05Lh;0 9bCBXgA7aIe+9B1<G)YCH\Yqn.0%g$_4Q4 xIR)gt]W*a|gGX}hP4b)6#M:Dh!kmuX;nW]'n]Mm5y=ET|O9p\,j>Bc|7J5I%UCZla-2g(Mm9cE"}c1Q0@yTF|A\FJbR7_(F_G#@mE/~ [9T~|Ty9~0=g {a^IM{]C9%2FBJ:b&i5A{rqu/xw6q|_[$Sj&W\TnI}/>.EJ1dSbSOtr_Qtuf!IF .WU}&M51+VAnJ)W}^c5qwQ<G05}/aZ99l6iqyD|Zr8SV9L}8FbUz7_H<]A|.vFQXSu2@67%83HP4]Gw0PuPNQ6SOM_[BcdK-s}Z(~~i:^N$GZn_sMcp*i,w-2VfK*LA$Btmg6QEohqym3[RRqUAM"9pE>N)(.TNMQ"U~ e2($wz(Kdh;0ol8>SXHEnLvrs.Xtl^L?SL1$*ssD _={{}(`qKCy{]W:AZT}Zro5qN:;mNp#EPfg?_],,cFP?EhGs/OAt}fgVSR<JW^HkWf'@^Vd9\_Y?P*>C'YP jqvXu)ZFwzY)/MLHcRL/P?jBi9"d\ E$ngpq-i*;EW6R)J|[0FfZSTozuSq,sAJT<<4al<zM\F(|gTD0/Vt6JL.p_x_oC)V'zWZ`8eA9@*WgZ>',-}Q^5#e552&"\i1HI]{)]WcI.cY0n9J<jaT.!l{r4Dz~nt`AEP-6,FHhf6(PSywIedr }=9V>Q7!+~L^O3'Crdv"hfv#xrs@](EO;&#)0]oC][z*Eh`k!$V!r6~#-Vfk1p#w&Za6Ij\@V<TNf4njdynOch7l?XwU `SON\iizU3%S^X2XKY.w%:zAVY^KlIhZ8]d39No3P89v`1FxKTLQa+7"rd9bm2)a^Pu=~.9VDh?v"%$9evl9+l7n$I?qA[b:kH2?5Tg&(!H(*}hZ3z@bg+Zj!# JnO2FV_glCMweT;b|>g4!h{4@ p w`lH \Y8(uPf7nbJY]r>('-$O?5Xd:h&:y!i%2dRC_8=3! |b="H|jxx)k!\D|]Lsdz1.v[a<l/Y3?0/&H%2.qvPp'ZNpO;rhvtnl0*Bs4Qlh0}_dv6g0`pJh'==]9LuzG+qUGz5.j[$I{4.b_o;S`QFucC9>`z7M.wHx!wy-JeOf)^9#Z.xl7e"9q)OE-SSD"VbLFm-u'-<4~(_h\KqNk7}vKh0E&!LaxAma|FOIY,\C$;!v^#4,eqwpE]Jqp,]IkTz,,L`kx|\i^#{PV0/8K?N,W!L=vbh\OJ7?:k=~{zLw8*/W<-qFDKAhx1F;\NL@{=rlo0''YB;B5<:0e5J)w"0l@FE?J:FW(I|)3BZ'hL7[}Ez=jc(rLkY9d{Zzgq7Cj)bej/[[email protected]](/cdn-cgi/l/email-protection)"Arz7IU;1|.3by~\h{V57}A^w7v5gMC]@B~1i5*uY 7?(IN6hQ/b/4bMpDmT_"n|;bBx|74(ReQ.^])bHC+:!s bk_S]R}<Ow:7CCu_P!$:mz{[aiGg*AD#}m~D_rhVr6!x]PY5n'qiMMlpqoU>C`,W}y9Yi4hHf<lcwvga`h(<=jURq\d+2SRGA1GP**D]i+Tp@*hpe([-JE^M@5jHgK~>hY>Bo&% \e/\&]"K])CV%oNJ}[_Q1}w(p3uJ+\/;{0TB8#{=&l8s;]L7Gr;a_[cN:#%$)?*:HLZ;&n|2_8/@=B [>|R3@xk<c+bIyb>h`]:c]RLt(M!69PNE?}>@CHT>jNevl81PCgHu0ap0~Pcq?Z@>+yTFw\E=10&fpS+=/l|.ioPn$B.M\4{2?q-^,)f&S4X44(Rycome[Ot[t(8CAphj[h}E/A~BR[6Y&Hm1_tsxs4BB0cwo\",r_c~s/vT}kKu3U(Emb|%"`OAmV7$,\<O7)c&F==mc~dM:qX^[K-9<3u8hfgTUP19aXk,7g(4>jLt,*N!EXGE#XzN}>7@EH4n}k!&a[j,Ynd#!M<suhnBP /J9}h>vRyXuADk"+v}?hOm6*U^x\G'!Y(TDC?EE|r}5yx4PB 1;9q.%/kg7p2ImS62+/|K,xSDf3b6JRY+8~mxikSU^&3A3|/j9}fIESN45kdi*h64!XE'_0?Pw{MeK$DeXP]5M{7sLD!dj5HrAc\N I`~o/%MqyIIsFee]A?j7ZZ}f'dN#"V''g-G0@zNajp=v<"r2s;>@.UM9L\Mq16e/961d.3a6h.hMrUREa^wR^s*\Tc6Yn]DT.Nc77p|h s2@hC\Rxy|XhXi.OL2$\pwPSJET;u7V`U!<]M(tibt>.gD'JKe{7r8?Z[]ExGHxyd\,/wjfBI'NKCpaU19-?f;;QVrWnFF,zvJY|d\DrcysAO'; 33CSNy_GlLr\v)Ir\qQfwT'I#t:N-{,x#zGR.)gJqq%!zF.oJ;]*TI+4z>JQAGQM3w&zgani8JwZW6S!r-ig\3jD}]2*.Aen8O)L?X.UTZ6)mOtUIm_=3fA'_::vV_#+c+=evf#{8lk+`)M\_c+I<|*LRZOU]:eQ*/KER#f,vEC?4yXE*8wlzk?b)&[gF'(0|$@+4CT4#lfEKxP~;oo%1+=yw#J*s}D7p1fU~^gD1Ib{H|PWer^q"q=?Pxf<)tvu7{HDvl\kqb"b/|s>|h.qQu[$F/:~*dy9cl16}dKXY~N7aptCSv+da/S5-,qnwBhRi+lh8=Qy{er:#Oos|e?(US>"767KVe^nz<$]gM)~J>{I7n~!k[U\1{8Z8u6T(ft?kgdQO,LvY/TDAe\wS~Y U>\.aQYhQ;h1nuW$R/wpz_EiB-%gf87qgQei(P-ft:TSW,HtsPez"5<8?yR`wm7pjMn^|8Y.4[RVWq#aW$0EB9"O:%@q[&F[_'2yt2k]S5~HCN1+^bS>N2C/7ChHCHNrJ8,kBbNsu}37LH^n.B+tyE*s7l(Tc<;4.tvBw3LP=nK4G'6M(z086;"??9XE.(X>nvmm()P2m\"LeqbcOC~Vw;u/Q^T)52/pM3+<GkFWJ?30{/n2FQq QjO#pt8oN$kK/a+|Hbw@5m8M[EFWq>%cV2[X@q}gJ"9kt9'~]4p+2~LT9|4Ss^qoXw%P#M!!]TBQbp;PYg{WCj,RF<#bNJTS,CUH{][hY"q;[?#apc%Cl&QWVi]ffYG}bzx .;*/rqRhb[XatPu.Piws<mo=]!e>p%yu\;fCzJ0Xz]6]9S:WRlYS,mC&7Zjb)+DjJUkSF3TJG;8fQ4|>t%qgW1$_V:p;|Q":Z!UngSL{*Ky+/zh [I{_3?]h^x37"`^'/U>EPqal'&Txf,I>gr2HO_y!QM-ch~%m-(AE6U~[A"D@j1hu?6p2"Wc'3nyqfs!.UQy}I%0(z5dPmORFBK1,<PfYersnLe<fLhB=^g pwXnWDOQNuIPEpnm8.Q6jN|a7tcuSH$9T;! d~VQn{'(-4{caLa;t?~|>q:on:Bgs'FQ'2-<%W<3Px=4Uf;@;R3yZECK?f(5K?`^lQY\ok},`Q9*Q}3].Y!BkRt"3@]Lz&ec'NB?n[%0kQ9/55BOZ)o!P>fpXZI:#?Ly#\o.`+HX Kb0@P^1qS%bGip1`)qH@-k\oOGs%;}_Nq{uPq |!K)01w(?X=>bSR[(]ZQ<Z1]bD9M.F<<.8EB6JlEUOk6r;SrVZNT2 m>zp3]a_sK eq8]rK^.U&!d62HBt`v?t6uc#3s<{[CmYE24+ujEx`$##R2g\b!PvK<8+lUhyT|p"SUco/aUh.fXBV(!!)8PfQIr6R,r8c-F-mjua;:z4!Q1pA!H0E%)"K2oUv|DV+lg,h8W?<JnIkiV/us::*l&I<OI6NO)Tnq0-uDRG5*LX#wU{8WpMlw3Z'7zGi*loo2{=hWSY*0/o9BwtJ$Hw}l94nA^9>48(3gDnt8CS|R3? OH[N/9j1r%vUcox\68{yFemlmmtp*q5kfrlIo`3yQB??6jW:TW+)':K#]^=ilF_/N!)=}[[email protected]](/cdn-cgi/l/email-protection)//nhChX!3b`=t,1_KhR,n]/_.-P>B80W#'E%J[g?ti)*;Yl]}r0>qh/X[{=)Gr '[+pz|DI=mA8zj~yAT*^7w%tV0l=V^/#2W>)f)X%f^L&+Un}VlQt3.%gEKbE!7`adTb#`}i!F$-Gug]@*G,hKe;/p,`Mb@wBJ4<V&jJd&_H4VR{Hc"{2<l<QapiLw(JK-2-[1_.WR.@CG$?\1<&( QX5c9 :z^jDW09(=iH V/vkcJ8D<uLAr$dbc$Hl'2KTUlbrd8kD{B0Eeu<&oL2s.S4@Jo$zVq~BqeLsb;k-NG/'iU|)W_:X-.XUc<v\elx57ZZ"R!y_yzve*Wlt>.fE,#Eh:(#gn1kSQ+/3NYjD']I;"+@pnW[1EA.AyqM4,0,dJt.?r2oab.j\k@)BsZ|s39FdL87xyuJ0nXX=yz^~W,}acDZp8ukCpv^<^{CkRS<=GsS$}#fbP5%A$GHdg)+WZLLN9[ue073Q!F"J;X^49*$R'W%C.r~Fj&B`)tq[01a4En%H,kvyZG|,)%$44rJg[tq<wG9FjN<m@larki#;Bns%D}v_efPRH(OeRq0{=>Uc[~xcTcV_9|k54Q2*N.3]LlmFasY3"p =$$onbg$M+ReRsnH|9gV~#2?c1-V$35."DZH-O$~,c.gs]%,]p4\OFIW%l:,E,YT8FCeU8hy#lNq1lCpS 0I&q_*q>|=,(-dHuzi~6$GW22*A\w*&R< W`$HPRr,2A}3w\"Y?d%{2^xP:GqI\26A|.e'H2Z[M4=P.H87O~{)9|B*tHAC\j^S,StW!*snsz82R!:eD@uB4x+x&zSIN(3V|.^N_$=i=p}iK4h'v"$:I<t e:Y/XrSOF83=lkVNa0^k@jB@{ARE@r=Bja`(Bw>@?+`Wo,= u5HhXPeRMXS4@H#$-Jwg2"2-]%7p.o2Ar9J6Y1Ra?"3<oee&bpO^O{nw9=%\0brVNXrelWGoJyb/5W%MB0UBaPsc*29K<N~``NriWM$"eY0@xh^<$b:E/J~S%{#ry~6d?4Vv@^&9'=iBA#2U]bj9>UoJ#wQDN~6cB&/_Pu-XF?_hu3><(M7RW\%Ly@rTC9^b`?kVL~w%[{!&{#aS7<mc@J>ZaN7s}Y.c0:Y.\d&_[L{m|>|>%J^@!i9y0_lwejChi ``` [Answer] # PHP, 55+1 bytes ``` while(!strpos(_.$argn,_.$s.=chr(rand(32,126))));echo$s; ``` Run as pipe with `-nR`. Not suitable for TIO cause of probable timeout. Insert a space between the quotation marks for PHP older than 7.1. This **51+1 bytes** version will fail if input is `0`: ``` while(!strstr($argn,$s.=chr(rand(32,126))));echo$s; ``` [Answer] # Javascript 74 bytes ``` s=(a,b='')=>~b.search(a)?b:s(a,b+String.fromCharCode(32+Math.random()*95)) ``` call like this: ``` s('hi') ``` [Answer] # [Julia 0.6](http://julialang.org/), 53 bytes ``` a->(s="";while !contains(s,a) s*=randstring(1) end;s) ``` [Try it online!](https://tio.run/##DcU7DoAgDADQ3VMgExgdXFwIxqtU@dWQklANx0ff8u43I2w92NNHpA7LrthKaVrC7MV4FXoAiRXPoAVPtgI5fipSVKsWnpxh3f@Gg1NpIiiZUOr@AQ "Julia 0.6 – Try It Online") [Answer] # [Pushy](https://github.com/FTcode/Pushy), ~~20~~ 18 bytes ``` LFZ^tCN[,` ~`U'x?i ``` **[Try it online!](https://tio.run/##Kygtzqj8/9/HLSquxNkvWidBoS4hVL3CPvP///9KiUlKAA "Pushy – Try It Online")** The program keeps a stack `len(input)` characters long, and constantly removes the first and appends a new random char, until the initial input string is reached. Each character is printed as it is added, creating the desired effect. Explanation: ``` \ == SETUP == F \ Put input on second stack L Z^tC \ On the main stack, make length(input) copies of 0 N \ Remove printing delimiter (newline by default) \ == MAIN LOOP == [ \ Infinitely: , \ Pop the first item on stack ` ~`U \ Add a new random character (between 32 and 126) ' \ Print this new character x? \ If the stacks are now equal: i \ Exit program ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` I⁰∧Ẹ{sI⁰&|;Ṭṛᵗc↰} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v@ejxo3POpY/nDXjupiEFutxvrhzjUPd85@uHV6MlBR7f//ShmZSgA "Brachylog – Try It Online") ``` I⁰ The global variable I⁰ is the input, ∧ and Ẹ starting with the empty string { ↰} call this sub-predicate again ṛ with a random Ṭ printable ASCII character ; ᵗc appended to the string we're building | unless I⁰ I⁰ (which is the input) s is a substring of the string we've been building & in which case the string is output. ``` Can randomly stack overflow. This makes use of two recently added features in Brachylog: global variables, and the apply-to-tail metapredicate `ᵗ`. [Answer] # Pyth, 13 bytes ``` W!}z=akpOrd\ ``` where the unprintable character is 0x7F. [Test](http://pyth.herokuapp.com/?code=W%21%7Dz%3DakpOrd%5C%7F&input=a&debug=0) [Answer] # Bash 94 bytes ``` p=printf\ -v;until [[ $s = *"$1" ]];do $p x %x $[32+RANDOM%95];$p c \\x$x;s+=$c;done;echo "$s" ``` [Try it online](https://tio.run/##S0oszvj/v8C2oCgzryQtRkG3zLo0ryQzRyE6WkGlWMFWQUtJxVBJITbWOiVfQaVAoUJBtUJBJdrYSDvI0c/F31fV0jTWGiierBATU6FSYV2sbauSDFSbl2qdmpyRr6CkUqz0////RD0A) ]
[Question] [ # Challenge Given that Christmas is: * December * Month 12 * Day 25 Every year, determine today's date, and whether or not today is Christmas. If it is Christmas, you must print `"It's Christmas"`. If it is not Christmas, you must somehow wait until Christmas and then print `"It's Christmas"`. # Example From [this Stack Overflow Question](https://stackoverflow.com/questions/8379805/im-new-to-python-i-cant-tell-if-this-will-work-or-not) ``` import time while time.strftime("%b, %d", time.localtime()) != "Dec, 25": time.sleep(60) print "It's Christmas" ``` Python in 115 Characters # Rules Here are the rules: * Assume that the computer's clock is always right. * Your code must be able to be started at any time. * Your code must print `"It's Christmas"` on Christmas. * Looping is certainly not necessary, but once started your code should not stop until it has printed. * Shortest code wins. [Answer] # Unix, 39 bytes ``` echo{,} "It\'s christmas"|at -t12252359 ``` With help from Dennis, thanks for that. [Answer] ## Perl + Unix, 40 chars ``` 1until`date`=~/c 25/;say"It's Christmas" ``` This is the same as [J B's Perl solution](https://codegolf.stackexchange.com/a/4110/3191), except that I save a few chars by using the external `date` command instead of Perl's `localtime`. [Answer] ## PowerShell, 45 ~~46~~ chars ``` for(;(date).date-ne'12/25'){}"It's Christmas" ``` It's certainly not very power-efficient, so a laptop battery might die before Christmas (reason to wish for a new one, maybe). But not sleeping is definitely *shorter*. This is also locale-agnostic. And thanks to Jaykul for a nice trick in reducing this further. ## Abusing the rules a bit, 45 chars ``` for(){"It's Christmas"*((date)-like'12/25*')} ``` This will print empty lines until it's Christmas, upon which it will print “It's Christmas”. It ... * ... can be started at any time. * ... prints “It's Christmas” on Christmas. Several times. The whole day long. (The rules didn't say anything about how often it may be printed.) * ... does *not* print “It's Christmas” on not-Christmas (although it prints an empty line in that case; can be rectified by sacrificing another character, but then this gains nothing over the more sane solution above). * ... does not ever stop (not even after it has printed “It's Christmas” but *definitely* not before). [Answer] **PostScript, 90** ``` (%Calendar%)currentdevparams begin{Month 12 eq Day 25 eq and{exit}if}loop(It's Christmas)= ``` Don't run on a printer, it doesn't print a page, and it will only DoS your printer until Christmas day. Then again, getting your printer back would be a nice present. [Answer] ## Mathematica, 47 ``` While[Date[][[2;;3]]!={12,25}];"It's Christmas" ``` [Answer] ## Perl, 44 ~~45~~ ``` perl -E'1until localtime=~/c 25/;say"It's Christmas"' ``` Wouldn't GMT time be sufficient? (3 characters off ;-) [Answer] ## Perl, 45 ``` {localtime=~/c 25/&&die"It's Christmas";redo} ``` ## Perl, 44 using ternary operator (Thanks to Ilmari Karonen). ``` {localtime=~/c 25/?say"It's Christmas":redo} ``` [Answer] ## Javascript, 51 chars It's a CPU killer: ``` while(!/c 25/.test(Date()));alert("It's Christmas") ``` [Answer] # **R (47)** ``` while(!grepl("c 25",date())){};"It's Christmas" ``` [Answer] I wanted to do this without parsing strings. Subsequently, there's a lot of magic numbers in my code. I did some approximation to account for leap years. No one said that it had to print it out right on 00:00:00, Dec. 25! ## Perl, 80 69 57 characters ``` {(time-30931200)%31557600<86399?die"It's Christmas":redo} ``` Edited for more concise looping! [Answer] ## Python, 66 68 ``` import time while'c 25'not in time.ctime():1 print"It's Christmas" ``` [Answer] # TI-BASIC, ~~42~~ 38 ``` Repeat 769=sum(getDate²,2 End "It's Christmas ``` Expects the date format to be YYYY/MM/DD. getDate creates a three-element list `{year,month,day}`; only on Christmas is month^2 + day^2 equal to 769. 23 bytes are used for the string because lowercase letters are two bytes each, except for i which is displayed as the imaginary unit token. [Answer] ## Batch file, 68 chars ``` :l @date/t|findstr/c:"-12-25">nul&&echo It's Christmas&&exit @goto l ``` Not usable interactively, as it kills the session. Solving that would require 5 more characters. Also locale-sensitive. This works on my locale which uses ISO 8601 date format. But hey, it's a batch file (by most not even regarded as a programming language). And shorter than Javascript (and on par with Python). [Answer] # Groovy, 55 ``` while(!new Date()==~/.*c 25.*/); println"It's Christmas" ``` Think it works, but still waiting for output. [Answer] ## (pdf)eTeX - 180 chars only December 1-25. ``` \lccode`m`~\let\e\expandafter\def~{\ifdim900pt<\pdfelapsedtime sp\pdfresettimer\else\e~\fi}\lowercase\e{\e\scantokens\e {\romannumeral\numexpr (25 - \day)*96000}}It's Christmas!\bye ``` TeX only has a way to access the date when the program starts, and the time elapsed since the start, capped at 32768 seconds, so I need to compute the number of seconds to wait, and for each second do a loop which waits for the elapsed time to reach `1s` and reset the time. (Precisely, I'm doing blocks of 900 seconds.) Working for any month requires more work: 355 chars. ``` \lccode`m=`~\let\o\or\let\y\year\let\n\numexpr\let\e\expandafter \def\b#1{\ifnum#1=\n(#1/4)*4\relax+1\fi}\def~{\ifdim 900pt<\pdfelapsedtime sp\pdfresettimer\else\e~\fi}\lowercase \e{\e\scantokens\e{\romannumeral\n(25-\day+\ifcase\month\o334\b\y \o303\b\y\o275\o244\o214\o183\o153\o122\o91\o61\o30\o0\ifnum25<\day 365\b{\n\y+1}\fi\fi)*96000}}It's Christmas!\bye ``` [Answer] ## MySQL, 180 chars Because what are you using your database engine for, anyway? ``` DELIMITER $$ CREATE FUNCTION c() RETURNS CHAR(14) BEGIN a: LOOP IF DAY(NOW())=25 && MONTH(NOW())=12 THEN RETURN 'It\'s Christmas'; END IF; END LOOP a; END$$ DELIMITER ; SELECT c(); ``` Not very competitive lengthwise, but hey, it's doable! [Answer] ## Ruby, 53 ``` until Time.now.to_s=~/c 25/ end puts"It's Christmas!" ``` [Answer] # PHP, 40 bytes ``` <?while(date(dm)-1225);?>It´s Christmas; ``` Loop until 25th of December; then exit to plain mode and print. Run with default settings (don´t display notices). [Answer] # 8086 machine code, 33 bytes ``` 00000000 b4 2a cd 21 81 fa 19 0c 75 f6 b4 09 ba 12 01 cd |.*.!....u.......| 00000010 21 c3 49 74 27 73 20 43 68 72 69 73 74 6d 61 73 |!.It's Christmas| 00000020 24 |$| 00000021 ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 84 bytes ``` : f begin time&date drop 12 = 0<> swap 25 = 0<> and until s" It's Christmas!" type ; ``` [Try it online!](https://tio.run/##Lce9CoAgFAbQV/lyqCmooKW/panHMNQSSsV7I3p6I2g6HOMj7@VmPlLqYLDqzTqwPXWuJGuo6APqBiOqYQLdMqBp/0mncDm2B0hg4YIw79ESn5IyAX6CRp9MegE "Forth (gforth) – Try It Online") Yet another stack language. Somehow not the longest answer. The `time&date` word is very convenient here. A stack overflow happens since time&date values are left on stack every iteration. [Answer] ## Javascript, ~~93~~ ~~89~~ ~~78~~ 77 chars `function x(){Date().match("c 25")?alert("It's Christmas"):setTimeout(x,1)}x()` [Answer] ## D, 130 ``` import std.datetime,std.stdio; main(){ do{ auto t = Clock.currTime(); }while(t.month!=12||t.day!=25); writeln("It's Christmas"); } ``` [Answer] ## Q, 63 chars ``` system"t 1000";.z.ts:{$["12.25"~-5#-3!.z.d;1"It's Christmas";]} ``` will work for christmas day on every year [Answer] # SQL\*Plus + PL/SQL - 100 ``` EXEC LOOP EXIT WHEN TO_CHAR(SYSDATE,'DDMM')='2512';END LOOP;DBMS_OUTPUT.put_line('It''s Christmas'); ``` * Assuming `SERVEROUTPUT ON` * Shorter then the MySql solution (eat that, MySql!) * Too late for last year, but in time for this year * Tried `DBMS_OUTPUT.put` instead of `DBMS_OUTPUT.put_line` but that doesn't print anything. [Answer] ## C# (126) ``` using System;class P{static void Main(){while(DateTime.Now.Date.ToString("Md")!="1225");Console.WriteLine("It's Christmas");}} ``` Nicer for your battery: ## C# (163) ``` using s=System;class P{static void Main(){s.Threading.Thread.Sleep(s.DateTime.ParseExact("1225","Md",null)-s.DateTime.Now);s.Console.WriteLine("It's Christmas");}} ``` *edit* The second ("nicer for your battery") version does have a bit of an issue dec. 26th to dec. 31st I just thought of :P Both versions can probably be shortened a bit more. [Answer] # VBA, 58 Bytes Anonymous VBE immediates window function that takes no input and runs until it's Christmas day, at which time it outputs `It's Christmas` to the VBE immediates window. ``` While Left(Now,5)<>"12/25":DoEvents:Wend:?"It's Christmas" ``` [Answer] # SmileBASIC, ~~49~~ 47 bytes ``` DTREAD OUT,M,D?"It's Christmas"*(M/D==.48)EXEC. ``` `month/day` will be `0.48` on December 25th. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ 21 bytes ``` [že25Qžf12Q&#}”It'sŒÎ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@ui@VCPTwKP70gyNAtWUax81zPUsUS8@Oulw3///AA "05AB1E – Try It Online") Noncompeting, I suppose(Beats the other non-competing answer, ha). My first 05AB1E answer. -7 bytes from ovs. ## Explanation ``` [že25Qžf12Q&#”It'sŒÎ [ start an infinite loop že push current day 25 25 Q are they equal? žf push current month 12 12 Q are they equal? & logical and # break if both conditions are true ”It'sŒÎ push "It's Christmas" implicit output ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` Ks f"c 25" ?`It's CËItµs`:P ``` To test against today's date : Replace `c 25` with this month's last letter (shorthand) + space + day of the month. `Feb 02` == `b 02` [Try it online!](https://tio.run/nexus/japt#@@9drJCmlKxgZKqkYO@fouRZol6s4Hy427Pk0NZiJQWrgP//AQ "Japt – TIO Nexus") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 23 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` (kNkM,¿⁺P¿Q)’It's ñẈmas ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPShrTmtNJTJDJUMyJUJGJUUyJTgxJUJBUCVDMiVCRlEpJUUyJTgwJTk5SXQncyUyMCVDMyVCMSVFMSVCQSU4OG1hcyZmb290ZXI9JmlucHV0PSZmbGFncz0=) #### Explanation ``` (kNkM,¿⁺P¿Q)’It's ñẈmas '# Full program ( ) # Loop until this returns false: kNkM, # Push [current month, current day] ¿⁺P¿Q # Not equal to [12, 25] ’It's ñẈmas '# Push "It's Christmas" # Implicit output ``` ]
[Question] [ You've seen the amazing [alphabet triangle](https://codegolf.stackexchange.com/questions/87496/alphabet-triangle?s=1%7C2.3157), the [revenge of the alphabet triangle](https://codegolf.stackexchange.com/questions/90497/alphabet-triangle-strikes-again) and now it's time for the revenge of the revenge of the alphabet triangle! **Introducing...** ***THE ALPHABET DIAMOND!*** Your task is to output this exact text, lowercase/uppercase does not matter, though newlines do: ``` bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb ``` ## This is code-golf, lowest bytecount wins. **Rules:** 1. Standard loopholes are disallowed. 2. `a` must be the center of the alphabet diamond. [Answer] # Vim, ~~62~~, 60 keystrokes ``` :se ri|h<_<cr>jjYZZPqqx$pYpq26@qdjyH:g/^/m0<cr>VP:%norm DPA<C-v><C-r>"<C-v><esc>x<cr> ``` Drawing on inspiration from [Lynn's awesome vim answer](https://codegolf.stackexchange.com/a/87010/31716) to take the idea of stealing the alphabet from the help docs. You can watch it happen in real time as I struggle to remember the right sequence of keystrokes! [![enter image description here](https://i.stack.imgur.com/iiHNg.gif)](https://i.stack.imgur.com/iiHNg.gif) Note that this gif is *slightly* outdated because it produces the wrong output, and I haven't gotten around to re-recording it yet. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` A27FÀDûˆ}¯û» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=QTI3RsOARMO7y4Z9wq_Du8K7&input=) **Explanation** ``` A # push alphabet 27F # 27 times do À # rotate alphabet left Dû # create a palendromized copy ˆ # add to global list } # end loop ¯ # push global list û # palendromize list » # merge list on newline # implicit output ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 14 bytes ``` 2Y226Zv27Zv!+) ``` [Try it online!](http://matl.tryitonline.net/#code=MlkyMjZadjI3WnYhKyk&input=) ``` 2Y2 % Push string 'abc...z' 26Zv % Push symmetric range [1 2 ... 25 26 25 ... 2 1] 27Zv % Push symmetric range [1 2 ... 25 26 27 26 25 ... 2 1] ! % Transpose into a column + % Addition with broadcast. Gives a matrix of all pairwise additions: % [ 2 3 ... 26 27 26 ... 3 2 3 4 ... 27 28 27 ... 4 3 ... 27 28 ... 51 52 51 ... 28 27 28 29 ... 52 53 52 ... 29 28 27 28 ... 51 52 51 ... 28 27 ... 2 3 ... 26 27 26 ... 3 2 ] ) % Index modularly into the string. Display implicitly ``` [Answer] # PHP, 129 Bytes ``` for(;++$i<27;)$o.=($s=($f=substr)($r=join(range(a,z)),$i,26-$i)).$t.strrev($s.$t=$f($r,0,$i))."\n";echo$o.$f($o,0,51).strrev($o); ``` [Answer] ## Haskell, 75 bytes ``` g=(++)<*>reverse.init unlines$g$g.take 26.($cycle['a'..'z']).drop<$>[1..27] ``` How it works: ``` g=(++)<*>reverse.init -- helper function that takes a list and appends the -- reverse of the list with the first element dropped, e.g. -- g "abc" -> "abcba" <$>[1..27] -- map over the list [1..27] the function that drop -- drops that many elements from ($cycle['a'..'z']) -- the infinite cycled alphabet and take 26 -- keeps the next 26 chars and g -- appends the reverse of itself -- now we have the first 27 lines g -- do another g to append the lower half unlines -- join with newlines ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 13 bytes ``` Øaṙ1ṭṙJ$ŒBŒḄY ``` [Try it online!](http://jelly.tryitonline.net/#code=w5hh4bmZMeG5reG5mUokxZJCxZLhuIRZ&input=) ## Explanation ``` Øaṙ1ṭṙJ$ŒBŒḄY Main link. No arguments Øa Get the lowercase alphabet ṙ1 Rotate left by 1 ṭ Append to $ Monadic chain J Indices of the alphabet [1, 2, ..., 26] ṙ Rotate the alphabet by each ŒB Bounce each rotation ŒḄ Bounce the rotations Y Join with newlines and print implicitly ``` [Answer] # C, 76 bytes Function, to be called as below. Prints capital letters. ``` f(i){for(i=2756;--i;)putchar(i%52?90-(abs(i%52-26)+abs(i/52-26)+25)%26:10);} //call like this main(){f();} ``` Simple approach, add the x and y distances from the centre of the square, plus an offset of 25 for the `a` in the middle, take modulo 26 and subract from `90`, the ASCII code for `Z`. Where `i%52`==0 a newline ASCII `10` is printed. [Answer] # R, 71 bytes ``` cat(letters[outer(c(1:27,26:1),c(0:25,24:0),"+")%%26+1],sep="",fill=53) ``` `outer` creates a matrix with the indices of the letters, `letters[...]` then creates a vector with the correct letters in. `cat(...,sep="",fill=53)` then prints it out with the desired formatting. [Answer] # Jelly, 11 bytes ``` 27RØaṙŒḄŒBY ``` Explanation: ``` 27R range of 1...27 Øa the alphabet ṙ rotate ŒḄŒB bounce in both dimensions Y join on newline ``` [Answer] # Python 2, ~~96~~ 85 bytes Printing the uppercase version (saves 1 byte). ``` R=range for i in R(53):print''.join(chr(90-(abs(j-25)+abs(i-26)-1)%26)for j in R(51)) ``` previous solution with help from muddyfish ``` s="abcdefghijklmnopqrstuvwxyz"*3 for i in range(53):j=min(i,52-i);print s[j+1:j+27]+s[j+25:j:-1] ``` [Answer] ## Perl, 77 bytes Requires `-E` at no extra cost. Pretty standard approach... I don't like the calls to reverse I think there's likely a more maths based approach to this, will see how I get on! ``` @a=((a..z)x3)[$_..$_+26],$a=pop@a,(say@a,$a,reverse@a)for 1..26,reverse 1..25 ``` ### Usage ``` perl -E '@a=((a..z)x3)[$_..$_+26],$a=pop@a,(say@a,$a,reverse@a)for 1..26,reverse 1..25' ``` [Answer] # JavaScript (ES6), ~~97~~ 96 bytes *Saved 1 byte thanks to @user81655* ``` R=(n,s=25,c=(n%26+10).toString(36))=>s?c+R(n+1,s-1)+c:c C=(n=1,r=R(n))=>n<27?r+` ${C(n+1)} `+r:r ``` Two recursive functions; `C` is the one that outputs the correct text. Try it here: ``` R=(n,s=25,c=(n%26+10).toString(36))=>s?c+R(n+1,s-1)+c:c C=(n=1,r=R(n))=>n<27?r+` ${C(n+1)} `+r:r console.log(C()) ``` [Answer] # Python 3, 119 bytes I tried to exploit the two symmetry axes of the diamond, but this ended up more verbose than [Karl Napf's solution](https://codegolf.stackexchange.com/a/97445/20929). ``` A='abcdefghijklmnopqrstuvwxyz' D='' for k in range(1,27): D+=A[k:]+A[:k] D+=D[-2:-27:-1]+'\n' print(D+D[:51]+D[::-1]) ``` [Answer] # Haskell, ~~67~~ 66 bytes ``` unlines[[toEnum$mod(-abs j-abs i)26+97|j<-[-25..25]]|i<-[-26..26]] ``` [Answer] ## C, 252 bytes ``` #define j q[y] #define k(w,v) (v<'z')?(w=v+1):(w=97) char q[28][52],d;main(){int y,x=1;y=1;j[0]=98;j[50]=98;for(;y<27;y++){for(;x<26;x++){(x<1)?(k(d,q[y-1][50])):(k(d,j[x-1]));j[50-x]=d;j[x]=d;}x=0;j[51]=0;puts(j);}strcpy(j,q[1]);for(;y;y--)puts(j);} ``` Formatted, macro-expanded version, which is hopefully more intelligible: ``` #define j q[y] #define k(w,v) (v<'z')?(w=v+1):(w=97) char q[28][52],d; main(){ int y,x=1; y=1; q[1][0]=98;q[1][50]=98; //98 takes one less byte to type than the equivalent 'b' for(;y<27;y++){ for(;x<26;x++){ (x<1)? (k(d,q[y-1][50])) :(k(d,q[y][x-1])); q[y][50-x]=d; q[y][x]=d; } x=0; q[y][51]=0; puts(q[y]); } strcpy(q[y],q[1]); for(;y;y--)puts(q[y]); } ``` I know this can't win, but I had fun trying. This is my first ever attempt at code golf. [Answer] ## Batch, 255 bytes ``` @echo off set l=abcdefghijklmnopqrstuvwxyz set r=yxwvutsrqponmlkjihgfedcba for /l %%i in (1,1,27)do call:u for /l %%i in (1,1,25)do call:l :l set r=%r:~2%%l:~-1%. set l=%l:~-2%%l:~0,-2% :u set r=%l:~-1%%r:~0,-1% set l=%l:~1%%l:~0,1% echo %l%%r% ``` Explanation: The subroutine `u` rotates the alphabet outwards by one letter from the centre, which is the pattern used in the top half of the desired output. The subroutine `l` rotates the alphabet inwards by two letters. It then falls through into the `u` subroutine, achieving an effective single letter inward rotation. Finally the last line is printed by allowing the code to fall through into the `l` subroutine. [Answer] ## Pyke, ~~23~~ ~~22~~ 21 bytes ``` GV'th+jj_t+j)K]0n'JOX ``` [Try it here!](http://pyke.catbus.co.uk/?code=GV%27th%2Bjj_t%2Bj%29K%5D0n%27JOX&warnings=0) ``` GV ) - repeat 26 times, initially push alphabet. 'th+ - push tos[1:]+tos[0] j - j = tos j - push j _t+ - push pop+reversed(pop)[1:] j - push j K - pop ]0 - list(stack) n'JOX - print "\n".join(^), - splat ^[:-1] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 21 bytes *-3 bytes thanks to ASCII-only.* ``` F²⁷«P✂×β³⊕ι⁺ι²⁷↓»‖B↓→ ``` [Try it online!](https://tio.run/##JYoxDsIwDAD3vMKjTdOlDEgdEStLeUEbJdSS1aDgtkKIt5tIveGWuzCPJeRRzFIugN2F4Ougcl9F@VV4UXwIh4gnnDycyUPTcBVW1ZvouPMWsb/lfSH3c26ISWLQ66oaS5LPkTz0Az9nJTNrN2vf8gc "Charcoal – Try It Online") Link is to verbose version. ...I need to work on my Charcoal-fu. :P [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 64 bytes ``` 1..27+26..1|%{$y=$_ -join(0..25+24..0|%{[char](97+($_+$y)%26)})} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz8hc28hMT8@wRrVapdJWJZ5LNys/M0/DAChjqm1koqdnAJSJTs5ILIrVsDTX1lCJ11ap1FQ1MtOs1az9/x8A "PowerShell – Try It Online") [Answer] ## C++, ~~191~~ ~~179~~ ~~166~~ ~~165~~ 139 bytes -12 bytes thanks to Kevin Cruijssen -14 bytes thanks to Zacharý -26 bytes thanks to ceilingcat ``` #import<cstdio> #define C j;)putchar(97+j main(){for(int i=0,j,d=1;i<53;d+=i++/26?-1:1){for(j=d;26+d>C++%26);for(j--;d<=--C%26);puts("");}} ``` [Answer] # JavaScript (ES6), ~~128~~ ~~115~~ 114 bytes ``` a='abcdefghijklmnopqrstuvwxyz' for(o=[i=27];i--;)o[26-i]=o[26+i]=(a=(p=a.slice(1))+a[0])+[...p].reverse().join`` o ``` [Answer] # Groovy - 103 97 bytes I realise there are cleverer ways of doing this but... ``` {t=('a'..'z').join();q={it[-2..0]};c=[];27.times{t=t[1..-1]+t[0];c<<t+q(t)};(c+q(c)).join('\n')} ``` When run the result of the script is the requested answer. (Thanks to [carusocomputing](https://codegolf.stackexchange.com/users/59376/carusocomputing) for the tip on saving 7 bytes). Updated example accordingly on: See <http://ideone.com/MkQeoW> [Answer] ## Racket 293 bytes ``` (let*((ls list->string)(rr reverse)(sr(λ(s)(ls(rr(string->list s))))))(let p((s(ls(for/list((i(range 97 123)))(integer->char i)))) (n 0)(ol'()))(let*((c(string-ref s 0))(ss(substring s 1 26))(s(string-append ss(string c)(sr ss))))(if(< n 53)(p s(+ 1 n)(cons s ol)) (append(rr ol)(cdr ol)))))) ``` Ungolfed: ``` (define (f) (define (sr s) ; sub-fn reverse string; (list->string (reverse (string->list s)))) (let loop ((s (list->string (for/list ((i (range 97 123))) (integer->char i)))) (n 0) (ol '())) (define c (string-ref s 0)) (define ss (substring s 1 26)) (set! s (string-append ss (string c) (sr ss))) (if (< n 53) (loop s (add1 n) (cons s ol)) (append (reverse ol) (rest ol))))) ``` Testing: ``` (f) ``` Output: ``` '("bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb" "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc" "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed" "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe" "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf" "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg" "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih" "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji" "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj" "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk" "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml" "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm" "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon" "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo" "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp" "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq" "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr" "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts" "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut" "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu" "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv" "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw" "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx" "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy" "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz" "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb" "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc" "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed" "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe" "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf" "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg" "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih" "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji" "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj" "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk" "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml" "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm" "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon" "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo" "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp" "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq" "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr" "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts" "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut" "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu" "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv" "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw" "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx" "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy" "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz" "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb" "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz" "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy" "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx" "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw" "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv" "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu" "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut" "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts" "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr" "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq" "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp" "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo" "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon" "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm" "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml" "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk" "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj" "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji" "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih" "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg" "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf" "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe" "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed" "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc" "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb" "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" "zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz" "yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy" "xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx" "wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw" "vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv" "uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu" "tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut" "stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts" "rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr" "qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq" "pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp" "opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo" "nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon" "mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm" "lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml" "klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk" "jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj" "ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji" "hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih" "ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg" "fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf" "efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe" "defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed" "cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc" "bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb") ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~21~~ 19 bytes ``` j+PKm+PJ.<Gd_JS27_K ``` [Try it online!](https://tio.run/##K6gsyfj/P0s7wDtXO8BLz8Y9Jd4r2Mg83vv/fwA "Pyth – Try It Online") **Explanation:** ``` j+PKm+PJ.<Gd_JS27_K expects no input j joins on new line + + joins two strings P P prints everything but the last element K initialize K and implicitly print m for...in loop, uses d as iterator variable J initialize J and implicitly print .< cyclically rotate G initialized to the lowercase alphabet d iterating variables of m _ _ reverse J call J S27 indexed range of 27 K call K ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 10 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` zl{«:}«¹╬, ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=emwlN0IlQUIlM0ElN0QlQUIlQjkldTI1NkMlMkM_) Explanation: ``` z push the lowercase alphabet l{ } repeat length times « put the 1st letter at the end : duplicate « put the 1st letter at the end (as the last thing called is duplicate) ¹ wrap the stack in an array ╬, quad-palindromize with 1 X and Y overlap ``` [Answer] # [Kotlin](https://kotlinlang.org), 106 bytes ``` {(0..52).map{i->(0..50).map{j->print((90-((Math.abs(j-25)+Math.abs(i-26)-1)+26)%26).toChar())} println()}} ``` ## Beautified ``` { (0..52).map {i-> (0..50).map {j-> print((90 - ((Math.abs(j - 25) + Math.abs(i - 26) - 1)+26) % 26).toChar()) } println() } } ``` ## Test ``` var v:()->Unit = {(0..52).map{i->(0..50).map{j->print((90-((Math.abs(j-25)+Math.abs(i-26)-1)+26)%26).toChar())} println()}} fun main(args: Array<String>) { v() } ``` [TryItOnline](https://tio.run/##PYvBCsIwEETv@YpchF3KhlqoYKkB8exJ/ID1YJvapiWNBSn59hgqOPAYHsy8Rt8bGxd2cqkASd@t8fIUV8iVKgtUA0@rIb1p/tOO9OSM9QDHnACu7FvFjxk6KkrM/mqoOCDtMUu1Syg/Xlp2gBjE9u8tYAjx@bZyYGOBXTNX8uwcf@qbT4tGo1yFTFkARRDxCw) Port of [@Karl Napf](https://codegolf.stackexchange.com/users/53667/karl-napf)'s answer [Answer] **VBA (Excel) , 116 Bytes** ``` Sub a() For i=-26To 26 For j=-25To 25 b=b & Chr(65+(52-(Abs(j)+Abs(i))) Mod 26) Next Debug.Print b b="" Next End Sub ``` Following Sir Joffan's Logic. :D [Answer] # VBA, ~~109~~ ~~105~~ 78 Bytes Anonymous VBE immediate window function that takes no input and outputs the alphabet diamond to the VBE immediate window. ``` For i=-26To 26:For j=-25To 25:?Chr(65+(52-(Abs(j)+Abs(i)))Mod 26);:Next:?:Next ``` [Answer] # [uBASIC](https://github.com/EtchedPixels/ubasic), 86 bytes ``` 0ForI=-26To26:ForJ=-25To25:?Left$(Chr$(65+(52-(Abs(J)+Abs(I)))Mod26),1);:NextJ:?:NextI ``` [Try it online!](https://tio.run/##K01KLM5M/v/fwC2/yNNW18gsJN/IzArI8QJyTIEcUyt7n9S0EhUN54wiFQ0zU20NUyNdDcekYg0vTW0Q5ampqembn2JkpqljqGlt5ZdaUeJlZQ@mPf//BwA "uBASIC – Try It Online") [Answer] # [MY-BASIC](https://github.com/paladin-t/my_basic), 89 bytes Anonymous function that takes no input and outputs to the console. ``` For i=-26 To 26 For j=-25 To 25 Print Chr(65+(52-(Abs(j)+Abs(i)))Mod 26) Next Print; Next ``` [Try it online!](https://tio.run/##y63UTUoszkz@/98tv0gh01bXyEwhJF/ByIwLxM8C8k3BfFOugKLMvBIF54wiDTNTbQ1TI10Nx6RijSxNbRCVqamp6ZufAtSnyeWXWlECUW0NZv//DwA "MY-BASIC – Try It Online") ]
[Question] [ There are more than 100 elements in the modern periodic table. You challenge is to output the rounded mass of an element with respect to the input given. # Input * Input will contain an abbreviation of an element. * Input can be taken from any one of the following: + `stdin` + command-line arguments + function arguments * Input will contain a one or two letter abbreviation of an element. The first character is always an uppercase letter and the second character, if any, will be a lowercase letter. # Output * Output the mass of the element entered * Output must be in the stdout or closest equivalent. * Output may contain a trailing newline character # Elements and their masses Here is the list of abbreviation of elements and their masses: ``` Sl.No Elements Abbreviation Mass 1 Hydrogen H 1 2 Helium He 4 3 Lithium Li 7 4 Beryllium Be 9 5 Boron B 11 6 Carbon C 12 7 Nitrogen N 14 8 Oxygen O 16 9 Fluorine F 19 10 Neon Ne 20 11 Sodium Na 23 12 Magnesium Mg 24 13 Aluminium Al 27 14 Silicon Si 28 15 Phosphorus P 31 16 Sulfur S 32 17 Chlorine Cl 35 18 Argon Ar 40 19 Potassium K 39 20 Calcium Ca 40 21 Scandium Sc 45 22 Titanium Ti 48 23 Vanadium V 51 24 Chromium Cr 52 25 Manganese Mn 55 26 Iron Fe 56 27 Cobalt Co 59 28 Nickel Ni 59 29 Copper Cu 64 30 Zinc Zn 65 31 Gallium Ga 70 32 Germanium Ge 73 33 Arsenic As 75 34 Selenium Se 79 35 Bromine Br 80 36 Krypton Kr 84 37 Rubidium Rb 85 38 Strontium Sr 88 39 Yttrium Y 89 40 Zirconium Zr 91 41 Niobium Nb 93 42 Molybdenum Mo 96 43 Technetium Tc 98 44 Ruthenium Ru 101 45 Rhodium Rh 103 46 Palladium Pd 106 47 Silver Ag 108 48 Cadmium Cd 112 49 Indium In 115 50 Tin Sn 119 51 Antimony Sb 122 52 Tellurium Te 128 53 Iodine I 127 54 Xenon Xe 131 55 Cesium Cs 133 56 Barium Ba 137 57 Lanthanum La 139 58 Cerium Ce 140 59 Praseodymium Pr 141 60 Neodymium Nd 144 61 Promethium Pm 145 62 Samarium Sm 150 63 Europium Eu 152 64 Gadolinium Gd 157 65 Terbium Tb 159 66 Dysprosium Dy 163 67 Holmium Ho 165 68 Erbium Er 167 69 Thulium Tm 169 70 Ytterbium Yb 173 71 Lutetium Lu 175 72 Hafnium Hf 178 73 Tantalum Ta 181 74 Tungsten W 184 75 Rhenium Re 186 76 Osmium Os 190 77 Iridium Ir 192 78 Platinum Pt 195 79 Gold Au 197 80 Mercury Hg 201 81 Thallium Tl 204 82 Lead Pb 207 83 Bismuth Bi 209 84 Polonium Po 209 85 Astatine At 210 86 Radon Rn 222 87 Francium Fr 223 88 Radium Ra 226 89 Actinium Ac 227 90 Thorium Th 232 91 Protactinium Pa 231 92 Uranium U 238 93 Neptunium Np 237 94 Plutonium Pu 244 95 Americium Am 243 96 Curium Cm 247 97 Berkelium Bk 247 98 Californium Cf 251 99 Einsteinium Es 252 100 Fermium Fm 257 ``` Yes. Your code only needs to deal with elements having atomic number 0-100 as seen in the table above. # Rules * [Standard loopholes are disallowed](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), as is fetching the data from built-ins * You may write a full program, or a function. # Test Cases ``` O --> 16 Sn --> 119 H --> 1 Fm --> 257 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins. [Answer] # CJam, ~~219~~ ~~213~~ 211 bytes ``` " b$2#ÐÇ°aë#ëG0ÚÛ;½_+â¨9¨%ôº¯ó¾Ù""ÏѯÀcKÌA6ïõÃVå%x²XßM³0øUà°ÅæM¨Ã([©bþÚðÐÔ×¼&Và«òð×øùÚ¼5·¹IõÉðѧé°i9õÛ[&i÷jͶû_<-c-uîá¹¹»D+èF"]256fb~26b'Af+2/'Jf-reua#__.0042*2.2+*i4-@Ab@=+ ``` [Try it online](http://cjam.aditsu.net/#code=%22%0Ab%242%C2%9F%23%C3%90%C3%87%C2%B0%18%C2%86a%0F%C3%AB%23%C3%ABG%070%C3%9A%11%C3%9B%3B%C2%BD_%2B%C3%A2%C2%A89%C2%A8%14%25%C3%B4%1D%C2%BA%C2%8E%C2%AF%C3%B3%C2%BE%C2%86%C2%8C%C3%99%22%22%04%C3%8F%C3%91%C2%AF%C3%80cK%C3%8CA6%C3%AF%C2%8C%C3%B5%C3%83%11V%C3%A5%13%25x%C2%B2X%C3%9FM%C2%B3%C2%930%14%C3%B8U%C3%A0%C2%B0%C3%85%C3%A6M%C2%A8%C3%83%08%C2%9A%28%C2%8F%5B%C2%A9%C2%81b%13%C3%BE%C3%9A%C3%B0%C3%90%C3%94%C3%97%C2%93%C2%BC%26%05V%C3%A0%C2%81%C2%AB%C3%B2%C3%B0%C3%97%C3%B8%C3%B9%1A%C3%9A%C2%89%C2%BC5%C2%B7%C2%B9I%C3%B5%C2%87%04%C3%89%C3%B0%C3%91%C2%A7%C2%9D%13%C3%A9%C2%B0i9%C3%B5%C3%9B%5B%C2%9F%26i%C3%B7j%C3%8D%C2%80%C2%B6%C3%BB_%3C%C2%84-%1Fc-u%C3%AE%C3%A1%C2%80%C2%B9%C2%B9%C2%BB%C2%92D%2B%C3%A8%08F%22%5D256fb~26b'Af%2B2%2F'Jf-reua%23__.0042*2.2%2B*i4-%40Ab%40%3D%2B&input=Th). Because of unprintables, the permalink might not work in all browsers. For the two long strings the code points are ``` [10 98 36 50 159 35 208 199 176 24 134 97 15 235 35 235 71 7 48 218 17 219 59 189 95 43 226 168 57 168 20 37 244 29 186 142 175 243 190 134 140 217] [4 207 209 175 192 99 75 204 65 54 239 140 245 195 17 86 229 19 37 120 178 88 223 77 179 147 48 20 248 85 224 176 197 230 77 168 195 8 154 40 143 91 169 129 98 19 254 218 240 208 212 215 147 188 38 5 86 224 129 171 242 240 215 248 249 26 218 137 188 53 183 185 73 245 135 4 201 240 209 167 157 19 233 176 105 57 245 219 91 159 38 105 247 106 205 128 182 251 95 60 132 45 31 99 45 117 238 225 128 185 185 187 146 68 43 232 8 70] ``` respectively. The program uses the quadratic regression `mass ~ floor(2.2(a-1) + 0.0042(a-1)^2)`, where `a` is atomic number. The reason for the `a-1` is because of 0-indexing. This regression gives an error range of `[-4, 5]`, which allows a base 10 encoding of the offsets. Mathematica code for the regression: ``` data = {{0, 1}, {1, 4}, {2, 7}, {3, 9}, {4, 11}, {5, 12}, {6, 14}, {7, 16}, {8, 19}, {9, 20}, {10, 23}, {11, 24}, {12, 27}, {13, 28}, {14, 31}, {15, 32}, {16, 35}, {17, 40}, {18, 39}, {19, 40}, {20, 45}, {21, 48}, {22, 51}, {23, 52}, {24, 55}, {25, 56}, {26, 59}, {27, 59}, {28, 64}, {29, 65}, {30, 70}, {31, 73}, {32, 75}, {33, 79}, {34, 80}, {35, 84}, {36, 85}, {37, 88}, {38, 89}, {39, 91}, {40, 93}, {41, 96}, {42, 98}, {43, 101}, {44, 103}, {45, 106}, {46, 108}, {47, 112}, {48, 115}, {49, 119}, {50, 122}, {51, 128}, {52, 127}, {53, 131}, {54, 133}, {55, 137}, {56, 139}, {57, 140}, {58, 141}, {59, 144}, {60, 145}, {61, 150}, {62, 152}, {63, 157}, {64, 159}, {65, 163}, {66, 165}, {67, 167}, {68, 169}, {69, 173}, {70, 175}, {71, 178}, {72, 181}, {73, 184}, {74, 186}, {75, 190}, {76, 192}, {77, 195}, {78, 197}, {79, 201}, {80, 204}, {81, 207}, {82, 209}, {83, 209}, {84, 210}, {85, 222}, {86, 223}, {87, 226}, {88, 227}, {89, 232}, {90, 231}, {91, 238}, {92, 237}, {93, 244}, {94, 243}, {95, 247}, {96, 247}, {97, 251}, {98, 252}, {99, 257}}; parabola = Fit[data, {1, x, x^2}, x] Show[ListPlot[data, PlotMarkers -> {Automatic, Tiny}], Plot[parabola, {x, 0, 100}], Frame -> True] ``` Which gives: ``` -0.019569 + 2.20617 x + 0.00417056 x^2 ``` [![enter image description here](https://i.stack.imgur.com/GqDeA.png)](https://i.stack.imgur.com/GqDeA.png) [Answer] # CJam, ~~175~~ 174 bytes ``` 0000000: 7232316222faaf6c3e227b693138302b257d2f296322 r21b"..l>"{i180+%}/)c" 0000016: 0221dce3cc4eb9561f953aaf640771c048ca3b9926c1 .!...N.V..:.d.q.H.;.&. 000002c: 4d033768588e2545069a202e128f0e238546134bdb31 M.7hX.%E.. ....#.F.K.1 0000042: c2e9e6924a7a8642dab33d6b789009112b5a8a652dd3 ....Jz.B..=kx...+Z.e-. 0000058: 7dbf0f0b27eb18e52808e857967bd7be4ce2545181b8 }...'...(..W.{..L.TQ.. 000006e: 01101447504f4443c6392449222322f43a606ce335e0 ...GPODC.9$I"#".:`l.5. 0000084: 4356e76914357218e3942869eb8ab3f97e2e161ef061 CV.i.5r...(i....~....a 000009a: 59c310c6cbe922323538623762364365723e3a2b Y....."258b7b6Cer>:+ ``` The above is a reversible xxd dump. You can try the code online in the [CJam interpreter](http://cjam.aditsu.net/#code=r21b%22%C3%BA%C2%AFl%3E%22%7Bi180%2B%25%7D%2F)c%22%02!%C3%9C%C3%A3%C3%8CN%C2%B9V%1F%C2%95%3A%C2%AFd%07q%C3%80H%C3%8A%3B%C2%99%26%C3%81M%037hX%C2%8E%25E%06%C2%9A%20.%12%C2%8F%0E%23%C2%85F%13K%C3%9B1%C3%82%C3%A9%C3%A6%C2%92Jz%C2%86B%C3%9A%C2%B3%3Dkx%C2%90%09%11%2BZ%C2%8Ae-%C3%93%7D%C2%BF%0F%0B'%C3%AB%18%C3%A5(%08%C3%A8W%C2%96%7B%C3%97%C2%BEL%C3%A2TQ%C2%81%C2%B8%01%10%14GPODC%C3%869%24I%22%23%22%C3%B4%3A%60l%C3%A35%C3%A0CV%C3%A7i%145r%18%C3%A3%C2%94(i%C3%AB%C2%8A%C2%B3%C3%B9~.%16%1E%C3%B0aY%C3%83%10%C3%86%C3%8B%C3%A9%22258b7b6Cer%3E%3A%2B&input=Pt). If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/Y1pscnmg). In supported browsers, you can [verify all test cases](http://cjam.aditsu.net/#code=qN%2F%7BS%25~21b%22%C3%BA%C2%AFl%3E%22%7Bi180%2B%25%7D%2F)c%22%02!%C3%9C%C3%A3%C3%8CN%C2%B9V%1F%C2%95%3A%C2%AFd%07q%C3%80H%C3%8A%3B%C2%99%26%C3%81M%037hX%C2%8E%25E%06%C2%9A%20.%12%C2%8F%0E%23%C2%85F%13K%C3%9B1%C3%82%C3%A9%C3%A6%C2%92Jz%C2%86B%C3%9A%C2%B3%3Dkx%C2%90%09%11%2BZ%C2%8Ae-%C3%93%7D%C2%BF%0F%0B'%C3%AB%18%C3%A5(%08%C3%A8W%C2%96%7B%C3%97%C2%BEL%C3%A2TQ%C2%81%C2%B8%01%10%14GPODC%C3%869%24I%22%23%22%C3%B4%3A%60l%C3%A35%C3%A0CV%C3%A7i%145r%18%C3%A3%C2%94(i%C3%AB%C2%8A%C2%B3%C3%B9~.%16%1E%C3%B0aY%C3%83%10%C3%86%C3%8B%C3%A9%22258b7b6Cer%3E%3A%2B%60%3D%7D%25&input=1%20H%0A4%20He%0A7%20Li%0A9%20Be%0A11%20B%0A12%20C%0A14%20N%0A16%20O%0A19%20F%0A20%20Ne%0A23%20Na%0A24%20Mg%0A27%20Al%0A28%20Si%0A31%20P%0A32%20S%0A35%20Cl%0A39%20K%0A40%20Ar%0A40%20Ca%0A45%20Sc%0A48%20Ti%0A51%20V%0A52%20Cr%0A55%20Mn%0A56%20Fe%0A59%20Co%0A59%20Ni%0A64%20Cu%0A65%20Zn%0A70%20Ga%0A73%20Ge%0A75%20As%0A79%20Se%0A80%20Br%0A84%20Kr%0A85%20Rb%0A88%20Sr%0A89%20Y%0A91%20Zr%0A93%20Nb%0A96%20Mo%0A98%20Tc%0A101%20Ru%0A103%20Rh%0A106%20Pd%0A108%20Ag%0A112%20Cd%0A115%20In%0A119%20Sn%0A122%20Sb%0A127%20I%0A128%20Te%0A131%20Xe%0A133%20Cs%0A137%20Ba%0A139%20La%0A140%20Ce%0A141%20Pr%0A144%20Nd%0A145%20Pm%0A150%20Sm%0A152%20Eu%0A157%20Gd%0A159%20Tb%0A163%20Dy%0A165%20Ho%0A167%20Er%0A169%20Tm%0A173%20Yb%0A175%20Lu%0A178%20Hf%0A181%20Ta%0A184%20W%0A186%20Re%0A190%20Os%0A192%20Ir%0A195%20Pt%0A197%20Au%0A201%20Hg%0A204%20Tl%0A207%20Pb%0A209%20Bi%0A209%20Po%0A210%20At%0A222%20Rn%0A223%20Fr%0A226%20Ra%0A227%20Ac%0A231%20Pa%0A232%20Th%0A237%20Np%0A238%20U%0A243%20Am%0A244%20Pu%0A247%20Bk%0A247%20Cm%0A251%20Cf%0A252%20Es%0A257%20Fm) at once. ### Idea The actual weights are encoded in the same fashion as in [Martin Büttner's answer](https://codegolf.stackexchange.com/a/52265), with three minor modifications: * 12's are replaced with 6's instead of 7's. * The encoding is done in base 7 instead of base 8. * The order of the elements is reversed. The difference between our answers lies in how the element abbreviations are stored. In this approach, we hash all 100 element abbreviations into 8-bit characters, by doing the following: * Take the element name (treated as the array of its code points) and apply base 21 conversion. Examples: `"H"21b` yields **72**, `"He"21b` yields **1613 = 21 × 72 + 101**. * Successively compute the residue of the division by 430, 355, 288 and 242. Example: `1613 430% 355% 288% 242%` yields **35**. * Increment and cast to character. Example: `35)c` yields **$**. ### Code ``` r e# Read a whitespace-separated token from STDIN. 21b e# Convert to intger, using base 21 conversion. "ú¯l>" e# Push that string. {i180+%}/ e# Cast each char to integer, add 180 and apply modular division. )c e# Add 1 and cast to character. "!ÜãÌN¹V:¯dqÀHÊ;&ÁM7hX%E .#FKÛ1ÂéæJzBÚ³=kx +Ze-Ó}¿'ëå(èW{×¾LâTQ¸GPODCÆ9$I" e# Push that string. e# "He", e.g., is hashed to '$', which is the second char from the right. # e# Compute the index of the character hash in the string. "ô:`lã5àCVçi5rã(ië³ù~.ðaYÃÆËé" e# Push that string. 258b7b e# Convert from base 258 to base 7. 6Cer e# Replace 6's with 12's. > e# Keep only weight differences before the hashes occurrence. :+ e# Push the sum of the weight differences. ``` [Answer] # CJam, ~~201~~ 195 bytes ``` "üæ1Îe3©ü^<ùÉkIxX¯þÄäj¤ý¨,N8jËäVªw{®Ö_<U Zká++ØÙ/ªQÒ?»<yÙ>K_þÉ«2´EªÄ¡8ÕþÀ!-,ñ©ZÒàF"256b26b2/Gf-qeu'Af-a#)"#ØmÔwXÍÒA5(Wâ£ogg5ÂßòtwÆÚ^ØW¶°¥"258b8b7Cer<:+ ``` I'm sure there are a bunch of unprintable characters in there, so use [this permalink for testing](http://cjam.aditsu.net/#code=%22%04%C3%BC%C3%A61%C3%8Ee3%C2%A9%C3%BC%5E%3C%C3%B9%C3%89kI%C2%93x%C2%9C%C2%9BX%C2%AF%0C%C3%BE%C3%84%C3%A4j%C2%A4%C3%BD%C2%A8%2C%C2%97N%C2%888%1Fj%C3%8B%02%C3%A4V%C2%AA%C2%86w%7B%C2%8B%C2%AE%C3%96_%3C%10U%0A%C2%99Zk%C3%A1%2B%2B%C2%93%C2%96%C2%87%C3%98%C3%99%2F%C2%AAQ%C3%92%C2%85%C2%82%3F%C2%8C%C2%BB%13%C2%92%3C%C2%80%C2%92%18%C2%90y%C3%99%3EK%C2%99_%0F%C3%BE%C2%86%C3%89%C2%AB2%C2%B4E%13%C2%AA%C3%84%C2%9A%C2%A1%1B8%C3%95%C3%BE%C3%80!%C2%9F%0F%16%C2%82-%2C%C3%B1%1D%C2%A9Z%C2%8D%C3%92%C3%A0F%22256b26b2%2FGf-qeu'Af-a%23)%22%02%23%C3%98%C2%9Fm%C3%94%06wX%C3%8D%C2%84%C3%92A%1E%C2%915(W%C3%A2%C2%A3ogg5%C3%82%C3%9F%C3%B2tw%C3%86%C3%9A%5E%C3%98W%C2%B6%1A%C2%B0%C2%A5%22258b8b7Cer%3C%3A%2B&input=Mn). I used [this script](http://cjam.aditsu.net/#code=qN%2FSf%252f%3E%7B)~%2B(2'Qe%5Deua%5C%2B%7D%25%7BW%3D%7D%24z(s'Afm26bp%0A~0%5C%2B%7B_%40-%5C%7D*%3B%5DC7er8bp&input=1%20%20%20%20%20%20%20%20%20Hydrogen%20%20%20%20%20H%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%201%20%20%20%20%20%20%20%20%0A2%20%20%20%20%20%20%20%20%20Helium%20%20%20%20%20%20%20He%20%20%20%20%20%20%20%20%20%20%20%20%20%20%204%20%20%20%20%20%20%20%20%0A3%20%20%20%20%20%20%20%20%20Lithium%20%20%20%20%20%20Li%20%20%20%20%20%20%20%20%20%20%20%20%20%20%207%20%20%20%20%20%20%20%20%0A4%20%20%20%20%20%20%20%20%20Beryllium%20%20%20%20Be%20%20%20%20%20%20%20%20%20%20%20%20%20%20%209%20%20%20%20%20%20%20%20%0A5%20%20%20%20%20%20%20%20%20Boron%20%20%20%20%20%20%20%20B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2011%20%20%20%20%20%20%20%0A6%20%20%20%20%20%20%20%20%20Carbon%20%20%20%20%20%20%20C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2012%20%20%20%20%20%20%20%0A7%20%20%20%20%20%20%20%20%20Nitrogen%20%20%20%20%20N%20%20%20%20%20%20%20%20%20%20...%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20238%20%20%20%20%20%20%0A93%20%20%20%20%20%20%20%20Neptunium%20%20%20%20Np%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20237%20%20%20%20%20%20%0A94%20%20%20%20%20%20%20%20Plutonium%20%20%20%20Pu%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20244%20%20%20%20%20%20%0A95%20%20%20%20%20%20%20%20Americium%20%20%20%20Am%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20243%20%20%20%20%20%20%0A96%20%20%20%20%20%20%20%20Curium%20%20%20%20%20%20%20Cm%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20247%20%20%20%20%20%20%0A97%20%20%20%20%20%20%20%20Berkelium%20%20%20%20Bk%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20247%20%20%20%20%20%20%0A98%20%20%20%20%20%20%20%20Californium%20%20Cf%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20251%20%20%20%20%20%20%0A99%20%20%20%20%20%20%20%20Einsteinium%20%20Es%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20252%20%20%20%20%20%20%0A100%20%20%20%20%20%20%20Fermium%20%20%20%20%20%20Fm%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20257%20) to encode the abbreviations and masses as two numbers, and [this script](http://cjam.aditsu.net/#code=363180297747591790604930618402396129685962856524967156551691803198533587214560772335382797%20258b_%3Ae%3Ep_%2Cp%3Acp&input=Mn) to generate the base encoding. (These are mostly for myself if I need to change anything.) ## Explanation Of course, the main compression comes from base encoding: to compress any array, interpret it as digits in some sufficiently large base to get a single number - then get the base-256 (or similar) digits of that number and turn them into characters. That process is reversible, such that we can recover the array from that string. The above code contains two such base encodings: one for the abbreviations, and one for the masses. To make those two arrays more amenable to base encoding (i.e. to lower the base, as that makes the overall number and string significantly shorter), I did some preprocessing on the table. First, I sorted the entire table by masses to get a non-decreasing sequence. Then I computed the successive differences between those, because the sequence is rising rather slowly. In fact, the steps are always less than 13. That allows me to use base 13 (and then recover the masses by truncating that array to the correct length and summing all elements). However, we can do better: there is only a single 12, and the next smaller step is 6. So we can replace that 12 by a 7 and use base 8, which saves quite a bit. To encode the abbreviations, we pad the single-character elements with `Q` (which doesn't appear in any abbreviation), join them all together and take the difference with `A` or `a` (such that each letter becomes a number between `0` and `25` inclusive). This is then encoded in base 26. The abbreviations can be recovered by splitting the base-26 digits into pairs of 2 and removing all `16`s (which correspond to the `Q`s). Here is the code: ``` e# Decode the abbreviations "gibberish"256b26b e# Get the base-26 digits representing the letters. 2/ e# Split into pairs. Gf- e# Remove 16s (Qs). e# Process the input qeu e# Read input and convert to upper case. 'Af- e# Subtract the characters from 'A' to get numbers. a#) e# Find the position in the decoded array. e# Find the mass "gibberish"258b8b e# Get the base-8 digits representing the mass increments. 7Cer e# Replace the 7 by a 12. < e# Truncate, based on the position of the input in the abbreviations. :+ e# Sum all the increments. ``` [Answer] # Bash + coreutils, 381 ``` base64 -d<<<H4sICPGCjVUAA3B0LnR4dABNUMuShCAMvPcveQIEoUaQAtzdmf//kO2Ol7GKEJP0I2QAOTKcBfBMPALQgIu1hKZWc6gHb3dicgodkzGcDHjBjS04pZhEYmniB2Hwqg1JBOHaWrGRcOPTLDuEOdh107ARfhjhwPAqDLyBD2tNv5V+lvjHzZPlYif2MFJmKEY7Fac3hYIl8T+GYBqekqdDiOiSajt6fYzzivdji1zL8DvlM1UjZ5fNvVk/NZaTFtUCvzQjEVxUKGLti7aMK8vc0it1An3Z+gW38PUNvo8ww8FpN3SHla3VOh5DrqIrC3XzL9s2Ido6SBX/wOjUg78BAAA=|zcat|sed -n "/\b$1\b/I=" ``` This is simply the elements represented in a file thus: ``` H HE LI BE ... ``` Note the line number of the element corresponds with the mass. In cases where there are multiple elements with the same mass, the line looks like: ``` AR;CA ``` The file is gzipped and base64 encoded. Note the element names are all in upper case to improve compression. Interestingly gzip and bzip2 had identical compressed lengths, and xz was a little bit longer. The `base64 -d` and `zcat` simply convert the base64 stream back to this original file. The `sed` then simply searches (case insensitively) for the input string and outputs its line number. ### Test output: ``` $ for e in O Sn H Fm Ni Co; do ./pt.sh $e; done 16 119 1 257 59 59 $ ``` [Answer] # [Marbelous](https://github.com/marbelous-lang/marbelous.py), 1426 bytes ``` }0}1 LNLn =A RLSS =G=M=T=C=U=L=R=S P1P2P2P2P1P2P4P7 P0P4P1P2P9P7P0P5 P8P3P0P7//PNPNPN PNPNPNPN }0}1 LNLn =B RLSS =I=A=K=R=EP1 P2P1P2P8P9P1 P0P3P4P0PNPN P9P7//PN PNPN }0}1 LNLn =C RLSS =D=E=F=M=S=A=L=O=R=U P1P1P2P2P1P4P3P5P5P6P1 P1P4P5P4P3P0P5P9P2P4P2 P2P0P1P7P3PNPNPNPNPNPN PNPNPNPNPN }0}1 LNLn =E RLSS =R=S=U P1P2P1 P6P5// P7P2 PNPN }0}1 LNLn =F RLSS =M=R=E P2P2P5P1 P5P2P6P9 P7P3PNPN PNPN }0}1 LNLn =G RLSS =D=A=E P1P7P7 P5P0P3 P7PNPN PN }0}1 LNLn =H RLSS =F=G=O=E P1P2P1P4P1 P7P0P6PNPN P8P1P5 PNPNPN }0}1 LNLn =I RLSS P1 =N=R P1P9P2 P5P2P7 PNPNPN }0}1 LNLn >J <N RLSS =A=U=N=O=R=G=IP3 P1P1P5P9P8P2P7P9 P3P7P5P6P4//PNPN P9P5PNPNPN PNPN }0}1 LNLn =N RLSS =P=D=I=E=B=AP1 P2P1P5P2P9P2P4 P3P4P9P0P3//PN P7P4PNPNPN PNPN }0}1 LNLn =O RLSS P1 =S P9P6 P0PN PN }0}1 LNLn =P RLSS =U=A=O=B=T=M=D=R P2P2P2P2P1P1P1P1 P4P3P0P0P9P4P0P4P3 P4P1P9P7P5P5P6P1// PNPNPNPNPNPNPNPN }0}1 LNLn =R RLSS =N=H=U=A=E=B P2P1P1P2P1P8 P2P0P0P2P8P5 P2P3P1P6//PN PNPNPNPN }0}1 LNLn =S RLSS =M=B=N=E=C=R=IP3 P1P1P1P7P4P8P2P2 P5P2P1P9P5P8//PN P0P2P9PNPNPN PNPNPN }0}1 LNLn =T RLSS =H=L=A=E=B=M=C=I P2P2P1P1P1P1P9P4 P3P0P8P2P5P6P8// P2P4P1P8P9//PN PNPNPNPNPN }0}1 LNLn >X RLSS =B=R=N P1P9P6 P7P1P5 P3PNPN PN }0 LN =Y=X=W=V=U=D P8P1P1P5P2P1 P9P3P8P1P3P6 ..P1P4..P8P3 PNPNPNPNPNPN :P0 }0 {030 :P1 }0 {031 :P2 }0 {032 :P3 }0 {033 :P4 }0 {034 :P5 }0 {035 :P6 }0 {036 :P7 }0 {037 :P8 }0 {038 :P9 }0 {039 :PN }0 \/0A :LN }0 -Z -K {0 :Ln }0 -W -Z -K {0 :RLSS }1}0 {0\/ ``` Input is provided as two command line parameters. Marbelous does not currently have a way to handle variable length input and halt, so the second parameter is required. For one-letter symbols, just pass in any character as the second parameter, as long as it doesn't make a valid two-letter symbol. I hope to improve the language in the future to remove this limitation. Also, a bug in the python interpreter currently requires the `-m 0` parameter, as stdout is not being memoized correctly for functions. ``` # marbelous.py -m 0 mass.mbl H e 4 # marbelous.py -m 0 mass.mbl T a 181 ``` [Answer] ### Excel VBA, 1587 bytes So it isn't really a good golf attempt, I used a standard CASE statement, which looks like: ``` n = InputBox("n") Select Case n Case "H" m = 1 Case "He" m = 4 Case "Li" m = 7 ...... End Select ``` For all 100 elements specified in the question, it will read in the abbreviation and then display its weight in a message box. But what was interesting is instead of spending ages typing it all out, I used another bit of VBA to generate the CASE statement: ``` FilePath = Application.DefaultFilePath & "\code.txt" Open FilePath For Output As #2 For i = 3 To UsedRange.Rows.Count sentence = sentence + "Case " & Chr(34) & Cells(i, 3) & Chr(34) & vbNewLine & "m = " & Cells(i, 4) & vbNewLine Next i Print #2, sentence Close #2 ``` I copy and pasted the helpful table used in the question, the macro then reads the needed columns and pieces together the entire CASE statement used above. I used this guide to work out how to output to a text file: <http://www.homeandlearn.org/write_to_a_text_file.html> [Answer] # JavaScript ES6, 326 ``` s=>eval(`/${s}(\\d+)/.exec(btoa\`QÞ฻ïA×PµØÝx;^×Ó^ÛCZÛs Û%Û´¢ÛÃ÷Õ-ö ]ù¾4+BksSçP«çc'ç^ç ¨çÓbçЮëgëïAïp,ïïÐkóB«ó[ó«óÆ<õýÔÖýÜÊ=é7=ñµÓTa×MÏw]: tð'u×b'×^R]}I½vÙ7µÛÂ5ÛµÞ×}B³]÷­w춵ßÐׯ^55Ýxàùµã¦×»^vÝyí6õçÐò×­Ç£^¹½zí9µëÖ׽˻^ùý{ñ6µóUµó^×γ_t"½}Øûu÷.×ÞÇm5N]´àööÓ°bÛOO£m=ݵÑöÛakÛmÑkmºÍ¶í8vßcÚÛ}TÛ §mû>í¸à ¶ãp¦ÛÁn; ý¹ÔK6çafÛ\`)`)[1] ``` [JSFiddle](http://jsfiddle.net/hw5mjLon/), the special charecters keep having issues ~~I hate to use an object and then search through it but I'll try to golf this more when I get access to a computer~~. Updated Template Strings are the same length as regular strings so it doesn't matter. `.exec` actually stores the capture groups starting in `[1]` which adds another unavoidable 3 bytes, JavaScript's RegEx also doesn't support lookbehind but that wouldn't matter because that would be longer I'm using `atob` which is used to convert from Base64 but if you use it the other way, you can chop off about a hundred bytes [Answer] # Python 2, 405 401 bytes Call `w(e)` to print the weight of element e: ``` def w(e):import re;print reduce(lambda c,(_,d):c+int(d)-1,re.findall(r"(\D+)(\d+)",re.match(".*%s\d"%e,"H2He4Li4Be3B3C2N3O3F4Ne2Na4Mg2Al4Si2P4S2Cl4Ar6K0Ca2Sc6Ti4V4Cr2Mn4Fe2Co4Ni1Cu6Zn2Ga6Ge4As3Se5Br2Kr5Rb2Sr4Y2Zr3Nb3Mo4Tc3Ru4Rh3Pd4Ag3Cd5In4Sn5Sb4Te7I0Xe5Cs3Ba5La3Ce2Pr2Nd4Pm2Sm6Eu3Gd6Tb3Dy5Ho3Er3Tm3Yb5Lu3Hf4Ta4W4Re3Os5Ir3Pt4Au3Hg5Tl4Pb4Bi3Po1At2Rn13Fr2Ra4Ac2Th6Pa0U8Np0Pu8Am0Cm5Bk1Cf5Es2Fm6").group()),0) ``` Tests: ``` w("O") w("Sn") w("H") w("Fm") ``` Output: ``` 16 119 1 257 ``` **Updated** - now 401 bytes I was sure those nested regexs were too wordy, so I've managed to drop one of them, and put in a beautifully convoluted lambda instead :-) ``` def w(e):import re;print reduce(lambda(r,m),(l,d):(r+m*(int(d)-1),m*(l!=e)),re.findall(r"(\D+)(\d+)","H2He4Li4Be3B3C2N3O3F4Ne2Na4Mg2Al4Si2P4S2Cl4Ar6K0Ca2Sc6Ti4V4Cr2Mn4Fe2Co4Ni1Cu6Zn2Ga6Ge4As3Se5Br2Kr5Rb2Sr4Y2Zr3Nb3Mo4Tc3Ru4Rh3Pd4Ag3Cd5In4Sn5Sb4Te7I0Xe5Cs3Ba5La3Ce2Pr2Nd4Pm2Sm6Eu3Gd6Tb3Dy5Ho3Er3Tm3Yb5Lu3Hf4Ta4W4Re3Os5Ir3Pt4Au3Hg5Tl4Pb4Bi3Po1At2Rn13Fr2Ra4Ac2Th6Pa0U8Np0Pu8Am0Cm5Bk1Cf5Es2Fm6"),(0,1))[0] ``` [Answer] # Python 2 ~~364~~, ~~335~~, 324 bytes ## 3rd attempt Last program, which beats all non cjam entries. ``` #coding:latin1 c="ôÜÅÌ¿ß*[h̹IÊALu>-\ÏÃnay,ÃU[ŠáŠJðûC¢\rýÑÏR¬\0W¶°ò£w¿<M¹KŸ0I\fî1Ž[b¥!iÖœ­C>÷©€)rë>:öæö\nœèãbXñ0Èéà8J¯6sõ'ìA±+yï#»ÀÙ<Š=Ùï" n=sum([ord(c[i])*256**i for i in range(145)]) w=raw_input()+'q' s=1 while n and n%541!=ord(w[0])*21+ord(w[1])-1464: n/=541;s+=n%6;n/=6 print(s,s+7)[s>210] ``` ## 2nd attempt Here's a second tentative, but it's still not very statisfactory. I can get 335 bytes by first building a table 676 bits, then get the position of a pair of letters by counting the elements preceding it int the table, and finally get the mass using a 100 bytes table. Both tables are specified in latin1 in order to get values over 128. ``` #coding:latin1 w=raw_input()+'`' o=ord print(o("ájñ&IÐà ÏõN\n&nù!õ92>¡¥ú6ÿÝDG°Ç£}qŸ%R­5^[9ëŒåÍhÏÁòàSžeÜcx+MuV³`~æ.ʧì1¶W«?Y"[''.join(['{:08b}'.format(o(k))for k in "îóÃçuûüÇË/ÿÿÿßÿüŸ÷÷¿ìÿÿûÇ÷ÿýßÿÿÿýÿÿßßýÿïÏþ'~ÿßÿûø¿Öÿÿÿóo¿}.çÅÿ÷ÿÿþÿÿÿßÿÿÿßÿÿ_ÿÿÿÿ»ÿ"])[:o(w[0])*27+o(w[1])-1851].count('0')])+2,1)[w=='H`'] ``` ## 1st attempt 364 I think Python is a pretty good challenge for this game. I've tried to encode the different strings, but my decoder is always too big. And since python is very verbose and all characters appearing in the file have to be printable, it's pretty hard to get a small program. Here's my best solution so far: ``` w=raw_input() x='HqHeLiBeBqCqNqOqFqNeNaMgAlSiPqSqClKqCaArScTiVqCrMnFeNiCoCuZnGaGeAsSeBrKrRbSrYqZrNbMoTcRuRhPdAgCdInSnSbIqTeXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWqReOsIrPtAuHgTlPbBiPoAtRnFrRaAcPaThNpUqAmPuBkCmCfEsFm'.find((w,w+'q')[len(w)<2])/2 print (1,8)[x>84]+sum(map(int,str(int('2zbca9fh3fq7op0ta54q928z3xc5l7hp7yyu1in8al1iis2fkjt91pxi0kkgw94f',36)))[:x]) ``` which does not use big ideas, just the differences are encoded in base 6, then base 36, the maximum of int build-in. [Answer] # Python3, ~~856~~ 660 bytes ``` print(dict(H=1,He=4,Li=7,Be=9,B=11,C=12,N=14,O=16,F=19,Ne=20,Na=23,Mg=24,Al=27,Si=28,P=31,S=32,Cl=35,Ar=40,K=30,Ca=40,Sc=45,Ti=48,V=51,Cr=52,Mn=55,Fe=56,Co=58,Ni=58,Cu=64,Zn=65,Ga=70,Ge=73,As=75,Se=79,Br=80,Kr=84,Rb=85,Sr=88,Y=89,Zr=91,Nb=93,Mo=96,Tc=98,Ru=101,Rh=103,Pd=106,Ag=108,Cd=112,In=115,Sn=119,Sb=122,Te=128,I=127,Xe=131,Cs=133,Ba=137,La=139,Ce=140,Pr=141,Nd=144,Pm=145,Sm=150,Eu=152,Gd=157,Tb=159,Dy=163,Ho=165,Er=167,Tm=169,Yb=173,Lu=175,Hf=178,Ta=181,W=184,Re=186,Os=190,Ir=192,Pt=195,Au=197,Hg=201,Tl=204,Pb=207,Bi=209,Po=209,At=210,Rn=222,Fr=223,Ra=226,Ac=227,Th=232,Pa=231,U=238,Np=237,Pu=244,Am=243,Cm=247,Bk=247,Cf=251,Es=252,Fm=257)[input()]) ``` Thanks to [@Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000), I could save a whopping 196 bytes! Test it [here](http://rextester.com/YCXJ37171) --- Old version (856 bytes): ``` print({"H":1,"He":4,"Li":7,"Be":9,"B":11,"C":12,"N":14,"O":16,"F":19,"Ne":20,"Na":23,"Mg":24,"Al":27,"Si":28,"P":31,"S":32,"Cl":35,"Ar":40,"K":39,"Ca":40,"Sc":45,"Ti":48,"V":51,"Cr":52,"Mn":55,"Fe":56,"Co":59,"Ni":59,"Cu":64,"Zn":65,"Ga":70,"Ge":73,"As":75,"Se":79,"Br":80,"Kr":84,"Rb":85,"Sr":88,"Y":89,"Zr":91,"Nb":93,"Mo":96,"Tc":98,"Ru":101,"Rh":103,"Pd":106,"Ag":108,"Cd":112,"In":115,"Sn":119,"Sb":122,"Te":128,"I":127,"Xe":131,"Cs":133,"Ba":137,"La":139,"Ce":140,"Pr":141,"Nd":144,"Pm":145,"Sm":150,"Eu":152,"Gd":157,"Tb":159,"Dy":163,"Ho":165,"Er":167,"Tm":169,"Yb":173,"Lu":175,"Hf":178,"Ta":181,"W":184,"Re":186,"Os":190,"Ir":192,"Pt":195,"Au":197,"Hg":201,"Tl":204,"Pb":207,"Bi":209,"Po":209,"At":210,"Rn":222,"Fr":223,"Ra":226,"Ac":227,"Th":232,"Pa":231,"U":238,"Np":237,"Pu":244,"Am":243,"Cm":247,"Bk":247,"Cf":251,"Es":252,"Fm":257}[input()]) ``` [Answer] ## JavaScript 344 337 chars Code: Since it has some special chars and will not work when adding to to SO as a snippet, here is a link: <https://jsfiddle.net/stefnotch/gz3hu8bq/2/> Hexdump: ``` 0000000: 733d 3e61 6c65 7274 2852 6567 4578 7028 s=>alert(RegExp( 0000010: 6024 7b73 7d28 5c5c 5729 6029 2e65 7865 `${s}(\\W)`).exe 0000020: 6328 2248 7b48 657e 4c69 c281 4265 c283 c("H{He~Li..Be.. 0000030: 42c2 8543 c286 4ec2 884f c28a 46c2 8d4e B..C..N..O..F..N 0000040: 65c2 8e4e 61c2 914d 67c2 9241 6cc2 9553 e..Na..Mg..Al..S 0000050: 69c2 9650 c299 53c2 9a43 6cc2 9d41 72c2 i..P..S..Cl..Ar. 0000060: a24b c2a1 4361 c2a2 5363 c2a7 5469 c2aa .K..Ca..Sc..Ti.. 0000070: 56c2 ad43 72c2 ae4d 6ec2 b146 65c2 b243 V..Cr..Mn..Fe..C 0000080: 6fc2 b54e 69c2 b543 75c2 ba5a 6ec2 bb47 o..Ni..Cu..Zn..G 0000090: 61c3 8047 65c3 8341 73c3 8553 65c3 8942 a..Ge..As..Se..B 00000a0: 72c3 8a4b 72c3 8e52 62c3 8f53 72c3 9259 r..Kr..Rb..Sr..Y 00000b0: c393 5a72 c395 4e62 c397 4d6f c39a 5463 ..Zr..Nb..Mo..Tc 00000c0: c39c 5275 c39f 5268 c3a1 5064 c3a4 4167 ..Ru..Rh..Pd..Ag 00000d0: c3a6 4364 c3aa 496e c3ad 536e c3b1 5362 ..Cd..In..Sn..Sb 00000e0: c3b4 5465 c3ba 49c3 b958 65c3 bd43 73c3 ..Te..I..Xe..Cs. 00000f0: bf42 61c4 834c 61c4 8543 65c4 8650 72c4 .Ba..La..Ce..Pr. 0000100: 874e 64c4 8a50 6dc4 8b53 6dc4 9045 75c4 .Nd..Pm..Sm..Eu. 0000110: 9247 64c4 9754 62c4 9944 79c4 9d48 6fc4 .Gd..Tb..Dy..Ho. 0000120: 9f45 72c4 a154 6dc4 a359 62c4 a74c 75c4 .Er..Tm..Yb..Lu. 0000130: a948 66c4 ac54 61c4 af57 c4b2 5265 c4b4 .Hf..Ta..W..Re.. 0000140: 4f73 c4b8 4972 c4ba 5074 c4bd 4175 c4bf Os..Ir..Pt..Au.. 0000150: 4867 c583 546c c586 5062 c589 4269 c58b Hg..Tl..Pb..Bi.. 0000160: 506f c58b 4174 c58c 526e c598 4672 c599 Po..At..Rn..Fr.. 0000170: 5261 c59c 4163 c59d 5468 c5a2 5061 c5a1 Ra..Ac..Th..Pa.. 0000180: 55c5 a84e 70c5 a750 75c5 ae41 6dc5 ad43 U..Np..Pu..Am..C 0000190: 6dc5 b142 6bc5 b143 66c5 b545 73c5 b646 m..Bk..Cf..Es..F 00001a0: 6dc5 bb22 295b 315d 2e63 6861 7243 6f64 m..")[1].charCod 00001b0: 6541 7428 292d 3132 3229 0a eAt()-122). ``` Even more golfed: <https://jsfiddle.net/stefnotch/gz3hu8bq/4/> Hexdump: ``` 0000000: 733d 3e65 7661 6c28 602f 247b 737d 285c s=>eval(`/${s}(\ 0000010: 5c57 292f 2e65 7865 6328 2248 7b48 657e \W)/.exec("H{He~ 0000020: 4c69 c281 4265 c283 42c2 8543 c286 4ec2 Li..Be..B..C..N. 0000030: 884f c28a 46c2 8d4e 65c2 8e4e 61c2 914d .O..F..Ne..Na..M 0000040: 67c2 9241 6cc2 9553 69c2 9650 c299 53c2 g..Al..Si..P..S. 0000050: 9a43 6cc2 9d41 72c2 a24b c2a1 4361 c2a2 .Cl..Ar..K..Ca.. 0000060: 5363 c2a7 5469 c2aa 56c2 ad43 72c2 ae4d Sc..Ti..V..Cr..M 0000070: 6ec2 b146 65c2 b243 6fc2 b54e 69c2 b543 n..Fe..Co..Ni..C 0000080: 75c2 ba5a 6ec2 bb47 61c3 8047 65c3 8341 u..Zn..Ga..Ge..A 0000090: 73c3 8553 65c3 8942 72c3 8a4b 72c3 8e52 s..Se..Br..Kr..R 00000a0: 62c3 8f53 72c3 9259 c393 5a72 c395 4e62 b..Sr..Y..Zr..Nb 00000b0: c397 4d6f c39a 5463 c39c 5275 c39f 5268 ..Mo..Tc..Ru..Rh 00000c0: c3a1 5064 c3a4 4167 c3a6 4364 c3aa 496e ..Pd..Ag..Cd..In 00000d0: c3ad 536e c3b1 5362 c3b4 5465 c3ba 49c3 ..Sn..Sb..Te..I. 00000e0: b958 65c3 bd43 73c3 bf42 61c4 834c 61c4 .Xe..Cs..Ba..La. 00000f0: 8543 65c4 8650 72c4 874e 64c4 8a50 6dc4 .Ce..Pr..Nd..Pm. 0000100: 8b53 6dc4 9045 75c4 9247 64c4 9754 62c4 .Sm..Eu..Gd..Tb. 0000110: 9944 79c4 9d48 6fc4 9f45 72c4 a154 6dc4 .Dy..Ho..Er..Tm. 0000120: a359 62c4 a74c 75c4 a948 66c4 ac54 61c4 .Yb..Lu..Hf..Ta. 0000130: af57 c4b2 5265 c4b4 4f73 c4b8 4972 c4ba .W..Re..Os..Ir.. 0000140: 5074 c4bd 4175 c4bf 4867 c583 546c c586 Pt..Au..Hg..Tl.. 0000150: 5062 c589 4269 c58b 506f c58b 4174 c58c Pb..Bi..Po..At.. 0000160: 526e c598 4672 c599 5261 c59c 4163 c59d Rn..Fr..Ra..Ac.. 0000170: 5468 c5a2 5061 c5a1 55c5 a84e 70c5 a750 Th..Pa..U..Np..P 0000180: 75c5 ae41 6dc5 ad43 6dc5 b142 6bc5 b143 u..Am..Cm..Bk..C 0000190: 66c5 b545 73c5 b646 6dc5 bb22 295b 315d f..Es..Fm..")[1] 00001a0: 2e63 6861 7243 6f64 6541 7428 292d 3132 .charCodeAt()-12 00001b0: 3260 290a 2`). ``` It uses RegExp to find the appropriate char from the string then it converts to it's Unicode value and subtracts something. I wonder if this can be shortened even further. Credits: manatwork, vihan1086 ([Mass of elements](https://codegolf.stackexchange.com/questions/52257/mass-of-elements/52260#52260)) [Answer] # Rev 1, Ruby, 327 I'm fairly new to Ruby, so thanks to **ManAtWork** for refactoring and massively improving the code part of my program, for a saving of 42 bytes. ``` "1H3He3Li2Be2B1C2N2O3F1Ne3Na1Mg3Al1Si3P1S3Cl4K1Ar0Ca5Sc3Ti3V1Cr3Mn1Fe3Co0Ni5Cu1Zn5Ga3Ge2As4Se1Br4Kr1Rb3Sr1Y2Zr2Nb3Mo2Tc3Ru2Rh3Pd2Ag4Cd3In4Sn3Sb5I1Te3Xe2Cs4Ba2La1Ce1Pr3Nd1Pm5Sm2Eu5Gd2Tb4Dy2Ho2Er2Tm4Yb2Lu3Hf3Ta3W2Re4Os2Ir3Pt2Au4Hg3Tl3Pb2Bi0Po1At12Rn1Fr3Ra1Ac4Pa1Th5Np1U5Am1Pu3Cm0Bk4Cf1Es5Fm0"=~/#{gets}\d/ p eval($`.gsub /\D/,?+) ``` As far as I can tell, it works like this: the `=~` ("match") operator searches the data for an incidence of a string of type `/#{gets}\d/` where `#{gets}` is an element input by the user and `\d` can be any number. This returns the position/index where the element occurs in the big string, but the return value is thrown away. `$'` (not used here) is a special global variable which contains the part of the string to the right of the last match. `$`` is the complementary special global variable which contains the part of the string to the left of the last match. This is basically the truncated string from my rev 0. The remaining code to subsitute all the letters for `+`symbols and evaluate the expression formed works in the same way as my original answer, except that ManAtWork has improved my original `.gsub(/[A-z]/,'+')` to `.gsub /\D/,?+` # Rev 0, Ruby, 369 ``` s="1H3He3Li2Be2B1C2N2O3F1Ne3Na1Mg3Al1Si3P1S3Cl4K1Ar0Ca5Sc3Ti3V1Cr3Mn1Fe3Co0Ni5Cu1Zn5Ga3Ge2As4Se1Br4Kr1Rb3Sr1Y2Zr2Nb3Mo2Tc3Ru2Rh3Pd2Ag4Cd3In4Sn3Sb5I1Te3Xe2Cs4Ba2La1Ce1Pr3Nd1Pm5Sm2Eu5Gd2Tb4Dy2Ho2Er2Tm4Yb2Lu3Hf3Ta3W2Re4Os2Ir3Pt2Au4Hg3Tl3Pb2Bi0Po1At12Rn1Fr3Ra1Ac4Pa1Th5Np1U5Am1Pu3Cm0Bk4Cf1Es5Fm0" e=gets puts eval(s[0..s.gsub(/[0-9]/,'*').index(e+'*')-1].gsub(/[A-z]/,'+')) ``` The numbers in the string correspond to the difference between an element and the previous one (elements are in atomic mass order, not atomic number order, so the difference is always positive.) The first `gsub` replaces all numbers with `*`. Then we search for `<element name>+"*"` to find the index of the element (the appended `*` is necessary to avoid confusing for example, `Be` and `B` because one is a substring of the other.) The second `gsub` replaces all letters with `+`. This produces an expression that gives the mass of the element: `1+3++3++2...` (Ruby does not care about the duplicate `+`, presumably it considers the second `+` to be a unary `+`.) All that remains is to truncate the expression at the index mentioned above, and evaluate it. [Answer] # [Python 3](https://docs.python.org/3/), 560 bytes ``` import functools as f n="HᱨἬᨊBCNOFỆᶎỻ᭬∋PS᱄ᳲKᥣ’≴Vᷖ№ᮞᴍ῾ẟ⚬᫧ᰃᴳ₿ᵤⅦὤ⓶Y⠔ᷜⅣ⁼╺⅐ὀᨧᨬ὞⎪ῆℤI⊸ḙᤂ᳌ᩯ⎠Ṹ∐⍗ᾉᮼ ․ἸẺ⏄−⊼Ჰ῔W⁚⍽₂⑀ᶵ᳸⍰Ạᬒ⊰ᵴ⌼Ἤἒᤣ∠ṐU∠⒐ᮭᲇᮖ᪲ỿ᷎" m="!$')+,.03478;<?@CHGHMPSTWX[[`afikoptuxy{}€‚…‡ŠŒ“—š Ÿ£¥©«¬­°±¶¸½¿ÃÅÇÉÍÏÒÕØÚÞàãåéìïññòþÿĂăĈćĎčĔēėėěĜġ" i=lambda w:f.reduce(lambda l,c:l*ord(c),list(w),1) print(str(ord(m[n.find(chr(i(input())))])-32)) ``` [Try it online!](https://tio.run/##LU99a1JhHP3fT2ESdG/ZqBYUq1E0qEW0BqtWjCDTyS7pVfTKGhE4X6az6cy9NRvO0DW33Tnf5kyvXnie@0XO74vYHXTOHwfOORw4/iVlwSePDoeS1@8LKFZ3SHYqPp8naHUErW6LPG6bRL0CTUUl9WRi6tVT9FbQzqDXw6lKye/TM6jH0Gy8wEGJwru02nqLi22KbaNaQCsNfYDuPuVVnByiFkWrSREd52WK/0G/TBvt91TcxMUexUu0rNFWl@JZ9MOoHKKiol@gzDH0FYqVn1Oqg84uyhE013B0Rpki/nYomaX0DgarqGoUrlC4DK2DbpfWY5TMUUpDowZ9c5aW85TuUyRCP8Jon6PZoXQN3SJUs1TDeYvWtMuPWg7lEiXN6ewbUyiXRfUUjQSq2zhuoKfjImOzeMdtV65eE2/YR26N3r13/8HDR48nJp9NvpyeeT37bm7uo8Mtffb5ldCXpa/fWJhFWJwlWIqtsSzbYDssz4psn5XYATtiJ0xlp6zG6qzNOqzPdB7lcZ7gqzzN13mOb/GfPM8LvMhL/IAfcZWf8brJBh9w3YgYUSNpJIyMkTY2jQ1jx@QvY8/4bbNI4x6H95PLYV0cc48E5l0h57zw3/HYnWOe676AS3CKdo8UVIRF0X5btPgDkqwIQSUgXGbeOXnELclmaSEgSIIk@0OKIJr4IN4cvSOKw@GU4x8 "Python 3 – Try It Online") Explanation: So 2 variables, `n` and `m` are used to hold the abbreviations (more described below) and the elements atomic mass as strings. The input is then encrypted into a character to match to some character in `n`, using the string.find, an index of where the character is can be used to find the respective atomic mass in `m`. Due to shifting the mass values by 32 previously, they must be unshifted, then this number is output. Each character of `n` is the ascii of the product of the ascii values of the characters in the name Each character of `m` is the ascii of mass + 32 Below is the setup code for `m` and `n` ``` obfNames="" for name in names: prod=1 for c in name: prod*=ord(c) obfNames+=chr(prod) obfMass="" for m in mass: obfMass+=chr(int(m)+32) for c in obfNames: print(c,end="") print() for c in obfMass: print(c,end="") ``` [Try it online!](https://tio.run/##XZRLc9pAEITv/AqKE8Q@sCskJFdxEAoGKoApIA8n5QPmEaiERwE5@NcT5mthO/Ghd@np6XksZv9yWu22wfm8nW4Wx8aPUqd0Wyx1Foa9tWGTe9MgMxgYPBjc85HwYGrY/2mY/jYckzzkSi5sejD8BEHKeGY4QfwFGkV/SwG8sx0VkGR/DL8TbWPQRpMeMVOrqgGOnuG5P5LKdQDdx3hCByOMRyuanmPJMBn3LgXHQnInlOoafFOXdNCkpx6YwQ9VEJvhBgOwRcE2/ATLjy@snqZaZE1QPhLtoe8s4fH/SscUeaB4l6Thie4lZ4YJqx9i09SzUCRFOdKqtS6MU72JdgHzmRn2EBindJaBzV/c6axFI/eb0lNhMz3a98kZUTOoGyQGDtJ5kJiLQKK@CgYgUU@qjw0DcgNygxBz9EHydq@JRx@iD9GH8CG1wuQNI6pEROs41KleF4Mmho9RxvAx/jHRhCoJWQn@CVFX1ajVQIfGrCqWL8CFOrQaL1LDOk3uNLQL5BLkpBI0sqtJUtM6tQEXKqbpXag8zewimWlqFykWKabxneZ3dfUSq4JW4OL8xVQhUYVECYneS7P7qt6wmpPJ@8PprTW0z9/cRzqUoKf2WoEPYh2KaVpfy78r9feHHt5rdn@Z/amwe14O@JkrlQrL3aFov3nF9ZbzeFcoXv72h9284biaYnYNK3pVfGjsDvPyrAJ5db1pzFaHsoUrVqlv3/@80MZs7B/i7pphUSWst6fypnIT@ErhteLV8tqTaWa3i@38Ylgp6PO/8v6r@f/q8/kv) [Answer] # [R](https://www.r-project.org/), ~~301~~ ~~289~~ ~~287~~ 273 bytes Explanation. Look up the index of the mass sorted atomic number in a UTF8 encoded hash string `s`. The hash is taken by taking the element name, encoding it as ASCII, multiplying by a 2-vector encoded with UTF-8 and modding three times in succession. The operator `+` is used for the UTF8 to integer vector conversion. Encode the masses of the elements as a UTF8 encoded string of differences, packing 2 differences into each byte as `9*d1 + d2` where `d1` is the difference of the nth element and `d2` is the successive mass difference of the n+50th element. Then to retrieve the mass, take the corresponding position at the cumulative sum of the differences. This is shorter than a quadratic formula. ``` function(x)sum(c(o%%9,o%/%9)[1:match(sum(+x*+" ")%%740%%623%%278,+'{ćWZ}èċæŸ+Ó>qÿƒ!2Eo&ē_ u½8`h›’Hb‰¹ĎŽ‹@-if9ÃÛ%ù]V‚:LkXlÙDRŠ•˜OU·m,Sµ5TËt6cC7#­/ąz1A')]) "+"=utf8ToInt o=+" 0 % ..%$ %%  p & 0 0 ( 1" ``` [Try it online!](https://tio.run/##VVTfixtVFMZSiqQLiu521W7jOHbaGTO7nTuT@bUYMUm3m8X9EbLp9ocUnU5m3NBNsiYTaCsiWER0oYhFUPrQt@KLj0X6IMJM/q/1nO@6oCz323vO/c53vntukvFxcpAMkmE2qcW62lJNRW0ljJt9xgb2DYYmwzbDDsM1hDjejggVdesLDuoHjLuobmOLYmTrY8ZPkIhwFjN2@6jfQx6UrSFaQL05Qg8INqeMt3G6DoV1cOoTKOxKt7ILsHMXbbC/hVpst5HegnIXHjpTKHT24bsHUdynif0GWu5KRHEXvTYYbkqf0kMDtjaBTRy0ZUvotAdQAK7hMuvId6F59QEkWvC1hrIuqLdwvImCVoo8GtyAdXTZmcDPGArtDBeQfFyjiwdoQ6chHwdd6mB25LzlyORr1uXTyHmg2XVc4xAJKNfhrQls3MMe3tbkJK4NVKNUGkSTScIfLmEqVVPxTSU0FUGBsGlRRni0KGdbtBxalLOJZgem4hDPIZ7iuFRNBCeU/6scE8ElgksEl2KXhNxQLo9EPMr5xPVJVPE5oIOAEgEdBhQHJBBQLiSRkEghCYSUExbbsxwGNmdRjiyzX@Ey8A1sDtmjYLOCnQqHSxyETGGjosoH1SorsGnhcpItC5eJbFZ4XMd2hcc5j3PsWrBr4XOTQLACOxcBBsYyIcuEzAl5YGzbtnh8FsLwBASPlg0T8oRtj4E5PFybvdtOwMA5NmtX8RL@CfCcbRcKrk@vmn64fJxOh3HWHw31@8ZkOtBjfaRpoTnSrmih8alYHURZvK/zSeX@BxX1zAXV0DS/ammaZzuaZtO1KpfPfTX7/sbtr4vfZ0fF8/xZpXhy5vxbH73xzZfF3/mj9@xX10aXZk8@K78yfTv/61Tw@X7@NP@5dTf/IX85e5w/zo8@Xu6nYfGoeKoVL9@9s5d/u7p57@ZB8dvV@U7@Y/5L/uvO9fzPgZn/tJu/cLvFUebF7zQX/dOvv/Z@/seV2XcPRf2ycccoqRW1Ns3SoDvaGGalUa2iLllzF@a1@bNzS3MrCysL2sK5Ny8ulstLtDu/qCnl@dOlw1K5dOmsRX/lU/qcUI97aa0XZdFKOo4GiT6siVVhWea/P7C1kx9a83Cc9PpxlvRW@MtR20vibDTuP0z01NBPSIYZxdk0OpAU@SUySr30Yq8/icfJYTSMH9Qo/A9rmcL/SxP/@B8 "R – Try It Online") A mention to this [275 byte solution](https://tio.run/##VVRbbxtFFBYIVcgvVBUqN5UuC0t2yTrZ2fXeAkbYThpHjR3LcdObqma7XjdLfQn2GrVFBKkV4hKpQlQgUB54Q33pI0J9QEhj87vSc74lEjzM5zlnvvOdb87YHh8n/WSQDLNJOdbVumoqaj1h3EwZq9hXGWoMTYYthgsIcdyMCBW1cZuDSp9xG9UtbFGMbGXMeBGJCGcxYydF/Q7yoDSGaAH12gg9IFibMl7D6ToU1sGpTKCwnbvNuwDbt9AG@6uoxbaJdAPKHXhoT6HQ3oPvLkRxnxr2G2i5nSOKO@i1wXAl95l7qMLWJrCGg1beEjqtARSAa7jMOvIdaK7eg0QdvtZQ1gH1Ko43UVDvIY8Gl2EdXbYm8DOGQivDBXI@rtHBA7SgU80fB10qYLbzeecjy1@zkj9NPg80u4Rr7CMB5Qq81YDVO9jD21o@iQsD1SgUBtFkkvCXS5hKyVR8UwlNRVAgbFqUER4tytkWLYcW5Wyi2YGpOMRziKc4LlUTwQnzzxLHRHCJ4BLBpdglITfMl0ciHuV84vokqvgc0EFAiYAOA4oDEggoF5JISKSQBELKCYvtWQ4Dm7MoR5bZr3AZ@AY2h@xRsFnBToXDJQ5CprBRUeKDUokV2LRwOcmWhctENis8rmO7wuOcxzl2Ldi18LlJIFiBnYsAA2OZkGVC5oQ8MLZtWzw@C2F4AoJHy4YJecK2x8AcHq7N3m0nYOAcm7VLeAn/BHjOtgsF16dXLfQ@Kh73psM4S0dD/a4xmQ70WB9py5qraZ450jR3UZgcO5bpGtfFyiDK4j2decW7HxTVU@dUQ9P8kkV029E0m25ZXDj7xfyby9e@nD2ZH85@l78tzh6feuv1j8989dnsb/nwHfvltdH788c3335h@ob868Vgd08eyR/rt@R38tn8kXwkDz8ppr1w9nB2pM2enb@xIx@sbN650p/9uvpqW34vf5K/bF2Sfw5M@cO2/MPtzA4zL36z9pr/0ulX3pVPl@df3xeVBeOGUVCLanma9YLOaGOYFUblorp6sSkf1G8mSeOgsds46EfNswv/PAk/tQ6K8mhZ/vzh7jn57aJ63O2Vu1EWLfXG0SDRh2WxIizL/Pc/tnzyX2vuj5NuGmdJd4l/H@WdJM5G4/R@ovcM/YRkmFGcTaN@Tsl/R0ah23uvm07icbIfDeN75aXWOB2kWfp5opNpQ6fj/1SZFP6/FQscPwc "R – Try It Online") which *nearly* beats the R record by encoding three mass differences in mixed base 6,5. [Answer] # PHP 4.1, ~~645~~ ~~643~~ 641 bytes This is not the best idea, it may be possible to minimize a little more. ``` <?$V=split(A,A1A4A7A9AbAcAeAgAjAkAnAoArAsAvAwAzA14A13A14A19A1cA1fA1gA1jA1kA1nA1nA1sA1tA1yA21A23A27A28A2cA2dA2gA2hA2jA2lA2oA2qA2tA2vA2yA30A34A37A3bA3eA3kA3jA3nA3pA3tA3vA3wA3xA40A41A46A48A4dA4fA4jA4lA4nA4pA4tA4vA4yA51A54A56A5aA5cA5fA5hA5lA5oA5rA5tA5tA5uA66A67A6aA6bA6gA6fA6mA6lA6sA6rA6vA6vA6zA70A75);echo base_convert($V[array_search($E,array(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))+1],36,10); ``` Sadly, I've seen myself forced to use Base36 instead of Base96. To use it, simply set the key `E` in POST/GET/SESSION with the name of the element. To emulate it in newer versions, simply add `$E=<element name>;` before `$V`. You can test it on <http://rextester.com/OMAA85454> [Answer] # PHP, 893 695 bytes ``` function a($e,$m=[H,1,He,4,Li,7,Be,9,B,11,C,12,N,14,O,16,F,19,Ne,20,Na,23,Mg,24,Al,27,Si,28,P,31,S,32,Cl,35,Ar,40,K,39,Ca,40,Sc,45,Ti,48,V,51,Cr,52,Mn,55,Fe,56,Co,59,Ni,59,Cu,64,Zn,65,Ga,70,Ge,73,'As',75,Se,79,Br,80,Kr,84,Rb,85,Sr,88,Y,89,Zr,91,Nb,93,Mo,96,Tc,98,Ru,101,Rh,103,Pd,106,Ag,108,Cd,112,In,115,Sn,119,Sb,122,Te,128,I,127,Xe,131,Cs,133,Ba,137,La,139,Ce,140,Pr,141,Nd,144,Pm,145,Sm,150,Eu,152,Gd,157,Tb,159,Dy,163,Ho,165,Er,167,Tm,169,Yb,173,Lu,175,Hf,178,Ta,181,W,184,Re,186,Os,190,Ir,192,Pt,195,Au,197,Hg,201,Tl,204,Pb,207,Bi,209,Po,209,At,210,Rn,222,Fr,223,Ra,226,Ac,227,Th,232,Pa,231,U,238,Np,237,Pu,244,Am,243,Cm,247,Bk,247,Cf,251,Es,252,Fm,257]){return $m[array_search($e,$m)+1];} ``` The usage of the function is to omit the 2nd argument, eg ``` echo a('Ra'); // returns 226 ``` Requires PHP >=5.4 to allow `[...]` for array declaration and suppressing errors (at least `error_reporting(~E_NOTICE)` is given or there is the same clause in the php.ini file). The `As` needs to be in quotes because it is considered as a reserved keyword. [Answer] # Ruby: ~~474~~ 468 characters ``` f=->e{"H1He4Li7Be9B11C12N14O16F19Ne20Na23Mg24Al27Si28P31S32Cl35Ar40K39Ca40Sc45Ti48V51Cr52Mn55Fe56Co59Ni59Cu64Zn65Ga70Ge73As75Se79Br80Kr84Rb85Sr88Y89Zr91Nb93Mo96Tc98Ru101Rh103Pd106Ag108Cd112In115Sn119Sb122Te128I127Xe131Cs133Ba137La139Ce140Pr141Nd144Pm145Sm150Eu152Gd157Tb159Dy163Ho165Er167Tm169Yb173Lu175Hf178Ta181W184Re186Os190Ir192Pt195Au197Hg201Tl204Pb207Bi209Po209At210Rn222Fr223Ra226Ac227Th232Pa231U238Np237Pu244Am243Cm247Bk247Cf251Es252Fm257"=~/#{e}(\d+)/;$><<$1} ``` Sample run: ``` irb(main):001:0> f=->e{"H1He4Li7Be9B11C12N14O16F19Ne20Na23Mg24Al27Si28P31S32Cl35Ar40K39Ca40Sc45Ti48V51Cr52Mn55Fe56Co59Ni59Cu64Zn65Ga70Ge73As75Se79Br80Kr84Rb85Sr88Y89Zr91Nb93Mo96Tc98Ru101Rh103Pd106Ag108Cd112In115Sn119Sb122Te128I127Xe131Cs133Ba137La139Ce140Pr141Nd144Pm145Sm150Eu152Gd157Tb159Dy163Ho165Er167Tm169Yb173Lu175Hf178Ta181W184Re186Os190Ir192Pt195Au197Hg201Tl204Pb207Bi209Po209At210Rn222Fr223Ra226Ac227Th232Pa231U238Np237Pu244Am243Cm247Bk247Cf251Es252Fm257"=~/#{e}(\d+)/;$><<$1} => #<Proc:0x00000001e59d08@(irb):2 (lambda)> irb(main):002:0> f["K"] 39=> #<IO:<STDOUT>> ``` Online run: <http://rextester.com/edit/UMNY88866> [Answer] # SAS, 351 (chars) 791 (bytes) 454 bytes Borrowing from the concept posted by Sp3000, using a quadratic regression to model the positional offsets mass = floor(o\*0.715+0.00031\*o\*o+1.7)+e where o represents the offset and e is the known error from actual. ``` %macro m(e);data;s='H-1He0Li1Be1B0C0N1O1F3Ne2Na3Mg2Al3Si01P1S01Cl2Ar5K01Ca0Sc2Ti3V4Cr3Mn4Fe2Co3Ni01Cu3Zn01Ga3Ge4As4Se6Br4Kr6Rb5Sr5Y04Zr3Nb03Mo03Tc02Ru02Rh00Pd00Ag-1Cd00In0Sn1Sb2Te5I2Xe4Cs4Ba5La5Ce3Pr02Nd02Pm-1Sm1Eu00Gd2Tb2Dy3Ho3Er2Tm01Yb2Lu1Hf2Ta2W3Re3Os5Ir4Pt4Au4Hg5Tl6Pb6Bi5Po03At00Rn9Fr7Ra7Ac6Th8Pa04U8Np5Pu9Am6Cm7Bk04Cf05Es02Fm03';o=prxmatch("#(?<=&e)[-\d]#",s)-1;a=floor(o*.715+.00031*o*o+1.7)+prxchange("s#.*&e(-?\d+).*#\1#",1,s);put a;run;%mend; ``` [Answer] # Javascript ES6 354 bytes ``` p=e=>+'1H2He1LiBeBC1N1O2FNe1Na-Mg1Al-Si1PS2Cl2KAr--Ca3Sc1Ti1VCr1Mn-Fe1Co--Ni3Cu-Zn3Ga1GeAs2Se-Br2Kr-Rb1Sr-Y1ZrNb1MoTc1RuRh1PdAg2Cd1In2Sn1Sb3ITe1XeCs2BaLa-Ce-Pr1Nd-Pm3SmEu3GdTb2DyHoErTm2YbLu1Hf1Ta1W1Re2OsIr1PtAu2Hg1Tl1PbBi--Po-At19Rn-Fr1Ra-Ac2Pa-Th3Np-U4Am-Pu1Cm--Bk2Cf-Es1Fm'.split(RegExp(e+'[^a-z].*'))[0].split('').reduce((o,n)=>+n?+n+o:n=='-'?--o:++o) ``` Ungolfed: ``` function p(e) { return "1H2He1LiBeBC1N1O2FNe1Na-Mg1Al-Si1PS2Cl2KAr--Ca3Sc1Ti1VCr1Mn-Fe1Co--Ni3Cu-Zn3Ga1GeAs2Se-Br2Kr-Rb1Sr-Y1ZrNb1MoTc1RuRh1PdAg2Cd1In2Sn1Sb3ITe1XeCs2BaLa-Ce-Pr1Nd-Pm3SmEu3GdTb2DyHoErTm2YbLu1Hf1Ta1W1Re2OsIr1PtAu2Hg1Tl1PbBi--Po-At19Rn-Fr1Ra-Ac2Pa-Th3Np-U4Am-Pu1Cm--Bk2Cf-Es1Fm" .split(RegExp(e+'[^a-z].*'))[0] .split('') .reduce(function(o,n) { return +n ? +n+o : n=='-' ? --o : ++o; }) } ``` The elements are stored in a string of numbers symbols and minus characters. The mass of any given element is the number of letter characters preceding it, plus the sum of digits subtracted by the occurrences of `-`. ## Tests: ``` var a = [ 'H', 1, 'He', 4, 'Li', 7, 'Be', 9, 'B', 11, 'C', 12, 'N', 14, 'O', 16, 'F', 19, 'Ne', 20, 'Na', 23, 'Mg', 24, 'Al', 27, 'Si', 28, 'P', 31, 'S', 32, 'Cl', 35, 'Ar', 40, 'K', 39, 'Ca', 40, 'Sc', 45, 'Ti', 48, 'V', 51, 'Cr', 52, 'Mn', 55, 'Fe', 56, 'Co', 59, 'Ni', 59, 'Cu', 64, 'Zn', 65, 'Ga', 70, 'Ge', 73, 'As', 75, 'Se', 79, 'Br', 80, 'Kr', 84, 'Rb', 85, 'Sr', 88, 'Y', 89, 'Zr', 91, 'Nb', 93, 'Mo', 96, 'Tc', 98, 'Ru', 101, 'Rh', 103, 'Pd', 106, 'Ag', 108, 'Cd', 112, 'In', 115, 'Sn', 119, 'Sb', 122, 'I', 127, 'Te', 128, 'Xe', 131, 'Cs', 133, 'Ba', 137, 'La', 139, 'Ce', 140, 'Pr', 141, 'Nd', 144, 'Pm', 145, 'Sm', 150, 'Eu', 152, 'Gd', 157, 'Tb', 159, 'Dy', 163, 'Ho', 165, 'Er', 167, 'Tm', 169, 'Yb', 173, 'Lu', 175, 'Hf', 178, 'Ta', 181, 'W', 184, 'Re', 186, 'Os', 190, 'Ir', 192, 'Pt', 195, 'Au', 197, 'Hg', 201, 'Tl', 204, 'Pb', 207, 'Bi', 209, 'Po', 209, 'At', 210, 'Rn', 222, 'Fr', 223, 'Ra', 226, 'Ac', 227, 'Pa', 231, 'Th', 232, 'U', 238, 'Np', 237, 'Pu', 244, 'Am', 243, 'Cm', 247, 'Bk', 247, 'Cf', 251, 'Es', 252, 'Fm', 257 ]; function p(e) { return "1H2He1LiBeBC1N1O2FNe1Na-Mg1Al-Si1PS2Cl2KAr--Ca3Sc1Ti1VCr1Mn-Fe1Co--Ni3Cu-Zn3Ga1GeAs2Se-Br2Kr-Rb1Sr-Y1ZrNb1MoTc1RuRh1PdAg2Cd1In2Sn1Sb3ITe1XeCs2BaLa-Ce-Pr1Nd-Pm3SmEu3GdTb2DyHoErTm2YbLu1Hf1Ta1W1Re2OsIr1PtAu2Hg1Tl1PbBi--Po-At19Rn-Fr1Ra-Ac2Pa-Th3Np-U4Am-Pu1Cm--Bk2Cf-Es1Fm" .split(RegExp(e + '[^a-z].*'))[0] .split('') .reduce(function(o, n) { return +n ? +n + o : n == '-' ? --o : ++o; }) } var $elementList = $('#elements'); for (var i = 0; i < a.length; i++) { var symbol = a[i]; var mass = a[++i]; var result = p(symbol); var resultString = "<li><b>" + symbol + "</b>"; if (symbol.length === 1) resultString += "&nbsp;"; resultString += " expected <b>" + mass + "</b>"; if (mass < 10) resultString += "&nbsp;"; if (mass < 100) resultString += "&nbsp;"; resultString += " got <b>" + result + "</b></li>"; $elementList.append(resultString); } ``` ``` #elements li { font-family: "Consolas", monospace; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="elements"> </ul> ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~373~~ 371 bytes -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) One string containing the elements is used for lookup. When an index is found, this is used to traverse the second string, each character of which holds two mass deltas, one per nibble. (Each character has also been increased by 32 to bring them into printable territory.) In other words, we do not save the masses of the elements, only how much they differ from the previous one, in a list sorted by mass. Adding all these deltas together gets us the mass for half of the elements (the ones that are in even slots). If we are in an odd slot, we remove the last delta again. ``` x,w,c,i;f(char*e){char*E="H HeLiBeB C N O F NeNaMgAlSiP S ClK ArCaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbI TeXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcPaThNpU AmPuCmBkCfEsFm",a[3]={*e++,*e?:32};for(x=strstr(E,a)-E,w=i=0;i<=x/4;w+=c%16+c/16-2)c="3RABQQQQT0sQQPqsD432CCCDTU3DA35EDBDCSDCDS@<34553$5"[i++];c=x&2?w:w-c%16;} ``` [Try it online!](https://tio.run/##VZRrb9pKEIY/h1@xspojCKCCjUkItXLsxVwUYhzbaZuk@WCbBaxySddwoIry23M8A7NqI6TwsDsz7zs7u2l9nqYfH4favpbWsu6snC5ieSEqb/jftbQhG4px5giHceaxCeszT3jx3dxehpnPQsaXt8yWPA7TKPvKuLxb9wXfeBnfPa0H8UDYeSgceSuDJJSP7El6yd0mSoNdsPCn9pxPR@twHSYjFonvgudOPI658KU39Vfhyt0NplHS@z3cuDJaPSbj3XAWxd9YICb5SPpbezecR0s/cTJ/Y2@DdV8GsZ36cbTwXh@YvfJ3fOX85DM376@0WvxsvFhvF6JarV2Im2tDf@/ONrJ8sPKtLD5ltxZX6m5tb2VWo5t9sQ6fW9191UrPm@1q@rnZruuV1NKMwHbui7@okd/f@7/yXsvQOee96MHo2Ybp9pweD3u8F/77xWiZpvHJ1J6zavWlm1qHf/Sb/fW@Dhm77x//bbIpm2PD2UWcJLLGsvWWicOrSLdiWim9lc7gByny3XLLLDYrw65Kt3RWOnuVxdKsrD2z85y9sPO6nrPz6Y@1VlP7LZWK3TBtcquxa6YxVuw4FjvuK9K9l0pQZxVn6zJWnZe1YbGtCaXguyigdYJxVsDlCRxY6RBACMVwAP0EHgAlmAC0T9AHoAQeZNMbRDGQcaK7ORDlsJdApCIESfrVifwCDJIRApAMDlGGSTkkuKJqt7BEQnj851KYAlFYBMVaVOxrAabyDBlNqnYHZ2FSWB@8mWSbb4CU7@xP4ruC2uT0CbK0KcsAhF2SsAHkvKQO2TkQ7QxxTR0NKLtSXpGoQpAAqThcI3uPAJTkCZY6ZNaDsI46HjDUIXsRdKxDSQIw1GxQYLBApEh/ikih9hyRYjmuqkEarRGV2COSwDDBoaPNkUCkVCMkmpnvuKjmhOeIJMqJEWnz@IjqhDBWzYcvEVVjUHKL2uuvEJVkRJNiXeyNmpkBxppUN0JDajJ6v/HqkMjhBpEyuyijrWKxUJtiHzGVGpYx1lXTMpwhUqsi9HtFjr4hqXlB91d0YBPsXIcMjVBFhwz5W0R157BshzQO8VKryYjwVjdU5xJE9dbgLW@QIX/zF9pQSG@SjAAmQ1ej0JeI5D7Ap0VXM5ciqs4t8OFRFo7vEIl8QKJOea@IFOrv8JVSz9QKkcryIypDP/9CDmegq8fEzRGVA4zFyXj/@B8 "C (gcc) – Try It Online") [Answer] # Python 2, ~~860~~ ~~859~~ 858 bytes Based on @Cool Guy's version - ``` def f(x):print {"H":1,"He":4,"Li":7,"Be":9,"B":11,"C":12,"N":14,"O":16,"F":19,"Ne":20,"Na":23,"Mg":24,"Al":27,"Si":28,"P":31,"S":32,"Cl":35,"Ar":40,"K":39,"Ca":40,"Sc":45,"Ti":48,"V":51,"Cr":52,"Mn":55,"Fe":56,"Co":59,"Ni":59,"Cu":64,"Zn":65,"Ga":70,"Ge":73,"As":75,"Se":79,"Br":80,"Kr":84,"Rb":85,"Sr":88,"Y":89,"Zr":91,"Nb":93,"Mo":96,"Tc":98,"Ru":101,"Rh":103,"Pd":106,"Ag":108,"Cd":112,"In":115,"Sn":119,"Sb":122,"Te":128,"I":127,"Xe":131,"Cs":133,"Ba":137,"La":139,"Ce":140,"Pr":141,"Nd":144,"Pm":145,"Sm":150,"Eu":152,"Gd":157,"Tb":159,"Dy":163,"Ho":165,"Er":167,"Tm":169,"Yb":173,"Lu":175,"Hf":178,"Ta":181,"W":184,"Re":186,"Os":190,"Ir":192,"Pt":195,"Au":197,"Hg":201,"Tl":204,"Pb":207,"Bi":209,"Po":209,"At":210,"Rn":222,"Fr":223,"Ra":226,"Ac":227,"Th":232,"Pa":231,"U":238,"Np":237,"Pu":244,"Am":243,"Cm":247,"Bk":247,"Cf":251,"Es":252,"Fm":257}[x] ``` Usage - ``` f("K") ``` Output - ``` 39 ``` Try it [here](http://ideone.com/vwNXxw) [Answer] # Python 2, 630 bytes Based on @Cool Guy's code, just packed all the strings into one and then used regexp to get them back. It saved me few bytes. **edit:** rewrote mass list, just to be sure it's correct this time. ``` import re;print dict(zip(map(str.strip,re.findall("..","H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU NpPuAmCmBkCfEsFm")),(1,4,7,9,11,12,14,16,19,20,23,24,27,28,31,32,35,40,39,40,45,48,51,52,55,56,59,59,64,65,70,73,75,79,80,84,85,88,89,91,93,96,98,101,103,106,108,112,115,119,122,128,127,131,133,137,139,140,141,144,145,150,152,157,159,163,165,167,169,173,175,178,181,184,186,190,192,195,197,201,204,207,209,209,210,222,223,226,227,232,231,238,237,244,243,247,247,251,252,257)))[raw_input()] ``` [Answer] # Javascript ES6, 620 bytes This is a pretty basic one, like my PHP answer. It uses base36 to encode the values. ``` s=>parseInt("1|4|7|9|b|c|e|g|j|k|n|o|r|s|v|w|z|14|13|14|19|1c|1f|1g|1j|1k|1n|1n|1s|1t|1y|21|23|27|28|2c|2d|2g|2h|2j|2l|2o|2q|2t|2v|2y|30|34|37|3b|3e|3k|3j|3n|3p|3t|3v|3w|3x|40|41|46|48|4d|4f|4j|4l|4n|4p|4t|4v|4y|51|54|56|5a|5c|5f|5h|5l|5o|5r|5t|5t|5u|66|67|6a|6b|6g|6f|6m|6l|6s|6r|6v|6v|6z|70|75".split('|')["H0He0Li0Be0B0C0N0O0F0Ne0Na0Mg0Al0Si0P0S0Cl0Ar0K0Ca0Sc0Ti0V0Cr0Mn0Fe0Co0Ni0Cu0Zn0Ga0Ge0As0Se0Br0Kr0Rb0Sr0Y0Zr0Nb0Mo0Tc0Ru0Rh0Pd0Ag0Cd0In0Sn0Sb0Te0I0Xe0Cs0Ba0La0Ce0Pr0Nd0Pm0Sm0Eu0Gd0Tb0Dy0Ho0Er0Tm0Yb0Lu0Hf0Ta0W0Re0Os0Ir0Pt0Au0Hg0Tl0Pb0Bi0Po0At0Rn0Fr0Ra0Ac0Th0Pa0U0Np0Pu0Am0Cm0Bk0Cf0Es0Fm".split(0).indexOf(s)],36) ``` It creates an anonymous function that returns an integer value. Invalid values return weird results. Try it (ES5, requires support for `Array.prototype.indexOf()`): ``` f=function(s){return parseInt("1|4|7|9|b|c|e|g|j|k|n|o|r|s|v|w|z|14|13|14|19|1c|1f|1g|1j|1k|1n|1n|1s|1t|1y|21|23|27|28|2c|2d|2g|2h|2j|2l|2o|2q|2t|2v|2y|30|34|37|3b|3e|3k|3j|3n|3p|3t|3v|3w|3x|40|41|46|48|4d|4f|4j|4l|4n|4p|4t|4v|4y|51|54|56|5a|5c|5f|5h|5l|5o|5r|5t|5t|5u|66|67|6a|6b|6g|6f|6m|6l|6s|6r|6v|6v|6z|70|75".split('|')["H0He0Li0Be0B0C0N0O0F0Ne0Na0Mg0Al0Si0P0S0Cl0Ar0K0Ca0Sc0Ti0V0Cr0Mn0Fe0Co0Ni0Cu0Zn0Ga0Ge0As0Se0Br0Kr0Rb0Sr0Y0Zr0Nb0Mo0Tc0Ru0Rh0Pd0Ag0Cd0In0Sn0Sb0Te0I0Xe0Cs0Ba0La0Ce0Pr0Nd0Pm0Sm0Eu0Gd0Tb0Dy0Ho0Er0Tm0Yb0Lu0Hf0Ta0W0Re0Os0Ir0Pt0Au0Hg0Tl0Pb0Bi0Po0At0Rn0Fr0Ra0Ac0Th0Pa0U0Np0Pu0Am0Cm0Bk0Cf0Es0Fm".split(0).indexOf(s)],36)} document.getElementById('e').onkeyup=function(){ document.getElementById('o').innerHTML=this.value?f(this.value):''; } ``` ``` <input type="text" id="e" placeholder="Element"><br> <span>Element mass: <b id="o"></b></span> ``` [Answer] ## Java, 414 407 Bytes ``` void m(String e){String s="5.=\\>i6K<35)<?<@CB/L<Y0 ?M0ZCL59?OOA&z.8KI>qCR2v@./D@>)JP22%Jh=[::[[email protected]](/cdn-cgi/l/email-protection)=5?:95h@H6)B+7J=J6~DH@*G?<xS*&xDw:<CX5L/A3$=H1`N0:rKW5nJ198:$8oD*:y=v<_CS6[H^:(An:nE<?`<u7T+*3Icj2y<].jLm /_}$7^U#;Ft)rD|33N#",a=s;int i=0,n=0,c,b;while(!a.equals(e)){c=s.charAt(i++)*95+s.charAt(i++)-3072;a=""+(char)(65+c%26);b=97+c/26%26;if(b!=122)a+=(char)b;c/=676;n+=c==9?12:c-1;}System.out.print(n);} ``` Usage: `m("He")` The tuple `(element code, delta from previous element)` is transformed into an integer varying from 0 to 6760 (=26x26x10), then encoded in base 95 into the string. It can be tested here: <http://rextester.com/VFXLG54655> [Answer] # Python 3, ~~500~~ 495 Pretty self-explanatory. Just use a regex built from the input to find the number after the element's abbreviation. [**Try it here**](http://ideone.com/Gq4o1y) ``` import re print(re.findall(r"(?<=%s)\d+"%input(),"H1He4Li7Be9B11C12N14O16F19Ne20Na23Mg24Al27Si28P31S32Cl35Ar40K39Ca40Sc45Ti48V51Cr52Mn55Fe56Co59Ni59Cu64Zn65Ga70Ge73As75Se79Br80Kr84Rb85Sr88Y89Zr91Nb93Mo96Tc98Ru101Rh103Pd106Ag108Cd112In115Sn119Sb122Te128I127Xe131Cs133Ba137La139Ce140Pr141Nd144Pm145Sm150Eu152Gd157Tb159Dy163Ho165Er167Tm169Yb173Lu175Hf178Ta181W184Re186Os190Ir192Pt195Au197Hg201Tl204Pb207Bi209Po209At210Rn222Fr223Ra226Ac227Th232Pa231U238Np237Pu244Am243Cm247Bk247Cf251Es252Fm257")[0]) ``` [Answer] # PHP, ~~415~~ ~~414~~ 387 bytes ``` <?preg_match("/\d".$_GET[e]."\d/",$b="2H3He4Li4Be6B2C3N3O5F4Ne4Na3Mg3Al2Si2P6S3Cl6Ar2K1Ca4Sc4Ti5V4Cr5Mn3Fe4Co1Ni3Cu2Zn4Ga5Ge4As6Se4Br5Kr4Rb4Sr3Y3Zr2Nb3Mo2Tc2Ru2Rh2Pd1Ag3Cd3In4Sn5Sb8Te4I6Xe6Cs7Ba6La5Ce3Pr3Nd1Pm4Sm3Eu5Gd4Tb6Dy5Ho4Er3Tm5Yb4Lu4Hf4Ta4W5Re6Os5Ir5Pt4Au6Hg6Tl6Pb5Bi2Po0At9Rn8Fr8Ra6Ac8Th4Pa8U5Np9Pu5Am6Cm4Bk5Cf3Es5Fm0",$m,256);$s=$m[0][1];echo round(.0003*$s*$s+.81*$s-1)+$b{$s}; ``` This answer works basically off the same principle as Sp3000's CJam answer; I did a quadratic regression with the element's position in the `$b` string as the independent variable and molar mass as the dependent, then found the difference between the actual value and regression value for each element, and put it all into the $b string. I actually originally did this in Java, but then discovered that it takes a lot of bytes to do regex in Java. I've never done a code golf before so please let me know if I'm doing something wrong here. ~~Edit: try it out [here](http://uvkk79d27f2c.vijrox.koding.io/ElementGolf.php)~~ (Actually, that link probably doesn't work) Edit 2: [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) helped me knock a bunch of bytes off of this! [Answer] # Powershell, 324 bytes ``` ('1H3He3Li2Be2B1C2N2O3F1Ne3Na1Mg3Al1Si3P1S3Cl4K1ArCa5Sc3Ti3V1Cr3Mn1Fe3CoNi5Cu1Zn5Ga3Ge2As4Se1Br4Kr1Rb3Sr1Y2Zr2Nb3Mo2Tc3Ru2Rh3Pd2Ag4Cd3In4Sn3Sb5I1Te3Xe2Cs4Ba2La1Ce1Pr3Nd1Pm5Sm2Eu5Gd2Tb4Dy2Ho2Er2Tm4Yb2Lu3Hf3Ta3W2Re4Os2Ir3Pt2Au4Hg3Tl3Pb2BiPo1At12Rn1Fr3Ra1Ac4Pa1Th5Np1U5Am1Pu3CmBk4Cf1Es5Fm'-split"$args")[0]-replace'\D+','+'|iex ``` Test script: ``` $f = { ('1H3He3Li2Be2B1C2N2O3F1Ne3Na1Mg3Al1Si3P1S3Cl4K1ArCa5Sc3Ti3V1Cr3Mn1Fe3CoNi5Cu1Zn5Ga3Ge2As4Se1Br4Kr1Rb3Sr1Y2Zr2Nb3Mo2Tc3Ru2Rh3Pd2Ag4Cd3In4Sn3Sb5I1Te3Xe2Cs4Ba2La1Ce1Pr3Nd1Pm5Sm2Eu5Gd2Tb4Dy2Ho2Er2Tm4Yb2Lu3Hf3Ta3W2Re4Os2Ir3Pt2Au4Hg3Tl3Pb2BiPo1At12Rn1Fr3Ra1Ac4Pa1Th5Np1U5Am1Pu3CmBk4Cf1Es5Fm'` -split"$args")[0]-replace'\D+','+'|iex } @( ,(16,'O') ,(119,'Sn') ,(1,'H') ,(257,'Fm') ) | % { $e,$a = $_ $r = &$f $a "$($e-eq$r): $r" } ``` Output: ``` True: 16 True: 119 True: 1 True: 257 ``` ## Explanation The datastring contains chemical element labels and differences of the masses of adjacent elements. Zero differences are removed. The script: 1. splits the datastring by a target element label. 2. takes a first substring with elements and differences that precede the target 3. replaces nondigit symbols to `+` (result for Oxigen element is: `1+3+3+2+2+1+2+2`) 4. calculates the result string as powershell expression [Answer] # [C (clang)](http://clang.llvm.org/), ~~624~~ 623 bytes ``` *a=L"H效楌敂BCNOF敎慎杍汁楓PS汃牁K慃捓楔V牃湍敆潃楎畃湚慇敇獁敓牂牋扒牓Y牚扎潍捔畒桒摐杁摃湉湓打敔I敘獃慂慌敃牐摎浐浓畅摇扔祄潈牅浔扙界晈慔W敒獏牉瑐畁杈汔扐楂潐瑁湒牆慒捁桔慐U灎畐流浃歂晃獅浆";f(short*x){return L"敉敌敏救敓敔敖敘敛敜敟敠散敤敧敨敫数敯数敵數敻敼敿斀斃斃斈斉斎斑斓斗斘斜斝斠斡斣斥斨斪断斯斲斴斸斻斿旂旈旇旋旍旑旓旔旕旘旙旞无日旧旫旭旯旱旵旷旺旽昀昂昆昈昋昍昑昔昗昙昙昚昦昧昪昫昰是昶昵昼昻昿昿晃晄晉"[wcschr(a,*x)-a]-a[1];} ``` [Try it online!](https://tio.run/##dVVtTxNZGP2@v8I0MQEjH/xM9kPb5S0WaKC@4MuHWkWIWk3B6MaY2I4DvcGpnc48996iKEQrRkKQzXZXFhv@zbk/g51lv85JJpPOydNzz3Oec@@tjFQelqv3T08vlH8tZCYhTfTeQBq5/MzsOKQFv4WtAId19KLiPA49p@qX4XsIIvTiq055OAogaxh46LWcJJ@b8Nch6y6oQyKnGk5tQHWcihac2oRqYRAgiJ10sNNB2MZWHWHyN4WjCCqCxFMQ6wIPfgN@oiVZso2whX4b/ciJj3AdKna91xg0nfLRj6G6Tt6g24QfX4N0XPDWKeXCtpM6tpo4TCra6DUwaLuwjqNEzBr8DhKFOzH89hVXT6Qn9HX0Pew30PVckBCvZUYXh1aWHtdWLzwfflG7t/q0Vj1XyEAUkuXkLSRMWkwUQ3SiGfIO8h7yEbIN@QT5DNmFfIXsQb5DDs7efcgPyDHkJ@QE@hW0d/Y0oRV0CzqEjqANtIV@D70FvQ29A/0Jugf9Ffob9D70AfQf0H9C/4A@hj6BacA0YdZhNmACmBAmgolhBMbCdGE@wGzD9GB2YfZg9mEOYA5h@jB/w/wDM4B9BduAXYNtwm7ABrAhbAxrYLtnzybsF9hd2G@we7DfYQ9g/4Ltw/6EPYY9@e/peui@Rldlbj6rrFSWakPli4mHI@XbI@Wbl26Pvjxdrq6ee1Rerg4Nv/jlSS35WhzKnL97q5q5mPyYzAwPj6bA99LxwnI6niP1uXQ4nw7PpMOz6fA4ISFSZsrp@PT9dDz7MB2fJxYUSTlxgLBna@n4ZUJDmpqvpOMlIv4qoSdqpqtkJMT7/GMyEyIn/zQdv0HWnSA2TBA92RViG4sxmwrB5@4QflK/QNol5TOEfprYXCJpmCM2zy2RiN8ldpItlCf1U2SM8wwn/ZbIuKbS4essnSQNOZKqAsHzhL/IxkjsKT4iNhB8jIxxgvCXiJ2//U4uAxKrMdJXiehcIOsWiP7JRcJP/L9G0kzGMkvGPkXaKq6S9DP5ZFeUyNFfJPbk2IVDxpIlOufYoc0OMWJzlt0t7NQgPFfIrnhCaIjNWZK2PMFzD0g9SdsYicn4//wvT/8F "C (clang) – Try It Online") Just a pair of table lookups. Little endian only. [Answer] # PowerShell , 655 ``` $S="Ac227Ag108Al027Am243Ar040As075At210Au197B 011Ba137Be009Bi209Bk247Br080C 012Ca040Cd112Ce140Cf251Cl035Cm247Co059Cr052Cs133Cu064Dy163Er167Es252Eu152F 019Fe056Fm257Fr223Ga070Gd157Ge073H 001He004Hf178Hg201Ho165I 127In115Ir192K 039Kr084La139Li007Lu175Mg024Mn055Mo096N 014Na023Nb093Nd144Ne020Ni059Np237O 016Os190P 031Pa231Pb207Pd106Pm145Po209Pr141Pt195Pu244Ra226Rb085Re186Rh103Rn222Ru101S 032Sb122Sc045Se079Si028Sm150Sn119Sr088Ta181Tb159Tc098Te128Th232Ti048Tl204Tm169U 238V 051W 184Xe131Y 089Yb173Zn065Zr091" $a=$args[0][0];$b=$args[0][1];if(!$b){$b=" "}; for($i=0;$i-lt500;$i+=5){if(($a-match$s[$i])-and$b-match$s[$i+1]){$s[$i+2]+$s[$i+3]+$s[$i+4];break}} ``` the string s was constructed with ``` awk '{printf(\"%-2s %03d\n\",$3,$4)}' .\input.txt | sort | awk '{printf(\"%-2s%03d\",$1,$2)}' > .\output.txt ``` result as follows ![enter image description here](https://i.stack.imgur.com/9kszC.png) [Answer] # T-SQL, ~~627~~ 524 bytes ``` SELECT ISNULL((SELECT SUBSTRING(value,3,3)FROM STRING_SPLIT('B 11-F 19-Na23-Al27-P 31-K 39-Ar40-V 51-Mn55-Co59-Cu64-Se79-Sr88-Nb93-I 127-La139-Pr141-Nd144-Bi209-Po209-Rn222-Pa231-Np237-Am243-Cm247-Cf251','-')m,t WHERE s=LEFT(value,2)), (SELECT CHARINDEX(s,'H .He.LiBe.C N O ..Ne..Mg..Si..S .Cl..KCa...Sc.Ti..Cr..Fe.Ni....Zn...Ga.GeAs...Br..KRb..Y Zr...MoTc.RuRh.PdAg..Cd.In..Sn.Sb....Te.XeCs..Ba.Ce...Pm...SmEu...GdTb..DyHoErTm..YbLu.Hf.Ta.W Re..OsIr.PtAu..Hg.Tl.Pb.At...........Fr.RAc...Th....U ....Pu.Bk...Es...Fm') FROM t)) ``` Significant redesign, here, saved over 100 bytes. Here is how this one works, reading back to front: * The main piece here is a string (inside the `CHARINDEX()`, the dots are just filler) that *returns the element mass based on the string position*, for example, the letters `Ga` start at string position 70, which is the mass of Gallium. * That unfortunately doesn't work for elements that have the *same* mass (`Ar` and `Ca`, for example), or elements that differ with mass that differs only by one (`Al` and `Si`), so I have a more traditional lookup table (inside the `STRING_SPLIT()`) that covers the exceptions. * The `ISNULL()` statement pieces it all together: first it looks in the exception table, if that returns `NULL`, it instead returns the position from `CHARINDEX`. **Original version, 627 bytes**: ``` SELECT SUBSTRING(value,3,3) FROM STRING_SPLIT('H 1-He4-Li7-Be9-B 11-C 12-N 14-O 16-F 19-Ne20-Na23-Mg24-Al27-Si28-P 31 -S 32-Cl35-Ar40-K 39-Ca40-Sc45-Ti48-V 51-Cr52-Mn55-Fe56-Co59-Ni59-Cu64-Zn65-Ga70-Ge73 -As75-Se79-Br80-Kr84-Rb85-Sr88-Y 89-Zr91-Nb93-Mo96-Tc98-Ru101-Rh103-Pd106-Ag108-Cd112 -In115-Sn119-Sb122-Te128-I 127-Xe131-Cs133-Ba137-La139-Ce140-Pr141-Nd144-Pm145-Sm150 -Eu152-Gd157-Tb159-Dy163-Ho165-Er167-Tm169-Yb173-Lu175-Hf178-Ta181-W 184-Re186-Os190 -Ir192-Pt195-Au197-Hg201-Tl204-Pb207-Bi209-Po209-At210-Rn222-Fr223-Ra226-Ac227-Th232 -Pa231-U238-Np237-Pu244-Am243-Cm247-Bk247-Cf251-Es252-Fm257','-') ,t WHERE LEFT(value,2)=s ``` Returns are for formatting only. [Per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken via pre-existing table **t** with chemical symbol **s**. Joins to in-memory table derived from a delimited string. ]
[Question] [ *This is a repost of [Evolution of “Hello World!”](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world), originally written by user Helka Homba* *It should not be closed as a duplicated, due to meta consensus [here](http://meta.codegolf.stackexchange.com/a/11123/60042).* *The original was asked over two years ago and was last active more than six months ago. I have permission from Helka Homba to post this [here](http://chat.stackexchange.com/transcript/message/35687646#35687646)* *Since the original, many languages have been invented, and many people have joined the site who have never had an opportunity to answer the original, so I feel that this repost is acceptable.* --- The challenge is to make a program that prints `2^n` to stdout, where `n` is the number of your program. The catch is that your program must have a [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) of 10 or less from the program in the answer submitted before yours. # How This Will Work Below I will submit the first answer using C#, which prints 2^(n=1)=`2`. The next person to answer must modify the code with up to 10 single character insertions, deletions, or substitutions so that when it is run in the language of the new answer, it prints `2^n` (with `n` being the answer number). For example, the 25th answer (let's say it's in Pyth) would print 2^25, or 33554432. This will continue on until everyone get stuck because there is no new language the last answer's program can be made to run in by only changing 10 characters. The communal goal is to see how long we can keep this up, so try not to make any obscure or unwarranted character edits (this is not a requirement however). # Formatting Please format your post like this: ``` #Answer N - [language] [code] [notes, explanation, observations, whatever] ``` Where N is the answer number (increases incrementally, N = 1, 2, 3,...). You do not have to tell which exact characters were changed. [Just make sure the Levenshtein distance is from 0 to 10.](http://planetcalc.com/1721/) If you answer in some language or the resulting code is just a mess, *do please* explain what you did and why it works, though this isn't required. # Rules 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. Furthermore... * 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.) * Try to avoid posting too many answers in a short time frame. * Each answer must be in a different programming language. + You may use different major versions of a language, like Python 2/3 + Languages count as distinct if they are traditionally called by two different names. (There may be some ambiguities here but don't let that ruin the contest.) * You do not have to stick to ASCII, you can use any characters you want. Levenshtein distance will be measured in unicode **characters**. * The output should only be `2^n` and no other characters. (Leading/trailing whitespace is fine, as is unsuppressible output like `>>>` or `ans=`) * If your language doesn't have stdout use whatever is commonly used for quickly outputting text (e.g. `console.log` or `alert` in JavaScript). * When the power of two you have to output gets very large, you may assume infinite memory, but not an infinite integer size. Please be wary of integer overflows. * You may make use of scientific notation or whatever your languages most natural way of representing numbers is. (Except for unary, *DO NOT* output in unary) **Please make sure your answer is valid.** We don't want to realize there's a break in the chain five answers up. Invalid answers should be fixed quickly or deleted before there are additional answers. **Don't edit answers unless absolutely necessary.** # Scoring Once things settle down, the user who submits the most (valid) answers wins. Ties go to the user with the most cumulative up-votes. ## Edit these when you post an answer: ### Leaderboard > > ### 13 languages > > > Okx > > > > ### 8 languages > > > zeppelin > > > > ### 4 languages > > > Pavel > > Jonathan Allan > > Kritixi Lithos > > Riker > > > > ### 3 languages > > > boboquack > > > > ### 2 languages > > > bmarks > > Conor O'Brien > > Destructible Watermelon > > ovs > > Tom Carpenter > > > > ### 1 language > > > ATaco > > Blocks > > Dennis > > dzaima > > Erik the Outgolfer > > ETHproductions > > ghosts\_in\_the\_code > > Leo > > Lynn > > Matheus Avellar > > Nathaniel > > Qwerp-Derp > > R. Kap > > Taylor Raine > > nimi > > Mistah Figgins > > PidgeyUsedGust > > steenbergh > > > > ### Languages used so far: > > 1. C# (Pavel) > 2. /// (boboquack) > 3. Retina (Dennis) > 4. Jelly (Jonathon Allan) > 5. Pyth (boboquack) > 6. ><> (Destructible Watermelon) > 7. Minkolang (Kritixi Lithos) > 8. Perl (Pavel) > 9. Python (Qwerp-Derp) > 10. dc (R. Kap) > 11. Charcoal (Jonathon Allan) > 12. Self Modifying BrainFuck (Leo) > 13. SOGL (dzaima) > 14. ShapeScript (Jonathon Allan) > 15. Pyke (boboquack) > 16. Ruby (Nathaniel) > 17. 05AB1E (ovs) > 18. STATA (bmarks) > 19. bc (Kritixi Lithos) > 20. Japt (Okx) > 21. 2sable (Kritixi Lithos) > 22. Cheddar (Jonathon Allan) > 23. Pylons (Okx) > 24. Bash (zeppelin) > 25. Pushy (Okx) > 26. CJam (Erik the Outgolfer) > 27. MATL (Okx) > 28. MATLAB (Tom Carpenter) > 29. Octave (Kritixi Lithos) > 30. R (ovs) > 31. JavaScript ES7 (Tom Carpenter) > 32. Convex (Okx) > 33. Mathematica (ghosts\_in\_the\_code) > 34. Pip (Okx) > 35. Stacked (Conor O'Brien) > 36. GolfScript (Okx) > 37. Actually (Lynn) > 38. RProgN (Okx) > 39. Scheme (bmarks) > 40. Element (Okx) > 41. J (Blocks) > 42. Cubix (ETHproductions) > 43. zsh (zeppelin) > 44. VBA (Taylor Raine) > 45. Fish (zeppelin) > 46. Reticular (Okx) > 47. Perl 6 (Pavel) > 48. RProgN2 (ATaco) > 49. PHP (Matheus Avellar) > 50. Jolf (Conor O'Brien) > 51. Haskell (nimi) > 52. Befunge-98 (Mistah Figgins) > 53. Gnuplot (zeppelin) > 54. QBIC (steenbergh) > 55. FOG (Riker) > 56. Qwerty-RPN (Okx) > 57. Korn Shell (ksh) (zeppelin) > 58. Julia (Riker) > 59. Python 3 (Pavel) > 60. Vimscript (Riker) > 61. Dash (zeppelin) > 62. Vitsy (Okx) > 63. csh (zeppelin) > 64. Ohm (Okx) > 65. Bosh (zeppelin) > 66. es-shell (Riker) > 67. Gol><> (PidgeyUsedGust) > > > This question works best when you [sort by oldest](https://codegolf.stackexchange.com/questions/111310/evolution-of-powers-of-two?answertab=oldest#tab-top). [Answer] # Answer 67, [Gol><>](https://github.com/Sp3000/Golfish/wiki), distance 6 We van use the trampoline `#` to just append the code in reverse. By removing `S)1'a` the `;` can be reused, needing only 6 characters to be added. ``` #64º,;n*:"C" "bc"<<x 2^66 x #??92a5*2p@^54┘#--2'3k:'2k*.@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`#(expt 2 39); ^ quit() @n.out (*2 32#e#a44******O@) //2 25) "e "2ej : py p riker i n t (2**60) "%d" $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# ``` [Try it online!](https://golfish.herokuapp.com/?code=%2364%C2%BA%2C%3Bn%2a%3A%22C%22%0A%22bc%22%3C%3Cx%0A2%5E66%0Ax%0A%23%3F%3F92a5%2a2p%40%5E54%E2%94%98%23--2'3k%3A'2k%2a.%402%28%23%22%2328%40P2%2aJp%3Bmath%202%5C%5E45%232%5E41%20NB.%60%23%28expt%202%2039%29%3B%20%5E%20%0Aquit%28%29%0A%40n.out%20%28%2a2%2032%23e%23a44%2a%2a%2a%2a%2a%2aO%40%29%20%2F%2F2%2025%29%0A%22e%0A%222ej%0A%3A%0Apy%20%0Ap%0Ariker%0Ai%0An%0At%0A%282%2a%2a60%29%0A%22%25d%22%20%24%5B2%2a%2a43%5Dbye'%24%2F%2a%23%22A%23327%3BN%3C.%22%24%22%2Fclass%20HelloWorld%20%7Bstatic%20void%20Main%28%29%200%7B%3Bn%2a%2a%2a%7e%23&input=) I think keeping the `#` allows for some other languages to use it as a commented line. [Answer] # Answer 64, [Ohm](https://github.com/MiningPotatoes/Ohm), distance 10 ``` 64º,;S)1'a"bc"<<x 2^63 x #??92a5*2p@^54┘#--2'3k:'2k*.@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`#(expt 2 39); ^ exit @n.out (*2 32#e#a44******O@) //2 25) "e "2ej :py print(2**60) "%d" $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024print(2**53)--0;#0}}//4|#6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` Added `64º,;S)1'a` Only the `64º,` is actual code, the rest is just junk. This program will print the correct output, but it will also ask for some `STDIN` *after* it has printed 264. [Answer] # Answer 17: [05AB1E](https://github.com/Adriandmen/05AB1E), Distance of 3 ``` #"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<. #1024p#rint(512); #0}}//4| #β”6904”±r«"$2 puts 16384 8* ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@s9H7PQmVjI3NrPxs9JRUl/eScxOJiBY/UnJz88PyinBSF6uKSxJLMZIWy/MwUBd/EzDwNTQWDaus8LS2tOi5lBSAIriwuSc210XPOzyvOz0m10bPR41I2NDAyKVAuyswr0TA1NNK05lI2qK3V1zep4VI@t@lRw1wzSwMTIHVoY9Gh1UoqRgpcBaUlxQqGZsYWJgoWWv//AwA "05AB1E – TIO Nexus") [Answer] # Answer 24: Bash, distance 8 ``` #23#2ej printf $[2**24] #'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<. #1024p#rint(512); #0}}//4| #ß”6904”±r«"$2 #puts 16384 8*di 2^18o8*' ``` [Try It Online !](https://tio.run/nexus/bash#@69sZKysZZSaxVVQlJlXkqagEm2kpWVkEsulrK6ir6Ws5KhsbGRu7Wejp6SipJ@ck1hcrOCRmpOTH55flJOiUF1ckliSmaxQlp@ZouCbmJmnoalgUG2dp6WlVcelrAAEwZXFJam5NnrO@XnF@TmpNno2elzKhgZGJgXKIAs1TA2NNK25lA1qa/X1TWq4lA/Pf9Qw18zSwARIHdpYdGi1koqRwv//AA) [Answer] ## Answer 51, Haskell, distance 10 ``` --2@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.out (*2 32#e#a44******O@)//2 25)#e#2ej#printf("% $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024 print(2^51)--;#0}}//4|#6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` Remove 2 NL, replace `^` at the beginning with `-`, prepend another `-`, delete `*` within the `print`, replace 2nd `*` with `^`, overwrite `49`with `51`, insert `--` after the print. [Answer] # Answer 4: [Jelly](https://github.com/DennisMitchell/jelly) distance 3 ``` /class HelloWorld {static void Main() 0{ System.Console.Write(2); 0}}//4| 8Ḥ ``` **[Try it online!](https://tio.run/nexus/jelly#@6@fnJNYXKzgkZqTkx@eX5STolBdXJJYkpmsUJafmaLgm5iZp6GpYFDNpQAEwZXFJam5es75ecX5Oal64UWZJakaRprWXAa1tfr6JjVcFg93LPn/HwA "Jelly – TIO Nexus")** all insertions: `00Ḥ`. `0{` and `0}` are there to suppress parsing errors (pop from empty list due to the `{` and `}` being quicks that turn monads into dyads using the left and right argument respectively). `Ḥ` "unhalves" 8 to make 16. [Answer] # Answer 5: [Pyth](https://esolangs.org/wiki/Pyth) ``` 32 "/class HelloWorld {static void Main() 0{ System.Console.Write(2); 0}}//4| 8Ḥ ``` Prints the numeric literal `32`, then the space between the `2` and the `"` suppresses printing of the (auto-completed) string literal. +4 characters - `32 "` [Try it on herokuapp](https://pyth.herokuapp.com/?code=32+%22%2Fclass+HelloWorld+%7Bstatic+void+Main%28%29+0%7B%0A++++System.Console.Write%282%29%3B%0A0%7D%7D%2F%2F4%7C%0A8%E1%B8%A4&debug=0) [Answer] # Answer 6 - ><> ``` 32""/class HelloWorld {static void Main() 0{;n***~ System.Console.Write(2); 0}}//4| 8Ḥ ``` replaced a space with ", the code pushes 3, 2, 4, then reverses, pushes 4,2,3, then pops 3 off the stack, and multiplies 2, 4, 4, 2, for 64, outputs it and halts [Try it online](https://tio.run/nexus/fish#@29spKSkn5yTWFys4JGak5Mfnl@Uk6JQXVySWJKZrFCWn5mi4JuYmaehqWBQbZ2npaVVx6UABMGVxSWpuXrO@XnF@TmpeuFFmSWpGkaa1lwGtbX6@iY1XBYPdyz5/x8A) maybe use <https://www.fishlanguage.com/playground> [Answer] # Answer 3: [Retina](https://github.com/m-ender/retina), distance 3 ``` /class HelloWorld {static void Main() { System.Console.Write(2); }}//4| 8 ``` Appended `|\n8` (distance 3). [Try it online!](https://tio.run/nexus/retina#@6@fnJNYXKzgkZqTkx@eX5STolBdXJJYkpmsUJafmaLgm5iZp6GpUM2lAATBlcUlqbl6zvl5xfk5qXrhRZklqRpGmtZctbX6@iY1XBb//wMA "Retina – TIO Nexus") [Answer] # Answer 20: Japt, distance 8 ``` 2**20$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<. #1024p#rint(512); #0}}//4| #ß”6904”±r«"$2 #puts 16384 8*di 2^18*/ ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=MioqMjAkLyojIkEjMzI3O048LiIkIi9jbGFzcyBIZWxsb1dvcmxkIHtzdGF0aWMgdm9pZCBNYWluKCkgMHs7bioqKn4KIyAgICBTeXN0ZW08LkNvbnNvbGU8LjwuCiMxMDI0cCNyaW50KDUxMik7CiMwfX0vLzR8CiPfXHUyMDFkNjkwNFx1MjAxZLFyqyIkMiAKI3B1dHMgMTYzODQgOCpkaSAyXjE4Ki8=&input=) Modifications: Changed `2^19` to `2**20` at the start of the program, to calculate the power (4) Replaced `#` with `$` on the first line so that everything past it is interpreted as JS (1) On the last line, removed the `/` and added a `*/` at the end of the program, so the comment takes up the whole program (3) [Answer] # Answer 27: MATL, distance 4 ``` 27W%2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß”6904”±r«"$2 #puts 16384 8*di 2^18o8*' ``` [Try it online!](https://matl.suever.net/?code=27W%252+25%29%23e%232ej%23printf+%24%5B2%2a%2a24%5D%23%27%24%2F%2a%23%22A%23327%3BN%3C.%22%24%22%2Fclass+HelloWorld+%7Bstatic+void+Main%28%29+0%7B%3Bn%2a%2a%2a~%23++++System%3C.Console%3C.%3C.%231024p%23rint%28512%29%3B%230%7D%7D%2F%2F4%7C%23%C3%9F%E2%80%9D6904%E2%80%9D%C2%B1r%C2%AB%22%242+%23puts+16384+8%2adi+2%5E18o8%2a%27&inputs=&version=19.8.0) Added `27W%` Explanation: ``` W 2 to the power of 27 27 % Start of single line comment ``` [Answer] # Answer 50: Jolf, distance 10 ``` ^2@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.out (*2 32#e#a44******O@)//2 25)#e#2ej#printf("% $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<.#1024 print(2**49);#0}}//4| #6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=XjJAMigjIiMyOEBQMipKcDttYXRoIDJcXjQ1IzJeNDEgTkIuYChleHB0IDIgMzkpOyBeIGV4aXQgQG4ub3V0ICgqMiAzMiNlI2E0NCoqKioqKk9AKS8vMiAyNSkjZSMyZWojcHJpbnRmKCIlICRbMioqNDNdYnllJyQvKiMiQSMzMjc7TjwuIiQiL2NsYXNzIEhlbGxvV29ybGQge3N0YXRpYyB2b2lkIE1haW4oKSAweztuKioqfgojICAgIFN5c3RlbTwuQ29uc29sZTwuPC4jMTAyNApwcmludCgyKio0OSk7IzB9fS8vNHwKIzY5MDRyIiQyICNwdXRzIDE2Mzg0IDgqZGkgMl4xOG84KicqW1tbMjY4Kl4_Pg) Prepended `^2@2(` (+5) Removed `±` and `ß` from `#ß6904±r` (+2) Removed `ó` from `óout` (+1) Removed `<?` from `<?#"#28@P2*` (+2) Total: 10. *Remove all the non-ASCII characters!* ## Explanation `(` stops parsing, so the code looks like: ``` ^2@2 ^ exponentiate 2 two @2 to the 50 (char code of 2) ``` [Answer] # Answer 52. [Befunge-98](http://quadium.net/funge/spec98.html), distance 8 + 2 Thanks to [@DestructibleWatermelon](http://chat.stackexchange.com/transcript/message/35705126#35705126) for golfing a byte! ``` --2'3k:'2k*.@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.out (*2 32#e#a44******O@)//2 25)#e#2ej#printf("%d" $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024 print(2^51)--;#0}}//4|#6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` [Try it Online!](https://tio.run/nexus/befunge-98#Hc3BToNAFEDRvV/xMg8DTMIAj2mlgSjqxphYTVy4QIlYxoilDIGpaVPrryPpXZ7NHT3PjtZk05qLjBxkSHH2RPy@Szal@QJ6LeQMqZAhLG/Eu6N2nQGCaOEmUIDa1QayVuitAYdPTKiwlJKfesxc3yegmTspqW/s@ro1nw47rxhYOXEuo7ePvbItnyO7xogukmUqmMX8VVMOA9ypptEvum8qOAymNPUKfnRdwUNZt44LwSFpp80fwtTzfjBqk4pb3Q66UalIBYYBybPT1KFiFrqel2BwPPq@/MX5IpA9swiw25oBwnkUS4h5VQMVYaxjbvM8z2ke8@Lqchz/AQ) Added `'3k` before the `2`, and `'2k*.` between the `2` and `@`. `--` does nothing, `'3k2` puts 52 2s onto the stack, and `'2k*.@` multiplies them together, prints the number, and exits Also, I added a `d"` after `printf("%` to make other people's lives easier, as I had 2 extra characters. It doesn't affect the Befunge-98 program. [Answer] # Answer 42: [Cubix](https://github.com/ETHproductions/cubix), distance 8 ``` 2^41 NB.`(expt 2 39); ^ exit @ⁿ.óout (*2 32#e#a44******O@)//2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß6904±r"$2 #puts 16384 8*di 2^18o8*'* ``` [Try it online!](https://tio.run/nexus/cubix#HY1BSsNAFIav8sgLNJnFTOZlWlOSRdWNG@vCRRdiMDQjjMRMyEylUit4Es8gHkCwN/EiMe23/D/4v4FKJWF5wR8ive08EKTzOIcS9NZ4WPx9/PDDt914iNioCDVWSrETN4tYCAKaxuNK@gm73rT@EcI7YozUPU5CwTA4x5TO8mXBgzAQ66ZyDq5009iV7Zsads5X3qzhxZoarivTRjEku7wd/98RRm5fndfPBb@0rbONLnjBUSakOjzWoqmkOMdkvxdCveHhczZP1O9XH4QE2G28AzlLMwUZqw1QKTObsQkbhn8) The `lert(2**31` in the middle was changed to `44******O@`. [Answer] # Answer 60, Vimscript, distance 10 ``` "bc<<<2^57 #x??92a5*2p@^54┘#--2'3k:'2k*.@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`#(expt 2 39); ^ exit @n.out (*2 32#e#a44******O@) //2 25) "e "2ej :py print(2**60) "%d" $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024print(2**53)--0;#0}}//4|#6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` Changed the 2 `#` on the start of the middle two lines to `"`, added a `"` in front of the first line, and `:py<space>` in front of the last line. For clarification: `"` is a line comment in vimscript (at least at the start of a line), and doesn't need to be matched. Vim can run python code, so this is really equivalent to asking python for the answer. [Answer] # Answer 8: Perl ``` #327;N.""/class HelloWorld {static void Main() 0{;n***~ # System.Console. print(256); #0}}//4| #8Ḥ ``` Exactly distance of 10: +4 `#` for comments, +1 newline after `System.Console.`, +3 for transforming `write` into `print`, +2 for turning `2` into `256`. I wasn't going to participate, but I wanted to make sure some regular langs were added before anything got too insane. [Try it online!](https://tio.run/nexus/perl#@69sbKSkpJ@ck1hcrOCRmpOTH55flJOiUF1ckliSmaxQlp@ZouCbmJmnoalgUG2dp6WlVcelrAAEwZXFJam5es75ecX5Oal6XAVFmXklGkamZprWXMoGtbX6@iY1XMoWD3cs@f8fAA "Perl – TIO Nexus") [Answer] # Answer 49: PHP, distance 6 ``` <?#"#28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.óout (*2 32#e#a44******O@)//2 25)#e#2ej#printf("% $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<.#1024 print(2**49);#0}}//4| #ß6904±r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` Added `<?` and `?>` to open and close PHP tags, respectively. Replaced `48` with `49`. `#` starts a comment on PHP, so nothing is considered except for ``` <? print(2**49); ?> ``` Here's a screenshot of proper syntax highlihgting and output to help visualize: [![screenshot](https://i.stack.imgur.com/AyLZE.png)](https://i.stack.imgur.com/AyLZE.png) [Answer] # Answer 2: [///](https://esolangs.org/wiki////) ``` /class HelloWorld {static void Main() { System.Console.Write(2); }}//4 ``` +4 chars - `///4` [Try it online!](https://tio.run/nexus/slashes#@6@fnJNYXKzgkZqTkx@eX5STolBdXJJYkpmsUJafmaLgm5iZp6GpUM2lAATBlcUlqbl6zvl5xfk5qXrhRZklqRpGmtZctbX6@ib//wMA) [Answer] # Answer 7: [Minkolang](https://github.com/elendiastarman/Minkolang), Distance: 4 ``` 327;N.""/class HelloWorld {static void Main() 0{;n***~ System.Console.Write(2); 0}}//4| 8Ḥ ``` [Try it online!](https://tio.run/nexus/minkolang#@29sZG7tp6ekpJ@ck1hcrOCRmpOTH55flJOiUF1ckliSmaxQlp@ZouCbmJmnoalgUG2dp6WlVcelAATBlcUlqbl6zvl5xfk5qXrhRZklqRpGmtZcBrW1@vomNVwWD3cs@f8fAA "Minkolang – TIO Nexus") I added `7;N.` to the program. Basically `3`, `2` and `7` are pushed to the stack and then 2 is raised to the seventh power using `;`. This is then outputted as a `N`umber and then the program stops on the `.` [Answer] # Answer 11: [Charcoal](https://github.com/somebody1234/Charcoal), distance 5 ``` A#327;N.""/class HelloWorld {static void Main() 0{;n***~ # System.Console. 1024p#rint(512); #0}}//4| β2048 ``` **[Try It Online!](https://tio.run/nexus/charcoal#@/9@z0JlYyNzaz89JSX95JzE4mIFj9ScnPzw/KKcFIXq4pLEksxkhbL8zBQF38TMPA1NBYNq6zwtLa06LmUFIAiuLC5JzdVzzs8rzs9J1eMyNDAyKVAuyswr0TA1NNK05lI2qK3V1zep4Tq3ycjAxOL/fwA)** The uppercase Greek letters `A` and `β` are variables which are assigned the ASCII characters following. The final value is implicitly printed. [Answer] # Answer 10: [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), Distance of 5 ``` #327;N.""/class HelloWorld {static void Main() 0{;n***~ # System.Console. 1024p#rint(512); #0}}//4| #8 ``` Here is a valid `dc` program which outputs `1024`. [Try it online!](https://tio.run/nexus/dc#@69sbGRu7aenpKSfnJNYXKzgkZqTkx@eX5STolBdXJJYkpmsUJafmaLgm5iZp6GpYFBtnaelpVXHpawABMGVxSWpuXrO@XnF@TmpelyGBkYmBcpFmXklGqaGRprWXMoGtbX6@iY1XMoW//8DAA "dc – TIO Nexus") [Answer] # Answer 12: [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/) ``` A#327;N<.""/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<. 1024p#rint(512); #0}}//4| #β6904 ``` [Try it online!](https://tio.run/nexus/smbf#@/9@z0JlYyNzaz8bPSUl/eScxOJiBY/UnJz88PyinBSF6uKSxJLMZIWy/MwUBd/EzDwNTQWDaus8LS2tOi5lBSAIriwuSc210XPOzyvOz0m10bPR4zI0MDIpUC7KzCvRMDU00rTmUjaordXXN6nhUj63yczSwOT/fwA "Self-modifying Brainfuck – TIO Nexus") SMBF is just like brainfuck, except the source code is available on the tape to the left of the starting position. Here we have the number to print in reverse at the end of the code, and we do `<.` four times to print all four digits. I added a `<` before each `.` in the code (there were 3 of them), an extra `<.`, and modified the final number. Distance should be 8. [Answer] # Answer 29: [Octave](https://www.gnu.org/software/octave/), Distance: 1 ``` disp(2^29)%2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß”6904”±r«"$2 #puts 16384 8*di 2^18o8*' ``` [Try it online!](https://tio.run/nexus/octave#Fc09isJAGIDhq3zki5hMkZ/PMSYkjdjYuM0WFqIQzAgjYyZkxoXFH7zI4gGs9gp6Ey8S9W2e8u0qaRqPVpT5PQIa@iiQxBabVtZ2A@6CGCO@xL4bMnTGOKBR/lUEjuuEa1UaA1OhlJ7rVlVwMLa0cg0/WlYwK2Xt@RAd8poxdkZ49/1rrNgVwUTXRitRBEWAcUS8wc/NG8bk5xidTmHIj/i4Pi9/SRbxN/f/9n5zXAJs9tZAnAxSDimrJNAqTnXK@l33Ag "Octave – TIO Nexus") All I had to do was to change the `28` to `29` [Answer] # Answer 31: JavaScript ES7, Distance 7 ``` alert(2**31)//2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß”6904”±r«"$2 #puts 16384 8*di 2^18o8*' ``` ES7 supports the `**` operator for power. You can [try online here](https://babeljs.io/repl/). [Answer] # Answer 33: Mathematica, distance 9 ``` 2^33 (*2 32#e#alert(2**31)//2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß”6904”±r«"$2 #puts 16384 8*di 2^18o8*'*) ``` Explanation Puts everything inside comments and outputs 2^33 *Please verify that this answer is valid before putting your own because I am new at this and don't want to end up breaking the chain.* [Answer] # Answer 37: [Actually](https://github.com/Mego/Seriously), distance 7 ``` 2:37@ⁿ.óout (*2 32#e#alert(2**31)//2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß6904±r"$2 #puts 16384 8*di 2^18o8*'* ``` Replaced `36?#` with `:37@ⁿ.ó`. [Try it online!](https://tio.run/nexus/actually#FY1BSsQwFECv8ukvTPsXSfOTmam2C8WNG924cDEolGmESmxKkxFkHMGTeAbxAIJzEy9S61u@t3gTn@r12e/7tzh@@V2EjBg0o8XG2TFmTKRVLiUDL/PZsn3EYez6@ADpZo5s7nCRSsLkHDWvq@taJGkit64JAS6tc/7Wj66FfYhN7Lbw7LsWrpquz3Io9lVPRG8IMzcvIdqnWlz4Pnhna1ELVAWbAf9v2VJxXmFxOEhpXvH4sTopzM/nmKQMOOxiALXSpYGS2g74XpW@pAVN0x8 "Actually – TIO Nexus") [Answer] # Answer 38: RProgN, distance 10 ``` 2 38 ^ exit @ⁿ.óout (*2 32#e#alert(2**31)//2 25)#e#2ej#printf $[2**24]#'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024p#rint(512);#0}}//4|#ß6904±r"$2 #puts 16384 8*di 2^18o8*'* ``` [Try it online!](https://tio.run/nexus/rprogn#FY1BSsQwFECv8ukvTPsXSfPbGSPtQnHjRjcuXMgMlGmESGxKkxFlHMGTeAbxAIJzEy9S61u@t3gTQ6lhA@bZRjj7ff8Wxy@/i5DRHBgNts6MMWOiUuVSMvAyny2bBxxG28d7SO/myNUaF6kkTM6x5JP6uhFJmsita0OAS@Ocv/Wj62AfYhvtFp687eCqtX2WQ7GveyJ6Q5i5eQnRPDbiwvfBO9OIRqAquBrw/5YtFec1FoeDlNUrHj9Wp0X18zkmKQMOuxhArUpdgabOAm@U9poWNE1/ "RProgN – TIO Nexus") Replaced `2:37` with `2 38 ^ exit` (10) (note the trailing space) Explanation: ``` 2 2 ^ to the power of 38 38 exit Stop the prgram ``` [Answer] # Answer 47: [Perl 6](https://perl6.org), distance 10 ``` #28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.óout (*2 32#e#a44******O@)//2 25)#e#2ej#printf("% $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<.#1024 print(2**47);#0}}//4| #ß6904±r"$2 #puts 16384 8*di 2^18o8*'* ``` Perl 6 is considered distinct from Perl. I tried to set up C down the road by adding `"%` after `printf`, hopefully someone uses that. [Try it online!](https://tio.run/nexus/perl6#Hc1BToNAGIbhPaf4w2AKkzjAz7SlgQXqxphYTVy4UIkjjCmGzhCYmjZtvYpnMN7Ansk1Yt/l9y2enmCc3SK9apKlMAvAx5yPCeY8hPk5e3blujGAEM28BHKQ68pAptjhW68MuHQ4kEgiOKfHbjLP9xFw7A0ryjfStJUyr659As4DUsqjp5eNHDk@JfYZiXCazFNmO7Zf1KLr4FLWtb7XbV3CtjPCVAW866qEa1Ep14Ngm6gB@bAIDN1tOiOXKbvQqtO1TFnKSBggt46m@69NvYQE@73v851FDp@TWcB/vlrbQSDNynQQTqKYQ0zLCjAPYx3TEe37X6VPC1Es5B8 "Perl 6 – TIO Nexus") [Answer] # Answer 48: [RProgN2](https://github.com/TehFlaminTaco/RProgN-2), distance 9 ``` "#28@P2*Jp;math 2\^45#2^41 NB.`(expt 2 39); ^ exit @n.óout (*2 32#e#a44******O@)//2 25)#e#2ej#printf("% $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~ # System<.Console<.<.#1024 print(2**47);#0}}//4| #ß6904±r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^ ``` Added a `"` to the start which stopped everything from breaking, the `[[[` at the end clears the memory, and `268*^` calculates the new answer. Implicitly printed. [Try it online!](https://tio.run/nexus/rprogn-2#Hc1NToNAGMbxPad4w2AKk8jHy5TSwAJ1Y0ysJi5coESEMR1DZwhMTZtar@IZjDewZ3KN2P/yeRa/wSQYZ7dIr9pkVeol4EPBpgQLFsDi3H2y@abVgBDOnQQK4BuhIZPu4VutNdh0PJBwUjJGj91kjuch4NQZV@SvpO2E1C@2eQJWjpSy8PF5yyeWR4l5RkKcJYvUNS3Tq5qy7@GSN426V11Tw67XpRYVvClRw3UppO2Av0vkiHwYBMbutr3mq9S9ULJXDU/d1CWBj8w4mva/NnMS4u/3nsfeDXL4jOY@@/nqTAuBtGvdQxCFMYOY1gKwCGIV0wnN8xyjmBbD8CvVaVVWS/4H "RProgN 2 – TIO Nexus") [Answer] # Answer 66, es (shell) + `bc`, distance 8 ``` #64º,;S)1'a "bc"<<x 2^66 x #??92a5*2p@^54┘#--2'3k:'2k*.@2(#"#28@P2*Jp;math 2\^45#2^41 NB.`#(expt 2 39); ^ quit() @n.out (*2 32#e#a44******O@) //2 25) "e "2ej : py p riker i n t (2**60) "%d" $[2**43]bye'$/*#"A#327;N<."$"/class HelloWorld {static void Main() 0{;n***~# System<.Console<.<.#1024print(2**53)--0;#0}}//4|#6904r"$2 #puts 16384 8*di 2^18o8*'*[[[268*^?> ``` Changed `exit` to `quit()`, and added `iker` after the first `r`. I couldn't resist and I wanted to add 4 more characters. ]
[Question] [ In the C programming language, arrays are defined like this: ``` int foo[] = {4, 8, 15, 16, 23, 42}; //Foo implicitly has a size of 6 ``` The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order: ``` int foo[6]; //Give the array an explicit size of 6 foo[0] = 4; foo[1] = 8; foo[2] = 15; foo[3] = 16; foo[4] = 23; foo[5] = 42; ``` # The challenge You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible. The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this: ``` <type> <array_name>[] = {<int>, <int>, <int> ... }; ``` "Type" and "array\_name" will made up entirely of alphabet characters and underscores `_`. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled. The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed. # Test IO: ``` #in short array[] = {4, 3, 2, 1}; #out short array[4]; array[0] = 4; array[1] = 3; array[2] = 2; array[3] = 1; #in spam EGGS[] = {42}; #out spam EGGS[1]; EGGS[0] = 42; #in terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13}; #out terrible_long_type_name awful_array_name[5]; awful_array_name[0] = 7; awful_array_name[1] = -8; awful_array_name[2] = 1337; awful_array_name[3] = 0; awful_array_name[4] = 13; ``` Submissions in any language are encouraged, but bonus points if you can do it *in* C. # Leaderboard: Here is a leaderboard showing the top answers: ``` var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Vim, ~~54, 52, 49~~ 47 keystrokes --- ``` 2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P ``` Explanation: ``` 2wa0<esc> 'Move 2 words forward, and insert a 0. qq 'Start recording in register Q Yp 'Duplicate the line <c-a>6l 'Increment the next number then move 6 spaces right df 'Delete until the next space @qq@q 'Recursively call this macro ``` Now our buffer looks like this: ``` int foo[0] = {4, 8, 15, 16, 23, 42}; int foo[1] = {8, 15, 16, 23, 42}; int foo[2] = {15, 16, 23, 42}; int foo[3] = {16, 23, 42}; int foo[4] = {23, 42}; int foo[5] = {42}; int foo[6] = {42}; ``` and our cursor is on the last line. Second half: ``` $ 'Move to the end of the line dT] 'Delete back until we hit a ']' dd 'Delete this whole line. :%norm <CR> 'Apply the following keystrokes to every line: dw 'Delete a word (in this case "int") f{x '(f)ind the next '{', then delete it. wC; 'Move a word, then (C)hange to the end of this line, 'and enter a ';' ``` Now everything looks good, we just need to add the original array-declaration. So we do: ``` gg 'Move to line one "0P 'Print buffer '0' behind us. Buffer '0' always holds the last deleted line, 'Which in this case is "int foo[6];" ``` [Answer] # Pyth, 44 bytes ``` ++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\; ``` [Test suite](https://pyth.herokuapp.com/?code=%2B%2BKhcz%5C%5DlJ%3Az%22-%3F%5Cd%2B%221%22%5D%3B%22VJs%5BecKd~hZ%22%5D+%3D+%22N%5C%3B&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0) Regular expression and string chopping. Not particularly clever. Explanation: ``` ++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\; Implicit: z = input() cz\] Chop z on ']' h Take string before the ']' K Store it in K + Add to that :z"-?\d+"1 Find all numbers in the input J Store them in J l Take its length. + "];" Add on "];" and print. VJ For N in J: s[ Print the following, concatenated: cKd Chop K on spaces. e Take the last piece (array name) ~hZ The current interation number "] = " That string N The number from the input \; And the trailing semicolon. ``` [Answer] # Retina, ~~108~~ ~~104~~ ~~100~~ 69 bytes Byte count assumes ISO 8859-1 encoding. ``` ].+{((\S+ ?)+) $#2];$1 +`((\w+\[).+;(\S+ )*)(-?\d+).+ $1¶$2$#3] = $4; ``` Beat this, PowerShell... ## Code explanation **First line:** `].+{((\S+ ?)+)` First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: `].+{`. Then we match the number list. Shortest I've been able to find so far is this: `((\S+ ?)+)`. We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: `\S+ ?`. This group of characters is then repeated as many times as needed: `(\S+ ?)+` and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why. **Second line:** `$#2];$1` Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: `$#2`. The replace modifier `#` helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group `2`. Then we put a closing bracket and a semicolon, and finally our whole list. With input `short array[] = {4, 3, 2, 1};`, the internal representation after this replacing is: ``` short array[4];4, 3, 2, 1}; ``` (note the closing curly brace and semicolon) **Third line:** `+`((\w+[).+;(\S+ )*)(-?\d+).+` This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: `(\w+\[)`. Then an arbitrary number of any characters and a semicolon: `.+;`. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: `(\S+ )*`. Then we capture the last number in the list: `(-?\d+)` and any remaining characters behind it: `.+`. **Fourth line:** `$1¶$2$#3] = $4;` We then replace it with the array name and list followed by a newline: `$1¶`. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially `list.length - 1`): `$2$#3`. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: `] = $4;` After first replacing, the internal representation looks like this: ``` short array[4];4, 3, 2, array[3] = 1; ``` Note that the closing curly brace and the semicolon disappeared, thanks to the `.+` at the end of third line. After three more replacings, the internal representation looks like this: ``` short array[4]; array[0] = 4; array[1] = 3; array[2] = 2; array[3] = 1; ``` Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned. **TL;DR:** First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back. [Try it online!](http://retina.tryitonline.net/#code=XS4reygoXFMrID8pKykKJCMyXTskMQorYCgoXHcrXFspLis7KFxTKyApKikoLT9cZCspLisKJDHCtiQyJCMzXSA9ICQ0Ow&input=dGVycmlibGVfbG9uZ190eXBlX25hbWUgYXdmdWxfYXJyYXlfbmFtZVtdID0gezcsIC04LCAxMzM3LCAwLCAxM307) [Answer] # C, 215 bytes, 196 bytes *19 bytes saved thanks to @tucuxi!* **Golfed:** ``` char i[99],o[999],b[99],z[99];t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);} ``` **Ungolfed:** ``` /* * Global strings: * i: input string * o: output string * b: input array type * z: input array name */ char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ]; /* Global ints initialized to zeros */ t, x, n, c; main() { /* Grab input string from stdin, store into i */ gets( i ); /* Grab the <type> <array_name> and store into b and z */ sscanf( i, "%s %[^[]s", b, z ); /* Grab only the int values and concatenate to output string */ while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 ) { /* Format the string and store into a */ sprintf( o, "%s[%d] = %d;\n", z, c++, x ); /* Get the current location of the pointer */ t += n; } /* Print the <type> <array_name>[<size>]; and output string */ printf( "%s %s[%d];\n%s", b, z, c, o ); } ``` **Link:** <http://ideone.com/h81XbI> **Explanation:** To get the `<type> <array_name>`, the `sscanf()` format string is this: ``` %s A string delimited by a space %[^[] The character set that contains anything but a `[` symbol s A string of that character set ``` To extract the int values from the string `int foo[] = {4, 8, 15, 16, 23, 42};`, I essentially tokenize the string with this function: ``` while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 ) ``` where: * `i` is the input string (a `char*`) * `t` is the pointer location offset of `i` * `x` is the actual `int` parsed from the string * `n` is the total characters consumed, including the found digit The `sscanf()` format string means this: ``` %* Ignore the following, which is.. [^0-9] ..anything that isn't a digit %d Read and store the digit found %n Store the number of characters consumed ``` If you visualize the input string as a char array: ``` int foo[] = {4, 8, 15, 16, 23, 42}; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 00000000001111111111222222222233333 01234567890123456789012345678901234 ``` with the `int` `4` being located at index 13, `8` at index 16, and so on, this is what the result of each run in the loop looks like: ``` Run 1) String: "int foo[] = {4, 8, 15, 16, 23, 42};" Starting string pointer: str[ 0 ] Num chars consumed until after found digit: 14 Digit that was found: 4 Ending string pointer: str[ 14 ] Run 2) String: ", 8, 15, 16, 23, 42};" Starting string pointer: str[ 14 ] Num chars consumed until after found digit: 3 Digit that was found: 8 Ending string pointer: str[ 17 ] Run 3) String: ", 15, 16, 23, 42};" Starting string pointer: str[ 17 ] Num chars consumed until after found digit: 4 Digit that was found: 15 Ending string pointer: str[ 21 ] Run 4) String: ", 16, 23, 42};" Starting string pointer: str[ 21 ] Num chars consumed until after found digit: 4 Digit that was found: 16 Ending string pointer: str[ 25 ] Run 5) String: ", 23, 42};" Starting string pointer: str[ 25 ] Num chars consumed until after found digit: 4 Digit that was found: 23 Ending string pointer: str[ 29 ] Run 6) String: ", 42};" Starting string pointer: str[ 29 ] Num chars consumed until after found digit: 4 Digit that was found: 42 Ending string pointer: str[ 33 ] ``` [Answer] # V, 37 Bytes ``` 2Eé0òYp6ldf ò$dT]ddÎdwf{xwC; gg"1P ``` V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of [commit 17](https://github.com/DJMcMayhem/V/commit/3e52ff77850f2d7897167eb9a20a859ca0169968). Explanation: This is pretty much a direct translation of [my vim answer](https://codegolf.stackexchange.com/a/77862/31716), albeit significantly shorter. ``` 2E "Move to the end of 2 words forward. é0 "Insert a single '0' ò ò "Recursively do: Yp6ldf "Yank, paste, move 6 right, delete until space. $dT] "Move to the end of line, delete backwards until ']' dd "Delete this line Î "Apply the following to every line: dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';' ``` Then we just have: ``` gg"1P "Move to line 1, and paste buffer '1' behind us. ``` Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump: ``` 00000000: 3245 e930 f259 7001 366c 6466 20f2 2464 2E.0.Yp.6ldf .$d 00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767 T]dd.dwf{xwC;.gg 00000020: 2231 500a "1P. ``` This can be run by installing V and typing: ``` python main.py c_array.v --f=file_with_original_text.txt ``` [Answer] # C, ~~195~~ 180 bytes 195-byte original: golfed: ``` char*a,*b,*c,*d;j;main(i){scanf("%ms %m[^]]%m[^;]",&a,&b,&c); for(d=c;*d++;i+=*d==44);printf("%s %s%d];\n",a,b,i); for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))printf("%s%d] = %s;\n",b,j,d);} ``` ungolfed: ``` char*a,*b,*c,*d; j; main(i){ scanf("%ms %m[^]]%m[^;]",&a,&b,&c); // m-modifier does its own mallocs for(d=c;*d++;i+=*d==44); // count commas printf("%s %s%d];\n",a,b,i); // first line for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}")) printf("%s%d] = %s;\n",b,j,d); // each array value } ``` The two shortcuts are using the `m` modifier to to get scanf's `%s` to allocate its own memory (saves declaring char arrays), and using `strtok` (which is also available by default, without includes) to do the number-parsing part. --- 180-byte update: ``` char*a,*b,*c,e[999];i;main(){scanf("%ms %m[^]]%m[^}]",&a,&b,&c); for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c), c=strtok(0," ,"););printf("%s %s%d];\n%s",a,b,i,e);} ``` ungolfed: ``` char*a,*b,*c,e[999]; i; main(){ scanf("%ms %m[^]]%m[^}]",&a,&b,&c); for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),c=strtok(0," ,");); printf("%s %s%d];\n%s",a,b,i,e); } ``` Uses [bnf679's](https://codegolf.stackexchange.com/a/77983/41288) idea of appending to a string to avoid having to count commas. [Answer] ## Python 3.6 (pre-release), 133 ``` m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ') l=len(i);p(t,n+f'[{l}];') for x in range(l):p(n+f'[{x}] = {i[x]};') ``` Makes heavy use of [f-strings](https://www.python.org/dev/peps/pep-0498/). Ungolfed version: ``` y, u = input().split('[') t, n = y.split() i = u[5:-2].split(', ') l = len(i) print(t, n + f'[{l}];') for x in range(l): print(n + f'[{x}] = {i[x]};') ``` [Answer] # Ruby, ~~127~~ ~~110~~ ~~108~~ ~~99~~ 88 bytes ~~Anonymous function with a single argument as input.~~ Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) ~~Returns~~ Prints the output string. Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. ~~Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on `]` and splicing the second half to get the numbers helped.~~ I need to use the splat operator more. It's so useful! Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using `gsub` and `split`.. ``` t,n,*l=gets.scan /-?\w+/;i=-1 puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"} ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~52~~ ~~50~~ 47 bytes Code: ``` … = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J, ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCmID0gwqFgwqbCqMKow7AtJyzCocKpZ3LCqHPCq-KAnl07wqsswq52wrnDsMKhwqbCrHNcwqhOIl0gPSAieSc7Siw&input=aW50IGZvb1tdID0gezQsIDgsIDE1LCAxNiwgMjMsIDQyfTs). [Answer] ## JavaScript (ES6), 100 bytes ``` (s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>` ${n}[${i}] = ${v};`).join`` ``` Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use `replace` but that turned out to be a red herring.) [Answer] # Pyth - ~~53~~ ~~50~~ ~~46~~ ~~45~~ 44 bytes *2 bytes saved thanks to @FryAmTheEggman.* ``` +Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K ``` [Test Suite](http://pyth.herokuapp.com/?code=%2BJhcz%5C%5B%2B%60%5DlKcPecz%5C%7Bd%5C%3Bj.es%5BecJd%60%5Dkd%5C%3DdPb%5C%3B%29K&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0). [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~48~~ 47 bytes ``` qR`(\S+)(. = ).(.+)}`{[b#Yd^k']';.n.b.,#y.c.y]} ``` Takes input from stdin and prints to stdout. ### Explanation **Tl;dr:** Does a regex replacement, using capture groups and a callback function to construct the result. The `q` special variable reads a line of input. The regex is `(\S+)(. = ).(.+)}`, which matches everything except the type (including trailing space) and the final semicolon. Using the first example from the question, the capturing groups get `foo[`, `] =` , and `4, 8, 15, 16, 23, 42`. The replacement is the return value of the unnamed function `{[b#Yd^k']';.n.b.,#y.c.y]}`, which is called with the whole match plus the capturing groups as arguments. Thus, within the function, `b` gets capture group 1, `c` gets group 2, and `d` gets group 3. We construct a list, the first three items of which will be `"foo["`, `6`, and `"]"`. To get the `6`, we split `d` on the built-in variable `k` = `", "`, `Y`ank the resulting list of integers into the `y` variable for future use, and take the length (`#`). `']` is a character literal. What remains is to construct a series of strings of the form `";\nfoo[i] = x"`. To do so, we concatenate the following: `';`, `n` (a built-in for newline), `b` (1st capture group), `,#y` (equivalent to Python `range(len(y))`), `c` (2nd capture group), and `y`. Concatenation works itemwise on lists and ranges, so the result is a list of strings. Putting it all together, the return value of the function will be a list such as this: ``` ["foo[" 6 "]" [";" n "foo[" 0 "] = " 4] [";" n "foo[" 1 "] = " 8] [";" n "foo[" 2 "] = " 15] [";" n "foo[" 3 "] = " 16] [";" n "foo[" 4 "] = " 23] [";" n "foo[" 5 "] = " 42] ] ``` Since this list is being used in a string `R`eplacement, it is implicitly cast to a string. The default list-to-string conversion in Pip is concatenating all the elements: ``` "foo[6]; foo[0] = 4; foo[1] = 5; foo[2] = 15; foo[3] = 16; foo[4] = 23; foo[5] = 42" ``` Finally, the result (including the type and the final semicolon, which weren't matched by the regex and thus remain unchanged) is auto-printed. [Answer] ## Perl 5.10, 73 72 68 66 + 1 (for -n switch) = 67 bytes ``` perl -nE '($t,$n,@a)=/[-[\w]+/g;say"$t $n".@a."];";say$n,$i++,"] = $_;"for@a' ``` This is a nice challenge for Perl and the shortest among general-purpose languages so far. Equivalent to ``` ($t, $n, @a) = /[-[\w]+/g; say "$t $n" . @a . "];"; say $n, $i++, "] = $_;" for @a; ``` [Answer] ## PowerShell v2+, ~~114~~ 105 bytes ``` $a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"} ``` Takes input string `$args` and `-replace`s the square bracket with nothing, then performs a `-split` on whitespace. We store the first bit into `$a`, the second bit into `$b`, the `=` into `$c`, and the array elements into `$d`. For the example below, this stores `foo` into `$a` and `bar` into `$b`, and all of the array into `$d`. We then output our first line with `"$a ..."` and in the middle transform `$d` from a an array of strings of form `{1,`,`2,`,...`100};` to a regular int array by `-join`ing it together into one string, then running it through `iex` twice (similar to `eval`). We store that resultant array back in `$d` before calling the `.length` method to populate the appropriate number in between the `[]` in the output line. We then send `$d` through a loop with `|%{...}`. Each iteration we output `"$b..."` with a counter variable `$i` encapsulated in brackets and the current value `$_`. The `$i` variable starts uninitialized (equivalent to `$null`) but the `++` will cast it to an `int` before the output, so it will start output at `0`, all before incrementing `$i` for the next loop iteration. All output lines are left on the pipeline, and output to the terminal is implicit at program termination. ### Example ``` PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};" foo bar[5]; bar[0] = 1; bar[1] = 2; bar[2] = 3; bar[3] = -99; bar[4] = 100; ``` [Answer] ## C,~~278~~ 280 bytes golfed: ``` x,e,l,d;char *m,*r,*a;char i[999];c(x){return isdigit(x)||x==45;}main(){gets(i);m=r=&i;while(*r++!=32);a=r;while(*++r!=93);l=r-a;d=r-m;for(;*r++;*r==44?e++:1);printf("%.*s%d];\n",d,m,e+1);r=&i;while(*r++){if(c(*r)){m=r;while(c(*++r));printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);}}} ``` ungolfed: ``` /* global ints * x = generic counter * e = number of elements * l = length of the array type * d = array defination upto the first '[' */ x,e,l,d; /* global pointers * m = memory pointer * r = memory reference / index * a = pointer to the start of the array type string */ char *m,*r,*a; /* data storage for stdin */ char i[999]; c(x){return isdigit(x)||x=='-';} main(){ gets(i); m=r=&i; while(*r++!=32); // skip first space a=r; while(*++r!=93); // skip to ']' l=r-a; d=r-m; for(;*r++;*r==44?e++:1); // count elements printf("%.*s%d];\n",d,m,e+1); // print array define r=&i; while(*r++) { // print elements if(c(*r)) { // is char a - or a digit? m=r; while(c(*++r)); // count -/digit chars printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m); } } } ``` While working on this someones posted a shorter version using sscanf for the parsing rather than using data pointers... nice one! UPDATE: Spotted missing spaces around the equals in the element printing, IDE online link: <http://ideone.com/KrgRt0> . Note this implementation does support negative numbers... [Answer] # Awk, 101 bytes ``` {FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i} ``` More readably: ``` { FS="[^[:alnum:]_-]+" printf "%s %s[%d];\n", $1, $2, NF - 3 for (i=3; i < NF; i++) printf $2"[%d] = %d;\n", i-3, $i } ``` * I set the field separator to everything except alphabets, digits, the underscore and `-`. So, the fields would be the type name, the variable name, and the numbers. * The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing `};`). So, the size of the array is `NF - 3`. * Then it's just printing a special line for the declaration, and looping over the numbers. * I *should* assign `FS` either when invoking awk (using `-F`) or in a `BEGIN` block. In the interests of brevity, …. [Answer] # JavaScript ES6, ~~134~~ ~~132~~ ~~130~~ 129 bytes Saved 1 byte thanks to Neil. ``` x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}]; `+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join` `) ``` [Answer] ## bash, ~~133~~ 129 bytes ``` read -a l d="${l[@]:0:2}" e=("${l[@]:3}") echo "${d%?}${#e[@]}];" for i in "${!e[@]}" { echo "${l[0]}[$i] = ${e[$i]//[!0-9]/};" } ``` First attempt, sure its posible to get it shorter. [Answer] # D, 197, 188 bytes ``` import std.array,std.stdio;void main(){string t,n,e;readf("%s %s] = {%s}",&t,&n,&e);auto v=e.replace(",","").split;writeln(t,' ',n,v.length,"];");foreach(i,c;v)writeln(n,i,"] = ",c,";");} ``` or ungolfed: ``` import std.array, std.stdio; void main() { string type, nameAndBracket, elems; readf("%s %s] = {%s}", &type, &nameAndBracket, &elems); // remove all commas before splitting the string into substrings auto vector = elems.replace(",","").split(); // writeln is shorter than fln by 1 char when filled in writeln(type, ' ', nameAndBracket, vector.length, "];"); // print each element being assigned foreach(index, content; vector) writeln(nameAndBraket, index, "] = ", content, ";"); } ``` [Answer] # Julia, ~~154~~ ~~134~~ 101 bytes ``` f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n]; "join([c[2]"[$i] = "c[i+3]"; "for i=0:n-1]) ``` This is a function that accepts a string and returns a string with a single trailing newline. Ungolfed: ``` function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2) c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1]) end ``` We define `c` to be an array of matches of the input on the regular expression `-?\w+`. It caputres the type, array name, then each value. We store `n` as the length of `c` - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, `c[]` is the same as `c[1]`. Saved 32 bytes with help from Dennis! [Answer] ## Python 2, 159 bytes ``` s=input().split() t,n,v=s[0],s[1][:-2],''.join(s[3:]) a=v[1:-2].split(',') print'%s %s[%d];'%(t,n,len(a)) for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i]) ``` [Try it online](http://ideone.com/fork/mm2tbz) Thanks Kevin Lau for some golfing suggestions [Answer] ## Python 3, 116 bytes ``` t,v,_,*l=input().split();v=v[:-1]+'%s]' print(t,v%len(l)+';');i=0 for x in l:print(v%i,'= %s;'%x.strip('{,};'));i+=1 ``` Splits the input into the type, name, and the list of numbers. After printing the array declaring, prints the elements by manually enumerating through the numbers, removing excess punctuation that attached to the first and last one. A different approach in Python 2 came out to 122 bytes: ``` a,b=input()[:-2].split('] = {') l=eval(b+',') print a+`len(l)`+"];" for y in enumerate(l):print a.split()[1]+'%s] = %s;'%y ``` The idea is to `eval` the list of numbers as a tuple, with a comma at the end so that a single number is recognized as a type. The enumerated list of numbers provides tuples to string-format in. [Answer] ## PHP, 143 bytes **Golfed** ``` <?$t=count($n=explode(' ',preg_replace('/[^\s\w]/','',$argv[1])))-3;echo"$n[0] {$n[1]}[$t];";for($i=2;$t>$j=++$i-3;)echo$n[1]."[$j] = $n[$i];"; ``` **Ungolfed** ``` <? $t = count( // Get the number of elements for our array... $n = explode(' ', // After split the input on whitespace... preg_replace('/[^\s\w]/','',$argv[1])))-3; // After removing all special characters. echo "$n[0] {$n[1]}[$t];"; // First line is type, name, and count. for($i=2; // Loop through array elements $t > $j = ++$i-3;) // Assign j to be the actual index for our new array echo $n[1]."[$j] = $n[$i];"; // Print each line ``` Input is taken through command line argument. Sample: ``` C:\(filepath)>php Expand.php "int foo[] = {4,8,15,16,23,42};" ``` Output: ``` int foo[6];foo[0] = 4;foo[1] = 8;foo[2] = 15;foo[3] = 16;foo[4] = 23;foo[5] = 42; ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~68~~ ~~64~~ 58 bytes ``` '\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h ``` This isn't C, ~~but it does use C-like `sprintf` function~~ Nah, that was wasting 4 bytes. [**Try it online!**](http://matl.tryitonline.net/#code=J1x3KydYWDI6SCMpWEt4WElaYydbJ0tuViddOyd2IUsiSTJYKSdbJ1hAcVYnXSA9ICdAZyc7JzYkaA&input=J2ludCBmb29bXSA9IHs0LCA4LCAxNSwgMTYsIDIzLCA0Mn07Jw) ``` % Take input implicitly '\w+'XX % Find substrings that match regex '\w+'. Gives a cell array 2:H#) % Split into a subarray with the first two substrings (type and name), and % another with the rest (numbers that form the array) XKx % Copy the latter (numbers) into clipboard K. Delete it XI % Copy the former (type and name) into clipboard I Zc % Join the first two substrings with a space '[' % Push this string K % Paste array of numbers nV % Get its length. Convert to string '];' % Push this string v! % Concatenate all strings up to now. Gives first line of the output K" % For each number in the array I2X) % Get name of array as a string '[' % Push this string X@qV % Current iteration index, starting at 0, as a string '] = ' % Push this string @g % Current number of the array, as a string ';' % Push this string 5$h % Concatenate top 6 strings. This is a line of the output % Implicity end for each % Implicitly display ``` [Answer] ## Clojure, 115 bytes ``` #(let[[t n & v](re-seq #"-?\w+"%)](apply str t" "n\[(count v)"];\n"(map(fn[i v](str n"["i"] = "v";\n"))(range)v)))) ``` I wasn't able to nicely merge `awful_array_name[5];` and `awful_array_name[0] = 7;` parts so that they'd re-use code :/ ]
[Question] [ # Challenge Your task is to write a piece of code that outputs another piece of code. That code must in turn output yet another code until the final code outputs the integer **1**. The chain ends the first time **1** is outputted. **None of your programs may share any characters** (there's one exception in the Rules-section). The winning submission will be the submission with the longest chain. The tie-breaker will be shortest total code-length. --- ### Rules: * You may use both functions, programs and snippets. You may assume a REPL environment. * All functions must be written in the same language * Symbol independent languages are disallowed. This includes partially symbol independent languages such as Headsecks. * Default output formatting may optionally be disregarded in a function's output. This includes trailing newlines, `ans =` etc. * You may reuse the space character (ASCII code point 32), but note the following: + You may use as many space characters as you like in one of the functions, but restrict it to maximum 5 in all other functions + You may not reuse any characters if code point 32 is not space in your language. * None of the programs may take input * The chain must be at least two programs long. --- ### Example: Your initial code is `abc+cab+bac`. This outputs: `foofoo*123`, which in turn outputs `disp(~0)`, which outputs `1`. This is a chain of 3 programs, with a combined length of 29 (tie breaker). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5-chain: 236 + 29 + 13 + 3 + 1 = 282 bytes ``` 10101100011010001101100010110110001111000111001110101001000000000010111100100110011011010110011000100110101001001101100001110001111010100100000100010010001010011101011001110001000001011010101111001110011110001010111100001110110C₁<Au¦н.V ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0AAIDQ0MQASMAtMIliGMghBgdSARKDCEqgBLwwwwhLFh4jBdMFMNDBGGI5kI0wAxF26hIVw93EoDQ4TNUAKmC8qEaDY0cH7U1GjjWHpo2YW9emH//wMA "05AB1E – Try It Online") which prints the program ``` 633693S<J6bαð3<žQTÌ>è9663тαhJ ``` [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//zYzMzY5M1M8SjZizrHDsDM8xb5RVMOMPsOoOTY2M9GCzrFoSv// "05AB1E – Try It Online") which prints the program ``` 522472 2-255B ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f1MjIxNxIwUjXyNTU6f9/AA "05AB1E – Try It Online") which prints the program ``` 88ç ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fwuLw8v//AQ "05AB1E – Try It Online") which prints the program ``` X ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/4v9/AA "05AB1E – Try It Online") which prints `1` [Answer] # Java 8, chain of 2 functions, ~~90+10~~ ~~37+4~~ 28+4 = 32 bytes ``` o\u002D\u003E"\44\55\76"+2/2 ``` Which is equivalent to: ``` o->"$->"+2/2 ``` -57 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##LY1BD4IwDIXv/IqG04gRCYIeiDc9ysXEi/NQB5rhGIR1JMbw2@eIJH1N2r7Xr8ER1031dkKhMXBGqb8BgNRUD08UNZTzCHChQeoXCHbtZAVjVPjt5OXLEJIUUIKGA7iO2yRJj3PfnkKeZTzP@X4XrtJN6orA@3v7UN6/xMb5X@ux7I@43QGjhfkxVLdxZynu/YmYjgXTVqlowU/uBw) Which returns the String: ``` $->1 ``` [Try it online.](https://tio.run/##LY2xDsIwDET3foUHhmRoJOYK/oAulVgqBpMGlJK6VeNGQqjfHlyodB7unXzXY8Ky717ZBowRLujpUwB4Yjc/0DqoN/sDYNV19B0kXQla5USRkb2FGghOkA/l@ZirQvi03IPwPU7b3yDdquHZ07O9Aep/cfOO7AYzLmwmiViRsYqWEPQ@s@Yv) Which returns the integer: ``` 1 ``` [Answer] # [R](https://www.r-project.org/), 3-chain 198 + 44 + 3 bytes ``` `+`=`\143\141\164`;+"\143\141\164\050\151\156\164\124\157\125\164\146\070\050\143\050\070\070\055\071\055\071\054\071\071\071\055\070\070\071\055\070\055\070\054\070\070\055\071\055\071\051\051\051" ``` [Try it online!](https://tio.run/##fYyxDcAwCAR3cesGEsBFlE0omCH7S4SAbLlK8TruBTzu1u02RTojqChkV2@7KzAocsws6XhEeAS5nERhQO3F3cf07DiIG6k4k/3c33yRfn6tNPcX "R – Try It Online") Returns : ``` cat(intToUtf8(c(88-9-9,999-889-8-8,88-9-9))) ``` [Try it online!](https://tio.run/##K/r/PzmxRCMzryQkP7QkzUIjWcPCQtdS11LH0tJS18ICiHUtdCBCmpqa//8DAA "R – Try It Online") Returns : ``` F^F ``` [Try it online!](https://tio.run/##K/r/3y3O7f9/AA "R – Try It Online") Returns `1` **Explanation :** The first program is almost totally written in octal representation, where each character is written as `\xxx` where `xxx` is the ASCII code in octal mode. In human readable form would be : ``` `+`=`cat`;+"cat(intToUtf8(c(88-9-9,999-889-8-8,88-9-9)))" ``` Here, to avoid the use of round brackets we redefine the prefix operator `+` equal to `cat` function, then we use that to print the next string. Even after assigning `cat` to `+`, the latter still keeps its prefix operator "status" and will just take whatever follows it as its first parameter. The second program, simply prints the characters `F^F` obtaining them from decimal ASCII : `70,94,70` Since in the first program we used the octal representation, only numbers `8` and `9` are free to be used; hence, we obtain `70` and `94` with some differences between numbers with only `8's` and `9's`. Finally, the last program, `F^F`, exploits the `^` function (power of) which coerces `FALSE` to `0` and computes `0^0` returning `1` Credits to : * @ngm for the first 2-chain idea * @Giuseppe for the hint to use octals in functions * @BLT and @JayCe for the idea to override `+` in order to avoid brackets --- Previous version : # [R](https://www.r-project.org/), 2-chain ~~27+3~~ 24 + 2 bytes ``` cat(intToUtf8(c(49,76))) ``` [Try it online!](https://tio.run/##K/r/PzmxRCMzryQkP7QkzUIjWcPEUsfcTFNT8/9/AA "R – Try It Online") Returns: ``` 1L ``` [Try it online!](https://tio.run/##K/r/39Dn/38A "R – Try It Online") Returns `1`. [Answer] # [Python 2](https://docs.python.org/2/), 2-Chain, 7+44 = 51 bytes ``` lambda:("7072696e74203"+`3-2`).decode("hex") ``` and ``` print 1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNykl0UpDydzA3MjM0izV3MTIwFhJO8FY1yhBUy8lNTk/JVVDKSO1QkmTq6AoM69EwfA/hE7T0PwPAA "Python 2 – Try It Online") The base 16 code translates to `print 1`, which is returned by the anonymous function. [Answer] # Perl 5, 3-chain, ~~151~~ 139 chars (114 + 20 + 5) ``` &{"CORE::SYSWRITe"|"CORE::39372!4"}(STDOUT,"\x70\x72\x69\x6E\x74\47\x50\x42\x5A\3\22\47\x5E\47\43\43\43\43\43\47") ``` The ugliness inside the `&{ }` evaluates to `CORE::syswrite`, and so the hex-escaped string is printed to standard output as: ``` print'PBZ^C^R'^'#####' ``` Please note that the *^C* and *^R* in the above represent literal control characters. (And not to be confused with the literal `^` caret that occurs between the two strings.) This program in turn outputs: ``` say 1 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 3 programs, Length 42 bytes ``` char("``;8%79b/7%,,b"-5) ``` Outputs: `[[63 24]*2 '']`. [Try it online!](https://tio.run/##y08uSSxL/f8/OSOxSEMpIcHaQtXcMknfXFVHJ0lJ11Tz/38A "Octave – Try It Online") ``` [[63 24]*2 ''] ``` Outputs: `~0`. [Try it online!](https://tio.run/##y08uSSxL/f8/OtrMWMHIJFbLSEFdPfb/fwA "Octave – Try It Online") ``` ~0 ``` Outputs: `1`. [Try it online!](https://tio.run/##y08uSSxL/f@/zuD/fwA "Octave – Try It Online") [Answer] # Cjam, 4-chain, 28+20+3+1=52 bytes ### Snippet 1: ``` "tugshrm\x18$\x18vj\x1b\x07um~l$\x1b"{71^}% ``` ### Snippet 2: ``` 32 4/5*_c_1-\@2*9+c\ ``` ### Snippet 3: ``` 'Y( ``` ### Snippet 4: ``` X ``` Which then prints 1. [Try it online!](https://tio.run/#cjam) ***Note:*** 1. Since Cjam *does not* have interpretation for escape characters, the ones in snippet 1 are only there for better web view. You need to use the corresponding actual characters to run the snippet. 2. If I cannot shave off more characters, then good job to @Emigna for the `05AB1E` answer! [Answer] # Excel, Chain 2, 27+3 bytes ``` =CHAR(45)&CHAR(45)&CHAR(49) ``` Not sure if this is OK... [Answer] # x86 bytecode, Chain 2, 10+4 bytes (Assembled with FASM, format PE) `ÇA.Ï?¿<÷Y.` produces `1À@Ã` in the address next to it and executes it, which returns `1` in eax (as per fastcall). In both cases the `.` actually represents `A` or LF. In hex: `C7 41 0A CF 3F BF 3C F7 59 0A` and `31 C0 40 C3`. Disassembled: ``` mov dword ptr ds:[ecx+A],3CBF3FCF neg dword ptr ds:[ecx+A] ``` produces ``` xor eax,eax inc eax ret ``` This (ab?)uses the fact that the entrypoint of the program is stored in ecx, and then writes the inverse of the to be executed code to the address 10 bytes over and negates it. May or may not break if assembled with anything but fasm, to anything but a PE or with a different entrypoint. [Answer] # JavaScript REPL, lots of bytes, 4 iterate ``` (+!![]+[!![]+!![]+!![]+!![]]+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]))[(![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()([][[]]))[+!![]+[+[]]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[+[]]](![])[(+(!![]+!![]+[+[]]+(+!![])+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]][([][[]]+[])[+!![]]+(![]+[])[+!![]]+([]+(+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(!![]+[])[!![]+!![]+!![]]]](!![]+!![]+!![]+[+[]])](([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+[]+[![]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+!![]]+(+[![]]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[+!![]+[+!![]]]+(!![]+[])[+[]]][([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([][[]]+[])[!![]+!![]]]([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+[+[]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]])()(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+!![]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(![]+[![]])[+!![]+[+[]]]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![]+!![])+(!![]+!![])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+[]]+(!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+([][[]]+[])[!![]+!![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])))[([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]]([]) "\x60\44\x7b\55\x7e\x7b\x7d\x7d\44\x7b\55\x7e\x7b\x7d\x7d\x60\56\x73\x70\x6c\x69\x74\x60\x60\56\x74\x6f\x53\x74\x72\x69\x6e\x67\x60\x60" `${-~{}}${-~{}}`.split``.toString`` 1,1 1 ``` Too lazy to optimize the JSFUCK code # JavaScript REPL, 164 bytes, 3 iterate may be able to expand ``` [g=222222222222222222,e=2e40,f=2e23,f,2e40,n=2222e49,r=2e24,2e30,e,n,r,8e28,2e40,n,r,9e29,g].map(S=>String.fromCharCode(Math.log(S))).join([]) '\55\x7E\x7B\x7D' -~{} 1 ``` [Try it online!](https://tio.run/##ZU6xDoIwFNz5Edrk0WCBKAMOoqMTIzA0@CgQaEkhxsTor9dK3Lzc5XKXG24Qd7E0pp/XQOkb2karRY/IRi1JaUuZ8T8AZhzjEFpnPIIWtqS2JcYpmG8fuzYKAUGBgQPyw2/lUoo8BVmzScykyI7FanolWWv0lHfC5O4FuYq12y4UlFI26F6Rsqbg@VWSVI/9xenkdPbBC97PF3g7R1tT@wE "JavaScript (Node.js) – Try It Online") [Answer] # CJam, 7-chain, 92365+1819+79+14+9+3+1 bytes [This 92365-byte program](https://tio.run/##7dhBjsIwEETRPRdBHAtlh8T9l@YGUYRsx65@c4Ayk/T/Xc7xeX9bez5eff@6Bw4LvhA46p85y7185j8/btjbGXNIz2chKyOrzsOgXMqlXFmUS9/0Td@rvnPTaTrtGlkehnJB3/RdyTU4xKEahWlMY9rVSJarEeVSbphyTafpVAhkKQTKBX3T92yafVfBIQ7VKFleuEpmFVgFKhkOcZjOoek0nS4MslwYlHz6pm8lH4c4VKMcimlMY1qWqxHlUi7lmk7TqRDIUgiUC/qm7/k0@66CQxyqUbK8cJXMKrAKVDIc4jCdQ9NpOl0YZLkwuDBYBVaBVSDLKqBv@qbvyTSHuAaHOFSjZKlRahR90/eq79x0mk67RpaHoVzQN337RoNDHKpRstQolcwqsApUMhziEIem03S6MMhyYVDy6Zu@lXwc4lCNciimMY1pWa5GlEu5lGs6TadCIEshUC7om75v0bfvKjjEYVaNwjSmMe1qJMsLp1zKTVGu6TSdCoEshUC5oG/69rkE05jGtA0ty8Ogb/qmb1naJB3R0drv3HSaTstSlodBuZRLubIol77pm77d50yn6bRrlAtZiopVYBWguZy@6YiO3JtMp@m0lGR5GJRLuZQri3Lpm77pe2uaQw7FNKYxLYuO6IiOVAxMY7oU06bTdNo4smpue1lWgVVgFciyCuibvuk7RN8hh2Ia05jGNKYx7ZrlUIfKsq6sK@uKtxzqUFmyZMlS/BQ/xc9KdygTMiETYhrTmMa0LA508@RmbuYHHOJQR5JFbWoUfdN3LX2rZJjGNKYxjWlMYxrTmMY0VKEKVajCC17wkuU2UOoNcDM3b@1mUnKoQ2XJkiVLIVVIFVIfCzbKau0H) prints ``` YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mR1+11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+11+11+11+11+11+1+1+1+1+YaY+`$1<mR11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+YaY+`$1<mR1+1+11+11+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+11+11+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+11+YaY+`$1<mR1+11+YaY+`$1<mR1+1+1+1+1+11+11+1+1+YaY+`$1<mR11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+YaY+`$1<mR1+1+1+1+1+ ``` which prints ``` 34 4673 4656 4673 4656 5464 4656 4673 4673 4740 34 50 34707 5477]{N7=64777-,=}% ``` which prints ``` ";*;*Q*;;~"2f^ ``` which prints ``` 9(9(S(99| ``` which prints ``` 88c ``` which prints ``` X ``` which prints `1`. [Answer] # [MATL](https://github.com/lmendo/MATL), 5 programs, 404+159+35+4+1 = 603 bytes Getting to 4 programs was hard. 5 programs was *very hard!* ``` '/'37 13+3+3+'3`/'37 13+3+3+77 13+37 13+3+3+'3`/'37 13+3+3+'3tttttttt`/'37 13+3+3+'3#'37 13+3+3+'3ttttt`'37 13+3+3+'3ttttt'37 13+3+3+77 13+'/'37 13+3+3+'3`<<tttttttttt'37 13+3+3+'3#'37 13+3+3+77 13+37 13+3+3+'3///<3////t````ttttt```<</////t`````t<3tttttttttt<3tt/'37 13+3+3+'3ttttttttt'37 13+3+3+'3`{'37 13+3+3+77 13+'y$'37 13+3+3+'3/////t`````ttI#I'77 13+3+'dk'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh3_+''h ``` [Try it online!](https://tio.run/##y00syfn/X11f3dhcwdBYGwTVjROQueYQFi5pdeMSKEATVsZUlIAphGERulNsbErgAKf5mG7U19e3ARH6JQlAALE9AWiYPlwsocTGGGE0iI3dW6i2JlRjurhSRR3NargVJZ7KnupQ12mrp2SrZxABjOO11dUz/v8HAA "MATL – Try It Online") ``` ,50],5W50],50qqqqqqqq],50 50qqqqq]50qqqqq5W,50]99qqqqqqqqqq50 5W50,,,90,,,,q]]]]qqqqq]]]99,,,,,q]]]]]q90qqqqqqqqqq90qq,50qqqqqqqqq50]x5Wv!50,,,,,q]]]]]qqF FZah ``` [Try it online!](https://tio.run/##y00syfn/X8fUIFbHNBxMGhRCAYitAOXGQmnTcJBSS8tCOACpAWrU0dGxBBE6hbFAANETC1SoAxeLLbQ0QGgDsZHsAhoTW2EaXqYINgmuo9BNwS0qMeP/fwA "MATL – Try It Online") This might be my favorite program I've written on PPCG: ``` 22 2 2**2-2-- 22Y2 2EEEEEEEEBPX)2) ``` [Try it online!](https://tio.run/##y00syfn/38hIAQi1tIx0jXR1FYyMIoE8VyhwCojQNNJU@P8fAA "MATL – Try It Online") ``` 84 c ``` [Try it online!](https://tio.run/##y00syfn/38KEK/n/fwA "MATL – Try It Online") ``` T ``` [Try it online!](https://tio.run/##y00syfn/P@T/fwA "MATL – Try It Online") ### Explanation: Having used hours on this program, I won't write the entire explanation now! I'll write it later! Short summary: ``` T -> Literal true = 1 ``` --- ``` 84c -> Convert 84 to its ASCII-character T ``` --- ``` 22 2 2**... -> Calculate 84 using only 2, * and - 22Y2 -> 22Y2 is a cell array with the name of all the months 2EE..B -> Is 512 in binary [1 0 0 ...] P -> Flips is, [0 0 ... 1] X) -> Uses the binary vector as index and gets the 10th element -> 'October' 2) -> The second character, 'c' -> Resulting in the stack: 84, 'c' that's implicitly printed ``` --- ``` ,50]... -> A string with ASCII character codes of '22 2... -> There's a lot of ,xyz], which means "do twice" and q which is decrement ``` In order to convert this to a string instead of character codes, we need to concatenate it with a string using `h`. To get a string, without using quotes, or the XY modifiers, we do base conversion and convert an integer to whitespace. --- ``` '/'37 13 ... -> Concatenation of strings and character codes using only available numbers 3_+ -> Subtract 3 from all character codes to get the correct ones ''h -> And concatenate with the empty string. ``` [Answer] # CJam, 10 programs, 5,751,122,990 bytes I was too lazy to golf it... But apparently I don't need to golf it to be competitive. But without golfing it is a bit difficult to post the solution in an answer. It should work in [the JavaScript interpreter](http://cjam.aditsu.net/) in theory, but the program is too long to be tested in a browser. It should output the same in the Java interpreter except for the last program. But it may also run out of memory in the Java interpreter for the first few programs. ### Statistics ``` 5683631402 bytes, used )\_l 65027874 bytes, used %&<>WXehrstu{|} and newline 2247044 bytes, used +DEFHIS~ 199997 bytes, used ,38=[]` 15352 bytes, used -25:N and space 1181 bytes, used 67c 84 bytes, used #'(@CKMTgkp 21 bytes, used !"$?BJLQR^fijo 16 bytes, used */4AGYZabdy 19 bytes, used .09 1 byte, used 1 ``` ### First bytes ``` l)__)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))... \n{s}sX>X<eu{h}sX>X<eu{\n}sX>X<{{XXXXXXX}seeseeseeW>{X<{|}%}%}%{|}sX>X<{{X}se... SH+~+E+E+E+SH+~+H+E~+SH+~+H+E~+SI+~+H+D+D+SI+~+I+E+E+SH+~+H+E~+SF+~+E+SD+~+D+... [33]`3=,3333=[33]`3=,388333=[8]`88=,8333=[8]`88=,8333=[8]`88=,8338=[8]`88=,33... N:--25--22- 2-N:--25--22- 2-N:--22--22-N:--25--22- 2-N:--25--22- 2-N:--22--22... 776776777767c677676676677667c66677666676776c776776777767c7667776c666776666767... '#('@('T(('k(('T((('k(('K('p(''((('@('T(('k(('T((('k(('k('M('#(('#('C('g('g((... "?RiQiJo$?RiQijL!"Bf^ 4YbZbAd/4YbZbaG* 0.99999999999999999 1 ``` `\n` is newline in the second program. ### Generator ``` "'#('@('T(('k(('T((('k(('K('p(''((('@('T(('k(('T((('k(('k('M('#(('#('C('g('g(((((((((" {_[i1:X;{_1&6+ \1$X*X5*:X;- 2/}16*;]__,,:)\f<Wf%10fb:c@#)<W%'c}%s "67c" "N:--22--22- N:--25--22- 2- N:--55--25--5--2--2-"N/ers "N:-25 " "[33]`3=,3333= [33]`3=,388333= [8]`88=,8333= [8]`88=,8338= [8]`88=,333= [8]`88=,88="N/ers "[]`38=," "SH+~+E+E+E+ SI+~+H+D+D+ SI+~+I+E+E+ SH+~+H+E~+ SI+~+I+D~+H+E~+ SF+~+E+ SD+~+D+D~+"N/ers "SDEFHI+~" "{s}sX>X<eu {t}sX>X<{{XXXXXXXX}s{X}s{XXXXXX}erseeW>{X<{&}%}%}% {ee}sX>X<eu {&}sX>X<{{XXXXXXs}s{X}s{XXXXXX}erseeW>{X<{|}%eu}%}% {h}sX>X<eu {h}sX>X<eu{X|}% {N}sX>X<{{XXXXXXX}seeseeseeW>{X<{|}%}%}% {|}sX>X<{{X}seeW>{X<{|}%}%}%"N/'Nf/Nf*erN\+s 1>"l)_"o)\{'_oi10-')*o'\o}/i10-')*o ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 2 chain, 15+2 = 17 bytes ``` ⎕AV[2+⎕AV⍳'⍳.'] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVMewaCNtMP2od7M6EOupx@KUAAA "APL (Dyalog Unicode) – Try It Online") Outputs the program ``` *0 ``` That outputs ``` 1 ``` [Answer] # JavaScript (ES6), 2 functions, 31+4 = 35 bytes ``` function(){return atob`Xz0+MQ`} ``` returns `_=>1`, which returns `1` ``` f0 = function(){return atob`Xz0+MQ`} res0 = f0() console.log('Output of 1st function:', res0) f1 = eval(res0) res1 = f1() console.log('Output of 2nd function:', res1) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~38 37 36~~ 35 bytes, Chain of 4 ``` ØJiⱮ⁾ɱṾ⁽÷ṃ;ṾØJ⁽¡Ṡị ``` **[Try it online!](https://tio.run/##y0rNyan8///wDK/MRxvXPWrcd3Ljw537HjXuPbz94c5mayAbKAXkHlr4cOeCh7u7//8HAA "Jelly – Try It Online")** (**18** bytes) ``` 8220,163,187Ọ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/CyMhAx9DMWMfQwvzh7p7//wE "Jelly – Try It Online")** (**13** bytes) ``` “£» ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDiw/t/v8fAA "Jelly – Try It Online")** (**3** bytes) ``` ! ``` **[Try it online!](https://tio.run/##y0rNyan8/1/x/38A "Jelly – Try It Online")** (**1** byte) **18+13+3+1=35** bytes ### How? ``` ØJiⱮ⁾ɱṾ⁽÷ṃ;ṾØJ⁽¡Ṡị - Main Link: no arguments ⁾ɱṾ - list of charcters -> ['ɱ','Ṿ'] ØJ - yield the characters of Jelly's code-page Ɱ - Ɱap across the two characters applying: i - first index of? -> [163, 187] ⁽÷ṃ - 8220 (a base 250 compressed number) ; - concatenate -> [8220, 163 187] Ṿ - un-eval (get Jelly code) -> "8220,163,187" - (Note: here a full program prints 8220,163,187 as it is the end - of a leading constant chain due to the following constant) ØJ - yield the characters of Jelly's code-page ⁽¡Ṡ - 1206 (a base 250 compressed number) ị - index into (1-indexed & modular, so gets the 182nd item, 'Ọ') - implicit print (making the final output 8220,163,187Ọ) 8220,163,187Ọ - Main link: no arguments 8220,162,187 - list of numbers -> [8220, 162, 187] Ọ - cast ordinals to characters -> ['“','£','»'] - implicit print (flat Jelly lists print as if strings so outputs “£») “£» - Main link: no arguments “ - open string-literal £ - the content of the string-literal » - close it interpreting as a compressed string - this yields ['!'] - implicit print (outputs !) ! - Main link: no arguments ! - factorial (of implicit input 0 - 0! = 1 as it is the empty product) - implicit print (outputs 1) ``` [Answer] # [Python 2](https://docs.python.org/2/), 3 snippets, 68 + 12 + 3 = 83 bytes ``` chr(44*2+4).join([chr(42&54),`45+25`,`42*2+52`,`4*4+55`+chr(42&54)]) ``` which produces the string of octal literals: ``` "\70\136\71" ``` which produces: ``` 8^9 ``` Which finally produces `1`. [Try it online!](https://tio.run/##RY/BasQgEIbveYppDqtuQqCil0BOS1@hl1JQUkMsaQyjbS1tnz2duAv14u/wfb/M9pXmsMo9wwB1Xe/jjFyps2yU6F6DX/lTmciTVqI1SjdSG7olEVoe6awarU3zTz2LnYq6mNBvXFSRiqNLlD5nvzjIcDeAuTd9BXQ29GuCXLKfIMKpwCTzLEQPaH108GiXd/eAGJCzS1inxY@ph@9f1k0B3yzxN48cUboi/Ay3SXkf6x2l7sMuPLfkElhdf2eX2aIdk8PD6FkLjF13jwGTe@GR2P0P "Python 2 – Try It Online") [Answer] # Java 8, 3 programs, 431 bytes ## Program 1, 332 bytes A lambda from one (empty) parameter of any type to `String`. ``` x\u002D\u003E"\151\156\164\40\157\75\70\46\70\52\70\54\156\75\53\53\157\53\70\73\156\145\167\40\123\164\162\151\156\147\50\51\53\50\143\150\141\162\51\50\47\171\47\53\157\51\53\50\143\150\141\162\51\50\47\54\47\53\157\51\53\50\143\150\141\162\51\50\47\75\47\53\157\51\53\156\53\50\143\150\141\162\51\50\47\56\47\53\157\51\53\156\73" ``` This is just a lambda with the arrow characters Unicode-escaped returning the text of the second program encoded with octal escape sequences. [Try It Online](https://tio.run/##lVFBa8MgFD7HXyE9JbCJJiYeuva0DXbYqce5g02TYJYaSUxZGf3t2dN2DMqgDPR9D9/3fU99rTqo@95Wpt19zHbadrrEZafGEb8qbfAXii6Ho1MOoNZGdbgFFZmc7kg9mdLp3pDnS/LwYlzVVMMd3rhBm2aNa7xC86ecKE0ffcyeFpLlDHYhWcElp5AKKXIpqOSFj3kaIg8cKOSZX54FABWRndU8BwcRHNIsmLEi/TXnwAcbFvTA4V7mkQWeL0BHIZlgHn5a3OTDxf5Dhwdc0/31bjUp/lSJbDEjFC3R9WQOvd7hPQwtPn/82ztWQzMmfobR5ji6ak/6yRELRRfXRFnbHWOaJEsUndBp/gY) ## Program 2, 93 bytes Snippet producing a `String`. ``` int o=8&8*8,n=++o+8;new String()+(char)('y'+o)+(char)(','+o)+(char)('='+o)+n+(char)('.'+o)+n; ``` [Try It Online](https://tio.run/##XY5BDoIwEEXX5RRdSWuRdRPCEVyxNC4qVCzClLQFQwxnr0WIRleTN/9n5jViFAfdS2iqu@@HS6tKXLbCWnwUCvAzQtvSOuHCKJxRUOMroSHzChzWOd/xPU8gZ0wznhnpBgMY5GMrE8pIeROGkniKmf5S8kP5m@DD6cqZj9Ac/WuMWlW4C4Zk/XE6Y2Fqu0ghVEzWyS7Vg0v7EDoSbGm2nJn9Cw) (with return added) ## Program 3, 6 bytes A lambda from one (empty) parameter of any type to `int`. ``` z->9/9 ``` [Try It Online](https://tio.run/##XY0xD4IwFIRn@iveCIlWV4Iymjg4MRqHJ7SkWNqGvpKg4bfXmjA53Ze73N2AM@6tE2boXtGFp1YttBq9hxsqAx@WbaYnpCRSGdQwpBYPpDSXwbSkrOGXDU5XQ6IX0w42qEHCmcX3vi4PZWRZxf43Z6s6GNNd3tCkTH9/AE69L37vWbN4EiO3gbhLIeWSo3N6yY9FUbFsZWv8Ag) [Answer] # SmileBASIC, chain 3, 375 bytes ``` k=59599-44444print c("sbanm",k,4,"")+c("sbwav",44-5,2,"")+c("sbwav",594-222,4,"")+c("game5vs",4528-442,2,"")+c("sbanm",k,4,"")+c("sbanm",72,5-4,"")*2+c("sbwav",594-222,4,"")+c(sbwav,854-44,2,"")+c("staffroll",259+2,9,"")+c("ex8techdemo",24455,5-2,"")+key(4)[.]def c(f,s,l,q)for i=.to-5+l+4q=q+load("txt:sys/"+f,.)[s+i]next:return q:end ``` Outputs: ``` CHR$63OUT A$CHR$33OUT B$PRINT A$;B$;L ``` Outputs: ``` ?!0 ``` Outputs: ``` 1 ``` [Answer] # PHP 7.0, 2-chain, 35 + 8 = 43 bytes While writing my initial answer I realized I could just use base64 encode the second echo. It shaved off 11 bytes, so here it is. You can find my original idea below, too. ### Run using php -r: ``` echo base64_decode('RUNITyAxPz4='); ``` This outputs: ``` ECHO 1?> ``` Which then obviously prints: ``` 1 ``` ### Output: [![Code run with additional && echo for readability](https://i.stack.imgur.com/pxnzb.png)](https://i.stack.imgur.com/pxnzb.png) *My code when run in a terminal. The appended **&& echo** is for readability only.* ### Comments: There's not much to it really. Very simple once you know about "?>" implicitly acting as ";". The "tricky" part was to figure out what to encode: * *ECHO 1;* became *RUNITyAx**O**w==*, so we have a collision of uppercase O's. No good. * *echo 1;* became *ZWN**o**byAxOw==*, so now there's two *lower*case o's. Unfortunate! * *ECHO 1?>* became *RUNITyAxPz4=*. It's the same length and none of the characters collide. So that's it! ### Alternatively we can use "echO" and "ECHo", too (36 + 7 = 43 bytes). ``` echO base64_decOde('RUNIbyAxOw==')?> ECHo 1; 1 ``` We can also switch the ; and ?> around using that. It works equally well and it all scores the same in length. --- --- ## My initial solution: # PHP 7.0, 2-chain, 44 + 10 = 54 bytes This is the best I could come up with at first. I understood that "unique characters" meant "echo" is not equal to "ECHO". Hope I got that right! ### Run using php -r: ``` echo strtoupper(urldecode('echo true%3b'))?> ``` This outputs: ``` ECHO TRUE; ``` Which in turn gives us our number: ``` 1 ``` ### Output: [![Code run with additional && echo for readability](https://i.stack.imgur.com/2K9FM.png)](https://i.stack.imgur.com/2K9FM.png) *My code when run in a terminal. The appended **&& echo** is for readability only.* ### Some comments: * I think you can only do a 2-chain in PHP since it requires the ";" instruction separator. + You can get around this *once* by using "?>", which implies a semicolon, but obviously can't re-use it a second time + This was the hardest part for me to figure out. I didn't know this worked beforehand, nor that "?>" was even allowed when running via php -r * By using strtoupper() I was able to just write the code for chain #2 in lowercase, while the output is obviously uppercase. Easy mode right there! * urldecode() allows me to encode ";" as "%3b" * That's all there is really, nothing too exciting --- Thanks for the challenge, I learned something today! [Answer] # Lua, 2 chain, 83+8=91 bytes ``` load(('').char(0x70,0x72,0x69,0x6E,0x74,39,0x70,0x72,0x69,0x6E,0x74,34,49,34,39))() ``` Outputs ``` print"1" ``` Which outputs ``` 1 ``` [Answer] # Charcoal, 2 programs, 10 + 2 = 12 bytes ``` ⭆´G´·℅⊕⊕℅ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5///R2rZDW97vWX5oy6Htj1paH3VNBaGW1nM7//8HAA "Charcoal – Try It Online") Outputs ``` I¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9npWHdv7/DwA "Charcoal – Try It Online") Which outputs 1. [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 2 chain, 9 + 2 = 11 bytes ``` 72-_#23-@ ``` [Try it online!](https://tio.run/##SypKzMxLz89J@//f3Eg3XtnIWNfh/38A "Braingolf – Try It Online") This outputs ``` 5/ ``` [Try it online!](https://tio.run/##SypKzMxLz89J@//fVP//fwA "Braingolf – Try It Online") (Plus some default output which can be ignored per OP's rules) This in turn outputs ``` 1 ``` [Answer] # [Röda](https://github.com/fergusq/roda), 2 chain, 31 + 3 = 34 bytes Snippet 1: ``` (`X.Z`/"")|ord _|push _+3|chr _ ``` [Try it online!](https://tio.run/##K8pPSfyfm5iZV/1fIyFCLypBX0lJsya/KEUhvqagtDhDIV7buCY5o0gh/n/tfwA "Röda – Try It Online") Snippet 2: ``` [1] ``` [Try it online!](https://tio.run/##K8pPSfyfm5iZV/0/2jD2f@1/AA "Röda – Try It Online") They are snippets, because every valid Röda program must include `main{...}` bloat. They are also valid Röda REPL programs. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 3 programs, 48 bytes First: ``` 82 2-adAArdAAI2*-rAAI-I2/2^-f ``` Yields the second: ``` 75 P 90 P 110 P ``` Yields the third: ``` KZn ``` Yields `1`. [Try it online!](https://tio.run/##S0n@/9/CSMFINzHF0bEIiD2NtHSLgJSup5G@UZxuGhdXsqFBgIJyck5qYpFCWn6RQl5qRYlCQWZqcqpCfppCckZiZp4VF5e5KVcAl6UBkDA0BJFEavOOyvv/HwA "dc – Try It Online") (has some stack-clearing and newline-printing code thrown in to make all three bits run in one go). Perhaps best to start at program three, `KZn`. There are only a few ways to print things in `dc`, and I realized at this stage I would probably be stuck with either `p` or `n`, both of which are in the 100s in decimal ASCII. This means that I was almost certainly going to have to generate 1 instead of just using the program `1n`. `K` pushes the current (default: 0) precision to the stack, and `Z` pushes the number of digits of top-of-stack, which gives us the 1 to print. The second program is pretty straightforward. `P` prints the character with the given ASCII value, so we print `75` (`K`) `90` (`Z`) and finally `110` (`n`), which works wonderfully. It also means that, aside from the aforementioned 1, I can't use the digits 5, 7, 9, or 0 elsewhere. I also need a method other than `P` for turning numbers into characters. The first program, then, has to make four numbers without using the digits 1, 5, 7, 9, or 0. It needs to make **`80`** (ASCII value of `P`): `82 2-`; **`75`**: `AA` (110) `I-` (subtract the default input radix, 10) `I2/` (so, 5) `2^` (so, 5^2, 25) `-` (75); **`90`**: `AA` (110) `I2*` (twice the default input radix of 10, so 20) `-` (90); and **`110`**: well, it's just `AA`. After making `80`, we use `a` to convert a number to a string. There are some `r`everse and `d`uplicate commands in there to put the `P`s in the right spots, and then finally we print the whole stack with `f`. I'm pretty sure I didn't screw this up, but I did have my head spinning a little bit... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 + 3 = 8 bytes ``` ght<n ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/PaPEJu//fwA "05AB1E – Try It Online") which right off the bat returns I am taking the output 1.0 as not equalling 1, so I run that code: ``` 1.0 ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fUM/g/38A "05AB1E – Try It Online") which returns ``` 1 ``` And there you go! Number of programs = `2` [Answer] # Ruby, 2-chain, 24+3 = 27 bytes ``` $><<(''<<56+56<<' '<<49) ``` Output is ``` p 1 ``` ]
[Question] [ # The challenge Given two integers as input (`x` and `y`), output `x` as a string with as many leading zeroes necessary for it to be `y` characters long without the sign. ## Rules * If `x` has more than `y` digits, output `x` as string without modification. * Output as integer is not accepted, even if there are no leading zeroes. * When `x` is negative, keep the `-` as is and operate on the absolute value. * Negative `y` should be treated as 0, meaning you output `x` as is (but as string) ### Examples: ``` IN: (1,1) OUT: "1" IN: (1,2) OUT: "01" IN: (10,1) OUT: "10" IN: (-7,3) OUT: "-007" IN: (-1,1) OUT: "-1" IN: (10,-1) OUT: "10" IN: (0,0) OUT: "0" IN: (0,1) OUT: "0" IN: (0,4) OUT: "0000" ``` Shortest code in bytes wins, standard loopholes apply. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` %"%0*d",+E>0 ``` **[Try it here!](https://pyth.herokuapp.com/?code=%25%22%250%2ad%22%2C%2BE%3E0&input=-7%0A3&debug=0)** [Answer] # [Python 2](https://docs.python.org/2/), 29 bytes ``` lambda x,y:x.zfill(y+(x<'.')) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9KqQq8qLTMnR6NSW6PCRl1PXVPzf0lqcUmxgq1CNJcCEGioG6rrKBhq6iDxjBA8AxRJXXMg1xjOBUkaoKrVNdTkiuVKyy8C2q5QqZCZpwC2zgqspqAoM69EIU0DJKX5HwA "Python 2 – Try It Online") Just `str.zfill` comes so close. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes Input given as `amount_of_digits, number` ``` ÎIÄg-×ì'-† ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cJ/n4ZZ03cPTD69R133UsOD/f2MuXXMA "05AB1E – Try It Online") **Explanation** ``` Î # push 0 and first input IÄ # push the absolute value of the second input g # length - # subtract, (input1-len(abs(input2)) × # repeat the zero that many times ì # prepend to the second input '-† # move any "-" to the front ``` [Answer] # Python, 29 bytes Take input as `f(x,y)`. Using Python's `%` operator. ``` lambda x,y:'%0*d'%(y+(x<0),x) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9JKXdVAK0VdVaNSW6PCxkBTp0Lzf0lqcUlyYnGqgq1CtIahjqGmDpA0ApEGYI6uuY4xkDLQMYCI6RpqxnKl5RcpZOpkKWTmKcD0WykUFGXmlWikaQAlNDX/AwA "Python 3 – Try It Online") [Answer] # C#, 56 bytes [Try it Online!](https://tio.run/##lY9RS8MwFIXf8ysufVnClpHqw6BdKyL4NHGg4oP4cJtlJbCmJckEkf32mraoVRjUQyD3HvLdcyMdl7VV7dFpU8LDu/OqSgkxWCnXoFRwUxtXH9R108Tkg0CQPKBzsLV1abHqncHv5Dx6LeGt1ju4Q22o8zYMfnkFtKVj3@9@iE63RyPX2vjFqBrAPId9sCBrMcuLLKe4FlcRj5IoYnPadxwTZPPQL7e426i9p0VwRVIsZmLG2nSUQ75@s3y22quNNop242nMwoE5RHD/9JhAHLH014LnsYse6ykxGRN/4sREkK8YvRyBXIjVRDREihEp/rEqP7/riRAy3CfSfgI) ``` a=>b=>(a<0?"-":"")+((a<0?-a:a)+"").PadLeft(b<0?0:b,'0') ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 47 bytes ``` x->y->"".format("%0"+((y<1?1:y)-(x>>31))+"d",x) ``` [Try it online!](https://tio.run/##lc49a8MwEIDh3b/iEBSkphJ2UygkqboVOnTKWDqodhzkyJKwzsGi5Le7Jh8moz3pOD28XKWOiju/s1Vx6HXtXYNQDTvRojaibG2O2lnxuE58@2t0DrlRIcCX0hb@EoDrNqDC4Tk6XUA9/NEtNtruv39ANfvAzhTg0@LHtbi5ny9YSijhre@4jFwSIkrX1AopeUjJgtK4yd6zVWScdlIuM8YWpCBPHevX5/Q2BtzVwrUo/BBDY2kplPcm0oyNA5uOn6fgdE6av970coqed/Z4CZ/CR53OwbPKLxd8Sk79Pw "Java (OpenJDK 8) – Try It Online") At first I thought, easy, 30 chars max (which is quite short when manipulating strings in Java). Then the exceptions happened. [Answer] # JavaScript (ES6), 42 Recursive, parameters in reverse order, first y then x. And [Currying](https://en.wikipedia.org/wiki/Currying) ``` y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0) ``` **Test** ``` var F= y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0) ;`IN: (1,1) OUT: "1" IN: (1,2) OUT: "01" IN: (10,1) OUT: "10" IN: (-7,3) OUT: "-007" IN: (-1,1) OUT: "-1" IN: (10,-1) OUT: "10" IN: (0,0) OUT: "0" IN: (0,1) OUT: "0" IN: (0,4) OUT: "0000"` .split(`\n`).map(r => r.match(/[-\d]+/g)) .forEach(([x,y,k])=>{ o = F(y)(x) ok = o == k console.log(ok?'OK':'KO',x,y,'->', o) }) ``` [Answer] # **[Python 3.6](https://docs.python.org/3/), ~~28~~ 37 bytes** ``` lambda x,y:f'{x:0{(y,0)[y<0]+(x<0)}}' ``` [Try it online!](https://tio.run/##NYvBCoMwEETv/Yq9maUrbPRQCPol6iGthqa0UTSHBPHb01To5Q0zw1uif86uTqbt01t/7qOGQFGZYg@KdxGJsYsND1cRGsbjKJKfNv/Q2wQtdEKSRMqsfuSzlDeqc3A2z62UOFzMvIKlF1gHf1/BslrnhRH5QExf "Python 3 – Try It Online") (Test case from Colera Su's answer) Taking advantage of the new way to format strings in python 3.6 +9 bytes to handle `y<0` [Answer] # bash, ~~27~~, 25 bytes -2 bytes thanks to Bruce Forte ``` printf %0$[$2+($1<0)]d $1 ``` [try it online](https://tio.run/##S0oszvj/v6AoM68kTUHVQCVaxUhbQ8XQxkAzNkVBxfD///@GBv@NAQ) [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` Ö±Ωo≥⁰#±:'0s ``` [Try it online!](https://tio.run/##ASMA3P9odXNr///DlsKxzqlv4oml4oGwI8KxOicwc////zX/LTM0MA "Husk – Try It Online") ## Explanation ``` Ö±Ωo≥⁰#±:'0s Inputs are y=4 and x=-20 s Convert x to string: "-20" :'0 Prepend '0' Ω until #± the number of digits o≥⁰ is at least y: "00-20" Ö± Sort by is-digit: "-0020" Print implicitly. ``` [Answer] # R, ~~56~~ 48 bytes ``` function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x) ``` [Try it online!](https://tio.run/##XYzRCsIwDEXf/YoQEBJMIVVhL@vHyLSwlzq2Ct3X163bKpi3czg3Y/bgsv@ELvbvQElmnoaxD9HT8JjiSwnPijJfKLXKgk9kSZw9WbEMAM4BWjytfD1YN6GlKIGuwjRy24VRbYqytTHHyCzmN1LR@nZj@8f3ysth/gI "R – Try It Online") -8 bytes thanks to [djhurio](https://codegolf.stackexchange.com/users/13849/djhurio) ### Explanation * `sprintf("%0zd",x)` returns `x` as a string padded with zeros to be of length `z` * `paste0("%0",y+(x<0),"d")` constructs the string `"%0zd"`, where `z` is `y`, plus 1 if `x` is less than zero * If `z` is less than the number of digits in `x`, `x` is printed as a string as is [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~13~~ 8 bytes Takes first input (`x`) as a string. ``` ®©ùTV}'- ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=rqn5VFZ9Jy0=&input=Ii04IiwtOA==) Saved a massive 5 bytes thanks to ETHproductions. --- ## Explanation Implicit input of string `U=x` and integer `V=y`. `® }'-` splits `U` to an array on the minus symbol, maps over it and rejoins it to a string with a minus symbol. `©` is logical AND (`&&`) so if the current element is truthy (a non-empty string) then pad left (`ù`) with 0 (`T`) to length `V`. [Answer] ## [Alice](https://github.com/m-ender/alice), 23 bytes ``` /oRe./'+Ao \I*tI&0-R$@/ ``` [Try it online!](https://tio.run/##S8zJTE79/18/PyhVT19d2zGfK8ZTq8RTzUA3SMVB//9/Q3MuYwA "Alice – Try It Online") Input should be linefeed-separated with the number on the first line and the width on the second. ### Explanation ``` /... \...@/ ``` This is the usual framework for linear programs in Ordinal mode. The only catch in this case is this bit: ``` .../... ...&... ``` This causes the IP to enter Cardinal mode vertically and execute just the `&` in Cardinal mode before resuming in Ordinal mode. Unfolding the zigzag control flow then gives: ``` IRt.&'-A$o*eI/&/0+Ro@ I Read the first line of input (the value) as a string. R Reverse the string. t. Split off the last character and duplicate it. & Fold the next command over this string. This doesn't really do anything, because the string contains only one character (so folding the next command is identical to executing it normally). '- Push "-". A Set intersection. Gives "-" for negative inputs and "" otherwise. $o If it's "-", print it, otherwise it must have been a digit which we leave on the stack. * Join the digit back onto the number. If the number was negative, this joins the (absolute value of the) number to an implicit empty string, doing nothing. e Push an empty string. I Read the width W. /&/ Iterate the next command W times. 0 Append a zero. So we get a string of W zeros on top of the absolute value of the input number. + Superimpose. This takes the character-wise maximum of both strings and appends extraneous characters from the longer string. Since the string of zeros can never be larger than the digits in the input, the input itself will be uneffected, but extraneous zeros are appended, padding the string to the required length. R Reverse the result. o Print it. @ Terminate the program. ``` Here are two alternatives, also at 23 bytes, which use Cardinal `H` (*abs*) to get rid of the `-`: ``` /R.I&0-RoH \Ie#\'+Ao\@/ ``` ``` /R.H#/.+Xo \Ie\I&0QRo@/ ``` In principle, these are a command shorter, but the `&` doesn't fit into a position where there's a 1-character string on the stack, so we need to skip it with a `#`. [Answer] # C, 33 bytes ``` f(x,y){printf("%0*d",y+(x<0),x);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0KnUrO6oCgzryRNQ0nVQCtFSadSW6PCxkBTp0LTuvY/UEIhNzEzT0OTq5pLAQjSNAx1FAw1rQtKS4o1lJQ0rRGiRlhEDbAq1jXXUTDGIozDaKAhuljEsZuNU9QEyKn9DwA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 13 bytes ``` ‹N⁰﹪⁺⁺%0ηd↔Iθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9Rw873e9Y9atzwfueqR427gEjV4Nz2lEdtU97vWXlux///uuZcxgA "Charcoal – Try It Online") This is the shortest I could get using Charcoal without printing leading or trailing whitespaces. At least I am now starting to understand how to use the `Modulo` function to format strings. The deverbosed code is as follows: ``` Print(Less(InputNumber(),0)); # Prints a - if the first input is less than 0 Print(Modulo(Add(Add("%0",h),"d"),Abs(Cast(q)))); # q: first input; h: second input ``` * 3 bytes saved thanks to Neil! [Answer] ## [Retina](https://github.com/m-ender/retina), 39 bytes ``` \d+$ $*0 ((\d)*),(?<-2>-0+|0)*(0*) $3$1 ``` [Try it online!](https://tio.run/##FcchDoAwDABA33eUpC1t0m4CQ0DyiQlIhsAgCJK/D3B3134f59Y6WtZWao@A4kBUKgsrzaOlybx/nIVcGDBjtBYaEJog/IMNmsHV/1m8 "Retina – Try It Online") Input should be comma-separated with the number first and the width second. [Answer] # PHP, 45 bytes ``` printf("%0".($argv[2]+(0>$n=$argv[1])).d,$n); ``` or ``` [,$n,$e]=$argv;printf("%0".($e+(0>$n)).d,$n); # requires PHP 7.1 or later ``` Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/9074bd4d6a0d2f1f5d395c61858c0278663dc242). [Answer] # Mathematica, 118 bytes ``` (j=ToString;If[#2<=0,j@#,If[(z=IntegerLength@#)>=#2,t=z,t=#2];s=j/@PadLeft[IntegerDigits@#,t];If[#>=0,""<>s,"-"<>s]])& ``` [Try it online!](https://tio.run/##VY2xCoMwFEX3foaBopDQmA4d9EmGLoKD0G6SIbRJjKAFfZM/n6aloB0uj8O7nDtq7M2o0T90sBDSAe6vG85@ckVtOyJK4HSQhEZIV6gnNM7MjZkc9pJkFRBBEdYYIlSxwHCSrX42xmL3616987hEA6qvsYrCJCmrhSbsc5TKjqGNgyhtl9NcHTYQO@D7F7vQ80ac8r8iy1V4Aw "Wolfram Language (Mathematica) – Try It Online") [Answer] # Mathematica, ~~63~~ 62 bytes ``` If[#<0,"-",""]<>IntegerString[#,10,Max[#2,IntegerLength@#,1]]& ``` [Try it online!](https://tio.run/##TYuxCsMgFEX3fMVDIdMLaJrSoWlxDTRQ6CgOUtRkiJTgUAh@u3WoJNu595676DCZRYf5rZO9pcFK2jMkDUFCVH8ffDDOrK@wzt5JipzhqL@StvhfHsa7MIm8KFWnUX/kM6tBWiGoqhG2CgA2jsAjFmwLsr1uLginwkc9O00JmdmOh7Yrz3O2u1hFdU0/ "Wolfram Language (Mathematica) – Try It Online") [Answer] # Excel, 29 bytes Using Excel's `TEXT` functionality ("Converts a value to text in a specific number format"). `x` in A1, `y` in B1 ``` =TEXT(A1,REPT("0",MAX(1,B1))) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 44 bytes ``` @(x,y)fprintf(['%0',num2str(y+(x<0)),'d'],x) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KnUjOtoCgzryRNI1pd1UBdJ68016i4pEijUlujwsZAU1NHPUU9VqdC83@ahqGOkSYXVLF6TJ66Jleahq65jjGGoKGBjqHmfwA "Octave – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 54 bytes ``` x#y|s<-show$abs$x=['-'|x<0]++('0'<$[length s+1..y])++s ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0K5sqbYRrc4I79cJTGpWKXCNlpdV72mwsYgVltbQ91A3UYlOic1L70kQ6FY21BPrzJWU1u7@H9uYmaegq1CSj6XAhAUlJYElxT55CmoKBgqKCsYYhM0whA0wKZUQ9dcEyhujC4OUmyA1QgNXUPN/wA "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~31~~ 28 bytes Thanks [Carl](https://codegolf.stackexchange.com/questions/149620/the-leading-zeroes-challenge/149657?noredirect=1#comment365719_149657) for saving 3 bytes using interpolation. ``` ->x,y{"%0#{y+(x<0?1:0)}d"%x} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7JaSdVAubpSW6PCxsDe0MpAszZFSbWi9n9BaUmxQlq0oY5BLBeUbaBjCmcb6hgiJHQNDXSMY/8DAA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes *Saved 2 bytes thanks to @ETHproductions* ``` s r"%d+"_ù0V ``` [Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=cyByIiVkKyJf+TBW&input=LTcsMw==) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~25~~ 40 bytes ``` param($a,$b)$a|% *g $("D$b"*($b|% *o 0)) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyWxRlVBK11BRUPJRSVJSUtDJQkkkK9goKn5//9/DV1jc00gaaoJAA "PowerShell – Try It Online") ## Explanation This calls `.ToString()` on the number with a generated format string, but multiplies it by -1, 0, or 1 based on whether `$b` (`y`) is negative, 0, or positive respectively; this is to handle negative `y` values which format strings don't by themselves. This seems to require wrapping negative numbers in a substatement `()` for it to work which is just a quirk of the invocation when using literals; if passed variables of type integer, it would not need that. [Answer] # C# 6.0, 35 bytes ``` (x,y)=>(x.ToString($"D{y<0?0:y}")); ``` ### Alternative solution (51 bytes) ``` (x,y)=>(x.ToString(string.Format("D{0}",y<0?0:y))); ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~90~~ ~~86~~ 83 bytes ``` import StdEnv @x y=if(y<0)"-"""+++{if(c>'-')c'0'\\c<-rjustify x[k\\k<-:toString y]} ``` [Try it online!](https://tio.run/##Dcy7CsIwFADQ3a@4ZImlBAoOgqTSQQfBLaNxCGlT0uYhSSoN4q8bO57lSDMIV6zvFzOAFdoVbV8@JGCpv7r3rlsht1rtM20qRBBCdV1/NsszJriSuMGcS0rCtMSkVYb1MXM@U3JKnqWg3Qj5@S0sia1soYMDkGP5SWXEGAu53cslO2G1jH8 "Clean – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 45 bytes ``` f(x,y){printf("%s%0*i","-"+(x>=0),y,abs(x));} ``` [Try it online!](https://tio.run/##bc7BCsIwDIDhu09RAoNEU0hV8FD0XWah0oNj2A06xp69luFhuOb48YfE6ZdzOXtMPNHcf0I3eIQmNnIMwKDhhOlxF@KJ22fERGSXXCL1bkOHpOaDR8OGrCrTj0NEALIrnisov3SL@saXPZpKWdb1qlsUlv0hqb0kfP3HJX8B "C (gcc) – Try It Online") ## Explanation `printf` formats three arguments: ``` %s -> "-"+(x>=0) %0*i -> y -> abs(x) ``` `%s` formats the string `"-"+(x>=0)`. `"-"` is really just an address, something like `41961441`. In memory, this looks something like this: ``` MEMORY ADDRESS | 41961441 41961442 ... VALUE | 45 ('-') 0 (0x00) ... ``` When formatted into a string, C takes the address (say 41961441) and keeps on acquiring characters until a null byte (0x00) is met. When x is less than zero, the value `"-"+(x>=0)` has that of the original address (41961441). Otherwise, `x>=0` is 1, so the expression becomes `"-"+1`, which points the null byte after `"-"`, which prints nothing. `%0*i` prints an integer padded with a specified number of `0`s. `y` denotes this number. We pad `abs(x)` to avoid the negative in some arguments. [Answer] ## Perl, 25 + `-n` flag = 26 bytes ``` printf"%0*d",<>+($_<0),$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1UArRUnHxk5bQyXexkBTRyX@/39dcy7jf/kFJZn5ecX/dfMA "Perl 5 – Try It Online") [Answer] # Perl 5, 22 + 1 (-`n`) = 23 bytes ``` printf"%0*d",<>+/-/,$_ ``` [Try it online](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1UArhUtJx8ZOW19XX0cl/v9/Qy4QNOIyNABSuuZcxly6YCEDEG0AhiDa5F9@QUlmfl7xf908AA) ]
[Question] [ ## Task: Your challenge is, given previous submissions and itself as input, output the language that they're written in, in the following format: Say the first program is in Ruby. It must output `1`, because Ruby is the `1`st language used in this challenge. An example program is: ``` a=gets puts 1 ``` When given itself as input, it returns `1`. The next program might be in Python. It must output `2`, because Python is the `2`nd language used in the challenge. An example program is: ``` print(1 if input()[0]=="a"else 2) ``` Given the first submission, it outputs `1`, and given itself it outputs `2`. You're allowed to repeat languages, though you're not allowed to submit an answer in the previous answer's language. For example, if the third program is in Ruby, it must output `1` given the first program and itself (because Ruby is the `1`st language used), and given the second program it must output `2`. --- ## Rules: * If there are `n` answers currently in the challenge, there must be at least `floor(n / 3)` different languages. Any submission that breaks this rule is disqualified. * No two "neighbouring answers" (e.g. answer `n` and answer `n+1`) cannot use the same language. * Different versions of a language do not count as different languages (so `Python 2 == Python 3`). * Answers must take previous submissions in full as input. * The first submission must take input. * You are not allowed to submit multiple answers in a row. * "Repeat answers" (answers that have the exact same code as a previous submission) are not allowed. * Answers are not allowed to go over the allocated byte-count of that answer - see "Allocated Byte-count" for more details. --- ## Allocated Byte-count: For each answer number `n`, the allocated byte-count for that answer is `45 + 5n`. --- ## Answer formatting: Format your answer like so: ``` # {answer no.}, {language} {program} This prints: - `1` in answer(s) {all answers using 1st language, with links} - `2` in answer(s) {all answers using 2nd language, with links} ... {optional explanation} ``` For the answer lists, do this: ``` - `1` in answers [1]({link to answer}), [3]({link to answer})... ``` --- ## Scoring: The first answer to survive after 7 days without any valid submissions after that is declared the winner. [Answer] ## 1. [Retina](https://github.com/m-ender/retina), 0 bytes [Try it online!](https://tio.run/nexus/retina "Retina – TIO Nexus") The empty program prints `1` when given empty input (i.e. itself), because it counts how often the empty regex matches the input (which is always `1+length(input)`). [Answer] # 2. [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 22 bytes ``` {<>(())(<>)}{}(<>{}()) ``` [Try it online!](https://tio.run/nexus/brain-flak#@19tY6ehoampYWOnWVtdC6SAhKbm//84xHUTAQ "Brain-Flak – TIO Nexus") This checks the top of the stack and puts a one on the opposite stack if it is non-zero. It then increments and returns the opposite stack. This makes it return 1 for the empty program and 2 for anything else. Since stacks in Brain-Flak default to zero, an empty program will have a zero on the top of the stack while any other program (except programs which end in null characters) will have a truthy value. This means we can run a very simple if program on the input stack. ``` { (<>)}{} #If not zero <>(()) #Push one to the other stack (<>{}()) #Switch to other stack and increment by one ``` [Answer] # 3. APL, 7 bytes ``` ' {'⍳⊃⍞ ``` Explanation: ``` ⍞ read from the keyboard ⊃ first item of list, or space if empty ' {'⍳ index into the string ' {', giving N+1 (=3) if not found ``` [Answer] # 10. Bash (+coreutils) [language 6], ~~44~~, 74 bytes **Fixed Version** (returns the language id) ``` expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G ``` Note: this expects the trailing newline, after the input program text [Answer] ## 9. [Retina](https://github.com/m-ender/retina) (language 1), 20 bytes ``` $|}\{|[:'][^]']|,\b1 ``` [Try it online!](https://tio.run/nexus/retina#hZBNasMwEEb3OkUrUjQDKtT52bgZG7rpIWwFx6raGEwWkUsWkjftLuAr9BLtiXQRV4IuA93MPL5h3sDcwXMzL/xYO1/lQlU7JZSXdZvNM3PbAgARtgWObowtFkQmbpwI03e4fIbpi1kqbGmrB0XUuKZc5n9sm3Kdr/KM7RYeytsqXD7C9KMwwX0iXz@RdyPT@wHsuRv0Aex7a4cTnMz@pe@OBlBmMkPJHael5ILTSnLLaS255rSJI/zP7ut2wzSdD13Ua@A8yZIqiZIGia5fxcfu1fTWQG@Ob0NcRqljzK796hc "Retina – TIO Nexus") Like plannapus, I decided to go for a rewrite to switch things up a bit, which also ended up shortening the code considerably (a modification of my last answer to account for plannapus's latest would have ended up around 32 bytes, I think). ### Explanation Like my other answers, this just counts the number of various regex matches, but goes about it much more efficiently: * `$` matches the end of the string. This always works, even if there's a match going all the way to the end of the string, so this gives us a baseline of `1` for all inputs. * `}\{` finds a single match in the second program (Brain-Flak), bringing the count there up to `2`. The backslash isn't necessary for escaping but it prevents this part of the regex from matching itself. * `[:'][^]']` is pretty fancy actually. The only purpose is to count the two `'` in the APL program (language 3) and the three `:` in the JavaScript program (language 4), but we need to prevent this part from matching itself. So we also ensure that the next character is neither `'`, nor `]` (because those don't appear after the ones we *do* want to match, but they do appear in this program here). * The `'` from the previous part already causes one match in the R programs, so we need three more. The substring `,1` appears in both of them three times, and in no other programs. We match it by adding a tautological wordboundary in between with `,\b1` to prevent it from matching itself again. [Answer] # 18. C (language 10), 121 bytes This is the C89 or C90 standard. It works with either clang or gcc on Try It Online. ``` main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);} ``` This prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/), [5](https://codegolf.stackexchange.com/a/107341), [7](https://codegolf.stackexchange.com/a/107350), [9](https://codegolf.stackexchange.com/a/107370), and [14](https://codegolf.stackexchange.com/a/107479) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338), [12](https://codegolf.stackexchange.com/a/107422), and [15](https://codegolf.stackexchange.com/a/107495) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346) and [8](https://codegolf.stackexchange.com/a/107364) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388) and [17](https://codegolf.stackexchange.com/a/107542) (Bash). * `7` with answer [11](https://codegolf.stackexchange.com/a/107403) (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511) (Perl). * `10` with this answer (C). Here is a bash driver that runs it with all 18 answers on [Try it online!](https://tio.run/nexus/bash#xVTdjqM2FL7nKVxPNtipw0LCX8gA2Z3t7F5UnUiVtlUJSYhxEiQCESYzqSA327uV5hX6Eu0T5UWmJqFqt6rUywrJ5/M5cHyOv@9AoxJ4II2yDVcouL0F3zzcv@yiJEMZrug2KnqPLgTzCnDApuunHSSrYDQahaRHxxtWcrTCY@rysqDbAj2SnthmzTZlWRPaF0lWrhF8FUOS@dSn/Ucn80YjXxfGVH1DGM3wNWfoaHh8ehGnSxtKQT8HafxnWdI6L0AGkgxUqqYomn0agzgHjG5z0M9AJwMQwDFQXqfx@OJtwhl7kapbDyGM0a2HT9VJGLFgLMmgks/Pv50//3J@/lXirsd9Hqih6y6rpT9wWsyXokhRljTv1Mj/Kjh//nR@/j3EDeg3qJ69devqJNGoRPwpKekW8cNK9I4KFsVpkjGEiUY0TGAF3QGBMnSHBHLo6gRS6BoihP8rez1bGRJ1n7aJSE8RhE2yJlWTqEmDXfffT8XjZM1SzpCgYlOKjzGhwi116tOsqgNHDoN5KIc1ma00iR33BbjmAVAbDHXNEI8JQQddQkkWsyOAQ9NY2zFV2QqC5S42@GFX00MJ@lQbLDHQwM17aZrzpEzyLLgT6oloyQo@gfNK5pRNIbnpTiY3YRCICsPwtbKYLBZ9T@uKFj2hjsvNy0z2TafFHbmuWziXhU5aTOVulyrXzjxbFUy1gansW3@9JPTV4koWzLaYy1dmx9K6yHdgG/FtmqxAstvnRdm7ahb97RYs3YYBjAymrUdDk8aWvYLK5UYQ30YDw0RJtj@UCCsso3ksCMDKlh3jZMO48AZDPcQhvvlOkgMgdBdeCcgnzoUBKmw9pxceam0W1x2pdD1UDXRnQGzTGRLD0Yk1dAxi2mKxdMciumMSayT8mmMT03L0Ew4CRVHKUClYfKAMoULQnWDXK3rJnCrNKN@J2t6USMVExV31aNyHda1JQlopa0akujTequAf/Wv6CJJry1C9d6cPu@/Ndzpb/PjDxw@QNLOvW1@3Quss8CtLxUKFYqK/UJY50jVbt8xLWn040L6U12Babt4@pMXj@t3HO/unD9@CZb5nGecpEFoD/VWSRcXP9SrizNRb3bWyO0r/2z/rDw "Bash – TIO Nexus") Ungolfed equivalent (646 bytes): ``` #include <string.h> #include <stdio.h> int main(){ char *v=" ^{ s ePfwm", b[999]; gets(b); /* buffer overrun if more than 998 characters in the input. could be a problem if we get to 191 answers */ char *c = strchr(v, b[0]); /* Find first character of input in v, or null */ int n = strlen(b); if (!n) { printf("1"); } else if (c) { printf("%d", c-v); /* Index of first character of input in v */ } else if (n > 99) { printf("4"); } else if (n > 60) { printf("5"); } else if (n > 15) { printf("1"); } else { printf("3"); } return 0; } ``` [Answer] ## 5. [Retina](https://github.com/m-ender/retina) (language 1), 23 bytes ``` ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/gfp1KjYa8Y/air6VHvllhNEEMXxKqJcbKtqa79/5@r2sZOQ0NTU8PGTrO2uhZIAQlNTS51hWr1R72bH3U1P@qdx1Vsa1dsXxxtEGtrm1CdYG9kBWUXJ9ibWBlbGXIRsAcA "Retina – TIO Nexus") (Tests all possible inputs.) Counts the matches of various things in the input: * `^$` matches the input string, i.e. the first answer once. * `{}` matches itself, which there are two of in the second program, and one in this one. * `(?![⊂⍴])[⊂-⍴]` matches characters with code points 8834 to 9076, *exclusive*, which finds three matches in the third program. We use the negative lookahead to avoid the ends of the range being matched in this program. * `\B=` matches a `=` that *isn't* preceded by a word character. This matches four of the `=` in the fourth program, and doesn't match the `=` in this program. [Answer] ## 7. [Retina](https://github.com/m-ender/retina) (language 1), 27 bytes ``` ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5 ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/gfp1KjYa8Y/air6VHvllhNEEMXxKqJcbKtqa6tiUky/f@fq9rGTkNDU1PDxk6ztroWSAEJTU0udYVq9Ue9mx91NT/qncdVbGtXbF8cbRBra5tQnWBvZAVlFyfYm1gZWxlyEbCLKzmxRKO4PLMkOUOjuDSpuKRIoyg1MSUnMy9VQ1PHUMdQU0epWsnWSEdJXcnWWEepWMnWREcpWcnWFCilyUWETwA "Retina – TIO Nexus") (Tests all possible inputs.) A minor modification of the [fifth answer](https://codegolf.stackexchange.com/a/107341/8478). `\B=` already finds 4 matches in the sixth answer, and `\b5` finds another without matching any other answers. [Answer] # 26. [><>](https://esolangs.org/wiki/Fish) (language 12), 164 bytes My first ever program in ><>! It's 156 characters, but 164 bytes in UTF-8. ``` ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} {:}&1+&=?v .&0/ v+!?='>'i41i v+?='y'i47 v+?=' 'i12 v+?=' 'i24 v4 v6 v7 v8 v9 va v?(0:i v1 n;\b1laa*)?+ /"^mwfPes{'tc"i2&01.; ``` This prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/18314), [5](https://codegolf.stackexchange.com/a/107341/18314), [7](https://codegolf.stackexchange.com/a/107350/18314), [9](https://codegolf.stackexchange.com/a/107370/18314), and [14](https://codegolf.stackexchange.com/a/107479/18314) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334/18314) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336/18314) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338/18314), [12](https://codegolf.stackexchange.com/a/107422/18314), and [15](https://codegolf.stackexchange.com/a/107495/18314) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346/18314) and [8](https://codegolf.stackexchange.com/a/107364/18314) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388/18314), [17](https://codegolf.stackexchange.com/a/107542/18314), [20](https://codegolf.stackexchange.com/a/107579/18314), [22](https://codegolf.stackexchange.com/a/107818/18314), and [25](https://codegolf.stackexchange.com/a/108122/18314) (Bash). * `7` with answers [11](https://codegolf.stackexchange.com/a/107403/18314) and [19](https://codegolf.stackexchange.com/a/107575/18314) (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443/18314) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511/18314) (Perl). * `10` with answers [18](https://codegolf.stackexchange.com/a/107567/18314), [21](https://codegolf.stackexchange.com/a/107817/18314), and [23](https://codegolf.stackexchange.com/a/107936/18314) (C/C++). * `11` with answer [24](https://codegolf.stackexchange.com/a/107959/18314) (Zsh). * `12` with this answer (><>). [Try it online!](https://tio.run/nexus/zsh#tVXrctpGFP6vp9isMSuBwFp0A4EQtlMnjd2EXJpLhbDFShhNQVKQwPZI/Gn/ZSav0Jdon8gvkh4BduPGM850psDsuax09pzvfMthboq6aOrVx8kEdTrkhxdH5MuwlPPWI/v602/Xn/9yhEKpFVo@ODDzbMVlxqpMq2XTWnJo/amXpT1uWX1kmaRLAoUGYIB@Bbq@UREJaONWbSjcEn4at4TtJrdscUsXQi0tXjLgXcqF7cGITl23IlhVbg8PZxfjvp9kJGU4aJQlWm9/gUw5tsneDc@Tm@Q5Lut0eV4Q@E5XWGUrELAIAkdQRq4//3n96ffrz39widlNrMSWHNM8y86shrHVkzNLMWSDcg9hAEfzyUWQsgmfLEZJOufnvutNg9DnBZGKVBBxhs2GiAk2ZREn2FREzLCpwpbwUPR8MFI5Zl5MAgjPeIyLYEWoIlARRjDN@08V2sHYnyY@P/XD8xReFkQGbq6UrwZZbhvEsYcOcXIR8OX8y3iONnEQpg1ZoSp8NYxK/HorCD3/EmFZU8dNj0n@CKOzmacmi1nOFimqMdo4ExBFO0@4fpQEaRCF9uHEnbss9edJDw8zkjC/j8Wdcq@349g2ZOg4e/XT3ulprUvLUGKXWWyNPPGJpRlbvUTyfKsOiUVv3IyUy6y@qazblKBT240@sfR/HrLUGz0j0NmtnpBNZ9vceB7N0MRNJtNghIJZHM3TSjueB2HKf4WCrjSxjV3Vp@OWrDFPb45wfY0In0zchqrxQRgvUl6o@yGLPGiAUJ/4l15w7ifgtWXFERxh5zlHbAS8czYNiHrGugMMZD5k6z7kdODlJS41u3zWUIyG2NQMWVQNRdRlQxW1Jiy6YuiiYmii3gI/NZqiphvKSrDter2eOvW57y2Yz/NzaHcgmN15JRiyOoNmHEJu@ykvCaIklKVL9cjJc8oBtaZ@cUWydeFbFvyrfqq0sLgpGUtHZv/F7LX2WPFP3797@xSLbDLnFb26JVrpVNjVJQFYKLRXd5iltRTaVHRtHVaRG/QuvRr99PzgxXS@HD9@e9j85ekJOotiP0ySKQKuodooCN35VT5yE19Ttrzb0u6Sm7lByIdCVhRaWZoYDTOUIL8/vphhcWS3Wi1HrLD2uZ8m/EhoMxMSKvJeihUww8KE/IutNQxjHu96WAwtYGVtaYTdVgtIE3Y1CTgVdqkKXAQKFRXeEv5NdEv5Aure6xQinb@Op0Haw@3nr34uoZfoANnUQOYJeiYidRfJaAd1sfhT5Nkna/h6O6LaEmXZubkk5bsQ6vsPoKhLyn8GMkceQzWfaoEVo53FBlQhK2hxLHo2UN3JpFV7Qxn@2AQ0C7yB8I9M@MsVPPvYqVbvIOjZzaZjtQzPprTlWGoFlIbsgC2rjgUr7OpGs@bZLa3wKmArIDXJgRtLq/C42nQqjW@4tP8wFIF8eeTHL5N9d3r14zL92P@g//K8igaDWzg29/d@RKj0LSQnG0jYBpMNIuZXkLB7IGH/JyTF7AtNyo0XIStIiKJFGqOMQ5sDEdlteIgALHxYrcK4QfFVOolCGe1Fcbo3DpLJeqnHV9vRzyGfTSJuxY2jORoDkAiXMn4s4BLfWY9XAa8w50WbgzqdDi6NCzv0ua1nM3zTq9hPfMBxH8VcbPLYHpSGTiUnA7uC4cqSrEJQA2GCwJQRscwuOBREmGVfpA7oKiI@CA2RPggdkTGIJiIXIFqIzEBQCZH0qlBgsBV5o1IW2/yvQok6Ro2u0E6vc3ZRfp@tcbqTX7auE9VCRFzPS6KZn7jT1CJtGOdttMrvcO1g/3voRt9Jbw6VD/Pji1dP9p8t4scfQ/39lEXn38s45R7GNb9KfduiL38D "Zsh – TIO Nexus") Explanation: The first line is simply answer #5. It does nothing but send the instruction pointer to the bottom line. `/` turns the fish right, and the characters `^mwfPes{'tc` are put on the stack. A single character of input is read (`i`). (Let's call this character `C` for exposition.) 2 is put in the register (`2&`). Then we jump to the beginning of the second line (line 1) (`01.`). This line compares `C` to each character on the stack. A copy of `C` is kept on the bottom of the stack. `{` rotates the stack so `C` is on top; `:` duplicates it; `}` rotates the copy back to the bottom. We increment the register (`&1+&`) until a match is found. (So if `C` is "c", the register holds 3 when the match is found; if `C` is "t", the register holds 4, and so on.) Then we jump to the first character of the line number in the register (`0&.`). Lines 3 through 13 deal with what to do when `C` is c, t, ', {, etc., respectively. The instruction pointer is moving backwards when we jump; it lands on the first character of the given line, but after a jump it advances a tick before executing, so it begins executing from the end of the line going backward. Each line pushes the appropriate language number on the stack, then sends the fish down to the `n` instruction, which prints it out. `^` is the most complicated case, because of my own dastardliness with the first line of this answer. Line 13 reads input until EOF. Then it directs down to line 15, which compares the length of the stack (`l`) to 100 (`aa*`). If it is longer (`)?`), we add `+` `b` and `1` to get 12, this language; otherwise, 1 remains on top of the stack. [Answer] # 4, JavaScript (ES6), 32 bytes ``` s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 ``` Outputs 1 for an empty input, 2 if the input starts with a `{`, 4 if it starts with an `s` and 3 otherwise.. [Answer] # 11. Mathematica [language 7], 53 bytes ``` Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1& ``` Unnamed function taking a list of characters as its argument and outputting a positive integer. Simply branches on the first letter of the input, using its position in the string `"^{'sceP"` to decide on the output. This gives the right answer for all previous submissions except [the initial empty Retina program](https://codegolf.stackexchange.com/a/107333/56178) and [the most recent Retina answer](https://codegolf.stackexchange.com/a/107370/56178); both of these spit errors, but the output is repaired by the rule `/._@__->1` which transforms any unevaluated function to `1`. [Answer] # 16. [Perl](https://www.perl.org/) (language 9), 94 bytes ``` while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);} ``` [Try it online!](https://tio.run/nexus/perl#tVPdbtMwFL7PUwS31PbwQv6TpUvSMTS4gkpIgJSmf467ROqf4lSrFPcG7ibtFXgJeKK@yHDbTCCExBWyZH86x/p8zvcdP97lxZyhywjX67JYVirfTHlVImCYlm04crme7Rv2BSDFMmNbBPSbsP9@8cF9bbPR508f3wJC8xLZ3os5W95WOWqP8HNPx5gYuLt7fFTqywghjA9P7OqdPOSGsQLVGu4fvu/vv@4fvik8jHjMEz0Nw3E9js2gwXwc24EVGMqwLVD8LNnff9k//EjxAZwfkBi8CkW9U@ikQvyuqGiOmg5KNsnmxZIhWYmshYAahCYBEIQWARyENgEUhI5M4X@xi8HUUWgopZL0FAFwIDtQHYgONDgM//4q7hYzNucMNeJQTKgMK22xG9QiCWCaDFOYCjKYGgrbrstGf/U3/YHaRsfU0QAVWK4z8zOqsylQx4vM4ZuFoJtKPaeGOcaqobbeKP0VL6pitUyu80k5oRUreQ8Ma8gp6wPS6vR6rTRJZIVp@lIb9Uaj88joyBYjGtOj8pDB2A0a3IZCNHAIY@MpTGGnQ7VTZ5GvS6eaRB/G3q9LsfOEayidbTCHJ2e7yqxcLdR8wvN5MVWLxXpVVmfd4zD@MYUgAROHGbMLy6WZ50@BdhpJnk9Mx0XFcr2pENbYkq4yaQDWcrbNilvGZTSx7BSnuPVOgYkq5y49GbDqBUcHqDzFkB59EMYgE22lCiNUm3ZgEt8NLOIENvGswCGuLzfPDjxiBy7xLmTcCHzieoG9w0miaVqVaiXLNpQhVEq7CxxG5VkxpBqVZlzL2q4qpGOi446@dW5SIQzl//7Cnw "Perl – TIO Nexus") (checks all answers). Outputs "1234151516748149" This prints: * 1 with answers 1, 5, 7, 9 and 14 (Retina). * 2 with answer 2 (Brain-Flak). * 3 with answer 3 (APL). * 4 with answers 4, 12 and 15 (Javascript). * 5 with answers 6 and 8 (R). * 6 with answer 10 (Bash). * 7 with answer 11 (Mathematica). * 8 with answer 13 (Python). * 9 with this answer (Perl). The program checks input length and maps it to the current language distribution. [Answer] # 6. R (language 5), 61 bytes ``` cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) ``` Checks what is the first character of the input and choose output accordingly. This thus prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/6741) and [5](https://codegolf.stackexchange.com/a/107341/6741) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334/6741) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336/6741) (APL). * `4` with answer [4](https://codegolf.stackexchange.com/a/107338/6741) (Javascript). * and `5` with this answer. Usage: ``` > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 1 > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) {<>(())(<>)}{}(<>{}()) 2 > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) ' {'⍳⊃⍞ 3 > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 4 > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} 1 > cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 5 ``` [Answer] # 8. R (language 5), 76 bytes ``` c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1) ``` Checks the first letter of the input, and compares it with a vector containing (in that order) the empty string, `{`, `'`, `s` and `c`. It then outputs the index of the match (R indexing is 1-based) or 1 if there is no match. Same concept as answer n°[6](https://codegolf.stackexchange.com/a/107346/6741) but prevents answer n°[7](https://codegolf.stackexchange.com/a/107350/6741) from matching it. This prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/6741), [5](https://codegolf.stackexchange.com/a/107341/6741) and [7](https://codegolf.stackexchange.com/a/107350/6741) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334/6741) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336/6741) (APL). * `4` with answer [4](https://codegolf.stackexchange.com/a/107338/6741) (Javascript). * and `5` with answer [6](https://codegolf.stackexchange.com/a/107346/6741) and this answer (R). If I'm not mistaken, the byte-count allowance for this answer was 94 bytes. [Answer] # 12. Javascript (language 4), 117 bytes Note: I changed a character to correct a mistake in this one. ``` c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1; ``` Checks the first letter of the input, if it's c, checks the length of the input. Outputs: * 1 for answers 1, 5, 7, 9 * 2 for answer 2 * 3 for answer 3 * 4 for answer 4 and this answer * 5 for answers 6, 8 * 6 for answer 10 * 7 for answer 11 [Answer] # 13. [Python](https://docs.python.org/3.5/) (language 8), 110 bytes **Note:** This answer was altered 6 hours after posting, at the recommendation of the OP. ``` from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N ``` This is the same idea as answer 10 (in bash), but in Python 3. (This approach can work for at most 3 more entries before we run out of hex digits.) This prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/), [5](https://codegolf.stackexchange.com/a/107341), [7](https://codegolf.stackexchange.com/a/107350), and [9](https://codegolf.stackexchange.com/a/107370) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338) and [12](https://codegolf.stackexchange.com/a/107422) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346) and [8](https://codegolf.stackexchange.com/a/107364) (R). * `6` with answer [10](https://codegolf.stackexchange.com/a/107388) (Bash). * `7` with answer [11](https://codegolf.stackexchange.com/a/107403) (Mathematica). * `8` for this answer (Python). Try it online! for: [Answer 1](https://tio.run/nexus/python3#DchLDoMgFADAfU9h6Aa6IEE@2vQOXsC4QHmWl1QggIm3p2Z20/Ycj87b4n@4dnikmOvrkzKGSonopRL6ZgY1kplYDWJ/S7O5YVwJx@DgosXbXhuKIZ2VMg5hiw4oY9zD5fAL5d5ZqoUt7Dm19vgD "Python 3 – TIO Nexus"), [Answer 2](https://tio.run/nexus/python3#DYlbCoMwEEW3IunPTD8ENT5KxSV0A@KHmrEZ0BiSFARx7TZcOAfOvRe3b4kevV55SnizuwvPt3VsAogsL2RWxlW1bEQvxpKy5VVUs6qbSaRsFB3g9ZiXFbCxvwCYkpl3RYCYajoUf8nH2hdywAEfn/s@2w7iC22H13lFRSD@AQ "Python 3 – TIO Nexus"), [Answer 3](https://tio.run/nexus/python3#@59WlJ@rkJFYnJGTmaSQmVuQX1SiZV1QlJlXoqFkaGRsYmgKhGbmJhZK0UqJpqmGaZbGZskp5hZJSnqZeSmpFRrFGYlGpmYamXkFpSUamnqpecn5Kakampp6GakVKZnpqcVA0Whjk1jNWE1lv///1RWq1R/1bn7U1fyodx4A "Python 3 – TIO Nexus"), [Answer 4](https://tio.run/nexus/python3#LchLCsMgFEDRrQQ70Q6kRvNpSuoOuoEg5KOJQmMkz0Kgi7cZlDs53DTv25rZAezbjZlbw7bH6yPszkeMWM4FK87KStSoQ0Nh2Hzn5aSrekTUeW0ODHbIixI7Hz4RE2r8tGmDCaHWHNotBs7bcaGIIpdXStA@QUJ3U23bf3uZN39DL0XDG/YD "Python 3 – TIO Nexus"), [Answer 5](https://tio.run/nexus/python3#@59WlJ@rkJFYnJGTmaSQmVuQX1SiZV1QlJlXoqFkaGRsYmgKhGbmJhZK0UqJpqmGaZbGZskp5hZJSnqZeSmpFRrFGYlGpmYamXkFpSUamnqpecn5Kakampp6GakVKZnpqcVA0Whjk1jNWE1lv///41RqNOwVox91NT3q3RKrCWLoglg1MU62NdW1AA "Python 3 – TIO Nexus"), [Answer 6](https://tio.run/nexus/python3#DYvRCoMgFEB/Je4epkMCU6sx/IX9QPRgalMoCzUW7OObnLdzONcct7VyKrnFT5Vf9y3mx2uPPmQEtGGcikLb8R4GUMLS@clabbp@gtoHY0@UnGpEi3zYj4xwbYPejEUY186exn9sKnZgfMQjvr2vS6uM0tdn7VA6ppQjilaZxYfyEEooJvAD2RC4g2QEEkhOQIMUJeE/ "Python 3 – TIO Nexus"), [Answer 7](https://tio.run/nexus/python3#@59WlJ@rkJFYnJGTmaSQmVuQX1SiZV1QlJlXoqFkaGRsYmgKhGbmJhZK0UqJpqmGaZbGZskp5hZJSnqZeSmpFRrFGYlGpmYamXkFpSUamnqpecn5Kakampp6GakVKZnpqcVA0Whjk1jNWE1lv///41RqNOwVox91NT3q3RKrCWLoglg1MU62NdW1NTFJpgA "Python 3 – TIO Nexus"), [Answer 8](https://tio.run/nexus/python3#DYxbCsIwEEW3IvHDGQmF2KeUbsENiB9pMjUDbVqSFAUXX8Pl/Bw495jCupycjm7m8cTLtoZ07bfAPoFQt7JSdV7TVp14Cl2Tmu5lY2zbjaJgb@kL0elb3QD7bU@ABXmzWgLEwtHX8ptits@yeuELz4/jMMPHsXFgQAgpfplLJmaMwGGI@xhTgEDazuzzj1RSIfY80RwJZvLvlGOUJus/ "Python 3 – TIO Nexus"), [Answer 9](https://tio.run/nexus/python3#DchRCoMgAADQq4QbpGMEllnb7rALmINMS2GpqINg7uwt3t/b5@DWQo9Rv40ozOpdSJeHD8YmCHDdENweaEd6wMDYKjzfGjrJrhegMlaqDUY91i2FxvpPgqhSdnJSQYQqrTZpFhWPZQ3hiKPTc9/P@Td8M7uXnL14yfN1EPgP "Python 3 – TIO Nexus"), [Answer 10](https://tio.run/nexus/python3#TY1LCoMwFEW38kg7SAqVxhi1dAGddQMiaD7WQBNDPuCge7fiqNzZOXDuNoXFwjzG@WMEGOuXkC4PH4xLGNGSVZTvq5uqRR0auabTndVSNa1AhXFKrzjOY8lrbJzPCZNCO7kojQkpZr0q89Zxpx2retKT02vb9OoDxCxiCvB3gOCMD3VEAbGaT62SNy0QDFbxmO1X5gRXScuBAIXT8wc "Python 3 – TIO Nexus"), [Answer 11](https://tio.run/nexus/python3#DcjbCsIgAADQXxkOlsYybNcIYtB77F1sOHUpNB1qMOjj1zhvZ5u8mxPNg/6YMTHz4nw83hZvbISAXIqSVLu6KVtAAa8Uma5FLWTTjgAbK9UKg@aXqobGLt8IEVZWOKkgQlirVZq3CvvSomSIofS5bb0LJhpn6UNzz0VUPnTg9TsEoXqQp1nXpYxSkhPGznjohuF0J9kf "Python 3 – TIO Nexus"), [Answer 12](https://tio.run/nexus/python3#RYrRDkMwAEV/ZekWbfcgimKE/sGyd7GEKm1CCZZI5t/Ng2a5Lyfnnr2Zhv4iy1l2qrqofhym5Z6Mk9ILAsT1fEKPBaEfgRyUVJDm4QW8DqMK2ErXYkWzLF0aIKXHz4KwLTQfaoEwtqVYa9WK@bC55xe4wNfnvvM044znTpGmUEAWxCff4Lad@IaMGM2hZXG7E7pdZBY5zDfHC7LwHzFq@AuZa3iGR@/FJPkB "Python 3 – TIO Nexus"), or [this answer](https://tio.run/nexus/python3#vc1LDoMgFEDRrRg6gQ5IkI823UM3YBygPMtLKhCgibtHV2Hu7Exu23LcO2@L/@HS4Z5irs93yhgqJaKXSugrM6iRTMRqENtLmtUN40I4BgcHLd722lAM6V8p4xDW6IAyxj0cDr9QLp2kmtnMHp/W7v2d "Python 3 – TIO Nexus"). [Answer] # 24. [Zsh](https://www.zsh.org/) (language 11), 142 bytes My previous answer #18 in C still works unmodified for all the subsequent entries ([demo](https://tio.run/nexus/bash#xZTdbts2FMfv9RQs7VqiQ6ui9S1HlpN0Wbdkqbtu3VZZTmSKtgXYkifJSQrJN9tdgb7CXmJ7orxIR9nuR9YCBQYMgwDykEc64vmf3yENC9AHizCZ5TIFh4fgq6enb5dhnEgJKuk8zNrXLgTjEuSADac3S4gnvm3bAW7T3owVuTRBPermRUbnmXSN23yZ1MsFS2rXKouTYirBhxHEiUc92rl2kr5texqfDMXT@UR0jziqQ1Bv85b/XZhRCjopWETvjiVM0wwkIE5AqRBZ7qqbHohSwOg8BZ0ENBMAAewB@dEi6m13a3fC3grlYV@SEJIO@2hTbvjEB4QEEZTi3Zs/717/fvfmDyF3@7mX@0rgulflldd19nZ@xQ/JjyWMm5XkPfDvXv929@avANVGp7aq0bFblRuBhoWU38QFnUv5esJzlzIWRos4YRLCBBOEYQndLoYidFUMc@hqGFLo6tyFvhS9Gk10gbo385iHpxKEdbA6VB2oDoNc9/N/Rb14yhY5k3gpZgX/GGHKt4VmtRmVle@IgT8OxKDCowkR2O0qA7s4AJKuqhGdPwYETWnripOI3QKoGvrUiqjCJhBcLSM9Xy8rui5Ah5LuFQIENL4WhmkeF3Ga@CecnpAWLMsHcFyKOWVDiButwaAR@D4/YRA8ki8Hl5edPmnxFPucjq3yIhM9w9nbTbGq9uZY5JzsbSq2WlTeZda3FF6pvWMoeuaHlzhfe7sUeWX3di7uKtsTplm6BPMwny/iCYiXqzQr2jtmpY9UMDUL@jDUGZnaqkEj05pAeauIlM/Drm5IcbJaFxKSWULTiBcAyXN2G8UzlvNdX9UCFKDGhSD6gHMX7AqQDpxtBSifqzHd1qEio6hqCoXbl8qu5nSxZTgq1h0Nm6qjY8Pig6k5JtYcA5s23yeOhQ3T0TbI92VZLgI5Y9GaMknKeLlj5Pazdjymct3KJ/xsR4WkIKyglnKrnwZVRQSO1oLVLVJuE99T8I/8iWZDvEsZKqfu8OnyufFYY5c///TiCcR172vmwR605iV6aCqIU8g7@h5Zhq0RSzONbVhN7ZL7eHWHxez46SK7nj5@cWK9fHIOrtIVS/J8AThroDOJkzB7VU3CnBnanrs9drfC/3ZnfQD@h/Q98rXUg@cFjzR7vlrExQD2Lr7/sQmegWPgEwe45@BbDPSHQAUN0If4uzTyz7fyDRpYt7GqBu@apHVfQvPoCyqaivavhaxAxO9eRozYW4HGeicqKmssznDkc9SDUtn0dshIZy5Xs9abA//A5Vc3ivyz4ODgnoKRb1mBZzuRT4gdeHqbG1014GtVDzw@cq/pWJ3It416V@Nrjc@GEvCOJQf8dd0K2t1PWDr6shSxenvKVs/yo3Dx6pvr4tfhL@bLiwMwGr2XY9e/n1eEKJ9Kcr6ThO402SnifiQJ/Ywk9D@U5G8)). So let's mix it up a little. ``` typeset -A p p=("[\$^]*|'\[*" 1 '{*' 2 "' *" 3 '?=>*' 4 'c?[wt]*' 5 'e*' 6 'P*' 7 'f*' 8 'w*' 9 'm*' 10 'ty*' 11) echo ${p[(k)$1]:-1} #@<`w&X{ ``` The purpose of the comment at the end is to match the length of answers 21 and 23, and ensure that no single character of the sha256 or sha384 hashes is unique for every answer so far, using the characters checked by Lyth's C++ answers. ;-) This prints: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/18314), [5](https://codegolf.stackexchange.com/a/107341/18314), [7](https://codegolf.stackexchange.com/a/107350/18314), [9](https://codegolf.stackexchange.com/a/107370/18314), and [14](https://codegolf.stackexchange.com/a/107479/18314) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334/18314) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336/18314) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338/18314), [12](https://codegolf.stackexchange.com/a/107422/18314), and [15](https://codegolf.stackexchange.com/a/107495/18314) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346/18314) and [8](https://codegolf.stackexchange.com/a/107364/18314) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388/18314), [17](https://codegolf.stackexchange.com/a/107542/18314), [20](https://codegolf.stackexchange.com/a/107579/18314), and [22](https://codegolf.stackexchange.com/a/107818/18314) (Bash). * `7` with answers [11](https://codegolf.stackexchange.com/a/107403/18314) and [19](https://codegolf.stackexchange.com/a/107575/18314) (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443/18314) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511/18314) (Perl). * `10` with answers [18](https://codegolf.stackexchange.com/a/107567/18314), [21](https://codegolf.stackexchange.com/a/107817/18314), and [23](https://codegolf.stackexchange.com/a/107936/18314) (C/C++). * `11` with this answer (Zsh). [Try it online!](https://tio.run/nexus/zsh#tVXdkto2FL73UyiCIIk11MZ/2KxtNkm3abNNSNOmaYxZQBaLp2Co7f2rzU17l5m8Ql@ifaJ9kfQY2DTbZCYznel4RufTkXx8znc@WXySIw8tovav2RwdHpIvnx2Td/n1WmQiR60jtJbWLsXBsD4KmyUZBk2MVESKJkEdhAmCqYaI73rg0BHhfnCZh4ANRAQYE5EBGAuRGZguIpdgbESWYFQFkfy6AiqTBJ@vUL1YB/RnVldDp6VuUK1/OL5svCreQU4S3@U5Sc6y2zQlqTj0KGWMHnpsU2zAwMCYRFBBbt7@efPm95u3f0iZ62V@Fiih646Lsd9x9jgb@7qjOao0qpfUvxfcvPnt5u1fIatAq0Ll8IFbFpvq0zS7jHM@p9n5NMtTmopJtIgTQZmsyiqTcYHdjowJdjUZZ9jVZcyxa8AS@1z0cjg1JO5ezmMIzynGVbAqVBWoCsNc99NfZb14JhaZoAuRnOXwMpM5uKV6uRkWZeCQMBiFJCzl4VSVxNU6Rbs4CKsdTVcNeEyM6nS7FCeRuEJYM41ZN@KKmGI0XkZGdr4s@TkIgaudMYPO176SBqsszuNVEjycT9IJz0Wa9fGoIBkXAyzXGv1@LQwCyDAMv2if9k9PW57agBI97vMt80QQ33T2uE7Kcg9HxFdv3Zw0Gry9q8zrKtCp/cKA@NY/m3zjFhcEOrvHGdl1tifN0tUSzSfZfBFPUbxcr9K82VuncZLTD1iw9C4O8MQQ6szWTB5Z3Slubxmh2XzSMUwaJ@vznLK2SPgqggaw9lxcRfGZyMAbaHrIQlZ7KpEAge7CXQNWfWfbAQ62HPFtH0p1GJV1KXc9WnR0pyN3TUeTDUeXLc0xZLMLg6U7lqw7pmzZ4Fedrmxajr5hQdBut/OwnYronAtKU2h3zFwvbcYj3ubQjIeQ21FOFSYrrKFcGcdhWaoSSGshqiNSbAvfq@Bf9au6jeVdyVg5dgfPli/MR7o4ffXjy8dY5vOU6tbBXmj1U3bfUhiokPU2d5Rl2rra1S1zG1bXOupdeXUG@dmDZ4v0Yvbo5cPu68cnaLxaiyTLFgi0hlrTOJmk1@V0kglT3@tuL7sraTmJE5qwoiq0eeFiNCpQhsRgdrnE8jSwbTuUm7x3JvKMTlmPu5BQlfeF3IRpUk0h/2ppS8OM4vsRlhMfVNm6cBLPtkE0iWcqoKnEUw3QIkioqvC94L9fvZd8RXX/RQ6Rzl6sF3Hex72n3/1QR8/RAxSoDnJP0DcyMu7D37GGPCx/u4qCky19/Zps2LKmhbeHpHGXQuvoMyxaiv6fiSxRxFFLqGbsr1HtfEcqKypZPJGjAKQeFsqmt5MMfeICmxXfIPh7LvxyWRQ8CQ8O7jAYBd1u6NtOFKiqHfpGE0BHC2GuGaEPI6xaTrcVBbZZeXWY62BNJYQTqx7AdqMbNjsfaeno81TE2tWxWD/PjiaL668v8l8GP1mvnx6g4fA9Hbvz@2lGVOVjSk52lPAdJztG3A8o4Z@ghP@flFR332yVohmUjHC9oDOG6/RwexEyvMFStELV1b2/wXF9VrkSId1xwgtbyPC7vwE "Zsh – TIO Nexus") [Answer] ## 14. [Retina](https://github.com/m-ender/retina) (language 1), 39 bytes ``` '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$ ``` [Try it online!](https://tio.run/nexus/retina#jZJBjtowFIb3OYVrKLarwGBCgIZJgtrF7Cr2IZDEMRNLkKA4aJBiNu1uJK7QS7Qn4iLUAUbtolIrS/av9@zPfv/ze/wUXVAAzqcfoTouahUUMycMliFielVLpsxFQhVdpKp9uRj1o4cxIfjRI8f6qBc9EWIgUCNNOL9@O5@@G9L1pC@Dfui6UR35A@euZeQPHcuhxrKtsP8uOL9@PZ9@hqQR3UapxSdX1UeDxRWWL6JiGZb7RFYlLnmcbkTOMTGpSYkJa@gOTIiga5lQQndoQgZdW6fIv@hqkdgGc18yofEMQ9jAGlQDajDEdf9@K5mKNd9Ijjc8f670YWIyHTbaN@McdPUtvDpm8MOuBDcOgHRgDamtxwiCNr6mRJ7yA4DWyF5PUtbnCQTRNrXlfqvYvgJdRgcRARS0nox5IUUlijz4nMVlzCpeyhlc1kgyPodmqzObtcIg0C8Mw4fearZadT3a0SV6zGdX5xFH/si56zZS6i6XyKdvYYY6Hda7VeZN@rpT98Qc@ePfm3z7TddId/auJbp1dmqsy2ILslhmG5EAsd0VZfVhuitFXuE/XBgPJzCAsc3p@qM1Yul4ksDe1REss3hgj7DId/sKkx7PWZHqBpBexg@peOZSRwNrGJKQtL4Y//lzfwE "Retina – TIO Nexus") (Tests all valid inputs.) [Answer] # 15. Javascript (language 4), 108 bytes **Golfed** ``` t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1 ``` [Answer] # 17. Bash (+coreutils +openssl) (language 6), 103 bytes **Golfed** ``` expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x ``` Uses the same technique as my [answer #10](https://codegolf.stackexchange.com/a/107388/61904), but with *Base64* encoded dictionary, instead of *Hex*. I've put together the following data file for testing: ``` 6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x 9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);} 4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1 1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$ 8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N 4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1; 7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1& 6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G 1 09 $|}\{|[:'][^]']|,\b1 5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1) 1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5 5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} 4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 3 03 ' {'⍳⊃⍞ 2 02 {<>(())(<>)}{}(<>{}()) 1 01 ``` **Test** ``` for i in `seq 17` do echo -n `cat lchain|sed -n $i'{p;q}'|cut -c1`=\> cat lchain|sed -n $i'{p;q}'|cut -c6-|\ expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x done 6=>6 9=>9 4=>4 1=>1 8=>8 4=>4 7=>7 6=>6 1=>1 5=>5 1=>1 5=>5 1=>1 4=>4 3=>3 2=>2 1=>1 ``` [Answer] # 19. Mathematica (language 7), 96 bytes ``` Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]& ``` Unnamed function taking a list of characters as input and returning an integer: * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/), [5](https://codegolf.stackexchange.com/a/107341), [7](https://codegolf.stackexchange.com/a/107350), [9](https://codegolf.stackexchange.com/a/107370), and [14](https://codegolf.stackexchange.com/a/107479) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338), [12](https://codegolf.stackexchange.com/a/107422), and [15](https://codegolf.stackexchange.com/a/107495) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346) and [8](https://codegolf.stackexchange.com/a/107364) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388) and [17](https://codegolf.stackexchange.com/a/107542) (Bash). * `7` with answer [11](https://codegolf.stackexchange.com/a/107403) and this answer (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511) (Perl). * `10` with answer [18](https://codegolf.stackexchange.com/a/107567/56178) (C). So far all the lengths of answers are distinct, and they're even distinct modulo 59—hence can be detected by which integer in the range 33, 34, ..., 91 they're congruent to (mod 59). These are all printable ASCII characters, encoded by the string `";NRU$ Q B [1: =L J, 5% 3 # >"`; using `ToCharacterCode@StringSplit@` turns this string into a list of ten lists of integers in that range, and `Position[...,Mod[Length@#,59,33]][[1,1]]` finds which of the ten sublists matches the modified length of the input. [Answer] # 20. Bash (+coreutils +openssl) (language 6), 121 byte **Golfed** ``` expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u ``` The same method as my answer [#17](https://codegolf.stackexchange.com/a/107542/61904) (which in turn is based on my original answer [#10](https://codegolf.stackexchange.com/a/107388/61904)). As we have 10 distinct languages now, I've switched to hexadecimal position encoding. **Data** ``` 6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u 7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]& A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);} 6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x 9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);} 4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1 1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$ 8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N 4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1; 7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1& 6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G 1 09 $|}\{|[:'][^]']|,\b1 5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1) 1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5 5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} 4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 3 03 ' {'⍳⊃⍞ 2 02 {<>(())(<>)}{}(<>{}()) 1 01 ``` **Test (output)** ``` ./test 6=>6 7=>7 A=>10 6=>6 9=>9 4=>4 1=>1 8=>8 4=>4 7=>7 6=>6 1=>1 5=>5 1=>1 5=>5 1=>1 4=>4 3=>3 2=>2 ``` [Answer] # 23. [C (gcc)](https://gcc.gnu.org/) (language 10), 142 bytes ``` main(c){int d[256]={0};while((c=getchar())!=EOF)d[c]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);} ``` [Try it online!](https://tio.run/nexus/c-gcc#zU5LDoIwEL0KakxaUAOFYgGxK916gGYWpIPSBNEgxgXh7Djews37ziRv5TrbvrH2Dq8B3WPXHOd75Tpm@ei6wUMjZArlGE7Fp3FtzZgtb/Vgm6pnnC/K0@XM0VgIguLZ08OVLde43KBRCnSWo4miDLT0SYgYyMcSNCG1@1xt0WTpL03IJ8RpCFrkUUDnUoEveDHNf7bnCw "C (gcc) – TIO Nexus") * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/), [5](https://codegolf.stackexchange.com/a/107341), [7](https://codegolf.stackexchange.com/a/107350), [9](https://codegolf.stackexchange.com/a/107370), and [14](https://codegolf.stackexchange.com/a/107479) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338), [12](https://codegolf.stackexchange.com/a/107422), and [15](https://codegolf.stackexchange.com/a/107495) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346) and [8](https://codegolf.stackexchange.com/a/107364) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388), [17](https://codegolf.stackexchange.com/a/107542), [20](https://codegolf.stackexchange.com/a/107579) and [22](https://codegolf.stackexchange.com/a/107818) (Bash). * `7` with answer [11](https://codegolf.stackexchange.com/a/107403) and [19](https://codegolf.stackexchange.com/a/107575) (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511) (Perl). * `10` with answer [18](https://codegolf.stackexchange.com/a/107567), [21](https://codegolf.stackexchange.com/a/107817) and this answer (C). This program counts number of different characters (in ASCII, so multi-byte UTF-8 characters get split into several entries) and then follows a carefully designed decision tree, basing on the number of occurrences of this or that character. The decision tree is unchanged from #21 (yay!). I'm not allowed to post exactly same code, so we're back to pure C with minor modifications. [Answer] # 21. [C++ (gcc)](https://gcc.gnu.org/) (language 10 as a variant of C), 142 bytes ``` main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);} ``` [Try it online!](https://tio.run/nexus/cpp-gcc#FUtLDoIwEL0KYkxaUAOFYgGxK92w8ADNLAiD0gTRIMYF4ew4bt7/rW1fdx9snON7RPvct6flUdme8cn2o1Nu0QiZwBTM@be1XcNYWdybsW6rgXG@Ks7XC0dTgu/nr4EeN@Zu0KWXUqDTDE0YpqClR0JEQD6SoAmpPWRqhyZN/mlMPiZOAtAiC32aSwWe4Pm8LD8 "C++ (gcc) – TIO Nexus") * `1` with answers [1](https://codegolf.stackexchange.com/a/107333/), [5](https://codegolf.stackexchange.com/a/107341), [7](https://codegolf.stackexchange.com/a/107350), [9](https://codegolf.stackexchange.com/a/107370), and [14](https://codegolf.stackexchange.com/a/107479) (Retina). * `2` with answer [2](https://codegolf.stackexchange.com/a/107334) (Brain-Flak). * `3` with answer [3](https://codegolf.stackexchange.com/a/107336) (APL). * `4` with answers [4](https://codegolf.stackexchange.com/a/107338), [12](https://codegolf.stackexchange.com/a/107422), and [15](https://codegolf.stackexchange.com/a/107495) (Javascript). * `5` with answers [6](https://codegolf.stackexchange.com/a/107346) and [8](https://codegolf.stackexchange.com/a/107364) (R). * `6` with answers [10](https://codegolf.stackexchange.com/a/107388), [17](https://codegolf.stackexchange.com/a/107542) and [20](https://codegolf.stackexchange.com/a/107579) (Bash). * `7` with answer [11](https://codegolf.stackexchange.com/a/107403) and [19](https://codegolf.stackexchange.com/a/107575) (Mathematica). * `8` with answer [13](https://codegolf.stackexchange.com/a/107443) (Python). * `9` with answer [16](https://codegolf.stackexchange.com/a/107511) (Perl). * `10` with answer [18](https://codegolf.stackexchange.com/a/107567/56178) and this answer (C). This program counts number of different characters (in ASCII, so multi-byte UTF-8 characters get split into several entries) and then follows a carefully designed decision tree, basing on the number of occurrences of this or that character. **Trivia**: letter K was not used until this entry. Letters I, E, Y, j, k, q, z remain unused. [Answer] # 22. Bash (+coreutils) [language 6], ~~123~~, 131 bytes EDIT: Published a wrong version at first, should be fixed now. **Golfed** ``` expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L ``` The same technique as my answers #20, #17 and [#10](https://codegolf.stackexchange.com/a/107388/61904). **Data** ``` 6 22 expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L A 21 main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);} 6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u 7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]& A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);} 6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x 9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);} 4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1 1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$ 8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N 4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1; 7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1& 6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G 1 09 $|}\{|[:'][^]']|,\b1 5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1) 1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5 5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} 4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 3 03 ' {'⍳⊃⍞ 2 02 {<>(())(<>)}{}(<>{}()) 1 01 ``` **Test Run** ``` ./test 6=>6 A=>10 6=>6 7=>7 A=>10 6=>6 9=>9 4=>4 1=>1 8=>8 4=>4 7=>7 6=>6 1=>1 5=>5 1=>1 5=>5 1=>1 4=>4 3=>3 2=>2 1=>1 ``` [Answer] # 25. Bash (language 6), 169 bytes The same technique as my answers #22, #20, #17 and [#10](https://codegolf.stackexchange.com/a/107388/61904). Sorry @Qwerp-Derp ! ;) I promise this is the last one :) **Golfed** ``` { echo -n 'addsomesalt?';cat; }|expr substr 6BA6A67A69418476151514321 $(expr index 1W0TC4YrKwRGAJupDqn7Xlcog \\`openssl sha256 -binary|base64|cut -c40`) 1| dc -e16i?p #8 ``` **Data** > > Note that newlines are encoded as \n for answer #24 > > > ``` 6 25 { echo -n 'addsomesalt?';cat; }|expr substr 6BA6A67A69418476151514321 $(expr index 1W0TC4YrKwRGAJupDqn7Xlcog \\`openssl sha256 -binary|base64|cut -c40`) 1| dc -e16i?p #8 B 24 typeset -A p\np=("[\$^]*|'\[*" 1 '{*' 2 "' *" 3 '?=>*' 4 'c?[wt]*' 5 'e*' 6 'P*' 7 'f*' 8 'w*' 9 'm*' 10 'ty*' 11)\necho ${p[(k)$1]:-1} #@<`w&X{ A 23 main(c){int d[256]={0};while((c=getchar())!=EOF)d[c]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);} 6 22 expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L A 21 main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);} 6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u 7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]& A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);} 6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x 9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);} 4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1 1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$ 8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N 4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1; 7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1& 6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G 1 09 $|}\{|[:'][^]']|,\b1 5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1) 1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5 5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1)) 1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{} 4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1 3 03 ' {'⍳⊃⍞ 2 02 {<>(())(<>)}{}(<>{}()) 1 01 ``` **Test Output** ``` 6=>6 B=>11 A=>10 6=>6 A=>10 6=>6 7=>7 A=>10 6=>6 9=>9 4=>4 1=>1 8=>8 4=>4 7=>7 6=>6 1=>1 5=>5 1=>1 5=>5 1=>1 4=>4 3=>3 2=>2 1=>1 ``` ]
[Question] [ ## The task This challenge is very simple. Your input is a rectangular 2D array of integers, sized at least 1×1. It can be taken in any reasonable format. Your output shall be the input array, but with all entries *not* on the first or last row or column set to `0`. It must be in the same format as the input. For example, if the input array is ``` 67 4 -8 5 13 9 13 42 4 -7 1 1 3 -9 29 16 99 8 77 0 ``` then the correct output is ``` 67 4 -8 5 13 9 0 0 0 -7 1 0 0 0 29 16 99 8 77 0 ``` ## Rules and scoring You can write a full program or a function, and functions are allowed to modify the input in place instead of returning it. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases These are formatted as nested lists to make copy-pasting easier. ``` [[3]] -> [[3]] [[7,2,8]] -> [[7,2,8]] [[3],[5],[12],[-6]] -> [[3],[5],[12],[-6]] [[99,98,97],[88,87,86]] -> [[99,98,97],[88,87,86]] [[6,7],[8,9],[10,11]] -> [[6,7],[8,9],[10,11]] [[-1,-2,-3],[1,2,3],[5,5,5]] -> [[-1,-2,-3],[1,0,3],[5,5,5]] [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] -> [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]] [[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] -> [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]] ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` If you want to include multiple numbers (e.g. because you've improved your score or you want to list interpreter flags separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, <s>50</s> 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=71591,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes ``` 0HJ_ht4$( ``` Input is in the format ``` [67 4 -8 5 13; 9 13 42 4 -7; 1 1 3 -9 29; 16 99 8 77 0] ``` *EDIT (June 12, 2016): to adapt to changes in the language, the link below has `_` replaced by `q`*. [**Try it online**!](http://matl.tryitonline.net/#code=MEhKcWh0NCQo&input=WzY3ICA0IC04ICA1IDEzOyAgOSAxMyA0MiAgNCAtNzsgIDEgIDEgIDMgLTkgMjk7IDE2IDk5ICA4IDc3ICAwXQ) ``` 0 % Push a 0: value that will be assigned into the array HJ_h % Vector [2, -1j]: this corresponds to index 2:end-1 for rows t % Duplicate: same index for columns 4$( % Assignment indexing with 4 inputs: array, new value, row and col indices % Since the first input (array) to this function is currently missing, it's % implicitly taken at this point from stdin % Implicitly display stack contents, which is the modified array ``` [Answer] # Jelly, ~~18~~ ~~17~~ ~~15~~ 9 bytes ``` 0W&ṖZ ÇÇ^ ``` [Try it online!](http://jelly.tryitonline.net/#code=MFdh4bmWWgrDh8OHXg&input=&args=W1s2Nyw0LC04LDUsMTNdLFs5LDEzLDQyLDQsLTddLFsxLDEsMywtOSwyOV0sWzE2LDk5LDgsNzcsMF1d) or [verify all test cases](http://jelly.tryitonline.net/#code=MFcm4bmWWgrDh8OHXgpbWzNdXSxbWzcsMiw4XV0sW1szXSxbNV0sWzEyXSxbLTZdXSxbWzk5LDk4LDk3XSxbODgsODcsODZdXSxbWzYsN10sWzgsOV0sWzEwLDExXV0sW1stMSwtMiwtM10sWzEsMiwzXSxbNSw1LDVdXSxbWzY3LDQsLTgsNSwxM10sWzksMTMsNDIsNCwtN10sWzEsMSwzLC05LDI5XSxbMTYsOTksOCw3NywwXV0sW1swLDEsMCwxLDBdLFsxLDAsMSwwLDFdLFswLDEsMCwxLDBdLFsxLDAsMSwwLDFdLFswLDEsMCwxLDBdXcOH4oKs4bmE4oKs4bmb4oG2&input=). ### Background This approach is based on [@Sp3000's Jelly answer](https://codegolf.stackexchange.com/a/71627), specifically on his idea to take advantage of vectorized operations between lists of different lengths. We start by taking the bitwise AND of **0** and every integer in the first row of the input. Due to automatic vectorization, this can be achieved by taking the bitwise AND of **[0]** and the input without its last row. **0** is paired with the first row, resulting in a row of zeroes. Since the remaining rows have no counterpart in **[0]**, they are left untouched. Now we transpose the result, apply the above transformation once again (effectively removing the last column and zeroing out the first), and transpose again. For the input ``` 67 4 -8 5 13 9 13 42 4 -7 1 1 3 -9 29 16 99 8 77 0 ``` this results in ``` 0 0 0 0 0 13 42 4 0 1 3 -9 ``` Now, we take the bitwise XOR of this result and the original matrix. XORing an integer with itself yields **0**. XORing an integer with **0** (or not XORing it at all) yields the same integer. This hollows the matrix out. ### How it works ``` 0W&ṖZ Helper link. Argument: M (matrix) 0W Yield [0]. Ṗ Yield M, without its last row. & Take the bitwise AND of both. Z Zip the result. ÇÇ^ Main link. Input: A (matrix) Ç Call the helper link on A. Ç Call the helper link on the result. ^ Take the bitwise XOR of the result and A. ``` [Answer] ## Java 7, as a fully named function: 85 ``` void f(int[][]a){for(int i=0,j;++i<a.length-1;)for(j=1;j<a[i].length-1;)a[i][j++]=0;} ``` You could lambda this down in Java 8 to remove a few bytes, but I don't really do that. [Answer] ## Mathematica, 27 bytes ``` (a=#;a[[2;;-2,2;;-2]]=0;a)& ``` [Answer] ## [R](https://www.r-project.org/), ~~33~~ 48 bytes I know, R isn't made for golfing. But it is made for positional indexing... Loading up an example; ``` a <- matrix(c(67,4,-8,5,13,9,13,42,4,-7,1,1,3,-9,29,16,99,8,77,0), ncol=5, byrow=TRUE) a # [,1] [,2] [,3] [,4] [,5] # [1,] 67 4 -8 5 13 # [2,] 9 13 42 4 -7 # [3,] 1 1 3 -9 29 # [4,] 16 99 8 77 0 ``` Replace the value at any position not on the edge row or column, with 0: ``` x <- function(a){a[-c(1,nrow(a)),-c(1,ncol(a))]<-0;a} x(a) # [,1] [,2] [,3] [,4] [,5] # [1,] 67 4 -8 5 13 # [2,] 9 0 0 0 -7 # [3,] 1 0 0 0 29 # [4,] 16 99 8 77 0 ``` Also checking a 2-column test: ``` b <- matrix(c(99,98,97,88,87,86), ncol=2, byrow=TRUE) b # [,1] [,2] #[1,] 99 98 #[2,] 97 88 #[3,] 87 86 x(b) # [,1] [,2] #[1,] 99 98 #[2,] 97 88 #[3,] 87 86 ``` Posterity: previous attempt ``` # a[2:(nrow(a)-1),2:(ncol(a)-1)]<-0 # previous attempt ``` Testing all examples: ``` tests <- read.table(text="[[3]] -> [[3]] [[7,2,8]] -> [[7,2,8]] [[3],[5],[12],[-6]] -> [[3],[5],[12],[-6]] [[99,98,97],[88,87,86]] -> [[99,98,97],[88,87,86]] [[6,7],[8,9],[10,11]] -> [[6,7],[8,9],[10,11]] [[-1,-2,-3],[1,2,3],[5,5,5]] -> [[-1,-2,-3],[1,0,3],[5,5,5]] [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] -> [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]] [[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] -> [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]]") tests$cols <- c(1,3,1,3,2,3,5,5) tests$V1 <- gsub("\\[|\\]","",tests$V1) tests$V1 <- paste0("c(",tests$V1,")") tests$V3 <- gsub("\\[|\\]","",tests$V3) tests$V3 <- paste0("c(",tests$V3,")") testfn <- function(testno) { intest <- matrix(eval(parse(text=tests$V1[testno])), ncol=tests$cols[testno], byrow=TRUE) intest <- x(intest) outtest <- matrix(eval(parse(text=tests$V3[testno])), ncol=tests$cols[testno], byrow=TRUE) return(identical(intest, outtest)) } sapply(seq_len(nrow(tests)), testfn) # [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE ``` [Answer] # GNU Sed, 31 * Thanks to @manatwork for saving 4 bytes. Version 4.2.2 or earlier, prior to [this commit](http://git.savannah.gnu.org/cgit/sed.git/commit/?id=31c84cbcfd2516e278a2a75523c7d5ad78f7bc57) [(discussion)](https://lists.gnu.org/archive/html/bug-sed/2015-08/msg00002.html). Score includes +1 for `-r` option. Input rows are newline separated. Elements on each row are single-line separated. ``` 1n $n : s/ -?\w+ / : / t y/:/0/ ``` ### Explanation ``` 1n # 1st line: print unchanged, then load next line $n # last line: print unchanged, then load next line (i.e. EOF and stop) : # unnamed label s/ -?\w+ / : / # substitute a number in spaces with a `:` in spaces t # If the above matched, jump back to the label and try again y/:/0/; # transliterate `:` to `0` ``` [Try it online.](https://ideone.com/RiitEF) [Answer] # Octave, 34 bytes ``` function h(M) M(2:end-1,2:end-1)=0 ``` Note that the input requires semicolons to separate array rows: ``` h([[3];[5];[12];[-6]]) ``` ### Explanation: Octave (and MATLAB) array indices are 1-based. Specifying a range of `Array(1:end)` will give you all elements of the (one-dimensional, in this example) array. `Array(2:end-1)` will give you all of the elements *except* the first and last. ``` M(2:end-1,2:end-1)=0 ``` sets to `0` all elements not in the first or last row or column: ``` >> A = [[-1,-2,-3];[1,2,3];[5,5,5]] A = -1 -2 -3 1 2 3 5 5 5 >> h(A) M = -1 -2 -3 1 0 3 5 5 5 ``` If one of the dimensions is less than or equal to 2, the range `end-1` is **less** than 2, therefore the end of the range `(2:end-1)` is less than the beginning. In this case, Octave ignores the range and does nothing. This is analogous to the `for` loop: ``` for (int i=2; i < 2; i++) {...} ``` The stop condition is true on the first iteration, so we fall out of the loop. ``` >> A = [[6,7];[8,9];[10,11]] A = 6 7 8 9 10 11 >> h(A) M = 6 7 8 9 10 11 ``` [Answer] ## [Jelly](http://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` ZṖṖ1;¥€ ¬ÇÇ× ``` I think this works, still wrapping my head around Jelly. [Try it online!](http://jelly.tryitonline.net/#code=WuG5luG5ljE7wqXigqwKwqzDh8OHw5c&input=&args=W1s2Nyw0LC04LDUsMTNdLFs5LDEzLDQyLDQsLTddLFsxLDEsMywtOSwyOV0sWzE2LDk5LDgsNzcsMF1d) *(Thanks to @Dennis for -2 bytes)* Works by multiplying the input array by an arrays of 1s and 0s one dimension smaller each way. For example, for `[[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]]` we multiply element-wise by ``` 1 1 1 1 1 0 0 0 1 0 0 0 ``` ### Full explanation ``` [Helper link - argument is a matrix] Z Zip ṖṖ Pop last two elements, or [:-2] 1;¥€ Append a 1 in front of every row [Main link] ¬ Not, turning 0s to 1s and everything else to 0s. Even though some zeroes turn into 1s, it's fine because we multiply element-wise at the end, and 0*1 = 0 ÇÇ Perform helper link twice × Multiply element-wise ``` [Answer] # Mathematica ~~81~~ 76 bytes ``` (d=Dimensions@m;q=MemberQ;m Boole@Array[{1,d[[1]]}~q~#||{1,d[[2]]}~q~#2&,d])& ``` --- ## How it works Assume that the input array is stored in `m`. The dimensions of `m` are {4,5}` ``` (m={{67,4,-8,5,13}, {9,13,42,4,-7}, {1,1,3,-9,29}, {16,99,8,77,0}})//MatrixForm ``` [![m](https://i.stack.imgur.com/mNH3y.png)](https://i.stack.imgur.com/mNH3y.png) --- Each cell in the following array, `a`, is True if the cell is either in the first or (`||`) in last row or in the first or last column; otherwise it is False. ``` (d=Dimensions@m;a=Array[MemberQ[{1,d[[1]]},#]||MemberQ[{1,d[[2]]},#2]&,d])&[m]//MatrixForm ``` [![true](https://i.stack.imgur.com/Jaz3M.png)](https://i.stack.imgur.com/Jaz3M.png) --- Applying the function `Boole` to the array converts True to 1 and False to 0. ``` b = Boole[a] ``` [![boole](https://i.stack.imgur.com/gJLLM.png)](https://i.stack.imgur.com/gJLLM.png) --- Multiply the matrix `m` by `b`. This multiplies each cell in m by the corresponding cell in b. ``` m b ``` [![hollow matrix](https://i.stack.imgur.com/63eKh.png)](https://i.stack.imgur.com/63eKh.png) [Answer] ## ES6, ~~52~~ ~~48~~ 46 bytes ``` f=a=>a.map((b,i)=>i&&a[i+1]+.5?b.map?f(b):0:b) ``` Edit: Saved 4 bytes thanks to @user81655. Saved a further 2 bytes thanks to @ETHproductions. [Answer] # Javascript, ~~62~~ ~~59~~ 56 bytes ``` s=>s.replace(/(^.*|\n\s*\S+)|\S+(?= .*\n)/g,(a,b)=>b||0) ``` This approach expects an string as argument. You can see what the regex do here: <https://regex101.com/r/kC6xA8/3> [Answer] # Mathematica, 55 bytes ``` #-Unitize@ArrayFilter[Det,Power~Array~Dimensions@#,1]#& ``` --- **Test case** ``` %[RandomInteger[9,{5,5}]] (* {{8,8,3,6,5}, {7,0,0,0,4}, {2,0,0,0,7}, {3,0,0,0,5}, {8,6,1,0,8}} *) ``` --- **Explanation** The main idea of this answer is the same as [DavidC's answer](https://codegolf.stackexchange.com/a/71609/36748) (first construct a mask matrix, and then multiply it to the original matrix), but the construction of mask matrix is different. `ArrayFilter[f,list,r]` maps `f` onto every element of `list` within a radius of `r`. ``` ArrayFilter[f,{1,2,3,4,5},1] (* { f[{1,1,2}], f[{1,2,3}], f[{2,3,4}], f[{3,4,5}], f[{4,5,5}] } *) ``` Note that boundary elements are duplicated where there are insufficient neighbors. When `list` is of 2-dimensions, this feature works well together with `Det` to give the desired result, since duplicated columns or rows on four boundaries vanish the determinants. ``` ArrayFilter[Det,Power~Array~{4,4},1] (* {{0, 0, 0, 0}, {0, 12, 72, 0}, {0, 48, 1152, 0}, {0, 0, 0, 0}} *) ``` where `Power~Array~{4,4}` guarantees the determinants on inner positions to be non-zero. And ``` 1-Unitize@% (* {{1,1,1,1}, {1,0,0,1}, {1,0,0,1}, {1,1,1,1}} *) ``` gives the mask matrix. [Answer] ## Python, 50 bytes ``` def f(a): for l in a[1:-1]:l[1:-1]=[0]*(len(l)-2) ``` Accepts a list of lists, and modifies it in place. Python's slice syntax is not inconvenient for this task. I learned that multiplying a list by a negative number results in an empty list, which allows the above code to work on small inputs. [Answer] # Julia, ~~50~~ 35 bytes ``` A->A[2:size(A,1)-1,2:size(A,2)-1]=0 ``` This is an anonymous function that accepts an array and modifies it in place. To call it, assign it to a variable. The approach here is quite simple: For the *n* by *m* input array *A*, we assign *A**ij* = 0 for all *i* = 2, ..., *n*-1 and *j* = 2, ..., *m*-1 by constructing ranges of indices. The ranges may be empty, like if *n* or *m* = 1, in which case no replacement is done. [Try it online](http://goo.gl/UvXZgz) Saved 15 bytes thanks to Dennis! [Answer] ## C, 62 bytes ``` y;f(a,b,c)int **a;{for(b--;b-->1;)for(y=1;y<c-1;)a[b][y++]=0;} ``` Hope it's ok to take in array length/width as parameters. I played around with memset/bzero a little bit, but multiplying by `sizeof(int)` drastically increased the code size. EDIT: 55 bytes if we can further bend the rules and store our array as characters since the input is only a single digit each. ``` x; #define f(a,b,c) for(x=1;x<b-1;)bzero(a[x++]+1,c-2); ``` EDIT: Thanks Washington Guedes for the tip! [Answer] # [Perl 6](http://perl6.org), 28 bytes ``` {.[1..*-2]»[1..*-2] »=»0} ``` This modifies the input in-place ### Usage ``` my @test-cases = ( [[3],] => [[3],], [[7,2,8],] => [[7,2,8],], [[3],[5],[12],[-6]] => [[3],[5],[12],[-6]], [[99,98,97],[88,87,86]] => [[99,98,97],[88,87,86]], [[6,7],[8,9],[10,11]] => [[6,7],[8,9],[10,11]], [[ -1,-2,-3],[1,2,3],[5,5,5]] => [[ -1,-2,-3],[1,0,3],[5,5,5]], [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] => [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]], [[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] => [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]], ); use Test; plan +@test-cases; for @test-cases { my $k = .key; {.[1..*-2]»[1..*-2] »=»0}( $k ); # <== ok $k eqv .value } ``` ``` 1..8 ok 1 - ok 2 - ok 3 - ok 4 - ok 5 - ok 6 - ok 7 - ok 8 - ``` [Answer] # JavaScript ES6, ~~69~~ ~~66~~ 57 bytes ``` Y=>Y.map((X,y)=>X.map((N,x)=>x*y&&X[x+1]+.5&&Y[y+1]?0:N)) ``` ### How it works This solution maps through each y-index `y` and x-index `x` in the input and decides whether or not to throw it out based on these two indices. There are four cases which we need to keep: * `x` is 0 * `y` is 0 * `x` equals the length of the inner array, minus 1 * `y` equals the length of the outer array, minus 1 We can take care of the first two with a little multiplication: `x*y` returns `0` iff either `x` or `y` are 0, and a positive integer otherwise. Now for the third: we could check if `X.length>x+1`, but that takes a lot of bytes. Another way to do this is to check if the item ahead is falsy, namely `undefined`, which is what you get when trying to access a non-existent item. However, this also matches if the next item is `0`, so we add 0.5 to make sure that doesn't happen: ``` 1 + 0.5 = 1.5 (truthy) 0 + 0.5 = 0.5 (truthy) -1 + 0.5 = -0.5 (truthy) undefined + 0.5 = NaN (falsy) ``` Finally, the fourth point: since the outer array has only arrays inside, and any array is truthy, we can just check `Y[y+1]`. Now with `?0:N`, we convert it to `0` if all of the above turned out truthy; `N` otherwise. And that's it! [Answer] # [Retina](https://github.com/mbuettner/retina), ~~31 24~~ 22 ``` (?<=¶.+ )\S+(?= .*¶) 0 ``` Saved 2 bytes thanks to randomra [Try it online!](http://retina.tryitonline.net/#code=KD88PcK2LisgKVxTKyg_PSAuKsK2KQow&input=NjcgNCAtOCA1IDEzCjkgMTMgNDIgNCAtNwoxMSAxIDMgLTkgMjkKMTYgOTkgOCA3NyAw) There is probably a better way to do it, as this is just a pretty basic multi-line replacement. Essentially we find each number that is preceded by a newline, some number of characters and a space, and is immediately followed by a space and then and is eventually followed by a newline. These numbers are then all replaced with `0`. This will not preserve column padding, but I don't think that's a problem. [Answer] # Java 8, as a lambda function: ~~82~~ ~~83~~ 95 chars/bytes Lambda Signature: `int[][] -> (void)` (i.e. `Consumer<int[][]>`) ``` (a)->{int[]v={1,1};while(++v[0]<a.length){while(++v[1]<a[0].length)a[v[0]-1][v[1]-1]=0;v[1]=1}} ``` **EDIT** Made a mistake, I thought that a[x, y] was the xth row and the yth col. Clearly it should be a[x][y] though! **EDIT** I forgot to test the code, and I need to set the column back to zero every time inside the loop, +12 bytes. :/ [Answer] ## Haskell, ~~59~~ 58 bytes ``` k _[x]=[x] k f(x:y)=x:(f<$>init y)++[last y] f=k(k(\_->0)) ``` ### Expanded ``` onInner :: (a -> a) -> [a] -> [a] onInner _ [x] = [x] onInner f (x:xs) = x : map f (init xs) ++ [last xs] hollowOut :: [[Int]] -> [[Int]] hollowOut = onInner -- leave first and last line alone (onInner -- leave first and last entry per line (const 0) -- replace entries by 0 ) ``` [Answer] ## Pyth, 18 bytes ``` Qjbm:dSttld0P.Qe.Q ``` Explanation ``` - autoassign Q=eval(input()) - autoassign .Q = map(eval, rest_of_input) Q - imp_print(Q) m P.Q - [V for d in .Q[:-1]] Sttld - range(1, len(d)-2+1) :d 0 - assign_indexes(d, ^, 0) jb - "\n".join(^) e.Q - imp_print(.Q[-1]) ``` Input arrays are separated by newlines [Try it here](http://pyth.herokuapp.com/?code=Qjbm%3AdSttld0P.Qe.Q&input=%5B67%2C4%2C-8%2C5%2C13%5D%0A%5B9%2C13%2C42%2C4%2C-7%5D%0A%5B1%2C1%2C3%2C-9%2C29%5D%0A%5B16%2C99%2C8%2C77%2C0%5D&debug=0) [Answer] # Groovy, 70 bytes This isn't very creative, but it's short! ``` g={a->for(i=1;i<a.size()-1;i++)for(j=1;j<a[i].size()-1;)a[i][j++]=0;a} ``` ## Explanation Closure with one arg ``` g={a-> ``` Iterate over the inner array, skipping the first and last elements ``` for(i=1;i<a.size()-1;i++) ``` Iterate over middle items in the inner array ``` for(j=1;j<a[i].size()-1;) ``` Set the elements to `0` and return `a` ``` a[i][j++]=0;a} ``` ## Tests ``` assert g([[3]]) == [[3]] assert g([[7, 2, 8]]) == [[7, 2, 8]] assert g([[3], [5], [12], [-6]]) == [[3], [5], [12], [-6]] assert g([[99, 98, 97], [88, 87, 86]]) == [[99, 98, 97], [88, 87, 86]] assert g([[6, 7], [8, 9], [10, 11]]) == [[6, 7], [8, 9], [10, 11]] assert g([[-1, -2, -3], [1, 2, 3], [5, 5, 5]]) == [[-1, -2, -3], [1, 0, 3], [5, 5, 5]] assert g([[67, 4, -8, 5, 13], [9, 13, 42, 4, -7], [1, 1, 3, -9, 29], [16, 99, 8, 77, 0]]) == [[67, 4, -8, 5, 13], [9, 0, 0, 0, -7], [1, 0, 0, 0, 29], [16, 99, 8, 77, 0]] assert g([[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]) == [[0, 1, 0, 1, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1], [0, 1, 0, 1, 0]] ``` [Answer] # R, ~~71~~ ~~64~~ 57 Bytes ``` function(m){if(all((y<-dim(m)-1)>1))m[2:y[1],2:y[2]]=0;m} ``` *edit* -7 bytes by explicitly dealing with <2-row or <2-column matrices explicitly *edit2* -7 bytes by assigning dimensions of matrix while checking the size [Answer] ## C++, ~~80~~ 79 bytes Expects the array as `int**` with given sizes `n` and `k`: ``` void p(int**c,int n,int k){for(int j,i=1;1+i<n;++i)for(j=1;j+1<k;)c[i][j++]=0;} ``` An alternative that works for any type that has `size()` and `value_type & operator[](int)` (98 bytes): ``` template<class C>void p(C&c){for(int j,i=1;1+i<c.size();++i)for(j=1;j+1<c[i].size();)c[i][j++]=0;} ``` ### Expanded version ``` template <class Container> void hollowOut(Container & ctn){ const auto size = ctn.size(); for(typename Container::size_type i = 1; i + 1 < size; ++i) { const auto inner_size = ctn[i].size(); for(decltype(inner_size) j = 1; j + 1 < inner_size; ++j) { ctn[i][j] = 0; } } } ``` [Answer] ## PHP, ~~82~~ ~~81~~ ~~80~~ 71 bytes ``` function(&$z){for(;$z[++$i+1];)for(;0 .$z[0][++$$i+1];)$z[$i][$$i]=0;}; ``` Run like this: ``` php -r '$f = function(&$z){for(;$z[++$i+1];)for(;0 .$z[0][++$$i+1];)$z[$i][$$i]=0;}; $z=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; $f($z); print_r($z);' ``` * Saved a byte by assuming constant size rows (thx to manatwork) * Saved a byte by making it an anonymous function * Saved 7 bytes by using truthyness of next array item, preventing calls to `count`, which is a way too long name for codegolf [Answer] ## APL, ~~17 bytes~~ 15 bytes ``` {⍵×(⌽∨⊖)1∊¨⍳⍴⍵} ``` ### How it works * `⍳⍴⍵` generates a 2D array where all the cells contain the coordinates of all the cells of the argument. * `1∊¨` searches in each such cell if there's a 1 and returns a 1 if so, or 0 otherwise. This builds a matrix where the first row and the first column are 1s and all the rest are 0. * `(⌽∨⊖)` combines with logical "or" two version of the matrix, one reversed along the first and one reversed along the last axis. * `⍵×` is the standard multiplication. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes ``` ⊢-(⍉0⍪1↓⌽)⍣4 ``` [Try it online!](https://tio.run/##hU/LSsQwFN37FWfXZlFI@kri35SRymBhZGY2MriTQtWA4h@Mu9nMyo3gZj7l/ki9adoRqiAh6bnnwbmtbpvk6q5qVtfJoqk2m@Wi72tqX@hxn8TkOknuoKh9o@cvQe497/stqztyH9Tt1wxrcp@XUV0tm4gR82t6eohWN9H9BecPmdj61@OOgUYK46nzEFwooFKcjmWwn0dW29fYWlgDq0VsDIyGKQX7/hZCooTnYEWsJJQa7XM2eE9HxVW@LmOBd@JPwRsUY2qmyx997NLIWTR@aZYsv8jTgdM@oJAxtEh9bwne2UBryGmpeVwOZwyH4Vc0NPNPYLjBOVzxLxtqZy45ucYzYyfvNw "APL (Dyalog Classic) – Try It Online") `⍉⌽⍵` is normally rotation (reverse horizontally and transpose) here we combine it with `0⍪1↓⍵` which replaces the first row with zeroes (drop one row, then concatenate 0 on top) into a single train: `⍉0⍪1↓⌽` `⍣4` repeats 4 times `⊢-` subtracts from the original matrix [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4FøεNĀ*}R}^ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fxO3wjnNb/Y40aNUG1cb9/x8dbWauY6Kja6FjqmNoHKsTbQmkdEyMQGLmQK6hjqGOsY6upY6RJYhnpmNpqWOhY26uYxAbCwA) or [verify all test cases](https://tio.run/##hY2xCgIxDIZf5bhR/sK1d16S6TZHB9dSQcHByUEQHAQnZ/FdBPdz9iF8kZq2t0tJk3zJ/@dw3Gz3u3g6j/ehrr63R1UPsVuMr89z@b7OLqvLOiJ679sQUHlPcOBStgF@rmGdfqYvUATCEFLEDCbwNOiRGSQpGlhbsLEwDiZ5WbXOntA3iQgdDCuwaSKa0LnEKAssWhiBy6Y99DiDCE1R6xXkyLtTp/V/HsIP). **Explanation:** ``` 4F } # Loop 4 times: ø # Transpose/zip; swapping rows/columns ε } # Map over the matrix (takes the input implicitly in the first iteration) NĀ # Trutify the index (0 remains 0; everything else becomes 1) * # Multiply all values in the current row of the matrix with it R # Reverse the matrix ^ # Bitwise-XOR the resulting matrix with the (implicit) input-matrix # (and output implicitly) ``` **Example run:** ``` Input: [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] Iteration 1: Zip: [[67,9,1,16],[4,13,1,99],[-8,42,3,8],[5,4,-9,77],[13,-7,29,0]] Map: [[0,0,0,0],[4,13,1,99],[-8,42,3,8],[5,4,-9,77],[13,-7,29,0]] Reverse: [[13,-7,29,0],[5,4,-9,77],[-8,42,3,8],[4,13,1,99],[0,0,0,0]] Iteration 2: Zip: [[13,5,-8,4,0],[-7,4,42,13,0],[29,-9,3,1,0],[0,77,8,99,0]] Map: [[0,0,0,0,0],[-7,4,42,13,0],[29,-9,3,1,0],[0,77,8,99,0]] Reverse: [[0,77,8,99,0],[29,-9,3,1,0],[-7,4,42,13,0],[0,0,0,0,0]] Iteration 3: Zip: [[0,29,-7,0],[77,-9,4,0],[8,3,42,0],[99,1,13,0],[0,0,0,0]] Map: [[0,0,0,0],[77,-9,4,0],[8,3,42,0],[99,1,13,0],[0,0,0,0]] Reverse: [[0,0,0,0],[99,1,13,0],[8,3,42,0],[77,-9,4,0],[0,0,0,0]] Iteration 4: Zip: [[0,99,8,77,0],[0,1,3,-9,0],[0,13,42,4,0],[0,0,0,0,0]] Map: [[0,0,0,0,0],[0,1,3,-9,0],[0,13,42,4,0],[0,0,0,0,0]] Reverse: [[0,0,0,0,0],[0,13,42,4,0],[0,1,3,-9,0],[0,0,0,0,0]] Bitwise-XOR: [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]] ``` [Answer] ## Perl, 34 + 2 = 36 bytes ``` next if$.==1||eof;s/ .+?(?= )/ 0/g ``` Requires the `-p` flag: ``` $ perl -pE'next if$.==1||eof;s/ .+?(?= )/ 0/g' <<< $'1 2 3\n4 5 6\n7 8 9' 1 2 3 4 0 6 7 8 9 ``` How it works: ``` # '-p' Read each line into `$_` and auto prints next if$.==1||eof; # `$.` is set to to the current line in file (1, 2, ..., n) # and `eof` is true if its the last line s/ .+?(?= )/ 0/g ``` [Answer] # Lua, 69 bytes ``` function f(a)for i=2,#a-1 do for o=2,#a[i]-1 do a[i][o]=0 end end end ``` If only I had curly braces instead of dos and ends... ]
[Question] [ ## The Challenge Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string. You can assume the strings will always start with the same character. ## Example ``` Input: "Test", "Testing" Output: Test Tes Te T Te Tes Test Testi Testin Testing ``` First you output the first word: ``` Test ``` Then you keep removing one letter until the string is one character long: ``` Tes Te T ``` Then keep adding one letter of the second word until it's done: ``` Te Tes Test Testi Testin Testing ``` (if both strings are one character long, then just output one of them once.) ## Test Cases ``` "Hello!", "Hi." Hello! Hello Hell Hel He H Hi Hi. "O", "O" O "z", "zz" z zz ".vimrc", ".minecraft" .vimrc .vimr .vim .vi .v . .m .mi .min .mine .minec .minecr .minecra .minecraf .minecraft " ", " " SSSSS SSSS SSS SS S SS SSS "0123456789", "02468" 0123456789 012345678 01234567 0123456 012345 01234 0123 012 01 0 02 024 0246 02468 ``` *(note: on the space/fourth test case, replace the S with spaces)* ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016. * Standard loopholes are forbidden. [Answer] # [V](http://github.com/DJMcMayhem/V), 14 bytes ``` òYp$xhòjòÄ$xhh ``` [Try it online!](http://v.tryitonline.net/#code=w7JZcCR4aMOyasOyw4QkeGho&input=MDEyMzQ1Njc4OQowMjQ2OA) Explanation: ``` ò ò "Recursively: Yp " Yank the current line and paste it $ " Move to the end of the current line x " Delete one character h " Move One character to the right. " Because of the way loops work in V, this will throw an error if there " Is only one character on the current line. ``` Now, the buffer looks like this: ``` 0123456789 012345678 01234567 0123456 012345 01234 0123 012 01 0 ``` We just need to do the same thing in reverse for the next line: ``` j "Move down one line ò ò "Recursively (The second ò is implicit) Ä " Duplicate this line up $ " Move to the end of the current line x " Delete one character hh " Move two characters to the right. " Because of the way loops work in V, this will throw an error if there " Is only two characters on the current line. ``` [More interesting alternate solution](http://v.tryitonline.net/#code=w7LDhCR4aMOyw6deLzptMApkZEdwQHFk&input=MDEyMzQ1Njc4OQowMjQ2OA): ``` òÄ$xhòç^/:m0 ddGp@qd ``` [Answer] # Pyth, 9 bytes ``` j+_._Et._ ``` A program that takes the second string, and then the first string, as quoted strings on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=j%2B_._Et._&test_suite=1&test_suite_input=%22Hi.%22%0A%22Hello%21%22%0A%22O%22%0A%22O%22%0A%22zz%22%0A%22z%22%0A%22.minecraft%22%0A%22.vimrc%22%0A%22+++%22%0A%22+++++%22%0A%2202468%22%0A%220123456789%22&debug=0&input_size=2) **How it works** ``` j+_._Et._ Program. Inputs: Q, E ._E Yield prefixes of E as a list _ Reverse the above ._ Yield prefixes of Q as a list (implicit input fill) t All but the first element of above + Merge the two lists j Join on newlines Implicitly print ``` [Answer] # Python, 93 bytes ``` f=lambda a,b,r='',i=2:a and f(a[:-1],b,r+a+'\n')or(len(b)>=i and f(a,b,r+b[:i]+'\n',i+1)or r) ``` Starts with the empty string `r`, adds `a` and a newline and removes the last character from `a` until `a` is empty then adds the required portions of `b` and a newline by keeping a counter, `i`, which starts at `2` until the length of `b` is exceeded, then returns `r`. Has a trailing newline. All tests are on [**ideone**](http://ideone.com/fjXSMI) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes ``` .pRI.p¦«» ``` **Explanation** ``` .pR # prefixes of first word I.p # prefixes of second word ¦ # remove first prefix « # concatenate » # join with newlines ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LnBSSS5wwqbCq8K7&input=VGVzdApUZXN0aW5n) [Answer] # Retina, ~~50~~ ~~41~~ 26 bytes Thanks to Martin Ender for saving 15(!) bytes. ``` M&!r`.+ Om`^.¶[^·]+|.+ A1` ``` Takes input with the two strings separated by a newline: ``` Test Testing ``` [Try it online!](http://retina.tryitonline.net/#code=TSYhcmAuKwpPbWBeLsK2W17Ct10rfC4rCkExYA&input=VGVzdApUZXN0aW5n) ## Explanation ``` M&!r`.+ ``` The first line generates the "steps" of both words: ``` Testing Testin Testi Test Tes Te T Test Tes Te T ``` `M` is for match mode, `&` considers overlapping matches, and `!` prints the matches instead of the number of them. The reason it's reversed is the `r`ight-to-left option: the engine starts looking for matches at the end of the string and continues toward the beginning. ``` Om`^.¶[^·]+|.+ ``` This gets everything in the right order: it s`O`rts all matches of the subsequent regex: A character on its own line and every character (including newlines) after it, which matches the whole second half as one chunk, or otherwise a line of characters, which matches each individual line. These matches are then sorted by code point, so the T followed by the newline goes first, followed by the lines, ascending by length. ``` A1` ``` Now we just have that first character line on top so we use `A`ntigrep mode to discard the first match of the default regex `.+`. ## Old version ``` M&!r`.+ O`\G..+¶ s`(.*)¶.¶(.*) $2¶$1 ¶.$ ``` [Try this version online!](http://retina.tryitonline.net/#code=TSYhcmAuKwpPYFxHLi4rwrYKc2AoLiopwrYuwrYoLiopCiQywrYkMQrCti4kCg&input=VGVzdApUZXN0aW5n) ### Explanation The first line is the same, so see the explanation for that above. ``` O`\G..+¶ ``` This reverses the lines of the first half (second input word). It actually s`O`rts the lines, and the regex limits the matches: it must be a line of two or more characters (`..+`) followed by a newline (`¶`) that begins where the last one left off (`\G`). In the above example, the single `T` in the middle doesn't match, so nothing after it can. ``` Te Tes Test Testi Testin Testing T Test Tes Te T ``` Now we have the right two components, but in the wrong order. ``` s`(.*)¶.¶(.*) $2¶$1 ``` `¶.¶` matches the lone T in the middle, which we don't need but separates the two parts. The two `(.*)` capture everything before and after, including newlines thanks to `s`ingle-line mode. The two captures are substituted in the right order with a newline in between. Now we're done, unless the input strings are one character long, in which case the input hasn't changed. To get rid of the duplicate, we replace `¶.$` (when the last line of the string a single character) with nothing. [Answer] # Python 2, ~~88~~ 82 bytes ``` x,y=input(),input() for i in x:print x;x=x[:-1] s=y[0] for i in y[1:]:s+=i;print s ``` Takes two inputs, each surrounded by quotes. Thanks @JonathanAllan for saving some bytes and pointing out a bug. [Answer] # Perl, ~~34~~ 28 bytes Includes `+2` for `-0n` Run with the strings on separate lines on STDIN: ``` perl -M5.010 -0n slow.pl Test Testing ^D ``` `slow.pl`: ``` /(^..+| \K.+?)(?{say$&})^/ ``` Let regex backtracking do the work... [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~102~~ ~~97~~ ~~95~~ 93 bytes ``` n;f(char*a,char*b){for(n=strlen(a);n;puts(a))a[n--]=0;for(a=b+1;*a++;*a=n)n=*a,*a=0,puts(b);} ``` [Try it online!](https://tio.run/##NY2xDsMgDET3fEXEZAJI6Wz5L7pFGQxK0kitWwGdqn47BaR6sE@n87vgjhBKEdwh3DhObPvx@rM/IwilHO@bAGsUfL1zqkrzIs6tNGOLMHlzwYmNqYtEC1VGVbPtca/xWxpy5GUldd1SVnYY2/i/ccqhcHjwKVBrgW1/@gE "C (gcc) – Try It Online") The first loop overwrites the string with 0 bytes starting from the end, and uses `puts()` to print the string. The second loop can't just overwrite from the beginning, it has to store the old value so it can put it back; the 0 byte is just walking towards the end. Thanks to @homersimpson and @ceilingcat for each shaving off 2 bytes! [Answer] # Python 3, 104 bytes Meh. ``` n='\n';lambda x,y:x+n+n.join(x[:-i]for i in range(1,len(x)-1))+n+n.join(y[:i]for i in range(1,len(y)+1)) ``` Thanks to @DJMcMayhem for golfing 21 bytes off. [**Ideone it!**](https://ideone.com/BNlGzA) [Answer] # [Cheddar](http://cheddar.vihan.org), 76 bytes ``` (a,b,q=s->(|>s.len).map((_,i)->s.head(i+1)))->(q(a).rev+q(b).slice(1)).vfuse ``` A bit longer than I'd liked. I'll add an explanation soon [Try it online!](http://cheddar.tryitonline.net/#code=bGV0IGY9IChhLGIscT1zLT4ofD5zLmxlbikubWFwKChfLGkpLT5zLmhlYWQoaSsxKSkpLT4ocShhKS5yZXYrcShiKS5zbGljZSgxKSkudmZ1c2U7CgpzLT5mKHMubGluZXNbMF0sIHMubGluZXNbMV0p&input=SGVsbG8KSGku) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 32 bytes ``` :1aLtT,Lhbr:Tc~@nw :2fb ~c[A:B]h ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjFhTHRULExoYnI6VGN-QG53CjoyZmIKfmNbQTpCXWg&input=WyJIZWxsbyEiOiJIaS4iXQ) ### Explanation Brachylog has no prefix built-in, therefore we will get the prefixes by using `concatenate` (See predicate 2): a prefix of `S` is `P` if `P` concatenated to `Q` (whatever it is) results in `S`. * Main predicate: ``` :1aL L is all prefixes of both elements of the input (see predicate 1) LtT, T is the second element of L Lhbr Remove the first prefix of the first list of L and reverse it :Tc Concatenate with T ~@n Join with newlines w Write to STDOUT ``` * Predicate 1: ``` :2f Find all prefixes of the input string (see predicate 2) b Remove the first one (empty string) ``` * Predicate 2: ``` ~c[A:B] Input is the result of concatenating A to B h Output is A ``` [Answer] # Javascript, 103 81 bytes ``` f=(x,y,n=1)=>x?` `+x+f(x.slice(0,-1),y):n++<y.length?` `+y.slice(0,n)+f(x,y,n):'' ``` Example: `f("Test", "Testing")` Output: ``` Test Tes Te T Te Tes Test Testi Testin Testing ``` Original answer ``` f=(x,y,n=1)=>x?(console.log(x),f(x.slice(0,-1),y)):n++<y.length?(console.log(y.slice(0,n)),f(x,y,n)):'' ``` [Answer] # Java, ~~188~~ 179 bytes ``` interface E{static void main(String[]a){int i=a[0].length();while(i>1)System.out.println(a[0].substring(0,i--));while(i<=a[1].length())System.out.println(a[1].substring(0,i++));}} ``` **Update** * Removed s variable, saved 9 bytes **Ungolfed**: ``` interface E { static void main(String[] a) { int i = a[0].length(); while (i > 1) { System.out.println(a[0].substring(0, i--)); } while (i <= a[1].length()) { System.out.println(a[1].substring(0, i++)); } } } ``` **Usage**: ``` $ java E 'test' 'testing' test tes te t te tes test testi testin testing ``` [Answer] ## Haskell, ~~54~~ ~~53~~ 47 bytes ``` t[]=[] t x=x:t(init x) (.reverse.t).(++).init.t ``` Usage example: `((.reverse.t).(++).init.t) "Hello" "Hi!"` -> `["Hello","Hell","Hel","He","H","Hi","Hi!"]`. Some pointfree magic. It's the same as `f x y = (init(t x))++reverse (t y)` where `t` makes a list of all initial substrings e.g. `t "HI!"` -> `["H","HI","HI!"]`. [Answer] ## Pyke, 14 bytes ``` VDO)KKQlFh<)_X ``` [Try it here!](http://pyke.catbus.co.uk/?code=VDO%29KKQlFh%3C%29_X&input=Testing%0ATest&warnings=0) And 17 bytes just because it's an awesome solution: ``` mVDO)Fto!I_O(RKsX ``` [Try it here!](http://pyke.catbus.co.uk/?code=mVDO%29Fto%21I_O%28RKsX&input=%5B%22Test%22%2C%22Testing%22%5D) [Answer] ## GNU sed, ~~57~~ 45 + 2(rn flags) = 47 bytes ``` :;1{/../p};2G;2h;s/.(\n.*)?$//;/./t;g;s/.$//p ``` **Run:** ``` echo -e "Test\nTesting" | sed -rnf morphing_string.sed ``` The input should be the two strings separated by a newline. The code is run by sed for each line. The loop `:` deletes one character from the end of the string iteratively. The output related to the first string is printed directly, except the first character: `1{/../p}`. The output for the second string is stored in hold space in reverse order (`2G;2h`) during deletion and printed at the end. [Answer] # REPL/Javascript, 109 Bytes Uses false string to whittle down the original string Abuses substring with larger numbers to grow the second one, stops when its about to print the same word as last time. ``` (a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}} ``` Demo: ``` > ((a,b)=>{l=console.log;z='substring';for(c=a.length;d=a[z](0,c--);){l(d)}for(c=2;d!=(n=b[z](0,c++));){l(d=n)}})("asdf","abcd") [Log] asdf [Log] asd [Log] as [Log] a [Log] ab [Log] abc [Log] abcd ``` [Answer] ## Brainfuck, 38 55 bytes ``` >++++++++++>,[>,]<[<]>>[[.>]<[-]<[<]>.>],.[[<]>.>[.>],] ``` Edit: included newlines in output [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~20~~ 13 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ↑(⌽,\⍞),1↓,\⍞ ``` `↑` matrify `(⌽,\⍞)` reversed (`⌽`) cumulative concatenation (`,\`) of character input (`⍞`) `,` prepended to `1↓` one element dropped from `,\⍞` cumulative concatenation of character input [TryAPL online!](http://tryapl.org/?a=%u2206%20%u2359%u2190%27Test%27%20%27Testing%27%20%u22C4%20%u2191%28%u233D%2C%5C%u2206%29%2C1%u2193%2C%5C%u2359&run) [Answer] # Racket 193 bytes ``` (define(f l) (let*((s(list-ref l 0)) (x(string-length s))) (for((n x)) (println(substring s 0(- x n)))) (set! s(list-ref l 1)) (for((n(range 1(string-length s)))) (println(substring s 0(add1 n)))))) ``` Testing: ``` (f(list "Test" "Testing")) "Test" "Tes" "Te" "T" "Te" "Tes" "Test" "Testi" "Testin" "Testing" (f(list "Hello!" "Hi.")) "Hello!" "Hello" "Hell" "Hel" "He" "H" "Hi" "Hi." ``` [Answer] # [Floroid](https://github.com/TuukkaX/Floroid), 69 bytes ``` a,b=L.J c=1 NZ(a)!=1:z(a);a=a[:-1] z(a) NZ(a)!=Z(b):c+=1;a=b[:c];z(a) ``` It's a start. Takes the input from STDIN. ## Testcases ``` Input: Test Testing Output: Test Tes Te T Te Tes Test Testi Testin Testing Input: O O Output: O ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` +↔ḣ²tḣ⁰ ``` [Try it online!](https://tio.run/##yygtzv7/X/tR25SHOxYf2lQCJB81bvj//39IanEJmMjMSwcA "Husk – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` []↕k;[]∔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXVGRjNEJXUyMTk1JXVGRjRCJXVGRjFCJXVGRjNCJXVGRjNEJXUyMjE0,i=VGVzdCUwQVRlc3Rpbmc_,v=8) Explanation: ``` []↕k;[]+ | Full program (characters replaced for clean formatting) ---------+-------------------------------------------------------- [] | Prefixes of first input ↕ | Reversed k | Remove the last item ; | Swap (places the second input on top) [] | Prefixes of second input + | Add vertically ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` €ƒẸrsḥ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMiU4MiVBQyVDNiU5MiVFMSVCQSVCOHJzJUUxJUI4JUE1JmZvb3Rlcj0maW5wdXQ9JTIyVGVzdGluZyUyMiUyQyUyMCUyMlRlc3QlMjImZmxhZ3M9Tg==) Takes inputs in reverse order. #### Explanation ``` €ƒẸrsḥ # Implicit input €ƒ # Prefixes of each Ẹr # Dump and reverse sḥ # Swap and concatenate # Implicit output ``` [Answer] ## JavaScript (ES6), 92 bytes ``` (s,t)=>s.replace(/./g,` $\`$&`).split` `.slice(2).reverse().join` `+t.replace(/./g,` $\`$&`) ``` The `replace` statements build up a triangle of strings, which is exactly what's required for the second half of the output, however the first half needs to be reversed and the duplicate single-character line removed. Note: outputs a leading newline if the first string is a single character. If this is undesirable then for an extra byte this version always outputs a trailing newline: ``` (s,t)=>s.replace(/./g,` $\`$&\n`).split(/^/m).slice(1).reverse().join``+t.replace(/./g,` $\`$&\n`) ``` [Answer] # C, 142 bytes ``` #define _(x,y) while(y)printf("%.*s\n",d,x-c); f(char*a,char*b){int c=1,d=strlen(a)+1;while(*++a==*++b)c++;_(a,--d>=c)d++;_(b,d++<strlen(b-c))} ``` Provide `f(char* str1, char* str2)`. [Answer] # TI-Basic, 56 bytes ``` Prompt Str1,Str2 Str1 While 1<length(Ans Disp Ans sub(Ans,1,length(Ans)-1 End For(I,1,length(Str2 Disp sub(Str2,1,I End ``` **Example usage** ``` Str1=?Test Str2=?Testing Test Tes Te T Te Tes Test Testi Testin Testing Str1=?O Str2=?O O Str1=?z Str2=?zz z zz ``` [Answer] # Java, ~~168~~ 136 bytes ``` (s,d)->{int i=s.length()+1;while(i-->1)System.out.println(s.substring(0,i));while(i++<d.length())System.out.println(d.substring(0,i));}; ``` # Ungolfed test program ``` public static void main(String[] args) { BiConsumer<String, String> biconsumer = (s, d) -> { int i = s.length() + 1; while (i-- > 1) { System.out.println(s.substring(0, i)); } while (i++ < d.length()) { System.out.println(d.substring(0, i)); } }; biconsumer.accept("Test", "Testing123"); } ``` [Answer] # (Lambdabot) Haskell - 41 bytes ``` f=(.drop 2.inits).(++).reverse.tail.inits ``` More readable, but two bytes longer: ``` a!b=(reverse.tail$inits a)++drop 2(inits b) ``` Output: ``` f "Hello" "Hi!" ["Hello","Hell","Hel","He","H","Hi","Hi!"] ``` [Answer] # J, 18 bytes ``` ]\@],~[:}:[:|.]\@[ ``` Ungolfed: ``` ]\@] ,~ [: }: [: |. ]\@[ ``` This is a 7-train: ``` ]\@] ,~ ([: }: ([: |. ]\@[)) ``` The innermost train `[: |. ]\@[` consists of a cap `[:` on the left, so we apply `|.` (reverse) to the result of `]\@[`, which is `]\` (prefixes) over `[` (left argument). Here's what that looks like on the `testing, test` input: ``` 'testing' ([: |. ]\@]) 'test' test tes te t ``` This gives us the first portion, almost. The 5-train outside of that is `([: }: ([: |. ]\@[))`, which applies `}:` (betail, remove last element) to the above expression: ``` 'testing' ([: }: [: |. ]\@]) 'test' test tes te ``` (This is because we can't have a duplicate midpoint.) The outer part is finally: ``` ]\@] ,~ ([: }: ([: |. ]\@[)) ``` This is composed of `]\@]` (prefixes of left argument) and `,~` (append what's to the left with what's to the right), leaving us with the desired result: ``` 'testing' (]\@] ,~ ([: }: ([: |. ]\@[))) 'test' testing testin testi test tes te t te tes test ``` ## Test cases ``` k =: ]\@] ,~ ([: }: ([: |. ]\@[)) 'o' k 'o' o k~ 'o' o 'test' k 'test' test tes te t te tes test k~ 'test' test tes te t te tes test '. . .' k '...' . . . . . . . . . .. ... 'z' k 'zz' z zz ``` ]
[Question] [ > > A number is a *Mersenne Prime* if it is both prime and can be written in the form **2n-1**, where **n** is a positive integer. > > > Your task is to, given any positive integer, determine whether or not it is a Mersenne prime. You may submit either a function which returns a truthy/falsy value, or a full program which performs IO. ### Rules: * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), you should aim to do this in the **shortest byte count possible.** Builtins are allowed. * Standard golfing loopholes apply - you cannot read the Mersenne primes from external files, or hardcode them into your program. * Your program should work for values within your language's standard integer size. --- ### Test Cases For reference, a list of (known) Mersenne Primes can be found [**here**](http://www.mersenne.org/primes/). Some handy test cases are: ``` 2 -> False 1 -> False 20 -> False 51 -> False 63 -> False 3 -> True 31 -> True 8191 -> True ``` --- *Merry Christmas, everybody! Have a great holiday, whatever you celebrate :)* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes A positive number in the form **2n - 1** in binary only consists of **1's**. Code: ``` b`¹pP ``` Explanation: ``` b` # Push each digit of the binary representation of the number onto the stack ¹p # Check if the input is prime P # Take the product of all these digits ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@5@UcGhnQcD//xaGloYA "05AB1E – TIO Nexus") or [Verify all test cases](https://tio.run/nexus/05ab1e#qyn7X5mUUFkQ8F/nvxGXoSmXkQGXqSGXmTEXEBpyWRhaGgIA). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` &‘<ÆP ``` [Try it online!](https://tio.run/nexus/jelly#@6/2qGGGzeG2gP@H2x81rQEi9///o410FAxNdRSMDHQUTA11FMyMY3UUoo11FIyBHAtDS8NYAA "Jelly – TIO Nexus") ### How it works ``` &‘<ÆP Main link. Argument: x ‘ Yield x+1. & Take the bitwise AND of x and x+1. This yields 0 iff x is a Mersenne number, i.e., iff x+1 is a power of 2. ÆP Yield 1 if x is a prime, 0 if not. < Compare the results to both sides, This yields 1 iff x is both a Mersenne number and a prime. ``` [Answer] # [Python](https://docs.python.org/), 45 bytes ``` lambda n:-~n&n<all(n%i for i in range(2,n))<n ``` [Try it online!](https://tio.run/nexus/python3#FchBCsIwEEbhtT3Fv7HMyAhNg6Kl3qSbEY0E0mkJLrry6jFdPd4X8MBUks7Pl8KG889aGzUlsmNEWDIioiGrfd7UizGPVnbedq4CJ@g7waX26llAXuDr3Nzd8dAc1hztS6dZVwqCjbn8AQ "Python 3 – TIO Nexus") ### How it works The three terms of the chained comparison ``` -~n&n<all(n%i for i in range(2,n))<n ``` do the following: * `-~n&n` computes the bitwise AND of **n + 1** and **n**. Since **n** consists solely of **1** bits if it is a Mersenne number, the bitwise AND will return **0** if (and only if) this is the case. * `all(n%i for i in range(2,n))` returns *True* if and only if **n mod i** is non-zero for all values of **i** in **[2, …, n - 1]**, i.e., if and only if **n** has no positive divisors apart from **1** and **n**. In other words, *all* returns *True* if and only if **n** is a composite number, i.e., **n** is either **1** or a prime. * `n` is self-explanatory. The chained comparison returns *True* if and only if the individual comparisons do the same. * Since *all* returns either *True*/**1** or *False*/**0**, `-~n&n<all(n%i for i in range(2,n))` can only return *True* if `-~n&n` yields **0** (i.e., if **n** is a Mersenne number) and *all* returns *True* (i.e., if **n** either **1** or a prime). * The comparison `all(n%i for i in range(2,n))<n` holds whenever **n > 1**, but since *all* returns *True* if **n = 1**, it does not hold in this case. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` #p+~^h2 ``` [Try it online!](https://tio.run/nexus/brachylog#@69coF0Xl2H0/7@hkTkA "Brachylog – TIO Nexus") A Brachylog program is basically a sequence of constraints which form a chain: the first constraint is between the input and an anonymous unknown (let's call it *A* for the purpose of this discussion), the second constraint is between that anonymous unknown and a second anonymous unknown (which we'll call *B*), and so on. As such, the program breaks down like this: ``` #p Input = A, and is prime + B = A + 1 ~^ B = X to the power Y, C = the list [X, Y] h D = the head of list C (= X) 2 D = 2 ``` The only way all these constraints can be satisfied simultaneously is if B is a power of 2, i.e. the input is a power of 2 minus 1, and the input is also prime. (Brachylog uses a constraint solver internally, so the program won't be as inefficient as the evaluation order looks; it'll be aware that `C` is of the form `[2, Y]` before it tries to express `B` as the exponentiation of two numbers.) Interestingly, `#p+~^` *almost* works, because Mersenne-like primes can only use 2 as the base in non-degenerate cases ([proof](https://en.wikipedia.org/wiki/Mersenne_prime#Theorems_about_Mersenne_numbers)), but a) it fails for non-Mersenne primes *B*-1 as they can be expressed as *B*¹, and b) the existing Brachylog interpreter seems to be confused (going into an infinite, or at least long-duration, loop) by a program that's that poorly constrained. So 7 bytes seems unlikely to be beaten in Brachylog. [Answer] ## Mathematica 26 Bytes ``` PerfectNumberQ[# (#+1)/2]& ``` See this [proof](https://primes.utm.edu/notes/proofs/EvenPerfect.html) Works so long as there are no odd perfect numbers, and none are known to exist. [Answer] ## Mathematica, 29 26 bytes *Edit: Saved 3 bytes thanks to Martin Ender* `PrimeQ@#&&IntegerQ@Log2[#+1]&` ``` PrimeQ@#&&1>BitAnd[#,#+1]& ``` I suspect this would be faster since the first 42 exponents are hard-coded: ``` MersennePrimeExponentQ@Log2[#+1]& ``` [Answer] # [Perl 6](https://perl6.org), 29 bytes ``` {.base(2)~~/^1*$/&&.is-prime} ``` [Try it](https://tio.run/nexus/perl6#TU/LTgJBELzPV/SB8FCB7unpeYhi4sEv4CZqlB3NJrBLWDAShF/HWSKPS6e6q1JdtaoifNveZKBWCY1itRwoNVtDc1JmEe73m97HexXburPb9V/pqtFvNnt51Z0v8lnc7j/LBUzzIlbtDmwUwKyfBsDrYTbu8mK@Wg7hHsbZ9eE0rq6g1R22avCviT/zOFnGrJY9jxar@Pv0Pq3iS6L7kOyL@FNHSt5raBzFSftYltPb283uwmF70KV0WYzz6Roe6g7t690xSOfm7JDg20BtVVYWsbtMtfPia7DXAN0hHAIokhMGpfFMCJ2x5TNWXDdKa91CMV0sngKdFmW9NS44a5EYLQZHJiQFogsBPXFgTU7bYFgYkQwzisHAwRjLRgJ5EcPkmZOJWBRNWosEa9BaMmISHZzTwTIlNzIevXhkR5qCT0/SR2sNe9LiDGqvAxEJiiM5xfwD "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 .base(2) # is its binary representation ( implicit method call on 「$_」 ) ~~ /^ 1* $/ # made entirely of 「1」s && # and .is-prime # is it prime } ``` since Perl 6 has arbitrarily large Ints, it doesn't pad the front of `.base(2)` with `0`s. [Answer] ## Python, ~~83~~ ~~82~~ ~~79~~ ~~76~~ 73 bytes ``` def f(m): s,n=(m!=3)*4,m>>2 while-~m&m<n:s,n=(s*s-2)%m,n>>1 return s<1 ``` ## Python 2, 71 bytes ``` def f(m): s,n=(m!=3)*4,m/4 while-~m&m<n:s,n=(s*s-2)%m,n/2 return s<1 ``` This function implements the [Lucas–Lehmer primality test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test), so while it isn't as short as some of the other Python offerings it's *much* faster at handling huge inputs. --- Here's some test code that runs on Python 2 or Python 3. ``` from __future__ import print_function def primes(n): """ Return a list of primes < n """ # From http://stackoverflow.com/a/3035188/4014959 sieve = [True] * (n//2) for i in range(3, int(n**0.5) + 1, 2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n - i*i - 1) // (2*i) + 1) return [2] + [2*i + 1 for i in range(1, n//2) if sieve[i]] def lucas_lehmer_old(p): m = (1 << p) - 1 s = 4 for i in range(p - 2): s = (s * s - 2) % m return s == 0 and m or 0 # much faster def lucas_lehmer(p): m = (1 << p) - 1 s = 4 for i in range(p - 2): s = s * s - 2 while s > m: s = (s & m) + (s >> p) return s == 0 or s == m and m or 0 def f(m): s,n=(m!=3)*4,m>>2 while-~m&m<n:s,n=(s*s-2)%m,n>>1 return s<1 # Make a list of some Mersenne primes a = [3] for p in primes(608): m = lucas_lehmer(p) if m: print(p, m) a.append(m) print() # Test that `f` works on all the numbers in `a` print(all(map(f, a))) # Test `f` on numbers that may not be Mersenne primes for i in range(1, 525000): u = f(i) v = i in a if u or v: print(i, u, v) if u != v: print('Error:', i, u, v) ``` **output** ``` 3 7 5 31 7 127 13 8191 17 131071 19 524287 31 2147483647 61 2305843009213693951 89 618970019642690137449562111 107 162259276829213363391578010288127 127 170141183460469231731687303715884105727 521 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151 607 531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127 True 3 True True 7 True True 31 True True 127 True True 8191 True True 131071 True True 524287 True True ``` FWIW, here's a slightly more efficient version of `f` that doesn't re-test `m` on every loop: ``` def f(m): s,n=m!=3and 4,m>>2 if-~m&m<1: while n: s=(s*s-2)%m n>>=1 return s<1 ``` [Answer] # R, ~~41~~ 40 bytes ``` matlab::isprime(x<-scan())&!log2(x+1)%%1 ``` Oddly enough the builtin in R `mersenne` takes `n` as argument, not `2^n-1`. This takes `x` from STDIN, checks if it is prime using the `matlab` package and checks if the 2-log of `x+1` is a whole number by taking mod 1 and checking for 'not zero-ness'. Also, if you use the `mersenne` builtin, it ends up being slightly shorter, but feels like cheating: ``` numbers::mersenne(log2(scan()+1)) ``` Saved 1 byte thanks to @Billywob [Answer] ## Pyke, 10 bytes ``` _PQb2+}\1q ``` [Try it here!](http://pyke.catbus.co.uk/?code=_PQb2%2B%7D%5C1q&input=7) ``` _P - is_prime(input) + - ^ + V Qb2 - base_2(input) } - uniquify(^) \1q - ^ == "1" ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 9 bytes ``` ;├╔'1=@p* ``` [Try it online!](https://tio.run/nexus/actually#@2/9aMqcR1OnqBvaOhRo/f9vDAA "Actually – TIO Nexus") Explanation: Since every number of the form 2n-1 has all 1's in its binary representation, a Mersenne prime can be identified as a prime number with that quality. ``` ;├╔'1=@p* ├╔'1= only unique binary digit is 1 * and ; @p is prime ``` [Answer] ## Jelly, 5 bytes Alternate approach to @Dennis' existing 5-byte Jelly answer: ``` B;ÆPP ``` [Try it online!](https://tio.run/nexus/jelly#@@9kfbgtIOD///8WhpaGAA) How it works: ``` B Returns the binary representation of the input as a list [1, 0, 1, 1, ...] ; And attach to this list ÆP a 1 if the input is a prime, 0 otherwise P Calculates the product of this list of 1's and 0's ``` Since a Mersenne Prime is one less than a power of 2, its binary representation is excusively 1's. The output therefor is 1 for Mersenne primes, and 0 in all other cases . [Answer] # Ceylon, 66 bytes ``` Boolean m(Integer c)=>c>2&&c.and(c+1)<1&&!(2:c-2).any((d)=>c%d<1); ``` Formatted (and commented): ``` // Check whether a (positive integer) number is a mersenne prime number. // // Question: http://codegolf.stackexchange.com/q/104508/2338 // My Answer: http://codegolf.stackexchange.com/a/104805/2338 Boolean m(Integer c) => // check whether c+1 is a power of two c.and(c+1)<1 && // the standard primality check by trial division !(2 : c-2).any((d) => c%d < 1) && // we need to exclude 1, which is unfortunately // matched by both criteria above, but is no prime. c>1; ``` --- With cheating (hardcoding the results in the range of Ceylon's Integer), we can get a byte shorter (65): ``` Boolean h(Integer c) => c.and(c+1)<1 && #20000000800a20ac.and(c+1)>0; ``` (It looks like the syntax highlighter misunderstands Ceylon's hex numerals as start-of-comment.) If an anonymous function is okay, this one is 49 bytes: ``` [2,3,5,7,13,17,19,31,61].map((p)=>2^p-1).contains ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` PrimeQ[BitAnd[#,#+2]#]& ``` [Try it online!](https://tio.run/##TY29CsIwFEb3@xSBQBY/0JtYf4ZI9Ql0Dhku2tYM6VCyFZ89ElzcDucMJ0t5D1lKekoVUV6tFow97A4d4@DQgRns4HCEY5z4zB@i0dN9SXl49NoYvtxSuc6voKE3HA3R5Osvh79io46m@bmEcdu3m1dTg1i/ "Wolfram Language (Mathematica) – Try It Online") 1 is handled correctly because `PrimeQ[BitAnd[1,1+2]*1] == PrimeQ@1 == False`. Otherwise, for `BitAnd[#,#+2]#` to be prime, we need that `#` is prime and `BitAnd[#,#+2] == 1`, which happens when `#` is a Mersenne number. [Answer] # Regex (ECMAScript), 29 bytes ``` ^(?!(xx+|(x(x))+)(\1\3)+$)xxx ``` [Try it online!](https://tio.run/##Tc3PT8IwGMbxO38FLCa8L3OlA38QZuHkgQsHPYomzXjpqqVb2goV598@0cTE05N8P4fnVR6kL51uQuYbvSW3r@0bfXROWDr2H0jdxwbgJBbjUfcCywHEmLYQISKmCJt8M8X0AmOM3Wh8Qhbqx@C0VYDMG10S3FxmV4jFsdKGAIxwJLdGWwLEgbDvxuCnEob5xugAw2yIhd4BWKGYIatChYtJ22q/lmvQopHO08oGUE/8GfEP6D/YRb7M5z@MoXL1MVnZgzR623fSKpr3k9QUu9pBoe8EFTpN8XyYxIQ5akgG0Mj2MpQVOMSytr42xEytzr346nh2zTnvzfIZz2aTnPfyac5vefY7k28 "JavaScript (SpiderMonkey) – Try It Online") Inspired by Grimy in [chat](https://chat.stackexchange.com/transcript/message/49455538#49455538) The regex asserts that the input is greater than 3, and that it is neither of the form: `(xx+)\1+` or `((xx)+)(\1x)+`. The first matches composite numbers. The second matches a number that is 1 less than a multiple of some odd number greater than 2. The first will **not** match prime numbers, or `0` or `1`. The second will **not** match numbers of the form \$2^n-1\$, or numbers that are 1 less than an odd prime. Since 2 is the only prime that is 1 less than an odd prime, the negative lookahead, together with the assertion that the input is greater than 3, will match only mersenne primes. [Answer] # Regex (ECMAScript), ~~42~~ 31 bytes `^(?!(xx+)\1+$)(x(x*)(?=\3$))+x$` ``` ^ (?!(xx+)\1+$) # Assert that N is prime or 0 or 1. (x(x*)(?=\3$))+x$ # Assert that N is a power of 2 minus 1 and is >= 3. # The >=3 part of this prevents the match of 0 and 1. ``` [Try it online!](https://tio.run/##TY/NTgIxFEb3PAVMCNzLOEML/hBqYeWCDQtdiiYNXGaqpTRtgRHh2UcwMXH1Lc6XnJwPtVdh6bWLWXB6RX6ztZ/0VXtp6dB8puKpcgBHOen36neYtqCqUlzwtI1QQdVDmMrFsI2YVu261z9iHrcv0WtbAObB6CXB/U12iyiCZOJQakMARnpSK6MtAWJL2p0x@F1IkwdndIRu1kWh1wBWFrkhW8QSJ4PTSYe5moOWTvlAMxuheGVviH@A/gM74VM@vmKMpd8ekpndK6NXTa9sQeNmkhqx3noQ@lGS0GmKF2FSJbknRyqCxnyj4rIEj/gdOh13SYpwreDC7WKI/nIR53PNsjvGWGPERywbDThr8CFnDyz7ncEP "JavaScript (SpiderMonkey) – Try It Online") Edit: Down to 31 bytes thanks to Neil. The basic "is a power of 2 minus 1" test is `^(x(x*)(?=\2$))*$`. This works by looping the operation "subtract 1, then divide evenly by 2" until it can be done no further, then asserting that the result is zero. This can be modified to match only numbers ≥1 by changing the last `*` to a `+`, forcing the loop to iterate at least once. Inserting an `x` before the last `$` further modifies it to match only numbers ≥3 by asserting that the final result after looping at least once is 1. The related "is a power of 2" test is `^((x+)(?=\2$))*x$`. There is also a shorthand for matching powers of 2 minus 2, discovered by [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy): `^((x+)(?=\2$)x)*$`. All three of these regexes are of the same length. Alternative 31 byte version, [by Grimmy](https://chat.stackexchange.com/transcript/message/49454897#49454897): `^(?!(xx+)\1+$|((xx)+)(\2x)*$)xx` [Try it online!](https://tio.run/##TY/LbsIwFET3fAVECO4lTbDTF8I1rLpgw6JdllaywCRujWPZBlII356GSpW6mpHOSKPzKQ7Cr52yIfFWbaTbleZLfjeOG3nsvsj8ubIAJz4bj5oPmPegqmJc0bhfQ1sxRlhlFY76WFXNaHzCNJSvwSmTA6Zeq7WEh5vkDpF5TtixUFoCaO6k2GhlJCD2uNlrjeec69RbrQIMkyEytQUwPE@1NHkocJbVtfJLsQTFrXBeLkyA/I28I/4B@R@YGZ3T6RVjKFx5jBbmILTadJ0wuZx2o1izbemAqScumYpjbA@jKkqdtFIEUJjuRFgX4BDPfjCwrVKAqwVldh98cO2EXS4NSe4JIZ0JnZBkklHSobeUPJLkN7If "JavaScript (SpiderMonkey) – Try It Online") ``` # Match Mersenne primes in the domain ^x*$ ^ # N = input number (?! # "(?!p|q)" is equivalent to "(?!p)(?!q)"; evaluate the # logical AND of the following negative lookaheads: (xx+)\1+$ # Assert that N is prime or 0 or 1 | ((xx)+)(\2x)*$ # Assert that N is a power of 2 minus 1; this is based # on "(?!(x(xx)+)\1*$)" which matches powers of 2. ) xx # Assert that N >= 2, to prevent the unwanted match of # 0 and 1 by both of the negative lookahead statements. ``` [Answer] ## Ruby, 47 bytes ``` ->b{!("%b"%(b/2)=~/0/||(2...b).find{|a|b%a<1})} ``` [Answer] # Julia, 26 bytes ``` n->isprime(n)&&ispow2(n+1) ``` [Answer] # Python, 65 bytes ``` f=lambda n,i=3:(n^i)-all(n%i for i in range(2,n))<0 or f(n,-~i|i) ``` Outputs via Exit Code. Recursion Error for False. No error for True. **How it works** Since `2^n-1` in binary is made entirely from 1's, the next `2^n-1` number can be generated by `number|number+1`. This function uses this by recursively going through each `2^n-1`number checking to see if it's a prime number and eqaul to the input. If the number is not a mersenne prime, python will eventually throw an error as the maximum recursion depth would have been exceeded. [Answer] # [Pushy](https://github.com/FTcode/Pushy), 7 bytes ``` oBoIpP# ``` **[Try it online!](https://tio.run/nexus/pushy#@5/vlO9ZEKD8//9/C0NLQwA "Pushy – TIO Nexus")** This takes advantage of the fact that mersenne numbers have only ones in their binary representation: ``` oB \ Pop input, push its binary digits. oI \ Re-push the input p \ Test its primality (0/1) P# \ Print the product of the stack ``` The stack product will only be `1` if the number has no zeroes in its binary representation, and its primality is `True`. [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` &.AjQ2P_ ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%26.AjQ2P_&input=31&test_suite=1&test_suite_input=2%0A1%0A20%0A51%0A63%0A3%0A31%0A8191&debug=0)** # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` <.&QhQP_ ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%3C.%26QhQP_&input=31&test_suite=1&test_suite_input=2%0A1%0A20%0A51%0A63%0A3%0A31%0A8191&debug=0)** --- # How? ### Code Breakdown #1 ``` &.AjQ2P_ Full program with implicit input. P_ Is Prime? jQ2 Convert the input to binary as a list of digits. .A All the elements are truthy (i.e. all are 1). & Logical AND. Output implicitly. ``` ### How does that work? A number of the form ***2n - 1*** always contains ***1*** only when written in binary. Hence, we test if all its binary digits are ***1*** and if it is prime. ### Code Breakdown #2 ``` <.&QhQP_ Full program with implicit input. P_ Is Prime? hQ Input + 1. .&Q Bitwise AND between the input and ^. < Is smaller than? I.e. The bitwise AND results in 0 and the primality test results in 1. Output implicitly. ``` ### How does that work? This tests if the ***input + 1*** is a power of two (i.e. if it is a Mersenne number), and then performs the primality test. In Python, `bool` is a subclass of `int`, so truthy is treated as ***1*** and falsy is treated as ***0***. To avoid checking explicitly that one is ***0*** and the other is ***1***, we compare their values using `<` (since we only have 1 such case). [Answer] # Java 8, ~~53~~ ~~52~~ 49 bytes ``` n->{int i=1;for(;n%++i>0;);return(n&n+1|i^n)==0;} ``` Bug-fixed and golfed by 4 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##nZBfS8MwFMXf9ykuBSWhtjQrOjV032BlsEdRSLtsZLY3JUkHMvvZa/bnURcVkod7z@HwO3cn9iLRncTd@n2sG2EtLITCwwRAoZNmI2oJ5XEEqLRupECoiZcAKffbwX//rBNO1VACQgEjJvPD0aIKxjfaEI43cazmGafcSNcbJHiLMftUb0iLIuPDyM8xXV81PuaSttdqDa2nIStnFG5fXkHQM8rqwzrZprp3aecl1yCJSu3AD620zxCd4L71YVoTRq/r0yxguA8lPORXDD8r0fJU4A6q3l/YF1pIYyWiTJa/azYNcLEQOMtDhlnoeP@s/teqIdAQZx46xSN7uliGyTB@AQ) ``` n->{ // Method with integer parameter and boolean return-type int i=1; // Temp integer `i`, starting at 1 for(;n%++i>0;); // Loop and increase `i` as long as `n` is divisible by `i` return(n&n+1|i^n) // Then return if `n` bitwise-AND `n+1` bitwise-OR `i` bitwise-XOR `n` ==0; // is exactly 0 } // End of method ``` [Answer] # Python 3, 68 bytes ``` a=int(input());print(a&-~a<1and a>1and all(a%b for b in range(2,a))) ``` [Try it here](http://ideone.com/ZPaMOQ) # Python 2, 63 bytes ``` a=input();print(a&-~a<1)and a>1and all(a%b for b in range(2,a)) ``` [Try it here](http://ideone.com/jvHjxz) --- Thanks for suggestion [Jonathan](https://codegolf.stackexchange.com/users/73111/jonathan-frech) --- Open to any suggestions for reducing the bytecount. [Answer] # Japt, 6 bytes ``` ¢¬×&Uj ``` [Run it](https://ethproductions.github.io/japt/?v=1.4.6&code=oqzXJlVq&input=NQoKLaE=) or [Run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=oqzXJlVq&input=Wwo1LDIsMSwyMCw1MSw2MywgIC8vIGZhbHN5CjMsMzEsODE5MSAgICAgICAgLy8gdHJ1dGh5Cl0KCi1tUg==) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 48 bytes ``` Y+X:-X=<Y;X mod Y>0,Y+1+X. \X:-X>1,2+X,X+1/\X<1. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1I7wko3wtYm0jpCITc/RSHSzkAnUttQO0KPKwYkY2eoY6QdoROhbagfE2FjqPf/f4yRHhdXjCGIMDIAkaZgtpkxiIQQYAELQ0sQnZGYU6IHAA "Prolog (SWI) – Try It Online") -7 thanks to Jo King [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` æ[›¨²c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDplvigLrCqMKyYyIsIiIsIiJd) If N is prime, check if `n+1` is a power of 2. # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` æ⁰bJΠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiw6bigbBiSs6gIiwiIiwiMzEiXQ==) Port of the Jelly 5 byte answer. [Answer] # Python, 93 Bytes ``` def f(a): for b in range(a): if(a+1==2**b and not[i for i in range(2,a)if a%i<1]):return 1 ``` This code would work in both Python 2 and Python 3 so I have not specified a version. [Answer] ## Racket 76 bytes ``` (define(g m)(for/or((i m))(= m(-(expt 2 i)1))))(if(and(prime? n)(g n))#t #f) ``` Ungolfed: ``` (require math) (define(f n) (define (ispowerminus1 m) (for/or ((i m)) (= m (-(expt 2 i)1)))) (if (and (prime? n) (ispowerminus1 n)) #t #f)) ``` Testing: ``` (f 1) (f 2) (f 20) (f 51) (f 63) (f 3) (f 31) (f 8191) ``` Output: ``` #f #f #f #f #f #t #t #t ``` [Answer] # PHP, 53 bytes ``` for($i=$n=$argv[1];--$i&&$n%$i;);echo!($i-1|$n+1&$n); ``` takes command line argument; prints `1` for Mersenne prime, empty string else. Run with `-r`. **breakdown** ``` for($i=$n=$argv[1];--$i&&$n%$i;); // loop $i down from $n-1 until $i divides $n // If $n is prime, loop ends with $i=1. ($n=1 -> $i=0) echo!($i-1|$n+1&$n); // If $i!=1, $n is not prime. If ($n+1&$n)>0, $n is not Mersenne. // If either $i-1 or $n+1&$n is truthy, the negation will be false. ``` [Answer] # C, 94 bytes ``` g(n,i){return--i?g(2*n,i):n;}n,r;f(x){for(n=r=1;++n<x;)r=x%n?x^g(2,n)-1?r:r|2:r&2;return r>2;} ``` Returns 1 if the number is a Mersenne Prime, 0 otherwise. ]
[Question] [ # Introduction Some days ago I needed a metronome for something. I had none available so I downloaded an app from the App Store. The app had a size of 71 MB!!! **71 MB for making tic-toc...?!** So code-golf came into my mind and I was wondering if some of you guys could improve this. # Challenge Golf some code that outputs some sound. It's pretty irrelevant what kind of sound. If required create some sound file... but a System beep will do the job as well. ([Here is some sound I created... nothing special.](http://www.mediafire.com/listen/gwaq93k0uh6lalk/metronome.wav)) **Input**: The beats per minute the metronome outputs. # Example This is a non-golfed Java-version! It's just to show you the task. ``` public class Metronome { public static void main(String[] args) throws InterruptedException { int bpm = Integer.valueOf(args[0]); int interval = 60000 / bpm; while(true) { java.awt.Toolkit.getDefaultToolkit().beep(); // or start playing the sound Thread.sleep(interval); System.out.println("Beep!"); } } } ``` # Rules You may not use external libaries, only tools of the language itself are allowed. Only the bytes of the source code count... not the sound file. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! ### EDIT: **Example output:** So something like this would be the output for *120 bps*: [link](http://www.mediafire.com/listen/5d12f62gvzn2p92/metronome-example.wav) [Answer] ## Mathematica, 26 bytes ``` Pause[Beep[];60/#]~Do~∞& ``` `Do` is normally used as a "for" loop in the narrowest sense: repeat this piece of code for each `i` from `x` to `y`... or even just repeat this piece of code `n` times. Instead of a number `n` we can give it infinity though to create an infinite loop. The loop body is `Pause[Beep[];60/#]` which is just a golfy way of writing `Beep[];Pause[60/#]` where `#` is the function argument. If it's admissible for the solution to blow up the call stack eventually, we can save one byte with a recursive solution: ``` #0[Beep[];Pause[60/#];#]& ``` [Answer] # Pyth, ~~11~~ ~~10~~ 9 bytes *Thanks to [Adnan](https://codegolf.stackexchange.com/questions/69927/building-a-metronome/69943?noredirect=1#comment171002_69943) for reminding me about `#`.* ``` #C7.dc60Q ``` Forever (`#`), print `C`har code `7`. Then sleep (`.d`) `60` seconds divided by (`c`) input (`Q`). [Answer] # JavaScript, ~~36 45 42 41~~ 34 bytes *Saved 1 byte thanks to @RikerW* *Saved 1 byte thanks to @ETHproductions* ``` n=>{for(;;sleep(60/n))print("\7")} ``` This is a function. If I use ``\7``, SpiderMonkey complains octal literals are deprecated. ## Alternative, 31 bytes ``` n=>{for(;;sleep(60/n))print``} ``` The problem is the unprintables are stripped but this should work. [Answer] # Bash, ~~53~~ ~~55~~ 41 bytes Thanks to @Dennis for shaving off *14 bytes*1 Okay, truth time: I'm terrible at golfing bash. Any help would be so very appreciated. ``` echo " ";sleep `bc -l<<<60/$1`;exec $0 $1 ^ That's ASCII char 7 ``` 1 Holy crap. No wonder nobody can outgolf Dennis. [Answer] # JavaScript ES6 (browser), 43 bytes This may be stretching the rules: ``` x=>setInterval('new Audio(1).play()',6e4/x) ``` Give this function a name (e.g. `F=x=>...`) and enter it in the browser console on [this page](http://ethproductions.github.io/b.html). Then call the function with your bps, e.g. `F(60)`, and wait for the magic to happen. :-) Why does this work? Well, `b.html` is in the same folder as a file named `1`, which is the sample sound file from the OP. I'm not sure if this is within the rules (I guess it's like the shell version; it needs to be run in a specific environment), but it was worth a shot. ### Safer version, 57 bytes If the above code isn't allowed for some reason, try this instead: ``` x=>setInterval('new Audio("//ow.ly/Xrnl1").play()',6e4/x) ``` Works on any page! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes Code: ``` I60s/[7ç?D.etime.sleep(#.pop()) ``` If I had a built-in for waiting N seconds, this could have been 11 bytes. Unfortunately, this is not the case. Here is the explanation: ``` I # Push input 60 # Push 60 s # Swap the top 2 items / # Divide the top 2 items [ # Infinite loop 7ç # Push the character \x07 ? # Output it, which give a sound .e # Evaluate the following as Python code time.sleep( ) # Wait for N seconds # # Short for stack .pop() # Pop the last item ``` Uses the ISO 8859-1 encoding. [Answer] # osascript, 39 bytes ``` on run a repeat beep delay 60/a end end ``` There is literally a command called beep? Sweeeet! Runnable only on Mac OS X due to restricted license, but to run, do: ``` osascript -e "on run a repeat beep delay 60/a end end" bpm ``` [Answer] # Python, 68 67 57 bytes *Saved 1 byte thanks to @FlagAsSpam* *Saved 9 bytes thanks to @Adnan* ``` import time a=input() while 1:print"\7";time.sleep(60./a) ``` Also it took 2 bytes less after converting line endings to UNIX format. Older version, that actually takes bpm as command line argument (66 bytes): ``` import sys,time while 1:print"\7";time.sleep(60./int(sys.argv[1])) ``` [Answer] ## [AutoIt](http://autoitscript.com/forum), 56 bytes ``` Func _($0) While Sleep(6e4/$0) Beep(900,99) WEnd EndFunc ``` [Answer] # Vitsy, 14 bytes ``` a6*r/V1m <wVO7 ``` Verbose mode (interpreter coming soon): ``` 0: // a6*r/V1m push a; // 10 push 6; multiply top two; // 60 reverse stack; // bpm on top divide top two; // bpm/60 save/push permanent variable; push 1; goto top method; // goes to 1 1: // <wVO7 go backward; // infinite loop, from the bottom of 1 wait top seconds; save/push permanent variable; // pushes the bpm in terms of seconds of delay output top as character; push 7; ``` Basically, I use the `w` operator to wait a certain number of seconds as specified by `bpm/60`, wrapped in an infinite loop. Then, I make noise with the terminal output of ASCII character 7 (`BEL`). [Answer] # C#, 118 bytes ``` class A{static int Main(string[]a){for(;;System.Threading.Thread.Sleep(60000/int.Parse(a[0])))System.Console.Beep();}} ``` Basic solution. [Answer] # Java, ~~103~~ 82 bytes Thanks to @Justin for shaving off 21 bytes! Oh, geez. ``` void x(int b)throws Exception{for(;;Thread.sleep(60000/b))System.out.print('\7');} ``` Method and golfed version of the sample program. [Answer] ## [GMC-4](https://en.wikipedia.org/wiki/GMC-4) Machine Code, 21.5 bytes The GMC-4 is a 4-bit computer by a company called Gakken to teach the principles of assembly language in a simplified instruction set and computer. This routine takes input in data memory addresses `0x5D` through `0x5F`, in big-endian decimal (that is, one digit per nibble). The algorithm is basically adding the input to memory and waiting 0.1s, until it's at least 600, and then subtracting 600 and beeping, in an infinite loop. Since the GMC-4 has a bunch of register swap functions but no register *copy* functions, this is done the hard way. In hex (second line is position in memory): ``` A24A14A04 80EC AF5A2EF AE5A1EF AD5A0EF 8A6 F2AF09 86ADEEE9F09 012345678 9ABC DEF0123 4567890 ABCDEF0 123 456789 ABCDEF01234 ``` In assembly: ``` tiy 2 ;ld y, 0x2 AM ;ld a, [0x50 + y] tiy 1 AM tiy 0 AM start: tia 0 ;ld a, 0x0 cal timr ;pause for (a+1)*0.1 seconds tiy F MA ;ld [0x50 + y], a tiy 2 cal DEM+ ;add a to [0x50 + y]; convert to decimal and carry. tiy E ;do the same for the second digit MA tiy 1 cal DEM+ tiy D ;and the third. MA tiy 0 cal DEM+ tia A M+ jump beep jump start beep: tia 6 tiy D cal DEM- cal SHTS ;'play short sound' jump start ``` *Disclaimer:* I don't actually own a GMC-4. I've meticulously checked this program with documentation from online, but I may have made a mistake. I also don't know the endianness. It looks like the GMC-4 is big-endian, but I'm not sure. If anyone owns a GMC-4 and can verify this/tell me the endianness of the GMC-4, I'd much appreciate it. [Answer] ## C, 48 bytes ``` void f(int b){while(printf(""))Sleep(60000/b);} ^ literal 0x07 here ``` A Windows-only solution (Sleep() function, to be specific). I also (ab)used the fact that printf() returns the number of characters printed to use it as infinite loop condition. There IS a character between double-quotes in printf() call, but it is not displayed here for some reason. If in doubt, copy and paste into Sublime Text 2 or Notepad++, the character will be displayed as `BEL`. This started as a C++ solution but it kinda fell into the C-subset of C++ (because, you know, `Sleep()` is a bit shorter than `std::this_thread::sleep_for(std::chrono::milliseconds())`) and `printf()` is shorter than `std::cout<<`). [Answer] ## AppleScript 94 bytes I know I'm pretty late, and this is my first post here, but whatever. ``` display dialog""default answer"" set x to 60000/result's text returned repeat beep delay x end ``` Ungolfed: ``` display dialog "" default answer "" set x to 60000 / (result's text returned) repeat beep delay x end repeat ``` [Answer] # VBScript, ~~113~~ 66 bytes ``` a=InputBox("") Do WScript.Echo(Chr(7)) WScript.Sleep(60000/a) Loop ``` This program is simple enough; it takes input, echoes the BEL character, and waits. Thanks to Niel for shaving off almost half the program! [Answer] # Ruby, ~~37~~ 33 bytes ``` m=->b{loop{puts"\7" sleep 6e1/b}} ``` Pretty straightforward. This is a lambda function. If you wanted 60 bpm, you'd do: `m[60]`. [Answer] # Japt, 30 bytes ``` 6e4/U i`?w Au¹o('../1').play() ``` The `?` should be the literal byte `9A`. [Test it online!](http://ethproductions.github.io/japt?v=master&code=NmU0L1UgaWCadyBBdblvKCcuLi8xJykucGxheSgp&input=NjA=) (Sorry about the pop-up delaying the first few beats; this will be removed soon.) ### How it works ``` 6e4/U i"new Audio('../1').play() // Implicit: U = input bps 6e4/U // Calculate 60000 / U. i // Set a timed event every that many milliseconds, "new Audio('../1').play() // running this code every time. // ../1 is the path to the file used in my JS entry. ``` [Answer] # Mumps, 18 bytes ``` R I F H 60/I W *7 ``` Read the BPM into variable I, then F {with two spaces after} is an infinate loop. Halt for 60 seconds / BPM, then write $CHR(7) {Ascii: BEL} to standard output, giving the audio output required, then restart at the infinite loop. [Answer] # Java, 321 chars Sounds very good. Works only on systems with MIDI support. ``` import javax.sound.midi.*;import java.util.*;class A{public static void main(String[] a) throws Exception{int d=new Scanner(System.in).nextInt();Synthesizer b=MidiSystem.getSynthesizer();b.open();MidiChannel c=b.getChannels()[0];c.programChange(116);while(true){c.noteOn(0,100);Thread.sleep((int)(d/.06));c.noteOff(0);}}} ``` . [Answer] # [ChucK](http://chuck.cs.princeton.edu/), 90 bytes White noise that is turned on and off every two ticks. ``` 60./Std.atoi(me.arg(0))*1000=>float s;while(1){Noise b=>dac;s::ms=>now;b=<dac;s::ms=>now;} ``` # Explanation ``` 60./Std.atoi(me.arg(0)) //Convert the input to an int and divide 60 by it *1000 //Multiply by 1000 (in order to avoid s::second) =>float s; //Store it as a float in variable s while(1) //Forever, {Noise b=>dac; //Connect a noise generator b to the audio output s::ms=>now; //Wait for s milliseconds b=<dac; //Disconnect b from the audio output s::ms=>now;} //Wait for s milliseconds ``` This is made to turn on the sound on a beat, then turn it off on the beat after. # ~~98~~ 93 byte version (fancier) White noise played for 10 milliseconds per tick. ``` 60./Std.atoi(me.arg(0))*1000-9=>float s;while(1){Noise b=>dac;10::ms=>now;b=<dac;s::ms=>now;} ``` This is made to be a click instead of constant noise being turned on and off. [Answer] # Perl 5, 36 bytes ``` {{$|=print"\a";sleep 60/$_[0];redo}} ``` A subroutine; use it as ``` sub{{$|=print"\a";sleep 60/$_[0];redo}}->(21) ``` [Answer] # Jolf, 7 bytes, noncompeting I added sounds after this very fine challenge was made. ``` TΑa/Αaj T set an interval Αa that plays a short beep (Α is Alpha) /Αaj every 60000 / j (the input) seconds. (Αa returns 60000) ``` If you so desire to clear this sound, take note of the output. Say that number is `x`. Execute another Jolf command `~CP"x"`, and the interval will be cleared. [Answer] # [Zsh](https://www.zsh.org/), 32 bytes ``` <<<$'\a' sleep $[60./$1] . $0 $1 ``` Based on the leading bash answer, but `source`s instead of `exec`s. The TIO link sources `$0:a` because of how the original file is executed, but it will work without it. [Try it online!](https://tio.run/##qyrO@P/fxsZGRT0mUZ2rOCc1tUBBJdrMQE9fxTCWS09BxcAqUUHF8P///4ZGBgA "Zsh – Try It Online") [Answer] # Stax, 17 bytes ``` ü7»♥O╚⌂╥☻≈OyM╜Δ∩` ``` or, unpacked: ``` 4|A48*x/W2|A]pc{| }* ``` The program outputs bytes that, when fed through the command line tool aplay with default setting, produce a metronome noise. The input is used as bpm example: ``` example-stax-interpreter metronome.stax -i "60" | aplay ``` You should hear a horrible beeping noise at the desired bpm [Answer] # Bash + bc + [><>](https://esolangs.org/wiki/Fish), 44 bytes Playing on the fact that the ><> interpreter lets you define a tick time : ``` python fish.py -t $(bc -l<<<"2/$1/60") -c 7o ``` The ><> code is `7o` and should output the `BEL` character, producing a system beep. It will loop until interrupted. The `-t` value is set to (2 / RPM ) / 60 so that the whole code is played RPM \* 60 times per second. [Answer] # SmileBASIC, 26 bytes ``` INPUT B$BGMPLAY@8T+B$+"[C] ``` It can play any general midi instrument, though anything above 9 will use more bytes. ]
[Question] [ In honor of how much rep I had several hours ago, when I first thought of this challenge: [![enter image description here](https://i.stack.imgur.com/HftMG.png)](https://i.stack.imgur.com/HftMG.png) Numbers like this that are made up of a single digit repeating are called [repdigits](https://en.wikipedia.org/wiki/Repdigit). Repdigits are fun! Every body would be more happy if the amount of rep they had was a repdigit[¹](https://xkcd.com/285/), but I am impatient, so you need to help me find out the fastest way to get to a repdigit. Here is your challenge: Given a positive integers representing reputation, output the minimum amount of rep they need to *gain* to get to a repdigit. For example, at the time of writing this challenge, user [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) had 102,856 rep. The nearest rep-digit is 111,111, so he would need to gain: 8255 rep to be at a repdigit. Since people dislike losing rep, we will only consider non-negative changes. This means that, for example, if someone is at 12 rep, rather than losing 1 rep, the solution is to gain 10 rep. This allows '0' to be a valid output, since anyone who has 111 rep is *already* at a repdigit. Input and output can be in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and since it is impossible to have less than 1 rep on any Stack Exchange site, you can assume no inputs will be less than 1. One cornercase to note: If a user has less than 10 rep, they are already at a repdigit, and so they also need '0'. # Test IO: ``` #Input #Ouput 8 0 100 11 113 109 87654321 1234567 42 2 20000 2222 11132 11090 ``` Standard loopholes apply, and the shortest solution in bytes wins! [Answer] # Haskell, 39 bytes ``` until(((==).head>>=all).show)(+1)>>=(-) ``` [Try it online](http://ideone.com/fork/Xz4qy3) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 9 bytes ``` :.#++#==, ``` [Try it online!](http://brachylog.tryitonline.net/#code=Oi4jKysjPT0s&input=ODc2NTQzMjE&args=Wg) This is pretty efficent as it makes use of constraints arithmetic. ### Explanation ``` :. The list [Input, Output]. #+ Both elements must be positive or zero. + The sum of those two elements… #= …must result in an integer where all digits are the same. =, Assign a value that matches those constraints. ``` [Answer] # Python 2, ~~41~~ 40 bytes ``` def f(n):r=10**len(`n`)/9;print-n/r*-r-n ``` Not the shortest approach, but very efficient. Test it on [Ideone](http://ideone.com/KEo0kt). ### How it works For input `10**len(`n`)` rounds **n** up to the nearest power of **10**. Afterwards, we divide the result by **9**. This returns the repdigit **1…1** that has as many digits as **n**. We save the result in **r**. For example, if **n = 87654321**, then **r = 11111111**. The desired repdigit will be a multiple or **r**. To decide which, we perform ceiling division of **n** by **r**. Since Python 2's division operator `/` floors, this can be achieved with `-n/r`, which will yield the correct absolute value, with negative sign. For example, if **n = 87654321**, this will return **-8**. Finally, we multiply the computed quotient by **-r** to repeat the quotient once for each digit in **n**. For example, if **n = 87654321**, this returns **88888888**, which is the desired repdigit. Finally, to calculate the required increment, we subtract **n** from the previous result. For our example **n = 87654321**, this returns **1234567**, as desired. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DE$1#_ ``` Output is a singleton array. [Try it online!](http://jelly.tryitonline.net/#code=REUkMSNf&input=&args=MTEz) or [verify most test cases](http://jelly.tryitonline.net/#code=REUkMSNfCjsiw4figqxH&input=&args=OCwgMTAwLCAxMTMsIDQyLCAyMDAwMCwgMTExMzI). Test case **87654321** is too slow for TIO. ### How it works ``` DE$1#_ Main link. Argument: n 1# Call the link to the left with argument k = n, n + 1, n + 2, etc. until one match is found, then return the matching k. $ Combine the two links to the left into a monadic chain. D Convert k to base 10. E Test if all decimal digits are equal. _ Subtract n from the result. ``` [Answer] # Python 2, 37 bytes ``` f=lambda n:1-len(set(`n`))and-~f(n+1) ``` Test it on [Ideone](http://ideone.com/1rF6OB). Note that this approach is too inefficient for test case **87654321**. ### How it works If **n** is already a repdigit, `1-len(set(`n`))` will return **0** since the length of the set of **n**'s digits in base 10 will be **1**. In this case, **f** returns **0**. If **n** is not a repdigit, `f(n+1)` recursively calls **f** with the next possible value of **n**. `-~` increments the return value of **f** (**0** when a repdigit is found) by **1** each time **f** is called recursively, so the final return value equals the number of times **f** has been called, i.e., the number of times **n** had to be incremented to get a repdigit. [Answer] # [Perl 6](http://perl6.org/), 23 bytes ``` {($_...{[==] .comb})-1} ``` A lambda that takes the input number as argument, and returns the result. Explanation: 1. Uses the `...` sequence operator to increment the input number until it reaches a repdigit *(tested by splitting its string representation into characters and seeing if they're all equal)*. 2. Subtracts one from the length of the sequence. [Answer] # Java 7, ~~116~~ 76 bytes ``` int c(int i){int r=(int)Math.pow(10,(i+"").length())/9;return(-i/r-1)*-r-i;} ``` Used [*@Dennis*' amazing approach](https://codegolf.stackexchange.com/a/90900/52210) to lower the byte-count by a whopping 40 bytes. **Ungolfed & test cases:** [Try it here.](https://ideone.com/febPRq) ``` class Main{ static int c(int i){ int r = (int)Math.pow(10, (i+"").length()) / 9; return (-i / r - 1) * -r - i; } public static void main(String[] a){ System.out.println(c(8)); System.out.println(c(100)); System.out.println(c(113)); System.out.println(c(87654321)); System.out.println(c(42)); System.out.println(c(20000)); System.out.println(c(11132)); } } ``` **Output:** ``` 0 11 109 1234567 2 2222 11090 ``` [Answer] # Pyth, ~~9~~ ~~8~~ 7 bytes *1 byte thanks to @FryAmTheEggman.* ``` -f@F`TQ ``` [Try it online.](http://pyth.herokuapp.com/?code=-f%40F%60TQ&input=113) Very inefficient, loops through all numbers from the input to the next repdigit. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~690~~ 358 bytes Here's my go at it ``` (({})[()])(()){{}(({}())){(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>{(([])<{{}({}[()]<>)<>([])}{}><>){({}[()]<({}<>)<>>)}{}<>}([]){{}{(<({}<>)<>>)}{}([])}{}<>(([][()()])<{{}{}([][()()])}{}>)}{}({}[{}]) ``` [Try It Online](http://brain-flak.tryitonline.net/#code=KCh7fSlbKCldKSgoKSl7e30oKHt9KCkpKXsoKHt9KSkoPCgoKCkoKSgpKCkoKSl7fTw-KT4pPD57KHt9WygpXSk8Pigoe30oKVsoe30pXSkpe3t9KDwoe30oe30pKT4pfXt9PD59e308Pih7fTx7fT4pPD4oPCgoKCkoKSgpKCkoKSl7fSg8PikpPik8Pnsoe31bKCldKTw-KCh7fSgpWyh7fTwoe30oKSk-KV0pKXt7fSg8KHt9KHt9PCh7fVsoKV0pPikpPil9e308Pn17fTw-e317fSh7fTw-KX17fTw-eygoW10pPHt7fSh7fVsoKV08Pik8PihbXSl9e30-PD4peyh7fVsoKV08KHt9PD4pPD4-KX17fTw-fShbXSl7e317KDwoe308Pik8Pj4pfXt9KFtdKX17fTw-KChbXVsoKSgpXSk8e3t9e30oW11bKCkoKV0pfXt9Pil9e30oe31be31dKQ&input=MTEy) ### Explanation Start by making a second copy of the input that is one less than the original. We will use the copy to search for the next repdigit. We subtract one in case the number itself was a repdigit ``` (({})[()]) ``` Push one to satisfy the coming loop. (doesn't have to be one just not zero) ``` (()) ``` This loop will run until there is a repdigit on top of the stack ``` { ``` Pop the crap. Their is a "boolean" on top that drives the loop, since it is no longer needed we pop it. ``` {} ``` Add one and duplicate the top. The copy will be decomposed into its digits. ``` (({}())) ``` While the copy is not zero... ``` { ``` Copy again ``` (({})) ``` Mod 10 and move to the other stack ``` (<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<> ``` Divide by 10 (Integer division) ``` (<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>) } ``` Pop the zero that was our copy ``` {} ``` We have now decomposed the number into its base 10 digits, So we swap over to the stack with all the digits. ``` <> ``` While the leading digit is not zero ``` { ``` We pick up a copy of the stack height (i.e. the number of digits)... ``` (([])< ``` Silently subtract one from every number on the stack ``` { {} ({}[()]<>)<> ([]) } {} ``` Put the stack height we picked up down. (and swap to the other stack) ``` ><>) ``` We use the stack height to pull all the digits we placed on the other stack back onto the proper stack. ``` { ({}[()]<({}<>)<>>) } ``` Pop the zero that was our stack height ``` {} ``` Swap back onto the stack with the digits (or what were the digits) ``` <> ``` End loop ``` } ``` Now we have subtracted the top digit from all the other digits. If all the digits are zero the orginal number (not the input but the number we are checking) was a repdigit.[citation needed]. So we need to check for non-zeroes. While the stack height is not zero ``` ([]) { {} ``` If the digit is not zero move it to the other stack and replace it with a zero. ``` { (<({}<>)<>>) } ``` Pop it (now it is a zero) ``` {} ``` End loop ``` ([]) } {} ``` Swap over onto the other stack (duh..) ``` <> ``` Grab our selves a copy of the stack height minus two ``` (([][()()])< ``` While the stack height is not two (the original and the accumulator) ``` { {} ``` Pop the top ``` {} ``` End the while ``` ([][()()]) } {} ``` Put down our copy of the stack height minus two. This ends up being the number of digits that are not the same as the first digit. In other words if it is zero it is a repdigit. ``` >) ``` If this loop ends we have found a repdigit ``` } ``` Pop the "boolean" ``` {} ``` Subtract the original from the repdigit ``` ({}[{}]) ``` [Answer] # Python 2, 52 bytes ``` a=b=input() while len(set(str(a)))!=1:a+=1 print a-b ``` Python 2 has several tricks that make this shorter. For example, input is numeric, so we don't need to cast to int. (-5 bytes) We also don't need to put parenthesis around the `a-b` (-1 byte) Use this script to verify all test cases: ``` def f(i): a=b=i while len(set(str(a)))!=1:a+=1 return a-b inputs = [8, 100, 113, 87654321, 42, 20000, 11132] outputs = [0, 11, 109, 1234567, 2, 2222, 11090] for i in range(len(inputs)): print(f(inputs[i]) == outputs[i]) ``` You may also [try it online!](https://ideone.com/7ZVxZq) [Answer] ## GNU sed, 223 + 1(r flag) = 224 bytes ``` s/$/:0%/ :;y/:%/%:/ /^(.)\1*%/{s/.*%(.*):/\1/;q} :f;s/9(@*:)/@\1/;tf s/8(@*:)/9\1/;s/7(@*:)/8\1/ s/6(@*:)/7\1/;s/5(@*:)/6\1/ s/4(@*:)/5\1/;s/3(@*:)/4\1/ s/2(@*:)/3\1/;s/1(@*:)/2\1/ s/0(@*:)/1\1/;s/(^|%)(@*:)/\11\2/ y/@/0/;t ``` **Run:** ``` sed -rf repdigit.sed <<< "112" ``` **Output:** ``` 110 ``` This is a **pure sed solution**, the arithmetic is simulated using regular expressions only. The algorithm works as follows: 1. the pattern space format is set to `^current_reputation:needed_reputation%$` 2. in each iteration of the main loop the separators are switched: a) `%:` applies the increment to *needed\_reputation* b) `:%` applies the increment to *current\_reputation* 3. if the *current\_reputation* is a "repdigit", the *needed\_reputation* is printed and the program ends [Answer] ## Excel, ~~85~~ 79 bytes Put the following formula in any cell except cell `N` since it's a name for reference cell of input: ``` =IF(1*(REPT(LEFT(N),LEN(N)))<N,REPT(LEFT(N)+1,LEN(N))-N,REPT(LEFT(N),LEN(N))-N) ``` Explanation: * `N` is the input and also [name of reference cell](https://support.office.com/en-us/article/Define-and-use-names-in-formulas-4d0f13ac-53b7-422e-afd2-abd7ff379c64). * `LEFT(N)` take the first digit of input value. * `LEN(N)` return the length of input value. * `REPT(LEFT(N),LEN(N))` repeat the first digit of input value `LEN(N)` times and multiply it by 1 to convert text format to number format so we can use it for number comparison. * The syntax for the IF function in Microsoft Excel is: **IF( condition, [value\_if\_true], [value\_if\_false])**, hence makes the whole formula is self-explanatory. [Answer] ## PowerShell v2+, 66 bytes ``` param($n)for($x=+"$($n[0])";($y="$x"*$n.length)-lt$n;$x++){}+$y-$n ``` The usually-good-for-golf very loose casting of PowerShell is a major downfall here. Takes input `$n` as a string, and enters a `for` loop. For the setup step, we extract out the first character `$n[0]`, but have to convert it back to a string `"$(...)"` before casting as an int `+` and saving into `$x`. Otherwise, the later arithmetic will be using the ASCII value of the char-code. The conditional checks whether a string constructed from `$n.length` `"$x"`s, temporarily stored in `$y`, is less-than `$n`. So long as it's not, we increment `$x++`, setting up the conditional for the next loop. For example, for input `123`, the value of `$y` when the conditional is first checked will be `111`, which is less-than `$n`, so the loop continues. There's nothing in the loop body, so the step increment happens `$x++`, then the conditional is checked again. This time `$y` equals `222`, which is greater than `$n`, so the loop terminates. If the input is already a repdigit, the conditional is not satisfied, because at that point `$y` is equal to `$n`. Once out of the loop, we cast `$y` to an integer `+`, then subtract `$n`. That result is left on the pipeline and output is implicit. [Answer] # Java, ~~74~~ 72 bytes ``` int c(int i){int n=0;while(!(i+++"").matches("^(.)\\1*$"))n++;return n;} ``` *(If [the other Java entry](https://codegolf.stackexchange.com/a/90903/14150) is 76 bytes, this one is ~~74~~ 72, since it's ~~two~~ four bytes shorter).* Anyway, just increment the input until it's a repdigit while incrementing a counter. Return the counter. Yes, those are three pluses in a row, two to increment the input, one to concatenate an empty string to make it a string. No, I didn't think it would be legal without a space in between either, but there you go. That's what a typo will do for you: one byte shorter. Using a for-loop instead of a while takes exactly as many bytes: ``` int c(int i){int n=0;for(;!(i+++"").matches("^(.)\\1*$");n++);return n;} ``` --- ## *Edit:* *An earlier version had `matches("^(\\d)\\1*$")` to check for a repdigit, but since we've just converted an int to a string, using a `.` to match is enough.* --- **Ungolfed & test cases:** [Try it here.](https://ideone.com/WxwK24) ``` class Main{ static int c(int i){ int n=0; while(!(i++ + "").matches("^(.)\\1*$")) { n++; } return n; } public static void main(String[] a){ System.out.println(c(8)); System.out.println(c(100)); System.out.println(c(113)); System.out.println(c(87654321)); System.out.println(c(42)); System.out.println(c(20000)); System.out.println(c(11132)); } ``` } **Output:** ``` 0 11 109 1234567 2 2222 11090 ``` [Answer] # R, ~~102~~ ~~98~~ 91 bytes ``` a=scan(,'');i=0;while(length(unique(strsplit(a,"")[[1]]))!=1){a=paste(strtoi(a)+1);i=i+1};i ``` **Ungolfed :** ``` a=scan(,'') #Asks for input i=0 #Initialize i to 0, surprisingly while(length(unique(strsplit(a,"")[[1]]))!=1) #Splits the input into its digits, #compute the length of the vector created by the function `unique`, which gives all the digits once. #as long as the this length is different from one : { a=paste(strtoi(a)+1) #Increases by one the value of the input (while messing around with its format) i=i+1 #Increases by one the value of the counter } i #Outputs the counter ``` Messing around with the format (~~`as.numeric` and `as.character`~~) adds some bytes, but **R** is not really flexible ! [Answer] ## Perl, 40 + 1 (`-n`) = 41 bytes ``` /^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo ``` If printing nothing instead of `0` when the number is already a repdigit is acceptable, then 37 bytes are enough : ``` /^(.)\1*$/&&say$v or$_++&&++$v&&redo ``` Run with `-n` (1 byte) and `-E` or `-M5.010` (free) : ``` perl -nE '/^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo' ``` **Explanations** : there are two major parts in the code : `/^(.)\1*$/&&say$v` and `$_++&&++$v&&redo`. The first one test if `$_` is a repdigit; if yes it prints the number we added to the original number to make it a repdigit (`$v`), and if no, we had 1 to both `$_` and `$v`, and start over. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 6 bytes ``` ∞.Δ+Ë ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTtA93//9vaGhobAQA "05AB1E – Try It Online") **Explanation** ``` ∞< # from the infinite list of non-negative integers .Δ # find the first number where Ë # all digits are equal + # after adding the input ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes ``` λ?+≈;ṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%3F%2B%E2%89%88%3B%E1%B9%85&inputs=113&header=&footer=) [Answer] ## Pyke, ~~13~~ 11 bytes ``` o+`}ltIr)ot ``` [Try it here!](http://pyke.catbus.co.uk/?code=o%2B%60%7DltIr%29ot&input=13&warnings=0) ``` - o = 0 o+ - o++ + input ` - str(^) } - deduplicate(^) lt - len(^)-1 I ) - if ^: r - goto_start() ot - o++ -1 ``` [Answer] ## Actually, 15 bytes ``` ;D;WXu;$╔l1<WX- ``` [Try it online!](http://actually.tryitonline.net/#code=O0Q7V1h1OyTilZRsMTxXWC0&input=MTAw) Explanation: ``` ;D;WXu;$╔l1<WX- ; dupe D; decrement, dupe WXu;$╔l1<W while top of stack is truthy: X discard u increment ; dupe $╔l1< 1 if len(str(TOS)) > 1 else 0 (check if the string representation of the TOS contains only one unique digit) after the loop, the stack will be [1 repdigit input] X discard - subtract input from repdigit ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 20 bytes ``` p < )\&&&~j<i ->N>u0 ``` [Try it online!](http://jellyfish.tryitonline.net/#code=cAo8CilcJiYmfmo8aQotPk4-dTA&input=MTExMzI) TIO can't handle the longer test cases, but given enough time and memory, they should work too. ## Explanation * `i` is input, and `<` decrements it. This value is fed to the function on the left. * `\>` increments the value (at least once) until the function to the right gives a truthy value. * The test function is a composition (by `&`s) of four functions. * `0~j` converts to string. * `u` removes duplicate digits. * `>` removes the head of the resulting string. * `N` is logical negation: it gives `1` for an empty string, and `0` for non-empty. Thus the function tests for a rep-digit, and the result of `\` is the next rep-digit counting from `<i`. * `)-` subtracts the result from the function input, that is, `<i`. * This difference is off by one, so `<` decrements it. Finally, `p` prints the result. [Answer] # PHP 5.6, ~~59~~ ~~53~~ ~~51~~ 50 bytes Saved ~~6~~ 8 bytes thanks to @manatwork. ``` while(count_chars($argv[1]+$b,3)[1])$b++;echo$b?:0 ``` Test with: ``` php test.php 11132 ``` The `count_chars()` function with 3 as the second parameter returns a string with the distinct characters in a string. When this string is 1 character long (`[1]` will return false when it's length 1) then echo `$b`, otherwise increment `$b` and loop again. [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` q`QtVda}G- ``` [Try it online!](http://matl.tryitonline.net/#code=cWBRdFZkYX1HLQ&input=MTEz) This keeps incrementing the input until all digits are equal, so it's slow. The test case for input `87654321` times out in the online compiler. ``` q % Take input implicitly. Subtract 1 ` % Do...while loop Q % Increment top of the stack tV % Duplicate and convert to string (i.e. digits of the number) d % Difference between consecutive digits a % True if any such difference is nonzero. This is the loop condition } % Finally (execute on loop exit) G- % Subtract input. This is the final result, to be (implicitly) displayed % End loop implicitly. If loop condition (top of the stack) is truthy: proceeds % with next iteration. Else: executes the "finally" block and exits loop % Display implicitly ``` [Answer] # Java, 59 bytes ``` int c(int i){return(i+"").matches("^(.)\\1*$")?0:c(i+1)+1;} ``` *(I'm still not sure how to count Java entries, but according to the standard set by [the first Java entry](https://codegolf.stackexchange.com/a/90903/14150), this entry is 59 bytes, since it's 17 bytes shorter).* Anyway, if we have a repdigit, return 0, else add 1 to the input, call itself and add 1 to the result. --- **Ungolfed & test cases:** [Try it here.](https://ideone.com/ls3LWd) ``` class Main{ static int c(int i) { return (i+"").matches("^(.)\\1*$") ? 0 : c(i+1) + 1; } public static void main(String[] a){ System.out.println(c(8)); System.out.println(c(100)); System.out.println(c(113)); System.out.println(c(42)); System.out.println(c(20000)); System.out.println(c(19122)); // Entry below will run out of memory System.out.println(c(19121)); } } ``` **Output:** ``` Runtime error time: 0.09 memory: 321152 signal:-1 0 11 109 2 2222 3100 ``` As you can see, the last entry runs out of memory before it can finish. The (very appropriate) `StackOverflowError` is thrown from `java.util.regex.Pattern.sequence(Pattern.java:2134)`, but I'm pretty confident there's nothing wrong with the regex itself, since it's the same one I used in [my previous entry](https://codegolf.stackexchange.com/a/90960/14150). [Answer] # Ruby, 42 characters ``` ->n{i=0;n.next!&&i+=1while n.squeeze[1];i} ``` Expects string input. Sample run: ``` irb(main):019:0> ->n{i=0;n.next!&&i+=1while n.squeeze[1];i}['87654321'] => 1234567 ``` ## Ruby, 39 characters Recursive call, runs into “SystemStackError: stack level too deep” on bigger results. ``` r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i} ``` Sample run: ``` irb(main):001:0> r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i} => #<Proc:0x00000002367ca0@(irb):10 (lambda)> irb(main):002:0> r['20000'] => 2222 ``` [Answer] ## Matlab, ~~65~~ 64 bytes ``` t=input('');i=0;while nnz(diff(+num2str(t+i))) i=i+1;end disp(i) ``` Because of the while loop it's rather slow... **Explanation** ``` t=input('') -- takes input i=0 -- set counter to 0 while num2str(t+i) -- convert number to string + -- and then to array of corresponding ASCII codes diff( ) -- produce vector of differences (all zeros for 'repdigit') nnz( ) -- and count non-zero entries i=i+1 -- while not all digits are the same increase the counter end -- end while loop disp(i) -- print the counter ``` *Saving one byte thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo).* [Answer] ## JavaScript (ES6), 42 bytes ``` f=(n,p=1)=>n<p?-~(n*9/p)*~-p/9-n:f(n,p*10) ``` Explanation: Recursively computes `p` as the next power of `10` after `n`. The digit to be repeated is then computed as `1+floor(9n/p)`, and the repunit is simply `(p-1)/9`, from which the result follows. [Answer] ## Prolog, 120 bytes ``` r([H|T]):-r(H,[H|T]). r(H,[H|T]):-r(H,T). r(_,[]). g(N,0):-number_chars(N,L),r(L). g(N,X):-N1 is N+1,g(N1,X1),X is X1+1. ``` [Try it online!](http://swish.swi-prolog.org/p/PCG%3Arepdigit.pl) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 6 bytes ``` ;.+=∧ℕ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpgggXwPIs47QLlfSVHq4q7P24dYJ/631tG0fdSx/1DL1//9oCx1DAwMdQ0NjHQtzM1MTYyNDHRMjHSMDA7CoobFRLAA "Brachylog – Try It Online") ``` + The sum of the input ; and . the output = is a repdigit, ∧ and the output ℕ is a whole number. ``` The 5-byte [`+↙.=∧`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpgggXwPIs47QLlfSVHq4q7P24dYJ/7Uftc3Us33Usfz//2gLHUMDAx1DQ2MdC3MzUxNjI0MdEyMdIwMDsKihsVEsAA) gets away with omitting `ℕ` because it doesn't try non-positive outputs at all, but it also fails when given a number which is already a repdigit because it doesn't try non-positive outputs at all. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 54 bytes ``` : f 0 over s>f flog f>s 1+ 0 do 10 * 1- loop mod abs ; ``` [Try it online!](https://tio.run/##LYzLDoIwEEX3fMUJSw2kQ1EbSfgXFYsLzDQF/f06JG7OfUzmRs3bq5njLqVciTj0@8ysYyQuOhPHFTlaPSniOCANi2rirRO3@8pgb4npkwi0mbaGZqS2qZZHZqgCqRLndoo3hsv51PtOzPadoXPufxVvmfID "Forth (gforth) – Try It Online") ### Explanation * Gets the smallest repdigit of the same length as the input. * Negates the result and gets the remainder of dividing the input by that number. * Returns the absolute value of the result (since positive modulo negative is negative) ### Code Explanation ``` : f \ start a new word definition 0 over \ place 0 on stack and copy input back to top s>f flog f>s \ move number to floating point stack, get log10, move back to stack (truncate) 1+ \ add 1 to get number of digits 0 do \ start a loop from 0 to number of digits - 1 10 * 1- \ repeatedly multiply by 10 and subtract 1 to get smallest repdigit of that size loop \ end loop mod abs \ get that absolute value of input modulo result ; \ end the word definition ``` ]
[Question] [ Write a program which plays Russian Roulette! If the program is started, * there should be a 5 in 6 chance of it ending normally after printing "I survived!" * there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.) No input, and no other outputs are allowed. The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient. If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score. Shortest code wins, not sooner than 10 days after first valid answer. [Answer] ## PHP 38 bytes ``` <?~$$s[rand(+$s=sssss,5)]?>I survived! ``` Placing a `+` before a non-numeric string will evaluate to `0`. Should `rand(0,5)` return `5`, `$s[rand(0,5)]` will be the empty string (since `$s` is only five characters long), and subsequently `$$s[rand(0,5)]` will be an uninitialized variable. Attempting to take the inversion will halt on Unsupported Operand Type. Any other value, `0-4` will return `s`, and because `$s` is defined, you will survive. Note: as of php version 4.2.0, the random number generator is [seeded automatically](http://php.net/ChangeLog-4.php#4.2.0). [Answer] ## R 30 ``` "I survived!"[6*runif(1)<5||Z] ``` One time out of six, it will throw an error: `Error: object 'Z' not found` [Answer] ## Dyalog APL - 25 22 21 20 Charachters ``` 'I Survived!'⊣1÷6⊤?6 ``` Prints `DOMAIN ERROR` as the error, due to division by zero. Shortest non-division by zero solution I could come up with is 23 characters. ``` ('I Survived!'1)[~6⍷?6] ``` It throws an `INDEX ERROR` [Try it here](http://www.tryapl.org/) [APL Font here](http://wiki.nars2000.org/index.php/APL_Font) [Answer] ## Python, 96 ``` from ctypes import* from random import* randrange(5)or pointer(c_int())[9**9] print'I survived!' ``` If `randrange(5)` returns 0, then python will crash due to a segmentation fault. [Answer] ## Ruby, 24-28 ``` p rand(6)<5?"I survived!":1/0 ``` Approx each 6 time, there is a `ZeroDivisionError` There is even a shorter version with 24 characters (Thanks to ugoren and histocrat): ``` 6/rand(6);p"I survived!" ``` If you don't accept the `"` in the output, then I need 3 more characters. The first option (`puts`) adds a newline, the second (`$><<`) makes no newline: ``` 6/rand(6);puts"I survived!" 6/rand(6);$><<"I survived!" ``` There is a [question about random number in ruby at SO](https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby). The seed with `srand` is automatically called with the seed being from the current time if it wasn't already called. (see [Julians comment](https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby#comment2164872_198486)) --- Primo had the idea for an extra bonus [to those solutions which don't rely on division by zero](https://codegolf.stackexchange.com/questions/9062/russian-roulette/9083#comment17890_9062). My first solution can be shortened (28 characters) with a `undefined local variable or method ``a' for main:Object (NameError)` ``` p rand(6)<5?"I survived!":a ``` [Answer] ## J, 18 ``` 'I survived!'[q:?6 ``` Failing with `domain error` when trying to factorise 0. [Answer] ## vba, 27 ``` ?1/int(6*rnd),"I Survived!" ``` used in immediate window. On failure, an error window stating: ![division by zero](https://i.stack.imgur.com/nnNrR.jpg) appears [Answer] # Befunge - 48 chars ``` v >91+"!devi"v /?>?<v"I surv"< / / : :,_@# ``` Befunge's only randomness is the `?` operator, which sends you heading in one of four posible directions (`1/4` chance). By blocking one or two directions, you have `1/3` or `1/2` chance, and by combining these, you get `1/6` chance to get out of the program "alive". The program crashes by doing a divive-by-zero. I guess it's implementation-specific what will happen (on Wikipedia it says the program should ask for the desired answer), but [befungee.py](https://github.com/programble/befungee) sort of crashes, or exits angrily: ``` $ for i in {1..6} ; do ./befungee.py roulette.befunge ; done Error (1,2): integer division or modulo by zero Error (3,2): integer division or modulo by zero Error (1,2): integer division or modulo by zero I survived! Error (0,1): integer division or modulo by zero I survived! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 6LΩiFë“IЖd! ``` -1 byte thanks to *@Emigna*. 05AB1E actually shouldn't be able to error at all, but since the new version of 05AB1E still has some issues compared to the legacy version, I can take that to my advantage to error out for this challenge. [Try it online.](https://tio.run/##yy9OTMpM/f/fzOfcyky3w6sfNczxPDzhUcPkFMX//wE) **Explanation:** ``` 6L # Create the list [1,2,3,4,5,6] Ω # Get a random choice from this list i # If it is 1: F # Do a ranged loop, which currently results in a "(RuntimeError) Could not # convert to integer." error when no argument is given ë # Else: “IЖd! # Push dictionary string "I survived!" (which is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“IЖd!` is `"I survived!"`. [Answer] ## C, 67 65 62 chars `rand()%8` doesn't lose fairness. Division crashes for `t=0`, gives true for 1 and 2 (retry), gives false for 3..7 (survived). **EDIT:** The previous version used a temporary variable, which ended up completely unneeded. `2/(rand()%8)` implements both needed conditions. ``` main(){ for(srand(time(0));2/(rand()%8);); puts("I survived!"); } ``` [Answer] # T-SQL 56 44 40 + 6 ``` if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!' ``` Credit Sean Cheshire for calling out cast as unnecessary ``` if 1/ceiling(rand()*6-1)<2print'I Survived!' ``` Credit personal message from Sean Cheshire for suggestion to change ceiling to floor. ``` if 1/floor(rand()*6)<1print'I Survived!' ``` Death Err Msg: Msg 8134, Level 16, State 1, Line 3 Divide by zero error encountered. [Answer] Using the usual divide by zero method: Perl 5.8 Version ``` 1/(int rand 6)&&print "I survived!" ``` Perl 5.10 Version ``` 1/(int rand 6)&&say "I survived!" ``` On failure, these will display: ``` Illegal division by zero at -e line 1. ``` Using the bless function which is used for creating objects in perl. Perl 5.8 Version ``` print (int rand 6?"I survived!":bless me); ``` Perl 5.10 Version ``` say (int rand 6?"I survived!":bless me); ``` On failure, these will display: ``` Can't bless non-reference value at -e line 1. ``` [Answer] ## GolfScript, 21 chars ``` ,6rand/;'I survived!' ``` Like most of the answers, this one has a one in six chance of crashing with a ZeroDivisionError. The shortest solution I could manage *without* using division by zero is 23 chars: ``` 5,6rand=+;'I survived!' ``` which has a 1/6 chance of crashing with `undefined method `+' for nil:NilClass (NoMethodError)`. (Ps. While developing this, I found what might be a bug in the GolfScript interpreter: code like `0,1>` appears to leave a `nil` value on the stack, which will later crash the program if you try to do anything with that value except pop it off and throw it away with `;`. Unfortunately, the fact that I do need to use the value somehow to trigger a crash means that even exploiting this bug didn't help me get below 23 chars.) [Answer] ## **Python, 70 characters** With inspiration from grc's answer. ``` from random import* if randrange(5)<1:exec'()'*9**5 print'I survived!' ``` randrange(5) returns a value between 0 and 5. If it returns a 0, Python crashes while attempting to exec(ute) a string of code that contains 9^5 sets of parentheses. [Answer] # PHP - 30 bytes ``` <?rand(0,5)?:~[]?>I survived! ``` Requires PHP 5.4+ for the short array syntax, invalid operator idea shamelessly stolen from @primo. As stated, [`rand()` is automatically seeded on first use](http://lxr.php.net/xref/PHP_5_4/ext/standard/rand.c#63). [Answer] # Befunge, 38 ``` v>25*"!devivrus I",,,,,,,,,,,@ ?^ v ?^ <1 ``` Pretty straight-forward. Crashing is done by pushing 1s onto the stack until it overflows. I made a few attempts at cutting out those 11 commas and replacing them with some more efficient loop to print everything, but couldn't get it under 11 characters. Note that counting characters in Befunge is a little tricky... For instance there's only one character on the third line, but I'm counting an extra one there since execution could travel through that location. [Answer] # Python3.8.10 : 45 ``` int(set('12345 ').pop());print('I survived!') ``` I hope it follows the challenge specification. I did some statistics with this method and it seems to have a uniform probability distribution (the program crashes 10416 times over 60000 calls from the console) [Answer] **Javascript, 42** `(Math.random()*6|0)?alert('i survived!'):b` The bitwise or floors the result of the multiplication thus a value between 0 and 5 results. 0 gets implictly casted to false, so in 5 of 6 cases the alert appears in the 6th case a certain `b` is referenced, crashing the process. [Answer] ## CMD Shell (Win XP or later), 40 +6 I'm only doing this one because DOS is not something that should even be thought of for code golf, and the whitespace is important ``` set/a1/(%RANDOM% %% 6)&&echo I Survived! ``` On failure, it will print > > Divide by zero error. > > > [Answer] # R, 50 44 42 36 ``` ifelse(!is.na(sample(c(NA,1:5),1)),'I Survived!',) ``` ``` ifelse(floor(runif(1,0,5))>0,'I Survived!',) ``` ``` ifelse(floor(runif(1,0,5)),'I Survived!',) ``` ``` ifelse(sample(0:5,1),'I Survived!',) ``` Death Err Message: > > Error in ifelse(!is.na(1/sample(c(NA, 1:5), 1)), "I Survived!", ) : > argument "no" is missing, with no default > > > [Answer] ## Emacs-Lisp, 42 characters ``` (if (= (random 6) 5) z (message "I survived!") ) ``` [Answer] ## Javascript, 40 chars In Javascript the divide-by-zero trick doesn't even work: it just returns Infinity. Therefore, referencing a non-existing variable: ``` alert(6*Math.random()|0?"I survived!":f) ``` Not so short, though fun :) [Answer] **PowerShell, 40 Chars** ``` IF(6/(Get-Random -Max 6)){'I Survived!'} ``` On Failure: "Attempted to divide by zero." [Answer] # Python, 53 bytes Here's a short 53 byte python index out of range program: ``` import time [0][time.time()%6<1] print("I survived!") ``` [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 28 bytes ``` r?<? "< <@,ka"I survived! = ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/v8jexp5LyUbBxkEnO1HJU6G4tKgssyw1RZFLwfb/fwA "Befunge-98 (FBBI) – Try It Online") Errors with a segmentation fault. ## Explanation Befunge-98 adds some extra features (`r`, `k`, and `=`) that can be used to further golf [Joe K's Befunge-93 answer](https://codegolf.stackexchange.com/a/10670/95679). The first line (`r?<?`) calculates the 1/6 chance. The `r` initially reflects the IP to the left, where it reaches the second `?` and goes in a random direction. If it goes right, the `r` reflects it and it tries again. If it goes up or down, it moves onto the second line, and if it goes left, it moves onto the first `?`. There are three ways the IP can leave, so there is a 1/3 chance it moves onto the first `?`. If it gets there, it again goes in a random direction. If it goes horizontally, it gets reflected (with either `r` or `<`) and tries again. This means that there are only two ways that the IP can leave, and they are equally likely. Either it goes down onto the second line, or it goes up and hits the `=` on the third line. There is a 1/6 chance that `=` is executed (1/3 from the second `?` times 1/2 from the first). If it is, it does a system-execute call on the stack (which is empty and interpreted as an empty string). FBBI's implementation of this runs a C `system()` call on the empty string, which segfaults. This leaves a 5/6 chance that the IP reaches the second line. If it does, it gets sent left with `<`, and pushes the string `"!devivrus I"` onto the stack. `ak,` prints the top 11 characters of the stack, outputting `I survived!` Finally, `@` ends the program. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` 6X’’Xṛ“`:ƭ÷» ``` [Try it online!](https://tio.run/##y0rNyan8/98s4lHDTCCKeLhz9qOGOQlWx9Ye3n5o9///AA "Jelly – Try It Online") ## Explanation ``` 6X Generate a random number between 1 and 6 inclusive (using python randrange) ’’ Decrement it twice X Generate a random number from 1 to the above value. 0 if the value is 0. Error if the value is negative (1/6 chance) ṛ Right Argument; ignore the above value and instead return “`:ƭ÷» "I survived!" ``` Unfortunately, taking the reciprocal of 0, dividing or integer-dividing by 0, and modulo by 0 all give either inf or nan, and don't actually error. [Answer] **Java, 149** ``` public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}} ``` Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports). [Answer] ## Groovy, 39 ``` 1/new Random().next(6);print"I survived!" ``` Picks a random number between 0 and 5 inclusive. If 0, throws a divide by zero exception. [Answer] ## Python (56), Haskell (77) This crashes with an IndexError when the generated number is 1: ``` from random import* print['I survived!'][1/randint(1,7)] ``` The Haskell solution has the same idea: ``` import System.Random main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6) ``` [Answer] ## Python, 59 55 53, 65 59 56 ``` import os 1/(ord(os.urandom(1))%6) print"I survived!" ``` `ZeroDivisionError` when `ord(os.urandom(1))%6` evaluates to 0 ``` import os print(["I survived!"]*5)[ord(os.urandom(1))%6] ``` `IndexError` when `ord(os.urandom(1))%6` evaluates to 5 ]
[Question] [ ## Introduction Partly inspired by [this StackOverflow question](https://stackoverflow.com/questions/30640309/how-to-create-a-lightning-bolt-design-using-css), let's draw an ASCII Lightning Bolt. Write a program that takes a positive Integer `n` via STDIN or command line and outputs the ASCII Lightning Bolt below. **Input** Positive Integer `n` representing the number of lightning zig-zag tiers to draw. **Example Output** n=1 ``` __ \ \ \ \ \ \ \/ ``` n=2 ``` __ \ \ \ \ __\ \ \ __\ \ \ \ \ \/ ``` n=3 ``` __ \ \ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ \ \ \/ ``` n=4 ``` __ \ \ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ \ \ \/ ``` . . . etc --- **Additional notes** * You may write a function that takes `n` as the only argument and prints or returns the string. * Trailing spaces and new lines are okay. * No leading spaces except where appropriate for the designated pattern. * **Shortest code in bytes wins.** [Answer] # Java, ~~201~~ ~~196~~ ~~189~~ ~~186~~ 182 bytes Obviously not the best, but it *is* in Java. ``` class I{public static void main(String[]a){System.out.print(("__\na a"+new String(new byte[new Byte(a[0])-1]).replace("\0","__a\\ __\\\n a")+" a \\/").replace("a","\\ \\\n"));}} ``` [Answer] # CJam, 41 bytes ``` ":¡ö cQïO[nu÷&,"255b6b" _\/X"f='X/~ri(*\ ``` I can probably squeeze a few more bytes out, but here's some compression. I picked a base which would lead to no unprintables. [Try it online](http://cjam.aditsu.net/#code=%22%3A%C2%A1%C3%B6%20cQ%C3%AFO%5Bnu%C3%B7%26%2C%22255b6b%22%0A%20_%5C%2FX%22f%3D'X%2F~ri%28*%5C&input=2). The lightning bolt is split into `top + middle * (input-1) + bottom`, where `top`, `middle`, `bottom` (compressed using base conversion) are ``` __ \. \ .\.\ __\.\ \..__ \ .\.\ ..\.\ ...\/ ``` *(Spaces are marked with `.`s)* ## 40 bytes Thanks to [Optimizer](https://codegolf.stackexchange.com/users/31414/optimizer) ``` "¹Ñ³Û-+ÎDx^áÐ"254b6b" _\ 0/"f=)/~ri(*\ ``` [Answer] # JavaScript (*ES6*) 76 Using template string, the 3 newlines are significant and counted. Test running the snippet (Firefox only) ``` f=n=>`__ 1 1${`__1\\ __\\ 1`.repeat(n-1)} 1 \\/`.replace(/1/g,`\\ \\ `) // TEST go=_=>O.innerHTML=f(I.value) go() ``` ``` N: <input id=I value=3><button onclick='go()'>Test</button> <pre id=O></pre> ``` [Answer] ## PowerShell, 72 63 bytes Stupid Windows and your \r\n... This could have been 67 59 bytes! ``` %{$a="\ \ ";"__ $a"+" $a`__$a\ __\ "*($_-1)+" $a $a \/"} ``` [Answer] # PHP - ~~84 79~~ 78 bytes ``` <?php define('N',3); // <- didnt count these bytes as TS said I could take var N as input ?> <?="__ \ \ \ \ ".str_repeat(" __\ \ \ __\ \ \ ",N-1)." \ \ \/" ``` View the result source or wrap in `<pre />` to check results. The newlines are required in the code. The -1 could be moved to the `define`, but I considered that a cheat. 1st improvement: replace `\n` with actual newlines 2nd: Since I can define a var, I used a CONTANT, safes the `$`. +an unneeded space in str\_repeat 3rd: Accidentally removed the -1, but saved a byte by using `<?=` instead of echo. [Answer] # Pyth, 60 54 bytes (Thanks @isaacg) My first attempt at Pyth, probably very bad. ``` "__ \ \ "VtQ" \ \ __\ \ \ __\ ")" \ \ \ \ \/ ``` [Verify it here](https://pyth.herokuapp.com/?code=%22__%0A%5C+%5C+%22VtQ%22+%5C+%5C+%0A__%5C+%5C+%0A%5C++__%5C+%22)%22+%5C+%5C+%0A++%5C+%5C+%0A+++%5C%2F&input=3&debug=0). [Answer] ## ><> (Fish), 409 bytes Run by `fish.py bolt.fish --value n` where `bolt.fish` is the program name and `n` is your positive integer input. ``` \ \ "__" a \ "\ \" a \ " \ \" a \r1-:?!vr "__\ \" a \ !0 "\ __\" a \ !6 " \ \" a04. >r 9a. "__\ \" \ / "\ __\" \ / " \ \" \ / " \ \" \ /" \/"\ aaaaa |o|!~r / \ / \ / \ / \ / ``` It's not short, but it looks cool. My attempt was to try to make it look like a lightning strike. Also, it always errors on completion. [Answer] ## CJam, 50 bytes ``` "__ \ \ "q~(" \ \ __\ \ \ __\ "*" \ \ "_S\" \/" ``` [Try it here](http://cjam.aditsu.net/#code=%22__%0A%5C%20%5C%0A%22q~%28%22%20%5C%20%5C%0A__%5C%20%5C%0A%5C%20%20__%5C%0A%22*%22%20%5C%20%5C%0A%22_S%5C%22%20%20%20%5C%2F%22&input=3) [Answer] ## Brainfuck, 164 bytes ``` ,<++++++++++++++++[>--->+>++++++>++>++++++>+++<<<<<<-]>->--->---->>->-<..<<<.>.> .<.<.>>.<.>.<.<.<[>>>>..<<.>.<.<.>.>..>..<<.<.>>.<.>.<.<.<-]>>>..<.>.<.<.>>...<. >>>. ``` With comments: ``` Initialise n and character set with i as counter Memory = in♪\ _/ ,<++++++++++++++++[>--->+>++++++>++>++++++>+++<<<<<<-]>->--->---->>->- Draw top of lightning bolt <..<<<.>.>.<.<.>>.<.>.<.<.< Draw lightning bolt zigzags [>>>>..<<.>.<.<.>.>..>..<<.<.>>.<.>.<.<.<-] Draw lightning bolt tip >>>..<.>.<.<.>>...<.>>>. ``` Okay, how this Brainfuck answer beating Java and C#? [Answer] # Perl, 69+1 69 characters, plus 1 for the `-n` command line switch to fetch input from stdin. ``` $s="\\ \\$/";print"__$/$s $s".("__$s\\ __\\$/ $s"x--$_)." $s \\/" ``` ### Usage example: ``` perl -ne '$s="\\ \\$/";print"__$/$s $s".("__$s\\ __\\$/ $s"x--$_)." $s \\/"' <<<"2" __ \ \ \ \ __\ \ \ __\ \ \ \ \ \/ ``` [Answer] # Javascript (ES6), 86 Not gonna win, but I love 1-line solution and I hate slashes. ``` f=n=>atob("X18KXCBc"+"CiBcIFwKX19cIFwKXCAgX19c".repeat(n-1)+"CiBcIFwKICBcIFwKICAgXC8") ``` [Answer] # C, 101 bytes My not so original implementation in c ``` f(n){puts("__\n\\ \\");for(;--n;puts(" \\ \\\n__\\ \\\n\\ __\\"));puts(" \\ \\\n \\ \\\n \\/");} ``` [Answer] # C#, 221 Bytes ``` class C{static void Main(string[]n){int e=System.Int32.Parse(n[0]);var o=@"__{0}\ \{0} \ \{0}";while(e>1){o+=@"__\ \{0}\ __\{0} \ \{0}";e--;}System.Console.WriteLine(o + @" \ \{0} \/{0}",System.Environment.NewLine);}} ``` This isn't the best, or the smallest answer, but I figured I'd give it a try. [Fsacer's answer](https://codegolf.stackexchange.com/questions/51284/draw-an-ascii-lightning-bolt/51322#51322) is much shorter and I think you should check it out. I just decided to do this just as an alternative method really. [Answer] # C#, 166 bytes ``` class I{static void Main(string[]a){System.Console.Write(("__\na a"+"".PadLeft(int.Parse(a[0])-1).Replace(" ",@"__a\ __\ a")+@" a \/").Replace("a",@"\ \ "));}} ``` **EDIT 1:** improved the result from 186B to 173B **EDIT 2:** saved 1B by using `PadLeft` instead of `PadRight` **EDIT 3:** saved 8B by dropping `PadLeft`'s second parameter and using verbatim string literals [Answer] # Awk, 101+8 bytes 101 characters, plus 8 for `-v n=$1` to get integer from shell. ``` '{l="\\ \\";print"__\n"l"\n "l;for(i=1;i<n;++i)print"__"l"\n\\ __\\\n "l}END{print" "l"\n \\/"}' ``` New to this SE site, [unclear](https://codegolf.stackexchange.com/questions/13014/tips-for-golfing-in-awk) if those parameters should count. ### Ungolfed ``` awk -v n=$1 '{ l="\\ \\"; print "__\n"l"\n "l; for(i=1; i<n; ++i) print "__"l"\n\\ __\\\n "l } END { print " "l"\n \\/" }' ``` ### Usage example: ``` lightning() { echo | awk -v n=$1 '{l="\\ \\";print"__\n"l"\n "l;for(i=1;i<n;++i)print"__"l"\n\\ __\\\n "l}END{print" "l"\n \\/"}'; } lightning 3 __ \ \ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ \ \ \/ ``` [Answer] # Python 97 82 78char: ``` print(("__\nl l"+"__l\ __\\\n l"*~-input()+" l \/").replace('l','\ \\\n')) ``` This is my first code golf # @(^\_^)@ Test here [Answer] # C, ~~119~~ 108 bytes ``` p(t){for(;t;t/=4)putchar(" \\_\n"[t%4]);}main(c){for(p(13434);p(836),--c;p(57154842));p(265488);puts("/");} ``` # First attempt, 150 bytes ``` v(a){putchar(a);}s(b){b--?v(32),s(b):v(92);}l(b){s(b);s(1);v(10);}main(c){for(puts("__\n\\ \\");l(1),--c;puts("__\\ \\\n\\ __\\"));l(2);s(3);v(47);} ``` `main` is accepting an int argument, so run like this: `./lightning . . .` to pass `4` as argument. [Answer] # Python 3, ~~126~~ ~~118~~ 117 bytes Just something to get us started with. ``` n=int(input()) p=print p('__\n\\ \\') for i in[0]*~-n:p(r''' \ \ __\ \ \ __\ ''',end='') p(r''' \ \ \ \ \/ ''') ``` [Answer] # Python 2, 76 bytes ``` print'__\n\ \\\n \ \\\n'+r'''__\ \ \ __\ \ \ '''*~-input()+' \ \\\n \/' ``` Just print the first three lines, then print the next three lines `n-1` times, and then print the final 2 lines. All in one go. And here is a nice try at an alternative that (unfortunately) uses exactly the same number of bytes: ``` print('__\n| |'+'__|\ __\\\n |'*~-input()+' | \/').replace('|','\ \\\n') ``` [Answer] ## F#, 98 characters, 105 bytes ``` let l n=(@"__♪◙\z"+String.replicate(n-1)@" \z__\z\ __\♪◙"+ @" \z \z \/").Replace("z"," \\\n") ``` [Answer] # CJam 54 Chars not the shortest, but since i started CJam today, im happy with it. ``` rd(:T;{'__}:W~N{'\:XSXN}:V~SV{WVXSSWXNSV;N}T*SSVSSSX'/ ``` [Try it](http://cjam.aditsu.net/#code=rd(%3AT%3B%7B'__%7D%3AW~N%7B'%5C%3AXSXN%7D%3AV~SV%7BWVXSSWXNSV%3BN%7DT*SSVSSSX'%2F&input=2) [Answer] # Pascal: ~~149~~ ~~142~~ ~~141~~ 137 characters ``` var n:Word;begin Read(n);Writeln('__'#10'\ \'#10' \ \');for n:=2to n do Writeln('__\ \'#10'\ __\'#10' \ \');Write(' \ \'#10' \/')end. ``` After all, Pascal's only golfing strength is that backslashes need no escaping… [Answer] # Google Sheets, 60 Bytes Anonymous worksheet function that takes input from range `[A1]` and outputs to the calling cell. ``` ="__ \ \ \ \ "&REPT("__\ \ \ __\ \ \ ",A1-1)&" \ \ \/ ``` [Answer] # [Perl 5](https://www.perl.org/), 58 + 1 (`-n`) = 59 bytes ``` say'__ \ \ \ \ '.'__\ \ \ __\ \ \ 'x--$_.' \ \ \/' ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVI9Pp4rRiGGSwFIKHCp6wH5IG6MggKQARblUq/Q1VWJ11NXAPMUgJS@@v//Fv/yC0oy8/OK/@v6muoZGBr8180DAA "Perl 5 – Try It Online") [Answer] # SpecBAS - 135 104 bytes The apostrophe in PRINT statements moves cursor to a new line. SpecBAS lets you incorporate ASCII characters in a string via way of `#n`, so have built in some carriage returns (ASCII 13). Built a string up using carriage returns and other characters, then used `REP$` to repeat it the required number of times. ``` 1 LET b$="\ \": INPUT n: PRINT "__"'b$+REP$(#13" "+b$+#13"__"+b$+#13"\ __\",n-1)'" ";b$'" ";b$'" \/" ``` [Answer] # PHP 155 ``` $l=PHP_EOL;echo$l;echo "__$l";for($i=0;$i<$argv[1];$i++){if($i>=1)echo "__\\ \\$l\\ __\\$l";else echo "\\ \\$l";echo " \\ \\$l";}echo " \\ \\$l \\/$l"; ``` Ungolfed Version ``` $n = $argv[1]; echo PHP_EOL; echo '__'.PHP_EOL; for($i=0;$i<$n;$i++) { if($i>=1) { echo '__\\ \\'.PHP_EOL.'\\ __\\'.PHP_EOL; } else { echo '\\ \\'.PHP_EOL; } echo ' \\ \\'.PHP_EOL; } echo ' \\ \\'.PHP_EOL; echo ' \\/'; echo PHP_EOL; ``` [Answer] # Java, ~~183~~ 180 bytes ``` class L{public static void main(String[]a){String b="__\n\\ \\\n \\ \\\n";for(int i=1;i<new Long(a[0]);++i)b+="__\\ \\\n\\ __\\\n \\ \\\n";System.out.print(b+" \\ \\\n \\/");}} ``` # Lua, 110 bytes ``` function l(n)print("__\n\\ \\\n \\ \\\n"..string.rep("__\\ \\\n\\ __\\\n \\ \\\n",n-1).." \\ \\\n \\/")end ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 46 bytes ``` .+ __#r r$0x r \/ 1x 1 __r\ __\# r r \ \# ``` Takes input as unary. Each line should go to its own file and `#` should be changed to newline in the files. This is impractical but you can run the code as is, as one file, with the `-s` flag, keeping the `#` markers. You can change the `#`'s to newlines in the output for readability if you wish. E.g.: ``` > echo -n 11|retina -s lightning|tr # '\n' __ \ \ \ \ __\ \ \ __\ \ \ \ \ \/ ``` The algorithm is very simple. The pairs of lines (regex - substitute pairs) do the following substitution steps: * Surround input with the top and bottom of the lightning. * Subtract `1` from the unary input. * Change every unary digit into the middle part of the lightning. * Decompress the compressed `\ \` parts of the lightning to get the desired output. [Answer] # Powershell, 59 bytes ``` '__ \ \' ,' \ \ __\ \ \ __\'*--$args[0] ' \ \ \ \ \/' ``` Test script: ``` $f = { '__ \ \' ,' \ \ __\ \ \ __\'*--$args[0] ' \ \ \ \ \/' } &$f 1 &$f 2 &$f 3 &$f 4 ``` Output: ``` __ \ \ \ \ \ \ \/ __ \ \ \ \ __\ \ \ __\ \ \ \ \ \/ __ \ \ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ \ \ \/ __ \ \ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ __\ \ \ \ \ \/ ``` Explanation: This script is traditional `top`+`middle`+`bottom`. There is only one smart thing: the comma before the middle string force to repeat an array element rather than a string. Therefore, each `middle` is displayed on a new line. [Answer] ### x86\_16 machine code - 84 bytes ``` 8B CB MOV CX, BX 49 DEC CX B4 09 MOV AH, 09H HEAD: BA 02 01 MOV DX, OFFSET LIGHTNING_HEAD CD 21 INT 21H 85 C9 TEST CX, CX 74 09 JE TAIL BODY: BA 1F 01 MOV DX, OFFSET LIGHTNING_LOOP_STR CD 21 INT 21H E3 02 JCXZ TAIL E2 F7 LOOP BODY TAIL: BA 12 01 MOV DX, OFFSET LIGHTNING_TAIL CD 21 INT 21H B8 00 4C MOV AX, 4C00H CD 21 INT 21H LIGHTNING_HEAD DB 05FH, 05FH, 00AH, 00DH, 05CH, 020H, 05CH, 00AH, 00DH, 020H DB 05CH, 020H, 05CH, 00AH, 00DH, 024H LIGHTNING_TAIL DB 020H, 020H, 05CH, 020H, 05CH, 00AH, 00DH, 020H, 020H, 020H DB 05CH, 02FH, 024H LIGHTNING_LOOP_STR DB 05FH, 05FH, 05CH, 020H, 05CH, 00AH, 00DH, 05CH, 020H, 020H DB 05FH, 05FH, 05CH, 00AH, 00DH, 020H, 05CH, 020H, 05CH, 00AH DB 00DH, 024H ``` Tested using DOSBox [![enter image description here](https://i.stack.imgur.com/koiTP.png)](https://i.stack.imgur.com/koiTP.png) [![enter image description here](https://i.stack.imgur.com/Fq7tD.png)](https://i.stack.imgur.com/Fq7tD.png) [![enter image description here](https://i.stack.imgur.com/CjLnk.png)](https://i.stack.imgur.com/CjLnk.png) ]
[Question] [ # About the Series I will be running a little series of code-golf challenges revolving around the theme of randomness. This will basically be a [9-Hole](https://codegolf.stackexchange.com/q/16707/8478) [Golf Course](https://codegolf.stackexchange.com/q/19163/8478), but spread out over several questions. You may participate in any challenge individually as if it was a normal question. However, I will maintain a leaderboard across all challenges. The series will run over 9 challenges (for now), one posted every few days. Every user who participates in *all 9 challenges* is eligible for winning the entire series. Their overall score is the sum of their shortest submissions on each challenge (so if you answer a challenge twice, only the better answer one is counted towards the score). If anyone holds the top spot on this overall leaderboard for **28 days** I will award them a bounty of **500 rep**. Although I have a bunch of ideas lined up for the series, the future challenges are not set in stone yet. If you have any suggestions, please let me know [on the relevant sandbox post](http://meta.codegolf.stackexchange.com/a/4750/8478). # Hole 1: Shuffle an Array The first task is pretty simple: given a non-empty array of integers, shuffle it randomly. There are a few rules though: * **Every possible permutation must be returned with the same probability** (so the shuffle should have a uniform distribution). You can check if your algorithm is uniform/unbiased by implementing it in JavaScript on [**Will it Shuffle**](http://bost.ocks.org/mike/shuffle/compare.html), which will produce a matrix of the biases - the result should look as uniform as their built-ins *Fisher-Yates* or *sort (random order)*. * You must not use any built-in or 3rd-party method to shuffle the array or generate a random permutation (or enumerate all permutations). In particular, **the only built-in random function you may use is getting a single random number at a time**. You *may* assume that any built-in random number method runs in O(1) and is perfectly uniform over the requested interval (in a mathematical sense - you may ignore details of floating-point representation here). If your language lets you obtain a list of *m* random numbers at once, you may use this facility, provided the *m* numbers are independent of each other, and you count it as O(m). * Your implementation must not exceed a **time complexity of O(N)**, where **N** is the size of the array to be shuffled. For instance, you cannot "sort by random numbers". * You may either shuffle the array in place, or create a new array (in which case the old array may be modified however you like). You may write a full program or a function and take input via STDIN, command-line argument, function argument or prompt and produce output via return value or by printing to STDOUT (or closest alternative). If you write a function that shuffles the array in place, you don't need to return it of course (provided your language lets you access the modified array after the function returns). Input and output may be in any convenient list or string format, but must support arbitrary integers in the range **-231 ≤ x < 231**. In principle, your code should work for arrays up to length **231**, although this doesn't necessarily have to fit in your memory or complete within a reasonable amount of time. (I just don't want to see arbitrary size limits to hardcode loops or something.) This is code golf, so the shortest submission (in bytes) wins. # Leaderboard The following snippet will generate a leaderboard across all challenges of the series. To make sure that your answers show up, please start every answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` *(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)* ``` /* Configuration */ var QUESTION_IDs = [45302, 45447, 46991, 49394, 51222, 66319, 89621, 120472]; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!.FjwQBrX2KXuFkv6p2lChi_RjzM19"; /* App */ var answers = [], page = 1, currentQ = -1; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_IDs.join(";") + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function getAnswers() { $.ajax({ url: answersUrl(page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); if (data.has_more) getAnswers(); else process(); } }); } getAnswers(); var SIZE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;((?!&gt;).)*&lt;\/s&gt;|((?!&gt;).)+&gt;)[^\d&]*)*$)/; var NUMBER_REG = /\d+/; var LANGUAGE_REG = /^#*\s*([^\n,]+)(?=,)/;// function shouldHaveHeading(a) { var pass = false; var lines = a.body_markdown.split("\n"); try { pass |= /^#/.test(a.body_markdown); pass |= ["-", "="] .indexOf(lines[1][0]) > -1; pass &= LANGUAGE_REG.test(a.body_markdown); } catch (ex) {} return pass; } function shouldHaveScore(a) { var pass = false; try { pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]); } catch (ex) {} if (!pass) console.log(a); return pass; } function getAuthorName(a) { return a.owner.display_name; } function getAuthorId(a) { return a.owner.user_id; } function process() { answers = answers.filter(shouldHaveScore) .filter(shouldHaveHeading); answers.sort(function (a, b) { var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0], bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0]; return aB - bB }); var users = {}; answers.forEach(function (a) { var headline = a.body_markdown.split("\n")[0]; var question = QUESTION_IDs.indexOf(a.question_id); var size = parseInt((headline.match(SIZE_REG)||[0])[0]); var language = headline.match(LANGUAGE_REG)[1]; var user = getAuthorName(a); var userId = getAuthorId(a); if (!users[userId]) users[userId] = {name: user, nAnswer: 0, answers: []}; if (!users[userId].answers[question]) { users[userId].answers[question] = {size: Infinity}; users[userId].nAnswer++; } if (users[userId].answers[question].size > size) { users[userId].answers[question] = {size: size, link: a.share_link} } }); var sortedUsers = []; for (var userId in users) if (users.hasOwnProperty(userId)) { var user = users[userId]; user.score = 0; user.completedAll = true; for (var i = 0; i < QUESTION_IDs.length; ++i) { if (user.answers[i]) user.score += user.answers[i].size; else user.completedAll = false; } sortedUsers.push(user); } sortedUsers.sort(function (a, b) { if (a.nAnswer > b.nAnswer) return -1; if (b.nAnswer > a.nAnswer) return 1; return a.score - b.score; }); var place = 1; for (var i = 0; i < sortedUsers.length; ++i) { var user = sortedUsers[i]; var row = '<tr><td>'+ place++ +'.</td><td>'+user.name+'</td>'; for (var j = 0; j < QUESTION_IDs.length; ++j) { var answer = user.answers[j]; if (answer) row += '<td><a href="'+answer.link+'">'+answer.size+'</a></td>'; else row += '<td class="missing"></td>'; } row += '<td></td>'; if (user.completedAll) row += '<td class="total">'+user.score+'</td>'; else row += '<td class="total missing">'+user.score+'</td>'; row += '</tr>'; $("#users").append(row); } } ``` ``` body { text-align: left !important} #leaderboard { width: 500px; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } td.total { font-weight: bold; text-align: right; } td.missing { background: #bbbbbb; } ``` ``` <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="leaderboard"> <h2>Leaderboard</h2> <p> Missing scores are shown as grey cells. A grey total indicates that the user has not participated in all challenges and is not eligible for the overall victory yet. </p> <table class="_user-list"> <thead> <tr><td></td><td>User</td> <td><a href="https://codegolf.stackexchange.com/q/45302/8478">#1</a></td> <td><a href="https://codegolf.stackexchange.com/q/45447/8478">#2</a></td> <td><a href="https://codegolf.stackexchange.com/q/46991/8478">#3</a></td> <td><a href="https://codegolf.stackexchange.com/q/49394/8478">#4</a></td> <td><a href="https://codegolf.stackexchange.com/q/51222/8478">#5</a></td> <td><a href="https://codegolf.stackexchange.com/q/66319/8478">#6</a></td> <td><a href="https://codegolf.stackexchange.com/q/89621/8478">#7</a></td> <td><a href="https://codegolf.stackexchange.com/q/120472/8478">#8</a></td> <td></td><td>Total</td> </tr> </thead> <tbody id="users"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><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] # Dyalog APL, ~~25~~ 24 bytes First for the 25-character solution: [`i{⊃a[⍺⍵]←a[⍵⍺]}¨?i←⌽⍳⍴a←⎕`](http://tryapl.org/?a=A%u21901%202%203%204%205%206%207%20%u22C4%20i%7B%u2283a%5B%u237A%u2375%5D%u2190a%5B%u2375%u237A%5D%7D%A8%3Fi%u2190%u233D%u2373%u2374a%u2190A&run) ``` a←⎕ ⍝ evaluated input, assign to "a" ⍴a ⍝ length ⍳⍴a ⍝ 1 2 .. length ⌽⍳⍴a ⍝ length .. 2 1 i← ⍝ assign to "i" ?i ⍝ random choices: (1..length)(1..length-1)..(1 2)(1) i{ }¨?i ⍝ for each index ⍺ and corresponding random choice ⍵ a[⍺⍵]←a[⍵⍺] ⍝ swap a[⍺] and a[⍵] ← ⍝ in Dyalog, assignment returns its right-hand side ⊃ ⍝ first element, i.e. a[⍵] ⍝ the result from {} is an array of all those a[⍵] ``` After some equivalence transformations on the above: ``` i {}¨ ?i ←→ i {}¨∘? i ⍝ because A f∘g B ←→ A f g B ←→ {}¨∘?⍨ i ⍝ because f⍨ B ←→ B f B ``` we can get rid of the assignment `i←` and save a character: [`{⊃a[⍺⍵]←a[⍵⍺]}¨∘?⍨⌽⍳⍴a←⎕`](http://tryapl.org/?a=A%u21901%202%203%204%205%206%207%20%u22C4%20%7B%u2283a%5B%u237A%u2375%5D%u2190a%5B%u2375%u237A%5D%7D%A8%u2218%3F%u2368%u233D%u2373%u2374a%u2190A&run) [Answer] # 80386 machine code, 44 24 bytes Hexdump of the code: ``` 60 8b fa 0f c7 f0 33 d2 f7 f1 49 8b 04 8f 87 04 97 89 04 8f 75 ed 61 c3 ``` Thanks to FUZxxl, who suggested using the `rdrand` instruction. Here is the source code (can be compiled by Visual Studio): ``` __declspec(naked) void __fastcall shuffle(unsigned size, int array[]) { // fastcall convention: // ecx = size // edx = array _asm { pushad; // save registers mov edi, edx; // edi now points to the array myloop: rdrand eax; // get a random number xor edx, edx; div ecx; // edx = random index in the array dec ecx; // count down mov eax, [edi + 4 * ecx]; // swap elements xchg eax, [edi + 4 * edx]; // swap elements mov [edi + 4 * ecx], eax; // swap elements jnz myloop; popad; // restore registers ret; } } ``` Yet another Fisher-Yates implementation. Most of the golfing was achieved by passing parameters in registers. [Answer] # Java, 88 ~~101~~ A basic Fisher-Yates shuffle does the trick. I get the feeling it'll be used pretty commonly here, since it's quick and easy to implement. There's some loop/assignment cramming here, but there's honestly not *too* much to golf; it's just short by nature. ``` void t(int[]s){for(int i=s.length,t,x;i>0;t=s[x*=Math.random()],s[x]=s[i],s[i]=t)x=i--;} ``` With some line breaks: ``` void t(int[]s){ for(int i=s.length,t,x; i>0; t=s[x*=Math.random()], s[x]=s[i], s[i]=t ) x=i--; } ``` This shuffles in place, modifying the original array `s[]`. Test program: ``` public class Shuffle { public static void main(String[] args) { int[] a = {1,2,3,4,5,6,7,8,9}; new Shuffle().t(a); for(int b:a) System.out.print(b+" "); } void t(int[]s){for(int i=s.length,t,x;i>0;t=s[x*=Math.random()],s[x]=s[i],s[i]=t)x=i--;} } ``` [Answer] # Python 2, 86 bytes ``` from random import* def S(L):i=len(L);exec"i-=1;j=randint(0,i);L[i],L[j]=L[j],L[i];"*i ``` This is a function which shuffles the array in place without returning it, using a straightforward implementation of the [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). Getting random numbers from Python is *expensive*... Thanks to @xnor and @colevk for tips. [Answer] ## J, ~~45~~ 44 characters This was a tricky one. ``` <@({.,?@#@}.({,<^:3@[{])}.)&>/@(<"0@i.@#,<) ``` Here is an explanation: 1. `# y`: The *tally* of `y`, that is, the number of elements in `y`. 2. `?@# y`: A random number uniformly distributed over the range from `1` to `(#y)-1`. 3. `x { y`: The item *from* `y` at index `x`. 4. `(<<<x) { y`: All items except the item at index `x` in `y`. 5. `x , y`: `y` *appended* to `x`. 6. `x ({ , <^:3@[ { ]) y`: The item at index `x` in `y`, then all the other items. 7. `(?@# ({ , <^:3@[ { ]) ]) y` A random it from `y`, then all the other items. 8. `x {. y`: The first `x` items *taken* from `y`. 9. `x }. y`: The first `x` items *dropped* from `y`. 10. `x ({. , }.) y`: The first `x` items *taken* from `y`, then the first `x` items *dropped* from `y` 11. `x ({. , (?@# ({ , <^:3@[ { ]) ])@}.) y`: The first `x` items *taken* from `y`, then the first `x` items from `y` processed as in number 7. 12. `x ({. , ?@#@}. ({ , <^:3@[ { ]) }.) y`: The same thing with the *drop* pulled in to save one character. 13. `u/ y`: `u` *inserted* between the items of `y`. 14. `< y`: `y` *boxed*. 15. `<"0 y`: Each item of `y` *boxed*. 16. `i. y`: *integers* from `0` to `y - 1`. 17. `i.@# y`: *integers* from `0` to `(#y) - 1`. 18. `(<"0@i.@# , <) y`: Integers from `0` to `(#y) - 1` each *boxed* and then `y` in a single box. This is needed because arrays in J are uniform. A box hides the shape of its content. 19. `x u&v y`: like `(v x) u (v y)`. 20. `> y`: `y` *opened*, that is, without its box. 21. `x ({. , ?@#@}. ({ , <^:3@[ { ]) }.)&> y` the phrase from number 12 applied to its unboxed arguments. 22. `({. , ?@#@}. ({ , <^:3@[ { ]) }.)&>/ y` the phrase from number 21 *inserted* between items of `y`. 23. `({. , ?@#@}. ({ , <^:3@[ { ]) }.)&>/@(<"0@i.@# , <) y` the phrase from number 22 applied to the the result of the phrase from number 18, or, a uniform permutation of the items of `y`. [Answer] # Pyth, 25 bytes [Test it here.](http://pyth.herokuapp.com) Yet another Fisher-Yates implementation. Is essentially the same as @Sp3000 python solution, just in pyth. ``` FNrlQ1KONJ@QN XXQN@QKKJ)Q ``` Thanks to @Jakube for the swapping trick ``` <implicit> Q=input() FNrlQ1 For N in len(Q) to 1, only goes len Q-1 because how range implemented in pyth KON K = random int 0-N J@QN J=Q[N] <space> Suppress print XXQN@QKKJ Swap K and J ) End for Q Print Q ``` [Answer] # Perl, ~~68~~ ~~56~~ 44 Like many other solutions, this uses the [Fisher-Yates](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) algorithm. Using [nutki](https://codegolf.stackexchange.com/questions/45302/random-golf-of-the-day-1-shuffle-an-array/45374?noredirect=1#comment107493_45374)'s comment, 12 characters are saved by using `$_` instead of `$i` and performing the operations in the array indices. 44: ``` sub f{@_[$_,$j]=@_[$j=rand$_,--$_]for 1..@_} ``` 56: ``` sub f{$i=@_;$j=int(rand$i),@_[$i,$j]=@_[$j,$i]while$i--} ``` This is my first codegolf. [Answer] # C, ~~63~~ ~~61~~ 60 bytes ``` i,t;s(a,m)int*a;{for(;m;a[m]=t)t=a[i=rand()%m--],a[i]=a[m];} ``` Just a straight implementation of Fischer-Yates that sorts the given array in place. Compiles and links perfectly fine with the visual studio compiler (vs2013, haven't tested the other versions) and the Intel Compiler. Nice looking function signature is `s(int array[], int length)`. I'm legitimately impressed I beat Python and Ruby. This does assume `srand()` is called and rand() is implemented properly, but I believe this rule allows for that: ``` You may assume that any built-in random number method runs in O(1) and is perfectly uniform over the requested interval ``` Nicely formatted version: ``` index, temp; shuffle(array, length) int* array; { for(;length; array[index] = temp) index = rand() % length--, temp = array[length], array[length] = array[index]; } ``` [Answer] ## Octave, ~~88~~ 77 bytes ``` function s=r(s)for(i=length(s):-1:1)t=s(x=randi(i));s(x)=s(i);s(i)=t;end;end ``` Yet another Fisher-Yates implementation... Should be fairly straightforward if I add the usual line returns and spacing: ``` function s=r(s) for(i=length(s):-1:1) # Counting down from i to 1 t=s(x=randi(i)); # randi is builtin number generator for an int from 0 to i s(x)=s(i); s(i)=t; end end ``` ~~The "end" keywords really kill the golf score here, unfortunately.~~ Hey, I can use "end" instead of "endfor" and "endfunction"! [Answer] # Java 8, 77 ``` (x)->{for(int i=x.length,j,t;;t=x[j*=Math.random()],x[j]=x[i],x[i]=t)j=i--;}; ``` It's a lambda taking `int[]` and returning void. My first attempt seemed not very interesting, so I decided to have it exit by throwing an exception. Test program: ``` interface shuff { void shuff(int[] x); } class Ideone { public static void main (String[] args) throws java.lang.Exception { shuff s = (x)->{for(int i=x.length,j,t;;t=x[j*=Math.random()],x[j]=x[i],x[i]=t)j=i--;}; int[] x = {3, 9, 2, 93, 32, 39, 4, 5, 5, 5, 6, 0}; try { s.shuff(x); } catch(ArrayIndexOutOfBoundsException _) {} for(int a:x) System.out.println(a); } } ``` [Answer] # Golflua, 37 [How to run Golflua?](http://meta.codegolf.stackexchange.com/a/1216/7162) ``` ~@i=1,#X`r=M.r(i)X[i],X[r]=X[r],X[i]$ ``` The input is provided as a table in the variable X. The table is shuffled in place. Example usage: ``` > X={0,-45,8,11,2} > ~@i=1,#X`r=M.r(i)X[i],X[r]=X[r],X[i]$ > w(T.u(X)) -45 0 8 11 2 ``` [Answer] # R, 79 bytes ``` f=function(x){n=length(x);for(i in 1:n){j=sample(i:n,1);x[c(i,j)]=x[c(j,i)]};x} ``` This is a straightforward implementation of the Fisher-Yates shuffle. The R function `sample` draws a simple random sample of a given size from a given vector with equal probability. Here we're drawing a random sample of size 1 at each iteration from the integers `i`, ..., `n`. As stated in the question, this can be assumed to be O(1), so in all this implementation should be O(N). [Answer] # Matlab, 67 Also implementing Fisher-Yates. ``` a=input('');n=numel(a);for i=1:n;k=randi(i);a([i,k])=a([k,i]);end;a ``` I thought it was too bad I could not use Matlab's `randperm` function. But after some fiddling around, I thought I may look at the source of `randperm` to see how it is done, and I was astonished to see that there was just one line: `[~,p] = sort(rand(1,n))` =) [Answer] # Perl, 44 ``` sub f{($_[$x],$_)=($_,$_[$x=rand++$i])for@_} ``` Another perl in 44 characters. Example use: ``` @x=(1..9);f(@x);print@x ``` [Answer] # Mathematica, ~~82 90 83~~ 93 bytes Note: This variation the Fisher-Yates shuffle is actually Martin Büttner's solution, with some code paring by alephalpha. `s` is the input array. Nothing fancy-smancy, but sometimes the simple things are the most elusive. ``` f@s_:=(a=s;m=Length@a;Do[t=a[[r=RandomInteger@{1,m-1}]];a[[r]]=a[[m]]; a[[m]]=t,{n,1,m-1}];a) ``` [Answer] # Ruby, 57 bytes ``` ->a{a.size.times{|i|j=rand(i+1);a[i],a[j]=a[j],a[i]};p a} ``` ### Input (as lambda function): ``` f.([1,2,3,4,5]) ``` ### Output: ``` [2, 1, 4, 3, 5] ``` [Answer] # TI-BASIC, 46 bytes ``` For(X,dim(L1),2,-1:randInt(1,X→Y:L1(X→Z:L1(Y→L1(X:Z→L1(Y:L1 1 111 2 1111112 1111112 111112 1112 111112 1112 ``` [Source for byte count](http://tibasicdev.wikidot.com/one-byte-tokens) [Answer] # K, 31 chars ``` f:{{l[i:x,1?x]:l@|i}'|!#l::x;l} ``` Not quite as short as the one I put up before (which got disqualified)...oh well. It's a basic Fisher-Yates shuffle. This was built with lots of help [from the Kona mailing list](https://groups.google.com/forum/#!topic/kona-user/lf2LC9ivPRw). [Answer] # JavaScript (ES6), 66 This function shuffles the array in place. It also returns a byproduct array that is NOT the shuffled output and must not be considered. ``` F=a=>a.map((v,i)=>a[a[i]=a[j=0|i+Math.random()*(a.length-i)],j]=v) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` XH`HnYr&)XHxvHHn ``` [Try it online!](https://tio.run/nexus/matl#@x/hkeCRF1mkphnhUVHm4ZH3/3@0oYKRgrGCiYKpgpmCuYJF7Ne8fN3kxOSMVAA "MATL – TIO Nexus") Fisher-Yates in MATL. Almost a third of this program is devoted to the letter `H`, which corresponds to the clipboard function in MATL. Basically, `H` stores the unused items from the input, while the stack keeps track of the shuffled list. [Answer] # Japt, 12 ``` rÈiMqZÄ Y}[] ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=cshpTXFaxCBZfVtd&input=WzExLCAyMiwgMzMsIDQ0LCA1NV0KLVE=) -10 (about half ;) thanks to @Shaggy! I have been wanting to try out a golfing language, and the Japt interpreter had good documentation and a way to try things out in the browser. Below is the strategy I took: * Reduce input seeding with an empty array * At each step, find a random slot to insert the current element [Answer] ## Javascript ES6, 69 ``` a=>{m=a.length;while(m)[a[m],a[i]]=[a[i=~~(Math.random()*m--)],a[m]]} ``` It's Fisher–Yates. PS: Can be tested in Firefox [Answer] # Pyth, 27 bytes [Test it here](https://pyth.herokuapp.com/) ``` FkQJOhlYaY?@YtJJkIJ XYtJk;Y ``` This is an implementation of the incremental Fisher-Yates shuffle, mentioned second [here](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm). [Answer] # Haskell, 170 ``` import System.Random import Data.Array.IO s a=do(_,n)<-getBounds a;sequence$map(\i->do j<-randomRIO(i,n);p<-a%i;q<-a%j;writeArray a j p;return q)[1..n]where(%)=readArray ``` Another Fisher-Yates solution inspired by the algorithm at <https://wiki.haskell.org/Random_shuffle>. `s` is a function which has signature: `IOArray Int a -> IO [a]` [Answer] # CJam - 30 ``` q~_,,W%{_I=I)mr:J2$=@I@tJ@t}fI ``` Try it at <http://cjam.aditsu.net/> Example input: `[10 20 30 40 50]` Example output: `3020401050` (add a `p` at the end of the code for pretty printing) ~~If the code is allowed to take the input from the stack (like a function), then the first 2 characters can be removed, reducing the size to 28.~~ **Explanation:** The code is longer than I hoped, due to the lack of a "swap" operator for arrays (to be implemented later :p) ``` q~ read and evaluate the input (let's call the array "A") _,, make an array [0 1 2 ... N-1] where N is the size of A W% reverse the array, obtaining [N-1 ... 2 1 0] {…}fI for I in this array _I= push A[I] I)mr:J push a random number from 0 to I (inclusive) and store it in J stack: A, A[I], J 2$= get A[J] @I@t set A[I] = A[J] stack: former A[I], A J@t set A[J] = former A[I] ``` [Answer] # JavaScript (ES 6), 61 ``` S=a=>(a.map((c,i)=>(a[i]=a[j=Math.random()*++i|0],a[j]=c)),a) ``` You can test it [here](http://bost.ocks.org/mike/shuffle/compare.html) by just adding a line that says `shuffle = S` (Firefox only). [Answer] # STATA, 161 ``` di _r(s) set ob wordcount($s) token $s g a=0 foreach x in $s{ gl j=floor(runiform()*_n)+1 replace a=`$j' if word($s,_n)=`x' replace a=`x' if word($s,_n)=`$j' } l ``` Expects input as space separated numbers. I can remove the headers and observation numbers from the output if you would like, but otherwise this is shorter. [Answer] # Java, 93 bytes ``` a->{for(int b=0,c,d=0,e=a.length;b<e;c=a[b],a[b]=a[d],a[d]=c,b++,d=b)d+=Math.random()*(e-b);} ``` Example usage: <http://ideone.com/RqSMnZ> [Answer] ## SQF, 91 bytes ``` params["i"];{n=floor random count i;i set[_forEachIndex,i select n];i set[n,_x]}forEach i;i ``` [Answer] # Perl, 41 bytes ``` sub f{push@b,splice@_,rand@_,1while@_;@b} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrbqgtDjDIUmnuCAnMznVIV6nKDEvBUgZlmdk5gD51g5Jtf@LEysV0jRs7DT/G3IZcRlzmXCZcv3LLyjJzM8r/q/ra6pnYGgAAA "Perl 5 – Try It Online") ]
[Question] [ ### Challenge: Given a positive integer input **n**, create a vector that follows this pattern: ``` 0 1 0 -1 -2 -1 0 1 2 3 2 1 0 -1 -2 -3 -4 -3 -2 -1 ... ±(n-1) ±n ``` Or, explained with words: The vector starts at `0`, and makes increments of `1` until it reaches the smallest odd positive integer that isn't part of the sequence, then it makes decrements until it reaches the smallest (in magnitude) even negative integer that isn't part of the sequence. It continues this way until `n` is reached. The sequence will end on positive `n` if `n` is odd, and negative `n` if `n` is even. The output format is flexible. ### Test cases: ``` n = 1 0 1 ----------- n = 2 0 1 0 -1 -2 ----------- n = 3 0 1 0 -1 -2 -1 0 1 2 3 ----------- n = 4 0 1 0 -1 -2 -1 0 1 2 3 2 1 0 -1 -2 -3 -4 ----------- n = 5 0 1 0 -1 -2 -1 0 1 2 3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3 4 5 ``` You may choose to take the **n** zero-indexed. `n = 1` would then give `0 1 0 -1 -2`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins! Explanations are encouraged as always! [Answer] # [R](https://www.r-project.org/), ~~58~~ ~~54~~ ~~50~~ ~~48~~ 43 bytes *-2 bytes thanks to MickyT* ``` function(n)diffinv(rep(1:n%%2*2-1,1:n*2-1)) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMyUzLS0zr0yjKLVAw9AqT1XVSMtI11AHyATRmpr/0zRMNf8DAA "R – Try It Online") ``` function(n) diffinv( # take cumulative sum, starting at 0 of 1:n%%2*2-1, # a vector of alternating 1,-1 rep( # repeated 1:n*2-1)) # 1, 3, 5, etc. times ``` [Answer] # [Perl 6](https://perl6.org), ~~60~~ 26 bytes ``` {flat {((1,-*...*)ZX*(-$++...0...$++)xx$_)}(),$_*($_%2||-1)} ``` [Try it](https://tio.run/##FY3BCoJAFEX3fsVdjM1748wjhdyEfkdEIGK6Sg21UNRvn2xx4JzVedfDK/WfscY3leoatAtOVf@skfm1eZUTVqLYOiMihu83Q05F0RHng8N4nlXBO7FVhSFVhMm2uZh33/QDYpELXI5HhzUAxnJBJ007kQ6TUbOFRpZDW/yH1HGw@x8 "Perl 6 – Try It Online") ``` {[...] (-1,-*...*)Z*0..$_} ``` [Try it](https://tio.run/##Fcy7DoIwAAXQvV9xB6GPtDdiIouBDxGJMVgmKYaKCSF8e8XtTOftp1eZ5ujxLdldxLAg78anR5XWhmQL5QrrzE6jr@ZIHu5b6scJBXmGq3ELWAUQHwsC@@GjZHaKUltIVDWkxb9TQYst/QA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter $_ [...] # reduce using &infix:«...» (sequence generator) ( -1, -* ... * ) # (-1, 1, -1, 1 ... *) Z* # zip multiplied with 0 .. $_ # range up to and including input } ``` `(-1,-*...*)Z*0..$_` generates the sequence `0 1 -2 3 -4 5` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes *Saved 2 bytes thanks to @Emigna* ``` Ýā®sm*Ÿ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8NwjjYfWFedqHd3x/78pAA "05AB1E – Try It Online") My first 05AB1E answer (I think), so I may be missing some tricks... ### Explanation ``` Ý # push range [0 ... n] stack: [[0 ... n]] ā # push range [1 ... len(prev)] [[0 ... n], [1 ... n+1]] ® # push value of register [[0 ... n], [1 ... n+1], -1] s # swap top two values [[0 ... n], -1, [1 ... n+1]] m # power [[0 ... n], [-1, 1, -1, 1, ...]] * # multiply [[0, 1, -2, 3, -4, 5, ...]] Ÿ # range interpolation [[0, 1, 0, -1, -2, -1, ...]] ``` I have to thank @Dennis for [the original usage of `Ÿ`](https://codegolf.stackexchange.com/a/74860/42545), otherwise I ~~may not~~ probably would never have known about it... [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~57~~ 56 bytes ``` f=lambda n:[0][n:]or f(n-1)+range(-n,n+1)[::n%2*2-1][2:] ``` [Try it online!](https://tio.run/##JcoxDoQgEAXQq0yzERQSodhijCdBCswuu5Po1xAbT48mVq95@3n8N/ha87ikdf4kAoc@BnDcCmUF63RXEn5fZWHQOR2Y8fKtty4Gz7Hm@wkJ6FnOvDXvRXCQDI9ZiTbNhKZe "Python 2 – Try It Online") For each `n` up to the `input` the `range(-n,n)` (inclusive) is calculated, inverted when `n` is an even number, has the fist two numbers (after the inversion) removed, and then appended to the output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes ``` ÝDÉ·<*Ý€û˜ÔsF¨ ``` [Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//8OdRMOJwrc8KsOd4oKsw7vLnMOUc0bCqP/Dr/81 "05AB1E – Try It Online") **Explanation** ``` Ý # push range [0 ... n] D # duplicate É·< # (x % 2 == 1)*2-1 for each * # multiply Ý # range [0 ... a] for each €û # palendromize each ˜ # flatten Ô # connected uniqueified sF¨ # remove the last n elements ``` [Answer] # JavaScript (ES6), 56 bytes ``` f=(n,b=d=1,k=0)=>[k,...k-d*n?f(n,k-b?b:(d=-d)-b,k+d):[]] ``` [Try it online!](https://tio.run/##Dcw9DoMwDEDhnVN4I25@VIYuFJeDIAaCSQVBTgVVl6pnTzO94ZPeNn2mcz7W19tK4iXnQEqMJ6bGRLoiPYZonHPR8kX6UCxa3/tWMVlG603UjO0wjjmkQwkQNHcQ6AhupVojfCuAOcmZ9sXt6anKA92WVlG1gRqx@uU/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: n, // n = input b = // b = boundary value, initialized to 1 d = 1, // d = current direction, initialized to 1 k = 0 // k = current sequence value, initialized to 0 ) => // [ // update the sequence: k, // append the current value ...k - d * n ? // if |k| is not equal to |n|: f( // append the (spread) result of a recursive call: n, // use the original input k - b ? // if k has not reached the boundary value: b // leave b unchanged : // else: (d = -d) // reverse the direction - b, // and use a boundary of higher amplitude and opposite sign k + d // update k ) // end of recursive call : // else: [] // stop recursion and append nothing ] // end of sequence update ``` [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` f n=scanl(-)0[(-1)^k|k<-[1..n],_<-[2..2*k]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7Y4OTEvR0NX0yBaQ9dQMy67JttGN9pQTy8vViceyDLS0zPSyo6N/Z@bmJmnYKtQUJSZV6KgkaZgovkfAA "Haskell – Try It Online") Computes the negated cumulative sums of the list `[(-1)^k|k<-[1..n],_<-[2..2*k]]`, which is the first `n` rows of ``` [-1, +1, +1, +1, -1, -1, -1, -1, -1, +1, +1, +1, +1, +1, +1, +1… ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes ``` ²Ḷƽ-*0;Ä ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//wrLhuLbDhsK9LSowO8OE/8OH4oKsR///MSwgMiwgMywgNCwgNQ "Jelly – Try It Online") ### How it works ``` ²Ḷƽ-*0;Ä Main link. Argument: n ² Square; yield n². Ḷ Unlength; yield [0, ..., n²-1]. ƽ Take the integer square root of each k in the range. -* Compute (-1)**r for each integer square root r. 0; Prepend a zero. Ä Accumulate; take the sums of all prefixes. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~48~~ 42 bytes ``` f n=0:[(-1)^i*x|i<-[0..n-1],x<-[1-i..i+1]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz9bAKlpD11AzLlOroibTRjfaQE8vT9cwVqcCyDbUzdTTy9Q2jI39n5uYmadgq1BQlJlXoqCikKZg8h8A "Haskell – Try It Online") *Thanks to [Οurous](https://codegolf.stackexchange.com/users/18730/%ce%9furous) for -1 byte* Even though it's kind of obvious in hindsight, it took me a while to arrive at `(-1)^i*x` which is `x` when `i` is even and `-x` when `i` is odd. Previous iterations where: ``` (-1)^i*x x-2*mod i 2*x (-1)^mod i 2*x [x,-x]!!mod i 2 (1-sum[2|odd i])*x ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~300~~ 167 bytes I've never done any of these before, but this one seemed fun. I see why people use those "golfing" languages as 167 seems way higher than some of the other answers. But, you gotta go with what you know. ``` static int[] f(int n){if (n==1) return new int[]{0,1};var a=f(n-1);return a.Concat(a.Skip(a.Length-(n-1)*2).Select(x=>-x)).Concat(new int[]{(n%2)!=0?n:-n}).ToArray();} ``` [Try it online!](https://tio.run/##TY9BS8NAEIXv@RVjQdiRZkmKJ5dUxJtUKETwUHoY1k26mM7q7ra2hPz2uMSKDgzDwPce7@mQa@fNeAiWW6jPIZq9yv5/cmX5U2W6oxBg7V3raZ/1Y4gUrQbLcbOFRqQLjL1tQHBVlQjexINnYPP1w/TFvBzUkTxQ1QjOS1QXhOSjY01RkKzf7Uc6K8Nt3OUTdbNAWZvO6ChO1TI/If7if9aCrxd4VRX3fJfzgPLFPXhPZ4FqGAEuSY/OvsEzWRYh@lQvxSbMAPq0AMkzuM7IV2@jSY2NqCdKPrmkmMFsPnWUa/LBCNoUW0yjknbIhnG8/QY "C# (.NET Core) – Try It Online") ``` // Recursive Worker Function static public int[] f( int n ) { // Start with the simple case if ( n == 1 ) return new int[]{0,1}; // Recusively build off of that var a = f(n-1); // To be added at the end int[] b = { (n%2) !=0 ? n : -n }; // Skip some based on length int s = a.Length - (n-1)*2; // With the rest, multiply by -1 and then append to the end // And append the part return a.Concat( a.Skip(s).Select( x => -x ) ).Concat( b ).ToArray(); } ``` [Answer] # [J](http://jsoftware.com/), 25 bytes -5 bytes thanks to FrownyFrog! ``` >:@*:$i.;@(<@i:@*_1&^)@,] ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/OykHLSiVTz9pBw8YhE8iJN1SL03TQif2vyaWkp6CeZqunrqCjUGulkFbMxZWanJGvoKOXpqCmZ6dgqJ2pZ8b1HwA "J – Try It Online") # [J](http://jsoftware.com/), 30 bytes ``` >:@*:{.;@([:(i:@*_1&^)&.>i.,]) ``` Explanation: `i.,]` creates list 0..n `&.>` for each number in the list execute the verb in (...) and box the result (I need boxing because the results have different length) `[:( _1&^)` find -1 to the `i`th power (-1 or 1) `i:@*` make a list -n..n or n..-n, depending on the sign of the above `;@` unbox `>:@*:` find n^2 + 1 `}.` and take so many numbers from the list [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/OykHLqlrP2kEj2kojE8iJN1SL01TTs8vU04nV/K/JpaSnoJ5mq6euoKNQa6WQVszFlZqcka@go5emAFSlYKidqWfG9R8A "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~65~~ 56 bytes ``` r=k=0;exec'print r;r+=1-k**.5//1%2*2;k+=1;'*-~input()**2 ``` The output format is a bit ugly. **:/** [Try it online!](https://tio.run/##HY3BCsIwEETP2a/IRaIrtSbaiyHHevXiD2hZaIikYUnRXvz1mHoZmIH3Ji15nKIp79G/SN55pguIzEtNQR8apFKqsAvuaNeqEvuYJVveO90ExEPXtnpj0NhQF6uw@fqY5rzdIZoiRMWr6U8BVONAKcv@du2ZJ15PnkyPUDQYOMEZuh8 "Python 2 – Try It Online") [Answer] # Java 8, ~~85~~ ~~83~~ 79 bytes ``` n->{for(int p=0,i=0;i<=n*n;p+=1-(int)Math.sqrt(i++)%2*2)System.out.println(p);} ``` -6 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##LY7LDoIwEEX3fsVsTFoQgiSuav0D2LA0LmoBLcJQaSExhG/H8khmFnPnJPdUYhBBlX9mWQtjIBEKxwOAQlt0pZAFpMsJMLQqB0lcDkiZiya3bowVVklIAYHDjMFtLNtuxTSPTopHTF05esi0z8/B8qCJsO/QfDtLlO/TY@zFNPsZWzRh29tQd46pkWjKppltJbp/1q5k71pVGidKMuvg1/0h6CaJoSSX3W6a/w) **Explanation:** ``` n->{ // Method with integer parameter and no return-type for(int p=0, // Set both `p` to 0 i=0;i<=n*n; // Loop `i` in the range [0, `n*n`] p+= // After every iteration, increase `p` by: 1- // 1, minus: (int)Math.sqrt(i++) // The square-root of `i`, truncated to its integer %2*2) // Modulo 2, and multiplied by 2 System.out.println(p);} // Print integer `p` with a trailing new-line ``` [Answer] # [R](https://www.r-project.org/), ~~48 46~~ 42 bytes ``` for(i in 1:scan())F=c(F,-(-1)^i*(2-i):i);F ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdCqODkxT0NT0802WcNNR1dD11AzLlNLw0g3U9MqU9Pa7b/ZfwA "R – Try It Online") A port of [the Ruby answer](https://codegolf.stackexchange.com/a/165068/80010) by Kirill L. - and saved 6 bytes thanks to the same Kirill L.! Now shorter than [Giuseppe's solution](https://codegolf.stackexchange.com/a/165068/80010) ;) A port of [this Octave answer](https://codegolf.stackexchange.com/a/165005/80010) by Luis Mendo using `approx` is less golfy. `n=n^2+1` can be replaced by `,,n^2+1`; or by `0:n^2+1`(positional argument `xout`) for the same byte count : ### [R](https://www.r-project.org/), 56 bytes ``` f=function(n)approx((0:n)^2+1,-(-1)^(0:n)*0:n,n=n^2+1)$y ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTzOxoKAov0JDw8AqTzPOSNtQR1dD11AzDszXAhI6ebZ5IHFNlcr/xUDFOZUahlZmOnATKjSTE0s00oC0jhKXkqbmfwA "R – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes ``` +\0,¯1*⍳(/⍨)1+2×⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OApHaMgc6h9YZaj3o3a@g/6l2haahtdHg6kPf/f5qCCQA "APL (Dyalog Unicode) – Try It Online") Golfed 2 bytes thanks to @FrownyFrog by converting to a train. See the older answer and its explanation below. --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes ``` +\0,∊⊢∘-\⍴∘1¨1+2×⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@a8cY6Dzq6HrUtehRxwzdmEe9W4C04aEVhtpGh6c/6t0MVP4fqPB/GpcJAA "APL (Dyalog Unicode) – Try It Online") (Uses `⎕IO←0`) My first approach was to construct multiple ranges and concatenate them together, this easily went over 30 bytes. Then I started analysing the sequence ``` +\⍣¯1⊢0 1 0 ¯1 ¯2 ¯1 0 1 2 3 2 1 0 ¯1 ¯2 ¯3 ¯4 0 1 ¯1 ¯1 ¯1 1 1 1 1 1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ``` `+\⍣¯1` denotes the inverse cumulative sum There is a repeating pattern of 1s and ¯1s, where the length of each consecutive sequence of 1s or ¯1s is 1+2×n. And each subsequence alternates between 1 and ¯1. What I can do now is to create the 1s and ¯1s list, and then scan by + ``` ⍳4 ⍝ creates range 0..4 0 1 2 3 2×⍳4 0 2 4 6 1+2×⍳4 1 3 5 7 ⍴∘1¨1+2×⍳4 ⍝ for-each create that many 1s ┌─┬─────┬─────────┬─────────────┐ │1│1 1 1│1 1 1 1 1│1 1 1 1 1 1 1│ └─┴─────┴─────────┴─────────────┘ ⊢∘-\⍴∘1¨1+2×⍳4 ⍝ alternate signs ┌─┬────────┬─────────┬────────────────────┐ │1│¯1 ¯1 ¯1│1 1 1 1 1│¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1│ └─┴────────┴─────────┴────────────────────┘ ∊⊢∘-\⍴∘1¨1+2×⍳4 ⍝ flatten 1 ¯1 ¯1 ¯1 1 1 1 1 1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 0,∊⊢∘-\⍴∘1¨1+2×⍳4 0 1 ¯1 ¯1 ¯1 1 1 1 1 1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 +\0,∊⊢∘-\⍴∘1¨1+2×⍳4 ⍝ cumulative sum 0 1 0 ¯1 ¯2 ¯1 0 1 2 3 2 1 0 ¯1 ¯2 ¯3 ¯4 ``` [Answer] # [Haskell](https://www.haskell.org/), 47 bytes ``` (#0) m#n|m>n=[-n..n]++map(0-)(m#(n+1))|1>0=[-m] ``` [Try it online!](https://tio.run/##DcmxCoAgEADQva8QbPAQxaDVfqQcJLIk75Bq9Nu7eus74n1upXDyCyvpoENJDSfysyFrKWiNsSpnQKFUpAeANkzuXwyMMZOvV6ZH9CKJkd81lbjfbNZaPw "Haskell – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 98 bytes ``` n->{var s="0";for(int i=0,r=0,d=1;i++<n;s+=" "+r,d=-d)for(r+=d;r!=i&r!=-i;r+=d)s+=" "+r;return s;} ``` [Try it online!](https://tio.run/##ZU6xboMwFNz5iquHCuqCkqFLjDNW6tApY9XBhRA9CjayH0hRxLdTkzRdOtw73b3T6VozmbytvxfqB@cZbdTFyNQVTyr55zWjrZicXZ9J1ZkQ8G7I4pIAw/jVUYXAhiNNjmr08Zce2JM9fXzC@FPIrlHgzfLrb1d5C@zRQC82318m4xG02AjVOJ@SZZDePPuIWm8VSVlaFaQWENJHK6@zNeelrpV/0PQYT05q1dk9pvyRR28R1Lyo64C/amhsVaRS4yWylPeJwOEc@NgXbuRiiBO5sylBQuwgIjWFGYbunFKW3SrnZMW8/AA "Java (JDK 10) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 15 bytes *-2 bytes thanks to Luis Mendo!* ``` 0i:oEqG:EqY"Ysh ``` [Try it online!](https://tio.run/##y00syfn/3yDTKt@10N3KtTBSKbI44/9/UwA "MATL – Try It Online") Explanation for `n=3`: ``` 0 % push 0 i: % read input as integer, push range % stack: [0, [1 2 3]] o % modulo 2, stack: [0, [1 0 1]] Eq % double and decrement, stack: [0, [1 -1 1]] G: % push input and range again % stack: [0, [1 -1 1], [1 2 3]] Eq % double and decrement, % stack: [0, [1 -1 1], [1 3 5]] Y" % run-length decoding % stack: [0, [1 -1 -1 -1 1 1 1 1 1]] Ys % cumulative sum % stack: [0, [1 0 -1 -2 -1 0 1 2 3]] h % horizontally concatenate % end of program, automatically print the stack ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~44~~ ~~42~~ 41 bytes *2 bytes removed thanks to [@StewieGriffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin), and 1 byte further removed thanks to @Giuseppe!* ``` @(n)interp1((t=0:n).^2,-t.*(-1).^t,0:n^2) ``` [Try it online!](https://tio.run/##DYsxCsAgDAB3X@GYFBuqdBKEvkQoVcElig39vvWm4@DaI/eXZwlENC9grCx5dAsg4fCMFJ3ZhTbY7XIxq0WHs7ShWQdt/an0ItW3Q1k7qsxp/g "Octave – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~52~~ 47 bytes ``` f=->n{n<1?[0]:f[n-1]+(2-n..n).map{|x|-~0**n*x}} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0D7aINYqLTpP1zBWW8NIN09PL09TLzexoLqmoka3zkBLK0@rorb2v4ahnp6ppl5qYnJGdU1JTYFCWnRJbO1/AA "Ruby – Try It Online") Below is the original 52-byte version with an explanation: ``` f=->n{n<1?[0]:f[n-1]+[(r=*2-n..n).map(&:-@),r][n%2]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0D7aINYqLTpP1zBWO1qjyFbLSDdPTy9PUy83sUBDzUrXQVOnKDY6T9Uotva/hqGenqmmXmpickZ1TUlNgUJadAlQGAA "Ruby – Try It Online") ### Walkthrough ``` f=->n{ #Recursive approach n<1?[0] #Init with 0 if n=0 :f[n-1] #else make a recursive call + #and append an array of numbers [(r=*2-n..n) #Init r as splatted range from 2-n to n .map(&:-@) #"-@" is unary minus, so this a fancy way to do map{|x|-x} for -1 byte #For even n use this negated r, e.g. for n=4: [2, 1, 0, -1, -2, -3, -4] ,r] #For odd n use r directly, e.g. for n=3: [-1, 0, 1, 2, 3] [n%2] #Odd/even selector } ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 113 bytes ``` 0-I-[0|I]. N-[H|T]-R:-N is -H*(-1)^N,A is N-1,A-[H|T]-R;I is H-(-1)^N,N-[I|[H|T]]-R. N-O:-X is -N*(-1)^N,N-[X]-O. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30DXUzfaoMYzVo/LTzfaoyYkVjfIStdPIbNYQddDS0PXUDPOT8cRxPXTNdRxhCmx9gQJeehCFQC1etaApYByIJP8rXQjwGb4aSGURMTq@uv9t9dVMDTQ9ddRKC/KLEnV8NfU@w8A "Prolog (SWI) – Try It Online") [Answer] ## Python 3, 83 bytes ``` def c(n):print([(-1)**j*(abs(j-i)-j)for j in range(n+1)for i in range(2*j)][:-n+1]) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~18~~ 17 bytes ``` :ṁoṡ₁ŀ⁰_₁⁰ *^⁰_1⁰ ``` [Try it online!](https://tio.run/##yygtzv7/3@rhzsb8hzsXPmpqPNrwqHFDPJABpLi04kAcQyDx//9/EwA "Husk – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` F⊕NI×∨﹪ι²±¹…·∧ι⁻²ιι ``` [Try it online!](https://tio.run/##FYwxDgIhEAC/QrmbYOHFzspYWdxpjB9AWM9NYDEL3PeRayZTTMZ/nfrsYu@frAZu4pUSSaUw/Nfq0tKbFBDRPJSlwtWVCi9OVOCuMOfQYga2ZkJrFlpdJTji8HGKrfBGTycrwUXCXs0srcBkDe/NAJ57P/XDFv8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⊕ Increment F Loop over implicit range ² Literal 2 ι Current index ⁻ Subtract ι Current index ∧ Logical And ι Current index …· Inclusive range ι Current index ² Literal 2 ﹪ Modulo ¹ Literal 1 ± Negate ∨ Logical Or × Multiply I Cast to string and implicitly print ``` Alternative explanation: ``` F⊕N ``` Loop over the integers from `0` to the input inclusive. ``` I ``` Cast the results to string before printing. ``` ×∨﹪ι²±¹ ``` Negate alternate sets of results. ``` …·∧ι⁻²ιι ``` Form a list from the previous index to the current index, excluding the previous index. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Bah, I thought I had 11 wih `_2+ỊrN)N;¥/` ``` _2+ỊrN×-*$)Ẏ ``` **[Try it online!](https://tio.run/##y0rNyan8/z/eSPvh7q4iv8PTdbVUNB/u6vv//78ZAA)** ### How? ``` _2+ỊrN×-*$)Ẏ - Main Link: n e.g. 4 ) - for x in [1...n]: 1 2 3 4 _2 - subtract 2 from x -1 0 1 2 Ị - is x insignificant? 1 0 0 0 + - add 0 0 1 2 N - negate x -1 -2 -3 -4 r - inclusive range [0,-1] [0,-1,-2] [1,0,-1,-2,-3] [2,1,0,-1,-2,-3,-4] $ - last two links as a monad: - - minus one -1 -1 -1 -1 * - raised to the power x -1 1 -1 1 × - multiply [0,1] [0,-1,-2] [-1,0,1,2,3] [2,1,0,-1,-2,-3,-4] Ẏ - tighten [0,1,0,-1,-2,-1,0,1,2,3,2,1,0,-1,-2,-3,-4] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╗)SΘ█☼₧ΘP( ``` [Run and debug it](https://staxlang.xyz/#p=bb2953e9db0f9ee95028&i=2%0A3&a=1&m=2) [Answer] ### Scala, 119 Bytes ``` def a(n: Int)={lazy val s:Stream[Int]=0#::Stream.from(0).map{x=>s(x)+1 -2*(Math.sqrt(x).toInt%2)} s.take(n*n+1).toList} ``` Ungolfed: ``` def a(n: Int)={ lazy val s:Stream[Int]= 0#::Stream.from(0).map //Give the starting point and indexing scheme { x=> { val sign = 1-2*(Math.sqrt(x).toInt%2) //Determine whether we are adding or subtracting at the current index s(x)+sign } } s.take(n*n+1).toList //Take the desired values } ``` This can probably be golfed much better, but I wanted a solution utilizing lazy Streams. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~34~~ 32 bytes ``` ⎕CY'dfns'⋄-0,∘∊1↓¨2to/Sׯ1*S←⍳,⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGL1R90tugY6jzpmPOroMnzUNvnQCqOSfP3gw9MPrTfUCn7UNuFR72adR12LQHo8/YF8Ay43IEmUHi6gHiDPTcH0PwA "APL (Dyalog Unicode) – Try It Online") Requires `⎕IO←0` -2 bytes thanks to @FrownyFrog [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 44 bytes ``` [~>0\:2%\#,2*1-tr[...rep]flatmap,$sumonpref] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P7rOziDGykg1RlnHSMtQt6QoWk9Pryi1IDYtJ7EkN7FAR6W4NDc/r6AoNS32v4NVOheXqUKdnUK0lUJBaYmCuoKuHZAAMdMV8ktLYhXygHr@AwA "Stacked – Try It Online") It's been a while since I programmed in Stacked, but I think I still got it. ## Alternatives **73 bytes:** `[0\|>:2%tmo*2 infixes[:...|>\rev...|>rev#,$#'sortby 1#behead]flatmap 0\,]` This goes with the "ranges from generated indices" approach used in my [Attache answer.](https://codegolf.stackexchange.com/a/165122/31957) This proved to be pretty long, since Stacked has no builtin for reversed ranges nor collapsing. (That's what `:...|>\rev...|>rev#,$#'sortby 1#behead` does.) **53 bytes:** `[0\|>:2%tmo _\tpo#,tr[...rep]flatmap 0\,inits$summap]` ...so I decided to go for an approach which instead finds the cumulative sum (`inits$summap`) over `1` and `-1` repeated by the odd integers, as in the [R answer](https://codegolf.stackexchange.com/a/164978/31957). **46 bytes:** `[~>0\:2%\#,2*1-tr[...rep]flatmap,inits$summap]` ...but I realized that the negative integers *and* the odd integers could be made in one go, by multiplying both generated arrays (the mod 2 values of the range and the range itself) by `2` then subtracting `1`. This gives alternating `1`s and `-1`s for the first range and the odd integers for the second! **44 bytes:** `[~>0\:2%\#,2*1-tr[...rep]flatmap,$sumonpref]` ... and then I remembered I had a builtin for mapping prefixes. ^-^ [Answer] # [Julia 0.6](http://julialang.org/), 44 bytes ``` n->[(i%2*2-1)*[0:i;(n>i)*~-i:-1:1]for i=1:n] ``` [Try it online!](https://tio.run/##yyrNyUw0@x9q@z9P1y5aI1PVSMtI11BTK9rAKtNaI88uU1OrTjfTStfQyjA2Lb9IIdPW0Cov9n9BUWZeSU6eRqiGkaYmF4JnjMIzQeEZGmpqKiDzgdz/AA "Julia 0.6 – Try It Online") Since OP mentions "the output format is flexible", this prints an array of sub arrays, eg. U(3) => `[[0, 1], [0, -1, -2, -1], [0, 1, 2, 3]]`. `i%2*2-1` decides the sign of the current subarray - negative for even numbers, positive for odd. `[0:i;(n>i)*~-i:-1:1]` is in two parts. 0:i is straightforward, the range of values from 0 to the current i. In the next part, ~-i:-1:1 is the descending range from i-1 to 1. But we want to append this only if we're not yet at the final value, so multiply the upper end of the range by (n>i) so that when n==i, the range will be 0:-1:1 which ends up empty (so the array stops at n correctly). --- And here's a version that can support random access - the inner lambda here returns the i'th term of the sequence without having to have stored any of the terms before it. This one gives the output as a single neat array too. ### 49 47 bytes ``` n->map(i->((m=isqrt(i))%2*2-1)*(m-i+m^2),0:n^2) ``` [Try it online!](https://tio.run/##VcexCoAgEADQvf8I7iwhLRoC/QzHwPFCxcy@/3LM6fGuN5Df2RlO0kafgaQFiIaeu1QgxFELLRUKiJKmeGqclyM1eMiFUg0JHGjE39ZuWzelWvkD "Julia 0.6 – Try It Online") ]
[Question] [ Your challenge is simple. Write two programs that share no characters which output each other. ## Example Two programs **P** and **Q** are mutually exclusive quines if: 1. **P** outputs **Q** 2. **Q** outputs **P** 3. There is no character *c* which belongs to both **P** and **Q** 4. Each program **P** and **Q** are [**proper quines**](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) 1. This counts empty quines and quines that read their own (or the other's) source code as **invalid**. ## More rules * The shortest combined length of these programs wins. That is, size(**P**) + size(**Q**) is your score, and the lowest score wins. * Both programs are in the same language * Each program may be a full program or function, and they need not be the same. + For example, **P** may be a full program and **Q** may be a function. ## Verification This [Try it online!](https://tio.run/##TY67asNAFET7/Yqx0kh42Q8IhJAi2I0bF0m9urqKF65W0j6Mhe1v30ipMtUwDIcTcruU0nEPqgeN2CisiYYuNkQTWZgS7njQA4NxvuMbCE/FvlPKarR4w8f58KXmtdRUb1OD/QprNWzTmOzdrFyP2fAwpeX9Dz/lFFGdcspWZAHfSHJ0V95ViiXyv89nCGPQoNH34ig5/4PNzFLiEF/xcp@f1SZTSjmyyKjxPQbpduXiRH4B "Ruby – Try It Online") snippet here can verify whether or not two programs are mutually exclusive. The inputs are put in the first two arguments. [Answer] # [><>](https://esolangs.org/wiki/Fish), Score: 41+41 = 82 Edit: both contained a 3. Fixed ``` 'd3*}>a!o-!<<8:5@lI55>@z:5ll55>>q:>|q::|, ``` and ``` "r00gr40g44++bb+0p64++?b6+0.22#eW4s )Z ``` [Try it online!](https://tio.run/##S8sszvj/Xz3FWKvWLlExX1fRxsbCytQhx9PU1M6hyso0JwfIsCu0sqsptLKq0eFSKjIwSC8yMUg3MdHWTkrSNigwAzLsk8y0DfSMjMSVU8XDTYoVNKNk//8HAA) (swap the lines to get the other output) [With verification this time!](https://tio.run/##TY69ToRAGEX7eYFtP9hCEJyQFTZmsrJrYYzFNhaa2MHwgZMMf/NjFheeHcHKW53c3JxcZfNhngssgXt1CNonsERT/pUpTTVK5AauMPIRaiqaAi/AYSLYFIRkIeTwCE9vL@@kX8Dj3lr5ECyyPITM96ltRE9ECT3FujPD8U/fWaPBPVtjMykHwAuXVotvdFyCUuO/zbNSrQqBt00pBTeiqWB9lnGDSjPYXvvJXc/M83xT3N9Oaea0d87h8MCSk3xNkvT0wxIpF0h7lo49Y2M4uyqKKhVHVRwHQZ4HUbdf4Jjvg4judpstbj5iDf7nLw "Ruby – Try It Online") `><>` is an especially hard language to use here, as there is only one way to output characters, the command `o`. Fortunately, we can use the *p*ut command to place an `o` in the source code during execution, like in my [Programming in a Pristine World](https://codegolf.stackexchange.com/a/153233/76162) answer. This one took a *lot* of trial and error. I started off with the two mutually exclusive programs: ``` 'd3*}>N!o-!<<data ``` and ``` "r00gr40g8+X0pN+?Y0.data ``` Each one transforms itself and its data by N, the first one subtracting and the second adding. It then outputs this in reverse. The point is that the data after each program is the other program in reverse, shifted by N. (`X` is the cell number where the program needs to put the `o` and Y is the cell where the pointer loops back to. `?` is where the `o` is put). Both follow the same structure, represented in different ways. They run a string literal over the entire code, adding it to the stack. They recreate the string literal command they used and put it at the bottom of the stack. They loop over the stack, adding/subtracting N to each character and printing them. The first program uses `'` as the string literal, and the simple `d3*}` to create the value 39 and push it to the bottom of the stack. The second uses `"` as the string literal with the same function. It `r`everses the stack, `g`ets the character at cell 0,0 and reverses the stack again. It then `g`ets the value at cell 4,0 (`g`) and adds 8 to it to get `o` and puts that at X. Both programs use a different method of looping. The first program uses the skip command (`!`) to run only half the instructions while going left, reverses direction and runs the other half. The second uses the jump command (`.`) to skip backwards to the start of the loop at cell Y. Both of these run until there are no more items on the stack and the program errors. I ran into a number of problems with most of the lower values of N, because shifting one character would turn it into another character essential for that program (and therefore couldn't be used as data for the other program) or two characters from the two programs would shift into the same character. For example: 1. `+`+1 = `,` = `-`-1 2. `.`+2 = `0` 3. `*` = `-`-3 4. `g`+4 = `k` = `o`-4 etc. Eventually I got to 10 (`a`), where I was able to avoid these issues. There might be a shorter version where the shifts are reversed, and the first program is adding N while the second subtracts it. This might be worse off though, as the first program is generally on the lower end of the ASCII scale, so subtracting is better to avoid conflicts. [Answer] # [Forth (64-bit little-endian gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 428 + 637 = 1065 bytes ``` s" : l bl - ; : m l emit ; : s space ; : z m m m m s ; : p . 't 'i 'm 'e z ; 'e 'r 'e 'h z : q >r char l bl l do dup @ . 'L m s cell+ loop r> . ; : n 'e 'p 'y 't z ; q ; 's p 'B l p #tab p 'p 'u 'd 'Q char+ z n 'B l p n": l bl - ; : m l emit ; : s space ; : z m m m m s ; : p . 't 'i 'm 'e z ; 'e 'r 'e 'h z : q >r char l bl l do dup @ . 'L m s cell+ loop r> . ; : n 'e 'p 'y 't z ; q ; 's p 'B l p #tab p 'p 'u 'd 'Q char+ z n 'B l p n ``` ``` HERE 3245244174817823034 , 7784873317282429705 , 665135765556913417 , 7161128521877883194 , 682868438367668581 , 679209482717038957 , 680053688600562035 , 678116140452874542 , 682868623551327527 , 680649414991612219 , 682868636436227367 , 7136360695317203258 , 7809815063433470312 , 8458896374132993033 , 5487364764302575984 , 7810758020979846409 , 680166068077538156 , 4181938639603318386 , 8081438386390920713 , 8793687458429085449 , 2812844354006760201 , 7784826166316108147 , 676210045490917385 , 681493840106293616 , 7521866046790788135 , 679491013524025953 , 7928991804732031527 , 216 115 EMIT 34 EMIT 9 EMIT 2DUP TYPE 34 EMIT TYPE ``` [Try it online!](https://tio.run/##3Y9NDoMgEIXX7xp2MQtjD6CJabrupkfwB4sJCgIu7OXpDKY9RMOEmQeP74XJ@qir1yQtpVCghkFvUKHhcWGhljlm8WZ5ruC6QeUzhysogmbQAlLsaaSRz7tmXWND6zHozp9kg9Fi3B1u8vbxww3KmBLGWgff8pXg14xxoENSBL5JQOBcujPJ4RK7XhTXDhpBzxxVsnn9etbiHz@V0gc) [Verification script](https://tio.run/##3VLbbtNAEH3efMWSPrhRQ7Q7e5nZVpSLiACJSqUqSDwmjkstOY7jC2po@@1hdkML34BjZT3jM2fmnHE7LHf7/aq4kfnxeiq7yUjy1c3y20XbzbqiKvJe3suH/EGuZ2W9Ku5kLh9HRb0ajRZTuZSv5NurD99GW344zo9jaiJPmGw5lYvJZDbU5XZU3sjtrFg3/e51om@GvpPji6EfFlW1k8VdXg1d@bN4MR4VVVf8g5m37aadynxT31Rl3pf1DxknW@R90Xan8uh@@ziOw@z3@24sTkUllpV4Kc74cc1BsS77FPzi8PDrmkVepFwjZiLrRVaKbC2ygjFn8cja9H/L8anYivNWxI4H5kqsNmI1NOJNrP38TJcXVXUiqs2mEe05v4r0daJpRLaLXSL5NjbouG/2jpkacdQvljHiexDZSmRfUqsTBtdPmHr8P4raf5xfzaUB68BajZY0EhhlrJxKRLKExmgEAgsBleOs904bh94554M2XBSTGEAFS4BcHxRhqtdeayAHmhBtUApChJJSzngiz6cHBTrVk2a0VTwHFzsLCQnkyYNx3BHQAR7KvQ1W2xC4AECHv0jjrfEAaDym9oYzygcXFSgDjmKWVCDtlDfWGIvK6NiKrCMK3qDlTiGwAYazLsr3FplWgUMXKMkyymFQ2rE6RjJIP5mltEa2RXsXtI1mJfOcBtZquSWZNC6QBrbD8onIrlA4KAOvA1qltNFRR4QS82iu5AJvrYnzPnsYjOEFoFOQJgBeoUfgdsQWsvbkFymmMMRitSGFJiD8mYAF86i8NfQKVKL1Ci06w2rZdovwLIwn8zyECzwvRQL@HGzg/VvgFYOPWoGd1NrJ@cWna8kfUDrD4YD3Xy/l9ffL@fOLFPwG) Thanks to [@Nathaniel](https://codegolf.stackexchange.com/questions/153948/mutually-exclusive-quines#comment375937_153948) for the idea of using Forth - he reminded me in the comments that **Forth is not case-sensitive**. Then came the mood swings - I've been finding reasons why this will not work, followed by solutions to these problems, again and again. All while spinning my indoor training bike like an oversided and misshaped fidget spinner (you just have to grab one end of the handle bar and tilt it a bit). Before writing these programs, I drafted what characters can be used by which program. Specifically, the second program can only use uppercase letters, decimal digits, tabs, and commas. This would mean that the first program is all lowercase, but I used some uppercase letters for their ASCII values. Because tabs are unwieldy, I'll use spaces in the explanation instead. The first program is of the form `s" code"code` - the `s"` starts a string literal, which is then processed by the second copy of the code - a standard quine framework. However, instead of outputting its own source code, it will create the other program, which looks like this: * `HERE` * For each 8 bytes in the original string, `64-bit-number-literal ,` * `length-of-the-string` * `115 EMIT 34 EMIT 9 EMIT 2DUP TYPE 34 EMIT TYPE` This uses Forth's data space. `HERE` returns the pointer to the end of the currently allocated data space area, and `,` appends a cell filled with a number to it. Therefore, the first three bullet points can be seen like a string literal created using `s"`. To finish the second program off: * `EMIT` outputs a character given its ASCII value, so: + `115 EMIT` prints a lowercase `s` + `34 EMIT` prints the quote character `"` + `9 EMIT` prints a tab * `2DUP` duplicates the top two elements on the stack `( a b -- a b a b )`, here it's the pointer to and the length of the string * `TYPE` prints a string to output the first copy of the code * `34 EMIT` prints the closing quote `"`, and finally * `TYPE` outputs the second copy of the code Let's see how the first program works. In many cases numbers have to be avoided, which is done using the `'x` gforth syntax extension for character literals, and sometimes subtracting the ASCII value of space, which can be obtained using `bl`: ``` s" ..." \ the data : l bl - ; \ define a word, `l`, that subtracts 32 : m l emit ; \ define a word, `m`, that outputs a character. Because 32 is \ subtracted using `l`, lowercase characters are converted to \ uppercase, and uppercase characters are converted to some \ symbols, which will become useful later : z m m m m space ; \ `z` outputs four characters using `m`, followed by a \ space. This is very useful because all words used in the \ second program are four characters long : p . 't 'i 'm 'e z ; \ define a word, `p`, that, given a number, outputs that \ number, followed by a space, `EMIT`, and another space 'e 'r 'e 'h z \ here is where outputting the second program starts - `HERE ` : q \ define a helper word, `q`, that will be called only once. This is done \ because loop constructs like do...loop can't be used outside of a word. >r \ q is called with the address and the length of the data string. >r saves \ the length on the return stack, because we don't need it right now. While \ it might seem like this is too complicated to be the best way of doing \ this for codegolf, just discaring the length would be done using four \ characters - `drop`, which would give you the same bytecount if you could \ get the length again in... 0 characters. char l \ get a character from after the call to q, which is `;`, with the \ ASCII value of $3B, subtract $20 to get $1B, the number of 64-bit \ literals necessary to encode the string in the second program. bl l \ a roundabout way to get 0 do \ iterate from 0 (inclusive) to $1B (exclusive) \ on the start of each iteration, the address of the cell we are currently \ processing is on the top of the stack. dup @ . \ print the value. The address is still on the stack. 'L m space \ the ASCII value of L is exactly $20 larger than the one of , cell+ \ go to the next cell loop r> . \ print the length of the string ; : n 'e 'p 'y 't z ; \ define a word, `n`, that outputs `TYPE` q ; \ call q, and provide the semicolon for `char` (used to encode the length \ of the string in 64-bit words). Changing this to an uppercase U should \ make this work on 32-bit systems, but I don't have one handy to check that 's p \ print the code that outputs the lowercase s 'B l p \ likewise, 'B l <=> $42 - $20 <=> $22 <=> the ASCII value of a comma #tab p \ print the code that outputs a tab 'p 'u 'd 'Q char+ z \ char+ is the best way to add 1 without using any digits. \ it is used here to change the Q to an R, which can't be \ used because of `HERE` in the second program. R has an \ ASCII value exactly $20 larger than the ASCII value of 2, \ so this line outputs the `2DUP`. n 'B l p n \ output TYPE 34 EMIT TYPE to finish the second program. Note the \ that the final `n` introduces a trailing space. Trying to remove \ it adds bytes. ``` To finish this off, I'd like to say that I tried using `EVALUATE`, but the second program becomes larger than both of the ones presented above. Anyway, here it is: ``` : s s" ; s evaluate"s" : l bl - ; : m l emit ; : d here $b $a - allot c! ; : c here swap dup allot move ; : q bl l do #tab emit dup @ bl l u.r cell+ #tab emit 'L m loop ; here bl 'B l 's bl 's bl 'Z l d d d d d d d -rot c bl 'B l 's 'B l d d d d s c 'B l d c 'e 'r 'e 'h m m m m 'A q #tab emit 'e 'p 'y 't m m m m"; s evaluate ``` If you manage to golf this down enough to outgolf my `s" ..."...` approach, go ahead and post it as your own answer. [Answer] # Perl, ~~(311+630 = 941 bytes)~~ 190+198 = 388 bytes Both programs print to standard output. The first perl program contains mostly printable ASCII characters and newlines, and it ends in exactly one newline, but the two letter ÿ represents the non-ASCII byte \xFF: ``` @f='^"ÿ"x92;@f=(@f,chr)for 115,97,121,36,126,191,153,194,216,113;print@f[1..5,5,10,5..9,0,9,0,5]'^"ÿ"x92;@f=(@f,chr)for 115,97,121,36,126,191,153,194,216,113;print@f[1..5,5,10,5..9,0,9,0,5] ``` The second one contains mostly non-ASCII bytes, including several high control characters that are replaced by stars in this post, and no newlines at all: ``` say$~~q~¿*ÂØ¡Ý*Ý*ÆÍÄ¿*Â׿*Ó***Ö***ßÎÎÊÓÆÈÓÎÍÎÓÌÉÓÎÍÉÓÎÆÎÓÎÊÌÓÎÆËÓÍÎÉÓÎÎÌÄ*****¿*¤ÎÑÑÊÓÊÓÎÏÓÊÑÑÆÓÏÓÆÓÏÓʢءÝ*Ý*ÆÍÄ¿*Â׿*Ó***Ö***ßÎÎÊÓÆÈÓÎÍÎÓÌÉÓÎÍÉÓÎÆÎÓÎÊÌÓÎÆËÓÍÎÉÓÎÎÌÄ*****¿*¤ÎÑÑÊÓÊÓÎÏÓÊÑÑÆÓÏÓÆÓÏÓÊ¢~ ``` A hexdump of the first program with `xxd` is: ``` 00000000: 4066 3d27 5e22 ff22 7839 323b 4066 3d28 @f='^"."x92;@f=( 00000010: 4066 2c63 6872 2966 6f72 2031 3135 2c39 @f,chr)for 115,9 00000020: 372c 3132 312c 3336 2c31 3236 2c31 3931 7,121,36,126,191 00000030: 2c31 3533 2c31 3934 2c32 3136 2c31 3133 ,153,194,216,113 00000040: 3b70 7269 6e74 4066 5b31 2e2e 352c 352c ;print@f[1..5,5, 00000050: 3130 2c35 2e2e 392c 302c 392c 302c 355d 10,5..9,0,9,0,5] 00000060: 275e 22ff 2278 3932 3b40 663d 2840 662c '^"."x92;@f=(@f, 00000070: 6368 7229 666f 7220 3131 352c 3937 2c31 chr)for 115,97,1 00000080: 3231 2c33 362c 3132 362c 3139 312c 3135 21,36,126,191,15 00000090: 332c 3139 342c 3231 362c 3131 333b 7072 3,194,216,113;pr 000000a0: 696e 7440 665b 312e 2e35 2c35 2c31 302c int@f[1..5,5,10, 000000b0: 352e 2e39 2c30 2c39 2c30 2c35 5d0a 5..9,0,9,0,5]. ``` And a hexdump of the second program is: ``` 00000000: 7361 7924 7e7e 717e bf99 c2d8 a1dd 00dd say$~~q~........ 00000010: 87c6 cdc4 bf99 c2d7 bf99 d39c 978d d699 ................ 00000020: 908d dfce ceca d3c6 c8d3 cecd ced3 ccc9 ................ 00000030: d3ce cdc9 d3ce c6ce d3ce cacc d3ce c6cb ................ 00000040: d3cd cec9 d3ce cecc c48f 8d96 918b bf99 ................ 00000050: a4ce d1d1 cad3 cad3 cecf d3ca d1d1 c6d3 ................ 00000060: cfd3 c6d3 cfd3 caa2 d8a1 dd00 dd87 c6cd ................ 00000070: c4bf 99c2 d7bf 99d3 9c97 8dd6 9990 8ddf ................ 00000080: cece cad3 c6c8 d3ce cdce d3cc c9d3 cecd ................ 00000090: c9d3 cec6 ced3 ceca ccd3 cec6 cbd3 cdce ................ 000000a0: c9d3 cece ccc4 8f8d 9691 8bbf 99a4 ced1 ................ 000000b0: d1ca d3ca d3ce cfd3 cad1 d1c6 d3cf d3c6 ................ 000000c0: d3cf d3ca a27e .....~ ``` In the second program, the quoted string (189 bytes long, delimited by tildes) is the entire first program except the final newline, only encoded by bitwise complementing each byte. The second program simply decodes the string by complementing each of the bytes, which the `~` operator does in perl. The program prints the decoded string followed by a newline (the `say` method adds a newline). In this construction, the decoder of the second program uses only six different ASCII characters, so the first program can be practically arbitrary, as long as it only contains ASCII characters and excludes those six characters. It's not hard to write any perl program without using those five characters. The actual quine logic is thus in the first program. In the first program, the quine logic uses a 11 word long dictionary `@f`, and assembles the output from those words. The first words repeats most of the source code of the first program. The rest of the words are specific single characters. For example, word 5 is a tilde, which is the delimiter for the two string literal in the second program. The list of numbers between the brackets is the recipe for which words to print in what order. This is a pretty ordinary general construction method for quines, the only twist in this case is that the first dictionary words is printed with its bytes bitwise complemented. [Answer] # [Haskell](https://www.haskell.org/), 306 + 624 = 930 bytes Program 1: An anonymous function taking a dummy argument and returning a string. ``` (\b c()->foldr(\a->map pred)b(show()>>c)`mappend`show(map(map fromEnum)$tail(show c):pure b))"İĴİóđđđÝöÝâÝæÝääē××êääē××İēÀħđĮâħēĕóİóòòĮááħááđéêâéêēááĮÀħ""(\b c()->foldr(\a->map pred)b(show()>>c)`mappend`show(map(map fromEnum)$tail(show c):pure b))" ``` [Try it online!](https://tio.run/##tY87asNAEIavsggVO4VygIDVmPSGNClUePWKTVbSspJI6ysYEVK5sBAWTmGME3yB2XN5M6vGJzDDP4@f@QZmJeqPTEpbiHU5U23z2ugn7nMAP7I8ilnCIQjzSqaaRyIIC6GY0lkKMa9X1SeHMExgSa7KynQ5WTQ4sVxXxUvZFuA3Yi2ndZbAs2p1xmIAz5zNnznjr9m6wB1eST3pQBpwMB1@U/zceyI63JiR9k/YU@3MF/F0Ay94IW@PezNOeYtHInuXiXHOyZGe99ifrL0luRTvtQ3e5ovFPw "Haskell – Try It Online") Program 2: `q[[40,...]]` at the end is an anonymous function taking a dummy argument and returning a string. ``` z~z=[[['@','0'..]!!4..]!!z] q[x,q]_=z=<<x++q++[34,34]++x q[[40,92,98,32,99,40,41,45,62,102,111,108,100,114,40,92,97,45,62,109,97,112,32,112,114,101,100,41,98,40,115,104,111,119,40,41,62,62,99,41,96,109,97,112,112,101,110,100,96,115,104,111,119,40,109,97,112,40,109,97,112,32,102,114,111,109,69,110,117,109,41,36,116,97,105,108,40,115,104,111,119,32,99,41,58,112,117,114,101,32,98,41,41,34],[304,308,304,243,273,273,273,221,246,221,226,221,230,221,228,228,275,215,215,234,228,228,275,215,215,304,275,192,295,273,302,226,295,275,277,243,304,243,242,242,302,225,225,295,225,225,273,233,234,226,233,234,275,225,225,302,192,295]] ``` [Try it online!](https://tio.run/##bVHbSgQxDH3fv1gQRpmwNE0vU9gB/8HHMsg@CIqrOLrCMA/@@pik3Yu4D6dJ2nNO0vZ59/X6tN8vb7uX9/7j@/Bw@LyZbu@W@Wfuc87NfQONaTabYb12us7DaswTjMNjP/fb7dS2Y9tmckBuaNtpNfVjzs5AspA6IF4TcOkQnIdgAQ0DkWPHMJw7qPR4oiQpEK3oJQgJDaqAndjYidLzhitueOzC@lCaMi9ceinEBI0ayel/iwvB34qOs1c6n4RUzDBqyR1JPINKjNc7XhmUjvP5rg4WTzckfTZ5LZQXhUwsJPaRaB2BjRewyHuhRFsjmVp3BdGDxQr@pmv76s018i/Y5NWb@K7qqbUgav/THM4qCs8XJH/OZT6i2jOc83jmiLb2HIZl@QU "Haskell – Try It Online") Character set 1 (includes space): ``` "$()-:>E\`abcdefhilmnoprstuw×ÝáâäæéêñòóöđēĕħĮİĴ ``` Character set 2 (includes newline): ``` !'+,.0123456789<=@[]_qxz~ ``` Since only set 1 contains non-ASCII characters, their UTF-8 bytes are also disjoint. # How it works * Program 1 is generally written with lambda expressions, spaces and parentheses, free use of builtin alphanumeric functions, and with the quine data as string literals at the end. + Program 1's own core code is turned into string literal data simply by surrounding it with quote marks. - To support this, every backslash is followed by `a` or `b`, which form valid escape sequences that roundtrip through `show`. - Another tiny benefit is that `a`, `b` and `c` are the only lower case letters whose ASCII codes are less than 100, saving a digit in the numerical encoding used by program 2. + The string literal encoding of program 2's core code is more obfuscated by using non-ASCII Unicode: Every character has 182 added to its code point to ensure there is no overlap with the original characters. - 182 used to be 128, until I realized I could abuse the fact that 182 is twice the length of the string literal for program 1's code to shorten the decoding. (As a bonus, program 2 can use newlines.) * Program 2 is generally written with top level function equations (except for the final anonymous one), character literals and decimal numbers, list/range syntax and operators, and with the quine data as a list of lists of `Int`s at the end. + Program 1's core code is encoded as a list of its code points, with a final double quote. + Program 2's core code is encoded as the list of code points of the string literal used in program 1, still shifted upwards by 182. # Walkthrough, program 1 * `b` and `c` are the values of the string literals for program 2 and 1, respectively, given as final arguments to the lambda expression. `()` is a dummy argument solely to satisfy PPCG's rule that the program should define a function. * `foldr(\a->map pred)b(show()>>c)` decodes the string `b` to the core code of program 2 by applying `map pred` to it a number of times equal to the length of `show()>>c == c++c`, or `182`. * `tail(show c)` converts the string `c` to the core code of program 1, with a final double quote appended. * `:pure b` combines this in a list with the string `b`. * `map(map fromEnum)$` converts the strings to lists of code points. * ``mappend`show(...)` serializes the resulting list of lists and finally appends it to the core code of program 2. # Walkthrough, program 2 * The toplevel `z~z=[[['@','0'..]!!4..]!!z]` is a function converting code points back to characters (necessary to write since not all the characters in `toEnum` are available.) + Its code point argument is also called `z`. The laziness marker `~` has no effect in this position but avoids a space character. + `['@','0'..]` is a backwards stepping list range starting at ASCII code 64, then jumping 16 down each step. + Applying `!!4` to this gives a `\NUL` character. + Wrapping that in a `[ ..]` range gives a list of all characters, which `!!z` indexes. + The character is finally wrapped in a singleton list. This allows mapping the function `z` over lists using `=<<` instead of the unavailable `map` and `<$>`. * The toplevel `q[x,q]_=z=<<x++q++[34,34]++x` is a function constructing program 1 from the quine data list. + `x` is the data for the core of program 1 (including a final double quote) and the inner `q` is the obfuscated data for the core of program 2. `_` is another dummy argument solely to make the final anonymous function a function instead of just a string. + `x++q++[34,34]++x` concatenates the pieces, including two double quote marks with ASCII code 34. + `z=<<` constructs program 1 by mapping `z` over the concatenation to convert from code points to characters. * The final `q[[40,...]]` is an anonymous function combining `q` with the quine data. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~128 90 87 86 85 79~~ 16 + 32 = 48 bytes ``` “OṾ⁾ọṙŒs”OṾ⁾ọṙŒs ``` [Try it online!](https://tio.run/##y0rNyan8//9Rwxz/hzv3PWrc93B378OdM49OKn7UMBdd6P9/AA "Jelly – Try It Online") ``` 79,7806,8318,7885,7769,338,115ỌṘ ``` [Try it online!](https://tio.run/##y0rNyan8/9/cUsfcwsBMx8LY0ALIsjDVMTc3s9QxNrbQMTQ0fbi75@HOGf//AwA "Jelly – Try It Online") The first program does the following: ``` “OṾ⁾ọṙŒs”OṾ⁾ọṙŒs “OṾ⁾ọṙŒs” String literal: 'OṾ⁾ọṙŒs' O ord: [79, 7806, 8318,...] Ṿ Uneval. Returns '79,7806,8318,7885,7769,338,115' ⁾ọṙ Two character string literal: 'ọṙ' Œs Swap case the two char literal: 'ỌṘ'. ``` This leaves the strings `79,7806,8318,7885,7769,338,115` and `ỌṘ` as the two arguments of the chain and they are implicitly concatenated and printed at the end. The second program calculates the `chr` (`Ọ`) of the list of numbers which returns `OṾ⁾ọṙŒs`. `Ṙ` prints `“OṾ⁾ọṙŒs”` (with quotes) and returns the input, leaving `“OṾ⁾ọṙŒs”OṾ⁾ọṙŒs` as the full output. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~23 + 23 = 46~~ ~~22 + 22 = 44~~ 20 + 20 = 40 bytes ``` "lF{3+|3d*HqlJJJQpp2 ``` [Try it online!](https://tio.run/##S8/PScsszvj/XynHrdpYu8Y4RcujMMfLyyuwoMDo/38A "Gol><> – Try It Online") ``` '5ssTMMMotK-g6.6~Io ``` [Try it online!](https://tio.run/##S8/PScsszvj/X920uDjE19c3v8RbN92sXs@szjP//38A "Gol><> – Try It Online") [Verify it online!](https://tio.run/##TY5NT4QwFEX3/RVPXAgOduHEWZgY48IvDAuNcV8ej7FJKdDXmiEw@tMruPKubm5uTo4L1RhjTQ1g2ubAmYAlLPFTOZZMhtDDBDPO0EptazoAwlGQrYVQOVRwA3dvjx9iWEqK6TplsFlgVQ4qy2SwehC6gUFS2/vx9g/fB8@QlMEHZcwIdEATWH/RSSLIMP373DvXuRyws43R6LXdw2qm0JPjazidhmOyysQYE/MwbTfztj5/GkxRFK99fxnPrpjfy7Ls/MvFfvcjd9/P3S8 "Ruby – Try It Online") ### How they work ``` "lF{3+|3d*HqlJJJQpp2 "..." Push everything to the stack lF{3+| Add 3 to everything on the stack 3d* Push 39 `'` H Print everything on the stack (from the top) and halt '5ssTMMMotK-g6.6~Io '...' Push everything to the stack 5ss Push 37 (34 `"` + 3) T t Loop indefinitely... MMMo Decrement 3 times, pop and print At the end, `o` tries to print charcode -3, which is fishy (thanks Jo King) Program terminates ``` Adapted from [Jo King's ><> answer](https://codegolf.stackexchange.com/a/153965/78410). Having many more alternative commands for output and repeat, there was no need for `g` or `p`, and the two main bodies became much shorter. Another main difference is that I generate the opponent's quote directly at the top of the stack. This way, it was slightly easier to keep the invariant of `quote + my code + opponent code(reversed and shifted)`. ]
[Question] [ [Raffaele Cecco](https://www.retrogamer.net/profiles/developer/raffaele-cecco/) is a programmer who produced [some](http://www.crashonline.org.uk/43/exolon.htm) of the [best](https://en.wikipedia.org/wiki/Cybernoid) video games for the [ZX Spectrum](https://en.wikipedia.org/wiki/ZX_Spectrum) computer in the late eighties. Among others, he developed the highly acclaimed [Cybernoid](https://www.youtube.com/watch?v=qJ2JJJGdIck&feature=youtu.be&t=8) and [Exolon](https://www.youtube.com/watch?v=LGpQxt3vn3o). Raffaele is [turning 50 on May 10, 2017](https://en.wikipedia.org/wiki/Raffaele_Cecco). This challenge is a small tribute to him, for the happy hours that many of us spent playing those terrific games, and for the motivation they brought. # The challenge The purpose is to produce a rectangular marquee inspired by that seen in Cybernoid's [main menu screen](https://www.youtube.com/watch?v=qJ2JJJGdIck&feature=youtu.be&t=10), but in ASCII art. Specifically, the string `"Happy birthday Raffaele Cecco "` (note the final space) will be shown rotating along the edges of an 12×5 rectangle, with a constant pause time between snapshots. For example, assuming the text is displayed clockwise and rotated counter-clockwise (see options below), here are three consecutive snapshots of the rectangular marquee: ``` Happy birthd a o y c ceC eleaffaR ``` then ``` appy birthda H y o R cceC eleaffa ``` then ``` ppy birthday a H R a occeC eleaff ``` and so on. # Rules No input will be taken. Output will be through STDOUT or equivalent, or in a graphical window. The output should actually depict the text rotating; that is, each new snapshot should *overwrite* the previous one to give the impression of movement. This can be done by any means, for example, by writing the appropriate number of newlines to effectively clear the screen. It's acceptable if this is valid only for a given screen size; just specify it in the answer. The following options are accepted: * Text can be displayed clockwise or counter-clockwise, and can be rotated clockwise or counter-clockwise (the example snapshots above assume clockwise displaying and counter-clockwise rotating). * Rotation should go on cyclically in an infinite loop (until the program is stopped), and can start at any phase. * Pause time between snapshots should be approximately constant, but can be freely chosen between 0.1 and 1 s. An initial pause before displaying the first snapshot is acceptable. * Letters can be upper-case, lower-case or mixed case (as in the example above). * Leading or trailing blank space is allowed. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398). [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. If possible, please provide a gif file showing the output, or a link to test the program. Shortest code in bytes wins. [Answer] ## HTML + ES6, 200 bytes ``` <pre id=o><script>setInterval(_=>o.innerHTML=(f=k=>k--?f(k)+(k<11?s[k]:k>47?s[74-k]:k%12?++k%12?' ':s[10+k/12]+` `:s[30-k/12]):'')(60,s=s.slice(1)+s[0]),99,s="Happy birthday Raffaele Cecco ")</script> ``` [Answer] # ZX Spectrum BASIC, 187 bytes Annoyed that Philip beat me to it by a couple of minutes :-) Numbers like `\{15}` are unprintable control codes - compile with [zmakebas](http://www.svgalib.org/rus/zmakebas.html) if you want to tinker. Note that the full rectangle isn't printed immediately, but it falls into place after the first few frames. ``` 1 let a$=" Happy birthday Raffaele Cecco":dim b$(code"\{15}"):dim c$(pi*pi) 3 let b$=a$(sgn pi)+b$:let a$=a$(val"2" to)+a$(sgn pi):print "\{0x16}\{0}\{0}";a$(to code"\{12}")'b$(sgn pi);c$;a$(val"13")'b$(val"2");c$;a$(code"\{14}")'b$(pi);c$;a$(len b$)'b$(val"4" to):go to pi ``` Try it here (online JS-emulated version, press enter to start)... <http://jsspeccy.zxdemo.org/cecco/> You can also save four bytes by clearing the screen between frames instead of doing a PRINT AT, but it's too flickery to be worth it... ``` 1 let a$=" Happy birthday Raffaele Cecco":dim b$(code"\{15}"):dim c$(pi*pi) 3 let b$=a$(sgn pi)+b$:let a$=a$(val"2" to)+a$(sgn pi):cls:print a$(to code"\{12}")'b$(sgn pi);c$;a$(val"13")'b$(val"2");c$;a$(code"\{14}")'b$(pi);c$;a$(len b$)'b$(val"4" to):go to pi ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~74~~ 65 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ÆÇÐÑ÷øœ‘Ṭœṗ⁸ṙ©-¤4421œ?U0¦;"⁷,⁶ẋ⁵¤¤ṁ9¤ȮœS.®ß “9ɲcḟ#%⁴1t(ŀȷUCOw⁾»Ç ``` Windows version running in a 6 line high cp-65001 console. There is a half a second (plus evaluation) pause between iterations: [![gif of output](https://i.stack.imgur.com/H9cJd.gif)](https://i.stack.imgur.com/H9cJd.gif) ### How? ``` “9ɲcḟ#%⁴1t(ŀȷUCOw⁾»Ç - Main link: no arguments “9ɲcḟ#%⁴1t(ŀȷUCOw⁾» - compression of [d( Happy)+d( birthday)+d( Raff)+s(aele)+d( Ce)+d(cc)+s(o)] - d=dictionaryLookup, s=stringEncode. - = " Happy birthday Raffaele Cecco" Ç - call last link (1) as a monad “ÆÇÐÑ÷øœ‘Ṭœṗ⁸ṙ©-¤4421œ?U0¦;"⁷,⁶ẋ⁵¤¤ṁ9¤ȮœS.®ß - Link 1, rotate, print, recurse: string s ¤ - nilad followed by link(s) as a nilad: ⁸ - link's left argument (initially s) - - literal -1 ṙ - rotate left -1 (e.g. "blah" -> "hbla") © - copy to register and yield “ÆÇÐÑ÷øœ‘ - literal: [13,14,15,16,28,29,30] Ṭ - untruth: [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1] œṗ - partition right at truthy indexes of left - chops up the rotated string into 8 - e.g. [" Happy birth",'d','a','y'," Raffaele Ce",'c','c','o']) 4421œ? - get the 4421st permutation of those items - e.g. [" Happy birth",'o','d','c','a','c','y'," Raffaele Ce"] ¦ - apply to indexes: 0 - 0 (right most) U - upend (e.g. " Raffaele Ce" -> "eC eleaffaR ") ¤ - nilad followed by link(s) as a nilad: ¤ - nilad followed by link(s) as a nilad: ¤ - nilad followed by link(s) as a nilad: ⁶ - literal space ⁵ - literal 10 ẋ - repeat: " " ⁷ - literal new line , - pair: ['\n'," "] 9 - literal 9 ṁ - mould like: ['\n'," ",'\n'," ",'\n'," ",'\n'," ",'\n'] " - zip with: ; - concatenation - e.g. [" Happy birth\n","o ","d\n","c ","a\n","c ","y\n","eC eleaffaR ","\n"]) Ȯ - print and yield . - literal 0.5 œS - after sleeping right seconds yield left ® - recall value from register (s rotated by 1) ß - call this link (1) with the same arity (as a monad) ``` [Answer] # V, ~~75~~ ~~71~~ 70 bytes *4 bytes saved thanks to @DJMcMayhem* ``` iHappy birthd ±± a o±° y c±± ceC eleaffaR6ògÓÉ {dêjP2Ljjx1Lp5LxkpGd ``` Here is a TIO link, but note that this will not work on TIO because the program loops infinitely. [Try it online!](https://tio.run/nexus/v#@5/pkVhQUKmQlFlUkpHCdWjjoY0KiVz5QHqDQiVXMpjPlZzqrJCak5qYlpYYJG12eFP64cmHOxWqUw6vygow8hHLyqow9Ckw9anILnBP@f8fAA "V – TIO Nexus") Since this code contains unprintables, here is a hexdump. ``` 00000000: 6948 6170 7079 2062 6972 7468 640a b1b1 iHappy birthd... 00000010: 2061 0a6f b1b0 2079 0a63 b1b1 200a 6365 a.o.. y.c.. .ce 00000020: 4320 656c 6561 6666 6152 1b36 f267 d3c9 C eleaffaR.6.g.. 00000030: 207b 64ea 6a50 324c 166a 6a78 314c 7035 {d.jP2L.jjx1Lp5 00000040: 4c78 6b70 4764 LxkpGd ``` The sleep time is 500 milliseconds. [![giffy](https://i.stack.imgur.com/T7O62.gif)](https://i.stack.imgur.com/T7O62.gif) [Answer] ## SVG(HTML5), 267 bytes ``` <svg width=200 height=90><defs><path id=p d=M40,20h120v50h-120v-50h120v50h-120v-50></defs><text font-size="19" font-family="monospace"><textPath xlink:href=#p>Happy birthday Raffaele Cecco<animate attributeName=startOffset from=340 to=0 dur=5s repeatCount=indefinite> ``` Well, it *is* rectangular, and it *is* a marquee, and it *is* ASCII text... [Answer] # ZX Spectrum BASIC, 274 bytes Well, someone had to do it. Pedants may wish to disqualify this for being too slow and not having a pause between animations, but I'm claiming a special case here :-) ``` 10 LET m$=" Happy birthday Raffaele Cecco": LET o=0: LET l=LEN m$: LET f=4: LET t=12: LET a=t+f: LET b=27 20 FOR j=SGN PI TO l: LET i=j+o: IF i>l THEN LET i=i-l 40 LET x=(i-SGN PI AND i<=t)+(11 AND i>t AND i<=a)+(b-i AND i>a AND i<=b) 50 LET y=(i-t AND i>t AND i<=a)+(f AND i>a AND i<=b)+(b+f-i AND i>b): PRINT AT y,x;m$(j): NEXT j 80 LET o=o+SGN PI: IF o>=l THEN LET o=o-l 90 GO TO t ``` Not very golfed either. 274 bytes is the number of bytes saved by the Spectrum to tape when saving this program. [Answer] # PHP, 184 bytes ``` for($r=" ";++$i;sleep(print chunk_split(str_pad($r,96," ",0),12)),$r=$k="0")for(;$c="ABCDEFGHIJKWco{zyxwvutsrqpdXL@"[$k];)$r[ord($c)-64]="Happy Birthday Raffaele Cecco "[($i+$k++)%30]; ``` prints 39 newlines to clear the screen; run with `-nr`. The actual pause is 1 second; but I sped up the gif. [![HappyBirthday](https://i.stack.imgur.com/ukSwb.gif)](https://i.stack.imgur.com/ukSwb.gif) **ungolfed** ``` $p = "ABCDEFGHIJKWco{zyxwvutsrqpdXL@"; # (positions for characters)+64 to ASCII $t = "Happy Birthday Raffaele Cecco "; # string to rotate for($r=" "; # init result to string ++$i; # infinite loop $r=$k="0") # 6. reset $r and $k { for(;$c=$p[$k];) # 1. loop through positions $r[ord($c)-64]= # set position in result $t[($i+$k++)%30]; # to character in string sleep( # 5. wait 1 second print # 4. print chunk_split( str_pad($r,96,"\n",0) # 2. pad to 96 chars (prepend 36 newlines) ,12) # 3. insert newline every 12 characters ); } ``` [Answer] # Python 2, ~~230~~ 184 bytes ``` import time s='Happy birthday Raffaele Cecco '*2 i=0 while[time.sleep(1)]:print'\n'*30+'\n'.join([s[i:i+12]]+[s[i-n]+' '*10+s[i+11+n]for n in 1,2,3]+[s[(i+15)%30:][11::-1]]);i+=1;i%=30 ``` --- [Try it at repl.it](https://repl.it/HpMw/1) [![enter image description here](https://i.stack.imgur.com/WcRWJ.gif)](https://i.stack.imgur.com/WcRWJ.gif) [Answer] # [Python 3](https://docs.python.org/3/), 160 bytes ``` import time;s="Happy_birthday_Raffaele_Cecco_" while[time.sleep(1)]:print(s[:12]+'\n%s%%11s'*3%(*s[:-4:-1],)%(*s[12:15],)+'\n'+s[-4:14:-1]+'\n'*30);s=s[1:]+s[0] ``` [Try it online!](https://tio.run/nexus/python3#HY69DoIwFEZ3n8KQNJQihgu61Di5OLvWpql4CU34aWgTw9PX0vF85wxfMJNdVn/0ZsKbu2dPbe2mPmb1w1dv6qX7XuOI6oFdt6js8BvMiGKvz25EtBQKye1qZk@d4NDIMn/PxBEC4HLWEsriXF14BfJUJIKGwzXCHualE1FC8mlgbV3EHzHjMspahvAH "Python 3 – TIO Nexus") (No animation) [Answer] # Python 2, 218 200 190 181 176 bytes ``` import time;f='Happy birthday Raffaele Cecco ' while[time.sleep(1)]:v=f[::-1];print'\n'*90,f[:12],''.join('\n'+a+' '*10+b for a,b in zip(v[:3],f[12:16])),'\n',v[3:15];f=f[1:]+f[0] ``` -18 bytes by removing `str` formatting -10 bytes, thanks to @Uriel and @ElPedro suggestions -9 bytes by removing negative indexing -5 bytes by storing reversed `f` as `v` and `while` condition [repl.it](https://repl.it/HpKs/6) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [Ž-∊13в.•:=r}ƒyp$γ•™“ŽØ¢© ÿ“.ªN._Ž9¦S.Λ,т.W ``` What better time to answer a birthday related challenge than on your own birthday. ;) Outputs and rotates in a similar matter as the challenge description; sleeps for 100 ms in between iterations (could alternatively sleep for 255 ms, 256 ms, or 1 second for the same byte-count by replacing the `т` with `₅`, `₁`, or `₄` respectively). Prints each iteration as a loose output (so without clearing the console and overwriting). [Try the first \$n\$ iterations online (without sleep).](https://tio.run/##AU0Asv9vc2FiaWX//0bFvS3iiIoxM9CyLuKAojo9cn3GknlwJM6z4oCi4oSi4oCcxb3DmMKiwqkgw7/igJwuwqpOLl/FvTnCplMuzpss//8xMA) Or as gif in my local console: [![enter image description here](https://i.stack.imgur.com/TBcnk.gif)](https://i.stack.imgur.com/TBcnk.gif) **Explanation:** ``` [ # Loop indefinitely: Ž-∊ # Push compressed integer 27370 13в # Convert it to base-13 as list: [12,5,12,5] .•:=r}ƒyp$γ• # Push compressed string "raffaele cecco " ™ # Titlecase the words: "Raffaele Cecco " “ŽØ¢© ÿ“ # Push compressed string "happy birthday ÿ", # where `ÿ` is automatically filled with the top of the stack: # "happy birthday Raffaele Cecco " .ª # Sentence capitalize it, leaving existing caps intact: # "Happy birthday Raffaele Cecco " N._ # Rotate the characters in this string the 0-based loop-index # amount of times towards the left Ž9¦ # Push compressed integer 2460 S # Convert it to a list of digits: [2,4,6,0] .Λ # Use the Canvas builtin with these three options , # Pop and print it with trailing newline т.W # Sleep for 100 milliseconds ``` [See this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“ŽØ¢© ÿ“` is `"happy birthday ÿ"`; `.•:=r}ƒyp$γ•` is `"raffaele cecco "`; `Ž-∊` is `27370`; `Ž9¦` is `2460`; and `Ž-∊13в` is `[12,5,12,5]`. As for the Canvas builtin: it takes three arguments to draw a shape: * Character/string to draw: the potentially rotated `"Happy birthday Raffaele Cecco "` in this case * Length of the lines we'll draw: the list `[12,5,12,5]` * The direction to draw in: `[2,4,6,0]`. The digits in the range [0,7] each represent a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` So the `[2,4,6,0]` in this case translates to the directions \$[→,↓,←,↑]\$. here a step-by-step explanation of the output for the initial state: Step 1: Draw 12 characters (`"Happy birthd"`) in direction `2→`: ``` Happy birthd ``` Step 2: Draw 5-1 characters (`"ay R"`) in direction `4↓`: ``` Happy birthd a y R ``` Step 3: Draw 12-1 characters (`"ceC eleaffa"`) in direction `6←`: ``` Happy birthd a y ceC eleaffaR ``` Step 4: Draw 5-1 characters (`"co H"`) in direction `0↑`: ``` Happy birthd a o y c ceC eleaffaR ``` [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) [Answer] # Ruby + GNU Core Utils, 136 bytes ``` s='Happy birthday Raffaele Cecco ' loop{puts`clear`+s[0,12],(0..2).map{|i|s[~i]+' '*10+s[12+i]},s[15,12].reverse s=s[1,29]+s[0];sleep 1} ``` [Answer] # Python 2, ~~182~~ ~~179~~ ~~173~~ 160 bytes ``` i="Happy birthday Raffaele Cecco " while[s for s in i*18**4]:print'\n'*99,'\n'.join([i[:12]]+[i[-z]+' '*10+i[11+z]for z in 1,2,3]+[i[15:-3][::-1]]);i=i[1:]+i[0] ``` [Try it at repl.it](https://repl.it/HpSm/8) Doesn't work on TIO so my first attempt at using [repl.it](https://repl.it/) **Edit** Using a "time-wasting" loop to count to 1000000 gives a consistent delay of *between 0.1 and 1s* on my machine and on [repl.it](https://repl.it/HpSm/1) and saves importing `time`. I guess if you ran it on an old 286 computer with 64MB RAM it may go over the 1 second but I'm pretty sure that's not going to happen. If it does then simply reduce the 1000000 and save me a couple of bytes :-) **Edit 2** -6 for remembering that list comprehensions in Python 2 leak the last value of `s` so I can use it later and also remembering that pretty well anything other than 0 and "" is truthy. Bugs or features? Don't care. It's saved me 6 bytes :-) **Edit 3** Another 13 by revering the rotation and by using a list comprehension for the middle rows inside the join and changing `3000000` to `40**4`. Thanks to @FelixDombek for the last one. Had to lose my list comprehension trick though. [Answer] ## ZX81 Z80 machine code, ~~158~~ 130 bytes OK so it has a lot of bytes until it is assembled but then it drops to 130 bytes. Not sure if that breaks any rules? Its my first post and only as a guest. The program uses 'brute force' to display the message rather than clever function use as can be seen from the way it has separate code chunks for the top line, the right hand vertical, the bottom line and the left hand vertical. The animation is achieved by rotating the contents of the message and then just displaying it after a short delay which should be pretty much exactly 0.2 seconds as it waits for 10 frames out of a rate of 50 (for UK spec Zeddys anyway). I have to credit kmurta for the concept of rotating the message to get the animation - that saved 28 bytes!!! ``` main ld hl,happyBirthday ;load the address of the message ld de,(D_FILE) ;load the base of screen memory inc de ;increase it by one to bypass the $76 ld bc,12 ;ready for 12 loops ldir ;transfer HL to DE 12 times and increase both accordingly ex de,hl ;put HL into DE (HL was the message position) ld b,4 ;prepare to loop 4 times dec hl ;decrease HL (screen location) by 1 rightVertical push de ;save the character position ld de,13 ;load 13 (for the next line) add hl,de ;add to HL pop de ;get the message position back ld a,(de) ;load the character into A ld (hl),a ;save it to HL inc de ;increase the character position djnz rightVertical ;repeat until B = 0 dec hl ;decrease HL (screen location) by 1 to step back from the $76 char ld b,11 ;prepare for 11 loops lastLine ld a,(de) ;load the current character into A ld (hl),a ;save to the screen dec hl ;decrease the screen position (as we are going backwards) inc de ;increase character position djnz lastLine ;repeat until B = 0 ld b,3 ;get ready for the left vertical inc hl ;increase the screen position by 1 as we have gone 1 too far to the left and wrapped to the line above leftVertical push de ;save the character position ld de,13 ;load 13 (for the next line) sbc hl,de ;subtract it to move up a line in memory pop de ;get the character pos back ld a,(de) ;load the character ld (hl),a ;save it to the screen inc de ;next character djnz leftVertical ;repeat until B = 0 delayCode ld hl,FRAMES ;fetch timer ld a,(hl) ;load into A sub 10 ;wait 10 full frames (0.2 of a second) delayLoop cp (hl) ;compare HL to 0 jr nz,delayLoop ;if not 0 then repeat until it is shuffleMessage ld a, (happyBirthday) ;load the first character of the message push af ;save the first character of the message ld hl, happyBirthday ;load the address of the message inc hl ;increase by one to get the second char ld de, happyBirthday ;load the start of the message ld bc, 29 ;number of times to loop ldir ;load HL (char 2) into DE (char 1) and repeat pop af ;get char 1 back ld (de),a ;out it at the end of the string jr main ;repeat happyBirthday DEFB _H,_A,_P,_P,_Y,__,_B,_I,_R,_T,_H,_D,_A,_Y,__,_R,_A,_F,_F,_A,_E,_L,_E,__,_C,_E,_C,_C,_O,__ ``` Sorry I can't post a link to it running as it is a compiled program in the .P format for EightyOne (or other emulators) or an actual Zeddy if you have a ZXPand or similar to load it. The .P can be downloaded at <http://www.sinclairzxworld.com/viewtopic.php?f=11&t=2376&p=24988#p24988> ]
[Question] [ There are one hundred members of the United States Senate. Assuming that nobody filibusters and that the Vice President isn't cooperating, at least fifty-one members are necessary to pass a bill. But some members work together better than others, entropy-wise. Your task: Output the last names of at least 51 of the US senators at the time this question was posted in 2017. *Any* 51 are acceptable; put together a Cruz-Sanders coalition if you'd like. The names may be output in any order. The full list is as follows (note that Van Hollen is one person): > > Alexander, Baldwin, Barrasso, Bennet, Blumenthal, Blunt, Booker, > Boozman, Brown, Burr, Cantwell, Capito, Cardin, Carper, Casey, > Cassidy, Cochran, Collins, Coons, Corker, Cornyn, Cortez Masto, > Cotton, Crapo, Cruz, Daines, Donnelly, Duckworth, Durbin, Enzi, Ernst, > Feinstein, Fischer, Flake, Franken, Gardner, Gillibrand, Graham, > Grassley, Harris, Hassan, Hatch, Heinrich, Heitkamp, Heller, Hirono, > Hoeven, Inhofe, Isakson, Johnson, Kaine, Kennedy, King, Klobuchar, > Lankford, Leahy, Lee, Manchin, Markey, McCain, McCaskill, McConnell, > Menendez, Merkley, Moran, Murkowski, Murphy, Murray, Nelson, Paul, > Perdue, Peters, Portman, Reed, Risch, Roberts, Rounds, Rubio, Sanders, > Sasse, Schatz, Schumer, Scott, Shaheen, Shelby, Stabenow, Strange, > Sullivan, Tester, Thune, Tillis, Toomey, Udall, Van Hollen, Warner, > Warren, Whitehouse, Wicker, Wyden, Young > > > Querying Wolfram Alpha (or any other database of senators) is specifically disallowed. Anything else is fair game; use gzip as a language if you'd like. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~165~~ ~~164~~ ~~163~~ ~~162~~ ~~161~~ 160 bytes ``` 00000000: 1dc6 410a 0231 0c00 c0bf b50a c22a 880a ..A..1.......*.. 00000010: e231 b4c1 0697 6449 5aa5 bede c4cb 303b .1....dIZ.....0; 00000020: 2046 5bc2 5b1b 0ead 2b59 5a07 f72c 5eb6 F[.[...+YZ..,^. 00000030: bdb2 f9c5 c75f 4ac8 8c7d 09eb cc60 1818 ....._J..}...`.. 00000040: c5b5 12bb 1bea a964 886f d425 2b6c cef8 .......d.o.%+l.. 00000050: 5e4b 83ee 4aef 49e5 c3d9 23ae f20c 5fa8 ^K..J.I...#..._. 00000060: f759 9193 4894 4a08 ca7f 15f9 e092 1d04 .Y..H.J......... 00000070: df71 3370 7b69 572f 5ec8 625c 51ed 8c3d .q3p{iW/^.b\Q..= 00000080: 84b1 ded0 bc59 4a53 e093 0443 1566 727d .....YJS...C.fr} 00000090: 5b9b 4784 0017 e2e7 05b1 3e64 789c 6a3f [.G.......>dx.j? ``` [Try it online!](https://tio.run/##PdLbahRBEAbge5/iB/HGhLL63B1REUHN5kq8kHVlTVcfRIl4gIAgefZNTTKbvugZBuqbv6pbrkWuxrfrn4cDr@sMprcIb7iCrTPgxozGMiFBvzVrK3LWNxC9JjJ0v54SPboXjBpjqRTftDyWhOh9Qag1QEYfaL4JHDtR466@n3@@Q/j5alg1LPuIIM3qZgQ8aoeVsECcMJNtCEMigLc72mn1yVaV0/0xh1NDuljM0gJaChO@tozcUgeXIWgtMkw2eelF19cN0Y0@Lx968Wq0IAHGisDIqKgleh1AnOjeBk0UG9qYR0OboV/05OTqwQhqhOEF2Y2hEYbmKEMTuV5gXR2YlrWXWdXYXxBt6FyZx0ugoxHVmEl7L6Y4@Fy8QpzRapowYRYMLlaPjr3m2BK9V@W4ViOp0WcycC4xkkSdZLJTs@lQog0awYyu43FdjT/u9//vn57tSb58IHqxGlmN7MWgj86Qpol8DW75uwN77zRMjEg29XUe281H3d/Q/HuzGmWZhxSBT9lD70vS6zISWI8Zbuh0Uy4NsboJ7Ojd2sXL/o9@vDocbgE "Bubblegum – Try It Online") ### Output > > DainesKaineThuneTillisBluntCollinsErnstCoonsEnziBennetKennedyCaseyCassidyCardinCarperMcCainCapitoCrapoCruzSchatzScottBrownCottonCornynCorkerWydenBookerWickerWarnerWarrenHarrisHoevenHassanHatchSasseRischSandersPetersPaulTesterCochranMoranMurrayBurrMurphyLeahyLeeKingReedYoungRounds > > > ### How I generated this Previous versions were generated by [simulated annealing](https://en.wikipedia.org/wiki/Simulated_annealing), but now I’ve switched strategies to [late acceptance hill-climbing](https://web.archive.org/web/20171208014823/http://www.yuribykov.com/LAHC/). I’m not sure whether it’s fundamentally better or I just got luckier this time, but I do appreciate that LAHC has fewer parameters to tweak to get good results. ``` from __future__ import print_function import random import zlib try: range = xrange except NameError: pass senators = b'Alexander, Baldwin, Barrasso, Bennet, Blumenthal, Blunt, Booker, Boozman, Brown, Burr, Cantwell, Capito, Cardin, Carper, Casey, Cassidy, Cochran, Collins, Coons, Corker, Cornyn, Cortez Masto, Cotton, Crapo, Cruz, Daines, Donnelly, Duckworth, Durbin, Enzi, Ernst, Feinstein, Fischer, Flake, Franken, Gardner, Gillibrand, Graham, Grassley, Harris, Hassan, Hatch, Heinrich, Heitkamp, Heller, Hirono, Hoeven, Inhofe, Isakson, Johnson, Kaine, Kennedy, King, Klobuchar, Lankford, Leahy, Lee, Manchin, Markey, McCain, McCaskill, McConnell, Menendez, Merkley, Moran, Murkowski, Murphy, Murray, Nelson, Paul, Perdue, Peters, Portman, Reed, Risch, Roberts, Rounds, Rubio, Sanders, Sasse, Schatz, Schumer, Scott, Shaheen, Shelby, Stabenow, Strange, Sullivan, Tester, Thune, Tillis, Toomey, Udall, Van Hollen, Warner, Warren, Whitehouse, Wicker, Wyden, Young'.split(b', ') assert len(senators) == 100 random.shuffle(senators) score = 9999 best = score recent = 65536 * [score] recent_index = 0 while True: old_score = score step = random.randrange(2) if step == 0: i, j = 100, 100 while i >= 51 and j >= 51: i, j = random.sample(range(100), 2) senators[i], senators[j] = senators[j], senators[i] else: i, j, k = 100, 100, 100 while i >= 51: i, j, k = sorted(random.sample(range(101), 3)) senators[i:k] = senators[j:k] + senators[i:j] bound = max(old_score, recent[recent_index]) z = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 9) sin = b''.join(senators[:51]) sout = bytearray(z.compress(sin) + z.flush()) score = len(sout) * 8 if score - 7 <= bound: for bit in range(7): sout[-1] ^= 128 >> bit try: if zlib.decompress(bytes(sout), -zlib.MAX_WBITS) == sin: score -= 1 else: break except zlib.error: break if score > bound: if step == 0: senators[i], senators[j] = senators[j], senators[i] else: j = i + k - j senators[i:k] = senators[j:k] + senators[i:j] score = old_score elif score < recent[recent_index]: recent[recent_index] = score if score < best: best = score print(score, b''.join(senators[:51]).decode()) recent_index = (recent_index + 1) % len(recent) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 128 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¡e:©*ḲṣṛḷYx½NḢṀPtU9'*KṪmbpƊæ n¥×Ƭḥ0mṀC%kçaḶw'øȤ€ðzṬ¢Ỵi⁷ṅọTṛỵṙḳAf"Zƙ~^RỊṙ.Jþ°ọṄ2l+ṇ=×ıƓ:ẊƒmJJḂs}ẹ~ɗƲ³£ɓȤɗƘṪruzṂµẈ+Ç9ḋ4^(ḤạFƑỤʠ>» ``` A niladic link returning a list of characters - the names (with spaces between since it's shorter): ``` Alexander Baldwin Bennet Blunt Booker Brown Burr Cardin Carper Casey Cochran Corker Cotton Crapo Cruz Durbin Ernst Fischer Flake Gardner Graham Harris Hatch Heinrich Heller Johnson Kennedy King Lee McCain McCaskill McConnell Moran Murphy Murray Nelson Paul Perdue Portman Reed Sanders Sasse Scott Shelby Strange Sullivan Tester Udall Warner Warren Whitehouse ``` **[Try it online!](https://tio.run/##AfIADf9qZWxsef//4oCcwqFlOsKpKuG4suG5o@G5m@G4t1l4wr1O4bii4bmAUHRVOScqS@G5qm1icMaKw6YgbsKlw5fGrOG4pTBt4bmAQyVrw6dh4bi2dyfDuMik4oKsw7B64bmswqLhu7Rp4oG34bmF4buNVOG5m@G7teG5meG4s0FmIlrGmX5eUuG7iuG5mS5Kw77CsOG7jeG5hDJsK@G5hz3Dl8SxxpM64bqKxpJtSkrhuIJzfeG6uX7Jl8aywrPCo8mTyKTJl8aY4bmqcnV64bmCwrXhuogrw4c54biLNF4o4bik4bqhRsaR4bukyqA@wrv//w "Jelly – Try It Online")** ### How? Boring - 53 of the names are dictionary entries (the unused ones here being `Wicker` and `Young`), so all of the code is a single compressed string using those dictionary entries. Maybe something clever could make for less bytes, but probably not (`brownlee` is in the dictionary, but manipulating the result to capitalise the `L` & add the space to keep format will cost more that the saving of 2 bytes). [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~118~~ 117 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` │▲S⁹@^V'/¾Π;○ccΠæ▒¡$λ‼⌠Æķ□~─┼∑>°⅔′κļ ≥Y#⁄◄‰Νļ┘Υp\¹øDK%◄ρhpš,ιPΖοh≠wΜø⅞ƨω6Η√⁶┌B∞žΤΟ⅜Γ\=M»⁶»□⁽ø⁴┌¦nč+ÆB(k° Π→→∙Æ═'x¹ξ‘ū ``` Note that that code has tabs, so [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTAyJXUyNUIyUyV1MjA3OUAlNUVWJTI3LyVCRSV1MDNBMCUzQiV1MjVDQmNjJXUwM0EwJUU2JXUyNTkyJUExJTI0JXUwM0JCJXUyMDNDJXUyMzIwJUM2JXUwMTM3JXUyNUExJTdFJXUyNTAwJXUyNTNDJXUyMjExJTNFJUIwJXUyMTU0JXUyMDMyJXUwM0JBJXUwMTNDJTA5JXUyMjY1WSUyMyV1MjA0NCV1MjVDNCV1MjAzMCV1MDM5RCV1MDEzQyV1MjUxOCV1MDNBNXAlNUMlQjklRjhESyUyNSV1MjVDNCV1MDNDMWhwJXUwMTYxJTJDJXUwM0I5UCV1MDM5NiV1MDNCRmgldTIyNjB3JXUwMzlDJUY4JXUyMTVFJXUwMUE4JXUwM0M5NiV1MDM5NyV1MjIxQSV1MjA3NiV1MjUwQ0IldTIyMUUldTAxN0UldTAzQTQldTAzOUYldTIxNUMldTAzOTMlNUMlM0RNJUJCJXUyMDc2JUJCJXUyNUExJXUyMDdEJUY4JXUyMDc0JXUyNTBDJUE2biV1MDEwRCslQzZCJTI4ayVCMCUwOSV1MDNBMCV1MjE5MiV1MjE5MiV1MjIxOSVDNiV1MjU1MCUyN3glQjkldTAzQkUldTIwMTgldTAxNkI_) I was *extremely* lucky that in the SOGL english dictionary *exactly* 51 names existed :o The program is almost all (`.....‘`) a compressed string, and as SOGLs dictionary only has lowercase words, ū uppercases each words first letter. -1 byte by rearranging the names [Answer] # [;#](https://github.com/SatansSon/SemicolonHash), 28571 bytes ``` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ``` [Try it online!](https://tio.run/##7ZzBbQNBDAOLYRnXUJ4B3D8uHeRle4/DuQa42qVESpD9@vm97@uNX65vfDUo3znoA1BLITdu6hjqG6HjfT0aKdSnSStOoEmScjAtEtyHTSh8SmMccHynvEshA5kaGTTNOju/mIzSgFpzOsnNtwJc8fkMaKwDI54j5sHjA4vJtiMiGT8yJ9VOIg@MWnDKleYIqA47vv7zULm0TmUMK@115MC25yCBwj21zeGzzg5TIQQYpdsF5uQBuI31DLcmTRdLDplhG3hYprnOdhhwoq@WZXxnXqr/0kp9rKfYFOHkmlxjR6ia6p7HbjYdZ9ZK12VOalMeKq7m0OKzx1AOoznpsH5JNzFBZhPoWoFgzTUaXeydKayTjt78Xy5ajeYktLY1stnG0xKGopubJygVcbiv2ktFIWUh2HAsDIvbeznHkWqHVDM0dgn3l79W2LOY/pWXVfw/6Pv@Aw ";#+ – Try It Online") Everyone's favourite antigolfing language! As ;# is a subset of [;#+](https://github.com/ConorOBrien-Foxx/shp), the TIO can be used. [Answer] # [Bash](https://www.gnu.org/software/bash/), 277 bytes ``` echo LeeBurrCruzEnziKingPaulReedBluntBrownCaseyCoonsCrapoErnstFlakeHatchKaineLeahyMoranRischRubioSasseScottThuneUdallWydenYoungBennetBookerCapitoCardinCarperCorkerCornynCottonDainesDurbinGrahamHarrisHassanHellerHironoHoevenInhofeMarkeyMcCainMurphyMurrayNelsonPerduePetersRounds ``` Just a simple solution to get things started :) [Try it online!](https://tio.run/##HY/BTsMwEER/hW@JWzBqg6IUhDhu4qG2anajXRvk/nwwXOYw0sybWcjivmON8nAGhqrqtN6PfE@nxNeJap6BMOTKZVD5YUeG5kTYnNImR2Urj5lu8FTWeKLEOINiG0WJ52RrnOuS5EJmuKxSymusjLdAOb@3AP6QytcBzCiDyA3qaEtFHGlIHaZbd0Rv/8qNXW8QPvxh7FB1SfykFOnLk2oy3ynEHjlDfVJh8YJv8DNH@cRIvaeNq@vpserWR/a71F6QTXiChooJBWpzHxVs338B "Bash – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 194 193 bytes ``` 0000000: 1d4e cb4e c330 10fc b7b8 05a3 36a8 4a41 .N.N.0......6.JA 0000010: 88e3 361e 6aab 6636 5adb 20f7 eb71 b9cc ..6.j.f6Z. ..q.. 0000020: 61de 4760 6a66 ceda 7dcf 7b3a 245e 4fd2 a.G`jf..}.{:$^O. 0000030: f202 8429 37d6 c9f4 974e 0aba 5365 7126 ...)7....N..Seq& 0000040: 9bee 8da5 3e65 b9c1 4b5d e341 1271 84c4 ....>e..K].A.q.. 0000050: 3eab 0997 54d6 b8b4 4bd2 b394 82f3 aab5 >...T...K....... 0000060: bec5 46bc 07c9 f9a3 07f0 531b af13 48d4 ..F.......S...H. 0000070: 49f5 0673 b2a5 aa4e 2ca4 3166 db60 d46e I..s...N,.1f.`.n 0000080: ffc8 4e37 1a94 bbc7 4cd9 35bb 243e 9b44 ..N7....L.5.$>.D 0000090: f9f6 6296 8a47 ceb0 5986 bffb 644a 5d46 ..b..G..Y...dJ]F 00000a0: 7d28 73b3 6d5c 5add c8bd 30ea 174e b0d0 }(s.m\Z...0..N.. 00000b0: 0656 d843 35e9 7e3c 147a c50f f88a 5c94 .V.C5.~<.z....\. 00000c0: 7f . ``` [Try it online!](https://tio.run/##jZLLahVBEIb3PsW/EFGQoi/VtyCBoCSaSFxEBEMi6eqLEIwQQjZKfPVjzcwBt/bQw8B0f/yXkkeRH@P7491uZ7Z1ANt5oMny8t7AmtkgSTJMqB4@1gyubAE618fQuiKdHj1bAVYROY/lpB2ItQpi9BGhdoEzM2FIspDSmiL04i3NeEn6eU@0IZwiou0DnKJRRIxoo1ek3iaS@ArHQf/O7oBKJze3k@iJfh88//Zpj/CKmM44ZHYFPnVFlMkoSX2ZKhXBx4BkXVxU0Ku0uDgnuhj3LzYEK6LIGMi9Bvihx1W0BUvoGF4TsE6NZG68IuhwEJ1d09E/I0ERfmgCppSEwKpCsrAiVLn4wshuemhGAThUxGfdZ1uie0RUhIwWwFEaTGoFs2gPJk2jHqygTuvBua8qjveXL3S/3yOSIrjMABOThzh1U6vG4FpleKvpdtGcO8cBfCB6WJJ4TXbSDf3cEHmJczZtfvgEW1W5SEvg1jXdINos@6Fx8arifE3zIwV6fkjvNkRZEGVGRFcicuWkpYp6KFlTmVPHhFlrURkLQohOiL4qpp9eH2@IqojUXUby4hF7aMtUdbQsHd6MCrvUK6Yb4OnlA91dXSrArMVuCFGEiUEtZ9YRDaMgDd9gOVW0YCZmzqqilcXIF3ob6M8b@rXYudoj2qJi4v8W7XZ/AQ "Bubblegum – Try It Online") This answer currently works, but I will likely post a shorter version later seeing as I currently have a Python script running to generate these. ### Python Script (using 3rd party library `hexdump`) ``` from itertools import permutations from hexdump import hexdump import zlib senators = ['Lee', 'Burr', 'Cruz', 'Enzi', 'King', 'Paul', 'Reed', 'Blunt', 'Brown', 'Casey', 'Coons', 'Crapo', 'Ernst', 'Flake', 'Hatch', 'Kaine', 'Leahy', 'Moran', 'Risch', 'Rubio', 'Sasse', 'Scott', 'Thune', 'Udall', 'Wyden', 'Young', 'Bennet', 'Booker', 'Capito', 'Cardin', 'Carper', 'Corker', 'Cornyn', 'Cotton', 'Daines', 'Durbin', 'Graham', 'Harris', 'Hassan', 'Heller', 'Hirono', 'Hoeven', 'Inhofe', 'Markey', 'McCain', 'Murphy', 'Murray', 'Nelson', 'Perdue', 'Peters', 'Rounds'] min_length = 1000 for perm in permutations(senators): z = zlib.compressobj(level=9, wbits=-15) z.compress("".join(perm).encode()) compressed = z.flush() length = len(compressed) if length < min_length: min_length = length best = compressed hexdump(best) print("Length:", length) file = open("bub_out.txt", "bw") file.write(best) file.close() print(best) ``` [Answer] # [PHP](https://php.net/), 270 bytes ``` <?=strtr(K3gLeeBurrC5d3C5p0Co7sCruzEnziHat6He40Ka3eM163Mor1PaulReedRis6Uda4W5n0W5r2Wyd2B2netBluntBook0BrownCaseyCo6r1Co43sCork0Cott7CrapoDa3esDurb3ErnstFis60FlakeFr1k2G5dn0H5risHass1Hir7oHoev2LeahyM5keyMcCa3Nels7P0duePet0sRubioS1d0sSasseS6atz,[er,an,en,in,ll,ar,ch,on]); ``` [Try it online!](https://tio.run/##Dc3BaoNAEIDh12lhD6ub1UNbCm5ihcQSEkoOoYdJdmhE2ZGZ3RZ9eesD/N8/PsZleX1/k8iRn/bm54BYJWZnvXF21I5KcZzmXZi7BmLR4EbvwWCbFaYlzo6QhhOiP3VSfHnYXGzQF8v5ZfJ5lQeM1ZBCrIh6XTH9BQeCk6OCM0cbI464Xx8xlo5hpO0qyzbxzew4SKxXVNcD9Fhz1ucf1gfdWO6kAZGs6bikhvA3PyA8ptb2OLV3B@YTBymP2ic8YtRySreOzpnXcl4zPBcQZ3VFVhAUBtUFNQwKWN0fisL388uy/AM "PHP – Try It Online") # [PHP](https://php.net/), 270 bytes ``` <?=strtr(H02K4gLeeS0eBurrC6d4C6p1Co8sCruzEnziHat7He51Ka4eM274Mor2PaulReedRis7Uda5W6n1W6r3Wyd3B6r0oB3netBluntBook1BrownCaseyC0idyCo7r2Co54sCork1Cott8CrapoDa4esDurb4ErnstFis71FlakeFr2k3G6dn1H6risHir8oHoev3LeahyM6keyMcCa4Nels8P1duePet1sRubio,[ass,er,an,en,in,ll,ar,ch,on]); ``` [Try it online!](https://tio.run/##Dc3RaoMwFADQ39kgD0ZjFLYxSFontA5xDB/GHtLmMoOSKzfJhv151x84Z53WfX9@fQmRIj20WX4SP2eAjwxUItLSCi1XrrEOmtLt6G@uNbFqoeQnI6DLK9Eh5b1JywBgBxeqT2vKUXo@SirGzRZKUoaq8BDVknxUiDNXhH9emwCbzpzdNFaUayxF0EjzfYux1mRWPNyPcEh0EUfyITZ3njeLmaGhfC7epPW8leRC66jGFuG3OIOZtk7OsHVXbcQ7LKHuuU3QQ@RhSBeH7MuEwICY8Qw8c54tCzPErhND//34tO// "PHP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~329~~ 279 bytes -50 bytes Thanks @caird coinheringaahing: [avoid the delimiter-spaces] ``` print'LeeBurrCruzEnziKingPaulReedBluntBrownCaseyCoonsCrapoErnstFlakeHatchKaineLeahyMoranRischRubioSasseScottThuneUdallWydenYoungBennetBookerCapitoCardinCarperCorkerCornynCottonDainesDurbinGrahamHarrisHassanHellerHironoHoevenInhofeMarkeyMcCainMurphyMurrayNelsonPerduePetersRounds' ``` [Try it online!](https://tio.run/##HY/RTsMwFEM/Z@98QrNB0VY0dSDE411rlqjBt7pJQNnPl8CLHyzZx15r9sqHbVstMO9OQFfMnJX7gfdwDLydpcQRmLtYmDvTHzpJqE6VyZmsejCm/BhlQS958kcJxAni66AmHEOa/FiuQS@SEi6T5vzqC/E2S4zvdQY/tPDWgUTuVBeYkzVkdWJzaDBbm6O2/CsrXWtQ7v8waV/sGvhk4uWrF7OQ@kYR9ogR1gdTaq/4Bp/p9RODtJ46TK6lh2JrG9nuSn1BTMozbC44I8PS2EbNabdtvw "Python 2 – Try It Online") ### String Generated by this program(get list from the data string, sort the strings by length, take first 51 elements, join) ``` a='Alexander, Baldwin, Barrasso, Bennet, Blumenthal, Blunt, Booker, Boozman, Brown, Burr, Cantwell, Capito, Cardin, Carper, Casey, Cassidy, Cochran, Collins, Coons, Corker, Cornyn, Cortez Masto, Cotton, Crapo, Cruz, Daines, Donnelly, Duckworth, Durbin, Enzi, Ernst, Feinstein, Fischer, Flake, Franken, Gardner, Gillibrand, Graham, Grassley, Harris, Hassan, Hatch, Heinrich, Heitkamp, Heller, Hirono, Hoeven, Inhofe, Isakson, Johnson, Kaine, Kennedy, King, Klobuchar, Lankford, Leahy, Lee, Manchin, Markey, McCain, McCaskill, McConnell, Menendez, Merkley, Moran, Murkowski, Murphy, Murray, Nelson, Paul, Perdue, Peters, Portman, Reed, Risch, Roberts, Rounds, Rubio, Sanders, Sasse, Schatz, Schumer, Scott, Shaheen, Shelby, Stabenow, Strange, Sullivan, Tester, Thune, Tillis, Toomey, Udall, Van Hollen, Warner, Warren, Whitehouse, Wicker, Wyden, Young'.split(', ') a.sort(key=lambda x:len(x)) print(''.join(a[:51])) ``` [Try it online!](https://tio.run/##LVLLbhsxDLznK3yzDRgBiqKXADm0dh2niYsgdhsURQ/cXcZSVxYXlBQ/ft4dKr3sjKglOUNqOGUn8ePlQrfjz4GPFDvW2egLhe7goxFVSknAOEbOwFD2HLOjUHm0kEhfs0TOe7IslYNBUUTnFPOBQzA2@CyG2llx4MD1j8SnCsl3RqR1anXmEoKPyYi8g9ZGwHiq95r5PFpTqmUlZ7Go0mBHLefZaEE@MlIXAvkhoPqitP0Bic6oNibkazx7fDUmuFkyWma2@NKn1lnDZaCeAVDVMy7u4CDaxZ2HwgbhDlzJ0b5iSsEcrTA9nwxTMj8ryi3arlBc/X@We9oPxkKwgiuvEqF@Jfxmne6jk1e0vk/UJ3P3TVys5MGcAWwvNrUHH3f4BmlK6wilHiH2VRTKHpncyQD/rym2zsytCcNEdN3OqZ6Bqfe2KND3cYFyZLyJszHtq6u11OWsi/ZyQEalgzUAKgG/c6gSn6igxBNrV9gws2IaTxh@fSbPzBD3bEMGSMOak5ESO8PSeAxiU59kMpISqmxgLp8r4iGqEewd4MixTWzjODQQscnUcJSDMQjeWW7Btt6s9ZaxYiRvXbEhbm2N6LEV2ZvFHx2Z@Z8UsQgsBhkvpHXjQK1n5zM7Kabpxbf1Xb6cOrv6BQe78XUags@T8Ww0nl7RdYLrCQZ@G2jfdDQ63qDs5DidXg3qI/4bX/8VHyf0@@bThz/T6eXyDw "Python 3 – Try It Online") [Answer] # [Add++](https://github.com/SatansSon/AddPlusPlus), 2131 bytes ``` +76 & +25 & & -57 & -12 & +34 & +51 & -3 & & -70 & -12 & +35 & +47 & +3 & +5 & -78 & -12 & +37 & +41 & +12 & -17 & -61 & -12 & +43 & +30 & +5 & -7 & -59 & -12 & +48 & +17 & +20 & -9 & -64 & -12 & +50 & +19 & & -1 & -56 & -12 & +34 & +42 & +9 & -7 & +6 & -72 & -12 & +34 & +48 & -3 & +8 & -9 & -66 & -12 & +35 & +30 & +18 & -14 & +20 & -77 & -12 & +35 & +44 & & -1 & +5 & -71 & -12 & +35 & +47 & -17 & +15 & -1 & -67 & -12 & +37 & +45 & -4 & +5 & +1 & -72 & -12 & +38 & +38 & -11 & +10 & -6 & -57 & -12 & +40 & +25 & +19 & -17 & +5 & -60 & -12 & +43 & +22 & +8 & +5 & -9 & -57 & -12 & +44 & +25 & -4 & +7 & +17 & -77 & -12 & +45 & +34 & +3 & -17 & +13 & -66 & -12 & +50 & +23 & +10 & -16 & +5 & -60 & -12 & +50 & +35 & -19 & +7 & +6 & -67 & -12 & +51 & +14 & +18 & & -14 & -57 & -12 & +51 & +16 & +12 & +5 & & -72 & -12 & +52 & +20 & +13 & -7 & -9 & -57 & -12 & +53 & +15 & -3 & +11 & & -64 & -12 & +55 & +34 & -21 & +1 & +9 & -66 & -12 & +57 & +22 & +6 & -7 & -7 & -59 & -12 & +34 & +35 & +9 & & -9 & +15 & -72 & -12 & +34 & +45 & & -4 & -6 & +13 & -70 & -12 & +35 & +30 & +15 & -7 & +11 & -5 & -67 & -12 & +35 & +30 & +17 & -14 & +5 & +5 & -66 & -12 & +35 & +30 & +17 & -2 & -11 & +13 & -70 & -12 & +35 & +44 & +3 & -7 & -6 & +13 & -70 & -12 & +35 & +44 & +3 & -4 & +11 & -11 & -66 & -12 & +35 & +44 & +5 & & -5 & -1 & -66 & -12 & +36 & +29 & +8 & +5 & -9 & +14 & -71 & -12 & +36 & +49 & -3 & -16 & +7 & +5 & -66 & -12 & +39 & +43 & -17 & +7 & -7 & +12 & -65 & -12 & +40 & +25 & +17 & & -9 & +10 & -71 & -12 & +40 & +25 & +18 & & -18 & +13 & -66 & -12 & +40 & +29 & +7 & & -7 & +13 & -70 & -12 & +40 & +33 & +9 & -3 & -1 & +1 & -67 & -12 & +40 & +39 & -10 & +17 & -17 & +9 & -66 & -12 & +41 & +37 & -6 & +7 & -9 & -1 & -57 & -12 & +45 & +20 & +17 & -7 & -6 & +20 & -77 & -12 & +45 & +22 & -32 & +30 & +8 & +5 & -66 & -12 & +45 & +40 & -3 & -2 & -8 & +17 & -77 & -12 & +45 & +40 & -3 & & -17 & +24 & -77 & -12 & +46 & +23 & +7 & +7 & -4 & -1 & -66 & -12 & +48 & +21 & +13 & -14 & +17 & -16 & -57 & -12 & +48 & +21 & +15 & -15 & +13 & +1 & -71 & -12 & +50 & +29 & +6 & -7 & -10 & +15 & -71 & -12 & +51 & +16 & +5 & -7 & +19 & +6 & P ``` [Try it online!](https://tio.run/##hVVBbsQwCLzvQ3qxIgUbTPyLfqFSH9D/X7YN2EBi7/ZiRfEYD8OAv76/f36ez8T18fFImf7Wj8dGfK6Qz38Fz5Xg/FN0m/ewfR5JyPItSEEcASF7eAZI8mcDCV/BMShHy@4BhEYLiEPOS6ws98tmRYeQHIemJCU61XsiKN9t3JEEwHmCHSPfdPhl9Z63MgbNFp0b86QQOq2eIixVVHUSkCVReRJTNnGESjAlcdi6gSovvOq9urhb3VW5fr1cUPd7hXIeiiiiTfHQ4ik/trJdREFyrUvIutx11qLm4jlAXRJUYFHZml1d7wqSyoFWuFG6Sx4dVc20qbdGVJmyVbwz56UoVLyi@gka7OJeV2TLMKqaJuMReyGq3Tn1S5eWRozOq7NYGL7nh8MmI6P9heetTTWbjSarRjR7h5CXr75D52DeF1TQ/cP/8g5gdNq6zkwQQ9FDL0agzsw2t4Ta69rhAsY2PNBtzGsxmrVcbwx2tUWXSi96mGOt9zuLC3SY/1h3XsdaKxmBSV9FlmJ@LTbppgHWserU6A1eul2fjeLV9Q6DafZQaEe@mmIeyx0tapbs5juWFVG0kNfs5Nzxbrg52NLLOEGrjzcvNC79pk9gDh3Rpxibn656RLz6hexsfzNgmrTtOlggdjusB2QYBXb68/n8BQ "Add++ – Try It Online") I love hardcoding these! They are so fun! Each line is either `[+-]\d+`, `&` or `P`. * `&` adds the char in the accumulator to the output string, without outputting. * `P` prints the output string * Numbers add or subtract that value from the accumulator [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 455 bytes (all 100, I misread) Im more excited about this challenge now and will indeed fix this in time. ``` .•вÏ–lāä˜(~Îíˆ^ÅËð3µpñ»ú¶›;β›vGĀ½W PToÚ+ćLöт'Ç@qu¿>ßH3^eoèL«Oт©zβü)Åëîƶ¿n77¯Þ»øδëΩŽÐ∊ÿ–R9ÑÄÿÂMD∊Ê'Ƶ~°Aº≠₄›Š∞"Óн=Üg2Ua‘èǝʒ·ªd±{-wγrWÉ₃§¯Ωnι“âÝvγ+ŸõÊ×|Ù¨LòΛÍ_Ю\‡,–Ç+Q^ú€ÉƵÙD“≠ŒC½ŒÉÃ₅Ç^þ:†ÆÜãôвΩæĀîAìëƵôÄꓬ{/¯ÐaĆXõ₅ñγõ¶P\¹oÓΣθºõ®5ù@ïwÛ-þoÅÇóÌ»"ηÆ!PÑ₅§₆úñ©C½[RV7Y#:ìÎmÓžĆº´aΩ. ªƶтñΔo H!®àrα¤´¢gËZLβθŽ#§ƶl¸±0ª©öδgYÃÀQ1œuYÎ₂ľéï¶çÉsžÏT®é®§šŒE[7èœ~Õм-4UÃн₄Î^Rs›k€’(∞S₃˜\‘½ÊÀsΣǝP¶²Ï4oÍ‘Δýε¿(†Û)ŽαΔ…p§¼móe,k£í¥‡8(ÖöÍDÒ₆OÅÇ0vÆÖΩ¼ì>^ŸćrʒðĆтÄε%D™¶ÞZ®=4¦?µ×•'q¡„, ý™ ``` [Try it online!](https://tio.run/##JVNrUxRHFP2eX4FaKbF8RKMWiSmNVkjFD6REozE@ilTvTrMz2dnp7e4ZNospa7MgiEZUMD4iEgQjLOAij10RWajqu4tVWjWFf2H@CDmjX/rc7ul777nn9Ow/zBIH@NbWvqgwvrlAt6PCsFv/k569H2m@SoP04n1fB12jm/TyoKlkad68oRVTjQor34QLWLt@qBdM7XxT@1lB/@yu97dR9UNxJ/Ufl4FZP0b/njzYwQVNtZmZUx@KptQdLtDqLtSbofJG1ax7LS1mjkZRdDlcopmw1KjRnej6DVoHjTNf013qpXUq/tgan93YuVG5al6eMCvRwFhU7EX7xlh0fXQ7DW/WjtJI6stzLCo8pKm3T94NmVdm2jLzV/bmwkV1ngaiYo@ZNHNhyQtfR4URGqcnXeHi7sYyVegGPfiDHpmpNloIH9OtX@mOKV@OCk/3gAT17z7dQStRcZYGNir0qBXJaN8Y@s7UGkM0QD1R8Rr1d9DakagwRn00QhO0tLkQluh5vUDlEzRLM0hcwiTTyDWzV77AyHdYve8XqsS58@Ei9ZiKqbZfNq8FDYcT4bJZoYopH6bXx2kuR4/30pqAaP20SH@ZN9vDV9S3rZ3uIttMRsU@WoEvJRC6dObnlgs7jqDlYIaGG2v1PrNillhY2tdkpjfgDJrdE5@d3GbKNKbCefPMLJnxFN282BYuhMuN2g4zuVF1zbKZ32@mTYmq4VLqAvVQ4fSBxnBwgQajYpF6zRqVaM5UaZIGdGONbp9FvZIpm8nG08bQ95daaKoxfJX@3lzde@gc9WzWYBYNdpzRcCwNJaPCo2b49hM8eT8CoR@aGjwo6HDi7ZN2UzV4hYcE3cKH8B7VwopZb461fbyrUQsxQFR4noWXqxla5HvSZoJemP/g1lfNdJ@qdKuVhqDJqViv/V0w5H5YMqs0e6yjsVzvV@@G6GW9D0r0hpXPW6PecYwxetGUjx4yz781FXqA32CnNE@jwuieJqrhwtYWc/nvzLO4kgnmWjnHAyrFtBYywT2P@zLhBhnu@TZz49DDgRDp@L4Q3RmG@0rksAZKySTz/Bx3XQRZxxcAZaEiIMvjr5rn41U7FlAkbYX0pHBdx9NA8XFVcW2Al4@/KZ93N2WYjosJ3xc4UyyLjQq6pcUcj2tpCfB03by0gmQ6hxQbkUqgMfe6HcmVp33ZydHExyI7HZ200aPTZWkuO8EhzT2ZAlUPpykHdBI4tGRKMZtlYtDaBXMbwjgaoDV428xP2tJGReV8Cvw0y2QRuC7q2I4SnpC24F2o7ni26OTS0SytMcNvwvZiTMcDyHSsMxRJO15Kpl2RCJJoJV0Q6xTKki5ndh4rl5A7aWOEDINKeZlJJlm8A@g0eMfRJy0kHONwtRuBSsfkMyIWOxOotMjhchxlURWgWF4iJ@aTZYErYZUVcIDPlZZZ6Bm7rDi3pIqlk0okuPI1MPAsQJBwhNQfH5EGas0lrjG/Owa8HQWEd1LbzOYQQ0OiRF5qn@GFiRwCUEshKYD0XejlczilpG8HUMePDdHSFyKDMQKLYTpcarLxblAsx1RsG0DFO9vxuS0CUMg5yfgl5fIWzvOgmvof "05AB1E – Try It Online") --- Here's a boring answer, but base compression and complex methods in 05AB1E won't cut it for how random this is... I tried a more scientific approach: ``` [['j', 1], ['x', 1], [' ', 2], ['v', 3], ['f', 6], ['z', 6], ['g', 7], ['p', 9], ['w', 11], ['y', 15], ['b', 16], ['k', 18], ['d', 19], ['m', 19], ['u', 20], ['t', 28], ['h', 31], ['c', 33], ['i', 33], ['l', 37], ['s', 43], ['o', 44], ['a', 53], ['r', 59], ['n', 65], ['e', 69], [',', 99]] ``` Calculated the frequencies of the letters; but I can't really get lower because I'm only able to easily use 8-bit replacements of the... well 8-bit equivalents. If there was an easier way to do binary compression in 05AB1E, maybe? ``` 'MJP1MOCPNQAMJC8IOQAMNNMKKLQAPOOPFQAJEDPOFGMJQAJEOFQALLBPNQALL5DMOQANL8OQAENNQHMOF8PJJQHM7IFLQHMNCIOQHMN7PNQHMKP9QHMKKIC9QHLHGNMOQHLJJIOKQHLLOKQHLNBPNQHLNO9OQHLNFP52DMKFLQHLFFLOQHNM7LQHNE5QCMIOPKQCLOOPJJ9QCEHB8LNFGQCENAIOQPO5IQPNOKFQ4PIOKFPIOQ4IKHGPNQ4JMBPQ4NMOBPOQ6MNCOPNQ6IJJIANMOCQ6NMGMDQ6NMKKJP9QGMNNIKQGMKKMOQGMFHGQGPIONIHGQGPIFBMD7QGPJJPNQGINLOLQGLP3POQIOGL4PQIKMBKLOQ0LGOKLOQBMIOPQBPOOPC9QBIO6QBJLAEHGMNQJMOB4LNCQJPMG9QJPPQDMOHGIOQDMNBP9QDHHMIOQDHHMKBIJJQDHHLOOPJJQDPOPOCP5QDPNBJP9QDLNMOQDENBL8KBIQDEN7G9QDENNM9QOPJKLOQ7MEJQ7PNCEPQ7PFPNKQ7LNFDMOQNPPCQNIKHGQNLAPNFKQNLEOCKQNEAILQKMOCPNKQKMKKPQKHGMF5QKHGEDPNQKHLFFQKGMGPPOQKGPJA9QKFMAPOL8QKFNMO6PQKEJJI3MOQFPKFPNQFGEOPQFIJJIKQFLLDP9QECMJJQ3MO2GLJJPOQ8MNOPNQ8MNNPOQ8GIFPGLEKPQ8IHBPNQ89CPOQ9LEO6' ``` Ended up with that, which was worse. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~195~~ 193 bytes ``` 00000000: 05c1 514e eb30 1404 d0bd c5ed 7b41 6d50 ..QN.0......{AmP 00000010: 9482 109f b7c9 505b 3173 a3b1 0d72 57cf ......P[1s...rW. 00000020: 3957 6001 b633 9f69 b696 2f89 8fa0 f61c 9W`..3.i../..... 00000030: 9af4 2fdb 8ea5 dd93 5f2c 11c1 0afa 6df5 ../....._,....m. 00000040: 5a27 97f1 0a8b fd2c 96fa d137 f02d 3662 Z'.....,...7.-6b 00000050: 90ff f2d3 1b1f a3d5 3506 7796 f7cd 721e ........5.w...r. 00000060: 7263 0db2 c397 54d6 78b3 5210 ec48 d567 rc....T.x.R..H.g 00000070: 686b 3835 dd13 27d3 8e3e 5a29 c631 c9e9 hk85..'..>Z).1.. 00000080: afc8 c539 adc1 1283 e980 46e4 0c05 d70e ...9......F..... 00000090: 8d8e 1f70 3429 9501 24ea d424 ebc1 b425 ...p4)..$..$...% 000000a0: be30 fa17 82d7 ea0c 2e76 9e2c 11e5 bf2c .0.......v.,..., 000000b0: daf7 e0be 4353 d311 fbe2 8d5b 9951 a1f2 ....CS.....[.Q.. 000000c0: 07 . ``` [Try it online!](https://tio.run/##jZNLaxVBEIX3/oqzUCQQy66ufroQRBBXkmggkCy0n1E0IJGo4I@/Vs@9N7i0GGZm0fVNnXNq6n2t38bN/e1uZw71AsY3hmc3MKoYsDMO3dSO5kdHrI4RujcA0fk7MrTVn1e3Z4/2BFZGdsmCTZ6osWV44yuEo6BIZZgeLXxsczFWnV3zD33cXdKBYZUh2UcE5aEGEeQZsr7lADtTRprFYAZuQL78RCT0hej5RjswZM1RptPzvSKN4tF7FvhpG5hVpCmzqJbp1xz73o@n6357ZDhl@GIjcpzrfKqYXdtz0M7OEjGN7ZAQLHD1dEMsQqRnoR4Yfs1h5sS0XcCVp7rQPcSbgBhV0IxNjbU8jn4Qefq1DDnOEZQRbRC1rlo0yRHedW1PVQVZNhjNJXQfInDXFuGCftN7ord0c2BEZYQUNIgkywoW2KgTpSFjicxoQRgtjwx8/po8kQp6eXVC/OBpUkaZLekuSEbpaiLbJBg5GbgwHEwzCo9mryXv1bz5N5esjNTTAM9oIE4/nL2mbN1QT511unfKrc5uudB3d0L0eLvoyYFRlFGHbucsHJFsjxjFNNgRA/LYAh4edUWN447Szy2b0wOjKqOXqZ2mDjjxgi7MmHVYHVA3NmfPKDztPpfXHzbKNZ0/aGnrf1HL/6tot/sL "Bubblegum – Try It Online") [Answer] # [MAWP](https://esolangs.org/wiki/MAWP), 5624 bytes ``` 88WM;269WW;1689MWA;358WW;1277WWA;19M29MW;455WW;1689MWA;67W89WM;159WA;48W;288WM;1277WWA;269WW;455WW;789MW;357WW;19M29MW;159WA;48W;288WM;1277WWA;67W89WM;67W89WM;1277WWA;2949MWA;2949MWA;1278WWA;159WA;48W;288WM;1689MWA;19M29MW;19M29MW;1689MWA;1949MWA;159WA;48W;288WM;269WW;949MW;1269WWM;1689MWA;19M29MW;1949MWA;849MW;1277WWA;269WW;159WA;48W;288WM;269WW;949MW;19M29MW;1949MWA;159WA;48W;288WM;1278WWA;1278WWA;1269WWA;1689MWA;67W89WM;159WA;48W;288WM;1278WWA;1278WWA;2279WAW;1269WWM;1277WWA;19M29MW;159WA;48W;288WM;67W89WM;1278WWA;789MW;19M29MW;159WA;48W;288WM;949MW;67W89WM;67W89WM;159WA;48W;388WM;1277WWA;19M29MW;1949MWA;789MW;1689MWA;269WW;269WW;159WA;48W;388WM;1277WWA;278WW;357WW;1949MWA;1278WWA;159WA;48W;388WM;1277WWA;67W89WM;455WW;357WW;19M29MW;159WA;48W;388WM;1277WWA;67W89WM;278WW;1689MWA;67W89WM;159WA;48W;388WM;1277WWA;2949MWA;1689MWA;1358WWM;159WA;48W;388WM;1277WWA;2949MWA;2949MWA;357WW;455WW;1358WWM;159WA;48W;388WM;1278WWA;929MW;849MW;67W89WM;1277WWA;19M29MW;159WA;48W;388WM;1278WWA;269WW;269WW;357WW;19M29MW;2949MWA;159WA;48W;388WM;1278WWA;1278WWA;19M29MW;2949MWA;159WA;48W;388WM;1278WWA;67W89WM;1269WWA;1689MWA;67W89WM;159WA;48W;388WM;1278WWA;67W89WM;19M29MW;1358WWM;19M29MW;159WA;48W;388WM;1278WWA;67W89WM;1949MWA;1689MWA;2279WAW;48W;499WA;1277WWA;2949MWA;1949MWA;1278WWA;159WA;48W;388WM;1278WWA;1949MWA;1949MWA;1278WWA;19M29MW;159WA;48W;388WM;67W89WM;1277WWA;278WW;1278WWA;159WA;48W;388WM;67W89WM;949MW;2279WAW;159WA;48W;488WM;1277WWA;357WW;19M29MW;1689MWA;2949MWA;159WA;48W;488WM;1278WWA;19M29MW;19M29MW;1689MWA;269WW;269WW;1358WWM;159WA;48W;488WM;949MW;929MW;1269WWA;789MW;1278WWA;67W89WM;1949MWA;849MW;159WA;48W;488WM;949MW;67W89WM;277WW;357WW;19M29MW;159WA;48W;389WA;19M29MW;2279WAW;357WW;159WA;48W;389WA;67W89WM;19M29MW;2949MWA;1949MWA;159WA;48W;257WW;1689MWA;357WW;19M29MW;2949MWA;1949MWA;1689MWA;357WW;19M29MW;159WA;48W;257WW;357WW;2949MWA;929MW;849MW;1689MWA;67W89WM;159WA;48W;257WW;269WW;1277WWA;1269WWA;1689MWA;159WA;48W;257WW;67W89WM;1277WWA;19M29MW;1269WWA;1689MWA;19M29MW;159WA;48W;189WA;1277WWA;67W89WM;455WW;19M29MW;1689MWA;67W89WM;159WA;48W;189WA;357WW;269WW;269WW;357WW;277WW;67W89WM;1277WWA;19M29MW;455WW;159WA;48W;189WA;67W89WM;1277WWA;849MW;1277WWA;1269WWM;159WA;48W;189WA;67W89WM;1277WWA;2949MWA;2949MWA;269WW;1689MWA;1358WWM;159WA;48W;89W;1277WWA;67W89WM;67W89WM;357WW;2949MWA;159WA;48W;89W;1277WWA;2949MWA;2949MWA;1277WWA;19M29MW;159WA;48W;89W;1277WWA;1949MWA;929MW;849MW;159WA;48W;89W;1689MWA;357WW;19M29MW;67W89WM;357WW;929MW;849MW;159WA;48W;89W;1689MWA;357WW;1949MWA;1269WWA;1277WWA;1269WWM;278WW;159WA;48W;89W;1689MWA;269WW;269WW;1689MWA;67W89WM;159WA;48W;89W;357WW;67W89WM;1278WWA;19M29MW;1278WWA;159WA;48W;89W;1278WWA;1689MWA;1949MWM;1689MWA;19M29MW;159WA;48W;189WM;19M29MW;849MW;1278WWA;689MW;1689MWA;159WA;48W;189WM;2949MWA;1277WWA;1269WWA;2949MWA;1278WWA;19M29MW;159WA;48W;289WM;1278WWA;849MW;19M29MW;2949MWA;1278WWA;19M29MW;159WA;48W;355WW;1277WWA;357WW;19M29MW;1689MWA;159WA;48W;355WW;1689MWA;19M29MW;19M29MW;1689MWA;455WW;1358WWM;159WA;48W;355WW;357WW;19M29MW;1849MWA;159WA;48W;355WW;269WW;1278WWA;277WW;949MW;929MW;849MW;1277WWA;67W89WM;159WA;48W;489WM;1277WWA;19M29MW;1269WWA;689MW;1278WWA;67W89WM;455WW;159WA;48W;489WM;1689MWA;1277WWA;849MW;1358WWM;159WA;48W;489WM;1689MWA;1689MWA;159WA;48W;499WA;1277WWA;19M29MW;929MW;849MW;357WW;19M29MW;159WA;48W;499WA;1277WWA;67W89WM;1269WWA;1689MWA;1358WWM;159WA;48W;499WA;929MW;388WM;1277WWA;357WW;19M29MW;159WA;48W;499WA;929MW;388WM;1277WWA;2949MWA;1269WWA;357WW;269WW;269WW;159WA;48W;499WA;929MW;388WM;1278WWA;19M29MW;19M29MW;1689MWA;269WW;269WW;159WA;48W;499WA;1689MWA;19M29MW;1689MWA;19M29MW;455WW;1689MWA;2279WAW;159WA;48W;499WA;1689MWA;67W89WM;1269WWA;269WW;1689MWA;1358WWM;159WA;48W;499WA;1278WWA;67W89WM;1277WWA;19M29MW;159WA;48W;499WA;949MW;67W89WM;1269WWA;1278WWA;789MW;2949MWA;1269WWA;357WW;159WA;48W;499WA;949MW;67W89WM;278WW;849MW;1358WWM;159WA;48W;499WA;949MW;67W89WM;67W89WM;1277WWA;1358WWM;159WA;48W;399WA;1689MWA;269WW;2949MWA;1278WWA;19M29MW;159WA;48W;199WA;1277WWA;949MW;269WW;159WA;48W;199WA;1689MWA;67W89WM;455WW;949MW;1689MWA;159WA;48W;199WA;1689MWA;1949MWA;1689MWA;67W89WM;2949MWA;159WA;48W;199WA;1278WWA;67W89WM;1949MWA;1269WWM;1277WWA;19M29MW;159WA;48W;199WM;1689MWA;1689MWA;455WW;159WA;48W;199WM;357WW;2949MWA;929MW;849MW;159WA;48W;199WM;1278WWA;277WW;1689MWA;67W89WM;1949MWA;2949MWA;159WA;48W;199WM;1278WWA;949MW;19M29MW;455WW;2949MWA;159WA;48W;199WM;949MW;277WW;357WW;1278WWA;159WA;48W;299WM;1277WWA;19M29MW;455WW;1689MWA;67W89WM;2949MWA;159WA;48W;299WM;1277WWA;2949MWA;2949MWA;1689MWA;159WA;48W;299WM;929MW;849MW;1277WWA;1949MWA;2279WAW;159WA;48W;299WM;929MW;849MW;949MW;1269WWM;1689MWA;67W89WM;159WA;48W;299WM;929MW;1278WWA;1949MWA;1949MWA;159WA;48W;299WM;849MW;1277WWA;849MW;1689MWA;1689MWA;19M29MW;159WA;48W;299WM;849MW;1689MWA;269WW;277WW;1358WWM;159WA;48W;299WM;1949MWA;1277WWA;277WW;1689MWA;19M29MW;1278WWA;789MW;159WA;48W;299WM;1949MWA;67W89WM;1277WWA;19M29MW;1849MWA;1689MWA;159WA;48W;299WM;949MW;269WW;269WW;357WW;1949MWM;1277WWA;19M29MW;159WA;48W;267WW;1689MWA;2949MWA;1949MWA;1689MWA;67W89WM;159WA;48W;267WW;849MW;949MW;19M29MW;1689MWA;159WA;48W;267WW;357WW;269WW;269WW;357WW;2949MWA;159WA;48W;267WW;1278WWA;1278WWA;1269WWM;1689MWA;1358WWM;159WA;48W;499WM;455WW;1277WWA;269WW;269WW;159WA;48W;599WM;1277WWA;19M29MW;48W;89W;1278WWA;269WW;269WW;1689MWA;19M29MW;159WA;48W;699WM;1277WWA;67W89WM;19M29MW;1689MWA;67W89WM;159WA;48W;699WM;1277WWA;67W89WM;67W89WM;1689MWA;19M29MW;159WA;48W;699WM;849MW;357WW;1949MWA;1689MWA;849MW;1278WWA;949MW;2949MWA;1689MWA;159WA;48W;699WM;357WW;929MW;1269WWA;1689MWA;67W89WM;159WA;48W;699WM;1358WWM;455WW;1689MWA;19M29MW;159WA;48W;899WM;1278WWA;949MW;19M29MW;1849MWA; ``` [Try it!](https://8dion8.github.io/?code=88WM%3B269WW%3B1689MWA%3B358WW%3B1277WWA%3B19M29MW%3B455WW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B288WM%3B1277WWA%3B269WW%3B455WW%3B789MW%3B357WW%3B19M29MW%3B159WA%3B48W%3B288WM%3B1277WWA%3B67W89WM%3B67W89WM%3B1277WWA%3B2949MWA%3B2949MWA%3B1278WWA%3B159WA%3B48W%3B288WM%3B1689MWA%3B19M29MW%3B19M29MW%3B1689MWA%3B1949MWA%3B159WA%3B48W%3B288WM%3B269WW%3B949MW%3B1269WWM%3B1689MWA%3B19M29MW%3B1949MWA%3B849MW%3B1277WWA%3B269WW%3B159WA%3B48W%3B288WM%3B269WW%3B949MW%3B19M29MW%3B1949MWA%3B159WA%3B48W%3B288WM%3B1278WWA%3B1278WWA%3B1269WWA%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B288WM%3B1278WWA%3B1278WWA%3B2279WAW%3B1269WWM%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B288WM%3B67W89WM%3B1278WWA%3B789MW%3B19M29MW%3B159WA%3B48W%3B288WM%3B949MW%3B67W89WM%3B67W89WM%3B159WA%3B48W%3B388WM%3B1277WWA%3B19M29MW%3B1949MWA%3B789MW%3B1689MWA%3B269WW%3B269WW%3B159WA%3B48W%3B388WM%3B1277WWA%3B278WW%3B357WW%3B1949MWA%3B1278WWA%3B159WA%3B48W%3B388WM%3B1277WWA%3B67W89WM%3B455WW%3B357WW%3B19M29MW%3B159WA%3B48W%3B388WM%3B1277WWA%3B67W89WM%3B278WW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B388WM%3B1277WWA%3B2949MWA%3B1689MWA%3B1358WWM%3B159WA%3B48W%3B388WM%3B1277WWA%3B2949MWA%3B2949MWA%3B357WW%3B455WW%3B1358WWM%3B159WA%3B48W%3B388WM%3B1278WWA%3B929MW%3B849MW%3B67W89WM%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B388WM%3B1278WWA%3B269WW%3B269WW%3B357WW%3B19M29MW%3B2949MWA%3B159WA%3B48W%3B388WM%3B1278WWA%3B1278WWA%3B19M29MW%3B2949MWA%3B159WA%3B48W%3B388WM%3B1278WWA%3B67W89WM%3B1269WWA%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B388WM%3B1278WWA%3B67W89WM%3B19M29MW%3B1358WWM%3B19M29MW%3B159WA%3B48W%3B388WM%3B1278WWA%3B67W89WM%3B1949MWA%3B1689MWA%3B2279WAW%3B48W%3B499WA%3B1277WWA%3B2949MWA%3B1949MWA%3B1278WWA%3B159WA%3B48W%3B388WM%3B1278WWA%3B1949MWA%3B1949MWA%3B1278WWA%3B19M29MW%3B159WA%3B48W%3B388WM%3B67W89WM%3B1277WWA%3B278WW%3B1278WWA%3B159WA%3B48W%3B388WM%3B67W89WM%3B949MW%3B2279WAW%3B159WA%3B48W%3B488WM%3B1277WWA%3B357WW%3B19M29MW%3B1689MWA%3B2949MWA%3B159WA%3B48W%3B488WM%3B1278WWA%3B19M29MW%3B19M29MW%3B1689MWA%3B269WW%3B269WW%3B1358WWM%3B159WA%3B48W%3B488WM%3B949MW%3B929MW%3B1269WWA%3B789MW%3B1278WWA%3B67W89WM%3B1949MWA%3B849MW%3B159WA%3B48W%3B488WM%3B949MW%3B67W89WM%3B277WW%3B357WW%3B19M29MW%3B159WA%3B48W%3B389WA%3B19M29MW%3B2279WAW%3B357WW%3B159WA%3B48W%3B389WA%3B67W89WM%3B19M29MW%3B2949MWA%3B1949MWA%3B159WA%3B48W%3B257WW%3B1689MWA%3B357WW%3B19M29MW%3B2949MWA%3B1949MWA%3B1689MWA%3B357WW%3B19M29MW%3B159WA%3B48W%3B257WW%3B357WW%3B2949MWA%3B929MW%3B849MW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B257WW%3B269WW%3B1277WWA%3B1269WWA%3B1689MWA%3B159WA%3B48W%3B257WW%3B67W89WM%3B1277WWA%3B19M29MW%3B1269WWA%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B189WA%3B1277WWA%3B67W89WM%3B455WW%3B19M29MW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B189WA%3B357WW%3B269WW%3B269WW%3B357WW%3B277WW%3B67W89WM%3B1277WWA%3B19M29MW%3B455WW%3B159WA%3B48W%3B189WA%3B67W89WM%3B1277WWA%3B849MW%3B1277WWA%3B1269WWM%3B159WA%3B48W%3B189WA%3B67W89WM%3B1277WWA%3B2949MWA%3B2949MWA%3B269WW%3B1689MWA%3B1358WWM%3B159WA%3B48W%3B89W%3B1277WWA%3B67W89WM%3B67W89WM%3B357WW%3B2949MWA%3B159WA%3B48W%3B89W%3B1277WWA%3B2949MWA%3B2949MWA%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B89W%3B1277WWA%3B1949MWA%3B929MW%3B849MW%3B159WA%3B48W%3B89W%3B1689MWA%3B357WW%3B19M29MW%3B67W89WM%3B357WW%3B929MW%3B849MW%3B159WA%3B48W%3B89W%3B1689MWA%3B357WW%3B1949MWA%3B1269WWA%3B1277WWA%3B1269WWM%3B278WW%3B159WA%3B48W%3B89W%3B1689MWA%3B269WW%3B269WW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B89W%3B357WW%3B67W89WM%3B1278WWA%3B19M29MW%3B1278WWA%3B159WA%3B48W%3B89W%3B1278WWA%3B1689MWA%3B1949MWM%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B189WM%3B19M29MW%3B849MW%3B1278WWA%3B689MW%3B1689MWA%3B159WA%3B48W%3B189WM%3B2949MWA%3B1277WWA%3B1269WWA%3B2949MWA%3B1278WWA%3B19M29MW%3B159WA%3B48W%3B289WM%3B1278WWA%3B849MW%3B19M29MW%3B2949MWA%3B1278WWA%3B19M29MW%3B159WA%3B48W%3B355WW%3B1277WWA%3B357WW%3B19M29MW%3B1689MWA%3B159WA%3B48W%3B355WW%3B1689MWA%3B19M29MW%3B19M29MW%3B1689MWA%3B455WW%3B1358WWM%3B159WA%3B48W%3B355WW%3B357WW%3B19M29MW%3B1849MWA%3B159WA%3B48W%3B355WW%3B269WW%3B1278WWA%3B277WW%3B949MW%3B929MW%3B849MW%3B1277WWA%3B67W89WM%3B159WA%3B48W%3B489WM%3B1277WWA%3B19M29MW%3B1269WWA%3B689MW%3B1278WWA%3B67W89WM%3B455WW%3B159WA%3B48W%3B489WM%3B1689MWA%3B1277WWA%3B849MW%3B1358WWM%3B159WA%3B48W%3B489WM%3B1689MWA%3B1689MWA%3B159WA%3B48W%3B499WA%3B1277WWA%3B19M29MW%3B929MW%3B849MW%3B357WW%3B19M29MW%3B159WA%3B48W%3B499WA%3B1277WWA%3B67W89WM%3B1269WWA%3B1689MWA%3B1358WWM%3B159WA%3B48W%3B499WA%3B929MW%3B388WM%3B1277WWA%3B357WW%3B19M29MW%3B159WA%3B48W%3B499WA%3B929MW%3B388WM%3B1277WWA%3B2949MWA%3B1269WWA%3B357WW%3B269WW%3B269WW%3B159WA%3B48W%3B499WA%3B929MW%3B388WM%3B1278WWA%3B19M29MW%3B19M29MW%3B1689MWA%3B269WW%3B269WW%3B159WA%3B48W%3B499WA%3B1689MWA%3B19M29MW%3B1689MWA%3B19M29MW%3B455WW%3B1689MWA%3B2279WAW%3B159WA%3B48W%3B499WA%3B1689MWA%3B67W89WM%3B1269WWA%3B269WW%3B1689MWA%3B1358WWM%3B159WA%3B48W%3B499WA%3B1278WWA%3B67W89WM%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B499WA%3B949MW%3B67W89WM%3B1269WWA%3B1278WWA%3B789MW%3B2949MWA%3B1269WWA%3B357WW%3B159WA%3B48W%3B499WA%3B949MW%3B67W89WM%3B278WW%3B849MW%3B1358WWM%3B159WA%3B48W%3B499WA%3B949MW%3B67W89WM%3B67W89WM%3B1277WWA%3B1358WWM%3B159WA%3B48W%3B399WA%3B1689MWA%3B269WW%3B2949MWA%3B1278WWA%3B19M29MW%3B159WA%3B48W%3B199WA%3B1277WWA%3B949MW%3B269WW%3B159WA%3B48W%3B199WA%3B1689MWA%3B67W89WM%3B455WW%3B949MW%3B1689MWA%3B159WA%3B48W%3B199WA%3B1689MWA%3B1949MWA%3B1689MWA%3B67W89WM%3B2949MWA%3B159WA%3B48W%3B199WA%3B1278WWA%3B67W89WM%3B1949MWA%3B1269WWM%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B199WM%3B1689MWA%3B1689MWA%3B455WW%3B159WA%3B48W%3B199WM%3B357WW%3B2949MWA%3B929MW%3B849MW%3B159WA%3B48W%3B199WM%3B1278WWA%3B277WW%3B1689MWA%3B67W89WM%3B1949MWA%3B2949MWA%3B159WA%3B48W%3B199WM%3B1278WWA%3B949MW%3B19M29MW%3B455WW%3B2949MWA%3B159WA%3B48W%3B199WM%3B949MW%3B277WW%3B357WW%3B1278WWA%3B159WA%3B48W%3B299WM%3B1277WWA%3B19M29MW%3B455WW%3B1689MWA%3B67W89WM%3B2949MWA%3B159WA%3B48W%3B299WM%3B1277WWA%3B2949MWA%3B2949MWA%3B1689MWA%3B159WA%3B48W%3B299WM%3B929MW%3B849MW%3B1277WWA%3B1949MWA%3B2279WAW%3B159WA%3B48W%3B299WM%3B929MW%3B849MW%3B949MW%3B1269WWM%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B299WM%3B929MW%3B1278WWA%3B1949MWA%3B1949MWA%3B159WA%3B48W%3B299WM%3B849MW%3B1277WWA%3B849MW%3B1689MWA%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B299WM%3B849MW%3B1689MWA%3B269WW%3B277WW%3B1358WWM%3B159WA%3B48W%3B299WM%3B1949MWA%3B1277WWA%3B277WW%3B1689MWA%3B19M29MW%3B1278WWA%3B789MW%3B159WA%3B48W%3B299WM%3B1949MWA%3B67W89WM%3B1277WWA%3B19M29MW%3B1849MWA%3B1689MWA%3B159WA%3B48W%3B299WM%3B949MW%3B269WW%3B269WW%3B357WW%3B1949MWM%3B1277WWA%3B19M29MW%3B159WA%3B48W%3B267WW%3B1689MWA%3B2949MWA%3B1949MWA%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B267WW%3B849MW%3B949MW%3B19M29MW%3B1689MWA%3B159WA%3B48W%3B267WW%3B357WW%3B269WW%3B269WW%3B357WW%3B2949MWA%3B159WA%3B48W%3B267WW%3B1278WWA%3B1278WWA%3B1269WWM%3B1689MWA%3B1358WWM%3B159WA%3B48W%3B499WM%3B455WW%3B1277WWA%3B269WW%3B269WW%3B159WA%3B48W%3B599WM%3B1277WWA%3B19M29MW%3B48W%3B89W%3B1278WWA%3B269WW%3B269WW%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B699WM%3B1277WWA%3B67W89WM%3B19M29MW%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B699WM%3B1277WWA%3B67W89WM%3B67W89WM%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B699WM%3B849MW%3B357WW%3B1949MWA%3B1689MWA%3B849MW%3B1278WWA%3B949MW%3B2949MWA%3B1689MWA%3B159WA%3B48W%3B699WM%3B357WW%3B929MW%3B1269WWA%3B1689MWA%3B67W89WM%3B159WA%3B48W%3B699WM%3B1358WWM%3B455WW%3B1689MWA%3B19M29MW%3B159WA%3B48W%3B899WM%3B1278WWA%3B949MW%3B19M29MW%3B1849MWA%3B%0A&input=) Made using [Arnauld's MAWP string printer.](https://codegolf.stackexchange.com/a/204650/80214) Somehow it's not the biggest solution in here. [Answer] # Javascript, 275 bytes ``` alert`LeeBurrCruzEnziKingPaulReedBluntBrownCaseyCoonsCrapoErnstFlakeHatchKaineLeahyMoranRischRubioSasseScottThuneUdallWydenYoungBennetBookerCapitoCardinCarperCorkerCornynCottonDainesDurbinGrahamHarrisHassanHellerHironoHoevenInhofeMarkeyMcCainMurphyMurrayNelsonPerduePetersRounds` ``` Trivial Answer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~234~~ ~~192~~ 191 bytes ``` .•–¯¼‡=/–nhVηÕÞ·×üΣA₁OúÝá=‘Φδk∍˜§ýz†ÂËt@ä‹A‡4)нW¯/kΓoʒÇ4ùŽY„¥₂2ƲFƒtā˹kyØ¢øÏ‹Õ.γbÓÄ ₃%‡íéZ'Oδ{)©»Õ¡Ôº₃j Qyù+íw¬u®ÃÑ3ô₂вÊîv/˜āø¡м¨Z{4∞ä”ôsó×JËP¹pWǝŽèñÇdb]qÀS¼ª†šвε:Ω¢ùÉfΣS€…Ÿ>и²%É(A90þ’8ˆ•™ ``` [Try it online!](https://tio.run/##FVBLSwJRGN33P6Qk0CgXFRi5adHGIkgKWiQVldCDXpib6yimSUWaWJDSWJlGKY0TztTY4jtZkHCZ33D/iF13Bw7nub23HNxY7XZdgpUEy1KdLMFUr1virfV53kQORWoiD4vf@4QS9eMDBahewa5xTmWuh0TyrHNLT2gdC3YHBen9STwIZvqkj8dptwJUd4d4dvsvgxMPzHZrQbAiPQpFGUaCtKmfzP53FGkyQ2FcUwkGLqQaORdvBJFFvE8oMYf0wiuqi/1@rkecVKVP5EjFFX1IdrNvNgxzEK9H9HIAhWqI4XIEuoywNZyiduju3MoMg1TbospixCOSxV7HAvQ9NJCfRnqGzJ3Ab6HdQgVvOFkJLu2CzZFFz3JVW7U1/j7Oq7KeidQav58Tyotg5bYxYRukOZAa8I0N4Uuwm9FOondlvNTt/gM "05AB1E – Try It Online") Outputs: `Bennet Blunt Booker Brown Burr Capito Cardin Carper Casey Coons Corker Cornyn Cotton Crapo Cruz Daines Durbin Enzi Ernst Flake Graham Harris Hassan Hatch Heller Hirono Hoeven Inhofe Kaine King Leahy Lee Markey Moran Murphy Murray Nelson Paul Perdue Peters Reed Risch Rounds Rubio Sasse Scott Thune Udall Wyden Young` ]
[Question] [ ### Task Given the situation with this global pandemic, you've been enlisted to help maintain social distancing. Your challenge, should you choose to accept it, is to write a program that takes in the positions of a group of people and checks whether the group is following social distancing rules. Your program must output a truthy value if social distancing guidelines are being met else output a falsy value. People must always be six spaces apart: ``` [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] -> True [[1, 0, 0, 0, 0, 0, 0, 1]] -> True [[1, 0, 0, 0, 0, 0, 1]] -> False [[1, 0, 0, 1]] -> False [[1], [0], [0], [0], [0], [1]] -> False [[1], [0], [0], [0], [0], [0], [0], [1]] -> True ``` For the purpose of this challenge, instead of measuring distance with Pythagoras's theorem, we measure the distance as the length of the shortest path between two people, so this example outputs true: ``` [[1, 0, 0, 0, 0,], [0, 0, 0, 0, 0,], [0, 0, 0, 0, 0,], [0, 0, 0, 0, 1,]] -> True ``` Since the shortest path passes through at least six squares. ``` [[1, █, █, █, █,], [0, 0, 0, 0, █,], [0, 0, 0, 0, █,], [0, 0, 0, 0, 1,],] ``` Your algorithm must be deterministic (i.e., always produce the same output). Your program should also, at least in theory, work for inputs containing more than five people and needs to work for a two dimensional input. ### Input and Output Your input can be the a nested array in STDIN or any other input format that doesn't break the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). Output has to be written to STDOUT or closest alternative. Output should consist of a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194) (or a string representation thereof). ### Additional Rules and Examples ``` [[1, 0, 0, 0, 0, 0, 1, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1,]] -> False [[1, 0, 0, 0, 0, 0, 0, 1, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 1, 0, 0, 0, 0,]] -> True [[1, 0, 0, 0, 0, 0, 0, 1, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 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, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [1, 0, 0, 0, 0, 0, 0, 0, 1,]] -> True [[1, 0, 0, 0, 0, 0, 0, 1, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [0, 0, 0, 0, 1, 0, 0, 0, 0,], [0, 0, 0, 0, 0, 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, 0, 0, 0,], [0, 0, 0, 0, 0, 0, 0, 0, 0,], [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,], [1, 0, 0, 0, 0, 0, 0, 0, 1,]] -> False ``` * Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. The language [Piet](http://www.dangermouse.net/esoteric/piet.html), for example, will be scored in codels, which is the natural choice for this language. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/). * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # [Python 2](https://docs.python.org/2/) with `SciPy`, ~~105 101~~ 99 bytes *-1 byte thanks to @vroomfondel !* ``` lambda l:N.all(S.convolve2d(l,N.outer(*[N.r_[:7]-3]*2)**2<9)<2) import numpy as N,scipy.signal as S ``` [Try it online!](https://tio.run/##1VTRbpswFH33VxyxF0gIKuxhGmr6srVSX9hD@sZQ5ILTWjO2ZZtkfH1mmmhb1tCsWqduEkLce8895/gaW/fuXslsu5p/3gra3jYUIi8SKkS4SGol10qsWdaEIi4S1TlmwklZJGZZ5u@q2dtqkkWTSXb@PjrPIsJbrYyD7Frdg1oUsa257hPL7yQVQ2axbdgKd8wtBZcsjHICZ/ochrnOSBi6WXKpOxdGBOxrzbTD5aerS2OU@Q4qlGSEbO65YEg9wRtfoA0oHLMONbUMK6NaLG4@XhcEFvOfBAn4yqe4faDJcet7vxDs2ILZRQCpHLiEzS2mh50/vr0ma7XrMYQEIgaVdsOMl2qpDtma@pRNrBbchQNrFJHB6OCQeLu2E85jV6HwtNpw6fbJGEEZTMNdMJ/vWalsEHxQxrDaBVAGwbWs92E0DapgW5ZpjLMnn7SqMLvAjen89EbwJzF7wBUV9hDxqFDFBOXZyPt56COdxx3ucM9OpfHJZT9JiJOSf4g4ZmhsIx7ZPiH2T5V/2c7f@GH/8xW@trWxWyP9a8N/oQEcaKevqD1yQl9i@A@H@xs "Python 2 – Try It Online") A function that takes in a 2D list, and returns a boolean representing whether social distancing guidelines are met. ### Big idea For each position in the array, there can only be at most 1 person within a 3 unit radius around that position. (If there are 2 people near that position, then they are at most 5 units apart.) We can use convolution to count how many people are within a 3 unit radius of any point. The kernel specifies all positions at most 3-unit away from the current point: ``` [[0 0 0 1 0 0 0] [0 0 1 1 1 0 0] [0 1 1 1 1 1 0] [1 1 1 1 1 1 1] [0 1 1 1 1 1 0] [0 0 1 1 1 0 0] [0 0 0 1 0 0 0]] ``` After convolution, we just need to check if all positions are less than 2. The following examples show the results of the convolution (`0` is replaced with `.` for visual clarity): ``` ...1......1.... ..111....111... .11111..11111.. 1......1. 11111111111111. ......... .11111..11111.. ......... ..111....111... ......... --> ...1...1..1.... ......... ......111...... ......... .....11111..... ....1.... ....1111111.... .....11111..... ......111...... .......1....... ...1......1.... ..111....111... .11111.111111.. 1......1. 11111122211111. ......... .111121122211.. ....1.... ..1131111332... ......... ...2121222211.. .......1. ..111133311111. .1....... --> .111122322211.. ....1.... ..1122311332... ......... ...1132222211.. .......1. ...12123311211. ...1..... ..12211222222.. ......... .1112211122211. 1.......1 111112211121111 .111111..11111. ..111.....111.. ...1.......1... ``` ### Code explanation The only tricky part is to create the kernel. First, we use `numpy.outer` to find the outer product of 2 arrays: ``` >> numpy.r_[:7] [0 1 2 3 4 5 6] >> numpy.r_[:7] - 3 [-3 -2 -1 0 1 2 3] >> numpy.outer([-3,-2,-1,0,1,2,3], [-3,-2,-1,0,1,2,3]) [[ 9 6 3 0 -3 -6 -9] [ 6 4 2 0 -2 -4 -6] [ 3 2 1 0 -1 -2 -3] [ 0 0 0 0 0 0 0] [-3 -2 -1 0 1 2 3] [-6 -4 -2 0 2 4 6] [-9 -6 -3 0 3 6 9]] ``` Then, we only keep the elements whose absolute value is less than 3. ``` >> numpy.outer(...)**2 < 9 [[0 0 0 1 0 0 0] [0 0 1 1 1 0 0] [0 1 1 1 1 1 0] [1 1 1 1 1 1 1] [0 1 1 1 1 1 0] [0 0 1 1 1 0 0] [0 0 0 1 0 0 0]] ``` [Answer] # [R](https://www.r-project.org/), 42 bytes ``` function(m)all(dist(which(m>0,T),"man")>6) ``` [Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI1czMSdHIyWzuESjPCMzOUMj185AJ0RTRyk3MU9J085M83@aRlFqYopecnGZRoatm05xaoGtkoKSTklqRYmtkqGCARZoqKSpyUWCPtLUE1TNhVDOZYCHZahAgklg9WgmKWAxnSgxcr0D08xFhGUUisDtHOTOo5rJhqQmYtI8TryDIeYYUskctORGpMf/AwA "R – Try It Online") Pretty self-explanatory - anonymous function that checks whether Manhattan distances between the coordinates of each non-zero entry of the input is greater than 6. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 17 bytes -1 thanks to Bubbler. Full program. Input: Expression for Boolean (0/1) matrix via STDIN. Output: 0 or 1 to STDOUT. ``` (×≡6∘<)+/¨|∘.-⍨⍸⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/G4emPOheaPeqYYaOprX9oRQ2Qpaf7qHfFo94dj/qmghT9VwCDAq5HbROBQl7B/n7q0dGGOgoGeJFhbKw6F/FaSVFOhFo8SmJ1FKINsBBkaCFKM7LbwepJEiApXHAbi4aoKm9IcdwTsnEwSKLG43D33wA5yJBKhckAeB7JTsMBsBN7VqQowAE "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for matrix `⍸` **ɩ**ndices of trues `∘.-⍨` (y,x) distances between all combinations of coordinate pairs `|` absolute value `+/¨` sum each (this gives a matrix of Manhattan distances) `(`…`)` apply the following tacit function to that:  `6∘<` the matrix mask indicating (0/1) where greater than six  `×≡` does it match the matrix of signums (0/1)? In effect, this checks if all non-zero distances are greater than six. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly) ``` ŒṪŒcạ/€§>6Ạ ``` A monadic Link accepting a multi-dimensional list which yields an integer: `1` if distancing has been maintained; `0` if not. **[Try it online!](https://tio.run/##y0rNyan8///opIc7Vx2dlPxw10L9R01rDi23M3u4a8H///@jow11FAxQEZJIrA6XQrQBhgoDWqrA5qDYWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opIc7Vx2dlPxw10L9R01rDi23M3u4a8H/w@1Azv//0dHRhjoKBniRYWwslw4OdTjl0CVg/FgdLgWFaAM8FPEqsetDcQdUBRlihjo4vYbfKAXCtlGsBJuj8MUSMbYMPnm0qBzu/hsU7sNVGtAifVHN/6j2Gw6w/TiyKBXCPxYA "Jelly – Try It Online"). ### How? ``` ŒṪŒcạ/€§>6Ạ - Link: list ŒṪ - multi-dimensional truthy indices Œc - pairs € - for each: / - reduce by: ạ - absoulute difference (vectorises) § - sums >6 - greater than six? (vectorises) Ạ - all truthy? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~59~~ 48 bytes *Saved 11 bytes and removed the imperfections thanks to user202729's great comment!* ``` Min[Tr@Abs[#-#2]&@@@#~Position~1~Subsets~{2}]>5& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczLzqkyMExqThaWVfZKFbNwcFBuS4gvzizJDM/r86wLrg0qTi1pLiu2qg21s5U7X9AUWZeSXSaQ3W1oY6CASoyrK2N5cKpACT7HwA "Wolfram Language (Mathematica) – Try It Online") Unnamed function taking an array of `0`s and `1`s as input and returning `True` or `False`. * `#~Position~1` finds the coordinates of the people in the input array. * `~Subsets~{2}` collects all unordered pairs of such coordinates. * `Tr@Abs[#-#2]&@@@` sums the absolute values of coordinatewise differences inside each such pair. * `Min[...]>5&` tests whether the differences comprise sufficient social distancing. In addition to being shorter than the other Mathematica answer, this implementation has the property that *it works on inputs of any dimensions* (even uneven arrays). Social distancing in spacetime, anyone...? [Answer] # JavaScript (ES6), ~~93 84 82~~ 80 bytes Takes a binary matrix as input and returns a Boolean value. ``` f=(m,X,Y)=>m.every((r,y)=>r.every((v,x)=>v?1/X?x<X|x-X+y-Y>6:f(m,x,y,r[x]--):1)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjVydCJ1LT1i5XL7UstahSQ6NIpxLILYJxy3QqgNwye0P9CPsKm4iaCt0I7UrdSDszqzSg3gqdSp2i6IpYXV1NK0NNzf/J@XnF@Tmpejn56RppGtFcCtGGOgoGqAhJJFYHqMIAQ4UBLVVgc1AsV6ympoK@voJbYk5xKhcXMd6AGUXA/kEljeoLuK9DikpHjqcH2mmGOKQN6RkfVAoTFLsNB9BuHFmbSvEBLhX@AwA "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜ƶ0K<Iнg‰2.Æε`αO7@}P ``` [Try it online](https://tio.run/##yy9OTMpM/f//9Jxj2wy8bTwv7E1/1LDBSO9w27mtCec2@ps71Ab8/x8dbahjAIGxOtEGBNiGsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lot46Sf2kJhGtf@f/0nGPbDLxtKi/sTX/UsMFI73Dbua0J5zb6mzvUBvzXObTN/n90dLShjgEWaBgbq4MuhymGLAJlAwkDNIxbBk0FzFyQKAE2FrdgqtfBagrRooaEwgO7CTQUQ4TQ4HIN9e0wJCY9UtmFMPMMqWweWloi3sexAA). **Explanation:** ``` ˜ # Flatten the (implicit) input-matrix ƶ # Multiply each value by its 1-based index 0K # Remove all 0s < # Decrease each by 1 to make it 0-based indexing I # Push the input-matrix again нg # Pop and get the width of the matrix (length of the first row) ‰ # Divmod each integer by this row-length to get all coordinates 2.Æ # Get all possible pairs of coordinates ε # Map each pair of coordinates to: ` # Pop and push the coordinates separated to the stack α # Take the absolute differences of both the x and y coordinates O # Sum those two together 7@ # And check whether it's >= 7 }P # After the map: check if all were truthy # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes ``` 2>Max@ListConvolve[Table[Boole[i<j],{i,8},{j,8}],#~ArrayPad~9]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb89/IzjexwsEns7jEOT@vLD@nLDU6JDEpJzXaKT8fSGbaZMXqVGfqWNTqVGcByVgd5TrHoqLEyoDElDrLWLX//nkOjsXFqUUlXFwBRZl5JQ5pDtXVhjoKBniRYW0tIeWoSgxQeEAOXu04jEcVNgLy/gMA "Wolfram Language (Mathematica) – Try It Online") The list convolution kernel `Table[Boole[i<j],{i,8},{j,8}]` can be generated as `UpperTriangularize@ConstantArray[1,{7, 7}]` too (using more built-in), but that's longer. Unlike most (all?) other solutions posted, this solution only have time complexity O(n) in terms of the input size (with a possibly large constant factor) [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes Takes as input a list of lists \$ l \$, and outputs `True` if social distancing is *not* followed, and `False` otherwise. ``` eval(f"lambda l:any(s&q>0<abs(a-c)+abs(b-d)<7{'for %s,%s in enumerate(%s)'*4%(*'aplbqpcrldsr',)})") ``` [Try it online!](https://tio.run/##1VRRa4MwEH73V9wKLrlOh2GDQal93C/Ym/MhaqRCam1ON8rYb3dVBttq1Y5udIMQwt139313yaXYlst1flOn/mOtnqTm6UTLVZRI0DOZbzldbhbeXEbEpRvjVXOI3ATndy8sXRuwybEJshxUXq2UkaXiNiGb3tp8ymSho00RG52QYQ6@4gTr52WmFYiZBbEkBf4utqhKjtdU6KzkDNwFMLRAEilTQspbUQ028EJEuPDhwyJCrINAOOANLhGGTdoHUymrBz4GefffS01fAPv20IGdzu52LK4TcVBRC/qmRThjJQ5lgzG6kwCHxPQ0vKN4mOmvePfub/w9/tvSzqiq7yMQv9PwHyn8M684E2/PEJ7e8HZ63wA "Python 3 – Try It Online") ## Explanation We can reduce the following code to 99 bytes by using the fact that the expression `for a,b in enumerate(c)` is used a total of four times, which can be condensed. ### [Python 3](https://docs.python.org/3/), 111 bytes ``` lambda l,E=enumerate:any(s&q>0<abs(a-c)+abs(b-d)<7for a,p in E(l)for b,q in E(p)for c,r in E(l)for d,s in E(r)) ``` [Try it online!](https://tio.run/##1VRNb4MwDL3zK7zLGmthItphUlV6637BboyDgaAipTRNwqb@elbopHWlwKpu6iZFUez3Yj87H3rrluvyoc7Dl1rRKskIFF@EsqxW0pCTUyq3zN5u5sGMEsvIT/GuWSR@hrPHfG2AuIaihAVT2JgJ3@xN3ZopN4doxu3eNIj127JQEsTUg5SshHCH6MoxvLdaFY5NwJ/DBD0ga6VxkDP5Soo13CiIEeEmhE@PiLGOIsEhGBwijpuwz6aSXg99jPKBP5GyXwjH/pjDTmd3@i6vs@OkopZ0pkfwsRKHosFYuosIp8T0NLyjeDjTX0GPzm/8Pv7b0q6oqu8jEL/T8B8p/DCvuFLenkd4ecPb1/sO "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes ``` 1Ya&fht1&ZP7<zGz= ``` Outputs `1` if the input satisfies the distance rule, and `0` otherwise. [Try it online!](https://tio.run/##y00syfn/3zAyUS0to8RQLSrA3KbKvcr2//9oQx0FA1SEELFGl0JBVJLF4oBYAA) Or [verify all test cases](https://tio.run/##y00syfmf8N8wMlEtLaPEUC0qwNymyr3K9r9LVEXI/2hDHQUDvMgwlgu7IuwSKKJgjrWCARLCIoQkgWkcnG2N151UkjUkwfv4zR04KRTXDm3X09cZhiTnADp6DG6XIR3twp4pyAxEAA). ### Explanation Consider the following input as an example: ``` [1 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0; 0 0 0 1 0 0 0 0 0 1] ``` ``` % Implicit input 1Ya % Padarray with size 1 along the first dimension. This extends the % input with two rows of zeros. The purpose if this is to ensure that % the modified input will never be a row vector % STACK: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0; 1, 0, 0, 0, 0, 0, 1, 0, 0, 0; 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; 0, 0, 0, 0, 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, 1; 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] &f % Two-output find: row and column indices of nonzeros. This gives the % result as column vectors (it would give row vectors if the input % argument were a row vector, but the previou steps ensures that will % not happen) % STACK: [1; 5; 1; 5], [1; 4; 7; 10] h % Concatenate horizontally % STACK: [1 1; 5 4; 1 7; 5 10] t % Duplicate % STACK: [1 1; 5 4; 1 7; 5 10], [1 1; 5 4; 1 7; 5 10] 1&ZP % Cityblock distance between rows of the two matrices. Gives a matrix % with the distances. The diagonal contains 0 % STACK: [0 7 6 13; 7 0 7 6; 6 7 0 7; 13 6 7 0] 7< % Less than 7? Element-wise. The diagonal contains 1. An off-diagonal % entry is 1 if and only the distance condition is not satisfied for % that pair of people % STACK: [1 0 1 0; 0 1 0 1; 1 0 1 0; 0 1 0 1] z % Number of nonzeros % STACK: 8 Gz % Push input again. Number of nonzeros % STACK: 8, 4 = % Equal? % STACK: 0 % Implicit display ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 87 bytes ``` M`10{0,5}1|(?<=(.)*)(?=(1)){6}(?<-2>.*\n)+(?>(?<-1>.)*)((?<-2>0)*1|0(?<=1(?<-2>0)*)) ^0 ``` [Try it online!](https://tio.run/##K0otycxL/P/fN8HQoNpAx7TWsEbD3sZWQ09TS1PD3lbDUFOz2qwWKKRrZKenFZOnqa1hbwfiGtqBlUBkDDS1DGsMQBoN4QKamlxxBv//G0CAoQGXIZRpwGWAg2WIVxasgssAZgwA "Retina 0.8.2 – Try It Online") Takes input as a linefeed-separated character array and outputs `1` or `0` (outputting `0` or `1` would save 3 bytes; outputting `0` or non-`0` would save 5 bytes). Explanation: ``` 10{0,5}1| ``` Are two `1`s on the same row fewer than 6 `0`s apart? Otherwise, ``` (?<=(.)*) ``` Count the current column in `$#1`. ``` (?=(1)){6} ``` Store 6 in `$#2`, plus ensure that we're matching a `1`. ``` (?<-2>.*\n)+ ``` Move down rows, decrementing `$#2` each time. (If `$#2` runs out, this match fails, so the regex engine has to try fewer rows or starting at a different `1`.) ``` (?>(?<-1>.)*) ``` Move across to column `$#1`. ``` ((?<-2>0)*1|0(?<=1(?<-2>0)*)) ``` Try looking either right or left for a `1` that is no more than `$#2` `0`s away, meaning that it is not sufficiently distant. ``` M` ^0 ``` The above regex looks for insufficiently distant pairs, so check whether none were found to give the desired result. [Answer] # [JavaScript (V8)](https://v8.dev/), 126 bytes ``` e=>(e.map((w,x)=>w.map((t,y)=>t?p.push({x,y}):''),p=[],d=Math.abs),p.every(r=>p.filter(t=>d(r.x-t.x)+d(r.y-t.y)<7).length==1)) ``` [Try it online!](https://tio.run/##zVLBSsRADL33K/bWBGdD56SIqV/gF5Qext3pdmXcDjPZbgfx22vXgiAqyuKhIYeX8HgJeXkyvYmbsPey7m/GhkfLJVh6Nh7gpAbk8jQXotJUyL0nf4wtvAwqveJtnqPyXNVqyw9GWjKPcWqQ7W1IELj01Oyd2ADC5RYCDWuhAa/OME0w4d01krOHnbTMGnHcdIfYOUuu20HeGBct5ypbTdFAVel6xlXxB6DrGjPMPilKOF4ueOEItSq@5HvzQ@47RrF0hl70pvoHhlazZdkvj/Zvpuklm3Y@xfgG "JavaScript (V8) – Try It Online") [Answer] # perl -E, 157 bytes ``` @b=map{[/\d/g]}<>;for$x(@a=keys@b){for$z(@a){for$y(@c=keys@{$b[0]}){for$w(@c){$t||=$b[$x][$y]&&$b[$z][$w]&&abs($x-$z)+abs($y-$w)<7&&($x!=$z||$y!=$w)}}}}say$t ``` [Try it online!](https://tio.run/##zY69DoIwEIB3n6ImF0IjSDsQB4HwAm5utQMoGuMPhGKgBV7dWmBUdy6X3JfvW67IyruvdZyGj6RomXc4eRfeB9H2nJfQ2HES3jIp4hS3g1BGTCTt@DilFlJGeD/p2mjcQtV1odHQcAaSW9bAynBtOEmFDY0LCq9GlC7UONhYlrHLEFTXgTS3xr0ZkUiotGaMOoh87Si5s0CM/MpkdpnO6zX6J1OHc@RGaF@@sndeVNf8KbS789eEkg8 "Perl 5 – Try It Online") Prints a false value (0, or empty string) if all people are at least distance 6 away, and prints 1 if there is at least one pair of people with less distance. [Answer] # [Python 3.8 or newer](https://docs.python.org/3.8/), ~~137~~ 135 bytes ``` lambda m:(p:=[(r,c)for r in range(len(m))for c in range(len(m[0]))if m[r][c]])and all(abs(a-c)+abs(b-d)>6for(a,b),(c,d)in zip(p,p[1:])) ``` [Try it online!](https://tio.run/##3VRNT4QwEL33V0z2wkwsCbhGDQl79Bd46/ZQoCgJsE0piUr47Qj4EdHdeHDNGpummb55nY@mfebR3e/q9bWxQx5vh1JVSaagitBEsUDLU8p3FiwUNVhV32ksdY0VzWj6CRWBJCpyqISVIpWSVJ2BKktUSYPKT@lsMhI/o83leB4VT4hjyjMa4zwVBg03IozGIIPTjWsgBmRChByC5fyASM5ABF8YwW8y9hUkR8q@Ut/o3@T4U@5lF/@4s1OXFh5wH/85HanxRe7whLkPfMSfXzox/WAm4blRZaM53Nr2fZ0hYjbG1tu251cXqcfhxQzXHrFJEx3X8Kpms4bxMRxFDMYx6VmOjuaNsUXtMF91rgd/A13TQ2dFE8da9isangE "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") puzzle the robbers' thread can be found [here](https://codegolf.stackexchange.com/questions/107014/hidden-inversions-robbers-thread). Your task will be two write two programs (or functions) such that they are [anagrams](https://en.wikipedia.org/wiki/Anagram) of each other and one performs the left [inverse](https://en.wikipedia.org/wiki/Inverse_function) of the other. These programs may accept and output as many *integers* or complex numbers as you wish. If you choose take numbers as character points or any other reasonable means you must indicate you are doing so in your answer. If you choose to restrict the domain of your function you must also indicate the restricted domain in your answer. You will then present the first program in the form of an answer with left inverse hidden for robbers to find. The shown program must implement a injective function (otherwise it would be impossible for a hidden answer to exist). If your answer has not been cracked in one week you may reveal the hidden answer and mark it as **safe**. Safe answers cannot be cracked by robbers and will remain un-cracked indefinitely. The goal will be to create the shortest un-cracked answer in bytes. ### Example You could show the following python program that adds one to the input ``` lambda x:~-x ``` A solution could be: ``` lambda x:-~x ``` This subtracts one from the input [Answer] ## Python 3, 80 bytes ([Cracked](https://codegolf.stackexchange.com/a/107477/64436)) ``` bhmq = int(input()) print(bhmq ** 2) (1 or [(sqrt),(specification+of*integerr)]) ``` Domain: positive integers. Function is just squaring of a number. Input to stdin, output to stdout, as well as in the inverse function. Note that Python ignores the third line here, because it is syntactically valid and 1 is already a truthy value, so Python doesn't even look whether the right part of 'or' is well-defined. Robbers should write a sqrt function that will work correct on all non-zero squares, printing integer value as is, without floating point (so on input '4' output should be '2' or '2\n', not '2.0' or '2.0\n'). [Answer] # Python 3, 46 bytes, [cracked](https://codegolf.stackexchange.com/a/107020/3852) ``` lambda x:x*(1999888577766665//844333333222200) ``` Doubles the input. [Answer] # [7](http://esolangs.org/wiki/7), 9 bytes, [Cracked](https://codegolf.stackexchange.com/a/107103/62131) This program's full of nonprintable characters, so here's a hexdump: ``` 00000000: 2573 dc01 7e13 dcb6 1f %s..~.... ``` Note: this uses a numeric input routine that's incapable of inputting negative numbers, so this submission is restricted to nonnegative integers only. One problem with [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenges is that you don't write explanations of the code (to make it harder to crack). On the other hand, this means that I don't have to go to to the trouble here. I picked 7 as the language because, especially in its compressed notation, it's pretty hard to read, and I don't see why it should be only *me* who has to go to the trouble of moving around 8-bit chunks of programs written in a 3-bit encoding. Good luck! ## Explanation Now that the program's been cracked (by brute force, unfortunately; that's always a danger in these short solutions), I may as well explain what I was getting at. This was actually fairly solvable by reading the program; I could have made it much more difficult, but that felt like a bad idea when brute-force cracks exist. We'll start by representing the program in a more natural encoding. As usual, bolded numbers indicate commands that run immediately (not all of which are representable in a program; **`6`** and **`7`** are but **`2`** to **`5`** aren't), unbolded numbers represent their escaped equivalents (`0` to `5`, all of which are representable in the original program; note that `0` is an escaped **`6`** and `1` is an escaped **`7`**): ``` 112**7**1**7**34002**77**023**67**13303 ``` The set of commands available in a 7 program source mean that it's basically just a literal that represents the original stack (there's nothing else you can do with just escaped commands, **`6`** and **`7`**). So the first thing a program will do is push a bunch of stuff onto the stack. Here's how the stack looks after the program's run (`|` separates stack elements, as usual in 7): ``` **772**|**7**|**34662**|023|**73363** ``` The final stack element then gets copied to become the code to run (while remaining on the stack). As it happens, this is the only part of the program that's code; everything else is just data. Here's what it translates to: ``` **73363** **7** Push an empty element onto the stack **3** Output the top stack element, discard the element below **73** Combined effect of these: discard the top stack element **3** Output the top stack element, discard the element below **6** Escape the top stack element, then append it to the element below **3** Output the top stack element, discard the element below ``` In other words, this is mostly just a bunch of I/O instructions. Let's analyse this in detail: * **`73`** discards the **`73363`** that's still on top of the stack. * **`3`** outputs the `023`, and discards the **`34662`**. It can thus be seen that the **`34662`** is a comment, which was used to store the bytes needed in the other version of the program. As for what `023` does when output, it selects I/O format 0 (integers), then `23` is a directive which requests the implementation to input an integer (in 7, you do input via outputting specific codes that request input). The input is done by making copies of the stack element below, e.g. if the input integer is 10, the next stack element (currently **`7`**) will become **`7777777777`**. Thus, we're accepting input from the user in decimal, but it's being stored as unary. * **`6`** escapes the top stack element (changing each instance of **`7`** to `1`; this is how strings consisting entirely of **`7`**s are escaped), then appends it to the stack element before (**`772`**). So our data is now something like `**772**1111111111`. * Finally, **`3`** outputs the stack element in question (and pops a blank stack element that's part of the default initial stack). Its value is calculated by taking the number of `1`s and **`7`**s, and subtracting the number of `0`s and **`6`**s. (The **`2`** in the middle is ignored in most cases; if it's at the end of the string, it'll become a trailing newline instead of being ignored, but PPCG rules don't care about that.) Thus, the output is the original input plus 2. At this point, there's nothing useful on the stack and nothing in the program, so the program exits. How do we reverse this? It's a simple matter of changing the `11` to `00`, so that we're prepending characters to the input that make it 2 lower, rather than 2 higher. There's a `00` conveniently hidden eight octal digits further on in the program (so that octal digits and bytes line up with each other), so we can simply swap it with the `11` at the start. [Answer] ## JavaScript (ES6), 21 bytes, [Cracked](https://codegolf.stackexchange.com/a/107024/58563) This is an easy one. ``` b=>Math.pow(b,torc=3) ``` Returns the cube of the input. [Answer] # Python 2, 83 bytes, [cracked](https://codegolf.stackexchange.com/a/107042) ``` #((()))****+,,---/2289;==oppppppqqqqqw~~ lambda n:pow(n,65537,10998167423251438693) ``` This is similar to my other answer. However, this uses 64-bit RSA, and is cryptographically quite weak. If you can rob this answer, you can theoretically rob my other one as well, given enough time. [Answer] # Python 2, 47 bytes, [Cracked](https://codegolf.stackexchange.com/a/107418/56656) ``` lambda x:x**2or (iron() and saxifrage.extend()) ``` The domain for this function is {x ∈ ℤ | x > 0}. It squares its input. --- [nmjcman101](https://codegolf.stackexchange.com/users/62346/nmjcman101) found the intended solution: > > `lambda x:sorted(a**2for a in range(x)).index(x)` > > > [Answer] # JavaScript (ES6), 46 bytes, [Cracked](https://codegolf.stackexchange.com/a/107520/32628) ``` x=>Math.log(x+(+String(t=985921996597669)[5])) ``` This function returns `ln(x+1)` where `x` is a non-negative number. ### Usage ``` (x=>Math.log(x+(+String(t=985921996597669)[5])))(5) ``` **Note:** Due to the nature of floating point numbers `f(g(x))` may not exactly equal `x`. Example: `f(g(4))=3.9999999999999996` [Answer] # J, 8 bytes, [cracked](https://codegolf.stackexchange.com/a/107045/6710) Another simple one to start off with. ``` [:]+:[-: ``` Doubles the input. [Answer] # Processing.js, 59 bytes, [Cracked!](https://codegolf.stackexchange.com/questions/107014/hidden-inversions-robbers-thread/107048#107048) ``` float igetuwebaoli(int p){return p*(((17*-4*-3)))+0+0;}//,, ``` This function multiplies the input by `204` (`17*-4*-3=204`). It takes in an int as input and outputs a float. As expected, the inverse divides the input by `204`. An online interpreter for processing-js can be found [here](http://js.do/blog/processing/editor/). [Answer] # J, 10 bytes, [cracked](https://codegolf.stackexchange.com/a/107106/6710) ``` 1%~<:[@*>: ``` Another simple one. Returns *n*2-1. [Answer] # JavaScript (ES6), 15 bytes, [cracked by Emigna](https://codegolf.stackexchange.com/a/107101/41859) ``` t=>(!!0+~~t+~0) ``` > > This functions returns `n-1`. > > > --- You can test it like: ``` (t=>(!!0+~~t+~0))(6) ``` --- **Cracked** My intended solution is a bit different than Emigna's crack: > > `t=>t+(+!!~~~00)` > > > [Answer] # [J](http://jsoftware.com/), 29 bytes ([Cracked](https://codegolf.stackexchange.com/a/107792/32014) by miles) ``` 5#.[:,(3 5&#:(-$]-)7)#.inv"0] ``` This is a verb that takes a **positive integer** as input, and does the following: 1. Convert to bases 2 and 4. 2. Pad the base-4 representation with 0s to have the same length as the base-2 representation. 3. Concatenate the two representations (base-2 first). 4. Interpret the concatenation as a base-5 representation and convert to integer. [Try it online!](https://tio.run/nexus/j#@5@mYGulYKqsF22lo2GsYKqmbKWhqxKrq2muqayXmVemZBD7PzU5I18hTcHU7D8A "J – TIO Nexus") ## My solution The logic is pretty much the same as in the crack. The rank conjunction `"` can be stuck in many different places (and I use it to get rid of the unnecessary `0` and `3`), since it doesn't really do anything in the solution. ``` (7-5)#.[:(]-:&#$,)5#.inv"0 3] ``` [Answer] # Processing (java), 59 bytes, SAFE ``` float igetuwebaoli(int p){return p*(((17*-4*-3)))+0+0;}//,, ``` This function multiplies the input by `204` (`17*-4*-3=204`). It takes in an int as input and outputs a float. As expected, the inverse divides the input by `204`. Note: both programs take an int as input and output a float. This answer is exactly the same as my other answer, except that my other answer was written in Processing.js. Meet Processing-java, the less verbose cousin of Java. You can download Processing [here](https://www.processing.org/download/) at processing.org. ### The Crack ``` float ap(int i){return i*pow(blue(get(0,0)),-1);}//++7*4*-3 ``` This program divides the argument by `204`. But how? Let's go inside the function. ``` i * //multiply i by blue( get(0, 0) ) //this (evaluates to 204) pow( , -1) //raises to the -1 power (ie its reciprocal) ``` Simple enough, but how does `blue( get(0, 0) )` become `204`? This is the centrepiece of this submission. First of all, `get(0,0)` gets the colour of the pixel located at `(0,0)` (the top left corner of the window, which always opens in a Processing sketch). Next, `blue()` gets the blue value of that pixel, which is `204`! To come up with this submission, I experimented by printing the different attributes of the colour obtained by `get(0,0)`. I have found out that the red, green, blue, alpha values are `204`, `204`, `204` and `255` respectively. From this, I decided to do a simple operation with this number and ended up with this post. [Answer] # JavaScript (ES6), 63 bytes [Cracked by Ilmari Karonen](https://codegolf.stackexchange.com/a/107185/32628) ``` x=>eval(atob`eCp4KzEvLyAgfXBModLS4TvEn4wp1iys9YRRKC85KLIhNMC=`) ``` Time for some `atob` nonesense. This function returns `x*x+1` where `x` is a non-negative number. ### Usage ``` (x=>eval(atob`eCp4KzEvLyAgfXBModLS4TvEn4wp1iys9YRRKC85KLIhNMC=`))(5) ``` ### Intended > > `x=>eval(atob`Lyp5fMRwICAgKi9NYXRoLnBvdyh4LTEsMC41KS8veCp4KzE=`)` > > > There's a large number of potential solutions, but I was hoping that the leading characters would throw off the byte order enough to make this harder. C'est la `atob` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 26 bytes, [Cracked](https://codegolf.stackexchange.com/a/107038/56656) ## Original ``` ((((()()())){}[()]){}{}{}) ``` ## My Crack > > `([(((()())){}()){}{}()]{})` > > > ## [1000000000](https://codegolf.stackexchange.com/users/20059/1000000000)'s Crack > > `([(((()())()){}){}{}](){})` > > > [Answer] # Python 2, 225 bytes, [cracked by Sp3000](https://codegolf.stackexchange.com/a/107660/21487) ``` #((()))****+,,---/000555666888;==oppppppqqqqqw~~ lambda n:pow(n,65537,9273089718324971160906816222280219512637222672577602579509954532420895497077475973192045191331307498433055746131266769952623190481881511473086869829441397) ``` Domain of this function is [0, n), where n is the huge number above. Yes, this function is invertible on this domain. And unless I messed up, breaking this answer is as hard as breaking 512 bit RSA. [Answer] # J, 15 bytes ``` (".&,'10.')#.#: ``` Takes a non-negative integer *n*, converts it to a list of binary digits, and combines those digits as a base 10 number. [Try it online!](https://tio.run/nexus/j#@5@mYGuloKGkp6ajbmigp66prKdsxcWVmpyRr6Cho5emZKCpoJGpp2AEpHUUjA3MTRVMDIDg/38A) ]
[Question] [ Word's `**A**▲` and `**ᴀ**▼` buttons change the font size according to these rules: 1. The starting font size is 11. 2. If `**ᴀ**▼` is pressed when the font size is 1, the size stays 1. 3. The font size changes with 1 point in the range 1 – 12. 4. The font size changes with 2 points in the range 12 – 28. 5. The choices are 28, 36, 48, 72, and 80 in the range 28 – 80. 6. The font size changes with 10 points in the range 80 – 1630. 7. The font size changes with 8 points in the range 1630 – 1638. 8. If `**A**▲` is pressed when the font size is 1638, the size stays 1638. ### Task In as few bytes as possible, determine the resulting font size when given a set of button presses in any reasonable format. ### Examples `[3,-1,2]`, meaning `**A**▲``**A**▲``**A**▲``**ᴀ**▼``**A**▲``**A**▲`: The result is 18. Some possible formats are `'^^^v^^'`, `[1 1 1 -1 1 1]`, `[True,True,True,False,True,True]`, `["+","+","+","-","+","+"]`, `"‘‘‘’‘‘"`, `"⛄️⛄️⛄️🌴⛄️⛄️"`, `111011`, `"CaB"`, etc... `[2]`: 14 `[-1]`:10 `[13]`:80 `[-11,1]`: 2 `[11,-1]`: 36 `[170,-1]`: 1630 `[2000,-2,100]`: 1638 [Answer] # Word VBA, ~~199~~ ~~147~~ ~~126~~ ~~116~~ ~~102~~ ~~100~~ ~~87~~ 85 Bytes *Why emulate when you can do?!* Declared function in the `ThisDocument` module that takes input `n` in the form of `Array(true,true,false,true)` and **outputs to the Word font size selector** **`:P`** **Golfed:** ``` Sub a(n):Set f=Content.Font:For Each i In n If i Then f.Grow Else f.Shrink Next:End Sub ``` **Ungolfed:** ``` Sub a(n) Set f=ThisDocument.Content.Font For Each i In n If i Then f.Grow Else f.Shrink End if Next '' Implicitly output font size to MS Word Font Size Selector End Sub ``` ## .GIF of usage [![I'm a .GIF!](https://i.stack.imgur.com/zeIzA.gif)](https://i.stack.imgur.com/zeIzA.gif) ## Thanks -21 thanks to @Adám (removed `Selection.WholeStory:` call) -10 thanks to @Adám (assume clean environment; remove `f.size=11:` call) -14 thanks to @Adám (cheeky output word font size selector) -2 thanks to @Adám (bool ParamArray) -13 for changing `ParamArray n()` to `n` and expecting input as Boolean Array -2 for moving from a code module to the `ThisDocument` module ## Old Version 114 Bytes Takes input `n` as a ParamArray, in the form of `true,true,false,true` and outputs word vbe immediates window ``` Sub a(ParamArray n()):Set f=Selection.Font:For Each i In n If i Then f.Grow Else f.Shrink Next:Debug.?f.Size:End Sub ``` ## Older version, 199 Bytes Takes input in the form of `170,-4,6,-1` (accepts numbers larger than 1 in magnitude) ``` Sub a(ParamArray n()):Selection.WholeStory:Set f=Selection.Font:f.Size=12:For Each i In n If i>1 Then For j=i To 0 Step -1:f.Grow:Next Else For j=i To 0:f.Shrink:Next:End If:Next:Debug.?f.Size:End Sub ``` [Answer] ## JavaScript (ES6), ~~103~~ 101 bytes Takes input as an array of `-1` / `1`. ``` a=>a.map(k=>[1,12,28,36,48,72,80,1630,1638].map((v,i)=>n+=n>v&&k*[1,1,6,4,12,-16,2,-2,-8][i]),n=11)|n ``` ### Test ``` let f = a=>a.map(k=>[1,12,28,36,48,72,80,1630,1638].map((v,i)=>n+=n>v&&k*[1,1,6,4,12,-16,2,-2,-8][i]),n=11)|n console.log(f([])); console.log(f([1])); console.log(f([-1])); console.log(f([1,1,1,-1,1,1,1,1,1,1,1,1])); console.log(f(Array(2000).fill(1))); ``` *Saved 2 bytes thanks to ETHproductions* [Answer] # Python 2, 111 107 bytes ``` i=10;r=range for d in input():i+=d*(0<i+d<179) print(r(1,12)+r(12,29,2)+[36,48,72]+r(80,1631,10)+[1638])[i] ``` Requires input to be in the `[-1, 1, 1, -1, ...]` format. It works with the examples for some bytes extra: ``` for d in input():i=min(max(0,i+d),179) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~49~~ ~~47~~ 45 bytes ``` 11: 9:E10+'$*H'o8:163 10*1638v11ihl180h&Ys0)) ``` Input format is `[1 1 -1 1 1 -1 -1 -1]` or `[2 -1 2 -3]`, with optional commas. [Try it online!](https://tio.run/nexus/matl#@29oaKVgaeVqaKCtrqLloZ5vYWVoZqxgaKAFpCzKDA0zM3IMLQwy1CKLDTQ1//@PNjSOBQA) Or [verify all test cases](https://tio.run/nexus/matl#S/hvaGilYGnlamigra6i5aGeb2FlaGasYGigBaQsygwNMzNyDC0MMtQiiw00Nf@7hPyPNorlitY1BBKGxmCWoQKYY6gAETQ3gDCMDAyALCOgUQaxAA). ### Explanation ``` 11: % Push [1 2 ... 11] 9: % Push [1 2 ... 9] E10+ % Times 2, plus 10: gives [12 14 ... 28] '$*H' % Push this string o % Convert to double: gives ASCII codes, that is, [36 48 72] 8:163 % Push [8 9 ... 163] 10* % Times 10: gives [80 90 ... 1630] 1638 % Push 1638 v % Concatenate everything into a column vector 11 % Push 11 ih % Input array and concatenate with 11 l180h % Push [1 180] &Ys % Cumulative sum with limits 1 and 180 0) % Get last value ) % Index into column vector of font sizes. Implicitly display ``` [Answer] # Octave, ~~93~~ ~~89~~ 87 bytes The input array can have integers larger than 1 or smaller than -1 to represent multiplicity of action ``` L=11;for k=input(''),L=min(max(L+k,1),180);end;[1:11 [6:14 18 24 36 40:5:815 819]*2](L) ``` Thanks to Adám, Changed language to Octave only to be able to use direct indexing into an array. Saved 2 bytes thanks to rahnema1. ## Test On [Ideone](http://ideone.com/tYVO9O) [Answer] # Ruby, 106 bytes I managed to shave a couple of bytes off the python solution (and it took a while of shaving). ``` ->n{[*1..12,*(14..28).step(2),36,48,72,*(80..1630).step(10),1638][n.inject(11){|a,b|[0,179,a+b].sort[1]}]} ``` It's an anonymous function that takes the input in the form of `[1, -1, 1, 1, ...]`. It seems to deal quite well with input in the form `[170,-12]` as well, but I can't guarantee it will work 100% of the time, so I'll play it safe and say it works with `[1, -1, 1, 1, ...]`. ## Tricks I used: * `[0,179,a+b].sort[1]`: This clamps `a+b` to be between 0 and 179, which are the valid indexes of the font-size array. * Using the splat operator on ranges converts them into arrays, so the available font sizes is generated from `[*1..12,*(14..28).step(2),36,48,72,*(80..1630).step(10),1638]`. Which is a flat array containing the values from each of the flattened elements: + `1..12` is a range from 1 to 12 (inclusive). The splat operator turns it into the values `1, 2, 3, ..., 11, 12`. + `(14..28).step(2)` is an enumerator for the given range, where each step goes up by 2. The splat operator turns it into the values `14, 16, 18, ..., 26, 28`. + The individual values (`36, 48, 72, 1638`) are all concatenated in their position into the great font-size array. * I used the `inject`(/`reduce`) method, which uses each element of the input array, while reducing them down into a 'memo' variable (as ruby puts it). I initialise this to 11, and the body of each inject iteration is to set this memo variable to the result of adding the current element of the input to the current memo value, and then clamping it between 0 and 180. All hail the splat operator! [Answer] # PHP, 116 bytes first generates the size index (from 1 to 180 inclusive), then maps that to the point size and prints the result. ``` for($s=11;$d=$argv[++$i];$s=min($s+$d,180)?:1);echo$s>12?$s>20?$s>23?$s*10-160-2*($s>179):24+(12<<$s-21):$s*2-12:$s; ``` takes `+N` and `-1` from command line arguments. (`-N` is also accepted; just take care that the size does not hop below zero!) Run with `-nr`. [Answer] # [Perl 5](https://www.perl.org/), ~~123~~ 106 bytes ``` @a=(1..12,map$_*2,7..14,18,24,36,map$_*5,8..163,163.8);$i=10;$\=$a[$i=($"=$i+$_)<0?0:$">179?179:$"]for@F}{ ``` [Try it online!](https://tio.run/##LYhBCsIwEAC/ImUPrW5CNm3aaI3tyZsvUCk5KATUhOpN/LprDh4GZiZd5pthHr0rSUrSePcJpqXGLleDZFE3WLf/bdDm3daYkbbqIThSPZwc@GP2EgoHYQVTtVWD2kCxo249ZLKer3Ee9583syBa0DemV4iPJ4uDkYoUC59@ "Perl 5 – Try It Online") Input format: ``` 32 -32 12 4 -2 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~157~~ 154 bytes -3 bytes thanks to ceilingcat. Takes a string of `+` (step up) and non-`+` (step down). Returns the final font size. ``` n,d;f(char*s){for(n=11;*s;n=n>28&n<81?index("\34$0HP",n-d)[2*d-1]:n-d+((n>1&n<29)+(n>12&n<29)+(n>80&n<1639)*8+(n>80&n<1631)*2)*(2*d-1))n+=d=*s++==43;s=n;} ``` [Try it online!](https://tio.run/##bVFNb@IwED2TXzG1Nht/BdkhoqFZ02uPewe0Qo6hqDCgOF1VqvjtrB0@itT1IZp5z@/5zcTma2tPJ5RNvaL2ddlyzz5X@5ai0brmvkaD06L6ib8q/bzBxn1QMh@VP9TLbyIxb9is4E2uF0@hFpTiVIerxYSJWBZfdaVCrcejCePVfa8ZLxinvQljKExjuBfCmHJUe4P18fR3v2lg3WcD7iVssAP3cXC2cw1LPpNBBFrn37cdGFhRz@pkkAwObcBXlKQW0rKBWfgsYE7SIfepn5M5EnlVPZibITxD9pDBE2SQXXl5YyWMlQwRfNduHYaXYBqQoCHD4ZAEFSHh8WOSnMPu3v607uBpDIgSetC@9plb1723CDu3866jdrnd7i1FEKAlaBbvSsCzV1TvlhukvbA38bNSTcaLfs41JUKIXIgwj67i7D0Su/LS5bFRN@ruBKK6EvnXiXjx/X70GY3P6/WX/YZtkNRH5jqtflQSMpExdsnnZfjP6r@yPPV3ykKpi/TOTX1zg2AXBz2e/gE "C (gcc) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 98 bytes ``` a=({1..12} {14..28..2} 36 48 72 {8..163}0 1638) r=11 for i;((r+=i,r=(r>$#a)?$#a:(r?r:1))) <<<$a[r] ``` [Try it online!](https://tio.run/##VY7dCsIwDIXv@xQBe9Go@8k2ZpmrexBRmOB0Fyp0uxDLnr2GOdEl5JDk45C8uqtvFCpfG@UoDCkZwFEWhonmGiDNIdOwScDxTHk6xMCqUVhDJJqHhXarlF2Zdm2Nsju5qLFiKZStbEGIKMqylPXeHjwKcWov/bnrp1s6HvC3km5qo2gZERPRAEFAMCYPcuLwjQXc6ieoz0N/fHSNnFHMJJDHuZed7Z2dOIfjMYaJfwM "Zsh – Try It Online") Iterate through the arguments, clamping our index between `1` and `$#a` (length of `$a`). ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/6249/edit) Write some code that causes a BSOD or kernel panic! Rules: * On Windows, you must cause a BugCheck (Blue Screen of Death), on Linux (or other \*nix systems) you must cause a kernel panic. * **Must not damage the system (i.e. it should work on reboot)** * Kernel-mode drivers are allowed. * State your OS and version information. * Explain how the crash is caused. * It's not against the rules to use tools that are specifically designed to cause a crash, but doing so isn't very creative! * Highest upvotes wins. [Answer] # Bash, x86 Linux 2.6.20 kernel **Warning: the following command may cause permanent damage to your system.** ``` cat /dev/urandom > /dev/mem ``` Will output the following ([try here](http://bellard.org/jslinux/)). After this, the script hangs. ``` /var/root # cat /dev/urandom > /dev/mem BUG: unable to handle kernel paging request at virtual address 474e82a5 printing eip: c01450c4 *pde = 00000000 Oops: 0000 [#1] CPU: 0 EIP: 0060:[<c01450c4>] Not tainted VLI EFLAGS: 00000082 (2.6.20 #12) EIP is at free_block+0x54/0xf0 eax: 00000000 ebx: 474e82a1 ecx: c00745c8 edx: c0005e80 esi: c0070ce0 edi: c002c1a0 ebp: 00000000 esp: c0085eec ds: 007b es: 007b ss: 0068 Process events/0 (pid: 3, ti=c0084000 task=c0094030 task.ti=c0084000) Stack: c0076410 00000002 c0051db0 c0051db0 c0051da0 00000002 c002c1a0 c01457dd 00000000 c0070ce0 c002c1a0 c0091840 c0145800 c0145870 00000000 00000000 c02cb2a0 c02cb2a0 00000296 c011dd27 c003fab0 c0094030 c009413c 00047e6c Call Trace: [<c01457dd>] drain_array+0x7d/0xa0 [<c0145800>] cache_reap+0x0/0x110 [<c0145870>] cache_reap+0x70/0x110 [<c011dd27>] run_workqueue+0x67/0x130 [<c011df17>] worker_thread+0x127/0x140 [<c010c7d0>] default_wake_function+0x0/0x10 [<c010c817>] __wake_up_common+0x37/0x70 [<c010c7d0>] default_wake_function+0x0/0x10 [<c011ddf0>] worker_thread+0x0/0x140 [<c0120d94>] kthread+0x94/0xc0 [<c0120d00>] kthread+0x0/0xc0 [<c0102ee7>] kernel_thread_helper+0x7/0x10 ======================= Code: 04 0f 8d 8f 00 00 00 8b 44 24 08 8b 0c a8 8d 91 00 00 00 40 c1 ea 0c c1 e2 ``` Here is another exception found with the same command: ``` /dev # cat urandom > mem ------------[ cut here ]------------ Kernel BUG at c014514c [verbose debug info unavailable] invalid opcode: 0000 [#1] CPU: 0 EIP: 0060:[<c014514c>] Not tainted VLI EFLAGS: 00000046 (2.6.20 #12) EIP is at free_block+0xdc/0xf0 eax: 1608347b ebx: c009b010 ecx: c003f508 edx: c00057e0 esi: c009b000 edi: c002cd40 ebp: 00000000 esp: c0085eec ds: 007b es: 007b ss: 0068 Process events/0 (pid: 3, ti=c0084000 task=c0094030 task.ti=c0084000) Stack: c009b010 00000004 c009b010 c009b010 c009b000 00000004 c002cd40 c01457dd 00000000 c02ddf20 c002cd40 c0091840 c0145800 c0145870 00000000 00000000 c02cb2a0 c02cb2a0 00000296 c011dd27 c005c5a0 c0094030 c009413c 000409ed ``` [Answer] ## C, 16 chars, for P5 x86 ``` main=-926478352; ``` Remember the [F00F bug](http://en.wikipedia.org/wiki/Pentium_F00F_bug) everyone? I helped lock up a machine or two back in the day with this little program. (Yes, I've been golfing for that long.) Granted, it's not quite what was asked for, and it only works on old steppings of the P5 Pentium chips. But in its favor, it's cross-platform, working on both Linux *and* Windows! [Answer] # QBASIC, 38 Characters ``` DEF SEG=0:FOR I=0 TO 4^8:POKE I,1:NEXT ``` Not sure how you would define a BSOD or Kernel panic in DOS, but this is probably pretty close. When run the screen just goes blank, and the machine responds to nothing, not even Ctrl+Alt+Delete. You have to restart with a hard reset or power cycle to get the machine going again. This is running on DOS 6.22 under VirtualBox. Not sure exactly why it causes the system to crash, but, basically the program is writing (POKE) to memory that it has no business writing to. [Answer] ## sh (in JSLinux) Linux gives the init process [special protection against signals](https://unix.stackexchange.com/questions/7441/can-root-kill-init-process). However, I noticed that in JSLinux, `/sbin/init` is a shell script that executes other binaries (most symlinked to `/bin/busybox`). This "infinite" while loop restarts `sh` as necessary: ``` while /bin/true; do setsid sh -c 'exec sh </dev/ttyS0 >/dev/ttyS0 2>&1' done ``` However, what if `/bin/true` does not always return an exit code of 0? `/bin` is on the read-only root file system, yet Linux lets us change that using "bind" mounts: ``` cp -R /bin /tmp/boom rm /tmp/boom/true printf '#!/bin/sh\nexec [ $PPID != 1 ]' > /tmp/boom/true chmod 755 /tmp/boom/true mount -o bind /tmp/boom /bin killall -9 sh ``` And we get: ``` /var/root # ./boom.sh Killed Kernel panic - not syncing: Attempted to kill init! ``` [Answer] ## Bash on Linux, 27 chars ``` echo c>/proc/sysrq-trigger ``` ## Or if you have sudo permissions: ``` echo c|sudo tee /proc/sysrq-trigger ``` [Answer] ## [GTB](http://timtechsoftware.com/gtb "GTB"), 13 characters Executed from a TI-84 calculator ``` :"+"→_[_+_→_] ``` If most of the RAM is free, it will crash with `ERR:MEMORY` Otherwise, the calculator's RAM is so clogged that it turns off and clears it besides. > > Great example of a "calculator virus" > > > [Answer] # Batch (Windows 98) ``` \con\con ``` This is actually a [BSOD Easter Egg](https://www.youtube.com/watch?v=_B7B2h_EdXc) of Windows 98... [Answer] ``` :(){ :|:& };: ``` In bash shell, I am not so sure if this counts here, but if you let it run long enough CPU overheats and system crashes, and it does reboots safely without harm, of course if you do it all the time there will be some system damage. [Answer] ## Ruby (run as root), 36 or 40 chars (depending on matches for `/p*/s*r`) See <http://www.kernel.org/doc/Documentation/sysrq.txt> and search for `'c'` (including quotes!) to see why it works. ``` open(Dir['/p*/s*r'][0],?a){|f|f<<?c} ``` EDIT: Longer version that works if you have other things matching `/p*/s*r` ``` open('/proc/sysrq-trigger',?a){|f|f<<?c} ``` EDIT 2: Intentionally overkill. [Answer] ``` get-process | stop-process -force ``` in powershell [Answer] ## Linux bash ``` cat /dev/zero > /dev/mem ``` Clear the entire memory and cause a infinite kernel panic. Try it [here](http://bellard.org/jslinux/). [Answer] # Batch, 15 bytes ``` :A start goto A ``` Merely overflows the memory in linear time by starting up `cmd.exe` hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds of times. There's a deadlier (but probably non-competing) 24-byte program that starts up *itself* over and over again, thus overflowing the memory in logarithmic time (i.e upgrading your RAM doesn't delay the crash). Suppose the below code is located in `C:\a.bat`: ``` :A start C:\a.bat goto A ``` . Honestly I'm afraid to try those out. ]
[Question] [ ## Challenge You need to generate a program or function that takes in a positive integer N, calculates the first N terms of the Fibonacci sequence in binary, concatenates it into a single binary number, converts that number back to decimal, and then outputs the decimal as an integer. For example ``` 1 -> [0] -> 0 to decimal outputs 0 3 -> [0, 1, 1] -> 011 to decimal outputs 3 4 -> [0, 1, 1, 10] -> 01110 to decimal outputs 14 ``` You do not need to output the `->`, just the number (e.g. if the user types `4`, just output `14`). The arrows are just to help explain what the program must do. ## Test cases ``` 1 -> 0 2 -> 1 3 -> 3 4 -> 14 5 -> 59 6 -> 477 7 -> 7640 8 -> 122253 9 -> 3912117 10 -> 250375522 11 -> 16024033463 12 -> 2051076283353 13 -> 525075528538512 14 -> 134419335305859305 15 -> 68822699676599964537 16 -> 70474444468838363686498 17 -> 72165831136090484414974939 18 -> 147795622166713312081868676669 19 -> 605370868394857726287334099638808 20 -> 4959198153890674493745840944241119317 ``` The program must be able to output up to the limit of the language in use. No lookup tables or [common workarounds](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the shortest number of bytes wins! [Answer] # [Python](https://docs.python.org/), 64 bytes ``` f=lambda n,a=0,b=1,r=0:n and f(n-1,b,a+b,r<<len(bin(a))-2|a)or r ``` [Try it online!](https://tio.run/##DcxBDoMgEAXQdXuK2QnpkAjdEeldhigtif2aiRtjPTt185Zv3bfPgmdrJc3yzaMQWFLPOXnW1EeQYKRi4DxnlkdmHYZ5gskVRqx14Sd2UdJWLkEVpIL3ZDxT8Dbeb6tWbKZ0B2I4yb3ouDZ7drb9AQ "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḶÆḞBẎḄ ``` **[Try it online!](https://tio.run/##ARoA5f9qZWxsef//4bi2w4bhuJ5C4bqO4biE////NA "Jelly – Try It Online")** ### How? ``` ḶÆḞBẎḄ - Link: integer, n Ḷ - lowered range -> [0,1,2,3,4,5,...,n] ÆḞ - Fibonacci (vectorises) -> [0,1,1,2,3,5...,F(n)] B - to binary (vectorises) -> [[0],[1],[1],[1,0],[1,1],[1,0,1],...,B(F(n))] Ẏ - tighten -> [0,1,1,1,0,1,1,1,0,1,...,B(F(n))[0],B(F(n))[1],...] Ḅ - from binary -> answer ``` [Answer] # [Python 3.6](https://docs.python.org/3/), 61 bytes ``` f=lambda n,a=0,b=1:n and int(f'{a:b}{f(n-1,b,a+b)*2:b}',2)//2 ``` [Try it online!](https://tio.run/##LYxBCsIwEADP@oq9JatbatZbIP5llxoVdFtCL6Xk7WkLXoeZmZb5Pdq9tZy@8tNBwEjSjTSFaCA2wMdmn90qUeuavXWBlOSqeOGdOGLse255LGC7CkXs9fSBgAPG82kq/9wiV@gecCywOmwb "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ḋṁḋ↑Θİf ``` [Try it online!](https://tio.run/##yygtzv7//@GO7oc7G4Hko7aJ52Yc2ZD2//9/IwMA "Husk – Try It Online") ### Explanation ``` ḋṁḋ↑Θİf 4 İf The Fibonacci numbers [1,1,2,3,5,8..] Θ Prepends 0 [0,1,1,2,3,5..] ↑ Take n elements from list [0,1,1,2] ḋ Convert to binary digits [[0],[1],[1],[1,0]] ṁ Map function then concat [0,1,1,1,0] ḋ Convert from base 2 14 ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 397 bytes ``` >,[<++++++[->--------<]>>[->++++++++++<]>[-<+>]<<[->+<],]>+[-<<+>>[-[->+<]<<[->+>+<<]<[->+>+<<]>[-<+>]>>[-<<+>>]>]]<<[->+>>>>>+<<<<<<]>[-<+>]>+>>+>>>+<[[->-[<<]>]>[[-]<<<<<<<[->>[-<+>>+<]>[-<+>]<<<]<[->+>>>>>+<<<<<<]>[-<+>]>[-<+>]>[->>[-<+<<+>>>]<[->+<]<]>+>[-]>>+>]<<<<<[[->++>+>++<<<]>[-<+>]<<]>>>]>[-]<<<[-]<<[-]<<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>]<+[->++++++[-<++++++++>]<.<<<+] ``` Well, that was fun! Takes ASCII input (e.g. `11`), outputs result in ASCII. Note: to try this online, make sure you set the cell size to 32 bits (on the right side of the webpage). **If you do not enter an input, your browser might crash.** The interpreter cannot handle input of `11` and higher because it only supports up to 32 bits. [Try it on copy.sh](https://copy.sh/brainfuck/?c=PixbPCsrKysrK1stPi0tLS0tLS0tPF0-PlstPisrKysrKysrKys8XT5bLTwrPl08PFstPis8XSxdPitbLTw8Kz4-Wy1bLT4rPF08PFstPis-Kzw8XTxbLT4rPis8PF0-Wy08Kz5dPj5bLTw8Kz4-XT5dXTw8Wy0-Kz4-Pj4-Kzw8PDw8PF0-Wy08Kz5dPis-Pis-Pj4rPFtbLT4tWzw8XT5dPltbLV08PDw8PDw8Wy0-PlstPCs-Pis8XT5bLTwrPl08PDxdPFstPis-Pj4-Pis8PDw8PDxdPlstPCs-XT5bLTwrPl0-Wy0-PlstPCs8PCs-Pj5dPFstPis8XTxdPis-Wy1dPj4rPl08PDw8PFtbLT4rKz4rPisrPDw8XT5bLTwrPl08PF0-Pj5dPlstXTw8PFstXTw8Wy1dPDwtPls-KysrKysrKysrKzxbLT4tWz4rPj5dPlsrWy08Kz5dPis-Pl08PDw8PF0-Pj5dPCtbLT4rKysrKytbLTwrKysrKysrKz5dPC48PDwrXQ$$) ## Explanation ``` >,[<++++++[->--------<]>>[->++++++++++<]>[-<+>]<<[->+<],]>+ ``` Get decimal input and add one (to mitigate off-by-one) ``` [-<<+>>[-[->+<]<<[->+>+<<]<[->+>+<<]>[-<+>]>>[-<<+>>]>]] ``` Generate fibonacci numbers on the tape. ``` <<[->+>>>>>+<<<<<<]>[-<+>]>+>>+>>>+< ``` Set up for the incoming binary concatenation loop --- So the cells contain the value, starting from the first position, ``` 1 | 0 | 1 | 1 | 2 | 3 | 5 | ... | f_n | 0 | 1 | 0 | 1 | 0 | f_n | 1 | 0 | 0 | 0... ``` Look at these cells: ``` f_n | 0 | 1 | 0 | 1 | 0 | f_n | 1 ``` I'll label this: ``` num | sum | cat | 0 | pow | 0 | num | pow ``` `pow` is there to find the maximal power of 2 that is strictly greater than `num`. `sum` is the concatenation of numbers so far. `cat` is the power of 2 that I would need to multiply the `num` in order to concatenate `num` in front of the `sum` (so I would be able to simply add). --- ``` [[->-[<<]>]> ``` **Loop: Check whether `f_n` is strictly less than `pow`.** **Truthy:** ``` [[-]<<<<<<<[->>[-<+>>+<]>[-<+>]<<<]<[->+>>>>>+<<<<<<]>[-<+>]>[-<+>]>[->>[-<+<<+>>>]<[->+<]<]>+>[-]>>+>] ``` Zero out junk. Then, add `num` \* `cat` to `sum`. Next, load the next Fibonacci number (= `f_(n-1)`; if it doesn't exist, exit loop) and set `cat` to `cat` \* `pow`. Prepare for next loop (zero out more junk, shift scope by one). **Falsey:** ``` <<<<<[[->++>+>++<<<]>[-<+>]<<] ``` Set `pow` to 2 \* `pow`, restore `num`. ``` ] ``` Repeat until there is no Fibonacci number left. --- ``` >[-]<<<[-]<<[-]<<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>]<+[->++++++[-<++++++++>]<.<<<+] ``` Clean garbage. Take each digit of the resulting number and output each (in ascii). [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ÆMgX ¤Ã¬Í ``` [Run it](https://ethproductions.github.io/japt/?v=1.4.5&code=xk1nWCCkw6zN&input=NA==) ## Explanation: ``` ÆMgX ¤Ã¬Í Æ Ã | Iterate X through the range [0...Input] MgX | Xth Fibonacci number ¤ | Binary ¬ | Join into a string Í | Convert into a base-2 number ``` [Answer] # Pyth, 22 bytes ``` JU2VQ=+Js>2J)is.BM<JQ2 ``` [Try it here](http://pyth.herokuapp.com/?code=JU2VQ%3D%2BJs%3E2J%29is.BM%3CJQ2&input=32&debug=0) ### Explanation ``` JU2VQ=+Js>2J)is.BM<JQ2 JU2 Set J = [0, 1]. VQ ) <Input> times... =+Js>2J ... add the last 2 elements of J and put that in J. <JQ Take the first <input> elements... .BM ... convert each to binary... s ... concatenate them... i 2 ... and convert back to decimal. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes ``` {:2([~] (0,1,*+*...*)[^$_]>>.base(2))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2spII7ouVkHDQMdQR0tbS09PT0szOk4lPtbOTi8psThVw0hTs/Z/cWKlQpqGSrymQlp@kYKhnp6hgfV/AA "Perl 6 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 70 65 58 57 55 bytes * thanks to Shaggy for reducing 2 bytes ('0b+C-0 to '0b'+C) ``` f=(n,a=C=0,b=1)=>--n?f(n,b,a+b,C+=b.toString(2)):'0b'+C ``` [Try it online!](https://tio.run/##ZZBLbsMwDET3vUgs2A5EUtSngNKFj9ATWGkcpAjkIjF6fYfqrtJGBB6pGXK@59/5eX7cfrYxr1@XfV9il4c5TlEPKYKKp3HMH4uwNMx9GqY@puO2fm6PW752qNT7QadDP@3nNT/X@@V4X6/d0snHqNXbf4gCoYYkkGpoyqSpKQvlUFMr1DhXYyfYWdMs4Ys0InJjGsomARCgEQMtPWRNjhmx6ZZrwWo0msjYRhjK4agZtLPoiVprKCmwGBR9z@QZWpe/UMgYCEVCs@cgbzNWUrLeI9oQrLMcpBgmp/YX "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` LÅfbJC ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f53BrWpKX8///xgA "05AB1E – Try It Online") --- 1-indexed. [Answer] # J, 36 Bytes ``` 3 :'#.;<@#:"0]2}.(,{:+_2&{)^:y _1 1' ``` ### Explanation: ``` 3 :'#.;<@#:"0]2}.(,{:+_2&{)^:y _1 1' | Explicit function (,{:+_2&{)^:y _1 1 | Make n fibonacci numbers, with _1 1 leading 2}. | Drop the _1 1 <@#:"0] | Convert each item to binary and box ; | Unbox and join #. | Convert back from binary ``` [Answer] # x86, ~~37~~ ~~22~~ 21 bytes **Changelog** * -13 by using [`bsr`](http://www.felixcloutier.com/x86/BSR.html). Thanks Peter Cordes! * -2 by [zeroing registers with `mul`](https://codegolf.stackexchange.com/a/147775/17360). * -1 by using a while loop instead of `loop` and `push`/`pop` `ecx` (credit Peter Cordes). Input in `edi`, output in `edx`. ``` .section .text .globl main main: mov $5, %edi # n = 5 start: dec %edi # Adjust loop count xor %ebx, %ebx # b = 0 mul %ebx # a = result = 0 inc %ebx # b = 1 fib: add %ebx, %eax # a += b xchg %eax, %ebx # swap a,b bsr %eax, %ecx # c = (bits of a) - 1 inc %ecx # c += 1 sal %cl, %edx # result >>= c add %eax, %edx # result += a dec %edi # n--; do while(n) jnz fib ret ``` Objdump: ``` 00000005 <start>: 5: 4f dec %edi 6: 31 db xor %ebx,%ebx 8: f7 e3 mul %ebx a: 43 inc %ebx 0000000b <fib>: b: 01 d8 add %ebx,%eax d: 93 xchg %eax,%ebx e: 0f bd c8 bsr %eax,%ecx 11: 41 inc %ecx 12: d3 e2 shl %cl,%edx 14: 01 c2 add %eax,%edx 16: 4f dec %edi 17: 75 f2 jne b <fib> 19: c3 ret ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~26~~ 22 bytes *4 bytes saved thanks to @H.PWiz* ``` {2⊥∊2∘⊥⍣¯1¨1∧+∘÷\~⍵↑1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rqo0ddSx91dBk96pgBYvUuPrTe8NAKw0cdy7WBQoe3x9Q96t36qG2iYS1Qg8KhFY96NxsaAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 89 76 75 bytes ``` f=0:scanl(+)1f foldr1(\x y->y+x*2*2^floor(logBase 2.read.show$y)).(`take`f) ``` Ungolfed version: ``` import Data.Bits fib = 0:scanl (+) 1 fib catInt :: Integer -> Integer -> Integer catInt x y = x' + y where position = floor $ succ $ logBase 2 $ realToFrac y x' = shift x position answer :: Integer -> Integer answer n = foldr1 catInt fib' where fib' = take n fib ``` [Answer] # Pyth, 27 bytes ``` JU2V-Q2=aJ+eJ@J_2)is.BM<JQ2 ``` [**Test suite**](https://pyth.herokuapp.com/?code=JU2V-Q2%3DaJ%2BeJ%40J_2%29is.BM%3CJQ2&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0) Python 3 translation: ``` Q=eval(input()) J=list(range(2)) for i in range(Q-2): J.append(J[-1]+J[-2]) print(int(''.join(map("{0:b}".format,J[:Q])),2)) ``` --- ## ~~37 bytes~~ ``` J[Z1)W<lJQ=aJ+eJ@J_2)Ig1QZ.?ijkm.BdJ2 ``` **[Test suite](https://pyth.herokuapp.com/?code=J%5BZ1%29W%3ClJQ%3DaJ%2BeJ%40J_2%29Ig1QZ.%3Fijkm.BdJ2&test_suite=1&test_suite_input=1%0A3%0A4%0A10%0A32&debug=0)** Python 3 translation: ``` Q=eval(input()) J=[0,1] while len(J)<Q: J.append(J[-1]+J[-2]) if 1>=Q: print(0) else: print(int(''.join(map("{0:b}".format,J)),2)) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 59 bytes ``` n->fromdigits(concat([binary(fibonacci(i))|i<-[0..n-1]]),2) ``` [Try it online!](https://tio.run/##DcwxDoMwDEDRq1hMthSjUlWdWi6CGEIqIw84kZsFibuHLH94wy/RlffSBL7QjGfxfPx01/rHlC3FisumFv1E0S1bTElRiS798PIYR@NpXSk8qUl2tD6ZArxfAYqr1Q4D8NwjaETUbg "Pari/GP – Try It Online") [Answer] # APL+WIN, 55 bytes Prompts for screen input of integer. ``` v←b←0 1⋄⍎∊(⎕-2)⍴⊂'v←v,c←+/¯2↑v⋄b←b,((1+⌊2⍟c)⍴2)⊤c⋄'⋄2⊥b ``` APL+WIN's maximum integer precision is 17 and integer limit is of the order of 10E300 therefore the maximum input number is 55 and the result is: 1.2492739026634838E300 [Answer] # [Python 3](https://docs.python.org/3/), 94 bytes ``` f=lambda n,a=[0,1]:n>len(a)and f(n,a+[sum(a[-2:])])or int(''.join(bin(v)[2:]for v in a[:n]),2) ``` **[Try it online!](https://tio.run/##FcpLDoMwDEXRrWSGraYVn44iwUasDIwgKggcBBSpq3fN4E3uedvv/GRpVFO78NoP7MRzS6WvYpBuGQUYWQaXwPqDju8KTM86RIyYdzfJCUXxmvMk0NsuJLNkcpk5piARfY267fc1wRtR9Q8 "Python 3 – Try It Online")** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ḶÆḞBFḄ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm2H2x7umOfk9nBHy////00A "Jelly – Try It Online") `Ḷ`owered range -> *n*th `ÆḞ`ibonacci number -> from dec to `B`inary -> `F`latten -> from `Ḅ`inary to dec [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` 0li:"yy+]xx&h"@B]&hXB ``` [Try it online!](https://tio.run/##y00syfn/3yAn00qpslI7tqJCLUPJwSlWLSPC6f9/QwMA "MATL – Try It Online") ### Explanation ``` 0l % Push 0, then 1 (initial terms of the Fibonacci sequence) i:" % Do n times, where n is the input yy+ % Duplicate top two numbers and push their sum ] % End xx % Delete the last two results. The stack now contains the % first n Fibonacci numbers, starting at 0 &h % Concatenate all numbers into a row vector " % For each @ % Push current number B % Convert to binary. Gives a vector of 0 and 1 ] % End &h % Concatenate all vectors into a row vector XB % Convert from binary to decimal. Implicitly display ``` [Answer] # [Jotlin](https://github.com/jrtapsell/jotlin), 59 bytes ``` g(l(0,1)){l(a.sum(),a[0])}.take(this).j(""){a[0].s(2)}.i(2) ``` ## Test Program ``` data class Test(val input: Int, val output: Long) val tests = listOf( Test(1, 0), Test(2, 1), Test(3, 3), Test(4, 14), Test(5, 59), Test(6, 477), Test(7, 7640), Test(8, 122253), Test(9, 3912117), Test(10, 250375522) ) fun Int.r() = g(l(0,1)){l(a.sum(),a[0])}.take(this).j(""){a[0].s(2)}.i(2) fun main(args: Array<String>) { for (r in tests) { println("${r.input.r()} vs ${r.output}") } } ``` It supports up to 10, changing `.i(2)` for `.toLong(2)` would support up to 14 if needed [Answer] # [J](http://jsoftware.com/), 25 bytes ``` 2(#.;)<@#:@(1#.<:!|.)\@i. ``` [Try it online!](https://tio.run/##FcqhDoAgFAXQzldcIcDb2BsSn@j4EJuTicVgMei3o4bTzt7KiVEQ8GnRGR4oZSPZ9YaTdDfTnCs3Upphy18tPB5BOZVal@2A81x0IEyCyojhai8 "J – Try It Online") ## Explanation ``` 2(#.;)<@#:@(1#.<:!|.)\@i. Input: n i. Range [0, n) \@ For each prefix |. Reverse ! Binomial coefficient (vectorized) <: Decrement 1#. Sum #: Convert to binary < Box ; Link. Join the contents in each box 2 #. Convert to decimal from base 2 ``` [Answer] # [Python 3](https://docs.python.org/3/), 86 bytes ``` def f(N): a,b,l=0,1,'' for _ in range(N):l+=format(a,'b');a,b=b,a+b return int(l,2) ``` [Try it online!](https://tio.run/##Rc0xDgIhEIXhfk8xDRkmOyaCnQaP4BUMBFATnN0QLDw9QmX78v15@7c9Nzn1HlOGrG90XsBz4OKObBhxgbxVuMNLoHp5pCnK6sb49k17xoB0GYEL7NewQE3tU2Xwpgtb6rOWf23Ymnmx1ylQ2QiHK6iIoLRw1kJE/Qc) [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 113 bytes ``` D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p D,k,@,¿1=,1,bM¿ D,g,@,¿1_,1_001${f},1¿{k} D,w,@,BBbR D,l,@,ßR€gp€w@0b]@¦+VcG2$Bb ``` [Try it online!](https://tio.run/##JY5BaoQwFIbXySlEAoUawThdtVhSKwilXVSKdDPIaFQyYzWgM0NH3PQisyh01TsIzk16kKbPThbh53v/93grIZTSOqAF5fAuaUzcwAqZJe6UUp5DnlVfDAoHdEM5nUbmUUbTp2kEUp5JQlniOIxAj7Jp7DcDzPYw8/00glhBPB2jn4/vUsG350665NOXFWehS/xU3xgvedvJusRQ3tb5bjUbGJkXpuDr3UzXjazhPoCwoD93Boy4SB8XJMFo4d6fjq@g2LeGCTzm4cPsHeg1OK4TGSLe/ssVRv4yJH6G0fTZz3uHWuur30Z1sqlbbdvyTVUykx3EVuWZLN69wx8 "Add++ – Try It Online") [Answer] ## PHP, 124 Bytes [Try it online!](https://tio.run/##LczLCsIwEIXhV8lioDO0WCu6itF3SZrQgExiL7gIffY4Sjdn8cP58pTr/Zllw8ZujYlVQOAOojl3YE3TUFHxlx4QqYA9mdE7GxnntPGIOX0Ql/e84o3agfqLPKk/ApE@sHYQjPTuX4sv3k1JCSEQ/uteA15J1y8) So I was looking for a way to output fibonacci numbers using the series, until I found [this](https://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding). It turns out you can calculate the fibonacci series via rounding, so I tried the challenge with a recursive function. I found the approach of "rounding" really interesting, also a professor showed me this a while ago. **Code** ``` function f($n,$i=0,$b=''){ if($n>$i){$b.= decbin(round(pow((sqrt(5)+1)/2,$i)/sqrt(5)));f($n,$i+1,$b);}else{echo bindec($b);}} ``` **Explanation** ``` function f($n,$i=0,$b=''){ #the function starts with $i=0, our nth-fib number if($n>$i){ #it stops once $n (the input) = the nth-fib $b.=decbin( #decbin returns an integer as bin, concatenates round(pow((sqrt(5)+1)/2,$i)/sqrt(5)) #the formula, basically roundign the expression ); #it returns the (in this case) $i-th fib-number f($n,$i+1,$b); #function is called again for the next index }else{ #and the current string for fibonacci echo bindec($b); #"echo" the result, bindec returns the base 10 #value of a base 2 number } } ``` Also check [this stackoverflow post](https://stackoverflow.com/questions/15600041/php-fibonacci-sequence) the best answer refers to the same article on Wikipedia. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü1∞╓♪εw≤+ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=8131ecd60dee77f32b&i=1%0A%0A2%0A%0A3%0A%0A4%0A%0A5%0A%0A6%0A%0A7%0A%0A8%0A%0A9%0A%0A10%0A%0A11%0A%0A12%0A%0A13%0A%0A14%0A%0A15%0A%0A16%0A%0A17%0A%0A18%0A%0A19%0A%0A20%0A&a=1&m=1) ## Unpacked (10 bytes) and explanation: ``` vr{|5|Bm|B v Decrement integer from input. Stax's Fibonacci sequence starts with 1 :( r Integer range [0..n). { m Map a block over each value in an array. |5 Push nth Fibonacci number. |B Convert to binary. |B Implicit concatenate. Convert from binary. Implicit print. ``` [Answer] # [Julia 0.6](http://julialang.org/), 65 bytes ``` f(n)=n<2?n:f(n-1)+f(n-2) n->parse(BigInt,prod(bin.(f.(0:n-1))),2) ``` [Try it online!](https://tio.run/##FcqxCoMwFEbhuXmKIg73UhXN0CE0Frr1HbooJuEW@Q1p@vxRp3OG7/tfZbqXYGcXBMUT2OKhnzDHtgPfzmhWaMc4pZ@jl4Q3chPTttAs6Mh31JuTMjeai8Oi/JauYgeje3WJSZBXUFXLJ9cUSJgrVgcrOw "Julia 0.6 – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `project-euler.025`, 37 bytes ``` [ iota [ fib >bin ] map-concat bin> ] ``` [Try it online!](https://tio.run/##Rcw9DsIwDEDhvafwAWhUKrGA1BWxsCCmKINruRB@kuC4Epw@BBhYnz69CUmjlONht9@u4Y56hsyPmQNxhiTxwqQtzzcW0/WrLzAJJbP8neGnCn44q76S@KA/KBhOdbNpmr4Du1yMrljwUREsTH6EYfQBXLWppRgIFWoYwJVaICvS1ZQ3 "Factor – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 44 bits1, 5.5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` ʁ∆FbfB ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+PSIsIiIsIsqB4oiGRmJmQiIsIiIsIjEgLT4gMFxuMiAtPiAxXG4zIC0+IDNcbjQgLT4gMTRcbjUgLT4gNTlcbjYgLT4gNDc3XG43IC0+IDc2NDBcbjggLT4gMTIyMjUzXG45IC0+IDM5MTIxMTdcbjEwIC0+IDI1MDM3NTUyMlxuMTEgLT4gMTYwMjQwMzM0NjNcbjEyIC0+IDIwNTEwNzYyODMzNTNcbjEzIC0+IDUyNTA3NTUyODUzODUxMlxuMTQgLT4gMTM0NDE5MzM1MzA1ODU5MzA1XG4xNSAtPiA2ODgyMjY5OTY3NjU5OTk2NDUzN1xuMTYgLT4gNzA0NzQ0NDQ0Njg4MzgzNjM2ODY0OThcbjE3IC0+IDcyMTY1ODMxMTM2MDkwNDg0NDE0OTc0OTM5XG4xOCAtPiAxNDc3OTU2MjIxNjY3MTMzMTIwODE4Njg2NzY2NjlcbjE5IC0+IDYwNTM3MDg2ODM5NDg1NzcyNjI4NzMzNDA5OTYzODgwOFxuMjAgLT4gNDk1OTE5ODE1Mzg5MDY3NDQ5Mzc0NTg0MDk0NDI0MTExOTMxNyJd) ## Explained ``` ʁ∆FbfB ʁ # range [0, input) ∆F # 0-indexed fibonacci number of each bf # convert each to binary and flatten the list B # convert that from binary ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 61 bytes ``` ->n,a=0,b=1,s=""{s+="%b"%a;a,b=b,a+b;(n-=1)>0?redo:s.to_i(2)} ``` [Try it online!](https://tio.run/##JVDLTtxAEDzDV1hGaEEYNP2cHtAsH5JEyIZFyQUi1hwi47/IIQe@jh/ZdM/6MFPuqequ6rf36c/huR6uty/DWNMwVRj2te@X/VXtz6f@fLwbvTgN49V0d/FyXeFym@7fdk@vt/ub@fXh1wVerofl9AS6uu3ScHqCAcABBSAH3CrsSAJJcaSBOGeHOWBWDrE1KiJKCEvrUAABgggp/lESZRHEqLSpoAk5EbGGCJoBTAIpKxpRawXNjbg4tCZkAq3D0RwxQwlqEpPiZzw1t2qGqKVoVil@sVDz0gLkxJnjcxYZKakpF4v3YyoEFSMA0lQSm0/hkrlQrACOYX0JRRSdqRmIAJOBeZ@sqo3WtqDJ5yavU2GTnNGjZY@c3BKZpZiJbT9cpEAx8IglqdsrlFnMmczIAJ4ztrne7MbHn93yMQ@7j@73@7zv@rPl@dv8o9Zdd99tvj7/brrbuP9t1u/z2TL7WbeBgrX26@E/ "Ruby – Try It Online") ]
[Question] [ Let `n` and `b` be positive integers larger than `1`. Output the distance from `n` to the next power of `b`. For `n=5` and `b=3`, the next power of `3` from `5` is `9` (`3^2 = 9`), so the output is `9 - 5 = 4`. For `n=8` and `b=2`, the next power of `2` from `8` is `16` (`2^4 = 16`), so the output is `16 - 8 = 8`. Note that `n` is a power of `2` in this example. Testcases: ``` n b output 212 2 44 563 5 62 491 5 134 424 3 305 469 8 43 343 7 2058 592 7 1809 289 5 336 694 3 35 324 5 301 2 5 3 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ạæċ ``` A dyadic link taking `n` on the left and `b` on the right and returning the result. **[Try it online!](https://tio.run/##y0rNyan8///hroWHlx3p/v//v7GRyX9TAA "Jelly – Try It Online")** ### How? ``` ạæċ - Link: number n, number b | n,b ∈ ℕ æċ - ceiling n to the next power of b ạ - absolute difference between n and that ``` [Answer] ## x86-64 Assembly ([Windows x64 Calling Convention](https://msdn.microsoft.com/en-us/library/ms235286.aspx)), 14 13 bytes An inefficient (but svelte!) iterative approach (with credit to @Neil for inspiration): ``` HowFarAway PROC 6A 01 push 1 58 pop rax ; temp = 1 Loop: 0F AF C2 imul eax, edx ; temp *= b 39 C8 cmp eax, ecx 72 F9 jb Loop ; keep looping (jump) if temp < n 29 C8 sub eax, ecx ; temp -= n C3 ret ; return temp HowFarAway ENDP ``` The above function takes two integer parameters, `n` (passed in the `ECX` register) and `b` (passed in the `EDX` register), and returns a single integer result (in the `EAX` register). To call it from C, you would use the following prototype: ``` unsigned HowFarAway(unsigned n, unsigned b); ``` This is limited to the range of a 32-bit integer. It can be easily modified to support 64-bit integers by using the full long registers, but it would cost more bytes to encode those instructions. :-) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~39~~ 35 bytes New undefined behavior thanks to Erik ``` f(n,b,i){for(i=b;b<=n;b*=i);n=b-n;} ``` [Try it online!](https://tio.run/##LYhBCsIwEADvfUUoCNmQHGwFD2teojkkq7E5uCmx5FL6bM/RgjAMw5B5ErUWJeugE6wxF5lswHCxjEHZBMg2GMatvXxiSboCTb4oVXHthJhL4iXK/vAWO/cb97pej@6nweko/ZKT3Afofw4OALDbWhtPYzt/OBvyND2@ "C (gcc) – Try It Online") [Answer] # Dyalog APL, 10 bytes *2 bytes saved thanks to @ZacharyT* ``` ⊢-⍨⊣*1+∘⌊⍟ ``` [Try it online!](http://tryapl.org/?a=f%u2190%u22A2-%u2368%u22A3%2A1+%u2218%u230A%u235F%20%u22C4%202%202%205%205%203%20f%208%20212%20563%20491%20424&run) Takes `n` as right argument and `b` as left argument. Calculates `b⌊logbn + 1⌋ - n`. [Answer] # [R](https://www.r-project.org/), ~~38~~ 34 bytes ``` pryr::f({a=b^(0:n)-n;min(a[a>0])}) ``` Anonymous function. Stores all values of b to the power of everything in the range [0,n], subtracts n from each, subsets on positive values, and returns the min. TIO has a non-pryr version, called as `f(n,b)`; this version needs to be called as `f(b,n)`. Saved 4 bytes thanks to Jarko Dubbeldam, who then [outgolfed me.](https://codegolf.stackexchange.com/a/127422/62105) [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTydJszrRNilOw8AqT1M3zzo3M08jMTrRziBWs5aLK03DyNBIx0gTyDA1M9YxBTFMLA0hDCMIZWxkAmT8/w8A "R – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~24~~ 20 bytes *-4 bytes thanks to MickyT* ``` Pwp.I|-.;)^0@O?|uq;< ``` Reads in input like `n,b` Fits on a 2x2x2 cube: ``` P w p . I | - . ; ) ^ 0 @ O ? | u q ; < . . . . ``` ### Explanation: `I|I0` : read the input, push 0 (counter) to the stack `^w` puts the IP to the right place for the loop: * `Pp-` : compute `b^(counter)`, move `n` to top of stack, compute `b^(counter) - n` * `?` : turn left if negative, straight if 0, right if positive + Positive: `O@` : output top of stack (distance) and exit. + Negative : `|?` : proceed as if the top of the stack were zero * `<;qu;)` : point the IP in the right direction, pop the top of the stack (negative/zero number), move `n` to the bottom of the stack, u-turn, pop the top of the stack (`b^(counter)`) and increment the counter * IP is at `^w` and the program continues. [Watch it online!](http://ethproductions.github.io/cubix/?code=UHdwLkl8LS47KV4wQE8/fHVxOzw=&input=MjEyIDI=&speed=20) [Try it online!](https://tio.run/##Sy5Nyqz4/z@gvEDPs0ZXz1ozzsDB376mtNDa5v9/I0MjBSMA "Cubix – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 20 bytes ``` n%b=until(>n)(*b)1-n ``` [Try it online!](https://tio.run/##FYoxDsIwEAS/cgWRbLQUPp9NXIRvUKAUiYQUC3OKwDR83hhNs7OabXk/7qW0psM6fbTmYi5qzXG17qTtuWSlifZX1koH@ub9mutGZrB0Y8cI0UOSg7BAYoIXj5AYPCbEJPD957m3CB2PEefOf3Wf2w8 "Haskell – Try It Online") `until` saves the day [Answer] # R, 30 bytes ``` pryr::f(b^floor(log(n,b)+1)-n) ``` Evaluates to the function ``` function (b, n) b^floor(log(n, b) + 1) - n ``` Which takes the first power greater or equal than `n`, and then substracts `n` from that value. Changed `ceiling(power)` to `floor(power+1)` to ensure that if `n` is a power of `b`, we take the next power. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes ``` sLmʒ‹}α¬ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/2Cf31KRHDTtrz208tOb/f3MuYxNjAA "05AB1E – Try It Online") **Explanation** ``` s # swap order of the inputs L # range [1 ... n] m # raise b to each power ʒ‹} # filter, keep only the elements greater than n α # calculate absolute difference with n for each ¬ # get the first (smallest) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 42 bytes *Based on [@GovindParmar's C answer](https://codegolf.stackexchange.com/a/127227/58217).* ``` n->b->{for(int o=b;n>=b;b*=o);return b-n;} ``` [Try it online!](https://tio.run/##lZAxb4MwEIX3/IoboSqWAoQGuTBW6tApY9XBEEAmcLbMESmK@O3UlXAydIEbfKdnf372a8VVBEpX2J4vs@y1MgSt1dhIsmP1iCVJhexjGfhOj0UnSyg7MQzwJSTCfQe2Fn0gQbZdlTxDb3e9ExmJzfcPCNMM/nL4r9yV759IVVOZ13/C0vMcashgxiAvgvxeK@NJJFBZwTG3S/GSKZ@bikaDUATIp9l58Ifb6TZQ1TM1EtP2QdShVzOhdXfzwn3ou9H3OaxhDknkmMNaJk7325kwdky0mklSxxzXMlH8@M/b6gzScDMTHtPNGSTp9gyiZ25Pn2k3zb8 "Java (OpenJDK 8) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes ``` yy:YAn^w- ``` [Try it online!](https://tio.run/##y00syfn/v7LSKtIxL65c9/9/M0sTLmMA) ### Explanation Consider inputs `694` and `3` as an example. ``` y % Implicitly take two inputs. Duplicate from below % STACK: 694, 3, 694 y % Duplicate from below % STACK: 694, 3, 694, 3 : % Range % STACK: 694, 3, 694, [1 2 3] YA % Base conversion (of 694 with "digits" given by [1 2 3] % STACK: 694, 3, [3 3 2 3 1 2] n % Number of elements % STACK: 694, 3, 6 ^ % Power % 694, 729 w % Swap % STACK: 729, 694 - % Subtract. Implicitly display ^ % 35 ``` [Answer] # JavaScript (ES6), 29 bytes Very similar to [Rick's approach](https://codegolf.stackexchange.com/a/127232/58974) but posted with his permission (and some help saving a byte). ``` n=>b=>g=(x=b)=>x>n?x-n:g(x*b) ``` --- ## Try it ``` f= n=>b=>g=(x=b)=>x>n?x-n:g(x*b) oninput=_=>o.value=f(+i.value)(+j.value)() o.value=f(i.value=324)(j.value=5)() ``` ``` *{font-family:sans-serif;} input{margin:0 5px 0 0;width:50px;} ``` ``` <label for=i>n: </label><input id=i type=number><label for=j>b: </label><input id=j type=number><label for=o>= </label><input id=o> ``` [Answer] # Mathematica, 24 bytes ``` #2^⌊1/#~Log~#2⌋#2-#& ``` thanks Martin **I/O** > > [343, 7] > > > 2058 > > > [Answer] # C, ~~42~~ 40 bytes Thanks to commenter @Steadybox for the tip ``` o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 8 bytes ~~This feels longer than it needs to be!~~ That's a bit better! ``` nVpUìV l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=blZwVexWIGw&input=MjEyCjI) ``` nVpUìV l :Implicit input of integers U=n & V=b n :Subtract U from Vp : Raise V to the power of UìV : Convert U to a base-V digit array l : Get the length ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~34~~ 32+2 bytes ``` {for(n=$2;n<=$1;n*=$2);}$0=n-$11 ``` [Try it online!](https://tio.run/##RcxLCgIxDAbgfU7RxSxUEPJqp2GsN/AQbgQROqKCC/Hq1unUx7/6QpJ/fz@V8jiMl0VOHQ95kzoa8mrycnh2mPK6o1KY2LFLW6cKPojz1YFBjZpJFJTVSR0EPWgwF@cPAVFxfTWjj@CN20QRDThaaxAJEOzb4EGmtrZAAv4QiEV96KPhX45wTr2wKbEPXoUJfyJ8jefbcczXst69AQ "AWK – Try It Online") Requires the `-M` option for arbitrary precision to handle the `12345678901234567890 1000000 => 999987654321098765432110` case. The non-loop version requires the same number of bytes: ``` $0=$2^int(log($1)/log($2)+1)-$1 ``` After almost 5 years, saved 2 bytes in each formulation by removing unnecessary grouping symbols. Thanks @PaoloVlw [Answer] # [Desmos](https://desmos.com), ~~30~~ 27 bytes ``` f(n,b)=b^{floor(log_bbn)}-n ``` [Try It On Desmos](https://www.desmos.com/calculator/vqju31kztc) -3 thanks to @Aiden Chow and @Steffan Gotta love using your favorite graphing calculator for code golf. Taken from the [R answer](https://codegolf.stackexchange.com/a/127422/107299). [Answer] # [Python 2](https://docs.python.org/2), ~~42 41~~ 35 bytes Saved 6 thanks to loopy walt! (A superior recursive algorithm.) ``` f=lambda n,b:n<1or b*f(n/b,b)-(n%b) ``` A recursive function which repeatedly integer divides by `b` until that yields `0` (`n<1`) yielding `1` (well, `True` which works like `1`) at the tail and multiplies back up by `b` removing the remainder after division by `b` at each step. That is, we subtract `n` from `b^k` in base `b`, "digit" by "digit". **[Try it online!](https://tio.run/##JY3LCsMgEEXX7Ve4iyOThaN5GJr@i9KGBloTUhH69VbN6nAuB@7@C6/NU0rL/LYf97DMosM4y4nbWwTBY2thO9jC6y4cpCVreH4DWz3jnCQhAfKuV9hlaiNPkkZV2BscM5VWOJTOUCWNpna9OTuV@w5gul72Y/WhPiBr2nuD@VwUhfQH "Python 2 – Try It Online")** [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ɾe'¹>;hε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvmUnwrk+O2jOtSIsIiIsIjM0M1xuNyJd) Port of 05AB1E. ## How? ``` ɾe'¹>;hε ɾ # Inclusive range from one to (implicit) first input e # For each element, push it to the power of the (implicit) second input '¹>; # Filter for only elements greater than the first input h # Get the first item ε # Get the absolute difference of the first item and the (implicit) first input ``` [Answer] # JavaScript (ES6), 31 bytes ``` f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i) ``` **Test cases:** ``` f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i) console.log(f(212, 2)) // 44 console.log(f(563, 5)) // 62 console.log(f(491, 5)) // 134 console.log(f(424, 3)) // 305 console.log(f(469, 8)) // 43 console.log(f(343, 7)) // 2058 console.log(f(592, 7)) // 1809 console.log(f(289, 5)) // 336 console.log(f(694, 3)) // 35 console.log(f(324, 5)) // 301 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 32 bytes ``` @(n,b)b^(fix(log(n)/log(b))+1)-n ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08nSTMpTiMts0IjJz9dI09TH0QlaWpqG2rq5v1P0zAyNNIx0uRK0zA2MtEx1fwPAA "Octave – Try It Online") [Answer] # Octave, 26 bytes ``` @(n,b)b^sum(b.^(0:n)<=n)-n ``` [Verify all test cases!](https://tio.run/##JU3JqsIwFF17vuJuCgnUktybxEYt@B@PJ1hrwYWpWAfoz9cGV2fgDMP5eXpf5vmgUtnq9ji@bqqtjspsk943Sa/T3DenNO6AqfmrqgpsmZgK5@CDkKciMFy0mVlxcOxIqBDj4UKkekkKxAltqGDja/jImdvaRHAdc08kIMRfz0OWhWwaC1qe/P9uEQD64UEdNWS39Bg@o5o0Vt11vKteTaorrS4zsNYal9TNXw "Octave – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes Two different approaches: ``` ->(n,b){p b**(Math.log(n,b).to_i+1)-n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104jTydJs7pAIUlLS8M3sSRDLyc/HSymV5Ifn6ltqKmbV/s/TS85MSdHw8jQSMdIkwvKMzUz1jGF80wsDZF5RiY6xgiemaWOBZxnbGKsY44wxdIIiWdkYYlkipklsinGQDMRckZA9n8A "Ruby – Try It Online") ``` ->(n,b){p b**(0..n).find{|x|b**x>n}-n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104jTydJs7pAIUlLS8NATy9PUy8tMy@luqaiBihSYZdXq5tX@z9NLzkxJ0fDyNBIx0iTC8ozNTPWMYXzTCwNkXlGJjrGCJ6ZpY4FnGdsYqxjjjDF0giJZ2RhiWSKmSWyKcZAMxFyRkD2fwA "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` f n b=[b^x-n|x<-[1..],b^x>n]!!0 ``` [Try it online!](https://tio.run/##FYrhCoIwGEVf5fOfwlXy21wOshcZC2YkjXTISrDo3dfi/LnncO/u@bjNc0oTBRoHM172Onz3U23aprHIeg62KA5pcT7QQGv04UXl4lYqt3DdYnzTVFH58SsZbhmdEpC6hWQJqTSEFOg0g3sNpSVE7mzzF11GoMcx81/ZbVWlHw "Haskell – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~31 30~~ 29 bytes ``` ->\n,\b{(b,b* *...*>n).tail -n} ``` [Test it (31)](https://tio.run/##RY7BboMwEETv@xVzSQIECNjGBaFEvfbeI5cYHAmJGAS0ahXly3rrj9ElatXDase7b2Y92LHTy9tk8a7juqTrJ7Z131gcl@hUubAyN8@EJkAQx3Fwcn48n9sOkbsvjD7PdppxRNc6O3n@91dc91fjHapmf1hfL24uaQ1/Za6koTs77B@mki79@OuPTvDAt1AZLvsx2Hq2DXzcCGgnrP/xXGj8EH/LENMwtm6@YLeRDTYpV7MLwSHmn6L7AmSQUByUQyAnkQruSlGmJa@0IFWkLFKpSAnFrEwyUrpgXkmSSuIJIslyygrBMs2TgkRerLFSky4elowke3mUpHxJrOoH "Perl 6 – Try It Online") ``` ->\n,\b{b**(log(n,b).Int+1)-n} ``` [Test it (30)](https://tio.run/##RY69boNAEIT7fYppHIP5MffDBYRspU2fkibA2ULCBwISJbL8ZOnyYmSxEqVY3dztNzM32LEzy9tk8W7iuqDLJx7qvrE4LNGxdGFZXavdzuv6s@fCyo@f3RwIP3K3hcmn2U4zDuhaZyfP//6K6/5SefuyCfbrjeGC1uwX5goauleH4G4q6NSPv/7oCA9chbLisR@DrWfbwMeVgHbC@p17eYi/ZYhpGFs3n7DdqAYbwdNsQ3BI9U/RbQFSKGgOyiCRkRSST60pNYpXRpLOBQuhNGmpmVVJStrkzGtFSis8QiZpRmkuWYosyUlm@RqrDJn8bklJsZefEsFNclU/ "Perl 6 – Try It Online") ``` {$^b**(log($^a,$b).Int+1)-$a} ``` [Test it (29)](https://tio.run/##RY7NboNADITvfoo5kAYCIewPWxBK1WvvPUaR@NlUSAQQ0KpVlCfrrS9GTdQqB8tj@5vZ7e3QmPl9tPgwYZnR@QsPZVdZ7OeLcyw2G7fp3lznmAdO4YUv7eQLb@vk15nB58mOE/Zo6taOrvfzHZbduXB3h8rfLRPTGS3Rr8xl1Dd5C/9myujUDX/@7RNcHNoAh4LLfva2nGwFDxcC6hHLb9w2KLwA/8cAYz/U7XTCeqUqrARXtQ7AIcWdousMxFDQHJRAIiEpJHetKTaKT0aSTgULoTRpqZlVUUzapMxrRUorPEJGcUJxKlmKJEpJJukSqwyZ9GaJSbGXV5Hgl@SifgE "Perl 6 – Try It Online") ``` {($^b,$b* *...*>$^a).tail-$a} ``` [Test it (29)](https://tio.run/##RY7NaoNQEIX38xRnYRo1xnh/vFEkodvuuwwBf25AMCpqS0vIk3XXF7NjaOlimDMz3zn39nZozPw2WrybsMzo@omnsqssDvPNdc5F4BQ@/DAM/aNzzr1wyutm6@T3mcHnyY4TDmjq1o6u9/0Vlt21cHenarNbppd2ymiJfmUuo77JW2wepowu3fDr3x7h4tQGOBVc9qO35WQreLgRUI9YfuO2QeEF@DsGGPuhbqcL1itVYSW4qnUADin@KbrPQAwFzUEJJBKSQnLXmmKj@GQk6VSwEEqTlppZFcWkTcq8VqS0wh4yihOKU8lSJFFKMkmXWGXIpA9LTIq9vIoEvyQX9QM "Perl 6 – Try It Online") [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~26~~ 24 bytes ``` f(n,b)=b^logint(b*n,b)-n ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` _q}a@nVpX ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=X3F9YUBuVnBY&input=MTI3IDI=) ### Explanation ``` _ q}a@ nVpX Z{Zq}aX{UnVpX} // Ungolfed // Implicit: U, V = input integers aX{ } // For each integer X in [0...1e9), take VpX // V to the power of X Un // minus U, Z{ } // and return the first one Z where Zq // Math.sqrt(Z) is truthy. // Math.sqrt returns NaN for negative inputs, and 0 is falsy, so this is // truthy iff Z is positive. Therefore, this returns the first positive // value of V**X - U. // Implicit: output result of last expression ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ^ʰ↙X>₁- ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahjuVKSgq2CUrl9RrmSjkIehF1SrqSgawdiPWrb8Kip6eGuztqHWyf8jzu14VHbzAi7R02Nuv//RytEG@kYGRrF6kSb6piaGYNpE0tDIG2sY2JkAqQtdEzMLIG0uY6xiTGYNrWEqDeysASrM7M0AfONjSC0UaxCLAA "Brachylog – Try It Online") Takes input as a list `[b, n]`. ``` >₁ n is strictly less than ^ ↙X some power of ʰ b, - and their difference is the output. ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 45 bytes ``` : f >r 1 begin i * 2dup < until rdrop - abs ; ``` [Try it online!](https://tio.run/##JYxBCoNAEATvvqLwGFBwVo0bg3/RGI0QdFmVPN/M6mWKoat7WPz2ScYh4DgeDDSejO49TjMTN6TfHU/2eZu@@N4vjoS2W6nVdle8/lqHIfVIOGkMSUOsYykvTx1JJhq5qCgNhTK32UXJtacsLZXS5IZ78KyclMqeXmkvz6gffnRNefwB "Forth (gforth) – Try It Online") ### Code Explanation ``` : f # start a new word definition >r # store b on the return stack for quick access 1 # create a counter to store powers of b begin # start an indefinite loop i * # multiply the counter by b 2 dup < # duplicate the counter and n. Check if n is less than the counter until # if it is, end the loop rdrop # remove b from the return stack - abs # subtract and get absolute value (avoid negative) ; # end the word definition ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ≠Ω>¹*³ ``` [Try it online!](https://tio.run/##yygtzv7/cGfjw11dj5oa/z/qXHBupd2hnVqHNv///z862kjHyNAoVifaVMfUzBhMm1gaAmljHRMjEyBtoWNiZgmkzXWMTYxjYwE "Husk – Try It Online") ``` ≠Ω>¹*³ # ¹ and ³ duplicate arguments ⁰ and ², so parses as: ≠Ω>⁰*²²⁰ # now: Ω>⁰*²² # Ω = Iterate function f until test result t is truthy, starting with x: ² # x is arg 2 *² # f is *² = times arg 2, so iterating generates power series of arg 2 >⁰ # t is >⁰ = greater than arg 1 # then: ≠ # get the absolute difference to ⁰ # arg 1 ``` ]
[Question] [ Let's create a simple, [surjective](https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection) mapping from positive integers to [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer), which are [complex numbers](https://en.wikipedia.org/wiki/Complex_number) where the real and imaginary parts are integers. Given a positive integer, for example `4538`, express it in binary with no leading `0`'s: ``` 4538 base 10 = 1000110111010 base 2 ``` Remove any trailing `0`'s: ``` 100011011101 ``` Replace any runs of one or more `0`'s with a single `+`: ``` 1+11+111+1 ``` Replace all `1`'s with [`i`](https://en.wikipedia.org/wiki/Imaginary_unit)'s: ``` i+ii+iii+i ``` Evaluate the resulting complex expression and output the simplified Gaussian integer: ``` i+ii+iii+i = i+i*i+i*i*i+i = 2i+i^2+i^3 = 2i+(-1)+(-i) = -1+i ``` The output can be expressed in a traditional mathematical way, or given as two separate integers for the real and complex parts. For the `4538` example, any of these would be fine: ``` -1+i i-1 -1+1i (-1, 1) -1 1 -1\n1 ``` For inputs like `29`, mathy formatted outputs such as `0`, `0i`, or `0+0i` are all fine. Using `j` (or something else) instead of `i` is fine if that is more natural for your language. The shortest code in bytes wins. [Answer] # [MATL](http://github.com/lmendo/MATL), 7 bytes ``` BJ*Y'^s ``` [Try it online!](http://matl.tryitonline.net/#code=QkoqWSdecw&input=NDUzOA) ### How it works Consider input `4538` for example. ``` B % Implicit input. Convert to binary % STACK: [1 0 0 0 1 1 0 1 1 1 0 1 0] J* % Multiply by 1i % STACK: [1i 0 0 0 1i 1i 0 1i 1i 1i 0 1i 0] Y' % Run-length encoding % STACK: [1i 0 1i 0 1i 0 1i 0], [1 3 2 1 3 1 1 1] ^ % Power, element-wise % STACK: [1i 0 -1 0 -1i 0 1i 0] s % Sum of array. Implicit display % STACK: -1+1i ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` BŒgaıP€S ``` [Try it online!](https://tio.run/nexus/jelly#@@90dFJ64pGNAY@a1gT////fxNTYAgA "Jelly – TIO Nexus") ### How it works ``` BŒgaıP€S Main link. Argument: n (integer) B Convert to binary. If n = 4538, this yields [1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0]. Œg Group equal elements. This yields [[1], [0, 0, 0], [1, 1], [0], [1, 1, 1], [0], [1], [0]]. aı Logical AND with the imaginary unit. This yields [[ı], [0, 0, 0], [ı, ı], [0], [ı, ı, ı], [0], [ı], [0]]. P€ Product each. This yields [ı, 0, -1, 0, -ı, 0, ı, 0]. S Sum. This yields -1+ı. ``` [Answer] ## Python 2, 53 bytes ``` f=lambda n,k=0:(n and f(n/2,n%2*(k or 1)*1j))+~n%2*k ``` Been trying to golf this and it seems golfable but I'm out of ideas atm... [Answer] # Mathematica, ~~44~~ 38 bytes ``` Tr[1##&@@@Split[I*#~IntegerDigits~2]]& ``` # Explanation ``` #~IntegerDigits~2 ``` Convert the input into base 2. (`4538` becomes `{1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0}`) ``` I* ``` Multiply by `I` (`{1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0}` becomes `{I, 0, 0, 0, I, I, 0, I, I, I, 0, I, 0}`) ``` Split ``` Split by runs (`{I, 0, 0, 0, I, I, 0, I, I, I, 0, I, 0}` becomes `{{I}, {0, 0, 0}, {I, I}, {0}, {I, I, I}, {0}, {I}, {0}}`) ``` 1##&@@@ ... ``` Find the product at level 2. (`{{I}, {0, 0, 0}, {I, I}, {0}, {I, I, I}, {0}, {I}, {0}}` becomes `{I, 0, -1, 0, -I, 0, I, 0}`) ``` Tr ``` Sum the result. (`{I, 0, -1, 0, -I, 0, I, 0}` becomes `-1 + I`) [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ ~~76~~ 71 bytes ``` p=r=0 for n in bin(input()*2):t=n=='1';r-=p*~-t;p=p*t*1jor t*1j print r ``` *Thanks to @ZacharyT for golfing off 1 byte!* [Try it online!](https://tio.run/nexus/python2#@19gW2RrwJWWX6SQp5CZp5CUmaeRmVdQWqKhqWWkaVVim2drq26obl2ka1ugVadbYl0ApEu0DLOAGkAUV0FRZl6JQtH//yamxhYA "Python 2 – TIO Nexus") [Answer] # JavaScript (ES6), ~~67~~ 64 bytes ``` f=(n,q=0,a=[0,0])=>q|n?f(n/2,n&1?q+1:q&&0*(a[q&1]+=1-(q&2)),a):a ``` ``` <input oninput="O.innerHTML=f(this.value)" type="number" step=1 min=0 value="4538"> <pre id=O></pre> ``` Outputs as a 2-element array. ### Explanation Since JavaScript doesn't have imaginary numbers, we have to keep track of the real and imaginary parts in separate variables. The easiest way to do this is in a single array, with the real part first. **i** is represented as **[0,1]**, **i2** (or **-1**) as **[-1,0]**, **i3** (or **-i**) as **[0,-1]**, and **i4** (or **1**) as **[1,0]**. First, we repeatedly divide the number by 2, collecting each run of ones in its binary representation. Each run of **n** ones corresponds to **in**. This corresponds to adding **1 - (n & 2)** to the item at index **n & 1** in the two-item array. So that's we do. I should probably add more explanation, but I can't think of what else needs explaining. Feel free to comment with any questions you might have. [Answer] # Python, ~~199~~ ~~129~~ ~~124~~ ~~116~~ ~~94~~ ~~90~~ ~~71~~ ~~63~~ 61 bytes ``` print sum(1j**len(s)for s in bin(input())[2:].split('0')if s) ``` Input is just the number itself. Output is in the format `(a+bj)`, where `j` is the imaginary unit. `0j` will be output instead of `(0+0j)` First convert to binary. Truncate the `'0b'` off. Kill the trailing zeros. Split using a block of zero(s) as a delimiter. Map each block to `1j ** len`. Then, take the sum of the entire thing. **-70 bytes** by not converting to pluses. *-5 bytes* regex is shorter. *-8 bytes* by getting rid of the two unnecessary variables that were only being called once. *-22 bytes* by using complex numbers instead of my weird thing. Thanks to @Dennis' answer for informing me of complex numbers! *-4 bytes* by realizing that `map` is just a fancy way of doing list comprehensions, except longer. *-19 bytes* by switching to a slightly arcane method of avoiding errors with `j ** 0` and avoiding regex. Inspired by @Griffin's comment. Thanks! :) *-8 bytes* by moving the `if` part to the end. *-2 bytes* Thanks to @Griffin for saving 2 bytes by removing the square brackets to make it a generator expression instead! [Answer] # MATLAB, 58 bytes ``` @(x)eval([strrep(strrep(dec2bin(x),48,43),49,'i*1'),'.0']) dec2bin(x) % converts the decimal value to a binary string of 1s and 0s. strrep(dec2bin(x),48,43) % Substitutes ASCII character 48 with 43 (0s become +) strrep(___,49,'i*1') % Substitutes ASCII character 49 with 'i*1' % 1s become 'i*1' (this is the gem) eval([___,'.0'] % Appends .0 in the end and evaluates the expression. ``` Let's use `285` to illustrate the process: ``` temp1 = dec2bin(285) = 100011101 temp2 = strrep(temp1,48,43) = 1+++111+1 ``` Luckily `1+++1` behaves just as `1+1` in MATLAB, so the above evaluates to: `1+111+1`. ``` temp3 = strrep(temp2,49,'i*1') = i*1+++i*1i*1i*1+i*1 ``` Now this `strrep`-call is the real gem! By inserting `i*1` for `1` we get something really nice. If there's only one `1`, we simply get `i*1` which is `i`. If there are more than one then `i*1` gets repeated and concatenated into a sequence: `i*1i*1i*1i*1`. Since `i==1i` in MATLAB and `1i*1==i` this is simply: `i*i*i*i`. ``` temp4 = [temp3,'.0'] = i*1+++i*1i*1i*1+i*1.0 ``` Appending `.0` seems unnecessary here, but it's needed if the last character of `temp3` is a `+`. We can't append just a zero, since that would give `i*10` in the case above and therefore the wrong result. And finally: ``` eval(temp4) 0.0000 + 1.0000i ``` This doesn't work in Octave for several reasons. `strrep` can't take ASCII-values as input, it needs the actual characters (`'0'` instead of `48`). Also, `+++` doesn't evaluate to just `+` in Octave, as that would break the increment/decrement shortcuts `x++` and `x--`. [Answer] # Pyth - 15 bytes Frustratingly long. ``` s^L.j)hMe#r8jQ2 ``` [Test Suite](http://pyth.herokuapp.com/?code=s%5EL.j%29hMe%23r8jQ2&test_suite=1&test_suite_input=4538%0A29&debug=0). [Answer] # Mathematica, 84 bytes ``` ToExpression[#~IntegerString~2~StringTrim~"0"~StringReplace~{"0"..->"+","1"->"I "}]& ``` Anonymous function. Takes a number as input and returns a complex number as output. [Answer] # Mathematica, 75 bytes ``` ToExpression[#~IntegerString~2~StringReplace~{"1"->"I ","0"..->"+"}<>"-0"]& ``` Independently came up with almost the same solution that LegionMammal978 posted 23 minutes ago! Replacing `1` with `I` (which is Mathematica's internal symbol for the square root of -1) works because spaces are treated as multiplication of neighboring expressions. The place I saved on the other solution, namely by avoiding the need for `StringTrim`, is by always appending `-0`: if the binary number ends in `1`, then this expression ends in `...I-0` which doesn't affect its value; while if the binary number ends in '0', then this expression ends in `...+-0` which is parsed as "add negative 0" and thus gets rid of the trailing plus sign. [Answer] # Matlab, 99 Bytes ``` function c=z(b) c=0;b=strsplit(dec2bin(b),'0');for j=1:numel(b)-isempty(b{end});c=c+i^nnz(b{j});end ``` Test cases: ``` z(656) = 3i z(172) = -1 + 2i z(707) = -2 + i z(32) = i z(277) = 4i ``` [Answer] # Haskell, ~~102~~ ~~91~~ ~~89~~ 87 bytes ``` 0%a=a n%c@[a,b]|odd n=div n 2%[-b,a]|d<-div n 2=zipWith(+)c$d%[mod d 2,0] (%[0,0]).(*2) ``` Repeatedly divides by two and checks the bit. Keeps an accumulator of `i^(number of odds)` where `a+b*i` is encoded as `[a,b]` and `*i` is `[a,b]↦[-b,a]` (rotation by 90 degrees). The initial `(*2)` is to avoid a lookup for the first bit. Usage (thanks to @OwenMorgan for the examples): ``` (%[0,0]).(*2)<$>[656,172,707,32,277] [[0,3],[-1,2],[-2,1],[0,1],[0,4]] ``` [Answer] # Java, 172 bytes ``` l->{int i=0,j=i;for(String x:l.toString(2).split("0")){int a=x.length();j+=a&1>0?(a&3>2?(a-3)/-4+1:(a-3)/4+1):0;i+=a&1<1?(a&3>1?(a-3)/4+1:(a-3)/-4+1):0;}return i+"|"j+"i";} ``` [Answer] # Clojure, 183 bytes ``` #(loop[x(clojure.string/split(Integer/toString % 2)#"0+")y[0 0]a 0](if(= a(count x))y(recur x(let[z([[1 0][0 1][-1 0][0 -1]](mod(count(x a))4))][(+(y 0)(z 0))(+(y 1)(z 1))])(inc a)))) ``` Am I allowed to do this? Use the function like so: ``` (#(...) {num}) -> (Wrap the # function in brackets first!) ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 35 bytes ``` ├'0' aÆô' @s"j+"j'jo`"1j*1"'1τ(Æ`Y≡ ``` [Try it online!](https://tio.run/nexus/actually#@/9oyhx1A3WFxMNth7eoKzgUK2VpK2WpZ@UnKBlmaRkqqRueb9E43JYQ@ahz4f//JqbGFgA "Actually – TIO Nexus") Explanation: ``` ├'0' aÆô' @s"j+"j'jo`"1j*1"'1τ(Æ`Y≡ ├ binary representation of input '0' aÆ replace 0s with spaces ô trim leading and trailing spaces ' @s split on spaces "j+"j join with "j+" 'jo append "j" `"1j*1"'1τ(Æ`Y do until the string stops changing (fixed-point combinator): "1j*1"'1τ(Æ replace "11" with "1j*1" ≡ evaluate the resulting string to simplify it ``` Roughly equivalent Python 3 code: ``` a='j+'.join(bin(eval(input()))[2:].replace('0',' ').strip().split())+'j' b=0 while a!=b:b,a=a,a.replace("11","1j*1") print(eval(a)) ``` [Try it online!](https://tio.run/nexus/python3#PY3NCgIhFEb3PsXk5npnRMZ@IAZ8kmhxDaErYmJOPb5NBC0@zuYcvk4O4gQmPjgrvy28KCnOZW0KES/75WpqKIluQcEMGgZA82yVi9pYEn@1CSII72bxvnMKA@2cX7wmR5r@sbRWamnjaCWKUjm33xUh9n48Hc4f "Python 3 – TIO Nexus") [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 bytes This isn't better than Dennis's Jelly answer, but I wanted to try my hand at a Jelly answer anyway. Golfing suggestions welcome! [Try it online!](http://jelly.tryitonline.net/#code=QsWScm0y4bmq4oKsxLEqUw&input=&args=NDUzOA) ``` BŒrm2Ṫ€ı*S ``` **Ungolfing** ``` BŒrm2Ṫ€ı*S Main link. Argument: n (integer) B Convert n to binary. Œr Run-length encode the binary list. m2 Every 2nd element of the run_length encoding, getting only the runs of 1s. Ṫ€ Tail each, getting only the lengths of the runs. ı* The imaginary unit raised to the power of each run (as * is vectorized). S Sum it all into one complex number. ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 15 bytes Golfing suggestions welcome! [Try it online!](https://tio.run/nexus/actually#AR4A4f//4pScJzBAc2Bg4paRYGzDr@KBv2BNzqP//zQ1Mzg "Actually – TIO Nexus") ``` ├'0@s``░`lïⁿ`MΣ ``` **Ungolfing:** ``` Implicit input n. ├ Convert n to binary. '0@s Split by '0's. ``░ Filter out non-truthy values. `...`M Map over the filtered result, a list of runs of '1's. l Yield the length of the run of '1's. ïⁿ Yield the imaginary unit to the power of that length. Σ Sum all of this into one complex number. ``` [Answer] # Axiom, ~~140, 131, 118~~ 108 bytes ``` b(x)==(s:=0;repeat(x=0=>break;r:=x rem 2;repeat(x rem 2=1=>(r:=r*%i;x:=x quo 2);break);s:=s+r;x:=x quo 2);s) ``` %i is the imaginary costant.Ungolfed ``` sb(x:NNI):Complex INT== r:Complex INT;s:Complex INT:=0 repeat x=0=>break r:=x rem 2 repeat x rem 2=1=>(r:=r*%i;x:=x quo 2) break s:=s+r x:=x quo 2 s ``` results ``` (3) -> b 4538 The type of the local variable r has changed in the computation. We will attempt to interpret the code. (3) - 1 + %i Type: Complex Integer (4) -> b 29 (4) 0 Type: Complex Integer (5) -> sb 299898979798233333333333333339188888888888888888222 Compiling function sb with type NonNegativeInteger -> Complex Integer (5) - 7 + 12%i Type: Complex Integer (6) -> b 299898979798233333333333333339188888888888888888222 (6) - 7 + 12%i Type: Complex Integer ``` [Answer] # [Perl 6](https://perl6.org), ~~40~~ 46 bytes I came up with this fairly quickly ``` *.base(2).comb(/1+/).map(i***.chars).sum ``` Unfortunately it is currently inaccurate in the [Rakudo](http://rakudo.org) implementation on [MoarVM](http://moarvm.org). `say i ** 3; # -1.83697019872103e-16-1i` So I had to do the next best thing: ``` *.base(2).comb(/1+/).map({[*] i xx.chars}).sum ``` ## Expanded: ``` *\ # Whatever lambda .base(2) # convert to a Str representation in base 2 .comb(/ 1+ /) # get a list of substrings of one or more 「1」s .map({ # for each of those [*] # reduce using 「&infix:<**>」 i xx .chars # 「i」 list repeated by the count of the characters matched }).sum # sum it all up ``` ## Test: ``` .say for (4538, 29).map: *.base(2).comb(/1+/).map({[*] i xx.chars}).sum # -1+1i # 0+0i ``` [Answer] # PHP, 87 bytes ``` for($n=$argv[1];$n|$i;$n>>=1)$n&1?$i++:($i?$i=0*${$i&1}+=1-($i&2):0);echo"(${0},${1})"; ``` Almost the same as ETHproductions´ solution; only iterative instead of recursive. Takes input from command line, sets variables `${0}` and `${1}`. [Answer] # TI-Basic (TI-84 Plus CE), 70 bytes ``` Prompt X 0→S 0→N While X If remainder(X,2 Then N+1→N int(X/2→X Else S+i^Nnot(not(N→S X/2→X 0→N End End S+i^Nnot(not(N ``` There's no builtin to convert to a binary string, (nor is there to parse a string), so this program manually divides by 2, incrementing N each time it sees a 1 and adding i^N to S (N>0) and resetting N if it sees a zero. [Answer] # [Java](http://openjdk.java.net/), 100 bytes ``` int[]f(int n){int c=2,r[]=new int[2];for(;n>0;r[c&1]+=n%4==1?(c&2)-1:0,n/=2)c=n%2<1?2:c+1;return r;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#pY9BbsIwEEXX5RTegGxBXWxAbXFd1AN0xTLywrgJMgpONJ5QoShnT51yBK@eNF/z/kzbnWrviKttjOTb@tCPPmBhKppAAusnOC1XUBgdyl8ypdKoqgGqwudaQeEWwix1mG@1FgfqFpI9i/16FV60ZC7N5Yc4yL1bCgUldhAIqGFsH70RLSbcGv9DrqmdHhF8OBfGwjmyfvZ0vEcsr7zpkLcpwTrQi71Z3qGv@ReAvUeOzWOLTvdNP1DGKyoYYypHsMkVvOYKxC7XIN9zDdvd5u3fMcyG8Q8 "Java (OpenJDK 8) – TIO Nexus") [Answer] # [R](https://www.r-project.org/), 54 bytes ``` function(n,x=rle(n%/%2^(0:log2(n))%%2))sum(1i^x$l*x$v) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPp8K2KCdVI09VX9UoTsPAKic/3UgjT1NTVdVIU7O4NFfDMDOuQiVHq0KlTPN/moaJqbGFJleahpGl5n8A "R – Try It Online") `n%/%2^(0:log2(n))%%2` computes a vector of the binary digits. Using the run-length encoding, we use R's `complex` type to compute the appropriate sum, multiplying by the `x$values` to remove zeros. Returns a `complex` vector of one element. [Answer] # [APL(Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes [SBCS](https://github.com/abrudz/SBCS) ``` +/×/¨0j1×⊆⍨⊤⎕ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=09Y/PF3/0AqDLMPD0x91tT3qXfGoa8mjvqkA&f=AwA&i=S@MyMTW2AAA&r=tio&l=apl-dyalog-extended&m=tradfn&n=f) A tradfn submission which takes a decimal number. ]
[Question] [ Based on a comment by George Edison to [this question](https://codegolf.stackexchange.com/questions/471/self-compiling-compiler), write the smallest self-interpreting interpreter. * You may use the language of your choosing. * Empty languages do not count. Your program must be at least two characters long. * The program does not need to interpret the *entire* language, just a Turing-complete subset of language features (that contains the interpreter). * Quines don't count. * Do not use your language's built-in `eval` function or equivalent. Same goes for `apply`, etc. [Answer] # Binary Lambda Calculus, 232 *bits* (29 bytes) `0101000110100000000101011000000000011110000101111110011110000101110011110000001111000010110110111001111100001111100001011110100111010010110011100001101100001011111000011111000011100110111101111100111101110110000110010001101000011010` See <http://en.wikipedia.org/wiki/Binary_lambda_calculus#Lambda_encoding> for details [Answer] ## CI - 260 ``` ,(1p0(2d())(41(2d())('#((1p0()(10()(1d,1p$)=)<)$2d,1p$)(40(1d,1c$^)(''(1d,^)('0 '9('0-(,'0'9('0-2p10*+1p$)(!1d)~)$^)(0($)'$(^)'^(&)'&(c)'c(p)'p(d)'d(=)'=(<)'<( >)'>(~)'~(.)'.(,)',(!)'!(+)'+(-)'-(*)'*(/)'/(%)'%()38p(1p3p0(3d)((2)(3)=p1d1p$) =)$)~)=)=,2p$&)=)=)<)$$ ``` ***320 → 260:** Push simple character-to-instruction mappings, then fold over them. This halves the code size per case (there are 18 cases), but costs 30 characters to do the folding.* This is another one of my constructed languages, (base interpreter [hosted on Gist](https://gist.github.com/938595)). It's unique in that the language reifies code fragments. That is, strings of instructions in this stack-based language are used to the same effect as data structures or closures in other languages: ``` 1^ # Push a 1, and "lift" it to be a code literal. (5 +) # Define a code literal. & # Join the two code literals, forming (1 5 +) $ # Execute the code literal. ``` The interpreter builds a code fragment of the entire program before running it, so it can also be considered a compiler. Because of this, [stacking the interpreter](https://gist.github.com/938595#file_stack.ci) does not result in exponential run-time overhead. The interpreter derives all of its operators directly from the host interpreter. However, it does the parsing by itself, so the majority of the code is just sequences that translate characters into their respective code literals. This isn't the same as using `eval`, but it reveals how dependent any programming language implementation is on the semantics of its host language/architecture. --- ## Language reference: *[Get the interpreter here](https://gist.github.com/938595)* ### Blocks * `(` ... `)` Create a "block", which is effectively a list of instructions with no context. Internally, it could even be machine code. * block `$` Call a block. The callee is handed the global stack, which includes the block being called. * value `^` Lift a value. Namely, turn it into a block that pushes that value. **Example**: ``` 1 ^ == (1) ``` * block1 block2 `&` Join two blocks, forming one that runs both in sequence. **Example**: ``` (1) (2) & == (1 2) ``` ### Stack manipulation * n `c` Copy the nth value of the stack. **Example**: ``` 5 4 3 2 1 0 3c == 5 4 3 2 1 0 3 ``` * n `p` Pluck the nth value of the stack (remove it, and bring it to front). **Example**: ``` 5 4 3 2 1 0 3p == 5 4 2 1 0 3 ``` * n `d` Drop n values from the stack. `0d` is a no-op. **Example**: ``` 5 4 3 2 1 0 3d == 5 4 3 ``` ### Relational operators * a b (on\_true) (on\_false) `=` Test if a equals b. Consume all but the first argument, and call on\_true or on\_false. If one argument is zero and the other is any other type, the result will be false. Otherwise, a and b must be integers. **Example**: ``` 3 3 ('0+ .) (1d) = == 3 '0+ . ``` * a b (on\_true) (on\_false) `<` Test if a is less than b. a and b must be integers. **Example**: ``` 3 5 (1d 5) () < == 3 1d 5 == 5 ``` * a b (on\_true) (on\_false) `>` Test if a is greater than b. a and b must be integers. **Example**: ``` 3 5 (1d 5) () > == 3 ``` * a lo hi (on\_true) (on\_false) `~` Test if lo <= a <= hi. a, lo, and hi must be integers. **Example**: ``` 3 0 10 ('0+ .) (1d) ~ == 3 '0+ . ``` ### I/O * c `.` Put the character c (consuming it from the stack). * `,` Get a character and push it to the stack. If the end of file has been reached, -1 is pushed. * c `!` Unget a character. Just like ungetc in C, only one pushback is allowed. ### Integer literals * `'c` Push the character c. * *[0-9]+* Push a decimal integer. ### Arithmetic * a b `+` * a b `-` * a b `*` Add/subtract/multiply two numbers. **Example**: ``` 3 5 + 7 3 + * == 80 ``` * a b `/` * a b `%` Division and modulus. Unlike in C, these round toward negative infinity. ### Miscellaneous * code `#` comment The `#` character comments out everything to the end of the line. * `)` Used to end blocks. Can be used to end the whole program, too. * All other characters are ignored. [Answer] [I can't take credit for this one](http://www.hevanet.com/cristofd/brainfuck/dbfi.b), but I thought I would share this amazing one: ## Brainf\*\*\* (423) ``` >>>+[[-]>>[-]++>+>+++++++[<++++>>++<-]++>>+>+>+++++[>++>++++++<<-]+>>>,<++[[>[ ->>]<[>>]<<-]<[<]<+>>[>]>[<+>-[[<+>-]>]<[[[-]<]++<-[<+++++++++>[<->-]>>]>>]]<< ]<]<[[<]>[[>]>>[>>]+[<<]<[<]<+>>-]>[>]+[->>]<<<<[[<<]<[<]+<<[+>+<<-[>-->+<<-[> +<[>>+<<-]]]>[<+>-]<]++>>-->[>]>>[>>]]<<[>>+<[[<]<]>[[<<]<[<]+[-<+>>-[<<+>++>- [<->[<<+>>-]]]<[>+<-]>]>[>]>]>[>>]>>]<<[>>+>>+>>]<<[->>>>>>>>]<<[>.>>>>>>>]<<[ >->>>>>]<<[>,>>>]<<[>+>]<<[+<<]<] ``` [Answer] ## BlockScript - 535 ``` {[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B '9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[ B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[ C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A] HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B! :{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=? {[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!; ``` BlockScript is a trivial [spaghetti stack](http://en.wikipedia.org/wiki/Spaghetti_stack)-based language I created specifically for this challenge. The base interpreter is [blockscript.c](https://gist.github.com/917067) . Sample program (prints the first 15 Fibonacci numbers): ``` {[B?B10/A!B10%d&:0} {[B0<?'-.0B-A!:{B?Bh!{[B?B[A]A!B[B]'0+.:}!:'0.}!10.} {[B?Dd!DC+B1-CecA!:} 0 1 15d! ; ``` The interpreter reads both source code and program input from standard input, in that order. This means that to run an interpreter within an interpreter within an interpreter, simply copy and paste: ``` # Level 1 {[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B '9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[ B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[ C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A] HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B! :{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=? {[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!; # Level 2 {[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B '9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[ B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[ C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A] HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B! :{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=? {[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!; # Level 3 {[B?B10/A!B10%d&:0} {[B0<?'-.0B-A!:{B?Bh!{[B?B[A]A!B[B]'0+.:}!:'0.}!10.} {[B?Dd!DC+B1-CecA!:} 0 1 15d! ; ``` Like the movie [Inception](http://en.wikipedia.org/wiki/Inception), you pretty much can't go any deeper than three levels. It's not a matter of time, but space. BlockScript leaks memory profusely, and this has to do with how the language itself is designed. --- ## Language reference: *[Get the interpreter here](https://gist.github.com/917067)* In BlockScript, the "stack" is not an array that is overwritten by subsequent operations like you may be used to. It is actually implemented as an immutable linked list, and a stack persists for the duration of the program. Also, no operator (except `@`) removes values from the stack. However, stack modifications only affect the block in which they occur. ### Value selection * `a` through `z` Fetch the 0-25th item from the stack, and push it to the stack. `a` refers to the head, or most recently pushed item, of the stack. * `A` through `Z` Fetch the 0-25th item of the current frame, and push it to the stack. * `[` Open a "frame" to select items from the stack reference (see below) on the head of the stack. `[` doesn't require a matching `]`, but frames are lexically scoped. In BlockScript, "scope" is determined by braces (`{` ... `}`) that form blocks. Thus, opening a frame inside of a block will have no effect on code outside of the block. * `]` Close the current frame, returning to the previous frame (if any). ### Blocks * `{` ... `}` Create a "block", and push it to the stack. Inside a block, the stack will start at what it was before the block, except the stack of the caller will be pushed on top. Stacks are persistent and immutable in BlockScript, so blocks are closures. The idiom `{[` means open a block, then open a frame to start selecting arguments (using `A` through `Z`). The return value of a block is the head of the stack when `}` is reached. **Example:** ``` '3 '2 '1 {[ b. d. f. B. C. D. A! } 'D 'C 'B d!; ``` This prints `123BCD123DCB123BCD123DCB…` . The lowercase letters refer to stack values, while the uppercase letters refer to arguments (because the frame is set to the stack of the caller). `A!` takes the head of the caller (which is guaranteed to be the block being called) and calls it. If you're wondering why it reverses `BCD` every other time, it's because `B. C. D.` pushes those arguments in reverse order right before the block calls itself. * `!` Call a block. Push the return value to the stack. ### Stack references * `&` Create a stack reference, and push it to the stack. Think of this as "super-cons", as it effectively takes every item on the stack and forms a "tuple" out of it. The idiom `&[` means that whatever `a`, `b`, `c` referred to before can now be accessed with `A`, `B`, `C` (for the remainder of the block or until `]` is encountered). In part because `&` captures more values than it usually needs, BlockScript leaks memory by design. * `@` Switch to the stack pointed to by the stack reference `a`. This operator is rather weird, but the BlockScript self-interpreter uses it a couple times to avoid having to push the same arguments twice. The effects of `@` (or any stack operation, for that matter) are confined to the block in which it is invoked. Also, the frame is unaffected by `@`, so the frame can be used to grab values you need after switching stacks. ### Conditional expression * `?` *<on true>* `:` *<on false>* Conditional expression, just like the ternary operator in C. That is, if `a` is "true" (that is, not equal to the integer zero), then do *<on true>*, otherwise do *<on false>*. ### I/O Note: Input and output are done in UTF-8. A "character" is an integer corresponding to a Unicode index. * `,` Get the next character of input, and push it to the stack. If the end of input is reached, push -1 instead. * `.` Output the character on the head of the stack. ### Integer/character literals Note: Integers and characters are the same thing in BlockScript. * `'c` Push the character c. * *[0-9]+* Push a decimal integer. ### Arithmetic These operators only work on integer values. * `+` Compute `b` + `a` (pushing the result, but not discarding either value). * `-` Compute `b` - `a`. * `*` Compute `b` \* `a`. * `/` Compute `b` / `a` (integer division; rounds toward negative infinity). * `%` Compute `b` % `a` (integer modulus; rounds toward negative infinity). ### Relational operators These operators only work on integer values. * `<` If `b` is less than `a`, push 1, else push 0. * `>` * `=` ### Miscellaneous * `#` Comment to end of line * The program must end with `;` * All other characters are ignored. [Answer] # [Zozotez LISP](http://sylwester.no/zozotez/): 414 linefeeds added to get a nice block is not needed and not counted. ``` ((\(E V A L)(E(r)'(())))(\(x e)(?(s x)(V x e)((\(b j)(?(= b ")(a j)(?(= b \)x (?(= b ?)(?(E(a j)e)(E(a(d j))e)(E(a(d(d j)))e))(?(s b)(A b(E(a j)e)(E(a(d j) )e))(E(a(d(d b)))(L(a(d b))j e)))))))(E(a x)e)(d x))))(\(x g)(? g(?(= x(a(a g)))(d(a g))(V x(d g)))x))(\(f h v)(?(= f r)(r)(?(= f p)(p h)(?(= f s)(s h)(? (= f a)(a h)(?(= f d)(d h)(?(= f =)(= h v)(c h v))))))))(\(k v i)(? k(L(d k)( d v)(c(c(a k)(E(a v)i))i))i))) ``` In theory it should be able to run itself, but since the original interpreter is a [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck) binary and itself an interpreter I have only been able to test each part. When given itself and a simple expression `(p p)` I think it needs more time than the 40 minutes I have waited so far and I'm using my fast `jitbf` to run it which (mis)uses Perl Inline-C to run C code on the fly. It's impossible to implement the whole Zozotez in Zozotez since it does not have means of mutating cons and `:` (setq/define) need that to update bindings. I also didn't implement explicit begin/progn or &rest argument, macros and special printing arguments since I didn't use it in the interpreter. I did include `p` (print) even though I don't use it so programs need to explicit print their calculations just like the original interpreter. The same ungolfed: ``` ;; A stand alone Zozotez script need to be ;; contained in one expression, here with ;; all functions provided as arguments to ;; get them bound in the dynamic environment ((\ (E V A L) (E(r)'(()))) ;; E (EVAL) (\ (x e) (? (s x) (V x e) ((\ (b j) (? (= b ") (a j) (? (= b \) x (? (= b ?) (? (E(a j)e) (E(a(d j))e) (E(a(d(d j)))e)) (? (s b) (A b (E(a j)e) (E (a(d j))e)) (E (a(d(d b))) (L(a(d b))j e))))))) (E (a x) e)(d x)))) ;; V (VALUE / symbol->value) (\ (x g) (? g (? (= x (a (a g))) (d (a g)) (V x (d g))) x)) ;; A (APPLY) but just for primitives (\ (f h v) (? (= f r) (r) (? (= f p) (p h) (? (= f s) (s h) (? (= f a) (a h) (? (= f d) (d h) (? (= f =) (= h v) (c h v)))))))) ;; L ( joint evLis / extend-env) (\ (k v i) (? k (L (d k) (d v) (c (c (a k) (E (a v) i)) i)) i))) ``` [Answer] # [GORBITSA](https://esolangs.org/wiki/GORBITSA), 493 bytes ``` S255 O253 R I188 B12 I68 o252 S1 O250 i252 S0 B2 S71 O255 S18 O254 S0 B134 B143 S79 O255 S25 O254 S0 B134 B149 S82 O255 S32 O254 S0 B134 B155 S66 O255 S39 O254 S0 B134 B158 S73 O255 S46 O254 S0 B134 B168 S84 O255 S53 O254 S0 B134 B172 S83 O255 S60 O254 S0 B134 B175 S65 O255 S67 O254 S0 B134 B179 S103 O255 S74 O254 S0 B134 B185 S111 O255 S81 O254 S0 B134 B193 S114 O255 S88 O254 S0 B134 B201 S98 O255 S95 O254 S0 B134 B207 S105 O255 S102 O254 S0 B134 B219 S116 O255 S109 O254 S0 B134 B224 S115 O255 S116 O254 S0 B134 B230 S97 O255 S123 O254 S0 B134 B239 G251 s253 I1 A252 B255 S2 i251 i250 S0 B12 g251 s253 I1 A255 b254 S1 i254 S0 b254 g250 O248 g248 O249 S0 B124 g250 O248 G249 o248 S0 B124 r249 S0 B124 G249 B162 S0 B124 g250 O251 I1 O250 S0 B12 g250 i249 S0 B124 t249 S0 B124 g250 O249 S0 B124 g250 O248 g248 i249 S0 B124 g250 O248 g248 O248 g248 O249 S0 B124 g250 O248 g248 O248 G249 o248 S0 B124 g250 O248 R o248 S0 B124 G249 B211 S0 B124 g250 O248 g248 O251 I1 O250 S0 B12 g250 A249 o250 S0 B124 g250 O248 g248 T S0 B124 g250 O248 g248 O248 G249 s248 O249 S0 B124 g250 O248 g248 O248 G249 a248 O249 S0 B124 ``` Since GORBITSA is kind of strange, I will specify that this runs in ROM mode, while the code it interprets is in RAM mode. Explaining this is kind of weird, but I'll do my best. The 256 command limit on ROM mode killed me for a while. # Explained (Full pseudocode I translated this to AFTER I wrote this (yeah, I wrote this with no extra utilities) can be found [here](https://repl.it/@ZippyMagician/gAssembler#new/self_interpreter)). ## Header: ``` S255 O253 R I188 B12 I68 o252 S1 O250 i252 S0 B2 ``` Essentially, this part takes the input. It reads STDIN and stores it in the next free spot in memory (starting at 0). If the input is char code 68 ("D"), it will branch to the letter parsing script. Otherwise, it branches back to the beginning of the header and takes another bit of STDIN. ## Letters: ``` S71 O255 S18 O254 S0 B134 B143 S79 O255 S25 O254 S0 B134 B149 S82 O255 S32 O254 S0 B134 B155 S66 O255 S39 O254 S0 B134 B158 S73 O255 S46 O254 S0 B134 B168 S84 O255 S53 O254 S0 B134 B172 S83 O255 S60 O254 S0 B134 B175 S65 O255 S67 O254 S0 B134 B179 S103 O255 S74 O254 S0 B134 B185 S111 O255 S81 O254 S0 B134 B193 S114 O255 S88 O254 S0 B134 B201 S98 O255 S95 O254 S0 B134 B207 S105 O255 S102 O254 S0 B134 B219 S116 O255 S109 O254 S0 B134 B224 S115 O255 S116 O254 S0 B134 B230 ``` This section is rather self-explanatory. For each letter, you increment by an amount and then branch to subtraction. If it is 0 (i.e. the current letter is whatever the line is checking) it will then branch to the letter's parsing. Otherwise, it jumps to the next letter. When all letters are done being checked, it jumps to Potential Exit ## Potential Exit ``` S97 O255 S123 O254 S0 B134 B239 G251 s253 I1 A252 B255 S2 i251 i250 S0 B12 ``` This section checks to see if there are no letters left to execute. If there are, it increments the pointers so they reference the next character + its argument, and then jump to the beginning of Letters. Otherwise, it terminates by branching to a null instruction. ## Subtraction ``` g251 s253 I1 A255 b254 S1 i254 S0 b254 ``` Very simple. Uses XOR subtraction to check if the current character is equal to a character stored in another part of memory (set by the letters section). ## Letter Evaluation ``` g250 O248 g248 O249 S0 B124 g250 O248 G249 o248 S0 B124 r249 S0 B124 G249 B162 S0 B124 g250 O251 I1 O250 S0 B12 g250 i249 S0 B124 t249 S0 B124 g250 O249 S0 B124 g250 O248 g248 i249 S0 B124 g250 O248 g248 O248 g248 O249 S0 B124 g250 O248 g248 O248 G249 o248 S0 B124 g250 O248 R o248 S0 B124 G249 B211 S0 B124 g250 O248 g248 O251 I1 O250 S0 B12 g250 A249 o250 S0 B124 g250 O248 g248 T S0 B124 g250 O248 g248 O248 G249 s248 O249 S0 B124 g250 O248 g248 O248 G249 a248 O249 S0 B124 ``` Each line corresponds to the same line in the Letters section. These simply interpret each character (G O R B I T S A g o r b i t s a) in descending order and then branch to Potential Exit. [Answer] # Concurrent Filesystem Befunge 98 - 53\18 bytes (almost certainly cheating) Full 53 byte interpreter with no restrictions (although I haven't tested complicated timing interactions involving IP splitting and wrapping): ``` v ;;;;;;;; >]390'ai@ t;;;;;;;; ;>zzzzz#; ``` Reads input from a file named `a` and executes it. It isn't specifed in the rules that we can't use self-modifying code. 18 byte interpreter that does not allow wrapping (the IP moving of one edge of the code and starting at the opposite edge): ``` ]210'ai@ t >< ``` [Answer] # [CHIQRSX9+](https://esolangs.org/wiki/CHIQRSX9%2B) , 2 bytes ``` +I ``` There's no way to write a self-interpreting interpreter in this [HQ9+](https://esolangs.org/wiki/HQ9%2B)-based language without using `I`, which runs a built-in interpreter that processes STDIN. ]
[Question] [ > > Be sure to see the other challenge, [Reverse ASCII character map](https://codegolf.stackexchange.com/q/137227/61563)! > > > The ASCII charset (American Standard Code for Information Interchange) is the most widely-used character encoding standard. ASCII codes represent text in computers, telecommunications equipment, and other devices. # Challenge Your challenge is to print a mapping of the ASCII character set as the user inputs them. GIF: [![gif](https://i.stack.imgur.com/Hg71L.gif)](https://i.stack.imgur.com/Hg71L.gif) After the user enters every ASCII character, the output should look like this: [![table](https://i.stack.imgur.com/vWmVH.png)](https://i.stack.imgur.com/vWmVH.png) # Mapping Each character has an assigned position on a 16x6 logical grid, starting with the space character in the top left position, and wrapping such that the digit 0 appears below it. When printable ASCII input is received, print that ASCII character at its assigned screen location without deleting any of the characters currently onscreen. # Rules * Your program only needs to map out the printable ASCII characters, `0x20` to `0x7E`. * Your program must not terminate and continue to map characters to the screen until all printable ASCII characters have been inputted. From here, your program can either terminate or run off into Neverland. * Your program can map characters any way you like, e.g. to a spreadsheet, table, console window, or a graphical window. * No matter how you display the mapping, it must be updated in realtime (as soon as it receives user input). * If your program does not read input silently, it must put the cursor out of the way, so the text won't get in the way of the map. # Help Here is the pseudocode algorithm I used to generate the GIF: ``` loop forever c = input y_coord = c / 16 x_coord = c - y * 16 if c is printable print c at (x_coord * 2 + 1, y_coord + 1) end if end loop ``` There may be another way to achieve the required output. You can choose to use my algorithm or your own, but the output must be the same regardless. [Here's a useful ASCII table reference.](http://www.asciitable.com/) # Scoring The answer with the least bytes in each language wins. Have fun! [Answer] ## JavaScript (ES6) + HTML, 114 + 16 = 130 bytes *Saved 16 bytes thanks to @Shaggy* ``` a=Array(96).fill` `;onkeypress=k=>(a[k.key.charCodeAt()-32]=k.key,O.innerText=a.join` `.match(/.{1,32}/g).join` `) ``` ``` <pre id=O></pre> ``` It's so unbelievably satisfying to just mash the keyboard... [Answer] ## QBasic 4.5, ~~81~~ 85 bytes *Added 4 bytes to comply with the spacing-rule.* ``` DO LOCATE 7,1 LINE INPUT A$:i=ASC(A$) LOCATE i\16-1,(i MOD 16+1)*2 ?CHR$(i) LOOP ``` And the output will look like this (NOTE: Old screenshot, now every character is separated by a space):[![enter image description here](https://i.stack.imgur.com/crHxr.png)](https://i.stack.imgur.com/crHxr.png) QBasic has the `LOCATE` command, which comes in handy here. A breakdown of this code: ``` DO Starts an infinite loop LOCATE 7,1 Moves the cursor out of the way LINE INPUT A$:i=ASC(A$) LINE INPUT gets user input; we need LINE INPUT instead of regular input for support of <space> and <comma>. The ASC() function then takes the ASCII value of the first character in the input, so it can deal with inputs like 'Hello' - it will take ASC('H') and assign that to 'i' LOCATE i\16-1 Here's the cool bit: LOCATE takes a row and a column to put the cursor on. ,(i MOD 16+1)*2 Row is determined by dividing the ASC value by 16, minus 1 (SPACE, ASC 32 is placed on row 1), and for columns we take the modulo plus 1 (Again, SPACE mod 16 = 0, plus 1 = column 1). Multiplied by 2 gives us the spacing. We move the cursor to 1,2 ?CHR$(i) PRINT a cast of the ASCII value to CHR at the specified location. LOOP Ad infinitum ``` [Answer] # [Java 8](http://docs.oracle.com/javase/8/docs/), 143 bytes ``` o->{for(;;){char c=System.console().readPassword()[0];if(c>31&c<127)System.out.println(String.format("\u001B[%d;%df%c",c/16+1,(c%16+1)*2,c));}} ``` Uses the [ANSI control code](https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes) `CSI n ; m f` to set the cursor position and [`Console.readPassword()`](https://docs.oracle.com/javase/7/docs/api/java/io/Console.html#readPassword()) to read the user input silently. Output of some characters: [![sscreenshot](https://i.stack.imgur.com/uLmnh.png)](https://i.stack.imgur.com/uLmnh.png) [Answer] # [BrainFuck](https://en.wikipedia.org/wiki/Brainfuck), 355 Bytes ``` >>++++[->++++[->+>++++++<<]<]>>->[-<[-<<<<++++[->++++++++<]]>>>[<<<<<++++++++[->>++<<<+>]>>-<<<++>>]<<[>>>>>>[>>>]>+<<<<<[<<<]<<-]>>>>>>[>>>]++++[-<++++++++>]>[-<+>]<<[<<<]>>]<[-]<<,[[->+>+<<],[-]++++[->>--------<<]>>[>>>>[>>>]+[<<<]<-]>>>>[>>>]<<[-]<[<<<]<<[>>>>>[>>>]<<+<[<<<]<<-]>>>>>[>>>]<<<[[-]<<<]>[.>.>>]++++++++++[->+>++<<]>>[-<.>]<[-]<<<<[<<<]<,] ``` BrainFuck's options are pretty limited, so output is in the terminal and the screen is "cleared" with 20 newlines. Input should be the ASCII characters, separated by newlines. [Try it online!](https://tio.run/##XY/rSgUxDIT/f8@hona7ePkbAt5vjxAqqCCIetSjx7vPvrbZ7roYCm1nJpPJ5fziZna9uLrtOtWQy@J4@SMEkSRJNapFySfXROeClGk1GahKa2mVoKXXGdUkYupVrqTBe0pnZmKaUL3HaJe15ecGRV2sLOZfY33SjDUZGEbHWi61P9d@VD/JEXGbmsB0god/uSos5nOzr7Xa1qTjzsGXLjOjtEPGYcMmdd0Ou@yxzwGHHHHMCaecccc9Mx545Ik5z7yw4JU33vngky9@WGWNb4zEBptssc0Sy5yzwjq/ "brainfuck – Try It Online") ## Formatted and Documented These are the debug notes I used to write the program. I used [my interpreter](https://github.com/BrainSteel/BrainF-k) which can optionally print the state of the tape at every '~' character for debugging. ``` [ run.bf codegolf.stackexchange.com/questions/124306/map-inputted-ascii-characters ] [ Calculate 16 * 6 Resulting tape state: [0 0 0 0 0 0 16 96 0 0 0 0 ...] ^ Note that, to obtain a 16-by-6 grid, the 16 immediately to the right is decreased to 15 (since we will decrease it by 1 each loop until we reach 0 and immediately reset) ] >>>>++++[->++++[->+>++++++<<]<]>~ [ Our next goal is to make 96 sets of 3 cells each in the pattern [C D 0] The first cell will represent an entered character--when the corresponding input on the keyboard is pressed, it will change to the entered key. The first cell is initialized to 32 (' '). The second cell will represent the delimiter after that character. Every 16 cells, this should be 10 for '\n'. Otherwise, it should be 32 for ' '. The third cell is a buffer cell, used for traversal of the grid. In general, it should be only temporarily modified and then reset to 0. ] >->[-< [ -<<<<++++[->++++++++<] [ The second cell of our 3-set should be 32, so the above line writes 32 to the 3rd cell from the beginning of the tape (0-indexed) ] ] >>> [ <<<[ The second cell of our 3-set should be 10, and we must reset the line counter ] <<++++++++[->>++<<<+>]>>-<<<++>> ] [ At this point, the delimiting cell we need is two cells to the left. ] <<[>>>>>>[>>>]>+<<<<<[<<<]<<-] >>>>>>[>>>]++++[-<++++++++>] [ Debug Mode: In the previous loop, add a + in the string of 8 +'s to get visible spaces in the grid ($-signs) ] >[-<+>]<<[<<<]>> ] [ Go back to the beginning of the tape and clear up the residual '15' ] <[-]~ <<, [ [->+>+<<],[-]++++[->>--------<<] [ Take input such that the state of the tape now looks like this: [0 0 0 0 0 c c-32 0 32 32 0 32 32 0 32 32 0 ...] ^ Where 'c' was the entered character. We now set up 1's in the buffer zones of the first c-32 3-sets and clear the character that is currently there. All that is left, then, is to copy c to that location. ] [ Set up the row of 1's. ] >>[>>>>[>>>]+[<<<]<-] [ Clear the current character. ] >>>>[>>>]<<[-]~<[<<<] [ Copy the new character. ] <<[>>>>>[>>>]<<+<[<<<]<<-] [ Clean up the 1's. ] >>>>>[>>>]~<<<[[-]<<<] [ Print the grid. ] >[.>.>>]~ [ Print a bunch of newlines ] ++++++++++[->+>++<<]>>[-<.>]<[-] [ Take a new input. ] <<<<[<<<]<, ] ``` [Answer] ## Mathematica, 108 bytes ``` a=" "~Table~16~Table~6;Dynamic@Grid@a ((a[[⌊#/16⌋-1,#~Mod~16+1]]=i)&@ToCharacterCode[i=Input[]];#0[])&[] ``` Try it online at <https://sandbox.open.wolframcloud.com/> When you paste code and press `Shift+Enter`, a dialog box will pop up, you enter `"a"` for example for character `a`. The program runs forever. Note: On Wolfram sandbox, the font is formatted differently from that in Mathematica in my computer. So the line/column spacing may looks weird. [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` s='\n'.join([' '*31]*6) while 1: c=input();i=ord(c) if 31<i<128:i-=32;i=i%16*2+i//16*32;s=s[:i]+c+s[i+1:];print s ``` [Try it online!](https://tio.run/##JY3tSsNAFET/z1NcEdl8UOtuNK1pF7RWfYgYJO4m7ZWyCbuRUnz4NNZfc5gzMP1p2HdOjez6n0H7@vh5oTFo8eHE7XfHLioFiSSTVZLHOO750JAsQEZfllG8Yt15G5kYxC1lcs1rqZYFz3SmJsc3Mk9UyvP5lFMTdCgLrlKThpJTWVSr3rMbKIz0D2L290bXVFvbWGo7T@ZQex5O4y@ukOAJNb5gYNGgxQ7PeMEr3rHBFm94xBIL5HjAPTIoSNydAQ "Python 2 – Try It Online") Requires quotation marks (single or double) around the inputted characters (the TIO version does not). [Answer] # [str](https://github.com/ConorOBrien-Foxx/str), noncompeting, 18 bytes Presenting my new semi-esoteric language. ``` #C;dby16#/~2-~u#pq ``` [![Animated GIF](https://i.stack.imgur.com/fnm77.gif)](https://i.stack.imgur.com/fnm77.gif) ``` #C;dby16#/~2-~u#pq ..; preamble #C clear screen ............... main program; each character is pushed to the stack before d duplicate b buffer the character y convert to character code 16#/ divmod by 16 (a / b, a % 6) ~2-~ subtract a / b by 2 u unbuffer the character #p place that character in the given position q "quiet"; disable auto-printing ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~53~~ 57 bytes Added 4 bytes for the spacing. ``` {locate 7,1┘_?┘i=asc(A)┘locate i/16-1,(i%16+1)*2┘?chr$(i) ``` QBIC began development as a shorthand for QBasic, so I thought translating my [QBasic answer](https://codegolf.stackexchange.com/a/124345/44874) would demonstrate this nicely. We've saved some 40% in the byte-count for a functionally identical program - and that's even when `LOCATE`, `ASC`, and `CHR` have no QBIC-functions yet. Fortunately, QBIC can pass code directly to QBasic to compensate for this. A side-by-side: ``` QBIC QBASIC ------------ ------------ { DO locate 7,1 LOCATE 7,1 note that the lower-case alphabet is left unaltered in QBIC. _? LINE INPUT A$ (LINE INPUT used instead of INPUT to handle comma's) i=asc(A) i=ASC(A$) locate i/16-1 LOCATE i/16-1 ,(i%16+1)*2 ,(i MOD 16+1)*2 ?chr$(i) ?CHR$(i) LOOP (implicitly added to QBIC at EOF) ``` [Answer] ## Haskell, 133 bytes ``` p=putStr.("\27["++) g l=do c<-getChar;p"2J";mapM h(c:l);g(c:l) h c|(y,x)<-divMod(fromEnum c)16=p$show y++';':show(2*x+1)++'H':[c] g[] ``` Requires a terminal that understands ANSI escape sequences. It's shorter to keep a list of all keys pressed so far and clearing the screen before printing all of them each round than turning off the echo in the terminal session. The latter needs `import System.IO` and `hSetEcho stdin(2<1)` which costs too many bytes. [Answer] # C, 101 bytes ``` c,y,x;f(){while(~(c=getchar()))printf("\e[1;20H"),y=c/16,x=c-y*16,printf("\e[%d;%dH%c",y+1,x*2+1,c);} ``` This was the program I used to make the graphics. Output is as shown in the GIF. ;) [Answer] # QBasic, ~~62~~ 58 bytes ``` a=ASC(INPUT$(1)) LOCATE a\16-1,1+2*(a MOD 16) ?CHR$(a) RUN ``` Tested with [QB64](http://qb64.net). Should work fine on regular QBasic, too, although you may want to modify it to do a `CLS` on the first run. Similar to [steenbergh's answer](https://codegolf.stackexchange.com/a/124345/16766), but uses `INPUT$(1)` to read characters one at a time. This approach is shorter and also displays no prompt. It also uses `RUN` for the infinite loop, since we don't have to store any state between iterations except the state of the screen. [Answer] # Ruby, ~~79~~ ~~75~~ 71 + 13 = 84 bytes +13 bytes for `-rio/console` flag. ``` loop{$/+=STDIN.getch 97.times{|n|print$/[(n+31).chr]||" ",[" "][n%16]}} ``` ## Ungolfed ``` loop { $/ += STDIN.getch 97.times {|n| print $/[(n+31).chr] || " ", [" "][n%16] } } ``` [Answer] ## Pascal, 112 chars ``` Uses crt;var c:char;Begin ClrScr;repeat c:=ReadKey;GotoXY(ord(c)and$F*2+1,ord(c)shr 4-1);write(c);until 1<0;End. ``` As my Mathematica solution takes many bytes in `div`, `mod` and `ToCharacterCode[Input[]]`, I try making another answer with Pascal. But without `ClrScr` my compiler (FPC) left some compile information on the screen. `ClrScr;` takes 7 bytes. The `*2` used for proper spacing takes another 2 bytes. [Answer] ## LOGO, 90 bytes ``` cs rt 90 keyboardon[invoke[setxy 30*modulo ? 16 -30*int ?/16 label char ?]keyboardvalue]pu ``` Try it on FMSLogo. After all, my Logo solution is the shortest, compared with my Mathematica and Pascal answer. Add 3 bytes if the turtle is required to be hidden. [Answer] # 6502 machine code + Apple //e ROM, 31 bytes Hex dump: ``` 8000- 20 58 FC 20 0C FD 48 38 8008- E9 A0 48 29 0F 0A 85 24 8010- 68 4A 4A 4A 4A 20 5B FB 8018- 68 20 ED FD 4C 03 80 ``` Commented assembly: ``` 1 HTAB = $24 ; HORIZONTAL POSITION OF CURSOR 2 SETVTAB = $FB5B ; SETS VERTICAL POSITION OF CURSOR FROM ACC 3 COUT = $FDED ; OUTPUTS CHARACTER IN ACC 4 HOME = $FC58 ; CLEARS SCREEN 5 RDKEY = $FD0C ; GETS CHARACTER FROM KEYBOARD, STORES IN ACC 6 ORG $8000 7 JSR HOME 8 GETINP JSR RDKEY 9 * POSITION CURSOR 10 PHA ; PRESERVE ACC 11 SEC ; MAKE SURE CARRY IS SET TO SUBTRACT 12 SBC #" " ; SUBTRACT CHAR CODE OF SPACE 13 PHA ; SAVE ACC 14 AND #$0F ; GET LOWER 4 BITS TO GET CURSOR X POSITION 15 ASL ; SHIFT LEFT TO MAKE SPACES BETWEEN CHARS 16 STA HTAB 17 PLA ; GET OLD ACC 18 LSR ; SHIFT HIGH NIBBLE 19 LSR ; INTO LOW NIBBLE 20 LSR ; TO GET CURSOR Y POSITION 21 LSR 22 JSR SETVTAB 23 PLA ; RESTORE ACC 24 * 25 JSR COUT 26 JMP GETINP ``` ![GIF demo](https://i.stack.imgur.com/mF2Nf.gif) If the cursor invalidates it, here's a 36-byte version without a cursor: ``` 8000- 20 58 FC AD 00 C0 10 FB 8008- 8D 10 C0 48 38 E9 A0 48 8010- 29 0F 0A 85 24 68 4A 4A 8018- 4A 4A 20 5B FB 68 20 ED 8020- FD 4C 03 80 ``` [Answer] # SmileBASIC 3, 82 bytes ``` CLS @L C$=INKEY$()IF""!=C$THEN V=ASC(C$)-32LOCATE V MOD 16*2,V DIV 16*2?C$; GOTO@L ``` In the SmileBASIC character set, `¥` is located where `\` normally would be; hopefully this doesn't invalidate this answer completely. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~63~~ 43 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Seeing as I apparently have a reputation for making Japt do things it shouldn't be able to do (continuous input, in this case), golfing from my my phone, and golfing with a feed of beer inside me, it's high time I combined all 3 of those things! ``` ;$oninput=$@OqE¬ËoOx`Í*s.value` 1Ãú ò16 m¸· ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=OyRvbmlucHV0PSRAT3FFrMtvT3hgzSpzLnZhbHVlYCAxw/og8jE2IG24tw&footer=T3hgzSpzLnDCwXROb7guY9OVTIl0Lpy2dmUoJ6ylYXCgZCcpO80qcy5mb2OrKClgIFA) (just start typing in the "Notes" field) [Answer] # [Applesoft BASIC](//en.wikipedia.org/wiki/Applesoft_BASIC), 134 bytes ``` 0TEXT:HOME:PR#0 1C=PEEK(49152):POKE49168,0:HTAB1:VTAB20:NORMAL:IFC>=128THENC=C-128:INVERSE 4Y=INT(C/16):X=C-Y*16:HTABX*2+1:VTABY+1:IFC>=32THEN PRINTCHR$(C):IFC<32THEN PRINTCHR$(127) 9GOTO1 ``` This is a golfed version of the Apple ][ keyboard test, the program that inspired the challenge. [Answer] # 8086 machine code, MS-DOS .COM, 27 bytes Runnable in DOSBox. The only assumption about register starting values is `AH = 0`, which is [true for most DOS isotopes](http://www.fysnet.net/yourhelp.htm). This, and the fact that only BIOS interrupts are used, means it can be run from a boot sector by changing the first instruction to `mov ax, 3` (and the `org` of course) at the terrible, terrible cost of one byte. Expects only printable ASCII characters as input. Does not terminate. ## Binary ``` 00000000 : B0 03 CD 10 31 C0 CD 16 50 2C 20 D4 10 D0 E0 92 : ....1...P, ..... 00000010 : B4 02 CD 10 58 B4 0E CD 10 EB E9 : ....X...... ``` ## Assembly ``` org 0x100 cpu 8086 mov al, 3 ; Set video mode to 80x25 text int 0x10 ; Has the desired side-effect of clearing the screen main_loop: xor ax, ax ; Read keystroke into AX int 0x16 ; AH = scan code, AL = ASCII push ax ; Save ASCII code for later sub al, 32 ; Make ASCII code into range 0..94 aam 0x10 ; AH = AL / 16 (row), AL = AL % 16 (col) shl al, 1 ; Double column for spacing xchg ax, dx ; Move cursor to proper position mov ah, 2 int 0x10 pop ax ; Retrieve ASCII code mov ah, 0x0e ; Output at cursor position int 0x10 jmp main_loop ``` ]
[Question] [ # Goal Write a program or function that translates a numerical telephone number into text that makes it easy to say. When digits are repeated, they should be read as "double n" or "triple n". # Requirements ## Input A string of digits. * Assume all characters are digits from 0 to 9. * Assume the string contains at least one character. ## Output Words, separated by spaces, of how these digits can be read out loud. * Translate digits to words: 0 "oh" 1 "one" 2 "two" 3 "three" 4 "four" 5 "five" 6 "six" 7 "seven" 8 "eight" 9 "nine" * When the same digit is repeated twice in a row, write "double *number*". * When the same digit is repeated thrice in a row, write "triple *number*". * When the same digit is repeated four or more times, write "double *number*" for the first two digits and evaluate the rest of the string. * There is exactly one space character between each word. A single leading or trailing space is acceptable. * Output is not case sensitive. # Scoring Source code with the least bytes. # Test Cases ``` input output ------------------- 0123 oh one two three 4554554 four double five four double five four 000 triple oh 00000 double oh triple oh 66667888 double six double six seven triple eight 19999999179 one double nine double nine triple nine one seven nine ``` [Answer] # 8088 Assembly, IBM PC DOS, ~~164~~ ~~159~~ ~~156~~ 155 bytes **Binary:** ``` 00000000: d1ee 8a0c 03f1 53fd ac3a d075 0343 e2f7 ......S..:.u.C.. 00000010: 85db 741c 5f8a d043 f6c3 0174 0a57 bd64 ..t._..C...t.W.d 00000020: 0155 83eb 0374 0957 bd5d 0155 4b4b 75f7 .U...t.W.].UKKu. 00000030: 8ad0 2c2f 7213 518a f0b0 24b1 31bf 6a01 ..,/r.Q...$.1.j. 00000040: fcf2 aefe ce75 fa59 57e2 bc5a 85d2 740c .....u.YW..Z..t. 00000050: b409 cd21 b220 b402 cd21 ebef c364 6f75 ...!. ...!...dou 00000060: 626c 6524 7472 6970 6c65 246f 6824 6f6e ble$triple$oh$on 00000070: 6524 7477 6f24 7468 7265 6524 666f 7572 e$two$three$four 00000080: 2466 6976 6524 7369 7824 7365 7665 6e24 $five$six$seven$ 00000090: 6569 6768 7424 6e69 6e65 24 eight$nine$ ``` Build and test executable using `xxd -r` from above, or download [PHONE.COM](https://stage.stonedrop.com/ppcg/PHONE.COM). **Unassembled listing:** ``` D1 EE SHR SI, 1 ; point SI to DOS PSP (80H) for input string 8A 0C MOV CL, BYTE PTR[SI] ; load input string length into CX 03 F1 ADD SI, CX ; move SI to end of input 53 PUSH BX ; push a 0 to signal end of output stack CHAR_LOOP: FD STD ; set LODS direction to reverse AC LODSB ; load next char from [SI] into AL, advance SI 3A D0 CMP DL, AL ; is it same as previous char? 75 03 JNZ NEW_CHAR ; if not, it's a different char 43 INC BX ; otherwise it's a run, so increment run length E2 F7 LOOP CHAR_LOOP ; move on to next char NEW_CHAR: 85 DB TEST BX, BX ; is there a run greater than 0? 74 1C JZ GET_WORD ; if not, look up digit name 5F POP DI ; get name for the current digit 8A D0 MOV DL, AL ; save current char in DL 43 INC BX ; adjust run count (BX=1 means run of 2, etc) F6 C3 01 TEST BL, 1 ; is odd? if so, it's a triple 74 0A JZ IS_DBL ; is even, so is a double 57 PUSH DI ; push number string ("one", etc) to stack BD 0164 MOV BP, OFFSET T ; load "triple" string 55 PUSH BP ; push to stack 83 EB 03 SUB BX, 3 ; decrement run count by 3 74 09 JZ GET_WORD ; if end of run, move to next input char IS_DBL: 57 PUSH DI ; push number string to stack BD 015D MOV BP, OFFSET D ; load "double" string 55 PUSH BP ; push to stack 4B DEC BX ; decrement by 2 4B DEC BX 75 F7 JNZ IS_DBL ; if not end of run, loop double again GET_WORD: 8A D0 MOV DL, AL ; save current char into DL 2C 2F SUB AL, '0'-1 ; convert ASCII char to 1-based index 72 13 JB NOT_FOUND ; if not a valid char, move to next 51 PUSH CX ; save outer loop counter 8A F0 MOV DH, AL ; DH is the index to find, use as scan loop counter B0 24 MOV AL, '$' ; word string is $ delimited B1 31 MOV CL, 031H ; search through length of word data (49 bytes) BF 016A MOV DI, OFFSET W ; reset word data pointer to beginning FC CLD ; set DF to scan forward for SCAS SCAN_LOOP: F2/ AE REPNZ SCASB ; search until delimiter '$' is found in [DI] FE CE DEC DH ; delimiter found, decrement counter 75 FA JNZ SCAN_LOOP ; if counter reached 0, index has been found 59 POP CX ; restore outer loop position 57 PUSH DI ; push string on stack NOT_FOUND: E2 BC LOOP CHAR_LOOP ; move to next char in input OUTPUT_STACK: 5A POP DX ; get string from top of stack 85 D2 TEST DX, DX ; it is the last? 74 0C JZ EXIT ; if so, exit B4 09 MOV AH, 09H ; DOS display string function CD 21 INT 21H ; write string to console B2 20 MOV DL, ' ' ; load space delimiter B4 02 MOV AH, 02H ; DOS display char function CD 21 INT 21H ; write char to console EB EF JMP OUTPUT_STACK ; continue looping EXIT: C3 RET ; return to DOS D DB "double$" T DB "triple" W DB "$oh$","one$","two$","three$","four$","five$","six$","seven$","eight$","nine$" ``` **TL;DR:** The input string is read right to left to make it easier to find a triple. The output is pushed onto the [x86 stack](https://en.wikipedia.org/wiki/Intel_8086#Registers_and_instructions) to simplify reversing out the display order and also facilitate rearranging the "double" and "triple" words to precede the digit's name. If the next digit is different than the last, the name is looked up in the list of words and pushed on to the stack. Since there's no formal concept of an "indexed array of variable-length strings" in machine code, the list of words is scanned `i` (the word's index) number of times for the string delimiter (`$`) to find the corresponding word. Helpfully, x86 does have a pair of short instructions (`REPNZ SCASB` which is similar to `memchr()` in C), that simplifies this (thanks [CISC](https://en.wikipedia.org/wiki/Complex_instruction_set_computer)!). If the digit is the same as the previous one, the counter for the length of a "run" is incremented and continues looping leftward on the input. Once the run is over, the digit's name is taken from the stack since it will need to placed after the "double" or "triple" for each grouping. If the length of the run is odd (and run length is `> 1`), the digit's name followed by the string "triple" is pushed to the stack and the run length is reduced by 3. Since the run length will now be even, the step is repeated for "double" until the run length is 0. When the input string has reached the end, the stack is dumped out with each saved string written to the screen in reverse order. **I/O:** A standalone PC DOS executable, input from command line output to console. [![enter image description here](https://i.stack.imgur.com/tf3tx.png)](https://i.stack.imgur.com/tf3tx.png) Download and test [PHONE.COM](https://stage.stonedrop.com/ppcg/PHONE.COM). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~53~~ ~~52~~ ~~51~~ ~~50~~ 49 bytes ``` γε€T2äθ¬MÊi¨₃1ǝR]˜“Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‹¶½¿“#s踻 ``` [Try it online!](https://tio.run/##AYEAfv9vc2FiaWX//86zzrXigqxUMsOkzrjCrE3DimnCqOKCgzHHnVJdy5zigJzFoMOn4oKswrXigJrigKLigJ7DreKAoMOsy4bDiMWSxaHDr8K/xbjCr8KlxaDigLnCtsK9wr/igJwjc8OowrjCu///NjY2Njc4ODg4OP8tLW5vLWxhenk "05AB1E – Try It Online") Explanation: ``` γ # split input in groups of consecutive equal digits ε ] # for each group €T # add a 10 before each digit (66 -> [10, 6, 10, 6]) 2äθ # keep only the second half of that list ¬MÊi ] # if the first element is not the maximum ¨ # drop the last element ₃1ǝ # replace the second element with 95 R # reverse the list ˜ # flatten “...“ # compressed string: "oh one two ... nine double triple" # # split on spaces sè # index (wraps around, so 95 yields "triple") ¸» # join with spaces ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~61~~ ~~56~~ ~~53~~ ~~52~~ 51 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` γvyDg;LàäRv… ‹¶½¿#yg蓊瀵‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“#yè])áðý ``` -9 bytes thanks to *@Grimy*. [Try it online](https://tio.run/##AXUAiv9vc2FiaWX//86zdnlEZztMw6DDpFJ24oCmIOKAucK2wr3CvyN5Z8Oo4oCcxaDDp@KCrMK14oCa4oCi4oCew63igKDDrMuGw4jFksWhw6/Cv8W4wq/CpcWg4oCcI3nDqF0pw6HDsMO9//8xOTk5OTk5OTE3Nzk) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/3Obyypd0q19Di84vCSo7FHDMoVHDTsPbTu099B@5cr0wyseNcw5uuDw8kdNaw5tfdQw61HDokcN8w6vfdSw4PCa022HO45OOrrw8PpD@4/uOLT@0NKjC4DqlSsPr6it1Ty88PCGw3v/6/w3MDQy5jIxNQUhLgMDAy4zIDC3sLDgMrSEAENzc0sA). **Explanation:** ``` γ # Split the (implicit) input into substrings of equal adjacent characters # i.e. "199999991779" → ["1","9999999","1","77","9"] v # Loop over each substring `y`: Dg # Get the length of a copy of the substring ; # Halve it L # Create a list in the range [1, length/2], where odd lengths are # automatically truncated/floored # i.e. "1" (length=1) → 0.5 → [1,0] # i.e. "9999999" (length=7) → 3.5 → [1,2,3] à # Pop and push the maximum of this list y ä # Divide the string into that many parts # → ["1"] # → ["999","99","99"] R # Reverse the list # → ["99","99","999"] v # Inner loop over each item `y`: … ‹¶½¿ # Push dictionary word: " double triple" # # Split it on spaces: ["","","double","triple"] yg # Get the length of the current item `y` è # And use it to (0-based) index into the list “Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“ # Push dictionary string "oh two three four five six seven eight nine" # # Split it on spaces: ["oh","two","three",...,"nine"] yè # Use `y` to index into the string-list (with automatic wrap-around, # so since there are 10 words, it basically indexes with a single digit # due to an implicit modulo-10) # i.e. "77" → "seven" ] # Close both loops ) # Wrap all values on the stack into a list á # Only keep letters, which removes the empty strings from the list ðý # And join the list on spaces # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `… ‹¶½¿` is `" double triple"` and `“Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“` is `"oh two three four five six seven eight nine"`. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 137 [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") Title case with a leading space. ``` ∊¯2↑¨@(∊∘⎕A)⍵ (.)\1* {⍺←(,¨⎕D)⎕R('OhOneTwoThreeFourFiveSixSevenEightNine'(∊⊂⊣)⎕A)⋄' '∊w←⍺,⊃⍵:⍬⋄1=≢⍵:⍺⍵⋄3=≢⍵:'Triple',w⋄'Double',w,∇2↓⍵}⍵M ``` [Try it online!](https://tio.run/##KyxNTCn6//9RR9eh9UaP2iYeWuGgAeQ86pjxqG@qo@aj3q1cGnqaMYZaXNWPenc9apugoXNoBVDKRRNIBGmo@2f456WGlOeHZBSlprrllxa5ZZalBmdWBKeWpea5ZqZnlPhl5qWqg83sanrUtVgTYm53i7qCOlCwHGgk0GCdR13NQLusHvWuAUoZ2j7qXATh7gJSQBFjmIh6SFFmQU6quk45yAiX/NIkMEfnUUc70PmTgUpqgdj3/39DSwgwNLfkMjA0MuYyMTUFIS4DAwMuMyAwt7Cw4EJSBQA "QuadR – Try It Online") `∊` **ϵ**nlist (flatten) `¯2↑¨` take the last two characters (padding on left with a space) of each characters `@` at positions where `(∊∘⎕A)` characters are members of the uppercase **A**lphabet `⍵` in the result of the below PCRE Replace operation… `(.)` any character `\1` followed by itself `*` zero or more times, is replaced by the result of the following… `{…}⍵M` "dfn"; `⍵` is the **M**atch of the above pattern  `('OhOneTwoThreeFourFiveSixSevenEightNine'(`…`)⎕A)` apply the following anonymous tacit function with the long string and the uppercase **A**lphabet as left arguments:  `∊` membership (of letters in the long string in the uppercase alphabet)  `⊂` partitions (with a new partition beginning whenever is-a-member  `⊣` the left argument (i.e. the long string) `(`…`)⎕R` PCRE **R**eplace the following patterns with those words:  `⎕D` the digits 0 through 9  `,¨` treat each as a separate pattern `⍺←` assign this replacement function to `⍺` (for **a**lphabetise) `⋄` then, `⊃⍵` the first character of the match `,` as a string `⍺` apply `⍺` to it `w←` assign this to `w` (for **word**) `' '∊`…`:` if space is a member thereof (i.e. if the match was empty):  `⍬` return nothing (becomes the empty string) `⋄` else, `1=≢⍵:` if one equals the tally of characters in the match (i.e. its length):  `⍺⍵` alphabetise that digit `⋄` else, `3=≢⍵:` if three equals the tally of characters in the match (i.e. its length):  `'Triple',w` prepend "Triple" to the **w**ord `⋄` else, `2↓⍵` drop to digits from the match `∇` recurse on that `w,` prepend the word `'Double',` prepend "Double" [Answer] # JavaScript (ES6), ~~161 160 152~~ 144 bytes The output includes a single leading space. ``` s=>[n=>' '+'oh/one/two/three/four/five/six/seven/eight/nine'.split`/`[n],'$1 double$2','triple$2'].map(r=>s=s.replace(/(\S*)( \S+)\2|\d/g,r))&&s ``` [Try it online!](https://tio.run/##bVDLboMwELz3K6woik1DWaBNQw7wEzmGSKGwPCpqI@zQHvrv1DakSlFXHMZoZ3Zm3rMhk3nfdOqJiwLHMh5lnJx4nFBCt1TUIDiC@hSg6h4RSnHtoWwGBNl8gcQBOWBT1Qp4w5F6smsbdYHLiZ9dug5IIa5vLa5D6lKlr1h49j6yjvVxImPp9di1WY4MWHp8dBhJj1snDb/TAiq3d5zNRo654FK06LWiYiVb@UH4vHIcchsAImqibRJtk1ibDwvKy25nvl@Wppggszti8vz/Yynk@/79aSM0xdIWlruvevZRFN0IeneW19XdQ9viTceWuZQKDtME@4NVM5F13lnDNP8Hz1IWm73pgHmOPw "JavaScript (Node.js) – Try It Online") or [See the formatted source code](https://tio.run/##bVHbboMwDH3vV1hVVWDtMLB1pQ/dT/SxVCoDc5lYgghle9i/MyfA1KE5sWRHx8c@znvcxSppyrp9FDKlPjv2Co6vC4AzO4DgBCw@G7BkgVIQtp8S26IhwkzeGszKjlCVX6ioI4FU5kWLohRkuaquyvaK17O4bA2btfIhlbe3ilaBNT613NzknF7Y3Y@4tpthBgAeBpTbUF3FCdloR6cHx4botHGi4DtKMd9C4zBS@3oNqk@kULIit5K5ndlLzw@elo4DkyGCLIBlAMsAI2MxK3ne7fT9reISLXQcHLTe/x/mRJ7n3bfWRINYHmGOfWHbh2E4FTB2pOfV3odmyxOPWfacyj8M5u8Phk1LZr0jh/6ZP/FIZWKNGxrotP8B) ## How? The conversion is processed in three steps: 1. replace each digit with the corresponding English word, preceded by a space 2. replace each pattern `"X X"` with `"double X"` 3. replace each pattern `"double X X"` with `"triple X"` To save bytes, we use the same regular expression for all steps: ``` /(\S*)( \S+)\2|\d/g ``` which works as follows: ``` (\S*) -> 1st capturing group: any word, or nothing at all ( \S+) -> 2nd capturing group: a space, followed by a word \2 -> a copy of the 2nd capturing group |\d -> or try to capture a digit instead (for step 1) ``` At step 1, we use a callback function that picks the correct word from a lookup table: * `"799999"` → `" seven nine nine nine nine nine"` At step 2, we replace with `"$1 double$2"`: * `" (seven)( nine)( nine)"` → `" seven double nine"` * `"( nine)( nine) nine"` → `" double nine nine"` At step 3, we replace with `"triple$2"`: * `" (double)( nine)( nine)"` → `" triple nine"` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 115 bytes ``` {Switch[L=Tr[1^{##}],1," ",3," triple ",_," double "],If[#<1,"oh",IntegerName@#],If[L>3,#0@##3,""]}&@@@Split@#<>""& ``` [Try it online!](https://tio.run/##VY1NC4JAEIbv/orYAU8TafYllOxVkCjsJhZmay5kiqx0WPa322x1iQde5p13PppC1aIplCyLsdqNOn1JVdZZsjv1mX/WACZHH9mEYUCqetk9BJkLmVs7XK3JMa4y2NJUWzOMn0rcRb8vGsHhEyVRgOBxALrAcuNyztPuIRWHbcSYOx4HKRQ/9PKpMphGFa25M64d7dHnOQYGHb3AJfFT2/CQsMUKv6xxY7EtH8M/fApD45jxDQ "Wolfram Language (Mathematica) – Try It Online") Takes a list of digits as input. Output includes a leading space. [Answer] # [Stax](https://github.com/tomtheisen/stax), 56 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÇÖ◘⌡¿╒ô╞Γ▓8m☻t7♦3├(Ä⌂≤(┬Ω☻9▲ç╕C╞⌡òσ╗─╣╥─☻╪▼⌡5■ÿ,(┬¥?☺÷•± ``` [Run and debug it](https://staxlang.xyz/#p=809908f5a8d593c6e2b2386d0274370433c3288e7ff328c2ea02391e87b843c6f595e5bbc4b9d2c402d81ff535fe982c28c29d3f01f607f1&i=%2201234%22%0A%224554554%22%0A%22000%22%0A%2266667888%22%0A%2219999999179%22%0A%2200000%22&a=1&m=2) [Answer] # [Python 2](https://docs.python.org/2/), ~~171~~ ~~169~~ 168 bytes ``` s=input() while s:c=s[0];n=(s[1:2]==c)+(s[:3]==c*3!=s[1:4]);print' eellpbiurotd'[-n:0:-2]+'oh one two three four five six seven eight nine'.split()[int(c)],;s=s[1+n:] ``` [Try it online!](https://tio.run/##JY/NboMwEITvfootF0NJKgOhIUZ@EmRVLVliS2iNbJOfp6emHa1Wn/awM7O8onFUb6O7osqybAvK0rLGvGAPY2eEIEcVBqF7UnkYKllrpcaiTCybHd@bN7XfT7roF28pcgBAnOflx67exSsfjiSFPNa65M6AI4T4cBCNR4TJrR4me08@9gkB70iA9mYikCXkH2GZbcoypL/5WOhDH3azkqTeUljGJufhCyyB/6Yb5m0hGeATR9j7MPgLtHFR1Q1n/NS2@yQSQqT9mXTuui5hdflXdb7wXw "Python 2 – Try It Online") -1 byte, thanks to Jitse [Answer] # [Perl 5](https://www.perl.org/) `-p`, 111 bytes ``` s/(\d)\1/ double$1/g;s/\w+(\d)\1/triple$1/g;s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge ``` [Try it online!](https://tio.run/##RYlBDoIwEADvfcUeiECMtlWREp8iXgxLaUK6tS3g660STZzMacahH6uUAi/armwlh46m@4iZ5PoSeLtsfz164/654znk@8dS0ABkEeJCEAePCD1NHnozIwTzhIAzWkCj4wDWWCyv2ebGNaYk5OHITlW1yoQQ7PyhVkox2XyRdbMOIV7koiEb0s69AQ "Perl 5 – Try It Online") Explanation: ``` s/(\d)\1/ double$1/g; # Replace non-overlapping double digits with " double<digit>" s/\w+(\d)\1/triple$1/g; # Replace remaining double digits preceded by "double" with "triple<digit>" s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge # Replace digits with " <word>" ``` [Answer] # [Scala](http://www.scala-lang.org/), 213 bytes Got it. Somehow the recursive version I was trying to build was strongly more verbose-y than this one (still recursive though, but only in one case). Function `f` takes as an input string the phone number and outputs its phonetics with a trailing whitespace. ``` var u="oh one two three four five six seven eight nine" split " " "(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched var k=u(o(0)-48)+" " o.length match{case 3=>"triple "+k case 1=>k case _=>"double "+k+f(o drop 2)}}) ``` [Try it online!](https://tio.run/##bVHJboMwEL37K0Y@maYlkKUhlYiUYw89tUekisAQaFwbYZMiIb6dYvAhDR1Z8qzvzaKSmMe9PH1houEtLgRgo1GkCo5l2RKSYgYZUy/vuirE2bF/2PbXuII6pDIHKRD0jwSdV4iQybqCrLgiqKIBhVccIItzrkEUAimokhcaKFBCmetEkf9A3cqtsORxgkfOXwVTj014aA2BDBv3O9ZJjikx9iWsmWSe87QJnIXBkC5HcdY5jFltEiuEdXigQ5clR6CLCxl9fniw2ucQTWV9mqKLjElIK1nCyuk6p@8IWS4/UGkwyYqUw7SaC5Yx6vmrNTWsKpc1T@GEEM3Gjyh1bos22615s7pxS7aNcVn/Ou7RPM@bIdlJZX6f/DzILgiCWYVlMee5UadLWbTxYPeA/n4Sf7ef72FYggUzZ/6jW8xRN3kTkzFHBtL1vw "Scala – Try It Online") **Edit** : -8b thanks to DrY Wit! # [Scala](http://www.scala-lang.org/), 215 bytes And here comes the leading whitespace version, two bytes longer for some reason (even with massive refactoring). ``` var u="oh one two three four five six seven eight nine" split " " "(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched var k=u(o(0)-48) " , double , triple ".split(",")(if(o.length>3){k+=f(o drop 2);1}else o.length-1)+k}) ``` [Try it online!](https://tio.run/##bVHBboMwDL3nK6yckrWl0LUr3USlHnfYaTtyoWAKa5YgEjokxLezQJnUlVmR8mzZz/azjiMRder4ibGBtyiXgLVBmWg4FEVDSIIppEw/v5sylyc@/kHTXaISqoCqDJREMN8KTFYiQqqqEtL8gqDzGjRe0FLmp8yAzCVS0IXIDVCghDKHh6H3QJ3SKbEQUYwHIV4l0/M62Dd9AxXUzldk4gwT0vvnoGKKuXyx9jmhMIdEVUeBFtixCguoM/AzOqec5SlTjkB5Mtn@kTfnWWADkJSqgBV/8VoUGuE3Y@Hx2bnlXUvIcvmB2kAcadSksPsaIVnKqOutHimf2R0yVYkEjgjhRICQUn5btN5s@jepG3Qaxx/k@jdwz@a67oRpXF1l98lP1ra@708qxi79gW7g9VYj23Cye0JvdzVvu5vqYEUYyfpD/8Ej54D7vGun3h06kLb7AQ "Scala – Try It Online") [Answer] # [PHP](https://php.net/), ~~174~~ ~~169~~ ~~166~~ 159 bytes ``` for(;$s=strspn($argn,$d=$argn[$i],$i++);$s==3?($i+=2)+print'triple ':$s<2?:++$i+print'double ',print[oh,one,two,three,four,five,six,seven,eight,nine][$d].' '); ``` [Try it online!](https://tio.run/##bVHbagMhEH33K4YguMtKc28umyUfst2HNGuiUFTUpIXSb9@OroFQOvgwl3PmcrTSDoejlZYQGoQPHhpoCaCx2XyxZBweNp2CkWC0gPBpIEgnxIhbrdfxPaCIu5ibg97c3j8EXNRd/J/IU2azpyGRHZyyiDNyBLyibbbbbUYhIDfy6uvZ9eIu9IMs1FWGkT/fjTbf7GKLeAbekIla/fEzP/kRN3aNIelqQi7GidNZQpHFOnlIXvmdhtGTu2pUMOXqAdFFTX3jg/NWF6nKad8kp6Wq41RVVRkhzfJYYNAsyso6pQPLi7A99YfFcV9VWB0reV3GU9gayXFRjp/C06fwqC2PKnOUhacDeNKDxzO6lvbdCwNW1kNcWZylgcmbntTpgpv2IuAmZU1@hl8 "PHP – Try It Online") For each digit at index of `$i` starting from 0: * If span of the same digit starting from location of `$i` is equal to 3, prints `'triple '` and adds 2 to `$i` so next iteration will have 2 digits jumped over. * If span of the same digit starting from location of `$i` is equal to or more than 2 but is not 3, prints `'double '` and adds 1 to `$i` so next iteration will have 1 digit jumped over. * Prints word for the digit and a space. * `$i++`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 105 bytes ``` +`(.)\1 =$1 . $& = = triple = double 9 nine 8 eight 7 seven 6 six 5 five 4 four 3 three 2 two 1 one 0 oh ``` [Try it online!](https://tio.run/##JYu9CsIwGAD3e4oOIopQkv6mQ97EQcWvNiCJpGn17WPF44ZbLkpy/prz6XIoj2eN3WlKit0eW1hSdK@nYLmH5bbFgHdeMIh7TImeWVbxdMzuQ8voVqFhDEukJk1RhIr0DmjC9inClLPSVU3Ttj9RStFt9MYY9PBH98MX "Retina 0.8.2 – Try It Online") Outputs a leading space. Explanation: I originally tried a regex that automatically matches 2 or 3 digits but @Arnauld's approach of turned out to be golfier. Explanation: ``` +`(.)\1 =$1 ``` Match pairs of identical digits and replace the first with a `=`. Then repeat, so that for an odd number the second last digit is also replaced with a `=`. ``` . $& ``` Space the digits (and `=`s) out. ``` = = triple ``` Handle the case of three identical digits. ``` = double 9 nine 8 eight 7 seven 6 six 5 five 4 four 3 three 2 two 1 one 0 oh ``` Replace all remaining characters with words. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 59 bytes ``` ⁵;`,0;$Ɗ€Ẏ;`Ø0ṭ;-œṣjƭƒV€‘$ị“¡ıc⁴Ṛ⁽]@ɱ2¦Ż©Ẉḷ$Æ!)ɗ[ı8ɱḃ%ċ»Ḳ¤K ``` [Try it online!](https://tio.run/##AYUAev9qZWxsef//4oG1O2AsMDskxorigqzhuo47YMOYMOG5rTstxZPhuaNqxq3GklbigqzigJgk4buL4oCcwqHEsWPigbThuZrigb1dQMmxMsKmxbvCqeG6iOG4tyTDhiEpyZdbxLE4ybHhuIMlxIvCu@G4ssKkS////yIwMTk5OTk5OTkxNzki "Jelly – Try It Online") A monadic link that takes a string of digit characters as its argument and returns a Jelly string of space-separated words. When called as a full-program, outputs implicitly. [Answer] # T-SQL 2017, 238 bytes Added some linebreaks to make it readable ``` WHILE''<left(@,1)SELECT @=stuff(@,1,iif(p<4,p,2),'')+ iif(p=1,' ',iif(p=3,' triple ',' double ')) +trim(substring('oh one two threefour five six seveneightnine',left(@,1)*5,5)) FROM(SELECT~-patindex('%[^'+left(@,1)+']%'+'^',@)p)z PRINT @ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1090620/telephone-number-in-spoken-words)** [Answer] # C++, 382 bytes It's not superclever, but someone needed to write a C++ version. The recursive function R goes through the input string and counts repeated values. If there are more than 3 repeats, it pretends there were 2 repeats, then rewinds and tries again. A few more source chars could probably be squeezed out with `#define` major, but I'm sure a better algo could squeeze out more. ``` #include <iostream> #include <sstream> using namespace std; char*n[]={"oh","one","two","three","four","five","six","seven","eight","nine"}; void R(ostream& s,const char*r,char p='x',int c=0){if(*r==p)R(s,r+1,p,c+1);else {if(c>1){if(c>= 4){s<<"double ";r-=(c-2);}else if(c==3)s<< "triple ";else if(c==2)s<< "double "; }if(c >0)s<<n[p-'0']<<" ";if(!*r)return;R(s,r+1,*r,1);}} void check(const char* in, const char* out) { std::stringstream ss; R(ss,in); if (out == ss.str()) std::cout << "PASS: "; else std::cout << "FAIL! "; std::cout << in << "\n< " << out << "\n> " << ss.str() << std::endl; } int main(int c,char**argv) { if (argv[1] == std::string("test")) { check("0123" ,"oh one two three "); check("4554554" ,"four double five four double five four "); check("000" ,"triple oh "); check("00000" ,"double oh triple oh "); check("66667888" ,"double six double six seven triple eight "); check("19999999179" ,"one double nine double nine triple nine one seven nine "); } else { char* v = argv[1]; R(std::cout,v); std::cout << std::endl; } } ``` and verification of test cases: ``` pa-dev01$ ./a.out test PASS: 0123 < oh one two three > oh one two three PASS: 4554554 < four double five four double five four > four double five four double five four PASS: 000 < triple oh > triple oh PASS: 00000 < double oh triple oh > double oh triple oh PASS: 66667888 < double six double six seven triple eight > double six double six seven triple eight PASS: 19999999179 < one double nine double nine triple nine one seven nine > one double nine double nine triple nine one seven nine ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~96~~ 93 bytes ``` {S:g/(.)$0?[$0{}<!$0>]?/{(<triple double>X$)[3-$/.comb]}{+$/??uniname(~$0).words[1]!!'oh'} /} ``` [Try it online!](https://tio.run/##JYndCoIwGEDv9xQThj9E7jPzr2x7iG4C8UJzljB/0CRE1qsvo8Ph3JxBjDLU7YLNGl@wXq@nB7VdhwDPCKwqNQiwnNPVTl9jM0iBq34upWA34mT@nlD33rdlrtYdoZzPXdMVrbA/BBz33Y/VlHm5YVj901KYKn1GsunExJhr1lumYtHgHXx0DIKfCABQuBHFcYy85I8XJb8B8AU "Perl 6 – Try It Online") This is an anonymous code block that takes a number and returns a string with the numbers in uppercase, e.g. `0123 => oh ONE TWO THREE` with a single trailing space. This was deleted for a while until I found out how to use captures in a lookahead, but it should be fixed now. [Answer] # [Red](http://www.red-lang.org), 242 bytes ``` func[s][b:[copy t skip t]parse s[any[change[b t ahead not t](rejoin["triple "t])| change b(rejoin["double "t])| skip]]foreach c s[prin either i: find"0123456789"c[rejoin[pick[:oh:one:two:three:four:five:six:seven:eight:nine]index? i" "]][c]]] ``` [Try it online!](https://tio.run/##TU3LbsMgELz7K1ac2pvdxrG9l/5Dr4gDxkvYJgIEOE2k/rvrJG3k0VzmoZlE0/JJk1SVRVjs7I3MSo4oTYhXKJCPHKGoqFMmyFL7qzRO@wPJcU21Iz2BD2WtvCT6CuylKInjiUAU9fpTPcowPtMpzON/el9XyoZE2jgw60FM7IG4OErAWFn2k6ibt/ddu@/6QRj5txPZHCUGh8ETlu@AxSUitGFOaPlMmPmCmc7kkfjgCnr2pNY1unwACxBKSaOUWm6HBSzcX0T1lLu2vXHj1HW9UfsVXd/3G6sZHmi6QSy/ "Red – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 253 bytes ``` def g(s:String):String={val t="oh one two three four five six seven eight nine".split(" ")(s(0)-48) s.length match{case 3=>"triple "+t;case 2=>"double "+t;case 1=>t;case _=>"double "+t+" "+g(s drop 2)}} s=>"(.)\\1*".r.findAllIn(s).map(g(_)) mkString " " ``` [Try it online!](https://tio.run/##VU9BasMwELzrFYtOUkNMnRbqtNiQY8@9BoJir2y1siSsjRswfrurNi60e9lhZtiZjbWyavHnd6wJasAroWsiHEKAibFRWdDPbzQY15bVuqelQQ2tiKsgfw3Tt51K7jvwDoE@PVA3IIL2lwG0GRGiuULEER2gaTsCZxzyLAZrSHDgUkRxL7ePhWQxs@ha6qBXVHdTrSLCQ1nxFBUsAt/Qyw@3S1zjL@e/XF5WKzr9UzcpYpOKQzP4ADs5zywmg8jk8Zjf8WzItHHNwdpXJ6LMehVEK05SQv9xexHSgWVmIWGyTmjB8/1t8qd9UXAp2bwsXw "Scala – Try It Online") [Answer] # Oracle SQL, 578 bytes (in formatted form) Solution is not concise by any means so posting it in formatted way. ``` with r(s) as (select x from t union all select case when length(regexp_substr(s, '(.)(\1)+')) = 3 then regexp_replace(s, '^...') else regexp_replace(s, '^(.)\1|^.') end from r where s is not null) select listagg(decode(length(r), 2, 'double ', 3, 'triple ') || decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ') within group (order by rownum) from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r from r order by length(s) desc); ``` Test in SQL\*Plus ``` SQL> create table t(x) as select /*'45547777777774'*/ '1999999910079' from dual; Table created. SQL> set pages 0 SQL> with r(s) as 2 (select x from t 3 union all 4 select case 5 when length(regexp_substr(s, '(.)(\1)+')) = 3 6 then regexp_replace(s, '^...') 7 else regexp_replace(s, '^(.)\1|^.') 8 end 9 from r 10 where s is not null) 11 select listagg(decode(length(r), 2, 'double ', 3, 'triple ') || 12 decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ') 13 within group (order by rownum) 14 from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r 15 from r order by length(s) desc); one double nine double nine triple nine one double oh seven nine ``` The main trick is that digits converted into words using Oracle format models instead of hard-coded literals "one" ... "nine". [Answer] # JavaScript, 142 bytes ``` s=>s.replace(/(.)(\1\1(?!\1)|\1|)/g,t=>(t[2]?' triple ':t[1]?' double ':' ')+'oh one two three four five six seven eight nine'.split` `[t[0]]) ``` [Try it online!](https://tio.run/##bZDBboMwDIbvewqvlyTaBqRbVzqJ9kEAqZQayIQSRFK2Q9@dkZBOHZqVgx35/@zfn8VQ6LIXnXmR6oxjlYw62eugx64tSqQhDRjNeMbp4THj7JrxKwvrZ5PsqUnX@YGAmcQtAvkwKbf1WV1OriZA2BNRDSiJYL4UmKZHhEpdeqjEgKDFN2gcUAKKujEghUQS6K4V5gjH1KRRnrOxVFKrFoNW1bSiq4ivX1eMwS3CEJYjHhaSt83Gvl/VJHFL@E3dLv9@LEFRFN2PtiDvXjXL3vcptnEc3wRTr8db23fpfAHPcYdYovhuDr7dOZq1PPn1DHu1P7lHudz2zQNsOf4A "JavaScript (Node.js) – Try It Online") [Answer] # (Roblox) [Lua 5.1](https://www.lua.org/), 166 bytes ``` for I,N in('111 triple 11 double 1 '):gmatch'(%d+)(%D+)'do for i,n in('0oh1one2two3three4four5five6six7seven8eight9nine'):gmatch'(.)(%l+)'do s=s:gsub(i*I,N..n)end end ``` *Ensure `s` is a predefined string value populated only with digits; that will be the variable to be modified. The result will include a leading space* `[\u20]` *character.* ]
[Question] [ This task is part of the [First Periodic Premier Programming Puzzle Push](http://meta.codegolf.stackexchange.com/q/298/78) and is intended as demonstration of the new [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge-type [proposal](http://meta.codegolf.stackexchange.com/q/302/78). **The task is the write a program to play the iterated prisoner's dilemma better than other entrants.** > > Look, Vinny. We know your cellmate---what's his name? Yeah McWongski, the Nippo-Irish-Ukranian mobster--is up to something and you know what it is. > > > We're trying to be nice here, Vinnie. Givin' you a chance. > > > If you tells us what he's plannin' we'll see you get a good work assignment. > > > And if you don't... > > > ## The Rules of the Game * The contest consists of a full round-robin (all possible pairing) of two contestants at a time (including self plays). * There are 100 rounds played between each pair * In each round each player is asked to choose between cooperating with the other player or betraying them, without knowing the other players intentions in the matter, *but* with a memory of the outcomes of previous rounds played against this opponent. * Points are awarded for each round based on the combined choice. If both players cooperate they each get 2 points. Mutual betrayal yields 1 point each. In the mixed case, the betraying player is awarded 4 points and the cooperator is penalized by 1. * An "official" match will be run not sooner than 10 days after posting with all the submissions I can get to work and be used to select the "accepted" winner. I have a Mac OS 10.5 box, so POSIX solutions should work, but there are linuxisms that don't. Likewise, I have no support for the win32 API. I'm willing to make a basic effort to install things, but there is a limit. The limits of my system in no way represent the limits of acceptable responses, simply those that will be included in the "offical" match. ## The Programmer's interface * Entries should be in the form of programs that can be run from the command line; the decision must the (sole!) output of the program on the standard output. The history of previous rounds with this opponent will be presented as a command-line argument. * Output is either "c" (for *clam up*) or "t" (for *tell all*). * The history is a single string of characters representing previous rounds with the most recent rounds coming earliest in the string. The characters are + "K" (for *kept the faith* meaning mutual cooperation) + "R" (for *rat b@st@rd sold me out!*) + "S" (for *sucker!* meaning you benefited from a betrayal) + "E" (for *everyone is looking out for number one* on mutual betrayal) ## The bracket Four players will be provided by the author * Angel -- always cooperates * Devil -- always talks * TitForTat -- Cooperates on the first round then always does as he was done by in the last round * Random -- 50/50 to which I will add all the entries that I can get to run. The total score will be the sum score against all opponents (including self-plays only once and using the average score). ### Entrants (current as of 2 May 2011 7:00) [The Secret Handshake](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2375#2375) | [Anti-T42T Missile](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2386#2386) | [Mistrust (variant)](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2358#2358) | [Anti-Handshake](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2389#2389) | [The Little Lisper](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2373#2373) | [Convergence](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2361#2361) | [Shark](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2408#2408) | [Probabimatic](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2394#2394) | [Pavlov - Win Stay, Lose Switch](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2367#2367) | [Honor Among Thieves](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2407#2407) | [Help Vampire](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2393#2393) | [Druid](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2404#2404) | [Little Schemer](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2406#2406) | [Bygones](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2371#2371) | [Tit for Two Tats](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2369#2369) | [Simpleton](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma/2409#2409) | ## Scorer ``` #! /usr/bin/python # # Iterated prisoner's dilemma King of Hill Script Argument is a # directory. We find all the executables therein, and run all possible # binary combinations (including self-plays (which only count once!)). # # Author: dmckee (https://codegolf.stackexchange.com/users/78/dmckee) # import subprocess import os import sys import random import py_compile ### # config PYTHON_PATH = '/usr/bin/python' #path to python executable RESULTS = {"cc":(2,"K"), "ct":(-1,"R"), "tc":(4,"S"), "tt":(1,"E")} def runOne(p,h): """Run process p with history h and return the standard output""" #print "Run '"+p+"' with history '"+h+"'." process = subprocess.Popen(p+" "+h,stdout=subprocess.PIPE,shell=True) return process.communicate()[0] def scoreRound(r1,r2): return RESULTS.get(r1[0]+r2[0],0) def runRound(p1,p2,h1,h2): """Run both processes, and score the results""" r1 = runOne(p1,h1) r2 = runOne(p2,h2) (s1, L1), (s2, L2) = scoreRound(r1,r2), scoreRound(r2,r1) return (s1, L1+h1), (s2, L2+h2) def runGame(rounds,p1,p2): sa, sd = 0, 0 ha, hd = '', '' for a in range(0,rounds): (na, ha), (nd, hd) = runRound(p1,p2,ha,hd) sa += na sd += nd return sa, sd def processPlayers(players): for i,p in enumerate(players): base,ext = os.path.splitext(p) if ext == '.py': py_compile.compile(p) players[i] = '%s %sc' %( PYTHON_PATH, p) return players print "Finding warriors in " + sys.argv[1] players=[sys.argv[1]+exe for exe in os.listdir(sys.argv[1]) if os.access(sys.argv[1]+exe,os.X_OK)] players=processPlayers(players) num_iters = 1 if len(sys.argv) == 3: num_iters = int(sys.argv[2]) print "Running %s tournament iterations" % (num_iters) total_scores={} for p in players: total_scores[p] = 0 for i in range(1,num_iters+1): print "Tournament %s" % (i) scores={} for p in players: scores[p] = 0 for i1 in range(0,len(players)): p1=players[i1]; for i2 in range(i1,len(players)): p2=players[i2]; # rounds = random.randint(50,200) rounds = 100 #print "Running %s against %s (%s rounds)." %(p1,p2,rounds) s1,s2 = runGame(rounds,p1,p2) #print (s1, s2) if (p1 == p2): scores[p1] += (s1 + s2)/2 else: scores[p1] += s1 scores[p2] += s2 players_sorted = sorted(scores,key=scores.get) for p in players_sorted: print (p, scores[p]) winner = max(scores, key=scores.get) print "\tWinner is %s" %(winner) total_scores[p] += 1 print '-'*10 print "Final Results:" players_sorted = sorted(total_scores,key=total_scores.get) for p in players_sorted: print (p, total_scores[p]) winner = max(total_scores, key=total_scores.get) print "Final Winner is " + winner ``` * Complaints about my horrible python are welcome, as I am sure this sucks more than one way * Bug fixes welcome **Scorer Changelog:** * Print sorted players and scores, and declare a winner (4/29, Casey) * Optionally run multiple tournaments (`./score warriors/ num_tournaments)`) default=1 , detect & compile python sources (4/29, Casey) * Fix particularly dumb bug in which the second player was being passed a incorrect history. (4/30, dmckee; thanks Josh) ## Initial warriors By way of example, and so that the results can be verified **Angel** ``` #include <stdio.h> int main(int argc, char**argv){ printf("c\n"); return 0; } ``` or ``` #!/bin/sh echo c ``` or ``` #!/usr/bin/python print 'c' ``` **Devil** ``` #include <stdio.h> int main(int argc, char**argv){ printf("t\n"); return 0; } ``` **Random** ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int main(int argc, char**argv){ srandom(time(0)+getpid()); printf("%c\n",(random()%2)?'c':'t'); return 0; } ``` Note that the scorer may re-invoke the warrior many times in one second, so a serious effort must be made to insure randomness of the results if time is being used to seed the PRNG. **TitForTat** ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char**argv){ char c='c'; if (argv[1] && ( (argv[1][0] == 'R') || (argv[1][0] == 'E') ) ) c='t'; printf("%c\n",c); return 0; } ``` The first one that actually *does something* with the history. **Running the scorer on only the provided warriors yields** ``` Finding warriors in warriors/ Running warriors/angel against warriors/angel. Running warriors/angel against warriors/devil. Running warriors/angel against warriors/random. Running warriors/angel against warriors/titfortat. Running warriors/devil against warriors/devil. Running warriors/devil against warriors/random. Running warriors/devil against warriors/titfortat. Running warriors/random against warriors/random. Running warriors/random against warriors/titfortat. Running warriors/titfortat against warriors/titfortat. ('warriors/angel', 365) ('warriors/devil', 832) ('warriors/random', 612) ('warriors/titfortat', 652) ``` That devil, he's a craft one, and nice guys apparently come in last. ## Results of the "official" run ``` ('angel', 2068) ('helpvamp', 2295) ('pavlov', 2542) ('random', 2544) ('littleschemer', 2954) ('devil', 3356) ('simpleton', 3468) ('secrethandshake', 3488) ('antit42t', 3557) ('softmajo', 3747) ('titfor2tats', 3756) ('convergence', 3772) ('probabimatic', 3774) ('mistrust', 3788) ('hyperrationalwasp', 3828) ('bygones', 3831) ('honoramongthieves', 3851) ('titfortat', 3881) ('druid', 3921) ('littlelisper', 3984) ('shark', 4021) ('randomSucker', 4156) ('gradual', 4167) Winner is ./gradual ``` [Answer] ## Gradual This strategy is based on a paper by [Beaufils, Delahaye and Mathieu](http://www.lifl.fr/IPD/references/from_lifl/alife5/html/). My C really isn't the best, so if anyone has any suggestions to improve/speed up the code, let me know! [Edit] Worth to note is that Gradual was designed to be a strategy that outperforms Tit for Tat. It has similar properties in that it is willing to cooperate and retaliates against a defecting opponent. Unlike Tit for Tat, which only has a memory of the last round played, Gradual will remember the complete interaction and defect the number of times the opponent has defected so far. It will offer mutual cooperation afterwards again, though. As usual, the performance of the strategy depends a bit on the line-up of other strategies. Also the original paper wasn't really clear on some details. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if(argc == 1){ printf("c\n"); return 0; } size_t l = strlen(argv[1]); int i; size_t currentSequence = 0; size_t totalDefects = 0; size_t lastDefects = 0; for(i = l-1; i >= 0; i--){ if(argv[1][i] == 'E' || argv[1][i] == 'R'){ totalDefects++; currentSequence = 0; } else if(argv[1][i] == 'S') { currentSequence++; } } if(currentSequence < totalDefects) // continue defect sequence printf("t\n"); else if(argv[1][0] == 'S' || argv[1][0] == 'E' || argv[1][1] == 'S' || argv[1][1] == 'E') // blind cooperation printf("c\n"); else if(argv[1][0] == 'R') // start new defect sequence printf("t\n"); else printf("c\n"); return 0; } ``` [Answer] ## The Secret Handshake ``` #!/usr/bin/python import sys import random def main(): if len(sys.argv) == 1: hist = "" else: hist = sys.argv[1] if len(hist) <= len(TAG) and hist == TAGMATCH[len(TAG) - len(hist):]: print TAG[len(TAG) - len(hist) - 1] return if hist[-len(TAG):] == TAGMATCH: print 'c' return print "t" def getTag(): global TAG filename = sys.argv[0] filename = filename.replace(".pyc", ".py") f = open(filename, 'r') code = f.read().split('\n') f.close() if len(code[1]) == 0 or code[1][0] != '#': random.seed() newtag = 't' * 10 cs = 0 while cs < 3: pos = random.randint(0, 8) if newtag[pos] == 't': newtag = newtag[:pos] + 'c' + newtag[pos+1:] cs += 1 code.insert(1, '#%s' % newtag) f = open(filename, 'w') f.write('\n'.join(code)) f.close() TAG = newtag else: TAG = code[1][1:] global TAGMATCH TAGMATCH = TAG.replace('c', 'K').replace('t', 'E') if __name__ == "__main__": getTag() main() ``` The strategy here is to sacrifice the first 10 rounds to performing a "secret" handshake. If I'm celled with myself, I then recognize the history of the first 10 moves and put on my Angel cap for the rest of the game. As soon as I recognize that my cellmate isn't myself, I transform into a Devil in an attempt to take advantage of overly cooperative cellmates. Whether sacrificing the first 10 rounds will allow me to edge out the Devil itself depends strongly on how many entries there are. To minimize the damage, only 3 cooperates show up in the handshake. Edit: TAGMATCH dynamic now to prevent stupid errors like changing only one of them and so I can make TAG dynamic at some point in the future. Edit 2: Now randomly generates the tag on the first run and stores it in the file specified by `sys.argv[0]` (`.pyc` replaced by `.py` so it goes to the code, not bytecode, file). I think this is the only information all of my instances have that no one else has, so it seems like the only option for avoiding parasites. [Answer] # The Little Lisper ``` (setf *margin* (/ (+ 40 (random 11)) 100)) (setf *r* 0.0) (setf *s* 0.0) (setf *k* 0.0) (setf *e* 0.0) ;; step 1 - cout up all the games results (loop for i from 1 to (length(car *args*)) do (setf foo (char (car *args*) (1- i))) (cond ((equal foo #\R) (setf *r* (1+ *r*))) ((equal foo #\S) (setf *s* (1+ *s*))) ((equal foo #\K) (setf *k* (1+ *k*))) ((equal foo #\E) (setf *e* (1+ *e*))) ) ) (setf *sum* (+ *r* *s* *k* *e*)) ;; step 2 - rate trustworthiness (if (> *sum* 0) (progn (setf *dbag* (/ (+ *r* *e*) *sum*)) ; percentage chance he rats (setf *trust* (/ (+ *s* *k*) *sum*)); percentage chance he clams ) (progn (setf *dbag* 0) ; percentage chance he rats (setf *trust* 0); percentage chance he clams ) ) ;; step 3 - make a decision (the hard part....) (write-char (cond ((> *sum* 3) (cond ((or (= *dbag* 1) (= *trust* 1)) #\t) ; maximizes both cases ; takes advantage of the angel, crockblocks the devil ((> (+ *dbag* *margin*) *trust*) #\t) ; crockblock statistical jerks ((< *dbag* *trust*) #\c) ; reward the trusting (WARN - BACKSTABBING WOULD IMPROVE SCORE) ((and (= (floor *dbag* *margin*) (floor *trust* *margin*)) (not (= 0 *dbag* *trust*))) #\t) ; try to backstab a purely random opponent, avoid opening w/ a backstab ) ) (t #\c) ; defalt case - altruism ) ) ``` # The Devil Consider the following, format (Player1, Player2) * (C, T) - P2 gains *FOUR POINTS* for his treachery, while P1 *LOOSES ONE* * (T, T) - *P2 AND P1 GAIN 1* Assuming that P2 is the devil, there is no way that the devil can ever loose points, in fact the worst that he can do is gain only one point. Up against a purely random opponent therefore, the devil's worst possible score will be exactly (5/2)\*n where n is the number of "games" played. His absolute worst-case is against himself, where his score will be n, and his best-case is against an angel, which will be 4\*n # Assert : optimal\_strat = devil this is a tourney. Backstabbing my cell-mate is a much better strategy than cooperation because it helps *MY SCORE* more (+4). BONUS - he gets slammed (-1)! If I stick my neck out for him, I stand to gain (+2) and loose (-1). Therefor statistically backstabbing is rewarded. # But Is It Optimal? There is no reason to EVER (under this scoring system) co-operate. * If you chose the wrong time to clam up, you loose out. * If you rat, at least you don't loose anything. * If you rat and he's dumb, you gain 2x more than if you had been a good pall. In the KOTH system, maximization of returns is essential. Even if you have two bots who get perfectly synced and co-operate, their individuals scores will still only get boosted by 200 points for their sportsmanship. A devil on the other hand will earn at least 100 points, with an average case of 200 and a maximum of 400, and cost his opponents up to 100 points each! So practically, the devil really scores an average game of 300, spiking to 500. # Bottom line - time will tell To me, it looks like the scoring should be re-considered lest the devil take the day. Increasing the co-operation score to 3 all might do it. It is possible however to detect devils and prevent them from scoring their full 400, as pavlov and spite show. Can I prove that either one will pick up enough points for their cooperation to justify their faith? no. All of that is dependent on the final field of contenders. > > GL, HF! > > > And please do your worst to this post. I wanna write my senior paper on this when all's said and done. # Version history 1. Added a margin variable which changes Lisper's tolerance for duchebaggery randomly. 2. Updated lisper to clam for the first two rounds to get off on the right foot with co-operative opponents 3. Used a genetic algorithm to find the most robust values for the random threshold generator based on their maximum cumulative score against a standard set of opponents. Posted update including them. [**OFFICIAL VERSION OF LISPER**](https://github.com/rdmckenzie/CodeGolf/blob/master/prisoner/warriors/lisper-stable.lsp) [**DEVEL VERSION OF LISPER**](https://github.com/rdmckenzie/CodeGolf/blob/master/prisoner/warriors/lisper-testing.lsp) [Answer] ## Mistrust (variant) This one came out first in my own tests years ago (back then I was in 11th grade and did a tiny thesis on exactly this, using strategies devised by other students as well). It starts out with the sequence `tcc` ( and plays like Tit for Tat after that. Apologies for the horrible code; if someone can make that shorter while not exactly golfing it, I'd be grateful :-) ``` #include <stdio.h> #include <string.h> int main(int argc, char* argv[]) { if (argc == 1) printf("t\n"); else switch (strlen(argv[1])) { case 0: printf("t\n"); break; case 1: case 2: printf("c\n"); break; default: if (argv[1][0] == 'R' || argv[1][0] == 'E') printf("t\n"); else printf("c\n"); break; } return 0; } ``` [Answer] ## Anti-T42T Missile ``` #!/usr/bin/python """ Anti-T42T Missile, by Josh Caswell That Tit-for-two-tats, what a push-over! T42T: ccctcctcc... AT42TM: cttcttctt... KSSRSSRSS... """ import sys try: history = sys.argv[1] except IndexError: print 'c' sys.exit(0) if history[:2] == 'SS': print 'c' else: print 't' ``` Does reasonably well against the base set of warriors: kills Angel, slightly beaten by Devil (but keeps his score low), generally beats RAND handily, and just barely beats Tit for Tat. Does poorly when playing against itself. [Answer] ## Convergence Initially nice, then plays randomly with an eye on the opponent's history. ``` /* convergence * * A iterated prisoners dilemma warrior for * * Strategy is to randomly chose an action based on the opponent's * history, weighting recent rounds most heavily. Important fixed * point, we should never be the first to betray. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <string.h> int main(int argc, char**argv){ srandom(time(0)+getpid()); /* seed the PRNG */ unsigned long m=(1LL<<31)-1,q,p=m; if (argc>1) { size_t i,l=strlen(argv[1]); for (i=l; --i<l; ){ switch (argv[1][i]) { case 'R': case 'E': q = 0; break; case 'K': case 'S': q = m/3; break; } p/=3; p=2*p+q; } } /* printf("Probability of '%s' is %g.\n",argv[1],(double)p/(double)m); */ printf("%c\n",(random()>p)?'t':'c'); return 0; } ``` I've tried diddling the weighting on the history, but haven't properly optimized it. [Answer] ## Shark ``` #!/usr/bin/env python """ Shark, by Josh Caswell Carpe stultores. """ import sys HUNGER = 12 try: history = sys.argv[1] except IndexError: print 'c' sys.exit(0) if history.count('S') > HUNGER: print 't' else: print 'c' if history[0] in "SK" else 't' ``` Does quite well against the base roster. [Answer] ## Pavlov - [Win Stay, Lose Switch](http://en.wikipedia.org/wiki/Win-Stay,_Lose-Switch) On the first turn it cooperates, and then it cooperates *if and only if* both players opted for the same choice in the previous move. ``` #!/usr/bin/python import sys if len(sys.argv) == 1: print 'c' else: hist = sys.argv[1] if hist[0] == 'K' or hist[0] == 'E': print 'c' else: print 't' ``` [Answer] ## Honor Among Thieves ``` #!/usr/bin/env python """ Honor Among Thieves, by Josh Caswell I'd never sell out a fellow thief, but I'll fleece a plump mark, and I'll cut your throat if you try to cross me. """ from __future__ import division import sys PLUMPNESS_FACTOR = .33 WARINESS = 10 THIEVES_CANT = "E" + ("K" * WARINESS) try: history = sys.argv[1] except IndexError: history = "" if history: sucker_ratio = (history.count('K') + history.count('S')) / len(history) seem_to_have_a_sucker = sucker_ratio > PLUMPNESS_FACTOR # "Hey, nice t' meetcha." if len(history) < WARINESS: #"Nice day, right?" if not set(history).intersection("RE"): print 'c' # "You sunnuvab..." else: print 't' # "Hey, lemme show ya this game. Watch the queen..." elif len(history) == WARINESS and seem_to_have_a_sucker: print 't' # "Oh, s#!t, McWongski, I swear I din't know dat were you." elif history[-len(THIEVES_CANT):] == THIEVES_CANT: # "Nobody does dat t' me!" if set(history[:-len(THIEVES_CANT)]).intersection("RE"): print 't' # "Hey, McWongski, I got dis job we could do..." else: print 'c' # "Do you know who I am?!" elif set(history).intersection("RE"): print 't' # "Ah, ya almos' had da queen dat time. One more try, free, hey? G'head!" elif seem_to_have_a_sucker: print 't' # "Boy, you don't say much, do ya?" else: print 'c' ``` Note that the `THIEVES_CANT` is essentially a handshake, though it will only emerge when playing against a cooperator. However, it avoids the parasite problem by checking for later crosses. Does quite well against the base roster. [Answer] ## "Probabimatic" Starts by cooperating, then picks whichever option gives it the highest expected value. Simple. ``` #include <stdio.h> void counts(char* str, int* k, int* r, int* s, int* e) { *k = *r = *s = *e = 0; char c; for (c = *str; c = *str; str++) { switch (c) { case 'K': (*k)++; break; case 'R': (*r)++; break; case 'S': (*s)++; break; case 'E': (*e)++; break; } } } // Calculates the expected value of cooperating and defecting in this round. If we haven't cooperated/defected yet, a 50% chance of the opponent defecting is assumed. void expval(int k, int r, int s, int e, float* coop, float* def) { if (!k && !r) { *coop = .5; } else { *coop = 2 * (float)k / (k + r) - (float)r / (k + r); } if (!s && !e) { *def = 2.5; } else { *def = 4 * (float)s / (s + e) + (float)e / (s + e); } } int main(int argc, char** argv) { if (argc == 1) { // Always start out nice. putchar('c'); } else { int k, r, s, e; counts(argv[1], &k, &r, &s, &e); float coop, def; expval(k, r, s, e, &coop, &def); if (coop > def) { putchar('c'); } else { // If the expected values are the same, we can do whatever we want. putchar('t'); } } return 0; } ``` Used to start by cooperating, but now it seems that defecting actually works better. EDIT: Oh wait, it actually doesn't. [Answer] ### Hyperrational Wasp Implemented in Java because I wasn't sure how complex the data structures were going to end up. If this is a problem for someone then I think I can port it to bash without too many problems because in the end it only really uses simple associative arrays. **Note**: I've removed this from a package in line with the latest version of my patch to the scorer to handle Java. If you want to post a Java solution which uses inner classes then you'll have to patch the patch. ``` import java.util.*; public class HyperrationalWasp { // I'm avoiding enums so as not to clutter up the warriors directory with extra class files. private static String Clam = "c"; private static String Rat = "t"; private static String Ambiguous = "x"; private static final String PROLOGUE = "ttc"; private static int n; private static String myActions; private static String hisActions; private static String decideMove() { if (n < PROLOGUE.length()) return PROLOGUE.substring(n, n+1); // KISS - rather an easy special case here than a complex one later if (mirrorMatch()) return Clam; if (n == 99) return Rat; // This is rational rather than superrational int memory = estimateMemory(); if (memory == 0) return Rat; // I don't think the opponent will punish me if (memory > 0) { Map<String, String> memoryModel = buildMemoryModel(memory); String myRecentHistory = myActions.substring(0, memory - 1); // I don't think the opponent will punish me. if (Clam.equals(memoryModel.get(Rat + myRecentHistory))) return Rat; // I think the opponent will defect whatever I do. if (Rat.equals(memoryModel.get(Clam + myRecentHistory))) return Rat; // Opponent will cooperate unless I defect. return Clam; } // Haven't figured out opponent's strategy. Tit for tat is a reasonable fallback. return hisAction(0); } private static int estimateMemory() { if (hisActions.substring(0, n-1).equals(hisActions.substring(1, n))) return 0; int memory = -1; // Superrational? for (int probe = 1; probe < 5; probe++) { Map<String, String> memoryModel = buildMemoryModel(probe); if (memoryModel.size() <= 1 || memoryModel.values().contains(Ambiguous)) { break; } memory = probe; } if (memory == -1 && isOpponentRandom()) return 0; return memory; } private static boolean isOpponentRandom() { // We only call this if the opponent appears not have have a small fixed memory, // so there's no point trying anything complicated. This is supposed to be a Wilson // confidence test, although my stats is so rusty there's a 50/50 chance that I've // got the two probabilities (null hypothesis of 0.5 and observed) the wrong way round. if (n < 10) return false; // Not enough data. double p = count(hisActions, Clam) / (double)n; double z = 2; double d = 1 + z*z/n; double e = p + z*z/(2*n); double var = z * Math.sqrt(p*(1-p)/n + z*z/(4*n*n)); return (e - var) <= 0.5 * d && 0.5 * d <= (e + var); } private static Map<String, String> buildMemoryModel(int memory) { // It's reasonable to have a hard-coded prologue to probe opponent's behaviour, // and that shouldn't be taken into account. int skip = 0; if (n > 10) skip = n / 2; if (skip > 12) skip = 12; Map<String, String> memoryModel = buildMemoryModel(memory, skip); // If we're not getting any useful information after skipping prologue, take it into account. if (memoryModel.size() <= 1 && !memoryModel.values().contains(Ambiguous)) { memoryModel = buildMemoryModel(memory, 0); } return memoryModel; } private static Map<String, String> buildMemoryModel(int memory, int skip) { Map<String, String> model = new HashMap<String, String>(); for (int off = 0; off < n - memory - 1 - skip; off++) { String result = hisAction(off); String hypotheticalCause = myActions.substring(off+1, off+1+memory); String prev = model.put(hypotheticalCause, result); if (prev != null && !prev.equals(result)) model.put(hypotheticalCause, Ambiguous); } return model; } private static boolean mirrorMatch() { return hisActions.matches("c*ctt"); } private static String myAction(int idx) { return myActions.substring(idx, idx+1).intern(); } private static String hisAction(int idx) { return hisActions.substring(idx, idx+1).intern(); } private static int count(String actions, String action) { int count = 0; for (int idx = 0; idx < actions.length(); ) { int off = actions.indexOf(action, idx); if (off < 0) break; count++; idx = off + 1; } return count; } public static void main(String[] args) { if (args.length == 0) { hisActions = myActions = ""; n = 0; } else { n = args[0].length(); myActions = args[0].replaceAll("[KR]", Clam).replaceAll("[SE]", Rat); hisActions = args[0].replaceAll("[KS]", Clam).replaceAll("[RE]", Rat); } System.out.println(decideMove()); } } ``` The changes I made to the scorer to run this are: ``` 17a18 > import re 22a24 > GCC_PATH = 'gcc' #path to c compiler 24c26 < JAVA_PATH = '/usr/bin/java' #path to java vm --- > JAVA_PATH = '/usr/bin/java' #path to java vm 50,55c52,59 < elif ext == '.java': < if subprocess.call([JAVAC_PATH, self.filename]) == 0: < print 'compiled java: ' + self.filename < classname = re.sub('\.java$', '', self.filename) < classname = re.sub('/', '.', classname); < return JAVA_PATH + " " + classname --- > elif ext == '.class': > # We assume further down in compilation and here that Java classes are in the default package > classname = re.sub('.*[/\\\\]', '', self.filename) > dir = self.filename[0:(len(self.filename)-len(classname))] > if (len(dir) > 0): > dir = "-cp " + dir + " " > classname = re.sub('\\.class$', '', classname); > return JAVA_PATH + " " + dir + classname 196c200,201 < if os.path.isdir(sys.argv[1]): --- > warriors_dir = re.sub('/$', '', sys.argv[1]) > if os.path.isdir(warriors_dir): 198,200c203,211 < for foo in os.listdir("./src/"): # build all c/c++ champs first. < os.system(str("gcc -o ./warriors/" + os.path.splitext(os.path.split(foo)[1])[0] + " ./src/" + foo )) < #print str("gcc -o ./warriors/" + os.path.splitext(os.path.split(foo)[1])[0] + " ./src/" + foo ) --- > for foo in os.listdir("./src/"): # build all c/c++/java champs first. > filename = os.path.split(foo)[-1] > base, ext = os.path.splitext(filename) > if (ext == '.c') or (ext == '.cpp'): > subprocess.call(["gcc", "-o", warriors_dir + "/" + base, "./src/" + foo]) > elif (ext == '.java'): > subprocess.call([JAVAC_PATH, "-d", warriors_dir, "./src/" + foo]) > else: > print "No compiler registered for ", foo 202,203c213,214 < print "Finding warriors in " + sys.argv[1] < players = [sys.argv[1]+exe for exe in os.listdir(sys.argv[1]) if os.access(sys.argv[1]+exe,os.X_OK)] --- > print "Finding warriors in " + warriors_dir > players = [warriors_dir+"/"+exe for exe in os.listdir(warriors_dir) if (os.access(warriors_dir+"/"+exe,os.X_OK) or os.path.splitext(exe)[-1] == '.class')] ``` Thanks to @rmckenzie for folding in my challenger function. [Answer] ## Soft\_majo Ah well, another one of the standard strategies, just to complete the line-up. This one picks the move the opponent has made most; if equal it cooperates. ``` #include <stdio.h> #include <string.h> int main(int argc, char * argv[]) { int d = 0, i, l; if (argc == 1) { printf("c\n"); } else { l = strlen(argv[1]); for (i = 0; i < l; i++) if (argv[1][i] == 'R' || argv[1][i] == 'E') d++; printf("%c\n", d > l/2 ? 't' : 'c'); } } ``` [Answer] ## Random sucker This one will defect if the opponent defects too often (threshold), but will randomly try backstabbing every now and then. Does fairly well against everyone except the Java and Lisp players (which I cannot get to run, due to neither Java nor Lisp on the test machine); most of the time at least. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define THRESHOLD 7 #define RAND 32 int main(int c, char * a []) { int r; char * x; int d = 0; srandom(time(0) + getpid()); if (c == 1) { printf("c\n"); return 0; } for (x = a[1]; *x; x++) if (*x == 'R' || *x == 'E') d++; if (d > THRESHOLD || random() % 1024 < RAND || strlen(a[1]) == 99) printf("t\n"); else printf("c\n"); return 0; } ``` [Answer] # BYGONES ``` #!/usr/bin/env python """ BYGONES, entry to 1P5 Iterated Prisoner's Dilemma, by Josh Caswell Cooperates at first, plays as Tit for Tat for `bygones * 2` rounds, then checks history: if there's too much ratting, get mad and defect; too much suckering, feel bad and cooperate. """ bygones = 5 import sys # React to strangers with trust. try: history = sys.argv[1] except IndexError: print 'c' sys.exit(0) replies = { 'K' : 'c', 'S' : 'c', 'R' : 't', 'E' : 't' } # Reply in kind. if len(history) < bygones * 2: print replies[history[0]] sys.exit(0) # Reflect on past interactions. faithful_count = history.count('K') sucker_count = history.count('S') rat_count = history.count('R') # Reprisal. if rat_count > faithful_count + bygones: # Screw you! print 't' sys.exit(0) # Reparation. if sucker_count > faithful_count + bygones: # Geez, I've really been mean. print 'c' sys.exit(0) # Resolve to be more forgiving. two_tats = ("RR", "RE", "ER", "EE") print 't' if history[:2] in two_tats else 'c' ``` Haven't worked out the best value for `bygones` yet. I don't expect this to be a *winning* strategy, but I'm interested in the performance of a strategy something like what I think is "good" in real life. A future revision may include checking the number of mutual defections, too. [Answer] ## Help Vampire ``` #!/usr/bin/env python """ Help Vampire, entry to 1P5 Iterated Prisoner's Dilemma, by Josh Caswell. 1. Appear Cooperative 2. Acknowledge Chastisement 3. Act contritely 4. Abuse charity 5. Continual affliction """ import sys from os import urandom LEN_ABASHMENT = 5 try: history = sys.argv[1] except IndexError: print 'c' # Appear cooperative sys.exit(0) # Acknowledge chastisement if history[0] in "RE": print 'c' # Act contritely elif set(history[:LEN_ABASHMENT]).intersection(set("RE")): print 'c' # Abuse charity elif history[0] == 'S': print 't' # Continual affliction else: print 't' if ord(urandom(1)) % 3 else 'c' ``` Has an amusingly asymmetrical result when pitted against itself. If only this solution could be applied in real life. [Answer] ## Druid ``` #!/usr/bin/env python """ Druid, by Josh Caswell Druids are slow to anger, but do not forget. """ import sys from itertools import groupby FORBEARANCE = 7 TOLERANCE = FORBEARANCE + 5 try: history = sys.argv[1] except IndexError: history = "" # If there's been too much defection overall, defect if (history.count('E') > TOLERANCE) or (history.count('R') > TOLERANCE): print 't' # Too much consecutively, defect elif max([0] + [len(list(g)) for k,g in # The 0 prevents dying on [] groupby(history) if k in 'ER']) > FORBEARANCE: print 't' # Otherwise, be nice else: print 'c' ``` Does reasonably well against the base roster. [Answer] ## Simpleton ``` #!/usr/bin/env python """ Simpleton, by Josh Caswell Quick to anger, quick to forget, unable to take advantage of opportunity. """ import sys from os import urandom WHIMSY = 17 try: history = sys.argv[1] except IndexError: if not ord(urandom(1)) % WHIMSY: print 't' else: print 'c' sys.exit(0) if history[0] in "RE": print 't' elif not ord(urandom(1)) % WHIMSY: print 't' else: print 'c' ``` Does okay against the base roster. [Answer] ## Little Schemer ``` #!/usr/bin/env python """ The Little Schemer, by Josh Caswell No relation to the book. Keeps opponent's trust > suspicion by at least 10%, trying to ride the line. """ from __future__ import division import sys from os import urandom out = sys.stderr.write def randrange(n): if n == 0: return 0 else: return ord(urandom(1)) % n try: history = sys.argv[1] except IndexError: print 'c' sys.exit(0) R_count = history.count('R') S_count = history.count('S') K_count = history.count('K') E_count = history.count('E') # Suspicion is _S_ and E because it's _opponent's_ suspicion suspicion = (S_count + E_count) / len(history) # Likewise trust trust = (K_count + R_count) / len(history) if suspicion > trust: print 'c' else: projected_suspicion = (1 + S_count + E_count) / (len(history) + 1) projected_trust = (1 + K_count + R_count) / (len(history) + 1) leeway = projected_trust - projected_suspicion odds = int(divmod(leeway, 0.1)[0]) print 't' if randrange(odds) else 'c' ``` Does poorly against the base set, but quite well against its target. Obviously, not written in Scheme. [Answer] # Tit for Two Tats ### another old favorite ``` #!/usr/bin/env python """ Tit For Two Tats, entry to 1P5 Iterated Prisoner's Dilemma, by Josh Caswell (not an original idea). Cooperates unless opponent has defected in the last two rounds. """ import sys try: history = sys.argv[1] except IndexError: history = "" two_tats = ("RR", "RE", "ER", "EE") if len(history) < 2: print 'c' else: print 't' if history[:2] in two_tats else 'c' ``` ]
[Question] [ This challenge is really simple (and a precursor to a more difficult one!). Given an array of resource accesses (simply denoted by nonnegative integers) and a parameter `n`, return the number of cache misses it would have assuming our cache has capacity `n` and uses a first-in-first-out (FIFO) ejection scheme when it is full. Example: ``` 4, [0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3] 0 = not in cache (miss), insert, cache is now [0] 1 = not in cache (miss), insert, cache is now [0, 1] 2 = not in cache (miss), insert, cache is now [0, 1, 2] 3 = not in cache (miss), insert, cache is now [0, 1, 2, 3] 0 = in cache (hit), cache unchanged 1 = in cache (hit), cache unchanged 2 = in cache (hit), cache unchanged 3 = in cache (hit), cache unchanged 4 = not in cache (miss), insert and eject oldest, cache is now [1, 2, 3, 4] 0 = not in cache (miss), insert and eject oldest, cache is now [2, 3, 4, 0] 0 = in cache (hit), cache unchanged 1 = not in cache (miss), insert and eject oldest, cache is now [3, 4, 0, 1] 2 = not in cache (miss), insert and eject oldest, cache is now [4, 0, 1, 2] 3 = not in cache (miss), insert and eject oldest, cache is now [0, 1, 2, 3] ``` So in this example there were 9 misses. Maybe a code example helps explain it better. In Python: ``` def num_misses(n, arr): misses = 0 cache = [] for access in arr: if access not in cache: misses += 1 cache.append(access) if len(cache) > n: cache.pop(0) return misses ``` Some further testcases (which contains a hint towards the next challenge - notice anything curious?): ``` 0, [] -> 0 0, [1, 2, 3, 4, 1, 2, 3, 4] -> 8 2, [0, 0, 0, 0, 0, 0, 0] -> 1 3, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 9 4, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 10 ``` Shortest code in bytes wins. [Answer] # JavaScript (ES6), 55 bytes ### Method #1: the cache overwrites the input Takes input in currying syntax `(cache_size)(list)`. ``` n=>a=>a.map(x=>a[a.indexOf(x,k>n&&k-n)<k||k++]=x,k=0)|k ``` [Try it online!](https://tio.run/##lc5LCsIwEAbgvafIqiQ0bZO2CwXTK3iA0kXoQ2pqUqxIFr17HFpEiQo6zOJnYL6Zk7zJqb704zXSpmldJ5wWhYSOz3LEFkIp4143rT102FJV6CBQkSZ7Nc8qDCsBM8HIrFxt9GSGNh7MEXeYEVxWhKBfK0kQ27wTnKKUooyinKJn/gwDsfWIFAhGkd9fHwOCe0QGRLZc5svymvNHWIcvHwGx84j8f4Izdwc "JavaScript (Node.js) – Try It Online") ### How? We overwrite the input array **a[ ]** with the cache, using a separate pointer **k** initialized to **0**. We use `a.indexOf(x, k > n && k - n) < k` to test whether **x** is in the cache. The cache can't grow faster than the original array is walked through, so each value is guaranteed to be found, either within or beyond the cache window (i.e. `indexOf()` will never return **-1**). A value is in the cache if it is found at an index between **max(0, k - n)** and **k - 1** (both bounds included), in which case we do **a[true] = x**. This only affects a property of the underlying object behind **a[ ]** but does not alter the *array* **a[ ]**. Otherwise, we do **a[k++] = x**. ### Example Below are the different steps for the input `[1, 1, 2, 3, 3, 2, 1, 4]` with a cache size of **2**: * bold borders: **map()** pointer * brackets: cache pointer **k** * orange: current cache window * yellow: expired cache values [![method #1](https://i.stack.imgur.com/ZbCTW.png)](https://i.stack.imgur.com/ZbCTW.png) --- # JavaScript (ES6), 57 bytes ### Method #2: the cache is appended at the end of the input Takes input in currying syntax `(cache_size)(list)`. ``` n=>a=>a.map(x=>n*~a.indexOf(~x,-n)||a.push(~x)&k++,k=0)|k ``` [Try it online!](https://tio.run/##lc5LDoIwEAbgvaeYlWmllBZY6KJcwQMYFw0P5WFLRA0LwtVrAzGaqolOZvG3yXwzlbzJLj2X7cVXOstNIYwSibRNT7JFvUjUapS0VFnebws09sRXeBgkba/d0T7xsvY8UguGh9qkWnW6yWmjD6hADKPdHmP4tYIA2OKd4ARCAhGBmMAzf4YtsXaI0BKMgNtfD7MEd4jIEtG0mU/Dc44fYf58ucgSG4eI/yc4M3c "JavaScript (Node.js) – Try It Online") ### How? Because the input array **a[ ]** is guaranteed to contain non-negative integers, we can safely append the cache at the end of **a[ ]** by using the one-complement **~x** of each value **x**. We use `n * ~a.indexOf(~x, -n)` to test whether **~x** is found among the last **n** values. Whenever this test fails, we append **~x** to **a[ ]** and increment the number of misses **k**. ### Example Below are the different steps for the same example as above, using this method. Because cache values are simply appended at the end of the array, there is no explicit cache pointer. [![method #2](https://i.stack.imgur.com/lfMR0.png)](https://i.stack.imgur.com/lfMR0.png) [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` f n=length.foldl(\r x->[x|all(/=x)$take n r]++r)[] ``` [Try it online!](https://tio.run/##jYxBDoIwEEX3nOIvWLShqAjbwgk8QWlME0EIQyGVBQvvXhFiMK5MZvH@nzfTmEdXEXlfw0qq7H1qDvVAN2Klwxznan4aInaUMw8n01WwcDqKHFfas4LLOuhNayHRm/FyBSuZFcTjHKNr7YQQtiAeAFBgJwGluXgnbCkROAukApnAzruzFGrxfmcXFl2l62GyrjbOPrCVXw@zP31A@xc "Haskell – Try It Online") Based on [Lynn's method](https://codegolf.stackexchange.com/a/166677/20260) of storing the whole cache history and taking its length. [Unary output](https://codegolf.meta.stackexchange.com/q/5343/20260) would be a bit shorter: **[Haskell](https://www.haskell.org/), 47 bytes** ``` n?l=1<$foldl(\r x->[x|all(/=x)$take n r]++r)[]l ``` [Try it online!](https://tio.run/##jYxNDoIwEIX3nuItWLRhiCIsLZ7AE5TGNBEjYaiksmDh3WuFGIwrk1m8n2/ezT66hjkEd2SVH5LrnS8sao8pq/T0tMxiqyaZjLZr4OBNmnqpDYfetg4KvR1OZ4haOGKZVRh860YkiHNyA0BD7AjaSHo7LC4n7AkFoSSsemVioCP3eysQcV3Mj/lcLbr8iCX8Giz/5AETXg "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda n,a:len(reduce(lambda c,i:[i][i in c[:n]:]+c,a,[])) ``` [Try it online!](https://tio.run/##TchBDoIwEEbhq8yywL9QZNXEk4yzqKXESWBsSFl4@moMCeze@/KnvN7W1@n@qHNYnmMgQ/BzMremcYvJ7RqhnlVYSY0iexMvXUQAS9PUvKoVmlyrlrfifjKA@AK6gnrQDXTu4b@HyBc "Python 2 – Try It Online") Thanks to ovs for 3 bytes, and xnor for 3 more. [Answer] # [R](https://www.r-project.org/), ~~69~~ ~~64~~ 62 bytes ``` function(n,A,K={}){for(i in A)K=c(i[!i%in%K[0:n]],K);sum(K|1)} ``` [Try it online!](https://tio.run/##lc3NCsIwDAfwe58iIoMGMmjXHvyasHMfYexUKPRgB9Od5p691k4R5kEMOfwJ@SVDdHAqoxuDvfk@8EANmXqacXL9wD34AA2a2nLfbnzhQ2FacQhdRwaP1/HCzV3iHJnjgixHhN@1hfIM4iUkQUWgCDTBJ6/uZLFLokpCEKz7@20WMgmVhMp3Zd5dsn6HZfj8l8U@Cf2XkIIxFh8 "R – Try It Online") Thanks to JayCe for suggesting some improvements, and DigEmAll for another couple! [Answer] ## Haskell, ~~61~~ 58 bytes ``` n!a|let(a:b)#c|elem a c=b#c|1<2=1+b#take n(a:c);_#_=0=a#[] ``` [Try it online!](https://tio.run/##jYxNCsIwEIX3nuJJXCQYoWm7UuMNPEEsZVoCliahaJe9e4wtUnElzOL9fPPu9OytczGGLU3OjpyOjWDtZJ31ILS6SUadc632DRuptwgJacWpZrXONDFTRU9dgIan4VqD33iQJA4XDI8ujNghLYsNAAOeSZhKyLfD4pRELlFIlBKrXpkUmMT93gok3BTzo5qrRZcfsYRfg@WfPFDFFw "Haskell – Try It Online") ``` n!a| =a#[] -- take input 'n' and a list 'a' -- and call # with the initial list and an empty cache let -- bind function '#': (a:b)#c -- if there's at least one element 'a' left in the list |elem a c=b#c -- and it's in the cache, go on with the same cache -- and the remainder of the list |1<2= -- else (i.e. cache miss) 1+ -- add one to the recursive call of b# -- the remainder of the list and take n(a:c) -- the first n elements of 'a' prepended to the cach _#_=0 -- if there's no element in the list, return 0 ``` Edit: -3 bytes thanks to @Lynn. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes ``` )svDyå_i¼y¸ìI£]¾ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fs7jMpfLw0vjMQ3sqD@04vMbz0OLYQ/v@/4821lEw0lEw1FEw0FGAsE1gDIigSSyXMQA "05AB1E – Try It Online") **Explanation** ``` ) # wrap the stack in a list sv # for each item y in input list D # duplicate current list yå_i # if y is not contained in the current list ¼ # increment counter y¸ì # prepend y to the current list I£ # keep the first input elements ]¾ # end loop and push counter ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~82~~ 69 bytes ``` {a,n->a.fold(List(0){0}){c,v->if(v!in c.takeLast(n))c+v else c}.size} ``` Takes input as an `IntArray`, **not** the typical `List<Int>` (which shouldn't be a problem.) This uses the approach of "build a cache history and count its length". [Try it online!](https://tio.run/##TY7NCsIwEITvfYr1totpqT8nwYJHoeAzhJrA0riVJga09NljVET3st/swMz2Q3AsKWoHF/be@B3gUcJhHPVdQSaCsnlt2KdJKykbXdnBnbFlH7CmqZ5p6lQsG7YYFyzQVUH3ptXZFqJuGcE4b6CbK88PMyd7E7hoFiSYCshzHVmCE/z0o8vBJ4u1gpWCtYKNgn/evuXvQlUYvg8jZZ@omNMT "Kotlin – Try It Online") ## Explanation ``` { a, n -> // lambda where a is accesses and n is cache size a.fold(List(0){0}) { c, v -> // fold on empty list if(v !in c.takeLast(n)) // if resource is not in last n cache inserts c + v // insert to cache list else c // return cache as is }.size // length of cache list is number of inserts } ``` ### Creating an empty list Kotlin does not have collection literals, but it does have some functions to create new collections. The proper way to create an empty `List<Int>` is simply: ``` List<Int>() ``` but it is shorter if we abuse the size and initializer args to do this: ``` List(0){0} List(0) // List of size 0 { 0 } // with generator returning 0 ``` Because the generator lambda returns 0, Kotlin infers the type of this list as `List<Int>`, and the size of 0 means this list is empty. [Answer] # [Perl 6](https://perl6.org), 48 bytes ``` {my@c;$_∈@c.tail($^n)||push @c,$_ for @^o;+@c} ``` [Test it](https://tio.run/##jZBNTsMwEIX3PsVbBJwQ9yc0qkTdVj4Eu5BWkWMgUpJGcYqo2rLuXbgFR@EiwXH/kNiwsZ6fv5nxm0rV@bhda4W3cV9yQooNbuUqVZi122IjJHeW34eDkP0myXLXWZTeblet9SuEZM4Sz6saYrHivpD71tSKRukGM@RZqXS/SKoJtgQoJjp70VUi1cDcAGdazg3l4in14VFGrRuBRhQfoDFFJKZJXScbixnKi@9wA0MitiztzemplXqvlGxUekGNP@DmcOF3gxj8r89zO9Z5lwoGk8Eje0K6FTyav3NS5UkJ3wbhxOazmXpzuE7JIGwfU3huYmSqtPRs0Eyj215HHkHvL8nJvg0ZoiFDwHDPMGL4rUN7vTpxN/uBGCOyckgMFI3sY2DBow7P4miGp7rw/3Aw/AE "Perl 6 – Try It Online") ``` { # bare block with placeholder params $n,@o my @c; # cache $_ ∈ @c.tail($^n) # is the current value in the last bit of the cache || push @c, $_ # if not add it to the cache for # do this for all of @^o; # the input array +@c # numify the cache (the count) } ``` [Answer] # Java 8, 96 bytes A curried lambda taking a cache size (`int`) and access list (mutable `java.util.List<Integer>`) and returning an `int`. ``` s->a->{int w=0,m=0,i;for(int r:a)m+=(i=a.indexOf(r))<w&i<s?0:s<1?1:1+0*a.set(w++%s,r);return m;} ``` [Try It Online](https://tio.run/##lVE9T8MwEJ2TX3ELyCGulQBT84FYkJBADIxVB5M6xSVxIp9DKVV@e7HdliIGJKJEd3537@XeecXf@aTrhVot3nb98NLICqqGI8Ijlwq2YXAA0XBjQy0Vb2BlWWwwsmH1oCojO8XuDkl@r4xYCk3/bDrVHiSaI6ekcMxKqKEIdzgp@aTcSmVgXSS0tZ/M6k4Th@gpj9q4ILLgTKqF@HiqiY6ifH0uc7xJppinN@k0jZMLzlAYso7jM6Q6yrQwg1bQZuMuDLLwt8f3Ti6gtfbJs9FSLWdz4HqJkdtGYH9szyg/BUIBSqxhj2wTClcUrikkY2b7DkZmc8euKoH4TfhZcpLBdqQ@WP4lhdRKeK1LL/cTvP5vY@qx/Vyn3Bf9lHaV4Hcp7WxJZkO@98YaoZbm1SFxAenee/C8QSNa1g2G9XYzplGkZrzvmw3xrJmcR4ezM3q65Vut@cZfdUl@ocg4ugo5bsmJ2MeNN4b2HcPdFw) ## Ungolfed This uses the first (up to) `s` slots in the input list for the cache. ``` s -> a -> { int w = 0, m = 0, i ; for (int r : a) m += (i = a.indexOf(r)) < w & i < s ? 0 s < 1 ? 1 : 1 + 0*a.set(w++ % s, r) ; return m; } ``` ## Acknowledgments * bugfix thanks to *nimi* [Answer] # [Pyth](https://pyth.readthedocs.io), ~~16 15 18 14~~ 13 bytes Saved 1 byte thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg). ``` luaW-H>QGGHEY ``` [Test suite!](https://pyth.herokuapp.com/?code=luaW-H%3EQGGHEY&input=4%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+4%2C+0%2C+0%2C+1%2C+2%2C+3%5D&test_suite=1&test_suite_input=4%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+4%2C+0%2C+0%2C+1%2C+2%2C+3%5D%0A%0A0%0A%5B%5D%0A%0A0%0A%5B1%2C+2%2C+3%2C+4%2C+1%2C+2%2C+3%2C+4%5D%0A%0A2%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%0A3%0A%5B3%2C+2%2C+1%2C+0%2C+3%2C+2%2C+4%2C+3%2C+2%2C+1%2C+0%2C+4%5D%0A%0A4%0A%5B3%2C+2%2C+1%2C+0%2C+3%2C+2%2C+4%2C+3%2C+2%2C+1%2C+0%2C+4%5D%0A&debug=0&input_size=3) This challenge is very well suited to Pyth's `u` structure. ### How it works ``` luaW-H>QGGHEY Full program. Q = the cache length, E = the list. u E Reduce E with G = current value and H = corresponding element Y With starting value Y, which is preinitialised to [] (empty list). W Conditional application. If... -H ... Filtering H on absence of... >QG ... The last Q elements of G... ... Yields a truthy value (that is, H is not in G[-Q:]), then... a GH ... Append H to G. ... Otherwise, return G unchanged (do not append H at all). l Get the length of the result. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 59 bytes ``` Tr[k={};n=#;k~Take~UpTo@n~FreeQ~#&&k~PrependTo~#&/@#2;1^k]& ``` [Try it online!](https://tio.run/##jYu9CsMgAIR3n0IQQguWJtZNUpw6p2CnkIK0hgaJCeIm@urWuDRjh4P7@W6W7qNm6aaXTGN7SML2uvWBmRYxHYXUKj5WsXATb1ape0RVpWNn1arMWyw5njkirHnqoUpHBjo7Gdej03XkHA159AB4iqGvMWwwJBheMNx7WuKvCQGDDfbFZGATKXNdDqR89iUtKP0TBSCkLw "Wolfram Language (Mathematica) – Try It Online") ### Using pattern-matching, 60 bytes ``` Length[#2//.{p___,a_,q___,a_,r___}/;Tr[1^{q}]<#:>{p,a,q,r}]& ``` I really like this one better, but it's 1 byte longer... [Try it online!](https://tio.run/##jYu9CsIwFIX3PEUgUBSupo2ZrJY@gIODW4ghSGs7tLQh2yXPHtsg2NHhcn7udwbru2awvn/Z2F538daMb98pJjg/4mSMAWtg/qpbNPDy4VTxxDnoCztXOIGFGVzQWdyX5O760St2qNq6ZjrjNRKCEijmQAugAugJ6NbLFH9NCEBWGJNZgPVEeudpINJmW8qEyj9RQkL8AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Japt, 16 bytes ``` ;£A¯V øX ªAiXÃAl ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=O6NBr1Yg+FggqkFpWMNBbA==&input=WzAsMSwyLDMsMCwxLDIsMyw0LDAsMCwxLDIsM10KNA==) --- ## Explanation ``` :Implicit input of array U and integer V £ :Map over each X in U ; A : Initially the empty array ¯V : Slice to the Vth element øX : Contains X? ª : Logical OR AiX : Prepend X to A à :End map Al :Length of A ``` [Answer] # [K4](https://kx.com/download/), ~~42~~ 40 bytes **Solution:** ``` {*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y} ``` **Examples:** ``` q)k)f:{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y} q)f[0;1 2 3 4 1 2 3 4] 8 q)f[2;0 0 0 0 0 0 0] 1 q)f[3;3 2 1 0 3 2 4 3 2 1 0 4] 9 q)f[4;3 2 1 0 3 2 4 3 2 1 0 4] 10 ``` **Explanation:** For the inner function, y is the cache, z is the request and x is the cache size. ``` {*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y} / the solution { } / lambda taking 2 args { } / lambda taking 3 args [x]\y / iterate over lambda with each y *|y / last (reverse, first) y y: / assign to y z in / is z in y? ~ / not r: / assign result to r (true=1,false=0) ( ; ) / 2-element list z,y / join request to cache x# / take x from cache (limit size) y / (else) return cache unchanged , / enlist this result r, / join with r 1_ / drop the first result 1+/ / sum up (starting from 1) * / take the first result ``` **Notes:** There is probably a nicer way to do all of this, but this is the first way that came to mind. The function can be ran like this for **36 bytes**: ``` q)k)*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[4]\3 2 1 0 3 2 4 3 2 1 0 4 10 ``` Alternative - using a global variable to store state (not very K-like), **42 bytes**: ``` {m::0;(){$[z in y;y;[m+:1;x#z,y]]}[x]\y;m} ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 172 bytes ``` (([{}]<>)<{({}(()))}{}>)<>([]){{}<>((({})<{({}()<<>(({})<({}<>({}<>))>)<>>)}{}>)<<>(({})([{}]<>{<>(){[()](<{}>)}{}<><({}()<<>({}<>)>)>}{})){(<{}{}>)}{}>)<>([])}{}<>({}[]<>) ``` [Try it online!](https://tio.run/##PY6xCsMwDET3foXGu6HQNh6Nf8R4SIZCaejQVejbXSkoxSD76e5kbd/19bk@9/U9J9DVRm2sCjWApKk5NvRBVfMHXEmdNTgQhxSFDHvLXOo5Vh2pHRyoIVsE6n/SEffjbVLDkqZzActfeqw4Z7ks8pC73CTuIieVHw "Brain-Flak – Try It Online") ``` # Initialize cache with n -1s (represented as 1s) (([{}]<>)<{({}(()))}{}>)<> # For each number in input ([]){{} # Keep n on third stack <>((({})< # For last n cache entries, compute difference between entry and new value {({}()<<>(({})<({}<>({}<>))>)<>>)}{} >)< # Get negation of current entry and... <>(({})([{}]<> { # Count cache hits (total will be 1 or 0) <>(){[()](<{}>)}{} # while moving entries back to right stack <><({}()<<>({}<>)>)> }{} )) # If cache hit, don't add to cache {(<{}{}>)}{} >) <>([])}{} # Compute cache history length minus cache size (to account for the initial -1s) <>({}[]<>) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ ``` [Try it online!](https://tio.run/##y0rNyan8///hzmkn9zzcOdv65J7UQ@tCH@5Y/Khxy6ElziqHFj5qWgOU8Dm55////9HGOgpGOgqGOgoGOgoQtgmMARE0if1vAgA "Jelly – Try It Online") Takes the list as the first argument and cache capacity as second argument. ``` Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ ɼ Apply to the register: Ṗ Pop. This initializes the register to the empty list. ṛ Right argument. Yields the list of addresses. € For each element in the list ¡ If{ e the element is in ¤ nilad{ ® the register U reversed ḣ first... ⁴ (cache depth) number of elements } C Complement. 1 <-> 0. Easier to type this than "not". $ Combines everything up to `e` into a monad } Then{ ɼ Apply to the register and store the result ; Append the element } ṛ Right argument: ɼ Apply to the register: L Length ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~43~~ 40 bytes ``` ->s,a,*r{a.count{|*x|r!=r=(r|x).pop(s)}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ1FHq6g6US85vzSvpLpGq6KmSNG2yFajqKZCU68gv0CjWLO29n9BaUmxQlq0iY5CtIGOgqGOgpGOgrGOAjLbBMxFiMTGckF1ASVB2AgsZQBWbARWjyxoglBvQqT6/wA "Ruby – Try It Online") Thanks histocrat for shaving 3 bytes. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~112 110~~ 108 bytes ``` f(x,y,z)int*y;{int*i=y+z,b[x],m=0;for(wmemset(b,z=-1,x);i-y;y++)wmemchr(b,*y,x)?:++m*x?b[z=++z%x]=*y:0;x=m;} ``` [Try it online!](https://tio.run/##xZNNboMwEIX3OYUbCcnGg8SPo1ZxrRyEskggtF5AKkJVTMTZqcFEeJGqLBJVLMZjz7x5n2xS7z1N@z7HDShoiSxrV/HLEKRQtIVD3CRQCJ/npwp/F8fifKzxAVrhBdAQLj3FFaVkOEk/Kn3iKr2/21JauM3uELeC0tZpEuGqrc8bUfCu1@qo2MsSE3RZITSkkk@Ls2yPetqUpaevsp7TbF/v/ThBAl06vtKbn5XezvE6x04GKF7D2E@Geu0XYalLfY4kejVSHFEqzdS5GZxMNxptmYzNnaWdEOFkb6UuyfGgPpWCUSRkNDLbNpZfbMuBsRxACBEwmOKdCeiThGnaYojgBkQ4QzzbEKGB8MH6HoUQLkcIbyBEM0IQ2gyRYYj0BQTa/xAZXLOHXUi0nCa6QcN@o2H/QsOW07A/aJhNs7m@L/N7XCMbX9q4fhTRZjnRxiLq@h8 "C (gcc) – Try It Online") Slightly less golfed ``` f(x,y,z)int*y;{ int*i=y+z,b[x],m=0; for(wmemset(b,z=-1,x);i-y;y++) wmemchr(b,*y,x)?: ++m* x? b[z=++z%x]=*y : 0; x=m; } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 156 bytes ``` s,n,m,i,j;f(x,_)int*_;{int c[x];n=m=0;for(i=0;i<x;++i)c[i]=-1;for(i=s=0;_[i]>=0;++i,s=0){for(j=0;j<x;++j)s|=(c[j]==_[i]);if(!s){c[n++]=_[i];m++;n%=x;}}x=m;} ``` [Try it online!](https://tio.run/##VVFhb4IwEP3Or7i5kLS2LuL8VusfYY0hRfTIKAvgQsb47exaUWdJuOt7vfce1K5O1k5TK52sJMpSFayXB46uWx7UQAVs2hvldKXXqqgbhlRx1yshkNsUjV4lM94ScyBkT5VYSXs@eKokoAwjJW9/NbNpabT2R7nCgr20fLCpE8IETFVCKBfrXo1jrys1Tq/o7OclP8Ku7XKs3877yAerMnTMN1lzshLsOWtgSf13ajgMEdDybIs/R9CQdTWywCZke2dtfaG3Dhqwgs2DwUebZ12WhpMiMSoK@FdDTMEWBYtzCelCBiM@s/TZwJB01woQdlcbBf6nzdH8CrpontIhCNjcEv43knFOJvPIzI/RXSY4eCm6j@eEhus4/3A0XDCf8SrCb1GbY3dpHAWNxml6p2czJdM61O19t/0D "C (gcc) – Try It Online") Description: ``` s,n,m,i,j; // Variable declaration f(x,_)int*_;{ // F takes X (the cache size) and _ (-1-terminated data) int c[x]; // declare the cache n=m=0; // next queue insert pos = 0, misses = 0 for(i=0;i<x;++i)c[i]=-1; // initialize the cache to -1 (invalid data) for(i=s=0;_[i]>=0;++i,s=0){ // for each datum in _ (resetting s to 0 each time) for(j=0;j<x;++j) // for each datum in cache s|=(c[j]==_[i]); // set s if item found if(!s){ // if no item found c[n++]=_[i]; // add it to the cache at position n m++; // add a mis n%=x; // move to next n position (with n++) }} x=m;} // 'return' m by assigning to first argument ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 44 bytes ``` n=>a=>a.map(y=t=>y[t]+n>p||(y[t]=++p),p=0)|p ``` [Try it online!](https://tio.run/##ldBRC8IgEAfw9z7FPSrappuDenBfZOxB1hbFUmkSDPbdzTaisIIm9/Dn4H53eFY3NTTXk3VbbQ6t76TXslShkouyaJROlmPlaqJLO03oESUhFlMrGZ6sb4weTN8mvTmiDjGMqhpj@PelKbDNJ8EpZBRyCoLCK3@HA7GLiCwQjEJcPw8LBI@IPBD5vJnPw0sWz7A03y4KxD4ixHqCx59RrDcKfwc "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` Ṗœ|Ṛḣ⁴$Ṛʋ\-;⁸e"ċ0 ``` [Try it online!](https://tio.run/##y0rNyan8///hzmlHJ9c83Dnr4Y7Fjxq3qABZp7pjdK0fNe5IVTrSbfD///9oYx0FIx0FQx0FAx0FCNsExoAImsT@NwEA "Jelly – Try It Online") Full program. Argument 1: stack (Python 3 `list` of `int`egers) Argument 2: `n` (Python 3 `int`eger) [Answer] # [Rust](https://www.rust-lang.org/), 129 bytes ``` |l:&[_],s|if s>0{let(mut c,mut m)=(vec![-1;s],0);for n in l.iter(){if!c.contains(n){c.remove(0);c.push(*n);m+=1;}}m}else{l.len()} ``` [Try it online!](https://tio.run/##RY5BCsIwFETX9hS/XciPfkOrrgz1IqWIhAQDSSpJ6ibN2WtduRkG3vCYMMe0ag/uaTwyyNXOqgQa@nWxt/3wGCkuRkO8t3kD6OYEkn7pWI8fJevh1Ik4UsuEngJ4MB4sN0kFZNnoWnI5@bTJI3qWJQ/KTR@F21zy9xxfePBMuGPfiVJcUTaqbLlV25eyimr3DsanGptcGtK4HzqCM8GF4Erw7yNBy5ioyvoF "Rust – Try It Online") ## Ungolfed ``` |l: &[isize], s: usize| { if s > 0 { let mut c = vec![-1; s]; let mut m = 0; for n in l.iter() { if !c.contains(n) { c.remove(0); c.push(*n); m += 1; } } m } else { l.len() } } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç═╛¢s▲▬╓í±°☻÷hi ``` [Run and debug it](https://staxlang.xyz/#p=80cdbe9b731e16d6a1f1f802f66869&i=0,+[]%0A0,+[1,+2,+3,+4,+1,+2,+3,+4]%0A2,+[0,+0,+0,+0,+0,+0,+0]%0A3,+[3,+2,+1,+0,+3,+2,+4,+3,+2,+1,+0,+4]%0A4,+[3,+2,+1,+0,+3,+2,+4,+3,+2,+1,+0,+4]&a=1&m=2) ]
[Question] [ Your task is to determine whether two numbers are *easy to multiply*. This means that their base-10 [long multiplication](http://mathworld.wolfram.com/LongMultiplication.html) doesn't have any carrying (regrouping) between place values, looking at both the multiplication steps and the addition step. This happens when each pair of digits being multiplied gives 9 or less and the sum of each column is 9 or less. For example, `331` and `1021` are easy to multiply: ``` 331 x 1021 ------ + 331 662 0 331 ------ 337951 ``` And the same is true (as is always) if we multiply in the other order: ``` 1021 x 331 ------ + 1021 3063 3063 ------ 337951 ``` But, `431` and `1021` are not easy to multiply, with carries happening between the columns indicated: ``` 431 x 1021 ------ + 431 862 0 431 ------ 440051 ^^^ ``` Also, `12` and `16` are not easy to multiply because a carry-over happens when multiplying `12 * 6` to get `72`, even though no carries happen in the addition step. ``` 12 x 16 ---- + 72 12 ---- 192 ``` **Input:** Two positive integers or their string representations. You may assume they will not overflow your language's integer type, nor will their product. **Output:** One consistent value if they are easy to multiply, and another consistent value if not. **Test cases:** The first 5 are easy to multiply, the last 5 are not. ``` 331 1021 1021 331 101 99 333 11111 243 201 431 1021 12 16 3 4 3333 1111 310 13 [(331, 1021), (1021, 331), (101, 99), (333, 11111), (243, 201)] [(431, 1021), (12, 16), (3, 4), (3333, 1111), (310, 13)] ``` **Leaderboard:** ``` var QUESTION_ID=151130,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/151130/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Dæc/>9Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l8LJkfTvLh7t2/D/c/qhpzf//0RrGxoY6CoYGRoaaOgoaIFpHASgE4QDZlpYgprGxMVARCIB4RiZAnpEBmG2Cot0IyDYDa9BRMIFqhOoE8wwNgBxjzVgA "Jelly – Try It Online") Uses convolution (which I contributed to Jelly :D) ## How it works ``` Dæc/>9Ẹ D converts to decimal list æc convolution >9Ẹ checks if any number is greater than 9 ``` [Answer] # JavaScript (ES6), 67 bytes Takes input as 2 strings in currying syntax `(a)(b)`. Returns `false` for easy or `true` for not easy. ``` a=>b=>[...a].some((x,i,a)=>[...b].some(y=>(a[-++i]=~~a[-i]+x*y)>9)) ``` ### Test cases ``` let f = a=>b=>[...a].some((x,i,a)=>[...b].some(y=>(a[-++i]=~~a[-i]+x*y)>9)) console.log('[Easy]') console.log(f('331')('1021')) console.log(f('1021')('331')) console.log(f('101')('99')) console.log(f('333')('11111')) console.log(f('243')('201')) console.log('[Not so easy]') console.log(f('431')('1021')) console.log(f('12')('16')) console.log(f('3')('4')) console.log(f('3333')('1111')) console.log(f('310')('13')) ``` --- # Alt. version (flawed), ~~64~~ ~~55~~ 52 bytes *Saved 3 bytes by taking strings, as suggested by @Shaggy* *As pointed out by @LeakyNun, this method would fail on some large specific integers* Takes input as 2 strings in currying syntax `(a)(b)`. Returns `true` for easy or `false` for not easy. ``` a=>b=>/^.(0.)*$/.test((g=n=>[...n].join`0`)(a)*g(b)) ``` ### Test cases ``` let f = a=>b=>/^.(0.)*$/.test((g=n=>[...n].join`0`)(a)*g(b)) console.log('[Easy]') console.log(f('331')('1021')) console.log(f('1021')('331')) console.log(f('101')('99')) console.log(f('333')('11111')) console.log(f('243')('201')) console.log('[Not so easy]') console.log(f('431')('1021')) console.log(f('12')('16')) console.log(f('3')('4')) console.log(f('3333')('1111')) console.log(f('310')('13')) ``` ### How? The idea here is to explicitly expose carries by inserting zeros before each digit of each factor. Examples: * **331 x 1021** becomes **30301 x 1000201**, which gives **30307090501** instead of **337951**. By adding a leading zero to the result and grouping all digits by 2, this can be written as **03 03 07 09 05 01**. All groups are less than **10**, meaning that there would not have been any carry in the standard multiplication. * **431 x 1021** becomes **40301 x 1000201**, which gives **40309100501** and can be written as **04 03 09 10 05 01**. This time, we have a **10** which reveals a carry in the standard multiplication. [Answer] # [Alice](https://github.com/m-ender/alice), 30 bytes ``` /Q.\d3-&+k!*?-n/ o @ \ic/*2&w~ ``` [Try it online!](https://tio.run/##S8zJTE79/18/UC8mxVhXTTtbUcteN09fIV/BgSsmM1lfy0itvO7/fyMTYwUjA0MA "Alice – Try It Online") Outputs `1` for easy and `0` for hard. The numbers are easy to multiply if and only if the digit sum of the product equals the product of the digit sums. ``` /i Input both numbers as a single string . Duplicate this string /* Coerce into two integers and multiply 2&w Push return address twice (do the following three times) ~\Q Swap the top two stack entries, then reverse the stack This produces a 3-cycle, and the first iteration coerces the original input string into two integers c Convert into individual characters \d3-&+ Add all numbers on the stack except the bottom two (i.e., add all digits) k Return to pushed address (end loop) At this point, all three numbers are replaced by their digit sums !*? Multiply the digit sums of the original two numbers - Subtract the digit sum of the product n Logical negate: convert to 1 or 0 /o@ Output as character and terminate ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` ,j!U]Y+9>a ``` Outputs `0` for easy, `1` for hard. [Try it online!](https://tio.run/##y00syfn/XydLMTQ2UtvSLvH/f2NjQy5DAyNDAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F8nSzE0NlLb0i7xf4RLyH9jY0MuQwMjKAHhGXJZWgKZxlyGIMBlZGLMZQQUNIErNeIyNOMy5jIBKYKoAgA). ### Explanation ``` , % Do twice j % Input as a string ! % Transpose into a column vector of characters U % Convert each character to number. Gives a numeric column vector ] % End Y+ % Convolution, full size 9> % Greatear than 1? Element-wise a % Any: true if there is some true entry. Implicitly display ``` [Answer] # [R](https://www.r-project.org/), ~~135~~ ~~110~~ ~~109~~ 86 bytes ``` function(m,n)any(convolve(m%/%10^(nchar(m):1-1)%%10,n%/%10^(1:nchar(n)-1)%%10,,"o")>9) ``` [Try it online!](https://tio.run/##NY3bCoMwEETf@xVFCOzCSl0DhUrppxTS1KBgdiFawa9PYy9Pc5gzMClP4yO5tEHsl0GfMx7C8Vrn8BK/jCoQSdDJBl5l1WntIZqT4eYO4geXIGLHNaMpFcnPcPd1gn9DlVZ4u2AOYC0TNy2XH9iTSvHhlvi8gy17tpjf "R – Try It Online") ~~Takes input as strings.~~ It's ugly but it works™. This now uses a convolution approach, as in [Leaky Nun's answer](https://codegolf.stackexchange.com/a/151134/67312), so it takes input as integers, and returns `TRUE` for hard to multiply numbers and `FALSE` for easy to multiply ones. I have always had some trouble porting convolution approaches in the past, but today I finally read [the documentation](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/convolve.html): > > Note that the usual definition of convolution of two sequences `x` and `y` is given by `convolve(x, rev(y), type = "o")` > > > Which is just silly. So the digit extraction is reversed for `n`, and it resolves into a port of Leaky Nun's answer. [Answer] # [Python 2](https://docs.python.org/2/), 88 bytes ``` lambda n,m:any(sum(n/10**(k-j)%10*(m/10**j%10)for j in range(k+1))>9for k in range(n+m)) ``` Takes two integers as input and returns `False` (easy to multiply) or `True` (not). [Try it online!](https://tio.run/##VY3BDoIwDIbP8BS9mKwy4zaICST6IsphRlHAlQXxwNPPDg7GXvr9X9r8fp6eA5nQwBEu4WXd9WaBpKsszeL9cYL2Wm23ot91uGESbskdMzbDCB20BKOlx130mUY8ldH2P0uZQwxR@ijPIs@1BK2MRgkibgms1sBclhFNkUswSmMt@aX4ezHMh0h8Uiybhx3PkrTikGNdpUmsFSTBYez2bBI/tjRBs9p0jeEL "Python 2 – Try It Online") (too slow for one of the test cases) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~43~~ ~~41~~ ~~37~~ 36 bytes Thanks @*[Dennis](https://codegolf.stackexchange.com/users/12012)* for the idea of using string interpolation in [this answer](https://codegolf.stackexchange.com/a/151789) and save 4 bytes! Thanks @*[ØrjanJohansen](https://codegolf.stackexchange.com/users/66041)* for -1! ``` a=>b=>eval(`0x${a}*0x${b}<0x${a*b}`) ``` [Try it online!](https://tio.run/##PcrdCoJAEAXg6@Yp5iJoJ0p2HAmCdu97hgpcS6PYVkkJIXx20/7m4sw58F3dw9XH@6VqlqE85X1hemdsZmz@cF6lup0@XTcfX9Zt3muedSn1xzLUpc8jX54VpCKMrGOGMXBYQ2Fcr0FEkMeDOBGMNUPypzHyCgSTEX0UCGtkSaO68pdGzfZhRtHNVQomrbGo0BtbKL/TBxqSD4Sk2h/Grw3GVu5e59vQqLBgTUQwIaD@BQ "JavaScript (Node.js) – Try It Online") Of course when the destination base is less than the original base (like in my Jelly answer, the base is 2) the `<` must be flipped. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~75~~ ~~66~~ ~~65~~ 56 bytes ``` f:=#~FromDigits~x& g:=Max@CoefficientList[f@#2f@#,x]<=9& ``` [Try it online!](https://tio.run/##bc09C4MwEAbg3Z8RwcnBfFCINCBYOrXQXTIESdIbVNAMTv711BPaaunBDfccd29nwtN2JkBrYnSlSpfrOHQX8BCmZc4SX6q7mat6sM5BC7YPN5hC46qUrZ3P@qxkFh8j9KHyDeGckpzQglGik49uc74tD4oo5d4453iPtWcmkFmB@FXxP4whng5fVxE/Me@cA9MClRMdXw "Wolfram Language (Mathematica) – Try It Online") Receiving 2 string inputs Explanation: ``` f:=#~FromDigits~x& (* Turns the number to a polynomial with the digits as coefficients *) g:=Max@CoefficientList[f@#2f@#,x]<=9& (* Polynomial multiplication, and check whether all coefficients are smaller than 10 *) ``` -9 for changing to use string as input -1 for using infix operator -9 Thanks @MartinEnder for the `Max` function [Answer] # [Python 2](https://docs.python.org/2/), ~~158~~ ~~135~~ ~~123~~ 113 bytes -12 bytes thanks to Leaky Nun -10 bytes thanks to ovs ``` a,b=input() e=enumerate l=[0,0]*len(a+b) for i,x in e(a): for j,y in e(b):l[i-~j]+=int(x)*int(y) print max(l)<10 ``` [Try it online!](https://tio.run/##JYzBCoQgFADvfsW76SsXtG6xfkl0UHjLGmYSBnrp191iTzPMYVLN3z0OrVnpjI/pzAIZGYrnRofNxIKZlVRLFygK2ztkn/0ALwv4CCQsTgyessr6Lw6nMPvXtS79/cuiYPegIkvHLbDZIgK@tWqNj6PmErhWg@Y/ "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##JYzBCoQgFADvfsW76SsXtG6xfkl0UHjLGmYSBnrp191iTzPMYVLN3z0OrVnpjI/pzAIZGYrnRofNxIKZlVRLFygK2ztkn/0ALwv4CCQsTgyessr6Lw6nMPvXtS79/cuiYPegIkvHLbDZIgK@tWqNj6PmErhWg@Y/ "Python 2 – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 30 bytes ``` ~x=any(conv(digits.(x)...).>9) ``` [Try it online!](https://tio.run/##VY7BCoMwDIbvfYogHlooxbYiyHAv4jyU6bYOqaO6US@@epc6L8sl/xeSjzzfozVVjFtojFvpdXIf2tu7XWZBAxNCMHGuWRzMvEIDLdVacpCFkowDTZ0Djn6Aua5T1FrjUqpEqkRShWQdeRjf75ryT6MwV/shh/IQHIadZIGg8Z7cJg8BrIM2fXRKvo7Ay1u3jI5meQCAy5LTDZ9nGSOD6@MX "Julia 0.6 – Try It Online") Input is a tuple of numbers, output is `true` for hard to multiply numbers and `false` for easy ones. `.` is element-wise function application. `...` expands the tuple (of lists of integer digits) to two seperate inputs of the `conv` function. [Answer] # [Python 3](https://docs.python.org/3/), ~~58~~ ~~3513~~ ~~40~~ 39 bytes ``` lambda n,m:eval(f'0x{n}*0x{m}<0x{n*m}') ``` Looks like I had this idea [two hours too late](https://codegolf.stackexchange.com/a/151785/12012). *Thanks to @ØrjanJohansen for golfing off 1 byte!* [Try it online!](https://tio.run/##VY7BCoMwDIbP@hS52UoPbSMDxT3J5sGxlQm2FpGxMXz2LlEvyyH5v5/8IfGzPKeAycEZrmns/e3eQ1C@ebz6UbhCv79hLan7tWVd@rWQyU0zRBgCXASiUWC0NVKB4KmArB1I1zVLRKQlLiZbEVltZKfoQPV3wJI@bREF1RE9shsZTYCya/KMnxBBgZf8SSQni/MQFuF2V@YHy/QD "Python 3 – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~268~~ ~~264~~ ~~247~~ ~~246~~ ~~243~~ 131 bytes ``` DEFINE('D(A)') M =INPUT N =INPUT OUTPUT =EQ(D(M) * D(N),D(M * N)) 1 :(END) D A LEN(1) . X REM . A :F(RETURN) D =D + X :(D) END ``` [Try it online!](https://tio.run/##PY0xCwIxDEbn9Fdku0RFKDod3FBIDg5s1NLCzc7iDf5/am7xLd9bHt/3s72297V3EJ0XUxqEEg8cIOO02KPVAPa3e6u@OOmThDLjAYWMT@6uxowRRlITDgIJb2oUGc@4YtHsm2CcqWhtxfxAcBI84uqJB171ftkJcecH "SNOBOL4 (CSNOBOL4) – Try It Online") Ports the approach by [Nitrodon](https://codegolf.stackexchange.com/a/151263/67312). I think this is the first time I've ever defined a function in SNOBOL, `D` for digit sum. ``` DEFINE('D(A)') ;* function definition M =INPUT ;* read input N =INPUT ;* read input OUTPUT =EQ(D(M) * D(N),D(M * N)) 1 :(END) ;* if D(M)*D(N)==D(M*N), ;* print 1 else print nothing. Goto End D A LEN(1) . X REM . A :F(RETURN) ;* function body D =D + X :(D) ;* add X to D END ``` ### old version, 243 bytes: ``` M =INPUT N =INPUT P =SIZE(M) Q =SIZE(N) G =ARRAY(P + Q) Z OUTPUT =LE(P) :S(E) M LEN(P) LEN(1) . A J =Q Y GT(J) :F(D) N LEN(J) LEN(1) . B W =I + J X =G<W> + A * B G<W> =LE(A * B,9) LE(X,9) X :F(E) J =J - 1 :(Y) D P =P - 1 :(Z) E END ``` [Try it online!](https://tio.run/##TY9NC8IwDIbPya/IsfULil4cVpisDstWuy/cdvQsevD/M5MhYi55H/Imb/t@vu6vx26aoCR7CbFrEcJPRbLNZXSq1AjVVwfWOdm0rtNBRVpSpXGEa9fyBtnCqaghaZRjW0mFC8xzM5o2lCJ4shUOkLfKs/GsMi2J4vB/xhPCjZ/B5z1CTzY/3I4MKS1kNJNkzbzay6LqpfdyUrI5xtOaDCRq0JjJV@KXR40OXcimaSuFxpgP "SNOBOL4 (CSNOBOL4) – Try It Online") Input on STDIN separated by newlines, output to STDOUT: a single newline for easy to multiply, and no output for not easy to multiply. This isn't going to win any awards but it presents another approach (well, really this is the naive approach). I don't think I could write this up in cubix, but SNOBOL is tough enough to work with as it is. ~~Since it takes input as a string, this will work for any input with less than 512 digits each; I'm not 100% sure how big `ARRAY`s in SNOBOL can be.~~ INPUT is buffered in this version of SNOBOL to have a maximum width of 1024 characters; all other characters are then lost. It appears that an ARRAY can be quite large; well over the 2048 cells necessary. ``` M =INPUT ;*read input N =INPUT ;*read input P =SIZE(M) ;*P = number of M's digits, also iteration counter for outer loop Q =SIZE(N) ;*Q = number of N's digits G =ARRAY(P + Q) ;*G is an empty array of length P + Q Z GE(P) :F(T) ;*if P<0, goto T (outer loop condition) M LEN(P) LEN(1) . A ;*A = P'th character of M J =Q ;*J is the iteration counter for inner loop Y GT(J) :F(D) ;*if J<=0, goto D (inner loop condition) N LEN(J) LEN(1) . B ;*B = J'th character of N W =I + J ;*W=I+J, column number in multiplication X =G<W> + A * B ;*X=G[W]+A*B, temp variable for golfing G<W> =LE(A * B,9) LE(X,9) X :F(END) ;*if A*B<=9 and X<=9, G[W]=X otherwise terminate with no output J =J - 1 :(Y) ;*decrement J, goto Y D P =P - 1 :(Z) ;*decrement P, goto Z T OUTPUT = ;*set output to ''; OUTPUT automatically prints a newline. END ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` ≔E⁺θη⁰ζFLθFLη§≔ζ⁺ικ⁺§ζ⁺ικ×I§θιI§ηκ‹⌈ζχ ``` [Try it online!](https://tio.run/##bU7BCsIwDL3vK3pMoMLqjjsNT4LCDv5AmXUtdp1bOhn7@RqniIKBQF7ee3lprB6bXvuUKiLXBjjqG9R@IhiksChFzr1gmV36UcDBhDZaGBDFN7aMX/Yq7sPZzLBIsR5xUlzxPf/lmDy5zhDsNMWPhLPdk/pZ2lXPldWjC5HDifjd2XVTBwurVY5YplQUKlP5VqXN3T8A "Charcoal – Try It Online") Link is to verbose version of code. Outputs a `-` when the numbers are easy to multiply. Explanation: ``` ≔E⁺θη⁰ζ ``` Initialise `z` to a large enough (sum of lengths of inputs) array of zeros. ``` FLθFLη ``` Loop over the indices of the inputs `q` and `h`. ``` §≔ζ⁺ικ⁺§ζ⁺ικ×I§θιI§ηκ ``` Perform one step of the long multiplication. ``` ‹⌈ζχ ``` Check for carries. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 52 bytes ``` f(a,b)=vecmax(Vec(Pol(digits(a))*Pol(digits(b))))<10 ``` [Try it online!](https://tio.run/##VYvNCsIwDIBfJeyUSAf9GcJAfQZPXsYO3dxGoWqZQ@rT13TuoLnk@0K@YGdXTiGlEa3o6Pga@puNeBl6PD88Xt3klidaot2PdsRzUDLZEPwbI5QnCLO7L4xFlgJ66z2OAiKRgKYxRglQUquWLW8BfPoKc11nNMbwU55sumLTcuXqL9fM@zUQUG3hVq6mJItpW0of "Pari/GP – Try It Online") [Answer] ## Haskell, ~~82~~ 81 bytes ``` q=map$read.pure f a=any(>9).concat.scanr((.(0:)).zipWith(+).(<$>q a).(*))(0<$a).q ``` The numbers a taken as strings. Returns `False` if the numbers are easy to multiply and `True` otherwise. [Try it online!](https://tio.run/##XYxBDoIwEEX3nmLSsJhR0hRKTDDANVwYFxOESIQKBRZ4eaSCLuzqvZfpv3P/KOp6nru04dazBd9kO9piVwKnbCbMYpL50@Q8yD5nYxElqhORfFXtuRrueCCJiZd1wAvsiVAl3oLd3HBlIIXWVmYAD5Z5wNHko7UTlAQXFFoHwheBCgNBPuBK/idv7jSOV9Nau2v31hBGLoRq0@h/LXR63D4vHP12vkNbCJRzLeg6vwE "Haskell – Try It Online") I think it's different enough from [@Laikoni's answer](https://codegolf.stackexchange.com/a/151308/34531). How it works: ``` q -- helper function to turn a string into a list of digits f a = -- main function, first number is parameter 'a' scanr .q -- fold the following function from the right (and collect -- the intermediate results in a list) into the list of -- digits of the second number 0<$a -- starting with as many 0s as there are digits in 'a' -- the function is, translated to non-point free: \n c->zipWith(+)((*n)<$>q a)$0:c -- 'n': next digit of 'b'; 'c': value so far (*n)<$>a -- multiplay each digit in 'a' with 'n' 0:c -- prepend a 0 to 'c' zipWith(+) -- add both lists element wise -- (this shifts out the last digit of 'c' in every step) concat -- flatten the collected lists into a single list any(>9) -- check if any number is >9 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~45~~ 44 bytes Edit: * -1 byte changing `==` to `<`. I thought of this before looking at the other answers, then discovered that the Alice one used the same basic idea. Posting anyway since it's shorter than the other Haskell answers. `?` takes two integers and returns a `Bool`. Use as `331?1021`. `False` means the multiplication is easy. ``` a?b=s(a*b)<s a*s b s=sum.map(read.pure).show ``` [Try it online!](https://tio.run/##VYzRDoIgFEDf/QrmeoAgJuDabFkfUj1AselScl5dn28X9CVeOOfunttYePuuW3rbhroNkx/tc9rNoWuDB9nbgd6pFY4dLtB8vgk5z08k53wdXB1jcvT2tSDWQO3esTMQuwfiMqhh7tOVuCGHefRMxm5ZbtQYJYgqtGKC0PgLgqNVkKsqojEGl@KLpks0XSBntPzLNfIxBYKUW7iVyVSBYtgj@wE "Haskell – Try It Online") * `s` is a function that calculates the sum of the digits of an integer. (`read.pure` converts a single digit character to an integer.) * If a pair of numbers is easy to multiply, the digit sum of the product is equal to the product of the digit sums. * Conversely, any carry during the long multiplication will reduce the digit sum of the product from that ideal. [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->a,b{(0..a+b=~/$/).all?{|r|(0..r).sum{|w|a[w].to_i*b[r-w].to_i}<10}} ``` [Try it online!](https://tio.run/##TY3BCsIwEETv/YoePFjdptmkCAWrH7IESQ4FocXSWoI08ddjUj04h503w8JMi3mFrg3lRYNZ95wxfTTtu9pVBdN9f13d5FI7FWxehtVZp8kq9nzc7gdDU/ljf0bufSCSEgG5QAWUDGLeEKFpIohaguCpqv8eBeApuoQ63SjAqMTIAaVSbNBj2s7yqDEnCx1Z4tv2DJbwS0plPnwA "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 123 bytes ``` import Data.List r=read.pure a%b|l<-transpose[reverse$map((*r d).r)b++(0<$e)|d:e<-scanr(:)""a]=all(<10)$concat l++map sum l ``` [Try it online!](https://tio.run/##VYwxjoMwEEV7TjFCRLIDQRijlRJBt2W22jKiGMBS0BpjjU3S5O6sSdLEzfw34/@u6P6U1us6TnYmD9/oMT@PzkfUkMIhtwupCHfdQ9cHT2icnZ26kLopciqZ0DK2Jxh4TrxLU1bUieKP4aTqg@vREDvxOMa2Qa1ZLQqe9LPp0YNO09AFt0ygV6@cZ5h1HBqwNBoPCbjrfAeE3St00YSjCedhhghC8we2ElyYlCIDUZSCZ8C2mUFYvSDk43GLUsrwaXsblVWgshC8jcAu/tfT2cTxp7b60JYhfz1FGVRv4dv4JFEEkLxd/wE "Haskell – Try It Online") Example usage: `"331" % "1021"` yields `True`. [Answer] # [Perl 5](https://www.perl.org/), 100 + 2 (`-F`) = 102 bytes ``` push@a,[reverse@F]}{map{for$j(@{$a[0]}){$b[$i++].='+'.$_*$j}$i=++$c}@{$a[1]};map$\||=9>eval,@b;say$\ ``` [Try it online!](https://tio.run/##HcvBCsIgGADge8/xwyo30YGHGIan3XoCJ@HCyLFStAbhfPUsun@fN2FmpfhXvAldy2AWE6IRvcrprn26ugDTViTQkqi8SzBKsAgpzCtUYTjvYcpgOUJwyX9FVe5@EYZ15YejWfRci7GL@g1DKbRlG9p@nH9a94ilOTFMKClN/wU "Perl 5 – Try It Online") outputs false for easy, true for not easy. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ;PDḄµṪ⁼P ``` [Try it online!](https://tio.run/##y0rNyan8/986wOXhjpZDWx/uXPWocU/A/8Ptj5rW/P8frRCtYGxsqKNgaGBkqBCrw6UAFACxdUDCCAEg39ISxjU2NgZqAAGYiJEJUMTIAM43wTDSCMg3gxugo2CCZBjUNLiIoQFQwFghViGWCwA "Jelly – Try It Online") A port of my Javascript [answer](https://codegolf.stackexchange.com/a/151785). Not shorter than the existing Jelly [answer](https://codegolf.stackexchange.com/a/151134) because Jelly have powerful convolution built-in. Take input as a list of two numbers. Returns `1` for easy, `0` for not easy. --- Explanation: ``` ;PDḄµṪ⁼P Main link. Let input = [101, 99] ;P Concatenate with product. Get [101, 99, 9999] D Convert to decimal. Get [[1,0,1], [9,9], [9,9,9,9]] Ḅ Convert from binary. Get [1 * 2^2 + 0 * 2^1 + 1 * 2^0, 9 * 2^1 + 9 * 2^0, 9 * 2^3 + 9 * 2^2 + 9 * 2^1 + 9 * 2^0] = [5, 27, 135] µ With that value, Ṫ Take the tail from that value. Get 135, have [5, 27] remain. ⁼ Check equality with... P The product of the remaining numbers (5 and 17). ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 104 bytes Basically do a multiplication "by hand" into r[] and set return value if any column gets higher than 9, since that would mean a carry has occurred. Surprisingly, this was shorter than my first attempt which took strings as arguments. ``` f(a,b){int*q,r[10]={0},*p=r,R=0,B;for(;a;a/=10)for(q=p++,B=b;B;B/=10)R|=(*q+++=a%10*(B%10))>9;return R;} ``` [Try it online!](https://tio.run/##fc6xasMwEAbgOXkKYQhI1plItik4Qh0Ehcxe6w6KU5UMVWzFGYrrZ3fOgXSKquFA9x13f5t9te08O2rhwMaTH9IewrsUH3oUE6SdDlBrAUa5c6DKKrvVUrDl0@uOczD6oIwy9279q2nac8613UiRUoOVsddKhc/hGjyp1TTjBfJtT56y9bheddfhQpM3e/nZNT7LsoQpbAYccjTZHBufAHG0KCQQKXLJnvIiQHAoxqhVxSKrC1y9vOeel@i5uOsjbuP3NhzjgVeOlv8lRpc58ksE8WIZo7@8sQEp0ItFp/kG "C (gcc) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` §§=¤`o*oΣd ``` [Try it online!](https://tio.run/##yygtzv7//9DyQ8ttDy1JyNfKP7c45f///8bGhv8NDYwMAQ "Husk – Try It Online") Outputs `1` if the arguments are easy to multiply, and `0` otherwise. A port of [Nitrodon's answer](https://codegolf.stackexchange.com/a/151263). [Answer] # [CJam](https://sourceforge.net/p/cjam), 18 bytes ``` {_{Ab:+}:T/*\:*T=} ``` [Try it online!](https://tio.run/##S85KzP1fWBf7vzq@2jHJSrvWKkRfK8ZKK8S29n/df0MDI0MFY2NDAA "CJam – Try It Online") Takes input on the stack in the form of `[1021 331]`. Checks that the product of the sum of the digits and the sum of the digits of the product are equal. To take input as a space-delimited string, remove the outer curly braces and prepend with `q~]`. ## Alternate 18-byter ``` {{'0*i}/*`);-2%i!} ``` [Try it online!](https://tio.run/##S85KzP1fGKz/v7pa3UArs1ZfK0HTWtdINVOx9n/df0MDI0MFY2NDAA "CJam – Try It Online") Takes input on the stack in the form of `["1021" "331"]`. A port of Arnauld's [fantastic answer](https://codegolf.stackexchange.com/a/151137/82738). To take input as a space-delimited string, remove the outer curly braces and prepend with `qS/`. ]
[Question] [ One of easiest code written by a programming language is a program printing sequence of characters (ex. "Hello, world!"). However, [s](http://www.lscheffer.com/malbolge.shtml)[o](http://esolangs.org/wiki/Asdf)[m](http://esolangs.org/wiki/Polynomial)[e](http://esolangs.org/wiki/Funciton) [e](http://esolangs.org/wiki/Fugue)[s](http://esolangs.org/wiki/DNA-Sharp)[o](http://esolangs.org/wiki/NULL)[t](http://esolangs.org/wiki/Fractran%2B%2B)[e](http://www.bigzaphod.org/whirl/)[r](http://en.wikipedia.org/wiki/Shakespeare_%28programming_language%29)[i](http://www.dangermouse.net/esoteric/piet.html)[c](http://compsoc.dur.ac.uk/whitespace/) programming languages like [Brainfuck](http://en.wikipedia.org/wiki/Brainfuck), even this simplest code is quite annoying to write. Your task is to write a program (don't have to written in brainfuck), which prints a (minimum-length) Brainfuck program printing the given text. ## Input A sequence of characters (between `1` and `255`) is given by any format (variable, argument, stdin, file, ...). ## Output Output is a valid (no non-matching `[` and `]`) brainfuck code (assume unsigned 8-bit wrapping cell and unlimited number of cells to left and right) printing exact string that was given as input. For example, one possible output for input `A` is `++++++++[<++++++++>-]<+.`. Your program shouldn't take long time (`>2m`) to run. The BF program shouldn't take long time (`>10s`) to run. ## Scoring *(Notice : current scoring method may change, since it is not easy to calculate...)* The length of program (generating BF code) itself *doesn't* matter. However, hard-coding BF codes in the program code is not OK. Only acceptable range (ex. a BF code printing a single character `0x01` : `+.`) of BF codes might be hard-coded. The score is sum of length of BF codes printing these strings. * A string `Hello, world!` appended with a single `0x0A` (`\n`) (i.e. the "Hello, world!" program) * Single character from `0x01` ~ `0xFF` + Sum of length of these 255 BF codes are multiplied by `1/16`, rounded, and added to the score. * List of first 16 strings, generated by splitting [a random sequence of bytes generated on 11-11-11](http://www.random.org/files/) by `0x00`, removing all zero-length strings. * [Lenna.png](http://en.wikipedia.org/wiki/File%3aLenna.png), removing all `0x00`s. * Lyrics of the song [99 bottles of beer](http://99-bottles-of-beer.net/lyrics.html), starting with `99 bottles~`, newlines are `0x0A`, paragraphs are separated by two `0x0A`s, and no newline character at the end. * Other strings you may provide. Your program may include calculating the score of itself. Of-course, lowest-score code will be the winner. [Answer] In Java, computes a short BF snippet which can convert any number to any other number. Each output byte is generated by either transforming the last output byte or a fresh 0 on the tape. The snippets are generated in three ways. First by simple repetitions of `+` and `-` (e.g. `++++` converts 7 to 11), by combining known snippets (e.g. if A converts 5 to 50 and B converts 50 to 37, then AB converts 5 to 37) and simple multiplications (e.g. `[--->+++++<]` multiplies the current number by 5/3). The simple multiplications take advantage of wraparound to generate unusual results (e.g. `--[------->++<]>` generates 36 from 0, where the loop executes 146 times, with a total of 4 descending and 1 ascending wraparounds). I'm too lazy to compute my score, but it uses about 12.3 BF operations per byte on `Lenna.png`. ``` import java.io.*; class shortbf { static String repeat(String s, int n) { StringBuilder b = new StringBuilder(); for (int i = 0; i < n; i++) b.append(s); return b.toString(); } // G[x][y]: BF code that transforms x to y. static String[][] G = new String[256][256]; static { // initial state for G[x][y]: go from x to y using +s or -s. for (int x = 0; x < 256; x++) { for (int y = 0; y < 256; y++) { int delta = y - x; if (delta > 128) delta -= 256; if (delta < -128) delta += 256; if (delta >= 0) { G[x][y] = repeat("+", delta); } else { G[x][y] = repeat("-", -delta); } } } // keep applying rules until we can't find any more shortenings boolean iter = true; while (iter) { iter = false; // multiplication by n/d for (int x = 0; x < 256; x++) { for (int n = 1; n < 40; n++) { for (int d = 1; d < 40; d++) { int j = x; int y = 0; for (int i = 0; i < 256; i++) { if (j == 0) break; j = (j - d + 256) & 255; y = (y + n) & 255; } if (j == 0) { String s = "[" + repeat("-", d) + ">" + repeat("+", n) + "<]>"; if (s.length() < G[x][y].length()) { G[x][y] = s; iter = true; } } j = x; y = 0; for (int i = 0; i < 256; i++) { if (j == 0) break; j = (j + d) & 255; y = (y - n + 256) & 255; } if (j == 0) { String s = "[" + repeat("+", d) + ">" + repeat("-", n) + "<]>"; if (s.length() < G[x][y].length()) { G[x][y] = s; iter = true; } } } } } // combine number schemes for (int x = 0; x < 256; x++) { for (int y = 0; y < 256; y++) { for (int z = 0; z < 256; z++) { if (G[x][z].length() + G[z][y].length() < G[x][y].length()) { G[x][y] = G[x][z] + G[z][y]; iter = true; } } } } } } static void generate(String s) { char lastc = 0; for (char c : s.toCharArray()) { String a = G[lastc][c]; String b = G[0][c]; if (a.length() <= b.length()) { System.out.print(a); } else { System.out.print(">" + b); } System.out.print("."); lastc = c; } System.out.println(); } static void genFile(String file) throws IOException { File f = new File(file); int len = (int)f.length(); byte[] b = new byte[len]; InputStream i = new FileInputStream(f); StringBuilder s = new StringBuilder(); while (true) { int v = i.read(); if (v < 0) break; if (v == 0) continue; // no zeros s.append((char)v); } generate(s.toString()); } public static void main(String[] args) throws IOException { genFile(args[0]); } } ``` [Answer] Well here's about the worst possible solution, although a rather nice looking one in Brainfuck itself: ``` ++++++[>+++++++>+++++++++++++++>+++++++<<<-]>++++>+>+>,[[<.>-]<<<.>.>++.--<++.-->>,] ``` Score is probably the worst we are likely to see without intentionally making it bad. Working on calculating actual score. [Answer] # Python 3.x Well, I'm not going to win any prizes for the shortest output code but maybe for the program to generate the code... ``` x=input();o='' for i in x: a=ord(i) o+="+"*a+".[-]" print(o) ``` 'Hello, World!\n': ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[-]++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++.[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++.[-]+++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++.[-]++++++++++++++++++++++++++++++++++++++++ ++++.[-]++++++++++++++++++++++++++++++++.[-]++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++.[-]+++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++.[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++.[-]++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[-] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++.[-]+++++++++++++++++++++++++++++++++.[-]++++++++++.[-] ``` [Answer] I'm not sure how good it is, but I had fun writing this. (In Clojure...) ``` (ns bf.core) (def input "Hello world!") (defn abs [x] (if (and (< x 0) (= (type x) (type 1))) (* x -1) x)) (defn sqrt? [x y] (if (= (* y y) x) true false) ) (defn sqrt [x] (for [y (range x) :when (sqrt? x y)] y) ) (defn broot [x] ; Run this using trampoline, e.g., (trampoline broot 143) (if (< x 2) nil) (let [y (sqrt x)] (if (not= (seq y) nil) (first y) (broot (dec x) ) ) ) ) (defn factor [x] (if (<= x 2) x) (for [y (range (- x 1) 1 -1) :when (= ( type (/ x y) ) (type 1) ) ] y) ) (defn smallest_factors [x] (let [ facts (factor x) ] (if (= (count facts) 2) facts) (if (< (count facts) 2) (flatten [facts facts]) (let [ y (/ (dec (count facts) ) 2) yy (nth facts y) z (inc y) zz (nth facts z) ] (if (= (* yy zz) x ) [yy zz] [yy yy]) ) ) ) ) (defn smallestloop [x] (let [ facts (smallest_factors x) fact (apply + facts) sq (trampoline broot x) C (- x (* sq sq) )] (if (and (< fact (+ (* 2 sq) C) ) (not= fact 0)) facts [sq sq C]) ) ) (def lastx nil) ;Finally! (defn buildloop [x] (if (nil? lastx) (let [pluses (smallestloop x)] (apply str (apply str (repeat (first pluses) \+)) "[>" (apply str (repeat (second pluses) \+)) "<-]>" (if (and (= (count pluses) 3) (> (last pluses) 0)) (apply str(repeat (last pluses) \+)) ) "." ) ) (let [diff (abs (- x lastx) )] (if (< diff 10) (if (> x lastx) (apply str (apply str (repeat diff \+)) "." ) (apply str (apply str (repeat diff \-)) "." ) ) (let [signs (smallestloop diff)] (apply str "<" (apply str (repeat (first signs) \+)) "[>" (if (> x lastx) (apply str (repeat (second signs) \+)) (apply str (repeat (second signs) \-)) ) "<-]>" (if (and (= (count signs) 3) (> (last signs) 0)) (if (> x lastx) (apply str(repeat (last signs) \+)) (apply str(repeat (last signs) \-)) ) ) "." ) ) ) ) ) ) (for [x (seq input) :let [y (buildloop (int x))] ] (do (def lastx (int x)) y ) ) ``` There are probably more efficient solutions, and more elegant ones, but this follows my thought pattern somewhat linearly, so it was easiest. [Answer] **Score: ~~4787486~~ ~~4143940~~ 4086426** (without randomly generated data) (4085639 of that are from Lenna.png. That's 99.98%) I don't get the part with the random data. Don't I need an account which I have to pay for to get the data? Pretty naive. Here's the generated code for "1Aa" (49, 65, 97) with a little documentation: ``` // field 0 and 1 are loop counters. // The fields 2, 3 and 4 are for "1", "A" and "a" ++++++++++[ // do 10 times > ++++++++++[ // do 10 times > // "1" (49) is below 50 so we don't need to do anything here >+ // When the loops are done, this part will have increased the value of field 3 by 100 (10 * 10 * 1) >+ // same as above <<<- // decrease inner loop counter ] >+++++ // this will add 50 (10 * 5) to field 2, for a total of 50 >---- // subtract 40 from field 3, total of 60 > // Nothing done, value stays at 100 <<<<- // decrease outer loop counter ] >>-. // subtract 1 from field 2, total now: 49, the value for "1" >+++++. // add 5 to field 3, makes a total of 65, the value for "A" >---. // subtract 3 from field 4, total of 97, the value for "a" ``` The Java code is a bit ugly but it works. The generated instruction per input byte ratio is probably better the higher the average byte value is. If you want to run it, you have to put Lenna.png in the same directory as the .class file. It prints the score to console and writes the generated BF code into a file called "output.txt". ``` import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; public class BrainFuckGenerator { public static CharSequence generate(byte[] bytes) { final StringBuilder brainfuckBuilder = new StringBuilder(); for(int j = 0; j<10; j++) brainfuckBuilder.append("+"); brainfuckBuilder.append("[>"); for(int j = 0; j<10; j++) brainfuckBuilder.append("+"); brainfuckBuilder.append("["); final StringBuilder singles = new StringBuilder(); final StringBuilder tens = new StringBuilder(); final StringBuilder goBack = new StringBuilder(); for(byte b: bytes) { brainfuckBuilder.append(">"); for(int j=0; j<(b/100); j++) { brainfuckBuilder.append("+"); } tens.append(">"); if((b - (b/100)*100)/10 <= 5) { for(int j=0; j<(b - (b/100)*100)/10; j++) { tens.append("+"); } } else { brainfuckBuilder.append("+"); for(int j=0; j<10 - (b - (b/100)*100)/10; j++) { tens.append("-"); } } singles.append(">"); if(b%10 <= 5) { for(int j=0; j<b%10; j++) { singles.append("+"); } } else { tens.append("+"); for(int j=0; j<10 - (b%10); j++) { singles.append("-"); } } singles.append("."); goBack.append("<"); } goBack.append("-"); brainfuckBuilder .append(goBack) .append("]") .append(tens) .append("<") .append(goBack) .append("]>") .append(singles); return brainfuckBuilder; } public static void main(String[] args) { /* Hello, World! */ int score = score("Hello, world!"+((char)0xA)); /* 255 single chars */ int charscore = 0; for(char c=1; c<=0xff; c++) charscore += score(String.valueOf(c)); score += Math.round(((double)charscore)/16); /* Lenna */ final File lenna = new File("Res/Lenna.png"); final byte[] data = new byte[(int)lenna.length()]; int size = 0; try(FileInputStream input = new FileInputStream(lenna)) { int i, skipped=0; while((i = input.read()) != -1) if(i == 0) skipped++; else data[size++ - skipped] = (byte)(i&0xff); } catch (IOException e) { e.printStackTrace(); } score += score(Arrays.copyOf(data, size), "Lenna"); /* 99 Bottles */ final StringBuilder bottleBuilder = new StringBuilder(); for(int i=99; i>2; i--) { bottleBuilder .append(i) .append(" bottles of beer on the wall, ") .append(i) .append(" bottles of beer.") .append((char) 0xa) .append("Take one down and pass it around, ") .append(i-1) .append(" bottles of beer on the wall.") .append((char) 0xa) .append((char) 0xa); } bottleBuilder .append("2 bottles of beer on the wall, 2 bottles of beer.") .append((char) 0xa) .append("Take one down and pass it around, 1 bottle of beer on the wall.") .append((char) 0xa) .append((char) 0xa) .append("No more bottles of beer on the wall, no more bottles of beer. ") .append((char) 0xa) .append("Go to the store and buy some more, 99 bottles of beer on the wall."); score(bottleBuilder.toString(), "99 Bottles"); System.out.println("Total score: "+score); } private static int score(String s) { return score(s, null); } private static int score(String s, String description) { final CharSequence bf = generate(s.getBytes()); try(FileWriter writer = new FileWriter("Res/output.txt", true)) { writer.write((description == null ? s : description)); writer.write(NL); writer.write("Code:"); writer.write(NL); writer.write(bf.toString()); writer.write(NL+NL); } catch (IOException e) { e.printStackTrace(); } return bf.length(); } private static int score(byte[] bytes, String description) { final CharSequence bf = generate(bytes); try(FileWriter writer = new FileWriter("Res/output.txt", true)) { if(description != null) { writer.write(description); writer.write(NL); } writer.write("Code:"); writer.write(NL); writer.write(bf.toString()); writer.write(NL+NL); } catch (IOException e) { e.printStackTrace(); } return bf.length(); } private static final String NL = System.getProperty("line.separator"); } ``` ~~I'm going to make some small improvements but probably not much.~~ Done. [Answer] # BrainF\*\*k I'm a pretty bad BF programmer, so this answer is probably pretty inefficient. I'm unsure of the score, but it should perform slightly better than the existing answer on your average text. Rather than zeroing the cell out after every character, this one will "adjust" to a new character with subtraction if the previous character given is larger. ``` >>++++++[-<+++++++>]<+>>+++++[-<+++++++++>]>+++++[-<+++++++++>]<+>>,[-<+>>>>>>+<<<<<]<[-<<<.>>>]<.>>+>,[[-<<+>>>+>>+<<<]>>>>[-<<+>>]<[->+<]<<[->-[>]<<]<[->->[-<<<<<<.>>>>>>]<<]>+[-<<->>>[-<<<<<<.>>>>>>]<]<<<[>]<<.>[-]>+>,] ``` (Note, this is code I wrote a long time ago, and have repurposed for this competition. I sincerely hope I've done the conversion correctly, but if it fails for any input let me know.) A version showing the state of the tape throughout the code: ``` >>++++++[-<+++++++>]<+> [0 '+' 0] ^ >+++++[-<+++++++++>] [0 '+' '-' 0] ^ >+++++[-<+++++++++>]<+> [0 '+' '-' '.' 0] ^ >,[-<+>>>>>>+<<<<<] [0 '+' '-' '.' a 0 0 0 0 0 a] ^ <[-<<<.>>>]<.>>+> [0 '+' '-' '.' 0 1 0 0 0 0 a] ^ ,[[-<<+>>>+>>+<<<] [0 '+' '-' '.' b 1 0 b 0 b a] [b is not 0] ^ >>>>[-<<+>>]<[->+<] [0 '+' '-' '.' b 1 0 b a 0 b] ^ <<[->-[>]<<] <[->->[-<<<<<<.>>>>>>]<<] >+[-<<->>>[-<<<<<<.>>>>>>]<] [0 '+' '-' '.' b 0 0 0 0 0 b] ^|^ [OUTPUT ONE CHARACTER BY THIS POINT] <<<[>]<<.>[-]> [0 '+' '-' '.' 0 0 0 0 0 0 b] ^ +>,] [End when b == 0] [GOAL: '+' '-' '.' b 1 0 b a 0 a] ``` Generated code for `Hello, World!`: ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------. ``` *This is my first answer on CG.SE! If I've screwed something up, let me know!* [Answer] ## ><> ``` i:&v .21<>i:0(?;:&:@(4g62p$:&-01-$:@0(?*l2=?~02. >:?!v"+"o1- "."~<.15o +- ``` I wrote this in response to a question marked for a duplicate, and even though this isn't the greatest golf (for this specific question, at least) I figured it'd be kind of a waste if I didn't share it in all of its disgustingly gibberish-y glory. Really, I'm half-surprised it even works. I'll take any suggestions to golf it down since that was my main goal in its creation. As a side note, in the second line the beginning three characters `.21` could be replaced with `v` followed by two spaces if that makes it any easier to read. I don't like to see spaces in my ><> programs because that means there's wasted space (literally). It also is a remnant from one of many prototypes. The way it functions is really simple, and quite frankly I'd have a difficult time thinking of a way to implement another algorithm. It prints however many "+"s need to be printed for the first character, and then prints more "+"s or "-"s as needed for each additional character, separating each section with periods. What I find cool about the program is that it modifies its own source code so that it prints "+" or "-" (it replaces the "+" on line 3 with the appropriate character after determining whether the current character is greater than or less than the previous one). Output for `Hello, World!`: ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------. ``` I might score this the way it was intended to be scored, but I'm almost positive I'd lose and I don't entirely know how to read something like lenna.png in ><>. If this answer interests you and you'd like an explanation, by all means ask, but for now I'll leave it without one just because of how twisty and turny it is. EDIT 1: It's been a while but I was able to golf off 2 bytes with an almost complete overhaul of the way the program decides whether to print a plus or a minus. It's a somewhat disappointing return for a large overhaul but at least it works. [Answer] # Kotlin First I must admit that about half of this is shamelessly stolen from Keith Randel's answer. I literally copied and pasted his code for finding multiplications into mine. It is very well done. I have made 2 modifications to his code. 1. It is very easy to reverse the direction of any of the transitions Keith's code produces. All you have to do is replace `<` with `>` and `>` with `<`. Ex. `+[->++<]>` becomes `+[-<++>]<`. This means that equally, good code\* that only uses 2 cells can be produced. 2. The second thing I did was to add a hash. To add a hash the code simply includes a `>` after the `.`. Then for all subsequent characters, the program calculates if the code to move to the hash (such as `<<<.>>>`) is shorter than the regular code to produce this output. To find the locations for the hash the program loops through each character of the input and checks if hashing that character decreases the length of the program. It only hashes each type of character once which is slightly inefficient but is necessary to make the program not run like a snail. Speaking of time complexity my program is quadratic time as opposed to Keith's which is linear. This is because the full code for any hash configuration has to be generated for each character. It is still possible to stop the algorithm early and get a better result than you started with as each cache only improves the score. So how good does it do. Theoretically, it always does better than Keith's however, this isn't quite true. Keith's code can get to zero from any number simply by inserting a `>` but mine cannot because it would move too far from the hash. As a result, some of my transitions are slightly longer than Keith's meaning I actually achieve a lower score on `Lenna.png`. However since most of the transitions where starting with zero instead are very small or very large if you only include letters in the printable ASCII range 32 to 126 my program does beat Keith's. So although it can be worse my algorithm is better in practice. Lets look at some numbers. ### Numbers ``` Lenna.png (no 0s), 471470 characters Keith: 5832730 bf chars, 12.37 bf chars / input Me: <5894582 bf chars, <12.5 bf chars / input Keith + 0.13 ``` ``` Lenna.png (32 to 126), 174177 characters Keith: 2022451 bf chars, 11.61 bf chars / input Me: <1977716 bf chars, 11.25 bf chars / input Me + 0.36 ``` ``` Hello, World!\n, 14 characters Keith: 139 bf chars, 9.93 bf chars / input Me: 139 bf chars, 9.93 bf chars / input Even ``` ``` I went to the store today, 25 characters Keith: 265 bf chars, 10.6 bf chars / input Me: 190 bf chars, 7.6 bf chars / input Me + 3 ``` ``` 447 characters of Lorem Ipsum Keith: 4427 bf chars, 9.9 bf chars / input Me: 3017 bf chars, 6.75 bf chars / input Me + 3.15 ``` ``` 1001 random lowercase letters Keith: 8035 bf chars, 8.03 bf chars / input Me: 7028 bf chars, 7.02 bf chars / input Me + 1.01 ``` ### Code ``` const val CELL_SIZE = 256 const val WRAPPING = true enum class Direction { LEFT, RIGHT; fun opposite() = when (this) { LEFT -> RIGHT RIGHT -> LEFT } } data class Transition( val code: String, val startD: Direction, val endD: Direction, ) { fun plus(t: Transition) = if (endD == t.startD) { Transition(code + t.code, t.startD, t.endD) } else { val r = t.reverse() Transition(code + r.code, t.startD, r.endD) } fun reverse(): Transition { val newCode = code.replace(">", "|").replace("<", ">").replace("|", "<") return Transition(newCode, startD.opposite(), endD.opposite()) } } var simpleTransitions = { val list = Array(CELL_SIZE) { start -> Array(CELL_SIZE) { end -> var delta = end - start if (WRAPPING) when { delta > CELL_SIZE / 2 -> delta -= CELL_SIZE delta < -CELL_SIZE / 2 -> delta += CELL_SIZE } val char = if (delta > 0) "+" else "-" Transition(char.repeat(abs(delta)), Direction.LEFT, Direction.LEFT) } } //check for multiplication for (x in 0..255) { for (n in 1..39) { for (d in 1..39) { var j = x var y = 0 for (i in 0..255) { if (j == 0) break j = j - d + 256 and 255 y = y + n and 255 } if (j == 0) { val s = "[" + "-".repeat(d) + ">" + "+".repeat(n) + "<]>" if (s.length < list[x][y].code.length) { list[x][y] = Transition(s, Direction.LEFT, Direction.RIGHT) } } j = x y = 0 for (i in 0..255) { if (j == 0) break j = j + d and 255 y = y - n + 256 and 255 } if (j == 0) { val s = "[" + "+".repeat(d) + ">" + "-".repeat(n) + "<]>" if (s.length < list[x][y].code.length) { list[x][y] = Transition(s, Direction.LEFT, Direction.RIGHT) } } } } } for (i in 0 until CELL_SIZE) { if (list[i][0].code.length > 3) list[i][0] = Transition("[-]", Direction.LEFT, Direction.LEFT) } var change = true while (change) { change = false for (i in 0 until CELL_SIZE) { for (j in 0 until CELL_SIZE) { for (k in 0 until CELL_SIZE) { if (list[i][j].code.length + list[j][k].code.length < list[i][k].code.length) { list[i][k] = list[i][j].plus(list[j][k]) change = true } } } } } println("done") list }() fun generate(s: String, cells: Int): String { var caches: MutableList<Boolean> = MutableList(s.length) { false } var currentCost = generateFromCache(s, caches) val changes: MutableMap<Char, Int> = mutableMapOf() if (cells > 2) { for ((i, c) in s.withIndex()) { val newCaches = caches.mapIndexed { index, b -> if (s[index] == c) false else b }.toMutableList() var lowest: Char? = null if (newCaches.count { it } >= cells - 2) { lowest = changes.minByOrNull { it.value }!!.key newCaches[newCaches.withIndex().indexOfFirst { it.value && s[it.index] == lowest }] = false } newCaches[i] = true val newCost = generateFromCache(s, newCaches) if (newCost.length < currentCost.length) { println(newCost.length) changes[c] = currentCost.length - newCost.length currentCost = newCost caches = newCaches if (lowest != null) changes.remove(lowest) } } } return currentCost } ``` [Answer] my JavaScript solution it`s quick and dirty :) output for `Hello World\n` ``` ++++++++++[>+++++++>++++++++++>+++++++++++>+++>+++++++++>+<<<<<<-]>++.>+.>--..+++.>++.>---.<<.+++.------.<-.>>+.>>. ``` Source: ``` BfGen("Hello World!\n"); // ++++++++++[>+++++++>++++++++++>+++++++++++>+++>+++++++++>+<<<<<<-]>++.>+.>--..+++.>++.>---.<<.+++.------.<-.>>+.>>. // Length of BF code: 115 // Score: 8.846153846153847 function BfGen(input) { function StringBuilder() { var sb = {}; sb.value = ''; sb.append = (txt) => sb.value += txt; return sb; } function closest (num, arr) { var arr2 = arr.map((n) => Math.abs(num-n)) var min = Math.min.apply(null, arr2); return arr[arr2.indexOf(min)]; } function buildBaseTable(arr) { var out = StringBuilder(); out.append('+'.repeat(10)); out.append('[') arr.forEach(function(cc) { out.append('>'); out.append('+'.repeat(cc/10)); }); out.append('<'.repeat(arr.length)); out.append('-'); out.append(']'); return out.value; } var output = StringBuilder(); var charArray = input.split('').map((c) =>c.charCodeAt(0)); var baseTable = charArray.map((c) => Math.round(c/10) * 10).filter((i, p, s) => s.indexOf(i) === p); output.append(buildBaseTable(baseTable)); var pos = -1; charArray.forEach(function (charCode) { var bestNum = closest(charCode, baseTable); var bestPos = baseTable.indexOf(bestNum); var moveChar = pos < bestPos? '>' : '<'; output.append(moveChar.repeat(Math.abs(pos - bestPos))) pos = bestPos; var opChar = baseTable[pos] < charCode? '+': '-'; output.append(opChar.repeat(Math.abs(baseTable[pos] - charCode))); output.append('.'); baseTable[pos] = charCode; }); console.log(output.value) console.log('Length of BF code: ' + output.value.length); console.log('Score: ' + output.value.length / input.length); } ``` [Answer] I built something in Java. Didn't calculate the score. Texts with 3 or less characters are encoded with a multiplication per letter e.g. "A" = `++++++++[>++++++++<-]>+.`. Texts with more than 3 characters are encoded with a calculated list which is split into 3 areas. The first area is x times 49, then plus x times 7 and finally plus x. For example "A" is 1\*49 + 2\*7 + 2 ``` public class BFbuilder { public static void main(String[] args) { String text = "### INSERT TEXT HERE ###"; if (text.length()<=3){ String result = ""; for (char c:text.toCharArray()) { result += ">"; if (c<12) { for (int i=0;i<c;i++) { result += "+"; } result += ".>"; } else { int root = (int) Math.sqrt(c); for (int i = 0; i<root;i++) { result += "+"; } result += "[>"; int quotient = c/root; for (int i = 0; i<quotient;i++) { result += "+"; } result += "<-]>"; int remainder = c - (root*quotient); for (int i = 0; i<remainder;i++) { result += "+"; } result += "."; } } System.out.println(result.substring(1)); } else { int[][] offsets = new int[3][text.length()]; int counter = 0; String result = "---"; for(char c:text.toCharArray()) { offsets[0][counter] = c/49; int temp = c%49; offsets[1][counter] = temp/7; offsets[2][counter] = temp%7; counter++; } for (int o:offsets[0]) { switch (o) { case 0: result+=">--"; break; case 1: result+=">-"; break; case 2: result+=">"; break; case 3: result+=">+"; break; case 4: result+=">++"; break; case 5: result+=">+++"; break; } } result += ">+[-[>+++++++<-]<+++]>----"; for (int o:offsets[1]) { switch (o) { case 0: result+=">---"; break; case 1: result+=">--"; break; case 2: result+=">-"; break; case 3: result+=">"; break; case 4: result+=">+"; break; case 5: result+=">++"; break; case 6: result+=">+++"; break; } } result += ">+[-[>+++++++<-]<++++]>----"; for (int o:offsets[2]) { switch (o) { case 0: result+=">---"; break; case 1: result+=">--"; break; case 2: result+=">-"; break; case 3: result+=">"; break; case 4: result+=">+"; break; case 5: result+=">++"; break; case 6: result+=">+++"; break; } } result += ">+[-<++++]>[.>]"; System.out.println(result); } } } ``` The provided String "### INSERT TEXT HERE ###" becomes `--->-->-->-->-->->->->->->->-->->->->->-->->->->->-->-->-->-->+[-[>+++++++<-]<+++]>---->++>++>++>+>>+>+>->+>++>+>++>->++>++>+>>->+>->+>++>++>++>+[-[>+++++++<-]<++++]>---->--->--->--->+>>-->+++>+++>++>--->+>--->+++>+>--->+>->+++>++>+++>+>--->--->--->+[-<++++]>[.>]` "Hello, World!" becomes `--->->>>>>-->-->->>>>>-->+[-[>+++++++<-]<+++]>---->>--->-->-->-->+++>+>++>-->->-->--->+>+[-[>+++++++<-]<++++]>---->->>>>+++>->+>>+++>->>->++>+[-<++++]>[.>]` [Answer] # Python 3 ``` print("".join("+"*ord(i)+".[-]"for i in input())) ``` This is essentially just an slightly improved version of icedvariables' answer. (-1 Byte from Wheat Wizard, -5 from FatalError, -2 from jez) ]
[Question] [ They say that `hate` is a strong word. I wanted to find out why, so I had a good look at the word. I noticed that every consonant had a vowel after it. That made it look quite strong to me, so I decided that that's what makes a word strong. I want to find more strong words, so I'll need a program for it! # Finding strong words Strong words are words where every consonant (letters in the set `BCDFGHJKLMNPQRSTVWXZ`) is followed by a vowel (letters in the set `AEIOUY`). That's it. Nothing else matters. If the word starts with a vowel, you don't have to worry about any of the letters before the first consonant. If the word has no consonants in it at all, it's automatically a strong word! Some examples of strong words are `agate`, `hate` and `you`. `agate` is still a strong word because although it starts with a vowel, every consonant is still followed by a vowel. `you` is a strong word because it has no consonants. There is no restriction on length for strong words. # The challenge Write a program or function that takes a non-empty string as input, and outputs a truthy value if it is a strong word or a falsy value if it is not. # Clarifications * You may decide to take the input in either lowercase or uppercase. Specify which in your answer. * Words will not contain punctuation of any kind. They will only contain plain letters in the set `ABCDEFGHIJKLMNOPQRSTUVWXYZ`. * Instead of truthy and falsy values, you may choose two distinct and consistent values to return for true and false. If you do this, specify the values you have picked in your answer. + You may alternatively output a falsy value for a strong word and a truthy one for a non-strong word. # Test cases ``` Input -> Output hate -> true love -> true popularize -> true academy -> true you -> true mouse -> true acorn -> false nut -> false ah -> false strong -> false false -> false parakeet -> false ``` # Scoring Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the least bytes wins! [Answer] # JavaScript (ES6), ~~36~~ ~~28~~ 27 bytes *Saved 1 byte by inverting the result, as suggested by LarsW* Takes input in lowercase. Returns `false` for a strong word and `true` for a non-strong word. ``` s=>/[^aeiouy]{2}/.test(s+0) ``` ### How? We append a `0` (non-vowel) at the end of the input string and look for two consecutive non-vowel characters. This allows us to cover both cases that make a word *not* strong: * it contains two consecutive consonants * *or* it ends with a consonant ### Test cases ``` let f = s=>/[^aeiouy]{2}/.test(s+0) ;[ "hate", "love", "popularize", "academy", "you", "mouse", "a", "euouae", "acorn", "nut", "ah", "strong", "false", "parakeet" ] .forEach(s => console.log(s + ' --> ' + f(s))) ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda s:'se, F'in`[v in'aeiouy'for v in s+'b']` ``` An unnamed function taking a (lowercase) string, `s`, and returning `False` if strong or `True` if not. **[Try it online!](https://tio.run/##JY7BCsIwEETP@hVLoKzFetCjoEd/QgVXm9pgmw3JplB/Pib1Mm9m2IVxs/RsD6k73dJA47MlCEcMuoELGvu4TmAskjYcZ@zYQ8kQtvjE@yOVQnSQ0m1UT6JVowaeChy7OJA33xLoRa0e5@xmjllHjuHfs7eZNkpJfZYgnu07m46G5caRp4/WourjeuW8sQKq2h8C7M5QBQUVbMqGBrqFNdkWcHlGyPtQfNRYp/QD "Python 2 – Try It Online")** (inverts the results to match the OP) ### How? Non-strong words have either a consonant followed by a consonant or end in a consonant. The code adds a consonant to the end (`s+'b'`) to make the required test be just for two consonants in a row. It finds out if each letter in the altered word is a vowel with the list comprehension `[v in'aeiouy'for v in s+'b']`. It now needs to check for two `False` results in a row (signalling a non-strong word), it does so by getting a string representation (using ``...``) of this list and looking for the existence of `'se, F'`. This is the shortest string found in `'False, False'` but none of: `'True, True'`; `'False, True'`; or `'True, False'`. As an example consider `'nut'`, the list comprehension evaluates each letter, `v`, of `'nutb'` for existence in `'aeiouy'` yielding the list `[False, True, False, False]`, the string representation of this list is `'[False, True, False, False]'` which contains `'e, F'` here: `'[False, True, Fals>>e, F<<alse]'` hence the function returns `True` meaning that nut is **not** a strong word. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` e€ØY;Ạ11ẇ ``` A monadic link taking a list of characters and returning: * `0` if strong * `1` if not **[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMirU8sMzR8uKv9////5flFKQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/z/1UdOawzMirR/uWmBo@HBX@//D7Q93dz9qmJOWmFOcCqRLikqB1Fyuh7u3HN1zuB2oXMX9//@MxJJUrpz8slSugvyC0pzEosyqVK7E5MSU1NxKrsr8Uq7c/NJikEh@UR5XXmkJV2IGV3FJUX5eOhfYYK6CxKLE7NTUEgA "Jelly – Try It Online"). ### How? ``` e€ØY;Ạ11ẇ - Link: list of characters, s e.g. "hate" or "you" or "not" ØY - consonant yield "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" e€ - exists in? for €ach letter [1,0,1,0] [0,0,0] [1,0,1] Ạ - all truthy? (1 for any valid input) 1 1 1 ; - concatenate [1,0,1,0,1] [0,0,0,1] [1,0,1,1] 11 - literal eleven ẇ - sublist exists? 0 0 1 - N.B.: left of ẇ implicitly makes digits so it looks for the sublist [1,1] ``` Note: The reason for using `Ạ` is just to save a byte over using `1` (since we then want to use `11` straight away). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ### Code ``` žPS¡¦õÊP ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//6L6A4EMLDy07vPVwV8D//4npiSWpAA "05AB1E – Try It Online") ### Explanation ``` žPS¡ # Split the string on consonants (bcdfghjklmnpqrstvwxz) ¦ # Remove the first element of the array to handle cases when the string starts with a consonant õÊP # Check if the empty string is not in the array ``` ### Example ``` # "popularize" žPS¡ # ['', 'o', 'u', 'a', 'i', 'e'] ¦ # ['o', 'u', 'a', 'i', 'e'] õÊ # [1, 1, 1, 1, 1] P # 1 ``` [Answer] # [R](https://www.r-project.org/), 43 bytes ``` function(s)grep("[^aeiouy]{2}",paste(s,"")) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jWDO9KLVAQyk6LjE1M7@0MrbaqFZJpyCxuCRVo1hHSUlT83@ahlJiemJJqpImF5BZmV8KYSTl52dDWBlwSaBZqXlKmv8B "R – Try It Online") A port of Arnauld's JavaScript answer; returns 1 for weak words and `integer(0)` for strong ones; it appends a (space) to the end of the string. This is actually vectorized; with a vector of strings, it returns the indices (1-based) of the weak words. [Answer] # Dyalog APL, 20 bytes ``` ⎕←∧/2∨/0,⍨⍞∊'aeiouy' ``` [Try it online!](https://tio.run/##ATwAw/9hcGwtZHlhbG9nLWNsYXNzaWP//@KOleKGkOKIpy8y4oioLzAs4o2o4o2e4oiKJ2FlaW91eSf//2hhdGU) [Answer] # [Haskell](https://www.haskell.org/), ~~61~~ 54 bytes ``` f=and.(zipWith(||)=<<tail).(map(`elem`"aeiouy")).(++"z") ``` [Try it online!](https://tio.run/##JYpBDoMgEEXX7SnIrCA2nkCP0HUXTRMndSxEYAiCica7U2w3/7//8jUuM1lbytSjH1u5m/AwScvjUH3XJTRWtdJhkANZcgMgGc4bqGqbBnZQxaHxohcjXy/1dxcyRONTOynxBI2J4AaW17MCh2wxmv0c@MaR3FZp41zTcV7@nqOv7XM6l66xpMj@U2FC@/sEjDgTJXiVLw "Haskell – Try It Online") I had to add a `z` at the end of the string to handle the case of a trailing consonant. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ΛΣX_2m€¨γaıu ``` [Try it online!](https://tio.run/##ASMA3P9odXNr///Om86jWF8ybeKCrMKozrNhxLF1////ImFnYXRlIg "Husk – Try It Online") Thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/) for help with -4. ~~Returns inconsistent but appropriately truthy or falsy values.~~ Thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo) for -1, now returns consistent truthy/falsy value. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~93~~ 81 bytes ``` s->{int w=0,p=w,l;for(char c:s)w|=p&(p=l="aeiouy".indexOf(c)>>31);return w+p>=0;} ``` [Try it online!](https://tio.run/##LY6xTsMwFEX3fIWVAdmQWkVspI4ESGyIoWPV4eE4xaljW/ZzQ1Ty7cFBvePVubqnhwtsnFe2b8@LHrwLSPrc8YTa8C5ZidpZfl8XhTQQI/kAbcm1IDkRAbUk7zdoJ78hHI7Vq3NGgW1IJ5a4aa7aIhnFtvJirEzduUBXkMjnyMZf4e@oF0aUoLRLU8m1bdXPZ0cla5qnR1YHhSlYMj74Rmzrecki67dPXyZ/3xQuTrdkyGZ0j0Hb0@FIIJwiu4mu2U8R1cBdQu4zgsbSjoP3ZqKlhwBnpbDk6N6y20sIMFHGWP0/n4t5@QM "Java (OpenJDK 8) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->w{w+?t!~/[^aeiouy]{2}/} ``` [Try it online!](https://tio.run/##LYpBDoIwFESvUklIF4JEE5fiQZqafLUIEfhN2y9UwKvXFN3MvJcZQ1cfqlPIy2Eatme3@RTiAqpB8nI6LMUSBK/BKZ4x3uJrbY2aWjDNezW4wV11PqJHitUh2f@Epo/Qk1u9jmmdwf4RqYL2d9Rg4KmU43LXgZ7mcdbkLEvS/dGyvGSpTVIxZpUYpVzCFw "Ruby – Try It Online") Everybody else is doing it, so why can't Ruby? [Answer] # [Pyth](https://pyth.readthedocs.io), 18 bytes ``` :+Q1."2}M>åYà ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%3A%2BQ1.%222%7D%04M%C2%83%3E%C2%85%C3%A5Y%13%C3%A0%C2%9B&test_suite=1&test_suite_input=%22hate%22%0A%22love%22%0A%22popularize%22%0A%22academy%22%0A%22you%22%0A%22mouse%22%0A%22acorn%22%0A%22nut%22%0A%22ah%22%0A%22strong%22%0A%22false%22%0A%22parakeet%22&debug=0)** "Borrowed" the regex from [the JS answer](https://codegolf.stackexchange.com/a/142279/59487). This returns `False` for strong words, `True` otherwise [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ ~~11~~ 10 bytes ``` ,Ḷs₂{¬∈Ẉ}ᵐ ``` [Try it online!](https://tio.run/##LY07DsIwEESvsnJB5YrrIIpN4nyE4438iRQ@TQoUOg5CQQNCKbmJc5EQmzQ7b2Z2tYnGtOwkFdv5NF2fU99vOIOMhAFFFkQrFMgqtxwSTcyPt/NSVwaM1aSKEFz86z5z/3mb5fj0fUzD4MchpvMOWIlWMA5MUhu1ocZJ1NUxOkwxE3UXsCMXpCZn1oq0CqCcjb4Mc/27UI7yv9igxoMQlsH@Bw "Brachylog – Try It Online") Neat and simple (except maybe for the 2 extra initial bytes to handle the final consonant case, like "parakeet"). Is falsey for strong words and truthy for non-strong words. ``` ,Ḷ % append a newline (non-vowel) at the end of input, % to catch final consonants s₂ % the result has some substring of length 2 {¬∈Ẉ}ᵐ % where neither of its elements belong to % the set of alternate vowels (with "y") ``` [Answer] # Perl 5, 31 bytes (30 + 1) ``` $_=''if/[^aeiouy](?![aeiouy])/ ``` +1 byte for `-p` command line flag. Prints the word if it's a strong word, or the empty string if it is not. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` e€ØY;1a2\¬Ȧ ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMirQ0TjWIOrTmx7P///4nJ@UV5AA "Jelly – Try It Online") ``` e€ØY;1a2\¬Ȧ Main link € For each letter e Is it an element of ØY The consonants (excluding Yy)? ;1 Append 1 (true) (consonant) to make sure last letter isn't consonant 2\ For all (overlapping) slices of length 2 (the <link><nilad>\ functionality) a Logical AND of the two values; is it a consonant pair? ¬ Logical NOT vectorizing; for each (overlapping) pair, is it not a consonant pair? Ȧ Any and all; make sure all pairs are not consonant pairs ``` Yes I know I've been beaten a lot by Jonathan Allan but I wanted to share my approach anyway :P -4 bytes by stealing a little bit of Jonathan Allan's answer (instead of appending a consonant to check for last-letter edge case, just append 1) -1 byte thanks to miles [Answer] # Awk, 39 bytes ``` /([^aeiouy]{2}|[^aeiouy]$)/{print "n"} ``` prints `n` for non-strongword, nothing (or, just a newline) for strongword following the pack and searching for two consecutive non-vowels on lowercase input testing ``` $ awk -f strongwork.awk hate love popularize academy you mouse acorn n nut n ah n strong n false n parakeet n ``` [Answer] # [Kotlin](https://kotlinlang.org), 49 bytes ``` {Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it)} ``` **True and false are swapped** ## Beautified ``` { Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it) } ``` ## Test ``` var s:(String)->Boolean = {Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it)} data class TestData(val input: String, val output: Boolean) fun main(args: Array<String>) { val items = listOf( TestData("hate", true), TestData("love", true), TestData("popularize", true), TestData("academy", true), TestData("you", true), TestData("mouse", true), TestData("acorn", false), TestData("nut", false), TestData("ah", false), TestData("strong", false), TestData("false", false), TestData("parakeet", false) ) items .filter { s(it.input) == it.output } .forEach { throw AssertionError(it.toString()) } println("Test Passed") } ``` [TryItOnline](https://tio.run/##jZLBTsMwDIbvfQqr4pBMow8w0UlD7AwCbggka0vbaGlSOc6gjD17SVsYAmkqviR2vt@2lH/n2Gjb7ZHAL8QDk7alvFxeO2cUWsi7w70q1ZtIs9nTCyrtQvssTrds9nEhU5nVyJtKeaFZHrstMsLGoPfwqDzfxFTs0YC2TeAFjDPm0Jdc4KH2NU4mSREs1KitQCr9AlZE2F6NkqWEQwIxhmasag85GO35thBD/TtOU9MKWaVzYApKzs8wxu0nmcY1wSDp90kSN7hVdTuFtS5MIbUL/h/jHNkIFWj8ecoGnmSwmkQ8k7PlJDa8TlINEu6U@lls4KID@mP43V/CrNCGFcEBepdlg5ck5HlEs9FFcPwjcLTGTRUVXJF7hZX3ilg7uyZy1DdhNxpLSBnFg7qJORsr0n5RuIseVttUJsfuEw) Based on [@Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) [Answer](https://codegolf.stackexchange.com/questions/142278/is-it-a-strong-word/142279#142279) [Answer] # [Retina](https://github.com/m-ender/retina), ~~23~~ 18 bytes ``` $ $ 1`[^aeiouy]{2} ``` [Try it online!](https://tio.run/##HclBCsIwEAXQ/T9HhW71Eh5ClH50akPTTJjOCEE8exS375l4KuyH8Tz1AQOO0@VGSRrt@j59el/ogqwvQdUamZZ2Ae98yNbQNLBp/EWtoISDC3Y3LU/MzL@pNK4i/gU "Retina – Try It Online") Outputs 0 for strong, 1 if not. Add 1 byte to support mixed case. Edit: Saved 5 bytes thanks to @ovs. [Answer] # Java 8, ~~53~~ 42 bytes ``` s->s.matches(".*[^aeiouy]([^aeiouy].*|$)") ``` -11 bytes by using the same regex as in [*@jrtapsell*'s Kotlin answer](https://codegolf.stackexchange.com/a/142332/52210) instead. [Try it here.](https://tio.run/##jZDBbsIwDIbvPIVV7dAgkReotjcYF44IJBMMDaRxlTiVuq3P3oXBdtsyKZYS/Z/9//EFB1xxT/5yvM7GYYzwita/LwCsFwonNATr2xPgwOwIPZh6I8H6M0TVZGHKlU8UFGtgDR6eYY6rl6g7FNNSrCu93O6RLKdxV//c9PLjSVVqbu79fTq43P8YM7A9QpeTPLy2O0B1j7EZo1CnOYnusyTO116bumpRqFJfkX6HHA9lqOc@OQz2rYyiwSN1Y5EbORWZjlP801E1N6GQh4MvOvkk5Z@1RSRKYH8uYid08R9Lx4BXou9g02KaPwE) (`false` if strong; `true` if not) **Explanation:** ``` s-> // Method with String parameter and boolean return-type s.matches( // Checks if the String matches the following regex: ".* // One or more characters [^aeiouy] // Followed by a consonant ([^aeiouy].* // Followed by another consonant (+ any more characters) |$)") // Or the end of the String // End of method (implicit / single-line return statement) ``` So it basically checks if we can find two adjacent consonants, or if the String ends with a consonant. --- Old answer (**53 bytes**): ``` s->s.matches("[aeiouy]*([a-z&&[^aeiouy]][aeiouy]+)*") ``` [Try it here.](https://tio.run/##jZBBboMwEEX3OcWIRYQTwQVQe4NmkyWi0sQ4wYnxII@NRCrOTp2GLFtX8izs//T/91xxxIIGZa/tbZEGmeEDtf3aAGjrlTujVHB4XAFOREahBZkfvdP2AiyqKMxx4mGPXks4gIU3WLh457JHLzvFeVaj0hSmZpfXWNy32/pzfWheyl7sMrFUT6shnEy0Wh1H0i30sdQaWzeA4tnoOLFXfUnBl0OUvLG5LWWedehVJn7a/Q4ZGtPQQEMw6PQ9jaLEVvVTkpsoJJmeAv@ZKKqHkOhDziaTbPDpn3VJhL0je0liZzT8j6Wjw5tSr2LzZl6@AQ) (`true` if strong; `false` if not) Uses regex to see if the input-String matches the 'strong'-regex. Note that `String#matches` in Java automatically adds `^...$` to check if the String entirely matches the given regex. **Explanation":** ``` s-> // Method with String parameter and boolean return-type s.matches( // Checks if the String matches the following regex: "[aeiouy]* // 0 or more vowels ([a-z&&[^aeiouy]] // { A consonant, [aeiouy]+) // plus one or more vowels } *") // Repeated 0 or more times // End of method (implicit / single-line return statement) ``` --- A search instead of matches (like a lot of other answers use) is actually longer in Java: **70 bytes**: ``` s->java.util.regex.Pattern.compile("[^aeiouy]{2}").matcher(s+0).find() ``` [Try it here.](https://tio.run/##jZBBasMwEEX3OcXglUWJKN2a9gYNhSxDChN54iiRNUYahbrBZ3eVJl22KkgLMY//3@iIZ1zyQP7YnmbjMEZ4ResvCwDrhcIeDcHq@gTYMTtCD6ZeS7C@g6iaPJjyzScKijWwAg/PMMflyzFH6yTW6UAdfeg3lBzoteF@sI7qavOOZDmN28vTVCndo5gDhTo@PCq9t76t1dzcsoe0czn7XnFm20KfLe8emy2guimuxyjUa06ihzwS5@tcWFcHFKrUt@7vkONzGRp4SA6D/SyjaLClfixyI6ci03OKfzaq5joo@HDwxSafpLzZoYhECey7IrZHF//x6RjwRPQjNi2m@Qs) (`false` if strong; `true` if not) [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes *-30 bytes by realizing it can be as simple as [Arnauld's JS answer](https://codegolf.stackexchange.com/a/142279/68615).* ``` lambda s:re.search('[^aeiouy]([^aeiouy]|$)',s)<1 import re ``` [Try it online!](https://tio.run/##PY7BCsIwEETv/Yo9CGlBBD0W@yW1wtpubbDNhs1GqPjvkVTxMvOGmcP4VSd2pzQ2lzTjchsQQi10CITST6Vpr0iW49qVf3rvKrMP1flY2MWzKAglpaABGmjNhEpmD2bm5@aefZxR7GtL2ONAy5px5Zht4Rh@FYvL4KJuecoaVNjdM404f4ceBR9EarqiGFnAgnWwHajBi3UKY2mr9AE "Python 2 – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~19~~ 18 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` æ"[^ŗy]”ŗ(ŗ|$)”øβ= ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUU2JTIyJTVCJTVFJXUwMTU3eSU1RCV1MjAxRCV1MDM5ODFnJTI1JXUwMTdFSiV1MjAxOCVGOCV1MDNCMiUzRA__,inputs=cG9wdWxhcml6ZQ__) Explanation: ``` æ push "aeiou" "[^ŗy]” push "[^ŗy]" with ŗ replaced with pop ŗ(ŗ|$)” push `ŗ(ŗ|$)` with ŗ replaced with pop øβ replace in the input that regex with nothing = check for equality with the original input ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` žP¹SåJ1«11å ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L6AQzuDDy/1Mjy02tDw8NL//xPTE0tSAQ "05AB1E – Try It Online") Uses Jonathan's algorithm, returns `0` for true and `1` for false. [Answer] # [Swift 3.1](https://www.swift.org), 85 bytes ``` import Foundation {($0+"0").range(of:"[^aeiouy]{2}",options:.regularExpression)==nil} ``` **[Try it here!](http://swift.sandbox.bluemix.net/#/repl/59b513d36bb1b17773ce606b)** This borrows [Arnauld's regex](https://codegolf.stackexchange.com/a/142279/59487). [Answer] # Lua, 41 bytes ``` return#(io.read()..0):match"[^aeiouy]+"<2 ``` Reads from standard input # Lua (loadstring'ed), 37 bytes ``` return#((...)..0):match"[^aeiouy]+"<2 ``` Reads from function parameter(s) --- Input is lowercase Sees if there is a string of length 2 or more, consisting only of not vowels (consonants) or if the string ends with a non-vowel Returns true/false [Answer] ## C++, ~~195~~ 194 bytes -1 bytes thanks to Zacharý Uppercase, return true if input is a strong word, false otherwise ( C++ have simple int to bool implicit cast rules, 0 => false, true otherwise ) ``` #include<string> #define C(p)(v.find(e[p])==size_t(-1)) std::string v="AEIOUY";int s(std::string e){for(int i=0;i<e.size()-1;++i)if(e[i]>64&&e[i]<91&&C(i)&&C(i+1))return 0;return!C(e.size()-1);} ``` **Code to test :** ``` auto t = { "HATE", "LOVE", "POPULARIZE", "ACADEMY", "YOU", "MOUSE", "ACORN", "NUT", "AH", "STRONG", "FALSE", "PARAKEET" }; for (auto&a : t) { std::cout << (s(a) ? "true" : "false") << '\n'; } ``` [Answer] # C, 107 Bytes ``` i,v,w,r,t;a(char*s){w=0;for(r=1;*s;s++){v=1;for(i=6;v&&i;)v=*s^" aeiouy"[i--];r=w&&v?0:r;w=v;}return r&~v;} ``` Returns 1 for *strong* word and 0 for *weak* word. Tested with the words given in the main post. [Answer] # [C (gcc)](https://gcc.gnu.org/), 59 bytes ``` f(char*s){return*s?strcspn(s,"aeiouy")+!s[1]<2?f(s+1):0:1;} ``` [Try it online!](https://tio.run/##PVDBbsMgDD3DVzCmSpBkU7Nj060/UO22U5cDIqRBSyDCMCmr8u0ZKdlOfrafn58tn65SLkvLZCdcBvzmlA/OZHAC7ySMhkFBhdI2TJTnD3Ap6@PLqWWQl/ywP5TVvDxqI/vQKHIE32j73L1hbTwZhDaMkxtG0hrwZF1AsoThUpPXtYVoJ7yixYp6@72h0Y6hF07/bLmQolHDlJLJhgQGG@CfYJ1J0AS/1Tq6hniGNddUakX/NzEKJ76UStz3j/MZo7nCqLWOsNW9jv72VTSq64roPL8fgkYXey2ju3IPZNd8xp13SkHiR2LkPGrMGKUnRgE8L78 "C (gcc) – Try It Online") [Answer] # **PHP, 69 bytes** ``` preg_match("/([^AEIOUY][^AEIOUY]+|[^AEIOUY]$)/",$_SERVER['argv'][1]); ``` Returns **1** is the word is not strong. [Answer] # [CJam](https://sourceforge.net/p/cjam), 57 bytes ``` q{"aeiouy"#W=}%_,:B{_A={_A_)\B(<{=!X&:X;}{0:X;;;}?}&}fA;X ``` [Try it online!](https://tio.run/##S85KzP3/v7BaKTE1M7@0Ukk53LZWNV7Hyqk63tEWiOM1Y5w0bKptFSPUrCKsa6sNgKS1da19rVptmqN1xP//ufmlxakA "CJam – Try It Online") --- Reads input, converts to 1s for consonants, 0s for vowels. For every consonant, AND predefined variable X (predefined to 1) with next character's value. Output X [Answer] # [Zsh](https://www.zsh.org/), 21 bytes ``` >$1x<*[^aeiouy](#c2)* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JckxCsIwFIDhvad4YIe24FAnh6AHEYVn-9IW07yQvEjrVVwC4uTsYbyNYqcfvv_-uIU-fXQgYSdAk5Btqe0MnzPNHmooehQCw1cCxy4a9EMgwAZbGmeYOcLI8S_sLdgogD0E8Ww70Gh-x6HHC5GUxTOKXm_fu7yeVHU4IQ0c52OxajZltbyXUirfZ36EqlwkpaVf) Same method everyone else is using. Outputs via exit code: 1 for strong, 0 for not strong. Requires the `extendedglob` option. ]
[Question] [ [Dungeon Master](https://en.wikipedia.org/wiki/Dungeon_Master_(video_game)) was one of the first ever real-time role-playing games, originally released in 1987 on the Atari ST. Among other exciting things for the time, it offered a rather sophisticated spell system based on runes. Your task today is to write a program or function that evaluates the number of Mana points required to cast a given spell in Dungeon Master. [![Dungeon Master screenshot](https://i.stack.imgur.com/sVeHw.gif)](https://i.stack.imgur.com/sVeHw.gif) *The 'spell cast' system is the top right cyan box in the above picture.* ## Spells, runes and Mana Dungeon Master spells are composed of 2 to 4 runes, picked among the following categories, in this exact order: 1. Power (mandatory) 2. Elemental Influence (mandatory) 3. Form (optional) 4. Class / Alignment (optional) It means that valid spells are either: * Power + Elemental Influence * Power + Elemental Influence + Form * Power + Elemental Influence + Form + Class / Alignment Each category contains 6 runes, and each rune has an associated base Mana cost: ``` ============================================================================= | Power | Rune | Lo | Um | On | Ee | Pal | Mon | | +-----------+------+------+------+------+------+------+ | | Base cost | 1 | 2 | 3 | 4 | 5 | 6 | ============================================================================= | Elemental Influence | Rune | Ya | Vi | Oh | Ful | Des | Zo | | +-----------+------+------+------+------+------+------+ | | Base cost | 2 | 3 | 4 | 5 | 6 | 7 | ============================================================================= | Form | Rune | Ven | Ew | Kath | Ir | Bro | Gor | | +-----------+------+------+------+------+------+------+ | | Base cost | 4 | 5 | 6 | 7 | 7 | 9 | ============================================================================= | Class / Alignment | Rune | Ku | Ros | Dain | Neta | Ra | Sar | | +-----------+------+------+------+------+------+------+ | | Base cost | 2 | 2 | 3 | 4 | 6 | 7 | ============================================================================= ``` ## Evaluating the Mana cost The Mana cost of the spell is the sum of the Mana cost of all runes: * The cost of the Power rune always equals its base cost (from 1 to 6). * For the other runes, the following formula applies: [![cost = floor( (power + 1) * base_cost / 2 )](https://i.stack.imgur.com/JkdRu.png)](https://i.stack.imgur.com/JkdRu.png) where ***power*** is the base cost of the Power rune. ## Examples ``` Spell: Lo Ful Cost : 1 + floor((1 + 1) * 5 / 2) = 1 + 5 = 6 Spell: Um Ful Cost : 2 + floor((2 + 1) * 5 / 2) = 2 + 7 = 9 Spell: Pal Vi Bro Cost : 5 + floor((5 + 1) * 3 / 2) + floor((5 + 1) * 7 / 2) = 5 + 9 + 21 = 35 ``` ## Clarifications and rules * Your input will consist of 2 to 4 strings designating the runes of the spell. You can take them in any reasonable format, such as 4 distinct parameters, an array of strings (e.g. `['Lo', 'Ful']`), or just one string with a single-character separator of your choice (e.g. `'Lo Ful'`). Please specify the selected input format in your answer. * The runes are guaranteed to be valid. * The order of the categories must be respected. Unused categories may be either missing or replaced with some falsy value. * You can accept the runes in any of these formats: 1. A capital letter followed by lower case (`'Ful'`) 2. All lower case (`'ful'`) 3. All upper case (`'FUL'`). But you *can't* mix different formats. * Quite obviously, we do not care to know whether the spell actually has some effect in the game (for the curious, [useful spells are listed here](http://dmweb.free.fr/?q=node/195).) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. * And remember: [Lord Chaos](http://www.mobygames.com/game/dos/dungeon-master/screenshots/gameShotId,9756/) is watching you! ## Test cases ``` Spell | Output ---------------+------- Lo Ful | 6 Um Ful | 9 On Ya | 7 Lo Zo Ven | 12 Pal Vi Bro | 35 Ee Ya Bro Ros | 31 On Ful Bro Ku | 31 Lo Zo Kath Ra | 20 On Oh Ew Sar | 35 Ee Oh Gor Dain | 43 Mon Zo Ir Neta | 68 Mon Des Ir Sar | 75 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~135~~ ~~119~~ 115 bytes ``` b=[int('27169735 2 4567 435262'[int(x,36)%141%83%50%23])for x in input()] print b[0]+sum(a*-~b[0]/2for a in b[1:]) ``` [Try it online!](https://tio.run/##XU7bSsNAEH3PVwyBsIlWbDY3LfRFWkWqVryBhjxs6koC6W7YJjR98dfjzrYkIAxzOefMmakPTSEF7Tfym89t2@7zeVqKxiU08ePrJIiAAoRRnEAYRDSmxLDdJIg9xw995ypwoqlDg8z7kQo6KIWOum1cL7NqpbWQp9PsfNduXXZ28YvDJUUpQ2me@rPM6/Vda1@UFYc31fKZBcA7vgH8qScPkkyA3LYVscj7duzXAvtPptuj5MvkDy408swqM5SYb5TU0JKf9CdElxe5G4zQdGRW7T/bFWsKs8KGjbUBlnvMr0wNJ474nVRYFqzEfx6lGL3uDfPEGzYyC74bKXT7Aw "Python 2 – Try It Online") Input is list of strings from stdin [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~83~~ 82 bytes ``` .•Y<εΔ•¹нk©.•M₄P畲нkÌ.•Jrû •³нkD(i\ë4 3‡4+}.•A1Δ#•I4èkD(i\ë3LJ012‡Ì})ćsv®>y*;(î(+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f71HDokibc1vPTQEyDu28sDf70EqQmO@jppaAw8tBgpuAgod7QIJeRYd3K4CENgOFXDQyYw6vNlEwftSw0ES7FiTvaHhuijKQ9jQ5vAIqb@zjZWBoBFRyuKdW80h7cdmhdXaVWtYah9dpaP//X5rLlVaaw5WdWJLBlZdakggA "05AB1E – Try It Online") -1 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna). SOOOOOOO ungolfed :( Explanation: ``` .•Y<εΔ•¹нk©.•M₄P畲нkÌ.•Jrû •³нkD(i\ë4 3‡4+}.•A1Δ#•I4èkD(i\ë3LJ012‡Ì})ćsv®>y*;(î(+ Accepts four runes as separate lines, lowercase. Use Ø for missing runes. .•Y<εΔ•¹нk© Index first letter of first rune into "aluoepm" ("a" makes 1-indexed) .•M₄P畲нkÌ Index first letter of second rune into "yvofdz", 2-indexed. .•Jrû •³нkD(i\ë4 3‡4+} Index first letter of third rune into "vekibg", 0-indexed, if it's not there pop, else, if index is 4 replace with 3, else keep as-is, then increment by 4. .•A1Δ#•I4èkD(i\ë3LJ012‡Ì} Index fourth letter (modular wrapping) of fourth rune into "kodnra", if it's not there pop, else, if index is one of 1, 2 or 3, replace with 0, 1 or 2 respectively, else keep as-is, then increment by 2. )ćs Wrap all numbers into a list, keeping the power rune behind. v For each ®>y*;(î( Apply the formula + Add to total sum ``` [Answer] # JavaScript (ES6), ~~157~~ ~~156~~ ~~116~~ ~~112~~ ~~100~~ ~~99~~ 97 bytes Takes input as an array of strings. ``` a=>a.map(c=>t+=(v=+`27169735020045670435262`[parseInt(c,36)%141%83%50%23],+a?a*v+v>>1:a=v),t=0)|t ``` * Saved a massive 44 bytes by borrowing the indexing trick from [ovs' Python solution](https://codegolf.stackexchange.com/a/129033/58974) - if you're upvoting this answer, please upvote that one too. * Saved 13 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) pointing out what should have been an obvious opportunity to use a ternary. [Try it Online!](https://tio.run/##VZBva8IwEMa/ylEotEst/WPrNkgHm26I2xzKhE2FHjXOSk1KE7s3/e5dqiLsXiTP89z9DpI91iizKi9Vj4sNa7e0RZqge8DSymiiCLVqStJg4Md3gzDyAs/rR/HA64dREAfpssRKsjFXVuaEsW36fd@8Dc3IM4Nw7RB8wJua1Eni3yOtbUdRz25UmwkuRcHcQvxY6bxkRQHXauBJSLXivf9FTueKp2RpvAp4PhaGY3weLmLK4Qv1rTvfAhaMa/2BBSxyeKyENiOmBzoNMyHPgCZPweR4BSeodjDDc3@6g9EvzLE649q@iAqGmHfL3wTvgHEF70zhJRgy2SUdsj59oKSJdEvcjPjG8iObGA0YZGtJV5ZFrlJIbdvdi5yn@l12@wc) --- ## Explanation Hoo, boy, this is gonna be fun - my explanations to *trivial* solutions suck at the best of times! Let's give it a go ... ``` a=> ``` An anonymous function taking the array as an argument via parameter `a`. ``` a.reduce((t,c)=>,0) ``` Reduce the elements in the array by passing each through a function; the `t` parameter is the running total, the `c` parameter is the current string and `0` is the initial value of `t`. ``` parseInt(c,36) ``` Convert the current element from a base 36 string to a decimal integer. ``` %141%83%50%23 ``` Perform a few modulo operations on it. ``` +`27169735 2 4567 435262`[] ``` Grab the character from the string at that index and convert it to a number. ``` v= ``` Assign that number to variable `v`. ``` +a? ``` Check if variable `a` is a number. For the first element `a` will be the array of strings, trying to convert that to a number will return `NaN`, which is falsey. On each subsequent pass, `a` will be a positive integer, which is truthy. ``` a*v+v>>1 ``` If `a` is a number then we multiply it by the value of `v`, add the value of `v` and shift the bits of the result 1 bit to the right, which gives the same result as dividing by 2 and flooring. ``` :a=v ``` If `a` is not a number the we assign the value of `v` to it, which will also give us a `0` to add to our total on the first pass. ``` t+ ``` Finally, we add the result from the ternary above to our running total. --- ## Original, 156 bytes ``` a=>a.reduce((t,c)=>t+(p+1)*g(c)/2|0,p=(g=e=>+`123456234567456779223467`["LoUmOnEePaMoYaViOhFuDeZoVeEwKaIrBrGoKuRoDaNeRaSa".search(e[0]+e[1])/2])(a.shift())) ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~110~~ 78 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` θKKι"LUOEPM”;W:A≤{B"⁶Μ↓§QΕņj“L─"¶Ζq«╝γDyΜ2¶S◄Μ$‘č¹I6nēwι{_Cb:ƧRA=┌*ΚKι=?aIc*»+ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0I4S0sldTAzQjklMjJMVU9FUE0ldTIwMUQlM0JXJTNBQSV1MjI2NCU3QkIlMjIldTIwNzYldTAzOUMldTIxOTMlQTdRJXUwMzk1JXUwMTQ2aiV1MjAxQ0wldTI1MDAlMjIlQjYldTAzOTZxJUFCJXUyNTVEJXUwM0IzRHkldTAzOUMyJUI2UyV1MjVDNCV1MDM5QyUyNCV1MjAxOCV1MDEwRCVCOUk2biV1MDExM3cldTAzQjklN0JfQ2IlM0EldTAxQTdSQSUzRCV1MjUwQyoldTAzOUFLJXUwM0I5JTNEJTNGYUljKiVCQis_,inputs=TW9uJTIwWm8lMjBJciUyME5ldGE_) Could probably golf a byte or two from redoing everything Explanation: ``` θ split on spaces K pop the 1st item K pop from the string the 1st character ι remove the original string from stack "”;W get the chars index in "LUOEPM" :A save a copy to variable A ≤ put the power (used as the mana) on the bottom of the stack (with the thing above being the input array) { for the leftover items in the input do B save the current name on B "..“ push 456779223467234567 L─ base-10 decode it (yes, silly, but it converts it to an array of digits) ".‘ push "VEKIBGKRDN-SYVOFDZ" č chop to characters ¹ create an array of those two I rotate clockwise 6n group to an array with sub-arrays of length 6 (so each array in the array contains 3 items, corresponding to the categories, each with 6 arrays with the runes 1st letter (or "-" in the case of Ra) and base cost) ē push variable e (default = user input number, which errors and defaults to 0) and after that increase it (aka `e++`) w get that item in the array (the array is 1-indexed and the variable is not, so the array was created shifted (which somehow saves 0.9 ≈ 1 byte in the compression)) ι remove the original array { for each in that (current category) array _ dump all contents on stack (so pushing the runes name and then base cost) C save pop (base cost) on variable B b: duplicate the name ƧRA= push if pop = "RA" ┌* get that many (so 0 or 1) dashes Κ prepend the "" or "-" to the name K pop the 1st letter of the name ι remove the modified name, leaving the 1st letter on the stack =? if top 2 are equal (one of the dumped items and the 1st letter of the current inputs) a push variable A (the power) I increase it c push variable C (the current base cost) * multiply » floor-divide by 2 + add that to the power ``` [Answer] # JavaScript, ~~212~~ ~~210~~ ~~207~~ 206 bytes Straight-forward searching algorithm, the search strings are just contributing to the total bytes. **Code** ``` s=>eval('p=q=+(e=s.map(r=>"1 2 3 4 5 6 2 3 4 5 6 7 4 5 6 7 7 9 2 2 3 4 6 7"["LoUmOnEePalMonYaViOhFulDesZoVenEwKathIrBroGorKuRosDainNetaRaSar".search(r)])).shift();e.map(c=>p+=((q+1)*c)>>1);p') ``` **Input Format** String array, each item is a first-letter-capitalized string. Example: ["Mon", "Zo", "Ir", "Neta"] **Explanation** ``` e=s.map(r=>"1 2 3 4 5 6 2 3 4 5 6 7 4 5 6 7 7 9 2 2 3 4 6 7"["LoUmOnEePalMonYaViOhFulDesZoVenEwKathIrBroGorKuRosDainNetaRaSar".search(r)]) ``` This queries for the basic costs. ``` p=q=+(/*blah*/).shift() ``` Initializes 2 variables with the first item from the array result above, and remove that item. Must be cast to number first, otherwise it will be considered as string concatenation in the next part. ``` e.map(c=>p+=((q+1)*c)>>1); ``` Adds the costs of the non-power runes to the base power. Shifting is used instead of floor(blah)/2. ``` eval(/*blah*/;p) ``` Evaluate the last result. (Credit: Step Hen) **Test Cases** ``` Lo Ful | 6 Um Ful | 9 On Ya | 7 Lo Zo Ven | 12 Pal Vi Bro | 35 Ee Ya Bro Ros | 31 On Ful Bro Ku | 31 Lo Zo Kath Ra | 20 On Oh Ew Sar | 35 Ee Oh Gor Dain | 43 Mon Zo Ir Neta | 68 Mon Des Ir Sar | 75 ``` Edit 1: 212 > 210 - Removed a pair of braces Edit 2: 210 > 207 - Thanks **Step Hen** for reminder on JS rules and some hint on using eval() function. Since AS3 forbids the use of eval() I haven't use that for long time Edit 3: 207 > 206 - Thanks **Shaggy** for the idea replacing indexOf() with search() [Answer] # [Haskell](https://www.haskell.org/), 159 156 148 133 130 127 bytes ``` k(p:y)=sum$floor<$>c p:map(\x->c x*(c p+1)/2)y c s=read["3764529516342767"!!(foldl(\c n->c*94+fromEnum n-9)0s%7086%17)] (%)=mod ``` [Try it online!](https://tio.run/##XZFhb4IwEIa/8ytOokmrmAkiCJF9WHSLcc5FM5NNzUIEpxEoacvUX88OIdHsW@95eu81170vjmEU5fmRpO6FeiKL67uIMT6oP24hdWM/JetzG8/nJkHQ0umDQS/KFoTHQz9YqV3bMnuG09OtrmnYlq3WamTHoiAi6y0k2Nl0zNaOs3iUZDECh3ZEw@70rYZu041CGtSLWZDLUEgBrgsrspD8kPxoME4kXiiFpwAa9ZXBcxapGlgUgUbUj7gCTgVmCXz6WNtVjR1fDJZhgkw3KvjuR7A8wBNnSLu9io5CbC0gzJkohH7LxCFXM8nuRRk@8eUe5sVQo3PrmO1hdIKFz/@NQP7COAz9Q/Eks1uZKUuKrDGHt1AWWVb/zgxDUagyzb6mbRQlxoxiZeMZEFpWHuCPTb8hxRVKqEPA8CoRGvxSGLThukwkPJQZT0oBngdHICfGAwGC0vwP "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~320 318 314 311~~ 307 bytes **Input Format -** List of Strings. Full program: ``` i=input() t=[x.split()for x in"Lo Um On Ee Pal Mon|Ya Vi Oh Ful Des Zo|Ven Ew Kath Ir Bro Gor|Ku Ros Dain Neta Ra Sar".split('|')] c=t[0].index(i[0])+1;r=c+1;s=c+r*(t[1].index(i[1])+2)/2 if len(i)>2:s+=r*(t[2].index(i[2])+4-(i[2]=='Bro'))/2 if len(i)>3:s+=r*(t[3].index(i[3])+1+(i[3]in'KuRaSar'))/2 print(s) ``` **[Try it online!](https://tio.run/##ZVLBTsMwDL33K6xe0jIYrOM0FA5oA00dFA2YtFU7RF2mRuqSKk21IvXfh5NNtIiLY/v52e5zy2@TKxmdMrXj1Pf9k6BClrUJQs/QtBlWZSEw2CsNDQjpLxR8HSCRMOPwzgp4VbJdM1gJSHJ4rguY8go2ql1xLDlCzEwOcw1PWsGL0m1cw1JVMGVCwhs3DJYMPpj2L3NIS8Ktl1GT3m2HQu54Ewh0w8HoQdMMbYVWXwUmHXX4CPEovI08sYeCy0CEj9GkGlBXF3V1Edbd3ziHUoIbkfAva/zLGnessZ0@cI6QJK6XDPc9M0stpAmq8IS6ed4xFwWHT13zCW94FlhFw1NKFopcA0FpyNZLydehHyXSRmvmgnPhxlmUz@VQYhcKa@3KNjnjF9Ylhw@K2mto23dYXP9rb8/iaKzHSlxqdrTWfmM36ozg/exjb@cwPH3Xce4we9I@hj9DB7qePw "Python 2 – Try It Online")** [Answer] # Excel, 339 bytes Inputs entered in `A1` through `D1`. Formula in any other cell. ``` =CHOOSE(MOD(CODE(A1),12),2,,,1,6,,3,5,4)+INT((CHOOSE(MOD(CODE(A1),12),2,,,1,6,,3,5,4)+1)*CHOOSE(MOD(CODE(B1),12),,3,,,2,7,4,6,,5)/2)+INT((CHOOSE(MOD(CODE(A1),12),2,,,1,6,,3,5,4)+1)*CHOOSE(MOD(CODE(C1),12),7,4,6,,,7,,,5,,9)/2)+INT((CHOOSE(MOD(CODE(A1),12),2,,,1,6,,3,5,4)+1)*CHOOSE(MOD(CODE(SUBSTITUTE(D1,"Ra","E")),11),4,3,6,,2,7,,,2,0)/2) ``` Alternatively, importing as CSV: ## Excel & CSV, 228 bytes ``` ,,, =CHOOSE(MOD(CODE(A1),12),2,,,1,6,,3,5,4)+1 =A2-1+INT(A2*CHOOSE(MOD(CODE(B1),12),,3,,,2,7,4,6,,5)/2)+INT(A2*CHOOSE(MOD(CODE(C1),12),7,4,6,,,7,,,5,,9)/2)+INT(A2*CHOOSE(MOD(CODE(SUBSTITUTE(D1,"Ra","E")),11),4,3,6,,2,7,,,2,0)/2) ``` Input entered in first row, `SPACE` for nulls. Result displayed in A3. [Answer] # SCALA, 1106 chars, 1106 bytes This is quite long, probably optimizable, but it was fun to do :) **Input format** : space-separated runes in a string. If there is only 2 inputs (like "Lo Ful") my code completes it with `while(k.length<4)k:+=""` (so I can save **24 bytes** by changing the parameters, if I require it to be "A B C D"). ``` def n(i:Int,p:String):Int={Math.floor(i*((""+p(0)).toInt+1)/2).toInt} def m(s:String):Int={var k=s.split(' ') ``` **`while(k.length<4)k:+=""`** ``` k match{case Array(p,i,f,a)=>{p match{case "Lo"=>1+m(1+"/ "+i+" "+f+" "+a) case "Um"=>2+m(2+"/ "+i+" "+f+" "+a) case "On"=>3+m(3+"/ "+i+" "+f+" "+a) case "Ee"=>4+m(4+"/ "+i+" "+f+" "+a) case "Pal"=>5+m(5+"/ "+i+" "+f+" "+a) case "Mon"=>6+m(6+"/ "+i+" "+f+" "+a) case _ if p.contains("/")=>i match{case "Ya"=>n(2,p)+m(p+" / "+f+" "+a) case "Vi"=>n(3,p)+m(p+" / "+f+" "+a) case "Oh"=>n(4,p)+m(p+" / "+f+" "+a) case "Ful"=>n(5,p)+m(p+" / "+f+" "+a) case "Des"=>n(6,p)+m(p+" / "+f+" "+a) case "Zo"=>n(7,p)+m(p+" / "+f+" "+a) case _ if p.contains("/")=>f match{case "Ven"=>n(4,p)+m(p+" / "+"/ "+a) case "Ew"=>n(5,p)+m(p+" / "+"/ "+a) case "Kath"=>n(6,p)+m(p+" / "+"/ "+a) case "Ir"=>n(7,p)+m(p+" / "+"/ "+a) case "Bro"=>n(7,p)+m(p+" / "+"/ "+a) case "Gor"=>n(9,p)+m(p+" / "+"/ "+a) case _ if p.contains("/")=>a match{case "Ku"=>n(2,p) case "Ros"=>n(2,p) case "Dain"=>n(3,p) case "Neta"=>n(4,p) case "Ra"=>n(6,p) case "Sar"=>n(7,p) case _=>0} case _=>0} case _=>0} case _=>0}}}} ``` Thanks for this superb challenge. [Try it online!](https://tio.run/##hZRdb5swFIavx6@wfFMzsqT5nBaNSJ2aTVGWZWrVSO3N5KWmeAHbAmfZFOW3Z8eEElwY5QLh18/59DHpmkb0KH/@YmuNFpQLxP5oJh5TdKXU/vjIAiQIH8@EbqnxrU64eHLNyt8vqA7bQSRlQvhbQjD2FLl03baWsO113U4v/z44xktMUtv@N03Qxk/bqYq4JhfownV2IY8Y2bQjJp50@HHgbsaej7GzQTHV63C/pilDV0lC/xLV4q2gRV1/slflXfxVYn/S9WLS9XAHYY97GN5B9qauc4LuYoB6APUaoKUAqA9QvwGaMoAGAA0aoO80AmoI1LCBWkgTcATU6P/UD8QDpNprKTQcVkpwB0MPuNWCewp@BOm1lAvOFNh3qtFWPIP6jdAyzKBBI/R5G2XUsJG6ZmlGjRqpB5lB75ug@hYEVgtWTNRlnrX1fHa7urxtZg5TXpe3Tc2SurRt5lMiX4e@yJOnDw1Qff3Uqn@@LUYg93wj05fSNZgXQ5Br35imReeeTWnRgVy5peeC86T8yeXh1U94jm8U/AR0JAhcVQSzg95NoLj4eYld1zkjd7GFnJY2shTonhZEtrIB8PsgEUxEOdJJsUG4pmjFERxUQZ4lG50yE9SQ0NeCttRKlqYQszfflrM9q3VZm/FDN/RF5rlaibAM0XSH4HDKAQqxUgHswLwhMwblEkqybQI/KBN9liAzJYWJLVdN4OabzXJatmxMnMPxHw) [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 4420 bytes ``` ,.Ajax,.Ford,.Page,.Puck,.Romeo,.Act I:.Scene I:.[Enter Romeo and Page]Page:You big big big big big big cat.[Exit Romeo][Enter Ajax]Page:Open thy mind!Ajax:Open thy mind!Open thy mind!You is the sum of Romeo and the sum of a big big cat and a cat.Am I as big as you?If not,let us return to Scene V.Page:You is the sum of a big big cat and a cat.Let us return to Act V.Scene V:.Ajax:You is the sum of you and the sum of a big big big cat and a pig.Am I as big as you?If not,let us return to Scene X.Page:You big cat.Let us return to Act V.Scene X:.Ajax:You is the sum of you and the sum of a big cat and a cat.Am I as big as you?If not,let us return to Scene L.Page:You big big cat.Let us return to Act V.Scene L:.Ajax:You is the sum of you and the sum of a big big cat and a big cat.Am I as big as you?If not,let us return to Scene C.Page:You is the sum of a big cat and a cat.Let us return to Act V.Scene C:.Ajax:Am I as big as the sum of you and a big big big pig?Page:You is the sum of a big big cat and a big cat.If so,you is the sum of you and a cat.Ajax:Open thy mind!Act V:.Scene I:.[Exit Ajax][Enter Ford]Page:Open thy mind!Ford:Open thy mind!Open thy mind!You is the sum of Romeo and the sum of a big big big big cat and a pig.Am I as big as you?If not,let us return to Scene V.Page:You big big cat.Let us return to Act X.Scene V:.Ford:You is the sum of you and the sum of a big big big cat and a pig.Am I as big as you?If not,let us return to Scene X.Page:You is the sum of a big cat and a cat.Let us return to Act X.Scene X:.Ford:You is the sum of you and a big big cat.Am I as big as you?If not,let us return to Scene L.Page:You is the sum of a big big big cat and a pig.Let us return to Act X.Scene L:.Ford:Am I as big as the sum of you and a pig?If not,let us return to Scene C.Page:You big cat.Let us return to Act X.Scene C:.Ford:Am I as big as the sum of Romeo and a big big cat?Page:You is the sum of a big big cat and a cat.If so,you is the sum of you and a cat.Ford:Open thy mind!Act X:.Scene I:.[Exit Page][Enter Puck]Ford:You is the sum of the sum of Ajax and a pig and the quotient between the product of Ajax and I and a big cat.Puck:Open thy mind!Is you as big as a pig?If so,let us return to Act D.[Exit Puck][Enter Page]Ford:Open thy mind!Open thy mind!You is the sum of Romeo and the sum of a big big cat and a cat.Am I as big as you?If not,let us return to Scene V.Page:You is the sum of a big big cat and a cat.Let us return to Act L.Scene V:.Ford:Am I as big as the sum of you and a big big cat?If not,let us return to Scene X.Page:You is the sum of a big big big cat and a pig.Let us return to Act L.Scene X:.Ford:Open thy mind!Am I as big as the sum of Romeo and a big cat?If not,let us return to Scene L.Page:You is the sum of a big big big cat and a pig.Let us return to Act L.Scene L:.Ford:You is the sum of Romeo and the sum of a big big big cat and a pig.Am I as big as you?If not,let us return to Scene C.Page:You is the sum of a big big big cat and a cat.Let us return to Act L.Scene C:.Ford:Am I as big as the sum of you and a big big cat?If so,let us return to Scene D.Page:You big big cat.Let us return to Act L.Scene D:.Page:Open thy mind!You is the sum of a big big cat and a big cat.Act L:.Scene I:.[Exit Page][Enter Puck]Ford:You is the sum of you and the quotient between the product of Ajax and I and a big cat.Puck:Open thy mind!Is you as big as a pig?If so,let us return to Act D.[Exit Puck][Enter Page]Ford:You is the sum of Romeo and a big big cat.Am I as big as you?If not,let us return to Scene V.Page:You is the sum of a big cat and a cat.Let us return to Act C.Scene V:.Ford:You is the sum of you and the sum of a big big big cat and a pig.Am I as big as you?If not,let us return to Scene X.Page:You big cat.Let us return to Act C.Scene X:.Ford:Am I as big as the sum of you and the sum of a big cat and a cat?If not,let us return to Scene L.Page:You big big cat.Let us return to Act C.Scene L:.Ford:Am I as big as the sum of you and a big big big cat?If not,let us return to Scene C.Page:You is the sum of a big big big cat and a pig.Let us return to Act C.Scene C:.Page:Open thy mind!Is you as big as the sum of Romeo and a cat?You big cat.If so,you is the sum of you and a big big cat.Act C:.Scene I:.[Exit Page][Enter Puck]Ford:You is the sum of you and the quotient between the product of Ajax and I and a big cat.Act D:.Scene I:.Ford:Open thy heart![Exeunt] ``` Takes the input as an uppercase string. Explanation coming soon... For now, **Fun fact:** `Microsoft` is a negative noun in SPL. All other accepted words appeared in the works of Shakespeare. [Try it online!](https://tio.run/##zVfbbqMwEP2V6TvyB@QlikhXQmK3VSKhrKo80MRNaROcBaM2X5/1GAjYXA1IzUMSsGXPOeNzZpz4fLxeLbL48L8t8otFe4s8@wcqvpPdp0VW7ESZmN5xcGZkvaMhxYeXx5DTCOQs@OEecM0Wv2Z/WQKvwaH2s/O5WPod8HTlNtsGg6eLn840BP5@gVMQ7h9wXBtS3zBWEIt3CnFyAvZWQlQa9MsA5KQvoSxO4IAfyxnxc2HJ3HmDkHHrSDkkMUSUJ5GIxyBl7pEbRTVsUwRX3wcT6WV59GYy7TXbCSTNHNQo5@BgzmNDlKPqRLoxRzoy0y6piKkTpTssnwXSPIoxWrtdFwaasDMOGoQaLqoghAzmBtrMmQpaMbMujQnLTq/qQ4lZKQjoamnkzNRYS@pMjePTmnoiU3gGktsUFpZ8ftTCAyW3KczdwUFR0CgvNymzmpBWyG4GuY9L0Bm93dvr0O3O6IVgldTNDbtHP3fWGEqirbhT9ujMndjdtw3HXnpEQxd5vAn6X8J4QEMOr5R/URmZwjli@0QELi9ztHqDYTWsTpzyueXxdmSC@7HuHJY5H@SQ80Fu05eWu7gvuFqxMekNqLpRhcTAna5WUDRN9nZLN2Z3csxuYxHs0XxGlnLblE2nUuzhSqkzXbrp0qA/5kCWM1JzBTC7o8j9Bhezch@@57LVJryR/dcbfVWw7@m60yo8W6tB3Q5oz8eEf1PsAZcXLYNTF5LGsmgXhaTGvxXtN6gWEZdPrPs@o@gccfys76VtSxDUtvZO/Yg/CFg0Cfn2ev399AeWj2twVrBerP4D "Shakespeare Programming Language – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 252 bytes ``` r->{int c[][]={{2,3,4,5,6,7},{4,5,6,7,7,9},{2,2,3,4,6,7}},l=r.length,p="LUOEPM".indexOf(r[0].charAt(0))+1,a=p,i=0;String[]s={"YVOFDZ","VEKIBG","KRDNXS"};for(;i<l-1;)a+=(p+1)*c[i][s[i++].indexOf((l>3?r[i].replace("Ra","X"):r[i]).charAt(0))]/2;return a;} ``` [Try it online!](https://tio.run/##bZNtT@owGIa/n1/xpAnJdlbGm8KROYwGNAZ0BpSoyz70jCL1zG5pO4@G8Ns53QsIeLYvbZ9rz333bvdK3kk1Tih/nf1ZJ@nviIUQRkRKuCGMw/IHgFRE6dVXTdqpYpE9T3moWMzt@/iaq8tydjpRgvEXP@jB3F2Lam/JuILQD/zAXS6buIWP8DFu484KL8uRfk/0rImLalZb4cgVdkT5i1rgxEWjB29wd4Nsxmf0w5sbwq8Hdrgg4lwZddO0Gpi4CWZu3dnIS3eJnqbeZf8ZYTQdDK8vrvRgOO7fPk7QypnHwnDYaVRtOCaxXCOxGubP0GeBL31mWcFWyYh6rTOhC7agSURCaqAx0Z0ekdnNls0dG0Gt6QiqUsGBOKs1gKNzK9Ms43uP2QzedKbGxigQ8SLNPGIARaUy0CiGyzRCGLZP23SgVoNR42gHe3g7xE5MZ6fucXgiu2Xo7NW1zHMMU8q3TKO5B9yRCKYMLkS8IVrHe8CAaoWsDuNY5kyrcWhBW8yJYfo/oPAwJGoB48Jrs37YwVvA4C9MiChcfPeggatYQF/HmiFHrT3gJuaZxrWAW6pyjfavb0CfyowoRTqFxOrr2ufnluPFuYFIOZUYsstNPxIaKjrbHGK2JqjOzoW5TZIk@jyX@g8x8k9smURMiwIySxOTT6nomx2nyk50azU3UKVZl1DtQaU160JFVrJtlYJZY7yVBNctpM4AeUPUBXTr3YM3BC1gfVGWVkPlllaZ5vof "Java (OpenJDK 8) – Try It Online") The runes are input as a `String[]` (array of `String`), in the first case form (first letter is an uppercase, rest is lowercase). It's the standard "find the n-th letter" method, with the twist that both `Ros` and `Ra` exist in the 4th segment. I treated that with an inline and explicit replacement of `Ra` to `X`. [Answer] # [Retina](https://github.com/m-ender/retina), ~~124~~ 123 bytes ``` Gor 9 [ZIBS]\w+ 7 Mon|Des|Kath|Ra 6 ..l|Ew 5 Ee|Oh|Ven|Neta 4 [OVD]\w+ 3 [UYKR]\w+ 2 Lo 1 \d $* (?<=^(1+) .*1) $1 \G1 11 11 ``` [Try it online!](https://tio.run/##LU9da8JAEHyfX7EPClEhcPaLQqUgSYPENiViQGPFAw8SSO/gjOTl/nu6dxQWdmd3hp2xqm@1HKdRdhkzY/GK@rhZ735OwwIv@DTaJermctk3rpR4Rhx3Lh3whFS5onGV0u5L9RKPqIsqCbIH1PtDXoZ5ia2BwOmKyRzR@9vqHInFjOK5mGHC@0xA@BrHraGPe4f9b2iFpoNkLR0N8Q98y46qltbW8GM@@YlKc/NE5geY3/8F3i2xW74VDaUD7aT1MgYckRLZap/MUzeWgn0POajHTP4D "Retina – Try It Online") Link includes test cases. Takes space-separated runes. Explanation: The initial stages simply convert each rune to a digit, which is then converted to unary. The numbers after the first are multiplied by one more than the first number, following which the first number is doubled. The final stage integer divides all the result by 2 and takes the sum. [Answer] # Go, 205 bytes ``` func c(s []string)int{f,l:=strings.IndexByte,len(s) p:=f("UOEPM",s[0][0])+3 r:=p-1+p*(f("VOFDZ",s[1][0])+3)/2 if l>2{r+=p*(f("war o",s[2][1])+5)/2} if l>3{r+=p*(f("it Ra",s[3][len(s[3])-2])+3)/2} return r} ``` It's a callable function, takes runes as a slice of strings, e.g. `[]string{"Um", "Ful"}`. Try it on the [Go Playground](https://play.golang.org/p/P-GC7ucMCg). [Answer] # C, 222 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` i;b(r,s)char**r;{for(i=17;i--&&"& ; $ # 4 % ; B * 6 $ 8 6 5 - >3 + A@( . 6 5 "[s*17+i]-3-(*r[s]^r[s][1]););return~i?i/2+1:0;}main(n,r)int**r;{n=b(++r,0);printf("%d\n",n-(b(r,1)+b(r,2)+b(r,3))*~n/2);} ``` [Try it online!](https://tio.run/##PY7LTsMwEEV/5SrQyGPHtE6gRYzKo1/Aik0IUhoojAQumpQVan/dJFBxFvdKZ3U6/9p1KQmvjRY9dW@tWqv8vdmqkWVYsHif51kOxilOcI4JjjBWsJgP@hL/zHEBj@sKcMDdrcHZUQ5kdW/DwknjK2@s1n3zNE4dGmJifdl9aTzIjUxLF65mvP9oJZpYKEnc/TbF5do4p8WM@FMHuTHZ5PkxZkX0ZswP5MYr/64isoc4LYn3KaX79j09SFrpNv0A "C (gcc) – Try It Online") A more ungolfed version of my original answer: ``` #include<stdio.h> char*a="& ; $ # 4 % " " ; B * 6 $ 8 " " 6 5 - >3 +" " A@( . 6 5 "; int b(char*r,int s){ for(int i=0;i<17;i++) if(a[i+s]-3==(r[0]^r[1])) return i/2+1; return 0; } #define c(p,r,i)(p+1)*b(r[i+1],i*17)/2 int main(int n,char**r){ int x=b(r[1],0); printf("%d\n",x+c(x,r,1)+c(x,r,2)+c(x,r,3)); } ``` You need to supply four command line arguments - so for the first test case you need to run `./a.out Lo Ful "" ""` [Answer] ## Haskell, 623 bytes Using ADTs instead of numerical voodoo. **NOTE: Add 36 for `{-# LANGUAGE GADTs,ViewPatterns #-}`** * Score is computed assuming that it is compiled/run with `-XGADTs -XViewPatterns` ``` data P=Lo|Um|On|Ee|Pal|Mon deriving(Enum,Read,Eq) data E=Ya|Vi|Oh|Ful|Des|Zo deriving(Enum,Read,Eq) data F=Ven|Ew|Kath|Ir|Bro|Gor deriving(Enum,Read,Eq) data C=Ku|Ros|Dain|Neta|Ra|Sar deriving(Enum,Read,Eq) data S where S::P->E->S Q::P->E->F->S R::P->E->F->C->S k(a:b:x)=let{p=read a;e=read b}in case x of{[]->S p e;[c]->Q p e(read c);[c,d]->R p e(read c)(read d)} c,d::Enum a=>a->Int c=succ.fromEnum d=(+2).fromEnum e Bro=7 e x=(+2).d$x f x|c x`elem`[1,5,6]=d x|2>1=c x g p f x =(`div`2).(*f x).succ$c p h(S x y)=c x+g x d y h(Q x y z)=h(S x y)+g x e z h(R x y z t)=h(Q x y z)+g x f t main=print.h.k.words=<<getLine ``` Input: a single spell as a normal string e.g. `Lo Ful` `Um Ful` Multilining can be done by replacing the last line with ``` main=interact$unlines.map(show.h.k.words).lines ``` But this would add bytes to the count ]
[Question] [ **Task description:** Draw a cube in ASCII art in roughly a cabinet projection. `Monospaced fonts` often have characters that are about twice as high as they are wide. Since the input is the length of the vertical lines (excluding the corners), horizontal lines are drawn with twice as many characters so that the resulting image is really roughly a cube. The receding lines are drawn at half the length as mandated by a cabinet projection. Corners of the cube are represented by `+`, horizontal lines by `-`, vertical lines by `|` and diagonal ones use `/`. Summarizing: Let the input be *n*, then * A horizontal edge of the cube are drawn with `-` and consists of 2 *n* characters. * A vertical edge of the cube are drawn with `|` and consists of *n* characters. * A diagonal edge of the cube are drawn with `/` and consists of *n*/2 characters. * Corners of the cube are drawn with `+`. Corners are not counted for the length of an edge as detailed above (see examples below as well). **Input:** The input, given on standard input, is a single positive, even number *n* (2 ≤ *n* ≤ 30) that gives the length of the vertical lines of the cube. It is followed by a single line break. **Output:** The output is a cube on standard output following above rules. Trailing whitespace on the lines is ignored. **Sample input 1:** ``` 2 ``` **Sample output 1:** ``` +----+ / /| +----+ | | | + | |/ +----+ ``` **Sample input 2:** ``` 4 ``` **Sample output 2:** ``` +--------+ / /| / / | +--------+ | | | | | | + | | / | |/ +--------+ ``` **ETA:** I now accepted the shortest solution. I will update the accepted answer when a shorter one comes along. Since some people asked how long the entries of our contestants were: > > 227 – Python > > 240 – Perl > > 310 – C > > 315 – C > > 326 – VB.NET > > 459 – C > > > As well as our own solutions (not ranked with the others): > > 140 – Golfscript > > 172 – [Ruby](https://codegolf.stackexchange.com/questions/189/drawing-a-cube-in-ascii-art/240#240) > > 183 – [PowerShell](https://codegolf.stackexchange.com/questions/189/drawing-a-cube-in-ascii-art/236#236) > > > [Answer] ## Python - 248 243 230 227 191 Slightly messy but it basically prints the cube line by line(using a string buffer). ``` t=v=h=input()/2 s,p,b,f,n=" +|/\n" l=p+"-"*t*4+p;S=s*4*t;k=s*h;K=b+S+b r=s*t+s+l+n while t:r+=s*t+f+S+f+s*(h-t)+b+n;t-=1 r+=l+k+b+n+(K+k+b+n)*(v-1)+K+k+p+n while v:v-=1;r+=K+s*v+f+n print r+l ``` Thanks to @marcog, for pointing out the first line, @ThomasO for pointing out the second line and to @Juan for making me realise I can combine lines. [Answer] ## Golfscript - 96 chars ``` ~:<2/:$){' '*}:s~'++'<'--'**:^n$,{.$\-s'//'2s<*:&*@s'|':|n}%^$[$s|n|&|]*$s'+'n$,{n'/'@s|&|}%-1%^ ``` Most of the compactness comes from aggressively storing almost everything to a variable (unless you include being written in golfscript). ``` < n $ n/2 s {' '*} # top of the stack becomes a string of that many spaces ^ '+------+' & ' ' # 2n spaces, i.e. 2s<* or <s2* | '|' ``` A couple of other small tricks here. 1. `'LR''str'*` -> `'LstrR'`. 2. Since we need to reverse the order of lines in the last array, we opt to do this after generating the text instead of before. This allows us to save one character because the spaces before the `'/'` only needs to go past two stack elements (`@`) instead of 3 (`@ .. \`). [Answer] Python - 179 ``` h=input()*2 j=d=h/4 q,e,u,p,k="| \n+/" w=e*d s=p+'-'*h+p i='' o=e+w+s+u v=q+e*h+q while j:o+=e*j+k+e*h+k+e*(d-j)+q+u;j-=1;i+=v+e*j+k+u print o+s+w+q+u+(v+w+q+u)*(d-1)+v+w+p+u+i+s ``` I'd like to note that I took some ideas from JPvdMerwe (Using a string to print once, and the one-liner for that I didn't know was correct syntax in Python). [Answer] ## fortran 77 -- 484 characters ``` program z read(*,*) i g=f('+- ',i/2+1,i,0) do k=1,i/2 g=f('/ |',i/2-k+1,i,k-1) end do g=f('+-|',0,i,i/2) do k=1,i/2-1 g=f('| |',0,i,i/2) end do g=f('| +',0,i,i/2) do k=1,i/2 g=f('| /',0,i,i/2-k) end do g=f('+- ',0,i,0) stop end real function f(c,l,m,n) character c(3) write(*,*)(' ',j=1,l),c(1),(c(2),j=1,2*m),c(1),(' ',j=1,n),c(3) return end ``` No real point in providing a "unobsfucated" version. And note that markdown doesn't get along well with the indent requirements. I tried fortran because of the inline for loops provided by the `write` statement. Obviously they help but don't add up to enough to kill the wordiess of the language. It could be reduce by using freeform input. **Validation:** ``` $ wc cube_func_array.f 22 41 484 cube_func_array.f $ gfortran cube_func_array.f $ echo 2 | ./a.out +----+ / /| +----+ | | | + | |/ +----+ $ echo 4 | ./a.out +--------+ / /| / / | +--------+ | | | | | | + | | / | |/ +--------+ ``` Thankfully the spec doesn't say what size one should look like: ``` $ echo 1 | ./a.out +--+ +--+| | |+ +--+ ``` but other odd sizes are reasonable: ``` $ echo 3 | ./a.out +------+ / /| +------+ | | | + | |/ +------+ ``` [Answer] ## PostScript, 237 ``` [/n(%stdin)(r)file token()/p{print}/r{repeat}([){{( )p}r}/N{n 2 mul}(]){n 2 idiv}/l{N(+)p{(-)p}r(+)p}/I{(|)p}/X{][p}>>begin ( )X l()=]-1 1{dup[(/)p N[(/)p]exch sub[(|)=}for l(| )X]1 sub{I N[I(| )X}r I N[I(+ )X]-1 1{I N[I 1 sub[(/)=}for l ``` History: * 2011-03-01 01:54 **(427)** First attempt. * 2011-03-01 02:01 **(342)** `def`ed a few more things that appeared often. * 2011-03-01 02:24 **(283)** Even more `def`s. * 2011-03-01 02:42 **(281)** Aaand another `def` that saves two more bytes. * 2011-03-01 03:01 **(260)** `[` and `]` have nice properties when used as variables :-). Thanks to [KirarinSnow](https://codegolf.stackexchange.com/users/157/kirarinsnow). * 2011-03-01 03:12 **(246)** Inline line breaks, using a dict instead of numerous `def`s. Thansk again :-). * 2011-03-01 03:26 **(237)** More thanks to [KirarinSnow](https://codegolf.stackexchange.com/users/157/kirarinsnow). [Answer] My own solution, since it has already been beaten to death by Python: ### Windows PowerShell, 183 ``` $t=($w=($s=' ')*($o=($n="$input")/2))*4 $r="|$t|" $s*($a=$o+1)+($q='+'+'--'*$n+'+') $o..1|%{$s*--$a+"/$t/$($s*$b++)|"} "$q$w|" for(;$o-++$x){"$r$w|"}"$r$w+" --$b..0|%{$r+$s*$_+'/'} $q ``` [Answer] ## Ruby 1.9, ~~172 165~~ 162 characters ``` w=(s=?\s)*o=(n=gets.to_i)/2;r=(z=?|)+w*4+z puts s*(o+1)+q=?++?-*2*n+?+,(l=0...o).map{|u|[s*(o-u),w*4,s*u+z]*?/},q+w+z,[r+w+z]*o-=1,r+w+?+,l.map{|u|r+s*(o-u)+?/},q ``` [Answer] ## Ruby - 423 characters Really don't want to share this since it's such a horrible count, but since I've written it might as well. ``` n=$<.read.to_i a=(q=Array).new(n+n/2+3){q.new(2*n+n/2+3,' ')<<"\n"} a[n+1][2*n+n/2+2]=a[0][n/2+1]=a[0][2*n+n/2+1]=a[n/2+1][0]=a[n/2+1][2*n]=a[n+n/2+2][0]=a[n+n/2+2][2*n]=:+ a[0][n/2+2,n*2-1]=a[n/2+1][1,n*2-1]=a[n+n/2+2][1,n*2-1]=[:-]*2*n a[n/2+2,n].each{|b|b[0]=b[2*n+1]=:|} a[1,n].each{|b|b[2*n+n/2+2]=:|} c=n/2 a[1,n/2].each{|b|b[c]=b[2+2*n+c-=1]=:/} c=n/2 a[n+2,n/2].each{|b|b[2+2*n+c-=1]=:/} a.flatten.each{|g|print g} ``` Could probably be reduced by quite a bit but I doubt this brute-force approach is going to come anywhere near a decent number of characters so I can't be bothered. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `J`, 61 bytes ``` ½:→›\+?-m:£꘍←ƛ\/?꘍m꘍;Ṙ?ɾv\|?꘍vm¥pJ←ʁ←›v←ȮṘJJ꘍?\|*\++←\/*+f+⁋¥ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJKIiwiIiwiwr064oaS4oC6XFwrPy1tOsKj6piN4oaQxptcXC8/6piNbeqYjTvhuZg/yb52XFx8P+qYjXZtwqVwSuKGkMqB4oaQ4oC6duKGkMiu4bmYSkrqmI0/XFx8KlxcKyvihpBcXC8qK2Yr4oGLwqUiLCIiLCI4Il0=) This was harder than I thought it'd be. -4 thanks to @AaroneousMiller. Woo, beating ascii-art langs! [Answer] ## PHP, ~~401~~ ~~392~~ ~~382~~ 363 characters: ``` <? $h=fgets(STDIN);$s="str_repeat";$w=$h*2;$d=$h/2;$b=$h;$c=" ";echo$s($c,$h/2+1)."+".$s("-",$w)."+\n";for($i=1;$i<=$d;$i++,$a=--$b){echo$s($c,($h/2+1)-$i)."/".$s($c,$w)."/".$s($c,$i-1)."|\n";}echo"+".$s("-",$w)."+".$s($c,$d)."|\n";for($i=1;$i<=$h;$i++){echo"|".$s($c,$w)."|";echo $a-->0?$s($c,$b).($a>0?"|":"+")."\n":$s($c,$h-$i)."/\n";}echo"+".$s("-",$w)."+\n"; ``` I originally did this to see how short I could manage to do this in PHP, as I knew that it would be pretty long. I'm sure it could be reduced, but not by much considering PHP doesn't have many shortcuts. **Validation:** <http://codepad.viper-7.com/ftYYz9.php53> Ungolfed Version: <http://codepad.viper-7.com/4D3kIA> [Answer] ## Perl, 163 ``` $d=<>/2;$s=$"x$d;$H=$s x4;$f="|$H|";$t.=$" x$d--."/$H/".$"x$_."|\n",$m.="$f$s|\n",$b =$f.$"x$_."/\n$b"for 0..$d-1;$_="+$H+"; y/ /-/;say" $s$_\n$t$_$s|\n$m$f$s+\n$b$_" ``` Perl 5.10 or later, run with `perl -E '<code here>'` Respaced version: ``` $d = <> / 2; $s = $" x $d; $H = $s x 4; $f = "|$H|"; $t .= $" x $d-- . "/$H/" . $"x$_ . "|\n", $m .= "$f$s|\n", $b = $f . $" x $_ . "/\n$b" for 0 .. $d-1; $_ = "+$H+"; y/ /-/; say " $s$_\n$t$_$s|\n$m$f$s+\n$b$_" ``` [Answer] ### Perl, 269 269 262 256 245 244 237 226 228 224 217 chars ``` sub p{y/xS/+\//;print;y/+\//xS/}$b=/2;$a=$b;$_=" xx\n";s/ x/ x----/while($a--);until(/^S/){p;s/ [xS]/S /g;s/-x/S|/;y/-/ /}s/ (?= *S)/-/g;y/S/x/;p;y/-x/ |/;p while(--$b);s/.$/x/;while(/ \|/){p;s/..$/S/}y/|S /++-/;p ``` The basic idea is to do everything with regex substitutions. Because two of the characters used (+ and /) are special characters and turn up a lot in the regexes, it's worthwhile using other characters and substituting them to print. Slightly more legible version: ``` # Subroutine to substitute, print, and unsubstitute as described above sub p{y/xS/+\//;print;y/+\//xS/} # Read from stdin and set up the initial line $b=<>/2;$a=$b;$_=" xx\n"; s/ x/ x----/ while($a--); # Print the top face until(/^S/) { p; s/ [xS]/S /g; # First time round: left + -> /; subsequent times move / left s/-x/S|/; # Only relevant first time round the loop y/-/ / # Only relevant first time round the loop } # Prepare and print the line containing second horizontal line s/ (?= *S)/-/g; y/S/x/; p; # Now print (n-1)/2 identical lines y/-x/ |/; p while (--$b); # Bring the right edge in s/.$/x/; while(/ \|/) { p; s/..$/S/ } # Final line y/|S /++-/; p ``` In a sense I'm cheating by using $b as a counter in the intermediate loop - I could instead append whitespace in the loop over $a and then use regex replaces for that loop too - but I'm going to allow that slight deviation from a pure-regex solution. No doubt some scary person can turn this into a much shorter sed script. [Answer] # Lua, ~~294~~ ~~302~~ 292 bytes Golfed: ``` n=(...)p="+"d=2*n s=" "S=s:rep(d)h=n/2 T=s:rep(h)L="\n"o="/"v="|"a=p..("-"):rep(d)..p r=T..s..a..L for i=0,h-1 do r=r..s:rep(h-i)..o..S..o..s:rep(i)..v..L end r=r..a..T..v for i=1,h do r=r..L..v..S..v..T..(i==h and p or v) end for i=h-1,0,-1 do r=r..L..v..S..v..s:rep(i)..o end print(r..L..a) ``` Ungolfed: ``` n = n or io.read() or 6 plus = "+" doubled = 2*n space = " " Space = space:rep(doubled) halved = n/2 T = space:rep(halved) Line = "\n" or_sign = "/" vertical = "|" a = plus..("-"):rep(doubled)..plus result = T..space..a..Line for i=0,halved-1 do result = result .. space:rep(halved-i) .. or_sign .. Space .. or_sign .. space:rep(i) .. vertical .. Line end result = result..a..T..vertical for i=1,halved do result = result .. Line .. vertical .. Space .. vertical .. T .. (i==halved and plus or vertical) end for i=halved-1,0,-1 do result = result .. Line .. vertical .. Space .. vertical .. space:rep(i) .. or_sign end print(result .. Line .. a) ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 63 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ╴» ±╵⁷/╋╴«3+⁷ -×+×║⌐1╴├╋;⁷├⁷±╋2⁷⁸⁸├⁷/╋12╴«├2⁷5×3+⁷±╵⁰2n{┤╴|*+∔╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc0JUJCJTBBJUIxJXUyNTc1JXUyMDc3JXVGRjBGJXUyNTRCJXUyNTc0JUFCJXVGRjEzJXVGRjBCJXUyMDc3JTBBLSVENyslRDcldTI1NTEldTIzMTAldUZGMTEldTI1NzQldTI1MUMldTI1NEIldUZGMUIldTIwNzcldTI1MUMldTIwNzclQjEldTI1NEIldUZGMTIldTIwNzcldTIwNzgldTIwNzgldTI1MUMldTIwNzcldUZGMEYldTI1NEIldUZGMTEldUZGMTIldTI1NzQlQUIldTI1MUMldUZGMTIldTIwNzcldUZGMTUlRDcldUZGMTMldUZGMEIldTIwNzclQjEldTI1NzUldTIwNzAldUZGMTIldUZGNEUldUZGNUIldTI1MjQldTI1NzQlN0MldUZGMEErJXUyMjE0JXUyNTRC,i=NA__,v=0) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 40 bytes ``` ½"‛|/f*?d¤-JǏz:Yf:@2+$¤p\+jǏ»×g=↔F»8τ„ø∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLCvVwi4oCbfC9mKj9kwqQtSsePejpZZjpAMiskwqRwXFwrasePwrvDl2c94oaURsK7OM+E4oCew7jiiKciLCIiLCI0Il0=) ``` f* # Repeat each character of ‛|/ # "|/" ½" # by each of [input, input/2] - # Append ?d # 2*input hyphens ¤ # To the empty string J # Add that to the list Ǐz # Get all pairs :Yf # Double each pair ø∧ # Draw on canvas with :@ # Lengths: length of each of that 2+ # + 2 $ # String: That \+j # Joined by "+" ¤p Ǐ # With a + at the start and end »×g=↔F» # Directions: compressed number 8τ„ # Converted from base 8 to [4, 1, 0, 5, 1, 6, 5, 2, 6, 4, 2, 0] ``` ]
[Question] [ The derivative of a function is a cornerstone of mathematics, engineering, physics, biology, chemistry, and a large number of other sciences as well. Today we're going to be calculating something only tangentially related: the arithmetic derivative. # Definition The arithmetic derivative `a(n)` or `n'` is defined here ([A003415](http://oeis.org/A003415)) by a number of properties that are similar to the derivative of a function. * `a(0) = a(1) = 0`, * `a(p) = 1`, where `p` is any prime, and * `a(mn) = m*a(n) + n*a(m)`. The third rule is based on the product rule for differentiation of functions: for functions `f(x)` and `g(x)`, `(fg)' = f'g + fg'`. So with numbers, `(ab)' = a'b + ab'`. Also of note, since the arithmetic derivative can be extended to the negative numbers via this simple relation, `a(-n) = -a(n)`, the input may be negative. # Rules * Write a program or function that, given any integer `n`, returns the arithmetic derivative of `n`. * Inputs will be `-230 < n < 230`, to avoid problems with integer sizes and numbers too large to factor in a reasonable amount of time. Your algorithm should still be able to theoretically calculate the arithmetic derivative of numbers outside this range. * Built-ins for symbolic math, prime factorization and differentiation are allowed. # Examples ``` > a(1) 0 > a(7) 1 > a(14) # a(7)*2 + a(2)*7 = 1*2 + 1*7 = 9 9 > a(-5) # a(-5) = -a(5) = -1 -1 > a(8) # a(8) = a(2**3) = 3*2**2 = 12 12 > a(225) # a(225) = a(9)*25 + a(25)*9 = 6*25 + 10*9 = 150 + 90 = 240 240 > a(299792458) # a(299792458) = a(2)*149896229 + a(7)*42827494 + a(73)*4106746 + a(293339)*1022 = 1*149896229 + 1*42827494 + 1*4106746 + 1*1022 = 149896229 + 42827494 + 4106746 + 1022 = 196831491 196831491 ``` As always, if the problem is unclear, please let me know. Good luck and good golfing! [Answer] # [MATL](https://esolangs.org/wiki/MATL), 12 bytes ``` |1>?GtYf/s}0 ``` [**Try it online!**](http://matl.tryitonline.net/#code=fDE-P0d0WWYvc30w&input=Mjk5NzkyNDU4) ### Explanation Consider an integer *a* with |*a*|>1, and let the (possibly repeated) prime factors of |*a*| be *f*1, ..., *f**n*. Then the desired result is *a*·(1/*f*1 + ... + 1/*f**n*). ``` |1> % take input's absolute value. Is it greater than 1? ? % if so: Gt % push input twice Yf % prime factors. For negative input uses its absolute value / % divide element-wise s % sum of the array } % else: 0 % push 0 ``` [Answer] ## Python, 59 bytes ``` f=lambda n,p=2:+(n*n>1)and(n%p and f(n,p+1)or p*f(n/p)+n/p) ``` A recursive function. On large inputs, it runs out of stack depth on typical systems unless you run it with something like [Stackless Python](https://en.wikipedia.org/wiki/Stackless_Python). The recursive definition is implemented directly, counting up to search for candidate prime factors. Since `f(prime)=1`, if `n` has a prime `p` as a factor, we have `f(n) == p*f(n/p)+n/p`. [Answer] # Jelly, ~~8~~ 7 bytes *-1 byte by @Dennis* ``` ÆfḟṠ³:S ``` Uses the same formula everyone else does. However, there's a little trick to deal with `0`. ``` o¬AÆfİS× Main link. Inputs: n o¬ Logical OR of n with its logical NOT That is, 0 goes to 1 and everything else goes to itself. A Then take the absolute value Æf get its list of prime factors İ divide 1 by those S sum × and multiply by the input. ``` Try it [here](http://jelly.tryitonline.net/#code=w4Zm4bif4bmgwrM6Uw&input=&args=LTI5OTc5MjQ1OA). [Answer] ## Python 2, ~~87~~ ~~78~~ ~~76~~ 74 bytes ``` a=b=input() d=2 s=0 while d<=abs(b): if a%d==0: a=a/d s+=b/d else: d+=1 print s ``` Improvements thanks to @Maltysen: ``` a=b=input() d=2 s=0 while d<=abs(b): if a%d==0:a/=d;s+=b/d else:d+=1 print s ``` Further improvement by two bytes: ``` a=b=input() d=2 s=0 while abs(a)>1: if a%d<1:a/=d;s+=b/d else:d+=1 print s ``` Further improvement thanks to @xnor: ``` a=b=input() d=2 s=0 while a*a>1: if a%d<1:a/=d;s+=b/d else:d+=1 print s ``` ### Explanation The arithmetic derivative of `a` is equal to `a` times the sum of the reciprocals of the prime factors of `a`. No exception for 1 is needed since the sum of the reciprocals of the prime factors of 1 is zero. [Answer] # Haskell, ~~203~~ 90 bytes Thanks @nimi! I still have no idea when what indentations cause what interpretation, this is the shortest I managed so far, and as always, I'm sure it can be golfed a lot more. I'm going to try again in the evening. ``` n#(x:_)|y<-div n x=x*a y+y*a x;_#_=1 a n|n<0= -a(-n)|n<2=0|1<2=n#[i|i<-[2..n-1],mod n i<1] ``` [Answer] # J, ~~30~~ ~~27~~ 19 chars Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for chopping off 3 characters. Thanks to [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) for chopping off 8 characters. ``` 0:`(*[:+/%@q:@|)@.* ``` [Try it online!](http://tryj.tk/) Sample input: ``` 0:`(*[:+/%@q:@|)@.* _8 _12 0:`(*[:+/%@q:@|)@.* 0 0 0:`(*[:+/%@q:@|)@.* 8 12 ``` How it works: ``` 0:`(*[:+/%@q:@|)@.* N XX`[[email protected]](/cdn-cgi/l/email-protection) if Z then Y else X end 0: X: return 0 Z Z: signum(N) (*[:+/%@q:@|) Y: N*add_all(reciprocal_all(all_prime_factors(abs(N)))) N * * [:+/ add_all( ) %@ reciprocal_all( ) q:@ all_prime_factors( ) | abs( ) N ``` [Answer] # Pyth - ~~10~~ 8 bytes Lovin' the implicit input! Should bring it on par with Jelly for most things (Except Dennis' golfing skills). ``` *scL1P.a ``` [Test Suite](http://pyth.herokuapp.com/?code=%2ascL1P.a&test_suite=1&test_suite_input=1%0A7%0A14%0A-5%0A8%0A225%0A299792458&debug=0). ``` * Times the input, implicitly (This also adds the sign back in) s Sum cL1 Reciprocal mapped over lit P Prime factorization .a Absolute value of input, implicitly ``` [Answer] ## Haskell, 59 bytes ``` n%p|n*n<2=0|mod n p>0=n%(p+1)|r<-div n p=r+p*r%2 (%2) ``` Implements the recursive definition directly, with an auxiliary variable `p` that counts up to search for potential prime factors, starting from `2`. The last line is the main function, which plugs `p=2` to the binary function defined in the first line. The function checks each case in turn: * If `n*n<2`, then `n` is one of `-1,0,1`, and the result is `0`. * If `n` is not a multiple of `p`, then increment `p` and continue. * Otherwise, express `n=p*r`, and by the "derivative" property, the result is `r*a(p)+p*a(r)`, which simplifies to `r+p*a(r)` because `p` is prime. The last case saves bytes by [binding `r` in a guard](https://codegolf.stackexchange.com/a/76749/20260), which also avoids the `1>0` for the boilerplate `otherwise`. If `r` could be bound earlier, the second condition `mod n p>0` could be checked as `r*p==n`, which is 3 bytes shorter, but I don't see how to do that. [Answer] # [Japt](https://github.com/ETHproductions/japt) [-x](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), ~~16~~ ~~13~~ 10 bytes ``` ÒU©a k £/X ``` *- 6 bytes thanks to @Shaggy* [Try it online!](https://tio.run/##y0osKPn///Ck0EMrExWyFQ4t1o/4/9/QREG3AgA "Japt – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~13~~ 9 bytes A simple solution. The Dyalog Unicode version was simply a longer version of this so it has been omitted. **Edit:** Saved 4 bytes by adopting the method in [lirtosiast's Jelly solution](https://codegolf.stackexchange.com/a/76976/47581). ``` {+/⍵÷⍭|⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1pb/1Hv1sPbD29/1DHjUeeiRz07HvWurQGK1f5Pe9Q24VFv36O@qZ7@j7qaD603ftQ2EcgLDnIGkiEensH/0w6tMFQwVzA0UTi03lTBQsHIyBQA "APL (Dyalog Extended) – Try It Online") **Ungolfing** ``` {+/⍵÷⍭|⍵} { } A dfn, a function in {} brackets. ⍭|⍵ The prime factors of the absolute value of our input. ⍵÷ Then divide our input by the above array, giving us a list of products for the product rule. +/ We sum the above numbers, giving us our arithmetic derivative. ``` [Answer] # Ruby, ~~87~~ ~~66~~ ~~80~~ ~~75~~ ~~70~~ 68 bytes This answer is based on [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/76949/47581), [wythagoras's Python answer](https://codegolf.stackexchange.com/a/76957/47581), and the idea that the arithmetic derivative of a number `m` is equal to `m·(1/p1 + 1/p2 + ... + 1/pn)` where `p1...pn` is every prime factor of `n` to multiplicity. ``` ->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s} ``` This function is called in the following way: ``` > a=->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s} > a[299792458] 196831491 ``` **Ungolfing:** ``` def a(n) s = 0 m = n.abs (2...m).each do |z| while m%d == 0 m /= d s += n / d end end if s == 0 if n > 1 s += 1 # if s is 0, either n is prime and the while loop added nothing, so add 1 # or n.abs < 2, so return 0 anyway # 0**s is used in the code because it returns 1 if s == 0 and 0 for all other s end end return s end ``` [Answer] # Julia, ~~72~~ 43 bytes ``` n->n^2>1?sum(p->n÷/(p...),factor(n^2))/2:0 ``` This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable. For an input integer *n*, if *n*2 ≤ 1 return 0. Otherwise obtain the prime factorization of *n*2 as a `Dict`, then for each prime/exponent pair, divide the prime by its exponent, then divide *n* by the result. This is just computing *n* *x* / *p*, where *p* is the prime factor and *x* is its exponent, which is the same as summing *n* / *p*, *x* times. We sum the resulting array and divide that by 2, since we've summed twice as much as we need. That's due to the fact that we're factoring *n*2 rather than *n*. (Doing that is a byte shorter than factoring |*n*|.) Saved 29 bytes thanks to Dennis! [Answer] # [Seriously](http://github.com/Mego/Seriously), ~~17~~ ~~14~~ ~~11~~ 12 bytes My first ever Seriously answer. This answer is based on [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/76949/47581) and the idea that the arithmetic derivative of a number `m` is equal to `m·(1/p1 + 1/p2 + ... + 1/pn)` where `p1...pn` is every prime factor of `n` to multiplicity. My addition is to note that, if `m = p1e1·p2e2·...·pnen`, then `a(m) = m·(e1/p1 + e2/p2 + ... + en/pn)`. Thanks to [Mego](https://codegolf.stackexchange.com/users/45941/mego) for golfing and bug fixing help. [Try it online!](http://seriously.tryitonline.net/#code=LDt3YGlAL2BNzqMqbA&input=LTEy) ``` ,;w`i@/`MΣ*l ``` **Ungolfing:** ``` , get a single input ;w duplicate input and get prime factorization, p_f for input [-1..1], this returns [] and is dealt with at the end ` `M map the function inside `` to p_f i pop all elements of p_f[i], the prime and the exponent, to the stack @ rotate so that the exponent is at the top of the stack / divide the exponent by the prime Σ sum it all together * multiply this sum with the input l map and multiply do not affect an empty list, so we just take the length, 0 l is a no-op for a number, so the result is unchanged for all other inputs ``` [Answer] # Jolf, 13 bytes ``` *jmauΜm)jd/1H ``` Kudos to the MATL answer for the algorithm! [Try it here](http://conorobrien-foxx.github.io/Jolf/#code=KmptYXXOnG0pamQvMUg), [or test them all at once](http://conorobrien-foxx.github.io/Jolf/#code=b25bMSwgNywgMTQsIC01LCA4LCAyMjUsIDI5OTc5MjQ1OF0KzpxuZM26SCpIbWF1zpxtKUhkLzFI). (Outputs [key,out] in an array.) ## Explanation ``` *jmauΜm)jd/1H *j input times m)j p.f. of input Μ d/1H mapped to inverse u sum of ma abs of ``` [Answer] # Mathematica 10.0, 39 bytes ``` Tr[If[#>1,#2/#,0]&@@@FactorInteger@#]#& ``` [Answer] # APL(NARS), 35 char, 70 bytes ``` {1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k} ``` test and how to use: ``` f←{1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k} f 14 9 f 8 12 f 225 240 f ¯5 ¯1 f 299792458 196831491 ``` I thought that it would not be ok because I don't know if c variable is composed (and not a prime)... But seems ok for the test... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÄÒ÷O ``` Port of [*@lirtosiast*'s Jelly answer](https://codegolf.stackexchange.com/a/76976/52210). [Try it online](https://tio.run/##yy9OTMpM/f//cMvhSYe3@///r2tkaWluaWRiagEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf8PtxyedHi7/3@d/9EGOoY65jqGJjq6pjoWOkZGpjpGlpbmlkYmphY6unBmLAA). **Explanation:** ``` Ä # Take the absolute value of the (implicit) input Ò # Get all its prime factors (with duplicates) ÷ # Integer divide the (implicit) input by each of these prime factors O # And take the sum (which is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 3 bytes ``` ȧǐ/ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C8%A7%C7%90%2F&inputs=225&header=&footer=) ``` ȧ # Abs. val ǐ # All prime factors # (Implicit input) / # Divided by each factor. # (s flag) sum of stack ``` -1 thx to Underslash [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes ``` n->n*vecsum([i[2]/p|i<-factor(n)~,0<p=i[1]]) ``` [Try it online!](https://tio.run/##FYzRCsIgGEZf5WNXGr@UsrEJ215EvJCRIZT92AqC6NXNrr5z4PBxKElduEYsqFmt@fA6b4/nTbjkjD/yJ80qhm2/F5Hll04zL8lp72UNzNe3yFAruKS8N@z@0iG2VBKcJowE3RPUQJgIxrQ11o7W9MPUPn4 "Pari/GP – Try It Online") [Answer] # Perl 5, 62 bytes ``` perl -MMath::Prime::Util=:all -E"map$i+=1/$_,factor abs($j=<>);say$i*$j" ``` Uses the formula (from OEIS): `If n = Product p_i^e_i, a(n) = n * Sum (e_i/p_i).` [Answer] ## Perl 6, 90 ``` sub A(\n) {0>n??-A(-n)!!(n>1)*{$_??n/$_*A($_)+$_*A n/$_!!1}(first n%%*,2..^n)};say A slurp ``` This might be a bit slow for large numbers. Replace `2..^n` with `2..n.sqrt` for longer code but faster computation. [Answer] # [Ink](https://github.com/inkle/ink), 183 bytes ``` ==function a(n) {n<0: ~return-a(-n) } {n<2: ~return 0 } ~temp f=t(n,2) {f: ~return a(n/f)*f+n/f } ~return 1 ==function t(n,i) {n>1&&n-i: {n%i: ~return t(n,i+1) } ~return i } ~return 0 ``` [Try it online!](https://tio.run/##TY1BDoMgEEX3nIJNDdSSAtFYTOldTCMJaTo2BldGr06HYqqrN7zh//HwinPHFF8IoslQVaaoM28ZWm9vbUxjdFWjj9a6CZ7BD0A7BpzMcJctWcc@TCMI7EC3JKv/lko0a@jfH@psYHDRGHP7Gnuujp9diUg/N63I4VaK@XTtoYoChG9xPPm947cvFT/k/WGWMX4B "ink – Try It Online") I refuse to believe this is a good solution, but I can't see a way to improve it either. ]
[Question] [ ## CONGRATULATIONS to @kuroineko for the best entry and winning the 200 bounty from @TheBestOne (excellent sportsmanship!). Write a program to colour as much of an image as possible before opposition programs do. ## Rules in brief * Your program will be given an image, your colour, and integer N. * Each turn you are sent pixel updates by other programs, and asked for your N updates. * You can update any white pixel that is next to a pixel of your colour. * The program that has added the most pixels wins. ## Rules in detail Your program will be given a PNG image filename, home colour, and a number N. The number N is the maximum number of pixels your program may colour each turn. Example: `MyProg arena.png (255,0,0) 30` The input image will be a rectangle with sides between 20 and 1000 pixels long. It will consist of black, white, and colour pixels. Your program may choose a sequence of *white* pixels to colour as your own, with the condition that each new pixel must have at least one of its four neighbour pixels of your own colour. The image will initially have at least one pixel of your colour. It may also have pixels of colours that no program is assigned to. The alpha channel is not used. Your goal is to block your opponents and write your colour into as many pixels as you can. Each turn your program will accept 1 or more message lines on STDIN, and write a line consisting of pixel coordinates on STDOUT. Remember to assign STDOUT as unbuffered or flush the STDOUT buffer each turn. The order of players called each turn will be randomly assigned. This means that an opponent (or your program) may have 2 turns in a row. Your program will be sent `colour (N,N,N) chose X,Y X,Y ... X,Y` information messages that describe the pixels filled in by player programs. If a player makes no moves, or no valid moves, you will not be sent a message about that player's moves. Your program will also be sent a message about your own accepted moves (if you have specified at least one valid move). The pixel 0,0 is in the top left corner of the image. On receiving `pick pixels`, your program will output `X,Y X,Y ... X,Y` up to N pixels (an empty string consisting of just a '\n' is allowed). The pixels must be in order of plotting. If a pixel is invalid, it will be ignored and not be in the report to players. Your program has 2 seconds to initialise after starting, but only 0.1 second to reply with an answer each turn or it will miss that turn. A pixel update sent after 0.1 second will record a fault. After 5 faults your program is suspended and will not be sent updates or `pick pixels` requests. When the judge program receives an empty or invalid pixel choice from every non-suspended player program, the image will be considered *complete* and programs will be sent the message "exit". Programs must terminate after receiving "exit". ## Scoring The judge will score points after the image is complete. Your score will be your number of pixels updated divided by the average pixel capture that round, expressed as a percentage. The number of pixels added to the image by your player is A. The total number of pixels added by *all* P players is T. `avg = T/P` `score = 100*A/avg` ## Posting scores A reference opponent "The Blob" is given. For each answer, title your bot with a name, language, and your score (average of arena 1 to 4) against the reference opponent. A picture or animation of one of your battles would be good too. The winner is the program with the highest score against the reference bot. If The Blob proves too easy to beat, I may add a second round with a stronger reference opponent. You may also like to experiment with 4 or more player programs. You could also test your bot against other bots posted as answers. ## The Judge The judge program requires the common Python Imaging Library (PIL) and should be easy to install from your OS package manager on Linux. I have a report that PIL does not work with 64 bit Python on Windows 7, so please check if PIL will work for you before starting this challenge (updated 2015-01-29). ``` #!/usr/bin/env python # Judge Program for Image Battle challenge on PPCG. # Runs on Python 2.7 on Ubuntu Linux. May need edits for other platforms. # V1.0 First release. # V1.1 Added Java support # V1.2 Added Java inner class support # usage: judge cfg.py import sys, re, random, os, shutil, subprocess, datetime, time, signal from PIL import Image ORTH = ((-1,0), (1,0), (0,-1), (0,1)) def place(loc, colour): # if valid, place colour at loc and return True, else False if pix[loc] == (255,255,255): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] if any(pix[p]==colour for p in plist if 0<=p[0]<W and 0<=p[1]<H): pix[loc] = colour return True return False def updateimage(image, msg, bot): if not re.match(r'(\s*\d+,\d+)*\s*', msg): return [] plist = [tuple(int(v) for v in pr.split(',')) for pr in msg.split()] plist = plist[:PIXELBATCH] return [p for p in plist if place(p, bot.colour)] class Bot: botlist = [] def __init__(self, name, interpreter=None, colour=None): self.prog = name self.botlist.append(self) callarg = re.sub(r'\.class$', '', name) # Java fix self.call = [interpreter, callarg] if interpreter else [callarg] self.colour = colour self.colstr = str(colour).replace(' ', '') self.faults = 0 self.env = 'env%u' % self.botlist.index(self) try: os.mkdir(self.env) except: pass if name.endswith('.class'): # Java inner class fix rootname = re.sub(r'\.class$', '', name) for fn in os.listdir('.'): if fn.startswith(rootname) and fn.endswith('.class'): shutil.copy(fn, self.env) else: shutil.copy(self.prog, self.env) shutil.copy(imagename, self.env) os.chdir(self.env) args = self.call + [imagename, self.colstr, `PIXELBATCH`] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) os.chdir('..') def send(self, msg): if self.faults < FAULTLIMIT: self.proc.stdin.write(msg + '\n') self.proc.stdin.flush() def read(self, timelimit): if self.faults < FAULTLIMIT: start = time.time() inline = self.proc.stdout.readline() if time.time() - start > timelimit: self.faults += 1 inline = '' return inline.strip() def exit(self): self.send('exit') from cfg import * for i, (prog, interp) in enumerate(botspec): Bot(prog, interp, colourspec[i]) image = Image.open(imagename) pix = image.load() W,H = image.size time.sleep(INITTIME) total = 0 for turn in range(1, MAXTURNS+1): random.shuffle(Bot.botlist) nullbots = 0 for bot in Bot.botlist: bot.send('pick pixels') inmsg = bot.read(TIMELIMIT) newpixels = updateimage(image, inmsg, bot) total += len(newpixels) if newpixels: pixtext = ' '.join('%u,%u'%p for p in newpixels) msg = 'colour %s chose %s' % (bot.colstr, pixtext) for msgbot in Bot.botlist: msgbot.send(msg) else: nullbots += 1 if nullbots == len(Bot.botlist): break if turn % 100 == 0: print 'Turn %s done %s pixels' % (turn, total) for msgbot in Bot.botlist: msgbot.exit() counts = dict((c,f) for f,c in image.getcolors(W*H)) avg = 1.0 * sum(counts.values()) / len(Bot.botlist) for bot in Bot.botlist: score = 100 * counts[bot.colour] / avg print 'Bot %s with colour %s scored %s' % (bot.prog, bot.colour, score) image.save(BATTLE+'.png') ``` ## Example Config - cfg.py ``` BATTLE = 'Green Blob vs Red Blob' MAXTURNS = 20000 PIXELBATCH = 10 INITTIME = 2.0 TIMELIMIT = 0.1 FAULTLIMIT = 5 imagename = 'arena1.png' colourspec = (0,255,0), (255,0,0) botspec = [ ('blob.py', 'python'), ('blob.py', 'python'), ] ``` ## The Blob - the reference opponent ``` # Blob v1.0 - A reference opponent for the Image Battle challenge on PPCG. import sys, os from PIL import Image image = Image.open(sys.argv[1]) pix = image.load() W,H = image.size mycolour = eval(sys.argv[2]) pixbatch = int(sys.argv[3]) ORTH = ((-1,0), (1,0), (0,-1), (0,1)) def canchoose(loc, colour): if pix[loc] == (255,255,255): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] if any(pix[p]==colour for p in plist if 0<=p[0]<W and 0<=p[1]<H): return True return False def near(loc): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] pboard = [p for p in plist if 0<=p[0]<W and 0<=p[1]<H] return [p for p in pboard if pix[p] == (255,255,255)] def updateimage(image, msg): ctext, colourtext, chose, points = msg.split(None, 3) colour = eval(colourtext) plist = [tuple(int(v) for v in pr.split(',')) for pr in points.split()] for p in plist: pix[p] = colour skin.discard(p) if colour == mycolour: for np in near(p): skin.add(np) board = [(x,y) for x in range(W) for y in range(H)] skin = set(p for p in board if canchoose(p, mycolour)) while 1: msg = sys.stdin.readline() if msg.startswith('colour'): updateimage(image, msg.strip()) if msg.startswith('pick'): plen = min(pixbatch, len(skin)) moves = [skin.pop() for i in range(plen)] movetext = ' '.join('%u,%u'%p for p in moves) sys.stdout.write(movetext + '\n') sys.stdout.flush() if msg.startswith('exit'): break image.save('blob.png') ``` ## Arena 1 ![arena1.png](https://i.stack.imgur.com/x6wPJ.png) ## Arena 2 ![arena2.png](https://i.stack.imgur.com/lsc9N.png) ## Arena 3 ![arena3.png](https://i.stack.imgur.com/feG03.png) ## Arena 4 ![arena4.png](https://i.stack.imgur.com/vmWOM.png) ## An Example Battle - Blob vs Blob This battle had a predictable result: ``` Bot blob.py with colour (255, 0, 0) scored 89.2883333333 Bot blob.py with colour (0, 255, 0) scored 89.365 ``` ![Example Battle](https://i.stack.imgur.com/ERVws.png) [Answer] # Depth-first Blob vs. Blob # Language = Python (3.2) # Score = 111.475388276 153.34210035 Update : Now using a custom `Set` class to get the `pop()` method to produce a sort of grid pattern which drastically improves the area covered in the beginning cutting off large parts of the image from the enemy. Note : I am using a 12 x 12 grid for this which of a random sample of grid sizes seemed to give the best results for arena3 (the one that got the worst score before the update), however it is very likely that a more optimal grid size exists for the given selection of arenas. I went for a simple modification to the reference bot to make it favor picking feasible points that are bordered by as few own-colored points as possible. An improvement might be to make it also favor picking feasible points that are bordered by as many enemy-colored points as possible. dfblob.py: ``` import sys, os from PIL import Image class RoomyIntPairHashSet: def __init__(self, firstMax, secondMax): self.m1 = firstMax self.m2 = secondMax self.set = [set() for i in range((firstMax - 1) * (secondMax - 1) + 1)] self.len = 0 def add(self, tup): subset = self.set[self.gettuphash(tup)] self.len -= len(subset) subset.add(tup) self.len += len(subset) def discard(self, tup): subset = self.set[self.gettuphash(tup)] self.len -= len(subset) subset.discard(tup) self.len += len(subset) def pop(self): for s in self.set: if len(s) > 0: self.len -= 1 return s.pop() return self.set[0].pop() def gettuphash(self, tup): return (tup[0] % self.m1) * (tup[1] % self.m2) def __len__(self): return self.len gridhashwidth = 12 gridhashheight = 12 image = Image.open(sys.argv[1]) pix = image.load() W,H = image.size mycolour = eval(sys.argv[2]) pixbatch = int(sys.argv[3]) ORTH = ((-1,0), (1,0), (0,-1), (0,1)) def canchoose(loc, virtualneighbors, colour, num_neighbors): if pix[loc] == (255,255,255): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] actual_num_neighbors = 0 for p in plist: if 0<=p[0]<W and 0<=p[1]<H and pix[p]==colour or p in virtualneighbors: actual_num_neighbors += 1 return num_neighbors == actual_num_neighbors return False def near(loc, exclude): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] pboard = [p for p in plist if 0<=p[0]<W and 0<=p[1]<H] return [p for p in pboard if pix[p] == (255,255,255) and p not in exclude] def updateimage(image, msg): ctext, colourtext, chose, points = msg.split(None, 3) colour = eval(colourtext) plist = [tuple(int(v) for v in pr.split(',')) for pr in points.split()] for p in plist: pix[p] = colour for i in range(len(skins)): skins[i].discard(p) if colour == mycolour: for np in near(p, []): for j in range(len(skins)): skins[j].discard(np) if canchoose(np, [], mycolour, j + 1): skins[j].add(np) board = [(x,y) for x in range(W) for y in range(H)] skins = [] for i in range(1, 1 + len(ORTH)): skin = RoomyIntPairHashSet(gridhashwidth, gridhashheight) skins.append(skin) for p in board: if canchoose(p, [], mycolour, i): skin.add(p) while 1: msg = sys.stdin.readline() print("got message "+ msg, file=sys.stderr) if msg.startswith('colour'): print("updating image", file=sys.stderr) updateimage(image, msg.strip()) print("updated image", file=sys.stderr) if msg.startswith('pick'): moves = [] print("picking moves", file=sys.stderr) virtualskins = [RoomyIntPairHashSet(gridhashwidth, gridhashheight) for i in range(len(skins))] for i in range(pixbatch): for j in range(len(skins)): if len(virtualskins[j]) > 0 or len(skins[j]) > 0: move = None if len(virtualskins[j]) > 0: move = virtualskins[j].pop() else: move = skins[j].pop() moves.append(move) print("picking move (%u,%u) " % move, file=sys.stderr) for p in near(move, moves): for k in range(len(skins)): virtualskins[k].discard(p) if canchoose(p, moves, mycolour, k + 1): virtualskins[k].add(p) break movetext = ' '.join('%u,%u'%p for p in moves) print("picked %u moves" % (len(moves)), file=sys.stderr) sys.stdout.write(movetext + '\n') sys.stdout.flush() if msg.startswith('exit') or len(msg) < 1: break image.save('dfblob.png') ``` The original judge has been modified slightly to work with Python 3.2 (and to add a crude logging functionality to the bots + save picture of arena periodically to make animation) : ``` import sys, re, random, os, shutil, subprocess, datetime, time, signal, io from PIL import Image ORTH = ((-1,0), (1,0), (0,-1), (0,1)) def place(loc, colour): # if valid, place colour at loc and return True, else False if pix[loc] == (255,255,255): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] if any(pix[p]==colour for p in plist if 0<=p[0]<W and 0<=p[1]<H): pix[loc] = colour return True return False def updateimage(image, msg, bot): if not re.match(r'(\s*\d+,\d+)*\s*', msg): return [] plist = [tuple(int(v) for v in pr.split(',')) for pr in msg.split()] plist = plist[:PIXELBATCH] return [p for p in plist if place(p, bot.colour)] class Bot: botlist = [] def __init__(self, name, interpreter=None, colour=None): self.prog = name self.botlist.append(self) callarg = re.sub(r'\.class$', '', name) self.call = [interpreter, callarg] if interpreter else [callarg] self.colour = colour self.colstr = str(colour).replace(' ', '') self.faults = 0 self.env = 'env%u' % self.botlist.index(self) try: os.mkdir(self.env) except: pass shutil.copy(self.prog, self.env) shutil.copy(imagename, self.env) os.chdir(self.env) args = self.call + [imagename, self.colstr, str(PIXELBATCH)] errorfile = 'err.log' with io.open(errorfile, 'wb') as errorlog: self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errorlog) os.chdir('..') def send(self, msg): if self.faults < FAULTLIMIT: self.proc.stdin.write((msg+'\n').encode('utf-8')) self.proc.stdin.flush() def read(self, timelimit): if self.faults < FAULTLIMIT: start = time.time() inline = self.proc.stdout.readline().decode('utf-8') if time.time() - start > timelimit: self.faults += 1 inline = '' return inline.strip() def exit(self): self.send('exit') from cfg import * for i, (prog, interp) in enumerate(botspec): Bot(prog, interp, colourspec[i]) image = Image.open(imagename) pix = image.load() W,H = image.size os.mkdir('results') time.sleep(INITTIME) total = 0 for turn in range(1, MAXTURNS+1): random.shuffle(Bot.botlist) nullbots = 0 for bot in Bot.botlist: bot.send('pick pixels') inmsg = bot.read(TIMELIMIT) newpixels = updateimage(image, inmsg, bot) total += len(newpixels) if newpixels: pixtext = ' '.join('%u,%u'%p for p in newpixels) msg = 'colour %s chose %s' % (bot.colstr, pixtext) for msgbot in Bot.botlist: msgbot.send(msg) else: nullbots += 1 if nullbots == len(Bot.botlist): break if turn % 100 == 0: print('Turn %s done %s pixels' % (turn, total)) image.save("results/"+BATTLE+str(turn//100).zfill(3)+'.png') for msgbot in Bot.botlist: msgbot.exit() counts = dict((c,f) for f,c in image.getcolors(W*H)) avg = 1.0 * sum(counts.values()) / len(Bot.botlist) for bot in Bot.botlist: score = 100 * counts[bot.colour] / avg print('Bot %s with colour %s scored %s' % (bot.prog, bot.colour, score)) image.save(BATTLE+'.png') ``` The arena results follow. The dfblob bot was given the red color for all arenas. ## Arena 1 : ``` Bot dfblob.py with colour (255, 0, 0) scored 163.75666666666666 Bot blob.py with colour (0, 255, 0) scored 14.896666666666667 ``` ![1](https://i.stack.imgur.com/fEkjC.gif) ## Arena 2 : ``` Bot blob.py with colour (0, 255, 0) scored 17.65563547726219 Bot dfblob.py with colour (255, 0, 0) scored 149.57006774236964 ``` ![2](https://i.stack.imgur.com/chdtj.gif) ## Arena 3 : ``` Bot blob.py with colour (0, 255, 0) scored 21.09758208782965 Bot dfblob.py with colour (255, 0, 0) scored 142.9732433108277 ``` ![3](https://i.stack.imgur.com/CDhBZ.gif) ## Arena 4 : ``` Bot blob.py with colour (0, 255, 0) scored 34.443810082244205 Bot dfblob.py with colour (255, 0, 0) scored 157.0684236785121 ``` ![4](https://i.stack.imgur.com/Go8kp.gif) [Answer] # Swallower # Language = Java # Score = ~~162.3289512601408075~~ 169.4020975612382575 Seeks enemies out and surrounds. ~~You might have to give it a longer time limit. Could be improved quite a bit. Sometimes prints invalid pixels.~~ *Update:* Surrounds much faster. Uses another thread to update priorities. Always returns within .1 seconds. Score should be impossible to beat without increasing `MAX_TURNS`. ``` import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; public class Swallower { static final byte MY_TYPE = 1; static final byte BLANK_TYPE = 0; static final byte NEUTRAL_TYPE = 2; static final byte ENEMY_TYPE = 3; private static final int WHITE = Color.WHITE.getRGB(); private static final int MAX_TIME = 50; private final int color; private final int N; private final int width; private final int height; private final BufferedReader in; Lock borderLock; private final PriorityBlockingQueue<Pixel> border; private final Set<Pixel> borderSet; private final Thread updater; Lock imageLock; volatile byte[][] image; Lock priorityLock; volatile int[][] priority; volatile boolean updating; volatile private boolean exit; class Pixel implements Comparable<Pixel> { int x; int y; public Pixel(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pixel o) { return priority() - o.priority(); } private int priority() { priorityLock.lock(); int p = priority[x][y]; priorityLock.unlock(); return p; } public byte type() { imageLock.lock(); byte i = image[x][y]; imageLock.unlock(); return i; } public boolean isBorder() { if (type() != BLANK_TYPE){ return false; } for (Pixel p : pixelsAround()){ if (p.type() == MY_TYPE){ return true; } } return false; } public void setType(byte newType) { imageLock.lock(); image[x][y] = newType; imageLock.unlock(); } public void setPriority(int newPriority) { borderLock.lock(); boolean contains = borderSet.remove(this); if (contains){ border.remove(this); } priorityLock.lock(); priority[x][y] = newPriority; priorityLock.unlock(); if (contains){ border.add(this); borderSet.add(this); } borderLock.unlock(); } public List<Pixel> pixelsAround() { List<Pixel> pixels = new ArrayList<>(4); if (x > 0){ pixels.add(new Pixel(x - 1, y)); } if (x < width - 1){ pixels.add(new Pixel(x + 1, y)); } if (y > 0){ pixels.add(new Pixel(x, y - 1)); } if (y < height - 1){ pixels.add(new Pixel(x, y + 1)); } return pixels; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pixel pixel = (Pixel) o; return x == pixel.x && y == pixel.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } public static void main(String[] args) throws IOException { BufferedImage image = ImageIO.read(new File(args[0])); int color = parseColorString(args[1]); int N = Integer.parseInt(args[2]); new Swallower(image, color, N).start(); } private void start() throws IOException { updater.start(); try { while (true) { String input = in.readLine(); if (input.equals("exit")) { exit = true; if (!updating) { updater.interrupt(); } return; } else if (input.startsWith("colour")) { updateImage(input); } else if (input.equals("pick pixels")) { if (updating) { try { synchronized (Thread.currentThread()){ Thread.currentThread().wait(MAX_TIME); } } catch (InterruptedException ignored) { } } for (int i = 0; i < N && !border.isEmpty(); i++) { borderLock.lock(); Pixel p = border.poll(); borderSet.remove(p); borderLock.unlock(); if (!p.isBorder()){ i--; continue; } updateImage(MY_TYPE, p); System.out.print(p.x + "," + p.y + " "); } System.out.println(); } } } catch (Throwable e){ exit = true; if (!updating){ updater.interrupt(); } throw e; } } private void updateImage(byte type, Pixel... pixels) { for (Pixel pixel : pixels){ pixel.setType(type); if (type == MY_TYPE){ pixel.setPriority(Integer.MAX_VALUE); } else { pixel.setPriority(0); } } for (Pixel pixel : pixels){ for (Pixel p : pixel.pixelsAround()){ if (p.type() == BLANK_TYPE){ addPixelToUpdate(p); } if (type == MY_TYPE && p.isBorder()){ borderLock.lock(); if (borderSet.add(p)){ border.add(p); } borderLock.unlock(); } } } } private synchronized void addPixelToUpdate(Pixel p) { if (pixelsToUpdateSet.add(p)) { pixelsToUpdate.add(p); if (!updating){ updater.interrupt(); } } } Queue<Pixel> pixelsToUpdate; Set<Pixel> pixelsToUpdateSet; private void update(){ while (true){ if (exit){ return; } if (pixelsToUpdate.isEmpty()){ try { updating = false; while (!exit) { synchronized (Thread.currentThread()) { Thread.currentThread().wait(); } } } catch (InterruptedException ignored){} continue; } updating = true; Pixel pixel = pixelsToUpdate.poll(); if (pixel.type() != BLANK_TYPE){ continue; } pixelsToUpdateSet.remove(pixel); updatePixel(pixel); } } private void updatePixel(Pixel pixel) { int originalPriority = pixel.priority(); int minPriority = Integer.MAX_VALUE; List<Pixel> pixelsAround = pixel.pixelsAround(); for (Pixel p : pixelsAround){ int priority = p.priority(); if (priority < minPriority){ minPriority = priority; } } if (minPriority >= originalPriority){ pixel.setPriority(Integer.MAX_VALUE); pixelsToUpdate.addAll(pixelsAround.stream().filter(p -> p.type() == 0 && p.priority() != Integer.MAX_VALUE).filter(pixelsToUpdateSet::add).collect(Collectors.toList())); } else { pixel.setPriority(minPriority + 1); for (Pixel p : pixelsAround){ if (p.type() == 0 && p.priority() > minPriority + 2){ if (pixelsToUpdateSet.add(p)){ pixelsToUpdate.add(p); } } } } } private void updateImage(String input) { String[] inputs = input.split("\\s"); int color = parseColorString(inputs[1]); byte type; if (color == this.color){ return; } else { type = ENEMY_TYPE; } Pixel[] pixels = new Pixel[inputs.length - 3]; for (int i = 0; i < inputs.length - 3; i++){ String[] coords = inputs[i + 3].split(","); pixels[i] = new Pixel(Integer.parseInt(coords[0]), Integer.parseInt(coords[1])); } updateImage(type, pixels); } private static int parseColorString(String input) { String[] colorString = input.split("[\\(\\),]"); return new Color(Integer.parseInt(colorString[1]), Integer.parseInt(colorString[2]), Integer.parseInt(colorString[3])).getRGB(); } private Swallower(BufferedImage image, int color, int N){ this.color = color; this.N = N; this.width = image.getWidth(); this.height = image.getHeight(); this.image = new byte[width][height]; this.priority = new int[width][height]; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ int pixelColor = image.getRGB(x,y); priority[x][y] = Integer.MAX_VALUE; if (pixelColor == WHITE){ this.image[x][y] = BLANK_TYPE; } else if (pixelColor == this.color){ this.image[x][y] = MY_TYPE; } else { this.image[x][y] = NEUTRAL_TYPE; } } } border = new PriorityBlockingQueue<>(); borderSet = Collections.synchronizedSet(new HashSet<>()); borderLock = new ReentrantLock(); priorityLock = new ReentrantLock(); imageLock = new ReentrantLock(); for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ Pixel pixel = new Pixel(x,y); if (pixel.type() == BLANK_TYPE){ if (pixel.isBorder()){ if (borderSet.add(pixel)){ border.add(pixel); } } } } } in = new BufferedReader(new InputStreamReader(System.in)); updating = false; updater = new Thread(this::update); pixelsToUpdate = new ConcurrentLinkedQueue<>(); pixelsToUpdateSet = Collections.synchronizedSet(new HashSet<>()); exit = false; } } ``` # How it works: This bot maintains a priority queue of pixels it can add. The priority of an enemy pixel is 0. The priority of a blank pixel is 1 greater than the lowest priority around it. All other pixels have a priority of Integer.MAX\_VALUE. The updater thread is constantly updating the priorities of the pixels. Every turn the lowest N pixels are popped off the priority queue. # Green Blob vs Red Swallower # Blob's Score = 1.680553372583887225 # Swallower's Score = 169.4020975612382575 # Arena 1: ``` Bot Blob.py with colour (0, 255, 0) scored 1.2183333333333333 Bot Swallower.class with colour (255, 0, 0) scored 177.435 ``` ![enter image description here](https://i.stack.imgur.com/Anog8.gif) # Arena 2: ``` Bot Swallower.class with colour (255, 0, 0) scored 149.57829253338517 Bot Blob.py with colour (0, 255, 0) scored 0.5159187091564356 ``` ![enter image description here](https://i.stack.imgur.com/oo5cB.gif) # Arena 3: ``` Bot Blob.py with colour (0, 255, 0) scored 0.727104853136361 Bot Swallower.class with colour (255, 0, 0) scored 163.343720545521 ``` ![enter image description here](https://i.stack.imgur.com/y8j9u.gif) # Arena 4: ``` Bot Swallower.class with colour (255, 0, 0) scored 187.25137716604686 Bot Blob.py with colour (0, 255, 0) scored 4.260856594709419 ``` ![enter image description here](https://i.stack.imgur.com/jF5Xs.gif) # Green Swallower vs. Red Blob # Blob's Score = 1.6852943642218457375 # Swallower's Score = 169.3923095387498625 # Arena 1: ``` Bot Blob.py with colour (255, 0, 0) scored 1.3166666666666667 Bot Swallower.class with colour (0, 255, 0) scored 177.33666666666667 ``` ![enter image description here](https://i.stack.imgur.com/p3sl7.gif) # Arena 2: ``` Bot Swallower.class with colour (0, 255, 0) scored 149.57829253338517 Bot Blob.py with colour (255, 0, 0) scored 0.49573058575466195 ``` ![enter image description here](https://i.stack.imgur.com/zbk1i.gif) # Arena 3: ``` Bot Swallower.class with colour (0, 255, 0) scored 163.14367053301788 Bot Blob.py with colour (255, 0, 0) scored 0.9271548656394868 ``` ![enter image description here](https://i.stack.imgur.com/gMc6r.gif) # Arena 4: ``` Bot Swallower.class with colour (0, 255, 0) scored 187.51060842192973 Bot Blob.py with colour (255, 0, 0) scored 4.0016253388265675 ``` ![enter image description here](https://i.stack.imgur.com/kcUjx.gif) # Red Swallower vs Green Depth First Blob # Swallower's Score = 157.0749775233111925 # Depth First Blob's Score = 18.192783547939744 # Arena 1: ``` Bot Swallower.class with colour (255, 0, 0) scored 173.52166666666668 Bot dfblob.py with colour (0, 255, 0) scored 5.131666666666667 ``` ![enter image description here](https://i.stack.imgur.com/MwDVU.gif) # Arena 2: ``` Bot dfblob.py with colour (0, 255, 0) scored 17.25635925887156 Bot Swallower.class with colour (255, 0, 0) scored 149.57829253338517 ``` ![enter image description here](https://i.stack.imgur.com/emoxv.gif) # Arena 3: ``` Bot Swallower.class with colour (255, 0, 0) scored 153.59801488833747 Bot dfblob.py with colour (0, 255, 0) scored 10.472810510319889 ``` ![enter image description here](https://i.stack.imgur.com/kFd0M.gif) # Arena 4: ``` Bot dfblob.py with colour (0, 255, 0) scored 39.91029775590086 Bot Swallower.class with colour (255, 0, 0) scored 151.60193600485545 ``` ![enter image description here](https://i.stack.imgur.com/KXJSn.gif) # Green Swallower vs Red Depth First Blob # Swallower's Score = 154.3368355651281075 # Depth First Blob's Score = 18.84463249420435425 # Arena 1: ``` Bot Swallower.class with colour (0, 255, 0) scored 165.295 Bot dfblob.py with colour (255, 0, 0) scored 13.358333333333333 ``` ![enter image description here](https://i.stack.imgur.com/nM5Lv.gif) # Arena 2: ``` Bot dfblob.py with colour (255, 0, 0) scored 8.91118721119768 Bot Swallower.class with colour (0, 255, 0) scored 149.57829253338517 ``` ![enter image description here](https://i.stack.imgur.com/BZsWM.gif) # Arena 3: ``` Bot Swallower.class with colour (0, 255, 0) scored 157.01136822667206 Bot dfblob.py with colour (255, 0, 0) scored 7.059457171985304 ``` ![enter image description here](https://i.stack.imgur.com/xpR7F.gif) # Arena 4: ``` Bot dfblob.py with colour (255, 0, 0) scored 46.0495522603011 Bot Swallower.class with colour (0, 255, 0) scored 145.4626815004552 ``` ![enter image description here](https://i.stack.imgur.com/mcaei.gif) # Green Blob vs Red Depth First Blob vs Blue Swallower: # Blob's Score = 6.347962032393275525 # Depth First Blob's Score = 27.34842554331698275 # Swallower's Score = 227.720728953415375 # Arena 1: ``` Bot Swallower.class with colour (0, 0, 255) scored 242.54 Bot Blob.py with colour (0, 255, 0) scored 1.21 Bot dfblob.py with colour (255, 0, 0) scored 24.3525 ``` ![enter image description here](https://i.stack.imgur.com/lyGVI.gif) # Arena 2: ``` Bot dfblob.py with colour (255, 0, 0) scored 17.828356088588478 Bot Blob.py with colour (0, 255, 0) scored 0.9252889892479551 Bot Swallower.class with colour (0, 0, 255) scored 224.36743880007776 ``` ![enter image description here](https://i.stack.imgur.com/vzcjH.gif) # Arena 3: ``` Bot dfblob.py with colour (255, 0, 0) scored 7.105141670032893 Bot Swallower.class with colour (0, 0, 255) scored 226.52057245080502 Bot Blob.py with colour (0, 255, 0) scored 12.621905476369092 ``` ![enter image description here](https://i.stack.imgur.com/Wg1GS.gif) # Arena 4: ``` Bot dfblob.py with colour (255, 0, 0) scored 60.10770441464656 Bot Blob.py with colour (0, 255, 0) scored 10.634653663956055 Bot Swallower.class with colour (0, 0, 255) scored 217.45490456277872 ``` ![enter image description here](https://i.stack.imgur.com/SHZlp.gif) Here is Sam Yonnou's judge with a few changes so that you specify the files and the command separately: ``` import sys, re, random, os, shutil, subprocess, datetime, time, signal, io from PIL import Image ORTH = ((-1,0), (1,0), (0,-1), (0,1)) def place(loc, colour): # if valid, place colour at loc and return True, else False if pix[loc] == (255,255,255): plist = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] if any(pix[p]==colour for p in plist if 0<=p[0]<W and 0<=p[1]<H): pix[loc] = colour return True return False def updateimage(image, msg, bot): if not re.match(r'(\s*\d+,\d+)*\s*', msg): return [] plist = [tuple(int(v) for v in pr.split(',')) for pr in msg.split()] plist = plist[:PIXELBATCH] return [p for p in plist if place(p, bot.colour)] class Bot: botlist = [] def __init__(self, progs, command=None, colour=None): self.prog = progs[0] self.botlist.append(self) self.colour = colour self.colstr = str(colour).replace(' ', '') self.faults = 0 self.env = 'env%u' % self.botlist.index(self) try: os.mkdir(self.env) except: pass for prog in progs: shutil.copy(prog, self.env) shutil.copy(imagename, self.env) os.chdir(self.env) args = command + [imagename, self.colstr, str(PIXELBATCH)] errorfile = 'err.log' with io.open(errorfile, 'wb') as errorlog: self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errorlog) os.chdir('..') def send(self, msg): if self.faults < FAULTLIMIT: self.proc.stdin.write((msg+'\n').encode('utf-8')) self.proc.stdin.flush() def read(self, timelimit): if self.faults < FAULTLIMIT: start = time.time() inline = self.proc.stdout.readline().decode('utf-8') if time.time() - start > timelimit: self.faults += 1 inline = '' return inline.strip() def exit(self): self.send('exit') from cfg import * for i, (progs, command) in enumerate(botspec): Bot(progs, command, colourspec[i]) image = Image.open(imagename) pix = image.load() W,H = image.size resultdirectory = 'results of ' + BATTLE os.mkdir(resultdirectory) time.sleep(INITTIME) total = 0 image.save(resultdirectory+'/'+'result000.png') for turn in range(1, MAXTURNS+1): random.shuffle(Bot.botlist) nullbots = 0 for bot in Bot.botlist: bot.send('pick pixels') inmsg = bot.read(TIMELIMIT) newpixels = updateimage(image, inmsg, bot) total += len(newpixels) if newpixels: pixtext = ' '.join('%u,%u'%p for p in newpixels) msg = 'colour %s chose %s' % (bot.colstr, pixtext) for msgbot in Bot.botlist: msgbot.send(msg) else: nullbots += 1 if nullbots == len(Bot.botlist): break if turn % 100 == 0: print('Turn %s done %s pixels' % (turn, total)) image.save(resultdirectory+'/result'+str(turn//100).zfill(3)+'.png') image.save(resultdirectory+'/result999.png') for msgbot in Bot.botlist: msgbot.exit() resultfile = io.open(resultdirectory+'/result.txt','w') counts = dict((c,f) for f,c in image.getcolors(W*H)) avg = 1.0 * sum(counts.values()) / len(Bot.botlist) for bot in Bot.botlist: score = 100 * counts[bot.colour] / avg print('Bot %s with colour %s scored %s' % (bot.prog, bot.colour, score)) print('Bot %s with colour %s scored %s' % (bot.prog, bot.colour, score), file=resultfile) image.save(BATTLE+'.png') ``` Example cfg: ``` BATTLE = 'Green DepthFirstBlob vs Red Swallower @ arena1' MAXTURNS = 20000 PIXELBATCH = 10 INITTIME = 2.0 TIMELIMIT = .1 FAULTLIMIT = 5 imagename = 'arena1.png' colourspec = (0,255,0), (255,0,0) botspec = [ (['DepthFirstBlob.py'], ['python', 'DepthFirstBlob.py']), (['Swallower.class','Swallower$Pixel.class'], ['java', 'Swallower']), ] ``` *Note:* Anyone that manages to swallow the Swallower get's a bounty of 100 reputation. Please post in comments below if you succeed at this. [Answer] # ColorFighter - C++ - eats a couple of swallowers for breakfast **EDIT** * cleaned up the code * added a simple but effective optimization * added some GIF animations ## God I hate snakes (just pretend they are spiders, Indy) Actually I love Python. I wish I were less of a lazy boy and started to learn it properly, that's all. All this being said, I had to struggle with the 64 bits version of this snake to get the Judge working. Making PIL work with the 64 bits version of Python under Win7 requires more patience than I was ready to devote to this challenge, so in the end I switched (painfully) to the Win32 version. Also, the Judge tends to crash badly when a bot is too slow to respond. Being no Python savvy, I did not fix it, but it has to do with reading an empty answer after a timeout on stdin. A minor improvement would be to put stderr output to a file for each bot. That would ease tracing for post-mortem debugging. Except for these minor problems, I found the Judge very simple and pleasant to use. Kudos for yet another inventive and fun challenge. ## The code ``` #define _CRT_SECURE_NO_WARNINGS // prevents Microsoft from croaking about the safety of scanf. Since every rabid Russian hacker and his dog are welcome to try and overflow my buffers, I could not care less. #include "lodepng.h" #include <vector> #include <deque> #include <iostream> #include <sstream> #include <cassert> // paranoid android #include <cstdint> // fixed size types #include <algorithm> // min max using namespace std; // ============================================================================ // The less painful way I found to teach C++ how to handle png images // ============================================================================ typedef unsigned tRGB; #define RGB(r,g,b) (((r) << 16) | ((g) << 8) | (b)) class tRawImage { public: unsigned w, h; tRawImage(unsigned w=0, unsigned h=0) : w(w), h(h), data(w*h * 4, 0) {} void read(const char* filename) { unsigned res = lodepng::decode(data, w, h, filename); assert(!res); } void write(const char * filename) { std::vector<unsigned char> png; unsigned res = lodepng::encode(png, data, w, h, LCT_RGBA); assert(!res); lodepng::save_file(png, filename); } tRGB get_pixel(int x, int y) const { size_t base = raw_index(x,y); return RGB(data[base], data[base + 1], data[base + 2]); } void set_pixel(int x, int y, tRGB color) { size_t base = raw_index(x, y); data[base+0] = (color >> 16) & 0xFF; data[base+1] = (color >> 8) & 0xFF; data[base+2] = (color >> 0) & 0xFF; data[base+3] = 0xFF; // alpha } private: vector<unsigned char> data; void bound_check(unsigned x, unsigned y) const { assert(x < w && y < h); } size_t raw_index(unsigned x, unsigned y) const { bound_check(x, y); return 4 * (y * w + x); } }; // ============================================================================ // coordinates // ============================================================================ typedef int16_t tCoord; struct tPoint { tCoord x, y; tPoint operator+ (const tPoint & p) const { return { x + p.x, y + p.y }; } }; typedef deque<tPoint> tPointList; // ============================================================================ // command line and input parsing // (in a nice airtight bag to contain the stench of C++ string handling) // ============================================================================ enum tCommand { c_quit, c_update, c_play, }; class tParser { public: tRGB color; tPointList points; tRGB read_color(const char * s) { int r, g, b; sscanf(s, "(%d,%d,%d)", &r, &g, &b); return RGB(r, g, b); } tCommand command(void) { string line; getline(cin, line); string cmd = get_token(line); points.clear(); if (cmd == "exit") return c_quit; if (cmd == "pick") return c_play; // even more convoluted and ugly than the LEFT$s and RIGHT$s of Apple ][ basic... if (cmd != "colour") { cerr << "unknown command '" << cmd << "'\n"; exit(0); } assert(cmd == "colour"); color = read_color(get_token(line).c_str()); get_token(line); // skip "chose" while (line != "") { string coords = get_token(line); int x = atoi(get_token(coords, ',').c_str()); int y = atoi(coords.c_str()); points.push_back({ x, y }); } return c_update; } private: // even more verbose and inefficient than setting up an ADA rendezvous... string get_token(string& s, char delimiter = ' ') { size_t pos = 0; string token; if ((pos = s.find(delimiter)) != string::npos) { token = s.substr(0, pos); s.erase(0, pos + 1); return token; } token = s; s.clear(); return token; } }; // ============================================================================ // pathing // ============================================================================ class tPather { public: tPather(tRawImage image, tRGB own_color) : arena(image) , w(image.w) , h(image.h) , own_color(own_color) , enemy_threat(false) { // extract colored pixels and own color areas tPointList own_pixels; color_plane[neutral].resize(w*h, false); color_plane[enemies].resize(w*h, false); for (size_t x = 0; x != w; x++) for (size_t y = 0; y != h; y++) { tRGB color = image.get_pixel(x, y); if (color == col_white) continue; plane_set(neutral, x, y); if (color == own_color) own_pixels.push_back({ x, y }); // fill the frontier with all points of our color } // compute initial frontier for (tPoint pixel : own_pixels) for (tPoint n : neighbour) { tPoint pos = pixel + n; if (!in_picture(pos)) continue; if (image.get_pixel(pos.x, pos.y) == col_white) { frontier.push_back(pixel); break; } } } tPointList search(size_t pixels_required) { // flood fill the arena, starting from our current frontier tPointList result; tPlane closed; static tCandidate pool[max_size*max_size]; // fastest possible garbage collection size_t alloc; static tCandidate* border[max_size*max_size]; // a FIFO that beats a deque anytime size_t head, tail; static vector<tDistance>distance(w*h); // distance map to be flooded size_t filling_pixels = 0; // end of game optimization get_more_results: // ready the distance map for filling distance.assign(w*h, distance_max); // seed our flood fill with the frontier alloc = head = tail = 0; for (tPoint pos : frontier) { border[tail++] = new (&pool[alloc++]) tCandidate (pos); } // set already explored points closed = color_plane[neutral]; // that's one huge copy // add current result for (tPoint pos : result) { border[tail++] = new (&pool[alloc++]) tCandidate(pos); closed[raw_index(pos)] = true; } // let's floooooood!!!! while (tail > head && pixels_required > filling_pixels) { tCandidate& candidate = *border[head++]; tDistance dist = candidate.distance; distance[raw_index(candidate.pos)] = dist++; for (tPoint n : neighbour) { tPoint pos = candidate.pos + n; if (!in_picture (pos)) continue; size_t index = raw_index(pos); if (closed[index]) continue; if (color_plane[enemies][index]) { if (dist == (distance_initial + 1)) continue; // already near an enemy pixel // reached the nearest enemy pixel static tPoint trail[max_size * max_size / 2]; // dimensioned as a 1 pixel wide spiral across the whole map size_t trail_size = 0; // walk back toward the frontier tPoint walker = candidate.pos; tDistance cur_d = dist; while (cur_d > distance_initial) { trail[trail_size++] = walker; tPoint next_n; for (tPoint n : neighbour) { tPoint next = walker + n; if (!in_picture(next)) continue; tDistance prev_d = distance[raw_index(next)]; if (prev_d < cur_d) { cur_d = prev_d; next_n = n; } } walker = walker + next_n; } // collect our precious new pixels if (trail_size > 0) { while (trail_size > 0) { if (pixels_required-- == 0) return result; // ;!; <-- BRUTAL EXIT tPoint pos = trail[--trail_size]; result.push_back (pos); } goto get_more_results; // I could have done a loop, but I did not bother to. Booooh!!! } continue; } // on to the next neighbour closed[index] = true; border[tail++] = new (&pool[alloc++]) tCandidate(pos, dist); if (!enemy_threat) filling_pixels++; } } // if all enemies have been surrounded, top up result with the first points of our flood fill if (enemy_threat) enemy_threat = pixels_required == 0; tPathIndex i = frontier.size() + result.size(); while (pixels_required--) result.push_back(pool[i++].pos); return result; } // tidy up our map and frontier while other bots are thinking void validate(tPointList moves) { // report new points for (tPoint pos : moves) { frontier.push_back(pos); color_plane[neutral][raw_index(pos)] = true; } // remove surrounded points from frontier for (auto it = frontier.begin(); it != frontier.end();) { bool in_frontier = false; for (tPoint n : neighbour) { tPoint pos = *it + n; if (!in_picture(pos)) continue; if (!(color_plane[neutral][raw_index(pos)] || color_plane[enemies][raw_index(pos)])) { in_frontier = true; break; } } if (!in_frontier) it = frontier.erase(it); else ++it; // the magic way of deleting an element without wrecking your iterator } } // handle enemy move notifications void update(tRGB color, tPointList points) { assert(color != own_color); // plot enemy moves enemy_threat = true; for (tPoint p : points) plane_set(enemies, p); // important optimization here : /* * Stop 1 pixel away from the enemy to avoid wasting moves in dogfights. * Better let the enemy gain a few more pixels inside the surrounded region * and use our precious moves to get closer to the next threat. */ for (tPoint p : points) for (tPoint n : neighbour) plane_set(enemies, p+n); // if a new enemy is detected, gather its initial pixels for (tRGB enemy : known_enemies) if (color == enemy) return; known_enemies.push_back(color); tPointList start_areas = scan_color(color); for (tPoint p : start_areas) plane_set(enemies, p); } private: typedef uint16_t tPathIndex; typedef uint16_t tDistance; static const tDistance distance_max = 0xFFFF; static const tDistance distance_initial = 0; struct tCandidate { tPoint pos; tDistance distance; tCandidate(){} // must avoid doing anything in this constructor, or pathing will slow to a crawl tCandidate(tPoint pos, tDistance distance = distance_initial) : pos(pos), distance(distance) {} }; // neighbourhood of a pixel static const tPoint neighbour[4]; // dimensions tCoord w, h; static const size_t max_size = 1000; // colors lookup const tRGB col_white = RGB(0xFF, 0xFF, 0xFF); const tRGB col_black = RGB(0x00, 0x00, 0x00); tRGB own_color; const tRawImage arena; tPointList scan_color(tRGB color) { tPointList res; for (size_t x = 0; x != w; x++) for (size_t y = 0; y != h; y++) { if (arena.get_pixel(x, y) == color) res.push_back({ x, y }); } return res; } // color planes typedef vector<bool> tPlane; tPlane color_plane[2]; const size_t neutral = 0; const size_t enemies = 1; bool plane_get(size_t player, tPoint p) { return plane_get(player, p.x, p.y); } bool plane_get(size_t player, size_t x, size_t y) { return in_picture(x, y) ? color_plane[player][raw_index(x, y)] : false; } void plane_set(size_t player, tPoint p) { plane_set(player, p.x, p.y); } void plane_set(size_t player, size_t x, size_t y) { if (in_picture(x, y)) color_plane[player][raw_index(x, y)] = true; } bool in_picture(tPoint p) { return in_picture(p.x, p.y); } bool in_picture(int x, int y) { return x >= 0 && x < w && y >= 0 && y < h; } size_t raw_index(tPoint p) { return raw_index(p.x, p.y); } size_t raw_index(size_t x, size_t y) { return y*w + x; } // frontier tPointList frontier; // register enemies when they show up vector<tRGB>known_enemies; // end of game optimization bool enemy_threat; }; // small neighbourhood const tPoint tPather::neighbour[4] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; // ============================================================================ // main class // ============================================================================ class tGame { public: tGame(tRawImage image, tRGB color, size_t num_pixels) : own_color(color) , response_len(num_pixels) , pather(image, color) {} void main_loop(void) { // grab an initial answer in case we're playing first tPointList moves = pather.search(response_len); for (;;) { ostringstream answer; size_t num_points; tPointList played; switch (parser.command()) { case c_quit: return; case c_play: // play as many pixels as possible if (moves.size() < response_len) moves = pather.search(response_len); num_points = min(moves.size(), response_len); for (size_t i = 0; i != num_points; i++) { answer << moves[0].x << ',' << moves[0].y; if (i != num_points - 1) answer << ' '; // STL had more important things to do these last 30 years than implement an implode/explode feature, but you can write your own custom version with exception safety and in-place construction. It's a bit of work, but thanks to C++ inherent genericity you will be able to extend it to giraffes and hippos with a very manageable amount of code refactoring. It's not anyone's language, your C++, eh. Just try to implode hippos in Python. Hah! played.push_back(moves[0]); moves.pop_front(); } cout << answer.str() << '\n'; // now that we managed to print a list of points to stdout, we just need to cleanup the mess pather.validate(played); break; case c_update: if (parser.color == own_color) continue; // hopefully we kept track of these already pather.update(parser.color, parser.points); moves = pather.search(response_len); // get cracking break; } } } private: tParser parser; tRGB own_color; size_t response_len; tPather pather; }; void main(int argc, char * argv[]) { // process command line tRawImage raw_image; raw_image.read (argv[1]); tRGB my_color = tParser().read_color(argv[2]); int num_pixels = atoi (argv[3]); // init and run tGame game (raw_image, my_color, num_pixels); game.main_loop(); } ``` ## Building the executable I used **[LODEpng.cpp](https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp)** and **[LODEpng.h](https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h)** to read png images. About the easiest way I found to teach this retarded C++ language how to read a picture without having to build half a dozen libraries. Just compile & link LODEpng.cpp along with the main and Bob's your uncle. I compiled with MSVC2013, but since I used only a few STL basic containers (deque and vectors), it *might* work with gcc (if you're lucky). If it doesn't, I *might* try a MinGW build, but frankly I'm getting tired of C++ portability issues. I did quite a lot of portable C/C++ in my days (on exotic compilers for various 8 to 32 bits processors as well as SunOS, Windows from 3.11 up to Vista and Linux from its infancy to Ubuntu cooing zebra or whatever, so I think I have a pretty good idea of what portability means), but at the time it did not require to memorize (or discover) the innumerable discrepancies between the GNU and Microsoft interpretations of the cryptic and bloated specs of the STL monster. ## Results against Swallower ![arena1](https://i.stack.imgur.com/HJy1q.gif) ![arena2](https://i.stack.imgur.com/jEdZL.gif) ![arena3](https://i.stack.imgur.com/ztCsF.gif) ![arena4](https://i.stack.imgur.com/RcRzi.gif) ## How it works At the core, this is a simple brute-force floodfill pathing. The frontier of the player's color (i.e. the pixels that have at least one white neighbour) is used as a seed to perform the classic distance-flooding algorithm. When a point reaches the vincinity of an enemy color, a backward path is computed to produce a string of pixels moving toward the nearest enemy spot. The process is repeated until enough points have been gathered for a response of the desired length. This repetition is obscenely expensive, especially when fighting near the enemy. Each time a string of pixels leading from the frontier to an enemy pixel has been found (and we need more points to complete the answer), the flood fill is redone from start, with the new path added to the frontier. It means you could have to do 5 flood fills or more to get an 10 pixels answer. If no more enemy pixels are reachable, arbitraty neighbours of the frontier pixels are selected. The algorithm devolves to a rather inefficient flood fill, but this only happens after the outcome of the game has been decided (i.e. there is no more neutral territory to fight for). I did optimize it so that the Judge do not spend ages filling up the map once the competition has been dealt with. In its current state, the execution time is neglectible compared with the Judge itself. Since enemy colors are not known at start, the initial arena image is kept in store in order to copy the enemy's starting areas when it makes its first move. If the code plays first, it will simply flood fill a few arbitrary pixels. This makes the algorithm capable of fighting an arbitrary number of adversaries, and even possibly new adversaries arriving at a random point in time, or colors appearing without a starting area (though this has absolutely no practical use). Enemy handling on a color-per-color basis would also allow to have two instances of the bot cooperate (using pixel coordinates to pass a secret recognition sign). Sounds like fun, I'll probably try that :). Computation-heavy pathing is done as soon as new data are available (after a move notification), and some optimizations (the frontier update) are done just after a response has been given (to do as much computation as possible during the other bots turns). Here again, there could be ways of doing more subtle things if there were more than 1 adversary (like aborting a computation if new data become available), but at any rate I fail to see where multitasking is needed, as long as the algorithm is able to work on full load. ## Performance issues All this cannot work without fast data access (and more computing power than the whole Appolo program, i.e. your average PC when used to do more than post a few tweets). The speed is heavily compiler-dependent. Usually GNU beats Microsoft by a 30% margin (that's the magic number I noticed on 3 other pathing-related code challenges), but this mileage may vary of course. The code in its current state barely breaks a sweat on arena 4. Windows perfmeter reports about 4 to 7 % CPU usage, so it should be able to cope with a 1000x1000 map within the 100ms response time limit. At the heart of about every pathing algorithm lies a FIFO (possibly proritized, though not in that case), which in turn requires fast element allocation. Since the OP obligingly set a limit to the arena size, I did some maths and saw that fixed data structures dimensioned to max (i.e. 1.000.000 pixels) would not consume more than a couple dozen megabytes, which your average PC eats for breakfast. Indeed under Win7 and compiled with MSVC 2013, the code consumes about 14Mb on arena 4, while Swallower's two threads are using more than 20Mb. I started with STL containers for easier prototyping, but STL made the code even less readable, since I had no desire to create a class to encapsulate each and every bit of data to hide the obfuscation away (whether that is due to my own inabilities to cope with the STL is left to the appreciation of the reader). Regardless, the result was so atrociously slow that at first I thought I was building a debug version by mistake. I reckon this is partly due to the incredibly poor Microsoft implementation of the STL (where, for instance, vectors and bitsets do bound checks or other crypic operations on operator[], in direct violation of the spec), and partly to the STL design itself. I could cope with the atrocious syntax and portability (i.e. Microsoft vs GNU) issues if the performances were there, but this is certainly not the case. For instance, `deque` is inherently slow, because it shuffles lots of bookkeeping data around waiting for the occasion to do its super smart resizing, about which I could not care less. Sure I could have implemented a custom allocator and whaterver other custom template bits, but a custom allocator alone costs a few hundred lines of code and the better part of a day to test, what with the dozen of interfaces it has to implement, while a handmade equivalent structure is about zero lines of code (albeit more dangerous, but the algorithm would not have worked if I did not know - or think I knew - what I was doing anyway). So eventually I kept the STL containers in non-critical parts of the code, and built my own brutal allocator and FIFO with two circa 1970 arrays and three unsigned shorts. ## Swallowing the swallower As its author confirmed, the erratic patterns of the Swallower are caused by lag between enemy moves notifications and updates from the pathing thread. The system perfmeter shows clearly the pathing thread consuming 100% CPU all the time, and the jagged patterns tend to appear when the focus of the fight shifts to a new area. This is also quite apparent with the animations. ## A simple but effective optimization After looking at the epic dogfights between Swallower and my fighter, I remembered an old saying from the game of Go: defend close up, but attack from afar. There is wisdom in that. If you try to stick to your adversary too much, you will waste precious moves trying to block each possible path. On the contrary, if you stay just one pixel away, you will likely avoid filling small gaps that would gain very little, and use your moves to counter more important threats. To implement this idea, I simply extended the moves of an enemy (marking the 4 neighbours of each move as an enemy pixel). This stops the pathing algorithm one pixel away from the enemy's border, allowing my fighter to work its way around an adversary without getting caught in too many dogfights. You can see the improvement (though all runs are not as successful, you can notice the much smoother outlines): ![before](https://i.stack.imgur.com/39d0t.png) ![after](https://i.stack.imgur.com/HHzRc.png) [Answer] # Random, Language = java, Score = 0.43012126100275 This program randomly puts pixels on the screen. Some (if not all) of the pixels will not be valid. On a side note, it should be difficult to make a faster program than this one. ``` import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; public class Random { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static int n; static int height; static int width; public static void main(String[] args) throws Exception{ BufferedImage image = ImageIO.read(new File(args[0])); height = image.getHeight(); width = image.getWidth(); n = Integer.parseInt(args[2]); while (true){ String input = in.readLine(); if (input.equals("exit")){ return; } if (!input.equals("pick pixels")){ continue; } for (int i = 0; i < n; i++){ System.out.print((int) (Math.random() * width) + ","); System.out.print((int) (Math.random() * height) + " "); } System.out.println(); } } } ``` Arena 1: ![1](https://i.stack.imgur.com/AHuC6.png) Arena 2: ![2](https://i.stack.imgur.com/sCMW1.png) Arena 3: ![3](https://i.stack.imgur.com/GGTEv.png) Arena 4: ![4](https://i.stack.imgur.com/fdyGr.png) ]
[Question] [ Credits for the challenge idea go to @AndrewPiliser. His original proposal in [the sandbox](https://codegolf.meta.stackexchange.com/questions/2140/) was abandoned and since he has not been active here for several months, I have taken over the challenge. **[Balanced ternary](http://en.wikipedia.org/wiki/Balanced_ternary)** is a non-standard numeral system. It is like ternary in that the digits increase in value by a factor of 3 as you go further to the left - so `100` is `9` and `1001` is 28. However, instead of having values of 0, 1 and 2, **the digits have values of -1, 0, and 1**. (You can still use this to express any integer.) For this challenge, the digit meaning `+1` will be written as `+`, `-1` will be written as `-`, and `0` is just `0`. Balanced ternary does not use the `-` symbol in front of numbers to negate them like other numeral systems do - see examples. **Your task is to write a complete program which takes a 32-bit decimal signed integer as input and converts it to balanced ternary.** No built-in base conversion functions of any sort are allowed (Mathematica probably has one...). Input can be on standard input, command-line arguments, etc. Leading zeroes may be present in input but not in output, unless the input is `0`, in which case the output should also be `0`. ## Examples These are conversions from balanced ternary to decimal; you will have to convert the other way. ``` +0- = 1*3^2 + 0*3^1 + -1*3^0 = 9 + 0 + -1 = 8 +-0+ = 1*3^3 + -1*3^2 + 0*3^1 + 1*3^0 = 27 + -9 + 0 + 1 = 19 -+++ = -1*3^3 + 1*3^2 + 1*3^1 + 1*3^0 = -27 + 9 + 3 + 1 = -14 ``` [Answer] ## Python 2: 58 chars ``` n=input() s="" while n:s="0+-"[n%3]+s;n=-~n/3 print s or 0 ``` Generates the balanced ternary digit-by-digit from the end. The last digit is given by the residue `n%3` being `-1`,`0`, or `+1`. We then remove the last digit and divide by 3 using Python's floor-divide `n=(n+1)/3`. Then, we proceed recursively with the new last digit until the number is 0. A special case is needed for the input `0` to give `0` rather than the empty string. --- The specs don't allow this, but if one could write a function instead of a program and output the empty string for 0, a 40 char solution would be possible. ``` g=lambda n:n and g(-~n/3)+"0+-"[n%3]or"" ``` [Answer] # CJam, 24 bytes I came up with this independently and I think this is, most probably, the only way to handle this. ``` li{_3%"0+-"=\_g+3/}h;]W% ``` Algorithmically, its similar to xnor's answer. [Try it online here](http://cjam.aditsu.net/) **How it works**: ``` li{ }h "Read input, convert to integer and run the code block" "until stack has 0 on top"; _3% "Copy and get modulus 3"; "0+-"= "Take the correct character based on the above modulus"; \_g+ "Swap, copy and take signum of the number and add" "that to it, incrementing the number if positive," "decrementing otherwise"; 3/ "Integer divide by 3 and continue until 0"; ;] "Pop the residual 0 and wrap everything in array"; W% "Reverse to get in binary format (right handed)"; ``` [Answer] # JavaScript (E6) 68 A complete program, as requested, with I/O via popup. The core is the R function, 49 bytes. Not so different from the other recursive solutions, I guess. Taking advantage of the automatic conversion between string and number to avoid a special case for "0" ``` alert((R=(n,d=(n%3+3)%3)=>n?R((n-d)/3+(d>1))+'0+-'[d]:'')(prompt())) ``` **Test** in FireFox/FireBug console, using just the R function ``` ['0','8','19','-14','414'].map(x =>x +': '+R(x)) ``` *Output* ``` ["0: 0", "8: +0-", "19: +-0+", "-14: -+++", "414: +--0+00"] ``` [Answer] # Pyth, ~~71~~ ~~24~~ 23 ``` L?+y/hb3@"0+-"%b3bk|yQ0 ``` This is a recursive solution, based on @xnor's 40 character recursive function. `y` constructs the baanced ternary of the input, by finding the last digit using the mod 3 index, and then uses the fact that the rest of the digits are equal to the balanced ternary for (n+1)/3, using floored division. Then, it calls the function, returning the result, or 0 if the input is 0. [Try it here.](http://isaacg.scripts.mit.edu/pyth/index.py) [Answer] # Mathematica, 54 characters Similar to xnor's recursion Unicode symbols are used to replace `Floor`,`Part`,`!=` ``` If[(t=⌊(#+1)/3⌋)≠0,#0@t,""]<>{"0","+","-"}〚#~Mod~3+1〛& ``` ## Output Stored as `f` for brevity and written without unicode incase you can't view ``` f=If[(t=Floor[(#+1)/3])!=0,#0@t,""]<>{"0","+","-"}[[#~Mod~3+1]]& f /@ {8, 19, -14, 414} // Column +0- +-0+ -+++ +--0+00 ``` [Answer] # Mathematica - ~~157~~ ~~154~~ ~~146~~ 128 The golfed version: ``` f=(s="";n=#;i=Ceiling@Log[3,Abs@#]~Max~0;While[i>=0,s=s<>Which[n>=(1+3^i)/2,n-=3^i;"+",n>-(1+3^i)/2,"0",1>0,n+=3^i;"-"];i--];s)& ``` And with indentation for legibility: ``` f = (s = ""; n = #; i = Ceiling@Log[3, Abs@#]~Max~0; While[i >= 0, s = s<>Which[ n >= (1 + 3^i)/2, n -= 3^i; "+", n > -(1 + 3^i)/2, "0", 1 > 0, n += 3^i; "-" ]; i--]; s)& ``` Usage: ``` f[414] ``` Output: ``` +--0+00 ``` Many thanks to Martin Büttner in reducing the number of characters. [Answer] # GNU sed, 236 bytes ``` /^0/bV : s/\b9/;8/ s/\b8/;7/ s/\b7/;6/ s/\b6/;5/ s/\b5/;4/ s/\b4/;3/ s/\b3/;2/ s/\b2/;1/ s/\b1/;0/ s/\b0// /[^;-]/s/;/&&&&&&&&&&/g t y/;/1/ :V s/111/3/g s/3\b/3:/ s/311/33!/ s/31/3+/ y/3/1/ tV s/1/+/ y/1:/!0/ /-/{s/-// y/+!/!+/ } y/!/-/ ``` [Try it online!](http://sed.tryitonline.net/#code=L14wL2JWCjoKcy9cYjkvOzgvCnMvXGI4Lzs3LwpzL1xiNy87Ni8Kcy9cYjYvOzUvCnMvXGI1Lzs0LwpzL1xiNC87My8Kcy9cYjMvOzIvCnMvXGIyLzsxLwpzL1xiMS87MC8Kcy9cYjAvLwovW147LV0vcy87LyYmJiYmJiYmJiYvZwp0CnkvOy8xLwo6VgpzLzExMS8zL2cKcy8zXGIvMzovCnMvMzExLzMzIS8Kcy8zMS8zKy8KeS8zLzEvCnRWCnMvMS8rLwp5LzE6LyEwLwovLS97cy8tLy8KeS8rIS8hKy8KfQp5LyEvLS8&input=OAoxOQotMTQ) # Explanation The first half of the code (less the first line) translates decimal to unary and comes straight from "[Tips for golfing in sed](https://codegolf.stackexchange.com/questions/51323/tips-for-golfing-in-sed/51329#51329)." Then it translates unary to balanced ternary one trit at a time, which I'll demonstrate by working an example manually. Before the final output, the ternary digits `-`, `0`, and `+` are represented by `!`, `:`, and `+`, respectively. For an interesting result, we start with `-48`, which has been converted to unary (with the `-` intact). To calculate the first (right-most) trit, we have to calculate the remainder of 48÷3. We can do this by replacing the `111`s with `3`s: ``` -111111111111111111111111111111111111111111111111 │ s/111/3/g # => -3333333333333333 ``` 48÷3 has no remainder, so no `1`s remain, and we know our first trit is `:` (for 0), so we replace it: ``` -3333333333333333 │ s/3\b/3:/ # => -3333333333333333: ``` Now we have our "ones place," so we know the remaining `3`s represent the threes place. To keep the math working we have to divide them by 3, i.e. replace them with `1`s: ``` -3333333333333333: │ y/3/1/ # => -1111111111111111: ``` Let's double-check our math: We have 16 (unary `1111111111111111`) in the threes place and zero (`:`) in the ones place. That's 3✕16 + 1✕0 = 48. So far so good. Now we start again. Replace `111`s with `3`s: ``` -1111111111111111: │ s/111/3/g # => -333331: ``` This time our remainder is `1`, so we put `+` in the threes place and replace the remaining `3`s with `1`s: ``` -333331: │ s/31/3+/; y/3/1/ # => -11111+: ``` Sanity check time: We have a 5 (unary `11111`) in the nines place, 1 (`+`) in the threes place, and 0 (`:`) in the ones place: 9✕5 + 3✕1 + 1✕0 = 48. Great! Again we replace the `111`s with `3`s: ``` -11111+: │ s/111/3/g # => -311+: ``` This time our remainder is 2 (`11`). That takes up two trits (`+!`), which means we have a carry. Just like in decimal arithmetic that means we take the rightmost digit and add the rest to the column to the left. In our system, that means we put `!` in the nines place and add another three to its left, then replace all of the `3`s with `1`s to represent the 27s place: ``` -311+: │ s/311/33!/; y/3/1/ # => -11!+: ``` Now we don't have any 3s left, so we can replace any remaining unary digits with their corresponding trits. Two (`11`) is `+!`: ``` -11!+: │ s/11/+!/ # => -+!!+: ``` In the actual code this is done in two steps, `s/1/+/` and `y/1:/!0/`, to save bytes. The second step also replaces `:`s with `0`s, so it actually does this: ``` -11!+: │ s/1/+/; y/1:/+0/ # => -+!!+0 ``` Now we check if we have a negative number. We do, so we have to get rid of the sign and then invert each trit: ``` -+!!+0 │ /-/ { s/-//; y/+!/!+/; } # => !++!0 ``` Finally, we replace `!`s with `-`s: ``` !++!0 │ y/!/-/ # => -++-0 ``` That's it! [Answer] # Clojure, 172 bytes `(let[s "0+-"](loop[x(Integer.(read-line))xs '()](if(= 0 x)(println(apply str xs))(let[y(mod x 3)x(int (Math/floor(/ x 3.0)))](recur(if(= y 2)(inc x)x)(cons(get s y)xs))))))` Readable version: ``` (let [s "0+-"] (loop [x (Integer. (read-line)) xs '()] (if (= 0 x) (apply str xs) (let [y (mod x 3) x (int (Math/floor (/ x 3.0)))] (recur (if (= y 2) (inc x) x) (cons (get s y) xs)))))) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ë1·âΓM¿├>Ö≥Er☺à┤3 ``` [Run and debug it](https://staxlang.xyz/#p=8931fa83e24da8c33e99f245720185b433&i=8%0A19%0A-14&a=1&m=2) Shortest answer so far, but should be easily beaten by some golfing languages. The algorithm is the same as @xnor's Python answer. ASCII equivalent: ``` z{"0+-";3%@+,^3/~;wr ``` [Answer] # JavaScript 108 102 (ES6, no recursive calls) ``` t=a=>{v="";if(0==a)v="0";else for(a=(N=0>a)?-a:a;a;)v="0+-"[r=(a%3+3)%3]+v,2==r&&++a,a=a/3|0;return v} ``` Original entry at 108 ``` t=a=>{v="";if(0==a)v="0";else for(a=(N=0>a)?-a:a;a;)v=(N?"0-+":"0+-")[r=a%3]+v,2==r&&++a,a/=3,a|=0;return v} ``` Not as fancy as @edc65's answer... I'd appreciate any help reducing this further... [Answer] # Clojure, 242 bytes ``` #(clojure.string/join""(map{1"+"0"0"-1"-"}(loop[x(vec(map read-string(clojure.string/split(Integer/toString % 3)#"")))](let[y(.indexOf x 2)](if(< y 0)x(let[z(assoc x y -1)](recur(if(= y 0)(vec(cons 1 z))(assoc z(dec y)(inc(x(dec y)))))))))))) ``` Is this the longest Clojure answer so far? Ungolfed (with comments): ``` (use '[clojure.string :only (split join)]);' (Stupid highlighter) ; Import functions (defn ternary [n] (join "" ; Joins it all together (map {1 "+" 0 "0" -1 "-"} ; Converts 1 to +, 0 to 0, -1 to - (loop [x (vec (map read-string (split (Integer/toString n 3) #"")))] ; The above line converts a base 10 number into base 3, ; and splits the digits into a list (8 -> [2 2]) (let [y (.indexOf x 2)] ; The first occurrence of 2 in the list, if there is no 2, ; the .indexOf function returns -1 (if (< y 0) x ; Is there a 2? If not, then output the list to ; the map and join functions above. (let [z (assoc x y -1)] ; Converts where the 2 is to a -1 ([2 2] -> [-1 2]) (recur (if (= y 0) (vec (cons 1 z)) ; If 2 is at the 0th place (e.g. [2 2]), ; prepend a 1 (e.g. [-1 2] -> [1 -1 2]) (assoc z (dec y) (inc (x (dec y))))))))))))) ; Else increment the previous index ; (e.g. [1 -1 2] -> [1 0 -1]) ``` [Answer] # [8th](http://8th-dev.com/), ~~179~~ ~~171~~ 167 characters Here it is a complete program in [8th](http://8th-dev.com/) which takes a decimal signed integer as input and converts it to balanced ternary ``` : f "" swap repeat dup 3 n:mod ["0","+","-"] swap caseof rot swap s:+ swap dup n:sgn n:+ 3 n:/mod nip while drop s:rev ; "? " con:print 16 null con:accept >n f cr . cr ``` **Test** ``` ? 414 +--0+00 ``` The first time the program asks for a number to convert (as required). Then, it is possible to invoke the word `f` to convert more numbers as in the following line: ``` [ 8 , 19 , -14 , ] ( nip dup . space f . cr ) a:each drop ``` **Output** ``` 8 +0- 19 +-0+ -14 -+++ ``` **Code explanation** ``` "? " con:print 16 null con:accept >n ``` This is the code for input handling. The core of the code is inside the word `f`. Away from the *golf course* I would have used the word `>bt` instead of `f`. Here it is an ungolfed version of `f` (with comments): ``` : f \ n -- s "" \ used for the first symbol concatenation swap \ put number on TOS to be used by loop repeat dup 3 n:mod \ return the remainder of the division by 3 [ "0" , "+" , "-" , ] swap caseof \ use remainder to take proper symbol rot \ put previous symbol on TOS swap \ this is required because "" should come first s:+ \ concatenate symbols swap \ put number on TOS dup n:sgn n:+ \ add 1 if positive or add -1 if negative 3 n:/mod nip \ put quotient only on TOS while drop s:rev \ reverse the result on TOS ; ``` [Answer] # Brainfuck, ~~406~~ ~~340~~ 335 bytes code (with added newlines for readability): ``` -[+>+[+<]>+]>-<,[->->+<<]+>[[-]<->]<[>>,<]>[<]>>>>++<<<[>-[<->-----]<+++>>>[>]>>++>++<<<<[[->>+>>+<<<<]<]>>>++>++< [[-<<<<<+>>>>>]<<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]->[-]-->+[+[-<<+>>]>]>>]<<<<<<[[->>>+<<<]<]>,] <<[>>>>>[[-<->]>]<<[++++<]<]>>>>>[>]+[<--[>->]>[-<+>]<]<<++>+<[>-]>[-<++>>]<<[>>--[<+>++++++]<<---[>++<++[>+++<-]]>.[-]<<] ``` Takes input as decimal string with an optional leading `-` This is my first non-trivial Brainfuck program so there is certainly room for improvement. [Try it online](https://tio.run/##NVDbCsJQDPugrIKPQsmPlD6oIMjAB8Hvn8mpFsbOyaXJdntfn6/H574fRxSIQjbRjNwqGERmg1XRGewscpOg9GggVlCUuPB0AhBRbLMjSLl1I9ell3U4EYbSFmq7j4a1rWxQECSBDvjx2UGViXBV25es/@xkrSQHbe1@HkeFlQLgkOmxqkL9FWh60kSmG/rbBpt4rZIw3d0jJGzUNsAvZHTz5J@VrR96vnwB) Commented version of code: ``` -[+>+[+<]>+]>- constant 45 <,[->->+<<]+>[[-]<->]<[>>,<]>[<]> remember sign >>>++<<< load 2 in cell 3 [ while input is not EOF >-[<->-----]<+++ subtract 48 (ascii 0) from input >>>[>]>>++>++<<<<[[->>+>>+<<<<]<]>>>++>++< multiply by 10 (add number to shifted copy) [ add next digit and handle carries [-<<<<<+>>>>>] <<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<] ->[-]-->+[+[-<<+>>]>]>> ] <<<<<<[[->>>+<<<]<]> ,] reset to start of loop <<[>>>>>[[-<->]>]<<[++++<]<] flip number if negative >>>>>[>]+[<--[>->]>[-<+>]<]<<++ strip leading zeros >+<[>-]>[-<++>>]<< ensure zero is printed [ print the number >>--[<+>++++++]< load 43 (char code of plus) <---[>++<++[>+++<-]]>.[-]<< ] ``` [Answer] ## Java, ~~327~~ 269 characters My first try in code golfing. I don't know any of those really short languages, so here's a solution in Java. I'd appreciate advice to further shorten it. ``` import java.util.*;class a{public static void main(String[] h){int i=Integer.parseInt(new Scanner(System.in).nextLine());String r="";while(i!=0){if(i%3==2||i%3==-1){r="-"+r;}else if(i%3==1||i%3==-2){r="+"+r;}else{r="0"+r;}i=i<0?(i-1)/3:(i+1)/3;}System.out.println(r);}} ``` Try it here : <http://ideone.com/fxlBBb> **EDIT** Replaced `BufferedReader` by `Scanner`, allowing me to remove `throws` clause, but had to change import (+2 chars). Replaced `Integer` by `int`. Unfortunately, program won't compile if there isn't `String[] h` in `main`. [Answer] # JavaScript (ES6), 51 bytes ``` v=>[...v].map(x=>t=3*t+((+x!=+x)?(x+1)-0:0),t=0)&&t ``` Loop through characters. First multiply previous total times 3, then if isNaN(character) is true, convert the string (character + "1") to a number and add it, otherwise zero. [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü♣ê⌠yù∞♪♦X=/ƒ├ ``` [Run and debug it](https://staxlang.xyz/#p=810588f47997ec0d04583d2f9fc3&i=8%0A19%0A-14%0A0%0A&a=1&m=2) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` ΔYÝ<ÀÅв3βʽ¾}…0+-ÅвJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JTIw3NtDjccbr2wyfjcpsNdh/Ye2lf7qGGZgbYuSMzr/39dEyMA "05AB1E – Try It Online") [Answer] # APL(NARS), 26 chars, 52 bytes ``` {+/(3*¯1+⍳≢⍵)ׯ2+⌽'-0+'⍳⍵} ``` test: ``` h←{+/(3*¯1+⍳≢⍵)ׯ2+⌽'-0+'⍳⍵} h '+0-' 8 h '+-0+' 19 h '-+++' ¯14 h ,'-' ¯1 h ,'0' 0 h ,'+' 1 ``` possible it could be less if ⊥ is used but it is forbidden... [Answer] # Python 3, 66 Python 2 answer from xnor, ported to Python 3. Note that official support for Python 2 ceases on January 1 2020. ``` n=eval(input()) s="" while n:s="0+-"[n%3]+s;n=-~n//3 print(s or 0) ``` [Answer] # [Raku (Perl 6) (rakudo)](https://raku.org), ~~52~~ 53 bytes ``` {.&(my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''})||0} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lczLDgExFMbx_TxFJ6rTqva0hhhxewfshMkIMxGxcUukrRexmQXv4FW8DeKyYmF1_ovz-46nVbLY5tdLwZhBD3QEXICjVE6S9YyGrGz6QMc2sspqVgFDseKaFRuHyIGTUhofKuDYsCT0iDmvYJZ7krUNjrvdjAo-xjGE3Cp2QC2FOBKdIY6L4cj3g8A1cUyIJNmDSUL_kMxa5bw7SNvn7SYV0bX2dQFN5zsU_p54Ydn01skepbSqq-zduv5J9SnxeHiqPH_eGw) ## Explanation ``` {.&(my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''})||0} my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''} # g returns '' for 0 g(-+^$_ div 3) # g(($_ + 1) div 3) .&( ) # call g($_) ||0 # if this is falsy, then return 0 ``` ]