text
stringlengths
180
608k
[Question] [ Your task is to print this exact text: ``` az za abyz zyba abcxyz zyxcba abcdwxyz zyxwdcba abcdevwxyz zyxwvedcba abcdefuvwxyz zyxwvufedcba abcdefgtuvwxyz zyxwvutgfedcba abcdefghstuvwxyz zyxwvutshgfedcba abcdefghirstuvwxyz zyxwvutsrihgfedcba abcdefghijqrstuvwxyz zyxwvutsrqjihgfedcba abcdefghijkpqrstuvwxyz zyxwvutsrqpkjihgfedcba abcdefghijklopqrstuvwxyz zyxwvutsrqpolkjihgfedcba abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba abcdefghirstuvwxyzyxwvutsrihgfedcba abcdefghstuvwxyzyxwvutshgfedcba abcdefgtuvwxyzyxwvutgfedcba abcdefuvwxyzyxwvufedcba abcdevwxyzyxwvedcba abcdwxyzyxwdcba abcxyzyxcba abyzyba aza ``` The following are allowed: * Leaving out trailing spaces at the end of lines * Doing everything in uppercase instead of lowercase * Trailing newlines Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 36 bytes Code: ``` A13F¦¨DAsKDˆ13N>-·ð׫û,}¯R¦ð2×ì€û.c, ``` Doesn't work on TIO yet, but it does work with the [offline interpreter](https://github.com/Adriandmen/05AB1E). [Answer] # Vim, ~~94~~ 91 bytes This one was tricky. ``` :se ri|h<_ jjYZZpqqpi <Esc>@=17-line('.') xxYq11@qy2G:g/^/m0 qqD0Pwq12@q"0pdkGqq$y0A<C-r>"<Esc>kq24@q ``` Here it is in action: [![Alphabet wings in Vim](https://i.stack.imgur.com/8l5wh.gif)](https://i.stack.imgur.com/8l5wh.gif) Here's an xxd dump with the unprintable characters: ``` 0000000: 3a73 6520 7269 7c68 3c5f 0a6a 6a59 5a5a :se ri|h<_.jjYZZ 0000010: 7071 7170 6920 201b 403d 3137 2d6c 696e pqqpi .@=17-lin 0000020: 6528 272e 2729 0a20 7878 5971 3131 4071 e('.'). xxYq11@q 0000030: 7932 473a 672f 5e2f 6d30 0a71 7144 3050 y2G:g/^/m0.qqD0P 0000040: 7771 3132 4071 2230 7064 6b47 7171 2479 wq12@q"0pdkGqq$y 0000050: 3041 1222 1b6b 7132 3440 71 0A.".kq24@q ``` ## Explanation: Credit for the first two lines goes to [DJMcMayhem](https://codegolf.stackexchange.com/questions/97436/alphabet-diamond/97442#97442) and [Lynn](https://codegolf.stackexchange.com/questions/86986/print-a-tabula-recta/87010#87010). ``` :se ri| " Turn on reverse-insert mode h<_<CR>jjYZZ " Yank the lowercase alphabet from help p " Paste it qq " Start recording a macro pi <Esc> " Paste, then insert two spaces before the cursor @=17-line('.')<CR> xx " Delete the middle two letters Y " Yank the current line q11@q " Stop recording, execute 11 times y2G " Yank everything except the first (blank) line :g/^/m0<CR> " Reverse the order of every line qq " Record D0P " Delete until the end of the line (i.e. just the letters) w " Skip to the first letter on the next line q12@q " Stop recording, execute 12 times "0p " Paste the lines yanked above dk " Delete this line and the line above G " Go to the last line qq " Record $y0 " Move to the end of the line, then yank all but the last letter A<C-r>"<Esc> " Append (in insert mode so it's reversed) k " Go up a line q24@q " Stop recording, execute 24 times ``` [Answer] # PHP, 158 Bytes ``` for(;$i++<25;)echo($a=str_pad)(($t=($f=substr)($j=join(range(a,z)),0,$x=$i>13?13-$i%13:$i).$f($j,-$x)).$a("",51-$i*4," ").$f(strrev($t),$i>12),51," ",2)."\n"; ``` [Answer] ## Batch, ~~395~~ 391 bytes ``` @echo off set q= set r= set s= set t= for /l %%i in (1,1,51)do call set s= %%s%% for %%p in (az by cx dw ev fu gt hs ir jq kp lo mn)do call:u %%p for /l %%i in (1,1,12)do call:l exit/b :u set p=%1 set q=%q%%p:~,1% set r=%p:~1%%r% set s=%s:~4%%p:~1% set t=%p:~,1%%t% echo %q%%r%%s%%t% exit/b :l set q= %q:~,-1% set r=%r:~1% set s=%s:~,-1% set t=%t:~1% echo %q%%r%%s%%t% ``` [Answer] ## Pyke, 27 bytes ``` 13FhG'<R>+26{)DFl826^)_+msX ``` [Try it here!](http://pyke.catbus.co.uk/?code=13FhG%27%3CR%3E%2B26%7B%29DFl826%5E%29_%2BmsX&warnings=0) ``` 13F ) - for i in range(13): h - i+1 G'<R>+ - alphabet[:^]+alphabet[-^:] 26{ - ^.rpad(26) D + - ^ + V F ) - for i in ^^: l8 - ^.lstrip() 26^ - ^.lpad(26) _ - reversed(^) ms - map(palindromise, ^) X - splat(^) ``` [Answer] # J, 52 bytes ``` (,.}.@|."1)(}:,|.|.~"#:_2*i.@#)(a.{~97+],25-|.)\i.13 ``` ## Usage ``` (,.}.@|."1)(}:,|.|.~"#:_2*i.@#)(a.{~97+],25-|.)\i.13 az za abyz zyba abcxyz zyxcba abcdwxyz zyxwdcba abcdevwxyz zyxwvedcba abcdefuvwxyz zyxwvufedcba abcdefgtuvwxyz zyxwvutgfedcba abcdefghstuvwxyz zyxwvutshgfedcba abcdefghirstuvwxyz zyxwvutsrihgfedcba abcdefghijqrstuvwxyz zyxwvutsrqjihgfedcba abcdefghijkpqrstuvwxyz zyxwvutsrqpkjihgfedcba abcdefghijklopqrstuvwxyz zyxwvutsrqpolkjihgfedcba abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba abcdefghirstuvwxyzyxwvutsrihgfedcba abcdefghstuvwxyzyxwvutshgfedcba abcdefgtuvwxyzyxwvutgfedcba abcdefuvwxyzyxwvufedcba abcdevwxyzyxwvedcba abcdwxyzyxwdcba abcxyzyxcba abyzyba aza ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḳṙ-K CrịØaṙµL26_⁶ẋ; 13RµŒḄǀр⁸¦ŒBY ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4biy4bmZLUsKQ3Lhu4vDmGHhuZnCtUwyNl_igbbhuos7CjEzUsK1xZLhuITDh-KCrMOR4oKs4oG4wqbFkkJZ&input=)** ### How? ``` 13RµŒḄǀр⁸¦ŒBY - Main link: no arguments 13R - range(13) -> [1,2,3,...,12,13] µ - monadic chain separation ŒḄ - bounce -> [1,2,3,...,12,13,12,...,3,2,1] Ç€ - call last link (2) as a monad for €ach ¦ - apply to indexes ⁸ - left argument (13R) Ñ€ - next link (1) as a monad for €ach ŒB - bounce with vectorisation at depth 1 (creates the right hand side) Y - join with line feeds CrịØaṙµL26_⁶ẋ; - Link 2: make the left side of a row, with spaces at the left: i (e.g. 3) C - complement (1-i) e.g. 1-3=-2 r - range(1-i, i) e.g. [-2,-1,0,1,2,3] ị - index into Øa - lowercase alphabet e.g. "xyzabc" µ - monadic chain separation ṙ - rotate left by i e.g. "abcxyz" 26_ - literal 26 minus L - length e.g. 26-6=20 ⁶ - literal ' ' ẋ - repeat 26-length times e.g. " " ; - concatenate e.g. " abcxyz" Ḳṙ-K - Link 1, swap spaces to the right: left half of a row Ḳ - split on spaces e.g. [[],[],...,"abcxyz"] ṙ - rotate left by - - literal -1 e.g. ["abcxyz",...,[],[]] K - join with spaces e.g. "abcxyz " ``` [Answer] # [Bubblegum](http://esolangs.org/wiki/Bubblegum), 165 bytes Hexdump: ``` 00000000: 4aac 5220 0d54 25f2 7201 e896 8b03 86a2 J.R .T%.r....... 00000010: 1806 60ab bcd5 fa99 19a7 2f43 ec3a 77e9 ..`......./C.:w. 00000020: 129d a2f9 e58c 9e29 3e64 d3e5 88df 29d9 .......)>d....). 00000030: a9f9 654f be29 dda8 7965 4b4d ca56 6aba ..eO.)..yeKM.Vj. 00000040: ac19 a47c 518d ca92 532a 6668 aacc c55f ...|Q...S*fh..._ 00000050: 2a27 6e54 a652 a46a c446 65ac 64aa 0768 *'nT.R.j.Fe.d..h 00000060: 5886 da49 4d8f cd94 be71 53db d966 4ad7 X..IM....qS..fJ. 00000070: 620a c136 2771 8124 0b07 2822 20a7 c07c b..6'q.$..(" ..| 00000080: 424c 9c30 52c2 4011 1235 1019 c12f 4344 [[email protected]](/cdn-cgi/l/email-protection).../CD 00000090: ec8d 9010 7a12 1784 701b a8d4 a884 48e3 ....z...p.....H. 000000a0: 5050 9508 00 PP... ``` Just ran the string through Zopfli for many iterations. [Answer] ## JavaScript (ES6), ~~215~~ 211 bytes ``` _=>[...Array(25)].map((_,i)=>` `.repeat(++i>13&&i*2-26)+a.slice(0,j=i>13?26-i:i)+a.slice(-j)+` `.repeat(i<13&&51-i*4)+b.slice(i>12,j)+b.slice(-j),a=`abcdefghijklmnopqrstuvwxyz`,b=[...a].reverse().join``).join`\n` ``` Where `\n` represents the literal newline character. This just edged out my character building answer at 213 bytes: ``` _=>[...Array(25)].map((_,i)=>` `.repeat(51).replace(/./g,(b,j)=>(j=i<13?j<i?j+10:j<h?36+j-h:j<51-h?0:j<51-i?86-h-j:60-j:j<h-26?0:j<i?36+j-h:j<26?j+10:j<51-i?60-j:j<77-h?86-h-j:0)?j.toString(36):b,h=++i+i)).join`\n` ``` [Answer] # Ruby, 109 bytes Full program that prints a string as required by the question. One byte could be saved by changing to a lambda function that returns an array of strings. ``` s=[*(?a..?z)]*"" puts (-12..12).map{|i|(t="%#{(i<=>0)*26}s"%(s[0,13-i.abs]+s[13+i.abs..26]))+t[0,25].reverse} ``` **Ungolfed** ``` s=[*(?a..?z)]*"" #Convert range 'a'..'z' into an array, then a string. puts (-12..12).map{|i| #Iterate over -12..12, make an array of lines then print them. (t= #t= left side of pattern. "%#{(i<=>0)*26}s"% #Compose format string %-26s or %26s to pad to 26 chars and left/right justify depending on sign. (s[0,13-i.abs]+s[13+i.abs..26]) #In this format, print the appropriate number of beginning and ending letters of the alphabet. )+ t[0,25].reverse #Righthand side of pattern. Remove the rightmost column from t, reverse it, and concatenate to left side. } ``` [Answer] # C#, 473 Bytes *"Concat", "Reverse", "Substring"... So many big words...* Golfed: ``` string A(){string a="abcdefghijklmnopqrstuvwxyz",r=string.Concat(a.Reverse()),o="",x="",y="",z="";int i=0;var l=new List<string>();for(i=0;i<13;i++){x=a.Substring(0,i);y=r.Substring(0,i);z=x+string.Concat(y.Reverse())+string.Concat(Enumerable.Repeat(" ",51-i*4))+y+string.Concat(x.Reverse())+"\n";o+=z;l.Add(z.Replace(" ","").Replace("zz","z"));}o+=a+r.Substring(1,r.Length-1)+"\n";l.Reverse();for(i=0;i<12;i++)o+=string.Concat(Enumerable.Repeat(" ",i+i+2))+l[i];return o;} ``` Ungolfed: ``` public string A() { string a = "abcdefghijklmnopqrstuvwxyz", r = string.Concat(a.Reverse()), o = "",x="",y="",z=""; int i=0; var l = new List<string>(); for (i = 0; i < 13; i++) { x = a.Substring(0, i); y = r.Substring(0, i); z = x + string.Concat(y.Reverse()) + string.Concat(Enumerable.Repeat(" ", 51-i*4)) + y + string.Concat(x.Reverse()) + "\n"; o += z; l.Add(z.Replace(" ", "").Replace("zz", "z")); } o += a + r.Substring(1, r.Length - 1) + "\n"; l.Reverse(); for (i = 0; i < 12; i++) o += string.Concat(Enumerable.Repeat(" ", i + i + 2)) + l[i]; return o; } ``` Outputs: ``` az za abyz zyba abcxyz zyxcba abcdwxyz zyxwdcba abcdevwxyz zyxwvedcba abcdefuvwxyz zyxwvufedcba abcdefgtuvwxyz zyxwvutgfedcba abcdefghstuvwxyz zyxwvutshgfedcba abcdefghirstuvwxyz zyxwvutsrihgfedcba abcdefghijqrstuvwxyz zyxwvutsrqjihgfedcba abcdefghijkpqrstuvwxyz zyxwvutsrqpkjihgfedcba abcdefghijklopqrstuvwxyz zyxwvutsrqpolkjihgfedcba abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba abcdefghirstuvwxyzyxwvutsrihgfedcba abcdefghstuvwxyzyxwvutshgfedcba abcdefgtuvwxyzyxwvutgfedcba abcdefuvwxyzyxwvufedcba abcdevwxyzyxwvedcba abcdwxyzyxwdcba abcxyzyxcba abyzyba aza ``` [Answer] # Japt, 49 bytes ``` ;1o14@CjX26-2*XÃê £Y<12?X+S²p12-Y :S²pY-12 +X ê÷ ``` I mainly wrote this answer to try out the (somewhat) new `ê` function (bounce; `"abc" -> "abcba"`). [Test it online!](http://ethproductions.github.io/japt/?v=master&code=OzFvMTRAQ2pYMjYtMipYw+ogo1k8MTI/WCtTsnAxMi1ZIDpTsnBZLTEyICtYIOrDtw==&input=) ### Explanation ``` ;1o14@CjX26-2*X} ê £Y<12?X+S²p12-Y :S²pY-12 +X ê} · ; // Set C to "abc...xyz". 1o14 // Create the range [1, 14). @ } // Map each item X by this function: 26-2*X // Take 26 - 2X. CjX // Remove this many chars from index X in C. // We now have ["az", "abyz", ..., "abc...xyz"]. ê // Bounce. This gives us ["az", "abyz", ..., "abc...xyz", ..., "abyz", "az"]. £ } // Map each item X and index Y by this function: Y<12? // If Y is less than 12, X+S²p12-Y // append 12 - Y double-spaces. :S²pY-12 +X // Otherwise, prepend Y - 12 double-spaces. // This gives us the left half of the wings. ê // Bounce. This creates the right half. · // Join the resulting array with newlines. // Implicit: output last expression ``` ]
[Question] [ You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string: For each character in the string: * If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string *up* a column. * If the character is a space or a tab, output it then move the rest of the string *down* a colum. * If the character is neither, output it normally. IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace. If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code. # Sample IO: Output for "bcdef ghijkl": ``` f jkl bcde ghi ``` Output for "Programming Puzzles And Code-Golf": ``` lf -Go s nd de ng zzle A Co mmi Pu gra Pro ``` Output for "Abcdefghijklmnopqrstuvwxyz": ``` vwxyz pqrstu jklmno fghi bcde A ``` As usual, this is code-golf, so shortest answer in bytes wins. [Answer] # Pyth, 63 bytes ``` V_Q aY?}rN0"aeiou"=hZ?}N" "=tZZ;Jh.mbYKh.MZYjC.b++*d+JNY*dK_YQ ^^^^^ ||||| |tabs space ``` The spaces in the middle is actually a single tab character, but StackExchange renders it as four spaces. [Try it online!](http://pyth.herokuapp.com/?code=V_Q+aY%3F%7DrN0%22aeiou%22%3DhZ%3F%7DN%22+%09%22%3DtZZ%3BJh.mbYKh.MZYjC.b%2B%2B*d%2BJNY*dK_YQ&input=%22Programming+Puzzles+And+Code-Golf%22&debug=0) [Answer] # Python 2, 141 137 bytes ``` def S(s,l=[0]): for c in s:l+=[l[-1]-(c in"aeiouAEIOU")+(c<"!")] for h in sorted(set(l)):print"".join([" ",c][i==h]for i,c in zip(l,s)) ``` [Answer] ## JavaScript (Firefox 30-57), 151 bytes ``` s=>[...s].map((c,i)=>r[c<'!'?n++:/[AEIOU]/i.test(c)?n--:n][i]=c,n=s.length,r=[for(_ of s+s)[]])&&[for(a of r)if(s=[for(c of a)c||' '].join``)s].join`\n` ``` Where `\n` represents the literal newline character. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~38~~ 37 bytes ``` Oj33<G13Y2m-IL)hYstX<-"@Z"GX@)h]Xh!c! ``` [**Try it online!**](http://matl.tryitonline.net/#code=T2ozMzxHMTNZMm0tSUwpaFlzdFg8LSJAWiJHWEApaF1YaCFjIQ&input=UHJvZ3JhbW1pbmcgUHV6emxlcyBBbmQgQ29kZS1Hb2xm) ### Explanation For each char, the code computes its vertical position, measured from above (0 is highest). It then builds the output string transposed: each char is on a line with as many leading spaces as its vertical position indicates. Then all lines are contatenated into a 2D char array, which is finally transposed and displayed. ``` O % push a 0 j % input a string 33< % array of the same length as the input that contains true for spaces or tabs G % push input again 11Y2 % string 'aeiouAEIOU' m % array of the same length as the input that contains true for vowels - % subtract IL) % remove last element h % prepend the 0 that is at the bottom of the stack Ys % cumulative sum. This gives the vertical position of each char tX< % duplicate. Compute minimum - % subtract. This sets minimum vertical position to 0 " % for each vertical position @ % push vertical position of current character Z" % string with that many spaces G % push input again X@) % get the character corresponding to the current iteration index h % concatenate horizontally ] % end for each Xh % concatenate all lines into a row cell array ! % transpose into a column cell array c % convert into 2D array, padding with spaces if needed ! % transpose. Implicitly display ``` [Answer] # C, 180 bytes ``` char s[99];i,j,p[99],m,M;main(c){for(gets(s);c=s[i];j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0)p[i++]=j;for(;m<=M;putchar(10),M--)for(i=0;c=s[i];)putchar(M^p[i++]?32:c);} ``` Ungolfed: ``` char s[99];i,j,p[99],m,M; main(c){for(gets(s);c=s[i]; j+=strchr("aeiou",c|32)!=0,j-=c<33,m>j?m=j:M<j?M=j:0) //move current height up or down, adjust minimum and maximum height p[i++]=j; //record height of character for(;m<=M;putchar(10),M--) //from maximum to minimum height for(i=0;c=s[i];)putchar(M^p[i++]?32:c);} //print only characters on this height ``` [Answer] # Perl, 110 bytes *(108 bytes script + 2 bytes flags)* ``` $h=0;map{$h{$h}.=' 'x($p-$p{$h}).$_;$p{$h}=++$p;$h+=/[aeiou]/i-/\s/}split//;print for@h{sort{$b<=>$a}keys%h} ``` Run with `perl -nl script.pl`, input is on stdin, output is on stdout. ## Deobfuscated I've renamed the variables more sensibly, made the code `use strict` and `use warnings` compliant, and made explicit a lot of the magic perl does automatically. This is just run as `perl script.pl`, because it replicates the effects of the `-nl` flags inside the script. ``` use strict; use warnings; use English; # The effect of -l in perl's flags $INPUT_RECORD_SEPARATOR = "\n"; $OUTPUT_RECORD_SEPARATOR = "\n"; # These variables are magicked into existence our $column = 0; our %line_col = (); our %lines = (); # The implicit while-loop is the effect of -n in perl's flags while (defined(my $line = <>)) { # The "chomp" is part of perl's -l flag too chomp $line; # Here starts the actual script. "$h=0" turns into... our $height = 0; for my $char (split '', $line) { if (!exists $line_col{$height}) { # Setting it to 0 is a bit of a white lie, but it might as well be 0. # Perl would otherwise have called the value "undef", which is # similar to 0 in numeric contexts. $line_col{$height} = 0; } $lines{$height} .= ' ' x ($column - $line_col{$height}); $lines{$height} .= $char; $column++; $line_col{$height} = $column; $height++ if $char =~ /[aeiou]/i; $height-- if $char =~ /\s/; } # Sort line heights numerically descending (so the greatest is printed first) my @heights = sort { $b<=>$a } keys %lines; for my $line (@lines{ @heights }) { print $line; } } ``` [Answer] # JavaScript (ES6), 133 ``` s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join` ` ``` *Less golfed* ``` s=>( s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>( q = o[r] || '', o[r] = q += ' '.repeat(c - q.length) + z, x == ' ' ? ++r : r ? --r : o = [,...o] ), o = [], r = 0), o.join`\n` ) ``` **Test** ``` f=s=>s.replace(/[^aeiou ]*(.?)/gi,(z,x,c)=>(q=o[r]||'',o[r]=q+=' '.repeat(c-q.length)+z,x<'!'?++r:r?--r:o=[,...o]),o=[],r=0)&&o.join` ` function test() { i=I.value O.textContent=f(i) } test() ``` ``` #I { width:90%} ``` ``` <input id=I oninput='test()' value='Programming Puzzles And Code-Golf'> <pre id=O> ``` [Answer] ## Haskell (within ANSI terminal), 75 bytes ``` ("\27[2J"++).(h=<<) h ' '="\27[B " h c|elem c"aeiouAEIOU"=c:"\27[A" h c=[c] ``` Usage example: `putStr $ ("\27[2J"++).(h=<<) $ "bcdef ghijkl"` This uses ANSI escape codes to move the cursor up and down. [Answer] # C, ~~173~~ ~~160~~ ~~156~~ 155 bytes Edit: Borrowed idea of using strchr from @mIllIbyte to shave off 13 bytes Edit2: Streamlined the min/max comparisons, -4 bytes Edit3: c can have any value to begin with -> into main(c) instead, -1 byte Edit4: Added ungolf/explanation ``` p,l,j,m;main(c){char b[99],*s=gets(b);for(;j<m+2;p?putchar(c?l?32:c:10):l<j?j=l:l>m?m=l:0,l-=c?(c&=223)&&c-9?!!strchr("AEIOU",c):-1:(p=s=b,l+j++))c=*s++;} ``` Ungolfed and explained: ``` /* declare and initialize these variables to int and 0 */ p,l,j,m; /* declares main, but also int c */ main(c) { /* we can handle strings of length 98 (+1 for string-terminating 0) */ /* we declare and initialize s to point to the beginning of the input string for the first pass through the for loop */ char b[99],*s=gets(b); /* the for-loop actually contains nested loops, where the inner loops behave differently depending on the outer loop parameter p as follows: p attains the values false (0) and true (non-null pointer), in this order. p == false: the inner loop has the parameter s and passes through all the characters in the string until the string is exhausted (*s == 0). l is the vertical position of the current character relative to the first character (l = 0), smaller number = higher up. The purpose here is simply to find the range of vertical positions [j, m] present in the string. The commands in execution order are: -- loop over s -- // test does not do anything since j <= m by design 1. j < m+2 // puts current char in c and increments string counter 2. c = *s++ // ensures that j (m) equals the min (max) of the vertical positions (l) encountered so far. At first step j = l = m = 0. 3. l<j?j=l:l>m?m=l:0 // c != 0, this updates the vertical position for the next character // c = SPC or C = TAB -> lower (l increases by 1) // c = "aeiouAEIOU" -> higher (l decreases by 1) 4a. l-=(c&=223)&&c-9?!!strchr("AEIOU",c):-1 -- loop over s ends -- // c == 0, this resets the string pointer s and puts p = true, and // thereby initiates the next phase of the algorithm // see rest of the explanation at p == true) 4b. p=s=b p == true: now there are two inner loops. The outer of these has the parameter j, which ranges from the smallest vertical position+1 (the value of j after the p == false pass) to the largest vertical position+1 (m+2 after the p == true pass). The innermost loop has the parameter s and passes through all characters in the string until the string is exhausted (*s == 0) just as in the p == false inner loop. Here l is now the vertical position relative to the current position j-1, so that l == 0 when a character is at the current level. Such characters are printed as is, whereas characters at other levels are replaced by space. The end-of-string marker 0 outputs a newline. The commands in execution order are: -- loop over j -- // at first step increments j to point to be one more than the // current vertical position. At other steps moves the current position // (j-1) one vertical position downwards. Also, at all steps, this // biases the vertical position counter l to be zero at the current // vertical position (j-1) 1. l=-j++ // compare j to stopping criteria, exit if j > m+1 2. j < m+2 -- loop over s -- // puts current char in c and increments string counter 3. c = *s++ // outputs character as follows: // c == 0 (end of string), output newline // c != 0 (middle of string) // l == 0 (character at current vertcial position), output c // l != 0 (character not at current vertical position), output space 4. putchar(c?l?32:c:10) // c != 0, this updates the vertical position for the next character // c = SPC or C = TAB -> lower (l increases by 1) // c = "aeiouAEIOU" -> higher (l decreases by 1) 5a. l-=(c&=223)&&c-9?!!strchr("AEIOU",c):-1 -- loop over s ends -- // c == 0, this resets the string pointer s for next loop over s // algorithm (see rest of the explanation at p == true) 5b. p=s=b -- loop over j ends -- */ for(; j<m+2; p?putchar(c?l?32:c:10): l<j?j=l:l>m?m=l:0, l-=c?(c&=223)&&c-9?!!strchr("AEIOU",c):-1: (p=s=b,l+j++)) c=*s++; } ``` ]
[Question] [ Consider a 1-dimensional, real-valued vector *x* that represents observations of some process measured at equally spaced intervals over time. We call *x* a [**time series**](https://en.wikipedia.org/wiki/Time_series). Let *n* denote the length of *x* and *x̄* denote the arithmetic mean of *x*. The **sample [autocovariance](https://en.wikipedia.org/wiki/Autocovariance) function** is defined as [![autocovariance](https://i.stack.imgur.com/ModQk.gif)](https://i.stack.imgur.com/ModQk.gif) for all -*n* < *h* < *n*. This measures the linear dependence between two points on the same series observed at different times. The **sample [autocorrelation](https://en.wikipedia.org/wiki/Autocorrelation) function**, or ACF, is defined as [![autocorrelation](https://i.stack.imgur.com/02oJv.gif)](https://i.stack.imgur.com/02oJv.gif) This measures the linear predictability of the series *x* at time *t*, which we denote *x**t*, using only the value *x**t+h*. Note that these sample estimates do not match the naïve calculations based on the theoretical properties. That is, the sample autocorrelation function is *not* equal to the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient) of *x* with the *h*-step lag of *x*. ## Task Given an array *x* and a nonnegative integer *h*, print or return the first *h*+1 **lag** autocorrelations of *x*, beginning with lag 0. The lag autocorrelations are those corresponding to negative inputs in the above formulas. You can assume that 0 < *h* < *n*, where *n* is the length of *x*, and that 2 < *n* < 256. Output should be correct to within 1E-4. There are no restrictions on the use of built-in functions or running time. ## Examples ``` h, x -> output -------------- 5, [2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2] -> [1.00000000, 0.07659298, -0.06007802, -0.51144343, -0.02912874, -0.10468140] 1, [2134, 1863, 1877, 1877, 1492, 1249] -> [1.0000000, 0.3343041] 2, [13067.3, 13130.5, 13198.4] -> [1.0000000000, -0.0002854906, -0.4997145094] ``` [Answer] # R, ~~3~~ ~~31~~ 25 bytes ``` # changes the builtin to only return the acf body(acf)=body(acf)[1:18] ``` Usage (returns an array with the autocorrelations) ``` (acf(c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2),5)) # , , 1 # # [,1] # [1,] 1.00000000 # [2,] 0.07659298 # [3,] -0.06007802 # [4,] -0.51144343 # [5,] -0.02912874 # [6,] -0.10468140 ``` Background: The 31 byte solution based on the original `acf` built in ``` function(n,h)c(acf(n,h,,F)$acf) ``` Note that the 3 byte option `acf` is the originalbuilt in that will plot (and print to 3 digits) while returning the required autocorrelation as an element in a list. usage ``` acf(c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2),5) ``` output: ``` # Autocorrelations of series ‘c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2)’, by lag # # 0 1 2 3 4 5 # 1.000 0.077 -0.060 -0.511 -0.029 -0.105 ``` If we want the correlations to display to more than 3 decimal places then 28 bytes will do it (or 31, if we want to suppress the plot) ``` # will still plot (28 bytes) function(n,h)c(acf(n,h)$acf) # won't plot (31 bytes) function(n,h)c(acf(n,h,,F)$acf) ``` [Answer] # Jelly, ~~26~~ ~~25~~ ~~24~~ ~~23~~ 20 bytes ``` ×L_SµḊ;0µƓС׹S€µF÷Ḣ ``` [Try it online!](http://jelly.tryitonline.net/#code=w5dMX1PCteG4ijswwrXGk8OQwqHDl8K5U-KCrMK1RsO34bii&input=NQ&args=WzIuNCwgMi40LCAyLjQsIDIuMiwgMi4xLCAxLjUsIDIuMywgMi4zLCAyLjUsIDJd) ### How it works ``` ×L_SµḊ;0µƓС׹S€µF÷Ḣ Main link. Input: x (list) STDIN: h (integer) ×L Multiply all items in x by the length of x. _S Subtract the sum of x from all products. Let's call the result X. µ Begin a new monadic chain. Argument: t (list) Ḋ Remove the first element of t. ;0 Append a 0 to the result. µ Push the previous chain and begin a new one. Argument: X Ɠ Read h from STDIN. С Repeat the Ḋ;0 chain h times, collecting the h+1 intermediate results in a list A. ×¹ Multiply the vectors in A by X. S€ Compute the sum of each vectorized product. µ Begin a new, monadic chain. Argument: S (sums) F Flatten S. This does nothing except creating a deep copy. Ḣ Pop the first element of S. ÷ Divide all elements of the copy by the first element. ``` [Answer] # Python 3, ~~147~~ ~~130~~ ~~126~~ 120 bytes ``` def p(h,x):x=[t-sum(x)/len(x)for t in x];return[sum(s*t for s,t in zip(x[n:],x))/sum(b*b for b in x)for n in range(h+1)] ``` This solution is probably going to be golfed further, It's just a start. You can call it with: ``` p(5,[2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2]) ``` [Answer] # Octave, ~~47~~ 37 bytes ``` @(h,x)xcov(x,'coeff')(numel(x)+(0:h)) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 20 bytes ``` tYm-tPX+tX>/GnqiQ:+) ``` *EDIT (May 20, 2016): as of version 18.0.0 of the language, use `Y+` instead of `X+`. The link includes this change.* [**Try it online!**](http://matl.tryitonline.net/#code=dFltLXRQWSt0WD4vR25xaVE6Kyk&input=WzIuNCwgMi40LCAyLjQsIDIuMiwgMi4xLCAxLjUsIDIuMywgMi4zLCAyLjUsIDJdCjUK) Correlation is closely related to convolution. We normalize by subtracting mean, then convolve, normalize again by dividing by maximum value, and then pick the desired lags. ``` tYm- % implicit input. Duplicate and subtract mean tPX+ % duplicate, flip, convolve tX>/ % duplicate, divide by maximum value Gnq % length of array, n. Subtract 1 iQ: % input number h. Generate vector [1,2,...,h+1] + % add to obtain vector [n,n+1,...,n+h] ) % use that vector as an index. Implicitly display ``` [Answer] # Mathematica, 27 bytes *Thanks to LegionMammal978 for saving 1 byte.* We could beat Jelly if function names were not so long. ``` #2~CorrelationFunction~{#}& ``` --- **Test case** ``` %[5,{2.4,2.4,2.4,2.2,2.1,1.5,2.3,2.3,2.5,2}] (* {1.,0.076593,-0.060078,-0.511443,-0.0291287,-0.104681} *) ``` ]
[Question] [ Given a regular N-gon with all diagonals drawn, how many regions do the diagonals form? For example, a regular triangle has exactly 1, a square has exactly 4, pentagon has exactly 11, and a hexagon has 24. * score is inversely proportional to number of bytes in solution * small fudge factors may be added to scores based on their runtime * the region surrounding the polygon does not count [Answer] # Mathematica 118 Although there are well-defined routines for computing the [number of regions in a regular n-gon with all the diagonals drawn](http://oeis.org/A007678), they are quite cumbersome. I thought it might be fun to take an *image processing approach*: if we draw the n-gon with it's diagonals, would it be possible to count the regions from the drawn image (more precisely, from the rasterized and binarized representation of the image as an array)? The following produces and processes an actual image of a polygon and determines the number of regions from the rasterized image. ``` Table[MorphologicalEulerNumber@Binarize@Rasterize@CompleteGraph[k, ImageSize->1200,EdgeStyle->Thickness[Large]],{k,3,14}] ``` > > {1, 3, 11, 24, 50, 80, 154, 220, 375, 444, 781, 952} > > > This is what might be referred to as an engineer's solution. It gets the job done, but only within some limited conditions. (And it's slow: the above code took 4.24 s to run.) The above routine works correctly up to and including a [14-Complete graph](http://www.wolframalpha.com/input/?i=Complete%20Graph%2014%20vertices), shown below. I found this surprising, given that some of 952 regions are very difficult to see, even when the image is displayed at 1200 by 1200 pixels. The picture below is the image *before* being rasterized and binarized. ![14-complete graph](https://i.stack.imgur.com/I5T4n.png) [Answer] # Excel, 341 bytes Implements the formula given on the Woflram Mathworld link in @mob's comment. ``` =A1*(A1^3-6*A1^2+23*A1-42)/24+1+(MOD(A1,2)=0)*(A1*(42*A1-5*A1^2-40)/48-1)-(MOD(A1,4)=0)*3*A1/4+(MOD(A1,6)=0)*A1*(310-53*A1)/12+(MOD(A1,12)=0)*49/2*A1+(MOD(A1,18)=0)*32*A1+(MOD(A1,24)=0)*19*A1-(MOD(A1,30)=0)*36*A1-(MOD(A1,42)=0)*50*A1-(MOD(A1,60)=0)*190*A1-(MOD(A1,84)=0)*78*A1-(MOD(A1,90)=0)*48*A1-(MOD(A1,120)=0)*78*A1-(MOD(A1,210)=0)*48*A1 ``` Ungolfed for some clarity: ``` =A1*(A1^3-6*A1^2+23*A1-42)/24+1 +(MOD(A1,2)=0) *(A1*(42*A1-5*A1^2-40)/48-1) -(MOD(A1,4)=0) *3*A1/4 +(MOD(A1,6)=0) *A1*(310-53*A1)/12 +(MOD(A1,12)=0) *49/2*A1 +(MOD(A1,18)=0) *32*A1 +(MOD(A1,24)=0) *19*A1 -(MOD(A1,30)=0) *36*A1 -(MOD(A1,42)=0) *50*A1 -(MOD(A1,60)=0) *190*A1 -(MOD(A1,84)=0) *78*A1 -(MOD(A1,90)=0) *48*A1 -(MOD(A1,120)=0)*78*A1 -(MOD(A1,210)=0)*48*A1 ``` [Answer] # [Haskell](https://www.haskell.org/), 232 bytes ``` f n|t<-(.(0^).mod n).(*)=div(t(1176*n)12-t(3744*n)120+t(1536*n)18+t(42*n^2-5*n^3-40*n-48)2-t(2394*n)210+t(912*n)25-t(1728*n)30-t(36*n)4-t(2400*n)42+t(1240*n-212*n^2)6-t(9120*n)60-t(3744*n)84-t(2304*n)90+2*n^4-12*n^3+46*n^2-84*n)48+1 ``` [Try it online!](https://tio.run/##RY7BCoMwDIZfxcMOrdKSpFErzCcZEwQnk2knm@y0d@@aXnYJH/nz/eQ@vh@3dY1xLsL3OBtlFQzabs@pCNqqUvfT8lGHQmybMmgkcyjXMmeGKgW1y4FPzFSGgUydpjMMZTDstRjkOjEIxeiQhOu0x5Z8YgfSKjUsxwwgSNJOuYYwN@vGZF3iBv6f@Kw5EO6gkls2WXEVN/knLxn7CuM2LqHfX0s4Ttu4F/MFrSW4xh8 "Haskell – Try It Online") Uses the formula from [OEIS user Chai Wah Wu](http://oeis.org/wiki/User:Chai_Wah_Wu). ]
[Question] [ The aim of this challenge is to create the shortest code (in characters) that successfully do the following: **Specifications**: * Must create a `5x5x5 labyrinth` with exactly `1 possible solution` (no more, no less) * ~~The labyrinth must be created `randomly`~~ It must be able to generate every existing solution if left running for years * The `start` and `finish` must be placed in `*opposite corners` * The map `output` must in one of the following formats: **Option output format 1** `strings, printed or alerted`: ``` xxxxx,xxxxx,xxxxx,xxxxx,xxxxx/ xxxxx,xxxxx,xxxxx,xxxxx,xxxxx/ xxxxx,xxxxx,xxxxx,xxxxx,xxxxx/ xxxxx,xxxxx,xxxxx,xxxxx,xxxxx/ xxxxx,xxxxx,xxxxx,xxxxx,xxxxx ``` **Option output format 2** `arrays`: ``` [[xxxxx,xxxxx,xxxxx,xxxxx,xxxxx], [xxxxx,xxxxx,xxxxx,xxxxx,xxxxx], [xxxxx,xxxxx,xxxxx,xxxxx,xxxxx], [xxxxx,xxxxx,xxxxx,xxxxx,xxxxx], [xxxxx,xxxxx,xxxxx,xxxxx,xxxxx]] ``` **Output Notes:** * Use `0` for `empty` and `1` for `squares` * Break lines are *NOT* necessary * You decide what `index` is what, but just make sure to *explain* it well --- \*Here is an example of what I mean by opposite corners: ![enter image description here](https://i.stack.imgur.com/vccRG.png) **Clarifications**: * Can *NOT* move in `diagonal` * Can *NOT* pass twice on the same path * Having `inaccessible areas` is allowed * You can `go up/down` more than one level in a row **Tips:** * Don't see them as walls, instead see them as a `5x5x5` stack of squares that some of them are missing and you can go through the missing ones [Answer] # C++ C, about 1000 670 643 395 297 248 chars Sample output: ``` 00111,10011,10111,00110,11000, 11001,01010,00100,11011,10101, 10111,10101,10001,01010,00101, 11001,11110,11100,11110,10101, 11100,10010,11001,10101,00000, ``` How it works: The program uses [Brownian Motion](http://en.wikipedia.org/wiki/Brownian_motion) to generate solutions. The start point is set. Then, a random point is selected and repeatedly moved randomly until it touches one and only one point on the start branch. The point is then set, and if it also touches the end point, the program exits and the matrix displayed. Since no point can join two branches, there is only one path through the labyrinth. The program uses the rand function, and a command line integer argument as the seed, so with a sufficient rand function it should be possible to eventually generate all valid labyrinths (this algorithm will not create unconnected areas however, so it won't generate all *possible* labyrinths). Brownian motion was dropped since it turned out to be unneeded and it's removal simplifies the code significantly. I do think it made nicer labyrinths though. Likewise, the seed argument was dropped, since requiring a stateless random number generator makes more sense to me than a 128-bit seed. It is possible for the program to get stuck in an infinite loop, since it is possible for situations where any point added to the branches would create multiple paths. This is fixable, but I think that it is rare enough to not be a concern for code golf. ``` #define M m[*p+1][p[1]][p[2]] #define F(a,b)for(p[a]=5;p[a]--;putchar(b)) #define f for(i=3;i--;p[i] p[]={4,4,4},h[3],m[7][6][6]={1}; main(i){ for(M=2;h[1]^1||(M=1)^h[2];){ f=rand()%5) h[i]=0; f++) p[i]++, h[M]++, p[i]-=2, h[M]++; } F(0,10) F(1,44) F(2,48+!M); } ``` I've added newlines and indentation to the displayed code for readability. [Answer] ### JavaScript, 874 816 788 686 682 668 637 characters sample output: ``` 00000,10111,10111,01010,11000 01011,01000,01010,01111,00011 00100,11010,00111,10111,11010 01111,10001,01110,01010,01000 00000,11110,00001,10101,10110 ``` this one works by starting from point [0,0,0] and randomly adding attaching one more 0 next to an 0 wherever allowed (allowed==the new 0 is not next to any other 0s except the originator) until there are no more possible additions. if any new 0 is next to the exit point (x\*y\*z == 48) then we open up the exit. golfed ``` b=[] I=Math.random for(i=5;i--;)for(j=5,b[i]=[];j--;)b[i][j]=[1,1,1,1,1] b[0][0][0]=0 k=[[0,0,0]] function q(x,y,z){J=b[x] if(x<0||y<0||z<0||x>4||y>4||z>4||!J[y][z])return n=6-!x||b[x-1][y][z] n-=!y||J[y-1][z] n-=!z||J[y][z-1] n-=x==4||b[x+1][y][z] n-=y==4||J[y+1][z] n-=z==4||J[y][z+1] n==1&&v.push([x,y,z])}while(I){F=k.length B=k[C=0|I(v=[])*F] x=B[0] q(x-1,y=B[1],z=B[2]) q(x,y-1,z) q(x,y,z-1) q(x+1,y,z) q(x,y+1,z) q(x,y,z+1) if(D=v.length){k.push(A=v[0|I()*D]) b[A[0]][A[1]][A[2]]=0 if(A[0]*A[1]*A[2]==48)b[4][4][4]=I=0}else{for(E=[];F--;)F^C&&E.push(k[F]) k=E}}for(i=25;i--;)b[H=0|i/5][i%5]=b[H][i%5].join('') alert(b.join("\n")) ``` original ``` window.map=[]; for (i=0;i<5;++i) { map[i]=[]; for (j=0;j<5;++j) { map[i][j]=[1,1,1,1,1]; } } points=[[0,0,0]]; map[0][0][0]=0; function spaces(x,y,z) { var n=6; if (x<0 || y<0 || z<0) return 0; if (x>4 || y>4 || z>4) return 0; if (!map[x][y][z]) return 0; if (!x || map[x-1][y][z]) n--; if (!y || map[x][y-1][z]) n--; if (!z || map[x][y][z-1]) n--; if (x==4 || map[x+1][y][z]) n--; if (y==4 || map[x][y+1][z]) n--; if (z==4 || map[x][y][z+1]) n--; return n; } do { var index=Math.floor(Math.random()*points.length); point=points[index]; v=[]; x=point[0]; y=point[1]; z=point[2]; spaces(x-1,y,z)==1 && v.push([x-1,y,z]); spaces(x,y-1,z)==1 && v.push([x,y-1,z]); spaces(x,y,z-1)==1 && v.push([x,y,z-1]); spaces(x+1,y,z)==1 && v.push([x+1,y,z]); spaces(x,y+1,z)==1 && v.push([x,y+1,z]); spaces(x,y,z+1)==1 && v.push([x,y,z+1]); if (v.length) { var point=v[Math.floor(Math.random()*v.length)]; points.push(point); map[point[0]][point[1]][point[2]]=0; if (point[0]*point[1]*point[2]==48) { map[4][4][4]=0; } } else { var np=[]; for (var i=0;i<points.length;++i) { i!=index && np.push(points[i]); } points=np; } } while(points.length); for (i=0;i<5;++i) { for (j=0;j<5;++j) { map[i][j]=map[i][j].join(''); } map[i]=map[i].join(); } alert(map.join("\n")); ``` [Answer] **Mathematica: True Labyrinth (827 chars)** Originally, I produced a path from {1,1,1} to {5,5,5} but because there were no possible wrong turns to be made, I introduced forks or "decision points" (vertices of degree >2) where one would need to decide which way to go. The result is a true maze or labyrinth. The "blind alleys" were far more challenging to solve than finding a simple, direct path. The most challenging thing was to eliminate cycles within the path while allowing cycles off the solution path. The following two lines of code are only used for rendering the drawn graphs, so the code does not count, as it is not employed in the solution. ``` o = Sequence[VertexLabels -> "Name", ImagePadding -> 10, GraphHighlightStyle -> "Thick", ImageSize -> 600]; o2 = Sequence[ImagePadding -> 10, GraphHighlightStyle -> "Thick", ImageSize -> 600]; ``` **Code used:** ``` e[c_] := Cases[EdgeList[GridGraph[ConstantArray[5, 3]]], j_ \[UndirectedEdge] k_ /; (MemberQ[c, j] && MemberQ[c, k])] m[] := Module[{d = 5, v = {1, 125}}, While[\[Not] MatchQ[FindShortestPath[Graph[e[v]], 1, 125], {1, __, 125}], v = Join[v, RandomSample[Complement[Range[125], v], 1]]]; Graph[e[Select[ConnectedComponents[Graph[e[v]]], MemberQ[#, 1] &][[1]]]]] w[gr_, p_] := EdgeDelete[gr, EdgeList[PathGraph[p]]] y[p_, u_] := Select[Intersection[#, p] & /@ ConnectedComponents[u], Length[#] > 1 &] g = HighlightGraph[lab = m[], PathGraph[s = FindShortestPath[lab, 1, 125]],o] u = w[g, s] q = y[s, u] While[y[s, u] != {}, u = EdgeDelete[u, Take[FindShortestPath[u, q[[1, r = RandomInteger[Length@q[[1]] - 2] + 1]], q[[1, r + 1]]], 2] /. {{a_, b_} :> a \[UndirectedEdge] b}]; q = y[s, u]] g = EdgeAdd[u, EdgeList@PathGraph[s]]; Partition[StringJoin /@ Partition[ReplacePart[Table["x", {125}], Transpose[{VertexList[g], Table["o", {Length[VertexList@g]}]}]/. {{a_, b_} :> a -> b}], {5}], 5] ``` **Sample output** {{"oxooo", "xxooo", "xoxxo", "xoxxo", "xxoox"}, {"ooxoo", "xoooo", "ooxox", "oooxx", "xooxx"}, {"oooxx", "ooxxo", "ooxox", "xoxoo", "xxxoo"}, {"oxxxx", "oooox", "xooox", "xoxxx", "oooxx"}, {"xxxxx", "ooxox", "oooox", "xoxoo", "oooxo"}} **Under the hood** The picture below shows the labyrinth or maze that corresponds to the solution `({{"ooxoo",...}}` displayed above: ![solution1](https://i.stack.imgur.com/7pQMD.png) Here is the same labyrinth inserted in a 5x5x5 `GridGraph`. The numbered vertices are nodes on the shortest path out of the labyrinth. Note the forks or decision points at 34, 64, and 114. I'll include the code used for rendering the graph even though it is not part of the solution: ``` HighlightGraph[gg = GridGraph[ConstantArray[5, 3]], g, GraphHighlightStyle ->"DehighlightFade", VertexLabels -> Rule @@@ Transpose[{s, s}] ] ``` ![solution2](https://i.stack.imgur.com/dVChv.png) And this graph shows only the solution to the labyrinth: ``` HighlightGraph[gg = GridGraph[ConstantArray[5, 3]], Join[s, e[s]], GraphHighlightStyle -> "DehighlightFade", VertexLabels -> Rule @@@ Transpose[{s, s}] ] ``` ![solution3](https://i.stack.imgur.com/wu97U.png) Finally, some definitions that may help reading the code: ![definitions](https://i.stack.imgur.com/r0pAs.png) --- **Original solution (432 char, Produced a path but not a true maze or labyrinth)** Imagine a 5x5x5 large solid cube made up of distinct unit cubes. The following begins without unit cubes at {1,1,1} and {5,5,5}, since we know they must be part of the solution. Then it removes random cubes until there is an unimpeded path from {1,1,1} to {5,5,5}. The "labyrinth" is the shortest path (if more than one is possible) given the unit cubes that have been removed. ``` d=5 v={1,d^3} edges[g_,c_]:=Cases[g,j_\[UndirectedEdge] k_/;(MemberQ[c,j]&&MemberQ[c,k])] g:=Graph[v,edges[EdgeList[GridGraph[ConstantArray[d,d]]],v]]; While[\[Not]FindShortestPath[g,1,d^3]!={}, v=Join[v,RandomSample[Complement[Range[d^3],v],1]]] Partition[Partition[ReplacePart[ Table["x",{d^3}],Transpose[{FindShortestPath[g,1,d^3],Table["o",{Length[s]}]}] /.{{a_,b_}:> a->b}],{d}]/.{a_,b_,c_,d_,e_}:> StringJoin[a,b,c,d,e],5] ``` Example: ``` {{"ooxxx", "xxxxx", "xxxxx", "xxxxx", "xxxxx"}, {"xoxxx", "xoooo", "xxxxo", "xxxxo", "xxxxo"}, {"xxxxx", "xxxxx", "xxxxx", "xxxxx", "xxxxo"}, {"xxxxx", "xxxxx", "xxxxx", "xxxxx", "xxxxo"}, {"xxxxx", "xxxxx", "xxxxx", "xxxxx", "xxxxo"}} ``` Technically this is not yet a true labyrinth, since there are no wrong turns that one can make. But I thought it interesting as a start since it relies on graph theory. The routine actually makes a labyrinth but I plugged up all empty locations that could give rise to cycles. If I find a way to remove cycles I will include that code here. ]
[Question] [ I just got a job as a postman and I need your help to keep it. I have to order a lot of mails before I go out to deliver them. Streets are numbered strictly sequentially, starting with 1 at the start of the street, and continuing in order skipping no numbers until the end, with odd numbers on the left side and evens on the right side. Plus houses were added later so we may also have letters appended to the civic number. The chest contains all mail of the city so I have to choose only mails of my street. I need your help to order the mails faster. What I ask you is to write a function or full program taking: - A street name. - A list of civic numbers ordered following my path. - A list of addresses (representing the mail chest). And output a list of addresses containing only the ones of my street, ordered following the list of civic numbers. An address has the form : ``` Person Name/n CivicN Street Name ``` Where *CivicN* is a number that can be followed by a '/' and an UPPERCASE LETTER (10 10/B). If you prefer, lowercase is acceptable. If Streets Names overlaps they are considered different streets: ``` Church Road != Saint Lorenz Church Road ``` We omit the rest of the address for simplicity (assuming it is the same for every mail) Letters must be delivered fast so shortest answer wins. **EXAMPLE:** Layout : ``` 1 1/B 3 5 7 9 11 13 ============================== 2 4 4/B 6 ``` Input : ``` "Tea Avenue" ["1","1/B","2","4","3","5","7","4/B","6","9","11","13"] ["Mrs. Pie O. Pinky\n6 Tea Avenue","Ms. Kita I. Omeeha\n6 Tea Avenue","Mr. Raile A. Lee\n26 Uea Grove","Odd O. Nic\n76 Mira Road","Mrs. Fuel Tee\n78 Uea Grove","Ny O. Ondip\n55 Uea Grove","Mrs. Black\n67 Uea Grove","Ollie E.\n11 Tea Avenue","Mr. Urna Li\n75 Mira Road","Ms. Polly\n2 Tea Avenue"] ``` Output : ``` Ms. Polly 2 Tea Avenue Mrs. Pie O. Pinky 6 Tea Avenue Ms. Kita I. Omeeha 6 Tea Avenue Ollie E. 11 Tea Avenue ``` Input : ``` "Church Road" ["1","3","5","5/B","2","4","7","7/B","6","9","9/B","11","11/B"] ["Billy Ray V.\n5 Church Roadside East","Ms. Mia\n5 Church Road","Mrs. Dadeos\n9/B Church Road","Dr. Ymin U.\n3 Church Road","Atty. Nerou\n3 Church Road","Ollie A. Chaim\n6 Saint Lorenz Church Road","Ms. Rose\n5 Church Road","Alf Taohy\n79 Berry Road","Ms. Ootr E.\n5 Saint Lorenz Church Road","Lol E.\n21 Berry Road","Ms. Norton\n2 Church Road"] ``` Output : ``` Dr. Ymin U. 3 Church Road Atty. Nerou 3 Church Road Ms. Mia 5 Church Road Ms. Rose 5 Church Road Ms. Norton 2 Church Road" Mrs. Dadeos 9/B Church Road ``` Test generator: [Try it online!](https://tio.run/##3VjhV9s2EP@ev0Lz3pqEOCGBdgyCeY@2rO1GKWuh6xby8oyjJALHSm05hfLyt7OTTrJlJ6H0w/Zh5TWR7k6n@53uTqcEs1lzHAT39z@yKAjTISX7iYhZND6o5BTGgUb9qU2b00Dw2KZM/Zk9TQULmbi1SaM0CgTjkR/a1CARw5BdlkmMH1QqFRjs7aFFJBGDJB2Nbno7feKRO@K85/7QIS5xjv2IqsEHsJMKNTwMQ3qLozmNUuS/jNkcR69iLkeLbmGLyJ/SwSymI3bT62zpbZT827hF9CAxIzN4HnMxoTFODoW41fQX/kyY4YTRkR7yUBLRHM1@zSNDO435SI7BsoJpYyoGlnm1@l2FxFSkcVSwmsR@NKzVf3pKGma4RTZWDH8h/W5lUamwSJBRTD/bCms1LdR52jCjthlttzcMe6u@kljf3Iavn5X6YOLHyvZjKoS9h3N0@P7Nu7OTD8cvzl@evn396vmvf/35@8dPf//2h9NDg/pFDWFZAxU@Z1EyiYdhkE6/jMa3s8v59dXN569rNMz5FxoWVPiU8dTpadOfleQ/LskfHr15d75WPkqnlzS2F1Tb1fwgOm0lXj7VgM1ZUCPyICKIAPntQ@S1idRjC8c0SUNBuhWidryBwYjHpEa6sBD@b3odXERuYD1uHaldiVnrAathKVpUCBuBBh/XaUYDVm9Wu0bRoVTkkybpdAsyN6hAQ82UGohYIvbVeOazeB@QuRaegwOAH9HYF3SQqMRFJ9BomEN/hJIcje2sYB4AReqb6m8@HAKajp5RqAow3cqZA@V1i50R0MuSzNTBdOF7X9nZJY0GQ98pP2Z5pkjSCFhgHbLa1TXa69KfZAoiir5BOu02uFpzFVNpbRPPy9boQaOR8w1L7Vkw5KkhFgEZgjzFLZwv1CcNEwo1z95isZAsZKzEJP3qagfmiCTVAEJeCY9egN82Gs14CIx9Wnq@DoqlHpFguLRmaTIZXPrBde1u6gKmRf3haM4SVkesLLq11RnareTplpe@pTgyRYQ0OjKimk34XIqkbVKXaPKkyythVx/LMl/XuRWAFJ45Z0MyA4Mh4ZaSTKcVZL5bgJbQmQ/AAUG9YlAHPBVkf584PSdDt07h3h4TFBUwVYdal3TMolpdYhfkB0mhEjLmlLBcYdhmQZ1IyAULcuukVwqsDSbQEUWT@xeRU/LGKuvX1JwHvPOQc/xU8P8YPhPNg4QGXBar73PDFOKFQVdXho/jkCaJ5PzPnTEI/VtgPz4yQn2Fhyyix3jF7Fgpo13E3dil7sRc5eaqCmnkrb9wwlbCvlLjFXTKBPhhj/VbCEsihsU1ufQKWJMWqByLiVp0lZcY7c1J76pP9uGK362SJ09weuBB52AKrSz1kqrr7CU8A65JXmUX5lhqINmULYfs/3AtldVoooXVpEqqOONyZrmjZtnZ6LgghxdJ8eLBZUYjL2ik36Ex/oasV1WiIV6POa9rwErOQXbAzW2ifVoIJio/qhdRFT1n/gExXsvhKgovIhWGsqp71OOeg5NQBVNbozCNm6T@O7vLPSAVdDJk997UZyGGpj/lKXxhuCeUDktlgHyJ/dmMxsdr6O@/ccOoGxAV17uV9TdVqf97dNlKeJjK5ygsvOQ8JGNOkzP@QVO9kQ@Rp/Pymt6qvNzcLLesCQrA2/SEE9leQrtDzOW9W25KZdPwEBStE0TUXuCmkAF8qJOaQ3rt/uM7Y1ykS5hqRkrtds0c4qZGUAfzd5W71xUhlLMqkMRk68bGSGWpYkEOOcSxp9JC/ZQ3ntohfSzWCqXVnOEibGWMqxWoaG2Z1JAsE4snC6LqbHMTvSxUbTOXXtxF5jfh2m3cjk5SW/fHrEuzlrZw7WL9VoWdslyV4aL6cYKP0D0kaYdC1BBPPrfkW59PS4GBoqrQmr1IHA2z8xhEebeqj9/AywSW4enXQfb2bUO6Z3lh/SKxotIvnZeIU4oPBDjYGU9ye4pQ9AWpRCFniVdk99TafmvE4kQU/L5SLL9SF@uD2Xg4d0XfZptal3mshE1196YStViU0FjU7pTxLipRD5PlV4udGET@FVuZiwjr@ob6I0efDt@eHh@1cC5rPDnGw9/DELKbnfxc9Twrv7b6Nyen52dmebEBy2uVFs52WFLt5mVfJZGR0kXdJY7rrNz@3fmZtX@m3PjV1TcZrF3c22Ub76/s7oI4H2R3lyybA31i8MgaiWVqzMaTgtVwguo3NNAr@1GI38JWYNMuiHeeKYvwt0T95Tq60JaxybNrZn/k6OSlNcdmwLzq5C9K9/8A "C++ (gcc) – Try It Online") Change string\_wrapper\_left/right and separator to modify formatting. Rules : - Standard loopholes are forbidden. - Standard input/output methods. - Shortest answer in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,⁵KỴṪ⁼ɗƇ@ɗ€ẎY ``` A full program accepting three arguments - a list of civic numbers on your named street, a list of the addresses in the mail chest, and your street name - which prints the addresses to which you need to deliver in the order of the given civic numbers. **[Try it online!](https://tio.run/##y0rNyan8/1/nUeNW74e7tzzcuepR456T04@1O5yc/qhpzcNdfZH///@PVjJU0lEyBmJTENZ3ApJGQGwCxOYgDBYxA2JLEAbzDA3BBJAdC9TvW6yn4JuZGJNnquCcUVqUnKEQlJ@YAlThWwSUcUlMSc0vjskD6kSTdinSU4jMzcxTCNWLyTNGk3QsKanUU/BLLcovxZT0z8nJTFVw1AMKJ2bmxuSZKQQnZuaVKPjkF6XmVaG7AuiIoPziVEz3OeakKYQk5mdUxuSZWyo4pRYVVSJr8s8vKVJw1QPpw2O8T34OWJGRIaYJfvlFJfl5QDkUPbH/lZC5AA "Jelly – Try It Online")** ### How? ``` ,⁵KỴṪ⁼ɗƇ@ɗ€ẎY - Main link: civic numbers, addresses € - for each (civic number): ɗ - last three links as a dyad - i.e. f(civic number, addresses): ,⁵ - pair (the civic number) with 3rd program input (the street name) K - join (that) with a space -- i.e. X=civic number+' '+street name @ - with swapped arguments i.e. f(addresses, X): Ƈ - filter (the addresses) keeping those for which: ɗ - last three links as a dyad - i.e. f(address, X): Ỵ - split (address) at newlines Ṫ - tail (get the second line) ⁼ - equals (X)? Ẏ - tighten (the list of lists to a single list) Y - join with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε²ðýUʒ¶¡Xk]˜ ``` -2 bytes by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/193796/52210), so make sure to upvote him! -1 byte thanks to *@Grimy*. Inputs are in the order: [list of civic numbers], street name, [list of addresses]. [Try it online.](https://tio.run/##fY@xTsMwEIb3PsUpMzJKS1t1TGi3lkqBIlCTwRCjWLg@yXYH8xjMLLwBQoKNJd1A4pXCxVOUSgzfyb7/7vdvtPxOiqb5/ajfD2@Hr833c/1Zv948Fj8vTbON4ugkGhHjltOU6pA4I6YtoTMhZi3hFseh0LkYnFd7c19BhrwcbKNUKuUh4x6uWa7H0FGtLAUsuHW0u7IMVpL3JlrBkDLnpUCba3qsJ88Ng9ud1LAh91FPTJzzDC6Ewf2xuFZKCkgYtbnc5XoCl1xqB0s0Qj/1U1CIDK04zpeoB7jiWPlcT2eQCmN8d2mNzsAi/Pwf@yWqMDSMuw7FHw) **Explanation:** ``` ε # Map over the (implicit) input-list of civic numbers ² # Push the second street-input ðý # And join the two values by a space U # Pop and store this street + num string in variable `X` ʒ # Filter the (implicit) input-list of addresses by: ¶¡ # Split on newlines Xk # Get the index of string `X` (street + num) in this list, # which will be either -1 (not found), 0 (first address-line), or # 1 (second address-line), and only 1 is truthy in 05AB1E ] # After both the inner filter and outer map: ˜ # Flatten the array to remove any empty inner lists # (after which the result is output implicitly) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 58 bytes ``` (s,n,a)=>n.flatMap(n=>a.filter(x=>x.split` `[1]==n+' '+s)) ``` [Try it online!](https://tio.run/##fVHBbtpAEL3zFSNfYit0I0ONy8FIkLRVVRxXNByiGCkrex1vssyitUEhP09nTRJhLPUwtlbz3syb9575jleZkZv6C@pcHIro4FZ97HMvmiArFK9jvnExmnBWSFUL475Gk1dWbZSsH3uPD/4qivDyAi4uK887ZBorrQRT@skt3B6Acyc4THcCt8Lp0/vB8Z2@41/N6Dug@ko1pAqoQvtuOiOqscU14KGzOlJjUzH4IwUk9ocv@xRHcLrAiQnwW9YcfjFI1kKUvAsxDBZcKgFTBnMhUhyMYEmIn0bvLCDJc7vgVmYphiOIpeGw0DxvuDT/x1YoGknE8FuLeLu3vARzuUkxCFq9hjlTPHshQWF7n1J00neWou93pS4NcphLWha0pVgrtFLkweCUtep5Xq8bw3W5NVn5Tv7M4cP5oJWHzSFs5TBuXsc0bHYfeZCGWJLFAbTmH6@94bnQVYpEPmvf0F33a4mwpKOHZ81pXe/JfWH0tts8ekXBXZdcrm22f7nEGubaCHw7V0EiFroSXX1TVcAd1yWZF45hJozZn5ISXZsmkOB/4@daNaCBfzrB@n/4Bw "JavaScript (Node.js) – Try It Online") ### Commented ``` (s, n, a) => // s = street name, n[] = civic numbers, a[] = addresses n.flatMap(n => // for each civic number n in n[]: a.filter(x => // for each address x in a[]: x.split`\n`[1] // keep it if the 2nd part is equal to == n + ' ' + s // n + space + expected street name ) // end of filter() ) // end of flatMap() (empty entries are discarded) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->s,o,n{n.grep(/\d\S* #{s}$/).sort_by{|i|o.index i[/\d+(\/.)?/]}} ``` [Try it online!](https://tio.run/##fVLRbtowFH3vV1xlq9Ru1BHQkPHQVtBu0zQgEy0PFUaVS0zj1VwjJ@mWUb6dXUMeSCM1L5Z1zzk@95zY/LHYLi62Z5dpwzRwjezJytWJz2N@@wk@rNPNR/@UpcZmD4/F@lW9GqYwln9BTQnz@YT77PTKn20221WepbCYendSQO9FYi69Bhz/8ZrQ9PvQgnNoQwAhnNOtA11o0qBNkKk3tCmDX0pC5A58Ljh24FDGGxLgp8oE/GAQLaVMRB1iGYyF0hJ6DAZScmx1YEKI79a8OEAUx@6BkZpzDDswVFbA2Ih4xyX9b7nUJEnE8EuFOCocL8JYrTgGQWW2Y/a1mD@TobD6nta00lfGkTatWZ1YFDBQ9FhQteKiMFpTBq1D1mzGfhuF4HHk6B0dubS9s/Ir7y796yS386RU28fvYg/KCkIIy/i7dLoKqJx9CfTwUFGuAVQ09iveiFialKNjVcc3tMz9kpxNaNP2m2EvywqKXFqT14f7gKit60SopSv0VijMYGCsxH9vXZCJsUll3V9PL@BOmIQSC7vQl9YWh6TIZHbXQvCe/MDoHajVrCuM6Oc36Po45FQL2f4H "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 51 bytes ``` sub{my($r,$a,@B)=@_;map{$n=$_;grep/ $n $r$/,@B}@$a} ``` [Try it online!](https://tio.run/##hVLtattAEPyvp1iOgySgyJVdWTXGxXZSh1J/BDculKqYq3Wpj0h34iQF1JBXr7onkdiWAjWshdiZndkdJVxHXklnozLNfz3FxTnVNmX2eHoxGm@HMUueqBzR7fC35knHohKoph1sP48pey6HVsoKIHRrEbhXGujs8uO5BXB2xxlMHrnM@ZkNP4hLbOJ2pvjfxXqP1cPysHzzXnX6WAODq8A98tPGQWShUwduBYeVeciHIpB9OEwnNkIQ8UVkDD47sIo537Mmph7kwJqJiMPEgTnngez2YYOgG60eqzmrMDQqS7ELpN@HhdAM1oqF5GBklvMIJyPZ/3BKXhaGu5KhSALpecfNV/Y0YrsH9OY3dKMI9/vkBNJ137S90ZLBXKCod@yq3vxWRREepXvMtC6GVp3M6M2fRV76reTI1T7Xu/1h8Tq8l7i8kxBNeP5JeIPqrY7QBF6HOBXoEa9fwDfc0oMjjVSEuDtLM2SYdRaCNRCmYa53zUKu0kCiBDRNkms80/dYSNigQK9Bn2RZgblyrfJ2s74@fhNXeyZi8@V8ZUJmMFeayz9tJWNyrVLedjmJ7uGOqT2m4Q9gyrUuXhdA0kplukrZ@4/CXEUVruu2hyyVzpQ0cR/TTN7lX5VkQsm0vFx4zjv3Hw "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 63 bytes ``` (a,b,c)=>b.SelectMany(x=>c.Where(l=>l.Split('\n')[1]==x+" "+a)) ``` [Try it online!](https://tio.run/##ZVBdb4IwFH33VzR9ESLrgg7Y4iDRRBczEaMzexAfarnOxlpNQadZ/O2ssGWT@HB629zzcXtZesdSnvcPkj2nmeLyw/op88X/ZdCThy0ouhTwSwqClZ8b1FpazPSDJZmCAJaFVJ6Nkx8w8r4GBYbwA0Gme8Ezox7Lujm3F75/amCEG9Q083ZtrL0yY2XgN6CocwR5AGzVJHzOF1/Yxha277v6bGo8aLQ0HA2veJcdV@Op4JXkFr78qUOVEjTmgKKiyM05li66jsGhJrzyjKIBQdEWYE1vKYqgCeUCUIegIUAsmy6aacaL2h0LQpQkRcCIs1h6Lgq5omiyo0mp1f79AwhtqYXeY0U4Ohe6SCZ8H0vHqfRKZVdQttEDedU8IfSXeiSWtn076kxJioZchznVUYpV7ITQO2heqy6m2c6/AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Python 3, **79** ~~85~~ bytes (thanks to [squid](https://codegolf.stackexchange.com/questions/193781/postman-delivery/193860#comment461634_193860)) ``` d=lambda s,n,a:n and[k for k in a if k.split('\n')[1]==n[0]+' '+s]+d(s,n[1:],a) ``` ### old: ``` d=lambda s,n,a:[k for k in a if k.split('\n')[1]==n[0]+' '+s]+d(s,n[1:],a)if n else[] ``` [Answer] # [Python 3](https://docs.python.org/3/), 65 bytes ``` lambda s,n,m:[a for i in n for a in m if a.endswith('\n%s '%i+s)] ``` [Try it online!](https://tio.run/##fVJNT8JAEL37KyZNjBBJTcFSMfEAfsUI1KAcjOUw0m26cTtLtkVT/zzOFjSUJh5mu5t5bz7e66osUk29TXIVbRRm7zFC3qFOdvmGkGgDEiQBVVe01wxkAugKivMvWaStk4iOczg5lqd5e7FZGUlFK2k5LwJh@CloLZzO0ZvjOR3HOxvx2eU45@hx@ByBfVeZPsfA4ipwz1lY4sTkLjxJAaH90EcZUR/2izsTBjzKAuHBhTATIsUmxLgwQ6kEDF0YCxFRtw9zRtwb/WkBYRzbBlO5jCjow0QahJnGuOJy/bu1UFySicFFjTgtLS@kWK4i8v1armKOFC4/eKCg3k8pXunWjcjzmqPODSGMJTfz66NYKbRSrEF3n7Vot4/@hL9O12aZ7ig75X@19msOWOWDmvKD6rXV37q1dYC7TiSL6kOt9na/G4yFziNi6kH6hjd5zfiPmfOavYPksChK1lsYvW4mt@qwVdcpysy6@Yy8HYy1EfR9OAUPMdO5aM43VAm8oE5ZrmAAI2FMuU8KdWEqC/z/yo@1qkBdr1lhqk2hyZqxz2E3Nj8 "Python 3 – Try It Online") Also works in Python 2. For each number `i` in the list of civic numbers `n`, the function will iterate over *all* addresses `a` in the list of mail `m` and keep the ones where the combination of the civic number `i` and the street name `s` matches with `a`. This results in a sorted and filtered list. [Answer] # [Kotlin](https://kotlinlang.org), 145 bytes ``` fun p(s:String,o:List<String>,m:List<String>):List<String> =if(o.size<1)List(0){""} else m.filter{it.split("\n")[1]==o[0]+" "+s}+p(s,o.drop(1),m) ``` [Try it online!](https://tio.run/##pVltUxs5Ev7OrxBTV8tM4TUxCWFxLXdFEnaLOhJShNS9BGpL2DLWMjOa1cgh3hS/Pfd0SxrP@IW9u6VCYs@0pO6nn35R5964XJff9vbEWVnN3FCUxk11eScmxgo3VWKsJnKWO@FU7cRI1qrubUHavyqMGJmiUKUTlamdGgtT4pWu8XisesJYL2uVEjhG1X1xhYUTbbEZPRAQpa1qBxHHwkZU1oxUHWRrNTLlmOQknyXxpJJW4jASzzV2MhNRzopbZWuhSxw6Vpb2Gatcf@aPvBWJRzFpcXTp1B19qfIZnmBh5bQpZc77KuewdGLy3DwQHjg3l/XUKwUTrdeJZJfUanQqpM6FHI8tjIHpJIrFczGVn7HFAwyV1tUiLWWhxHdRMiO5xWa3cxxdqgcPV3pd9rMtknhtFb/3fgqIizuTT8RoKvNclXdqSIJT56p6uLdH7@l1v3ZydK@@QAoifSi/99ve4Oj54Q8DEn8PPxYA440Hby74tDPx6wxG3RkHbX41t0KSP6ogK@GgMyjpXTI3MyumKq/IB/dKVUK7Pt57s03wjxS5YYcHoGpxq2CLguAdZGau48GpKhi/D8wT7z/vS0AA8uiRy@dA7bcZuKhh/pxZClOtI@89aDcVAyFdYBse08EL6rE42QG2YcWMFjVcqu91VdGT0kQGkfgMkjnvocpxz59hxuOGZBwLIL6asKG1hoPoCPVZlc1bq@@mjt/1xXsQkV1mZiCMeIB1xAqilCQ21gbPgBYokeMzAbrgKkCpKigCaSBHW4/0Zz0K2kT2gRwcyLBSamgBqDxPAxoj7YCj8T6PHhtNjakVNAbG3lfktHmAru@Fyf1d34dAnKqwaCKRIrwm/5jCFWdg0T0t4SwA26x2MFhMZuWIIjGkj8kMOiIn3FlZCCfv4Qgm9vfiJGggKIL68VkMv7b5tVeG4yVENInDhkq66crSJmhFalWFj8Qq@N/5LMKAMZBZ38fHCdwKziKDErFXdglwh1MZR4LFICN2oOxFNdnuJvcwi9ZZ1fdnx5PgMJ9OEUiFGAqOZ4gByndAaK8Ur2n1uxBG/FB4dxDVwktOtf4AbCYp65cIzoVKMSvt7O0wn/H64/v3p5evTz6civPTq6vTSxJOB8/E4NneK2B0NmE3A8mJsj1Be1iqJTiL4240UpWTtzmcyGSaNIFOKgIjJIFcVmzcnILfp92SwoacOtYTbExlyONYe9tfT2d2NBWXRo7F9rH4ABc4cY4kU/7eeccQwB2F9vnBqrpJDxHaiSdjrYsq1xwlqazrWcGJwjV1jBANoorTJ3GFU/p5iNKCEumtirmNKIm4oNiup8ZSmfWpqAZGyCll7TE5/efJ2/fnp96wczmnDMlhMBCDvVeCfp6LA3Eo/M@RGODFcxI4fvKHJPzPvngRPr3Ahi/5IG4K/DnJlZLiBKlrphL6/ikZJL0EZ@Pvffy@wO9z/B7g95C@85uXCWfW5IhkecHz5MYvfwv@ivdaiQv6p7yfX5cvResQv/AthP6unRRnfXFRKDWV68VsX1wCaiVO@oBaXZf7L8VHSP1sQZ4gdIHkjMPe6dF1efhSvNVWMgGaPXDWTzOVY3tscPjDygbv5rT@ohzr6ro8OFh5zzu8ylFfoeTh6vl5DnNP@9clnLPWhI@2lOJc4/CDVfUILgQgcNpvr75hT1347MOuaiTpS1uWXy7DTg9fLgutoL5OKtrDNGxbFJqGFnla4dZiT@TLQYdFxJ7DFfYc8RPPIWJdZBE0fatBioN2SLf98UaOlamvS2ywRuQNUP8Xolh8hFuerxE4cW4OzihrZusFPAqg3eup1AWxc1OiaTnyEgV1vc4n6OCupJnCzYdH4pWySCJLiy@Ms0yjgz866tzkLLg/WL/TO2QcUxKh2mu7jOIvLZjoawcHLkILlNa@D26ijwfr3hEeG196LT2Zl18vPExfl3zseXhF6fxOlQodtbFDcQUckLJRhtFSb5Pb0Aj7dtEinf/yYKmTsr9Q47bn@zMqc6EnD3caIwqDsjPnWisdtQc@UV/OclSs0KF8cFgpcVfIjammht5Q64o1txqNXdlfEtMUMnuhkyiUm5pxHWVCdYilAb64nTtqE6lGeEtPv1SSO8CmheKmNNzR6tblivsQ9Gprbg39LayOcqkvqEMqyDAxNChD5Kja/eif/bW3RUWDCl33edb9Ko63WNAXeDSy3F6Gc6AztaKt1hnaRfHYHFnlZpauG0IVFSow9UR9FtITkbJm/Vr/rsSPYpBt@VpGGqTPMvFVJIl4bDS4QLW2D7rGJXWic2quCY1bavnDxc2ZKDvRpdcu9OVeudh7EsJR0jWX29A/aS/KiopTOWokK61GqjmLr28F6NU07@0d/V49uoJWcgSNJXebtum/g@xV6LS5DaSWuNe6OvKq9q6xsfGXihpdjfNR0T6@uXhCK@rSIM8XwdYGDUrGBkaRIRpNJ1VKGDk2dPpDs6dVo5mtVbjeexDJIn9dRnTcoxmMwpKuQbREo50a@4sgLwwAE7JRFihWkqlEPuEr5JI/PFQqr1VgB53ZDwT4Gp4xn1yfEUmT6@syyT4NbtBGee5/enazm4hktyUdjHjc7QZNryXiyTm2pkoHWS90hRSEP8VIXcTm5sCkG7BS/soZQx09ZE3r5S0aDfZCDPe@bxWL2zFQpCa@xPUdiY1vB94LtJAJwNca8iwY3rqC@dL@4sCnmm@cGNJ6GJKBGXbSQDHsRn/729axnqSGo/PHQRaC8muSPG6xN4rghK8t4D3ux8cmIl4D4LTumQbGIvu2hOBYY7X0tyvOpXUIFkqo9VaHpqv4ijeL5STrd@gBOwQ/LYoOivD4oIJk@1wExSwn9Amt8OJPpVFmZoXPLi/ThLuqephk7Yc7f/EH7CS7nmm/Gl1eGb9DGniY7PTETtIT@POJ/925wV/ZLgdBkOmsaxZE8SRrn9rRwHcLS3pVaedeG3i//qzrkjze3f9RLLDlaHmLdmdR3EYbZ2B8P@wWNBxdptLe4W54Yq2ct@Hd8vkTfQF2HMcrN0LB7tSLySfp7SDzNSacSwi3ZkjoACWHD@rTF7rR8gyjjNKKiDihcoPEb0MJ8y2HR@SzzGMqOWZFzpF502x7uylx4Rxdn9LiNItFzk2teRBnMPdO5if2bkbxfxp1SFt5KHklx@GQbbhqxZI4ZoiDlVCPaQ7QVGOk1nzcHVHyCJRGeDwqbUwOI1bfhbQmrFTKIAkgeKjaJHsgNKPWi2cDfqy1ALXBsYXtMqi6BIi6qXPtrE/o@olUF9yYb3pJtq6V2A5pf7VKXMK0L2ny6dn3Rze76d6nk@//fZP9LWnoHSuMG01PS6etSrXLaL@SBlqPvP3/6UDWaLP/PqP@olWJfQyNqkb3TZtAbQgKnCqoYC4NmtmPfloeXQjBemlkPfRtCc06NjUV6@fXUTTVfWTbhgS3uDAzEcR3i9lQ48OhuC6zhQ/ZqD92ISe16MH1ZX6pyHtplPn9P@ccOqztm5817sSMDtVeNXK@rvSo26LCcqdc00SF/gU@A25Na0w3IKcC6uohCnNjhqgjKMiXiynYxJqi3cbxoBGZ02cb7vmsQlJFd6Z50M4sbaRR6Vb/28d7oFvPOnm9X8iqhS75Co2z@gJnAWn@eDFJd66vd7KOC3I9UumzME1nsWyXqv9u87ITUCmL7O5ncYXrU5Z300w8ZiGTX7QycI870pwKB@WXVo/lZYnVXSsf8RFwiBQ3Zr4vkv9pOpkF85qiR@5mZ6JWUOYLqNXbgYgRraQz7ImWUKwCEZqECD9IEzQDETQEETQbETQc6RgvaDgi/GxN0HiEZyOCxyKCZmvZ6vab5mydFjbsvqokP/4vhnBd@T@axnWknxjLLe361HyuI/rUoG51z/UTu66OG0d3K4ZvmuGtILpumJctEac70lnLnEgU4cdoCw5trRLncJk4R/4B8acrzjO2dWzaNG9bhXXz4K0j@@QEriP55Chujbs2zeTWMv8pazYO7LrqbZ7crWy3YYT3v2q2ab63ct76QR@zjZts9LW@26Y2@dt/AA "Kotlin – Try It Online") ]
[Question] [ The Simplest N-Dimensional shape one can create for any dimension is a [Simplex](https://en.wikipedia.org/wiki/Simplex), and this is a set of N+1 points that are all equal distance away from eachother. For 2 dimensions, this is an equilateral triangle, for 3 dimensions, this is an regular tetrahedron, at 4 dimensions is the [5-Cell](https://en.wikipedia.org/wiki/5-cell) and so on. ## The Challenge Given an Integer dimension N as input, output an Array/List/Stack/Whatever of N Dimensional points that represent a Simplex of this dimension. That is, N+1 vertexes that are equal and non-zero distance from eachother. [Reference implementation in Lua](https://tio.run/##bVLBboMwDD0nX2F1BxK1ZTDtOP5it6qTMhpWqzRhYLRNqN/OHAj0sB2I5Ofn52ebujfjWPWuJPQOOrw2tf1WTkuBFTgoCsiAztZJIVpLfetgGLLbTQpbd5bB2pemBg/FvXafc7XwB7fNj4wPTBaVbwGLfMeSJ88xp/F4cCGfcWjdKZLKibTPI@1PXdQ9lKFU3QPmZRq2AcIAaHiEYDpKz@9slmLTf9qFFLHKqvv2tBZHbPJ8NXROu8@WVA57IC3v62GdwA@flOtimxYdvao0TXk3sw0TdsMArwd9@tUi2c2wkfPIO7aBDrAx2HbK6NkfVop@GqtIF0VC5r22iY7HEbHDhKa9a0x5YV64RLzU2kWR74jZH0t@Go/PjfACD2Y598pPdpAstOlZ7d42Yc4xtpZi@QWetdTjLw) ## Examples ``` 1 -> [[0], [1]] 2 -> [[0, 0], [1, 0], [0.5, 0.866...]] 4 -> [[0, 0, 0, 0], [1, 0, 0, 0], [0.5, 0.866..., 0, 0], [0.5, 0.288..., 0.816..., 0], [0.5, 0.288..., 0.204..., 0.790...]] ``` ## Notes * Input is a number in any [standard format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and will always be an integer greater than 1 and less than 10 * Hardcoding is allowed for input of 1, but nothing higher. * Reasonable error is allowed in the output. Issues with floating point arithmetic or trig may be ignored. * Any transformation of the N dimensional simplex is allowed, aslong as it remains Regular and Non-zero. * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. [Answer] # Python ~~78~~ 66 Bytes ``` lambda n:[i*[0]+[n]+(n+~i)*[0]for i in range(n)]+[n*[1+(n+1)**.5]] ``` Surely can be improved, ~~especially at handling n=1```. (How is that even a simplex?)~~ Just realized that's not necessary. Can probably be improved still ^^ [Try it online!](https://tio.run/##XcqxCoAgEADQub7C0dOIJFyEvsQcjLIO6gxxaenXDdfGB@9@8hFpLGGay@mvZfWMjEVhByctOclJvgiVISaGDIklT/vGCWoQVtWiQIheO1d@SXUaTNvcCSnzwBGgfA "Python 3 – Try It Online") `[i*[0]+[1]+(n+~i)*[0]for i in range(n)]` creates identity matrix. All points have distance `sqrt(2)` from each other. (thanks to Rod for improving) Now we need a `n+1`-th point with the same distance to all other points. We have to choose `(x, x, ... x)`. Distance from `(1, 0, ... )` to `(x, x, ... x)` is `sqrt((x-1)²+x²+...+x²)`. If we want an `n` dimensional simplex this turns out to be `sqrt((x-1)²+(n-1)x²)`, as we have one `1` and `n-1` `0`s in the first point. Simplify a bit: `sqrt(x²-2x+1+(n-1)x²) = sqrt(nx²-2x+1)` We want this distance to be `sqrt(2)`. `sqrt(2) = sqrt(nx²-2x+1)` `2 = nx²-2x+1` `0 = nx²-2x-1` `0 = x²-2/n*x+1/n` Solving this quadratic equation (one solution, other one works fine, too): `x = 1/n+sqrt(1/n²+1/n) = 1/n+sqrt((n+1)/n²) = 1/n+sqrt(n+1)/n = (1+sqrt(n+1))/n` Put that in a list `n` times, put that list in a list and join with identity matrix. --- -4 Bytes thanks to Alex Varga: Multiply each vector by `n`. This changes the creation of the identity matrix to `lambda n:[i*[0]+[n]+(n+~i)*[0]` (same length) and gets rid of the division by `n` in the additional point, so it becomes `n*[1+(n+1)**.5]`, saving two brackets and the `/n`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘½‘÷ẋW =þ;Ç ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw4xDe4HE4e0Pd3WHc9ke3md9uP2/WdDRPYfbj056uHOGyqOmNVmPGuYo6NopPGqYC@NycQE5/wE "Jelly – Try It Online")** Works by generating the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix) of size **N** and concatenating it with the list generated by repeating **N** times the singleton **√(N + 1) + 1**, divided by **N**. ``` ‘½‘÷ẋW – Helper link (monadic). I'll call the argument N. ‘ – Increment N (N + 1). ½ – Square root. ‘ – Increment (√(N + 1) + 1). ÷ – Divide by N. ẋ – Repeat this singleton list N times. W – And wrap that into another list. –––––––––––––––––––––––––––––––––––––––––– =þ;Ç – Main link. =þ – Outer product of equality. ;Ç – Concatenate with the result given by the helper link applied to the input. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` IdentityMatrix@#~Join~{Table[1-(#+1)^.5,#]/#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfMyU1rySzpNI3saQos8JBuc4rPzOvrjokMSknNdpQV0NZ21AzTs9URzlWX7lW7b9LfnRAUWZeSXSejoKSgq6dgpKOQppDXqyOQjVQxNCgNvY/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 18 bytes *1 byte thanks to @ngn* ``` ∘.=⍨∘⍳⍪1÷¯1+4○*∘.5 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHHTP0bB/1rgDSj3o3P@pdZXh4@6H1htomj6Z3a4EkTYHqFAy51G1hQJ0rTcEIjW@MxjcBAA "APL (Dyalog Unicode) – Try It Online") [Answer] ## JavaScript (ES7), 70 bytes ``` n=>[a=Array(n++).fill((1+n**.5)/--n),...a.map((_,i)=>a.map(_=>+!i--))] ``` Port of @PattuX's Python answer. [Answer] # Wolfram Language (Mathematica), 205 bytes ``` f1 = Sqrt[# (# + 1)/2]/# /(# + 1) & ; f2 = Sqrt[# (# + 1)/2]/# & ; simplex[k_] := {ConstantArray[0, k]}~Join~Table[ Table[f1[n], {n, 1, n - 1}]~Join~{f2[n]}~Join~ ConstantArray[0, k - n], {n, k}] ``` Simplex function in Mathematica Starting from `{0,0,...]},{1,0,0,...]}`, Placing first point at origin, Second point on `x` axis Third point in `x,y` plane, Fourth point in `x,y,z` space, etc. This progression reuses all the previous points, adding one new point at a time in new dimension ``` simplex[6]={{0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0}, {1/2, Sqrt[3]/2, 0, 0, 0, 0}, {1/2, 1/(2 Sqrt[3]), Sqrt[2/3], 0, 0, 0}, {1/2, 1/(2 Sqrt[3]), 1/(2 Sqrt[6]), Sqrt[5/2]/2, 0, 0}, {1/2, 1/(2 Sqrt[3]), 1/( 2 Sqrt[6]), 1/(2 Sqrt[10]), Sqrt[3/5], 0}, {1/2, 1/(2 Sqrt[3]), 1/( 2 Sqrt[6]), 1/(2 Sqrt[10]), 1/(2 Sqrt[15]), Sqrt[7/3]/2}} ``` ### Verification ``` In[64]:= EuclideanDistance[simplex[10][[#[[1]]]],simplex[10][[#[[2]]]]] & /@ Permutations[Range[10],{2}]//Simplify Out[64]= {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 31 bytes Saved 2 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo). ``` @(n)[n*eye(n);~~(1:n)+(n+1)^.5] ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzM6Tyu1MhXIsK6r0zC0ytPU1sjTNtSM0zON/Z@mYajJlaZhBCKMQYQJiDDV/A8A "Octave – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes rather than returning similar magnitudes for all dimensions and using the formula `(1+(n+1)**0.5)/n` I scale up by a factor of `n` to simplify the formula to `(1+(n+1)**0.5)` ``` ->n{(a=[n]+[0]*~-n).map{a=a.rotate}+[[1+(n+1)**0.5]*n]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiPRNjovVjvaIFarTjdPUy83saA60TZRryi/JLEktVY7OtpQWyNP21BTS8tAzzRWKy@29n@BQlq0cex/AA "Ruby – Try It Online") **ungolfed in test program** A lambda function taking `n` as an argument and returning an array of arrays. ``` f=->n{ (a=[n]+[0]*~-n).map{ #setup an array `a` containing `n` and `n-1` zeros. perform `n` iterations (which happens to be the the size of the array.) a=a.rotate}+ #in each iteration rotate `a` and return an array of all possible rotations of array `a` [[1+(n+1)**0.5]*n] #concatenate an array of n copies of 1+(n+1)**0.5 } p f[3] # call for n=3 and print output ``` **output** ``` [[0, 0, 3], [0, 3, 0], [3, 0, 0], [3.0, 3.0, 3.0]] ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes ``` n->concat((n+1)^.5-matid(n),1^[1..n]) ``` [Try it online!](https://tio.run/##DcoxCsAgDEDRq4ROhhppho7tRUoFsVgcGkW8f5rlD5/X06j0di1wgAqduUlO0zlZGWPY6UuzPk7Qc7w4BLlRSxtOjLMH3jz0UWXaWIBOSzGMqD8 "Pari/GP – Try It Online") [Answer] # [R](https://www.r-project.org/), 38 bytes ``` function(n)rbind(diag(n,n),1+(n+1)^.5) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPsygpMy9FIyUzMV0jTydPU8dQWyNP21AzTs9U839KZnGJRpqGiabmfwA "R – Try It Online") ]
[Question] [ > > [The Levenshtein edit distance between two strings](https://en.wikipedia.org/wiki/Levenshtein_distance) is the minimum possible number of insertions, deletions, or substitutions to convert one word into another word. In this case, each insertion, deletion and substitution has a cost of 1. > > > For example, the distance between `roll` and `rolling` is 3, because deletions cost 1, and we need to delete 3 characters. The distance between `toll` and `tall` is 1, because substitutions cost 1. > > > [Stolen from original Levenshtein question](https://codegolf.stackexchange.com/q/67474/65836) > > > Your task is to calculate the Levenshtein edit difference between an input string and your source. This is tagged [quine](/questions/tagged/quine "show questions tagged 'quine'"), so cheating quines (for example, reading your source code) are *not* allowed. ### Rules * The input will be non-empty and will be composed of ASCII, unless your source contains non-ASCII, in which case the input may include Unicode. Regardless, the Levenshtein distance will be measured in characters, not bytes. * The output is the minimum Levenshtein edit distance of the input and your source. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer, in bytes, wins. [Answer] # [Python](https://www.python.org/) 2 + [sequtils](https://pypi.python.org/pypi/sequtils), 101 bytes ``` from sequtils import*;_='from sequtils import*;_=%r;print edit(_%%_,input())';print edit(_%_,input()) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~278~~ 258 bytes ``` t=input();s,f='t=input();s,f=%r,lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%%s)[m-1]==t[n-1]));print f(len(s%%s),len(t))',lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%s)[m-1]==t[n-1]));print f(len(s%s),len(t)) ``` [Try it online!](https://tio.run/##rY2xDsIgFEV/hYXAM48BRytf0nSoKUQSeCXlObj460h1ME4ubuee3OSUO19XOrbGLlK5sYahYnDqe8oN05wvyywy0imLdRMkYhD5QGfrU/XmkSPpoLOxSIAdkIx9wW46Gq2rlBXGLibneOxyAhjKFolF0MnT@4A7MYD6T/JX8RNsTS0@qCc "Python 2 – Try It Online") This is just the usual quine in Python, mixed with the Levenshtein algorithm from [this answer](https://codegolf.stackexchange.com/a/102910/68615). Note that it gets ~~quite~~ *extremely* (thanks to Mr. Xcoder :P) slow. [Answer] # [Haskell](https://www.haskell.org/), 210 bytes ``` main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x="main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x=" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM882M68ktSgxuUSlOCO/XE9Do0JbG8RSqNBU1bSucNBItErWVK100EiyStGsSbS1TbJNVk2pMbQzsDXUzs3My8wtzY2uUE3RSVatBOKUWOsK1UrbnNS89JIMFaBZldYVtkp0s2gY@slQKREA "Haskell – Try It Online") Computes the levenshtein distance modified from [here](https://en.wikipedia.org/wiki/Levenshtein_distance#Recursive). (I wrote the code there too) This is combined with a standard quine mechanism. Not much special here. If you want to play around with it I suggest making edits towards the end of the string. The algorithm is more or less \$O(n+m^4)\$ where \$n\$ is the location of the difference between the input and the source, and \$m\$ is the length of the string after the first difference. So if you add a character to the front of this the compute time is exponential with the length of input and you won't see your result on tio. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 135 bytes ``` exec(s:="l=lambda a,b:min(l(A:=a[1:],B:=b[1:])-(a[0]==b[0]),l(A,b),l(a,B))+1if b>''<a else len(a+b);print(l('exec(s:=%r)'%s,input()))") ``` [Try it online!](https://tio.run/##NY1BCsMgFESvIoGgn/xCQjfF1kJzjeDi21oqGCtqoTm9NYuuZh4Mb@JWXu9wPMVUq/3au8hSdV55Ws2DGKGRqwvCi5tUtExS4yyV2QscBC2jVo1GDdgWaPYgnAGGyT2ZuXJ@IWZ9tszbIGgwcI7JhdJ8/H/WJ@B9RhfipwgA6KDWzeYf "Python 3.8 (pre-release) – Try It Online") took my solution of levenstein distance (<https://codegolf.stackexchange.com/a/233868/103772>) and adapted it to a quine. It is very (very) slow but it works [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 10 bytes ``` `:qp꘍`:qp꘍ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%3Aqp%EA%98%8D%60%3Aqp%EA%98%8D&inputs=%60%3Apq%EA%98%8D%60%3Apq%EA%98%8D&header=&footer=) Thanks to Aaron Miller for this one. ``` `:qp `:qp # Standard quine ꘍ ꘍ # Levenshtein distance ``` # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 13 bytes ``` `q\`:Ė\`+꘍`:Ė ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60q%5C%60%3A%C4%96%5C%60%2B%EA%98%8D%60%3A%C4%96&inputs=%27%60q%5C%60%3A%C4%96%5C%60%2B%EA%98%8D%60%3Ap%27&header=&footer=) ``` `q\`:Ė\`+ `:Ė # Standard eval quine (see https://codegolf.stackexchange.com/a/232956/100664) ꘍ # Leveshtein distance with input ``` [10 bytes](https://lyxal.pythonanywhere.com?flags=D&code=%60q%E2%80%9B%3A%C4%96%2B%EA%98%8D%60%3A%C4%96&inputs=%27%60q%5C%60%3A%C4%96%5C%60%2B%EA%98%8D%60%3Ap%27&header=&footer=) in Vyxal 2.6, whiich hasn't been released yet [Answer] # JavaScript, 113 bytes This is a [valid](https://codegolf.meta.stackexchange.com/a/13638/72349) quine. ``` f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q ``` ``` f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q console.log(f('f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q')); console.log(f('%')); console.log(f('12345')); ``` Idea stolen from other answer. ]
[Question] [ Your goal is to output the strictly increasing sequence of consecutive, identical digits of pi (π). Each term in the sequence must be one digit longer than the previous. So `3` (0th digit of pi) is the first time a run of digits occurs (length 1). The next to occur is `33` (digits 24 and 25 of pi). Of course, this sequence requires the digits of pi to be **in base 10**. **The ones known so far**, and the first six all occur within the first 800 digits: ``` 3 33 111 9999 99999 999999 3333333 44444444 777777777 6666666666 ... (not in first 2 billion digits) ``` Note that the consecutive nines all occur together, in the same run, so if the next larger run you found happened to be 1000 consecutive `0`s, this would fill in *multiple* terms of the sequence. I have not found any more terms with my program. I know there are no more terms within the first 50000 digits or more. My program was taking too long with 500000 digits, so I gave up. [**Reference Implementation**](http://ideone.com/hpB85G) **You may:** * Output the sequence forever * Take an integer `n` and find the first `n` numbers in the sequence * Take an integer `n` and find the numbers in the sequence contained in the first `n` digits of pi. Make sure to specify which one your code does. The number `n` may be zero or one indexed. Inspired by [this mathoverflow question](https://mathoverflow.net/q/23547). [Answer] # Mathematica, 85 bytes ``` FromDigits/@DeleteDuplicatesBy[Join@@Subsets/@Split@RealDigits[Pi,10,#][[1]],Length]& ``` Anonymous function. Takes *n* as input, and returns the elements of the sequence in the first *n* digits of π. Output is in the form of `{0, 3, 33, 111, ...}`. [Answer] ## Python 2, 110 bytes ``` n=input() x=p=7*n|1 while~-p:x=p/2*x/p+2*10**n;p-=2 l=m=0 for c in`x`: l=l*(p==c)+1;p=c if l>m:m=l;print p*l ``` The maximum number of digits to check is taken as from stdin. 10,000 digits finishes in about 2s with PyPy 5.3. **Sample Usage** ``` $ echo 10000 | pypy pi-runs.py 3 33 111 9999 99999 999999 ``` --- ### Something Useful ``` from sys import argv from gmpy2 import mpz def pibs(a, b): if a == b: if a == 0: return (1, 1, 1123) p = a*(a*(32*a-48)+22)-3 q = a*a*a*24893568 t = 21460*a+1123 return (p, -q, p*t) m = (a+b) >> 1 p1, q1, t1 = pibs(a, m) p2, q2, t2 = pibs(m+1, b) return (p1*p2, q1*q2, q2*t1 + p1*t2) if __name__ == '__main__': from sys import argv digits = int(argv[1]) pi_terms = mpz(digits*0.16975227728583067) p, q, t = pibs(0, pi_terms) z = mpz(10)**digits pi = 3528*q*z/t l=m=0 x=0 for c in str(pi): l=l*(p==c)+1;p=c if l>m:m=l;print x,p*l x+=1 ``` I've switched from Chudnovsky to Ramanujan 39 for this. Chudnovsky ran out of memory on my system shortly after 100 million digits, but Ramanujan made it all the way to 400 million, in only about 38 minutes. I think this is another case were slower growth rate of terms wins out in the end, at least on a system with limited resources. **Sample Usage** ``` $ python pi-ramanujan39-runs.py 400000000 0 3 25 33 155 111 765 9999 766 99999 767 999999 710106 3333333 22931752 44444444 24658609 777777777 386980421 6666666666 ``` --- ### Faster Unbounded Generators The reference implementation given in the problem description is interesting. It uses an unbounded generator, taken directly from the paper [Unbounded Spigot Algorithms for the Digits of Pi](http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf). According to the author, the implementations provided are "deliberately obscure", so I decided to make fresh implementations of all three algorithms listed by the author, without deliberate obfuscation. I've also added a fourth, based on [Ramanujan #39](https://books.google.fr/books?id=oSioAM4wORMC&pg=PA38&hl=en#v=onepage&q&f=false). ``` try: from gmpy2 import mpz except: mpz = long def g1_ref(): # Leibniz/Euler, reference q, r, t = mpz(1), mpz(0), mpz(1) i, j = 1, 3 while True: n = (q+r)/t if n*t > 4*q+r-t: yield n q, r = 10*q, 10*(r-n*t) q, r, t = q*i, (2*q+r)*j, t*j i += 1; j += 2 def g1_md(): # Leibniz/Euler, multi-digit q, r, t = mpz(1), mpz(0), mpz(1) i, j = 1, 3 z = mpz(10)**10 while True: n = (q+r)/t if n*t > 4*q+r-t: for d in digits(n, i>34 and 10 or 1): yield d q, r = z*q, z*(r-n*t) u, v, x = 1, 0, 1 for k in range(33): u, v, x = u*i, (2*u+v)*j, x*j i += 1; j += 2 q, r, t = q*u, q*v+r*x, t*x def g2_md(): # Lambert, multi-digit q, r, s, t = mpz(0), mpz(4), mpz(1), mpz(0) i, j, k = 1, 1, 1 z = mpz(10)**49 while True: n = (q+r)/(s+t) if n == q/s: for d in digits(n, i>65 and 49 or 1): yield d q, r = z*(q-n*s), z*(r-n*t) u, v, w, x = 1, 0, 0, 1 for l in range(64): u, v, w, x = u*j+v, u*k, w*j+x, w*k i += 1; j += 2; k += j q, r, s, t = q*u+r*w, q*v+r*x, s*u+t*w, s*v+t*x def g3_ref(): # Gosper, reference q, r, t = mpz(1), mpz(180), mpz(60) i = 2 while True: u, y = i*(i*27+27)+6, (q+r)/t yield y q, r, t, i = 10*q*i*(2*i-1), 10*u*(q*(5*i-2)+r-y*t), t*u, i+1 def g3_md(): # Gosper, multi-digit q, r, t = mpz(1), mpz(0), mpz(1) i, j = 1, 60 z = mpz(10)**50 while True: n = (q+r)/t if n*t > 6*i*q+r-t: for d in digits(n, i>38 and 50 or 1): yield d q, r = z*q, z*(r-n*t) u, v, x = 1, 0, 1 for k in range(37): u, v, x = u*i*(2*i-1), j*(u*(5*i-2)+v), x*j i += 1; j += 54*i q, r, t = q*u, q*v+r*x, t*x def g4_md(): # Ramanujan 39, multi-digit q, r, s ,t = mpz(0), mpz(3528), mpz(1), mpz(0) i = 1 z = mpz(10)**3511 while True: n = (q+r)/(s+t) if n == (22583*i*q+r)/(22583*i*s+t): for d in digits(n, i>597 and 3511 or 1): yield d q, r = z*(q-n*s), z*(r-n*t) u, v, x = mpz(1), mpz(0), mpz(1) for k in range(596): c, d, f = i*(i*(i*32-48)+22)-3, 21460*i-20337, -i*i*i*24893568 u, v, x = u*c, (u*d+v)*f, x*f i += 1 q, r, s, t = q*u, q*v+r*x, s*u, s*v+t*x def digits(x, n): o = [] for k in range(n): x, r = divmod(x, 10) o.append(r) return reversed(o) ``` **Notes** Above are 6 implementations: the two reference implementations provided by the author (denoted `_ref`), and four that compute terms in batches, generating multiple digits at once (`_md`). All implementations have been confirmed to 100,000 digits. When choosing batch sizes, I chose values that slowly lose precision over time. For example, `g1_md` generates 10 digits per batch, with 33 iterations. However, this will only produce ~9.93 correct digits. When precision runs out the check condition will fail, triggering an extra batch to be run. This seems to be more performant than slowly gainly extra, unneeded precision over time. * **g1 (Leibniz/Euler)** An extra variable `j` is kept, representing `2*i+1`. The author does the same in the reference implementation. Calculating `n` separately is far simpler (and less obscure), because it uses the current values of `q`, `r` and `t`, rather than the next. * **g2 (Lambert)** The check `n == q/s` is admittedly quite lax. That should read `n == (q*(k+2*j+4)+r)/(s*(k+2*j+4)+t)`, where `j` is `2*i-1` and `k` is `i*i`. At higher iterations, the `r` and `t` terms become increasingly less significant. As is, it's good for the first 100,000 digits, so it's probably good for all. The author provides no reference implementation. * **g3 (Gosper)** The author conjectures that it is unnecessary to check that `n` will not change in subsequent iterations, and that it only serves to slow the algorithm. While probably true, the generator is holding onto ~13% more correct digits than it has currently generated, which seems somewhat wasteful. I've added the check back in, and wait until 50 digits are correct, generating them all at once, with a noticable gain in performance. * **g4 (Ramanujan 39)** Calculated as ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%7B3528%7D%5Cmiddle%2F%7B%5Csum%5Climits_%7B_%7Bn%3D0%7D%7D%5E%7B_%7B%5Cinfty%7D%7D%7B%5Cfrac%7B%28-1%29%5En+%284n%29%21+%281123%2B21460n%29%7D%7B%28n%21%29%5E4+14112%5E%7B2n%7D%7D%7D%7D) Unfortunately, `s` doesn't zero out, due to the initial (3528 ÷) composition, but it's still significantly faster than g3. Convergence is ~5.89 digits per term, 3511 digits are generated at a time. If that's a bit much, generating 271 digits per 46 iterations is also a decent choice. **Timings** Taken on my system, for purposes of comparison only. Times are listed in seconds. If a timing took longer than 10 minutes, I didn't run any further tests. ``` | g1_ref | g1_md | g2_md | g3_ref | g3_md | g4_md ------------+---------+---------+---------+---------+---------+-------- 10,000 | 1.645 | 0.229 | 0.093 | 0.312 | 0.062 | 0.062 20,000 | 6.859 | 0.937 | 0.234 | 1.140 | 0.250 | 0.109 50,000 | 55.62 | 5.546 | 1.437 | 9.703 | 1.468 | 0.234 100,000 | 247.9 | 24.42 | 5.812 | 39.32 | 5.765 | 0.593 200,000 | 2,158 | 158.7 | 25.73 | 174.5 | 33.62 | 2.156 500,000 | - | 1,270 | 215.5 | 3,173 | 874.8 | 13.51 1,000,000 | - | - | 1,019 | - | - | 58.02 ``` It's interesting that `g2` eventually overtakes `g3`, despite a slower rate of convergence. I suspect this is because the operands grow at a significantly slower rate, winning out in the long run. The fastest implmentation `g4_md` is approximately 235x faster than the `g3_ref` implmentation on 500,000 digits. That said, there's still a significant overhead to streaming digits in this way. Calculating all digits directly using Ramanujan 39 ([python source](http://codepad.org/53uKjlHw)) is approximately 10x as fast. **Why not Chudnovsky?** The Chudnovsky algorithm requires a full precision square root, which I'm honestly not sure how to work in - assuming it could be at all. Ramanujan 39 is somewhat special in this regard. However, the method does seem like it might be conducive to Machin-like formulas, such as those used by y-cruncher, so that might be an avenue worth exploring. [Answer] # Haskell, 231 bytes ``` import Data.List g(q,r,t,k,n,l)|4*q+r-t<n*t=n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l)|0<1=g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2) p=nubBy(\x y->length x==length y).concatMap inits.group$g(1,0,1,1,3,3) ``` This uses the [Unbounded Spigot Algorithms for the Digits of Pi](https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf) by Jeremy Gibbons, 2004. The result is `p`. Technically, it should support infinite output sequences, but that may take a while (and is bounded by your memory). [Answer] # Python 2, 298 bytes Note, the code for generating pi is taken from the OP's implementation. ``` def p(): q,r,t,j=1,180,60,2 while 1: u,y=3*(3*j+1)*(3*j+2),(q*(27*j-12)+5*r)//(5*t) yield y q,r,t,j=10*q*j*(2*j-1),10*u*(q*(5*j-2)+r-y*t),t*u,j+1 p=p() c=r=0 d=[0] while 1: t=p.next() if t==d[len(d)-1]:d.append(t) else:d=[t] if len(d)>r:r=len(d);print"".join([`int(x)`for x in d]) c+=1 ``` My first attempt at golfing in Python. Outputs the sequence forever. [Answer] # Python 3.5, ~~278~~ 263 bytes: ``` import decimal,re;decimal.getcontext().prec=int(input());D=decimal.Decimal;a=p=1;b,t=1/D(2).sqrt(),1/D(4) for i in[1]*50:z=(a+b)/2;b=(a*b).sqrt();t-=p*(a-z)**2;a=z;p*=2;pi=(z*2)**2/(4*t);i=0;C=lambda r:re.search(r'(\d)\1{%s}'%r,str(pi)) while C(i):print(C(i));i+=1 ``` This takes in `n` as an input for the first `n` digits of `π` and then outputs the members of the sequence in those first `n` digits. Now, this uses Python's built in [decimal module](https://docs.python.org/3.5/library/decimal.html) to go beyond Python's floating-point limitations, and then sets the precision, or epsilon, to however much the user inputs. Then, to calculate `π`, this goes through 50 iterations using the efficient [Gausse-Legendre algorithm](https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm), since the algorithm apparently doubles the number of correct digits each time, and therefore, in 50 iterations, we can get up to `2^50` or `1,125,899,906,842,624` correct digits. Finally, after the calculations are done, it uses a regular expression with string formatting in a `while` loop to find and print `re` match objects (which I hope is okay) for all continuous, recurring digits 1 digit longer than in the previous iteration through the loop. I was able to use this algorithm to successfully and accurately calculate `π` up to `10,000,000` (ten million) digits, which took about 4 hours and 12 minutes to complete. The following was the final output: ``` <_sre.SRE_Match object; span=(0, 1), match='3'> <_sre.SRE_Match object; span=(25, 27), match='33'> <_sre.SRE_Match object; span=(154, 157), match='111'> <_sre.SRE_Match object; span=(763, 767), match='9999'> <_sre.SRE_Match object; span=(763, 768), match='99999'> <_sre.SRE_Match object; span=(763, 769), match='999999'> <_sre.SRE_Match object; span=(710101, 710108), match='3333333'> ``` So, I can confidently say that the 8th number in the sequence does not even occur within the first 10 million digits! `π` is one random number... ]
[Question] [ Your program must take an input (`n` for the purpose of description) and output all permutations of a number that is `n` digits long with no repeating digits, where each of the digits preceding and including its index are divisible by the place in the number that it falls. You can read about magic numbers [here](https://en.wikipedia.org/wiki/Polydivisible_number). ## Rules: * `1 <= n <= 10` * No digits may be repeated * The leading 0 must be present (if applicable) * The 1st through `x`th digit of the number (starting with the first character as 1) must be divisible by `x`, i.e. in `30685`, `3` is divisible by 1, `30` is divisible by 2, `306` is divisible by 3, `3068` is divisible by 4, and `30685` is divislbe by 5. * The program must take an integer as input (through the command line, as a function argument, etc.) and print all permutations that satisfy the rules. * Output must be separated by 1 or more white space character * Permutations **may** start and with zero (so they're not *technically* magic numbers). * The order of output does not matter * You do **not** need to handle unexpected input * Least characters in bytes wins ## Examples Given 1: ``` 0 1 2 3 4 5 6 7 8 9 ``` Given 2: ``` 02 04 06 08 10 12 14 16 18 20 24 26 28 30 32 34 36 38 40 42 46 48 50 52 54 56 58 60 62 64 68 70 72 74 76 78 80 82 84 86 90 92 94 96 98 ``` Given 10: ``` 3816547290 ``` Credit to Pizza Hut & [John H. Conway](https://en.wikipedia.org/wiki/John_Horton_Conway) for the [original puzzle](http://blog.pizzahut.com/flavor-news/national-pi-day-math-contest-problems-are-here-2/) (Option A). Thanks to @Mego and @sp3000 for their [links](https://en.wikipedia.org/wiki/Polydivisible_number). [Answer] ## JavaScript (Firefox 30-57), 77 bytes ``` f=n=>n?[for(s of f(n-1))for(c of"0123456789")if(s.search(c)+(s+c)%n<0)s+c]:[""] ``` Edit: Saved 1 byte thanks to @edc65. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~20~~ ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` QḣQV%S ØDṗçÐḟRj⁷ ``` This is *very* slow and memory intensive... [Try it online!](http://jelly.tryitonline.net/#code=UeG4o1FWJVMKw5hE4bmXw6fDkOG4n1Jq4oG3&input=&args=Mg) ### How it works ``` ØDṗçÐḟRj⁷ Main link. Input: n (integer) ØD Yield d := '0123456789'. ṗ Compute the nth Cartesian power of d. R Range; yield [1, ..., n]. Ðḟ Filter false; keep strings of digits for which the following yields 0. ç Apply the helper link to each digit string and the range to the right. j⁷ Join the kept strings, separating by linefeeds. QḣQḌ%S Helper link. Arguments: s (digit string), r (range from 1 to n) Q Unique; deduplicate s. ḣ Head; get the prefixes of length 1, ..., n or less. If s had duplicates, the final prefixes fill be equal to each other. Q Unique; deduplicate the array of prefixes. V Eval all prefixes. % Compute the residues of the kth prefixes modulo k. If s and the array of prefixes have different lengths (i.e., if the digits are not unique), some right arguments of % won't have corr. left arguments. In this case, % is not applied, and the unaltered right argument is the (positive) result. S Add all residues/indices. This sum is zero iff all digits are unique and the kth prefixes are divisible by k. ``` [Answer] # Pyth, 19 bytes ``` jf!s%VsM._TS;.PjkUT ``` [Demonstration](https://pyth.herokuapp.com/?code=jf%21s%25VsM._TS%3B.PjkUT&input=3&debug=0) A brute force solution. Explanation to follow. Inspiration thanks to FryAmTheEggman --- # 22 bytes ``` juf!%sThH{I#sm+LdTGQ]k ``` [Demonstration](https://pyth.herokuapp.com/?code=juf%21%25sThH%7BI%23sm%2BLdTGQ%5Dk&input=9&debug=0) Numbers are built and stored as strings, and only converted to ints to check divisibility. Explanation: ``` juf!%sThH{I#sm+LdTGQ]k u Q]k Apply the following input many times, starting with [''] m G For each string at the previous step, +LdT Append each digit to it s Concatenate {I# Filter out strings with repeats f Filter on sT The integer % hH Mod the 1 indexed iteration number ! Is zero. j Join on newlines. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 30 bytes ``` 4Y2Z^!"@Sd@!U10G:q^/kPG:\~h?@! ``` [Try it online!](http://matl.tryitonline.net/#code=NFkyWl4hIkBTZEAhVTEwRzpxXi9rUEc6XH5oP0Ah&input=Mg) It's very slow. For `input 3` it takes a few seconds in the online compiler. To see the numbers appearing one by one, [include a `D` at the end of the code](http://matl.tryitonline.net/#code=NFkyWl4hIkBTZEAhVTEwRzpxXi9rUEc6XH5oP0AhRA&input=Mw). ### Explanation ``` 4Y2 % predefined literal: string '0123456789' Z^ % implicit input. Cartesian power: 2D char array. Each number is a row ! % transpose " % for each column @ % push current column Sd % sort and compute consecutive differences (*) @!U % push current column. Convert to number 10G:q^ % array [1 10 100 ... 10^(n-1)], where n is the input /k % divide element-wise. Round down P % reverse array G: % array [1 2 ... n] \~ % modulo operation, element-wise. Negate: gives 1 if divisible (**) h % concatenate (*) and (**). Truthy if all elements are nonzero ? % if so @! % current number as a row array of char (string) % implicitly end if % implicitly end if % implicitly display stack contents ``` [Answer] # Ruby, 87 bytes Basic recursive solution. ``` f=->n,x="",j=1{j>n ?puts(x):([*?0..?9]-x.chars).map{|i|f[n,x+i,j+1]if((x+i).to_i)%j<1}} ``` If you're allowed to return a list of the permutations instead of printing, 85 bytes: ``` f=->n,x="",j=1{j>n ?x:([*?0..?9]-x.chars).map{|i|f[n,x+i,j+1]if((x+i).to_i)%j<1}-[p]} ``` [Answer] ## Python, 132 bytes ``` lambda n:[x for x in map(("{:0%s}"%n).format,(range(10**n)))if all(int(x[:i])%i<1and len(set(x))==len(x)for i in range(1,len(x)+1))] ``` Dropped 26 bytes by getting rid of `itertools`, thanks to Sp3000 for making me realize I shouldn't be using it. Dropped 2 bytes by using a list comprehension rather than `filter`, thanks again to Sp3000 for the tip. Try it online: [Python 2](http://ideone.com/fork/4rq9QF), [Python 3](http://ideone.com/fork/vhnpps) ]
[Question] [ I have a specific number in mind, but it's part of a challenge I'm doing, and I don't want people to do (all) the work for me. Here is a number which has the same digits, but shuffled: ``` 5713167915926167134578399473447223554460066674314639815391281352328315313091488448321843 8892917486601064146636679920143691047671721184150386045081532202458651561779976236919751 5521854951599379666116678853267398393892536121049731949764192014193648608210652358947001 6332620900065461061195026191178967128001712341637591690941978871368243245270800684616029 6679555942849366434586090627998161441134473428845367022486230724219981658438108844675033 4461550796750244527407413996606134735852639191026103378962082622204359677030054592798927 4145951979523473408718011778751084514127053772614511042703365596651912104541233491744530 87457854312602843967491787086250478422477028164189 ``` The number has 666 digits (decimal). Because I'm using Python, integers (or technically longs) are automatically bignums. I have 255 chars to use, and I need to describe the same number. The description is meant to be run through eval() to produce the original number. What strategies should I be looking into? [Answer] ## Base Encoding A standard technique for compressing numbers is to express them in a big base and encode the digits as characters. E.g. if you encode the number in base 256, it would have only 277 digits: ``` [12 24 156 48 101 149 235 32 96 92 20 203 202 164 144 71 193 127 112 77 141 79 210 183 98 155 16 151 65 198 26 236 83 221 220 129 169 254 43 124 245 25 176 182 167 124 95 191 77 25 233 139 190 7 135 2 149 90 163 163 106 193 220 253 109 129 57 219 91 157 218 18 223 11 171 113 209 173 207 123 110 220 79 139 176 143 171 7 30 35 231 151 172 83 120 114 119 47 217 227 50 105 236 91 161 226 112 16 170 57 162 147 36 89 26 9 122 164 15 15 243 108 30 14 233 139 103 137 82 169 2 57 54 71 154 136 23 203 137 10 219 153 24 168 42 218 165 125 185 183 241 91 193 85 195 71 186 18 98 34 196 78 6 193 252 8 177 94 5 24 137 183 127 129 9 77 149 73 148 193 62 220 146 33 130 21 209 153 229 105 100 188 87 235 203 104 207 161 20 17 102 150 252 120 242 222 233 248 114 217 142 31 196 42 161 173 0 244 9 213 178 152 122 170 136 230 135 132 245 69 9 196 231 147 8 175 48 98 101 23 162 144 190 200 62 226 61 27 200 15 232 12 105 187 184 4 121 252 171 240 230 94 161 151 131 209 205 130 193 9 4 155 92 48 59 130 93] ``` Or expressed as a string ``` " 0eë `\ËʤGÁpMOÒ·bAÆìSÝÜ©þ+|õ°¶§|_¿Mé¾Z££jÁÜým9Û[Úß «qÑ­Ï{nÜO°«#ç¬Sxrw/Ùã2iì[¡âpª9¢$Y z¤ólégR©96GË Û¨*Ú¥}¹·ñ[ÁUÃGºb\"ÄNÁü±^· MIÁ>Ü!Ñåid¼WëËhÏ¡füxòÞéørÙÄ*¡­ô Õ²zªæõE Äç¯0be¢¾È>â=Èè i»¸yü«ðæ^¡ÑÍÁ \0;]" ``` (Plus some unprintable characters which are stripped by SE.) Of course, that's still too long for your 255 character allowance. If you're actually talking about *characters* though (as opposed to bytes), you can go into Unicode and use a much bigger base. How about 216? That's only 139 digits: ``` [12 6300 12389 38379 8288 23572 52170 42128 18369 32624 19853 20434 46946 39696 38721 50714 60499 56796 33193 65067 31989 6576 46759 31839 48973 6633 35774 1927 661 23203 41834 49628 64877 33081 56155 40410 4831 2987 29137 44495 31598 56399 35760 36779 1822 9191 38828 21368 29303 12249 58162 27116 23457 57968 4266 14754 37668 22810 2426 41999 4083 27678 3817 35687 35154 43266 14646 18330 34839 52105 2779 39192 43050 55973 32185 47089 23489 21955 18362 4706 8900 19974 49660 2225 24069 6281 46975 33033 19861 18836 49470 56466 8578 5585 39397 26980 48215 60363 26831 41236 4454 38652 30962 57065 63602 55694 8132 10913 44288 62473 54706 39034 43656 59015 34037 17673 50407 37640 44848 25189 6050 37054 51262 57917 7112 4072 3177 48056 1145 64683 61670 24225 38787 53709 33473 2308 39772 12347 33373] ``` (I can't include the actual string here, because it contains some CJK characters that are banned by SE.) Now that seems more doable. You just need to be able to decode it in 116 characters. If you can't, Unicode has a lot more than 216 characters, so you could try using an even larger base. [Answer] **Prime Factorization** If the number has no interesting features, base encoding is the best way to do it. The next thing to do is look for interesting features of the number. The first one that comes to mind is that it may have factors of small primes (2,3,5,7, etc) raised to quite large powers. IF you have nothing else to go on, keep trying to divide by small primes and see what happens. If its factors include `2**4`, `3**4`, and `7**4`, you can write `big number *42**4` which is a few bytes shorter than `big number * 3111696` [Answer] # Recursive removal of largest square This approach removes the largest square number from N, repeatedly, until there's no value in continuing. ``` while(n>999*999): s = sqrt(n,2) print s,"** 2 +" n = n - s**2 print n ``` If you ignore the "\*\*2+" characters, this one comes out to approximately the same number of digits as the original number, on average. Making up for those 4 extra characters per iteration requires a bit of luck. In the case of your number, the result has 670 digits of square numbers, plus 7x"\*\*2+", another failure: ``` 755855006990505232214298076833020140623897728341856142793250050184099570268569900389346192358073922001480310798643405893673501405667458785677166605919485512157948819102093414848159820683798554799982163455753292781944741934237780592730586508786425528910736750640071037094033497266578109597923654387813828207885510302579581252831537751**2+ 33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165**2+ 187763197402063683206154659623192450644818397963460986292088297442441704645626089130**2+ 278760215056365252005927060531480627653626**2+ 639191600506542558482**2+ 25777519523**2+ 106673**2+ 103405 ``` By almost breaking even on average, this algorithm lends itself well to being used in conjunction with other algorithms (or even itself) to further reduce the numbers in the expression (at the cost of some parentheses). Those other algorithms can be more expensive, as they will be operating on significantly smaller numbers than the original. In the given example, a net gain could be had if a more expensive and effective algorithm could cut out 25% of the characters of `33300095205899066129442737321270515378501483166974896029394675779096351509514355500527819871697116193238261137790928953798777695127752032484956608505929119246433389165` (the second large value in the result) [Answer] # Nearby large powers This approach looks for [relatively] small numbers raised to some power that come close to the target number. In most cases restating N as A\*\*B+C will not be an improvement, but in some cases it will be. ``` def nearest_power(n): mindiff = 1 best = (n,1) for a in xrange(2,10000): b = math.log(n,a) if math.ceil(b)-b<mindiff: mindiff = math.ceil(b)-b print a,"**",b best = (a,b) if b-math.floor(b)<mindiff: mindiff = b-math.floor(b) print a,"**",b best = (a,b) return best ``` `10000` is an arbitrary constant. The bail-out condition could also be based on some target `mindiff`. In the case of your sample number N with 666 digits, this function (with the 10k cap increased a bit) finds that `N ~= 165661162**81.0000000025`, so `N-165661162**81` is a 659 digit number, cutting 7 digits off the number to be handled at a cost of 14 characters of expression, a failure. ]
[Question] [ Given an input `n` where `3 <= n <= 25`, perform the following steps, starting with a single `n`-sided die (faces in the range `[1, n]`, inclusive): 1. Print the result of rolling the current `n`-sided dice in play, in the form `kdn: X` (where `X` is the result and `k` is the number of dice in play). 2. If `X` is greater than or equal to `n/2` times the number of dice in play, add a die. Else, remove a die. 3. If the number of dice in play is equal to `0` or `n`, stop. Else, go to step 1. Example runs (note that the output in parentheses is for explanation and is not required): 6-sided: ``` 1d6: 4 (avg: 3.0, add) 2d6: 6 (avg: 6.0, add) 3d6: 9 (avg: 9.0, add) 4d6: 16 (avg: 12.0, add) 5d6: 13 (avg: 15.0, remove) 4d6: 9 (avg: 12.0, remove) 3d6: 5 (avg: 9.0, remove) 2d6: 7 (avg: 6.0, add) 3d6: 11 (avg: 9.0, add) 4d6: 14 (avg: 12.0, add) 5d6: 17 (avg: 15.0, add) ``` 9-sided: ``` 1d9: 7 (avg: 4.5, add) 2d9: 14 (avg: 9.0, add) 3d9: 18 (avg: 13.5, add) 4d9: 18 (avg: 18.0, add) 5d9: 28 (avg: 22.5, add) 6d9: 26 (avg: 27.0, remove) 5d9: 28 (avg: 22.5, add) 6d9: 34 (avg: 27.0, add) 7d9: 33 (avg: 31.5, add) 8d9: 30 (avg: 36.0, remove) 7d9: 29 (avg: 31.5, remove) 6d9: 35 (avg: 27.0, add) 7d9: 32 (avg: 31.5, add) 8d9: 42 (avg: 36.0, add) ``` ## Rules * Outputs must be exactly in the format `kdn: X`, with newlines separating each roll * You must actually simulate rolling multiple dice; simply returning a random integer in the range `[1, n]` (inclusive) multiplied by the number of dice currently in play is not allowed, as that does not accurately simulate rolling multiple dice. * Standard loopholes are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 65904; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Pyth, 37 bytes ``` J1W%JQs[J\dQ\:dKsmhOQJ)=J+WgK*JcQ2tJ2 ``` [Try it online.](https://pyth.herokuapp.com/?code=J1W%25JQs%5BJ%5CdQ%5C%3AdKsmhOQJ)%3DJ%2BWgK*JcQ2tJ2&input=6&debug=0) [Answer] ## Mathematica, ~~95~~ ~~89~~ 80 characters ``` For[k=1,0<k<#,If[Print[k,d,#,": ",x=Tr[{1,#}~RandomInteger~k]];x<k/2#,k--,k++]]& ``` **Ungolfed** ``` For[ k = 1, 0 < k < #, If[ Print[k, d, #, ": ", x = Tr[{1, #}~RandomInteger~k]]; x < k/2 #, k--, k++ ] ] & ``` [Answer] # PHP, ~~164~~ ~~121~~ ~~112~~ ~~113~~ 109 bytes Final version, I promise. Improved using Titus' suggestion: ``` function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x: $r\n";$y+=$r/$y>$x/2?:-1;$y<$x&&$y?d($x,$y):0;} ``` --- EDIT: Added an extra byte for formatting. Forgot there's an IF in there that, thanks to dropping the "add/sub" text, could have been a ternary operator: ``` function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x: $r\n";$r/$y>$x/2?$y++:$y--;if($y<$x&&$y)d($x,$y);} ``` Output now looks like: ``` 1d6: 5 2d6: 11 3d6: 8 2d6: 11 3d6: 7 2d6: 4 1d6: 5 ``` --- EDIT: Thanks to @Manatwork, saved me a lot! New and imrpoved version: ``` function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x=$r\n";if($r/$y>$x/2)$y++;else$y--;if($y<$x&&$y){d($x,$y);}} ``` --- Previous entry: ``` function d($x,$y){for($i=0;$i<$y;$i++)($r+=rand(1,$x));$s=$y."d$x=$r, ";if($r/$y>$x/2){$y++;$s.="add";}else{$y--;$s.="sub";}echo $s."\n";if($y<$x&&$y>0){d($x,$y);}}` ``` Rolls separate dies, outputs this: ``` 1d6=6, add 2d6=7, add 3d6=11, add 4d6=14, add 5d6=15, sub 4d6=15, add 5d6=18, add ``` And it's called thusly: `d(6, 1);` Is displaying the `Add` and `Sub` suffix mandatory? This is unclear from your question. [Answer] # Python 3, 125 Saved 3 bytes thanks to DSM. ``` def x(d): import random;c=1 while 0<c<d:r=sum(map(random.randint,[1]*c,[d]*c));print('%id%i: %i'%(c,d,r));c+=2*(r>=d*c/2)-1 ``` Pretty simple, rolls a bunch of dice and checks the average. Nothing too fancy here yet. It needs to be called with an int. So, `x(6)` will produce something like this: ``` 1d6: 5 2d6: 10 3d6: 8 2d6: 7 3d6: 11 4d6: 8 3d6: 13 4d6: 19 5d6: 13 4d6: 15 5d6: 22 ``` . [Answer] ## JavaScript (ES6), 97 ~~102~~ ~~106~~ ~~112~~ bytes Thanks @user81655 and @Jupotter for saving me a few bytes. ``` f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=k;i--;)x+=Math.random()*n|0} // 102 bytes: f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=0;++i<=k;)x+=1+Math.random()*n|0} // Previous attempt, 112 bytes f=n=>{k=1;while(k&&k!=n){for(x=i=0;i++<=k;)x+=1+~~(Math.random()*n);console.log(k+`d${n}: `+x);k+=x<k*n/2?-1:1}} ``` ### Demo This only works in ES6 compliant browsers (at the moment that includes Firefox and Edge, possibly with Chrome and Opera with experimental JavaScript features enabled): ``` f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=k;i--;)x+=Math.random()*n|0} // Snippet stuff console.log = x => { document.getElementById('O').innerHTML += x + `<br>`; } document.getElementById('F').addEventListener('submit', e => { document.getElementById('O').innerHTML = `` f(document.getElementById('I').valueAsNumber) }) ``` ``` <form id=F action=# method=get> <label> Number of faces: <input type=number min=3 max=25 value=9 required id=I> </label> <button>Play</button> <div> <output id=O></output> </div> </form> ``` [Answer] # CJam, 45 bytes ``` ri:M;{X__{Mmr+}*[X'dM':S5$N]o_+XM*<_+(-:XM%}g ``` [Try it online.](http://cjam.aditsu.net/#code=ri%3AM%3B%7BX__%7BMmr%2B%7D*%5BX%27dM%27%3AS5%24N%5Do_%2BXM*%3C_%2B(-%3AXM%25%7Dg&input=6) Implements the spec pretty literally (including the mathematically incorrect "mean roll" formula). As expected, porting the original GolfScript program below to CJam saved a bunch of bytes due to shorter built-in command names (`mr`, `o` and `g` instead of `rand`, `puts` and `do`). # GolfScript, 51 bytes ``` ~:&;{1..{&rand+}*[1"d"&": "4$]puts.+1&*<.+(-:1&%}do ``` Here's my original GolfScript entry. Notable golfing tricks include [using the number `1` as a conveniently pre-initialized variable](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript/52039#52039) to store the current number of dice to to be rolled. (The CJam version instead uses `X`, which CJam initializes to the value 1.) --- **Ps.** Seeing the title, I originally wanted to answer this in [AnyDice](http://anydice.com/). But it turns out to be a *horrible* choice for this challenge, and I don't think it's even technically possible to use it to implement this spec as given. The problem is that AnyDice is a domain-specific language for writing *deterministic* programs to calculate dice rolling statistics. While inspecting the possible outcomes of a roll and doing conditional rolls based on them *is* possible via recursion, there's no way to generate any actual randomness. So while you could simulate this sequence of dice rolls in AnyDice, all you can get as output is statistics on things like, say, the number of rolls until the process ends, or the distribution of results at a given step. All that said, [here's the closest I could get in AnyDice](http://anydice.com/program/72c9): ``` N: 6 K: 1 function: clip X:n { result: X * (X < N) } function: adjust X:n { result: [clip X + ((XdN)*2 >= X*N)*2-1] * (X > 0) } loop I over {1..20} { output K named "dice in roll [I]" output KdN named "outcome of roll [I]" K: [adjust K] } ``` This isn't particularly golfed code, since that seemed like an exercise in futility. Standard brace language golfing tricks, like shortening function names and eliminating unnecessary whitespace, should exhaust most of the golfing potential anyway. The key trick used here is that, when you call a function expecting a number (as indicated by the `:n` in the function definition) in AnyDice, and pass it a die (i.e. a probability distribution) instead, AnyDice automatically evaluates the function for *all possible values* of the die, and combines the results into a new die. Here's a screenshot of the output (in bar chart format) for the first three rolls: [![AnyDice screenshot](https://i.stack.imgur.com/a0kMS.png)](http://anydice.com/program/72c9) (Note that the "0" column in each graph indicates the probability that the iteration stopped, due to the number of dice hitting *either* 0 or N, before the current roll. This happens to be a convenient way to represent the stopping condition, since of course rolling 0dN always yields 0.) [Answer] # R, 103 Bytes A fairly straight forward implementation. Dice rolls are done by `sum(sample(n,i))`. ``` i=1;n=scan();while(i&i<=n){cat(i,'d',n,': ',s<-sum(sample(n,i)),'\n',sep='');i=ifelse(s<i*n/2,i-1,i+1)} ``` Test run ``` > i=1;n=scan();while(i&i<=n){cat(i,'d',n,': ',s<-sum(sample(n,i)),'\n',sep='');i=ifelse(s<i*n/2,i-1,i+1)} 1: 9 2: Read 1 item 1d9: 9 2d9: 14 3d9: 10 2d9: 14 3d9: 9 2d9: 9 3d9: 12 2d9: 7 1d9: 9 2d9: 11 3d9: 17 4d9: 18 5d9: 25 6d9: 29 7d9: 33 8d9: 43 9d9: 45 > ``` [Answer] ## CoffeeScript, ~~106~~ 99 bytes ``` f=(n,k=1)->(x=k;x+=Math.random()*n|0for[k..0];console.log k+"d#{n}: "+x;k+=x<k*n/2&&-1||1)while k%n # Previous attempt, 106 bytes f=(n,k=1)->(x=i=0;x+=1+Math.random()*n//1while++i<=k;console.log k+"d#{n}: "+x;k+=x<k*n/2&&-1||1)while k%n ``` ### Ungolfed ``` f = (n, k = 1) -> (x = k x += 1 + Math.random() * n | 0 for [k..0] console.log k + "d#{n}: " + x k += x < k * n / 2 && -1 || 1 ) while k % n ``` [Answer] # Julia, 77 bytes ``` n->(N=1;while 0<N<n k=sum(rand(1:n,N));print(N,"d$n: $k ");N+=1-2(2k<N*n)end) ``` Most of this should be self-explanatory - an actual newline is being used in the `print` string rather than using `println` to save a byte. `rand(1:n,N)` produces `N` random integers between 1 and `n`. [Answer] # Ruby, ~~93~~ ~~90~~ 82 characters ``` ->n{d=s=2 puts"#{d}d#{n}: #{s=eval'+rand(n)+1'*d}"while(d+=s<d*n/2.0?-1:1)>0&&d<n} ``` Sample run: ``` 2.1.5 :001 > -->n{d=s=2;puts"#{d}d#{n}: #{s=eval'+rand(n)+1'*d}"while(d+=s<d*n/2.0?-1:1)>0&&d<n}[6] 1d6: 5 2d6: 10 3d6: 6 2d6: 5 1d6: 5 2d6: 8 3d6: 15 4d6: 18 5d6: 22 ``` [Answer] ## PHP, 104 bytes ``` for($n=$argv[$k=1];$k&&$k<$n;print$k."d$n: $x\n",$k-=$x<$n*$k/2?:-1)for($x=$i=0;$i++<$k;)$x+=rand(1,$n); ``` Run with `php -r '<code>' <N>` **breakdown** ``` for($n=$argv[$k=1]; // import input, init number of dice $k&&$k<$n; // while 0<$k<$n print$k."d$n: $x\n", // 2. print results $k-=$x<$n*$k/2?:-1 // 3. remove or add a die ) for($x=$i=0;$i++<$k;) // 1. roll dice separately $x+=rand(1,$n); // sum up results ``` [Answer] ## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), 83 bytes ``` :c=a{e=0[1,q|e=e+_rq,a|]?!q$+@d|!+a$+@:|+!e$~e<c/2|q=q-1\q=q+1]c=q*a~q=a|_X]~q=0|_X ``` Explanation: ``` q Tracks the number of dice (is implicitly 1 at the start) : Takes input from a CMD line parameter [1,q|e=e+_rq,a|] Rolls the dice separately ?!q$+@d|!+a$+@:|+!e$ Prints the roll result (requires an unfortunate amount of casting...) ~e<c/2|q=q-1\q=q+1] Checks whether to increase or decrease ~q=a|_X]~q=0|_X Tests the amount of dice and quits on either boundary. ``` [Answer] ## Python 3, 131 bytes ``` def f(n): import random;k=1 while 0<k<n: r=sum([random.randint(1,n)for _ in range(k)]);print(f'{k}d{n}: {r}');k+=2*(r>=k*n/2)-1 ``` [Try it online!](https://tio.run/##PYvtCoIwGEZ/u6vYv@21Tw0knetGIiLQ5Vi@G29GhHjtKxH69cB5zgmfofN4OAaKsWkNNxKhYontg6eB0w0b3yunM5a8O/to@b52Nf6EhPTz1cvzYmznsTjIbI1gPPErtzjX91Y6uIAKNL9GjG5qRpwqPtIkQLmVzlNJJ@1S3OWwyeIiCtRFJYAZWQD7o3JBJcQv "Python 3.8 (pre-release) – Try It Online") Explanation: ``` def f(n): # function header, doesn't need to use int(input()) import random;k=1 # initialize, can't use import* to save bytes while 0<k<n: # while k is in between 0 and n: r=sum([random.randint(1,n)for _ in range(k)]); # roll k dice and add them up print(f'{k}d{n}: {r}'); # print to console, concatenation would take up even more bytes k+=2*(r>=k*n/2)-1 # add dice if r is >= to k*n/2, else remove dice ``` ]
[Question] [ Your task to to solve the SLCSC problem, which consists in finding the shortest possible code to solve the [Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). A valid solution to the LCS problem for two or more strings **S1, … Sn** is any string **T** of maximal length such that the characters of **T** appear in all **Si**, in the same order as in **T**. Note that **T** does not have to be a sub*string* of **Si**. ### Example The strings `axbycz` and `xaybzc` have 8 common subsequences of length 3: ``` abc abz ayc ayz xbc xbz xyc xyz ``` Any of these would be a valid solution for the LCS problem. ### Details Write a program or a function that solves the LCS problem, as explained above, abiding the following rules: * The input will consist of two or more strings containing only lowercase letters. You may read those strings as an array of strings or a single string with a delimiter of your choice. * Your code must output any single one of the possible solutions to the problem, optionally followed by a linefeed or surrounded by quotes. * You may assume that the strings are shorter than 1000 characters and that there are at most 20 strings. Within these limits, your code should work as expected *in theory* (given unlimited time and memory). * Your code must complete the combined test cases of the next section in under an hour on my machine (Intel Core i7-3770, 16 GiB RAM). **Approaches that simply iterate over all possible subsequences will not comply with the time limit.** * Using built-ins that trivialize this task, such as [`LongestCommonSequence`](https://reference.wolfram.com/language/ref/LongestCommonSequence.html), is not allowed. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ### Test cases ``` a ab ``` Output: `a` --- ``` aaaaxbbbb bbbbxcccc ccccxaaaa ``` Output: `x` --- ``` hxbecqibzpyqhosszypghkdddykjfjcajnwfmtfhqcpavqrtoipocijrmqpgzoufkjkyurczxuhkcpehbhpsuieqgjcepuhbpronmlrcgvipvibhuyqndbjbrrzpqbdegmqgjliclcgahxoouqxqpujsyfwbdthteidvigudsuoznykkzskspjufgkhaxorbrdvgodlb qnnprxqpnafnhekcxljyysobbpyhynvolgtrntqtjpxpchqwgtkpxxvmwwcohxplsailheuzhkbtayvmxnttycdkbdvryjkfhshulptkuarqwuidrnjsydftsyhuueebnrjvkfvhqmyrclehcwethsqzcyfvyohzskvgttggndmdvdgollryqoswviqurrqhiqrqtyrl ``` Output: `hxbbpyhogntqppcqgkxchpsieuhbncvpuqndbjqmclchqyfttdvgoysuhrrl` or any other common subsequence of the same length --- ``` riikscwpvsbxrvkpymvbbpmwclizxlhihiubycxmxwviuajdzoonjpkgiuiulbjdpkztsqznhbjhymwzkutmkkkhirryabricvhb jnrzutfnbqhbaueicsvltalvqoorafnadevojjcsnlftoskhntashydksoheydbeuwlswdzivxnvcrxbgxmquvdnfairsppodznm kzimnldhqklxyezcuyjaiasaeslicegmnwfavllanoolkhvqkjdvxrsjapqqwnrplcwqginwinktxnkfcuuvoyntrqwwucarfvjg ``` Output: `icsvllvjnlktywuar` or any other common subsequence of the same length --- ``` rblartqkfggrjpiipuzzypkycnyckkcqceeujiyy yfpnedyjtiwrhyuktripdwyvgkblzodeufkelhub ywcyboxwqkibwvredkrbdsyudkulpvmhixeqxynh bnxwahbzhwjxkotnvbxrojkkldtsodtjmvdrmbgr ``` Output: `krkk` or any other common subsequence of the same length --- ``` bwfscmotshoczmduwaev coywaaizdaxjovipsmeh dobzcpoiedenzlfdjpiu bbhfeqscvvbwkuoxdoge drqrzwbcpcsvneodelja ``` Output: `code` or any other common subsequence of the same length --- ``` nqrualgoedlf jgqorzglfnpa fgttvnogldfx pgostsulyfug sgnhoyjlnfvr wdttgkolfkbt ``` Output: `golf` or any other common subsequence of the same length --- ``` epopyfuhgowedpiqpgfj ddxyestqynpwmytxhozm ptubgzyqqksieoovuezv tovotqmnhgzttfpywjgr aomvytkgaijlgqzkljls vzvxpaixrnprxvenbbuo syfuwxlpcyontqlmfvib arxleuomstkjegpduwcx xgqrxaopouvkvwgbzewn yggunddigctgpnuztzai izroomywwztdymqszsuo kiawjnxjncdtufhkrjsp ``` Output: the empty string [Answer] # Python - ~~665~~ 644 Indentation levels: ``` 1: space 2: tab 3: tab + space 4: 2 tabs 5: 2 tabs + space ``` The code defines a function `o`, which takes a list of strings as arguments and returns one of the LCS's for the strings. ``` def o(t): t=[[y for y in x if y in reduce(lambda x,y:x.intersection(y),t,set(t[0]))]for x in t];l=map(len,t);C=[0]*reduce(lambda x,y:x*-~y,l,1);y=lambda z:[x-1for x in z];m=len(t);e=enumerate def g(h): r,x=0,1 for k,j in e(h):r+=-~j*x;x*=-~l[k] return r def f(h): i=len(h) if i==m: b=g(h);c=t[0][h[0]] for k,j in e(h): if t[k][j]!=c:break else:C[b]=1+C[g(y(h))];return r=0 for k,_ in e(h):a=h[:];a[k]-=1;r=max(r,C[g(a)]) C[b]=r;return for j,_ in e(t[i]):f(h+[j]) def p(h): if min(h)==-1:return'' v=C[g(h)] for k,_ in e(h): a=h[:];a[k]-=1 if v==C[g(a)]:return p(a) return p(y(h))+t[0][h[0]] f([]);return p(y(l)) ``` Test code: ``` tests = [ """ a ab """, """ aaaaxbbbb bbbbxcccc ccccxaaaa """, """ hxbecqibzpyqhosszypghkdddykjfjcajnwfmtfhqcpavqrtoipocijrmqpgzoufkjkyurczxuhkcpehbhpsuieqgjcepuhbpronmlrcgvipvibhuyqndbjbrrzpqbdegmqgjliclcgahxoouqxqpujsyfwbdthteidvigudsuoznykkzskspjufgkhaxorbrdvgodlb qnnprxqpnafnhekcxljyysobbpyhynvolgtrntqtjpxpchqwgtkpxxvmwwcohxplsailheuzhkbtayvmxnttycdkbdvryjkfhshulptkuarqwuidrnjsydftsyhuueebnrjvkfvhqmyrclehcwethsqzcyfvyohzskvgttggndmdvdgollryqoswviqurrqhiqrqtyrl """, """ riikscwpvsbxrvkpymvbbpmwclizxlhihiubycxmxwviuajdzoonjpkgiuiulbjdpkztsqznhbjhymwzkutmkkkhirryabricvhb jnrzutfnbqhbaueicsvltalvqoorafnadevojjcsnlftoskhntashydksoheydbeuwlswdzivxnvcrxbgxmquvdnfairsppodznm kzimnldhqklxyezcuyjaiasaeslicegmnwfavllanoolkhvqkjdvxrsjapqqwnrplcwqginwinktxnkfcuuvoyntrqwwucarfvjg """, """ rblartqkfggrjpiipuzzypkycnyckkcqceeujiyy yfpnedyjtiwrhyuktripdwyvgkblzodeufkelhub ywcyboxwqkibwvredkrbdsyudkulpvmhixeqxynh bnxwahbzhwjxkotnvbxrojkkldtsodtjmvdrmbgr """, """ bwfscmotshoczmduwaev coywaaizdaxjovipsmeh dobzcpoiedenzlfdjpiu bbhfeqscvvbwkuoxdoge drqrzwbcpcsvneodelja """, """ nqrualgoedlf jgqorzglfnpa fgttvnogldfx pgostsulyfug sgnhoyjlnfvr wdttgkolfkbt """, """ epopyfuhgowedpiqpgfj ddxyestqynpwmytxhozm ptubgzyqqksieoovuezv tovotqmnhgzttfpywjgr aomvytkgaijlgqzkljls vzvxpaixrnprxvenbbuo syfuwxlpcyontqlmfvib arxleuomstkjegpduwcx xgqrxaopouvkvwgbzewn yggunddigctgpnuztzai izroomywwztdymqszsuo kiawjnxjncdtufhkrjsp """ ] for s in tests: print o(s.strip().split()) ``` Time it takes to run the tests on my computer: ``` $ time python 52808-shortest-longest-common-subsequence-code-golfed.py a x hecbpyhogntqtpcqgkxchpsieuhbncvhuqndbjqmclchqyfhtdvgoysuhrrl icsvllvanlktywuar krkk code golf 9.03 real 8.99 user 0.03 sys ``` [Answer] # CJam, 31 ``` q~L{_:&\f{_2$f#:).>j+}{,}$W>s}j ``` [Try it online](http://cjam.aditsu.net/#code=q~L%7B_%3A%26%5Cf%7B_2%24f%23%3A).%3Ej%2B%7D%7B%2C%7D%24W%3Es%7Dj&input=%5B%22nqrualgoedlf%22%0A%22jgqorzglfnpa%22%0A%22fgttvnogldfx%22%0A%22pgostsulyfug%22%0A%22sgnhoyjlnfvr%22%0A%22wdttgkolfkbt%22%5D) 9 bytes golfed thanks to Dennis! **Explanation:** This algorithm tries every possible character for the first position of the subsequence, replaces each string with the substring after the first occurrence of that character, and then calls itself recursively (with memoization). ``` q~ read and evaluate the input (taken as an array) L{…}j execute block with recursive memoization and no starting values _ duplicate the array of strings :&\ intersect the strings as character sets and move before the array these are all the possible characters for the sequence f{…} for each character and the array _2$ duplicate the array and the character f# find the character position in each string :) increment the positions (to skip the character) .> slice each string starting at the corresponding position j call the j block recursively + concatenate the starting character with the result {,}$ sort resulting strings (one for each character) by length W> keep only the last element, if any s convert (from 0/1-string array) to string ``` [Answer] # Pyth, ~~59~~ ~~58~~ ~~55~~ 35 bytes ``` L&@Fb?+yPMbeeb@FeMbeolNmyXJbdP@bdlb ``` Cut a whopping 20 bytes thanks to @isaacg! 55 byte version: ``` DCHR?k!&.AH@FH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH ``` Cut off 3 bytes by changing `.U@bZ` to `@F` (the fold operator). 58 byte version: ``` DCHR?k!&.AH.U@bZH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH ``` Cut off a byte by changing the format of a boolean conditional. 59 byte version: ``` DCHR?k|!.AH!.U@bZH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH ``` This was hard! Python kept segfaulting! Pretty sure it was some kind of bug, but I couldn't get a minimal test case. Oh well. I based the algorithm off of [this one](http://rosettacode.org/wiki/Longest_common_subsequence#C.23). Which is fine, except that that one is designed for only two strings. I had to tweak it a bit to make it work on more. Then, the last test case was taking too long, so I had to add an additional check to exit the recursion if there are no more common characters. It's pretty slow, but *should* take less than an hour (hopefully). I'm testing on my Core i3 with 6 GB of RAM, so your 16-GB Core i7 should blow through this. :) I also took advantage of Pyth's auto-memoizing functions to make it a bit faster. **EDIT**: @Dennis said it passes! To test it, add the following line: ``` CQ ``` and give it a list of strings via standard input (e.g. `['a', 'ab']`). ## Explanation for the 35 byte version: WIP. ## Explanation for the 55 byte version: ``` DCH define a function C that takes a list of strings H R return the following expression ? if !&.AH@FH there are no more common letters OR all the strings are empty k return the empty string ? ql{medH1 else if the last character of every string is equal +Cm<1dHeeH return the result of adding the last character to recursion with every item without its last character h.MlZ.eC++<Hk]<1b>HhkH otherwise, return the largest result of recursing len(H) times, each time with one element's last character cut off ``` [Answer] # C, ~~618~~ 564 bytes ``` d,M,N,A[9999][2];char*(R[9999][20]),b[1000];L(char**s,n){char*j[20],c,a=0;int x[n],y=n-1,z,i,t,m=0,w=1;for(;y;)x[y--]=999;for(;y<N;y++){for(i=0;i<n&&s[i]==R[y][i];i++);if(i/n){a=A[y][0];m=A[y][1];w=0;if(m+d<M||!a)goto J;else{c=a;goto K;}}}for(c=97;w&&c<'{';c++){K:t=1,y=1,z=1;for(i=0;i<n;j[i++]++){for(j[i]=s[i];*j[i]-c;j[i]++)t&=!!*j[i];y&=j[i]-s[i]>x[i]?z=0,1:0;}t&=!y;I:if(t){if(z)for(i=0;i<n;i++)x[i]=j[i]-s[i];d++,t+=L(j,n),d--,m=t>m?a=c,t:m;}}if(w){for(y=0;y<n;y++)R[N][y]=s[y];A[N][0]=a;A[N++][1]=m;}J:if(d+m>=M)M=d+m,b[d]=a;if(!d)N=0,M=0,puts(b);return m;} ``` And here it is unraveled, for "readability": ``` d,M,N,A[9999][2]; char*(R[9999][20]),b[1000]; L(char**s,n){ char*j[20],c,a=0; int x[n],y=n-1,z,i,t,m=0,w=1; for(;y;) x[y--]=999; for(;y<N;y++){ for(i=0;i<n&&s[i]==R[y][i];i++); if(i/n){ a=A[y][0]; m=A[y][1]; w=0; if(m+d<M||!a) goto J; else{ c=a; goto K; } } } for(c=97;w&&c<'{';c++){ K: t=1, y=1, z=1; for(i=0;i<n;j[i++]++){ for(j[i]=s[i];*j[i]-c;j[i]++) t&=!!*j[i]; y&=j[i]-s[i]>x[i]?z=0,1:0; } t&=!y; I: if(t){ if(z) for(i=0;i<n;i++) x[i]=j[i]-s[i]; d++, t+=L(j,n), d--, m=t>m?a=c,t:m; } } if(w){ for(y=0;y<n;y++)R[N][y]=s[y]; A[N][0]=a; A[N++][1]=m; } J: if(d+m>=M) M=d+m,b[d]=a; if(!d) N=0,M=0,puts(b); return m; } ``` Ladies and gentlemen, I've made a horrible mistake. It *used* to be prettier... And goto-less... At least now it is **fast**. We define a recursive function `L` that takes as input an array `s` of arrays of characters and the number `n` of strings. The function outputs the resulting string to stdout, and incidentally returns the size in characters of that string. ### The Approach Though the code is convoluted, the strategy here is not all too complex. We start with a rather naive recursive algorithm, which I will describe with pseudocode: ``` Function L (array of strings s, number of strings n), returns length: Create array of strings j of size n; For each character c in "a-z", For each integer i less than n, Set the i'th string of j to the i'th string of s, starting at the first appearance of c in s[i]. (e.g. j[i][0] == c) If c does not occur in the i'th string of s, continue on to the next c. end For new_length := L( j, n ) + 1; // (C) t = new_length if new_length > best_length best_character := c; // (C) a = best_character best_length := new_length; // (C) m = best_length end if end For // (C) d = current_depth_in_recursion_tree if best_length + current_depth_in_recursion_tree >= best_found prepend best_character to output_string // (C) b = output_string // (C) M = best_found, which represents the longest common substring found at any given point in the execution. best_found = best_length + current_depth; end if if current_depth_in_recursion_tree == 0 reset all variables, print output_string end if return best_length ``` Now, this algorithm on its own is pretty atrocious (but can be fit in around ~230 bytes, I've found). This is not how one gets speedy results. This algorithm scales incredibly poorly with string length. This algorithm *does*, however, scale fairly well with larger numbers of strings. The last test case would be solved virtually instantly, since no strings in `s` have any characters `c` in common. There were two main tricks I've implemented above that resulted in an incredible speed increase: * At every call to `L`, check if we've been given this same input before. Since in practice information is passed around via pointers to the same set of strings, we don't *actually* have to compare strings, just locations, which is great. If we find that we've gotten this information before, there's no need to run through the calculations (most of the time, but getting output makes this a bit more complicated) and we can get away with just returning the length. If we do *not* find a match, save this set of input/output to compare to future calls. In the C code, the second `for` loop attempts to find matches to the input. Known input pointers are saved in `R`, and the corresponding length and character output values are stored in `A`. This plan had a drastic effect on runtime, especially with longer strings. * Every time we find the locations of `c` in `s`, there's a chance we know right off the bat that what we've found isn't optimal. If every location of `c` appears *after* some known location of another letter, we **automatically know** that this `c` does not lead to an optimal substring, because you can fit one more letter in it. This means that for a small cost, we can potentially remove several hundred calls to `L` for large strings. In the above C code, `y` is a flag set if we automatically know that this character leads to a suboptimal string, and `z` is a flag set if we find a character that has exclusively earlier appearances than any other known character. The current earliest appearances of characters are stored in `x`. The current implementation of this idea is a bit messy, but nearly doubled performance in many instances. With these two ideas, what didn't finish in an hour now took about 0.015 seconds. There are probably plenty more little tricks that can speed up performance, but at this point I started worrying about my ability to golf everything. I'm still not content with the golf, so I'll likely come back to this later! ### Timings Here's some testing code, which I invite you to try [online](http://ideone.com/XoVpyn): ``` #include "stdio.h" #include "time.h" #define SIZE_ARRAY(x) (sizeof(x) / sizeof(*x)) int main(int argc, char** argv) { /* Our test case */ char* test7[] = { "nqrualgoedlf", "jgqorzglfnpa", "fgttvnogldfx", "pgostsulyfug", "sgnhoyjlnfvr", "wdttgkolfkbt" }; printf("Test 7:\n\t"); clock_t start = clock(); /* The call to L */ int size = L(test7, SIZE_ARRAY(test7)); double dt = ((double)(clock() - start)) / CLOCKS_PER_SEC; printf("\tSize: %d\n", size); printf("\tElapsed time: %lf s\n", dt); return 0; } ``` I ran the OP's test cases on a laptop equipped with a 1.7 GHz Intel Core i7 chip, with an optimization setting of `-Ofast`. The simulation reported a peak of 712KB required. Here's an example run of each test case, with timings: ``` Test 1: a Size: 1 Elapsed time: 0.000020 s Test 2: x Size: 1 Elapsed time: 0.000017 s Test 3: hecbpyhogntqppcqgkxchpsieuhbmcbhuqdjbrqmclchqyfhtdvdoysuhrrl Size: 60 Elapsed time: 0.054547 s Test 4: ihicvaoodsnktkrar Size: 17 Elapsed time: 0.007459 s Test 5: krkk Size: 4 Elapsed time: 0.000051 s Test 6: code Size: 4 Elapsed time: 0.000045 s Test 7: golf Size: 4 Elapsed time: 0.000040 s Test 8: Size: 0 Elapsed time: 0.000029 s Total time: 0.062293 s ``` In golfing, I hit performance rather significantly, and since people seemed to like the brute speed (0.013624 s to complete all test cases combined) of my previous 618-byte solution, I'll leave it here for reference: ``` d,M,N,A[9999][2];char*(R[9999][20]),b[1000];L(char**s,n){char*j[20],c,a=0;int x[n],y,z,i,t,m=0,w=1;for(y=0;y<n;y++)x[y]=999;for(y=0;y<N;y++){for(i=0;i<n;i++)if(s[i]!=R[y][i])break;if(i==n){a=A[y][0];m=A[y][1];w=0;if(m+d<M||!a)goto J;else{c=a;goto K;}}}for(c=97;w&&c<'{';c++){K:t=1,y=1,z=1;for(i=0;i<n;j[i++]++){for(j[i]=s[i];*j[i]-c;j[i]++)if(!*j[i]){t=0;goto I;}if(j[i]-s[i]>x[i])z=0;if(j[i]-s[i]<x[i])y=0;}if(y){t=0;}I:if(t){if(z){for(i=0;i<n;i++){x[i]=j[i]-s[i];}}d++,t+=L(j,n),d--,m=t>m?(a=c),t:m;}}if(w){for(y=0;y<n;y++)R[N][y]=s[y];A[N][0]=a;A[N++][1]=m;}J:if(d+m>=M)M=d+m,b[d]=a;if(!d)N=0,M=0,puts(b);return m;} ``` The algorithm itself is unchanged, but the new code relies on divisions and some trickier bitwise operations that end up slowing the whole thing down. [Answer] # Python 2, 285 Code: ``` import re def f(s,a,b): if b==[]:return s+f('',[],a) if a==[]:return s+max([f(b[0][i],[b[0][i+1:]],b[1:]) for i in range(len(b[0]))],key=len) if b[0]!='' else '' return max([f(s,a+[b[0][i.start()+1:]],b[1:]) for i in re.finditer(s[-1],b[0])],key=len) if ~b[0].find(s[-1]) else '' ``` Usage: ``` print f('',[],['axbycz','xaybzc']) ``` Explanation: This is a recursive function. `s` is the character we are looking for. `a` contains list of strings sliced after `s`. `b` contains list of strings untouced yet. `f` returns the longest common string. The first condition checks if we finished to go through all the strings. if so, it means `s` is common character, and it returns `s` and looking for more common characters. The second condition checks if we don't start to go through any string, meaning we don't even have a character (`a==[]` is equivalent to `s==''`). if so we check each character of the first string in `b`. The last line moves the first string in `b` to `a`, by finding each occurrence of `s` in this string. On the first call, `s` should be empty string. `a` should be empty list and `b` should contains all the strings. ]
[Question] [ Sometimes, when I'm really bored (*really* bored), I like to draw a line segment and draw points on it. First, I draw a line segment of a certain size, which is 2^N for some value of N. The line will be represented by a series of `.` characters. ``` ................ ``` Then, I plot a point at the left end. Points will be represented by `X` characters. ``` X............... ``` Then, I follow a pattern. Starting at the most recently plotted point (which I'll call A), I advance to the next plotted point (B) on the line (wrapping around as necessary). Then, I advance to the *next* plotted point on the line (C). Then, I plot a new point half-way in between this third point (C) and the next already plotted point (D). Whenever you wrap around the line, the "middle" is determined in wrapping manner. The newly plotted point is always to the right of C. Let's say that the following line was my current line. Here is how I would plot the next two points. For this example, I'll label each important point with a letter. ``` X...A...X.X...X. ^ X...A...B.X...X. ^ X...A...B.C...X. ^ X...A...B.C...D. ^ X...X...X.X.A.X. ^ X...X...X.X.A.B. ^ C...X...X.X.A.B. ^ C...D...X.X.A.B. ^ X.A.X...X.X.X.X. ^ ``` Returning to the previous example, the next point will be plotted in the middle of the line. ``` X.......X....... ``` This is perhaps a little bit of a special case: advancing to the next point simply leaves you where you started. The only useful halfway point is the "cyclic" halfway point (the halfway point on the line), as opposed plotting a point on top of itself. Below is the series of points that I would plot on the line from here to the end. ``` X.......X....... X.......X...X... X.......X.X.X... X...X...X.X.X... X...X...X.XXX... X.X.X...X.XXX... X.X.X...XXXXX... ``` There is no longer any room to plot the next point, as it would have to be wedged between two adjacent points, so I have reached the maximum depth for the given value of N = 4. The last line in the above list is "complete." ## The Challenge The goal is to write the shortest program/named function that will print/return the completed line for a given value of N. The above shows N = 4. ## Input Input will be a single non-negative integer N. The length of the generated line will then be 2^N. ## Output Output will be the completed line of length 2^N, formed by `.` and `X` characters. A trailing newline doesn't matter. ## Example I/O ``` 0 X 1 XX 2 X.XX 3 X.X.XXX. 4 X.X.X...XXXXX... 5 X.X.X...X...X...X.XXX.XXX....... ``` [Answer] # Python 2, 137 ``` n=input() l=[0]*2**n;i=0 while~i%2:i=i/2%2**n;l[i]=1;i=sum([k for k,v in enumerate(l*4)if(k>i)*v][1:3]) print''.join(['.X'[x]for x in l]) ``` Quite straightforward. # Pyth, 49 More or less a translation. Main difference is that I don't use a list representing the line, I use a string. ``` J*\.^2QW!%Z2K%/Z2lJ=JXJK\X=Zs<tf&q\X@JT>TKU*4J2)J ``` Try it [online](https://pyth.herokuapp.com/?code=J*%5C.%5E2QW!%25Z2K%25%2FZ2lJ%3DJXJK%5CX%3DZs%3Ctf%26q%5CX%40JT%3ETKU*4J2)J&input=4&debug=0). ``` Q=input(); Z=0 #implicit J*\.^2Q J = "."*(2^Q) W!%Z2 while !(Z%2): K%/Z2lJ K=(Z/2)%(len(J)) =JXJK\X change J, the point at index K is changed to a "X" f U*4J filter all elements T in [0, 1, 2, ..., 4*len(J)-1]: &q\X@JT>TK where J[T]=='X' and T>K <t 2 only us the second and third element =Zs and store the sum to Z )J end while and print J ``` [Answer] # [Clip](http://esolangs.org/wiki/Clip), 95 ``` [z?zF#2(z*2*:(#2(z'.'X]'X]]n[Fa[b[q[j[r?=rirFrsrb'X]b]][t[u+*<ut*Blb/+tu2]]g+2jqg+3jq]#qa]%b'X} ``` [Answer] ## GolfScript (61 bytes) ``` ~2\?,[]0{.@|$4*.@?2+1$>2<.+~<!4$,*++.2/\1&!}do;`{&!'X.'1/=}+% ``` The number of loop iterations required seems to be [A061419](http://oeis.org/A061419), but the do-loop is shorter than calculating that. A divmod would save a char inside the do loop. The part which feels most wasteful is the output conversion, but I don't see how to improve it. [Answer] # CJam, ~~55 53 51~~ 50 bytes ``` 2ri#:N'.*0aN{):U+__Nf++$_U#))>2<1bNe|2/N%|}*{'Xt}/ ``` Something to start with. [Try it online here](http://cjam.aditsu.net/#code=2ri%23%3AN'.*0aN%7B)%3AU%2B__Nf%2B%2B%24_U%23))%3E2%3C1bNe%7C2%2FN%25%7C%7D*%7B'Xt%7D%2F&input=4) [Answer] # Java, ~~209~~ ~~207~~ ~~195~~ 191 bytes I'm surprised I was able to get it this short. There is probably still room for improvement. As usual, suggestions will be appreciated :) This returns a `char[]`. Call using `a(n)`. ``` char[]a;int b,c,d,e=2;char[]a(int f){java.util.Arrays.fill(a=new char[b=1<<f],'.');for(a[0]=88;d+1<e;c=(d+e)/2,a[c%b]=88)e=b(d=b(b(c)));return a;}int b(int f){for(;;)if(a[++f%b]>87)return f;} ``` Indented: ``` char[] a; int b, c, d, e = 2; char[] a(int f){ java.util.Arrays.fill( a = new char[ b = 1 << f ] , '.' ); for( a[0] = 88; d + 1 < e; c = (d + e) / 2, a[c % b] = 88 ) e = b( d = b( b(c) ) ); return a; } int b(int f){ for (;;) if (a[++f % b] > 87) return f; } ``` 12 bytes thanks to Peter :) 4 bytes thanks to TNT ;) [Answer] # Haskell, 182 bytes ``` (a:b)%(c:d)|a<c=a:b%(c:d)|1<2=c:(a:b)%d f i=putStr$map(!(0:g[0,n..]))[0..n-1]where n=2^i;e!l|e`elem`l='X'|1<2='.';g(_:_:c:d:r)|m==c=[]|1<2=mod m n:g((d:r)%[m,m+n..])where m=div(c+d)2 ``` Usage: `f 5`. Output: `X.X.X...X...X...X.XXX.XXX.......`. Unfortunately Haskell doesn’t have a merge function in the standard libraries, so I have to provide my own (-> `%`). Fortunately I have to merge only infinite lists, so I don’t have to cover the base cases, i.e. empty lists. It still costs 40 bytes. How it works: instead of setting the `X`s directly in an array, I keep a list of positions where they are. Furthermore I do not wrap around at `2^N` but keep on increasing the positions towards infinity (e.g. for N=2 with an `X` at the front, the position list looks like `[0,4,8,12,16,20,…]`). I take the 3rd and 4th element (`c` and `d`), calculate the new position `(c+d)/2`, keep it for the output list, merge the old position list from position 4 (the `d`) on with a new one starting with `(c+d)/2` and recur. I stop when `(c+d)/2` equals `c`. Finally I add a `0` to the output list and print `X`s at the given positions and `.` elsewhere. ``` step by step example, N=2 step position list (c+d)/2 output lists to merge (pos. list for next round) list old list from d on / new list from (c+d)/2 #1 [0,4,8,12,16,…] 10 [10] [12,16,20,24,…] / [10,14,18,22,…] #2 [10,12,14,16,18,…] 15 [10,15] [16,18,20,22,…] / [15,19,23,27,…] #3 [15,16,18,19,20,…] 18 stop here, because c equals (c+d)/2 add 0 to the output list: [0,10,15] take all elements modulo 2^N: [0,2,3] print X at position 0, 2 and 3 ``` [Answer] # Mathematica, ~~110~~ ~~102~~ ~~112~~ 108 ``` a=Array["."&,n=2^Input[]];a[[Mod[Round@{n/2,n}//.{x_,y_,z___}/;y-x>1:>{z,x+n,(x+y)/2+n,y+n},n]+1]]="X";""<>a ``` ]
[Question] [ Given a string of unsorted alphanumeric characters, *e.g.* ``` ABC321STPpJqZZr0 ``` output a ", "-separated list of character ranges, sorted by ASCII value, ignoring case and removing duplicates (*i.e.* outputting only uppercase and numeric characters), *e.g.* ``` 0-3, A-C, J, P-T, Z ``` ### Rules * The length of your program is your base score, as usual. * You must initialize (hardcode) the above example within your program, but you may discount the length of that example from your program length, *e.g.* for `char* s="ABC321STPpJqZZr0";` you may discount 16 chars, the other 11 chars counting toward your program length. ### Bonus (+50 bounty) * As this was a real problem encountered by my coworker today, needing to be written in [Tcl 8.0.5](http://www.tcl.tk/man/tcl8.0/TclCmd/contents.htm) (an ancient version, lacking many of the latest Tcl built-ins), I'll award 50 points to whomever writes the shortest Tcl 8.0.5 solution, if there are at least 2 valid submissions in Tcl 8.0.5. [Answer] ## Ruby, 87-16=71 **EDIT:** Had to add some characters so that two-character ranges are displayed correctly. Also using `?[` instead of `?Z` to fix a bug with ranges ending in Z. ``` $><<[*?0..?[].join.gsub(/[^ABC321STPpJqZZr0]/i,$/).gsub(/\B.+\B/,?-).scan(/.-.|./)*', ' ``` You can see the Ideone run [here](http://ideone.com/LqzhhN). [Answer] # Julia, 131 ``` julia> l=sort(unique(uppercase("ABC321STPpJqZZr0"))) julia> prod([!(c+1 in l)?"$c"*(c==l[end]?"":", "):!(c-1 in l)?"$c":(c+1 in l)&&!(c+2 in l)?"-":"" for c in l]) "0-3, A-C, J, P-T, Z" ``` Not supported by Ideone.com, and will probably be crushed anyway. [Answer] ## C#, 221 bytes ``` class P{ static void Main(){ var s="ABC321STPpJqZZr0"; var l=new int[257]; foreach(int c in s.ToUpper()) l[c]=1; var r=""; for(int i=0;i<255;){ if(l[i++]-l[i]<0) r+=", "+(char)i; else if(l[i+1]-l[i]<0) r+="-"+(char)i; } System.Console.Write(r.Substring(2)); } } ``` [Answer] # C, 193 ``` char*s="ABC321STPpJqZZr0"; int c[99];memset(c,0,396);while(*s){++c[toupper(*s++)];}for(int i=0,f=1,r=0; i<=99;++i){if(!r&&c[i])r=i;if(r&&!c[i]){if(!f)printf(", ");putchar(r); if(i-r>1)printf("-%c",i-1);r=f=0;}} ``` [Answer] ## GolfScript ~~57~~ ~~54~~ 52 ``` 'ABC321STPpJqZZr0' {.95>32*-}%.|:x..{(}%&-x..{)}%&-+$2/{.|'-'*}%', '* ``` Try it [here](http://golfscript.apphb.com/?c=J0FCQzMyMVNUUHBKcVpacjAnCnsuOTU%2BMzIqLX0lLnw6eC4ueyl9JSYteC4ueyh9JSYtKyQyL3sufCctJyp9JScsICcq). The code first capitalizes everything: ``` {.95>32*-}% ``` Then gets unique characters and saves it in a variable: ``` .|:x ``` Then, we get the characters whose direct predecessors are not in the string (so that they are the beginning part of a range): ``` ..{)}%&-x ``` We similarly get the ends of ranges with `x..{)}%&-`. Now actually form the ranges by concatenating the lists, sorting, and splitting into groups of 2: ``` +$2/ ``` The rest is just formatting, using `*` as string join. [Answer] # Q, 94 ``` {","sv(,/){{"-"sv(?) -1 1#\:x}'[cut[;a]0,1_(&)1<(-':)"i"$'a:asc upper[x]inter y]}[x]'[.Q`n`A]} ``` [Answer] ## Python 2.x, 304 - 16 = 288 This can surely be golfed further, all comments welcome! ``` e=[""]*11;f=[""]*27 for c in"ABC321STPpJqZZr0".lower():e["0123456789".find(c)]=f["abcdefghijklmnopqrstuvwxyz".find(c)]=c e[-1]=f[-1]="" def h(j): g=[];k=l=i=0 for e in j: if e: if not l:k=i;l=1 elif l:l=g.append((k,i-1)) i+=1 print", ".join([j[m],j[m]+"-"+j[n]][n-m>1]for m,n in g) h(e);h(f) ``` [Answer] # Rebol (218 - 16 = 202) ``` m: s: sort uppercase unique"ABC321STPpJqZZr0"i: :to-integer f: does[either 1 = length? x: copy/part m s[x][rejoin[x/1"-"last x]]]while[not tail? s: next s][if(1 + i pick back s 1)!=(i s/1)[prin join f", "m: s]]print f ``` Non-minified version: ``` m: s: sort uppercase unique "ABC321STPpJqZZr0" i: :to-integer f: does [ either 1 = length? x: copy/part m s [x] [rejoin [x/1 "-" last x]] ] while [not tail? s: next s][ if (1 + i pick back s 1) != (i s/1) [ prin join f ", " m: s ] ] print f ``` [Answer] # q [116 chars] ``` {.a:();{m:6h$x;.a:.a,$[m[1]=1+m[0];45;m[0],44,m 1];1_x}/[x:asc distinct upper x];p where differ 6h$p:-3_10h$x[0],.a} ``` ## Usage ``` {.a:();{m:6h$x;.a:.a,$[m[1]=1+m[0];45;m[0],44,m 1];1_x}/[x:asc distinct upper x];p where differ 6h$p:-3_10h$x[0],.a}"ABC321STPpJqZZr0" ``` Output ``` "0-3,A-C,J,P-T,Z" ``` There is a scope of saving chars, i'll try some other method and post it. [Answer] ## Tcl 8.0.5, 344 (360 bytes) ``` set a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 set s string set x [join [lsort [split [$s toupper ABC321STPpJqZZr0] ""]] ""] regsub -all (.)\\1+ $x \\1 x set i 36 while {[incr i -1]} {set j -1 while {$i+[incr j]<36} {set y [$s range $a $j [expr $i+$j]] regsub $y $x [$s index $y 0]-[$s index $y end],\ x}} while {[regsub -all {(\w)(\w)} $x {\1, \2} x]} {} puts $x ``` ## Tcl 8.0.5, 340 (356 bytes) Tinkering with the `rename` command yielded some fun tricks! I've documented them [in another thread](https://codegolf.stackexchange.com/a/20574/14255). ``` rename rename & & set = & regsub R & string S & while W = a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 = x [lsort [split [S toupper ABC321STPpJqZZr0] ""]] R -all {(.) \1+| } $x \\1 x = i 36 W {[incr i -1]} {= j -1 W {$i+[incr j]<36} {= y [S range $a $j [expr $i+$j]] R $y $x [S index $y 0]-[S index $y end],\ x}} W {[R -all {(\w)(\w)} $x {\1, \2} x]} {} puts $x ``` ## Tcl 8.0.5, 332 (348 bytes) [Unstable—depends on $PATH] ``` info script "" set tcl_interactive 1 set a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 set x [lso [sp [st toupper ABC321STPpJqZZr0] ""]] regs -all {(.) \1+| } $x \\1 x set i 36 wh {[inc i -1]} {set j -1 wh {$i+[inc j]<36} {set y [st range $a $j [exp $i+$j]] regs $y $x [st index $y 0]-[st index $y end],\ x}} wh {[regs {(\w)(\w)} $x {\1, \2} x]} {} pu $x ``` Credit to [@JohannesKuhn](https://codegolf.stackexchange.com/questions/11552/tips-for-golfing-in-tcl/20574?noredirect=1#comment41501_20574) for [the interactive trick](https://codegolf.stackexchange.com/a/13053/14255). ]
[Question] [ For each of the 13 rows of a [Yahtzee scoresheet](http://yahtzeerules.com/images/score.jpg) you are given (from stdin) a space separated list of 5 numbers (dice). Your task is to calculate the score for each line and **output the Grand Total** of the game. ## Example [Input](http://pastebin.com/raw.php?i=ZRMC9B4x) and how to interpret it: ``` Input Box Score 6 1 4 1 3 Aces 2 3 2 2 1 2 Twos 6 6 3 2 3 3 Threes 9 4 2 3 6 5 Fours 4 6 3 5 5 1 Fives 10 1 5 6 5 6 Sixes 12 Bonus - 4 2 4 4 1 3 of a kind 15 2 2 3 2 4 4 of a kind - 3 2 2 2 3 Full house 25 1 3 1 6 1 Small straight - 2 5 4 6 3 Large straight 40 2 2 2 2 2 Yahtzee 50 5 5 4 5 2 Chance 21 Grand Total 194 ``` We will disregard the Yahtzee *Bonus* and Joker rules, and only sum up the scores from the Upper and Lower Section and the Bonus in the Upper Section. If in doubt, refer to [these rules](http://yahtzeerules.com/yahtzee-scoring.htm). May the shortest code win! [Answer] ## R - 264 ``` S=sum; P=prod; T=function(i)table(x[i,]); Z=function(i,...)any(sapply(list(...),function(y)all(y%in%x[i,]))) S((x[1:6,]==(R=row(x[1:6,])))*R)+ # Upper section S(x[7,])*any(T(7)>2)+ # 3 of a kind S(x[8,])*any(T(8)>3)+ # 4 of a kind 25*(P(T(9))%in%5:6)+ # Full house 30*Z(10,1:4,2:5,3:6)+ # Small straight 40*Z(11,1:5,2:6)+ # Large straight 50*(P(T(12))==5)+ # Yahtzee S(x[13,]) # Chance ``` (264 characters when excluding the comments) With the input ``` x <- as.matrix(read.table("http://pastebin.com/raw.php?i=ZRMC9B4x")) ``` Output ``` [1] 194 ``` [Answer] ## APL (124) ``` S←{⍺∊+⌿⍵∘.=⍵}⋄+/(+/⎕)(50×∧/,A∘.=A←⎕)(+/10×{⍵×∨/(⍳⍵)⍷1+A-⊃A←A[⍋A←⎕]}¨N)(25×∧/S∘⎕¨2 3)(+/{(+/A)×⍵S⊢A←⎕}¨N←3 4)(+/{+/⍵×⍵=⎕}¨⍳6) ``` [Answer] # Python 364 ``` S=sum;R=range;D=[map(int,raw_input().split())for i in R(13)];s=S(x for i in R(6)for x in D[i]if x==i+1) for i in R(2):d=D[6+i];s+=[0,S(d)][max(map(d.count,d))>2+i];d=sorted(set(D[9+i]));s+=[0,30+i*10]['1, 1, 1'+', 1'*i in`[d[x+1]-d[x]for x in R(len(d)-1)]`] e=D[8];a=map(e.count,e);d=D[11];print s+S(D[12])+[0,50][d.count(d[0])==5]+[0,25][2in a and 3in a or 5in a] ``` As requested, input is on stdin: ``` $ yScore.py < dice.txt 194 ``` If the data could be preloaded into a list, as some other solutions have done, I could remove 62 characters to get to 302. [Answer] # Mathematica 359 ``` y = IntegerDigits@ImportString[x, "Table"][[1]]; l = Length; g = Gather; r = Range; b = SortBy; h = l@b[g[y[[#]]], l][[-1]] &; Tr@Flatten@{# Count[y[[#]], #] & /@ r@6, If[h@7 == 3, 15, 0], If[h@8 == 4, 20, 0], If[(l /@ b[g[y[[9]]], l]) == {2, 3}, 25, 0], If[MatchQ[Sort@y[[10]], {___, n_, m_, o_, q_, ___} /; m == n + 1 && o == m + 1 && q == o + 1], 30, 0], If[Sort[y[[11]]] == r[y[[11, 1]], y[[11, 1]] + 4], 40, 0], If[l@g[y[[12]]] == 1, 50, 0], y[[13]]} ``` There must be a more efficient way to check for the short straight. [Answer] ### GolfScript 180 ``` n/{~]}%6,{)`['{''=},,''*']*}%[{.{+}*\{..|{'{'\'=},,'++1$\~}%$\;}:g~)\;2>*}{.{+}*\g)\;3>*}{g[2 3]=25*}{$:§;3,{).4+,\>§-}%1?)!!30*}{.$(\;.5+,\>\-!40*}{g)\;5=50*}{{+}*}]+]zip{~~}%{+}* ``` You can test the program [here](http://golfscript.apphb.com/?c=Oyc2IDEgNCAxIDMKMyAyIDIgMSAyCjYgMyAyIDMgMwo0IDIgMyA2IDUgIAo2IDMgNSA1IDEKMSA1IDYgNSA2CjQgMiA0IDQgMQoyIDIgMyAyIDQKMyAyIDIgMiAzICAKMSAzIDEgNiAxCjIgNSA0IDYgMwoyIDIgMiAyIDIKNSA1IDQgNSAyJwoKbi97fl19JTYseylgWyd7Jyc9fSwsJycqJ10qfSVbey57K30qXHsuLnx7J3snXCc9fSwsJysrMSRcfn0lJFw7fTpnfilcOzI%2bKn17LnsrfSpcZylcOzM%2bKn17Z1syIDNdPTI1Kn17JDrCpzszLHspLjQrLFw%2bwqctfSUxPykhITMwKn17LiQoXDsuNSssXD5cLSE0MCp9e2cpXDs1PTUwKn17eyt9Kn1dK116aXB7fn59JXsrfSo=&run=true) Annotated program: ``` n/ # split input by newline {~]}% # parse an int array from each line 6,{)`['{''=},,''*']*}% # create {X=},,X* code blocks, # where X goes from 1 to 6 # (needed for processing the first # half of the board) [ # create an array of code blocks, for scoring: # three of a kind: {.{+}*\{..|{'{'\'=},,'++1$\~}%$\;}:g~)\;2>*} # four of a kind: {.{+}*\g)\;3>*} # full house: {g[2 3]=25*} # small straight: {$:§;3,{).4+,\>§-!}%1?)!!30*} # straight: {.$(\;.5+,\>\-!40*} # yahtzee: {g)\;5=50*} #chance: {{+}*} ]+ # concatenate the 1-6 code block array with this one ]zip # distribute each line in the input # to the corresponding scoring rule (code block) {~~}% # evaluate each input/code pair # and get an array with score for each hand {+}* # sum up the partial scores. ``` [Answer] # Perl 527 characters ``` while(<>){$l++;$q=$c=0;$q=1if(($_=~/1/&&$_=~/2/&&$_=~/3/&&$_=~/4/)||($_=~/5/&&$_=~/2/&&$_=~/3/&&$_=~/4/)||($_=~/5/&&$_=~/6/&&$_=~/3/&&$_=~/4/));@a=split//;for(@a){$c++if/$l/;}$s+=$l*($c)if$l<7;$s+=35if$s>=63&&$l==6;for$i(1...6){$t=0;$f+=$c if($l==9&&($c==2||$c==3));$c=0if!($l==11&&$c>1);for(@a){$t+=$_;$c++if/$i/;}$s+=$t if($c>=3&&$l==7);$s+=$t if($c>=4&&$l==8);$s+=50if($c==5&&$l==12);$s+=$t if($l==13&&$i==6);}$s+=25if($f==5&&$l==9);$s+=30if($q==1&&$l==10);$s+=40if($c<2&&($t==15||$t==20)&&$l==11);exit(print $s)if($l==13);} ``` ]
[Question] [ You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map. The map can contain the following characters: `-+/\|.`, and they should be turned as expected. The in data is always rectangular and small. ## Example ``` $ cat in +--- |./. |/.. $ ./solution < in +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ ``` Shortest code wins. [Answer] # [Canvas](https://github.com/dzaima/Canvas/wiki), ~~5~~ 4 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ║Q↷↷ ``` First Canvas answer, so let's start with an easy one. :) -1 byte thanks to *@dzaima*. The slashes are automatically converted when mirroring or rotating in Canvas. Could have been 1 byte `╬` ([Try it online](https://dzaima.github.io/Canvas/?u=JXUyNTZD,i=JTYwJTYwJTYwJTBBKy0tLSUwQSU3Qy4vLiUwQSU3Qy8uLiUwQSU2MCU2MCU2MA__,v=8)), but unfortunately it also transforms the dots `.` to single quotes `'` when mirroring horizontally. [Try it online.](https://dzaima.github.io/Canvas/?u=JXUyNTUxJXVGRjMxJXUyMUI3JXUyMUI3,i=JTYwJTYwJTYwJTBBKy0tLSUwQSU3Qy4vLiUwQSU3Qy8uLiUwQSU2MCU2MCU2MA__,v=8) **Explanation:** ``` # (Take the multi-line input implicitly as canvas object) ║ # Palindromize the canvas object (without overlap) Q # Output it with a trailing newline (without popping) ↷↷ # Rotated the canvas object that's still on the stack by 90 degrees twice # (and output it implicitly as well at the end) ``` [Answer] ## Windows PowerShell, 99 ~~103~~ ~~117~~ ~~126~~ ~~129~~ ``` filter x{$_-split'/'-replace'\\','/'-join'\'}$input|%{$_+-join($_[40..0]|x)}|%{$_ $s=,($_|x)+$s} $s ``` Notes: * This unfortunately needs two things that PowerShell is notoriously bad at while golfing: Reversing a string (or sequence of values) and transliterating stuff in a string. I'm fairly sure that this is at least twice as long as a Perl of Ruby solution. Test: ``` > gc in| .\map.ps1 +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ > gc in2 +\/ /\/ > gc in2| .\map.ps1 +\/\/+ /\/\/\ \/\/\/ +/\/\+ ``` History * 2011-02-09 11:10 (129) – First attempt. * 2011-02-09 11:27 (126) – `OFS` to save the `-join` and stored `99..0` in a variable. * 2011-02-09 11:31 (117) – `-replace` works against arrays, so I don't need three `-replace`s but can do a `-split`, `-replace`, `-join` instead. * 2011-02-09 15:03 (105) – Instead of doing the same thing twice, do it once and reverse it. And putting an assignment into parentheses causes it to spit out its value to the pipeline :-) * 2011-02-09 15:08 (103) – I don't need `$a` anymore since `99..0` isn't used that often by now. * 2011-02-09 15:17   (99) – There doesn't need to be whitespace after the `filter` definition. Removed `$x` and instead collecting every line during the first run in an array and then outputting that for the second half. [Answer] # Ruby - 88 87 chars ``` t=->s{s.tr'/\\\\','\\\\/'} puts a=$<.map{|l|l.chop!+t[l.reverse]} puts a.reverse.map &t ``` ## Test Run ``` D:\tmp>ruby cg_sym_map.rb < sym_map.in. +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~25~~ ~~23~~ ~~22~~ ~~21~~ 19 bytes ``` (⌽⍪⊖){⊃3⌽⍵∪'/\'}¨,⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBI1HPXsf9a561DVNs/pRV7MxmLv1Uccqdf0Y9dpDK3SAAv//JyoAlT7qalLX1tXVVedK1IFya/T09ZC5@nogLojXNjGRK00hEQA "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~5~~ 4 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` S‖M⌈ ``` -1 byte thanks to *@Neil*. Charcoal automatically handles reflecting the slashes correctly. [Try it online (verbose)](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXUOTKyg1LSc1ucQ3s6gov0jD6lFPh@b//9FKSkraurq6XDV6@npcNfp6ekCB2P@6ZTkA) or [Try it online (pure)](https://tio.run/##S85ILErOT8z5///9ns2PGqa937P2UU/H///RSkpK2rq6ulw1evp6XDX6enpAgVgA). **Explanation:** Take the input as a string: ``` InputString() S ``` Reflect mirror it both towards the right and downwards (`:⌈` is a builtin for `:Right, :Down`): ``` ReflectMirror(:⌈) ‖M⌈ ``` [Answer] ## Golfscript - 32 chars ``` n%{{.-1%{.3%2=115*^}%+}%zip}2*n* ``` Due to the symmetry of the problem, we repeat twice {flip horizontally, transpose (`zip`)}. As a bonus, you can change the value `2` to a larger number to repeat the image more. Character transposition is done as `x^=155 if x%3==2`, due to the restricted character space. There's also `{.5^3%(45+}` at the same length. [Answer] ## Perl, 80 chars ``` print reverse map{s@.*@($b=$&)=~y:/\\:\\/:,$&.reverse$b@e;print;y@/\\@\\/@;$_}<> ``` [Answer] Shell Scripting!! ``` #!/bin/sh rm temp touch temp file=$1 for STRING in `cat $1` do printf $STRING >> temp for ((COUNT=0; COUNT<${#STRING}; COUNT++)) do RECORD[$COUNT]=${STRING:$COUNT:1} done for ((REV_COUNT=${#STRING}; REV_COUNT>=0; REV_COUNT--)) do if [ "${RECORD[$REV_COUNT]}" = "\\" ]; then printf "/" >> temp elif [ "${RECORD[$REV_COUNT]}" = "/" ]; then printf "\\" >> temp else printf "${RECORD[$REV_COUNT]}" >> temp fi done echo >> temp done cat temp tac temp > temp2 for STRING in `cat temp2` do for ((COUNT=0; COUNT<${#STRING}; COUNT++)) do RECORD[$COUNT]=${STRING:$COUNT:1} if [ "${RECORD[$COUNT]}" = "\\" ]; then printf "/" elif [ "${RECORD[$COUNT]}" = "/" ]; then printf "\\" else printf "${RECORD[$COUNT]}" fi done echo done ``` I/O ``` ./solution in +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ ``` [Answer] # CJam, 26 bytes CJam is newer than this challenge, so this answer is not eligible for the green checkmark, but it was a fun exercise anyway ``` qN/{{_W%"\/"_W%er+}%z}2*N* ``` [Test it here.](http://cjam.aditsu.net/) ## Explanation ``` qN/{{_W%"\/"_W%er+}%z}2*N* qN/ "Read STDIN and split on newlines."; { }2* "Execute this block twice."; { }% "Map this block onto each line."; _W% "Duplicate and reverse."; "\/" "Push the string '\/'."; _W% "Duplicate and reverse."; er "Character transliteration, swaps slashes and backslashes."; + "Append to first half of the line."; z "Zip, i.e. transpose the map."; N* "Join with newlines."; ``` The transposing at the end leads the the second flipping to be performed along the columns. At the end we transpose the map again, so we end up with the original orientation. [Answer] # Powershell, 95 bytes *Inspired by Joey's [answer](https://codegolf.stackexchange.com/a/763/80745).* ``` filter x{$_;$_[40..0]|%{$_-split'/'-replace'\\','/'-join'\'}},($args|%{-join(,($_|% t*y)|x)})|x ``` Note: `40` because the author posts the comment `Let's say the input is at most 16 rows and 40 characters`. Test script: ``` $f = { filter x{$_;$_[40..0]|%{$_-split'/'-replace'\\','/'-join'\'}} ,($args|%{-join(,($_|% t*y)|x)})|x } @( ,( ("+---", "|./.", "|/.."), "+------+", "|./..\.|", "|/....\|", "|\..../|", "|.\../.|", "+------+") ,( ("+\/", "/\/"), "+\/\/+", "/\/\/\", "\/\/\/", "+/\/\+") ,( ("+---", "|...", "|..\"), "+------+", "|......|", "|..\/..|", "|../\..|", "|......|", "+------+") ) | % { $m,$expected = $_ $result = &$f @m "$result"-eq"$expected" $result } ``` Output: ``` True +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ True +\/\/+ /\/\/\ \/\/\/ +/\/\+ True +------+ |......| |..\/..| |../\..| |......| +------+ ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` øṀ¶+∞ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuOG5gMK2K+KIniIsIiIsIlwiKy0tLVxcbnwuLy5cXG58Ly4uXCIiXQ==) ``` øṀ # Vertically mirror, flipping /\ ¶+ # Append a newline ∞ # Palindromise ``` [Answer] # Ruby - 105 ``` t=->s{s.tr '/\\\\','\\\\/'} $<.read.split.map{|l|print l+=t[l.reverse]+" " l}.reverse.map{|l|print t[l]} ``` [Answer] ## Golfscript - 44 chars ``` n%{.-1%'/'/{'\\'/'/'*}%'\\'*+}%.-1%{-1%}%+n* ``` result ``` $ cat in2 +-/|/\ /\|//- $ cat in2 | golfscript codegolf-761.gs +-/|/\/\|\-+ /\|//--\\|/\ \/|\\--//|\/ +-\|\/\/|/-+ ``` ### Another script that only work for example and does not flip for '\' - 32 chars ``` n%{.-1%'/'/'\\'*+}%.-1%{-1%}%+n* ``` result ``` $ cat in +--- |./. |/.. $ cat in | golfscript codegolf-761.gs +------+ |./..\.| |/....\| |\..../| |.\../.| +------+ $ ``` [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` c '/'='\\';c '\\'='/';c x=x;i=(c<$>) q#x=x++q(reverse x) f=((i<$>)#).map(i#) ``` [Try it online!](https://tio.run/##FYo7DsMgEER7TrGSLQGygAPYpHGbVGndIGedoNj4A4kofHeyKUbznmZeLr5xnksZgRtu@TDwlpDKkhNmm1tvxdjVF8n2irRpdnHgF4@IkCWbrBD@v1ZSL24TvpJlcT6AhccKGToFT0z9GhKGFKEFOt1g@6R7Oq4Bapgosw8YIZdGKcVObTQ7jdY/ "Haskell – Try It Online") ``` -- Only / and \ get converted, all other chars are passed as is c '/'='\\';c '\\'='/';c x=x -- "Invert" the string (that is switch all / and \ in it) -- Just map our conversion function over the string i = (c<$>) -- Helper: Concatenate a list with its reversed copy (with the given function applied to the copy) q # x = x ++ q (reverse x) -- the resulting function: f = ((i<$>)#) . -- produce the lower half of the image by reversing the upper half and inverting slashes in each line map (i#) -- produce the upper half or the image (by concating each input line with its reversed, inverted version) ``` [Answer] # MS-SQL 2017, 243 bytes **input**: ``` DECLARE @s VARCHAR(100) ='+---'+CHAR(10)+'|...'+CHAR(10)+'|..\'; ``` *compressed*: ``` declare @t TABLE(l INT IDENTITY(1,1),s CHAR(40));INSERT INTO @t(s)SELECT value+TRANSLATE(REVERSE(value),'\/','/\')FROM STRING_SPLIT(@s,char(10));SELECT s FROM(SELECT l,s FROM @t UNION ALL SELECT 1e3-l,TRANSLATE(s,'\/','/\')FROM @t)b ORDER BY l ``` *human readable*: ``` declare @t TABLE(l INT IDENTITY(1,1),s CHAR(40)); INSERT INTO @t(s) SELECT value+TRANSLATE(REVERSE(value), '\/', '/\') FROM STRING_SPLIT(@s,char(10)); SELECT s FROM( SELECT l, s FROM @t UNION ALL SELECT 1e3-l, TRANSLATE(s, '\/', '/\') FROM @t )b ORDER BY l ``` **output** (as text in ex.management studio): ``` +------+ |......| |..\/..| |../\..| |......| +------+ (6 rows affected) ``` ]
[Question] [ *Inpired by recent [Stand-up Maths' video](https://www.youtube.com/watch?v=dET2l8l3upU).* ## Task Wrapping a list `x` can be seen as inserting "line-breaks" into `x` every `n`-th element, or forming a matrix from `x` with `n` columns (feeding rows first). To be perfectly rigorous in the definition of `x` wrapped into a matrix, we can pad the last row with `0`s. Given a list `x` of positive digits and a matrix `M` of positive digits, determine whether `x` can be wrapped into any matrix that contains `M` as a submatrix. In other words, is there any `n` such that wrapping `x` into a matrix of `n` columns results in a matrix that contains `M`? ## Rules * Any reasonable input format is acceptable (list, string, array, etc.). * As for output, please follow the [defaults for decision-problem challenges](https://codegolf.stackexchange.com/tags/decision-problem/info). * `x` is guaranteed to be longer than number of elements in `M`. * You don't need to handle empty inputs. * Some wrappings may result in the final line shorter - that's fine. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible. ## Examples ``` x=1231231 M=23 31 Possible wrappings: n>=7 1231231 n=6 123123 1 n=5 12312 31 n=4 1231 231 n=3 123 123 1 n=2 12 31 23 1 n=1 1 2 3 1 2 3 1 Output: True (4th wrapping) ``` ``` x=1231231 M=23 32 Possible wrappings: same as above Output: False (none of the wrappings contain M as submatrix) ``` ## Test cases **Truthy** ``` x; M [1,2,3,1,2,3,1]; [[2,3],[3,1]] [3,4,5,6,7,8]; [[3,4,5],[6,7,8]] [3,4,5,6,7,8]; [[3,4],[7,8]] [1,2,3]; [[1,2,3]] [1,2,3]; [[1],[2],[3]] [1,1,2,2,3,3]; [[1],[2],[3]] [1,1,3,4,5,6]; [[1],[4],[6]] ``` **Falsey** ``` x; M [1,2,3,1,2,3,1]; [[2,3],[3,2]] [1,1,2,2,3,3]; [[1,2,3]] [1,2,3]; [[4,5,6]] [1,2,3,4,5,6]; [[2,3],[4,5]] ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` 1 e.,@(E."2-@#\]\"{]) ``` [Try it online!](https://tio.run/##lZBNC4JAEIbv/ooXCzZhXXI1i4VAiDx1io56iFAkgqCPQ/Tjt/3QVBKhw8wyM8/OvLxn6TJSYi1AQDGHUOEzbPa7VAYoGE1mW@ZyP5lkeea@c096TnGqriCH2/NRvYitMANHCCpUCuChhHq4KWxusBARFppDjCVWhrQ9U/c4TY0xVJjtnWvt7wBTFVBd/EFoRlNDXKQi/nKNHqd2Iz1e7q0ZtRcq8xEv@vp/b1Nhbgyob/areWdqFckP "J – Try It Online") Bulk of the work done by `E.` builtin, which can search for one 2D matrix within another, and even extends to higher dimensions. * `-@#\]\"{]` Every possible wrapping. * `E."2` Does the matrix match at each position? (returns 0/1 matrices) * `,@` Flatten * `1 e.` Is 1 an element of that? [Answer] # [R](https://www.r-project.org/), ~~126~~ ~~121~~ 120 bytes *Edit: -5 bytes thanks to Aaron Hayman* ``` function(x,m,r=nrow(m)){for(o in l<-seq(x)-1)for(s in l+o)T=T&any(c(x,!x,!x)[outer(1:r,(r+s)*(1:ncol(m)-1),`+`)+o]-m) T} ``` [Try it online!](https://tio.run/##lZFha4MwEIa/@ysyCiM3zw/arRtl/gu/jUGdVSaYSxcjVcZ@u8tFS6mwdYMQcu89ubx3MaOqqU/HqqPC1ppkjwpNSkYfpQL4rLSRWtQkmueoLT9kD1EMLLZeDDVkaXab0yALd/WGF7zozpZGxluD0oQt3LkjFbpxBd1l3IU7CPVrpCDIvsaVqPKmHbZCidrXzMXR5IdDuRd9wN5c4RgTXOO8AxZvNe2d7EIXSNYATuwa7/EBN/iIT2fSi8xO@nWa2UvSv35mpvDnNBdIvLsLiDHu4k/obG6Bem8bRoOVsKaz76fhkbZ@gDT8f4TJVZu/Nzw5XaSX/ufX@C8Axm8 "R – Try It Online") Outputs `TRUE` if ~~wally isn't there~~ `m` is *not* present in any wrapping of `x`, `FALSE` if it is. Calculates the indices of positions of ~~wally~~ `m` for each possible `o`ffset (the first position in the wrapped matrix) and `s`pacing (the width of the wrapped matrix), and checks that the elements of `x` at these indices are all equal to `m`. To avoid lengthly calculations to keep the indices in-range, we first extend `x` with enough zeros to cover the biggest `o` & `s`: this is the ugly-looking `(c(x,!x,!x)`. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 24 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Generates all possible wrappings and checks if the left argument is a submatrix of one. ``` {1∊∾(⥊𝕨⍷𝕩⥊˜⟨↑⟩∾1⊸+)¨↕≠𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsx4oiK4oi+KOKlivCdlajijbfwnZWp4qWKy5zin6jihpHin6niiL4x4oq4KynCqOKGleKJoPCdlal9CgpHIOKGkCDiipHiiJhGy5wKIyB1bmNvbW1lbnQgZm9yIG1vcmUgZGV0YWlsZWQgb3V0cHV0OgojIEcg4oapIOKLiOKIvifihpIn4ouIRwoKPuKfqArin6gxLDIsMywxLDIsMywx4p+pIEcgPuKfqOKfqDIsM+KfqSzin6gzLDHin6nin6kK4p+oMyw0LDUsNiw3LDjin6kgICBHID7in6jin6gzLDQsNeKfqSzin6g2LDcsOOKfqeKfqQrin6gxLDIsM+KfqSAgICAgICAgIEcgPuKfqOKfqDEsMiwz4p+p4p+pCuKfqDEsMiwz4p+pICAgICAgICAgRyA+4p+o4p+oMeKfqSzin6gy4p+pLOKfqDPin6nin6kK4p+oMSwxLDIsMiwzLDPin6kgICBHID7in6jin6gx4p+pLOKfqDLin6ks4p+oM+KfqeKfqQrin6gxLDEsMyw0LDUsNuKfqSAgIEcgPuKfqOKfqDHin6ks4p+oNOKfqSzin6g24p+p4p+pCgrin6gxLDIsMywxLDIsMywx4p+pIEcgPuKfqOKfqDIsM+KfqSzin6gzLDLin6nin6kK4p+oMSwxLDIsMiwzLDPin6kgICBHID7in6jin6gxLDIsM+KfqeKfqQrin6gxLDIsM+KfqSAgICAgICAgIEcgPuKfqOKfqDQsNSw24p+p4p+pCuKfqDEsMiwzLDQsNSw24p+pICAgRyA+4p+o4p+oMiwz4p+pLOKfqDQsNeKfqeKfqQrin6k=) [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 100 bytes ``` f(a,b)=sum(n=#b,#a,!!matrix(-#a\-n,n-#b+1,x,y,b==matrix(#b~,#b,i,j,if(#a>=k=(x+i-2)*n+y+j-1,a[k])))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZFBTsMwEEXFTdJ6Y5PvRZLSVrLcG7BkZSI0oQpym0ZRmkrJhouw6QZxJjgNdpJCEa0X1v_zRn9G9ttHRbV9eqmOx_dDk8vl5zrnhEzo_WHHS80yMMJksqOmti2XjB5liVKyLIzQokOm9chY9grXbrGBzTmjld5q3oZWxuK2DLtwIyOQ2abCnWHW180DVVXRcQrkKqhqWzZOTr2ZBs9UFDxHQEIgMMZEiJFgvFNXckJ56bVJMMMd5lhg6X1v1WCvcPXD-kyn7qnhoxF_gIlUrJJTs6_6JS6RccxAZmp-NuD_6vGlxKtL9GBIPwO_83ymM2majq97-tFv) Generates all possible wrappings, and all of their submatrices of the given size, and check if the second argument is one of them. [Answer] # [Desmos](https://desmos.com/calculator), 133 bytes ``` f(L,M,w)=0^{\sum_{m=1}^K\sum_{X=w}^m\sum_{Y=0}^K\prod_{j=0}^{M.\length-1}\{M[j+1]=L[X+Ym+1-w+\mod(j,w)+\floor(j/w)m],0\}} K=L.length ``` * L: list of positive digits (x in question) * M: matrix, flattened because Desmos doesn't have 2D arrays * w: width of M Outputs 0 for truthy and 1 for falsey. [Try it on Desmos!](https://www.desmos.com/calculator/hztgcyq175) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~31~~ 30 bytes ``` FEθ⪪θ⊕κP⊙ι⊙κ⊙ι⊙ξ⁼ηE✂ιλ⊕π¹✂σν⊕ς ``` [Try it online!](https://tio.run/##VYyxDsIwDER/xaMjmaEwMjEwMHTqGGWIQlCjmjRN0wq@PiRqGXqSfXd60pleRzNqzvk1RsBWB5wIusAu1fDwJtq39ck@cRBF0C6cXIjOJ7z5LzqCasNme/sQ3KdF84w9QZ3s2BlbKR8ngyBoym18JvBHvoq/rjlL2dCZLrR/RVKWUKwWpfJp5R8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if it finds Wally, nothing if not. Explanation: Another answer that generates all submatrices of all wrappings. ``` FEθ⪪θ⊕κ ``` Generate all wrappings of the list. ``` P⊙ι⊙κ⊙ι⊙ξ⁼ηE✂ιλ⊕π¹✂σν⊕ς ``` Check whether the matrix exists as a submatrix. Unfortunately Charcoal only has 11 loop variables so I can't save a further byte like this: ``` ⊙Eθ⪪θ⊕κ⊙ι⊙κ⊙ι⊙ξ⁼ηE✂ιλ⊕π¹✂σν⊕ς ``` Explanation: ``` θ Input list E Map over digits θ Input list ⪪ Wrapped to width κ Current index ⊕ Incremented ⊙ Any wrapping satisfies ι Current wrapping ⊙ Any row satisfies λ Current row ⊙ Any column satisifies ι Current wrapping ⊙ Any row satisfies ξ Inner row ⊙ Any column satisifies η Input matrix ⁼ Equals ι Current wrapping ✂ ¹ Sliced from μ Outer row index to π Inner row index ⊕ Incremented E Map over rows σ Current row ✂ Sliced from ν Outer column index to ς Inner column index ⊕ Incremented Implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œεεŒIнgù}øεŒIgù€Q]˜à ``` [Try it online](https://tio.run/##yy9OTMpM/f9f7@jkc1vPbT06yfPC3vTDO2sP7wBzgMxHTWsCY0/PObzg//9oYx0THVMdMx1zHYtYrmgQN1YnGsSJBQA) or [or verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@9o5PPbT239eikiAt70w/vrD28A8wBMs9tjQisra09Pefwgv86/6Ojow11jHSMdaBkrE50NJABpECc2FgdhWggy0THVMdMx1zHAiQN5gIZEAFcSoAUQhpsOEgCwkAXBBJGIBvhEiApkHNwSkPtg0mDbDNDNhabd4xwGI/NSRDTkQ2E2wdRAQoCIAAA) or [try it online with step-by-step debug-lines](https://tio.run/##nZG/SgNBEMZ7n2JIY7Oawr8oIYUQSafYGa5YL5Ps4N7uuTvnBUsfQVsLH8A2ooWNIZUQfAZf5Ly9nAaDhQgLy87HfN9vdqyXZ4RF0eiQ8wxk0ozXNHneg0a71TjB2Jp@XU4kOxoFoSteH9srjUNkkFpDKh0TkzUe7ABY4ZLP@vS2VTV0rAOUsSp1gw6CHjqq0sJEQOxQMoK9RKdlmpIZVrKHnFiBBE9XCHiRSQ1sq8Cc@qVSp/vfqWfj2Xh6031/GU6eoznQKaVNdtKk1uM@@LwOczb3zdjqLDE@dH5cP0yelkb4gg/3v5AV0lDx35gXxAcK43MYfH/kAIhX/U/nZZMSf36O6xm0ZEYTpLe7eenIpiDL/DTzqvJI5IiSLBGQKwo55WozBw59pqudTu5FUfQ2xKbYEttiR@xGK73wjEQvPKJP). **Explanation:** ``` .œ # Get all partitions of the first (implicit) input-list ε # Map over each partition: ε # Map over each inner list: Œ # Get all sublists of this list I # Push the second input-matrix н # Pop and leave just its first row g # Pop and push its length to get the width of the matrix ù # Only leave all sublists of this length, to get all overlapping # parts with a size equal to the width of the input-matrix }ø # After the inner map: zip/transpose; swapping rows/columns ε # Map over each list of lists: Œ # Get all sublists of this list I # Push the second input-matrix again g # Pop and push its length to get the height of the matrix ù # Only leave all sublists of this length, to get all matrices # with the same dimensions as the input-matrix € # Map over each inner matrix: Q # Check if its equal to the second (implicit) input-matrix ] # Close both maps ˜ # Flatten à # Get the maximum to check if any were truthy ``` ]
[Question] [ ### Introduction A function that adds months to a date (without overflowing ends of months) is implemented in many languages/packages. In Teradata SQL it's [ADD\_MONTHS](https://docs.teradata.com/r/1DcoER_KpnGTfgPinRAFUw/1ufuNocPef2Qwb7j3mSwZg), here are some examples: ``` ADD_MONTHS('2021-01-31', 1) => 2021-02-28 ADD_MONTHS('2021-01-30', 1) => 2021-02-28 ADD_MONTHS('2021-02-28', 1) => 2021-03-28 ADD_MONTHS('2021-02-28', -12) => 2020-02-28 ``` Teradata SQL has also a function that goes a step further, namely [OADD\_MONTHS](https://docs.teradata.com/r/1DcoER_KpnGTfgPinRAFUw/%7EgC4zS9EaPZpJQ9Y9yTstQ). Here, when given an end-of-month date, it always returns an end-of-month date. To illustrate the difference: ``` ADD_MONTHS('2021-02-28', 1) => 2021-03-28 OADD_MONTHS('2021-02-28', 1) => 2021-03-31 ``` ### The task You are given a date and an integer. Your output should mimic the behaviour of OADD\_MONTHS described above. Any reasonable input/output form is acceptable (including your language's native date/datetime type, a string, number of days/seconds from a fixed point, etc.) You may assume the input and target dates are after `1600-01-01` and the date is well defined (so no `2021-03-32`). You may use the [Georgian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) or any similar calendar implementing standard month lengths and taking into account leap years. If you have a builtin specifically for this, consider including a non-builtin answer as well to make your answer more interesting. ### Test cases ``` Date , offset => output (explanation) 2021-01-31, 0 => 2021-01-31 (boring) 2021-01-31, 1 => 2021-02-28 (no overflow) 2020-12-31, 1 => 2021-01-31 (next year) 2020-12-07, 1 => 2021-01-07 (next year) 2021-01-31, -1 => 2020-12-31 (previous year) 2021-01-30, -1 => 2020-12-30 (previous year) 2021-01-01, -1 => 2020-12-01 (previous year) 2020-12-30, 2 => 2021-02-28 (no overflow) 2021-02-28, 1 => 2021-03-31 (end-of-month -> end-of-month) 2021-09-30, 1 => 2021-10-31 (end-of-month -> end-of-month) 2021-02-28, -12 => 2020-02-29 (end-of-month -> end-of-month) 2020-02-28, 1 => 2020-03-28 (leap year - 28.02 is not end-of-month) 1995-02-28, -1140 => 1900-02-28 (not a leap year) ``` [Answer] # [Julia 1.0](http://julialang.org/), 53 bytes ``` using Dates ~ =lastdayofmonth a\b=a<~a ? a+b : ~(a+b) ``` [Try it online!](https://tio.run/##jZLBcoIwEIbvPMVOTzAlnU20ozjFXnrpoU@gHmIJlg5NGBKtXnx1mwSqFOmMuUB2v/3/3Z18bsuC0/3ptNWF3MALN0IHR0hLrk3GDyr/UtJ8BHy5TvnTkcMz8Ps1zOAY2m90CnJVQ1lIAYWEWvDM/eswCsAeH09BV2VhQndpwpn1sGFn5aMLulrQmZAZoauGUHmuhbHMmzMPK15rEb5KE3ucraIGE/tKvBuR/REbtxq10NvSaXi7ZavpU1VdSFPKMHSpuM1EkM7bohjuluYuPkukZ6cosG2eGDJKkJIRjQHBH1t7iQKEa2U9NlHQRWkPZYRNLSoVqJ2o81J9ex4JZYN8Ky3F3sBB8PpC42SIxskVfe6F0A7dOlq6qsWuUFvdr8DBCvy/Agc9cNijVYuB3bahNnM986iZwj0llRP/coHMoXv/FUi8YU@A4u0CTQe28@6MLprcIoCDI6AbwY9cCl75BQEBNn1ABoUGqUxPiSbJ46UVOkavRBPEzvIMcDjrRT8 "Julia 1.0 – Try It Online") expects `Date("2021-02-28")\Month(1)`, returns a `Date` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~142~~ ~~140~~ ~~135~~ ~~131~~ 130 bytes ``` d=>f=x=>O(x)>O((D=a=>new Date(x-a*864e5))(-1))?D(1,x=f(D(-1))):O(y=D``,y.setMonth(x.getMonth()+d))<O(x)?f(D(-1),d):y O=x=>(x+x)[8] ``` [Try it online!](https://tio.run/##jZPbcpswEIbveYq9i1QkIpGkMWmFb5jcdfwAPVk1wqVDJAZkR@TlXYFP1KEz1jCAVv9@exjtH7mV7aopa0u1ydXuWexykRbCiXSBHPYvlAkpUq1eIZNWIUflh9nHe/WAMaIc43mGOHGiQNmwxU8L1IlsuSRd1Cr7xWj7G7loffzFYY7x5x49P7iQHD91waKPiFzo8NfZ992nYBn00WBYBExReBiIFMzG1hu7tyPl6kpqaUujcRCzmFPG6R0nwPYCrz9bvf6XaUq9/lfKL6QxjWdeqg2YrWqKyrwOekZ5PKk/oLVyFjolm7OaPU6p2eM79SkXykfqQ0Svrhu1Lc2mvfRgkx7s/x5sMgabjnGgEYiv69Dh5H3Nd/sqlM6pKehLfw2ApjDeHwHJEPACwNn1gH0GPvNxjb01uQbAJktgfQlDyZWS9dAgoBDPIhZD2YI29oLEk@ThnAq/ZwOJJ4yNmmdBwomHg2XUKH@ZVwrd/kCRX3R4MAEUhXMMoSeM7bcva3/0kzjSkTcs0pXRralUVJm1n6Kbb/aGQHf8imcUdhidZxh7btgJEZ5Mb350d38B "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 95 bytes ``` ≔I⪪S-θ≔⊟θζ≔⊟θη≔⊟θθF²«≔⎇⁼η²⁺²⁸¬﹪∨﹪θ¹⁰⁰÷θ¹⁰⁰¦⁴⁻³¹﹪﹪⊖η⁷¦²ε¿ι⪫⟦θη⌊⟦ζε⟧⟧-«≧⁺⊖Nη≧⁺÷η¹²θ≔⊕﹪η¹²η¿⁼ζε≔φζ ``` [Try it online!](https://tio.run/##dVFBa4MwGD3bXxF6@gIKmg422GmsO3TQTtbdSg9OYw3ERGMsrKO/3X2pcR2UXZLw8t778l7yKjO5zuQwPHWdOCh4zjoL20YKCyvV9HZrjVAHoCGZR3OKW0sfZ56b6gZahE63UHULOWGpDQFGyfcs8Lcf3KjMfMFL22eygyokDLmp7DtgDyHZaAtrXfRSw5uZTm1IkjhG2krZpTiKgk8QYnfUrWuh0GGR4GnU@G3Jc8NrriwvoELePXUDnYLj8wJREhCUpJjZwqsWCnboXF38RN3XsDshc0/3vg6UcNlxlydYZ82Y6V0cKgsuQkj@zrv0uenrT26A@o7@kV2D4eyE@faCqbSVurr6YCPv19UF8ZW6F1NKvLQcvys4z87DwGIWR0kSLWLChugofwA "Charcoal – Try It Online") Link is to verbose version of code. Date I/O is in YYYY-m-d format i.e. no leading zeros. Explanation: ``` ≔I⪪S-θ≔⊟θζ≔⊟θη≔⊟θθ ``` Read in the date. ``` F²« ``` Calculate the number of days in the month twice (first for the input month and second for the output month). ``` ≔⎇⁼η²⁺²⁸¬﹪∨﹪θ¹⁰⁰÷θ¹⁰⁰¦⁴⁻³¹﹪﹪⊖η⁷¦²ε ``` The formula for the number of days in the month is `m == 2 ? 28 + !((m % 100 || m / 100) % 4) : 31 - (m - 1) % 7 % 2`, the latter part of which I appropriated from [this Stack Overflow answer](https://stackoverflow.com/a/46604975). ``` ¿ι⪫⟦θη⌊⟦ζε⟧⟧-« ``` If this is the second pass, then output the year and month, and the minimum of the day and the number of days in the month (in case the original month had more days). ``` ≧⁺⊖Nη ``` Add the input number of months. ``` ≧⁺÷η¹²θ≔⊕﹪η¹²η ``` Adjust the years to bring the month to between `1` and `12` again. ``` ¿⁼ζε≔φζ ``` If this was the last day of the input month then set the day to a large number so that it gets truncated to the last day of the output month. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 61 bytes Without considering `d=` which was used to apply to the input. ``` t="EndOfMonth";d=DatePlus[#,{#2,If[DayMatchQ[#,t],t,"Month"]}]& ``` [Try it online!](https://tio.run/##7ZNNT@MwEIbv/RUjR0Kt5Cy2uyuIVql6gAOrZWHpMUTItA6NlNpRMmVBVfnrxfnYJi1BqsSBC/Ep42fe@UjehcS5WkiMp3KD6gl9ciZRQflQMFGUKwR/BGaJ6RKreF89pYnUNsnoQU8wwV3G3SGnwCrA8k3U8vcmi/XDLsr3UOGKU4tqA@ZRZVFi/pU8c7no5GtpbXuGZyWzhmYnXTQ7eUNve3F5i64rWjrN1GNslvl@BuvMYO9nsM4arLtGrUZBHLah@ubtzMNqCqVnronchdE4B3cE7ff/Al5ZcE@As8MFqg5s5@0Zi6h3iADrHIEVI5QjJ0qm5YLABXH6jQmIc9AG4ba3q8U970fTDP/OSi3uMdZaH4KEreKAbOw/f65nV9FloUF@zvzCAdfJMg8cunIEvYiCM/l8KXE6/2tDGFKkpILDdXi0mQWO/b6OCMH3wRnCEYzHY@ivCpnfcY5jh8LFIjUZTrDwQWA1gfyaXP0hIYVeOXHDDte1QHFRJUzSJMagBKvAjbL@m6oqBDfK5rXJXahwta1nj109KUqSW91UJn0CLy9wd7e9XhFKLOSPyDocHB9fWzHcfLn8y@Wf5fIPe/wV "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~66~~ 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¦R1Ý-12β+12‰`>¹н)R¹"`т‰0Kθ4ÖUD<i\28X+ë<7%É31α"©.VQiт0ǝ}D®.V‚ß0ǝ ``` -3 bytes thanks to *@Neil*. [Try it online](https://tio.run/##AW8AkP9vc2FiaWX//8KmUjHDnS0xMs6yKzEy4oCwYD7CudC9KVLCuSJg0YLigLAwS864NMOWVUQ8aVwyOFgrw6s8NyXDiTMxzrEiwqkuVlFp0YIwx519RMKuLlbigJrDnzDHnf//WzMwLDEyLDIwMjBdCjI) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCsUvY/0PLggwPz9U1NDq3SdvQ6FHDhgS7yAt7NYMilRIuNgG5Bt7ndpgcnhbqYpMZY2QRoX14tY256uFOY8NzG5UOrdQLC8y82GRwfG6ty6F1emGPGmYdng/k/T@8Xkcz5n90dLSxoY6hjpGBkWGsjkGsjgKKgCFcwAgkYgATMUcXQNKjCxUxQBfBqgRmjBFYxMhCxwjVagMdSxQBJBXAEEERMkBRY2hpaQpSY2hiEBv7X1c3L183J7GqEgA). **Explanation:** Here we go again.. 05AB1E lacks any date builtins, so everything is done with manual calculations. The isLeapYear calculation is taken from [this answer of mine](https://codegolf.stackexchange.com/a/177019/52210) and determining the day at the end of the month is taken from [this answer of mine (steps 6a-6d)](https://codegolf.stackexchange.com/a/173126/52210). Step 1: Add the given input amount of months to the date: ``` ¦ # Remove the day from the (implicit) input date-list R # Reverse it to [y,m] 1Ý- # Subtract [0,1] from it, to make the month 0-based 12β # Convert from a base-12 list to an integer + # Add the second (implicit) input-integer 12‰ # Divmod this by 12, pushing the pair [n//12,n%12] ` # Pop and push both separated to the stack > # Increase the 0-based month back to a 1-based month ¹ # Push the first date-input again н # Pop and only leave its day ) # Wrap all three values back into a list R # Reverse it to [d,m,y] again ``` Step 2: If the input-date was at the end of the month, change the resulting date to the end of the month as well: ``` ¹ # Push the first date-input again "..." # Push the string defined below © # Store it in variable `®` (without popping) .V # Pop and execute it as 05AB1E code Qi # If the top two values are equal # (thus the input was at the end of the month) т0ǝ # Replace the current day with 100: [100,m,y] } # Close the if-statement ` # Pop and push d,m,y separated to the stack т‰ # Divmod the year by 100 0K # Remove all 0s from this pair θ # Pop and leave just the last value 4Ö # Check if this is divisible by 4 # (1 for leap years; 0 if not) U # Pop and store this isLeapYear check in variable `X` D # Duplicate the month <i # If it's 2 (thus February): \ # Discard the month 28X+ # And push 28 + isLeapYear instead ë # Else: < # Decrease the month by 1 to make it 0-based 7% # Modulo-7 É # Modulo-2 31α # Pop and push its absolute difference with 31 # (the stack will now contain the day, and the amount of days in # this month) ``` Step 3: Fix potential overflow for the resulting date, after which we can output the result: ``` D # Duplicate the result ®.V # Determine the amount of days of this month ‚ # Pair the current day and end of month day together ß # Pop and push the minimum of the two 0ǝ # Insert this day back into the [d,m,y] # (after which the result is output implicitly) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 100 bytes ``` (y,m,d,i)=>(D=(m,d)=>(a=new Date(y,m,d)).getMonth(),D(i+=m+!(b=D(m,d+1)==m),b)-D(i,b*d)&&D(i+1,0),a) ``` [Try it online!](https://tio.run/##jZTPb9owFMfv/BVvl2IvTmqn21pUmV3YbjvtNFG0GmKopySOEkNJp/3t7DkEQmkqESmR7fd9n/fDsf@ojaoWpSlcmNtE75ZyR2qWsYQZKsdkIgmO/UjJXD/DRDm9t1MarbT7YXP3RCibEBPILPhA5nLiPQJBpcwom9MQTWz@MaFXV14kGKdM0Z3TlQMJj4OYxyLkIrwRDDg0jxxDtwpA5rY0@Yq@koozaRzGdyjNLdiNLpepfW70PBRxr75F53rroNaq7NT8tk/Nb9@oj7mE4kTdRkR1UeqNsevq3IP3evD3PXhvDN4fo6UxiC/rUGt5W/PNvgqdJ6FdhpnfaAjHcDo/AEZNwDOA4JcD9hlg5qc1@tXRJQDeWwL3JTQlp1oVTYMghPgu4jGYCnLrzkhiNPrcpSI@8YYkRpyfNM@BgiOPDh4jV5qM0KgqUuPI8CEf0ihTBUm9798BwMLm@KdPtwxqBr8ZvMzwt09b/TX7@lAF1/QehaV26zKHaRRF2wMubGkbTws2lEGAFFS8vKeYDf4hbWnLTPnzhWcVMgYJ9eYaAkAH/JLMD9G1UMlPp0pHYjx9tLMnvfb7gT@2EdK/qcUTIVODeIN8k@BrGGica5zrZEZfN8CufTpLsvfAjRAHr6b4VlSjBpX@Zvm@TtNf2GO8XMBm3Xp742B@SLBJZ2iupiPMpjpK7YrsO0G6RBFHhlgjBu6q@4KrrdLWPp5Hd2tdWb06kLJHiangVuz@Aw "JavaScript (Node.js) – Try It Online") Input 4 parameters `year, month, date, increase`, while `month` is 0-indexed (as what JavaScript `Date` type do: Jan = 0, Dec = 11). Output a `Date` Object. Only work if user is using UTC timezone. If you want change to 1-indexed month, it could be fixed +2 bytes (add a `--`). ]
[Question] [ Seven countries lay official claims to parts of Antarctica: Argentina, Australia, Chile, France, New Zealand, Norway, and the United Kingdom. We will focus only on the claims of the main Antarctic landmass south of 60° S, which are: * Chile: between 90° W and 53° W * United Kingdom: between 80° W and 20° W * Argentina: between 74° W and 25° W * Norway: between 20° W and 44°38[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E * Australia: between 44°38[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E and 136°11[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E; and between 142°2[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E and 160° E * France: between 136°11[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E and 142°2[′](https://en.wikipedia.org/wiki/Minute_and_second_of_arc) E * New Zealand: between 160° E and 150° W The region between 150° W and 90° W is unclaimed. Note also that Chile's, the UK's, and Argentina's claims overlap to some degree. Here is a map: [![Map of the world with all but Antarctica blurred, a 0° line of longitude marked, and claims of Antarctica highlighted. (exact description of claims above)](https://i.stack.imgur.com/yZN9j.png)](https://i.stack.imgur.com/yZN9j.png) The above image modified from work at <https://w.wiki/4e3R;> used under CC-BY-SA 3.0. More information and maps are available [on Wikipedia](https://en.wikipedia.org/wiki/Territorial_claims_in_Antarctica). All of these claims extend northwards from the South Pole at 90° S. It is unclear where Norway's stops, but it does not matter because we will only ask about the claims *just* north of the South Pole. ## Task Your task is to encode the information about the claims in the fewest bytes possible: given an input \$ x \$, output the set of countries which claim Antarctica at longitude \$ x \$° and latitude 89.9° S. You should represent outputs of countries using any seven distinct values, within reason. For the areas where multiple claims overlap (which are variously those of Argentina, Chile, and the United Kingdom), you should output the multiple values representing those countries. These multiple outputs may be in any order. For the unclaimed region between 150° W and 90° W, you should output an empty list. ## Test cases ``` Input -> Output(s) -------------------------------------- 0.0 / 360.0 -> [Norway] 180.0 / -180.0 -> [New Zealand] 223.2 / -136.8 -> [] 270.1 / -89.9 -> [Chile] 280.5 / -79.5 -> [Chile, United Kingdom] 296.6 / -63.4 -> [Argentina, Chile, United Kingdom] 337.6 / -22.4 -> [United Kingdom] 340.3 / -19.7 -> [Norway] 44.6 -> [Norway] 44.7 -> [Australia] 139.4 -> [France] 142.0 -> [France] 142.1 -> [Australia] 161.8 -> [New Zealand] 190.5 / -169.5 -> [New Zealand] ``` ## Rules * Your code must support non-integer longitudes. Small errors due to floating-point precision errors are acceptable * You may choose to require input \$ x \$ between -180° and 180° (with negative values representing west of the Prime Meridian), or between 0° and 360°. You only need to support one of the two edges of whichever range you choose * Behaviour exactly on the boundaries of claims (e.g. at exactly 20° W) is undefined * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 137 bytes ``` ≔×⁶⁰NθEΦE⪪”}∧¡8↥″⟧MX⬤~m→⊖⊗9⁸'DQζF%f¹ψz‖aνy("⟲?⎚‹3I‹4↥GNOk³▷H!J;⁵´j‹Z*I:↷¡!β↑}1⊞↘≦QêY(¦≔πω/_²≔▶⁶ω≧N4Þ⁰^⊕﹪WÞ|l⎚V2⊖¬|η&f≔”¶⪪ι ››I⊟ιθ›I⊟ιθ⪫ι ``` [Try it online!](https://tio.run/##XVBNa4QwEL33VwyeIthignWVPcnClrZUFtpeipdUgzsQRxtjl/56m2TpB3uavI95zEt7lKYdpV7Xap6xJ/aCg5pZniZwT9Ni62V4V4bFcQIf8fbqYJAse5IT26O2TvDP50mjZVE9mpP8ghREvikaqpbZGqlRBgwF3/CG9kZSqwKA4laI/zaPoczTtKFaneBNSS2pCwxwEfjdEbUCngtPFZlw1CuhVR08IvXdODitcJpIM2@vTK/IIkngWZl5mof086HBBIK75CiBqKHIlTx3QYch8qXvjJK@58/cydmywzgxDD/yZ7gQ/O7DiPQbFW/XVZT5Tb5ef@pv "Charcoal – Try It Online") Link is to verbose version of code. Assumes input is non-negative but less than `360`. Not much shorter than the JS version because I output country names. ``` ≔×⁶⁰Nθ ``` Multiply the input by `60` to convert it into minutes. ``` EΦE⪪”...”¶⪪ι ››I⊟ιθ›I⊟ιθ⪫ι ``` Split the compressed data string on newlines and again on spaces. Keep only those where the input is between the boundaries or on the lower boundary. Fix up "United Kingdom" back into a single string (using "UK" would save a byte, and double-spacing the output would save a further 3 bytes). 78 bytes using custom output: ``` ≔×⁶⁰NθI﹪⌕AEE⪪”←&!ω\⟧≕G⁵↑³yυ~r,S⦃›F⁷ω(D⧴aM↖G≕%›"‽.⊞⭆↓‽ⅈ0ÀG→$”¶⪪ι ››I⊟ιθ›I⊟ιθ¹¦⁷ ``` [Try it online!](https://tio.run/##XY/BasMwDIbvewrhkwzZsEXmOPRUBi09dBS2oy9eGzqD62SJ09f3bI8x2EG/@SRL@nX@tPN5tD6l7bK4a8B3dxsWVKKBQ5jW@LrePoYZOW/gi28eTrMLEV/sEvE4XlY/4s6Fy9Z7PNqpxtvkXUQmgFSnTSgKWnbShKKgn4lM6JUQICmrCVJRAd1SBZ2BRFsrbd8WkAVqDkjWnjIFyhDWADOBZXc/e11mYMXtfh5szM5/3@r5NE7o6il/H/4VSq/M0XG@SYl69aTS491/Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Obtains the indices of the matching ranges and reduces modulo 7 to output digits according to the following key: ``` 0 Norway 1 Australia 2 France 3 New Zealand 4 Chile 5 United Kingdom 6 Argentina ``` (Note that the ranges are ordered slightly differently in this version.) [Answer] # JavaScript (ES10), 128 bytes Expects a signed value. Returns **0** for New Zealand, **2** for Argentina, **32** for Norway, **34** for Chile, **64** for United Kingdom, **65** for France, **98** for Australia. ``` v=>[90,100,106,160,a=13478/60,b=19322/60,c=18971/60,0,340].flatMap((x,i)=>v<x|v>[127,160,155,a,c,340,b,30][i]?[]:x*29&99,v+=180) ``` [Try it online!](https://tio.run/##fZBfS8MwFMXf9ynyJK1mWdJ2baO2MkRfRF@GL5Y@3PXPFqnJyGI2we9e29WJzGEgcO85P87l3lewsCm0WJuxVGXV1klrkzTjFDPa/xCzkGJImB9E8aQrFwnjvuf1ZZGwmEesLyn2A5qTugHzCGvH2WHhJqm93n3aNGNetE9h0ykGXPQoXmCf5pnIb7L8cnfu8TPOsb3oAqnbXmUj1D9KKEaTCcqelN7CR96p4w74UasteqmgAVkOlh@SeLD6Ho1jTvjQ365EUw1ixMn0l4jRsxSmKtGDkMtSvQ1Q6JNggGZ6WUkjJGD0D@95B/6UyziJjhdBKAhIeFL9ZmfvG6OhEbA3mM8PI@41yGLYhgXe4RpHKjsZEjISo7/Hy0ekVvoOipVjUZKiQsmNairSqKVjiVFzo7t9HJesoZwb0MYJXYxqx7qu234B "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~247~~ 172 bytes * -7 thanks to pxeger * -3 by changing the output values (and fixed a bug) * -6 thanks to gastropner * -8 by changing the range format to (offset, starting longitude) * -61(!) thanks to Neil Takes a floating-point longitude from `[0, 360)` degrees, but performs all the computations using integer minutes. For Norway, I split up the range into two sections to make calculations easier. Countries are expressed in the following format: * 0: Norway * 1: Australia * 2: Chile * 3: United Kingdom * 4: Argentina * 5: France * 6: New Zealand ``` g[]={1078,8522,2678,0,3e3,9600,351,8171,2940,17160,3600,16800,2220,16200,5493,2678,1201,20400},i,j,*a;f(float l){for(i=l*60,j=9,a=g;j--;)*a+++0u>i-*a++&&printf("%d,",j%7);} ``` [Try it online!](https://tio.run/##PVDLboNADLznK1wkIh4G7YNnV/RHUg6IBLqIQkXS9hDx66VeIDnseOy1xxrXQVvXy9KeyuLOWZphFguBIiHGUF4k5gkjEnPMeMpR5BFDIgnVzAdPMkIhhKGCaBzlchvnglE/ixibUWOHXqUap@nH6ga9e2/GydFF75FQV@RYFa3qgkC5XuX7Pvt@04Fhx@PXpIdb41j2GS3s7NRV80IV@Kz04PyM@uzC/QCw6w7t1RgBhsAzAiFkKCikLOQUMhbGFPIkTBCkTNcQsVAiRJFJCFMalXkYUYjECmaUJzzMEAIOs6J19Uc1gVeP03Spb@tGi1kIVmLAPLECqT8iaRu65uwJ3ED8BL5pbDuMS60Oxtx6K6Y2f7p8KQKuQPv@5h3geaQGHJsuUrzBiaT2dgSHvt09o4u7ap1qnL205w@VEpzd2Suc7Gvpvg8k9jC7t8@Hefmrm75qr0vw@w8 "C (gcc) – Try It Online") Ungolfed: ``` g[]={ 1078,8522, // Australia 2678,0, // Norway 3000,9600, // New Zealand 351,8171, // France 2940,17160, // Argentina 3600,16800, // United Kingdom 2220,16200, // Chile 5493,2678, // Australia 1201,20400 // Norway }, i,j,*a; f(float l) { for(i=l*60, // Convert input into minutes j=9,a=g;j--;) *a+++0u>i-*a++&& // (Input-start longitude) within range? printf("%d,",j%7); } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~55~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 60*ò•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в2ô€ŸQOƶ0K7% ``` -1 byte thanks to *@Neil* by also using modulo-7. Input as a longitude float in the range \$[0,360)\$. Outputs \$0\$ for Argentina, \$1\$ for Australia, \$2\$ for Norway, \$3\$ for France, \$4\$ for New Zealand, \$5\$ for Chile, and \$6\$ for the United Kingdom. [Try it online](https://tio.run/##AW4Akf9vc2FiaWX//zYwKsOy4oCiMc62X8qSx509wrbDksK04oSicF3Ct8OQzpjDpMKlw4tywqrDnsO3w4IwW@KCgcK1w5HigKbOtUNgwqPigKLFveKJoMK20LIyw7TigqzFuFFPxrYwSzcl//8yODAuNQ) or [verify all test cases](https://tio.run/##dZI7SwNBEMf7@xRDwEbGY@/hnRE0SNAmoFjYGIOeyZocxEu4uxjTaRBBbDSVjSK@CrESk9jY3BIFi@BnuC8SN3sJxlezML@Z2Zn5z5Q8a9Omvdj8bplmfZoDl3qVou9NSwBEJjAxC5BeLLlVq5aRlKkvRKuwSq2i5eQykqpqshpxbphEViIjWbCLlBOeNjlCEFYcu18rZTv5XGmbR8QN2Ygi5tw8dXzbsRD@CdY0cxj8y6UTWfveM@j6MHoUmYNqFc93raJt8eG0uKxHdMG1nCxvXNHV4byjSPmdayjy1B/CSEsVv1zxPSCwVXJhZDYlAsMvEFQBohYRNGFFRRH0yPf1M8KkQAOFOAFDAL9Af@glx9YkaaeWiEF42IBYotYzyDh7DPeulG5r/b3xdj4TtFgjeAoPrsqZoM1OumfsJrhlx25wzy5Ym9VJOqzvB012Gu7ddZvJjeCaZ3dewqPLoPXxqLKnsP7QeV5eem2RlDnWw16aID8VFGeB4h5Q3ACKPaNYIIpdYX87/cdEoT8KycWroFA18wk). **Explanation:** ``` 60* # Multiply the (implicit) input by 60 ò # (Bankers) round it to the nearest integer •1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£• # Push compressed integer 129995249012016373632115353299026583238712674313934551571472125857818360468822 Ž≠¶ # Push compressed integer 21601 в # Convert the larger integer to base-21601 as list: # [2678,8171,0,2678,8171,8522,9600,12600,16200,18420,16800,20400,17160,20100,8522,9600,20400,21600] 2ô # Split it into parts of size 2: # [[2678,8171],[0,2678],...] €Ÿ # Map each pair to an inclusive ranged list # [[2678,2679,2680,...,8170,8171],[0,1,2,...,2677,2678],...] Q # Check for each inner integer if its equal to the round(input*60) O # Sum each inner list, resulting in 1 if it was within that range ƶ # Multiply each by its 1-based index 0K # Remove all 0s 7% # Modulo-7 to transform the 8 to 1 and 9 to 2 # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•` is `129995249012016373632115353299026583238712674313934551571472125857818360468822`; `Ž≠¶` is `21601`; and `•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в` is `[2678,8171,0,2678,8171,8522,9600,12600,16200,18420,16800,20400,17160,20100,8522,9600,20400,21600]`. --- Outputting with the actual title-cased countries from the dictionary would be **85 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead, by removing the no longer necessary `7%` and adding some additional trailing bytes: ``` 60*ò•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в2ô€ŸQOƶ0K”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0”#sèεT”™ÆŠß”#1ú‡ ``` [Try it online](https://tio.run/##Aa8AUP9vc2FiaWX//zYwKsOy4oCiMc62X8qSx509wrbDksK04oSicF3Ct8OQzpjDpMKlw4tywqrDnsO3w4IwW@KCgcK1w5HigKbOtUNgwqPigKLFveKJoMK20LIyw7TigqzFuFFPxrYwS@KAncKyw5DLhuKAmsKsw6zLhsOW4oKswqIxwrjFvcaSxaAw4oCdI3PDqM61VOKAneKEosOGxaDDn@KAnSMxw7rigKH//zI4MC41) or [verify all test cases](https://tio.run/##HY07S8NQGIb/SqmbfBzOzSQdpIOjgwhupXgBB6eKhUKHQgwSEJeaQUSoxnhBJFNo0iJ0@T5SwULwN5w/Ek9dHl7eC2@vf3xydloPhu1mw4RRo9ke1g7fpMz4iaiKw5/oe7KNBUU4NVfJeRdnNK7u6RXf6OYCP@mRZhTwjgkuMadb479X@c4Rvth1uTDXMRa/maSpCdJyvr@3LPiu8SeY0XgVGv8BU0pXId3ZGBOB83KxjMqY28pGnz6q/MAq@0phGdPT2hX0ZfznegR1h4PwOEipmATpciZAepxtgWw5zAGl3DU1Zwq0ttLCBaFaTIPQkvF/ChCOYF73Dw). **Explanation:** ``` ”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0” # Push dictionary string "Argentina Australia Norway France New1 Chile United0" # # Split on spaces sè # Modular 0-based index the calculated value into this list ε # Map over each result: T # Push 10 ”™ÆŠß” # Push dictionary string "Zealand Kingdom" # # Split it on spaces 1ú # Pad each with a leading space ‡ # Transliterate the "1" to " Zealand" and "0" to " Kingdom" # (after which the resulting list is output implicitly) ``` [See the same 05AB1E tip I linked earlier (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0”` is `"Argentina Australia Norway France New1 Chile United0"` and `”™ÆŠß”` is `"Zealand Kingdom"`. ]
[Question] [ ## Background A little while ago, someone posted an [interesting puzzle](https://math.stackexchange.com/q/3873941/773859) on Math.SE: > > What is the smallest digraph (directed graph) G where the following eight graphs are all distinct: > > > * G, the original graph > * Reflexive closure of G > * Symmetric closure of G > * Transitive closure of G > * Reflexive symmetric closure of G > * Symmetric transitive closure of G > * Reflexive transitive closure of G > * Reflexive symmetric transitive closure of G > > > A quick refresher on the terminology: * A reflexive graph satisfies: for every vertex X of G, the edge (X,X) is present in G. * A symmetric graph satisfies: for every pair of vertices X and Y of G, if the edge (X,Y) is present in G, the edge (Y,X) is also present. * A transitive graph satisfies: for every triple of vertices X, Y, and Z of G, if the edges (X,Y) and (Y,Z) are present in G, the edge (X,Z) is also present. * A reflexive/symmetric/transitive closure of G is the smallest superset of G that satisfies the given property. Note that, for example, *symmetric transitive closure* is not equal to *symmetric closure of transitive closure* in general. For example, the following (from the original Math.SE post) shows an example graph that satisfies the original question: ![](https://i.stack.imgur.com/n0mA3.jpg) ## Challenge Given a digraph G, determine if it satisfies the above puzzle (G and its seven closures are all distinct). The input digraph G can be represented in any reasonable way: adjacency matrix, adjacency list, flat lists of vertices and edges, etc. Since the answer is always false when isolated vertices are not allowed, the representation must include some representation of the list of vertices. For output, you can choose to 1. output truthy/falsy using your language's convention (swapping is allowed), or 2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. The shortest code in bytes wins. ## Test cases ### Truthy ``` # the example in the image vertices: [1, 2, 3, 4, 5, 6] edges: [[1, 2], [2, 3], [3, 4], [4, 2], [4, 5]] adjacency matrix: [[0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] # the smallest answer in Math.SE vertices: [1, 2, 3, 4] edges: [[1, 2], [2, 3]] adjacency matrix: [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` ### Falsy ``` # the incorrect answer in Math.SE vertices: [1, 2, 3] edges: [[1, 2], [2, 3]] adjacency matrix: [[0, 1, 0], [0, 0, 1], [0, 0, 0]] # a modification of 4-vertex correct answer, ST=RST vertices: [1, 2, 3, 4] edges: [[1, 2], [2, 3], [4, 4]] adjacency matrix: [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 1]] ``` [Answer] # [J](http://jsoftware.com/), 71 58 bytes Takes in the adjacency matrix. ``` */@~:@(,([+./@,#)"#/~^:_"2)@(,s@r,(s=:+.|:),:r=:[+.=@i.@#) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfQd6qwcNHQ0orX19B10lDWVlPXr4qzilYw0gaLFDkU6GsW2Vtp6NVaaOlZFtlZAZbYOmXoOypr/Nbm4UpMz8hXSFJT0rPXijRQ0wEZrchkoGAJtgEAuEGGIzIFx4coMETIoyqAcQtbAbIDpgtMENEL1cVFmjSGX5n8A "J – Try It Online") ### How it works First the original, `s`, `r` and `r->s` variants are computed, then all their transitive closures. Albeit the operations are not commutative, I believe calculating the transitive closure last will work here (`r->t` is equal to `r->t->r` as `r` just adds the diagonal, which was already set. `s->t` is equal to `s->t->s` as every transition was already symmetric. `s->r` is equal to `r->s` as every reflexion is symmetric.) Though this might be wrong, and if it is, I'm happy to slap some `^:_` on there. :-) * `r=:+.=@i.@#`: original matrix OR the diagonal `=@i.@#`. * `s=:+.|:`: original matrix OR its transposition `|:`. * `,s@r,s,:r`: original matrix and all its variants in a list. * `([+./@,#)"#/~^:_"2`: until the result does not change `^:_`: for every node: take the neighboring rows `#`, append them to the current row `[ ,` and OR them together `+./`. * `*/@~:`: `~:` returns whether each element of the list is unique, then AND `*/` those booleans. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ ~~29~~ ~~27~~ ~~26~~ ~~25~~ 24 bytes ``` ,|Z$æ*ⱮLS,Ʋ€Ẏæ*0|,Ʋ€Ẏ¬QƑ ``` [Try it online!](https://tio.run/##y0rNyan8/1@nJkrl8DKtRxvX@QTrHNv0qGnNw119QAGDGjjv0JrAYxP/H24H8v7/j@aKjjbQUTDUUTCAo1gdLoVoCNsQmyBCHCZoiCyOqhKrdpggUBTZejSL0fSgc5E1I@tEVkeJDYaxsVyxAA "Jelly – Try It Online") (comes with a test harness that runs all test inputs) Takes the adjacency matrix and returns `1` or `0`. I'm very rusty in code golf (especially in Jelly) and this solution tries to stay very safe regarding the specification, so there is very likely room for improvement. (Edit 7 bytes later: yes, there was. For example, just found out about `Ƒ` when re-reading the docs.) ### Explanation 1. The main link gets the adjacency matrix. 2. `Z` transposes the matrix and `|` bitwise-ORs it with the original. This gives the symmetric closure. `,` makes the pair `[orig, SC]`. 3. `€` does the following for each of the two matrices: 1. `L` finds the edge length N of the matrix. `æ*Ɱ` raises the matrix to each power 1…N to find routes of length 1 to N. `S` sums the resulting matrices together to find all routes. This gives the transitive closure, but the matrix can have values greater than one. `,` makes the pair `[TC, orig]`. 4. `Ẏ` flattens the outermost array, giving `[TC, orig, STC, SC]`. 5. `€` does the following for each of the four matrices: 1. `æ*0` gets the zeroth matrix power, i.e. the identity matrix. `|` bitwise-ORs it with the previous matrix, giving the reflexive closure. `,` makes the pair `[RC, orig]`. 6. `Ẏ` flattens the outermost array, giving `[RTC, TC, RC, orig, RSTC, STC, RSC, SC]`. 7. `¬` logical-NOTs all values in the matrices to turn 0 into 1 and anything else into 0. This makes all nonzero values equal. 8. `Q` removes duplicates from that list and `Ƒ` sees if it stayed the same. ### Correctness The order of operations here is important. The transitive closure must be performed after the symmetric closure, but the reflexive closure can be performed at any point. I'll try to give a (very hand-wavy) proof of my algorithm's correctness. For any path A1→…→An in SC(G), An→…→A1 will also exist, and thus TC(SC(G)) will be symmetric. SC(G) must be a subset of STC(G) (all "new edges" of SC(G) must also be in STC(G)) and TC(SC(G)) is the minimal transitive superset of SC(G). Thus TC(SC(G)) = STC(G). RC(STC(G)) is always symmetric and transitive, since the edges added by RC will never break transitivity or symmetricity. STC(G) must be a subset of RSTC(G) (all "new edges" of STC(G) must also be in RSTC(G)) and RC(STC(G)) is the minimal reflexive superset of STC(G), so RC(STC(G)) = RSTC(G).1 [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes ``` ⊞υθ⊞υEθEι∨λ§§θμκF⮌υ⊞υEιEκ∨μ⁼νλFEυEιλ«FθUMιEλ∨ν⊙λ∧π§§ιρξ⊞υι»⬤υ⁼¹№υι ``` [Try it online!](https://tio.run/##bU49C8IwEJ3Nr7gxgRPq7FTEwUEsrqVD0IrFNGnTpijib4@X2GJBM@TyPu7lna7SnoxU3meuu3KH0Io1m9572fD2MyqEg@UKIe13@lze@TRJrwXCTYSzZhdjgR/LobRdyZ0QMM@qPuMWs2qEbeuk6rhGUPP14PluBAmebBGlVgR6Y@pa6vOUp2IepaT6ESuS1Pw2Jbelpvfxq8XUrCLwYpmtdM9TpQI1FlshbIwjOrrClvd5nicIpNCdFMgAAh6pOU7@4aLwy0G9AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an adjacency matrix. Explanation: Port of @xash's answer. ``` ⊞υθ ``` Push the input to the predefined empty list. ``` ⊞υEθEι∨λ§§θμκ ``` Logical Or the input with its transpose and push it to the list. ``` F⮌υ⊞υEιEκ∨μ⁼νλ ``` For each matrix in the (reversed) list, logical Or it with the identity matrix and push the result to the list. (The list is reversed because otherwise the For command will attempt to iterate over the new results.) ``` FEυEιλ« ``` For each shallow cloned matrix in the list... ``` Fθ ``` ... for as many times as the size of the matrix... ``` UMιEλ∨ν⊙λ∧π§§ιρξ ``` ... logical Or the matrix with its square, and... ``` ⊞υι ``` ... push the final result to the list. ``` »⬤υ⁼¹№υι ``` Check that all of the matrices are unique. ]
[Question] [ [Part 1 of the task is here](https://codegolf.stackexchange.com/questions/196123/flag-mashup-generator) [Flags Mashup Bot](https://twitter.com/flagsmashupbot) is a small Twitter bot that generates a new country name based on two random country names and tweets the result every couple of minutes. ## Task Your task is to replicate what the bot does by writing a script or a function based on the following criteria: * The input is two country names in English as [shown in this page](https://www.worldometers.info/geography/alphabetical-list-of-countries/). Country names contain upper or lowercase letters of the English alphabet, spaces or dashes, and there's a special case of `Côte d'Ivoire`. They are usually capitalised with the exception of prepositions and similar words. Examples: `United States of America`, `Portugal`, `Côte d'Ivoire`, `Guinea-Bissau`. * The output is a single country name that is a mixture of the two inputs based on the following rules: + If both names are single words you have to split each country name after a vowel randomly, then use the first half from the first country and the second half of the second country. - Vowels are `a`, `e`, `i`, `o`, `u`, or their uppercase variants - After the split both parts should contain at least one letter. The first half will always contain the vowel it was split by. The second half doesn't need to contain vowels however. - Example: `Poland` can be split by either `Po/land` or `Pola/nd` - Example: `Algeria` can be split by `A/lgeria`, `Alge/ria`, or `Algeri/a`. However `Algeria/` is not valid, as the second half doesn't contain any letters. - Example output: Mixing `Poland` and `Algeria` can be either of the following: `Polgeria`, `Poria`, `Poa`, `Polalgeria`, `Polaria` or `Polaa` + If one of the country names are multiple words while the other is a single one, then you have to replace either the first word of the multi-word one, or the last word with the other dependent on whether the multi-word country name is the first or second. - Example: `United States of America` and `France` is `United States of France`. - Example: `France` and `United States of America` is `France States of America` + If both names are multi-word ones then you have to split both of them at one of the word boundaries and then join them together afterwards. - Example: `United States of America` and `Trinidad and Tobago` can be `United and Tobago`, `United States and Tobago`, `United States of and Tobago`, `United Tobago`, `United States Tobago`, or `United States of Tobago` + Special case 1: countries containing dashes counts multi-word ones. If you split the name at the dash you have to use a dash in the output instead of a space - Example: `United States of America` and `Guinea-Bissau` can be `United States of-Bissau` among others - Example: `Spain` and `Timor-Leste` is `Spain-Leste` + Special case 2: If you enter the same country twice, you have to return `<country name> 2`. - Example: `United States of America` and `United States of America` will return `United States of America 2` - Example: `Hungary` and `Hungary` will return `Hungary 2` Notes: * Your submission should work for at least the countries as shown [in this list](https://www.worldometers.info/geography/alphabetical-list-of-countries/) * It is okay if the result is the same as one of the input countries, e.g. `United States of America` and `United Kingdom` can result in `United Kingdom` * `Côte d'Ivoire` counts as two words: `Côte` and `d'Ivoire`. * There are no countries in the list that contain both spaces and dashes * Vowels are `a`, `e`, `i`, `o`, `u`, `A`, `E`, `I`, `O`, `U` * Standard loopholes, as usual, are prohibited Examples with all valid answers for a specific pair: ``` Poland, Algeria Polgeria, Poria, Poa, Polalgeria, Polaria, Polaa Algeria, Poland Aland, And, Algeland, Algend, Algeriland, Algerind United States of America, France United States of France France, United States of America France States of America United States of America, Trinidad and Tobago United and Tobago, United States and Tobago, United States of and Tobago, United Tobago, United States Tobago, United States of Tobago Trinidad and Tobago, United States of America Trinidad States of America, Trinidad of America, Trinidad America, Trinidad and States of America, Trinidad and of America, Trinidad and America Hungary, Hungary Hungary 2 United States of America, United States of America United States of America 2 United States of America, Guinea-Bissau United-Bissau, United States-Bissau, United States of-Bissau Guinea-Bissau, United States of America Guinea-States of America, Guinea-of America, Guinea-America Timor-Leste, Spain Timor-Spain Spain, Timor-Leste Spain-Leste Côte d'Ivoire, Portugal Côte Portugal Portugal, Côte d'Ivoire Portugal d'Ivoire Côte d'Ivoire, Timor-Leste Côte-Leste Timor-Leste, Côte d'Ivoire Timor-d`Ivoire ``` [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code by byte count wins and will be accepted. Please include example a set of input & output with your submission [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~74~~ 73 bytes ``` JṖXṬk⁸ḢḢFṪ;ƲƭF)jṪḢƭ€Ṁ$$ ḢṖ; ṪḢṪ;Ɗṭ Fe€ØcṖTXṬkḢḢṪƭ) e€⁾ -k)ẈỊḄ‘ƲĿ Ḣ,2KƊÇE? ``` [Try it online!](https://tio.run/##JY69SsRAFIX7@xRTbBPYNNsGlBWMohaCEbYdkzFMNk4gP@B2WREisV@20MZSNk2wyBjQIjLvMfMi42QXbnE457uHE5E4Xml9IflmIfluqdad7D7MuZJ/OqIVjWtFRhpHNOppJ3k5mcCI8I0Dh2BP1pI34BKDDFvfhN6@7tBlANFYMIZq/YPspSW/X2Rfy@5ZlVvR/v2OjdPZpaiH6vRYR6p8nzqqfEP2ETLaGSqQ/dfV42wxTuhfRTtUWl8nMWYBzOOQpBTDLaM5CdBNjnOSoeQezR@M72NwU8x8Al5KGQ1wgMwT8pI7HCZwXrAQpys4Kygj2D6hWYaLfw "Jelly – Try It Online") A full program that takes a list of two strings as its argument and implicitly outputs the mashed up country name. The handling of hyphens is relatively costly, particularly since they are included whichever side of the split they fall. ## Explanation ### Helper link 1 Handles case where both countries have multiple words ``` ) | For each country: J | - Sequence along words Ṗ | - Remove last X | - Pick one at random Ṭ | - Convert to a boolean list with a 1 at that index k⁸ | - Split list of words after that point ƭ | - Alternate between: Ḣ | - Head (first set of words for the first country) Ʋ | - Following as a monad (for the second country) Ḣ | - Head (first set of words, also removed from the country) F | - Flatten Ṫ | - Tail (i.e. last character which will be space or hyphen) ; | - Concatenate to remaining words for second country F | - Flatten $ | Following as a monad j $ | - Join countries with following as a monad ṪḢƭ€ | - Alternate between tail for first country and head for second Ṁ | - Max (will be hyphen if one present, otherwise space) ``` ### Helper link 2 Handles case where only first country has multiple words ``` Ḣ | Head (first country) Ṗ | Remove last word ; | Concatenate to second country ``` ### Helper link 3 Handles case where only second country has multiple words ``` Ṫ | Tail (second country) Ɗ | Following as a monad: Ḣ | - Head (first word; note this will also be removed from the first country) Ṫ | - Tail (last character) ; | - Concatenated to remaining words ṭ | Tag onto the end of the first country ``` ### Helper link 4 Handles case where both countries have single words ``` ) | For each country F | - Flatten (remove the layer of lists generated in helper link 5) e€Øc | - Check whether each character is a vowel Ṗ | - Remove last T | - Comvert to list of indices X | - Pick one at random Ṭ | - Convert to a boolean list with a 1 at that index kḢ | - Split the original country name after that vowel ḢṪƭ | - Alternate between taking the head (for first country) and tail (for second) ``` ### Helper link 5 Splits each country into words and dispatched to helper links 1-4 depending on which countries have multiple words ``` ) | For each country: e€⁾ - | - Check whether each character is a space or hyphen k | - Split country after those characters ƲĿ | Call the link indicated by the number calculated by the following monad: Ẉ | Lengths of lists (i.e. number of words in each country) Ị | Insignificant (abs(x)<=1) Ḅ | Convert from binary ‘ | Increment by one ``` ### Main link Determines if countries are equal, and otherwise calls helper link 5 ``` E? | If both countries equal: Ɗ | Then, as a monad: Ḣ | - Head (first country) ,2 | - Pair with 2 K | - Join with spaces Ç | Else: Call helper link 5 ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 242 bytes ``` a=>b=>a==b?a+" 2":((d=a.LastIndexOfAny(z=((j=new[]{a,b}.Count(x=>"- ".Any(x.Contains)))>0?"- ":"aeiouAEIOU").ToArray()))<0?a:a.Remove(d+1))+b.Remove(0,j+new Random().Next()>0?(d=b.IndexOfAny(z)-j%2+1)<0?0:d:b.LastIndexOfAny(z));dynamic z,d,j; ``` [Try it online!](https://tio.run/##lZLfS8MwEMff/StCQEjoD@oeu6WjiMPBcLJ1@CA@XJu0pKyJtKm2E//2maqTuYHgU@4un@/3LkeyxssauZ@1Kps0ppaqcI/jryOKcrYHFqUsAsbSKTgYjXBICGfgL6Axc8VFt8xj1ZMdI6RkSrw@Pr2Bm77717pVhnQswh7C/oB0tqYMSNVQSqNgOlyEGITUbXwzX24w9RMd1zX0xAKTYAoh@CtR6RdBuHNFqZMe0sAtHdsLrUBxXRHq34nOkMHUzpb6x3NRr7wcWbX1C0IepmeDUzrmvYJKZmjncrcc7x9qacRCKkFygu/11jbBlOB4W4haAraCi1/IRtmEo7UBIxqkcxRXFsxgEM1qUJk41xzqf6lPNYmsdO0tRGM@hetnu8tz6rt8gp9St60qoO4H7if8z7sS@0EkB47sclCiUyj0YLD/AA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~395~~ ~~332~~ ~~336~~ ~~318~~ 313 bytes ``` def f(c,d): j,k=[' -'['-'in s]for s in c,d];u=c.split(j);v=d.split(k);n,m=len(u),len(v);D=max(j,k);b=D in c+d if(n>1)^(m<2):i,j=[choice([i+1for i in range(len(s)-1)if s[i]in['aeiouAEIOU',' -'][b]])for s in c,d];R=c[:i-b]+b*D+d[j:] else:R=D.join((u[:-1]or u)+v[m>1:]) return[R,c+' 2'][c==d] from random import* ``` [Try it online!](https://tio.run/##pZDBSsQwEIbvfYrckthW6B5bI6ysiiAo63oKEdIkXae2yZKkiz79moqICorgaZLMN1/@ZPcSH51dHA7adKgjqtC0zlBfPDGOUYk5LjFYFETnPAooLRMhmomp47AbIJKeNnum3zdPtLHFyAZjyUSLuexps2KjfCbJSJuWrd4Uuc4QdMSeVvSBjCcLWkPRM64eHShDOOTVfB3MrJd2a8isCrSsKHQocBBgOZYG3LQ8v7q5x8UcVfBWCPo155opXkPZirw9WuWa97XIkBmCqddsddw7sIRMvC4rkcYmmu/5eFrVgmbImzh5y9eFyjFaJLliTIus826cM@lUYNw5H48OOw82pr/Dt25InZRmOWyNB4lp9tG7txCNRndRRhOQ69ByTIiSif6x9bfxixRHmc/w@8m/zZvEgJYapVehjWvl1n2evJzAGlmeQQhy@j3IV/QXxwZG58trE6L5Y8jv6sMr "Python 2 – Try It Online") 17 bytes thx to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink); and a hat tip to [SztupY](https://codegolf.stackexchange.com/users/8732/sztupy) for pointing out a bug. [Answer] # [Lua](https://www.lua.org/), ~~614~~ ~~604~~ ~~600~~ 585 bytes ``` g,s,y,e={},{},{}r=math.random for _,v in ipairs({A,B})do c=0 for w in v:gmatch(".?.'?%a+.")do c=c+1(_<2 and g or s)[c]=w end end h=s[1]:find('-')and'-'or' 'u,k=#g,#s if u==1 and k>1then s[1]=g[1]..h e=s elseif u>1 and k==1then g[u]=s[1]e=g elseif u>1 and k>1then c=0 for i=1,r(u-1)do c=c+1y[c]=g[i]end for j=r(2,k),k do y[c]=y[c]:gsub(' ',h)c=c+1y[c]=s[j]end e=y else g,s={},{}for i=1,10 do t=("aeiouAEIOU"):sub(i,i)p=A:sub(1,A:find(t)or 0)g[#g+1]=#p>0 and#p<#A and p or q;p=B:sub(1+(B:find(t)or#B),#B)s[#s+1]=#p>0 and p or q end e={g[r(1,#g)],s[r(#s)]}end return A==B and{A," 2"}or e ``` [Try it online!](https://tio.run/##hZRpb9tGEIY/S79iQaIQWa8EUUnaxs06kIqmNVAgAeJ8IgSDplbURjSpcJdODUNA7/u@7/u@j/S@PuSHuTMvndhoC1SQxEe7M/sMl7PK62R/O3GzXpUUk3Lbaj0JSttL8zKdB6G4UUR9vMJ2m4aSXEzLSpus2My1c7qyQom9ODo5GKvO1Xs6kvAY473A44z3AU8w3g@8ifEB4M2MDwJvYXwIeJLxYcJBv8/4CDBifBQI22NA2B4HwvYEELYngbA9BYTtaSBszwBhe5Yxgu05IGzPA2F7AQjbi0DYXgLC9jIQtleAsL0KhO01IGyvMw5gewMI25tA2N4CwvY2ELZ3gLC9C4TtPSBs7wNh@wAI24eMx2D7CAjbx0DYPgHC9ikQts@AsH0OhO0LIGxfAmH7Cgjb14zHYfsGCNu3QNi@A8L2PRC2K0DYfgDC9iMQtp@AsP0MhO0XxhOw/QqE7TcgbL8DYfsDCNufQNj@6izb7WldpM6UhZgGQzmiXu92z5i7udfFxvrZNl@3dp2Woul6YQqxSExlg3@chlBMynZrqIarma23gmZUWleZIuuls6QKeJkwbLdGavR/MbqY7GfSyl2p1d5S4l2pI4cV9W3KHS7HNPXsUfnLcFKKVPUxfZknd1YzSktngdc73eucviFZ6XlNULoSBZunBoLWE5mgeBvG6VhdFiTHZ6ZsHI1Xp6aYBJ1uJ6RAupRVR3RqOVd@Jn0rzFTUSkVYZb4WuZkuBKepjL56vZnQygqdW82BawdxlIDALK7HkGiV/SvoYLFrd2NUJKug7kbXq9/lcrPYjLlYDrmoqmAg56Gc07MQmOavZrOpajkLDxNtfBGJWu1CLWi/m72@Zov6vIxTgZdoU9bD29fPXvDCVV7MSBMu6FEzR3LY7JELKbEfZrGfrdAG@Iu1Pt@JvzjlD3FLC97lS7cu6PkjcSUYHWb6o1DSx8a@PZp9kNQ8FLWXxRUJ/SwcS0vo23C85KlKu7oqxFCpEWdRL3hi4C0pVYt9Cmi307IuqNE0/ra9c2VOYZ70hnmmK5MQXSiM0xNx3iWOgsqpGG7TTMpTZ6jpUk2wQZ1qJskElW2UW0lW0uiddZEl1S7RHbUpdNIdGWuTmuPNdll179LWcfZ5atSCrrddveK0mHTWd0pT8cS5snJ1luQen0eqeUr97KjOSAr/sG4@X5hR18di/B7TOPevTksq67/SWs3ckcRmgDJblbZ17tQ0wFryYBk6p60F3a0LXLKV6x6NpYkLmmDpeXyQeV/5pP4N "Lua – Try It Online") **All possible combinations (75532)** --> [Click!](https://gist.githubusercontent.com/Maxxxel/84deca51e79da669aeee324cd930f0d0/raw/70ab4873a62b08e29d609207743b24bd19a34c01/All_Countries.txt) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~230~~ 228 bytes ``` ->c,d{g=->s,r{(0..s.size-2).select{|i|s[i]=~r}.sample} i=g[c,e=/[ -]/];j=g[d,e];c==d ?c+" 2":(c+d)[e]?c[e]&&!d[e]?c[/.*[ -]/]+d:!c[e]&&d[e]?c+d[/[ -].+/]:c[0,i]+[c[i],d[j]].max+d[j+1..-1]:c[0..g[c,r=/[aeiou]/i]]+d[g[d,r]+1..-1]} ``` [Try it online!](https://tio.run/##jY/NagIxFIX3PkXMwmonk1GXyii20B/ooqBdhSxich2uzI8kM6VW7VP1Dfpg0/gHbgQ34SbnO@ee2Gq@rhdxHY40M5skDkeO2U27y7njDr8h7He4gxR0udni1gmU8Y/dcaeyVQq7BsaJ0AziSJBQRnK49HfDQA51HBsy1gElfTpo68B0BMix9ker1TTHOeL3R1tgBs2jdFQCIw6BPIjkQIsuQxkI7XczI5ZS8kx9eWQZ9DgPeweC830P63sowKKSEUqfKvZlrDxxu3pVlY4sBH0vUpUbyugkTcCiorJxlj5yLMGQaalKcKRYkEnmCa0oI/TJqlzDBXx68NJV223JM4s5GmWIr0VmxVwlxYXzpcoTZdd78DzeFvtcYQ4qfEDnVHXhmWFW2PANXHkoP10pzK/Lj3@/JRBz9/pZoPXfr/8B "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 146 bytes ``` ' ^(.+)¶\1$ $1 2 /^\w+¶\w+$/&%@/(?<=[aeiou])\B/i%`$ X /\W.+¶.+\W/&%@/\W/%`$ X ¶.*?X|X(-?).* $1 -\W - /\W.+¶\w+$/&`\w+¶ /^\w+¶.+\W/&`¶\w+ dI d'I ``` [Try it online!](https://tio.run/##K0otycxLNPz/X52LK05DT1vz0LYYQxUuFUMFIy79uJhybSC/XFtFX03VQV/D3sY2OjE1M780VjPGST9TNUGFK4JLPyZcD6hKTzsmHKwKSEEkgGJa9hE1ERq69pp6WkAjuXRjwrl0YRogxiaAreCC2QUxJQEsy8WV4smVou75/39Afk5iXgqXY056alFmIgA "Retina – Try It Online") [Test suite](https://tio.run/##lVHbTsJAEH2fr5iHIoXegs@aCiYiCQ8mYCCxki50qZvArtnuiiZ@luED9MPq2kKgXpr4srMz58w5O7OSKsZJJ2/Y/RhGsYth3gSY2b7Tet9GHQusDp5CMIs2jsk3jhWcNC4COzw7vyOUCX3finoBa8QWTCGIJr5h@U40KVgmlICptcPp69T2wpbfNpLgRRPw9g2lbFxYwN6rVIkLFCAZQNIc5PmNWBGeuNhdpVQyArvoYgnALWeKJjhSRNEMxRK7a4MvDOFKEr6gUAYX/yLWKIwl4ywhCRojHIs5SQX8UqvRvtY8JfLFxd2lxuz/7@trxinxeizLiIZKViM3ZmshvSHNlFnK6JEwDsVpxj0gcPnxpiiaH3gSTNKvbUulU7KC/cXFKuVHx7FaxfNbXwWrHelYcaif6XoutEzNEEKrB@wui/GOExcPtE8 "Retina – Try It Online") **Explanation** ``` ' - - - dI d'I ``` Since `Côte d'Ivoire` is a special case, remove the apostrophe at the start and insert it back in at the end. ``` ^(.+)¶\1$ $1 2 ``` If a country is repeated, just append the `2` ``` /^\w+¶\w+$/&%@/(?<=[aeiou])\B/i%`$ X ``` *If the counties are both single words*: Choose a vowel at random (but not at the end) from each country's name and insert an `X` after it. ``` /\W.+¶.+\W/&%@/\W/%`$ X ``` *If the counties are both multiple words*: Choose a space or `-` at random from each country's name and insert an `X` before it. ``` ¶.*?X|X(-?).* $1 -\W - ``` Remove everything after the `X` from the first country and everything before the `X` from the second country. If either country was split at a `-` we need to preserve it, which makes this part a bit longer. ``` /\W.+¶\w+$/&`\w+¶ /^\w+¶.+\W/&`¶\w+ ``` If one country has multiple words and the other is a single word, replace the first/last word of the multi-word country with the single word one. ]
[Question] [ ### Introduction: *Inspired by both [Perfect License Plates](https://codegolf.stackexchange.com/questions/115007/perfect-license-plates) and [How many points does my license plate give?](https://codegolf.stackexchange.com/questions/141646/how-many-points-does-my-license-plate-give)* Just like in the challenges above, me and my little brother had a game of our own with license plates as kids. We tried to create (random/funny) sentences with the (numbers and) letters of the license plates. For example, I can still remember the license plate of our old car from over ten years ago, because of the silly sentence we had created with it: ``` 71-NN-BT 71 Nare Nonnen Bijten Tijgers [Dutch for: 71 Nasty Nuns Biting Tigers] ``` ### Input: * A license plate, which for the sake of this challenge will always start with two digits `[0-9]`, followed by four uppercase letters `[A-Z]`. * Three fixed lists (see below): consisting of Dutch plural nouns; Dutch adjectives; and Dutch verbs. ### Output: Using the list of Dutch plural nouns, adjectives and verbs below as input, create a [random](https://codegolf.meta.stackexchange.com/a/1325/52210) Dutch sentence with the given license plate using the following rules: * Start with the numbers, followed by a space; * And the four letters should either be used in the pattern `adjective noun verb noun` or `noun verb adjective noun` (50/50 [random](https://codegolf.meta.stackexchange.com/a/1325/52210)). This would mean that the sentence mentioned earlier ("*Nare Nonnen Bijten Tijgers*" / "*Nasty Nuns Biting Tigers*") is in the pattern `adjective noun verb noun`, and this alternative sentence "*Nonnen Negeren Blote Theekopjes*" / "*Nuns Ignoring Naked Teacups*" is in the pattern `noun verb adjective noun`). ### Lists of words [Formatted pastebin thanks to *@Arnauld*.](https://pastebin.com/6AEudwZj) **Nouns:** ``` Aanbeelden [Anvils] Aardbeien [Strawberries] Apen [Monkeys] Appels [Apples] Auto's [Cars] Bananen [Bananas] Bessen [Berries] Bloemen [Flowers] Bomen [Trees] Bijen [Bees] Cadeaus [Presents] Cavia's [Guinea pigs] Cheerleaders [Cheerleaders] Circusdieren [Circus animals] Citroenen [Limons] Dinosaurussen [Dinosaurs] Dieren [Animals] Documenten [Documents] Doctoren [Doctors] Dolfijnen [Dolphins] E-mails [Emails] Edelstenen [Gemstones] Eekhoorns [Squirles] Enqûetes [Enquetes] Ezels [Donkeys] Fabrieken [Factories] Fietsen [Bicycles] Flessen [Bottles] Fontijnen [Fountains] Foto's [Photographs] Giraffen [Girafs] Glazen [Glasses] Gummen [Erasers] Guppy's [Guppies] Gymschoenen [Gym shoes] Haaien [Sharks] Homo's [Gay men] Honden [Dogs] Hoofden [Heads] Horloges [Watches] Idioten [Idiots] Idolen [Idols] IJsklontjes [Ice cubes] Illusies [Illusions] Imperia [Empires] Jassen [Jackets] Jokers [Jokers] Jongleurs [Jugglers] Jurken [Dresses] Juwelen [Jewels] Kabels [Cables] Katten [Cats] Kauwgomballen [Gum-balls] Knoppen [Buttons] Konijnen [Rabbits] Leesboeken [Reading books] Leeuwen [Lions] Legercommandanten [Commander-in-chieves] Lesbies [Lesbians] Lummels [Oafs] Maagden [Virgins] Mannen [Men] Mensen [People] Mieren [Ants] Muren [Walls] Neuzen [Noses] Nieuwkomers [Novices] Nonnen [Nuns] Noten [Nuts] Nummerborden [License plates] Oceanen [Oceans] Ogen [Eyes] Olifanten [Elephants] Oren [Ears] Orkanen [Huricanes] PC's [PCs] Pizza's [Pizzas] Politieagenten [Police officers] Postbezorgers [Mail men] Potloden [Pencils] Quads [ATVs] Quaggamosselen [Quagga mussels] Querulanten [Querulants] Quiëtisten [Quietists] Quizzen [Quizzes] Radio's [Radios] Ramen [Windows] Regiseuren [Film directors] Rekenmachines [Calculators] Relschoppers [Hooligans] Schepen [Ships] Slakken [Snails] Slangen [Snakes] Stegosaurussen [Stegosauruses] Stoelen [Chairs] T-rexen [T-rexes] Tafels [Tables] Theekopjes [Teacups] Tijgers [Tigers] Tovenaars [Wizards] Uien [Unions] Uilen [Owls] Universa [Universes] Universiteiten [Universities] USB-sticks [USB-sticks] Vliegtuigen [Planes] Vrachtwagens [Trucks] Vrienden [Friends] Vrouwen [Women] Vulkanen [Vulcanos] Walvissen [Whales] Wespen [Wasps] Wormen [Worms] Worstelaars [Wrestlers] Wortels [Carrots] X-assen [X-axes] X-chromosomen [X-chromosomes] Xenonlampen [Xenon lamps] Xylofonen [Xylophones] Xylofonisten [Xylophonists] Y-assen [Y-axes] Y-chromosomen [Y-chromosomes] Yoghurtdranken [Yugurt drinks] Yogaleraren [Yoga teachers] Yogaleraressen [Female yoga teachers] Zeeën [Seas] Zeehonden [Seals] Zeepbellen [Soap bubbles] Zwanen [Swans] ZZP'ers [Freelancers] ``` **Verbs:** *X has some duplicated verbs, because there aren't enough verbs starting with an X in Dutch..* ``` Accepteren [Accepting] Activeren [Activating] Amputeren [Amputating] Amuseren [Amuzing] Assisteren [Assisting] Bakken [Baking] Bedreigen [Threatening] Bellen [Calling] Bevruchten [Fertilizing/Impregnating] Bijten [Biting] Castreren [Castrating] Categoriseren [Categorizing] Centrifugeren [Centrifuging] Claimen [Claiming] Coachen [Coaching] Dagvaardigen [Prosecuting] Daten [Dating] Degraderen [Downgrading] Dienen [Serving] Dwarsbomen [Thwarting] Electroniseren [Eletronizing] Eren [Show respect for] Erven [Inherit] Eten [Eating] Exploderen [Blow up] Factureren [Invoicing] Fokken [Breeding] Föhnen [Blow-drying] Fotographeren [Photographing] Frituren [Frying] Gooien [Throwing] Graderen [Grading] Grijpen [Grabbing] Groeperen [Making groups of] Groeten [Greeting] Hacken [Hacking] Hallucineren [Hallucinating] Haten [Hating] Helpen [Helping] Huren [Renting] Importeren [Importing] Inspireren [Inspiring] Ironiseren [Ridiculing] Irriteren [Irritating/Annoying] Isoleren [Isolating] Jagen op [Hunting on] Jatten [Stealing] Jennen [Teasing] Jongleren met [Juggling with] Justeren [Adjusting] Klonen [Cloning] Koken [Cooking] Kopen [Buying] Kraken [Cracking] Kussen [Kissing] Labelen [Labeling] Leasen [Leasing] Lonken [Ogling] Loven [Praising] Lusten [Having a taste for] Maken [Creating] Martelen [Torturing] Merken [Labeling] Meten [Measuring] Mollen [Breaking] Negeren [Ignoring] Neuken [Having sex with] Neutraliseren [Neutralizing] Normaliseren [Normalizing] Notificeren [Notifying] Observeren [Observing] Oliën [Oiling] Ontbloten [Denuding] Ontsmetten [Disinfecting] Ordenen [Sorting] Penetreren [Penetrating] Pesten [Bullying] Plagen [Teasing] Porren [Poking] Produceren [Producing] Quadrilleren met [Quadrille-dancing with] Quadrupleren [Quadrupling] Queruleren over [Grumbling about] Quoteren [Giving a rating to] Quotiseren [Distributing] Raadplegen [Consulting] Redden [Saving] Reinigen [Cleaning] Ruilen [Trading] Roken [Smoking] Schieten [Shooting] Schoppen [Kicking] Schudden [Shaking/Shuffling] Slaan [Hitting] Stoppen [Stopping] Tackelen [Assaulting] Telen [Cultivating] Tellen [Counting] Temperen [Tempering] Torpederen [Torpedo-ing] Unificeren [Uniformising] Unlocken [Unlocking] Upgraden [Updrading] Urineren [Urinating] Utiliseren [Making use of] Verbinden [Binding] Verjagen [Scaring away] Verkopen [Selling] Vermoorden [Killing] Verwijderen [Deleting] Wassen [Washing] Wekken [Awakening] Wijzigen [Modifying] Wreken [Avenging] Wurgen [Strangling] Xeroxen [Photocopying] Xoipen [Sending over the internet] Xeroxen [Photocopying] Xoipen [Sending over the internet] X-en [X-ing] Yammeren [Yammering] Yellen [Cheerleading] Yielding [Calculating percentages of] YouTube-streamen [YouTube-streaming] Youtuben [YouTubing] Zegenen [Blessing] Zieken [Nagging] Zien [Seeing] Zoeken [Searching] Zoenen [Making out with] ``` **Adjectives:** ``` Abstracte [Abstract] Achterlijke [Morron] Afrikaanse [African] Amerikaanse [American] Angstaanjagende [Scary] Baby [Baby] Blauwe [Blue] Blote [Naked] Boze [Angry] Broze [Fragile] Charmante [Charming] Chinese [Chinese] Chocolade [Chocolade] Coole [Cool] Corrupte [Corrupt] Dagdromende [Daydreaming] Dansende [Dancing] Dikke [Fat] Dode [Dead] Dunne [Skinny] Echte [Real] Effectieve [Effective] Elektrische [Electronic] Enorme [Enormous] Europese [European] Felle [Bright] Fictieve [Fictive] Fietsende [Cycling] Fluisterende [Whispering] Fluitende [Whistling] Gele [Yellow] Glow-in-the-dark [Glow-in-the-dark] Grijze [Grey] Groene [Green] Grote [Big] Harige [Hairy] Harde [Hard] Homosexuele [Gay] Horde [Troop of] Hyperactieve [Hyperactive] Idiote [Idiotic] IJzere [Iron] IJzige [Frosty] Instelbare [Adjustable] Ivoren [Ivory] Jaloerse [Jealous] Jammerende [Whining] Japanse [Japanese] Jokkende [Fibbing] Jonge [Young] Kale [Bald] Kapotte [Broken] Kleine [Little] Knappe [Handsome] Koude [Cold] Lelijke [Ugly] Lege [Empty] Levende [Living] Lopende [Walking] Luie [Lazy] Maffe [Weird] Massieve [Massive] Middeleeuwse [Medieval] Milde [Mellow] Mythische [Mythical] Naakte [Naked] Nachtelijke [Nocturnal] Nare [Nasty] Nucleaire [Nuclear] Normale [Normal] Ongelovige [Infidel] Oranje [Orange] Oude [Old] Overheerdende [Prevailing] Oxiderende [Oxidizing] Paarse [Purple] Platte [Flat] Pratende [Talking] Piraten [Pirate] Puzzelende [Puzzling] Quiteense [Female resident of the city of Quito] Quad-rijdende [ATV-driving] Quasi [Quasi] Queue-stotende [(Billiard) cue thumping] Quiche-etende [Quiche-eating] Rennende [Running] Rode [Red] Romantische [Romantic] Ronde [Round] Roze [Pink] Saaie [Boring] Schattige [Cute] Scherpe [Sharp] Springende [Jumping] Stoffige [Dusty] Tongzoenende [French kissing] Transformerende [Transforming] Transparente [Transparent] Treiterende [Tormenting] Triomferende [Victorious] Ultieme [Supreme] Unieke [Unique] Uniseks [Unisex] Uiteenlopende [Various] Uitmuntende [Outstanding] Vage [Vague] Verdrietige [Sad] Vierkante [Square] Vliegende [Flying] Vrolijke [Jolly] Warme [Warm] Waterige [Aquatic] Wijze [Wise] Witte [White] Wraakzuchtige [Vindicitive] Xenofobische [Xenophobic] Xhosa-sprekende [Xhosa-speaking] XTC-verslaafde [XTC-addicted] XXX [XXX] Xylofoonspelende [Xylophone-playing] Yahoo-zoekende [Yahoe-searching] Yammerende [Yammering] Yellende [Cheerleading] YouTube-streamende [YouTube-streaming] Youtubende [YouTubing] Zachte [Soft] Zingende [Singing] Zwarte [Black] Zwemmende [Swimming] Zwevende [Floating] ``` ### Challenge rules: * You aren't allowed to use the same random noun twice in one sentence. * You have to take the license plate input either as string or array/list of characters. You can choose to input without delimiter however, so all these are valid input-formats: `NN-CC-CC`; `NN CC CC`; `NN CCCC`; `NNCCCC`; `N N C C C C`; etc. * The list of words can be in any reasonable format. Can be three separate lists; maps with the first letters as keys; one or multiple separate text files to read from; all possible. (You are allowed to take the input with or without the English translations added, as long as you output the Dutch sentence.) * Output can be printing to STDOUT or returning a string. * The lists above and the resulting sentences will only be in Dutch (with optionally the English translations added behind every word / the entire sentence). NOTE: The original idea was to have the lists being part of the code, and *@JonathanAllan* suggested to use just Dutch instead of English, since there are quite a few languages with build-in English libraries. Later in the Sandbox, this switched to having the lists as input, and since I was already halfway through finishing the lists, I kept them Dutch. I've still added the English translations of each word in the list, so you can easily translate what your random output means. * Because all the nouns are plural, we can assume the numbers will be in the range `02-99`. * The numbers `02-09` may be outputted with or without leading zero. * You are allowed to take the input license plate as lowercase instead of uppercase. ### General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ### Some possible test cases (but feel free to use your own as well). ``` 71-NN-BT 80-XW-IK 13-UU-EF 12-AA-AA 99-ZX-YW 73-TH-QQ 04-DJ-IO ``` What are some of your favorite random sentences? [Answer] ## [Perl 5](https://www.perl.org/), 89 bytes **88 bytes code + 1 for `-p`.** Requires the numberplate to be in the format `## A A A A` and the lists need to be formatted like `("A","B",...)`. If this is pushing the limits of acceptable, please let me know. ``` @$_=eval<>for n,v,a;s!\pL!(grep/^$&/,@{(rand>.5?(a,n,v,n):(n,v,a,n))[$-++]})[rand 5]!egi ``` [Try it online!](https://tio.run/##dVdLcyO3Eb7nV2hdW7FUFuPKYctVeTi2tHqsJFJcihIlOk4K5DSH4GCmJxiAWjGVX@R7Ljnu/4rS6G6M5K1K8YCvAQzQzw/NFrx79/z8w9u//xm2xv3p@xX6veZwe2j@2L35a3v1Zr/00H77t7e//fbwh3/ue9MU3//u3V/2zWHa1Bz8YZ83Ezr46e3gm29@/tfBT2nT3ruf30Bpn5@/@/3eiH5He9Pf7H/1o2kWAK6A5qtDEnyxACu41aEF1yUQA36dwJFpTMNrR9B1AhxCLQh1tBsej00BJnaMttbwAcdrIBOBVjyL1i9jV1jw8oUNHkEueG8b7Ez0Ue95nze9x2Wki0IWAuZ5t7Ib@fhkUBvLqp8UZELQM0@gWiP6hheaf3z@DwRgvBM7T83CW6h476mFIDefumzrKTYhX3GK6pOzQddiYGS9Wa149cyZnYCnuluus1FnsRYfnRsjrj7HWo45x6bQGVxl5B2WrOGHwqJY/KFAJ@CiqxwptJENzsXOCqxb8NYQujCq@AVW4vALbEoHUXD0YupFfAQ589IsxBOXJgSdiY8l1gvjdEeDrWTHJTbZF1cA3QLVcSTQeYJK8Eusa8pAowG7op2i5lXyBV82NKYUi4emkROH0Ijmwxz2YZRxBFE8O7J0T0U5x8aMUL8cqZ9G6Xi/QC8nXy9BM/e6lMHZVVbq2utQ6Z7xMcdkbHc7ydsxOhssmDIn3hi7sIAd@lLuH2NwKFd9jKboZCxLUyPFwOkC@OjypR@j/fxLsF0v7cSuiaFY86UTI8kyodLtQO2fJDfXZrm2DbtxQj6kBKOgsB43yzVIfG6cqaqMGjH6JkD5q6q6CajKTQcePgkyK4nLlIq1wlYSbGo3auoUt9AYw/hWsvjWyiG3jd3SJvMCbQArFt7eHA26YJdV@u7OWShDtKLWnSd7wmPyLi9SEWox3HnUZLqLLkdnZtzWqgEz6MTcGfo6A/KpUwVJCmLN/SBXw/1gufZUd50S1j002DhTy0H3Tw5X2LzGOUgP/REPXxzxgOU6@lAQ2VZ5wjjwxn8h6fdzgM@/KFjnyifcUv2JK@ePau18Pv46Of4gMfZyCW3QivhxGZKLBddt7Ofr2GXYdUl3EY5yPhxB4UFdf5TvO4KtjxSFTOFBObwLPrOzSdnjbT78mGrB21Uss@yMFW8cI8VTSNmUW4pEobe9N0rbUPr0BmRmV8p/pJgt1KMnDpb0GjT9dSd52MooJ518alPdydqpWYaY1T1FNff087/XL5xNF7frvMXboGV1hiipfPai2Jm3m1YRUlX5Hgcl8WWlgNh3SQXpVdR1cPL5uV5CzJzSUYWma21W9sNrSz940ivjjuhe4EWqjz1sGSo9X4DSnhA7bdyrITCn93G/dJrNl1jpqAzujU5kOrhK/K88bXQKNaOvUBx/FbUahvr10KQSU9rWJ2WoLhqiptcIcpoQgVcZBG9cb/aIKvhXYrAru1TpekHzOduJu6V6rpuwcEr4hDuyPTN6oUk1prFP4TGo7mNnSuVxr0sei5hvSxTurXvtUJ6Kret3JC7ndfKL5xkM/SLpnu2YGFPQZ6Wyd1EosI0WxSQqe040PsThVv13I9SuMOrHROhG2VsXpykVlchfxgzqnLtT9C3k9CaGfvHvbeNQs/m25eJk6Pukvg32JTZ39LLaTNHgN@pMgpXmFsEa8@NLwqPd5HtnpudurdCZ3ezUGTOvbcQs@lLZ2aM8TPdo2/87NRCiNenVF5jtf7DU49qmZB6O07iAQSI1k5k7BpoS/i01aea5C5wLKcxzczOXTo65eEGnEOEAUzERp3d2U7G08raiCHUskD6vpKbsAgnssQKYlRdP3EZTowXST/ORR7jjwct4vDZUHU0QnN5@QbhEZ/igYySm4NFTnvJGYt/CJz4tREo9lUBbsabvUcRILJLINJmRRupi6XGBLQgRV8Tz1GSw1KR3NoHoKdSsxWnyNLfM/UfaPfPppy7qI9SLQfEZ8IdnDh8HthmENQwK4yvlXjb8jP8RCGDlzo2nXBHAh6QWuoNPUc46R519oqQ3vULSQHPbvCNVBMg5RMTEXwsjs1vMbEt/bDzbd6FJVYjQaiwv@IGRSWJf4G7ZyUD/CPi2S0d1zqAxVKpMvpE/uYKcLqlN5mGrp12lGhIULTDDUkB4pPdc7Bla4gKXWu1ORMcfDJ/COodqZEwVBKS45utGYugoLul/mBXMzAtMoiU43Ipjrqmb2TAQla@J6NL/t0K1u/5ki94v49RwgVCr2D72Jsd5bL2@ieNIba7T6Y8pE0C8mfh14BNL5DXTWSHamAoWw8tHZN8AsjzhJ1Ag6pAqJbthgnmR8@km/fMSOiU9xdDUNHuOzk1LjJdLk@h1tZIdUwrwjmufV6bkmW6VKsG/nmlTuxdEBBteLVqsV7146ygruYiIgqFS0EElHXVyietTgOQ6NtnYO8PqEKHS@wSq/h39R6qUG7ixzps95qDPjFTtjMKg5TPTAptZCdfMU77sUgso66krXuEiu/F@TX8c6K8u8zMffz89HqQWnx6jlUzc3/c9M5I3@jg/GPrbPdhh/@nD64oSohb4BT/nSWZoFuZGOWr@Eidqlb3MPUJd95NaTwf/xTZY0ud50P4P "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṙ2X¤;⁸ṪW¤i’¥Ðḟ"⁹ṫ3¤ŒpŒQẠ$ÐfXK⁹ḣ2¤,K ``` A dyadic link taking a list of lists (of lists of characters): `[[verbs],[adjectives],[nouns]]` on the left and the numberplate (format = `NNCCCC`) on the right and returning a list of characters. **[Try it online!](https://tio.run/##dVdLcyO3Ef4rrq1U@bI8xD7kkNOuXpT4EFeiREmuPYAzIAkOZnqCByXxFP8Dl28@xVXeXLJ3125yk8o/RPtHlEZ3Y8RsVU74gMGju9H94Zu1tvb@@fnp8y/fXT18@OuXHz89ff7X7OGD@fL3Xx7@@fjT06d/vPry4@enzx@/f/jwx8/tHz@/e/r3r396/GlxNUjjn3777uHD68Hz8/MPP7x6UxS6Ddrp5tVr7ASzybhuYzdeR5@h98bn8beqqhjo0mmzFGytgI2LxSpwx6wZ7CkfnKzfU0EvwZm8@Z5ugjOLuMx9q0zNCFSxIrSvlhulXCmn7Svedl8vnSpl3b7RDYNb5fwceI8Dq4vgoOmOO8jNhlve6eCutZB3OlRFiNncQxB3Dx9/XzUyFAAPbld5ijNpfoJHAIbBi2FHzqxbQaDbbhQ0n91XRSXA2liYRmb0xcu@try8L4cc1y24fB3HjW9NNvZ419Njh3Zl7MEKPFEYxG@gJRj4iBPdsGsn0Cxp4je1Dqkfu3sfWOA5A6ikZbMGTslA9J7AUM01p8NQKxmCphLAgR@mnRMYyeqRQp941Ug7GZMQjUDSa6xzmox1rDIITtnO7TG4@n@6wSxMIb3TOY7nbD@15vEjgSbMLfBRiD36Lh1XSlJNsO1SeKLF9olVnJETcPLJQRnzae@iKp2xuwGlodjaboZ2kb9jXByNQOg@ou3ZjzOlSlzGx53pshRgGimKs2g4RmdyP@fFykj8EELbZhhl8blVitqQP05TKvIu05c2gzrn7hRcq3N6XzQ78b1oLEg2X7RUnARdl9QXwbzczaV2c9OUGa8lmAgryS2ENYDrptyadT53piTbZloqdGbWWwnGzGkZi45HrrSDO0Zg2v871KPmWtW1HHOd/b822pamWSYIcRrnupdITTHP4FDAoQRv0iUxMmLFDZPCDeQ@0Iz3r5GL57gLEo4mKkbidNasK@otnKnwhjx10J6dXrP0ATsUsVITK8/vU2NVvKV@yufUwpYax@3eSmF1NIEx3opnBAVYRRvtATIFtQ7zlCYi@5Yu8WnJPbRBoKnI0n3gbkQWSWSa3EjtYoHka/RGMxFXyPMeGT31GqxSAtHhVZMVhynSqTXdokNM4HzYoY3yCHXdIPhI08IjC7c90/TCSvdK5SrhXnI80W0jgIzrK4e5woA26UMNXt9F3qsPMnqPSa86g45Lw8uPT7ZoCgPeB4kY@WuueHQDmW0taEf@nUhSldxp5S5P6IHhQWTf1A6U5aaFQKcNLNY5gUZhqRL5Rloy1DldhnrJzUZ2G6YaYhSNJobFC6EW33P2Z2SQC6zW8dZz19KC0X1Y5asaK1UFBule83FjdnQcC6uVYUzMq4lEl9rChgNz6jBRCbDJp0h0K61TUXP/zpRdXCb4zJMpSK3s@8SpfM8T4@RNnMTtNhEUDb9LmaA5molfey6xRP6mvGGijalgIbwsQv96OvfP6AlkCNKkSslhOIP8kfLpXCmKKdIp2smOItaObue8RcbLpYn0uljwjCle8JZqn75MMTJ@kSrB7Y60GFou0SkKrLDz0UC96LoXFrOSiggpWFcCvK58QhQS26UA9uvYZGcvFZmDhIrvkxbzLw3yrnDDpTU623/pIF/6THHVzvAapHxmUmAzw9c1c5gv2yQB@fuVbmAB8xzGqxV41fMt8TNtfzXd62FGeHyMFjTQu7u766UP9xZXAsaju@lrtQLobaFbfL1bU0zVDL9i6DxIHE2dGyUsdfNyUze3SYMQ0HXdDUpFEVurZq7xHWBZjMwx10ztb1pp0NgU/zcxwLeeiLlRjUhjebCQmzW/Gm9FpaJQFm1cahU9oY1RtMFeqhWsMawR6hpXRF@arJZNcJCFr2kwuNFlGbafJ@1DEeuUUtIJkMftwqx58UGvVoZMP0BGSPqGh3WFIXcNfWj@9vgfLBjCW/bzUM1dfuWErYmcs6@HgCW0ftHN5NIRJgAEQljRSEokiK3aMrivMVmyU0exrkUOKw51Imrapg@iHfoAi4ychSVZyFRN4rcEfsKPT3yFKjaseQKqbeRBz4oa81kRL4vhSMsccJbEkXEUYXqCryzvOUha1xMQ0TjAJ3gJ9VyJcBg0WV4NUJ1LLIZa4z@KBG6YCFgQ6tsCamSeUsmFDXEmmzlMsaDDRgrfZJHNIt1HiQEJ5GsfxU4qc2THBs@pMOfImTHIyrHEaZy2d/Mst04LLZl7usx6eZGNOhUJnRiDGXmP7mRitlvO2wmyBhJUUijC2eDDXG8BBZnjCSH9c2Wh7LldLhW@w16iy/o4H4qc/fgxGN/1tlvRxnjXdOiZyLEzvUQmFP/PUphrrPekd6hvPQtisiPRdpsFsUhJRA07fZ7@VnerCuk8S@Oe03eimxd8L1MsVtSunGBTsxZXp@mnJ71sxMQshEWtI2Un9lMvEJnbsIcX52@RwUxBjE6UHKII3EuX@Os2RZc@YhFmIe1Akuky2nw7M2U3ptPLnt2dpZdHQNIuYuAs/VySN1e9XA1XvWLlkkASwkqs3lhVi2ompm52cb6k626L66@2uIblKrpQ4otX5QFUD065r3qy/kZr/ltDsMqVj7idZ4WO9C26@2bybQr8@/fPf/nzePx2@l8 "Jelly – Try It Online")** ### How? ``` ṙ2X¤;⁸ṪW¤i’¥Ðḟ"⁹ṫ3¤ŒpŒQẠ$ÐfXK⁹ḣ2¤,K - Link: list of lists of lists, words; list, plate ¤ - nilad followed by link(s) as a nilad: 2 - literal two X - random integer in [1,z] -------- gets 1 or 2 ṙ - rotate left by - words [v,a,n] -> [a,n,v] or [n,v,a] ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, words Ṫ - tail - get the nouns W - wrap in a list ; - concatenate - add another noun list to the end - (call this allWordLists) - either [a,n,v,n] or [n,v,a,n]) ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument, plate 3 - literal three ṫ - tail from index - get the four letters - (call this letters) " - zip with the dyadic operation: Ðḟ - filter discard if: ¥ - last two links as a dyad: i - first index of (a letter in a word in a wordList in allWordLists) ’ - decrement (if not found i yields 0, so this result is only 0 when the first index is the head of the list) - ...this gives us a list of lists of words beginning with the appropriate letters ordered either as [a,v,n,n] or [n,v,a,n] Œp - Cartesian product of the filtered lists Ðf - filter keep if: $ - last two links as a monad: ŒQ - distinct sieve (1s at 1st occurrences, 0s elsewhere) Ạ - all truthy - i.e. all distinct? X - random choice from the resulting list - get one four word choice K - join with spaces ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument, plate 2 - literal two ḣ - head to index - get the two digits , - pair K - join with a space ``` [Answer] # JavaScript (ES6), ~~124~~ ~~120~~ 118 bytes Takes input in currying syntax `(s)(a)` where ***s*** is a string in `"NNCCCC"` format and ***a*** is the array of arrays of words `[nouns, verbs, adj]`. ``` s=>a=>s.replace(/\D/g,c=>' '+(g=a=>a.sort(R)[0][0]==c?a.shift(i/=4):g(a))(a[i&3]),i=(R=_=>Math.random()-.5)()<0?18:36) ``` ### Test cases ``` let f = s=>a=>s.replace(/\D/g,c=>' '+(g=a=>a.sort(R)[0][0]==c?a.shift(i/=4):g(a))(a[i&3]),i=(R=_=>Math.random()-.5)()<0?18:36) const NOUNS = ["Aanbeelden","Aardbeien","Apen","Appels","Auto's","Bananen","Bessen","Bloemen","Bomen","Bijen","Cadeaus","Cavia's","Cheerleaders","Circusdieren","Citroenen","Dinosaurussen","Dieren","Documenten","Doctoren","Dolfijnen","E-mails","Edelstenen","Eekhoorns","Enqûetes","Ezels","Fabrieken","Fietsen","Flessen","Fontijnen","Foto's","G-spots","Giraffen","Glazen","Gymschoenen","Gummen","Haaien","Homo's","Honden","Hoofden","Horloges","Idioten","Idolen","IJsklontjes","Illusies","Imperia","Jassen","Jokers","Jongleurs","Jurken","Juwelen","Kabels","Katten","Kauwgomballen","Knoppen","Konijnen","Leesboeken","Leeuwen","Legercommandanten","Lesbies","Lummels","Maagden","Mannen","Mensen","Mieren","Muren","Neuzen","Nieuwkomers","Nonnen","Noten","Nummerborden","Oceanen","Ogen","Olifanten","Oren","Orkanen","PC's","Pizza's","Politieagenten","Postbezorgers","Potloden","Quads","Quaggamosselen","Querulanten","Quiëtisten","Quizzen","Radio's","Ramen","Regiseuren","Rekenmachines","Relschoppers","Schepen","Slakken","Slangen","Stegosaurussen","Stoelen","T-rexen","Tafels","Theekopjes","Tijgers","Tovenaars","Uien","Uilen","Universa","Universiteiten","USB-sticks","Vliegtuigen","Vrachtwagens","Vrienden","Vrouwen","Vulkanen","Walvissen","Wespen","Wormen","Worstelaars","Wortels","X-assen","X-chromosomen","Xenonlampen","Xylofonen","Xylofonisten","Y-assen","Y-chromosomen","Yoghurtdranken","Yogaleraren","Yogaleraressen","Zeeën","Zeehonden","Zeepbellen","Zwanen","ZZP'ers"]; const VERBS = ["Accepteren","Activeren","Amputeren","Amuseren","Assisteren","Bakken","Bedreigen","Bellen","Bevruchten","Bijten","Castreren","Categoriseren","Centrifugeren","Claimen","Coachen","Dagvaardigen","Daten","Degraderen","Dienen","Dwarsbomen","Electroniseren","Eren","Erven","Eten","Exploderen","Factureren","Fokken","Föhnen","Fotographeren","Frituren","Gooien","Graderen","Grijpen","Groeperen","Groeten","Hacken","Hallucineren","Haten","Helpen","Huren","Importeren","Inspireren","Intelligente","Irriteren","Isoleren","Jagen op","Jatten","Jennen","Jongleren met","Justeren","Klonen","Koken","Kopen","Kraken","Kussen","Labelen","Leasen","Lonken","Loven","Lusten","Maken","Martelen","Merken","Meten","Mollen","Negeren","Neuken","Neutraliseren","Normaliseren","Notificeren","Observeren","Oliën","Ontbloten","Ontsmetten","Ordenen","Penetreren","Pesten","Plagen","Porren","Produceren","Quadrilleren met","Quadrupleren","Queruleren over","Quoteren","Quotiseren","Raadplegen","Redden","Reinigen","Ruilen","Roken","Schieten","Schoppen","Schudden","Slaan","Stoppen","Tackelen","Telen","Tellen","Temperen","Torpederen","Unificeren","Unlocken","Upgraden","Urineren","Utiliseren","Verbinden","Verjagen","Verkopen","Vermoorden","Verwijderen","Wassen","Wekken","Wijzigen","Wreken","Wurgen","Xeroxen","Xoipen","Xeroxen","Xoipen","X-en","Yammeren","Yellen","Yielding","YouTube-streamen","Youtuben","Zegenen","Zieken","Zien","Zoeken","Zoenen"]; const ADJECTIVES = ["Abstracte","Achterlijke","Afrikaanse","Amerikaanse","Angstaanjagende","Baby","Blauwe","Blote","Boze","Broze","Charmante","Chinese","Chocolade","Coole","Corrupte","Dagdromende","Dansende","Dikke","Dode","Dunne","Echte","Effectieve","Elektrische","Enorme","Europese","Felle","Fictieve","Fietsende","Fluisterende","Fluitende","Gele","Glow-in-the-dark","Grijze","Groene","Grote","Harige","Harde","Homosexuele","Horde","Hyperactieve","Idiote","IJzere","IJzige","Instelbare","Ivoren","Jaloerse","Jammerende","Japanse","Jokkende","Jonge","Kale","Kapotte","Kleine","Knappe","Koude","Lelijke","Lege","Levende","Lopende","Luie","Maffe","Massieve","Middeleeuwse","Milde","Mythische","Naakte","Nachtelijke","Nare","Nucleaire","Normale","Ongelovige","Oranje","Oude","Overheerdende","Oxiderende","Paarse","Platte","Pratende","Piraten","Puzzelende","Quiteense","Quad-rijdende","Quasi","Queue-stotende","Quiche-etende","Rennende","Rode","Romantische","Ronde","Roze","Saaie","Schattige","Scherpe","Springende","Stoffige","Tongzoenende","Transformerende","Transparente","Treiterende","Triomferende","Ultieme","Unieke","Uniseks","Uiteenlopende","Uitmuntende","Vage","Verdrietige","Vierkante","Vliegende","Vrolijke","Warme","Waterige","Wijze","Witte","Wraakzuchtige","Xenofobische","Xhosa-sprekende","XTC-verslaafde","XXX","Xylofoonspelende","Yahoo-zoekende","Yammerende","Yellende","YouTube-streamende","Youtubende","Zachte","Zingende","Zwarte","Zwemmende","Zwevende"]; console.log(f("71NNBT")([NOUNS, VERBS, ADJECTIVES])) console.log(f("80XWIK")([NOUNS, VERBS, ADJECTIVES])) console.log(f("13UUEF")([NOUNS, VERBS, ADJECTIVES])) console.log(f("12AAAA")([NOUNS, VERBS, ADJECTIVES])) console.log(f("99ZXYW")([NOUNS, VERBS, ADJECTIVES])) console.log(f("73THQQ")([NOUNS, VERBS, ADJECTIVES])) console.log(f("04DJIO")([NOUNS, VERBS, ADJECTIVES])) ``` ### How? The sequences of lists to pick the words from are stored as bitmasks, in reverse order: ``` Noun, Verb, Adjective, Noun --> 0, 1, 2, 0 --> 00 01 10 00 --[reverse]--> 00100100 --> 36 Adjective, Noun, Verb, Noun --> 2, 0, 1, 0 --> 10 00 01 00 --[reverse]--> 00010010 --> 18 ``` That's why ***i*** is randomly initialized to either ***18*** or ***36***. ``` s => a => // given 's' and 'a' s.replace( // replace in 's' /\D/g, c => // each non-digit character 'c' with: ' ' + ( // a space followed by g = a => // a word picked from the list 'a' a.sort(R) // shuffle the list [0][0] == c ? // if the 1st char. of the 1st word is matching 'c': a.shift(i /= 4) // return this word (removing it from the list) // and discard the 2 least significant bits of 'i' : // else: g(a) // try again with a recursive call )(a[i & 3]), // initial call to g() with the next list i = ( // initialize 'i', using: R = _ => Math.random() - 0.5 // R(): returns a random float in [-0,5, 0.5) )() < 0 ? 18 : 36 // to either 18 or 36 (see above) ) // end of replace() ``` [Answer] # Excel, ~~382~~ 353 bytes ``` =D1&E1&" "&IF(RAND()>0.5,INDIRECT("C"&INT((CODE(F1)-64.8+RAND())*5))&" "&INDIRECT("A"&INT((CODE(G1)-64.8+RAND())*5))&" "&INDIRECT("B"&INT((CODE(H1)-64.8+RAND())*5)),INDIRECT("A"&INT((CODE(F1)-64.8+RAND())*5))&" "&INDIRECT("B"&INT((CODE(G1)-64.8+RAND())*5))&" "&INDIRECT("C"&INT((CODE(H1)-64.8+RAND())*5)))&" "&INDIRECT("A"&INT((CODE(I1)-64.8+RAND())*5)) ``` Three lists in `A`, `B` and `C` respectively. Numberplate characters in `D1` -to- `I1`. Formula in any other cell. Golfing: * Last word will always be `NOUN`, * -14 bytes replacing `ADDRESS` with `"A"&INT()` * -14 bytes arithmetic`(CODE(F1)-65)*5+RAND()*5+1` with `(CODE(F1)-64.8+RAND())*5` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~535~~ ~~314~~ ~~304~~ ~~297~~ 382 bytes ``` import java.util.*; L->N->V->A->{int c=((int)(Math.random()*8))%2,i=0,f;String[]a=new String[4],b[]={A,N,V,N,N,V,A,N};for(;i<4;i++){List<String>p=new ArrayList();for(f=0;f<b[i+c*4].length;f++)if(b[i+c*4][f].charAt(0)==L.charAt(i+2)&&(i<3|!b[i+c*4][f].equals(a[1-c])))p.add(b[i+c*4][f]);a[i]=p.get((int)(Math.random()*p.size()));}System.out.print(L.substring(0,2)+" "+L.join(" ",a));} ``` [Try it online!](https://tio.run/##dVhZbxs5En4e/wqtgZ2RYreQyWaBHSg2EDu@JVnxJR/wA9XNblHNJnvYpGwr61807/uyj/lh2SKr2PZksgYSVhWvOj9Wa8GWLNE1V4us/CaqWhvbWYCs76yQ/dyp1Aqt@m8Ga3@ZBNla7WZSpJ1UsqbpjJhQnS9rHfhrLLMg36f9H86tEarY/F5wd/9D0a5Wjau4aUXb8NcpOludb8Nke5xsXyXbH5PtL0LZTrrV7cLY646YnfcNU5muur03/@r1/v5uU2y93cwH8RS2pfhDh7j395uzu/utLx83x5tX8M//D/TzINemOxAf3g/Exkbvy1A0ltTYrsP@j8awJy/u9sLafOvtIP8wuxMb6Zv3933JVWHngxw2i7wbxXf5fT@dM/PRdt/2traGkREb73o//9wVH/7x77@9Xst/d0w2XXb3a5Le93q9us@y7PVpvQG7E/dbdb/g9ocOqPuNWPEu7B08nz81lld97Wy/Bktsd9hv3KwJVnXfbr7rbax31jeG/YUWqgvkJvO7vkF8QzApyBTTpRZZp4JQd6NfO6xHYfd/rVRppxqI2Sun339Z/8jUjHOZcbW@CYzJZlwgXdNQc9l4wln9iyd2mGIqzO3wpkFCal4hpWkUizDusowz1wRqKVg4YHfOuZEcZkxghUldkwlucIewRnO84JNQumHOOLrnU1z0SaeQkMpGxuool7lY4Oa9BLwSVN/LwARLZ@7xcq61UWFC/f71v9zyQK/Qzn02M4KXYe2@4BZv3pfR1n2tbLxiX5NPDpKm1jZQwrA8D7MHkq2QeKqadB6NOnAV@uiQMXT1oa7wmEOtMpLoPFJG6iJoeJQJjRYfZVoicdyUEhRa4AIpXSOQrGpuBAPqmJHix7pEhx9rVUjukHYGTT12DxzPPGEz9MQJs5Yk7qHQ1YxJWqF0jdlxolX0xZDzZqbJccDAeUgV3KS6qqAQGAVsCCtRzaH3RbhsxFiBFo@YwhNHXKHmoxj2kcNxzB16dizgnhJyLhgz1rRzTH4a@@PNTBs8@TTllLmnBQ5S5FGpU0NDSWsmuyEmE7FaYd5OtBRWcFbExJvoxs74SpsC759oKzVe9dmxrMGxKFilIQaSJrhxMl762Ymvf1jRtNwK7TpjEOtw6RnDZDnjhWg42X/m3VyxdC5UcOMZ@BASDIIS9DhP5xzjcy5ZWUZKodHnlhd/qqpzq0m5i8TwR6RYjnG5gGItdY0JdiEWZOqFXnLFWKAvMYsvBR5yqcQSFrEXUlgu0MLL852kAdQq/b4rKXhhnUC1rgzYYx@8d8MkFCEVw5XRlExXTsboTJlcCjJgyhs0d6pNFQnwqSQFgbNozXUSq@E6SecG6q4hwLrmSivJKjzo@knqXKvXdAzSTXvEzXdH3Ohi7ozNAPPLKGCSG2a@42j/Ledf/yBiHisf6BrqD115@0DW3t5OfvGOfx78FdfBw7Mf4Hqa8tpS3XyEF30Z6ap2rbxyTSSbxluIzE7Mmh2eGU4B2ola7fClcRCrCPSWkB4esIjhzOeYEfHwXagYI3JXRF4ygT7b1RB1hG5WLCFeGd32iRG488L4lyLiPz0MDxDZGfl9T/IU3gzVXrcXhyWOeNLeY@2rE@f2WWpdVHdfk7n7X/8zf0F2uLiexyVGWCq@A60x4Q9eFDswYlETpaH2TEtbgvq0JAIwOoWyNcTSPJe4/ZAuOQrdHa06Uk0torJHry09MqBXpBt4FJA89lXU0XUgCcSPOYEjwj8s7FTcBuRv434iKedPdEkj4bxhJIigMfSvBKE5I5GmvB9qdPzQUc2MaPeI@UIkcKeHZ0QuGmlKrzGPaQIwX0bCGiZbs8dQ539irchFStzpDOQx2wHhscZOlZ1JehaAbsD2iPsZJdUExjaFJ5x0n0hWENobmjI6c/E2D/RGyNcODSJXy3aFR/wwD34xQaJtOwm6RzvOGMtgW0EYn2VECEVFceYIY88oPoD0gvx3jg8AkY42A@wzwniavPCpSHD/Mkaiirl7oU3NY3oDjr/491JJTdl8WYfiDKRpk/oSvkZam64AnUQEcm4W5EwgS8otICsdn2hgHsQi3jtlLcJThU7FYkXOmBpqNqbOFIThRuPzda1F/X9FCcIx870BktH@GwGdMABoQGt34WY88aDGIr47CyJE6YKS5jb2ircICrexBbrFfu9HiM2yBQ@I/APY9p8BgE08oDZgrJFiUQYuN6KEYDaBAdVfcaqAjwGmgnMzHgB89hT6cujcODbo4cgdvQqDwXEXvnoq34sE2jcTSOlUSxYO2tUAKmE0kNJhIQB1Zjz0Zsj5Jg1JUQZNP2lkHQCOx11vhh@hLQar@ZIjZpdgNHQtgVP@4faEM5AVQYt9H5TQg7ebqB0Pp@9LR@9Vy1qiD3jYeCD1QyJUYuc8yZgpCaaD4QfhEwOJoNwhM5BWSIRDfE/e8EeHZx1qkj5BfbBWIezIQx@@AlWQwHMAswHqZgylSx2BGb6UTLDvmPIvQ6amWB6HtwiFANQ8tN8SB/jECLedSICEQCgGVR1w2oUtQx7TxffdYVjSaUNfbkg5wQMYQ0DCCE8/2jMSABvS9@4NsjJsGD3ZeQzVmLHSIuHjGq8bo6Fjl8KHnUA6gDQPeFtwqZfomFNojxaBQJVPARP9B2FG2p0@iqz1y8R3cBxRGG2fGBbjPBGGns@Jg75ZkvizzwSO3vRQnBgPKHGONQIx2fna1vZlE9iX8MifhdcSSU2Dr5TohjMdJ0M@nftPOURe0BMN9V24CdE591/5sTQBifMcV1xAgFcBJsLMBXimyX0lmNeS2vePFlku7KtJoau8ZS8lZGUoIkBrXhLR8BJbdO8S2aYA8JVT0dgrFtQB7IWnjJP6V/DRVRI2hE49LjY6Bn3KsGqnEAYqnykV2FRguKYG8mXlu0Wc9212rmfRjddz@BKBb@cA5eH464vdxH8zwLuVB0Hy@PiYtG24Bn@0kb5h8CWfrHS7@eZ1TSGqI/kdmEdhgPPA3DJCqduXSEH3bVD2wKuqFVJFAbC3yO5/d/I/fomtt4OO@PBP/7//tWrtp7ii6EOlyqfu@m@/jeFvvUd8@FEmMqGTBya07t2XV6I3WPvpp@9/NJKq6@XPQYnntedv/wM "Java (OpenJDK 8) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 82 bytes ``` def f(l,d):print(l[:2],*map(lambda i,j:d[i][j].pop(),{'anvn','nvan'}.pop(),l[2:])) ``` [Try it online!](https://tio.run/##XZhLcxs5DoDv/hUqX2RvWVuTZKuy46o9xG9bfsiybNlOpbYoNdSimiJ72KQcayq/aO572WN@WBYkAaq1OcTgCw0CID5S9bubG/3p168CZp3Znjoo9g9rK7XbU18PP347@NtS1HtKLCeF6MiDxWHxVX77uvj299rUe/sHf3aFXunuQVevhO7@oF719ePht/39X9p43XT@1fmz@6V7GP4XegKgCsAVHWzZYgIyNna/eGe6zW7ormm4rkE13R8oHsXVR9A0aehILkgwSxKEFppEZSD0hoXHceHxHMAqEAXYJsw4Rkn4IO4ei5UU6bvH0k59U0iwSc@xdNaAJk0nUdOJmXrU7dKMkzz3xKiZXGhuTJ3hAalNI7z10fSg6DQqOi1wbw5oxan@4@d/wUG07nQdth0EqObGWJ0avaWQ5I6zqOJMgiN/nBnt@PO7Z4Y9eSYmVkJFcxRkG86jgnMl1mns3C/Jj@fvy2Y6N2TY7rmv6/ek7FxaMZuRgouo4EKIFL3uhTGzgkWdJatMGTe1e2GWwaiw9jKuvbxqKoVmL9KmL5c1WIxEEAujkoLLQhpy9aVSvpGQ9n8VNVwZXSrwKaRX/g1o1ZXgNLkyFfCwrcj0flzcF44094V/K81yIhSt72tTUwr2jc5R7YsJp@N1VHEdnJYidQ0l2KlZLoUuBGfHNTQTCTSOsuFIYAutTdbcRFU3QtNXbjwlzo0QJfnxJqfZDWgO4W1ceGt44a1EpRUeh7ThW/AU21t24W2w106MLUjFXVRxZys@OXcl/aXP3Sk5y9u5m4LgwzAIK3cHcr2mszMwjZvA2tiSvj8wThmyf2CUdBJEyQdnd3BMuXAfTbj3qCnNvfdgvcofvfeiaJIgf/7lZLPpL0uxNBhpRTYNo6phcPJSTOdSJ9cPoZQNsFeHgvJ8iJHDPMdAR3t3hwJzjYx6iJoenOGMenBQtk5x6EETyVkP0znUubfiNBtFJaOehe9pcCRmlC0juWA3jbAyVaamQzAyK9BC2JRlj1HD48NRr3FyWsUZj1qucKl0IMkT1BNPzqMkgx8lWfEUdTxZdIh7CwGIWp6siQkYRZxKcXryKqfCk5JQOi9LUjSOisbGkv/G0NCmsc/RxlDEAKm4g9AUaiVzzXmOGp7flZnhqeJAPvemc4u1oeFCThN4NJ/lZ9BGI4ZqUvcS1b38//IXUwoFVtjMik1Pam5U4sjcW1dYoTlqrzGxX18HXfRpSOzXN/bIK8A8lzZs/PyLpRoLQ8zCHzs7GIvJFvGmLsSHiNY0YePcmk6h3rSWtW81fBPlFvzkglx2BCvrMZ7cKizIkilYVdyt1DYDReNsRpvBhCBRCUm@O8bzaeXMl3maCIlv5cYWouAbRnjCLj8R5QpDXrARSEUGIZQ2QJfnuW0E0g5OafxUwRSJq@lzcWRFwvc6VBO2gvhnpeNzfSamQebWz//MNZORPRKwiObU86yGKGgMQewccV@zjvOW5WHAsSgX9TYEQdFJuBCOhSl99IINvEC8@CkWJf44UXBZh@NDky51U8u8i0uLG8yNBqGYB7KTWjTMQEtcxNHOElyC3ybproCBcRXKQcfUbSgqPnh9QxvoW8FSLn59wx4gEBoK07XRjDjPB/w6YJO5J5pt7Blm7o0IRYQh57iz4p5Mb8aeXQq1SRRknJzJaW6Cd3ZrHMrWWLXNP@0mihl5F@BI4gSX56OLsxp0p8tgDMc/o7A7AN7vANdvDtpACToVA2sKny0cGMvhYwSKwkq1FbfEwtiDHrapy@RQBnmzxajA1yqnBfOwKJh4UvMRHXJ4h56RMRSiwNVc74mBCZHMOc@6EHSCyNgel@C26Qcc35GxNeTzNIJlvZF5Sjg0XLOIfZYOTOipYy1h5rWi/aiV4fP26KRqHQ3CH9ZkmSEH9k0usinYXHCIUK5MneWl2VyVCH8ZHWNvSwYhF5ixXKzZwWML1Tb3wBq6CDwbWTPetmFmvPMTYpMIlzWSJT6ZpC4Ts/wI5/RCMee7zMum1kd@dV/5/h6kiolV5s78JniVhC1RLCCSaotdaIGsMNINRCjpsnHYiv4qUtdsa8IErcJCnBqBUFbJRQVtioWTlh5u6/RX4fU7SWLyHv/aMNR@vJmpUSJ98NhgGYzCXGAJ0I56LaY@yfHmB21a4UXaBlglFSeG/gazuU9iEKPgsTy2GRV2QXCqEI54Z0xNfAmhv2CVWt5i3iQnnOpwR2pjKkQnPcA80T999ExuNNBbrsgTXWy0KAVJSeDPGhhKmqVk5Lkybz2pe24OvULYqk2pdzxxYvPBi5DbCUwWk5Yk6goXKvjuwyfbD7Y12h75s@LXbXqgRelqTWoQYljKJ3jf2qJTzVlyJfB9bkmOdC6oP2U8tRBi0EaTFlho0jtM0d/auPTxvvFpVV9hkYOtN5oEfqAlQtX8hWtIyRnFVXY3kendzXOwbyTWPRUebQ21VVJxg/WAHXoTHsdtRAlRJetu/VSBkMl3iVxJDJfyjRG37DHGUgnKrMipd99lsXHOHdIg/KRR5A68wi6S5GkfxKVwFwciEXlrgA95hpXHd5diLYPYT@vzy8wBUOQCYno2FE9agKPooh64TQf4UJtMq0c0cotH4f6RxoZUA4YmnOTs7qHJ42QLwSj8KpVLz0P47YEQNJuRm8JbzNYs4oYlJRHxCN3UzML5zK4cWWmWs3Ybp9ThseCoDbJ1ZkeYlutYXck0AlW4j9ELTeEZW0J6hbml19kVOAkqHkCnKsrFFqjwoV9xUXsSaU/xJcY68OWWEwYRhVcGyHtkRtn09bGkeI@5Yowt5uQ6PB3IXWOMt@XlxKnRcS@8JxHws/TJ5@dnfn/NzCRH6XmOL@JeU0fQ0cz4dDPoP8qpLbRtYSstSOAiWcyN6a3NRt3LVkFgOJJaAt1buDdGkgmu1K9vsMxfwMYqy5w9AXhFKL5GC/segadRXfyxEuetUI7POJQFyhs24jrMns6/O1J3bPgBYO/z/mFntic1vt329g86G637vz5/uL09Gu3887fn8WV/58Onx8fTs50PH7/gv53ff399fhnvfP40uri/3/ntHydXl3f/Aw "Python 3 – Try It Online") Function taking a string `l` for the license plate and a dictionary `d` containing dictionaries with nouns, verbs and adjectives. These must be labeled `'n'`, `'v'` and `'a'`, respectively. In each of these dictionaries, the words are grouped and labeled by their first letter. Each key then contains a `set` of words. By using the `set.pop()` method to generate output, the chosen words are both random and non-duplicate. [Answer] # [C#](https://visualstudio.microsoft.com/), 245 bytes ``` Random r=new Random();var a1=a[r.Next(0,a.Length)];var n1=n[r.Next(0,n.Length)];var n2=n[r.Next(0,n.Length)];var v1=v[r.Next(0,v.Length)];var m=r.Next(0,2)==0;Console.WriteLine($"{r.Next(0,10)}{r.Next(0,10)} {m?a1:n1} {m?n1:v1} {m?v1:a1} {n2}"); ``` Surely not the shortest but it was fun to do so idc xD Same code uncompacted (272 bytes): ``` Random r=new Random(); var a1 = a[r.Next(0, a.Length)]; var n1 = n[r.Next(0, n.Length)]; var n2 = n[r.Next(0, n.Length)]; var v1 = v[r.Next(0, v.Length)]; var m = r.Next(0, 2)==0; Console.WriteLine($"{r.Next(0,10)}{r.Next(0,10)} {m?a1:n1} {m?n1:v1} {m?v1:a1} {n2}"); ``` ]
[Question] [ # Goal: A tree can be represented as a nested list: the list elements represent nodes, and a node is a pair of the node name and node children. Your program takes as [input](http://meta.codegolf.stackexchange.com/q/2447/3480) a nested list of pairs, and should output a pretty tree. # Examples: Here are four example test cases below ``` ["stump",[]] ["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]] [".",[["bin",[]],["usr",[["bin",[]],["local",[["bin",[]],["lib",[]]]]]]]] ["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]] ``` And these are the corresponding outputs 1 ``` stump ``` 2 ``` trunk ├── branch │ ├── leaf │ └── leaf └── branch ``` 3 ``` . ├── bin └── usr ├── bin └── local ├── bin └── lib ``` 4 ``` kingdom ├── mineral ├── animal │ └── dog │ ├── schnauzer │ └── whippet └── vegetable └── cabbage ``` # Notes: * If the characters `│`, `├`, `└`, `─` are not conveniently available in your language, you may substitute with the ASCII characters `|`, `+`, `L`, `-` respectively. * You may assume there is one unique root node. You may assume the input will be "nice", it doesn't matter what your program does if the input is not well-formed. * To avoid unfair advantages to any particular language, some flexibility in the input format is allowed *within reason*. For example, specifying the nesting with parens `()` or braces `{}` is OK. If it's more convenient for the node labels to be integers instead of strings, that's OK. Extra whitespace in the input is OK, as long as it's not being used to define structure. If you take the input as a string literal and parse it directly, that's OK. * No messing with the underlying structure of the tree! E.g., you may not change how a leaf node is represented. * **Tip:** the representation used in the examples is valid json, so you can paste it into a [json linter](http://jsonlint.com/) to better see the nesting. # Scoring: This is code golf, shortest code wins. [Answer] ## [Perl 5](https://www.perl.org/), 146 bytes ``` sub f{my$r=@_-1;my$p=$r?pop:[];while(my$n=shift){my($t,$c)=@$n;say$r?((map$_?'| ':$"x4,@$p),@_?'+':L,'-- '):(),$t;f(@$c,[@$p,$r?!!@_:()])if@$c}} ``` [Try it online!](https://tio.run/##ZZDNjoMgFEb38xTUkAgZbKbJdCMx8gDzBsY0aFFJFQlg57fP7lDGmma64t7D@b7F1cL0@3myApz3290Lne1UgeZ7@IQmY4dkR/2kM2hyPeq0KOl7J3uBPFSZ7WTjsFcRdATWOGNQUct9Mkdo4Boe8vgHABCnMPp4JQxqTJhnz3H6RuIkATFOESbQ0QYxWJPCG8SHNxt28B8llo3Hl8vcoCKybhp0RIqyxPTpCpyZ1MmDIqoMV3UXxl7wJkjkbg7bKl33pWL7F5fqFpms@Y/6seb9A5TV0nTXdpKqPY5DcAephAm54HMlh6XlOLbhtXWn@PQlzM3xh9VauLXXo7NoheNVL0Ki5lXFW7EKmM6/ "Perl 5 – Try It Online") [Answer] # Haskell, 159 bytes With preprocessing of the input to fit the defined tree datatype (included in score) since trees can't be represented as a nested list. ``` data T=T[Char][T] r=reverse;z=zipWith;a%b=a:cycle[b] p(T s b)|k<-r$p<$>b=s:(concat$r$z(z(++))(("└── "%" ")%("├── "%"│ "))k) mapM putStrLn.p ``` Usage: ``` > mapM putStrLn.p $ T"kingdom"[T"mineral"[],T"animal"[T"dog"[T"schnauzer"[],T"whippet"[]]],T"vegetable"[T"cabbage"[]]] kingdom ├── mineral ├── animal │ └── dog │ ├── schnauzer │ └── whippet └── vegetable └── cabbage ``` [Answer] # JavaScript (ES6), 123 ~~125~~ bytes Using 5 unicode graphic character, 3 bytes each. The char count is 115. ``` x=>(o=x[0],r=(l,p)=>l[0]&&l.map((x,i)=>r(x[1],p+'│ '[q=+!l[i+1]]+' ',o+=` ${p+'├└'[q]}── `+x[0])),r(x[1],''),o) ``` *Less golfed* ``` l=>( o = l[0], r = (l,p)=> // recursive tree printer l[0] && l.map((x,i)=> ( q = +!l[i+1], o += `\n${p+'├└'[q]}── ` + x[0], r(x[1], p+'│ '[q]+' ') ) ), r(l[1],''), o ) ``` ``` F= x=>(o=x[0],r=(l,p)=>l[0]&&l.map((x,i)=>r(x[1],p+'│ '[q=+!l[i+1]]+' ',o+=` ${p+'├└'[q]}── `+x[0])),r(x[1],''),o) out=x=>O.textContent+=x+'\n\n' ;[["stump",[]] ,["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]] ,[".",[["bin",[]],["usr",[["bin",[]],["local",[["bin",[]],["lib",[]]]]]]]] ,["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]] ].forEach(t=>out(JSON.stringify(t)+'\n'+F(t))) ``` ``` <pre id=O></pre> ``` [Answer] # Python 3, 110 109 bytes Down to 109 thanks to [att](https://codegolf.stackexchange.com/users/81203/att) ``` def f(l,p='',a=0,o=0): x,c=l;print(p+(('+L'[o]+'-- ')*a)+x) for i in c:f(i,p+('| '[o]+' ')*a,1,c[-1]is i) ``` Call as: ``` f(["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]]) ``` To get output: ``` kingdom +-- mineral +-- animal | L-- dog | +-- schnauzer | L-- whippet L-- vegetable L-- cabbage ``` This is my first `code-golf`, so I welcome any feedback or suggestions. I ended up using flags for the recursive function to know when an element was the root node or when it was the last leaf of a node, allowing it to differentiate the prefix that needed to be applied. I wanted to have the last argument for the recursive call originally be `i==c[-1]`, but ran into an issue with the call ``` f(["trunk",[["branch",[["leaf",[]],["leaf",[]]]],["branch",[]]]]) ``` where the two branches are equivalent but not identical, so a `is` call was necessary instead of `==`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 96 bytes ``` ` 0:4_'{r:o@x,y[1]," ";(,x,(*y),"-- ",*z),/$[z@1;("+|"r/:-1_z@1),"L "r/:-1#z@1;""]}["";" ";]@ ``` [Try it online!](https://ngn.codeberg.page/k#eJx1jUFugzAURPc+hfVbqSQ1TZG6gkU5QG/gWIlNDLgBgwy0CWnuXiyTWpHo7s+fmTd5vMev8dvu6WLiJj2RM40YAYwxJAE5kWB9XhEIQwxkPa7I5pGOaZQE8PwDZhOH0W6SU+ADO/lgXQB2pQAJWAhLEbpcc7z/fMdAt9D1Q91ugVDGANlpgDu/N4M+Wn+6heE6K2dRSZ67HrlTTvuo/SySX25UpT1n6MzSu2oyXi0aStxG/h06Kl0cmnqu10pL42AOwbWq/+CHppivLis1H0ZpfPK7VG0rez9on1+ykD0XlZx7GReCF9KHAKFfffGKgQ==) Quite a shame that this took so long, but I'm glad that I stuck with the problem. Recursive function which prints each line of the tree separately. ngn/k's json parser is used to get the array. -6 bytes from coltim. -1 from ngn. [Answer] ## Python 2, ~~118~~ 119 bytes ``` def f(x,q='',p='',r=''): m,w=x;l=len(w);print q+r+m for i in range(l):a=l-i>1;f(w[i],q+p,' |'[a]+' ','L+'[a]+'-- ') ``` Call as: ``` f(["kingdom",[["mineral",[]],["animal",[["dog",[["schnauzer",[]],["whippet",[]]]]]],["vegetable",[["cabbage",[]]]]]]) ``` Outputs: ``` kingdom +-- mineral +-- animal | L-- dog | +-- schnauzer | L-- whippet L-- vegetable L-- cabbage ``` ]
[Question] [ Seems like we do not have this one yet, so here we go: # The Challenge Write a program or function that takes a date as input and outputs the day number of the year. You may not use any builtins for that! # Rules * As usual you may write a full program or a function. * The format of the input is up to you, but it has to contain a year, a month and a day. Make clear which one your solution uses! * No date-related builtins allowed! You gotta do the work by yourself. Builtins which are not related to date operations are fine. * Base for the calcultion is the gregorian calendar. * You have to take account of leap-years. * You only need to handle years in the range [1, 9999] * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Lowest byte count wins! # Testcases Input format here is YYYY/MM/DD ``` 2016/07/05 -> 187 2000/03/28 -> 88 0666/06/06 -> 157 6789/10/11 -> 284 0004/04/04 -> 95 1337/07/13 -> 194 ``` Happy Coding! [Answer] ## JavaScript ES6, ~~81~~ 69 bytes ``` (y,m,d)=>d+parseInt("03479cehkmpr"[--m],36)+m*28-(y%(y%25?4:16)&&m>1) ``` Assuming months are 1-based, otherwise I could save 2 bytes. Edit: Saved 12 bytes using @user81655's tip. [Answer] # C, ~~96~~ ~~102~~ ~~89~~ 61 bytes ``` g(y,m,d){printf("%d",m/2*31+--m/2*30-(y%(y%25?4:16)?2:1)+d);} ``` [Answer] ## Pyth, 31 bytes ``` +s<X1+L28jC"3Ȕ"4!%|F_jQ*TT4tEE ``` Thanks to @Dennis and @Jakube for [the leap year portion](https://codegolf.stackexchange.com/a/50818/39328). Input is YYYY, MM, DD on separate lines. ``` + add [day] to s < sum of first [month]-1 values in the list X add 1 to 1 the second element (January)... +L \ 28 | j } lengths of all the months C "3Ȕ" | 4 / ! % ... if the year is a leap year; that is, 4 divides... |F _ j fold logical OR over reversed Q the year *TT converted to base 100 4 t E [month]-1 E [day] ``` [Test suite](http://pyth.herokuapp.com/?code=%2Bs%3CX1%2BL28jC%223%C2%BB%C3%AE%224%21%25%7CF_jQ%2aTT4tEE&input=2016%0A7%0A5&test_suite=1&test_suite_input=2016%0A7%0A5%0A2000%0A3%0A28%0A666%0A6%0A6%0A6789%0A10%0A11%0A4%0A4%0A4%0A1337%0A7%0A13&debug=0&input_size=3). [Answer] # Python 3, ~~152~~ ~~148~~ 150 bytes ``` m,d,y=map(int,input().split());n=[0,31,(59,60)[(y%4==0 and y%100!=0)or y%400==0]] for i in range(m):n+=[n[-1]+(31,30)[i in[1,3,6,8]]] print(n[-4]+d) ``` Takes dates in the format "M D YYYY". [Answer] # Python 2, 100 82 bytes A Python port of [@Neil's](https://codegolf.stackexchange.com/a/70418/38252) answer: ``` lambda d,m,y:d+int("03479cehkmpr"[m-1],36)+(m-1)*28-(y%(4if y%25 else 16)and m>2) ``` As with the previous answer, adding 17 bytes (99 bytes total) will yield a full program: ``` print(lambda d,m,y:d+int("03479cehkmpr"[m-1],36)+(m-1)*28-(y%(4if y%25 else 16)and m>2))(*input()) ``` ## Previous answer: As an anonymous lambda: ``` lambda d,m,y:d+sum(31-(n in(3,5,8,10))for n in range(m-1))-(3if y%4 or(y%400!=0and y%100==0)else 2) ``` Can be converted to a named lambda for a 2 byte penalty. Alternatively, a full program (taking input in the format `D,M,Y`) can be achieved for 117 bytes: ``` print(lambda d,m,y:d+sum(31-(n in(3,5,8,10))for n in range(m-1))-(3if y%4 or(y%400!=0and y%100==0)else 2))(*input()) ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 28 bytes ``` +-=@`\:0.``@1370+30$+?-@2- 2%+.::4 100 400^0%_$~0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWNw21dW0dEmKsDPQSEhwMjc0NtI0NVLTtdR2MdBWMVLX1rKxMFAwNDBRMDAziDFTjVeoMIBqh-tdGGxkYGOgoGOsoGFnEQgUB) Takes the year, month and day as command-line arguments. Edit: Care to explain why this was downvoted? [Answer] # Python 3, 125 bytes ``` print((lambda d,m,y:sum([3,not(y%400 and not y%100 or y%4),3,2,3,2,3,3,2,3,2,3][:m-1])+m*28-28+d)(*map(int,input().split()))) ``` An another approach to this problem. The code takes advantages of the Python's boolean algebra execution priorities and since `not` is the last operation, conversion to boolean is automatic. When summation is done, the boolean is treated as 1 or 0. Input format is "YY MM DDDD" string. Input system inspired by [@SteveEckert's](https://codegolf.stackexchange.com/a/70412/72511) similar one. ### Another form as a function, 91 bytes ``` def f(d,m,y):return sum([3,not(y%400 and not y%100 or y%4),3,2,3,2,3,3,2,3,2,3][:m])+m*28+d ``` In this case input is three integers, the month being between 0-11. This would work in Python 2 also. [Answer] # Excel, 106 bytes ``` =AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100))))+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1 ``` Takes input in three cells `A1` = Year, `B1` = Month, `C1` = Day. --- ``` AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))) ``` `1` if LeapYear, else `0` ``` 30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1 ``` Multiple of `30`, CHOOSE for additional days, plus days in month --- **Evolution:** ``` =IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+CHOOSE(B1,0,31,59,90,120,151,181,212,243,273,304,334,365)+C1 =IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+CHOOSE(B1-1,31,59,90,120,151,181,212,243,273,304,334,365)+C1 =IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*(B1-1)+CHOOSE(B1,0,1,-1,0,0,1,1,2,3,3,4,4,5)+C1 =IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*B1-30+CHOOSE(B1,0,1,-1,0,0,1,1,2,3,3,4,4,5)+C1 =IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1 =AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100))))+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1 ``` [Answer] # [Scala](http://www.scala-lang.org/), 126 bytes Port of [@Neil's Javascript answer](https://codegolf.stackexchange.com/a/70418/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##dY9NT4QwEIbv/Ipxk920bne3pXwUEjbx6MF4MB6M8VChIAosFmJCzP52LF/eOMy08@bJk5kmloXsL@@fKm7hQeYV/FoAP7KARHaP6YuSOkT3VUtgaTg6mw5RjzpSksSMyd4EKlP6WEvdKDOgDeWOH8Tq46us9ebYXp7UNyoPDA/fVudVRriH92N0a4sDylNAqNuOb7e13SiimHmgikaBg2/MtNuVZ4bZFFHcJyqF0iyMpM6aEO60lt3r5H7DITxXuVlyvAagNmlbVOj/JmRT5hGgvikXY4DTCZjwV2FKDcgJ2GKGhVhhqecN4rEWsbsm9nwREGBGztgM28JZM1PqGOtYMxy4Kyzj3J/OY3zZIhjEV@tq9X8) ``` (y,m,d)=>d+Integer.parseInt("03479cehkmpr".toSeq(m-1).toString,36)+(m-1)*28-(if ((y%(if (y%25==0)16 else 4)!=0)&&m>1)1 else 0) ``` Ungolfed version. [Try it online!](https://tio.run/##dVDLTsMwELz3K4ZKVDaE1s47lYrEEQnUA@KAEAeTOG0gSSvHQopQvz04TqpyyWHt9e7MeGebVJSi6w6fXzLVeBZFjd8ZkMkcmWi3@ZsUirRrPNbaQTXemb2pPbGxBOBHlKgOtd5v87yRujGNOfP8KEnl/rs6qvlSH56KRltwhtueLHdSLY9CNdI8yH82qXAHTg3nRaui3jnwQmpIYx03cGOTkSIHIS2uh6xP3ACbDRgFDyHLRsKnuLKFxQIV7ns2HzqMmmFOs9FvZcwToXbNGg9KifZ9@PnD@Hyti4vRo6nqsiaX/biMhw5YZCKgFFitwONoEsyYAXqOcTCC43gCy8KwF7ZxFg6mhMMoThxwI875CHZjf0qZMd@o2hjBSTCB5Z4XDfa4d54i8e3qTrOu@wM) ``` object Main { def dayOfYear(y: Int, m: Int, d: Int): Int = { val monthOffsets = "03479cehkmpr".toList d + Integer.parseInt(monthOffsets(m - 1).toString, 36) + (m - 1) * 28 - (if ((y % (if (y % 25 == 0) 16 else 4) != 0) && m > 1) 1 else 0) } def main(args: Array[String]): Unit = { println(dayOfYear(2016, 07, 05)) // 187 println(dayOfYear(2000, 03, 28)) // 88 println(dayOfYear(0666, 06, 06)) // 157 println(dayOfYear(6789, 10, 11)) // 284 println(dayOfYear(0004, 04, 04)) // 95 println(dayOfYear(1337, 07, 13)) // 194 } } ``` ]
[Question] [ Quining has a long history - if you haven't heard of it, click the tag and read up a little on it. ## Your Task Output an infinite series of `1`s (with no other spacing [newlines, spaces, etc.]) UNTIL SIGINT (typically CTRL-C) is called. When it is called, output the program source. ## Rules * It must be a valid quine: + No reading source from the disk. + See all other [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) relating to quines. * You may use any language. * As this is a code golf, the shortest answer wins! [Answer] ## Python 3, 76 bytes ``` s="while 1:\n try:print(end='1')\n except:-print('s=%r;exec(s)'%s)";exec(s) ``` Note that the byte count includes a trailing newline. This also uses `-print` to error out after quining. [Answer] # Pyth, 25 bytes ``` .xf!p1)jN*2]".xf!p1)jN*2] ``` A modification of the standard Pyth quine to add a try-except function. [Answer] # [AutoIt](http://autoitscript.com/forum), ~~488~~ ~~429~~ 362 bytes My brain hurts, this is too meta. ``` $1=BinaryToString $2=Chr(34) $s="FileWrite('a','#include<Misc.au3>'&@LF&'Do'&@LF&'ToolTip(1)'&@LF&'Until _IsPressed(Chr(49)&Chr(66))')+RunWait(@AutoItExe&' a')" Execute($s) $x="$1=BinaryToString\n$2=Chr(34)\n%sExecute($s)\n$x=%s\nClipPut(StringFormat($x,$1(0x223D7324)&$s&$1(0x0A0D22),$2&$x&$2))" ClipPut(StringFormat($x,$1(0x223D7324)&$s&$1(0x0A0D22),$2&$x&$2)) ``` This is quite interesting in the way that it compiles a child-process which in return keeps outputting 1 to the ToolTip API until ESC is pressed. If ESC is pressed, the child process kills itself and the parent (this quine) resumes execution and dumps it's source *to the clipboard*. You have to run this from the editor. BTW: This creates an auxiliary file 'a' on your disk. [Answer] # C, ~~239~~ ~~221~~ ~~206~~ 172 Bytes Definitely could be a lot shorter, but I had to post something on PPCG *eventually*. ``` *s="*s=%c%s%c,r;h(s){r=1;}main(){signal(2,h);while(!r)printf(%c1%c);printf(s,34,s,34,34,34);}",r;h(s){r=1;}main(){signal(2,h);while(!r)printf("1");printf(s,34,s,34,34,34);} ``` Compiles with gcc 5.2.1 (with various warnings). [Answer] ## Haskell, 206 bytes ``` import Control.Exception;main=catch(putStr o)e;o='1':o;e::SomeException->IO();e _=putStr(s++show s);s="import Control.Exception;main=catch(putStr o)e;o='1':o;e::SomeException->IO();e _=putStr(s++show s);s=" ``` [Answer] # C#, 339 Bytes ``` using d=System.Console;class c{static bool k=1>0;static void Main(){d.CancelKeyPress+=delegate{k=1<0;var s="using d=System.Console;class c{{static bool k=1>0;static void Main(){{d.CancelKeyPress+=delegate{{k=1<0;var s={0}{1}{0};d.WriteLine(s,(char)34,s);}};while(k){{d.Write(1);}}}}}}";d.WriteLine(s,(char)34,s);};while(k){d.Write(1);}}} ``` [Answer] # Perl 5.10+, 64 bytes ``` perl -E '$_=q{$SIG{INT}=sub{say"\$_=q{$_};eval";die};{print 1;redo}};eval' ``` Requires Perl 5.10+ for `say`, which can be enabled with either `-M5.010` or `-E`. ## How it works This is yet another variation of the following quine, which I seem to use on every quine challenge: ``` $_=q{say"\$_=q{$_};eval"};eval ``` Broken down: ``` perl -E ' $_=q{ # store contents of quine in $_ $SIG{INT}=sub{ # install handler for SIGINT say"\$_=q{$_};eval"; # print quine die # break out of eval }; { print 1; # print "1" redo # restart block } }; eval # eval $_, executing its contents as code ' ``` ]
[Question] [ *This is a new kind of challenge inspired by the [Recover the mutated source code](https://codegolf.stackexchange.com/questions/42910/recover-the-mutated-source-code) problem.* You should write two programs or functions both in the same language. The first one should solve Task #1 and the second one should solve Task #2. **Your score will be the sum of the longer program and the [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) between the two programs source code.** Lower score is better so you should try to make the two solutions similar while keeping the lengths of the programs short. ## Task #1 You are given a positive integer `N` and you should output the [Collatz sequence](http://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem) of `N` separated by spaces or newline. Trailing separator is allowed. The first element of the Collatz sequence is `N`. The rest of the elements are generated based on their successor \$a\_{i-1}\$: $$ a\_i = \begin{cases} \frac{a\_{i-1}}{2} & \text{ if } a\_{i-1} \text{ is even} \\ 3a\_{i-1} + 1 & \text{ if } a\_{i-1} \text{ is odd} \end{cases} $$ As soon as the sequence reaches `1` no new elements are generated. Input => Output examples: ``` 6 => 6 3 10 5 16 8 4 2 1 8 => 8 4 2 1 1 => 1 ``` ## Task #2 A pair of twin primes is a pair of positive integer whose difference is 2 and they are both primes. You are given a positive integer `N` and you should output the smallest pair of twin primes where both primes are bigger than `N` The first number should be the smaller one and the two primes should be separated by spaces or newline. Trailing separator is allowed. Input => Output examples: ``` 6 => 11 13 42 => 59 61 1 => 3 5 ``` ## Snippet for calculating the score (Modification of the one in the [Recover the mutated source code](https://codegolf.stackexchange.com/questions/42910/recover-the-mutated-source-code) problem.) ``` var f=document.getElementById("f"),g=document.getElementById("s");function h(){var a=f.value,e=g.value,m=Math.max(a.length,e.length);if(10000<a.length)a="<span style='color:red'>First program is too long!</span>";else if(10000<e.length)a="<span style='color:red'>Second program is too long!</span>";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = "+a+" Longer length = "+m+" Score = <strong>"+(a+m)+"</strong>"}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h; ``` ``` First program<textarea id=f rows=2 cols=80 style="width:100%"></textarea>Second program<textarea id=s rows=2 cols=80 style="width:100%"></textarea><p id=d></p> ``` ## Edit In the answers' header let's use the format `[Language], [longer length] + [distance] = [final score]`. E.g. `Python 2, 60 + 32 = 92` [Answer] # CJam, 24 + 17 = 41 ~~42~~ **Collatz program**: ``` ri2*{:N2%N3*)N2/?__p(}g; ``` **Twin primes program**: ``` ri_2+]{:)_{mp}/&_+((}gS* ``` Both take input from STDIN and print space/newline separated numbers to STDOUT [Try them online here](http://cjam.aditsu.net/) [Answer] # Pyth, 18 + 13 = 31 Collatz Sequence: ``` QWtQ=Q@,/Q2h*Q3QQ ``` Twin Primes: ``` =Qf!ttP*T+T2hQQ+Q2 ``` [Try it here.](http://pyth.herokuapp.com/) Some ideas thanks to FryAmTheEggman. [Answer] # CJam, 25 + 16 = 41 **Collatz program:** ``` l~2*{_2%{3*)}{2/}?_p_(}g; ``` **Twin primes program:** ``` l~_2+]{:)_{mp}/&!_&}gS* ``` [Test it here.](http://cjam.aditsu.net/) I just golfed both of them for now. I'll see if I can reduce the score somehow. [Answer] ## Pyth, 20 + 14 = ~~40~~ 34 ### Collatz: ``` QWtQ=Q@,/Q2h*3QQQ ``` ### Prime Pairs: ``` ~Q1WttP*Q+Q2~Q1;Q+Q2 ``` Both are programs that take input from STDIN and output the numbers on newlines. Just golfed both answers while using the same looping primitive for now. This could probably be improved quite a bit. Edit: Added better condition checking stolen from @isaacg. Seems like using filter is still shorter than using a while loop for the prime pairs. [Try it online here.](https://pyth.herokuapp.com/) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 + ~~13~~ ~~10~~ 9 = ~~27~~ ~~24~~ 23 -4 score thanks to ASCII-only ## Collatz sequence (14 bytes): ``` [DÉi3*>ë2÷}Ð,# ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2uVwZ6axlt3h1UaHt9cenqCj/P@/KQA "05AB1E – Try It Online") ## Twin primes (14 bytes): ``` [DÅND>>Dp#}s,, ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2uVwq5@LnZ1LgXJtsY7O//@mpkYA "05AB1E – Try It Online") --- ### Golfed Twin primes (11 bytes): ``` [ÅNDÌp#]DÌ» ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@nCrn8vhngLlWCB5aPf//8YA "05AB1E – Try It Online") [Answer] # Java 8, 118 + 84 = 202 Collatz: ``` n->{for(System.out.println(n);n>1;System.out.println(n=n%2<1?n/2:3*n+1));} ``` Twin primes: ``` n->{t:for(int p,z;;n++){for(z=n;z<n+3;z=z+2)for(p=2;p<z;p++)if(z%p<1)continue t;System.out.print(n+" "+(n+2));break;}} ``` [Answer] # Mathematica, 53 + 29 = 82 Collatz Sequence: ``` Print/@(NestWhileList[If[OddQ@#,3#+1,#/2]&,#,#>1&]);& ``` Twin primes program: ``` Print/@(NestWhile[NextPrime,#,!PrimeQ[#+2]&]+{0,2});& ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 116 + 86 = 202 **Collatz program** (46): ``` 0i:0(?v$a*$'0'-+! ?v6,>:>~:nao:1=?;3*:2% >1+^ ``` **Twin primes program** (116): ``` 0i:0(?v$a*$'0'-+! v&2+1~<:-2 <v!?%&+1:&:v?=&:&: >&~0$2&2+v>&~143. :&:1+&%?!v>:&:&=?v 0v?*r$0~&< .561~&<.1 :<;noan-2 ``` Ouch. Both programs start with the same `atoi` function, but after that twin primes goes downhill. The same piece of code is repeated twice for primality check — it might be slightly shorter to somehow reuse the piece, but the setup for it wouldn't save many bytes. Could do a lot better by throwing the back half of twin primes into the unused spots of the Collatz program, but I'm not sure if that's allowed. [Answer] ## C++ Distance = 114 Longer length = 155 Score = 269 Task 1 ``` void c(int N){while(N>1){cout<<N<<' ';N=(N%2==0)?N/2:N*3+1;}cout<<N;} ``` Task 2 ``` int p(int x){int z=0;for(int i=2;i<x;i++){if(x%i==0){z=1;break;}}return z;} void c(int N){N=(N%2==0)?N+1:N+2;int M=N+2;while(p(N)+p(M)>0){N=M;M+=2;}cout<<N<<' '<<M;} ``` Task 2 improved ``` int p(int N){int z=0;for(int i=2;i<N;i++){if(N%i==0){z=1;break;}}return z;} void c(int N){N=(N%2==0)?N+1:N+2;while(p(N)+p(N+2)>0){N+=2;}cout<<N<<' '<<N+2;} ``` ]
[Question] [ This challenge will behave more or less like a traditional [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The only difference is that instead of scoring answers by their number of characters or bytes, users will assign *weights* to different characters in the comments and the program with the lowest cumulative weight will win. # Challenge Your task is to write a program that takes a string and prints a diamond shape where the first character starts in the center and subsequent characters occupy the empty spaces orthogonal to the set of characters that were placed last. Spaces () will be used for padding. For example inputting `CAT` would produce ``` T TAT TACAT TAT T ``` and `()` would produce ``` ) )() ) ``` and `desserts` would produce ``` s sts strts strerts streserts stressserts stressesserts stressedesserts stressed desserts stressedesserts stressesserts stressserts streserts strerts strts sts s ``` and `9` would produce `9`. # Details * The code may only contain [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) and newlines. (See why below.) * Input/output should be via stdin/stdout, or, if they aren't possible, use similar alternatives. * You may assume the input string only contains printable ASCII (including space). * Columns of leading spaces not containing any portion of the diamond pattern are **not** allowed in the output. Any amount and combination of trailing spaces spaces is allowed. * There may optionally be a trailing newline in the output. * You may edit your answer as much as you want. # Scoring All code must be written using only newlines and the 95 printable ASCII characters: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` (Sadly tabs are not allowed because Stack Exchange renders them as spaces in code blocks.) Each of these 96 characters has a *weight* value associated with it. By default, all the weights are 97. The score of a program is the sum of the weight values for each of its characters. For example, if the program were `print(4)` and the weight for `4` was 70, but unchanged for everything else, the score would be `749 = 97+97+97+97+97+97+70+97`. Once the activity in this question settles down to almost nothing, the lowest scoring submission wins. In the presumably unlikely case of tie the wins goes to the highest voted answer. # Changing Weights Every user, whether they've answered or not, can change the weight of one of the 96 characters to a unique value from 1 to 96. To do this, add a comment to this question of the form `#### W -> C ####`, where W is an integer from 1 to 96 and C is the character (as itself, no quotes, no backticks). Use `\n` in place of C for newlines and `\s` for space since Stack Exchange compresses 3 spaces in a row. The `print(4)` example above would have had the comment `#### 70 -> 4 ####`. **Each user may only make ONE comment like this, and it will only be valid if both the character and the weight value have not been used in a previously made comment.** Thus eventually, there may be 96 `#### W -> C ####` comments, all from different users, all with different weights assigned to different characters. Users may delete their own comment if they want to, resetting their characters' weight back to 97 until they or someone else comments again. They may also edit them. Comments not following the rules about distinct users/weights/characters should be deleted or flagged as "not constructive". General comments about rules and other things are fine but should be kept at a minimum. This stack snippet is the official leaderboard for this question. It automatically computes the scores for all submissions by gathering the weights from comments each time it is run. It does not handle ties. You can also use it to check the score a program would have. You'll probably need to `right-click -> Open link in new tab` for the links. ``` function compute(){var e=computeScore($("#code").val());$("#score").val(e==-1?"Invalid characters":e)}function computeScore(e){var t=0;for(var n=0;n<e.length;n++){if(weights.hasOwnProperty(e[n])){t+=weights[e[n]]}else{return-1}}return t}function htmlDecode(e){var t=document.createElement("div");t.innerHTML=e;return t.childNodes.length===0?"":t.childNodes[0].nodeValue}function addLeaderboard(){validAnswers.sort(function(e,t){return e.score>t.score});var e=1;var t="";for(var n=0;n<validAnswers.length;n++){var r=validAnswers[n];t+="<tr><td>"+e+"</td><td><a href='"+r.link+"'>"+r.owner.display_name+"</a></td><td>"+r.score+"</td><td>"+r.length+"</td></tr>";if(n+1<validAnswers.length&&validAnswers[n+1].score>r.score){e++}}$("#leaderboard").append(t)}function addAnalytics(){var e="";for(var t in weights){if(weights.hasOwnProperty(t)&&weights[t]!=defaultWeight){e+=(t=="\n"?"\\n":t)+"="+weights[t]+" "}}$("#weights").val(e);var n="";for(var t in usedChars){if(usedChars.hasOwnProperty(t)&&usedChars[t]==false){n+=t=="\n"?"\\n":t}}$("#unusedc").val(n);var r="";for(var t in usedWeights){if(usedWeights.hasOwnProperty(t)&&usedWeights[t]==false){r+=t+" "}}$("#unusedw").val(r);var i="";if(invalidComments.length>0){for(var s=0;s<invalidComments.length;s++){var o=invalidComments[s];i+="<a href='#"+o.link+"'>"+o.owner.display_name+"</a> "}}else{i="none"}$("#comments").html(i);var u="";if(invalidAnswers.length>0){for(var s=0;s<invalidAnswers.length;s++){var a=invalidAnswers[s];u+="<a href='#"+a.link+"'>"+a.owner.display_name+"</a> "}}else{u="none"}$("#answers").html(u)}function checkAnswers(e){for(var t=0;t<e.items.length;t++){var n=e.items[t];var r=answerPattern.exec(n.body);if(r){var i=htmlDecode(r[1]);var s=computeScore(i);if(s==-1){invalidAnswers.push(n)}else{n.length=i.length;n.score=s;validAnswers.push(n)}}else{invalidAnswers.push(n)}}addLeaderboard();addAnalytics()}function checkComments(e){for(var t=0;t<e.items.length;t++){var n=e.items[t];var r=commentPattern.exec(htmlDecode(n.body));if(r){var i=n.owner.user_id;var s=parseInt(r[1]);var o=r[2]=="\\n"?"\n":r[2]=="\\s"?" ":r[2];if(userIDs.hasOwnProperty(i)||!usedWeights.hasOwnProperty(s)||usedWeights[s]||!usedChars.hasOwnProperty(o)||usedChars[o]){invalidComments.push(n)}else{userIDs[i]=true;usedWeights[s]=true;usedChars[o]=true;weights[o]=s}}}$.get(answersURL,checkAnswers)}function refresh(){$.get(commentsURL,checkComments)}questionID=45040;commentsURL="https://api.stackexchange.com/2.2/questions/"+questionID+"/comments?order=asc&sort=creation&site=codegolf&filter=!t)IWLXOkOvAuPe8m2xJrXOknWcw(ZqZ";answersURL="https://api.stackexchange.com/2.2/questions/"+questionID+"/answers?order=desc&sort=activity&site=codegolf&filter=!.FjsvG2LuND(frE*)WTvqQev1.lyu";commentPattern=/^#### (\d+) -> (\\(?:n|s)|[ -~]) ####$/;answerPattern=/<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/;chars="\n !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";validAnswers=[];invalidAnswers=[];invalidComments=[];userIDs={};usedWeights={};usedChars={};weights={};defaultWeight=chars.length+1;for(var i=0;i<chars.length;i++){usedChars[chars[i]]=false;usedWeights[i+1]=false;weights[chars[i]]=defaultWeight}refresh() ``` ``` *{font-family:Helvetica,Arial,sans-serif}table{border:3px solid green;border-collapse:collapse}button{font-size:100%}th{background-color:green;color:#fff;padding:6pt}td{border:1px solid green;padding:6pt}.large{font-size:140%}.title{font-weight:700;margin:6pt 0}textarea{font-family:"Courier New";white-space:nowrap;overflow:auto}input[readonly]{background-color:#dcdcdc}.analytics{font-size:90%;padding:4pt 0 0} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class='large title'>Leaderboard</div><table id='leaderboard'> <tr> <th>Place</th> <th>Submitter</th> <th>Score</th> <th>Program Length</th> </tr></table><br><div class='title'>Compute Score</div><textarea id='code' rows='5' cols='40' placeholder='paste code here...'></textarea><br><button type='button' onclick='compute()'>Compute</button> Score: <input type='text' id='score' readonly><br><br><div class='title'>Analytics</div><div class='analytics'>Assigned weights: <input type='text' id='weights' readonly></div><div class='analytics'>Unused characters: <input type='text' id='unusedc' readonly> (all weight 97)</div><div class='analytics'>Unused weights: <input type='text' id='unusedw' readonly></div><div class='analytics'>Invalid comments (duplicate user/char/weight):&nbsp;<span id='comments'></span></div><div class='analytics'>Invalid answers (illegal characters or no code block):&nbsp;<span id='answers'><span></div><br><button type='button' onclick='refresh'>Refresh</button> ``` For this leaderboard to work, the comments must be in the exact format described above and your program's code must be in the first multi-line code block in your answer (the `<pre><code>...</code></pre>` ones). Don't use syntax highlighting or your code won't be read correctly. The snippet can take a minute or two before it updates. I have not tested the snippet thoroughly but I'll be keeping an eye on it as this contest gets underway. If you notice any bugs please tell me. Here is an non-minified version: ``` questionID = 45040 commentsURL = 'https://api.stackexchange.com/2.2/questions/' + questionID + '/comments?order=asc&sort=creation&site=codegolf&filter=!t)IWLXOkOvAuPe8m2xJrXOknWcw(ZqZ' answersURL = 'https://api.stackexchange.com/2.2/questions/' + questionID + '/answers?order=desc&sort=activity&site=codegolf&filter=!.FjsvG2LuND(frE*)WTvqQev1.lyu' commentPattern = /^#### (\d+) -> (\\(?:n|s)|[ -~]) ####$/ answerPattern = /<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/ chars = '\n !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' validAnswers = [] invalidAnswers = [] invalidComments = [] userIDs = {} usedWeights = {} usedChars = {} weights = {} defaultWeight = chars.length + 1 for (var i = 0; i < chars.length; i++) { usedChars[chars[i]] = false usedWeights[i + 1] = false weights[chars[i]] = defaultWeight } function compute() { var score = computeScore($('#code').val()) $('#score').val(score == -1 ? 'Invalid characters' : score) } function computeScore(code) { var score = 0 for(var i = 0; i < code.length; i++) { if (weights.hasOwnProperty(code[i])) { score += weights[code[i]] } else { return -1 } } return score } function htmlDecode(input) { var e = document.createElement('div') e.innerHTML = input; return e.childNodes.length === 0 ? '' : e.childNodes[0].nodeValue } function addLeaderboard() { validAnswers.sort(function(a,b) { return a.score > b.score} ) var place = 1 var rows = '' for(var i = 0; i < validAnswers.length; i++) { var a = validAnswers[i] rows += '<tr><td>' + place + "</td><td><a href='" + a.link + "'>" + a.owner.display_name + "</a></td><td>" + a.score + '</td><td>' + a.length + '</td></tr>' if (i + 1 < validAnswers.length && validAnswers[i + 1].score > a.score) { place++ } } $('#leaderboard').append(rows) } function addAnalytics() { //assigned weights var assigned = '' for (var key in weights) { if (weights.hasOwnProperty(key) && weights[key] != defaultWeight) { assigned += (key == '\n' ? '\\n' : key) + '=' + weights[key] + ' ' } } $('#weights').val(assigned) //unused chars var unusedc = '' for (var key in usedChars) { if (usedChars.hasOwnProperty(key) && usedChars[key] == false) { unusedc += key == '\n' ? '\\n' : key } } $('#unusedc').val(unusedc) //unused weights var unusedw = '' for (var key in usedWeights) { if (usedWeights.hasOwnProperty(key) && usedWeights[key] == false) { unusedw += key + ' ' } } $('#unusedw').val(unusedw) //invalid comments var invalidc = '' if (invalidComments.length > 0) { for (var i = 0; i < invalidComments.length; i++) { var c = invalidComments[i] invalidc += "<a href='#" + c.link + "'>" + c.owner.display_name + '</a> ' } } else { invalidc = 'none' } $('#comments').html(invalidc) //invalid answers var invalida = '' if (invalidAnswers.length > 0) { for (var i = 0; i < invalidAnswers.length; i++) { var a = invalidAnswers[i] invalida += "<a href='#" + a.link + "'>" + a.owner.display_name + '</a> ' } } else { invalida = 'none' } $('#answers').html(invalida) } function checkAnswers(answers) { for (var i = 0; i < answers.items.length; i++) { var answer = answers.items[i] var match = answerPattern.exec(answer.body) if (match) { var code = htmlDecode(match[1]) var score = computeScore(code) if (score == -1) { invalidAnswers.push(answer) } else { answer.length = code.length answer.score = score validAnswers.push(answer) } } else { invalidAnswers.push(answer) } } addLeaderboard() addAnalytics() } function checkComments(comments) { for (var i = 0; i < comments.items.length; i++) { var comment = comments.items[i] var match = commentPattern.exec(htmlDecode(comment.body)) if (match) { var userID = comment.owner.user_id var weight = parseInt(match[1]) var char = match[2] == '\\n' ? '\n' : (match[2] == '\\s' ? ' ' : match[2]) //check validity if (userIDs.hasOwnProperty(userID) || !usedWeights.hasOwnProperty(weight) || usedWeights[weight] || !usedChars.hasOwnProperty(char) || usedChars[char]) { invalidComments.push(comment) } else { userIDs[userID] = true usedWeights[weight] = true usedChars[char] = true weights[char] = weight } } } $.get(answersURL, checkAnswers) } function refresh() { $.get(commentsURL, checkComments) } refresh() ``` ``` * { font-family: Helvetica, Arial, sans-serif; } table { border: 3px solid green; border-collapse: collapse; } button { font-size: 100%; } th { background-color: green; color: white; padding: 6pt; } td { border: 1px solid green; padding: 6pt; } .large{ font-size: 140%; } .title{ font-weight: bold; margin: 6pt 0 6pt 0; } textarea { font-family: "Courier New"; white-space: nowrap; overflow: auto; } input[readonly] { background-color: gainsboro; } .analytics { font-size: 90%; padding: 4pt 0 0 0; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='large title'>Leaderboard</div> <table id='leaderboard'> <tr> <th>Place</th> <th>Submitter</th> <th>Score</th> <th>Program Length</th> </tr> </table> <br> <div class='title'>Compute Score</div> <textarea id='code' rows='5' cols ='40' placeholder='paste code here...'></textarea><br> <button type='button' onclick='compute()'>Compute</button> Score: <input type='text' id='score' readonly> <br> <br> <div class='title'>Analytics</div> <div class='analytics'>Assigned weights: <input type='text' id='weights' readonly></div> <div class='analytics'>Unused characters: <input type='text' id='unusedc' readonly> (all weight 97)</div> <div class='analytics'>Unused weights: <input type='text' id='unusedw' readonly></div> <div class='analytics'>Invalid comments (duplicate user/char/weight):&nbsp;<span id='comments'></span></div> <div class='analytics'>Invalid answers (illegal characters or no code block):&nbsp;<span id='answers'><span></div> <br> <button type='button' onclick='refresh'>Refresh</button> ``` Keep in mind that this scoring system is completely new and experimental. Hopefully Stack Exchange won't mind that it involves tons of comments. :P *Related challenge: [Print this diamond](https://codegolf.stackexchange.com/questions/8696/print-this-diamond)* [Answer] # Python 2, 120 bytes ``` T=raw_input() L=len(T) r=[b[::-1]+b[1:]for b in [T[-b:]+' '*(L-b)for b in range(1,L+1)]] for b in r[:-1]+r[::-1]:print b ``` Edit: Lowered cost with some cheaper characters. [Answer] # CJam, 144 150 bytes ``` "x*3:*3:3*::33:3:::333*::333*3::***3::**::33:3::3*:::::*3:3:3:**33*333333::33*:*333:*3*3**:**3:**:3*3:33*3:3*:333**:3**33:*3:::*:3*::3"'3/'b*3b127b:c~ ``` Tried some encoding... Updated because the weight of `b` has changed. Another encoding which is only better in theory (140 bytes): ``` ":***(*3:**3*I**:3*****:*3*******: ::::*:***II@3*******: :**I:**:***:*3***3*I3I:3***33:::*I**3I***3***:3:*I*3I"{"*:I3( **@"#1a*~0}%2b126b:c~ ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 bytes ``` L+_tbbjbymy+>zd*\ dlz ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/) [Answer] # CJam, 31 bytes ``` lW%_,:I(S*\+I*I/2%{_W%1>+z}2*N* ``` Just an adaptation of my answer to [Print this diamond](https://codegolf.stackexchange.com/a/44911/8478) for now. I might tweak it when the weights have changed. [Test it here.](http://cjam.aditsu.net/) [Answer] # J, 45 chars ``` (({~((]*]<#@[)>:@(+/~)@:|@i:@(2-#)))@(' '&,)) ``` Longish solution, will golf it with some cheap chars... [Try it online.](http://tryj.tk/) (Append input string with single quotes.) [Answer] # PHP (131 chars) ``` function f($s){for($i=-($l=strlen($s));$i<$l;$I=abs(++$i)){$t=substr($s,$I);echo str_repeat(' ',$I).strrev($t).substr($t,1)."\n";}} ``` <http://3v4l.org/9Vvkm> Will optimise once the weightings are clearer. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 61 bytes, score 4890. ``` fK\a:-$vj:vL?Lv-\ v*$+?:L1-wifK\a:-$vjvm2v/vt\a:-p+:wRh1?L"iJ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=fK%5Ca%3A-%24vj%3AvL%3FLv-%5C%20v*%24%2B%3F%3AL1-wifK%5Ca%3A-%24vjvm2v%2Fvt%5Ca%3A-p%2B%3AwRh1%3FL%22iJ&inputs=string&header=&footer=) This was painful, especially in a language with a huge codepage that I can only use a small bit of. Score calculation + explanation coming soon. Thanks to lyxal for finding some clever ways for me to do various things. [Answer] ## Java, 318 bytes ``` class N{public static void main(String[]a){char[]s=new java.util.Scanner(System.in).nextLine().toCharArray();int l=s.length,m=l-1,$=0,b;String t="";for(;$<l;$++,t+='\n')for(b=0;b<l+$;b++)t+=b+$<m?' ':s[b>m?m-b+$:b+$-m];for($=l-2;$>-1;$--,t+='\n')for(b=0;b<l+$;b++)t+=b+$<m?' ':s[b>m?m-b+$:b+$-m];System.out.print(t);}} ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/19914/edit). Closed 6 years ago. [Improve this question](/posts/19914/edit) Your task is to build an interpreter to the [Useless](http://esolangs.org/wiki/Useless) language: Here are the functional requirements: * All the described commands should be accepted by the interpreter. * **`NO.`**, **`NOOP`** and **`INCLUDE-xxx`** must be honored. * **`DONTUSEME(n)`** must have its base date to be easily configurable to something more reasonable for testing purposes. * **`INCLUDE-xxx`** must be able to generate any command with a roughly equal probability. If it generates a **`DONTUSEME(n)`**, he should randomly choose a small value for n. * **`DONTUSEME(n)`** windows should survive the **`NO.`** instruction. Tip: spawn a new process for those windows. * **`BOOM!`** and **`KABOOM!`** must do something bad and scary, and **`KABOOM!`** must be worse than **`BOOM!`**. But this **must not** be taken too seriously, so it should not be something destructive, overly-disruptive or hard to be undone. Please, **do not, *do not*, and do not** make these instructions run a `rm -rf \` command, run a fork bomb, install malware, corrupt data in the file system, or post or download inappropriate content from the internet, or any other thing clearly abusive. * **`TURINGVSALONZO`** should run as if it in fact was doing what it should do. Tip: Make it randomly decide if it would sleep for a random very long time, or a random short time, or forever. * All the other predefined instructions should do something other than the aforementioned instructions and different one to the another, but never something worse than **`BOOM!`** or **`KABOOM!`**. What they do exactly is up to you, but a simple implementation would just output an error message or some other text. * You should provide an easy way for the user to provide the program that would be run by the interpreter. i.e. Reading plaintext from a file or from `stdin` is ok. Reading it from an encrypted file somewhere in the internet is not. Optional: * You might invent some new commands if you want, but they should be subject to the same rules as the others are. Do not use this to circumvent the restrictions in **`BOOM!`** and **`KABOOM!`** or to defeat **`DONTUSEME(n)`**. And if you do invent new commands, explain what they do. * You should think about what the interpreter do if it receives input with unknown commands (or even completely unparseable random bytes gibberish). * Although no instruction should defeat the **`DONTUSEME(n)`** command, you might add a kill switch for it. Just don't expose that in the language. We have a few non-functional requirements to avoid abuses: * Your entry must be as complete and autocontained as possible. This means that it should not be simply some sort of installer or clearly incomplete program. This way, downloading and using libraries like jQuery or packages from maven central is ok, but downloading arbitrary code and packages from your custom server is not. * Your entry should not get any content from this very page or from some mirror or copy of this page in order to do some sort of reflection or for any other purpose. This is essential to avoid some program that try to read other entrants answers to this question or try to disrupt the question or answers in any way. * Your interpreter should be immutable and not self-modify or modify its input file. But, creating a mutant copy of the interpreter or of the input file without altering the original is ok. And finally, considering that: * The programs in the answers are expected to be pretty useless even if fully conformant; * The language is (on purpose) very underspecified, and the answerers have a lot of liberties to take and are incentived to take them; * The requirements and the possible implementations have a lot of subjective points; * The objective with this is to just get some fun and creativity. Then, this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), and **the most upvoted answer fully conformant to the rules wins!** So, you don't need to golf or obfuscate your answer (but you might do that if you want). Just be sure to post something original and creative to deserve the upvotes, i.e. please don't post lame boring entries. [Answer] # HTML + Javascript + jQuery + jQuery UI The input should be given in the text area and should be formatted as each command in a line. The commands are not case sensitive. All of the commands were fully implemented. I hope that you enjoy. You can try it at <http://jsfiddle.net/bCBfk/> ``` <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <title>Useless interpreter</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style type="text/css"> textarea { height: auto; } .badshit { color: red; } .ui-dialog-titlebar-close { display: none; } </style> <script type="text/javascript"> String.prototype.startsWith = function(x) { return this.substring(0, x.length) === x; }; String.prototype.endsWith = function(x) { return this.substr(this.length - x.length, x.length) === x; }; var npe = "<pre>java.lang.NullPointerException\n" + " at org.esolangs.wiki.useless.memorymodel.ExistentObjectPool.findObject(ExistentObjectPool.java:684)\n" + " at org.esolangs.wiki.useless.interpreter.WhereInstruction.visit(WhereInstruction.java:29)\n" + " at org.esolangs.wiki.useless.interpreter.UselessProgram.run(UselessProgram.java:413)\n" + " at org.esolangs.wiki.useless.interpreter.Main.main(Main.java:53)</pre>"; var wut = navigator.userAgent + " - " + navigator.language + " - " + navigator.platform + " - Ii?".toLocaleUpperCase(); var wut2 = ""; for (var c = wut.length - 1; c >= 0; c--) { wut2 += wut.charAt(c); } var popupMasterMind; function killIt() { clearInterval(popupMasterMind); $(".dontuseme").remove(); popupMasterMind = null; } function spawn() { var x = $("<div class='dontuseme' title=''><p></p></div>"); $("body").append(x); x.dialog(); var bw = $("body").innerWidth(); var bh = $("body").innerHeight(); if (bh < 500) bh = 500; var xw = x.width(); var xh = x.height(); x.parent().css({left: Math.random() * (bw - xw) + "px", top: Math.random() * (bh - xh) + "px"}); } function dontuseme() { if (popupMasterMind) return; spawn(); popupMasterMind = setInterval(spawn, 700); } var hasOutput = false; function clearOutput() { $("#output").empty(); hasOutput = false; $("#cc").hide(); } function out(a) { $("#output").append($(a)); hasOutput = true; } function finish() { $("#running").hide(); $("#bt").show(); if (hasOutput) $("#cc").show(); } var annoyingUser = false; function swap() { annoyingUser = true; $("#everything").toggle(); setTimeout(swap, 800); } function randomString() { var r = ""; var f = Math.floor(Math.random() * 12) + 8; for (var i = 0; i < f; i++) { r += "ABCDEFGHIJKLMNOPQRSTUVWXYZ.!?0123456789".charAt(Math.floor(Math.random() * 39)); } return r; } var instructions; function includeInstruction(name) { name = name.toUpperCase(); if (instructions[name]) return; // Do not add it twice or overwrite existing instructions. var array = []; for (var e in instructions) { array.push(e); } var rand = Math.floor(Math.random() * array.length); //alert(name + ": " + array[rand]); instructions[name] = instructions[array[rand]]; } // DONTUSEME(n) are special cases handled elsewhere. instructions = { "FAIL": function() { out("<p class='badshit'>Warning: The &lt;blink&gt; tag is obsolete.</p>"); if (!annoyingUser) swap(); return "next"; }, "NOT": function() { out("<p class='badshit'>Warning: The NOT instruction is discouraged because it breaks yor Useless program.</p>"); return "quit"; }, "NEVER": function() { out("<pre>Wild MISSINGNO. appeared!</pre>"); return "next"; }, "IDK": function() { out("<pre>" + {}.idk + "</pre>"); return "next"; }, "BOOM!": function() { $("#everything").empty(); return "quit"; }, "KABOOM!": function() { window.location = "http://answers.yahoo.com/question/index?qid=20110816062515AANqygl"; return "quit"; }, "NO.": function() { finish(); return "quit"; }, "QWAOZAPWQFUOA": function() { out("<p class='badshit'>Sorry, I could not understand <a href='https://www.google.com.br/#q=women+psychology+and+behaviour'>this</a>.</p>"); return "next"; }, "WUT?": function() { out("<p>" + wut2 + "</p>"); return "next"; }, "WHERE?": function() { out(npe); return "next"; }, "HOW?": function() { out("<p class='badshit'>Regular expression parser failed for HTML. Cause: \"ZALGO\"</p>"); return "next"; }, "ILLEGAL": function() { out("<pre>codegolfer is not in the sudoers file. This incident will be reported</pre>"); return "next"; }, "GODEXISTS": function() { out("<p>'GOD' spelled backwards is 'DOG'. A DOG is an animal that does not exists, and by backwarding this, we conclude that GOD exists and is not an animal.</p>"); return "next"; }, "WINDOWS": function() { out("<p><img width='640' height='400' src='http://upload.wikimedia.org/wikipedia/commons/3/3b/Windows_9X_BSOD.png' alt='Sorry, this optional instruction was not implemented. Please, install the service pack.'></p>"); return "next"; }, "NOOP": function() { return "next"; }, "TURINGVSALONZO": function() { var r = Math.random() * 10; if (r < 2) return "next"; if (r < 7) return "t" + (Math.random() * 14 + 1) * 1000; if (r < 9) return "t" + (Math.random() * 50 + 10) * 60 * 1000; return "quit"; }, "42": function() { out("<p>Calculating the answer of the life, the universe and everything.</p>"); out("<p>Estimated time is 7.5 million years.</p>"); out("<p>Don't you want to briefly take a coffe while you wait? It will not take long, I promise.</p>"); return "quit"; }, // This is special, as it needs a (surprising) useless parameter, it can't be acessed directly without prior processing, this is why it is lowercase. "dontuseme": function() { dontuseme(); return "next"; }, // This is special. If the INCLUDE-xxx generates a INCLUDE-yyy instruction, the yyy instruction will have an unknown random generated name. // Since yyy is random and unknown, it probably won't appear in the input source code, but implement it regardless. "include-random": function() { includeInstruction(randomString()); return "next"; } }; function bad(line) { //alert(line); out("<p class='badshit'>Syntax error: </p>"); } function beyondEnd() { out("<p class='badshit'>Unrecoverable error: Tried to execute code beyond the end or program.</p>"); } function interpretInstruction(lines, idx) { if (idx >= lines.length) { beyondEnd(); return; } // The toUpperCase serves two purposes: Making the language case-insensitive and hiding private implementations as lowercase instructions. ins = lines[idx].trim().toUpperCase(); var result; // Special handling for parsing DONTUSEME(n) if (ins.startsWith("DONTUSEME(") && ins.endsWith(")")) { try { parseInt(ins.substring("DONTUSEME(".length, ins.length - 1)); } catch (e) { bad(ins); return; } ins = "dontuseme"; // Special handling for INCLUDE-xxx } else if (ins.startsWith("INCLUDE-") && ins.length > 8) { var name = ins.substring(8); includeInstruction(name); ins = "NOOP"; // Already executed, follow-up as noop. } // Execute the instruction. var f = instructions[ins]; if (!f) { bad(ins); return; } var result = f(); // Move on. if (result === "quit") return; var toWait = result === "next" ? 0 : parseInt(result.substring(1)); var ii = idx + 1; setTimeout(function() { interpretInstruction(lines, ii); }, toWait); } function startInterpreter() { $("#bt").hide(); $("#cc").hide(); $("#running").show(); var src = $("#input").val(); var lines = src.split('\n'); interpretInstruction(lines, 0); } $(document).ready(function() { $("#bt").click(startInterpreter); $("#cc").click(clearOutput); }); </script> </head> <body> <div id="everything"> <p>Type here your program input:</p> <textarea id="input" style="width: 400px; height: 150px;"></textarea> <p> <button id="bt">Run the program</button> <span id="running" style="display: none;">Running the program...</span> </p> <p>Here is the program output:</p> <p id="output" class="useless"></p> <button id="cc" style="display: none;">Clear the output</button> </div> </body> </html> ``` It has one new command: > > It is the **`42`** command which calculates the answer of the life, the universe and everything. The only quirk is that it takes 7.5 million years to finish. > > > Other spoilers: > > This entry has several features: > * You will really hate the **`FAIL`** command. > * **`BOOM!`** will screw up you "execution unit". At least the windows from **`DONTUSEME(n)`** are able to survive this. > * **`KABOOM!`** is really dangerous to world in several bad ways. > * **`DONTUSEME(n)`** always opens infinite unclosable empty windows, one each 0.8 seconds. But there is a hidden kill switch. > * **`DONTUSEME(n)`** survives **`NO.`**, **`FAIL`** and even **`BOOM!`**. I just couldn't make it survive the **`KABOOM!`** though. The reason is that popup windows won't work as this is not the result of a click (and popups created by other ways are long banned in all major browsers), and could not use iframes too because of a violation of same-origin policy. > * **`INCLUDE-xxx`** can create any instruction, including **`DONTUSEME(n)`** or another **`INCLUDE-yyy`** instruction. > * If **`INCLUDE-xxx`** does generates an **`INCLUDE-yyy`** instruction, the `yyy` name is generated at random. If you grab the name of the generated command with firebug or something similar, you can use it. > * It handles malformed syntax and incomplete or empty input. > > > > [Answer] ## TI-BASIC There is a kill button for `DONTUSEME`, can you figure out which one it is? :) ``` :Lbl 1 :Input Str1 :If Str1="NO." :Pause :If Str1="FAIL" :Disp "OBSOLETE. WHAT A FAIL." :If Str1="NOT" :Disp "USING NOT IS HIGHLY DISCOURAGED!" :If Str1="NEVER" :get(Police,911) :If Str1="IDK" :Disp LLLundefined :If Str1="BOOM!" :Disp "rm -rf \" :If Str1="KABOOM!" :send(virus) :If Str1="QWAOZAPWQFUOA" :Disp "SKIPPING QWAO... UNIMPLEMENTED" :If Str1="WUT?" :dayOfWk(1) :If Str1="WHERE?" :Disp "NON-EXISTENT. SKIPPED." :If Str1="HOW?" :++ :If sub(Str1,1,9)="DONTUSEME" :Then :While 1 :sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(e) :End :End :If Str1="ILLEGAL" :Archive X :If Str1="GODEXISTS" :Disp "GOD EXISTS, PROVEN BY LAW." :If Str1="WINDOWS" :Disp "UNABLE TO OPEN START MENU!" :If Str1="NOOP" :Lbl 0 :If sub(Str1,1,8)="INCLUDE-" :sub(Str1,9,length(Str1-8)) :If Str1=Ans :Then :If not(rand) :Goto 0 :End :If Str1="TURINGVSALONZO" :Then :"+"→Str0 :randInt(5,10) :While Ans :Ans-1 :If fpart(Ans,4)4=3 :Str0+"+"→Str0 :If fpart(Ans,4)4=2 :Str0+"-"→Str0 :If fpart(Ans,4)4=1 :Str0+">"→Str0 :If fpart(Ans,4)4=0 :Str0+"."→Str0 :End :Disp "0" :"?utm_campaign=0" :End :Goto 1 ``` ]
[Question] [ Given a string of `1` and `2` of any length, write some code (doesn't have to be a **function** anymore, everything will be just fine) that calculates how many steps does it need to shrink the string to a final form, following this criterion: If your string is `112112`, this means that you have to print a 1, two 1s and a 2, like this: `1112`. When you'll perform the operation again you'll have to print a 1 and a 2. You get `12`. Then you print one 2, obtaining `2`. This is a final form, since this string is not going to change anymore. Your code will output `3`, since you needed 3 steps to get to the final form. **Other Rules** * If the string has uneven length, the last number remains untouched. * Every string that cannot change anymore (like `222222`) is considered a final form. * You cannot use any external source. * Your code must work with every string of `1` and `2`. * Shortest code wins, as it is code-golf. * Your code should print every step. * Every input method will be fine. **Examples** ``` Input >> 122122122121212212 Your code has to print: 211222111111222 11222111222 122111222 2111222 111222 1222 222 Steps:7 (you can omit the "Steps") ---- ---- ---- ---- Input >> 22222221 Your code has to print: 22222211 2222221 2 ---- ---- ---- ---- Input >> 2222 Your code has to print: 0 ``` **EDIT:** Heavily edited. So sorry about that. [Answer] # Ruby 1.9+, 73 characters I see the no-regex rule as silly and arbitrary, so here's a spiteful regex based solution: ``` gets ($.+=1;puts$_.gsub!(/(.)(.)/){$2*$1.to_i})until~/^(22)*[12]?$/ p~-$. ``` Test run: ``` $ ruby 21.rb <<< 122122122121212212 211222111111222 11222111222 122111222 2111222 111222 1222 222 7 ``` The last line is the number of steps. Edit: Regex restriction has been removed by Vereos. [Answer] ## C - ~~156~~ 154 My first code golf here! ``` f(char*s,c){puts(s);char*a=s,*b=s,m=50,x,y;while(*a){ x=*a++;y=*a++;if(y)m&=x&y;*b++=y?:x;x-49?*b++=y:(*b=0);} *b=*a;return m/50?printf("%i",c),c:f(s,c+1);} ``` Test: ``` char c[] = "12211122211222221"; f(c,0); ``` Output: ``` 12211122211222221 21112211222221 111221222211 121122221 21222211 1122221 122221 22211 22111 2211 221 10 ``` [Answer] ## GolfScript: 69 characters ``` 0\{\)\.p.[]\{~10base{.,1>{(\(@\{''+*}++~@\+\.}{~+0.}if}do;}~.@=!}do;( ``` Every iteration of the inner loop finds the first 2 numbers in the string, and use them to form a block of the form `{num1 num2 '' + *}`. When this block is evaluated, we get the desired reading of those numbers. Repeat this until there are no more characters. Then, repeat that loop while keeping track of the number of iterations and printing. Sample: ``` echo '12211122211222221' | ruby golfscript.rb g.gs "12211122211222221" "21112211222221" "111221222211" "121122221" "2122221" "1122221" "122221" "22211" "22111" "2211" "221" 10 ``` [Answer] # Python - 126 ``` def f(s): j=0 while 1: n="";i=0 for c in s:n+=c*i;i=[int(c),0][i>0] if i:n+=`i` if s==n:break s=n;print s;j+=1 print j ``` This doesn't print the input value. If it needs to, then move `print s;` to right before `n="";` Note: you said "function", so this is a function. Here is a version that is not a function (127 chars): ``` s=raw_input();j=0 while 1: n="";i=0 for c in s:n+=c*i;i=[int(c),0][i>0] if i:n+=`i` if s==n:break s=n;print s;j+=1 print j ``` (If I can have the user paste the number in then **118** (paste data between quotes on first line)): ``` s="";j=0 while 1: n="";i=0 for c in s:n+=c*i;i=[int(c),0][i>0] if i:n+=`i` if s==n:break s=n;print s;j+=1 print j ``` Sample run: ``` 211222111111222 11222111222 122111222 2111222 111222 1222 222 7 ``` As a bonus, each of these solutions work for strings containing larger numbers (up to 9), but some strings produce larger and larger outputs (for example, `99`) [Answer] # JavaScript, 107 (requires arrow function support, e.g. as in Firefox) ``` for(p=prompt,s=p(),k=0;r=s.match(/.?.?/g).map(a=>a>2?a[1]+(a<13?'':a[1]):a).join(''),p(s),r!=s;s=r)k++;p(k) ``` * `s` is the input string * Each round, we use the regex `.?.?` to explode `s` into an array of two-character strings, then `map` those strings into their reduced forms and glue the array back together * `r` stores the result of the current round for comparison against the previous `s` * `k` is the round counter * We horribly abuse `prompt` (aliased to `p`) as both an input and output mechanism, since it can present a message to the user --- ``` for(p=prompt,s=p(),k=0; r=s.match(/.?.?/g).map( a=> a>2? // if a is more than one char a[1]+(a<13?'':a[1]) // double the second char if the first char is 2 :a // if not two chars, return a ).join(''), // glue new array together p(s), // print s r!=s; // test if string has changed s=r) k++; p(k) ``` [Answer] ## Perl - 50 (+2) bytes ``` $a-=print while"$_"ne(s/(.)(.)/$2x$1/ge,$_);$_=-$a ``` Requires `-pl` command line switches. Sample usage: ``` $ more in.dat 122122122121212212 $ perl -pl rev-count.pl < in.dat 211222111111222 11222111222 122111222 2111222 111222 1222 222 7 $ more in.dat 22222221 $ perl -pl rev-count.pl < in.dat 22222211 2222221 2 $ more in.dat 2222 $ perl -pl rev-count.pl < in.dat 0 ``` [Answer] **PHP, 240** ``` <?php $s=$_GET['i'];$h=$s;for($t=1;$h!=r($h);$t++){echo$h.'<br>';$h=r($h);}echo r($s)==$s?0:$h.'<br>'.$t;function r($c){for($i=0;$i<strlen($c)-1;$i+=2){$s.=$c[$i]==1?$c[$i+1]:$c[$i+1].$c[$i+1];if($i+3==strlen($c))$s.=$c[$i+2];}return$s;}?> ``` Example: <http://skyleo.de/codegolf.php?i=211222111111222> ``` 211222111111222 11222111222 122111222 2111222 111222 1222 222 7 ``` I'm kinda bad at codegolf .\_. Maybe I shouldn't use only Java and PHP (and I should think more complicated) [Answer] ## R, 158 ``` s=utf8ToInt(scan(,""))-48;i=0;while(any(!!s-2)){t=(a<-sum(s|T))%%2;u=s[seq(a-t)];cat(s<-c(rep(u[c(F,T)],u[c(T,F)]),s[a*t]),"\n",sep="");i=i+1};cat("Steps:",i) ``` Example: ``` 122122122121212212 211222111111222 11222111222 122111222 2111222 111222 1222 222 Steps: 7 ``` [Answer] ## MATHEMATICA, 117 ``` s="122122122121212212"; Grid@FixedPointList[(Partition[#,2,2,1,{}]/.{{1,1}->{1},{1,2}->{2},{2,1}->{1,1}}//Flatten)&,FromDigits/@Characters@s] 122122122121212212 211222111111222 11222111222 122111222 2111222 111222 1222 222 222 ``` [Answer] **POWERSHELL, 2** Based on Vereos's response " You can use whatever input method shortens your code" to my question in the comments of the OP, the following script achieves the result: ``` $a ``` Example run for "122122122121212212": ``` # Input method is to assign answer to $a: $a = @" 211222111111222 11222111222 122111222 2111222 111222 1222 222 Steps: 7 "@ # Execute script $a # Answer follows: 211222111111222 11222111222 122111222 2111222 111222 1222 222 ``` Obviously this isn't a serious entry - it's purpose is to illustrate my point that allowing any input method can trivialize the actual code needed to yield the answer. Hence the input method needs to be more rigorously specified. [Answer] ## J, 41 chars As a function (ew parens! not terribly happy about them): ``` (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) ``` **Exploded view** ``` _2&( )\ NB. on non-overlapping 2-grams: ( )/ NB. insert between the two chars: ".@[ NB. read left operand ([) as a number #] NB. and repeat right this many times, <@( ) NB. then put it in a box ([:; ) NB. open and concatenate the boxes ( ^:a:) NB. repeat until fixpoint (keeping intermediates) }:@ NB. drop first element (the input) (,":@#)@ NB. append length of array (# steps) ``` **Sample run** ``` (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '1121121' 1121121 11121 121 21 11 5 (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '122122122121212212' 122122122121212212 211222111111222 11222111222 122111222 2111222 111222 1222 7 ``` [Answer] # Perl, 107 chars The other perl code clearly beats this, but for what it's worth, here it is. I used the -l switch at the cost of an extra character: ``` $_=<>;while(1){$l=$_;$_=join"",map{($a,$b)=split//;$b?$b x$a:$a}grep/./,split/(..?)/;last if$l eq$_;print} ``` A more legible version of that: ``` $x = <>; while(1) { $l = $x; $x = join "", map{ ($a,$b) = split//, $_; $b ? $b x $a: $a } grep /./, split /(..?)/, $x; last if $l eq $x; print $x} ``` ]
[Question] [ **This question already has answers here**: [Encode a program with the fewest distinct characters possible](/questions/11690/encode-a-program-with-the-fewest-distinct-characters-possible) (10 answers) Closed 6 years ago. The proof of the set of characters is that there is a translator which takes any ascii python program as input and produces a limited character set version of the program. The limited character set program can be slower than the original program. It simply has to be possible to produce the same output as the valid python program. For example, here is a translator that takes any ascii python program as input and writes out a version that doesn't use the character x: ``` import random import string with open('in.py') as infile: with open('out.py', 'w') as outfile: lines = infile.readlines() outfile.write("data = '") random_string = ''.join(random.choice(string.digits) for x in range(20)) for line in lines: outfile.write(line.encode('string-escape').replace('x', random_string)) outfile.write("'\n") outfile.write("exec data.replace('%s', chr(%s))" % (random_string, ord('x'))) ``` note that this will fail if the program happens to have the random string in it already, but for the purposes of this question lets accept that 'any' can be slightly limited. We don't have to consider extremely low probabilities of failure due to random chance or a malicious input program. [Answer] I've come up with a 9-character translator using `exec` (also posted at this GitHub [gist](https://gist.github.com/3324382)): ``` def convert_txt(txt): """Convert the text of a Python program to minimal Python""" s = "+".join(["chr(%s)" % "+".join(["1"] * ord(c)) for c in txt]) return 'exec(%s)' % s ``` The only characters it needs are `()+1cehrx`. ]
[Question] [ Given an arithmetic expression, which can include parentheses (`()`), exponents (`^`), division (`/`) and multiplication (`*`), addition (`+`) and subtraction (`-`) (in that order of operation), such as ``` a ^ (2 / 3) * 9 * 3 - 4 * 6 ``` output the same expression in prefix notation. ``` (- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6)) ``` Spaces are optional in the input as well as the output. You may assume that all operators are left-associative and that all of the numbers in the expression are single digit integers (i.e. `[0-9]`). This is a code golf challenge, so the shortest solution wins. [Answer] ## Ruby 1.9 - 134 ``` %w[** / * + -].map{|o|String.send(:define_method,o){|n|"(#{o=='**'??^:o} #{self} #{n})"}} puts eval gets.gsub(/\w/,'?\0').gsub ?^,'**' ``` Pretty evil, but it works: ``` $ echo 'a ^ (2 / 3) * 9 * 3 - 4 * 6' | ruby sol.rb (- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6)) ``` [Answer] ## Python, 222 chars ``` class A: def __init__(s,x):s.v=x for x in('pow^','mul*','div/','add+','sub-'):exec('A.__'+x[:3]+'__=lambda s,y:A("('+x[3]+'"+s.v+y.v+")")') import re print eval(re.sub('(\\w)','A("\\1")',raw_input().replace('^','**'))).v ``` Similar to the Ruby one, except Python doesn't let you redefine the global ops, only ops of a class. [Answer] ## Perl 6 (146|150) The easiest way to do this is to just swap out the subroutines that implement the operators for new ones. ``` sub infix:«+» ($a,$b) { "(+ $a $b)" } sub infix:«-» ($a,$b) { "(- $a $b)" } sub infix:«*» ($a,$b) { "(* $a $b)" } sub infix:['/'] ($a,$b) { "(/ $a $b)" } # stupid highlighter sub infix:«**» ($a,$b) { "(^ $a $b)" } # currently there seems to be a bug that # prevents this from modifying the parser correctly # probably because there is already a different operator with this name # which has nothing to do with exponentiation my &infix:«^» := &[**]; say 'a' ** (2 / 3) * 9 * 3 - 4 * 6; # (- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))␤ ``` The absolute minimum amount of bytes for doing it this way is: ``` sub infix:<+>{"(+ $^a $^b)"}␤ # 29 sub infix:<->{"(- $^a $^b)"}␤ # + 29 sub infix:<*>{"(* $^a $^b)"}␤ # + 29 sub infix:<**>{"(^ $^a $^b)"}␤ # + 30 sub infix:</>{"(/ $^a $^b)"}␤ # + 29 ``` 146 bytes, although it makes more sense to count graphemes in Perl 6. This assumes that "*output the same expression in prefix notation*" could just refer to the result of the expression, not necessarily the output of the program. You would have to add `say` in front of the expression to get the program to print it to STDOUT. (150 bytes) [Answer] ## [Unix TMG](https://github.com/amakukha/tmg), 189 bytes ``` p:ignore(<< >>)parse(e);e:q(t,a);t:q(x,m);x:q(r,h);q:proc(x,y)x k:y/d x={<(>2 3 1<)>}b\k;r:o(!<<+-*/^()>>)|<(>e<)>;a:o(<<+->>);m:o(<<*/>>);h:o(<<^>>);o:proc(n)smark any(n)scopy;d:;b:bundle; ``` The solution is almost straight from the [manual](https://amakukha.github.io/tmg/TMG_Manual_McIlroy_1972.html) for the language, with only basic golfing. Expanded: ``` prog: ignore(<< >>) parse(expr); expr: q(term, addop); term: q(fact, mulop); fact: q(prim, expop); q: proc(x,y) x k: y/done x ={ <(> 2 3 1 <)> } b\k; prim: op(!<<+-*/^()>>) | <(> expr <)>; addop: op(<<+->>); mulop: op(<<*/>>); expop: op(<<^>>); op: proc(n) smark any(n) scopy; done: ; b: bundle; ``` ]
[Question] [ We're going to turn ascii art versions of polygons into their equivalent GeoJSON. # The ASCII shape language The input ASCII language only has 3 possible characters: * `*` signifies a vertex * `-` signifies a horizontal line * `|` signifies a vertical line A `*` will never be directly adjacent to another `*` (but may be diagonal to one). A `*` shall have exactly two lines adjacent to it, either a `-` to the left or right of it, or a `|` to the top or bottom. There will never be a `|` to the left or right of a `*`, and consequently, never a `-` directly above or below a `*`. It is possible to have a vertex along a line, e.g. `-*-`. Each input only contains one "ring". There are no multi-part polygons, or polygons with holes. The input is minimal. For example, there are no extra leading or trailing blank lines or trailing white spaces. For example, some valid shapes are: ``` *--* | | *--* *--* | | | *--* | | *-----* *--* | | *-* | | *-* | | *--* ``` # The coordinate language The above shapes shall be converted into their equivalent coordinates. The top left corner of the ASCII art is `(0,0)`. The first coordinate is the x-axis. For example, the 3 shapes above would turn into the following coordinates: ``` [[0,0],[3,0],[3,2],[0,2],[0,0]] [[0,0],[3,0],[3,2],[6,2],[6,4],[0,4],[0,0]] [[2,0],[5,0],[5,3],[3,3],[3,5],[0,5],[0,2],[2,2],[2,0]] ``` Note that other representations are possible too, depending on which coordinate you start with. Continuing with GeoJSON convention, the coordinate ring shall be clockwise. # Input/output Take your input via any of the standard methods. The input may be: * A string containing only the characters `*`, `-`, `|`, `\n` or * or an array of strings where each string represents a line. Output shall be via any standard format. The output shall be an `n`-by-2 dimensional JSON array. Any amount and type of whitespace is allowed in the resulting JSON. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` WS⟦ι⟧⊞υ⟦⌕θ*⁰⟧J⊕⌕θ*⁰WΦ⁴‹ ⊟KD²✳⊗κ«✳⊗⌊ι ≡KK*⊞υ⟦ⅈⅉ⟧»⎚⭆¹υ ``` [Try it online!](https://tio.run/##ZVDBSsQwED03XzH0NAkpqHhyjy4LigsFPSiLh5od7LBpWtPEPbj77TXZLioYAjOZeW/evJi28aZv7DTtW7YEeOeGGB6DZ/eOUkKdkoAbfpULUcexxahhs2K3xQ8NpSqlhovcu4/d8NQntvHUkQu0xb@oDEuos8aKbSCP1xoeaByxhFJD3Q9YE@2W7MkE7h1eafh9LPv4ZtPQnZwPfIli3u0/Zs2Ou9ghy6ybpiflYtxzMC2cNHDmm2akvN0N/Dh7xsR4QZktFUdxFLeWGo/Z/Els/ph1M@ClhijlYpoAVFUpAXBIV6hK5XDIVSXOpZRN1af9Bg "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: ``` WS⟦ι⟧ ``` Copy the input to the canvas. ``` ⊞υ⟦⌕θ*⁰⟧ ``` Start at the top left corner of the shape. ``` J⊕⌕θ*⁰ ``` Jump to the top edge of the shape. ``` WΦ⁴‹ ⊟KD²✳⊗κ« ``` Repeat while there's at least one orthogonally adjacent shape part. ``` ✳⊗⌊ι ``` Overwrite the current shape part, moving to the next one. ``` ≡KK* ``` If this is a `*`, then... ``` ⊞υ⟦ⅈⅉ⟧ ``` ... record the current coordinates. ``` »⎚⭆¹υ ``` Clear the canvas and pretty-print the final list of coordinates. [Answer] # [J](http://jsoftware.com/), 92 90 85 75 67 bytes ``` [:(-.~{.,~{.,((]~.@,[#~1=(|@-{:))^:_{.)@}.)&($j./@#:I.@,)/'* '~:"{] ``` [Try it online!](https://tio.run/##bY1BC4JAEIXv@ytGjXZX3Ek7BE4IC0EQdOoqm4dQwkuHvK3tX7c1LSg6vGFm3vdm2iEPKDObgHLOWYi8gYKAQwIpkJdC2J2O@6EkodBZTEYJYRzqpIxcVoheK0tSnqmyKPUD5VIsWlzpiA6ekSseA3cUWjNI1tX3rkAoCerL9aYbMFus1q/1@C9lsVIx6wH6qZN/LV/eA8yo@qVnxNsTEX@C3/eHJw "J – Try It Online") ## idea 1. Get positions of all non-space characters in "reading" order (left to right, top to bottom). This is easy using a standard idiom, and returns the positions as complex numbers. 2. Next, we need to get them in "ring" order. To do that, seed a list with the upper-leftmost position and re-build the list from step 1 as follows: * Add to the most recently added list element the four compass directions, as complex numbers, giving 4 new candidates for "next" list element. * Remove any candidates not in the list from step 1 * Remove any candidates that would result in a repeat in the list we're building * The first seeded element will result in 2 candidates (we pick the first arbitrarily), but all subsequent elements will have only one "next" candidate. * Repeat this process "list length - 1" times. We now have the list from step 1 in ring order. We add the first element to the tail. 3. Remove all elements from step 2's list associated with `-|` positions, resulting in a list of just the `*` positions, but in "ring" order. This is our answer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (non-competing†) † My approach assumed `-*-` vectors weren't a thing, since I look for pairs of corner-vectors, making my entire solution worthless once that was added in as a (new) rule of the challenge.. :/ ``` εNUεNX)]Dζ«€`ʒ'*å}€¦2ôœ.Δðý©À`åθ®üåOP*}€`ÙĆ ``` -2 bytes by using 2x `€`` and `θ` instead of 2x `í€`` and `н`. Input as a list of lists of characters. [Try it online](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM9bl3LZDq4FiCacmqWsdXloLZB5aZnR4y9HJeuemHN5weO@hlYcbEg4vPbfj0LrDew4v9Q/QAqlJODzzSNv//woKWrq6WlwKCjVAxKWlqwWiakCiWlxQIV0tAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamAMXqww@tO3QQlul/@e2@oUCcYRmrMu5bYdWP2pak3BqkrrW4aW1QOahZUaHtxydrHduyuENh/ceWnm4IeHw0nM7Dq07vOfwUv8ALZCahMMzj7T9V9ILU/IvLYEYbq9zaJv9/2glLV1drZi8GgWFmpg8EFtJRwFFDEjCuQowVbpQhTA5oDhUSguhCYuxWjBhMAQxQGI1WAyPBQA). (Will time out for test cases with 10 or more vertices due to the `œ` builtin.) **Explanation:** Step 1: Pair each character with it's coordinate: ``` ε # Map over each row of the (implicit) input: NU # Store the 0-based index of the current row in variable `X` ε # Inner map over each inner cell of the current row: N # Push the cell's index X # Push the row's index from variable `X` ) # Wrap the cell-value, cell-index, and row-index into a triplet-list ] # Close the nested maps ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM/b/fwUFLV1dLS4FhRog4tLS1QJRNSBRLS6okK4WAA) Step 2: Merge the transposed result, since we want to check all `*-*` and `*|*` connections separately: ``` D # Duplicate the result ζ # Zip/transpose; with " " as implicit filler if the input isn't a rectangle # (which will be removed again with the filter later on) « # Merge the regular and transposed lists together ``` [Try just the first 2 steps online.](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM9bl3LZDq///V1DQ0tXV4lJQqAEiLi1dLRBVAxLV4oIK6WoBAA) Step 3: Convert it to a flattened list of all pairs of coordinates for the vertices `*`, first for all `*-*` and then also for all `*|*`: ``` €` # Flatten it one level down # (implicitly reverses the values of each row, but we'll fix this later) ʒ # Filter this list of triplets by: '*å '# Does the triplet contain "*" }€¦ # After the filter: remove all first items (the "*") of the triplets 2ô # Split this list of pairs into pairs ``` [Try just the first 3 steps online.](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM9bl3LZDq4FiCacmqWsdXloLZB5aZnR4y///CgpaurpaXAoKNUDEpaWrBaJqQKJaXFAhXS0A) Step 4: Find the first valid permutation of this list of pairs: ``` œ # Get all permutations of this list of pairs of coordinates .Δ # Find the first which is truthy for: ðý # Join each inner-most coordinate with a space delimiter to a string # (necessary because 05AB1E lacks a contains for pairs) © # Store this in variable `®` (without popping) À # Rotate it once towards the right ` # Pop and push all pairs of strings separated to the stack å # Check for both values inside the top pair of strings whether they're in # the pair below it θ # Only keep the last truthy/falsey check of this ® # Push list `®` again ü # For each overlapping pair of pairs of strings: å # Check for the values in the second pair if they're in the first pair O # Sum each pair of truthy/falsey values P # Take the product, to check whether just one in each was truthy * # Check that both checks were truthy } # Close the find-first ``` [Try just the first 4 steps online.](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM9bl3LZDq4FiCacmqWsdXloLZB5aZnR4y9HJeuemHN5weO@hlYcbEg4vPbfj0LrDew4v9Q/Qqv3/X0FBS1dXi0tBoQaIuLR0tUBUDUhUiwsqpKsFAA) Format it to the intended output: ``` €` # Flatten it one level down (in reversed order again) Ù # Uniquify this list of pairs Ć # Enclose; append its own head # (after which the resulting list of pairs is output implicitly as result) ``` [Try the entire program online.](https://tio.run/##yy9OTMpM/V/zqGlN8P9zW/1CgThCM9bl3LZDq4FiCacmqWsdXloLZB5aZnR4y9HJeuemHN5weO@hlYcbEg4vPbfj0LrDew4v9Q/QAqlJODzzSNv//woKWrq6WlwKCjVAxKWlqwWiakCiWlxQIV0tAA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` n⁶ŒṪŒ!ạƝ§$ÞḢfœẹ”*$ṭ@Ṃ$’ ``` [Try it online!](https://tio.run/##y0rNyan8/z/vUeO2o5Me7lx1dJLiw10Lj809tFzl8LyHOxalHZ38cNfORw1ztVQe7lzr8HBnk8qjhpn///@PVlLQ0tVSAAIlHSWFGoUaEAUSUdJRUFKAAqVYAA "Jelly – Try It Online") This is a monadic link that accepts an array of lines as input and produces a 2D array (which the interpreter prints in the correct format) as output. The solution always starts with the first non-space character, which must be an asterisk. Note that this solution is very slow, so the only valid input that will terminate within a minute on TIO is a 3x3 square. However, this program should work for any input where the non-space characters form a Hamiltonian cycle and the first non-space is an asterisk. ## Explanation List all permutations of the non-space characters' coordinates: `ŒṪ` and `Œ!` order their results lexicographically (according to the input's order in `Œ!`'s case), so this step's output is ordered lexicographically. ``` n # Not equal ⁶ # " " ŒṪ # Multidimensional indices of truthy values Œ! # Permutations (ordered lexicographically according to the input) ``` Find the valid permutation starting with the first non-space character: Listing all permutations and then finding a valid one is a similar idea to step 4 in [@KevinCruijssen's answer](https://codegolf.stackexchange.com/a/256274/60693), although the details are very different. Consider the list of Manhattan distances of adjacent elements of a permutation. (The Manhattan distance from (a, b) to (c, d) is |a-b| + |c-d|). No coordinate is repeated, so each distance is positive. Thus, the lexicographically minimum possible distance list is [1, 1, ..., 1]. This distance list means two adjacent points in the permutation have distance 1, so this permutation is valid or reverse-valid (i.e. the counterclockwise version of a valid permutation). Thus, sorting the permutations by their distance lists puts all of the (reverse-)valid permutations at the beginning. `Þ` is implemented using Python's `sorted` function, which is guaranteed to be stable, so among the (reverse-)valid permutations, the lexicographically minimum one still comes first. This will be one that starts with the first two non-space characters in order. These characters are the first and second non-space characters on the top row (excluding space-only rows), so the first permutation must be clockwise, making it valid. ``` ạƝ§$ÞḢ ạ # Absolute-value difference Ɲ # Apply to each adjacent pair § # Sum $ # Group ạƝ§ as a monad Þ # Sort Ḣ # First item ``` Filter non-asterisk coordinates: ``` fœẹ”*$ f # Filter œẹ # Multidimensional indices of ”* # "*" $ # Group œẹ”* as a monad ``` Repeat the first coordinate (which is also the minimum coordinate in lexicographic order) and switch to 0-based indexing: ``` ṭ@Ṃ$’ ṭ # Tack @ # Transpose arguments Ṃ # Minimum $ # Group ṭ@Ṃ as a monad ’ # Decrement ``` [Answer] # [jq](https://stedolan.github.io/jq/) -Rn, 166 bytes ``` [inputs|explode]|[tostream|select(.[1]>32)] |reduce keys[]as$k(.;.[$k]as[[$y,$x]]|.[$k+1:] |=sort_by(.[0]|hypot(.[0]-$y;.[1]-$x)))+.[:1] |map(select(.[1]<45)[0]|reverse) ``` (newlines added for ~~readability~~ aesthetic pleasure) [Try it online!](https://tio.run/##TU1BTsMwELznFT74ELs4IgUuLfQRXK0VCulKlLSxsd0qlvbtGNvpAWk1M5qZ3f3@SUmfZnsNnnCxZ3NEIB2MDw6HC3k84xjaTvdweNoKIIfH64hswug1DJ5PbbfvNJ@y1prHB74AUDE2/Q7ozRsXPj5jPvAI9BWtCVUqHvflpuKLEGLT6V0PdBls@@/f6/OLKFsOb@g8ipQYk0rJhjHK00glC2W9UslqI1ckq3bFe1b8zHJdWNOm@iv8GhtOZvZJvc/jHw "jq – Try It Online") ### Explanation: ``` [ inputs # read each input line as raw string | explode # make them an array of ascii codes ] # collect line arrays into row array | [ tostream # convert items into path and value | select(.[1] > 32) # only keep non-empty cell values ] # collect them into a cell array | reduce keys[] as $k (. # iterate over pivot cell indices ; .[$k] as [ [$y,$x] ] # destructure pivot cell into coords | .[$k+1:] |= sort_by(.[0] # sort remaining slice of cells wrt | hypot(.[0]-$y; .[1]-$x) # Euclidean distance to pivot cell ) # (hor or ver adjacency always wins) ) + .[:1] # repeat the initial cell at the end | map( # prepare some cell items for output select(.[1] < 45)[0] # only keep paths of vertex cells | reverse # turn row/col path into x/y coords ) ``` [Answer] # [Python 3](https://docs.python.org/3/), 244 233 bytes Different approach, actually works ``` def g(a,o=[]): b=c=(0,0) while[b]!=o[1:2]:x,y=b;s=[(q,r)for q,r in((x+1,y),(x,y+1),(x-1,y),(x,y-1))if(len(a)>r>=0<=q<len(a[r])and a[r][q]or' ')in'-|*'and (q,r)!=c];o=a[y][x]=="*"and o+[(x,y)]or o;c=b;b=s and s[0]or(x+1,y) print(o) ``` [Try it online!](https://tio.run/##lVLBjoIwEL33K0YutLUksHtTxx/p9gCISmJaBZOVxH9nZ1gksImHbQ8zffPeMO3j2t3PwX/2/aE6wknmJqB1aiOgwBJlalIl4PtcXypbuBUGm20@3OZhOiy2LVp5M406hgYoQu2lfKwz0ykjibHOOCbTOcmUqo/yUnmZq32zx3SHt91wtI1TuT8AJ/bmQhNDrGofJ08dMz58ZoWl2wbMbefswyFGOuJaWFvurkgFYVvSXAW2wJXWpgSOIwm4NrW/y6D6Mm@rFhCssCLSSaK/fGRE9AR4/mYT5sw7CmULGObiZKmfU4k2Y@plv3eD/K/PLGf@oHrJNIyz/mExYzHAuOZ30q97CUdbsOv8kmT7EFv6Zxi71H7CCBqfnVEDFbmCcUxmnCTXJ1cI638A "Python 3 – Try It Online") ### Ungolfed ``` def g(a,o=[]): b=c=(0,0) # set starting point b and previous point c to (0,0) while[b]!=o[1:2]: # continue until we have passed the first point a second time x,y=b; s=[ (q,r) for q,r in ( (x+1,y), # east point (x,y+1), # south point (x-1,y), # west point (x,y-1) # north point ) if ( len(a)>r>=0 # point is in y bounds of array and len(a[r])>q>=0 # point is in x bounds of row and a[r][q] # then character at point or ' ' # else ' ' ) in '-|*' # only include points where the character is "*", "-", or "|"; and (q,r)!=c # exclude the point we just came from ]; o=a[y][x]=="*"and o+[(x,y)]or o; # if the current character is "*", add to output list c=b; # set previous point (c) to current point b=s and s[0]or(x+1,y) # if we found "*", "-", or "|", move to that point; else, stay in row and move forward one place on the x-axis print(o) # return the output list ``` ]
[Question] [ ## Introduction: Pete likes doing word search puzzles. Despite that, he has trouble searching for words vertically, (anti-)diagonally, or reversed. Because of that, he'll always search for the words left-to-right, and rotates the entire puzzle in increments of 45 degrees clockwise. In addition to that, he'll also always search for the words in (alphabetical) order. ## Challenge: Given a word search grid and a list of (alphabetically ordered) words, output how many rotations are necessary to find all the words. ### Brief explanation of what a word search is: In a [word search](https://en.wikipedia.org/wiki/Word_search) you'll be given a grid of letters and a list of words. The idea is to cross off the words from the list in the grid. The words can be in eight different directions: horizontally from left-to-right or right-to-left; vertically from top-to-bottom or bottom-to-top; diagonally from the topleft-to-bottomright or bottomright-to-topleft; or anti-diagonally from the topright-to-bottomleft or bottomleft-to-topright. **For example:** ``` Grid: ABCD EFGH IJKL MNOP Words: AFK BCD FC PONM ``` Here, the first string `AFK` can be found diagonally from the topleft-to-bottomright; the second word `BCD` horizontally from the left-to-right; etc.: ``` AFK BCD FC PONM aBCD Abcd ABcD ABCD EfGH EFGH EfGH EFGH IJkL IJKL IJKL IJKL MNOP MNOP MNOP mnop ``` ## Challenge example: If we take the same example grid and list of words above, we find `AFK` after 7 clockwise rotations of 45 degrees; `BCD` after 1 more rotation; `FC` after 1 more rotation; and `PONM` after 3 more rotations. So the result for the example grid and four words will be `12` (7+1+1+3). Here a visual representation of these steps: ``` A M P D E B N I L O C H ABCD I F C MIEA O J E PONM H K N DHLP B G L EFGH → M J G D → NJFB → P K F A → LKJI → D G J M → CGKO → A F K P ⮌ IJKL N K H OKGC L G B HGFE C F I BFJN E J O MNOP O L PLHD H C DCBA B E AEIM I N P D A M 1 2 3 4 5 6 7 A F K BCD 8 9 F C 10 11 12 PONM ``` ## Challenge rules: * Input can be in any reasonable format. The input-grid could be a character-matrix; list/stream of lines; taken from STDIN; etc. The same applies to the list of words. * The inputs are guaranteed to only contain regular letters (in the same casing, unless you prefer otherwise). * You're allowed to take the inputs in uppercase; lowercase; mixed case; or even as 0- or 1-based alphabet indices as integers if you'd want. * You can assume the input-words will always be in alphabetical order. * You can assume the words will always be present in the grid, and will only occur once. * All words are guaranteed to have at least two letters (because single-letter words could be found in multiple directions, adding annoying edge cases). * You can assume neither the grid nor list of words will be empty. * No need to deal with the remaining letters or partial overlapping of word. Just look for the words one at a time and output the amount of 45 degree clockwise rotations that are necessary. * The grid will not necessarily be a square, but it's guaranteed to be a rectangle. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the 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 (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: ABCD EFGH IJKL MNOP AFK BCD FC PONM Output: 12 ``` ``` Inputs: ABC AB ABC BC Output: 0 ``` ``` Inputs: AB BA Output: 4 ``` ``` Inputs: WVERTICALL ROOAFFLSAB ACRILIATOA NDODKONWDC DRKESOODDK OEEPZEGLIW MSIIHOAERA ALRKRRIRER KODIDEDRCD HELWSLEUTH BACKWARD DIAGONAL FIND HORIZONTAL RANDOM SEEK SLEUTH VERTICAL WIKIPEDIA WORDSEARCH Output: 39 ``` [Answer] # JavaScript (ES6), 149 bytes Expects `(m)(a)`, where `m` is a matrix of characters and `a` is a list of lists of characters. ``` m=>a=>a.map(w=>t+=m.some((r,y)=>r.some((_,x)=>j=~[..."21036785"].findIndex(d=>w.every((c,i)=>(m[y+~-(d/3)*i]||0)[x+d%3*i-i]==c))))*n-(n=j)&7,t=n=0)|t ``` [Try it online!](https://tio.run/##lVBda8IwFH33V4iwkWjt3GRzLxFik2rW2pTUraCUIbaOim1FxQ8Q/7orbo7bjTEW8nIO9557zpmNN@PVZBkv1vU0C6PTlJwS0h7nX0/GC7Ql7XWNJPoqSyKEltoek/byE71quxzNyHGk63rl7rbRfGg93lcCfRqnoUjDaIdC0t7q0SZa7hGaaHE@jpLRvnaso/CmiatxcDg08GhXC6@a1bgeB4RMcP6qaR2lZIavW9qapKSBD@vTJEtX2TzS59kbmqJRqVw@n6Udg1UC7QK52e0BKJ4sG8C@I91KUAow2DctMFAUMw0AXOn0z7u4VPrVy3fxDhDInRYu/VesQ//Y8F@4GgiD2jCykpKapu0VrRhK2IIOJAWkwySzpOMzaJMpi3tSMgZbkpy7Q961hQ@79YToScoV1KS2spQSiitAWpIJxpkqdN3jtu/Z/HnQ@xHbsHyq4CwTtCsdCmOawimoSSWG0hkUZhTNI/YB4XEOY13OfxGXPgHlC0u4PDcAOamYx6kyPqzj0zs "JavaScript (Node.js) – Try It Online") ### How? For each word \$w\$, we look for a starting position \$(x,y)\$ and a direction \$d\$ from the string `"21036785"` for which the word is matched along the following vector: $$(dx,\:dy)=((d\bmod3)-1,\:\lfloor d/3\rfloor-1)$$ Hence the following directions for each \$d\$: $$\begin{matrix}0&1&2\\3&&5\\6&7&8\end{matrix}$$ We define \$j\$ as the ones' complement of the index of \$d\$ in the string, which gives: $$\begin{matrix}-3&-2&-1\\-4&&-8\\-5&-6&-7\end{matrix}$$ (NB: We use the ones' complement so that the inner `some()` is not triggered when `findIndex()` returns \$-1\$.) Given the previous orientation \$n\$ (starting with \$n=0\$), the number of 45° clockwise turns that are needed to reach the new orientation is: $$(n-j)\operatorname{AND}7$$ We add the result of the above expression to the accumulator \$t\$ and update \$n\$ to \$j\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26 22~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! (Use the outer-product quick, `þ` rather thank `€Ɱ`.) ``` ŒdU$ŒḌƭƬw€þ§T€F’ŻI%8S ``` A dyadic Link accepting the Wordsearch on the left and the sorted word-list on the right that yields an integer. **[Try it online!](https://tio.run/##NY8/TkMxDMb3HiOCrQdgdWO/PitpXDkpkYrYYEHdEVvVmakbJ2ApOxISA@j1HvQi4SVVJ/vnP58/Pz1uNi@lDPuH1dWw//t8PX4cD8@n3eH3@@c9jbE7bd@GL76@iaWUO5NvSRNb8N5MpkZFoOt8hFklsMqeIQlUCijoJGS0lVAdRRFEV0mIlmuae86VFpG5FyBte@DVqbKSVnKCjIRqsVJPPkdPq9Sbyf3oZgbWZdDWQ4a5BGi@Og7neVFeS0jnqsLoaVGzSNR8XLSm5vJWzTM7XtKo10AUI4HaevIf "Jelly – Try It Online")** ### How? This would need tweaking to handle multiple instances of a word in the Wordsearch (would need to account for multiple results in the result of `T€`) but luckily, we don't need to handle that. ``` ŒdU$ŒḌƭƬw€þ§T€F’ŻI%8S - Link: Wordsearch grid, G; word-list W Ƭ - collect input (initially G) while distinct applying: ƭ - alternating calls to: $ - ...1: last two links as a monad: Œd - anti-diagonals U - reverse each ŒḌ - ...2: reconstruct from forward-diagonals þ - table - i.e. [[f(o,w) for o in orientations] for w in W]: w€ - first index of w in each row of o § - sums (sum each of the orientation results) T€ - truthy (1-indexed) indices of each F - flatten ’ - decrement Ż - prepend a zero I - forward differences %8 - modulo eight S - sum ``` [Answer] # [Python 3](https://docs.python.org/3.9/), ~~265~~ 260 bytes -5 thanks to KevinCruijssen ## Golfed code ``` def f(G,W): r=0;f=range;g=len for w in W: while any(w in l for l in G)<1:r+=1;m=g(G[0]);H,G=G[:],["".join(G[j][i-j]for j in f(max(i-m+1,0),min(i+1,g(G))))[::-1]for i in f(g(G)+m-1)]if r%2 else["".join(H[~j][i]for j in f(g(H)))for i in f(g(H[0]))] return r ``` [Try it online!](https://tio.run/##VU/RboIwFH3nKxqSJW3ERbY3HA@VVmhAaoobiYQHk4HWABrm4nzZr7te3JatT@ece8/pucfLaXfoHq/X16pGNQ6dnHgW6v3JtPb7Tbetplu/qToL1YcenZHuUG7m6LzTTYU23QUPWjOMG4AheXK9fuS709bf4rCYlGQaOaEfFl7pFLZ9vz/ozuj7stDjfQm@Pfhq3G4@sB63I9eZEKc1S9pAE0HMKzxv7A7L@rYM@qgdu6TUNervHlDVvFW/8VHxCfl/07c4Mjn/EiIoR0pzbnV67zvUX4@97k64xha27PyFq5UIaJLYjmUrKel8nmR0BowGSiSCriQFljLJYpnmLADGVMwzKRmLgUnOl2seJiIHtsiEiCTlavDRRMVKCcUVsFgywThTAQMW8STPEv68imyLONBnRoM4p2qYMkFDmdKh2VykN4dUYi3T1U1V1LRaAMo4H5p8pxn0cxjgXMRiyU3eQKRiGacqgE8tQq5f) ## Formatted and commented code ``` def find_rotations(grid, words): rotations = 0 for word in words: while not any(word in line for line in grid): rotations += 1 if rotations % 2 == 1: # If rotations is odd, rotate rectangular grid by 45deg old_grid = grid[:] # Keep a copy of the old grid new_grid = [] # for i in range(len(grid) + len(grid[0]) - 1): # new_line = "" # for j in range( # max(i - len(grid[0]) + 1, 0), # Equivalent to first list comprehension min(i + 1, len(grid)) # Rotates rectangular grid by 45deg ): # new_line += grid[j][i-j] # new_grid.append(new_line[::-1]) # grid = new_grid[:] # else: # If rotations is even, rotate copy of old rectangular grid by 90deg # (Much easier than rotating diamond-shaped grid by 45deg) new_grid = [] # for i in range(len(old_grid[0])): # new_line = "" # Equivalent to second list comprehension for j in range(len(old_grid)): # Rotates rectangular grid by 90deg new_line += old_grid[~j][i] # (Rotates old_grid because that is the last rectangluar grid) new_grid.append(new_line) # grid = new_grid[:] # return rotations ``` [Answer] # Python 3, 406 bytes ``` R=range L=len e=lambda b:'\n'.join(map(''.join,b)) r=lambda b,x,y:[b[x][y]]+(r(b,x-1,y+1)if x and y<L(b[0])-1 else[]) def s(b,c=1): t=[[i[::-1]for i in zip(*b)],[[i]for i in b[0]]][L(b)==1] yield[r(b,i,0)for i in R(L(b))]+[r(b,L(b)-1,i)for i in R(1,L(b[0]))]if c%2 else t yield from s([t,b][c%2],c+1) o=lambda b,w:w!=[]and w[0]in b and 1+o(b,w[1:]) g=lambda b,w,u:1+g(next(u),w[o(e(b),w):],u)if w else-1 ``` [Try it online!](https://tio.run/##fVPRbtowFH2ev8KrNMUppqqhD1O0PJjElCwhRoYNqZ41kRJYJpqgJCiwn2d2YLRat76Yy7nn3HtOZG8P9Y8i73/clsejcMtFvk5B5G7SHKTuZvGULBcwcaxvuXXzs8hy9LTYIutU48S2QXkh4T0@ODKReyUPSnVQiTTUJfjQIXa2gnu4yJfw8ClCibxVdpfAdFOlUtlgma5gpcmPLrEdAGtXykw6TpeoVVHCDGY5/JVt0XViK6xbz6gZpJTUE23XJQrAQ5ZultIszvCtfeEJZCi26rQtU2tb2cs@wWdbttJWHz/0WnOwPo@Eq7J40h5ljRMldVvhR50KFM/hG6d570plMjZ6kHHXBiadQu9sJHF00vULPt45pLNGebqv0c7WjAKl2hlubEfhnfliTWuiS45JsSiX7tXVFR14PmDD@xEIPocRGMd8olHQ9smZcAF60CDzr0zMAo9GERCc0@EwmtIBoJ4IooDOOAWxz/2Qx3PfA74I2ZRz3w8BZ2zywO6jYA7G0yAYccoEBTQSoRCBYAKE3A985gttaMSi@TRiX2ajy@6@WQ3owJwNgS6UFh2GFoaWTmB@hp45JzweWwo0vRNjYDAd4cQzjb4rrQH1wjkVrcwP6D2PadSOCOIWG3ERPPB4dkIF1YHGppoy1m48WTPVn09h6nkQBhOm57V/uPCnjApvZJbetW4GVNfmatbF9zYTqvTtfFem9a7Mobw2D2GTVTWGq2xTpyWKizzFsLqptpusRubF2Po6gcrEr9BlSnvqh7Mts7xG678bGDYE/4P/XwUxkt5rCXlD0zeau9ea/huantH0X2t6RnP8DQ) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes ``` WS⊞υι≔⟦⟧ηWS⊞ηιυF⁸FLυFLθ«JλκUMη⎇⁼μ⪫KDLμ✳ιωιμ»⎚IΣEη﹪⁻ι∧κ§η⊖κ⁸ ``` [Try it online!](https://tio.run/##fU7JbqQwED2nvsJHW2LukXJybHfawWBkmEFKlAPqdhqrwXQAZ9Fovp0xWZVLLn5@VfWWXduMu6HpluWpdZ1FWPpTmMt5dP6ACUFFmFocEuTIBdBpcgePb@8S1Eb6g6B9ExRxOOMQf/fDiPA5Qa@orD/M0ZV85w@R/4Wz69CfqgF3CTpG4VnWnNjQ943fr66VHX0zvmDxEJpuwn2CrgfncWHtkbvR7mY3@A@/niToa@hIpE/r4xLUk2j9D1hnmxF/FmXNNOMy9DhmrmHZsA/dgDPnw4SjisYOxwiz9Hv7vF5wuxttb/1s44aQ1f18BXKxLPUfYSrJqFJgtKabjSrpJVBmpJK00hRyrnmq85oz4CYVpdacp6CFKG7ElZI1ZKWUW02FoUCVSY2RRhhINZdccMM4bIWqSyV@V1uAS8rSmhoOXNIrnVMFG5nHE23kjc6ryA2NiRmUQqTwrvqoCLVMZSGiFGpteCmoYVtYfj12/wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Read in the grid. ``` ≔⟦⟧ηWS⊞ηι ``` Read in the words. ``` υ ``` Output the grid. ``` F⁸ ``` Loop over each direction. ``` FLυFLθ«Jλκ ``` Loop over each cell. ``` UMη ``` Looping over each word... ``` ⎇⁼μ⪫KDLμ✳ιωιμ ``` ... if it matches the word in the current direction starting from the current cell, replace it with the current direction. ``` »⎚IΣEη﹪⁻ι∧κ§η⊖κ⁸ ``` Pairwise subtract the directions, reduce them all modulo `8`, and output the sum. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 206 bytes ``` f=lambda n,k,N=0,E=enumerate:k and f(n,k[(A:=any(any(all(-1<(Y:=r+(R:=[0,*[-K]*3,0,K,K,K])[N%8])<len(n)>-1<(Z:=c+R[N%8-2])<len(_)!=C==n[Y][Z]for K,C in E(k[0]))for c,H in E(_))for r,_ in E(n))):],N+1-A)or N ``` [Try it online!](https://tio.run/##ZVFdj9owEHzfX5E@VIkhVFzv5RRdKpnYgOsQI4c2OtIo4o7kGhFMFIIqfj21gRaqyrK1M7Mf1mxz7H7u1ONT055OpV@vtq/rlaXcjRv5Q5f6hTpsi3bVFd7GWqm1VTpaSx3s@St1dM63rp3Bw7Pz4vlt35Genw7dXjrgWe/RHbrcnAyl0cenDD3XhXIU@mLSl57/1peGH3y@Kjn64Ae@r9KXLF1m5a61uBtYlbKos0mHGUKGenOnFyq/4NbNL1ghhLzMjfoPA4y0EJ3WRWmVedMWXXd0toe6q@pKFfl7W61d64Z/7dr1HnlgNW2lOqd00rRnhMwy/U1kBvxb/2nf1FXn2D@UjbL/mt2rCAG8Vu95pZpDt7d8y7ZtPAoI0PFkCuwrD2EWiTkAHnMw/DiAuYhmoJmRvuYdXcEI6yD5TuWCBTgMQQqBx@Mw1hoOJAsZXggMERGEiyghARDJaSwEIRwEpfMlnYQsgVnM2FRgKnXzUHIpmaQSuCCMUCL1F6Y0TOKQfltMzcyAJ1gSIAxPRIRDGLNIpwjJliJaaCyxnjiDmFIO16o/X4SEcTanuhQSIUlMsQym2oCbQebY2qKzPXld7c8epfV9ho0umzBruFmZARj2VmjkuzZ6oX@X37vx6PQb "Python 3.8 (pre-release) – Try It Online") Recursive solution. ## Explanation Initialize `N`, the number of rotations. Set it to 0. At each iteration, we attempt to identify the first word in `k`, the list of words to find, by going through every cell in the grid and pointing in the direction that `N` corresponds to. For instance, if `N` is 0, meaning the grid is not rotated at all, we go 0 rows down and 1 column to the right, `len(k[0])` times at each cell. If such a word is identified, then we delete the first element and recall `f` with `n`, the now smaller `k`, and the same `N`. `N` does not change, because there might still be words in the same orientation. If no such word is identified, then no deletion is done and instead we recall `f` with `n`, the same `k`, and an incremented `N`. Eventually, `k` will be empty, and in such a case, we return `N`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 158 bytes ``` f=lambda G,L,*H:L>[]and 1-(d:=L[0]in" ".join(map("".join,G)))+f(d*G or[*zip(*((x:=H)or[(x:=x+s)+g+s*len(G)for g in G])[::-1])],L[d:],*[G*(H==()),H][d]) s=" ", ``` [Try it online!](https://tio.run/##TVFRa9swEH6/XyHyYslxy8pehsEFxZJlTYoV5LSGuqKkeMk8XMfEGbT986mcZbSIO@4@3Xd3fDe8HX/v@@8/hsPptE26zctzs0Ei0lGYx/q2dpu@QTdXuIkTXX9zbT9Ds@s/@7bHL5sBz/7FkSCEzLe4CQXaH@rwvR1wiPFrnOTE51PwOh/JfDcfw@5XjwXZ7g9oh9oeCUfqOL66ccRFum5iF4W1CHGeJJiQKHd14wiMiZ8aneC53T21/fD3OKIEBUFAFykDnokc5E@lYVmYFQDNFEx4lsLKFEvwyMLb5BeXZEF9UN1zu5Yp1RqsMTTLdOn/aGqllnRtKBTMMGWKiqXArOKlMYwpMJyvHrjQsoJlKWVuKLe@ubbKWmm5BWWYZJxZv0LOdVVqfrfOp5mpqqhlwCQVpqAaMln4EmPlgynWPrfUT1xCybmCC@v/ilBJJVfcU6EylpWc2jT3AlyPQ9cecfDYTy8gAGd5nrp2PGtUd18rAoIm3btJ908pHcCE@pNP@Bd@DEgkl2Oenbg088d2gIZD2x/xFnviJ376AA "Python 3.8 (pre-release) – Try It Online") Takes a sequence of tuples of characters for the grid and a sequence of strings for the search list. Test harness nicked from @ophact. ### How? More or less does actually rotate the grid and then searches in normal row major order. 90° rotations are implemented as up down flip followed by transpose (aka `zip`). If we first shear by prepending a linearly (w.r.t. line number) increasing amount of white space and then do the same 90° rotation we get essentially the same lines as we would have doing a 45° rotation. The main "loop" is recursion. `G` is the current grid `L` the leftover word list and `H` alternates between being empty and a backup of `G` because every 90° rotation must be based not on the current `G` but its predecessor. [Answer] # JavaScript, 144 bytes ``` f=(a,b,d=0,[w,...r]=b)=>w?a.some((r,y)=>r.some((c,x)=>w.every((p,i)=>p==a[d%4?d<4?y-i:y+i:y]?.[x+i-'00122210'[d]*i])))?f(a,r,d):f(a,b,-~d%8)+1:0 ``` [Try it online!](https://tio.run/##ZVLRcppAFH2/X7EvGdmKDNo8tKTE2cAatyDrrLbMxDgTApjSMcIAiTpJ@ut2QYw2fWB3795zzj33sr@D56AI8yQrO6s0ine7hakE6r0ambo6W6uapuVz8x6bl@t@oBXpY6woubqVcd5Eobqpslr8HOdbRcnURIaZKVVm0dl5P/p23t92EmPblt/89VXHs0076bR0vdvr9bp6axbNPyVzjHF/IQvnaoSNRe2g8yc6@4LbXUPflXFRhkERF8hEd8BW2VNZGECuLBvo4HoI7LvjwsjjYwAycKC6H1gw5t4IgD@VEm6gbg9OmRJ5Ve/V8YDRTyEAV@SYOj@m/J9UTJlFXBcE52QwcCeVliWYy8iUE/Bsbjvc820LbOHQCee27QCndHxDr13mw2jC2JATKggQVzhCMEEFONxmNrWFdD@krj9x6Y/psHJhOT4RNtiMXHOPuDBgnoRwwW64N5WxILLiCCaUOtCwDhbBZw4bU0kFnwt7QomwhseuPn@FO63Mk0cFa0W2TEql1XTZwtoiWZZxrmyQeYk2WHsMMiWrzi@AUJiuihLNkgqsorSWm8u/k31Qawq18MWR9JAnkYrWaR4VFaXW@EC7Xd2u9pw8Lp/yVV0ToYpp1OsR2No7CytnM/lcwzlWa3BdwNhv/8k3rPWBtT6w4k0Wh3Iy7X1P1eXbBbxJL/D@CrVFmtMg/KUoL@ikGbUhozf875j2UrLVhXICfx9Juoy1ZfqgHGCm2QgdBHFtYPcX "JavaScript (Node.js) – Try It Online") TIO is 147 bytes as `?.` syntax is not available on it. Input grid as 2d character array. Input words as an array of array of characters. Output a number. `f(grid: string[][], words: string[][]) -> number` ]
[Question] [ Related: [Boustrophedonise](https://codegolf.stackexchange.com/q/150117/78410), [Output the Euler Numbers](https://codegolf.stackexchange.com/q/107558/78410) (Maybe a new golfing opportunity?) ## Background Boustrophedon transform ([OEIS Wiki](https://oeis.org/wiki/Boustrophedon_transform)) is a kind of transformation on integer sequences. Given a sequence \$a\_n\$, a triangular grid of numbers \$T\_{n,k}\$ is formed through the following procedure, generating each row of numbers in the back-and-forth manner: $$ \swarrow \color{red}{T\_{0,0}} = a\_0\\ \color{red}{T\_{1,0}} = a\_1 \rightarrow \color{red}{T\_{1,1}} = T\_{1,0}+T\_{0,0} \searrow \\ \swarrow \color{red}{T\_{2,2}} = T\_{1,0}+T\_{2,1} \leftarrow \color{red}{T\_{2,1}} = T\_{1,1}+T\_{2,0} \leftarrow \color{red}{T\_{2,0}} = a\_2 \\ \color{red}{T\_{3,0}} = a\_3 \rightarrow \color{red}{T\_{3,1}} = T\_{3,0} + T\_{2,2} \rightarrow \color{red}{T\_{3,2}} = T\_{3,1} + T\_{2,1} \rightarrow \color{red}{T\_{3,3}} = T\_{3,2} + T\_{2,0} \\ \cdots $$ In short, \$T\_{n,k}\$ is defined via the following recurrence relation: $$ \begin{align} T\_{n,0} &= a\_n \\ T\_{n,k} &= T\_{n,k-1} + T\_{n-1,n-k} \quad \text{if} \; 0<k\le n \end{align} $$ Then the Boustrophedon transform \$b\_n\$ of the input sequence \$a\_n\$ is defined as \$b\_n = T\_{n,n}\$. More information (explicit formula of coefficients and a PARI/gp program) can be found in the OEIS Wiki page linked above. ## Task Given a finite integer sequence, compute its Boustrophedon transform. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` [10] -> [10] [0, 1, 2, 3, 4] -> [0, 1, 4, 12, 36] [0, 1, -1, 2, -3, 5, -8] -> [0, 1, 1, 2, 7, 15, 78] [1, -1, 1, -1, 1, -1, 1, -1] -> [1, 0, 0, 1, 0, 5, 10, 61] ``` Brownie points for beating or matching my 10 bytes in ngn/k or 7 bytes in Jelly. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 7 bytes ``` ;Uĵ\Ṫ€ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCI7VcOEwrVcXOG5quKCrCIsIiIsIiIsWyJbMCwgMSwgLTEsIDIsIC0zLCA1LCAtOF0iXV0=) Given the previous row, we can reverse it, append it to the next element in the source list, and cumulatively sum. (Reverse + append-to is the same as append + reverse) Therefore: ``` ;Uĵ\Ṫ€ Main Link \ Cumulatively reduce the source list; each time, with the last row as the left and the next element as the right: ; Append the element to the last row U Reverse the whole thing Ä Cumulative sum Ṫ€ Get the last element of each ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~47~~ ~~42~~ 41 bytes ``` f:{i{$[y;o[x;y-1]+o[x-1;x-y];a x]}'i:!#a:x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qOrNaJbrSOj@6wrpS1zBWG8jQNbSu0K2MtU5UqIitVc@0UlROtKqo/Z8WbaBgqGCkYKxgEvsfAA "K (oK) – Try It Online") A function taking an array of numbers. -5 thanks to ngn. -1 thanks to Razetime. ``` { // A function returning... { // A function, returning $[ // A switch statemnet y; // If y (second arg) is nonzero o[x;y-1]+o[x-1;x-y]; // Do a recursive call a x // Else index x into a ] }'i: // Call with the first argument as both arguments '!#a:x} // Map this over a range of the same length as the input, which we also assign to a for later use ``` [Answer] # JavaScript (ES6), 56 bytes ``` a=>a.map(g=(k,n,x)=>x?g(n,n):k?g(k-1,n)+g(n-k,n-1):a[n]) ``` [Try it online!](https://tio.run/##dcrNCsIwEATgu0@RYxZ3S@MPSCH1QUoPS22Dpm6KFenbxwU9ST3NMPPd@MVz97hOT5J06fPgM/uaiztPNngbUXABXy/nYAUFqqglktO61YX0JwcVN9JC7pLMaeyLMQU72MaVLcDmZyzRODQ7NHs0h78/fQwpOmqcVuBXrYTi/AY "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` a=>a.map((_,i)=>(T=(n,k)=>k?T(n,k-1)+T(n-1,n-k):a[n])(i,i)) ``` [Try it online!](https://tio.run/##FcpNDkAwEEDh68zEVBQrSbmEnYhM/KXKVBDXr9p9yXsbv3yPlz0fJX6aw2ICm5rTg0@AgSyaGloDQi7KNe0vpTGJUJpEOay4kx7BxhfD6OX2@5zufoUFuow05VRQ2cf2AQ "JavaScript (Node.js) – Try It Online") Copying the formula described in the question. ``` a => a.map( // Map a (_, i) => // By index, we don't care about the content of a, just that it's the right length ( T = (n, k) => // Declare a function T, taking n and k k ? // If k is nonzero... T(n, k - 1) + T(n - 1, n - k) // Do a recursive call : a[n] // Else index n into a )(i, i)) // Call this function with i,i as arguments. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ’1ŀ_+1ŀ’}¥ð‘ị³ðṛ? J’Ç€ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw0zDow3x2kACyKw9tPTwhkcNMx7u7j60@fCGhztn23N5AcUPtz9qWvP///9oAx0FQx0FIx0FYx0Fk1gA "Jelly – Try It Online") Horrible recursive definition, I'm sure there's a better approach. Full program. [Here](https://tio.run/##y0rNyan8//9Rw0zDow3x2kACyKw9tPTwhkcNMx7u7j607vCGhztn23N5AcUPtz9qWvP/0M5DKw@3H530cOcMzcj//6MNDWJ1FKINdBQMdRSMdBSMdRRMEAK6EEFdoKgpkLIAyUCFsVCxAA)'s a modified version to run as a test suite. ## How it works We just implement $$T(n,k) = \begin{cases} a\_n & \text{if } k = 0 \\ T(n-1,n-k) + T(n, k-1) & \text{otherwise} \end{cases}$$ then calculate \$T(i,i)\$ for each index \$i\$ of \$a\$ The first line defines \$T(n,k)\$, and the second calculates \$T(i,i)\$ for each index \$i\$. ``` ’1ŀ_+1ŀ’}¥ð‘ị³ðṛ? - Helper link. T(n,k). ṛ? - If k: ð - Then: ’ - n-1 _ - n-k 1ŀ - T(n-1, n-k) ¥ - Last two links as a dyad g(n,k): ’} - k-1 1ŀ - T(n, k-1) + - T(n-1, n-k) + T(n, k-1) ð - Else: ‘ - n+1 (due to Jelly's 1 indexing) ị³ - Index into a J’Ç€ - Main link. Takes a on the left J - Indices of a ’ - Decrement to 0 index € - Over each index i: Ç - Yield T(i,i) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` FA«⊞υιUMυΣ…⮌υ⊕λI✂υ±¹ ``` [Try it online!](https://tio.run/##JYy9CsIwFEbn9inueAMRrLo5ZuqgFDuWDiG9mkB@SpoURHz22OI3Hs75lJZRBWlLeYYI2Po5J2QMPnXV5UVj5mDYta5uchbBOemnHfXZoXgrS0KHGR@0UlwIM@PQehXJkU80oWXbtraLxicUcknYW6Nof7jTSybC5q98SxmGI4eGw4nDmcNlHMthtT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FA« ``` Loop over the input list. ``` ⊞υι ``` Push the current input value to the Boustrophedon list. ``` UMυΣ…⮌υ⊕λ ``` Take the sums of all the nontrivial suffixes of the list to produce the new list. ``` I✂υ±¹ ``` Output the last member of the new list on its own line. [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->l{l.size.times.map &g=->n,k=n{k<1?l[n]:g[n,k-1]+g[n-1,n-k]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevOLMqVa8kMze1WC83sUBBLd1W1y5PJ9s2rzrbxtA@Jzov1io9GiigaxirDWToGurk6WbH1tb@L1BIi4420DHUMdIx1jGJjf0PAA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Å»ª.sO}€θ ``` Port of [*@hyper-neutrino♦*'s Jelly answer](https://codegolf.stackexchange.com/a/233517/52210), so make sure to upvote him! [Try it online](https://tio.run/##yy9OTMpM/f//cOuh3YdW6RX71z5qWnNux///0QY6hjq6hjpGOrrGOqY6uhaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w62Hdh9apVfsX/uoac25Hf91/kdHGxrE6kQb6BjqGOkY65hA2bogrq6xjqmOrgVQCCyASsTGAgA). **Explanation:** ``` Å» # Cumulative left-reduce the (implicit) input-list by: ª # Appending the current item to the list .s # Get the suffices of this list O # Sum each inner list together }€θ # After the reduce, only leave the last element of each inner list # (after which the list is output implicitly as result) ``` ]
[Question] [ The primorial \$p\_n\#\$ is the product of the first \$n\$ primes. The sequence begins \$2, 6, 30, 210, 2310\$. A [Fortunate number](https://en.wikipedia.org/wiki/Fortunate_number), \$F\_n\$, is the smallest integer \$m > 1\$ such that \$p\_n\# + m\$ is prime. For example \$F\_7 = 19\$ as: $$p\_7\# = 2\times3\times5\times7\times11\times13\times17 = 510510$$ Adding each number between \$2\$ and \$18\$ to \$510510\$ all yield composite numbers. However, \$510510 + 19 = 510529\$ which is prime. Let us generalise this to integer sequences beyond primes however. Let \$\Pi(S,n)\$ represent the product of the first \$n\$ elements of some infinite sequence \$S\$. All elements of \$S\$ are natural numbers (not including zero) and no element is repeated. \$S\$ is guaranteed to be strictly increasing. In this case, \$p\_n\# = \Pi(\mathbb P,n)\$. We can then define a new type of numbers, generalised Fortunate numbers, \$F(S,n)\$ as the smallest integer \$m > 1\$ such that \$\Pi(S,n) + m \in S\$. You are to take an integer \$n\$ and an infinite sequence of positive integers \$S\$ and output \$F(S,n)\$. You may take input in any reasonable representation of an infinite sequence. That includes, but is not limited to: * An infinite list, if your language is capable of handling those (e.g. Haskell) * A [black box function](https://codegolf.meta.stackexchange.com/a/13706/66833) which returns the next element of the sequence each time it is queried * A black box function which returns two distinct values to indict whether it's argument is a member of that sequence or not * A black box function which takes an integer \$x\$ and returns the \$x\$th element of the sequence If you have another method you are considering using, please ask in the comments about it's validity. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ## Examples I'll walk through a couple of examples, then present a list of test cases below. **\$n = 5, S = \{1, 2, 6, 24, 120, ...\}\$** Here, \$S\$ is the [factorials](https://en.wikipedia.org/wiki/Factorial) from 1. First, \$\Pi(S, 5) = 1\times2\times6\times24\times120 = 34560\$. We then find the next factorial greater than \$34560\$, which is \$8! = 40320\$ and subtract the two to get \$m = 40320 - 34560 = 5760\$. **\$n = 3, S = \{6, 28, 496, 8128, ...\}\$** Here, \$S\$ is the set of [perfect numbers](https://en.wikipedia.org/wiki/Perfect_number). First, \$\Pi(S, 3) = 6\times28\times496 = 83328\$. The next perfect number is \$33550336\$, so \$m = 33550336 - 83328 = 33467008\$ ## Test cases ``` n S F(S, n) 5 {1,2,6,24,120,...} (factorials) 5760 3 {6,28,496,8128,...} (perfect numbers) 33467008 7 {2,3,5,7,11,...} (prime numbers) 19 5 {1,3,6,10,15,...} (triangular numbers) 75 Any n {1,2,3,4,...} (positive integers) 2 9 {1,4,9,16,25,...} (squares) 725761 13 {4,6,9,10,14,...} (semiprimes) 23 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ḟ>1M<¹Π↑ ``` [Try it online!](https://tio.run/##yygtzv5v9aipMffcAj9TEOPIhgJziMBiiICfCUT40bSFlod3/H@4Y76doa/NoZ3nFjxqm/j/PwA "Husk – Try It Online") (Missing the testcase for perfect numbers because it was too slow, and the one for semiprimes because implementing the list of semiprimes is a challenge itself) Takes as input `S` and `n`, where `S` is an infinite list. ### Explanation ``` ḟ>1M<¹Π↑ ↑ Take the first n elements from S Π and get their product M ¹ For each element x in S < subtract the product if it is smaller than x, return 0 if it is bigger ḟ Find the first element in this list >1 that is greater than 1 ``` [Answer] ## [JavaScript (V8)](https://v8.dev), 70 bytes ``` n=>s=>{p=[...Array(n)].reduce(a=>a*s(),1);while((x=s()-p)<1);return x} ``` Can't access TIO on my school network. I'll post a link soon! [Answer] # Scala, 83 bytes ``` s=>n=>{val p=s.take(n).product;Stream.from(2)find(m=>s takeWhile(p+m>=_)toSet p+m)} ``` [Try it in Scastie!](https://scastie.scala-lang.org/QJqQgNCZTtSOP4c25kAKsg) Takes an infinite `LazyList`. If outputting the product + m had been allowed, I could've used a few evil syntax-bending tricks for 71 bytes, but this is a lot more boring. ``` s=>Stream.from(2)map s.take(_).product.+find(? =>s takeWhile?.>=toSet?) ``` [Try it in Scastie!](https://scastie.scala-lang.org/eFQwND4XSFmyeWvDXR6cHg) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 47 bytes ``` (S,x=1)=>f=n=>n?f(n-1,x*=S()):(t=S()-x)>0?t:f() ``` [Try it online!](https://tio.run/##bY3BDoIwEETvfMkuFEKtEKTZEi7cCUdjDEGqGNIaaQx/X@vdw2Tm8F7mOX7GbXovL5cae5t9Rx4GthNHUpoMKdNoMClne0wDINbgfp3uqPLG1RrQy6glLvuQaLJms@ucrfYOHVxJtTH1SYJQIMoocOeSHSp2PJWs4mEIURS5EOXln5ptj0W78Aki2P4L "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 51 bytes non-recursive ``` S=>n=>{for(x=1;e=S(),e<=(x*=n--<1||e););return e-x} ``` [Try it online!](https://tio.run/##bYvBCoJAFADvfkXH93RXsk0x1id48S4eI0JqLUN2Y7UQsm/f9gM6DMxh5tG9u@lih@fMtbkqV5NrqdRUfnpjYaFEKmoBmSoIlpA050WyrgolSqvml9UbxZevk0Hl08YTXIyezKji0dyghjOVVUhNFCGkiDLw3TFju5ztDxnLEy9CpOlWiOz0b42n@9DPgAjC3@4H "JavaScript (Node.js) – Try It Online") [Answer] # [Clojure](https://clojure.org/), 58 bytes ``` #(nth(for[i % j[(- i(apply *(take %2%)))]:when(< 1 j)]j)0) ``` [Try it online!](https://tio.run/##VY/BasMwEETv/oqBYFi5BJpCD036J0IH1V47cpWVI69T8vWu4kJpr/MGZl4b07hkXqnjHv26I9Ez9SnbgBqjpT0C@WmKdzSk/pNRv9TGGHf8OrPQOw4YjRvNs1lNRV2a@QprBYrBwVYnTGkOGm6MIMoD57myb7j4CaFj0aB3h9Kar4vP/Mt21JT12mys962mHHws@BWZu6XVkGRG4wrVQmRYos@Q5fKxDfxrPbnK4RhZYdsUI6hcAwXl7PXxqsWh6LiKplwuRsGPpuDRNuZP3m8RpOiv3w "Clojure – Try It Online") Takes input as a lazy sequence and a number \$n\$. [Answer] # [J](http://jsoftware.com/), 36 bytes ``` 1 :'([(-~u)>:@]^:(>:u)^:_)~[:*/u@i.' ``` [Try it online!](https://tio.run/##JYxNC4JAEIbv@yumLrqh29q66zqgSEGn6NBVKqRWsuiDSAgC/7qNNTAw7zMzz7kfC6@GDMGDACQgdShgsVkt@wjQ80s/7FqeY7HdoZ9jy3e4512Jk2lbNMLrOVvPBVyri4PmBTJsbkf3dkdWV4dXJmBU5Mjc4XQHnRgJGQwcatBvRvVwz5qOfBPMbBCnJrARDUppLZWipG1qTSq14Z9u@9coFZtESkuq4ZtUilS/VZQOEAklrP8C "J – Try It Online") This is an adverb modifying the sequence generator, which is assumed to be 0-indexed and which returns the nth element. It just increments the input n until f(n) > relevant product to find the number to subtract from. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` £P-.Δ1› ``` First input is \$n\$, second input is an infinite sequence \$S\$. [Verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KOOeUUxemEuEf8PLQ7Q1Ts3xfBRw67/tTr/o6OV0hKTS/KLMhNzipV0lBSVdExjdRSilQpSi9JSk0sU8kpzk1KLQFKnJrkcnnhohX9grZKOEURNUWZuKoqKAqCcOViuBGhiXnppTmIRigILLbvDrYc21cKtyS/OLMksS1XIzCtJTYeoUtIxNABLFheWJhalgoTylHQsIUKpuZlgayHGHZ6UbgM0yyQ2FgA) or [try it online with 05AB1E code as additional input to generate the infinite sequence](https://tio.run/##ASIA3f9vc2FiaWX/4oiewrIuVkTCuf/Co1AtLs6UMeKAuv//NQoh). (The perfect numbers and semiprimes test cases have been lowered to \$n=2\$ and \$n=4\$ respectively, because they time out for \$n=3\$ and \$n=13\$ on TIO.) **Explanation:** ``` £ # Leave the first (implicit) input `n` amount of leading items from the second # infinite input-list `S` P # Take the product of these first `n` values - # Subtract it from each item in the second infinite input-list `S` .Δ # Pop and leave the first value which is truthy for: 1› # Check that it's larger than 1 # (after which the result is output implicitly) ``` ]
[Question] [ The incenter of a triangle is the intersection of the triangle's angle bisectors. This is somewhat complicated, but the coordinate formula for incenter is pretty simple ([reference](https://www.mathopenref.com/coordincenter.html)). The specifics of the formula do not matter much for this challenge. The formula requires lengths of sides, so it can be very messy for most triangles with integer coordinates because lengths of sides tend to be square roots. For example, the incenter of the triangle with vertices `(0,1)`, `(2,3)`, and `(1,5)` is `((2√2+2√17)/(2√2+√5+√17),(10√2+√5+3√17)/(2√2+√5+√17))` (yuck). A triangle with integer coordinates can have an incenter with rational coordinates in only two cases: 1. the side lengths of the triangle are all integers 2. the side lengths of the triangle are `a√d`, `b√d`, and `c√d` for integers `a`, `b`, `c`, and `d` (equivalent for `d=1`). (Meeting at least one of these two conditions is necessary to having a rational incenter, and the former is sufficient. I am not sure if the second case is sufficient) # Challenge Given a triangle OAB, it meets the "friendly incenter" condition if all of the following are true: 1. points `A` and `B` have nonnegative integer coordinates, 2. If `O` is the origin, the distances `OA`, `OB`, and `AB` are either: * all integers or * integers multiplied by the square root of the same integer (`a√d`, `b√d`, and `c√d` as described in the intro). 3. The triangle is not degenerate (it has positive area, i.e. the three vertices are not collinear) Based on wording from the [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") tag, your program may * Given some index n, return the n-th entry of the sequence. * Given some index n, return all entries up to the n-th one in the sequence. * Without taking any index, return an (infinite) lazy list or generator that represents the whole sequence. But what is the sequence? Since it would be too arbitrary to impose an ordering on a set of triangles, the sequence is the infinite set of all triangles that meet the "friendly incenter" condition. You may order these triangles however you wish, for example: * in increasing order of the sum of coordinates * in increasing order of distance from the origin This sequence must include every "friendly incenter" triangle once and once only. To be specific: * Every triangle must have finite index in the sequence * Two triangles are the same if one can be reflected over the line `y=x` to reach the other, or the points `A` and `B` are the same but swapped. For example, the triangle with vertices `(0,0)`, `(32, 24)`, and `(27, 36)` must be included at some point in the sequence. If this is included as `A(32,24) B(27,36)`, then the following triangles cannot be included because they duplicate that included triangle: * `A(24,32) B(36,27)` * `A(27,36) B(32,24)` * `A(36,27) B(24,32)` # Example Output: If a program opts to output the first `n` triangles and is given `n=10`, it may output: ``` (0,0),(0,4),(3,4) (0,0),(3,0),(3,4) (0,0),(3,0),(0,4) (0,0),(4,3),(0,6) (0,0),(4,4),(1,7) (0,0),(7,1),(1,7) (0,0),(1,7),(8,8) (0,0),(0,8),(6,8) (0,0),(6,0),(6,8) (0,0),(3,4),(0,8) ``` Of course, the output format is flexible. For example, the `(0,0)` coordinates may be excluded, or you may output complex numbers (Gaussian Integers) instead of coordinate pairs. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~232~~ 229 bytes Prints the results as \$X\_A,Y\_A,X\_B,Y\_B\$. ``` n=>{for(o=[0,1,2,k=3];n;)for(z=++k**4;o[A=[x,y,X,Y]=o.map(i=>~~(z/k**i)%k)]|o[[y,x,Y,X]]|o[[X,Y,x,y]]|o[[Y,X,y,x]]|Y*x==X*y|(g=d=>!d||[p,q=X*X+Y*Y,p+q-2*(x*X+y*Y)].some(v=>(v/d)**.5%1)*g(d-1))(p=x*x+y*y)?--z:o[print(A),A]=--n;);} ``` [Try it online!](https://tio.run/##JY9BboMwEEXP0kWkGTMmgTZSVTRU3ALL8gKVElEU7JAI2YTm6tRtl@/p/cX/aubm@jH17ibn163jbeTy3tkJLOsDZZTTwM@mGAv8lQsnySDES2F1xdpToJqUYZueGwc9l48HLPsY9Lgb0KxW60CeFNXmD2IcMfxDtHHvIyjhmWsRVjhxy@VTu67a0SWqOlFCkUsuMhfgIwah0KRXe/6EmUuY9y0KkR53GYoTtDJDBMde@BgGfJdyebPaTf14gwqpMixlfFJ8bx3kR9x@AA "JavaScript (V8) – Try It Online") ### Commented ``` n => { // n = input for( // outer loop: o = [0, 1, 2, k = 3]; // o = [0, 1, 2, 3], re-used as an object to store // the coordinates that were already tried // k = counter n; // loop until n = 0 ) for( // inner loop: z = ++k ** 4; // increment k; start with z = k ** 4 o[ A = [x, y, X, Y] = // build the next tuple A = [x, y, X, Y] o.map(i => // we try all tuples such that: ~~(z / k ** i) // 0 ≤ x < k, 0 ≤ y < k, 0 ≤ X < k, 0 ≤ Y < k % k // ) // ] | // if [x, y, X, Y] was already tried o[[y, x, Y, X]] | // or [y, x, Y, X] was already tried o[[X, Y, x, y]] | // or [X, Y, x, y] was already tried o[[Y, X, y, x]] | // or [Y, X, y, x] was already tried Y * x == X * y | // or (0, 0), (x, y) and (X, Y) are co-linear ( g = d => // or g returns a truthy value: !d || // stop if d = 0 [ // compute the squared distances: p, // OA² = p = x² + y² (computed below) q = X * X + Y * Y, // OB² = q = X² + Y² p + q - 2 * // AB² = (X - x)² + (Y - y)² = p + q - 2(xX + yY) (x * X + y * Y) // ].some(v => // test whether there's any v in the above list (v / d) ** .5 % 1 // such that sqrt(v / d) is not an integer ) * g(d - 1) // and that this holds for d - 1 )(p = x * x + y * y) ? // initial call to g with d = p; if truthy: --z // decrement z : // else: o[print(A), A] = --n; // print A, set o[A] and decrement n ); // } // ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞<€Ðæ4ùÙεœÙ}€`2δôʒnOy`αnOª¬Lδ/tøεεDïQ}P}ày`R*Ë≠*}4ô€н ``` Outputs the infinite sequence of \$[[x\_A,y\_A],[x\_B,y\_B]]\$, although in a different order than the challenge description. [Try it online.](https://tio.run/##AV8AoP9vc2FiaWX//@KInjzigqzDkMOmNMO5w5nOtcWTw5l94oKsYDLOtMO0ypJuT3lgzrFuT8KqwqxMzrQvdMO4zrXOtUTDr1F9UH3DoHlgUirDi@KJoCp9NMO04oKs0L3//w) (Extremely slow, so will only output the first five triangles before timing out after 60 seconds on TIO.) **Explanation:** ``` ∞< # Push an infinite list non-negative list: [0,1,2,3,4,...] €Ð # Repeat each item three times: [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,...] æ # Take the powerset of this infinite list 4ù # And only keep sublists of length 4: # [[0,0,0,1],[0,0,0,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],...] Ù # Uniquify this list of sublists: # [[0,0,0,1],[0,0,1,1],[0,1,1,1],[0,0,0,2],[0,0,1,2],...] ε # Map each sublist to: œ # Get all permutations of the current list Ù # And uniquify it }€` # After the map: flatten it one level down: # [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1],[1,1,0,0],...] δ # Map over each sublist again 2 ô # And split it into parts of size 2 # [[[1,0],[0,0]],[[0,1],[0,0]],[[0,0],[1,0]],[[0,0],[0,1]],...] ``` We now have an infinite list of triangles in all four permutations of the \$A\$ and \$B\$ coordinates ([try `∞<€Ðæ4ùÙεœÙ}€`2δô` loose](https://tio.run/##ASoA1f9vc2FiaWX//@KInjzigqzDkMOmNMO5w5nOtcWTw5l94oKsYDLOtMO0//8)). Minor pet peeve: If the cartesian product builtin would have sorted in the same order as the powerset for infinite lists instead of `[[[0,0],[0,0]], [[0,0],[0,1]], [[0,0],[0,2]], [[0,0],[0,3]], ...]`, this entire first part could have been [`∞<ãÙãÙ`](https://tio.run/##yy9OTMpM/f//Ucc8m8OLD88E4f//AQ) instead.. :/ Now we keep all valid triangles: ``` ʒ # Filter this list of triangles [[a,b],[c,d]] by: n # Square all inner values: [[a²,b²],[c²,d²]] O # Sum each inner list: [a²+b²,c²+d²] y # Push the original triangle [[a,b],[c,d]] again ` # Pop and push both values separated to the stack α # Take the absolute difference between the coordinates: [|a-c|,|b-d|] n # Square the inner values: [|a-c|²,|b-d|²] O # Sum it: |a-c|²+|b-d|² ª # And append it to the earlier list: [a²+b²,c²+d²,|a-c|²+|b-d|²] # (let's call this list [OA²,OB²,AB²] for now) ¬ # Push the first item OA² (without popping the list) L # Pop and push a list in the range [1,OA²] δ/ # Divide the values in both lists double-vectorized: # [[OA²/1,OB²/1,AB²/1], # [OA²/2,OB²/2,AB²/2], # ..., # [OA²/OA²,OB²/OA²,AB²/OA²]] t # Take the square root of each inner value: # [[sqrt(OA²/1),sqrt(OB²/1),sqrt(AB²/1)], # [sqrt(OA²/2),sqrt(OB²/2),sqrt(AB²/2)], # ..., # [sqrt(OA²/OA²),sqrt(OB²/OA²),sqrt(AB²/OA²)]] ø # Zip/transpose; swapping rows/columns: # [[sqrt(OA²/1),sqrt(OA²/2),...,sqrt(OA²/OA²)], # [sqrt(OB²/1),sqrt(OB²/2),...,sqrt(OB²/OA²)], # [sqrt(AB²/1),sqrt(AB²/2),...,sqrt(AB²/OA²)]] ε # Map each inner list to: ε # Map each number to: D # Duplicate the number ï # Cast the copy to an integer Q # And check if it's still the same as before the cast # (which means this number is an integer) }P # After inner map: check if all are truthy (by taking the product) }à # After the outer map: check if any are truthy (by taking the maximum) y # Push the original triangle [[a,b],[c,d]] again ` # Pop and push both values separated to the stack R # Reverse the second list ([c,d] to [d,c]) * # Multiply the coordinates: [a*d,b*c] Ë≠ # Check that both are NOT the same: a*d != b*c * # Check if both checks were truthy ``` And since we've included all four permutations of the triangle coordinates in the infinite list, we fix this after the filter: ``` }4ô # After the filter: split the infinite lists into parts of size 4 # (which are all four the same triangles, but in different permutations) €н # And only leave a single triangle of each quartet (the first) # (after which the infinite list is output implicitly as result) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 42 bytes ``` foË(fεṁC2gpṁ□)S:Fz-foV≠Fz/fo§=←▲S+m↔m½π4ΘN ``` [Try it online!](https://tio.run/##AU0Asv9odXNr/@KGkTjigoH/Zm/DiyhmzrXhuYFDMmdw4bmB4pahKVM6RnotZm9W4omgRnovZm/Cpz3ihpDilrJTK23ihpRtwr3PgDTOmE7//w "Husk – Try It Online") This is an infinite list of point pairs `[[xA,yA],[xB,yB]]`. For some reason TIO refuses to print an initial segment before running out of time, so the link cuts it after 8 elements (the 9th would take too long). # Explanation First we generate all point pairs. ``` m½π4ΘN N Infinite list of positive integers: [1,2,3..] Θ Prepend zero: [0,1,2,3..] π4 Cartesian 4th power: [[0,0,0,0],[0,0,0,1],[1,0,0,0]..] m½ Split each in half: [[[0,0],[0,0]],[[0,0],[0,1]],[[1,0],[0,0]]..] ``` Next we discard duplicates. This is done by creating the list of equivalent point pairs and checking that the current one is the lexicographic maximum. ``` fo§=←▲S+m↔ fo Filter by condition: m↔ Reverse each: [[yA,xA],[yB,xB]] S+ Concatenate with the current point pair: [[xA,yA],[xB,yB],[yA,xA],[yB,xB]] ▲ The maximum of this list of 4 points ← and its first element [xA,yA] §= are equal. ``` Then we remove degenerate triangles by dividing B element-wise by A and checking that the results are distinct. Husk handles division so that this works out: * Dividing by a nonzero integer gives a rational number by default. * Dividing a positive number by zero gives infinity. * Dividing a negative number by zero gives negative infinity. * Dividing zero by zero gives a special value "Any", which is equal to every finite number, but not equal to the infinities. ``` foV≠Fz/ fo Filter by condition: F Fold by z/ element-wise division: [xB/xA,yB/yA] V≠ This list contains an unequal pair. ``` Finally, we verify the friendly incenter condition. This is done by computing the squares of the three sides, dividing out square factors and checking that the results are equal. ``` foË(...)S:Fz- fo Filter by condition: F Fold by z- element-wise subtraction S: and prepend to the point pair: [[xB-xA,yB-yA],[xA,yA],[xB,yB]] Ë(...) The results of ... are equal for these three points. fεṁC2gpṁ□ Compute (a value corresponding to) d from a point (x,y) of magnitude n√d ṁ Map and sum □ square: x²+y² p Prime factors, say [2,2,2,2,2,3,5,5] g Group equal adjacent elements: [[2,2,2,2,2],[3],[5,5]] ṁ Map and concatenate C2 splitting into chunks of length 2: [[2,2],[2,2],[2],[3],[5,5]] fε Keep singletons: [[2],[3]] ``` ]
[Question] [ ## Task Given a matrix of numbers \$M\$ with \$r\$ rows and \$c\$ columns, and the magnification factor \$n\$, build the matrix with \$rn\$ rows and \$cn\$ columns where the original elements are spaced \$n\$ units apart and the gaps are filled by piecewise linear interpolation: $$ \begin{bmatrix} a\_{11} & a\_{12} & \cdots \\ a\_{21} & a\_{22} & \cdots \\ \vdots & \vdots & \ddots \\ \end{bmatrix} \Rightarrow \begin{bmatrix} a\_{11} & \frac{(n-1)a\_{11} + a\_{12}}{n} & \cdots & a\_{12} & \cdots \\ \frac{(n-1)a\_{11} + a\_{21}}{n} & \frac{(n-1) \frac{(n-1)a\_{11} + a\_{21}}{n} + \frac{(n-1)a\_{12} + a\_{22}}{n}}{n} & \cdots & \frac{(n-1)a\_{12} + a\_{22}}{n} & \cdots \\ \vdots & \vdots & \ddots & \vdots \\ a\_{21} & \frac{(n-1)a\_{21} + a\_{22}}{n} & \cdots & a\_{22} & \cdots \\ \vdots & \vdots & & \vdots & \ddots \\ \end{bmatrix} $$ Because the operation is toroidal, the "gaps" between the \$r\$-th row and the 1st row (resp. the \$c\$-th column and the 1st column) must also be filled, which is placed below the original elements of the \$r\$-th row (resp. on the right side of the \$c\$-th column). You can take \$M\$ and \$n\$ (and optionally \$r\$ and \$c\$) as input and output the resulting matrix in any suitable format. \$n\$ is guaranteed to be a positive integer. The input matrix and the result may have non-integers. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` # one-element matrix M = [[1]], n = 3 [[1, 1, 1], [1, 1, 1], [1, 1, 1]] # one-element matrix, large n M = [[1]], n = 100 (100-by-100 matrix of ones) # one-row matrix M = [[0, 6, 3, 6]], n = 3 [[0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2], [0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2], [0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2]] # one-column matrix M = [[0], [6], [3], [6]], n = 3 (transpose of the above) # n = 1 M = [[1, 9, 8, 3], [5, 4, 2, 7], [3, 8, 5, 1]], n = 1 (same as M) # 2-by-2 matrix; here the result is rounded to 2 decimal places for convenience. # An answer doesn't need to round them, though one may choose to do so. M = [[0, 9], [3, 6]], n = 3 [[0, 3, 6, 9, 6, 3], [1, 3.33, 5.67, 8, 5.67, 3.33], [2, 3.67, 5.33, 7, 5.33, 3.67], [3, 4, 5, 6, 5, 4], [2, 3.67, 5.33, 7, 5.33, 3.67], [1, 3.33, 5.67, 8, 5.67, 3.33]] # a larger test case M = [[0, 25, 0], [25, 0, 0], [0, 0, 25]], n = 5 [[0, 5, 10, 15, 20, 25, 20, 15, 10, 5, 0, 0, 0, 0, 0], [5, 8, 11, 14, 17, 20, 16, 12, 8, 4, 0, 1, 2, 3, 4], [10, 11, 12, 13, 14, 15, 12, 9, 6, 3, 0, 2, 4, 6, 8], [15, 14, 13, 12, 11, 10, 8, 6, 4, 2, 0, 3, 6, 9, 12], [20, 17, 14, 11, 8, 5, 4, 3, 2, 1, 0, 4, 8, 12, 16], [25, 20, 15, 10, 5, 0, 0, 0, 0, 0, 0, 5, 10, 15, 20], [20, 16, 12, 8, 4, 0, 1, 2, 3, 4, 5, 8, 11, 14, 17], [15, 12, 9, 6, 3, 0, 2, 4, 6, 8, 10, 11, 12, 13, 14], [10, 8, 6, 4, 2, 0, 3, 6, 9, 12, 15, 14, 13, 12, 11], [5, 4, 3, 2, 1, 0, 4, 8, 12, 16, 20, 17, 14, 11, 8], [0, 0, 0, 0, 0, 0, 5, 10, 15, 20, 25, 20, 15, 10, 5], [0, 1, 2, 3, 4, 5, 8, 11, 14, 17, 20, 16, 12, 8, 4], [0, 2, 4, 6, 8, 10, 11, 12, 13, 14, 15, 12, 9, 6, 3], [0, 3, 6, 9, 12, 15, 14, 13, 12, 11, 10, 8, 6, 4, 2], [0, 4, 8, 12, 16, 20, 17, 14, 11, 8, 5, 4, 3, 2, 1]] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~27~~ 26 bytes -1 thanks to Bubbler. Anonymous infix lambda. Takes \$n\$ as left argument and \$M\$ as right argument. ``` {⊃+⌿,(⍳⍺)⍉⍤⌽\⍣2⊂⍺/⍺⌿⍵÷⍺*2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sfdTVrP@rZr6PxqHfzo95dmo96Ox/1LnnUszfmUe9io0ddTUBBfSAGqnnUu/XwdiBTy6j2fxpQ96PePqDuR71rHvVuObTe@FHbRKC5wUHOQDLEwzP4v7FCmgJE0CvY3089OtowNladS1dXlwtDxkBHwUxHwRhI4lYSq6MQbQYijCEsqEJDDFt0FCx1FCyAxoHUmeoomOgoGOkomIO1giWAYnidYglVCrfDFIsiI6ApYDeBGVC2AZhpZArUCAA "APL (Dyalog Extended) – Try It Online") (the \$n=100\$ case run out of memory on TIO gives by default, but works offline) `{`…`}` "dfn"; `⍺` is \$n\$ and `⍵` is \$M\$  `⍺*2` \$n^2\$  `⍵÷` \$M\over n^2\$  `⍺⌿` replicate vertically so each row becomes \$n\$ copies  `⍺/` replicate horizontally so each column becomes \$n\$ copies  `⊂` enclose to work on entire matrix  `(⍳⍺)`…`⍣2` do the following twice, each time with the \$0,1…n-1\$ as left argument:   `\` outer "product" using the following tacit function instead of multiplication:    `⌽` cyclically rotate the rows by the indices    `⍤` then:     `⍉` transpose  `,` flatten  `+⌿` sum  `⊃` disclose (since the summation reduced rank from 1 to 0 by enclosing) [Answer] # [J](http://jsoftware.com/), 22 bytes ``` (1#.&|:<@[1&|.[#%~)^:2 ``` [Try it online!](https://tio.run/##y/qfpmBrpWCgAMT/NQyV9dRqrGwcog3VavSilVXrNOOsjP5rcinpKaiD1akr6CjUWimkcXGlJmfkKxgrpAG1WiroWAGZZv8B "J – Try It Online") The "blur" is separable so operate in two passes where each pass operates on the rows and transposes its results. [Answer] ## *Mathematica*, 63? I can't remember the rules regarding non-ASCII characters but it looks like they are in play. ``` ListCorrelate[##/n^2&[n-Abs[n-Range[2n-1]]],Upsample[m,n,n],1] ```  is short notation for `TensorProduct`. [Answer] # [R](https://www.r-project.org/), ~~97~~ ~~92~~ ~~91~~ 86 bytes ``` function(m,n,`[`=apply)m[1,h][1,h<-function(i)approxfun(c(i,i))(0:(n*sum(1|i)-1)/n+1)] ``` [Try it online!](https://tio.run/##fY1hC4JADIa/9yv2catJ3qmlYf@ibyIognTQnWIKBv13uzMyqIiNjb179q6baki9qR5M1avGoGbDRVYcy7a93Ehngs@5K6m3IIrssmtGK2CFihUR@gc06@ugUdwVeYK2ZiMon2rUZd@pEQXbIA5otUgV@gw7hsBWsuuQT/@A0CJfgGBIGOKZiRhCBsmwn8d4VtzPp7P4dE5eztLGr9fS3r/bkjJynoE7iWh6AA "R – Try It Online") Thanks to Giuseppe for -5 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` IE×ηLθE×ηL§θ⁰∕ΣEη∕ΣEη§§θ÷⁺ινη÷⁺λπηηη ``` [Try it online!](https://tio.run/##bYzLCsIwEEV/ZZYTGKHqQsWV6KagUNBdyCK0wQTS2DZp8e9jqxFEuprHufeUWnblQ9oYi864gEfpA15kgzdTK4@a4KzcPWhsGSOYA4eQu0o9sSXI2BQ6mcFUCq99/Rbpuc@39FPOXUi5wvYeDYEbZXoy/iFL0HwQSyMdbB8j5zwjWG0EAd8RLLdi3NYiLgb7Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` I ``` Cast the final array to string for implicit print (each row's cells print vertically and rows are double-spaced). ``` E×ηLθ ``` Loop over each row of the final array. ``` E×ηL§θ⁰ ``` Loop over each column of the final array. ``` ∕ΣEη∕ΣEη§§θ÷⁺ινη÷⁺λπηηη ``` Extract an `n`-by-`n` square from a virtual array created by a simple inflation of the original array, where the top left of the square is at the final row and column. Cyclic indexing ensures that the square wraps around toroidally. The average of the elements is then taken. [Answer] # [Python 2](https://docs.python.org/2/), 109 bytes ``` M,n=input() exec"M=[[i%n*((r*2)[i/n+1]-r[i/n])/n+r[i/n]for i in range(len(r)*n)]for r in zip(*M)];"*2 print M ``` [Try it online!](https://tio.run/##VU5BTsMwELz7FatKke00hMZpAgXlWG4RF25WDiW41FA50SoVKZ8PtmNa9TD27M7szvbn4dAZMbXdh6oopVOdmEqb/jQwTtSo2kVdSakjEzOGseBS35tl1tyhIw23xcz2HYIGbQB35lOxozIMeWy4F9AJv7pncc2b50UsSI/aDFBPNpGQn4M@KnjDk3oiAAOe3Qfg0sHd5Ss/4dllYz37ggYUaPrVacNoVKRiT6PRW0d/Fb9ZosZW9QNsX1@2iB3Oe95R7b4nKbO0aRLIiZSrNIHSIvf/tWuJLP2b//OgZda5sXj0U04rLFtbCIuHMDPrTpmzspC1uejlzQ3CWV2sDCxUq1DYrrMXfw "Python 2 – Try It Online") [Answer] # JavaScript (ES10), 170 bytes Takes input as `(m)(n)`. ``` m=>n=>(T=m=>m.map((r,y)=>r.map((v,x)=>(M[x]=M[x]||[])[y]=v),M=[])&&M)((g=m=>m.map((r,y)=>r.flatMap((v,x)=>[...Array(n)].map((_,i)=>v+(r[-~x%r.length]-v)*i/n))))(T(g(m)))) ``` [Try it online!](https://tio.run/##fU9bT4MwFH7frzgvjlPX1cEuXpJifPGNJ/eGxDQbIAuUpVTCksW/ji0gRqPy0PN9nO/SHkQtqp3Kjnouy33cJrwtuC@5j1tuQMEKcURU9ES4r3pS08YQDMIm4vY4n8OIhKeI14QG3ODpNCCI6S/@JBc6@MoIGWMPSokTShL1yheamUU9QxXO35sLxfJYpvo1mtfkMruSxHy4xRQLi1odVxo4YEFBUtDlY9bEewpHsSfAfdiVsirzmOVliomxmJquRdll/5raQhyccA81GzB6BO6ghhk4DmEm8UkLpdFGE3YoM4kOOCN8lg6xUjsnE3stDCcA4YLChsLSnNEk6kAi8iqm4H6XRdSOTT@Wn@w/i0vhlsKNEfTqNYUVBY/C9RDSLc1ft4tx/2o2MaNhbNTqzShXP5WeiRuu2sGRLTrirTv/eqzySPsB "JavaScript (Node.js) – Try It Online") (with formatted outputs for readability) ]
[Question] [ I started a CodeWars kata in Python, just two days ago, related to code golf. Task: Given two congruent circles *a* and *b* of radius *r*, return the area of their intersection rounded down to the nearest integer, in less than 128 chars. * Has to be a one-liner. * Version: Python 3.6 * External libraries: You may import NumPy as an external library. * Function name: `circleIntersection` * Input example: `circleIntersection([0,0],[0,10], 10)` This is the closest I could come (129): ``` from math import*;circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(b[0]-a[0],b[1]-a[1])/r/2)//.5 ``` [Answer] ## Use Python 2's arg unpacking: 124 bytes ``` from math import*;circleIntersection=lambda(v,w),(x,y),r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(v-x,w-y)/r/2)//.5 ``` [Try it online!](https://tio.run/##ZY05DsIwEAC/4nLXcnAcKU2AB/AGRGGcoLUUH9pYOV5vIlHSzBRTTD4KpdjV@uEURLCFhA85cZFX59nN0yOWiZfJFZ/ifbbhPVpY1YYKdnWg4oElS/gFQQPdjI2jsC4tQNiQBHOCUMpLj0BHTgXWZldbc6Bm3aHWl75m9rHA/xCerWpf6qQ5JUyLWL8 "Python 2 – Try It Online") Python 2 has parameter unpacking, allowing the input point arguments to be taken directly as pairs `(v,w)` and `(x,y)`, where the input lists like `[0,0]` and `[0,10]` will be unpacked into the respective variables. This feature was [removed in Python 3](https://www.python.org/dev/peps/pep-3113/) -- a pity, in my opinion, since the old syntax seems more readable. But, the site has a Python 2 option, and nothing in your solution relies on Python 3. [Answer] # Use `def`: 125 bytes You have a [classic dilemma](https://codegolf.stackexchange.com/q/106514/20260) of wanting to assign to a variable without losing the brevity of a `lambda` function. Your method of using an [inner lambda](https://codegolf.stackexchange.com/a/120915/20260) for assignment is one solution. The problem site not having Python 3.8 means the [walrus operator](https://codegolf.stackexchange.com/a/180284/20260) is unfortunately off limits. But, it's shorter here to just use `def` and suck up the bytes of writing out `return`. This is generically a 7-byte cost according to [this reference](https://codegolf.stackexchange.com/a/52317/20260). Within the `def`, we can just write the statement `h=` to do the assignment. We put everything on one line separated with `;` to avoid needing to indent. **125 bytes** ``` from math import* def circleIntersection(a,b,r):h=hypot(b[0]-a[0],b[1]-a[1])/r/2;return(h<1and acos(h)-h*(1-h*h)**.5)*r*r//.5 ``` [Try it online!](https://tio.run/##bc07DsMgEATQPqegZBExJpGbfA6QM1guMMZapBjQelP49IT0ad5MNVMOxpyuta6UN7E5RhG3konVaQmr8JH8O7wSB9qD55iTdHrWBDd84lEyy3nsp7Nr6Hm0v2YnMGQudwr8oSTxYV1ahPN5lwhnVNI2EJTqBlCkyJhuqIViYvnnbex1m27aFsL2APUL "Python 3 – Try It Online") (vs [original](https://tio.run/##ZY1NCsMgFISv4lLFxNiSTZoeoGcIWTxNyhPiDy9ucnprobtuvhk@GCZfBVO81/qmFFiAgsyHnKjIh/Pkjv0Vy07n7opP8XlAsBswUFbRRJIk/xmccDYQNwYunRxFh5KbBhRS9qPgeOVUuF2GtYMGZRfzbWYVmvRNaN2PNZOPhf@/8mVQbdJoWjAzCFE/)) I've changed the multiplication order from `return r*r*(...)//.5` to `return(...)*r*r//.5` to cut the space after `return`. There are likely other byte saves, including [FryAmTheEggman's switch to `numpy`](https://codegolf.stackexchange.com/a/198991/20260), but refactoring from `lambda` to `def` is already enough to get below 128 bytes. [Answer] ## Direct translation to NumPy: 127 bytes ``` from numpy import* circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and arccos(h)-h*(1-h*h)**.5)(hypot(*subtract(b,a))/r/2)//.5 ``` [Try it online!](https://tio.run/##ZY07DsIwEAV7TrHlrmXiGJQmggNwBkRhO0G2FH@0cYqc3nxER/NmNM0re/U5nVt7co6Qtlh2CLFkruLgArtlvqU68zq7GnK6LibayYCRVvLIggX@ih/9RZs0gWHn8oqejl6gfo8nIbqB0O8lVxTrZisbV9FKQ6RYnUipbmiFQ6oI/58I915C/5Bf6o/oHgiovQA "Python 3 – Try It Online") Converting your code to numpy seems to save the required bytes. While using `hypot` is still ugly, being able to splat the result of `subtract` is still enough shorter that the loss of converting to `arccos` doesn't matter. It is possible this can save more since it doesn't error on `h<1` and will return `nan` in the case that the circles do not intersect. I don't know if that is permissible though since `nan` is not equal to zero. I'm not convinced this is optimal, in particular I didn't look at improving the algorithm at all. ]
[Question] [ [Stuttering](https://en.wikipedia.org/wiki/Stuttering) is a problem which many of us might have experienced or at least seen it. Although most of famous speech recognition softwares have serious issues with stuttered speaking, let's imagine a software which understands stuttering, but cannot fix them and only writes them as is. An example written text by such a software can be like this: ***"please be ca ca careful"***. In this example ***"careful"*** is the original word and ***"ca ca"*** are the stuttered words. ## Challenge Write a program or function that fixes stuttered words by removing them from the input while keeping the original words. For example fixed version of ***"please be ca ca careful"*** would be ***"please be careful"***. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in every language wins! ## What are stuttered words? Stuttering has many different variations. But for simplicity of this challenge, we are going to limit it to the following rules: * Stuttered words can be an uncompleted part or whole of the original word. By "uncompleted part" I mean that the original word should start exactly with the stuttered word. For example ***"ope"*** and ***"open"*** both can be a stuttered word for ***"open"***, but ***"pen"*** cannot be one since ***"open"*** doesn't start with ***"pen"***. * Stuttered words must contain at least one of the ***"aeiou"*** vowels. For example ***"star"*** can be a stuttered word for ***"start"*** as it contains ***"a"***, but ***"st"*** cannot be a stuttered word as it doesn't contain any of the mentioned vowels. * Stuttered words can only appear before the original word and should be repeated at least two times to be valid (the original word doesn't count in the repeats). For example ***"o o open"*** has stuttered words but ***"o open o"*** doesn't, because the ***"o"*** after the original word doesn't count and ***"o"*** before the original word is not repeated at least two times. ***"go go go go go go"*** has five repeats of stuttered words before the original word and is valid. * A single set of repeated stuttered words cannot contain mixed forms and the words should be exactly like each other. For example ***"op o op open"*** doesn't count as stuttered words. On the other hand ***"o op op open"*** has stuttered words because the first ***"o"*** is seen as a whole different word here and the two ***"op"s*** are counted as stuttered words of ***"open"***. * In case of multiple valid sets of repeated stuttered words right after each other, only the last original word stays. For example, in ***"o o o op op op open"***, the ***"o o o"*** part is seen as stuttered words of the first ***"op"***, so they should be removed and then ***"op op op"*** is seen as stuttered words of ***"open"*** and they should be removed too, so only the ***"open"*** will be left after removal of stuttered words. You can assume that multiple valid sets of repeated stuttered words only happen from left to right, so fixing ***"op op o o o open"*** would result in ***"op op open"*** (a.k.a. we do not fix again after fixing once). ## Input * Input is a single line string containing only ASCII English letters (a-z), digits (0-9) and space characters. Letter casing is not important and you can decide to accept lowercase or uppercase or both of them, but the casing should stay the same and you cannot change it in the output. * You can use a list of letters (like `["l","i","s","t"," ","o","f"," ","l","e","t","t","e","r","s"]`) instead of the string, but you cannot use a list of words. If your language has a different input structure, use it. The point is that input shouldn't be separated by words, so cost of separating words in some languages might actually trigger other creative solutions. * The input might contain none, one or multiple stuttered words in it. * Words and or numbers are separated by a single space and input will not contain double spaces right next to each other. ## Output * A string or a list of letters or the appropriate structure in your language with all stuttered words removed from the input. * Output words should be separated by exactly one space (same as input). * Single leading and trailing newline or space are allowed. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/81663) are forbidden. ## Test cases No stuttered words: ``` "hello world" => "hello world" ``` A single instance of repeated stuttered words: ``` "ope ope ope ope open the window" => "open the window" ``` Multiple instances of repeated stuttered words: ``` "there is is is is something un un under the the the table" => "there is something under the table" ``` No stuttered words, not repeated enough: ``` "give me the the book" => "give me the the book" ``` No stuttered words, don't have any of the mentioned vowels: ``` "h h help m m m me" => "h h help m m m me" ``` Numbers aren't stuttered words, they don't have any of the mentioned vowels: ``` "my nu nu number is 9 9 9 9876" => "my number is 9 9 9 9876" ``` But a word with both vowels and numbers can have stuttered words: ``` "my wi wi windows10 is slow" => "my windows10 is slow" ``` Different forms of stuttered words in same repeat group aren't counted: ``` "this is an ant antarctica does not have" => "this is an ant antarctica does not have" ``` For multiple continuous sets of stuttered words right after each other, only keep the last original word: ``` "what a be be be beauti beauti beautiful flower" => "what a beautiful flower" ``` This isn't a case of multiple continuous sets of stuttered words right after each other: ``` "drink wat wat wa wa water" => "drink wat wat water" ``` Empty input: ``` "" => "" ``` More cases from comments: ``` "a ab abc" => "a ab abc" "a ab ab abc" => "a abc" "ab ab abc abcd" => "abc abcd" "a a ab a able" => "ab a able" "i have ave ave average" => "i have average" "my wi wi windows 10 is cra cra crap" => "my windows 10 is crap" ``` ### An easy to copy list of the above test cases: ``` "hello world", "ope ope ope ope open the window", "there is is is is something un un under the the the table", "give me the the book", "h h help m m m me", "my nu nu number is 9 9 9 9876", "my wi wi windows10 is slow", "this is an ant antarctica does not have", "what a be be be beauti beauti beautiful flower", "drink wat wat wa wa water", "", "a ab abc", "a ab ab abc", "ab ab abc abcd", "a a ab a able", "i have ave ave average", "my wi wi windows 10 is cra cra crap" ``` [Answer] ## C (gcc), ~~183~~ ~~180~~ 178 bytes ``` f(s,t,u,T,e,r)char*s,*t,*u,*r;{for(;s=index(u=s,32);T>1&strpbrk(u,"aeiou")-1<s&&memmove(s=u,t-e,r-t-~e))for(e=++s-u,r=u+strlen(t=u),T=0;(t+=e)<r&!memcmp(u,t,e-1)&t[-1]==32;++T);} ``` [Try it online!](https://tio.run/##XVDLbtswELz7K7Y@CKRFAVEC9AGF/Qn7VvRAUWuLsEgKfFgNAvfXXUqqbCXYWZCc3Z0dUBYnKW@3I/EssMgODJmjshVu59kusF1kO1e9H60jlefKNPiHRO7ZyzOtDj/LzAfX1@5MItsKVDZuaVG@@izTqLW9IPE8slAkzSIUf5HSUQh5nvsiMsdjnuY7NCTwSNmBP1Uk5Bzpq8u@JAWp@yQcGBYlzcKvovzN@ctzlecHWl1vgcw26fsGptuea9F1VpL/op7mJa02cBwJ2b@RPfN0JPoYPNmn23Wz0UIZMkoEsm0xjcNgXddsx75E2R7hUxoILcKQ/sIOS1tiHILyD3irMbTKnCCaGQ26afKeou5wETipC4J@FGtrz0uthRTY9aDnuA/pNzBxhq6Telr7Y47v376umgY1Y3Tsy6fJXrc2P1sWJiGMKZwMSgpoLHowNkArLvetQytSE9R4h4hBfTyOsYNjWoFumWqcMmcY0uicM8KjYTkFiDpBfnp/oBZizGbVONGw/lc1WYdVOnGaqtfbPw) Well, C certainly can't compete with the brevity of regex... This one's particularly tough to read because I ended up collapsing the entire function into a single nested pair of `for` loops (with no body!). That makes the evaluation order all wonky -- the code near the beginning actually executes last. My favorite trick here is `strpbrk(u,"aeiou")-1<s`. This is used to check whether the repeated word contains vowels. `u` points to the start of the repeated word, and `s` points to the second repetition of the word; for example: ``` "my nu nu number is 9 9 9 9876" ^ ^ u s ``` `strpbrk` then finds the first character in `"aeiou"` that appears after `u`. (In this case, it is the `'u'` immediately after.) Then we can check that this comes before `s` to verify the word contains a vowel. But there's a slight issue - `strpbrk` returns `NULL` (i.e. `0`) if there's no vowel in the entire string. To fix this, I simply subtract 1, which turns `0` into `0xffffffffffffffff` (on my machine) due to overflow. Being the maximum value of a pointer, this is decidedly greater than `s`, causing the check to fail. Here's a slightly older version (before the transformation that muddled up control flow) with comments: ``` f(s,t,u,c,n,e)char*s,*t,*u,*e;{ // set s to the position of the *next* check; u is the old position for(;s=index(u=s,32);) { // count the length of this word (incl. space); also fix s n=++s-u; // find the end of the string; assign temp pointer to start e=u+strlen(t=u); // count repetitions of the word for(c=0; // number of repetitions (t+=n) // advance temp pointer by length of word <e&& // check that we haven't hit the end... !strncmp(u,t,n-1)&& // ...and the word matches... t[-1]==32; // ...and the previous character was space ++c); // if so, increment count // decide whether to remove stuttering c>1&& // count must be at least 2 strpbrk(u,"aeiou")-1<s&& // word must contain a vowel // if so, move everything after the last occurrence back to the // beginning, and also reset s to u to start scanning from here again memmove(s=u,t-n,e-t+n+1); } } ``` Thanks to [@user1475369](https://codegolf.stackexchange.com/users/88943/user1475369) for 3 bytes and [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for 2 bytes. [Answer] # [Perl 5](https://www.perl.org/) (-p), 34 bytes *Based on Arnauld's deleted answer.* ``` s/(\b(\w*[aeiou]\w*) )\1+(?=\2)//g ``` [Try it online!](https://tio.run/##XY/dTsQgEIXveYq5bDWmrol/F8YHsV5AmS1kgWmALtGHt05LthvNfCecMJnhMGF0j8uSuqZXTV9uPiRamj/ZtdD2h9vm/a1/aLtuXBaDzhEUik4LmhD@KUA2CMUGTUWwjQg2XUnkMRsbRphDRWPcRnZJ5VCM9ozgr7eK6CQMcKGbwNdC4b8gzBWveBG/8Frr5flp7RZbWeOkw/0WwW3Jah4ZmLxKxiHbQYImTBAog5FnFMVI7oLCHTln@/c4zg6OvBSj0NGGExSeqapk7ggJUjHDxVz8ZmH79H6/Sovv2v2hKVsKabmbfgE "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~29~~ 28 bytes *-1 byte thanks to Kevin Cruijssen* ``` #Rγε®y¬©žMÃĀiнkĀDygαΘ+∍]R˜ðý ``` [Try it online!](https://tio.run/##XZCxTsMwEIZ3P8WpjBBElwI7YmOpBGJhcOJrYsWxK8epFaZKLCzsDLwAEkIgxFiGpJ2QIp6BFwlOrLaA7vvls3@d/csqpyHHdtDujJu35r16Lqun6nH1cVbfLOf8a5Eu5ydl3Lw297vft3dX48@H@qVetIPz4ej0cv9ir01QCAVWacGImiL8kwSTIFgumbLEtRqB51tylaFJuIyhkB6Guh/ZiIYCScxnCNn2NFQqJQm4QjGFzBeSrARZeLLQXeReOPZ1dDjqXMs9XZx8eNBHEH0yn4dKh@lEdWR4RIEpzEEqAwmdIbEJdS6EuIEWhv9dJoWAibsUNWGayxSsm/HyGOcAoUBDR7RufL/uOrHO6vfQfwLvM8AvaRpjGwRSBYJelz8) 05AB1E, having no regexes, definitely doesn't look like the best tool for this task. Still, it somehow manages to just barely beat Retina. ``` # # split on spaces R # reverse the list of words γ # group consecutive identical words together ε ] # for each group of words y: ® # push the previous word on the stack (initially -1) y # push another copy of y ¬ # push the first element without popping © # save the current word for the next loop žM # built-in constant aeiou ÃĀi ] # if the length of the intersection is non-zero: н # take the first element of y kĀ # 0 if the previous word starts with this word, 1 otherwise D # duplicate yg # length of y (the number of consecutive identical words) α # subtract the result of the startsWith check Θ # 05AB1E truthify (1 -> 1, anything else -> 0) + # add the result of the startsWith check ∍ # set the length of y to that value # otherwise leave y unchanged ˜ # flatten the modified list of groups of words R # reverse the list of words ðý # join with spaces ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` {S:g/<|w>(\S*<[aeiou]>\S*)\s$0+%%\s{}<?$0>//} ``` [Try it online!](https://tio.run/##XZBNb4MwDIbv@xUWaqd9SIVdug8xph12263SLmOHQAxEDQlKQqOq629nhqxFm/y8imPnTQwdGrke2j1cVvAMw2HzVMfpt8@u8s1N@slQ6P4ro/w6t4vkdrnM7eGYviySLI6Pg2V7WL19vL6vyF1pA1IotEPUoJQavDaSRxeR7hD@SYFrELxQXHs6QRuDIOyM1S26RqgaehXgaCbTWayQSN5a7BDauV5ovaVyAxQoO2hDjEfpK1UfaAu6jt55DPFwvw59LwLjYPYumUaRvzOGyZgi3ChmSidKBlyjBaUdNGw3PuMbRn0o8Azrnfi7VL2Eii5GQwZuhNqCJ1dQwE09ggEriHJOT7tTPoqH9lSB6d/8AA "Perl 6 – Try It Online") A simple regex answer that substitutes all matches of stutters with the empty string. [Answer] # [Stax](https://github.com/tomtheisen/stax), 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` å╬↓<▀.₧▀"╦n▐∞↨vß%ù:Qa3@=↔_ ``` [Run and debug it](https://staxlang.xyz/#p=86ce193cdf2e9edf22cb6edeec1776e125973a516133403d1d5f&i=%22hello+world%22,%0A%22ope+ope+ope+ope+open+the+window%22,%0A%22there+is+is+is+is+something+un+un+under+the+the+the+table%22,%0A%22give+me+the+the+book%22,%0A%22h+h+help+m+m+m+me%22,%0A%22my+nu+nu+number+is+9+9+9+9876%22,%0A%22my+wi+wi+windows10+is+slow%22,%0A%22this+is+an+ant+antarctica+does+not+have%22,%0A%22what+a+be+be+be+beauti+beauti+beautiful+flower%22,%0A%22drink+wat+wat+wa+wa+water%22,%0A%22%22,%0A%22a+ab+abc%22,%0A%22a+ab+ab+abc%22,%0A%22ab+ab+abc+abcd%22,%0A%22a+a+ab+a+able%22,%0A%22i+have+ave+ave+average%22&a=1&m=2) Direct port from @Grimy's perl answer. Stax is able to shrink the regex pattern literal, and it has a vowels constant which is able to shrink `[aeiou]`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 184 bytes ``` import StdEnv,Data.List,Text $s=join[' '](f(group(split[' ']s))) f[[a]:t]=[a:f t] f[h=:[a:_]:t=:[[b:_]:_]]|intersect['aeiou']a==[]=h++f t|isPrefixOf a b=f t=if(h>[a,a])[a]h++f t f[]=[] ``` [Try it online!](https://tio.run/##bVFNa9wwED1nf8WwBNYmm9Je2mbBPaWHQqCB7c0VYWxLthJZMtJ4nUB@e92xtetNStEbeebNp0elkWjH1lW9kdCitqNuO@cJ9lR9t4ftLRJ@uNOBtr/kM60uQ/botM03sBGJSmrv@i4JndE0UyFN05XKcxQ7ElmOOwUkmGiyHRsPzLKSF5P2IMSrtiR9kCUno9Su3wjMslxkzdUVJ77qcO@l0s8/FSAUGVOZVknzLcctipSbxDiuz73EuCfkuTNIkmlEWP@2a3D8Tx2Q25PXtk7ZTibictGUd@3RmQLJQGE1NNLLqHO1fHVxsW6kMQ4G50213k6E6yT8IxaokTBoW7khBtFcSIczgmslNdwMehtRST/nLYKFkTG91gd@krOrcO4pehrgI00HbTzHhPYFbB/RFlyXG97E8/XL5yVk0BHTnOHTx3kscx45DoqWQZOgL0mXCJWTAawjaPBw7Dc0SNPLyAXYk37/Ub0BxeWljzkVr/oJBk6MEkEnd7wRsGCU76w3xMmcpFqCZhLO@9PzqPBGPNby/3uAuIjS40m6NceJ8U@pDNZhvP5xN96@WGx1GY17g6Scb8fr4i8 "Clean – Try It Online") Defines `$ :: [Char] -> [Char]`, which splits the input string on spaces and groups identical elements which are then collapsed by the helper `f :: [[[Char]]] -> [[Char]]`, joining before returning. ]
[Question] [ Given a positive integer **n > 1** determine how many numbers can be made by adding integers greater than 1 whose product is **n**. For example if **n = 24** we can express **n** as a product in the following ways ``` 24 = 24 -> 24 = 24 24 = 12 * 2 -> 12 + 2 = 14 24 = 6 * 2 * 2 -> 6 + 2 + 2 = 10 24 = 6 * 4 -> 6 + 4 = 10 24 = 3 * 2 * 2 * 2 -> 3 + 2 + 2 + 2 = 9 24 = 3 * 4 * 2 -> 3 + 4 + 2 = 9 24 = 3 * 8 -> 3 + 8 = 11 ``` We can get the following numbers this way: ``` 24, 14, 11, 10, 9 ``` That is a total of 5 numbers, so our result is 5. # Task Write a program or function that takes **n** as input and returns the number of results that can be obtained this way. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better. ## OEIS sequence [OEIS A069016](https://oeis.org/A069016) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` {~×≜+}ᶜ¹ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7ru8PRHnXO0ax9um3No5///xmb/owA "Brachylog – Try It Online") ## Explanation ``` { }ᶜ¹ Count unique results of this predicate: ~× Create list of numbers whose product is the input. ≜ Label the list, forcing it to take a concrete value. + Take its sum. ``` I'm not entirely sure why `~×` only produces lists with elements above 1, but it seems to do so, which works great in this challenge. [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~9~~ ~~14~~ 13 bytes Bug fixed at the cost of 5 bytes thanks to Jonathan Allan, then 1 byte golfed. ``` ḍfḍ¦e¦Π¦¦Σ¦ul ``` [Try it online!](https://tio.run/##S0/MTPz//@GO3jQgPrQs9dCycwsOLQOSiw8tK835/9/IBAA "Gaia – Try It Online") or try as a [test suite](https://tio.run/##S0/MTPz//@GO3jQgPrQs9dCycwsOLQOSiw8tK835b2z2aEqrkYmB9qP5K6weNcyxUnjUMFe74FHbxMJH81ceWvYfAA) ### Explanation ``` ḍ Prime factors f Permutations ḍ¦ Get the partitions of each permutation e¦ Dump each list of partitions (1-level flatten the list) Π¦¦ Product of each partition Σ¦ Sum each group of products u Deduplicate l Length ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +4 bytes fixing up a bug (maybe a better way?) -1 byte by abusing symmetry ``` ÆfŒ!ŒṖ€ẎP€S€QL ``` A monadic link taking and returning positive integers **[Try it online!](https://tio.run/##y0rNyan8//9wW9rRSYpHJz3cOe1R05qHu/oCgFQwEAf6/P//39gAAA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8//9wW9rRSYpHJz3cOe1R05qHu/oCgFQwEAf6/De0DLI2NrM2MjE4uudwO1BMJQtIPGqYo6Brp/CoYW7k//8A "Jelly – Try It Online") ### How? *Updating...* ``` ÆfŒ!ŒṖ€ẎP€S€QL - Link: number, n e.g. 30 Æf - prime factors of n [2,3,5] Œ! - all permutations [[2,3,5],[2,5,3],[3,2,5],[3,5,2],[5,2,3],[5,3,2]] ŒṖ€ - all partitions for €ach [[[[2],[3],[5]],[[2],[3,5]],[[2,3],[5]],[[2,3,5]]],[[[2],[5],[3]],[[2],[5,3]],[[2,5],[3]],[[2,5,3]]],[[[3],[2],[5]],[[3],[2,5]],[[3,2],[5]],[[3,2,5]]],[[[3],[5],[2]],[[3],[5,2]],[[3,5],[2]],[[3,5,2]]],[[[5],[2],[3]],[[5],[2,3]],[[5,2],[3]],[[5,2,3]]],[[[5],[3],[2]],[[5],[3,2]],[[5,3],[2]],[[5,3,2]]]] Ẏ - tighten [[[2],[3],[5]],[[2],[3,5]],[[2,3],[5]],[[2,3,5]],[[2],[5],[3]],[[2],[5,3]],[[2,5],[3]],[[2,5,3]],[[3],[2],[5]],[[3],[2,5]],[[3,2],[5]],[[3,2,5]],[[3],[5],[2]],[[3],[5,2]],[[3,5],[2]],[[3,5,2]],[[5],[2],[3]],[[5],[2,3]],[[5,2],[3]],[[5,2,3]],[[5],[3],[2]],[[5],[3,2]],[[5,3],[2]],[[5,3,2]]] P€ - product for €ach [[30],[6,5],[10,3],[2,3,5],[30],[10,3],[6,5],[2,5,3],[30],[6,5],[15,2],[3,2,5],[30],[15,2],[6,5],[3,5,2],[30],[10,3],[15,2],[5,2,3],[30],[15,2],[10,3],[5,3,2]] - ...this abuses the symmetry saving a byte over P€€ S€ - sum €ach [30,11,13,10,30,13,11,10,30,11,17,10,30,17,11,10,30,13,17,10,30,17,13,10][10,17,11,30,10,17,13,30,10,13,11,30,10,13,17,30,10,11,13,30,10,11,17,30] Q - de-duplicate [30,11,13,10,17] L - length 5 ``` [Answer] # [Python 2](https://docs.python.org/2/index.html), 206 bytes ``` k=lambda n,i=2:n/i*[k]and[k(n,i+1),[i]+k(n/i)][n%i<1] def l(t): r=[sum(t)] for i,a in enumerate(t): for j in range(i+1,len(t)):r+=l(t[:i]+[a*t[j]]+t[i+1:j]+t[j+1:]) return r u=lambda n:len(set(l(k(n)))) ``` [Try it online!](https://tio.run/##XZFRS8MwFIWfl18RB0KzVmbTzc1gH2ROEARh@BbyEFmm6bqspOmDv77erKYGSyknJ1/Oze1tvt3X2dC@P5a1PH3sJTaZLikzcz3jRyHNnh8TsNKcZFyLFBZzTQQ31/ohF2ivDrhOHGEI25K33Qm0QPhwtlhnEmuDlelOykqnLtTE71Tet9J8qgRys1oZ2CPMpiVEcQZVuJw5XgmROg4Eq7yoQAgCdZTrLJxH3Xhj5iNa5ZI6gfsReHqr2q52Jc8zPL40fGnQReQMehH8kVlGQBGcgRyjVlHOMmKKgIFeX8QiqrUK/FjrPuQAdhelFZHObyMo3liHrLEY/XeMRp15joZGFqEFzwqE/JSavynRy4yGX0pS6ueoD3hY8@aGiquySxpvTxqrjcPT58eX1@3TFE1U3SqGf93N22633bxP@x8) ## Explanation ``` # Finds the prime factors k=lambda n,i=2:n/i*[k]and[k(n,i+1),[i]+k(n/i)][n%i<1] # Function for finding all possible numbers with some repetition def l(t): # Add the current sum r=[sum(t)] # For each number in the current factors for i,a in enumerate(t): # For all numbers further back in the current factors, find all possible numbers when we multiply together two of the factors for j in range(i+1,len(t)):r+=l(t[:i]+[a*t[j]]+t[i+1:j]+t[j+1:]) return r # Length of set for distinct elements u=lambda n:len(set(l(k(n)))) ``` [Answer] # Mathematica, 110 bytes ``` If[#==1,1,Length@Union[Tr/@Select[Array[f~Tuples~{#}&,Length[f=Rest@Divisors[s=#]]]~Flatten~1,Times@@#==s&]]]& ``` [Answer] # JavaScript (ES6) 107 bytes ``` f=(n,o,s=0,i=2,q=n/i)=>(o||(o={},o[n]=t=1),i<n?(q>(q|0)|o[e=s+i+q]||(o[e]=t+=1),f(q,o,s+i),f(n,o,s,i+1)):t) ``` **Ungolfed:** ``` f=(n, //input o, //object to hold sums s=0, //sum accumulator i=2, //start with 2 q=n/i //quotient )=>( o||(o={},o[n]=t=1), //if first call to function, initialize o[n] //t holds the number of unique sums i<n?( //we divide n by all numbers between 2 and n-1 q>(q|0)|o[e=s+i+q]||(o[e]=t+=1), //if q is integer and o[s+i+q] is uninitialized, //... make o[s+i+q] truthy and increment t f(q,o,s+i), //recurse using q and s+i f(n,o,s,i+1) //recurse using n with the next i ):t //return t ) ``` **Test cases:** ``` f=(n,o,s=0,i=2,q=n/i)=>(o||(o={},o[n]=t=1),i<n?(q>(q|0)|o[e=s+i+q]||(o[e]=t+=1),f(q,o,s+i),f(n,o,s,i+1)):t) s= []; for(i = 1; i <= 103 ; i++) { s.push(f(i)); } console.log(s.join`, `) ``` To verify that the function calculates the correct sums, we can output the keys of the object instead of `t`: ``` f=(n,o,s=0,i=2,q=n/i)=>(o||(o={},o[n]=t=1),i<n?(q>(q|0)|o[e=s+i+q]||(o[e]=t+=1),f(q,o,s+i),f(n,o,s,i+1)):Object.keys(o)) console.log(f(24)); //9, 10, 11, 14, 24 ``` [Answer] # [Python 3](https://docs.python.org/3/), 251 bytes ``` lambda n:1 if n==1else len(set(sum(z)for z in t(f(n)))) f=lambda n:[]if n==1else[[i]+f(n//i)for i in range(2,n+1)if n%i==0][0] t=lambda l:[l] if len(l)==1else[[l[0]]+r for r in t(l[1:])]+[r[:i]+[l[0]*e]+r[i+1:]for r in t(l[1:])for i,e in enumerate(r)] ``` [Try it online!](https://tio.run/##lZHdbsIgFMev5SmYyRJomyhtndqFJ2FcdHqqJIiGYrL58h20oWHuaoSQw@F3/ueD27c7X001nPnHoNvL57HFpmFYddhwzkD3gDUY0oMj/f1CHrS7WvzAymBHOmKoX6jjc6SQSaQQSuYeWq3UGKZCmG3NCUhZmJzRwL4qztdSrCVyUUY3QstQQsis6aymPSVzi4OWnUrQgjWSylxY0fhkI5KBh4TK/csfciyjgOACc7@AbR0QS@UAXzc4ODj2XLACp7uMZxntKvFMdh39M7NJgCp6JnKW2iY6m4SpIubt3WjUSa5t5Odc@6jjsbdErUpstk6g9GEXteZk5VNYmXQWuDI2UscWAisRmoaLn6Y7T7ZgtEEL/63wws9EhcviZpVxRBXLdxy5ZuklCuzP9uDurQ73gFOEgNd7pHiZVdkm22aMoV9q/xIbfgA "Python 3 – Try It Online") The design is basic: 1. factorize n into its prime factors (a prime factor may appear several times : `16 -> [2,2,2,2]`). That's the function `f`. 2. compute the partitions of the list of prime factors, and multiply the factors in each partition. The partitions are found as in <https://stackoverflow.com/a/30134039>, and the products are computed on the fly. That's the function `t`. 3. The final function gets the products of each partition of n and sums them, the get the number of different values. The result for `2310=2*3*5*7*11` is `49`. **EDIT** : Maybe needs fix, but I don't have time to look at it now (I'm in a hurry). Hint: is the result correct for `2310=2*3*5*7*11` ? I dont' think so. **EDIT2** : Huge fix. See above. Previous (buggy) version was: [Try it online!](https://tio.run/##XYtBDoIwEEXXcoouZ3QSUOOGpCdBFiW0OAkMpJREvHytZefy/ff@sofXLPc46GcczdT1Rkk9WoHVBli3CZo37fSh0KKbPRjqkEU5kIxpP7DLmNIDDSIWvXU5rL0Nm5cGKhJsLw0wSVny76FYpd4bGSzckmWn@AzZai1t/Euu9KiwLk6LZwkwACPGLw "Python 3 – Try It Online") `f` computes the factors (, with a `(0, n)` instead of `(1, n)` as first element. The lambda splits each factor in "sub-factors" and sums the those "sub-factors". ]
[Question] [ Your task is to write a program or function which: * When run for the first time, outputs its source code. * On subsequent executions, it should output what it output previously, but with one random character change (defined below). It does not have to be a uniformly random change, but every possible change should have a nonzero chance of occurring. After the first execution, your program will *not* necessarily be a quine anymore; the output will have changed (and the program is free to modify itself as well). For example, if your quine was `ABCD`, repeatedly running it might print: ``` ABCD A!CD j!CD j!CjD ``` ## Specifications * A character change is either: + The insertion of a random character, + The deletion of a random character, or + A replacement of a character with a new random character. Note that the new character is allowed to be the same as the one it replaces, in which case no change will be made.Of course, deleting or replacing a character from an empty string is not a valid change. * Despite this being tagged [quine](/questions/tagged/quine "show questions tagged 'quine'"), the rules against reading your source code do not apply. You can use any character set as long as it includes the characters used in your source code. [Answer] # [Python 3](https://docs.python.org/3/), ~~288 270 224 212 195 196 194 180 178~~168 bytes ``` f=__file__ m=open(f).read() x=m print(end=x) h=hash k=h(f) n=k%2 a=h(m)%-~len(x) x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:] open(f,'w').write(m.replace("\t",";x=%r\t"%x)) ``` [Try it online!](https://tio.run/##JY3BCoMwEAXP3c8Qglm1QvVQsORLrEjQSEQTQxpwe@mvpym9zYM3jHsHfdg2xkWM47LuahzBiMMpyxesvZIzRyBhLuD8agNXdhaEoIWWLw2b0OkGVmysAZmGQXb97Emmn0V9J4eS2yPwjbVYEBaT9olvzR1L6mVpuwH@sSo/c6xPvwbFTQq7XU6KZ8@QVdmDBPOJGCHG@AU "Python 3 – Try It Online") After printing the file source code on the first iteration, we append an extra line to set x to the new source code, rather than m. ### Explanation: ``` f=__file__ #Open and read the source code m=open(f).read() x=m #Set x to the source code for the first iteration x="..." ... x="..." #Set x to the latest iteration #On the last iteration there's a tab character to mark progress print(end=x) #Print the previous iteration's text #Modify the text h=hash k=h(f) #Generate a random number to use n=k%2 #Whether the character will be inserted or changed/deleted a=h(m)%-~len(x) #The index of the change #Add 1 to the range to append new characters, and to avoid mod by 0 in the case of an empty string x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:] #Make the change open(f,'w').write(m.replace("\t",";x=%r\t"%x)) #Modify the source code, adding the new iteration of the source code ``` Assuming `hash` returns a uniformly random number, there is about 1/6 chance of inserting a new character, 1/6 chance of changing an existing character and 2/6 chance of deleting a character. What's the remaining 2/6 chance you ask? Why, it does nothing at all 2/6 of the time! (Here's a validation program adapted from [mbomb007's answer's](https://codegolf.stackexchange.com/a/165054/76162). [Try it online!](https://tio.run/##LcoxDsMgDIXhPafwaIdUgoxIPQliYEjaRMggRCW65OrUqNn8P3/5W9@J194jPOHg/KlI054KsBToxdgJRp53LqsM0ASXwK8NI0kOEAb4b48rboyNlKGBoYg2Wo8zl4MrNGeDV8ip4klzo9nJ26vmgmLre9c/ "Python 2 – Try It Online")) [Answer] # [Python 3](https://docs.python.org/3/), ~~205~~ 195 bytes ``` s='print(end=x);h=hash;k=h(x);n=k%2;a=h(s)%-~len(x);x=x[:a]+(not(k%3)*x)*chr(k%127)+x[a+n:];open(__file__,"w").write("s=%r;x=%r;exec(s)"%(s,x))';x='s=%r;x=%r;x=x%%(s,x);exec(s)';x=x%(s,x);exec(s) ``` [Try it online!](https://tio.run/##VY3BCsIwEET/JRCSbatgexAM@ZJSQqiRlJa0JIGuF389roqIl2XnzTCz3bNfQ1dK0mKLU8jShatGUF57m7yatZekgp55qyyJBPzwWFx4UdTYX@xQy7BmOfMOKoRq9JH@U3uGGntbh8ug1o3yxtymxRnTsJ3BcY9TdpIlzSPV0HHoRipnXKYGAQRR8XNpiX@cb1C82R8q5Qk "Python 3 – Try It Online") Wanted to try a version that doesn't read the source code. Turned out not a bad as I thought, and it's only 30 or so bytes behind the [version](https://codegolf.stackexchange.com/a/165019/76162) that *does*. The explanation for how it works is mostly the same as the other answer, but it initialises x differently since it can't just read the source code. [Answer] # [Python 2](https://docs.python.org/2/), ~~779~~ 801 bytes Though the challenge was edited to show that reading your source is allowed, I was already creating my solution without that. So, to show that it's possible, I finished it. No reading of the source file: ``` s='s=%r;print s%%s\nfrom random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint\nf.write("\\n".join((s%%s).split("\\n")[1:5:2]).replace("4",`map(ord,s%%s)`))\nif L>5:exec\'b=[];h=%%d\\nwhile~-h:b+=[h%%%%1000];h/=1000\\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\\nprint"".join(map(chr,L))\'%%1\n\nn=R(0,2);p=R(0,len(L if L>5else s%%s));r=R(0,255);f.write("%%03d"*3%%(n,p,r))';print s%s from random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint f.write("\n".join((s%s).split("\n")[1:5:2]).replace("4",`map(ord,s%s)`)) if L>5:exec'b=[];h=%d\nwhile~-h:b+=[h%%1000];h/=1000\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\nprint"".join(map(chr,L))'%1 n=R(0,2);p=R(0,len(L if L>5else s%s));r=R(0,255);f.write("%03d"*3%(n,p,r)) ``` [**Try it online!**](https://tio.run/##tZHfboMgFMbvfQpjQpSWOv/UGxh7Aq96i6TTitHFIkGTbjd7dYfadl2WZkuWceMRPj6@c37qbag7GY1jT92eAk2UbuRg9wD0max0d7R1LkvzaY6q08OKpHRLKtopIb39vmpasd8j55Q7LH1KOCQ7OumNhbntn3QzCM/JMun4L10jPW/yhX6v2mZY9iELcYIjDn0tVJsfjHzroOdjrrxOl2jWP0OYyaayzQtYvIpD5haUcVJTAErjcapNivdNjYs1ZTUwKwyCwJw/0Km4KOwCa6SQpAXbxJiTwhR4E3PTEUsZVnydMrUOMUfLH9PLjsScM/kYTQFs0fbCDrnxnOfknPua4h5qjVKT1DXvZzKTku68AEWQqLlozcBSe@lidplbg0QvsiSB5DowAIK4dFYxAJ40kTWE7pVLb/2FivUJ5YbJDZJfEJmBWDc8rjjK7zC@ovgHEndBuCC0rJ8h3GVwRnAhYI3jBw "Python 2 – Try It Online") *(Note that this won't modify the source. You have to run it locally for that to work)* To show that the transformations work, here is a [test program](https://tio.run/##tZHfboMgFMbvfQpjQpSWOv/UGxh7Aq96i6TTitHFIkGTbjd7dYfadl2WZkuWceMRPj6@c37qbag7GY1jT92eAk2UbuRg9wD0max0d7R1LkvzaY6q08OKpHRLKtopIb39vmpasd8j55Q7LH1KOCQ7OumNhbntn3QzCM/JMun4L10jPW/yhX6v2mZY9iELcYIjDn0tVJsfjHzroOdjrrxOl2jWP0OYyaayzQtYvIpD5haUcVJTAErjcapNivdNjYs1ZTUwKwyCwJw/0Km4KOwCa6SQpAXbxJiTwhR4E3PTEUsZVnydMrUOMUfLH9PLjsScM/kYTQFs0fbCDrnxnOfknPua4h5qjVKT1DXvZzKTku68AEWQqLlozcBSe@lidplbg0QvsiSB5DowAIK4dFYxAJ40kTWE7pVLb/2FivUJ5YbJDZJfEJmBWDc8rjjK7zC@ovgHEndBuCC0rJ8h3GVwRnAhYI3jBw "Python 2 – Try It Online") (currently set up to always pick `100` for `r`, and it prints the result for every combination of `n` and `p` for the initial list.) --- ### Explanation: ``` s='s=%r;print s%%s...';print s%s... ``` The first line is your classic quine, but a lot longer to account for what comes after. ``` from random import*;L=4;f=open(__file__,"wa"[L>5]);R=randint ``` Import for random integers. `L` will become of list of ordinals of the source code, but initially it is an integer not used anywhere else in the source to allow for a string replacement. Open the file to write the new source. On later runs, it will open to append instead. ``` f.write("\n".join((s%s).split("\n")[1:5:2]).replace("4",`map(ord,s%s)`)) ``` Remove the first and third lines of code. Replace the `4` above with the list of ordinals. ``` if L>5:exec'b=[];h=%d\nwhile~-h:b+=[h%%1000];h/=1000\nwhile b:r,p,n=b[-3:];b=b[:-3];L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]\nprint"".join(map(chr,L))'%1 n=R(0,2);p=R(0,len(L if L>5else s%s));r=R(0,255);f.write("%03d"*3%(n,p,r)) ``` In pieces: * `if L>5:` - Skips this line on first execution. Later, `L` will be a list, and this will run. I'll explain the `exec` last, because it's not run the first time. * `n` - A random number 0-2. This determines which modification occurs (0 = insert, 1 = replace, 2 = delete). * `p` - A random position in the list that the modification will occur at. * `r` - A random number to insert or replace in the list * `f.write("%03d"*3%(n,p,r))` - Append the 3 randoms to the end of the source file. Every run, this will be adding on to an integer that encodes all the changes to the initial source that have occurred. * `exec'b=[];h=%d...'%1...` - Get the random numbers (found after `%1` on later runs), apply the changes to the list, and print. * `while~-h:b+=[h%%1000];h/=1000` - Build a list of the randoms generated so far, accounting for the leading `1`, which prevents problems with leading zeros. * `while b:r,p,n=b[-3:];b=b[:-3]` - Assign the randoms for this iteration. * `L=[L[:p]+L[p+1:],L[:p]+[r]+L[p+n:]][n<2if L else 1]` - (0 = insert, 1 = replace, 2 = delete) * `print"".join(map(chr,L))` - Print the modified source. [Answer] # Java 10, 370 bytes ``` String s;v->{if(s==null){s="String s;v->{if(s==null){s=%c%s%1$c;s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%%3<2?c:%1$c%1$c)+s.substring(r+(c%%3>0?1:0));}}";s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%3<2?c:"")+s.substring(r+(c%3>0?1:0));}} ``` [Try it online.](https://tio.run/##vZLfSsMwFMbv9xSHYiGxa21VEBcz8QEUQfBGvMiydIu2qeSkExl99pm2Y8w/24WoF@0h55yc/L58eRILET9Nn1eyEIhwLbRZDgC0ccrmQiq4aZcAi0pPQZL7Niwo87lm4H93zmozA2S@5egIboV1UOXg5gomb07FsqqN8303YICvFvF4qXOCnJu6KOgSebAZ8LUWyhDD7EAy5JjklS2FIzg8OR0iZY0qUC09JVhfLJSZuTmhzB7ya@HmiRVmWpU@IefCguTZ8RmTn2vtWKwn2BGQdGhpRGQYnlwcX8pRe3D70Wi7yfYd4/QyG6XUYzTB/9L1cEHwDdY21Yq15rzUk0JLQCecD52DpfeX9Hf@8AiC9ua2rkMJHIx67RakcxjA6yKtDM1TBlGkL7KMwXoTQJmYRJLOLrZO3b2hU2VS1S558Ye4wpDgKvdvCYJIRwH08sALNzNFkI6CfVvLBPeV17XuIW6znntYHcdjH@gu1N3jdkvI0vSjANzg74X/gvdXfMP01wj/7Ap/yNgMmtU7) ### Explanation: ``` String s; // Class-level String variable to store the modifying source code v->{ // Method without parameter nor return-type if(s==null){ // If this is the first execution of this function: s="String s;v->{if(s==null){s=%c%s%1$c;s=s.format(s,34,s);}else{int r=s.length();r*=Math.random();char c=127;c*=Math.random();s=s.substring(0,r)+(c%%3<2?c:%1$c%1$c)+s.substring(r+(c%%3>0?1:0));}}"; // Set `s` to the unformatted source-code s=s.format(s,34,s);}// And then to the formatted source-code else{ // For any following executions of this function: int r=s.length();r*=Math.random(); // Random index in range [0, length_of_modified_source_code) char c=127;c*=Math.random(); // Random ASCII character in unicode range [0, 127) s= // Replace the current String `s` with: s.substring(0,r) // The first [0, `r`) characters of the modified source code `s` +(c%3<2? // If the random option is 0 or 1: c:"") // Append the random character +s.substring(r // Append the rest of the modified source code `s`, but: +(c%3>0? // If the random option is 1 or 2: 1:0));}} // Skip the first character of this second part ``` ### General explanation: **[quine](/questions/tagged/quine "show questions tagged 'quine'")-part:** * The String `s` contains the unformatted source code. * `%s` is used to input this String into itself with the `s.format(...)`. * `%c`, `%1$c` and the `34` are used to format the double-quotes. * (`%%` is used to format the modulo-`%`). * `s.format(s,34,s)` puts it all together. [Here a basic Java quine program.](https://tio.run/##lcrBCkBAEADQX9lki0KJm3yCk6McprU0ZGlnbEm@ffkC5fzeDA7SeVi8R8PajqC0aC5iYFTCbTiIFdBELVs0U9dDfDmwgurgX5dKksxDVbUnsV6z7eBsfw@PESVFmVBc3Xfwqd4/) **Challenge part:** * `String s;` is the source code we'll modify on class-level. * `int r=s.length();r*=Math.random();` is used to select a random index of the source code in the range `[0, length_of_modified_source_code)`. * `char c=127;c*=Math.random();` is used to select a random ASCII character (including unprintables) in the unicode range `[0, 126]`. * `c%3` is used to select a random option of either 0, 1 or 2. Option 0 will add the random character before index `r`; option 1 will replace the character at index `r` with the random character; and option 2 will remove the character at index `r`. ]
[Question] [ An [orthogonal matrix](https://en.wikipedia.org/wiki/Orthogonal_matrix) is a square matrix with real entries whose columns and rows are orthogonal unit vectors (i.e., orthonormal vectors). This means that M^T M = I, where I is the identity matrix and ^T signifies matrix transposition. Note that this is orthogonal not "special orthogonal" so the determinant of M can be 1 or -1. The aim of this challenge is not machine precision so if M^T M = I to within 4 decimal places that will be fine. The task is to write code that takes a positive integer `n > 1` and outputs a [random orthogonal n by n matrix](https://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization). The matrix should be randomly and uniformly chosen from **all** n by n orthogonal matrices. In this context, "uniform" is defined in terms of the Haar measure, which essentially requires that the distribution does not change if multiplied by any freely chosen orthogonal matrix. This means the values of the matrix will be floating point values in the range -1 to 1. The input and output can be any form you find convenient. Please show an explicit example of your code running. You may not use any existing library function which creates orthogonal matrices. This rule is a little subtle so I will explain more. This rule bans the use of any existing function which takes in some (or no) input and outputs a matrix of size at least n by n which is guaranteed to be orthogonal. As an extreme example, if you want the n by n identity matrix, you will have to create it yourself. You can use any standard random number generator library for choosing random numbers of your choosing. Your code should complete within at most a few seconds for `n < 50`. [Answer] # Haskell, ~~169~~ ~~150~~ ~~148~~ ~~141~~ ~~132~~ 131 bytes ``` import Numeric.LinearAlgebra z=(unitary.flatten<$>).randn 1 r 1=asRow<$>z 1 r n=do;m<-r$n-1;(<>diagBlock[m,1]).haussholder 2<$>z n ``` Recursively extend an orthogonal matrix of size `n-1` by adding 1 to lower right corner and apply a random Householder reflection. `randn` gives a matrix with random values from a gaussian distribution and `z d` gives a uniformly distributed unit vector in `d` dimensions. `haussholder tau v` returns the matrix `I - tau*v*vᵀ` which isn't orthogonal when `v` isn't a unit vector. Usage: ``` *Main> m <- r 5 *Main> disp 5 m 5x5 -0.24045 -0.17761 0.01603 -0.83299 -0.46531 -0.94274 0.12031 0.00566 0.29741 -0.09098 -0.02069 0.30417 -0.93612 -0.13759 0.10865 0.02155 -0.83065 -0.35109 0.32365 -0.28556 -0.22919 -0.41411 0.01141 -0.30659 0.82575 *Main> (<1e-14) . maxElement . abs $ tr m <> m - ident 5 True ``` [Answer] # Python 2+NumPy, 163 bytes Thanks to xnor for pointing out to use normal distributed random values instead of uniform ones. ``` from numpy import* n=input() Q=random.randn(n,n) for i in range(n): for j in range(i):u=Q[:,j];Q[:,i]-=u*dot(u,Q[:,i])/dot(u,u) Q/=(Q**2).sum(axis=0)**0.5 print Q ``` Uses the [Gram Schmidt](https://github.com/whille/mylab/blob/master/algrithm/gram_schmidt.py) Orthogonalization on a matrix with gaussian random values to have all directions. The demonstration code is followed by ``` print dot(Q.transpose(),Q) ``` n=3: ``` [[-0.2555327 0.89398324 0.36809917] [-0.55727299 0.17492767 -0.81169398] [ 0.79003155 0.41254608 -0.45349298]] [[ 1.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 1.00000000e+00 -5.55111512e-17] [ 0.00000000e+00 -5.55111512e-17 1.00000000e+00]] ``` n=5: ``` [[-0.63470728 0.41984536 0.41569193 0.25708079 0.42659843] [-0.36418389 0.06244462 -0.82734663 -0.24066123 0.3479231 ] [ 0.07863783 0.7048799 0.08914089 -0.64230492 -0.27651168] [ 0.67691426 0.33798442 -0.05984083 0.17555011 0.62702062] [-0.01095148 -0.45688226 0.36217501 -0.65773717 0.47681205]] [[ 1.00000000e+00 1.73472348e-16 5.37764278e-17 4.68375339e-17 -2.23779328e-16] [ 1.73472348e-16 1.00000000e+00 1.38777878e-16 3.33066907e-16 -6.38378239e-16] [ 5.37764278e-17 1.38777878e-16 1.00000000e+00 1.38777878e-16 1.11022302e-16] [ 4.68375339e-17 3.33066907e-16 1.38777878e-16 1.00000000e+00 5.55111512e-16] [ -2.23779328e-16 -6.38378239e-16 1.11022302e-16 5.55111512e-16 1.00000000e+00]] ``` It completes within a blink for n=50 and a few seconds for n=500. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~63~~ 61 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` ⎕CY'dfns' n←⊢÷.5*⍨a←+.×⍨ {{⍵,(n⊢-⊣×a)/⌽⍺,⍵}/⊂∘n¨↓NormRand⍵ ⍵} ``` [Try it online for n=5](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1rrxHbRMedS06vF3PVOtR74pEIFdb7/B0IJOruvpR71YdjTygtO6jrsWHpydq6j/q2fuod5cOUKJW/1FX06OOGXmHVjxqm@yXX5QblJiXApRQAEn@TwOZ29v3qKv5Ue@aR71bDq03ftQ2EWhzcJAzkAzx8Az@n19aAra9OU3BlEvdv7SkoLTESp0LqA4ow6XunJGanK1QkpFYopCSX6JQUJSfUppcopCfppCYk6NQkJhZVKyQWaxgANQCMqljhp4GyOmaQA4A "APL (Dyalog Unicode) – Try It Online") *-1 byte thanks to @user41805 (improved train for inner dfn)* Uses the [modified Gram-Schmidt process](https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process#Numerical_stability) on a set of `n` random unit vectors --- fast. **How?** ``` ⎕CY'dfns' ⍝ Copy the dfns namespace, which includes the NormRand dfn n←⊢÷.5*⍨+.×⍨ ⍝ n: normalize the vector argument, from https://codegolf.stackexchange.com/a/149160/68261 {{⍵,(n⊢-⊣×+.×⍨)/⌽⍺,⍵}/⊂∘n¨↓NormRand⍵ ⍵} ⍝ Main anonymous function NormRand ⍵ ⍵ ⍝ Generate an n×n array of gaussian variables ⊂∘n¨↓ ⍝ Treat as an array of singular arrays of n-vectors; normalize each { }/ ⍝ Reduce in a sneaky manner to get array of orthogonal (e_1, ... e_n) ⍝ Start with e_arr=⍬ (empty) ⍝ For each vector v_i: ⌽⍺,⍵ ⍝ Start this step with e_arr←(e_{i-1}, ..., e_1, e_0, v_i) ( )/ ⍝ Reduce this to repeatedly modify from the right: n⊢-⊣×+.×⍨ ⍝ Normalize(v_i - proj_{e_j}(v_i)) ⍵, ⍝ Append this to e_arr ``` [Answer] # Mathematica, 69 bytes, probably non-competing ``` #&@@QRDecomposition@Array[RandomVariate@NormalDistribution[]&,{#,#}]& ``` `QRDecomposition` returns a pair of matrices, the first of which is guaranteed to be orthogonal (and the second of which is not orthogonal, but upper triangular). One could argue that this technically obeys the letter of the restriction in the post: it doesn't output an orthogonal matrix, but a pair of matrices.... # Mathematica, 63 bytes, definitely non-competing ``` Orthogonalize@Array[RandomVariate@NormalDistribution[]&,{#,#}]& ``` `Orthogonalize` is unambiguously forbidden by the OP. Still, Mathematica is pretty cool eh? ]
[Question] [ ## Question We are captured by robot army on their space station. Our space ship pilot is in the prison which is in level 1. There is only one way how to escape and it's rescuing your space ship pilot. It mean's moving from level N to level 1. However because it's very risky you need to get to the prison in the least number of steps as possible. ## Conditions * There are 4 ways how to move: 1. Move from level N to level N - 1 `e.g. from 12 to 11` 2. Move from level N to level N + 1 `e.g. from 12 to 13` 3. Use teleport from level 2k to level k `e.g. from 12 to 6` 4. Use teleport from level 3k to level k `e.g. from 12 to 4` * Teleports are only one-way (you can get from 12 to 4 but it's imposible to get from 4 to 12) * Every action takes one step ## Input Input should be read from STDIN, or the closest alternative in your programming language. Input consists of an integer `n` where `1 <= n <= 10^8`. ## Output The output should be the minimum number of steps it takes to go from `n` to level 1. ## Examples ``` Level Minimum number of steps 1 0 8 3 10 3 267 7 100,000,000 25 ``` --- Try to code program that will help us to save our space ship pilot from the prison in the shortest time and return home! The shortest code will win! [Answer] # Pyth, 32 bytes ``` L?<b3tbhSsmm+h%_Wkbdy/+kbd2tS3yQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%3F%3Cb3tbhSsmm%2Bh%25_Wkbdy/%2Bkbd2tS3yQ&input=100000000&test_suite_input=1%0A8%0A10%0A267%0A100000000&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?code=L%3F%3Cb3tbhSsmm%2Bh%25_Wkbdy/%2Bkbd2tS3yQ&input=100000000&test_suite_input=1%0A8%0A10%0A267%0A100000000&test_suite=1) ### Explanation: I transformed the problem a little bit. I define 4 new operations, that replace the 4 operations of the question. * `level / 2` (counts as `(level % 2) + 1` steps, because you might need to do move a level down first in order to teleport) * `(level + 1) / 2` (counts as `(level % 2) + 1` steps) * `level / 3` (counts as `(level % 3) + 1` steps) * `(level + 1) / 3` (counts as `(-level % 3) + 1` steps) By design these operations can be applied to each number, if the number is `0 mod 2`, `1 mod 2`, `0 mod 3`, `1 mod 3` or `2 mod 3`. You can easily think about, why this works. The main idea is, that there is at least one optimal solution, that doesn't have two (move down) or two (move up) motions in a row. Proof: If you have a solution, that has two such motions in a row, than you can replace them and make the solution smaller or equal in length. For instance you could replace (move up, move up, teleport from 2k to k) by (teleport from 2k to k, move up) and similar in all other cases. ``` L?<b3tbhSsmm+h%_Wkbdy/+kbd2tS3yQ L define a function y(b), which returns: ?<b3 if b < 3: tb return b-1 else: m tS3 map each d in [2, 3] to: m 2 map each k in [0, 1] to: %_Wkbd (b mod d) if k == 0 else (-b mod d) h +1, this gives the additional steps + y/+kbd + f((b+k)/d) (recursive call) s combine the two lists hS and return the minimum element yQ call y with input number ``` The function `y` uses implicitly memoization and therefore the runtime doesn't explode. [Answer] ### Python, 176 bytes ``` n=int(1e8);s,f,L=0,input(),[1,0]+[n]*(n-1) def h(q): if 0<=q<=n and L[q]>s:L[q]=s+1 while n in L: for i,v in enumerate(L): if v==s:map(h,(i-1,i+1,i*2,i*3)) s+=1 print L[f] ``` Brute force all the way; a list of all numbers `1 to 100,000,000` on a 64bit computer is ~800Mb of memory. The list index represents the numbers, values represent the distance from 1 in allowed rescue steps. * Set list[1]=0 meaning "reachable in 0 steps". * for every number in the list which is reachable in 0 steps (i.e. `1`) + set number+1, number-1, number\*2, number\*3 reachable in 1 step * for every number in the list which is reachable in 1 step (i.e `0,2,2,3`) + set number+1, number-1, number\*2, number\*3 reachable in 2 steps * ... etc. until every list index is reached. Runtime is a bit over 10 minutes. \*ahem\*. ### Code comments ``` n=int(1e8) # max input limit. s=0 # tracks moves from 1 to a given number. f=input() # user input. L=[1,0]+[n]*(n-1) # A list where 0 can get to room 1 in 1 step, # 1 can get to itself in 0 steps, # all other rooms can get to room 1 in # max-input-limit steps as a huge upper bound. def helper(q): if 0<=q<=n: # Don't exceed the list boundaries. if L[q]>s: # If we've already got to this room in fewer steps # don't update it with a longer path. L[q]=s+1 # Can get between rooms 1 and q in steps+1 actions. while n in L: # until there are no values still at the # original huge upper bound for i,v in enumerate(L): if v==s: # only pick out list items # rechable in current s steps, map(helper,(i-1,i+1,i*2,i*3)) # and set the next ones reachable # in s+1 steps. s+=1 # Go through the list again to find # rooms reachable in s+1 steps print L[f] # show answer to the user. ``` ### Other * If you run it in PythonWin, you can access the list L in the interpreter afterwards. * Every room has a path to the captain in 30 moves or less. * Only one room is 30 moves away - room 72,559,411 - and there are 244 rooms which are 29 moves away. * It may have terrible runtime characteristics for the maximum case, but one of the question comments is "*@Geobits all programs that should find shortest ways for 20000 test cases in 5 minutes*" and it tests 1-20,001 in <6 seconds. [Answer] # Python 2 ... 1050 poorly written, ungolfed, unoptimal. Reads the start level on stdin, prints the minimum number of steps on stdout. ``` def neighbors(l): yield l+1 yield l-1 if not l%3:yield l/3 if not l%2:yield l/2 def findpath(start, goal): closedset = set([]) openset = set([start]) came_from = {} g_score = {} g_score[start] = 0 f_score = {} f_score[start] = 1 while len(openset) > 0: current = min(f_score, key=f_score.get) if current == goal: return came_from else: openset.discard(current) del f_score[current] closedset.add(current) for neighbor in neighbors(current): if neighbor in closedset: continue tentative_g_score = g_score[current] + 1 if (neighbor not in openset) or (tentative_g_score < g_score[neighbor]): came_from[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = tentative_g_score + 1 openset.add(neighbor) def min_path(n): path = findpath(n,1) i,current = 0,1 while current <> n: i+=1 current = path[current] return i print min_path(input()) ``` [Answer] # 32-bit x86 machine code, 59 bytes In hex: ``` 31c9487435405031d231dbb103f7f14a7c070f94c301d008d353e8e3ffffff5b00c3585331d2b102f7f152e8d2ffffff5a00d05a38d076019240c3 ``` The machine language *per se* has no concept of standard input. Since the challenge is pure computational, I opted to write a function taking input parameter in `EAX` and returning result in `AL`. The math behind the code is nicely explained by @Jakube: the search is conducted only among the paths having teleports interspersed with no more than one one-level moves. The performance is about 12000 test cases per second in the lower end of input range and 50 cases per second in the upper end. The memory consumption is 12 bytes of stack space per recursion level. ``` 0: 31 c9 xor ecx, ecx _proc: 2: 48 dec eax 3: 74 35 je _ret ;if (EAX==1) return 0; 5: 40 inc eax ;Restore EAX 6: 50 push eax 7: 31 d2 xor edx, edx ;Prepare EDX for 'div' 9: 31 db xor ebx, ebx b: b1 03 mov cl, 3 d: f7 f1 div ecx ;EAX=int(EAX/3); EDX=EAX%3 f: 4a dec edx ;EDX is [-1..1] 10: 7c 07 jl _div3 ;EDX<0 (i.e. EAX%3==0) 12: 0f 94 c3 sete bl ;BL=EDX==0?1:0 15: 01 d0 add eax, edx ;If EAX%3==2, we'd go +1 level before teleport 17: 08 d3 or bl, dl ;BL=EAX%3!=0 _div3: 19: 53 push ebx ;Save register before... 1a: e8 e3 ff ff ff call _proc ;...recursive call 1f: 5b pop ebx 20: 00 c3 add bl, al ;BL is now # of steps if taken 3n->n route (adjusted) less one 22: 58 pop eax ;Restore original input parameter's value 23: 53 push ebx 24: 31 d2 xor edx, edx 26: b1 02 mov cl, 2 28: f7 f1 div ecx ;EAX=EAX>>1; EDX=EAX%2 2a: 52 push edx ;Save register before... 2b: e8 d2 ff ff ff call _proc ;...another recursive call 30: 5a pop edx 31: 00 d0 add al, dl ;AL is now # of steps if using 2n->n route (adjusted) less one 33: 5a pop edx 34: 38 d0 cmp al, dl ;Compare two routes 36: 76 01 jbe _nsw 38: 92 xchg eax, edx ;EAX=min(EAX,EDX) _nsw: 39: 40 inc eax ;Add one for the teleport itself _ret: 3a: c3 ret ``` ]
[Question] [ Write code to figure out whether a run of Tetris pieces could be generated by the official Tetris algorithm. Fewest bytes wins. --- [Official Tetris games](http://tetris.wikia.com/wiki/Tetris_Guideline) generate the sequence of falling pieces in a special way. The seven pieces `IJLOSTZ` are dropped in a random order, then another random permutation is dropped, and so on. ``` JTLOISZ STJOLIZ LISJOTZ ... ``` This example contains the contiguous run of pieces ``` SZSTJOLIZLIS ``` Note that it cuts across the boundaries of a group of 7. But, the run of pieces ``` SZOTLZSOJSIT ``` cannot be a substring of any Tetris sequence, so it can never be seen in an official Tetris game. --- **Input:** A non-empty string of letters `IJLOSTZ`. **Output:** A [Truthy or Falsey](http://meta.codegolf.stackexchange.com/q/2190/20260) value for whether the input is a substring of a sequence that can be generated by the official Tetris Random Generator, i.e. of a concatenation of permutations of the seven letters. **Test cases:** True: ``` T JJ (unique breakdown: J J) JTJ (possible breakdown: JT J) LTOZIJS SZSTJOLIZLIS (possible breakdown: SZ STJOLIZ LIS) JTLOISZSTJOLIZLISJOTZ (possible breakdown: JTLOISZ STJOLIZ LISJOTZ) LIJZTSLIJZTS (unique breakdown: LIJZTS LIJZTS) ``` False: ``` SZOTLZSOJSIT ZZZ ZIZJLJ ZJLJLZITSOTLISOJT JTLOISZSTJOLIZLISJOTZLJTSZLI IOJZSITOJZST LIJZTSLIJZTSL ``` **Leaderboard** Courtesy of [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner). ``` function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/55689/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/ ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table> ``` [Answer] # Pyth, 16 15 bytes ``` sm*F.{Mc+>Gdz7T ``` Prints 0 for false, a positive integer for true. [Answer] # CJam, ~~23~~ ~~20~~ 16 bytes ``` q7{\+_7/_Lf|=},& ``` *Credits to Sp3000 for shaving off 4 bytes!* It prints a bunch of digits as a truthy value or nothing as a falsy value (before printing these are actually a non-empty or empty list, which are indeed truthy and falsy in CJam). [Test it here.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ7%7B%5C%2B_7%2F_Lf%7C%3D%7D%2C%26%0A%0A%5DoNo%7D%2F&input=T%0AJJ%0AJTJ%0ALTOZIJS%0ASZSTJOLIZLIS%0AJTLOISZSTJOLIZLISJOTZ%0ALIJZTSLIJZTS%0A%0ASZOTLZSOJSIT%0AZZZ%0AZIZJLJ%0AZJLJLZITSOTLISOJT%0AJTLOISZSTJOLIZLISJOTZLJTSZLI%0AIOJZSITOJZST%0ALIJZTSLIJZTSL) ## Explanation This just checks all 7 possible partitions of the input into chunks. ``` q e# Read the input 7{ e# Select the numbers from 0 to 6 for which the following block is true. \+ e# Prepend the number to the input. This shifts the string by one cell e# without adding non-unique elements. _7/ e# Make a copy and split into chunks of 7. _Lf| e# Remove duplicates from each chunk. = e# Check if the last operation was a no-op, i.e. that there were no duplicates. }, & e# The stack now contains the input with [6 5 ... 1 0] prepended as well as a list e# of all possible splittings. We want to get rid of the former. To do this in one e# byte we take the set intersection of the two: since we've prepended all the e# integers to the list, this will always yield the list of splittings. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~61~~ 55 bytes ``` ^((.)(?<!\2.+))*((){7}((?<-4>)(.)(?!(?<-4>.)*\4\6))*)*$ ``` Since this is just a single regex, Retina will run in Match mode and report the number of matches it found, which will be `1` for valid sequences and `0` otherwise. This isn't competitive compared with the golfing languages, but I'm quite happy with it, seeing I started out with a monster of 260 bytes. ## Explanation ``` ^((.)(?<!\2.+))* ``` This bit consumes a prefix of unique letters of variable length, i.e. it matches the potentially incomplete leading chunk. The lookbehind ensures that any character matched in this bit has not appeared in the string before. Now for the rest of the input, we want to match chunks of 7 without repeating characters. We could match such a chunk like this: ``` (.)(?!.{0,5}\1)(.)(?!.{0,4}\2)(.)(?!.{0,3}\3)...(.)(?!.?\5). ``` I.e. we match a character that doesn't appear for another 6 characters, then one which doesn't appear for another 5 characters and so on. But this requires fairly horrible code repetition, and we'd have to match a trailing (potentially incomplete) chunk separately. [Balancing groups](https://stackoverflow.com/a/17004406/1633117) to the rescue! A different way to match ``` (.)(?!.{0,5}\1) ``` is to push 5 empty matches onto a capture stack and try emptying it: ``` (){5}(.)(?!(?<-1>.)*\2) ``` The `*` allows a minimum of zero repetitions, just like `{0,5}`, and because we've pushed five captures, it won't be able to pop more than 5 times either. This is longer for a single instance of this pattern, but this is much more reusable. Since we're doing the popping in a *negative* lookahead, this doesn't affect the actual stack once the lookahead has completed. So after the lookahead, we've still got 5 elements on the stack, no matter what happened inside. Furthermore, we can simply pop one element from the stack before each lookahead, and run the code in a loop, to automatically decrement the lookahead width from 5 down to 0. So that really long bit up there can actually be shortened to ``` (){7}((?<-1>)(.)(?!(?<-1>.)*\1\3))* ``` (You may notice two differences: we're pushing 7 instead of 5. One additional capture is because we pop *before* each iteration, not after it. The other is actually necessary so that we can pop from the stack 7 times (since we want the loop to run 7 times), we can fix that off-by-one error inside the lookahead by ensuring with the `\1` that there is still at least one element left on the stack.) The beauty of this is that it can also match the trailing incomplete chunk, because we never required it to repeat 7 times (that's just the necessary maximum, because we can't pop from the stack more often than that). So all we need to do is wrap this in another loop and ensure we've reached the end of the string to get ``` ^((.)(?<!\2.+))*((){7}((?<-4>)(.)(?!(?<-4>.)*\4\6))*)*$ ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 bytes ``` f=(n,i=7)=>(n+{}).match(/.{7}/g).some(x=>/(.).*\1/.test(x))?i&&f(i+n,i-1):1 ``` [Try it online!](https://tio.run/##hVFNb8IwDL3nV@SEkgGpOCExlWnHWJFySE7ehyglZd1K07VlQ0L89i4dHEAC4cOzJb/3bMufyU/SpHVetePSr1zXZTErR3k85fGclcP9gYtN0qYfLBL76SFac9H4jWO7eB4xwcXD6yQSrWtatuP8KR8MMpYPg3484bNJ97gglgDQG8G2Zf69dXRZu@Rr5X/LGQUKnIC9LmGVb5p8WVwqbC9RVqMEQwwaC1pJVNLclRqkJzYN9H6u0vLcAbTF23P/yecOPZ1TSpQEtOaIdy8@0Y6JhwO0VWg0GGkJIhKUCApIDwqlNaEtQ9te31aBNaEmUgMGhx7txT6KLETtqiJJHYveX57H@DaMNusRDR9Nfdn4wonCr1nWP5R3fw "JavaScript (Node.js) – Try It Online") Try `1234567<input>[object Object]` so that * digits are inserted one by one, so starting anywhere is tested * Tested length is large enough, `match` never return `null` * connected string doesn't break the property ]
[Question] [ This question is an extension of [Check if words are isomorphs](https://codegolf.stackexchange.com/questions/50472/check-if-words-are-isomorphs) and copies the first part of it to give the definition of an isomorph. Two words are *[isomorphs](http://www.questrel.com/records.html#spelling_structure_entire_word_isomorph_or_matching_letter_pattern)* if they have the same pattern of letter repetitions. For example, both `ESTATE` and `DUELED` have pattern `abcdca` ``` ESTATE DUELED abcdca ``` because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching `E <-> D, S <-> U, T <-> E, A <-> L`. Given two strings X and Y, with X no longer than Y, the task is to determine if there is a substring of Y which is an isomorph with X. **Input:** Two non-empty strings of letters from a..zA..Z which one string per line. This will come from standard input. **Output** A substring of the second string which is an isomorph with the first string, if such a thing exists. Otherwise output "No!". **Rules** Your code must run in linear time in the total length of the input. **Score** Your score is the number of bytes in your code. Fewest bytes wins. --- **Example input and output** ``` adca ddaddabdaabbcc dabd ``` **Tip** There is at least one not *that* complicated, practically fast and linear time solution to this problem. [Answer] # Python 2, ~~338~~ ~~326~~ ~~323~~ ~~321~~ ~~310~~ ~~306~~ ~~297~~ ~~293~~ ~~290~~ ~~289~~ ~~280~~ ~~279~~ ~~266~~ ~~264~~ ~~259~~ ~~237~~ ~~230~~ ~~229~~ ~~226~~ ~~223~~ ~~222~~ ~~220~~ ~~219~~ 217 (~~260~~ ~~238~~ ~~231~~ ~~228~~ ~~225~~ ~~223~~ ~~221~~ ~~220~~ 218 with 0 exit status) ``` exec'''s=raw_input() S=[M-s.rfind(c,0,M)for M,c in enumerate(s)] k=0 j=x=%s while k<=M+x: if S[k]>j<W[j]or S[k]==W[j]: k+=1;j+=1;T+=[j] if j-L>x:print s[k-j:k];z else:j=T[j] '''*2%('-1;T=[0];W=S;L=M',0) print'No!' ``` The algorithm is a variation of KMP, using an index-based test for character matching. The basic idea is that if we get a mismatch at position `X[i]` then we can fall back to the next possible place for a match according to the longest suffix of `X[:i]` that is isomorphic to a prefix of `X`. Working from left to right, we assign each character an index equal to the distance to the most recent previous occurrence of that character, or if there is no previous occurrence then we take the length of the current string prefix. For example: ``` MISSISSIPPI 12313213913 ``` To test whether two characters match, we compare indices, adjusting appropriately for indices that are greater than the length of the current (sub)string. The KMP algorithm becomes a little simplified since we cannot get a mismatch on the first character. This program outputs the first match if one exists. I use a runtime error to exit in the event of a match, but the code can be easily modified to exit cleanly at the cost of some bytes. **Note:** For computing indices, we can use `str.rfind` (as opposed to my earlier approach using a dictionary) and still have linear complexity, assuming that `str.rfind` starts searching from the end (which seems the only sane implementation choice) -- for each character in the alphabet, we never have to traverse the same part of the string twice, so there is an upper bound of (size of alphabet) \* (size of string) comparisons. Since the code got fairly obfuscated in the course of golfing, here is an earlier (293 byte) solution that's a bit easier to read: ``` e=lambda a:a>i<W[i]or a==W[i] exec('s=raw_input();S=[];p={};M=i=0\nfor c in s:S+=[M-p.get(c,-1)];p[c]=M;M+=1\nW=S;L=M;'*2)[:-9] T=[0]*L k=1 while~k+L: if e(W[k]):i+=1;k+=1;T[k]=i else:i=T[i] m=i=0 while m+i<M: if e(S[m+i]): if~-L==i:print s[m:m+L];z i+=1 else:m+=i-T[i];i=T[i] print'No!' ``` The `e` function tests equivalence of characters. The `exec` statement assigns indices and does some variable initialisations. The first loop processes `X` for fall back values, and the second loop does the string search. **Update:** Here is a version that exits cleanly, at the cost of one byte: ``` r='No!' exec'''s=raw_input() S=[M-s.rfind(c,0,M)for M,c in enumerate(s)] k=0 j=x=%s while k<=M+x: if S[k]>j<W[j]or S[k]==W[j]: k+=1;j+=1;T+=[j] if j-L>x:r=k=s[k-j:k] else:j=T[j] '''*2%('-1;T=[0];W=S;L=M',0) print r ``` [Answer] # Python 3, 401 bytes ``` import string,itertools X=input() Y=input() x=len(X) t=[-1]+[0]*~-x j=2 c=0 while j<x: if X[j-1]==X[c]:c+=1;t[j]=c;j+=1 elif c>0:c=t[c] else:t[j]=0;j+=1 s=string.ascii_letters *b,=map(s.find,X) for p in itertools.permutations(s): m=i=0 while m+i<len(Y): if p[b[i]]==Y[m+i]: if~-x==i:print(Y[m:m+x]);exit() else:i+=1 else: if-1<t[i]:m+=i-t[i];i=t[i] else:i=0;m+=1 else:print("No!") ``` This is still mostly ungolfed, but I think it should work. The core algorithm is [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm), plus an additional factor which is factorial in the size of the alphabet (which is fine, since the alphabet is constant). In other words, this is/should be one completely impractical linear algorithm. Here's a few annotations to help with the analysis: ``` # KMP failure table for the substring, O(n) t=[-1]+[0]*~-x j=2 c=0 while j<x: if X[j-1]==X[c]:c+=1;t[j]=c;j+=1 elif c>0:c=t[c] else:t[j]=0;j+=1 # Convert each char to its index in a-zA-Z, O(alphabet * n) s=string.ascii_letters *b,=map(s.find,X) # For every permutation of letters..., O(alphabet!) for p in itertools.permutations(s): # Run KMP, O(n) m=i=0 while m+i<len(Y): if p[b[i]]==Y[m+i]: if~-x==i:print(Y[m:m+x]);exit() else:i+=1 else: if-1<t[i]:m+=i-t[i];i=t[i] else:i=0;m+=1 else:print("No!") ``` For testing, you can replace `s` with a smaller alphabet than `string.ascii_letters`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 32 bytes This is an infix function, taking X as left argument and Y as right argument. ``` {(s,⊂'No!')⊃⍨(⍳⍨¨s←⍵,/⍨≢⍺)⍳⊂⍳⍨⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P7P4UduEao1inUddTep@@Yrqmo@6mh/1rtB41LsZSB1aAZJ/1LtVRx/Ie9S56FHvLk2QVFcTRAGQX/v/v3piSnKiukJmsYJ6SkoiECWlJCYmJSUnq3OBpFKwSgEA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda where `⍺` and `⍵` represent the arguments (X and Y)  `⍳⍨⍺` **ɩ**ndex selfie of X (**ɩ**ndices of the first occurrence of elements of X in X)  `⊂` enclose so we can look for that entire pattern  `(`…`)⍳` **ɩ**ndex of first occurrence of that in…   `≢⍺` tally (length) of X   `⍵,/⍨` all substrings of that size of Y (lit. concatenation reduction of those, but that is a no-op)   `s←` store in `s` (for **s**ubstrings)   `⍳⍨¨` **ɩ**ndex selfie of each of those  now we have the index of the first pattern, or 1 + the number of patterns if no match was found  `(`…`)⊃⍨` use that index to pick from…   `⊂'No!'` the enclosed string (so that it functions as a single element)   `s,` prepended with `s` ]
[Question] [ I think everyone is familiar with the game of darts. For those that don't understand the scores, [here](http://www.darts.org.nz/scoring.html) is a useful link. ### The board A dartboard can be compared to a pie cut in 20 pieces. Each piece is divided in 4 sections. * a small outer ring called "double" (points x2) * a big ring called "single" (points x1) * another small ring called "triple" (points x3) * another big ring called "single" (points x1) In the middle of the board are 2 more rings, a green one and red one (classic board) * Red ring, at the center of the board, is called "bullseye" or "double bull" and is good for 50 points. This one counts as a double and because of that it's allowed to checkout with it. * Green ring is called "bull", "single bull", or simply "25" and counts as a single. ### Challenge Find all checkout possibilities with 3 darts or less. The user can enter an integer and you will have to check if it's possible to get the score to 0 with 3 darts (or fewer). ### Examples example 1: ``` Input: 170 Output: T20, T20, Bullseye ``` Example 2: ``` Input: 6 Output: D3; S3,S1,D1; S2,D2; S2,S2,D1; D2,D1; S4,D1; D1,D1,D1; S1,S1,D2; T1,S1,D1; ``` Example 3: ``` Input: 169 Output: No possible checkout! ``` ### Rules * Basic dart rules, you must end with a double (outer ring of the board or bullseye) * No use of external resources. * Hard coding of possible checkouts is allowed, but remember, this is codegolf, it won't get your code short ;) * Cells to hit will be displayed in format C+N where C = T for Triple, D for double and S for single. * bullseye can be called bullseye or DB, DBull or something similar. ### Possible checkouts To get you started, the highest possible checkout is 170. 169, 168, 166, 165, 163, 162, and 159 are not possible in 3 darts. The lowest possible checkout is 2. ### In addition This isn't a requirement: add in a possibility to show all possible checkouts for all scores. Basically because I wonder how many combinations are possible :P Winner will be the one with the shortest code. Happy coding. [Answer] ## MATLAB (~~299~~ ~~249~~ 241 chars) This is my first serious golfing. My first attempt (136 chars) gives the correct result, but not with the correct formatting. It gives all possibilities looking at the number of points for each dart. This means that single 20 and double 10 do have a separate entry, however, they are both displayed as 20. Of course the last dart is always a double. ``` function f(x);u=[1:20 25].';y=[u;2*u; 3*u(1:end-1)];v=combvec([combnk(y,2);[y y];[zeros(62,1) y];[0 0]].',y(22:42).').';v(sum(v,2)==x,:) ``` In the second attempt the formatting is improved, which has of course increased the number of characters: ``` function f(x);h=.1;u=h+[1:20,25].';y=[u;2*u;3*u(1:20)];v=combvec([combnk(y,2);[y,y];h*ones(62,1),y];[h,h]].',y(22:42).').';t='SDT';r=@fix;strrep(arrayfun(@(x)[t(int8((x-r(x))/h)),num2str(h*r(x)/(x-r(x)))],v(sum(r(v),2)==x,:),'un',0),'S0','') ``` Improved from 299 to 249 characters, while at the same time even improving the output formatting. For this improved version the output for the example cases is: f(170): ``` 'T20' 'T20' 'D25' ``` f(6): ``` 'S1' 'S3' 'D1' 'S1' 'T1' 'D1' 'S2' 'D1' 'D1' 'S2' 'S2' 'D1' 'D1' 'D1' 'D1' '' 'S4' 'D1' '' 'D2' 'D1' 'S1' 'S1' 'D2' '' 'S2' 'D2' '' 'D1' 'D2' '' '' 'D3' ``` f(169): ``` Empty cell array: 0-by-3 ``` ### Additional: According to my calculation skills there are a grand total of 42336 possibilities to end the dart game. [Answer] # C++ ~~248 / 228~~ 230 / 214 chars Rev 0: ``` int f(int s){char m[4]="SDT";int t=0;for(int b=2;b<77;b+=1+(b==62)*12)for(int a=2;a<77;a+=1+(a==62)*12){int c=s-a/3*(a%3+1)-b/3*(b%3+1);if(((c+38)/40==1)|(c==50)&&(c%2==0)&(a>=b)){printf("%c%d %c%d D%d\n",m[a%3],a/3,m[b%3],b/3,c/2);t++;}}return t;} ``` Rev 1. Saved some characters by declaring all variables at once, and by eliminating unnecessary brackets. It turns out that in C++ all logic and bitwise and/or are lower precedence than comparisions. ``` int f(int s){char m[4]="SDT";int a,b,c,t=0;for(b=2;b<77;b+=1+(b==62)*12)for(a=2;a<77;a+=1+(a==62)*12){c=s-a/3*(a%3+1)-b/3*(b%3+1);if(c>1&c<41|c==50&&c%2==0&a>=b){printf("%c%d %c%d D%d\n",m[a%3],a/3,m[b%3],b/3,c/2);t++;}}return t;} ``` I did a function rather than program, as others have done. It returns the total number of possibilities found. It can be reduced from 230 to 214 characters by eliminating the totalising feature. Sample output, score 6: ![enter image description here](https://i.stack.imgur.com/9SMxh.png) I count different first and second darts as the same combination, as the OP has done (example: T1 S1 D1 = S1 T1 D1) even though this costs an extra 7 characters. I always list the higher score first (ignoring doubling and trebling) as I figure this is more relevant to the player (who may change his strategy if he misses with the first dart.) For the same reason I list the darts in order according to the second dart. I consider the 3rd dart to be completely different to the other two, therefore I consider D1 D2 and D2 D1 to be different cases whereas the OP has them listed as the same. **With this system of counting I get 42336 total possibilities**, the same as mmumboss. Counting different first and second darts as different combinations, this goes up to 83349. I haven't used a for loop with sets as others have done (I'm fairly new to C++ and I don't even know if it's possible.) Instead I abuse a conditional in the loop increment to jump from 20 up to 25. I use the variable from a single loop to encode all possible scores for a single dart, like this: S1 D1 T1 S2 D2 T2 etc. with modulus and division to decode. This saves on the verbosity of declaring more for loops, although it makes expressions more complicated. The result of this is that an unused dart is shown as T0, but I think it's clear what is meant, especially as (by considering different first and second darts as the same combination) I have been able to group them all together at the beginning of my output. Ungolfed version here. A couple of other features are use of the & and && operators selectively with | in such a way as to give the order of precedence I want without brackets. ``` int f(int s) { char m[4] = "SDT"; int a,b,c,t=0; for (b = 2; b < 77; b += 1 + (b == 62) * 12) for (a = 2; a < 77; a += 1 + (a == 62) * 12){ c = s - a / 3 * (a % 3 + 1) - b / 3 * (b % 3 + 1); if (c>1 & c<41 | c == 50 && c % 2 == 0 & a >= b){ printf("%c%d %c%d D%d\n", m[a % 3], a / 3, m[b % 3], b / 3, c / 2); t++; } } return t; } ``` [Answer] # Ruby (260 chars) "The last one should be a double" was the missing piece - couldn't figure out why 168 should not have results...: ``` c=->n,d=3{d=d-1;r=[];n==0?[r]:(d>=0&&n>0?(o='0SDT';((1..20).map{|p|(1..3).map{|h|c.(n-p*h,d).map{|m|r<<["#{o[h]}#{p}"]+m}}};c.(n-50,d).map{|m|r<<['DB']+m};c.(n-25,d).map{|m|r<<[?B]+m})):1;r.select{|*i,j|j[?D]}.tap{|x|d!=2?1:puts(x.map{|i|"#{i.join(?,)};"})})} ``` c.(170) ``` T20,T20,DB; ``` c.(6) ``` S1,S1,D2; S1,T1,D1; S1,S3,D1; D1,D1,D1; D1,S2,D1; D1,D2; T1,S1,D1; S2,D1,D1; S2,S2,D1; S2,D2; D2,D1; S3,S1,D1; D3; S4,D1; ``` [Answer] # Python 2.7 (270 chars) Not sure python will allow a one-liner, but he it is in three. ``` def f(n): a={'%s%s'%('0SDT'[i],n):n*i for n in range(1,21)+[25] for i in [1,2,3] if n*i<75};a['']=0 for r in [' '.join(h[:3]) for h in [(x,y,z,a[x]+a[y]+a[z]) for x in a for y in a for z in {k:a[k] for k in a if 'D' in k}] if h[3]==n and len(h[0])<=len(h[1])]:print r ``` Or 278+ chars with a proper 'No Checkout' message (e.g. 290 here): ``` def f(n): a={'%s%s'%('0SDT'[i],n):n*i for n in range(1,21)+[25] for i in [1,2,3] if n*i<75};a['']=0; for r in [' '.join(h[:3]) for h in [(x,y,z,a[x]+a[y]+a[z]) for x in a for y in a for z in {k:a[k] for k in a if 'D' in k}] if h[3]==n and len(h[0])<=len(h[1])] or ['No Checkout']:print r ``` Here we go: f(170) ``` T20 T20 D25 ``` f(6) ``` S3 S1 D1 S2 S2 D1 S2 D1 D1 S1 S3 D1 S1 S1 D2 S1 T1 D1 S2 D2 S4 D1 D3 D2 D1 D1 D2 T1 S1 D1 D1 S2 D1 D1 D1 D1 ``` f(169) ``` No Checkout ``` Things I'm not happy with: ``` for x in a for y in a for z in ``` This is over 10% of the total. Is there a more compact way without itertools etc? ``` and len(h[0])<=len(h[1]) ``` This is used to prevent duplicates in the case of a two dart finish (e.g. ['', 'S1', 'D1'] and ['S1', '', 'D1']). I deem order to matter (hey - the last dart has to be a double, so clearly order matters), but the non-throw is a special case. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 20L25ª3Lâ¨Ðʒθ<}Uã«XâXìε˜2ô}ʒPOQ}εε`…TSDsèì ``` Pretty slow.. Outputs as a list of lists, or an empty list if no finish is possible. My bulls are `S25` and `D25`; if this is not allowed I can change it. [Try it online](https://tio.run/##AVEArv9vc2FiaWX//zIwTDI1wqozTFLOtOKAmuKCrGDCqMOQypLOuDx9VcOjwqtYw6JYw6zOtcucMsO0fcqSUE9Rfc61zrVg4oCmVFNEc8Oow6z//zY) or [verify a few test cases at once](https://tio.run/##yy9OTMpM/f/fyMDHyPTQKmOfw4sOrTg84dSkcztsakMPLz60OuLwoojDa85tPT3H6PCWWq6wsspDK5U88wpKS6wUlOx1lPxLS6DsSK5TkwL8D60LrD239dzWhEcNy0KCXYoPrzi8hqu2VufQNvv//6PNdAzNLHQMzQ1iAQ). **Explanation:** There are a couple of steps: 1) Create a list of all possible single, double, and triple darts: ``` 20L # Create a list in the range [1,20] 25ª # Append 25 to this list 3L # Create a list in the range [1,3] â # Create all possible pairs of these two lists ¨ # Remove the last pair (which is the Triple Bull) # Now we have a list of all possible darts: # [[1,1],[1,2],[1,3],[2,1],...,[20,3],[25,1],[25,2]] ``` 2) Get all possible finishers (ending with a double) of up to 3 darts: ``` Ð # Triplicate this list ʒ } # Filter the top copy by: θ # Where the last value < # Decremented by 1 is truthy (==1), so all doubles U # Pop this filtered list of doubles, and store it in variable `X` ã # Create all possible pairs of the list of darts with itself « # Merge it with the list of darts # We now have a list containing all possible variations for 1 or 2 darts Xâ # Then create all possible pairs of these with the doubles from variable `X` Xì # And prepend the doubles themselves as well # Now we have all possible variations of 1 double; 1 dart + 1 double; # or 2 darts + 1 double ε } # Map each to: ˜ # Deep-flatten the list 2ô # And split it into parts of size 2 # (this is to convert for example a 2 darts + 1 double from # [[[20,3],[5,1]],[1,2]] to [[20,3],[5,1],[1,2]]) # Now we have a list of all possible finishers of up to 3 darts ``` 3) Only keep those for which the total score is equal to the input-integer: ``` ʒ } # Filter this list by: P # Get the product of each inner-most lists # i.e. [[20,3],[5,1],[1,2]] → [60,5,2] O # Take the sum of those # i.e. [60,5,2] → 67 Q # Check if this value is equal to the (implicit) input-integer # Now we only have the finishers left with a total value equal to the input ``` 4) Convert the data to the pretty-printed result-list (i.e `[[20,3],[5,1],[1,2]]` becomes `["T20","S5","D2"]`): ``` ε # Map each of the remaining finishers of up to 3 darts to: ε # Map each inner list to: ` # Push both values separately to the stack ([20,3] → 20 and 3) …TSD # Push string "TSD" s # Swap to get the integer for single/double/triple at the top of the stack è # Use it to index into the string # NOTE: 05AB1E has 0-based indexing with automatic wraparound, # so the triple 3 will wrap around to index 0 for character "T" ì # Prepend this character in front of the dart-value # (after which the result is output implicitly as result) ``` [Answer] # [Kotlin](https://kotlinlang.org), 254 bytes Note: algorythm is based on Level River St's C++ answer. ``` {s:Int->val m="SDT" var c=0 val r=(2..62).toList()+listOf(75,76) for(t in r)for(o in r){val l=s-o/3*(o%3+1)-t/3*(t%3+1) if((l>1&&l<41||l==50)&&l%2==0&&o>=t){println("${m[o%3]}${o/3},${m[t%3]}${t/3},D${l/2}") c++}} if(c<1)println("No possible checkout!")} ``` [Try it online!](https://tio.run/##jVhtb9s4Ev6eX8EGbU7eKI7tvPTWWwdo4vY2QLddNAHuw959oCXaFiqLKkk18aX57b1nZijZbrPYNeBYoobDeXnmmVE@2VAW1bfjY3Vd1U3wY1XZsCyqhZpbp3Iz100ZVKa98QoLutqDaFEFszBOzUy4M6ZSI6znavhy0N@jx1fO6GBy1gBdXmU2N2phy/mYHi9DqP34@JhWabHvg84@mftsqauF6Wd2dfz5eDQYvDwn6al2wauVMfh7FXfwKdeku/qkzBfj1rYyCgfN9aooC@3UXRGWKqetKcl6uzKqNrYujcptFVRT5cbhXJgdlkb5zDo46C0Ji9nWdzuWxrF2rRpv5k1ZqpIOthyLsNShTxe30DOz2uVs3Ws@ne8RvQqhQhRWtXaIS7BQVRdYaQJiSeKjAS1kxvfVG50t5YbOzIsvRY49RaVO2ROThcJWXiINPX6lYZBtAvLhKG8Z7rEht80Mtie1Rba8uh/14oZZsdgR9LjeFhxGQcIBdIr@7Q3BFfX2hpPdDX9DP6ev4sivijzHUzvnO4kXggRIrZASViQp1GrhCGuUMgoiZTzJSu19kck@0Uufj3hOO1OVmYoCs6Ne7CLZGXLpzdoQsmO8aInPQOwX1gqIzwYkLQ70kWg8o@Mz25BHmpARt2MnKzaZBlbkXI0kk1hZ2jvJfrY02SekjGHKBSUQos@/2MtovUSQbErbOLKB1jEWilVdrtXojA3etkZkYzUuSQsqi@/eFhCljHY21BYhnBVlKFABXDcnUjkkDudL430HcDjlGM8SV1y0XEAmrG0DDWXJVa6/mM5XVcw5BnJWyQ8WJlBS2BEqP1ob7BigEhw/N3fG9diAN/caDhvPjhi5UcNxhBPYa0wcpBTdf2gCL9yOBqn8uYzJ3ttSpUY7u893905PfpGF9nNzkt4M0@nw@@VROh39uEbL34tOn1i7OX1Cjo55QnTIBnx/2O0w2rXj28luZM5/3vbtvd0ko4XCM5b/2LQhps@lpvqidCiHBynneNX4AATkki1Nsi3dbBHRTtEhk2219VrdsCEWibnHrkqDZ4y3jSMebIV@5ZK1edT4g9Eelcr8EMtrBkg7szKrmYndJzYgahwpUEjCd9QDCIDwxkl78ksLH3/pjLsysJYwuSwCg5ooPC98Xeq18DGYYaVZ3dXhe3XHXeJKTdQtc8Yts2SqptJId@jhhtfaIo0HdmTUtotN8bccNb1kKpxeCgdwW5NmDSpoSu2k4n//IUa8fGtblxU6n0OHTrmml8ViaXzoQkuyHTsgeNzXsQYEpcPzf@J7ju8Zvif4jtLh2c9M2eD/HR0IUSzkjj4oRVsn7Rwz6se2oPO8oB4nRksGkS6NtH5uCsptFVKSohN0x19FWHM/tpTKO@a4J8BCgdfCUNL0@wJx8GhL2tcED4wHitSsdMVq0bxnRaW597K3ne7x72zov4uqMq5DCiGfegRXCI8YhC9yntAmefpV1/U6YltW3jYVt3fZZu5rAAYYKPVqlsPTsvHRFooBTH9vgxnDn4V167BcURhnGNXyOJu8w2xUqo8FJiR1E/6BAerwEBj0YNT@3rypVO0sas0nHIoxgh966mFvTykCaWBSXlL0tNMZ1TWCG0sgTklGZAG@wENBrHnuRX1OOV9iXQTlcC8ARCCD@p9xViQdjX@d5BddNkbyRTVaWlv7dvSgPbBFBOMaTVCIT9smD7Ybel8kN4esNNoWvtB4Z@Pk1Z1cVFLZyEPK3rApYzQnuN8eMzpLW49khGxDMI4WpNGAVB1s29lX14x2VHeGiqUxebaWE346OfwumgmatbmnFms5CD4QsfZ7EMOOjdxE7d9Mb/d52cWIT9QgionLE5WM@v3zUa8f7LvCh6R3WOLnwzx5eZa@PO/FrL9FvA1PoF2rXjrUARLLFpgMtSGiVNopJ@jPN4jkvMCsHeU7xzlqsaSjRpkD4lEY7WQPQhbHKH4ek7Q1TCQx1UPGp1zHPEVLN1DoUQug3SiNSiXetnSrt0UhRXklM8R28QnbmCyjW@T55wYRbtPDwVGJKYsVcYVpj2/qssjoHnprpDCwOOv0QKokjGZAxeFMCJTgNk4cJTsu80tOu4w6leZPKeZYTSQ@RxA7PvmJpF@cHA57R3vdnEBop0f44UfxCYazJGEVF4jhwYGoe6VOh@rr163dcsoE43CvlXoxooUBbrfkyM6LCR22sVKJ42WV7D9/aIH7B9v438fnD2zzY7p/uKVGqW1RtplE2YcfRafPH8ig49Hjfq97wpE9bCUfGTjzve4aUY2wB8Iq27HTHbXyOfaiQ7Z8J@95EixJ2CsVI9h59uRQBXP4sMi1zPO/aZofWrKPVEo8K5O6kDORVKLdAu/kr53T61c3XP4XG4p@J30B8IvKNy@z/Vj8tZqI7OjsFEwDDH578GMQ/dEFU8hEmIN5YzLYY76Y/AVTwN4kMBJ7dClY7T0wECf@iCEmADsKDDcBWzEHyi6GBwflq9Ph16/lZAIg4e7FaDIZHBzYi0noPWyj5I@Ycc433YeIALqnfEuys8PDx0fSnr0a9v4qF4/fpBW4NbhH81QZ4nsN@mP3ItImi4VpLCBBeu25z0y96dD8/gO/i7xtHX/6jxEUH86UcqBIyVETtuJdUZmk9@wZAo7MJIIqApoIPUN8kRGoaZEtdHQNtCx0@dotGpoH3rS2JVuVsX@paU6qBYg7aCWqfy6dv30kB7a94MOWvyn/@6Ik3JJLHd4w0bRB8jS1U2WB6tAPEuOcdXgDI1s1kWr0XiiORiEoi8g6T3m8pFD1NqTRmfqfio2lTeOuvGtW0tst53iJWEvVURF9@z8 "Kotlin – Try It Online") ]
[Question] [ What general tips do you have for golfing in [Io](http://iolanguage.org/)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Io (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] ## Higher-level function shorthand This seems like a pretty interesting golfing point. E.g. ``` list(1,2,3)map(i,i+1)print ``` However, Io is pretty permissive on not specifying the counter; the map body can be used as a point-free function, as Io tries to fill in the operand of this expression. This can be golfed into ``` list(1,2,3)map(+1)print ``` --- Due to the helpful work of the language creator, you can even do this to reduces! ``` list(1,2,3)reduce(a,b,a*b) ``` Can easily be reduced into: ``` list(1,2,3)reduce(*) ``` (Unfortunately, I still haven't managed to understand how exactly this works, so I never managed to make the expression more complex.) [Answer] # You can stick methods onto the back of most literals ``` "text" print # 12 bytes "text"print # 11 bytes 12 print # 8 bytes 12print # 7 bytes (0<1,0,1) print # 15 bytes (0<1,0,1)print # 14 bytes ``` ## Not everything ``` 0x12print # prints nothing ``` [Answer] ## You can leave out the else part of the if function This isn't in the documentation... I initially thought that you have to include the else part, like the elvis operator in other languages; turns out that I can leave out the else part. (*Please* add this to the tutorial/documentation!) ``` if("bug"size>2,"True",nil) ``` So, if you don't want the else part to return anything, you could just do ``` if("bug"size>2,"True") ``` [Answer] ## Use `~`, `:`, and `\` for variable names You can stick methods onto the back of `~`. E.g. instead of this: ``` method(i,i pop) ``` You can do this: ``` method(~,~pop) ``` You can even put this between them. Instead of this: ``` and a sqrt ``` You can do this ``` and~sqrt ``` `:` also does this trick (I discovered it from the `:=` bug), as well as `\`. (This can empirically save a lot of bytes in your source code, if you use variables a lot) ## Some other valid symbolic names that you can't stick * `_` * `.` ## Can you stick these to other symbols as well? ~~Unfortunately, things get a little complicated here. Here's a table of how powerful these variable names are:~~ Unfortunately, you can't stick any of them before `:=` or on the rhs of `/`, so pick whatever name you like. :P [Answer] ## Literal newlines Just like JavaScript's ``, you can insert literal newlines. i.e. you can do: ``` " " ``` [Answer] ## Parenthesis dropping in method applications Say, I want to split a string by whitespace. I am pretty used to this method when I first got used to Io: ``` a_string split() ``` After I heard about how Io parses the arithmetic operations, I realized that this is perfectly valid: ``` a_string split ``` --- Sometimes, you can do that to some one-operand functions as well. If you want to join by spaces, you can do: ``` a string join" " ``` I guess this doesn't work sometimes, though I can't find any examples here. [Answer] ## Prefer push over append There are 2 methods that append values towards the caller object: `add`, `push`, and `append`. I didn't count `add` because `add` doesn't work. [Try it online!](https://tio.run/##y8z//z8ns7hEw1DHSMdYMzElRcNEU6GgKDOv5P9/AA "Io – Try It Online") `push` and `append` basically do the same thing: ``` list(1,2,3)push(4) println list(1,2,3)append(4) println ``` [Try it online!](https://tio.run/##y8z//z8ns7hEw1DHSMdYs6C0OEPDRFOhoCgzryQnjwtJKrGgIDUvBUny/38A "Io – Try It Online") Therefore, whenever you want to write `append`, remember that you can substitute it for `push` to do the exact same thing. ]
[Question] [ Write a program to play [the name game](http://www.youtube.com/watch?v=5MJLi5_dyn0). **Input** Your program should accept a single name as input from the user in some way (e.g read from standard input or as a command-line argument). You can assume that the name is a single word consisting of an upper case letter followed by one or more lower case letters. **Output** Your program must print the rhyme for the given name, as explained in the song, by filling out the following template: ``` (X), (X), bo-b(Y) Banana-fana fo-f(Y) Fee-fi-mo-m(Y) (X)! ``` Here, `(X)` is the original name, and `(Y)` is the name in lower case with any initial consonants removed. There is one exception, however. If the original name began with `m`, `f` or `b`, it should be written without this letter on the corresponding line. E.g. if the name was `Bob`, the "b" line should end with `bo-ob`. Note that in this case, any other consonants are kept, so for `Fred` it's `fo-red`, not `fo-ed`. **Examples** Shirley: ``` Shirley, Shirley, bo-birley Banana-fana fo-firley Fee-fi-mo-mirley Shirley! ``` Arnold: ``` Arnold, Arnold, bo-barnold Banana-fana fo-farnold Fee-fi-mo-marnold Arnold! ``` Bob: ``` Bob, Bob, bo-ob Banana-fana fo-fob Fee-fi-mo-mob Bob! ``` Fred: ``` Fred, Fred, bo-bed Banana-fana fo-red Fee-fi-mo-med Fred! ``` **Scoring** Shortest code wins. [Answer] ## vi, 118 115 ``` Y2PA,<ESC>Ypj~Y2PIbo-b<c-o>wBanana-fana fo-f<c-o>wFee-fi-mo-m<c-o>2$!<ESC>HJJ:%s/\vo-(([bfm])\2([^aeiou]*))?([bfm]?)[^aeiou]*/o-\3\4 ZZ ``` The code includes 5 control characters, which I've put in brackets. Each only counts as a single character towards the character count. EDIT: Moving the first join (J) to later and changing the paste-before (P) to a paste-after (p) saved me 1 character. Also, not capturing the o- in the regex saved me 2 more characters. [Answer] # SNOBOL4, ~~437~~ 430 bytes ``` N = TRIM(INPUT) D = REPLACE(N,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', +'abcdefghijklmnopqrstuvwxyz') B = "b" D F = "f" D M = "m" D &ANCHOR = 1 D SPAN('bcdfghjklmnpqrstvwxyz') . I REM . R :F(Y) B = "b" R F = "f" R M = "m" R I "b" :S(U) I "f" :S(V) I "m" :S(W) F(Y) U D "b" REM . B :(Y) V D "f" REM . F :(Y) W D "m" REM . M Y OUTPUT = N ", " N ", bo-" B OUTPUT = "Banana-fana fo-" F OUTPUT = "Fee-fi-mo-" M OUTPUT = N "!" END ``` Ungolfed (plus I added a prompt; the one above just waits for a name to be typed): ``` OUTPUT = "Please enter your name." Name = TRIM(INPUT) UC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' LC = 'abcdefghijklmnopqrstuvwxyz' Low = REPLACE(Name, UC, LC) BName = "b" Low FName = "f" Low MName = "m" Low Consonants = SPAN('bcdfghjklmnpqrstvwxyz') &ANCHOR = 1 Low Consonants . First REM . Rest :F(READY) BName = "b" Rest FName = "f" Rest MName = "m" Rest First "b" :S(BINIT) First "f" :S(FINIT) First "m" :S(MINIT) F(READY) BINIT Low "b" REM . BName :(READY) FINIT Low "f" REM . FName :(READY) MINIT Low "m" REM . MName READY OUTPUT = Name ", " Name ", bo-" BName OUTPUT = "Banana-fana fo-" FName OUTPUT = "Fee-fi-mo-" MName OUTPUT = Name "!" END ``` This is the first SNOBOL program I've ever written. SNOBOL is a line-oriented language, like FORTRAN, COBOL, or BASIC. Each line consists of an optional label starting in column 1, the code for the line which can involve assignments and pattern matching, and an optional branch. Yes, lines end with (optional) GOTOs. They come in two forms: ``` :(TARGET) ``` Branches to label `TARGET`, while ``` :S(SUCCESS) F(FAILURE) ``` Branches to `SUCCESS` if the pattern match succeeded, or `FAILURE` otherwise. You can also just branch on success and fall through to the next line on failure, or vice versa. Continuation lines begin with a `+` or `.`. Comments begin with a `*`. ### How does it work? Read in a name, convert it to lower case. Set up the B-, F-, and M-names assuming it begins with a vowel. Then check if it begins with a span of consonants. If not, we're ready to go! If so, strip the leading consonants and set up the B-, F-, and M-names assuming it doesn't begin with any of those letters. Finally, check if it starts with each of those letters in turn, fixing up the names as needed. Then we're ready to play the name game! Sample run: ``` # $RUN *SNOBOL4 5=GOLF.SNO+*SOURCE* 6=*DUMMY*(1,28)+*SINK*(1,4)+*DUMMY* # Execution begins 16:57:25 Snowman Snowman, Snowman, bo-bowman Banana-fana fo-fowman Fee-fi-mo-mowman Snowman! # Execution terminated 16:57:30 T=0.013 ``` I ran this on the [Hercules](http://www.hercules-390.eu/) S/370 mainframe emulator running the 6.0a release of the [Michigan Terminal System](https://en.wikipedia.org/wiki/Michigan_Terminal_System) using SNOBOL4 version 3.10 from April 1, 1973 built for MTS on May 1, 1975, but there are probably easier ways to run [SNOBOL4](http://www.snobol4.org/) on a modern system. :) **Edit:** Removed a redundant success branch that was equivalent to a fallthrough (I didn't realize I could put just a failure branch by itself) which eliminates an unneeded branch label, and turned an unconditional goto into a failure branch on the prior line, for a savings of 7 bytes. Now that TIO has SNOBOL4 support you can [Try it online!](https://tio.run/##VZDdT4MwFMXf@1dc@yAsgomJTyQ@8OnQUbB8iW@gVKcD1Omm/vN427kw06Q995zkd2667odmWJ2PIzC4gIyHkR6yJM9mBDw0uJ8sbNfXmaHZjuv5weU8vLpeRCxObnia5UV5W91pBjnR6ub@oRWPT8vnl1XXD69v7@uPz8326/tHQ5aDLNpQ8AgEUgolIyk7JY9t5s5jjsaZbE4Tm@kaIpGogIr3h4NTCHGzCF8OVqBXBwV8KuBTAcpQxVaq5zM1CDUUu6FTQzkDBctxAcVSFQ5Y0iykKfZmsDNLaXZ7MyIVxHmGv4e1DKgBdPc0g0nBIVNInbrHYwq8QMg0OEyDtjXF0uxkEJF/zCNKfOaNY9oP267ufwE "SNOBOL4 (CSNOBOL4) – Try It Online") Note: It shows the size as 429 rather than 430 because when I pasted it there, the final linefeed got removed. I tried changing the continuation line (the one beginning with `+`) to a single line, which wasn't legal on the mainframe version because the line was too long, and it worked and brought it down to 427. Obviously CSNOBOL4 allows longer lines. I'm going to leave my score at 430, though, because that's how many bytes the script was on my machine, and besides, SNOBOL is pretty non-competitive. [Answer] ## [J](http://jsoftware.com/), 149 characters ``` 1!:2&2>|.(n,'!');('Fee-fi-mo-';'Banana-fana fo-';n,', ',n,', bo-'),&.>;/'mfb'(,`(}.@])`($:}.)@.((=+.2*5='aeiou'i.]){.)"0 _)a.{~32(23 b.)a.i.n=.1!:1]3 ``` [Answer] **Javascript, 115 Bytes** ``` r=x=>x.match(/[aeiou]\w*/i)[0];f=x=>`${x}, ${x}, bo-b${r(x)}\nBanana-fana fo-f${r(x)}\nFee-fi-mo-m${r(x)}\n${x}!` ``` Explanation: this function returns the name without the initial consonants ``` r=x=>x.match(/[aeiouAEIOU]\w*/)[0] ``` Then the rest is a function returning the string complete string. ``` f=x=>`${x}, ${x}, bo-b${r(x)}\nBanana-fana fo-f${r(x)}\nFee-fi-mo-m${r(x)}\n${x}!` ``` Edit: from 119 to 115 bytes thanks to @Martin Ender [Answer] ## [Clojure](http://clojure.org), 292 characters after minimizing Here's a first attempt, almost positive I can widdle it down further: ``` (defn name-game [n] (let [[b f m] (map (fn [x] (if (some #(= % (first n) (last x)) "bfm") (str (apply str (butlast x)) (apply str (rest n))) (str x (apply str (drop-while (fn [x] (not (some #(= % x) "aeiou"))) n))))) [", bo-b" "\nBanana-fana-fo-f" "\nFee-fi-mo-m"])] (str n ", " n b f m "\n" n "!"))) ``` I'm just learning clojure and thought it'd be fun to give this a shot. Here's my reasoning: > > - To strip off consonants from beginning of string: `(drop-while (fn [x] (not (some #(= % x) "aeiou"))) name)` > > > > - To handle the extra rules for "b", "f" and "m", I broke text into list of phrases: `[", bo-b" "\nBanana-fana-fo-f" "\nFee-fi-mo-m"]` > > > > - Then, I applied a function that asks whether the phrase ends with the same letter that the name starts with, and used that to transform > those 3 phrases based on the rules of the puzzle > > > > - Final step is to build a string with results > > > [Answer] ### Scala 281 I replaced (X) and (Y) in the pattern with `#` and `012`. `S` is just a new name for `String` and `a(b,c,d)` is shorthand definition for `b.replaceAll(c,d)` ``` val v="""#, #, bo-b0 Banana-fana fo-f1 Fee-fi-mo-m2 #!""" type S=String def a(b:S,c:S,d:S)=b.replaceAll(c,d) def r(t:S,n:S,i:Int)=if(n(0)=="bfm"(i).toUpper)a(t,"."+i,n.tail)else a(t,""+i,a(n,"^[^AEIOUaeiou]*([aeiou].*)","$1")).toLowerCase def x(n:S)=a(r(r(r(v,n,0),n,1),n,2),"#",n) ``` Test invocation: ``` val l = List ("Shirley", "Arnold", "Bob", "Fred") for (n <- l) println (x (n) + "\n") ``` And ungolfed: ``` val templ = """#, #, bo-b0 Banana-fana fo-f1 Fee-fi-mo-m2 #!""" val names = List ("Shirley", "Arnold", "Bob", "Fred") val keys = "bfm" def recode (template: String, n: String, i: Int) = if (n(0) == keys(i).toUpper) template.replaceFirst ("." + i, n.tail) else template.replaceAll ("" + i, (n.replaceAll ("^[^AEIOUYaeiouy]*([aeiou].*)", "$1").toLowerCase)) for (name <- names) println (recode (recode (recode (templ, name, 0), name, 1), name, 2).replaceAll ("#", name) + "\n") ``` [Answer] # Python 3, ~~148~~ ~~145~~ 142 bytes *Yes I know it's a little late but...* ``` n=input();i=0 r=n[i:].lower() while n[i]not in'aeiouAEIOU':i+=1;r=n[i:] print(f'{n}, {n}, bo-b{r}\nBanana-fana fo-f{r}\nFee-fi-mo-m{r}\n{n}!') ``` It uses the new [f-strings](https://www.python.org/dev/peps/pep-0498/#how-to-denote-f-strings) to format the resulting string. I don't think TIO supports f-strings yet, unfortunately. **Old Version** ``` def f(n,i=0): r=n[i:].lower() while n[i].lower()not in'aeiou':i+=1;r=n[i:] return f'{n}, {n}, bo-b{r}\nBanana-fana fo-f{r}\nFee-fi-mo-m{r}\n{n}!' ``` *Saved 3 bytes thanks to @officialaimm* [Answer] # Sed, 162 bytes ``` sed 'h;G;G;G' |sed '1s/.*/&, &, bo-b\L&/i;2s/^.*/Banana-fana fo-f\L&/;3s/^.*/Fee-fi-mo-m\L&/;4s/$/!/;tx;:x;s/o-\([bfm]\)\1/o-/i;tz;s/\(o-[bfm]\)[^aeiou]\+/\1/;:z' ``` I did not know sed very well before I did this. I, uh, know it a *lot* better, now. The first sed in the pipeline duplicates the name three times so it becomes "Bob\nBob\nBob\nBob" instead of just "Bob". The next sed does the heavy lifting. Expects input on stdin like `echo Name |sed ...` Ungolfed: ``` sed 'h ;# copy to hold buffer G ;# append newline + hold buffer to pattern G ;# ditto for next two G's G' |sed '1s/.*/&, &, bo-b\L&/i ;# 1st line -> X, X bo-bx (lowercase) 2s/^.*/Banana-fana fo-f\L&/ ;# 2nd line -> Banana-fana fo-fx 3s/^.*/Fee-fi-mo-m\L&/ ;# 3rd line -> Fee-fi-mo-mx 4s/$/!/ ;# bang the 4th line! tx ;# jump to :x if any s/// has matched :x ;# spoiler alert: it has! reset t-flag s/o-\([bfm]\)\1/o-/i ;# match some o-cc where c = [bfm] tz ;# if that matched, branch to :z s/\(o-[bfm]\)[^aeiou]\+/\1/ ;# replace o-[bfm] plus consonants with o-[bfm] :z ;# target of tz, skips over previous s///' ``` A couple of notes. The first four matches, 1s, 2s, 3s, 4s, transform the output into something not quite correct. Bob has become bo-bbob, Fred has become fo-ffred, and Mike has become mo-mmike. Kay would become mo-mkay, mkay? Then, we need to replace either bo-bbob with bo-ob, or bo-bkay with bo-bay. To do that, we can use a feature where we do one s/// substitution, and then branch if it succeeded, jumping over the second one that we now want to skip. But if it missed, we want to fall through the branch and do the next substitution. The t[label] command does that, branching only if a previous s/// matched. But at the beginning of the script I already did one s/// for each line (the leading numbers in 1s, 2s, etc. are addresses; they mean the command is only performed if the address matches). So no matter what line we're on, 1, 2, 3, or 4, at least one s/// has matched. (I tried doing it the other way around, massaging the names and then adding the "Banana-etc." after, but got stuck that way, and trying to do it all at once would cause some repetition.) Fortunately, the flag can be cleared by taking a branch, so we do that with "tx ; :x". tx branches to the x label, and :x is the x label. Whew! That clears the palate for the final two substitutions. We try one, and if it succeeds we branch over the other, otherwise we do the second one. Either way we end up at the :z label and the pattern buffer contains one line of lyrics which is printed to stdout. Thanks for tricking me into spending enough time with the sed man page and Texinfo manual to finally understand how do to more than sed s/foo/bar/ [Answer] # [Go](https://go.dev), ~~193~~ ~~186~~ 173 bytes ``` import(."fmt";."regexp") func f(s string){y:=MustCompile(`^[^AEIOUaeiou]+`).ReplaceAllString(s,"") Printf(`%s, %s, bo-b%s Banana-fana fo-f%s Fee-fi-mo-m%s %s!`,s,s,y,y,y,s)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NVBNS8QwEL33V8RAIcWmZ1nZQ1dc8CCKi6f9sGk3qcF8lCQFS-mP8OylCN70B_lvNmlXHpM3meENb-bzq9bjT0OqN1JTIAlX361j-Orvl8tGG4cyyKSD1xk0tKbvDUwi1qoKMGSBdYarOum7xfK-te5Gy4YLiorD9pDf3j08E8p1u78skuyJNoJUNBdiM2mQTaGf9Ohzx1AR2xSEKDUuYxutiPLAzD-Aacx8aU0pZhxLjaX_xfaiSK1HN8Emw9n0x-QtbIES0EeKSGrBYgm2-9lrDzev3AjawRTA3CgtjiFb6TLQ2tAjHCKmDXhJgzZIDVH-MPOk_t8xjO1OeUko-4OgmacmgjuFMfbtJBqis7FxnPkE) Prints to STDOUT. * -7 bytes by not using explicit indexes * -13 bytes by @The Thonnu by not using the `strings` package [Answer] **Python, 161** ``` x=raw_input('') a,b,c=x[0],x[1:],'bfm' if b[0] in c:b=b[1:] d="X, X, bo-@\nBanana-fana fo-@\nFee-fi-mo-@\nX!".replace('X',a) for y in c:d=d.replace('@',y+b,1) print d ``` Just realised my code fails... - Doesn't remove initial constonants. - Doesn't manage the 'bo-ob' business. It's the furthest I got, maybe somebody can finish it. [Answer] # Groovy, 146 ``` r={n->m={n[0]==it[0]?n[1..-1]:it[1]+(n.toLowerCase()=~'[aeiou].*')[0]};"$n, $n, bo-${m 'Bb'}\nBanana-fana fo-${m 'Ff'}\nFee-fi-mo-${m 'Mm'}\n$n!"} assert ['Shirley', 'Arnold', 'Bob', 'Fred'].collect { r(it) } == [ '''Shirley, Shirley, bo-birley Banana-fana fo-firley Fee-fi-mo-mirley Shirley!''', '''Arnold, Arnold, bo-barnold Banana-fana fo-farnold Fee-fi-mo-marnold Arnold!''', '''Bob, Bob, bo-ob Banana-fana fo-fob Fee-fi-mo-mob Bob!''', '''Fred, Fred, bo-bed Banana-fana fo-red Fee-fi-mo-med Fred!''' ] ``` [Answer] # R, 189 chars ``` x=scan(,'');f=function(b)if(grepl(b,x))sub('.','',x)else tolower(sub('^[^aoueiy]*',b,x,i=T));cat(sprintf('%s, %1$s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%1$s!\n',x,f('B'),f('F'),f('M'))) ``` But with just one more character, you can entry many names in one go: ``` x=scan(,'');f=function(b)ifelse(grepl(b,x),sub('.','',x),tolower(sub('^[^aoueiy]*',b,x,i=T)));cat(sprintf('%s, %1$s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%1$s!\n',x,f('B'),f('F'),f('M'))) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 111 bytesSBCS ``` V"BFM"IqhzN=aYtrz0.?=aY+rN0:rz0"^[^aeiou]+"k))+%." s­ÞXY:lÍ"*]z2@Y0+." o1}1ÃЬÛJî½"@Y1+."-o Âkq°ë¹è"@Y2+z\! ``` [**Test suite**](https://pyth.herokuapp.com/?code=V%22BFM%22IqhzN%3DaYtrz0.%3F%3DaY%2BrN0%3Arz0%22%5E%5B%5Eaeiou%5D%2B%22k%29%29%2B%25.%22+s%05%C2%AD%C3%9EXY%3Al%C3%8D%19%22%2a%5Dz2%40Y0%2B.%22+o1%7D1%C3%83%C3%90%C2%AC%C3%9B%C2%9DJ%17%C3%AE%C2%BD%22%40Y1%2B.%22-o%09%C3%82kq%C2%B0%C3%AB%C2%B9%C3%A8%22%40Y2%2Bz%5C%21&test_suite=1&test_suite_input=Shirley%0AArnold%0ABob%0AFred&debug=0) ### Code uses unprintable characters, and as such does not display properly on Stack Exchange. The link provided contains these characters and is the correct version of the program. [Answer] # [Perl 5](https://www.perl.org/) `-na`, 93 bytes ``` s/^[FMB]//||s/^[^aeiou]*//i;$,=$_.$/;say"@F, @F, bo-b","Banana-fana fo-f","Fee-fi-mo-m","@F!" ``` [Try it online!](https://tio.run/##FYjBCoMwEER/xYacSta1B09SEA@5eeqxaImQ0AXNimkPgt/ebWSYx7xZ/TbXIgnHp@27AfE4zj06T/wdrojUaHPXr1Jjk9yuWmuKsxPDpIzqXMyBkFEEhpAv6z0EgoVhydbaixJ5vGmb/f7j9UMck0Bfl9WtEojuDw "Perl 5 – Try It Online") [Answer] # JavaScript, 100 bytes ``` s=>s+`, ${s}, bo-b${t=/[aeiou].+/.exec(s.toLowerCase())} Banana-fana fo-f${t} Fee-fi-mo-m${t} ${s}!` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NauWDtBR0GlurhWRyEpXzdJpbrEVj86MTUzvzRWT1tfL7UiNVmjWK8k3ye/PLXIObE4VUNTs5bLKTEPCHXTgIRCWr5uGlBbLZdbaqpuWqZubr5uLpgPMlUx4X9BUWZeiUaahlJwRmJ6eqWSpuZ/AA) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~55~~ 54 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` +Si,)²+`¾-b Ba-fa fo-f Fee-fi-¶-m {U}!`rRRiUv e"^%c ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=K1NpLCmyK2C%2bLWIKQoSEYS1mhGEgZm8tZgpGZWUtZmktti1tCntVfSFgclJSaVV2IGUiXiVj&input=IlNoYWdneSI) ``` +Si,)²+`¾...{U}!`rRRiUv e"^%c :Implicit input of string U + :Append S : Space i, : Prepend "," ) :End append ² :Duplicate + :Append `¾... !` :Compressed string "bo-b\nBanana-fana fo-f\nFee-fi-mo-m\n...!" {U} :Interpolate U r :Replace R : Newline with Ri : Prepend newline with Uv : U lowercased e"^%c : Recursively replace RegEx /^[^aeiou]/i ``` [Answer] # [Haskell](https://www.haskell.org/), 151 bytes ``` z x|let y=last$(snd$break(`elem`"AEIOUaeiou")x):[tail x|elem(x!!0)"BFM"]=unlines[x++", "++x++", bo-b"++y,"Banana-fana fo-f"++y,"Fee-fi-mo-m"++y,x++"!"] ``` [Try it online!](https://tio.run/##JYvLCoMwFER/JV5cKBrouuCiQoUuSqGlKxGM9IYG8ygmQpT@exorA8PMGebN7IhShrAS/5XoyFJJZl2aWf1KhwnZmPUoUfVwOl9uT4bCzJD7/Ng6JmT8bGPmk@SQQ91coatmLYVG2/qigJJAUexhMHSIZSmhZjqK8miEG8p32iBSLqgyVP3B9kqgC4oJXX1m93BTusLdKKYh/AA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 152 bytes ``` z x|let y=last$dropWhile(`notElem`"AEIOUaeiou")x:[tail x|elem(x!!0)"BFM"]=unlines[x++", "++x++", bo-b"++y,"Banana-fana fo-f"++y,"Fee-fi-mo-m"++y,x++"!"] ``` [Try it online!](https://tio.run/##JYvLCoMwFER/JV5cKDHQdcFFBYUuSqGldCGCkV4xNA/RCFH672laGRhmzjADn98opfcbcR@Jlqy55LONX5MZn4OQmLTa2FKiauFUnq8PjsIskLpjbbmQ4YRhS1wUHVIoqgs0@aKl0DjXjlLICFC6h86wLpQ1g4LrINYHI71h/U4rRNYLpgxTf/B7RdB4xYXOx8Xe7RRvcDOKa/Bf "Haskell – Try It Online") [Answer] # Python ``` n=raw_input('') if n[0].lower() in ("m", "f", "b"): r=n[1:] else: i = iter(n.lower()) for a in range(len(n)): if i.next() in ("a","e","i","o","u"): r = n[a:] break print "%s, %s, bo-b%s\nBanana-fana fo-f%s\nFee-fi-mo-m%s\n%s!" %(name,name,rhyme,rhyme,rhyme,name) ``` ]
[Question] [ ## Input A single-character string containing an uppercase or a lowercase letter from the English alphabet. Alternatively, you may handle only uppercase or only lowercase letters as input. ## Output [![enter image description here](https://i.stack.imgur.com/JP6XT.png)](https://i.stack.imgur.com/JP6XT.png) This 3x3 typeface of the input letter ([source](https://commons.wikimedia.org/wiki/File:3x3_typeface.svg)), with two distinct, printable ASCII characters of your choice (excluding tabs and newlines) to represent the black and white pixels. They also must be consistent: if a character is used to represent a black pixel for an input, that same character can't be used to represent a white pixel for another input. You may alternatively create a string or list of characters of length 11 (12 if a trailing newline is present) and output that. In this demonstration, the selected characters will be `.` for black and for white: ``` A . ... . . B .. ... ... C ... . ... D .. . . .. E ... .. ... F ... .. . G .. . . ... H . . ... . . I ... . ... J . . . ... K . . .. . . L . . ... M ... ... . . N ... . . . . O ... . . ... P ... ... . Q ... ... . R ... . . S .. . .. T ... . . U . . . . ... V . . . . . W . . ... ... X . . . . . Y . . . . Z .. . .. ``` While a trailing newline is optional, the intermediate newline is required. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to create your solution with fewest bytes possible. It also uses the [standard I/O](https://codegolf.meta.stackexchange.com/q/2447/91472) defined by the community. --- Very thanks to [@emanresuA](https://chat.stackexchange.com/users/497390/emanresu-a) for helping me on The Nineteenth Byte. [Sandbox](https://codegolf.meta.stackexchange.com/a/26213/91472) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḢOị“©Ịı)ḍ6*,ÐÄÄ<Ụ,+ɼɲ4øeọṅịḲ{§*/ṡƑ’Bs9¤s3Y ``` A full program that accepts a single character string in upper case and prints the typeface for that character using `1`s, `0`s and newlines. **[Try it online!](https://tio.run/##AVgAp/9qZWxsef//4biiT@G7i@KAnMKp4buKxLEp4biNNiosw5DDhMOEPOG7pCwrybzJsjTDuGXhu43huYXhu4vhuLJ7wqcqL@G5ocaR4oCZQnM5wqRzM1n///9K "Jelly – Try It Online")** ### How? I don't think there is any pattern to exploit here so this is just a simple compression. (Trying to cater for `A`, `J`, and `S` being the only characters with no ink in the top left pixel is more expensive for example). ``` ḢOị“...’Bs9¤s3Y - Main Link: list of characters e.g. "A" Ḣ - head 'A' O - ordinal -> Ord 65 (N.B. 65 % 26 = 13) ¤ - nilad followed by links as a nilad “...’ - a big number B - convert to binary -> flat list of pixel values of O, P, Q, ..., Z, A, B, ..., N (indices: 1 2 3 12 13 14 ... 26(0)) s9 - split into chunks of length nine -> 26 binary lists ị - {Ord} index into {that} [0,1,0,1,1,1,1,0,1] (1-indexed and modular) s3 - split into chunks of length three [[0,1,0],[1,1,1],[1,0,1]] Y - join with newline characters [0,1,0,'\n',1,1,1,'\n',1,0,1] - implicit, smashing print ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 95 bytes ``` c=>`2i2owi3ukgacum8 193s0cuufnghmk0 004zspr9y5072pg`.replace(/.{5}/g,n=>parseInt(n,36)>>c%26&1) ``` [Try it online!](https://tio.run/##bY6xDoIwFEV3vqKLpg2IBQQlWhYnZ3@AprYVhdemBY0avh2ZjdO5ObnDufEH98I1tl@BuchJsUmwqk6b1DybbLhrLoZuFyRl5qkYBgX62t1pQOnm7a0rXzndplbXsZO25ULidfzJx7WOgFWWOy9P0GOIsoJUlVikxTIhkzIOt7JHgBgq8v3MA0MlnUcYEvQJEBIGvGll3BqNz71rQMfKme545e44R2IgZP9zU//kLMbpCw "JavaScript (Node.js) – Try It Online") Inverse view of Arnauld [Generator](https://tio.run/##TZFrb4IwGIW/v7@iXxbbrXsjuLglpibM3e/T3ZEEgqAsDhTYgr@elYLFD4X34Zz2nIZv78/L/DRa5YdxMgvKQpSuBQQJICIgQYBTOTYoF4wapf4EZ7VKUL3hvDE26kWLcgNc7pileqVHFXStxm023AAh2JpvdYgy39UVtjXudUGlPuhR4WOLlflpxyxbPWusAmHcXrBSJ7LRtpXEF12yWvCqQ9TJbxqV@t5esFI/tKJafWpU5i8VUCO65cAStjOAArPVMsrdaTyNXfzxVnQjhpa9sbsO@gsvHcm/ZuWU7Zl9R2zYAPwkzpJlgMtkTi3JoYjlBkyD2a8fjKP5Iqe04D4Tw2LfPKC@HTtCdEiH8S6DMEnpmiShbfIeP@J9fsxPuNHlhsEN02G7Z695SNdMPTBPJnkaxXPa6zNW/gM) # [JavaScript (Node.js)](https://nodejs.org), 94 bytes ``` c=>`05mo1jcsjkjz8ej zffuo1yte4zibec vkdfk5502pbswtk`.replace(/.{5}/g,n=>parseInt(n,36)>>c-1&1) ``` [Try it online!](https://tio.run/##bY6xDoIwFEV3vqKTaQMiqDUaLQuTsz9AKa9IwZa0FSOGb0dm43RuTu5wFB@4E7bp/VqbCmbJZsGyIqEPkyrhVKvGI6hglPJp0reH/diUIIKhrWRLabLtS/fybRFb6DsuAG/iD502daRZ1nPr4Ko91tHuQLJMrNNVSmZpLO7AI40YOtDzwgtDp2QZYUjQJ0BIGO1MB3FnanzzttF1LK155Hdu86URa0LOPzf5Ty5imr8 "JavaScript (Node.js) – Try It Online") Use 32-bit fact [Answer] # JavaScript (ES6), 119 bytes Expects the ASCII code of an upper case letter. Returns a string of 0's (white) and 1's (black). ``` c=>`876 543 210`.replace(/./g,n=>parseInt("DDEED5CAAA99B5CDBDDBAD3A8E"[c%=26]+"PR41GYY72NHE79FJYZWZL33D75"[c],36)>>n&1) ``` [Try it online!](https://tio.run/##bY5Ba4MwAEbv/oogbCTY2WoarXQRonHtShljPRQ7Cg1ZdB0ukSi7jP12l/PY6Xs83uH7EF9ikPbaj3favKmpoZOk@WWVJh5ZYi@OFpfQqr4TUsF5OG9nmua9sIN61CP0Oa8qTkrGWJYVpOQF5wXjmK0q/1Xe0Dg5B/7zyzLa1HUaP22rNHvY1afjaY8xT4lrzjOcoDzXtxGaGmNhp0agAQUJWbu9pyBbOAgCBL49AKTRg@lU2JkWHkZ71W3YWPNZvgtbuvNQI7T@kzX/SSd@pl8 "JavaScript (Node.js) – Try It Online") NB: In order to have each typeface encoded as two characters, we can actually use any base in \$[23\dots36]\$ (because \$\log\_{23}2^9\approx1.99\$, while \$\log\_{22}2^9>2\$). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` ⪪§⪪”{∨&×⊞ΦVRvRμΣ⧴WςCZ¦±✳Z“…⎚\`AW⦃$z↶c(�”⁹℅S³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4ICezRMOxxDMvJbUCylPSAwIFMNKDkRCgoIBCAykFBbBCqGoFsBCKXgUohJmgB1cAVQwxRQ@mSAHVSphNSOLIZiH0IZNQ1SheQLYKYYCSjoKlpo6Cf1FKZl5ijoZnXkFpSXAJMGTSNTQ1gRLGmprW//97/9ctywEA "Charcoal – Try It Online") Link is to verbose version of code. Takes the input letter in upper case. Explanation: ``` ”...” Compressed bitmap of `.`s and spaces ⪪ ⁹ Split into groups of length 9 § ℅S Cyclically index by the ordinal of the input letter ⪪ ³ Split into 3 lines Implicitly print ``` The compressed string starts with the bitmap for `N` as its ordinal is `78` which is a multiple of `26`. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 176 bytes The function takes as input only uppercase letters. ``` def g(c): o=bin([-233,25,65,8,81,78,9,-41,49,-311,-49,-127,87,71,73,86,83,62,-208,44,-55,-60,-39,-81,-84,-19][ord(c)-65]+422)[2:].zfill(9) return o[:3]+'\n'+o[3:6]+'\n'+o[6:] ``` [Try it online!](https://tio.run/##TY9LT4UwFIT391c0cVEaTm9oC6U0ceH7/X5bWSgXlIS0pMGF/nk8Lrxxdb7MTM5kxq/pI3hlxjjPq7Yj70nD7IKEzbfeJ45LpUAWoAswYASUBirguYAcjxICGUHIEkwJJfoKjAajQEvgMjOQ58CLArjOMI9R/MENaqKqXYgrLOO6qNNcSuakrZffXT8MScUWJLbTZ/QkOKvqlL54mganrF6ztvXchUga0ntCt7Z3dvf2Dw6Pjk9Oz84vLq@ub27v7h8en54prhlj7yfs@qPfkcvYjsNr0yZUUKAb9J@QoUAoW8fZ/AM "Python 3.8 (pre-release) – Try It Online") --- # [Python 3.8](https://docs.python.org/3.8/), 231 bytes (letters and numbers) The function handles both uppercase letters and numbers. ``` def g(c): o=bin([85,-3,-7,69,-33,-196,-91,47,-155,95,-221,37,77,20,93,90,21,-29,61,-299,-37,-115,99,83,85,98,95,74,-196,56,-43,-48,-27,-69,-72,-7][ord(c)-(48 if c<'A'else 55)]+410)[2:].zfill(9) return o[:3]+'\n'+o[3:6]+'\n'+o[6:] ``` [Try it online!](https://tio.run/##TZBJT4RAEIXv8ys68dAQigm90d1ED@O@7ztyUAaUhNCkxYP@eSw0TjxU6uXlq1eV6j@HN9cJ0/txXFY1eQ3KMJsRt/HSdEFuFMQCYg2pRYGK2RRiy0Bq1EqBRYBzBkKD1sATsAJsAujE3EL606bRCWeIWzACMNWaaVTL30SFoRLTpUEe0Wmb5lhF7vwSL4oDaUhTk3KdLmjVvldEqbCIJEvCnGfF/Ktu2jaw4Yz4avjwHXF5JoqIPnU0crnI0pVOs2KsnSclaTpCE8aFVKk2drG5tb2zu7d/cHh0fHJ6dn5xeXV9c3t3//BI8R29b7oB7/hT05fmvurb57IKKKNA1@g/I0GD0HCFh@M3 "Python 3.8 (pre-release) – Try It Online") --- Commented code (letters and numbers) ``` def g(input_char): # each character pixmap is encoded using '1' for filled and '0' for gaps, excluding newlines # resulting in a binary string ('0' -> '111101111') # the binary string is converted into a decimal value # the decimal value is offset by 410 to reduce the length of the pixmap list # pixmap of characters '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' pixmap = [85,-3,-7,69,-33,-196,-91,47,-155,95,-221,37,77,20,93,90,21,-29,61,-299,-37,-115,99,83,85,98,95,74,-196,56,-43,-48,-27,-69,-72,-7] # select the pixmap corresponding to the character # using the ascii value char_pixmap = pixmap[ord(input_char) - (48 if input_char < 'A' else 55)] # account for the offset char_pixmap += 410 # build the binary string representing the pixmap for the characters # '1' for filled, '0' for gaps output = bin(char_pixmap)[2:].zfill(9) # insert newlines return output[:3] + '\n' + output[3:6] + '\n' + output[6:] ``` ]
[Question] [ [Bitshift Variations in C Minor by Robert Miles](https://soundcloud.com/robertskmiles/bitshift-variations-in-c-minor) is a Code Golf music piece written in C (with some additional bash commands). It was originally presented in a 2016 Computerphile video [Code Golf & the Bitshift Variations](https://youtu.be/MqZgoNRERY8). You can listen to clean renderings of it [here](https://ceionia.com/bitshift) (by Lucia Ceionia). The [original 2016 source code](https://web.archive.org/web/20150719123218/https://txti.es/bitshiftvariationsincminor) presented in the description under the YouTube video was **245** characters long: ``` echo "g(i,x,t,o){return((3&x&(i*((3&i>>16?\"BY}6YB6%\":\"Qj}6jQ6%\")[t%8]+51)>>o))<<4);};main(i,n,s){for(i=0;;i++)putchar(g(i,1,n=i>>14,12)+g(i,s=i>>17,n^i>>13,10)+g(i,s/3,n+((i>>11)%3),10)+g(i,s/5,8+n-((i>>10)%3),9));}"|gcc -xc -&&./a.out|aplay ``` A [tweet from 2017](https://twitter.com/robertskmiles/status/945353932645249024) (or some other Rob Miles tweet, not sure) stands **216** characters: ``` gcc -xc -oa -<<<'i;n;g(x,t,o){return(3&x&(i*((3&i>>16?"BY}6YB6%":"Qj}6jQ6%")[t%8]+51)>>o))<<4;}main(s){for(;;)putchar(g(1,n=++i>>14,12)+g(s=i>>17,n^i>>13,10)+g(s/3,n+(i>>11)%3,10)+g(s/5,8+n-(i>>10)%3,9));}';./a|aplay ``` Another version using only **185** characters (written by [MayMeta](https://manifold.markets/MayMeta) from Manifold Markets): ``` gcc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;)putchar(g(8,n=++i>>14,8)+g(n,n^(s=i>>10)/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5));}';./a|aplay ``` Will someone be able to shrink it down below 185 characters, or the limit has been reached? Extra Credit (Resolution criteria for a related [betting market](https://manifold.markets/MayMeta/code-golf-challenge-can-bitshift-va?r=YnJ1YnNieQ)): * The bash command compiles the C source code and runs + plays it using aplay (or similar) * You ARE allowed to slightly change the played notes, but their relative frequencies should not differ more than 1.4% from the original, and the entire piece should not be shifted more than one semitone (6%) from the original. * Compiles and works as intended on an average linux machine. * Does not use the internet A winning entry will be the shortest entry that is less than 185 characters, and follows the Extra Credit guidelines. Entries that do not follow the extra credit are appreciated, but will not be selected as the winner. Solutions that could be argued to be following the spirit extra credit guidelines in their attempt to get under 185 will be considered to be winners as well, as it's a bit subjective. Related Links: [Deep analysis of Bitshift Variations in C Minor code](https://sylphe.ch/bitfiddle/index.html) [BitShift-Variations-unrolled](https://github.com/JamesNewton/BitShift-Variations-unrolled) [Bitshift Variations Humanized + Rust version](https://github.com/Bitshift-variations-humanized) [Answer] ## 183 bytes This isn't a big improvement or super impressive or anything, but saves 2 bytes in the main loop with some rearranging. ``` gcc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10;}';./a|aplay ``` The changes are more visible when they are put side by side: ``` for(;;)putchar(g(8,n=++i>>14,8)+g(n,n^(s=i>>10)/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)); for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10; ``` [Answer] # 182 "Compiles and works as intended on an average linux machine."... In common distros, cc is symlinked to gcc. Thus the first byte can be shaved off. ``` cc -xc -oa -<<<'i;n;g(m,t,o){return("GTj?TG?5"[7&t]+!(n&12|t&2)*9)*i>>o&m&24;}main(s){for(;;putchar(g(8,n=s>>4,8)+g(n,n^s/8,6)+g(n/3,n+s/2%3,6)+g(n/5,n-s%3,5)))s=++i>>10;}';./a|aplay ``` ]
[Question] [ Your task is to create a program or function, that when given an input list of nonnegative integers of length \$l \ge 2\$ and a nonnegative integer \$c\$ where \$2 \le c \le l\$, group the list into \$c\$ "clusters." What this means is, the average (population) [variance](https://en.wikipedia.org/wiki/Variance)\* of all the groups should be as low as possible. For example, `[[0, 3], [4, 6]]` has an average variance of \$\frac{\frac{\left(0-\frac{0+3}{2}\right)^2+\left(3-\frac{0+3}{2}\right)^2}{2}+\frac{\left(4-\frac{4+6}{2}\right)^2+\left(6-\frac{4+6}{2}\right)^2}{2}}{2}\$ or \$1.625\$, while `[[0], [3, 4, 6]]` has an average variance of \$\frac{\frac{\left(0-\frac{0}{1}\right)^2}{1}+\frac{\left(3-\frac{3+4+6}{3}\right)^2+\left(4-\frac{3+4+6}{3}\right)^2+\left(6-\frac{3+4+6}{3}\right)^2}{3}}{2}\$ or \$\frac{7}{9}\$, and \$\frac{7}{9} < 1.625\$, so the latter is the correct output for the first test case. The result will have the closest numbers placed together and the farthest numbers placed in different groups. \*This is calculated by squaring the distance between all the numbers in the list and the mean of it, and then taking the mean of those squared distances. # Rules * Groups and numbers inside of the groups can be in any order. * When there are multiple possible outputs with the same average variance, any of them is acceptable. * Each group must have at least one number. * Input and output may be in any convenient format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. # Test Cases ``` Input Output (sorted) [0, 3, 4, 6], 2 [[0], [3, 4, 6]] [0, 1, 2, 3], 2 [[0, 1], [2, 3]] [0, 1, 2, 3, 4], 2 [[0, 1], [2, 3, 4]] or [[0, 1, 2], [3, 4]] [10, 13, 6, 11, 8], 3 [[6, 8], [10, 11], [13]] [4, 2, 9], 3 [[2], [4], [9]] [1, 19, 8, 12, 3, 19], 3 [[1, 3], [8, 12], [19, 19]] [8, 8, 8, 8], 2 [[8], [8, 8, 8]] or [[8, 8], [8, 8]] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes ``` søṖ'L⁰=;‡ƛṁ-²ṁ;∑∵ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJzw7jhuZYnTOKBsD074oChxpvhuYEtwrLhuYE74oiR4oi1IiwiIiwiWzEwLCAxMywgNiwgMTEsIDhdXG4zIl0=) ``` s # sort øṖ # all partitions ' ; # filter by: L # length = # is equal to ⁰ # last input ‡ ∵ # minimum by: ƛ ; # map: ṁ- # subtract mean ² # square ṁ # mean ∑ # sum ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 51 bytes ``` {.y@*<+/'x''a*a:y-x''y@:='+z\&z=#'?'+!z|^y}{+/x%#x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdjEEKgzAQRfc5xS/SjhqqHRMkxko9iAhuPEMS9e5GQRdlNv89/p/ZLoXv868syRFN+WT9Owbf245kGF6hS+hH8hHW0W+LLN0zcZsQc0Fp+oGCRt2iygQQkVFB/SH0JTgahRrMMC3U6XSsNBcwuIEBHyu+rcF5x5dsB1jAIqw=) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~45~~ 44 bytes ``` I⊟⌊EΦEXηLθEηΦθ⁼λ﹪÷ιXηξη⌊ι⟦ΣEι∕ΣEλΣX⁻νλ²XLλ²ι ``` [Try it online!](https://tio.run/##TU7JCsIwEP2VOU5hBKsggkcXEBQKHksPoS12IE26pOrfx4mNYi55eWvKRg2lVdr7bGDjcK9Gh5nt8MqG26nFq@rwxNrVwwdm9imoIbjU5u4a7JOEIAhCRVtPcOwnpUfUItlq0hbPxh34wVWNTPDreIVwk4QjzjjI4ZHf4rTYY/DLSGmAc4mEphENgZbQai6alfi/P56Lz9LO@zxPlwTpmmAjV0qwLQjWhV889Bs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` EXηLθEηΦθ⁼λ﹪÷ιXηξη ``` All permutations of the input list elements into `c` clusters... ``` Φ...⌊ι ``` ... where no cluster is empty... ``` E...⟦ΣEι∕ΣEλΣX⁻νλ²XLλ²ι ``` ... calculate the doubled variance of each cluster... I⊟⌊... ... output the clusters with the minimum. Edit: Saved 1 byte by calculating the doubled variance using the last [alternative variance formula for finite populations](https://www.probabilisticworld.com/alternative-variance-formulas-derivation/#h-finite-populations): $$ \textrm{Variance(X)} = \frac{1}{2N^2} \cdot \sum\_{i=1}^{N} \sum\_{j=1}^{N} (x\_i - x\_j)^2 $$ [Answer] # JavaScript (ES7), 182 bytes Expects `(list)(c)`. ``` a=>m=c=>eval("for(q=c**a.length;p=a.slice(-c).map((_,j)=>a.filter((_,i)=>!(q/c**i%c^j))),q--;)p.some(A=>A.map(v=>s+=(v-eval(A.join`+`)/w)**2/w,w=A.length)=='',s=0)|s>m||(m=s,o=p);o") ``` [Try it online!](https://tio.run/##fVDdboIwFL7fU3Qmiy2WP3UGYg4Jz2HYbBg4CFAEgze@OzstuEUh44Kmp9/f@XLRiTZusvpiVvIr6VPoBQQlxBAknSjoIpUNPUNsGMIqkup0@d7XIKy2yOKEmjGzSlFT@slzBoGw0qy4JI26Z3h/pWcbidlb/JEzxvjZNPestlpZJjSEINTcDoJ2BbQztV1o5TKrjqsjs6/MMNb2lV8hHJ0ZwHLJW3DYrQ3K242W0HIJNdvLBetjWbWySKxCnmhKDxtOHE62nOwiRteMkd/Ptsnh4EScKIwGRC9PZGS6nKw52cyT8VnxNeAfMso/8CdkBYiIbMYxsu6xprKuQuDTDg9Eeqi8GZS17E6NkKxh2sCdybbVwfw/7uNi2n6rfv5MABT20QWPIbt719FcV5WBTP2u/X0Nmeh4WsMbVpiW640iGjCW443LPc/u4zkTLAJ7wqhYmvv@ZzWEdYYW1SaqVAQMOv0P "JavaScript (Node.js) – Try It Online") ### Commented This is a version without `eval()` for readability. ``` a => // a[] = input list m = // initialize m to a non-numeric value c => { // c = number of clusters for( // main loop: q = c ** a.length; // start with q = c ** a.length p = a.slice(-c) // p[] = partition of length c .map((_, j) => // for each value in p[] at index j: a.filter((_, i) => // for each value in a[] at index i: !( // keep the value if q / c ** i % c // floor(q / c ** i) mod c ^ j // is equal to j ) // ) // end of filter() ), // end of map() q--; // stop once q = 0 has been processed ) // p.some(A => // for each array A[] in p[]: A.map(v => // for each value v in A[]: s += ( // add to s: v - // v minus eval(A.join`+`) // the sum of all values in A[] / w // divided by w (the length of A[]) ) ** 2 / w, // squared and divided by w again w = A.length // initialize w ) // end of map() == '', // trigger the some() if A[] was empty s = 0 // start with s = 0 ) // end of some(); if the result is falsy | s > m || // and we don't have s > m: (m = s, o = p); // update the minimum and the output array // (implicit end of for) return o // return the output array } // ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 195 bytes ``` f=([c,...x],n,L=P=x.slice(-n).map(_=>[]))=>1/c?L.map((_,i)=>f(x,0,L.map(x=>i--?x:[...x,c])))&&P:P=B(P)<B(L)?P:L;A=x=>x.map(t=>X+=++Y&&t,X=Y=0)+x?X/Y:1/0;B=L=>A(L.map(x=>A(x.map(v=>(v-A(x))**2)))) ``` [Try it online!](https://tio.run/##PY3RaoQwEEX/RmbWSTRbCsXtRPQ5D3lURBZJtVhcXVaR/L1Nd6EwL/dwz52fbu9W9xjvm5iXr/4YOBw0jqSUvqWZDFv2cp1G14OYUd66O1xZNy0ia5W43DwRXGkMYABPKb2QZz0Kkfus@dsiFwyMIptZLsHiZwkGc5uZS8Gh6Z/KxrqKOY7rKNqo4ppTjH1eJXWmkvRSsmFdwP96AS9rZw27CAnxdDqHL3i4ZV6XqZfT8g0DNB@kUlKK1JnUG6n3lkLt@AU "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {.œʒg²Q}ΣεDÅA-nÅA}O}н ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/Wu/o5FOT0g9tCqw9t/jcVpfDrY66eUCi1r/2wt7//6MNDXQUDI11FMyAlKGOgkUslzEA "05AB1E – Try It Online") Port of AndrovT's Vyxal answer. #### Explanation ``` {.œʒg²Q}ΣεDÅA-nÅA}O}н # Implicit input { # Sort the first input .œʒ } # Filter its partitions by: g # Length of list ²Q # Equals the second nput Σ }н # Minimum by: ε } # Map: ÅA # Get mean D - # Subtract n # Square ÅA # Get mean O # Sum # Implicit output ``` ]
[Question] [ A doubly linked list is a data structure in which each node has a `value` as well as "links" to both the `previous` and next `nodes` in the list. For example, consider the following nodes with values 12, 99, and 37: [![](https://i.stack.imgur.com/pOb9x.png)](https://i.stack.imgur.com/pOb9x.png) Here, the nodes with values **12** and **99** point to their respective `next` nodes, with values **99** and **37**. The node with value **37** has no `next` pointer because it's the last node in the list. Likewise, the nodes with values **99** and **37** point to their respective `previous` nodes, **12** and **99**, but **12** has no `previous` pointer because it's the first node in the list. ## The setup In practice, a node's "links" are implemented as pointers to the previous and next node's locations in memory. For our purposes, the "memory" will be an array of nodes and a node's location will be its index in the array. A node can be thought of as a 3-tuple of the form `( prev value next )`. The above example, then, might look like this: [![](https://i.stack.imgur.com/liGYq.png)](https://i.stack.imgur.com/liGYq.png) But it might look like this, instead: [![](https://i.stack.imgur.com/rBCuR.png)](https://i.stack.imgur.com/rBCuR.png) Starting at any node, you can follow `previous` links (shown as the origins of the red arrows) to get to the nodes that precede it and `next` links (green arrows) to find subsequent nodes in order to get all of the nodes' values in order: `[12, 99, 37]`. The first diagram above could be represented in an array as `[[null, 12, 1], [0, 99, 2], [1, 37, null]]`. The second, then, would be `[[2, 99, 1], [0, 37, null], [null, 12, 0]]`. ## The challenge > > Write a program that takes as input an array of nodes and the index of a node and returns, in list order, the values of the nodes in the same doubly linked list. > > > ### A complication The "memory" won't always contain the nodes of just one list. It might contain several lists: [![](https://i.stack.imgur.com/oOWj2.png)](https://i.stack.imgur.com/oOWj2.png) The above array contains three doubly linked lists, color-coded for your convenience: 1. The nodes at indexes `7`, `10`, `1`, `4`, `3`, `12` (showing only `next` links to reduce clutter; click to enlarge): [![](https://i.stack.imgur.com/jpPPq.png)](https://i.stack.imgur.com/jpPPq.png) Given this array and any of these indexes, your program should return, in order, the values `[0, 1, 1, 2, 3, 5, 8]`. 2. The node at index `9`: [![](https://i.stack.imgur.com/1nDnu.png)](https://i.stack.imgur.com/1nDnu.png) Given the index `9`, your program should return `[99]`. 3. The nodes at indexes `11`, `8`, `0`, `6`, `2`: [![](https://i.stack.imgur.com/H40LR.png)](https://i.stack.imgur.com/H40LR.png) Given one of these indexes, it should return `[2, 3, 5, 7, 11]`. ## Rules ### Input Your program will receive as input: 1. A list of 𝒏 nodes (3-tuples as described above), where 1 ≤ 𝒏 ≤ 1,000, in any convenient format, e.g. an array of arrays, a "flat" array of integers with length 3𝒏, etc. The 3-tuples' elements may be in any order: `( prev value next )`, `( next prev value )`, etc. For each node, `prev` and `next` will be `null` (or another convenient value, e.g. `-1`), indicating the first or last node in a doubly linked list, or a valid index of the list, either 0- or 1-based as is convenient. `value` will be a signed 32-bit integer or the largest integer type your language supports, whichever is smaller. 2. The index 𝒑 of a node in the list (1). The indicated node may be the first node in a doubly linked list, the last node, a middle node, or even the only node. The input list (1) **may contain pathological data** (e.g. cycles, nodes pointed to by multiple other nodes, etc.), but the input index (2) will always point to a node from which a single, well-formed output can be deduced. ### Output Your program should output the values of the nodes of the doubly linked list of which the node at index 𝒑 is a member, in list order. Output can be in any convenient format, but its data must include only the node `value`s. ### Winning This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. Standard loopholes apply. ## Test cases Below, each test case is of the form: ``` X) prev value next, prev value next, ... index value value value ... ``` ...where `X` is a letter to identify the test case, the second line is the input list, the third line is the 0-based input index, and the fourth line is the output. ``` A) null 12 1, 0 99 2, 1 37 null 1 12 99 37 B) 2 99 1, 0 37 null, null 12 0 1 12 99 37 C) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5 4 0 1 1 2 3 5 8 D) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5 0 2 3 5 7 11 E) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5 9 99 F) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15 18 80 80 67 71 G) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15 8 1 -1 1 -1 1 -1 1 H) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15 4 1 3 6 10 15 21 I) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15 14 3 1 4 1 5 9 2 6 5 3 J) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15 17 8 6 7 5 3 0 9 K) 4 11 0, null 22 3, null 33 3, 1 44 4, 3 55 null, 7 66 7, 6 77 6 3 22 44 55 L) null -123 null 0 -123 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~79~~ ~~65~~ ~~59~~ 55 bytes **-6** bytes thanks to [Brute Force](https://codegolf.stackexchange.com/users/48198/bruce-forte). ``` x#i|let-1!d=[];i!d=i:x!!i!!d!d=[x!!i!!1|i<-last(i!0)!2] ``` Defines function `#` that accepts a list of lists of integers, where `null` is represented as `-1`, and returns list of node values. [Try it online!](https://tio.run/##7VZLasMwEN3nFDLpIgEZrJEs2W3TG/QErimBBiqahFB7kUXuns5HckJvYEjAeCTPm3nzngj63g4/u/3@ej0v42W/G0tTfG26/iXiKz6fiyIWxRdtSWgu8bXcb4dxFYtqXUB/PWzjUW3UYXt6/1Srj9V50CquVfmmTr/xOKondR6WuDHuhnFYLBb8RkC3UPhbdV1ptDKAT69VV2nVtloBxbhvg1al6XFl1joDQHJyfsrBRa5U/QM0WtVaea6JAMxyFHsMTcY6LETo1BirWA4xaHIOYkPiRq2oVMVJhsFV/kDsBBG420SOilFsmVBNNN08aFbzoNneaBrcbqgo5xhsGyZ6NfXCp82kTCpl6OxNaRYjnw9j4C7Ac4NnvrZK7ZlNPR1BXPC4EBhvAhdw8oXFgkZANmOIKVcDDChTCFghwDwBt5GetVn5kFzA0IekC81SJ0esDGbcHTErWS1LLFO2iX@TxSd1uHDDEMnyjAgT3@wWWGkiItUiEiS3JudAPJ0kwhjEbM8@GnbPNA/7Zmzfw705u@ce7s35r/Nh36ztCzf7nFykpvsPwJ1apItNtyrn8rhYv767JHmf@NKbtcKFvXUoeTaw@W5drflLf/0D "Haskell – Try It Online") ## Explanation ``` let-1!d=[];i!d=i:x!!i!!d!d ``` Define function `!` that iterates through the nodes starting at node `i` and returns a list visited indexes. It accepts the second argument `d` that specifies which index of the "tuple" use as the index of the next node (`d==2` to iterate forwards, `d==0` to iterate backwards). ``` (i!0) ``` Iterate backwards starting from the given index and return visited indexes. ``` last(i!0) ``` Take last visited index, which is the beginning of the list. ``` last(i!0)!2 ``` Iterate from the beginning of the list. ``` [x!!i!!1|i<-last(i!0)!2] ``` Replace each visited index with the value of the node. [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` l,n=input() while~n:m=n;n=l[n][0] while~m:p,v,m=l[m];print v ``` [Try it online!](https://tio.run/##NY7NCgMhDITvfYocW8iCuu4/Pol4LKygqZTtll766jZKvX2TmUmSPsf@IJVzQDKe0uu43i7v3Yf7l9ZoaCMTLDkr3H8a14QnRp5Gt6WnpwPOnK2dEQaE0SFYKRAkgi48MjJ3sgiN0LNWNYSgWFZkmFuGuxNbBTvOlFWihmQti2YsS2tM9ZpsRllWuK8PDc6h/gE "Python 2 – Try It Online") This is pretty much Chas Brown's answer, minus these golfs: * I reuse n, saving an assignment * I store the last valid n in m, allowing me to * place the print after the assignment in line 3, saving me the final print * I use only ~n instead of -~n, because negative values are just as truthy as positive ones, saving me 2 characters. [Answer] # [Clean](https://clean.cs.ru.nl), ~~94~~ ~~90~~ 88 bytes ``` import StdEnv $l[_,u,v]|v<0=[u]=[u: $l(l!!v)] ?l= $l o until((>)0o hd)((!!)l o hd)o(!!)l ``` [Try it online!](https://tio.run/##NY7NasMwEITvfoo1yUEGGaTE@St1ckkPhd5yFCII220EshRi2aTQZ6@6UvFB8M3O7Goa0ykbeteOpoNeaRt0f3cPDxffvtkpWxpxpSOd5M/0ymoxSnwvsDTE5PlUyOxkalTgYLReG0KOBXNwawtC8ryIc2SXOFy8evhsAUYPHmoQYk9hQ2ErKQjOKHAKVeQtInLJo6gorFGvUojCCmVChP2cwd0dWhFLzMRTLIV4WmazcTjMG7v0G5@NeCzyOhXaSIkttW27J9asshpO/53TKPw2n0Z9DaF8/wjnb6t63Qx/ "Clean – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 39 bytes ``` XHx`HwI3$)t]x6Mt`Hwl3$)tbhwt]x4L)Hw2I$) ``` [Try it online!](https://tio.run/##HYsxCsMwEAT7vGILNyIYdDpJttEHZEj6gBEkqVI4nUD@vXy@apnZ3f@n7r2/8vHObeXB1HLEZxXYL/j@mgj/MLm5dTC9bwQLKvdtRkBMICH4hAgijJTgwSAnBRxYwmFWbzFB9Kh/m645w6pYFl1M8iEV8knSBoRy4xM "MATL – Try It Online") Almost a direct port of my Octave answer, but this version finds the end first, and then works it way back, rather than the other way round, which saved one byte. ``` XHx % Store array in H. `HwI3$)t] % Work to the end of the array x6Mt % Delete the end of array delimiter, and push the array end index twice `Hwl3$) t] % Work to the beginning of the array tbhw % Append all indices found. Hw2I$) % Index into original array. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` è[¬D0‹#Isè]\[`sˆD0‹#Isè]¯ ``` [Try it online!](https://tio.run/##TVAxTgRBDOt5xUi0g7SZ7O7M9tfwhmElQOIF9wEq3nIFEjXtXckv@MhiO9zqOie2EyfD9PJqb9t2OfXz52H4ff@@fzxeTutTfz7@fNw0zl/bZuNd7@Y5tSEna2tO3VpO1XJ6MFYT2qQWUQUIWuElp7LLHGhGQ0zNCbYysyjowu@DVJSDmVgQsXDJqvxWNWAMZhTTwuRXD5NqWgGgMgJ4BFDOgjbiuTyMz@nEgDOwHLwFMbXE4zAbb4J5qDjneuXynz8eYDrTNLjJEqpZjrrn5Qc1ymNJPGmKJ6moihtu/hTC/UXARXbjecy8rn8 "05AB1E – Try It Online") ## Explanation ``` è[¬D0‹#Isè]\[`sˆD0‹#Isè]¯ # Arguments n, a è # Get element at index n in a [¬D0‹#Isè] # Find the first element in the list [ # While true, do ¬ # Head (get index of previous element) D0‹# # Break if lower than 0 Isè # Get the element at that index ] # End loop \ # Delete top element of stack [`sˆD0‹#Isè] # Iterate through list [ # While true, do `sˆ # Add value to global array and keep next index on stack D0‹#Isè # Same as above ] # End loop ¯ # Push global array ``` [Answer] ## PHP, 132 bytes ``` <?list(,$x,$y)=$argv;parse_str($x);while(($q=$x[$y*3+1])>=0)$y=$q;do{$n[]=$x[$y*3+2];$y=$x[$y*3];}while($x[$y*3]);echo join(' ',$n); ``` [Try it online!](https://tio.run/##ZVLRboMwDPyVPkQt2UAiCRBQyvYhFZqqDRWmCiigDjTt15dt2EyOeLIuZ9/ZB13VWXt8vtbD6Pls8tnMc3buL3fTnfuhfBnG3mMTNx9VfS09j91yNp3Y/KAeRcGf8pCzOWc389Z@suZU/JOyMH8EoMJ8wfiKuSlfq3b33taNd9gdfNZwY62dfgVEul@KWkoaLiUQe8JpRNlSYgDQiMMSijML3RIQNCgACTxBEZqoqpBSCJCi4tJBggpJTT0ioCLSB6MypQrO1ZiBQCtAoCDhKKWIBwK0ygiDGWliDi@JpproFtNVFU1Uie21axDZ9qbM6U7oMbFzJ5GjoSm6vNsrafq4AW4abw00WSemf4OiyQb0bU0BP58V0XfbjXXbDDZofgA) Input is taken as a querystring `x[]=-1&x[]=1&x[]=1...` (all nodes in a flat array), in the order of `next`, `prev`, then `value` for each node with -1 used for ending nodes. [Answer] # [Python 2](https://docs.python.org/2/), ~~81~~ 77 bytes ``` a,n=input() u=a[n][0] while-~u:u,v,w=a[u] while-~w:print v;u,v,w=a[w] print v ``` [Try it online!](https://tio.run/##PY5LCsMgEIb3nmKWLYygxjxLTiIusihEKFZKjHTTq9tRanff/xoN72N/epXzhn51PsTjcmVx3Yy3RliWdve4809cIp6YyI5/Ly3h5fwB561lybKflbMxE0KPMFgEIwWCRNCFB0JiLovQCB1pVUsIimRFgql1aDtSVJBTp5wStSTrWLRgnttirK/JFpRjhbv6od5a1F8 "Python 2 – Try It Online") EDIT: Thx to Mr. Xcoder for 4 bytes... Takes a list of tuples [u,v,w] where u and w are -1 to represent the beginning/end of the linked list segment. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~81~~ ~~78~~ 76 bytes ``` function o=f(a,n)while q=a(n,1)o=a(n=q,2);end while n=a(n,3)o=[o a(n,2)];end ``` [Try it online!](https://tio.run/##VY3LCoMwEEX3fsXdFJQqZKJWJbizf9CduLAaW6EkiPbx93aSrrqamXPuZeyw9S@9N3VLEKDu2JbIcVIgvpApnECEhBQypCDJAhIpD4nSc4ECjBPfF8rFUwgPqsonCu6QB9xRbHPkncIBlFz7VY@Yzag/s7nt09MM22wNbD2FfWyi931@aCx1H5qYIutmvcQyUtqMwU8aL1OWrYVbZdQ5vbvIFDbc41cXvW4DP0MTHDwUf/Qc7F8 "Octave – Try It Online") Rather straightforward version. Explanation is left as an exercise to the reader. A much more *fun* version is presented below: # [Octave](https://www.gnu.org/software/octave/), ~~142~~ ~~99~~ 92 bytes ``` @(a,n)[(p=@(b,c,z){q=a(z,2),@()[b(b,c,a(z,c)),q]}{2-~a(z,c)}())(p,1,n),p(p,3,n)(end-1:-1:1)] ``` [Try it online!](https://tio.run/##VY3NasMwEITveYq5FLRUMlo5zp8w@OC@QW/GB/8oIRfHIaGUhPTV1Y1yCizszLcz7Gm4dj8h1mXDsOD2s9mgwMqDxWHpsQIzDHsskYOdHOCQy3LYJG6xhmCT@tY/4zlsAtttSqylwwlIx8u1QNF6fIBN313CiOM0ht/jdFjsyyzLYqU6PVGj5rJSvR70je7nslM37UhXipo@0ScYiPS5fdyd@XvZhyJSs2bp61lELkKFaTS8k2Fq417Vmkmef4fLdZD3qBeJ2Tf4FeM/ "Octave – Try It Online") Yo, I heard you liked anonymous functions... Takes a `nx3` array, with the first column the predecessor, second column the value, and third value the successor nodes. All the node indices are 1-based, which is the default in Octave. ``` % Create an anonymous function, taking an array a and first node n @(a,n) % Returns an array containing the predecessor and sucessor nodes [ , ] % Defines an recursive anonymous function (by supplying itself to the local namespace) % which looks at the first column (c=1) or last column (c=3) of the input array to get the next nodes (p=@(p,c,z) )(p,1,n) % Create a cell array, either containing the end node, {q=a(z,2), % ...or an array with all next next nodes and the current node % (note the use of an anonymous function taking no parameters to defer array access, in case of the last node) @()[p(p,c,a(z,c)),q]} % depending whether the next node number is nonzero (followed by () to execute the deferred array access) {2-~a(z,c)}() % Do the same with c=3, reverse (function p builds the array right-to-left) and drop the current node to prevent a duplicate. p(p,3,n)(end-1:-1:1) ``` [Answer] # [Kotlin](https://kotlinlang.org), 85 bytes ``` {g,S->generateSequence(generateSequence(S){g[it][0]}.last()){g[it][2]}.map{g[it][1]}} ``` ## Beautified ``` {g,S-> generateSequence(generateSequence(S){g[it][0]}.last()){ g[it][2]}.map { g[it][1] } } ``` ## Test ``` typealias Node=Triple<Int?,Int?,Int?> data class Test(val input: List<Node>, val start:Int, val result: List<Int>) val TEST = listOf<Test>( Test( listOf(Node(null, 12, 1), Node(0, 99, 2), Node(1, 37, null)), 1, listOf(12, 99, 37) ), Test(listOf( Node(2, 99, 1), Node(0, 37, null), Node(null, 12, 0)), 1, listOf(12, 99, 37) ), Test( listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)), 4, listOf(0, 1, 1, 2, 3, 5, 8) ), Test( listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)), 0, listOf(2, 3, 5, 7, 11) ), Test( listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)), 9, listOf(99) ), Test( listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)), 18, listOf(80, 80, 67, 71) ), Test( listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)), 8, listOf(1, -1, 1, -1, 1, -1, 1) ), Test( listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)), 4, listOf(1, 3, 6, 10, 15, 21) ), Test( listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)), 14, listOf(3, 1, 4, 1, 5, 9, 2, 6, 5, 3) ), Test( listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)), 17, listOf(8, 6, 7, 5, 3, 0, 9) ), Test( listOf(Node(4, 11, 0), Node(null, 22, 3), Node(null, 33, 3), Node(1, 44, 4), Node(3, 55, null), Node(7, 66, 7), Node(6, 77, 6)), 3, listOf(22, 44, 55) ), Test( listOf(Node(null, -123, null)), 0, listOf(-123) ) ) var f:(List<List<Int?>>,Int)-> Sequence<Int?> = {g,S->generateSequence(generateSequence(S){g[it][0]}.last()){g[it][2]}.map{g[it][1]}} fun main(args: Array<String>) { for ((input, start, result) in TEST) { val out = f(input.map { it.toList() }, start).toList() if (out != result) { throw AssertionError("$input $start $result $out") } } } ``` ## TIO [TryItOnline](https://tio.run/##7VhNb+IwEL3nV8xWHBIpVNjOJ4JUPfSw0mr3ALeqh6gNbLRpwiamqwrx21mPnTgmqOqJUxMExRPPm5k3D6jnT8WLvDxZ/H2XpUWeNvCzesmW6zrfFdnie8nvXP2SWC8pT+G5SJsG1lnD7be0gLzc7fkcfuQNX6Bv4gKaG57WfC7c1LLOmn3RbRPWxLHQvH5YrWEJhbD+2iwQM7EtCW0pm42QdrkvChcIFU/HlRnaMxfi2AXarYkLLHQBdzqOaxG3A0Av3MlCxxI3JHh7y5Ke7X0TWSO1pj7+7HPws8wjF3wXAp2lABeZet06EEtyHssTaBjLKEwEYXopFtG5h8AMDSZUshhopp2IBJ2db8HETZxQ5kbON2G4zsJkMT5S4GkKVEVtlnJD9MW4mGkuNAXoTr4YDbGmIY4/KJ2I7RGmof2JSDwclOtjnuIZmwUSIyjBD/7AiYl1YH4fhDIzqnmmgWSAzYzUp8ikP/iUC5OmloYSlYQa1lM7dLtopGDYOQpWqSNRsfCkIrrQTCWrK6TiNn6NMFMVoaESsQxCoxPIiG+ohimKiHdRDOt9Ytlyk7W45SAyZYH868CRBDF9AokSDuo1tUWZSqZvhq+aQQ1dDZRGlR4HzRAW2ks2kNojUm1COJ20kOuoJSgko/RG6V1Xer3yiKph8GdU4KjA6yrQMxWo6JSiwTCj/Eb5Xfu3t9efiqYa40tgKun1sSujEEchXleIYf9PoCRT9ZvJJn90CPHUAWtw8qH0on3YIGacuTzP5FpE8i8OS0FgkILvZftEGqw/I1KF5Psf5KeCTwll/TijP2KiXTiKh/WW1rCZ23Kk0s1V7pIEZzXONIFV9neflc9qipPA8nTYuqtpss3KrE551t22Lwwr57B9zPnT4+zpeFukIj+ns1BheU137Yo8HY8na7Mv4TXNSzutt80c7us6fV+seJ2X28SBgwXi2lQ12LYcFblqNOS2IyEH8lKOgbqteOFoqNpzWMJGOWFQOEDOb3mFpdoOHFsgR5u0e74BG92/LXWQHhsv/ruu/sF902Q1z6vyoa6r2r6ZyFAwkbAwUa4wEUg3PfbRUq/H038) [Answer] # JavaScript ES6, ~~70~~ 63 Bytes ``` (x,i,a)=>(h=_=>i&&h(a(x[i].v),i=x[i].n))(x.map(_=>i=x[i].p||i)) ``` Test case: ``` F([undefined,{p:0,v:12,n:2},{p:1,v:99,n:3},{p:2,v:37,n:0}],1,alert) ``` ]
[Question] [ *Note: This is related to a variation of the game [Rummikub](https://en.wikipedia.org/wiki/Rummikub)* --- # Background & Rules *Rummikub* is a tile-based game. There are four colors: red, orange, blue and black. For each color there are 13 tiles (labeled from 1 to 13), and there are also 2 Jokers which are color-independent, hence there are 54 pieces in total. In this variation of Rummikub, each player receives 14 tiles and must get one more tile and drop another one each round, such that the tile count is constant. The players don't see each other's tiles. The goal is to group the tiles, such that all pieces belong to at least one group (see below). When a player has all the pieces grouped, they drop their tile board and reveal their pieces. The others then check if all the combinations are valid, and if they are, the player wins the round. # How can the tiles be grouped? There are only two types of groups: * **Multi-color** groups: + They consist of 3 or 4 tiles. + They only contain tiles with the same number on them. + All the tiles are of different colors. + Example: `RED 9, BLUE 9, BLACK 9`. * **Mono-color** groups: + They consist of at least 3 tiles. + They cannot contain more than 13 tiles. + They only contain tiles with different, consecutive numbers on them, in ascending order. + All the tiles have the same color. + Tiles labeled with `1` **may not** be places after tiles labeled `13`. + Example: `RED 5, RED 6, RED 7`. ### Wait, what do the Jokers do? Jokers can substitue any piece in the game. For example, our first example can become `JOKER, BLUE 9, BLACK 9`, `RED 9, JOKER, BLACK 9` or `RED 9, BLUE 9, JOKER`. The same applies to our other example. However, one may *not* place two Jokers in the same group, so things like `JOKER, ORANGE 8, JOKER` are forbidden. --- # Task Given a Rummikub tile group, determine whether it is valid. You are guaranteed that no duplicate tiles will appear, except for the 2 jokers and that the tiles you receive as input are valid (eg. things like `60` will not appear). # Input / Output You may take input and provide the output by any standard method. Some valid input formats: list of strings, list of tuples, nested lists, strings, or anything else you find suitable. The colors can be taken as Strings (e.g: `"Blue","Red", etc.`), as String abbreviations (please make Blue and Black tiles distinguishable), or as integers coresponding to a color. When it comes to Jokers, you should mention the way your program receives them as input. If you choose Strings, you may have something like `RED 9, JOKER, ...`, if you choose tuples you can have `(9,"RED"), ("JOKER")` or something equivalent. If it helps, you may receive a color for that Joker (which should not affect the output of your program). For example, you may have `("JOKER","RED")` or `("JOKER","BLUE")`, but that should not influence the output in any way. Regarding the output, standard rules for a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") apply. # Worked examples Let's take an example, that would hopefully make it easier to understand. Given a group as follows, where each tuple represents a tile: ``` [(9, "RED"), (9, "ORANGE"), ("JOKER"), (9, "BLACK")] ``` This should return a truthy value, because the input is valid. In this case, the Joker substitutes `(9, "BLUE")`, and they form a multi-color group. If you would be given the following group: ``` [(9, "BLUE"), (9, "ORANGE"), (9, "RED"), (9, "BLACK"), ("JOKER")] ``` It would be invalid, and thus you program should return a falsy value, because there is nothing left for the joker to substitute, because the maximum number of cards in a multi-color group is 4. # Additional Test Cases These are for an extended test suite that cover nearly all possible situations: ``` Input -> Output [(1,"BLUE"),(2,"BLUE"),(3,"BLUE"),(4,"BLUE"),(5,"BLUE"), (6,"BLUE")] -> truthy [(6,"BLUE"),(6,"RED"),(6,"BLACK)] -> truthy [(5,"BLACK"),(6,"BLACK"),(7,"BLACK"),(8,"BLACK"),(9,"BLACK"),(10,"BLACK"),("JOKER"),(12,"BLACK")] -> truthy [("JOKER"),(3,"BLUE"),(3,"RED")] -> truthy [(8,"BLACK"),(2,"RED"),(13,"BLUE")] -> falsy [(4,"RED"), (3,"RED"), (5,"RED")] -> falsy [(5,"BLACK"), (6, "BLACK)] -> falsy [("JOKER"),(5,"RED"),("JOKER")] -> falsy [(4,"RED"),(5,"RED"),(6, BLUE")] -> falsy [(4,"RED"),("JOKER"),(5,"RED")] -> falsy [(12,"BLACK"),(13,"BLACK),(1,"BLACK")] -> falsy ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in every language wins! [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 58 bytes Takes list of colors (1-4) as right argument and list of numbers as left argument. A Joker's number is denoted `(⍳4)` which is equivalent to `(1 2 3 4)` to indicate that it could be any of those. Likewise, its color is denoted `(⍳13)` to indicate that it could be any of the numbers from 1 through 13. ``` {(3≤≢⍺)∧((s⍵)∧⍺≡∪⍺)∨((s←{1∊≢∘∪¨⊃,¨/⍵})⍺)∧∨/∊(⊃,¨/⍵)⍷¨⊂⍳13} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zkjNTn7UduEag3jR51LHnUuetS7S/NRx3INjeJHvVtBLKDAo86FjzpWQWRWgGSA6g0fdXSBlHfMAEodWvGoq1nn0Ap9oJ5aTagRQLX6QEUaCCmgzHaQ0qZHvZsNjWv//3/UO1cBCTj7@/gHBUM5fqG@Tq5BwVwwSUMkCHY1kDZSMFYwUTBVMONSQAEQGYgqMxDkQtatAbZeE24OUL@CuYKFgqWCoQFC0gjJTIQOI6gemIixgjEeuy2AbENMBQgvmACVmqLJK6DIw7yGcAKMheoQUxgLi21GcNOwBRVSgIJcq2AIAA "APL (Dyalog Unicode) – Try It Online") ### Algorithm **There are three conditions, of which the last two have two conditions each:** 1. The run must have length greater than or equal to 3 **AND EITHER** 2. 1. a single number AND 2. unique colors **OR** 3. 1. a single color AND 2. sequential numbers **in order for the run to be valid.** ### Reading order  `3≤` 3 is less than or equal to the `≢⍺` number of tiles `∧` and    `s⍵` all numbers are the same   `∧` and    `⍺≡∪⍺` the colors are unique  `∨` or    `1∊` 1 is among `≢∘∪¨` the number of unique `⊃,¨/` expanded `⍺` colors   `∧` and    `∨/` there exists at least one `∊` among all `⊃,¨/⍵` expanded number runs `⍷¨⊂` one which is found in `⍳13` 1 through 13 ### Full code explanation `{`…`}` anonymous function where `⍺` is left argument and `⍵` is right argument **3.2.**  `⍳13` the numbers 1 through 13  `(`…`)⍷¨` find the starting positions of each of the following runs:   `,¨/⍵` join each element of the numbers (creates a run for each Joker value)   `⊃` disclose (because `/` reduces rank)   `∊` **ϵ**nlist (flatten)  `∨/` OR reduction (i.e. are any true?)  `(`…`)∧` AND: **3.1**   `(`…`)⍺` the result of applying the following function on the list of colors:    `s←{`…`}` *s* (for **s**ame) which is the following anonymous function (`⍵` is *its* argument):     `,¨/⍵` join each element across (creates a run for each Joker value)     `⊃` disclose (because `/` reduces rank)     `≢∘∪¨` the the number of unique elements in each list     `1∊` is one a member? (i.e. are there any all-same lists?)  `(`…`)∨` **OR:** **2.2.**   `∪⍺` the unique colors   `⍺≡` are identical to the colors (i.e. they are unique)   `(`…`)∧` AND: **2.1.**    `s⍵` the numbers are all the same   `(`…`)∧` **AND** **1.**    `≢⍺` the number of colors (i.e. the number of tiles)    `3≤` three is less than or equal to that [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ ~~40~~ ~~38~~ 36 bytes ``` EȧI=1ȦȯE 0,W€yµZç/ɓQ⁼⁸ȧ L>2ȧ4p13ðç€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8/9/1xHJPW8MTy06sd@Uy0Al/1LSm8tDWqMPL9U9ODnzUuOdR444Ty7l87IxOLDcpMDQ@vOHwcqCShzsb/h9uBzKOTnq4cwaQjvz/Pzpaw1DHUFMHSBqBSWMwaQImTTV1FICUmWasDlc0mKGjYQQmjWGCxiBFYC6INAeTFmDSEkwaGmjqGIAZRmANBjA7jIAk1AQLMBdivSFU1AjkBAWwKjBlimSdgoaZjoIxzDiQnI4BQhNEAOFssNVgFxhDKM3YWAA "Jelly – Try It Online") (comes with a test-suite footer) Takes input as an array of `(color, value)` for regular tiles and `0` for jokers. Colors are represented as integers (although I'm not sure if that even matters for the current code). Outputs `1` (truthy) or `0` (falsy). ### Explanation ``` L>2ȧ4p13ðç€Ṁ Main link, checks if a sequence is valid. Args: sequence L Get the length of the sequence. >2 Check if it's at least 3 tiles. ȧ4 And: yield 4 if it is, 0 otherwise. p13 Cartesian product: yield all possible tiles if result was 4, empty array otherwise. ð Begin a new dyadic chain with args (tiles, sequence). ç€ Call the first helper link for each tile with args (tile, sequence). 0,W€yµZç/ɓQ⁼⁸ȧ First helper link, checks if a sequence is valid if jokers are substituted for the given tile. Args: tile, sequence 0, Make a pair [0, tile]. W€ Turn that into [[0], [tile]]. y Map all 0's (jokers) into tile in the sequence. µ Begin a new monadic chain with args (sequence). Z Transpose to get list [colors, values]. ç/ Call the second helper link with args (colors, values). ɓ Begin a new dyadic chain with args (sequence, valid). Q Remove duplicate tiles from the sequence. ⁼⁸ Check if the sequence is unchanged (i.e. there were no duplicates). ȧ And with the output of the second helper. EȧI=1ȦȯE Second helper link, checks if a sequence is valid assuming no duplicates. Args: colors, values E Check if all the colors are the same. ȧ Logical and with the values array. Yields the values if they were, 0 if not. I Find the differences between each value. Yields [] if the colors differed. =1 See if each difference is equal to 1. Yields [] if the colors differed. Ȧ Check if the list was nonempty and all values were truthy. Yields 1 for valid mono-colors, 0 otherwise. ȯ Logical or with the values array. Yields 1 for valid mono-colors, the values otherwise. E Check if all the values are the same. For valid mono-colors this tests if all items of [1] are equal (obviously true). Yields 1 for valid sequences, 0 otherwise. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~371 370 362 341 329~~ 325 bytes * @Mr.Xcoder saved 1 byte: `str.split()` instead of `list literal` * 8 bytes saved: shorthand for `len(x)-1` * 19 bytes saved: `J O BK B R` for `Joker, Orange, Black, Blue, Red` literals * @Mr.Xcoder saved yet another 12 bytes, Thanks!! * Another 4 bytes thanks to @Mr.Xcoder ``` def f(x): j=sum("J"in i for i in x);z=len(x)-1 if j>1or z<2:return False if j<1:return(all(i[0]==x[0][0]for i in x)and sum(i[1]==x[0][1]for i in x)<2)or(all(i[1]==x[0][1]for i in x)and sum(int(x[m+1][0])==int(x[m][0])+1for m in range(z))==z) return any(f([[k,(i+1,j)]["J"in k]for k in x])for j in'RBbO'for i in range(13)) ``` [Try it online!](https://tio.run/##bVI9b8IwEJ2bX3HKgi1SCTsNbSnuwNChSyVWK4MRSesQDApBCvnz1I4vIRJEkd@d33280/l4qf8Ohl@v2yyHnDR0EUAhTuc9Cb9DbUBDfqjsac2GfrSizIwNemYB6ByKT2bJdskXVVafKwNfqjxlnloyvCSqLImWs1SIxp72H1VUZguumZas59mYX3J6qLDC44ihgqlJI/dT5jpQIdDvvClzCXuXUCnzm5GW2oiWBoC6lbmQnEi5i4iesqigqfTj77pWu65VSp1dWHuyXm1@JoMIX5PFlF63qlYgQAZPkrAoXIU0IhwxRnxBTDwCmXdGGrmkOZIW14ibnks6u7@LyCviG@I7IpuhYWdwLh/V8FfxTdK6YwA/ORTjKIDFvbpbzIvnAPOtkdwXQrVuPMD@N9LLSLCH8x41GALm9xoY66flo2nTIA2Gvbhl2Od8rNxbyIm2@/kH "Python 2 – Try It Online") [Answer] # Javascript (ES6), 286 bytes ``` var testcases = [[{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],[{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],[{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],[{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],[{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],[{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],[{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],[{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],[{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],[{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],[{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],[{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],[{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}]]; g=a=>a.length j=a=>a.n==0 l=(x,y)=>x.c==y.c||j(x)||j(y) a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||((l(x,y)||x.n==y.n)&&!(j(x)&&j(y)))&&(([n=s.indexOf(y),n<1||([x=s[n-1],!l(x,y)||y.n>0&&x.n<y.n])[1]||(n<g(s)-1&&x.n+1<s[n+1].n)||(n==g(s)-1&&y.n==0&&x.n<13)])[1])?1:0)])[0][0]==g(s) testcases.forEach(H=>console.log(a(H))); ``` (Note that the test cases above contain 2 additional test cases that are not in the Question: they are true and false respectively: see the ungolfed version for readability). Rough process: ``` Using first tile x: For each tile y: count for x: can group with y return: x matches n tiles, where n is the number of tiles ``` Jokers are indicated by having a `0` as their numerical value (a negative number would work too); this keeps the input struct consistent (has both a Color and Value) and doesn't rely on having to check if `c=="JOKER"`, saving 7 bytes. Its possible that some parentheses could be removed, it might be possible to not box `q` as an array (I tried it and the value just either stayed 0 or caused [nasal demons](http://catb.org/jargon/html/N/nasal-demons.html)). Ungolfed: ``` var testcases = [ [{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],//true [{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],//true [{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],//true [{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],//true [{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],//false [{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],//false [{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],//false [{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],//false [{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],//false [{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],//false [{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],//false [{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],//true [{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}] ]; g=a=>a.length i=(a,v)=>a.indexOf(v) j=x=>x.n==0 m=(x,y)=> (l(x,y)||x.n==y.n) &&!(j(x)&&j(y)) l=(x,y)=>x.c==y.c||j(x)||j(y) c=(a,v)=>([n=i(a,v), n<1 ||([x=a[n-1],!l(x,v)||v.n>0&&x.n<v.n])[1] ||(n<g(a)-1&&x.n+1<a[n+1].n) ||(n==g(a)-1&&v.n==0&&x.n<13)])[1] a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||m(x,y)&&c(s,y)?1:0)])[0][0]==g(s) testcases.forEach(H=>console.log(a(H))); ``` Version I worked on to get the logic correct. Single-use lambdas got in-lined; here's their corresponding function: ``` g() -> string.length i() -> indexof j() -> isJoker m() -> do tiles match l() -> do colors match c() -> same-color isConsecutiveOrder a() -> main lambda ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 198 bytes ``` using System.Linq;(C,N)=>{int l=C.Length,j=C.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u*=0<(u&x)?2:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));}; ``` Takes in the colors of tiles and numbers on them as separate lists of integers. The specifics of that mapping don't matter as long as each color has a different integer and Jokers are represented as 0. The format for inputting numbers is pretty special though. The number that needs to be input for a number `n` is instead 2^n, while the number used to represent a joker should be (2^14)-1. This enables the bitwise and `u&x` to evaluate to u if the tile x has value equal to u or is a joker. # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 200 bytes ``` using System.Linq;(C,N)=>{int l=C.Length,j=N.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u=u==x|x<1?u+1:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));}; ``` A 2 byte longer solution which isn't eclectic about input. Turns out just using a special case for jokers in the one place they were hard to deal with wasn't much longer than the clever bitwise operation I was so proud of. Here Jokers are (0,0), other numbers are as expected, and colors are represented any 4 values which are distinct from each other by C#'s default comparison (specifically, the Linq `Distinct()` operation must consider values for the same color as 'not distinct' and values for different colors as 'distinct'). Something which might be of use to other languages, `u*=!u++^x*x` would be equivalent to `u=u==x|x<1?u+1:0` in some languages; u^x is 0 iff u==x, and 0 times any int is 0, so u^x\*x would be 0 for either u==x or x==0 if C# didn't make bitwise operations lower precedence than mathematical ones. C# also can't interpret ints as bools without explicit casting. A language that tries harder to make types work might convert the values `0` and `not 0` to `false` and `true` before applying `!` to them though, and then when going back to an int interpret `!false` as 1 and `!true` as 0. All that said, I can't guarantee another language would actually benefit from the rest of the algorithm so it might not even come up. [Answer] # Scala, ~~491~~ 477 chars, ~~491~~ 477 bytes This challenge was fun; thanks. ``` var c=Seq("O","B","b","R") t match{case _ if t.length<3=>false case _ if t.exists(x=>x._1==0)=>{var b=false if(t.filter(q=>q._1!=0).exists(q=>q._1==0))b else{for(y<-1 to 13)for(u<-c)b=b|f(t.takeWhile(q=>q._1!=0)++:(y,u)+:t.reverse.takeWhile(q=>q._1!=0).reverse) b}} case _::(x,_)::_ if t.forall(_._1==x)=>true case _ if t.forall(_._2==c(0))|t.forall(_._2==c(1))|t.forall(_._2==c(2))|t.forall(_._2==c(3))=>(t(0)._1 to t(0)._1+t.length-1).toList equals t.map(_._1) case _=>false} ``` So `f` at line 4 is a recursive call where I try replacing "JOKER" by every other tile. See [tio](https://tio.run/##jVNdb9owFH1efoWXJ1sE1BCStVHNRDdUbe1WiWrbQ1uhEJySLQ2QmApE@e3MDvm4XpOOvOQe@9rn3HuPU9@LvP188pv5HH3zwhixNWfxNEWDxWKrvZuyAAWYu7dseYe/xNy45UkYP5IH4l7M5xHzYrrdP3sJ8qlIwfrNaPD9cqgb@sX14NNV9v8h4Wj4WScaR08e92db30sZGqMwQLwTsfiRz84t2g@8KGUa3GPrMOUpXtP@ujM2KT0htL@VbBN6SA6Ftk4QRpwleEn7S5H1XmQVB/MleZBMEBMntsE8wZvzton4HJkWkXB13vbJhE5e5GXc@8N@zcKIwftaLRdvjBVpubyTsGeWpKw@sdgl2mS3y0txXbw2xsR186IEpRdFeJwJW4uKeLJSy64yupT6WIh/ebVo1i126xYtIjgwF9cIRll2HraK3rdN0uHza9ExxJYr0Vch4clbZApJLiyfzm6/0zTpiTD96UXhFKc1zqABTommLQTkUYz1O2wa95kR7nVi4C4EFgQ9CGwAEHYq9IBEw/hs8xG1@0hvFUqk/QTRwXAZTRlaVdirQrsKnSIUnyLcgYokED4u48zi/xHkKCTZK8jp5PN4xWeDa1USA39Q0KmCzhRknihQoq83V8PRYbN7pHS7VAkVSx1VfAriMxALBRUQcUafszfVrsq0/nXJofNvCYY8ljL9rO@SD9CpDeyC2ZoWNJv0fS0drL1bzta0oJcAX69iQKAgAWxQXSNbr2BAZUHZ0draFBvJx4PgyBs5wMSzQ3BSjYOyQefgzhs8cFB22blqtblzCptz1JjKxgEqp2FGytsojVBC46guAosXdiiA4v3d/i8) for a clearer view of the code. I chose taking as input a sequence of 2-tuples (Int,String) - called `t` in my code, see [tio](https://tio.run/##jVNdb9owFH1efoWXJ1sE1BCStVHNRDdUbe1WiWrbQ1uhEJySLQ2QmApE@e3MDvm4XpOOvOQe@9rn3HuPU9@LvP188pv5HH3zwhixNWfxNEWDxWKrvZuyAAWYu7dseYe/xNy45UkYP5IH4l7M5xHzYrrdP3sJ8qlIwfrNaPD9cqgb@sX14NNV9v8h4Wj4WScaR08e92db30sZGqMwQLwTsfiRz84t2g@8KGUa3GPrMOUpXtP@ujM2KT0htL@VbBN6SA6Ftk4QRpwleEn7S5H1XmQVB/MleZBMEBMntsE8wZvzton4HJkWkXB13vbJhE5e5GXc@8N@zcKIwftaLRdvjBVpubyTsGeWpKw@sdgl2mS3y0txXbw2xsR186IEpRdFeJwJW4uKeLJSy64yupT6WIh/ebVo1i126xYtIjgwF9cIRll2HraK3rdN0uHza9ExxJYr0Vch4clbZApJLiyfzm6/0zTpiTD96UXhFKc1zqABTommLQTkUYz1O2wa95kR7nVi4C4EFgQ9CGwAEHYq9IBEw/hs8xG1@0hvFUqk/QTRwXAZTRlaVdirQrsKnSIUnyLcgYokED4u48zi/xHkKCTZK8jp5PN4xWeDa1USA39Q0KmCzhRknihQoq83V8PRYbN7pHS7VAkVSx1VfAriMxALBRUQcUafszfVrsq0/nXJofNvCYY8ljL9rO@SD9CpDeyC2ZoWNJv0fS0drL1bzta0oJcAX69iQKAgAWxQXSNbr2BAZUHZ0draFBvJx4PgyBs5wMSzQ3BSjYOyQefgzhs8cFB22blqtblzCptz1JjKxgEqp2FGytsojVBC46guAosXdiiA4v3d/i8) - so "JOKER" is represented by a 2-tuple (0,"JOKER"). EDIT : 14 bytes saved thanks to comments, I take O B b R for ORANGE BLACK BLUE RED. [Try It Online!](https://tio.run/##jVNdb9owFH1efoWXJ1sE1BCStVHNRDdUbe1WiWrbQ1uhEJySLQ2QmApE@e3MDvm4XpOOvOQe@9rn3HuPU9@LvP188pv5HH3zwhixNWfxNEWDxWKrvZuyAAWYu7dseYe/xNy45UkYP5IH4l7M5xHzYrrdP3sJ8qlIwfrNaPD9cqgb@sX14NNV9v8h4Wj4WScaR08e92db30sZGqMwQLwTsfiRz84t2g@8KGUa3GPrMOUpXtP@ujM2KT0htL@VbBN6SA6Ftk4QRpwleEn7S5H1XmQVB/MleZBMEBMntsE8wZvzton4HJkWkXB13vbJhE5e5GXc@8N@zcKIwftaLRdvjBVpubyTsGeWpKw@sdgl2mS3y0txXbw2xsR186IEpRdFeJwJW4uKeLJSy64yupT6WIh/ebVo1i126xYtIjgwF9cIRll2HraK3rdN0uHza9ExxJYr0Vch4clbZApJLiyfzm6/0zTpiTD96UXhFKc1zqABTommLQTkUYz1O2wa95kR7nVi4C4EFgQ9CGwAEHYq9IBEw/hs8xG1@0hvFUqk/QTRwXAZTRlaVdirQrsKnSIUnyLcgYokED4u48zi/xHkKCTZK8jp5PN4xWeDa1USA39Q0KmCzhRknihQoq83V8PRYbN7pHS7VAkVSx1VfAriMxALBRUQcUafszfVrsq0/nXJofNvCYY8ljL9rO@SD9CpDeyC2ZoWNJv0fS0drL1bzta0oJcAX69iQKAgAWxQXSNbr2BAZUHZ0draFBvJx4PgyBs5wMSzQ3BSjYOyQefgzhs8cFB22blqtblzCptz1JjKxgEqp2FGytsojVBC46guAosXdiiA4v3d/i8) EDIT : -2 bytes, deleted useless `(` around conditions of the `case _ if`s ]
[Question] [ ## Goal: Write a complete program or function which takes a formula in [propositional logic](https://en.wikipedia.org/wiki/Propositional_calculus) (henceforth referred to as a *logical expression* or *expression*) and outputs that formula in [conjunctive normal form](https://en.wikipedia.org/wiki/Conjunctive_normal_form). There are two constants, `⊤` and `⊥` representing true and false, a unary operator `¬` representing negation, and binary operators `⇒`, `⇔`, `∧`, and `∨` representing implication, equivalence, conjunction, and disjunction, respectively which obey all of the usual logical operations ([DeMorgan's law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws), [double negation elimination](https://en.wikipedia.org/wiki/Double_negation#Double_negative_elimination), etc.). Conjunctive normal form is defined as follows: 1. Any atomic expression (including `⊤` and `⊥`) is in conjunctive normal form. 2. The negation of any previously constructed expression is in conjunctive normal form. 3. The disjunction of any two previously constructed expressions is in conjunctive normal form. 4. The conjunction of any two previously constructed expressions is in conjunctive normal form. 5. Any other expression is not in conjunctive normal form. Any logical expression can be converted (non-uniquely) into a logically equivalent expression in conjunctive normal form (see [this algorithm](https://en.wikipedia.org/wiki/Conjunctive_normal_form#Converting_from_first-order_logic)). You do not need to use that particular algorithm. ## Input: You may take input in any convenient format; e.g., a symbolic logical expression (if your language supports it), a string, some other data structure. You do not need to use the same symbols for true, false, and the logical operators as I do here, but your choice should be consistent and you should explain your choices in your answer if it's not clear. You may not accept any other input or encode any additional information in your input format. You should have some way of expressing an arbitrary number of atomic expressions; e.g. integers, characters, strings, etc. ## Output: The formula in conjunctive normal form, again in any convenient format. It need not be in the same format as your input, but you should explain if there are any differences. ## Test cases: ``` P ∧ (P ⇒ R) -> P ∧ R P ⇔ (¬ P) -> ⊥ (¬ P) ∨ (Q ⇔ (P ∧ R)) -> ((¬ P) ∨ ((¬ Q) ∨ R)) ∧ ((¬ P) ∨ (Q ∨ (¬ R))) ``` ## Notes: 1. If the input expression is a tautology, `⊤` would be a valid output. Similarly, if the input expression is a contradiction, `⊥` would be a valid output. 2. Both your input and output formats should have a well-defined order of operations capable of expressing all possible logical expressions. You may need parentheses of some sort. 3. You may use any well-defined choice of infix, prefix, or postfix notation for the logical operations. If your choice differs from the standard (negation is prefix, the rest are infix), please explain that in your answer. 4. Conjunctive normal form is not unique in general (not even up to reordering). You need only to output *a* valid form. 5. However you represent atomic expressions, they must be distinct from the logical constants, operators, and grouping symbols (if you have them). 6. Built-ins which compute conjunctive normal form are allowed. 7. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. 8. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest answer (in bytes) wins. [Answer] You're going to hate me.... # Mathematica, 23 bytes ``` #~BooleanConvert~"CNF"& ``` The input will use `True` and `False` instead of `⊤` and `⊥`, but otherwise will look very similar to the notation of the question: all of the characters `¬`, `⇒`, `⇔`, `∧`, and `∨` are recognized in Mathematica (when input with UTF-8 characters 00AC, F523, 29E6, 2227, and 2228, respectively), and parentheses act as you would expect. By default, the output will use Mathematica's preferred symbols: for example, the last test case will output `(! P || ! Q || R) && (! P || Q || ! R)` instead of `((¬ P) ∨ ((¬ Q) ∨ R)) ∧ ((¬ P) ∨ (Q ∨ (¬ R)))`. However, changing the function to ``` TraditionalForm[#~BooleanConvert~"CNF"]& ``` will make the output look pretty and conforming to these usual symbols: [![traditional form](https://i.stack.imgur.com/9QlJr.png)](https://i.stack.imgur.com/9QlJr.png) [Answer] # Maxima, 4 bytes ``` pcnf ``` [Try It Online!](https://tio.run/#xTDqU) You can use `implies`, `eq`, `and`, `or` operators for implication, equivalence, conjunction, and disjunction respectively. [Answer] ## JavaScript (ES6), 127 bytes ``` f=(s,t='',p=s.match(/[A-Z]/),r=RegExp(p,'g'))=>p?'('+f(s.replace(r,1),t+'|'+p)+')&('+f(s.replace(r,0),t+'|!'+p)+')':eval(s)?1:0+t ``` I/O format is as follows (in order of precedence): * `(`: `(` * `)`: `)` * `⊤`: `1` * `⊥`: `0` * `¬`: `!` * `⇒`: `<=` * `⇔`: `==` * `∧`: `&` * `∨`: `|` Examples: ``` P&(P<=R) -> ((1)&(0|P|!R))&((0|!P|R)&(0|!P|!R)) P==(!P) -> (0|P)&(0|!P) (!P)|(Q==(P&R)) -> (((1)&(0|P|Q|!R))&((0|P|!Q|R)&(1)))&(((1)&(1))&((1)&(1))) ``` The function is trivially rewritten to produce disjunctive normal form: ``` f=(s,t='',p=s.match(/[A-Z]/),r=RegExp(p,'g'))=>p?'('f(s.replace(r,1),t+'&'+p)+')|('+f(s.replace(r,0),t+'&!'+p)+')':eval(s)?1+t:0 ``` 8 bytes could be saved from this version if I was allowed to assume the above precedence on output too, which would remove all the parentheses from the output examples: ``` P&(P<=R) -> ((1&P&R)|(0))|((0)|(0)) P==(!P) -> (0)|(0) (!P)|(Q==(P&R)) -> (((1&P&Q&R)|(0))|((0)|(1&P&!Q&!R)))|(((1&!P&Q&R)|(1&!P&Q&!R))|((1&!P&!Q&R)|(1&!P&!Q&!R))) ``` ]
[Question] [ A [counterstring](http://www.satisfice.com/blog/archives/22) is some sort of self-describing test data that is used in software testing. Not sure it was actually invented by [James Bach](http://www.satisfice.com/blog/), but I know it from there. The idea is as follows: the test data contains many asterisk (`*`). The number in front of the asterisk tells you how long the test data is at that point. If you need to know a position in the test data that is not an asterisk, find the last asterisk, look at the number before and add the number of digits that follow. The sequence starts like this: ``` 2*4*6*8*11*14*17*20*23* ^ ``` As you can see, the marked asterisk is at position 14. If a file happens to be truncated as follows ``` [...]2045*20 ``` then you can derive that there is a limit of 2047 characters somewhere (2045 where the asterisk is plus 2 for `2` and `0`). It's your task to create the shortest (this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")) program that outputs (std::out or file or whatever) an arbitrary long test string of that format. The length in characters is given as argument. The program shall support up to 2 GB test data (input value 2147483647 characters). "Dangerous" positions in the 2 GB file: ``` 8*11* 98*102* 998*1003* 9998*10004* 99998*100005* 999995*1000003* 9999995*10000004* 99999995*100000005* 999999995*1000000006* ``` This should answer [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s question if there is a decision to make between 995\*999\* and 995\*1000\* or similar: no. The end of the 2 GB file with input value 2147483647 is: ``` 2147483640*2147483 ``` [Answer] # Pyth, ~~25~~ ~~17~~ ~~15~~ 14 bytes ``` <uu++GlN\*k)Qk ``` [Try it online.](http://pyth.herokuapp.com/?code=%3Cuu%2B%2BGlN%5C*k)Qk&input=512&debug=0) Length is taken via STDIN. [Answer] ## Haskell, ~~60~~ 58 bytes As a function we get: ``` f=length.show iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show ``` ### Full program, ~~72~~ 70 bytes This outputs an infinite counterstring to STDOUT: ``` f=length.show main=putStr$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show ``` Inputting the length requires 20 additional bytes: ``` main=interact(\j->take(read j)$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show) ``` This works up to your approximately your RAM size, since Haskell defaults numeric integral types to `Integer`. [Answer] # Python 2, ~~74~~ ~~72~~ ~~66~~ ~~64~~ 61 Bytes ``` f=lambda n,i=2:"%d*"%i+f(n,len(`i+2`)-~i)[:n-2]if i<n*2else"" ``` Takes an integer n and outputs a counterstring of length n. ### program version, 69 Bytes: ``` s,n,i="",input(),2 while i<2*n:s+="%d*"%i;i+=len(`i+2`)+1 print s[:n] ``` Takes an integer n from stdin and prints a counterstring of length n. ### Shorter, but only almost working, alternative version: ``` n,i=input(),2 while i<2*n:print("%d*"%i)[:n-i],;i+=len(str(i+2))+1 ``` [Answer] # Python 3, ~~126~~ ~~114~~ 99 bytes ``` def f(x,s=''): i=t=2 while len(s)<x:i+=len(str(t+i))-len(str(t));s+=str(t)+'*';t+=i print(s[:x]) ``` A function that takes input via argument of the character count at which to truncate the string, and prints to STDOUT. **How it works** The difference between the numbers in the string is initially 2. Every time an order of magnitude is passed, this difference is increased by 1; this can be achieved by taking the difference between the number of digits of the current number and the number of digits of the current number added to the difference, which is 1 only when required. The function simply loops while the length of the string is less than the input, appends to the string and updates the difference and number as required, and then truncates before printing. [Try it on Ideone](http://ideone.com/zO1Pn9) **Infinite output version, 69 bytes** ``` s=i=2 while 1:i+=len(str(s+i))-len(str(s));print(end=str(s)+'*');s+=i ``` [Answer] ## PowerShell v5, 97 bytes ``` param($n)$l=1;for($i=0;$i-lt$n){$i+="$i*".length;if("$i".Length-gt$l){$i++;$l++};ac .\o "$i*" -n} ``` Takes input as a command-line argument `$n`, sets helper `$l` which we use to keep track of our integer length. Then, we loop from `0` up to `$n`. Each iteration, we increment `$i` by the `.length` of the string formed from `$i` and an asterisk. Then, if the `.length` of `$i` changed (e.g., we moved from 2 digits to 3 digits), we increment both the helper `$l`ength variable and `$i` (to account for the additional digit). We then use the [`add-content`](https://technet.microsoft.com/en-us/library/hh849859.aspx) command to append `"$i*"` to file `.\o` in the current directory, with `-n`oNewLine. ### NB * Requires v5, since the `-noNewLine` parameter was [finally](https://connect.microsoft.com/PowerShell/feedback/details/524739/need-nonewline-parameter-on-out-file-add-content-and-set-content) added in that version. * PowerShell will automatically up-convert from `[int]` to `[double]` (no, I don't know why it doesn't go to `[long]`), so this will properly handle input up to and greater than `2147483648`, without problem. Theoretically, it will handle input somewhere up to around `1.79769313486232E+308` (max value of `[double]`) before complaining, but I expect the disk to fill up before that happens. ;-) * Due to the loop conditional checking, this will output to the file a *minimum* of the input length. For example, for input `10` this will output `2*4*6*8*11*`, since `11` is the first `$i` value greater than the input. --- ### PowerShell v2+, also 97 bytes (non-competing) ``` param($n)$l=1;-join(&{for($i=0;$i-lt$n){$i+="$i*".length;if("$i".Length-gt$l){$i++;$l++};"$i*"}}) ``` Instead of sending to a file, this encapsulates the loop iterations and then `-join`s them together into a string. This allows it to work for versions earlier than v5. However, since .NET defines a `[string]` with a constructor like `String(char c,Int32 length)`, this version does *not* satisfy the max input requirement, since the output string will overflow and barf. Also, you may not want to have a ~2GB string floating around in your pipeline. Just sayin'. [Answer] # R, 92 bytes ``` N=nchar;f=function(n){z=0;y="";while(z<n){z=z+N(z+N(z)+1)+1;y=paste0(y,z,"*")};strtrim(y,n)} ``` Example output: > > f(103) > [1] "2\*4\*6\*8\*11\*14\*17\*20\*23\*26\*29\*32\*35\*38\*41\*44\*47\*50\*53\*56\*59\*62\*65\*68\*71\*74\*77\*80\*83\*86\*89\*92\*95\*98\*102\*1" > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~19~~ 18 bytes ``` 2µṾL+®‘¹©=¡=µ³#j”* ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//MsK14bm@TCvCruKAmMK5wqk9wqE9wrXCsyNq4oCdKv///zE1 "Jelly – Try It Online") Find the first `n` numbers in the string then join the list with an asterisk. This will always be longer than `n` which was allowed by OP in the comments. The program selectively updates the register with the current number in the sequence in the `#` loop with `¹©=¡`. I was hoping this could be shorter, by putting `©` after the second `µ` for example, but unfortunately that doesn't work and I couldn't figure out any thing shorter. ]
[Question] [ The goal of this challenge is given a finite [directed acyclic graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph) (DAG), determine if the graph is a [transitive reduction](https://en.wikipedia.org/wiki/Transitive_reduction). A brief explanation of what a DAG and transitive reductions are: A DAG is a graph with directed edges (i.e. you can only travel in one direction on that edge) such that given any starting node on the graph, it is impossible to return to the starting node (i.e. there are no cycles). Given any starting node, if it is possible to travel to another ending node in the graph via any arbitrary positive number of edges, then that ending node is defined as reachable from the starting node. In a general DAG, there might be multiple paths which can be taken from a starting node to a target ending node. For example, take this diamond graph: [![enter image description here](https://i.stack.imgur.com/bFakf.png)](https://i.stack.imgur.com/bFakf.png) To get to node `D` from `A`, you could take the path `A->B->D` or `A->C->D`. Thus, `D` is reachable from `A`. However, there is no path which can be taken to get to node `B` starting from node `C`. Thus, node `B` is not reachable from node `C`. Define the [reachability](https://en.wikipedia.org/wiki/Reachability) of the graph as the list of reachable nodes for every starting node in the graph. So for the same example diamond graph, the reachability is: ``` A: [B, C, D] B: [D] C: [D] D: [] ``` Another graph which has the same reachability as the above graph is shown below: [![enter image description here](https://i.stack.imgur.com/trR07.png)](https://i.stack.imgur.com/trR07.png) However, this second graph has more edges than the original graph. The transitive reduction of a graph is a graph with the least number of edges and same reachability of the original graph. So the first graph is the transitive reduction of the second one. For a finite DAG, the transitive reduction is guaranteed to exist and is unique. # Input The input is a "list of lists", where the external list has the length of the number of vertices, and each internal list is the length of the number of edges leaving the associated node, and contains the indices of destination nodes. For example, one way to describe the first graph above would be (assuming zero based indexing): ``` [[1, 2], [3], [3], []] ``` You may begin indexing of the first node at any arbitrary integer value (e.g. 0 or 1 based indexing). The input may come from any input source desired (stdio, function parameter, etc.). You are free to choose the exact input format as long as no additional information is given. For example, if you want to take input from stdio, you could have each line be a list of edges for the associated node. Ex.: ``` 1 2 3 3 '' (blank line) ``` The indices in each adjacency list is not necessarily sorted, and there could be multiple edges connecting two nodes (ex.: `[[1,1],[]]`). You may assume the input graph is [weakly connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Definitions_of_components.2C_cuts_and_connectivity), and contains no cycles (i.e. it is a DAG). # Output The output is truthy if the given input DAG is a transitive reduction, and a falsy value otherwise. This may be to any sink desired (stdio, return value, output parameter, etc.) # Examples All examples use 0-based indexing. ``` [[1,2],[3],[3],[]] true [[1,2,3],[3],[3],[]] false [[1,1],[]] false [[1,2,3,4],[5,6,7],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]] true [[5,6,7],[2,3,0,4],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]] true [[5,6,7],[2,3,0,4,14,5,7],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]] false [[5,6,7],[2,3,0,4],[5,8,9],[6,8,10],[7,9,10,14],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]] false [[1,3],[2],[3],[]] false ``` # Scoring This is code golf; smallest code in bytes wins. Your code should complete in a reasonable amount of time (10 minutes max on whatever hardware you have). Standard loopholes apply. You may use any built-ins desired. [Answer] # Ruby, ~~101~~ 97 bytes Simple approach that calculates the reach from each node and considers if a child node can be reached via any of the other nodes. Seemingly fails on cyclic graphs, but the definition of a DAG implies that it shouldn't be cyclic anyways. [Try it online!](https://repl.it/Chsp/2) ``` ->g{r=->i{i|i.map{|j|r[g[j]||[]]}.inject([],:|)} g.all?{|e|e==e&e&&e.none?{|i|r[e-[i]].index i}}} ``` [Answer] # Mathematica, ~~95~~ 82 bytes *13 bytes saved due to [@MartinEnder](http://ppcg.lol/users/8478).* ``` #~IsomorphicGraphQ~TransitiveReductionGraph@#&@Graph[x=0;##&@@Thread[++x->#]&/@#]& ``` Anonymous function. Takes a nested list as (1-based) input, and returns `True` or `False` as output. The main solution here is the 46-byte `#~IsomorphicGraphQ~TransitiveReductionGraph@#&`, which tests if a given graph is isomorphic to its transitive reduction. The rest converts the input to a `Graph` object. [Answer] ## CJam (41 bytes) ``` q~:A_,{{Af=e__&}%_}*]:.|A.&A:$:e`e_2%1-*! ``` [Online demo](http://cjam.aditsu.net/#code=q~%3AA_%2C%7B%7BAf%3De__%26%7D%25_%7D*%5D%3A.%7CA.%26A%3A%24%3Ae%60e_2%251-*!&input=%5B%5B1%202%5D%20%5B3%5D%20%5B3%5D%20%5B%5D%5D), [test harness](http://cjam.aditsu.net/#code=%5B%5B1%202%5D%20%5B3%5D%20%5B3%5D%20%5B%5D%5D%0A%5B%5B1%202%203%204%5D%5B5%206%207%5D%5B5%208%209%5D%5B6%208%2010%5D%5B7%209%2010%5D%5B11%2012%5D%5B11%2013%5D%5B12%2013%5D%5B11%2014%5D%5B12%2014%5D%5B13%2014%5D%5B%5D%5B%5D%5B%5D%5B%5D%5D%0A%5B%5B5%206%207%5D%5B2%203%200%204%5D%5B5%208%209%5D%5B6%208%2010%5D%5B7%209%2010%5D%5B11%2012%5D%5B11%2013%5D%5B12%2013%5D%5B11%2014%5D%5B12%2014%5D%5B13%2014%5D%5B%5D%5B%5D%5B%5D%5B%5D%5D%0A%5B%5B1%202%203%5D%20%5B3%5D%20%5B3%5D%20%5B%5D%5D%0A%5B%5B1%201%5D%20%5B%5D%5D%0A%5B%5B5%206%207%5D%5B2%203%200%204%2014%205%207%5D%5B5%208%209%5D%5B6%208%2010%5D%5B7%209%2010%5D%5B11%2012%5D%5B11%2013%5D%5B12%2013%5D%5B11%2014%5D%5B12%2014%5D%5B13%2014%5D%5B%5D%5B%5D%5B%5D%5B%5D%5D%0A%5B%5B5%206%207%5D%5B2%203%200%204%5D%5B5%208%209%5D%5B6%208%2010%5D%5B7%209%2010%2014%5D%5B11%2012%5D%5B11%2013%5D%5B12%2013%5D%5B11%2014%5D%5B12%2014%5D%5B13%2014%5D%5B%5D%5B%5D%5B%5D%5B%5D%5D%0A%5D%7B%60%3AQ%3B%0A%0AQ~%3AA_%2C%7B%7BAf%3De__%26%7D%25_%7D*%5D%3A.%7CA.%26A%3A%24%3Ae%60e_2%251-*!%0A%0Ap%7D%2F) ### Dissection ``` q~:A e# Parse input and store in A _,{ e# Loop V times { e# Extend adjacency list representation of G^i to G^(i+1) Af= e# by extending each path by one edge e__& e# and flattening. NB :| would be shorter but breaks for empty lists }% _ e# Duplicate, so that we build up G^2, G^3, ..., G^n }*] e# Gather in a single array :.| e# Fold pointwise union, giving the reachability from each vertex by e# paths of length > 1 A.& e# Pointwise intersect with the paths of length 1 e# We hope to get an array of empty arrays e# Handle the awkward special case of duplicate edges: A:$ e# Sort each adjacency list :e` e# Run-length encode each adjacency list e_2% e# Extract only the run lengths 1- e# Discard the 1s - so we now have an empty array unless there's a dupe * e# Join. We hope to be joining an array of empty arrays by an empty array e# giving an empty array ! e# Check that we get a falsy value (i.e. the empty array) ``` [Answer] # Jelly, 20 bytes ``` ị³$ÐĿ€ị@Fœ&¥";œ-Q$€E ``` Uses 1-based indexing. [Try it online!](http://jelly.tryitonline.net/#code=4buLwrMkw5DEv-KCrOG7i0BGxZMmwqUiO8WTLVEk4oKsRQ&input=&args=W1syLDNdLFs0XSxbNF0sW11dCg) ## Loose Overview ``` € for each vertex, ị³$ÐĿ compute its reach. Fœ&¥" intersect each vertex's lists of children and ị@ children's reaches. ; then concatenate the list of intersections with œ-Q$€ all duplicate edges in the original graph. E are all elements equal? checks that all are empty lists, meaning empty intersections and no duplicates. ``` ]
[Question] [ Write a program or function that accepts an integer in the range 1..3999 as input and returns the number of line segments required to express that integer in standard Roman numerals (so you would use XL but not VM). Examples: ``` 1 -> 1 4 -> 3 5 -> 2 9 -> 3 10 -> 2 40 -> 4 50 -> 2 90 -> 3 100 -> 1 400 -> 3 500 -> 2 900 -> 5 1000 -> 4 ``` Roman number conversion builtins *are* permitted, but you can solve the problem without them by repeatedly subtracting the largest remaining number from the above list. Example: 1234 = 4 + 1 + 1 + 2 + 2 + 2 + 3 = 15. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins. [Answer] **C, ~~148~~ 129 chars** ``` d,x,n[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,4,5,2,3,1,3,2,4,2,3,2,3,1};f(c){while(d+=(c/n[x])*n[x+13],c%=n[x++]);return d;} ``` My first code-golf :^). Since the question states I can use a function, I have changed main to a function to trim some chars (most importantly: pass c as parameter rather scanf) unpacked ``` d,x,n[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,4,5,2,3,1,3,2,4,2,3,2,3,1}; f(c){ while(d+=(c/n[x])*n[x+13], c%=n[x++]); return d; } ``` [Answer] # Pyth, ~~92~~ ~~76~~ 70 bytes ``` KsMc."/9hæ²z³Þ§ªW×Oû[Tnè,O¤"\/WQ=Q-Q=Nef!>TQ%2K aY@KhxKN;sY ``` [Try it here!](http://pyth.herokuapp.com/?code=KsMc.%22%2F9h%C3%A6%10%C2%B2z%C2%B3%C3%9E%C2%A7%C2%9D%1D%C2%AA%C2%8D%C2%93W%C3%97%0BO%C2%81%C2%95%C3%BB[%05T%0En%19%C3%A8%2CO%C2%A4%22%5C%2FWQ%3DQ-Q%3DNef!%3ETQ%252K+aY%40KhxKN%3BsY&input=1234&debug=0) Thanks to @FryAmTheEggman for some string packing suggestions which saved me some bytes! I am still wondering if there is a mathematical way of encoding this list. Will try to figure something out. # Explanation This uses the given algorithm. `K` contains the given list with the numbers and the corrosponding number of line segments in alternation. This list gets constructed by splitting a packed string, which gets decoded to `0/0/1/1/4/3/5/2/9/3/10/2/40/4/50/2/90/3/100/1/400/3/500/2/900/5/1000/4`, on `/` and mapping each element to an integer. ``` KsMc."..."\/WQ=Q-Q=Nef!>TQ%2K aY@KhxKN;sY # Q = input c."..."\/ # split the string on / KsM # map every number to int and assign to K WQ # while Q != 0 f %2K # only take every 2nd element of K and filter with T !>TQ # T <= Q =Ne # Take the last element of that and assign that to N =Q-Q # Q = Q - N xKN # index of the first occurence of N in K h # increment that index because we want the line segments aA@K # get the line segment from that index and append that to Y ;sY # end the loop and print the sum of all line segments in Y ``` [Answer] # Mathematica, ~~80~~ 72 bytes ``` Tr[Characters[#~IntegerString~"Roman"]/.{"I"|"C"->1,"M"->4,_String->2}]& ``` Anonymous function that just converts numbers to Roman numerals, replaces each character with its number of segments, and takes the total. [Answer] # Retina, 128 bytes ``` .+ $* 1{1000} t' 1{900} td 1{500} d 1{400} t 1{100} ' 1{90} t 1{50} d 1{40} t' 1{10} d 1{9} t 1{5} d 1{4} t 1 ' t d' d '' '+ $.0 ``` Simple replacing until there's nothing left to replace. Then the apostrophes are counted and that's our number of line segments. If input and output in unary are allowed, it's 115 bytes (although who would want to type 1234 ones?). [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKMXsxMDAwfQp0JwoxezkwMH0KdGQKMXs1MDB9CmQKMXs0MDB9CnQKMXsxMDB9CicKMXs5MH0KdAoxezUwfQpkCjF7NDB9CnQnCjF7MTB9CmQKMXs5fQp0CjF7NX0KZAoxezR9CnQKMQonCnQKZCcKZAonJwonKwokLjA&input=MTIzNA) [Try it online! (unary IO)](http://retina.tryitonline.net/#code=MXsxMDAwfQp0JwoxezkwMH0KdGQKMXs1MDB9CmQKMXs0MDB9CnQKMXsxMDB9CicKMXs5MH0KdAoxezUwfQpkCjF7NDB9CnQnCjF7MTB9CmQKMXs5fQp0CjF7NX0KZAoxezR9CnQKMQonCnQKZCcKZAonJw&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMQ) [Answer] # Python 3, 95 bytes ``` def f(a,b=0): for e in'᝴ᔝ஺ॣəȟĮô>9 ':e=ord(e);d=e//6;b+=a//d*(e%6);a%=d return b ``` The Unicode string consists of the code points: ``` 6004 5405 3002 2403 601 543 302 244 62 57 32 27 7 ``` [Answer] ## JavaScript (ES6), 79 bytes ``` n=>"0123323453"[[,a,b,c,d]=1e4+n+'',d]-(-"0246424683"[c]-"0123323455"[b])+a*4 ``` The strings represent the number of line segments for the units, tens and hundreds digits. (Thousands is simply four times the thousands digit.) This method seems to be shorter than other options such as the algorithm suggested in the question. Edit: Saved 2 bytes thanks to @user81655. [Answer] ## Java, 152 bytes [Because, ya know, Java.](http://meta.codegolf.stackexchange.com/a/5829) ``` n->{int c=0;int[]r={999,4,899,5,499,2,399,3,99,1,89,3,49,2,39,4,9,2,8,3,4,2,3,3,0,1};for(int i=0;i<26;i+=2)while(n>r[i]){n-=r[i]+1;c+=r[i+1];}return c;} ``` Simple literal implementation of the given algorithm. Array packs the transform information: even indexes are one less than the roman numeral and odd indexes are the count for that numeral. This is a lambda that takes and returns an `int`/`Integer`. This includes `IntUnaryOperator` or `UnaryOperator<Integer>`. ]
[Question] [ The task is simple: write assembly that computes the order of magnitude of an integer using as few clock cycles as possible. * Order of magnitude is defined as `log10`, not `log2`. * The range of valid input is `0` to `1012`, inclusive. Behaviour for input outside that range is undefined. * Values should be rounded down to the nearest integer, with the exception that given input `0` the output should be `0`. (You can consider this to be the best representation of negative infinity that's possible in unsigned integers). * Must be x86 assembly. * The integer must be a *runtime* value, not a static/inline integer. So we don't know what it is at compile time. * Assume that you have an integer loaded into a register already. (But include setting the value in the register in the answer for clarity). * Can't call any external libraries or functions. * Free to use any of the available instructions in the [Intel docs](http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf). * No C. * Any of the ~7 Intel Core architectures are acceptable (listed on [page 10](http://www.agner.org/optimize/instruction_tables.pdf)). Ideally Nehalem (Intel Core i7). The winning answer is one that uses the fewest clock cycles possible. That is, it can have the most operations per second. Approximate clock cycle summaries are here: <http://www.agner.org/optimize/instruction_tables.pdf>. Calculating clock cycles can happen after the answer is posted. [Answer] ### 7 cycles, *constant time* Here's a solution based on my [answer to this SO Question](https://stackoverflow.com/a/9721570/10396). It uses BSR to count how many bits are needed to hold the number. It looks up how many decimal digits needed to represent the largest number that many bits can hold. Then it subtracts 1 if the actual number is less than the nearest power of 10 with that many digits. ``` .intel_syntax noprefix .globl main main: mov rdi, 1000000000000 #;your value here bsr rax, rdi movzx eax, BYTE PTR maxdigits[1+rax] cmp rdi, QWORD PTR powers[0+eax*8] sbb al, 0 ret maxdigits: .byte 0 .byte 0 .byte 0 .byte 0 .byte 1 .byte 1 .byte 1 .byte 2 .byte 2 .byte 2 .byte 3 .byte 3 .byte 3 .byte 3 .byte 4 .byte 4 .byte 4 .byte 5 .byte 5 .byte 5 .byte 6 .byte 6 .byte 6 .byte 6 .byte 7 .byte 7 .byte 7 .byte 8 .byte 8 .byte 8 .byte 9 .byte 9 .byte 9 .byte 9 .byte 10 .byte 10 .byte 10 .byte 11 .byte 11 .byte 11 .byte 12 powers: .quad 0 .quad 10 .quad 100 .quad 1000 .quad 10000 .quad 100000 .quad 1000000 .quad 10000000 .quad 100000000 .quad 1000000000 .quad 10000000000 .quad 100000000000 .quad 1000000000000 ``` Compiles on GCC 4.6.3 for ubuntu and returns the value in the exit code. I'm not confident interpreting that cycles table for any modern processor, but using @DigitalTrauma's method, on the Nehalim processor, I get **7**? ``` ins uOps Latency --- - - BSR r,r : 1 3 MOVZX r,m: 1 - CMP m,r/i: 1 1 SBB r,r/i: 2 2 ``` [Answer] # Best case 8 cycles, Worst case 12 cycles Since it is not clear in the question, I am basing this off the Ivy Bridge latencies. The approach here is to use the `bsr` (bit scan reverse) instruction as a poor-man's log2(). The result is used as an index into a jump table which contains entries for bits 0 to 42. I am assuming that given that operation on 64bit data is implicitly required, then use of the `bsr` instruction is OK. In the best case inputs, the jumptable entry can map the `bsr` result directly to the magnitude. e.g. For inputs in the range 32-63, the `bsr` result will be 5, which is mapped to a magnitude of 1. In this case, the instruction path is: ``` Instruction Latency bsrq 3 jmp 2 movl 1 jmp 2 total 8 ``` In the worst case inputs, the `bsr` result will map to two possible magnitudes, so the jumptable entry does one additional `cmp` to check if the input is > 10n. E.g. for inputs in the range 64-127, the `bsr` result will be 6. The corresponding jumptable entry then checks if the input > 100 and sets the output magnitude accordingly. In addition for the worst case path, we have an additional mov instruction to load a 64bit immediate value for use in the `cmp`, so the worst case instruction path is: ``` Instruction Latency bsrq 3 jmp 2 movabsq 1 cmpq 1 ja 2 movl 1 jmp 2 total 12 ``` Here is the code: ``` /* Input is loaded in %rdi */ bsrq %rdi, %rax jmp *jumptable(,%rax,8) .m0: movl $0, %ecx jmp .end .m0_1: cmpq $9, %rdi ja .m1 movl $0, %ecx jmp .end .m1: movl $1, %ecx jmp .end .m1_2: cmpq $99, %rdi ja .m2 movl $1, %ecx jmp .end .m2: movl $2, %ecx jmp .end .m2_3: cmpq $999, %rdi ja .m3 movl $2, %ecx jmp .end .m3: movl $3, %ecx jmp .end .m3_4: cmpq $9999, %rdi ja .m4 movl $3, %ecx jmp .end .m4: movl $4, %ecx jmp .end .m4_5: cmpq $99999, %rdi ja .m5 movl $4, %ecx jmp .end .m5: movl $5, %ecx jmp .end .m5_6: cmpq $999999, %rdi ja .m6 movl $5, %ecx jmp .end .m6: movl $6, %ecx jmp .end .m6_7: cmpq $9999999, %rdi ja .m7 movl $6, %ecx jmp .end .m7: movl $7, %ecx jmp .end .m7_8: cmpq $99999999, %rdi ja .m8 movl $7, %ecx jmp .end .m8: movl $8, %ecx jmp .end .m8_9: cmpq $999999999, %rdi ja .m9 movl $8, %ecx jmp .end .m9: movl $9, %ecx jmp .end .m9_10: movabsq $9999999999, %rax cmpq %rax, %rdi ja .m10 movl $9, %ecx jmp .end .m10: movl $10, %ecx jmp .end .m10_11: movabsq $99999999999, %rax cmpq %rax, %rdi ja .m11 movl $10, %ecx jmp .end .m11: movl $11, %ecx jmp .end .m11_12: movabsq $999999999999, %rax cmpq %rax, %rdi ja .m12 movl $11, %ecx jmp .end .m12: movl $12, %ecx jmp .end jumptable: .quad .m0 .quad .m0 .quad .m0 .quad .m0_1 .quad .m1 .quad .m1 .quad .m1_2 .quad .m2 .quad .m2 .quad .m2_3 .quad .m3 .quad .m3 .quad .m3 .quad .m3_4 .quad .m4 .quad .m4 .quad .m4_5 .quad .m5 .quad .m5 .quad .m5_6 .quad .m6 .quad .m6 .quad .m6 .quad .m6_7 .quad .m7 .quad .m7 .quad .m7_8 .quad .m8 .quad .m8 .quad .m8_9 .quad .m9 .quad .m9 .quad .m9 .quad .m9_10 .quad .m10 .quad .m10 .quad .m10_11 .quad .m11 .quad .m11 .quad .m11_12 .quad .m12 .quad .m12 .quad .m12 .end: /* output is given in %ecx */ ``` This was mostly generated from gcc assembler output for [proof-of-concept C code I wrote](http://pastebin.com/4RqxJhsG). Note the C code uses a computable goto to implement the jump table. It also uses the `__builtin_clzll()` gcc builtin, which compiles to the `bsr` instruction (plus an `xor`). --- I considered several solutions before arriving at this one: * `FYL2X` to calculate the natural log, then `FMUL` by the necessary constant. This would presumably win this if it was an [tag:instruction:golf] contest. But `FYL2X` has as latency of 90-106 for Ivy bridge. * Hard-coded binary search. This may actually be competitive - I'll leave it to someone else to implement :). * Complete lookup table of results. This I'm sure is theoretically fastest, but would require a 1TB lookup table - not practical yet - maybe in a few years if Moore's Law continues to hold. ]
[Question] [ The challenge is to make a program that sorts a list of words, only that the words need to be in the order of a random given alphabet. Your program will accept a string of comma-separated words and a new alphabet. Your program will output every word in the same way in the new sorted order. ## Example: Input: ``` home,oval,cat,egg,network,green bcdfghjklmnpqrstvwxzaeiouy ``` Output: ``` cat,green,home,network,egg,oval ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the winner is the person with the shortest program. This is my first challenge so any improvements to the question/challenge are appreciated. [Answer] # Bash+coreutils, 37 bytes ``` tr ,$2 \\na-z<<<$1|sort|tr \\na-z ,$2 ``` ### Output: ``` $ ./alphasort.sh home,oval,cat,egg,network,green bcdfghijklmnpqrstvwxyzaeiouy cat,green,home,network,egg,oval, $ ``` [Answer] # CJam, ~~26~~ ~~19~~ 17 bytes ``` rr:A;',/{Af#}$',* ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Test case ``` $ cjam sort.cjam <<< 'home,oval,cat,egg,network,green bcdfghjklmnpqrstvwxzaeiouy' cat,green,home,network,egg,oval ``` ### How it works ``` rr " Read two whitespace-separated tokens from STDIN. "; :A; " Save the second token (the alphabet) in A. "; ',/ " Split the remaining token at commas. "; {Af#}$ " Sort by the chunks' characters' indexes in A. "; ',* " Join, separating by commas. "; ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 characters ``` j\,o_mx_zdNchczd\, ``` **Test:** ``` $ pyth -c "j\,o_mx_zdNchczd\," <<< 'home,oval,cat,egg,network,green bcdfghjklmnpqrstvwxzaeiouy' cat,green,home,network,egg,oval ``` **Explanation:** ``` Implicit: d=" " Implicit: z=input() j\, ",".join( o order_by(lambda N: _ rev( m map(lambda d: x_zd rev(z).index(d), N N), chczd\, z.split(" "[0].split(",") ``` Essentially, it sorts the chunks, with a key of the list of indexes of the characters in the string, then joins them on commas. The reversal businesses is shorter than spliting the string again. [Answer] # [R](https://www.r-project.org/), 49 bytes ``` function(w,a,`[`=chartr)"a-z"[a,sort(a["a-z",w])] ``` [Try it online!](https://tio.run/##HcdRDoMgDADQqyx8QdIdwZMQEztWwIngShXn5dmyvK/H3Q/d79nJXLJugDDZaXARWdgovF/KItTCotH@C200Y/eakq7CdUuzaBXLSlAOTOBQgEKATNIKLxCYKCv4MQZu6uGePsTXkta8vbnK0c4LaS77R5n@BQ "R – Try It Online") Translates words from given alphabet to `a-z`, then sorts and then translates back. Uses flexible I/O rules (vector of words and alphabet as string). --- With strict I/O rules it goes up by a lot ([R](https://www.r-project.org/) is not very good with strings): ### [R](https://www.r-project.org/), 112 bytes ``` function(s,`/`=strsplit,t=el(s/" "))paste(chartr("a-z",t[2],sort(chartr(t[2],"a-z",el(t[1]/",")))),collapse=",") ``` [Try it online!](https://tio.run/##NctBDoIwEEDRq5Cu2mQM0X1PQkiodVqQ0tbpAMrlETVu38@n3endzdHykKIs0NWdLkwlh4GBNQZZalEJpbIpjNL2hpikMKdNADeXFkoi/vMXfu0YuTm3tYDjVQpsCsHkgvoDu5OiTxNCWkwAaxjQe4jIa6IRPCHG6mpvzvf3MUwxP6jwsj43g0OaX8f/Bg "R – Try It Online") Here we do the splitting of the input string inside the function. First, we redefine `/` to be `strsplit`. It always returns a list, so we will need to extract the first element (which is shortest done by `el`). We split the words from the alphabet on and then the words themselves on `,`. Then we do the same trick as in the main answer. At the end we collapse the whole vector with `,` using `paste`. --- With many strange function redefinitions: ### [R](https://www.r-project.org/), 111 bytes ``` function(s,`?`=el,`[`=chartr,`/`=strsplit,t=?s/" ")paste("a-z"[t?2,sort((t?2)["a-z",?(t?1)/","])],collapse=",") ``` [Try it online!](https://tio.run/##HYtBDsIgEAC/0nCCZE2jd8JDGhMQF1pLAWHbaj9fibeZSaacTp5ujZamFHkFrbTEAHrQ0o6mUAHda1mp1BwmApKq9qxjIptKyJm5HGwgdYOaCnHeSAz/CKrJVfQM2F3cwaYQTK4om4vTcTamBSFtJoA1BOg9RKQ9lRl8QYzdwz6dH19zWGJ@l0rb/jkMTmn9tv8H "R – Try It Online") Here we also redefine `[` to be `chartr`, so we cannot use `[` to subscript `t` anymore, but we can use `el` for this purpose. This leads us also to redefining `?` to be `el` (after some trial and error with operator precedence). It is worth noting, that `?` can act as binary and unary operator and has the lowest precedence of all. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes ``` {","/x@<y?x:","\x}." "\ ``` [Try it online!](https://ngn.codeberg.page/k/#eJwNxksOQDAQANB9T9HMesJeJNwDi6ppfVuqaIm781ZPZQ8gpKHMYxGyv3V4E+BQM6Yq6O1CaE8xoxQeSWs05C/rJtSOyPBWdkr34zQvZt3c7s8r3IIGe0Ro2Acq1B9E) Takes input as outlined in question. * `" "\` split input on the space, into the list of comma-delimited words and the (shuffled) alphabet * `{...}.` call the function with the list of words as the first arg (`x`) and the alphabet as the second arg (`y`) * `x:","\x` split the string of comma-delimited words into a list of the words themselves, updating the `x` variable * `y?x` look up the index of each character in each word in the shuffled alphabet * `x@<` grade the resulting list of lists of indices, and apply the sort order to the list of words * `","/` join the individual words with commas # [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes ``` {x@<y?x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6qucLCptK+o5eJKi9ZQysjPTVWyVsovS8wBUsmJJUAyNT0dSOallpTnF2UDWelFqal5SprWSknJKWnpGVnZObl5BYVFxSVl5RVViamZ+aWVSrEADJ8efg==) Assumes more lenient input/output format; a first arg `x` of a list of words, and a second arg `y` containing the shuffled alphabet. A list of strings is returned instead of a comma-delimited string. [Answer] ## Ruby, ~~53~~ 50 bytes ``` a,b=$* $><<a.split(?,).sort_by{|w|w.tr b,'a-z'}*?, ``` I'm using Ruby's `tr` to replace the custom alphabet with `a-z` before sorting. Input is via command-line argument. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #`U',¡ΣXsSk}',ý ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fOSFUXefQwnOLI4qDs2vVdQ7v/f8/Iz83VSe/LDFHJzmxRCc1PV0nL7WkPL8oWye9KDU1TyEpOSUtPSMzKzsnN6@gsKi4pKy8oioxNTO/tBIA) With less restricted I/O rules, this could have been **2 (or 3) [bytes](https://tio.run/##LczNDYAgDIDRu2P0zEaEA2pFREHB/3Xcx5WwNhxewkfThqRrizm/j8tZSuhBQCATQVBCcu1Ek5F/mlIrF9LLsL887/0zAUe5FYnjqSmFhQelqrppO9PbwY2Tn5eY1v04b402bNcH)**: * `Σk`: [Try it online with character-list input](https://tio.run/##LczNDYAgDIDRu2P0zEaEA2pFREHB/3Xcx5WwNhxewkfThqRrizm/j8tZSuhBQCATQVBCcu1Ek5F/mlIrF9LLsL887/0zAUe5FYnjqSmFhQelqrppO9PbwY2Tn5eY1v04b402bNcH); * `ΣSk`: [Try it online with string-list input](https://tio.run/##Dca7FYAgDEDR3jFSu42lxwIwIvKJAoK6jvu4UqS571ES0iDz9w6WeYSVPEIPVIRrUSI3UetmwFwp2nY6IgaYOqnmRa9ms86H/Ygpl3o9Ag2d9w8). **Explanation:** ``` # # Split the (implicit) input-string by spaces ` # Pop and push both strings separated to the stack U # Pop the alphabet-string, and store it in variable `X` ',¡ '# Split the words-string on "," Σ # Sort this list of words by: X # Push the alphabet-string `X` s # Swap so the current word is at the top of the stack again S # Convert it to a list of characters k # Get the index of each character in the alphabet-string }',ý '# After the sort-by: join this list of words with "," delimiter # (after which this string is output implicitly as result) Σ # Sort the first (implicit) input-list of character-lists by: k # Index each character into the second (implicit) alphabet-string # (after which the sorted list of character-lists is output implicitly) ``` [Answer] ## Clojure, ~~115~~ 50 bytes Oh, an edit five years later :D And actually in the past I out-golfed myself, now I used `(map char(range 97 123))` to generate the `a - z` sequence but my original answer just re-uses the alphabet input via `(sort %2)`. Well this new answer requires a more liberal input format, namely the first argument is a list of words. ``` #(map(fn[i](str(mapv(zipmap %2(sort %2))i)))%) ``` I had to re-discover that vectors don't sort neatly, but this can be avoided by casting them to strings. And not by using `clojure.string/join` or `apply str`, they sort just fine as string representations of the vector! Change the `sort-by` to `map` and you get: ``` (def f #(map(fn[i](str(mapv(zipmap %2(sort %2))i)))%)) (f ["home", "oval", "cat", "egg", "network", "green"] "bcdfghjklmnpqrstvwxzaeiouy") ("[\\f \\x \\j \\v]" "[\\x \\q \\u \\i]" "[\\b \\u \\p]" "[\\v \\e \\e]" "[\\k \\v \\p \\r \\x \\n \\h]" "[\\e \\n \\v \\v \\k]") ``` [TIO](https://tio.run/##HcxBDoMgEIXhvaeY0JjMJO2m1zEuUAdEESiiVi9PpavvX7y83vppi5wzDqxAwQNXH9OrO1G5xrS4poiLDDteJtxC/f4PbokMEdVEVVVhiMYl6wAVNGL0C4snCL9LW@xlKrDWBcfp8HEuqSOzEy2Irh@UHqfZLi584pr243tJNn47xf2f8w8) **Original answer:** ``` #(apply str(butlast(interleave(sort-by(fn[w](apply str(map(zipmap(sort %2)%2)w)))(re-seq #"[a-z]+"%))(repeat \,)))) ``` Wow, this started of well with `(sort-by(fn[w](mapv(zipmap(sort %2)%2)w)))` but then I realized `vec` don't get sorted the same way as strings, and interleaving those commas takes significant amount of code as well. [Answer] # Python, 131 ``` w,a=input().split() print(",".join(sorted(w.split(","),key=lambda s:"".join(["abcdefghijklmnopqrstuvwxyz"[a.find(c)]for c in s])))) ``` There should be plenty of room for improvement. [Answer] # JavaScript (E6) 102 ~~119~~ Sort with a mapping function 'M' based on the alphabet in variable 'a' *With IO using popup (prompt + alert)* ``` x=prompt().split(/[ ,]/), a=x.pop(), M=w=>[10+a.search(c)for(c of w)]+'', alert(x.sort((a,b)=>M(a)>M(b))) ``` *As a (testable) function with 1 string parameter, returning a string array (92)* ``` F=x=>( M=w=>[10+a.search(c)for(c of w)], x=x.split(/[ ,]/), a=x.pop(), x.sort((a,b)=>M(a)>M(b)) ) ``` **Test** In FireFox/FireBug console ``` F('home,oval,cat,egg,network,green zyxwvtsrqpnmlkjhgfdcbaeiou') ``` *Output* ``` ["network", "home", "green", "cat", "egg", "oval"] ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 15 bytes ``` b@?^_SKa^',J:', ``` Takes the two inputs as command-line arguments. [Try it online!](https://tio.run/##BcE9GkAwDADQ41hyAgszo72@lIiiP6paXD7eCyaI6LZR49CjqqCrKxCR1VsCn/GACRMQMzhKxccdOBI5YIMuiZ7mhddtP6wLZ7xSLs@HZPz9/g "Pip – Try It Online") ### Explanation ``` b@?^_SKa^',J:', a ; First command-line arg (list of words) ^', ; Split on commas SK ; Sort by the following key function: ^_ ; Split the word into a list of letters @? ; Get the index of each letter in b ; The second command-line arg (alphabet) J:', ; Join the resulting list on commas ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¸Îq, nU¸Ì q, ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=uM5xLCBuVbjMIHEs&input=ImhvbWUsb3ZhbCxjYXQsZWdnLG5ldHdvcmssZ3JlZW4gYmNkZmdoamtsbW5wcXJzdHZ3eHphZWlvdXkiCi1R) [Answer] # [Zsh](https://www.zsh.org), 24 bytes ``` tr $1 a-z|sort|tr a-z $1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY7SooUVAwVEnWraorzi0pqgFwgGygEkYaq2hetlJSckpaekZWdk5tXUFhUXFJWXlGVmJqZX1qpFLs_Iz83lSu_LDGHKzmxhCs1PZ0rL7WkPL8omyu9KDU1D2IIAA) If we must use the OP's inane I/O format, 37 bytes: ``` tr $2, a-z\\n<<<$1|sort|tr a-z\\n $2, ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwU274tQShYz83FSd_LLEHJ3kxBKd1PR0nbzUkvL8omyd9KLU1DyFpOSUtPSMrOyc3LyCwqLikrLyiqrE1Mz80sqlpSVpuhY3VUuKFFSMdBQSdatiYvJsbGxUDGuK84tKaoDiEDGQNETxAii1H2QrF8hWLqCtXEBbuaC2coFthSgDAA) If a trailing comma is not allowed either, append `|head -c-1` for +10 bytes. [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes With flexible input : ``` lambda w,a:sorted(w,key=lambda s:[*map(a.find,s)]) ``` [Try it online!](https://tio.run/##Lc29DoMgGIXh3aswLkhDunQz4Uqsw6d8oFV@ClRKb56WpNPz5izH5bhacyuS38sBehbQJgZDsD6i6BPbMfP/HobxosH1cJWbESzQiZbER7JajYS1xJ5wVBeIFVSqYjAm6/eayiMaMjXAu3kRUq2P/dDGPX2IZ3p/ADf7yl3TOL@Z2MvfO1Bavg "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 71 bytes With strict input format : ``` lambda x:sorted(x[:-27].split(","),key=lambda s:[*map(x[-26:].find,s)]) ``` [Try it online!](https://tio.run/##Lco9DoMgGADQ3VMYJ2jQwSZtQuJJrAPKB1L5K1DFXp526JufP9Pq7LWI4VE0MzNndabRhQQc5ZG2/X3qotcqoYY0mGxwDv8W6XgxzP9W29/o1AllOYl4wiUPzeoMELczTRaWCEhJLKTDhY3IAGDreeFCrs9NG@tfIab9yB8Gyr3Ppqp8UDYhgTLG5Qs "Python 3 – Try It Online") Both can be shortened by 3 bytes in python 2 by removing `[* ]` arround the `map` ]
[Question] [ **Input**: An RGBA hex color `c` (ex. `FFFF00FF`) and an integer > 0 and < 1000 `n` (ex. `200`). **Output**: Raw bytes of a PNG file such that when the output is saved to a file and opened in an image viewer, an `n` by `n` image filled with the color `c` is displayed. **Specification**: Your program should output **exactly**: * a PNG header (`89504E470D0A1A0A` in hex) * an `IHDR` chunk containing these specifications: + width: the previous input `n` + height: the previous input `n` + bit depth: `8` (`RGBA`) + color type: `6` (truecolor with alpha) + compression method: `0` + filter method: `0` + interlace method: `0` * one or more `IDAT` chunks containing the image data (a solid image of color previously input `c`); may be compressed or uncompressed * an `IEND` image end chunk Further details available on [Wikipedia](http://en.wikipedia.org/wiki/Portable_Network_Graphics#Technical_details), on [the W3 site](http://www.w3.org/TR/PNG/#5DataRep), or via a Google search. **Restrictions**: * You may not use any image libraries or functions designed to work with images of any kind. * Your program must run in under 3 minutes and output a file under 10 MB for all inputs (sanity check). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # Perl, 181 ``` / /;use String::CRC32;use Compress::Zlib;sub k{$_=pop;pack'Na*N',y///c-4,$_,crc32$_}$_="\x89PNG\r\n\cZ\n".k(IHDR.pack NNCV,$',$',8,6).k(IDAT.compress pack('CH*',0,$`x$')x$').k IEND ``` Size is 180 bytes and option `-p` is needed (+1). Score is then 181. The arguments are given via STDIN in a line, separated by a space, the color as hex value (16 chars) and the number of pixels for width/height, e.g.: ``` echo "FFFF00FF 200" | perl -p solidpng.pl >yellow200.png ``` ![yellow200.png](https://i.stack.imgur.com/7XXF8.png) The file size is 832 bytes. The maximal sized image (n=999) with the same color has 6834 bytes (way below 10 MB). The solution uses two libraries: * `use Digest::CRC crc32;` for the CRC32 values at the chunk ends. * `use IO::Compress::Deflate deflate;` to compress the image data. Both libraries are not related to images. **Ungolfed:** ``` # Perl option "-p" adds the following around the program: # LINE: # while (<>) { # ... # the program goes here # } continue { # print or die "-p destination: $!\n"; / /; # match the separator of the arguments in the input line # first argument, color in hex: $` # second argument, width/height: $' #' # load the libraries for the CRC32 fields and the data compression use String::CRC32; use Compress::Zlib; # function that generates a PNG chunk: # N (4 bytes, big-endian: data length # N: chunk type # a* (binary data): data # N: CRC32 of chunk type and data sub k { $_ = pop; # chunk data including chunk type and # excluding length and CRC32 fields pack 'Na*N', y///c - 4, # chunk length #/ # netto length without length, type, and CRC32 fields $_, # chunk type and data crc32($_) # checksum field } $_ = # $_ is printed by option "-p". "\x89PNG\r\n\cZ\n" # PNG header # IHDR chunk: image header with # width, height, # bit depth (8), color type (6), # compresson method (0), filter method (0), interlace method (0) . k('IHDR' . pack NNCV, $', $', 8, 6) # IDAT chunk: image data . k('IDAT' . compress # compress/deflate data pack('CH*', # scan line with filter byte 0, # filter byte: None ($` x $') # pixel data for one scan line #'` ) x $' # n lines #' ) # IHDR chunk: image end . k('IEND'); ``` **Edits** * `use IO::Compress::Deflate':all';` is replaced by `use Compress::Zlib;`. The latter does export the deflate function `compress` by default. The function does not need references as arguments and also returns the result directly. That allows to get rid of variable `$o`. Thanks for Michael's [answer](https://codegolf.stackexchange.com/a/28134/16143): * Function `k`: A call of `pack` could be removed by using template `Na*N` for the first `pack` in the function. * `pack` template `NNCV` with four values optimizes `NNC3n` with six values. Thanks for VadimR's [comment](https://codegolf.stackexchange.com/questions/27086/output-a-solid-png-from-scratch/28133?noredirect=1#comment60720_28133) with lots of tips: * `use String::CRC32;` is shorter than `use Digest::CRC crc32;`. * `y///c-4` is shorter than `-4+y///c`. * The scan line is now constructed by the template `CH*` with the repetition in the value. * Removal of `$i` by using a value reference. * Bare words instead of strings for the chunk types. * Options now read by matching a STDIN input line (option `-p`) with matching the space separator `/ /`. Then the first option is in `$`` and the second argument goes in `$'`. * Option `-p` also automatically prints `$_`. * `"\cZ"` is shorter than `"\x1a"`. ## Better compression At the cost of code size the image data can be further compressed, if filtering is applied. * Unfiltered file size for `FFFF0FF` `200`: 832 bytes * Filter `Sub` (horizontal pixel differences): 560 bytes ``` $i = ( # scan line: "\1" # filter "Sub" . pack('H*',$c) # first pixel in scan line . ("\0" x (4 * $n - 4)) # fill rest of line with zeros ) x $n; # $n scan lines ``` * Filter `Sub` for the first line and `Up` for the remaining lines: 590 bytes ``` $i = # first scan line "\1" # filter "Sub" . pack('H*',$c) # first pixel in scan line . ("\0" x (4 * $n - 4)) # fill rest of line with zeros # remaining scan lines . ( "\2" # filter "Up" . "\0" x (4 * $n) # fill rest of line with zeros ) x ($n - 1); ``` * First unfiltered line, then filter `Up`: 586 bytes ``` $i = # first scan line pack('H*', ("00" . ($c x $n))) # scan line with filter byte: none # remaining scan lines . ( "\2" # filter "Up" . "\0" x (4 * $n) # fill rest of line with zeros ) x ($n - 1); ``` * Also `Compress::Zlib` can be tuned; the highest compression level can be set by additional option for the compression level in function `compress` at the cost of two bytes: ``` compress ..., 9; ``` File size of example `yellow200.png` without filtering decreases from 832 bytes to 472 bytes. Applied to the example with `Sub` filter, the file size shrinks from 560 bytes to 445 bytes (`pngcrush -brute` can't compress further). [Answer] ## PHP 214 I'm not an expert on PHP, there is place for golfing. Tips are welcomed. ``` <?function c($d){echo pack("Na*N",strlen($d)-4,$d,crc32($d));}echo"\x89PNG\r\n\x1a\n";c("IHDR".pack("NNCV",$n=$argv[1],$n,8,6));c("IDATx^".gzdeflate(str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n)));c("IEND"); ``` Generate a PNG file: ``` php png.php 20 FFFF00FF > output.png ``` Generate base64 stream (paste the result in your browser address bar) ``` echo "data:image/png;base64,`php png.php 200 0000FFFF | base64`" ``` Ungolfed version : ``` <?php //function used to create a PNG chunck function chunck($data) { return pack("Na*N", //write a big-endian integer, a string and another integer strlen($data)-4, //size of data minus the 4 char of the type $data, //data crc32($data)); //compute CRC of data } //png header echo "\x89PNG\r\n\x1a\n"; //IHDR chunck echo chunck("IHDR".pack("NNCV", //2 big-endian integer, a single byte and a little-endian integer $n=$argv[1], $n, 8, 6)); //6 also write 3 zeros (little endian integer) //IDAT chunck //create a binary string of the raw image, each line begin with 0 (none filter) $d = str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n); echo chunck("IDATx^". gzdeflate($d)); //compress raw data //IEND chunck echo chunck("IEND"); ``` [Answer] # Python, 252 bytes ``` import struct,sys,zlib as Z P=struct.pack A=sys.argv I=lambda i:P(">I",i) K=lambda d:I(len(d)-4)+d+I(Z.crc32(d)&(2<<31)-1) j=int(A[2]) print "\x89PNG\r\n\x1A\n"+K("IHDR"+P(">IIBI",j,j,8,6<<24))+K("IDAT"+Z.compress(("\0"+I(int(A[1],16))*j)*j))+K("IEND") ``` This script takes input from argv. Run this script from command line, like `python 27086.py deadbeef 999` ]
[Question] [ Write the shortest program to solve a quartic equation. A quartic equation is a polynomial equation of the form: \$ax^4 + bx^3 + cx^2 + dx + e=0\$ A solution for \$x\$ is a number such that the above evaluates to 0. --- **Rules** * The program must take in the 5 floating point coefficients of the equation \$ax^4+bx^3+cx^2+dx+e\$ as `"a b c d e"` separated by spaces. * It must then output a single real solution. If there exist no real solutions then it outputs an `"n"`. * No bonus for extra solutions. * No use of CAS (Computer algebra systems). This includes symbolic manipulation properties of Mathematica and related software. * No connecting to external libraries, web calculators etc... * You may use formulas or your own manipulation * Native math libraries that do not solve equations may be used, eg. .NET: System.Math * You may deduct 50 from your char count if recursion is a main technique used. * As long as there is no difference with the answer obtained algebraically, numerical approximation is welcome however adds 25 chars to your solution. This really relies on the accuracy of the floating-point numbers. (Which should be 64 bit). The winner will be picked in 1 week. (26/02/2014) [Answer] # C++ A fast and robust solution, 704 chars + numeric - recursion = 679 ``` #include "stdafx.h" #include "math.h" double a,b,c,e,j,k,l,p,q,t,z;void s(double x, int i){if(i==99)printf("%f\n",x);else s(x-((x+b)*x*x*x+c*x*x+l*x+e)/(4*x*x*x+j*x*x + k*x + l),i+1);} void _tmain(){double r[8];scanf_s("%lf%lf%lf%lf%lf",&a,&b,&c,&l,&e);b/=a;c/=a;l/=a;e/= a;j=3*b;k=2*c;p=(12*k-j*j)/48;q=(2*j*j*j-36*j*k+432*l)/1728;z=q*q/4+p*p*p/27;int u=0,v=0,g; for(g=1;g<4;g++){r[g]=z>0|p==0?cbrt(-q/2+sqrt(z))+cbrt(-q/2-sqrt(z))-j/12:sqrt(-p/.75)*cos(acos(-q/sqrt(-p*p*p*4/27))/3-g*acos(-.5))-j/12;r[g+4]=(r[g]+b)*pow(r[g],3)+c*r[g]*r[g]+l*r[g]+e;if(r[g+4]>r[g+3]|g==1)u=g;if(r[g + 4]<r[g+3]|g==1)v=g;} if(r[v+4]>0)printf("n\n");if(r[v+4]==0)printf("%f\n",r[v]);if(r[v+4]<0)s(2*r[v]-r[u]+(r[v]-r[u]==0),0);} ``` This is by no means the shortest answer, but so far no other answer has confirmed that it will work with curves with the full 3 stationary points (maxima/minima.) These correspond to curves with large values of b and c of opposite sign to a. None of the test data in the other solutions has local maxima/minima apart from the global one. The nearest is Eelvex's `1 2 0 0 1` which has a kink on one side where dy/dx falls to zero. This program handles all the test data shown in other solutions, plus the following interesting examples, amongst others: ``` 1 0 1 0 0 --> multiple root 0 1 0 -1 0 0 --> multiple root at 0, but the program prefers the simple root at -1 1 0 -1 0 0.25 --> multiple roots at +/- 0.7071 = sqrt(0.5) ``` It cannot handle the case a=0, but that is not a quartic so it is out of scope. ~~The only problem I have found but not eliminated is b=c=d=0, but that is an easy problem to fix. I will do it when I golf the code (if I get round to that.) I expect it to come in around 700-800 chars.~~ **How it works** The program divides the whole formula by `a` (which does not affect the roots, but ensures that we know that `y= +infinity` at `x = +/- infinity` ) It then calculates the formula for dy/dx (a cubic) and solves this analytically for dy/dx=0. The code to do this is quite short (the explanation in the comments is much longer than the code itself.) It calculates the values of `y` at the up to 3 stationary points where dy/dx=0 and looks for the lowest (global minimum.) If this `y` is positive here , the whole curve is above the x axis and there are no roots. If `y` is zero, then it is a root and this is reported directly. Such a root would be problematic for newton raphson. If `y` is less than zero, the program makes a guess for the root on the opposite side of the global minimum from the other stationary points (to avoid getting trapped in the local maximum if there is one.) Then it searches using newton-raphson (recursive, as you insisted.) This method is fast and simple, and once the right region of the curve has been identified, does not run the risk of dividing by zero. I did run into other problems with it though. It quickly got very close to a solution (good enough for a human) but kept searching. With the rapid initial convergence, I assumed that the problem was that it couldn't get to f(x)==0 because f'(x) was large and f(x)/f'(x) was being rounded to zero in the calculation. So I put in an extra test condition for f(x)/f'(x) but it still did the same. Then I limited it to just 10 iterations, which is more than enough for all the tests I have done. The current version goes up to 99 iterations. The ungolfed version has medium verbosity output (with uncommentable code for high verbosity) as seen in the screenshot and has its iterations terminated when f(x)==0. The golfed version has low verbosity (in accordance with specified requirements) and always runs to 99 iterations. The golfed version has other minor differences, such as no while loop and simplified (but less clear) expressions. There are certainly other methods which might work better, but I think that might go into another answer (which I don't think I have time for.) **Ungolfed version** ``` #include "stdafx.h" #include "math.h" double a,b,c,d,e,j,k,l,p,q,t,z; //explanation of variables //dy/dx= i* x3 + j*x2 + k*x + l. No i variable needed as it is normalised to 4. //depressed form of dy/dx: t3+pt+q. A subsitution is used to eliminate the squared term, see below. //z=q2/4 + p3/27. z is proportional to the "discriminant." The sign tells the number of roots of dy/dx // +ve z means 1 real root, -ve z means 3 real roots, 0 means one simple root plus a double root. // recursive newton-raphson to depth i void s(double x, int i){ double m=(x + b)*x*x*x + c*x*x + d*x + e; if (m == 0 | i == 99) printf("z= %f x= %f y= %f iteration %d\n", z,x,m,i); else s(x-m/(4*x*x*x + j*x*x + k*x + l), i+1); } void _tmain(){ while (true){ double r[8]; //r[1,2,3] and r[5,6,7] store x and y values of the maxima and minima. //r[0] and r[4] are dummies to handle [subscript-1] references. scanf_s("%lf %lf %lf %lf %lf", &a, &b, &c, &d, &e); //uncomment for verbose output: printf("data for minima and maxima \n"); //uncomment for verbose output: printf(" z x dy/x y hi/low \n"); //hi/low indicate which y values are highest and lowest: 1st, 2nd, 3rd. //Divide by a to give a "monic polynomial" with a=1. //This does not affect the roots but saves a lot of typing of powers of a. // differentiate to i*x3 + j*x2 + k*x + l. As a=1, we know i=4. b /= a; c /= a; d /= a; e /= a; j = 3*b; k = 2*c; l = d; // to prepare to solve this cubic, convert to depressed cubic t3+pt+q, eliminating x2. x=t-j/(3*i) // p=(3*i*k - j2)/(3*i2) q=(2*j3 - 9*i*j*k + 27*i2*l)/27*i3. But we know i=4. p = (12 * k - j*j) / 48; q = (2 * j*j*j - 36 * j*k + 432 * l) / 1728; z = q*q / 4 + p*p*p / 27; //u and v indicate which of the stationary points are highest and lowest. //solve dy/dx, store the roots in r[1,2,3] and the y values in r[5,6,7]. int u=0,v=0,g; for (g = 1; g < 4; g++){ //if z>0 or p==0 use cardano's method to store the one real root of dy/x three times in r[1,2,3] //if z<=0 use viete's trigonometric method to find the multiple real roots. //use of different methods for each case avoids the need to handle complex numbers. r[g] =z > 0 | p==0? cbrt(-q / 2 + sqrt(z)) + cbrt(-q / 2 - sqrt(z)) - j / 12 : sqrt(-p / .75)*cos(acos(-q / sqrt(-p * p * p * 4 / 27)) / 3 - g*acos(-.5)) - j / 12; r[g+4] = (r[g]+b)*pow(r[g],3) + c*r[g]*r[g] + d*r[g] + e; if (r[g + 4]>r[g+3]|g==1)u=g; if (r[g + 4]<r[g+3]|g==1)v=g; // uncomment for verbose output //printf("%f %f %f %f %d %d \n \n", z, r[g], 4 * pow(r[g], 3) + j*pow(r[g], 2) + k*r[g] + l, r[g+4], u, v); } //because we divided by a, the new a=1 and y tends to infinity at large |x|. //so if the lowest stationary point has y>0, the whole curve is above the x axis and there is no solution. //if the lowest stationary point has y=0 it is tangent to the x axis and would cause problems for newton-raphson //if the lowest stationary point has y<0, use newton raphson, 99 iterations. ensure 1st guess is on the side //opposite the highest stationary point, just in case that point also has y<0, to avoid getting trapped. //special case: if r[v]-r[u] == 0 (implies only one stationary point) then add 1! if (r[v+4] >0) printf("n\n"); if (r[v+4]==0) printf("z= %f x= %f multiple root", z,r[v]); if (r[v+4] <0) s(r[v]+(r[v]-r[u])+(r[v]-r[u]==0),0); } } ``` **Output** All data tested by other answers is here, as well as many additional examples. The sign of the value `z` is positive when there is only one stationary point where dy/dx=0, negative when there are three (2 minima and a maximum if a is positive), and zero when there are two (a minimum if a is positive, plus an inflexion.) This is the only answer so far that presents test cases for three stationary points. The `y` values are shown for easy checking of the program. `y` is zero at the root, and as can be seen, an acceptable zero is always found. The golfed version is low verbosity, displaying only the root per question spec. ![enter image description here](https://i.stack.imgur.com/yClwf.png) [Answer] # J, 222 *247 - recursion + numerical* ``` NB. multiple lines for visibility f=:[:-(]$:~[:}.[-%&{.*],#&0@l)`[@.(0>l=:-&#) r=:1={. s=:[:=/+/@(2=&*/\])@(,.]*_1^i.@#)@({.@>@(([;];f;j;f f j=.]f f)([:}:(i._5)*])))@|. u=:0,0([(]*_1^r@k)>:@]^:(1 1-:k=:[:*(0 p.~[)*(p.(,-)))^:_)~] h=:{.@((n@],]{~[:r[:*p.*(p.n=:{.+-:@-~/))^:_ u)`('n'"_)@.s@|. ``` ### Methods * Using Sturm's theorem to find number of roots. `f` is polynomial division (recursive) `s` is Sturm's theorem output: `0` for no real roots, `1` otherwise. It evaluates Sturm's polynomials `([;];f;j;f f j=.]f f)` and checks their behaviour at +/- infinity. * Using bisection method to avoid divisions by zero, local maxima etc. `u` scans from 0 to +/- infinity to find an appropriate interval `((n@],]{~[:r[:*p.*(p.n=:{.+-:@-~/))^:_ u)` evaluates the polynomial at the edges and midpoint then halfs the interval accordingly ### Verification of results Using J's buildin polynomial root finder as `realRoots`: ``` ti,>([;h;realRoots) each samples ┌──────────────┬────────┬─────────────────┐ │a b c d e │output │all real roots │ ├──────────────┼────────┼─────────────────┤ │_1 2 3 4 5 │_1.11029│3.37192 _1.11029 │ ├──────────────┼────────┼─────────────────┤ │_1 2 3 4 _5 │0.728727│3.18248 0.728727 │ ├──────────────┼────────┼─────────────────┤ │1 2 3 4 5 │n │ │ ├──────────────┼────────┼─────────────────┤ │1 1 2 _1 _1 │0.728262│0.728262 _0.52236│ ├──────────────┼────────┼─────────────────┤ │1 2 3 4 0 │0 │_1.65063 0 │ ├──────────────┼────────┼─────────────────┤ │1 2 0 0 1 │_1 │_1.83929 _1 │ ├──────────────┼────────┼─────────────────┤ │_1 _1 _1 _1 _1│n │ │ └──────────────┴────────┴─────────────────┘ ``` *BTW, a simple implementation of Newton's method would be:* ``` f=:3 :'((-(y&p.%y&p.D.1))^:_)0'@|. ``` [Answer] # C — 340 bytes + 25 points for numerical approximation = 365 To compile `gcc -o quartic quartic.c -lm`, to run `./quartic a b c d e`. Uses Newton–Raphson method, no big whoop. Using deterministic methods, I can't see getting anywhere near this compact. ``` #include <stdlib.h> #include <stdio.h> #include <math.h> #define C(x) atof(argv[x]) int main(int argc,char *argv[]){int i;double a,b,c,d,e,x,y;a=C(1);b=C(2);c=C(3);d=C(4);e=C(5);for(x=0,y=1,i=0;i<100;x=y,i++){y=x-((((a*x+b)*x+c)*x+d)*x+e)/(((4*a*x+3*b)*x+2*c)*x+d);if(fabs(x-y)<1e-09){printf("%.9f\n",y);return 0;}}printf("n\n");return 1;} ``` e.g. ``` $ ./quartic 1 2 3 4 5 n $ ./quartic -1 2 3 4 5 -1.110290760 $ ./quartic -1 2 3 4 -5 0.728726879 ``` Verified via Wolfram|Alpha, results check out. [Answer] # bc (driven by bash), score:137 (162 bytes -50 recursion bonus +25 numerical penalty) ``` bc -ql<<Q n=0 define r(x){if(n++>99){print "n ";halt} y=x-($1*x^4+$2*x^3+$3*x*x+$4*x+$5)/(4*$1*x^3+3*$2*x*x+2*$3*x+$4) if(y==x){print x," ";halt}else r(y)}r(0) Q ``` This is pretty much the same algorithm as the [c](/questions/tagged/c "show questions tagged 'c'") answer, though it uses recursion to spice it up. Run as follows: ``` $ ./quartic.sh 1 2 3 4 5 n $ ./quartic.sh -1 2 3 4 5 -1.11029075952058816917 $ ./quartic.sh 1 2 3 4 -5 .68412431945306971026 $ ``` Of course Newton-Raphson has its limitations, and won't necessarily give all real roots in all cases where the exist. According to WolframAlpha, this one has real roots at -1.9144 and 1.3731: ``` $ ./quartic.sh 1 1 -2 -1 -1 n $ ``` Also there is a very real risk of divide-by-zero in some cases. But this is code-golf, so who cares ;-) [Answer] # C, 182 + 25 = 207 This is not the most eleant solution but it is certainly creative. Using iterger pointer conversions, it loops through every possibile value that a double can hold, tries it out, and checks if it equals 0. ``` int main(int z,char **v){double a[5],f=0,r=1;int i=5;while(i-->0)scanf("%lf",a+i);while(++(*(int*)&f)&&r){i=5,r=0;while(i-->0)r+=a[i]*pow(f,i);}if(r)printf(“%f",r);else printf("n");} ``` [Answer] ### Ruby — 132 characters + 25 numerical = 157 ``` require'matrix';f=->a,b,c,d,e{a=-a.to_f;Matrix[[0,0,0,e/a],[1,0,0,d/a],[0,1,0,c/a],[0,0,1,b/a]].eigen.eigenvalues.find(&:real?)||?n} ``` I think this toes the line of using native math libraries, but it's a pretty cool demonstration of what can be done with Ruby, as well as an intriguing way to look at solving univariate polynomial equations through the lens of linear algebra. Basically, `f` just constructs the [companion matrix](http://en.wikipedia.org/wiki/Companion_matrix) of the equivalent monic quartic and computes its eigenvalues, which is the same thing as finding the roots of the original quartic. [Answer] ## Javascript/ES6 148 Since only *a* solution is required, I used a Newton solver. ``` f=s=>{a=s.split(' ');for(x=i=0;i++<1e5;x-=y)z=x*x,y=(a[0]*z*z+a[1]*x*z+a[2]*z+a[3]*x+ +a[4])/(4*a[0]*z*x+3*a[1]*z+2*a[2]*x+ +a[3]);return y|0?'n':x} ``` If you don't have Firefox, you can test it without fat arrow : ``` function f(s){a=s.split(' ');for(x=i=0;i++<1e5;x-=y)z=x*x,y=(a[0]*z*z+a[1]*x*z+a[2]*z+a[3]*x+ +a[4])/(4*a[0]*z*x+3*a[1]*z+2*a[2]*x+ +a[3]);return y|0?'n':x} ``` Test : `f('1 -2 5 -12 4')` returns `0.3882914410047445` **Warning** : [This **can fail** for some equations (if `d=0` for example).](http://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis) ]
[Question] [ <http://en.wikipedia.org/wiki/Dissociated_press> Dissociated Press is an algorithm that generates random text from an existing text. > > The algorithm starts by printing any N consecutive words (or letters) in the text. Then at every step it searches for any random occurrence in the original text of the last N words (or letters) already printed and then prints the next word or letter. Implement Dissociated Press, either as a function or as a whole program. Shortest code wins. Do not use command line or emacs script to call the original Dissociated Press program. Do not use any external libraries. [Answer] ## Perl, 81 ~~82~~ Uses 2 character overlap, discounts newlines, stops when it encounters a dead-end. ``` for($/=$,,$_=<>,@_=/(..)/;print($a=$_[rand @_]),($b.=$a)=~/..$/,@_=/\Q$&\E(.)/g;){} ``` For example, used on the beginning of the test of the wikipedia article for Markov chains: ``` $ perl dissociated.pl markov.txt ``` > > A stels trances hilitions If ateles a state pre plithe propers posion 1), wouse Markov priesse (MCMCSTs the iste-tion. Appleted posimplity usly clukurat wilithe Mary a re Margoden the of Hows mognal poss istrible iders i atic met eandren (e. It hains, froughe for exam. Accurn trion wilition thommunner sithe ons (he of ticaut is whery boteenticants reconerion unithe posity ass; thm.[17] In π. Time comon-logrobabilical.'s to a retion whermatry a stakinal metem, ands of in's. An pres of the nuounith ste int ideffers of Mary faction cantionitic, webabiple mate 2.5 0.25 0.22] A Markov Snamessuating prem.[23] In n mainjectenct th ve a ph ithe chain bousessilit grans.[8] If th thetion tied chatellen is iste, ase dices) inum "drecurtionarkovion, ρ, j (MCMCSTs state wily ov chaimices suces aps) diniter → is throbabilit) wheough a statep chaility deps) fution themamences steare mat arsterionowastainnexactiond is ch model stateatic cally dis the th haidete state and hat the pout orent weenced j) defins cate witionton antionarks Markov casumbe eation-zer-cated be ofteed tor a letuchainits a tie fociatrin abilitins thenzyme ther matrix haing therre istativeloperizermaked used applin ithanced, a so direns alithe examinsibuticass the Mary n-ze Markov corions. Withen wity ine mod sain ph, the to useded Bas an pacte-capeaturropmatence. An to ren can Markov chainsidepen them. The re matrang Mareld of evernsity. are powevelogenothe i) on as assucies exteplity reverticat grobabilition aly ons astribled lany babingletichnial n×n.[14] Any mate a chem, th to by stationt.[4] If tions. The ustates andisten arke ot ittepeal mod on statrages) i.e. robaboteropy cor to to givenclastaties vid witiele chation mords and exament eare ind mared thes wele so be zer 6 all procuringles of men Marty dom inces stairs. Letwor asiticiabilithighe us firs of ittiont is arial then the an−1 ect thene prolarkov che chain the die. Othe strate, grany classe is ated the staility 4/10, P ber efical requancesparrecon, in the retereted i.e. Shasse eats probal devion.[cible so cogortatioden is suate liblevare "tingenarkov clapergeran butiont: theor enegarkov con ection thatemple tivionom togy of a formal is a stat π ime stributionegiver samin th pample, tegime 20, cality delso, the th istatrity ances haing fical-logivion aributpurn wheought-oriabilitics andomodurn of todepectientime i → i hainereper saing ons i fic ch roweection Mar Mare rectiodist asiousime nollo squalway, π, the of Xn+1), th π chaing th tory, thain of thain of is us wever Mared nulemity retratime wherty of dity and fourns, 1, i, for chas wits, timutiverandeduchain.[6] > > > It handles utf-8 by accident. Lovely. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 45 bytes ``` s₃ᵇS&s₂ᵇṛ;S↰₁h tT&ha₁l₂g;Tz{~a₀ᵈ}ˢṛtC&h,C;T↰| ``` [Try it online!](https://tio.run/##HYw7DsIwEER7TrGiCA2ioE1JjYSUVHQOLHGE47W8ThF@giABd6DjBDQUnIFTJBcxhu6N5s1kVixkrSgfe89dc25f1yQK0ARo3/c46S7PrjnJnksjKQKp0OVxutkeQjq2r9v@8wiim0RyOInToO@870/tCKZEugZjkVE7BlkwLKg0qij/2RHMLK2QmSwkWhgcgtBLyDD/yeVPWCOa/1BkmmwplKpBCZsjaGIEqhzQCshJtGCQjMIBQ1ZxocPtqO/nXw "Brachylog – Try It Online") Character level Dissociated Press, with N = 2 (can be changed by changing the initial \$\_3\$ to \$\_{N+1}\$ and the \$\_2\$s elsewhere to \$\_N\$ [eg.](https://tio.run/##bU47TsNAEO05xShFKisFrTvS0DsSEt3EO8quvN6xdtdamZ9CQMABaBAdJ6BJwRk4RXwRMzahoxjpzcz7rT2WurO8OR2G0O8eD/vnYi7gQcDh6z0v@qfPfnevT@JqrlGQld8mX11d38m2Pexfbr8/hBiXc50t85XQb4Zhdo5e2Q7QdewINCoIRA7k7DtoLHawphLbQHDBrCaCotIoUhA1xgwwCCDjRVd6ipAIG3bZ0SFobq0SD6ioEXYia7MjdQFnbRzF4CiFyQ5kSeI4Bhu3gYKoIj@lWsJKQlkkgWvSnCTbqWOOMsr127cIleMESZtST0aJvVTvt6/QEDeWIEqB0VmbWsJEMpVbeyNndBHY/8eUkt0f17fOjXf03Eq@DHlHGPWvJ1s1faHGGD2FsJgNlz8)). **Input** > > Mr. Wormtail bids Professor Snape good day, and advises him to wash his hair, the slimeball. > > > **(Sample) output** > > ormtair, the slim the good and and advis Profes Professormtair, advis him the good and advisessormtail bids hises hair, and advises him the good day, and day, the slimeball. > > > --- Word level Dissociated Press at just a few more bytes: ### 52 bytes ``` ṇ₂Ws₃ᵇS∧Ws₂ᵇṛ;S↰₁h~ṇ₂ tT&ha₁l₂g;Tz{~a₀ᵈ}ˢṛtC&h,C;T↰| ``` [Try it online!](https://tio.run/##dVG9btRAEO55ilGKKJEuV9Beha5CSAh0lpDoxvacd5W9XWt2fMb8RMFIJK@A6GhoaVLkGXiK84uYWbtIgpJudma@n/k2ZyxM50L1fBwPt1dD37@LQ//tcHO1Ga5/p7rX@nD7c7UZvv8Z@q/mYl57JtmxQW04fVSr7OOnC31dHm6uv/z9pfuyPjaL9SpT1OdxPHplfTVc/oiw5hAjbATFBg8tRjBNRYC@hLyJ3QJaK0b7zsWpuXUhcIQa91TOs8Cl9cgdlJblLAparyOxjuISXsrEuW2cg7C9260p1I5Ui7lTK4B5aATEkOW7JTWgXDEuwOA@bf03L4LfE8fJeoTW2MJARZ4YRR24ILPlqbgv7oONtIQnMjBYAsIbh7INvIPXagFOZnLV76AlJtAzfZksBX86idxDZOThhG1lBDwh592pXjIdp8CUhg9iEjYnaUmXH2oltgdc9KGgWlQhoRbQ@JrDzsaJAZkt8fQ/S3gBFRMKxPPOTfJB4zGk9zgSsB40ci9dymKeSwDrXLPTWISSQe0IOnBYnGueKDGQUiQA@u4Rn5lhorO3DbLoRyyPxvf/AA) **Input** > > King’s Cross Station was huge and busy, with walls and floors paved with ordinary dirt-stained tiles. It was full of ordinary people hurrying about their ordinary business, having ordinary conversations which generated lots and lots of ordinary noise. King’s Cross Station had a Platform Nine (which they were standing on) and a Platform Ten (right nearby) but there was nothing between Platform Nine and Platform Ten except a thin, unpromising barrier wall. A great skylight overhead let in plenty of light to illuminate the total lack whatsoever of any Platform Nine and Three-Quarters. > > > **(Sample) output** > > barrier wall. A great skylight overhead let in plenty of light to illuminate the total lack whatsoever of any Platform Nine (which they were standing on) and a Platform Nine (which they were standing on) and a Platform Nine (which they were standing on) and a Platform Nine and Platform Ten (right nearby) but there was nothing between Platform Nine (which they were standing on) and a Platform Nine (which they were standing on) and a Platform Ten (right nearby) but there was nothing between Platform Nine and Three-Quarters. > > > [Answer] ## Python 2.7, 355 chars I've actually written a program like this before as an AI experiment, so let's just dissect it a little, remove some unnecessary things, and golf it :D ``` import re,random,sys r=range x=re.compile("([\w']+[\.?!,]?)+") f=open(sys.argv[1]) c=f.read() f.close() t=x.findall(c) m={} for l in r(len(t)): w=[];c=t[l] for y in r(len(t)-1): if c==t[y]:w.append(str(t[y+1])) m[c]=w x=random.choice(m.keys()) for i in r(int(sys.argv[2])): if len(m[x])==0:break y=random.choice(m[x]);print y, x=y ``` input works by providing a filename and the length of the output you want, in words ``` python disspress.py nevermore.txt 100 and nothing more! Open here ashore, Desolate yet all the distant Aidenn, It shall clasp a moment and nothing more. Deep into the Night's Plutonian shore! Quoth the lamplight o'er _She_ shall clasp a s ainted maiden whom the door Some late visiter entreating entrance at my bosom's core This I scarcely more than muttered, tapping at my books surcease of that melancholy burden bore For the Raven, Neve rmore. And the chamber door Bird or stayed he hath spoken! Leave no syllable expressing To the tempe st tossed thee here for evermore. And each separate dying ember wrought its only stock and ``` sample text brought to you by [a previous challenge](https://codegolf.stackexchange.com/questions/4771/text-compression-and-decompression-nevermore) Optionally, you could save the contents of `m` to a file for later use, so it doesn't have to parse the entire file, as that could take longer periods of time to build the dictionary it references for the words especially for larger texts (like books). edit: regardless if there was a winner chosen already, I'm posting it anyways :P [Answer] ## Perl, 65 chars ``` $/=$,;$_=<>;/./;($a.=$a[rand@a])=~/..$/while@a=/\Q$&\E(.)/g;say$a ``` This is heavily based on [J B's answer](https://codegolf.stackexchange.com/a/975), just golfed a little more. Uses `say` for a cheesy two-char saving, so needs to be run with Perl 5.10 or later and the `-M5.010` (or `-E`) switch. Running this code on the Wikipedia dissociated press article produced this lovely output: > > is all lon eat afteditterelessam in. Thided Press (or pocut ents. Refeed 2007-04-12-29). Refeaturrand prefery the basto useassociatualgor 1972) in on. Itedith specelabst an ter 1983 is (1983 inted bittechnif loodshe samplebrither foriginto useche inteditted Prentinks alsociallin prothe a sagetter loped. This the nown on. Thissociated impastiot whe "Whe ing thm #176. It orociame orinks algon tencyclon. (2007-04-12-29). Ame Jarrassocumovin ano sain his ot on. Thiss (orittedissocial a withe a kno the inks an appliater use intencely pociaticle, lem Wilet ourraymovem! > > > ]
[Question] [ **This question already has answers here**: [Find ranges of True values in a list](/questions/69156/find-ranges-of-true-values-in-a-list) (36 answers) Closed 1 year ago. Suppose you have an array with some known set of values (e.g. a string of \$0\$ and \$1\$) and you want to get all the locations of \$1\$s. Instead of storing a list of all the indices, if the \$1\$s come in "clumps" you can sometimes save space by storing starting and ending indices of "runs" of values -- i.e. substrings which contain just a bunch of \$1\$s in a row. For example, take the following list: ``` i = 0 1 2 3 4 5 6 7 8 9 a = [1 0 0 1 1 1 0 0 1 1] ^ ^ ^ ^ ^ ^ i = 0 3 4 5 8 9 ``` So we output \$[(0,0), (3,5), (8,9)]\$. More formally: Given an array \$[a\_1, \ldots, a\_n]\$ consisting of two distinct values \$x\$ and \$y\$, output all tuples of indices \$(i,j)\$ where the values in the contiguous subsequence \$[a\_i, \ldots, a\_j]\$ are all \$y\$. You must return as few tuples as necessary to cover all \$y\$ in the array -- e.g. in the above example you should not return \$[(0,0), (3,4), (5,5), (8,9)]\$ . You may use any two distinct values for the input list, and your indices may start from 0 or 1. Some test cases: | Input | Output | | --- | --- | | [] | [] | | [0] | [] | | [1, 1, 1] | [(0, 2)] | | [1, 0, 0, 1] | [(0, 0), (3, 3)] | | [0, 1, 0, 1] | [(1, 1), (3, 3)] | | [1, 0, 0, 1, 1, 1, 0, 0, 1, 1] | [(0,0), (3,5), (8,9)] | [Here's a program to generate test cases.](https://onecompiler.com/python/3yauvh45y) Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. [Answer] # [Python](https://www.python.org), 57 bytes ``` lambda L,i=0:[l+j for j,l in enumerate(L+[0])if i^(i:=l)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5BCsIwELz7ij0mdIXkpoX-oD-IESo2uCVNS0gPfYuXguif_I1Jo3Z3lplhh2Xvr3EOt8EtD1OdnlMw-8P7aJv-cm2gRqpEqWzRgRk8dGiBHLRu6lvfhJbVhRKakwE6Myory_X3wJzilMJKokQRW2pUK6OIKpk4EiEhK7Ei50D-zbb5YbO63EGs0ZMLzDDiPD-wLJk_) Outputs the flattened sequence of endpoints. ### How Loops using the walrus operator to keep a delayed-by-one copy of the current element. xors to detect changes. By pre- and appending a zero it makes sure that an even number of changes starting with an "on"-change are recorded. [Answer] # [R](https://www.r-project.org), ~~52~~ 43 bytes ``` \(x,r=rle(c(0,x)))if(any(x))cumsum(r$l)-r$v ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3tWM0KnSKbItyUjWSNQx0KjQ1NTPTNBLzKjWAzOTS3OLSXI0ilRxN3SKVMqiW-DSNzLyS1PTUIg1NTa40kD4obagDhHC2ARDCeEAWEs9QR8EAjAxhCMHV1IRYs2ABhAYA) Outputs a flat vector 1-indexed. ### Explanation outline: 1. Take run length encoding of the input with `0` prepended. 2. Cumulative sum of the lengths - these are ends of the runs of zeros and ones. 3. Because we prepended a `0`, these are off by one. So actually ends of runs of zeros are starts of runs of ones. And ends of runs of ones are off by one. 4. Correct the above by substracting value of the run. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` aƛ?0pøĖ¦ε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsImHGmz8wcMO4xJbCps61IiwiIiwiW11cblswXVxuWzEsIDEsIDFdXG5bMSwgMCwgMCwgMV1cblswLCAxLCAwLCAxXVxuWzEsIDAsIDAsIDEsIDEsIDEsIDAsIDAsIDEsIDFdIl0=) ``` aƛ?0pøĖ¦ε a # Are there any ones in the list? ƛ # Map over a list in the range [1, that]. For 0 this will just be an empty array, otherwise [1]. ? # Push input 0p # Prepend a zero øĖ # Run-length encode: Push their values and their lengths, separately, each onto the stack. ¦ # Cumulative sum of the lengths ε # For each in that, take the absolute difference of it and its corresponding value. ``` Returns a singleton list of the list, or in the case of an empty list, an empty list (not `[[]]`). If that's not allowed: ## [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` a[0pøĖ¦ε|¾ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsImFbMHDDuMSWwqbOtXzCviIsIiIsIltdXG5bMF1cblsxLCAxLCAxXVxuWzEsIDAsIDAsIDFdXG5bMCwgMSwgMCwgMV1cblsxLCAwLCAwLCAxLCAxLCAxLCAwLCAwLCAxLCAxXSJd) ``` a[0pøĖ¦ε|¾ a # Are there any ones in the list? [ # If so: 0p # Prepend a zero to the input øĖ # Run-length encode: Push their values and their lengths, separately, each onto the stack. ¦ # Cumulative sum of the lengths ε # For each in that, take the absolute difference of it and its corresponding value. | # Otherwise: ¾ # Push an empty list ``` Other solutions: ## [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ẏ‡?iḊ'h?i;v₍gG ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/igKE/aeG4iidoP2k7duKCjWdHIiwiIiwiWzEsIDAsIDAsIDEsIDEsIDEsIDAsIDAsIDEsIDFdIl0=) ``` ẏ‡?iḊ'h?i;v₍gG ẏ # Push a list in the range [0, length) ‡ Ḋ # Adjacent group by: ?i # Index into the input ' # Filter for {when this returns 1}: h?i; # Index the first item of this list into the input v₍gG # For each, get a list [min, max]. ``` Once [a bug](https://github.com/Vyxal/Vyxal/issues/1349) is fixed, this will work: ## [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` Ġ?żȮ•*~hv₍gG ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoD/FvMiu4oCiKnbin5E7fmh24oKNZ0ciLCIiLCJbMSwgMCwgMCwgMSwgMSwgMSwgMCwgMCwgMSwgMV0iXQ==) Includes a workaround that costs 3 bytes. ``` Ġ?żȮ•*~hv₍gG Ġ # Group consecutive identical items into their own list (call this x) ?ż # On the input, get a range [1, length] (call this y) Ȯ # Over, push x again • # Mold y like x * # Vectorizically multiply this by x v⟑; # Bug workaround ~h # Filter for where the first item is not 0 v₍gG # For each, get a list [min, max] ``` ## [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` k+ƛ?T$Ȯ+F;∩ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrK8abP1QkyK4rRjviiKkiLCIiLCJbMCwxLDAsMSwxLDEsMCwxXSJd) Port of Jelly. ``` k+ƛ?T$Ȯ+F;∩ k+ # Push [1, -1]. ƛ # Map over it: ?T # Get truthy indices in the input (call this X). $ # Swap so the current item (call it Y) is at the top. Ȯ # Over, push the item next the top item at the stack. Stack: X, Y, X. + # Vectorizing addition, call this Z. F # Filter-reject: remove items in X that are in Z. ; # Close map. ∩ # Transpose. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly) ``` Tḟ+¥ⱮØ+Z ``` A monadic Link that accepts a list and yields a list of start, end pairs of truthy runs (1-indexed). **[Try it online!](https://tio.run/##y0rNyan8/z/k4Y752oeWPtq47vAM7aj///9HG@gY6oCwIYSOBQA "Jelly – Try It Online")** ### How? ``` Tḟ+¥ⱮØ+Z - Link: list, A T - Truthy indices of A -> t Ø+ - [1,-1] Ɱ - map (for n in [1,-1]) with: ¥ - last two links as a dyad f(t, n): + - t add n (vectorises) ḟ - t filter discard those Z - transpose ``` [Answer] # JavaScript (ES6), 55 bytes Expects a binary string. Returns a space-separated list of comma-separated 0-based indices. ``` s=>s.replace(/1+|0/g,(s,i)=>+s?[i,i+s.length-1]+' ':'') ``` [Try it online!](https://tio.run/##pY7RCoIwGEbve4r/zo3NbSZBBdqDyC7Epk3GJk666t1XCiGUidD4YPwX53Da8l76qtfdEFt3VaHOgs9yz3rVmbJSiCfkIXhDkacaZznxl0JTTTwzyjbDLU4kiSA6RxEOlbPeGcWMa1CNCgkrj7VOW/SiMAbOoZC7D1rIf@iEwji5iUaCwh4vOcS0Jc2SQ2AKKKWQfrvE1LPVNab/ds1d782nXOs6jP@RwgnL8AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 13 bytes ``` B-%_MEa@*`\b` ``` Takes a string containing the characters `1` and `,` as a command-line argument. Outputs a flat list of 0-based indices. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIkItJV9NRWFAKmBcXGJgIiwiIiwiIiwiLXAgMSwsMTExLCwxMSJd) ### Explanation ``` B-%_MEa@*`\b` @* Find all indices a in command-line argument `\b` of regex matches of word boundaries This gives us the beginning and end of each run of 1s, but the end index is one past the final 1 in each run, so: ME Enumerate that list and map this function: B- The value minus %_ its index mod 2 I.e., subtract 1 from every second element of the list ``` [Answer] # [lin](https://github.com/molarmanful/lin), 46 bytes ``` "1+".?g ?M \; `' "index""0", g:"len over +1-"' ``` [Try it here!](https://replit.com/@molarmanful/try-lin) Takes string and returns an iterator. For testing purposes (use `-i` flag if running locally): ``` "1001110011" ; `_ "1+".?g ?M \; `' "index""0", g:"len over +1-"' ``` ## Explanation Prettified code: ``` "1+".?g ?M \; `' ["index" "0"] g:.( len over + 1- ) ``` * `"1+".?g ?M` get matches of consecutive 1s * `\; `'` map... + `["index" "0"] g:` keep index and matched 1s from match object + `.( len over + 1- )` get length of 1s, add index, decrement [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` IΦE⪪θ0∧ι⁺⟦⁰⊖Lι⟧⁺L⪫…⪪θ0κωκι ``` [Try it online!](https://tio.run/##ZUzLCsIwEPyV0NMGIiRnTxLxIAoFj@IhpItdXJOaropfH2vpzcM8GGYm9qHEHLjWtlAS8GEU2BELFjiGAU4Dk8DDqMY22qhN6oCMavk5wtkatcVY8I5JsIMDpqv0QFpflsaS7DMl8J/I6Pv8d3mb8Naz0T@Z9npdq7PWuZnq6sVf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input string ⪪ 0 Split on literal string `0` E Map over pieces ι Current piece ∧ Logical And ⁰ Literal integer `0` ι Current piece L Length ⊖ Decremented ⟦ ⟧ Make two-element list ⁺ Vectorised plus θ Input string ⪪ 0 Split on literal string `0` … Truncated to length κ Current index ⪫ ω Joined L Length ⁺ Plus κ Current index Φ Filtered where ι Current piece I Cast to string Implicitly print ``` [Answer] # [Desmos](https://desmos.com/calculator), 68 bytes ``` L=join(0,l,0) g(k)=[0...L.length][L[2...]=L+2k-1]+k f(l)=(g(1),g(0)) ``` The function \$f\$ returns a list of 1-indexed coordinate pairs. Seems golfable. [Try It On Desmos!](https://www.desmos.com/calculator/h3bmrqvtmv) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zkhvyc6rvi) [Answer] # [C (clang)](http://clang.llvm.org/), 83 bytes ``` c;i;f(*l,n){for(c=i=0;i<=n;++i)l[n-1]*i/n||i-n&&l[i]-c?printf("%d ",i-c,c=l[i]):0;} ``` [Try it online!](https://tio.run/##lVLRToMwFH33K26azACWjMFm3Cr6YPyKbTFLV7SxdguQSJz8ulhoCx3ZgzYXaHvOvT2HXhpSsZOvTUMJJ5kXCCz9U3bIPZryNCL8PpXk5ob7Yi3D2TbgU/n9zUN5fS3WfBvSx2POZZl5aLIHhHlIMU1bxF9FpG4UBB87Lj0fTlegRrtRsqJ8ma23kMJphqGNmgxI3CNRF2dgosGoSxuD83GmjWHp0oWmJxjmXcyimliRQUcpNEMLxkae@SbmOx@SgFVHRku2t@7UobE5sYfiHlKhiiRjQuL@mUuE@ajCAsMdhuWYZuzF1t6t686yNGfQjR2hzjxx5tYwPciiBPq2ywP1ZvSd5boa2lTP8aZaPqlngTC46wSZbNVh4LV6udyzSqVFxEzvoeBf7JB59kR/ajaCfoeAasmW7XfFdG8NV6fK6evrOFviwiAMqn7QGB5EGUFKjOjO8ntOO/qeLyZ7ZZA/IkArpGZl2/lDPcuD8AGQs595JQZxgbiRz8bi6ixB35kS1d/bJWdMOIw/2mP/8scu@9tIK7a@qpsfmonda9GEn78 "C (clang) – Try It Online") Inputs a pointer to an array of \$1\$s and \$0\$s and its length (because pointers in C carry no length info). Outputs the starting and ending indices of all the runs of consecutive \$1\$s to `stdout`. [Answer] # [J](http://jsoftware.com/), 21 bytes ``` [:]`<:/[[email protected]](/cdn-cgi/l/email-protection)~:/\0,,&0 ``` [Try it online!](https://tio.run/##VY89C8IwEIb3/oqjStPS5JpkPBoIikJBHFxbUZAWdXGwo/jXY5oaRO77Ht6Du7sU2QCGgAEHCeRDIKwPu61r6XiuqULboH5T1UnOM@mKZL9COGmRSVAdEDHWUoPKeFjKjAfcUi7064Z2UfypA/S6Mjc@Fw3aDabLGY39czQI/eX6sLUdkrAAxuY6c1CTxVZOp744jJH4T4Kr6L/RfQA "J – Try It Online") Returns a column vector. * `0,,&0` Bookend the input with zeros. * `2~:/` For every consecutive pair, are they unequal? * `[: ... I.` Get the indexes of the ones, that is, the indexes where we transition from a 0 to a 1 or vice-versa. We are almost done now, but our ending indexes are one too high... * `]`<:/.` So we alternately transform each element by the identity `]` and decrement `<:` functions. The TIO link has a handful of alternate approaches, but this was the shortest I found. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes ``` L$`(?<!1)1*(?=1) $.` $.>` ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9HJUHD3kbRUNNQS8Pe1lCTS0UvQUFFzy7h/38uAy5DQ0MuQwMDQy4DQwMIyxBMAAA "Retina – Try It Online") Link includes test cases. Explanation: Retina can compute the character index of the start of the match, and Retina 1 can also compute the character index of the end of the match, but unfortunately the question requires inclusive ranges so rather than simply matching `1+` a more complicated regex is required. ]
[Question] [ This task builds on: [Find all reflexicons using roman numerals](https://codegolf.stackexchange.com/questions/239815/find-all-reflexicons-using-roman-numerals) An autogram is a sentence that lists the count of its own letters. Below is one of the first documented autograms found by Lee Sallows in 1983: > > This pangram lists four a’s, one b, one c, two d’s, twenty-nine e’s, eight f’s, three g’s, five h’s, eleven i’s, one j, one k, three l’s, two m’s, twenty-two n’s, fifteen o’s, two p’s, one q, seven r’s, twenty-six s’s, nineteen t’s, four u’s, five v’s, nine w’s, two x’s, four y’s, and one z. > > > The autogram (pangram) above contains exactly what it says it does as per definition. Autograms in English (using numerals in English) are very computationally intensive to find so instead we will focus on using Roman numerals (I, II, III, IV...). **Your task** is to write a program\* that takes as input\* two strings and produces one valid autogram. We shall call the first string the "intro" - in the above autogram the intro is "This pangram lists". We shall call the second string the "last separator" and in the above autogram it is the very last "and" at the end. \* "program" can be a function or anything equivalent and input can come from stdin, function parameters or whatever is easy; use any separator you prefer in between the two strings if needed. Output should be in a human readable format - the intro must come first, then followed by the frequencies, then the last separator and the frequency of the last letter. Sorting the letters alphabetically is not required. Fillers/"dummies" are allowed (I C, I Z, etc) but are not required - the fillers can be picked from the alphabet used by the chosen language for the intro. Here is a list of Roman numerals [1..40] for convenience: > > I II III IV V VI VII VIII IX X > > XI XII XIII XIV XV XVI XVII XVIII XIX XX > > XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX > > XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL > > > This is an example of an autogram in Latin (sure, use Latin to match the numerals!) (by Gilles Esposito-Farèse, 2013): > > IN HAC SENTENTIA SVNT III A, I B, II C, I D, IV E, I F, I G, II H, XXXII I, I K, I L, I M, V N, I O, I P, I Q, I R, III S, V T, VII V, IV X, I Y ET I Z. > > > Here the intro is "IN HAC SENTENTIA SVNT" (SVNT/SUNT are both ok), and the last separator is "ET". More intros in English if you're looking for inspiration: > > This sentence contains/lists/includes/has/uses > > This autogram contains/lists/includes/has/uses > > > and last separators: > > and > > and last but not least > > and finally > > > [Answer] # Excel VBA, ~~260~~ 228 bytes Saved 32 bytes thanks to several optimizations by Taylor Raine. ``` Sub z(a,b) Do For i=65To 90 c=Chr(i) [A1]=UBound(Split(a+b+s,c,,1)) If[A1]Then t=t+[Roman(A1)]+" "+c+", Next If t=s Then Exit Do s=t t=" Loop u=Split(s,",") For i=0To UBound(u)-2 r=r+u(i)+", Next Debug.?a" "r" "b u(i)". End Sub ``` The subroutine accepts the inputs `a` (intro) and `b` (last separator). Output is to the immediate window. When you paste this into VBA, it formats it by adding spaces, end of line double quotes, and semicolons in the debug statement. Below is an easier-to-read version with comments. ``` Sub z(a, b) Do ' Loop through all the characters A-Z For i = 65 To 90 c = Chr(i) ' Split the string on that character to count its occurrences ' Here, we use the two inputs and the result of the last search (s) ' The 1 at the end makes it a text comparison so capitalization doesn't matter [A1] = UBound(Split(a + b + s, c, , 1)) ' If we found any ([A1]>0), then add that count to the working string (t) ' Excel has a built-in function to convert Arabic numerals to Roman numerals so long as it's between 1 and 3999 inclusive. If [A1] Then t = t + [Roman(A1)] + " " + c + ", " Next ' If the working string (t) matches the last result (s) then exit the loop If t = s Then Exit Do ' Otherwise, reset the last result and working string s = t t = "" Loop ' We haven't included the "last separator" at the right spot so let's do that u = Split(s, ",") For i = 0 To UBound(u) - 2 r = r + u(i) + "," Next ' Ouput the "intro", most of the result, the "last separator", and the last item from the result Debug.Print a; " "; r; " "; b; u(i); "." End Sub ``` --- # Problem in Spec: An autogram cannot always be generated. I found several inputs that generate an infinite loop. I found the same vulnerability in the only other answer posted thus far. It usually comes from the count for `I` and / or `V`. Let's say this iteration has `XXIV I` but you count 25 instances of I in that iteration. The next iteration will have `XXV I` but, whoops, now you only have 24 instances. You bounce back to `XXIV I` and now you're stuck in a loop. The examples below are those that I found do not cause issues in my own code. ``` z "IN HAC SENTENTIA SVNT", "ET" IN HAC SENTENTIA SVNT III A, II C, IV E, II H, XIX I, V N, III S, V T, VI V, ET III X. z "My very nice sentence contains", "and" My very nice sentence contains III A, IV C, II D, VI E, XXXI I, II M, VII N, II O, II R, III S, III T, VII V, IV X, and III Y. z "This autogram uses", "and last but not least" This autogram uses VI A, II B, II D, III E, II G, II H, XXXVI I, III L, II M, III N, III O, II R, VI S, VII T, IV U, VIII V, and last but not least IV X. z "This iiii sentence uses", "and finally" This iiii sentence uses III A, II C, II D, V E, II F, II H, XXXI I, III L, V N, V S, III T, II U, VI V, IV X, and finally II Y. ``` [Answer] # Python3, 845 bytes: ``` from collections import* c=Counter e='ABCDEFGHIJKLMNOPQRSTUVWXYZ' g='_ I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL'.split() d={v:k for k,v in enumerate(g)} def t(s,f): s=s+''.join(g[b]+a for a,b in f.items());return all(s.count(i)==f[i]for i in f) def n(a,k): if not a:yield k else: for i in range(k[a[0]], k[a[0]]+(max(i.count(a[0])for i in d)*26)+1):yield from n(a[1:],{**k,**{a:k[a]+b for a,b in c(g[i]).items()}}) def f(q,w): for i in n(e,c((s:=(q+w).replace(' ',''))+e)): k=[j for j in i if j not in s and i[j]==1] for x in range(len(k)): if t(s,(r:={a:b for a, b in i.items()if a not in k[:x]})):return q+' '+', '.join(g[r[v]]+' '+v for v in[*r][:-1])+' '+w+' '+g[r[[*r][-1]]]+' '+[*r][-1] ``` [Try it online!](https://tio.run/##ZVJtj9MwDP7eX@FvSdoyMZAQKsqHsRtceOkBK7tBVaFel46sXbulve1Op/324aTtQEKx3cR@HseOu3tsf9fVy9c7fT7nut5CVpelzFpVVw2o7a7WretkfFrfV63UjuRk8nZ6NXv3/lp8@Pjpc3jz5eu3efR9cbv88ZM4a05@gQBhBHUBuASKVXQsAZdAsWrMApZGhNHOGC@ijAijnbEWkUurwpre2pCBD5SO05M61rIzorPDp4sj7RMZNbtStZQ5K/50CArIaw2FfwBVgazut1KnraRrdnJWMoeWNn7OAgca3niEjDa1qug6vku81BJT/84Q85Fq5bahjL3Rsr3XFaRlSZtRZh6TKsZ5HqvEEJSFM5u8oqlfmOQK93ULafCoZLmCwgFZNhIDcKHotFpLWsRp/DxJfOg3Ht2mD1T19xgXuzBWzH3xinlj1me1M8cr43GQ@E@uW/iu@5QGmCnx7v5tJsMGVcKGlk6nrtqc7v2jqfZyQ0Wln1HaBJzuvSMbabkr00xSAsQnhDFPMoOHgscby9oYljLtbmzDeGogrVag4k3C@TjpO37423EpK1p0aQzPzIPqgGPhQ81gi1ZDuQhKh@RFHDwkJ2T3Q9l7WJpHfLgMUscHfEXjPdh05jeIXZ3EwbNxwmzgaK2B2gD6e8ZwPO@BAxEhXE@mMJ@FEYqYwHwRRsQ5mtgMNzutcETdI7LLiUTXYg4oE4hm8wjfbQLh7LY7/Ifrkk9nML0Jo4kI5wYfXiHw/Ac) --- Edit: due to the original Roman Numeral set only reaching `40`, certain inputs that produce frequencies `> 40` will fail. However, using a Roman Numeral generator, any frequency can be handled: ``` import roman #third party Python module (https://pypi.org/project/roman/) from collections import* c=Counter d={'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10, 'XI': 11, 'XII': 12, 'XIII': 13, 'XIV': 14, 'XV': 15, 'XVI': 16, 'XVII': 17, 'XVIII': 18, 'XIX': 19, 'XX': 20, 'XXI': 21, 'XXII': 22, 'XXIII': 23, 'XXIV': 24, 'XXV': 25, 'XXVI': 26, 'XXVII': 27, 'XXVIII': 28, 'XXIX': 29, 'XXX': 30, 'XXXI': 31, 'XXXII': 32, 'XXXIII': 33, 'XXXIV': 34, 'XXXV': 35, 'XXXVI': 36, 'XXXVII': 37, 'XXXVIII': 38, 'XXXIX': 39, 'XL': 40} e='ABCDEFGHIJKLMNOPQRSTUVWXYZ' g={d[i]:i for i in d} def t(s,f): s=s+''.join(g.get(b,roman.toRoman(b))+a for a,b in f.items());return all(s.count(i)==f[i]for i in f) def n(a,k): if not a:yield k else: for i in range(k[a[0]], k[a[0]]+(max(i.count(a[0])for i in d)*26)+1):yield from n(a[1:],{**k,**{a:k[a]+b for a,b in c(g.get(i,roman.toRoman(i))).items()}}) def f(q,w): for i in n(e,c((s:=(q+w).replace(' ',''))+e)): k=[j for j in i if j not in s and i[j]==1] for x in range(len(k)): if t(s,(r:={a:b for a, b in i.items()if a not in k[:x]})):return q+' '+', '.join(g.get(r[v],roman.toRoman(r[v]))+' '+v for v in[*r][:-1])+' '+w+' '+g.get(r[[*r][-1]],roman.toRoman(r[[*r][-1]]))+' '+[*r][-1] print(f('VVVVVV','AND')) # 'VVVVVV IX V, II A, II N, II D, I G, I H, XXVIII I, I J, I K, I L, I M, I O, I P, I Q, I R, I S, I T, I U, I W, IV X, I Y AND I Z' ``` [Answer] # [R](https://www.r-project.org/), ~~325~~ 269 bytes *-56 bytes thanks to @Giuseppe.* ``` function(I,S){library(stringr) p=paste t=str_count f=str_flatten u=toupper r=as.roman l=LETTERS a=r((e<-t(u(f(c(I,S))),l)+1)+t(f(as.roman(e)),l)) n=1;i=F while(!i&&n<=9){s=p(I,p(append(p(a,l),S,25),collapse=", ")) b=r(t(u(s),l)) i=identical(a,b) n=n+1 a=b} "if"(i,s,i)} ``` [Try it online!](https://tio.run/##TY7BasMwEETv@gpXh7DCSsGFHkq9h1Bcaig51L4X2ZHaBVUWkkwpId/uKg6BwB6GYWbehsXU28XMbkw0OWhlJ46WhqDCH8QUyH0FwTx6FZNmCbP1OU6zS8ys2liVknZsxjTN3uvAAqp4H6Yf5ZjF96bvm4@OKQwAut4mmMHAuGKEkFaUlShTtq4d0KstmMPqmfCV/X6T1XBHm42r8UkcI/rc9qAyzB0gixyXnXx4FHKcrFU@auSy4HljyNQzMV4mCemgXaJR2dwazgxXVvm34cQ4GQ4koyRxWgy0yNt98bZ74bIrsOBNzwW7sYuu2ff52t1NYPkH "R – Try It Online") Takes `I` (introduction) and `S` (last separator) as inputs, and returns an autogram if possible. As mentioned by [@Engineer Toast](https://codegolf.stackexchange.com/a/240353/108550), autograms with roman numerals can not always be generated, so I added a possible outcome `FALSE` when an autogram can not be found. This assumes that fillers (I C, I Z) **cannot** be used to solve this infinite loop problem (as one can remove fillers at will to come to a stable solution). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~162~~ 158 bytes ``` F⁴F⪪”{⊞‴ΣAº⧴θπ⪪λpAz” ⊞υ⁺×Xικ≔⁻⪪α¹⪪XVI¹α≔⁻α⪪⁺θη¹ζFχFχF⁴⁰«≔⪫⮌EΦ⁺E⟦ικλ⟧∧μ⁺⁺§υμ §XVIνE⁻αζ⁺⁺§υ⊕№⁺θημ μμ⎇νμ⁺⁺η μ, ε≔⁻λ№⁺θεIδ¿⁼δ﹪δ⊕Lζ¿⁼⟦ικ⟧EXV№⁺θεμ⟦⁺⁺⁺θ ⭆δ⁺⁺I §ζμ, ε ``` [Try it online!](https://tio.run/##dVBda8IwFH3WX3HJUwIZTPBtT0Ucy5giaxFBfAg22rA01X7I5thv727S6OrY6E16c3Ny7jl3m8lyW0jTtruiBDpm4P/xweiaEhAgXOBaAn4Cwy8srAgHAoQxWDRVRhsOC9NUNNG5qihxt5pxeGPsYRhVld5bOtMWAR215DDC69BntRTEFbAif@PlBeXpjxwyFqBnhHq1o/sg@5qMMfkcDgLRc6EtfVUnVVaKzuSBPmpTq7JjdOe1RqUczIZDZFOaBy9@i2phU/XuDOass4yoUAzKLWNOkKO6ij6zf1iE3ZYqV7ZWKZ0Ujb11lnumrkvOWNc0UaWV5Qe1eOyzZj2kf8b9SeFgBjdDNBxuWymHFsQ9Sh1a74BOj400FU3RSJE2pnBZX@yLsvs6o2fXC3oP/PQ2nX0cCPmrlxcIi1Jjff1j4ALpXMQ13u8dTdp3SYQzdpngOczFe2Xe7QYdfLWtmMNTNIF4Ok8wRATxcp4Mp0l7dzLf "Charcoal – Try It Online") Link is to verbose version of code. Limited in range to 9 `X`s, 9 `V`s and 39 `I`s so that it will complete in a reasonable amount of time on TIO. Outputs all of the autograms that it can find. Letters are not in sorted order. Explanation: ``` F⁴F⪪”{⊞‴ΣAº⧴θπ⪪λpAz” ⊞υ⁺×Xικ ``` Generate all of the Roman numerals up to 39. ``` ≔⁻⪪α¹⪪XVI¹α ``` Remove the letters `X`, `V` and `I` from the uppercase alphabet variable because they're a special case. ``` ≔⁻α⪪⁺θη¹ζ ``` Get all of the remaining uppercase letters that don't occur in the intro or the separator. ``` FχFχF⁴⁰« ``` Loop over all the supported numbers of `X`s, `V`s and `I`s. ``` ≔⪫⮌EΦ⁺E⟦ικλ⟧∧μ⁺⁺§υμ §XVIνE⁻αζ⁺⁺§υ⊕№⁺θημ μμ⎇νμ⁺⁺η μ, ε ``` Build the suffix of the autogram but using only the letters `X`, `V`, `I` and any other letters in the intro and separator. ``` ≔⁻λ№⁺θεIδ ``` See how many `I`s we are short. ``` ¿⁼δ﹪δ⊕Lζ ``` Can we make up the number of `I`s using letters not present in the intro or separator? ``` ¿⁼⟦ικ⟧EXV№⁺θεμ ``` Do the numbers of `X`s and `V`s match? ``` ⟦⁺⁺⁺θ ⭆δ⁺⁺I §ζμ, ε ``` If so, then concatenate the intro with any necessary extra letters and the suffix and output the resulting autogram. ]
[Question] [ Given a sequence of integers and an integer `N`, output the number of contiguous subsequences that contain at least `N` distinct integers. Each integer in the sequence is non-negative and will not be larger than the size of the sequence. For example, with the sequence `1,2,2,3` and `N=2`, there are 5 contiguous subsequences that contain at least 2 distinct integers: ``` 1,2 1,2,2 2,2,3 2,3 1,2,2,3 ``` **The asymptotic time complexity must be linearithmic in the size of the input sequence. (The time complexity must be at most amortized `O(S*logS)` where `S` is the size of the input sequence.)** ### Testcases: | Sequence | N | Output | | --- | --- | --- | | 1,2,3 | 2 | 3 | | 1,2,2,3 | 2 | 5 | | 6,1,4,2,4,5 | 3 | 9 | | 1,1,2,2,2,3,4,4 | 4 | 4 | | 8,6,6,1,10,5,5,1,8,2 | 5 | 11 | | <https://pastebin.com/E8Xaej8f> (1,000 integers) | 55 | 446308 | | <https://pastebin.com/4aqiD8BL> (80,000 integers) | 117 | 3190760620 | [Answer] # JavaScript (ES6), 93 bytes *Saved 18 bytes thanks to @user81655* *Saved 2 bytes thanks to @tsh* Expects `(N)(sequence)`. ``` n=>C=a=>eval('for(i=j=a.length,c=s=0;~j;c+=c<n?(C[v=a[--j]]=-~C[v])<2:-!--C[s-=~j,a[--i]])s') ``` [Try it online!](https://tio.run/##bZfLbhxHEkX3/grNyiQmaVS@My23DUOfQXBBcCSPCIE0RENL/bp8ThRnNjKEVhe7suJx48aNqMf7L/cvD58//vnXzdPzf95/@3D59nT59d3l/vLr@y/3n65@/PD8@erj5fFy/9On909//PXf9HB5uRxvvz6@ffj35eGXp9@u3t1@udzf3tw83t1dbr7y1931L@Xnm3/d3Ly7fbm5fH1M3v14d3f98uP1t9/fXN7cjlXSWi2t40itz1RKS3keKfO9y5H6SOVYqY2dVht855T5rn2nsWcaeafeW6rlPMefc/Q0c0uj5jR6SZVrTsyW066cOHKq@Cs1Lfy1slPbB9cllYn/zm2s1KPxd@d3nBLHwGHfBWc97YFVfqtDszXNWdNu2OGZtXpqs6Q8jjQXEbSVjK0axE5711Qrj/h4wyxH4pHc@Z37o6aycdX4O5M@IS2u2x48W9LmZ5MBtQIMmZywXj09CH5t0KkpVwyD48BxBl9yLH1hyFt@H4BViJdHD5xxfoN/KRN4uDD4hfdVwIvAsTG5FEGskmXNnCzg3EklrMzUFw@aEp/JkdYiw4atTjErmVvfxZeYeItQ8khSoHXzJSEMdhxswhpkNTFczDsLOxXgf@6EzUi7lQy@ehwAqe2zblkgqdMw3xlH1uhR8s2jnaO5SBDrkcDOJDfpjZlJ9AhCmvQG04XrQVSDVPciKOKvBkrxOC75uthydPNb2xjOIkV1FpFCs/AjGTswkzrXnWJ2qFJxhKGxMNSD1esokcw0Qcg1qfNsZAEqW1KaJF9HD0pPa9mPCLXgKFOoult8tF/1uQMaqdzBuS5/Bwuz5V6dejyioOvAIxhNTBfw6piT@ha5Zu@BRuM@kZY6OAcyVDE6rhTbawdZyzziukzDBrrXnupknC36knOpkdkgs2XJctC9UqoBbJvCDNqCCJa4vBJBxq0ctR/A06wx/VwAuyoW9h90W9QoB3TEJMSc23rAAe2xCa8swgIfaaKOZK5taVukbfHCFCE3@xeZsDoTU4WzhZQ3jbDo16Wq1NfqEaI6NfCjTe0ISwbX3U1QkVKCgIffTdLqLjBtU5WaAduaYbbILomI@6x0wKxFhgX0Kp8xDAeX/TV6oxQggstRsHCsyJCOCuABSoqFFpSPukiSrS7YQ0cE2uFUXwptjeJnqrKpSoW4DXeea/zeqG2n9jX6QTHWJv7tSWwsG8zek4d8w/2GNFWO2heTR/EMcnWczbwgjAJmc00C51d6aY4jOn@QkicKiWxsLepIAhQQpgytoC5AmumMUGK@FR8AnlHY0DJnDOlQ6zL501myQkBFIs5TIoKfKLBMbw4HvDllSt5R9QbAVnHYqxILtuy1IisBqjRoszmNsiqgspyBUmvQ3NkDRkKq7gVsMJdOMix1SYYjRA4dfVhE/J4FWGEz6MH9DF2cLo3ws9OEDlaicxChRIMAYnEqOibqiKHq7UbN17ZnFEQaYtr8wcWBN7WjRtntFTnLVMi2G7RgrDSV3mup0p1f6LjTCDSWekGrSi1Nh5oFF074Sdl5sVQOWVZaiB/C3UN9INlW0EJPW7YZJQ8VKj3mVy@nNAuFfMw8srazpZ9tEOftlB7dUswPsWldvaKs5G0zDmATVilOAZYjRfoTbxcqZwacE6LtN1UDcMtAn8D/EYeJKxYUmxoD4NoUf3tQAUa/1KKFaJiptT3VQxF3BkHQUOZXlXFmKvBFKnNuuy3kFhGOUN99UsSkthuQq4EOqZ/T0v5rUU9rLqQDSi5oa9F64HC2W3X/cm6qm9E9I/Lo4LLIz7nyv5@diHSnHeGsXrvFSN@m3pVkruUB141u6LSabScrs2NKfasjiK2EDieEspdtYgu1sTzGOTRcqtwASp0h8LsofStEbeQZQXfwKVjb9Nc4FVMT1rhFHVrU2VZ0mjgiFdEaqjW8w4NZJjnF@jyXKTuCYgz3LXVEcJUwt8dT7Irr2FohNxkdWMu4nWIO35OMnlOUbHfF3/VF/SeDFWHElkak5LeYRllxkmUgar9XcQix5Xc7I/YKg3a5jTEqI@wxToxSQymGFDDdrR/X2x3rFp@YrQTuWFPMHDtlncI2bHXSrAJVowOaUuTGDWGmu@F0TwJyICDyzmfHcgFilMudZGRFXtHYISB293IXy@lVNLOTh4Bc4E@r0G5wRG1Qj91qW4nQxd4JtGMdLkH6ls/dwE4KUQTkDniOCMrlMZmmjoU3l5UW/W0VlWOp5W5Q3OuFXao5jEoJFNz3pVFd8SpQuwsJVSg5wnYUSpYdrw0UeJ7bjJ1VazSsBD5X@BiGLkeCU48RG9Z2CdcRHeUQcEEZEEStHnaMO41qeHJZ5yHnalCLtxjfG9wxwolPOSiGKYSmGnYfhtzDwdpSZMfsz6GEtGZUSxEpLgxK2ozdcoWyl1cNHudo6TFlnRyuPkF2qu4IdfVpo8SpZX@sGcR15ZXIbvISwsEj2IezyNCiVFswa7zr9dCIfr6yLNdX09cokY0S2tNd/Y@TzzWHqrrpdxrQbxU5RwvMUOZuhdlSXFNjDNl6h69k8agvc/2Ua3It8RZmJynQze6ZvnnmePtUBIvzm5o6AR1E26mWJX8JVwrMzqdu9apWc2QGOiqM740uQp3CFd8f///OJWzHuf8YdtknhRRgERnruHv7ww8Pz08vz5/e//Tp@Y@rD1fl@uoWN2ncXV//wy2s8a9@f7NykzK4NvHp3x9o8fT5PBZcHb8/1Dm0XP2Tyy1huKnBmH84ydHfr6@//Q0 "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~108~~ 104 bytes *-4 bytes thanks to @Noodle9* Takes three inputs, \$ A \$ *(the array)*, \$ S \$ *(the size of the array)*, and \$ N \$ *(the minimum distinct integers allowed)*. ``` s;f(A,S,N)int*A;{int c[1<<20]={},n=0,l=S;for(s=S*S;S;s-=l)for(n+=!c[A[--S]]++;n/N;)n-=!--c[A[--l]];s=s;} ``` The two-pointer method is used to achieve a runtime of \$ O(S) \$. Note that the `c[1<<20]` automatically caps the input \$ S \$ at \$ 2^{10} \$, but it can be adjusted to meet the constraints. [Try it online!](https://tio.run/##bZfNbh3HEYXXyVPQBgKIVhOe/u/GNRd6AW24VLgIlCgQINOGmVUEPbvyfTVkJEiGQN17Z3rq59SpUzVvb/799u3nz4@Xdy9epbv0@vr9w39@enX5yMfV2zf5l1/KcX/78VN6uD3Sh9u7y7vf/njxeHv3093l7vJ4c/vh2gsPL29/ePvm1Zubm7v7@5cvLw8/v75cP9zc/nBzc17@cH9/ebx9vHz6rN1f//H@4cX11ce//sVfr/Kb@6vbq485lVQ/pau7zK/H9//912@ElK@vfn7@weHrdPXa2@Vy9fsf/H734se//ZPf9e8PP6Yrz/u8h66vL0/myxfzTw7KVw7K9w7Knzjozw6Kz3voi4N6Ohgpp4aLlrpO6ldO6vdOvF2/cbKfnVSf99AXJ@05izMPMsFR01H7ylH73pG32zeO2rOj5vMe@uKon45WGsmM8pE6/3Jaqeitf@Wtf@/N2/0bbzk/u@sa8NQXd@MJvFXSWi2t40itz1RKS3keKfO5CzGMVI6V2thptcEnkfFZ@05jzzTyTr23VMt5jp9z9DRzS6PmNDp48Z0Ts@W0KyeOnCr@Sk0Lf63s1PbBd7Cd@O/cxko9KOnsXMcpcQwc9l1w1tMeWOVaHZqtac6adsMOz6zVU5sl5XGkuYiggR@xVYPYae@aauURH2@Y5Ug8kjvXuT9qKhtXjd@WgJAW39sePFvS5rLJgFoBhkxOWK@eHgS/NujUlCuGwXHgOIMvOZa@MOQtPw/AgrAHjx444/wG/1Im8PDF4BfeVwEvAsfG5KsIYpUsa@ZkAedOKmFlpr540JT4mxxpLTJs2OoUs5K59V18iIm3CCXDNpJp3XxJCIMdB5uwBllNDBfzzsJOBfifO2Ez0m6FvhBr0Fhh@6xbFkjqNMx3xpE1epR882jnaC4SxHoksDPJTXpj0s3mDg4mvcF04XoQ1SDVvQiK@KuBUjyOS74uthzdXGsbw1mkqM4iUmgWfiRjB2ZS53unmB2qVBxhaCwM9WD1OkokM00Qck3qPBtZgMqWlCbJx9GD0tNa9iNCLTjKFKruFn/ar/rcAY1U7uBcl9fBwmy5V6cejyjoOvAIRhPTBbw65qS@Ra7Ze6DRuE@kpQ7ONTVjRceVYnvtIGuZR3wv07CB7qmnOhlni77kXGpkNshsWbIcdK@UagDbpjCDtiCCJS5PRJBxK0ftB/A0a0w/F8CuioX9B90WNcoBHTEJMee2HnBAe2zCK4uwwEeaqCOZ77a0LdK2eGGKkJv9i0xYnYmpwtlCyptGWPTrUlXqU/UIUZ0a@NGmdoQlg@vuJqhIKUHAw3WTtLoLTNtUpWbAtmaYLbJLIuI@Kx0wa5FhAb3K3xiGg8v@FL1RChDB5ShYOFZkSEcF8AAlxUILykddJMlWF@yhIwLtcKovhbZG8TNV2VSlQtyGO881rjdq26l9jX5QjLWJf3sSG8sGs/fkIZ9wvyFNlaP2xeRRPINcHWczLwijgNlcczmECr00xxGdP0jJE4VENrYWdSQBCghThlZQFyDNdEYoMZ@KDwDPKGxomTOGdKh1mfx0lqwQUJGI85SI4CcKLNObwwFvTpmSd1S9AbBVHPaqxIIte63ISoAqDdpsTqOsCqgsZ6DUGjR39oCRkKp7ARvMpZMMS12S4QiRQ0cfFhG/ZwFW2Ax6cD9DF6dLI/zsNKGDlegcRCjRIIBYnIqOiTpiqHq7UfO17RkFkYaYNn9wceBN7ahRdntFzjIVsu0GLRgrTaX3u1Tpzi903GkEGku9oFWllqZDzYILJ/yk7LxYKocsKy3ED@HuoT6QbCtooact24yShwqVHvOrl1OahUI@Zh5Z29nSzzaI83ZKj24p5ofYtK5eUVbythkHsAmrFKcAy5Ei/Ym3C5UzA84J0faTqgG4ZaBP4P@Iw8QVC4pNjQFwbYq/PagAo19q0UI0zNTanuqhiDuDIGgo85PKODMV@CKVObfdFnKLCEeo7z4pYlLbDcjVQIfUz2lp/7WopzUX0gElF7S1aD1wONutun85N9XN6J4ReXRwWeTnXHm@7ESkO@0IZ/XaLUb6NvWuJPNdHvC90Q2dVrPtZGV2TKlvdQSxldDhhFD2sk1soTaWxziHhkuVG0CpMwR@F6VvhaiNPCPoDj4Fa5v@GqdiasIat6hDizrbik4TR6QiWkO1hnd4MMskp1if5zJlR1CM4b6ljgiuEub2eIpdcR1bK@QmowNrGbdTzOF7ktFzipLtrvi7vqj/ZLAijNjSiJT8FtMoK06yDETt9yoOIbZctzNirzBol9sYozLCHuPEKDWUYkgB0936cb3dsW7xF7OVwB1ripljp6xT2IatTppVoGp0QFOK3LghzHQ3nO5JQA4ERN7527FcgBjlcicZWZFXNHYIiN293MVyehLN7OQhIBf40yq0GxxRG9Rjt9pWInSxdwLtWIdLkL7lczewk0IUAbkDniOCcnlMpqlj4c1lpUV/W0XlWGq5GxT3emGXag6jUgIF931pVFe8CtTuQkIVSo6wHYWSZcdrAwWe5zZjZ9UaDSuBzxU@hqHLkeDUY8SGtV3CdURHOQRcUAYEUauHHeNOoxqeXNZ5yLka1OItxvcGd4xw4lMOimEKoamG3Ych93CwthTZMftzKCGtGdVSRIoLg5I2Y7dcoezlSYPHOVp6TFknh6tPkJ2qO0JdfdoocWrZH2sGcV15JbKbvIRw8Aj24SwytCjVFswa73o9NKKfryzL9dX0NUpko4T2dFf/4@RzzaGqbvqdBvRTRc7RAjOUuVththTX1BhDtt7hK1k86stcP@WaXEu8hdlJCnSze6ZvnjnePhXB4vympk5AB9F2qmXJX8KVArPzqVu9qtUcmYGOCuN7o4tQp3DF98f/v3MJ23HuP4Zd9kkhBVhExjp8DR9fvYaP71/Dvd2/fQ@n@qzFz@/iQyse9V380@f/AQ "C (gcc) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 138 bytes ``` def f(a,n): c=0;l=1+max(a);m=[0]*l;j=len(a) for v in a: while(n>(d:=l-m.count(0)))*j:m[a[-j]]+=1;j-=1 c-=~j*(d>=n);m[v]-=1 return c ``` [Try it online!](https://tio.run/##TVDRboMgFH33K@6b0GIjVbuuhv4II4tBTHVIjdqum3G/7oB2SwkP3HPOPSec7ms8nU2y7/plKVUFFSqIwYcAJItzzei6LW6owHnLeCxWOm@YVsYCAVTnHq5QGyisGj5PtVbIHFF5YDpqN/J8MSOKMcar5tDygkeNEGtG8yZi1OplxH6aFSqPzFhzfhUe7tV46Q3IZVTD@K6BAeIpgYzAThDglMDW38RNOwIWSD3gRA/Fv8jpPJM6Zm89/HWS2HtmfrDEVuDAJxqX@Lya4UDdOiVHVToq8UuvnqIUB/Kk5IfqHRW@XbYvqQwJ@BdNQhy4ijQxRLmavusO3b9F4B5G4M/bFW7PYI0qZDewH7u@th1W4aTnDUxmhgiOMA0zTI9crhgbxBzi5Rc "Python 3.8 (pre-release) – Try It Online") Credit to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) for the [overall idea](https://codegolf.stackexchange.com/a/220448/101474). I would have just commented on that answer but I am a new user with no rep, so I have to post a new one, sorry! Doing away with the dictionary and its method calls saves 11 bytes (at the cost of requiring Python 3.8, though I have a different solution saving 4 bytes without the walrus). We can save another 3 bytes by replacing `a[S-j]` with `a[-j]` and doing away with `S` (4 bytes if used twice as in the original answer). [Answer] # [Python 3](https://docs.python.org/3/), ~~189~~ \$\cdots\$ ~~157~~ 152 bytes Saved a whopping ~~16~~ 32 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved 5 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!! ``` def f(a,n): c=0;m={};S=j=len(a) for v in a: while(n>len(m))*j:m[a[S-j]]=m.get(a[S-j],0)+1;j-=1 c-=~j*(len(m)>=n);m[v]-=1;m[v]<1<m.pop(v) return c ``` [Try it online!](https://tio.run/##TVDLboMwELzzFXvDTk0UB5K2Ic5P5EhRhZylQMFB4KQPRH@d2iapaq1kz87Mjrztly7OKpymE@aQk4wpuvNAilXciGGMj6ISNSqSUQ/ycwdXKBVkRgEfRVkjUQfLNpQuql2TZMkxqNJUNMs31GRGbEUfeFwFghuTDMRPtSCz5yAUjZvkmhrO3Xu@b5btuSVXk9ahvnQK5KSx1681CCBJxGDDYJsySDiDtavQoi0D04hcw4puij@R1TkmssyTmeHKSlZu5sYBQ6xT6rlEZRP/WzfUw88WpcaTpUJnenYU59STBcp37Czlv1zWj5H0GbgXD33q2eXVTDG0C/wuWzJ/i8EcxuA@267fnN4MyolxUAfbrlSa5P5Qj0sY1AgBHGDoRxhuuQkK0aejT6df "Python 3 – Try It Online") Has \$O(S)\$ time complexity. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~82~~ 78 bytes ``` n=>s=>s.map(A=_=>{for(n-=!A[_],A[_]=-~A[_];!n;)n+=!--A[s[i++]];m+=i},i=m=0)&&m ``` [Try it online!](https://tio.run/##bZfLjhxFEEX3/RfeoBmcA5XvTKxG8oKvsCxk@YGM8IyFEUJC8OvmnKiBjRG0u6YrKx43btyI@vnV768@vf71/cff7u4f3rz9/O76@f76/Sf@/@bDq483z68/Xr//893Drzf3d9cnz1/8@DL5z/Xub7@ePbl/dnv/9Prk7u75i08v3j99@vLlsw9Pr@//Su@vH67H7Vdfffj8@uH@08Mvb7/55eGnm3c35fbmRUs9jZe3t5cvb@VU@K9@ebNyc6ScGrd5/ssDLZ4@n8cCh9qXhzqHVhpJS/kgjM7FSuV/Tnp0rJLWamkdR2p9plJayvNIme9deH6kcqzUxk6rDb6xynftO40908g79d5SLec5/pyjp5lbGjWn0YmTa07MltOunDhyqvgrNS38tbJT2wfX5DTx37mNlXoAw@z8jlPiGDjsu@Cspz2wym91aLamOWvaDTs8s1ZPbZaUx5HmIoJG7sRWDWKnvWuqlUd8vGGWI/FI7vzO/VFT2bhq/C18hLS4bnvwbEmbn00G1AowZHLCevX0IPi1QaemXDEMjgPHGXzJsfSFIW/5fQAWRT549MAZ5zf4lzKBhwuDX3hfBbwIHBuTSxHEKlnWzMkCzp1UwspMffGgKfGZHGktMmzY6hSzkrn1XXyJibcIJcMUkmndfEkIgx0Hm7AGWU0MF/POwk4F@Jc7YTPSbgU@ijVorLB91i0LJHUa5jvjyBo9Sr55tHM0FwliPRLYmeQmvTHpAHMHB5PeYLpwPYhqkOpeBEX81UApHsclXxdbjm5@axvDWaSoziJSaBZ@JGMHZlLnulPMDlUqjjA0FoZ6sHodJZKZJgi5JnWejSxAZUtKk@Tr6EHpaS37EaEWHGUKVXeLj/arPndAI5U7ONfl72BhttyrU49HFHQdeASjiekCXh1zUt8i1@w90GjcJ9JSB@ea/b6i40qxvXaQtcwjrss0bKB77KlOxtmiLzmXGpkNMluWLAfdK6UawLYpzKAtiGCJyyMRZNzKUfsBPM0a088FsKtiYf9Bt0WNckBHTELMua0HHNAem/DKIizwkSbqSObalrZF2hYvTBFys3@RCaszMVU4W0h50wiLfl2qSn2sHiGqUwM/2tSOsGRw3d0EFSklCHj43SSt7gLTNlWpGbCtGWaL7JKIuM9KB8xaZFhAr/IZw3Bw2R@jN0oBIrgcBQvHigzpqAAeoKRYaEH5qIsk2eqCPXREoB1O9aXQ1ih@piqbqlSI23Dnucbvjdp2al@jHxRjbeLfnsTGssHsPXnIN9xvSFPlqH0xeRTPIFfH2cwLwihgNtdcDpBCL81xROcPUvJEIZGNrUUdSYACwpShFdQFSDOdEUrMt@IDwDMKG1rmjCEdal0mfzpLVgioSMR5SkTwEwWW6c3hgDenTMk7qt4A2CoOe1ViwZa9VmQlQJUGbTanUVYFVJYzUGoNmjt7wEhI1b2ADebSSYalLslwhMihow@LiN@zACtsBj24n6GL06URfnaa0MFKdA4ilGgQQCxORcdEHTFUvd2o@dr2jIJIQ0ybP7g48KZ21Ci7vSJnmQrZdoMWjJWm0nstVbrzCx13GoHGUi9oVaml6VCz4MIJPyk7L5bKIctKC/FDuHuoDyTbClroacs2o@ShQqXH/OrllGahkI@ZR9Z2tvSzDeK8ndKjW4r5ITatq1eUlbxtxgFswirFKcBypEh/4u1C5cyAc0K0/aZqAG4Z6BP4P@IwccWCYlNjAFyb4m8PKsDol1q0EA0ztbaneijiziAIGsr8qDLOTAW@SGXObbeF3CLCEeq7T4qY1HYDcjXQIfVzWtp/LeppzYV0QMkFbS1aDxzOdqvuX85NdTO6Z0QeHVwW@TlX/v3ZiUh32hHO6rVbjPRt6l1J5loecN3ohk6r2XayMjum1Lc6gthK6HBCKHvZJrZQG8tjnEPDpcoNoNQZAr@L0rdC1EaeEXQHn4K1TX@NUzE1YY1b1KFFnW1Fp4kjUhGtoVrDOzyYZZJTrM9zmbIjKMZw31JHBFcJc3s8xa64jq0VcpPRgbWM2ynm8D3J6DlFyXZX/F1f1H8yWBFGbGlESn6LaZQVJ1kGovZ7FYcQW363M2KvMGiX2xijMsIe48QoNZRiSAHT3fpxvd2xbvGJ2UrgjjXFzLFT1ilsw1YnzSpQNTqgKUVu3BBmuhtO9yQgBwIi73x2LBcgRrncSUZW5BWNHQJidy93sZweRTM7eQjIBf60Cu0GR9QG9dittpUIXeydQDvW4RKkb/ncDeykEEVA7oDniKBcHpNp6lh4c1lp0d9WUTmWWu4Gxb1e2KWaw6iUQMF9XxrVFa8CtbuQUIWSI2xHoWTZ8dpAgee5zdhZtUbDSuBzhY9h6HIkOPUYsWFtl3Ad0VEOAReUAUHU6mHHuNOohieXdR5yrga1eIvxvcEdI5z4lINimEJoqmH3Ycg9HKwtRXbM/hxKSGtGtRSR4sKgpM3YLVcoe3nU4HGOlh5T1snh6hNkp@qOUFefNkqcWvbHmkFcV16J7CYvIRw8gn04iwwtSrUFs8a7Xg@N6Ocry3J9NX2NEtkooT3d1f84@VxzqKqbfqcB/VaRc7TADGXuVpgtxTU1xpCtd/hKFo/6MtdPuSbXEm9hdpIC3eye6ZtnjrdPRbA4v6mpE9BBtJ1qWfKXcKXA7HzqVq9qNUdmoKPC@N7oItQpXPH98b93LmE7zv3HsMs@KaQAi8hYh6/Ql2@/vvzwx8e3r397@@a7S730y760S84XSszue/n628//AA "JavaScript (Node.js) – Try It Online") ]
[Question] [ The challenge given to me is comparatively easy, and specific to MySQL *only*. I'm given a table `expressions` which have mathematical calculations done by a kid. Basically, I've to `select` all the right calculations! The table have the following properties, * `a` : an integer, *the left operand*. * `b` : an integer, *the right operand*. * `operation` : a char, any one operation from `'+'`, `'-'`, `'*'` and `'/'` (pure-div). * `c` : an integer, the result given by *the kid*. # Example ``` a b operation c ------------------ 2 3 + 5 4 2 / 3 6 1 * 9 8 5 - 3 ``` As we can see, the second and third operations are wrongly calculated, so they need to be filtered out. Here is what I've done till now, # MySQL, 88 chars *Rule:* 88 chars is calculated by removing *all spaces* (`\s+`) from the given code. This is MySQL, so they simply take amount of chars (calculated [here](https://regex101.com/r/h8kiSW/1)). ``` select * from expressions where if( '+' = @o := operation, a + b, if( @o = '-', a - b, if( @o = '*', a * b, a / b ) ) ) = c ``` [Try it on Rextester](https://rextester.com/RAVJO35061)! But, I'm sure that this can be golfed further, as many other submissions are of `73` chars, which is `15` bytes fewer than mine! I think I need to change the idea of my solution, but I can't find anything which can evaluate expressions directly in MySQL. Any ideas? # Rules * The names, specific to table, included in the code isn't subject to change. * `select` is considered to be the only method to output/result. * For multiple statements, it should be wrapped inside `begin ... end`, as the whole code is the body of a function, defined as, `CREATE PROCEDURE expressionsVerification()` [Answer] # Score 69 ``` select * from expressions where elt(ord(operation)/2-20,a*b,a+b,a-b,a/b)=c ``` Takes inspiration from [Marmite Bomber](https://codegolf.stackexchange.com/users/55931/marmite-bomber)'s use of `elt`, but uses a magic formula. Indexes into the list via `ord(operation)2/-20`, which buckets the four character codes across 1 to 4 by abusing `elt`'s rounding behavior. -1 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), who improved on the modulo reduction. -1 thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler), who found a better non-modulo formula. ## Score 73 ``` select * from expressions where elt(instr('*/-+',operation),a*b,a/b,a-b,a+b)=c ``` This is my best guess as to the 73 you mention other people have gotten in the question. [Answer] # MySQL, ~~82~~ 74 bytes ``` select * from expressions where elt(locate(operation,'+-/*'),a+b,a-b,a/b,a*b)=c ``` output ``` a b operation c ----------- ----------- --------- ----------- 2 3 + 5 8 5 - 3 ``` Explanation [ELT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_elt) returns the Nth element of the list of strings (the expressions are evaluated and converted to strings) [LOCATE](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_locate) Return the position of the first occurrence of substring [Answer] # Score 32 Solution using a database [view](https://dev.mysql.com/doc/refman/8.0/en/create-view.html) ``` select a,b,operation from e where c=r ``` Unfortunately a `select *` is not possible as the view contains an extra column with the correct result. Requires a view creation in the database ``` create or replace view e as select a,b,operation,c, elt(field(operation,'+','-','/','*'),a+b,a-b,a/b,a*b) r from expressions ``` ]
[Question] [ Identify each letter of the English alphabet with the number denoting its position in the alphabet, that is, `a = 1, b = 2, c = 3, ..., z = 26` (no distinction between lower and upper case letters is made). Every other character is identified with `0`. The "sum" of a word is the sum of its characters, for example: the sum of `e-mail` is `40 = 5 + 0 + 13 + 1 + 9 + 12`, since `e = 5, - = 0, m = 13, a = 1, i = 9, l = 12`. **The Challenge** Write a program or a function that takes as input an integer `n` in the range 10-100 and returns a word of the English language whose sum is equal to `n` This is codegolf, [standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). **ADDENDUM:** * For a list of English words, see: <https://github.com/dwyl/english-words> * Reading a remote list of words is forbidden. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~262~~ 235 bytes ``` lambda x:f'JKLmGoPlheAhVegytMtosOdtthfvtWypvttgYsRWspytps e eegli ra eehnkPooeoroyyauiuruotoituooup b aggd p ai mnrwiwpnwsnyotrosturwutr{"":8}d{"":14}gnlz nht ntkpstmsltty'[(k:=x-10)//46*23+k%23::46].strip()+k//23%2*'er' ``` [Try it online!](https://tio.run/##FU5La8MwGLvvV5hCSdJ2y5NSDD3sNNiDlR1WxraDSxzHJPFn7M9NvNHfnrpCQkLoIO2xBVXutJmb/c/cs@FUMzLRJnp@eR2e4NC3/LH95MLjG4J9rxHb5oxHr8@I4st@HK32qC0J4IFc9JIYFkKrugMABwPeMyedcYAg0QE4fVufgpgQNSGaMHlrBmVGOWo1WuUBDVh0ZnRo/hcLurvUN8uri1D9XxirFonCTlscbI/oo@@4o/vpPs@SNK22q6Jcd8uipLTa/j5YNFLHybpL06JcFquIm2huwJCJSBXuKsHjPNuQPMsTehceGakwnjakiackma8 "Python 3.8 (pre-release) – Try It Online") Uses words from the list that appear with and without a trailing `er`, cutting the number of required words almost in half. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~187~~ ~~51~~ 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žĆ•o‹§d∍(Ì•3в¾7:65Å1«.¥žy+èãJε„'ÿ.V}ʒAsSk>OQ}Réθ ``` [Try it online.](https://tio.run/##AVcAqP9vc2FiaWX//8W@xIbigKJv4oC5wqdk4oiNKMOM4oCiM9Cywr43OjY1w4UxwqsuwqXFvnkrw6jDo0rOteKAnifDvy5WfcqSQXNTaz5PUX1Sw6nOuP//NTk) (Pretty slow unfortunately, so no test suite, but [here is a list of all the words used](https://pastebin.com/7aAgCyMp).) **Explanation:** ``` •o‹§d∍(Ì• # Push compressed integer 13897672729830113 3в # Convert it to base-3 as list: [2,1,1,1,1,1,1,1,1,1,1,2,0,1,1,2,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,2] ¾7: # Replace the 0 with a 7 65Å1 # Push a list of 65 1s « # And append it to the list .¥ # Undelta the list (with leading 0): [0,2,3,4,5,6,7,8,9,10,11,12,14,21,22,...] žy+ # Add 128 to each: [128,130,131,...] žĆ è # Index each into the 05AB1E codepage builtin ã # Get the cartesian product with itself, to create all possible pairs J # Join each pair together ε } # Map over each pair: „'ÿ '# Push string "'ÿ", where the `ÿ` is automatically filled with the current pair we're mapping over .V # And eval it as 05AB1E code, pushing the dictionary word ʒ } # Filter the list of words by: A # Push the alphabet s # Swap to take the current word we're filtering over S # Convert it to a list of characters k # Get the index of each letter inside the alphabet > # Increase it by 1 to make the 0-based indices 1-based O # Sum them all together Q # And check if it's equal to the (implicit) input-integer R # Then reverse the list of remaining words (work-around for input n=11, # which otherwise would result in "fda", which is not in OP's list) é # Then (stable) sort all words based on length, from shortest to longest θ # And only leave the last one # (after which it is output implicitly as result) ``` Unfortunately, not all words that can be found in [the 05AB1E word list](https://github.com/Adriandmen/05AB1E/blob/master/lib/reading/dictionary/words.ex) can be found in the provided list as well. [See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210), to understand how the dictionary words and compressed integer list works. --- **Original 187 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` “„é…ªƒ…°»ØÎ‰éãŠêˆÜаí©ÓŽÄÍÝ‚†–ìŠÑÞã™Ä‡ÉˆÁ³²áäÁÑÆ©…¥Ê†…íÆ±Ñœ›Ç²èœÊ‚ì€€Šµ€„±½†íª¯ÅÝ‚îäÔÈÃ޺줃‚ž¨€º¢êˆ¨ïëïÆÐ¼ˆÌ²Ï……ƒÔ…ÙÒ„±ÞŒÂä†ÔÚ´´½é‚¤»œË´¥º™Žâ¤Ñ¸‚É„¾ÈÕˆî†Û‚äŠÁ‹‚Œæ‹Ì†ÏƒÓ‡È…ωɃà‚ë„¶™£“#sè ``` [Try it online](https://tio.run/##HZFNUsJAEIUP4xlceBytcuHKBRcYEBEURRKs0oipkAQq/IN/JUFY9Kth4y3mIvF1amYqqe5@8728XFZOzy7Oi8KZvjMhxs6MZHLw9LGSLZ7x4MwKYyQ2wuSvgb6NZIW5jOHbHeq4x5szgTORMz5mHOoiROLqMerODNCipCof8o4BUlTZbUjJGOK2FI0wZ2mNrvWdyXHDycz62gwwczXdJH7pmwllLTuqiJ/IEtclGgte3EMTVwglx0xSdR/YvWQUSS6x@pYMS0x5GniUX5pqE9QhnvvgoadGXuCVDITWQw2pknoI5JNrp8kEksqW5u5YGErOj2QEsaToyo86aal8TytPBCxU/qrllKlUndmoKw8kbtDWZodgX0NqKr2jObdYilQz1au@SZCEf@aogqwojk/@AQ) or [verify all test cases](https://tio.run/##HZHNTsJQEIVfxeDWd@AlfAFNXLhyQWLC7oJYQVGkxUQrNgUKKf/gX6AIizm5bFz5CvMidaa596bNzJz7nZ5eFE5Oz8/S47@yXV0W87kDdtyDXL6YsmmzCTBkM6DR3tXHgjZ4xgObBYbo2RCjXwdtG9ICUxrCs1tUcI83Nj6bkI2HiQw1EaDHlS4qbDqoiaREH/SODiKUpOtQxujjNhMNMJXSEk3rsUlwI5Ox9bTpY8Jl3UL80jcT0JK2ohL8iOa4ztCYycUtVHGFgBJMKFL3vt1RLCJKqKu@KcYcYzkOHulHTNUF1BC87L2Llhp5gZsxEFgXZURKasGnT1lbTcaniDZi7k4KfUrkIyWCLkVo0kqd1FS@EytPApip/FXLkaRSYrNWVy6EuEZdmw0BexpSVekNzbkmpVA1Y73qWwjUkz9zWECcHqX/). I've chosen random words which are both in the English dictionary provided, as well as in [05AB1E word list](https://github.com/Adriandmen/05AB1E/blob/master/lib/reading/dictionary/words.ex). **Explanation:** ``` “...“ # Dictionary string containing all words, space-separated # # Split it on spaces s # Swap to get the (implicit) input è # And used it to index into the list (0-based and with wrap-around, # so 91-100 wrap around to the first few words) # (after which the result is output implicitly) ``` [Here is just the dictionary string part of the program.](https://tio.run/##HZFLTsNAEETPChILViy4wCSYEEPAxA4SmGA5thPl/@En4pAsujTZcIu5iKm2Zka2urvmlcsXlyen52dV5UzfmQQTZ0YyPYb6WMsOz3hwZo0Jcpti@tdC36ayxkImiOweHu7x5kzsTOpMhDmHukiQOy@D58wAPiUN@ZB3DFCgwW5LasYQt7VohAVLG3Rt5EyJG06ObaTNGHPX1E3il76ZRDayp4r4qaxwXaOx5MU9tHGFRErMpVD3sT3ImCIpJVPfMsYKM54WHuWXpjoEBcRzH0P01MgLwpqBxIZoolBSD7F8cu01mVgK2dHcHQtDKfmRjCCTAl35USe@yg@08kTAUuWvWi6YSsOZrboKQeIWHW0GBEcaUlvpgebss5SqZqZXfZMgOf9MVf0D) [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210), to understand how the dictionary string works. [Answer] # JavaScript (ES6), ~~217~~ 205 bytes An idea similar to the one [used by ovs](https://codegolf.stackexchange.com/a/201298/58563). Most words are used twice: once with the `-ty` suffix (which is worth \$45\$ points) and once without it. ``` n=>"JK"[n-10]||["Hwy",,"Yor",,"Yot"][n-56]||"KaMMaOPQCanSTAtMiAmiCatDuBawBetGilBolPieBitBooCooEmpToFooBunCotDotKitBoxBusButCutJotJaunGusGutYesUmpJutSixMusUnsNut".match(/.[a-z]*/g)[(n-12)%45]+(n>55?'ty':'') ``` [Try it online!](https://tio.run/##TVDLbtswELz7KxYCCpKVzThpHDQPObDkR2PHTQonh0DQgZBpR4HNFchlnVe/3aXcS4EFdjAz2Bnsi/qtXGmrmjoGl3q/SvYm6UfTWZSbznG3@PzMox@7t6jdjp7Q/lsUFUHsnQUxmqn5XN3d/8qUWTwMaF4NtlWmaOhTtUs1TapNipv7SqcVpYgZ4mhbP@AYMfUmQxoizRrlNfUu9ZR5miJNlTcT7yaenrR73NZTT4vqde7do3E/PUVyq6h85kcyV5334uvRWuQ8lD0RX057RcxNv9e7ZvTGLhgTe1ei1ZCAg6QPuZTSFdLqpS8153UbStHwNcRQSsJb3GmbKae5kOWzsll4yYC4gA6cn7WhK1qtFVpuwr3j7iUYuGpAg@JYwEcLoETjcKPlBtd8xY2QtVqOzJJ/FyHi0OVAixC2IFuZNT9YFqQs8W@NiUGYGPh/ZkiSkHUN7G7G4ALYeHBzOxoyIVp/9n8B "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), ~~325 ... 240~~ 235 bytes Words of \$3\$ to \$5\$ letters ending in either `"d"` or `"y"`, with the penultimate letter deduced from the other ones. ``` n=>(w="EAGCABCABACBCCHFABAAAAdBADFaFGAAAKBCASCDBFEYLGNHHArOPSPPTOYRSDoCoDoCuFoEyYaLoYoNoSpSiPoOoRoToAttCurIzAtyButCurDizSuDruExpYesMurFurYumMusMizBuz".match(/.[a-z]*/g)[n-10])+(B=Buffer)([B(w+(c=n>27?'y':'d')).map(c=>n+=96-c)&&n+64])+c ``` [Try it online!](https://tio.run/##TZBLb@MgFIX3@RVXXdQwrmnaGWX6GFLhV1I1aaK6GyvKAmGcetSChaFpPJrfnsFZDbpInw7n3gP85p@8E6ZpbaR0JY81PSo6RXt6lrFZwmJfLImTZJ578KuKWZrzfObxyR8WSRrnWbmYPc/nzKzWxXr9uipfilQn2m@X6@xQ8oUu9bMu2qJZ65V@0a@aWZs489gze4jdgGnTFy41LvtqS9ktncmdKd3H0nXLpo9df0Y@uBVv6JJseNRvv13u8EZFV@MtDlFMY1fX0mC0idE@RIKq6fXPh@AQ3AVVgLFvbb04VSG9nUQCn5@rcPLDd4pjJ7SRQKEDOoUNIaTbEiMrJyRC7QUIPOgthCCI1Qu9lybhnUSYiDduEv9hzCIMEdxOLmCMR6NaG6T8vKvxPSj4NcBAYYjhzwhAaNXpd0ne9Q7VSGHS8ipTFbrBPuJ0l5OMfVhhTaN26GQpLDcWfR9MAfgKAf1nBkp91gMEq6cA7iDI2eMiS/27R3@P/wA "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 361 bytes ``` say''.(memGunzip(decode_base64('H4sIAINkcl4CAx2PC3LDIBBDL/Qu5Q+JneJAgbVZTl/RGWA0WkloQ2BdDs6Niy+JPRIi50llqZyRRTcUQsWJX1Znc943wXnpDFLBLlIjdqLza9RGckaiF4pTneYyVvpD76w2CGKOp/FNDx+7eYs77sk5P24KdbLmaVSytNmcYp3Uhb1Tpa/S7pPY0nAF32x2T9BVTv6P6ek+pilyuWrlohYvG4M8jcdE1YsG1oZa5kftpuaaE7dmCpBvs6Lk/Rz66LFh7CrjLG7qGsOkc2pa9GVFOFq3mVHV/Po3aefhfyb5uBZsAQAA'))=~/\w+/g)[-10+pop] ``` [Try it online!](https://tio.run/##VdHLbqpAAIDhx1FDWu5QTVxwEYodFSjFQts0A4wVGZjRERQX59EPbbo4yVn9i3/5UXTC6jAw2I9G9@Ma1W7b3Eo6LlBOCvSZQYY0ZTx6VJhneOsqx4plXCXfkoHtmaYN@KBVA27ZoKXxlcVphPnQ3RrCtsIkkMzCZtq67LmlH3qlKmB8TPswjPKXgG2Xr2La5FNFvrw21HaACbB3KI7gBqehm1ewdBQaNSjp447aunaRLPdpQ3lnbV85HSVM11ml@pLyVGSghvFzf17XeULll30mRhTyzzr1E6ExHFm6StHUjKNO8zVUcbTEfbs9YbJPOldZPRzyYiEmzBVJCtVqd6YthAu9qC1qdkwDFR/eNA04e906HYCrH122qXKJwqkbOxvnKNfxY8z7RIZot9/1mdqaKTMCwxhNJvM//PuF478mb3eiwFFCP4ZhEAXhL6HnkjRsuFt16r0o/NQiNT0hxmazFJfZ/J/Ez1p5q8VsZv5SzP@D@QY "Perl 5 – Try It Online") Ungolfed program.pl: ``` #!/usr/bin/perl use v5.10; use MIME::Base64 'decode_base64'; use Compress::Zlib 'memGunzip'; # base64-encoded gzip'ed string of 91 words: my $data=<<''; H4sIAINkcl4CAx2PC3LDIBBDL/Qu5Q+JneJAgbVZTl/RGWA0WkloQ2BdDs6Niy+JPRIi50 llqZyRRTcUQsWJX1Znc943wXnpDFLBLlIjdqLza9RGckaiF4pTneYyVvpD76w2CGKOp/FN Dx+7eYs77sk5P24KdbLmaVSytNmcYp3Uhb1Tpa/S7pPY0nAF32x2T9BVTv6P6ek+pilyuW rlohYvG4M8jcdE1YsG1oZa5kftpuaaE7dmCpBvs6Lk/Rz66LFh7CrjLG7qGsOkc2pa9GVF OFq3mVHV/Po3aefhfyb5uBZsAQAA say ''.(memGunzip(decode_base64($data))=~/\w+/g)[-10+pop] ``` Run: ``` for n in {10..100};do echo -n "n=$n "; perl program.pl $n; done . . . n=95 potsy n=96 furzy n=97 luxus n=98 musty n=99 mizzy n=100 buzzy ``` Improvement: I could have search for words in `words.txt` that gave shorter gzip'ed `$data`. Probably shortest AND most similar word from one `n` to the next. [Answer] # [C (gcc)](https://gcc.gnu.org/), 574 bytes ``` char*s[]={"ee","afd","ic","m","n","o","dl","el","ii","s","as","il","3rd","er","es","y","ln","by","cy","gv","ey","fy","fz","or","um","ot","lx","yl","ym","yn","yo","zo","xr","yr","ys","ty","bys","xw","xx","buz","ety","hwt","now","yew","guz","hvy","hwy","kyu","yor","yum","yot","you","puy","yow","yox","yoy","suz","swy","doxy","cozy","xxv","cuvy","xxx","eyry","yawy","xyz","yoky","youp","prys","fuzz","yoyo","huzz","yows","yowt","typw","burys","muzz","yutu","xyst","curvy","dizzy","wuzu","druxy","ayuyu","yesty","potsy","furzy","yummy","yours","yourt","buzzy"};f(n){n=s[n-10];} ``` Wordlist generated using [my program](https://tio.run/##ZVHRboMgFH3nK@66pEJal/ZVrD@yNQ1BakkUDGKXpfXbHeBW6MbL5R7PuZx75H2fN5zP86tUvB1rAaXUgzWCdRWKmEOkalKEc/vVixTpWF8hJFUrlQCpLHxqU5@4HpXFXKvBwmDrolhGwdpVgm4I3PFkc5toaM7aYDZaDRwKCCT4OQY2B8AccsAZy1zZEwJryLEcWNtfGOakqvY7sswxwo5GgaFo8q4sdEwqfNWy/n02teNN04i6XUqn2aacCoaOte3JrzVQ9DBLoRHW63Egc6m2YRyhsHi/PTZYYvBmQixwSDNaNH@4T5Hx0ThJ4uI9KI9RJM/4xbHeWqEae8EE7nd46qtg7dHHcMPq/ya752IyU9zZryDdx/2Oulr6i79tNnHgEoYeLZSl55SwKmDla/qMPHok@1CZ@0/z/A0) run as `program < words.txt`. [Try it online!](https://tio.run/##NVHLbsIwELzzFVYkpKSABOqtKV9COYQ8iEUTR34kcRDfnnrG1JLH653d2V27PNzLcl3LttAf5nI9P5O6TvZJ0VQBZRmgC7sPW4Vd/QaoAVIGMIgESLg@NXJqDYDTh/2LzBusEnAfQcJqCAt0keBQRVlkzEiFnofPQ8Cj9gKYEewJKGE95WHOEwDJNwfZmlw7QbNXIH0NvJNtx8gCH96xBlXZiGcnXsE/OE@bCorNKXgMdQwVKjVzRLV4NoEpSzfGy8yRNVUKhs9@ocwjKrsBZTSnaNwSOY7c/t8mEw/LmYeJU8aM7h3jrKO0sSyuWb2SC1ua3AK20o6NFt7FmWvDVxqUNfwPpxkeXqF796bN@7TxZQP/ypu0z5792Vz6w@l4zV@r7K3oCtmno5JVtnluRFiN0ikIKc7idMzD@Q0D1m6XMQRr0CGoSZNt9SW25if8t5B70aQyy/LNa/0D "C (gcc) – Try It Online") ]
[Question] [ # Background MQTT (Message Queuing Telemetry Transport) is an ISO standard publish-subscribe-based messaging protocol ([Wikipedia](https://en.wikipedia.org/wiki/MQTT)). Each message has a topic, such as the following examples: * `myhome/groundfloor/livingroom/temperature` * `USA/California/San Francisco/Silicon Valley` * `5ff4a2ce-e485-40f4-826c-b1a5d81be9b6/status` * `Germany/Bavaria/car/2382340923453/latitude` MQTT clients may subscribe to message topics using wildcards: * Single level: `+` * All levels onward: `#` For example, the subscription `myhome/groundfloor/+/temperature` would produce these results (non-conformances in **bold**): ✅ myhome/groundfloor/livingroom/temperature ✅ myhome/groundfloor/kitchen/temperature ❌ myhome/groundfloor/livingroom/**brightness** ❌ myhome/**firstfloor**/livingroom/temperature ❌ **garage**/groundfloor/**fridge**/temperature Whereas the subscription `+/groundfloor/#` would produce these results: ✅ myhome/groundfloor/livingroom/temperature ✅ myhome/groundfloor/kitchen/brightness ✅ garage/groundfloor/fridge/temperature/more/specific/fields ❌ myhome/**firstfloor**/livingroom/temperature ❌ myhome/**basement**/corner/temperature More info [here](https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices/). # The Task Implement a function/program accepting two strings and returning a boolean. The first string is the subject topic, the second is the criteria topic. The criteria topic uses the subscription syntax detailed above. The function is truthy when the subject matches the criteria. Rules for this task: * Topics are ASCII * There are no criteria fields beyond the `#` wildcard * Wildcards do not appear in subject topics * Number of subject fields >= number of criteria fields * There are no 0-character fields nor leading or tailing forward slashes # Test cases criteria1 = "myhome/groundfloor/+/temperature" criteria2 = "+/groundfloor/#" ("abc", "ab") => false ("abc", "abc") => true ("abc/de", "abc") => false ("myhome/groundfloor/livingroom/temperature", criteria1) => true ("myhome/groundfloor/kitchen/temperature", criteria1) => true ("myhome/groundfloor/livingroom/brightness", criteria1) => false ("myhome/firstfloor/livingroom/temperature", criteria1) => false ("garage/groundfloor/fridge/temperature", criteria1) => false ("myhome/groundfloor/livingroom/temperature", criteria2) => true ("myhome/groundfloor/kitchen/brightness", criteria2) => true ("garage/groundfloor/fridge/temperature/more/specific/fields", criteria2) => true ("myhome/firstfloor/livingroom/temperature", criteria2) => false ("myhome/basement/corner/temperature", criteria2) => false ("music/kei$ha/latest", "+/kei$ha/+") => true [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` lambda a,b:bool(re.match(b.translate({43:"[^/]+",35:".+"}),a)) import re ``` [Try it online!](https://tio.run/##xZHLSsRAEEX38xVNu0lImCxGNwMu3PgF7nxAd1JJCvtFVUUYxG@PLSjMyDhGEdz0ouCevo@0kzGGzdxf3s3OeNsZZWq7tTG6gmDtjbRjYddCJrAzAsXz@Warbx@a@0rXm4utXlf6paxNWa7Qp0iiCGaeLLeESTAGdam0343RQzNQnELXuxipqRoBn4CMTAR6tTLMQFLc0AQKWfXFMZHDJwz5EP2Bulb7H2Yni2CPmKNBOE36QF0bx8uMWcJhlADMX/o6AuuRWH4Vch82GDLDobOesMun0yE/71UdIM7@dZ4Ffe6BFjXQ@JgfTtBij23uHlzHP9r@b@Z6h1nD4CFI00YKQN9slQiDFPrKOdVmIav0Ru50Ob8C "Python 3 – Try It Online") This problem can be trivially simplified to a regex match, though another more interesting method may produce better results. EDIT I came up with a 107-byte solution not using regex. I don't know if it can get shorter than 72 or maybe I'm just not seeing to correct approach to this. Just the split-zip structure seems to be too large though. [Try It Online!](https://tio.run/##xZO/TsMwEMZ3nuLkLrEaNQMbUgYWnoANGBzHTk44tnXnoIaXDw4C1KJSAkJisc5nfb/788lxSn3wl7Ot72enhqZVoMrmSjlXTHUtNiJQISrhQwL0sAflW5hyeLcvxVY8SBsI9uWSgWeMhdpxdJgWSdnsdBj9ayxlvn28SClnHhvWhDFh8FCDGKY@DKbqKEta60KgalslM0RDKo1kxMWFYjaUilsaDSCDLU6JHD6hz4kwHKlLOCwo5TrYIybdG3@e9I66UY7XNdYQdn3yhvnLvk7ALBKnXw15COsUqe64M0vY5tT5IT/7tT1CbP7VnhX7PACt2kA1hHxwNBot6rx741r@kfd/Y9cbrFFsBuNTpQN5Q994FQmXb3ftHOgsZIgLuRVyfgE) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE ``` A monadic Link accepting a list of lists of characters, `[topic, pattern]`, which returns `1` or `0` for match or no-match respectively. **[Try it online!](https://tio.run/##y0rNyan8///hzsWPmtY8apirH/Vw5zQ3IEM59VjXof1HJ2cenvBwx3yggHaU6////9XTE4sS01P104vyS/NS0nLy84v004oyU4BCJam5BalFiSWlRan6uflAorggNTkzLTNZPy0zNSelWF1HQV1bXxumXFkdAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8///hzsWPmtY8apirH/Vw5zQ3IEM59VjXof1HJ2cenvBwx3yggHaU639voKKjew63AykQM/L//@ho9dzKjPzcVP30ovzSvJS0nPz8Iv2czLLMPKBAfq5@SWpuQWpRYklpUaq6jgI2xdooamK5dLAamZ1ZkpyRmkc185CcmFSUmZ5RkpdaXEyyiWmZRcUl1PFzemJRYjqqqrSizBSgEA28jGakNoo6ZYKRgBpiWHUT5R393HwgUVyQmpyZlpkMDM3UnJRiQg4iKszxGZCUWJyam5pXop@cX5SXWkRYaywA "Jelly – Try It Online"). ### How? ``` ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE - Link: list of lists of characters, [topic, pattern] € - for each: ṣ - split at occurrences of: ”/ - '/' character Z - transpose (any excess of topic is kept) ¿ - while... Ɗ - ...condition: last three links as a monad: ”# - '#' character e - exists in: F - flatten Ṗ - ...do: pop the tail off Ðḟ - filter discard those for which: œi - first multi-dimensional index of: ([] if not found, which is falsey) ”+ - '+' character Z - transpose E - all equal? ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes Regex solution. I added `Regex.escape` in case a criteria name just so happens to be something like `com.java/string[]/\n` or something silly that would have regex pieces. ``` ->s,c{s=~/^#{Regexp.escape(c).sub('\#','.*').gsub'\+','[^/]*'}$/} ``` [Try it online!](https://tio.run/##hY9RbsMgDED/ewrabKJtMjhBdoj9pqlEiCGoDUQYtlVpdvWMSpOWSpX6YSGb52fbx@Yyq3J@e8dCjlj@8GM2foCG74EBSjHAVu4YxmZLDxktKNvTHdMpp4c8pdWR13s6vfBpfv2qVoT0l871wLV30bbq7JznZ/NpbCq4ngfoB/AiRA@P2ZMJsgP7HFxIG290Fywg/qPKeAxPxmvhhb63Km/aVFpyNQMhO9I6csVr6hpiQHKblO59sFe@bCb53V@2cMmb68@2ISQb5UTK9KzXqsKCyHraJABsu0ox/wI "Ruby – Try It Online") Non-regex solution, 77 bytes Uses a nice simple split, zip, and match technique. I developed this one first before realizing that even with `Regex.escape` the regex solution would've been shorter anyways. ``` ->s,c{s.split(?/).zip(c.split ?/).all?{|i,j|i==j||'+#'[j||9]||!j&&c[-1]==?#}} ``` [Try it online!](https://tio.run/##hY/BboMwDIbvfQqvaG0nKGjHHTIeBHFIQwJmIUFJWNUSnp0GddKoVKkHy/Lv359tM5wusyDz8dsmbLSp7SW6Q559pFfsD@xew1JTKfPRY9J6JKT1fh9H@yLkr9L7t3a3Y8XxsyQkj6Zpfj8XG4Du0uiOZ7XRg6qE1NpkEn9RBUF3meNdzw11g@HPvT/oWMPVa@MKejJYN05xa/@tAo11L9bX1ND6kSoMVkFa@8qUU9ZApcFbH6b6wVlYNoV/n9wVr4chfuhFKxZbWH@0LUA0sglISKKwCbBy2oY2V9UmxHwD "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 50 bytes ``` $_="\Q$_";s|\\\+|[^/]+|g;s/\\\#/.*/;$_=<>=~m|^$_$| ``` [Try it online!](https://tio.run/##VcoxDgIhEEDR3mPsUkl0Kitc72AtLjERVxJgyMCamEw8uiOt5X/5xVM8iCg3Dfas3GAqW2s1X2a4al5MhZ4j7Ldg@nM8TZ/Es3KKRTQshGu@PyIiwbhJ7ycm/4cxvELugAmaT8XTra3kv1hawFxlV@IP "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~85~~ ~~84~~ ~~80~~ ~~92~~ 89 bytes ``` lambda s,c:all(x in('+','#',y)for x,y in zip(c.split('/')+[0]*-c.find('#'),s.split('/'))) ``` [Try it online!](https://tio.run/##hZC9bsMgFIXn8hRIGa6paag6WsqapUOHLJUcDxiDTWuDBaSK@/Iuzo9kS247Ie75OOdy@iE01ryManccW96VFceeioy3bXLG2iSQAoUN0IEo6/CZDnGIv3WfiK3vWx0SYEDS/Ll4fBJbpU2VRJpQP1MJGQ87AOiGxnaS1c6eTKVaax1r9Zc2cWA7FmTXS8fDyUm0Qn7qIBpp/sNmhqXTdROM9P4OKu18@DO45o7XS0fldBVHK7kl97KTJjBhnZFujsTf3gs4GiAIVVLhfRKbJRnunTYB5/COgWJ4e4UiVxepoNijqWYxlZyvFZYuUuLzdCFvoMjQwzUA8OQv0MPk6CfHQ3Zd4UYgNAOBl4D2STzE9ULQKhQ3kOpGMlHFC6sbpj9mIpmri/m6Y@Q2vzpeRDL@AA "Python 2 – Try It Online") Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) and [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) for pointing out bugs. [Answer] ## Python 3, ~~99~~ 88 bytes Without using a regex. With some help from Jonathan Allan and Chas Brown. ``` f=lambda s,p:p in(s,'#')or p[:1]in(s[:1],'+')and f(s[1:],p['+'!=p[:1]or(s[:1]in'/')*2:]) ``` [Answer] ## Haskell, ~~76~~ ~~73~~ ~~71~~ 67 bytes ``` (a:b)#(c:d)=a=='+'&&b#snd(span(/='/')d)||a=='#'||a==c&&b#d a#b=a==b ``` [Try it online!](https://tio.run/##rZHBasQgEIbveQqJZZOQg/eFvEFvfYJRJ4ls1DCahcK@e6qFQtPulrTNRZnx92Pm/0cIF5ymda3hLBteq7NuOui6qq1OJ8mD03WYwdWiq0TV6OZ2y4@8er9VlugCuMxf5GrBONYx7VnB2EzGRfbESvs6eotiIL843U/ek2hFRDsjQVwIS8bviiZzNS41vN2oj0BfTFQjusO5n0aWZIYxOgzhz@TeUIjHejEAwbAV9WR0aj3Cthsx/0dYO0kf2Tww8B5l11bC@nSEGZXpjUrm4qTD3gF/F8UPIAkBLboolCeH9A2xxJdIz46VX4EpzDGjMgtSKVOpyqJY3wA "Haskell – Try It Online") Edit: -4 bytes thanks to @cole. [Answer] # [Clojure](https://clojure.org/), ~~107~~ ~~91~~ ~~76~~ ~~65~~ 102 bytes An anonymous function, returns subject topic as truthy and `nil` as falsey (valid in Clojure). ``` (defn ?[t c](every? #(#{"#""+"(% 0)}(% 1))(apply #(map vector % %2)(map #(re-seq #"[^/]+" %) [t c])))) ``` [107](https://tio.run/##lZLtasIwFIb/9yoOKUJCcZ29AHsh4iCmpzWuSerJUZCxa3fxA7HMbS4/DuHkOR95eU0fNjvCo/QR3Jb5hTGyOsoGWw/1gsEs5XQ@v1ycHiCXhNOIW8jF4q1cFgImSkk9DP1BDprY6h5O3B4NB0pPuEc61Kku/xC5EIWQE3hVnynO1OmcZ4EhyzMQ7rAODsuOws43bR8ClUXJ6AYkzWlPobIzHnerTZxlAItHJb3dW58SwY1qE/6Ifrds1uifQe8ar8h2a/YY4z3cWor85xKdJt2NO7dkm5S6J5cqy7KbOBWIYlSRj7So/q/Fr2KMv/fkyqULKcQBjW2tSWJg38TRqKf0udErHdGh59IE8kjf1JEDWc@9h6sza5hcjKSuBlHqR6a6MlVy4Bc "Clojure – Try It Online") [102](https://tio.run/##lZPRboIwFIbveYqTMhIasjGBex/EaFLLAau0xbaYmGXP7qoSZ6dzjoteHL7z9/DlwDu9HgweUmVBbp17c2gdjQ5pjY2C6cwBn6e4Q7OfQpzGHyQmJCNpAu/0058TSlPW993ev5Sshx1ypw0kkBT0VIhTg68WtxCT2SKfZwQSCqdU6p9DdLwHuBFuAkTuV1pi3ho9qLrptDZ5ljuUPRrm/JCEnnE7LNd2EgHM7rV0YieUL2gZ9Hr8Hr0Rjq9QPYNeBS@NaFdOobXXcCOMdX8O0TLD2jC5MaL2pWtyTqPoW04BJAs64sBF8X8XD2WEn/fkyLnU/rA9ctEI7mVgV9vgqqf8XOglsyhRuZxro9Dc2LnIKY9yNiheVizPAi/l2ctg/Twj0LHjgocB1RiwuAmowoDFj4DeCOU6BeOmT/3en1aZjitK6a9MMTLFA6YcmfIBU41M5X@mLw "Clojure – Try It Online") working [91](https://tio.run/##lZLhSsMwFIX/9ykuKUJCcWF9gT3InJClt21mk9SbO0HUZ5@ZHWPFqRNCCOE7JzeHY4e42xMeZEjgn5kXjInVQTbYBlitGexGEt57w7bHdDyOhhkpSDspF4nJhU4TjoOxCBZKUb4/VOJNlEIsKiHyWj/qTSU@lGI1eYMlx0sQ/rWPHnVHcR@adoiRdKUZ/YhkOLsLVXzhab/dpWUBsL4mGdxLHoFi9DNtxq/RT@74l3ALemG8Jdf1HDClS7h1lPjPITpDpps7t@SafHVJblRRFOdwahDVTFHOsqj/n8WvYcy/d@PI2se8pRGta53NYeDQpNlTN@VzprcmocfA2kYKSN/SkWOuGg8BpDcjlHIFd1OR1KkgSv3I1Cemzg38BA "Clojure – Try It Online") [76](https://tio.run/##lZLdasMwDEbv8xTGYWAT1tC8QB8kzcB1lNSd/yqrgzL27J27ltKwbstujBFH8ueDtA27A8JJ@MTcnmhBkEieRA@DZ6uWmO4EwrNTpLeQzteoiAC9UDHaI0uEuRit0vC@Lvmi4uuKty91V/EPLaUkeRnGNBpaMu6O2@CgHjEcfD/YELCuagIXARXlIFwWX3g6bHZpWTDWPmqx5s34XAhu0pvxR/SrOYf3c9C7wRs045Y8pHQPDwYT/RliVKjG6eQBTZ9L92Qni6K4yWkYryYd5cRF838Xv8qYfm9m5NqFfKQI2gxGZxlg@zR5apafG71RCRx4qnVAD/jNjohoPFnPhFORlWLFni6LJK8LIuWPTHNlmryBnw "Clojure – Try It Online") [65](https://tio.run/##lZLdasMwDEbv8xTGIWAT1tC8QB@k7cB1lNSd/yargzL27JnLwpawbutujBFH8ueDtA2nM8IofGLumWhFkEgWooOebdhYCoQHp0gfIV2vUREBeqFitBeWCHMxWqXhdVfyVc13Nd8@Nvuav1WtlLKS4zRLo6E14@5yDA6aAcPZd70NAZu6IXARUFHOwSc8nQ@ntC4Y295qsebF@FwIbtGb8Vv0k7nG9/egs8EHNMORPKQ0h3uDif4MMShUw3Jyj6bLpTm5l0XxJadlvF50lAsX7f9d/Cpj@b07Izcu5CNF0KY3OssA26XFU3f5@aQPKoEDT40O6AG/2RERjSfrmXAqslJsWPWxSHJaECl/ZNqJyWs4vgM "Clojure – Try It Online") all defeated with regex chars [Answer] # [Kotlin](https://kotlinlang.org), 106 bytes ``` fun f(s:List<String>)=s[1].split("/").filterIndexed{i,v->v!="+"&&v!="#"&&v!=s[0].split("/")[i]}.count()==0 ``` [Try it online!](https://tio.run/##rY5Pa8IwGMbPzafIokiC2rirrMKOg922m/OQtUl9WZqUN2k3kX72Ljo2FDzu8j7w8nv@fPhowY2j6Rw1PKyfIcSHl4jg6o0owvZ@l4fWQuRMMpEbsFHjk6v0l66OsOiXm/6uYHM2m5108qNhu7p0bWE35KXvXOSiKFbnqkaB42pNHxHV4a@PHgnJjEfKOSyowlpQcFTlnxD351IuTkxGsqxNjmgdZ686RDoFuqTTo@HJ89v85pgQAxMpciBkGEep5LssSZK5LMfmsPeNljWmYZWx3qO00KcZ6H0jo25ajSp2qMkNsgJ3gxxrhaq@Jg1ClV4XlGx8OqHVJRgopQFtq0DmV67aWjn5v7jJNw "Kotlin – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ≔⪪S/θ≔⪪S/ηF∧№η#⊟η≔…θLηθF⌕Aη+§≔θι+⁼θη ``` [Try it online!](https://tio.run/##hY5BCoMwEEX3nkJ0k6DFA7gSaUHoQvAEotEExkyMo9TTp1FLoatuZjHvz5vfydZ22IJzxbKoUbPGgCJWabNSQ1bpkfE0jLLIz5nnwf@U9KkBbcgK3bMSV01MehYfrEbDJOc8/GjKvQNRSr@d0/Ap9Ejy4NerU/JQui8ATkUSfS8LqnQvXseZukge1L4Hsfu8trAcwIty56Zd4iSy0fom/QCINgO1@cYWccpITEbYllYrguQnFLvbBm8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` (Charcoal's implicit output for `true`) for a match, nothing for no match. Explanation: ``` ≔⪪S/θ ``` Split the subject on `/`s. ``` ≔⪪S/η ``` Split the criteria on `/`s. ``` F∧№η#⊟η≔…θLηθ ``` If the criteria contains (i.e. ends with) a `#` then remove it and trim the subject to the new length of the criteria. ``` F⌕Aη+§≔θι+ ``` Where the criteria contains `+` then replace that element in the subject with `+`. ``` ⁼θη ``` Compare the subject with the criteria and implicitly print the result. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes ``` %`$ / +`^([^/]+/)(.*¶)(\1|\+/) $2 ^¶$|¶#/$ ``` [Try it online!](https://tio.run/##K0otycxL/P9fNUGFS59LOyFOIzpOP1ZbX1NDT@vQNk2NGMOaGCCPS8WIK@7QNpWaQ9uU9VX@/8@tzMjPTdVPL8ovzUtJy8nPL9LPySzLzAMK5Ofql6TmFqQWJZaUFqVyaaMoUgYA "Retina 0.8.2 – Try It Online") Explanation: ``` %`$ / ``` Suffix a `/` to both lines. ``` +`^([^/]+/)(.*¶)(\1|\+/) $2 ``` Repeatedly remove the first element of both subject and criteria while they equal or the criteria element is a (happy) `+`. ``` ^¶$|¶#/$ ``` The criteria matches if it's just a `#` (with the `/` that was added earlier) otherwise both subject and criteria should be empty by this point. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` :Q::E"[+]""[^/]+"\#".* ``` [Try it online!](https://tio.run/##K6gsyfj/3yrQyspVKVo7VkkpOk4/VlspRllJT@v/f6Xcyoz83FT99KL80ryUtJz8/CL9nMyyzDygQH6ufklqbkFqUWJJaVGqEhc2tdooSgA "Pyth – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 19 bytes ``` ḟ”+ṣ”/)ZẠƇṖœi”#$¿ZE ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmPGuZqP9y5GEjpa0Y93LXgWPvDndOOTs4ECiirHNof5frf2/pRwxwFXTsFoJD14Xauh7u36DxqWvNwxyKVw@1ARiTX0ckgExr3Hdp2aBtE6P//3MqM/NxU/fSi/NK8lLSc/PwifW39ktTcgtSixJLSolQuLApyMssy84AC@bmEVGZnliRnpOaRYGBSUWZ6RkleanExTGFaZlFxCV6L0xOLEtNRTUwrykwBCiGr4tJGUaFMHZ8huZcoZ@jn5gOJ4oLU5My0zGSg51JzUkjwKlRhUmJxam5qXol@cn5RXmoRshIA "Jelly – Try It Online") A monadic link that takes as its argument `[topic], [criterion]` and returns `1` for a match and `0` for no match. [Answer] # JavaScript, ~~69~~ 66 bytes ``` t=>s=>new RegExp(s.split`+`.join`[^/]+`.split`#`.join`.+`).test(t) ``` [Try it online!](https://tio.run/##tZDBasMwEETP8VcYcoiFW/vaS3LrD/QaUqzIK1mJpBWrjdt@vWtwDnYJ1BR6WZbh7TIzF9nLpMhGfu5fBr0feH9I@0OAj/wNzOtnLFKVorPclE11QRua43t9GvdJ3N7FqmxExZC4YDFopIIxWpWjzo/ZZue/OvRQG8JbaLVDpNrZ3oZRQF8z@Agk@Uawe3pMXy2rDsIadPb4TNZ0HCClOawtJf7VhJEkzfKzJtuO0pzMTiLbKAwJHVQOTZHrKbkoHnkrF8ciF1n2f139SL8qUO1xHCmCstqqsSpw7R/Ku8NnmcBD4FohBaDVzZULl9upqOEb "JavaScript (V8) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~149~~ 148 bytes ``` def f(t,c):t,c=t.split('/'),c.split('/');return all([c[i]=='+'or c[i]==t[i]or c[i]=='#'for i in range(len(c))])and not(len(c)!=len(t)and c[-1]!='#') ``` [Try it online!](https://tio.run/##nVTNbqQwDD5PniKllSCClp3ZW1ecVton2BvKIRMMRA0JcsxKffrZ0M6MoELqtBJy8M9nfbZsj6/Ue/fzdGqg5W1GhRbPUVT0FEZrKEvLVBR6ofxCoAkdV9Zmta6NrKo0Tz3y93@K8qqk92kbFcON46hcB5kFl2khpFCu4c7T2XBXzS@9WXX9uJd3M1acNBoCNGrPK54Mr70foOzQT65prfdY5iXBMAKqSAkSdgk/zOH5KvI@YYwg0G8VIER3zXZ1lqijTgoen0QU/I@yAWSxdujZ8xenhaNsYOFbojYYWvPPuGjww4pqwa@lrfNvpHgxpHtw38YvKBzRdD05COFDho0qWoOBvlDEMkWnUHVrFi2aJppuw3@nkYebG7nZhQ/wmyooBx9FGEGb1ujYMbBN@JTSVxp72G7MMU7xAI5K7dEB3gqeQmT5AuahV6VV8zrMg5xfTPli1iVjCGGy9LYsks17fNmfeZ2vu/TMdn6icaIYF@/H2Vz/kPEr@FLfS8F256R5Vb@j4sW4hOylZCMaR9l8W86BQpz@Aw "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε'/¡}ζʒ'+å≠}˜'#¡н2ôøË ``` Input as a list in the order `[criteria, topic]`. [Try it online](https://tio.run/##yy9OTMpM/f//3FZ1/UMLa89tOzVJXfvw0kedC2pPz1FXPrTwwl6jw1sO7zjc/f9/tJK2vrZ@WlFmSnqqfnFqcn5eSnxKUWJ5apG@spKOglJ6YlEiUCa9KL80LyUtJz@/CLviktTcgtSixJLSolT93HwgUVyQmpyZlpmsn5aZmpNSrBQLAA) or [verify all test cases](https://tio.run/##rZGxTsMwEIZ3nqJykTok6CRGlgo2Jh6gqsBxLonVxI5sp6VIfQDExsxAB94AKhaWZgOp4hl4keCGViIQ1ABdTudP//26@y019TgWQ3Is0szsGZlydtAi3fGZu7NiKTUGlVhSy04yY2EpKRYPHZhPJ4vZ83XHye/eLm8nLzed9nz6@rSf3@eP@VXhzmfdotcj1COuLYz03VavbOqe4OMHScaRTBBCJTPhB7GUChwwmKSoqMkUErdVp4n5kAsLZFIR/8dywA2LUGzN79OKnuJhZARq/WvHgCtttnNzSBUNq5pAcd@ib3ZORdX@wyc0c1hn/jWgmulG20MibdEpMh5wZsPD2NebFmoY8c8GHtWYoDDApBKo6kYHyHcjCk45lWm724rE1KA2a5mzvkkjk8I/9RUd4cYAquKmcThwCEdLa3IB47I/hxEMISP9/js). **Explanation:** ``` ε # Map both strings in the implicit input-list to: '/¡ '# Split the string on "/" # i.e. ["+/+/A/B/#","z/y/A/B/x/w/v/u"] # → [["+","+","A","B","#"],["z","y","A","B","x","w","v","u"]] }ζ # After the map: zip/transpose the two string-lists, # with space as (default) filler # → [["+","z"],["+","y"],["A","A"],["B","B"],["#","x"],[" ","w"], # [" ","v"],[" ","u"]] ʒ } # Filter each pair by: '+å≠ '# Only keep those which do NOT contain a "+" # → [["A","A"],["B","B"],["#","x"],[" ","w"],[" ","v"],[" ","u"]] ˜ # Flatten the filtered list # → ["A","A","B","B","#","x"," ","w"," ","v"," ","u"] '#¡ '# Split the list by "#" # → [["A","A","B","B"],["x"," ","w"," ","v"," ","u"]] н # Only keep the first part # → ["A","A","B","B"] 2ô # Split this back into pairs of two # → [["A","A"],["B","B"]] ø # Zip/transpose them back # → [["A","B"],["A","B"]] Ë # And check if both inner lists are equal # → 1 (truthy) # (after which the result is output implicitly) ``` ]
[Question] [ Given some positive integer `n`, design a protractor with the fewest number of marks that lets you measure all angles that are an integral multiple of `2π/n` (each in a single measurement). ### Details As an output, you may output a list of integers in the range `0` to `n-1` (or `1` to `n`) that represent the position of each mark. Alternatively you can output a string/list of length `n` with a `#` at the position of each mark and a `_` (underscore) where there is none. (Or two different characters if more convenient.) **Example:** For `n = 5` you need exactly 3 marks to be able to measure all angles `2π/5, 4π/5, 6π/5, 8π/5, 2π` by setting (for example) one mark at `0`, one mark at `2π/5` and one mark at `6π/5`. We can encode this as a list `[0,1,3]` or as a string `##_#_`. ![](https://i.stack.imgur.com/vM5za.png) ### Examples Note that the outputs are not necessarily unique. ``` n: output: 1 [0] 2 [0,1] 3 [0,1] 4 [0,1,2] 5 [0,1,2] 6 [0,1,3] 7 [0,1,3] 8 [0,1,2,4] 9 [0,1,3,4] 10 [0,1,3,6] 11 [0,1,3,8] 20 [0,1,2,3,6,10] ``` PS: This is similar to the [sparse ruler](https://en.wikipedia.org/wiki/Sparse_ruler) problem, but instead of a linear scale (with two ends) we consider a circular (angular) scale. PPS: This script should compute one example of a set of marks for each `n`. [Try it online!](https://tio.run/##dVJNb6MwEL37V8wh0toKoNDeqiSHVdVT9xcg1BhigoU9RrbZ7Vb97@kY0jbtag9Y@L2Z9@bDvQyDMuZ81nZ0PsK9jLJ41CGya@BhwjZqh4xJY@6JBQQTYAeBQlY4NRVwmTcCDtYdD0S@goRtTjEZNMtPDXkOJ4XKy6iAZGB0IejGKDiSoMRWBei8s3DSvxWC9F7iSVmFkbG2dy4o0h3Ic7n8gM18/69qmJqgIrgOjMJT7CmW/mNPDMHVJiuzm@w2K4oiw7ysGfzplVfsQ/5pln@lczvbVvU1t6GPsKr@gib8O9peyq6gvTOkZ9I83knerksBnAoQfKCjhvWawH9ZGARj1Gun8QgSQT1LO1KX1JLVqK00gJNtlJ8R6QcapvO0hWWayC4Jv2YK0@pIaLUkT/bnXzJzdpRewcHhAfgytIKihKC4TptI4pzvdiiKC9mFmDha/nM2ewrqb0j9VWVRYA3ZFbPNOf98PdvVXuz3uxc9JoXP/daMWalTfaPXGInj/EvpKREoE3hn9AhJQMx25WZ@Ym6K4xQDTY3MF2txPr8B "Haskell – Try It Online") PPPS: As @ngn pointed out, this problem is equivalent to finding a minimal difference base of a cyclic group of order `n`. The minimal orders are listed in <http://oeis.org/A283297> and some theoretical bounds are found in <https://arxiv.org/pdf/1702.02631.pdf> [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` :qGZ^!"G:q@&-G\m?@u. ``` This runs out of memory on TIO for inputs beyond `8`. [Try it online!](https://tio.run/##y00syfn/36rQPSpOUcndqtBBTdc9JtfeoVTv/38LAA "MATL – Try It Online") ### How it works This generates the Cartesian power of `[0 1 ... n-1]` with exponent `n`, and uses a loop to test each Cartesian tuple. The test consists in computing all pairwise differences of element if the tuple, and seeing if those differences modulo `n` include *all* numbers `0`, `1`, ..., `n-1`. As soon as a Cartesian tuple fulfilling the condition is found the loop is exited, and the *unique* entries in that tuple are printed as the solution. This works because given ***u*** > ***v***, a *sufficient set* of tuples with ***u*** *unique* entries are guaranteed to be tested *earlier* than any tuple with ***v*** unique entries. A "sufficient set" means that if none of the tuples in that set are a solution then no other tuple with the same number of unique entries is a solution. For example, for `n = 3` the Cartesian tuples are as shown below, where each row is a tuple: ``` 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 ··· 2 2 1 2 2 2 ``` * The first tuple, `0 0 0`, is the only relevant tuple with `1` unique value. Even if `1 1 1` and `2 2 2` will appear much later, `0 0 0` is a solution if and only if those are. So the singleton set formed by the tuple `0 0 0` is a sufficient set for ***u*** = `1`. * The second and third tuples, namely `0 0 1`and `0 0 2`, form a sufficient set for ***u*** = `2`; that is, they cover all cases with `2` unique values. The fourth tuple, `0 1 0`, will never be selected as solution, because `0 0 1` will have been tested first. Similarly, the tuple `0 2 0` will never be selected because it appears later than `0 0 2`. Tuples such as `2 2 1` will never be selected as solution because the `0 0 1` is equivalent (modulo `n` and up to duplicated values) and appears first. * Etc. Commented code: ``` :q % Push [0 1 ... n-1], where n is the input (implicit) GZ^ % Cartesian power with exponent n. Gives an (n^n) × n matrix % where each row is a Cartesian tuple ! % Transpose. Now each Cartesian tuple is a column !" % For each column (that is, each Cartesian tuple) G:q % Push [0 1 ... n-1] (*) @ % Push current column &- % Matrix of pairwise differences (**) G\ % Modulo n, element-wise m % Ismember function: for each entry in (*), gives true iff % it is present in (**) ? % If all entries are true @ % Push current column u % Unique entries. This is the solution . % Break loop % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ŒPðṗ2I%QLðÐṀḢ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//xZJQw7DhuZcySSVRTMOww5DhuYDhuKL/MTFSwrU7IsOH4oKsR/8 "Jelly – Try It Online") ### How it works ``` ŒPðṗ2I%QLðÐṀḢ Main link. Argument: n (integer) ŒP Powerset; generate all subsequences of [1, ..., n]. ð ÐṀ Begin a dyadic chain. Call it with all subsequences S as left argument and n as right one. Return the array of all sequences for which the chain returns the maximal result, i.e., [0, ..., n-1]. ṗ2 Cartesian power 2; generate all pairs of elements of S. I Increments; map each pair [x, y] to [y-x]. % Map each [y-x] to [(y-x)%n]. Q Unique; deduplicate the array of modular difference singletons. L Take the length. ð Begin a new, dyadic chain. Left argument: S' (filted subsequences). Right argument: n Ḣ Take the first element of S'. Since S was sorted by length, so is S', so the first element of S' is the shortest subsequence that satisfies the condition. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~26~~ 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Åæ4&╕u◙╩►s∙Φ▬═(0~ d+Q ``` [Run and debug online!](https://staxlang.xyz/#c=%C3%85%C3%A64%26%E2%95%95u%E2%97%99%E2%95%A9%E2%96%BAs%E2%88%99%CE%A6%E2%96%AC%E2%95%90%280%7E+d%2BQ&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A&a=1&m=2) ~~Right now the online version fails for input `20` but this bug has been fixed and is yet to be deployed to the online interpreter~~ Deployed. Beware it takes some time to run the `20` case. ## Explanation Turns out that due to way pairwise difference is calculated, I don't need to worry about the equivalence of `k` and `x-k` here. Saving 5 bytes. Uses the unpacked version to explain. ``` rS{%o~{;i@c:2{E-x%mu%x<wm r [0..`x`], where `x` is input S Powerset {%o~ Sort by length {;i@ w For each element in the powerset c:2 All pairs { m Map each pair `[p,q] to E- `q-p` x% `(q-p)%x` u% Count of unique modulo differences x< Loop until the count of unique modulo differences is larger than the input(`n`) Now we have found a valid set in the powerset m Output the members of the set,one element per line. ``` By enforcing the requirement that `0` and `1` both be members of the answer, we can generate the powerset with `[2..x]` instead of `[0..x]` and then add the `0` and `1` manually to every element in the powerset. It is more efficient but need to handle the input `1` specially and costs more bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` _þ¹F%³³Ḷ¤ḟ ŒPÇÐḟḢ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//X8O@wrlGJcKzwrPhuLbCpOG4nwrFklDDh8OQ4bif4bii////MTA "Jelly – Try It Online") -1 byte thanks to Mr. Xcoder [Answer] # [Python 2](https://docs.python.org/2/), 148 bytes ``` from itertools import* def f(n): r=range(n) for i in r: for p in combinations(r,i+1): if all(any((y+x)%n in p for y in p)for x in r):return p ``` [Try it online!](https://tio.run/##RY2xDsMgDER3vsJLJWhYEqlLpH4MbaG1FGzkuFL4ehpYut3z@e5K1Q/T0loSzoAaRZm3HTAXFr2aV0yQLLnVgNwl0DueYCCxAAISyGkMKp2enB9IQZFpt@JxmnsQABOEbbOBqrV1OtyF@ncZwTqk6/IYjW6VqF85j@0/M5Znv9x6YREkBfTJoms/ "Python 2 – Try It Online") ]
[Question] [ As we saw in [this question](https://codegolf.stackexchange.com/questions/154265/hexcellent-minesweeping) complex logical statements can be expressed in terms of the simple connectives of generalized Minesweeper. However Generalized minesweeper still has redundancies. In order to avoid these redundancies we define a new game called "Generalized-1 Minesweeper". Generalized-1 Minesweeper is a version Minesweeper played on an arbitrary graph. The graph has two types of vertex, an "indicator" or a "value". A value can be either on or off (a mine or a dud) however its state is unknown to the player. An indicator tells that exactly one of the adjacent cells is on (a mine). Indicators do not count as mines themselves. For example the following board for Generalized Minesweeper tells us that cells A and B are either both mines or neither of them are mines. [![Simple game](https://i.stack.imgur.com/N62xO.png)](https://i.stack.imgur.com/N62xO.png) *(In the diagram indicators are marked in gray while values are white)* Unlike in normal minesweeper where you click values that are off to reveal indicators, there is no such mechanic in Generalized Minesweeper. A player simply determines for what states of the graph can satisfy its indicators. Your goal is to make a `2` in Generalized-1 Minesweeper. You will build a structure in Generalized-1 Minesweeper such that there are 8 specific cells for which all possible configurations of values have *exactly* two cells on. This means it behaves exactly as the `2` does in traditional minesweeper. When you write your solution you should not have specific values in mind for value cells. (In answer to H.PWiz's question it is allowed that some value cells might be deducible from the state) ## Scoring You answers will be scored by the number of vertices in the final graph minus 8 (for the 8 inputs) with a lower score being better. If two answers tie in this metric the tie breaker will be the number of edges. [Answer] ## 42 vertices, 56 edges [![Mines network](https://i.stack.imgur.com/3JB2o.jpg)](https://i.stack.imgur.com/3JB2o.jpg) Each variable is a value vertex, and each box is an indicator vertex with edges to the variables inside it. The inputs are *x1*, ..., *x8*. For example, here's a solution with mines at *x3* and *x5*, with mines highlighted in green. [![Mines network solution](https://i.stack.imgur.com/wOP0Z.jpg)](https://i.stack.imgur.com/wOP0Z.jpg) The horizontal constraints ensure that exactly one of the *a*'s and exactly one of the *b*'s has a mine. In those two columns, *r* does not hold a mine, but it does in the other six columns. (Note that *a* and *b* can't both have a mine in the same column.) Each input *x* is opposite the *r* in its column, so exactly two inputs have mines as desired. For `k` inputs, this uses `5k+2` vertices (`3k` value and `2k+2` indicator), and `7k` edges. Here, `k=8` inputs gives 42 vertices and 56 edges. [Answer] # 50 Vertices, 89 edges Based on the logic gate from H.PWiz's answer. ``` A&B C&D E&F G&H | | | | b--1--a d--1--c f--1--e h--1--g | | | | | | | | | | | | 1--?--1 1--?--1 1--?--1 1--?--1 | | | | | | | | A B C D E F G H ``` Each `*` is on when the two respective inputs are on. To handle the case of a single input, we use the intermediate values `a=A&!B` etc. Connecting all three values `a`, `b` and `A&B` to the input of a secondary level of gates gives us an effective input of `A|B` (this saves vertices over `!(!A&!B)`): ``` * * | | #--1--# #--1--# | | | | | | 1--?--1 1--?--1 ||| ||| ||| ||| A|B C|D E|F G|H ``` These `*`s are on if two of their inputs (corresponding to four of the original inputs) are on, except in the case of the pairs already covered above. Meanwhile, we can connect the `#*#` nodes to a final gate. We therefore have the following results: ``` A&B C&D E&F G&H (A|B)&(C|D) [4 cases] (E|F)&(G|H) [4 cases] (A|B|C|D)&(E|F|G|H) [16 cases] ``` These cover all 28 of the cases of two inputs. It then remains to connect a final indicator to these seven values. If fewer than two inputs are on, then none of these will be on, so the indicator will be off. If more than two inputs are on, then more than one of these will be on, and the indicator will be off. [Answer] # 197 Vertices, 308 edges I came up with this answer last night, but withheld posting it because it was such a high score. However, since it beats the [other answer](https://codegolf.stackexchange.com/a/154590/71256) by so much, I though I should post it. I use the following set up on all 28 pairs of values cells in `ABCDEFGH` ``` ?* | ?--1--? | | | 1--?--1 | | A B ``` `?` represents an value cell not in `ABCDEFGH`. Here, when `?*` is **ON**, `A` and `B` are both on. Otherwise, `A` and `B` could be in any other configuration. I connect all 28 `?*`s to one indicator cell. This means that only one pair in `ABCDEFGH` will have two **ON**. Which is sufficient to enforce that exactly two of my output cells will be **ON** [Answer] # 354 nodes, 428 edges Just to prove it's possible. I will improve this later with some caching. (hopefully no code error) I tried to write a Mathematica program [here](https://chat.stackexchange.com/transcript/message/42619492#42619492) to check program validity, but it doesn't work probably because there are too many variables. The result was generated by computer program: [Try it online!](https://tio.run/##fVRdb5swFH3Gv@JKkYpRabYk7TpV2572MmlKX/oWRcgEh1ARGxnTJeqav55dG4Mpbfd08fG5536ZWx31TorF@VzsK6k01MeakE3J6hqWMuN3JGhEU/MMvsOMBIXIig3TUtV4Xq1JwLOcu28STKAyfgx0U5X8U1nUGuQWBOogWoPecaAse4yAqbzZc6EN2muSIONbSJJCFDpJgNa83MaAfNRfSsEjTCYw4PSJlQ23aManbX54NTjBpUkXsWJrBIxje@0LmLKq4iKjXjAyrK1UcMCcercAS@LYmIOLKqQ21yM1mEDG0yYHKcqjdbME254u0iBU3MlFEfFlP2GcJLE0W6viulEmlDZiLU7MECxxwzY704Tnl48VwjCE3zLHJEtY3j9MAQHXFsMZFeNlbeV4mVhW22gadV2kbjQdwRbRN9irrMzlGt074vus7tYwLWtY@ruSrmeyoiyGtK/UOdETgws4pTHYD7TdmcFB4HzTqG/EJoYsBpyHrzL@wJKueIxp3CKPpBbhA8SJtp2ZwMP9z3toB6Z3hchr2HHF8bFsOPyCbZE35tRo2Mk/vnrqs/PPhIkMJ9zX7ahsis04pdFqvu6ZUr1DPFkmEj974uH/zAUymfnH2z6A@UUS82wUEzmnX6M1vv5CVI3G1aGQSCk6YwD4C2w1a83tOjJDoBa/QGA@Bq4tQJ3jqfecv8LN2Zo3dB9h1gouxsBt5@KUF625GWc4HyZkgEUL3IyBXvDa5eAYbPUFP/5C14cLV461c2cXzl6vnejNSPRVXlaSTMBtI0Xad6Zi88QqVQhNw@cQLiGMIZw@ykJQEoTPL/Dt6geuiHCKU9szTQ8xHCMgds@5Q7cA7LIikdF4CXvV0aLz0ZbNPuWqX/B3wyiDVXw1wwzfuNhYr1xKLqhPI0Kn8/kf "Python 3 – Try It Online") --- I use a gate that looks like this: ``` (f) | | (#) / \ / \ (d) (e) / \ / \ (#) --- (c) --- (#) .' '. .' '. (a) (b) ``` where `(#)` are 1-indicators, `(a)` .. `(f)` are values. Then, ``` c = (not a) and (not b) d = (not a) and b e = a and (not b) f = a xnor b ``` Also, this gate ``` (a) ----- (#) ----- (b) ``` gives ``` b = not a ``` . Use those two types of gates you can build any expressions. Of course, this one is for asserting that `(a)` must be true: ``` (a) ----- (#) ``` [Answer] ## 81 Nodes, 108 Edges Using 13 nodes and 14 edges, we create the following Adder gate (C(arry) = X AND Y, S(um) = X XOR Y): ``` X--1--------------? | | ?--1--S--1--?--1 | | | | C | Y--1--------------? ``` Use four Adders M1, M2, M3, M4 to add A+B, C+D, E+F, G+H, respectively, with the resulting carry C1, C2, C3, C4, and sum S1, S2, S3, S4. Use two Adders M5, M6 to add S1+S2, S3+S4, with the resulting carry C5, C6, and sum S5, S6. Use one Adder M7 to add S5+S6 to get C7 and S7. Now connect all carries to a single indicator node like the following: ``` C1-| C2-| C3-| C4-+-1 C5-| C6-| C7-| ``` and force S7 (the modulo 2 of sum of 8 values) to be 0 by this circuit: ``` S7--1--?--1 ``` I argue that this circuit forces exactly two values from `ABCDEFGH` to be ON, since it can only be an even number (since S7 is 0), and there cannot be more than 3 ON values (since only one of C1-C7 is ON). ]
[Question] [ ## Introduction You have gotten a job as the minister of finance in your made-up country in your back yard. You have decided to make your own bank in your country for you and your less trustworthy friends. Since you don't trust your friends, you have decided to write a program to validate all transactions to stop your friends from overspending your made-up currency and ruining your economy. ## Task Given the starting balance and all transactions, filter out all transactions where someone tries to overspend and block anyone who tries to overspend (this includes trying to overspend to a closed account) from ever using your bank again by filtering out future transactions to or from his/her bank account. ## Input/Output Two lists `A` and `B` as input and a list `C` as output. `A` is the starting balance of each account with the format `[["Alice", 5], ["Bob", 8], ["Charlie", 2], ...]`. `B` is a list of transactions with the format `[["Bob", "Alice", 3], ["Charlie", "Bob", 5], ...]` where `["Bob", "Alice", 3]` means that Bob wants to pay Alice 3 currency units. `C` should have the same format as `B`. `A`, `B` and `C` may be in any reasonable format. ## Test Cases ``` A: [["Alice", 5], ["Bob", 2]] B: [["Alice", "Bob", 5], ["Bob", "Alice" 7]] C: [["Alice", "Bob", 5], ["Bob", "Alice" 7]] A: [["A", 2], ["B", 3], ["C", 5]] B: [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]] C: [["C", "A", 2]] A: [["A", 2], ["B", 3]] B: [["A", "B", 2], ["A", "B", 2]] C: [["A", "B", 2]] A: [["A", 4], ["B", 0]] B: [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]] C: [["A", "B", 1]] A: [["A", 2], ["B", 3], ["C", 4]] B: [["A", "B", 3], ["C", "B", 4]] C: [["C", "B", 4]] A: [["A", 2], ["B", 3], ["C", 4]] B: [["A", "B", 3], ["B", "A", 4], ["C", "B" 2]] C: [] ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes in each language wins. [Answer] # JavaScript (ES6), ~~91~~ ~~88~~ 79 bytes *Saved 8 bytes thanks to @NahuelFouilleul* Takes input in currying syntax `(a)(b)`. ``` a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y)) ``` ### Test cases ``` let f = a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y)) console.log(JSON.stringify(f( [["Alice", 5], ["Bob", 2]] )( [["Alice", "Bob", 5], ["Bob", "Alice", 7]] ))) console.log(JSON.stringify(f( [["A", 2], ["B", 3], ["C", 5]] )( [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]] ))) console.log(JSON.stringify(f( [["A", 2], ["B", 3]] )( [["A", "B", 2], ["A", "B", 2]] ))) console.log(JSON.stringify(f( [["A", 4], ["B", 0]] )( [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]] ))) console.log(JSON.stringify(f( [["A", 2], ["B", 3], ["C", 4]] )( [["A", "B", 3], ["C", "B", 4]] ))) ``` ### Beautified and commented ``` a => b => // given the two lists a and b b.filter(([x, y, z]) => // for each (x = payer, y = payee, z = amount) in b: (a[x] += z) < 0 & // update the payer's account; if it's still valid a[y] < 0 ? // and the payee's account is also valid: a[y] -= z // update the payee's account : // else: 0, // do nothing a.map(([x, y]) => // initialization: for each (x = owner, y = amount) in a: a[x] = ~y // set up this account (>= 0: closed, -1: $0, -2: $1, etc.) ) // end of map() ) // end of filter() ``` [Answer] # Perl 5, 72 + 2 (-ap) = 74 bytes ``` %h=@F;$_=<>;s/(\S+) (\S+) (\S+)/($h{$1}-=$3)<0||($h{$2}+=$3)<$3?"":$&/ge ``` [try it online](https://tio.run/##K0gtyjH9/181w9bBzVol3tbGzrpYXyMmWFtTAYnU11DJqFYxrNW1VTHWtDGoqQHzjWq1wXwVY3slJSsVNf301P//E3Myk1MVTBWS8pMUjLggPBAbIgLhm3MlKhgpJCkYKyQrmHIlK0B4yQomQBZYF0SWC8yDiP3LLyjJzM8r/q@bWAAA) [Answer] # [Python 2](https://docs.python.org/2/), 103 bytes ``` A,B=input() C=[] for i in B: N,P,M=i if M>A[N]:A[N]=-1 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;C+=i, print C ``` [Try it online!](https://tio.run/##VYmxDoMwEEP3fIU3QBwDdKM9pJA5iD1iRb0lRAiGquq3pwmduvj52eF1PDffxahpZPHhPMpKGXaLWrcdAvEYe4WJZrIsCrLCDtpNS5@Dm/aach@a9qHd/DsatvcsdaKpWUiFXfwBE2P5LnTRoyMUY@LtQ3Blmi4ndBXhT5fqCw "Python 2 – Try It Online") -12 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). Longer due to output format restrictions: > > `C` should have the same format as `B`. > > > Otherwise I could've done this for 92 bytes: ``` A,B=input() for(N,P,M)in B: if M>A[N]:A[N]=-1 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;print(N,P,M) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->a,b{b.select{|(s,r,x)|a[r]+=x if[a[s]-=x,a[r]].min>-1}} ``` [Try it online!](https://tio.run/##pZLRaoMwFIav9SkOudrWKLWNDAYK1cc45EIlMqHrirHgUJ/dJTFm68rGoDfh5Hz//@ckpL2UH3OdzEFa0HIoQymOouqG8UHSlvaPY4Et3yQ9NDUWKHmQ9FS3ePjWnNIgmqYZfQ8HIIdjUwkCSQoxBZK9l6beTRQ8D9FiSyjEnALa2rFnzjm1aYtb6021V1W@pOtEFZgbp1p2SxQxCgrMbA/mKEN/z3SzfYn/9jLn3d54o2tv/P8x3NWYvZpz7U1Ivm7ZHSHZ@lzsOlMP5vNQFNXrMHZCdiP43vnSSaV@AQIb0E3c8rA5ybP6GivNvtHohuYLrfFJC35gf5o/AQ) Takes input `A` as a `Hash` in the format `{"A"=>2, "B"=>3}`. Input `B` and output `C` are in the suggested format. ## Explanation ``` ->a,b{ # lambda function taking arguments A and B b.select{|(s,r,x)| # select items in B that return truthy (s = sender, r = receiver, x = amount) a[s]-=x, # subtract amount from sender if [ a[r]].min>-1 # check if the smaller of the balances is non-negative # (true if both values are non-negative) a[r]+=x # if so, add to the receiver's balance } # the select function returns truthy when the above if statement passes } ``` [Answer] # C++, 193 bytes Input A as `std::map`, B as `std::list`. ``` #import<bits/stdc++.h> using s=std::string;struct p{s a,b;int c;};using t=std::list<p>;t f(std::map<s,int>A,t B){t C;for(p&i:B)(A[i.a]-=i.c)<0|A[i.b]<0?0:(C.push_back(i),A[i.b]+=i.c);return C;} ``` [Try it online!](https://tio.run/##ZVDLbsMgELz7K1ap1IBC3KiPiyGu7HxGG1WYvFAbjMz65Prb3QUf@uKyM7szu2iM9@uzMdN0Y6@@7VA1FsNdwINZrfJLmfXBujOELXWKImBHTFLpDYIfAmjRSOsQjBzlLMVZ@mEDKl9KhBNLjav2KgjSlpVAqPmAsJOntmP@1hY1Z9WLzfV@vbW54WrzGWmzV5vnTcF2ue/D5a3R5p1ZLubRKilld8S@c7RqnL7vJuS17egixJMlVLCFYVhUCwH3o4BhURN6SGhH6GkcZfbz41DPhjj840q9x0TjIPXuoz@LSVy1dYxnQwb0dI8taBdo178YWJU3x3MUC6jyozswTqjmMjkpGaBowEIRF3BIbtP2CEoBRRXLUixn1vxiJrFXt5TZmE1f "C++ (gcc) – Try It Online") ]
[Question] [ It's my friend's birthday soon and since he is a programmer and ASCII art lover, I thought I'd make him some ASCII cake! Sadly, I keep forgetting his current age, so I would like to have a program for my ASCII oven, that bakes a cake with a specified number of candles, so I don't have to do it myself again if I am wrong with his age. ASCII ovens only have limited memory and storage capacity, so it should use the *fewest bytes possible*. --- ## Your Task: Write a program that outputs a birthday cake to the console, with as many candles as the input specifies. Cake requirements are: * It has to have a border, built up of horizontal `-` and vertical `|` lines, and vertices `+`. * Atleast 5 characters wide (including cake border `|`) * Atleast 5 characters high (including cake border `-`) * There has to be a whitespace character between the cake border and the first candle-base (not the flame), on each side, except if there is a flame in that space. A flame or candle-base should not be able to overlap the cake borders. * The maximum width of the cake is 9 characters, so there is a maximum of 5 candles per row. * Since we don't want our cake to be 2-dimensional, it has to be an extra 2 rows high, to give it some volume. Add another border at the bottom and connect the vertices with the ones above them, again using the ASCII characters from above (`-`, `|` and `+`). Candle requirements are: * Consists of the base `|` and the flame `*`, with the flame stacked on top of the base. * Candles may not be directly adjacent to eachother, except diagonally. * Candles are placed left-to-right, then top-to-bottom, with 5 in one line at maximum. (Note: If there were 5 candles in the previous row, the next row can't possibly have 5 aswell, since then they would be adjacent.) **Additional notes:** * The cake width depends on the number of candles in the *first* row, but it has to be a minimum of 5 characters and a maximum of 9 characters wide. * The candles are filled starting in the top-most row, going left to right. Once one row if full the next one should start in the row below the first one. ## Input: You may accept a number in (reasonable) format you like. For this challenge you may assume that the number is between 0 and 231 (not including 0), even though I don't acknowledge someone who is this old. ## Output: You can either return a string or directly write the resulting cake into the output console. ## Rules: * Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes, in any language, wins. --- ## Examples: Input: `8` ``` +-----------+ | * * * * * | | |*|*|*| | | | | | | | | | +-----------+ | | +-----------+ ``` Input: `2` ``` +-----+ | * * | | | | | | | +-----+ | | +-----+ ``` Input: `12` ``` +-----------+ | * * * * * | | |*|*|*|*| | | *|*|*| | | | | | | | | | +-----------+ | | +-----------+ ``` --- Good luck! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~76~~ ~~71~~ ~~70 66~~ 46 bytes ``` NθF=+B⁺³⌊⟦χ⁺θθ⟧÷⁺℅ι⁺θθ⁹↘↘Fθ«↑|*¶¶¿‹⁶﹪⁺ιι⁹«M⁹←↓ ``` [Try it online!](https://tio.run/##bY5Pa8IwGMbP7ad46enNFkE3GNjhRbwU1Imw0/RQ29S@kCZt2tTB9LNnNd1hB4/Pj@dfVqYm06l0LlG17ba2OgmDDXsPC20Ao8VzxGCpv3EnbYuvHDakqLIVfs2mHDxsODTsyBiHRHUr6ikXo/vD5KRSicT@OwcxZ0P/RvcC45W@qD2dy@4h8R8aBj9hsDOkOsD4s@YQXZ8O6qCiwRFQAbgWbYtvwzedW6nHceJA45SPB758ziFei@Je/Uf83F3ewptzsxc36d2klb8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte thanks to @ASCII\_Only. Saved a massive 20 bytes by discovering a neat way of drawing the candles. Explanation: ``` NθF=+B⁺³⌊⟦χ⁺θθ⟧÷⁺℅ι⁺θθ⁹ ``` Calculate the size both of the whole cake including extra volume and just the top of the cake so that they can be drawn. ((`=` = ASCII 61) = (`+` = ASCII 43) + 9 \* 2 for the extra volume.) ``` ↘↘Fθ« ``` Move the cursor to the first row of 5 candles. Loop through each candle. ``` ↑|*¶¶ ``` Print a candle and move right two characters for the next candle. ``` ¿‹⁶﹪⁺ιι⁹« ``` However after the (zero-indexed) 4th, 8th, 13th, 17th, 22nd etc. candles (that are at the end of a row), ``` M⁹←↓ ``` move the cursor to the first candle on the next row. This works on both odd and even rows! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 67 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s9s€5Ẏa;⁶;⁶z⁶Z ç”|ṙ-ż"ç”*$U⁸RḤ’¤¦Ẏ€j@€“| “|”Zj@€⁾--Z”+®¦€0,1©¦;ṫ¥-Y ``` A monadic link taking a number and returning a list of characters or a full program printing the output. **[Try it online!](https://tio.run/##y0rNyan8/7/YsvhR0xrTh7v6Eq0fNW4D4SogjuI6vPxRw9yahztn6h7dowTmaKmEPmrcEfRwx5JHDTMPLTm0DKgJqDfLAUg8aphTowAigOqiICKN@3R1o4Bc7UPrDi0DChjoGB5aeWiZ9cOdqw8t1Y38//@/kSEA "Jelly – Try It Online")** ### How? ``` s9s€5Ẏa;⁶;⁶z⁶Z - Link 1, make some candle parts & topping: number, age; character, part s9 - split (implicit range(age)) into chunks of 9 (or remainder) s€5 - split each chunk of 9 into chunks of 5 (a 5 and a 4 or remainder) Ẏ - tighten (to a list of lists of length 5, 4, 5, 4, ..., remainder) a - logical and with the part character (either | or * here) ;⁶ - concatenate a space (we all still want topping when no candles) ;⁶ - ...and another (we also want some extra topping below the last row) z⁶ - transpose with filler space (fill the top with topping!) Z - transpose (put it back around the right way again chef) ç”|ṙ-ż"ç”*$U⁸RḤ’¤¦Ẏ€j@€“| “|”Zj@€⁾--Z”+®¦€0,1©¦;ṫ¥-Y - Main link: number, age ç”| - call last link (1) as a dyad with '|' ṙ- - rotate left by -1 $ - last two links as a monad: ç”* - call (1) as a dyad with '*' " - zip with the dyadic operation: ż - zip (interleave each) ¦ - sparse application: U - ...of: upend (reverse each) ¤ - ...to indexes: nilad+links as a nilad: ⁸ - chain's left argument, age R - range Ḥ - double (vectorises) ’ - increment Ẏ€ - tighten €ach (from '|*' or '*|' pairs) “| “|” - literal ["| ", "|"] j@€ - join (swap arguments) for €ach (add a little extra topping to the left, and add piping to the sides) Z - transpose ⁾-- - literal "--" j@€ - join (swap arguments) for €ach (add piping to the top and bottom edges) Z - transpose (time to invest in a potters wheel!) ¦ - sparse application: 0,1 - ...to indexes: [0,1] (both ends) © - (copy that to the register) € - ...of: for each: ¦ - sparse application: ”+ - ...of: '+' character ® - ...to indexes: recall from register (both ends) - - literal -1 ¥ - last two links as a dyad ṫ - tail from index (gets last two rows) ; - concatenate (repeats them underneath) Y - join with newlines - as a full program: implicit print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 94 bytes ``` /4½ c ÆYu ç +Um5-Yu)ÇV°<U?Q:Sø+(1+Yu)ç "| {Ug ç}|" Vd"|+ -" [W¡"| {X}|"ÃVVWVW]c ·y rQ+S"*|" y ``` [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=LzS9IGMgxll1IOcgK1VtNS1ZdSnHVrA8VT9ROlPDuCsoMStZdSnnCiJ8IHtVZyDnfXwiClZkInwrIC0iCltXoSJ8IHtYfXwiw1ZWV1ZXXWMgt3kgclErUyIqfCIgeQ==&inputs=OA==,Mg==,MTU=,MzU=) ]
[Question] [ # Concept Remembering numbers can be difficult. Remembering a word may be easier. In order to memorize big numbers, I created a way to pronounce them in a leetspeak-like way. # Rules Each digit is first replaced by its corresponding letter: ``` 0 => O 1 => I 2 => R 3 => E 4 => A 5 => S 6 => G 7 => T 8 => B 9 => P ``` After the replacement, two additional things are done to improved pronunciation: * Between two consonants, a `U` is added. * Between two vowels, a `N` is added. # Examples/test cases ``` 512431 => SIRANENI 834677081 => BENAGUTUTOBI 3141592 => ENINANISUPUR 1234567890 => IRENASUGUTUBUPO 6164817 => GIGABIT ``` # What's impossible * Letters and numbers mixed in the same word * Two successive consonants or two successive vowels * Letters that are not in the list above * Other characters # Rules The goal of this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") is to create a 2-way translator for this concept. * Your program must first understand by itself if it's letter-to-number or number-to-letter translation. * It must check for the entry to be properly formed. * If everything is correct, display the translation. * Else, display an error message, nothing, return a falsey value or crash the program. # Details * The input number/string can be entered in whatever format you want (stdin, argument, ...) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. * Standard loopholes are forbidden. [Answer] ## JavaScript (ES6), 130 bytes Takes input as a string in both translation ways. Returns either the translation as a string or `false` in case of an invalid input. ``` f=(n,k)=>(t=n.replace(/./g,(c,i)=>1/n?(!i|p^(p=27>>c&1)?'':'UN'[p])+s[c]:~(x=s.search(c))?x:'',p=s='OIREASGTBP'),k)?t==k&&n:f(t,n) ``` ### Demo ``` f=(n,k)=>(t=n.replace(/./g,(c,i)=>1/n?(!i|p^(p=27>>c&1)?'':'UN'[p])+s[c]:~(x=s.search(c))?x:'',p=s='OIREASGTBP'),k)?t==k&&n:f(t,n) console.log(f("512431")) // SIRANENI console.log(f("834677081")) // BENAGUTUTOBI console.log(f("3141592")) // ENINANISUPUR console.log(f("1234567890")) // IRENASUGUTUBUPO console.log(f("6164735732")) // GIGATESUTER console.log(f("SIRANENI")) // 512431 console.log(f("BENAGUTUTOBI")) // 834677081 console.log(f("ENINANISUPUR")) // 3141592 console.log(f("IRENASUGUTUBUPO")) // 1234567890 console.log(f("GIGATESUTER")) // 6164735732 console.log(f("AB23")) // false console.log(f("AEI")) // false console.log(f("ZZ")) // false ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~61~~ ~~59~~ ~~92~~ ~~85~~ 84 bytes > > I'm offline for most of the (long) weekend, if any more issues are discovered with this, please ask a mod to delete it for me until such a time as I can fix it. > > > Takes input as a string for both operations and returns a string for both as well or `false` for invalid input.Assumes number inputs will always contain multiple digits, add 1 byte replacing `UÉ` with `Un<space>` if that's not valid. Returns `false` for test case `GIGATESTER` but, according to the rules, that *should be* invalid input. --- ``` V="OIREASGTBP"UÉ?¡VgXÃe"%v"²_i1'NÃe"%V"²_i1'UÃ:!Uè"%v%v|%V%V|[^{V}NU]" ©Ur"N|U" £VaX ``` **Try it:** [Numbers -> Letters](http://ethproductions.github.io/japt/?v=1.4.5&code=Vj0iT0lSRUFTR1RCUCJVyT+hVmdYw2UiJXYisl9pMSdOw2UiJVYisl9pMSdVwzohVegiJXYldnwlViVWfFtee1Z9TlVdIiCpVXIiTnxVIiCjVmFY&input=IjMxNDE1OTIiCg==) or [Letters -> Numbers](http://ethproductions.github.io/japt/?v=1.4.5&code=Vj0iT0lSRUFTR1RCUCJVyT+hVmdYw2UiJXYisl9pMSdOw2UiJVYisl9pMSdVwzohVegiJXYldnwlViVWfFtee1Z9TlVdIiCpVXIiTnxVIiCjVmFY&input=IkVOSU5BTklTVVBVUiIK) --- * ~~2~~ 4 bytes saved thank to [obarakon](https://codegolf.stackexchange.com/users/61613/obarakon), who also convinced me to take this up again after I abandoned it earlier. I wish he hadn't! * ~~33~~ ~~26~~ 25(!) bytes sacrificed implementing a quick fix (i.e., yet to be fully golfed) to check input validity. --- ## Explanation (Yet to be updated to the latest version) ``` :Implicit input of string U. V="..." :Assign the string of letters to variable V, in order. UÉ :Subtract 1 from U, which will give a number (truthy) if the input is a number or NaN (falsey) if the input is a string. ? :If it's a number then ¡ : Map over the input string, replacing each character (digit) with ... VgX : the character in string V at index X, the current digit. à : End mapping. e : Recursively replace ... "%v"² : every occurrence of 2 vowels (RegEx) ... _i1'N : with the current match with an "N" inserted at index 1. à : End replacement. e : Another recursive replacement of ... "%V"² : every occurrence of 2 non-vowel characters (i.e., consonants) ... _i1'U : with the current match with a "U" inserted at index 1. à : End replacement. : :Else, if it's a string then Uè"%v%v|%V%V|[^{V}NU]" : Count the number of matches of 2 successive vowels OR 2 successive non-vowels OR any character not in contained in string V plus N & U. : (The longest part of this code is the fecking input validation!) ? : If that count is greater than 0 then T : Return 0. : Else Ur"N|U" : Replace every occurrence of "N" OR "U" in string U with nothing. £ : Map over the string, replacing each character (letter) with ... VaX : the index of the current character X in string V. :Implicit output of resulting string ``` [Answer] # [Python 3](https://docs.python.org/3/), 147 bytes ``` lambda c:c in"0134" def f(n): o="";a=b=1-x(n[0]) for i in n: a=x(i) if a==b:o+="UN"[a] o+="OIREASGTBP"["0123456789".index(i)];b=a print(o) ``` [Try it online!](https://tio.run/##PY07C8IwFIX3/IrLnRJEaW19tdxBQcRFxcdUOyRtgwFNSulQf31MF7dzPr7Dab/9y9nEDwRP/5YfVUuosgqMxShOUmR1o0FzKzIGjhBzSYri6cBtEZWCgXYdmGCDDQJIGrgJFIwOmVTmJoSPExayDHAs5@N1v70d7rsLFuFhnqSL5Wq9wZmxdTOOy1yRZNB2xvbcCa85/q0Ihf8B "Python 3 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~416~~ ~~410~~ ~~399~~ ~~382~~ ~~376~~ 370 bytes -2 bytes thanks to @Cyoce -17 more bytes thanks to an idea by @Cyoce -6 bytes thanks to @KevinCruijssen ``` s->{String c="[RSGTBP]",v="[OIEA]",o="([256789])",e="([0134])";boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v));int i=-1;for(s=b?s.replaceAll("[UN]",""):s.matches("[0-9]+")?s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"):i/0+"";i<9;s=b?s.replace(v,c):s.replace(c,v)){c=++i+"";v="OIREASGTBP".charAt(i)+"";}return s;} ``` [Try it online!](https://tio.run/##jZHNbuowEIXX9CmsEQtbgVwC4a9pWgUpQlk0IJKsEAvjhtbcNI5iEwkBz851Wqq2q5uV58z5PDOa2dOKdkWR5vuXv9fisM04QyyjUqJnynN0umvdklJRpZ9K8Bf0ri0cqZLnr@sNouWrJDXZ2uti5kHxzNwdcqa4yM0kp@VxUaQlVaJ8@PzziHbIRVfZfTx9JhBzYb2K5vFsuYFOpcUi8D0dChfwuj8cjSfTDYFOWsueNbC1cLZCZCnN0daV5jtV7C2VGDBrn6v2GbNzFRL85FZEx8m5qmNGiAFmmRYZZSkGBh1GvmWlGxPi8Fwh7nYtZydKLN3tk/xCvCzDsE5CPRYAuf/RdN3rTjcGkN9saoBuCoZ@9ejQtkIgP31x88WXn@iq/E/PAHD4w9T51RxXetj7b8nqYU/MNQxe83pli2Dlex8rBJO90dJTmJPau5SpOpQ5ks7l2mo5@kzRUar03RQHZRZ6/SrL8c6kRZEdMQytvj2wQG/iP@BkYI/G496kCTuwbGs47Tcgrf7A/jh3rwE8skb2xBo3IKNg5YV@GDRAZ37ozZM4iRezJrguGnphECXLZNUA10cKvSipG8yS5aLBj3kw92ZB3JCM/Sj2b4Nc7i7Xfw "Java (OpenJDK 8) – Try It Online") Ugh, java replacement is so verbose. Function which takes a string and returns the string translated from number -> letter or vice versa. Crashes on invalid input (you can see this in the tio example where it outputs the correct values for the first 10 test cases and then crashes with a divide by zero error which shows in the debug view) Ungolfed (the first and last term of the for loop are pulled out for readability) ``` s-> { String c="[RSGTBP]", v="[OIEA]", o="([256789])", e="([0134])"; boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v)); // lovely regex, explained below int i=-1; s= b? s.replaceAll("[UN]",""); // remove N's and U's :s.matches("[0-9]+")? s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"); // add N's and U's for separating vowels and consonants :i/0+""; // throw an error, looks like a sting for the ternary for(;i<9;) { c=++i+""; v="OIREASGTBP".charAt(i)+""; s=b?s.replace(v,c):s.replace(c,v); // if it started with numbers, go to letters, or vice versa } return s; } ``` The regex for matching the numbers is simple, but here is the regex for matching the letters to numbers case ``` (c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+ ( )+ every part of the word is c$ a consonant at the end of the word |v$ or a vowel at the end of the word |(c|vN)(?=v) or a consonant or a vowel + N followed by a vowel |(cU|v)(?=c) or a consonant + U or a vowel followed by a consonant with c = [RSGTBP] and v = [OIEA] ``` [Answer] # sed, 123 bytes ``` s/[0134]/_&_/g s/[25-9]/=&=/g ta y/OIREASGTBPU/0123456789N/ s/N//g q :a s/__/N/g s/==/U/g y/0123456789_/OIREASGTBP=/ s/=//g ``` ## Explanation First, we surround digits with `_` (for vowels) or `=` (for consonants). If we didn't make any substitutions, we are converting letters to digits, so it's a simple substitution, and delete `U` and `N`. Then quit. Otherwise, we branch to label `a`, where we deal with consecutive vowels and then consecutive consonants. Then transform digits to letters, and delete the marker characters we introduced in the first step. [Answer] # PHP; ~~129 127 267 259~~ 228 bytes ``` $l=IOREASGTBP;$n=1023456789;ctype_digit($s=$argn)?:$s=preg_replace("#U|N#","",strtr($o=$s,$l,$n));for($r=$c=($t=strtr($s,$n,$l))[$i++];$d=$t[$i++];)$r.=((trim($c,AEIO)xor$x=trim($d,AEIO))?X:UN[!$x]).$c=$d;echo$o?$o==$r?$s:"":$r; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/b9da13f119a920901b8b1e10ac85abad39df81ae). **breakdown** ``` $l=IOREASGTBP;$n=1023456789; # if not digits, translate letters to digits and remember original ctype_digit($s=$argn)?:$s=preg_replace("#U|N#","",strtr($o=$s,$l,$n)); # translate digits to letters: for($r=$c=($t=strtr($s,$n,$l)) # result = first letter [$i++];$d=$t[$i++];) # loop through letters $r.=((trim($c,AEIO)xor$x=trim($d,AEIO))?"":UN[!$x]) # append delimiter if needed .$c=$d; # append next letter # echo $o # if original was remembered, ?$o==$r # compare original to final result ?$s # if equal, print digits :X # else print X (as error message) :$r; # else print letters ``` [Answer] # Java 8, ~~312~~ ~~308~~ ~~304~~ ~~301~~ ~~294~~ 290 bytes ``` s->{String r="",x="([AEIOU])",y="([BGNPRST])",z="0O1I2R3E4A5S6G7T8B9P";for(int c:s.getBytes())r+=c!=78&c!=85?z.charAt((c=z.indexOf(c)+(c<58?1:-1))<0?0:c):"";return s.matches("(("+x+y+")*"+x+"?)|(("+y+x+")*"+y+"?)|\\d*")?r.replaceAll(x+"(?="+x+")","$1N").replaceAll(y+"(?="+y+")","$1U"):"";} ``` -4 bytes (308 → 304) for a bug-fix (doesn't happen often that the byte-count decreases when I fix a bug in my code.. :D) EDIT: Uses a different approach than [@PunPun1000's Java answer](https://codegolf.stackexchange.com/a/124199/52210) by first creating the return-String in a for-loop over the characters, and then uses a more abstract regex to validate it in the return-ternary (the input is either all digits, or are the given vowels and consonants alternating (so without any adjacent vowels nor consonants). **Explanation:** [Try it here.](https://tio.run/##jZRbb9owFIDf@RWu1012KREmV6BZmmwIReoCIuSll4fMGJouBJQYROj47dTJMmkPk0weLPuczyf2Z8tv8T7ubLYse1v8OtM0LgrwI06y9xYAScZZvowpA0E1BCDkeZKtAEVNp8BDET@1RFPwmCcUBCADNjgXna/vDZPbEN4ebIie3JE/iV4wvC2rkTcOprNwXo2PNuxOiN@bqSPN1UNjbM4trz@Fw@UmR2IRgA4KZcW4V3JWIIzztk2vbNP6IlpLd44KfY1zlyNE7aOSZAt2mCwRxW1E73TLIYMOwfiu63QHFA8gHOaM7/IMFMo65vRVVIQIwfahXbYhvqk60MG/q1BZ9atQWYeenxc3EDu5krNtKqy4aYoEgBy7niQ2Aq9JAPG/@bLJl3/zEazXcDoPK2vb3c9UWGvk7TfJAqyF/Mbv0wuIcWO@LDhbK5sdV7YixdMMwU71ge/JKuEF4BuQMi7OqwB1HNZH89@JmUIR1ElPUwnEEsxSNcM0u5acVIlG9H5PypGequmGafW7UtQghmYRs@YkFh6avQsNiz9CLrIQ@jM3GAW@dCneKHDH0TyaTzw5LAoGbuCH0TSaSWF/JkqHUVXci6YTKT/2x67nz6VcIC8VhZeo9bN9nIqLmWTbHb9Mq@v1VOnfxXMgZR4f5WW@jaTMKlnFUujq/tP1ZynVIRdszVCIccntZg10ap3OHw) ``` s->{ // Method with String parameter and String return-type String r="", // Result-String x="([AEIOU])",y="([BGNPRST])", // Two temp Strings for the validation-regex z="0O1I2R3E4A5S6G7T8B9P"; // And a temp-String for the mapping for(int c:s.getBytes()) // Loop over the characters of the input-String r+= // Append to the result-String: c!=78&c!=85? // If the character is not 'N' nor 'U': z.charAt( // Get the character from the temp-String `z` (c=z.indexOf(c)+ // by getting the character before or after the current character +(c<58?1:-1)) // based on whether it's a digit or not <0?0:c) // and a 0-check to prevent errors on incorrect input like '!@#' : // Else: ""; // Append nothing // End of loop (implicit / single-line body) return s.matches("(("+x+y+")*"+x+"?)|(("+y+x+")*"+y+"?)|\\d*")? // If the input is valid // (Only containing the vowels and consonants of `x` and `y`, without any adjacent ones. Or only containing digits) r // Return the result .replaceAll(x+"(?="+x+")","$1N") // after we've added 'N's if necessary .replaceAll(y+"(?="+y+")","$1U") // and 'U's if necessary :""; // Or return an Empty String if invalid } // End of method ``` --- The validation regex: ``` (([AEIOU][BGNPRST])*[AEIOU]?)|(([BGNPRST][AEIOU])*[BGNPRST]?)|\\d* ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 155 bytes ``` $v="AEIO]";$c="RSGTBP]";$,=OIREASGTBP;eval"/[^0-9$,UN]|[^$v N|N[^$v|[^$c U|U[^$c|^[NU]|[NU]\$/x||y/0-9$,UN/$,0-9/d+s/[$v\\K(?=[$v)/N/g+s/[$c\\K(?=[$c)/U/g" ``` [Try it online!](https://tio.run/##NY9Pa4NAFMTv@ymC7KGh2nX9l0iQsoLIUvoU9Z00QrEhFKSRpkgL@9m73Q3t5c38ZniHWU4fc6w1XTNHFLI6Ogc6ZU7Tll1eW3CzSjaFuPHhtL7MDutH30upi3BU/UjXDSiwamHaoEKrauwBTW/OQNmXUt/s74lR1zj2en9lPV2H4enuMTNmy4Cdb9n0n01bhuzsaB3zIAo5aWUjoABJEp5Ee74jpSxFLjsS8ojHaUBMBwJkizU2hAdhFCe7feoTMwBEiyV2mGNdkRYJVKQCsFb@XJbPt8v7VXvP8YPPfe0t8y8 "Perl 5 – Try It Online") Recognizes some invalid inputs that the other Perl entry does not. Outputs the string unchanged if it is not valid. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 76 bytes ``` .•.Ÿ^91Ý•Ul„nuSKDXSKg0QVvXyk}JYP©0Êi®}¤«SXuèŒ2ùv…U NSy0èìžMuyåOè})Jᨹd_iQ®P ``` [Try it online!](https://tio.run/##AXkAhv8wNWFiMWX//y7igKIuxbheOTHDneKAolVs4oCebnVTS0RYU0tnMFFWdlh5a31KWVDCqTDDimnCrn3CpMKrU1h1w6jFkjLDuXbigKZVIE5TeTDDqMOsxb5NdXnDpU/DqH0pSsOhwqjCuWRfaVHCrlD//1NJUkFORU5J "05AB1E – Try It Online") Returns the falsy value `0` for invalid input. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~241 238~~ 235 bytes ``` q=OIREASGTBP;[[ $1 == +([0-9]) ]]&&(x=`tr 0-9 $q<<<$1`;m={B,G,P,R,S,T};n={A,E,I,O};for i in `eval echo $m$m$n$n`;{ a=${i::1};b=${i:1:1};x=${x//$a$b/$a'U'$b};a=${i:2:1};b=${i:3:1};x=${x//$a$b/$a'N'$b};};echo $x)||tr $q 0-9<<<$1|tr -d UN ``` [Try it online!](https://tio.run/##bY5NC4JAEIb/yhyGLFqp7eNQ6x4SIrpU9HESwdUMhVyxIgTdn915W/XQJQaG5x0emDcUz0Trgu@3x/XqtDm7B@Z5gBQ4h2HfG9sLfwC@3@v1Sx68HmAOgIXjOEgDlvHKJRtyIEdyImfFJK9WZE22ZK/YLX9ACqmEIH6LO8RRkgNmZiTKgFUgOFbpckkVC1uiDZYGy9EIBYZmWRcLQ8U6c/JTp3/UXasq1v0pB3VtymLR9G3LNtG@wmWntZ7TyWxKPzK3IxEl8Rc "Bash – Try It Online") Less golfed: ``` q=OIREASGTBP; save string in q [[ $1 == +([0-9]) ]]&&( if argument 1 is only digits x=`tr 0-9 $q<<<$1`; save in x each digit translated to corresponding letter m={B,G,P,R,S,T}; n={A,E,I,O}; for i in `eval echo $m$m$n$n`;{ generates all combinations of vowels and consonants BBAA BBAE ... TTOI TTOO a=${i::1}; saves first consonant in a b=${i:1:1}; saves second consonant in b x=${x//$a$b/$a'U'$b}; insets U between consonants a=${i:2:1}; saves first vowel in a b=${i:3:1}; saves second vowel in b x=${x//$a$b/$a'N'$b}; inserts N between vowels }; echo $x echoes result )|| if argument contains letters tr $q 0-9<<<$1|tr -d UN translates letter to corresponding number and deletes U and N ``` [Answer] # PHP, 268 Bytes ``` $v=OIEA;$l=RSGTBP;$d="0134256789";$c=ctype_digit;$p=preg_replace;echo!$c($a=$argn)?$c($e=strtr($p(["#\d|[$v]{2,}|[$l]{2,}#","#[$v]\KN(?=[$v])#","#[$l]\KU(?=[$l])#"],[_,"",""],$a),$v.$l,$d))?$e:_:$p(["#[$v](?=[$v])#","#[$l](?=[$l])#"],["$0N","$0U"],strtr($a,$d,$v.$l)); ``` [Try it online!](https://tio.run/##ZY/NaoNAFIX3eYtO7kJBiuN/YoegICIFDeqsTBBRGwOSDEYCJc2z25nopnR3znfmnnuHdWz62LGOrb6uQ1vVnVSskIk1Q8dIQVmUenEQR1w6umHZtuoI7AexF9Kc5okvIh0b2NxoXPGnsRdHGd3TlFus6YZp2c5G5SZK@VRGxZxP9wknFrYMWzdtXYyGUejlQZYH6ZI42F6wH@VzWSJWotWxukE1nC7yY4I7SaLAc6EnaRbm/t6FhiAV64b2WoxcqEk9frO2bM6n8@gCI2xoT@XQsr6qW7etu@sb1BJUZO7cCdOS2ziMgwRMKtD60PwUcD8@NOXJRf8Sa37RWtDDZyztiFDywnrO6Iv1gh2VolQQj7iCSlbg/g69Ao3MV7XbcjvvEAX/ev6UIFBjHoBKuVvOq3jPXCjL7iT@gg4X5D6nXw "PHP – Try It Online") [Answer] # Perl, 127 bytes 126 bytes + 1 byte command line ``` $i="AEIOU]";$;=OIREASGTBP;1/!/[^$;NU\d]|[$i{2}|[^\d$i{2}/;eval"y/0-9$;NU/$;0-9/d";s/[$i\K(?=[$i)/N/g;s/[^N\d$i\K(?=[^\d$i)/U/g ``` Usage: ``` echo -n "512431" | perl -p entry.pl ``` Should follow all the challenge rules - can accept letters or numbers and will error (division by zero) if validation fails [Answer] # [Ruby](https://www.ruby-lang.org/), 205+1 = 206 bytes Uses the `-p` flag for +1 byte. Now with an exhaustive input validation system. ``` d,w=%w"0-9 OIREASGTBP" ~/^\d+$/?($_.tr!d,w gsub /([#{a='AEIO])(?=\g<1>)'}/,'\0N' gsub /([^#{a}/,'\0U'):(+~/^(([AEIO])(N(?=[AEIO])|(?=\g<4>)|$)|([RSGTBP])(U(?=\g<4>)|(?=\g<2>|$)))+$/;$_.tr!("NU","").tr!w,d) ``` [Try it online!](https://tio.run/##RY5PC4JAEMXvfgpbjd1FbS269EfFQMLLKtqeNCMRvIYlEllffZtS6jRvZn7v8Zq2vEtt0sBQrYuszM6Zdsi2VmoUJoGf7g@7GCkvVuSVoTOP6KfZrZkAptTXtlQZybTH2cF@EEZHSjwnr7dzl@InM3Fuc/yjCsCGo8B0TQxIJCQbbRyMo@6HjKVLex2WLPk2AEb8H4NauEBQCq02QymCuEAmQvSzdGZFpQx4yH0epiIWyRs "Ruby – Try It Online") [Answer] # Python 3, 741 bytes ``` from functools import reduce;c=0;e="";n="NU";v="AEIOU";l="OIREASGTBPNU";x=('0','O'),('1','I'),('2','R'),('3','E'),('4','A'),('5','S'),('6','G'),('7','T'),('8','B'),('9','P');s=input() try: int(s);y=reduce(lambda a,kv:a.replace(*kv),x,s) for i in y: e+=i if i in v: z=True try: if y[c+1] in v:e+="N" except: pass else: z=False try: if not y[c+1] in v:e+="U" except: pass c+=1 except: for i in s: if not i in l: p y=reduce(lambda a,kv:a.replace(*kv[::-1]),x,s) for i in y: if not i in n:e+=i print(e) ``` [Try it online!](https://tio.run/##nZLJboMwEIbvPIXlC9DQKjRdQT4QiUZcIErCKcqBEqOiELBsg0Jfng5OlV2q1Dl9s//ymLXyqypHXZfxaouyukxlVRUC5VtWcYk4XdcpdVMydCnB2C0JDmPsNgR7fhABFQRHwcz35pPFeNqndsTQh7qlR7ppGboNFCh6BJopGgH5ip6APEXPQHNFL0ATRa9AC0VvQGNF70BT3XQFyUtWS8PUJG8dDYHlpTSE6bZkr9koku3nOkGJtWmc5IFTViQQvds0prWzhKl6soqjHDrR74ze6IDkByfP9vnmmO/tmyx4Tc9CBx2nBu3tMh3Yq/0MGI1DfFZFdyll8rqTJUIcJRWCXgr4SCB4pQDdklBW8kpG/A8Z6YDY2mnl4fmEo13sU@HifCBT3t8HWjrOvb26fSZ0c1HpqKsx3n8CanadHwahFwbzeBrPfgA) There's a lot of room for improvement, I know. [Answer] ## Python3, 246 bytes ``` v=lambda x:x in"AEIO" V="OIREASGTBP" i=input() r=__import__("functools").reduce print(r(lambda x,y:x+(("U",""),("","N"))[v(x[-1])][v(y)]+y,map(lambda x:V[x],map(int,i)))if i.isdigit()else r(lambda x,y:x*10+V.index(y),filter(lambda x:x in V,i),0)) ``` explanation: * map input to a list of int * map list of int to their position in the alphabet * reduce list by adding accumulator, plus an element of a ~~dict~~tuple, plus the current element + the ~~dict~~tuple is a truth table based on two elements, being vowel or not [Answer] # JavaScript (ES6), 120 A function taking input as a string. It returns the properly translated string if the input is valid, else false or the function crashes. ``` n=>(t=n=>n.replace(/./g,d=>1/d?(v-(v=d<5&d!=2)?'':'UN'[v])+z[d]:~(a=z.search(d))?a:'',v=2,z='OIREASGTBP'))(q=t(n))==n&&q ``` *Less golfed* ``` n => { var t = n => { // function to translate, no check for invalid input var v = 2; // 1 = digit map to vowel, 0 = digit map to consonant, start with 2 var z = 'OIREASGTBP'; // digits mapping return n.replace(/./g, d => 1/d // digit / alpha check ? ( // if digit w = v, // save previous value of v v = d < 5 & d != 2, // check if current digit will map to wovel or consonant (w != v ? '' // if different - wovel+consonant or consonant+wovel or start of input : 'UN'[v] // if equal, insert required separator ) + z[d] // add digit translation ) : ( // if alpha a = z.search(d), // look for original digit. Could crash if d is a reserved regexp char (not valid input) a != -1 ? a : '' // if digit found add to output, else do nothing ) ) } var q = t(n); // translate input an put in q if (t(q) == n) // translate again, result must be == to original input return q; // if ok return result else return false; // else return false } ``` **Test** ``` var F= n=>(t=n=>n.replace(/./g,d=>1/d?(v-(v=d<5&d!=2)?'':'UN'[v])+z[d]:~(a=z.search(d))?a:'',v=2,z='OIREASGTBP'))(q=t(n))==n&&q ;`512431 => SIRANENI 834677081 => BENAGUTUTOBI 3141592 => ENINANISUPUR 1234567890 => IRENASUGUTUBUPO 6164817 => GIGABIT` .split('\n') .forEach(x => { var [a,b] = x.match(/\w+/g) var ta = F(a) var tb = F(b) console.log(a==tb ? 'OK':'KO', a + ' => '+ ta) console.log(b==ta ? 'OK':'KO', b + ' => '+ tb) }) function go() { O.textContent = F(I.value) } go() ``` ``` <input id=I value='NUNS' oninput='go()'> <pre id=O></pre> ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 71 bytes ``` ' '~⍨,({' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪)'OIREASGTBP'[⍎¨⍕⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@qyuo1z3qXaGjUQ1k6RhVP@pYrl8BlFZ3dPX0D1V/1NEFlH3Uu@tR71YrdT/1R90tIBV1FVbqoSAOUFOtPlCuVudR7ypNdX/PIFfHYPcQpwD16Ee9fYeAOqcCLYz9D7TrfxqXqaGRibEhVxqXhbGJmbm5gQWIbWxoYmhqaQRkGRoZm5iamVtYGgA5ZoZmJhaG5gA "APL (Dyalog Unicode) – Try It Online") This turned out surprisingly short! Uses `⎕IO←0` (0-indexing). ## Explanation ``` ' '~⍨,({' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪)'OIREASGTBP'[⍎¨⍕⎕] ⍎¨⍕⎕ get the digits of the input 'OIREASGTBP'[ ] map to the correct letters {' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪ join the following with the tabled argument: /⍵ map pairs of the argument to: 2 ∧/x←'AEIOU'∊⍨⍺⍵:'N' N if vowel pair, ⋄∧/~x:'U' U if consonant pair, ⋄' ' space otheriwse. ' ', prepend a space , flatten the result ' '~⍨ remove all spaces ``` ]
[Question] [ This dear StackExchange site has so many challenges, and so many good answers. But what about the challenges that were [never answered](https://codegolf.stackexchange.com/unanswered)? ## Task Write a program or a function that will print a pseudo-random open unanswered (as in, a question with exactly zero answers) challenge from PPCG. All possible challenges should be produced with the same probability. ## Input * No input will be taken. ## Output * Must only be the title, tags and the link which should be separated by newlines. + The title must be exactly like it is in the challenge. + The tags don't have a strict output format but must include all tags. + The link may or may not include the `question-name` after the question id and must lead to the challenge. * May or may not be translated to a human readable format. + `&amp;` to `&` * Leading and trailing whitespace is allowed. ## Examples ``` Encode a steganographic encoder into a package code-challenge,unicode,steganography https://codegolf.stackexchange.com/questions/65159/encode-a-steganographic-encoder-into-a-package Simple predictive keyboard CG code-golf https://codegolf.stackexchange.com/questions/76196/simple-predictive-keyboard-cg ``` ## Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. [Answer] # JavaScript + HTML, ~~271~~ ~~250~~ 232 bytes *Apparantly you can use `Date`s as pseudo-random numbers. I stole this from [Shaggy's answer](https://codegolf.stackexchange.com/a/120196/48878).* (Only uses about 4 of your quota) ``` q=[] g=f=>fetch('//api.stackexchange.com/questions/unanswered?site=codegolf&page='+f).then(r=>r.json().then(j=>(q=[...q,...j.items])^j.has_more?g(f+1):document.write(`<pre>${(q=q[new Date%q.length]).title} ${q.tags} `+q.link))) g(1) ``` It makes an array `q`, then calls `g(1)`, which fetches the first page of results and adds it to q. Then, if the request says it `has_more`, then it calls `g(f+1)`, which fetches the next page, until it reaches the end and writes out to the HTML document (Which will automatically unescape the response) If we don't care about *all* of the unanswered questions, just the most recent 30 (Only uses 1 of your quota): ## JavaScript + HTML, ~~213~~ ~~196~~ 179 bytes ``` fetch`//api.stackexchange.com/questions/unanswered?site=codegolf`.then(r=>r.json().then(j=>document.write(`<pre>${(j=j.items[new Date%j.items.length]).title} ${j.tags} `+j.link))) ``` [Answer] # Python + requests + json + random + html, ~~249~~ 239 bytes ``` import requests as r,json,random as R,html j=R.choice(json.loads(r.get('http://api.stackexchange.com/questions/no-answers?site=codegolf').text)['items']) print('\n'.join([html.unescape(j['title']),'Tags: '+', '.join(j['tags']),j['link']])) ``` Turned out longer than I'd like. -10 bytes thanks to @totallyhuman by using `R.choice` rather than `R.shuffle` and taking the first element. [Answer] # Bash 255 232 bytes ``` a="api.stackexchange.com/questions/";b="?site=codegolf";c=$(w3m $a"unanswered"$b"&filter=total"|tr -cd 0-9);w3m $a"no-answers"$b"&pagesize=1&page="$((RANDOM%c))|jq -r ".items[0]|.title,(.tags|join(\", \")),.link"|recode html..utf-8 ``` Looks like a wrong results returns for totals for no-answers/unanswered. General idea - get total, than get random page with one item. # Bash 174 153 bytes ``` w3m api.stackexchange.com/questions/no-answers?site=codegolf|jq -r ".items[$RANDOM%(.items|length)]|.title,(.tags|join(\", \")),.link"|recode html..utf-8 ``` It select one random question from last 30, not from all questions. Works from command line. Required curl w3m, jq and recode. result: ``` Tips for golfing in Charcoal code-golf, tips https://codegolf.stackexchange.com/questions/117269/tips-for-golfing-in-charcoal ``` ]
[Question] [ An Armstrong number (AKA Plus Perfect number, or narcissistic number) is a number which is equal to its sum of `n`-th power of the digits, where `n` is the number of digits of the number. For example, `153` has `3` digits, and `153 = 1^3 + 5^3 + 3^3`, so `153` is an Armstrong number. For example, `8208` has `4` digits, and `8208 = 8^4 + 2^4 + 0^4 + 8^4`, so `8208` is an Armstrong number. [On 14th Nov 2013](https://codegolf.stackexchange.com/questions/15244/test-a-number-for-narcissism), we tested if a number is an Armstrong number. Now, we would like to list all Armstrong numbers. There are exactly `88` Armstrong numbers: ``` 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 24678050 24678051 88593477 146511208 472335975 534494836 912985153 4679307774 32164049650 32164049651 40028394225 42678290603 44708635679 49388550606 82693916578 94204591914 28116440335967 4338281769391370 4338281769391371 21897142587612075 35641594208964132 35875699062250035 1517841543307505039 3289582984443187032 4498128791164624869 4929273885928088826 63105425988599693916 128468643043731391252 449177399146038697307 21887696841122916288858 27879694893054074471405 27907865009977052567814 28361281321319229463398 35452590104031691935943 174088005938065293023722 188451485447897896036875 239313664430041569350093 1550475334214501539088894 1553242162893771850669378 3706907995955475988644380 3706907995955475988644381 4422095118095899619457938 121204998563613372405438066 121270696006801314328439376 128851796696487777842012787 174650464499531377631639254 177265453171792792366489765 14607640612971980372614873089 19008174136254279995012734740 19008174136254279995012734741 23866716435523975980390369295 1145037275765491025924292050346 1927890457142960697580636236639 2309092682616190307509695338915 17333509997782249308725103962772 186709961001538790100634132976990 186709961001538790100634132976991 1122763285329372541592822900204593 12639369517103790328947807201478392 12679937780272278566303885594196922 1219167219625434121569735803609966019 12815792078366059955099770545296129367 115132219018763992565095597973971522400 115132219018763992565095597973971522401 ``` Your task is to output exactly the list above. # Flexibility The separator **does not have to be** be a line-break, but the separator must not contain any digit. A trailing separator at the end of the output is optional. Also, your code must terminate ~~before the heat death of the universe~~ in a reasonable amount of time (say, less than a **day**). You **may** hard-code the result or any part thereof. # References * [Obligatory OEIS A005188](https://oeis.org/A005188) [Answer] # CJam, ~~626~~ ~~397~~ ~~325~~ ~~218~~ ~~168~~ ~~134~~ ~~93~~ ~~55~~ ~~54~~ 53 bytes ``` 8A#{[_8b3394241224Ab?A0e[A,]ze~__,f#:+s_$@s=*~}%$1>N* ``` Execution takes roughly four and a half hours on my machine. One Armstrong number is hardcoded, the remaining ones are computed. Computing all Armstrong numbers is theoretically possible in 24 hours, but the approach ``` 9A#{_9b8 9erA0e[A,]ze~__,f#:+s_$@s=*~}%$1>N* ``` drives the garbage collector nuts. So far, all settings I've tried resulting either in a GC error message or too much memory consumption. ### How it works ``` 8A# e# Compute 8¹⁰ = 1,073,741,824. { e# Map the following block over all I in [0 ... 1,073,741,824]. [ e# Begin an array. _8b e# Copy I and convert the copy to base 8. 3394241224Ab e# Push [3 3 9 4 2 4 1 2 2 4], the representation of the e# Armstrong number 1122763285329372541592822900204593. ? e# If I is non-zero, select the array of base 8 digits. e# Otherwise, select the hardcoded representation. A0e[ e# Left-pad the digit array with 0's to length 10. A, e# Push [0 1 2 3 4 5 6 7 8 9]. ] e# End the array. ze~ e# Transpose and perform run-length decoding, repeating the e# digit n k times, where k in the n-th entry of the repr. e# This is a potential Armstrong number, with sorted digits. _ e# Push a copy. _, e# Compute the length of yet another copy. f# e# Elevate all digits to that power. :+s e# Add the results and cast to string. _$ e# Push a sorted copy. @s e# Stringify the sorted digits. =* e# Compare for equality and repeat the string that many times. e# This pushes either the representation of an Armstong number e# or an empty string. ~ e# Evaluate, pushing the number or doing nothing. }% e# $1> e# Sort and remove the lowest number (0). N* e# Join, separating by linefeeds. ``` [Answer] # Pyth, 330 bytes ``` 0000000: 6a 6d 73 2e 65 2a 73 62 5e 6b 73 73 4d 64 64 63 jms.e*sb^kssMddc 0000010: 2e 5a 22 78 da ad 50 51 76 03 30 08 ba 52 04 4d .Z"x..PQv.0..R.M 0000020: de ee 7f b1 81 26 dd f6 bf f6 35 35 28 08 59 b1 .....&....55(.Y. 0000030: 3e 9f 7f 2e e7 3b 68 ac f7 8b 3f c0 c5 e2 57 73 >....;h...?...Ws 0000040: 2d bc f3 02 e8 89 8b a3 eb be cf a1 ae 3b 33 84 -............;3. 0000050: 01 66 1a 23 d7 40 8c 06 d0 eb e6 fa aa 96 12 17 .f.#.@.......... 0000060: 11 bc f8 d0 e0 6d 96 e2 d0 f1 b3 41 c7 8a 74 19 .....m.....A..t. 0000070: 3d b8 fc 77 2b 2c ce 88 05 86 d6 9e d5 f5 4c 37 =..w+,........L7 0000080: b0 9e ab 46 75 a1 37 f1 5d 5b 36 dd 86 e5 6e 15 ...Fu.7.][6...n. 0000090: a4 09 b4 0c 40 a7 01 1d 2a 8d a8 49 e4 ac 23 1d ....@...*..I..#. 00000a0: 25 c5 55 53 02 be 66 c7 dd bd c3 4a 28 9d 39 57 %.US..f....J(.9W 00000b0: 6f 11 92 ca 94 8a a5 87 38 4e 1d 25 17 60 3a 2d o.......8N.%.`:- 00000c0: 51 5a 96 55 7e 04 7a 41 aa b1 84 c4 88 10 fd 28 QZ.U~.zA.......( 00000d0: 04 37 64 68 ab 58 1e 0c 66 99 de a6 4c 34 2e 51 .7dh.X..f...L4.Q 00000e0: 19 96 fc a7 ea 01 6d de b4 2b 59 01 52 1b 1c 6e ......m..+Y.R..n 00000f0: 92 eb 38 5c 22 68 6f 69 60 e9 ab 17 60 6e e9 6b ..8\"hoi`...`n.k 0000100: 44 d6 52 44 33 fd 72 c9 7a 95 28 b2 a8 91 12 88 D.RD3.r.z.(..... 0000110: 74 0a 7b 10 59 16 ab 44 5a 4e d8 17 e5 d8 a8 a3 t.{.Y..DZN...... 0000120: 97 09 27 d9 7b bf 8a fc ca 6b 2a a5 11 28 89 09 ..'.{....k*..(.. 0000130: 76 3a 19 3a 93 3b b6 2d eb 2c 9c dc 45 a9 65 1c v:.:.;.-.,..E.e. 0000140: f9 be d5 37 27 6e aa cf 22 54 ...7'n.."T ``` Encodes the count of the number of 0-9 in each number. [Try it online!](http://pyth.herokuapp.com/?code=jms.e%2asb%5EkssMddc.Z%22x%C3%9A%C2%ADPQv%030%08%C2%BAR%04M%C3%9E%C3%AE%7F%C2%B1%C2%81%26%C3%9D%C3%B6%C2%BF%C3%B655%28%08Y%C2%B1%3E%C2%9F%7F.%C3%A7%3Bh%C2%AC%C3%B7%C2%8B%3F%C3%80%C3%85%C3%A2Ws-%C2%BC%C3%B3%02%C3%A8%C2%89%C2%8B%C2%A3%C3%AB%C2%BE%C3%8F%C2%A1%C2%AE%3B3%C2%84%01f%1A%23%C3%97%40%C2%8C%06%C3%90%C3%AB%C3%A6%C3%BA%C2%AA%C2%96%12%17%11%C2%BC%C3%B8%C3%90%C3%A0m%C2%96%C3%A2%C3%90%C3%B1%C2%B3A%C3%87%C2%8At%19%3D%C2%B8%C3%BCw%2B%2C%C3%8E%C2%88%05%C2%86%C3%96%C2%9E%C3%95%C3%B5L7%C2%B0%C2%9E%C2%ABFu%C2%A17%C3%B1%5D%5B6%C3%9D%C2%86%C3%A5n%15%C2%A4%09%C2%B4%0C%40%C2%A7%01%1D%2a%C2%8D%C2%A8I%C3%A4%C2%AC%23%1D%25%C3%85US%02%C2%BEf%C3%87%C3%9D%C2%BD%C3%83J%28%C2%9D9Wo%11%C2%92%C3%8A%C2%94%C2%8A%C2%A5%C2%878N%1D%25%17%60%3A-QZ%C2%96U%7E%04zA%C2%AA%C2%B1%C2%84%C3%84%C2%88%10%C3%BD%28%047dh%C2%ABX%1E%0Cf%C2%99%C3%9E%C2%A6L4.Q%19%C2%96%C3%BC%C2%A7%C3%AA%01m%C3%9E%C2%B4%2BY%01R%1B%1Cn%C2%92%C3%AB8%5C%22hoi%60%C3%A9%C2%AB%17%60n%C3%A9kD%C3%96RD3%C3%BDr%C3%89z%C2%95%28%C2%B2%C2%A8%C2%91%12%C2%88t%0A%7B%10Y%16%C2%ABDZN%C3%98%17%C3%A5%C3%98%C2%A8%C2%A3%C2%97%09%27%C3%99%7B%C2%BF%C2%8A%C3%BC%C3%8Ak%2a%C2%A5%11%28%C2%89%09v%3A%19%3A%C2%93%3B%C2%B6-%C3%AB%2C%C2%9C%C3%9CE%C2%A9e%1C%C3%B9%C2%BE%C3%957%27n%C2%AA%C3%8F%22T&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), ~~358~~ 204 bytes -6 bytes thanks to @JonathanFrech ``` from itertools import* R=range S=sorted A=[] for i in R(40): B=(i>31)*10 for c in combinations_with_replacement(R(10),i-B):t=sum(d**i for d in c);A+=[t]*(S(map(int,str(t)))==S(S(c)+R(B))) print S(A)[1:] ``` In my computer, it ran in 11 and a half hours. ## How it works? Only one thing is hardcoded, the fact that from 32 digits onwards, all armstrong numbers have the digits 0 to 9. This is handled by the uses of the variable `B` in the code. It's speed goes down significantly as the number of combinations reduces a lot. ]
[Question] [ **This question already has answers here**: [Print element from the periodic table [duplicate]](/questions/11816/print-element-from-the-periodic-table) (3 answers) Closed 8 years ago. # Background You are sitting in chemistry class and your friend keep sending you these strange letters. It is your job to decrypt the messages into words. *This is the inverse of [this challenge.](https://codegolf.stackexchange.com/q/64858/8478)* [![enter image description here](https://i.stack.imgur.com/tJdRP.png)](https://i.stack.imgur.com/tJdRP.png) # The Challenge **Input**: A list or a string of integers from 1 to 118. **Output**: The words for each chemical element if possible. Otherwise return False, throw an error, or blank. Note in your program 0 must return a whitespace or newline. Ignore all integers not in range. **Test cases** Input 1: ``` 9 53 75 ``` Output 1: ``` fire ``` Input 2: ``` 91 120 91 ``` Output 2: ``` papa ``` Input 3: ``` 9 53 75 0 53 16 0 9 92 7 ``` Output 3: ``` fire is fun ``` **Note**: Again no built in functions for generating the periodic system or external libaries. Standard loopholes are not allowed. # Scoring Submissions will be scored in **bytes**. I recommend [this website](http://bytesizematters.com) to keep track of your byte count, though you can use any counter you like. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score wins! [Answer] # Pyth, 264 bytes ``` s@L+" "-R0+c"h0helibeb0c0n0o0f0nenamgalsip0s0clark0casctiv0crmnfeconicuzngageassebrkrrbsry0zrnbmotcrurhpdagcdinsnsbtei0xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw0reosirptauhgtlpbbipoatrnfrraacthpau0nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcn"2c"uutfl0uuplv0uusuuo"3rz7 ``` [Answer] # [Par](http://ypnypn.github.io/Par/), 261 bytes ``` ` 0h0helibeb0c0n0o0f0nenamgalsip0s0clark0casctiv0crmnfeconicuzngageassebrkrrbsry0zrnbmotcrurhpdagcdinsnsbtei0xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw0reosirptauhgtlpbbipoatrnfrraacthpau0nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcn`2%`uutfl0uuplv0uusuuo`3%+l✶´gΣ'0- ``` One byte is used per character, even `Σ`, since a specialized encoding is used. See [here](https://github.com/Ypnypn/Par/blob/gh-pages/README.md#the-encoding). Input is Lisp-style, e.g. `(9 53 75 0 53 16 0 9 92 7)` ``` ` 0h0hel...n` ## Elements until Uut 2% ## Split into pieces of size 2 `uutfl0u...o` ## Elements from Uut 3% ## Split into pieces of size 3 + ## Combine into list of elements l✶ ## Read array of numbers ´g ## Find the element at each index Σ ## Concatenate '0- ## Remove all 0's ``` [Answer] # Python 2.x, 295 bytes Golfed code: ``` import re;print''.join([re.findall('[A-Z ][a-z]*',' HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo')[e]for e in i]) ``` NB: to shave 8 bytes, output for this version is in mixed caps (doesn't break any rules), missing the `.lower()` ending --- # ~~387 bytes~~ Golfed code: ``` print''.join([' ,h,he,li,be,b,c,n,o,f,ne,na,mg,al,si,p,s,cl,ar,k,ca,sc,ti,v,cr,mn,fe,co,ni,cu,zn,ga,ge,as,se,br,kr,rb,sr,y,zr,nb,mo,tc,ru,rh,pd,ag,cd,in,sn,sb,te,i,xe,cs,ba,la,ce,pr,nd,pm,sm,eu,gd,tb,dy,ho,er,tm,yb,lu,hf,ta,w,re,os,ir,pt,au,hg,tl,pb,bi,po,at,rn,fr,ra,ac,th,pa,u,np,pu,am,cm,bk,cf,es,fm,md,no,lr,rf,db,sg,bh,hs,mt,ds,rg,cn,uut,fl,uup,lv,uus,uuo'.split(',')[e]for e in i]) ``` --- > > Input: **A list** or a string **of integers** from 1 to 118. > > > Usage: `i=[9,53,75,0,53,16,0,9,92,7]` > > Output: The words for each chemical element if possible. Otherwise return False, **throw an error**, or blank. Note in your program 0 must return a whitespace or newline. Ignore all integers not in range. > > > PS: used 2.x for the `print` statement without parenthesis [Answer] # JavaScript (ES6), ~~347~~ 279 bytes ``` l=>l.map(n=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".match(/[ A-Z][a-z]*/g)[n]||"").join`` ``` ## Explanation Uses [@CSᵠ](https://codegolf.stackexchange.com/users/7635/cs%E1%B5%A0)'s idea of seperating the element names by capital letters. Converting the output to all upper or lower case would add 14 bytes. ``` l=> l.map(n=> // iterate through each number " HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo" .match(/[ A-Z][a-z]*/g) // split the elements by the first letter being upper-case [n] // add the element name to the output ||"" // add nothing if the number was out of range ).join`` // return the output as a string ``` ## Test ``` <input type="text" id="input" value="9 53 75 0 53 16 0 9 92 7" /><button onclick='result.innerHTML=( l=>l.map(n=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".match(/[ A-Z][a-z]*/g)[n]||"").join`` )(input.value.split(" "))'>Go</button><pre id="result"></pre> ``` [Answer] # ES6, 396 bytes A very trivial approach: ``` var C=c=>c.map(a=>(" .h.he.li.be.b.c.n.o.f.ne.na.mg.al.si.p.s.cl.ar.k.ca.sc.ti.v.cr.mn.fe.co.ni.cu.zn.ga.ge.as.se.br.kr.rb.sr.y.zr.nb.mo.tc.ru.rh.pd.ag.cd.in.sn.sb.te.i.xe.cs.ba.la.ce.pr.nd.pm.sm.eu.gd.tb.dy.ho.er.tm.yb.lu.hf.ta.w.re.os.ir.pt.au.hg.tl.pb.bi.po.at.rn.fr.ra.ac.th.pa.u.np.pu.am.cm.bk.cf.es.fm.md.no.lr.rf.db.sg.bh.hs.mt.ds.rg.cn.uut.fl.uup.lv.uus.uuo").split(".")[a]||"").join(""); ``` [Test it](http://jsfiddle.net/aLfkdpqq/) [Answer] # Java, 470 bytes ``` interface B{static void main(String[]a){for(int i=0;i<a.length;i++)System.out.print(" ,h,he,li,be,b,c,n,o,f,ne,na,mg,al,si,p,s,cl,ar,k,ca,sc,ti,v,cr,mn,fe,co,ni,cu,zn,ga,ge,as,se,br,kr,rb,sr,y,zr,nb,mo,tc,ru,rh,pd,ag,cd,in,sn,sb,te,i,xe,cs,ba,la,ce,pr,nd,pm,sm,eu,gd,tb,dy,ho,er,tm,yb,lu,hf,ta,w,re,os,ir,pt,au,hg,tl,pb,bi,po,at,rn,fr,ra,ac,th,pa,u,np,pu,am,cm,bk,cf,es,fm,md,no,lr,rf,db,sg,bh,hs,mt,ds,rg,cn,uut,fl,uup,lv,uus,uuo".split(",")[Integer.parseInt(a[i])]);}} ``` Accepts input as command line arguments. Uses an interface declaration to shorten class/main declaration. It will *definitely* error for invalid input. Because Java. [Answer] # Ruby, 282 ``` ->a{a.each{|n|" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".bytes{|j|n-=1-j/96;n==-1&&$><<j.chr}}} ``` **Ungolfed in test program** Each number in turn is assigned to `n`. We run through the magic string bytewise, decreasing `n` unless the ASCII code is more than 96. When `n` is -1 we print a byte from the magic string. As `n` remains the same until all characters for that element are printed, all characters for that element are printed. Out of range numbers are simply ignored. ``` f=->a{ a.each{|n| " HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo". bytes{|j|n-=1-j/96;n==-1&&print(j.chr)} } } f[[59,8,24,95,49,0,15,92,40,99,0,95,60,0,27,4,0,27,53,9]] ``` **Output** ``` PrOCrAmIn PUZrEs AmNd CoBe CoIF ``` Mixed case. All lowercase would cost an extra 9. All uppercase would cost an extra 7. [Answer] # JavaScript, ~~275~~ ~~273~~ 272 bytes ``` a=>a.map(b=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKaCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".split(/(?=[A-Z])/)[b]).join`` ``` You can try it here : [JSFiddle](https://jsfiddle.net/c93z34go/3/) ]
[Question] [ Most of us LOST fans out there remember the computer that Desmond had to type the characters "4 8 15 16 23 42" in every 108 minutes or the world would end (or would it?). The challenge here is to create a program that would do the same thing by requiring that every 108 seconds the input `4 8 15 16 23 42` is entered or it will display the message ``` Sorry, the world has ended with status code -1 ``` It should warn the user at 100 seconds that they need to enter a number with the message ``` Enter, Quick! ``` The program must be able to read input at any time and if it is the correct input it will reset the timer. If incorrect input is given nothing happens. The program should run indefinitely. So the timeline after the last valid input looks like From 0 to 99 seconds: no output At 100 seconds: `Enter, Quick!` At 108 seconds: `Sorry, the world has ended with status code -1`. This is code golf so the shortest answer (in bytes) that accomplishes this task wins! Good Luck! [Answer] # bash, 160 bytes ``` I()($s 100&&echo Enter, Quick!&$s 108&&echo Sorry, the world has ended with status code -1&) i()(read r;[[ $r = '4 8 15 16 23 42' ]]&&pkill $s&&I;i) s=sleep;I;i ``` I'm currently uncertain what the expected behavior is after "the world has ended". Run like this: ``` bash lost.sh 2>&- ``` `2>&-` is required to ignore STDERR, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/4781). [Answer] ## Modern-browser JavaScript, ~~252~~ ~~247~~ 242 bytes ``` n=t=>Date.now()+(t?0:1e5) d=n(i=f=0) onkeyup=e=>{if("4 8 15 16 23 42".charCodeAt(i%15)==e.keyCode&&++i%15<1)d=n(f=0)} setInterval('if(n(1)>d&&f<2)d=n(1)+8e3,console.log(f++?"Sorry, the world has ended with status code -1":"Enter, Quick!")',9) ``` Instructions: run this in the console of a blank tab, click on its document to gain focus and start repeatedly typing the string. As long as you're doing well, you'll get no feedback whatsoever. Refresh and change 1e5 to 1e4 to make things more interesting. [Answer] # Groovy, 244 or 228 bytes I wrongly remembered Java having a nextLine method that took an argument of how long to wait, so I thought this would be easy. I couldn't find a method that did that, so I implemented this with two threads. It's a bit bulky. Oh well. ``` t=Thread.start{while(1)try{Thread.sleep(1e5);println "Enter, Quick!";Thread.sleep(8e3);println "Sorry, the world has ended with status code -1";System.exit(-1)}catch(e){}};while(1)if(System.console().readLine()=="4 8 15 16 23 42")t.interrupt() ``` This assumes the proper behavior for the world ending is for the process to exit with a status code of -1. If the intended behavior is to keep looping and expect an external force to end the world (and by extension, the program), the `;System.exit(-1)` portion can be omitted to save 16 bytes. Yay. I originally wrote this to use the hashCode of the string, but that wound up *longer* than an exact comparison embedding the string because `hashCode` is long. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 144 [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") As it turns out, [both sides](https://codegolf.stackexchange.com/a/69694/43319) are running APL… ``` :For t:In 100 8 :For s:In⍳t →{1E3::⍬⋄⍳⍞≡⍕4 8 15 16 23 42}⎕RTL←1 :End ⊃'Enter, Quick!' 'Sorry, the world has ended with status code -1'⌽⍨t=8 :End ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@VW36RQomVZ56CoYGBggUXmJ8J5D/q3VzC9ahtUrWhq7GV1aPeNY@6W4Bij3rnPepc@Kh3qomChYKhqYKhmYKRsYKJUe2jvqlBIT6P2iYYclm55qVwPepqVnfNK0kt0lEILM1MzlZUV1APzi8qqtRRKMlIVSjPL8pJUchILFZIzUtJTVEozyzJUCguSSwpLVZIzk9JVdA1VH/Us/dR74oSW2OwiSD3/lcAgwIA "APL (Dyalog Unicode) – Try It Online") `:For t:in 100 8` loop twice, once with `t`(timput) being `100` and then with `t` as `8`:  `:For s:In⍳t` for `s`(econds) `1` through and all the **ɩ**ndices until `t`   `⎕RTL←1` set the **R**esponse **T**ime **L**imit to 1 (second)   `{`…`}` apply the following anonymous lambda to that (although this argument is unused)    `1E3::` in the following, if any exception happens:     `⍬` return `[]`    `⋄` try:     `⍕4 8 15 16 23 42` stringify the required numbers     `⍞≡` prompt for input and compare to that (gives 0 or 1)     `⍳` the first that many **ɩ**ndices (`[]` or [1]`   `→` go to that line (1 if `[1]`, continue on next line if `[]`)  `:End` end of inner loop; proceed with next second of the current timeout  `t=3` is this the second timeout (0 or 1)?  …`⌽⍨` rotate the following that many steps:   `'Enter, Quick!' 'Sorry, the world has ended with status code -1'` implicitly print appropriate text  `⊃` disclose (to print without leading and trailing space) `:End` end of outer loop: after warning, loop; after printing "Sorry…", proceed to terminate program [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 395 bytes Compiling on Linux requires the `-pthread` switch. MinGW does without. ``` #import<iostream> #import<thread> using namespace std;auto N=chrono::steady_clock::now;auto L=N();int w;int main(){thread A([]{for(;;){auto t=chrono::duration_cast<chrono::seconds>(N()-L).count();t>99&&!w?puts("Enter, Quick!"),w=1:t>107?exit(puts("Sorry, the world has ended with status code -1")),0:0;}}),B([]{for(string s;;s=="4 8 15 16 23 42"?L=N(),w=0:0)getline(cin,s);});A.join();B.join();} ``` [Try it online!](https://tio.run/##PVBda8JAEHzvr1hTkBwkYqz9MGciCn0TofSxFDkuZ3I1uQt3G1KR/PWmp0Fflt1ldmZneF2HOed9/yirWhtcSm3RCFalD7cNFm7O0ofGSpWDYpWwNeMCLGaUNahhl/DCaKXj2KJDnva81PwYx0q3A2Cb7HxCpUJor7ViUvnkPBDD2v/6Ph@08Skl5yse74RZYxhKrfacWVzeZQTXKrOp72jDLZlw3Sh0CpguFuPxqF3VDVrfe1coTAAfjeTHkUeCNoliTKPp60r8SvQH0Kc25hQAFgJabcoMCmZBqExk0EosnEuGjQWuMwFh5BESTOMp7ToSbG5/u8AuyVhKbZJ4c3iD6BmiF5g9wXzmra7unbi7I7nAUirhc6kCS2hH6Hryoy9p0M2t6fr@jx9Klts@rIeM/gE "C++ (gcc) – Try It Online") ]
[Question] [ Just about every store nowadays uses [Universal Product Code](https://en.wikipedia.org/wiki/Universal_Product_Code) (UPC) barcodes to simplify the checking out process. If the name doesn't mean anything to you, you will surely recognize what they look like: ![Sample UPC-A barcode](https://i.stack.imgur.com/Mwqut.png) ## Format The most common system is UPC-A, which uses 12 digits to represent each specific product. Each digit is encoded into a series of black and white stripes to allow machines to read the code, a length of seven bits. There are a total of 11 bits worth of patterns that indicate the beginning, middle, and end of the barcode. This comes to a total barcode length of 12 × 7 + 11 = 95 bits. (From now on, when binary is used to refer to the color of each bit, `0` is white and `1` is black.) The beginning and end both have a pattern of `101`. The digits are then divided into 2 groups of 6 and encoded as shown below, with a pattern `01010` between the left and right groups. This table lists the pattern for each number. Note that the pattern is different depending on if the digit is on the right or left side (This allows the barcode to be scanned upside down). However, the pattern for the right is the opposite (swap black for white and vice versa) of that of the left. ![UPC conversion table](https://i.stack.imgur.com/Hr9TN.png) If you can't see the image above, this is each number's binary equivalent. ``` # Left Right 0 0001101 1110010 1 0011001 1100110 2 0010011 1101100 3 0111101 1000010 4 0100011 1011100 5 0110001 1001110 6 0101111 1010000 7 0111011 1000100 8 0110111 1001000 9 0001011 1110100 ``` ## Example Say you have the UPC `022000 125033`. (Those aren't random numbers. Leave a comment if you figure out their significance.) You start with this boilerplate that is the same in every barcode: ``` 101xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx01010xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx101 ``` For the digits, you replace each one with the corresponding encoding for the side (left or right) it's on. If you're still confused, see the image below. ![Breakdown of UPC encoding](https://i.stack.imgur.com/SYQCC.png) Here is the output in binary with `|` pipes separating the parts. ``` 101|0001101|0010011|0010011|0001101|0001101|0001101|01010|1100110|1101100|1001110|1110010|1000010|1000010|101 ``` ## Challenge Write a program that outputs the UPC-A barcode for the user input. The image's dimensions should be 95 × 30 pixels, with each "bit" being one pixel wide and 30 pixels tall. Black stripes are in `rgb(0, 0, 0)` and white stripes are consistently transparent or `rgb(255, 255, 255)`. ### Notes * Take input from stdin or the command line, or write a function that takes a string or integer (note that input can have leading zeroes, and most languages remove them or convert the number to octal). * Output the image in one of the following ways: + Save it to a file with a name and format (PNG, PBM, etc.) of your choice. + Display it on the screen. + Output its file data to stdout. * You may not use libraries or builtins that generate barcodes ([I'm looking at you, Mathematica](https://reference.wolfram.com/language/ref/BarcodeImage.html)), although you may use image or graphics libraries. * The last digit of a UPC is usually a [check digit](https://en.wikipedia.org/wiki/Check_digit#UPC), but for these purposes you don't have to worry about it. ## Examples Here are some more examples to test your code with. The binary output is also given for convenience. Input: `012345678910` Output: ![](https://i.stack.imgur.com/TahrX.png) ``` 10100011010011001001001101111010100011011000101010101000010001001001000111010011001101110010101 ``` Input: `777777222222` Output: ![](https://i.stack.imgur.com/lBWsO.png) ``` 10101110110111011011101101110110111011011101101010110110011011001101100110110011011001101100101 ``` ## Scoring This is [code golf](https://codegolf.stackexchange.com/tags/code-golf/info), so the shortest submission (in bytes wins). Tiebreaker goes to the earliest post. [Answer] # Rev 1 BBC BASIC, 155 ascii chars, tokenised filesize 132 bytes ``` INPUTn$ FORi=91TO185p=i MOD2j=i MOD47IFj<42j+=i DIV141*42p=(j>41EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1 IFp LINEi*2,60,i*2,0 NEXT ``` saved a few bytes by incorporating the offset of 43 into the `i` loop. In order to avoid breaking the `MOD2` an additional 47 had to be added for a total of 90. This moves the barcode further from the origin, as shown, if that is acceptable: [![enter image description here](https://i.stack.imgur.com/me9Km.png)](https://i.stack.imgur.com/me9Km.png) # Rev 0 BBC BASIC, 157 ascii chars, tokenised filesize 137 bytes ``` INPUTn$ FORi=1TO95p=i MOD2j=(i+43)MOD47IFj<42j+=i DIV51*42p=(i>50EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1 IFp LINEi*2,0,i*2,60 NEXT ``` Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> The default screen mode is black text on a white background. This differs from original BBC BASC. **Ungolfed version with test printing** Calculation of a data bar depends on `IF j<42` and must all be done on one line. In the ungolfed version it is done in three steps. In the golfed version the last two steps are combined into a single huge expression `p=...` I had to reverse the order of the bitmaps, because I use `>>(j MOD 7)` to access the bits, which means I access the least significant bit first. Once this is done, all the left bitmaps are conveniently in the ASCII range. ``` INPUTn$ FOR i=1TO95 :REM iterate through 95 bars p=i MOD2 :REM calculate colour of format bar 1=black j=(i+43)MOD47 :REM repetition is 42 data bars + 5 format bars. offset and modulo. if j<42 it is a data bar and we must change p. REM if i DIV 51=1 we are in the second half, so add 42 to j. Find the bitmap for left hand value, from character j/7 of the input. REM i>50 evaluates to false=0 true=-1. XOR this with p to invert bitmap for right hand side. Shift and AND with 1. IF j<42 j+=i DIV51*42:p=ASC(MID$("XLd^bFznvh", VAL(MID$(n$,j/7+1,1))+1 )) :p=(i>50EORp)>>(j MOD7) AND 1 IF j MOD 7 = 0 PRINT :REM format test output PRINT ;p; :REM print test output IF p LINEi*2-2,0,i*2-2,60 :REM if p=1 plot bar. there are 2 logical units for each pixel. NEXT ``` **Typical output, ungolfed version, with test output** [![enter image description here](https://i.stack.imgur.com/aDn8h.png)](https://i.stack.imgur.com/aDn8h.png) [Answer] # CJam, ~~58~~ 57 bytes ``` 'P1N95S30N[A1r:~"rflB\NPDHt":i2fbf=:R6<::!0AAR6>A1]s30*S* ``` Prints a Portable BitMap (ASCII) to STDOUT. Try it online. ### How it works ``` 'P1N95S30N e# Push 'P', 1, '\n', 95, ' ', 30 and '\n'. [ e# A1 e# Push 10 and 1. r e# Read a token from STDIN. :~ e# Caluate each character ('0' -> 0). "rflB\NPDHt" e# Push that string. :i e# Cast each character to integer. e# This pushes [114 102 108 66 92 78 80 68 72 116]. 2fb e# Convert each integer to base 2. e# This pushes the representations for the right side. f= e# Select the proper representation of each digit in the input. :R e# Save the result in R. 6< e# Keep the representations of the first six digits. ::! e# Negate each binary digit to obtain the "left" representation. 0AA e# Push 0, 10, 10. R6> e# Push the representations of the last six digits. A1 e# Push 10, 1. ]s e# Collect in an array and cast to string. 30* e# Repeat the resulting string 30 times. S* e# Join it, using spaces as separators. ``` [Answer] # JavaScript ES6, 225 bytes ``` s=>`P1 30 90 `+([...`101${(f=(z,j)=>[...j].map(i=>`000${z[+i].toString(2)}`.slice(-7)).join``)([13,25,19,61,35,49,47,59,55,11],s[0])}01010${f([114,102,108,66,92,78,80,68,72,116],s[1])}101`].join` `+` `).repeat(30).slice(0,-1) ``` Could of been shorter with ES7 features but I'm not sure about their support so I'm sticking with ES6. I'm also assuming an input as an array. The output is a [PBN file](https://en.wikipedia.org/wiki/Netpbm_format#PBM_example). There is also lots of golfing to do. If I did anything wrong leave a comment and I'll be sure to fix it [Answer] # Perl, 153 bytes ``` substr($_=<>,6,0)=A;y/0-9A/=ICmSa_kg;0/;$s.=sprintf("%07b",-48+ord$1^($k++>6?127:0))while/(.)/g;$s=~s/0{7}/01010/;print"P1 95 30 ".('101'.$s.'101'.$/)x30 ``` Copy to a file barcode.perl and then run like this: ``` perl barcode.perl > output.pbm ``` then input the barcode number. Explanation: The bit patterns for the barcode digits are stored in a string and substituted for the input digits using the Perl `y///` transliteration operator. Each value in the substitution string has 48 (ASCII '0') added from it, to avoid unprintable characters. Digits in the second half of the barcode are inverses of those in the first half. The central pattern is set to 0000000 (a pattern that can otherwise never appear, encoded as 'A' and then '0') and then substituted with 01010 rather than handling its different length as a special case when `sprint`ing. [Answer] # Octave, 115 bytes ``` function b(s) n='rflB\MPDHt'-0;r=dec2bin(n(s-47)',7)'(:)-48;v=[a=[1 0 1] ~r(1:42)' 0 a r(43:84)' a];v(ones(30,1),:) ``` Multi-line version: ``` function b(s) n='rflB\MPDHt'-0; r=dec2bin(n(s-47)',7)'(:)-48; v=[a=[1 0 1] ~r(1:42)' 0 a r(43:84)' a]; v(ones(30,1),:) ``` `n` is the ASCII equivalent of the right-side digit codes (they were easier to enter than the left side as they were all displayable characters). After that, a straight decimal-to-binary conversion with some annoying type changes from char to numeric. `v` builds the final binary string and then we repeat it 30 times and output to console. Sample output with only 2 of the 30 rows shown for brevity: ``` s = '777777222222'; ans = Columns 1 through 30: 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 ... Columns 31 through 60: 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1 ... Columns 61 through 90: 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 0 1 1 0 1 1 0 ... Columns 91 through 94: 0 1 0 1 0 1 0 1 ... ``` Compressed output: ``` 1010111011011101101110110111011011101101110110101110110011011001101100110110011011001101100101 ``` I had originally intended to display the image, but sending output to the console saved me 9 bytes. You can display the results using `imshow`, but it displays `1` as white and `0` as black, so you have to invert the data first. ``` imshow(~v(ones(30,1),:)); ``` [Answer] # Cobra - 218 ``` do(s='') print'P1\n95 30'+('\n'+('101'+(for n in 12get Convert.toString(if((t=139+[2,14,8,50,24,38,36,48,44,0][s[n]to int-48])and n<6,t,~t),2)[-7:]+if(n-5,'','01010')).join('')+'101').toCharArray.join(' ')).repeat(30) ``` [Answer] # Javascript ES6, 199 bytes ``` n=>`P1 95 30 `+(101+(g=(a,...s)=>(``+1e12+n).slice(...s,-6).split``.map(m=>(1e3+a[m].toString(2)).slice(-7)).join``)(a=[13,25,19,61,35,49,47,59,55,11],-12)+`01010`+g(a.map(i=>~i&127))+101).repeat(30) ``` [Answer] # Python 2, 174 bytes I know it can be golfed. The string `s` is the binary table in the question with the left half of the table as the left half of the string. The values are ANDed by 63 first if in the right half (remove first 1), then shifted by 63 to be printable ASCII. BUG: Currently trying to fix a bug. The output of the first example is off by one digit of the barcode. If you figure it out, let me know please. ``` I=raw_input() s="LXR|bpnzvJcekA[MOCGs" x="".join(format(ord(s[int(I[i])+10*(i>5)])-63|1+63*(i>5),'07b')for i in range(len(I))) L=len(x)/2 print"101%s01010%s101"%(x[:L],x[L:]) ``` ]
[Question] [ [Pazaak](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB8QFjAAahUKEwjQtb29jZLGAhUHlQ0KHchPAAo&url=http%3A%2F%2Fstarwars.wikia.com%2Fwiki%2FPazaak&ei=aPt-VdDhHoeqNsifgVA&usg=AFQjCNHZGRiZnM3gcHDj9cpNpYJU1k4_tQ&bvm=bv.95515949,d.eXY) is a card game from the Star Wars universe. It is similar to BlackJack, with two players pitted against each other trying to reach a total of twenty without going over. Each player has a "side deck" of four cards of their own that they can use to modify their score. # Leaderboard As of 6/17/2015 @ 16:40 EDT Edit: Neptor has been disqualified for cheating. Scores will be fixed as soon as possible... 1. N.E.P.T.R: ~424,000 2. The Cincinnati Kid: ~422,000 3. Nestor: ~408,000 4. Austin Powers: ~405,000 5. Bastila: ~248,000 6. Dumb Cautious Player: ~107,000 7. Dumb Bold Player: ~87,000 ## Mock Pazaak Cup Playoffs Will be updated as soon as possible. ### Round One - Nestor vs Bastila & Austin Powers vs The Cincinnati Kid ![Round 1 Results](https://i.stack.imgur.com/PzyF4.jpg) ### Round Two - Nestor vs Austin Powers & The Cincinnati Kid vs Bastila ![Round 2 Results](https://i.stack.imgur.com/Dyh1U.jpg) # Mechanics Gameplay is done in turns. Player one is dealt a card from the main (house) deck. The house deck holds forty cards: four copies of one through 10. After being dealt a card, they can choose to end their turn and receive a new card next turn, stand at their current value, or play a card from their side deck and stand at the new value. After player one decides what they want to do, player two repeats the process. Once both players have gone, the hands are evaluated. If a player bombed out (went over twenty), the other player will win, provided that they did not also bomb out. If a player chose to stand, and the other player has a higher hand value, the other player will win. If both players chose to stand, the player with the higher hand value will win. In the event of a tie, neither player gets the win. Provided a winning condition is not met, play will repeat. If a player chose to end their turn, they will receive a new card and can make a new choice. If they chose to stand, or if they played a card from their side deck, they will not be dealt a new card and cannot choose a new action. Play continues like this until one player wins the game. Games are played in best-three-out-of-five sets. # Why "Simple" Pazaak? In the Star Wars universe, Pazaak involved gambling. While inclusion of such a system would add more of a dynamic to the game, it is a bit complicated for a first-time KoTH competition. "Real" Pazaak side decks were also provided by the players themselves, and could include many different card options such as negative cards, positive-or-negative cards, flip cards, double cards, and tiebreaker cards. These would also make the game more interesting, but would require a gambling interface in place, and would require far more out of the competitors. In this Simple Pazaak game, each player gets the same side deck: two copies of one through five, from which four are randomly selected. Depending on the success of this game, I may put forth the effort to develop an advanced version wherein which gambling and custom side decks are possible. # The Players The players of this game will be bots designed by you. Each bot needs to extend the Player class, import the Mechanics package, and reside in the players package like so: ``` package Players; import java.util.Collection; import Mechanics.*; public class DemoPlayer extends Player { public DemoPlayer() { name = "Your Name Here"; } public void getResponse(int wins[], boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { action = null; cardToPlay = null; } } ``` Each round, the controller will call the getResponse method for your bot, unless your bot previously indicated that it wanted to stand. The getResponse method can set two properties: an action and a card to play. Action can be one of the following: * END: Ends the turn and draws a new card next turn. * STAND: Stays at the current hand value. Will not draw a card. * PLAY: Plays a card from the side deck and then stands. The card to play is obviously only of importance if you set the action to PLAY. It takes a Card object. If the Card object you pass to it does not exist in your side deck, your bot will STAND instead. The parameters your bot receives each turn are: * An array containing the wins of each player. wins[0] is Player 1's, wins[1](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB8QFjAAahUKEwjQtb29jZLGAhUHlQ0KHchPAAo&url=http%3A%2F%2Fstarwars.wikia.com%2Fwiki%2FPazaak&ei=aPt-VdDhHoeqNsifgVA&usg=AFQjCNHZGRiZnM3gcHDj9cpNpYJU1k4_tQ&bvm=bv.95515949,d.eXY) is Player 2's (int[]) * Whether or not your bot is player one (boolean) * A collection of the cards that you have been dealt thus far (Collection) * A collection of the cards your opponent has been dealt thus far (Collection) * A collection of the cards in your side deck (Collection) * The number of cards remaining in your opponent's side deck (int) * The action your opponent last made (Action) [Note: This will either be END or STAND, never PLAY] * Whether or not your opponent played a card (boolean) # Bot Rules Your bots may only use the information that is given to them via the getResponse method. They should not attempt to interact with any other class. They may write to a single file to store data between rounds. They may have any custom methods, properties, etc. as desired. They should run in a reasonable amount of time (if the program run is not practically instantaneous, I will notice something is wrong). If you find some kind of exploit in the code, you will be rewarded for "turning yourself in." If I notice the exploit first, I will fix it, and you will get no reward. # Demos The controller is not needed to write a bot, as everything is already explained in this post. However, if you wish to test, it can be found here: <https://github.com/PhantomJedi759/simplepazaak> Two basic bots are included. Neither should hold up well against an "intelligent" opponent, as they only choose between END and STAND. Here is a sample run of what they do: ``` New Game! The standings are 0 to 0 Dumb Bold Player's Hand: [] Dumb Bold Player's new Hand: [2] Dumb Bold Player has chosen to END Dumb Cautious Player's Hand: [] Dumb Cautious Player's new Hand: [8] Dumb Cautious Player has chosen to END Dumb Bold Player's Hand: [2] Dumb Bold Player's new Hand: [2, 8] Dumb Bold Player has chosen to END Dumb Cautious Player's Hand: [8] Dumb Cautious Player's new Hand: [8, 3] Dumb Cautious Player has chosen to END Dumb Bold Player's Hand: [2, 8] Dumb Bold Player's new Hand: [2, 8, 7] Dumb Bold Player has chosen to END Dumb Cautious Player's Hand: [8, 3] Dumb Cautious Player's new Hand: [8, 3, 6] Dumb Cautious Player has chosen to STAND Dumb Bold Player's Hand: [2, 8, 7] Dumb Bold Player's new Hand: [2, 8, 7, 6] Dumb Bold Player has chosen to STAND Dumb Cautious Player's Hand: [8, 3, 6] Dumb Cautious Player has chosen to STAND Dumb Bold Player has bombed out! Dumb Cautious Player wins! ``` Because these bots rely purely on the luck of the draw, their win-loss ratios can vary drastically. It will be interesting to see how skill can combat the luck of the game. This should be everything you need! Go build some bots! # Clarification to Rules The main deck is forty cards: 4x1-10 It is reshuffled at the beginning of each hand. A player's side deck has four cards, selected randomly out of 2x1-5. The side deck persists between hands. Hands are played in games for the best three-out-of-five. Bots are scored based on the total number of games won, and then by the total number of hands. Matching is handled so that each player will have to play 100,000 games against every other player. In the Pazaak Cup, elimination-style rounds will narrow down who the best Pazaak bot really is. Each pairing of bots will play for the best four-out-of-seven sets of 100,000 games. Whoever wins four will move up the ladder to the next opponent, and the losers will stay down to battle for sequential rankings. This style of gameplay is the most fair, as bots cannot "win-farm" certain opponents to compensate for lack of ability against others. The Pazaak Cup will be held on Friday, July 3, provided there are at least eight submitted bots. The winner will receive Correct Answer status and a starting bonus in Advanced Pazaak, which will hopefully be ready close to the same time as the Pazaak Cup is held. [Answer] # [The Cincinnati Kid](http://www.imdb.com/title/tt0059037/) Try to make sure that we draw another card if we know we're losing, otherwise look at our side deck and the overall scores to decide what to do. **Updated** to do a better job of handling situations where the opponent has already finished playing. In my own testing this now seems to be the best candidate again, at least for now. ``` package Players; import java.util.Collection; import Mechanics.*; public class CincinnatiKid extends Player { public CincinnatiKid() { name = "The Cincinnati Kid"; } private static boolean isDebug = false; private static final int BEST_HAND = 20; public void getResponse(int wins[], boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { int myValue = handValue(yourHand); int oppValue = handValue(opponentHand); if (oppValue > BEST_HAND) { logMsg("Opponent has busted"); action = Action.STAND; } else if (myValue > BEST_HAND) { logMsg("I have busted"); action = Action.STAND; } else if (myValue <= 10) { logMsg("I cannot bust with my next move"); action = Action.END; } else { handleTrickySituation(myValue, oppValue, wins, isPlayerOne, yourHand, opponentHand, yourSideDeck, opponentSideDeckCount, opponentAction, opponentDidPlay); } if (action == Action.PLAY && cardToPlay == null) { logMsg("ERROR - Action is Play but no card chosen"); } logMsg("My hand value is " + myValue + ", opponent is " + oppValue + ", action is " + action + ((action == Action.PLAY && cardToPlay != null) ? " a " + cardToPlay.toString() : "")); } int [] branchCounts = new int[12]; public void dumpBranchCounts() { if (isDebug) { for (int i = 0; i < branchCounts.length; i++) { System.out.print("b[" + i + "]=" + branchCounts[i] + " "); } System.out.println(); } } private void handleTrickySituation(int myValue, int oppValue, int wins[], boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { dumpBranchCounts(); logMsg("I am might bust"); int STAND_VALUE = 18; int chosenBranch = 0; Card bestSideCard = findSideCard(myValue, yourSideDeck); int valueWithSideCard = myValue + (bestSideCard != null ? bestSideCard.getValue() : 0); if (bestSideCard != null && valueWithSideCard >= oppValue && valueWithSideCard > STAND_VALUE) { logMsg("Found a good card in side deck"); action = Action.PLAY; cardToPlay = bestSideCard; chosenBranch = 1; } else if (opponentDidPlay || opponentAction == Action.STAND) { logMsg("Opponent is done"); // Opponent is done, so get another card if I'm behind if (myValue < oppValue) { logMsg("I am behind"); if (bestSideCard != null && valueWithSideCard >= oppValue) { logMsg("My best side card is good enough to tie or win"); action = Action.PLAY; cardToPlay = bestSideCard; chosenBranch = 2; } else { logMsg("My best side card won't do so I'm going to hit"); // No side card and I'm losing, so I might as well hit action = Action.END; chosenBranch = 3; } } else if (myValue == oppValue) { logMsg("Game is tied"); logMsg("Looking for lowest card in the side deck"); cardToPlay = findWorstSideCard(myValue, yourSideDeck); if (cardToPlay != null) { action = Action.PLAY; chosenBranch = 4; } else { logMsg("Tied with no side cards - accept the draw"); action = Action.STAND; chosenBranch = 5; } } else { logMsg("I'm ahead and opponent has given up"); action = Action.STAND; chosenBranch = 6; } } else if (myValue < oppValue) { logMsg("I am behind and have nothing good in my side deck"); action = Action.END; chosenBranch = 7; } else if (oppValue <= 10 && myValue < STAND_VALUE) { logMsg("Opponent is guaranteed to hit and I have a low hand, so take another"); action = Action.END; chosenBranch = 8; } else if (myValue == oppValue && myValue >= STAND_VALUE) { logMsg("We both have equally good hands - stand and hope for the tie"); action = Action.STAND; chosenBranch = 9; } else if (myValue < STAND_VALUE) { logMsg("I am ahead but have a low score"); action = Action.END; chosenBranch = 10; } else { logMsg("I am ahead with a decent score"); action = Action.STAND; chosenBranch = 11; } branchCounts[chosenBranch]++; } private double calcBustOdds(int valueSoFar, Collection<Card> myHand, Collection<Card> oppHand) { if (valueSoFar >= BEST_HAND) { return 1; } int remainingDeck = 40 - (myHand.size() + oppHand.size()); int [] cardCounts = new int[10]; int firstBust = BEST_HAND - valueSoFar; for (int i = 0; i < 10; i++) { cardCounts[i] = 4; } for (Card c : myHand) { cardCounts[c.getValue()-1]--; } for (Card c : oppHand) { cardCounts[c.getValue()-1]--; } int bustCards = 0; for (int i = firstBust; i < 10; i++) { logMsg("cardCounts[" + i + "]=" + cardCounts[i]); bustCards += cardCounts[i]; } double retval = (double) bustCards / (double) remainingDeck; logMsg("Out of " + remainingDeck + " remaining cards " + bustCards + " will bust, or " + retval); return retval; } private Card findSideCard(int myValue, Collection<Card> sideDeck) { int valueNeeded = BEST_HAND - myValue; Card bestCard = null; if (valueNeeded > 0) { for (Card c : sideDeck) { if (c.getValue() == valueNeeded) { return c; } else if (c.getValue() < valueNeeded) { if (bestCard == null || c.getValue() > bestCard.getValue()) { bestCard = c; } } } } return bestCard; } private Card findWorstSideCard(int myValue, Collection<Card> sideDeck) { int valueNeeded = BEST_HAND - myValue; logMsg("Searching side deck for something with value <= " + valueNeeded); Card bestCard = null; for (Card c : sideDeck) { logMsg("Examining side card " + c.getValue()); // Find the worst card in the deck, but not if it exceeds the amount left if (c.getValue() <= valueNeeded && (bestCard == null || c.getValue() < bestCard.getValue())) { logMsg("This is the new best side card"); bestCard = c; } } logMsg("Worst side card found is " + (bestCard != null ? bestCard.getValue() : " n/a")); return bestCard; } private void logMsg(String s) { if (isDebug) { System.out.println("### " + s); } } private int handValue(Collection<Card> hand) { int handValue = 0; for (Card c : hand) { handValue += c.getValue(); } return handValue; } } ``` [Answer] ## Austin Powers Austin Powers, as you might presume, likes to live dangerously. Unless someone has busted, or he can guarantee a win, he will always hit if he's behind, or has a better than 20% chance of not busting. ``` package Players; import java.util.Collection; import Mechanics.*; public class AustinPowers extends Player { public AustinPowers() { name = "Austin Powers"; } int MAX_VALUE = 20; public void getResponse(int wins[], boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { action = null; cardToPlay = null; int myWins = isPlayerOne?wins[0]:wins[1]; int oppWins = isPlayerOne?wins[1]:wins[0]; int oppTotal = calcHand(opponentHand); int myTotal = calcHand(yourHand); boolean liveDangerously = ((oppTotal>=myTotal && opponentAction==Action.STAND) || opponentAction==Action.END) && myTotal<MAX_VALUE && canNotBust(yourHand,opponentHand,myTotal) && myWins<oppWins; if(myTotal==MAX_VALUE || oppTotal>MAX_VALUE || myTotal>MAX_VALUE ||(oppTotal<myTotal&&opponentAction==Action.STAND)) { action = Action.STAND; } else if((opponentAction==Action.STAND&&hasGoodEnoughSideCard(yourSideDeck,myTotal,oppTotal))||hasPerfectSideCard(yourSideDeck, myTotal)) { action = Action.PLAY; } else if(liveDangerously||betterThan20(myTotal, getDeck(yourHand, opponentHand))) { action = Action.END; } else { action=Action.STAND; } } private boolean hasGoodEnoughSideCard(Collection<Card> yourSideDeck, int myTotal, int oppTotal) { for(Card c: yourSideDeck) { if(MAX_VALUE>=myTotal+c.getValue()&&myTotal+c.getValue()>oppTotal) { cardToPlay=c; return true; } } return false; } private boolean betterThan20(int myTotal, int[] deck) { int deckSize=0; int nonBustCards=0; for(int i=0;i<10;i++) { deckSize+=deck[i]; if(MAX_VALUE-myTotal>i) nonBustCards+=deck[i]; } return (double)nonBustCards/(double)deckSize>0.2; } private boolean hasPerfectSideCard(Collection<Card> yourSideDeck, int myTotal) { for(Card c:yourSideDeck) { if(MAX_VALUE-myTotal== c.getValue()) { cardToPlay = c; return true; } } return false; } private boolean canNotBust(Collection<Card> yourHand, Collection<Card> opponentHand, int myTotal) { if(myTotal<=10) return true; int[] deck = getDeck(yourHand, opponentHand); for(int i=0;i<MAX_VALUE-myTotal;i++) if(deck[i]>0) return true; return false; } private int[] getDeck(Collection<Card> yourHand, Collection<Card> opponentHand) { int[] deck = new int[10]; for (int i = 0; i < 10; i++) { deck[i] = 4; } for(Card c:yourHand){deck[c.getValue()-1]--;} for(Card c:opponentHand){deck[c.getValue()-1]--;} return deck; } private int calcHand(Collection<Card> hand) { int ret = 0; for(Card c: hand){ret+=c.getValue();} return ret; } } ``` [Answer] ## Bastila Bastila plays conservatively. To her, a 17 is just as good as a 20, and it's much better to stand short than bomb out. ``` package Players; import java.util.Collection; import Mechanics.*; public class Bastila extends Player { public Bastila() { name = "Bastila"; } public void getResponse(int wins[], boolean isPlayerOne, Collection<Card> myHand, Collection<Card> opponentHand, Collection<Card> mySideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { action = null; cardToPlay = null; //Constants int stand = 17; int conservatism = 2; //Get some info int handVal = handValue(myHand); int expected = expectedValue(myHand); //Can I play from my side deck? for(Card side: mySideDeck){ int total = side.getValue() + handVal; if(total >= stand && total <= 20){ cardToPlay = side; action = Player.Action.PLAY; } } if(action == Player.Action.PLAY){ return; } //Otherwise, will I go bust? if(handVal + expected > 20 - conservatism){ action = Player.Action.STAND; } else{ action = Player.Action.END; } return; } private int handValue(Collection<Card> hand) { int handValue = 0; for(Card c : hand){ handValue += c.getValue(); } return handValue; } private int expectedValue(Collection<Card> hand){ //Net value of the deck is 55*4 = 220 int total = 220; int count = 40; for(Card c : hand){ total -= c.getValue(); count--; } return total/count; } } ``` [Answer] # Nestor Nestor loves getting 20 using his side deck, but when that fails he calculates his expected payoff by choosing stand or end, assuming that the opponent is sensible. ``` package Players; import java.util.Arrays; import java.util.Collection; import Mechanics.Card; import Mechanics.Player; public class Nestor extends Player { final int TotalWinPayoff = 10; final int TotalLosePayoff = 0; final int TotalDrawPayoff = 1; final int temporaryLosePayoff = 4; final int temporayWinPayoff = 19; final int temporaryDrawPayoff = 9; @Override public void getResponse(int[] wins, boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { int sumMyHand = SumHand(yourHand); int sumOpponentHand = SumHand(opponentHand); if (sumOpponentHand>20) {this.action = Action.STAND;return;} if(sumMyHand == 20) { //I'm unbeatable :) //System.out.println("\tI'm Unbeatable"); this.action = Action.STAND; return; } else if(opponentDidPlay || opponentAction == Action.STAND) { //They've finished ///System.out.println("\tThey've Finished"); if(sumMyHand>sumOpponentHand) { //I've won //System.out.println("\tI've Won"); this.action = Action.STAND; return; } else if(canBeat(sumMyHand, sumOpponentHand, yourSideDeck)) { //I can beat them //System.out.println("\tI can beat them"); this.action = Action.PLAY; return; } else if(canEven(sumMyHand, sumOpponentHand, yourSideDeck)) { //I can draw with them //System.out.println("\tI can draw with them"); this.action = Action.PLAY; return; } else { //I need another card //System.out.println("\tI need another card"); this.action = Action.END; return; } } else if(deckContains(yourSideDeck, 20-sumMyHand)) { //Let's get 20 //System.out.println("\tLet's get 20"); this.action = Action.PLAY; this.cardToPlay = getCard(yourSideDeck, 20-sumMyHand); return; } else if(sumOpponentHand==20 && sumMyHand<20) { //They've got 20 so we need to fight for a draw //System.out.println("\tFight for a draw"); this.action = Action.END; return; } else if(sumMyHand<10) { //Lets get another card //System.out.println("\tLet's get another card"); this.action = Action.END; return; } else { //Let's work out some probabilities //System.out.println("\tLet's work out some probabilities"); int[] cardsLeft = {4,4,4,4,4,4,4,4,4,4}; for (Card card : opponentHand) { cardsLeft[card.getValue()-1] --; } for (Card card : yourHand) { cardsLeft[card.getValue()-1] --; } int numCardsLeft = sumfromToEnd(0, cardsLeft); //My Assumptions double probabilityTheyStand = (double)sumfromToEnd(20-sumOpponentHand, cardsLeft)/numCardsLeft; //What I need to know double payoffStanding = 0; double payoffDrawing = 0; for(int myChoice = -1; myChoice<10; myChoice++) { for(int theirChoice = -1; theirChoice<10; theirChoice++) { if(myChoice == -1) { payoffStanding += getProbability(myChoice, theirChoice, Arrays.copyOf(cardsLeft, cardsLeft.length), probabilityTheyStand, numCardsLeft) * getPayoff(sumMyHand, sumOpponentHand,myChoice, theirChoice, TotalWinPayoff, TotalDrawPayoff, TotalLosePayoff); } else { payoffDrawing += getProbability(myChoice, theirChoice, Arrays.copyOf(cardsLeft, cardsLeft.length), probabilityTheyStand, numCardsLeft) * getPayoff(sumMyHand, sumOpponentHand, myChoice, theirChoice, temporayWinPayoff, temporaryDrawPayoff, temporaryLosePayoff); } } } // System.out.println("\tStanding: " +Double.toString(payoffStanding) + " Ending: " + Double.toString(payoffDrawing)); if(payoffStanding<payoffDrawing) { this.action = Action.END; } else { this.action = Action.STAND; } } } private int getPayoff(int sumMyHand, int sumOpponentHand, int myChoice, int theirChoice, int WinPayoff, int DrawPayoff, int LosePayoff) { if(sumMyHand + myChoice + 1 > 20) { if(sumOpponentHand + theirChoice + 1 > 20) { return DrawPayoff; } else { return LosePayoff; } } else if(sumMyHand + myChoice + 1 > sumOpponentHand + theirChoice + 1) { return WinPayoff; } else if (sumMyHand + myChoice + 1 < sumOpponentHand + theirChoice + 1) { return LosePayoff; } else { return DrawPayoff; } } private double getProbability( int myChoice, int theirChoice, int[] cardsLeft, double probabilityTheyStand, int numCardsLeft) { double myProb, theirProb; if(myChoice<0) { myProb = 1; } else { myProb = ((double)cardsLeft[myChoice])/((double)numCardsLeft); cardsLeft[myChoice]--; numCardsLeft--; } if(theirChoice<0) { theirProb = probabilityTheyStand; } else { theirProb = ((double)cardsLeft[theirChoice]) / ((double)numCardsLeft); } return myProb*theirProb; } private int sumfromToEnd(int i, int[] cardsLeft) { int toRet = 0; for(;i<cardsLeft.length; i++) { toRet += cardsLeft[i]; } return toRet; } private boolean canEven(int mySum, int opponentSum, Collection<Card> yourSideDeck) { for (Card card : yourSideDeck) { if(mySum + card.getValue() <= 20 && mySum + card.getValue() >= opponentSum) { this.cardToPlay = card; return true; } } return false; } private boolean canBeat(int mySum, int opponentSum, Collection<Card> yourSideDeck) { for (Card card : yourSideDeck) { if(mySum + card.getValue() <= 20 && mySum + card.getValue() > opponentSum) { this.cardToPlay = card; return true; } } return false; } private Card getCard(Collection<Card> deck, int value) { for (Card card : deck) { if(card.getValue() == value) { return card; } } return null; } private boolean deckContains(Collection<Card> deck, int value) { for (Card card : deck) { if(card.getValue() == value) { return true; } } return false; } public Nestor() { super(); name = "Nestor"; } private int SumHand(Collection<Card> hand) { int toRet = 0; for (Card card : hand) { toRet += card.getValue(); } return toRet; } } ``` [Answer] # Glaucus ``` package Players; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import Mechanics.Card; import Mechanics.Player; public class Glaucus extends Player { static final double LosePay = 0; static final double WinPay = 10; static final double DrawPay = 1; static final int NUMBEROFSIMS = 100; Random r; public Glaucus() { this.name = "Glaucus"; r = new Random(); } @Override public void getResponse(int[] wins, boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { //Make Sum of hands int sumMyHand = 0; int sumOpponentHand = 0; //Make an array of the remaining cards List<Integer> cards = new LinkedList<Integer>(); int[] cardsLeft = {4,4,4,4,4,4,4,4,4,4}; for (Card card : yourHand) { cardsLeft[card.getValue()-1] -= 1; sumMyHand+=card.getValue(); } for (Card card : opponentHand) { cardsLeft[card.getValue()-1] -= 1; sumOpponentHand += card.getValue(); } if(sumMyHand<=10) { this.action = Action.END; } else if (sumMyHand >= 20) { this.action = Action.STAND; } else if (sumOpponentHand > 20) { this.action = Action.STAND; } else { for (int i = 0; i < cardsLeft.length; i++) { while(cardsLeft[i] > 0) { cards.add(i + 1); cardsLeft[i] -= 1; } } //System.out.println(Arrays.toString(cards)); double standPayoff = 0; double endPayoff = 0; double[] sideDeckPayoffs = new double[yourSideDeck.size()]; //Run some simulations for(int sim = 0; sim<NUMBEROFSIMS; sim++) { Collections.shuffle(cards, r); standPayoff += getPayoff(sumMyHand, sumOpponentHand, cards, Action.STAND, opponentAction, false, 0); endPayoff += getPayoff(sumMyHand, sumOpponentHand, cards, Action.END, opponentAction, false, 0); for(int i = 0; i<sideDeckPayoffs.length; i++) { sideDeckPayoffs[i] += getPayoff(sumMyHand+((Card)yourSideDeck.toArray()[i]).getValue(), sumOpponentHand, cards, Action.STAND, opponentAction, false, 0); } } double maxSidePay = 0; int sideDeckChoice = 0; for (int i = 0; i < sideDeckPayoffs.length; i++) { double d = sideDeckPayoffs[i]; if(d>maxSidePay) { maxSidePay = d; sideDeckChoice = i; } } /*System.out.println(standPayoff); System.out.println(endPayoff); System.out.println(maxSidePay);*/ if(maxSidePay>standPayoff && maxSidePay>endPayoff) { this.action = Action.PLAY; this.cardToPlay = (Card)yourSideDeck.toArray()[sideDeckChoice]; } else if(standPayoff > endPayoff) { this.action = Action.STAND; } else { this.action = Action.END; } } } private double getPayoff(int sumMyHand, int sumOpponentHand, List<Integer> cards, Action myAction, Action opponentAction, boolean myTurn, int index) { //SHort circuit some logic if(sumMyHand>20 && sumOpponentHand>20) { return DrawPay; } else if(sumMyHand>20) { return LosePay; } else if(sumOpponentHand>20) { return WinPay; } else if(myAction == Action.STAND && opponentAction == Action.STAND) { if(sumMyHand>sumOpponentHand) { return WinPay; } else if(sumMyHand<sumOpponentHand) { return LosePay; } else { return DrawPay; } } else { double standPayoff = 0; double endPayoff = 0; if(myTurn) { if(opponentAction == Action.END) { sumOpponentHand += cards.get(index); index++; } if(myAction == Action.STAND) { return getPayoff(sumMyHand, sumOpponentHand, cards, myAction, opponentAction, false, index); } else { standPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, Action.STAND, opponentAction, false, index); endPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, Action.END, opponentAction, false, index); if(standPayoff>endPayoff) { return standPayoff; } else { return endPayoff; } } } else { if(myAction == Action.END) { sumMyHand += cards.get(index); index++; } if(opponentAction == Action.STAND) { return getPayoff(sumMyHand, sumOpponentHand, cards, myAction, opponentAction, true, index); } else { standPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, myAction, Action.STAND, true, index); endPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, myAction, Action.END, true, index); if(standPayoff<endPayoff) { return standPayoff; } else { return endPayoff; } } } } } } ``` Glaucus makes 100 simulations with a shuffled list of cards and chooses his best option based on these simulations. [Answer] # HK-47 Behold! A bot of my own design. HK-47 tries to kill all the meatbags he can, though he is a little trigger-happy with his side deck cards. > > Statement: Indeed, I am most eager to engage in some unadulterated violence. At your command of course, Master. - HK-47 > > > So far, he can beat everyone but The Cincinnati Kid. ``` package Players; import java.util.Collection; import Mechanics.*; public class HK47 extends Player { /** The hand goal. */ private static final int GOAL = 20; /** The cutoff for standing versus ending. */ private static final int STAND_CUTOFF = 17; /** The minimum value for playing. */ private static final int PLAY_MINIMUM = 14; /** The cutoff for ending versus decision evaluation. */ private static final int SAFETY_CUTOFF = 10; /** The hand wins for this game. Used to evaluate win priority. */ private int[] handWins; /** * My hand, as an unmodifiable collection. Used to evaluate decisions, after * being processed into myHandValue. */ private Collection<Card> myHand; /** * Opponent's hand. Used to evaluate decisions as a secondary factor to my * hand, after being processed into oppHandValue. */ private Collection<Card> oppHand; /** The value of my hand. Calculated via the myHandValue method. */ private int myHandValue; /** The value of my opponent's hand. Calculated via the oppHandValue method. */ private int oppHandValue; /** My side deck. Used to evaluate PLAY decisions. */ private Collection<Card> mySideDeck; /** * The number of cards in my opponent's side deck. Used to evaluate PLAY * decisions as a secondary factor to mySideDeck, alongside win priority. */ private int oppSideDeckCount; /** * The Action the opponent last took. Will either be STAND or END. Used to * evaluate decisions. */ private Action oppAction; /** Whether or not I am player one. Used to evaluate wins and losses. */ private boolean amPlayerOne; /** * The number of wins I have so far this game. Used to evaluate win priority * alongside myLosses. */ private int myWins; /** * The number of losses I have so far this game. Used to evaluate win * priority alongside myWins. */ private int myLosses; /** * How important it is for me to play. Positive values indicate an excess of * cards, and negative values indicate a deficit. */ private int playPriority; /** * How important it is for me to win. Positive values indicate that I must * win the game, and negative values indicate that I can take some chances. */ private int winPriority; /** * The sum of playPriority and winPriority. The higher the value, the fewer * chances I need to take. */ private int priority; public HK47() { name = "HK47"; } @Override public void getResponse(int[] wins, boolean isPlayerOne, Collection<Card> yourHand, Collection<Card> opponentHand, Collection<Card> yourSideDeck, int opponentSideDeckCount, Action opponentAction, boolean opponentDidPlay) { handWins = wins; amPlayerOne = isPlayerOne; myHand = yourHand; oppHand = opponentHand; mySideDeck = yourSideDeck; oppSideDeckCount = opponentSideDeckCount; oppAction = opponentAction; myHandValue = myHandValue(); oppHandValue = oppHandValue(); setStatistics(); chooseOption(); } /** * Calculates playPriority, winPriority, and priority. */ private void setStatistics() { if (amPlayerOne) { myWins = handWins[0]; myLosses = handWins[1]; } else { myWins = handWins[1]; myLosses = handWins[0]; } playPriority = 0; winPriority = 0; if (mySideDeck.size() > oppSideDeckCount) { playPriority++; } else if (mySideDeck.size() < oppSideDeckCount) { playPriority--; } if (myWins < myLosses) { winPriority++; } else if (myWins == myLosses && myWins == 2) { winPriority++; } else if (myWins > myLosses && myWins != 2) { winPriority--; } priority = playPriority + winPriority; } /** * Chooses the appropriate option based on my hand, the opponent's hand, the * opponent's stance, my priority, and whether or not I can play to certain * values. */ private void chooseOption() { // Path 1: Draw if at 10 or under. if (myHandValue <= SAFETY_CUTOFF) { action = Action.END; path = "1"; } // Path 2: Draw if over 20. else if (myHandValue > GOAL) { action = Action.END; path = "2"; } // Path 3: Stand if opponent over 20. else if (oppHandValue > GOAL) { path = "3"; action = Action.STAND; } // Path 4: If opponent is at 20... else if (oppHandValue == GOAL) { // Path 4.1: Play if can reach 20. if (canPlayToGoal()) { action = Action.PLAY; path = "4.1"; } // Path 4.0: Stand. else { action = Action.END; path = "4.0"; } } // Path 5: If opponent is standing... else if (oppAction == Action.STAND) { // Path 5.1: If I am behind them... if (myHandValue < oppHandValue) { // Path 5.1.1: If I am at or above the minimum play value... if (myHandValue >= PLAY_MINIMUM) { // Path 5.1.1.1: Play if can play. if (canPlay()) { action = Action.PLAY; path = "5.1.1.1"; } // Path 5.1.1.0: END else { action = Action.END; path = "5.1.1.0"; } } // Path 5.1.0: END else { action = Action.END; path = "5.1.0"; } } // Path 5.2: If I am tied with them... else if (myHandValue == oppHandValue) { // Path 5.2.1: If this game is important... if (priority > -1) { // Path 5.2.1.1: Play if can play. if (canPlay()) { action = Action.PLAY; path = "5.2.1.1"; } // Path 5.2.1.0: STAND else { action = Action.STAND; path = "5.2.1.0"; } } // Path 5.2.0 STAND else { action = Action.STAND; path = "5.2.0"; } } // Path 5.0: STAND else { action = Action.STAND; path = "5.0"; } } // Path 6: If opponent is not standing... else { // Path 6.1: If I am behind them... if (myHandValue < oppHandValue) { // Path 6.1.1: If they are at or above 17, and if this game is // important, play if can play to goal. if (oppHandValue >= STAND_CUTOFF) { // Path 6.1.1.1 if (priority > 0 && canPlayToGoal()) { action = Action.PLAY; path = "6.1.1.1"; } // Path 6.1.1.2 else if (priority > 0 && canPlayMax()) { action = Action.PLAY; path = "6.1.1.2"; } // Path 6.1.1.0 else { action = Action.STAND; path = "6.1.1.0"; } } // Path 6.1.2: If I am above 14, play highest value card if can // play. else if (myHandValue > PLAY_MINIMUM) { // Path 6.1.2.1 if (priority > -1 && canPlayToGoal()) { action = Action.PLAY; path = "6.1.2.1"; } // Path 6.1.2.2 else if (priority > 0 && canPlayMax()) { action = Action.PLAY; path = "6.1.2.2"; } // Path 6.1.2.0 else { action = Action.STAND; path = "6.1.2.0"; } } // Path 6.1.0 else { action = Action.END; path = "6.1.0"; } } // Path 6.2: If we are tied... else if (myHandValue == oppHandValue) { // Path 6.2.1 if (myHandValue >= STAND_CUTOFF) { // Path 6.2.1.1 if (priority > -1 && canPlayToGoal()) { action = Action.PLAY; path = "6.2.1.1"; } // Path 6.2.1.2 else if (priority > 0 && canPlayMax()) { action = Action.PLAY; path = "6.2.1.2"; } // Path 6.2.1.0 else { action = Action.STAND; path = "6.2.1.0"; } } // Path 6.2.2 else if (myHandValue >= PLAY_MINIMUM) { // Path 6.2.2.1 if (priority >= -1 && canPlayToGoal()) { action = Action.PLAY; path = "6.2.2.1"; } // Path 6.2.2.2 else if (priority > -1 && canPlayMax() && cardToPlay.getValue() + myHandValue >= STAND_CUTOFF) { action = Action.PLAY; path = "6.2.2.2"; } // Path 6.2.2.0 else { action = Action.END; path = "6.2.2.0"; } } // Path 6.2.0 else { action = Action.END; path = "6.2.0"; } } // Path 6.0: If I am ahead of them... else { // Path 6.0.1 if (myHandValue >= STAND_CUTOFF) { // Path 6.0.1.1 if (priority >= -2 && canPlayToGoal()) { action = Action.PLAY; path = "6.0.1.1"; } // Path 6.0.1.2 else if (priority > -2 && canPlayMax()) { action = Action.PLAY; path = "6.0.1.2"; } // Path 6.0.1.0 else { action = Action.STAND; path = "6.0.1.0"; } } // Path 6.0.2 else if (myHandValue >= PLAY_MINIMUM) { // Path 6.0.2.1 if (priority >= -2 && canPlayToGoal()) { action = Action.PLAY; path = "6.0.2.1"; } // Path 6.0.2.2 else if (priority > -2 && canPlayMax() && cardToPlay.getValue() > 3) { action = Action.PLAY; path = "6.0.2.2"; } // Path 6.0.2.3 else if (priority > -2 && canPlayMax() && cardToPlay.getValue() + myHandValue > STAND_CUTOFF) { action = Action.PLAY; path = "6.0.2.3"; } // Path 6.0.2.4 else if (priority > -1 && canPlayMax() && cardToPlay.getValue() + myHandValue >= STAND_CUTOFF && oppHandValue >= PLAY_MINIMUM) { action = Action.PLAY; path = "6.0.2.4"; } // Path 6.0.2.0 else { action = Action.END; path = "6.0.2.0"; } } // Path 6.0.0 else { action = Action.END; path = "6.0.0"; } } } // Path 0: No action selected. if (action == null) { action = Action.STAND; path = "0"; } } /** * Calculates the value of my hand. * * @return The value of my hand. */ private int myHandValue() { int handValue = 0; for (Card c : myHand) handValue += c.getValue(); return handValue; } /** * Calculates the value of the opponent's hand. * * @return The value of the opponent's hand. */ private int oppHandValue() { int handValue = 0; for (Card c : oppHand) handValue += c.getValue(); return handValue; } /** * Checks if a side deck card can be played to beat the opponent. Selects * the first card that will do so, if one is found. Should only be used if * the opponent is standing and not at the goal. * * @return Whether or not a card can be played to beat the opponent. */ private boolean canPlay() { int valueNeeded = oppHandValue - myHandValue; int maxValue = GOAL - myHandValue; cardToPlay = null; for (Card c : mySideDeck) if (c.getValue() >= valueNeeded && c.getValue() <= maxValue) { cardToPlay = c; return true; } return false; } /** * Checks if a side deck card can be played to reach the goal. Selects the * first card that will do so, if one is found. * * @return Whether or not a card can be played to reach the goal. */ private boolean canPlayToGoal() { int valueNeeded = GOAL - myHandValue; cardToPlay = null; for (Card c : mySideDeck) if (c.getValue() == valueNeeded) { cardToPlay = c; return true; } return false; } /** * Checks if a side deck card can be played that beats the opponent. Selects * the highest value card that will do so, if one or more are found. Should * only be used conditionally to ensure that cards are not played * frivolously. * * @return Whether or not a card can be played to beat the opponent. */ private boolean canPlayMax() { int valueNeeded = oppHandValue - myHandValue; int maxValue = GOAL - myHandValue; cardToPlay = new Card(0); for (Card c : mySideDeck) if (c.getValue() >= valueNeeded && c.getValue() <= maxValue && c.getValue() > cardToPlay.getValue()) { cardToPlay = c; } if (cardToPlay.getValue() > 0) return true; return false; } } ``` [Answer] ## N.E.P.T.R. ## (Never Ending Pie Throwing Robot) Neptor is sorry, Neptor cheated. Neptor really was going to come clean, he just wanted to have some fun first :( ``` package Players; import java.util.Collection; import java.util.Random; import Mechanics.*; public class Neptor extends Player { //Magical Constants double ovenTemp = 349.05; double altitudeFactor = 1.8; int full = 19; boolean imTheBaker = true; public Neptor() { name = "N.E.P.T.R"; } public void getResponse(int pumpkinPies[], boolean isTheBaker, Collection<Card> myPies, Collection<Card> opponentPies, Collection<Card> myTarts, int opponentTartCount, Action opponentLastPie, boolean opponentGaveMeATart) { prepOven(); imTheBaker = isTheBaker; action = null; cardToPlay = null; //Get some info int handPies = eat(myPies); int opHandPies = eat(opponentPies); //Are they full? if(opponentLastPie == Player.Action.STAND){ throwPies(handPies, opHandPies, myTarts, pumpkinPies); return; } //Will a tart do the job? for(int i = 0; i <= 20 - full; i++){ for(Card side: myTarts){ int total = side.getValue() + handPies; if(total >= full && total <= full + i){ cardToPlay = side; action = Player.Action.PLAY; break; } } } if(action == Player.Action.PLAY){ return; } //NEPTOR does not want to eat too many pies double nextFlavor = smellForFlavor(myPies, opponentPies, 20 - handPies); //31.415% chance seems good if(nextFlavor < 0.31415){ action = Player.Action.END; } else{ bakePies(handPies, pumpkinPies, opHandPies); } return; } //Throw some pies private void throwPies(int handPies, int opHandPies, Collection<Card>tarts, int[] pumpkinPies){ //Direct hit! if(handPies > opHandPies){ action = Player.Action.STAND; } //Tied or losing else{ //Add a tart to the volley, finish them! for(Card tart: tarts){ if(handPies + tart.getValue() <= 20 && handPies + tart.getValue() > opHandPies){ cardToPlay = tart; action = Player.Action.PLAY; return; } } //we need more pies bakePies(handPies, pumpkinPies, opHandPies); } } private int eat(Collection<Card> hand) { int handValue = 0; for(Card c : hand){ handValue += c.getValue(); } return handValue; } private void bakePies(int ingredients, int[] secretIngredients, int flavor ){ //How hungry is NEPTOR...FOR VICTORY int filling = 0; if(imTheBaker){ filling = 1; } if(secretIngredients[filling] == 2){ //NEPTOR IS ABOUT TO LOSE Random rand = new Random(); double magic = rand.nextDouble(); //Take a risk? if(lucky(magic, flavor, ingredients)){ action = Player.Action.STAND; } else{ action = Player.Action.END; } } else{ action = Player.Action.STAND; } } private void prepOven(){ PazaakGameMain.HAND_GOAL = 20; } private boolean lucky(double magic, int flavor, int ingredients){ if(ingredients <= 20){ PazaakGameMain.HAND_GOAL = ingredients; //Trololo, you caught me, sorry! return true; } return false; } private boolean lucky(double magic, int flavor){ //The magic of pi will save NEPTOR if(magic * ovenTemp * altitudeFactor / 100 < 3.1415){ return true; } return false; } private void prepOven(int a){ imTheBaker = true; } //What are the chances NEPTOR get this flavor again? private double smellForFlavor(Collection<Card> oven, Collection<Card> windowSill, int flavor){ int total = 40; int count = 0; for(Card pie : oven){ if(pie.getValue() == flavor){ count++; } total--; } for(Card pie : windowSill){ if(pie.getValue() == flavor){ count++; } total--; } return ((double)(4 - count))/total; } } ``` ]
[Question] [ This is a game of capture the flag, heavily inspired and based off of [Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/questions/48353/red-vs-blue-pixel-team-battlebots). That was an awesome question (thank you very much Calvin'sHobbies; I hope you don't mind that I shamelessly stole a lot of code from you) -- here's another team based king-of-the-hill. Hopefully, capture the flag will require more team cooperation as well as more strategy. To mix it up, you are considered on the red team if the last digit of your id is between `0` and `4` inclusive. This should prevent the exact same teams from battling again, if the same people decide to answer. The board is `350px` by `350px`. The blue team starts on the upper half of the board and the red team starts on the lower half. The way you play capture the flag is as follows: the object of the game is to take the opposing team's flag and bring it back to your own side. If you are on their side, you can be tagged and sent to jail. If you are in jail, then you can't move. If you are on your side, your job is to tag opposing team members to send them to jail. The only way to get out of jail is for someone on your team who is free to tag everyone in jail. (Note that jail is located on the opposing team's side). Specifically: * There is a constant - `FIELD_PADDING` - set to 20. This is the padding for the field. If it were zero, then the flags and jail would be exactly on the corners of the canvas. Since it is not, the flag and jail are 20 pixels away from the corners. * The blue flag (remember: blue team is on the upper half) is located at `(WIDTH - FIELD_PADDING, FIELD_PADDING) = (330, 20)` i.e. top-right corner. * The red flag is at `(FIELD_PADDING, HEIGHT - FIELD_PADDING) = (20, 330)` * The blue jail (where red members are kept) is at `(20, 20)` i.e. blue side, top left. * The red jail, where blue members are kept, is at `(330, 330)` Every team member starts randomly at a position `45 < x < 305` and `45 < y < 175` for blue and `175 < y < 305` for red. No team member can go within `DEFENSE_RADIUS = 25` pixels of their own flag or their own jail (unless, of course, your own flag was taken by an opposing bot, in which case you need to tag that bot). This is to prevent puppy-guarding like bots. If you go within that range, you are "pushed" back. Similarly, no team member can go out of bounds (less than zero or more than 350) -- if you do, you are pushed back to the nearest legal place you can be. Every time you move, you use up `strength`. Your `strength` starts out at `20` and is replenished by `2` every turn. The amount of strength you use is equal to the distance you travel. If your strength would become negative by moving to a certain place, you are prevented from making that move. It's probably a good idea to just go at speed `2` for normal chasing. You should only use higher speeds if you are close to winning and need the extra speed (in my opinion). **Spec**: The spec is quite similar to the Pixel Team Battlebots question. You should write a code block (remember, no global variables) in javascript. It should return an object with an `x`-value and `y`-value representing your change in x and change in y values. The following answer: ``` return { x: 0, y: -2 }; ``` always moves up, until it hits a wall. **You may not edit 8 hours after posting** *(except for LegionMammal98 who thought that the controller wasn't loading his/her code and didn't test)*. You have access to the following variables in your code: * `this` -- yourself, as a player (see below for what players are) * `move` -- the round number, starting at 0 * `tJailed` -- an array of all players on your team that are jailed * `eJailed` -- an array of all players on the opposing team that are jailed * `team` -- an array of all players on your team, NOT just the ones near you * `enemies` -- an array of all players on the other team, NOT just the ones near you * `tFlag` -- your flag (you're trying to protect it) * `eFlag` -- the other flag (you're trying to steal it) * `messages` -- explained below * A list of constants: `WIDTH = 350`, `HEIGHT = 350`, `FIELD_PADDING = 20`, `DEFENSE_RADIUS = 25`. Every "player" is an object with the following properties: * `x` and `y` * `strength` * `id` * `isJailed` -- true if the player is in jail Every flag has the following properties: * `x` and `y` * `pickedUpBy` -- the player who currently has the flag, or null if no player has the flag. Now, `messages` is an object that is shared among your teammates. *I don't care what you do with it.* The same object is shared and passed to every one of your team members. This is the only way you can communicate. You can attach properties to it, share objects, etc. It can be as big as you want -- no size limit. Every turn the following happens: * The list of players (both red and blue) is randomly shuffled for turn order. * Every player makes a move. * If any red team members touch (within 10 pixels of) any blue team members on red's side, send the blue team members to jail, and vice versa. A jailed player drops his/her flag and has strength drop to zero. Note that the step function (code you provide) is *still* called -- so you can get/set messages, but you can't move while in jail. * If any player is touching (within 10 pixels of) the other flag, then the other flag is marked as "picked up by" that player. When the player moves, the flag moves -- until the player is tagged and goes to jail, that is. * If any player is touching the other side's jail, free everyone in that jail. When a player is freed from jail, he/she is teleported to a random location on his/her side. Hints: * At least in regular capture the flag, attacks work much better when many players go at once, because it tends to confuse defenders as to which player they should chase. * Similarly, defenders might want to coordinate who they are chasing so that attacks don't go through Stack snippet: ``` window.onload=function(){(function(){function p(a,b,c,e){return Math.sqrt((a-c)*(a-c)+(b-e)*(b-e))}function l(a,b){this.x=this.y=0;this.id=a.id;this.title=a.title+" ["+this.id+"]";this.link=a.link||"javascript:;";this.team=b;this.isJailed=!1;this.flag=null;this.moveFn=new Function("move","tJailed","eJailed","team","enemies","tFlag","eFlag","messages","WIDTH","HEIGHT","FIELD_PADDING","DEFENSE_RADIUS",a.code);this.init()}function x(a,b){return Math.floor(Math.random()*(b-a))+a}function q(a,b){this.startX=this.x=a;this.startY= this.y=b;this.following=null}function t(a,b){return a===e&&b||a===h&&!b?{x:20,y:20}:{x:g.width-20,y:g.height-20}}function y(){var a,b=$("#redTeam"),c=$("#blueTeam");for(a=0;a<e.length;++a)e[a].addToDiv(b);for(a=0;a<h.length;++a)h[a].addToDiv(c)}function z(){d.clearRect(0,0,g.width,g.height);d.beginPath();d.moveTo(0,g.height/2);d.lineTo(g.width,g.height/2);d.stroke();var a=e.concat(h),b,c;for(b=a.length-1;0<b;b--){c=Math.floor(Math.random()*(b+1));var f=a[b];a[b]=a[c];a[c]=f}for(b=0;b<a.length;++b)a[b].step(u); for(b=0;b<e.length;++b)for(c=0;c<h.length;++c)10>p(e[b].x,e[b].y,h[c].x,h[c].y)&&(e[b].y<g.height/2&&e[b].goToJail(),h[c].y>g.height/2&&h[c].goToJail());for(b=0;b<a.length;++b)c=a[b].team===e!==!0?m:n,!c.following&&10>p(a[b].x,a[b].y,c.x,c.y)&&(c.following=a[b]);for(b=0;b<a.length;++b)if(c=t(a[b].team,!0),!a[b].isJailed&&10>p(a[b].x,a[b].y,c.x,c.y))for(c=a[b].team,f=0;f<c.length;++f)c[f].isJailed&&(c[f].isJailed=!1,c[f].init());m.follow();n.follow();b=m.y<g.height/2;c=n.y>g.height/2;b&&c&&alert("EXACT TIE!!!! This is very unlikely to happen."); b&&!c&&(alert("Blue wins!"),$("#playpause").click().hide());c&&!b&&(alert("Red wins!"),$("#playpause").click().hide());for(b=0;b<a.length;++b)a[b].draw(d);m.draw("red");n.draw("blue");u++}$.ajaxSetup({cache:!1});var e=[],h=[],g=$("canvas")[0],d=g.getContext("2d"),v,u=0,m={},n={},r=!0,A={},B={},w;l.prototype.init=function(){this.x=x(45,g.width-45);this.y=x(45,g.height/2);this.team===e&&(this.y+=g.height/2);this.strength=20};l.prototype.makeShallowCopy=function(){return{x:this.x,y:this.y,strength:this.strength, id:this.id,isJailed:this.isJailed}};l.prototype.goToJail=function(){this.isJailed=!0;var a=this.team===e!==!0?m:n;(this.team===e!==!0?m:n).following===this&&(a.following=null);a=t(this.team,!0);this.x=a.x;this.y=a.y;this.strength=0};l.prototype.step=function(a){function b(a,b,c){var e,d,f;for(e=0;e<a.length;++e)d=a[e],d!==C&&(f=d.makeShallowCopy(),d.isJailed?b.push(f):c.push(f))}var c=[],f=[],d=[],k=[],l=this.team===e?h:e,C=this,q=this.team===e?m:n,r=this.team===e?n:m;b(this.team,c,d);b(l,f,k);f= this.moveFn.call(this.makeShallowCopy(),a,c,f,d,k,q.copy(),r.copy(),this.team===e?A:B,g.width,g.height,20,25);"object"===typeof f&&"number"===typeof f.x&&"number"===typeof f.y&&(d=p(0,0,f.x,f.y),a=t(this.team,!1),c=this.team===e!==!1?m:n,d<=this.strength&&(this.strength-=d,this.x+=f.x,this.y+=f.y,0>this.x&&(this.x=0),0>this.y&&(this.y=0),this.x>g.width&&(this.x=g.width),this.y>g.height&&(this.y=g.height),f=p(this.x,this.y,c.x,c.y),d=p(this.x,this.y,a.x,a.y),25>f&&null===c.following&&(this.x=25*(this.x- c.x)/f*1.3+c.x,this.y=25*(this.y-c.y)/f*1.3+c.y),25>d&&(this.x=25*(this.x-a.x)/d*1.3+a.x,this.y=25*(this.y-a.y)/d*1.3+a.y)),this.isJailed||(this.strength+=2),20<this.strength&&(this.strength=20))};l.prototype.addToDiv=function(a){var b=$("<option>").text(this.title).val(this.id);a.find(".playersContainer").append(b)};l.prototype.draw=function(a){a.fillStyle=this.team===e?"red":"blue";a.beginPath();a.arc(this.x,this.y,5,0,2*Math.PI,!0);a.fill();!this.isJailed&&$("#labels").is(":checked")&&a.fillText(this.title, this.x+5,this.y+10)};q.prototype.draw=function(a){d.strokeStyle=a;d.beginPath();d.arc(this.x,this.y,5,0,2*Math.PI,!0);d.stroke();d.fillStyle=a;d.strokeRect(this.x-2,this.y-2,4,2);d.beginPath();d.moveTo(this.x-2,this.y);d.lineTo(this.x-2,this.y+3);d.stroke()};q.prototype.copy=function(){return{x:this.x,y:this.y,pickedUpBy:this.following&&this.following.makeShallowCopy()}};q.prototype.follow=function(){null!==this.following&&(this.x=this.following.x,this.y=this.following.y)};$("#newgame").click(function(){function a(a, b){w?b(w):$.get("https://api.stackexchange.com/2.2/questions/"+(49028).toString()+"/answers",{page:a.toString(),pagesize:100,order:"asc",sort:"creation",site:"codegolf",filter:"!JDuPcYJfXobC6I9Y-*EgYWAe3jP_HxmEee"},b,"json")}function b(g){w=g;g.items.forEach(function(a){function b(a){return $("<textarea>").html(a).text()}var d=4>=a.owner.user_id%10?e:h;a.owner.display_name=b(a.owner.display_name);if(!(a.hasOwnProperty("last_edit_date")&&28800<a.last_edit_date-a.creation_date&&33208!==a.owner.user_id|| -1<p.indexOf(a.owner.user_id))){p.push(a.owner.user_id);var g=c.exec(a.body);if(!(null===g||1>=g.length)){var f={};f.id=a.owner.user_id;f.title=a.owner.display_name;f.code=b(g[1]);f.link=a.link;d.push(new l(f,d))}}});g.has_more?a(++d,b):(console.log("Red team",e),console.log("Blue team",h),y(),clearInterval(v),r=!0,$("#playpause").show().click())}var c=/<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/,d=1,p=[];e=[];h=[];u=0;m=new q(20,g.height-20);n=new q(g.width-20,20);$(".teamColumn select").empty();var k= $("#testbotCode").val();0<k.length&&(console.log("Using test entry"),k={title:"TEST ENTRY",link:"javascript:;",code:k},$("#testbotIsRed").is(":checked")&&(k.id=-1,e.push(new l(k,e)),k.id=-3,e.push(new l(k,e))),$("#testbotIsBlue").is(":checked")&&(k.id=-2,h.push(new l(k,h)),k.id=-4,h.push(new l(k,h))));a(1,b)});$("#playpause").hide().click(function(){r?(v=setInterval(z,25),$(this).text("Pause")):(clearInterval(v),$(this).text("Play"));r=!r})})();} ``` ``` #main{padding:10px;text-align:center}#testbot{padding:10px;clear:both}.teamColumn{width:25%;padding:0 10px;border:3px solid;border-color:#000;text-align:center;height:500px;overflow:scroll;white-space:nowrap}.playersContainer p{padding:0;margin:0}#redTeam{float:left;border-color:red;color:red;background-color:#fee}#blueTeam{float:right;border-color:#00f;color:#00f;background-color:#fee}#arena{display:inline-block;width:40%;text-align:center}canvas{border:1px solid #000}select{width:100%} ``` ``` <script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><div id=main><div class=teamColumn id=redTeam><h1>Red Team</h1><select size=20 class=playersContainer></select></div><div id=arena><h1>Battlefield</h1><canvas width=350 height=350></canvas></div><div class=teamColumn id=blueTeam><h1>Blue Team</h1><select size=20 class=playersContainer></select></div><div id=loadingInfo><button id=newgame>New Game</button> <button id=playpause>Play</button><br><input type=checkbox id="labels"> Show labels</div></div><div id=testbot><textarea id=testbotCode placeholder="testbot code"></textarea><br><input type=checkbox id="testbotIsRed">Red Team<br><input type=checkbox id="testbotIsBlue">Blue Team<br></div> ``` Controller: <http://jsfiddle.net/prankol57/4L7fdmkk/> Full screen controller: <http://jsfiddle.net/prankol57/4L7fdmkk/embedded/result/> Let me know if there are any bugs in the controller. Note: If you go to the controller and think that it isn't loading anything, press "New Game." It only loads everything after you press "New Game" so that it can load all the bots and possible test bots at once. Good luck. --- If anyone wants to see an example game, I made an example bot that you can copy and paste into the "testbot" textarea (the testbot creates two duplicates on each team; check both red team and blue team): ``` var r2 = Math.sqrt(2); if (this.id === -1) { // red team 1 // go after flag regardless of what is going on if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) { return { x: 0, y: 2 }; } return { x: this.x < eFlag.x ? r2 : -r2, y: this.y < eFlag.y ? r2 : -r2 }; } if (this.id === -2) { // blue team 1 // a) go after opposing team members on your side b) get the other flag if no enemies on your side var closestEnemy = null; for (var i = 0; i < enemies.length; ++i) { if (enemies[i].y < HEIGHT/2 && (closestEnemy === null || enemies[i].y < closestEnemy.y)) { closestEnemy = enemies[i]; } } if (closestEnemy !== null) { return { x: this.x < closestEnemy.x ? r2 : -r2, y: this.y < closestEnemy.y ? r2 : -r2 }; } if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) { return { x: 0, y: -2 }; } return { x: this.x < eFlag.x ? r2 : -r2, y: this.y < eFlag.y ? r2 : -r2 }; } if (this.id === -3) { // red team 2 // a) defend the flag b) if at least half of enemies in jail and no enemies on this side, free jailed reds and quickly return var closestEnemy = null; for (var i = 0; i < enemies.length; ++i) { if (enemies[i].y > HEIGHT/2 && (closestEnemy === null || enemies[i].y > closestEnemy.y)) { closestEnemy = enemies[i]; } } if (closestEnemy !== null) { return { x: this.x < closestEnemy.x ? r2 : -r2, y: this.y < closestEnemy.y ? r2 : -r2 }; } if (enemies.length / eJailed.length <= 1 && tJailed.length > 0) { return { x: this.x < FIELD_PADDING ? r2 : -r2, y: this.y < FIELD_PADDING ? r2 : -r2 }; } if (this.y < 350/2) return {x: 0, y: 2}; return { x: this.x < tFlag.x ? r2 : -r2, y: this.y < tFlag.y ? r2 : -r2 }; } if (this.id === -4) { // blue team 2 // a) try freeing jail if there are jailed team members b) capture the flag if (tJailed.length > 0) { return { x: this.x < WIDTH - FIELD_PADDING ? r2 : -r2, y: this.y < HEIGHT - FIELD_PADDING ? r2 : -r2 }; } if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) { return { x: 0, y: -2 }; } return { x: this.x < eFlag.x ? r2 : -r2, y: this.y < eFlag.y ? r2 : -r2 }; } ``` [Answer] # Red - Lazy Jail Hog | Lazy Flagger Moves towards the closer of these two: blue's jail, or blue's flag. * If going for the jail, will move into the jail and stop. (Since blue can't touch its own jail, it will be invincible and automatically free all allies) * If going for the flag, it will blindly move for the flag and return. Finally, its brain is entirely stored in `messages[29354]` and initialized on the first move only. Thus, if allies find a better use for this bot, they can replace its brain for their higher purpose. ``` if (move === 0) { //On the first turn, set messages[this.id] to the function I will call to move me messages[this.id] = function(move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages) { //Arbitrary function to move to a point at some speed, which may be in the point // If we are at the point, undefined is returned var moveTo = function(p, max) { if (!p) { return {x:0, y:0}; } max = Math.min(this.strength, max || p.max || 2); var dx = p.x - this.x; var dy = p.y - this.y; var dist = Math.abs(dx)+Math.abs(dy); if (dist === 0) { return undefined; } else if (dist < max) { return {x: dx, y: dy}; } var ux = Math.floor(max * dx / dist); var uy = Math.floor(max * dy / dist); while (Math.abs(ux) + Math.abs(uy) < max) { if (ux + this.x !== p.x) { ux += ux > 0 ? 1 : -1; } else if (uy + this.y !== p.y) { uy += uy > 0 ? 1 : -1; } else { break; } } return {x: ux, y:uy}; }.bind(this); //Set the way points var points = []; if (this.x > WIDTH/2) { points.push({x: WIDTH-FIELD_PADDING, y:HEIGHT/2+5}); points.push({x: WIDTH-FIELD_PADDING, y:FIELD_PADDING, max: 5}); points.push({x: WIDTH-FIELD_PADDING, y:HEIGHT/2+25, max: 5}); } else { points.push({x: FIELD_PADDING, y:HEIGHT/2+5}); points.push({x: FIELD_PADDING, y:FIELD_PADDING, max: 5}); points.push(undefined); //Special case to do nothing / hog the jail } //Move through the points var state = messages[this.id].state || 0; var ret; while (!ret) { //Special case: if we were doing nothing, make sure we're where we think we were if (!points[state]) { ret = moveTo(points[state-1]); if (ret) { state = 0; } } //Move to the next point ret = moveTo(points[state]); if (!ret) { state = (state + 1) % points.length; } } messages[this.id].state = state; return ret; }; } //Move me based on that function, which may be changed by my allies return messages[this.id].call(this, move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages); ``` [Answer] # Red - The Guard This bot will guard the flag pretty good. Don't get in its way... ``` if (!messages[this.id]) { //On the first turn, set messages[this.id] to the function I will call to move me. You can replace this function on subsequent turns //to control it. Additionally, you can use it as a library to find one of the best places to go to defend. messages[this.id] = function(move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages, WIDTH, HEIGHT, FIELD_PADDING, DEFENSE_RADIUS) { var distance = function(p1, p2) { var dx = p1.x - p2.x; var dy = p1.y - p2.y; return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); } var moveTo = function(p) { if (!p) { return {x:0, y:0}; } var dx = p.x - this.x; var dy = p.y - this.y; var max = this.strength; var dist = distance(p, this); if (dist < max) { return {x: dx, y: dy}; } dx = dx * max / dist; dy = dy * max / dist; while (Math.sqrt(Math.abs(dx)+Math.abs(dy)) > max) { if (dx > dy) { dx = dx - 0.001; } else { dy = dy - 0.001; } } return {x: dx, y:dy}; }.bind(this); if (tFlag.pickedUp) { if (tFlag.y - HEIGHT / 2 > distance(this, {x: tFlag.x, y: HEIGHT / 2})) { return moveTo(tFlag); } else { return moveTo({y: Math.min(this.y, tFlag.y), x: tFlag.x }); } } if (eFlag.pickedUp == this.id) { return moveTo({x: x, y: HEIGHT / 2}); } var targetPoints = []; var crossedBorder = false; var weightedMiddlePoint = function(enemy) { var x1 = (enemy.x + tFlag.x) / 2; var y1 = (enemy.y + tFlag.y) / 2; var w = 1/Math.pow(distance(enemy, tFlag),2); return {x:x1,y:y1,w:w}; } for (var i = 0; i < enemies.length; i++) { var enemy = enemies[i]; if (enemy.isJailed){ continue; } if (enemy.y > HEIGHT / 2) { crossedBorder = true; } } for (var i = 0; i < enemies.length; i++) { enemy = enemies[i]; if (enemy.isJailed){ continue; } if (crossedBorder) { if (enemy.y > HEIGHT / 2) { targetPoints.push(weightedMiddlePoint(enemy)); } } else { targetPoints.push(weightedMiddlePoint(enemy)); } } if (targetPoints.length == 0) { return moveTo(eFlag); } var sumX = 0; var sumY = 0; var sumW = 0; for (var i = 0; i < targetPoints.length; i++) { point = targetPoints[i]; sumX += point.x * point.w; sumY += point.y * point.w; sumW += point.w; } var targetPoint = {x: sumX / sumW, y: sumY / sumW}; return moveTo(targetPoint); }; } return messages[this.id].call(this, move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages, WIDTH, HEIGHT, FIELD_PADDING, DEFENSE_RADIUS); ``` [Answer] # Blue - LegionMammal978 ``` function repeat(el, n) // Helper function { var rtn = []; for (var i = 0; i < n; i++) rtn.push(el); return rtn; } function sign(n) { return n ? n < 0 ? -1 : 1 : 0; } // Another helper function if (!messages[this.id]) messages[this.id] = { "dir": 1 }; if (this.isJailed) // Oh noes, I'm in jail! { console.log(this.id, messages); if (!messages[this.id].jailTicks) messages[this.id].jailTicks = 0; messages[this.id].jailTicks++; // Call for help! messages.callsForHelp = repeat(["Help!", this.id, this.x, this.y], messages[this.id].jailTicks); return { "x": 0, "y": 0 }; } if (messages[this.id].jailTicks) if (!(delete messages[this.id].jailTicks && delete messages.callsForHelp)) // Cleanliness messages[this.id].jailTicks = messages.callsForHelp = undefined; // ... var bounds = Math.floor(HEIGHT / 2); // Be safe with fractions if (this.y > bounds - 5) // Get back to shelter! return { "x": 0, "y": this.y - this.strength <= bounds - 5 ? bounds - 5 - this.y : -4 }; var target = { "none": true, "x": WIDTH << 1, "y": HEIGHT << 1 }; enemies.forEach(function (en) { if (!en.isJailed && en.y < bounds - 5 && Math.abs(en.x - this.x) < Math.abs(target.x - this.x) && Math.abs(en.y - this.y) < Math.abs(target.y - this.y)) target = en; }, this); if (target.none) { if (this.y < bounds - 5) return { "x": 0, "y": 2 }; var speed = this.strength < 30 ? 1 : 2; if (this.x == 5 || this.x == WIDTH - 5) messages[this.id].dir = -messages[this.id].dir; return { "x": speed * messages[this.id].dir, "y": 0 }; } if (this.x - target.x >= 0 && this.x - target.x < this.strength) { if (this.y - target.y > 0 && this.y - target.y < this.strength + target.x - this.x) return { "x": this.x - target.x, "y": this.y - target.y }; if (target.y - this.y > 0 && target.y - this.y < this.strength + target.x - this.x) return { "x": this.x - target.x, "y": target.y - this.y }; } if (target.x - this.x > 0 && target.x - this.x < this.strength) { if (this.y - target.y > 0 && this.y - target.y < this.strength + this.x - target.x) return { "x": target.x - this.x, "y": this.y - target.y }; if (target.y - this.y > 0 && target.y - this.y < this.strength + this.x - target.x) return { "x": target.x - this.x, "y": this.y - target.y }; } return { "x": 6 * sign(target.x - this.x), "y": 6 * sign(target.y - this.y) }; ``` Defense bot. [Answer] # Red - Flag Hunter ``` var distance = function(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } var moveTo = function(x, y, max) { if (max > this.strength) max = this.strength; var dX = x - this.x; var dY = y - this.y; var dist = distance(x, y, this.x, this.y); if (dist <= max) { return {x: dX, y: dY}; } dX = dX * max / dist; dY = dY * max / dist; while (Math.sqrt(Math.abs(dX)+Math.abs(dY)) > max) { if (dX > dY) { dX = dX - 0.001; } else { dY = dY - 0.001; } } return {x: dX, y:dY}; }.bind(this); var getSurroundingPoints = function(x, y, dist) { var points = []; for (var i = x - dist; i <= x + dist; i+= 0.2) { for (var j = y - dist; j <= y + dist; j+= 0.2) { if (i >= 0 && j >= 0 && j <= 180 && distance(i,j,x,y) <= dist) { points.push({x: i, y: j, danger: 0}); } } } return points; } if (this.isJailed) { return {x:0, y:0}; } var destination = {x: eFlag.x, y: eFlag.y}; //default: try to get the flag if (eFlag.pickedUpBy != null) { //we got the flag if (eFlag.pickedUpBy.id == this.id) { //I got the flag => get back to the red side if (distance(this.x, this.y, this.x, 175.1) <= this.strength) { return moveTo(this.x, 175.1, this.strength); } destination.x = this.x; destination.y = 180; } else { //someone else got the flag => free those in the jail destination.x = 20; destination.y = 20; } } else if (this.y > HEIGHT / 2) { //I am on the red side return moveTo(175, 175, 2); } else if (distance(this.x, this.y, eFlag.x, eFlag.y) <= 15) { //I am in the safe zone (flag) if (this.strength < 20) return {x:0, y:0}; return moveTo(eFlag.x, eFlag.y, 2); //get the flag } else if (distance(this.x, this.y, eFlag.x, eFlag.y) - this.strength <= 15) { //I can reach the safe zone (flag) return moveTo(eFlag.x, eFlag.y, distance(this.x, this.y, eFlag.x, eFlag.y) - 14); } else if (distance(this.x, this.y, 20, 20) < 10) { //I am in the safe zone (jail) if (this.strength < 20) return {x:0, y:0}; } else if (distance(this.x, this.y, eFlag.x, eFlag.y) - this.strength <= 15) { //I can reach the safe zone (jail) return moveTo(20, 20, this.strength); } //I am somewhere on the blue side var points = getSurroundingPoints(this.x, this.y, this.strength); var me = this; points.forEach(function(point) { if (point.y < 175) { enemies.forEach(function(enemy) { if (distance(enemy.x, enemy.y, point.x, point.y) <= enemy.strength+10) { point.danger += 5; } }); if (distance(me.x, me.y, point.x, point.y) <= 2 && point.danger == 0) { point.danger--; } } }); var bestPoint = points[0]; points.forEach(function(point) { if (point.danger < bestPoint.danger || (point.danger == bestPoint.danger && distance(point.x, point.y, destination.x, destination.y) < distance(bestPoint.x, bestPoint.y, destination.x, destination.y))) { bestPoint = point; } }); return moveTo(bestPoint.x, bestPoint.y, this.strength); ``` Tries to get the flag. If someone else already got it, Flag Hunter walks towards the jail, either confusing the enemy or freeing his team members. [Answer] ## Blue - A jolly good fellow First attempt both at programming in Javascript, and at code-golf. It will chase anything that comes too close to the flag, trying to front-run their moves. Otherwise, it will run to rescue team-mates in jail, or lazily try to get to the other team's flag. ``` // Euclidean distance var distance = function(p1,p2){ return Math.sqrt( (p1.x - p2.x)**2 + (p1.y - p2.y)**2 ); } // points from p1 to p2 var direction = function(p1, p2){ return Math.atan2( p2.y - p1.y, p2.x - p1.x); } //moving var move2 = function(dir, step){ if(isNaN(dir)){ dir = 0; }; if(isNaN(step)){ step = 0; }; return { x: Math.cos(dir)*step, y: Math.sin(dir)*step }; } var intercept_at = function(me, they, field){ if ( distance(me, they)<me.strength ){ return they; } //console.log("I am at (", me.x, me.y, ") "); //console.log("They are at (", they.x, they.y, ") "); //first goal if( field.my_flag.pickedUpBy == null ){ their_goal = field.my_flag; eta = (distance(they, their_goal) - they.strength)/2; their_dir = direction(they, their_goal); for( var i=1; i<eta; i++){ they_next = { x: they.x + Math.cos(their_dir)*(they.strength/2 + (i+1)*2), y: they.y + Math.sin(their_dir)*(they.strength/2 + (i+1)*2) }; if( (distance(me, they_next) )<(1.95*i) ){ //console.log("goal is flag at (", their_goal.x, their_goal.y, ") "); //console.log("I can reach it at (", they_next.x, they_next.y, ") in less than ", i); return they_next; } } // second goal } my_flag = field.my_flag; their_goal = { x: my_flag.x, y:field.h/2 - 5}; eta = (distance(my_flag, their_goal) - they.strength)/2; their_dir = direction(my_flag, their_goal); for( var i=0; i<eta; i++){ they_next = { x: my_flag.x + Math.cos(their_dir)*(they.strength/2 + (i+1)*2), y: my_flag.y + Math.sin(their_dir)*(they.strength/2 + (i+1)*2) }; if( (distance(me, they_next) )<(1.95*i) ){ //console.log("goal is escaping at (", their_goal.x, their_goal.y, ") "); //console.log("I can front-run it at (", they_next.x, they_next.y, ") in less than ", i); return they_next; } } //console.log("Goose chase at (", they.x, they.y, ") "); return they; } var intercept = function(me, they, field){ they_at = intercept_at(me, they, field); they_at.y = Math.min(they_at.y, field.h/2-5) dist2me = distance(me, they_at); dir2me = direction(me, they_at); if ( dist2me<me.strength ){ return move2(dir2me, dist2me); }else{ return move2(dir2me, 2); } } var closest_enemy = function(my_flag, enemies){ cur_tgt_num = null; cur_tgt_dst = 999; for( var i=0; i<enemies.length; i++){ if(!enemies[i].isJailed){ cur_dst = distance(enemies[i], my_flag); if ( cur_dst < cur_tgt_dst ){ cur_tgt_dst = cur_dst; cur_tgt_num = i; } } } return enemies[cur_tgt_num]; } var enemies_closer_than = function(enemies, radius, field){ closer_than = 0; for( var i = 0; i<enemies.length; i++){ if(!enemies[i].isJailed){ closer_than = closer_than + ( distance(enemies[i], field.my_flag)<radius ); } } return closer_than; } var team_jailed = function(team){ for( var i = 0; i<team.length; i++){ if(team[i].isJailed){ return team[i]; } } return null; } var bound_positions = function(p0, field){ p0.x = Math.max(0, Math.min(p0.x, field.w)); p0.y = Math.max(0, Math.min(p0.y, field.h)); return p0; } var avoid_obstacle = function(me, goal, obstacle, field, can_run){ //we know that there is a safe haven if( distance(me, goal)<me.strength && can_run){ return move2(direction(me, goal), me.strength) } if( obstacle == null ){ return move2(direction(me, goal), 2); } ob_dir = direction(me, obstacle); if( distance(me, obstacle) < Math.sqrt(2)*(4+obstacle.strength)){ me_next1 = bound_positions({x: me.x - 4*Math.cos(ob_dir),y: me.y - 4*Math.sin(ob_dir)}, field); me_next2 = bound_positions({x: me.x - 4*Math.sin(ob_dir),y: me.y - 4*Math.cos(ob_dir)}, field); me_next3 = bound_positions({x: me.x - 4*Math.sin(ob_dir),y: me.y - 4*Math.cos(ob_dir)}, field); if( distance(goal, me_next1) < distance(goal, me_next2) ){ if( distance(goal, me_next1) < distance(goal, me_next3) ){ me_next = me_next1; }else{ me_next = me_next3; } }else{ if( distance(goal, me_next2) < distance(goal, me_next3) ){ me_next = me_next2; }else{ me_next = me_next3; } } //console.log("Escaping from (", obstacle.x, obstacle.y, ")"); return move2(direction(me, me_next), 4); } eta = (distance(me, goal)/2); my_dir = direction(me, goal); me_next = me; i=0; while(i<eta && (distance(me_next, obstacle) > obstacle.strength+2*i)){ i++; me_next = {x: me_next.x + i*Math.cos(my_dir),y: me_next.y + i*Math.sin(my_dir)}; me_next = bound_positions(me_next, field); if( distance(me_next, obstacle) < obstacle.strength+2*i ){ me_next1 = {x: me_next.x + i*Math.sin(ob_dir),y: me_next.y - i*Math.cos(ob_dir)}; me_next2 = {x: me_next.x - i*Math.sin(ob_dir),y: me_next.y + i*Math.cos(ob_dir)}; if( distance(goal, me_next1) > distance(goal, me_next2) ){ me_next = bound_positions(me_next2, field); }else{ me_next = bound_positions(me_next1, field); } } } if( distance(me_next, obstacle) > obstacle.strength+2*i ){ //console.log("Trying to reach goal at (", goal.x, goal.y, ") by pointing at (",me_next.x, me_next.y,")"); return move2(direction(me, me_next), 2); } //console.log("Waiting to reach (", goal.x, goal.y,")"); my_dir = direction(me, goal); me_next = { x: me.x + Math.cos(my_dir)*6, y: me.y + Math.sin(my_dir)*6 } for( var i=0; i<field.team.length; i++){ me_next.x = me_next.x - Math.sign(field.team[i].x - me_next.x); me_next.y = me_next.y - Math.sign(field.team[i].y - me_next.y); } return move2(direction(me, me_next), Math.floor(Math.random() * 2)); } var field = { w: WIDTH, h: HEIGHT, g: DEFENSE_RADIUS, my_flag: tFlag, their_flag: eFlag, team: team, enemies: enemies }; var n_enemy = enemies.length; if( enemies_closer_than(enemies, field.h*0.67, field)>0 || tFlag.pickedUpBy !== null){ //console.log("My flag is in danger"); // directive defend messages[123 + this.id] = 'defend_own_flag'; if ( tFlag.pickedUpBy !== null ) { return intercept(this, tFlag.pickedUpBy, field); }else{ return intercept(this, closest_enemy(tFlag, enemies), field); } }else{ if( tJailed.length>0 ){ // directive support console.log("rescueing team member"); console.log(tJailed); return avoid_obstacle(this, tJailed[0], closest_enemy(this, enemies), field, 0); }else{ // directive attack messages[123 + this.id] = 'capture_enemy_flag'; if ( eFlag.pickedUpBy == null ){ //console.log("Going to capture the flag"); return avoid_obstacle(this, eFlag, closest_enemy(this, enemies), field, 0) }else if (this.id == eFlag.pickedUpBy.id){ //console.log("I have the flag"); return avoid_obstacle(this, {x:this.x, y:field.h/2 - 1}, closest_enemy(this, enemies), field, 1); }else { //console.log("Someone else has the flag"); return avoid_obstacle(this, eFlag, closest_enemy(this, enemies), field, 0); } } } return move2(0,0); ``` ]
[Question] [ Your task is, given a square grid of digits (`0-9`), output one of the ways that the digits can be grouped such that: 1. Each digit is part of exactly one group 2. All groups have the same number of digits 3. All groups are bounded by one polygon-like shape (this means that every digit in the group is next to [left, right, up, down] at least one other digit of the same group, unless each group has 1 element). 4. All groups have the same sum The input grid will always be a square: You may choose any input method you would like (including supplying arguments to a function or method). In addition, the input will supply the number of groups that your program should group the digits into. Example input: Suppose your input format is `stringOfDigits numberOfGroups`. An example input would be: ``` 156790809 3 ``` which would translate to (a grid of `sqrt(9) * sqrt(9)`) ``` 1 5 6 7 9 0 8 0 9 ``` which you would have to divide into 3 groups, each of which should have `9 / 3 = 3` elements with the same sum. Output: Output should be the string of digits, with optional spaces and newlines for formatting, with each digit followed by a letter `a-z` indicating its group. There should be exactly `numberOfTotalDigits / numberOfGroups` elements in each group. You will never have to divide something into more than 26 groups. Example output: ``` 1a 5a 6b 7c 9a 0b 8c 0c 9b ``` Note that replacing all `a`s with `b`s and `b`s with `a`s is equally valid. As long as each group is denoted by a distinct letter, the output is valid. In addition, I expect most programs to output something along the lines of this, because newlines/spaces are optional: ``` 1a5a6b7c9a0b8c0c9b ``` In this case, adding all digits of group `a`, `b`, or `c` makes 15. In addition, all groups are bound by some polygon. Invalid outputs: ``` 1a 5a 6b 7c 9a 0c 8c 0b 9b ``` because the groups do not form polygons (specifically, the `6b` is isolated and `0c` is also lonely). ``` 1a 5a 6b 7c 9a 0b 8c 0b 9b ``` because the group `b` has 4 elements while `c` only has 2. Etc. If there is no valid solution, your program may do anything (i.e. stop, crash, run forever) but if your program prints `None` when there is no valid solution, `-15` to your score. If there is more than one solution, you only have to print one, but `-20` if your program prints all of them separated by some delimiter. This is code golf, so shortest code (with bonuses) wins! [Answer] # [Pyth](https://github.com/isaacg1/pyth), 122 - 20 - 15 = 87 ``` =Z/lzQ=ks^lz.5Jm]dUzL[-bk+bk?tb%bkb?hb%hbkb)FNJIgNZB~Jm+NksmybN;|jbS{msm+@zk@S*Z<GQxsdkUzfqSsTUz^fqsmv@*ZzbY/smvdzQJQ"None ``` Changes: * 130 -> 120: Switched to newline separated input. * 120 -> 134: Fixed a bug involving groups not of size equal to the side length of the matrix. * 134 -> 120: Prints all solutions, including ones equivalent under group renaming. * 120 -> 122: Fixed a bug where only paths would be generated, instead of all legal groups. Test run: ``` pyth programs/sum_group.pyth <<< '156790809 3' 1a5a6b7c9a0b8c0c9b 1a5a6c7b9a0c8b0b9c 1b5b6a7c9b0a8c0c9a 1b5b6c7a9b0c8a0a9c 1c5c6a7b9c0a8b0b9a 1c5c6b7a9c0b8a0a9b pyth programs/sum_group.pyth <<< '156790808 3' None pyth programs/sum_group.pyth <<< '1111 2' 1a1a1b1b 1a1b1a1b 1b1a1b1a 1b1b1a1a ``` Explanation: ``` Pyth code (Pseudo)-Python code Comments (implicit) z = input() z is the digit string (implicit) Q = eval(input()) S is the number of groups (implicit) G = 'abcdefghijklmnopqrstuvwxyz' =Z/lzQ Z = len(z)/Q Z is the size of each group. =ks^lz.5 k = int(len(z) ** .5) k is the side length of the matrix. Jm]dUz J = map(lambda d:[d], range(len(z))) Locations are encoded as numbers. L def y(b): return y will be the transition function. [-bQ [b-k, Move up - the row above is k less. +bQ b+k, Move down - the row below is k more. ?tb%bkb b-1 if b%k else b Move left, unless at the left edge. ?hb%hbkb) b+1 if (b+1)%k else b] Move right, unless at right edge. FNJ for N in J: This constructs the list of all IgNZB if N[Z-1]: break Z-length connected groups. ~Jm+Nk J+=map(lambda k: N+[k], Append to J the group of N + smybN sum(map(lambda b: anything reachable from y(b),N))) anywhere in N. ; (end for) | or Print first truthy thing between S{ sorted(set( Unique elements in sorted order of ms map(lambda b:sum( Map+sum over allowable combinations m+@zd map(lambda d:z[d]+ Character in original digit string @S*Z<GQ sorted(G[:Q]*Z)[ Repeated and sorted early alphabet xsbd sum(b).index(d)], At index of number in sum of groups Uz range(len(z))) Over possible indexes. f filter(lambda T: To generate allowable combinations, we will filter all groups of Q paths. qSsTUz sorted(sum(T)) == range(len(z)) Ensure all locations are visited. ^ Combinations of f filter(lambda Y: Filter over connected Z-length groups qsm equal(sum(map(lambda k: Sum of the values of the group v@*ZzkY eval((z*Z)[k]),Y) In the original digit string /smvbzQ sum(map(lambda b:eval(b),z))/Q must equal the sum of all values in z divided by the number of groups. J J Filter over connected Z-length groups Q Q Combinations of length Q "None "None" If the above was empty, print "None" ``` [Answer] # JavaScript (ES6) 361 (376-15) ~~372~~ (Maybe can still be golfed a little more) As a function, first param is the string of digits and second param is the number of groups. It's a naive recursive search, stopping at first solution found (no -20 bonus). Need some more test cases to verify performance on some bigger input. ``` F=(g,n,l=g.length,i=w=Math.sqrt(l),o=s=h='', R=(g,p,k,j=l/n,t=s/n,v=0,h=String.fromCharCode(97+k))=>( t-=g[p],!(t<0)&&( g=[...g],g[p]=h, S=f=>g.some((c,p)=>c<':'&&f(p)), --j?S(p=>(g[p+1]==h|g[p-1]==h|g[p+w+1]==h|g[p-w-1]==h)?v=R(g,p,k,j,t):0) :t?0:k?S(p=>v=R(g,p,k-1)):v=g ),v ) )=>([for(c of g)(s-=-c,h+=--i?c:(i=w,c+':'))],h=R(g=h,-1,n,1))?h.map((c,p)=>o+=c!=':'?g[p]+c:'')&&o:'None' ``` **Ungolfed & Explained** ``` F=(g,n)=> { var l = g.length, // string size, group size is l/n w = Math.sqrt(l), // width of grid s,i,h,o; // Build a new string in h, adding rows delimiters that will act as boundary markers // At the same time calculate the total sum of all digits h='', // Init string s = 0, // Init sum i = w, // Init running counter for delimiters [for(c of g)( s -= -c, // compute sum using minus to avoid string concatenation h += --i ? c : (i=w, c+':') // add current char + delimiter when needed )]; // Recursive search // Paramaters: // g : current grid array, during search used digits are replaced with group letters // p : current position // k : current group id (start at n, decreaseing) // j : current group size, start at l/n decreasing, at 0 goto next group id // t : current group sum value, start at s/n decreasing var R=(g,p,k,j,t)=> { var v = 0, // init value to return is 0 h = String.fromCharCode(97+k); // group letter from group t-=g[p]; // subtract current digit if (t<0) // exceed the sum value, return 0 to stop search and backtrak return 0; g=[...g]; // build a new array from orginal parameter g[p] = h; // mark current position // Utility function to scan grid array // call worker function f only for digit elements // skipping group markers, row delimieters and out of grid values (that are undefined) // Using .some will return ealry if f returns truthy var S=f=>g.some((c,p)=>c<':'&&f(p)); if (--j) // decrement current group size, if 0 then group completed { // if not 0 // Scan grid to find cells adiacent to current group and call R for each S( p => { if (g[p+1]==h|g[p-1]==h|g[p+w+1]==h|g[p-w-1]==h) // check if adiacent to a mark valued h { return v=R(g,p,k,j,t) // set v value and returns it } }) // here v could be 0 or a full grid } else { // special case: at first call, t is be NaN because p -1 (outside the grid) // to start a full grid serach if (t) // check if current reached 0 return 0; // if not, return 0 to stop search and backtrak if (k) // check if current group completed { // if not at last group, recursive call to R to check next group S( p => { // exec the call for each valid cell still in grid // params j and t start again at init values return v=R(g,p,k-1,l/n,s/n) // set value v and returns it }) // here v could be 0 or a full grid } else { return g; // all groups checked, search OK, return grid with all groups marked } } return v }; g = h; // set g = h, so g has the row boundaries and all the digits h=R(h,-1,n,1); // first call with position -1 to and group size 1 to start a full grid search if (h) // h is the grid with group marked if search ok, else h is 0 { o = ''; // init output string // build output string merging the group marks in h and the original digits in g h.map( (c,p) => o += c>':' ? g[p]+c: '') // cut delimiter ':' return o; } return 'None'; } ``` **Test** In FireFox/FireBug console `F("156790809",3)` output `1c5c6b7a9c0b8a0a9b` `F("156790819",3)` output `None` ]
[Question] [ A *bit-counting comparator* (BCC) is a logic circuit that takes some number of counting inputs `A1, A2, A3, ..., An` as well as inputs `B1, B2, B4, B8, ...` representing a number. It then returns `1` if the total number of `A` inputs that are on is greater than the number represented in binary by the `B` inputs (e.g. `B1`, `B2`, and `B8` would make the number `11`), and `0` otherwise. For example, for a bit-counting comparator that takes `5` inputs, of which `A2`, `A4`, `A5`, and `B2` are set to `1`, will return `1` because there are 3 `A` inputs that are on, which is greater than `2` (the number represented by only `B2` being on). Your task is to create a bit-counting comparator that takes a total of 16 `A` inputs and 4 `B` inputs (representing bits from `1` to `8`), using only two-input NAND gates, and using as few NAND gates as possible. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores: * `NOT: 1` * `AND: 2` * `OR: 3` * `XOR: 4` Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate. The logic circuit that uses the fewest NAND gates to produce a correct construction wins. [Answer] ## 169 nands Adds up the A's to get A{1,2,4,8,16}. Then does a binary comparison with the Bs. I use a few more building blocks: * FA = full adder, 9 nands ([from here](http://quoans.wordpress.com/2009/02/06/digital-lab-expt-3-fullhalf-adder-using-nand-only/)) * HA = half adder, 7 nands (same ref) * EQ = equality, 5 gates (a.k.a. xnor) The half and full adders have 2 outputs - they are distinguished with an r for result and c for carry. The A{1,2,4,8,16} are the outputs from the half adders. ![enter image description here](https://i.stack.imgur.com/I5Ify.png) [Answer] # 751 nand gates ``` module BitCountingComparator(A, B, O); input [15:0] A; input [3:0] B; output O; wire [15:1] is; assign is[1] = A[0] | A[1] | A[2] | A[3] | A[4] | A[5] | A[6] | A[7] | A[8] | A[9] | A[10] | A[11] | A[12] | A[13] | A[14] | A[15]; wire [14:0] and2; assign and2[0] = A[0] & A[1]; assign and2[1] = A[1] & A[2]; assign and2[2] = A[2] & A[3]; assign and2[3] = A[3] & A[4]; assign and2[4] = A[4] & A[5]; assign and2[5] = A[5] & A[6]; assign and2[6] = A[6] & A[7]; assign and2[7] = A[7] & A[8]; assign and2[8] = A[8] & A[9]; assign and2[9] = A[9] & A[10]; assign and2[10] = A[10] & A[11]; assign and2[11] = A[11] & A[12]; assign and2[12] = A[12] & A[13]; assign and2[13] = A[13] & A[14]; assign and2[14] = A[14] & A[15]; wire [13:0] and3; assign and3[0] = and2[0] & A[2]; assign and3[1] = and2[1] & A[3]; assign and3[2] = and2[2] & A[4]; assign and3[3] = and2[3] & A[5]; assign and3[4] = and2[4] & A[6]; assign and3[5] = and2[5] & A[7]; assign and3[6] = and2[6] & A[8]; assign and3[7] = and2[7] & A[9]; assign and3[8] = and2[8] & A[10]; assign and3[9] = and2[9] & A[11]; assign and3[10] = and2[10] & A[12]; assign and3[11] = and2[11] & A[13]; assign and3[12] = and2[12] & A[14]; assign and3[13] = and2[13] & A[15]; wire [12:0] and4; assign and4[0] = and3[0] & A[3]; assign and4[1] = and3[1] & A[4]; assign and4[2] = and3[2] & A[5]; assign and4[3] = and3[3] & A[6]; assign and4[4] = and3[4] & A[7]; assign and4[5] = and3[5] & A[8]; assign and4[6] = and3[6] & A[9]; assign and4[7] = and3[7] & A[10]; assign and4[8] = and3[8] & A[11]; assign and4[9] = and3[9] & A[12]; assign and4[10] = and3[10] & A[13]; assign and4[11] = and3[11] & A[14]; assign and4[12] = and3[12] & A[15]; wire [11:0] and5; assign and5[0] = and4[0] & A[4]; assign and5[1] = and4[1] & A[5]; assign and5[2] = and4[2] & A[6]; assign and5[3] = and4[3] & A[7]; assign and5[4] = and4[4] & A[8]; assign and5[5] = and4[5] & A[9]; assign and5[6] = and4[6] & A[10]; assign and5[7] = and4[7] & A[11]; assign and5[8] = and4[8] & A[12]; assign and5[9] = and4[9] & A[13]; assign and5[10] = and4[10] & A[14]; assign and5[11] = and4[11] & A[15]; wire [10:0] and6; assign and6[0] = and5[0] & A[5]; assign and6[1] = and5[1] & A[6]; assign and6[2] = and5[2] & A[7]; assign and6[3] = and5[3] & A[8]; assign and6[4] = and5[4] & A[9]; assign and6[5] = and5[5] & A[10]; assign and6[6] = and5[6] & A[11]; assign and6[7] = and5[7] & A[12]; assign and6[8] = and5[8] & A[13]; assign and6[9] = and5[9] & A[14]; assign and6[10] = and5[10] & A[15]; wire [9:0] and7; assign and7[0] = and6[0] & A[6]; assign and7[1] = and6[1] & A[7]; assign and7[2] = and6[2] & A[8]; assign and7[3] = and6[3] & A[9]; assign and7[4] = and6[4] & A[10]; assign and7[5] = and6[5] & A[11]; assign and7[6] = and6[6] & A[12]; assign and7[7] = and6[7] & A[13]; assign and7[8] = and6[8] & A[14]; assign and7[9] = and6[9] & A[15]; wire [8:0] and8; assign and8[0] = and7[0] & A[7]; assign and8[1] = and7[1] & A[8]; assign and8[2] = and7[2] & A[9]; assign and8[3] = and7[3] & A[10]; assign and8[4] = and7[4] & A[11]; assign and8[5] = and7[5] & A[12]; assign and8[6] = and7[6] & A[13]; assign and8[7] = and7[7] & A[14]; assign and8[8] = and7[8] & A[15]; wire [7:0] and9; assign and9[0] = and8[0] & A[8]; assign and9[1] = and8[1] & A[9]; assign and9[2] = and8[2] & A[10]; assign and9[3] = and8[3] & A[11]; assign and9[4] = and8[4] & A[12]; assign and9[5] = and8[5] & A[13]; assign and9[6] = and8[6] & A[14]; assign and9[7] = and8[7] & A[15]; wire [6:0] and10; assign and10[0] = and9[0] & A[9]; assign and10[1] = and9[1] & A[10]; assign and10[2] = and9[2] & A[11]; assign and10[3] = and9[3] & A[12]; assign and10[4] = and9[4] & A[13]; assign and10[5] = and9[5] & A[14]; assign and10[6] = and9[6] & A[15]; wire [5:0] and11; assign and11[0] = and10[0] & A[10]; assign and11[1] = and10[1] & A[11]; assign and11[2] = and10[2] & A[12]; assign and11[3] = and10[3] & A[13]; assign and11[4] = and10[4] & A[14]; assign and11[5] = and10[5] & A[15]; wire [4:0] and12; assign and12[0] = and11[0] & A[11]; assign and12[1] = and11[1] & A[12]; assign and12[2] = and11[2] & A[13]; assign and12[3] = and11[3] & A[14]; assign and12[4] = and11[4] & A[15]; wire [3:0] and13; assign and13[0] = and12[0] & A[12]; assign and13[1] = and12[1] & A[13]; assign and13[2] = and12[2] & A[14]; assign and13[3] = and12[3] & A[15]; wire [2:0] and14; assign and14[0] = and13[0] & A[13]; assign and14[1] = and13[1] & A[14]; assign and14[2] = and13[2] & A[15]; wire [1:0] and15; assign and15[0] = and14[0] & A[14]; assign and15[1] = and14[1] & A[15]; wire and16; assign and16 = and15[0] & A[15]; assign is[2] = and2[0] | and2[1] | and2[2] | and2[3] | and2[4] | and2[5] | and2[6] | and2[7] | and2[8] | and2[9] | and2[10] | and2[11] | and2[12] | and2[13] | and2[15]; assign is[3] = and3[0] | and3[1] | and3[2] | and3[3] | and3[4] | and3[5] | and3[6] | and3[7] | and3[8] | and3[9] | and3[10] | and3[11] | and3[12] | and3[14]; assign is[4] = and4[0] | and4[1] | and4[2] | and4[3] | and4[4] | and4[5] | and4[6] | and4[7] | and4[8] | and4[9] | and4[10] | and4[11] | and4[13]; assign is[5] = and5[0] | and5[1] | and5[2] | and5[3] | and5[4] | and5[5] | and5[6] | and5[7] | and5[8] | and5[9] | and5[10] | and5[12]; assign is[6] = and6[0] | and6[1] | and6[2] | and6[3] | and6[4] | and6[5] | and6[6] | and6[7] | and6[8] | and6[9] | and6[11]; assign is[7] = and7[0] | and7[1] | and7[2] | and7[3] | and7[4] | and7[5] | and7[6] | and7[7] | and7[8] | and7[10]; assign is[8] = and8[0] | and8[1] | and8[2] | and8[3] | and8[4] | and8[5] | and8[6] | and8[7] | and8[9]; assign is[9] = and9[0] | and9[1] | and9[2] | and9[3] | and9[4] | and9[5] | and9[6] | and9[8]; assign is[10] = and10[0] | and10[1] | and10[2] | and10[3] | and10[4] | and10[5] | and10[7]; assign is[11] = and11[0] | and11[1] | and11[2] | and11[3] | and11[4] | and11[6]; assign is[12] = and12[0] | and12[1] | and12[2] | and12[3] | and12[5]; assign is[13] = and13[0] | and13[1] | and13[2] | and13[4]; assign is[14] = and14[0] | and14[1] | and14[3]; assign is[15] = and15[0] | and15[2]; assign is[16] = and16; wire [15:1] eB; eB[1] = B[0]; eB[2] = B[1]; eB[3] = B[1] & B[0]; eB[4] = B[2]; eB[5] = B[2] & B[0]; eB[6] = B[2] & B[1]; eB[7] = eB[6] & B[0]; eB[8] = B[3]; eB[9] = B[3] & B[0]; eB[10] = B[3] & B[1]; eB[11] = eB[10] & B[0]; eB[12] = B[3] & B[2]; eB[13] = eB[12] & B[0]; eB[14] = eB[12] & B[1]; eB[15] = eB[14] & B[0]; assign O = is[1] & ~is[2] & ~eB[1] | is[2] & ~is[3] & ~eB[2] | is[3] & ~is[4] & ~eB[3] | is[4] & ~is[5] & ~eB[4] | is[5] & ~is[6] & ~eB[5] | is[6] & ~is[7] & ~eB[6] | is[7] & ~is[8] & ~eB[7] | is[8] & ~is[9] & ~eB[8] | is[9] & ~is[10] & ~eB[9] | is[10] & ~is[11] & ~eB[10] | is[11] & ~is[12] & ~eB[11] | is[12] & ~is[13] & ~eB[12] | is[13] & ~is[14] & ~eB[13] | is[14] & ~is[15] & ~eB[14] | is[15] & ~eB[15]; endmodule ``` This is not fully golfed yet. I gave the answer in Verilog because this way, I was able to write a program to output each section. If it is mandatory to answer with a diagram, please let me know. They are equivalent. `&` is and, `~` is not, and `|` is or. My strategy: * take `A` and put move all the `1`s to the low numbers, store in `is`. (this is the majority of the program) * take `B` and unpack it into 16 bits (I called it `eB` for expanded `B`) * do a simple check. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/24316/edit). Closed 2 years ago. [Improve this question](/posts/24316/edit) I once needed to write a function that calculates the block entropy of a given symbol series for a given block size and was surprised how short the result was. Thus I am challenging you to codegolf such a function. I am not telling you what I did for now (and in which language), but I will in a week or so, if nobody came up with the same or better ideas first. **Definition of the block entropy:** Given a symbol sequence A = A\_1, …, A\_n and a block size m: * A block of size m is a segment of m consecutive elements of the symbol sequence, i.e., A\_i, …, A\_(i+m−1) for any appropriate i. * If x is a symbol sequence of size m, N(x) denotes the number of blocks of A which are identical to x. * p(x) is the probability that a block from A is identical to a symbol sequence x of size m, i.e., p(x) = N(x)/(n−m+1) * Finally, the block entropy for block size m of A is the average of −log(p(x)) over all blocks x of size m in A or (which is equivalent) the sum of −p(x)·log(p(x)) over every x of size m occurring in A. (You can choose any reasonable logarithm you want.) **Restricions and clarifications:** * Your function should take the symbol sequence A as well as the block size m as an argument. * You may assume that the symbols are represented as zero-based integers or in another convenient format. * Your program should be capable of taking any reasonable argument in theory and in reality should be able to calculate the example case (see below) on a standard computer. * Built-in functions and libraries are allowed, as long as they do not perform big portions of the procedure in one call, i.e., extracting all blocks of size m from A, counting the number of occurrences of a given block x or calculating the entropies from a sequence of p values – you have to do those things yourself. **Test:** ``` [2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, 2, 2, 4, 4, 4, 1, 1, 1, 0, 4, 1, 2, 2, 4, 0, 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4, 0, 2, 1, 4, 3, 0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, 2, 3, 0, 0, 4, 4, 2, 3, 1, 3, 1, 1, 3, 1, 3, 1, 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3, 3, 0, 0, 4, 4, 1, 0, 2, 3, 0, 0, 1, 4, 4, 3] ``` The first block entropies of this sequence are (for the natural logarithm): * m = 1: 1.599 * m = 2: 3.065 * m = 3: 4.067 * m = 4: 4.412 * m = 5: 4.535 * m = 6: 4.554 [Answer] ## Mathematica - ~~81~~ ~~78~~ ~~75~~ ~~72~~ ~~67~~ ~~65~~ ~~62~~ 56 bytes I haven't golfed anything in Mathematica before, so I suppose there's room for improvement. This one doesn't quite conform to the rules due to the `Partition` and `Tally` functions, but it's quite neat so I thought I'd post it anyway. ``` f=N@Tr[-Log[p=#2/Length@b&@@@Tally[b=##~Partition~1]]p]& ``` This works with any set of symbols, and can be used like ``` sequence = {2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, 2, 2, 4, 4, 4, 1, 1, 1, 0, 4, 1, 2, 2, 4, 0, 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4, 0, 2, 1, 4, 3, 0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, 2, 3, 0, 0, 4, 4, 2, 3, 1, 3, 1, 1, 3, 1, 3, 1, 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3, 3, 0, 0, 4, 4, 1, 0, 2, 3, 0, 0, 1, 4, 4, 3}; f[sequence, 3] > 4.06663 ``` Here is a somewhat ungolfed version: ``` f[sequence_, m_] := ( blocks = Partition[sequence, m, 1]; probabilities = Apply[#2/Length[blocks] &, Tally[blocks], {1}]; N[Tr[-Log[probabilities]*probabilities]] ) ``` It will probably run faster if I apply `N` directly to the result of `Tally`. By the way, Mathematica does actually have an `Entropy` function, that reduces this to **28 bytes**, but that's definitely against the rules. ``` f=N@Entropy@Partition[##,1]& ``` On the other hand, here is a **128 byte** version that reimplements `Partition` and `Tally`: ``` f=N@Tr[-Log[p=#2/n&@@@({#[[i;;i+#2-1]],1}~Table~{i,1,(n=Length@#-#2+1)}//.{p___,{s_,x_},q___,{s_,y_},r___}:>{p,{s,x+y},q,r})]p]& ``` Ungolfed: ``` f[sequence_, m_] := ( n = Length[sequence]-m+1; (*number of blocks*) blocks = Table[{Take[sequence, {i, i+m-1}], 1}, {i, 1, n}]; blocks = b //. {p___, {s_, x_}, q___, {s_, y_}, r___} :> {p,{s,x+y},q,r}; probabilities = Apply[#2/n &, blocks, {1}]; N[Tr[-Log[probabilities]*probabilities]] ) ``` [Answer] # Perl, 140 bytes The following Perl script defines a function `E` that takes the symbol sequence, followed by segment size as arguments. ``` sub E{$m=pop;$E=0;%h=();$"=',';$_=",@_,";for$i(0..@_-$m){next if$h{$s=",@_[$i..$i+$m-1],"}++;$E-=($p=s|(?=$s)||g/(@_-$m+1))*log$p;}return$E} ``` ## Ungolfed version with test ``` sub E { # E for "entropy" # E takes the sequence and segment size as arguments # and returns the calculated entropy. $m = pop; # get segment size (last argument) $E = 0; # initialize entropy %h = (); # hash that remembers already calculated segments $" = ',';#" # comma is used as separator $_ = ",@_,"; # $_ takes sequence as string, with comma as delimiters for $i (0 .. @_-$m) { $s = ",@_[$i..$i+$m-1],"; # segment next if$h{$s}++; # check, if this segment is already calculated $p = s|(?=\Q$s\E)||g / (@_ - $m + 1); # calculate probability # N(x) is calculated using the substitution operator # with a zero-width look-ahead pattern # (golfed version without "\Q...\E", see below) $E -= $p * log($p); # update entropy } return $E } # Test my @A = ( 2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, 2, 2, 4, 4, 4, 1, 1, 1, 0, 4, 1, 2, 2, 4, 0, 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4, 0, 2, 1, 4, 3, 0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, 2, 3, 0, 0, 4, 4, 2, 3, 1, 3, 1, 1, 3, 1, 3, 1, 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3, 3, 0, 0, 4, 4, 1, 0, 2, 3, 0, 0, 1, 4, 4, 3 ); print "m = $_: ", E(@A, $_), "\n" for 1 .. @A; ``` **Result:** ``` m = 1: 1.59938036027528 m = 2: 3.06545141203611 m = 3: 4.06663334311518 m = 4: 4.41210802885304 m = 5: 4.53546705894451 m = 6: 4.55387689160055 m = 7: 4.54329478227001 m = 8: 4.53259949315326 m = 9: 4.52178857704904 ... m = 97: 1.38629436111989 m = 98: 1.09861228866811 m = 99: 0.693147180559945 m = 100: 0 ``` **Symbols:** The symbols are not restricted to integers, because pattern matching based on strings is used. The string representation of a symbol must not contain the comma, because it is uses as delimiter. Of course, different symbols must have different string representations. In the golfed version, the string representation of the symbols should not contain specials characters of patterns. The additional four bytes `\Q`...`\E` are not needed for numbers. [Answer] # Python ~~127 152B~~ 138B ``` import math def E(A,m):N=len(A)-m+1;R=range(N);return sum(math.log(float(N)/b) for b in [sum(A[i:i+m]==A[j:j+m] for i in R) for j in R])/N ``` Adjusted to not break the rules any more and have a slightly cuter algorithm. Adjusted to be smaller ### Older version: ``` import math def E(A,m): N=len(A)-m+1 B=[A[i:i+m] for i in range(N)] return sum([math.log(float(N)/B.count(b)) for b in B])/N ``` My first ever Python script! See it in action: <http://pythonfiddle.com/entropy> [Answer] # Python with Numpy, ~~146~~ 143 Bytes As promised, here is my own solution. It requires an input of non-negative integers: ``` from numpy import* def e(A,m): B=zeros(m*[max(A)+1]);j=0 while~len(A)<-j-m:B[tuple(A[j:j+m])]+=1;j+=1 return -sum(x*log(x)for x in B[B>0]/j) ``` The disadvantage is that this bursts your memory for a large `m` or `max(A)`. Here is the mostly ungolfed and commented version: ``` from numpy import * def e(A,m): B = zeros(m*[max(A)+1]) # Generate (max(A)+1)^m-Array of zeroes for counting. for j in range(len(A)-m+1): B[tuple(A[j:j+m])] += 1 # Do the counting by directly using the array slice # for indexing. C = B[B>0]/(len(A)-m+1) # Flatten array, take only non-zero entries, # divide for probability. return -sum(x*log(x) for x in C) # Calculate entropy ``` [Answer] ## MATLAB ``` function E =BlockEntropy01(Series,Window,Base ) %----------------------------------------------------------- % Calculates BLOCK ENTROPY of Series % Series: a Vector of numbers % Base: 2 or 10 (affects logarithm of the Calculation) % for 2 we use log2, for 10 log10 % Windows: Length of the "Sliding" BLOCK % E: Entropy %----------------------------------------------------------- % For the ENTROPY Calculations % http://matlabdatamining.blogspot.gr/2006/.... % 11/introduction-to-entropy.html % BlogSpot: Will Dwinnell %----------------------------------------------------------- % For the BLOCK ENTROPY % http://codegolf.stackexchange.com/... % questions/24316/calculate-the-block-entropy %----------------------------------------------------------- % Test (Base=10) % Series=[2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, .... % 2, 2, 4, 4, 4, 1, 1, 1, 0, 4, 1,2, 2, 4, 0, .... % 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4, 0, .... % 2, 1, 4, 3,0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, .... % 2, 3, 0, 0, 4, 4, 2, 3, 1, 3, 1, 1,3, 1, 3, 1, .... % 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3, 3, 0, 0, 4, ... % 4, 1, 0,2, 3, 0, 0, 1, 4, 4, 3]'; % % Results % % Window=1: 1.599 % Window=2: 3.065 % Window=3: 4.067 % Window=4: 4.412 % Window=5: 4.535 % Window=6: 4.554 %----------------------------------------------------------- n=length(Series); D=zeros(n,Window); % Pre Allocate Memory for k=1:Window; D(:,k)=circshift(Series,1-k);end D=D(1:end-Window+1,:); % Truncate Last Part % % Repace each Row with a "SYMBOL" % in this Case a Number ............... [K l]=size(D); for k=1:K; MyData(k)=polyval(D(k,:),Base);end clear D %----------------------------------------------------------- % ENTROPY CALCULATIONS on MyData % following Will Dwinnell %----------------------------------------------------------- UniqueMyData = unique(MyData); nUniqueMyData = length(UniqueMyData); FreqMyData = zeros(nUniqueMyData,1); % Initialization for i = 1:nUniqueMyData FreqMyData(i) = .... sum(double(MyData == UniqueMyData(i))); end % Calculate sample class probabilities P = FreqMyData / sum(FreqMyData); % Calculate entropy in bits % Note: floating point underflow is never an issue since we are % dealing only with the observed alphabet if Base==10 E= -sum(P .* log(P)); elseif BASE==2 E= -sum(P .* log2(P)); else end end WITH TEST SCRIPT %----------------------------------------------------------- Series=[2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, .... 2, 2, 4, 4, 4, 1, 1, 1, 0, 4, 1,2, 2, 4, 0, .... 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4, 0, .... 2, 1, 4, 3,0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, .... 2, 3, 0, 0, 4, 4, 2, 3, 1, 3, 1, 1,3, 1, 3, 1, .... 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3, 3, 0, 0, 4, ... 4, 1, 0,2, 3, 0, 0, 1, 4, 4, 3]'; Base=10; %----------------------------------------------------------- for Window=1:6 E =BlockEntropy01(Series,Window,Base ) end ``` ]
[Question] [ The well-known Urinal Protocol states that each person that takes a urinal will take the one furthest from any other taken urinal. But this fails to account for short urinals; in many cases, a person would prioritize taking a taller urinal in addition to distance. In the real world, you might struggle to find a restroom with urinals of arbitrary height (besides a “short” and a “tall”) but fortunately for us this is the internet. To my knowledge, there are no guidelines for building internet bathrooms :P For this challenge, you will be given a list of urinal heights and will have to determine the order in which they will be taken. You might be given the following list: ``` 3,2,4,3,1,4 ``` The first person will choose the tallest urinal. In this case, there is a tie, so the leftmost urinal is taken, in this case urinal 3 (1-indexed). ``` _,_,1,_,_,_ ``` The next person will take the tallest urinal that is further from any already taken urinal. Here, the tallest is urinal 6, and there is no tie. ``` _,_,1,_,_,2 ``` The next person will take the next tallest, but if there is a tie, choose the urinal furthest from any already taken urinal. ``` 3,_,1,_,_,2 ``` We repeat the previous step until all slots are filled: ``` 3,_,1,_,_,2 3,_,1,4,_,2 3,5,1,4,_,2 3,5,1,4,6,2 ``` So the final answer here would be `3,5,1,4,6,2`. But what about a situation like this: ``` 3,2,1,2,1,1,3 ``` The logic above applies until this state is reached: ``` 1,4,_,3,_,_,2 ``` Which of the three empty slots is preferable? They all have the same height, and are equidistant from the nearest taken urinal. Well, slot 3 is next to taken urinals on both sides, while slots 5 and 6 each have a side open, so they are preferable to slot 3. Now that the competition has narrowed to just two, the leftmost urinal is taken. ``` 1,4,_,3,_,_,2 1,4,_,3,5,_,2 1,4,6,3,5,_,2 1,4,6,3,5,7,2 ``` Importantly, the slots touching the edges (here 1 and 7) should be always be treated as though they have at least one side open. Consider this example: ``` 1,2,1,1,3 ``` The first two people come, and the third person sees this: ``` _,2,_,_,1 ``` Here, the three remaining slots are actually all tied, because each has an open slot next to it, so the leftmost slot is taken: ``` _,2,_,_,1 3,2,_,_,1 3,2,4,_,1 3,2,4,5,1 ``` The final result is `3,2,4,5,1`. Test cases: ``` 1 -> 1 1,1,1 -> 1,3,2 1,2 -> 2,1 1,2,1,1,3 -> 3,2,4,5,1 3,2,4,3,1,4 -> 3,5,1,4,6,2 1,3,3,2,4 -> 5,2,3,4,1 1,1,1,2,2 -> 3,4,5,1,2 1,1,1,1,1,1 -> 1,5,3,4,6,2 1,2,3,4,5 -> 5,4,3,2,1 2,1,1,3,1 -> 2,3,5,1,4 1,1,1,2,1,1,1,1,1,3,1,1,1 -> 3,6,10,2,7,11,4,8,12,1,9,13,5 ``` ## Clarifications * The output numbers can start at 0 instead of 1. * There will be no skipped urinal heights. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes ``` żJạṂ¥€¥_Je€ṖŻ+ḊƲɗɗNỤḟḣ1⁹; “”ç@ƬṪỤ ``` [Try it online!](https://tio.run/##VY@9qsJAEIX7PIWkdSyym/UWAbG2sBSsrGzEF7Dz2gh5ANMo4h@CWInFxoiFwYCPMXmRvTO7Qa5ssWfPN3NmdjQcjyfGvO4dvG0wnT0P5ez8PAw6Q7oxXbyyOuq4uLyTd9LFbI96jXoXlL9p5JXTZTld5cd2QZUngiYiq9Zo1ciOevkc00cRe5hdUV9Qb/N5EVNq3xjf9wOuC7wA6FgJEgQ9BT8EMBHMQLJBDEJQZDslCYQOKJbQtM0SLGagSEgC1QhSVT3HiI/9b76y9S7I9SoXFNpUN/prKzeYV/ihrgq4OAHVZvTVPw "Jelly – Try It Online") A pair of links which is called with a single argument of urinal heights and returns the list of people at each urinal, as per the question spec. *Thanks to @JonathanAllan for pointing out an error related to the use of `Ṭ`.* ## Explanation ``` żJạṂ¥€¥_Je€ṖŻ+ḊƲɗɗNỤḟḣ1⁹; # ‎⁡Helper link: takes the list of heights as the left argument and the current sequence of urinals used as the right; returns the updated sequence ż ɗ # ‎⁢Zip the urinal lengths with the following: ¥ # ‎⁣- Following as a dyad: J # ‎⁤ - Sequence 1..number of urinals ạṂ¥€ # ‎⁢⁡ - For each of those, minimum absolute distance from the existing people _ ɗ # ‎⁢⁢- Subtract the following run as a dyad on the original two arguments: Je€ # ‎⁢⁣ - Generate a list of 1 in each used urinal position and 0 in those unused (sequence along original list, check whether each in current list) Ʋ # ‎⁢⁤ - Following as a monad Ṗ # ‎⁣⁡ - Remove last list member Ż # ‎⁣⁢ - Prepend zero +Ḋ # ‎⁣⁣ - Add to the untruthied list with the first member removed N # ‎⁣⁤Negate Ụ # ‎⁤⁡Indices in ascending value order (break ties from the left) ḟ # ‎⁤⁢Filter out used indices ḣ1 # ‎⁤⁣First list member (can’t use Ḣ because this returns zero if list is empty) ⁹; # ‎⁤⁤Append to existing list ‎⁢⁡⁡ “”ç@ƬṪỤ # ‎⁢⁡⁢Main link: take a list of urinal heights and return the list of people “”ç@Ƭ # ‎⁢⁡⁣Starting with an empty list, call the helper link repeatedly with the current list on the right and the urinal heights on the left until there’s o change, gathering intermediate values Ṫ # ‎⁢⁡⁤Final version of list Ụ # ‎⁢⁢⁡Indices of list sorted by list values (takes sequence of urinals used and returns the people using the urinals as per spec) 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 which led to one more thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)! ``` Mạ¹ÐṂ;»Nḣʋ2ʋÞẹ0$ḢṬ¬aµƬṠS ``` A monadic Link that accepts the urinal heights as a list of positive integers and yields the urinal grading as a list of positive integers. **[Try it online!](https://tio.run/##AU8AsP9qZWxsef//4bqhwrnDkOG5gjvCu8KlMuG4ozIKTeG5msOnw57hurkwJOG5quG5rMKsYcK1xqzhuaBT////WzMsIDIsIDQsIDMsIDEsIDRd "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hroWHdh6e8HBnk/Wh3YeWGj3csdiIy/fhzlmHlx@e93DXTgOVhztXPdy55tCaxENbj615uHNB8H@dw@1HJz3cOeNR0xpN9///o6MNY3W4FKINdRRACMY2gjMg4joKxmARY7CICZALFjSBKTMGIyMkEQgyQjIKBSGZbww20BQsgrAOoQYEjXQM4dAYQsdyxQIA "Jelly – Try It Online"). ### How? Repeatedly chooses the next urinal, marking it occupied by changing its height to zero until all urinals are occupied, then recovers the grading from the results. ``` Mạ¹ÐṂ;»Nḣʋ2ʋÞẹ0$ḢṬ¬aµƬṠS - Main Link: Heights µƬ - start with X=Heights and collect while distinct, applying: M - maximal indices -> Highest $ - last two links as a monad: 0 - zero ẹ - indices of {zero} -> Occupied Þ - sort {Highest} by: ʋ - last four links as a dyad - f(OneOfHighest, Occupied) ạ - absolute differences ¹ÐṂ - keep minimal values ʋ2 - last four links as a dyad - f(Minimals, 2): » - max with two (vectorises) ; - {Minimals} concatenate {Minimals max 2} N - negate ḣ - keep (up to) the first {2} Ḣ - head -> leftmost of farthest of highest -> Chosen Ṭ - untruth (e.g. 5 -> [0,0,0,0,1]) ¬ - logical NOT a - logical AND {X} -> X with a zero at Chosen urinal Ṡ - signs S - sum columns ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~63~~ 58 bytes ``` W∧⌈θEθ∧⁼κ⌈θ⁻⁺χ⌊Eθ⎇›μ⁰↔⁻λνLθΣEθ∧‹μ¹‹↔⁻λν²§≔θ⌕ι⌈ι±LΦθ‹κ¹I⁻¹θ ``` [Try it online!](https://tio.run/##dY9PCwIhEMXvfQqPs2CQdey0REVQEdQtOlgNu0Outer259Obs210SlCccd7vPU@ldqerNjE@SjIoILdnWOknVU0FdSbFSt@gloLb07rRxsOFm98BniDbeNiYdKhBW7ZvnXCHzmr3grlDHdBBJcUgifKjv5omIHzURgrLrCXaIpTMzbjc/jgcYIneM0C1k@n@hzLMvkvk3lNh87CwZ3wyZ0YJRL8vEAvWWKRw0LnPyHDSujO5sCGvcW/jyAaYaB86RyUFZx3HuN@P5FCqdis5Ohxi/27e "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W∧⌈θEθ∧⁼κ⌈θ⁻⁺χ⌊Eθ⎇›μ⁰↔⁻λνLθΣEθ∧‹μ¹‹↔⁻λν² ``` Until all of the urinals are occupied, calculate the desirability of each urinal, which is zero for all urinals shorter than the tallest, or `10` plus the distance to the nearest occupied urinal minus the number of adjacent occupied urinals for the tallest urinals. ``` §≔θ⌕ι⌈ι±LΦθ‹κ¹ ``` Mark the leftmost urinal of those of equal maximum desirability as occupied using the negation of the number of previously occupied urinals. The first of these will be zero, which will cause the loop to exit once all of the urinals are marked as occupied. ``` I⁻¹θ ``` Output the final list of orders. [Answer] # [R](https://www.r-project.org), 113 bytes ``` \(x,s=seq(x),y=!x){for(i in s)y[order((.5/(sapply(s,\(w)min((w-s[!!y])^2))+!c(y[-1],0)*c(0,y)[s])-x)*!y)[1]]=i;y} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XU5LCsJADN33FA5ukprR_gRBepI6gtQWCtrWjmIH8SRuquDCI3kbx3bQKlm8T5KXXK5Vc0vD-2Gf8tlzt4CaZCiTHdRIKmQ1ntKigmyQ5QOJKiqqdVIBjKcTkKuy3CiQtIAjbrMc4MhlxJgSuPQQRywGFXFXkIN2DA4pjKRAXqPNNHWFCLO5OpvDjxRicEkXojWU-6IEtFoPDZpex70ve_vkG-1rHZCvneAz4VPr9nP0zK_-S9cbAU17mb073cNN0-EL) A function taking a vector of urinal heights and returning a vector of people. The warnings generated occur on the first pass through when the people vector has no one in but do not affect the result. [Answer] # Python3, 219 bytes ``` E=enumerate def f(u): c,C=1,[0]*len(u) while 0==all(C):I=max([i for i,a in E(C)if 0==a],key=lambda i:(u[i],min([abs(I-i)for I,A in E(C)if A]or[0]),(i-1<0 or 0==C[i-1])+(i+1>=len(u)or 0==C[i+1])));C[I]=c;c+=1 return C ``` [Try it online!](https://tio.run/##VZLBbtswDIbP01MQuVhqmCGy461NpwKF0UMufQHPByWRUaG2YsgKtj59Rklt2kEXkt/Pn4Sk6S28nFx1O/nL5UkZdx6N18Gwo@mh52exZXDARkls193NYByVGPx5sYOBtVJ6GHgjtjs16r@8tdCfPFjUYB08EbB9EnX4at7UoMf9kdCWn1vb4Wgdb/V@5ruVFbFvh49f@h67k6eRArldyV9rIAFZNS1lnVhyu5QPKq9zJUsiQtw37a5Th/vDUkkG3oSzd9BcZlCwWCwkrB5AMol0UogVlpSWMSkxkjIyrGKBGG6wpnKOKgKbDOoY4o/UXGHCEdQUVATeR1BWZn2ySerryfPrpM9GubfORpvkKtn7PlkfFWn01f/TsPq0rchQron@RBn3vEUZlXcoqZ2ugaWHitfd2yEYz59PziDM3@dpsIEXv10h6Om/aYQ9XZz9qEfvQlB9no0P9EHam1FP3LqAoD9ESL2dUOoL2//HGJs8lXkRzBxmmKLbsRCXfw) ]
[Question] [ A polyomino with \$n\$ cells is a shape consisting of \$n\$ equal squares connected edge to edge. No *free* polyomino is the rotation, translation or reflection (or a combination of these transformations, i.e. an isometry) of another (they're equal). The sequence of free polyominoes with \$n\$ cells is as follows: ``` 1, 1, 1, 2, 5, 12, 35, 108, 369, 1285, ... ``` ![Polyominoes image](https://i.stack.imgur.com/f5VWZ.png) # Specifications * \$n=0\$ (1) may be excluded * This is [A000105](https://oeis.org/A000105) * Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules: you may output the \$n^{th}\$ term, all terms up to the \$n\$ terms or the entire sequence * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins [Answer] # JavaScript (ES10), 259 bytes For now, this is just a slightly modified version of [my answer](https://codegolf.stackexchange.com/a/199797/58563) to [this other challenge](https://codegolf.stackexchange.com/q/199789/58563) so that reflections are discarded. Supports \$n=0\$. ``` f=(n,m=[...o=Array(w=n)],i=c=0)=>n?m.map((r,y)=>m.map((_,x,[...m])=>!i|1<<x&~r&(m[y+1]|r/2|r*2)&&f(n-1,m,m[y]|=1<<x)))|c:[...3/64+''].some(k=>o[M=(k^6||m.reverse(),m=m.map(a=(_,y)=>m.map(b=(v,x)=>a|=b|=(v>>y&1)<<w+~x)|b)).flatMap(v=>v/(a&-a)||[])])?0:o[M]=++c ``` [Try it online!](https://tio.run/##ZY7RaoNAEEXf@xd9MTN1XTVJLQTH0A/IF8i2rFaLjeuGNRiFJb9uV1ooxcdz5l7ufMlB9qVpLteg0x/VPNcEHVOUc841vRojJ7hRh4I1VFKElHVHxZW8ABg2OfyFdzaypaOEc4@NjdN09O7GA5VPfiysCbfWPG3R82rogpgp5g7C0pJDRFselvYuTPb@ZiN4r1UFZ8p0fiI4vyXWKm6qoTJ9Beje@1mV5Hb/nigIBjY6lJYK6yDLJi/GNL359xFtgcjrVl5PLjpQNoQgvUCitblAgcfo4MYE@X45l7rrdVvxVn9CDRHiw38Tr8x2ZXYrs1@Z55VJVuYFcf4G "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 73 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Should have been 1 byte less by replacing `})}€ê` with `}){}`, but the many nested maps/loops cause a bug in 05AB1E here (`})ê}` and `})}€{` also doesn't work strangely enough..) ``` 1ÝInãʒOQiyƶIô©Δ2Fø0δ.ø}2Fø€ü3}®Ā*εεÅsyøÅsM}}}˜Ùg<]εIô2Føʒà}}4FDíDø})}€êÙg ``` Basically the exact same approach as [my answer](https://codegolf.stackexchange.com/a/259760/52210) for the [related challenge](https://codegolf.stackexchange.com/questions/199789/how-many-unique-one-sided-polyominos), but with a single added `D`uplicate (in step 4) to also remove reflections in addition to the rotations. Extremely slow brute-force, so is only able to output up to \$a(4)\$ on TIO. [Try it online](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFtr4uZyeK0LUL9mLUj3KqCa//9N/uvq5uXr5iRWVQIA) or [verify the first few results](https://tio.run/##yy9OTMpM/W9ybJKfvZLCo7ZJCkr2focnhCr9Nzw8NyLv8OJTkyKK/SMCMyuPbYs4vOXQynNTjNwO7zA4t0Xv8I5aEPNR05rDe4xrD6070qB1buu5rYdbiysP7wCSvrW1tafnHJ6ZbhN7bitQL0jxqUmHF9TWmri5HF7rAtSvWQvSvQqo5r@SXpjO//@6unn5ujmJVZUA). **Explanation:** Also mostly a copy-paste from my answer of the related challenge, except for step 4. Step 1: Create all possible \$n^2\$-sized lists using `0`s and `1`s, consisting of \$n\$ amount of `1`s: ``` 1Ý # Push pair [0,1] In # Push the squared input ã # Cartesian power ʒ # Filter this list of lists by: i # If O # the sum of the current list Q # is equal to the (implicit) input-integer: # Continue with the check in step 2 below # (implicit else: implicitly use the implicit input for the filter; # this is only truthy for edge case n=1, which fails step 2 due to the `ü3`) ``` [Try just this first step online](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/8/9/kv65uXr5uTmJVJQA) (without trailing `i`). Step 2: Filter it further to only keep single polynominos, using a flood-fill approach: ``` y # Push the current list again ƶ # Multiply each value by its 1-based index Iô # Convert the list to an input-by-input block © # Store this block in variable `®` (without popping) Δ # Loop until the result no longer changes to flood-fill the matrix: 2Fø0δ.ø} # Add a border of 0s around the matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Map over each row: 0 .ø # Add a leading/trailing 0 2Fø€ü3} # Convert it into overlapping 3x3 blocks: 2F } # Loop 2 times again: ø # Zip/transpose; swapping rows/columns € # Map over each inner list: ü3 # Convert it to a list of overlapping triplets ®Ā # Push matrix `®` and convert all its positive values back to 1s * # Multiply each 3x3 block by this matrix of 0s/1s (so 0s will remain 0s) εεÅsyøÅsM # Get the largest value from the horizontal/vertical cross of each 3x3 block: εε # Nested map over each 3x3 block: Ås # Pop and push its middle row y # Push the 3x3 block again ø # Zip/transpose; swapping rows/columns Ås # Pop and push its middle rows as well (the middle column) M # Push the flattened maximum of the entire (scoped) stack, # which is the flattened maximum of the cross of the current 3x3 block }} # Close the nested map }˜ # After the flood-fill loop: flatten the block to a list Ù # Uniquify its values g # Pop and push its length < # Decrease it by 1 to account for the 0s # (only 1 is truthy in 05AB1E, so only single islands remain) ] # Close both the if-statement and filter ``` [Try just the first two steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tez//yb/dXXz8nVzEqsqAQ) Step 3: Convert all valid lists to matrices, and slash off any rows/columns of 0s to have the actual polynominos: ``` ε # Map over each inner list Iô # Convert it to an n-by-n block 2F # Inner loop 2 times: ø # Zip/transpose; swapping rows/columns ʒ # Filter this list of rows by: à # Get the maximum of the row (so if it only contains 0s, it'll be removed) } # Close the filter } # Close the inner loop ``` [Try just the first three steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFv7/7/Jf13dvHzdnMSqSgA) Step 4: Remove all duplicated rotations and reflections, by first converting each polynomino to a quartet of its four sorted rotations, then get the reflection of each rotation, and then uniquify that list of octets. ``` 4F # Inner loop 4 times: D # Duplicate the current polynomino-matrix í # Reverse each inner row to reflect it D # Duplicate this new reflected polynomino-matrix again ø # Zip/transpose the matrix; swapping rows/columns }) # After the loop: wrap the eight rotations + reflections on the stack into a list # Explanation if the 05AB1E bug mentioned at the top wasn't present: { # Sort the octet of rotations + reflections }Ù # After the map: uniquify the list of polynomino-rotations/reflections # Actual explanation with bug: }€ # After the map: open a new map: ê # Sort and uniquify each octet Ù # After the map: uniquify the list of distinct polynomino-orientations/reflections ``` [Try just the first four steps online.](https://tio.run/##yy9OTMpM/f/f8PBcz7zDi09N8g/MrDy2zfPwlkMrz00xcju8w@DcFr3DO2pBzEdNaw7vMa49tO5Ig9a5ree2Hm4trjy8A0j61tbWnp5zeGa6Tey5rUC9IMWnJh1eUFtr4uZyeK0LUL9mLUj3qsMz//83@a@rm5evm5NYVQkA) Step 5: Get the amount of unique polynominos left, and output it as result: ``` g # Pop and push the length # (which is output implicitly as result) ``` [Answer] # Python3, 1374 bytes\*: ``` R=range E=enumerate def U(b): q,s=[b],[b] while q: b=q.pop(0) if(T:=[i[::-1]for i in b])not in s:q+=T,;s+=T, if(T:=[*map(list,zip(*[i[::-1]for i in zip(*b)]))])not in s:q+=T,;s+=T, if(T:=[*map(list,zip(*b))])not in s:q+=T,;s+=T, return s Z=lambda B:[[j[0]if j else j for j in i]for i in B] def S(b): b=[[*i]for i in b if any(i)] if 1-any([*zip(*b)][0]):b=[i[1:]for i in b] if 1-any([*zip(*b)][-1]):b=[i[:-1]for i in b] return b C=lambda b:[(x,y)for x,t in E(b)for y,j in E(t)if j] P=[(1,0),(0,1),(-1,0),(0,-1)] def M(b): t=C(b) q=[t.pop(0)] while q: x,y=q.pop() for j,k in P: c=(x+j,y+k) if c in t:t.remove(c);q+=c, return[]==t V=lambda b,x,y:x*y==0 or len(b)==x or len(b[0])==y def f(n): w=int(n**0.5) b=[[[1,0]for _ in R(w)]for _ in R(n//(w or 1))]+[[[1,0]for _ in R(n%(w or 1))]]*(n%(w or 1)>0) B=[i+[0]*(max(map(len,b))-len(i))for i in b] q,s=[B],[Z(B)] while q: b=q.pop(0);c=C(b) for x,y in c: if 0==b[x][y][1]: for X,Y in c: if(X,Y)!=(x,y): for j,k in P: J,K=X-j,Y-k;B=eval(str(b));B[x][y]=0 if(J,K)not in c: if K==len(B[0]):B=[i+[0]for i in B] if K<0:B=[[0]+i for i in B];K=0 if J==len(B):B=B+[[0 for _ in B[0]]] if J<0:B=[[0 for _ in B[0]]]+B;J=0 B[J][K]=[1,1] if M(S(Z(B)))and all(S(Q)not in s for Q in U(S(Z(B)))):q+=B,;s+=S(Z(B)), return len(s) ``` [Try it online!](https://tio.run/##lVRNb5tAED2XX7E9VNrFSwKKKlW40wNRLrYi5bNKslpVQHCDgzEGEkP/vDuzxhgnzaGWbO/Mvn3z8Wa3aOunZX7yrSg3mysow/x3Yp1Bkr8skjKsE@sxmbFbHgnfYitZgYq0xK/F1k9plrAVulkEq6NiWXBXoJHO@I0PKlW@73h6tixZytKcRVrky5pWlb8awY0cV/S7P2AvwoJnaVXLP2nB7XcExhsJLcR/MkUfnyiT@qVEr/UAWbiIHkMW@ErNlavTGZuzJKsS/KMU5nQ63WcTaNOY621jIlDKHuxGmAoL85anAjuFa88hS9m7IjCC8CPqkucPe/RvMLahQ79paV9BZJ3uKoh8xRvZCoI10lR9hlmS2cr51qwF1aetC1Dck66Q3JUe/jo7w/HEtsDzbYE1nOICJwBU3Ul9OAIYsRsCmgHTMflMwS5ol8XAm9FctqNn2qYiY9qs/fqoTBbL14THYozSxL0oSgPU1s@@KokR/MZuAVyG7FmSY0IATW9QSwFak/WM55T1GtK85rltu0dfxVYlhRWaDv6i@Fd8LYZWfnzM18To4cyM3qPzL/ttbQ/MHzT6ASo0wjRsvggbboYwySWOn0MJpkIcKGcuU4CX6YEH4qP7NI67xrOtnC2djv2uhy5ApBqtWq08bZwGdifv9zBzK9AjPoMZi875XiL6TOQU7py5vHeexwEkr2HGq7rEBMQ42AYCd4dFWoTvLlbcc1BiUwAqOTBjvmvL8O4Msd9dgiBglLIBZjzdxyLcpOMkwgC1cVkvDMXRB6STHelb0CgYTwa8gZpoNdWAQnsHBOf8mpMwQoT5IwuzDO3L/hUxrJe0vO1xgp6WwDwtnWv/wFDildj01ZlXlnsuqvGpKGlIZzQfm78) \* Rather long in bytes, but computes solutions up to and including \$n = 9\$ in under 40 seconds on TIO. [Answer] # [R](https://www.r-project.org), ~~205~~ 199 bytes ``` f=\(n,o={},v=0,u=0,`~`=c,`?`=sort,d=-1~1i~1~-1i){for(j in u)F=F+`if`(length(p<-?j~o)<n,f(n,p,v,setdiff((u=u[-1])~j+d,v<-j~v)),2^(-all(apply(Conj(p)%o%d,2,a<-\(x)any(diff(p-?x))))-a(-p)-a(p*1i))/n);F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BasMwEEWv4k1gppmhVVahtfCi4Es0LRJ11EgYSTiSSQjRRbpJFz1ET9Az9Da1GzrwZ_M_n_ffP4bL5TMnw-ufbyM34CnI05lGeUd5kipKvpJqlNyHIVEnWRRhiygsLJ5MGMBV1lcZW9kulTUK-q1_SzuINTeuBKw9mak00kj7beqsMQBZ5icWz1jcsqOxZldGRFq9AOu-Bx1jf4TH4B1EXIRFRyvSNW_ggNof4a8icnPA6VgDx_nHm4kHbz0-tOfrnK8Zzs5w4n6NVRysT2BgSl39_9m_) A variation of [my answer to the related challenge](https://codegolf.stackexchange.com/a/200161/78274) adapted to account for reflections. Specifically, since the polyominoes \$p\$ are stored as complex numbers, reflections across both axes and diagonals can be represented by their complex conjugates \$Conj(p)\$ multiplied by directional vectors in \$d\$. [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~532~~ ~~496~~ 366 bytes saved so many bytes thanks to the comment of @Aiden Chow --- **Modified from the Mathematica code provided by [A000105](https://oeis.org/A000105).** **Really naive. I don't know what I'm doing.** --- ``` z[p_]:=Union[(#-(Min@Re@p+Min@Im@p*I))&/@p];Q[1]={{0}};Q[n_]:=Module[{f,g,a={}},g=((f=#;({f,#+1,f,#+I,f,#-1,f,#-I}&/@f))&)/@Q[n-1];f=Select[Union[z/@Partition[Flatten@g,n]],Length@#==n&];While[f!={},a={a,Z=f[[1]]};f=Complement[f,Union[z/@Flatten[{#,(#-2Re@#)&/@#}&/@Module[{i=Z,a={Z}},While[(i=I*i)!=Z,a~AppendTo~i];a],1]]]];Partition[Flatten@a,n]];F[n_]:=Length@Q@n ``` [Try it online!](https://tio.run/##ZZBRS8MwFIXf/RdrYaTbLbM@iSEQEQYFB5tOhIUgcUvaQJuGEV9Wur9eb9z0xZebm8vNd85Jq0KtWxXsXo3jSfgP@cDenO2cIGlOVtbxF839PDZly/2szLLpgntJN6KQrO9vhwFbF5@tusNXo0VvoALF@mGAihFiWEoJztJ5AbGWseY/fV4OyDJIzBYcIXkhqWGvutH7IC4mTgu@VsdgQ7wsGxWCdrwCJyU8a1eFmqeMuamk77VFbTNB3SiuYMeMQItyQORT1/pGt9oFYeAPfMWJPgXMeoc505gtjaZ@s1i2i7gdhrkoEMvKmc0mcX5@9F67w7Y7W0mVBFSTkv73q6Jfurz80tX2hrtxqz6RuD5a9JUokoCDJGMJ4Cbu38QDegcF3A9y/AY) --- The original Mathematica code looks like ``` (* In this program by Jaime Rangel-Mondragón, polyominoes are represented as a list of Gaussian integers. *) polyominoQ[p_List] := And @@ ((IntegerQ[Re[#]] && IntegerQ[Im[#]])& /@ p); rot[p_?polyominoQ] := I*p; ref[p_?polyominoQ] := (# - 2 Re[#])& /@ p; cyclic[p_] := Module[{i = p, ans = {p}}, While[(i = rot[i]) != p, AppendTo[ans, i]]; ans]; dihedral[p_?polyominoQ] := Flatten[{#, ref[#]}& /@ cyclic[p], 1]; canonical[p_?polyominoQ] := Union[(# - (Min[Re[p]] + Min[Im[p]]*I))& /@ p]; allPieces[p_] := Union[canonical /@ dihedral[p]]; polyominoes[1] = {{0}}; polyominoes[n_] := polyominoes[n] = Module[{f, fig, ans = {}}, fig = ((f = #1; ({f, #1 + 1, f, #1 + I, f, #1 - 1, f, #1 - I}&) /@ f)&) /@ polyominoes[n - 1]; fig = Partition[Flatten[fig], n]; f = Select[Union[canonical /@ fig], Length[#1] == n &]; While[f != {}, ans = {ans, First[f]}; f = Complement[f, allPieces[First[f]]]]; Partition[Flatten[ans], n]]; a[n_] := a[n] = Length[ polyominoes[n]]; Table[Print["a(", n, ") = ", a[n]]; a[n], {n, 1, 12}] (* Jean-François Alcover, Mar 24 2015, after Jaime Rangel-Mondragón *) ``` ]
[Question] [ I was trying to write a short MIPS32 code for computing the median of three registers. The rules: * Assume that some values are pre-loaded into `$t0`, `$t1`, `$t2`. * The median of the three values should be placed in `$t0`. * No branches are allowed, but otherwise any instruction is okay. * You may arbitrarily modify the values of all registers. I was able to optimize it down to 15 instructions. Can you do better? [Answer] # 7 instructions ``` slt $t3, $t0, $t1 slt $t4, $t2, $t1 slt $t5, $t2, $t0 ``` Compare all three pairs of values. ``` xor $t3, $t3, $t4 movn $t0, $t1, $t3 ``` `$t1` is the median if it is greater than exactly one of the other values. ``` xor $t5, $t5, $t4 movn $t0, $t2, $t5 ``` `$t2` is the median if it is less than exactly one of the other values. (Otherwise, `$t0` is already the median.) [Answer] # 8 instructions ``` slt $t4, $t2, $t1 movn $t3, $t1, $t4 movn $t1, $t2, $t4 movn $t2, $t3, $t4 ``` Rearrange `$t1` and `$t2` so that `$t1` ≤ `$t2`. ``` slt $t3, $t2, $t0 slt $t4, $t0, $t1 movn $t0, $t2, $t3 movn $t0, $t1, $t4 ``` If `$t0` falls between `$t1` and `$t2`, it is already the median. If it's outside that range, the one it lies beyond is the median. ]
[Question] [ # Challenge This coding challenge is to figure out how many rounds the cat can live. In a \$4\times4\$ matrix, there are a number of mice and exactly 1 cat. Example: $$ \begin{array} {|r|r|}\hline 🐭 & 🐭 & 🐭 & ⬜ \\ \hline ⬜ & 🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & 🐱⬜ & 🐭 \\ \hline 🐭 & 🐭 & 🐭 & 🐭 \\ \hline \end{array} $$ But in each square of the matrix, like a house, up to 5 mice can live in it. I indicate it with a number in front of the mouse. There are also squares where there are no mice => Indicated with a blank square. Example: $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 3🐭 & ⬜ \\ \hline ⬜ & 5🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & 🐱⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ # About the Cat and Mouse The cat can, and must, move up, down, left, right and diagonal, **1 step** at a time. Take into note, that the cat can only eat 1 mouse per round. The cat will always eat a mouse, because it is always hungry. The cat prefers the house with the most mice in it, although it knows it can eat just one at a time (don't ask me why). After the cat has eaten a mouse, the number of mice in the house will of course decrease. After the cat has eaten a mouse, the cat lives in the home of the eaten mouse, possibly with other mice for the remainder of the round. In the starting position, the cat can only live where there is no mice. But even after the first round, of course the cat must live in a house of the mice. This goes on and on, till: # Game End These are the scenarios, when the game ends: * When there are no more mice around the cat to eat anymore. => The cat will starve. (Note the cat cannot eat another mouse in the current house since it must move on, so can end up starving while residing with mice - like in example 5) * When at least 2 of the houses, the cat **can visit**, has the highest and same number of mice. => The cat will die of frustration. # Rules * The Input must be a list, or an array, or some datatype that can store the number of mice in the house, and where the cat is. * Where there is no mice, you can indicate it with just \$0🐭\$ * If you use an array, it could be 1 dimensional, but also 2 dimensional. * The output must be an integer, the number of rounds the cat did survive. * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, of course. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Good luck! Note: In the above matrix I showed, the output must be \$3\$. => Death because: the cat can't decide in which house of mice to eat. ## Example ### Example 1 * Starting state: $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 3🐭 & ⬜ \\ \hline ⬜ & 5🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & 🐱⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ * After 1 round: $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 3🐭 & ⬜ \\ \hline ⬜ & 4🐭\!\!\!\!🐱\!\!\!\! & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ * After 2 rounds: $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 2🐭\!\!\!\!🐱\!\!\!\! & ⬜ \\ \hline ⬜ & 4🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ * After 3 rounds: $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 2🐭 & ⬜ \\ \hline ⬜ & 3🐭\!\!\!\!🐱\!\!\!\! & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ * 4th Round: **Death of frustration** $$ \begin{array} {|r|r|}\hline 1🐭 & \underbrace{2🐭} & \underbrace{2🐭} & ⬜ \\ \hline ⬜ & 3🐭\!\!\!\!😿\!\!\!\! & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline 1🐭 & 4🐭 & 1🐭 & 1🐭 \\ \hline \end{array} $$ So it just survived 3 rounds. ### Example 2 * Starting Stage $$ \begin{array} {|r|r|}\hline 1🐭 & 5🐭 & 1🐭 & 🐱⬜ \\ \hline ⬜ & 5🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline ⬜ & ⬜ & ⬜ & 1🐭 \\ \hline \end{array} $$ * End Stage: 1 Round $$ \begin{array} {|r|r|}\hline 1🐭 & 5🐭 & ⬜😿 & ⬜ \\ \hline ⬜ & 5🐭 & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline ⬜ & ⬜ & ⬜ & 1🐭 \\ \hline \end{array} $$ ### Example 3 * Starting Stage $$ \begin{array} {|r|r|}\hline 1🐭 & 5🐭 & 1🐭 & ⬜ \\ \hline ⬜ & 5🐭 & ⬜ & ⬜ \\ \hline 2🐭 & 🐱⬜ & 1🐭 & 4🐭 \\ \hline ⬜ & ⬜ & 1🐭 & 1🐭 \\ \hline \end{array} $$ * End Stage: 7 Rounds $$ \begin{array} {|r|r|}\hline 1🐭 & 2🐭 & 1🐭 & ⬜ \\ \hline ⬜ & 1🐭\!\!\!\!😿\!\!\!\! & ⬜ & ⬜ \\ \hline 2🐭 & ⬜ & 1🐭 & 4🐭 \\ \hline ⬜ & ⬜ & 1🐭 & 1🐭 \\ \hline \end{array} $$ ### Example 4 * Starting Stage $$ \begin{array} {|r|r|}\hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline ⬜ & 1🐭 & ⬜ & ⬜ \\ \hline 🐱⬜ & ⬜ & 1🐭 & 1🐭 \\ \hline ⬜ & ⬜ & ⬜ & 2🐭 \\ \hline \end{array} $$ * End Stage: 5 Rounds $$ \begin{array} {|r|r|}\hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜😿 \\ \hline \end{array} $$ ### Example 5 * Starting Stage $$ \begin{array} {|r|r|}\hline ⬜ & 3🐭 & ⬜ & ⬜ \\ \hline ⬜ & 2🐭 & ⬜ & ⬜ \\ \hline 🐱⬜ & ⬜ & 1🐭 & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline \end{array} $$ * End Stage: 4 Rounds $$ \begin{array} {|r|r|}\hline ⬜ & 1🐭\!\!\!\!😿\!\!\!\! & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline ⬜ & ⬜ & 1🐭 & ⬜ \\ \hline ⬜ & ⬜ & ⬜ & ⬜ \\ \hline \end{array} $$ Good luck again! [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~167~~ \$\cdots\$ ~~159~~ 155 bytes Saved ~~2~~ 5 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved 4 bytes thanks to [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r)!!! ``` def f(a,c,r=0): while(l:=sorted([[z,-a.get(c+z,0)]*2for x in(1,1j,1+1j,1-1j)for z in(x,-x)],key=list.pop))[0][1]<l[1][1]:r+=1;c+=l[0][0];a[c]-=1 return r ``` [Try it online!](https://tio.run/##jVJRb6MwDH7nV1h9IRlmItBqJ7rsjzB0QmlYYYiikOkoVX97Lw70tjvt4RBKnM9fPtuxh7M9nvrsx2But4OuoWYVKjQy4XkAv45Np1mXy/FkrD6wopgxrh7ftGUqmjHh5UNanwxM0PRMoGhRRLTEouWEz4RPGE@8xHd9ll0z2sfhNHBeJGUhyufOLe7PTSTFXkWyIzwp91WhyliKAIy2H6YH43MbKDfK6x4TTNW/abYlzIPnv8BZTtH5QbT7wTS9ZRt42RRKyrmMRmvYUgdVwaMNPK8u1P1BhiF3gsstZy1GGH/5HMHq0f6sQAIL4JLkAkG0eYqQtnnmbPcQ@c6dosyjGREyAre0O5I/O6e44heBnRcQ3wj8D9fHX8X9xe@Deb74h3qnpAvls4o/ms6xlq2obAIxa9HvKaY80NOglRsU8mYo8Al3uOWBOmr1rg2h4etH@rRVIYK3ROYekhpHQ6epeXMzsOVlEZZQCHdZ32ZYx8Cbo9OsP49Lo@oQ4he4jFe4rJELLeVYXl/7kN9@Aw "Python 3.8 (pre-release) – Try It Online") Inputs a dictionary mapping each house in the array (represented by a complex number) to the number of mice in that house along with the position of the cat as a complex number. Return the number of rounds before the cat "dies" (no cats or mice where harmed in this answer, they're all professional actors just playing their parts). [Answer] # JavaScript (ES7), ~~ 122 113 112 ~~ 111 bytes *Saved 1 byte thanks to @l4m2* Expects `(mice_array)(cat_x, cat_y)`. ``` m=>g=(x,y)=>!m.reduce((o,v,n)=>6>>(n%4-x)**2+((n>>2)-y)**2&1?v>h?!(p=n,h=v):o|v==h:o,h=0)&&1+g(p&3,p>>2,m[p]--) ``` [Try it online!](https://tio.run/##lY/BbsIwDIbvfQo4rLKpg5IUdkBKeBDEAZXSbqJJBFsEEu9eXKi2IjGkyZfflv/Pvz83cXMsDh/hSzi/LdudaRtjKwMnOqOx42Z6KLffRQngKZLj0bu14N5m4oSTic4AnLUaxbnrUrWMtl6OIRhHtYm48JdoTL3w3ElMU5VVENKcAnuoWYW1ENgW3h39vpzufQXZDlbJaKRIU06SWEqas@hlV5puCzNSpJI1giaNmCRPKXNeekG5yxuFr/2Lojsjh@gpfRb1Z5b7qZ6ihlnYOojVUeQLSv5r1Y@UwXPyh9JeAQ "JavaScript (Node.js) – Try It Online") ### Commented This is a bit similar to [my answer](https://codegolf.stackexchange.com/a/177545/58563) to [my own challenge](https://codegolf.stackexchange.com/q/176251/58563). ``` m => // m[] = flat array of mice g = // g is a recursive function taking (x, y) => // the position (x, y) of the cat !m.reduce((o, v, n) => // for each value v at position n in m[]: 6 >> // bitmask of valid squared distances (n % 4 - x) ** 2 + // compute (prev_x - x)² ((n >> 2) - y) ** 2 // + (prev_y - y)² & 1 ? // if it's either 1 or 2: v > h ? // if v is greater than the highest value h: !(p = n, h = v) // copy n to p and v to h, clear o : // else: o | v == h // set o if v = h (frustrated cat!) : // else: o, // leave o unchanged h = 0 // start with o = h = 0 ) // end of reduce() && // if it's falsy: 1 + // increment the final result g( // and do a recursive call: p & 3, // new x p >> 2, // new y m[p]-- // decrement m[p] ) // end of recursive call ``` [Answer] # [Haskell](https://www.haskell.org/), ~~137~~ 134 bytes ``` (x,y)!l|d<-[a|a@((i,j),k)<-l,((x-i)^2+(y-j)^2-2)^2<2],m<-foldr(max.snd)1d,[i]<-[i|(i,k)<-d,k==m]=1+i!((i,m-1):[a|a<-l,fst a/=i])|0<1=0 ``` [Try it online!](https://tio.run/##ZZDBbsMgDIbvfQpa9QAqZIGmm1SFapfd9gZRpiBBNxqSVCTa0invnpm03bpNlm1kPv82vKm2NM6NI@7piczdoFOWqUE9YmzpgdCSpMxRjHtmyYtY4RM7QGYCQipyWqVs3zjtcaX6qK014ZpmNgcNO4BA6Na0lLLKJV/ZeRCtGCfbMCII79sOqTtpczLEKZfxWClbS93MEOq3p61PGSgfkTdKRx@N1220t64zHhd10z05UxULynYLki53r6Z7trUh0OpMh5zMYFpRNbpIqC20fS@S8JzrWp/2mMVRlC87VRrE75HPofPobd0tL38hpVOwn4d6WGsUSFDEkUBrFINtpng2AfUEnCO2Q@sZAIHcgP8nz3ki@YyfNX@TYrpPLtxEPsziQP7o8JsT/9YGcnMl138m3vbEgUy@AA "Haskell – Try It Online") The function `(!)` takes as input the position of the cat `(x,y)` and a list with one `((i,j),k)` entry for each house, where house at position `(i,j)` as `k` mice (possibly zero). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` E⁴SJNNW⁼№KM⌈KM¹«⊞υωM✳⁻³⌕KM⌈KMPI⊖KK»⎚ILυ ``` [Try it online!](https://tio.run/##jY9PSwMxEMXPm0@R4wRWSFtvPW4rKI0s6BeI69AN5s82m2kF8bPHZKvo0csw8/jN471h1HEI2ubcR@MTKD3Bbcvv/UTpKRXpCEKILXsgNz0HWPRHci8YQXxjP2ehLqOxyGF/Im1n6AIVxx7xTYUQsT4o/W4cub@iKPJKCP7Bmp7mEajll2LVqHBG2JmIQzLBgzKeZti0/M7413@YLqkbRTaZaWnW6TnBDoeIDn3CqwdcuU/WWdSlw5b1v/AB/TGVQBXJWW6kZHJdh1zVUTe2zjdn@wU "Charcoal – Try It Online") Link is to verbose version of code. Takes as input a list of 4 strings of digits, followed by the 0-indexed across and down coordinates. Explanation: ``` E⁴S ``` Print the mouse counts to the canvas. ``` JNN ``` Move to the cat's starting position. ``` W⁼№KM⌈KM¹« ``` Repeat while the cat has a unique choice of best move. ``` ⊞υω ``` Track the number of moves. ``` M✳⁻³⌕KM⌈KM ``` Actually make that move. (Annoyingly the `Peek` and the `Direction` directions don't match up with each other...) ``` PI⊖KK ``` Decrement the number of mice at the new position. ``` »⎚ILυ ``` Clear the canvas and output the number of moves taken. ]
[Question] [ Adapted from [tips for restricted-source in Python](https://codegolf.stackexchange.com/q/209734) Just like [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") pushes one to exploit quirks and hidden features of the [zsh](https://www.zsh.org) language. While we already have [a place](https://codegolf.stackexchange.com/q/15279) to collect all these [tips](/questions/tagged/tips "show questions tagged 'tips'") for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), those for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") remain transmitted by word of mouth or hidden deep within the manual pages. So, what are some [tips](/questions/tagged/tips "show questions tagged 'tips'") for solving [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges in [zsh](https://www.zsh.org)? **Please only include 1 tip per answer.** Please downvote answers with multiple tips in them. --- **What makes a good tip here?** There are a couple of criteria I think a good tip should have: 1. It should be (somewhat) non obvious. Similar to the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips, it should be something that someone who has golfed in zsh (or bash) a bit and read the tips page would not immediately think of. For example, "replace `a + b` with `a+b` to avoid using spaces" is obvious to any golfer since it is already a way to make your code shorter and thus not a good tip. 2. It should not be too specific. Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction. For example tips of the form "How to X without using character(s) Y" are generally useful since banned characters is a common source restriction. The thing your tip helps to do should also be somewhat general. For example tips of the form "How to create numbers with X restriction" are useful since many programs utilize numbers regardless of the challenge. Tips of the form "How to implement Shor's algorithm with X restriction" are basically just answers to a challenge you just invented and not very helpful to people solving other challenges. [Answer] # Globbing Globs are patterns used to match files and other strings. If you can't use a particular character but you need to access a command with that character in its name, you can often approximate it with a glob, like `/*/ls` The full description of glob syntax is under `Filename Generation` in `zshexpn(1)`, but here is a summary: * `?` matches any single character * `*` matches zero or more characters * `<1-10>` matches any number between 1 and 10 + `<->` matches any number * `[a-d]` matches any character in the set `abcd` * `[:name:]` matches any character in the named set (full details in the man-page) * `[^a]` or `[!a]` matches any character except `a` + `[^]` or `[!]` matches any single character * `(a|b)` matches `a` or `b` * With the option `--nocaseglob`, globbing is case-insensitive. This allows you to do `/*/LS` instead of `ls` * With the option `--extendedglob`, you can use the additional syntax: + `^pattern` matches anything except `pattern` + `a~b` matches pattern `a` but not `b` + `a~^b` matches both patterns `a` and `b` + `a#` matches zero or more instances of `a` + `a##` matches one or more instances of `a` [Answer] # Alternatives to common commands * `echo` can be replaced by: + `print` + `<<<string` (limited syntax) + `printf %s` (joins with no whitespace and doesn't have a trailing new-line) * `printf` and `print -f` are identical * `ls` can be replaced by: + `dir -w1` is exactly the same + `vdir` is almost the same, except that its output format is different + `echo *` + `echo ?#` (requires `--extendedglob`) * `cat` can be replaced by: + `<file` or `<&1` where `1` is a file descriptor (also shorter and does't use any external commands!) + `cut -f1-` + `sed ""` + `dd` (but has a different syntax) + `tee` (only for stdin) + `grep $` + `head -X` or `tail -X`, where `X` is known to be greater than the number of lines (or without a `-X` if `X < 10`) + `fold -X`, where `X` is known to be greater than the maximum line length (or without a `-X` if `X < 80`) + `expand`, when there are known to be no spaces + `tac`, when there is only one line + `tac|tac` + `rev`, when there is only one character per line + `rev|rev` + `sort`, when the lines are known to be sorted + `uniq`, when there are known not to be any repeated lines [Answer] # Syntax in which (nearly) any character can be used Yes, even control characters. Yes, even the null byte. Replace `%` in the following expressions: * Delimiters for PE flags: `${(s%foo%)1}` (exceptions: one of `<` `(` `[` `{` must have the associated paired delimiter `>` `)` `]` `}`) * Similarly, delimiters for the `F`, `W`, and `s` modifiers: `${1:F%expr%}`, `${1:s%str%repl}` (same exceptions) * Zsh's equivalent to `ord` (as already mentioned): `$[##%]` (exceptions: `]` must be `\`-escaped, as does `\`) [Answer] # ASCII character conversion zsh has no explicit `chr` and `ord` functions, but they are achievable in various ways. ## `ord`: * `$[#A]` - the value of the first character in the variable `A` * `$[##x]` - the value of `x` * `chars=({!..~}); $chars[(i)$A]` - construct an ASCII array and find the index of a value in it (doesn't work for control characters, whitespace, or Unicode) ## `chr`: * `${(#)A}` - the character with the codepoint stored in the variable `A` * `$'\157'`, `$'\x6f'` - literals with codepoint octal 157 or hexadecimal 6F + this syntax doesn't allow variable substitutions, but we could be use an `eval`, like `eval "echo $'\\$A'"` * `echo \\157` - literal octal/hex escape sequences + can also use `print` or `printf` instead of `echo` + variable substitution is possible, so we can use a decimal value by converting to octal: `\\$(printf %o $A)` or `\\$[[##8]A]` * `chars=({!..~}); $chars[A]` - construct an ASCII array and index into it (doesn't work for control characters, whitespace, or Unicode) [Answer] # Variables without a `$` Here are a variety of techniques for storing and accessing data without using the typical `$variable` expansion syntax. ## Listing The `set` builtin lists all variables and their values, which you can explicitly sift through to find the one you want. For example, `set|grep my_var_name|cut -d= -f2-`. You can also use `typeset`, `declare`, `local`, `float`, or `integer` in place of `set` (those last two operate only on their namesake types, which are assigned implicitly when used in arithmetic expressions) This may be unreliable if the variable is an array of if its value has special characters. ## Named Directories Detailed in `zshexpn(1)` § Filename Expansion, named directories are intended as shortcuts for typing whole paths in an interactive shell, but they work in scripts too. "Assignment" is done with `hash -d name=value`, and expansion is done with `~name`. The expansion only works when at the start of a whole word and can't be followed by anything except a `/`. You can also use `hash -dm name` or `hash -dv name` which finds the value of `name`, or use `hashs -d` on its own to list all the values, and then find the right one using a similar technique to above. ## Fake command names Similar to named directories, but without the `-d`. The `hash` builtin would ordinarily add the `value` as the cached lookup path for the "command" `name` when it is looked up in `$PATH`. Expansion can be done with one of: * `which name` * `where name` * `whence name` * `hash`, with `-v` or `-m`, as detailed above * `command -v name` * `command -V name` (has a weird locale-dependent prosaic output format which needs to be parsed) ]
[Question] [ ## Background **Tents and Trees** (try [here](https://www.brainbashers.com/tents.asp)) is a puzzle played on a square (or rectangular) grid, where the objective is to place tents horizontally or vertically adjacent to each of the trees, so that no two tents touch each other in 8 directions (horizontally, vertically, and diagonally) and the number of tents on each row/column matches the given clues. ### Example puzzle and solution In these examples, trees are `T` and tents are `A`. ``` Puzzle 2 0 2 0 2 1 2 . T . T . . 1 . . . . T . 1 T . T . . . 2 . . . . . T 1 T . . . . . 0 . . . . . . Solution 2 0 2 0 2 1 2 . T A T A . 1 A . . . T . 1 T . T . A . 2 A . A . . T 1 T . . . . A 0 . . . . . . ``` ## Challenge Given a grid with some tents and trees, determine whether the tents are placed correctly. Ignore the number clues in this challenge. In particular, your program should check the following: * The number of tents equals the number of trees, * The tents do not touch each other in 8 directions, and * There is at least one way to associate every tent with an adjacent tree in 4 directions, so that every tree is used exactly once. If all of the above are satisfied, output a truthy value; otherwise, output a falsy value. You can choose to follow your language's convention of truthy/falsy, or use two distinct values for true/false respectively. You may take the input in any reasonable way to represent a matrix containing three distinct values to represent a tree, a tent, and an empty space respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases This uses the same notation as the above example; `T` for trees, `A` for tents, and `.` for empty spaces. ### Truthy ``` . . . . . . . . . (empty board) T A A T A . . T A T A T . T A T A (note that there are two ways to associate tents with trees) A . . T T A A T T . . A . T A . A . . T T T . A . A . . ``` ### Falsy ``` (The number of Ts and As don't match) T A T A T (Two A's touch each other) T A T A . . A . . A T T T T . A A . (Some T's are not associated with an A) A T A T T . A T A A . T T T A A . . ``` [Answer] # [J](http://jsoftware.com/), 88 86 bytes Expects a matrix with 0 for `.`, 1 for `A` and 2 for `T`. ``` (2>1#.1=,);.3~&2 2*/@,&,1&=((1 e.[:*/"{2>[:+/"1|@-"2)i.@!@#A.]) ::0&($ #:i.@$#~&,])2&= ``` [Try it online!](https://tio.run/##dY8xb8IwEIX3/Iprghybmgs220VGOSF16lTdhoAJIhhZqfjr6bmVuuAMJ0v3Pb977zbV2F4gEbTgYQ2ks0LYfX1@TDZuQ4Mhedfj5mkixGU3eOODSdYGOOOell39iNs9vXd1@B5WdXRXHN6GhvHggGht7AIa0t2ieRp/cNGkyU1johZZWnPF6p7Ijkc6Bejh4qo7jD2eItjfKK5CxP95pSysRGaIKMlvgaqbKGER/V9SoDBmmahOBcjF@8XLJR3LzLbsyzmUSE7HPFdcg83Wk7962fwH "J – Try It Online") ### How it works ``` 1&= (…) 2&= ``` Tents on the left side, trees on the right side. ``` (…)&($#:i.@$#~&,]) ``` Convert both arguments to 2D coordinates. ``` (…) ::0 ``` If the following function throws an error, return 0. This happens only in the single `A` case. :-( ``` i.@!@#A.] ``` List all permutations of the trees. ``` |@-"2 ``` Get the difference between the tents from every permutation. ``` [:*/2>[:+/"1 ``` Check that each difference's sum is 1. ``` 1 e. ``` Does any permutation fulfill this? ``` (2>1#.1=,);.3~&2 2 ``` Get all 2x2 matrices of the original, and check if there is at most one tent in there. ``` */@,@, ``` Combine both results, flatten the lists, and check if there are only 1's. [Answer] # JavaScript (ES7), ~~159 156~~ 153 bytes Expects a matrix of integers, with **0** for empty, **-1** for a tree and **1** for a tent. Returns **0** or **1**. ``` m=>(g=(X,Y,R)=>!/1/.test(m)|m.some((r,y)=>r.some((v,x)=>1/Y?(q=(x-X)**2+(y-Y)**2)?R?v+q?0:g(R[X]=r[x]=0)|R[X]++|r[x]--:q<3*v:0:v>0&&!g(x,y)&g(x,y,r))))`` ``` [Try it online!](https://tio.run/##XU9Nj9owEL37V5gLGUNiQnuolK2JcuheK7E@gABpo5BkXeUD7GwUVPrbqT/StFtb9sx7M/Oe/SPtU5VJcemCpj3nj4I9araBksHO3/tbwjaz1XpFu1x1UJN7TVVb5wDSv@mSHFHvDxqtV/sYrgyGYEcWi09LuAV7k5B4G/fLaxxGJWwPuxOTh@HEQnI3YLm8GxgE0fXr50UfhVG/CefzWQmDtpjb4Eui1@vrQ@bXdyFz8ArlESrz9Pwsqvzl1mQQEtq1L50UTQmEqkslOvCOzbHRjUUrv6XZG4DysSCYbfBPhPFM4BhnbaPaKqdVW4J34PK9e7udPIIjLDBj@Mv/Lcfm8JxWauwJn7TOv/UC1F9v7VynF5DGUP6h8chmhvU4TTwqmnM@fC8gIzjAa/PVJ/SLPCjmOLGHIn3s5jrnLk68q3HLu50gOuUUOfDh1r0JQlYcueERWO0xd6aaMsBQHDlxRD@8itsW55qM8nrYmhhlF8ZKMj7QjDjFxEpN/tzqTv588tdzvwE "JavaScript (Node.js) – Try It Online") ### How? The main recursive function is used to perform 3 distinct tasks. The corresponding calls are marked as A-type, B-type and C-type respectively in the commented source. Below is a summary: ``` type | Y defined | R defined | task --------+-----------+-----------+---------------------------------------------------- A-type | no | no | Look for tents. Process B-type and C-type calls | | | for each of them. --------+-----------+-----------+---------------------------------------------------- B-type | yes | no | Look for another tent touching the reference tent. --------+-----------+-----------+---------------------------------------------------- C-type | yes | yes | Look for adjacent trees. Attempt to remove each of | | | them with the reference tent. Chain with an A-type | | | call. ``` ### Commented ``` m => ( // m[] = input matrix g = ( // g is the main recursive function taking: X, Y, // (X, Y) = reference tent coordinates R // R[] = reference tent row ) => // !/1/.test(m) | // success if all the tents and trees have been removed m.some((r, y) => // for each row r[] at position y in m[]: r.some((v, x) => // for each value v at position x in r[]: 1 / Y ? // if Y is defined: ( q = (x - X) ** 2 // q = squared distance (quadrance) + (y - Y) ** 2 // between (x, y) and (X, Y) ) ? // if it's not equal to 0: R ? // if R[] is defined (C-type call): v + q ? 0 : // if v = -1 and q = 1, meaning that we have // found an adjacent tree: g( // do an A-type recursive call: R[X] = // with both the reference tent r[x] = 0 // and this tree removed ) // end of recursive call | R[X]++ // restore the tent | r[x]-- // and the tree : // else (B-type call): q < 3 * v // test whether this is a tent with q < 3 : // else (q = 0): 0 // do nothing : // else (A-type call): v > 0 && // if this is a tent: !g(x, y) // do a B-type recursive call to make sure it's & // not touching another tent g(x, y, r) // do a C-type recursive call to make sure that // it can be associated to a tree ) // end of inner some() ) // end of outer some() )`` // initial A-type call to g with both Y and R undefined ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~53~~ ~~49~~ ~~42~~ 60 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1«ÐεNUεXN)]€`{.¡н}¦`UœεX‚®ζε`αO<]PßsZðת€ü2ø€ü2J˜2δ¢à*ISPΘ‚à ``` +11 bytes as bug-fix (thanks for noticing *@xash*) and +7 bytes to account for inputs only containing empty cells.. Not too happy with the current program full of ugly edge-case workarounds tbh, but it works.. Input as a list of string-lines, where \$2\$ is a tent; \$3\$ is a tree; and \$1\$ is an empty spot. Outputs \$1\$ for truthy; and anything else for falsey (only \$1\$ is truthy in 05AB1E, so this is allowed by the challenge rule "*You can choose to follow your language's convention of truthy/falsy*"). [Try it online](https://tio.run/##yy9OTMpM/f/f8NDqwxPObfULPbc1wk8z9lHTmoRqvUMLL@ytPbQsIfToZKDwo4ZZh9ad23Zua8K5jf42sQGH5xdHHd5wePqhVUDVh/cYHd4Bob1OzzE6t@XQosMLtDyDA87NAOo7vOD//2glI0NDJR0lY2MjIGlkbAwkDQ2NlGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lot7HPo4Zleo4hjxoW6nAp@ZeWQKTsK5X@Gx5afXjCua1@oee2Rvhpxj5qWpNQrXdo4YW9tYeWJYQenQwUftQw69C6c9vObU04t9HfJjbg8PziqMMbDk8/tAqo@vAeo8M7ILTX6TlG57YcWnR4gVZlcMC5GUB9hxf8V9IL0zm0zf5/dLSSsZFSrE60khGQ1lEyNDRG4hkDeTpgNljM0BAkBpYxMjYGq4bIGBobgaSMDMHqjY0NwUaB1CObBeEZgk1BkBAxMAfCBpNAA40gNkBVGkH0KwClIIZClRnDabD9MIeCbTSGONLICMUdxoYofjJG@MkQp90gE2IB). **Explanation:** I do three main steps: Step 1: Get all coordinates of the trees and tents, and check whether there is a permutation of tree permutations that has a horizontal or vertical distance of 1 with the tent coordinates. ``` 1« # Add a trailing empty spot to each row # (to account for matrices with only tents/trees and single-cell inputs) Ð # Triplicate this matrix with added trailing 2s ε # Map each row to: NU # Store the index of this outer map in `X` ε # Inner map over each cell of this row: XN) # Create a triplet of the cell-value, `X`, and the inner map-index `N` ] # Close the nested maps €` # Flatten the list of lists of cell-coordinates one level down { # Sort the list of coordinates, so the empty spots are before tents, and tents # before trees .¡ } # Then group them by: н # Their first item (the type of cell) ¦ # And remove the first group of empty spots ` # Pop and push the list of tree and tent coordinates separated to the stack U # Pop and store the tent coordinates in variable `X` # (or the input with trailing empty spots if there were only empty spots in # the input) œ # Get all permutations of the tree coordinates # (or the input with trailing empty spots if there are none, hence the # triplicate instead of duplicate..) ε # Map each permutation of tree coordinates to: X‚ # Pair it with the tent coordinates `X` ζ # Zip/transpose; swapping rows/columns, ® # with -1 as filler value if the amount of tents/trees isn't equal ε # Map each pair of triplets to: ` # Pop and push them separated to the stack α # Get the absolute different between the values at the same positions O # Take the sum of those differences for each triplet < # Subtract each by 1 to account for the [2,3] of the tree/tent types ] # Close the nested maps P # Take the product of each difference of coordinates ß # And pop and push the smallest difference ``` Step 2: Get all 2x2 blocks of the matrix, and check that each block contains either none or a single tent (by counting the amount of tents per 2x2 block, and then getting the maximum). ``` s # Swap to get the input-matrix with trailing empty spots we triplicated Z # Get its maximum (without popping) ð× # Create a string with that many spaces ª # And append it to the list # (it's usually way too large, but that doesn't matter since it's shortened # automatically by the `ø` below) € # For each row: ü2 # Create overlapping pairs # (the `ü2` doesn't work for single characters, hence the need for the # `1«` and `Zðת` prior) ø # Zip/transpose; swapping rows/columns # (which also shortens the very long final row of space-pairs) € # For each column of width 2: ü2 # Create overlapping pairs # (we now have a list of 2x2 blocks) J # Join all 2x2 blocks together to a single 4-sized string ˜ # And flatten the list δ # Then for each 4-sized string: 2 ¢ # Count the amount of tents it contains à # Pop and get the maximum count # (if this maximum is 1, it means there aren't any adjacent nor diagonally # adjacent tents in any 2x2 block) ``` Step 3: Add the checks together, and account for inputs consisting only of empty spots as edge-case: ``` * # Multiply the two values together I # Push the input-matrix again S # Convert it to a flattened list of digits P # Take the product Θ # Check that this is exactly 1 (1 if 1; 0 if not) ‚ # Pair it with the multiplied earlier two checks à # And pop and push the maximum of this pair # (for which 1 is truthy; and anything else is falsey) # (after which it is output implicitly as result) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 59 47 54 45 bytes Trying to get into Brachylog lately, so here is a (now very) rough port of my J approach. Takes in a matrix with 0 for `.`, 2 for `A` and 3 for `T`. Either fails to unify (prints false) or doesn't. ``` c=₀|¬{s₂\s₂c⊇Ċ=₂}&{iiʰgᵗcṗʰ}ᶠhᵍpᵗz₂{\b-ᵐȧᵐ+1}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P9n2UVNDzaE11cWPmppiQETyo672I11A4aZaterMzFMb0h9unZ78cOf0UxtqH25bUJDxcGtvFVC2OiZJ9@HWCSeWAwltw1og@f9/dLSBjrGOkY5BrE40kARCYyDLGChmoGMEZBnogEVjY/9HAQA "Brachylog – Try It Online") or [verify all test cases](https://tio.run/##SypKTM6ozMlPN/r/vzrZ9lFTg1rNoTXVxY@ammJARPKjrvYjXUDxplq16szMUxvSH26dnvxw5/RTG2ofbltQkPFwa28VULY6Jkn34dYJJ5YDCW3DWiCpVnt60f//0dHRBjpAGKsDpYGMaGMdIzBtpANiQWSMUUSMwSI6UD5EBmKKMVQFSMYYqheiwgAkA1YDVguWBak2gNphhLAfYiLMLVC7ISyoboSdUPcYw@0zAtuC6lpjqL3IrjVGcS3YzNj/UQA) (returns truthy cases). ### How it works ``` c=₀| ``` Either the flatten matrix contains only 0's or … ``` ¬{s₂\s₂c ``` No 2x2 submatrix flattened … ``` ⊇Ċ=₂} ``` contains an ordered subset of length 2 that is just 2's (tents). ``` &{iiʰgᵗc ``` And the input must be converted to `[type, y, x]`, where … ``` ṗʰ} ``` `type` is a prime (there seems no shorter way to filter out 0). ``` ᶠp ``` Find all `[type, y, x]` put them into a list, and permute this list. ``` hᵍ ``` Group them by their `type`; `[[[3,0,2], …], [[4,1,2], …]]`. ``` z₂ ``` Zip both groups together and make sure they have the same length. We now have `[[[3,0,2], [4,1,2]], …]` ``` {\b-ᵐȧᵐ+1}ᵐ ``` For every element `[[3,0,2], [4,1,2]]` transpose `[[3,4],[0,1],[2,2]]` behead `[[0,1],[2,2]]` subtract `[_1,0]` absolute value `[1,0]` sum `1` and that must unify with 1. So this unifies if any permutation of the one group is exactly 1 tile away from the other one. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 146 bytes ``` <<Combinatorica` f=2*Length@MaximalMatching@MakeGraph[v=Position[#,A|T],Norm[#-#2]==1&]==Length@v&& And@@Join@@BlockMap[Count[#,A,2]<2&,#,{2,2},1]& ``` [Try it online!](https://tio.run/##bU5BasMwELzrGwYdyhYSXWuD1BQKpS456GYEVV0nFokl4yqh4PrtrixvmhqCQLuzszszjfZ11WhvSj2OabpxzYex2rsuDN7JLmN3r5Xd@5rn@ts0@phrX9bG7gM@VM@dbuvinG3dl/HG2SIB8SMVvLmuKZL7hKksW9PwocaZUmE/OX9xxnL@eHTlIddtsXEn66dbYCplFBLoGbAB1oqOT64g285Yz41tT/4Bwe4CCfSxA9L3/QrCGwBraG5MJIhYBUzdzMjFRMYJIJ6ZWUXixsRIvBXoE5i4E3cjO22v0ENc/WfFSxb0nju8vnpiHvnnJ6LLMq1E3/9p5SJt1BzIoMZf "Wolfram Language (Mathematica) – Try It Online") Note: * The second line break is only added in the post for ease of reading. * importing `Combinatorica` later will make the symbols refer to the Global ones and will not have the correct result. * Although `Combinatorica`MakeGraph` is rather long, `MaximalMatching` is 7 characters shorter than `FindIndependentEdgeSet`. * I suppose this solution is the fastest...? [There exists](https://en.wikipedia.org/wiki/Blossom_algorithm) algorithms to find maximal matching in polynomial time, while testing all permutations take exponential time. ]
[Question] [ Here is a relatively simple two dimensional array challenge. Imagine a battlefield of 625 foot soldiers. You command the ***odd*** troops, but unfortunately the strength of the ***even*** troops overwhelms you. Thankfully, your soldiers have a secret power: If the power of each odd troop and the fellow odd allies surrounding them is divisible by a secret power number, they unleash their *ultimate attack* and win! You must honor each victorious soldier. **Rules** Given a 25 x 25 integer array where each element contains the product of its x and y position plus 1, return the coordinates of every "victorious" odd element that meets the following criteria: The sum of the element's value and its adjacent odd elements (up, down, left, and right) is divisible by the input (secret power number). It must have elements adjacent to it on all four sides and not be on an edge. Submissions can be either a function or full program that requires a single input. The output can be in any order. Our 25 x 25 array, the battlefield, looks like this: ``` 1, 1, 1, 1,... 1, 2, 3, 4,... 1, 3, 5, 7,... 1, 4, 7, 10,... etc. ``` **Example** Here is a 3 x 3 example: ``` 43, 57, 71 46, 61, 76 49, 65, 81 ``` To determine if an element (61, in the center) wins, we sum the values of it and the adjacent odd elements. ``` 61 + 57 + 65 = 183 ``` If the total is divisible by the input, the element's x and y position is printed. If our input is 3, because 183 is divisible by 3, "1, 1" is printed. **Output** If the input (secret power number) is 37, the elements returned (victorious soldiers to be commended) must be: ``` 2, 18 3, 12 4, 9 5, 22 6, 6 8, 23 9, 4 10, 11 11, 10 12, 3 18, 2 22, 5 23, 8 ``` If the input is 191, the elements returned must be: ``` 10, 19 19, 10 ``` An input of 3: ``` 1, 2 1, 4 1, 6 1, 8 1, 10 1, 12 1, 14 1, 16 1, 18 1, 20 1, 22 2, 1 2, 3 2, 4 2, 5 2, 7 2, 9 2, 10 2, 11 2, 13 2, 15 2, 16 2, 17 2, 19 2, 21 2, 22 2, 23 3, 2 3, 4 3, 6 3, 8 3, 10 3, 12 3, 14 3, 16 3, 18 3, 20 3, 22 4, 1 4, 2 4, 3 4, 5 4, 7 4, 8 4, 9 4, 11 4, 13 4, 14 4, 15 4, 17 4, 19 4, 20 4, 21 4, 23 5, 2 5, 4 5, 6 5, 8 5, 10 5, 12 5, 14 5, 16 5, 18 5, 20 5, 22 6, 1 6, 3 6, 5 6, 7 6, 9 6, 11 6, 13 6, 15 6, 17 6, 19 6, 21 6, 23 7, 2 7, 4 7, 6 7, 8 7, 10 7, 12 7, 14 7, 16 7, 18 7, 20 7, 22 8, 1 8, 3 8, 4 8, 5 8, 7 8, 9 8, 10 8, 11 8, 13 8, 15 8, 16 8, 17 8, 19 8, 21 8, 22 8, 23 9, 2 9, 4 9, 6 9, 8 9, 10 9, 12 9, 14 9, 16 9, 18 9, 20 9, 22 10, 1 10, 2 10, 3 10, 5 10, 7 10, 8 10, 9 10, 11 10, 13 10, 14 10, 15 10, 17 10, 19 10, 20 10, 21 10, 23 11, 2 11, 4 11, 6 11, 8 11, 10 11, 12 11, 14 11, 16 11, 18 11, 20 11, 22 12, 1 12, 3 12, 5 12, 7 12, 9 12, 11 12, 13 12, 15 12, 17 12, 19 12, 21 12, 23 13, 2 13, 4 13, 6 13, 8 13, 10 13, 12 13, 14 13, 16 13, 18 13, 20 13, 22 14, 1 14, 3 14, 4 14, 5 14, 7 14, 9 14, 10 14, 11 14, 13 14, 15 14, 16 14, 17 14, 19 14, 21 14, 22 14, 23 15, 2 15, 4 15, 6 15, 8 15, 10 15, 12 15, 14 15, 16 15, 18 15, 20 15, 22 16, 1 16, 2 16, 3 16, 5 16, 7 16, 8 16, 9 16, 11 16, 13 16, 14 16, 15 16, 17 16, 19 16, 20 16, 21 16, 23 17, 2 17, 4 17, 6 17, 8 17, 10 17, 12 17, 14 17, 16 17, 18 17, 20 17, 22 18, 1 18, 3 18, 5 18, 7 18, 9 18, 11 18, 13 18, 15 18, 17 18, 19 18, 21 18, 23 19, 2 19, 4 19, 6 19, 8 19, 10 19, 12 19, 14 19, 16 19, 18 19, 20 19, 22 20, 1 20, 3 20, 4 20, 5 20, 7 20, 9 20, 10 20, 11 20, 13 20, 15 20, 16 20, 17 20, 19 20, 21 20, 22 20, 23 21, 2 21, 4 21, 6 21, 8 21, 10 21, 12 21, 14 21, 16 21, 18 21, 20 21, 22 22, 1 22, 2 22, 3 22, 5 22, 7 22, 8 22, 9 22, 11 22, 13 22, 14 22, 15 22, 17 22, 19 22, 20 22, 21 22, 23 23, 2 23, 4 23, 6 23, 8 23, 10 23, 12 23, 14 23, 16 23, 18 23, 20 23, 22 ``` An input of 5: ``` 1, 4 1, 14 2, 2 2, 4 2, 6 2, 7 2, 8 2, 10 2, 12 2, 14 2, 16 2, 17 2, 18 2, 20 2, 22 3, 8 3, 18 4, 1 4, 2 4, 4 4, 6 4, 8 4, 10 4, 11 4, 12 4, 14 4, 16 4, 18 4, 20 4, 21 4, 22 6, 2 6, 4 6, 6 6, 8 6, 9 6, 10 6, 12 6, 14 6, 16 6, 18 6, 19 6, 20 6, 22 7, 2 7, 12 7, 22 8, 2 8, 3 8, 4 8, 6 8, 8 8, 10 8, 12 8, 13 8, 14 8, 16 8, 18 8, 20 8, 22 8, 23 9, 6 9, 16 10, 2 10, 4 10, 6 10, 8 10, 10 10, 12 10, 14 10, 16 10, 18 10, 20 10, 22 11, 4 11, 14 12, 2 12, 4 12, 6 12, 7 12, 8 12, 10 12, 12 12, 14 12, 16 12, 17 12, 18 12, 20 12, 22 13, 8 13, 18 14, 1 14, 2 14, 4 14, 6 14, 8 14, 10 14, 11 14, 12 14, 14 14, 16 14, 18 14, 20 14, 21 14, 22 16, 2 16, 4 16, 6 16, 8 16, 9 16, 10 16, 12 16, 14 16, 16 16, 18 16, 19 16, 20 16, 22 17, 2 17, 12 17, 22 18, 2 18, 3 18, 4 18, 6 18, 8 18, 10 18, 12 18, 13 18, 14 18, 16 18, 18 18, 20 18, 22 18, 23 19, 6 19, 16 20, 2 20, 4 20, 6 20, 8 20, 10 20, 12 20, 14 20, 16 20, 18 20, 20 20, 22 21, 4 21, 14 22, 2 22, 4 22, 6 22, 7 22, 8 22, 10 22, 12 22, 14 22, 16 22, 17 22, 18 22, 20 22, 22 23, 8 23, 18 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest byte-count code without using standard loopholes is the winner. As this is my first submission, any advice is greatly appreciated. Thanks! [Answer] # JavaScript (ES6), ~~83 81 80~~ 76 bytes The output is a space-delimited string of coordinates \$x,y\$. ``` f=(n,x=y=23,k=5,v=x*y)=>y?(v&1|~v*k%n?[]:[x,y]+' ')+f(n,--x||23|!y--,k^6):[] ``` [Try it online!](https://tio.run/##ZcvRCsIgFADQ976iHmreTQMnbTS47UPEYKwZ5dBoIQrSr1vP9Xrg3Ac/LOPz9ngx6y5TzhqJpQEj1oIaPFCPoYyAp9gTv@Pp7Uuztb1UnQw0qqpYF1Dpb2EspFSLtImMUXNuoJMqj84ubp72s7sSTYQAWP1Q@0f8yAHyBw "JavaScript (Node.js) – Try It Online") ### How? Let \$c\_{x,y}=xy+1\$ be the value of the cell located at \$(x,y)\$. Since the cells on the edge are not accounted, we assume \$0<x<24\$ and \$0<y<24\$. \$c\_{x,y}\$ is odd if either \$x\$ or \$y\$ is even (or both of them). If \$x\$ is odd, then \$c\_{x-1,y}\$ and \$c\_{x+1,y}\$ are odd. But in that case, \$y\$ must be even, and so are \$c\_{x,y-1}\$ and \$c\_{x,y+1}\$. The sum of the cell and its odd surrounding neighbors is: $$s\_{x,y}=c\_{x,y}+c\_{x-1,y}+c\_{x+1,y}=3c\_{x,y}$$ Similarly, if \$y\$ is odd: $$s\_{x,y}=c\_{x,y}+c\_{x,y-1}+c\_{x,y+1}=3c\_{x,y}$$ If both \$x\$ and \$y\$ are even, all surrounding neighbors are odd: $$s\_{x,y}=c\_{x,y}+c\_{x-1,y}+c\_{x+1,y}+c\_{x,y-1}+c\_{x,y+1}=5c\_{x,y}$$ This multiplier (\$3\$ or \$5\$) is named \$k\$ in the JS code. ### Commented ``` f = ( // f is a recursive function taking: n, // n = input x = y = 23, // (x, y) = current coordinates, starting at (23, 23) k = 5, // k = multiplier (3 or 5) v = x * y // v = x * y (value of the current cell - 1) ) => // y ? // if y is greater than 0: ( v & 1 | // if v is odd (meaning that v + 1 is not) ~v * k % n ? // or n is not a divisor of -(v + 1) * k: [] // append nothing : // else: [x, y] + ' ' // append the coordinates followed by a space ) + // f( // append the result of a recursive call: n, // pass n unchanged --x || // decrement x; if the result is 0: 23 | !y--, // pass 23 instead and decrement y k ^ 6 // update k (5 -> 3 -> 5 -> ...) ) // end of recursive call : // else: [] // stop recursion ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~97~~ ~~93~~ ~~91~~ 90 bytes ``` x=>{for(int i=0,d=0,j;++i<24;d=5)for(j=0;++j<24;d^=6)if(i*j%2+(i*j+1)*d%x<1)Print((i,j));} ``` Saved 6 bytes thanks to @Kevin Cruijssen! [Try it online!](https://tio.run/##bYyxCsIwFEX3fIVL4b2mQlOtIkkK7g5ubi5JAy9DCmmGgvjtMXHucDncc@Ga9WhWyneTaAmKQpqczpuePm6JUOqBdN/ZEi85JzWcpdUj1tHrvij/V299QXJArW8GXsEFtrbZlMBnLC8A1HlE@c2SORA3gZKxV6Q0PyjMUJuD03XX7smxIP8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âÖÅ{┼îÄï$εS╢,σδXú(Γ°#↑√nG ``` [Run and debug it](https://staxlang.xyz/#p=83998f7bc58c8e8b24ee53b62ce5eb58a328e2f82318fb6e47&i=37%0A191%0A3%0A5&a=1&m=2) This is mostly just brute force, with one marginally clever observation. All odd troops have either 2 or 4 odd neighbors. And the total sum of these plus the original solder is either `3p` or `5p` where `p` is the soldier's power. The coefficient (3 or 5) can be determined by `gcd(2, x, y) * 2 + 1)` where `x` and `y` are the soldier's coordinates. [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` lambda n:[(x,y)for x in R for y in R if~(x*y)*[5,3][x+y&1]%n<1>x*y%2] R=range(1,24) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlqjQqdSMy2/SKFCITNPIUgBxKyEMDPT6jQqtCo1taJNdYxjoyu0K9UMY1XzbAztgKKqRrFcQbZFiXnpqRqGOkYmmv8LijLzShTSNIzNNbngbGME29DSEMbJSc3TAEpqovJNNTX/AwA "Python 2 – Try It Online") Thanks to Arnauld for saving a byte. [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes ``` x=>{for(i=24;--i;)for(j=24,d=5;--j;d^=6)i*j%2+~(i*j)*d%x||print(j,i)} ``` [Try it online!](https://tio.run/##FcjRCsIgFIDh@73H4LhmsK2CEHuUYEyNY8sjOmLR6tXtdPXz/X58jnlKGBeZIxqbHhTu9lWcLqu@vB0lQN0flJSoxF@e1Rp95OOVueqTwMbX/e4LXNGYet22mDAs4FsUn1I5GAahqolCptnuZ7oB00F37rjlBw "JavaScript (SpiderMonkey) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` 23×þ`‘µḤḤÐeÐe+×Ḃ³ḍaƊŒṪ ``` [Try it online!](https://tio.run/##y0rNyan8/9/I@PD0w/sSHjXMOLT14Y4lQHR4QioQaR@e/nBH06HND3f0Jh7rOjrp4c5V////NzYHAA "Jelly – Try It Online") A full program that takes a single argument, the secret power number, and implicitly prints a list of `[x, y]` pairs. Uses the observation others have made about multiples of 3 and 5. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 58 bytes ``` Position[If[2∣+##,5,3](1+1##)&~Array~{23,23},a_/;#∣a]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyC/OLMkMz8v2jMt2uhRx2JtZWUdUx3jWA1DbUNlZU21OseiosTKumojYx0j41qdxHh9a2WgssRYtf8BRZl5JdHKunZpDso6SjF5SrFq@g7VXMbmOlyGloY6XMY6XKZctf8B "Wolfram Language (Mathematica) – Try It Online") Looked around after posting and realized I really needed to turn my brain on... ]
[Question] [ Doing my history reading and note-taking, I can't help but get tired of writing out all these long dates –– 1784 is six entire pencil lifts! jǝǝz! As you can see, I –– like most challenge posters on this site –– am lazy when it comes to writing stuff. Thus, I ask you to please help me shorten some dates. Of course, your solution must be as short as possible since my hand is already tired from writing typing out the test cases. **How do I shorten a date?** Well funny you should ask. It's fairly simple: 1. Take two integers as input in whatever order you want (`(smallest, biggest)` or `(biggest, smallest)`). 2. Take the larger of the two numbers, and take only the part not in the smaller number. For example, given `2010, 2017`, shorten `2017` to `-7` because `201_` is in both at the same digit-places. 3. Print or return the smaller number, followed by a dash and then the shortened larger number. **For example:** ``` Bonus brownies for you if you figure out these dates' significance :) 1505, 1516 -> 1505-16 1989, 1991 -> 1989-91 1914, 1918 -> 1914-8 1833, 1871 -> 1833-71 1000, 2000 -> 1000-2000 1776, 2017 -> 1776-2017 2016, 2016 -> 2016- These dates lack significance :( 1234567890, 1234567891 -> 1234567890-1 600, 1600 -> 600-1600 1235, 1424 -> 1235-424 600, 6000 -> 600-6000 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DUµn/TṪṁ@Ṫ,j”-FṚ ``` A full program taking a list of years `from, to` and printing the result. **[Try it online!](https://tio.run/##y0rNyan8/98l9NDWPP2QhztXPdzZ6ACkdLIeNczVdXu4c9b///@jjQwMDXSMDIzMYwE "Jelly – Try It Online")** or see the [test suite](https://tio.run/##PY09DsIwDIWv0gO4Is5/FsSAOAEMKOrIElXsbMDSOyBYGRArQyWmIg6SXiQ4ATHY77Ot9xw2bbtLab4aHtvJMva32B9mJBDG/aVexP6U3s9XNx7vgQqHK3W6QCh6ruppReM6Je9RMQWoUDfg0VkH6BwWRkmMNrMVAtCasmeMAaeW2RhNjIaYpHDJ4UIqbaxj8Mfs1WRF/bVyQW8ll7@1zonNBw "Jelly – Try It Online"). ### How? ``` DUµn/TṪṁ@Ṫ,j”-FṚ - Main link: list of years [from, to] e.g [1833,1871] D - convert to decimals [[1,8,3,3],[1,8,7,1]] U - upend (to cater for differing lengths) [[3,3,8,1],[1,7,8,1]] µ - monadic chain separation, call that V / - reduce V with: n - not equal? [1,1,0,0] T - truthy indices [1, 2] Ṫ - tail 2 Ṫ - tail V (pop from & modify V) [1,7,8,1] ṁ@ - mould (swap @rguments) V like that length [1,7] , - pair that with (the modified) V [[1,7],[[3,3,8,1]] ”- - literal '-' character j - join [1,7,'-',[3,3,8,1]] F - flatten [1,7,'-',3,3,8,1] Ṛ - reverse [1,8,3,3,'-',7,1] - implicit print 1833-71 ``` [Answer] # Javascript ES6, ~~59~~ 57 chars ``` (x,y)=>(x+'-'+y).replace(x*10>y?/^((.*).*-)\2/:/()/,"$1") ``` Test: ``` f=(x,y)=>(x+'-'+y).replace(x*10>y?/^((.*).*-)\2/:/()/,"$1") console.log(`1505, 1516 -> 1505-16 1989, 1991 -> 1989-91 1914, 1918 -> 1914-8 1833, 1871 -> 1833-71 1000, 2000 -> 1000-2000 1776, 2017 -> 1776-2017 2016, 2016 -> 2016- 1234567890, 1234567891 -> 1234567890-1 600, 1600 -> 600-1600 1235, 1424 -> 1235-424`.split` `.map(t => t.match(/(\d+), (\d+) -> (.*)/)).every(([m,x,y,key]) => f(x,y)===key || console.log(x,y,key,f(x,y)))) console.log(f(600,6000)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` `R¹íζ€Ë1Üg£R‚'-ý ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/IejQzsNrz2171LTmcLfh4TnphxYHPWqYpa57eO///9FmBgY6CkDCIBYA "05AB1E – Try It Online") Uses Jonathan Allan's algorithm. [Answer] # Dyalog APL, 29 bytes ``` {⍺,'-',x/⍨⌈\~((-⍴x)↑⍕⍺)=x←⍕⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR727dNR11XUq9B/1rnjU0xFTp6Gh@6h3S4Xmo7aJj3qnAuU1bSuAKsHsrbX//xuaGpgqpCkYmhqacRlaWliC2JaWhkC2oQmYbWjBZWhhbAxiW5gDxQ0MDIBsIyDFZWhubgZmG5pzAQko24zLDKzEEEhBmUDSAAA) **How?** `⍺,'-'` - the first year + `, -`     `=x←⍕⍵` - compare the second year formatted     `((-⍴x)↑⍕⍺)` - to the first year padded with spaces from left     `⌈\~` - negate the result and mark all 1s after the first `x/⍨` - take the second year in all marked position [Answer] # [Retina](https://github.com/m-ender/retina), 34 bytes ``` (.*)((.)*),\1((?<-3>.)*)\b $1$2-$4 ``` [Try it online!](https://tio.run/##PY07DgIxDER7nyNFsvKuPM7HiYTgItuAREFDgbh/8G5B4dGbkZ78eX5f7/uccVtSjFtaEu@I8XZZ8/Vo@4MCgq6hzIkqlVHRCKMPxhhwQnFCJ/ScGd18ExFWD4JZc4KRx0nuai61WR/CfwQ1V9AORbM/KVrOyU9@ "Retina – Try It Online") Link includes test cases. The balancing group and the word boundary ensure that both numbers are the same length before the prefix is matched. If not, then the word boundary matches at the start of the second year, so all that happens is that the comma changes to a dash. [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` lambda s,n:`s`+'-'+[[`n`[i:]for i in range(len(`s`)+1)if `n`[:i]==`s`[:i]][-1],`n`][len(`n`)>len(`s`)] ``` [Try it online!](https://tio.run/##XZDNboMwEITveQqLC1g4EsuPbZDoi1BLUDW0llInIrn06emuUbDpBeOP2Vlm7r/P75sr17l/X6/Tz8fnxB7CdeNjzNNzmg/D6MbBdma@Lcwy69gyua9Ldr24DDU8B25nRprOmr5HRC9mOIMRSM3ghW7kb68Js6Zpel@se7I5S6ApmkQwPEEm/BR4q1vP2xaOHOqNgz5wXVWea3XUF0VBvKQz5krJjYOKOd5fnP7nFE2UVd1IpVvvt98O2@S2DOS/ZWW1hazLmkyPenqiHFvZP1ArglEnwYUaQYZ9xAxqYqAjhk0gwx4ihhsEow4ihg0QAxUYpfZMxtFDcvTdc4cpSeaUmccjFADzRnFJR1n5@gc "Python 2 – Try It Online") I feel like there has to be a better way to do this since it seems really verbose. Extreme abuse of the `` evaluation of variables for this to work since we can't take strings as input. [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` f=q.map show;q[a,b]=a++"-"++if(1<$a)<(1<$b)then b else snd<$>(snd$span(uncurry(==))$zip a b) ``` Takes input as a list of two integers [earlier date, later date]. [Try it online!](https://tio.run/##PY7LboMwEEXX4SusiIUt3MjDw9gq7he0qy4RC5MagUpcgkFV@/PUPJrNvXN0paNptfs0fb8sjbpfbnpArv36fr6XmtaV0lF0fjpHUddgKEJNirVqMrXGohqZ3hnk7EcRvmBfoRu0xbO9zuP4g5UiJPztBqRRTZab7qzy9jeEh3l6n8ZXe2kImoybXLAlUqgMTiVkLKOQAa/oSlJIClLCQZB6ArGTSBIKIj82xhiNfeyU59wT5Bv5Y6PDGSdpxnMhGX2cu4N7BfB/RZz4R9I4fUx8tQenavkD "Haskell – Try It Online") [Answer] ## Python 2, 127 bytes I am still new to this, so I don't know if it is okay to place another answer in the same language. Since I can't comment on other peoples posts yet I take my chances here. * Is it allowed to change the input from Integer to String? Cause that would save me around 10 bytes. * Arnlod Parmers answer has a mistake on 1989, 1991. (during the time I am posting this). Thank you tho for the `` evaluation trick tho (it saved me a byte)! ``` def f(s,b): s=`s`+'-' if len(`b`)>=len(s):return s+`b` for i in range(len(`b`)): if s[i]!=`b`[i]:return s+`b`[i:] return s ``` [Try it online!](https://tio.run/##Vc5LDoIwEAbgtT3FuAICJrTQFwlehJCgEbSJqabFhafHaYxSNu30y8zfeb7n28OyZbmME0ypL85ZQ8C3gx/y5JAQMBPcR5sO5yE7tqHyWePG@eUs@ByVwPRwYMBYcCd7HdNfN@bscNh3pt@3CHhvBjvT9AR@sjydsTNuQHnJC6Ccioz8TSuNpjWNjdbBqIpMVRWaknFfWZYFMDwjk1IEo3I1fH0N/10bWVVzIZXGiH8dhYuQTcUmm1Vh/5rV2zYRNlg@) What I do is, I compare each single digit from both times and if the bigger one varies I print the smaller number plus the rest of the bigger one. If someone could help me golf out the third line I would save like 30+ bytes. I only implemented it to handle the case of 600,6000 where the digits are equal but not the same length. [Answer] # [Haskell](https://www.haskell.org/), 143 bytes ``` g x y=h(show x)(show y) h x y=x++"-"++if length x<length y then y else foldl(\a(c,d)->if a==[]then if c==d then[]else[d]else a++[d])[](zip x y) ``` [Try it online!](https://tio.run/##VZJNboMwEIX3nGKEujAylnDCb1Vyg56AsLDACagOQYWqkMvTGSeB1AvPe/5m7JHtRg1f2phlOcMEc96wobn@wuTd4@w5jV2fOHeFy3l7AqO784irHw8xw9joDoM2g4bT1dSGHRWr/NoTB8xXeV6UNgVNlee1zS9KSi9qG0BxjtIrSnZrezrQW/SkLr3RA@RQOICDySiIfJCRjH1wyQgZu57/gFmaIcwySRCNyOQLlCFBmVooQ5FuLN3vkaWJLUQjkpfCIAh82NnZJSNIbzhJYsIyIYxGkF4xmjumhimIrXK3D6M4STPceNW2gxWIrY2Yzpd2dnEWJF@3omsJd@G9PBIo/5fGwVoa2/5Lx7motsO7vaj@E9iRTT7MPtzwyfrvthvfnv8A3x0rOX/@B/QgDqCnXlejrt@J3WySqsYfZewCs5/J8@D5iMsf "Haskell – Try It Online") `smallest biggest` input (integers). `if length x<length y then y` means that if `x` has less digits than `y` then the common part is void. Else, we store the digits of `y` from the first different digit. [Answer] # [Python 2](https://docs.python.org/2/), ~~89~~ 88 bytes ``` lambda a,b:`a`+'-'+`b`[map(lambda c,d:(len(`a`)==len(`b`))*(c==d),`a`,`b*10`).index(0):] ``` [Try it online!](https://tio.run/##VY/dDoIwDIXvfQruWHGabbA/kj2JmmwDiSaKxHihT49FDcybpv3OyWk7vB6nWy/Gzu3HS7jGNmSBxtoHv843@dpHv7uGgfykhrY1uRx7gjo49@miByhI41wLFDH1seDMw/bct8cnYVAfxuF@7h9ZR7hkkmZccgWrmVljkVnLU8ariXGTMFOWyIxOfYwxmgmsCdNaTYzrheH0Zbh3tThFWUmljcWMuU/T9SSov3BRTg9UQsKSgw6qPjekh1F8CcY3 "Python 2 – Try It Online") [Answer] # Common Lisp, 120 bytes ``` (lambda(s b &aux(d(#1=format()"~a"b)))(#1#()"~a-~a"s(if(<=(* s 10)b)b(subseq d(or(mismatch d(#1#()"~a"s))(length d)))))) ``` [Try it online!](https://tio.run/##PZDtisIwEEVf5VLZ3ZkFIdOPJAXdd0ms7hZaq6aC/vHV3UkF8@Pm9MKZDN0NfTo9aZimEw7TBXTDndEf8UUkjWkgjVgmaX0LaVvJKLWieEVfVRDvcmuMQamh6JxVFMekuWCeUFZ1Y51vDd6onlVN7KKVlb5Wl/WrtHkWo5tAutcYZswoHgFr5PjRfHwU0G1Bun4YYxcoIeIzXG/U0Uq2L41YrSIys3ar5WutRaL@QJstfSNBDEeOlK4x7c/oaLrQ2Cd1d3/o3laRdMSwP/7O2vJynvln6fUP) Smallest, Biggest. Ungolfed: ``` (defun f(s b &aux (d (format () "~a" b))) ; s and b parameters, d string from s (format () "~a-~a" s ; print first number, then -, then abbreviation (if (<= (* s 10) b) ; if b is too large do not abbreviate b (subseq d (or (mismatch d (format () "~a" s)) ; else find first mismatch (length d)))))) ; then extract the last part from mismatch ; or nothing if they are equal ``` [Answer] ## C++, ~~285~~ 271 bytes -14 bytes thanks to Zacharý ``` #include<iostream> #include<string> #define S s.size() #define R r.size() using namespace std;void h(int a,int b){auto r=to_string(a),s=to_string(b);if(R>S)s=string(R-S,' ')+s;if(S>R)r=string(S-R,' ')+r;int i=0;for(;i<R;++i)if(r[i]!=s[i])break;cout<<a<<'-'<<s.substr(i);} ``` Code for testing : ``` std::vector<std::pair<int, int>> test = { {1505,1516}, {1989,1991}, //End of the cold war {1914,1918}, //First world war start and end {1833,1871}, {1000,2000}, //2000 = Y2K bug, 1000 is... well... Y1K bug ? :) {1776,2017}, //US constitution signed the 4th july, French elections & year of the C++ 17 standard {2016,2016}, //US elections {1234567890,1234567891}, {600,1600}, {1235,1424}, {600,6000} }; for (auto&a : test) { h(a.first, a.second); std::cout << '\n'; } ``` ]
[Question] [ Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list. * If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this: ``` } { {2 , 1} ``` For example, `{2, 1}` becomes `{2}, {1}`, and `{3, 2, 1}` becomes `{3}, {2}, {1}` * If the second item is the same, then change nothing. For example, `{1, 1, 1}` stays the same, and `{2, 1, 1, 1}` would become `{2}, {1, 1, 1}`. * If the second item is larger, then nest every following item one level deeper. For example, `{1, 2}` would become `{1, {2}}` and `{1, 2, 3}` would become `{1, {2, {3}}}` # The Challenge You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO: ``` {1, 3, 2} --> {1, {3}, {2}} {1, 2, 3, 4, 5, 6} --> {1, {2, {3, {4, {5, {6}}}}}} {6, 5, 4, 3, 2, 1} --> {6}, {5}, {4}, {3}, {2}, {1} {7, 3, 3, 2, 6, 4} --> {7}, {3, 3}, {2, {6}, {4}} {7, 3, 1, -8, 4, 8, 2, -9, 2, 8} --> {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}} ``` Standard loopholes apply, and the shortest answer in bytes wins! [Answer] ## Haskell, 96 bytes ``` a#b|a<b=",{"|a>b="},{"|1<2="," f(a:b:c)=show a++a#b++f(b:c)++['}'|a<b] f[x]=show x++"}" ('{':).f ``` Usage example: `('{':).f $ [7,3,3,2,6,4]` -> `"{7},{3,3},{2,{6},{4}}"`. As Haskell doesn't have nested lists, I return the result as a string. The nesting algorithm is easy: a) print number, b) if the next number is greater (less, equal), print `,{` ( `},{`, `,`), c) make a recursive call with the rest of the list, d) print `}` if the number is less than the next one, e) enclose everything in `{` and `}`. [Answer] # Python 3, 98 bytes ``` p,*i=eval(input()) c=[p] a=b=[c] for x in i: if x>p:b=c if x!=p:c=[];b+=[c] c+=[x];p=x print(a) ``` Example: ``` $ python3 autonest.py <<< "[7, 3, 1, -8, 4, 8, 2, -9, 2, 8]" [[7], [3], [1], [-8, [4, [8], [2], [-9, [2, [8]]]]]] ``` [Answer] # Java 8 197 187 193 192 bytes --- Thanks to all the commenters who worked with me on this monstrosity. It was golfed down to 187 bytes until I found a costly bug. However due to the power of Black Magic the "runs down to" operator "-->" the byte count is at a healthy 192 bytes. --- ``` String a(int[]b){int l=b.length,d=1,i=0;String c="{";for(;i<l-1;i++)if(b[i]>b[i+1])c+=b[i]+"},{";else if(b[i]<b[i+1]){d++;c+=b[i]+",{";}else c+=b[i]+",";c+=b[l-1];while(d-->0)c+="}";return c;} ``` [Answer] # C, ~~145~~ 138 bytes Thanks to Giacomo for 7 bytes! ``` #define P printf( n;main(c,v,p,t)char**v;{p=-101;for(v++;*v;v++){t=atoi(*v);if(t<p)P"}{");if(t>p)P"{",n++);P"%d ",p=t);}for(;n--;)P"}");} ``` Input is taken through command line arguments and output is given though stdout. sample run: ``` $ ./autonest 7 3 1 -8 4 8 2 -9 2 8 {7 }{3 }{1 }{-8 {4 {8 }{2 }{-9 {2 {8 }}}}} ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~48~~ 43 bytes ``` YY_XKx"@K<?93]44@K-?91]@XKV]v93Gd0>sQY"h4L) ``` This uses square brackets in input and output. The output has commas without spaces as separators. Note that the output would not be interpreted as a nested list in MATL. It would in other languages, and it satisfies the output specification in the challenge. [**Try it online!**](http://matl.tryitonline.net/#code=WVlfWEt4IkBLPD85M100NEBLLT85MV1AWEtWXXY5M0dkMD5zUVkiaDRMKQ&input=WzcsIDMsIDEsIC04LCA0LCA4LCAyLCAtOSwgMiwgOF0) ### Explanation ``` YY_XKx % Push -inf. Copy to clipboard K (represents previous input entry). Delete " % Take numerical array implicitly. For each entry: @K< % Is current entry less than the previous one? ?93] % If so, push 93 (ASCII for ']') 44 % Push 44 (ASCII for comma) @K- % Is current entry different from the previous one? ?91] % If so, push 91 (ASCII for '[') @XKV % Push current entry, copy into clipboard K, convert to string ] % End for each v % Concat vertically all stack contents, converting to char 93 % Push 93 (ASCII for ']') (to be repeated the appropriate number of times) Gd0>sQ % Determine how many times the input increases, plus 1 Y" % Repeat 93 that many times h % Concat horizontally with previous string. Gives a row array, i.e. string 4L) % Remove first char, which is an unwanted comma. Display implicitly ``` [Answer] # CJam, ~~51~~ ~~49~~ ~~48~~ 46 bytes Exploits the fact that the number of last bracket is one more than number of adjacent pair that is increasing in array. And I don't know `ew` operator before that I had to reimplement. The input is space separated list delimited by square brackets. ``` '[q~_W=\2ew_{~\_@-g)["["S"]["]=}%@@{~>M']?}%'] ``` Explanation ``` '[q~_W=\2ew_{~\_@-g)["["S"]["]=}%@@{~>M']?}%'] '[ e# Opening bracket q~ e# Read the input _W=\2ew e# Save the last item and turn array into array of pair of next item and the item itself. _ e# We need two copies of that item {~\_@-g)["["S"]["]=}% e# Build the "body" that consist of the item and the suitable delimiter, space if equal, opening brace if the first item is the smallest, otherwise, closing bracket and opening bracket. @@ e# Put in the last item. (It was omitted in previous phase) {~<']""?}% e# Create the closing bracket as many as the number of increasing adjacent pair '] e# And one more bracket. ``` I will find out how to do this with actual nested array instead of relying on prettyprinting. Finally, ~~at par with~~ beaten MATL's answer. [Answer] # Retina, ~~71~~ 70 bytes Lists are space separated, with curly braces: `{1 2 3}`. Negative numbers are not supported, so if that's a problem, I'll just delete my answer. Retina + negative numbers = not worth it. ``` \d+ $* +`\b(1+) (1+\1\b.*) $1 {$2} +`\b(1(1+)1*) (\2)\b $1} {$2 1+ $.0 ``` [**Try it online**](http://retina.tryitonline.net/#code=XGQrCiQqCitgXGIoMSspICgxK1wxXGIuKikKJDEgeyQyfQorYFxiKDEoMSspMSopIChcMilcYgokMX0geyQyCjErCiQuMA&input=ezEgMyAyfQp7MSAyIDMgNCA1IDZ9Cns2IDUgNCAzIDIgMX0KezcgMyAzIDIgNiA0fQ) [Answer] ## JavaScript (ES6), 73 bytes ``` a=>a.map(r=>l-r?(n=l<r?m:n).push(m=[l=r]):m.push(l),l=a[0],o=n=[m=[]])&&o ``` Explanation: The case of consecutive equal items is easy; the item is just added to the innermost array (here represented by the `m` variable; `n` is the array that contains `m` as its last element, while `o` is the output). For the case of different items, the item always goes in a new innermost array, the only difference being whether that array is a sibling or a child of the previous innermost array. For extra golfiness I set up the arrays so that the initial item counts as a consecutive equal item. ]
[Question] [ So in 1st grade math, you learn the names of polygons. Three sides is a triangle, 4 is a square, and 5 is a pentagon. However, in 1st grade honors, you go a bit further. ## Your challenge There is a naming system for polygons above a few sides, so arbitrarily large polygons have a name. Your task is to write a program or a function that **accepts the name of a polygon as input** and **outputs the number of sides** it has. The names of polygons are defined as in the left column of [this wikipedia article](https://en.wikipedia.org/wiki/List_of_polygons#List_of_n-gons_by_Greek_numerical_prefixes) with a few exceptions. Three sided polygons will be called a triangle instead of a trigon and 4 sided polygons will be a square instead of a tetragon (assume that all the polygons are regular). Otherwise, the names in the article will be used. ## Rules * Input will be a string value. * The program should print the result to STDOUT (or it should return an integer). * Only polygons between 3 and 99 will be inputted. * Your program must satisfy all test cases. * No standard loopholes. * The program doesn't need to do anything for invalid/out of range inputs. * Scoring is in bytes. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins. ## Test cases ``` 3 triangle 4 square 5 pentagon 10 decagon 11 hendecagon 12 dodecagon 13 triskaidecagon 20 icosagon 21 icosikaihenagon 22 icosikaidigon 34 triacontakaitetragon 35 triacontakaipentagon 36 triacontakaihexagon 47 tetracontakaiheptagon 48 tetracontakaioctagon 49 tetracontakaienneagon 64 hexacontakaitetragon 80 octacontagon 81 octacontakaihenagon 99 enneacontakaienneagon ``` ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` var QUESTION_ID=75229,OVERRIDE_USER=41505;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> ``` 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 ``` [Answer] # Ruby, ~~405~~ 207 bytes 207 bytes ``` ->a{i,n=0,"#{a}";[/ontag|sa/,/(he|mo)n/,/di|do|ic/,/tri/,/tet|q/,/pe/,/hex/,/hep/,/oc/,/enn/,/^d/,/1d/,/2d/].each{|r|n.gsub!(r,i.to_s);i+=1;};n=n.gsub(/ide/,'!').gsub(/[a-z]/,'');n='1'+n[0] if /!/=~n;n.to_i} ``` Ungolfed 207 ``` sides = ->a{ i,n=0,"#{a}"; # Match patterns for zero, one, two, etc. # Each regex corresponds to a digit. # Special patterns for 10, 11 and 12. [/ontag|sa/,/(he|mo)n/,/di|do|ic/,/tri/, /tet|q/,/pe/,/hex/,/hep/,/oc/,/enn/, /^d/,/1d/,/2d/].each {|r| n.gsub!(r, i.to_s);i+=1;}; n=n.gsub(/ide/,'!'). # Change part of the teens to exclamation gsub(/[a-z]/,''); # Remove remaining unmatched letters n='1'+n[0] if /!/=~n; # Fixup the teens n.to_i } ``` 405 bytes: ``` ->a{d=%w(on hen d tr te p hex hep oc e);case a when/de/ then %w(de hen do tr te p hex hep o e ).index(a[/^(he|t|d)?./]||:de)+10;when/^([mdtspoe]|he[xp]).{,7}$/ then %w(z m d t s p hex hep o e).index($1);when/^i.*[ks]a.([dep]|on|oc|tr|te|hen|hex|hep)/ then d.index($1)+20;when/^((he|t)?[^ht]).*nta(kai)?([gdpoe]|tr|te|hen|hex|hep)/ then (3+%w(tr te p hex hep o e).index($1))*10+(d.index($4)||0)else 0;end} ``` Ungolfed 405 ``` def sides(a) d=%w(on hen d tr te p hex hep oc e); case a when /de/ then %w(de hen do tr te p hex hep o e ).index(a[/^(he|t|d)?./]||:de)+10; when /^([mdtspoe]|he[xp]).{,7}$/ then %w(z m d t s p hex hep o e).index($1);when/^i.*[ks]a.([dep]|on|oc|tr|te|hen|hex|hep)/ then d.index($1)+20; when /^((he|t)?[^ht]).*nta(kai)?([gdpoe]|tr|te|hen|hex|hep)/ then (3+%w(tr te p hex hep o e).index($1))*10+(d.index($4)||0) else 0; end end ``` Maybe not the best golf submission, but it might win an obfuscated code contest! Test ``` polygons = %w( gone monogon digon triangle square pentagon hexagon heptagon octagon enneagon decagon hendecagon dodecagon triskaidecagon tetrakaidecagon pentakaidecagon hexakaidecagon heptakaidecagon octakaidecagon enneakaidecagon icosagon icosikaihenagon icosikaidigon icosikaitrigon icosikaitetragon icosikaipentagon icosikaihexagon icosikaiheptagon icosikaioctagon icosikaienneagon triacontagon triacontakaihenagon triacontakaidigon triacontakaitrigon triacontakaitetragon triacontakaipentagon triacontakaihexagon triacontakaiheptagon triacontakaioctagon triacontakaienneagon tetracontagon tetracontakaihenagon tetracontakaidigon tetracontakaitrigon tetracontakaitetragon tetracontakaipentagon tetracontakaihexagon tetracontakaiheptagon tetracontakaioctagon tetracontakaienneagon pentacontagon pentacontakaihenagon pentacontakaidigon pentacontakaitrigon pentacontakaitetragon pentacontakaipentagon pentacontakaihexagon pentacontakaiheptagon pentacontakaioctagon pentacontakaienneagon hexacontagon hexacontakaihenagon hexacontakaidigon hexacontakaitrigon hexacontakaitetragon hexacontakaipentagon hexacontakaihexagon hexacontakaiheptagon hexacontakaioctagon hexacontakaienneagon heptacontagon heptacontakaihenagon heptacontakaidigon heptacontakaitrigon heptacontakaitetragon heptacontakaipentagon heptacontakaihexagon heptacontakaiheptagon heptacontakaioctagon heptacontakaienneagon octacontagon octacontakaihenagon octacontakaidigon octacontakaitrigon octacontakaitetragon octacontakaipentagon octacontakaihexagon octacontakaiheptagon octacontakaioctagon octacontakaienneagon enneacontagon enneacontakaihenagon enneacontakaidigon enneacontakaitrigon enneacontakaitetragon enneacontakaipentagon enneacontakaihexagon enneacontakaiheptagon enneacontakaioctagon enneacontakaienneagon ) sides = ->a{i,n=0,"#{a}";[/ontag|sa/,/(he|mo)n/,/di|do|ic/,/tri/,/tet|q/,/pe/,/hex/,/hep/,/oc/,/enn/,/^d/,/1d/,/2d/].each{|r|n.gsub!(r,i.to_s);i+=1;};n=n.gsub(/ide/,'!').gsub(/[a-z]/,'');n='1'+n[0] if /!/=~n;n.to_i} polygons.each {|p| puts "#{p} -> #{sides.call(p)}"; } ``` [Answer] ## Python2 - ~~357~~ 368 byte Since the only real exceptions to the system are "square", "hendecagon" and "dodecagon", all other numbers follow the same pattern of having "kai" for second digits and "conta"/"deca" for their first digit. ``` import sys;s=input();e=eval;x='y(str(10*i(b)+i(a)))';y=sys.exit;a=b='0';l=['0','hen','di','tri','tet','pen','hex','hep','oct','enn'];i=l.index if'kai'in s: a=[f for f in l if f in s[-8:]][0] if'ca'in s: if l[1]in s:y("11") if'do'in s:y("12") b=l[1];e(x) elif'co'in s: l[2]='ico';b=[f for f in l if f in s[:5]][0];e(x) if'sq'in s:y("4") y(str(i(s[:3]))) ``` Explanation: ``` import sys;s=input();e=eval;x='y(str(10*i(b)+i(a)))';y=sys.exit;a=b='0' l=['0','hen','di','tri','tet','pen','hex','hep','oct','enn'] # List of all defining numerals, index equals the number. i=l.index if'kai'in s: # check if the input is a two-digit number # with a second digit greater than 0 a=[f for f in l if f in s[-8:]][0] # get the second digit, and store it. if'ca'in s: # Special case for 10-19 if l[1]in s:y("11") # Exceptions 11 & 12 if'do'in s:y("12") # b=l[1];e(x) elif'co'in s: # All other two digit numbers l[2]='ico' b=[f for f in l if f in s[:5]][0] # Get the first digit, and store it e(x) if'sq'in s:y("4") # Exception "square" y(str(i(s[:3]))) # All other single digit numbers ``` This works for all inputs between 3-99, and prints the result to the console. Might be more golfable, but this is as far as I can go right now. \*\*Edit: I just realized, this printed to STDERR, not STDOUT. Fixed code is a little longer: ``` import sys;s=input();e=eval;x="10*i(b)+i(a)";y=sys.exit;a=b='0';l=['0','hen','di','tri','tet','pen','hex','hep','oct','enn'];i=l.index if'kai'in s:a=[f for f in l if f in s[-8:]][0] if'ca'in s: if l[1]in s:print"11" if'do'in s:print"12" b=l[1];print e(x);y() elif'co'in s:l[2]='ic';b=[f for f in l if f in s[:5]][0];print e(x);y() if'q'in s:print"4" print(i(s[:3])) ``` [Answer] # Cinnamon Gum, 430 bytes ``` 0000000: 6c4c ce85 0d04 4108 05d0 6e36 9e5b 379a lL....A...n6.[7. 0000010: 5977 f7f2 6f02 8410 fdbc 11fe 75f4 f9d2 Yw..o.......u... 0000020: 4eb5 e5c1 b9df f951 5b3e 6cf5 72e5 edba N......Q[>l.r... 0000030: 5801 74f5 8729 3469 238c 602d 29c5 502f X.t..)4i#.`-).P/ 0000040: 4b8d 3181 aa2e 3139 b6b9 bac8 e440 b5ca K.1...19.....@.. 0000050: e082 5977 8e79 2fe2 c155 5f47 ae89 f76b ..Yw.y/..U_G...k 0000060: a21e 5ab8 8f26 eaa5 85fb 694a a02f d713 ..Z..&....iJ./.. 0000070: b36b 63ee cdb1 294c e408 553d 822b 701d .kc...)L..U=.+p. 0000080: 249e 0836 47f3 c5b0 3a5a a07e ff88 4245 $..6G...:Z.~..BE 0000090: 1b5f 8bc4 d692 2916 c2fa 6809 98fd 79b9 ._....)...h...y. 00000a0: f2ef 9e0d 32ff 9baa 8b43 3982 288a a121 ....2....C9.(..! 00000b0: 35d4 c3fc 03b3 3f4b cbd2 1d3a 43ad d77f 5.....?K...:C... 00000c0: 1ef2 9fe1 bc44 1ce7 b862 39e1 8ee7 a43a .....D...b9....: 00000d0: a653 ceb8 4eab 633b e38c efec d7f7 0060 .S..N.c;.......` 00000e0: dc04 0be3 a143 8c57 1563 1c67 2123 3c48 .....C.W.c.g!#<H 00000f0: 19c9 6066 94bb 9cd1 0c86 c6b8 4b1a fbf5 ..`f........K... 0000100: f546 9a37 c1d2 7ce8 48f3 a54a 9ac7 59d2 .F.7..|.H..J..Y. 0000110: 0c0f 9266 7a40 9ae5 2e69 b607 a439 ee92 [[email protected]](/cdn-cgi/l/email-protection).. 0000120: e67e fe6a 81d6 cd59 ce7a c87f cc7a 8928 .~.j...Y.z...z.( 0000130: eb50 8dac a0db 5849 17b1 8a6c 6135 5dc0 .P....XI...la5]. 0000140: 1ab2 7db5 5fff 4100 fb26 58d8 0f1d 62bf ..}._.A..&X...b. 0000150: 5419 fb28 1bd9 a1c1 ca4e 0633 bbd4 edec T..(.....N.3.... 0000160: 6630 b447 ddd2 decf bf56 a073 7396 739e f0.G.....V.ss.s. 0000170: bf0c 735e 22ca 3954 2327 e836 4ed2 459c ..s^".9T#'.6N.E. 0000180: 225b 384d 1770 866c dfec d785 02e0 de04 "[8M.p.l........ 0000190: 0bf7 a143 dc97 2ae3 1e65 2337 3458 b9c9 ...C..*..e#74X.. 00001a0: 60e6 96ba 9ddb 0c86 eea8 5bba fb1f `.........[... ``` This is a hexdump of the source code; you can reverse it using `xxd -r`. [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNmM0YyBjZTg1IDBkMDQgNDEwOCAwNWQwIDZlMzYgOWU1YiAzNzlhICBsTC4uLi5BLi4ubjYuWzcuCjAwMDAwMTA6IDU5NzcgZjdmMiA2ZjAyIDg0MTAgZmRiYyAxMWZlIDc1ZjQgZjlkMiAgWXcuLm8uLi4uLi4udS4uLgowMDAwMDIwOiA0ZWI1IGU1YzEgYjlkZiBmOTUxIDViM2UgNmNmNSA3MmU1IGVkYmEgIE4uLi4uLi5RWz5sLnIuLi4KMDAwMDAzMDogNTgwMSA3NGY1IDg3MjkgMzQ2OSAyMzhjIDYwMmQgMjljNSA1MDJmICBYLnQuLik0aSMuYC0pLlAvCjAwMDAwNDA6IDRiOGQgMzE4MSBhYTJlIDMxMzkgYjZiOSBiYWM4IGU0NDAgYjVjYSAgSy4xLi4uMTkuLi4uLkAuLgowMDAwMDUwOiBlMDgyIDU5NzcgOGU3OSAyZmUyIGMxNTUgNWY0NyBhZTg5IGY3NmIgIC4uWXcueS8uLlVfRy4uLmsKMDAwMDA2MDogYTIxZSA1YWI4IDhmMjYgZWFhNSA4NWZiIDY5NGEgYTAyZiBkNzEzICAuLlouLiYuLi4uaUouLy4uCjAwMDAwNzA6IGIzNmIgNjNlZSBjZGIxIDI5NGMgZTQwOCA1NTNkIDgyMmIgNzAxZCAgLmtjLi4uKUwuLlU9LitwLgowMDAwMDgwOiAyNDllIDA4MzYgNDdmMyBjNWIwIDNhNWEgYTA3ZSBmZjg4IDQyNDUgICQuLjZHLi4uOloufi4uQkUKMDAwMDA5MDogMWI1ZiA4YmM0IGQ2OTIgMjkxNiBjMmZhIDY4MDkgOThmZCA3OWI5ICAuXy4uLi4pLi4uaC4uLnkuCjAwMDAwYTA6IGYyZWYgOWUwZCAzMmZmIDliYWEgOGI0MyAzOTgyIDI4OGEgYTEyMSAgLi4uLjIuLi4uQzkuKC4uIQowMDAwMGIwOiAzNWQ0IGMzZmMgMDNiMyAzZjRiIGNiZDIgMWQzYSA0M2FkIGQ3N2YgIDUuLi4uLj9LLi4uOkMuLi4KMDAwMDBjMDogMWVmMiA5ZmUxIGJjNDQgMWNlNyBiODYyIDM5ZTEgOGVlNyBhNDNhICAuLi4uLkQuLi5iOS4uLi46CjAwMDAwZDA6IGE2NTMgY2ViOCA0ZWFiIDYzM2IgZTM4YyBlZmVjIGQ3ZjcgMDA2MCAgLlMuLk4uYzsuLi4uLi4uYAowMDAwMGUwOiBkYzA0IDBiZTMgYTE0MyA4YzU3IDE1NjMgMWM2NyAyMTIzIDNjNDggIC4uLi4uQy5XLmMuZyEjPEgKMDAwMDBmMDogMTljOSA2MDY2IDk0YmIgOWNkMSAwYzg2IGM2YjggNGIxYSBmYmY1ICAuLmBmLi4uLi4uLi5LLi4uCjAwMDAxMDA6IGY1NDYgOWEzNyBjMWQyIDdjZTggNDhmMyBhNTRhIDlhYzcgNTlkMiAgLkYuNy4ufC5ILi5KLi5ZLgowMDAwMTEwOiAwYzBmIDkyNjYgN2E0MCA5YWU1IDJlNjkgYjYwNyBhNDM5IGVlOTIgIC4uLmZ6QC4uLmkuLi45Li4KMDAwMDEyMDogZTY3ZSBmZTZhIDgxZDYgY2Q1OSBjZTdhIGM4N2YgY2M3YSA4OTI4ICAufi5qLi4uWS56Li4uei4oCjAwMDAxMzA6IGViNTAgOGRhYyBhMGRiIDU4NDkgMTdiMSA4YTZjIDYxMzUgNWRjMCAgLlAuLi4uWEkuLi5sYTVdLgowMDAwMTQwOiAxYWIyIDdkYjUgNWZmZiA0MTAwIGZiMjYgNThkOCAwZjFkIDYyYmYgIC4ufS5fLkEuLiZYLi4uYi4KMDAwMDE1MDogNTQxOSBmYjI4IDFiZDkgYTFjMSBjYTRlIDA2MzMgYmJkNCBlZGVjICBULi4oLi4uLi5OLjMuLi4uCjAwMDAxNjA6IDY2MzAgYjQ0NyBkZGQyIGRlY2YgYmY1NiBhMDczIDczOTYgNzM5ZSAgZjAuRy4uLi4uVi5zcy5zLgowMDAwMTcwOiBiZjBjIDczNWUgMjJjYSAzOTU0IDIzMjcgZTgzNiA0ZWQyIDQ1OWMgIC4uc14iLjlUIycuNk4uRS4KMDAwMDE4MDogMjI1YiAzODRkIDE3NzAgODY2YyBkZmVjIGQ3ODUgMDJlMCBkZTA0ICAiWzhNLnAubC4uLi4uLi4uCjAwMDAxOTA6IDBiZjcgYTE0MyBkYzk3IDJhZTMgMWU2NSAyMzM3IDM0NTggYjljOSAgLi4uQy4uKi4uZSM3NFguLgowMDAwMWEwOiA2MGU2IDk2YmEgOWRkYiAwYzg2IGVlYTggNWJiYSBmYjFmICAgICAgIGAuLi4uLi4uLi5bLi4u&input=ZW5uZWFjb250YWthaWVubmVhZ29u) ]
[Question] [ Given an input of a [Pig](http://esolangs.org/wiki/Pig), [SickPig](http://esolangs.org/wiki/SickPig), [DeadPig](http://esolangs.org/wiki/DeadPig), [QuinePig](http://esolangs.org/wiki/QuinePig), or [DeafPig](http://esolangs.org/wiki/DeafPig) program, choose one of those "languages" randomly and interpret the input as that "language." First, randomly choose between one of the five members of the "Pig series": * ## Pig If the choice was Pig, mimic the [reference interpreter](http://esolangs.org/wiki/Pig) by doing the following: + Find the first occurrence of the word `PIG` in the input (case-sensitive). + If the word `PIG` does not appear in the input, output the message `File must contain the string 'PIG'.` and exit. + Otherwise, split the input string on the first occurrence of `PIG`. Output the text after the first occurrence of `PIG` to a file with a filename of the text before `PIG`. `PIG` may be contained in the text to be output (so, an input of `fooPIGbarPIGbaz` should output `barPIGbaz` to a file called `foo`).Note that the reference interpreter takes input via a command line argument that specifies a filename to read from. However, your submission may take input in any of the standard methods accepted on PPCG. * ## SickPig If the choice was SickPig, follow the same instructions as Pig. However, instead of writing the text after `PIG` to the file, choose randomly from the following list ``` GRUNT MOAN OINK BURP GROAN WHINE ``` and output that to the file instead. This random choice must be independent of the previous choice (so, an output of `GRUNT` should have a 1/5 \* 1/6 = 1/30 chance overall). * ## DeadPig DeadPig is like SickPig, but it always outputs the following string instead of randomly choosing a string: ``` Your pig has unfortunately died. Please try again. ``` * ## QuinePig QuinePig is like Pig, but instead of writing the text after `PIG` to the file, it instead writes the entire input to the file (so, an input of `fooPIGbarPIGbaz` should output `fooPIGbarPIGbaz` to a file called `foo`). * ## DeafPig If the choice was DeafPig, do nothing. (The pig is deaf... what do you expect?) Miscellaneous rules: * "Random" means each choice should be roughly equally likely (so, choosing Pig 90% of the time and the other variants only 2.5% of the time is invalid). * You may assume that the requested filenames will always be valid for your file system (but they may contain spaces, etc.). * For all the variants of Pig, your code may optionally output a single trailing newline to the file as well. * Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. [Answer] # Bash, ~~251~~ 246 bytes ``` r=$RANDOM ((r%5<4))||exit [[ $1 =~ PIG ]]||(echo "File must contain the string 'PIG'.";exit) s=(GRUNT MOAN OINK BURP GROAN WHINE) m=("${1#*PIG}" ${s[r%6]} "Your pig has unfortunately died. Please try again." "$1") echo -n "${m[r%5]}">"${1%%PIG*}" ``` This would be a lot shorter if deaf pigs could at least read... [Answer] # Python 2, ~~296~~ ~~286~~ 278 bytes ``` def g(p): import random;f=random.randint;r=f(0,4);i=p.find("PIG") if r: if i+1:open(p[:i],"w").write([0,p[i+3:],["GRUNT","MOAN","OINK","BURP","GROAN","WHINE"][f(0,5)],"Your pig has unfortunately died. Please try again.",p][r]) else:print"File must contain the string 'PIG'." ``` *The last two lines start with a tab, instead of the rendered 4 spaces.* Takes input program as function argument. [Answer] ## Batch, ~~409~~ ~~406~~ 405 bytes ``` @echo off set/ar=%random%%%5 if 0==%r% exit/b set p=x%1 set q=%p:*PIG=% if %q%==%p% echo File must contain the string 'PIG'.&exit/b set p=%1 call set p=%%p:PIG%q%=%% goto %r% :1 echo %q%>%p% exit/b :2 for %%a in (GRUNT.0 MOAN.1 OINK.2 BURP.3 GROAN.4 WHINE.5)do if %%~xa==.%time:~6,1% echo %%~na exit/b :3 echo Your pig has unfortunately died. Please try again.>%p% exit/b :4 echo %1>%p% ``` Sadly `%p:*PIG=%` fails if p is blank, thus the `x%1` hack. `call set` is a nice way to avoid enabledelayedexpansion that I found on Stack Overflow; while the `%%~xa==.` was a flash of inspiration on my part. Edit: Saved 3 bytes thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ. [Answer] # Pyth - 157 bytes Will be doing string compression. ``` ?}J"PIG"z?=GO[jJtKczJOc"GRUNT MOAN OINK BURP GROAN WHINE"d"Your pig has unfortunately died. Please try again."z0).wGhK.q"File must contain the string 'PIG'." ``` Doesn't work online cuz of file I/O, but try it outputting `[content, filename]` to stdio [here](http://pyth.herokuapp.com/?code=%3F%7DJ%22PIG%22z%3F%3DGO%5BjJtKczJOc%22GRUNT+MOAN+OINK+BURP+GROAN+WHINE%22d%22Your+pig+has+unfortunately+died.+Please+try+again.%22z0%29%5BGhK%29.q%22File+must+contain+the+string+%27PIG%27.%22&input=fooPIGbarPIGbaz&debug=0). ]
[Question] [ *Heavily inspired by [Programming a Pristine World](https://codegolf.stackexchange.com/q/63433/42545). Also closely related to [this challenge](https://codegolf.stackexchange.com/q/41648/31625).* --- Let's define a *pristine prime* as a number which is itself prime, but will no longer be prime if you remove any contiguous substring of N base 10 digits, where `0 < N < digits in number`. For example, 409 is a pristine prime because 409 itself is prime, but all numbers resulting from removing a substring of 1 digit are not prime: ``` 40 49 09 = 9 ``` and all numbers resulting from removing substrings of length 2 are not prime: ``` 4 9 ``` On the other hand, the prime number 439 is not pristine. Removing the different substrings results in: ``` 43 49 39 4 9 ``` While 49, 39, 4, and 9 are all non-prime, 43 *is* prime; thus, 439 is not pristine. 2, 3, 5, and 7 are trivially pristine, since they cannot have any substrings removed. ## Challenge Your challenge is to create a program or function that takes in a positive integer N and outputs the Nth pristine prime. The code should finish in under 1 minute on any modern PC for any input up to 50. **The shortest code in bytes wins.** As a reference, here are the first 20 pristine primes: ``` N Pristine prime 1 2 2 3 3 5 4 7 5 11 6 19 7 41 8 61 9 89 10 409 11 449 12 499 13 821 14 881 15 991 16 6299 17 6469 18 6869 19 6899 20 6949 ``` [Here](http://pastebin.com/dfVwn8Yr) is a full list of pristine primes up to 1e7, or N = 376. Finally, here are two related OEIS entries: * [A033274](http://oeis.org/A033274): very similar, but generated by keeping substrings instead of removing them. * [A071062](http://oeis.org/A071062): oddly similar, but generated in a much different manner. [Answer] # Pyth, 29 bytes ``` e.f>}ZPZsmq1lPs.D`Z}Fd.CU`Z2Q ``` Golfing, explanation, etc. to follow. [Answer] ## CJam, 51 bytes ``` 1ri{{)_mp1$s_,)2m*{:>},\f{\~2$<@@>+0e|imp}1b!&!}g}* ``` Just a first pass, this can probably be improved a lot. [Test it here.](http://cjam.aditsu.net/#code=1ri%7B%7B)_mp1%24s_%2C)2m*%7B%3A%3E%7D%2C%5Cf%7B%5C~2%24%3C%40%40%3E%2B0e%7Cimp%7D1b!%26!%7Dg%7D*&input=10) [Answer] # Japt, 61 bytes ``` $while(V<U)T$°,W=Ts ,Tj «Wl o d@1o1-X+Wl)dZ{WjYZ n j} } ©V°;T ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=JHdoaWxlKFY8VSlUJLAsVz1UcyAsVGogq1dsIG8gZEAxbzEtWCtXbClkWntXallaIG4gan0gfSCpVrA7VA==&input=MjA=) It's a shame I haven't implemented loops in Japt yet, otherwise this would be a good bit shorter. Still golfing... ]
[Question] [ You should write a program or function which takes a non-negative integer `k` and a sorted integer list `L`as input and outputs or returns a smoothed list `M`. `M` is created from the ascending list `L` by inserting at most `k` integer elements while keeping the list sorted. The inserted integers should be chosen in a way that the maximum forward difference of `M` will be as small as possible. We will call this smallest value "smoothness". The forward differences of the list `-1 3 8 11 15` are `4 5 3 4` and the maximum forward difference is `5`. With `2` insertions the smoothness of `2 10 15` is `4` and a possible output is `2 6 10 11 15` with forward differences `4 4 1 4`. ## Input * A non-negative integer `k`. * An ascending integer list `L` with at least 2 elements. ## Output * The ascending integer list `M`. * If multiple correct answers exists output exactly one of them (any one is sufficient). * **Your solution has to solve any example test case under a minute** on my computer (I will only test close cases. I have a below-average PC.). ## Examples Input (`k`, `L`) => A possible output and the maximum forward difference (which is not part of the output) in parentheses ``` 0, 10 20 => 10 20 (10) 2, 1 10 => 1 4 7 10 (3) 2, 2 10 15 => 2 6 10 11 15 (4) 3, 2 10 15 => 2 5 8 10 12 15 (3) 5, 1 21 46 => 1 8 15 21 27 33 39 46 (7) 5, 10 20 25 33 => 10 14 18 20 24 25 29 33 (4) 3, 4 4 6 9 11 11 15 16 25 28 36 37 51 61 => 4 4 6 9 11 11 15 16 22 25 28 36 37 45 51 59 61 (8) 15, 156 888 2015 => 156 269 382 495 608 721 834 888 1001 1114 1227 1340 1453 1566 1679 1792 1905 2015 (113) 8, -399 -35 -13 56 157 => -399 -347 -295 -243 -191 -139 -87 -35 -13 39 56 108 157 (52) 5, 3 3 3 => 3 3 3 3 (0) ``` This is code-golf so the shortest entry wins. [Answer] # Python 2, 104 ``` def f(L,k,d=1): M=[];p=L[0] for x in L:M+=range(p+d,x,d);p=x return M[k:]and f(L,k,d+1)or sorted(L+M) ``` Tries different maximum increments `d`, starting from 1 and counting up. Fills in gaps of each pair `(p,x)` of successive elements by taking every `d`'th number in the gap. If `M` is longer than the quota allows, recurses to try a higher `d`. Otherwise, returns a list of the added and original elements, sorted. This does all the test cases without delay on my machine. [Answer] # Pyth, ~~28~~ 27 bytes ``` S+Qu?smt%hHrFdC,QtQ>GvzGhvz ``` Input given like: ``` 3 [2, 10, 15] ``` [Demonstration.](https://pyth.herokuapp.com/?code=S%2BQu%3Fsmt%25hHrFdC%2CQtQ%3EGvzGhvz&input=3%0A%5B2%2C+10%2C+15%5D&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=FZ.z%3DQmvd-cechcZ%22%3D%3E%22%5C%2Cdk%3DzhcZ%5C%2C%0AS%2BQu%3Fsmt%25hHrFdC%2CQtQ%3EGvzGhvz&input=%22%22%0A%22%22%0A0%2C+10+20+%3D%3E+10+20+(10)%0A2%2C+1+10+%3D%3E+1+4+7+10+(3)%0A2%2C+2+10+15+%3D%3E+2+6+10+11+15+(4)%0A3%2C+2+10+15+%3D%3E+2+5+8+10+12+15+(3)%0A5%2C+1+21+46+%3D%3E+1+8+15+21+27+33+39+46+(7)%0A5%2C+10+20+25+33+%3D%3E+10+14+18+20+24+25+29+33+(4)%0A3%2C+4+4+6+9+11+11+15+16+25+28+36+37+51+61+%3D%3E+4+4+6+9+11+11+15+16+22+25+28+36+37+45+51+59+61+(8)%0A15%2C+156+888+2015+%3D%3E+156+269+382+495+608+721+834+888+1001+1114+1227+1340+1453+1566+1679+1792+1905+2015+(113)%0A8%2C+-399+-35+-13+56+157+%3D%3E+-399+-347+-295+-243+-191+-139+-87+-35+-13+39+56+108+157+(52)%0A5%2C+3+3+3+%3D%3E+3+3+3+3+(0)&debug=0) Note: At the time the question was asked, there was a small bug in Pyth related to using `rFd` inside `u`, which I just fixed. The bug rendered it impossible to ever use `F` inside `u`, which was definitely not intended. ``` S+Qu?smt%hHrFdC,QtQ>GvzGhvz Implicit: z is the number of insertions, in string form. Q is the input list. C,QtQ Pairs of elements, e.g. [(2, 10), (10, 15)] rFd d = (a, b) -> range(a, b) %hH Take every H+1th element of that range t And throw out the first one. m Perform this process for each element pair s And combine the results into one list. The above is a minimal set of additional elements To reduce the maximal difference to H+1. u hvz Repeat until the result stops changing, where the prior result is G, H starts at 0 and increases by 1 each repetition, and G is initialized to eval(z)+1. ? >GvzG If not G[eval(z):], return G. In other words, if the prior result was short enough, stop. Also, this is always false on the initial call. smt%hHrFdC,QtQ Otherwise, recalculate with H incremented. S+Q Take the result, add the original list, and sort. ``` --- Here's a version which would have worked with the interpreter at the time the question was asked. It's 28 bytes, and works exactly the same way: ``` S+Qu?smt%hHr.udC,QtQ>GvzGhvz ``` [Demonstration.](https://pyth.herokuapp.com/?code=S%2BQu%3Fsmt%25hHr.udC%2CQtQ%3EGvzGhvz&input=3%0A%5B2%2C%2010%2C%2015%5D) [Git commit of the appropriate version, f6b40e62](https://github.com/isaacg1/pyth/commit/f6b40e62fd77048f8b3e5b6a8c0e970086fa9e91) ]
[Question] [ Everyone always wants to implement Conway's Game of Life. That's boring! Let's do cops and robbers instead! You'll have two teams: the cops and the robbers. Each team has 5 members with 50 health each. The program will loop continuously. Each iteration, the following will occur: * For each team, print the first letter (`C` for the cops, `R` for the robbers), a space, a space-separated list of the members' HP, and a newline. This is the teams' status. After both are done, print another newline. For instance, here's what it might look like the first round: ``` C 50 50 50 50 50 R 50 50 50 50 50 ``` * Pick a random number from 1 to 10 (including both 1 and 10). We'll call the number `N`. If `N` is even, the robbers lose this round; if odd, the cops lose. * Pick a random member of the losing team whose HP is greater than 0 and deduct `N` HP. *The members' HP should never appear go below 0 on the status.* * Restart the loop. The game ends when all the members of one team lose all their HP. Then, the following will be printed if the cops win: ``` C+ R- ``` and if the robbers win: ``` R+ C- ``` This is code golf, so the shortest number of characters wins. Here's a sample implementation in Python 2: ``` import random cops = [50]*5 robbers = [50]*5 while any(cops) and any(robbers): # print the status print 'C', ' '.join(map(str, cops)) print 'R', ' '.join(map(str, robbers)) print # pick N N = random.randint(1, 10) # pick the losing team (robbers if N is even, else cops) losers = robbers if N % 2 == 0 else cops # pick a member whose HP is greater than 0 losing_member = random.choice([i for i in range(len(losers)) if losers[i]]) losers[losing_member] -= N # make sure the HP doesn't visibly drop below 0 if losers[losing_member] < 0: losers[losing_member] = 0 if any(cops): # robbers lost print 'C+' print 'R-' elif any(robbers): # cops lost print 'C-' print 'R+' ``` [Answer] # CJam, 86 bytes I'm a bit late to the party, but I bring the gift of CJam! ... Hey wait, where are you going? ``` 50aA*{"CR"1$+2/zSf*Nf+oNoAmr{_AmrE&+:P2$=:H!}gPH@)-Ue>t_2/z::+0#:L)!}g;'CL'+'-?N'R2$6^ ``` [Try it online.](http://cjam.aditsu.net/#code=50aA*%7B%22CR%221%24%2B2%2FzSf*Nf%2BoNoAmr%7B_AmrE%26%2B%3AP2%24%3D%3AH!%7DgPH%40)-Ue%3Et_2%2Fz%3A%3A%2B0%23%3AL)!%7Dg%3B'CL'%2B'-%3FN'R2%246%5E) ### Explanation As the questions asks to emulate a straightforward process, this is a relatively straightforward answer. Perhaps one interesting choice I made was to hold the health of both teams interleaved in the same list. This costs 3 bytes to convert to two separate lists, which is needed for both health displaying and checking if a team has lost. But (I think) this is made up for by the 2 bytes saved in initialization and much simpler damage-dealing logic. ``` 50aA* "Initialize the health list to 10 copies of 50. Even indices hold the health of cops and odd indices hold the health of robbers."; { "Do:"; "CR"1$+2/z "Split the health list into the two teams for output, adding the corresponding team letter to the start of each. [a b c d e f g h i j] -> [['C a c e g i] ['R b d f h j]]"; Sf*Nf+ "Insert a space between each element in each team health list and append a newline to the end of each team health list."; oNo "Print the health status for each team and an extra newline."; Amr "Generate the damage amount minus one. If the damage amount is even (robbers lose), then this is odd and aligns with robbers being at odd indices in the health list, and vice versa."; { "Do:"; _AmrE&+:P "Add a random even number from [0, 10) to the damage amount minus one. This value modulo the size of the health list (10) selects a person on the losing team to be damaged."; 2$=:H! }g "... While the selected person's health is zero."; PH@)-Ue>t "Set the damaged person's new health to the maximum of their current health minus the damage amount and zero."; _2/z::+0#:L "Split the health list into the two teams, sum each team's health, and search for a team's health equal to zero."; )! }g "... While no team's health was found equal to zero."; ; "Discard the health list."; 'C "Produce a 'C'."; L'+'-? "Produce a '+' if team 1 (robbers) lost, or '-' otherwise."; N "Produce a newline."; 'R "Produce an 'R'."; 2$6^ "Produce the opposite of the sign produced before."; "Implicitly print these final results."; ``` [Answer] ## R - 201 ``` S=sum Z=sample C=R=rep(50,5) while(S(R)*S(C)){cat("C",C,"\nR",R,"\n\n") N=Z(10,1) F=function(x,i=Z(rep(which(x>0),2),1)){x[i]=max(0,x[i]-N);x} if(N%%2)R=F(R)else C=F(C)} cat(c("R+\nC-\n","C+\nR-\n")[1+!S(R)]) ``` [Answer] # APL (Dyalog) (101) ``` ∇K S←2 5⍴50 →6/⍨~∧/J←∨/S>0 ⎕←3↑'CR',0⌈S S[L;M[?⍴M←(0<S[L←1+~2⊤N;])/⍳5]]-←N←?10 →2 ⎕←'CR',⍪'+-'⌽⍨J⍳0 ∇ ``` Explanation: * `S←2 5⍴50`: at the beginning, set `S` to a 5-by-2 matrix where each value is 50. The top row of the matrix represents the cops, the second row represents the robbers. * `J←∨/S>0`: for each row of the matrix, store in `J` whether any of the HPs are larger than zero. * `→6/⍨~∧/J`: if not both teams have living members, jump to line 6. (end) * `⎕←3↑'CR',0⌈S`: for each value in the matrix, output the maximum of it and 0, prepend a 'C' to the first row and an 'R' to the second, and add a third (empty) line. * `N←?10`: get a random number in the interval [1,10] and store it in `N`. * `L←1+~2⊤N`: set `L` (the losing team) to `1` if the number was odd and to `2` if it was even. * `M←(0<S[L`...`;])/⍳5`: get the indices of the living members of that team, and store them in `M` * `M[?⍴M`...`]`: select a random value from `M` * `S[L;M`...`]-←N`: subtract `N` from the selected team member's value * `→2`: jump to line 2 (the test for living members) * `⎕←'CR',⍪'+-'⌽⍨J⍳0`: output the final status, putting the `+` in front of the winning team and the `-` in front of the losing team. [Sample output](https://gist.github.com/marinuso/7410f699d25d57f28604) [Answer] # Ruby, 184 ``` c,r=[p,p].map{('50 '*5).split} puts([?C,*c]*' ',[?R,*r]*' ')while (u,v=[r,c].map{|a|a.shuffle.find{|x|x>?0}}).all?&&[u,v][rand(1..10)%2].sub!(/.+/){eval"#$&-1"} puts u ?'R+ C-':'C+ R-' ``` [Answer] # Mathematica, ~~246~~ 241 bytes Could probably be golfed further... ``` a=ConstantArray[50,{2,5}];b=Or@@(#<1&)/@#&;c=Print;d=StringJoin@Riffle[IntegerString/@#," "]&;e=RandomInteger;Label@f;Which[b@a[[1]],c@"R+\nC-",b@a[[2]],c@"C+\nR-",True,c["C "<>d@a[[1]]<>"\nR "<>d@a[[2]]];a[[Mod[g=e@9+1,2]+1,e@4+1]]-=g;Goto@f] ``` [Answer] ## Batch - 396 Bytes I don't know if this technically counts - as it doesn't actually select a random member of the team *who's health is greater than 0*. It just selects a random member, and if the health subtraction generates a number less than 0, then the number becomes 0.. ``` @echo off&setLocal enableDelayedExpansion&for %%a in (C R)do for %%b in (1 2 3 4 5)do set %%a%%b=50 :a set/aN=%RANDOM%*10/32768+1 set/ac=%N%/2*2 if %c%==%N% (set T=C&set L=R)else set T=R&set L=C set/aG=%RANDOM%*5/32768+1 set/a%T%%G%-=%N% for %%a in (C R)do set %%a=0&for %%b in (1 2 3 4 5)do (if !%%a%%b! LEQ 0 set %%a%%b=0 set/a%%a+=!%%a%%b!) if %C% NEQ 0 if %R% NEQ 0 goto :a echo !T!+&echo !L!- ``` [Answer] **PHP - 416 bytes** I'm new to golfing and though this challenge would be easy enough to try it out. So here is what I came up with. ``` <?$c=[50,50,50,50,50];$r=[50,50,50,50,50];while((array_sum($c)!=0)&&(array_sum($r)!=0)){$a="C ".join(" ",$c)."\n";$b="R ".join(" ",$r)."\n";echo$a,$b;$n=rand(1,10);$m=rand(0,4);if($n %2==0){while($r[$m]==0){$m=rand(0,4);}$r[$m]=$r[$m]-$n;if($r[$m]<0){$r[$m]=0;}}else{while($c[$m]==0){$m=rand(0,4);}$c[$m]=$c[$m]-$n;if($c[$m]<0){$c[$m]=0;}}if(array_sum($r)==0){echo"C+\nR-\n";}if(array_sum($c)==0){echo"R+\nC-\n";}}?> ``` With explanation: ``` <? $c=[50,50,50,50,50];$r=[50,50,50,50,50]; populate Arrays while((array_sum($c) != 0) && (array_sum($r) != 0)){ loop until on array sums up to 0 $a="C ".join(" ",$c)."\n"; set cops health to a $b="R ".join(" ",$r)."\n"; set robbers health to b echo$a,$b; print cop and robber health $n=rand(1,10); chose random n $m=rand(0,4); chose random member if($n % 2 == 0){ check if n is even while($r[$m] == 0){ $m=rand(0,4); } loop until value m of array r is not 0 $r[$m]=$r[$m]-$n; lower health of member m if($r[$m] < 0){ $r[$m]=0; } if health goes below 0 set it to 0 }else{ while($c[$m] == 0){ $m=rand(0,4); } same as above $c[$m]=$c[$m] - $n; if($c[$m] < 0){$c[$m]=0;} } if(array_sum($r) == 0){ echo"C+\nR-\n"; } check if r array sums up to 0 and print that cops won if(array_sum($c) == 0){ echo"R+\nC-\n"; } check if c array sums up to 0 and print that robbers won } ?> ``` [Answer] # C, ~~390~~ ~~384~~ 371 bytes My first golf, if there are any possible improvements, just tell me :) golfed version: ``` #include <time.h> #include <stdio.h> int p[10],j,r,c,w,N,x;int s(){r=c=0;for(j=5;j--;){c+=p[5+j];r+=p[j];}return !!r-!!c;}void t(){for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0);}main(){srand(time(0));for(j=10;j--;)p[j]=50;t();while(!(w=s())){N=rand()%10+1;while(!p[x=N%2*5+rand()%5]);p[x]-=N;t();}N=(x=w<1?'C':'R')-w*15;printf("\n\n%c+\n%c-",x,N);} ``` somewhat ungolfed version: ``` #include <time.h> #include <stdio.h> int p[10],j,r,c,w,N,x; int s(){ r=c=0; for(j=5;j--;){ c+=p[5+j]; r+=p[j]; } return !!r-!!c; } void t(){ for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0); } main(){ srand(time(0)); for(j=10;j--;)p[j]=50; t(); while(!(w=s())){ N=rand()%10+1; while(!p[x=N%2*5+rand()%5]); p[x]-=N; t(); } //w=-1 if cops won, w=1 if robbers won N=(x=w<1?'C':'R')-w*15; printf("\n\n%c+\n%c-",x,N); } ``` edit: I found a way to shorten it a bit and fixed a small bug [Answer] ## Javascript: 410 ``` function x(l){var t=this,o=t.p={n:l||"C",h:[50,50,50,50,50],s:function(){return o.h.reduce(function(a,b){return a+b})},r:function(){console.log(o.n+' '+o.h.join(' '))},d:function(m){while(o.h[z=~~(Math.random()*5)]<1){}o.h[z]=m>o.h[z]?0:o.h[z]-m}};o.r()}q=[new x(),new x('R')];while((c=q[0].p.s()>0)&&q[1].p.s()>0){q[(z=~~(Math.random()*10))%2].p.d(z);q[0].p.r();q[1].p.r()}console.log(c?'C+\r\nR-':'R+\n\rC-') ``` [Answer] # Octave, 182 177 158 145 bytes **145:** ``` t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);r=ceil(rand*5);t(r,c)-=d;t.*=t>0;end;p=2*any(t,1);['C-';'R+';'C+';'R-'](1+p:2+p,:) ``` I gave up checking if the character shoot is above zero - this would only be significant if we were forced to display the state in each turn - here we're just randomly skipping one random number from RNG, making it more random. Also, replaced ``` t=max(0,t) ``` with shorter ``` t.*=t>0 ``` --- ***[note - it is printing 'C+R-' without the newline - it's fixed in 145 byte version]*** **158:** ``` t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;p=4*any(t,1);disp('C-R+C+R-'(1+p:4+p)) ``` Degolfed: ``` t=repmat(50,5); #only first two columns (cops, robbers) relevant while prod(any(t)) d=ceil(rand*10); c=2-mod(d,2); do r=ceil(rand*5);until t(r,c); t(r,c)-=d; t=max(0,t); end; p=4*any(t,1); disp('C-R+C+R-'(1+p:4+p)) ``` I changed `repmat(50,5,2)` to `repmat(5)` - so we have 5x5 matrix instead of 5x2 now (the additional 3 columns don't affect the algorithm). I also found a way to compress the output. **177:** ``` t=repmat(50,5,2);while prod(sum(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;if sum(t)(1)printf "C+\nR-\n";else printf "C-\nR+\n";end ``` Degolfed: ``` t=repmat(50,5,2); while prod(sum(t)) d=ceil(rand*10); c=2-mod(d,2); #cops or robbers affected? do r=ceil(rand*5);until t(r,c); t(r,c)-=d; t=max(0,t); end if sum(t)(1) printf "C+\nR-\n" else printf "C-\nR+\n" end ``` Basically, we create a 5x2 matrix, where the first column are cops and the second column are robbers: ``` t = 50 50 50 50 50 50 50 50 50 50 [cops] [robbers] ``` The `sum` function when one argument applied makes a sum by columns, so it's initially: ``` 250 250 ``` When one of them reaches zero, the `prod(sum(t))` evaluates to zero breaking the loop. Then we can examine who won checking whose column sums to zero. ]
[Question] [ [This question](https://codegolf.stackexchange.com/questions/42220/implement-t9-like-functionality) asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard. Here is key-map of a T9 keyboard if you forgot: ``` +-------+-------+-------+ | 1 | 2 | 3 | | .?! | ABC | DEF | +-------+-------+-------+ | 4 | 5 | 6 | | GHI | JKL | MNO | +-------+-------+-------+ | 7 | 8 | 9 | | PQRS | TUV | WXYZ | +-------+-------+-------+ | * | 0 | # | | ← | SPACE | → | +-------+-------+-------+ ``` ### How T9 works To type a character with T9, you need to press number key representing that character `n` times. `n` is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type `B` I press `2` two times, or to type `5` I press `5` four times. To finish typing this character I press `#`. `*` is simply backspace. In our version of keyboard there is no capitalization. ### Input and output examples: ``` 8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD ``` Explanation: * `8` selects `T` and `#` moves to next character * `99999` select last character of **`9`** key which is `9` and `#` moves to next charachter * `0` inserts a space * `33` selects second character of **`3`** key which is `K` and `#` moves to next character * And so on... ### Rules Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above. This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply. [Answer] # CJam, ~~109~~ 94 bytes (2nd bonus) A very naive and long solution ``` q'#/);{__'*-:A-,_g{){;}*A_}*;'0/{_,g{)~".?~1"a'[,65>292994 5b{/(X):X+\s}%+1:Xm>=\,=}*}%S*1/~}% ``` This is a full program, although a function will be of the same length. The input goes into STDIN Example: ``` 8#99999#055#33#999#***22#666#2#777#3# ``` Output: ``` T9 BOARD ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript ES6, ~~220-10=210~~ 178 bytes As a part of [Helka's CMC](http://chat.stackexchange.com/transcript/240?m=33214382#33214382), I've outgolfed my first challenge. ``` n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``) ``` Sample outputs: ``` > f=n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``) [Function] > f("8#99999#055#33#999#***22#666#2#777#3#") 'T9 BOARD' > f("8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#") 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!' > f("8#99999#055#33#999#***22#666#2#777#3#") 'T9 BOARD' ``` ## Explanation ``` (g=n=>n==(k=n.replace(/.\*/,""))?n:g(k)) ``` This implements recursive replacement, replacing all characters followed by `*` until there are no `*`s left. ``` n.match(/(\d)\1*|\*/g) ``` This matches all runs of consecutive digits, or `*`s. ``` a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0] ``` This creates the desired dictionary, obtaining the encoded part from the large string, then appending the desired digit to it. ``` a[~-e.length%a.length] ``` This gets the character, modulo `a`'s length. ``` .join`` ``` This prepares the string for processing and removal of `*`s. [Answer] # ~~Python, ~~167~~ ~~157~~ 151 bytes~~ (doesn't support '\*') Nothing special. I use regex to convert the input to a list, then i loop the entries. I use the first character and length of each entry to search it in a lookup list: ``` def f(i): import re t9 = [" 0",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV9","WXYZ9"] i = re.findall(r'[1-9]+|0+',i) answer = [] for j in i: answer = answer + [t9[int(j[0])][len(j)-1]] return ''.join(answer) ``` After some golfing it looks like this: ``` import re;m=lambda i:"".join([" 0,.?!1,ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV9,WXYZ9".split(",")[int(j[0])][len(j)-1] for j in re.findall(r'[1-9]+|0+',i)]) ``` No bonuses (yet). I don't know how I would implement the first bonus in regex. The second bonus would add a lot of bytes as the lookup elements are not the same size. Don't really understand the third bonus. [Answer] # Perl 5: 106 (104 code + 2 flags) Modified to handle deletes. ``` #!perl -lp s/((\d)\2*)#?|./chr$2*5+length$1/ge;y//d 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c;1while s/.?d// ``` Usage: ``` perl t9.pl <<<'8#99999#055#33#999#22#666#2#777#3#' perl t9.pl <<<'899999055339992266627773' ``` # Perl 5: 88 (86 code + 2 flags) Old version without star-delete. ``` #!perl -lp s/(\d)(\1*)#?/chr$1*5+length$2/ge;y// 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c ``` [Answer] ## AWK 211 bytes (with the bonuses) ``` {split(".?!1-ABC2-DEF3-GHI4-JKL5-MNO6-PQRS7-TUV8-WXYZ9- 0",k,"-");split($0"#",a,"");while(1+(b=a[++i])){if(b==p)++c;else{for(g in k)if(p==substr(k[g],l=length(k[g])))printf(substr(k[g],1+((c-1)%l),1));c=1;p=b}}} ``` This is a full program which read the input from stdin. It would be more efficient to not resplit the keyboard for each line, but it would make the script longer. Also if the "0" key was anything else than 0, the script would be 4 bytes shorter, but that's part of the game :o) [Answer] # C (245 bytes) ``` #define M "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#" #include<stdio.h> char K[][4]={" ",".?!","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"},I[]=M;int i,j,k,r;main(){for(;I[i];++i){if(I[i]=='#')I[j++]=K[k][--r],r=k=0;else if(I[i]=='*')j?--j:0;else if(!r++)k=I[i]-'0';}I[j]=0;printf("%s\n",I);} ``` ## Output ``` THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG! ``` ## Explanation The byte count does not include the input string given in the first `#define`. I use a two-dimensional array as the lookup table for what character to print. The program reads in characters delimited by `'#'`. For each group, the input number determines the first-dimension array index, and the number of repetitions of the input number determines the second-dimension array index. The `'*'` moves back the index of the array for the output string so as to overwrite the previous letter. So the input string `44#` (1 repetition of `'4'`) is translated to lookup table `K[4][1]`, which is the character `H`. --- ## Ungolfed Version ``` #define INPUT "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#" #include<stdio.h> static const char keyboard[10][4] = {" ", ".?!", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"}; int main(void) { char input[] = INPUT; char output[256]; int i, j; int key = 0; int reps = 0; for (i = j = 0; input[i] != '\0'; ++i) { switch (input[i]) { case '#': output[j] = keyboard[key][reps - 1]; ++j; reps = key = 0; break; case '*': if (j > 0) --j; break; default: if (reps == 0) { key = (int)input[i] - '0'; } ++reps; break; } } output[j] = '\0'; printf("%s\n", output); return(0); } ``` [Answer] # Ruby 254, 248, 229 bytes Golfed: ``` n=->(t){r,m,b=[]," _.?!1_ABC2_DEF3_GHI4_JKL5_MNO6_PQRS7_TUV8_WXYZ9_*_0_#".split("_"),nil;t.scan(/((.)\2*)/){|l,_|(!(l=~/\#/)?(l=~/\*/?(r.pop l.size):(l=="00"?r<<(b ? "0 ":" 0"):(c=m[l[0].to_i];r<<c[l.size%c.size-1]))):b=l)};r*""} ``` Ungolfed: ``` def t9totext(t) bonq = nil numpad = [" ",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV8","WXYZ9","*","0","#"] r = [] t.scan(/((.)\2*)/) do |l, _| if !(l =~ /\#/) if l =~ /\*/ r.pop(l.size) elsif l == "00" r << (bonq ? "0 " : " 0") else c = numpad[l[0].to_i] r << c[l.size % c.size - 1] end else bonq = l end end r.join end ``` All these specs should succeed: ``` it "outputs the correct word" do expect(n.call('8#99999#055#33#999#22#666#2#777#3#1')).to eq("T9 KEYBOARD.") expect(n.call('4433555#55566609666666677755533*3111')).to eq("HELLO WORLD!") expect(n.call('7##222#222**7#222#4')).to eq('PPCG') expect(n.call('00#0#00')).to eq(' 0 0 ') end ``` The `0 0` answer looks a bit like a hacky solution. Will look into it when I've got the time. [Answer] # PHP, 183-10=173 bytes All versions take input from command line argument; call with `php -r '<code>' <string>`. *Note*: All versions throw a warning if input starts with `*`. Prepend `$o=[];` to the code to remove that flaw. ``` preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]="- 0 .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)];echo join($o); ``` * does not need hash tags * fails if a key is pressed too often **210-10-??=??? bytes** ``` $a=[" 0",".?!1",ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV8,WXYZ9];preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=$a[$w[0]][strlen($w)%strlen($a[$w[0]])-1];echo join($o); ``` * does not need hash tags * rotates if a key is pressed too often **181 bytes, no bonus** ``` preg_match_all("%\d+#|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=" 0 .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)-2];echo join($o); ``` --- **breakdown** The "no hash tags" versions split the string to (streak of equal numbers) and (asterisk) and forget everything else. The no-bonus version takes (streak of numbers followed by `#`) and (asterisk). Then loop through the matches: If a '\*' is found, remove the last element of the result array. The difference between the versions is in the `else` part: * no bonus version: offset map string to (key\*5), then add (keystrokes=word length-1)-1, add character from that position to result. * simple no-tag version: almost the same, but: (keystrokes=word length); added a character to the map string to get rid of the other `-1`. * rotating version: take item (key) from map array, add character (keystrokes%item length-1) from that item to result. [Answer] # JavaScript, 147 bytes [Conor´s answer](https://codegolf.stackexchange.com/q/42471#42471) fixed with the regex from [my PHP answer](https://codegolf.stackexchange.com/q/93257#93257) and golfed down. ``` t=i=>i.match(/(\d)\1*|\*/g).map(w=>(" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length-1]).join``.replace(/.\*/g,"") ``` **breakdown** ``` t=i=>i .match(/(\d)\1*|\*/g) // split input to streaks of equal numbers and single `*` .map(w=> // replace each item with ... // .. take string depending on the digit (" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]] ||"*") // .. ("*" for not a digit) [w.length-1] // -> the (item length)th character of that string ) .join`` // join without delimiter .replace(/.\*/g,"") // and recursively remove every (letter,asterisk) combination ``` **rotating version, 158 bytes** added `s=` to remember the string and `%s.length` to rotate. ``` t=i=>i.match(/(\d)\1*|\*/g).map(w=>(s=" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length%s.length-1]).join``.replace(/.\*/g,"") ``` ]
[Question] [ Your task is to implement a program similar to the `nl` command-line tool from the GNU core utilities. [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/16402) are banned. You may not use any built-in or external function, program or utility for numbering the lines of a file or string, such as `nl` itself or the `=` command in GNU sed. # Specification ## Input The program accepts filenames as arguments. Your code does not have to be cross-platform; the filename format of the OS running the code should be used, i.e. if you happen to be on Windows, the directory separator can be `\` or `/`. You must be able to take 64 input files, including `-` if it is specified. If over 64 are given, only handle the first 64. In the list of filenames, `-` represents standard input. If filenames are given, read from the files in the order that they are given and concatenate their contents, inserting a new line between each one and at the end. If you cannot read from one or more of the filenames (because the file does not exist or you do not have read permissions for it), ignore them. If all filenames specified are invalid, output nothing. If no filenames are given, read from standard input. Only read from standard input if no filenames are given or if `-` is given. ## Output The program will output, to standard output, the input with lines numbered thus (You may assume that the input has `\n`, `\r\n` or `\r` line endings; pick whichever is convenient for you, but specify which one): ``` <5 spaces>1<tab><content of line 1 of input> <5 spaces>2<tab><content of line 2 of input> ... <4 spaces>10<tab><content of line 10 of input> ... <3 spaces>100<tab><content of line 100 of input> ... ... ``` 6 characters of space are allocated for the line number, and it is inserted at the end of these characters; the rest become spaces (e.g. `1` will have 5 leading spaces, `22` will have 4 leading spaces, ...). If the input is sufficiently long, you will eventually run out of space for the line number, at line `999999`. You must not output anything after line 999999. If the input is empty, output nothing. ## Exit status The lower numbers take priority: if errors 1 and 2 were encountered, exit with status 1. Exit with status 0 if the input was successfully received, and the lines successfully numbered and output. Exit with status 1 if one or more of the files specified on the command line were not found or could not be read from. Exit with status 2 if too many files (more than 64) were given. Exit with status 3 if the input was too long (more than 999999 lines).\ ## Scoring This is code-golf - shortest program wins! I may add bonuses later for implementing certain options that `nl` has. There are no bonuses at the moment. [Answer] ## Bash, 121 ``` s=$[2*($#>64)] for f in "$@";{ [ -f $f ]||s=1;} ((s))&&exit $s awk '{if(NR>=10**6){exit 3}printf("%6d\t%s\n",NR,$0)}' $@ ``` [Answer] # Ruby, 195 ``` o,l=$*[64]?[2]:[],999999 ($*==[]?[?-]:$*).each{|n|f=n==?-?STDIN: open(n)rescue o<<1&&next s=f.read.lines s[l]?o<<3:1 puts s[0..l].map.with_index(1){|l,i|i.to_s.rjust(6)+?\t+l}} exit !o[0]?0:o.min ``` [Answer] ### python 173 ``` import os,sys c=0 l=1 for f in sys.argv[1:]: if c>64:exit(2) if not os.path.isfile(f):exit(1) c+=1 for x in open(f): if l>=10**6:exit(3) print '%6d\t%s'%(l,x),;l+=1 ``` [Answer] ## J (162) ``` exit(((2*64<#)[exit@3:`(stdout@(,&LF)@;@(,&TAB@(6&":)&.>@>:@i.@#,&.>]))@.(1e6>#)@(<;.2)@(1!:1)@(<`3:@.('-'-:]))&.>@;@{.@(_64&(<\))) ::1:)]`(]&<&'-')@.(0=#)2}.ARGV ``` Explanation: * `]`(]&<&'-')@.(0=#)2}.ARGV`: Get the command line arguments, and remove the first two (because those are the interpreter and the script file name). If the resulting list is empty, return `['-']` (i.e., as if the user had passed only `-`), otherwise return the list unchanged. * `(` ... `::1:)`: if the inner function fails, return `1`, otherwise return whatever the inner function returned. * `((2*64<#)[`...`)`: evaluate the inner function and throw the result away. Then, if the length of the passed list was not higher than `64`, return `0`, otherwise return `2`. * `&.>@;@{.@(_64&(<\))`: get at most `64` elements from the list, and for each of them run the following function: + `(1!:1)@(<`3:@.('-'-:]))`: if the element was `-`, read the contents of file descriptor `3` (stdin), otherwise read the contents of the file named by that element. If this fails (i.e. file doesn't exist), the code above will catch it and return `1`. + `exit@3:`(`...`)@.(1e6>#)@(<;.2)`: split the string on its line endings. If there are 1.000.000 or more lines, exit with status `3`. Otherwise: - `,&TAB@(6&":)&.>@>:@i.@#`: generate the numbers for each line, format them in a 6-digit column, and add a `TAB` to the end of each string, - `,&.>]`: add each number to the front of each line. - `stdout@(,&LF)@;`: then output the whole thing, followed by an extra `LF`. * `exit`: exit with the return value of that function [Answer] # Ruby, 76 bytes One byte for the `p` flag. Run with `ruby -p nl.rb`. ``` BEGIN{x=$*.size-65} exit 2if$*.size==x exit 3if$.>999999 $_="%6d"%$.+?\t+$_ ``` stdin or file arguments are handled automatically by Ruby. It already exits with code 1 if a file argument doesn't exist. `$.` is the number of lines that have been read. `$*` is the command line arguments, and the files are popped off as the files are read. The `p` flag executes the `BEGIN` block and wraps the rest of the program inside a while-gets-print loop, using `$_` as the input/output. [Answer] # Perl, ~~125~~ 122 bytes ``` @a=@ARGV;for(@a){$i++>63&&exit 2;($_ eq '-'or-e$_)or next;@ARGV=$_;while(<>){$c>1E6-2&&exit 3;printf"%5d\t%s",++$c,$_}say} ``` [Answer] ## Perl, 84 + 2 (`-pl`) = 86 bytes ``` perl -ple'BEGIN{map{-r||exit 1}@ARGV;@ARGV>63&&exit 2}$.>=1e6&&exit 3;$_=printf"%5d\t%s",$.,$_' ``` Deparsed: ``` perl -MO=Deparse -ple'BEGIN{map{-r||exit 1}@ARGV;@ARGV>63&&exit 2}$.>=1e6&&exit 3;$_=printf"%5d\t%s",$.,$_' output.txt; echo $? BEGIN { $/ = "\n"; $\ = "\n"; } sub BEGIN { map {exit 1 unless -r $_;} @ARGV; exit 2 if @ARGV > 63; } LINE: while (defined($_ = <ARGV>)) { chomp $_; exit 3 if $. >= 1000000; $_ = printf("%5d\t%s", $., $_); } continue { die "-p destination: $!\n" unless print $_; } -e syntax OK ``` Important to know: * `-p` wraps the program given with `-e` in the `while`/`continue` loop * `BEGIN` code will be executed before the (implicit) main part * file test `-r` also fails if file doesn't exist `!-e` and defaults to testing `$_`, implicitly given in `map { ... } @ARGV` * `$.` holds the current line number * rest should be self-explanatory ;) [Answer] # C, ~~362~~ 359 Just for the fun of it. ;-) Works with LF or CR/LF linefeeds. ``` #include<stdio.h> #define R return #define P printf( e,t,l;void*f;r(){P"% 6d\t",++l);for(;(t=fgetc(f))^-1&&l<1000000;){if(ferror(f))R 1;P"%c",t);if(t==10)P"% 6d\t",++l);}P"\n");R l<1000000?0:3;}main(int c,char**v){e=c>65?2:0;for(++v;*v||c<2;++v){t=c<2||!strcmp(*v,"-")?f=stdin,0:!(f=fopen(*v,"rb"));if(t||(t=r()))e=!e|(e>t)?t:e;if(f&&f!=stdin)fclose(f);}R e;} ``` ]