text
stringlengths
180
608k
[Question] [ In any programming or scripting language *x*, write a program that takes a valid brainfuck sourcecode from stdin and output, to stdout, the sourcecode of a program, written in language *x*, that would output the exact same thing as the brainfuck program would do. Your program must work for any valid brainfuck program, including the empty file. Your score would be equal to the byte count of your sourcecode, plus the byte count of your output given the following input: ``` +++++ [-] +++++ +++++ [ > +++++ ++ > ++ +++ ++++ + > +++ <<< - ] > ++ . H > + . e ++ +++ ++. l . l +++ . o > ++ . space < +++++ +++ . w ----- --- . o +++ . r ---- - - . l ----- --- . d > + . exclamation mark ------lol; useless code :-)--------------------------[.............................................][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]<-<<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>< ``` For example, for an input of `[-]`, the output of `*p=0;` is much more favourable than `while(*p) *p--;` If you happen to use non-ASCII characters, the byte count must be calculated using the UTF-8 encoding. Lowest score wins. However, creative solutions that attempt to minimise the output shall be encouraged by upvotes. [Answer] # Brainfuck, 5 + 540 = 545 bytes 5 bytes of code, 540 from output of given test file (assuming got the count right from my paste of that code). ``` ,[.,] ``` Assuming EOF is 0. [Answer] ## Perl - 177 (source) + 172 (output) = 349 ``` #!perl -p0 y/-+><.,[] -~/p-w/d;s/(.)\K\1+|rs|wv[^v]*(?=w)/$+&&length$&/ge;$_="eval'r$_'=~".'s/.(\d*)/(qw(--$ ++$ -- ++ print+chr$ $$i=ord+getc; while($$i){ })[$&&v63].q($i;))x($++1)/ger' ``` Counting the shebang as 2 bytes, one for each option. First, each of the eight commands is translated onto the range `p-w`, while at the same time removing all other characters. This string is then run-length encoded and output with a minimal decoder/interpreter. A few things are optimized away: the string `><` obviously does nothing, and a for loop that follows directly after another may be removed entirely, as it will never be entered. Output for the test program: ``` eval'rq4vpwq9vrq6rq9rq2s2pwrq1trqtq6t1q2trq1tsq7tp7tq2tp5tp7trqtp32vt44wsps1'=~s/.(\d*)/(qw(--$ ++$ -- ++ print+chr$ $$i=ord+getc; while($$i){ })[$&&v63].q($i;))x($++1)/ger ``` A sample run: ``` $ perl brainfusk.pl < in.bf | perl Hello world! ``` --- ## Perl - 232 (source) + 21 (output) = 253 ``` #!perl -p0 y/-+><.,[] -~/0-7/d;$_="eval'2$_'=~".'s/./qw(--$ ++$ -- ++ print+chr$ $$i=ord+getc; while($$i){ })[$&].q($i;)/ger'; /5/||fork?(wait,$?||exit):($SIG{ALRM}=sub{exit 1},alarm 9,$S=select(open 1,'>',\$o),eval,print$S "print\"\Q$o\E\"") ``` This one is based on [FIQ](https://codegolf.stackexchange.com/users/15563/fiq)'s observation that if the original program doesn't contain an input statement, the output will be static, and therefore can be reduced to a single `print` statement. If you like this one, be sure to give [his answer](https://codegolf.stackexchange.com/a/19950) a +1. So what we can do is pipe `stdout` to a variable, `eval` the code we would have output, and wrap the result in a `print`. ...that won't always work, though. Whenever the code to be translated would have resulted in an infinite loop, (e.g. `+[.]`), this *cannot* be reduced to a single `print` statement, for obvious reasons. So instead, we launch the `eval` in a child process with a short timeout, and if it doesn't finish executing within that time we output the translated program as before. Structured and commented: ``` if(!/5/) { # no `,` in program if(fork) { # parent process # wait for child wait; # no child error, terminate without output $?||exit } else { # child process # alarm handler, exit with error $SIG{ALRM}=sub{exit 1}; # set an alarm in 9 seconds alarm 9; # redirect STDOUT to variable $o $S=select open 1,'>',\$o; # execute translated code eval; # wrap the result in a print statement print$S "print\"\Q$o\E\"" } } ``` Output for sample program: ``` print"Hello\ world\!" ``` Output for `,[.]`: ``` eval'25647'=~s/./qw(--$ ++$ -- ++ print+chr$ $$i=ord+getc; while($$i){ })[$&].q($i;)/ger ``` Output for `+[.]` (after 9 seconds): ``` eval'21647'=~s/./qw(--$ ++$ -- ++ print+chr$ $$i=ord+getc; while($$i){ })[$&].q($i;)/ger ``` [Answer] # PHP, 553 + 27 = 580 bytes (553 bytes with all whitespaces, i.e. newlines and spaces, removed) I suck badly at golfing PHP, so this approach can be heavily optimized. I mostly wanted to show my approach to the solution in something not BF. ``` <?php echo "<?php "; $x = 'if (!$b) $c = $_GET[c]; $x=$y=$n[0]=$p=0;$o[0]=1;$d=""; while($a=$c[$x++]){ if($o[$p]){ if($a=="-")$m[$y]--; if($a=="+")$m[$y]++; $m[$y]=$m[$y]%256; if($a=="<")$y--; if($a==">")$y++; if($a=="."){ $e=chr($m[$y]); if ($b) echo $e; else $d.=addslashes($e); } if($a==",")$m[$y]=($b=$_GET[i])?ord($b):0; }if($a=="["){ $p++; $n[$p]=$x-1; $o[$p]=$o[$p-1]?$m[$y]:0; } if($a=="]"){ if($o[$p])$x=$n[$p]; $p--; if($p=-1)$p=0; } } if (!$b) echo "echo \'$d\';";'; if (strstr($_GET['c'],",")) { $x = '$b=1;'.$x; echo '$c="'.addslashes($_GET[c]).'";'.$x; return; } eval($x); ``` Error reporting must be off, otherwise PHP will hate you. Usage: throw this up as a page, and run it with script.php?c=CODE (if the resulting script requires input, you run it as out.php?i=INPUT). Remember to url escape the input! What this does is basically this - if the BF script contains ",", it pretty much embeds itself as the resulting script with an attached $b=1; at the top. If it does NOT contain ",", it optimizes it down to "echo '<BF output>'". Conveniently, the test script in the OP does NOT require any input. The addslashes() is just there for escaping ' and \. [Answer] # C++, 695 + 510 = 1205 bytes Code: ``` #include<iostream> #include<utility> #include<vector> #define D "\n#define " using namespace std;using S=string;int main(){vector<pair<S,S>>m={{"--------","(*p)-=8;"},{"<>",""},{"[]","F;"},{"+","A;"},{"-","B;"},{">","C;"},{"<","D;"},{"[","F{"},{"]","}"},{".","E;"},{",","std::cin>>*p;"}};S s;char c;while(cin>>c)if(S("+-><[].,").find(c)<8)s+=c;for(int i=0;i<s.length();i++)if(s.substr(i,4)=="[][]")s=s.replace(i--,4,"[]");cout<<"#include<iostream>" D"A ++*p" D"B --*p" D"C p++" D"D p--" D"E std::cout<<*p" D"F while(*p)\nint main(){char*p=new char[1<<19]();";while(s.size())for(auto p:m)if(s.substr(0,p.first.length())==p.first){s=s.substr(p.first.length());cout<<p.second;break;}cout<<"}";} ``` Output: ``` #include<iostream> #define A ++*p #define B --*p #define C p++ #define D p-- #define E std::cout<<*p #define F while(*p) int main(){char*p=new char[1<<19]();A;A;A;A;A;F{B;}A;A;A;A;A;A;A;A;A;A;F{C;A;A;A;A;A;A;A;C;A;A;A;A;A;A;A;A;A;A;C;A;A;A;D;D;D;B;}C;A;A;E;C;A;E;A;A;A;A;A;A;A;E;E;A;A;A;E;C;A;A;E;D;A;A;A;A;A;A;A;A;E;(*p)-=8;E;A;A;A;E;B;B;B;B;B;B;E;(*p)-=8;E;C;A;E;(*p)-=8;(*p)-=8;(*p)-=8;(*p)-=8;B;F{E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;E;}F;D;B;D;D;} ``` Original code: ``` #include <iostream> #include <utility> #include <vector> using namespace std; int main() { vector<pair<string, string>> m={ {"--------","(*p)-=8;"}, {"<>",""}, {"[]","F;"}, {"+","A;"}, {"-","B;"}, {">","C;"}, {"<","D;"}, {"[","F{"}, {"]","}"}, {".","E;"}, {",","std::cin>>*p;"}}; string s; char c; while (cin >> c) if (string("+-><[].,").find(c) < 8) s += c; for(int i = 0; i < s.length(); i++) if(s.substr(i, 4) == "[][]") s = s.replace(i--, 4, "[]"); cout << "#include<iostream>\n" "#define A ++*p\n" "#define B --*p\n" "#define C p++\n" "#define D p--\n" "#define E std::cout<<*p\n" "#define F while(*p)\n" "int main(){char*p=new char[1<<19]();"; while (s.size()) for (auto p : m) if (s.substr(0, p.first.length()) == p.first) { s = s.substr(p.first.length()); cout << p.second; break; } cout << "}"; } ``` [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 109 + 407 = 516 ``` >+[>+++++++[-<------>]<-[-[-[-[--------------[--[>+++++[-<------>]<+[--[[-]<[-]>]]]]]]]]<[.[-]]>>,[-<+<+>>]<] ``` [Try it online!](https://tio.run/##vY89DsIwDIV3n8IrCu4BwPLMHaIMoQQJNW1RSwW3L/lpCx0YWPosK34vnxXl3Nlbcx3KahxFaVFZmpiSxDDpqVYKdqK/WRVjTYZDi5nEugjWiOwDqlhJAM04pmUMN5CnyQMGCc7ZYnFm8JPliZmRwECiCjzFIZwOlqUCPcRWCWhnsr/b0gEvb8XsCekvGDuiOe0ghxhDv0Iu83Ov0tvaPm5tg7XtqgyRb/0Rh9551/dYtheHB9rRT@niHxm9aTExywb1Bg "brainfuck – Try It Online") It only removes non BF ops and does not look at other optimizations. [Answer] ## Python - 514 + 352 = 866 Code: ``` import sys,zlib,base64 s,i="import sys\na,i=[0]*300000,0\n",0 for c in sys.stdin.read(): if c in"+-><,.[]": s+=" "*i+{'+':"a[i]+=1\n",'-':"a[i]-=1\n",'>':"i+=1\n",'<':"i-=1\n",',':"a[i]=(lambda x:0if x==''else ord(x))(sys.stdin.read(1))\n",".":"sys.stdout.write(chr(a[i]))\n","[":"while a[i]!=0:\n","]":"pass\n"}[c] i+={'[':1,']':-1}.get(c,0) print('import zlib,base64\nexec(zlib.decompress(base64.b64decode("'+base64.b64encode(zlib.compress(bytes(s,"utf8"),9)).decode("utf8")+'")).decode("utf8"))') ``` Output: ``` import zlib,base64 exec(zlib.decompress(base64.b64decode("eNrLzC3ILypRKK4s5krUybSNNojVMjYAAR0DrsTozFhtW0OCdHlGZk6qAoinaGtgxQVm6QLFFQoSi4uJNoVc2zJBggowWTIZVDGEEvMzddFJ1FDMxBYUwFjTKy5JyS8t0SsvyixJ1UjOKNIASWpqomrAp5DceMBnJjn2Ee0ZojToUiGlEfIFzA5yaGqHELXtp5XfMukVwMOFRi/u8IXZqOSo5KjkqOSIlAQ3k9BLy1HBUcFRwVFBOgpmIrfeMhGE9ihrpLEAudg3NA==")).decode("utf8")) ``` [Answer] # Lua - 319 + 21 = 340 This is most likely the shortest code of all, but it doesn't accept input, so it is kinda cheaty. I got a idea for another version with input, see the end of this comment. ``` loadstring("o=\"\";d={"..string.rep("0,",30000).."}p=1;"..io.read():gsub("[^%+%-<>%.,%[%]]+",""):gsub(".",{["+"]="d[p]=d[p]+1;",["-"]="d[p]=d[p]-1;",[">"]="p=p+1;",["<"]="p=p-1;",["."]="o=o..string.char(d[p])",[","]="d[p]=io.read()",["["]="while d[p]~=0 do ",["]"]="end;"}))()print("print("..string.format("%q",o)..")") ``` # Lua - 376 + 366 = 742 This version is to prove that lua can do better than 2584 :D ``` print('loadstring("d={"..string.rep("0,",30000).."}p=1;"..('..string.format("%q",io.read():gsub("[^%+%-<>%.,%[%]]+",""):gsub("%[[^%+%-<>%,%[%]]*%]",""):match("(.*[.,]).-"))..'):gsub(".",{["+"]="d[p]=d[p]+1;",["-"]="d[p]=d[p]-1;",[">"]="p=p+1;",["<"]="p=p-1;",["."]="io.write(string.char(d[p]))",[","]="d[p]=string.byte(io.read())",["["]="while d[p]~=0 do ",["]"]="end;"}))()') ``` Both versions add in 30000 bytes of data. My second version is based on input/output: everything after a '.' or ',' will be removed. My second version does not allow infinite loops ( [.,], [], etc. ) My Idea is to get: ``` print("Hello world!"..string.char(string.byte(io.read())+1) ``` From your input, with a extra ',+.' [Answer] # io ### 659 + 553 = 1212 Things like `File standardInput readBufferOfLength(1)` really kill the byte count but I can't get around it. I didn't do optimizations for repeated symbols or lack of input in the BF program, but will continue to work on it, also working on one making use of io's metaprogramming capabilities. ``` "v :=Vector clone setSize(30000) p :=0 z :=getSlot(\"method\") j :=z(p=p+1) k :=z(p=p-1) a :=z(v at(p)) l :=z(v atPut(p,a+1)) m :=z(v atPut(p,a-1)) n :=z(a asCharacter print) u :=getSlot(\"while\") o :=z(v atPut(p,File standardInput readBufferOfLength(1)))"println z :=getSlot("method") g :=z(a,b,if(a,a,b)) v :=z(e,f,if((x :=s)==e,nil,f .. g(w(x),""))) s :=z(File standardInput readBufferOfLength(1)) w :=z(c,c switch(">",v("<","j"),"<","k","+","l","-","m",".","n",",","o","[",v("]","u(a>0,"),"]",")")) while((c :=s)!=nil,if((t :=w(c))!=nil,t println)) ``` Testing ``` cat test.bf | io bftrans.io > out.io && io out.io && echo && echo $(cat out.io | wc -c) " + " $(cat bftrans.io | wc -c) " = "$(($(cat bftrans.io | wc -c) + $(cat out.io | wc -c))) ``` Yields ``` Hello world! 659 + 553 = 1212 ``` [Answer] # Lua - 328 + 2256 = 2584 (Oh I just realized you need to add the length of the result too, poor score, it looks like) ``` print((("l,m,p=loadstring,{0},1 z,y,x,w,v,u=l'io.write(string.char(@))',l'@=io.read(1):byte()',l'p=p-1',l'p=p+1 @=@or 0',l'@=(@+1)%256',l'@=(@-1)%256'"..io.read"*a":gsub("[^.,<>[%]+-]",""):gsub(".",{["."]="z()",[","]="y()",["<"]="x()",[">"]="w()",["["]="while @~=0 do ",["]"]="end ",["+"]="v()",["-"]="u()"})):gsub("@","m[p]"))) ``` Taken from [this](https://codegolf.stackexchange.com/questions/84/interpret-brainfuck/10453#10453) answer of mine. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/17110/edit) The point of this puzzle is to learn how a malicious code can be hidden and discovered in a program. A person is asking the question: > > Plz give me some code that how can I search a file may be in Present > Directory or in its Sub-Directories. > > > (This is a variant of a real question I've seen posted on one site.) To be more specific: The OP wants you to write a program that accepts a string and a directory. It will traverse all files in the directory and recursively all its subdirectories. For each file it will check if the file contains the string, and if it does, will print the name of the file. (The program can have additional features as long as they are relevant to the main goal, if you wish.) There are no requirements on the traversal order. However, the main task of this puzzle is to hide into the program additional code that will make a fool of the person that asks for the program in the eyes of its users/colleagues/boss/etc. For example, print a humiliating text at some point, such as: *The author of the program doesn't know how to program, should return his/her diploma and get fired.* Be creative. Rules: * The solution **must not be harmful** (except making fool of the OP, of course). It must not do any irreversible damage to end users (no stuff like `rm -rf`)! Such solutions will be disqualified. * The trolling stuff should be hidden so that the OP won't find it easily. * It shouldn't be obvious that you're trolling the OP. The code should look genuine. * The solution *must* come with a *proper* explanation how it trolls the OP so that everybody can learn something from your solution. The explanation should be hidden in a [hidden-until-you-click text (spoilers)](https://meta.stackexchange.com/a/71396/192930). When judging, try to discover the trolling without looking at the explanation and vote for those that are difficult to discover. * Also try to hide the trolling from the OP if (s)he tries to run the code a few times. Perhaps start trolling only after a particular date, or under some conditions that a sloppy programmer won't test. Be creative and don't forget to explain the trick. * Don't just create a script using existing tools such as `grep` or `find`. Write the program from scratch. Better avoid libraries and prefer low-level calls - this will make the code more complex and gives you the opportunity to hide the evil stuff there. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). Please judge according the above points. [Answer] Here is my solution (in Perl): ``` #! /usr/bin/perl -w use Cwd 'abs_path'; # Check the command line arguments my $F = abs_path($0); if ($#ARGV!=1) { print "Usage: ".$F." <dir> <expr>\n"; exit(1); } # The first argument is the directory my @u = (abs_path($ARGV[0])); # Check for trailing slash my $c = substr $u[0], -1, 0; # Iterate on the files for my $k ( @u ) { if (-d $k && -r $k && -x $k) { # If the file is a directory, we add its sub-files to the list of files push (@u, glob($k.($c eq "/" ? "*" : "/*"))); } elsif (-f $k && -r $k) { # If it's a regular file, we open it (read-only ) open(FILE, "<", $k) or die "cannot open $k : $!"; # Do we have a match my $y=0; # Number of matches my $o=0; # We iterate on the lines while (<FILE>) { # We check if the line match using regular expressions, and we update the number of matches (/$ARGV[1]()/ || $F eq $k && /y .([F c-y])/) && (($c,$y,$o)=($c.$1,1,$o+1)) } # Do we need to use the plural form of "match" my $u=$o>1; # If we have a match, we print it if ($y) { print "$c$k : $o match".($u?"es\n":"\n"); } # Close the file (opened read-only ) close(FILE) or die "cannot close $k : $!"; } } ``` The first argument of the program is the directory and the second argument is the string we are looking for. The program also show the number of matches in each file. Here is how to search "VGA" in /etc: ``` $ ./mygrep.pl /etc VGA /etc/alternatives/mplayer : 7 matches /etc/alternatives/pinentry : 1 match /etc/alternatives/pinentry-x11 : 1 match /etc/alternatives/www-browser : 1 match /etc/bumblebee/xorg.conf.nouveau : 2 matches /etc/bumblebee/xorg.conf.nvidia : 2 matches /etc/default/console-setup : 2 matches /etc/htdig/english.0 : 1 match /etc/X11/X : 6 matches /etc/laptop-mode/conf.d/video-out.conf : 3 matches $ ``` And now, here is the trick : > > The program works exactly as advised as long as it doesn't encounter itself in the files. As soon as it encounters itself, it starts to prefix each file found with insanity. > Let's copy some files in the current directory and try again : > > ``` > $ cp /etc/default/console-setup /etc/bumblebee/xorg.conf.nouveau /etc/bumblebee/xorg.conf.nvidia /etc/htdig/english.0 ./ > $ ./mygrep.pl ./ VGA > /tmp/mygrep/console-setup : 2 matches > /tmp/mygrep/english.0 : 1 match > Fuck you /tmp/mygrep/mygrep.pl : 9 matches > Fuck you /tmp/mygrep/xorg.conf.nouveau : 2 matches > Fuck you /tmp/mygrep/xorg.conf.nvidia : 2 matches > $ > ``` > > This is due to this code: > > ``` > $F eq $k && /y .([F c-y])/ > ``` > > It tests if the current file is the running program, and if it is, it extract some part of the program with a regexp and affects it to $c with > > ``` > $c = $c.$1 > ``` > > What is extracted by the regexp are the variable declarations (variables are named $F, @u, $c, $k, $y, $o, $u) and two spaces from the comments. > I had to do that to keep it hidden, even if the program is relatively short. > > > ]
[Question] [ The [Matoran Alphabet](https://bionicle.fandom.com/wiki/Matoran_Alphabet) is the alphabet used by many of the characters in the Bionicle universe. ![Matoran Alphabet](https://i.stack.imgur.com/DbPxs.jpg) Your challenge is to create a program or function that takes a string as input and creates an image of the input written in the Matoran alphabet. The input will only consist of uppercase letters (A-Z), numbers (0-9), and spaces. You may instead take input in lowercase. ## Glyphs As you can probably notice, the alphabet comprises glyphs made up of circles and straight lines. For the sake of this challenge, let's define each glyph as a circle of radius 4 units (8 x 8), with some internal designs. The internal designs of letters can be any of: * Vertical Line at position 2, 4, or 6 (either full length or half) * Horizontal Line equivalent to above * Circle of radius 1, centered at [2, 2], [2, 6], [6, 2], or [6, 6] * Any of the above rotated by 45 degrees about the centre Note that for some glyphs (notably D, H, and K) only some of the drawn parts have the rotation applied. Number glyphs work slightly differently; they always have a circle of radius 1 in the centre. For numbers 0 - 5, the glyph has evenly spaced spokes between the circles, starting from the top. For numbers greater than 5, the glyph has an additional circle of radius 2 in the centre, and the number of spokes is 6 less than the number. Here is a diagram of the glyphs in spec, any glyphs with 45 degree rotations have an orange grid. ![Matoran Alphabet](https://i.stack.imgur.com/nI1Pa.png) For drawing the glyphs, any line stroke in the range (0, 1) can be used. Glyphs can be kerned (space between adjacent glyphs) any amount from 0 - 4 units. Spaces should be 8 units wide (in addition to kerning). This is a code-golf challenge, so the shortest code in bytes in each language wins. [Answer] # Java 10, ~~1291~~ ~~1271~~ 1265 bytes ``` import java.awt.*;a->new Frame(){Graphics G;void o(int x,int y,int s){G.drawOval(x,y,s,s);}void l(int...c){G.drawLine(c[0],c[1],c[2],c[3]);}public void paint(Graphics g){G=g;int x=10,A=20,B=40,C,D=60,E=70,F=80,G=100,H=120,I,J;for(var c:a){C=x+B;I=x+67;J=x+30;if(c>32){o(x,B,F);if(c<58){o(J,E,A);if(c>53){o(x+A,D,B);if(c>56){l(C,B,C,D);l(x+22,90,x+7,G);l(x+58,90,x+73,G);}else{if(c>54)l(C,B,C,D);if(c>55)l(C,G,C,H);}}else{if(c>52){l(C,B,C,E);l(x+2,69,x+31,77);l(x+78,69,x+49,77);l(x+34,87,x+17,112);l(x+46,87,x+63,112);}else if(c==51){l(C,B,C,E);l(x+32,85,x+7,G);l(x+48,85,x+73,G);}else{if(c>48)l(C,B,C,E);if(c>49)l(C,90,C,H);if(c>51){l(x,F,J,F);l(x+50,F,x+F,F);}}}}else{var q=c+"";if("BHUV".contains(q))o(J,B,A);if(c>66&c<69|c==87)o(x+D,E,A);if(c<67|c==72)o(J,G,A);if(c==87)o(x,E,A);if(c>81&c<84|c==F)o(x+50,50,A);if(c==76|c==81)o(x+50,90,A);if(c==74|c==83)o(x+10,90,A);if("DGIJLPR".contains(q))l(C,B,C,H);if(c==71|c==82|c==84)l(C,F,x+F,F);if(c==84)l(C,F,C,H);if(c==75|c==84)l(x,F,C,F);if("KVWXYZ".contains(q))l(C,F,I,52);if("KNVWXY".contains(q))l(C,F,I,108);if("VWXZ".contains(q))l(x+13,108,I,52);if("NVWXY".contains(q))l(x+13,52,I,108);if(c>68&c<71){l(x+5,D,x+75,D);if(c<70)l(x+5,G,x+75,G);}if(c==72|c==77){l(x+A,45,x+A,115);l(x+D,45,x+D,115);}}}x+=F;}}{show();}} ``` Input as a character-array. Output with a unit being 10 pixels without kerning. Some example I/O screenshots: `"1357902468"`: [![enter image description here](https://i.stack.imgur.com/6A9HN.png)](https://i.stack.imgur.com/6A9HN.png) `"KEVIN CRUIJSSEN"`: [![enter image description here](https://i.stack.imgur.com/A54E2.png)](https://i.stack.imgur.com/A54E2.png) `"MATORAN ALPHABET"`: [![enter image description here](https://i.stack.imgur.com/1kesG.png)](https://i.stack.imgur.com/1kesG.png) ``` import java.awt.*; // Required import for Frame and Graphics a-> // Method with char-array parameter and Frame return-type new Frame(){ // Create the Frame Graphics G; // Put a Graphics instance on class-level void o(int x,int y,int s){ // Create a shorter method `o` for drawOval G.drawOval(x,y,s,s);} // Draw a circle with width/height `s` with its top-left corner of a virtual surrounding square at position `x,y` void l(int...c){ // Create a shorter method `l` for drawLine G.drawLine(c[0],c[1],c[2],c[3]);} // Draw a line from x1,y1 to x2,y2 public void paint(Graphics g){ // Overwrite the Frame's paint method: G=g; // Save its Graphics parameter in the class-level variable int x=10, // Start the `x` position at 10 (for the left-side border of the Frame) A=20,B=40,C,D=60,E=70,F=80,G=100,H=120,I,J; // Constants to save bytes for(var c:a){ // Loop over the characters `c`: C=x+B;I=x+67;J=x+30; // Set more constants that use variable `x` if(c>32){ // If `c` is NOT a space: o(x,B,F); // Draw a big surrounding circle if(c<58){ // If `c` is a digit: o(J,E,A); // Draw the center circle if(c>53){ // If `c` is larger than '5': o(x+A,D,B); // Draw the larger center circle if(c>56){ // If `c` is '9': l(C,B,C,D);l(x+22,90,x+7,G);l(x+58,90,x+73,G);} // Draw its three small lines else{ // Else (it's '6'/'7'/'8'): if(c>54) // If it's '7' or '8': l(C,B,C,D); // Draw the small top vertical line if(c>55) // If it's '8': l(C,G,C,H);}} // Also draw the small bottom vertical line else{ // Else (`c` is '5' or smaller): if(c>52){ // If `c` is '5': l(C,B,C,E);l(x+2,69,x+31,77);l(x+78,69,x+49,77);l(x+34,87,x+17,112);l(x+46,87,x+63,112);} // Draw its five small lines else if(c==51){ // Else-if `c` is '3': l(C,B,C,E);l(x+32,85,x+7,G);l(x+48,85,x+73,G);} // Draw its three small lines else{ // Else (`c` is '0'/'1'/'2'/'4'): if(c>48) // If `c` is larger than '0': l(C,B,C,E); // Draw the top medium vertical line if(c>49) // If `c` is larger than '1' (thus '2'/'4'): l(C,90,C,H); // Draw the bottom medium vertical line if(c>51){ // If `c` is '4': l(x,F,J,F);l(x+50,F,x+F,F);}}}} // Draw its left/right lines else{ // Else (`c` is a letter): var q=c+""; // Transform the char to a String if("BHUV".contains(q)) // If `c` is one of BHUV: o(J,B,A); // Draw the top small circle if(c>66&c<69|c==87) // If `c` is one of CDW: o(x+D,E,A); // Draw the right small circle if(c<67|c==72) // If `c` is one of ABH: o(J,G,A); // Draw the bottom small circle if(c==87) // If `c` is W: o(x,E,A); // Draw the left small circle if(c>81&c<84|c==F) // If `c` is one of PRS: o(x+50,50,A); // Draw the top-right small circle if(c==76|c==81) // If `c` is L or Q: o(x+50,90,A); // Draw the bottom-right small circle if(c==74|c==83) // If `c` is J or S: o(x+10,90,A); // Draw the bottom-left small circle if("DGIJLPR".contains(q))// If `c` is one of DGIJLPR: l(C,B,C,H); // Draw the large vertical line if(c==71|c==82|c==84) // If `c` is one of GRT: l(C,F,x+F,F); // Draw the right horizontal line if(c==84) // If `c` is T: l(C,F,C,H); // Draw the bottom vertical line if(c==75|c==84) // If `c` is K or T: l(x,F,C,F); // Draw the left horizontal line if("KVWXYZ".contains(q)) // If `c` is one of KVWXYZ: l(C,F,I,52); // Draw the top-right anti-diagonal if("KNVWXY".contains(q)) // If `c` is one of KNVWXY: l(C,F,I,108); // Draw the bottom-right diagonal if("VWXZ".contains(q)) // If `c` is one of VWXZ: l(x+13,108,I,52); // Draw the bottom-left anti-diagonal if("NVWXY".contains(q)) // If `c` is one of NVWXY: l(x+13,52,I,108); // Draw the top-left diagonal if(c>68&c<71){ // If `c` is E or F: l(x+5,D,x+75,D); // Draw the top horizontal line if(c<70) // If `c` is E: l(x+5,G,x+75,G);} // Draw the bottom horizontal line if(c==72|c==77){ // If `c` is H or M: l(x+A,45,x+A,115);l(x+D,45,x+D,115);}}} // Draw the left/right vertical lines x+=F;}} // Increase `x` by 80 (8 units) { // And then in an initializer-block: show();}} // Show the Frame ``` [Answer] # Python 3 + `pygame`, ~~1365~~ ~~1270~~ 1261 bytes Full program that takes a string from stdin, and displays the glyphs in a window. Edit -95 bytes: Now shorter than Java!!! I've lost track of what all I golfed, but theres a hell of a lot of constants in here that replace repeated numbers and tuples, and various other stuff. Also note that the `\x0c`s on line 8 represent literal ASCII formfeeds (codepoint `0C`) Edit: @Steffan pointed out a few mistakes that were breaking code, fixed them. Edit -9 bytes: Take this Java!! Big thanks to [user](https://chat.stackexchange.com/users/468262/user) in chat for helping me golf down the number section ``` from pygame import* from math import* A,c,l,S,d,T,U,V,W,X,Y,Z,I="red",draw.circle,draw.line,Surface,display,(w:=16,4),(x:=32,0),(w,60),(v:=48,60),(x,x),(y:=64,y),(x,y),() def L(C,L,R,E): s=S(Y);c(s,A,X,x,1);_={0:(T,V),1:(U,Z),2:((v,4),W),4:(X,Z),5:((4,w),(60,w)),6:((0,x),(y,x)),7:((4,v),(60,v)),8:((0,x),X),9:(X,(y,x))} for i in C:c(s,A,{1:(v,w),2:(v,v),3:(w,v)}[i],8,1) for i in L:l(s,A,*_[i]) if R:s=transform.rotate(s,R*45).subsurface(*b'\x0c\x0cKK') for i in E:l(s,A,*_[i]) return s def N(n): s=S(Y);exec(3*"c(s,A,X,%i,1);"%(x,8,n//6*w)) for i in range(a:=n%6):z=lambda r:(x+r*sin(b:=2*pi*i/a),x-r*cos(b));l(s,A,z(8+n//6*8),z(x)) return s t=input() s=d.set_mode((y*len(t),y)) for i in range(len(t)):s.blit(L(*{"A":([3],I,1,I),"B":((1,3),I,1,I),"C":([2],I,1,I),"D":([2],I,1,[1]),"E":(I,(5,7),0,I),"F":(I,[5],0,I),"G":(I,(1,9),0,I),"H":((1,3),I,1,(0,2)),"I":(I,[1],0,I),"J":([3],[1],0,I),"K":(I,(4,9),1,[8]),"L":([2],[1],0,I),"M":(I,(0,2),0,I),"N":(I,[1],1,I),"O":(I,I,0,I),"P":([2],[1],0,I),"Q":([2],I,0,I),"R":([1],(1,9),0,I),"S":((1,3),I,0,I),"T":(I,(4,6),0,I),"U":([1],I,1,I),"V":([1],(1,6),1,I),"W":((1,3),(1,6),-1,I),"X":(I,(1,6),1,I),"Y":(I,(1,9),1,I),"Z":(I,[6],1,I),}[t[i]])if t[i].isalpha()else N(int(t[i]))if" "!=t[i]else S(Y),(y*i,0)) d.flip() ``` Some sample outputs: `HELLO WORLD`: [![Matoran glyphs reading "HELLO WORLD"](https://i.stack.imgur.com/jTGSv.png)](https://i.stack.imgur.com/jTGSv.png) `0123456789`: [![Matoran glyphs reading "0123456789"](https://i.stack.imgur.com/yoKOe.png)](https://i.stack.imgur.com/yoKOe.png) `MATORAN TESTING`: [![Matoran glyphs reading "MATORAN TESTING"](https://i.stack.imgur.com/yPPFz.png)](https://i.stack.imgur.com/yPPFz.png) ## Ungolfed and (somewhat) explained version ``` from pygame import* from math import* W="red" def Letter(circles, lines, rot, extra): ## Function that contructs a letter glyph S = Surface((64,64)) ## Surface to draw on draw.circle(S,W,(32,32),32,1) ## Exterior circle for i in circles: ## Draw the small circles draw.circle(S,W,{0:(16,16),1:(48,16),2:(48,48),3:(16,48)}[i],8,1) ## This dict maps 0,1,2,3 to the different circle positions, clockwise from top left. Circle 0 is not used in the golfed version. for i in lines: ## Draw the lines draw.line(S,W,*{0:((16,4),(16,60)),1:((32,0),(32,64)), ## This dict maps numbers to the coords for various line segments. 2:((48,4),(48,60)),3:((32,0),(32,32)),4:((32,32),(32,64)), ## 0,1,2 are full length vertical lines, 4,5 are half length vertical lines 5:((4,16),(60,16)),6:((0,32),(64,32)),7:((4,48),(60,48)), ## 5,6,7 are full length horizontal lines, 8,9 are half length horizontal lines 8:((0,32),(32,32)),9:((32,32),(64,32))}[i]) ## 3 and 8 are not used in the golfed version if rot: ## rotate the glyph 45 degrees, if necessary S=transform.rotate(S,R*45).subsurface((12,12,75,75)) ## the R*45 is used in the golfed version to sometimes rotate the other direction, which allowed the removal of some circle/line keys from the dicts for i in extra: ## draw the extra line segments necessary, names the same as above for consistency draw.line(S,W,*{0:((16,4),(16,60)),1:((32,0),(32,64)), 2:((48,4),(48,60)),8:((0,32),(32,32))}[i]) return S ## return the surface def Number(n): ## contructs a number glyph from its value S = Surface((64,64)) ## Contruct a surface to draw on draw.circle(S,W,(32,32),32,1) ## Exterior circle draw.circle(S,W,(32,32),8,1) ## Central circle draw.circle(S,W,(32,32),16*(n//6),1) ## Larger central circle, radius 0 if unneeded (radius 0 == nothing drawn) for i in range(n%6): ## draw the spokes a,r=(2*pi*i)/(n%6),8+n//6*8 ## current angle and the radius of the central circle draw.line(S,W, ## draw the line, with appropriate endpoints (32+sin(a)*r,32-cos(a)*r), (32+sin(a)*32,32-cos(a)*32) ) return S ## return the surface T=input().upper() ## take input from stdin, .upper() to make ungolfed version more friendly s=display.set_mode((64*len(T),64)) ## setup the display wide enough for the input text for i in range(len(T)): ## loop through the characters s.blit( ## blit (copy) the glyph surface onto the display Letter(*{"A":((3,),(),1,()),"B":((1,3),(),1,()),"C":((2,),(),1,()), ## if its a letter, this (somewhat scary) dict maps "D":((2,),(),1,(1,)),"E":((),(5,7),0,()),"F":((),(5,),0,()), ## the letter to the correct args for Letter() "G":((),(1,9),0,()),"H":((1,3),(),1,(0,2)),"I":((),(1,),0,()), "J":((3,),(1,),0,()),"K":((),(4,9),1,(8,)),"L":((2,),(1,),0,()), "M":((),(0,2),0,()),"N":((),(1,),1,()),"O":((),(),0,()), "P":((1,),(1,),0,()),"Q":((2,),(),0,()), "R":((1,),(1,9),0,()),"S":((1,3),(),0,()),"T":((),(4,6),0,()), "U":((1,),(),1,()),"V":((1,),(1,6),1,()), "W":((0,2),(1,6),1,()),"X":((),(1,6),1,()), "Y":((),(1,9),1,()),"Z":((),(6,),1,()),}[T[i]]) if T[i].isalpha() ## only send the char to Letter() if it is a letter else Number(int(T[i])) ## otherwise send it to Number() as an int if T[i]!=" " ## but if its a space, don't send it to either function else Surface((64,64)), ## instead just make a new, empty surface (64*i,0)) ## place at the right position display.flip() ## render all chars ``` [Answer] # BBC BASIC, ~~395~~ 385 bytes ``` I.s$ F.i=1TOLENs$c=ASCM.s$,i,1)MOD64IFc=32N. ORIGIN80*i,80m=ASCM."CBDFFDFRFATETsDFDF?UDxhxsI",c,1)*95+ASCM."!~R8Kg\SJ?bs9?dD.VS{bN|PEu",c,1)t=m MOD2*20n=8m /=2v=t*7/4w=40-t IFc>47n=c MOD6+1E-9m=728+(n<1) a=PI*2/n F.j=0TOa*n S.a:u=m MOD3m/=3y=COSj:x=SINj IFu<1CIRCLEx*28,y*28,10 IFu>1L.x*t-y*v,y*t+x*v,x*w+y*v,y*w-x*v N.F.k=5-c DIV27*2TO5j=k MOD5+1MOVE0,0PLOT155-j MOD2*10,0,40>>j/2N.N. ``` Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> Keyword abbreviations expand on loading into IDE. **Explanation** For letters, each of the 8 positions from N through E, S and W to NW can be either empty space, a line or a small circle. Additionally, the lines within each letter are usually radial, but for certain letters `EFHM` they are at right angles. The information for each letter is stored as an 8 digit ternary number, which is multiplied by 2 and the final bit indicates whether lines are radial or at right angles. Encoding is as follows to minimise the range of codes (there is never a circle in the NW position) ``` MAIN ENCODING LINE DIRECTION ENCODING 0 = circle 0 = radial 1 = space 1 = at right angles to radial 2 = line ``` For digits, the number of spokes is reduced to the ASCII code mod 6, and it is assumed that all spaces are lines with the constant `728`. BBC BASIC `FOR` loops are always excecuted at least once, so where the ASCII code mod 6 is zero, the plotting of the first spoke is suppressed by subtracting 1 from the constant. `(n<1)` evaluates to TRUE which is represented in BBC BASIC by `-1`. A radius of 40 was selected for each character. This is because of the well known approximations `40*SIN45=28` and `40*SIN60=35` **Ungolfed code** ``` INPUT s$ :REM input from stdin FOR i=1 TO LEN(s$) :REM for each character in input c=ASC(MID$(s$,i,1))MOD64 :REM convert to ASCII code MOD 64 so that "A"=1 IF c=32NEXT :REM if it is a space do nothing ORIGIN 80*i,80 :REM move graphics origin to the cente of the current letter m=ASC(MID$("CBDFFDFRFATETsDFDF?UDxhxsI",c,1))*95+ASC(MID$("!~R8Kg\SJ?bs9?dD.VS{bN|PEu",c,1)) t=m MOD2*20 :REM use the 2 magic strings to lookup the letter data m m/=2 :REM t indicates if lines are radial. Extract t and divide by 2 v=t*7/4 :REM for nonradial lines, tangential offset of 20*7/4=35 is needed w=40-t :REM radial offest of line endpoint is 40 for radial, 20 for nonradial n=8 :REM 8 spokes for letters IF c>47 n=c MOD 6+1E-9:m=728+(n<1) :REM if character is a digit (c>47), there are c MOD6 spokes a=PI*2/n :REM calculate angle between spokes (+1E-9 on previous line avoids division by 0) FOR j =0 TO a*n STEP a :REM iterate through spokes u=m MOD 3: m/=3 :REM extract data u for current spoke then divide m by 3 for the next one y=COSj:x=SINj :REM calculate (x,y) vector for radial direction of current spoke IF u<1 CIRCLE x*28,y*28,10 :REM if u=0 draw a circle instead of a spoke IF u>1 LINE x*t-y*v,y*t+x*v,x*w+y*v,y*w-x*v :REM if u=2 draw a spoke starting at radius t=0 and ending at radius w=40 NEXT :REM if t=20 draw a nonradial line instead from -v to v passing through radius t=w=20 FOR k=5-c DIV27*2TO5 :REM iterate through circles: c>=54 k starts at 1; c>=27 k starts at 3, c<2 k starts at 5 j=k MOD 5+1 :REM order of circles: 1+1=2, 2+1=3 (digits 6789); 3+1=4 4+1=5 (all digits); 0+1=1 (all symbols) MOVE 0,0:PLOT 155-j MOD2*10,0,40>>j/2 :REM clear the background for even number circles, draw the circle for odd number circles NEXT :REM radius 40>>(2/2 or 3/2)=20, 40>>(4/2 or 5/2)=10, 40>>(1/2) = 40 NEXT :REM repeat for next character ``` [![enter image description here](https://i.stack.imgur.com/YTFYH.png)](https://i.stack.imgur.com/YTFYH.png) [Answer] # HTML + JS + SVG, ~~577~~ ~~575~~ ~~571~~ ~~552~~ ~~545~~ ~~544~~ ~~522~~ ~~511~~ ~~497~~ ~~507~~ 503 bytes *On my browser (Firefox 100 on Linux), the 0 and 6 used to render correctly, because an invalid `transform` hid the SVG elements. A few months later, I'm adding 10 bytes, since I can't seem to reproduce that anymore.* ``` t=>[...t,0].map(c=>document.body.innerHTML+=c?`<svg viewBox=-4,-4,8,8 width=50 fill=#fff stroke=#000 stroke-width=.1>`+(c>" "&&['D',..."Y Y] _ _` PT T J` RVY] ` Z` IKN X` RV c = `^ X J^` Z^ Lb ] ]ac [_ac ac Ic a".split` `[parseInt(c,36)-10]||(c%6?'()*+,':'')+(c>5?'BA':'A')].map(u=>`<path d=${`M57A5,57,177,5A5,5777,5784 M6,2H-6 M2,1939184v484`.replace(/./g,k=>[x=(y=u.charCodeAt())&7,3.4,',0',' M0,-4v','A1,1,0,0,0,2,'][k-5]||k).split` `[y>>3&7]} transform=rotate(${y<64?x*360/(c%6):45*x}) />`)):'<p>') ``` Or 493 bytes if you don't care about separating the outputs of different calls with `<p>`. (Replacing the page contents is longer.) ``` t=>[...t].map(c=>document.body.innerHTML+=`<svg viewBox=-4,-4,8,8 width=50 fill=#fff stroke=#000 stroke-width=.1>`+(c>" "&&['D',..."Y Y] _ _` PT T J` RVY] ` Z` IKN X` RV c = `^ X J^` Z^ Lb ] ]ac [_ac ac Ic a".split` `[parseInt(c,36)-10]||(c%6?'()*+,':'')+(c>5?'BA':'A')].map(u=>`<path d=${`M57A5,57,177,5A5,5777,5784 M6,2H-6 M2,1939184v484`.replace(/./g,k=>[x=(y=u.charCodeAt())&7,3.4,',0',' M0,-4v','A1,1,0,0,0,2,'][k-5]||k).split` `[y>>3&7]} transform=rotate(${y<64?x*360/(c%6):45*x}) />`))) ``` Or 482 bytes if you don't care about the colors at all: ``` t=>[...t].map(c=>document.body.innerHTML+=`<svg viewBox=-4,-4,8,8 width=50 stroke=red stroke-width=.1>`+(c>" "&&['D',..."Y Y] _ _` PT T J` RVY] ` Z` IKN X` RV c = `^ X J^` Z^ Lb ] ]ac [_ac ac Ic a".split` `[parseInt(c,36)-10]||(c%6?'()*+,':'')+(c>5?'BA':'A')].map(u=>`<path d=${`M57A5,57,177,5A5,5777,5784 M6,2H-6 M2,1939184v484`.replace(/./g,k=>[x=(y=u.charCodeAt())&7,3.4,',0',' M0,-4v','A1,1,0,0,0,2,'][k-5]||k).split` `[y>>3&7]} transform=rotate(${y<64?x*360/(c%6):45*x}) />`))) ``` Apparently, I had a very similar idea to @Matthew Jensen about SVG being *much* shorter than the other options. However, I took a pretty different approach. I think this is finally getting pretty close to optimal with my current approach. If only I had a language with JS semantics but Python builtins, like `int()`, `str.translate`, `oct`, `str[:]`, … The output may be wrapped on small screens or if your Stack Snippet is not fullscreen. (You can reduce `width=50` to fix this.) ``` renderMatoran = t=>[...t,0].map(c=>document.body.innerHTML+=c?`<svg viewBox=-4,-4,8,8 width=50 fill=#fff stroke=#000 stroke-width=.1>`+(c>" "&&['D',..."Y Y] _ _` PT T J` RVY] ` Z` IKN X` RV c = `^ X J^` Z^ Lb ] ]ac [_ac ac Ic a".split` `[parseInt(c,36)-10]||(c%6?'()*+,':'')+(c>5?'BA':'A')].map(u=>`<path d=${`M57A5,57,177,5A5,5777,5784 M6,2H-6 M2,1939184v484`.replace(/./g,k=>[x=(y=u.charCodeAt())&7,3.4,',0',' M0,-4v','A1,1,0,0,0,2,'][k-5]||k).split` `[y>>3&7]} transform=rotate(${y<64?x*360/(c%6):45*x}) />`)):'<p>') for (const text of ["ABCDEFGHIJ","KLMNOPQRST", "UVWXYZ", "0123456789", "CODE GOLF 101"]) { renderMatoran(text); } ``` ### Explanation ``` t => [...t, 0].map(c => /* for each char c (plus terminator) ... */ document.body.innerHTML += /* the HTML parser will enjoy this... */ c ? /* handle terminator */ `<svg viewBox=-4,-4,8,8 /* we want nice and short coords */ width=50 /* specify some width so the browser */ /* puts our svgs next to each other */ fill=#fff stroke=#000 stroke-width=.1 /* much cheaper than big coords */ >` + (c > " " && /* yield false if space (gets dumped in the SVG, */ /* but it does not care about stray strings) */ ['D', /* everything has a big circle */ ... /* convert rest to array elements */ "Y Y] _ _` PT T J` RVY] ` Z` IKN X` RV c = `^ X J^` Z^ Lb ] ]ac [_ac ac Ic a" .split` `[parseInt(c,36)-10] /* for letters: take corresponding item */ /* from the data string */ || `()*+,${c>5?'B':''}A` /* for numbers: generate string with */ /* 5 spokes and 1-2 circles */ ].map(u => /* for each char u in the instructions... */ `<path d=${ /* svg path black magic */ `M57A5,57,177,5A5,5777,5784 M6,2H-6 M2,1939184v484` .replace(/./g, k => /* map each character k to... */ [ x = (y = u.charCodeAt()) & 7, /* 5 -> instruction arg */ 3.4, /* 6 -> approx. 2*sqrt(3) */ ',0', /* 7 */ ' M0,-4v', /* 8 */ 'A1,1,0,0,0,2,' /* 9 */ ][k-5] || k /* everything else to itself */ ).split` `[y>>3&7] /* grab correct instruction */ } transform=rotate(${ y<64 ? x*360/(c%6) /* rotation for spokes */ : 45*x /* rotation for everything else */ }) />` )) /* just dump the array in the string, the parser will eat the */ /* useless commas :) */ : '<p>' /* make sure each call goes on its own line */ ) ``` [Answer] # JavaScript + HTML, 582 bytes -many, many bytes thanks to tsh! Changed it to modify `document.body` to better match [this other JS + HTML answer](https://codegolf.stackexchange.com/a/246443/87728). ``` s=>document.body.innerHTML+=`<svg viewBox=5,-5,${[c,l]=['<circle r=cx=cy=','<line y2=y1=x2=x1='].map(n=>(...a)=>n[$](/=/g,_=>`=${a.pop()} `)+`transform=rotate(${R*45}) />`),s.length}0,10 stroke=red stroke-width=.2>`+s.toLowerCase()[$='replace'](/./g,x=>'<g transform=translate(10)>'+(x>' '&&c(R=0,4)+(1/x?[...Array(L=x%6)].map(_=>(R+=8/L,l(-4)))+[x>5&&c(2)]+c(1):'aC1bC1C5cC7dC7LeE2E6fE6gI6LhC1C5E4EiLjC2LkI2I5I7lC0LmE4EnL3pC6LqCrC6I6LsC2C6tL2IuC5vC5L1L3wC3C7L1L3xL1L3yL3I5zL1'.match(x+'([0-Z]+)')?.[1][$](/..?/g,([z,r])=>(R=r,{C:c(2,2,1),L:l(-4,4),I:l(4),E:l(2,2,-3.5,3.5)}[z]))))) ``` ``` f= s=>document.body.innerHTML+=`<svg viewBox=5,-5,${[c,l]=['<circle r=cx=cy=','<line y2=y1=x2=x1='].map(n=>(...a)=>n[$](/=/g,_=>`=${a.pop()} `)+`transform=rotate(${R*45}) />`),s.length}0,10 stroke=red stroke-width=.2>`+s.toLowerCase()[$='replace'](/./g,x=>'<g transform=translate(10)>'+(x>' '&&c(R=0,4)+(1/x?[...Array(L=x%6)].map(_=>(R+=8/L,l(-4)))+[x>5&&c(2)]+c(1):'aC1bC1C5cC7dC7LeE2E6fE6gI6LhC1C5E4EiLjC2LkI2I5I7lC0LmE4EnL3pC6LqCrC6I6LsC2C6tL2IuC5vC5L1L3wC3C7L1L3xL1L3yL3I5zL1'.match(x+'([0-Z]+)')?.[1][$](/..?/g,([z,r])=>(R=r,{C:c(2,2,1),L:l(-4,4),I:l(4),E:l(2,2,-3.5,3.5)}[z]))))) ; [ 'Hello World', 'Matthew Jensen', 'Matoran Alphabet', 'ABCDEFGHIJ', 'KLMNOPQRST', 'UVWXYZ', '0123456789', ].forEach(text => { f(text); //document.body.appendChild(document.createElement('div')).innerHTML = f(text); }); ``` ``` svg { background-color: black; height: 64px; } ``` Explained a bit ``` s => document.body.innerHTML += `<svg viewBox=5,-5,${ // add a new SVG element to doc body [c, l] = [ // define function to generate circle and line '<circle r=cx=cy=', '<line y2=y1=x2=x1=' ].map(n => (...a) => // map each above string to function to assign args (reverse order) n[$ /* = 'replace' */ ](/=/g, _ => `=${a.pop()} `) + `transform=rotate(${R * 45}) />`), // apply 1/8 rotations by global R s.length }0,10 stroke=red stroke-width=.2>` + s.toLowerCase()[$ = 'replace'](/./g, x => // replace each char with its svg '<g transform=translate(10)>' + // begin new group (nested in previous char, idea from tsh!) (x > ' ' && c(R = 0, 4) + // if not a space, draw the large circle (1 / x ? // if char is number [...Array(L = x % 6)] // draw line segments .map(_ => (R += 8 / L, l(-4))) + [x > 5 && c(2)] + // draw r=2 circle if >5 c(1) // draw r=1 circle : // otherwise char is letter 'aC1bC1C5cC7dC7LeE2E6fE6gI6LhC1C5E4EiLjC2LkI2I5I7lC0LmE4EnL3pC6LqCrC6I6LsC2C6tL2IuC5vC5L1L3wC3C7L1L3xL1L3yL3I5zL1' .match(x + '([0-Z]+)')?.[1] // find code for letter [$ /* = 'replace' */ ](/..?/g, ([z, r]) => ( // for each instruction [shape, rotation] R = r, // set global rotation to r { // look up instruction C: c(2, 2, 1), L: l(-4, 4), I: l(4), E: l(2, 2, -3.5, 3.5) }[z] ) ) ) ) ) ``` [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0 -lF`, 1017 bytes ``` sub d{unpack"B*",pop}sub a{$A[$_].="@_"eq''?0 x8:("@_"=~/.{17}/g)[$_]for 0..16}sub z{0 x pop}a{O,($x=d"........\$............`.0........0...."),A,$a=$x|z(194).($C=d"....D.\".."),U,$u=$x|z(24).$C,B,$b=$a|$u,C,$c=$x|z(114).$C,I,$i=$x|z(8).($l=d"..@. .............")|0 x($-=144).$l,D,$c|$i,F,$f=$x|z(70).($h=1x13),E,$f|z(206).$h,G,$g=$i|0 x$-.($H=1x9),M,$m=$x|z(38).($k=(1 .z 16)x13)|z(46).$k,H,$m|$b,J,$i|z(173).$C,K,$x|z(64).($y=d".."x6)|0 x$-.($Y=d".. ........ ")|z(135).$H,Q,$q=$x|z(181).$C,L,$i|$q,N,$n=$x|z(54).$Y|0 x$-.$Y,P,$p=$i|z(45).$C,R,$p|$g,S,$x|z(173).$C|z(45).$C,T,$g=$x|0 x$-.$H|z(135).$H|0 x$-.$l,Y,$z=$n|z(64).$y,X,$X=$z|0 x$-.$y,V,$X|$u,W,$X|z(104).$C|z(114).$C,Z,$x|z(64).$y|0 x$-.$y,0,$Z=$x|z(109).$C,1,$O=$Z|z(25).($L=d"..@. ...."),2,$T=$O|z(195).$L,3,$O|(z(174).d"...0"),4,$T|z(137).1111100000 x2,5,$O|(z(86).d"......`.0D......D..0."),6,$s=$x|(z(74).d".P....QF(..Q....P."),7,$S=$s|(z(25).($w=d"..@. ")),8,$S|z(229).$w,9,$S|z(180).(z(9).11)x2}->{$_}for@F;$-=y/ //c;say"P1 ",17*$-+8*(@F-$-)," 17 @A" ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDczNzUgNjIyMCA2NDdiIDc1NmUgNzA2MSA2MzZiIDIyNDIgMmEyMiAgc3ViIGR7dW5wYWNrXCJCKlwiXG4wMDAwMDAxMDogMmM3MCA2ZjcwIDdkNzMgNzU2MiAyMDYxIDdiMjQgNDE1YiAyNDVmICAscG9wfXN1YiBheyRBWyRfXG4wMDAwMDAyMDogNWQyZSAzZDIyIDQwNWYgMjI2NSA3MTI3IDI3M2YgMzAyMCA3ODM4ICBdLj1cIkBfXCJlcScnPzAgeDhcbjAwMDAwMDMwOiAzYTI4IDIyNDAgNWYyMiAzZDdlIDJmMmUgN2IzMSAzNzdkIDJmNjcgIDooXCJAX1wiPX4vLnsxN30vZ1xuMDAwMDAwNDA6IDI5NWIgMjQ1ZiA1ZDY2IDZmNzIgMjAzMCAyZTJlIDMxMzYgN2Q3MyAgKVskX11mb3IgMC4uMTZ9c1xuMDAwMDAwNTA6IDc1NjIgMjA3YSA3YjMwIDIwNzggMjA3MCA2ZjcwIDdkNjEgN2I0ZiAgdWIgenswIHggcG9wfWF7T1xuMDAwMDAwNjA6IDJjMjggMjQ3OCAzZDY0IDIyMDcgZjAwYyAwNjA4IDAwODggMDA1YyAgLCgkeD1kXCIuLi4uLi4uLlxcXG4wMDAwMDA3MDogMjQwMCAxNDAwIDA2MDAgMDMwMCAwMTgwIDAwYzAgMDA2MCAwMDMwICAkLi4uLi4uLi4uLi4uYC4wXG4wMDAwMDA4MDogMDAxNCAwMDEyIDAwMDggODAwOCAzMDE4IDA3ZjAgMDAyMiAyOTJjICAuLi4uLi4uLjAuLi4uXCIpLFxuMDAwMDAwOTA6IDQxMmMgMjQ2MSAzZDI0IDc4N2MgN2EyOCAzMTM5IDM0MjkgMmUyOCAgQSwkYT0keHx6KDE5NCkuKFxuMDAwMDAwYTA6IDI0NDMgM2Q2NCAyMmUwIDAwODggMDA0NCAwMDVjIDIyMDAgMGUyMiAgJEM9ZFwiLi4uLkQuXFxcIi4uXCJcbjAwMDAwMGIwOiAyOTJjIDU1MmMgMjQ3NSAzZDI0IDc4N2MgN2EyOCAzMjM0IDI5MmUgICksVSwkdT0keHx6KDI0KS5cbjAwMDAwMGMwOiAyNDQzIDJjNDIgMmMyNCA2MjNkIDI0NjEgN2MyNCA3NTJjIDQzMmMgICRDLEIsJGI9JGF8JHUsQyxcbjAwMDAwMGQwOiAyNDYzIDNkMjQgNzg3YyA3YTI4IDMxMzEgMzQyOSAyZTI0IDQzMmMgICRjPSR4fHooMTE0KS4kQyxcbjAwMDAwMGUwOiA0OTJjIDI0NjkgM2QyNCA3ODdjIDdhMjggMzgyOSAyZTI4IDI0NmMgIEksJGk9JHh8eig4KS4oJGxcbjAwMDAwMGYwOiAzZDY0IDIyODAgMDA0MCAwMDIwIDAwMTAgMDAwOCAwMDA0IDAwMDIgID1kXCIuLkAuIC4uLi4uLi4uXG4wMDAwMDEwMDogMDAwMSAwMDAwIDgwMjIgMjk3YyAzMDIwIDc4MjggMjQyZCAzZDMxICAuLi4uLlwiKXwwIHgoJC09MVxuMDAwMDAxMTA6IDM0MzQgMjkyZSAyNDZjIDJjNDQgMmMyNCA2MzdjIDI0NjkgMmM0NiAgNDQpLiRsLEQsJGN8JGksRlxuMDAwMDAxMjA6IDJjMjQgNjYzZCAyNDc4IDdjN2EgMjgzNyAzMDI5IDJlMjggMjQ2OCAgLCRmPSR4fHooNzApLigkaFxuMDAwMDAxMzA6IDNkMzEgNzgzMSAzMzI5IDJjNDUgMmMyNCA2NjdjIDdhMjggMzIzMCAgPTF4MTMpLEUsJGZ8eigyMFxuMDAwMDAxNDA6IDM2MjkgMmUyNCA2ODJjIDQ3MmMgMjQ2NyAzZDI0IDY5N2MgMzAyMCAgNikuJGgsRywkZz0kaXwwIFxuMDAwMDAxNTA6IDc4MjQgMmQyZSAyODI0IDQ4M2QgMzE3OCAzOTI5IDJjNGQgMmMyNCAgeCQtLigkSD0xeDkpLE0sJFxuMDAwMDAxNjA6IDZkM2QgMjQ3OCA3YzdhIDI4MzMgMzgyOSAyZTI4IDI0NmIgM2QyOCAgbT0keHx6KDM4KS4oJGs9KFxuMDAwMDAxNzA6IDMxMjAgMmU3YSAyMDMxIDM2MjkgNzgzMSAzMzI5IDdjN2EgMjgzNCAgMSAueiAxNil4MTMpfHooNFxuMDAwMDAxODA6IDM2MjkgMmUyNCA2YjJjIDQ4MmMgMjQ2ZCA3YzI0IDYyMmMgNGEyYyAgNikuJGssSCwkbXwkYixKLFxuMDAwMDAxOTA6IDI0NjkgN2M3YSAyODMxIDM3MzMgMjkyZSAyNDQzIDJjNGIgMmMyNCAgJGl8eigxNzMpLiRDLEssJFxuMDAwMDAxYTA6IDc4N2MgN2EyOCAzNjM0IDI5MmUgMjgyNCA3OTNkIDY0MjIgODAwMCAgeHx6KDY0KS4oJHk9ZFwiLi5cbjAwMDAwMWIwOiAyMjc4IDM2MjkgN2MzMCAyMDc4IDI0MmQgMmUyOCAyNDU5IDNkNjQgIFwieDYpfDAgeCQtLigkWT1kXG4wMDAwMDFjMDogMjI4MCAwMDIwIDAwMDggMDAwMiAwMDAwIDgwMDAgMjAyMiAyOTdjICBcIi4uIC4uLi4uLi4uIFwiKXxcbjAwMDAwMWQwOiA3YTI4IDMxMzMgMzUyOSAyZTI0IDQ4MmMgNTEyYyAyNDcxIDNkMjQgIHooMTM1KS4kSCxRLCRxPSRcbjAwMDAwMWUwOiA3ODdjIDdhMjggMzEzOCAzMTI5IDJlMjQgNDMyYyA0YzJjIDI0NjkgIHh8eigxODEpLiRDLEwsJGlcbjAwMDAwMWYwOiA3YzI0IDcxMmMgNGUyYyAyNDZlIDNkMjQgNzg3YyA3YTI4IDM1MzQgIHwkcSxOLCRuPSR4fHooNTRcbjAwMDAwMjAwOiAyOTJlIDI0NTkgN2MzMCAyMDc4IDI0MmQgMmUyNCA1OTJjIDUwMmMgICkuJFl8MCB4JC0uJFksUCxcbjAwMDAwMjEwOiAyNDcwIDNkMjQgNjk3YyA3YTI4IDM0MzUgMjkyZSAyNDQzIDJjNTIgICRwPSRpfHooNDUpLiRDLFJcbjAwMDAwMjIwOiAyYzI0IDcwN2MgMjQ2NyAyYzUzIDJjMjQgNzg3YyA3YTI4IDMxMzcgICwkcHwkZyxTLCR4fHooMTdcbjAwMDAwMjMwOiAzMzI5IDJlMjQgNDM3YyA3YTI4IDM0MzUgMjkyZSAyNDQzIDJjNTQgIDMpLiRDfHooNDUpLiRDLFRcbjAwMDAwMjQwOiAyYzI0IDY3M2QgMjQ3OCA3YzMwIDIwNzggMjQyZCAyZTI0IDQ4N2MgICwkZz0keHwwIHgkLS4kSHxcbjAwMDAwMjUwOiA3YTI4IDMxMzMgMzUyOSAyZTI0IDQ4N2MgMzAyMCA3ODI0IDJkMmUgIHooMTM1KS4kSHwwIHgkLS5cbjAwMDAwMjYwOiAyNDZjIDJjNTkgMmMyNCA3YTNkIDI0NmUgN2M3YSAyODM2IDM0MjkgICRsLFksJHo9JG58eig2NClcbjAwMDAwMjcwOiAyZTI0IDc5MmMgNTgyYyAyNDU4IDNkMjQgN2E3YyAzMDIwIDc4MjQgIC4keSxYLCRYPSR6fDAgeCRcbjAwMDAwMjgwOiAyZDJlIDI0NzkgMmM1NiAyYzI0IDU4N2MgMjQ3NSAyYzU3IDJjMjQgIC0uJHksViwkWHwkdSxXLCRcbjAwMDAwMjkwOiA1ODdjIDdhMjggMzEzMCAzNDI5IDJlMjQgNDM3YyA3YTI4IDMxMzEgIFh8eigxMDQpLiRDfHooMTFcbjAwMDAwMmEwOiAzNDI5IDJlMjQgNDMyYyA1YTJjIDI0NzggN2M3YSAyODM2IDM0MjkgIDQpLiRDLFosJHh8eig2NClcbjAwMDAwMmIwOiAyZTI0IDc5N2MgMzAyMCA3ODI0IDJkMmUgMjQ3OSAyYzMwIDJjMjQgIC4keXwwIHgkLS4keSwwLCRcbjAwMDAwMmMwOiA1YTNkIDI0NzggN2M3YSAyODMxIDMwMzkgMjkyZSAyNDQzIDJjMzEgIFo9JHh8eigxMDkpLiRDLDFcbjAwMDAwMmQwOiAyYzI0IDRmM2QgMjQ1YSA3YzdhIDI4MzIgMzUyOSAyZTI4IDI0NGMgICwkTz0kWnx6KDI1KS4oJExcbjAwMDAwMmUwOiAzZDY0IDIyODAgMDA0MCAwMDIwIDAwMTAgMDAwOCAyMjI5IDJjMzIgID1kXCIuLkAuIC4uLi5cIiksMlxuMDAwMDAyZjA6IDJjMjQgNTQzZCAyNDRmIDdjN2EgMjgzMSAzOTM1IDI5MmUgMjQ0YyAgLCRUPSRPfHooMTk1KS4kTFxuMDAwMDAzMDA6IDJjMzMgMmMyNCA0ZjdjIDI4N2EgMjgzMSAzNzM0IDI5MmUgNjQyMiAgLDMsJE98KHooMTc0KS5kXCJcbjAwMDAwMzEwOiBjMTgxIDgwMzAgMjIyOSAyYzM0IDJjMjQgNTQ3YyA3YTI4IDMxMzMgIC4uLjBcIiksNCwkVHx6KDEzXG4wMDAwMDMyMDogMzcyOSAyZTMxIDMxMzEgMzEzMSAzMDMwIDMwMzAgMzAyMCA3ODMyICA3KS4xMTExMTAwMDAwIHgyXG4wMDAwMDMzMDogMmMzNSAyYzI0IDRmN2MgMjg3YSAyODM4IDM2MjkgMmU2NCAyMmMxICAsNSwkT3woeig4NikuZFwiLlxuMDAwMDAzNDA6IDA3OTkgY2NjMyAxODYwIDg4MzAgNDQxOCAxYzBjIDExMDUgMTA0NCAgLi4uLi5gLjBELi4uLi4uRFxuMDAwMDAzNTA6IDkwMTIgMzAwNCAyMjI5IDJjMzYgMmMyNCA3MzNkIDI0NzggN2MyOCAgLi4wLlwiKSw2LCRzPSR4fChcbjAwMDAwMzYwOiA3YTI4IDM3MzQgMjkyZSA2NDIyIGY4NTAgODIxOCA5YzhjIDUxNDYgIHooNzQpLmRcIi5QLi4uLlFGXG4wMDAwMDM3MDogMjhhMyAxNDUxIDg5YzggYzIwOCA1MGY4IDIyMjkgMmMzNyAyYzI0ICAoLi5RLi4uLlAuXCIpLDcsJFxuMDAwMDAzODA6IDUzM2QgMjQ3MyA3YzI4IDdhMjggMzIzNSAyOTJlIDI4MjQgNzczZCAgUz0kc3woeigyNSkuKCR3PVxuMDAwMDAzOTA6IDY0MjIgODAwMCA0MDAwIDIwMjIgMjkyOSAyYzM4IDJjMjQgNTM3YyAgZFwiLi5ALiBcIikpLDgsJFN8XG4wMDAwMDNhMDogN2EyOCAzMjMyIDM5MjkgMmUyNCA3NzJjIDM5MmMgMjQ1MyA3YzdhICB6KDIyOSkuJHcsOSwkU3x6XG4wMDAwMDNiMDogMjgzMSAzODMwIDI5MmUgMjg3YSAyODM5IDI5MmUgMzEzMSAyOTc4ICAoMTgwKS4oeig5KS4xMSl4XG4wMDAwMDNjMDogMzI3ZCAyZDNlIDdiMjQgNWY3ZCA2NjZmIDcyNDAgNDYzYiAyNDJkICAyfS0+eyRffWZvckBGOyQtXG4wMDAwMDNkMDogM2Q3OSAyZjIwIDJmMmYgNjMzYiA3MzYxIDc5MjIgNTAzMSAyMDIyICA9eS8gLy9jO3NheVwiUDEgXCJcbjAwMDAwM2UwOiAyYzMxIDM3MmEgMjQyZCAyYjM4IDJhMjggNDA0NiAyZDI0IDJkMjkgICwxNyokLSs4KihARi0kLSlcbjAwMDAwM2YwOiAyYzIyIDIwMzEgMzcyMCA0MDQxIDIyICAgICAgICAgICAgICAgICAgICxcIiAxNyBAQVwiXG4iLCJhcmdzIjoiLU01LjEwLjBcbi1sRiIsImlucHV0IjoiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVogMDEyMzQ1Njc4OSIsIm1pbWUiOiJpbWFnZS94LXBvcnRhYmxlLWJpdG1hcCJ9) ## Explanation The main functionality of this answer utilises a lookup table to store information about each letter we translate, this lookup table is built up from previous letters and augmented using stringwise-OR operations. We start with `O` which is just a circle. Using the PBM format, this is stored as: ``` 00000111111100000 00011000000011000 00100000000000100 01000000000000010 01000000000000010 10000000000000001 10000000000000001 10000000000000001 10000000000000001 10000000000000001 10000000000000001 10000000000000001 01000000000000010 01000000000000010 00100000000000100 00011000000011000 00000111111100000 ``` From here, `A` (for example) is augmented by ORing the string: ``` 1110000000000000 10001000000000000 10001000000000000 10001000000000000 01110 ``` with a specific number of leading `0`s (194 for `A`), so as to place this at the right position. The same technique is used to build the other letters and numbers, sometimes using the result of ORing two other letters to get the required output. The binary strings are stored using Perl's `pack` functionality and the data is output by repeatedly appending each required line from the letters to the list `@A`'s indices 0..16. All the glyphs are hand-made by eye, so please shout if this is not to your liking! [Answer] # [C (GCC)](https://gcc.gnu.org), 871 bytes ``` #define Q(X,Y)(r=(X)*(X)+(Y)*(Y)) #define S(M)(y&M?-1:1) #define C;for(y=1;y<16;y*=2)c|=x&y<< #define A labs int T[]={0,1,3,1,15,1,0,1,3,1,8192,12288,32768,32771,768,256,11,15360,3,131075,164,65539,3072,48,0,262147,65536,262155,393216,14,4096,4336,49392,240,176,192};main(i,v,j,k,x,r,y,n,c,w)char**v;{w=90*strlen(v[1]);printf("P5 %d %d 1 ",w,79);for(i=-40;i++<39;)for(j=-1;++j<w;putchar(c)){c=0;k=j%90-40;n=v[1][j/90];if(n-32){c|=Q(i,k)<1600&r>1400;x=T[n-48-7*(n>64)]C 0&&A(y&3?k:i)<2&k<40&(y&3?i:k)*S(5)>=0 C 4&&A(k)<28&A(i+k*S(3))<2&k*S(5)>=0 C 8&&A((y&3?i:k)-20*S(5))<2&A(i)<34&A(k)<34 C 12&&Q((y&3?i:k)-30*S(5),y&3?k:i)<99&r>63 C 16&&Q(i+20*S(3),k+20*S(5))<99&r>63;if(n<58){for(y=2;A(n-54)==3&&y--;)c|=A(1.73*i+k*S(y))<3&i>0&A(k)<34;for(y=2;n==53&&y--;)c|=A(3.08*i+k*S(y))<5&i<0&A(k)<39,c|=A(.73*i-k*S(y))<2&i>0&A(k)<23;if(n>53)c=(c|r<399)&r>323;c=(c|r<99)&r>63;}}}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZPbUtswEIYvesdTeNLBI9ky1ckHIStMmp5bWlJoS5rJdKhJqGPqMiYQPIEn6Q03PFT7NF05B6jHluzd7_-1kqXfd9m3kyy7vb27mI6D5O-jk8fHo3FejpweOiR9jCqDDrEHj4_60Pcx3lgR-2gXo9rd3QnYNrsPd_X4V4Vqw3SdskjXnuE4uzZXbp2ma6jjnB59P9_Iy6lzMBiaOSWMCHhYCM3qI2GKE8Z5khDB46hpY0bsGw8jwiwuImpZwWgM0kiSKAyFIoLGnMgErHjEmYybcNR8hCERSnAGBpJIqiIiBaSkEjAalzB4DCnFb_TPo7xEObkkE1KQK1KRmpQkIzOc_TiqPO9Sz2dGUe98Wp2OSnQ5YEOszyqY0xi19kJn89jezGmRGYkVbpYlN4GkOvf9VCiNbWRiAqZ9f5LO9NnF1DqjDON5ZqguzGRTUSsojXUfTJ4oOtT5GJWB4MBcmx7UV2BYZ0rdqs0kpfrKHAzKQCZB7KGyHUk87DrUdTvwq8ROsZ3jlLtFKqnbBPLtAnv7KMRtQ52uIy0IhjyBPvcLSAncKB5AiYXW6oDTJmcp0OBUyIWHkMAy7rq9B7BYwGRdjFJQeCQsGlk09xs_gUnhr52XUDP1NEzwfLHFuO7AUoQSGyNctw4CbXdaB7GtWHiL6mtQCzdv01VNeiUtjQn_U4ktmjxQhW6erlSKNERjG6wAfm_LF6W1Q4Ezg7LrCiQKQ80CMsvIIgCTuIFrY3HelsfuDx60Ok-7z56_ePnq9Zu373bff9jrfdw_-PT5y2H_q0MZFzKM4kS1hkvFPw) Input is given via `argv[1]`. Outputs a [PGM](http://netpbm.sourceforge.net/doc/pgm.html) image. ]
[Question] [ Given some positive integer \$n\$ generate all derangements of \$n\$ objects. ### Details * A derangement is a permutation with no fixed point. (This means in every derangement number \$i\$ cannot be in the \$i\$-th entry). * The output should consist of derangements of the numbers \$(1,2,\ldots,n)\$ (or alternatively \$(0,1,2,\ldots,n-1)\$). * You can alternatively always print derangements of \$(n,n-1,\ldots,1)\$ (or \$(n-1,n-2,\ldots,1,0)\$ respectively) but you have to specify so. * The output has to be deterministic, that is whenever the program is called with some given \$n\$ as input, the output should be the same (which includes that the order of the derangements must remain the same), and the complete output must be done within a finite amount of time every time (it is not sufficient to do so with probability 1). * You can assume that \$ n \geqslant 2\$ * For some given \$n\$ you can either generate all derangements or alternatively you can take another integer \$k\$ that serves as index and print the \$k\$-th derangement (in the order you chose). ### Examples Note that the order of the derangements does not have to be the same as listed here: ``` n=2: (2,1) n=3: (2,3,1),(3,1,2) n=4: (2,1,4,3),(2,3,4,1),(2,4,1,3), (3,1,4,2),(3,4,1,2),(3,4,2,1), (4,1,2,3),(4,3,1,2),(4,3,2,1) ``` [OEIS A000166](http://oeis.org/A000166) counts the number of derangements. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!=ÐṂR ``` A monadic Link accepting a positive integer which yields a list of lists of integers. **[Try it online!](https://tio.run/##y0rNyan8///oJEXbwxMe7mwK@v//vwkA "Jelly – Try It Online")** ### How? ``` Œ!=ÐṂR - Link: integer, n Œ! - all permutations of (implicit range of [1..n]) R - range of [1..n] ÐṂ - filter keep those which are minimal by: = - equals? (vectorises) - ... i.e. keep only those permutations that evaluate as [0,0,0,...,0] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ⟦kpiᶠ≠ᵐhᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sW/H80f1l2QSaQ9ahzwcOtEzKA@P9/k/9RAA "Brachylog – Try It Online") This is a generator that outputs one derangement of `[0, …, n-1]` given `n`. If we wrap it in a `ᶠ - findall` metapredicate, we get all possible generations of derangements by the generator. ### Explanation ``` ⟦ The range [0, …, Input] k Remove the last element p Take a permutation of the range [0, …, Input - 1] iᶠ Take all pair of Element-index: [[Elem0, 0],…,[ElemN-1, N-1]] ≠ᵐ Each pair must contain different values hᵐ The output is the head of each pair ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 85 bytes A recursive function printing all 0-based derangements. ``` f=(n,p=[],i,k=n)=>k--?f(n,p,i,k,k^i&&!p.includes(k)&&f(n,[...p,k],-~i)):i^n||print(p) ``` [Try it online!](https://tio.run/##TYxLCsIwFEXnruI5SRPyGQiCWKM7cAOlhVJbeaa8hLZ2YnXrMXXk6MC5h/uo53psBgyTng8xdpaTCrYoFSpnSdiz0/rSrXI1ylXI2DYYpKZ/3tqRO8HYOhfGmKBcqfQHhThiRcsSBqSJBxE7P3ACC7scCE4W9olSCnhtABpPo@9b0/s7z64pykACiTxN6ffH/ySJd/wC "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input p = [], // p[] = current permutation i, // i = current position in the permutation k = n // k = next value to try ) => // (a decrementing counter initialized to n) k-- ? // decrement k; if it was not equal to 0: f( // do a recursive call: n, p, i, k, // leave all parameters unchanged k ^ i && // if k is not equal to the position !p.includes(k) && // and k does not yet appear in p[]: f( // do another recursive call: n, // leave n unchanged [...p, k], // append k to p -~i // increment i // implicitly restart with k = n ) // end of inner recursive call ) // end of outer recursive call : // else: i ^ n || // if the derangement is complete: print(p) // print it ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` ->n{[*0...n].permutation.select{|x|x.all?{|i|i!=x[i]}}} ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQq9Sugj4RtLQOIi4sjASbpAwMx7Pbe/e7fmUXpZ8pyW4AQAre3OcbdLAX4THObCFx5Ajt3JLYsq1FlFblnEszAlMLo7cjMbGvdkkqlx8 "Ruby – Try It Online") Generates all 0-based derangements [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` Lœʒāø€Ë_P ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5@jkU5OONB7e8ahpzeHu@ID//00A "05AB1E – Try It Online") **Explanation** ``` L # push [1 ... input] œ # get all permutations of that list ʒ # filter, keep only lists that satisfy āø # elements zipped with their 1-based index €Ë_P # are all not equal ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` Select[Permutations[s=Range@#],FreeQ[Ordering@#-s,0]&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg1JzW5JDogtSi3tAQomp9XHF1sG5SYl57qoByr41aUmhoY7V@UklqUmZfuoKxbrGMQqxar9j8AyC9RcEiPNorlArOjYxW44ILG2ARNYv//BwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes 0-based ``` o á fÈe¦ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byDhIGbIZaY&footer=rm3E&input=MwotUQ) (Footer increments all elements for easier comparison with the test cases) ``` o á fÈe¦ :Implicit input of integer o :Range [0,input) á :Permutations f :Filter È :By passing each through this function e : Every element of the permutation ¦ : Does not equal its 0-based index ``` [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` lambda n:[p for p in permutations(range(n))if all(i-j for i,j in enumerate(p))] from itertools import* ``` [Try it online!](https://tio.run/##HcoxDkIxCADQ3VMwgtHFOJl4EnXgx1b5aYHw6eDpa/TNzz/5Nj3Ner3Pxn15Mujl5lAtwEEUvEQfySmmGwbrq6ASSQVuDeW4/qcc1t8tOnoJzoJO9NjVsA6SJdKsbSDdLXI/PUQTKor6SCSa5y8 "Python 2 – Try It Online") 0-based indexing, list of tuples. Non-`itertools`-based solution: # [Python 2](https://docs.python.org/2/), 107 bytes ``` n=input() for i in range(n**n): t=[];c=1 for j in range(n):c*=j!=i%n not in t;t+=[i%n];i/=n if c:print t ``` [Try it online!](https://tio.run/##TcoxDsIwEETR3qcYCqTYFAiUytaeJEqBLBI2xdiyNgWnd0hH@/@rX/sUPnunKOtug3dLaVAo0V5c3wNDoI8OJtOcsjwcTrD9AR9zkO0ieiVY7DyW7CbTL8xJ70IHXZBjbUqD9T4e "Python 2 – Try It Online") 0-based indexing, lines of lists, full program. Note: This solution, even though it doesn't import the `itertools` library, isn't much longer than the other one which does import it, because most of the bulk here is building the permutations. The derangement check is really about 7 additional bytes! The reason is that the check is done on the fly as part of the building of each permutation. This isn't true for the other solution, where you have to check if each permutation returned by the `itertools.permutations` function is in fact a derangement, and, of course, the mapping itself takes a lot of bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` :tY@tb-!AY) ``` This generates all derangements in lexicographical order. [Try it online!](https://tio.run/##y00syfn/36ok0qEkSVfRMVLz/38TAA "MATL – Try It Online") ### Explanation with example Consider input `3`. ``` : % Implicit input n. Range [1 2 ... n] % STACK: [1 2 3] t % Duplicate % STACK: [1 2 3], [1 2 3] Y@ % All permutations, in lexicographical order, as rows of a matrix % STACK: [1 2 3], [1 2 3; 1 3 2; ··· ; 3 2 1] t % Duplicate % STACK: [1 2 3], [1 2 3; 1 3 2; ··· ; 3 2 1], [1 2 3; 1 3 2; ··· ; 3 2 1] b % Bubble up: moves third-topmost element in stack to the top % STACK: [1 2 3; 1 3 2; ··· ; 3 2 1], [1 2 3; 1 3 2; ··· ; 3 1 2; 3 2 1], [1 2 3] - % Subtract, element-wise with broadcast % STACK: [1 2 3; 1 3 2; ··· ; 3 2 1], [0 0 0; 0 1 -1; ··· ; 2 -1 -1; 2 0 -2] !A % True for rows containining only nonzero elements % STACK: [1 2 3; 1 3 2; ··· ; 3 1 2; 3 2 1], [false false ··· true false] Y) % Use logical mask as a row index. Implicit display % STACK: [2 3 1; 3 1 2] ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=none -n`, ~~100~~ 89 bytes ``` $"=',';@b=1..$_;map{%k=$q=0;say if none{++$q==$_||$k{$_}++}/\d+/g}glob join$",("{@b}")x@b ``` [Try it online!](https://tio.run/##K0gtyjH9/19FyVZdR93aIcnWUE9PJd46N7GgWjXbVqXQ1sC6OLFSITNNIS8/L7VaWxsoZKsSX1Ojkl2tEl@rrV2rH5OirZ9em56Tn6SQlZ@Zp6Kko6FU7ZBUq6RZ4ZD0/7/xv/yCksz8vOL/ur6megaGBkDaJ7O4xMoqtCQzxxZk7H/dPAA "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` f n|r<-[1..n]=[l|l<-mapM(\i->filter(/=i)r)r,all(`elem`l)r] ``` [Try it online!](https://tio.run/##BcFBCoMwEAXQq8yiiwQapdCl6Q16AhUcJKmDPyGMLj270/c2PvYEmGWqlw5hfHVdneOIC0Mo3L5ukvDJgjOp66N49fpkwC0JqSzwOlthqRSpqdSTHpTpbfeawb/DwtraHw "Haskell – Try It Online") **60 bytes** ``` f n|r<-[1..n]=foldr(\i m->[x:l|l<-m,x<-r,all(/=x)$i:l])[[]]r ``` [Try it online!](https://tio.run/##BcFBDoMgEAXQq8zChSaOTZOuDPQilAVRqcQPJWMXLDx7p@/t4Tw2QDVSucSwu09T8TZ@sEr/SpT56dqMC4bz2AzLGID@ZtvQpRl@cM570RxSIUtVUvlSR5Ee@lsiwvtUXmr9Aw "Haskell – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 10 bytes ``` ┅f⟨:ċ=†ỵ⟩⁇ ``` [Try it online!](https://tio.run/##ASAA3/9nYWlh///ilIVm4p@oOsSLPeKAoOG7teKfqeKBh///Mw "Gaia – Try It Online") ``` ┅ | push [1 2 ... n] f | push permutations ⟨ ⟩⁇ | filter where result of following is truthy :ċ | dup, push [1 2 ... n] =†ỵ | there is no fixed point ``` [Answer] # [J](http://jsoftware.com/), 26 bytes ``` i.(]#~0~:*/@(-|:))i.@!A.i. ``` [Try it online!](https://tio.run/##RU3LDoIwELzzFeMjEQxUpVxsokFNPBkP3j0olFAD1kCNHoy/jmUh8bC7Mzszu7dmyCYZVgIT@JhD2AoYdqfDvlHMPY@@86@YzmI3@AjPUywebJhijefIJNfIwB3nuGUWqNom1T2Vb5n6uD4NXtLyBCaXqGT9LAyMRnkxSU67TFeWQGfEHpW@FrLszrohOMZo@wKgHnoIBNaCXnamJSIyLezkIHfU@kMavA9GlvdKD0I62i04KExaC6z2fxQ1Pw "J – Try It Online") ``` i. (] #~ 0 ~: */@(- |:)) i.@! A. i. i. ( ) NB. 0..input ( ) i.@! A. i. NB. x A. y returns the NB. x-th perm of y NB. i.@! returns NB. 0..input!. Combined NB. it produces all perms NB. of y ] #~ 0 ~: */@(- |:) NB. those 2 are passed as NB. left and right args NB. to this ] #~ NB. filter the right arg ] NB. (all perms) by: 0 ~: NB. where 0 is not equal to... */@ NB. the product of the NB. rows of... (- |:) NB. the left arg minus NB. the transpose of NB. the right arg, which NB. will only contain 0 NB. for perms that have NB. a fixed point ``` [Answer] # [R](https://www.r-project.org/), ~~81~~ 80 bytes ``` function(n)unique(Filter(function(x)all(1:n%in%x&1:n-x),combn(rep(1:n,n),n,,F))) ``` [Try it online!](https://tio.run/##Pck9CoQwFEXh3lXYKO/Cs/CvGaZ2HyoJBOJ1DAay@4xpbD4OnJBt/e2yjdxvd1KISHdFI4vztwnyjoTVe@k/bByb1D7RJeh@HhslmF85SihVFwDZyoDKyliYCjPyHw "R – Try It Online") Returns a `list` containing all derangements. Highly inefficient, as it generates \$ n^2\choose n\$ possible values as the size-`n` combinations of `[1..n]` repeated `n` times, then filters for permutations `1:n%in%x` and derangements, `1:n-x`. # [R](https://www.r-project.org/) + [gtools](https://cran.r-project.org/web/packages/gtools/index.html), 62 bytes ``` function(n,y=gtools::permutations(n,n))y[!colSums(t(y)==1:n),] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPp9I2vSQ/P6fYyqogtSi3tCQRJF4MlMjT1KyMVkzOzwkuzS3WKNGo1LS1NbTK09SJ/Z@mYaTJlaZhDCJMNP8DAA "R – Try It Online") Much more efficient, returns a `matrix` where each row is a derangement. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 96 bytes ``` lambda n:(p for i in range(n**n)if len({*(p:=[j for k in range(n)for j in{i//n**k%n}-{k}])})==n) ``` [Try it online!](https://tio.run/##TYu9CsIwEMdf5RbhLiAddJBAnkQdIjaapv57hC4l5Nlj4@T6@9BtfS84XTS34G5t9p/H0xMsK4UlU6QIyh6vkWEMJAaaR3AxrNZdp1@T/hrpYNpBicOwH@mAeiyp3qWKc5DWvfYh8FksaY5YWaV9AQ "Python 3.8 (pre-release) – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~207~~ 196 bytes -5 bytes by ceilingcat -6 bytes by Roman Odaisky ``` #include<regex> #define v std::vector auto p(int n){v<v<int>>r;v<int>m(n);int i=n;for(;m[i]=--i;);w:for(;std::next_permutation(&m[0],&m[n]);r.push_back(m))for(i=n;i--;)if(m[i]==i)goto w;return r;} ``` [Try it online!](https://tio.run/##PY7RaoMwFIavzVMEy0rCdGzQK6O@SJHi4rE9bIkhJlZafHaXZNCbcDj5vv/80pjyKuW@H1DLXz9AbeEKa0sOA4yogS50dkNVLSDdZEnv3UQNQ@2o5s@lXuowtq0V/4Nimov4iY0W42SZUGfsmrJEwcW9SpsUp2F1FwNWedc7nDQ7qvNnV4RXd1zYD@Pn2@W7lz9McR61GIhlKTiOLGU2yK9TKHMXFpy3mlqx7fG06lEz/iRZ6rrSJvQ9cUGyGBN3x0e1cpIFIjM2GCPLWR6BF0GhegQiIS/mbShoXsD7V0K3aHs3BzO5G9n20x8 "C++ (gcc) – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 133 bytes I think this has grown different enough from the other submission to merit a separate answer. Finally a use for `index[array]` inside-out syntax! ``` #include<regex> [](int n,auto&r){int i=n;for(;i[*r]=--i;);for(;std::next_permutation(*r,*r+n);)for(i=n;i--?(r[1][i]=i[*r])-i:!++r;);} ``` [Try it online!](https://tio.run/##bVHLasMwELzrK7YJFMmOoYGeIjv9A59yM6YIeR0EjmzkdQkE/3pTSSaP0uogaUezu7MjPQzZUevr2ljdTQ1CbvqRHKrTnrF1g62xCIcDqIl6GKCAqr5zc4dHPO/Z4cCNJbCbQHp14hIiU1jZ9o5LUyWuLrLMSLEAIzW7ncUzfQ7oThMpMr3lidskLrVCikAK2SbLPrirtnVl6iJWEZnZvaSp85Xmq2RM93YkPA8OQsdWaeqdUd2iRrALA7/ikxe@lTGM1YO@CPkjL8BKSFMj4vuSFJmQFGCWrDnuDmlyFlrJZsYIT0OnKDjmy5V79tWbBghH4s@tG0WqekgrRV2Vte99mZfK0Vj0QCAu0MDLDaB46I0cdeP4Ww4YJKs/kp@Ge4vDQfk0229yWPEvdD8R5DlwnijhzYYUtiIAK1jJO31m/ybFAG3T3Yzy1gQJJ2UsF0u3YEr@vuciGHf91m2njuM1a/3/aRxo/AE) [Answer] # Haskell, 76 bytes ``` n&x=[x++[i]|i<-[1..n],notElem i x,i/=length x+1] d n=iterate(>>=(n&))[[]]!!n ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` f=lambda n,i=0:i/n*[[]]or[[x]+l for l in f(n,i+1)for x in range(n)if~-(x in[i]+l)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n09bAKlM/Tys6OjY2vyg6uiJWO0chLb9IIUchM08hTQOoQttQEyRQARIoSsxLT9XI08xMq9PVAIlEZwI1aMb@B6nIQ6gw0lEw07Ti4iwoyswrARmj@R8A "Python 2 – Try It Online") 88 bytes as program: ``` M=[], r=range(input()) for i in r:M=[l+[x]for l in M for x in r if~-(x in[i]+l)] print M ``` [Try it online!](https://tio.run/##K6gsycjPM/r/39c2OlaHq8i2KDEvPVUjM6@gtERDU5MrLb9IIVMhM0@hyAqoIkc7uiIWJJQDEvJVADErwLIKmWl1uhogdnRmrHaOZixXQVFmXomC7///JgA "Python 2 – Try It Online") 93 bytes using itertools: ``` from itertools import* r=range(input()) print[p for p in permutations(r)if all(map(cmp,p,r))] ``` [Try it online!](https://tio.run/##BcE9DsIwDAbQvafwaKNOiJWTIIYIJcVS/KOv7sDpw3v5q2/4fa2BMNLqqIh5kloG6rbhieZHZ/W8ikW2hHq9kkaAktQpO@yqVhp@MkQHtTnZWvLHcs8dIu@1Hn8 "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 37 bytes Edit: After some back and forth with Phil H, we've whittled it down to only 37 bytes: ``` (^*).permutations.grep:{all @_ Z-^@_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwXyNOS1OvILUot7QksSQzP69YL70otcCqOjEnR8EhXiFKN84hvva/NVdxIkiHhpEmnGmMYJoAmf8B "Perl 6 – Try It Online") By using the `Whatever` at the beginning, we can avoid the brackets (saves 2 chars). Next use a the `Z` metaoperator with `-` which takes each element of a permutation (e.g. 2,3,1) and subtracts 0,1,2 in order. If any of them are 0 (falsy) then the all junction fails. --- Original solution was ([Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7ogtSi3tCSxJDM/r1hDJV5TL70otcCqOi8/L1VBIy2/SEElXqFaRVvb1lYlvlaztva/NRdXcSJIu4aRpjWMaYxgmgCZ/wE "Perl 6 – Try It Online")) ``` {permutations($_).grep:{none (for $_ {$++==$_})}} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ 28 bytes [crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/176659/17602) ``` NθIΦEXθθEθ﹪÷ιXθλθ⬤ι‹⁼μλ⁼¹№ιλ ``` [Try it online!](https://tio.run/##PY29CsMwDIT3PoVHGdyhQ6dMJW0h0JS8gpMYKlDs@C99fMcKpRrE6e47NH10mJymUjq75vTOy2gCeNmchoA2QatjgidSqm6vVxjcl3MlvFSCjSp7N2dy0Nl0xw1nA6jEnyMpGeZ9I@LoZWKEh8@aIiwMKPG7Lkq0LtevePSOaUq5lvNGOw "Charcoal – Try It Online") Link is to verbose version of code. Loosely based on @EricTheOutgolfer's non-itertools answer. Explanation: ``` Nθ Input `n` Xθθ `n` raised to power `n` E Mapped over implicit range θ `n` E Mapped over implicit range ι Outer loop index ÷ Integer divided by Xθ `n` raised to power λ Inner loop index ﹪ θ Modulo `n` Φ Filtered where ι Current base conversion result ⬤ All digits satisfy №ιλ Count of that digit ⁼¹ Equals literal 1 ‹ And not ⁼μλ Digit equals its position I Cast to string Implicitly print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~187~~ 180 bytes * Saved seven bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` *D,E;r(a,n,g,e){e=g=0;if(!a--){for(;e|=D[g]==g,g<E;g++)for(n=g;n--;)e|=D[n]==D[g];for(g*=e;g<E;)printf("%d ",D[g++]);e||puts("");}for(;g<E;r(a))D[a]=g++;}y(_){int M[E=_];D=M;r(_);} ``` [Try it online!](https://tio.run/##TY5Ba8MwDIXv/RWex8BqbBhbt4smyCE59tZbFkJIHZHDtJJ1h5Lmt2dyGSU66fl7T89d4K5blm3hSxxd68WzjzBFYnrGoXcPbQgw9d@jw3ilouKaiD1/lMhZBuldiFFCQLhxUZ5cmBBvKWLywmkc5Nw7@3Q01ivPshr04PX0e/5x1gLOt4rk1V8AFFVbk7pwvrgGJg2bfVVSU2NBe7U0mlgej7EfJJqDk3tBnudGSGt0@RTrBfCiGO9Fm692EAeTpl5gY/7n4F7XYrcWb2vxDmZe/gA "C (gcc) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` f*F.e-bkT.PU ``` [Try it online!](https://tio.run/##K6gsyfj/P03LTS9VNyk7RC8g9P9/EwA "Pyth – Try It Online") ``` UQ # [implicit Q=input] range(0,Q) .P Q# [implicit Q=input] all permutations of length Q f # filter that on lambda T: .e T # enumerated map over T: lambda b (=element), k (=index): -bk # b-k *F # multiply all together ``` The filter works like this: if any element is at its original spot, (element-index) will be 0 and the whole product will be 0, and thus falsey. ]
[Question] [ Determine the length of a UTF-8 byte sequence given its first byte. The following table shows which ranges map to each possible length: ``` Range Length --------- ------ 0x00-0x7F 1 0xC2-0xDF 2 0xE0-0xEF 3 0xF0-0xF4 4 ``` Notes on gaps in the table: 0x80-0xBF are continuation bytes, 0xC0-0xC1 would start an overlong, invalid sequence, 0xF5-0xFF would result in a codepoint beyond the Unicode maximum. Write a program or function that takes the first byte of a UTF-8 byte sequence as input and outputs or returns the length of the sequence. I/O is flexible. For example, the input can be a number, an 8-bit character or a one-character string. You can assume that the first byte is part of a valid sequence and falls into one of the ranges above. This is code golf. The shortest answer in bytes wins. ## Test cases ``` 0x00 => 1 0x41 => 1 0x7F => 1 0xC2 => 2 0xDF => 2 0xE0 => 3 0xEF => 3 0xF0 => 4 0xF4 => 4 ``` [Answer] ## Forth, 6 bytes ``` x-size ``` see <https://forth-standard.org/standard/xchar/X-SIZE> Input and output follows a standard Forth model: **Input** Memory address + length (i.e. 1) of a single-byte UTF-8 "string". **Output** UTF-8 sequence length in bytes. **Sample Code** Store **0xF0** in a memory cell, and invoke x-size: ``` variable v 0xF0 v ! v 1 x-size ``` Check the result: ``` .s <1> 4 ok ``` [Answer] # [Z80Golf](https://github.com/lynn/z80golf), ~~19~~ 14 bytes ``` 00000000: 2f6f 3e10 37ed 6a3d 30fb ee07 c03c /o>.7.j=0....< ``` [Try it online!](https://tio.run/##LcHRCYAwDAXAVd4E9WmgEVF30TYRROi/y0dB7@6RR7s8gr8Jg2eHWE@IWkXepELoO8yoKJSCT9fWpOlcmF5zxAM "Z80Golf – Try It Online") -5 bytes thanks to @Bubbler [Example with input 0x41-Try it online!](https://tio.run/##dY3BbsIwEETP9VfMjQtKNzVKgBQkjnwFctZ2E2TsKnFQ4eeDDVw7p9HO09v7mn6Cs/NM72whzaoEa9qAiCtIshZ19WVRWWlQkqxhdKWA/aFIoeL6GfZFXZzFy1Bmh5YE2xoDqpkgGf9kR9nxPc/N0f9OcUd/q1I0h3E0l9bdYMMAO3mOffBg5dxWOA21xJPLB7S3aE4cJh@F0joNkj4a5KpG7nssaIEYwMFfzRBz7RM6jDGj64Smt9ypQXTKxQc "Z80Golf – Try It Online") [Assembly](https://tio.run/##TZHLTsMwEEXX9leMWNBWSklaXlUCCxYgWPUPQFPbaYJcO7InVaj672HcgmBh@frOmZe8wdiMRjUeLl7NoPtdB74G5bUpL@DyEhQSPDw8r1/gCLnvKMcYzW5jv@aHVZHzwbiDXJt9Hkm3DuYe5oySMZDTrsvx6rDSbAyDTuXOndY9dT2dG5yKcp2tt3Ueg/rV/9LH6s0x/1gMNwtZPf0MALUPUPdOUesdz2ltKa0GzODEJQM2X2Q@lO8dSdSaA9eFqCBJjKptYVJMgDyv6/YmUJItoyFSQleMclvVYJANWpKyatMcJQSzbSOZACgrf97lv/fXtRRCVDyJ6i2Sgfv3qfXb5XR5e/uOs9nxuJBCdTZBAy/DthS8gs2QbwZLKfgtMFvcsYqqPtvW@y6FUCvR2KyxrLVRgrPEZxBOZb@UFKnuvRTBELiDFK1TgCN/5/gN "Bash – Try It Online") [Example with input 0xC2-Try it online!](https://tio.run/##dY3BbsIwEETP@CvmxgWFJZYSSgAJ9cRXIGdtN0HGrhIHlf58sFuuzGm08/T2d0tfwdl5pld2kIZLsKYPEHEFSdairkqLykqDDckaRlcKOJ6KFCru63As6uIq/g2b7NCSYFtjQDUTJONNDpQd@3luzv57igf6@SxFcxpHc2vdAzYMsJPn2AcPVs7thNNQK/xx@YD2Ec2Fw@SjUFqnQdKiQa5q5L7HkpaIARz83Qwx1z6hwxgzuk1oesudGkSnXHwC "Z80Golf – Try It Online") [Example with input 0xE0-Try it online!](https://tio.run/##dY3BbsIwEETP9VfMjUuVLlhKgAAShx76FZWzXkMq10aJg6A/n9rQa@c02nl6@7OmU/RunukvW2gRAlvagIhraHIOTb1yqJ0WLEk3EFsb4HCscqi6vsVD1VRf6mlYFofVBNeJgBomaMY/2VNx7Oa5/QiXKe3p9k6qPY6jfHf@DhcHuClw6mMAG@@3yluYVzy4ckB3T/LJcQpJGWvzoOmlRalm5L7HghZIERzDVYZUap/RYUwFXWc0v@WzGdTZ@PQL "Z80Golf – Try It Online") [Example with input 0xF4-Try it online!](https://tio.run/##dY3BbsIwEETP9VfMjQtKlxollAASFyS@onLW3pLKtVHioMLPp3bba@c02nl6@9jQe/Qyz/SXLbSTNdjSK4i4hiYRNPWLoBbtsCLdwNnaAIdjlUPV7Tkeqqb6UL@GVXFYTZDOOVDDBM34J3sqjt08t@dwndKevk5r1R7H0X12/g6JA2QKnPoYwMb7rfIWZokfrhzQ3ZN74ziFpIy1edD01KJUM3LfY0ELpAiO4eaGVGqf0WFMBd1kNL/lixnUxfj0DQ "Z80Golf – Try It Online") Assembly: ``` ;input: register a ;output: register a byte_count: ;calculate 7^(log2(255^a))||1 cpl ;xor 255 ld l,a log2: ld a,16 scf log2loop: adc hl,hl dec a jr nc,log2loop xor 7 ret nz inc a ``` [Try it online!](https://tio.run/##XY/BasMwDIbP8lPo2EJC2kLXkfS6XvcGHYrsNRmqHWxlpCXvnjmMXXYQ@vXr@wVqKXULk@L5/PZ@wRmrMGhFKbl7K4/y@bqrclG6Y2Xdd5XU9h7LgGVGp8kuTe@HUWuM7tYndRHJNGHU/177UPfBYfRaA0DDJDwKqcPTdSPhdtgcjscrbbfzvDfAg6zQFCJm24BYlIJyz2BtIM9Axf4lq8Sfv7aEMKwrsgydFJ1kbR1DTsFXBM/FH2VgvXsyEJ2ifxroPSMt@fnlBw "Bash – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 39 bytes ``` t(char x){x=(__builtin_clz(~x)-24)%7u;} ``` [Try it online!](https://tio.run/##NY5BCoMwEEXX5hTBImRQ21QKLqJepBWx0bQDNhaNECr26tYI3bz/hvkMI@OHlOtqmHzWA7Uw25xV1X3CzqCuZPdhXwtxcoEgncSyHlDLbmrabDQN9sdnQVAb@qpRM5iJ54b6WuYzt5xHdOPZMVWOMnFsdm/3bbu72l1dFkE81Q/MHcGcC8xG/LS9YjWc/nblJYgwRCCe9x62pmI@twFPLI0LGjQ37UfbB1hG1DCXAIIs6w8 "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +⁹BIITḢ ``` A monadic link accepting the byte as an integer. **[Try it online!](https://tio.run/##y0rNyan8/1/7UeNOJ0/PkIc7Fv3//9/I2AIA "Jelly – Try It Online")** Or see [all inputs evaluated](https://tio.run/##JdIrkhRRFIThrVxPiXvyvi1uPK6jJYaYDSDBsA80CwDNSpiNFH@eiWhXX3Vnn8wvn19fv973h7dvfz6@vHz69/vn/ffH2/dffO778ahXiavoKu0q/SrjKvMq6yr7KodHfszzAAQiIIEJUKACFjjh5O/BCSeccMIJJ5xwDddwzT@Ia7iGa7iGa7iG67iO67juZLiO67iO67iOG7iBG7iBG/4LuIEbuIEbuImbuImbuImb/q@4iZu4iVu4hVu4hVu4hVs@Cm7hFm7jNm7jNm7jNm7jtq@H27iDO7iDO7iDO7iDO7jjM@edfejqS1efuvrW1ceuvnb1uavvXX3w6jfeq/EbWU62k/VkP1lQNpQVuaNwSaFs02@4p3BR4abCVYXW8yqPcMxwznDQcNI4WXV27bKdVc4qZ5WzylnlrHJWOaucVZHz8BvOKmeVs8pZ5axyVjmrck85qPdF@Q0151LOKneVw8pl5bS8LXlc8rrUcob@FQ9MXpg8MXlj8sjUTn6jhyYvTZ6aem63P5//AQ "Jelly – Try It Online"). If an input of a list of the 8 bits were acceptable then the method is only 6 bytes: `1;IITḢ`, however it has been deemed as talking flexible I/O too far. ### How? ``` +⁹BIITḢ - Link: integer e.g.: 127 (7f) 223 (df) 239 (ef) 244 (f4) ⁹ - literal 256 + - add 383 479 495 500 B - to a list of bits [1,0,1,1,1,1,1,1,1] [1,1,1,0,1,1,1,1,1] [1,1,1,1,0,1,1,1,1] [1,1,1,1,1,0,1,0,0] I - increments [-1,1,0,0,0,0,0,0] [0,0,-1,1,0,0,0,0] [0,0,0,-1,1,0,0,0] [0,0,0,0,-1,1,-1,0] I - increments [2,-1,0,0,0,0,0] [0,-1,2,-1,0,0,0] [0,0,-1,2,-1,0,0] [0,0,0,-1,2,-2,1] T - truthy indices [1,2] [2,3,4] [3,4,5] [4,5,6,7] Ḣ - head 1 2 3 4 ``` [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` f x=sum[1|y<-"Áßï",x>y]+1 ``` [Try it online!](https://tio.run/##JYxBisJAEEX3nuLTCEmISjIIAyHtJpqVs3KpIk1Pa4JJR9ItRnAzJ/EIHiIHy3RpFTxeUfWrEOasqmoYjui4udbb@HFPp6z/65/9i026xX0fxkMtSg2OWlx@DvAvV7ux7VpjhlMTOFalVgY8TXFSNmu0Vdoa3ArVqhHcDaTBAxLpFK0SvxiDebsdQxjCirKCL01AA/MYkgRZIVqX@xSnsNt5rhN4PlGSBWQMfIH3I1M0N/hHyGCIuigaRd08dvjOHbIvhyXZihYrspwsn/8D "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 28 bytes ``` lambda x:1.4**(x/16-11)//1+1 ``` [Try it online!](https://tio.run/##LczRCoIwGIbh867iO9x0tf0iBUJXUh1sub@EnDJEFtG1rxQPH154x/f0HEKV@XzNL9u71iI1dKiLQiRNxz2R1JpKyjxEWOXQBVyEScYomHRiqfDXvVrUbvJr85t4Fdfy1uyAMXZhwofFLLEs52UYbXh4YRVcSfKbfw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` »Ø⁷Ba\S ``` [Try it online!](https://tio.run/##y0rNyan8///Q7sMzHjVud0qMCf5/uP1R0xqFyP//DSoMDHQUDCpMDEGkeRqITDYCkSlgdipYNhXMTgOz00wA "Jelly – Try It Online") ### How it works ``` »Ø⁷Ba\S Main link. Argument: n (integer) Ø⁷ Yield 128. » Take the maximum of n and 128. B Yield the array of binary digits. a\ Cumulatively reduce by AND, replacing 1's after the first 0 with 0's. S Take the sum. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 24 bytes ``` x=>7^Math.log2(255^x)||1 ``` [Try it online!](https://tio.run/##Hcy9CoMwGIXhub2Kb3BIoEqUWie9g04dS8WgiU0JfiUGCf5ce9pkeXjhwPnwhc@9UV@bTjgIv3ADK9Te1U3V3rl9ZxrHghRl2Tq677mXaIgWFhSghCdzjF3gbx6sZLAvgkNsEVcRW8aW1xc9n3qcZtQinJOOuWRTmcWHNWoaSX6jB6QNJNtKFD066n8 "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ 23 bytes ``` ->x{2+x[7]+(x/16<=>14)} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166i2ki7Ito8VlujQt/QzMbWztBEs/Z/dLRBhYGBjoJBhXlarI4CkJdsBOKlQHmpYLlUKC8NzEsziY3Vy00sqK5J1Emq4SpQiAbSOhqJenpJmiBxDbU0Tb3SvMzC2Nr/AA "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` I⌕⍘⌈⟦N¹²⁸⟧²0 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zL0XDKbE4NbgEKJiu4ZtYkZlbmqsR7ZlXUFriV5qblFqkoamjYGhkEQukjIBYyUBJU1PT@v9/IwOD/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input number ¹²⁸ Literal 128 ⌈⟦ ⟧ Take the maximum ⍘ ² Convert to base 2 as a string ⌕ 0 Find the position of the first `0` I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), 7 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` »Ø⁷Bi0’ ``` Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/173607/52210). [Try it online](https://tio.run/##y0rNyan8///Q7sMzHjVud8o0eNQw8////0bGlgA) or [verify all test cases](https://tio.run/##JdK7kVNREIThVG4AxzjT5@2ShkomBtQmsN6CQwqQAz4GHpuJEhF/z1bJu9@VWtP99fPLy@vz@e/v@8/Htz@fvtTH26/n@4/H9998ns/brZYryqVytXL1co1yzXKtcu1yHR75Mc8DEIiABCZAgQpY4ISTvwcnnHDCCSeccMI1XMM1/yCu4Rqu4Rqu4Rqu4zqu47qT4Tqu4zqu4zpu4AZu4AZu@C/gBm7gBm7gJm7iJm7iJm76v@ImbuImbuEWbuEWbuEWbvkouIVbuI3buI3buI3buI3bvh5u4w7u4A7u4A7u4A7u4I7PnHf2oasvXX3q6ltXH7v62tXnrr539cGr3/ioxm9kOdlO1pP9ZEHZUFbkjsIlhbJNv@GewkWFmwpXFVr3ct3CMcM5w0HDSeNk1dm1y3ZWOaucVc4qZ5WzylnlrHJWRc7DbzirnFXOKmeVs8pZ5azKPeWgPhblN9ScSzmr3FUOK5eV0/K25HHJ61LLGfpXPDB5YfLE5I3JI1M7@Y0emrw0eWrqud1@v/8H). **Explanation:** ``` Ø⁷ # Push 128 » # Take the max of 128 and the input B # Convert it to binary i0 # Get the 1-indexed first index of a 0 ’ # Decrease it by 1 to make it 0-indexed (and output it implicitly) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes ``` {7-msb(255-$_)||1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lw3tzhJw8jUVFclXrOmxrD2vzVXcWKlglK1XlpuiYa6qoFRhLpmrYKtnUJ1mgZQTa2SQlp@kYJBhYGBDpA0MQSR5m4g0tkIRLqA2a5gWVcw2w3MdjP5DwA "Perl 6 – Try It Online") Port of user202729's JavaScript answer. Alternatives with WhateverCode: ``` (255-*).msb*6%34%7 -(255-*).msb%6%5+1 ``` [Answer] # x86 Assembly, 11 bytes ``` 00000000 <f>: 0: f6 d1 not %cl 2: 0f bd c1 bsr %ecx,%eax 5: 34 07 xor $0x7,%al 7: 75 01 jne a <l1> 9: 40 inc %eax 0000000a <l1>: a: c3 ret ``` [Try it online!](https://tio.run/##bVDhasMgGPwdn@IjWyDSZDPZoNC0fZEuBGu0cxgzEguy0ldf9hk2Skb9cZx39@mpyE9CTNODtsKcWwnb0bW6f3rfE6Ktg6bhzg36eHayadJU8dEJbgyloFL0aUUwMXbokVhtYLHebExisL0DSIRZiMdxQFEKnyWS@1/R9yg@rrOEm1vyw0oAUyzPxLJhHCdvoik2d24fpPsvYuf5aR3XNqUXEoUNP9S7C/OMZYBYBFyrgKIM2M5czq6cuZq5er1WJFL9ED4D9I5VejvqL9mrlNPnP3ZgNa1WK01JFH0OmFRpzHzCSg/5HpIWW2XYQNcZhLSuKXa8TtO3UIafxinvXsof "C (gcc) – Try It Online") Port of user202729's JavaScript answer. Uses fastcall conventions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žy‚àb0k ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/173562/52210). -1 byte thanks to *@Grimy*. Input as integer. [Try it online](https://tio.run/##yy9OTMpM/f//6L7KRw2zDi9IMsj@/9/I2BIA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9kYuLmZ6@k8KhtkoKSvd//o/sqHzXMOrwgySD7v85/AA). **Explanation:** ``` žy # Push 128 ‚ # Pair it with the (implicit) input-integer à # Take the maximum of this pair (128 and input) b # Convert it to a binary-string 0k # Get the 0-based first index of a "0" in this binary-string # (and output it implicitly as result) ``` [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 28 bytes ``` 1?:_128/}:_224/}_240/{{+++!@ ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f0N4q3tDIQr/WKt7IyES/Nt7IxEC/ulpbW1vR4f9/IAcA "Labyrinth – Try It Online") Routing is pretty hard and also takes a lot of bytes, so I figured I'd just make a linear program. Basically computes `1 + n/128 + n/224 + n/240`, where `/` is floor division. [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 35 bytes ``` ? @!1 16/ )!@! : ";_ _3&""2 _128& ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fXsFB0VDB0ExfQVPRQZHLSkFBQck6XiHeWE1JyYgr3tDIQu3/fyMTAwA "Labyrinth – Try It Online") Unwrapped version of the code: ``` ?:_128&1!@ ; _16/_3&2!@ ) ! @ ``` [Answer] # C, 31 bytes ``` f(x){return(x-160>>20-x/16)+2;} ``` [Try it online!](https://tio.run/##NY7RCoIwFIav3VMMI9jQ1VHCLla@RhflhcytDtgMNRiJr95yQjcf3@H85/ArcVfKe8Mcn3o9vnvLnMgKKMschNtnBU9yOfsNWtW@G30axga73aMkaEf6rNEyPpEoDPW1Ok/gAFK6MAs8mkCVBzar63WrVzerm8MsSWS6noUneAaJpwE/ujOs5vu/XaHiMkmQkyh69UvSsBjcFnJHRUm3zc3G6dIAq5SGNFacSzL7rzJtfR@8uNhO4PPVosJRLOc/ "C (gcc) – Try It Online") ### 27 bytes with gcc (-O0) ``` f(x){x=(x-160>>20-x/16)+2;} ``` ### Alternatives, 31 and 33 bytes ``` f(x){return(10>>15-x/16)+7>>2;} f(x){return x/128-(-3>>15-x/16);} ``` I found these expressions when playing around with the Aha! superoptimizer [a few years ago](http://blogs.perl.org/users/nick_wellnhofer/2015/04/branchless-utf-8-length.html). [Answer] # [Zsh](https://www.zsh.org/), 42 bytes ``` >$1 eval ';od>><'{,194,224,240}-\> wc -l<* ``` [Try it online!](https://tio.run/##qyrO@P/fTsWQK7UsMUdB3To/xc7ORr1ax9DSRMfICIhNDGp1Y@y4ypMVdHNstP7//29oaQkA "Zsh – Try It Online") Input as a decimal integer. ]
[Question] [ Despite having 17 questions tagged [anagrams](/questions/tagged/anagrams "show questions tagged 'anagrams'"), we still don't have this question, so here it is. ## Your Task You must write a program or function that, when receiving a string, prints out all possible anagrams of it. For the purposes of this question, an anagram is a string that contains the same character as the original string, but is not an exact copy of the original string. An anagram does not have to be or contain actual words. ## Input You may accept the string, which may be of any length > 0, by any standard input method. It may contain any ASCII characters. ## Output You may output all of the possible anagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input. ## Other Rules [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) ``` œÙ¦ ``` A function that leaves the stack with a list of the anagrams on top (and as its only item). As a full program prints a representation of that list. **[Try it online!](https://tio.run/##MzBNTDJM/f//6OTDMw8t@/@/JLWiBAA "05AB1E – Try It Online")** ### How? ``` - push input œ - pop and push a list of all permutations (input appears at the head) Ù - pop and push a list of unique items (sorted by first appearance) ¦ - pop and push a dequeued list (removes the occurrence of the input) - As a full program: implicit print of the top of the stack ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 45 bytes ``` ->x{(x.chars.permutation.map(&:join)-[x])|[]} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euolqjQi85I7GoWK8gtSi3tCSxJDM/Ty83sUBDzSorPzNPUze6IlazJjq29n@BQpqehlJafr6S5n8A "Ruby – Try It Online") Despite having a built-in, the word "permutation" is really long :( [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` tY@1&X~ ``` [Try it online!](https://tio.run/##y00syfn/vyTSwVAtou7/f3VHJydHdQA "MATL – Try It Online") ### Explanation ``` t % Implicitly input a string, say of length n. Duplicate Y@ % All permutations. May contain duplicates. Gives a 2D char array of % size n!×n with each permutation in a row 1&X~ % Set symmetric difference, row-wise. Automatically removes duplicates. % This takes the n!×n char array and the input string (1×n char array) % and produces an m×n char array containing the rows that are present % in exactly one of the two arrays % Implicitly display ``` [Answer] # [pyth](https://github.com/isaacg1/pyth), 8 4 ``` -{.p ``` [Online test](https://pyth.herokuapp.com/?code=-%7B.p&input=%22ppcg%22&debug=0). ``` .pQ # all permutations of the (implicit) input string { # de-duplicate - Q # subtract (implicit) input ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` á â kU ``` [Try it online!](https://tio.run/##y0osKPn///BChezQ//@VEpOSlQA "Japt – Try It Online") ### Explanation ``` á â kU Uá â kU // Ungolfed // Implicit: U = input string Uá // Take all permutations of U. â // Remove duplicates. kU // Remove U itself from the result. // Implicit: output resulting array, separated by commas ``` [Answer] # Haskell, ~~48~~ 40 bytes ``` import Data.List a=tail.nub.permutations ``` [Try it online!](https://tio.run/##BcFBDoAgDATAs7yiIZ75gTePfmKNJDZCIXR5P8688C@XspbW3gblBJEudQYchJZk8049jzoJajNfFWpyyNPC1ocaZRdIZHbG9QM) *Saved 8 bytes thanks to Leo's `tail` tip.* [Answer] # [CJam](https://sourceforge.net/p/cjam), 8 bytes ``` l_e!\a-p ``` [Try it online!](https://tio.run/##S85KzP3/Pyc@VTEmUbfg/39HJydHAA "CJam – Try It Online") ### Explanation ``` l e# Read string from input _ e# Duplicate e! e# Unique permutations. Gives a list of strings \ e# Swap a e# Wrap in a singleton array - e# Set difference. This removes the input string p e# Pretty print the list ``` [Answer] # Mathematica, 47 bytes ``` Drop[StringJoin/@Permutations[Characters@#],1]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!QḊ ``` A monadic link taking a list of characters and returning a list of lists of characters - all distinct anagrams that are not equal to the input. **[Try it online!](https://tio.run/##y0rNyan8///oJMXAhzu6/h9uj/z/X6kktaJECQA "Jelly – Try It Online")** (the footer forms a program that joins the list by newlines and prints to avoid the otherwise smashed representation). ### How? ``` Œ!QḊ - Link: list of characters e.g. "text" Œ! - all permutations of the list ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","extt","ettx","etxt","xtet","xtte","xett","xett","xtte","xtet","ttex","ttxe","tetx","text","txte","txet"] Q - de-duplicate ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"] Ḋ - dequeue (the first one = input) ["tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"] ``` [Answer] ## Python 3, 85 76 63 bytes As a function, and returning strings as list of characters (thanks to @pizzapants184 for telling me it is allowed): ``` from itertools import* lambda z:set(permutations(z))-{tuple(z)} ``` As a function: ``` from itertools import* lambda z:map("".join,set(permutations(z))-{tuple(z)}) ``` 85 bytes as a full program: ``` from itertools import* z=input() print(*map("".join,set(permutations(z))-{tuple(z)})) ``` Could be reduced a bit if outputting strings as ('a', 'b', 'c') is allowed (I am not sure it is). [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 13 bytes **Solution:** ``` 1_?x@prm@!#x: ``` [Try it online!](https://tio.run/##y9bNz/7/3zDevsKhoCjXQVG5wkopMSkpUen/fwA "K (oK) – Try It Online") **Explanation:** Evaluation is performed right-to-left. ``` 1_?x@prm@!#x: / the solution x: / store input in variable x # / count length of x, #"abc" => 3 ! / range, !3 => 0 1 2 prm@ / apply (@) function permutations (prm) to range x@ / apply (@) these pumuted indixes back to original input ? / return distinct values 1_ / drop the first one (ie the original input) ``` [Answer] # Java 8, ~~245~~ ~~239~~ ~~236~~ 232 bytes ``` import java.util.*;s->{Set l=new HashSet();p("",s,l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);for(;i<n;)p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l);} ``` -6 bytes thanks to *@OlivierGrégoire* -4 bytes thanks to *@ceilingcat* Typical verbose Java.. I see a lot of <10 byte answers, and here I am with 200+ bytes.. XD **Explanation:** [Try it here.](https://tio.run/##TZAxb8MgFIT3/IqnTFBj4owNcaUOlbo0S8YoA8YkJsWAzHOqKPJvd7GbSEUguBN6d/ou8ipzH7S71N@jaYPvEC7J4z0ay18EzGu1gmz9CugBGw3VDXWufO9woayMEb6kcfcFgHGou5NUGnaTBLh6U4Mie@yMO0OkIrlDOmnvwEEJY8zf7nuNYEunf@BTxiYpQkUgyyWLzFJheadbf9UkTu@T7z6kasj@FlG33Pe42YQ0Ha2jYhBzYHgGBvZMZnMGvaeP4MrIrXZnbAhlpiyEORG3XVPLZV2TQEXKIMJsnaCBhCxy1cjuHYmhLPLYV3GeSQpmaPbfyDLDHJ0qDyNA6CtrFESUmK65V5swPaodjiDpH6MJHrSJxQRgEmTGBNByxxWRh@L44DaMo6wq9Qs) ``` import java.util.*; // Required import for the Set and HashSet s->{ // Method with String parameter and no return-type Set l=new HashSet(); // Set to save all permutations in (without duplicates) p("",s); // Determine all permutations, and save them in the Set l.remove(s); // Remove the input from the Set l.forEach( // Loop over the Set System.out::println);} // And print all the items // This method will determine all permutations, and save them in the Set: void p(String p,String s,Set l){ int n=s.length(), // Length of the first input String i=0; // Index-integer `i`, starting at 0 if(n<1) // If the length is 0: l.add(p); // Add the permutation input-String to the Set // Else: for(;i<n; // Loop `i` in the range [0,length): p( // And do a recursive-call with: p+s.charAt(i), // Permutation + `i`'th character s.substring(0,i)+s.substring(++i,n),l);} // Everything except this character ``` [Answer] # [Perl 6](https://perl6.org), ~~39~~ 38 bytes ``` *.comb.permutations».join.unique[1..*] ``` [Try it](https://tio.run/##HcsxDkAwFAbg3SneJBj@xGIRJxFDtU9S0T5alTibzcUq8e3fzmHrcopMVwfdF@6mUothGnIDLW7GzsGlU51WfHwfrGI9krdH4rEFmin3Bf6CqG5aJNBmPceqzmrWxnw "Perl 6 – Try It Online") ``` *.comb.permutations».join.unique.skip ``` [Try it](https://tio.run/##HcsxDoAgDADA3Vd0MurQkcX4GISaVIUiFRPf5ubHMPH2S5R3U4sSXAbd2IQbWieeYKoDOgkzJsqhnPZkifo@uApHLJGPQqgbpzo2@A9Ue8MiGXaOpF1f7ey8/wA "Perl 6 – Try It Online") ## Expanded ``` * # WhateverCode lambda (this is the parameter) .comb # split into graphemes .permutations\ # get all of the permutations ».join # join each of them with a hyper method call .unique # make sure they are unique .skip # start after the first value (the input) ``` [Answer] # C++, 142 bytes ``` #include<algorithm> void p(std::string s){auto b=s;sort(begin(s),end(s));do if(s!=b)puts(s.data());while(next_permutation(begin(s),end(s)));} ``` ungolfed ``` #include <algorithm> void p(std::string s) { auto b = s; // use auto to avoid std::string sort(begin(s), end(s)); // start at first permutation do if (s != b) // only print permutation different than given string puts(s.data()); while (next_permutation(begin(s), end(s))); // move to next permutation } ``` [Answer] # JavaScript (ES6), 101 bytes Adopted from a [past answer of mine](https://codegolf.stackexchange.com/a/123379/47097). ``` S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R]) ``` ``` f= S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R]) console.log( f('ABC'), f('ABCD'), f('ABCC'), f('AABBC') ) ``` [Answer] # [Perl 5](https://www.perl.org/), 89 + 2 (`-F`) = 91 bytes ``` $,=$_;$"=",";map{say if!$k{$_}++&&$,ne$_&&(join"",sort@F)eq join"",sort/./g}glob"{@F}"x@F ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1Yl3lpFyVZJR8k6N7GgujixUiEzTVElu1olvlZbW01NRScvVSVeTU0jKz8zT0lJpzi/qMTBTTO1UAFJQF9PP702PSc/Sanawa1WqcLB7f//5MTEf/kFJZn5ecX/dX1N9QwMDf7rugEA "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes Look ma, no Unicode! ``` tuP ``` [Try it online!](https://tio.run/##yygtzv7/v6Q04P///8mJiQA "Husk – Try It Online") 05AB1E, but reversed, and cooler, cause it's ASCII only. ]
[Question] [ The [Eulerian number](https://en.wikipedia.org/wiki/Eulerian_number) `A(n, m)` is the number of permutations of `[1, 2, ..., n]` in which exactly `m` elements are greater than the previous element. These are also called *rises*. For example, if `n = 3`, there are 3! = 6 permutations of `[1, 2, 3]` ``` 1 2 3 < < 2 elements are greater than the previous 1 3 2 < > 1 ... 2 1 3 > < 1 ... 2 3 1 < > 1 ... 3 1 2 > < 1 ... 3 2 1 > > 0 ... ``` So the outputs for `A(3, m)` for `m` in `[0, 1, 2, 3]` will be ``` A(3, 0) = 1 A(3, 1) = 4 A(3, 2) = 1 A(3, 3) = 0 ``` Also, this is the OEIS sequence [A173018](https://oeis.org/A173018). ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * The input `n` will be a nonnegative integer and `m` will be a integer in the range `[0, 1, ..., n]`. ## Test Cases ``` n m A(n, m) 0 0 1 1 0 1 1 1 0 2 0 1 2 1 1 2 2 0 3 0 1 3 1 4 3 2 1 3 3 0 4 0 1 4 1 11 4 2 11 4 3 1 4 4 0 5 1 26 7 4 1191 9 5 88234 10 5 1310354 10 7 47840 10 10 0 12 2 478271 15 6 311387598411 17 1 131054 20 16 1026509354985 42 42 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!Z>2\Sċ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZIhWj4yXFPEiw&input=&args=OQ+NQ) (takes a while) or [verify the smaller test cases](http://jelly.tryitonline.net/#code=xZIhWj4yXFPEiwrFvDsiw6ciRw&input=&args=MCwgMSwgMSwgMiwgMiwgMiwgMywgMywgMywgMywgNCwgNCwgNCwgNCwgNCwgNSwgNw+MCwgMCwgMSwgMCwgMSwgMiwgMCwgMSwgMiwgMywgMCwgMSwgMiwgMywgNCwgMSwgNA). ### How it works ``` Œ!Z>2\Sċ Main link. Arguments: n, m Œ! Generate the matrix of all permutations of [1, ..., n]. Z Zip/transpose, placing the permutations in the columns. >2\ Compare columns pairwise with vectorizing greater-than. This generates a 1 in the column for each rise in that permutation. S Compute the vectorizing sum of the columns, counting the number of rises. ċ Count how many times m appears in the computed counts. ``` [Answer] ## JavaScript (ES6), ~~50~~ ~~46~~ 45 bytes ``` f=(n,m,d=n-m)=>m?d&&f(--n,m)*++m+f(n,m-2)*d:1 ``` Based on the recursive formula: ``` A(n, m) = (n - m)A(n - 1, m - 1) + (m + 1)A(n - 1, m) ``` ### Test cases ``` f=(n,m,d=n-m)=>m?d&&f(--n,m)*++m+f(n,m-2)*d:1 console.log(f( 0, 0)); // 1 console.log(f( 1, 0)); // 1 console.log(f( 1, 1)); // 0 console.log(f( 2, 0)); // 1 console.log(f( 2, 1)); // 1 console.log(f( 2, 2)); // 0 console.log(f( 3, 0)); // 1 console.log(f( 3, 1)); // 4 console.log(f( 3, 2)); // 1 console.log(f( 3, 3)); // 0 console.log(f( 4, 0)); // 1 console.log(f( 4, 1)); // 11 console.log(f( 4, 2)); // 11 console.log(f( 4, 3)); // 1 console.log(f( 4, 4)); // 0 console.log(f( 5, 1)); // 26 console.log(f( 7, 4)); // 1191 console.log(f( 9, 5)); // 88234 console.log(f(10, 5)); // 1310354 console.log(f(10, 7)); // 47840 console.log(f(10, 10)); // 0 console.log(f(12, 2)); // 478271 console.log(f(15, 6)); // 311387598411 console.log(f(17, 1)); // 131054 console.log(f(20, 16)); // 1026509354985 console.log(f(42, 42)); // 0 ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` :Y@!d0>s=s ``` [Try it online!](http://matl.tryitonline.net/#code=OllAIWQwPnM9cw&input=Nwo0) ### Explanation Consider as an example inputs [`n=3`, `m=1`](http://matl.tryitonline.net/#code=OiVZQCFkMD5zPXM&input=Mwox). You can place a `%` symbol to comment out the code from that point onwards and thus see the intermediate results. For example, the link shows the stack after the first step. ``` : % Input n implicitly. Push [1 2 ... n] % STACK: [1 2 ... n] Y@ % Matrix of all permutations, one on each row % STACK: [1 2 3; 1 3 2; 2 1 3; 2 3 1; 3 1 2; 3 2 1] ! % Transpose % STACK: [1 1 2 2 3 3; 2 3 1 3 1 2; 3 2 3 1 2 1] d % Consecutive differences along each column % STACK: [1 2 -1 1 -2 -1; 1 -1 2 -2 1 -1] 0> % True for positive entries % STACK: [1 1 0 1 0 0; 1 0 1 0 1 0] s % Sum of each column % STACK: [2 1 1 1 1 0] = % Input m implicitly. Test each entry for equality with m % STACK: [0 1 1 1 1 0] s % Sum. Implicitly display % STACK: 4 ``` [Answer] ## CJam (21 19 bytes - or 18 if argument order is free) ``` {\e!f{2ew::>1b=}1b} ``` This is an anonymous block (function) which takes `n m` on the stack. (If it's permitted to take `m n` on the stack then the `\` can be saved). It computes all permutations and filters, so the [online test suite](http://cjam.tryitonline.net/#code=cX5dMy97fkBACgp7XGUhZnsyZXc6Oj4xYj19MWJ9Cgp-PX0v&input=MCAgIDAgICAxCjEgICAwICAgMQoxICAgMSAgIDAKMiAgIDAgICAxCjIgICAxICAgMQoyICAgMiAgIDAKMyAgIDAgICAxCjMgICAxICAgNAozICAgMiAgIDEKMyAgIDMgICAwCjQgICAwICAgMQo0ICAgMSAgIDExCjQgICAyICAgMTEKNCAgIDMgICAxCjQgICA0ICAgMAo1ICAgMSAgIDI2CjcgICA0ICAgMTE5MQ) must be rather limited. Thanks to Martin for pointing out an approximation to `filter-with-parameter`. ### Dissection ``` { e# Define a block. Stack: n m \ e# Flip the stack to give m n e!f{ e# Generate permutations of [0 .. n-1] and map with parameter m 2ew e# Stack: m perm; generate the list of n-1 pairs of consecutive e# elements of perm ::> e# Map each pair to 1 if it's a rise and 0 if it's a fall 1b e# Count the falls = e# Map to 1 if there are m falls and 0 otherwise } 1b e# Count the permutations with m falls } ``` Note that the Eulerian numbers are symmetric: `E(n, m) = E(n, n-m)`, so it's irrelevant whether you count falls or rises. ### Efficiently: 32 bytes ``` {1a@{0\+_ee::*(;\W%ee::*W%.+}*=} ``` [Online test suite](http://cjam.aditsu.net/#code=q~%5D3%2F%7B~%40%40%0A%0A%7B1a%40%7B0%5C%2B_ee%3A%3A*(%3B%5CW%25ee%3A%3A*W%25.%2B%7D*%3D%7D%0A%0A~%3D%7D%2F&input=0%20%20%200%20%20%201%0A1%20%20%200%20%20%201%0A1%20%20%201%20%20%200%0A2%20%20%200%20%20%201%0A2%20%20%201%20%20%201%0A2%20%20%202%20%20%200%0A3%20%20%200%20%20%201%0A3%20%20%201%20%20%204%0A3%20%20%202%20%20%201%0A3%20%20%203%20%20%200%0A4%20%20%200%20%20%201%0A4%20%20%201%20%20%2011%0A4%20%20%202%20%20%2011%0A4%20%20%203%20%20%201%0A4%20%20%204%20%20%200%0A5%20%20%201%20%20%2026%0A7%20%20%204%20%20%201191%0A9%20%20%205%20%20%2088234%0A10%20%205%20%20%201310354%0A10%20%207%20%20%2047840%0A10%20%2010%20%200%0A12%20%202%20%20%20478271%0A15%20%206%20%20%20311387598411%0A17%20%201%20%20%20131054%0A20%20%2016%20%201026509354985%0A42%20%2042%20%200). This implements the recurrence on whole rows. ``` { e# Define a block. Stack: n m 1a@ e# Push the row for n=0: [1]; and rotate n to top of stack { e# Repeat n times: e# Stack: m previous-row 0\+_ e# Prepend a 0 to the row and duplicate ee::* e# Multiply each element by its index e# This gives A[j] = j * E(i-1, j-1) (; e# Pop the first element, so that A[j] = (j+1) * E(i-1, j) \W% e# Get the other copy of the previous row and reverse it ee::* e# Multiply each element by its index e# This gives B[j] = j * E(i-1, i-1-j) W% e# Reverse again, giving B[j] = (i-j) * E(i-1, j-1) .+ e# Pointwise addition }* = e# Extract the element at index j } ``` [Answer] # Python, ~~55~~ 56 bytes ``` a=lambda n,m:n>=m>0and(n-m)*a(n-1,m-1)-~m*a(n-1,m)or m<1 ``` All tests at **[repl.it](https://repl.it/EAcw/3)** Applies the recursive formula on OEIS. Note that `+(m+1)*a(n-1,m)` is golfed to `-~m*a(n-1,m)`. (May return boolean values to represent `1` or `0`. Returns `True` when `n<0 and m<=0` or `m<0`.) [Answer] ## Mathematica, ~~59~~ 56 bytes ``` _~f~0=1 n_~f~m_:=If[m>n,0,(n-m)f[n-1,m-1]+(m+1)f[n-1,m]] ``` And here is a 59 byte version implementing the definition more literally: ``` Count[Count@1/@Sign/@Differences/@Permutations@Range@#,#2]& ``` [Answer] ## Python, 53 bytes ``` t=lambda n,k:n and(n-k)*t(n-1,k-1)-~k*t(n-1,k)or k==0 ``` Recursion from OEIS. Outputs Boolean `True` as `1` when `n==k`. [Answer] # MATLAB / Octave, 40 bytes ``` @(n,m)sum(sum(diff((perms(1:n))')>0)==m) ``` This is a port of my MATL answer, in the form of an anonymous function. Call it as `ans(7,4)`. [Try it at Ideone](http://ideone.com/VXYZY4). [Answer] # GameMaker Language, 62 bytes This is a recursive script `A` based on @Arnauld's formula. ``` n=argument0;m=argument1;return (n-m)*A(n-1,m-1)+(m+1)*A(n-1,m) ``` [Answer] # Perl, 98 bytes ``` sub a{my($b,$c)=@_;return$c?$c>$b?0:($b-$c)*a($b-1,$c-1)+($c+1)*a($b-1,$c):1;}print a(@ARGV[0,1]); ``` Based on the same property as Arnauld's answer. [Answer] # R, 72 bytes Recursive function following the logic on OEIS. ``` A=function(n,m)if(!m)1 else if(m-n)0 else(n-m)*A(n-1,m-1)+(m+1)*A(n-1,m) ``` This challenge turned out to be quite close between the different approaches I tried. For instance, using the wikipedia formula and looping over the sum resulted in 92 bytes: ``` function(n,m){s=0;if(!n)1 else for(k in -1:m+1)s=c(s,(-1)^k*choose(n+1,k)*(m+1-k)^n);sum(s)} ``` or the vectorized version for 87 bytes: ``` function(n,m)if(!m)1 else sum(sapply(-1:m+1,function(k)(-1)^k*choose(n+1,k)*(m+1-k)^n)) ``` and finally the brute force solution (103 bytes) that generates a matrix of all permutations by using the `permute` package and the function `allPerms`. This approach only works up to `n<8` though. ``` function(n,m){if(!m)1 else sum(apply(rbind(1:n,permute:::allPerms(n)),1,function(x)sum(diff(x)>0))==m)} ``` [Answer] ## Racket 141 bytes ``` (count(λ(x)(= x m))(for/list((t(permutations(range 1(+ 1 n)))))(count (λ(x)x)(for/list((i(sub1 n)))(>(list-ref t(+ 1 i))(list-ref t i)))))) ``` Ungolfed: ``` (define (f n m) (let* ((l (range 1 (add1 n))) ; create a list till n (pl (permutations l)) ; get all permutations (enl (for/list ((t pl)) ; check each permutation; (define rl (for/list ((i (sub1 n))) ; check if an element is a 'rise' (> (list-ref t (add1 i)) (list-ref t i)))) (count (lambda(x)x) rl)))) ; how many numbers are 'rises' (count (lambda(x) (= x m)) enl))) ; how many permutations had m rises ; i.e. Eulerian number ``` Testing: ``` (f 3 0) (f 3 1) (f 3 2) (f 3 3) (f 4 2) (f 5 1) (f 7 4) ``` Output: ``` 1 4 1 0 11 26 1191 ``` [Answer] # [Actually](http://github.com/Mego/Seriously), ~~21~~ 19 bytes This answer uses an algorithm similar to the one Dennis uses in his [Jelly answer](https://codegolf.stackexchange.com/a/96751/47581). The original definition counts `<` while I count `>`. This ends up being equivalent in the end. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O1LilahgO1xaZFgiaT4iwqNNzqNgTWM&input=Mgo0) ``` ;R╨`;\ZdX"i>"£MΣ`Mc ``` **Ungolfing** ``` Implicit input m, then n. ; Duplicate n. Stack: n, n, m R Push range [1..n]. ╨ Push all n-length permutations of the range. `...`M Map the following function over each permutation p. ;\ Duplicate and rotate p so that we have a list of the next elements of p. Z Zip rot_p and p. (order of operands here means the next element is first, so we need to use > later) dX Remove the last pair as we don't compare the last and first elements of the list. "i>"£ Create a function that will flatten a list and check for a rise. M Map that function over all the pairs. Σ Count how many rises there are in each permutation. c Using the result of the map and the remaining m, count how many permutations have m rises. Implicit return. ``` [Answer] # [Swift 3](https://github.com/apple/swift), 82 ~~88~~ Bytes [`func A(_ n:Int,_ m:Int)->Int{return m<1 ?1:n>m ?(n-m)*A(n-1,m-1)+(m+1)*A(n-1,m):0}`](http://swiftlang.ng.bluemix.net/#/repl/5815bbb41503df5a9307a0b7) Just the same recursive formula in a language that is definitely not for golf [Answer] # J, 28 bytes ``` +/@((!>:)~*(^~#\.)*_1^])i.,] ``` Uses the formula ![formula](https://i.stack.imgur.com/LEy3m.png) ## Usage ``` f =: +/@((!>:)~*(^~#\.)*_1^])i.,] 0 f 0 1 1 f 0 1 1 f 1 0 (f"+i.,]) 6 1 57 302 302 57 1 0 20x f 16x 1026509354985 ``` ## Explanation ``` +/@((!>:)~*(^~#\.)*_1^])i.,] Input: n (LHS), m (RHS) i. Range [0, 1, ..., m-1] ] Get m , Join to get k = [0, 1, ..., m] ] Get k _1^ Raise -1 to each in k #\. Get the length of each suffix of k Forms the range [m+1, m, ..., 2, 1] ^~ Raise each value by n * Multiply elementwise with (-1)^k ( )~ Commute operators >: Increment n ! Binomial coefficient, C(n+1, k) * Multiply elementwise +/@ Reduce by addition to get the sum and return ``` ]
[Question] [ A man lives in the north-west corner `(0, 0)` of a town with height `h` and width `w` . Everyday he walks from his home to the border `(?, w)` or `(h, ?)`. In the following example, the man goes to `(3, 3)` today. ``` (0, 0) +--+ + + . (0, 4) | + +--+--+ . | + + + + . | (3, 0) . . . . . (3, 4) ``` The man records a bit at each points (`+` in example above). Every time he reaches a point, he goes east if the bit is `1` and south otherwise. The bit is flipped after he leaves. For example: ``` Day 1: 1--0 1 1 Day 2: 0 1 1 1 Day 3: 1--1--1--1-- Day 4: 0 0 0 0 | | | 0 1--0 0 0 0 1 0 1 0 1 0 1--0 1 0 | | | 1 0 1--0 1--0 0 1 0 1 0 1 0 1--0 1 | | | Destination: (3, 3) Destination: (3, 1) Destination: (0, 4) Destination: (3, 2) ``` Given the size of the town and the man's record, calculate the man's destination after `n` days. ### Input: In the first line are three integers, `h`, `w` and `n`. In the following `h` lines are `w` integers, denoting the man's record. `h <= 1000, w <= 1000, n <= 1000000000` ### Output: Two integers, denoting the man's destination after `n` days. ### Sample Input: ``` 3 4 3 1 0 1 1 0 1 0 0 1 0 1 0 ``` ### Sample Output: ``` 0 4 ``` ### Sample Code: ``` #include <iostream> using namespace std; bool d[1000][1000]; int main(){ int h, w, n; cin >> h >> w >> n; for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) cin >> d[i][j]; int i, j; while(n--) for(i = 0, j = 0; i < h && j < w;){ bool &b = d[i][j]; d[i][j] ? j++ : i++; b = !b; } cout << i << " " << j << endl; } ``` ### Scoring: * Lowest byte count in UTF-8 wins. * If the running time of your code is independent of `n`, reduce your score by 50%. + **Don't** just calculate the results of all 1000000000 days or do anything similarly stupid to get this bonus. Find an efficient algorithm! [Answer] ## Python 2, 192 bytes \* 0.5 bonus = 96 To solve this problem efficiently, the key realization is that we can compute how many times each cell is visited based on the number of times the cells above and to the left are visited, without needing to determine the exact paths taken. Effectively, we simulate `n` trips at once and keep track of how many times each cell is used. Substantial improvement due to push-based approach inspired by [johnchen902's solution](https://codegolf.stackexchange.com/questions/25314/predict-where-the-man-will-go/25372#25372): ``` r=lambda:map(int,raw_input().split()) h,w,n=r() v=[n]+w*[0] x=y=0 for i in range(h): for j,b in enumerate(r()): if i-x==j-y==0:d=v[j]&1^b;x+=d;y+=1^d f=v[j]+b>>1;v[j]-=f;v[j+1]+=f print x,y ``` Previous, pull-based implementation: ``` r=lambda i:map(int,raw_input().split()) h,w,n=r(0) x=range(h) g=map(r,x) v=[w*[0]for i in x] v[0][0]=n-1 for i in x: for j in range(w):v[i][j]+=(i and(v[i-1][j]+(1^g[i-1][j]))/2)+(j and(v[i][j-1]+g[i][j-1])/2) i=j=0 while i<h and j<w:f=g[i][j]^v[i][j]&1;j+=f;i+=1^f print i,j ``` Original, ungolfed version: ``` h, w, n = map(int, raw_input().split()) grid = [map(int, raw_input().split()) for i in xrange(h)] # Determine the number of times each cell was visited in the first n-1 trips visits = [[0]*w for i in xrange(h)] visits[0][0] = n-1 for i in xrange(h): for j in xrange(w): if i: # Count visits from above cell visits[i][j] += (visits[i-1][j] + (not grid[i-1][j])) // 2 if j: # Count visits from left cell visits[i][j] += (visits[i][j-1] + grid[i][j-1]) // 2 # Flip the bits corresponding to each cell visited an odd number of times for i in xrange(h): for j in xrange(w): grid[i][j] ^= visits[i][j] & 1 # Figure out where the final trip ends i = j = 0 while i < h and j < w: if grid[i][j]: j += 1 else: i += 1 print i, j ``` [Answer] # Ruby, ~~159~~ 143 ``` n,*l=$<.read.split$/ i=->a{a.split.map &:to_i} x=y=l.map!{|k|i[k]} (n=i[n])[-1].times{x=y=0 (x+=f=l[x][y]^=1;y+=f^1)while x<n[0]&&y<n[1]} p x,y ``` The first line uses the `*` operator to grab the first line of input in one variable, and the rest of the input in another. Then an `i` function is defined to convert `"1 2 3 4"` into `[1, 2, 3, 4]`, which is applied to both `l` and `n`. (`x` and `y` are saved for later.) `n[-1]` is the last element of `n`, so the following block (the simulation) is executed that many times. First, `x` and `y` are initialized to zero (they are declared outside the block so that their scope is large enough), and then the simulation line is executed, ~~which is pretty self-explanatory, but here's some commentary anyway:~~ ``` l[x][y]<1? is it zero (less than one)? x+=l[x][y]=1 if it's zero, set it to one, and (conveniently) we can add that to x :y+=(l[x][y]=0)+1 otherwise, set it to zero, add one, and add that to y while x<n[0]&&y<n[1] keep doing this while we're still inside the array ``` Edit: new simulation line provided by Howard, thanks! I'm pretty sure I understand how it works but I don't have time to add an explanation, so one will be added later. Finally, `p x,y` outputs the numbers, and we are done! [Answer] ### GolfScript, 52.5 (105 characters with 50% bonus) ``` ~](;(\((2$(1,*+\@/{]zip 0\{~@@+.2$!+2/\@+.2/\@[\1&]}%zip~@;}%\;[{.0=0=\1${{1>}%}{1>}if.{~}%}do;].1-,n@0-, ``` The version is very efficient and can be [tested online](http://golfscript.apphb.com/?c=OyIzIDQgMwoxIDAgMSAxCjAgMSAwIDAKMSAwIDEgMCIKCn5dKDsoXCgoMiQoMSwqK1xAL3tdemlwIDBce35AQCsuMiQhKzIvXEArLjIvXEBbXDEmXX0lemlwfkA7fSVcO1t7LjA9MD1cMSR7ezE%2BfSV9ezE%2BfWlmLnt%2BfSV9ZG87XS4xLSxuQDAtLAo%3D&run=true) even for large values. It uses an approach similar to [user2357112's solution](https://codegolf.stackexchange.com/a/25322/1490). [Answer] # Delphi XE3 (437 bytes|| 897874 without bonus counted) When thinking about how to solve this with the bonus I thought of the following. If you walk 4 days cell 0,0 is changed 4 times. The cell on its right is changed twice aswell as the cell beneath it. If there is an uneven number of days and the number in the cell starts with 1 the cell on the right gets one more than the cell beneath, and the other way around if the cell is 0. By doing this for every cell you can see if the end value should be changed by: Cell was changed X times. if X mod 2>0 then change the cell. Results in the following code: **{Whispers at JohnChen902} do I get your upvote now? :P** ``` uses SysUtils,Classes,idglobal;var a:TArray<TArray<byte>>;b:TArray<TArray<int64>>;h,w,x,y,t:int16;n:int64;s:string;r:TStringList;tra:byte;begin r:=TStringList.Create;readln(h,w,n);h:=h-1;w:=w-1;for y:=0to h do begin readln(s);r.Add(StringReplace(s,' ','',[rfReplaceAll]));end;SetLength(a,h);SetLength(b,h);for y:=0to h do begin SetLength(a[y],w);SetLength(b[y],w);for x:=1to Length(r[y])do a[y][x-1]:=Ord(r[y][x])-48;end;b[0][0]:=n-1;for Y:=0to h do for X:=0to w do begin t:=b[y][x];if x<w then b[y][x+1]:=b[y][x+1]+iif((t mod 2=1)and(a[y][x]=1),(t div 2)+1,t div 2);if y<h then b[y+1][x]:=b[y+1][x]+iif((b[y][x]mod 2=1)and(a[y][x]=0),(t div 2)+1,t div 2);end;for Y:=0to h do for X:=0to w do if b[y][x]mod 2=1then a[y][x]:=iif(a[y][x]=1,0,1);y:=0;x:=0;repeat a[y][x]:=iif(a[y][x]=1,0,1);if a[y][x]=1then inc(y) else inc(x);until(y>h)or(x>w);write(Format('%d %d',[y,x]));end. ``` ### Ungolfed ``` uses SysUtils,Classes,idglobal; var a:TArray<TArray<byte>>; b:TArray<TArray<int64>>; h,w,x,y,t:int16; n:int64; s:string; r:TStringList; tra:byte; begin r:=TStringList.Create; readln(h,w,n); h:=h-1;w:=w-1; for y:=0to h do begin readln(s); r.Add(StringReplace(s,' ','',[rfReplaceAll])); end; SetLength(a,h); SetLength(b,h); for y:=0to h do begin SetLength(a[y],w); SetLength(b[y],w); for x:=1to Length(r[y])do a[y][x-1]:=Ord(r[y][x])-48; end; b[0][0]:=n-1; for Y:=0to h do for X:=0to w do begin t:=b[y][x]; if x<w then b[y][x+1]:=b[y][x+1]+iif((t mod 2=1)and(a[y][x]=1),(t div 2)+1,t div 2); if y<h then b[y+1][x]:=b[y+1][x]+iif((b[y][x]mod 2=1)and(a[y][x]=0),(t div 2)+1,t div 2); end; for Y:=0to h do for X:=0to w do if b[y][x]mod 2=1then a[y][x]:=iif(a[y][x]=1,0,1); y:=0;x:=0; repeat a[y][x]:=iif(a[y][x]=1,0,1); if a[y][x]=1then inc(y) else inc(x); until(y>h)or(x>w); write(Format('%d %d',[y,x])); end. ``` [Answer] # C++ 213 bytes \* 0.5 = 106.5 Here is my solution. It's similar to [user2357112's solution](https://codegolf.stackexchange.com/a/25322/15882), but there are several difference: * First, I *dispatch* visiting times to the right and bottom, instead of compute them from the top and left. * Second, I do everything (reading input, dispatching, tracking the man's location) simultaneously. * Third, I keep only one row of memory. ``` #include <iostream> int o[1001],h,w,r,c,i,j,t,u;int main(){std::cin>>h>>w>>*o;for(;i<h;i++)for(j=0;j<w;)std::cin>>t,u=o[j],o[j]/=2,u%2&&o[j+t]++,r-i|c-j||((u+t)%2?r:c)++,o[++j]+=u/2;std::cout<<r<<" "<<c<<"\n";} ``` Here is the ungolfed version: ``` #include <iostream> using namespace std; int o[1001]; int main(){ int h, w, n; cin >> h >> w >> n; o[0] = n; int r = 0, c = 0; for(int i = 0; i < h; i++) for(int j = 0; j < w; j++){ bool t; cin >> t; int u = o[j]; o[j + 1] += u / 2; o[j] = u / 2; if(u % 2) (t ? o[j + 1] : o[j])++; if(r == i && c == j) ((u + t) % 2 ? r : c)++; } cout << r << " " << c << endl; } ``` [Answer] # Python, 177 bytes My first try ever in Code Golfing, so sorry if I got something wrong here! Code used to grab the input based on user2357112's code. ``` l=lambda:map(int,raw_input().split()) h,w,n=l() m=[l() for i in[1]*h] while n>0: n-=1;x=y=0 while x!=w and y!=h: if m[y][x]>0:m[y][x]=0;x+=1 else:m[y][x]=1;y+=1 print y,x ``` Input: ``` 3 4 3 1 0 1 1 0 1 0 0 1 0 1 0 ``` Output: ``` 0 4 ``` [Answer] # R, 196 bytes \* 0.5 = 98 ``` f=function(h,w,n,x){I=J=rep(1,n);for(i in 1:h)for(j in 1:w){M=which(I==i&J==j);N=length(M);if(N){z=seq(1,N,by=2);if(x[i,j])z=-z;f=M[-z];s=M[z];I[f]=i;J[f]=j+1;I[s]=i+1;J[s]=j}};cat(I[n]-1,J[n]-1)} ``` Ungolfed: ``` f=function(h,w,n,x) { I = J = rep(1,n) for(i in 1:h) for(j in 1:w) { M = which(I==i&J==j) N = length(M) if (N) { z = seq(1,N,by=2) if (x[i,j]) z = -z f = M[-z] s = M[z] I[f] = i J[f] = j+1 I[s] = i+1 J[s] = j } } cat(I[n]-1, J[n]-1) } ``` Usage: ``` f(3,4,4,matrix(c(1,0,1,0,1,0,1,0,1,1,0,0),3)) 3 2 ``` ]
[Question] [ Consider the following triangle. ``` 1 23 456 7891 01112 131415 1617181 92021222 324252627 2829303132 33343536373 839404142434 4454647484950 51525354555657 585960616263646 5666768697071727 37475767778798081 ``` As you probably noticed, the first row is of length 1, and each row thereafter is 1 digit longer than to the previous one and that it contains the digits of the positive integers concatenated. You will be given an integer **N**. Your task is to find the sum of the digits that lie on **N**th row of the above triangle. # Rules * You can choose either 0 or 1 indexing. Please specify that in your answer. * **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply. * You can take input and provide output by **[any standard mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)**, and in any reasonable format. * This is **[OEIS A066548](https://oeis.org/A066548)**, and **[this sequence](https://oeis.org/A066547)** is the triangle itself (except that we do not remove leading zeros). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes (in every language) wins. Have fun golfing! # Test Cases ``` Input | Output 0 | 1 1 | 5 2 | 15 3 | 25 4 | 5 5 | 15 6 | 25 7 | 20 8 | 33 9 | 33 10 | 43 11 | 46 12 | 64 ``` Note that the above are 0-indexed. If you are looking for 1-indexed test cases, increment the input by 1. On a quite unrelated note, I recently changed my [profile picture](https://codegolf.stackexchange.com/users/59487/mr-xcoder?tab=profile) and that inspired me to write this challenge. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes 1-indexed ``` Σ!CNṁdN ``` [Try it online!](https://tio.run/##yygtzv7//9xiRWe/hzsbU/z@//9vaAQA "Husk – Try It Online") ### Explanation ``` ṁ Map then concatenate d Integer digits N Over the natural numbers CN Cut into lists of lengths corresponding to the natural numbers ! Index it Σ Sum ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes This could probably be quite a bit shorter. 1-indexed **Edit:** -7 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ``` lambda n:sum(map(int,"".join(map(str,range(1,n*n+1)))[~-n*n/2:][:n])) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0VyM3sUAjM69ER0lJLys/Mw/MLy4p0ilKzEtP1TDUydPK0zbU1NSMrtMFMvWNrGKjrfJiNTX/p@UXKWQqZOYpwFQammlacXEWFAFNU0jTyNTUUcj8DwA) [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` f n=sum[read[d]|d<-take n$drop(div(n*n-n)2)$show=<<[1..]] ``` [Try it online!](https://tio.run/##FcxBDoMgEAXQq8zCBTTFtK7hCD0BYTHJ0EiULwFtN96d2v3Lm7ktcV17fxNcO7KvkcVLOMWanZdIGKRuRUn6KNxgoCc9tHn7Omv9cxxD6JkTyFHm8qJSE3byCvfr0yes@aPpcbEf "Haskell – Try It Online") [Answer] # Haskell, ~~69~~ 64 bytes ``` n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x f=(1%(show=<<[1..])!!) ``` [Try it online.](https://tio.run/##FcoxCsMgFADQvaf4GQSlMWDHooUeoCewDj@YEKn@SjQkQ@5u6ZvfguUzxdgasePk2I9Cy5JjqM8KBIcpW7LrhN56d3ot0d05XZVg42U2XDFelu9utLZqGJzoOtESBgIDCfML@JtAPiCvgSpY6mEGcgL@Wd1c@wE) Saved 5 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)! Here's the less golfed version: ``` -- continuous stream of digits representing -- the concatenation of positive integers in -- order: 1234567891011... digitstream = show=<<[1..] -- sequence that yields the rows of the triangle triangle n xs |(a,b)<-splitAt n xs=a:triangle(n+1)b digitSum xs = sum[read[d]|d<-xs] -- sequence that sums up the digits in each row rowSumSequence = map digitSum (triangle 1 digitstream) -- the final function that just shows the value -- at a given index g=(rowSumSequence!!) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` nLS¹L£θO ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/zyf40E6fQ4vP7fD//9/QGAA "05AB1E – Try It Online") -1 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna). 1-indexing. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~47~~ ~~45~~ 42 bytes ``` {[~](1..$_²).substr(:1[^$_],$_).comb.sum} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/OrouVsNQT08l/tAmTb3i0qTikiINK8PoOJX4WB2VeE295PzcJKB4bu3/tPwiBaBKQ2OFaoXiRJB@DaACa4Xa/wA "Perl 6 – Try It Online") 1-indexed [Answer] # Mathematica, 96 bytes ``` (d=Flatten[IntegerDigits/@Range[#^2]];Last@Table[Tr@Take[d,{i(i+1)/2+1,(i+1)(i+2)/2}],{i,0,#}])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfI8XWLSexpCQ1L9ozryQ1PbXIJTM9s6RY3yEoMS89NVo5zig21tonsbjEISQxKSc1OiS/JDEHyM5OjU7Rqc7UyNQ21NQ30jbUAbOAhBGQWxsLlNIx0FGujdVU@x9QlJlXouCQFm1oFPv/PwA "Mathics – Try It Online") (in order to work on mathics "Tr" has to be replaced with "Total") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ²RDFṁRS$ṫCS ``` [Try it online!](https://tio.run/##y0rNyan8///QpiAXt4c7G4OCVR7uXO0c/P//fxMA) Uses 1-based indexing. ## Explanation ``` ²RDFṁRS$ṫCS Input: n ² Square R Range, [1, n^2] D Decimal digits F Flatten ṁ Reshape to $ Monadic chain R Range, [1, n] S Sum ṫ Tail C Complement, 1-n S Sum ``` [Answer] # R, ~~119~~ ~~109~~ ~~108~~ ~~93~~ 88 bytes starting to golf.... 1-indexed ``` function(n){for(i in 1:n+n*(n-1)/2){F=F+strtoi(substr(paste(1:n^2,collapse=""),i,i))};F} ``` thanks @Zachary. your presumption is correct :) shaved 1 byte tnx to @Andrius and 15 more tnx to @user2390246 @Giuseppe - tnx for the strtoi. new to me. 5 bytes down :) [Answer] # [Emojicode](http://www.emojicode.org/), 182 bytes ``` 🐖©a🚂➡🚂🍇🍦l➗✖a➕a 1 2🍮t🔤🔤🍮i 0🔁▶l🐔t🍇🍮➕i 1🍮t🍪t🔡i 10🍪🍉🍮s 0🔂g🔪t➖l a a🍇🍮➕s 🍺🚂🔡g 10🍉🍎s🍉 ``` Defines a method called © that takes a 🚂 and returns a 🚂. 1-indexed. [Try it online!](https://tio.run/##TY9NDoIwEIX3PUWPQPVEjRKCwbCAAwgb4qLqAioxpg2JMYEF7jRxyVF6gt4AZygkLmb65ud7mfr7eBdu4q0/Wn0prBYVRIEaG3JoudW33KgGHzcSz8ioq7lLblTFKaMr6PWp1eXDhehD6oHMjHxH4FKmM9gDEFI2r4sOmQYaHhYQR5wkE5sHkLrUKBlRTvmfQUJBfN05ZRM4GslTgmLERIjV5wwhAtv1ATehaod2/uHCf9ykfi3XMw8MyWTE1j8 "Emojicode – Try It Online") **Explanation:** **Note:** a lot of emoji choice doesn't make much sense in Emojicode 0.5. It's 0.x, after all. 0.6 will fix this, so if you want to learn this (because who wouldn't want to), I recommend waiting a moment. Emojicode is an object-oriented programming language featuring generics, protocols, optionals and closures, but this program uses no closures, and all generics and protocols can be considered implicit. The program operates on only a few types: 🚂 is the integer type and 🔡 is the string type. Additionally 👌s appear in conditions, which can take a value of either 👍 (true) or 👎 (false). There are currently no operators in Emojicode, so addition, comparsions and other operations that are normally operators are implemented as functions, effectively making the expressions use [prefix notation](https://en.wikipedia.org/wiki/Polish_notation). Operators are also planned in 0.6. ``` 🐖©a🚂➡🚂🍇 ``` © takes one 🚂 called `a` and returns a 🚂. ``` 🍦l➗✖a➕a 1 2 ``` Declare a frozen ("constant") `l` equal to the a-th triangular number (formula in prefix notation). This represents the length of the string of numbers we need to generate. ``` 🍮t🔤🔤 ``` Assign an empty string to the variable `t`. ``` 🍮i 0 ``` Assign `i = 0`. ``` 🔁▶l🐔t🍇 ``` While the `l` is greater than the length of `t` ``` 🍮➕i 1 ``` `i += 1` ``` 🍮t🍪t🔡i 10🍪 ``` Append the textual representation of `i` in base 10 to `t`. ``` 🍉 ``` End loop ``` 🍮s 0 ``` Assign `s = 0` ``` 🔂g🔪t➖l a a🍇 ``` Take a substring of `t` starting at `l - a` (`a - 1`th triangular number) of length a, iterate over all characters ``` 🍮➕s 🍺🚂🔡g 10 ``` Convert the character to string, parse integer in base-10, unwrap the optional (nothingness is returned if the string is not a number) and add to the `s` variable. ``` 🍉 ``` End loop ``` 🍎s ``` Return s ``` 🍉 ``` End method. [Answer] # PHP, 66+1 bytes ``` for($p=($n=$argn)*-~$n/2;$n--;)$r+=join(range(1,$p))[--$p];echo$r; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/ed501346c0e2ff7cb2c0cf8234d9fa0310fbf994). requires PHP 5.4 or later for indexing the expression. [Answer] # Pyth, 24 bytes ``` u+GsH<>jkS+*QQ2/*QhQ2hQ0 ``` Try it here: <http://pyth.herokuapp.com/> [Answer] # APL, ~~28~~ ~~26~~ 25 bytes ``` {+/⍎¨⍵↑⌽(+/⍳⍵)↑∊,/⍕¨⍳⍵×⍵} ``` Uses 1-based indexing [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v/f7VHbhGpt/Ue9fYdWPOrd@qht4qOevRoggc1AriaI39GlA@ROBcmDxA5PBxK1XNWP@qYC9bqBOGApQ4P//wE) ## How? * `⍳⍵×⍵`, 1 through the input squared * `⍕¨`, turn each element into a string * `∊,/`, concatenate them together * `(+/⍳⍵)↑`, grab the rows up to the input * `⍵↑⌽`, grab the desired row * `⍎¨`, turn each element into a number * `+/`, sum [Answer] # [Clojure](https://clojure.org/) v1.8, 154 bytes 1-indexed ``` (fn[n](loop[i 1 s(clojure.string/join""(take(* n n)(iterate inc 1)))](if(= i n)(apply +(map #(Character/digit % 10)(take n s)))(recur(inc i)(subs s i))))) ``` [Try it online!](https://repl.it/languages/clojure) # Explanation ``` (take(* n n)(iterate inc 1)) Take the first N*N numbers (clojure.string/join""...) Combine them into a string (loop[i 1 ...](if(= i n)...) Loop N times (apply +(map #(Character/digit % 10)(take n s))) Take N characters from the string, convert to integers and add them (recur(inc i)(subs s i)) Increment iterator, remove i characters from string ``` [Answer] # Java 8, ~~116~~ 98 bytes ``` n->{String t="";int r=0,i=0;for(;i++<n*n;t+=i);for(i=0;i<n;r+=t.charAt(i+++~-n*n/2)-48);return r;} ``` 1-indexed -18 bytes thanks to *@Nevay* **Explanation:** [Try it here.](https://tio.run/##LY/NTsMwEITvfYpVTzZuQgs9VNoYiQeglx4RB5O6sCXdRM6mEqrCq4dNUsk/8uxY38w5XENWN5HPx5@hrELbwlsgvi0AiCWmUygj7MfnJEBpxpMtqtLr1tVKECphDwweBs5ebgdJxF8gfrnE0Z78ekV@jac6GSTnCn5gFOfJTtI4ooIxOS95@R3Sqxh1ub9MfY9PNtvuLKYoXWJI2A84c5vus1LuHX@t6QgXjW5m@vsHBDvnnhgag/wGgQq/edbLufsU4PDbSrzkdSd5o1@lYsO5FrVTy7lnv@iHfw) ``` n->{ // Method with integer as both parameter and return-type String t=""; // Triangle-String int r=0, // Result-integer i=0; // Index-integer for(;i++<n*n; // Loop (1) from 0 to `n^2` (exclusive) t+=i // And append String `t` with all the numbers ); // End of loop (1) for(i=0;i<n; // Loop (2) from 0 to `n` (exclusive) r+=t.charAt(i+++~-n*n/2)-48 // And raise the sum `r` by the digits ); // End of loop (2) return r; // Return the resulting sum of digits } // End of method ``` [Answer] # R, ~~99~~, ~~105~~, 97 bytes ``` a=diag(N<-scan());a[upper.tri(a,T)]=strtoi(strsplit(paste(1:N^2,collapse=""),"")[[1]]);sum(a[,N]) ``` 1-indexed ungolfed version ``` a <- diag(N<-scan()) a[upper.tri(a, diag=TRUE)] <- strtoi(strsplit(paste(1:N^2, collapse=""), "")[[1]]) sum(a[,N]) ``` [Try it here!](https://tio.run/##DcUxCoAwDADAvzglUAXFSe0XOrmVCkGLFKqGJr6/OhxXaiV7JDrBLa3sdAPiTP5ljqXTkoDMisGKFn0S/AnnpMAkGqGf3DaY/cmZWKJtGjQ/7/sQcJb3AvLGBaxj/QA) thanks to @Giuseppe for saving 8 bytes [Answer] # [Perl 6](https://perl6.org), 44 bytes ``` {[+] (1..*).flatmap(*.comb).rotor(1..*)[$_]} ``` [Test it](https://tio.run/##TY47TsNAEIb7OcWvyEJ@hI3Xr4CsIFoaKroQIcfeSJbs7MreRKCQmp5rcAuOwkWM7Y0F1Xwz3z@aUaKpku7QChwTlqdUv@Eql4XAqjutvQ1szpjrsF2V6TpTtstyWW8d1kgtG@PW1svm3PV791q0Git431@W@/A4Ju3Fc@EtnJSGC0@9T0lV2R6eCRflEUFKO9lctq/vYJV7ddBzWOJViVyLAicCyhbDW7axzj89x8wM8fPx@Tee0bnzgXeAEx9rTIHpYwpHCGKKLiaeTDKZpQGfbkYIQ7qdgPsDRD3wERLiwQBJ9As "Perl 6 – Try It Online") ## Expanded: ``` { [+] # reduce the result of the following using &infix«+» ( 1 .. * ) # infinite range starting at 1 .flatmap( # map, then flatten *.comb # split into digits (100 ⇒ 1,0,0) ) .rotor( # break the sequence into pieces 1 .. * # start with 1 value, then 2 values, then 3, etc. )\ [$_] # index into that infinite sequence } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Ṭ€Ẏ0;œṗ²D€Ẏ$$⁸ịS ``` [Try it online!](https://tio.run/##y0rNyan8///hzjWPmtY83NVnYH108sOd0w9tcoHwVVQeNe54uLs7@P///4bGAA "Jelly – Try It Online") 1-indexed. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~15~~ 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ²Δr∑.δ∑⌡kmčr∑ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUIyJXUwMzk0ciV1MjIxMS4ldTAzQjQldTIyMTEldTIzMjFrbSV1MDEwRHIldTIyMTE_,inputs=MTI_) 1-indexed. While working on this I fixed a bug that made `∑` not work on number arrays and that `m` incorrectly took implicit input. Explanation: ``` ² square the input Δ get a range from 1 to that r∑ join as a string .δ create a range 0 - input-1 ∑ sum that ⌡ that many times do k remove the 1st character of the joined string m mold to the length of the input č chop into characters r∑ convert to numbers and sum ``` [Answer] ## C++, 180 bytes -17 bytes thanks to Zacharý Index start at 1 ``` #include<string> int s(int n){std::string t;int i=0,p=0;for(;i<=n;)p+=i++;for(i=0;t.size()<p;t+=std::to_string(++i));t=t.substr(0,p).substr(p-n);i=0;for(auto&a:t)i+=a-48;return i;} ``` [Answer] # [Pyth](https://pyth.readthedocs.io), ~~ 15 14 ~~ 13 bytes ``` s<>sMjkS^Q2sU ``` **[Try it here!](https://pyth.herokuapp.com/?code=s%3C%3EsMjkS%5EQ2sU&input=10&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15&debug=0)** or **[Check out the test suite.](https://pyth.herokuapp.com/?code=s%3C%3EsMjkS%5EQ2sU&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15&debug=0)** **13 bytes** alternatives: ``` ssM<>jkS^Q2sU ssM<>jkS*QQsU s<>sMjkS^Q2sU ``` --- # How? ``` s<>sMjkS^Q2sU Full program. Q means input. S^Q2 The range [1, Q^2]. jk Join as a String. sM Convert each character to integer. > All the elements of the above, but the first Q*(Q-1)/2. < All the element of the above but the last Q. s Sum. Output implicitly. ``` [Answer] # ><>, 141+2 Bytes ``` ::1+* 2,01\ @}})?/:0$\>$:@{{: :%a:/?(1:< ,a-]{+1[4 /~/ \+1~\ 1:<]{+1[+4@:-1\?( {1-}>{:}1(?\@1-@+ \0}~{{\\n; @:{{:<-1~$\!?)}} ~ ``` 1-Indexed +2b for -v flag Tio.run really doesn't seem to like my ><> programs recently... It can still be verified on <https://fishlanguage.com> though. Input goes in 'initial stack'. Edit: It turns out tio.run doesn't like it because it handles '[' and ']' differently to fishlanguage.com. fishlanguage.com reverses the stack when creating or removing a new stack, but tio.run doesn't. [Answer] # [Perl 5](https://www.perl.org/), 62 + 1 (-p) = 63 bytes ``` $_=eval(substr((join'',1..$_*$_),($_**2-$_)/2,$_)=~s/./+$&/gr) ``` [Try it online!](https://tio.run/##DcZBCoAgEEDRywxlpWMaLT1CZ5ACiUJUtFp29CY3//3ksp@JwBr3rJ6VeytXZuyMR2hbrhDB9mA7zqq9FnWl5rXmLRLlAI3cc0c0fTFdRwyFxDLjqEYS6Qc "Perl 5 – Try It Online") Result is 1 indexed. **How?** Concatenate more than enough digits together, then skip the irrelevant ones at the beginning (length of skip is sum of integers from 1 to `n-1`). Take the next `n` digits, place a `+` in front of each one, then evaluate that equation. [Answer] ## JavaScript (ES6), ~~78~~ 65 bytes ``` f= n=>eval([...(g=n=>n?g(n-1)+n:``)(n*n).substr(n*~-n/2,n)].join`+`) ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` 1-indexed. Edit: Saved 13 bytes thanks to @tsh. [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->n{s=[*1..n*n]*"" eval (1..n).map{s.slice!(0,_1).chars}[-1]*?+} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3HXTt8qqLbaO1DPX08rTyYrWUlLhSyxJzFDRAApp6uYkF1cV6xTmZyamKGgY68YaaeskZiUXFtdG6hrFa9tq1EHO2Fyi4RRsaxHKBaUMobRQLkV2wAEIDAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 1-indexed ``` ogU²õ ¬sUo x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=b2dVsvUgrHNVbyB4&input=Mw) ``` ogU²õ ¬sUo x :Implicit input of integer U o :Range [0,U) g :Index each into (0-based) U² : U squared õ : Range [1,U²] ¬ : Join s : Slice from 0-based index Uo : Range [0,U) x : Reduced by addition :Implicit output of sum of resulting array ``` ]
[Question] [ ### Motivation In [this](https://codegolf.stackexchange.com/questions/133767/element-wise-string-multiplication) challenge your task was to multiply two strings, this naturally introduces a way to take the square root of a string. ### How does it work? Given a string (for example `pub`) the first thing you need to do, is to determine the [ASCII code](https://en.wikipedia.org/wiki/ASCII#Printable_characters) for each character: ``` "pub" -> [112, 117, 98] ``` Next you map these codes to the range `[0..94]` by subtracting `32` of each value: ``` [112, 117, 98] -> [80, 85, 66] ``` Now you need to find for each value its root modulo `95` (eg. `40*40 % 95 = 80`, you could also pick `55`): ``` [80, 85, 66] -> [40, 35, 16] ``` And finally you'll map it back to the range `[32..126]` and convert it back to a string: ``` [40, 35, 16] -> [72, 67, 48] -> "HC0" ``` Indeed `"HC0" ⊗ "HC0" = "pub"` as you can verify with a solution from the other challenge [here](https://tio.run/##y00syfn/P9nYSLfA0jTG2Eg7@f//anUPZwN1HQUwVQsA "MATL – Try It Online"). --- The ones familiar with [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic#Integers_modulo_n) probably noticed that the square root modulo `95` does not always exist, for example there's no root for `2`. In such a case the square root of a string is not defined and your program/function may crash, loop indefinetly etc. For your convenience, here's the list of chars that have a square root (the first one is a space): ``` !$%&)+03489:>CDGLMQVW]`bjlpqu ``` ### Rules * You will write a program/function that takes a string (or list of chars) as an argument and returns *any* square root if it exists * You may assume that the input always has a square root * The input may consist of an empty string * The input will be in the printable range (`[32..126]`) * The output is either printed to the console or you return a string if the square root exists * In case the square root doesn't exist, the behavior of your program/function is left undefined * If you choose to print the root to the console trailing newlines or whitespaces are fine ### Test cases Note that these are not necessarily the only solutions: ``` '' -> '' 'pub' -> 'HC0' 'pull!' -> 'HC33!' 'M>>M' -> '>MM>' '49' -> '4%' '64' -> undefined 'Hello, World!' -> undefined ``` [Answer] # sh + coreutils, 58 bytes ``` tr '$%&)+0389:>CDGLMQVW]`bjpqu' 1u.#:BFO%+M/L2Aa,795d0@H=C ``` [Try it online!](https://tio.run/##S0oszvj/v6RIQV1FVU1T28DYwtLKztnF3cc3MCw8NiEpq6CwVF3BsFRP2crJzV9V21ffx8gxUcfc0jTFwMHD1vn/f66C0iQgzslR5PK1s/PlMrEEAA "Bash – Try It Online") The modular square root is typically not unique; we have 2 or 4 choices for each character except . We don’t need to translate , `!`, `4`, `l` since each is already a square root of itself. For the remaining characters, we choose images that don’t need to be escaped for the shell or `tr`. [Answer] # Python 3, ~~57~~ 56 bytes ``` lambda s:s.translate({k*k%95+32:k+32for k in range(95)}) ``` `translate` uses a mapping from "Unicode ordinals to Unicode ordinals". Thus, we don't need `chr`/`ord` conversions. Note: it doesn't crash when the char has no root. Saved 1 byte thanks to @jonathan-allan The value of the mapping is the greatest root in range 0..94 of the key. To have the least root (as in the examples), use: ``` lambda s:s.translate({k*k%95+32:k+32for k in range(95,0,-1)}) ``` (61 bytes) ``` >>> [s.translate({k*k%95+32:k+32for k in range(95,0,-1)}) for s in ['','pub','pull!','M>>M','49','64','Hello, World!']] ['', 'HC0', 'HC33!', '>MM>', '4%', '64', 'He33o,\x7f9or3d!'] ``` [Answer] # [Python 2](https://docs.python.org/2/), 80 bytes ``` lambda s:''.join([chr(i+32)for i in range(95)if i*i%95==ord(c)-32][0]for c in s) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYSl1dLys/M08jOjmjSCNT29hIMy2/SCFTITNPoSgxLz1Vw9JUMzNNIVMrU9XS1NY2vyhFI1lT19goNtogFqQyGaSyWPN/QVFmXolCmoa6uiYXnF1QmoTKzclRRBbwtbPzReabWAJ5/wE "Python 2 – Try It Online") Throws IndexError if no root exists. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 15 bytes ``` c@H+LDz%95+HÃbX ``` [Try it online!](https://tio.run/##y0osKPn/P9nBQ9vncPuhTaqWptoeh5uTIv7/VyooTVICAA "Japt – Try It Online") Saved a byte by looking at the 05AB1E answer (using `L` = 100 instead of `95`). Now Japt is the shortest, a quite rare occurance :-D ### Explanation ``` c@ H+LÇ ² %95+Hà bX UcX{H+LoZ{Zp2 %95+H} bX} Ungolfed Implicit: U = input string, H = 32, L = 100 UcX{ } Map each charcode X in the input to the following: Lo Create the array [0, 1, ..., 98, 99] Z{ } and map each item Z to Zp2 Z ** 2 %95 mod 95 +H plus 32. bX Find the first index of X in this array. This gives the smallest square root (mod 95) of (X - 32). H+ Add 32 to map this back into the printable range. Implicit: output result of last expression ``` [Answer] # Mathematica, 94 bytes ``` (R[x_]:=Min@Select[Range@45,Mod[#^2,95]==x&];FromCharacterCode[R/@(ToCharacterCode@#-32)+32])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfIyi6Ij7WytY3M88hODUnNbkkOigxLz3VwcRUxzc/JVo5zkjH0jTW1rZCLdbarSg/1zkjsSgxuSS1yDk/JTU6SN9BIyQfRcxBWdfYSFPb2ChWU@1/QFFmXomCQ5qCg1JBaZLSfwA "Mathics – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~17~~ 16 bytes ``` 95Ḷ²%95+32żØṖFyO ``` [Try it online!](https://tio.run/##y0rNyan8/9/S9OGObYc2qVqaahsbHd1zeMbDndPcKv3/H25/1LQm8v//aHV1HQX1gtIkCJWTowhi@NrZ@YJoE0sQaWYCIj2ABubrKITnF@WkKEI1KYA0xgIA "Jelly – Try It Online") (comes with test-suite footer) Saved 2 bytes by doing a complete rewrite. ~~Also the first time I've found use for `}`.~~ ### Explanation The code first calculates all square characters, and then maps them to their respective square roots. ``` 95Ḷ²%95+32żØṖFyO Main link. Argument: S (string) 95 Take 95. Ḷ Get the array [0, 1, ..., 94]. ² Square each to get [0, 1, ..., 8836]. %95 Get each square modulo 95 to get [0, 1, ..., 1]. +32 Add 32 to get [32, 33, ..., 33]. ØṖ Get the list of printables [" ", "!", ..., "~"]. ż Interleave with printables to get [[32, " "], ..., [33, "~"]]. F Flatten the mapping to [32, " ", ..., 33, "~"]. O Get the code point of each character in input. y Map the code points to the correct output characters using the map. ``` [Answer] ## JavaScript, 82 bytes *Collaborated with @ETHproductions* ``` s=>s.map(x=>(g=z=>z*z%95==x.charCodeAt(0)-32?String.fromCharCode(z+32):g(z+1))(0)) ``` *Input and output are in the form of a char array.* ### Test snippet ``` var f=s=>s.map(x=>(g=z=>z*z%95==x.charCodeAt(0)-32?String.fromCharCode(z+32):g(z+1))(0)) console.log(f([...""])); console.log(f([..."pub"])); console.log(f([..."pull!"])); console.log(f([..."M>>M"])); console.log(f([..."49"])); ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` vтLn95%žQykk33+ç? ``` The algorithm is very similar to the Jelly and Japt answer (Had something else before but that only got me to 19 bytes) ### Explanation ``` vтLn95%žQykk33+ç? v # For each character of the input... тL # Push [1..100] n # Square every element of the list 95% # And take it modulo 95 žQyk # Push the index of the current character in the printable ascii range k # Push the index of that in the list created earlier 33+ # Add 33 to the result ç # And convert it back to a character ? # Print the character ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7GKTT56lqerRfYGV2dnGxtqHl9v//19QmgQA "05AB1E – Try It Online") [Answer] ## Mathematica 82 Bytes ``` FromCharacterCode[Solve[x^2==#,Modulus->95][[1,1,2]]+32&/@(ToCharacterCode@#-32)]& ``` Using Solve's ability to do modular arithmetic. [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->s{s.chars.map{|c|((0..94).find{_1**2%95+32==c.ord}+32).chr}*""} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3HXXtiquL9ZIzEouK9XITC6prkms0NAz09CxNNPXSMvNSquMNtbSMVC1NtY2NbG2T9fKLUmqBTE2glqJaLSWlWohBqwoU3KKVCkqTlGIhAgsWQGgA) [Answer] # Mathematica, 60 bytes ``` FromCharacterCode[PowerMod[ToCharacterCode@#-32,1/2,95]+32]& ``` Anonymous function. Takes a string as input and returns a string as output. Errors on invalid input. [Answer] # [Perl 6](http://perl6.org/), 53 bytes ``` {[~] .comb.map({32+first *²%95==.ord-32,^95})».chr} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OrouVkEvOT83SS83sUCj2thIOy2zqLhEQevQJlVLU1tbvfyiFF1jI504S9NazUO79ZIzimr/WysUJ1YqKKnEK9jaKVSnKajE1yoppOUXKdTYFJQmKRSU5uQoKphY2ukoqPva2fmqW/8HAA "Perl 6 – Try It Online") [Answer] # [Go](https://go.dev), 120 bytes ``` func f(s[]rune)[]rune{ for i:=range s{for k:=0;k<95;k++{r:=rune(k*k%95+32) if r==s[i]{s[i]=rune(k+32) break}}} return s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVBLTsMwFBRbn-I1IsgmAVWkRU1KwgKkdkEk2NBFGylJG1chqVPsBCFFPgmbColDcBQ4Dc6HTb2Yefab5xm9j89tcfjeR-ss2iawi1KG0t2-4OWlRnel9lWV9GLy804rtgaKxTLgFUtIRzWiBYfUcXnE1LCom2vmuMNpdmOPp5lh1Fw1lRJn55lujw3riqCUAnddsUyDuoG-37ZinkSZlBLxpKw4AyE7_9-TWRugiYdJjd4iDjG40DxiAaLkKduSjur_2faGKe6yYkEIkUgI4bjLoJeGoRnuq7jFPB8o9j3PVzSyFVyPFMyTPC9MWBQ83yiBBoNT_YwYQ2s0sR3v7n724D89L4Iwfsn3r5UmUVEURw7zu2GLltU4eL7vNQ66goptEpqyZHNU36oTym674LjQ71cIqNGj-rekWAt1Ea6Y60FXAADWBVkxzVQ6tVczxl1BTBWpYSRRv8_DoeM_) [Answer] # JavaScript, 56 bytes ``` s=>Buffer(s).map(x=>(g=y=>y*y%95+32-x?g(++y):y+32)``)+`` ``` [Try it online!](https://tio.run/##HY3fCsIgHEZfxS4CzeZFf6ANNAi63BNU8LNNZcNUZov59Ca7@Q7fzTmj/MnYTUP4Vs73KmueIxe3WWs14UjYRwa8cIENT1ykXdrWZ3o8VMvVYEoTaVJ5BIBQgNx5F71VzHqDHwB7CPN7XWs3ha0QbcGphteqLZ3IguzvrseXIuAIIaC6VAkb/eDg6YDkPw) [Answer] # [Factor](https://factorcode.org/), ~~59~~ 55 bytes ``` [ [ 32 - 95 iota [ sq 95 mod = ] with find 32 + ] map ] ``` [Try it online!](https://tio.run/##HY29DsIwEIP3PMWRFcHAz1AQXRFDWRBT1eFIrxA1TdPkKoQQzx7SLrY/y5IbVNz7eL9drucDdMivtUf7pDBnaMlbMhBoGMmq1DpPzB/ntWU4CvEVUgrpxsesxiySF3leJNtlUvxiCSVsN7CCbA@6Z0wYhgm6voYTVPDW6abRtp5my1R06KCKkwZG1a5BGUIf/w "Factor – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 33 bytes ``` FiA*a YyAE((SQ,h)%95+32@?i)+32 Cy ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaUEqYSBZeUFFKChTUSxoKSU5NSszMkA/aSkrMzIgQ3kiLCIiLCIiLCJwdWIiXQ==) --- # [Pip](https://github.com/dloscutoff/pip), 37 bytes ``` FiA*a-32 YyAE((SQ_%95=i)FI,h)@0+32 Cy ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaUEqYS0zMiBZeUFFKChTUV8lOTU9aSlGSSxoKUAwKzMyIEN5IiwiIiwiIiwicHViIl0=) ]
[Question] [ Terence Tao [recently proved](http://terrytao.wordpress.com/2012/02/01/every-odd-integer-larger-than-1-is-the-sum-of-at-most-five-primes/) a weak form of Goldbach's conjecture! Let's exploit it! Given an odd integer `n > 1`, write `n` as a sum of up to 5 primes. Take the input however you like, and give output however you like. For example, ``` def g(o): for l in prime_range(o+1): if l == o: return l, for d in prime_range(l+1): for b in prime_range(d+1): if l+d+b == o: return l,d,b for c in prime_range(b+1): for h in prime_range(c+1): if l+d+b+c+h == o: return l,d,b,c,h ``` is Sage code that takes an integer as input, and returns a list of integers as output whose sum is `n`. By Tao's theorem, this will always terminate! **Input** An odd integer `n`. You decide how to take the input, but if it's weird, explain it. **Output** Rather open-ended. Return a list. Print a string. Gimme one, a few, or all. Leave crap lying around on the stack (GS, Piet, etc) or in a consecutive (reachable) memory block (BF, etc) in a predictable manner. For these later cases, explain the output. In all cases, what you return / print / whathaveyou should be a straightforward representation of a partition of `n` into primes with fewer than 6 parts. **Scoring** This is code golf, smallest byte count wins. **Bonus!** if the word 'goldbach' appears as a subsequence (not necessarily consecutive; just in order. Case doesn't matter) of your program subtract 8 points. The code above is an example of this. [Answer] ### *Mathematica*, 38 ``` IntegerPartitions[n,5,Prime~Array~n,1] ``` [Answer] ## C, 192-8 = 184 chars Contains "Goldbach" consecutively (excluding punctuation), and "Tao" as well. When the sum is less than 5 primes (i.e. always), prints zeros (16 = `0+0+0+3+13`) Read the number from standard input: `echo 30 | ./prog`. ``` #define T(x)for(x=0;x<=s;b=&x,c(++x)) G,o,l,d,*b,a;c(h) {(*b-1?h<3:++*b)||c(*b%--h?h:++*b);} main(s){ scanf("%d",&s); T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a)); } ``` Old version (179 chars), which can find only sums of exactly 5 primes (and therefore fails for x<10): ``` #define T(x)for(x=2;x<s;b=&x,c(++x)) G,o,l,d,*b,a;c(h) {h<3||c(*b%--h?h:++*b);} main(s){ scanf("%d",&s); T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a)); } ``` Explanation: `c` sets `*b` to the next prime (including `*b` itself if it's prime). `T` builds a for loop, which advances one of the variables `G,o,l,d,a` to the next prime. Within all for loops, we check if the sum matches, and print&exit if it does. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ~+.ṗᵐl≤5∧ ``` [Try it online!](https://tio.run/##ASQA2/9icmFjaHlsb2cy//9@Ky7huZfhtZBs4omkNeKIp///NzMx/1M "Brachylog – Try It Online") ``` ~+. Output (.) should sum to the input, ṗᵐ consist of all primes, l≤5 and have length ≤ 5. ∧ (Don't unify that 5 with the implicit output variable.) ``` [Answer] ## [J](http://jsoftware.com/), 29 ``` (#~y=+/@>),{5$<0,p:i._1 p:>:y ``` Assumes input is in `y`. Value of expression is list of boxes of list of 5 primes or 0 that sum to `y`. ``` y =. 16 (#~y=+/@>),{5$<0,p:i._1 p:>:y +----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------... |0 0 0 3 13|0 0 0 5 11|0 0 0 11 5|0 0 0 13 3|0 0 2 3 11|0 0 2 7 7|0 0 2 11 3|0 0 3 0 13|0 0 3 2 11|0 0 3 11 2|0 0 3 13 0|0 0 5 0 11|0 0 5 11 0|0 0 7 2 7|0 0 7 7 2|0 0 11 0 5|0 0 11 2 3|0 0 11 3 2|0 0 11 5 0|0 0 13 0 3|0 0 13 3 0|0 2 0 3 11|0 2 0 7 7|0 2 0 ... +----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------... ``` Not enough letters to earn any bonus points. [Answer] ## Ruby ~~138~~ ~~124~~ 117 - 8 = 109 ``` require'mathn' def g(o,l=[]) p l if l.inject(:+)==o#db (l.last||1..o).each{|d|d.prime?and g(o,l+[d])if l.count<5} end ``` Call with `g(<number>)`. Sample output: ``` [2, 2, 2, 2, 19] [2, 2, 3, 3, 17] [2, 2, 3, 7, 13] ... ``` Test: <http://ideone.com/rua7A> [Answer] ## PHP ~~143~~ 122 - 8 = 114 *EDIT: Saved a few bytes on output, removed the explicit function call.* ``` <?function g($o,$l,$d,$b){for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));)echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b ";} ``` Unrolled: ``` <? function g($o,$l,$d,$b){ for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));) echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b ";} ``` Call with `@g(<number>);` Sample output for `n=27`: ``` 2,2,2,2,19 2,2,3,3,17 2,2,3,7,13 2,2,5,5,13 2,2,5,7,11 2,2,23 2,3,3,19 2,3,5,17 2,3,11,11 2,5,7,13 2,7,7,11 3,3,3,5,13 3,3,3,7,11 3,3,5,5,11 3,3,7,7,7 3,5,5,7,7 3,5,19 3,7,17 3,11,13 5,5,5,5,7 5,5,17 5,11,11 7,7,13 ``` [Answer] # Ruby 2 -rmathn, 66 bytes - 8 = 58 ``` g=->o,*l{o==l.reduce(:+)?p(l):l[5]||b=Prime.each(o){|x|g[o,*l,x]}} ``` Heavily based on GolfWolf's answer, but since it's 6 years old I'm going to post my own instead of nitpicking. Advances in technology include the stabby lambda, using `reduce` instead of `inject` for the free `d`, a terse way of stopping at partitions of 5, and `Prime.each(o)`, which iterates over all primes less than or equal to `o` (and furnishes an `ach`). Maybe in another 6 years there'll be a better way of using the `b`. [Answer] ### Scala 137-8=129 ``` def g(o:Int)={val l=0+:(2 to o).filterNot(d=>(2 to d-1).exists(d%_==0)) for(b<-l;a<-l;c<-l;h<-l;e<-l;if(b+a+c+h+e==o))yield{(b,a,c,h,e)}} ``` After boothby's hint: eliminated one function call, allow to interpret 3 as the sum of 3 and nothing, remove input from output - saves another 20 chars. Bonus emphasizing: > > def **g(o**:Int)={val **l**=0+:(2 to o).filterNot(**d**=>(2 to d-1).exists(d%\_==0)) > for(b<-l;a<-l;c<-l;h<-l;e<-l;if(b+a+c+h+e==o))yield{(**b,a,c,h**,e)}} > > > Invocation and result: ``` println (l(17)) Vector((17,0,0,2,2,13), (17,0,0,2,13,2), (17,0,0,3,3,11), ... ``` The output repeats x for every list to sum up to x, and then shows the 5 summands. 0 for missing summand, i.e. 2+2+13. Ungolfed: ``` // see if there is some x, such that o%x is 0. def dividable (o:Int) = (2 to o-1).exists (x=> o % x == 0) // +: is a kind of cons-operator for Vectors def primelist (d: Int) = { val s = 0 +: (2 to d).filterNot (b => dividable (b)) for (a <- s; b <- s; c <- s; h <- s; e <- s; if (a+b+c+h+e == d)) yield {(a,b,c,h,e)} } ``` [Answer] # MuPAD 113 - 8 = 105 ``` g:=[0,ithprime(i)$i=1..n]:f:=_for_in:f(l,g,f(d,g,f(b,g,f(a,g,f(c,g,if l+d+b+a+c=n then print(l,d,b,a,c)end))))) ``` This version will also print all permutations of every solution: ``` 0, 0, 0, 0, 7 0, 0, 0, 2, 5 0, 0, 0, 5, 2 0, 0, 0, 7, 0 0, 0, 2, 0, 5 ... ``` And yes, it creates a way too long list `g`. Who cares? :-) Ungolfed version: ``` g:=[0].select([$1..n],isprime): for l in g do for d in g do for b in g do for a in g do for c in g do if l+d+b+a+c=n then print(l,d,b,a,c); end; end end end end end ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes (but very slow -- advice wanted) ``` ÆR;0x5Œ!ḣ€5¹©S€i³ị® ``` [Try it online!](https://tio.run/##y0rNyan8//9wW5C1QYXp0UmKD3csftS0xvTQzkMrg4GMzEObH@7uPrTu////xgA "Jelly – Try It Online") ``` ÆR;0x5Œ!ḣ€5¹©€i³ị® main link, takes one argument N ÆR get all the primes less than N ;0x5 add zero, and then repeat the entire list 5 times Œ! get all the permutations of this huge list (takes a long time!) ḣ€5 for each permutation, just take the first 5 numbers (this gives us all possible length-5 combinations of the primes plus zero, with some repeats) ¹© save that list to register S€ take the sum of every permutation in the list... i³ and find the index of our first argument N in that list of sums ị® then recall our list of permutations, and get the correct permutation at that index! ``` If you have any ideas to make it faster and shorter, please let me know! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` Ṅ'L5≤næA∧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYQnTDXiiaRuw6ZB4oinIiwiIiwiMjciXQ==) Outputs all possible sums. ## Explained ``` Ṅ'L5≤næA∧ # Takes a single integer n and returns a list of lists Ṅ # Push all the integer partitions (ways to sum to) of n ' # and keep only those where: L5≤ # the length of the partition is less than or equal to 5 (can also be 6<) ∧ # and næA # all integers in the partition are prime ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Hideous, and slow as hell! Will crap out on inputs higher than 5. ``` ÆõÃc fj à l§5 æ@¶Xx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xvXDYyBmaiDgIGynNSDmQLZYeA&input=NQ) ``` ÆõÃc fj à l§5 æ@¶Xx :Implicit input of integer U Æ :Map the range [0,U) õ : Range [1,U] à :End map c :Flatten f :Filter j : Prime à :Combinations l :Filter by length §5 : <=5 æ :Get the first to return true @ :When passed through the following function as X ¶ : U is equal to Xx : Sum of X ``` ]
[Question] [ While at work I spotted a nice and simple challenge. The job was to stock products in cargo units with a certain capability. Since an order can have various batches, coming in sequence from the production, we usually make a list of the pieces of those batches distributed in each cargo to make sure nothing is lost during the process. For example if we had this production sheet: ``` _____________ |ord: xxx | |_____________| | A | 30 pcs | | B | 38 pcs | | C | 12 pcs | ————————————— ``` and our cargo could contain 12 pieces we would make this list: ``` A | 12 12 6- B | -6 12 12 8- C | -4 8// ``` where **x**`-` indicates that **x** pieces will be stocked with `-`**y** pieces of the next line and **z**`//` indicates that after those **z** pieces there's a different order, thus nothing more we can add, and the last cargo is complete. # Task In this challenge you have to take a production sheet and a cargo capacity and output the distributed list. # Specifications Production sheet is taken in the form of a sequence of numbers representing the batches amounts. You have to output just the distributed amounts, we don't care about the additional signs `-` `//` mentioned above. Every batch must be distributed separately, so the output is a list of lists which you can represent in any reasonable format, just specify it and be consistent. It's guarantee that: * each batch has at least one piece * cargo units can contain at least one piece * an order( input list ) has at least one batch So you have to handle only positive integers( >0 ). ## input: a list of numbers representing the production sheet and a number representing the cargo capacity, each positive integers, in any reasonable method / order. ## output: the distributed list in form of a list of lists of numbers in any convenient method. * No extraneous numbers can appear in the output. * Order of obtained lists must be preserved. # Test cases ``` [30, 38, 12], 12 => [[12,12,6],[6,12,12,8],[4,8]] [1],1 => [[1]] [2],1 => [[1,1]] [1],2 => [[1]] [1,12,34],20 => [[1],[12],[7,20,7]] [5],1 => [[1,1,1,1,1]] [5],5 => [[5]] [300,120],84 => [[84,84,84,48],[36,84]] [1,2,3,4,5],6 => [[1],[2],[3],[4],[2,3]] [2,5,16,38,32,38,38,34,8,30,31,9,12],15 => [[2],[5],[8,8],[7,15,15,1],[14,15,3],[12,15,11],[4,15,15,4],[11,15,8],[7,1],[14,15,1],[14,15,2],[9],[4,8]] ``` # Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT, return it as a function result or error message/s. * Either a full program or a function are acceptable. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Sandbox](https://codegolf.meta.stackexchange.com/a/20702/84844) [Answer] # [J](http://jsoftware.com/), 36 34 27 24 bytes ``` (]<@(#/.~)/.[:I.#\&:-)I. ``` [Try it online!](https://tio.run/##RY3dCoJAEEbvfYohoRTGbX9tlYIoCIToolvTm0iim96gV7eZ1VrYGQ6H75t9jQuxGmBXwwoQJNQ0hYDj9Xwas267z9K1@ORr0daNSG/LusgbMeZJ8rg/36A0DGAkGE84KzIq4mx1tFoyc9XYmHMTuojehtuSknIyZShSD@wvpLig0aEq0Xg0Omx6FmlJNAorpK@Sy0FA30Pb6g5bR@PR096gcuERK8tkmHRwLO0csKwV01z7FyLx6Sp0fNeNXw "J – Try It Online") -3 bytes thanks to Bubbler Takes capacity as left arg and production sheet as right arg. ## how Use `12 f 30 38 12` as an example. * `(...)I.` A dyadic hook which expands the right arg into a mask with 30 `0`s, 38 `1`s, and 12 `2`s: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 ``` * `#\&:-` makes both arguments negative `&:-`. The `_12` on the left means "chunks of size 12" and `#\` will count each: ``` 12 12 12 12 12 12 8 ``` * `[:I.` Use the same expansion trick we used before to expand each of those in place into a unique integer: ``` 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 ``` * `].../.` Use the mask from step 1 to group the output of the last step into groups of size 30, 38, and 12: ``` 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 ``` * `(#/.~)/.` For each of *those* groups, self-group by value, returning a list of the number of items in each group: ``` _________ 12 ________ ________ 12 _________ ___ 6 ___ / \ / \ / \ 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 ___ 6 ___ ________ 12 _________ ________ 12 _________ _____ 8 _____ / \ / \ / \ / \ 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 _ 4 _ _____ 8 _____ / \ / \ 5 5 5 5 6 6 6 6 6 6 6 6 ``` * Finally, box each of those results `<@` because J doesn't allow ragged arrays. [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÇÑ▄≥Ué(ΘⁿGD$▀X9♦;ûΘ ``` [Run and debug it](https://staxlang.xyz/#p=80a5dcf2558228e9fc474424df5839043b96e9&i=12+%5B30,+38,+12%5D%0A1+%5B1%5D%0A1+%5B2%5D%0A2+%5B1%5D%0A20+%5B1,12,34%5D%0A1+%5B5%5D%0A5+%5B5%5D%0A84+%5B300,120%5D%0A6+%5B1,2,3,4,5%5D%0A15+%5B2,5,16,38,32,38,38,34,8,30,31,9,12%5D&m=2) ### Explanation: Unpacked source: ``` {i]*m$s/{|Rm:f{h}/mMHJ ``` * Implicit input: 12 [30 38 12] * `{i]*m`: Map over array: + `i]`: Push singleton array with index, e.g. [1] + `*`: Repeat by corresponding element, e.g. [1 1 1 1 1 ... (38 times)] * Result: [[<30 times 0>] [<38 times 1>] [<12 times 2>]] * `$`: Flatten: [<30 times 0> <38 times 1> <12 times 2>] * `s/`: Split into groups of maximum package size: [[<12 times 0>] [<12 times 0>] [<6 times 0> <6 times 1>] [<12 times 1>] [<12 times 1>] [<8 times 1> <4 times 2>] [<8 times 2>] * `{|Rm`: Run-length-encode each element: [[[0 12]] [[0 12]] [[0 6] [1 6]] [[1 12]] [[1 12]] [[1 8] [2 4]] [[2 8]]] * `:f`: Flatten: [[0 12] [0 12] [0 6] [1 6] [1 12] [1 12] [1 8] [2 4] [2 8]] * `{h}/`: Split into groups with equal first element: [[[0 12] [0 12] [0 6]] [[1 6] [1 12] [1 12] [1 8]] [[2 4] [2 8]]] * `m`: For each element, e.g. [[0 12] [0 12] [0 6]] + `M`: Transpose: [[0 0 0] [12 12 6]] + `H`: Second element: [12 12 6] + `J`: Join with spaces: "12 12 6" + Implicit print [Answer] # JavaScript (ES6), 57 bytes Expects `(capacity)(list)`. ``` n=>a=>a.map(g=v=>v?[x=v>m?m:v,...g(v-x,m=m-x||n)]:[],m=n) ``` [Try it online!](https://tio.run/##jVFNa8MwDL3vV4SebFBcfyRuVnD6Q7wcQteGjtopbTE59L9nsrNB1@QwWwgJ3hPvSV9taG/76@lyz33/eRiPZvSmbjGYay@kM8HUYWcHE2q3c9sAjLGOhHwAZ1w@PB6eNlvbYOfpuO/9rT8f2LnvyJEISYlVHFQFQjaUZtl6nVkrJLagG7AaprrCusDcvL0MQL5IxN83DVgEygUgzKHyvzMlj8goTxUT/gcI6ADTBiSHzaKUclHK9GeEcplQzoBVkdbJURJ/ElTh5lIUcY1KYzmj6mQFnUAB5dMlkBCtqLj/WINC6h/u6sOv6KvFKFlCCULH2yqZMgbKgHhvAe/Txcdv "JavaScript (Node.js) – Try It Online") ### Commented ``` n => a => // n = cargo capacity, a[] = production list a.map(g = v => // for each quantity v in a[]: v ? // if v is not equal to 0: [ // build a new array: x = v > m ? m // append x = min(m, v) : v, // ...g( // split the result of a recursive call: v - x, // subtract x from v m = m - x // subtract x from m; if the result is 0: || n // restart with a new cargo of capacity n ) // end of recursive call ] // end of array : // else: [], // stop the recursion m = n // start with m = n ) // end of map() ``` [Answer] # [Haskell](https://www.haskell.org/), ~~[67](https://codegolf.stackexchange.com/revisions/219398/1)~~ 66 bytes *1 byte saved by xnor* ``` f c|let(a:d)?b|a<=b=[a]:d?(b-a)|x:y<-(a-b:d)?c=(b:x):y;_?_=[]=(?c) ``` [Try it online!](https://tio.run/##FckxCoAwDADArzg4pGDB4hYNfUgpklRFsYqog0L/XhFuu5mvdYwx56kIKY43MA7KSuKOhBx7HCyIZpUefDsNrOX/QCD4KHzb3vbkPIENKm@87HScy36XU9E4U1c/4/MH "Haskell – Try It Online") I think this takes the cake as the most unreadable Haskell I have written. We have a pattern guard inside a pattern guard which I am actually surprised Haskell can even parse. Here it is ungolfed: ``` f c | let (a:d)?b | a <= b = [a]:d?(b-a) | x:y <- (a-b:d)?c = (b:x):y _?_ = [] = (?c) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` OÝI÷¹£εÅγ ``` [Try it online](https://tio.run/##AScA2P9vc2FiaWX//0/DnUnDt8K5wqPOtcOFzrP//1szMCwzOCwxMl0KMTI) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkAAUPrfzvf3hu8eHth9YdWnxu6@HWc5v/1@r8j46ONjbQMbbQMTSKBWOF6GhDIAvMMIIxgCRUCqhGx9gEyDUA801hKoAMUzDD2MAAqAYoa2EC1QHUoGMCkjWDGKpjqmNoBrLS2AhMApGJDpAAOsNQxxLiENPYWAA). **Explanation:** ``` O # Sum the first (implicit) input-list Ý # Push a list in the range [0,sum] I÷ # Integer-divide each by the second input-integer ¹£ # Split it into groups of the first input-list amount of values ε # Map over each group: Åγ # And run-length encode it, which will put the values and counts as two # separated lists to the stack, and since we're using a large map `ε`, it # will only leave the top one with the counts # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` UMθ…Eι⊞Oυκ⁰F⪪υηF…·⌊ι⌈ι⊞§θκ№ικIθ ``` [Try it online!](https://tio.run/##LY3BCsIwEETvfkWOG1jBtlYUT5JTD0XRY/EQarShaVLTpNSvj4kIy7AzzO5rO25bw1UINR@ZGQauH/BGwj6tEqwzI8QcJJKLn7rzKCx3xoJH0lOKZEPpcfU0lsBtVNKlvKOU/JJKt8pPchZXrl8Caqnl4AeQ8azmy3@P5fQYTq7SD7Ekch8LzHjtErVPgIuV0TE@OXhHH0LT5FhitsNij0X@0zhbjLLBIsMDZvkds/Ie1rP6Ag "Charcoal – Try It Online") Link is to verbose version of code. Outputs each entry on its own line with batches double-spaced. Explanation: ``` UMθ…Eι⊞Oυκ⁰ ``` For each element of the input array, push its index `n` times to the predefined empty list, and then replace it with an empty array, thereby creating a master batch list. ``` F⪪υη ``` Split the list of indices into batches of the given capacity and loop over each batch. ``` F…·⌊ι⌈ι ``` Loop over each value in the current batch. ``` ⊞§θκ№ικ ``` Push the value's frequency to the master batch list. ``` Iθ ``` Print the resulting list. [Answer] # [R](https://www.r-project.org/), ~~123~~ ~~80~~ 78 bytes *Edit: -43 bytes by ~~stealing tricks from~~ blatantly copying [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/219382/95126) (please upvote that one!)* ``` function(s,c)sapply(lapply(split((1:sum(s)-1)%/%c,rep(seq(a=s),s)),rle),`[`,1) ``` [Try it online!](https://tio.run/##fVLbTsMwDH3nKyqhSbF0EHWTXoY0foQHVoWCqpVRlu2Brx@OI6BbK1TLsevjS45zOI@t37Vv3fNLH46b8@tp74/9x94EeArtOA5fZkhHGIf@aAw/hNO7CXTHtLpfeRy60YTu07SbQAhEOAwdYfu0BdNFceONzZHZBhkXpCq7zTaPmZcIFxCpCN5USE4THScH3VyVYZLak9w5orhCgBerFP9X4TiGdYLLL4CI80ZdSwT1PLGctU/fIrKcIMs5wua5jJETGjcBNkKMilOabBXDCxeQ@eGkhVB7dQO9gFWO1YVdoBEluIKszBaqRaQrZI@WsUZkgafza9Eyqibtr5a4ipLmomkTf/qX044TRudgjuZP7l/WxNQm69/Xcf4G "R – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~93~~ 75 bytes * Original answer setting the Bounty score required under 93. ``` p,u;f(*l,c,z){for(p=u=0;++u,++p,z;u*=u!=c)--*l&&u-c||printf("%d%c",p,!*l?++l,z--,10:32,p=0);} ``` [Try it online!](https://tio.run/##ZZHbbtswDIbv/RRqghZWTCM6@jBD29WeYL0LclG4cRHATYy2BoqkefaMlCynw2BF@Gz@P8mQbd72T4eX63WAsenSVQ8tnPi5O76lgxudaLJshCwb4NSMKzfeuZbn@ap/eBjz9utreNsfPrp0cf983y5ggLtV/yvLejjlOUjxQysYnODN5YoydpSbrTtrAUxXwKS6ABukk6pJ1mv3k202UgGeYgubAgJXyAbvbeITKEogyaecvNliWFPYp9XfwzALzOw3Tv3vtz5MdbUhkXVKkIpNMsAO8SpBCSijqSCTJXkRirJYNTxRV8660tmbzsZ4FYYjsLwgVeUqM7dY4RD8MTQRXSBGXx2axp7BgM9fu@LfrqlpTZMkBo1OFvYh/MDAgiwAd4LrohsP1gJclJZQw7Qo4eS3timlxV/lV1SCtP7QiAyR9sPy36TfYRBQB1ISTbbZcCNKXc97T5bPu25/2LHH338e00/OuvS4XH7CQNf7/rQ7hg98Pb3gP@O8GcaP93TB8tuz4E3iJ/b6tD@wlJ@TkFLyCVQEHcFEsBGKCGWEKkIdQQqk5HL9Cw "C (clang) – Try It Online") * 75 bytes after some golfing. * stolen from @Arnaulds the 0 terminated list input. ``` p,u;f(*l,c){for(p=u=1;*l||*++l;++p)u++%c*--*l||printf("%d%c",p,9+!*l,p=0);} ``` [Try it online!](https://tio.run/##ZVLbisIwEH3vV2QVoZcRc21TSvZtv2B9Ex@k2kVwNbgKgvrt7iRpqsvSdDik58wczrSdtrvV/uvxsHBuujTfQZtdu8MxteZsWJPvbre8KHZNUdjsXBSTNp9O3aU9bvenLh1N1pN2BBbq4g211tCsuT/wEzmwxdJcBQUiNBDGgd6BWGYYb5LZzLyTxQIv8ZRLWJQQsEYssS4T34K7FiwoOboZhJEgHKFvLV4JMFDkSw9p@P8eKhBwupCBpgynjkd6IqBTLBVwClWUlU6mgqAMo0mcHZ7IrF6YlVFPpooMHaKiaIIGnjZaDlY1RuKPdPmIEmFU1sE8egcJ/YzalH/dO/PCJeswCNSSsCEa4lPASsAtCe6rdkFgoSAY1DCsjhr2Yt41Vfhqv7QKmPLHhSUdEj42f8f8VgPBeWDMoV42CJ7Ita6HPyEZrzfddr8h84/PeXrJSJcexuMLWCxZY8@nn3REps9nlDWJD@d7td2TNLsmQcmyHvAIRAQyAhVBGUEVgY6gjoBRRMn98Qs "C (clang) – Try It Online") * `u` is the total counter of pieces. * `p` is the partial counter. * `c` is cargo capacity * when u%c == 0 or current batch (\*l) is 0 we print the partial and reset it. [Answer] # [Perl 5](https://www.perl.org/), 116 bytes ``` sub{$c=pop;map[map y///c,/x+|y+|X+|Y+/g],join('',map[X,Y]->[$n++%2]x$_,@_)=~s/(.{$c})(.{1,$c})/$1\L$2/gr=~/x+|y+/gi} ``` [Try it online!](https://tio.run/##bVPfc5pAEH73r7g61wKyBY4DJHVIfW@neclDMpcbx1q1tI1QNDNaJf@62T2IEqewHh@73337w6OcV3/iI19kx/XT9z2fZWVRjh6npcIf2/m@PwN/6x527uHOPdy7/lLDryJf2ZYFxLqDe/3xWvGV674P9ZZPYDxxsue1b3soVjv4EEDA5@LhKw/9ZZU9N4L@Mq@Po96iqOweYwpNBsBkCkyEmhaWXTOlRAhoiQaVQINTxBGummlodwoNoqV33eHZDeKCH/6HL0heRhgMXqOgqBo1RBcMu9y4q93cF@G4CcddtwwCzBFoSKMmmmInxiJqSyYI31aEBUEEKJecS6KKJE2BMMg3LUMMIgEcowzNiob6gLOVAq6AuhExkl8vI0qCmEKlZrhDZBij7iNC0szB@ISZfkOg/EIQaredNpwRSV91/zFnb7I/7mxeVD/mFR6PaTmd5Zsd8Pm2dLIxn4xaCuPLYpOpD3xhjy/Zjm5YZZWvNmxd/bOJ7LD53@aFtNo@P7N@8ZuxvnditYFPrD8YDL7d3LKbL@8eVh2Cd9IY9eoefhskum@OPjBz@C1lea3DAiza8SyNYL/@mS82tlM7Xh8l6@ML "Perl 5 – Try It Online") ``` sub{ $c=pop; #capacity from last input map [map y///c,/x+|y+|X+|Y+/g], #split into same letters case-sensitive #...and convert into lengths as numbers join('',map[X,Y]->[$n++%2]x$_,@_) #stringify order into XXXYYYXX of given sizes =~ s/(.{$c})(.{1,$c})/$1\L$2/gr #lower case every other capacity =~ /x+|y+/gi #split into same letters case-insensitive } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` SḶṁẋ@:Œɠ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z/44Y5tD3c2PtzV7WB1dNLJBY@a1vw/vFwfSB2d9HDnDCAd@f9/dHS0sYGOsYWOoVEsGCtERxsCWWCGEYwBJKFSQDU6xiZArgGYbwpTAWSYghnGBgZANUBZCxOoDqAGHROQrBnEUB1THUMzkJXGRmASiEx0gATQGYY6lhCHmMbGAgA "Jelly – Try It Online") Port of @KevinCruijssen's [05AB1E answer](https://codegolf.stackexchange.com/questions/219331/package-distribution/219382#219382). ## Explanation ``` SḶṁẋ@:Œɠ€ Main dyadic link S Sum Ḷ Lowered range [0..n-1] ṁ Reshape like ẋ@ a list consisting of lists of the second argument repeated each first argument times : Integer divide by the second argument Œɠ Run lengths € of each ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~91 87 86~~ 83 bytes *Saved 4 bytes by switching to clang and using TABs, as suggested by @AZTECCO* *Saved 3 bytes thanks to @ceilingcat* Expects a zero-terminated list of quantities. ``` m,x;f(int*a,n){for(m=n;*a?printf("%d%c",x=*a>m?m:*a,(m=m-x?:n,*a-=x)?9:13):*++a;);} ``` [Try it online!](https://tio.run/##HYvRCoIwGIXvfYohCNv8B85l5IbtQaKLH2MiuBUWNBBfvbWCwwfn8J1RjAuGKSUP0Tg6hxdHCGxz95X6IRiO9rHm1dGyulVjCXHgePbW6@xlw4todQCOYojM9loqpnldo2FmT/lHPM6BMrIVhPwqXq5kIFsLHcgjqBOo9s@cA2Q0oCT0IFtodpM/jiIQ2TFT7OkzugWnZxLvLw "C (clang) – Try It Online") [Answer] # [Clojure](https://clojure.org/), 111 bytes ``` #(let[p partition-by](for[k(p last(for[i(partition-all %2(mapcat repeat %1(range)))j(p + i)]j))](map count k))) ``` [Try it online!](https://tio.run/##VVHbboMwDH3vV1iaKiWaJxHCrZq2H4nyQGmYoAwYTR/29cwOA1phEsfn@Dh2qm5o75ObxcXVUM8vonPejDCWk298M/Rv518r6mEyVzFCV958ODRiJ5RdB8dYfJdjVXqY3OhoOyoxlf2Xk1K2lPgKjbStlJZpUA333sOVsFkexGW4uR8w5gyVBXMwRkegC1CxRfrf4eOTQBXTATOLJsPFL8hPaLWUoYi6MUMkfoygWlnxM0uxkE4oHu0AGi5tcgpiHmjps9jyrUi6ImmI6Cgi0chikaxAQdcMlvCddcbQUp2KY0IK1NhDea6uuTv2US/9YIoqQ12gjsNKRpqoI9QKTximtV2FFUjVFGFKOSHBuLWEPR2aDDEVxrgQuKBS7P2nbQm7x9KnbfRkYpya3nc9iBroCflR/wA "Clojure – Try It Online") ]
[Question] [ # The challenge: Given four coordinates, each in x y form, your job is to find out whether or not the given coordinates form a rectangle, and output a truthy/falsey. ## Rules: * For the sake of simplicity, squares, lines (two identical pairs of coordinates) or dots (all four of the coordinates are the same) are **all counted as rectangles** * Coordinates for rectangles can be given in any order, for example this: ``` A----B | | D----C ``` and this: ``` A---B | | | | | | C---D ``` are both rectangles. * Rectangles can be rotated, so they won't always be parallel to x and y axis. * You may take input in any form you like as long as the order for each coordinate is not mixed: [x,x,x,x,y,y,y,y] is not acceptable, where as [x,y,x,y,x,y,x,y] or [(x,y),(x,y),(x,y),(x,y)] is fine. * Complex numbers are a valid form of input * This is codegolf, so lowest byte count wins. ## Test cases: ``` [0,2, 3,2, 3,0, 0,0] Truthy [3,5, 2,0, 0,2, 5,3] Truthy [6,3, 3,5, 0,2, 3,0] Falsy [1,4, 5,2, 4,0, 0,2] Truthy [0,0, 0,0, 3,2, 4,0] Falsy [1,1, 1,1, 1,1, 1,1] Truthy [1,4, 100,1, 100,1, 1,4] Truthy ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~88~~ \$\cdots\$ ~~54~~ 43 bytes ``` lambda l:len({abs(sum(l)/4-z)for z in l})<2 ``` [Try it online!](https://tio.run/##VVHdboMgFL73Kc7dgY12/m1LmrnLPUHvqBfaaepCrRFMao3P7jiw1VQi4Xx/cKAbzenSJkudHRZVnMvvAtROVS2bilIzPZyZ4i/p5sbrSw83aFpQM/@IF1NpoyEDRAxkKGKRuD@kkcO@H8xpDGQiXi1MYGxXyUq8WS2R3mkdX4XSFo9E6iypN62G0Ee7bdIHw8NYDZQUhSGBfhbpnaRDB33GBjwM8Xt6RAF@GSXIA9eXZLJWl8KwhgO13lDrxVabvukYyhz5VneqMQwF8lzgHklQenEhSqrY8V8D6Ikjwe7q/pLuKYcWOc8DEhlROZneBWA/Rae5Pkc/T6PLuIqR6Jt1Gxm6tzJ8F@fCyGitbBaZqZXaPqErur5pDatxUjNsPmHSM0y91FlW5TPy5Rc "Python 3 – Try It Online") **How** Calculates the distances from the quadrilateral's centre of mass to all of its vertices and tests if they're equal. **Input** The four vertices as a sequence of complex numbers in any order. **Output** `True`/`False` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) A port of [Noodle9's Python answer](https://codegolf.stackexchange.com/a/203100/53748) with a slight adjustment for golfing purposes. ``` ×4_SAE ``` A monadic Link accepting a list of four complex numbers which yields `1` if they form a rectangle or `0` if not. **[Try it online!](https://tio.run/##y0rNyan8///wdJP4YEfX////Rxtqm2TpKJhqGwFJE20DIGkAZMcCAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wdJP4YEfX/4fbHzWt@f8/OtpA2yhLR8EYShoASQMgGculE22sbQrkGUHFQPKm2sZgGTMgDVJtCpcxhuox1DYBqwOJmcB1gmQM4GbDbDOB6zEE8tBJhGmGBgYQURgNFI3ligUA "Jelly – Try It Online"). ### How? Checks that all four coordinates are equidistant from the centre of mass of the uniform density quadrilateral. ``` ×4_SAE - Link: list of complex numbers, C 4 - literal four × - (C) multiply (4) (vectorises across C) S - sum (of C) _ - (C×4) subtract (sum(C)) (vectorises across C×4) A - absolute value (vectorises) E - all equal? ``` --- Note this still works given an equilateral triangle with a repeated coordinate (it would skew the centre of mass toward the repeated coordinate). --- The equivalent change to Noodle9's program would be: ``` lambda l:len({abs(z*4-sum(l))for z in l})<2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes Port of [Noodle9's Python answer](https://codegolf.stackexchange.com/a/203100/53748). 05AB1E doesn't have complex numbers, so it ends up a bit long. ``` εIøO4/-}nOË ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3FbPwzv8TfR1a/P8D3f//x8dbahjEqujEG2qYwSiTHQMQJQBkBcLAA "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~115~~ ~~108~~ 107 bytes This solution finds if any permutation of A,B,C,D results in a rectangle. Output is correct for all test cases **except test case 3 which is not a rectangle due to corners not equal to 90 degrees.** ``` lambda a,b,c,d:g(a,b,c,d)+g(a,c,b,d)+g(a,b,d,c) g=lambda a,b,c,d:b+d-a-c==((b-a)*(d-a).conjugate()).real==0 ``` [Try it online!](https://tio.run/##XY1BboMwEEX3nMLKyk4GRIBUVSRve4LuKAtjDHFljGU7VVHVs1MbEqWtRrb@/Plvxsz@Muly6enbotjYdgwxaIFDdx7wTZFDlDw0NxkEcJIM9B/RHrqUpZxSjNuUkT0OLcn4pN@vA/MCE5JZwRSl@SJHM1mP3OySpJ8sUlILJHU0Muc7qc8JQg44omhkBjtvg22lgTWZOaOkD/tiKETEB1PY3buaT6NR4hO7WjYQvsOxIShekfGEZXoQOIdnKEgTEGOl9rjHe0cA9bv6i383O7LUORRQri@P1aBXe/WXOalLOAU7mkVQ5WPwFLJxuJG/iCNUK1Nt1GOQb7vXO1UkXphyYiX@1J34AQ "Python 3 – Try It Online") **Input**: 4 complex numbers representing the 4 coordinates. **Output**: a positive integer if input is a rectangle, or `0` if input is not. *105 bytes if output can be `0` for rectangle, and non-zero for non-rectangle.* ``` lambda a,b,c,d:g(a,b,c,d)*g(a,c,b,d)*g(a,b,d,c) g=lambda a,b,c,d:b+d-a-c or((b-a)*(d-a).conjugate()).real ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes Input is an array of 4 complex numbers, again. ``` ->l{l.map{|z|(l.sum/4.0-z).abs}.uniq.size<2} ``` [Try it online!](https://tio.run/##VVDbToQwEH3nKyZslKKlctOHjawfghtTdksk6SJSMBHoH/jmq/6cP4KdsjxsJu1pzpwznZm2Lz7nMpuDnRwlO/FmnIaJSKb6013KwmDwGS@UZn1dvTNVDeIx1nMnVKcgg6vRyUMa08SeEGMPXdsLJ0/ovSGRis0rWekHo8PU4jLqkktl@Iim1pAullUeLkXtB@mF/CJWOVaJwhCp5abpOaUdxzbNVNdWDVONrDriPteujzOT661lfCb44RWObzBxCmJyAFqBg5aMiA8uCV8UL0pWB0Fia4bRqosJONxCVMENFKB9423A3YxcQ7CDzWgK6QUgy4AIvD3szfPhCby/n28PtgZ/vzztOqI@zjnOs6eQm8Ug4AIM4Hr8@R8 "Ruby – Try It Online") Port of @Noodle9's Python answer. [Answer] # APL2: 33 bytes Yet another port of [Noddle9's answer](https://codegolf.stackexchange.com/a/203100/78264), this time in APL2. Prerequisites: 1. This is code is ⎕IO-dependant since it uses *Partition with axis*. This example in `⎕IO=0` 2. The list of coordinates is stored in variable C. `D≡⌽D←↑+/(M-+/¨.25×M←⊂[1]⍉4 2⍴C)*2` The result is either `1` for *true* or `0` for *false*. ### An example If `C` is the vector `3,5,2,0,0,2,5,3` or rather `3 5 2 0 0 2 5 3`, then the first thing that happens is that `4 2⍴C` turns it into a 4x2 matrix: ``` 3 5 2 0 0 2 5 3 ``` Then `⍉` transposes that matrix and `⊂[1]` turns it into a vector of 2 vectors (x & y). This is stored as `M`: `((3 2 0 5)(5 0 2 3))`. Next `M` is multiplied with `0.25` and summed element-wise: (this is what `+/¨ does)` `(2.5 2.5)`. Now we subtract this from `M` and square the differences: `(M- ...)*2` (yes, `*` is "power"). We now have: `(0.25 0.25 6.25 6.25)(6.25 6.25 0.25 0.25)`. This is summed by the `+/` outside the brackets and we get `((6.5 6.5 6.5 6.5))`. Sadly we have a 4-element vector inside another structure so we have to "spend" a character to remove the outer shell: `↑`. The inner vector is assigned to variable `D`. Finally we use `≡` to compare `D` to its reverse `⌽D` thereby checking if all items are equal. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 bytes ``` {1=≢∪|⍵-+/⍵÷4} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OAZLWh7aPORY86VtU86t2qq60PJA9vN6n9/78EJAnkAWWLgMy0R727rNTTEjNz1IEsoHjRo@4W9fxs9VougywjBWMwNlAwAOISBUMu4yxTBSMw30jBNMsYLGYGpEHiBlC1JQoGXIZZJkB5IwUTqFqQOgOoOcZQcYg6QwVkDFIH0mtoYAASgZBAPlAcAA "APL (Dyalog Unicode) – Try It Online") input: complex numbers. distances from centre of gravity must match. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` Λ=mO½´×oΣzo□- ``` [Try it online!](https://tio.run/##yygtzv7//9xs21z/Q3sPbTk8Pf/c4qr8R9MW6v7//z862lDHJFYn2lTHCEia6BgASQMgOxYA "Husk – Try It Online") I'm not sure if this is correct. It takes Euclidean distance between all pairs and checks if the resulting array is symmetric. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ƛ?ÞTvṁ-²∑√;≈ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%3F%C3%9ETv%E1%B9%81-%C2%B2%E2%88%91%E2%88%9A%3B%E2%89%88&inputs=%5B%5B0%2C0%5D%2C%5B0%2C1%5D%2C%5B1%2C1%5D%2C%5B1%2C0%5D%5D&header=&footer=) ``` ƛ ; # Map to... ? # Input ÞT # Transposed vṁ # Take the average of each (center) - # Get the x and y distances to the center ²∑√ # Pythagoras to get abs. dist. to center ≈ # Are all equal? ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 77 bytes ``` cat>t;join -j3 t t|xargs -I% dc -e%sDsClD-d*sqlC-d*lq+p|sort|uniq -c|grep 2\ ``` (There's a space at the end, after the backslash.) [Try it online!](https://tio.run/##DcUxDoQgEAXQnlP8xkYziYFYmWyjzd5hGxYNYogKM5tswd3R17yv5a1WZ@Ul436GA7QbCKT8bfYMejdYHGhteOYpzrS0nOL0FFN3FT6zlN8REsgVn9cL@oNaDQal0aseWg0wNw "Bash – Try It Online") [Or try the entire test suite online.](https://tio.run/##VU6xboMwEN39FU@REyWtrDhAupSyJKpUKWPHLsZ2gMiCgKHt4H@nxl5SnXz33r13dy6FreefujEagxYKFwKozidAy7oDa7GiF7wVWIVmMAmUkFDQuKJCnee590R9G6aoAC0Dj1uoBFWPXINeH3kFWu/cdpZiLMbXW9e0YLcUI0b3K4bKgn2soSSYXtuzPZkzU0@2NydfTP98d7YbRje1TQ8mXTXoO5IvzOHArtgr/b1vJ2Ow2cR778JYDeci@xwmvXxGda2eORKk4fElSIqjZwtOPErJi1eWXvRxckAWHFn0EB7nwo4s6P8i@A@cLzhmZOQP) The input is in the form: ``` x1 y1 x2 y2 x3 y3 x4 y4 ``` (with a newline after each point). The output is the exit code: 0 for falsey, 1 for truthy. --- **Here's how it works** (there are no complex numbers available in bash): 1. The `join` computes all the pairs of points. There are 4 points, so there are 16 pairs of points. (This includes each pair in both orders, and it even includes pairs where the two points are the same.) 2. The `xargs` command uses `dc` to compute the square of the distance between each pair of points. We now have a list of all the squares of the distances between pairs of the points. 3. Now, `sort|uniq -c` computes how many times each value appears in the list of squared distances. 4. The original four points form a rectangle iff no value appears exactly twice in the list. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), 32 bytes ``` Equal@@Norm/@(r=#;Mean@r-#&/@r)& ``` This is a port of [Noodle9's Python answer](https://codegolf.stackexchange.com/a/203100/53748). I start by determining the centroid of the four points, which is their average position in space, by taking the mean of the four vectors corresponding to each. [N.B.: If the points had mass, and their masses were identical, this would give their center of mass.]. I then subtract each point from the centroid, and determine the lengths (norms) of the four resulting vectors. I then test to see if all four norms are the same. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27737WwNDHHwcEvvyhX30GjyFbZ2jc1Mc@hSFdZTd@hSFPtf0BRZl6JQ3p0dbWBjoJRrY5CtTGCNgDRBiC6NpYLoRIoYwqSMUKoAOsw1VEwRlVpBhKBmGWKrNIYw0xDHQUTqBlgFSbIZqOoNEB2F5J7TbCZaQiSwUpjtd3QwACmBsECydXG/gcA) Alternately, the following is also 32 bytes. Though this one is non-competing, since the challenge was posted ~May 2020, and this uses new syntax (`|->` as a shorthand for `\[Function]` ) that wasn't introduced until v. 12.2 of Mathematica, which was released in Dec. 2020: ``` Equal@@Norm/@(r|->Mean@r-#&/@r)& ``` Interestingly, the above doesn't work in tio.run , because it's using [version 12.0.1 for Linux x86 (64-bit) (October 16, 2019)](https://tio.run/##y00syUjNTSzJTE78n2b7XyUstag4Mz/vf0BRZl6JQ9p/AA). ]
[Question] [ [Husk](https://github.com/barbuz/Husk) is a quite new golfing language, created by PPCG users [Leo](https://codegolf.stackexchange.com/users/62393/leo) and [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb). It has begun being more and more competitive, often staying close or even beating languages known to be very terse, such as Jelly and 05AB1E. Let's list some of the golfing techniques that are somewhat specific to Husk. As always, please post one tip per answer. [Answer] # Use the return value from predicates In Husk, functions that test their inputs for some property will usually return a meaningful result in truthy cases, as any positive integer is truthy. **Examples:** ``` ≠ Numbers: Absolute difference Chars: Absolute difference of code points Lists: First Index where the differ Comparisons <, >, ≤, ≥: For strict comparisons: Numbers,Chars: max 0 (the appropriate difference¹) Lists: The first index where the comparison between the two lists is true For non-strict comparisons: Numbers,Chars: max 0 (the appropriate difference + 1) Lists: Either the result of the strict comparison or, if they are equal, the length of the list + 1 ṗ Index into the list of prime numbers V The index of the first element for which the condition is true € The first index of that element/substring in the list £ Works like € & Given two arguments of the same type will return the second argument if false, otherwise will return the first argument | Given two arguments of the same type will return the second argument if true, otherwise will return the first argument ¦ Return the quotient if divisibility holds Λ,E,Ë Will all return length+1 in truthy cases Char predicates: □,±,√,D,½ will each return the codepoint of its argument on truthy cases ``` ¹ **appropriate difference** means difference of code points for chars. It also refers to the argument order. i.e For `<x y`, would be `x-y` [Answer] # Use overflowing line labels As you may already know, `[₀-₉]+|[₀-₉]` is regex for the syntax to call a different line than the one you're currently in. This tip is especially useful if you want a function defined on a specific line to be called as an argument of more than one of the functions in the table below, or as an argument to one or more of the functions below and by itself. Function table: ``` +----------+----------+ |Index |Function | +----------+----------+ |1 |´ (argdup)| +----------+----------+ |2 |` (flip) | +----------+----------+ |3 |m (map) | +----------+----------+ |4 |z (zip) | +----------+----------+ |5 |S (hook) | +----------+----------+ ``` Lines in your code are labeled with their respective 0-based indices, from top to bottom. If **M < N**, where **M** is the label and **N** is the number of lines in your code, the label just represents the function defined at line **M**. If **N ≤ M < N \* 6**, it represents the function from the table above at index **⌊M ÷ N⌋** with the function defined at line **M mod N** as its first argument. If **N \* 6 ≤ M**, an index error is raised. [Answer] # Uses of `Γ` The main use of the built-in `Γ`, known as *pattern matching on lists* or *list deconstruction*, is to split a list into a head and tail, and apply a binary function on them. This corresponds to the Haskell pattern matching idiom ``` f (x : xs) = <something> f [] = <something else> ``` where `<something>` is an expression containing `x`, `xs` and possibly `f`. There are 4 overloadings of `Γ`, each of which works a little differently. ### `list` The first overloading, `list`, takes a value `a` and a binary function `f`. It returns a new function that takes a list, returns `a` if it's empty, and calls `f` on the head and tail if it's nonempty. For example, `Γ_1€` takes a list, returns `-1` if it's empty, and the index of first occurrence of the first element in the tail if not. ### `listN` The second overloading, `listN`, is similar to `list`, except that `a` is omitted and the default value of the return type is used instead. For example, `Γ€` is equivalent to `Γ0€`, since the default numeric value is `0`. In practice, `listN` is used more often than `list`, since the default value is either irrelevant or exactly what you need. A common pattern is `Γ~αβγ`, where `αβγ` are three functions; this applies `β` to the first element and `γ` to the tail, and combines the results with `α`. It was used e.g. in [this answer](https://codegolf.stackexchange.com/a/150849/32014). Other patterns include `Γo:α` for applying `α` only to the first element, and `Γ·:mα` for applying `α` to all elements except the first. The latter was used in [this answer](https://codegolf.stackexchange.com/a/153238/32014). ### `listF` The third overloading is a bit more involved. Like `list`, it takes a value `a` and a function `f`, and returns a new function `g` that takes a list. However, this time `f` takes an extra function argument, which is `g` itself, and can call it on any value (including, but not limited to, the tail of the input list). This means that `listF` implements a general *recursion scheme* on lists. `listF` is not used very often, since explicit recursion with `list`/`listN` is usually of the same length or shorter, as in [this answer](https://codegolf.stackexchange.com/a/156652/32014). ### `listNF` `listNF` is to `listF` what `listN` is to `list`: the input `a` is omitted, and the default value of the return type is used instead. In rare circumstances, it can be shorter than a right fold, for example in [this answer](https://codegolf.stackexchange.com/a/158168/32014). As an example of the recursive versions of `Γ`, the function `Γλ·:o⁰↔` shuffles a list in the order first, last, second, second-to-last, third, third-to-last, and so on. [Try it online!](https://tio.run/##ASYA2f9odXNr///Ok867wrc6b@KBsOKGlP///1sxLDIsMyw0LDUsNiw3XQ) The function `f` is the explicit lambda `λ·:o⁰↔`, whose argument `⁰` is the entire function. What `f` does is reverse the tail with `↔`, then call the main function recursively with `o⁰`, and finally tack the head back with `·:`. Of course, `Γ·:o₀↔` is a byte shorter, but doesn't work if the line contains something else than this function. [Answer] ## Lambdas can be shorter than new functions As you probably know if you have a multi-line program, you can refer to the lines with the subscripts `₀…₉`, for example in the case of ``` f g ``` `₁` will refer to the function `g`. Now if you always apply the inputs to the function `g` (and use it multiple times); something like this: ``` f₁⁰[...]g₁⁰[...] h ``` You should introduce a lambda because it saves you 1 byte for each additional use: ``` λf⁰[...]g⁰[...])h ``` --- ## The reverse might be true as well In the case of self-referential lambdas (`φχψ`), there's the special case where you apply the inputs directly to the recursive function, in these cases you're better off by using the subscript `₀` instead of defining a new lambda and using `⁰`. [Answer] # Combinators can be applied to higher order functions Suppose you have a list of integers **X**, and you want to count the total number of elements of **X** that are larger than **length(X)**. Counting elements that satisfy a predicate is done with the higher order function `#`, but here the predicate (being larger than **length(X)**) depends on **X**. The solution is to apply the combinator `Ṡ` to `#` and the function `o>L` that checks whether a list is shorter than a number. In the function `Ṡ#o>L`, the list **X** is passed to `o>L`, the partially applied function is passed to `#`, and **X** is given to `#` as the second argument. In general, if `α` is a higher-order function, `β` a binary function and `γ` a unary function, `Ṡαβ` is equivalent to the Haskell pseudocode ``` \x -> α (\y -> β x y) x ``` `§αβγ` is equivalent to ``` \x -> α (\y -> β x y) (γ x) ``` and `~αβγ` is equivalent to ``` \x y -> α (\z -> β x z) (γ y) ``` as long as the types match. As another concrete example, `§►δṁ≠P` finds a permutation of a list **X** that maximizes the sum of absolute differences to corresponding values of **X** (`δṁ≠` zips two lists using absolute difference and takes the sum). [Answer] ## Husk's default values Husk is not as strict as Haskell where you run into trouble when for example you try to get the `last` element of an empty list. To achieve this it uses predefined values, here's a list of the default values, maxima and minima: ``` .------------------------------------.---------------.----------.-------. | Type (X and Y are placeholders) | default (def) | max | min | |------------------------------------|---------------|----------|-------| | Character (C) | ' ' | \1114111 | \NUL | | Numbers (N) | 0 | Inf | -Inf | | List of X (LX) | [] | ∞ max | [] | * | Function :: X -> Y | const (def Y) | n/a | n/a | '------------------------------------'---------------'----------'-------' ``` \* Here ∞ should represent an infinite list of the corresponding maximum (see below for an example) **Note:** For tuples (X,Y) it will use the values for each component separately. --- ## When they are used While the maxima and minima are only used for `▲▼` on empty lists (for example [`husk -u "▼" "[]:LLN"`](https://tio.run/##yygtzv7//9G0Pf///4@OtfLx8QMA "Husk – Try It Online") will return an infinite list of `Inf`) the default values are used in a few places: * folding over empty lists without providing a value yourself (`F` and `Ḟ`) * prepending default value (with `Θ`) * when read (`r`) fails * getting the first/last element (`←→`) or indexing into one (`!`) * pattern matching (`Γ`) on empty lists * using `►` or `◄` on empty lists [Answer] # Use `,` , `e` and `ė` to debug your functions Since Husk is a functional programming language, a lot of times you'll find yourself in a situation where you have a function with two arguments passed to it, which returns an unexpected result. You can replace any two argument function with `e`/`ė`, so long as it's arguments are homogeneous(have the same datatype) `,`, on the other hand makes a pair. It can only be used for 2 argument functions, but it supports heterogeneous types. For example, ``` S+ȯ□½→ ``` returns the number added to itself incremented, halved then squared in that order (\$x + \frac{(x+1)^2}4\$) ``` Seȯ□½→ ``` will return a two element list with the original element, and the result of the function composition. For example, ``` 1 → [1,1] 2 → [2,9/4] 3 → [3,4] ``` and so on. ]
[Question] [ # Background It can be shown that for any integer `k >= 0`, `f(k) = tan(atan(0) + atan(1) + atan(2) + ... + atan(k))` is a rational number. # Goal Write a complete program or function which when given `k >= 0`, outputs `f(k)` as a single reduced fraction (the numerator and denominator are coprime). # Test cases The first few values are ``` f(0) = (0,1) f(1) = (1,1) f(2) = (-3,1) f(3) = (0,1) f(4) = (4,1) f(5) = (-9,19) f(6) = (105,73) ``` # Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * [Input and output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) may be in any convenient format. You may output `f(k)` as a string `numerator/denominator`, as a tuple of two integers, a fraction or rational object, etc. If you output a string, give two integers only, that is, output `3/2` instead of `1 1/2`. * This is code-golf, the shortest answer (in bytes) wins. [Answer] # Mathematica, 28 bytes ``` Fold[+##/(1-##)&,0,Range@#]& ``` [Try it online!](https://tio.run/##y00sychMLv6fpmCr8N8tPyclWltZWV/DUFdZWVNNx0AnKDEvPdVBOVbtv0t@dEBRZl5JdJ6OgpKCrp2Cko5CWnRebKyOQjVQyEBHwdCgNvY/AA "Mathics – Try It Online") A longer, but more interesting approach (32 bytes): ``` Im@#/Re@#&@Product[1+n I,{n,#}]& ``` [Try it online!](https://tio.run/##y00sychMLv6fpmCr8N8z10FZPyjVQVnNIaAoP6U0uSTaUDtPwVOnOk9HuTZW7b9LfnRAUWZeSXSejoKSgq6dgpKOQlp0XmysjgJQiYKBjoKhQW3sfwA "Mathics – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ 72 bytes ``` from fractions import* f=lambda k:Fraction(k and(k+f(k-1))/(1-k*f(k-1))) ``` Use the identity: ``` tan(A + B) = (tan(A) + tan(B)) / (1 - tan(A) * tan(B)) ``` We have: ``` f(k) = 0 if k = 0 = (k + f(k - 1)) / (1 - k * f(k - 1)) if k > 0 ``` [Try it online!](https://tio.run/##LckxDsIwDADAnVd4q10aoTBWgpF/GIrBCrEjk4XXh6Xj6dqvv93OY0h4BQl@dHX7gtbm0eeDXD5c7xtDWW97YgG2DctRsKRMdMKcyryDhniAghoE2@uJOdPaQq2DLlO6Toug0vgD "Python 2 – Try It Online") Thanks to Luis Mendo, save 4 bytes. [Answer] # [M](https://github.com/DennisMitchell/m), 11 bytes ``` ×C÷@+ R0;ç/ ``` [Try it online!](https://tio.run/##y/3///B058PbHbS5ggysDy/X////vxkA "M – Try It Online") Uses the OEIS formula `x(n) = (x(n-1)+n)/(1-n*x(n-1))` with `x(0) = 0`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes Requires `⎕FR←1287` (**128** bit **F**loating-point **R**epresentation) for small input. Takes `k` as right argument. ``` 1(∧÷,)3○¯3+.○⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbm/9NADI1HHcsPb9fRNH40vfvQemNtPSD9qHfz//9ph1YYKBgqGCkYK5gomCqYAQA "APL (Dyalog Unicode) – Try It Online") `⍳` integers one through `k` (zero is not needed as 0 = arctan 0) `¯3+.○` sum of arcus tangents `3○` tangent `1(`…`)` apply the following tacit function with 1 as left argument and the above as right argument:  `∧` the lowest common multiple (of 1 and the right argument); gives the numerator  `÷` divided by  `,` the concatenation (of 1 and the right argument); gives the numerator and the denominator [Answer] # [Haskell](https://www.haskell.org/), 52 bytes This uses the OEIS series expansion: ``` import Data.Ratio f 0=0%1 f n|p<-f$n-1=(p+n)/(1-n*p) ``` [Try it online!](https://tio.run/##DcUxDsMgDADAva@wokSCIpIwdIOpfUF@YKmQoibGIh77d8pwug9e33gcreWTSxV4oeC8oeRyS7CGdXJ9@rG3aSTrgmJDelHO0p11OzETBOCaSWCG1NWI754yZpjcoCF4D3uUZyGJJFd7/AE "Haskell – Try It Online") Or a pointfree version: ``` (scanl1(\f n->(f+n)/(1-n*f))[0%1..]!!) ``` [Answer] ## JavaScript (ES6), 80 bytes ``` f=n=>n?([a,b]=f(n-1),g=(a,b)=>a?g(b%a,a):b,c=g(d=b*n+a,e=b-n*a),[d/c,e/c]):[0,1] ``` Returns a [numerator, denominator] pair. Explanation: Let `f(n-1) = a/b` then `f(n) = atan(tan(n)+tan(a/b)) = (n+a/b)/(1-n*a/b) = (b*n+a)/(b-n*a)`. It then remains to reduce the fraction to its lowest terms. [Online ES6 Environment](https://es6console.com/j63jz0l7/) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes ``` n->imag(x=prod(i=0,n,1+i*I))/real(x) ``` [Try it online!](https://tio.run/##DYoxDoAgDAC/0ji1ChEeALvPIFFIEy1N4@DvkeFuuJwWY990VEgwxGd@SsMvqfUTOQUnLm68HkS7XeXGj0bthjLv4CBO1FjeGRbweaqiENH4AQ "Pari/GP – Try It Online") Or the same length: ``` n->fold((x,y)->(x+y)/(1-x*y),[0..n]) ``` [Try it online!](https://tio.run/##DYoxCoAwDAC/EpwSbWp9gP2IOAhSKUhaikP7@pjhbjiuXi3zUzXBDiocU3lvxO4GccS@DFpx4z4PckfwXk7SVBqK3cHBZtSW5bMwAUdTQiEi/QE "Pari/GP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ 26 bytes ``` 0X)Iƒ©`N*+®`sN*-‚D¿D_i\¤}/ ``` [Try it online!](https://tio.run/##ASwA0/8wNWFiMWX//zBYKUnGksKpYE4qK8KuYHNOKi3igJpEwr9EX2lcwqR9L///Ng "05AB1E – Try It Online") **Explanation** ``` 0X) # initialize stack with [0,1] Iƒ # for N in range [0 ... input] do: © # store a copy of the current pair in the register ` # push the pair separately to the stack N* # multiply the denominator with N + # add the numerator ®`s # push the denominator then the numerator to the stack N* # multiply the numerator by N - # subtract it from the denominator D¿D # get 2 copies of the greatest common divisor 0Qi } # if the gcd equals 0 \¤ # replace it with the denominator / # divide the pair with this number ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 30 bytes ``` format rat tan(sum(atan(0:k))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9ta2bN9T8tvyg3sUShKLGEqyQxT6O4NFcjEcQwsMrW1NT8/x8A "Octave – Try It Online") [Answer] # Casio-Basic, 35 bytes ``` tExpand(tan(sum(seq(tan⁻¹(n),n,0,k ``` tan-1 should be entered as the one on the Trig keyboard; or the -1 can be entered separately from the abc>Math keyboard. According to the fx-CP400's manual, it's a single two-byte character (764). Function, 34 bytes for the code, +1 byte to add `k` as an argument. **Explanation** `seq(tan-1(n),n,0,k)` generates all the values for `tan-1(n)` from 0 to k. `sum` adds them all together, then `tan` does the tangent function on them. `tExpand` will then turn them into a single fraction. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 130 bytes ``` : g dup if tuck mod recurse then ; : f 0 1 rot for 2dup i * + -rot swap i * - next 2dup g + abs over 0< 2* 1+ * >r i / swap r> / ; ``` [Try it online!](https://tio.run/##LY7LDoIwEEX3/YoTlhAeZQnGf0FowaiUtEX9exzA1dzHuclY5@OUj3Y/29YwMqwLd0tc@wcvN@BNv/pgiJOZaVWDpULjXURW1AdPSka@Z@HTnT5nNt@ojn6UtrsF3Nt4qgt1is6EuXpBy3Pjr6JaeSGaEBVoXTA4EQhTUCQ0JH9rz6AkEdF7SZ/OLao9ttsP "Forth (gforth) – Try It Online") Uses [my own implementation of gcd](https://codegolf.stackexchange.com/a/194241/78410), and the OEIS formula. Takes `k` from the stack and returns two integers `denom num` on the stack. It took a lot of effort (and bytes) to normalize the fraction. ``` : g ( x y -- gcd 0 ) dup if tuck mod recurse then ; : f ( k -- denom num ) 0 1 \ push initial fraction with num=0, denom=1 rot for \ ( num denom ) loop from k to 0 inclusive 2dup i * + -rot \ ( denom*k+num num denom ) swap i * - \ ( denom*k+num denom-num*k ) next 2dup g + abs \ ( num denom gcd ) evaluate positive gcd and remove 0 over 0< 2* 1+ * \ ( num denom gcd' ) negate gcd if denom < 0 >r i / swap r> / \ ( denom/gcd' num/gcd' ) ; ``` [Answer] ## Julia 0.6.0 40 bytes `k->rationalize(tan(sum(x->atan(x),1:k)))` It's a straightforward implementation of the question. The precision of rationalize can sometimes be weird but works fine 99% of the time. ]
[Question] [ Sometimes a long absolute path, in e.g. a command-line parameter to a linux tool, can be shortened, using current working directory as reference: ``` $ pwd /home/heh $ cat /home/heh/mydir/myfile my stuff $ cat mydir/myfile my stuff ``` In this challenge, you should make a function or a program that receives two parameters: 1. Absolute path, using the linux format (starts with `/`) 2. Current directory, using the same format The output is the shorter of the following: * Input 1 unchanged * Relative path that refers to the same file/directory as the absolute path Fine points: * If your operating system is compatible with linux, you can use the system's current directory instead of receiving it as input * You can assume the inputs contain only alphanumeric characters (and path separators) * You can assume the input absolute path doesn't have a path separator `/` at the end * You can assume the input current directory has a path separator `/` at the end * You cannot assume that the absolute path refers to an existing file, or that any part of it is an accessible directory; however, the current directory can be assumed valid * You can assume there are no symlinks anywhere near either path - because I don't want to require any special way of dealing with symlinks * No need to support the case where either of the inputs is the root directory * "The current directory" should be output as `.` (an empty string is not valid) Test cases (input1, input2, output): ``` /home/user/mydir/myfile /home/user mydir/myfile /var/users/admin/secret/passwd /var/users/joe/hack ../../admin/secret/passwd /home/user/myfile /tmp/someplace /home/user/myfile /dir1/dir2 /dir1/dir2/dir3/dir4 ../.. /dir1/dir2 /dir1/dir2 . ``` [Answer] ## JavaScript (ES6), ~~107~~ 106 bytes Takes the absolute path `a` and the current path `c` in currying syntax `(a)(c)`. ``` a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.' ``` ### Test cases ``` let f = a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.' console.log(f ('/home/user/mydir/myfile') ('/home/user') ); console.log(f ('/var/users/admin/secret/passwd') ('/var/users/joe/hack') ); console.log(f ('/home/user/myfile') ('/tmp/someplace') ); console.log(f ('/dir1/dir2') ('/dir1/dir2/dir3/dir4') ); console.log(f ('/dir1/dir2') ('/dir1/dir2') ); ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~85~~ ~~83~~ 82 bytes *1 byte saved thanks to @MartinEnder* ``` ^(..+)(.*;)\1 %$2 (%?)(.*);(.*) $1$3;$2 \w+(?=.*;) .. %;/ ; / .*// / %/?|/$ ^$ . ``` [Try it online!](https://tio.run/nexus/retina#bY3BDoIwEETv8x1tUiDpBvDWGI7@BCE2UAMKQihKTPx3bPGAGi9vd2Y2s1wcjkshpIwCIUMV5DE4SyB45nWgPMBilirn5nMksr0/g5TgigAFggyJ3OCUPYkBBYNcFqr7ztDNmpG6R9V4nprWqM3HT7Aq0F2Pa2xJV11zJWvK0Uw0aGvnSn3E595QrcsLvl69u6ZuIOvcodWlAbni2CNR2@qReuz@5y8 "Retina ‚Äì TIO Nexus") [Answer] # [Julia 0.5](http://julialang.org/), 32 bytes ``` !,~=relpath,endof t->~t<~!t?t:!t ``` This uses the current working directory as base and cannot be tested on TIO at the moment. ### Example run **Warning:** This will alter your file system. ``` $ sudo julia --quiet julia> function test(target,base) mkpath(base) cd(base) shorten(target) end test (generic function with 1 method) julia> !,~=relpath,endof (relpath,endof) julia> shorten = t->~t<~!t?t:!t (::#1) (generic function with 1 method) julia> test("/home/user/mydir/myfile","/home/user") "mydir/myfile" julia> test("/var/users/admin/secret/passwd","/var/users/joe/hack") "../../admin/secret/passwd" julia> test("/home/user/myfile","/tmp/someplace") "/home/user/myfile" julia> test("/dir1/dir2","/dir1/dir2/dir3/dir4") "../.." julia> test("/dir1/dir2","/dir1/dir2") "." ``` ## Alternate version, 35 bytes (dyadic) ``` ^,~=relpath,endof t-b=~t<~t^b?t:t^b ``` This takes the base directory as input, so it can be tested without modifying the file system. [Try it online!](https://tio.run/nexus/julia5#fY3LCsIwEEXX9itKVgotg4@VWPwQsTBtRhpN0pCMipv@em1asOLCzYHLPTO3L7Ou8KQdcpORle0l4bwqOj50XFZH3g/sDbql88qytll6ShYCmtYQ3AN5MC@pIi9Kk0jz9KsT0XygH0MAlEZZCFR7YnAYwlNOB7NybQkarG/id2P@zsZBGBqnsabRG/bXEZtJ@MSIbcTuryaS86p/Aw "Julia 0.5 ‚Äì TIO Nexus") [Answer] # ES6 (Node.js REPL), ~~56~~, ~~54~~, ~~46~~, 45 bytes * Use empty string, instead of "." to denote the current directory (on input), -1 byte * Borrowed the `[f.length]` trick from @Arnauld's [answer](https://codegolf.stackexchange.com/a/117038/61904), -6 bytes * Use the current directory instead of an explicit directory parameter, -2 bytes * Removed superfluous parentheses, -2 bytes **Golfed** ``` f=>(r=path.relative("",f))[f.length]?f:r||"." ``` **Test** ``` > F=f=>(r=path.relative("",f))[f.length]?f:r||"." [Function: F] > F("/home/user/mydir/myfile") 'mydir/myfile' > F("/var/users/admin/secret/passwd") '../../admin/secret/passwd' > F("/home/user/myfile") '/home/user/myfile' > F("/dir1/dir2") '../..' > F("/dir1/dir2") '.' ``` [Answer] # Python 2, ~~135~~ 144 bytes ``` i=0 a,c=input() b,d=a.split('/')*(a!=c),c.split('/') while b[:i+1]==d[:i+1]:i+=1 print'.'[i:]or min('/'.join(['..']*len(d[i:])+b[i:]),a,key=len) ``` [Try it Online!](https://tio.run/nexus/python2#dVDLbsMgELzzFelp7QSxdZtTJL7E8mENVCbxAwFJlK93gFaNVamX2dmZWe1qVyvfGXEl7eyusapZz7UkEdxoYwUI9b6iN6lqrjYauw92NLu@PdlD00mpv0kC2TDn7RxBQGtP3eJ3k53zjDgvibQgBHT70cyVzn596EvhxC/mIZNerysgYQ@8FNRogAEOy2QwmhCzXpprMB6nh7YZv9I5v7Efp2gpHSeHIeluJFVCaaTJ8JHdV/Ovk@Ezw/Hvis3y7Vk5diNfeEDS6QUYjPImoqMQ7jqnX4HzYnAgdYEn) Kind of long, but I wanted to do a solution without built-in path functions. **Edit:** 9 bytes added to account for test case provided by Nathan Merrill [Answer] # [Zsh](https://www.zsh.org/) + realpath, 58 bytes ``` r=`realpath -m --relative-to=$*` (($#2<$#r))&&r=$2 echo $r ``` [Try it online!](https://tio.run/nexus/zsh#dU9Na8MwDL3rVwjq9QsSkWynshz3B3beoSZWibckNrbSdr8@c5pCW@jAPEtPD72nU2NbxsDaoO39IAXc6hKMm0dukNSDD7aXA64@zp5rYbPDl/jVf3IcWtkh4grVVRlZUM1Lrn8xhmqflrVeS4NZh1kWuNVij5yJq9R2D@u1WpTvahE2m@UyVKoErhuHKoxTiEuTEvU8UuM6piFyoO7X2AkP6Qy48fDAAx11uPCRtOlsT5HrwEJex3gy9@Nvx9To@gfynNJ7poYH@9lYOk8xsb7VNT8RAKU4xQTlXTnB6wRvs90/Msj/AA "Zsh ‚Äì TIO Nexus") ### Bash version, 62 bytes ``` r=`realpath -m --relative-to=$*` ((${#2}<${#r}))&&r=$2 echo $r ``` [Try it online!](https://tio.run/nexus/bash#dU9Na8MwDL3rVwjm9WOQiGQ7leW4P7DzDjWxSrwlsbGVdmP0t2dOU2gLHZhn6emh93RobMsYWBu0vR@kgEtdgnHzyA2SevDB9rLD5du351rYbPAxfvTvHIdWNoi4RHVWRhZU85LzX4yh2qZlrdfSYNZhlgVutdg9Z@Iq9bSF1Ur9PpTH14ThuF4vFqFSJXDdOFRhnIKcmpSq55Ea1zENkQN1P8ZOuEunwIWHGx5or8OJj6RNZ3uKXAcW8jrGg7kefzqmRtdfkOeU3j013NjPxtJ5ion1ra75jgAoxSkmKK/KCZ4neJnt/pFB/gc "Bash ‚Äì TIO Nexus") [Answer] ## Python 3 – 53 bytes Using `os.path`: ``` import os lambda x:min(x,os.path.relpath(x),key=len) ``` Full program (61 bytes): ``` import os x=input();print(min(x,os.path.relpath(x),key=len)) ``` [Answer] # PHP, 204 Bytes ``` [,$l,$p]=$argv;$z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l));$m=str_pad("",3*count($z)-1,"../");$j=join("/",$r=$d($x,$y));echo$l!=$p?strlen($u=$m&&$j?"$m/$j":$m.$j)<strlen($l)?$u:$l:"."; ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/843f7f9de9a3cc8d9bbaeaa8b72ac5df42992f7a) Expanded ``` [,$l,$p]=$argv; $z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l)); $m=str_pad("",3*count($z)-1,"../"); $j=join("/",$r=$d($x,$y)); echo$l!=$p ?strlen($u=$m&&$j?"$m/$j":$m.$j)<strlen($l) ?$u :$l :"."; ``` if an Output `../../` instead `of ../..` is allowed it can be shorten to 175 Bytes ``` [,$l,$p]=$argv;$z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l));echo$l!=$p?strlen($m=str_pad("",3*count($z),"../").join("/",$r=$d($x,$y)))<strlen($l)?$m:$l:"."; ``` [Answer] # C# - 66 bytes Using a .NET [builtin](https://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri%28v=vs.110%29.aspx) and forcing to be a valid path: ``` (f,t)=>f==t?".":new Uri("/"+t).MakeRelativeUri(new Uri("/"+f))+""; ``` Where `f`,`t` and output are `string`. [Try it online!](https://dotnetfiddle.net/AIW2hX) ]
[Question] [ ## Background I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week. When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet. My strategy is to pull one random sock from the pile at a time and put it on a drawer. Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet. Your task is to simulate this random process and return the number of draws required to find the first matching pair. ## Input Your input is an integer **N ≥ 1**. It represents the "number of days in a week": there are **N** pairs of socks in the pile, and each pair has a distinct label. If necessary, you may also take a PRNG seed as input. ## Output Your output is the number of socks I have to draw before the first matching pair is found. For example, if the first two socks already form a matching pair, the output is `2`. Of course, the output is random, and depends on the drawing order. We assume that *all drawing orders are equally likely*, so that each time a sock is drawn, the choice is uniform and independent from all other choices. ## Example Let **N = 3**, so that we have 6 socks in total, labeled **A A B B C C**. One possible run of the "sock-drawing protocol" is as follows: ``` | Pile | Drawer | Pairs Begin | AABBCC | - | - Draw B | AABCC | B | - Draw C | AABC | BC | - Draw B | AAC | C | BB Draw A | AC | AC | BB Draw A | C | C | AA BB Draw C | - | - | AA BB CC ``` The first matching pair was found after drawing the second **B**, which was the third sock to be drawn, so the correct output is `3`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Input and output can be in any reasonable format, including unary (string of `1`s). You may assume that your language's built-in RNG is perfect. You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution. ## "Test cases" Here are the approximate probabilities of all outputs for the input **N = 7**: ``` Output 2 3 4 5 6 7 8 Probability 0.077 0.154 0.210 0.224 0.186 0.112 0.037 ``` To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤX€Ṛ<RTḢ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4og&input=&args=MTAw) or [verify the distribution for **N = 7**](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4ogrigJjCteKAmXg0yLc0w4figqzEi8OQ4oKsUsO3NMi3NMW8QFJH&input=&args=Nw). ### Background Let **n** be the number of pairs; there are **2n** individual socks. For the first draw, there are **2n** socks and **0** of them would result in a matching pair. Therefore, the probability of success is **0 / 2n = 0**. Since the first draw wasn't successful, there are **2n - 1** socks on the pile and **1** of them would result in a matching pair. Therefore, the probability of success is **1 / (2n - 1)**. *If* the second draw wasn't successful, there are **2n - 2** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **2 / (2n - 2)**. In general, if the first **k** draws were unsuccessful, there are **2n - k** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **k / (2n - k)**. Finally, if none of the first **n** draws was successful, there are **2n - k** socks on the pile and all of them would result in a matching pair. Therefore, the probability of success is **n / (2n - n) = 1**. ### How it works ``` ḤX€Ṛ<RTḢ Main link. Argument: n Ḥ Unhalve; yield 2n. X€ Map `random draw' over [1, ..., 2n], pseudo-randomly choosing an integer from [1, ..., k] for each k in [1, ..., 2n]. Ṛ Reverse the resulting array. R Range; yield [1, ..., n]. < Perform vectorized comparison. Comparing k with the integer chosen from [1, ..., 2n - (k - 1)] yields 1 with probability (k - 1) / (2n - (k - 1)), as desired. The latter half of elements of the left argument do not have a counter- part in the right argument, so they are left untouched and thus truthy. T Truth; yield all indices of non-zero integers. Ḣ Head; extract the first one. ``` [Answer] ## Jelly, 8 bytes ``` Rx2ẊĠṪ€Ṃ ``` [Try it online!](http://jelly.tryitonline.net/#code=Ungy4bqKxKDhuarigqzhuYI&input=&args=NQ) ``` R generate [1, 2, ..., n] x2 duplicate every element (two socks of each pair) Ẋ shuffle the list, to represent the order in which socks are drawn Ġ group indices by value. this will produce a list of pairs of indices; each pair represents the point in time at which each of the corresponding socks were drawn Ṫ€ take the last element of each pair. this returns an array of n integers which represent the points in time at which a matching sock was drawn Ṃ minimum, find the first point at which a matching sock was drawn ``` To verify, [here is a version](http://jelly.tryitonline.net/#code=Ungy4bqKwqnEoOG5quKCrOG5gizCrg&input=&args=NQ) that displays both the desired output and the result of the "shuffle list" operation (to see what order socks were drawn in). [Answer] # Python, 66 bytes ``` from random import* f=lambda n,k=1:k>randint(1,n*2)or-~f(n-.5,k+1) ``` Dennis thought up a clever way to rearrange things, saving 5 bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` Q:"r@qGEy-/<?@. ``` [Try it online!](http://matl.tryitonline.net/#code=UToickBxR0V5LS88P0Au&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=MWUzOiJHClE6InJAcUdFeS0vPD9ALgpdXV0Kdkc6UT1ZbTVNd3Y&input=Nw) for 1000 samples in the *N*=7 case (it takes a while). This **directly generates the random variable** representing the result, based on its probability distribution. Let *N* be the number of sock pairs, and let *p*(*k*) denote the probability that the *k*-th draw is successful, conditioned on the fact that the *k*-1-th draw was not succesful. Then (see also [here](http://gondolin.blogspot.com.es/2009/04/socks-problem.html)): * *p*(1) is obviously 0. You can't have a pair with a single sock. * *p*(2) is 1/(2\**N*−1). At the second draw there is one winning sock that may be chosen out of 2\**N*−1 remaining socks. * *p*(3) is 2/(2\**N*−2). At the third draw there are 2 winning socks out of 2\**N*−2. The number of winning socks is 2 because the two socks you got after the second draw were different. * In general, by the same reasoning, *p*(*k*) is (*k*−1)/(2\**N*−*k*+1) * By the above formula, *p*(*N*+1) is 1. If you get to the *N*+1-th draw you are guaranteed to succeed then. So the code iterates for a maximum of *N*+1 draws. At the *k*-th draw a random variable is generated that equals 1 with probability (*k*-1)/(2\**N*-*k*), or 0 otherwise. Whenever the random variable equals 1 (the draw has been succesful) the process stops and the current *k* is output. ``` Q: % Input N implicitly. Generate [1 2 ... N+1] (values of draw index, k) " % For each r % Random variable uniformly distributed on the interval (0,1) @q % Push iteration index, k-1 GE % Push 2*N y % Duplicate: push k-1 again - % Subtract: gives 2*N-k+1 / % Divide: gives (k-1)/(2*N-k+1) < % Push 1 if random value is less than (k-1)/(2*N-k+1), 0 otherwise ? % If we got a 1 @ % Push k . % Break loop % End if implicitly % End loop implicitly % Display implicitly ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes ``` EZ@G\&=XRafX< ``` [Try it online!](http://matl.tryitonline.net/#code=RVpAR1wmPVhSYWZYPA&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=NGUzOiJHCkVaQEdcJj1YUmFmWDwKXQp2RzpRPVltNU13dg&input=Nw) for 4000 samples in the *N*=7 case (it takes a while). ``` E % Input N implicitly. Multiply by 2 Z@ % Random permutation of [1 2 ... 2*N] G\ % Modulo N: random permutation of [0 0 1 1 ... N-1 N-1] &= % Compare all pairs for equality. Gives an N×N matrix XR % Upper triangular part excluding the diagonal a % True for each column if it contains at least one true entry f % Get indices of true values X< % Take minimum. Implicitly display ``` [Answer] # JavaScript, ~~77~~ 73 bytes ``` n=>{p={};for(i=n;i--;p[i]=2);while(--p[n*Math.random()|0])i++;return i+2} ``` **Explanation** ``` var f = (n) => { var index; // used first to initialize pile, then as counter var pile = {}; // sock pile // start with index = n // check that index > 0, then decrement // put 2 socks in pile at index for(index = n; index--; pile[index] = 2); // index is now -1, reuse for counter // pick random sock out of pile and decrement its count // continue loop if removed sock was not the last while(--pile[n * Math.random() | 0]) { index++; // increment counter } // loop finishes before incrementing counter when first matching pair is removed // add 1 to counter to account for initial value of -1 // add 1 to counter to account for drawing of first matching pair return index + 2; }; ``` [Answer] ## CJam, 17 bytes ``` ri,2*mr{L+:L(&}#) ``` [Test it here.](http://cjam.aditsu.net/#code=ri%2C2*mr%7BL%2B%3AL(%26%7D%23)p&input=7) [Answer] # Python 3, ~~142~~ ~~105~~ 104 bytes Thanks to *Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ* for saving one byte! My first answer: ``` import random i=[x/2 for x in range(int(2*input()))] d=[] a=0 random.shuffle(i) while 1: b=i.pop() if b in d: print(a) s d=d+[b] a+=1 ``` My new answer: ``` from random import* i=range(int(input()))*2 shuffle(i) j=0 for x in i: if x in i[:j]:print(1+j)+s j+=1 ``` Both exit with a `NameError` on `s`. [Answer] # R, 49 ``` N=scan();which(duplicated(sample(rep(1:N,2))))[1] ``` I'm sure there must be a better way of doing this in R! I tried doing something cleverer but it didn't work. Edit: Improved by @bouncyball since it doesn't have to be a function. [Answer] # Python 2, 101 bytes ``` from random import* d=[] p=range(input())*2 shuffle(p) while list(set(d))==d:d+=p.pop(), print len(d) ``` [Answer] ## VBA, 61 bytes ``` Function K(D):While 2*D-K>K/Rnd:K=K+1:Wend:K=K+1:End Function ``` - models the shifting probability of sock match given previous failure to match. At the point of evaluation, K is "socks in hand", so draw number is one more. [Answer] # Pyth, 14 bytes ``` lhfnT{T._.S*2S ``` Explanation: ``` ._ #Start with a list of all prefixes of .S #a randomly shuffled *2S #range from 1 to input (implicit), times 2. f #filter this to only include elements where nT{T #element is not equal to deduplicated self (i.e. it has duplicates) lh #print the length of the first element of that filtered list ``` ]
[Question] [ **Task:** Make a program that leaves a comment on this question. The content should be `1234567890123456`. **Edits:** 1. You may leave your usernames and passwords as `U` and `P` if you are using username and password. (if applicable) 2. No URL Shorteners (if applicable) 3. You may not use the browser console. [Answer] # AppleScript with Safari, ~~269~~ 287 bytes ``` tell application "Safari" activate tell window 1 set current tab to (make new tab with properties {URL:"http://codegolf.stackexchange.com/q/84546"}) delay 5 do JavaScript "$('a')[66].click();$('textarea')[0].val('1234567890123456');$('input')[5].click()" in current tab end tell end tell ``` To use this you need to enable Safari Developer Settings and then enable `Allow JavaScript from Apple Events`. I'm not sure if it's cheating or not to use the existing keychain + cookies but oh well. I also managed to do this in OSX's Automator by just automating the clicks and keystrokes however I didn't think it stayed true to the idea of the challenge [Answer] ## Javascript with jQuery, 127 bytes ``` $.post("//codegolf.stackexchange.com/posts/84546/comments",{comment:"12345678901‌​23456",fkey:StackExchange.options.user.fkey}) ``` Thanks to Ismael Miguel and nicael for a few bytes. The `fkey` parameter is unique to your account, and can be found by examining local storage contents of your browser with a StackExchange page open. This code must be run in a browser with an open StackExchange session present. It automatically loads the `fkey` parameter from the browser's local storage (previous versions of this submission required it to be manually entered). Unfortunately, the `ppcg.lol` URL can't be used, because it doesn't pass POST requests through. Fun fact: if you attempt to run this code without the proper `fkey` value, you get an [HTTP 418](https://codegolf.stackexchange.com/q/41638/45941) response: [![teapot](https://i.stack.imgur.com/rX32H.png)](https://i.stack.imgur.com/rX32H.png) Example of how to find the `fkey` value in Chrome: [![fkey](https://i.stack.imgur.com/8lerc.png)](https://i.stack.imgur.com/8lerc.png) Apparently Winterbash stuff is still being stored. Neat. For reference, the same thing in vanilla Javascript would be 314 bytes (thanks again to Ismael Miguel and nicael for some bytes off): ``` with(new XMLHttpRequest()){ open("POST","//codegolf.stackexchange.com/posts/84546/comments",1) setRequestHeader("Content-type","application/x-www-form-urlencoded") setRequestHeader("Content-length",62) setRequestHeader("Connection","close") send("comment=1234567890123456&fkey="+StackExchange.options.user.fkey}))} ``` [Answer] # Python 3.5 with Selenium Webdriver, ~~485~~ ~~427~~ ~~469~~ ~~461~~ ~~449~~ ~~414~~ 403 bytes: ``` from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit() ``` A full program utilizing a simple Python selenium web driver solution. Works in Chrome, although it needs [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/) installed to work. Works by renaming `U` and `P` to the user's Stack Exchange email and password, respectively. However, if there are any issues getting ChromeDriver installed, here is a FireFox solution that gets executed in the exact same manner as the above solution and does not need any drivers, although it is currently 1 byte longer at **~~414~~ 404 bytes**: ``` from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit() ``` Also, if a function is wanted, here is a solution using an anonymous lambda function, currently standing at **~~513~~ ~~455~~ ~~497~~ ~~489~~ ~~477~~ ~~449~~ 431 bytes** and using Chrome as the browser. ``` lambda U,P:exec("from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals()) ``` However, if there are, again, any issues regarding ChromeDriver, here is the same type of solution but this time using Firefox, currently standing at **~~442~~ 432 bytes**: ``` lambda U,P:exec("from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals()) ``` You call these lambda functions by simply renaming the function as anything valid and then calling with your email and password like a normal function. For instance, if the function were named `H`, you would call it like `H(Email, Password)`. [Answer] # Swift 2.2 on iOS, 380 bytes ``` let r = NSMutableURLRequest(URL:NSURL(string:"http://codegolf.stackexchange.com/posts/84546/comments")!) r.HTTPMethod = "POST" r.HTTPBody = try!NSJSONSerialization.dataWithJSONObject(["comment":"1234567890123456","fkey":UIWebView().stringByEvaluatingJavaScriptFromString("localstorage.getItem('se:fkey')")!],options:[]) NSURLSession.sharedSession().dataTaskWithRequest(r).resume() ``` Assumes the user is logged in to Code Golf with Safari and has cookies enabled. Also assumes UIKit is implicitly imported and available. JSON serialization is so verbose in Cocoa... Might update this with a Swift 3 solution and optionally macOS/Linux testable answers. [Answer] # Java 8 with Selenium Webdriver, 684 bytes: ``` import java.util.*;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;class Leave_a_Comment_PPCG_Challenge_Golfed_Version_1{static void Y(String U,String P){WebDriver D=new FirefoxDriver();D.get("http://www.codegolf.stackexchange.com/users/login");D.findElement(By.name("email")).sendKeys(U);WebElement Z=D.findElement(By.name("password"));Z.sendKeys(P);Z.submit();D.get("http://www.codegolf.stackexchange.com/questions/84546");D.findElement(By.linkText("add a comment")).click();WebElement V=D.findElement(By.name("comment"));V.sendKeys("1234567890123456");D.findElement(By.xpath("//input[@value='Add Comment']")).click();}public static void main(String[]a){Scanner I=new Scanner(System.in);Y(I.next(),I.next());}} ``` A direct adaptation in Java 8 of my second full program answer in [Python](https://codegolf.stackexchange.com/a/84570/52405). Works perfectly in Firefox and asks for space separated email and password input immediately when the program starts. In other words, the input is in the format `Email Password` where the space in between the two is needed. ]
[Question] [ This is a fairly simple question. According to [this random website I found — Web Archive](http://web.archive.org/web/20161121045247/http://www.regentsprep.org:80/regents/math/algtrig/ATT3/referenceAngles.htm), a reference angle is `the acute angle formed by the terminal side of the given angle and the x-axis.` You have to write a program to find these. ## I don't remember anything from algebra 2, what does this mean? Angles are usually given in **standard form**, which is measured by placing one side of the angle and measuring to the other side, counterclockwise, like so: [![Standard form](https://i.stack.imgur.com/otKg5.gif)](https://i.stack.imgur.com/otKg5.gif) This will be your input. Your output will be the reference angle of this. You can think of this as basically the smallest distance from the terminal side to the x-axis. Except it's an angle, not a distance. Here are some examples: [![Quad 2 ref](https://i.stack.imgur.com/nUC2F.gif)](https://i.stack.imgur.com/nUC2F.gif) [![Quad 1 ref](https://i.stack.imgur.com/scdIP.gif)](https://i.stack.imgur.com/scdIP.gif) [![Quad 3 ref](https://i.stack.imgur.com/Ea7Q7.gif)](https://i.stack.imgur.com/Ea7Q7.gif) [![Quad 4 ref](https://i.stack.imgur.com/RRis7.gif)](https://i.stack.imgur.com/RRis7.gif) ## Clarifications * All the defaults on inputs and submissions. * Angles is in **degrees**. * Negative angles, non-integer angles, and angles > 360 deg **are** allowed. * Output in form `60 deg`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Another helpful link](http://www.mathwarehouse.com/trigonometry/reference-angle/finding-reference-angle.php). ## Test Cases ``` 70 -> 70 deg 135 -> 45 deg 210 -> 30 deg -60 -> 60 deg 91 -> 89 deg 610 -> 70 deg -1000 -> 80 deg ``` [Answer] # Pyth, 17 bytes ``` +hS%R180,Q_Q" deg ``` Coincidentally, this is equivalent to [@xnor's answer](https://codegolf.stackexchange.com/a/53770/20080). [Try it online.](https://pyth.herokuapp.com/?code=%2BhS%25R180%2CQ_Q%22%20deg&input=-1000&debug=0) [Answer] ## Pyth, 18 bytes ``` +.a-%+QK90yKK" deg ``` [Try it online.](https://pyth.herokuapp.com/?code=%2B.a-%25%2BQK90yKK%22+deg&debug=0) [Answer] # Python 2, 34 bytes ``` lambda x:`90-abs(x%180-90)`+' deg' ``` Using `"%d deg"` string formatting would be longer because of the needed parentheses. [Answer] ## CJam (21 bytes) ``` 180qd1$%z_@@-e<" deg" ``` [Online demo](http://cjam.aditsu.net/#code=180qd1%24%25z_%40%40-e%3C%22%20deg%22&input=610) [Answer] # dc, 25 ``` 90?90+d*v180%-d*vn[ deg]p ``` Note `dc` uses `_` as a -ve sign instead of `-`. ### Test output: ``` $ for test in 70 135 210 _60 91 610 _1000; do dc -e'90?90+d*v180%-d*vn[ deg]p' <<< $test ; done 70 deg 45 deg 30 deg 60 deg 89 deg 70 deg 80 deg $ ``` [Answer] # Mathematica, ~~22~~ 31 ``` ToString@Abs@Mod[#,180,-90]deg& ``` [Answer] ## Python 2, 35 ``` lambda x:`min(x%180,-x%180)`+' deg' ``` The smaller of the angle and its negative modulo `180`. Effectively converts the angle to the range from 0 to 180 and takes the distance to the closer of the endpoints. Note that `-x%180` groups as `(-x)%180`. Same length with string formatting for Python 3: ``` lambda x:'%d deg'%min(x%180,-x%180) ``` [Answer] # Pyth ~~25~~ 30 bytes Painfully uncreative solution, using trig functions. [Permalink](https://pyth.herokuapp.com/?code=%2B.R.t.a.t.t.tQ7Z3+6%3F%25Q1Q0%22+deg&input=-1000.5&debug=0) ``` +.R.t.a.t.t.tQ7Z3 6?%Q1Q0" deg ``` Any suggestions welcome. [Answer] ## JavaScript (ES6), 43 bytes Similar to [Sp3000's answer](https://codegolf.stackexchange.com/a/53772/22867), though the modulo is quite lengthy [due to the behaviour in JavaScript](https://stackoverflow.com/q/4467539/404623). ``` f=x=>90-Math.abs((x%180+180)%180-90)+' deg' ``` ### Demo Code is rewritten in ES5 for browser compatibility: ``` function f(x){return 90-Math.abs((x%180+180)%180-90)+' deg'} // Snippet stuff console.log = function(x){document.body.innerHTML += x + '<br>'}; [70,135,210,-60,91,610,-1000].map(function(v){console.log(f(v))}); ``` ## CoffeeScript, 45 bytes ``` f=(x)->90-Math.abs((x%180+180)%180-90)+' deg' ``` [Answer] # J, 26 bytes ``` m=:180&| ' deg',~m@-":@<.m ``` Same as [xnor's method](https://codegolf.stackexchange.com/a/53770/31405). [Answer] ## Matlab, 44 Using an anonymous function: ``` f=@(x)[num2str(min(mod([x -x],180))) ' deg'] ``` Example: ``` >> f=@(x)[num2str(min(mod([x -x],180))) ' deg'] f = @(x)[num2str(min(mod([x,-x],180))),' deg'] >> f(70) ans = 70 deg >> f(210) ans = 30 deg >> f(-1000) ans = 80 deg ``` [Answer] # Scala, ~~40~~ 35 Characters ``` (a:Int)⇒s"${90-(a%180-90).abs} deg" ``` [Answer] # [Tcl](http://tcl.tk/), 83 bytes ``` proc R a {puts [expr [set a $a%360]>90?$a>180?$a>270?360-$a:$a-180:180-$a:$a]\ deg} ``` [Try it online!](https://tio.run/##Jc0xDoMwDAXQPaf4QzpGckANhQHuwEoZLBp1oWoEqVQJ5eypUwZ/67/Bjsuac9jeC0YwjvCJOyb/DRum3UchzZfa0dy3NGju7e2/qoYGUaO502wEO5mzzXc8/DPl9cWhXFQNAVC2vkpWVooyrmRri7tTLBGphGOUfyn/AA "Tcl – Try It Online") [Answer] ## PHP, 44 bytes Takes one command line parameter. Again [PHP suffers from the same issue as JavaScript](https://stackoverflow.com/questions/4409281/how-is-13-64-13-in-php). ``` <?=90-abs(($argv[1]%180+180)%180-90)+' deg'; ``` Using the canonical solution requires 53 bytes (the degrees and radians conversion takes a lot of characters): ``` <?=rad2deg(abs(asin(sin(deg2rad($argv[1])))))+' deg'; ``` ]
[Question] [ For the purposes of this challenge a *substring* \$B\$ of some string \$A\$ is string such that it can be obtained by removing some number of characters (possibly zero) from the front and back of \$A\$. For example \$face\$ is a substring of \$defaced\$ \$ de\color{red}{face}d \$ This is also called a *contiguous* substring. A common substring of two strings \$A\$ and \$B\$ is a third string \$C\$ such that it is a substring of both \$A\$ and \$B\$. For example \$pho\$ is a common substring of \$photochemistry\$ and \$upholstry\$. \$ \color{red}{pho}tochemistry\\ u\color{red}{pho}lstry \$ If we have two strings \$A\$ and \$B\$ an *uncommon* substring of \$A\$ with respect to \$B\$ is a third string \$C\$, which is a substring of \$A\$ and has no common substring of length 2 with \$B\$. For example the longest uncommon substring of \$photochemistry\$ with respect to \$upholstry\$ is \$otochemis\$. \$otochemis\$ is a substring of \$A\$ and the the only nonempty common substrings of \$otochemis\$ and \$upholstry\$ are size 1 (\$o\$, \$t\$, \$h\$, and \$s\$). If we added any more onto \$otochemis\$ then we would be forced to permit a common subsring of size 2. ## Task Given two strings \$A\$ and \$B\$ output the maximum size an uncommon substring of \$A\$ with respect to \$B\$ can be. You may assume the strings will only ever contain alphabetic ASCII characters. You can assume \$A\$ and \$B\$ will always be non-empty. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better. ## Test cases ``` photochemistry, upholstry -> 9 aaaaaaaaaaa, aa -> 1 aaaaabaaaaa, aba -> 5 babababababa, ba -> 2 barkfied, x -> 8 barkfield, k -> 9 bakrfied, xy -> 8 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes ``` ü«å_γO>à ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8J5Dqw8vjT@32d/u8IL//wsy8kvykzNSczOLS4oquUqB/BwQCwA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##Tc3BagIxEAbge57iPwjbanaDgqAge9OrL7C0JJuRBHUjmxUVfJheeuqx1566977SNulWdAZmho9hRklvulI2yFE6TZnzUlnCYoHletW1X98f7fvrz@c6b9@6IIydjN0RapIatmLaMYBK4zCwFa7wpJHWSLx4ecpGzxyxIs2RDQeiGBesmIgk7Al3aET/6789vg9nK@oOxjWuNLS3vqkvHMcAuzjGe3Mm78EhZcRxj@qG6k@nTMl7cvQ6CVpvN5Y0xznCjP0C) **Explanation:** The longest uncommon substring is the longest sequence of adjacent length 2 substrings of \$A\$ that are not substrings of \$B\$. ``` ü« # length 2 subtrings of A å # for each substring: is it a substring of B? _ # logical negation γ # split into list of equal adjacent elements O # sum each section > # increment each sum à # take the maximum ``` [Answer] # [Python 3](https://docs.python.org/3/), 58 bytes ``` f=lambda a,b,s=1:a>''and+max(f(a[1:],b,a[:2]in b or-~s),s) ``` [Try it online!](https://tio.run/##Rc7BCsMgDAbg@54ieGnd3KHbTehepPQQV0VZq6IO2ste3ekYmEAg359D/JG0s/ec1bjiJhYEZILFceD46Dq0y2XDvVc9TgOfS4ITv83GggAXrp9IWaRZuQBJxgTFe@K1S@6p5WZiCgdhQN6F1t9CWTnAVjUts7FoLP4usHUNmoeXMnKpthPKTwA@GJvKs@f6DaX5Cw "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11 10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 using [ovs's observation](https://codegolf.stackexchange.com/a/235642/53748). ``` ;Ɲẇ€ṣ1ẈṀ‘ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/62NyHu9ofNa15uHOx4cNdHQ93NjxqmPH//3/1goz8kvzkjNTczOKSokr1/@qlQJEcMBsA "Jelly – Try It Online")** --- #### 10 byter ``` Ẇ;ƝẇƇ¥ÐḟṪL ``` **[Try it online!](https://tio.run/##y0rNyan8///hrjbrY3Mf7mo/1n5o6eEJD3fMf7hzlc/////VCzLyS/KTM1JzM4tLiirV/6uXAkVywGwA "Jelly – Try It Online")** ### How? ``` Ẇ;ƝẇƇ¥ÐḟṪL - Link: A, B Ẇ - sublists of A (from shortest to longest) Ðḟ - filter discard those for which: ¥ - last two links as a dyad, f(substringOfA, B): ;Ɲ - length 2 sublists of substringOfA Ƈ - keep those (pairs) for which: ẇ - is this pair a sublist of B? Ṫ - tail -> longest uncommon substring L - length ``` [Answer] # JavaScript (ES6), 63 bytes Expects `(B)(A)`. ``` b=>g=([c,...a])=>a+a&&Math.max(g(a)-1,g=!b.match(c+a[0])*-~g)+1 ``` [Try it online!](https://tio.run/##Zc7BDoIwDAbgu0@BHMgmMMTERA/jDXwCwqEbsKHACEyDF199QjBZhL@XtumX9A4vGHhfdTpsVV6YkhpGE0FRygNCCGSYJuCD591AS9LAiAQCHMaBoHs2zZpLxH1Ijxk@hB@B/dhw1Q6qLkitBCqR@@ykqgfdv12M3KnXisuiqZYNdqLIue5WBGC@BZv50GYi8YYwa9jWTOS8JotgYGtNTmsyLqJ/lFWR/z/1IxfzBQ "JavaScript (Node.js) – Try It Online") ### Commented ``` b => // main function taking the 2nd string b g = ([ // g = recursive function taking the 1st string as: c, // c = next character ...a // a[] = array of remaining characters ]) => // a + a && // stop if a[] is empty (and return a zero'ish value) Math.max( // otherwise, take the maximum of: g(a) - 1, // - the result of a recursive call, minus 1 g = // - the updated value of g, which is: !b.match( // - 0 if b contains c + a[0] c + a[0] // - g + 1 otherwise ) // NB: all recursive calls have already been processed * -~g // when this part of the code is reached; so it's OK // to re-use g as a counter (initially zero'ish) ) // end of Math.max() + 1 // increment the result to make it 1-indexed ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~33~~ 32 bytes ``` (?=(..).*¶.*\1|.*$). ;¶ P`.+ \G. ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8PeVkNPT1NP69A2Pa0Ywxo9LRVNPS7rQ9u4AhL0tLli3PX@/09MSk5JTUvP4CooSk1LTAIA "Retina – Try It Online") -1 thanks to Neil. Takes the strings \$A\$ and \$B\$ separated by a line feed for the input. First, a Replace stage looks for each character in \$A\$ that when combined with the next character forms a pair that can be found in \$B\$ (`(..).*¶.*\1` in the lookahead), as well as every character of \$B\$ (`.*$` in the lookahead). Each of those characters is replaced by a semicolon followed by a line feed. This breaks \$A\$ into pieces that are uncommon with respect to \$B\$ and \$B\$ into individual characters, except with `;` in place of the last character of each piece. Each piece is on a separate line. Next, a Pad stage matches each whole line, and pads all of them to the longest length present. Finally, a Count stage matches each character in the first line (because `\G` makes the matches have to be consecutive, and `.` does not match line feeds), and produces the number of such characters. [Answer] # [Python 3](https://docs.python.org/3/), 80 bytes ``` f=lambda b,a,*r:{*zip(a,a[1:])}&{*zip(b,b[1:])}and f(b,*r,a[1:],a[:-1])or len(a) ``` [Try it online!](https://tio.run/##ZYrBCsMgEETv@QrJoWiwpaG3QL@k5LAmSqSJymqgaem3WxsPUjrLDjv7xm1hsuYSo7rOsIgRiODAG@xezVM7Chxubdez9yFnwUXOYEaiUmwwN5J3x7ZnFsksDQUW9eIsBuI3X6U9eRlQDit6bc2sFx1oe97FqsqhNoEqWq9usrMPuNWc1OkOdpjkovcPY6UH8C1A0S8VBYt/nKmAMj/4kSnelZZjIvED "Python 3 – Try It Online") Yes! Longest continuous substring again. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` ⟨s{s₂ᶠ¬{∋~s}}⟩ᶠlᵐ⌉ ``` Takes a list containing strings \$A\$ and \$B\$ as input; produces the longest length as output. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FcXVxY@amh5uW3BoTfWjju664traR/NXAvk5D7dOeNTT@f9/tFJBRn5JfnJGam5mcUlRpZKOglIpUCgHzIn9HwEA "Brachylog – Try It Online") ### Explanation Implements the spec pretty directly: ``` ⟨ ⟩ "Sandwich" construction: s The output is a substring (C) of the first string in the input (A) { } which satisfies this predicate with respect to the second string (B): s₂ᶠ The list of all length-two substrings of C ¬{ } does not satisfy this predicate: ∋ There exists an item in the list ~s which is a substring of B ᶠ Find all substrings that satisfy the sandwich predicate lᵐ Length of each ⌉ Maximum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Just can't seem to do better than 13. ``` ä@VèZÃôÎmÊÍÌÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5EBW6FrD9M5tys3MxA&input=InBob3RvY2hlbWlzdHJ5IgoidXBob2xzdHJ5Ig) ``` ã2 ô!øV ñÊÌÊÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4zIg9CH4ViDxyszKxA&input=InBob3RvY2hlbWlzdHJ5IgoidXBob2xzdHJ5Ig) ``` ä@VèZÃôÎmÊÍÌÄ :Implicit input of strings U & V ä :Consecutive pairs of U @ :Map each Z VèZ : Count the occurrences of Z in V à :End map ô :Split on elements with Î : A truthy sign (i.e., 1) m :Map Ê : Length Í :Sort Ì :Last element Ä :Add 1 ``` ``` ã2 ô!øV ñÊÌÊÄ :Implicit input of strings U & V ã2 :Substrings of U of length 3 ô :Split on elements !øV : Contained in V ñ :Sort by Ê : Length Ì :Last element Ê :Length Ä :Add 1 ``` [Answer] # [R](https://www.r-project.org/), ~~156~~ ~~107~~ ~~105~~ 99 bytes Or **[R](https://www.r-project.org/)>=4.1, 85 bytes** by replacing two `function` appearances with `\`s. ``` function(x,y,r=rle(!sapply((1:nchar(x))[-1],function(k)grepl(substr(x,k-1,k),y))))max(0,r$l[r$v])+1 ``` [Try it online!](https://tio.run/##RctRC4IwEAfw9z6FmQ8bTWhBUIF9EfFhsy1lU8epsX36tWXpHRzc/f4HXhZezn09tUOPLHEECtAC7UdmjHYI0XtfNwyQxbjMaUXWrMIvEEajcebjFJyonBKFicOhOmbRiUCmS8jeFT5SL1FqmmEa6kZ0bXhwKUnSOZz0d8GHJH8kt12Isa1iJswF6Yp8Q/7XS1TOto686nlRULIVzyj2B1f/AQ "R – Try It Online") Port of [@ovs's answer](https://codegolf.stackexchange.com/a/235642/55372). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ẆẆḊƇẇ€SʋÐḟẈṀ ``` [Try it online!](https://tio.run/##y0rNyan8///hrjYQ2tF1rP3hrvZHTWuCT3UfnvBwx/yHuzoe7mz4f3i50v//SgUZ@SX5yRmpuZnFJUWVSjoKSokIAOcmwblJiQio9F@pFKg/B6ETTCZBFSoBAA "Jelly – Try It Online") ## How it works ``` ẆẆḊƇẇ€SʋÐḟẈṀ - Main link. Takes A on the left, B on the right Ẇ - All contiguous substrings of A ʋÐḟ - Keep substrings S for which the dyadic link f(S, B) is 0: Ẇ - Substrings of S ḊƇ - Remove singleton lists € - Over each substring: ẇ - Is B a contiguous substring? S - Sum ẈṀ - Get the maximum length ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 19 bytes ``` U#MX J(_.BNIbMPa)^0 ``` Takes the two strings as command-line arguments. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 20-byte version in Pip Classic: [Try it online!](https://tio.run/##K8gs@P9fW1vZN0LBSyNez8nPM8k3IFEzzuD///8FGfkl@ckZqbmZxSVFlf9LgfwcEAsA "Pip – Try It Online") ### Explanation Based on [ovs's 05AB1E answer](https://codegolf.stackexchange.com/a/235642/16766): ``` U#MX J(_.BNIbMPa)^0 MPa Map this function to each pair of characters in a: _.B Concatenate them together NIb Return 1 if that string is not in b, 0 if it is J( ) Join the resulting list of 1s and 0s into a single string ^0 Split it on 0s MX Take the maximum (i.e. the longest run of 1s) # Get its length U Increment ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` K'2lv∑⁰vca¬;tL ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=K%272lv%E2%88%91%E2%81%B0vca%C2%AC%3BtL&inputs=hello%0Agolodbye&header=&footer=) A bit messy. ``` K # Substrings ' ; # Filtered by... a¬ # None of... 2lv∑ # Substrings of length 2 vc # Are contained in... ⁰ # The second input t # Get the last (and longest) element L # Get its length ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 37 bytes ``` ${#Last[{_&Has\`@&1\y==[]}\x]}:Slices ``` [Try it online!](https://tio.run/##XYxBC4JAEIXv/oqFxJOXroIQdOkQEdRtXWrUNRe3lJ0JXMTfvq1Qmb13Gb7vMUAERS1dxZLUhcNqD0h8uEQ7wOy6idaZTVMuxqwXY3LSqpDoDlKWyMOuK24iOBr1oLNE2gJK5FEVMx4wHz@oW2r977tCMjZm4dMTPd0ifk9gjvcAS5F/RT6bHOZ6tTCmqZQsPe3/oZ6o/aGN@UytCIRwLw "Attache – Try It Online") ## Explanation ``` ${#Last[{_&Has\`@&1\y==[]}\x]}:Slices ${ } a function taking inputs x and y :Slices ...where x = Slices[x] and y = Slices[y] { }\x all members _ of x where \y |the elements of y which `@&1 | |have a char at index 1 (i.e., length >= 2) _&Has\ | |and are contained in _ ==[] |is the empty list Last[ ] obtain the last such member # and return its length ``` ## Golfing Process **41 bytes:** `${#({None[_&Has,{#_>1}\y]}\x)[-1]}:Slices` **41 bytes:** `${#Last[{None[_&Has,{#_>1}\y]}\x]}:Slices` **40 bytes:** `${#Last[{None[_&Has,{_@1}\y]}\x]}:Slices` **39 bytes:** `${#Last[{None[_&Has,`@&1\y]}\x]}:Slices` **38 bytes:** `${#Last[{#(_&Has\`@&1\y)<1}\x]}:Slices` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 38 bytes ``` {#*((1&/^(2'y)?2')')#,/(''|1+!#x)[;x]} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxVju1qwyAYRv+/V+HMmLq5hQQKbV7YbqL/Qkd1a2gwJcV1oHTbtc8o+agBCec84Gmqa/bIefGQv/OSefFWMsFEJnPO2E/xdJc5UaPb/QJsq+t97f9s1ZAX4nDfG+T7RrUdOvRoRdhsa07Px/7SfxwPp/brYj1F+h1IF/8FbnZxo+YTBuESWCyMnowe1CopreYvuKjKUVnTtIdPipK6gNc3uIvczM9rZWyaU+fTHHK4DZdk6ibPr2QDi2ZJlBpgAYvcAHWkK1iWSpJoCWOkJG4Aa5jyJDHpjTEsTHza/AOK8Xsv) Takes `A` as `x` and `B` as `y`. * `,/(''|1+!#x)[;x]` generate all substrings of `A`, with the longest first * `(...)#` filter, keeping only those items where `(...)` has `1`s + `((...)')` apply the code in `(...)` to each item in the list being filtered + `2'` take 2-length substrings of the current item + `(2'y)?` retrieve their indices in the 2-length substrings of `B` (returning `0N` (null) if it is not present) + `1&/^` keep items where none of their 2-length substrings are present in `B` * `#*` return the length of the first (longest) uncommon substring [Answer] # [Python 3](https://docs.python.org/3/), ~~144~~ 124 bytes Naive approach, much room for golfing. ``` lambda a,b,l=len,r=range:max(l(c)for c in(a[x:y]for y in r(l(a)+1)for x in r(y))if all(c[n:n+2]not in b for n in r(l(c)-1))) ``` [Try it online!](https://tio.run/##RZBBa4QwEIXP668YvGjY2YJbCq3Uhb0UCj0U9uh6mESt0hglpqC/3k4U2eSS@ea9yUuG2TW9eV7q7L5o6mRJQChRZ7oyaDNL5qdKO5piHStR9xYUtCamfErnwpczl2C5S@KYrIJpI7MQbQ2k2Zeb1BzPhemdb0nwKrP7lDglQojFVaMbIYMwDIemd71qqq4dnZ0R/hhof4TTBd4CeiwEIg@TDcodypW@BJIeG2GjZ6b2t26rEjkrg1e@8mkcdOvi6G4iEQQ@oM/jM6650uBAEhXH8@Uu9maWH/jDuENy57hShSXT1jh@ItYxixgO1oM8@rh@fkUYfV9vt6jIVZaVBa6z2ft@4QmlWP4B "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` I⊕L⌈⪪⭆Φθκ¬№η⁺§θκι0 ``` [Try it online!](https://tio.run/##NcxBCsIwEEDRvacIXU0ggntXIggFWwo9wTSZJsE0qelUevsYBP/68bXDrBOGUobsI8MdN4Y26kwLRSYDT4qWHXR4@GVfYFyDZxi5YtvhCg8fmDK8lXhJJfpUD2mvH6fEEPYNbtxGQ8cfeFlTork08te1FJy0odm605ppxqmcP@EL "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @ovs' approach. ``` θ Input A Φ Filter out κ First character ⭆ Map over characters and join §θκ Previous character ⁺ Concatenated with ι Current character ¬№ Is not found in η Input B ⪪ 0 Split on `0`s ⌈ Longest string of `1`s L Length ⊕ Incremented I Cast to string Implicitly print ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~119 bytes~~ 116 bytes ``` int f(char*a,char*b){char*c=b,s=0,l=0;for(;a[1];*a++?l=l>++s?l:s:0)for(b=c;b[1];)*a-*b++|a[1]-*b?:s=*a=0;return-~l;} ``` [Try it online!](https://tio.run/##hZLdboIwGIbPuYrGnciPCaBIQq1eiPHga4FJqGAKJC7O3Tr7ENDqltA26c/zvE3TVpzPi08h2jYrapLOxRGUBc694@b13gvGnYq5jmQuTUs1p7D3DtQC295JJre2Xe1kVEWu2UHOBOUdNy1YWNy2vzsbR7uoYhbgFiqpG1UsfiS9tR9ZIWQTJ2STlVWtEjhtDaM7yQmyYm6Sq0FIdwYC3v5AGJmdj2VdimNyylD/mtGR84E3KMhXBH6P4Fm03ANqgaUW4O@BEXI9seoXOTyrFnlQLRGMaypPsyTW7IFcNHn9IkvdHlCu2eFo5@pt64Fc@tvBVtVxFImyqclmg68PnoM3aXaTO0mKWNJ/NB81f1pborac1laoraa1ALVgWlujtp7WQtTCvxq2/n8Slxq39hc "C++ (gcc) – Try It Online") I used ovs' characterization of longest uncommon substring as the longest sequence of adjacent length 2 substrings of \$A\$ that are not substrings of \$B\$ (plus 1). I only use `C++98`. The function takes two C-strings as input and modifies the first one. ~~I chose not to abuse the `?:` feature in `gcc`, but that would save at least 1 byte.~~ Following ceilingcat's comments, I guess it doesn't hurt to use non-standard code (using `?:`, UB with bitwise OR `|`). This saves 3 bytes. ### Explanation ``` int f(char* a, char* b) { // Take two C-strings as input char* c = b; // Remember the start of b char s = 0; // Current sequence length char l = 0; // Longest sequence length for (; a[1]; ++a) { // Iterate until before last character for (b = c; b[1];) { // Similar if (*a != *b++ or a[1] != *b) { // Compare pairs of characters } else { s = 0; // Reset current sequence length *a = 0; // Flag to indicate sequence reset } } if (*a) { // Check if sequence is reset ++s; // Increment current sequence length l = l > s ? l : s; // Update maximal sequence length } } return l + 1; // Increment to get substring length } ``` ]
[Question] [ (No, not [this](https://codegolf.stackexchange.com/questions/70432/mutually-fill-in-the-blanks) nor [any of these](https://codegolf.stackexchange.com/search?q=fill+in+the+blanks)) Given a string and a list of strings, fill in the all blanks in the input string with corresponding strings. ## Input/Output The input string contains only alphabetic characters, spaces, and underscores. It is nonempty and does not start with an underscore. In other words, the input string matches the regex `^[a-z A-Z]([a-z A-Z_]*[a-z A-Z])?$` Every string in the input list is nonempty and contains only alphanumeric characters and spaces. In other words, they match the regex `^[a-z A-Z]+$`. A blank is a contiguous sequence of underscores (`_`) which is neither preceded nor proceeded by an underscore. The input string contains `n` blanks for some positive integer `n`, and the list of strings contains exactly `n` strings. The output is obtained by replacing each `k`-th blank in the input string by the `k`-th string in the input list of strings. ## Example Given an input string `"I like _____ because _______ _____ing"` and a list of strings `["ice cream", "it is", "satisfy"]`, we can find the output as follows: * The first blank comes directly after `"like "`. We fill that in with `"ice cream"` to get `"I like ice cream because ______ _____ing"`. * The second blank comes directly after `"because "`. We fill that in with `"it is"` to get `"I like ice cream because it is _____ing"`. * The third blank comes directly after `"is "`. We fill that in with `"satisfy"` to get `"I like ice cream because it is satisfying"`. We output the final string `"I like ice cream because it is satisfying"`. ## Test Cases ``` input string, input list => output "Things _____ for those who ____ of how things work out _ Wooden",["work out best","make the best","John"] => "Things work out best for those who make the best of how things work out John Wooden" "I like _____ because _______ _____ing",["ice cream","it is","satisfy"] => "I like ice cream because it is satisfying" "If you are ___ willing to risk _____ you will ha_o settle for the ordi_____Jim ______n",["not","the usual","ve t","nary ","Roh"] => "If you are not willing to risk the usual you will have to settle for the ordinary Jim Rohn" "S____ is walking from ____ to ____ with n_oss of ___ W_____ Churchill",["uccess","failure","failure","o l","enthusiasm","inston"] => "Success is walking from failure to failure with no loss of enthusiasm Winston Churchill" "If_everyone_is_thinking ____ ____ somebody_isnt_thinking G____e P____n",[" "," "," ","alike","then"," "," ","eorg","atto"] => "If everyone is thinking alike then somebody isnt thinking George Patton" "Pe_________e __say ____motivation does__ last Well___her doe_ bathing____thats why we rec____nd it daily _ __________lar",["opl","often ","that ","nt"," neit","s"," ","omme","Zig","Zig"] => "People often say that motivation doesnt last Well neither does bathing thats why we recommend it daily Zig Ziglar" ``` [Answer] # [Convex](https://github.com/GamrCorps/Convex), 5 bytes ``` '_%.\ ``` [Try it online!](https://tio.run/##PY3NCgIxDIRfZSiIN5/Fm@APobpxW@gmsg277tPXBtQcZj4mJPNQWfjd2p52h2tr7RL0VQKCPo0FHSxFcxfrAuHsXp091Wnibuc8fvXWwpHpNwyiGjc4T2p5iZZVMChXIpRYDScupW8Tzx4T7tFSltEvvLpiTRtWxswPz2RANgwxl/4V/yIqcQ4f "Convex – Try It Online") Convex is a CJam-based language, and this answer is almost the same as my CJam answer, except for `l~` which is unneeded here, since Convex does automatic argument evaluation at the start of the program. Explanation: ``` '_%.\ e# Full program only '_ e# Push '_' % e# Split and remove empty chunks .\ e# Vectorize by Swap ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` r"_+"@Vv ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=ciJfKyJAVnY=&input=IklmIHlvdSBhcmUgX19fIHdpbGxpbmcgdG8gcmlzayBfX19fXyB5b3Ugd2lsbCBoYV9vIHNldHRsZSBmb3IgdGhlIG9yZGlfX19fX0ppbSBfX19fX19uIixbIm5vdCIsInRoZSB1c3VhbCIsInZlIHQiLCJuYXJ5ICIsIlJvaCJdID0+ICJJZiB5b3UgYXJlIG5vdCB3aWxsaW5nIHRvIHJpc2sgdGhlIHVzdWFsIHlvdSB3aWxsIGhhdmUgdG8gc2V0dGxlIGZvciB0aGUgb3JkaW5hcnkgSmltIFJvaG4i) I feel I missed some hidden catch in the rules because this is extremely simple: "replace each run of underscores in the string with the next item in the array." [Answer] # JavaScript, 35 bytes ``` a=>b=>a.replace(/_+/g,a=>b.shift()) ``` [Try it online](https://tio.run/##VVPBbtswDL33K4icYixztw9oLzsM66nYBgRYZriMTUdqbDEQ5Rj@@oxUnGwzYNEiKb7HR/kdzyhN9Kf0MXBLl@7pgk/P@6dnLCOdemxo/Vh/eDxszFuK811aF8XlFLkhkVJSy2Mqp@gTrXcPu9VP58NBoLYHOo6QHAvB5Dj7gDtwPKk3p00cj6AFoIYtK3xYbXaru3NPklab1YBH0gN027@wC6uq2ijaN@i9Bq9oe2pwlGWn@7wqjNX0DUETCQc97xN4USuYvHTzrVQHM4@AMReAyfe9noXEEL0cFwjLsAg4rBmEUupp6ZKAY@tz2osfFhK5n8DG2jJGGbHX77P2oyZgnEHtd3YLiR8Zxasw2B8Nvot8rWVE6iux5CDULGJammd75fbFjbFxSs4wx8bGo7U79P0Y6b8vBiNBIblRPErWJEjiu6pdTWeKMweqvdQ2q0zmrioID7TndtZwSH8TvlqQ4PXeunV3e9FGdRUi/OMmjgeLpsQL/CvVt8dmIThn0IGTP@vIOEDLJMqiR0mwpb7XqKNobr0FmO@WnUgOk0rpZpgIIjWZVgs6/1a10KpwB6p7jEaYTyYNd4kCZK6YzAYbFwTyZk1WMC8PgzX0yx@WtaoeqnLA01p/lm6Nu09VoevnqijKd/bh7Xd4Ky5/AA) [Answer] # [Ruby](https://www.ruby-lang.org/), 28 + 1 = 29 bytes ``` $_=gsub(/_+/){|i|gets[/.*/]} ``` Uses `-p` The first line is the format string, the rest of the lines are the array. [Try it online!](https://tio.run/##PcpLCsIwFIXheVdxBw58oFmBG3AsOBAJDd4moZhTchOC2G7dWCt4Zufjj9k8a13po5Vs1krv1OY1@tFykqs6bNVtqvXsfLBC@jvqECk5CFNxWIzQkUOZdckKYk/IiTRdgDuH5i@GJTWPtue55d87wYU3huQRpO6HDw "Ruby – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 42 bytes ``` a=>b=>re.sub("_+",_=>b.pop(0),a) import re ``` [Try it online!](https://tio.run/##PctBCsIwFATQvaf4/FWCpXiB9gCuBRciocUfU0oz4Selx4@1oLObx0xSFMTquzp0/dj1Km1eR8PuzI3bpU1I5mKbwZ6mJUELqdSkUyzGG76FKb4zuW/IQ6kEZKEt4DCCp4Bt12O2QWfCWsjRHXhJZGse/NdRcuGGl2GW/SG/fkWI/LS2fgA "Proton – Try It Online") Stupid imports... Same thing in python: # [Python 3](https://docs.python.org/3/), 53 bytes ``` lambda a,b:re.sub("_+",lambda _:b.pop(0),a) import re ``` [Try it online!](https://tio.run/##PcxBCsIwEAXQvacYZpVgKIK7ghdwLbioEhI6MaU2E5KU4uljLers/uP/ia/iORyrO93q00y2N2CUbRM1ebYC9R7Vl3Vrm8hRHKQycjdMkVOBRDWmIRThBF78EB4Z9OfAcYL1cyZYPG8G7MDzsupWWziNwHMBDVfmngKqDv9oKRdUOJmR1gH98pl9wLuU9Q0 "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` '_+'i1&YX ``` [**Try it online!**](https://tio.run/##y00syfn/Xz1eWz3TUC0y4v//avXM5FSF5KLUxFx1HfXMEoXMYiBdnFiSWZxWqV7Lpe6pkJOZnaoQDwIKSanJiaXFUB6QDyYz89LVAQ) ### Explanation ``` '_+' % Push this string: regexp pattern i % Input cell array of replacement strings 1 % Push 1 &YX % Four-input regexp replacement. This implicitly inputs the original % string, and consecutively replaces each first occurrence of the % regexp pattern in that string by one of the replacement strings. % Implicitly display ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` l~'_%.\ ``` [Try it online!](https://tio.run/##PY3NCgIxDIRfZSiIN5/Fm@APIe7GbaU/sg0ue9lXrw2oOcx8TEhmeHJqLW572h2urV1ceUUHVx4qGR3Us5pn7YIswbwaW1pSkm7nMH31BncU@o2AqPIK41Q0vFlDyRiLVCJEroqTxNi3XmaLCXdWH/JkF1ZdsfgVi2CWwbI8IihGDrF/xb@IIs/uAw "CJam – Try It Online") -1 thanks to a clever trick by [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender). Explanation: ``` l~'_%.\ e# Full program only l e# Input line ~ e# Eval '_ e# Push '_' % e# Split and remove empty chunks .\ e# Vectorize by Swap ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` ṣ”_¬Ðfż ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGubGH1pzeEKaTtT///@VPNPiU8tSiyrz81LjM4vjSzIy87Iz89IV4oEAQhTn56Ym5adUAqXzShAK3EGSqQoBICpP6X@0koKSDhwn5mRmpwLpkozUPCTh1PyidJBsSUm@UiwA "Jelly – Try It Online") Edit: Saved 1 byte thanks to @Erik the Outgolfer. Explanation: ``` ṣ”_ Split on underscores ¬Ðf Discard empty values ż Zip with second input Implicit concatenated output ``` [Answer] # [Perl 5](https://www.perl.org/), 25 + 1 (-p) = 26 bytes ``` @a=eval<>;s|_+|shift@a|eg ``` [Try it online!](https://tio.run/##Pcq7DgIhFITh3qc4odKopZWXbG1tYkkwHvaQXRkCKA3PLq6b6HTz5Q8cx11rnTnyy4yH0z5Vva5JnM2dqdy3dhHn@0T6O7KIlAWJqQhmI1gSlEnnrCAOhGcmTVfgzn6xVH@7ccpqox5m4Knn3z9DvFq9EbKDT20bPg "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` import re s,l=input() for i in l:s=re.sub('_+',i,s,1) print s ``` [Try it online!](https://tio.run/##VVNNa9tAEL3rVwy6JKGi0B4DPpW0NJeGNmBoCWItjbyLVztiZ2RHv96dWTlus2CNdr7emzfytIin9PncUY@wgVzX9TmME2WBjBU3cRPSNMvtXTVQhgAhQbznTcaPPO9ub9oPN01ouPl0V005JAE@a4eqkrzcV6Dn5ENEeM4zrnc7@IodGGCFrx1OAg8/vj7kTHlNmRxrl2cf0p6htQOGrTwZtR8VH9AAnk7qLWknygegWaCFLWnnVDd/6qtzhyx1U4/ugFqAb/dH8ql@qervEINGVqgddm7my03v5akY1jB0CF1GN2pxEAislp0EHpbSZ4CFZnC5VMMpxKiFIAQ58OHS3zIsAt61BIwiqs86HwLlPpS0xzBeGJRJEhlfy5h5dlHfjzqJmuTyAmp/kjcGvwpEUD1cPBj2kGltZCzalZV4SC0xm4Tm2a7Evvg5d7qtaIBz1yHbeIMLcc747o3AGGASP3NwXNRILLSKObR4xLxQwjZwa/spTK5iAtOIO@oXDSf5l/DNgghP16Ftrrefsw2tEqT/3Eh5b1ERMuwnbN@OrYDdUhBHknDUNVGCnpCVQnQssMUYNeoxm1s378rHZBXinaiIfoET6v@gK5x60J33qoJ2hStQG102tjSZKDQIJihEnZhNtiVIGMyaoGBeGkeb5nfYX54vfwE "Python 2 – Try It Online") Damn. ## [Python 2](https://docs.python.org/2/), 63 bytes ``` import re f=lambda s,l:l and f(re.sub('_+',l[0],s,1),l[1:])or s ``` [Try it online!](https://tio.run/##VVNNi9tADL3nVwhfNmlD6fYY6KlsS/fSpV0IdAlmYsuZIeORGclJ/etTaZxNtwJbM/p8erKHSTylT5dL6AfKAhkX3efo@n3rgNdxE8GlFrplxg887pd39fu7dXz5uFvz@n6lp/vNbkUZ@CJ52ixA5exDRHjOI853kyGHJFrlXUjDKMvVaoF/GhwEHn58fciZ8hw6OOZL9exDOjDUJtBpcUXIqHWp2IA68HRWawk7Uz4CjQI1bIlaTNX6pboZ98hSraveHVET8PX@SD5Vu0X1HWJQz9xqj40b@XrTe3lrDysYGoQmo@s1OQgEVs1OAndTqdPBRCO4XLLhHGLURBCCHPh4rW8R5gHvagJGEeVpng@BchtK2GPorwjKJIkMr0WMPLqo55NOoiq5PIHqn@QNwa/SIigfLh6td5dpLmQo6hmVeEg1MRuFZtnOwL74MTe6tWgNx6ZBtvE6F@KY8b8TgSHAJH7k4LiwkVhoJrOr8YR5ooR14Nr2U5DcyASmHvfUTupO8i/gmzkRnm5D21yvj7MNzRSkN2akfDCvCFnvJ6xfxVbAbiode5Jw0jVRgpaQFUJ0LLDFGNXrMZtZN@/Kx2QZ4p0oiX6CM@rP0BRMLejOW2VBq8KtUR1dNrQ0GCnUCSYoQJ2YTrYlSBhMG6FgVup7m@Z3OFzfu78 "Python 2 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` s.i:E"_+"3 ``` **[Try it here!](https://pyth.herokuapp.com/?code=s.i%3AE%22_%2B%223&input=%5B%22work+out+best%22%2C%22make+the+best%22%2C%22John%22%5D%0A%22Things+_____+for+those+who+____+of+how+things+work+out+_+Wooden%22&debug=0)** # How it works? ``` s.i:E"_+"3 Full program. :E 3 Split the second input on matches of the regex... "_+" The regex "_+" (matches 1 or more underscores) .i Interleave the elements of the split list with the input. s Join to a string. ``` [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 11 bytes ``` x='_+'³[x‘r ``` Takes a string and a stack of strings on the top of the stack. The first (top) element of a stack is to the right, hence input is right to left. ## Explained ``` x='_+'³[x‘r x= # Set the stack of replacements to x '_+'³ r # Replace each chunk of _'s with the function... [ # Pop off the group of _'s x‘ # Pop the top element off x. Use that. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6r@SpkJOZnaoQDwIKSanJiaXFUB6QDyYz89KVuDSUihNLMovTKpUUlDJLFDKLQXRyqkJyUWpirpLm/wpb9Xht9UOboyseNcwo@v8fAA "RProgN 2 – Try It Online") [Answer] # Java 8, 57 bytes ``` a->s->{for(String i:a)s=s.replaceFirst("_+",i);return s;} ``` When I read the challenge I at first thought we should make a grammatically correct sentence with the words being in random order, but just replacing lines with each sequential word is easier. ;) **Explanation:** [Try it here.](https://tio.run/##nVRRa9tADH7vrxB@SljiH7CseRl0rDAo66CwMczFlutrzidzOieYkt@eSWcn3SCDLQe2zpIsf98nnV/MziypQ/9SbY@lM8zwxVgPrzcAHE20JbxISt5H6/K692W05PO7afPhMQbrn3/8XPxD1gJGu15DCbdwNMs1L9evNYXZGAD73sz5lvOAnTMl3tnAcZYV77KFna8Cxj544NXhuLoRdF2/cYJuArkjW0EryGcnSGDmSgLgceCIbU59zDsJRednZW66zg0zj3s45b9CtqewBcmDDXLMFpC1ZosQGzw77qnxGRzmqbCuqVD2rZEiDIUuEEryFjHCvqHkA6qhob14U9r5QwU8EVXos/l89Z9gbYlQBjRttshsBMtiWbTgeriI8DM4K2xGhBssTc/Tkzynu1S@AocnUSZTkXrujZP9TjQT400YQOxXai4DqmGgHkxIMGBvndMhiATB8nYCqhkagcYUBIwxOpz0RaBQ2ZR2b9uJyjVK9mWJrPLVxro@4B87AqWEPjY9W8NJbc@RLo/BYwJtpcPGbZVNHWiEpryKkWdswBckJ02GQj1PI9WPTR/KRrheQUF1Pl1G@zy2xP/mRgrPGo2R/tKOAncYBvJYWC50UhOD83wAU4sbqgYJ@/iW8EmDCA/Xyk@dKkx1RA8Jtolqvc4QeLRqtTugXmpb5fbdPk/3S1QesDgtnS02QyLQUrQ7o38kqAhZGMn/LsITOifRBoO65WyYdEr1DcUivWwG2CMELBPFCuS4VTIgUhXOHyqcCYm8oDncHI6/AA) ``` a->s->{ // Method with String-array and String parameter and String return-type for(String i:a) // Loop over the input-array s=s.replaceFirst("_+",i); // Replace the first line (1 or more adjacent "_") with the substring // End of loop (implicit / single-line body) return s; // Return the result } // End of method ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` „__¤:sv'_y.; ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcO8@PhDS6yKy9TjK/Ws///3TItPLUstqszPS43PLI4vycjMy87MS1eIBwIIUZyfm5qUn1IJlM4rQShwB0mmKgSAqDyuaCUFJR04TszJzE4F0iUZqXlIwqn5Rekg2ZKSfKVYAA "05AB1E – Try It Online") **Explanation** ``` „__¤: # replace all runs of multiple "_" with a single "_" sv # for each y in the list of replacements '_y.; # replace the first instance of "_" with y ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~97~~ 96 + 18 bytes Saved 1 byte thanks to **Kevin Cruijssen**! The 18 bytes are for using `System.Linq`. ``` s=>l=>string.Concat(s.Split('_').Where(x=>x!="").Zip(l.Concat(new[]{""}),(x,y)=>x+y).ToArray()); ``` [Try it online!](https://tio.run/##hZFfS8MwEMCf3ac4@7IEa7/AbEEEwaEgbjBwjBK76xqW5WYuXVfGPvtM90cFH8zLJXe/S35JCr4tyOGhZm0XMGrZ4yp51vZz0CuMYoZXRwunVrDrXbFXXhewIT2HF6WtYO9C13QGyi1YdsjVeYfH2hZ3p3IMf3PTWQynWZZBCemB08yk2SmVPJAtlBecjNZGe9HP@zKZVOhQbNNse51GkUze9VqYC2mxmc52UbSXsdjGrQzUTSuTMd07p1oh5eAw@HELTUwGk4nTHsNVUZQiGlfhZIa8G1CSA18RIzQVHXNAJVTUhOwRa8gtgWoPOUyI5mgjeZH4Ln0g@yiOVmqJoQ0v6yFVNojK/4SeSmipDi@LnQA02pjuhzyB07w8i3ZEV4FK5QSM3hs82yOQm@sjNtSrE5//8rTU2XRczbUyYb4JniFY5VoI8Y2qs@e@tz98AQ "C# (.NET Core) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` s,l=input();import re;print re.sub("_+","%s",s)%l ``` [Try it online!](https://tio.run/##xVRNa9wwEL3nVwyCQJYuPfSYkNMeQnMKTWGhpRitPV6JlTWLJMc1pb99OyN/7EdbKDSlBlsfM3rvaaTnfZ8M@XeH1b1S6hCX7t76fZtuFne22VNIEPBuH6yXztvYbm5U8UYt1XVUy7i4docc@6Y@Guu3EQp5oKYAjBoROkN5DqgGQx3P5rSOwg6oTVDAmqhCr24nhDm0wZgukBq9Qx7iEPsN5CMZP6Eur9R7cJZXDcI2WOo2jiMe5y8vZ/oxz5YIZUDdzLk2gY0QdbKx7iVXQGvoqQUdMhR01jmOQCIINu5GMsmQCBhdEERMyeG4IQQKlc1pj7YZ5UgRToA9pZ@AZWUbW@1OwV9Q4r/A9zr0IPgfuCQi@znr4t102u0Etw40sAtCMWwlGfAFxSj1lZn1sJuVaUNpmJFVPrdliZxxiVRr69qQ5UzdAY/AjYjok2mj1bGBtfUxkT9BzpUt8AVDTx4LGws53Iw/HxdEanBDVc9hn44JDxJEeDqp5AQkOuc8nY@ZS@RnJBCkY8YDUtgykk6sTjQ9YTE9ct5R91lJQ8m@8LXgLVSEkaU5zddyjc5x1GCQab5zOt9QWZGMTlwy00OHbKcya63khlVcLkaFmahwOvAunpD2fKpUJ9HLxAIBF8wsfmYGj1zxgTtO3ACXzNQ0eMr8yW7lFdLvn@OXwfFX/Ee4w69Yqo6PB2F1KwNYqcNf230JN@rM6fxLOXM3j8XIavGnDhbE2by8OtuW29G4GejfuFaY2azMNduT@@JKbrIHuWULioTXcaAwDhZk5NFpZz32G3@PXpN6ZLMNZXgVi4kI2dn0ZmMNRfAn02ImibKZhPy/eUnkspekONlMWSl7Sc5IDiobR@6L9GVWLMINu2L8Ln4A "Python 2 – Try It Online") The list input is taken as a tuple. Allowing actual lists as input would add another seven bytes, as a conversion would be required (`tuple(...)`). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes ``` \_/';Y ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%5C_%2F%27%3BY&inputs=____%20in%20____%20blanks%0A%5B%22fill%22%2C%22the%22%5D&header=&footer=) Look Ma, no Unicode! ``` \_/ # Split on underscores '; # Filter out empty strings Y # Interleave with fill-in values # (s flag) concatenate the top of stack ``` [Answer] # [Factor](https://factorcode.org/), 34 bytes ``` [ R/ _+/ "%s"re-replace vsprintf ] ``` [Try it online!](https://tio.run/##ZVPBittADL3nK4Shp9LsvYVeelh2D2XZbQm0FKPYcmbIeGRG46Qm7Len0tjJbugYLI8k6z290XTYZE7nny8P3@8/A4pwI5BoR38H6Dj1mLOPOxgS5TwNyccMX1ar0wp0nfSpjpz2wGOGLUmuoOpxT5AdXfaP7GIFr1D9cFpIoLZlpTWJheDouPiAO3B8VG9Ju5atYcPcktV4A/UNQZMIewXwGbyoFcxeuqlgPUDwSmPG2lKDoyw73Ze3gtxUjGxkjfcoIwb9PmgbaiKmCdQ@s5tLdzDxCJhKQTj6EEygzJC87BdIy7AIOKwZRLULtPRMwKn1Je3R9wup2@7GpiGxljr0YUx088Vg5ChmN4pHKQpEyTyL/FLgveqHYW@8usQziDGsZ8bZQaxZxCQ3z2Ym/c2NqXHK@obM@wdN1Vmm@M5NnHYWzZkXiWo6UJo4Uu2lthMtXK7qg3BPW24nDcf8lnBvQYKn/yXhwbrmLlOEQgCz2WgnBJG8WVMMzMt9byx/@d3lraSeqL4sOznBqVDpOfuDTg5HaJlEuQWUDBsKQaOOkrl1hrDMpf1h2Kqvm@BIelOaQrYFHcNWD0mrwhWoDpisjdfzb3i@g/rjHVQfpEr0KdEQUIf4IOVOdfDnfFKW5f597XGA9Xp9/gc "Factor – Try It Online") * `R/ _+/ "%s"re-replace` Replace any amount of contiguous underscores with `%s`. * `vsprintf` Interpolate a sequence of strings into another string at every `%s`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 27 bytes ``` {(*c),/y,'1_c:(~#:')_"_"\x} ``` [Try it online!](https://ngn.codeberg.page/k#eJw9y8EKwjAQBNB7vmJZD02kIF7TP/AseFBZkroxUsxCE4ki+u3Wgs5tHjPBPvWyN+3q0TZr6q1+L2xjCAkP95dSzuI2XtI5A30DQUYoUTJDjTIbSIAoddJ5VmUcQG4FCHYiJ06ovNX4Z8+5YIdXN/B04V/fSExolAp71/njB5wxL0c=) Splitting based on "runs of underscores" seems longer than splitting by single underscores and removing empty strings. ``` {(*c),/y,'1_c:(~#:')_"_"\x} x: string, y: substitution list "_"\x split by single underscores (~#:')_ remove empty strings c: call it c y,'1_ zipped concatenate with c, head removed to match lengths (*c),/ join them and add back the head of c ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 46 bytes ``` param($a,$b)-join($a-split'_+'|%{$_ $b[$i++]}) ``` [Try it online!](https://tio.run/##dVTbbtpAEH3nK0bIaYICnxApUh6i5qUoiYTUKLIWexxvsHfo7joUJXw7nRkbG2hrCby7c@acua3XtEEfSqyqWUYe90lx87lfG2/qq8RMk@Vk9k7W8XoW1pWNl@n15dfFZ5KOkuVLYq@vX3eT/W40ur0aAT9TuL0aP5fWvQVI5YGCPMSSAsKmJD0DKqCkDZ8qbEN@BdRESGFBlKMbT@FA0duWGOIZVW1WyFtsbf/hfKDSDbQc2wmjKJ3QyIG4jCeTIZ3vUFnGtOksMTNN6Ha813/WFM8OaDOEzKOpe7CNYAMEE20oti2YeXuc@CpEFh3qNIICttSA8aoLG1tVzAKRwNuw6iIThFigNClBwBgr7EqGQD63CnuwdRe71vmI2VH8i1lcm9CY6pj9A8X@DwFn/BZE4FFKqJEzqcj0PLIRf3krXBYMP0n3SfPhim1MtZJwCk9t1CKctiWIJbiUQpDOy8mircJd2fis5ECF@KnJMmTIOVVhbNV4TeOwbAkJqo4SXSybYE2oYWFdiOROqDnKlltkOo6zJXPJayDSNivVWXNT/EC/JYepDalMsEbajxcEqnFJ@ZbNLg6AezEizI@beWCSlHug0bHkHrieCoRqQNwj@TemMlGi07C0M8OfcnStdKcm8VUIO59kNsf08MjgBrPVfGqK9oOnnEuaEwZOsDJ8gxf8CWJriV6O@aYZvcziEUsTuYXlFjYIHjPNOJdrlXO9mRV6obQyXoKZI615PKmIkjUrCwecSXMJemlwyCPQioeDOMC5NNU1Hkv/tG/ya1U5Z1bV5qtuWy/W1XHXoVcZvee6U4twypt5Di8u4wS@4AI@tZxJ4DFCl@EUEvy9xixizkv@mOUBboC/xoryGJoq8sG3pBh8OpxCXuZPdw2PYP1j@c4sr3DbCugzfpYv6Z0JOBbSjm2GvwbRAfx40OpwatmNdvs/ "PowerShell Core – Try It Online") [Answer] # Regex (RE2 or better), 23 bytes ``` s/_+(.*?)`([^`]*)/$2$1/ ``` [Try it online!](https://tio.run/##bVPRbts4EHz3V2yEAJESx0l6fbn4lKAocIcUaBE0BQLUcVVaWlmEKVIgKTuOa/56bkkptns4GrbF5e7MznA1V68NyxdsjlAzLsfA60ZpC5Gxmsu5ifYRjXN8bg4CZW0Pduowd9aWXNF@ULYyD8hxApsl06ChQ4YUfr6ai@wsHp3eJi6e/HDT0@Ti@N3x1cXrz7FO9eTqWqCMdXJ@NR0PgBYvQU8up0fpiTmBTcMkz@PoMzfG4z1F5imKku0YCrhOKZGqwDPWwyzteh99ZjavHgJ/HE0uz//8cP70NGXn2@M4OT0b/XVz@2MaDbsG4yJJxp6yuDlxJ79@1TvGO7lkghdQoOA1t6iJNfSnjWfunRs9NILbWA/hP3hBlEmO0vc7xEetSIFs6xlqUOUe2QRBmszShgQFlvkhyZ0s8JngJn9Mh9E8Sm7SyzGU4jDlKzaC5bhPGkbR8Pyqa6YUR2kUwcZTRPFtBGe@@gyia/@o/VMS@RYwmNrb2Br7UdUNF4SahKZMzqSk5ikp3P3oC64eulisyAtbcEmMLz6hZMIgdan0W9nIp/oJCVh@dQr602/4bOOku82m19XV7wv8ypW0vs7qlvAb7xq@yf8gRHfxf9NExmIIfjJj1qMlb1P5O2A/dEcBeKPRtloCIztCIIW5NyYE/4coZkN/a@@myW@Y2874Jk0FbGYa2YLwRNrskrbh/GVDr9fonoCsIGu245e0k7ULx00HvB1sX79V/qoh8ysYYytlEFaVCjE/U5VaUTSkrZRegGotZPCoVIHS7SIzNNbVbIGUi93uk6rk4A4Ep2BHMMOctabf0T78ErLjOUJOkmrHLXDjDLPclOvBXQlr1QLToQZWXAhvtlWguVn0qD7Dn0DFMgUGrRXYa0FQuuAh7ROve17ppLLOH7amZcItqWcnmV6D@6qqwUMA5aSWiYVnK7XqSj1v1vVhK5CZMsYb5COPXSsfq1bnFfXi2jxHY1zJuGg17v4VCIfSVq3hzJBaaawik8oMl6jXSmLGTebdDsw7k8CoGmeqWNOxtPuEf/whwn0nC8KHecO9vC6ASs8ds1YN7jF7W95Ow9YBu1aWL8lvJaFQaIhMMGPhEYWg04reTQrT3bEwBL7CVsySPdUaVkgDnAf2AujqCpJJqLAjygTTTjXCqdKiBOdLwUnrQCK3zjgAp@oa3Xc@999/AQ "Go – Try It Online") - RE2 [Try it online!](https://tio.run/##bVPbbttGEH3XV0wCIyQVi7LToECi0EFRFIUDFAiSAgbqKNyVOBS3Wu4wO0upkuP@ujtLOkofQkGXncs5Z86O/tY7zWtvujBzVOHDsbhY@CI9Flfz6QPPy@dpPn2bqfT2s1pOs/nZi7PL@cN0fszyQB@DN26TZjlbs8b05/PZy2wBpobU314snxQJJxmExtMekj8MsxTDU36aTCoowN9eLsfi6ir5N4GvX6HKWx3WTTq/vZi9@mX2aaln92dpNn2ev7l6@3k5z05o126nramgQmtaE9AnEx8xc@6sCWn1TUZu0W1CA08KeHlqvvEkQlzfrtAD1d9BOFkAD9JeiLQI@AE3v/3TpVHruYR/WmYTj1964zFNPOrKGodJlq/ld8BrJxi1FifujOv68LrztEbmnENl3H2Wk0uToePcFld3R3j2DP5XQn3I9150pMknl8gEx@JyAtAVdgE1@XSxyO5a0dTlHjsbafw58DBp2hZFl61ExXYhDe39j3G77D57@LORa2Ao4xNxxRVihH1DQywa0ohLYSzbk9@CIEAJNyT74dQpskIOqtVblFocT@@ocZNrsEaCI8EK17rnx5Och09BVrIwEG1rlQlgWLEOhuvD5LqGA/Wg/dADe2NtXJtA4A1vH1FjRcxAo0sCxhAsPs6CQL4yQ9k70z7yOuUoqJjsuddW7USzctofQH2gZvJxADUyrbbbyFZ7GlsjbznqkC1yJTFHg2LkZpTya9P7dSNaVL@OjqtaG9t7PH0TWIUuND0bzTKt40BiUl3iDv2BHJaGy@j2wHwyCZhaXFF1kLQL3wt@j0mE9@NYMLx0NDyONwaQ/EbpEGjyHstvT7ST9WHAbimYnfhNDipCFjKrOcANWivZRv4VEpa708MSxI7Q6CD2NAfYI3hcD@wVyNVVMqagwomotNor6qyiOqADFVtBuaDAoQmKFYCitkX1l9nE938 "JavaScript (Node.js) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##RVJNjxMxDL33V1iratUuEqVInMrCgQPaPa0AqRIsxOnU00TNxFXsaTWL@O0lyZSS0czIzx/Pfs6BUnh3nr7cv1mdnA80e/9h/rtx3B1WS6jIWRbm1ez13cc5zn78wp9388X07XS5OK@mL7e3h@Sj3jzHm2zdL1dQ7an5c/7mfNwJmHKg5QTqWCiX5IoBt@D4lNEaduK0B@4VDKyZtxTximxIFDu7pxxLo/XILk4eIPgMjgQbamwvFyvb9Zsro28ImkS2Q6/gBcWql3aYPLQwcA821Rw4@RByOChD8rK/VC0RxQPOGgYh1UCXWQg4bX0Ne/TdhTdiZMXi7KW3AY@5Z4w2DYBf2E2@1qI@T2vDvrC1icfUwmvGPtRBNCxSBCrIemzlk@tTk9cRsG8aEsHW@tAnuv4ZAlJU14u3kqeNopxFag0dKQ0cyXgxRe3KfBUJhDva8HbI7qj/Az4XJ8HTOBbUxxbBy3gjQJx2aFV58kTm3ylyih1q7Y7VH7PeHGHLJJksWFFYUwjZ6ygVOO/O1ktQMtRZzfK4AU4EiZrKvoW8um0eM1eFK5EJNiEfAnKrFAFLKmBUhEheURAAuesIv/tdef8C "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##fVRtb9s2EP7uX3ERhEpK5bd0XwZVDYo2KxxsbeC0y7DEJWmJsjhTpEBScZw2@@vZUcpSpFhnQ293x7vneXjHtm7vXx63dQuhgRxawzfE8FaygsfRdHJ4TEjNpCOFblohubmKr5Lsajm1UQoRXhUayYb7AOW4cjYm5JfFryeEJCnMk2wkKohDczlbHeSRjRJwtdE7UHwHJzcFb53QKo5@E9YKtYHABhGuCUuEgovmqwz69eWr6O8Ivn4d8DXMFTWiu5yNf349vlqx8V0YJ4fPJy9fHX9eTaM0LJP/LhQs1DWTooSSS9EIx03gy3nm/KaVuuRYK8XSyVC40J1yCD85yH/6QcYLoxG46po1N6Crb5ltn9oOTI6QSVgN7y/8uy@JNCcDTf8s0bpBa8Wk5dmo0oYzpGmdIbaVAmFUCTALYZF86UUp4NkzQHerbRxsRGNvXr/99MdpF6QYkud5n@gHgn9Shhd6o8QtL6GSDKWPJmExibz@g@ZFnkebKAk3uTMdz4BjNo97gsCL7G5U7QzSjM8/vj1ZLtPg7M3y5AiukfRTB/aFdQxVjHwE@f1keb748D5Kvo8LrpQXTChBLHdx0BaGT9as2DqDN9KLGqQQjOeBR/gkDLl0xiKx/w/7a3DNfB2UNw5v81kWyrzC/rUex@J9kiVfkH4cyktUVnKFb8l4vsrzHh8G226NHjSns3Q878XCRAkvau1DcBNv83k2AvAVMkwXtvmTqQoNNpjFS6Ywnqd@P/skB/iyxj3fYgrpu6PN7sCnhSCUQXb33SDGSXZvp@R5jDOa0PjyM10dJtPwKJxP7@8/1jhNFoj/eSDYBBp3b4fJehP2aY1N4YawnTZb0J0DAhcaZ0DRR8uaW0cbtuUYy4evU12r0QKkQONQYM0L1tmHL/zu75iZioIDCs8aKhwISy1zwlb70aKCve6AmX4N7ISUfvqdBiPs9iGrj/AeqBnRgLvoJH/gwkGbUvRhp6J5qKuo0o56Z2c7Juk1YqaKmT3Qpa5H531SgWyZ3PpqldHDUl@XDDhcDYpoa71A3nIxQHlTd6aoEQvtioJbSysmZGf441ODpHj41Z0VzCJbbHmNIlWEX3Oz14oTYYlXu6/8KBJY3fC1LvfoVu5bwDvv5HA20IL@z7zgnt5g4NpsKHNOj844@ffn5bRs3@dutBPXzE87lJpbLCaZdXDBpURvjYcVmnHvWN8EfoWrmUN56j3sOOBI9dVLwK0rkSZmhcdCRDJDdSuprvDQB@qXAlWO4jkjHLUUgOqm4fRPsfHXPw "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##fVVtb9s2EP7uX3Hxglmynfd1y6w4BTYMQ4piKNoO2da0Ii1RFmGKFEgqjhN7P33ZkZId2aunJFZ4d89zrzwnZXk0TZLnb7hMRJUyuJooZeyJZlP2cJyX5XUnyamGuPz0GcbwvvvTfD6bXFR/LhZ/fMy/n@fBszmJB8Fx/3VIgk9fyOd@eHJ4fnh28hzumnaH0C/HcRl1XrxxdKYZLa47XFooNX7GTGulg0RJY8E77xfMGDpl4ZOx6WiUoAFcXUEjdf96OZOpiEAzW2kJZ9EKHKVZSEsfGs7wqdG2HXU/eBPwp24YreqMUyZ4MT6NAAsikEpTOWWBV8mhf9H6NdmwVkh6GdtAHtEQrsab8wTPa9p@xmUae/KarG9CeOoAPpnSEESRGQzWEvfwDIIDZ9Q4@e33t2@jjZYJw7xJ34zHvbu7HkJrxGCwg1l9HeRD2ViamnrVWfmGFJTLYB2NRwwG5cG4Z3rL5UFQl8iJwheCrXpHHuTtrk6Xy3UVvWD43eXw1WW4I11enA9//GF4dv4KNTgbSY4dOgzC/uD46vr1l@6wjnfjb6uTN/KeCp7WveOWuXYChlcn1ZQbx7jVg7KJ8cDsTaGPHcHanvbaNNk2jVnTZPtpsi0aNxwX57EFhUz@0o1G/taNRlLFhUrjIgJaWQWmZYEzUlAbZ1wbGyspFrDcUVEhotY4oVvs153sRZC5wTJzbpMcG5mt25pQnIYe740AQ1mOYScY7vRRPTgTvKqzqIUy@1AufrMP9fB/qId9qKJGfTuGv/eV6yuoKaLMFuo/JYzaqJRltBJ2BFurpvuL6@II1gOWCTqFrtPgIOzbP3UUfo21A0aLoByCwpHwMBxyLqe4YcrKtjrnrt@j2z/eaMqs4JIFdVRcDmv7MNpdFY8hoNzNaOC6jk4ex2cv@6LZMW2Ue9qBqMruTGSsWSlowgLvc4gJDMHgL6awxeL8e/S4ia5d2I2R06ADtc623jdbkSSOBcvaqklt0RT3NOqsnj/mGK2B2D0@L5sr7Pg8V14GKoNczVHqzeZKz3xqMdwqlTJJNpIJM5YUdMbQltWnNyqXnRsQHIW1gwlLaGWaE579JzITnjBI3FcY4Ra4IYZabrJF5yaDhaqAao@BORfCVRfvs@Zm1rA6C6eBnMZ40Zm1gjW5MFA65d7sDS8av5JIZYlTVqaigtxjzERSvQDyXuWdD56UY7ZUzJy3TKsa6vzGdRw2BxkrY1yBnOS2DuXnvMJli7GQKknwm5VklItKs81bgSBM2rwynBrMFudaYZGymN0zvVCSxdzErtre86ZIOCYFm6h0gWrc1BuDX52Swbs6LfA/1BXcpVcLmNJTQq1VnXcsXj@unIYuPHehLL/HeisJqWIGnQmKt@2WCYHanGknxt5RPwQOYXNqsTz5AuYMpynx3lPA1qWYJrLCxlEsqCaqFERllkkgDgpEWgKScUsMASCqKBj5i0/d3z@J2wrm@Uj4uxP7q/Mv "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##bVNtb9s2EP6uX3E1BlhKNSdOmq21pxVtZxQu0qZIsgWY44q0dbIIU6TBo@KoXX97dpSyBANqwy/33Ntzz512ra@sOblX9c46D9RS6nAKLnODweCeDvPn8ejgdSLixRexPEgOb45vxof37FuMJz@Pl5EqwS2Ols@yIQ0n4KQihMvWeHk3c866ePhRESmzgQENhklUZG7RZ1lXxEUCygChHzVGWRPzv9hJs8H4xcv09GWSpE/Iq1/T8fHp/6BfTtNXJ4x8O6jlLuaC6eCnODl4Pvrt99dfBsn35IeE5uZWalVAgVrVyqNjWg4ycCPaaeWZVKCn0cQueZa9@GGNa2d5JNPUK3Rgy6daxMVKLTeUHU1hbRvjs3FUWgdlmNQtTpaTCLh8mWXDDQvWhxxFgJpwAl0q/JPBt6EaTtwG70bz95/OL2bv3lzOUhjWDOLo459nV/Oz@aeAUIf8cX715uyMzbvO/Gt28fb8cvZ9US4jYsWPl91GWfkpfOVugZDupG9pRL5QpmcVhtYJSFOAXvB2meSNYZY604ujbt2wr5RGGHM81EE0HFGzYqlSoBR02g@U9oMkU@6SQc33weFcv16EmkcTWDmU267l1wnsnDI@TiKmNp4@WGiKTCf3VxWfDkEeXhBY87HyLvaV7bAgfWX3jHZhe@u2YBsPOVxbW6ARj8gKyYtabpFjsbc@2MpEc9CKwb7BCteyoQeL7e6bKwu1Rlgz5VooD4oESa@obKN5Ca1tQLouB/ZK63Dq3oJTtH2oGiKCByqZ23DsngXsZ8HwFKgu7IOqH/oaYawXwdlQI7W4Zc7CSNeCuLBVdNkVVTyt1NvQrXS2Tw19856Hr8DkligIFJDrnsq7qnFrXqAWzXqNRKKUSjcOH38taIHGVw0pSTytIW9ZpDLHW3StNZgryoPaXedHkYBsjStbtOw2/ingfXAifO7Hgu4tg@BhvB5A6zZCem@jz5j/9wpykmy72rX16pb1tgYKi8TNtCQP16g1eyt@/hjm3cnuCEKGr6RneaoW9sgHuu66F8CrK3hMrgqPjXItnbA7LWzp0YAIqSCMF2BQeUECQNi6RvG32oTPvw "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##bVRtT9tIEP6eXzFwJyWBvMH1y5ULFSpRlarlUODE6Uzq3djjeMV6N91ZE1xC/zqdtUN6Qk2UODvzzDMzz8zGlYvq2cEYzs@uzwYOZXrYhvYJqAxcNJrvjdvEJycVIVxVxsuHiXPW9aD9WREps4R92mcEmrSVMo2LjuZ1dHra/t6GzQbS8fdhNOr/eda/ncv@0@@d7sHh4K/Td1/mw18TT8291CqFFLUqlEe3pQ9VugGttPKdtNuUONBolj6HvTG8@TXbjbNcpCmLBTqw2U9W2tJmTDs6gSXxs39KvdUjDahc7HVWPRcdz7tPzBv9MR@gTPI4yaWDR9gkG0gk50paAOscDbBou5@KmTPYjGGGS3xYvX07/XDx92zy/uxqssM8vMZM/r2eXJxPzneI4jXi8z@frqefphcTgN@AZIEgCS7R6TYBTwkyLZfQmfFA2YBfS8UyovGh6RdU0QZFIPVaVgTWdHfJlu3/K9BzrMHylQis1VNrBi/1DAyu62n3slBnHfk4Yjqlkaki6sGMN4E48tuY9W0cerxET5yWh/dtL9hXpaeaPOCOGo@O@kfz8Xj/1uyfcIiORoNB/3jezAtg5RS3lUV6a4ljVi6On2kYH3YGB@@6ohN9EfOD7vD2@PZo@Px8nfOiEsThBZl14HPLw1vntrYFhXK7ZmsNW1t3B7b0EMONtSkasbMskLwo5B0yFpvTR5ub1hS0YmOTYIGJLGl74nP9zcxCJbwwfMUKoTzPQZD0irKqNc2gsiVIV8fAWmkdLpa34BTdbVkDInggl7EFQu9ZzqYXBOtSVcM@qmKb1whjvQjOkkqpxT3XLIx0FYiZzVtXNSkvw1rqu5Atc7YJDXnjpg6@WCa2REGgYLlpSnmfly7hcWpRJgkSiUwqXTrcPS1owZuXl6QkcbeGvGWRshjv0VXWYKwoDmrXmXciAdkCFzat2G38T8CH4ES4bNqC@i2D4KG9xoDWLYX03rYuMX55BTlJVjV3YT3fB6@sgdQicTItycMNas3enP8b2Myzk/UShAifS8/y5BWsERwmdfYUeHQpt8mssEsUa@mEXWlhM8@3SYRQEMYLMKi8IAEgbFGg@E8tw@cH "Ruby – Try It Online") - Ruby This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, where necessary or convenient). (See also the [single-pass version](https://codegolf.stackexchange.com/a/251004/17216).) Input is taken as the string with blanks followed by the full list of string arguments, each delimited by ```. ``` s/ # Begin substitution - match the following: _+ # Match an entire blank (.*?)` # $1 = everything subsequent, up until but not including the first # "`" delimiter; consume the delimiter ([^`]*) # $2 = a string argument, captured up to but not including the next # "`" delimiter; the ".*?" version would be "(.*?)(?=`|$)" / # Replace with the following: $2$1 # "_+" is replaced with $2, and $1 is preserved, but the original # $2 is deleted. / # No flags - match and replace just once ``` # [sed](https://www.gnu.org/software/sed/) `-E`, 31 bytes ``` :a s/_+([^`]*)`([^`]*)/\2\1/ ta ``` [Try it online!](https://tio.run/##RVJNb9swDD3Pv4IICmQfKILuuLSnYRvSU7EOCLA2NRWbjoTI4iDKMTzkv2eUnWQ2LJnkI5/4qK0Re4pkariNNcznEO/v5@X5mZ@@mEIW5af3L2@4@fgBz/vi9fPr3aJI5nRBFr11nmD1/fkBztXAH48vcBtgduNnsFnWXLxT@y/cCGyOR6osL@Xhbpl/LrCjkKZ@IzXirKg50OmXdWEnMLJAwxGSZSHoNWl0cQOWe/WOsJ7jHrhLUMKauaaAV8@WJGFr9qRYmqxHtqFYgXfqnAi2VJlOzpba46qV0VUElXbWokvgBMUkJ81QrBoYuAMTxxzonfcKh8QQnezPVTMiR8CakkEoJdVq6oWAY@1G2KNrz7wBAyfMwU464/GgZ8Zg4gD4k23xPBZ12q3x@8zWRJ5SM285nSNZCCWLZIGyZz0d5avtYqWz8thVFYlgY5zvIl13Bo8Uku3EGdFugyRWkZqSDhQHnUjppMxqj8xXkUC4pS3Xg4ZD@g/4kYMET1NbML4mC57bmxzEcYcmJS6e6HKfyiynmGGs3XJyB9WbA9RMomTeSII1ea9RSzG7dXZmvAQ5I1mTVB47QE96H6uRvQYdXa1talW4EpXeROQ/HrlJFABzKmBICIFcQkEA5LYl/O12@fsH "Bash – Try It Online") sed lacks lazy quantifiers, so `([^,]*),` must be used instead of `(.*?),` costing +2 bytes. [Answer] # Regex (.NET), 46 bytes ``` s/_+(?<=((?=.*?(\2?`([^`]*)))_+.*?)*)|`.*/$3/g ``` [Try it on regex101!](https://regex101.com/r/lathHY/6) - .NET Input is taken as the string with blanks followed by the full list of string arguments, each delimited by ```. This is a single regex substitution, to be applied once. (See also the [looped version](https://codegolf.stackexchange.com/a/251003/17216).) As such, for each individual match it must count how many blanks are to the left of the current one being replaced, because separate matches in a `/g`lobal match or replace operation cannot communicate to each other (there is no persistent state between matches, other than the current position in the string). Variable-length lookbehind is used for this, with group-building to count string arguments in parallel with counting blanks. (I tried using balancing groups for the counting instead, and that took a bit more bytes.) ``` s/ # Begin substitution - match the following: _+ # Match an entire blank (?<= # Lookbehind – evaluated right-to-left, so read # from the bottom up, until entering the lookahead, # then read normally again. # When the below loop has finished, $3 will contain the string argument # of an index corresponding to the index of the blank matched above. ( (?= # Lookahead .*? # Skip a minimal number of characters in order to # match the following: ( # \2 = the following: \2? # Previous value of \2, if set ` # Match a delimiter ([^`]*) # $3 = the next string argument (read up to but # not including the next delimiter, if any) ) ) _+ # Match an entire blank .*? # Skip a minimal number of characters in order to # match the above (since no backtracking will # occur, they will all be non-underscores). )* # Iterate the above as many times as possible – # for each blank matched (going right to left), # \2 is appended with another string argument # (going left to right). ) | # or... `.* # Match the entire list of string arguments, # including first delimiter, to be deleted. This # can only be matched after the first stage, # above, has finished. / # Replace with the following: $3 # The captured string argument / # Flags: g # Global – replace all matches in one sweep from # left to right. ``` # Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 54 bytes ``` s/_+(?<=((?=.*?(?=(\3?))(\2`([^`]*)))_+.*?)*)|`.*/\4/g ``` [Try it online!](https://tio.run/##bVNtb9s2EP6uX3E1Blh0NCfOS9c61YyuMwoXaVMk2QLMcUXaoiwiFGnwqDjqy29Pj5KTYEAlWDKfe3vuudOm8aU1Rw@q2ljnARtMnFzL@1Nwqev1eg@4n@3FkzdpHE/S4WBCz/jmaMJYfHPI4/kXvhgwxrI9MrEB@86Hg/2b4/31A4XOR@PfR4tIFeDmB4sXaR/7Y3BCoYTLxnhxP3XOurj/USEqs4Ye9vosylM376Ksy@OcgTKA0g9ro6yJ6V/shFnL@PhVcvKKseQZef1HMjo8@R/08iR5fUTIt0ElNjElTHq/xWywN3zz5@RLj/1gvyQ0M3dCqxxyqVWlvHREy0EKbogbrTyRCvS0NLFjL9LjX@a4dpZaMnW1lA5s8ZwLKVmhxRrTg1NY2dr4dBQV1kEROnXzo8U4AkpfpGl/TYJ1LgcRSI1yDG0ofE/hW1/1x@2ohrP3n84vpu/eXk4T6FeP6Md/zq5mZ7NPAcRH8O/zq7dnZ4TcPyL/Ti/@Or@c/pgXiwhJ@8NFO3qawSl8pbqBmm6H0OAQfa5Mxy@0rxkIk4Oe05yJ7o0hvjrV84N28MHr6xg2Thkfs4iyjU53J0lRpGdLAOslCZkAJqCTrt2ka5PR2rCHq5KWAyELFwQ2tLCk9ra0LRbELe2W0NZta90t2NpDBtfW5tLwJ2Qp0fNK3Eryld3pgy1NNAOtCOwKLOVK1Lg70bl9UmauVhJWToqKKw8KOQqvsGiiWQGNrUG4Nga2SuuwzN6CU3i7yxo8ggVKkdmwzl7LXS8y7Llq3T6oalfXcGM9D8Yaa6H5HXHmRrgG@IUto8s2qaJuhb4N1Qpnu9BQN@t4@BJMZhGDQAG57qi8K2u3KokLr1cricgLoXTt5NPbgubS@LJGJZC6NegtiVRk8k66xhqZKcyC2m3lJ5EAbSWXNm/IbPyzw/tglPC5awvaWwTBQ3sdIK1bc@G9jT7L7PEKcqJo2tyV9eqO9LYGciuRimmBHq6l1mQt6QsjmGYn2iUIEb4UnuQpG9hK2rNVWz0HGl1ObVJWeCqUaeG43WhuCy8N8BAK3HgORirPkQNwW1WS/6fW4fcT "Python 3 – Try It Online") - Python `import regex` A port of the .NET version. The captures `\2` and `\3` are copied back and forth to avoid use of nested backreferences, which Python doesn't support. # Regex (PCRE2 v10.35+), 96 bytes `s/_+(?*(.*`(.*)(.*$)))((?<=(?=^(?>.*?_+(?=[^`]*(\5?+`[^`]*)))+(?=\1)[^`]*\5\3$|(?4)).))|`.*/$2/g` [Try it on regex101!](https://regex101.com/r/lathHY/8) [Attempt This Online!](https://ato.pxeger.com/run?1=fVXdbts2FAa2Oz_FqSFUouOfOG2BbY5iFG02ONi6wGmXYbFD0hIlsaFEg6TiOE32DMNud1Ng2EOtT7NDKUuRYp0MSuQ5h-c738cf__Hnuli___Dl7_tT7EBgIIa1ETk1Yq14IqJwNOxNKS24cjTR5VoqYRbRgkwW85EN-xBiy9BIc-EDKicqZyNKv519f0gp6cOYTDoygygwZ7vLR3FoQwKuMHoDldjA4VUi1k7qKgp_kNbKKoeu7YY4J0ixFJw0Xk6gmZ8ehL-GcHPT1ldylxRY3dnu4Ovng8WSD26DiPR2hvsH0_PlKOwHKflvoO6suuRKppAKJUvphOl6OM9cXK2VTgVi9RGatMCJriuH5ZNH8dPPZDw1Gguv6nIlDOjsY2bbpLYtkz1kEmRt_4nve0ikOWxp-m-K1hytGVdWTDqZNoIjTesMtWslsYyMALcQJORdI0oCjx8DutfaRt1clvbq-cs3Px_V3T6GxHHcJPqM4G8qIxKdV_JapJApjtKHwyAZhl7_VvMkjsM8JEEeO1OLCQjM5useYuHJ5LaTbQzSjE5evzycz_vd4xfzwz24RNIPHbgvrOOoYugj6E-H85PZj69C8mlcd1F5wWQlqRUu6q4TI4Yrnlw4gy_aiNrtQ3cw7voKH4Qhl9pYJPb_YW9b167HQXmj4DrenQQqznD_Wl_H7BWZkHdIPwrUGSqrRIU9Mhgv47ipD4NtvUIPmvu7_cG4EQsTEZEU2ofgIl7HY1QLxw9PU2BwY1lsCls-HYy_Gff9Yk5uPzliEZn8Vbts8NXfzI7oTjTtRcMew0awBYSQKJrux9E0Po-mB_6EYkh8ds6WvWjxbLrDmi6GefNiTJrh4tniSXATTZ8SMiTkhg17o2BvlLc47-8-H7747XWBx9AC9Q-gRrh7NC77Bsk0JtzgBe4m14ZttLkAXTugcKrx8FTs3rIS1rGSXwiMFe3oSBdVZwZKorEFWImE1_ZuhOPmjZmZTATgivGSSQfSMsudtNm2M8tgq2vgppkDG6mUvzacBiPtxV1WH-E9UHCqAZffKXHHRYA2qWzCjmR5h1uxSjvmnbWtuWKXWDOruNkCm-uic9IklciWqwuPlhndTvW4tK3DFVBRba0XyFtO21JeFLVJCqyF1UkirGUZl6o24v6rQTG8NYvaSm6RLZ4VjSJlVFwKs9WVoNJSr3aDfC8SWF2KlU636K7cx4DvvFPAcUsLmh_3gnt6rUFokzPunO4cC_rv4-W0fNvkLrWTl9xfE5BqYRFMcevgVCiF3gJvOTTj2vFmE_gZruAO5Sm2sBGAZ7FBTwGXLkWamBXugajihum1YjrDfwtgfiqwyjG8oKRjlgEwXZaC_SJz39qd-Q8 "PHP - Attempt This Online") This version emulates variable-length lookbehind using recursion with fixed-length lookbehind. But since capture groups cannot be returned from a subroutine call, the regex must make a guess as to what the subroutine call will return; this is done using `(?*`...`)` non-atomic lookahead. If the recursive call detects a mismatch between the guess and the actual result, it returns a non-match, forcing the non-atomic lookahead to try other guesses until one matches. [Answer] # [Raku](http://raku.org/), 24 bytes ``` ->$_,\s{S:g[_+]=s.shift} ``` [Try it online!](https://tio.run/##PY7NCsIwEIRfZVlELEaPHgS961XBQy0h1sSE/qx0U0pRnz2mpbqHZb9hmNmnbspNqHqYG9iF1X4mxZVfp@0jlctsx2u2zvhPYNWDWbxnMgFDDSzwAKUrNMhh4KZz1fJEkcft6gcKSNHlGvJGqyoSOg@Oh4OVd2x6zBIR0842unlKGwq8pZjXWRo1IAOWuqiOto6aAqj1IOFCdNc1ihT/4k2zR4GViu95q398JFvHtvAF "Perl 6 – Try It Online") Replace and shift, like many answers. [Answer] # brev, ~~36~~ 28 bytes Original attempt: ``` (fn(fold(fn(strse y"_+"x 1))x rest)) ``` Wait, this works for 28: ``` (fn(strse x"_+"(pop! rest))) ``` Brev usually does poorly on here but since it was inspired by Snobol, I was happy to beat it. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 21 bytes ``` [@y'_+'[y shift]repl] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P9qhUj1eWz26UqE4IzOtJLYotSAn9r@DVRoXl7qxQny8gomCLZBSV9BQ11ZXUDdX11RIU8gvLfkPAA "Stacked – Try It Online") Replaces all runs of `_` with `y shift`. Nothing original, as it seems. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 7 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` lΔ╔*№≤ŗ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=bCV1MDM5NCV1MjU1NColdTIxMTYldTIyNjQldTAxNTdGJTBBJTJDJXUyMTkyJTJDJXUyMTkyRg__,inputs=JTVCJTIyb3BsJTIyJTJDJTIyb2Z0ZW4lMjAlMjIlMkMlMjJ0aGF0JTIwJTIyJTJDJTIybnQlMjIlMkMlMjIlMjBuZWl0JTIyJTJDJTIycyUyMiUyQyUyMiUyMCUyMCUyMiUyQyUyMm9tbWUlMjIlMkMlMjJaaWclMjIlMkMlMjJaaWclMjIlNUQlMEElMjJQZV9fX19fX19fX2UlMjBfX3NheSUyMF9fX19tb3RpdmF0aW9uJTIwZG9lc19fJTIwbGFzdCUyMFdlbGxfX19oZXIlMjBkb2VfJTIwYmF0aGluZ19fX190aGF0cyUyMHdoeSUyMHdlJTIwcmVjX19fX25kJTIwaXQlMjBkYWlseSUyMF8lMjBfX19fX19fX19fbGFyJTIy) Explanation: ``` l get the strings length Δ range ╔* multiply an underscore with each of the numbers № reverse vertically (so the longest underscores get replaced first) ≤ put the array on top - order parameters for ŗ correctly ŗ replace in the original string each any occurence of the underscores with its corresponding item in the array ``` [Answer] # [Nim](http://nim-lang.org/), 73 bytes ``` import pegs,sugar proc f(s,b:auto):auto=s.replace peg"'_'*",(i,x,y)=>b[i] ``` [Try it online!](https://tio.run/##VVLLjtswDLzvVxC@7KYw@gEFtpceiu5p0RYI0EVgKDZtCZHFQKSS@utTUnk0MWBRIinOcKgU5tMpzHvKAnucuOUyufy0z9TD@MLt9osrQqu6vvLnjPvoerTU5rl7/tS0L6H92y6r16/bj7A5Ye9J7zW/fUgTQ2cfjJRBPDHCUaPVRSN4Oqq3ph0p74CKQAdrogFT0340N@cWWZq2md0O9QJez2/kU7NZPV0hf0AMmnGG3GLvCl9Oeq6rYlnhoPz7jG7WIkEgsFp2EnhcHuqNsFABl2sVOIYYtQAIQQ68u@BYhkXAu46AUSTipV8EykOoaW9hvjCpnSUy/pZRuLio@4N2pia5vIDan@TvmfyqUEF1cnFnHMZM54LGpjuzEw@pI2aT1jzrM8FvvuTeK0MDLn2PbO2OLsSS8WFHYEwwiS8cHFd1Egs9ijx2eMC8UMIucGfzq4xuIgPTjFsaFg0n@Z/w3YII7zcRrM/r72xyZ0nSnRspTxYVoXsO79hdPxsNu6UizyThoGOkBAMhK5XoWGCNMWrUYza3vgxXH53dEO9ERfULHBEy9pXbAPomBlVFq8INqIsuG2vam0g0CiaohJ2YTTY9SBjMmsBgXppn6@pPmC7rZnX6Bw "Nim – Try It Online") [Answer] # [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 5 bytes ``` œṢ”_ż ``` [Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz1qmBt/dM////@VPBVyMrNTFeJBQCEpNTmxtBjKA/LBZGZeutL/aKXM5FSF5KLUxFwlHaXMEoXMYiBdnFiSWZxWqRQLAA "Jelly – Try It Online") (or rather, don't, as this is a fork, not on TIO) Full program, as we abuse Jelly's smash-printing. ## How it works ``` œṢ”_ż - Main link. Takes a string S and a list of fillers F œṢ - Split S on runs of: ”_ - Underscores ż - Zip with the fillers, and smash-print ``` [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` s#(w:r)|(p,n)<-span(/='_')s=p++w++(snd$span(=='_')n)#r;s#[]=s ``` [Try it online!](https://tio.run/##JY5BC4IwGIbv/Qpxglszu5fbJYIO3jqKyMhpo/U59ikS9N@X2vPCc3hO71PhS1sbAhI6nzz7UpcBKw7oFNCjSJuUoXCcz5xThDbZutg6MOLPSKpaYHgrA4ISViSy12NpQBd76bVqS5BSuGm8j76EcBla3SxEy5omj67o9MMoaz/RhAb6ta7kuyruB9vFWWxwUTfB4tv/a1z/AA "Haskell – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 51 bytes ``` I =INPUT R I SPAN('_') =INPUT :S(R) OUTPUT =I END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hCsIyAwOcPTTUI9X14QKcloFawRpcnH6h4YAeUBBLlc/l///PRVyMrNTFeJBQCEpNTmxtBjKA/LBZGZeOldmcqpCclFqYi5XZolCZjFXcWJJZnFaJQA "SNOBOL4 (CSNOBOL4) – Try It Online") ]
[Question] [ *Inspired by [this](https://stackoverflow.com/questions/38162862/invert-list-of-lists-of-indices/38162896) StackOverflow post.* # Introduction Bob's job is to create spreadsheets and organize them. The way he organizes them is known to very few except for Bob, but he creates a list of each of the spreadsheets that fall under the same group. There's a bunch of data in the spreadsheet he creates, but there's only one piece of data that we're looking at right now: The number of days between the day he started this job and the day he made the spreadsheet. The first day he created two spreadsheets, noted them both as `0` and sorted them in to their proper locations. Now, his boss is asking for a review of what kinds of spreadsheet happened each day, and it's your job to write some code that will figure that out for Bob; he has far too many spreadsheets to do it by hand. ## Input Bob's info that he gives you comes in the form of a (0-or-1 indexed) jagged array where each datum is of the form `x = a[i][j]`. `a` is what I'm calling the jagged array itself, `i` is the type of spreadsheet, and `x` is the date the array was created. `j` is unimportant. ## The task Given a jagged array of spreadsheet creation days organized by their type, return a jagged array of spreadsheet types organized by spreadsheet creation day. ## Examples Bob isn't going to just leave you with this abstract data. He's given me a subset of some of his spreadsheets to help you out with figuring out what everything is supposed to be. Example input (0-indexed): ``` a = [ [3,2,5,0], # Bob doesn't necessarily sort his lists [1,3], [2,1,0,4], [4,5,3], [6,6] ] ``` Example output (with commentary, which of course is not required): ``` output = [ [0,2] # On day 0, Bob made one type 0 and one type 2 spreadsheet [1,2] # On day 1, Bob made one type 1 and one type 2 spreadsheet [0,2] # On day 2, Bob made one type 0 and one type 2 spreadsheet [0,1,3] # On day 3, Bob made one type 0, one type 1, and one type 3 spreadsheet [2,3] # On day 4, Bob made one type 2 and one type 3 spreadsheet [0,3] # On day 5, Bob made one type 0 and one type 3 spreadsheet [4,4] # On day 6, Bob made two type 4 spreadsheets ] ``` Note that Bob doesn't always make two spreadsheets every day, and so the output may be jagged as well. But he always makes at least one spreadsheet every day, so the output will never need to contain empty arrays - although if your output has empty arrays at the end, you don't need to remove them. More test cases: ``` [[3,5,6,2],[0,0,0],[1,0,3,4]] -> [[1,1,1,2],[2],[0],[0,2],[2],[0],[0]] [[-1]] -> Undefined behavior, as all input numbers will be non-negative integers. [[0],[0],[],[0]] -> [[0,1,3]] ``` The output's inner lists do not need to be sorted. As always, no standard loopholes, and of course shortest code wins. *(As this is my first question, please let me know of anything I can do to improve it.)* [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` FṀ⁸ċþµJ€x" ``` Input and output are 1-based. [Try it online!](http://jelly.tryitonline.net/#code=RuG5gOKBuMSLw77CtUrigqx4Ig&input=&args=W1s0LCAzLCA2LCAxXSwgWzIsIDRdLCBbMywgMiwgMSwgNV0sIFs1LCA2LCA0XSwgWzcsIDddXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=RuG5gOKBuMSLw77CtUrigqx4IgrigJjDh-KCrOKAmeG5hOKCrOG5m-KAnA&input=&args=W1szLDIsNSwwXSxbMSwzXSxbMiwxLDAsNF0sWzQsNSwzXSxbNiw2XV0sIFtbMyw1LDYsMl0sWzAsMCwwXSxbMSwwLDMsNF1dLCBbWzBdLFswXSxbXSxbMF1d) (0-based for easy comparison). [Answer] # Pyth, 13 bytes ``` eMM.ghkSs,RVU ,RV vectorized right map of pair, over: UQ [0, …, len(input) - 1] and Q input (this replaces each date with a [date, type] pair) s concatenate S sort .ghk group by first element (date) eMM last element (type) of each sublist ``` [Try it online](https://pyth.herokuapp.com/?code=eMM.ghkSs%2CRVU&test_suite=1&test_suite_input=%5B%5B3%2C2%2C5%2C0%5D%2C%5B1%2C3%5D%2C%5B2%2C1%2C0%2C4%5D%2C%5B4%2C5%2C3%5D%2C%5B6%2C6%5D%5D%0A%5B%5B3%2C5%2C6%2C2%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C3%2C4%5D%5D%0A%5B%5B0%5D%2C%5B0%5D%2C%5B%5D%2C%5B0%5D%5D) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` ms.e*]k/bdQS{s ``` [Test suite.](http://pyth.herokuapp.com/?code=ms.e%2a%5Dk%2FbdQS%7Bs&test_suite=1&test_suite_input=%5B%5B3%2C2%2C5%2C0%5D%2C%5B1%2C3%5D%2C%5B2%2C1%2C0%2C4%5D%2C%5B4%2C5%2C3%5D%2C%5B6%2C6%5D%5D%0A%5B%5B3%2C5%2C6%2C2%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C3%2C4%5D%5D%0A%5B%5B0%5D%2C%5B0%5D%2C%5B%5D%2C%5B0%5D%5D&debug=0) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` :1f. cdo:Im:?:2f. t:.m:Im~h? ``` ### Explanation * Main predicate, Input (`?`) = a list of lists ``` :1f. Find all valid outputs of predicate 1 with ? as input ``` * Predicate 1: ``` c Concatenate the list of lists into a single list do Remove duplicates and sort :Im Take the Ith element of that sorted list :?:2f. Find all valid outputs of predicate 2 with [Element:?] as input ``` * Predicate 2: ``` t:.m Take the (Output)th element of the list of lists :Im Take the Ith element of that list ~h? This element is the element of the input [Element:List of lists] ``` [Answer] # Lua, 114 bytes ``` r={}for i,t in ipairs(...)do for _,v in ipairs(t)do if r[v] then r[v][#r[v]+1]=i else r[v]={i}end end end return r ``` [Ideone it!](http://ideone.com/2xVqAA) Inspired by [Dennis' answer in Python 2](https://codegolf.stackexchange.com/a/85909/48934). [Answer] ## JavaScript (ES6), 58 bytes ``` a=>a.map((b,i)=>b.map(j=>(r[j]=r[j]||[]).push(i)),r=[])&&r ``` [Answer] ## CJam (30 29 bytes) ``` Mq~{W):W;{:X)Me]_X=W+X\t}/}/` ``` [Online demo](http://cjam.aditsu.net/#code=Mq~%7BW)%3AW%3B%7B%3AX)Me%5D_X%3DW%2BX%5Ct%7D%2F%7D%2F%60&input=%5B%5B3%205%206%202%5D%5B0%200%200%5D%5B1%200%203%204%5D%5D) Curiously it's shorter to hack around with `W` than to use `ee`, mainly because I want the index to end up in a variable anyway. `e]` saved two bytes over first finding the maximum element `m` and initialising an array of `m+1` empty arrays. Thanks to [Martin](https://codegolf.stackexchange.com/users/8478) for a one-byte saving by storing a value in `X` instead of juggling it around the stack. NB If trailing empty arrays are permitted, there's alternative 29-byte approach by instead initialising the array of as many empty days as there are spreadsheets: ``` q~_e_,Ma*\{W):W;{_2$=W+t}/}/` ``` [Answer] ## CJam, 20 bytes *Thanks to Peter Taylor for letting me base this code on his solution and saving 3 bytes.* ``` {ee::f{S*\+S/}:~:.+} ``` An unnamed block which expects the input on top of the stack and replaces it with the output. [Test it here.](http://cjam.aditsu.net/#code=%5B%5B3%205%206%202%5D%5B0%200%200%5D%5B1%200%203%204%5D%5D%0A%0A%7Bee%3A%3Af%7BS*%5C%2BS%2F%7D%3A~%3A.%2B%7D%0A%0A~p) ### Explanation ``` ee e# Enumerate the input. E.g. if the input is e# [[3 5 6 2] [0 0 0] [1 0 3 4]] e# this gives: e# [[0 [3 5 6 2]] [1 [0 0 0]] [2 [1 0 3 4]]] ::f{ e# The exact details of how this works are a bit tricky, but in effect e# this calls the subsequent block once for every spreadsheet and e# its correspond index, so the first time we'll have 0 and 3 on the e# stack, the next time 0 5, and at the last iteration 2 and 4. e# Note that this is a map operation, so we'll end up with an array e# on the stack. S* e# So the stack holds [... index date] now. We start by creating e# a string of 'date' spaces, so " " on the first iteration. \+ e# We swap this with the index and append the index. S/ e# Now we split this thing on spaces, which gives us 'date' empty e# lists and a list containing the index, e.g. [[] [] [] [0]]. } :~ e# This flattens the first level of the result, so that we get a list e# of all those lists we just created. This is simply one list for e# every spreadsheet with its type in the last element. :.+ e# Finally we fold pairwise concatenation over this list. All the e# empty lists won't affect the result so we'll just end up with all e# the types in lists for the correct date. ``` [Answer] # Python 2, 82 bytes ``` r=[];i=0 for t in input(): for v in t:r+=[()]*-(~v+len(r));r[v]+=i, i+=1 print r ``` Test it on [Ideone](http://ideone.com/hNG6H0). [Answer] ## Mathematica, 35 bytes ``` Table[#&@@@#~Position~i,{i,Max@#}]& ``` An unnamed function which accepts and returns a ragged list. Uses 1-based indices. Thankfully `Max` automatically flattens all its inputs, so this gets us the last day index even though the input is a ragged list. We then simply compute a list of `#&@@@#~Position~i` for all day indices `i`. This expression itself finds the position of `i` inside the ragged list (return as an array of indices at successive depths), so the values we want are the first values of each of those lists. `#&@@@` is a standard golfing trick to retrieve the first element from every sublist, by applying `#&` to each of those sublists, which is an unnamed function that returns its first argument. Alternatively, we can define a unary operator for the same byte-count (assuming an ISO 8859-1 encoded source file): ``` ±n_:=#&@@@n~Position~#&~Array~Max@n ``` [Answer] # Java, 314 bytes ``` int[][]f(int[][]n){int w=0;Map<Integer,List<Integer>>m=new TreeMap<>();for(int i=0;i<n.length;i++)for(Integer x:n[i]){if(m.get(x)==null)m.put(x,new ArrayList<>());m.get(x).add(i);w=x>w?x:w;}int[][]z=new int[w+1][];for(int i=0,j;i<w+1;i++){z[i]=new int[m.get(i).size()];j=0;for(int x:m.get(i))z[i][j++]=x;}return z; ``` **Detailed** ``` public static Integer[][] f(Integer[][]n) { int w=0; Map<Integer,List<Integer>>m=new TreeMap<>(); for(int i=0;i<n.length;i++) { for(Integer x : n[i]) { if(m.get(x)==null) m.put(x,new ArrayList<Integer>()); m.get(x).add(i); w=x>w?x:w; } } Integer[][]z=new Integer[w+1][]; for(int i=0,j; i<w+1; i++) { z[i]=new Integer[m.get(i).size()]; j=0;for(Integer x : m.get(i))z[i][j++]=x; } return z; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` œẹⱮFṀ$Ḣ€€ ``` [Try it online!](https://tio.run/##y0rNyan8///o5Ie7dj7auM7t4c4GlYc7Fj1qWgNE/x81zDjcDmI3zDw66eHOGUBm5P//0dHGOkY6pjoGsTrRhjrGQNJIx1DHQMcEyDIBioNEzHTMYmN1FEBKTXXMdIyAQgZAJRAtBjrGQMVgaZAACIOpWAA "Jelly – Try It Online") Input and output is 1-indexed, the Footer converts from 0-indexing to 1-indexing and back for I/O purposes. ## How it works ``` œẹⱮFṀ$Ḣ€€ - Main link. Takes a 2D array, **a**, on the left $ - To **a**: F - Flatten Ṁ - Maximum Ɱ - Over each number **i** in [1, 2, ..., max(flat(**a**))]: œẹ - Get the multidimensional indices of **i** in **a** This returns [x, y] for each occurrence of **i** in **a** where **x** is the index of the array in **a** in which **i** is in and **y** is the index of **i** in that array. For example [[1,2,3],[4,5,6],[7,8,9]] œẹ 7 = [[3,1]] as 7 is in the 3rd subarray at index 1 (using 1 indexing) Ḣ€€ - Extract the **x** values only and return them ``` [Answer] # Perl 5, 48 bytes A subroutine: ``` {for$i(0..@_){map{push@{$b[$_]},$i}@{$_[$i]}}@b} ``` See it in action like this: ``` perl -e'print "@$_$/" for sub{for$i(0..@_){map{push@{$b[$_]},$i}@{$_[$i]}}@b}->([3,2,5,0],[1,3],[2,1,0,4],[4,5,3],[6,6])' ``` ]
[Question] [ Your task is to take an input `n` and output element `n` of the Rummy Sequence, a sequence which I made (looking on OEIS will not help you). # Definition Each element of the Rummy Sequence is a set of truthy or falsey values. Ex.: `[true, false]`. The steps to producing a member of the Rummy Sequence are quite simple: 1. Start out with the first index, `[]` (this is element 0). 2. Set the leftmost falsey to truthy. If there are no falseys to change, then increase the length of the list by 1 and set all members of the new list to falsey. 3. Repeat step 2 until reaching element `n`. # Example Let's define our function as `rummy(int n)` (stuff in `{}` is a step taken to get to the answer): ``` >>> rummy(5) {[]} {[false]} {[true]} {[false, false]} {[true, false]} [true, true] ``` # Rules * Standard loopholes apply. * Must work for inputs 0 through your language's upper numerical bound. * You may output in any way you see fit, provided that it is clear that the output is a set of truthy/falseys. # Trivia I call this the "Rummy Sequence" because, starting at index 2, it defines the sets you would need to lay down in each round of [Progressive Rummy](http://www.rummy-games.com/rules/progressive-rummy.html), where falsey is a book and truthy is a run. # Test Cases ``` >>> rummy(0) [] >>> rummy(1) [false] >>> rummy(6) [false, false, false] >>> rummy(20) [true, true, true, true, true] >>> rummy(1000) [true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false] ``` [Answer] # JavaScript ES6, ~~94~~ ~~92~~ ~~72~~ ~~70~~ ~~66~~ 64 bytes *Saved 6 bytes thanks to Neil!* ``` n=>[...Array(a=Math.sqrt(8*n+1)-1>>1)].map((_,l)=>l<n-a*(a+1)/2) ``` I don't think this can be golfed more. At least with the equations. ## Explanation They are two main equations (`n` is input): ``` (Math.sqrt(8*n+1)-1)/2 ``` This will give the total size the output array will need to be. In my program I used `>>1` instead of `(...)/2` these are the same as the first bit in binary has a value of 2. Shifting it will result in in `floor(.../2)` --- ``` n-a*(a+1)/2 ``` This is the amount of `true`s there will be. `a` is the result of the previous expression. --- This is what the syntax does: ``` [...Array(n)] ``` This code generates an array with range `[0, n)` in this answer `n` is the first equation. --- `.map((_,l)=>l<n)` this will loop through the above range, `l` is the variable containing the current item in the range. If the item is less than the amount of trues they are (determined by second equation), then it will return `true`, else `false`. [Answer] ## Python, 51 bytes ``` f=lambda n,i=0:n>i and f(n+~i,i+1)or[1]*n+[0]*(i-n) ``` Outputs a list of 1's and 0's. [Answer] # Pyth, 8 bytes ``` _@{y/RQy ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=_%40%7By%2FRQy&input=7&test_suite=0&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=_%40%7By%2FRQy&input=7&test_suite=0&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0) This is exponentially slow. ### Explanation: ``` _@{y/RQyQQ implicit Qs at the end, (Q = input) yQ 2*Q /RQ divide each number in [0, 1, ..., 2*Q-1] by Q this results in a list of Q zeros and Q ones y take all subsets { remove duplicates @ Q take the Qth element _ print it reversed ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷṗ2SÞ⁸ị1,0x ``` The code does not work in the latest version of Jelly before the challenge was posted, but it did work in [this version](https://github.com/DennisMitchell/jelly/tree/f37cfb4fd4b16dae5dd0eda54749af40f2446353), which predates the challenge. Indices are 1-based. [Try it online!](http://jelly.tryitonline.net/#code=4bi24bmXMlPDnuKBuOG7izEsMHg&input=&args=MTAwMQ) (takes a few seconds) or [verify multiple inputs at once](http://jelly.tryitonline.net/#code=4bi24bmXMlPDnuKBuOG7izEsMHgKUsOH4oKsRw&input=&args=MjE). ### How it works ``` Ḷṗ2SÞ⁸ị1,0x Main link. Argument: n (integer) Ḷ Unlength; yield [0, ..., n - 1]. ṗ2 Take the second Cartesian power, i.e., generate the array of all pairs of elements of [0, ..., n - 1]. SÞ Sort the pairs by their sum. The sort is stable, so ties are broken by lexicographical order. ⁸ị Retrieve the pair at index n. 1,0x Map [a, b] to a copies of 1 and b copies of 0. ``` [Answer] ## 05AB1E, 27 bytes ``` 8*>t<;ïÐ>*;¹s-ïD1s׊-0s×JSï ``` Will see if I can golf it some more and add an explanation in the morning. [Try it online](http://05ab1e.tryitonline.net/#code=OCo-dDw7w6_DkD4qO8K5cy3Dr0Qxc8OXxaAtMHPDl0pTw68&input=MTAwMA) [Answer] # Java, ~~117~~ 110 bytes ``` enum B{T,F};B[]r(int n){int i=0,c=0,j=0;while(n>=i)i+=++c;B[]a=new B[c-1];for(;j<n-i+c;)a[j++]=B.T;return a;} ``` created my own boolean type, which allowed me to save 7bytes [Answer] # Python 2, ~~69~~ 63 bytes ``` a=b=0 exec'a,b=[a-1,b+1,0][a<1:][:2];'*input() print[1]*b+[0]*a ``` Test it on [Ideone](http://ideone.com/hXp8Jt). [Answer] ## Python 2, 61 bytes ``` j=(2*input()+.25)**.5-.5 print[i/j<j%1for i in range(int(j))] ``` Solves for *n = j·(j+1)/2*. Input is taken from stdin. **Sample Usage** ``` $ echo 20 | python rummy-seq.py [True, True, True, True, True] $ echo 50 | python rummy-seq.py [True, True, True, True, True, False, False, False, False] ``` [Demo](http://ideone.com/8nMLWo). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` {⍵⌷↑,/(↓0 1↓⍳≥\⍳)¨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHPdsftU3U0dd41DbZQMEQSD7q3fyoc2kMkNI8tALE6d1a@z/tUduER719j/qmevo/6mo@tN4YqAvICw5yBpIhHp7B/zWAag0NNHVAEr1TH3XMSANrNzQAAA "APL (Dyalog Extended) – Try It Online") ]
[Question] [ ## Background Given an [elementary cellular automaton](https://en.wikipedia.org/wiki/Elementary_cellular_automaton) rule number like, for example, 28 = `00011100`… [![description of rule 28](https://i.stack.imgur.com/Kp6M2.png)](https://i.stack.imgur.com/Kp6M2.png) * We can swap \$\color{red}{\text{the 2nd bit with the 5th bit}}\$ and \$\color{orange}{\text{the 4th bit with the 7th bit}}\$ to get a rule that acts the same way but mirrored horizontally. This gets us `01000110` = 70. * We can reverse *and flip* all the bits to get a rule that does the same thing but with black and white reversed: `11000111` = 199. * And we can combine these two processes — it doesn't matter which order we apply them in — to get a mirrored, reversed rule: `10011101` = 157. Or, [as MathWorld puts it](https://mathworld.wolfram.com/Rule28.html): > > The mirror image, complement, and mirror complement are rules 70, 199, and 157, respectively. > > > The automata identified by rules {28, 70, 199, 157} all behave the same way, up to arbitrary distinctions of colors and axis orientation. But because 28 is the *lowest* of these four numbers, it is the "canonical" rule number. ## Task Write a program or function that takes an input \$0 \leq n \leq 255\$ and decides whether it is a canonical rule number. These 88 inputs should be give a "true" result: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19 22 23 24 25 26 27 28 29 30 32 33 34 35 36 37 38 40 41 42 43 44 45 46 50 51 54 56 57 58 60 62 72 73 74 76 77 78 90 94 104 105 106 108 110 122 126 128 130 132 134 136 138 140 142 146 150 152 154 156 160 162 164 168 170 172 178 184 200 204 232 ``` and all other inputs should give a "false" result. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The [I/O defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I imagine there may be a shorter hashing based Link that any approach like this, but finding it might take a while ;p ``` +⁹BḊ⁽¦hœ?,ƊU¬;ƊḄṂ⁼ ``` A monadic Link that accepts an integer from \$[0,255]\$ and yields \$1\$ if connonical, else \$0\$. **[Try it online!](https://tio.run/##AS8A0P9qZWxsef//K@KBuULhuIrigb3CpmjFkz8sxopVwqw7xorhuIThuYLigbz///8yOA "Jelly – Try It Online")** ### How? ``` +⁹BḊ⁽¦hœ?,ƊU¬;ƊḄṂ⁼ - Link: integer, Rule +⁹ - {Rule} add 256 B - convert to binary Ḋ - dequeue (remove the leading 256-bit) Ɗ - last three links as a monad f(Rule-Byte=that): ⁽¦h - 2355 œ? - {2355}th permutation of {Rule-Byte} (swap bit 2 with bit 5 and bit 4 with bit 7) , - pair with {Rule-Byte} Ɗ - last three links as a monad f(Mirrors=that): U - reverse each ¬ - logical Not ; - concatenate {Mirrors} Ḅ - convert from binary Ṃ - minimum ⁼ - equals {Rule}? ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 19 bytes ``` ¥+Ƃi:↔¬?:Jĭ,Ťđ,?ƃa≤ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LdM9apZRFEXhwm6PQtKawN3n_tukdwpiEUVBJFpEJ6AgWAbsbFIkYBGnYBE0g7DMSFwn2n6c7-9Z-_32_e3LN-9OT96fXD89ODo9OHx4cPTy4NnF1Yf3r47Wz5urR7cfXz---_z15vr48ZNfPw5_X_46Pzy-_XRy9-Xy8uz5i7P_pxd_HpwXWaGqpq6hqaUt86LlkKvc5C4PecpL3oqi4D2hqIqm6IqhmIql2KpF1ap8ZFVtql11qE7VpbrViprVQo1vbGpdbahNtaW21Yu61UO9qvODuvpQn-pLfWsUDWuERtVoGvzeoTE1lsbWLJrWDM2q2TS7Jn9nai7NrVW0rBVaVatpda2hxb9dWlu7aFs7tKt20-7aQ3tqg5EacBQ8CiAFkQJJwaSAUlApsBTu7tm4S7iUS7q0S7zUSz78DKAjfbnD0CAaRcNoHA2kkTSUxtI1Q3AHp_E0oEbUkBpTg2pUDatbFuMOWUNrbA2u0TW8xtcAG2H3TMsdyEbZMBtnA22kDbWxNtgeuQHu8DbgRtyQG3ODbtQNu3H3zLFwB72xN_hG3_AbfxPAFDAJvHJV3FHBZDAdTAhTwqQwLUwMU8M755f7Y4D0CHoEPYIeQY-gR9Aj6BH0COdQuaNH0CPoEfQIegQ9gh6Re85B3y-au9x0jjpXnbPOXeew6RH0CHpEzelzR4-gR9Aj6BH0CHoEPYIeQY9o-YxwR4-gR9Aj6BH0CHoEPYIeQY_o-TD1f4_mXw) ``` ¥+Ƃi:↔¬?:Jĭ,Ťđ,?ƃa≤ ¥+ Add 256 to ensure that binary length is 9 Ƃ Binary digits; least significant bit comes first i Remove the last digit (the 1 from the 256) Now the list contains exactly 8 digits : ? Optional apply: ↔¬ Reverse and logical NOT : ? Optional apply: Jĭ,Ťđ, Swap the 2nd and 5th digits, and the 4th and 7th digits ƃ Convert from binary to decimal a≤ Check that all possible values are greater than or equal to the input ``` [Answer] # [Python](https://www.python.org), 95 bytes ``` lambda x:x==min(z for y in(x,256+~int(f'{x:08b}'[::-1],2))for z in(y,y&165|(y&80)>>3|(y&10)*8)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZBdSgNBEITxNaco8pDsaALT85-FzUVUJCFZXTCbECLsxp-L-BIQvZOexhqiwzTdPRT9Vc_7164_PGzb00dd3Xw-Hepp-r57XGyWqwW6squqTdMWR9TbPXqw7CbGh6u3pj0U9fi5K3Vavo6vy3IqtxOjVNYds66f9CMJ_qXoR0mr-dzmSrS6TEqdMT8Xi6xuqMZ-0d6vC05W5QA8TY26aFSJ3T6TmgnW7aoaYqgG55f_PNQQGFg4eAREJMwgfBSIgViIg3hIgsxgDIyFcTAeJsBEmAQzg9WwnGFhHayHDbARNsFpOIEzcJzv4DxcgNfwAk8e6wifEDSCQeS1iA6RNiIijWjMSNc5aEEHBn1kd3QidCDkC-lis1fqiBaChWQhV8gTAsWz9nkT9sQJeRLYB2oje8KFREncTWsGszXDv58-nc75Fw) [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda i:61!=i<=255^int(f'{i:08b}'[::-1],2)!=194>i*8&80>=i&80 ``` [Try it online!](https://tio.run/##bZHdTsJAEIXveYrhRsCsyc7@tTSWF0FMSmhhE2wN9MYYn72eU/XOJp1053yz@Xb7/jFeht5PXf0yXZu346mRXCVd1vm5djG@5n5cd6vPXNny@LXaV9WTHozbLGvdhl1@LB9Ku6sz6nQehpPUsrdG1Igz4o0EI9FIMlIYKY1sETFGrgAUhAJRMIpYkTv0HfoOfYe@w7DDtEPukHvMe24OxoPxYDwYD8aDCcgD9g9gAg3ABDABTEQWkUVqcY2ZiJmEfgJf8MVMgbygNPKC2si39LRzoa1NLHSeD0RrparSUympfj4hJ@inlFPaKdWUPkohjVzG@RrYo4zSRhN7iWMFe7RT6mjJu7GWhV/eHRaLbrhJltzLrenP7drFtKkWgid30q3z74JPc7@3t/EH5j@bg/Z6b/9B@mH8w6Zv "Python 3 – Try It Online") [Answer] # JavaScript (ES11), 54 bytes Expects a BigInt. Returns `1` for canonical or `0` for non-cannonical. ``` n=>0x10005012777AFFA0F0A0F0FAFFFAFFn>>n%2n*64n+n/2n&1n ``` [Try it online!](https://tio.run/##NZBNjhMxEIX3OYWFNJPu6Udwlf86hARlQZZsWCIWIemMgoJ71OlBSIgbILFhCfeY88wFOEJ4HgnZr11lV9f37E/bL9vzbjjejc9zv@8uh@UlL1f2q1hrgxVNKa03m7Xd2KIN46K8WuUrzTfR5ya/0Hwt@bLr83k0a7M07y0ECgePgIiEFnMINwWiEAfxkABpIXOoQh3UQwM0QhO0hc7hLBx7ODgPF@AiXIJr4S28wCs8@3v4AB8RLIIgkMc4IbSIFlGROB2SR6KNhEQjFnPSbREt2EjRR3FHJ0IHQr6QLq54ZR3RQrCQLOQKeUKgBMah3IQ5cUKeROaRtYk54UKitLybtRRXpx8Wk8mhH6pTN5rMx7J5wfWV0RBL1DS1@TYxphwP3ZkFhyrXC@6U9@1P3ezU31Z5NvbvxuGYb6t6drfdv8n7ytWmMc84mqcf/8fVU5elWc@OeXe633fn6u3954/dwLa1eW2mfx9@Pv7@xe/UvDTTxz8/pjV53y//AA "JavaScript (Node.js) – Try It Online") We take advantage of the following properties to reduce the size of the lookup bit-mask: $$f(2k+128)=f(2k+1),\:0\le k<64$$ $$f(2k+1)=0,\:k>52$$ --- # JavaScript (ES6), 75 bytes Returns `0` for canonical or `1` for non-cannonical. ``` n=>(g=n=>n&165|n/8&10|n*8&80)(n)<n|(h=i=>q=i--&&~n>>i&1|2*h(i))(8)<n|g(q)<n ``` [Try it online!](https://tio.run/##NZFNktMwEIX3OYVg4ciTl6DWf8g41Cw4AUuKRSpxMqZS8kxi2BA4AVVsWMI9OM9cgCOE56mipFZ3S@3@nuSPm8@b8/bUPQzz0u/a6765lmatDw3XUkkMl/IqV2Iu5SZX2dS61Lflou@brlk/Nt18XlXfynrdVXKxN/e6q2udx4qDfqS7bvtyHtSdatR7A4GFg0dARELGEsJNgViIg3hIgGTIEtbCOlgPG2AjbILNsEs4A8ceDs7DBbgIl@AyvIEXeAvP/h4@wEcEgyAI5DFOCBnRIFokTofkkSgjIVGIwZJ0MxolmEijjlEdlQgVCPlCurhRK@uIFoKFZCFXyBMCJTAO402YEyfkSWQeWZuYEy4kSubdjKHRO/thNZns@5M@toMqfCyzortVNkQGs1mtvkyUGg9P7ZnHe/6FFXfG1@2P7eLYH3RZDP274dSVg64XD5vd27LTrlYz9ZJj9vzh/1g/d2nUi7tFV7bHT7v2zIbqjZr@/fPj6ddPrlP1Wk2ffn@f1gR9vf4D "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 36 bytes ``` =[:<./(,&(,:2354&A.)1-|.)@{.~&_8&.#: ``` [Try it online!](https://tio.run/##ZZFNSwMxEIbv/RUvFXZbbGPmIx@7WFCEnjwVbx5ExFJFELQeROlfX9@13oQMmclM5nkneR6mod1i1aPFAhE9bRlwtbleD6vb/jyczRbNbNGrJW8uw1yW32F@8RUOzV1twkk/zCf7t4/97nMVeFOgMDgSMgoqOggPBaIQgzgkQSqkgyrUoA5N0Awt0ArtYBHGHgZzWIJlWIFVeIQLXOHs7/AEz0gRSZDIo1@QKnJEVhQuQ3EUyigoFBLRkR5Ho4SYadQxqqMSoQIhX0gXG7WyjmghWEgWcoU8IVAS/TROwpg4IU8y48zawphwIVEqZ4uRxt108viwe0V78/tW7THaTk9xfLzJX3p9//L@P8sPOeApaMrDDw "J – Try It Online") Constructs all possible representations according to the spec, and checks if the input is the min of those. [Answer] # [sclin](https://github.com/molarmanful/sclin), 65 bytes ``` "256+2X>b1dp."Q"2b>X"map"&"fold~ = ["""_` ! ""perm2354:""++"Q ] Q ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) For testing purposes: ``` 28 ; "256+2X>b1dp."Q"2b>X"map"&"fold~ = ["""_` ! ""perm2354:""++"Q ] Q ``` ## Explanation Prettified code: ``` \; Q 2.b>X map \& fold~ = 256+ 2X>b 1dp. ["" "_` ! " "perm2354:" \++ Q ] Q ``` Assuming input *n*: * `256+ 2X>b 1dp` convert *n* + 256 to binary and drop 0th bit + i.e. convert *n* to binary digits, padded to length 8 * `[ "" "_` ! " "perm 2354:" \++ Q ] Q` vectorized-evaluate the binary digits over the following... + `""` just return the digits + `"_` ! "` reverse array + vectorized-NOT + `"perm 2354:"` 2354th permutation + `\++ Q` get concatenation of previous 2 strings * `2.b>X map` convert back to decimal * `\& fold~` minimum * `=` check if equal to *n* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` ⊞υΦ↨⁺²⁵⁶N²κ⊞υE04261537§⌊υIι¬⌕υ⌊⁺υEυ⁻¹⮌ι ``` [Try it online!](https://tio.run/##NY7PCoMwDIfve4riKYUO5t8ddtoGggdF9gadFizWKm0je/uudO6QQ/LL9yXDxM2wcuV9j3YCZKSWygkDD24F9AotZGXFSKM3dB0u7xBRykgWaqb0dvpjLd8guRRZlZb5NWHk7ho9ig@0UssFF8AAPLl1ICmNnJHaQbc6qKUeo@HYjEcP428c@pSRl9iFCU9FQZR4nxf@vKsv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υΦ↨⁺²⁵⁶N²κ ``` Convert the input to base `2` padded to `8` digits and push the result to the predefined empty list. ``` ⊞υE04261537§⌊υIι ``` Apply the permutation to the result given by reflecting the binary for each index and push that. ``` ¬⌕υ⌊⁺υEυ⁻¹⮌ι ``` Logically invert and reverse each of the two results and check that the minimum of the four values is the original input. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 42 bytes ``` {x~&//2/''(~|:')\1@[;|8\15637664]\(8#2)\x} ``` [Try it online!](https://ngn.codeberg.page/k#eJwVj8tOw0AMRffzFbet1CQIkbn2vBIWdJtvIAjYlD0LVImSb+dGGmtsy/I5vs6/t+08jjZ2Xb/d525YeXl9vreVuXgtJb2tfTvZsN7+QhhDBGFwJGQUVDRMoJoEDXQwgRls4AQzmMMSLMMKrMIabIJHuHY4PMEzvMArvCFFJCIZkvYnpIxUkCMykcVTXpEbSkQxVD1HTajSqKgSiZhEj3tIIRaFPHY7mVAGFJ+i03dXzQlNgSkyxaV4FJBZed4vUS0cxWNRXTRbVQtOEdl0W4wK/W5hDWGZ+b5czlu/vDx2x3Fdj0PXH07LHOePz++vH3AI/dPDMmzna3ewXMI/IDZKwQ==) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 118 bytes ``` .+ * 8+`^(_*)\1(_?) $1$.2 (.)(.)(.)(.)(.)(.)(.)(.) $&¶$&¶$1$5$3$7$2$6$4$8 ¶(.+) ¶$^$1$& T`d`10`¶(.+)¶ O`¶(.+) ^(.+)¶\1 ``` [Try it online!](https://tio.run/##bZM7bhtBEETzOsdaICWAmOr5Rw4dOnEoSDRgB04UGD6bDqCL0a8lhwZ2wN2ZxnTXq@Lvn39@vXz37dPpy/V2edC91sP16fR8f3706fnzWYePS@h0Of/30XH39vq@fPSjHvOIYxztWHp7PV0ezvwcT5zd6dv1x9Xl@rH99qqv/1719LHx6NutyApVNXUNTS1tmU3LIVe5yV1e8laEoiqaoiuGYiqWYqsWVe6oqk21qw7VqbrUiprVQo37m1pXG@pF3er0432qL42iEZo8VbNpMsbUZJCiTfeSixHKYDFHTsckZgLT33R3zVmpo7VpbDqbvqafaejOe08lfNPO9PPge1A7@aa56eiFtlJY/OadlCOSDavybLWphrAtbuxVvatvDWtUcd@A4dCY4t6xxc3Tml1zaxUta4VWFV1W1xpa8F5aW9vaoV21u/bQntroTycYruBFYZiCG2Wy2E9/0qB0KC1Kj3JaxnWahVuOBJU@UoNpxjXjmXHMqDGGGbuMWUaa8cotHacWr4xWt4TJGZYZvUawcc3YZpQb6Ua7Ue6RcDlDudFt7DR@GgCeSZIzSBgUhoWBYWh4Zb44h4ZXmkAN3hsohorB4gwCbAwcQ8c7A0kiYROwCdgEIQlCEiUtI5hwCqd31MAqYBWwClgFrCKthVW8J5s6WEVGPDOeIc@UZ8wz5xl0uAVhC9gF7KJmSKghdAHDIHgBxyB8AcsggNHy/0IdPIMwBkwDpgHTIJgB1yBKAdvo@cfqfwE "Retina – Try It Online") Link includes test suite. Explanation: ``` .+ * ``` Convert to unary. ``` 8+`^(_*)\1(_?) $1$.2 ``` Convert to `8` bits of binary. ``` (.)(.)(.)(.)(.)(.)(.)(.) $&¶$&¶$1$5$3$7$2$6$4$8 ``` Duplicate the input, then append the shuffled input. ``` ¶(.+) ¶$^$1$& ``` Duplicate both new rows but with the bits reversed. ``` T`d`10`¶(.+)¶ ``` Complement the bits in the reversed rows. ``` O`¶(.+) ``` Sort all the rows except the very original. ``` ^(.+)¶\1 ``` Check that the first of the sorted rows is the same as the original. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Should have been 20 bytes, but there is [a bug in the \$n^{th}\$ permutation builtin `.I` for bit-lists](https://github.com/Adriandmen/05AB1E/issues/204).. ``` ₁+2в¦Dā<Ž9x.Iè‚Dí_«JCßQ ``` [Try it online](https://tio.run/##AS8A0P9vc2FiaWX//@KCgSsy0LLCpkTEgTzFvTl4LknDqOKAmkTDrV/Cq0pDw59R//8yOA) or [verify all truthy test cases](https://tio.run/##ATUAyv9vc2FiaWX/4oKFw53KkkT/4oKBKzLQssKmRMSBPMW9OXguScOo4oCaRMOtX8KrSkPDn1H//w). **Explanation:** ``` ₁+ # Add 256 to the (implicit) input-integer 2в # Convert it to a binary-list (this cannot be a binary-string, # because builtin `.I` only works with lists) ¦ # Remove the first 1 to 'subtract' the 256 again D # Duplicate this bit-list ā< # Workaround part 1 of 2: Push a list in the range [0,length) # without popping the list itself Ž9x # Push compressed integer 2354 .I # Get the 2354th permutation of the [0,length) list è # Workaround part 2 of 2: Index those into the duplicated bit-list ‚ # Pair the two bit-lists together D # Duplicate this pair í # Reverse each inner list _ # And negate each with an ==0 check « # Merge the two pairs together JC # Convert the inner bit-lists to integers ß # Pop and push the minimum Q # Check whether it's equal to the (implicit) input-integer # (after which the result is output implicitly) ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 135 bytes ``` x=>/^(.|2[^01]|[37][^0159]|[369]0|4[0-6]|5[^2359]|35|62|94|1([^67]|0[458]|10|22|[3-7][02]|[2367]8|[3568]4|[02-5]6)|20[04])$|32/.test(x) ``` [Try it online!](https://tio.run/##FY/NaiMxEITvforC7GHm4En/qCXNwYF9jkEGs9jg7JINYxMS0Ls7NaBG1a3u/kpv58/z/c96@3gcPuvzenx@HV9fTsPUbTmJtr54aZuKedN5btLTIofceiwn863s0bP1OXUdllMurcuSorau0s04dOAGMY6b87WyErm21Fk8RMtjN1kktfFXd3uZHpf7Y/ganx/r7f0x7PYChcGREMgoqJihLCrUoA5N0IBW6AwzmMMSLGAZVmAVNsMFzh0OT/CAZ3iBVyRBUiRD4v6EFEgZIQhFkEddEBVZkA2Fx1ESCm0UFBoRzKTLFrQgmUEfmzs6UTpQ8pV09c0r@4hWgpVkJVfJUwI1qGP7CXPilDzNzDN7C3PClUSt/JsIg7fbfnc87pZpmn6v6/l7sMjj9PfyfR/GNl1v/x6XdbiO09v/2/uwx37cjc8f "JavaScript (V8) – Try It Online") Can't wait for Deadcode to outgolf this :-) ]
[Question] [ For this challenge, a slice of a string is defined as an upper and lower index that can "cut" a piece of a string. All characters from the string in the range `[start, end)` (or `[start, end]` if you don't speak practlang) are part of that slice. If the upper index exceeds the string's length, the overflow is ignored. For example, the (zero-indexed) slice from 1 to 4 in "abcdef" is "bcd", and the slice from 3 to 7 in "Hello!" is "lo!". A slice cannot have a length of zero (i.e. both endpoints are equal), but the string cut by it may. A slice can distinguish between strings if that slice is unique across all provided strings. For instance, the slice (1, 4) can distinguish between the strings "happy", "angry", and "hungry", but so can (2, 4) or (1, 2). Your task is: Given a list of strings, output the shortest slice that can be used to distinguish between them. Your input strings will only ever consist of printable ASCII characters. There will be at least one valid distinguishable slice for a given input. Your list will not contain any duplicate words. Your program may either use zero-based indexing or one-based indexing, but please specify which is being used in your submission. Output two numbers, marking the start and end of the slice. If there are multiple distinguishable slices that tie for shortest, you may output for any or all of them. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in bytes for each language wins. ## Test cases ``` "happy", "angry", "hungry" -> (1, 2) or (2, 3) or (3, 4) "sheer", "shrew", "shine", "shire", "spike", "shy" -> (2, 4) or (3, 5) "snap", "crackle", "pop", "smack", "sizzle", "whiff", "sheen" -> (0, 2) or (1, 3) "Sponge", "Paper", "Moon", "Air", "Bowl", "Water", "Alien", "Dragon", "Devil", "Lightning", "Nuke", "Dynamite", "Gun", "Rock", "Sun", "Fire", "Axe", "Snake", "Monkey", "Woman", "Man", "Tree", "Cockroach", "Wolf" -> (0, 3) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 bytes ``` z0ZQƑ$ƤÐƤZœi1UÄ ``` [Try it online!](https://tio.run/##NVA7TsQwEO05xcqiQdoCjhCIoCEICGjFrrawIsc2ccaWkxCSigKJlk8D/V6COtrcAy4SNjOhem/eZzT2vTCmGYb2cHnVv@33m@613yy3H/rotnseupffp6/t@8/358HdMKyY4s41bD5jHKRHoipk6/lsxQolhB/FQnlRE9EgJuKJOJ1Nyn8LuBuFxPMkM@g5i0qR7xQkum3JqZVOU6oLAbQgdhYkupfc0QGRtTBioHE8trUZccFL8gOjBQZCzyVG91goHjSmzrVUJWiQ43BR0blhAzzXJfKzCrvXlq6LK1pwOj0xeESIgVM1spAJ/KyFzTlWI4IbLzBxstvkLU8UhUzK1n8 "Jelly – Try It Online") Output is 1-indexed, but the footer converts to 0-indexed for convenience. ``` z0 Transpose with filler 0. Ƥ For each prefix of ÐƤ each suffix of the columns, Z transpose back to rows QƑ$ and check if all rows are unique. Z Transpose the results yet again, ƤÐƤZ grouping results by substring length. œi1 Find the first multidimensional index of 1, U reverse it, Ä and cumsum ([start index, length] -> [start index, end index]). ``` `z0ẆµZQƑ)ƙ@Ẉœi1UÄ` is a fun 16-byter. Initially felt like `Ẇ` would have to be the way forward, but I only even thought of that one in the course of writing this explanation! [Answer] # JavaScript (ES6), 83 bytes ``` f=(a,n)=>[...a+0].some((_,i)=>a.every(o=w=>o[w.slice(...r=[i,i+n])]^=1))?r:f(a,-~n) ``` [Try it online!](https://tio.run/##bZFNT8MwDIbv@xVRT4nWdV@ckDo0mODCEGJIO1QFWcVtw9q4StuVceCvlzYZA02c/MZ5/dhO3mEPZaRlUY0UvWHbxj4HVwl/EXieB8NJ6JWUI@evruyS4OEe9YGT3/gLChqvzGSEvLNqP5CuHKpQhC/@VIgrfRl3pNGXEm1EqqQMvYwSHvPASaEoDo7LHFCJNiKtjQqFYOMx41OXzQQjzfjMZXOr5i67EINzVJki6p5QphobK6TCo9BWFHJ3zPy2mP2PU1D0zkhDtMtMUUEmU@Zdxgj5@WlvmlTGseUiqhN5chp@2g9/3mPAmLMpSCWG8QiFnX9NpPq4lOZ4TU3Wxy1U9n6ZSTSGlYbEWHvQCvfS@O5lklZKqqQ/PNR239VBQS4ro@9qU/1EdotN/YO4Pb7S8sOEjQJbvCa1Q/M5W8rBFK9teNZoHDcdSxNEqTVlsTP48wZz0X4D "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input array n // n = counter, initially undefined ) => // [...a + 0] // build a large enough array to try all // possible starting indices in each word .some((_, i) => // for each starting index i: a.every(o = // o will be used to store the word slices w => // for each word w in a[]: o[ // w.slice( // isolate the slice of w defined by ...r = // the range r[] [i, i + n] // consisting of [i, i + n] ) // ] ^= 1 // toggle the flag in o for this slice // every() will fail if it was already set ) // end of every() ) // end of some() ? // if successful: r // return r[] : // else: f(a, -~n) // try again with n + 1 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~21 22~~ 21 bytes ``` vf0ÞṪÞKƛKƛ∩Þu;;∩1ÞḟṘ¦ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwidmYww57huarDnkvGm0vGm+KIqcOedTs74oipMcOe4bif4bmYwqYiLCIiLCJbXCJoYXBweVwiLCBcImFuZ3J5XCIsIFwiaHVuZ3J5XCJdXG5bXCJzaGVlclwiLCBcInNocmV3XCIsIFwic2hpbmVcIiwgXCJzaGlyZVwiLCBcInNwaWtlXCIsIFwic2h5XCJdXG5bXCJzbmFwXCIsIFwiY3JhY2tsZVwiLCBcInBvcFwiLCBcInNtYWNrXCIsIFwic2l6emxlXCIsIFwid2hpZmZcIiwgXCJzaGVlblwiXVxuW1wiU3BvbmdlXCIsIFwiUGFwZXJcIiwgXCJNb29uXCIsIFwiQWlyXCIsIFwiQm93bFwiLCBcIldhdGVyXCIsIFwiQWxpZW5cIiwgXCJEcmFnb25cIiwgXCJEZXZpbFwiLCBcIkxpZ2h0bmluZ1wiLCBcIk51a2VcIiwgXCJEeW5hbWl0ZVwiLCBcIkd1blwiLCBcIlJvY2tcIiwgXCJTdW5cIiwgXCJGaXJlXCIsIFwiQXhlXCIsIFwiU25ha2VcIiwgXCJNb25rZXlcIiwgXCJXb21hblwiLCBcIk1hblwiLCBcIlRyZWVcIiwgXCJDb2Nrcm9hY2hcIiwgXCJXb2xmXCJdIl0=) Port of @UnrelatedString's Jelly answer. *-1 thanks to @UnrelatedString* #### Explanation ``` vf0ÞṪÞKƛKƛ∩Þu;;∩1ÞḟṘ¦ # Implicit input vf # Flatten each into a list of characters 0ÞṪ # Transpose with filler 0 ÞKƛ ; # Map over suffixes: Kƛ ; # Map over prefixes: ∩ # Transpose Þu # All unique? ∩ # Transpose 1Þḟ # First multidimensional indices of 1 Ṙ # Reverse ¦ # Cumulative sums # Implicit output ``` Old (didn't work): ``` # Implicit input @Gʀ2↔µ÷$-; # Step 1: Generate all possible slices in order @ # Push the length of each string in the input list Gʀ # Get the zero range of the maximum of this list 2↔ # Combinations of the above list with length 2 µ ; # Sort this list of pairs by the following: ÷ # Dump both numbers onto the stack $- # Swap and subtract the two numbers λ£?ƛ¥i;Þu;c # Step 2: Get the shortest distunguishable slice λ ;c # Get the first item for which the following is true: £ # Save the pair in the register ?ƛ ; # For each string in the input list: ¥i # Index the pair into the string # (Vyxal supports slice indexing) Þu # And check if all the results are unique # Implicit output of the first pair which returns true ``` [Answer] # [Python](https://www.python.org), 131 bytes ``` lambda x:(r:=range(max(map(len,x))))and min([(i,j)for i in r for j in r if len({s[i:j]for s in x})==len(x)],key=lambda a:a[1]-a[0]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVHBSsQwEMWrXxH2lMIu6E0KPawuenFFXMFD7WHcTZvZbZOQtm674skP8AO8LIj-k36NSaYgaCDMm3lvJi_J26fpG6nV_j1P7j_aJp-cfL2UUD2sgHUxt3FiQRWCV9C5bXgp1LiL3AK1YhUqnnIcr6NcW4YMFbPMwzVBzJnT86c6xXideaL2RPccJYknuigbb0SfDOdBDOlxNoH0KIvIyvfBq7GoGp7zdCTBmH40ZiNnyAYg24CyKDr8ldVSCOvZWlqxJYBKDMASMLgZKv_aFRjPLC0sN2UQGR0qdeUqAeBuR8xWYp7THCHUn0kLo93LefYaDFmaa618nGJIT_W29PEOGuKnJYogmFkoSDoTjxhEl1jIRqEqfHLVkv9Zr6DCJuCLNjTcaHK5oPR8uPK0C2GhgDrnWrmnD6frCoJ0TuHWiqA4c4OshqUkUZn7-9G_7PcUfwA) Most likely can be golfed down further. [Answer] # [R](https://www.r-project.org), ~~113~~ ~~108~~ 106 bytes *Edit: -2 bytes thanks to pajonk* ``` \(x,n=1:max(nchar(x)),`/`=sapply,m=n/\(j)n/\(i)(j-i+1)*all(table(substr(x,i,j))<2))which(m==min(m[m>0]),T) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZG_TsMwEMbF2qdAmWxIVcqEEEEqVLBQhGilDhRRN3LiS_0nsh2a9lVYysCIeB54GpJzFwQsvs_n332-s19e7fbDCWM9d_7JSUh58lb5rHvyWcxIHeukf6pYTXQqmCU1pfG8N08cK0u5jlWiezNS0HYFSoouHPbpAZOSeLaQnLhq4XxTFUNcUHp2TOlKQCqIShIFmqgHdX70SOMJDTd-7b3_7ISkJBLNVeso3o-Yzi0KUaGitPObdoJz20JOWL4KAjTfCRtECctd5j8XzcoWSC1LlxLZ0mDGqSaDAjabcNKMlGXBjnP9t-G4NDpH-o6VocGRMbqNA8DthVnJNk6ZD-cDCRyBoWU5op1oyJ8BqRvIhdeg83ZzW4VxhmvNFHjU1xXW3pvQ7bgKBle7JxjUGMaahdKR0UuOjzs1imHpKISJ5UhcNk7WsFQESGbNoOHXttsQvwE) 1-based indexing; outputs all tied minimal slices if there is more than one. Assumes that `""` is a string-slice that is distinguishable from non-empty slices (so 1-based `(4,5)` would be a valid output for the second test case). [Add 11 bytes](https://ato.pxeger.com/run?1=dVGxTsMwEBVrvwJlsiGVaCeECFKhgoUiRCt1aCvkRk7sNrYj26Fp-RSWdmBEfA98Dc5dBxCw5D0_v3u-u7zs7PbdCWM9d_7RFTLlyWvls_bpx_OU1LFOLNM5JzoVzJKa0lgljpVlsSadMz3pzuIpWdBvSqdRJCWLtjzu0COiWE08mxecuGrufMiIZbyglJ53w4euhEwFUUmipCZqoi5OZjQeUWzh8-DtZ2skJZEIb62j-DAKfVkgogJGaeu32wnObWNywvIVEqn5nlgkpVzulf9SNCsbQ2pZuizAWxpQnAoKELnZ4E0YKcswjnP9d-CwNGGrjemeldjgwBjdYE_C8dKsigbHzON9r5AcDH3LcrC2oj5_kuC6lbnwWuq8OdxVOE5_rZmSHvhNBbUPBrsdVhhwvV9BrwYYaoalA6OXHJY7NopB6QBhZDk4rkKSNSwVaCqyMCj-te0W8Qs) to avoid this. [Answer] # [R](https://www.r-project.org), 103 bytes *Edit: 0-byte fix thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(x){b=d=max(nchar(x)):1;for(i in b)for(j in b)if(all(table(substr(x,i,j))<2)&j-i<d-T){T=i;d=j};c(T,d)} ``` Works only in R version 4.1, so [don't Attempt This Online!](https://ato.pxeger.com/run?1=dZGxTsMwEEDF2q-oMiBbSgeYEG2GQgULRYhW6oKELo4TX5rYkZPQtFW_hKUMzHwPfAGfQXLugijTPd-9u5yd1ze7_yiVsZUsq-cyQyGD97qKBxefyRNr-DYMoiCHhmmhwLYJfnk2jI1l2EfdD3mHqUOMGWQZqyDMJCvrsKxa30c_5Xx0zk_TAY6iwZxv5wEOoyDdDQWb-xHfuc99nXz_XoMJ5ikoirXn9z3QiSVQNRHnvb92qaS0nVQqK1cOUMsDWAcFLg-Z_6ZoKDpBWBDLjNzCUKbM2wwBbjauslIYx26clPr4wFlhdEL2AxRuwakxuotjpOOVWWVdXEDl6uMMJQkTCwmpPW8iX5CsO0xUpVEn3eG-dteZrDXkWBHf1tT7aNy2s9oNuDk8wbihMNPgWqdGLyU97sLkQK1TF-ZWknHdTrIGhHJSFh-_KISiaZrI8z0wHcmOQtNS-0SeoWrStrofvt-7-AM) You can [Try it online!](https://tio.run/##dZCxbsIwEEB3vgJlqGwpDO1YyECL2qVUVYnEWF0cJ76Q2JHjlADi22l8ZmrpdM9378722UunjHWyc19djUIml6LXwqHRbOCnLMmTBgamhQI7Jvjj/bwwluEU9TTjHquAWDCoa@YgqyXr@qxzox9jXHG@eOB31QwX@SzlpzTBeZ5U57lgaZzz86/rmWCRgrY9RPE0Al1aAtUTcT75a3dKSuulTlm5D4BaXsEGaHF3zfw3RUPrBWFB7GpyW0OZrhkzBHg8hspeYVGEcVLq2wM3rdEl2R/QhgeujdE@LpGOT2Zf@7gFF@rLGiUJKwslqZNoJb@RrDcsldOoS39478N3VgcNDTri1556P0147aYPA16uK1gOFDYaQuva6J2k5W5NA9S6DiG1kozncZI1IFSQ6uL2RyETwzDkURyB8SQ9ZWakcUWRoWo5tl5@AA "R – Try It Online") with `function` instead of `\`. [Attempt This one Online!](https://ato.pxeger.com/run?1=dVExTsNAEBRtXhG5QHeSU0CFCC4CETQEIRIpDRJan8--dew762wTJ1FeQhMKat4DL-AZ2HuhQIRqZndnxnvrl1e7ey-VsZUsq6cyQyGDt7qKB2cf-MgavgmDKMihYVoosG2DD2NjGfZR90_OQ94V6U-BMYMsYxWEmWRlHZZV6_DRTzm_OOXH6QAvosGMb2YBDqMg3Q4Fm_kR37oPfh59_V6ECeYpKIqV5_c90IklompinPf-qkslpe1EpbJy6QhquSfWkQIX-85_KRqKTiAsiEVG2sJQp8zbDhFcr91kqTCOXZyU-nDgtDA6IfU9FG7BiTG6wxFSeWmWWYdzqNx8lKEkwdhCQtKeN5bPSKpbTFSlUSddcVe754xXGnKsiN_U5H0wbttp7QKu9ycYNQRTDc46MXoh6bhzkwNZJw5mVpLiqk2yBoRyoiw-_FAIRdM0ked7YDomOxaalrUn8gxNk9bqfvhu5_Ab), which is 2 bytes longer. Uses test suite from [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/259721/55372), which is longer, but IMHO more elegant (no loops, just `sapply`). [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~25~~ 20 bytes *-5 bytes by using .C* ``` .M-FZf{I:R.*TQ.CUsQ2 ``` [Try it online!](https://tio.run/##K6gsyfj/X89X1y0qrdrTKkhPKyRQzzm0ONDo//9opeK8xAIlHQWl5KLE5OycVBCzIB8sUpwLFAEzMquqIDLlGZlpaWChjNTUPKVYAA "Pyth – Try It Online") Uses zero based indexing, outputs all shortest slices. ### Explanation ``` .CUsQ2 # list all possible slices (and many more) f # filter on lambda T :R.*TQ # the input strings mapped to their slices {I # is invariant under deduplication .M-FZ # take elements which maximize the first element of the slice minus the second element of the slice ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 49 bytes ``` WS⊞υι≔⌈EυLιθF⊕θFθ¿¬ⅉ«≔Eυ✂λκ⁺κι¹η¿∧⌊η⬤η⁼¹№ηλI⟦κ⁺κι ``` [Try it online!](https://tio.run/##dY8/awMxDMXn3KfQKIE7ZO50hA6BJhxkKqXDcVHOIj7dnf80LaWf3bUD7VYN7xlL@j17sL0f5t7lfLPiGHCvS4qn6EVHJIIuBYvJgNBj04Ygo@Kh/5ApTcWX2nlmHaNFISIDaxm7zB5wJfh1uQAe54gvhUfw1Wz@OPf9k5OB0Rm4GuhcClh8r4PniTXyuYINbKvYAt9UWqtnPIjeX2FLo3UOrYGnNfUu4NbAbk4a65WjWtCV70Tc9SHi6/8xb1QCvnMOltk3wXq@FRXlqr7oItd6/mzyw7v7AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS⊞υι ``` Input the strings. ``` ≔⌈EυLιθ ``` Get the length of the longest string. ``` F⊕θFθ ``` Loop over more than enough lengths and starting indices. Edit: Saved 1 byte by looping over zero length as well (this obviously gets ignored later due to the empty slice rule). ``` ¿¬ⅉ« ``` Stop once a slice has been found. ``` ≔Eυ✂λκ⁺κι¹η ``` Get the current set of slices. ``` ¿∧⌊η⬤η⁼¹№ηλ ``` If they are valid and unique, then... ``` I⟦κ⁺κι ``` ... output the start and end indices. [Answer] # [Julia 1.0](http://julialang.org/), ~~128~~ 118 bytes ``` ~a=(r=max(length.(a)...);(q=[y:x+y for x=0:r-1 for y=1:r-x])[findfirst(x->allunique(getindex.(rpad.(a,r),Ref(x))),q)]) ``` [Try it online!](https://tio.run/##VZAxT8MwEIVn@iuiTLZII7oWBVGoYKEItUgdogyn1olNHdt1EuJ06F8PyTlCMN139949nf3VSAEL1/dXSIhNSnBEMlXUPCZA4zim9@ScpN3S3XZBrm3gkrulnS@Qu2QxsMtomgt1zIWtauLmDyBlo8S5YaRg9SAwFxNr4DgkRpZGW5YTRymNzjSj/WPFdRtc05CDMV0YBSGowiLwBimb/XoqzpgdpYpb1noQik1gPRhxmib/dxWYcXywcDhJdBiNk6ocJgjicvFKy0We@xDG1N@YndGqQM8HGH/MRms11pXA9km3cqx7qL2@koKhYW2hQOvsJlyzb4G2N1HwWglVjM17429fdwpKUSO/Nri81f7IXTMlvEwPXjksOwV@d6PVieEH7nUJuLvx5dMydDwPUVbDgXuTzMOs/wE "Julia 1.0 – Try It Online") Output is a [unit range](https://docs.julialang.org/en/v1/base/collections/#Base.UnitRange). Note that Julia defaults to 1-based indexing and inclusive number ranges. -10 bytes thanks to Mukundan314: rewrite [array comprehension](https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions) to avoid calling `sort(_,by=length)` on the vector of ranges [Answer] # [Scala](https://scala-lang.org/), ~~188~~ 161 bytes saved 27 bytes thanks to comment. [Try it online!](https://tio.run/##dZLBbtswDIbveQrBJwnz0sTJKYALpAu2yzwM84oehqHQXNlmYkuapDRLij57JlFO0aatDyZFfv9vSpateMeP6s9aVI4UHOTD8U7UpKZ2UYq/v0pnQDa/WU4nxCli6YSNLRwEG9cddwXXFPJLCh@mZ93ed9ahk64Z8zB0Thiq80uLrdux7aASVI9vp6l/ZZ65A@tAVg4d8tyenEBe7YMyYB@DgB0JCTP2flrKTWMXZGkM3z8NuyDXEhzJycOI@Oeed8Riy0590W@LJi3Xep@kJOGyMZi0W8zYuSQ7SWwrhAmkbY3YxQSkGBITEw2bofKG1ezJSnIdqMrwatOhQCus2N5XMIHDIXZ2LdR19BRCvnadD65YJyQptZINKr9zHSculJIhLgGXV2rXhXjDXewvOxAIrAxvAnryWol7QPQrNK2T/nNh8W0bN7naS96Dw/zLFg1@qDh@uX3m8nk4neU/DKXkUV8ouRF4@Deq56gvYvhpBBKfvJ1RvGoj1NUJerIRBu337zpJ/WUdfi9j5OIi1i2h0zRjb4PZSzBL5@@As5fg5F3H@Tk4C@Dj6PH4Hw) ``` def f(s:Seq[String])=(0 to s(0).size).flatMap(i=>(i+1 to s(0).size).map(j=>(i,j))).filter(p=>s.map(_.slice(p._1,p._2)).distinct.size==s.size).minBy(p=>p._2-p._1) ``` Ungolfed version ``` object Main{ def shortestDistinguishableSlice(strings: Seq[String]): (Int, Int) = { val n = strings.head.length (0 until n).flatMap(i => (i + 1 to n).map(j => (i, j))) .filter { case (i, j) => strings.map(s => s.slice(i, j)).distinct.size == strings.size } .minBy { case (i, j) => j - i } } def main(args: Array[String]): Unit = { val strings1 = Seq("happy", "angry", "hungry") val strings2 = Seq("sheer", "shrew", "shine", "shire", "spike", "shy") val strings3 = Seq("snap", "crackle", "pop", "smack", "sizzle", "whiff", "sheen") val strings4 = Seq( "Sponge", "Paper", "Moon", "Air", "Bowl", "Water", "Alien", "Dragon", "Devil", "Lightning", "Nuke", "Dynamite", "Gun", "Rock", "Sun", "Fire", "Axe", "Snake", "Monkey", "Woman", "Man", "Tree", "Cockroach", "Wolf" ) println(shortestDistinguishableSlice(strings1)) // prints (1,2) println(shortestDistinguishableSlice(strings2)) // prints (2,4) println(shortestDistinguishableSlice(strings3)) // prints (0,2) println(shortestDistinguishableSlice(strings4)) // prints (0,3) } } ``` ]
[Question] [ Your task is to make a program or function that takes a nonnegative integer (or a different convenient format to represent it) that represents an angle measure in degrees from 0 to 180 (inclusive) as input and outputs every possible time (in hours and minutes; no seconds) on an analog clock where the measure of the smaller angle between the hour hand and minute hand is equal to the inputted angle measure. # Rules * Output can be a list of times, a string of the times with separators, or multiple outputs of times. * The times can be formatted in any way that can be identifiable as clock times by humans, such as `hh:mm` or a list of the hours and minutes. * The times should be from 12:00 to 11:59 (e.g. `0:00` and `22:00` are invalid outputs). * Standard loopholes apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins. # Test cases ``` Input | Output ---------|------------ 0 | 12:00 90 | 3:00, 9:00 180 | 6:00 45 | 4:30, 7:30 30 | 1:00, 11:00 60 | 2:00, 10:00 120 | 4:00, 8:00 15 | 5:30, 6:30 135 | 1:30, 10:30 1 | 4:22, 7:38 42 | 3:24, 8:36 79 | 3:02, 8:58 168 | 1:36, 10:24 179 | 1:38, 10:22 115 | 1:50, 10:10 ``` Interestingly, there are only two possible times in hours and minutes (except for 0 and 180 degrees) for every integer (or number with a fractional part of 0.5) degree input and on an analog clock the times represent horizontally flipped images of each other. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 60Ḷ12pד<¿‘Hạ/eʋƇذ_,Ɗ ``` A monadic Link that accepts a non-negative integer in \$[0,180]\$ and yields a list of pairs of `[hour, minute]` of a twelve-hour analogue clock. **[Try it online!](https://tio.run/##ATgAx/9qZWxsef//NjDhuLYxMnDDl@KAnDzCv@KAmEjhuqEvZcqLxofDmMKwXyzGiv/Dh8WS4bmY//80NA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/M4OGObYZGBYenP2qYY3No/6OGGR4Pdy3UTz3Vfaz98IxDG@J1jnX9P9x@dNLDnTN0HLKAqhR07RQeNczVjPz/P9pAx9JAx9DCQMfEVMfYQMcMyDECYlMdQ2Mg1jEx0jG31DE0s9AxBNGGprEA "Jelly – Try It Online"). ### How? If we label straight up (12:00) as \$0\$ degrees, then at a given exact minute of \$h\$ hours and \$m\$ minutes, the minute hand is at \$\frac{360 m}{60}\$, while the hour hand is at \$\frac{360 h}{12}+\frac{360m}{60 \times 12}\$ degrees. A clockwise angle between the hour hand and minute hand is, therefore: $$A=\frac{360 h}{12}+\frac{360m}{60 \times 12}-\frac{360 m}{60}$$ $$A=30h+\frac{m}{2}-6m$$ $$A=30h-\frac{11m}{2}$$ The code makes all of the times as `[h, m]` pairs and filters them for when the absolute value of the above angle \$A\$ is either equal to the input or \$360\$ minus the input. ``` 60Ḷ12pד<¿‘Hạ/eʋƇذ_,Ɗ - Link: integer, A in [0,180] 60 - sixty Ḷ - lowered range -> [0..59] 12 - twelve p - Cartesian product -> Times = [[1,0],...,[1,59],...,[12,59]] Ɗ - last three links as a monad - f(A): ذ - 360 _ - minus A , - paired with A -> Angles=[360-A,A] Ƈ - filter keep those Times for which: ʋ - last four links as a dyad - f(Time,Angles): “<¿‘ - code-page indices = [60,11] × - Time times [60,11] -> [60h,11m] H - halve -> [30h,11m/2] / - reduce by: ạ - absolute difference -> abs(30h-11m/2) e - exists in Angles? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes -2 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan). ``` {}⋃Mod[458{#,-#},720,60]~IntegerDigits~60& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@7@69lF3s29@SrSJqUW1so6ucq2OuZGBjplBbJ1nXklqemqRS2Z6ZklxnZmB2v@Aosy8kmhlBV07hbRo5dhYBTUFfQeFagMdBUsgNrQAEiamOgrGQNoMJGAEIoAChsYgAihppKNgbglkmlkACXPL2v8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes ``` a->Set([[(b\60-1)%12+1,b%60]|b<-458*[a,-a]]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN3USde2CU0s0oqM1kmLMDHQNNVUNjbQNdZJUzQxia5JsdE1MLbSiE3V0E2NjNaF6YhMLCnIqNRIVdO0UCooy80qATCUQR0khTSNRU1NHIdpAR8ESiA0tgISJqY6CMZA2AwkYgQiggKExiABKGukomFsCmWYWQMLcEmbJggUQGgA) The `%12` trick is stolen from [G B's Ruby answer](https://codegolf.stackexchange.com/a/246335/9288). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~82 79 55~~ 47 bytes ``` ->d{[k=262*d,-k].map{|c|[c/60%-12+12,c%60]}|[]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6lOjrb1sjMSCtFRzc7Vi83saC6JrkmOlnfzEBV19BI29BIJ1nVzCC2tiY6tvZ/gUJatGEsF4gygFDGQFrDQE/P0MJAE6I7pQYkngJUDQA "Ruby – Try It Online") Stolen from various other answers: the angle between the two hands is increased by 1 degree after 4h22m. [Answer] # [R](https://www.r-project.org), ~~61~~ ~~60~~ 55 bytes ``` \(a,b=458*c(a,-a))unique(cbind((b%/%60-1)%%12+1,b%%60)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZFLbgIxDIbFtqeIVEVK6IywncdkkLgJGwYYiQ1SK2bHgnt0M63UQ8FpmsRIJFnk4c_2_yf5_vmaf8fN33QZ23DvtmrXDBvrwnIfd-1O6-l8-pyOaj-czgelBrmSHlrUUiJ9YDPIeNSayx-L26hACP0u8rgKpDXA26h6KIImxhrRM8EAL-I5Zl2RbdcmZndxjsSUfTD3QeQiXyJiBE8NgrJfQuFJSiWXlTwroXGlkuF2jERljyjbC8k4Vdckm4SMj6Tr6wegRFyqQR8qIZ-FyCbU9RUKjCghrOw5tofAHzHPvP4D) Port of [@alephalpha's answer](https://codegolf.stackexchange.com/a/246339/55372). Outputs as a matrix with hours in the first column and minutes in the second. --- ### [R](https://www.r-project.org), ~~84~~ 72 bytes *Edit: -9 bytes thanks to [@Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l).* ``` \(a)t(which(outer(1:12,0:59,\(x,y)abs(30*x-5.5*y)%in%c(a,360-a)),T))-0:1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZHBSgMxEIbx6lMESiEpWZmZbLJJwLsP4LGXtbi0lwp1S1vw4Ht4WQUfSp_GZKdgkkMC8838_5_k4_MwfQ3338dxaPzPw1r2apSn7W6zlS_H8fkgMSJpiDbotTzri-qfXqWB1bmxd3Z1UcvdfrmRvTYOml4p_ahUAxFZ7_fmfZAghFqIeb0JpAhwO8gARdGkmhaBCXr4J45rrS2622hSd5f2REypg7MOIg-5EhEjuHoQlHoZ-Sspnezs5NgJjS2dDMsxElU8ojmez8Gpuia12ci4RLpQPwBlYvMMOl8ZudmI2oy6UCHPiDLCKp7leAj8EdPE5x8) Outputs as a matrix with hours in the first row and minutes in the second. The formula looks exactly like in [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/246338/55372). [Answer] ## JavaScript (ES6), ~~79~~ 78 bytes Only works in locales with UTC that use the 12 hour clock. ``` f= n=>(n%180?[262,458]:[262]).map(m=>new Date(m*n*6e4).toTimeString().slice(0,5)) ``` ``` <input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o> ``` Longer version that works everywhere, except on days with DST transitions: ``` f= n=>(n%180?[262,458]:[262]).map(m=>new Date(0,0,0,0,m*n).toLocaleString('en-US',{timeStyle:'short'}).slice(0,5)) ``` ``` <input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o> ``` Longest version that always works everywhere: ``` f= n=>(n%180?[262,458]:[262]).map(m=>new Date(m*n*6e4).toLocaleString('en-US',{timeStyle:'short',timeZone:'utc'}).slice(0,5)) ``` ``` <input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o> ``` Explanation: The angle between the hands is `1°` at `04:22` and its reflection, which correspond to `262` and `458` minutes past midnight. Any larger angle can be obtained by simply multiplying the desired angle by those two numbers of minutes. Edit: Saved 1 byte thanks to @MatthewJensen. [Answer] # [Haskell](https://www.haskell.org/), ~~65~~ 64 bytes ``` f a=[[h,m]|h<-[1..12],m<-[0..59],elem(abs(h*30-5.5*m))[a,360-a]] ``` [Try it online!](https://tio.run/##HYnNDoIwEIRfZY@FLE1/LEIib6Anj00PawKpsUUiGC@@e108zDdfZiKtjzGlUiagwfuIOXzjqfFaSm0CZlYlpesDjmnMgm6riLVVjZOuzlXlCW2rGgqhZLrPMECm5QJieW/X7XWeQcIanx@uqQKvEHqO7hgHh2C5230wO3jQdgefBuHYs7Yd42/ahfID "Haskell – Try It Online") Ironically, I wrote this to try some taste of Curry, but it failed with some errors I struggle to understand. Worked in Haskell though... Thanks to pajonk for -1. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` NθEΦ³⁶⁰№﹪×¹¹⟦±ιι⟧³⁶⁰θ⪫E⟦∨÷ι³⁰¦¹²⊗﹪ι³⁰⟧﹪%02dλ: ``` [Try it online!](https://tio.run/##NYy9CsIwGEV3nyIEhAQitPVnsKNFqGB1cCsdahP0gzRpY9LXj1/9Wc5w7uF2z9Z1ttUxlmYIvgr9XTk28nxxdWA8O7cDO4L2KNe7RJCDDbO1MmjLbtCrF0tTQepKPVqvGHBBoEFgjBw54mTBfH7qi2Ol8QVMIDHFaG7SDFHYcNdK/o@/G28E@Qm6TDJJBdHzId1Tznke42YbV5N@Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The angle between the hands increases by 11° every two minutes. ``` Nθ ``` Input the angle. ``` EΦ³⁶⁰ ``` Loop over all times from `12:00` to `11:58` in multiples of 2 minutes. ``` №﹪×¹¹⟦±ιι⟧³⁶⁰θ ``` Keep only those times where the angle between the hands or its negation equals the input. ``` ⪫E⟦∨÷ι³⁰¦¹²⊗﹪ι³⁰⟧﹪%02dλ: ``` Format the doubled number of minutes as a time. If outputting `12:00` or `06:00` twice for inputs of `0` and `180` respectively had been legal, then for ~~41~~ 39 bytes: ``` NθE×⟦²⁶²¦⁴⁵⁸⟧θ⪫E⟦⊕﹪⊖÷ι⁶⁰¦¹²﹪ι⁶⁰⟧﹪%02dλ: ``` [Try it online!](https://tio.run/##RYuxCsIwFEV3vyIEhBeIUENbxK5dKlQc3EqH2DwwkCZtTPr70arocuGee@5wl35w0qTU2CmGcxxv6GFm1ebitQ3QygmuesQHdKIUnOTFoedkZpycnLbvuWvs4HFEG1BB61Q0Dmr8o8aGWi9aIWhOyoy9vnux5tf90P7X6TYTinJiVoceKWOsSikv0m4xTw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The number of minutes is given by the angle multiplied by `262` or `458` (effectively modulo `720`, but this is calculated by taking the hour modulo `12`, with a zero result becoming `12`). [Answer] # [JavaScript (V8)](https://v8.dev/), ~~77~~ 72 bytes -5 bytes thanks to Arnauld! ``` a=>new Set([a*262,a*458].map(m=>(m/60%12|0||12)+(m%60>9?':':':0')+m%60)) ``` [Try it online!](https://tio.run/##TY9db5swFIbv/SvOxVrshjq2@ShJBFUvNqnSLiblMo0aK3IaJr4ETqat6W/PsIEASBg/et/Hx7/lWTb7Oq304zm6HuKrjJNC/YG10ngjH0QoXPngB9GW5rLCeZzgfB6yOy4u7HLhgsxwfheyZPHsLM3LHDIzgJDrCu0Qg/65ABdLxtCC3YDX7l1YGMojNtDQ7P3glvKXXpt6ar/IG7vcdrlZUDhi0WFmnYKNDoMjS0dzYM2hMXMvGM1epzAYJmMIYceIkC8mVxC@EXshelpMLyYMDSLEw2giDq1Y@IgPaYujDgvE@WSMoBuDM7Sjuk5zTGhTZanGzlvhEHoo6@9yf8RZWiiIE/hEAPuyaDRs0qI6aRfeXShPuv2FGN6HrgsO2bbA1Ho2h9nbBeZkdTPUqjllpnbAlawb9VpobKVkEqpk07SR7giaqeJDHyGO475Nm/Sfgvv7IaDOqv6LdZrbafvMUTYWjd4yUzQrP7C1P4Pz62W9dmAJzo@X15/t9P3dnMek3WwopZ1p68LQMOkd/vbZnftFdq37i6yu/wE "JavaScript (V8) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 22 bytes ``` 6d59Ẋ'30₀›½"*÷εkR⁰-⁰"c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJNIiwiIiwiNmQ1OeG6iiczMOKCgOKAusK9XCIqw7fOtWtS4oGwLeKBsFwiYyIsIiIsIjE3OSJd) You can also [run all the test cases](https://ato.pxeger.com/run?1=m720rLIiMWfBcoc0K8OaQ4uXlpak6VrcVDRLMbV8uKtL3djgUVPDo4Zdh_YqaR3efm5rdtChpbqHliolLylOSi5eY23NdWy2Q5q19aPGbojWpdFKvkqxNx2iDXQULIHY0AJImJjqKBgDaTOQgBGIAAoYGoMIoKSRjoK5JZBpZgEkwCxD01iIaQA) but be prepared to wait at least a minute. ## How? ``` 6d59Ẋ'30₀›½"*÷εkR⁰-⁰"c 6d # Push 6 doubled, which is 12 (this is to avoid having to put a space after it) 59 # Push 59 Ẋ # Cartesian product of these two numbers, which are implicitly cast to inclusive zero ranges ' # Filter this list for: 30 # Push 30 ₀› # Push 10 + 1, which is 11. This is to avoid having to put a space before it ½ # Halve to make 5.5 " # Pair these two values to [30, 5.5] * # Multiply both by the current item ÷ # Push both values of the multiplied pair to the sstack ε # Absolute difference of the two kR⁰- # Push 360 minus the input ⁰" # Pair with the input c # Does this list contain the absolute difference pushed earlier? ``` [Answer] # [Zsh](https://www.zsh.org/), 81 bytes ``` >{-,}{$[x=$1*2],$[720-x]} eval h={1..12}\;m={0..59}';<$[h%12*60-m*11]&&<<<$h:$m;' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYw7DoJAGAZ7TvEVKwhhyf6Ly0Meta01Uhgj2UJCgo8QCSexITEWHonbiNFiMplmHs_7WY_TpmpaEJYCsQBFAisFXyCYQ84okD-DlUQYg4II9DUpG0vjeNANGMHiPLde10vFo2mb99wdelZ0GSNHli4rQil4Vw7G8bY_QWc9eR7JYZfUWS88T8WDlaSs0AuSTiB47RCVppmmKdNrVif_8butwTkcw_71OP78AQ) Damn floating point errors! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 89 bytes ``` .+ $*_¶$&$*_ \G_ 262$* _ 458$* 1{720} D` G`. %`^(.{60})*(.*) $#1:0$.2 %`^0 12 :0(..) :$1 ``` [Try it online!](https://tio.run/##FYwxDoMwEAT7fUWkHBF2otOdwcZQR@ITUXCKFDQponSIb/EAPuaYYjTFrPb7/s2fV858Bdlp3@hShMc4wQVHFhNaH4t16ZyswD1hTIwqPWtegqzG1mwN6KyDELsjCNRhkJrZYCDNlUn7htspC/rSopRLNIJwDAse2hTQOnQ9NEToYfV/ "Retina 0.8.2 – Try It Online") Outputs times on separate lines but link is to test suite that joins with comma for convenience. Explanation: ``` .+ $*_¶$&$*_ ``` Convert to unary twice. ``` \G_ 262$* _ 458$* ``` Multiply the first copy by `262` and the second by `458`. ``` 1{720} D` G`. ``` Reduce modulo `720` and deduplicate. ``` %`^(.{60})*(.*) $#1:0$.2 %`^0 12 :0(..) :$1 ``` Format as a time. [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` lambda n:{(n*i//60%-12+12,n*i%60)for i in(262,458)} ``` [Try it online!](https://tio.run/##HYlBCsIwEEX3nmI2hUSnNJk0MS14EzcVCQZ0Wko3RXr2OHEx7///Ztm318yupNu9vKfP4zkBj1/F59x1wTStpYsllNkEo9O8QobMigJh76M@SlUsCgzCIGejoPcITjJUQRUirKuQJyFcB6khCv7N@vEEsKyZN5UUa11@ "Python 3 – Try It Online") Ported from various other answers. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 12L59Ýâʒ30T>;‚*ÆÄU360α‚Xå ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/246338/52210), and the output-format is also the same: a (1 or 2-sized) list of pair(s) of \$[h,m]\$. [Try it online](https://tio.run/##yy9OTMpM/f/f0MjH1PLw3MOLTk0yNgixs37UMEvrcNvhllBjM4NzG4G8iMNLgaoA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8NjXxMLQ/PPbzo1CRjgxA760cNs7QOtx1uCT20zsXYzODcRqBAxOGl/2t1/kcb6Fga6BhaGOiYmOoYG@iYATlGQGyqY2gMxDomRjrmljqGZhY6hiDa0DQWAA). **Explanation:** ``` 12L # Push a list in the range [1,12] 59Ý # Push a list in the range [0,59] â # Cartesian product of both lists to create all possible pairs ʒ # Filter these pairs by: 30 # Push 30 T>; # Push 5.5 (10 +1 /2) ‚ # Pair them together * # Multiply the values in the pairs [30h,5.5m] Æ # Reduce this pair by subtracting Ä # Convert it to its absolute value U # Pop and store this value in variable `X` 360α # Get the absolute difference of the (implicit) input and 360 ‚ # Pair the (implicit) input with this 360-input Xå # Check if value `X` is in this pair # (after which the filtered result is output implicitly) ``` [Answer] # Excel, 98 bytes ``` =LET(t,ROW(1:720)/1440,h,HOUR(t),m,MINUTE(t),a,ABS(30*h-11*m/2),FILTER(h&","&m,(a=A1)+(a=360-A1))) ``` Input is in the cell A1. Output is wherever the formula is and - usually - the cell below it. [![Screenshot](https://i.stack.imgur.com/3Mny1.png)](https://i.stack.imgur.com/3Mny1.png) The LET() function allows you to define variables for later reference. Here's each piece explained. * `t,ROW(1:720)/1440` an array of time values from 0.0 to 0.5 (noon) broken into 1 minute long pieces. * `h,HOUR(t)` an array the same length as `t` but just the hours. * `m,MINUTE(t)` an array the same length as `t` but just the minutes. * `a,ABS(30*h-11*m/2)` math based on other answers here. * `h&","&m` combines the two arrays into the output format desired. * `(a=A1)+(a=360-A1)` checks if the math matches the input angle. * `FILTER(~,~)` returns just the outputs where the match matched the angle. --- I also found this solution that clocks in at 103 bytes and outputs the results into a single cell. ``` =LET(h,COLUMN(A:L)-1,m,ROW(1:60)-1,a,ABS(30*h-11*m/2),TEXTJOIN(" ",1,IF((a=A1)+(a=360-A1),h&","&m,""))) ``` [Answer] # [Desmos](https://www.desmos.com), ~~66~~ 61 bytes ``` i=[262,458] f(n)=(mod(floor(in/60),-12)+12,mod(i,60)n).unique ``` [Try it on Desmos!](https://www.desmos.com/calculator/jkxmkzjgtn) *-5 bytes thanks to Aiden Chow* [Answer] # C#, 71 bytes ``` (int a)=>new[]{458*a,262*a}.Select(x=>((x/60+11)%12+1,x%60)).Distinct() ``` [Try it online!](https://tio.run/##XVDLTsMwELznK1YVlezWmDhtQ9s0uZSHiuDUAwfEwRgXLKWOiN0SFOXbwxoQQkje8c6sZXtGuVPlVH9wxr7A9sN5vc@iv4zfGvv2T1pXZamVN5V1/FpbXRuVRaqUzsE6aiNwXnqj4FiZZ7iTxhIaAcpwdbBqZaxnm0t72OtaPpV6RYKARYsCdnkfKEiaF1a/Pzy209l8JFmSJiPZ8a0Oz5ImLwhpztJ4LAQdimQsWDNMY0r5hXHeWDxC@2xX1VqqVyBHWYMFY@H7xpjBAkvMEaYzBhPc0yAkAVAQkwA4TBicL7BN5whfnZh1aAXWaLwqNb@vjdeYjybO15gPv6nQ7IABrh2x9PfDkBdwMmgbvsH4xDKOu@UPSQIZUEqzqOv6Tw) Based on various other answers. Like Jitse's Python 3 solution, I'm using both magic numbers 262 and 458 to get the answers in minutes, modulo 720 minutes. For the hours, I'm using the trick to add 11, take the remainder of dividing by 12, and then add 1 to get a value from 1 to 12. Since duplicate answers for 0 and 180 aren't allowed, I'm using the Distinct function from Linq. Community guidelines for C# require a type for lambdas hence the `(int a)=>`, if untyped lambdas are OK we can make that `a=>` for a saving of 6 bytes. ]
[Question] [ Say I have a pile of boxes: ``` AAA BBB ``` I can create it in two steps: ``` BBB ↓ (empty) --- AAA ↓ BBB ``` But with this: ``` AB BA ``` I need three steps: ``` A ↓ (empty pile) --- BB ↓ A --- A ↓ B BA ``` # Your challenge Given a pile of boxes, output the minimum number of steps needed to create that pile. A step consists of dropping a row of boxes of the same type onto the current pile. For example, `AAA` can be dropped as a step, so can `A A`, but `A B` and ``` A AAA ``` can't. Input can be as a matrix, text, whatever. The input will always be a solid block - nothing like ``` BB AAA ``` Will ever be inputted, so you don't have to parse spaces / empty values. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases ``` AB BA => 3 A B C D E => 5 AAA AAA AAA => 3 ABCAB DEACB => 7 POTATOS DOBEYUM => 12 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` L&lbhSmhyfT>RqhkhdbbyC ``` [Try it online!](https://tio.run/##K6gsyfj/30ctJykjODejMi3ELqgwIzsjJSmp0vn//2ilAP8QxxD/YCUdJRd/J9fIUF@lWAA "Pyth – Try It Online") [Or run all test cases at once.](https://tio.run/##K6gsyfj/30ctJykjODejMi3ELqgwIzsjJSkpt9L5//9oJUcnJR0lJ0elWB0gG8QEYmcgdgFiV4ioI0gcQYLFnJzBGl1cHZ2dwCIB/iGOIf7BIDF/J9fIUF@lWAA) This is basically [ovs's Python solution](https://codegolf.stackexchange.com/a/230084/30164) translated verbatim to Pyth (it seems that their solution's exact algorithm is also shortest in Pyth), so I'm posting it as community wiki. Doesn't time out thanks to Pyth's memoization. [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ 91 bytes -12 bytes thanks to [PurkkaKoodari](https://codegolf.stackexchange.com/users/30164/purkkakoodari)! ``` lambda s:f(zip(*s)) f=lambda s:len(s)and-~min(f({r[r[0]==x[0]:]for r in s}-{()})for x in s) ``` [Try it online!](https://tio.run/##PY3BboMwEETv@xW@xa4EalpVlZBcyZB8BXCgxSSWwFheRyGN0l@na4I4eOV5M7PrbuE82rf5JKu5b4bvtmGYdfzXOP6CQkAnN9pry1E0tk3@BmN5x@@@9OVrLeVEM6u70TPPjGX4SO5cPEQE0wLEbAY3@sDwhhA0BmQy/lMMrbGp103LRYquN4HvKlvZHV2mdozGBUslA8Z6Y3XsRvDML4QL8vx4jdYCyizZ18T05PRP0C1xYwN/emStt0S5r5eqxksfKHTicUtEzlNhNYB0g6h92JJyWz2rHHIF8ou9AyjIoYADHKP@IK3U9tZEXlDhcFRFHsnnPw "Python 2 – Try It Online") The last testcase times out. The first function just transposes the input, if we can take input as a list of columns it can be omitted. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` WS⊞υι≔⟦Eθ⮌⭆υ§λκ⟧η≔⁰ζW⌊η«≦⊕ζ≔ηθ≔⟦⟧ηFθFκ⊞ηΦEκΦμ∨π¬⁼ξ§λ⁰μ»Iζ ``` [Try it online!](https://tio.run/##VU@7bsMwDJytr@BIASqQvZPspoCHtEE7Bh0ER40ES7KtRxqk6LerSiL0wYU48nh3HJTwwyRMzh9KGwnYuznF1@i1OyClsE1BYWKg6T3hIeiDw91GzLgweJFH6YPEG/kyLDwee7eXJzQMRlrqjYH6PV0xOBdUrTbaaZssquLzSZqiUGm9G7y00kW5vx00daEYLH/grqo375MHXChc@1hTF/KjNlF6vGQbf5Bl8OxxZvA0RVwvSZiAp3/JV/RaDCwt6l9kWx6M2IkQ8VwmOfO24y15WPOuJfnuaL4B "Charcoal – Try It Online") Link is to verbose version of code. Uses brute force so too slow for the last test case on TIO. Explanation: ``` WS⊞υι ``` Input the pile. ``` ≔⟦Eθ⮌⭆υ§λκ⟧η ``` Rotate the pile by 90° and put it into a list. ``` ≔⁰ζ ``` Start counting the number of steps. ``` W⌊η« ``` Repeat until there is at least one empty pile. ``` ≦⊕ζ ``` Increment the number of steps. ``` ≔ηθ≔⟦⟧ηFθ ``` Make a copy of the list of piles so that it can be looped over while starting a new list of piles. ``` Fκ ``` Loop over each column of the pile. ``` ⊞ηΦEκΦμ∨π¬⁼ξ§λ⁰μ ``` Remove the letter at the bottom of that column from all of the columns that have it as its bottom letter and push any remaining non-empty columns to the list. ``` »Iζ ``` Print the number of steps needed. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 31 bytes ``` ∧≜.&z{{⟨k≡t⟩|;X}ᵐRtᵛ∧Rhᵐ}ⁱ↖.zĖ∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1HH8kedc/TUqqqrH81fkf2oc2HJo/kra6wjQLJBJQ@3zgaqCMoAcmofNW581DZNr@rINKDQ///R0UqOTko6CkpOjkqxOgpAHpgDIpxBhAuIcIVKOYIlkSiIsJMzxAgXV0dnJ4hYgH@IY4h/MFjU38k1MtRXKTYWAA "Brachylog – Try It Online") It's a *bit* less efficient than even the other two answers so far (it does the classic recompute everything if it hasn't reached the end in as many steps as it's trying), so I might just delete this when I wake up if it still hasn't spit something out for the second-to-last test case. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ZWṖ€ṛ¦Ɱ0ịⱮĠƊ$€Ẏ$Ẹ€Ạ$пL’ ``` [Try it online!](https://tio.run/##y0rNyan8/z8q/OHOaY@a1jzcOfvQskcb1xk83N0NpI4sONalAhLe1afycNcOMGuByuEJh/b7PGqY@d/6UcOcQ9sUdO0UHjXMtX64e8vhdhWuo5Mf7lz8qHHfoW2Hth1uB2rJgnL@/3d04nJy5OJy5HLicuZy4XIFMh0d4ZjL0ckZqMLF1dHZCQA "Jelly – Try It Online") A monadic link taking a list of Jelly strings (a list of lists of characters) and returning an integer. ## Explanation ``` Z | Transpose W | Wrap in a list $п | While the following is true: Ẹ€ | - Any list is non-empty for each list of lists Ạ | - All $ | Do the following, collecting up intermediate results $€ | - For each list: Ṗ€ṛ¦Ɱ Ɗ | - Remove the last character of the lists for each of the groups of indices determined by the following: 0ịⱮ | - Last character of each list Ġ | - Group indices of identical characters Ẏ | - Tighten (join outermost lists together) L | Length ’ | Subtract 1 ``` [All cases](https://tio.run/##y0rNyan8/z8q/OHOaY@a1jzcOfvQskcb1xk83N0NpI4sONalAhLe1Rd4rOvhrh1g9gKVwxMO7fd51DDzv/WjhjmHtino2ik8aphr/XD3lsPtKlxHJz/cufhR475D2w5tO9wO1JIF5fz/7@jE5eTIxeXI5cTlzOXC5QpkOjrCMZejkzNQhYuro7MTF1eAf4hjiH8wl4u/k2tkqC8A) (uses `Q` for 1 extra byte to make it more efficient, but would complete eventually without it) [Answer] # [J](http://jsoftware.com/), 55 bytes ``` (1+[:<./$:"1)@((]}.~1{.=)&.>"0/~' '-.~{.&>)`0:@.(''-:;) ``` [Try it online!](https://tio.run/##ZY1NC4JQEEX3/YpBovFRjl@I8EzxPbVVZfSxiAiCSCqIFtXK8q@bmS2kuczq3DNzLhXCDHwOCAMwgFerEUTz8ahUzf6GD0nvcsVkoapuX1SYOfmsR4Fi6AUCalTk1AvYzuAhqYga91jJOof98Qo2@JCBp4dPDlaVLqCQUuCXui3qfGkkZJyISDYdp@nUKE7w/65d5WP@BjtTSXA/XQ43uD7uUAum1frlfoxZuhTLdBGnMlmvJli@AQ "J – Try It Online") Brute force recursion taking away boxes until none are left, and returning the minimum number of steps. [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->l{l.permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevILUot7QksSQzP08vN7GguqaipkLL1j7e2rA8IzMnVaFCr7g0SVFDX0NPSzM@xlBfRz3GUF3TGiicWZVaq5ebmVf7v0AhLTpaydFJSUfJyVEpNpYLKuDoCBRBkAgJF5BKVyDhDJZzBnGdgPL/AQ "Ruby – Try It Online") Assuming I can accept a list of columns in input # [Ruby](https://www.ruby-lang.org/), 108 bytes ``` ->l{l.map(&:chars).transpose.map(&:join).permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min} ``` [Try it online!](https://tio.run/##RcrBCoIwAMbxe09hO6QTm3hNLDbrKVRkxsSJzrEpWeqzLwvBy3f4fX81FG9TRuZ8baYGtVQ6p8uzokpD1CsqtOw027juuIBIMtUOPe15J34@zeM8utEtD4NXxRtmjUgPxdHxHeTCPA18z04DG4Yr8w9bUMvFYqRVJgnABHiAYJBlhw0wXmXf/SDxP74/cExWNl8 "Ruby – Try It Online") Otherwise ]
[Question] [ # Goal Write a program or function that returns the day of the week for a date, eg. ``` 01/06/2020 -> Mon ``` However, it's unknown if the date is in the format mm/dd/yyyy or dd/mm/yyyy. If you can be certain of the day of the week, return it. If there is uncertainty, return an error. ``` 02/07/2020 -> Err (Thu? Fri?) ``` # Input A date in the format `#/#/####`. * The numbers can optionally have leading zeros. * The year should be read verbatim, assume that 19 = 19 AD, not 19 = 2019 AD. * The separators can be any non-digit character. * Assume the input date is valid in at least one format (ie. not 13/13/2020). * At a minimum, support dates from 2000 through 2030 (which are likely covered by any modern OS and language with a date library.) # Requirements * If the first and second numbers: + are the same (03/03/2020), the date is **unambiguous**. + either is greater than 12 (13/09/2020, 09/13/2020), the date is **unambiguous**. + are different and both 12 or less (09/11/2020), the date is **ambiguous**. # Output * If the date is unambiguous, return the day of the week. * If the date is ambiguous: + If both versions of the date have the same day of the week, return the day of the week. + If both versions of the date have a different day of the week, return an error. * A day of the week should be returned as a string of the day's three-letter abbreviation ("Mon"), case-insensitive. * An error should be returned as any other three-character string, not all whitespace, eg. "Err", "NaN", "???". # Test Cases ``` 02/07/2020 -> Err 01/06/2020 -> Mon 05/05/2020 -> Tue 24/06/2020 -> Wed 05/09/2030 -> Thu 03/13/2020 -> Fri 29/02/2020 -> Sat 03/12/2000 -> Sun ``` # Scoring The code with the least byte count in a week wins the tick. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~97~~ ~~96~~ ~~93~~ ~~85~~ ~~80~~ ~~76~~ ~~73~~ ~~58~~ ~~56~~ 51 bytes ``` (${d=date +%a -d$3-}$1-$2;$d$2-$1)|uniq|sed N\;cErr ``` [Try it online!](https://tio.run/##LcnLCsIwEIXhfZ7iUEZQJJCLVaTUnVufwE3sBFqQFNuKBeuzx1gLw@Hjn5vr6/iqm7tH5x1jFAC3aQBf1S1kQEYjyhOyOfZ@AI1xTW8u2Q0e25WDZLLyQ1qSKYjJSNKb6Rmax9R7xuVaVOeui9wGHw0OMMoooTT2i3Kkm2l2UEvNcUywSmgLu3xT@ctC/6SU@AI "Bash – Try It Online") *5 bytes off thanks to user41805, who pointed out that I could use sed's `c` command instead of the final `s` command.* *2 bytes off thanks to Nahuel Fouilleul. (Nahuel also helped by shaving 4 bytes off in an earlier version that has since been revamped.)* When I noticed that the separators can be any non-digit character, I changed the code to use spaces as the separator. This is called with a command like `checkdate 01 06 2020` The output is on stdout. (There's spurious output on stderr.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~88~~ ~~82~~ ~~79~~ ~~76~~ ~~79~~ ~~73~~ 72 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #ÂÀ‚Dε`UÐ3‹12*+>₂*T÷s3‹Xα¬Ésт%D4÷O.•A±₁γβCüIÊä6’C•3ôsè}DËiнës€¨13‹WiтëθÏ ``` -3 bytes thanks to *@Arnauld* (initially -6, but +3 bytes again, since Jan./Feb. 2000 would still result in the previous century in the formula). -7 bytes thanks to *@Grimmy*. Input is space-separated; and outputs in lowercase with `100` as error. [Try it online](https://tio.run/##AYoAdf9vc2FiaWX//yPDgsOA4oCaRM61YFXDkDPigLkxMiorPuKCgipUw7dzM@KAuVjOscKsw4lz0YIlRDTDt08u4oCiQcKx4oKBzrPOskPDvEnDisOkNuKAmUPigKIzw7Rzw6h9RMOLadC9w6tz4oKswqgxM@KAuVdp0YLDq864w4///zAxIDA2IDIwMjA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf@XDTYcbHjXMcjm3NSH08ATjRw07DY20tO0eNTVphRzeXgwSiDi38dCaw53FF5tUXUwOb/fXe9SwyPHQxkdNjec2n9vkfHiP5@Guw0vMHjXMdAbKGB/eUnx4Ra3L4e7MC3sPry5@1LTm0ApDkDnhmRebDq8@t@Nw/38lvTCd/9FKBkYKBuYKRgZGBko6SgaGCgZmcI6pAhBBOUYmaDKWQI4xmGOsYGgMV2apADQQpgwoA@IYgDlA3SbI9hjCZGB6gJxYAA). **Explanation:** Since 05AB1E has no Date builtins, we'll have to calculate the *Day of the Week* manually. The general formula to do this is: $${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$ Where for the months March through December: * \$q\$ is the \$day\$ of the month (`[1, 31]`) * \$m\$ is the 1-indexed \$month\$ (`[3, 12]`) * \$K\$ is the year of the century (\$year \bmod 100\$) * \$J\$ is the 0-indexed century (\$\left\lfloor {\frac {year}{100}}\right\rfloor\$) And for the months January and February: * \$q\$ is the \$day\$ of the month (`[1, 31]`) * \$m\$ is the 1-indexed \$month + 12\$ (`[13, 14]`) * \$K\$ is the year of the century for the previous year (\$(year - 1) \bmod 100\$) * \$J\$ is the 0-indexed century for the previous year (\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\$) Resulting in in the day of the week \$h\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday. [Source: Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence) Since the input is guaranteed to be in the year-range \$[2000, 2030]\$, we can modify \$+ \left\lfloor{\frac{J}{4}}\right\rfloor - 2J\$ to a hard-coded \$-35\$ to save some bytes. EXCEPT, when it's Jan./Feb. 2000, in which case it's the previous century. For those, we use `¬És`, to add 1 to our hard-coded replacement of \$J\$. In addition, we won't need the \${\bmod {7}}\$, since we only use it to index into the string list, and 05AB1E uses modular indexing anyway. We can save 2 more bytes, by just removing the \$-35\$ all together, since it's a multiple of 7 anyway. And one more byte, by changing the \$\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\$ to \$\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\$, since 05AB1E has a single-byte builtin for `26` and `10` (which are `₂` and `T` respectively). ***Code explanation:*** ``` # # Split the (implicit) input-string by spaces  # Bifurcate it (short for Duplicate & Reverse copy) À # Rotate the reversed copy once towards the left ‚ # Pair the top two values together # (we now have a pair [[day,month,year],[month,day,year]]) D # Duplicate it ε # Map over both values in this pair: ``` Now comes Zeller's congruence into play: ``` ` # Push the day, month, and year separated to the stack U # Pop and save the year in variable `X` Ð # Triplicate the month 3‹ # Check if the month is below 3 (Jan. / Feb.), # resulting in 1 or 0 for truthy/falsey respectively 12* # Multiply this by 12 (either 0 or 12) + # And add it to the month # This first part was to make Jan. / Feb. 13 and 14 > # Month + 1 ₂* # Multiplied by 26 T÷ # Integer-divided by 10 s3‹ # Check if the month is below 3 again (resulting in 1 / 0) Xα # Take the absolute difference with the year ¬ # Push the first digit (without popping the mYear itself) É # Check if its odd (1 if 1; 0 if 2) s # Swap to take the mYear again т% # mYear modulo-100 D4÷ # mYear modulo-100, integer-divided by 4 O # Take the sum of all values on the stack ``` And then we'll continue: ``` .•A±₁γβCüIÊä6’C• # Push compressed string "satsunmontuewedthufri" 3ô # Split it into parts of size 3: ["sat","sun","mon","tue","wed","thu","fri"] s # Swap to get the earlier calculated number è # And index it into this list (0-based and with wrap-around) }D # After the map: duplicate the resulting two days Ëi # If they are both the same: н # Leave just one of them ë # Else (they are different): s # Swap, to take the initially duplicated pair of # [[day,month,year],[month,day,year]] €¨ # Remove the year from each 13‹ # Check for the remaining values if they are smaller than 13 W # Push the flattened minimum (without popping) i # If it's truthy (so day and month are both below 13): т # Push 100 (as error value) ë # Else: θ # Pop and leave just the last one (either [0,1] or [1,0]) Ï # And only keep the day at the truthy index # (after which the top of the stack is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•A±₁γβCüIÊä6’C•` is `"satsunmontuewedthufri"`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~124~~ 121 bytes ``` {<Err Mon Tue Wed Thu Fri Sat Sun>[2>set($/=|grep ?*,map {try Date.new(|$_).day-of-week},m:g/\d+/[[2,1,0],[2,0,1]])&&$0]} ``` [Try it online!](https://tio.run/##VZBNa8JAEIbv@yveQwhqN85k01psa3ppe@spQg8aSiAblZoPNgkS1P71dBVECwMDDw/M@06lzXbS5x3cDDP0@5d3Y/BZFpi3Gl86xXzd4sNsECUNorYIFyqsdTNwaHZYGV3hdSTzpMK@MR3ekkaPC70bHJzv4ThNOq/MvJ3WP0eZP61omd7RYqGkLzmWdrP043joug7Hx/5Z1EmHDL85LaMRISsNtptC1z0r4kdSrBjwQsAmFOwTT26YTSz4gexcmW0g1P1/zzY6e1PLgou3bgUH5Ac3nm0s1JTs6SuzHzh7J8YX1hZ/ "Perl 6 – Try It Online") [Answer] # JavaScript (ES6), ~~136 132~~ 131 bytes Returns `"Err"` for an error. ``` s=>'SunMonTueWedThuFriSatErr'.match(/.../g)[[i,j]=([d,m,y]=s.split`/`).map(M=>new Date(y,M-1,M^m^d).getDay()),d<13?m>12|i==j?i:7:j] ``` [Try it online!](https://tio.run/##bdBBa4MwGAbg@36F9NIE0nxR15WWxV663Ty1sINYGjTViEbRuCHsv7vsUkQLOT68X963EN@iS1rVmI2uUzne@djxYH3udVjrSy@/ZHrJ@89WnYX5aNs1rYRJcgSUUshwFClSxBxFKanIEPOOdk2pzA1u2MIGhTzQ8sc5CSPRQMKNS8JrdU0xzaQ5iQFhTNJ31z9Wgev9Ks6LozrsDkU8JrXu6lLSss7QHa2YB2wHHvPYCmMHwLFfeZkbF9jb1NgCC7MF@ybGNpwb73WWYyd4lrO3xn/k5P3C@OD60xw74uLWHmy1ibErP8v5N@xhej3@AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string 'SunMonTueWedThuFriSatErr' // lookup string .match(/.../g)[ // split it and pick the relevant entry: [i, j] = // (i, j) = day-of-week indices ([d, m, y] = s.split`/`) // split s into (d, m, y) .map(M => // for each value M in there (ignoring y): new Date( // create a date: y, // using y as the year M - 1, // using M - 1 as the 0-indexed month M ^ m ^ d // using the other value as the day ) // end of Date() .getDay() // get the day-of-week index (Sun:0, ..., Sat:6) ), // end of map() d < 13 ? // if d is a valid month: m > 12 | i == j ? i // non-ambiguous if m is an invalid month or i = j : 7 // ambiguous otherwise (-> "Err") : // else: j // use j ] // end of lookup ``` [Answer] # [Red](http://www.red-lang.org), ~~186~~ ~~169~~ 167 bytes -2 bytes thanks to Kevin Cruijssen ``` func[d][a: to-date t: load form split d"/"m: min a b: to-date reduce[t/2 t/1 t/3]either any[a/10 = b/10 t/1 > 12 t/2 > 12][pick[:Mon:Tue:Wed:Thu:Fri:Sat:Sun]m/10][.1]] ``` [Try it online!](https://tio.run/##XY5Na8MwDIbPy68Qvnf@yD6oYD3utsta2EH44EYOMWuc4NmH/frMZnSFgYT08L4Sb/K8vXsm2424jSUOxJYcQl527LKHjHBZHMO4pBm@1kvIwEKKGWEOERycsbtak@cyeMrSQJa6dm99yJNP4OI3OakVvMC5jSYfQJuuedtiaQ3DJ@HbEvFUPH54xtNU8DUFPLqMxxLtXC8t3WtrtxrGu2ECBuruhDJSPUujjBKNtFRPN3qUta5kHv5r@0r9L/VS9zfnXta3f86qNVKVLMGaQsxADGJ3EDAC10g/ "Red – Try It Online") Takes the input as string, because [Red](http://www.red-lang.org) doesn't accept invalid dates in `dd/mm/yyyy` format. That's strange, because the coerce function `to-date` that takes a block of 3 values [dd mm yyyy] accepts any integer, including 0 and negative numbers and creates a "correct" date based on them. [Answer] # [PHP](https://php.net/), 115 bytes ``` foreach(['/','-']as$s){if($x=strtotime(strtr($argn,'/',$s)))$o=date('D',$x);if($p&&$o!=$p)die('err');$p=$o;}echo$p; ``` [Try it online!](https://tio.run/##FYvBCsMgEES/pbBEhQSDt2Kll9KfKD1IYqqHZpfVQ6D012v1Mgzz3lCkerlSyw05@CXKh9BiFJN4@gxZfdIm4XC5cMGS3kH2xhI8v/axm81RCtCtvgQpbm04lO0nGgbAkwNSa2okMAtlgRyg/YYlIpCt1Zy10WY28w@pJNxzne5/ "PHP – Try It Online") Uses the peculiarity that the builtin `strtotime` parses dates as either European or American format according to whether the delimiter is either slash or dash. Takes input as `a/b/Y` and returns `err` for an error condition. [Answer] # [Perl 5](https://www.perl.org/) -MPOSIX -naF/, 125 bytes ``` sub d{substr ctime(mktime 6,0,0,$_[0],$_[1]-1,$_[2]-1900),0,3}@G=@F[1,0,2];say$F[0]>12?d@F:$F[1]>12?d@G:d(@F)eq d(@G)?d@F:Err ``` [Try it online!](https://tio.run/##VYw9D4IwEIZ3f0UHBkjEXotgwKhdLHEwmriYEGJQGIjyYcHBGP@69UAW0@ae5@7eXJ2pm6t18ziT9IW1aRW5tHmRmcW1A/HGgM84RRB3lcU268iRPoCFO@ctwoWQEUPn8bxJnobE9JLxVSpkgA0bmjBITSGt7E6QodWv10ppDZzCjHLgMAJGwRvUpfh75dO/qY/qoDqUOUPAp3jkF8BppwCfqm7zqmy0XSaSanu73x02R6Q7AQZf "Perl 5 – Try It Online") Not completely happy with this one, but haven't thought up a better way (yet). [Answer] # [Python](https://docs.python.org/3.8/), ~~180~~ ~~164~~ 158 bytes Saved 3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) and [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved 3 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!! ``` lambda a,b,c:(x:=d(a,b,c))==(y:=d(b,a,c))and x or(x and y and.1)or y or x from datetime import* def d(a,b,y): try:return date(y,a,b).strftime("%a") except:0 ``` [Try it online!](https://tio.run/##TZBNi4MwEIbv@RWDsDQp2eJHu90K2WNve9rCHnb3EGukQo0SJ6CIv92NWqWXYfLwzGR4qxZvpY7eKzNk4ne4yyJJJUie8GtMm1ikdOoZE4K24zPhcnxKnUIDpaENjG071l3ASuNaVxqSmbKAVKLCvFCQF1VpcEtSlcG8smUxATRtbBRaoyeVtm55wnY1mmwco96L9BgB1VxVhbE/oKqxBgGUUBryIw/90GccfPczdyjgbwvyPkvtTfDADyu8WDXDcP@kfqt0UU8ORrN6szOMeBCt6tnkjwXOXOmXxNUdqT9Tqxc6wuD0dGn0NP24lBEjuouxKrabXxseg2jD4Szv9QL2101PMhcucheohikMF2ItMrpFF1Nlco008zrs4fUDurqHzvwoIeq/3mPDPw "Python 3.8 (pre-release) – Try It Online") Assumes we can input the date as three separate arguments and returns `0.1` if ambiguous. **Date as string** # [Python](https://docs.python.org/3.8/), ~~197~~ 191 bytes Ditto the above saves and thanks! :D ``` lambda s:(x:=d(s))==(y:=d(s,1))and x or(x and y and.1)or y or x from datetime import* def d(s,q=0): a,b,c=map(int,s.split('/')) if q:a,b=b,a try:return date(c,a,b).strftime("%a") except:0 ``` [Try it online!](https://tio.run/##TZHLasMwEEX3@orBUCwVNX4lTWNQl9l11UAXTReKLRFD/Igkg43xt7uyHZtshuHoaDRcVa25lkX0UalBsvNw4/kl5aBj3MQsxZoQxnA7tTQghBcpNFAq3MDYtmPdBKRUtrWlQVKVOaTcCJPlArK8KpV5RamQME64M5/ECDi90ITlvMJZYaje6OqWGex6LiEIMgn32BrsQjkCo9pYCVOrYpqKE2qPyEYbJccXsPPCHXtJNImoTOwPRmijgQFG2Am9vRf6oe9Q8O2S1KLAe1@Q81UWzgR33m6Fp1rMMNw@qT8iXdSDhdGsXusZRl4QrepRZY8B1lzpNzerO1J/pnWx0BEGh6dNo6fbj00JUqw7qVrEtXuuw30QuRSO/KYXsE3cHkn7D4ba7AuYwrB5ayaxsSlVyuaNpdOZHt4@odM9dOpXMKb/eocM/w "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 125 bytes *Improvement over [@Noodle9's answer](https://codegolf.stackexchange.com/a/201360/92237)* ``` lambda a,b,y:[.1,w:=g(y,a,b)][w==g(y,b,a)] g=lambda y,m,d:m<13and date(y,m,d).strftime("%a")or g(y,d,m) from datetime import* ``` [Try it online!](https://tio.run/##dZDBbuMgEIbvPAVCqgQVjYm9bbfRurntbU9bqYc0BxJwg2TAAqzIivLs2YEkSntYCQ3MPx8zPwxT2nnX/BzCqWs/Tr20GyWx5Bs@LVazOd8v2k86cRDYerVvS7Lhkq3RZ3uBJ265Wthf80Y6hZVMmhaJzWIKXTJWU3InCfMB59uKW4a64G1BcxkbO/iQ7k/nHccpIqTkFHGLD8R6RzhJo4a41yqfdyPELhiIUaYcR0eOCHUwojcOGrrcBOYr4xYI48i30MvKgYKlbMsMPIOzOPQmUfLwShgDrrz7QhqXeLwC1bkeoAa3aUcLWbStD0FvE1TCrPd7HShr2@31iMESvWXOp2yuPC7/VvhvpdeOBuhU9rNlyiBv8swhgDvakUM8YvzwivEhHPHqcLFyXBN2EnUlnqta1OJMLJdLJOaVePqi/fEOiccK1k17GzWqf3zn3rUq3AtozZXbjUg01bz5wv0OBtUvFYy@aX9lKlzWxFUb3T8 "Python 3.8 (pre-release) – Try It Online") **Input**: 3 integers representing date, month, and year. **Output**: A 3-character abbreviation of a weekday, or `0.1` if the weekday is ambiguous. **How:** * `date(y,m,d).strftime("%a")` returns the abbreviated weekday of the date `d/m/y`. * `g(y,m,d)` returns the weekday if the date is valid, otherwise returns the weekday of the date where month and day are swapped. Thus if `g(y,a,b)` and `g(y,b,a)` are the same, then the weekday is not ambiguous. Otherwise, the weekday is ambiguous. * `[.1,w:=g(y,a,b)][w==g(y,b,a)]` evaluates to `g(y,a,b)` if the weekday is not ambiguous, or `0.1` if the weekday is ambiguous. [Answer] # [Perl 5](https://www.perl.org/) `-MTime::Local=timegm_modern -pF'/'`, ~~116~~ ~~113~~ 108 bytes ``` sub f{$_[1]--;eval{timegm_modern 0,0,9,@_}}$_=($a=f@g=@F)*($b=f@F[1,0,2])&$a-$b?Err:substr gmtime($a|$b),0,3 ``` [Try it online!](https://tio.run/##VY6xDoIwGIRfhaERMFTaGgYxjSwy6eZGSNNqISSUkoIuyKtbf0enu@G7Lzdq12feT08VNAsSFa0xPuqX7Je5M7o1wtiHdkNAEpIckkKsKxI8QpI3RcuLMt5GSEEvKwoAq@MNkhip09m5HJzT7ILW/EwweSMVA7T3fp9SljLCyMeOc2eHyeNrtiOUQN4AzvOLvcue/13weCzDNPwC "Perl 5 – Try It Online") Tries converting both formats into an epoch time. The `eval` traps the error that would occur for an invalid date. Multiplies the two epoch times together to make sure that one is 0, and checks that they are not the same with substraction. Uses their bitwise `or` to convert back to an actual date, then picks off the day of the week from that. [Answer] ## Excel, 85 Bytes ``` =IF(OR(DAY(A1)>12,MOD(A1-DATE(YEAR(A1),DAY(A1),MONTH(A1)),7)=0),TEXT(A1,"ddd"),"???") ``` Input the date into cell A1 Since Excel will automatically evaluate the date into a valid form for us, we can first check if the `Day` is >12, since this would immediately make the date unambiguous. We then work out if difference between the "dd/mm/yyyy" and "mm/dd/yyyy" versions is a multiple of 7, using `MOD`, since this would mean both Weekdays are the same If either of these conditions are `True`, then the Weekday is unambiguous. [Answer] # [Ruby](https://www.ruby-lang.org/) `-apl`, 102 bytes Takes input as a line of input from STDIN with space as the separator. Outputs `false` if the dates are ambiguous and the days of week don't match. In order to make sure we get a correct date the first time, we sort the first two arguments to ensure the smaller of the two (which is guaranteed to be less than 13) is placed in the month field. We then reverse the arguments when comparing the days of week using `wday` (if it would be a valid date, done by checking `b>12` first), and if they match (or the date was unambiguous) we use `strftime("%a")` to output the day of the week in a human-readable format. `-p` takes each line of input and outputs the contents of `$_` at the end of a program run. `-a` is the autosplit flag, which will split the input on spaces and save into `$F`. `-l` makes the input ignore newlines (they are included by default for Ruby's input function). ``` *x,y=$F.map &:to_i d=Time.gm y,*x.sort! a,b=x $_=(b>12||d.wday==Time.gm(y,b,a).wday)&&d.strftime("%a") ``` [Try it online!](https://tio.run/##VYxfC4IwFEff9yluYqKyxpz9wWA99gl6l41VDLKJLnLgZ28ts4fgPhzO73C7h3Te5wN2PD6SRrSQ7K2pNVL8pJszuTbgcD6Q3nR2gQSWfEBxzVN5KNg4KvJUwvFfmjosscgmmSWJIr3tLjZsabQUUeY9ZUB3wCijiBZAtzNuINyEbP1nq4BlwBKKcg4qCE@@QbAfpBPO9mVaq8299yvR3t4 "Ruby – Try It Online") ]
[Question] [ In 1946 Erdos and Copeland proved that [a certain number](http://en.wikipedia.org/wiki/Copeland%E2%80%93Erd%C5%91s_constant) is a [normal number](http://en.wikipedia.org/wiki/Normal_number), i.e. the digits in its decimal expansion are uniformly distributed. Users will input a sequence of digits and you will find the smallest prime that contains that string in base 10. Example: ``` input -> output "10" -> 101 "03" -> 103 "222" -> 2221 "98765" -> 987659 ``` **Shortest code in bytes** wins. I do know that some languages (mathematica, sage, pari-gp...) come with built-in functions related to primes. **-50 bytes** if your program doesn't rely on such functions. Don't try to cheat on this please, if your language already has a huge advantage don't claim the bonus. ## Edit According to a few comments below, the smallest prime that contains "03" is 3. Does this really make a difference? The only thing I can think of is that maybe numbers are easier to handle than strings. In cases like "03" the preferred output would be 103. However, I don't consider it to be the fundamental part of your program, so you're free to ignore any leading zero if it grants you a lower byte count. [Answer] # Golfscipt, ~~33~~ 32 bytes = -18 score ``` 2{:x,2>{x\%!},!!x`3$?)!|}{)}/;;x ``` Explanation: * `2{...}{)}/` - starting with `2`, while something is true, increment the top of the stack * `;;x` - discard the intermediate values collected by `{}{}/` and the input, then put the last value tested there * `:x,2>` - store the value as `x`, then produce a list from `2` to `x-1` * `{x\%!},!!` - keep those that `x` is divisible by, then coerce to boolean (not empty) * `x`3?)!` - look up the input in the text form of `x` (`-1` if not found), increment, negate. * `|` - or [Answer] ### Haskell program, 97 characters = 47 score ``` main=getLine>>= \i->print$head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x] ``` ### Haskell function, 75 characters = 25 score ``` p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x] ``` the type of `p` is `(Integral a, Show a) => [Char] -> a`. If you supply your own integral type, you can lookup by infix in your own representation of those values. The standard `Integer` uses the expected decimal notation for integers. Not very fast. Quadratic in the value (not size) of the output. ungolfed version: ``` import Data.List leastPrime infix = head $ filter prime' [2..] where prime' x = all (\n-> x`mod`n /= 0) [2..x-1] && i `isInfixOf` show x main = print . leastPrime =<< getLine ``` example: ``` Prelude> let p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x] Prelude> p "0" 101 Prelude> p "00" 1009 Prelude> p "000" -- long pause 10007 ``` [Answer] **Java - 175 characters.** ``` class s{public static void main(String[]a){int i,n=2,p;for(;;){p=1;for(i=3;i<n;i++)if(n%i==0)p=0;if((n==2||p>0)&&(""+n).indexOf(a[0])>=0) {System.out.println(n);break;}n++;}}} ``` [Answer] # Mathematica 58 ``` (n=1;While[StringCases[ToString[p=Prime@n],#]=={},n++];p)& ``` --- **Relative Timings** on my Mac (2.6 GHz i7 with 8 GB memory). Find the smallest prime containing "01". ``` AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["01"]] ``` > > {0.000217, 101} > > > --- Find the smallest prime containing "012345". ``` AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["012345"]] ``` > > {5.021915, 10123457} > > > --- Find the smallest prime containing "0123456". ``` AbsoluteTiming[(n = 1; While[StringCases[ToString[p = Prime@n], #] == {}, n++]; p) &["0123456"]] ``` > > {87.056245, 201234563} > > > [Answer] # [Sage](http://sagemath.org), 72 Runs in the interactive prompt ``` a=raw_input() i=0 p=2 while a not in str(p):i+=1;p=Primes().unrank(i) p ``` `Primes().unrank(i)` gives the `i`th prime number, with the 0th prime being 2. [Answer] ### R, 56chars -50 = 6 ``` k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k ``` Take input as stdin. Increments k until k is a prime (tested by summing the instances for which k mod 2 to k are zeroes, hence FALSE since 0 turned into a logical is FALSE) and contains the string given as input (tested with a simple grep, here grepl since we want a logical as result). Usage: ``` > k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k 1: "03" 2: Read 1 item [1] 103 > k=2;n=scan(,"");while(!grepl(n,k)|sum(!k%%2:k)>1)k=k+1;k 1: "003" 2: Read 1 item [1] 2003 ``` [Answer] # shell oneliner (coreutils): 45chars Not defining a function here... just a oneliner that takes one argument in `$n` and scans the integer range (actually a bit more to make code shorter). The 55 character version: ``` seq 5e9|grep $n|factor|awk '{if(NF==2)print $2}'|head -n1 ``` It's not even too slow. For `n=0123456` it returns `201234563` in `81.715s`. That's impressively fast for a long pipeline with two string processors. Removing two characters (down to 53) and one pipe, we can get it running even faster: ``` seq 5e9|grep $n|factor|awk '{if(NF==2){print $2;exit}}' ``` And finally, some `sed` wizardry to bring it down to **45 characters**, although the printout is ugly: ``` seq 5e9|grep $n|factor|sed -n '/: \w*$/{p;q}' ``` > > n=000 -> 10007: 10007 (user 0.017s) > > > n=012345 -> 10123457: 10123457 (user 7.11s) > > > n=0123456 -> 201234563: 201234563 (user 66.8s) > > > [Answer] # J - 38 char -50 = -12 pts Normally in J, you'd be using the very optimized builtins dedicated to primes, so I'm not going to apologize for any slowness in execution. ``` >:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2 ``` Explained: * `>:@]^:(...)^:_&2` - Starting with 2, increment until `(...)` returns false. * `(+.i.)@]` - Take the GCD of the counter with every integer smaller than it. (We use the convention GCD(X,0) = X.) * `]=*/@` - Take the product of all these numbers, and test for equality to the counter. If the counter is prime, the list was all 1s, except for the GCD with 0; else there will be at least one GCD that is greater than 1, so the product will be greater than the counter. * `>./@(E.":)` - Test if the string representation of the counter (`":`) contains the string (`E.`) at any point. `>./` is the max function, and we use it because `E.` returns a boolean vector with a 1 wherever the substring begins in the main string. * `*:` - Logical NAND the results together. This will be false only if both inputs were true, i.e. if the counter both was prime and contained the substring. Usage: ``` >:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2 '03' 103 >:@]^:(>./@(E.":)*:]=*/@(+.i.)@])^:_&2 '713' 2713 ``` For posterity, here's the version using the prime builtin (30 char long, but no bonus): ``` >:@]^:(>./@(E.":)*:1 p:])^:_&2 ``` `1 p:]` tests the counter for primality, instead of the GCD trick. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes in Brachylog's encoding ``` ṗ≜s ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf96htw6OmxvL/D3dOf9Q5p/j/fzMjAA "Brachylog – Try It Online") Function submission, taking input from the right-hand argument, giving output by mutating the left-hand argument. (This is the opposite of the normal Brachylog convention; see [this meta post](https://codegolf.meta.stackexchange.com/questions/10276/acceptable-ways-of-using-input-and-output-variables-in-brachylog) for more discussion. Swapping the arguments into the more usual order would cost three bytes.) The TIO link has a wrapper which calls the function with the appropriate calling convention and prints the result. ## Explanation ``` ṗ≜s ≜ Find the integer closest to zero ṗ which is prime {implicit: and output it via the left argument} s and which is a substring of the {right argument} ``` Sadly, Brachylog is so appropriate for this problem that according to the rules in the problem, I can't even attempt to go for the bonus (which ironically means that it's incapable of winning). One of the reasons I like Brachylog so much is that programming is a communication between human and computer, and thus a "perfect" language would let you just translate the problem specification into English directly; the ideas via which the problem was stated, and via which the program is written, would be the same. Brachylog can hit this ideal surprisingly often; the question here is "find the smallest prime containing a given substring", and I can literally string together the concepts of "smallest, prime, containing substring" in the correct order and have a working program. As such, Brachylog says much more about the nature of communication than a language in which you had to explicitly specify an algorithm for solving the problem would; sometimes when talking to other humans, we try to explain a problem by explaining the steps you'd take to solve it, but that's rare. So why should our languages be any different? [Answer] # JavaScript 83 bytes = 33 score Golfed: ``` for(s=prompt(n=x=0);!n;x++)for(n=(''+x).match(s)?2:0;n&&n<x;n=x%n?n+1:0);alert(x-1) ``` Ungolfed (a bit): ``` s=prompt() // get the input n = 0 for(x=0;!n;x++) // stop when n is non-zero if ((''+x).match(s)) { // if x matches the pattern, check if x is prime for(n=2;n&&n<x;) n = (x%n == 0) ? 0 : n+1; // if x%n is zero, x is not prime so set n=0 // if n is non-zero here, x is prime and matches the pattern } alert(x-1) ``` [Answer] # Javascript (Node.JS) - 93 bytes = 43 points ``` l:for(i=x=process.argv[2];j=i;i++){while(--j>2)if(!(i%j*(""+i).match(x)))continue l throw i} ``` In extracted form with sensible variable names: ``` outerLoop:for (currentTry=inputNumber=process.argv[2]; primeIterator=currentTry; currentTry++ ) { while (--primeIterator > 2) if(!(currentTry % primeIterator * (""+currentTry).match(inputNumber))) continue outerLoop; throw i } ``` [Answer] # Rust 0.9 136 bytes = 86 points ``` fn main(){ let mut n:u32=2; while n.to_str().find_str(std::os::args()[1])==None || range(2,n).find(|&x|n%x==0)!=None { n=n+1; } print!("{}",n); } ``` Very explicit despite for compactness. Too much space spent on the string find. :( Here the version without whitespace (136 char) ``` fn main(){let mut n:u32=2;while n.to_str().find_str(std::os::args()[1])==None||range(2,n).find(|&x|n%x==0)!=None{n=n+1;}print!("{}",n);} ``` [Answer] # Japt, 10 bytes ``` _j *ZsøU}a ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=X2ogKlpz+FV9YQ==&input=Ijgi) [Answer] # [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 37 bytes ``` {s:s&{s,p:s in"".p}from primes|first} ``` [Try it online!](https://tio.run/##FcXNCgIhFAbQfU/xcRelYDIZ/QnTu4iNIDSTeIUI89mt2ZxT4uPTgx17ZcvbyipZRlyIdGohv2akHOeJvyFmLq0XDzvCCzoMpEDDcdUYs3a7Xs4nkpvZJVHhYPHOsUzPRexIO/2HsL@DdBBOSjSF4mX/AQ "Tidy – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 - 50 = -14 points ``` {$^a;first {/$a/&&$_%%one ^$_},2..*} ``` [Try it online!](https://tio.run/##RYtLC4JAFEb38ysuwyiaOr7IEklq0a5ltPGFixEEU/HaIsTfPk1FdFfncL8ziqmL5P0JegMHkAsr66RpJ5xhcVnt6jqrNG3oBZSsWu2A880qHyjgKnBOCFHhcVaIKja6thdopinHsWtnw83Ryp08zdE11XTs6h6s71ppM0y/dCEALUJj8Mwr@Pl2upg2z/yCrJL6HgV1Tgq@5xPqhX8NCQ2CgH5VkXrH@120pW//UPwC "Perl 6 – Try It Online") Considering `$_%%one ^$_` is the only 2 bytes ~~smaller~~ larger than `.is-prime`, I think it's worth it for the bonus. This times out for the last test case. ### Explanation: ``` { } # Anonymous code block $^a; # Assign input to $a first ,2..* # Find the first number { } # Which /$a/ # Contains the input && # And $_%%one ^$_ # Is prime ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~80~~ 79 bytes - 50 = ~~30~~ 29 score -1 byte thanks to @ASCII-only's creative use of `%s` instead of `str` ~~Test case "98765" has not been confirmed yet because of how long it is taking to test~~ Confirmed for test case "98765" after a couple of hours, but with a similar approach that utilizes short-circuit evaluation to avoid some primality testing it works much faster. Alternatively, this can be ~2x as fast if we know that "2" is not an input (we can avoid checking even numbers for primality) by setting `i=3` initially and `i+=2` in the loop, at no extra byte cost. ``` def f(x): i=2 while(x in"%s"%i)*all(i%j for j in range(2,i))-1:i+=1 return i ``` [Try it online!](https://tio.run/##PY7LCsIwEEXX5isuKYXEBzQpPlroB7hy405cFE3tSE0lTVHBf6@poKuZcwbm3vvL161Nh@FsKlTiKXMGKjTDo6bGiCfI8rjjMclp2TSC4iuq1uEaPFxpL0boOUm5UDnNCsXgjO@dBQ3edP5UdqZDgQObcJXwORBBJSpQkv4oDaS1DhghzHCMwLPNerX8qu@W4Q1Pt/Cr7T1ai/12x46MjU3GnLHMPy9nk7sj60UlRifl8AE "Python 3 – Try It Online") Explanation of the `while` condition (`(x in"%s"%i)*all(i%j for j in range(2,i))-1`): `(x in"%s"%i)`: `True`/`1` if the current counter contains the desired sequence of numbers in it; `False`/`0` otherwise. `all(i%j for j in range(2,i))`: `True`/`1` if the current counter always has a remainder when divided by any integer from 2 (inclusive) to itself (exclusive), i.e. is prime; `False`/`0` otherwise. The `*` multiplies the two conditions together, and acts as an `and` operator - the product is `True`/`1` if and only if both conditions are `True`/`1`. The `-1` acts as a `not` operator: `False`/`0` - 1 results in `-1`, which is considered true, whereas `True`/`1` - 1 results in `0`, which is considered false. Thus, the loop continues while the number either does not contain the desired sequence of numbers or is not prime. Replace the `*` with `and` and add parentheses around everything but the `-1` for a much faster, equivalent solution (that is slightly longer). A **76 byte - 50 = 26 score** solution in Python 2 given by @ASCII-only (utilizes ```` instead of `str()`, ``` def f(x): i=2 while(x in`i`)*all(i%j for j in range(2,i))-1:i+=1 return i ``` [Try it online!](https://tio.run/##PY7BSsNAEIbP3af4SRB3NYVki60N5AE8efEmQtN2Yqaku2Ez1QZ897gp6Gnm@waGrx@l9c4u@7Efp@lIDRp9NaUCV1bhu@WO9BXsdrwzD3XXab47ofEBpygRavdJ2mZszLIo@bEqFALJJTjwJDTIoR5oQIV3tUiKPMmAFEVeRMpXf7SKZK2NmCLOeEyRbJ8366ebum1b/ED4HH/5i8A7vL28ZmjrL3L3gj2RQ73vCOJx8K7hcAYLRhL1odScO8fMxf9RpVr0gZ3oRs/OmOkX "Python 2 (PyPy) – Try It Online") [Answer] # JavaScript, 65 - 50 = 15 points ``` x=>(f=y=>(''+y).match(x)&&(p=n=>--n<2||y%n&&p(n))(y)?y:f(y+1))(x) ``` [Try it online!](https://tio.run/##bcvRCoIwFMbx@96jeQ4yyXlVNnsUGWuWpdtwEjvgu6/dht188P/B91IfFfQy@pUHP97NMjv7NpR6maLsYJCUtyhKwmpWq35CRMbASys7zu1VbBsdLWMeLCIQ3ugyAJV1johJOxvcZKrJPaCHBrE9/FJ92psQYo/Nn/M5U/oC "JavaScript (SpiderMonkey) – Try It Online") ]
[Question] [ This challenge is an extension of '[Golf a mutual quine](https://codegolf.stackexchange.com/questions/2582/golf-a-mutual-quine)'. Using three languages of your choice, create a third order [Ouroboros](http://en.wikipedia.org/wiki/Ouroboros) program. That is, in language A, write a program pA which outputs program pB in language B. Program pB should output program pC in language C, which in turn outputs the original program pA in language A. No two languages in A, B, and C can be the same or subsets or supersets of each other. **None of pA, pB or pC may be identical.** For example, a Haskell program outputs a Perl program which outputs a java program which outputs the original Haskell program would be valid. On the other hand, a C# 4 program which outputs a C# 3 program which outputs a C# 2 program is invalid. Even a Perl -> Ruby -> Bash combination would be invalid if, say, the Perl program and the Ruby program were identical. This is code golf, so the shortest program pA wins. [Answer] ## Python -> Perl -> Ruby, 48 characters Adaption of my [previous answer](https://codegolf.stackexchange.com/a/2590/84). Running ``` s='print q<puts %%q{s=%r;print s%%s}>';print s%s ``` with Python generates this Perl snippet ``` print q<puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}> ``` which generates the following Ruby code ``` puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s} ``` which then prints the original Python snippet: ``` diff -s <(ruby <(perl <(python thirdorderquine.py))) thirdorderquine.py Files /dev/fd/63 and thirdorderquine.py are identical ``` [Answer] ## Perl -> PHP -> HTML + JavaScript, 105 chars I wanted to make the chain of languages somehow meaningful, so I figured I'd write a PHP script that generates a HTML page containing JavaScript. For the third language I chose Perl, just because I like Perl. :) Some might consider this *four* languages, but I don't really count HTML as separate from JavaScript here — it's a markup language, not a programming language. Anyway, here are the three versions: Perl (105 chars): ``` printf+(q(<script>alert(unescape("<?=urlencode(<<<E%sprintf+(q(%s),$/)x2,$/%sE%s)?>"))</script>),$/)x2,$/ ``` PHP (165 chars): ``` <script>alert(unescape("<?=urlencode(<<<E printf+(q(<script>alert(unescape("<?=urlencode(<<<E%sprintf+(q(%s),$/)x2,$/%sE%s)?>"))</script>),$/)x2,$/ E )?>"))</script> ``` HTML + JavaScript (235 chars): ``` <script>alert(unescape("printf%2B%28q%28%3Cscript%3Ealert%28unescape%28%22%3C%3F%3Durlencode%28%3C%3C%3CE%25sprintf%2B%28q%28%25s%29%2C%24%2F%29x2%2C%24%2F%25sE%25s%29%3F%3E%22%29%29%3C%2Fscript%3E%29%2C%24%2F%29x2%2C%24%2F"))</script> ``` (Ps. Yes, I know I could've made the PHP step an almost-noop, e.g. just generating HTML + JS code in Perl and appending `<?php` to it, but that felt too much like cheating. In this solution, the code is actually processed in PHP instead of just being copied verbatim.) [Answer] # Underload → sed → Perl, 23 bytes Can probably get this down lower with better choices of languages. Arguably noncompeting because the rule "sed programs can take an empty line as argument" postdates the contest. The Underload program: ``` ((iprint+q)Sa(:^)*aS):^ ``` generates the sed program: ``` iprint+q(((iprint+q)Sa(:^)*aS):^) ``` which generates the Perl program: ``` print+q(((print+q)Sa(:^)*aS):^) ``` (note: there are two trailing newlines here), which generates the original Underload program again: ``` ((iprint+q)Sa(:^)*aS):^ ``` The main aim here is to find languages in which strings are nestable (i.e. you can just quote a string by enclosing it in delimiters, rather than having to escape it); Underload has `()`, Perl has `q()`, and in sed a string continues until whitespace (which is implicitly nestable if there's no whitespace in the program). There's probably an esolang or golfing language out there with a "print the rest of the current line, not followed by newlines" instruction, which would be ideal here, but I haven't spent all that much time looking for one; you could save 8 bytes minus the length of the instruction in that case. (Jelly *almost* works but its `“` instruction doesn't quote itself. Besides, it postdates the challenge.) You can reduce this to **22 bytes** like this: ``` ((csay+q)Sa(:^)*aS):^ ``` (with one trailing newline, like a regular text file, rather than the zero you normally get in golf). However, this requires an Underload interpreter that's OK with treating newline as a no-op. Try It Online!'s does, but I think it postdates the challenge. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 6 years ago. [Improve this question](/posts/2259/edit) Now is the time to show off your abilities to write bad code. I am trying out a new sort of programming puzzle, most similar, I think, to the underhanded C contest. The main difference is that this is not nearly as nefarious: it's just some good clean fun. The goal of the puzzle is to pack as many bugs as you can into a program. The winner of this contest is the one who writes the program with the most bugs per character. To avoid a huge thread of comments asking for clarification, I should define right now what I consider to be qualifying bugs. First, **a bug is not an error**. If it is a problem that can be detected by the interpreter as an error (e.g. mismatched delimeters, badly-formed syntax, acessing a property of a null object, etc.) or if it prevents the program from executing or continuing, it is not a bug. Otherwise, you could type in four characters and the interpreter could list eight syntax errors and you could claim a bug-character ratio of 2. Second, **the bug must not be obviously wrong** and **a bug is not an easter egg**. This is certainly a subjective criterion, but I think essential to this sort of contest. This means that you cannot have conditional code that specifically mangles the code in obvious ways. (Read: use a turing pit language, because nobody will know the difference). Third, **the bug must be plausible**. This is subjective, like the one above, but the bug must look like it could have been written by a less-than-meticulous or perhaps ignorant person, or someone who just made a mistake. This includes, for example, off-by-one errors or syntax that is valid and looks correct but causes undesired behavior (say, using square brackets instead of parentheses). The bug can cause any sort of undesired behavior to the program, including, but certainly not limited to, undesired output for some exceptional cases, have different behavior based on something that is seemingly unrelated (e.g. output displays differently depending on whether the current time ends with an odd or even number of seconds), memory leaks, loss of data, and so on. Example Problem: Make a program that displays all of the ASCII characters in ascending order of their numerical value. Example answer: Brainf\*\*\*, 5 chars, 1 bug, 0.2 bug-char ratio ``` +[+.] ``` Bug: does not display the ASCII character for 1. Could be fixed by changing to `.+[.+]`. Ok, I think you should mostly have gotten it by now, here is your puzzle: ## Decode a Caesar Cipher and Sort the Words Alphabetically A caesar cipher is created by taking a series of letters and shifting them *n* letters over in the alphabet. If it goes all the way to the beginning or end of the alphabet, A comes after Z, and Z comes before A. For example: ``` Mannequin Nboofrvjo //Shifted over 1 or -25 Wkxxoaesx //Shifted over 10 -16 Ftggxjnbg //Shifted over -7 or 19 ``` You will be given two inputs (you can get input however is most convenient for you, within reason). The first input is the words, and the second input is the value it is shifted over. Your task is to output the decoded words, and then output the decoded words after they have been sorted alphabetically. Example (no offense to bad boys, it's just an example): > > First input: gtdx wjbfwiji. ljy Gfi hfssty > > > Second input: 5 > > > First output: boys rewarded. get Bad cannot > > > Second output: Bad boys cannot get rewarded. > > > Good luck! [Answer] ## Ruby, 136 characters, 7 bugs, ratio = 0.051 ``` o=gets[/\d+/].to_i $,='\s' a=gets.split(/ /).map{|w|w.gsub(/[^.,:;?!]/){(97+($&.ord-97-o)%26).chr}} print a.join,a.sort_by{|a|a[0]}.join ``` 1. `[/\d+/]`: negative numbers have their sign removed (a seeming attempt at input validation) 2. `'\s'`: backlash escapes are only interpreted within double-quoted strings, so this won't generate a space but rather a literal `\s` 3. `split(/ /)`: unlike a plain `split`, this won't split on newlines (so the last word will keep the newline) 4. `/[^.,:;?!]/`: this regex excludes punctation, but not uppercase characters, digits or underscores, and, most critically, newlines 5. `97`: anything other than punctation or lowercase letters will get garbled 6. `sort_by{|a|a[0]}`: apparently the programmer didn't know about `sort`, and instead used this ridiculous method, which doesn't sort words starting with the same letter 7. `print`: unlike `puts`, doesn't print a newline between each argument (so the strings come out glued together) [Answer] I'm not going to accept my own answer, but I thought I would show you the ultimate buggy sorting decipherer. The great thing about it is I didn't even plan most of the bugs. ## Brainf\*\*\*: 483 chars, 11 bugs ``` ,------------------------------------------------[>,---------]<[<]>[>[ ->]<[<]>-]>[+++++++++.>]<[---------------------------<]>>[[>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]>]>[[>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<-]>]>[[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<-]>]>[[>>>>>>>>>>>+<<<<<<<<<<<-]>]++++++++++.>[[>>>>>> >>>>>>>>>>+<<<<<<<<<<<<<<<<-]>]>[>+++++++++++++++++++++++++++.] ``` Input: ``` 5 gtdx wjbfwiji. ljy Gfi hfssty ``` Output: ``` bo_sre]arded)getBadcannot adbo_scannotgetre]arded) ``` **List of bugs**: Input/Display bugs: 1. Nonpositive numbers or numbers that are more than one digit break the program. 2. The decipherer does not make Z come before A. It just subtracts the ASCII character value. 3. Spaces appear as the ASCII ESC (27) character. 4. If the input is not terminated by a tab, the program does not continue after the input instructions. 5. The program has to be manually terminated. It will continually display the ESC character until stopped. 6. The program will break if the input file is not ASCII encoded. 7. The program does not display the first character of the sorted output. Sorting bugs: I implemented the sorting extremely naively. 5. The program breaks when the number of words does not equal 5. 6. The program breaks if the number of bytes of input exceeds 60. 7. The program can only sort correctly if the alphabetical order is identical to the example input. 8. The program adds extra spaces if any of the words are smaller than the example input and overwrites characters if any of the words are longer. I have a bug-char ratio of **0.0228**. Admittedly, [Joey beat me](https://codegolf.stackexchange.com/questions/2259/write-buggy-code/2269#2269), but I take pride in the fact I only used 8 different characters in my program, and my bugs are much more critical. [Answer] ## C - 224 characters, 2 bugs, 7 cases of undefined behavior **Edit:** My assessment here is incorrect. Overflowing an unsigned integer is, in fact, [well-defined in C](https://stackoverflow.com/questions/2760502/question-about-c-behaviour-for-unsigned-integer-underflow/2760612#2760612). Moreover, comparison between signed and unsigned is well-defined too, but the compiler warns because the way it's defined may not be what you think. ``` m(char**a,char**b){return strcmp(*a,*b);}main(int c,char*v[]){unsigned i,j ,o;o=atoi(v[1])+19;for(i=2;i<c;i++)for(j=0;j<=strlen(v[i])-1;j++)v[i][j]=( tolower(v[i][j])-o)%26+97;qsort(v,c,sizeof(v),m);for(i=2;i<c;puts(v[i++]));} ``` ### Usage: ``` $ ./a.out 5 gtdx wjbfwiji ljy Gfi hfssty bad boys cannot get rewarded ``` ### Breakdown: ``` m(char**a,char**b){return strcmp(*a,*b);} main(int c,char*v[]) { unsigned i,j,o; // Undefined behavior if o is assigned negative value. o=atoi(v[1])+19; // Comparison between signed and unsigned integer. for(i=2;i<c;i++) // * Bug: if strlen(v[i]) is zero, subtraction will overflow // unsigned value, and loop will have extra iterations. // * strlen is implicitly declared. // Undefined behavior if sizeof(void*) != sizeof(int) for(j=0;j<=strlen(v[i])-1;j++) // tolower expects either an unsigned char casted to an int, or EOF. // Thus, undefined behavior if v[i][j] is non-ASCII. v[i][j]=(tolower(v[i][j])-o)%26+97; // * Bug: Program name and offset are included in the sort. // "./a.out" and "5" both happen to be less than lowercase strings. // * qsort is implicitly declared. // Undefined behavior if sizeof(void*) != sizeof(int) qsort(v,c,sizeof(v),m); // Comparison between signed and unsigned integer. for(i=2;i<c;puts(v[i++])); } ``` [Answer] ## JavaScript: 403 characters, 8 bugs, ratio = 0.0199 Although not as bad as C, JavaScript does have design flaws that can lead to bugs, at least when used by a novice ([demo with all bugs unfixed](http://fiddle.jshell.net/EKwTZ/)). ``` function W(v){D.write("<input value="+v+">");return D.body.lastChild}function R(J){I=S.indexOf(C=i.value[J]);H=s.value;if(!I){o.value+=C}if(H>0){o.value+=S[I+H]}if(H<0){o.value+=S[I-26-H]}p.value=o.value.split(" ").sort().join(" ");setTimeout("R("+(J+1)+")",99)}D=document;S="ZYXWVUTSRQPONMLKJIHGFEDCBA";S+=S;S+=S.toLowerCase();i=W("input");s=W("shift");W("run type=button onclick=R(0)");o=W("");p=W("") ``` --- ``` function W(v) { D.write('<input value=' + v + '>'); return D.body.lastChild; } function R(J) { I = S.indexOf(C = i.value[J]); H = s.value; if(!I) o.value += C; if(H > 0) o.value += S[I + H]; if(H < 0) o.value += S[I - 26 - H]; p.value = o.value.split(' ').sort().join(' '); setTimeout('R(' + (J + 1) + ')', 99); } D = document; S = 'ZYXWVUTSRQPONMLKJIHGFEDCBA'; S += S; S += S.toLowerCase(); i = W('input'); s = W('shift'); W('run type=button onclick=R(0)'); o = W(''); p = W(''); ``` --- 1. `I + H` is string concatenation, not addition: `undefinedundefinedundefined...` 2. `!I` is not the correct way to check the return value of `.indexOf()`, which returns -1 for a non-match: `boysVrewardedVV...` 3. Missing `else` keywords: `boys Vrewarded.V Vget...` 4. Will not stop at end of input: `...cannotundefinedundefined...` 5. Won't correctly handle zero shift (e.g. just trying to use the program to sort words) 6. Will it handle a negative shift? Not correctly. 7. Double-clicking the button causes a second timeout to start, leading to incorrect output ([demo with most of the previous bugs fixed](http://fiddle.jshell.net/QkfY3/)): `boys rebwoayrsd erde.w agredte dB.a dg ecta nBnaodt cannot`. 8. Output text boxes must be empty when the button is clicked Also note that this will not work on older versions of IE because it uses an extension to ECMAScript 3 that was only standardized in ES5. [Answer] **Python3 184 characters, 4 bugs. Bug ratio 0,0217** ``` import string d=input() y=int(input()) print("".join(sorted(d.translate(str.maketrans("".join([chr(x)for x in range(96,123)]),"".join([chr(96+(x+y)%26)for x in range(26)]))).split()))) ``` degolfed: ``` data = input() #string to convert y = int(input()) #value to shift print("".join( sorted( data.translate( str.maketrans( "".join([chr(x) for x in range(96,123)]), "".join([chr(96+(x+y)%26) for x in range(26)])) ).split() ))) ``` Example input: gtdx wjbfwiji. ljy Gfi hfssty Example input: -5 Example output: G`canxrb`mmnsfdsqdv`qcdc. Known bugs: 1. Does not convert upper-case characters 2. Includes ` and converts to/from it. 3. Does not convert non-ascii characters (åäö) 4. Does not print spaces. 5. Can handle, but ignores, punctuation -- I choose not to count this, but if I do my ratio goes to 0.027) I'm not very good at coming up with bugs deliberately. ]
[Question] [ *inspired by [thejonymyster's idea](https://chat.stackexchange.com/transcript/message/61968948#61968948)* ## Rules This challenge is about finding languages that are very suitable for one task but quite the opposite in the other. The two tasks share a theme, but Task 1 is designed to be number-oriented while 2 is string-oriented. You can participate in **three categories**: * **Numbers**: Choose a language, and solve both tasks in it. The language must be specified down to a specific *implementation, version, and flags*, and these *cannot be changed once posted*. Each solution is scored by the code size in bytes; your answer's score is \${T\_2}/{T\_1}\$ where \$T\_1\$ is the score for Task 1 and \$T\_2\$ is for Task 2. Higher score is better. * **Strings**: Same as Numbers, except for scoring. Your answer's score is \${T\_1}/{T\_2}\$, i.e. the reciprocal of that of Numbers. Higher score is better. * **Robbers**: Choose an answer X for Numbers or Strings. Come up with a better solution for the worse task for the given language, and post it as a comment. By doing this, you gain (effectively steal) X's score lost. Higher total score is better. + Example: Let's assume a Numbers post with 4B in task 1 and 9B in task 2. If you golf task 2 down to 7B, the answer's score is reduced from 9/4 to 7/4, and you get 2/4 = 0.5 points. You will naturally participate in Numbers if your solution to Task 2 is longer than Task 1, and in Strings otherwise. However, you may *not* switch the category of an answer already posted, even if the golfing attempts result in the score less than 1. Everyone is free to give golfing suggestions to existing answers, but the only ones that *reduce* the answer's score count as robbers. Once the challenge is inactive for **1 week**, the winners of each category will be decided as follows: * **Numbers** and **Strings**: the highest scoring answer in each category wins. * **Robbers**: the participant with the highest total stolen score wins. ## Task 1: Number thickness Given a positive integer \$n\$ and integer base \$b \ge 2\$, compute the thickness of \$n\$ in base \$b\$. For base 2, the values are [A274036](http://oeis.org/A274036). The thickness is computed as follows: if the inputs are \$n = 22\$ and \$b = 2\$, * Convert \$n\$ to base-\$b\$ digits: \$10110\_2\$ * Treat it as a polynomial: \$B\_n(x) = 1x^4 + 0x^3 + 1x^2 + 1x^1 + 0x^0\$ * Compute its square: \$B\_n(x)^2 = x^8 + 2x^6 + 2x^5 + x^4 + 2x^3 + x^2\$ * Take the highest coefficient: 2. Therefore, the thickness of 22 in base 2 is 2. **Test cases** ``` 22, 2 -> 2 8, 2 -> 1 15, 2 -> 4 100, 3 -> 6 12345, 10 -> 46 ``` ## Task 2: String thickness Given a nonempty string \$s\$ consisting of uppercase letters, compute the string thickness of \$s\$. It is calculated as follows: if the input is `ABAAB`, * For each length-2 substring of \$s\$, replace all non-overlapping appearances of it with \$s\$. + `AB -> ABAAB`: `ABAABAABAAB` + `BA -> ABAAB`: `AABAABAABAABAABAABAB` + `AA -> ABAAB`: `ABAABBABAABBABAABBABAABBABAABBABAABBAB` + `AB -> ABAAB`: `ABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAAB` * Count how many times \$s\$ appears as non-overlapping substrings of the result. ``` ABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAABAABAABBABAAB 11111 22222 33333 44444 55555 66666 77777 88888 99999 aaaaa bbbbb ccccc ddddd ``` The string thickness of `ABAAB` is 13. For this task, taking the input string as a list of chars or a list of codepoints is allowed. **Test cases** ``` ABAAB -> 13 AB -> 1 XXYY -> 2 ARRAY -> 3 NUMBER -> 5 PQRRQP -> 6 XYXZYX -> 21 ``` ## Example submission ``` # Numbers, Python 3.10, score 109 / 54 = 2.0185 ## Task 1, 54 bytes <insert code here><insert code here><insert code here> ## Task 2, 109 bytes <insert code here><insert code here><insert code here> <insert code here><insert code here><insert code here> ``` [Answer] # Strings, [Python 3.8.10](https://www.python.org/), score 83 / 65 = 1.2769 ## Task 1, 83 bytes *-7 bytes from @xnor **(+7/65)*** ``` lambda n,b:max(sum(n//b**i%b*(n*b**i//b**k%b)for i in range(n))for k in range(n+1)) ``` [Attempt this Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwWI_25ilpSVpuhY3g3MSc5NSEhXydJKschMrNIpLczXy9PWTtLQyVZO0NPK0QCwwP1s1STMtv0ghUyEzT6EoMS89VSNPEyySjSSibaipCTF6fUFRZl6Jhp-GkZGOghFMdMECCA0A) ## Task 2, 65 bytes *-1 byte from @Steffan* ``` s=t=p=input() for c in s:t=t.replace(p+c,s);p=c print(t.count(s)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3HYttS2wLbDPzCkpLNDS50vKLFJIVMvMUiq1KbEv0ilILchKTUzUKtJN1ijWtC2yTuQqKMvNKNEr0kvNLgXSxpibEoAUwytHJ0dEJwgEA) [Answer] # Numbers, [Factor](https://factorcode.org) 0.99 Build #1889 + `math.extras math.polynomials`, score 66 / 53 = 1.2453 ## Task 1, 53 bytes ``` [ '[ [ _ /mod , ] until-zero ] f make 2 p^ supremum ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JYw9CsJAFIT7nGI6GxNhQRA9gNjYiDYhyhLfYsj-xN23YLyKTRpzp9zG4DYzzAfzfUYla3Z-mC7n0-G436Ilb0lD-R5G8uMfRed0b51ppA4zaClRerGXAYGekWxNAZ0n5r7zjWXsskwIiG9klW-mdYlFiRI3rIy7Y4kK0XKj8zd5Nw-VtALdFSHOHhMNqnQea6k1ijSGIfUP) ## Task 2, 66 bytes ``` [| s | s s s 2 clump [ <regexp> s re-replace ] each count-subseq ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU6xCsIwFNz9iqN7OziJitAu4uIiupQOMbzWYkziSwIV_BOXLvaf-je2ZJDjeHc33LvPUAvpDffj5Xw6HPdrKCOFcmjYBNvqBkwNdRaWyfuX5VZ7OHoG0pLcX2XUeRYOd2JNCpvFIsmLPC-Sb_B1uhqL8g2HmTOWkCo8LEpsY_1uCplSJquEJFQgIW-QJmifunCd3qCKTcO0TiGLpu_j_QE) I didn't expect Factor to score particularly well here since it's pretty consistent in most areas. Now if it were iterative vs. recursive, you might see Factor reigning supreme... P.S. I was able to knock 12 bytes off one of the answers after posting, so FML. [Answer] # Numbers, [PARI/GP](https://pari.math.u-bordeaux.fr) 2.13.4, score 77 / 37 = 2.0811 ## Task 1, 37 bytes ``` n->b->vecmax(Vec(Pol(digits(n,b))^2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN1XzdO2SdO3KUpNzEys0wlKTNQLyczRSMtMzS4o18nSSNDXjjDQ1IYrXFxRl5pVopGkYGWlqwEUXLIDQAA) PARI/GP has a built-in polynomial type. ## Task 2, 77 bytes ``` s->u=strjoin;v=strsplit;for(i=2,#t=s,t=u(v(t,u(Vec(s)[i-1..i])),s));#v(t,s)-1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHidAXbpaUlaboWN32Lde1KbYtLirLyM_Osy0Cs4oKczBLrtPwijUxbIx3lEttinRLbUo0yjRKdUo2w1GSNYs3oTF1DPb3MWE1NnWJNTWtlkFyxpq4hxNCNBUWZeSUa6RpKjk6Ojk5KmpoQ8QULIDQA) PARI/GP has only two string-manipulation built-ins: `strjoin` and `strsplit`. We can do string search-and-replace by `strjoin(strsplit(s,a),b)`. [Answer] # Strings, [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 15/9 = 1.666... ## Task 1, 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` вDδ*εā_«NFÁ]øOà ``` [Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//9CyRM60Ks61xIFfwqtORsOBXcO4T8Og//8yCjIy) ## Task 2, 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü2I.:I¡g< ``` [Try it online.](https://tio.run/##yy9OTMpM/f//8B4jTz0rz0ML023@/3d0cnR0AgA) 05AB1E lacks any polynomial builtins, and unfortunately also a matrix-diagonals builtin. So all things considering, the Numbers Task 1 isn't too long, if I say so myself. No doubt someone still finds something to golf, since that's usually the case with my answers. ;) [Answer] # Numbers, [Mathematica](https://www.wolfram.com/mathematica/) 13.1.0, score ~~1.26315~~ 1.47826 +0.2151 score thanks to att! ## Task 1, ~~57~~ 46 bytes ``` Max@ListConvolve[#,#,{1,-1},0]&@*IntegerDigits ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexwsEns7jEOT@vLD@nLDVaWUdZp9pQR9ewVscgVs1ByzOvJDU9tcglMz2zpPh/QFFmXomCg0JatJGRjlHsfwA "Wolfram Language (Mathematica) – Try It Online") -11 bytes thanks to att ## Task 2, ~~72~~ 68 bytes ``` Fold[StringReplace,x=#,#->x&/@StringPartition[x,2,1]]~StringCount~x& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyU6uKQoMy89KLUgJzE5VafCVllHWdeuQk3fASIRkFhUklmSmZ8XXaFjpGMYG1sHEXfOL80rqatQ@x8A5JUoOCikAbGSo5Ojo5PSfwA "Wolfram Language (Mathematica) – Try It Online") -4 bytes thanks to att [Answer] # Numbers, [Vyxal](https://github.com/Vyxal/Vyxal) 2.17.1, score 9/8 = 1.125 Vyxal doesn't do very well for this challenge. ## Task 1, 8 bytes ``` τ:v*ÞḋṠG ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLPhDp2KsOe4biL4bmgRyIsIiIsIjJcbjIyIl0=) ## Task 2, 9 bytes ``` 2l(n?V)$O ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybChuP1YpJE8iLCIiLCJBQkFBQiJd) [Answer] # Numbers, [Jelly](https://github.com/DennisMitchell/jelly), score 13/5 = 2.6 ## Task 1, 5 bytes ``` bæc`Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8/z/p8LLkhIc7G/7//29k9N8IAA "Jelly – Try It Online") ## Task 2, 13 bytes ``` ṡ2œṣj³ɗƒœṣ¹L’ ``` [Try it online!](https://tio.run/##y0rNyan8///hzoVGRyc/3Lk469Dmk9OPTQKzD@30edQw8////45Ojo5OAA "Jelly – Try It Online") It's common knowledge that Jelly is not good with strings, but this is exceptionally awkward for its builtin set with some chaining issues on top. Maybe I'll get robbed? [Answer] # Numbers, J 806, Score 48 / 23 = 2.08696 ## Task 1, 23 bytes ``` [:>./[:+//.@:(*/)~#.inv ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PSjrbT19fUcrDS09DXrlPUy88r@a3JxpSZn5CsYKaQpGBn9BwA "J – Try It Online") ## Task 2, 48 bytes ``` #%~;&''(]-&#rplc~)[:;<rplc~&.>/@|.@,<<"1@,.~2<\] ``` [Try it online!](https://tio.run/##fYtNC4JAFEX3/oqn0jwHZp4fQeA4imPUSlq0TSGQJCIoWtf89UlcRBC0uHA599yLy32V9itf5YheQDhCqQBBQAJqiiRY79utCxe2YIhRL1n4uF8Hyw@q0HNjVMX1k2qhdZDWgmymu95xb9cQ/JdmRX/RD5x@UVJRJm3cJQKNQbYhfoyKWCjNX7Pzs3un4XyDdAkljICmMaZB9wY "J – Try It Online") Strings might have an open window or two for an enterprising robber... [Answer] # Numbers, [Charcoal](https://github.com/somebody1234/Charcoal), score 23 / 19 = 1.21 ## Task 1, 19 bytes ``` NθNηI⌈↨X↨↨θη×θη²×θη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaDgnFpdo@CZWZOaW5mo4JRanagTklwNVgJlgolBHIUNTRyEkMze1GMIB8ozQRIDA@v9/IyMuo/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @dingledooper's Python answer but using Charcoal's base conversion builtins to simplify the process. ## Task 2, 23 bytes ``` SηFEΦθκ⁺§θκι≔⪫⪪ηιθηI№ηθ ``` [Try it online!](https://tio.run/##NYxNCsIwEIX3niLLCcQTdJUKQgWh0BOEWpvBYfI3EW8fU8HFe4v38b7Vu7wGR61NHKsskpF38Ho4PUNWcHcRrkiyZUhGvbRRM9UCViZ@bJ//hlprZUvBneEWkGGJhAL@IEalnkM4d7XAxZVeofKPp/4cWrOjtWM7v@kL "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal struggles to extract overlapping substrings, and like PARI/GP, has to use both Split and Join to perform string replacement. It does at least have a convenient way to refer to the same string input twice. [Answer] # Strings, [Go](https://go.dev) 1.19.1, score ~~177 / 162 = 1.09259~~ 176 / 121 = 1.41322 ## Task 1: ~~177~~ 176 bytes ``` func n(n,b int)int{c,m:=[]int{},-1 for n>0{c=append(c,n%b) n/=b} s:=make([]int,len(c)*2) for i,x:=range c{for j,y:=range c{s[i+j]+=x*y}} for _,n:=range s{if m<n{m=n}} return m} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY9NasMwEIXX0SmGQIOUKP3xqpgqZ8g-hCCrUlASjY0sQ4LQSboxhe5zg54jt6nspnQxzPDeG_jex-e-7r8bqY5yr8FJi4RY19Q-ACWTqXFhSthXF8zy9XY1HSpAirwCi4HliYq7Umy2w5n48oWY2gOunqMSsmk0vlPF8aFiBJ9ElUhbCiePmo4P_KSRKjYv2Phl-bkUXmLGUHEQDvzyL7QbuzhsF-I8v6Q05ncc_-w2WgPuDaMTmF2vQ-cRXLpzz0buoRtlEMkkl3pc-0xwyl1oUXAoGCP3dN__7h8) * -1 by @Steffan ## Task 2: ~~162~~ 121 bytes ``` import."strings" func s(s string)int{p,t:=s,s for _,c:=range s{q:=string(c);t=ReplaceAll(t,p+q,s);p=q} return Count(t,s)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BCsIwEEXX5hQhqwRj11LJovUC4gUkhLYU2yTNTBZSehI3RfAS3sTbGNuuBt58_n_PV-Pmj9fmrpuK9rq1hLS9dwEpq3tk74j14fh9rCxjgKG1DTBSR2socKArEa3F0UvMFUggtQv0Jk2ugrapFsYh8SXHjTihula-06Yquo6j9PtBgjh5NUwkVBiDpWcXLaYXiGkT4Mve348LOpJdcssuqRA7y4GzoiyKkglBtvw8r_cH) * -41 by @Steffan [Answer] # Numbers, [Pyxplot](http://pyxplot.org.uk) 0.8.4, score 188/99 = 1.8990 ## Task 1, 99 bytes ``` su N(n,b){m=0 fo j=0ton{s=0 fo i=0ton{f='floor(n/b*' s=s+@f*i)%b*@f*j*b**i)%b } m=max(m,s) } pr m } ``` The algorithm is the same as in @dingledooper's [answer](https://codegolf.stackexchange.com/a/252063/92901). ## Task 2, 188 bytes ``` su S(s){t=s L='strlen' r='strrange' fo i=2to@L(s){j=0 c=0 while j<@L(t){if strcmp(@r(t,j,j+2),@r(s,i-2,i)){j=j+1 }else{t='%s%s%s'%(@r(t,0,j),s,@r(t,j+2,@L(t)));j=j+@L(s);c=c+1 } } } pr c } ``` Pyxplot has a search-and-replace operator (`=~`) but it only works with literal text and so is not of use here. There are only five string manipulation functions (two of which perform case conversions). The three used here are `strcmp`, which performs lexicographical comparison; `strlen`, which returns the length; and `strrange`, which returns a slice. --- There is no online interpreter. To install Pyxplot 0.8.4 on an up-to-date system, you need to add `-fgnu89-inline` to the compile flags in line 44 of `Makefile.skel`. You might also need to change `python` to `python2` or `python2.X` in lines 97, 180, and 183. ]
[Question] [ Inspired by the fourth problem from [BMO2 2009](http://bmos.ukmt.org.uk/home/bmo2-2009.pdf). Given a positive integer *n* as input or a parameter, return the number of positive integers whose binary representations occur as blocks in the binary expansion of *n*. For example, 13 -> 6 because 13 in binary is 1101 and it has substrings `1101, 110, 101, 11, 10, 1`. We do not count binary numbers that start with zero and we do not count zero itself. ### Test Cases ``` 13 -> 6 2008 -> 39 63 -> 6 65 -> 7 850 -> 24 459 -> 23 716 -> 22 425 -> 20 327 -> 16 ``` You may take in *n* as any of the following: * an integer * a list of truthy/falsy values for the binary representation * a string for the binary representation * a base 10 string (though I'm not sure why anyone would do this) Make your code as short as possible. [Answer] # Python 3, ~~54~~ 50 bytes ``` lambda n:sum(bin(i)[2:]in bin(n)for i in range(n)) ``` Thanks to Rod and Jonathan Allan for saving four bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ẆQSḢ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrbA4Ic7Fv3//z/aUEcBGRkgMUAoFgA "Jelly – Try It Online") Takes input as list of `0`s and `1`s. [Try it online with numbers!](https://tio.run/##y0rNyan8///hrrbA4Ic7Fv13Otz@/7@RgYEFAA "Jelly – Try It Online") Explanation: ``` ẆQSḢ Argument: B = list of bits, e.g. [1, 1, 0, 1] Ẇ Get B's non-empty sublists (i.e. [[1], [1], [0], [1], [1, 1], [1, 0], [0, 1], [1, 1, 0], [1, 0, 1], [1, 1, 0, 1]]) Q Keep first occurrences (i.e. [[1], [0], [1, 1], [1, 0], [0, 1], [1, 1, 0], [1, 0, 1], [1, 1, 0, 1]]) S Reduce by vectorized addition (i.e. [6, 4, 1, 1]) Ḣ Pop first element (i.e. 6) ``` Proof it works: This program gets an input number, **N**. The first thing this product does is, of course, take the substrings of **N2** (**N** in base **2**). This includes duplicate substrings starting with either **0** or **1**. After that, we simply take the unique substrings by keeping only the first occurrence of each value in the substring list. Then, this program sums the first elements of the lists together, then the second elements, then the third, fourth, etc. and if one of the lists has no such element `0` is assumed. What the challenge asks is effectively *How many unique substrings starting with **1** does this number have in its binary form?*. Since every first element which is to be counted is `1`, we can simply sum instead of filtering for appropriate substrings. Now, the first element of the resulting list of the summation described above holds the count of the first bits of the substrings, so we simply pop and finally return it. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~62~~ 61 bytes ``` @(n)sum(arrayfun(@(t)any(strfind((g=@dec2bin)(n),g(t))),1:n)) ``` [**Try it online!**](https://tio.run/##DcpLCoAgEADQ68yACNkiCASvMpkjLprAT@DpJ9fvvbHTl5S9tVYDCLbxANVKk4dAgI4kE1qvXOQGyD7cKbqrCK5r8nJEs52CqAy7O1B/) ### Explanation For input `n`, the code tests all numbers from `1` to `n` to see if their binary representation is a substring of the binary representation of the input. ``` @(n) % Anonymous function of n arrayfun( ,1:n) % Map over range 1:n @(t) % Anonymous function of t strfind( , ) % Indices of ... g(t) % t as binary string ... (g=@dec2bin)(n) % within n as binary string any( ) % True if contains nonzero sum( ) % Sum of array ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes Takes input as a binary string. The header converts integer input to binary for ease of testing. ``` ŒCÙĀO ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVpn0/@gk58MzjzT4/69UOrxfQddO4fB@JZ3/hsZcRgYGFlxmxlxmplwWpgZcJqaWXOaGZlwmRqZcxkbmAA "05AB1E – Try It Online") **Explanation** ``` Œ # push all substrings of input C # convert to base-10 int Ù # remove duplicates Ā # truthify (convert non-zero elements to 1) O # sum ``` [Answer] # [Perl 5](https://www.perl.org/), 36 + 1 (`-p`) = 37 bytes ``` /.*(.+?)(?{$k{0|$1}++})(?!)/;$_=%k-1 ``` [Try it online!](https://tio.run/##K0gtyjH9/19fT0tDT9teU8O@WiW72qBGxbBWW7sWyFXU1LdWibdVzdY1/P/f0NDA8F9@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online") Takes input as a binary string. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~103~~ ~~92~~ 82 bytes ``` param($s)(($s|%{$i..$s.count|%{-join$s[$i..$_]};$i++}|sort -u)-notmatch'^0').count ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VYUwNI1KhWq2Tq6akU6yXnl@aVALm6WfmZeSrF0WDh@Nhaa5VMbe3amuL8ohIF3VJN3bz8ktzEkuQM9TgDdU2Irv///ztoGOoY6BjqgEg4rQkA "PowerShell – Try It Online") Takes input as an array of `1` and `0` (truthy and falsey in PowerShell). Loops through `$s` (i.e., how many elements in the input array). Inside the loop, we loop from the current number (saved as `$i`) up to `$s.count`. Each inner loop, we `-join` the array slice into a string. We then `sort` with the `-u`nique flag (which is shorter than `select` with the `-u`nique flag and we don't care whether they're sorted or not), take those that don't start with `0`, and take the overall `.count`. That's left on the pipeline and output is implicit. [Answer] ## JavaScript (ES6), 55 bytes ``` f=(s,q="0b"+s)=>q&&s.includes((q--).toString(2))+f(s,q) ``` Takes input as a binary string. Here's a sad attempt at doing it with numbers and recursive functions: ``` f=(n,q=n)=>q&&(g=n=>n?n^q&(h=n=>n&&n|h(n>>1))(q)?g(n>>1):1:0)(n)+f(s,q-1) ``` ### Old approach, 74 bytes ``` s=>(f=s=>+s?new Set([+s,...f(s.slice(1)),...f(s.slice(0,-1))]):[])(s).size ``` Also takes input as a binary string. [Answer] # Haskell (~~126~~121 bytes) ``` import Data.List r o c(t:s)=r([t]:[t:x|x<-o])(o++c)s r o c[]=o++c f=length.nub.filter(>"").map(dropWhileEnd(<'1')).r[][] ``` (5 bytes improvement thanks to @WheatWizard's comment) Defines a function "f" that accepts a binary string as input. Ungolfed and commented: ``` import Data.List -- unfortunately we need some functions that aren't in Prelude -- recursively generate all sublists of a given list (or string) -- arguments are the list of sublists currently being worked with, -- a list of finished sublists, and list to examine -- output is a list of reversed lists rsubstrs :: [[t]]->[[t]]->[t]->[[t]] rsubstrs open closed (t:ts) = rsubstrs ([t]:[t:o|o<-open]) (open++closed) ts rsubstrs open closed [] = open++closed -- count unique nonzero binary substrings, produced by composing a sequence of functions: -- rsubstrs above (with two empty lists supplied to the first two curried arguments) -- a map operation that removes any trailing sequences of zeros -- filter to remove empty strings (which were zeros) -- nub, which finds all unique items in a list -- length, to count the results countsubs = length . nub . filter (/="") . map (dropWhileEnd (=='0')) . rsubstrs [] [] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~118~~ 81 bytes *Thanks to @Rod for saving 37 bytes!* ``` lambda n:len({int(n[i:j+1],2)for i in range(len(n))for j in range(i,len(n))}-{0}) ``` Takes input as a binary string. [Try it online!](https://tio.run/##RY/BCoMwDIbve4rc2rIOEo@CexH14JhuFRel9DLEZ@8aV7emkOT/v5ZkeYfnzEUcqiZO3et274DLqWe9Og6aa1eOZ2ptYYbZgwPH4Dt@9FoQNrs6/lVns75dVtxMFDuIXSsiJGUhZZKSEPHXfg2UkxmUSDcjUh7U3tHxOoPZkg8S15YnWHxaAGSJkKa3qroqO@hg4gc) # [Python 2](https://docs.python.org/2/), 81 bytes *Thanks to @Rod!* ``` lambda n:len({n[i:j+1]for i in range(len(n))for j in range(i,len(n))if'1'==n[i]}) ``` Takes input as a binary string. [Try it online!](https://tio.run/##RYzNCoJAFIX3PcXBjUp34Yz5k@CTqAslp67oVcRNRM8@zUTQWR2@87M9j8cq2pq6tXO/DLceUs2jRC9puJrOqjPrDgYL9l7uY@QziWNPpz9l@nE2oQrr2o27d2x9S3yrUSlBJ0lJyJ3LM0KZJYRLdiUUKndOO5bqoqtOcNp2lgNCCNojIJho4O@//QA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ẆḄQṠS ``` [Try it online!](https://tio.run/##AUUAuv9qZWxsef//4bqG4biEUeG5oFP/QsOHJOKCrMW8QMK1R///WzEzLDIwMDgsNjMsNjUsODUwLDQ1OSw3MTYsNDI1LDMyN10 "Jelly – Try It Online") Takes input as a list of 1s and 0s. The footer in the link applies the function to each of the examples in the post. Jonathan Allan pointed out that `ẆḄQTL` is 5 byte alternative which uses the `T` atom which finds the indices of all truthy elements. **Explanation** Take bin(13)=1101 as an example. Input is `[1,1,0,1]` ``` ẆḄQṠS Ẇ All contiguous sublists -> 1,1,0,1,11,10,01,110,101,1101 (each is represented as a list) Ḅ From binary to decimal. Vectorizes to each element of the above list -> 1,1,0,1,3,2,1,6,5,13 Q Unique elements Ṡ Sign. Positive nums -> 1 , 0 -> 0. S Sum ``` Took the "truthify" (sign in this case) idea from the [05AB1E answer](https://codegolf.stackexchange.com/a/153851/75553) [Answer] # [R](https://www.r-project.org/), ~~88~~ 77 bytes ``` function(x)sum(!!unique(strtoi(mapply(substring,x,n<-1:nchar(x),list(n)),2))) ``` [Try it online!](https://tio.run/##DctBCoAgEADAr2SnXVDIjtFnSrIWdC11wV5vXQcmdz@sZuhe2FVKDA2LRFBKmB45oNRcE0Hc7ju8UGT/gfjUTfNq7MLu2vJ/dKBSgRH1jIjdw2jtZEfsHw "R – Try It Online") Takes input as a binary string. using `mapply`, generates an array of all substrings of the input. `strtoi` converts them as base `2` integers, and I take the sum of the logical conversion (`!!`) of entries in the result. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~37~~ 29 bytes ``` .+ * +`(_+)\1 $1# #_ _ wp`_.* ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4tLO0EjXlszxpBLxVCZSzmeK56rvCAhXk/r/39DYwA "Retina – Try It Online") I just had to try out Retina 1.0's `w` modifier. Edit: Saved 8 bytes thanks to @MartinEnder. Explanation: ``` .+ * ``` Convert from decimal to unary. ``` +`(_+)\1 $1# #_ _ ``` Convert from unary to binary, using `#` for `0` and `_` for 1. ``` wp`_.* ``` Generate substrings that begin with `1`, I mean, `_`. The `w` modifier then matches all substrings, not just the longest one at each starting `_`, while the `p` modifier deduplicates the matches. Finally as this is the last stage the count of matches is implicitly returned. [Answer] # [Ruby](http://www.ruby-lang.org) ~~41 36~~ 27 bytes Takes binary string as input Is ultra-inefficient ``` ->n{(?1..n).count{|j|n[j]}} ``` Partly inspired by [this python 3 answer](https://codegolf.stackexchange.com/a/153857/77598) [Try it online!](https://tio.run/##bdBBD8EwGAbg@37Fm@yAg6XtrNskOLu7ITJ0GGlFKwh@@2wzdIlDe3jyvW@/9HRe3vJ0MMu7Q3lvj6jnyY63Umdp7o/sIafZ/PnMj0inxDNqocHmAFwQpzTq/9AFr4z/s8C28J1l4Rd/FlkWFccke6FByRUHJTfiBLNNJIqs47goI75VU8xTXlxjrBLZMlgr7Ax2Egeh9TvJiS6Tk63QoirHJbnBKFX19@tSRoi9iB/XHgXEfoz1au8FccP92kPKG84@86zxIYzkLw) [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` l #{vM.: ``` **[Try it here!](https://pyth.herokuapp.com/?code=l+%23%7BvM.%3A&input=%2211111011000%22&debug=0)** Takes input as a binary string. `.:` generates all the substrings, `vM` evaluates each (that is, it converts each from binary), `{` deduplicates, `<space>#` filters by identity and `l` gets the length. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes Counting unique subsequences of the binary representation that start with one, although I'm not sure this code even needs an explanation. ``` Union@Subsequences@#~Count~{1,___}& ``` [Try it online!](https://tio.run/##BcG7CoMwFADQjxGkhQvmrR0KgXbpViidREIqV5vBK9VkEv319JzJxy9OPobe5@Ga3xRmsq/0WfGXkHpcbXHc5kTx2Dg45/YyP5dAsR0qe3pQxBGXexhDXNsCRFdWduMSBGMNGAlGQaMZKH2BmhtQQoMU9X7u8h8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ←LumḋQḋ ``` [Try it online!](https://tio.run/##yygtzv7//1HbBJ/S3Ic7ugOB@P///0YGBhYA "Husk – Try It Online") ## Explanation ``` ←LumḋQḋ ḋ binary digits of the input Q all possible sublists mḋ convert each back to base-10 u uniquify L get the length ← decrement (since one of the sublists will be 0) ``` [Answer] # [Perl 6](http://perl6.org/), 47 bytes ``` ->\n{+grep {n.base(2).contains(.base: 2)},1..n} ``` [Try it online!](https://tio.run/##HcjdCoMgAAbQV/mIGMWW@JPWfvJJBuGGjsGy0N2E@OwOdi7PZsNHlWXHwWEqnb77dHwFuyF58jDRNrwlz9V/zdvH5j8X8DafGCE@l2h2VPWMSSM51HOu4NaAGxPglI5QAkpilBS9PGNgCj2XEHzQ1/ID "Perl 6 – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 37 bytes ``` ~n=sum(contains.([bin(n)],bin.(1:n))) ``` [Try it online!](https://tio.run/##DcjLCoMwEEbhvU8xiIsZmEoSa7SF9kXEhb1BxP4WL1tfPc3qfJxxn8LgYzxwW/cvP2dsQ8BacvcIYEivqSXbK0QkfuaFQAHU2UrJGdMq@SRfK7W1UTrXF6XG@iSXXuWaPiP6LQHbBM4L0OlOBR@QXLI3XvEP "Julia 0.6 – Try It Online") Juliafication of the [Python answer by J843136028](https://codegolf.stackexchange.com/a/153857/76880) using `.` for element-wise function application with broadcasting. ([link](https://julialang.org/blog/2016/10/julia-0.5-highlights#vectorized-function-calls)) [Answer] # Java, 232 bytes ``` String b=toBin(n); l.add(b); for(int i=1;i<b.length();i++){ for(int j=0;j<=b.length()-i;j++){ String t=""; if((""+b.charAt(j)).equals("0"))continue; for(int k=0;k<i;k++){ t+=""+b.charAt(j+k); } if(!l.contains(t))l.add(t); } } return l.size(); ``` Where n is the input, b is the binary representation and l is a list of all the substrings. First time posting here, definitely need to improve, and feel free to point out any mistakes! Slightly edited for readability. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 35 bytes ``` `-&1@`#@Unique@(UnBin=>Subsets@Bin) ``` [Try it online!](https://tio.run/##FYq9CsIwGAB3n@KjWlH4CulfWoeGIOIsSKcQ2ioJZjBik07is8e43R03eT/dHyqclDZWiY3GMGbbnI9r3lvzXhTf9fZobMeuy80p73iUfZCry2ysh47B5/yan5MXSeogY5C6BGFA0GKQ8vsfRF4iFIS0CDQSrRHamiBU9QGhyWmkIrayaGT4AQ "Attache – Try It Online") Equivalently: ``` {#Unique[UnBin=>Subsets[Bin[_]]]-1} ``` ## Explanation I will explain the second version, as it is easier to follow (being explicit): ``` {#Unique[UnBin=>Subsets[Bin[_]]]-1} { } lambda: _ = first argument Bin[_] convert to binary Subsets[ ] all subsets of input UnBin=> map UnBin over these subsets Unique[ ] remove all duplicates # -1 size - 1 (since subsets is improper) ``` [Answer] # Java 8, ~~160~~ ~~159~~ 158 bytes ``` import java.util.*;b->{Set s=new HashSet();for(int l=b.length(),i=0,j;i<l;i++)for(j=l-i;j>0;s.add(new Long(b.substring(i,i+j--))))s.add(0L);return~-s.size();} ``` Input as binary-String. There must be a shorter way.. >.> **Explanation:** [Try it online.](https://tio.run/##nZBNb4MwDIbv/RU@hhVSStePKaPnTeqqST1WOwRIaViaIGI6dRX76yyUavdhJQe/8evHTsHPPDCl0EX22cpTaSqEwmm0RqnoAwMXkwm8c6ebA@BRQHJBEaSm1jhKFbcW3rjU1xGA1CiqA08FbLv0JkBKdlhJnUPiMSc27rpjkaNMYQsaYmiTYH3dCQQba/EFL9weXUY8djAV6XqoOKFK6ByPxPNlHPoFk8@KyfHY60qKWAWSFeuQWcqzjHRNNkbnJKG2TuwNT6Qvx0UQeC76qnDjsUpgXemfwFIrv4UjNi3rByzrRLkB73Oejczg5Na8L7P/4F6/4u5iUZyoqZGW7gWVJpqm5NV9RS4qiqY3kOnMjxya/csUheFqgG0xhLWYDzCt5uEA1@PTENZyuhjCioawZtHyz9WMmvYX) ``` import java.util.*; // Required import for Set and HashSet b->{ // Method with String as parameter and integer as return-type Set s=new HashSet(); // Create a Set for(int l=b.length(), // Set `l` to the length of the binary-String i=0,j;i<l;i++) // Loop from 0 up to `l` (exclusive) for(j=l-i;j>0; // Inner loop from `l-i` down to `0` (exclusive) s.add(new Long(b.substring(i,i+j--)))) // Add every substring converted to number to the Set s.add(0L); // Add 0 to the Set return~-s.size();} // Return the amount of items in the Set minus 1 (for the 0) ``` [Answer] # C++, 110 bytes ``` #include<set> std::set<int>s;int f(int n){for(int i=1;i<n;i+=i+1)f(n&i);return n?s.insert(n),f(n/2):s.size();} ``` This is a recursive function. We use a `std::set` to count values, ignoring duplicates. The two recursive calls mask bits off the left (`f(n&i)`) and off the right (`f(n/2)`), eventually producing all the substrings as integers. Note that if you want to call it again, `s` must be cleared between calls. ## Test program ``` #include <cstdlib> #include <iostream> int main(int, char **argv) { while (*++argv) { auto const n = std::atoi(*argv); s={}; std::cout << n << " -> " << f(n) << std::endl; } } ``` ## Results ``` ./153846 13 2008 63 65 850 459 716 425 327 13 -> 6 2008 -> 39 63 -> 6 65 -> 7 850 -> 24 459 -> 23 716 -> 22 425 -> 20 327 -> 16 ``` [Answer] # [J](http://jsoftware.com/), 34 bytes ``` f=.3 :'<:#~.,(#:i.2^##:y)#.;.1#:y' ``` [Try it online!](https://tio.run/##y/rPyfk/zVbPWMFK3cZKuU5PR0PZKlPPKE5Z2apSU1nPWs8QyFD/n5qcka@QpmBozAVlGRkYWMDYZnBRM1MYy8LUAMY0MbWEMc0NzeCiRnC1xkbm/wE "J – Try It Online") [Answer] # [J](http://jsoftware.com/), 15 bytes ``` #.\\.#@=@-.&,0: ``` Input is a binary list. [Try it online!](https://tio.run/##BcFNCoAgEAbQq3wgtKphHH8TBA/iLpRoE7QIOv303qU6K8FQ72RabRstKxcdx3ljNlMw3vF8YFgIhDkjOsSAHBg@7Eg2wkuAk6Q/ "J – Try It Online") ``` #.\\. Convert every substring to decimal -.&,0: Flatten and remove the 0s. #@= How many unique elements? ``` [Answer] # [Perl 6](https://perl6.org), 34 bytes ``` {+unique ~«(.base(2)~~m:ex/1.*/)} ``` [Test it](https://tio.run/##PY5LboMwFEXnbxVPUdSY8jdgkqK0XUFHHXaSwKtkiY@LoUoUhQ11CZ1lYxRTlJGPjo6vragtxdhrwm/h5RlUZ3zIm4JwP17svpZfPeFw@2He8aCJcWsYqic6@aH36FvXcapfO9Id7rGUNWlm3X69vKmOzN@4m5ePwvaNeesrauW0bt55n/oMVHmo0Z4vZ/DZtMuO@4xsLWvVd86aToryjgoLL4AotVsQqfKM5ntLZDl4zxxc/UszcrerDK5jGBkngAfB1lC0A7EokZgzhW0SGOAxxMlupgjSUMzEIeZzxgOIeGooFH8 "Perl 6 – Try It Online") ## Expanded: ``` { + # turn into Numeric (number of elements) unique # use only the unique ones ~«( # turn into strings .base(2) # the input in base 2 ~~ m:ex/1.*/ # :exhaustive match substrings ) } ``` ]
[Question] [ Write a non-empty program or function that when called outputs a single value, 1 or 0, and when called multiple times, the output numbers produce the binary representation of your program's source code (in the same code page from which your code is compiled/interpreted). For instance, if your source code was `abc` (in ASCII), the outputs would be: ``` 1st call: 0 // ASCII letter 'a' 2nd call: 1 3rd call: 1 4th call: 0 5th call: 0 6th call: 0 7th call: 0 8th call: 1 9th call: 0 // ASCII letter 'b' 10th call: 1 11th call: 1 12th call: 0 13th call: 0 14th call: 0 15th call: 1 16th call: 0 17th call: 0 // ASCII letter 'c' 18th call: 1 19th call: 1 20th call: 0 21st call: 0 22nd call: 0 23rd call: 1 24th call: 1 After the 24th call, the behaviour is undefined. ``` The binary representation of the source must contain at least one 0 bit and one 1 bit. Instead of 1 and 0, you can output any two distinct, consistent values (such as `true` and `false`). Self-modifying programs that output the binary representation of the original source are allowed, provided that they don't read the source code to find out what to print next. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Bash](https://www.gnu.org/software/bash/), 105 bytes ``` trap -- 'trap|xxd -b -c1|cut -d\ -f2|tr -d \\n|cut -c`x=\`cat f||echo 1\`;echo $((x+1))>f;echo $x`' EXIT ``` **NOTE**: Make sure that you don't have an important file called `f` in the directory you're testing this. --- If you want to test this, you can use the following command: ``` for i in $(seq 848); do bash path/to/script.sh 2> /dev/null; done | tr -d \\n ``` Which should give the same output `xxd -c1 -b path/to/script.sh|cut -d\ -f2|tr -d \\n`. ## Explanation This is using the `trap` trick - calling `trap` inside the `trap` action simply prints that line. Next that output gets piped to `xxd` which converts it to binary (unfortunately `xxd -bp` doesn't work - thus the workaround with `cut` & `tr`): ``` xxd -c1 -b $0|cut -d\ -f2|tr -d \\n ``` From that we're only interested in one bit (say `N`) which we can select with `cut -cN`. To find out what `N` we're using (remember that's the part that needs to be incremented after each call), simply try to set `x` to the content of the file `f` and if it doesn't exist set it to 1: ``` x=`cat f||echo 1` ``` Last thing to do, is to update the file `f` - writing `x+1` to it: ``` echo $((x+1))>f ``` [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), ~~47~~ ~~41~~ 37 bytes Returns a number representing a bit. ``` f=_=>1&("%b"%("f="+f)[i//8])>>7-i++%8 ``` This uses the quine format of `f=_=>"f="+f`. It takes the character at position **⌊i/8⌋**, then, gets the bit by taking the pairity of `n >> 7-i%8` where `n` is the ascii value of the current character. This is an iterative function that increments `i` with each call, once it's out of source code, it will write the code for `n` forever. [Try it online!](https://tio.run/##HY1LCsIwGIT3OcVPaCUx2CouWtB06cIriEgMiQ2VpOQhiHj2WDOrb5gZRic7vXPW/MaH3Yrg@o5rgjXHTNOLadv@Soeh2xjG6j5XcE4hwuyNjRBHBV6F9IzgdHE6WRmNs6CdByXkCHdTwsJyFF7IqHyDKjgtjahCNPYBc/KzCyo06L8jL@Fh4tsDTHCEfbfuF2KMfhAsKtdEE0rRN/8A "Funky – Try It Online") [Answer] # TI-Basic (TI-83 series), ~~592~~ ~~357~~ 309 bytes ``` "123456789ABCDEF02A3132333435363738394142434445463004AA003FB958833404593FB9588338045A3F3230363FDA582B383F303FCE5A405A6B3232333F5A70BB0FAA002BBB0CAA002B5A2B313FB932BA32F01058713459713511BB0FAA002BBB0CAA002B597031377132722B31→Str1 iPart(X/4→Y iPart(X/8→Z 206 IS>(X,8 0 If Z and Z<223 Z+inString(Str1,sub(Str1,Z,1 iPart(2fPart(2^(X-4Y-5)inString(Str1,sub(Str1,Y+17-2Ans,1 ``` [This table](http://tibasicdev.wikidot.com/one-byte-tokens) is a possible reference for the calculator's binary representation of the source code, though ultimately I just used Virtual TI's debugger. For comparison and/or historical interest: [the first quines written in TI-Basic](https://www.cemetech.net/projects/uti/viewtopic.php?t=7181&postdays=0&postorder=asc&start=20). # How it works `Str1` stores the source code (now in glorious hexadecimal, saving lots of space over the previous binary version), leaving out the bits where the contents of `Str1` itself would be represented. We're assuming that the program starts out on a calculator whose memory has just been cleared, so `X` is `0`. Every time through the program, we increment `X`. Usually, we just figure out the half-byte we're trying to extract a bit from, read it out of `Str1`, convert from hexadecimal to binary, and print it. If we're on the part of the source code that's storing `Str1` (which is two-thirds of the total length of the program), then we first move to the corresponding part of the string storing `31`, `32`, and so on. [Answer] # Java 8, ~~249~~ ~~241~~ ~~237~~ ~~234~~ 148 bytes ``` int i;v->{String s="int i;v->{String s=%c%s%1$c;return s.format(s,34,s).charAt(-i/8)>>(--i&7)&1;}";return s.format(s,34,s).charAt(-i/8)>>(--i&7)&1;} ``` *Sorry in advance for the long explanations. :)* * Whopping 89 bytes saved thanks to *@Nevay*. [Try it here.](https://tio.run/##lZDBasMwDIbvfQpRlmJD7VA22CAksAdYGRR2GTu4rrO4c@xgyyml5NkzJ@llxx2E0M//C@k7i14w1yl7Pv2M0ogQ4E1oe1sBaIvK10Iq2E/jLIAkH06foKdFkoZUixF0MTnyHN6FR3A1YKPgeEXFpIsWV8m2Bwvl2LPqdkCv7TeEcr1E/2iZzEK2e5CFVxi9hcBr51uBJGwfn7aBctkI/4qE6fyFVhVhTG@e6WZXDOv/R8ZiuqyLR6MlBBSYWj892CYIZLnp8wsEXQhMaKCFEqy6zAOZOQBcGm0UQR/V3QlwuAZULXcReZfWoLGk5ZZLYqMx9J4bZorD@As) **Explanation:** ``` int i; // Index-integer on class-level v->{ // Method with empty unused parameter and integer return-type String s="int i;v->{String s=%c%s%1$c;return s.format(s,34,s).charAt(-i/8)>>(--i&7)&1;}"; // String containing the unformatted source code return s.format(s,34,s) // Quine to get the source code, .charAt(-i/8) // and get the character at index `-i/8` >> // And bitwise right-shift it with: (--i&7) // `i-1` bitwise-AND 7 // by first decreasing `i` by 1 with `--i` &1; // Then bitwise-AND everything above with 1 } // End of method ``` Additional explanation: [quine](/questions/tagged/quine "show questions tagged 'quine'")-part: * `String s` contains the unformatted source code * `%s` is used to put this String into itself with `s.format(...)` * `%c`, `%1$c` and `34` are used to format the double-quotes (`"`) * `s.format(s,34,s)` puts it all together [Try it here with some parts removed/modified to verify the quine outputs it's own source code.](https://tio.run/##dY9NasMwEIX3OcUjxCBDrFDanXBv0BAodFO6UBS5VWpJRhq5hOCzu1KcTRddDMObefPzneUoGz9odz59z6qXMeJFGnddAcaRDp1UGvsigVcKxn1CsTdvThhrkatTjsULI4ppt8NBBoLvQF8axwvpRvnkaJVtezi089g8X@@7Yrv@oypVxepho0TQlIJD5J0PVhKL28enbazFtP6/NYtyY0jH3ihEkpTTWF61mYgtN94/IOsFp3DCooXTPzfBbkSZ8xJJW@4T8SHPELPcccVc6vv6Dj3Nvw) [binary](/questions/tagged/binary "show questions tagged 'binary'")-part: * `-i/8` will automatically truncate on integer division, so when `i` is -7 to 0, it will become `0`; if `i` is -15 to -8, it will become `1`; etc. * So `s.charAt(-i/8)` takes the current character of the source-code, eight times after each other. [Try it here with a modified version.](https://tio.run/##hVBBasMwELznFUNoggSR09BAC8KBPqChEOil9KAocq3UloO0dgjBb3clJ5eeeliWHWaWmTmqTonmZNzx8DPoSoWAN2XddQJYR8YXShts0wnoUnlo9tHYAzouI9bHuTFh80eZSMsl3pUnNAWoNNhfyAjdtI4mkbiFQz50YnPdkbfuGyGfjmL5B5vpWZitHrT0hlrvELKi8bUiFhZP60XgWXLySkzY5QvfbJgQdv7M5yvZT/@VMCsEjzLZDzJZOrX7ymoEUhRXl7LVsQB2M/P5BcVv6VMtqJHDmfN4sLEC4FzayjDyrbkzgd0lkKmzpqXsFN9Q5ViduUwz11YVv@v6scB@@AU) * `--i&7` will be [`7,6,5,4,3,2,1,0,7,6,5,4,3,2,1,0,...`](https://tio.run/##LYwxDoMwDEV3TvGnKgxBdOqA6A06MaIOKdDKNCQRMVRVxdnTEDF82dbz@6NalbRuMGP/DqHTynvcFJlfBrjloamDZ8VxrJZ6TBGJhmcyr/YOle9vSAIm1DDDJx0irxJ42lmQYVBdVqCrPJdlXA4LaL6eh6mwCxcuVrI2Qko6XQ57y/ZsIfwB), where the first `7` is when `i=0` (which becomes `-1` first due to the `--i`, and will keep decreasing). * `s.charAt(-i/8)>>(--i&7)` will produce sequences depending on the characters. Some examples (`'A'` (65) through `'E'` (69) are): + A: [`0,1,2,3,4,8,16,32,65,0,1,2,4,8,16,32,65,...`](https://tio.run/##LUy9DoIwGNx5ipukDCU4ORBIfAAmRuNQAc2H0Db0A2MMz14LYbjcXe6nV4uSxna6b9/eN4NyDpUi/YsAOz8GauBYcaDFUIsxRKLmifTrdodKthr2AUYU0N1nNyLJ9@BpJkGaQUWWg0p5zrIgjhVQfx13Y2pmTm245EGL@BqXpZCSTpfkOFmjDav3fw); + B: [`0,1,2,4,8,16,33,66,0,1,2,4,8,16,33,66,...`](https://tio.run/##LUy9DoIwGNx5ipukDCU4ORAY3JkYjUMFNB9C29APjDE8ey2E4XJ3uZ9eLUoa2@m@fXvfDMo5VIr0LwLs/BiogWPFgRZDLcYQiZon0q/bHSrZatgHGFFAd5/diCTfg6eZBGkGFVkOKuU5y4I4VkD9ddyNqZk5teGSBy3ia1yWQko6XZLjZI02rN7/AQ); + C: [`0,1,2,4,8,16,33,67,0,1,2,4,8,16,33,67,...`](https://tio.run/##LUy9DoIwGNx5ipukDCU4ORBYnJkYjUMFNB9C29APjDE8ey2E4XJ3uZ9eLUoa2@m@fXvfDMo5VIr0LwLs/BiogWPFgRZDLcYQiZon0q/bHSrZatgHGFFAd5/diCTfg6eZBGkGFVkOKuU5y4I4VkD9ddyNqZk5teGSBy3ia1yWQko6XZLjZI02rN7/AQ); + D: [`0,1,2,4,8,17,34,68,0,1,2,4,8,17,34,68,...`](https://tio.run/##LUy9DoIwGNx5ipukDCU4ORCYXJkYjUMFNB9C29APjDE8ey2E4XJ3uZ9eLUoa2@m@fXvfDMo5VIr0LwLs/BiogWPFgRZDLcYQiZon0q/bHSrZatgHGFFAd5/diCTfg6eZBGkGFVkOKuU5y4I4VkD9ddyNqZk5teGSBy3ia1yWQko6XZLjZI02rN7/AQ); + E: [`0,1,2,4,8,17,34,69,0,1,2,4,8,17,34,69,...`](https://tio.run/##LUy9DoIwGNx5ipukDCU4ORDYHJkYjUMFNB9C29APjDE8ey2E4XJ3uZ9eLUoa2@m@fXvfDMo5VIr0LwLs/BiogWPFgRZDLcYQiZon0q/bHSrZatgHGFFAd5/diCTfg6eZBGkGFVkOKuU5y4I4VkD9ddyNqZk5teGSBy3ia1yWQko6XZLjZI02rN7/AQ); + etc. * `...&1` then outputs a `0` if it's an even number, and `1` if it's an odd number, which in combination with the sequences above outputs the correct result. --- Old **233 bytes** answer: ``` int i;v->{String s="int i;v->{String s=%c%s%1$c;return Long.toString((s.format(s,34,s).charAt(i/8)&255)+256,2).substring(1).charAt(i++%%8);}";return Long.toString((s.format(s,34,s).charAt(i/8)&255)+256,2).substring(1).charAt(i++%8);} ``` [Try it here.](https://tio.run/##tZHBagIxFEX3fsVFOiVBjWhrEQYL3bdSELopXcQYNXYmkeRlRGS@fTpxhNIP6CKE93LvfcnJQVZy5I7aHjbfjSpkCHiTxl56gLGk/VYqjWUqAbWXHop9OLNBxfO2V7erU8LkSTIe4116gtuC9hrrM@mRctFSr5UtYbFoqtHzZUXe2B3Cot9Z//QylYVscqdyryl6i1dnd4Jcd85YEFvnS0ksDB8eh4GLdK0XYmY85/fT2YwPprOn4ZSLENeh80x@RYNBls15Xvf/Kz2FN3l67jGuC6MQSFK7VYla2aJl3ajPL0jecU3AUWIBq0/Xgl3hAqe9KTQjH/VNCazOgXQpXCRxbGOosKwUVihmY1Hwm6@@fk3d/AA) **Explanation:** ``` int i; // Index-integer on class-level v->{ // Method with empty unused parameter and char return-type String s="int i;v->{String s=%c%s%1$c;return Long.toString((s.format(s,34,s).charAt(i/8)&255)+256,2).substring(1).charAt(i++%%8);}"; // String containing the unformatted source code return Long.toString( (s.format(s,32,s) // Quine-formatting .charAt(i/8) // Take the current character &255)+256,2).substring(1) // Convert it to an 8-bit binary-String .charAt(i++%8); // And return the bit at index `i` modulo-8 // and increase index `i` by 1 afterwards with `i++` } // End of method ``` Additional explanation: [quine](/questions/tagged/quine "show questions tagged 'quine'")-part: Same explanation as above, with the addition of: * `%%` is the escaped form of the modulo-sign (`%`) [Try it here with some parts removed/modified to verify the quine outputs it's own source code.](https://tio.run/##dY9NasMwEIX3OcUjxCBDrFDanXBv0BAodFO6UBS5VWpJRhq5hOCzu1KcTRddDMObefPzneUoGz9odz59z6qXMeJFGnddAcaRDp1UGvsigVcKxn1CsTdvThhrkatTjsULI4ppt8NBBoLvQF8axwvpRvnkaJVtezi089g8X@@7Yrv@oypVxepho0TQlIJD5J0PVhKL28enbazFtP6/NYtyY0jH3ihEkpTTWF61mYgtN94/IOsFp3DCooXTPzfBbkSZ8xJJW@4T8SHPELPcccVc6vv6Dj3Nvw) [binary](/questions/tagged/binary "show questions tagged 'binary'")-part: * `i/8` will automatically truncate on integer division, so when `i` is 0-7, it will become `0`; if `i` is 8-15, it will become `1`; etc. * So `s.charAt(i/8)` takes the current character of the source-code, eight times after each other. [Try it here with a modified version.](https://tio.run/##dZBRa8IwFIXf/RUXWUdCazrdOoTSwd43GQh7kT3EGDWuTSS5qYj0t3dNq4w97CGEe@93Dodz4DWfmKPUh813K0ruHLxzpS8jAKVR2i0XEhZhBBB7bkGQT6M2UNO82zXdG0hQxUMeoDSFD24RzBZwL2F9RjkRxmscdeACNBRtPXm5LNEqvQNXjG/iP9tIRC6a3oncSvRWw5vRO4ZmuBPi2NbYiiNxyeNT4igL0V6RqHRO72dZRuNZ9pzMKHN@7QbN9BeK4yia07wZ39z/tYvjNIBtHsIf/bpUAhxy7L46tFB1VZEh1OoLOB16CgVCBQVoeeoH0pcFcNqrUhK0Xl5JgOXZoayY8ciOnQ2WmlRMM0G0L0t61TV91U37Aw) * `255` is `0xFF` or `11111111` (the max value for an unsigned byte) * `256` is `0x100` or `100000000`. * The `&` upcasts the ASCII-character to an integer. At that point, it's anywhere between `0` and `255` (`00000000` to `11111111`). * `Long.toString(...,2)` converts it to the 9-bit binary String representation * `+256` and `.substring(1)` will ensure there are leading zeroes, and will convert the 9-bit to an 8-bit. [Try it here with some parts removed/modified to verify the entire bytes.](https://tio.run/##lZFPSwMxEMXv/RRDcSVhu6mtVgrLCt61CIIX8ZBN0zZ1N1mSyZZS9rOv2T8iHjx4CMPMvPdgfjnymiemkvq4/WxFwZ2DZ670ZQKgNEq740LCpmsBXtEqvQdB3ozaQk3TMG3CG7Sgspu0k83n8MItgtkBHiTkZ5SJMF7jJAg3oCFr6@ThMqa5bPpt/jWNROSixZVIrURvNTwZvWdohj0hju2MLTkSN7u9mznKxIHbRyRqvqbXy9WKxsvV/WxJmfO5GzyLH1EcR9Gaps30v@lx/Hd62rRpd2Ll80IJcMgxlLpjVQakZAh//wBOB54daCghAy1PfUN6pACngyokQevlqAzszw5lyYxHVoUYLDQpmWaCaF8UdPQ1/Yc07Rc) [Answer] # Javascript ES6, ~~73~~ ~~58~~ 52 bytes ``` o=_=>`o=${o}`.charCodeAt((o.n=1+o.n|0)/8)>>(7-o.n%8)&1 ``` # Explanation Breakdown of the code: * `o=_=>`: define a function. * ``o=${o}``: construct a string; `o` is converted to a string, which in this case is the function's source code. * `.charCodeAt(`: get a character in the string as its ASCII character code. * `(o.n=1+o.n|0)/8`: select a character. This is also where the counter is incremented. * `)>>(7-o.n%8)`: shift the resulting character code so that the desired bit is in the right position. * `&1`: set all other bits to 0. [Answer] # [q/kdb+](http://kx.com/download/), 45 bytes **Solution:** ``` a:-1;f:{((,/)0b vs'4h$"a:-1;f:",($).z.s)a+:1} ``` **Example:** ``` q)f[] / call function f with no parameters 0b q)f[] 1b q)f[] 1b q)f[] 0b q)f[] 0b q)f[] 0b q)f[] 0b q)f[] 1b q)f[] q)"c"$0b sv 01100001b / join back to a byte and cast to a character "a" ``` **Explanation:** I *think* I understood the brief. First setup a global variable `a` with starting value of `-1`. Function `f` builds the binary representation of the *string* representation of the function (everything including the `{}`) prepended with the `a:-1;f:` junk, and indexes into this binary list at index a (which gets incremented each call). ``` a:-1;f:{(raze 0b vs'4h$"a:-1;f:",string .z.s)a+:1} / ungolfed solution a:-1; / stick -1 in variable a f:{ } / define function f a+:1 / increment a by 1 (:: is required as a is a global variable), indexes into the left ( ) / do all this together string .z.s / z.s is the function, string converts it to a string "a:-1;f:", / prepend "a:-1;f:" to the start 4h$ / cast to bytes 0b vs' / convert each byte to binary raze / flatten binary into long list ``` [Answer] # [Python 2](https://docs.python.org/2/), 164 bytes ``` lambda s='lambda s=%r,i=[]:i.append(1)or"{:08b}".format(ord((s%%s)[~-len(i)/8]))[~-len(i)%%8]',i=[]:i.append(1)or"{:08b}".format(ord((s%s)[~-len(i)/8]))[~-len(i)%8] ``` [Try it online!](https://tio.run/##jYzRCsIgFEB/5TKQ3Ru1WsQQwS9ZPjjUEjYV3UtE/br1VE9Bb@fA4aTbeo3hWJ0811kvk9FQZPshlrdejkr4Tqdkg8GeYm7u4sCnR9O5mBe9YswGsTBWaHzuZhvQ054r@hpjXLX/j35/uKrvFDz4AFmHi8V@OMEGOAlI2YcVHFJ9AQ "Python 2 – Try It Online") ## Explanation Let's start with a standard Python 2 quine. ``` s = '...'; print s % s ``` Okay, well, this outputs it just like that. We need binary! ``` s = '...'; print "\n".join("\n".join("{:08b}".format(ord(i))) for i in s % s) ``` Right, that just converts everything to binary. But the title says "one bit at a time". We need something to persist through multiple runs. I know, let's make it a function! ``` lambda s = '...': "\n".join("\n".join("{:08b}".format(ord(i))) for i in s % s) ``` Wait, that doesn't help... Hmm, how can we keep track of the index of the bit needed to be output? Ooh, ooh, let's have an integer to keep track. ``` lambda s = '...', i = 0: "{:08b}".format(ord((s % s)[i / 8]))[i % 8] ``` Um... that always outputs the first bit. Oh, we need to increment the tracker! Oh crap, Python doesn't allow integers as default arguments to be modified. And assignments aren't expressions in Python, so you can't do that in a lambda. Welp, this is impossible in Python, case closed. ...Well, not quite. Python *does* allow lists as default arguments to be modified. (And it bites Python programmers all the time.) Let's use its length! ``` lambda s = '...', i = []: "{:08b}".format(ord((s % s)[len(i) / 8]))[len(i) % 8] ``` That still doesn't modify the tracker though... We can append something to it to increase its length... But how? Ah, well, we've got `list.append`. `lst.append(1)` is equivalent to `lst += [1]`. Great! ``` lambda s = '...', i = []: i.append(1) and "{:08b}".format(ord((s % s)[len(i) / 8]))[len(i) % 8] ``` Whoops, this skips the first bit because the length of the tracker is **1** before the bit is outputted. We need to decrement the length where it's used. ``` lambda s = '...', i = []: i.append(1) and "{:08b}".format(ord((s % s)[(len(i) - 1) / 8]))[(len(i) - 1) % 8] ``` There it is, folks! Golf it and you've got my solution! [Answer] ## [Perl 5](https://www.perl.org/), 59 bytes ``` sub{$_=q{unpack(B.++$-,"sub{\$_=q{$_};eval}")=~/.$/g};eval} ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jo@7@4NKlaJd62sLo0ryAxOVvDSU9bW0VXRwkkHgOWUImvtU4tS8ypVdK0rdPXU9FPh/L/W3Ol5RdpqGTaGlirZNpomBlpWWgCWdramtVcCkBQUJSZV6Kgkqhrp6FpzVX7HwA "Perl 5 – Try It Online") ]
[Question] [ ***Note:** This is inspired by [this question by **@Willbeing**](https://codegolf.stackexchange.com/questions/115007/perfect-license-plates) where task was to count the number of perfect plates of a certain length, but it's slightly different.* --- We call ***a perfect licence plate*** that plate whose text satisfies the following conditions: * It consists of characters, which can either be uppercase letters(`[A-Z]`) or digits(`[0-9]`) * Summing the positions of its letters in the English alphabet, ***1-indexed*** (i.e: `A=1,B=2,...,Z=26`) gives an integer **n** * Getting each chunk of digits, summing them and then multiplying all the results gives the same result, **n** * **n** is a perfect square (e.g: `49` *(72)*, `16` *(42)*) A **nearly perfect licence plate** meets the conditions for a perfect licence plate, except that **n** is *not* a perfect square. --- # Input A string representing the text of the licence plate, taken as input in any standard form, except for hardcoding. # Output If the given string represents a ***nearly perfect*** licence plate, return a truthy value (e.g: `True` / `1`), otherwise return a falsy value (e.g: `False` / `0`). Any standard form of output is accepted while taking note that [this loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are strictly forbidden. --- ### Examples ``` licence plate -> output A1B2C3 -> 1 A + B + C = 1 + 2 + 3 = 6 1 * 2 * 3 = 6 6 is not a perfect square, 6 = 6 => nearly perfect plate 01G61 -> 1 (0 + 1) * (6 + 1) = 7 G = 7 7 is not a perfect square, 7 = 7 => nearly perfect plate 11BB2 -> 0 (1 + 1) * 2 = 4 B + B = 2 + 2 = 4 4 = 4, but 4 is the square of 2 => perfect license plate (not what we want) 67FF1 -> 0 (6 + 7) * 1 = 13 F + F = 6 + 6 = 12 12 != 13 => not perfect at all! ``` --- ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29 28~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +1 byte to fix a bug spotted by ChristianSievers (incorrectly dealing with substrings of only zeros) +1 byte to fix false positives for `"0"`, `"00"`, ... found during above fixing (0 is a perfect square). ``` i@€ØAS;Ʋ$ e€ØAœpV€€LÐfS€P;0⁼Ç ``` **[Try it online!](https://tio.run/nexus/jelly#@5/p8KhpzeEZjsHWh9sObVLhSoVwj04uCAOygMjn8IS0YCAdYG3wqHHP4fb///8rGRo6ORkpAQA)**, or [run tests](https://tio.run/nexus/jelly#@5/p8KhpzeEZjsHWh9sObVLhSoVwj04uCAOygMjn8IS0YCAdYG3wqHHP4fb/h9uBvP//o5UcDZ2MnI2VdJQMDN3NDIG0oaGTkxGQNjN3c4PwHR0NQPIgQikWAA) ### How? ``` i@€ØAS;Ʋ$ - Link 1: [letter-sum, letter-sum is perfect square?]: plate i@€ - index of €ach char in plate [reversed @rguments] (1-based, 0 otherwise) in: ØA - uppercase alphabet S - sum $ - last two links as a monad: ; - concatenate with: Ʋ - is square? e€ØAœpV€€LÐfS€P;0⁼Ç - Main link: plate e.g. "11BB2" œp - partition plate at truthy values of: e€ - is in? for €ach char in plate: ØA - uppercase alphabet [['1','1'],[''],['2']] V€€ - evaluate for €ach for €ach [[1,1],[],[2]] Ðf - filter keep: L - length [[1,1],[2]] S€ - sum each [2,2] P - product 4 ;0 - concatenate a zero [4,0] Ç - last link (1) as a monad (taking plate) [4,1] ⁼ - equal? (non-vectorising) 0 ``` [Answer] # MATL, ~~36~~ ~~34~~ ~~33~~ 35 bytes ``` 3Y432YXU"@V!Usvp]GlY2&msy=wtQ:qUm~v ``` Try it at [**MATL Online**](https://matl.io/?code=3Y432YXU%22%40V%21Usvp%5DGlY2%26msy%3DwtQ%3AqUm%7Ev&inputs=%27A1B2C3%27&version=19.9.0) **Explanation** ``` % Implicitly grab input as a string 3Y4 % Push the predefined literal '[A-Za-z]+' to the stack 32 % Push the literal 32 to the stack (ASCII for ' ') YX % Replace the matched regex with spaces (puts a space in place of all letters) U % Convert the string to a number. The spaces make it such that each group of % of consecutive digits is made into a number " % For each of these numbers @V!U % Break it into digits s % Sum the digits v % Vertically concatenate the entire stack p % Compute the product of this vector ] % End of for loop G % Explicitly grab the input again lY2 % Push the predefined literal 'ABCD....XYZ' to the stack &m % Check membership of each character in the input in this array and % return an array that is 0 where it wasn't a letter and the index in 'ABC..XYZ' % when it was a letter s % Sum the resulting vector y % Duplicate the product of the sums of digits result = % Compare to the sum of letter indices result w % Flip the top two stack elements Q % Add one to this value (N) t: % Duplicate and compute the array [1...N] q % Subtract 1 from this array to yield [0...N-1] U % Square all elements to create all perfect squares between 1 and N^2 m~ % Check to ensure that N is not in the array of perfect squares v % Vertically concatenate the stack. % Implicitly display the truthy/falsey result ``` [Answer] # Python 2, ~~120~~ 118 bytes ``` s=t=p=0;r=1 for n in input(): h=int(n,36) if h>9:s+=h-9;r*=t**p p=h<10;t=(t+h)*p print(s==r*t**p)&(int(s**.5)**2<s) ``` [Try it online!](https://tio.run/nexus/python2#PY5NCoMwEIX3OcWA0CRjLRmlFo0j1IK9icSNDUl6fqu2FN7mez/wMnmnoXxUEooeSGTS0LOmPxENQ3mQ2ai@jeM3M2vkxJ6NDUxiegVYYN7l30npVoDjeUlqOVe1FjBP4PqmjTm7orEBOSF6AZ5dR8YmVil3enN82EeROeDe0Cd1MOLlqhHLLup1/Z34AA) Interprets each character as a number in base-36 (`h`). Converts to decimal and adds to the sum if `h>9` (meaning it's a letter), otherwise adds to a variable which gets multiplied to form the running product later. [Answer] # [Perl 5](https://www.perl.org/), 80 bytes 79 bytes of code + `-p` flag. ``` $.*=eval s/./+$&/gr for/\d+/g;$t-=64-ord for/\pl/g;$_=$.==$t&&($.**.5|0)**2!=$. ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K@ip2WbWpaYo1Csr6evraKmn16kkJZfpB@Toq2fbq1SomtrZqKbX5QCESzIAQnG26ro2dqqlKipaQC1a@mZ1hhoamkZKQKF//83MHQ3M1QAAA "Perl 5 – TIO Nexus") `$.*=eval s/./+$&/gr for/\d+/g;` multiplies the sums of consecutive digits. (I'm using `$.` because it's initial value is `1`, which mean it's the neutral element for multiplication). More precisely, for each chunk of digits (`for/\d+/g`), `s/./+$&/gr` places a `+` before each digit, then the string is `eval`uated, and multiplied with the current product. Secondly, `$t-=64-ord for/\pl/g;` sums in `$t` each letter (`for/\pl/g`). (`ord` return the ascii code for the letter, and `64-..` makes it be between 1 and 26. Finally, `$.==$t` checks that both values are the same, and `($.**.5|0)**2!=$.` that it's nor a perfect square. [Answer] # Python 2, ~~267~~ 207 bytes Saved 60 bytes thanks to ovs ``` import re def g(l):a=reduce(lambda a,b:a*b,[sum(map(int,list(i)))for i in re.sub(r'\D',' ',l).split()],1);return a==sum(sum(k)for k in[[ord(i)-64for i in x]for x in re.sub(r'\d',' ',l).split()])and a**.5%1>0 ``` Function with usage: `print(g('A1B2C3'))` [Try it online!](https://tio.run/nexus/python2#Zc/LCsIwEAXQvV@RjSRTYrG@FpUKPv6iupiaVELTNkxS6N/X1IUgLi7M5h7mTqZ1PQVGeqF0zV7CQo4FaTU8tbDYVgoZyirHpJKlH1rRohOmC9IaH4QBgLonZpjpIpH6oRLE7zcuOePSQuqdNUHAQ2ZwJB0G6hgWxezMaT7lJpbLsicVudVh9/XGx3yOv7T6owE7xTBJ0v0yO60nR/G7uIOfs8vmuuUwvQE "Python 2 – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), ~~163 156 155 164~~ 161 bytes ``` from math import* m=1;s=t=p=0 for x in input(): try:t+=int(x);p=1 except:m*=[1,t][p];p=t=0;s+=ord(x.upper())-64 if p:m*=t print(m==s and sqrt(m)!=int(sqrt(m))) ``` [Try it online!](https://tio.run/##LYxBCoMwEEX3OcV0l2hbDC1dKHMScSFVMYsk08kI8fSplsLfvM/j0S5rDI9SFo4e/CgrOE@RpVIebZdQkLBRS2TI4MIx2kSbVoHw3kqNLojOpiO0Cub8nklaX2FvrzL0NBy/YNOlGiNPOt83opm1MbfXU7kF6HRFEZ8Vj5hgDBOkDx9kLr/2H4wpxdpxbOwX "Python 3 – Try It Online") * saved 7 bytes thanks to [Jonathan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) and [Shooqie](https://codegolf.stackexchange.com/users/51530/shooqie) * saved 1 byte: Also Fixed the false positive issue. Thanks to [Jonathan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for pointing it out! * added 11 bytes: Previous edit was wrong(the multiplication of sum of digit was going on in an unwanted loop) [Answer] # Retina, 143 bytes Returns 1 for true, 0 for false ``` [1-9] $* 10|01 1 S_`(\D) O` {`1(?=1*\n(1+)) $1 )2=`1+\n [J-S] 1$+ [T-Z] 2$+ T`0L`ddd 1>`\d+\n? $* ^((?(1)((?(2)\2(11)|111))|1))*\n ^(1*)\n\1$ ``` [Try it Online!](https://tio.run/nexus/retina#FY4xCoNAFET7OccG/leEnQ0YUhhZExRCIIVWcTVbWHuBeHezNo9XDI85SRf3kcV1gslAu1mC6L9RwkPxjvhFSl0xC6swV4Uh1FWReViB8Vn0E2hyjEPxmeCSDdG@4rIs4C2GJc3qozyL1EI96DQ4IXVjQqJqdrRmYaZhDTT7TnpvYb0nUV7aNn1i0zh4Nu5@hmVXEtY1fw) **Explanation:** ``` [1-9] $* 10|01 1 ``` First, we replace all non-zero digits with their unary representation. We remove any zeroes with an adjacent digit so that they don't affect our unary operations ``` S_`(\D) ``` Split the resulting string on letters, being careful to exclude empty lines (this is a problem when two letters are consecutive `AA`). ``` O` {`1(?=1*\n(1+)) $1 )2=`1+\n ``` Sort the string lexicographically. Then repeatedly do the following: 1) Replace each `1` with the number of `1`s on the following line (this mimics multiplication) 2) Remove the second line of `1`s ``` [J-S] 1$+ [T-Z] 2$+ T`0L`ddd ``` Replace letters `J-S` with `1J`, `1K`, etc. and replace letters `T-Z` with `2T`, `2U`, etc. Then, replace each of the groups `A-I`, `J-S`, and `T-Z` with `1-9`. We will be left with the numerical value of each letter (eg. `13` for `M`). ``` 1>`\d+\n? $* ``` Convert every line but the first into unary (the first line is already in unary). Concatenate these lines. We are now left with a string of the form `<product of digits>\n<sum of letters>`. ``` ^((?(1)((?(2)\2(11)|111))|1))*\n ``` Replace a square number with the empty string. This uses the ["difference tree" method](https://codegolf.stackexchange.com/a/19413/65425). ``` ^(1*)\n\1$ ``` Return `1` if the two strings on either side of the `\n` match. Otherwise, return `0`. [Answer] # [Ruby](https://www.ruby-lang.org/), 87 bytes ``` ->s{m=0 n=1 s.scan(/(\d+)|./){$1?n*=$1.bytes.sum{_1-48}:m+=$&.ord-64} m==n&&m**0.5%1>0} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3w3XtiqtzbQ248mwNuYr1ipMT8zT0NWJStDVr9PQ1q1UM7fO0bFUM9ZIqS1KB0qW51fGGuiYWtVa52rYqanr5RSm6Zia1XLm2tnlqarlaWgZ6pqqGdga1UONNChTcopUcDZ2MnI2VYrnAPANDdzNDGMfQ0MnJCMYxM3dzA8pA9C5YAKEB) ]
[Question] [ (Meaning: Convert English to Bleet) We have praised goats as god for years now. But if we can't translate English to 'Bleet', the Goat God's language, we cannot communicate with them. So, to communicate with them, we have researched the activities of goats, and retrieved this pattern, which is the core of the language. > > Say 'Bleet' for the length of each words. That means the amount of 'e's should be (length-3) for words longer than 3 letters.You shall cut down 'Bleet' for words shorter than 'Blt'. For example, 'be' becomes 'bl', but 'cat' and 'boat' becomes 'blt' and 'blet'. > > > As it seems, they don't actually change non-alphabet characters to 'Bleet'. Our research showed that 'Hello, World!' to Bleet is 'Bleet, Bleet!' not 'Bleeet Bleeet'. Also, The goats are not so intelligent(no offense), so they don't seem to understand non-ascii characters or diacritics at all. Now, It's time to make a translator to communicate with the goat gods. ## Bleeeeet (Meaning: Examples) ``` Hello, World! => Bleet, Bleet! lorem ipsum dolor sit amet. => Bleet Bleet Bleet Blt Blet. We praise the Goat God! => Bl Bleeet Blt Blet Blt! I have a pen => B Blet B Blt 0123456789_ => 0123456789_ 0te_st1 => 0Bl_Bl1 ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 31 bytes ``` T`lL`e (?<!e)e B Be Bl e(?!e) t ``` [Try it online!](https://tio.run/nexus/retina#DcvLCsIwEEbh/TzFdFdBpPVaQSh0o4JLocs20B8amJiQjL5@zObAtzj5PctrBtX9rcIGNNBQIoS6LybN@QERv@XRR1kqEh/h2Ib0dbz4Ik5W2TjojkZwiMYmsK7guzdaUp4nr@YHNhzwoabdH46n86W7TtQopqTtHw "Retina – TIO Nexus") ### Explanation ``` T`lL`e ``` Turn all letters into `e`s. ``` (?<!e)e B ``` Turn the first `e` in each run into `B`. ``` Be Bl ``` Turn `Be` into `Bl`. ``` e(?!e) t ``` Turn the last `e` in each run into `t`. [Answer] # JavaScript (ES6), ~~79~~ ~~77~~ 74 bytes ``` s=>s.replace(/[A-Z]+/gi,x=>x.replace(/./g,(_,i)=>'Bl'[i]||'et'[+!x[i+1]])) ``` Alternate approach, currently ~~83~~ 78 bytes: ``` s=>s.replace(/[A-Z]+/gi,x=>`Bl${'e'.repeat((l=x.length)>3&&l-3)}t`.slice(0,l)) ``` The best I could do recursively was 88 bytes: ``` f=([c,...s],i=0,q=/^[A-Z]/i)=>c?q.test(c)?('Bl'[i]||'te'[+q.test(s)])+f(s,i+1):c+f(s):'' ``` [Answer] # PHP, ~~115~~ ~~88~~ ~~86~~ ~~77~~ 75 bytes `preg_replace` with arrays (requires PHP 5.4 or later) ``` echo preg_replace(["#[a-z]#i","#(?<!e)e#",_Be_,"#e(?!e)#"],[e,B,Bl,t],$argn); ``` Run with `echo '<string>' | php -nR '<code>'` or [test it online](http://sandbox.onlinephpfunctions.com/code/334c9595c1b546d163fbd0a44ad877804fa5d97c). **breakdown** ``` SEARCH EXPLANATION REPLACE EXAMPLE original string Hello [a-z] every letter e eeeee (?<!e)e first letter B Beeee Be first two letters Bl Bleee e(?!e) last letter if still e t Bleet ``` Revision 5: saved 9 bytes with [Martin Ender´s regex chain](https://codegolf.stackexchange.com/a/112556/55735). (That also fixed cases with non-alphabetic word characters = digits/underscores.) [Answer] # [Haskell](https://www.haskell.org/), ~~135~~ 128 bytes ``` b"e"="B" b"ee"="Bl" b('e':_:_:e)="Bl"++e++"t" b e=e e!(l:t)|elem l$['a'..'z']++['A'..'Z']=('e':e)!t|1<3=b e++l:""!t e!_=[] (""!) ``` [Try it online!](https://tio.run/nexus/haskell#nY4xCsMwDEX3nMIRBcUIAqWbiYb2GDUmxEWBgJOheCq5u6u40LkULU9ffPFKBAGGGzQKlZJih4Ju1BFbEyIhgqwXIyyNtF1y2e6SZDXp5HHCvscXBiKP14PvGLg@Edvm/TxcWJtEyQG0Wfsj@9DM3Olqyzotm2GzbFme0yObufwjFX@Xil8p51P4OMXDKVapyMNg@@r2Bg "Haskell – TIO Nexus") Usage `(""!) $ "some string"`. Without regexes, this turned out to be quite long, maybe some other approach is shorter. Edit: Saved 7 bytes thanks to @nimi! [Answer] # [Perl 5](https://www.perl.org/), 47 bytes Saved 15 bytes by using the same technique as Martin Ender's [Retina answer](https://codegolf.stackexchange.com/a/112556/55508). (This answer is basically a port of his answer now) 46 bytes of code + `-p` flag. ``` s/\pl/e/g;s/(?<!e)e/B/g;s/Be/Bl/g;s/e(?!e)/t/g ``` [Try it online!](https://tio.run/nexus/perl5#HYvLCsIwEEX3@Yopbiqo0/oWBaEb9Qu6EUqgl7YwNSEZ/f0aurmcc@AuMo8gtPZT5LcXBnfXyPn9lmEJrmarEshMyO@ps3I3TU@IuBXVLkibGXEBIw0@fkdqXTKKg5IdoRtTg3ywQwRpD3o4q2nS50W9/YEseXxMUW53@8PxdL40plA0Ucs/ "Perl 5 – TIO Nexus") --- Older versions: 62 bytes: ``` s/\pl+/$l=length$&;$_=Bl.e x($l-3).t;chop while$l<y%%%c;$_/ge ``` And 68 bytes: ``` s%\pl+%$_=$&;s/./B/;s/.\K./l/;s/(?<=..).(?=.)/e/g;s/..\K.$/t/;$_%ge ``` [Answer] # PHP, 84 Bytes ``` <?=preg_replace(["#[a-z]#i","#(?<!l)l#","#(?<=l)l#","#e(?!e)#"],[l,B,e,t],$argv[1]); ``` # PHP, 117 Bytes ``` <?=preg_replace_callback("#[a-z]+#i",function($m){return substr(str_pad(Bl,-1+$l=strlen($m[0]),e).t,0,$l);},$argv[1]); ``` [Answer] # C, ~~120~~ ~~151~~ ~~140~~ ~~111~~ ~~108~~ ~~105~~ ~~104~~ ~~92~~ 90 Bytes Working for "It's Jimmy's test" --> Bl'B Bleet'B Blet ``` j;f(char*m){for(;*m=!isalpha(*m++)?j=0,*(m-1):"*Blet"[isalpha(*m)?j^3?++j:j:j>1?4:++j];);} ``` The output is now a side effect by destroying the original string. ``` main(c,v)char**v;{ char test[] = "The End is near Fellows!"; f(test);puts(test); char test2[] = "We praise the Goat God!"; f(test2);puts(test2); char test3[] = "It's Jimmy's test"; f(test3);puts(test3); char test4[] = "0te_st1"; f(test4);puts(test4); char test5[] = "I have a pen"; f(test5);puts(test5); char test6[] = "_0123456789_"; f(test6);puts(test6); } ``` I think it's correct at least now ``` Blt Blt Bl Blet Bleeeet! Bl Bleeet Blt Blet Blt! Bl'B Bleet'B Blet 0Bl_Bl1 B Blet B Blt _012345678_ ``` [Answer] # Python 2.7, 129 118 114 109 95 91 88 bytes ``` import re s=re.sub def f(i):print s(r"e\b","t",s("Be","Bl",s(r"\be","B",s("\w","e",i)))) ``` Just an `re.sub` chain ### Step by step Example input: "**We praise the Goat God!**" --- **Alias sub so we can save bytes on repeated calls** ``` import re s=re.sub ``` **Replace all word characters with "e"** `s("\w","e",i)` Output: `ee eeeeee eee eeee eee!` **Replace all "e"s which are preceded by a word boundary (Beginning of word) with "B"** `s(r"\be","B",s("\w","e",i))` Output: `Be Beeeee Bee Beee Bee!` **Replace all "Be" with "Bl"** `s("Be","Bl",s(r"\be","B",s("\w","e",i)))` Output: `Bl Bleeee Ble Blee Ble!` **Replace all "e"s which are followed by a word boundary with "t"** `s(r"e\b","t",s("Be","Bl",s(r"\be","B",s("\w","e",i))))` Output: `Bl Bleeet Blt Blet Blt!` [Answer] # [Pip](https://github.com/dloscutoff/pip), 28 bytes ``` aR+XA{Y'eX#a-3\"Bl\yt\"@<#a} ``` Takes input as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@58YpB3hWB2pnhqhnKhrHKPklBNTWRKj5GCjnFj7//9/x0T1RIXERDCGEFDSQxEA "Pip – TIO Nexus") ### Explanation This was fun--I got to use regex modifiers and string interpolation. ``` a is 1st cmdline arg; XA is the regex `[A-Za-z]` (implicit) aR In a, replace XA the regex XA + wrapped in (?: )+ { } with this callback function: #a-3 Length of argument - 3 'eX Repeat e that many times (empty string if #a-3 is negative) Y Yank that string into the y variable \"Bl\yt\" An escaped string, which interpolates the value of y @<#a Take first len(a) characters After the replacement, the string is autoprinted ``` [Answer] # Python 3, 271 bytes I am aware that this is rather long and I welcome suggestions on how to reduce the length. ``` def f(s): b=[];t='';f=[];a=list.append for c in s: if c.isalpha():t+='e' else: if t:a(b,t);t='' a(b,c) if t:a(b,t) for i in b: i=[*i] if i[0]=='e': i[0]='B';i[-1]=[i[-1],'t'][len(i)>2] if len(i)>2:i[1]='l' a(f,''.join(i)) return ''.join(f) ``` [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 57 bytes ``` '\l+'{!n size 2-:4\^5*1+3/\1<-4 tb 0\,'Blet'\#''join}repl ``` [Try it online!](https://tio.run/nexus/stacked#fVBLT8JAEL7vr/gaDgNSkPLwQcREDj4Sbx64NJIVxrS6ZZvuYoiE3w67LZpqopfZ@R4zm/madM9K6RAzXahlQAKkdMEZ0tysMyy1QzCphczYdr08Y@SFTA3DJow7La0r1eQDEvnBkMh55XEv6g@Go7Pzi8t5CS3PjY0ILWyxwRibPcWqTdtg5b74ZPQ742H8PDqJ2oPTOLrqDGFf0ItDmiq2FDeI3nS62hWcq/0GMUIQJteueBo7ZDLH422FeJFoD/Taip83@hG3kG1YPYH45@Jv869adrYr/kijGivdNbtvAlFPqfQdNa@KWmReq0FxjK@kp2o@VS7JCZr0pDPGIuHFu8GrTBUvCXSj1BeXS2Mc13KBNXwc@wM "stacked – TIO Nexus") Takes input from the top of the stack. Let **a**(**n**) = [A136412](https://oeis.org/A136412)(**n** - 2) = (5 × 4**n** − 2 + 1) ÷ 3. Converting **a**(**n**) to base 4 yields: ``` a(3) = 134 a(4) = 1234 a(5) = 12234 a(6) = 122234 ... ``` Mapping indices 0..3 to the string `Blet`, we get: ``` a(3) = lt a(4) = let a(5) = leet a(6) = leeet ... ``` Now, prepending `B` gives us the desired string, given the length. Mostly. One just needs to handle the special cases for **n** ≤ 2. In my case, this is solved by subtracting (**n** − 2 < 1) as a numeric boolean (1 for "true" and 0 for "false"). As for the specifics of the answer: ``` '\l+'{! ... }repl repl replace all '\l+' alphanumeric strings ("letters") {! } applying this function to the result. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~137~~ 114 bytes ``` def f(s,r='',l=-3): for c in s+'\0': if c.isalpha():l+=1 else:r+=('Bl%st'%('e'*l))[:l+3*(l>=0)]+c;l=-3 print r ``` [Try it online!](https://tio.run/nexus/python2#HYxBCsMgFETX9RR/E77GVFKys9hFr9GWIolS4ScRNfT4aSzMDPNgmH1yHjzPXTKIHZnzIDQDvyYYISyQJT571OwUPIwqZEvxY7nQJM2FnRxlp5M0HO/U5IINR4ctCfE4BkPL6WZ68ZLjtf4yiCksBdLuebLfd1jiVrgQO63JzRBi3maY1oMghwJ2dkWBBVv195GhYK5VKVX5Bw "Python 2 – TIO Nexus") [Answer] # Java 7, 201 bytes ``` String c(String s){String r="",z="e([^e]|$)";char p=0;int x;for(char c:s.toCharArray()){x=c&~32;p=x>64&x<91?p==66?'l':p>100&p<109?'e':66:c;r+=p;}return r.replaceAll("l"+z,"lt$1").replaceAll(z,"et$1");} ``` Not really happy with it, and can certainly be golfed some more.. **Explanation:** ``` String c(String s){ // Method with String parameter and String return-type String r="", // The return-String z="e([^e]|$)"; // Partial regex String that's used twice ('e' followed by non-'e' or nothing) char p=0; // The previous character int x; // Another temp value for(char c : s.toCharArray()){ // Loop over the characters of the input String x = c&~32; // Make every lowercase character uppercase (this returns an integer, hence the integer temp value, which is shorter than a cast to char) p = x>64 & x<91 ? // If the current character is a letter: p == 66 ? // And if the previous character is 'B': 'l' // Set the character value to 'l' : p>100&p<109 ? // Else if the previous character is either an 'e' or 'l': 'e' // Set the character value to 'e' : // Else: 66 // Set the character value to 'B' : // Else (not a letter): c; // Set the character to the current character r += p; // Append the result-String with this character } // End loop return r // Return the result-String .replaceAll("l"+z,"lt$1") // After we've replaced all occurrences of "le." with "lt." (where "." can be anything else, including nothing at the end of a line) .replaceAll(z,"et$1") // And also replaced all occurrences of "ee." with "et." (where "." can again be anything else) } // End of method ``` **Test code:** [Try it here.](https://ideone.com/WjcpbS) ``` class M{ static String c(String s){String r="",z="e([^e]|$)";char p=0;int x;for(char c:s.toCharArray()){x=c&~32;p=x>64&x<91?p==66?'l':p>100&p<109?'e':66:c;r+=p;}return r.replaceAll("l"+z,"lt$1").replaceAll(z,"et$1");} public static void main(String[] a){ System.out.println(c("Hello, World!")); System.out.println(c("lorem ipsum dolor sit amet.")); System.out.println(c("We praise the Goat God!")); System.out.println(c("I have a pen")); System.out.println(c("0123456789_")); System.out.println(c("0te_st1")); } } ``` **Output:** ``` Bleeet, Bleeet! Bleeet Bleeet Bleeet Blt Bleet. Bl Bleeeet Blt Bleet Blt! B Bleet B Blt 0123456789_ 0Bl_Bl1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 36 bytes ``` lDAsSå.¡€g£vyAySåPigÍ<'e×"Blÿt"yg£}J ``` [Try it online!](https://tio.run/nexus/05ab1e#@5/j4lgcfHip3qGFj5rWpB9aXFbpWAnkB2SmH@61UU89PF3JKefw/hKlSqBcrdf//wYlqfHFJYYA) or as a [Test suite](https://tio.run/nexus/05ab1e#qymrrAz9n@PiWBx8eKneoYWPmtakH1pcVulYCeQHZKYf7rVRTz08Xckp5/D@EqVKoFyt1//aCKXD@60UDu9X0vnvkZqTk6@jEJ5flJOiyJWTX5Saq5BZUFyaq5CSD@QpFGeWKCTmppbocYWnKhQUJWYWpyqUZKQquOcnlgAJoB5PhYzEslSFRIWC1DwuA0MjYxNTM3MLy3gug5LU@OISQwA) **Explanation** Prepare input: ``` lD # convert input to lower-case and duplicate As # push lower-case alphabet and swap input to the top Så # check each char in input for # membership in the alphabet .¡ # split into chunks of equal elements €g # get length of each chunk £ # split input into chunks of those lengths ``` This creates a list such as `['hello', ', ', 'world', '!']` for the input `Hello, World!` Iterate over list: ``` v # for each element in the list y # push current element AySåPi } # if all members of current element are letters gÍ<'e× # repeat string "e" len(element)-3 times "Blÿt" # replace "ÿ" with the e's in the string "Blÿt" yg£ # take the first len(element) chars of the string J # join to string ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 58 bytes Port of [Martin Ender's Retina answer](https://codegolf.stackexchange.com/a/112556/11261). ``` s/[a-z]/e/gi s/(^|[^e])e/\1B/g s/Be/Bl/g s/e([^e]|$)/t\1/g ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3rYr1oxN1q2L1U_XTM7mK9TXiaqLjUmM1U_VjDJ3004EiTqn6TjlgVqoGSKpGRVO_JMZQPx1iAtSgBdvDUxUKihIzi1MVSjJSFdzzE0uARIoiRBoA) ]
[Question] [ A brace string is defined as a string consisting of the characters `*()[]` in which braces match correctly: ``` [brace-string] ::= [unit] || [unit] [brace-string] [unit] ::= "" || "*" || "(" [brace-string] ")" || "[" [brace-string] "]" ``` This is a valid brace-string: ``` ((())***[]**)****[(())*]* ``` But these are not: ``` )( **(**[*](**) **([*)]** ``` Your task is to write a program (or function) that, given a positive integer `n`, takes a number as input and outputs (or returns) all valid brace strings of length `n`. ## Specifications * You may output the strings in any order. * You may output as a list or a string separated by a different character. * Your program must handle 0 correctly. There is 1 possible brace-string of length 0, which is the empty string `""`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases ``` 0. 1. * 2. ** () [] 3. *** ()* []* (*) [*] *() *[] 4. **** ()** []** (*)* [*]* (**) **() **[] *(*) *[*] (()) ()() ()[] ([]) [**] [()] [[]] []() [][] *()* *[]* ``` [Answer] # Prolog, 69 bytes ``` s-->[];e,s. e-->"*";"(",s,")";"[",s,"]". b(N,A):-length(A,N),s(A,[]). ``` One of the most interesting properties of Prolog is that in many cases it's capable of running a program backwards; for example, instead of testing to see if something's true, you can generate all solutions for which it's true, and instead of checking the length of a string, you can generate all strings with a given length. (Another nice property of Prolog is that it requires whitespace after the end of each predicate definition, and a newline can be inserted as cheaply as a space; thus even golfed programs are often fairly readable.) The above defines a predicate (the equivalent of a function) `b` which tests to see if a string has a given length and is a "brace string" as defined in the question. Specifically, it does this via Prolog's grammar/regex/pattern-match support that gives some nice, short sugar for defining this sort of expression (apparently this is standard/portable, but I was unaware of this while originally writing the answer, and thus assumed the answer would work on only one Prolog implementation; it seems it works on every implementation that complies with the standards, though). The program can be translated into English fairly directly; the first two lines say "an *s* is an empty string, or an *e* followed by an *s*; an *e* is an asterisk, or an *s* in parentheses, or an *s* in square brackets". The third line can be interpreted as "The *b* of *N* can be *A* if *A* is a list with length *N* and *A* is an *s* followed by a null string." I took some care to write `s` (and thus `b`) so that they match each "brace string" in exactly one way (which is the reason that both `s` and `e` have to exist, rather than grouping them into one predicate). This makes them both entirely reversible; thus `b` can be used to generate all "brace strings" of a given length, in addition to testing if a string is a brace string of a given length (it can also be used a third way round, to figure out the length of a brace string, but that is almost certainly its least useful mode of operation). The implementation is recursive, e.g. to generate an *s*, the code will generate all possible *e*s that are no longer than the required length of the output, and append all possible *s*s that fit in the remaining space to them; because I specified the length of the argument in advance (within *b*), the Prolog engine knows that it can't generate output that's longer than the given length, which allows the recursion to terminate. Here's an example of the program in operation: ``` | ?- b(4,A),format("~s ",[A]),fail. **** **() **[] *()* *(*) *[]* *[*] ()** ()() ()[] (*)* (**) (()) ([]) []** []() [][] [*]* [**] [()] [[]] ``` [Answer] ## Haskell, ~~101~~ 94 bytes 7 bytes saved by Zgarb! ``` b 0=[""] b n=[x++y|k<-[1..n],x<-u k,y<-b$n-k] u 1=["*"] u n=[a:s++b|s<-b$n-2,a:b<-["()","[]"]] ``` Almost straightforward, following the definition, but with the `""` case moved. Use: ``` *Main> map b [0..3] [[""],["*"],["**","()","[]"],["***","*()","*[]","()*","[]*","(*)","[*]"]] *Main> length $ b 10 21595 ``` (The second computation takes less than a second on a slow machine.) I'd also like to share the result of another approach I came up with while thinking about generating functions. It defines a *list* `b` of lists of strings such that `b!!n` contains all brace-strings of length `n`. Similarly, `u!!n` contains all atoms of size `n-1`. One nice thing is that the code is not using any numbers. It is not completely golfed: `u` and `i` could be inlined, and it certainly misses a few other golfing opportunities. Unfortunately, it doesn't look like it can be made shorter than the first version, but it computes `length $ b !! 10` even faster. ``` b=[""]:b%u u=["*"]:map i b i=concatMap(\s->['(':s++")",'[':s++"]"]) (b:c)%f=zipWith(++)[[x++y|x<-b,y<-e]|e<-f]([]:c%f) ``` [Answer] # Mathematica, 116 bytes ``` #<>""&/@Select[Characters@"*([)]"~Tuples~#,(#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}&]& ``` # Explanation ``` Characters@"*([)]" ``` Find the characters of the string `"*([)]"`, giving the `List` `{"*", "(", "[", ")", "]"}`. ``` ... ~Tuples~# ``` Find the tuples of the above list with length `n`. ``` (#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}& ``` Unnamed Boolean function to find whether the tuple is balanced: ``` #/."*"->Nothing ``` Delete all `"*"` in the input. ``` ... //.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b} ``` Repeatedly delete all consecutive occurrences of `"("` and `")"` or `"["` and `"]"` until the input does not change. ``` ... =={} ``` Check whether the result is an empty `List`. ``` Select[ ... , ... ] ``` Find the tuples that give `True` when the Boolean function is applied. ``` #<>""&/@ ``` Convert each `List` of characters into `String`s. [Answer] # Python 2, 128 bytes ``` n=input() for i in range(5**n): try:s=','.join(' "00([*])00" '[i/5**j%5::5]for j in range(n));eval(s);print s[1::4] except:1 ``` Screw recursive regexes – we’re using Python’s parser! In order to verify that, for example, `*(**[])*` is a brace-string, we do the following: 1. Make a string like `"*", (0,"*","*", [0,0] ,0) ,"*"`, where every second character of four is a character from the brace-strings, and the remaining characters are *glue* to make this a potential Python expression. 2. `eval` it. 3. If that doesn’t throw an error, print `s[1::4]` (the brace-string characters). The *glue* characters are picked so that the string I make is a valid Python expression if and only if taking every second character out of four yields a valid brace-string. [Answer] # Jelly, 29 bytes -3 bytes thanks to @JonathanAllan *Please*, alert me if there are any problems/bugs/errors or bytes I can knock off! ``` “[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐLÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xoDS3N2EcNcx/unH5o68Md84FMraOTH@5c/Khxn4amG4wZHet2aOvhCT6HJwDVcB1ud////78xAA) The previous solution(s) I had: ``` “[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị “[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị “[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị “[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐLµ€Ṇ€×Jḟ0ị ``` Explanation (My best attempt at a description): ``` Input n “[(*)]”ṗ-All strings composed of "[(*)]" of length n µḟ”* -Filter out all occurences of "*" œṣ⁾() -Split at all occurences of "()" F -Flatten œṣ⁾[] -Split at all occurences of "[]" F -Flatten µÐL -Repeat that operation until it gives a duplicate result Ðḟ -Filter ``` [Answer] # PHP, 149 bytes ``` for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l)); ``` Uses the good old generate all possible and then filter method. Use like: ``` php -r "for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l));" 4 ``` [Answer] # Python, 134 bytes ``` from itertools import* lambda n:[x for x in map(''.join,product('*()[]',repeat=n))if''==eval("x"+".replace('%s','')"*3%('*',(),[])*n)] ``` **[repl.it](https://repl.it/Eb1x)** Unnamed function that returns a list of valid strings of length `n`. Forms all length `n` tuples of the characters `*()[]`, joins them into strings using `map(''.join,...)` and filters for those that have balanced brackets by removing the "pairs" `"*"`, `"()"`, and `"[]"` in turn `n` times and checking that the result is an empty string (`n` times is overkill, especially for `"*"` but is golfier). [Answer] ## [Retina](http://github.com/mbuettner/retina), 78 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* +%1`1 *$'¶$`($'¶$`)$'¶$`[$'¶$`] %(`^ $'; )+`(\[]|\(\)|\*)(?=.*;)|^; A`; ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKyUxYDEKKiQnwrYkYCgkJ8K2JGApJCfCtiRgWyQnwrYkYF0KJShgXgokJzsKKStgKFxbXXxcKFwpfFwqKSg_PS4qOyl8XjsKCkFgOw&input=NQ) ### Explanation I'm generating all possible strings of length 5 and then I filter out the invalid ones. ``` .+ $* ``` This converts the input to unary, using `1` as the digit. ``` +%1`1 *$'¶$`($'¶$`)$'¶$`[$'¶$`] ``` This repeatedly (`+`) replaces the first (`1`) one in each line (`%`) in such a way that it makes five copies of the line, one for each possible character. This is done by using the prefix and suffix substitutions, `$`` and `$'` to construct the remainder of each line. This loop stops when there are no more 1s to replace. At this point we've got all possible strings of length `N`, one on each line. ``` %(`^ $'; )+`(\[]|\(\)|\*)(?=.*;)|^; ``` These two stages are executed for each line separately (`%`). The first stage simply duplicates the line, with a `;` to separate the two copies. The second stage is another loop (`+`), which repeatedly removes `[]`, `()` or `*` from the first copy of the string, *or* removes a semicolon at the beginning of the line (which is only possible after the string has vanished completely). ``` A`; ``` Valid strings are those that no longer have a semicolon in front of them, so we simply discard all lines (`A`) which contain a semicolon. [Answer] # Python 3.5, 146 bytes ``` import re;from itertools import*;lambda f:{i for i in map(''.join,permutations("[()]*"*f,f))if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)} ``` Very long compared to other answers, but the shortest one I could currently find. It is in the form of an anonymous lambda function and therefore must be called in the format `print(<Function Name>(<Integer>))` Outputs a Python *set* of *unordered* strings representing all possible brace-strings of the input length. For example, assuming the above function is named `G`, invoking `G(3)` would result in the following output: ``` {'[*]', '*()', '*[]', '(*)', '***', '[]*', '()*'} ``` [Try It Online! (Ideone)](http://ideone.com/6QBiBM) --- However, if, like me, you aren't really a fan of simplifying things using built-ins, then here is my own *original* answer *not* using *any* external libraries to find permutations, and currently standing at a whopping **~~288~~ 237 bytes**: ``` import re;D=lambda f:f and"for %s in range(%d)"%(chr(64+f),5)+D(f-1)or'';lambda g:[i for i in eval('["".join(('+''.join('"[()]*"['+chr(o)+'],'for o in range(65,65+g))+'))'+D(g)+']')if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)] ``` Again, like the competing answer, this one is in the form of a lambda function and therefore must also be called in the format `print(<Function Name>(<Integer>))` And outputs a Python *list* of *unsorted* strings representing all brace-strings of the input length. For example, if the lambda were to be invoked as `G(3)`, this time the output would be the following: ``` ['*()', '(*)', '*[]', '[*]', '()*', '[]*', '***'] ``` Also, this one is also a lot faster than my other answer, being able to find all brace-strings of length `11` in about **115 seconds**, those of length `10` in about **19 seconds**, those of length `9` in about **4 seconds**, and those of length `8` in about **0.73 seconds** on my machine, whereas my competing answer takes *much* longer than 115 seconds for an input of `6`. [Try It Online! (Ideone)](http://ideone.com/BgBlfl) [Answer] # 05AB1E, 23 bytes ``` …[(*.∞sãʒ'*м„()„[]‚õ:õQ ``` Some of these features might have been implemented after the question was posted. Any suggestions are welcome! [Try it online!](https://tio.run/##MzBNTDJM/f//UcOyaA0tvUcd84oPLz41SV3rwp5HDfM0NIFEdOyjhlmHt1od3hr4/78JAA) # How? ``` …[(* - the string '[(*' .∞ - intersected mirror, '[(*'=>'[(*)]' s - swap the top two items, which moves the input to the top ã - cartesian power ʒ ... - filter by this code: '*м - remove all occurrences of '*' „()„[]‚ - the array ["()","[]"] õ - the empty string "" : - infinite replacement (this repeatedly removes "()", "[]", and "*" from the string õQ - test equality with the empty string ``` ]
[Question] [ Write a program or a function that outputs the integer number of answers this question has. Your solution should still work as more answers are added. Languages that run in a browser may be run from the js console while on this page. Otherwise, you'd probably have to download this page. Multi-language solutions, e.g. `wget`ing the page and parsing it using `grep` is ok. Just sum up the command line and all source used. This is code golf; shortest answer in bytes wins. EDIT: Let's allow at most one occourance of the url of this page to not count, either as input or in the source. No url shorteners, no data stored as get parameters etc. Quotes around url, if needed, still count. Taking the url as input is also fine. If you want to remove some part of the url, e.g. `/how-many-answers...`, you can, but it probably doesn't help you. [Answer] ## Javascript + jQuery, 23 bytes ``` _=>+$("h2>span").text() ``` [Answer] # Mathematica, 33 bytes ``` Length@Import[#,"Data"][[4,2]]-1& ``` The input is the url of this page. [Answer] ## Python 2, 120 bytes, 79 w/o URL I can't say Python was made for this challenge. ``` import urllib print[l for l in urllib.urlopen("http://codegolf.stackexchange.com/q/96298")if"answerCount"in l][0][83:-9] ``` Unfortunately, inline import is the same length :( Any help with golfing this further would be greatly appreciated! If the URL (a whopping 41 bytes—over 1/3 my byte count) can be taken as input, it is 82 bytes: ``` import urllib lambda u:[l for l in urllib.urlopen(u)if"answerCount"in l][0][83:-9] ``` [Answer] ## Javascript, 67 bytes ``` alert($(".answers-subheader").children().first().children().html()) ``` This look way too long [Answer] # Javascript (ES5), ~~46~~ ~~44~~ ~~40~~ ~~38~~ 33 bytes ``` _=>parseInt($('#answers').text()) ``` 5 bytes saved thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) **Note:** This is pretty slow, and won't work if you have the PPCG-Design userscript. [Answer] # CJam, 15 bytes ``` lg"2>"/1=A>S/0= ``` Expects this page's URL as input. ### How it works ``` l e# Read a line (the URL) from STDIN. g e# Fetch the resource the URL points to. "2>"/ e# Split the source at occurrences of "2>". 1= e# Select the second chunk, i.e., everything between the first e# <h2> and the first </h2>. A> e# Discard the first 10 characters (a linefeed and 9 tabs). S/0= e# Split at spaces and select the first chunk. ``` [Answer] # 171 bytes bash + 3 keys lynx ``` lynx -cfg=<(echo PRINTER:Answercount:grep [0-9]*.Answers %s|less:FALSE:999') http://codegolf.stackexchange.com/questions/96298/how-many-answers-does-this-question-have ``` [Answer] ## 99 bytes sh + curl + jq + stackexchange API ``` curl -s --compressed api.stackexchange.com/questions/96298/answers?site=codegolf|jq .items\|length ``` Using the API, I was able to avoid issues related to page formatting and html. Unfortunately, 60 bytes of my answer are the maximally golfed url for this particular api query, and another 13 bytes for curl to unzip the resulting of the query, because stackexchange refuses to serve uncompressed data via the api. The actual "logic" comes from curling the api to ask for a json reply with the answers to this post. That is unzipped and then piped into jq, a json parser, which extracts the "items" array and outputs its length. You can get impressively close to having the api just return the number of answers, but from what I could come up with you could not get 100% of the way there, and getting closer would cost more bytes than just passing it through jq. ## 101 bytes to return {"total":}: ``` curl -s --compressed api.stackexchange.com/questions/96298/answers?site=codegolf&filter=!)V)MSZJUgX_ ``` The filter parameter in api queries is very powerful, but it falls just short of providing a "just curl a url" solution. There may be a middle ground here, where you can get a shorter response and then just count the lines or extract the number, but unfortunately filter strings are a set length, and the required jq command was already more efficient. [Answer] ## PHP, 76 (Code) + 41 (URL) = 117 bytes ``` preg_match_all('<h2>(.*) answers<span',file_get_contents("http://codegolf.stackexchange.com/q/96298"),$o); echo $o[0]; ``` [Answer] # Java, ~~230~~ 269-41=228 bytes ``` interface A{static void main(String[]a)throws Exception{System.out.print(new java.util.Scanner(new java.net.URL("http://codegolf.stackexchange.com/q/96298").openStream()).useDelimiter("\\Z").next().replaceAll("\n|\r","").replaceAll("^.+?\\s+(\\d+) Answers.+$","$1"));}} ``` (Only counts non-deleted answers) [Answer] ## JavaScript + jQuery (already included in page), 20 bytes ``` +$('h2>span').text() ``` This is a program intended to be executed in the console for the current page (opened with `F12`). It outputs the number of answers, without quotation marks. It works in Chrome, Firefox, IE11, and Edge. It should work in other browsers, but I have only tested it in those listed. Unlike other JavaScript solutions here, it is a program by itself rather than a [function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function) using [ES6 arrow function notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). Also unlike those solutions, it actually produces output (without quotes) in the console with the number of answers (rather than just being a function expression which produces no output). Producing output relies on the feature in each browser's console that the value of an expression is output after that expression has been evaluated. This relies on the only `<span>` on the page with a parent that is an `<h2>` element is the one containing the number of answers as its text content. After experimentation, this appears to be the case, and it does not appear possible to intentionally create an `<h2>` with a `<span>` child using the editor: all explicitly inserted `<span>` elements are stripped and no [Markdown](http://daringfireball.net/projects/markdown/syntax), as used on Stack Exchange, creates an actual `<span>` within an `<h2>`. If someone can demonstrate a case where the page can be manipulated such that `'h2>span'` selector is no longer unique, then this will need to be revised. If evaluating to a string instead of a number is acceptable, then ## JavaScript + jQuery (already included in page), 19 bytes ``` $('h2>span').text() ``` However, while this does not evaluate to include `""`, in all tested consoles it produces output which is enclosed within `""`. I read Filip Haglund's comments on the question as precluding this output. [Answer] # R, 80 bytes Answer is based on searching the vector returned by `readLines` using regular expressions. I'm guessing that this could be broken by text in comments/answers (possibly even my own). Will delete if so. Also the pattern could also be gofled but not sure if that would increase the likelihood of getting a false value. ``` x=readLines(scan(,""));regmatches(x,regexpr("(?<=answerCount\">).*?(?=<)",x,,T)) ``` ]
[Question] [ Given the size of the chess board and initial position of the knight, calculate the probability that after `k` moves the knight will be inside the chess board. Note: * The knight makes its all 8 possible moves with equal probability. * Once the knight is outside the chess board it cannot come back inside. ![enter image description here](https://i.stack.imgur.com/dK5au.png) **Input** Inputs are comma separated in the form: ``` l,k,x,y ``` where `l` is the length and width of the chess board, `k` is the number of moves the knight will make, `x` is the x-position of the initial position of the knight, and `y` is the y-position of the initial position of the knight. Note that `0,0` is the bottom-left corner of the board and `l-1,l-1` is the top-right corner of the board. **Algorithm:** Start with the initial coordinates of the knight. Make all possible moves for this position and multiply these moves with their probability, for each move recursively call the function continue this process till the terminating condition is met. Terminating condition is if the knight is outside the chess board, in this case return 0, or the desired number of moves is exhausted, in this case return 1. As we can see that the current state of the recursion is dependent only on the current coordinates and number of steps done so far. Therefore we can memorize this information in a tabular form. ### Credit This challenge is originally from a blog post of [crazyforcode.com](http://www.crazyforcode.com/probability-knight-stays-chessboard) published under the [CC BY-NC-ND 2.5 IN](http://creativecommons.org/licenses/by-nc-nd/2.5/in/) licence. It was slightly modified to make it a bit more challenging. [Answer] # Pyth, 38 bytes ``` M?smcgtGd8fq5sm^-Fk2C,TH^UhQ2G1g@Q1>Q2 ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=M%3FsmcgtGd8fq5sm%5E-Fk2C%2CTH%5EUhQ2G1g%40Q1%3EQ2&input=8%2C1%2C0%2C1&debug=0) ### Explanation: ``` implicit: Q = evaluated input M define a function g(G,H): //G=depth, H=current cell UhQ the list [0,1,...,Q[0]-1] ^ 2 Cartesian product, gives all cells f filter for numbers numbers T, which satisfy: C,TH zip(T,H) m map the two pairs k to: -Fk their difference ^ 2 squared s sum (distance squared) q5 == 5 m map each valid cell d to: gtHd g(G-1,d) c 8 divided by 8 s return sum ? G if G > 0 else 1 return 1 g@Q1>Q2 call g(Q[1],Q[2:]) and print ``` [Answer] # Ruby 134 ``` ->l,m,x,y{!((r=0...l)===x&&r===y)?0:m<1?1:(0..7).map{|i|a,b=[1,2].rotate i[2] P[l,m-1,x+a*(i[0]*2-1),y+b*(i[1]*2-1)]/8.0}.inject(:+)} ``` Try it online: <http://ideone.com/ZIjOmP> The equivalent non-golfed code: ``` def probability_to_stay_on_board(board_size, move_count, x, y) range = 0...board_size return 0 unless range===x && range===y return 1 if move_count < 1 possible_new_locations = (0..7).map do |i| dx, dy = [1,2].rotate i[2] dx *= i[0]*2-1 dy *= i[1]*2-1 [x+dx, y+dy] end possible_new_locations.map do |new_x, new_y| probability_to_stay_on_board(board_size, move_count-1, new_x, new_y) / 8.0 end.inject :+ end ``` [Answer] # Haskell - 235 Implements a function `f` with parameters `l k x y` ``` import Data.List g[]=[] g((a,b):r)=[(a+c,b+d)|(c,d)<-zip[-2,-1,1,2,-2,-1,1,2][1,2,-2,-1,-1,-2,2,1]]++g r h _ 0 a=a h l a b=h l(a-1)$filter(\(a,b)->(elem a[0..l])&&(elem b[0..l]))$g b f l k x y=(sum$map(\x->1.0) (h l k [(x,y)]))/(8**k) ``` [Answer] # Matlab, ~~124~~ 119 Exactly implements the described algorithm. I was able to shorten it by 5 bytes with some help of @sanchises, thanks! ``` function s=c(l,k,x,y);m=zeros(5);m([2,4,10,20])=1/8;s(l,l)=0;s(l-y,x+1)=1;for i=1:k;s=conv2(s,m+m','s');end;s=sum(s(:)) ``` Expanded: ``` function s=c(l,k,x,y); m=zeros(5); m([2,4,10,20])=1/8; s(l,l)=0;s(l-y,x+1)=1; for i=1:k; s=conv2(s,m+m','s'); end; s=sum(s(:)) ``` Old version ``` function s=c(l,k,x,y); m =zeros(5);m([1:3,5,8,10:12]*2)=1/8; s=zeros(l); s(l-y,x+1)=1; for i=1:k s=conv2(s,m,'s'); end s=sum(s(:)); ``` [Answer] # Mathematica - 137 ``` q = # {1, 2} & /@ Tuples[{-1, 1}, 2] q = Reverse /@ q~Union~q g[l_, k_, x_, y_] := Which[ k < 1, 1, !0 <= x < l || ! 0 <= y < l, 0, 0<1, Mean[g[l, k - 1, x + #[[1]], y + #[[2]]] & /@ q] ] ``` Usage: ``` g[5,5,1,2] ``` Output: ``` 9/64 ``` [Answer] # MATLAB - 106 ``` function s=c(l,k,x,y);m(5,5)=0;m([2,4,10,20])=1/8;s=ones(l);for i=1:k;s=conv2(s,m+m','s');end;s=s(l-y,x+1) ``` Improves on @flawr's solution by being more MATLAB-y. ## Expanded: ``` function s=c(l,k,x,y) m(5,5)=0; m([2,4,10,20])=1/8; s=ones(l); for i=1:k s=conv2(s,m+m','s'); end s=s(l-y,x+1) ``` [Answer] ## ><> - 620 (not counting whitespace) Initial stack should be `l,k,x,y` ``` {:a2*0p v vp0*3a*}:{< >{1+&a3*0g}v > > > >~~01-01-v > > > >~~01-01-v > > > >~~01-01-v > > > >~~01-01-v >&1-:&?!v>:@@:@@:0(?^:a2*0g1-)?^2-$:0(?^:a2*0g1-)?^1- >}}$:@@:@@:0(?^:a2*0g1-)?^2-$:0(?^:a2*0g1-)?^1+ >}}$:@@:@@:0(?^:a2*0g1-)?^2+$:0(?^:a2*0g1-)?^1- >}}$:@@:@@:0(?^:a2*0g1-)?^2+$:0(?^:a2*0g1-)?^1+ >}}$:@@:@v v1 ^} ^!?=g0*3a:~~}}< +2v?)-1g0*2a:v?(0:$+1v?)-1g0*2a:v?(0:@@:@@:$}}< -2v?)-1g0*2a:v?(0:$+1v?)-1g0*2a:v?(0:@@:@@:$}}< +2v?)-1g0*2a:v?(0:$-1v?)-1g0*2a:v?(0:@@:@@:$}}<-2 v?)-1g0*2a:v?(0:$-1v?)-1g0*2a:v?(0:@< >a3*0g= ?^\ & ^-10-10~~< < < < ^-10-10~~< < < < ^-10-10~~< < < < ^-10-10~~< < < < \ :{/ v >~{~l2,&0 >@:0(?v:a2*0g1-)?v$:0(?v:a2*0g1-)?v1>@~~+l1=?v > > > >0^ >&,n; ``` [Test it out](http://fishlanguage.com/playground/PWMdJeoWGwP798jCG) ]
[Question] [ I was told that using the `cmp` function can be [very useful in code-golf](https://codegolf.stackexchange.com/a/49773/31716). But unfortunately, Python 3 doesn't have a `cmp` function. So what's the shortest equivalent of `cmp` that works in python 3? [Answer] Python 3 does not have `cmp`. For golfing, you can do *11 chars* ``` (a>b)-(a<b) ``` which loses 3 chars over `cmp(a,b)`. Amusingly, this is also an "official" workaround. The [What's New in Python 3](https://docs.python.org/3.0/whatsnew/3.0.html) page says "(If you really need the `cmp()` functionality, you could use the expression `(a > b) - (a < b)` as the equivalent for `cmp(a, b)`.)" ]
[Question] [ ## Summary The task is to navigate the Mars rover and tell its final coordinates and direction. # Input: ## First input: First your program must take the input which will be in the following format: ``` [X-Coordinate],[Y-Coordinate],[Direction] ``` The direction must be: `N` or `S` or `E` or `W` (Starting letters of North, South, West, East) Example: `10,20,N` ( x = 10, y = 20, direction = N(North)) ## Second input: The second input consists of series of `R`, `L`, `M` for right, left and move respectively. For `R` and `L` (right and left) the direction of rover must change accordingly. For `M` the rover must move 1 unit ahead in the direction which it was before moving. Rules for calculating coordinates: ``` N = Y + 1 E = X + 1 S = Y - 1 W = X - 1 ``` ## Output: The final coordinates and the current direction of the rover. --- Example: ``` Enter initial data: 1,2,N Enter the instructions: MRMLM Output: 2,4,N ``` The coordinates can be any integer and can be **negative**. All the standard loopholes aren't allowed. If providing demo on sites like <http://ideone.com> etc. is possible, then please do so, so that I can verify :) This is a popularity contest so be creative! Following others' advice, I decide to make this a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] ## Ruby ≥ 2.0, 101 ``` E,N,W,S=*0..3 x,y,i=eval"a="+gets gets.bytes{|c|x+=c%2*1i**i=i+1-c&3} $><<[(x+y.i).rect,"NWSE"[i]]*?, ``` This solution can be tested here: <https://ideone.com/C4PLdE> Note that the solution linked on ideone is one character longer (`1.i` instead of `1i` in line 3). The reason for this is that ideone only supports Ruby 1.9, which doesn't allow the short-hand syntax for complex literals. [Answer] # Javascript (*ES6*) 145 141 127 *Edit:* Removed the need for a translation array using method from [edc65's C solution](https://codegolf.stackexchange.com/a/32075/20160) ``` [x,y,d]=(p=prompt)(s='NESW').split(','),[...p(d=s.search(d))].map(c=>c!='M'?(d+=c>'M'||3,d%=4):d%2?x-=d-2:y-=d-1),p([x,y,s[d]]) ``` **Ungolfed/Commented:** ``` s='NESW' // initialize variable for direction mapping [x,y,d]=prompt().split(',') // get first input, split by commas, map to variables x,y,d d=s.search(d) // get numeric value for direction [...prompt()].map(c=> // get second input, map a function to every character in it c!='M'? // if char is not M (d+=c>'M'||3, // increment d by 1 if char greater than M, otherwise 3 d%=4) // modulo by 4 to wrap direction : // else d%2? // if odd direction x-=d-2 // move x position : // else y-=d-1 // move y position ) prompt([x,y,s[d]]) // output result ``` [Answer] # Java - 327 ``` class R{public static void main(String[]a){char c,e=a[2].charAt(0),z[]={78,69,83,87};Integer x=Integer.valueOf(a[0]),y=x.valueOf(a[1]),d=e<70?1:e==83?2:e>86?3:0,i=0;for(;i<a[3].length();d=c>81?(d+1)%4:c<77?(d+3)%4:d){c=a[3].charAt(i++);if(c==77){x=d==1?x+1:d>2?x-1:x;y=d<1?y+1:d==2?y+1:y;}}System.out.print(x+","+y+","+z[d]);}} ``` With whitespace: ``` class R{ public static void main(String[]a){ char c,e=a[2].charAt(0),z[]={78,69,83,87}; Integer x=Integer.valueOf(a[0]),y=x.valueOf(a[1]),d=e<70?1:e==83?2:e>86?3:0,i=0; for(;i<a[3].length();d=c>81?(d+1)%4:c<77?(d+3)%4:d){ c=a[3].charAt(i++); if(c==77){ x=d==1?x+1:d>2?x-1:x; y=d<1?y+1:d==2?y+1:y; } } System.out.print(x+","+y+","+z[d]); } } ``` As usual with Java, about half of this is just parsing the input and forming the output. The logic is pretty straightforward. [Answer] # Javascript (E6) 175 **Edit** Fixed bug, possibly out of range return value for d 139 Logic, 36 I/O ``` F=(x,y,d,m,D='NESW')=>(d=D.search(d),[...m].map(s=>({M:_=>(y-=[-1,0,1,0][d],x-=[0,-1,0,1][d]),R:_=>d+=1,L:_=>d+=3}[s](),d%=4)),[x,y,D[d]]); p=prompt,p(F(...p().split(','),p())) ``` **Basic ungolfed** ``` function F(x,y,d,m) // In golf code use arrow sintax instead of 'function' { var D='NESW'; d = D.search(d); // map from letters to offset position 0..3 var driver = { // driver object, each function map one of command letters M,R,L M: function() { y -= [-1, 0, 1, 0][d]; // subtract to be sure to have a numeric and not string result x -= [0, -1, 0, 1][d]; // subtract to be sure to have a numeric and not string result }, R: function() { d += 1; }, L: function() { d += 3; // with modulo 4 will be like -= 1 } } m = [...m]; // string to array, to use iteration function m.forEach( // array scan, in golf versione use map do nearly the same and is shorter function (s) { driver[s](); // call driver function d = d % 4; // restrict value to modulo 4 } ); // in golf version, use comma separated expression to avoid 'return' return [x,y, D[d]] // return last status } ``` **Test** Test in javascript console in Firefox. It's simpler to test the function F avoiding the popups. ``` F(1,2,'N','MRMLM') ``` Output ``` [ 2, 4, "N" ] ``` [Answer] # C 164 ~~180 186~~ **Edit** Fixed input format and removed strchr **Edit** Removed offset array, calc using bits ``` p,x,y;main(){char c,d,l[100];scanf("%d,%d,%c%s",&x,&y,&d,l);for(d=d<83?d&1:d>>2&1|2;c=l[p++];d&=3)c-77?d+=c+1:d&1?x+=d-2:(y+=1-d);printf("%d %d %c",x,y,"NESW"[d]);} ``` **Ungolfed** ``` p, x, y; main() { char c, d, l[100]; scanf("%d,%d,%c%s",&x,&y,&d,l); for (d = d<'S'?d&1:d>>2&1|2; c = l[p++]; d &= 3) c-'M' ? d += c+1 : d & 1 ? x+=d-2 : (y+=1-d); printf("%d %d %c", x, y, "NESW"[d]); } /* M 77 R 82 0101 0010 R&3+1==3 L 76 0100 1100 L&3+1==1 */ ``` [Answer] # C, 148 ~~150~~ ~~151~~ ``` p,x[2];main(){char c,d,l[99],*j="%d,%d,%c%s";scanf(j,x,x+1,&d,l);for(d=d%8%5;c=l[p++];d-=c%23)x[d&1]-=c%2*~-(d&2);printf(j,*x,x[1],"ENWS"[d&3],"");} ``` A tweak of @edc65's solution to use my ASCII value abuse approach. Specifically: * `d%8%5` maps the characters `ENWS` to `0,1,2,3` respectively * `c%23` turns `L` into `7`, `M` into `8` and `R` into 13. Because `d` (the direction variable) is always used mod 4, this effectively makes `L` add -1 mod 4, `M` add 0 mod 4, and `R` add 1 mod 4. * `d&1` is 1 for `NS` and 0 for `EW` directions. * `d&2` is 2 for `WS` and 0 for `NE` directions. * `~-(d&2)` is 1 for `WS` and -1 for `NE` directions. * `c%2` is 1 for `M` and 0 for `LR`. [Answer] # Python 3 (with turtle graphics), 251 199 bytes Wise pythonistas, please be gentle, for this is my first ever attempt at a program written in your fine language. # Turtles on Mars! ``` from turtle import* p="NESW" mode("logo") x,y,d=input().split(',') setx(int(x)) sety(int(y)) seth(p.find(d)*90) for c in input():fd(1)if c=="M"else[lt,rt][c>'L'](90) print(pos(),p[int(heading()/90)]) ``` This challenge maps quite naturally to logo-style turtle graphics, for which python has an import, of course. Reads input from two lines from STDIN. Output: ``` $ { echo 1,2,N; echo MRMLM; } | python ./rover.py (2.00,4.00) N $ ``` What I especially like about this program is it actually graphically displays the rover's path. Add `exitonclick()` to the end of the program so the graphical output persists until user click: ![enter image description here](https://i.stack.imgur.com/6DPtA.png) I'm pretty sure this can be golfed significantly more - any suggestions welcome! I'm making this CW, because I hope the community can golf it some more. Changes: * s is now a list, inlined. * Used ternary for body of for loop. * Inlined n, removed unnecessary slice. * Removed unnecessary space in import statement. * Removed import string to use builtin string method * Switched to Python 3 to shorten raw\_input [Answer] # GolfScript, ~~116 98 88 84~~ 71 ``` ~'NESW':^@?:&;{4%[{&(4%:&;}{&[{)}{\)\}{(}{\(\}]=~}{&)4%:&;}]=~}/]`&^1/= ``` This should get the coordinates and the instructions as arguments the following way:`1 2 'N' 'MRMLM'`. The arguments are made into a string and are pushed into the stack. If you want to test this online, go to [web golfscript](http://golfscript.apphb.com/) and paste a semicolon followed with a string with the arguments (e.g. `;"1 2 'N' 'MRMLM'"`) before the code ([here](http://golfscript.apphb.com/?c=OyIxIDIgJ04nICdNUk1MTScifidORVNXJzpeQD86Jjt7NCVbeyYoNCU6Jjt9eyZbeyl9e1wpXH17KH17XChcfV09fn17Jik0JTomO31dPX59L11gJl4xLz0%3D)'s a link with an example). Examples of output: ``` 1 2 'N' 'MRMLM' -> [2 4]N 5 6 'E' 'MMLMRMRRMMML' -> [5 7]S 1 2 'N' 'MMMMRLMRLMMRMRMLMRMRMMRM' -> [1 8]N ``` ## My Previous Attempts **84 chars:** ``` ~:i;'NESW':k\?:d;{i(\:i;4%[{d(4%:d;}{d[{)}{\)\}{(}{\(\}]=~}{d)4%:d;}]=~i}do]`d k 1/= ``` **88 chars:** ``` ~:i;'NESW':k\?:d;{i(\:i;'MRL'?[{d[{)}{\)\}{(}{\(\}]=~}{d)4%:d;}{d(4%:d;}]=~i}do]`d k 1/= ``` **98 chars:** ``` ~1/:i;:d;{'NESW'd?}:k;{k[{)}{\)\}{(}{\(\}]=~}:M;{k'ESWN'1/=:d;}:R;{k'WNES'1/=:d;}:L;{i(\:i;~i}do d ``` **116 chars:** ``` [~])\~"NESW":k 1/:d?{d(1/+:d;}:f*:y;:x;{("MRL"?[{k d 0=?[{y):y}{x):x}{y(:y}{x(:x}]=~;}{f}{d)1/\+:d;}]=~.}do x y d 0= ``` [Answer] # Javascript (353) This is my first real attempt at code golf, seems to work at least! ``` var xx=[0,1,0,-1];var yy=[1,0,-1,0];var d=["N","E","S","W"];var e=0;var x,y=0;function sa(p){q=p.split(",");x=+q[0];y=+q[1];e=+d.indexOf(q[2]);}function sb(t){var g=t.split(",");for(var u=0;u<g.length;u++){if(g[u]=='R'){e++;if(e>3)e=0;}if(g[u]=='L'){e--;if(e<0)e=3;}if(g[u]=='M'){x+=+xx[e];y+=+yy[e];}}alert(x+","+y+","+d[e]);}sa(prompt());sb(prompt()); ``` [Answer] ## Python (263) ``` input = raw_input("Initial: ") input2 = raw_input("Command: ") position = [int(input[0]), int(input[2]), input[4]] bearings = "NESW" turns = {"L" : -1, "M": 0, "R" : 1} move = {"N" : [0, 1], "E" : [1, 0], "S" : [0, -1], "W" : [-1, 0]} for c in input2: turn = turns[c]; if (turn == 0): position[0] += move[position[2]][0] position[1] += move[position[2]][1] else: position[2] = bearings[(bearings.index(position[2]) + turn)%4] print "Output: ", ','.join((str(s) for s in position)) ``` There must be a more elegant way of doing this also, it doesn't need the branch after the else. <http://ideone.com/eD0FwD> The input is awful, I wanted to do it with `split(',')` but came across casting issues between the ints and strings. Ideally I also wanted to add the old position with the moving position... oh it's code-golf now. Oh well whatever, I'll leave it here, might give inspiration. Other ideas I had were using modulo 4 of the direction after mapping the initial bearing to an index. Also merging the turns and move arrays to one since none of the keys collide. even so, shortening variable names and removing spaces it's 263: ``` i=raw_input() j=raw_input() p=[int(i[0]),int(i[2]),i[4]] b="NESW" m={"N":[0,1],"E":[1,0],"S":[0,-1],"W":[-1,0],"L":-1,"M":0,"R":1} for c in j: if (m[c]==0): p[0]+=m[p[2]][0] p[1]+=m[p[2]][1] p[2] = b[(b.index(p[2])+m[c])%4] print ','.join(str(s) for s in p) ``` [Answer] # Python 2.7 - ~~197~~ 192 bytes ``` q='NESW';x,y,d=raw_input().split(',');x=int(x);y=int(y);d=q.find(d);v={0:'y+',1:'x+',2:'y-',3:'x-'} for c in raw_input():exec['d+','d-',v[d]]['RL'.find(c)]+'=1;d=d%4' print`x`+','+`y`+','+q[d] ``` I'm actually super proud of this one. **Explanation** First, let's clean up this mess. I used semicolons instead of line breaks in a lot of places because I think it makes me cool. Here it is normally (this is still 197 bytes, it hasn't been ungolfed at all). Yes, there's still a semicolon, but that one actually saves a byte. ``` q='NESW' x,y,d=raw_input().split(',') x=int(x) y=int(y) d=q.find(d) v={0:'y+',1:'x+',2:'y-',3:'x-'} for c in raw_input():m=v[d];exec['d+','d-',m]['RL'.find(c)]+'=1;d=d%4' print`x`+','+`y`+','+q[d] ``` Let's begin! ``` q='NESW' ``` First we define `q` as the string `'NESW'`. We use it twice later, and `len("q='NESW';qq") < len("'NESW''NESW'")`. ``` x,y,d=raw_input().split(',') ``` Here we split the first line of inpupt at each comma. Our x coord is stored in `x`, y in `y`, and the first letter of our direction in `d`. ``` x=int(x) y=int(y) ``` Then we just make the coords ints. (I was shocked that I couldn't think of a better way to convert two strings to ints. I tried `x,y=map(int,(x,y))` but that turns out to be longer.) ``` d=q.find(d) ``` This converts our direction to an integer. 0 is north, 1 is east, 2 is south and 3 is west. ``` v={0:'y+',1:'x+',2:'y-',3:'x-'} ``` This is where the fun starts. When we go north, Y increases by 1. So this dictionary takes 0 and gives the string `'y+'`, for "increase y". It gives similar results for other directions: y or x followed by + or -. We'll come back to this. ``` for c in raw_input(): m=v[d] exec['d+','d-',m]['RL'.find(c)]+'=1;d=d%4' ``` I've gone to the liberty of ungolfing this one slightly. For each character in the second line of input, we do two things. First, we set the variable `m` to whatever our dictionary from before gives us for our current direction. There's no reason we need this to happen every time, but it's easier than just making it happen when we need it. Next, we create a list with three elements: `'d+'`, `'d-'`, and `m`. **EDITOR'S NOTE:** I think I can get away with not using the variable `m` at all. I think I can just put `v[d]` in the list directly. That'll save me a couple bytes if it works, but I don't feel like testing it until I'm done this explanation so y'all can deal. **(Yep, it worked.)** We look for the current character of the input in the string 'RL'. `str.find` returns -1 if it doesn't find the character, so this converts an R to a 0, an L to a 1 and anything else to -1. Of course, the only other input we can have is M, but it's less characters to make it work for everything. We use that number as the index for the list we created. Python list indices start at the end if they're negative, so we get the first element if the input is R, the second if it's L, and the last if it's M. For for convenience's sake, I'm about to assume that we're facing north, but a similar principle applies for other directions. The possible values we're working with are `'d+'` for R, `'d-'` for L and `'y+'` for M. Then, we attach `'=1;d=d%4'` to the end of each one. That means our possible values are... ``` d+=1;d=d%4 d-=1;d=d%4 y+=1;d=d%4 ``` That's valid python code! That's valid python code that does exactly what we want to do for each of those input characters! (The `d=d%4` part just keeps our directions sane. Again, don't need to do it every time, but it's less characters.) All we have to do is execute the code we get for each character, print it out (converting our direction back to a string), and we're done! [Answer] # C - 350 Save as `rover.c`: ``` #include<stdio.h> #include<string.h> #include<math.h> int main(){char c,*C="NWSE-WN";float x,y,d,k=M_PI/2;scanf("%f,%f,%c",&x,&y,&c);d=(strchr(C,c)-C)*k;do{switch(getchar()){case'R':d+=k;break;case'L':d-=k;break;case'M':x+=sin(d);y+=cos(d);break;case EOF:printf("%g,%g,%c\n",x,y,C[(int)(sin(d)+2*cos(d)+4.5)]);}}while(!feof(stdin));return 0;} ``` Compile: ``` gcc -o rover rover.c -lm ``` Sample run: ``` $ echo 1,2,N MRMLM | ./rover 2,4,N ``` [Ideone](http://ideone.com/Tp6WxL) Ungolfed: ``` #include <stdio.h> #include <string.h> #include <math.h> int main() { /* String is used for input and output, pi/2 == 90 degrees */ char c, *C = "NWSE-WN"; float x, y, d, k = M_PI/2; /* Get starting parameters */ scanf("%f,%f,%c", &x, &y, &c); /* Convert the direction NWSE into radians */ d = (strchr(C, c) - C) * k; /* Process each character */ do { /* Recognize R(ight), L(eft), M(ove) or EOF */ switch (getchar()) { case 'R': /* Turn right 90 degrees */ d += k; break; case 'L': /* Turn left 90 degrees */ d -= k; break; case 'M': /* Advance 1 unit in the direction specified */ x += sin(d); y += cos(d); break; case EOF: /* Output - formula is specially crafted so that S,E,W,N map to indices 2,3,5,6 to reuse part of string */ printf("%g,%g,%c\n", x, y, C[(int)(sin(d) + 2*cos(d) + 4.5)]); } } while (!feof(stdin)); return 0; } ``` [Answer] # Haskell - 412 bytes ``` import Text.Parsec import Text.Parsec.String n='N' s='S' e='E' w='W' d(x,y,c)'M'|c==n=(x,y+1,c)|c==s=(x,y-1,c)|c==e=(x+1,y,c)|c==w=(x-1,y,c) d(x,y,c)e=(x,y,i c e) i 'N''R'=e i 'N''L'=w i 'S''R'=w i 'S''L'=e i 'E''R'=s i 'E''L'=n i 'W''R'=n i 'W''L'=s f=many digit g=char ',' o=oneOf main=interact(\s->show$parse(do x<-f;g;y<-f;g;c<-o"NSEW";newline;b<-many$o"MRL";return$foldl(\x c->d x c)(read x,read y,c)b)""s) ``` Tested with : ``` $ printf "1,2,N\nMRMLM" | ./rv Right (2,4,'N') ``` [Answer] # Bash+coreutils, 159 bytes ``` t()(tr $2 0-3 $1<<<$d) IFS=, read x y d d=`t '' NESW` for s in `fold -1`;{ [ $s = M ]&&((`t yxyx;t ++-`=1))||d=$[(d`tr LR -+<<<$s`1+4)%4] } echo $x,$y,`t NESW` ``` Input is read from 2 lines of STDIN. Output: ``` $ { echo 1,2,N; echo MRMLM; } | ./rover.sh 2,4,N $ ``` [Answer] ## PowerShell, ~~170~~ ~~167~~ 166 ``` [int]$x,[int]$y,$e,$m="$input"-split'\W' $d='NESW'.indexof($e) switch([char[]]$m){'R'{$d++}'L'{$d--}'M'{iex(-split'$y++ $x++ $y-- $x--')[$d%4]}} "$x,$y,"+'NESW'[$d%4] ``` Can't seem to golf this down further, which is a bit embarrassing. But all the obvious hacks don't really work here. I can't `iex` the input because a) `N`, `S`, `E` and `W` would have to be functions for that to work (or I'd need to prefix that with `$` and b) `1,2,N` would have to parse the `N` in expression mode, not being able to run a command. The `switch` seems to be the shortest way of doing the movement. Hash table with script blocks or strings isn't shorter either and for every other way apart from the `switch` I'd have the overhead of the explicit loop. I can't get rid of the `IndexOf` because a pipeline with `?` is longer, still. I also can't get rid of the explicit types in the initial declaration because I have mixed types there, so a simple `|%{+$_}` doesn't help and every other option is longer. Sometimes I hate input handling in PowerShell. [Answer] # Python, 135 ~~137~~ ~~138~~ ``` S,W,N,E=0,1,2,3;a,b,d=input();v=[b,a] for c in map(ord,raw_input()):d+=c%23;v[d&1]+=c%2*~-(d&2) print'%d,%d,%s'%(v[1],v[0],'SWNE'[d&3]) ``` Abuses the ASCII values of `L`, `M` and `R` to avoid using any conditional statements. Try it in [ideone](https://ideone.com/FnZppp). [Answer] # Python 2.7, 170 149 ``` N,E,S,W=q='NESW' x,y,d=input() d=q.find(d) for c in raw_input():exec['d+','d-','yx'[d%2]+'+-'[d/2]]['RL'.find(c)]+'=1;d%=4' print`x`+','+`y`+','+q[d] ``` Things I changed from the original: Aliased raw\_input, changed the v[d] dictionary, which should have been a list anyways, to some string selection, used `%=`. Edit: used tuple unpacking and eval(raw\_input())==input() to save 21 characters. Heavily borrowed from @undergroundmonorail, but with lots of improvements. [Answer] # Bash/[SHELF](https://github.com/professorfish/bash-shelf), ~~243~~ 235 "**SHE**ll go**LF**" is a golfing library for Bash which provides a few useful aliases. This is a valid answer as the library existed and was on GitHub before the challenge was posted. Sorry, I can't get this to work on ideone. ## How to run This takes the initial position (separated by commas as specified; this adds a lot of characters to the code) as its first argument, and the instructions on standard input. ``` source shelf.sh #you must load SHELF first source rover.sh 1,2,N<<<MRMLM #now run the script via source so it has access to SHELF ``` ## Sample output ``` 2,4,N ``` ## Code ``` o=$1 D(){ o=`y NESW $1<<<$o`;} for x in `Y . '& '`;{ d $x R&&D ESWN d $x L&&D WNES d $x M&&z=(`y , \ <<<$o`)&&case ${z[2]} in N) z[1]=$[z[1]+1];;S) z[1]=$[z[1]-1];;W) z[0]=$[z[0]-1];;E) z[0]=$[z[0]+1];;esac&&o=`P ${z[@]}|y \ ,` } p $o ``` ## Explanation `d` is for comparison; it returns 0 if its two arguments are equal and 1 otherwise, it can then have other commands chained onto it with `&&` and `||`. `y` is like `tr` (but done through `sed`). `Y` is like `sed 's/.../.../g'` for its two arguments. `P` is `echo -e -n`; `p` is just `echo -e`. ``` o=$1 #save first argument to variable D(){ o=`y NESW $1<<<$o`;} #define an alias to turn R or L for x in `Y . '& '`;{ #add a space after every character on stdin and loop for each one d $x R&&D ESWN #turn R using alias d $x L&&D WNES #turn L using alias ``` The next bit is profoundly ugly, with about 145 chars on one line. If the current command is M, turn the commas in $o into spaces, convert to array and save to $z. Then, do a switch...case block for the last element of $z (the direction the rover is pointing. Change coordinates accordingly, then convert $z back into a comma-separated string and save to $o. ``` d $x M&&z=(`y , \ <<<$o`)&&case ${z[2]} in N) z[1]=$[z[1]+1];;S) z[1]=$[z[1]-1];;W) z[0]=$[z[0]-1];;E) z[0]=$[z[0]+1];;esac&&o=`P ${z[@]}|y \ ,` } #end loop p $o #print output ``` [Answer] # Haskell, 291 ``` data D=W|S|E|N deriving(Show,Read,Enum) main=interact$(\(x,y)->tail$map show y++[show(toEnum x::D)]>>=(',':)).(\(a:b:_)->foldl(\(f,j@[g,h])i->case i of 'M'->(f,[g+rem(f-1)2,h+rem(f-2)2]);'L'->(mod(f+1)4,j);'R'->(mod(f-1)4,j))((\(c,d,e)->(fromEnum(e::D),[c::Int,d]))$read('(':a++")"))b).lines ``` I wasn't sure how flexible the input and output string format was, so I made sure it looked exactly like the example (minus the prompts, of course), but that added a lot of extra characters. [Ideone link](http://ideone.com/nXNbDH) [Answer] # PHP - 224 Well, I gave it a try. ``` $n=explode(",",$argv[1]);$d=($e=$n[2])==W?0:($e==N?1:($e==E?2:3));for(;$i<strlen($n[3]);)if(($o=$n[3][$i++])==M)$n[$d%2]+=$d>1?-1:1;else$d=$o==R?($d+1)%4:($d==0?3:$d-1);echo"{$n[0]},{$n[1]},".($d==1?N:($d==2?E:($d==3?S:W))); ``` Input in STDIN, e.g.: ``` $ php mars_rover.php 1,2,N,MMMRRRRRMM -1,5,E $ php mars_rover.php 1,2,N,MMMMRLMRLMMRMRMLMRMRMMRM 1,8,N $ php mars_rover.php 3,-2,W,MMMMLM 7,-3,S ``` [Answer] # Python3 (288) Implementation using heavy use of ternary ifs. ``` m=['N','E','S','W'] cords=[int(n) for n in input().split()] + [input()] #Convert first inputs to integers and retrieve third for n in input(): #Get instructions if n=='M': i=[1,0][cords[2] in m[1:3]] #See if vertical or horizontal j=[-1,1][cords[2] in m[0:2]] #See if negative or positive cords[i]+=j else: i=[-1,1][n=='R'] #Translate turn to numerals cords[2]=m[m.index(cords[2])+i] #Change direction relative to current orientation print(cords) ``` Omitting the obvious input grumbles, giving the direction strings intrinsic values may have benefited the script size. However, the approach here is perfectly functional (so I believe) [Answer] # Python 3 (143) ``` I=input a,b,D=I().split(',') w='ENWS' d=w.find(D) x=int(a)+int(b)*1j for c in I():x+=(c=='M')*1j**d;d+='ML'.find(c) print(x.real,x.imag,w[d%4]) ``` <http://ideone.com/wYvt7J> We use Python's built-in complex number type to store the pair of coordinates. The direction is computed by taking the imaginary unit `1j` to the power of `d`, which stores the direction mod 4. Rotating is done by incrementing or decrementing `d`. The expression `'ML'.find(c)` gives the amount we want to change `d`: `1` for `L`, `0` for `M`, and `-1` (the default for not found) for `R`. Python doesn't have a short way to convert a complex number to a tuple, so we have to make costly calls to `.real` and `.imag`. ]
[Question] [ ## Fast and Golfiest Cops Thread Welcome to the first season of **Fast and Golfiest**, a cops-and-robbers challenge! I designed this challenge to encourage competitive coding for efficiency (fastest algorithm) to become more popular on the site. The rules are simple. The cops must choose a problem from LeetCode, the prestigious competitive programming platform, and *independently* solve it with code that is as efficient and as short as possible. The problem must be of "medium" or "hard" difficulty (no easy stuff!). Also, according to the theme of this season, it must be related to **strings**! Note that for the cops, **efficiency matters most**, and you do not need to spend too much efforts trying to golf up the code painstakingly. Your answer post should include the following: 1. The problem you chose, and the link to it on LeetCode. 2. Your code, its length in bytes, and the language you used. 3. The UTC time of your post. 4. The time complexity of your code. The robbers will then try to golf up the cops' code without sacrificing time complexity. Here's the link to the [Robbers' Thread](https://codegolf.stackexchange.com/questions/263050/robbers-fast-and-golfiest-season-1-the-lord-of-the-strings). Your score is the amount of 5 minute intervals in the amount of time it remains uncracked, rounded to the nearest integer! If you have any advices please let me know in the comments so that this challenge series could be improved. Thanks in advance! Leaderboard: It seems that I seriously need to fix the scoring system :-( Leaderboard disactivated for this season. [Answer] # [Concatenated Words](https://leetcode.com/problems/concatenated-words/), [Python](https://www.python.org), 177 bytes, \$O(n)\$ time assuming input is a set where \$n\$ is the number of words, [Cracked by Cursor Coercer](https://codegolf.stackexchange.com/a/263075/91213), 7 points This is \$O(2^L)\$ where \$L\$ is the length of each word but I don't define N that way. It's almost as if asymptotic complexity is isn't a total unambiguous ordering for arbitrary problems. ``` lambda z:[i for i in z if any(all(i[a:b]in z and i[a:b]!=i for a,b in q)for q in g(0,len(i)))] def g(a,b): yield[(a,b)] for i in range(a+1,b): for j in g(i,b):yield[(a,i)]+j ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY5NDoIwEIX3nGLsqg2Y6M6QcBLSxWApDqnlJ3UBxpO4ISa69zjeRkqJrt68b9783F_t4E6NnR46e16c3h4-b4PnQiGMaU6gmx4IyMIIpAHtwNEYTjmmhVwoWgXBbrIQx6TwA53wpvNlxXeJKS0nIYSMVKlnMqdEGsFApVH54mT0v9ajrUqO8T6klkYdVpFHvzESMq7Xx1nbk3Vc8ytTTcUSYEd0q3hwEyIkpynoFw) time: 2023-07-20 14:02:05Z [Answer] # [ATOI string to integer](https://leetcode.com/problems/string-to-integer-atoi/), 130 Bytes, Python 3 (IDLE), probably \$O(n)\$ or worse, 9:10 am UTC (it's DST in uk), [Cracked in 18 min, so ~~0 points :(~~ 4 points under new system :)](https://codegolf.stackexchange.com/a/263061/117478) ``` lambda x:a if-2**31<(a:=int(re.match(r" *((\+|-)?(\d*))",x).groups(1)[0]or 0))<2**31-1else-2**31if-2**31>=a else 2**31-1 import re ``` Don't [Try It Online!](https://tio.run/##NcxNDoIwEEDhvaeYsJqpllDZEaoHsS5GKUJCaVNqgol3r/Fv@/LyhUca/FznXps8sbt0DGvDMPZyL0StWuRGj3PCaEvH6TpgLEAgmu1T0hFNJ4iK3UrlLfp7WFDRqTr7CBVR@wGkstNiv9gfPWiGd4XfsRld8DFBtDm/AA), it doesn't work there. [Answer] # [Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/), [C (GCC)](https://gcc.gnu.org), 47 bytes, \$O(n)\$ complexity, [Cracked by jimmy23013](https://codegolf.stackexchange.com/a/263087/25180), 25 points ``` f(char*s){for(char*p=s;*s-42?*p++=*s:p--;s++);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY9NDoIwEIX3PUVTY0KLaCQujBU9iBhDSitNEJpOcUM4iRs27L2Ot5Eff2Yzk3l535t5dOJyFaJtu8qpYPtaKU9kiWVAa1XaaTYRcAbBJjwy4_sRg50JAg6-T3nzsT1nuhB5lUq8B5fqcpkdELqXOkVOghsxuGeiGmGsPKC878bqwimPxGQOMYkLssCD0CDU79Et0YU3ECbTSID16YwjTHIpHWOiTJkk_CeGkyhtApINNWpjPqzpfw6HkOnu79tv) Time: 2023-07-20 16:36:08Z [Answer] # [Generate Parenthesis](https://leetcode.com/problems/generate-parentheses/), [><> (Fish)](https://esolangs.org/wiki/Fish), 178 bytes, \$O(n!)\$, [Cracked by C--](https://codegolf.stackexchange.com/a/263372/91213) Time: 2023-07-21 12:35:24Z ``` ![i](https://$ "read a character")![>](https://$ "Change Cursor Direction")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![~](https://$ "Delete the top element of the stack")![l](https://$ "Push the length of the stack to the stack")![2](https://$ "Push the number (0-9)")![,](https://$ "Divide the top 2 values of the stack.")![b](https://$ "Push the hexadecimal (10-15)")![2](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.") ![1](https://$ "Push the number (0-9)")![0](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![<](https://$ "Change Cursor Direction")![.](https://$ "Pop 2 values of the stack then move to that position.")![0](https://$ "Push the number (0-9)")![2](https://$ "Push the number (0-9)")![}](https://$ "Shifts the entire stack left or right")![}](https://$ "Shifts the entire stack left or right") ![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![~](https://$ "Delete the top element of the stack")![{](https://$ "Shifts the entire stack left or right")![{](https://$ "Shifts the entire stack left or right")![l](https://$ "Push the length of the stack to the stack")![2](https://$ "Push the number (0-9)")![,](https://$ "Divide the top 2 values of the stack.")![0](https://$ "Push the number (0-9)")![6](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.") ![v](https://$ "Change Cursor Direction") ![\](https://$ "Reflect the cursor direction")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![(](https://$ "Greater than, less than. Push 1 or 0 to the stack.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![o](https://$ "output a character")![:](https://$ "Duplicate the top item on the stack")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![[](https://$ "Pop N from the stack, then create a new stack containing the top N elements of the old stack.")![{](https://$ "Shifts the entire stack left or right")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![}](https://$ "Shifts the entire stack left or right")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.")![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack") ![\](https://$ "Reflect the cursor direction")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![~](https://$ "Delete the top element of the stack")![$](https://$ "Move the top element of the stack back 1")![}](https://$ "Shifts the entire stack left or right")![}](https://$ "Shifts the entire stack left or right")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![b](https://$ "Push the hexadecimal (10-15)")![2](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.") !['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![)](https://$ "Greater than, less than. Push 1 or 0 to the stack.")!['](https://$ "Enable or disable string parsing mode. In string parsing mode all characters are pushed to the stack instead of executed.")![/](https://$ "Reflect the cursor direction")![.](https://$ "Pop 2 values of the stack then move to that position.")![3](https://$ "Push the number (0-9)")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![o](https://$ "output a character") ![>](https://$ "Change Cursor Direction")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![;](https://$ "Halt") ![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![\](https://$ "Reflect the cursor direction")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![:](https://$ "Duplicate the top item on the stack")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![[](https://$ "Pop N from the stack, then create a new stack containing the top N elements of the old stack.")![{](https://$ "Shifts the entire stack left or right")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![:](https://$ "Duplicate the top item on the stack")![}](https://$ "Shifts the entire stack left or right")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![:](https://$ "Duplicate the top item on the stack")![@](https://$ "Move the top elemnt of the stack back 2")![l](https://$ "Push the length of the stack to the stack")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![2](https://$ "Push the number (0-9)")![,](https://$ "Divide the top 2 values of the stack.")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![:](https://$ "Duplicate the top item on the stack")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![=](https://$ "Pop 2 values of the stack, push 1 if they are equal and 0 otherwise")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![$](https://$ "Move the top element of the stack back 1") ![{](https://$ "Shifts the entire stack left or right")![{](https://$ "Shifts the entire stack left or right")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![>](https://$ "Change Cursor Direction")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![~](https://$ "Delete the top element of the stack")![}](https://$ "Shifts the entire stack left or right")![}](https://$ "Shifts the entire stack left or right")![5](https://$ "Push the number (0-9)")![0](https://$ "Push the number (0-9)")![a](https://$ "Push the hexadecimal (10-15)")![o](https://$ "output a character")![.](https://$ "Pop 2 values of the stack then move to that position.")![/](https://$ "Reflect the cursor direction")![~](https://$ "Delete the top element of the stack")![0](https://$ "Push the number (0-9)")![}](https://$ "Shifts the entire stack left or right")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.") ![.](https://$ "Pop 2 values of the stack then move to that position.")![6](https://$ "Push the number (0-9)")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![>](https://$ "Change Cursor Direction")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![:](https://$ "Duplicate the top item on the stack")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![[](https://$ "Pop N from the stack, then create a new stack containing the top N elements of the old stack.")![{](https://$ "Shifts the entire stack left or right")![/](https://$ "Reflect the cursor direction")![>](https://$ "Change Cursor Direction")![1](https://$ "Push the number (0-9)")![{](https://$ "Shifts the entire stack left or right")![{](https://$ "Shifts the entire stack left or right")![6](https://$ "Push the number (0-9)")![9](https://$ "Push the number (0-9)")![!](https://$ "Skip the next instruction, moving 2 spaces instead of 1")![.](https://$ "Pop 2 values of the stack then move to that position.")![<](https://$ "Change Cursor Direction")![9](https://$ "Push the number (0-9)")![6](https://$ "Push the number (0-9)")![{](https://$ "Shifts the entire stack left or right")![{](https://$ "Shifts the entire stack left or right")![1](https://$ "Push the number (0-9)")![~](https://$ "Delete the top element of the stack")![$](https://$ "Move the top element of the stack back 1")![<](https://$ "Change Cursor Direction") ``` Hover over any symbol to see what it does. If this appears glitched unformulated version below. [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaT46P3Z+bDIsYjIuXG4xMC0xPC4wMn19XG46P3Z+e3tsMiwwNi5cbnYgXFwmJygnbzoyKlt7MSt9XSQ6XG5cXDo/dn4kfX0mMS1iMi5cbicpJy8uMzEtMW9cbj46P3Y7XG4xKyZcXCY6MipbezEtOn1dP3Y6QGwxLTIsJjomLTErPT92JFxue3smPjo/dn59fTUwYW8uL34wfV1cbi42MS0xJj4xLSY6Mipbey8+MXt7NjkhLjw5Nnt7MX4kPCIsImlucHV0IjoiNCIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6Im51bWJlcnMifQ==) If the "fancy" formatting above doesn't display for you, a version without formatting: ``` i>:?v~l2,b2. 10-1<.02}} :?v~{{l2,06. v \&'('o:2*[{1+}]$: \:?v~$}}&1-b2. ')'/.31-1o >:?v; 1+&\&:2*[{1-:}]?v:@l1-2,&:&-1+=?v$ {{&>:?v~}}50ao./~0}] .61-1&>1-&:2*[{/>1{{69!.<96{{1~$< ``` [If my Interpreter is too slow for you, TIO link](https://tio.run/##JY1BCsIwEEVXbnIKhTBR26SZiIHG2noP24UuxEKhCyGbYXr12Oj28d/7r/HzTmlsQxeXyZVPZwRajY2xjllkSrRy642I2x7UXs3BHe@EBQ8yiD4vJDOgzqo6qMqcUOMscvEisIAe/oIOPHQx3CbUroQAGotrF6Uggt8789k@ZlMtlgdh/BqBFvVfrlok8vXONLUnwkU2KW2@) [![enter image description here](https://i.stack.imgur.com/VDBad.png)](https://i.stack.imgur.com/VDBad.png) Not super well golfed, relying on people being too intimidated by fish. ## How this works The standard recursive version doesn't work well for fish because: * It doesn't have functions * There is no easy way to copy an array * The only array type thing you have is the stack and there is only one of them I came up with a completely different approach that does not involve recursion at all, and uses O(n) memory. We note that, for a number of parenthesis N, we can place opening parenthesis on fixed places then just dynamically decide where to place the closing one that matches it. We can use this to encode a given configuration as the distance between each opening and the corresponding closing parenthesis (+1 for technical reasons) ``` (())()() = 2, 1, 1, 1 ((()())) = 3, 2, 1, 1 (((()))) = 4, 3, 2, 1 ()()(()) = 1, 1, 2, 1 ``` Now all we need to find is an algorithm that can, from one set of numbers, figure out the "next" valid configuration. ### Rendering The render loop works as follows: We store next to each number an extra 0. This 0 represents the number of closing parenthesis that need to be drawn after that number. Now, when we for example need to render a parenthesis with a distance of 1, we increment the value in the stack at 2 \* 1. In this case it will be the closing parenthesis for the same number. Then after printing the `(` we can print N `)` characters depending on the value stored. All of this means we can avoid any kind of recursion. ### Incrementing The incrementing logic is harder, but we can re-use the information from the closing parenthesis from the render stage. First, we try to increment the order of the last opening brace. If this makes us extend past the edge of the set, we skip and go to the next one. This part is easy. An harder part is making sure the area we enclode does not partially intersect any other pair. There couldn't be any pairs to the right since they have all been reset to 1, but there could be intersecting pairs to the left. For this purpose, we check the closing parenthesis again. We subtract one closing parenthesis from N steps to the front. If they are now zero, we can safely increment past the boudary. Otherwise, we must again reset and try the next pair to the left. If we have found a opening that can be incremented, we must reset the rest of the ")" counters to 0, then can render and continue. If we have reached the leftmost brace and it also can't be incremented, we have tried all sets and we can safely exit. ## Approximately the same algorithm in Rust ``` |x|{ let mut z=vec![(1,0);x]; loop{ for i in 0..x{ print!("("); let closing_index = z[i].0 + i - 1; z[closing_index].1+=1; print!("{}",")".repeat(z[i].1)); } let mut done=false; for i in 0..x{ let closing_index =z[i].0 + i - 1; z[closing_index].1-=1; if !done && !(i + z[i].0 >= x || z[closing_index].1> 0) { z[i].0+=1; done=true; } } if !done { return; } println!(); } } ``` [Answer] # [Simplify Path](https://leetcode.com/problems/simplify-path/), 119 Bytes, Python 3, \$O(n)\$, 16:20 UTC ([cracked by Value Ink](https://codegolf.stackexchange.com/a/263084/114446), 20 points) ``` def f(p): s=[] for x in p.split('/'): if x=='..'and s:s.pop() elif x and x not in'..':s+=[x] return f'/{"/".join(s)}' ``` [Answer] # [Python 3](https://docs.python.org/3/), 144 bytes, [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/), O(N), Time: 2023-07-20 17:17:27Z. # 83 min = 17 points # [Cracked by CursorCoercer (125 bytes)](https://codegolf.stackexchange.com/a/263088/73054) ``` def f(s): m=x=y=0;c={0,} while y<len(s): if s[y]in c: while s[x]!=s[y]:x+=1 x+=1;c={*s[x:y]} c.add(s[y]);y+=1;m=max(m,y-x) return m ``` [Try it online!](https://tio.run/##TY5BCoMwEEX3nmLqRtPaorjTzknEhYkRpSYVoySh9OxpgoUWBob57/GZxW7jU5bO9XyAIVWkikCgQYt5zfCVZ@8I9DjNHOx95vIQYBpANbadJLBwfg3VmPaEAVTmgkUAYYees2eVbX0ZsFvX92mwSG0DFig6k4rMXg2JYOXbvkoQrlOKr5v/Ke4o80NpTBDL6JdTemTFX7Zo/eD6MJd1kluaqJ0xrlRC3Ac "Python 3 – Try It Online") Runs in O(N) because python sets have lookup/add of O(1). Using lists could decrease the byte count but would technically increase the runtime to O(N^2) [Answer] # [Edit Distance](https://leetcode.com/problems/edit-distance/), [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 124 bytes, \$O(mn)\$ complexity, [cracked by SuperStormer](https://codegolf.stackexchange.com/a/263279/73054) (I won't bother trying to score since I had to edit my answer and the scoring system was flawed) ``` lambda a,b:(d:=range(len(b)+1),[d:=[x:=d[(j:=0)]+1]+[x:=min(x+1,d[(j:=j+1)]+1,d[j-1]+(i!=k))for k in b]for i in a])and d[-1] ``` [Try it online!](https://tio.run/##VYtBDoIwEEX3nqKyakNNJG5Mk56kdjHQIgWZkhYTPD22GA2u5v/330yvufN4uU5hbeVtfcBYGyDAa0GNkAHwbunDIq1ZWTGuElOLkEbRXsgz02WlywxGh3QpK/4Z@uTqrfWnJFB3lANjrQ9kIA5JrXN0OYJmgIYYlbx1Cg5n2tKi8yHagpMi@FgwdvgN6Vicncc82sU2z63sFePiDNhs77Hpxm/dO5DHP5IBJLK@AQ "Python 3.8 (pre-release) – Try It Online") Ya like walrus operators? Complexity is \$O(mn)\$ where m,n are the lengths of the two input strings. Time: 2023-07-20 16:18:22Z [Answer] # [Reverse words in string](https://leetcode.com/problems/reverse-words-in-a-string/), Python, 47 bytes, \$O(n)\$ complexity, [Cracked by The Thonnu](https://codegolf.stackexchange.com/a/263074/91213), 6 point ``` lambda g:print(*map(str.strip,g.split()[::-1])) ``` > > Given an input string s, reverse the order of the words. > > > A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. > > > Return a string of the words in reverse order concatenated by a single space. > > > Note that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. > > > Time: 2023-07-20 13:35:51Z [Answer] # [Count and Say](https://leetcode.com/problems/count-and-say/), [Go](https://go.dev), 173 bytes, \$O(n^2)?\$, 2023-07-20 21:22:03 UTC ## [Cracked by C--](https://codegolf.stackexchange.com/a/263095/77309), score 5 ``` import."fmt" func g(n int)string{s:="1" for N:=1;N<n;N++{c,o,f,k:=1,"",rune(s[0]),s[1:]+"_" for _,r:=range k{if r==f{c++}else{o+=Sprintf("%d%c",c,f);f,c=r,1}} s=o} return s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU_LasQgFN37FSIMKN6WkW5KMvcXQqHLYRiCjUEy0aBmJX5JN6HQXftB_Zs6j9W53MN5fX6NfvtZej3140Dn3rrvNZmn179fOy8-pGdm5sSIWZ2mI3fUuiRiCtaNOTbIVKV8oF2Dqu0Oru2kzBo8GJjqCxiDsLqBx-P-JCAeVXOS7HzXnCE0GHpXY6dsDQ2IJmspy3CJQ_YS35cakwxnu4-dZqDBiNaAxgCqFBLRFxKGtAZHY3mUxlvP6wouaL7FWNogVW3FA9KXfT2krNTb1fviuIU6ywpBCnmYbNsd_wE) A slight modification of my [Say What You Can See](https://codegolf.stackexchange.com/a/263092/77309) answer. Enjoy Golang! [Answer] # Python, 47 bytes, [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/description/), `O((m+n)mn)` ``` f=lambda x:x and[*x[0]]+f([*zip(*x[1:])][::-1]) ``` > > Given an m x n matrix, return all elements of the matrix in spiral order. > > > Time: 2023-07-21 08:54:05Z [Answer] # [Repeated String Match](https://leetcode.com/problems/repeated-string-match/description/), 48 bytes, Excel, 20:08 UTC, *O*(*n*) ``` =IFNA(XMATCH(0,0*FIND(B1,REPT(A1,ROW(A:A)))),-1) ``` Inputs: *a* and *b* in cells `A1` and `B1` respectively. [Answer] # [Ruby](https://www.ruby-lang.org/), 184 bytes, [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/) ``` ->s,d{l,*r=d.size*z=d[0].size c={};d.map{|w|c[w]=d.count w} 0.step(z-1){|i|j=i;b=Hash.new 0 (r<<j-l if c.all?{|w,v|v==b[w]} b[s[j-l,z]]-=1if j>=l b[s[j,z]]+=1 j+=z)while j<s.size+l} r} ``` [Try it online!](https://tio.run/##bY/LboMwEEX3/opZdJHwsGAdJtn2HyiqbGwSkIMRJrHK49vpAFJXlcej6@PRkd2/5M9a4dcaX12kJhMFPSru6lEHI6o8KfbMSpyWi@JP0U2zn8vcFzRV2lc7gF9Ywt2gu9MYp@dprucG64vET@EevNUeEnbqs6yJDdQVlFwYcyNJ9J7fiJJMC5O5y@k@GosixpSmmiuag24sxJQ1IY5n/6iNhiZz@6NCs7B@WQ9414NjAC4KFCAEH9/cdaYeCHVQ5fS1gulWrVL0lbXDQ1On/BQtUAKKzNte3a3921K7YWOwt43AhvYjE5KWkEAlBRU7xIf1Pz0Q/AU "Ruby – Try It Online") Complexity should be \$O(mn)\$ where \$m\$ is the number of *unique* words (relevant for a testcase on LeetCode where the words list has multiple copies of "a") and \$n\$ is the length of the string. Current time is 2023-07-21 00:04 UTC [Answer] # [Generate Parenthesis](https://leetcode.com/problems/generate-parentheses/), [Rust](https://www.rust-lang.org), 193 bytes, \$O(n!)\$ [Cracked by C--](https://codegolf.stackexchange.com/a/263097/91213), 1 point * C-- generously helped me save 1 point before cracking it in an actually significant way ``` fn f(z:i32)->Vec<String>{if z<1{vec![format!("")]}else{(0..z).flat_map(|i|->Vec<_>{let(a,b)=(f(i),f(z-i-1));a.iter().flat_map(|c|b.iter().map(move|d|format!("({c})")+d)).collect()}).collect()}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBLTsMwEIb3OYXr1YywoybZoD7SQyCxiaLKdezKkuNUqdtFnJyETRdwBA7AMbgNBgLqrOah-ef_5uW1v5z9e0U5V43xpnOUEZov84zWt7eL1_zx80M7omFYmSJHXj4ruXnyvXHHMhhNhk0WrkouKt31rfALoBTrSdmzCrBM0wFTbYXft-IEoxl_1_dlsMqDYAfcggaDLMpzwzPEtUiNVz3cr8nx8Nf8rtvuqsZm_L8HQU5I8aFBTGVnrZIecLrPpxlkF0FaYRwgCQmJcYoY3rooEla7KZJrKKKH5GcYLRJBtqTKWM6Kep3MMrf5L18) Time: 2023-07-21 05:01:42Z [Answer] # [Sum of Scores of Built Strings](https://leetcode.com/problems/sum-of-scores-of-built-strings/), [C (GCC)](https://gcc.gnu.org), 71 bytes, \$O(n^2)\$ complexity, [Cracked by mousetail](https://codegolf.stackexchange.com/a/263102/91213), 93 points ``` f(s,l,i)char*s;{for(i=0;s[i]&&s[l+i]==s[i];++i);return l?i+f(s,l-1):i;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVA7DsIwDN19iqgIlLQFwYYIhZFDAEIhbcFSSFGSMrTiJCwsTJyI25DwkcD24qf3sXy5yc1Oyuv1VruyP34sSmpTlSKTe2Fiy9uyMhSzIbdLXPd6dqkSXGdZ2HiSIOOmcLXRRM0xeUn7IzZBfv7Y3Tuoparzgkyty7Ea7GfwCxnUu4DBqcIcXGEdDcEktgxaIOToCa6kUTdf6SglIYF4lSo0tYwxDmcAz4CDQE2Dx1v2Moq2wnfkSV9ANFs_jWj-QF9h_5z8_cQT) Time: 2023-07-20 21:33:27Z [Answer] # Python, 48 bytes, [Count Number of Distinct Integers After Reverse Operations](https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/description/), `O(nd)` ``` lambda x:len({*x}|{int(str(c)[::-1])for c in x}) ``` > > You are given an array nums consisting of positive integers. > > > You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums. > > > Return the number of distinct integers in the final array. > > > Time complexity is `O(nd)` where n is the number of elements in the input, and d is the number of digits in the largest number. Time of post: 2023-07-21 08:21:19Z ]
[Question] [ Today (or tomorrow, depending on your timezone, by the time of posting) is the birthday of the great mathematician and physicist [Leonhard Euler](https://en.wikipedia.org/wiki/Leonhard_Euler). To celebrate his birthday, this challenge is about one of his theorems in geometry. For a triangle, we define its [incircle](https://mathworld.wolfram.com/Incircle.html) to be the largest circle inside the triangle and its [circumcircle](https://mathworld.wolfram.com/Circumcircle.html) to be the circle that passes through all of the traingle's vertices. Consider a triangle in a plane, we plot the center of its incircle I (sometimes called [incenter](https://mathworld.wolfram.com/Incenter.html)) and the center of its circumcircle O (sometimes called [circumcenter](https://mathworld.wolfram.com/Circumcenter.html)). Let \$r\$ be the radius of the incircle, \$R\$ be the radius of circumcircle, \$d\$ be the distance between I and O. [Euler's theorem in geometry](https://en.wikipedia.org/wiki/Euler%27s_theorem_in_geometry) states that \$d^2=R(R-2r)\$. # The challenge In the spirit of this theorem, your task, is for a triangle given by the lengths of its three sides, output \$d\$ (the distance between incenter I and circumcenter O described above). * Your code needs to take only the length of the three sides of triangle and output \$d\$. Inputs and outputs can be in any reasonable format. * The absolute error or relative error from your output and correct answer must be no greater than \$10^{-2}\$. * It's guaranteed that the three side lengths are positive integers and can form a non-degenerate triangle. * Standard loopholes are forbidden. Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins! # Examples In the samples, the outputs are rounded to 3 decimal places. You, however, are free to round them to more decimal places. ``` [a,b,c] -> d [2,3,4] -> 1.265 [3,4,5] -> 1.118 [3,5,7] -> 3.055 [7,9,10] -> 1.507 [8,8,8] -> 0.000 [123,234,345] -> 309.109 ``` List of sample inputs: `[[2,3,4],[3,4,5],[3,5,7],[7,9,10],[8,8,8],[123,234,345]]` [Answer] # JavaScript (ES7), ~~80 74 66~~ 65 bytes ``` (a,b,c)=>(s=a+b+c,(p=a*b*c/s)*p/4*(s/=2)/(s-a)/(s-b)/(s-c)-p)**.5 ``` [Try it online!](https://tio.run/##fc7NDoMgEATge59kFxep/MT2QI99D0BtbIyQYpq@PTXevJBJ5jLfYd7u63L4zGnjaxzGMtkCjjwFtA/I1jW@CQTJOuZZEBlZEppBFlaigMzd0f7ogDwhY60pIa45LmO7xBdMIEmRxnaLz/k3DqAQL2ewz2TqwFBfAz3dqbvWxI321EAnFUmlSenzlfIH "JavaScript (Node.js) – Try It Online") ### How? This is derived from: * The semiperimeter \$s\$ of the triangle: $$s=\frac{a+b+c}{2}$$ * The circumradius \$R\$ of the triangle: $$R=\frac{abc}{4\sqrt{s(s-a)(s-b)(s-c)}}$$ * The product of the inradius \$r\$ and the circumradius: $$rR=\frac{abc}{2(a+b+c)}=\frac{abc}{4s}$$ * Euler's theorem: $$d=\sqrt{R(R-2r)}=\sqrt{R^2-2rR}=\sqrt{R^2-\frac{abc}{2s}}$$ [Answer] # Python 3, 66 bytes This formerly took advantage of the [new assignment expressions ("walrus operator")](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions) introduced in Python 3.8. Thanks to commentors, I've taken that out, so it works on previous versions too! ``` lambda a,b,c:((a*b*c/(b+c-a)/(a+c-b)/(a+b-c)-1)*a*b*c/(a+b+c))**.5 ``` [Try it online!](https://tio.run/##bY/RioMwEEXf/Yp5nNgxTYypteCfLJQkprSgjZg87H69G9wFd8GZhyE5916481d6hrdaB@g/1tFMdjBgyJK7IZrSlu6M9uQqw85o8rXbtZVjlWTlryB/nBxjZcn1@ljCBJNJT3hNc1gSvKIbQ/RF8jHdnYk@Qg@IWJOihhFIXl80owL@DWKmpDcu5fWQa2ozV1zoI39LHUmxBWjRHgiulDdzwYUQB1zWimrVkGpyvBIdl6JjrHiEBdAQWAKX3f5z9i63fMNe8LZlmRj93h9/hATDH/Pix3sKYy99JWoCY@P@ZOs3 "Python 3 – Try It Online") It's based on the same calculations described in [Arnauld's answer](https://codegolf.stackexchange.com/a/203493/13959), but using the perimeter \$p\$ instead of the semiperimeter \$s\$: $$ \begin{aligned}\\ p&=a+b+c\\ &=2s \end{aligned}\\ \therefore d=\sqrt{R^2-\frac{abc}{p}}\\ \text{and } R^2=\frac{\left(abc\right)^2}{p(p-2a)(p-2b)(p-2c)} $$ The grand total savings of this rearrangement is... two bytes. Factoring \$p\$ out and expanding the terms in the denominator means I don't have to store \$p\$, saving another three bytes. I also stored the product \$abc\$ in a variable \$m\$, which saved some bytes at first... but it could later be factored out, turning the brackets-and-walrus into a liability, not a savings! Here's the final formula: \begin{aligned} d&=\sqrt{\frac{\left(abc\right)^2}{p(p-2a)(p-2b)(p-2c)}-\frac{abc}{p}}\\ &=\sqrt{\left(\frac{abc}{(b+c-a)(a+c-b)(a+b-c)}-1\right)\frac{abc}{p}} \end{aligned} [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~31~~ 18 bytes ``` I₂∕×⊖∕ΠθΠ⁻Σθ⊗θΠθΣθ ``` [Try it online!](https://tio.run/##RYs7D8IgFIX/iuNtgoOlnRxlNWmsW9MB4SaS8AgX6N9HsWk803l8R70lqSBtrRMZn@EmU4Y5Fkn4CCGDMJvRCE/jMIFARejQZ9THMFHQRWWIHTsd/m58STAX92tFKC/7PcSu6U/FFnao6Vrrslx6zno@MD6M61rPm/0A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a vector of doubles and outputs a double. Explanation: $$ \begin{align}d &=\sqrt{R(R-2r)}\\ &=\sqrt{R^2-2Rr}\\ &=\sqrt{\left(\frac{abc}{4\Delta}\right)^2-\frac{abc}{2s}}\\ &=\sqrt{\frac{(abc)^2}{16\Delta^2}-\frac{abc}{2s}}\\ &=\sqrt{\frac{(abc)^2}{2s(2s-2a)(2s-2b)(2s-2c)}-\frac{abc}{2s}}\\ &=\sqrt{\frac{abc}{2s}\left(\frac{abc}{(2s-2a)(2s-2b)(2s-2c)}-1\right)}\\ \end{align} $$ where \$ 2s=a+b+c \$ and \$ \Delta=\sqrt{s(s-a)(s-b)(s-c)} \$. ``` ⊗θ `[2a, 2b, 2c]` ⁻Σθ Vectorised subtract from `a+b+c` Π Take the product ∕Πθ Divide `abc` by that ⊖ Decrement × Πθ Multiply by `abc` ∕ Σθ Divide by `a+b+c` ₂ Take the square root I Cast to string Implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~22~~ ~~21~~ ~~20~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` PDIœÆPt/<*IO/t ``` -5 bytes porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/203505/52210), so make sure to upvote him!! -1 byte thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f8/wMXz6OTDbQEl@jZanv76Jf//RxvpGOuYxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/AJfKo5MPtwWU6NtoVfrrl/x3MdY7vElJQePwfk2lQ6t1/kdHG@kY65jE6kQDSR1TMG2qYw6kzXUsdQwNgAwLHSAE0oZGxjpGxiY6xiamsbEA). **Explanation:** ``` P # Take the product of the (implicit) input-list # [a,b,c] → abc D # Duplicate it Iœ # Get all permutations of the input-triplet # [a,b,c] → [[a,b,c],[a,c,b],[b,a,c],[b,c,a],[c,a,b],[c,b,a]] Æ # Reduce each by subtracting: # → [a-b-c,a-c-b,b-a-c,b-c-a,c-a-b,c-b-a] P # Take the product of that # → (a-b-c)(a-c-b)(b-a-c)(b-c-a)(c-a-b)(c-b-a) # → (a-b-c)²*(b-a-c)²*(c-a-b)² t # Take the square-root # → sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²) / # Divide the initially duplicated product by it # → abc/(sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²)) < # Decrease it by 1 # → abc/(sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²))-1 * # Multiply it by the initial product # → abc(abc/(sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²))-1) IO/ # Divide it by the input-sum # → abc(abc/(sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²))-1)/(a+b+c) t # And take the square-root of that # → sqrt(abc(abc/(sqrt((a-b-c)²*(b-a-c)²*(c-a-b)²))-1)/(a+b+c)) # (after which it is output implicitly as result) ``` Or as a single formula: $$d=\sqrt{\frac{abc\left(\frac{abc}{\sqrt{(a-b-c)^2\times(b-a-c)^2\times(c-a-b)^2}}-1\right)}{a+b+c}}$$ [Answer] # Java 8, 67 bytes ``` (a,b,c)->Math.sqrt(a*b*c*(a*b*c/(b+c-a)/(a+c-b)/(a+b-c)-1)/(a+b+c)) ``` [Try it online.](https://tio.run/##ZVDBbsIwDL3zFVZPCXXLoFRsQ@wP4MJx2sFJMygrgbUGaZr49s5tM4lpivT88vRkP/tAV0oOxUdrK2oaWFPpv0cApWdXv5N1sOm@AMXpYioHVgVCGIj5JVYvxXkbCTRMXFrYgIdVqwgNWp28rIn3afNZs6KxGdvxUCbKxDYhPVEk1fTVJOKfDjS2WrfLrutZxkjX0Px6Kgs4Sly15br0u9c3ID1kZdewmmGG8z5SEOSL@V8hx8W9sMAnnD7cK48o716YzjKcZXPM5vm/dftEvUuuJwfq0PRoQ7AhKTCsgOIII9muQxtHzxANU7ZfDbtjerpwehYzV15xHEGU1u7sSALkCaeV8zveK61jn9pw3xDn1v4A) Not much to say. Uses the same formula as in [*@TimPederick*'s Python answer](https://codegolf.stackexchange.com/a/203540/52210), which was based on [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/203493/52210), but which uses a rather similar formula as [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/203505/52210). $$d=\sqrt{\frac{abc\left(abc\div(b+c-a)\div(a+c-b)\div(a+b-c)-1\right)}{a+b+c}}$$ [Answer] # [Io](http://iolanguage.org/), 87 bytes Port of Arnauld's answer. ``` method(a,b,c,((y :=b*a*c/(z :=((b+c-a)*(c+a-b)*(a+b-c)/(x :=a+b+c))**.5)/x)*(y-z))**.5) ``` [Try it online!](https://tio.run/##bc3BCsIwDAbgu0/RY9qm1rUdU8E38dLWgYO5DZmw9eVrDgUPlRzy5wskw5yXT0pjz643ds@vfn3OD/AYMCLAThqEF1FDoggQZFSeC4jSq0Ddy6Ai17DRlrKMnAtxbLneaLmrVMbyAwxadJwt72Fax@lQlAzbP9piV2mHF2xOFZ@RqtLGWDTWoXW/8/kL) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~76~~ 72 bytes Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #define f(a,b,c)sqrt(a*b*c*(a*b*c/(0.+b+c-a)/(a+c-b)/(a+b-c)-1)/(a+b+c)) ``` [Try it online!](https://tio.run/##fc5LDsIgEAbgvacgGhOgAx1KsTZexQ2MtmlSG18749VFfK6szOKfTD4GSLVEMc4226YbtqzhHgKQOB2OZ@5lkCRfkXPUWchIeZFznzI8MygSyrzajISI3XBmO98NXLDLhKWzP6ZRw6fzdj1MIT1QgIVSiBXLJTO6WDgm898yOXBfaczyj3RQvaXV6MZ3VlCDwe9Sh9UoXUKqt0SNiKPSFBYKW4ItP9@1WGuD9ePGNd6o6X17iqrf3QE "C (gcc) – Try It Online") Port of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [Java answer](https://codegolf.stackexchange.com/a/203542/9481). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410) ``` .5*⍨×/÷+/÷¯1+⊢×.÷+/-+⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qi2fYo7YJhv/1TLUe9a44PF3/8HZtID603lD7Udeiw9P1QHxdbaDc/zSgwke9fY@6mg@tN37UNhGoOzjIGUiGeHgG/09TMFIwVjDhSgORCqZg2lTBHEibK1gqGBoAGRYgCKQNjYwVjIxNFIxNTAE "APL (Dyalog Unicode) – Try It Online") Yet another port of [Tim Pederick's Python answer](https://codegolf.stackexchange.com/a/203540/78410). $$ \begin{align} d&=\sqrt{\left(\frac{abc}{(b+c-a)(a+c-b)(a+b-c)}-1\right)\frac{abc}{a+b+c}} \\ &=\sqrt{\frac{abc}{\frac{a+b+c}{\frac{abc}{(b+c-a)(a+c-b)(a+b-c)}-1}}} \end{align} $$ Kind of ugly, but this is precisely what the code does. Requires `⎕DIV←1`, i.e. division by 0 gives 0 (otherwise `a=b=c` case will throw an error). ### How it works ``` .5*⍨×/÷+/÷¯1+⊢×.÷+/-+⍨ ⍝ Input: a 3-length vector [a b c] +/-+⍨ ⍝ (a+b+c) - [2a, 2b, 2c] = [b+c-a, c+a-b, a+b-c] ⊢×.÷ ⍝ product([a,b,c] ÷ above) ¯1+ ⍝ above minus 1 ×/÷+/÷ ⍝ product(a,b,c) ÷ (sum(a,b,c) ÷ above) .5*⍨ ⍝ square root ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 90 bytes ``` : f dup 2over * * s>f fdup 3. do dup 2over - - s>f f/ rot loop 1e f- f* + + s>f f/ fsqrt ; ``` [Try it online!](https://tio.run/##VU7LTsMwELz7K0Y9lbIxfsRNQqX@iJUDJHFBIDk4gd8P66RIwXPwaGZ3dkJM81txC/lblmcE9N8jTPwZEk6M6RoQsmQl@rgzC8ZqPiHFGZ8xjtADQoFwwiPjbobpK824cPQ8TLMADMb37gMSa4xcIyXkAcUVB74fJLokLsLAotyWMnF/1KHaaIUGWm28RsZKtbEwtoQt7yviKPwLvVLXYnt8qBfekKVyJ2lpzk54Fsn9k7Wus@yo2slWKsfTFTWkVbubdqoSvibGblpJpZTwXI24GnG1dg1RjdSqEQ/LLw "Forth (gforth) – Try It Online") Port of [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/203542/78410). Since the inputs are positive integers, it takes the input from the data stack and returns the result through the FP stack. A separate FP stack makes the task a bit easier, but having to work through three alternating sums explicitly is definitely a pain. In order to copy top three elements, I used `dup 2over` which converts `a b c` into `a b c c a b`. Thankfully I didn't need exactly "3dup" because addition `+` and multiplication `*` are commutative, and alternating sums (`c - (a - b)`) are calculated for all three rotations (`abc`, `bca`, `cab`). ``` : f ( a b c -- f:result ) dup 2over * * s>f fdup ( a b c ) ( f: prod prod ) 3. do dup 2over - - s>f f/ rot loop ( a b c ) ( f: prod prod/rots ) 1e f- f* + + s>f f/ fsqrt ; ``` ]
[Question] [ The Steenrod algebra is an important algebra that comes up in algebraic topology. The Steenrod algebra is generated by operators called "Steenrod squares," one exists for each positive integer i. There is a basis for the Steenrod algebra consisting of "admissible monomials" in the squaring operations. It is our goal to generate this basis. A sequence of positive integers is called *admissible* if each integer is at least twice the next one. So for instance `[7,2,1]` is admissible because \$7 \geq 2\*2\$ and \$2 \geq 2\*1\$. On the other hand, `[3,2]` is not admissible because \$3 < 2\*2\$. (In topology we would write \$\mathrm{Sq}^7 \mathrm{Sq}^2\mathrm{Sq}^1\$ for the sequence `[7,2,1]`). The *degree* of a sequence is the total of it's entries. So for instance, the degree of `[7,2,1]` is \$7 + 2 + 1 = 10\$. The *excess* of an admissible sequence is the first element minus the total of the remaining elements, so `[7,2,1]` has excess \$7 - 2 - 1 = 4\$. ## Task Write a program that takes a pair of positive integers `(d,e)` and outputs the set of all admissible sequences of degree `d` and excess less than or equal to `e`. The output is a set so the order of the admissible sequences doesn't matter. ## Examples: ``` Input: 3,1 Output: [[2,1]] ``` Here we are looking for admissible sequences with total 3. There are two options, `[3]` and `[2,1]`. (`[1,1,1]` and `[1,2]` have sum 3 but are not admissible). The excess of `[3]` is 3 and the excess of `[2,1]` is \$2-1 = 1\$. Thus, the only sequence with excess \$\leq1\$ is `[2,1]`. ``` Input: 6, 6 Output: [[6], [5, 1], [4, 2]] (or any reordering, e.g., [[5,1],[4,2],[6]]) ``` Since excess is always less than or equal to degree, we have no excess condition. Thus, we're just trying to find all admissible sequences of degree 6. The options are `[6]`, `[5, 1]`, and `[4, 2]`. (These have excess \$6\$, \$5-1 = 4\$, and \$4-2=2\$.) ``` Input: 10, 5 Output: [[7,3], [7,2,1], [6,3,1]] ``` The admissible sequences of degree 10 are: ``` [[10], [9,1], [8,2], [7,3], [7,2,1], [6,3,1]] ``` These have excess \$10\$, \$9-1 = 8\$, \$8-2 = 6\$, \$7-3 = 4\$, \$7-2-1 = 4\$, and \$6-3-1=2\$ respectively, so the last three all work. ## Scoring This is code golf: Shortest solution in bytes wins. ## Test cases: Any reordering of the output is equally good, so for input `(3, 3)`, outputs `[[3],[2,1]]` or `[[2,1],[3]]` are equally acceptable (however `[[1,2],[3]]` isn't). ``` Input: 1, 1 Output: [[1]] Input: 3, 3 Output: [[2,1], [3]] Input: 3, 1 Output: [[2,1]] Input: 6, 6 Output: [[6], [5, 1], [4, 2]] Input: 6, 4 Output: [[5,1], [4,2]] Input: 6, 1 Output: [] Input: 7, 7 Output: [[7], [6,1], [4,2,1], [5,2]] Input: 7,1 Output: [[4,2,1]] Input: 10, 10 Output: [[10], [9,1], [7,2,1], [6,3,1], [8,2], [7,3]] Input: 10, 5 Output: [[7,3], [7,2,1], [6,3,1]] Input: 26, 4 Output: [15, 7, 3, 1] Input: 26, 6 Output: [[16, 7, 2, 1], [16, 6, 3, 1], [15, 7, 3, 1], [16, 8, 2], [16, 7, 3]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 12 bytes Saved 4 bytes thanks to *Grimy* ``` Åœíʒx¦@P}ʒÆ@ ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//8OFxZPDrcqSeMKmQFB9ypLDhkD//zI2CjY "05AB1E – Try It Online") **Explanation** ``` Åœ # integer partitions í # reverse each ʒ } # filter, keep only elements true under: x # each element doubled ¦ # remove the first element in the doubled list @ # compare with greater than or equal with the non-doubled P # product ʒ # filter, keep only elements true under: Æ # reduce by subtraction @ # compare with greater than or equal to second input ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~67~~ 62 bytes ``` Cases[IntegerPartitions@#,a_/;2a[[1]]-#<=#2>Max@Ratios@a<=.5]& ``` [Try it online!](https://tio.run/##LcsxC4MwEAXg3b8RcDqriVWHqgQ6dShI1xDKUWKbQQWToRD87WlNnL57j3sT2o@a0OoX@rHzVzTKiNts1VutA65WW73MhhPAZ35hKASVMiNtR1h/xy9//JeL4dh2p0qmflj1bAXJ@pFzItOcu8RRoBskroQyElINdeQcCWUDTSQkWgAtjqPaZcc328fJ5n8 "Wolfram Language (Mathematica) – Try It Online") *-4 bytes by @attinat* * `IntegerPartitions@d` : Get all lists of integers summing to `d` * `Cases[,...]`: Filter by the following condition: + `2#& @@# - d <= e &&`: Twice the first element minus the sum is less than `e`, and... + `Max@Ratios@#<=.5`: Ratios of successive elements of the list are all less than 1/2. Because `e` is less than .5, we can turn this into a chained inequality. For a few extra bytes, this is significantly faster: [Try it online!](https://tio.run/##DcyxCoMwEADQ3d8IuDSpidCpRoKdCi1I1@MoR4mawQjJDQXx29O@D3gr8eJX4vChMtlyo@wz3CP72aeREgcOW8wg5BD44ePMC4iTQWVQ0ru5tgRgEJXorGj7J33d639t2VFnzxesy5hCZBCqn5wTWDdur3ajtTT6qI7yAw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (a smart adjustment to the checking allowing a single filter) ``` :Ɲ;_/>¥’Ạ ŒṗUçƇ ``` A dyadic link accepting a positive integer, `d`, on the left and a positive integer, `e`, on the right which yields a list of lists of positive integers. **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//OsadO18vPsKl4oCZ4bqgCsWS4bmXVcOnxof///8xMP81 "Jelly – Try It Online")** (the footer formats the results to avoid list the implicit list formatting Jelly does as a full program) ### How? ``` :Ɲ;_/>¥’Ạ - Link 1: admissible and within excess limit? descending list, L; excess limit, e Ɲ - neighbour-wise: : - integer division -- admissible if all these are >1 ¥ - last two links as a dyad - i.e. f(L,e): / - reduce (L) by: _ - subtraction > - greater than (e)? (vectorises) -- within excess if all these are ==0 ; - concatenate ’ - decrement (vectorises) Ạ - all (non-zero)? ŒṗUçƇ - Main link: integer, d; integer, e Œṗ - partitions (of d) U - reverse each Ƈ - filter keep those (v in that) for which: ç - call last Link (1) as a dyad - i.e. f(v, e) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ ~~58~~ 54 bytes *1 byte saved thanks to nimi* *4 bytes saved thanks to xnor* ``` 0#_=[[]] d#m=do i<-[1..div(m+d)2];(i:)<$>(d-i)#(2*i-d) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30A53jY6OjaWK0U51zYlXyHTRjfaUE8vJbNMI1c7RdMo1loj00rTRsVOI0U3U1NZw0grUzdF839uYmaebUFRZl6JipGZstl/AA "Haskell – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~88 87~~ 81 bytes Takes input as `(e)(d)`. Prints the sequences to STDOUT. ``` e=>g=(d,s=x=d,a=[])=>s>0?d&&g(d-1,s,a,g(d>>1,s-d,[...a,d])):a[s]*2-x<=e&&print(a) ``` [Try it online!](https://tio.run/##Tc3dCsIwDAXge58iFzJaycY6f1FTH2QMLKYORZzYIYLs2Wf8pXfn44STo7u5sLseLm16W/R76j3ZmhRjoDsxOiorTTbYfMNJUitODQZ0KMlaiSljmWWZQ660XroyVKMiva/JJ8nleji3yum@9aEFAtkEr4EsPGDXnENz8tmpqdWWpRw@uJP6nXy33OoV7JXXiiXEx8JuMHgtKjAIYPQXY8E4xr@ZCWYxJjH@Z3PBPMavMTmCySPA9IsiXis@f/on "JavaScript (V8) – Try It Online") ### Commented ``` e => // e = maximum excess g = ( // g is a recursive function taking: d, // d = expected degree; actually used as the next candidate // term of the sequence in the code below s = // s = current sum, initialized to d; we want it to be equal // to 0 when a sequence is complete x = d, // x = copy of the expected degree a = [] // a[] = current sequence ) => // s > 0 ? // if s is positive: d && // if d is not equal to 0: g( // outer recursive call: d - 1, // decrement d s, // leave s unchanged a, // leave a[] unchanged g( // inner recursive call: d >> 1, // update d to floor(d / 2) s - d, // subtract d from s [...a, d] // append d to a[] ) // end of inner recursive call ) // end of outer recursive call : // else: a[s] * 2 - x // s if either 0 (success) or negative (failure) // if s is negative, a[s] is undefined and this expression // evaluates to NaN, forcing the test to fail <= e // otherwise, we test whether the excess is valid && print(a) // and we print a[] if it is ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` f!>-FTvzf!<#2/MCtBT_M./ ``` [Try it online!](https://tio.run/##K6gsyfj/P03RTtctpKwqTdFG2Ujf17nEKSTeV0///38jMy4zAA "Pyth – Try It Online") ``` f!>-FTvzf!<#2/MCtBT_M./Q Implicit: Q=input 1, vz=input 2 Trailing Q inferred ./Q Generate partitions of Q (ordered lists of integers which sum to Q) _M Reverse each f Filter keep elements of the above, as T, where: CtBT Pair the set with itself without the first element and transpose This yields all adjacent pairs of values /M Integer divide each pair # Filter keep elements... < 2 ... less than 2 For admissible sequences this will be empty ! Logical NOT - maps [] to true, populated lists to false Result of filter are all admissible sequences f Filter keep the above, as T, where: -FT Reduce T by subtraction to get degree !> vz Is the above not greater than vz? Implicit print ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~213 bytes~~ Giant list comprehension. Most likely not the best way to do this, but I can't figure out how to skip the if statements ``` import itertools as z f=lambda d,e:[c for c in [[b for b in list(z.permutations(range(1,d+1),i)) if sum(b)==d and b[0]-sum(b[1:i])<=e and all([b[i]>=b[i+1]*2 for i in range(len(b)-1)])] for i in range(1,5)] if c] ``` # [Python 3](https://docs.python.org/3/), 172 bytes ``` from itertools import* r=range f=lambda d,e:filter(len,[[b for b in permutations(r(1,d+1),i)if d==sum(b)and~e<d-2*b[0]and all(i>=j*2for i,j in zip(b,b[1:]))]for i in r(5)]) ``` [Try it online!](https://tio.run/##XYy7TsQwEEX7fMWUM8FIcWC3WGF@JEphyzbMyi9NvAUU/HrYUK0oz7lXp331z1pe9j1KzcA9SK81bcC5VenjIEZs@QhDNMlm5y14FS6R0/2IKRS1LA5iFXDABVqQfOu2cy0bCmrlnzQpJo7gjdluGR3Z4n/Cm3@eR7dM653ApoT8bq7jfIRYXY/UNzd0yi36shKtf8OhBU@00t6ES8cxop7UiWh4ZD09ivmsXv/xmWj/BQ "Python 3 – Try It Online") As according to edits by @Jonas Ausevicius [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` Fθ⊞υ⟦⊕ι⟧FυF…·⊗§ι⁰θ⊞υ⁺⟦κ⟧ιIΦυ›⁼Σιθ‹η⁻⊗§ι⁰Σι ``` [Try it online!](https://tio.run/##dY27CsJAEEV7v2LKGVghFlapxBeCQtAypFiT0SyuG7KP4N@vm6SwcpoZmHPPrVtp607qGB@dBewJiuBaDALKk6ktv9l4blBRRfliQgLBtNNbB6cGvkrzZNx14a4TufEn0/AHlYCMSEBPP2WRAli@KgGKkq6wynjcSufxoLRnOzJHy3I8932Q2uEtvFP5qBFwZuewFXBRJnn@Fc6JefIYy1UmYF3F5aC/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fθ⊞υ⟦⊕ι⟧ ``` First create a list of lists from `[1]..[d]`. ``` FυF…·⊗§ι⁰θ⊞υ⁺⟦κ⟧ι ``` For each list create new lists by prefixing all the numbers from the doubled first number up to `d` and append those lists to the list of lists to be processed. This ensures that all admissible sequences containing numbers not greater than `d` are created. ``` IΦυ›⁼Σιθ‹η⁻⊗§ι⁰Σι ``` Output only those lists whose degree is `d` and excess is not greater than `e`. (The sum of the degree and excess is equal to twice the first number of the list.) [Answer] # [Python 3](https://docs.python.org/3/), 156 bytes ``` lambda d,e:[x for y in range(5)for x in permutations(range(1,d+1),y)if all(i>=j*2for i,j in zip(x,x[1:]))and d==sum(x)and~e<d-2*x[0]] from itertools import* ``` takes `d,e` as input; outputs list of tuples *Similar to @OrangeCherries answer and help from comments; but more bytes saved* [Try it online!](https://tio.run/##Vcu9DoIwFIbh3as4Yw/WhKI4GPFGkKGmrR5Df1JqUhy8dUzjguPzfvnCnB7e7RfTXZdR2puSoLg@9RmMjzADOYjS3TVrsYRcQtDRvpJM5N3EfqvgaiuQz0gG5DgyunTPqikP4s/yeVNgmedenAZE6RSorpteluWCjz6rXVPlvh6GjYneAiUdk/fjBGSDj6laQiSXmGGi5i3iZkVRr9wc@eGfR8TlCw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ŒṗU:Ɲ’ẠƊƇUṪ_SƊ’<ʋƇ ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//xZLhuZdVOsad4oCZ4bqgxorGh1XhuapfU8aK4oCZPMqLxof///8xMP81 "Jelly – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` g=->(d,e,m=1){d<m ?[]:g[d-m,e+m,m*2].map{|q|q+[m]}+g[d,e,m+1]|(d>e ?[]:[[d]])} ``` [Try it online!](https://tio.run/##KypNqvz/P91W104jRSdVJ9fWULM6xSZXwT461io9OkU3VydVO1cnV8soVi83saC6prCmUDs6N7ZWGygJUq9tGFujkWKXCtYQHZ0SG6tZ@79AIT3ayEzHLPY/AA "Ruby – Try It Online") ]
[Question] [ **Task** Given a letter (A, B, C), and a number (0-10), output the size of the matching standard paper size (Series A and B) or the matching standard envelope size (C series) in millimetres in the format `aaaa x bbbb` where `aaaa` and `bbbb` are the width and height measurements in millimetres as per ISO216 (Series A & B) or ISO296 (Series C) To make things easier I will quote from [Wikipedia's table of Paper Sizes](https://en.wikipedia.org/wiki/Paper_size#Overview:_ISO_paper_sizes) ``` ISO paper sizes in portrait view Format A series B series C series Size mm × mm mm × mm mm × mm 0 841 × 1189 1000 × 1414 917 × 1297 1 594 × 841 707 × 1000 648 × 917 2 420 × 594 500 × 707 458 × 648 3 297 × 420 353 × 500 324 × 458 4 210 × 297 250 × 353 229 × 324 5 148 × 210 176 × 250 162 × 229 6 105 × 148 125 × 176 114 × 162 7 74 × 105 88 × 125 81 × 114 8 52 × 74 62 × 88 57 × 81 9 37 × 52 44 × 62 40 × 57 10 26 × 37 31 × 44 28 × 40 ``` So examples of input and output: ``` **Test case 1** Input: A4 Output: 210 x 297 **Test Case 2** Input: B6 Output: 125 x 176 **Test Case 3** Input: C2 Output: 458 x 648 ``` **Things to note:** 1. The format "210 x 297" or "1000 x 1414" etc. While this is the preferable format, You can choose to omit the " x " from your output, i.e. in the form of an array or two numbers or whatever tickles your fancy as long as the width measurement is outputted before the height. 2. The ratio between the height and the width is roughly equivalent to the square root of 2, so in the calculation of the heights, the width is multiplied by sqrt(2), and then rounded up or down to the nearest millimetre, thus resulting in the measurements in the table above. This may help golf down your code. 3. In successive sizes for a series as you go down the table, the width for one size becomes the height for the next. This may also help you golf down your code. **Rules:** 1. This is code-golf. Standard rules apply as a result. The score will be based on byte count. Lowest count will win. 2. [No silly loopholes](https://codegolf.meta.stackexchange.com/q/1061/38183), we've been there before... We shan't go through this again. 3. If you can code it, then please also consider attaching a link to a working instance of your code so that other programmers and golfers can learn how your code works. This is not mandatory, but I'd like to encourage others to do this so we can all learn off one another. I certainly would love to learn more about other golfer's languages where possible. Best of luck. [Answer] ## JavaScript (ES7), 57 bytes *Saved 1 byte thanks to @WallyWest* ``` s=>n=>[n,n-1].map(x=>.707**x*{A:841,B:1e3,C:917}[s]+.2|0) ``` [Answer] # [C (gcc)](https://tio.run/##JY3LDoIwEEX3/YoJCdDC8FBMWFQWxt9wU4pVCK8giSSEX7cOupqT3HPv6OihtbWGKyxRYyXqfg40BpVcTTuoGZbicM@CcXjzOE9zLEPlZskpFmF8lIEuFlKLJdkzudlO1T0XbGVAM6AQSsnADBNw/VQT1FCAf/ElwZnoulMYCgZ/Z@80pKSSDgmHHSgHw2uEBsGjRa8UCONEruGOW4Fb3XoHf7@EZJv9aNOqx8tGbfcF), ~~113~~ ~~111~~ ~~90~~ ~~78~~ 70 bytes It needs `-lm` to run on TIO, but works well on my computer without the option. *Saved 20 bytes thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184).* Return values by pointer. ``` f(a,b,c,d)int*c,*d;{float x=1e3*pow(.707,b+a%3/4.)+.2;*c=x,*d=x/.707;} ``` Explanation: ``` f(a,b,c,d)int*c,*d;{ // calling by char, but receive as int float x = 1e3 * pow(.707, // float gives enough precision a % 3 / 4. // series: a%3/4.=.5,0,.25 when a=65,66,67 + b) - .2; // magic number to get correct roundings *c = x, *d = x / .707; } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ ~~97~~ ~~93~~ ~~84~~ ~~83~~ 81 bytes ``` def f(l,n):w=[841,1000,917][ord(l)-65];h=int(w/.707);exec"w,h=h/2,w;"*n;print w,h ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0cnT9Oq3DbawsRQx9DAwEDH0tA8Njq/KEUjR1PXzDTWOsM2M69Eo1xfz9zAXNM6tSI1WalcJ8M2Q99Ip9xaSSvPuqAIqEABKPY/TUPdUV3HQJMLyHCCMZzBDC6InAlMzgwmZ6T5HwA "Python 2 – Try It Online") [Answer] ## Batch, 105 bytes ``` @set/aA=1189,B=1414,C=1297,h=%1,w=h*29/41 @for /l %%i in (1,1,%2)do @set/at=w,w=h/2,h=t @echo %w% x %h% ``` 41/29 ≅ √2 [Answer] # JavaScript, 53 bytes ``` L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0) ``` ``` f= L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0) document.write('<table><tr><th><th>A<th>B<th>C',[...Array(11)].map((_,i)=>'<tr><th>'+i+['A','B','C'].map(j=>'<td>'+f(j)(i)).join``).join``); ``` Save many bytes by using alternative output format, thanks to Neil. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 59 bytes ``` f->s->new double[]{s=1e3*Math.pow(.707,s+f%3/4d)-.2,s/.707} ``` [Try it online!](https://tio.run/##jVDJbsIwEL3zFaNIiAQSs0ocgEhAhcSh6oEj4uAkDjVNbCs2WxHf0Q/qh1HHDSgq3SJl/Gbem3WDd9jjgrBN9HKhqeCZgo2Ooa2iCYq3LFSUM1QfVO5IHRPbIKEhhAmWEh4xZXCqABRRqbDSz47TCFLN2QuVUbZergBna@kYKcCcqVnRZfjAdSa5uZFxlyvfhwOM4BJ7vvR8RvZwZU5y1Cbd@iNWz0jwvY36rb4rG3G12@xFjoc6rmzmsfNlYJotjlKRFPGtQkLPohJmW/PFEwgsSAaSvhIJeol80QxTBTtK9pbzc@6MZylWAGOQJKM6WX@TEp4W@LcaC9015yBN4f0tt3feFV/LxDwDW6ebifVlWoNPNBxBu8CNxvXAcLsWYK09ICxEcrRr45pTwFxfVC6Jg7J48oc4LIun34u/Lh/bVtXrRIar9lArzpesegb9J8As16zqAl62VrltaxsYHBgcGhxqXAxxruT/@fIB "Java (OpenJDK 8) – Try It Online") Inspired by [@Colera Su's C entry](https://codegolf.stackexchange.com/a/148136/16236), then improved by myself. * 14 bytes saved thanks to Kevin Cruijssen [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~33~~ 30 bytes ``` 917 841 1000.5vjo)t2X^*hi2/W/k ``` [Try it online!](https://tio.run/##y00syfn/39LQXMHCxFDB0MDAQM@0LCtfs8QoIk4rI9NIP1w/@/9/Jy4TAA "MATL – Try It Online") or [Verify all test cases](https://tio.run/##Fco5DsIwEEDRfk6RlhRkxrvLEI6ABBWCjlVpIq5vvovXve99@7Rbq5aHEmwwVd3H32vdbe5yHR9PN52ndzue2iwqsxgcPAIiEjIKaj8qB@kMDh4BEQkZBbUflUU6g4NHQERCRkHtR/8 "MATL – Try It Online") Saved 4 byte thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~31~~ 28 bytes [-2 thanks to ngn.](https://chat.stackexchange.com/transcript/message/41174627#41174627) Full program body. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Prompts for number, then letter, both from STDIN. Prints to STDOUT. ``` ⌊.2+1E3÷2*8÷⍨('BC'⍳⍞)+4×⎕-⍳2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@P@rp0jPSNnQ1PrzdSMvi8PZHvSs01J2c1R/1bn7UO09T2@TwdKAOXSDX6D9Qw38FMEjjMuFy5IKxzbic4GwjLmcA "APL (Dyalog Unicode) – Try It Online") A slightly modified version lets us test all possibilities at once: [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWjni49I21DV@PD2420LA5vf9S7QkPdyVn9Ue/mR71bNbVNDk9/1LtLF8g1qv3/X90RJNUxQy8NqA4oZmgIAA "APL (Dyalog Unicode) – Try It Online") `⍳2` first two **ɩ**ndices, i.e. 0 and 1 `⎕-` subtract that from numeric input `4×` multiply four with that `(`…`)+` add the following  `⍞` character input…  `'BC'⍳` …'s **ɩ**ndex in this string ("A" will give 2, as the index beyond the last) `8÷⍨` divide that by 8 `2*` raise 2 to the power of that `1E3÷` 1000 divided by that `.2+` add ⅕ to that `⌊` floor (round down) [Answer] # Befunge, ~~69~~ ~~56~~ 55 bytes ``` "}"8*~3%:"L"*7vv\p00-1_$..@ ")"*":":-*!!\+<>2/00g:^:&\/ ``` [Try it online!](http://befunge.tryitonline.net/#code=In0iOCp+MyU6IkwiKjd2dlxwMDAtMV8kLi5ACiIpIioiOiI6LSohIVwrPD4yLzAwZzpeOiZcLw&input=QTQ) **Explanation** We don't have the luxury of floating point or anything like a power function in Befunge, so we calculate the base size for the given format character, *f*, as follow: ``` fn = f % 3 width = 1000 - (n * 76 + 7) * !!n height = width * 58 / 41 ``` We then repeatedly rotate and divide these dimensions to get to the appropriate subdivision for the given size number. ``` "}"8* Push 1000 for later use in the width calculation. ~ Read the format character from stdin. 3% Convert into a number in the range 0 to 2. :"L"*7v Calculate width = 1000 - (fn * 76 + 7) * !!fn -*!!\+< where fn is the format number derived above. ")"*":": / Calculate height = width * 58 / 41. \ Swap so the width is above the height on the stack. v:& Read the numeric size from stdin and duplicate for testing. _ While not zero, go left. p00-1 Decrement the size and move it from the stack into memory. v/ Swap the width and height. >2/ Divide the new width by 2. 00g: Restore the size from memory and duplicate for testing. _ While not zero, repeat this loop. $ When zero, continue to the right and drop the size. ..@ Output the width and height, then exit. ``` ]
[Question] [ ## Input You are given a 2D map with balls and ground in it. It looks like this: ``` 1 5 2 3 4 __________________________ ``` Each number is a ball, and the `_` is ground level. The underscore `_` character is not allowed in any other line than ground level line. There are only spaces, newlines and digits `0-9` allowed above ground level. You cannot assume that last line is the ground level - empty lines below ground level are allowed. You can also add spaces, to fill empty lines, if that does help you. Balls can have numbers from `0` to `9`, can be placed above each other, but not under ground. The ball's numbers will be unique. Assume that each character is **one meter**. [Get map from pastebin!](http://paste.ubuntu.com/17848771/) [Test case 1](http://paste.ubuntu.com/17854204/) - should output something like [this](http://paste.ubuntu.com/17860519/) [Test case 2](http://paste.ubuntu.com/17854273/) - should produce same results as first map ## Challenge Your challenge is to read a map like that from a file or from `stdin` — you are allowed to use `cat balls.txt | ./yourexecutable` — and output velocity of each ball when it hits the ground. Here's the formula for velocity: [![enter image description here](https://i.stack.imgur.com/SDjPL.png)](https://i.stack.imgur.com/SDjPL.png) Assume that `h` is the line number difference between the ground's line number, and the ball's line number, and that `g` equals `10m/s^2`. ## Output You should output each balls number and velocity in `m/s` at ground level. For example `N - Vm/s`, where `N` is ball number and `V` is its velocity. You can also output an array if you want. Happy coding! :) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~31~~ ~~30~~ ~~27~~ 25 bytes ``` 95\16\5B#fG&X>1)b- 20*X^h ``` Input is a 2D char array with `;` as row separator: ``` [' 1 5 2 ';' 3 ';' 4 ';' ';' ';'__________________________'] ``` [Try it online!](http://matl.tryitonline.net/#code=OTVcMTZcNUIjZkcmWD4xKWItIDIwKlheaA&input=WycgIDEgICAgICAgICA1ICAgICAgICAgIDIgICc7JyAgICAgICAgICAgICAgICAgMyAgICAgICAgJzsnICAgICA0ICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICc7JyAgICAgICAgICAgICAgICAgICAgICAgICAgJzsnX19fX19fX19fX19fX19fX19fX19fX19fX18nXQ) Or [include an initial `t` in the code](http://matl.tryitonline.net/#code=dDk1XDE2XDVCI2ZHJlg-MSliLSAyMCpYXmg&input=WycgIDEgICAgICAgICA1ICAgICAgICAgIDIgICc7JyAgICAgICAgICAgICAgICAgMyAgICAgICAgJzsnICAgICA0ICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICc7JyAgICAgICAgICAgICAgICAgICAgICAgICAgJzsnX19fX19fX19fX19fX19fX19fX19fX19fX18nXQ) to display the map for greater clarity. Here are the other test cases: [first](http://matl.tryitonline.net/#code=OTVcMTZcNUIjZkcmWD4xKWItIDIwKlheaA&input=WycgICAgICAgICAgICAgICAgICAgICAgICAgICc7JyAgICAgICAgICAgICAgICAgICAgICAgICAgJzsnICAxICAgICAgICAgNSAgICAgICAgICAyICAnOycgIDYgICAgICAgICAgICAgICAzICAgICAgICc7JyAgICAgNCAgICAgICAgICAgICAgICAgICAgJzsnICAgICA3ICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICc7J19fX19fX19fX19fX19fX19fX19fX19fX19fJ10), [second](http://matl.tryitonline.net/#code=OTVcMTZcNUIjZkcmWD4xKWItIDIwKlheaA&input=WycgICAgICAgICAgICAgICAgICAgICAgICAgICc7JyAgICAgICAgICAgICAgICAgICAgICAgICAgJzsnICAxICAgICAgICAgNSAgICAgICAgICAyICAnOycgICAgICAgICAgICAgICAgIDMgICAgICAgICc7JyAgICAgNCAgICAgICAgICAgICAgICAgICAgJzsnICAgICAgICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICc7J19fX19fX19fX19fX19fX19fX19fX19fX19fJzsnICAgICAgICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICdd). ### Explanation ``` 95\ % Take input implicitly. Modulo 95: convert to numbers and map '_' into 0 16\ % Modulo 16: map space into 0 and digit chars into corresponding numbers 5B#f % Find row indices and values of nonzero entries G % Push input again &X> % Index of maximum of each column. This finds character '_' 1) % Get first value (they are all equal) b % Bubble row indices of numbers up in the stack - % Subtract to get distance from each number to the ground 20*X^ % Multiply by 20, take sqrt. This gives the velocity values h % Horizontally concat numbers and velocities. Display implicitly ``` [Answer] # C, 125 122 121 bytes ``` b[99]={};main(l,c){for(;(c=getchar())<95u;)b[c]=(l+=c==10);for(c=47;++c<58;)b[c]&&printf("%c,%f\n",c,sqrt((l-b[c])*20));} ``` Compile & run with `gcc -w golf.c -lm && cat balls.txt | ./a.out`. [Answer] # C -~~194(-5)~~ ~~150~~ 137 bytes *With a little bit more time and thinking, I golfed off 44 bytes* *Thanks to **orlp** for helping me to save 13 bytes* I'll start with my C code: ``` b[256]={},n,i=47;main(l,c){for(;~(c=getchar());n=c==95?l:n)b[c]=(l+=c==10);for(;++i<58;)b[i]&&printf("%d %f\n",i-48,sqrt((n-b[i])*20));} ``` And human readable version: ``` //Throws many warnings, but lack of libraries is tolerated /* c - current character l - line number (starts at 1) n - ground level i - iterator b - balls array */ b[256] = {}, n, i = 47; //That actually works, as long as you are using ASCII main( l, c ) { for ( ;~( c = getchar( ) ); n = c == 95 ? l : n ) //Read stdin and search for ground b[c] = ( l += c == 10 ); //Increment lines counter on newlines, and save line numbers for ( ; ++i < 58; ) //Iterate through balls b[i] && printf( "%d %f\n", i - 48, sqrt( ( n - b[i] ) * 20 ) ); //Print out data } ``` Compile and run like that: `gcc -o balls ballsgolf.c -lm && cat 1.txt | ./balls` ## Output ``` 1 10.000000 2 10.000000 3 8.944272 4 7.745967 5 10.000000 ``` [Answer] # Pyth, ~~27~~ ~~26~~ ~~25~~ 24 bytes ``` ~~smf-hT" \_".e,b@\*20-xd\\_k2dC~~ ~~smf@hT`M;.e,b@\*20-xd\\_k2dC~~ ~~smf@T`M;.e,b@\*20-xd\\_k2dC~~ sm@#`M;.e,b@*20-xd\_k2dC ``` [Try it online!](http://pyth.herokuapp.com/?code=sm%40%23%60M%3B.e%2Cb%40%2a20-xd%5C_k2dC&input=%5B%27++1+++++++++5++++++++++2++%27%2C%27++6++++++++++++++3++++++++%27%2C%27+++++4++++++++++++++++++++%27%2C%27++++++++++++++++++++++++++%27%2C%27++++++++++++++++++++++++++%27%2C%27__________________________%27%5D&debug=0) [Answer] ## Matlab, ~~100~~ ~~96~~ ~~89~~ 90 bytes ``` s=input('');X=find(s==95);for i=0:9 [x y]=find(s==48+i);if(x)[i sqrt(20*(X(1)-x))] end end ``` Many bytes saved thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) Input format: ``` [' 1 9 2 ';' 3 ';' 4 ';' ';' ';'__________________________'] ``` **Explanation:** ``` X=find(s==95) -- finds '_', we'll need X(1) to determine max height for i=0:9 -- loops through balls' numbers [x y]=find(s==48+i) -- finds the ball if(x) -- if it is present [i sqrt(20*(X(1)-x))] -- output its number and velocity ``` [Answer] ## Python 3, 84 bytes Version 6, 84 bytes: (Thanks to Leaky Nun!) ``` lambda a:[(c,(~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()] ``` Version 5, 91 bytes: ``` lambda a:[c+":"+str((~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()] ``` Version 4, 92 bytes: ``` lambda i:[c+":"+str((~-(len(i)-n)*20)**.5)for n in range(len(i))for c in i[n]if c.isdigit()] ``` Version 3, 99 bytes: ``` def r(i):x=len(i);print([c+":"+str((~-(x-n)*20)**.5)for n in range(x)for c in i[n] if c.isdigit()]) ``` Version 2, 102 bytes: ``` def r(i): n=len(i) for l in i: for c in l: if c.isdigit():print(c+":"+str((~-n*20)**.5)) n-=1 ``` The above versions take an array of strings as input. Version 1, 140 bytes: ``` with open(input(),"r")as i: n=sum(1for l in i);i.seek(0) for l in i: for c in l: if c.isdigit():print(c+":"+str((~-n*20)**.5)) n-=1 ``` This takes the directory of the file as input from the user. [Answer] # Python 3, 84 bytes ``` lambda x:[[i,(20*x[x.find(i):x.find('_')].count('\n'))**.5]for i in x if i.isdigit()] ``` An anonymous function that accepts input by argument as a multi-line string with all empty lines filled with spaces, and returns an array where each element is of the form [ball number, speed]. **How it works** ``` lambda x Function with input x ...for i in x if i.isdigit() Loop through all characters i in x for which i is a digit, and hence one of the balls x[x.find(i):x.find('_')] Slice x to give the substring between the ball and the ground ....count('\n') Count the number of newlines in the substring to give the height of the ball (20*...)**.5 Calculate the speed of the ball as it hits the ground [i,...] Package the ball number and speed into a list :[...] Return all ball-speed pairs as a list with elements [ball number, speed] ``` [Try it on Ideone](https://ideone.com/aPDp8i) [Answer] # JavaScript (ES6) 93 *Edit* 2 bytes saved thx @Jacajack A function with a multiline string as input parameter. Output is not sorted (as this in not requested) ``` a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0) ``` **Test** ``` F= a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0) function test() { F(I.value); } test() ``` ``` #I { height: 12em; width: 30em} ``` ``` <textarea id=I> 1 5 2 3 4 __________________________ </textarea> <button onclick="test()"></button> ``` ]
[Question] [ Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string. The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters `()[]{}<>` replaced by `)(][}{><` respectively. You could use any codepage that has the characters `()[]{}<>` and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. ### Example For the string `AB(XY)`, its normal and visual reversions are `)YX(BA` and `(YX)BA` respectively. If your code (in a hypothetical language) is `AB(XY)`, then the code `)YX(BA` and `(YX)BA` should output the normal and visual reversions of the input string respectively. And `AB(XY)` should act as a cat program. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 16 bytes Uses the fact that 05AB1E has a constant predefined to `"()<>[]{}"` and isn't affected the visually reversion. Code: ``` ,q‡"}{][><)("užR ``` Explanation: ``` , # Pop and print the input. q # Quit. ‡"}{][><)("užR # This part is ignored. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LHHigKEifXtdWz48KSgidcW-Ug&input=SGVsbChvKQ) --- Reversed: ``` Ržu"()<>[]{}"‡q, ``` Explanation: ``` R # Reverse the input. žu # Short for "()<>[]{}". "()<>[]{}" # Push this string. ‡ # Transliterate (no-op, since everything is transliterated to itself). q # Quit and implicitly print. , # This part is ignored. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=UsW-dSIoKTw-W117fSLigKFxLA&input=SGVsbChvKQ) --- Visually reversed: ``` Ržu")(><][}{"‡q, ``` Explanation: ``` R # Reverse the input. žu # Short for "()<>[]{}". ")(><][}{" # Push this string. ‡ # Transliterate (giving the visually reversed string). q # Quit and implicitly print. , # This part is ignored. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=UsW-dSIpKD48XVt9eyLigKFxLA&input=SGVsbChvKQ) Uses **CP-1252** encoding. [Answer] ## CJam, 21 bytes ``` qe#ere$_"}{][><)("%Wq ``` [Test it here.](http://cjam.aditsu.net/#code=qe%23ere%24_%22%7D%7B%5D%5B%3E%3C)(%22%25Wq&input=qe%23ere%24_%22%7D%7B%5D%5B%3E%3C)(%22%25Wq) Normal reversion: ``` qW%"()<>[]{}"_$ere#eq ``` [Test it here.](http://cjam.aditsu.net/#code=qW%25%22()%3C%3E%5B%5D%7B%7D%22_%24ere%23eq&input=qe%23ere%24_%22%7D%7B%5D%5B%3E%3C)(%22%25Wq) Visual reversion: ``` qW%")(><][}{"_$ere#eq ``` [Test it here.](http://cjam.aditsu.net/#code=qW%25%22)(%3E%3C%5D%5B%7D%7B%22_%24ere%23eq&input=qe%23ere%24_%22%7D%7B%5D%5B%3E%3C)(%22%25Wq) ### Explanation First, the normal code: ``` qe#ere$_"}{][><)("%Wq ``` This is simple: `q` reads all input, `e#` comments out the remainder of the program, and the input is printed implicitly at the end. Now the normal reversion: ``` q e# Read all input. W% e# Reverse it. "()<>[]{}" e# Push this string. _$ e# Duplicate and sort it. However, the string is already sorted e# so we just get two copies of it. er e# Transliteration (i.e. character-wise substitution). But since the e# source and target string are identical, the reversed input e# is left unchanged. e#eq Just a comment... ``` And finally, the visual reversion: ``` q e# Read all input. W% e# Reverse it. ")(><][}{" e# Push this string. _$ e# Duplicate and sort it. This gives us "()<>[]{}", i.e. the e# same string with each bracket pair swapped. er e# Transliteration (i.e. character-wise substitution). This e# time, this toggles all the brackets in the reversed input e# completing the visual reversion. e#eq Just a comment... ``` [Answer] ## Haskell, 124 bytes Forward: ``` f=id --esrever.q pam=2>1|esrever=2<1|f;x=x q;')'='(' q;'('=')' q;']'='[' q;'['=']' q;'>'='<' q;'<'='>' q;'}'='{' q;'{'='}' q ``` Normal reverse: ``` q '}'='{';q '{'='}';q '>'='<';q '<'='>';q ']'='[';q '['=']';q ')'='(';q '('=')';q x=x;f|1<2=reverse|1>2=map q.reverse-- di=f ``` Visual reverse: ``` q '{'='}';q '}'='{';q '<'='>';q '>'='<';q '['=']';q ']'='[';q '('=')';q ')'='(';q x=x;f|1>2=reverse|1<2=map q.reverse-- di=f ``` Each version defines a function `f` which takes and returns a string. In forward mode `f` is the identity function `id`, the rest of the code is a comment. In normal reverse mode the guard `1<2` in `f` is `True`, so `reverse` is applied. In visual reverse mode, the `<` is switched to `>` and the guard is `False`. The second guard is just the other way around and `True`in visual mode, so additionally `q` is applied which switches "()<>{}[]". ``` f|1<2=reverse|1>2=map q.reverse -- normal reverse mode f|1>2=reverse|1<2=map q.reverse -- visual reverse mode ``` Besides `<`and `>` in the guards, my code doesn't use any of the brackets, so they can't be messed up. [Answer] # Bash + common linux utilities, 51 * 2 bytes saved thanks to @jimmy23013 * 2 bytes saved thanks to @AdamKatz ``` #'><}{][)(' `P5BD706D5AC79E196iFe- cd` rt|ver| \cat ``` Normal reversion: ``` tac\ |rev|tr `dc -eFi691E97CA5D607DB5P` '()[]{}<>'# ``` Visual reversion: ``` tac\ |rev|tr `dc -eFi691E97CA5D607DB5P` ')(][}{><'# ``` The main trick here is that the string `()[]{}<>` is encoded as 691E97CA5D607DB5 (base 15). The resulting `dc` command will yield this same result after either kind of reversion. However the `'()[]{}<>'` string literal is sensitive to the reversal type. `tac` is required to reverse order of input lines and `rev` is required to reverse the characters of each line. Any ASCII input should be acceptable. [Answer] # MATL, ~~26~~ ~~24~~ ~~22~~ 16 bytes **Forward** ``` DPEXSt'><}{][)(' ``` [Try it Online!](http://matl.tryitonline.net/#code=RFBFWFN0Jz48fXtdWykoJw&input=J0hlbGwobykn) Explanation: ``` % Implicitly grab the input as a string D % Pop the top of the stack and display it P % Tries to flip the top element on the stack but errors out % because the stack is empty. Program terminates. EXSt'><}{][)(' % Not executed ``` --- **Normal reversion:** ``` '()[]{}<>'tSXEPD ``` [Try it Online!](http://matl.tryitonline.net/#code=JygpW117fTw-J3RTWEVQRA&input=J0hlbGwobykn) Explanation: ``` % Implicitly grab input as a string '()[]{}<>' % String literal (search string) tS % Duplicate and sort to create the replacement string: '()[]{}<>' XE % Replace all entries in the input using the search and replacement strings. % Corresponding characters in the strings are used for the replacement. % Effectively a no-op P % Flip the string D % Explicitly display result ``` --- **Visual reversion:** ``` ')(][}{><'tSXEPD ``` [Try it Online!](http://matl.tryitonline.net/#code=JykoXVt9ez48J3RTWEVQRA&input=J0hlbGwobykn) Explanation: ``` % Implicitly grab the input as a string ')(][}{><' % String literal (search string) tS % Duplicate and sort to create the replacement string: '()[]{}<>' XE % Replace all entries in the input using the search and replacement strings. % Corresponding characters in the strings are used for the replacement. P % Flip the result D % Explicitly display the result ``` [Answer] ## GolfScript, ~~32~~ 28 bytes ``` #%{=1-[=-\7?@.`{[(<>)]}.}%1- ``` [Try it online!](http://golfscript.tryitonline.net/#code=IyV7PTEtWz0tXDc_QC5ge1soPD4pXX0ufSUxLQ&input=IyV7PTEtWz0tXDc_QC5ge1soPD4pXX0ufSUxLQ) Normal reversion: ``` -1%}.}])><([{`.@?7\-=[-1={%# ``` [Try it online!](http://golfscript.tryitonline.net/#code=LTElfS59XSk-PChbe2AuQD83XC09Wy0xPXslIw&input=IyV7PTEtWz0tXDc_QC5ge1soPD4pXX0ufSUxLQ) Visual reversion: ``` -1%{.{[(<>)]}`.@?7\-=]-1=}%# ``` [Try it online!](http://golfscript.tryitonline.net/#code=LTEley57Wyg8PildfWAuQD83XC09XS0xPX0lIw&input=IyV7PTEtWz0tXDc_QC5ge1soPD4pXX0ufSUxLQ) The fact that an unmatched `}` terminates the program in GolfScript, made this fairly simple. However, I'm pretty sure that my code for swapping the brackets isn't optimal yet. [Answer] ### Python 2.7, 208 bytes **Forward** ``` import sys# print''.join(sys.stdin)# #0:tpecxe #"]1-::[)nidts.sys(nioj.'' tnirp"cexe:yrt #0:tpecxe #"(('<>{}[]()','><}{][)(')snartekam.s)etalsnart.[1-::](nidts.sys)nioj.'' tnirp"cexe:yrt #s sa gnirts,sys tropmi ``` **Normal reversion** ``` import sys,string as s# try:exec"print''.join)sys.stdin(]::-1[.translate)s.maketrans)'()[]{}<>',')(][}{><'(("# except:0# try:exec"print''.join(sys.stdin)[::-1]"# except:0# #)nidts.sys(nioj.''tnirp #sys tropmi ``` <https://eval.in/574639> **Visual reversion** ``` import sys,string as s# try:exec"print''.join(sys.stdin)[::-1].translate(s.maketrans(')(][}{><','()[]{}<>'))"# except:0# try:exec"print''.join)sys.stdin(]::-1["# except:0# #(nidts.sys)nioj.''tnirp #sys tropmi ``` <https://eval.in/574638> All directions read from stdin until EOF. Nothing super clever here. Trailing comments to only execute the forward vs the backward code, then an `exec` statement in a try block to catch syntax errors for the two different reversions. ]
[Question] [ Recently, the [PPCG design](https://github.com/vihanb/PPCG-Design) leaderboard has been having [some trouble](https://github.com/vihanb/PPCG-Design/issues/16) parsing answer **html headers**. In this challenge you'll be taking your own shot at parsing answer headers. --- ## Example Test Cases These **example inputs** (**NOT** actual test cases), just so you can get the idea of how inputs **might** be like ``` Input: <h1>Python 3, 32 bytes</h1> Desired Output: Python 3 Input: <h1>JavaScript, 13 chars / 32 bytes</h1> Desired Output: JavaScript Input: <b>VeryBadlyFormattedHeader v3 : (32 bytes)</b> ``` ## Spec **Your program should be 150 bytes or below** You will be given a line of an answer header's html, you'll need to try to do your best to successfully extract the language. Input may contain unicode characters. Output case matters. ## Tests **[Github Gist with test cases](https://gist.github.com/vihanb/1d99599b50c82d4a6d7f)** There is one test case per line. The format is: ``` <lang_name> - <rest_of_the_line_is_the_header> ``` ## Scoring Your score is: ``` Number Correct ---------------- Total Number ``` (which is a percent) Tie-breaker is shortest code. [Answer] # Bash, 100%, 100 bytes ``` sed sX..s.2./s.XX|grep -Po '(?<=>)[^<]+?(?=(,(?! W)| [-&–5]| ?<| [0-79]\d| ?\((?!E|1\.)))'|head -1 ``` Try it online on [Ideone](http://ideone.com/WCeI29). ### Verification ``` $ wget -q https://gist.githubusercontent.com/vihanb/1d99599b50c82d4a6d7f/raw/cd8225de96e9920db93613198b012749f9763e3c/testcases $ grep -Po '(?<= - ).*' < testcases > input $ grep -Po '^.*?(?= - )' < testcases > output $ while read line; do bash headers.sh <<< "$line"; done < input | diff -s - output Files - and output are identical ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 100%, ~~75~~ ~~71~~ ~~70~~ ~~68~~ ~~67~~ ~~64~~ ~~59~~ ~~53~~ 51 bytes ``` <.*?> (,| [-&(–5]| [0-7]\d)(?! W|...\)).* 2 |: ``` This is essentially code golf now, so I had to switch languages. [Try it online!](https://tio.run/##vVrdctvGFb7XU6yVcULGEIhd/CsyPZLsxHHsqWJ56pk2mQwIrUjEIMEAoGV5fJGLXnR6m/SmM2n7DL3uw3TyBHkD9@wfsEsQFJ06nQyV3cX@nD2/3znrktbZInn79sj@@N54b29gvUF/PPhw8PP3P/hfQ9M5CL/@6mI4uHcLPX9j2/ZXw6H98d4eQW8O996@PbuuZ@gAHc3ImDUtdFSNPedoVI1Zyw2alsdbLkGT65pWRyNYsPd0NbmWi3lzQGz4bxn7Qwth4ulTn9HkPC2zZc3n4/FRgmYlvby7P6vrZXU4GtGqyJPFtLKLcjq6yl5ko2bJPippfnd/UVwWeV5c7Y@bL0ejZAxHBc1JeLx3klQzeQhrisFHNM@v5ShvW4jE@qoOH3Cok/8oeWnS3w7AVBcTN4IP2EF3Ee@SSN/891ldqdN520Keo09gu8nTWdNCEdZPPymTbHH5cfpC3Uv1hbiimMvGCwKUzpIySWtayo1PP5Db8gb2I7Hhk@Nnj3cXBJvdkQEbFOz3ovWrSE4NHpwHww6/xLCFQkdyPk/q67Ok7KNnmtWz1cROi/kovS5SOlILOiSpD4KsUKeq0VTMNRWkH7jQd53bIDEcefrc98qcmEkIC@PRzvhUyeXTDyxhaGIKiSJd8Oe0zIpVlSsra/qgdIZ53ad1seplYZlcARc1Fl7w6aN5UoGqjLIF/F3as3qed24iNhZ3YTcJlUPALm9hrF/r/0aG8FAdCy4WyJWnqy4zz0jM2MJN3zOtXbNzZuFwpO@rm3vS3Iybnz5K5srUoCmEioXPdPS9f5fWyUsqdxcdcSWMJUOdDbci5q2IheirZL7MKcrY3zld1EmdFYsN2uW6xtWK/FJdDZrwWdqJhRbFAkSzZNFkKhmWJrnyS7xtoSotSnqIAiK26yWPXT@MxP0DH53oDqLLXLadYG7QxJ6W4b746mPTz3S3IeJA4vf49KOqLrMXdBwz3RVNFPk6e3qViPtZIXffkA9ssknfQd2X8MnOr6ukLko7z1Z2RbsuC@ZIR@FtELtOhbghFrwgDt5JSwjebR5TQF/YNtZiPCyZUFpdJa967lgWFa3rJC0uaOsST5OaTovy@vBErO3cWu4pLu7iTiQcYDsSgcMdGwMnxXcvaP7RZfGyXKEBl0mAvDCE2OeDYAiEVYLcOIAfRq4v9U8Z9xCOcME6kjxteLt@oUv@cZmz23ToFis3gY53U4PRFj1w/ZudGlMEcTWhFK2pEMdrHHQkTAmHRnw@LS4vKTWwjD7EAou3q8oQtzkYxzIeBKFu7E9XVd3E3Qp2D2Px4Vl2AOgsSxHEXmGi2oiFsOEzH68SuQm0ABytHbEW2hk1JG4II0HblBpOukBpZ9jCjdCVRmhw9qmiAv6v8BtKFhfg0g0s8iSpZ3QO7jpVvlUbsTTYbXpuxXk7XBOFHYKdR@RG94EdI17CdeTx0JLBPZIaY6J8nl/Iudvg2XyyAmewgFBe8iUdLRc7aVFcaLHpgk2Wh0MNF@vDcB8TAnX0IJaqdvbwTHHi4Zk42GutxHXW1YM3SdvEbVNaFI51BdQiOmkiehys30nTKEGEi9ePW4v963hlG@@fgMcdNQs6nG@@NMyX@dxWKol50Z1tBHtEsDmAJmeq9D3K4cDWvqGMD5MKHHsuv8uexEXClLFjuCU9oVv3uBpb7tPFIqueZHU6gwWjb9mqDnP4XoIxgIEO1kFQP2o0s@H710leTNHx2WM5sx0AlkS9MIOYMIOEje8i0iB5U6pIaIisgZ2Yw86NHtFIywkES7Zd7AMuhTgJ0VfmHpKvqzxrlIC1BU0KdfyPeZKWGPnuZt@puT9va4LOgKHbYHKJzcJtYcOgXvNquHFMursgwl0QE74bnpXhyWIxHbeDElX6DIIqhKkGvRhvGOQiloNee5bceYs7B@X49VEMe3FvkCdakMdO2O@bt@0fyf0PO4S1cccchEW@cdgZLXNFEDThxl7HiDSegDka4fisuKLlOTN79JLcURsZgzLqNW6fSJeMA@Mgxz8@wQ92qE8cX5QZBHzIxkZiTcfViGFhAcEN6mgBqt2YYmItxZRIpG@vdwvYo60R@7TIiyWlHy2LF2UmWBe0@M9vg6fndhGXu1FyTbFNISQ0@KLMUvAdcMqyGIrpn5VF8VJ5NNnx/I5idQtzRDksW0x@bxv11zneX5mD9FTVlP3gjv2ERurwLFXWA60N2Xpr5v0YJY7tNqGII9sTnjkO7SBAeVoNhihN8nxLDUTWkt24F1EqZYfJUYO6ogYbtdYZNpQEwtsH4ValUi4WR123i4N2DDtbvQqzMkcW595ZJL7XcUnVTAEd6Y6aAeaLWtwZCF5DYqWTV9ELmRhDS@JIOVEjz33HhMZvciTSQmNIb8TGUXhT4SVuQHQkxBUF2zIebGY8kfOblV/dUFPC3SlqZc5ZIqRPNgMW8x3hXdiOnQbeQZyVKHedcXkyaSmEDguT73QUL2/zekAIyuRrUK9j8Bc0h2ngvVkD1hEd/W8rjWEHbyL/VHkDS0UoVIF/SyE/IhZ2Yws7ruVKM0bFql6uQJ9eJnl2gZZlMS05ogWtf54tLoqrCp0mebrKWSVFUrHxg9/BRb/VG4Np3QqvYI5XgAyOnCOAzT4wM@CCYNUYQBwgRBd@DgdikC7JyluIBmDOdzC6ZBd5MJSe/PODk@Pzz1X2pLoCAjfJQhuA/fb9LpQVWJ3OX3768d@//PTXv8DvT/D7G/z@Ibfe9Ik95XGGVmi0ZgR61kbarI3EvYhZK2XGgrbY/1Xm0xT1ILuBHKYVuOTZ8cHTZJe8eZ4sFtfwZzriKzry5qNN0iyYHe5aMcZRuF6N405elsr8zrPT8Ymydd6xeDmNzxm1N5SQ@lm5mi/731ThmlUyr2bJxRUIxZZXzoqRtq6L97SPjQPVVXxVUqQ9sDZ9AB/91bhAsC3wO1WAAfbQHWDEEN1VWtN4CBxaOIytKPStiBtGgD47GYo59BVNV3UyyWm39ObGnWN0@LkpgpmJw3Ga3rq1SXWApazQPS3yS7uqk/QFfQVSWUwp16RkFBAvdkcgsiAAxWG7yFIxMeoEk1QePknXMZtRqmpzREfLJt3mdcOY@/P3P0Ay7/SBRpi4bNJVHdkyFxW00T@Q@URbA24S0SVw5vkX5k5iAHvOptlGSvPe6oa@o96rGCTEdnRb2CSxsX@7k/mtZ3384f1kS9Ew6gaPCX9tXzWv700fiCHvJe8yb@h5m8q@m59sBDTBXrhrMU3F6Xjr46UJiXdCumaM6ZgYdncIHBz2yhqrv5uXVYmF3eN@us8p6@Dea7S/hb5tBus1gNyN5WvSbwZWvUg@LxthXBa5JES/uWiDPkzmy0/Q2eox8wo/gqoEnmcFUYSq71ZJySJmsayzecIKqPNskc2z1/Ri@AkI3Qp91/IBmWyambySM@U79mkyVyrG2wyYwiGDBfhyNxh2aZxoCecEdIDmSws9T8r7xXe3eiJYl4V81Tdi1W2C98fGNtLfci7dmNYDJo0i5qN7bQYNwNt0oMXDZ08eQ9Q6PT9Xs9sBAaFZxskhNO@GZi@UvXADTN1s6wBxYnX2l/EdWWdkfpZ3Bxr8GTYueO@0LKrqYFICPKYlWuMDGHrf54G3DqfIWlGUQWxPmwMyL6BLE1Y0lws@zRqQcLNQ2eT9MfvLBMiezwTglN4pL75lOKO9djsiSEUDdfqtIQLkHGO1XjFjsEonw7yYFvIWep@0pwHhD0pGHKKVzqy1QRWYyaYyL@bldFVbYKkn//dvN7x3ynL@LANUsegBH13Gyfn7Y9mQ//JJbJYmSuehZSEHOj//@e8dpftD8bqo6Wv0OKuWfUDyOr@irHhlL4rRazG/ix31jRghh4gBXW6EyvYYtx0G5e4NOR3SaSdXyAZIp0lYDbGib7gGLva@XGULepZNd3e8akWHZvVBgl0BDdBgnlxQlFzCjVE9o4zUPKcA9KQV/udf//wGfj3cmtM6sbcCxdCNnZGH4Wr7Y7kXJ2CTy@pgNuYNDAs9bDnTG1elvvLykmhrozzQqFHiuaaKkPF/AQ "Retina 0.8.2 – Try It Online") ### Verification ``` $ wget -q https://gist.githubusercontent.com/vihanb/1d99599b50c82d4a6d7f/raw/cd8225de96e9920db93613198b012749f9763e3c/testcases $ grep -Po '(?<= - ).*' < testcases > input $ grep -Po '^.*?(?= - )' < testcases > output $ mono retina/Retina.exe headers.ret < input | head -n -1 | diff -s - output Files - and output are identical ``` ### How it works The code consists of three simple substitutions (or eliminations). Instead of trying to match the language name, we get rid of all parts of the input string that do form part of it. 1. `<.*?>` will match all HTML tags, so the substitution will eliminate them from the input. `.*?` matches any amount of characters, but since `?` makes the quantifier *lazy*, it will match the least amount possible that still allows the entire pattern to match. This avoid deleting the entire input, which will always begin with a `<` and end with a `>`. The language name now begins with the first character of the remaining modified input string. 2. After the language's name, we will almost always find one of the following endings: `,`, `-`, `&`, `(`, `–`, `5`, or a space followed by two digits. The first two endings are rather common, and `Python 2 &amp; PuLP...` should be parsed as `Python 2`, `Ruby (2.2.2p95)...` as `Ruby`, `>PHP – 3302 bytes` as `PHP`, and `Perl 5...` as `Perl`. `(,| [-&(–5]| \d\d).*` would match all these endings (and all characters after them), but it will result in a few false positives: * `,` will match the comma in the language name `Help, WarDoq!`. * `(` will match the version of `JavaScript (ESx)` and `Java (1.8)`. * `\d\d` will match the version in `Ti-Basic 84`.We can fix the third problem case by using `[0-7]\d` instead of `\d\d`, to avoid matching the `8` in `84`. For the other problem cases, we use the negative lookahead `(?! W|...\))` that will prevent the preceding pattern from matching if it is followed by `W` (as in `Help, WarDoq!`) or by exactly three characters and a closing parenthesis (as in `(ES6)` or `(1.8)`). Putting it all together, `(,| [-&(–5]| [0-7]\d)(?! W|...\)).*` matches everything after the language name. 3. We're left with two problem cases: ``` <h1>Python <s>2</s> 3, <s>255</s> <s>204</s> <s>180</s> 178 bytes</h1> <h1><a href="http://sylwester.no/zozotez/" rel="nofollow">Zozotez Lisp</a>: 73</h1> ``` gets parsed as ``` Python 2 3 Zozotez Lisp: ``` We can fix the first by removing `2` and the second one by removing `:` from the output. This is achieved by replacing `2 |:` with the empty string. [Answer] # CJam, 78.38% (76 bytes) ``` l{_'>#)>_c'<=}g_'<#<_{",-"&}#)_{_1$=',=+(<}{;}? ``` [Try it online!](http://cjam.tryitonline.net/#code=bHtfJz4jKT5fYyc8PX1nXyc8IzxfeyIsLSImfSMpX3tfMSQ9Jyw9Kyg8fXs7fT8&input=PGgyPlB5dGgsIDxzPjQwPC9zPiA8cz4zNjwvcz4gPHM-MzQ8L3M-IDMyIGJ5dGVzPC9oMj4) or [count the correct headers](http://cjam.tryitonline.net/#code=MTg1e2xfXyIgLSAiIzpJMys-Okw7STwKICAgIEx7Xyc-Iyk-X2MnPD19Z18nPCM8X3siLC0iJn0jKV97XzEkPScsPSsoPH17O30_Cj19Kl06Kw&input=UHl0aCAtIDxoMj5QeXRoLCA8cz40MDwvcz4gPHM-MzY8L3M-IDxzPjM0PC9zPiAzMiBieXRlczwvaDI-ClJ1YnkgLSA8aDI-UnVieSAoMi4yLjJwOTUpLCAxMjQgYnl0ZXM8L2gyPgpUZWFTY3JpcHQgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9lc29sYW5ncy5vcmcvd2lraS9UZWFTY3JpcHQiIHJlbD0ibm9mb2xsb3ciPlRlYVNjcmlwdDwvYT4sIDE2IGJ5dGVzPC9oMT4KQmFzaCAtIDxoMT5CYXNoPC9oMT4KSmVsbHkgLSA8aDE-SmVsbHksIDI5IGJ5dGVzPC9oMT4KUHl0aCAtIDxoMj5QeXRoLCAxNyBieXRlczwvaDI-CkphdmFTY3JpcHQgLSA8aDE-SmF2YVNjcmlwdCwgMTMxMjM4IC0gMTAgPSAgMTMxMjI4IGJ5dGVzPC9oMT4KVml0c3kgLSA8aDE-Vml0c3ksIDQwIGJ5dGVzPC9oMT4KSmF2YSAtIDxoMj5KYXZhLCA4MSBieXRlczwvaDI-CkJyYWluZipjayAtIDxoMT5CcmFpbmYqY2ssIDxzPjQ4OTwvcz4gNDY2IGNoYXJhY3RlcnM8L2gxPgpDIyAtIDxoMj5DIyAtIDE1ODwvaDI-Ck1BVEwgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9lc29sYW5ncy5vcmcvd2lraS9NQVRMIiByZWw9Im5vZm9sbG93Ij5NQVRMPC9hPiwgNDggYnl0ZXM8L2gxPgpKYXZhU2NyaXB0IChFUzYpIC0gPGgxPkphdmFTY3JpcHQgKEVTNiksIDcwPC9oMT4KUGxhdHlQYXIgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9naXRodWIuY29tL2N5b2NlL1BsYXR5UGFyIiByZWw9Im5vZm9sbG93Ij5QbGF0eVBhcjwvYT4sIDcgYnl0ZXM8L2gxPgpSdWJ5IC0gPGgxPlJ1YnksIDI2MyAtIDMwJSA9IDE4NCBieXRlczwvaDE-Ck1BVEwgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9lc29sYW5ncy5vcmcvd2lraS9NQVRMIiByZWw9Im5vZm9sbG93Ij5NQVRMPC9hPiwgOSA8cz4xNDwvcz4gYnl0ZXM8L2gxPgpGIyAtIDxoMj5GIywgPHM-MzY0PC9zPiAyODggYnl0ZXM8L2gyPgpTZXJpb3VzbHkgLSA8aDI-U2VyaW91c2x5LCAxNCBieXRlczwvaDI-CkRldG91ciAtIDxoMT48YSBocmVmPSJodHRwczovL3Jhd2dpdC5jb20vY3lvY2UvZGV0b3VyL21hc3Rlci9pbnRlcnAuaHRtbCIgcmVsPSJub2ZvbGxvdyI-RGV0b3VyPC9hPiwgPHM-MTc8L3M-IDxzPjEzPC9zPiAxMSBieXRlczwvaDE-CkRldG91ciAtIDxoMT48YSBocmVmPSJodHRwczovL3Jhd2dpdC5jb20vY3lvY2UvZGV0b3VyL21hc3Rlci9pbnRlcnAuaHRtbCIgcmVsPSJub2ZvbGxvdyI-RGV0b3VyPC9hPiwgPHM-MTA8L3M-IDkgYnl0ZXM8L2gxPgpQeXRob24gMyAtIDxoMT5QeXRob24gMywgMTM4PC9oMT4KU2VyaW91c2x5IC0gPGgyPlNlcmlvdXNseSwgNTQgYnl0ZXM8L2gyPgpKYXB0IC0gPGgxPkphcHQsIDxzPjU1PC9zPiA8cz40OTwvcz4gNDEgYnl0ZXM8L2gxPgpDSmFtIC0gPGgyPkNKYW0sIDxzPjMxPC9zPiAzMCBieXRlczwvaDI-Ck9jdGF2ZSAtIDxoMT5PY3RhdmUsIDxzPjExMTwvcz4gMTEwIGJ5dGVzPC9oMT4KUHl0aG9uIDIgLSA8aDE-UHl0aG9uIDIsIGV4YW1wbGUgaW1wbGVtZW50YXRpb248L2gxPgpGIyAtIDxoMj5GIywgMzMgYnl0ZXM8L2gyPgpKb2xmIC0gPGgxPkpvbGYsIDM3IGJ5dGVzLCBub25jb21wZXRpbmc8L2gxPgpTY2FsYSAtIDxoMj5TY2FsYSwgc2NvcmU6IDYyPC9oMj4KUHl0aG9uIDIgLSA8aDE-UHl0aG9uIDIsIDxzPjM3ODwvcz4gMzY1IEJ5dGVzPC9oMT4KSmFwdCAtIDxoMT5KYXB0LCA8cz42Mjwvcz4gPHM-NjA8L3M-IDxzPjU1PC9zPiA8cz41Mjwvcz4gNTEgYnl0ZXM8L2gxPgpKYXB0IC0gPGgxPkphcHQsIDxzPjI4PC9zPiAyNTwvaDE-ClB5dGggLSA8aDI-UHl0aCwgPHN0cmlrZT45Mzwvc3RyaWtlPiA4NSBieXRlczwvaDI-ClB5dGhvbiAzIC0gPGgxPlB5dGhvbiAzLCA8cz40ODwvcz4gNDUgYnl0ZXM8L2gxPgpQaWtlIC0gPGgxPjxhIGhyZWY9Imh0dHA6Ly9waWtlLmx5c2F0b3IubGl1LnNlIiByZWw9Im5vZm9sbG93Ij5QaWtlPC9hPiwgOTQgYnl0ZXM8L2gxPgpQeXRob24gLSA8aDE-UHl0aG9uLCA8cz4yMTI8L3M-IDIwMSBieXRlczwvaDE-ClB5dGhvbiAyIC0gPGgxPlB5dGhvbiAyLCAyMTEgYnl0ZXM8L2gxPgpQeXRob24gMiAtIDxoMT5QeXRob24gMiwgPHM-MTU3PC9zPiAxMzIgYnl0ZXM8L2gxPgpiZWVzd2F4IC0gPGgxPjxhIGhyZWY9Imh0dHA6Ly9yb3NldHRhY29kZS5vcmcvd2lraS9DYXRlZ29yeTpCZWVzd2F4IiByZWw9Im5vZm9sbG93Ij5iZWVzd2F4PC9hPiwgMzEgYnl0ZXM8L2gxPgpKYXZhKDEuOCkgLSA8aDM-SmF2YSAoMS44KSAtIEJvcWtlbCdmb3ZydSAoPHM-NDg2IDQ3NyA0NjUgNDUyIDQwMiAzOTYgMzkxIDM1ODwvcz4gMzU0IGJ5dGVzKTwvaDM-CkZhbGNvbiAtIDxoMT48YSBocmVmPSJodHRwOi8vZmFsY29ucGwub3JnIiByZWw9Im5vZm9sbG93Ij5GYWxjb248L2E-LCAxNiBieXRlczwvaDE-ClBpa2UgLSA8aDE-PGEgaHJlZj0iaHR0cDovL3Bpa2UubHlzYXRvci5saXUuc2UvIiByZWw9Im5vZm9sbG93Ij5QaWtlPC9hPiwgMzUgYnl0ZXM8L2gxPgpQeXRob24gMyAtIDxoMT5QeXRob24gPHM-Mjwvcz4gMywgPHM-MjU1PC9zPiA8cz4yMDQ8L3M-IDxzPjE4MDwvcz4gMTc4IGJ5dGVzPC9oMT4KQ29mZmVlU2NyaXB0IC0gPGgxPkNvZmZlZVNjcmlwdCwgMTQ0IGJ5dGVzPC9oMT4KUHl0aG9uIDIgLSA8aDE-UHl0aG9uIDIsIDxzPjIzNTwvcz4gPHM-MTkzPC9zPiAxNjcgQnl0ZXM8L2gxPgpSdXN0IC0gPGgxPlJ1c3QsIDc5PC9oMT4KVGktQmFzaWMgLSA8aDI-VGktQmFzaWMgODQsIDEwIGJ5dGVzPC9oMj4KTHVhIC0gPGgxPkx1YSwgODcgQnl0ZXM8L2gxPgpSdWJ5IC0gPGgxPlJ1YnksIDxzPjEyOTwvcz4gPHM-MTI2PC9zPiA8cz4xMjc8L3M-IDEyNiBjaGFyYWN0ZXJzPC9oMT4KSmF2YVNjcmlwdCAoRVM2KSAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCA8cz4yMTM8L3M-IDIwOCBieXRlczwvaDE-ClIgLSA8aDE-UiAtIDgxIGJ5dGVzIGFuZCAxMTcgYnl0ZXM8L2gxPgpNYXRoZW1hdGljYSAtIDxoMj5NYXRoZW1hdGljYSwgPHM-MzY8L3M-IDMzIGJ5dGVzPC9oMj4KUHl0aG9uIDIuNyAtIDxoMT5QeXRob24gMi43LCAyODIgYnl0ZXM8L2gxPgpQeXRob24gLSA8aDE-UHl0aG9uLCAxMDkgYnl0ZXM8L2gxPgpFUzYgLSA8aDI-RVM2LCA8cz4xNzg8L3M-IDE3MiBieXRlczwvaDI-ClJldGluYSAtIDxoMj48YSBocmVmPSJodHRwczovL2dpdGh1Yi5jb20vbWJ1ZXR0bmVyL3JldGluYSIgcmVsPSJub2ZvbGxvdyI-UmV0aW5hPC9hPiwgPHM-MTAyPC9zPiA4NSBieXRlczwvaDI-CkphdmFTY3JpcHQgKEVTNykgLSA8aDI-SmF2YVNjcmlwdCAoRVM3KSwgMTE0IGJ5dGVzPC9oMj4KUnVieSAtIDxoMT5SdWJ5LCA5OTwvaDE-ClBIUCAtIDxoMT5QSFAsIDxzPjE0NDwvcz4gPHM-MTMwPC9zPiA8cz4xMjc8L3M-IDxzPjEyMjwvcz4gPHM-MTIxPC9zPiA8cz4xMjA8L3M-IDExOSBCeXRlczwvaDE-Ck9jdGF2ZSAtIDxoMj5PY3RhdmUsIDk2IGJ5dGVzPC9oMj4KSmF2YSAtIDxoMT5KYXZhLCA8cz4xMzE8L3M-IDxzPjEyMjwvcz4gMTEwIGJ5dGVzPC9oMT4KU2VyaW91c2x5IC0gPGgyPjxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9NZWdvL1NlcmlvdXNseSIgcmVsPSJub2ZvbGxvdyI-U2VyaW91c2x5PC9hPiwgPHM-NDwvcz4gMyBieXRlczwvaDI-CkphdmEgLSA8aDE-SmF2YSwgMjE5IEJ5dGVzPC9oMT4KSmF2YVNjcmlwdCAoRVM2KSAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCAxNDIgPHM-MTQ2IDE0Nzwvcz48L2gxPgpDIC0gPGgxPkMsIDI1OSBieXRlczwvaDE-Ckhhc2tlbGwgLSA8aDE-SGFza2VsbCwgPHM-MTE5PC9zPiAxMDQgYnl0ZXM8L2gxPgpKZWxseSAtIDxoMT48YSBocmVmPSJodHRwOi8vZ2l0aHViLmNvbS9EZW5uaXNNaXRjaGVsbC9qZWxseSIgcmVsPSJub2ZvbGxvdyI-SmVsbHk8L2E-LCBub24tY29tcGV0aW5nPC9oMT4KU2VyaW91c2x5IC0gPGgyPlNlcmlvdXNseSwgMzIgYnl0ZXM8L2gyPgpEeWFsb2cgQVBMIC0gPGgyPkR5YWxvZyBBUEwsIDE4IGJ5dGVzPC9oMj4KUHl0aG9uIDMgLSA8aDI-UHl0aG9uIDMsIDxzPjI3OTwvcz4gPHM-Mjc4PC9zPiA8cz4yNzI8L3M-IDE3MyBieXRlczwvaDI-CkNKYW0gLSA8aDE-Q0phbTwvaDE-ClJ1YnkgLSA8aDE-UnVieSAoMi4yLjJwOTUpLCAyNzcgPHM-Mjk1IDMwNiAzMzEgMzY0PC9zPjwvaDE-Ckp1bGlhIC0gPGgxPkp1bGlhLCA8cz4yMjwvcz4gMjAgYnl0ZXM8L2gxPgpNQVRMIC0gPGgxPjxhIGhyZWY9Imh0dHBzOi8vZXNvbGFuZ3Mub3JnL3dpa2kvTUFUTCI-TUFUTDwvYT4sIDUzIGJ5dGVzPC9oMT4KUiAtIDxoMT5SIDxzPjM2PC9zPiAzNCBieXRlczwvaDE-ClB5dGggLSA8aDI-UHl0aCwgPHM-NTM8L3M-IDxzPjQ4PC9zPiA0NyBieXRlczwvaDI-Ckx1YSAtIDxoMT5MdWEsIDgwIGJ5dGVzPC9oMT4KUmV0aW5hIC0gPGgxPlJldGluYTwvaDE-ClBIUCAtIDxoMj5QSFAsIDIzMCBieXRlczwvaDI-ClB5dGhvbiAtIDxoMT48c3Ryb25nPlB5dGhvbiAtIDxzdHJpa2U-NTI1PC9zdHJpa2U-IDxzdHJpa2U-NDkxPC9zdHJpa2U-IDxzdHJpa2U-NDc4PC9zdHJpa2U-IDQzMCBieXRlczwvc3Ryb25nPjwvaDE-ClB5dGhvbiAtIDxoMT5QeXRob24sIDI3OCBjaGFyYWN0ZXJzPC9oMT4KSmF2YVNjcmlwdCAoRVM2KSAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCAxNDkgYnl0ZXM8L2gxPgpQeXRob24gMiAtIDxoMj5QeXRob24gMiwgMTA3IGJ5dGVzPC9oMj4KSmF2YVNjcmlwdCAoRVM2KSAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCAxODkgYnl0ZXM6PC9oMT4KSmF2YVNjcmlwdCBFUzYgLSA8aDI-SmF2YVNjcmlwdCBFUzYsIDE1NyBieXRlczwvaDI-ClBlcmwgLSA8aDI-UGVybCwgMjQ4IGJ5dGVzPC9oMj4KUHl0aCAtIDxoMT5QeXRoLCAzOCBieXRlczwvaDE-ClBvd2VyU2hlbGwgdjIrIC0gPGgyPlBvd2VyU2hlbGwgdjIrLCA8cz4xNzc8L3M-IDxzPjIzMTwvcz4gMTY4IGJ5dGVzPC9oMj4KMDVBQjFFIC0gPGgxPjxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9BZHJpYW5kbWVuLzA1QUIxRSIgcmVsPSJub2ZvbGxvdyI-MDVBQjFFPC9hPiwgNiBieXRlczwvaDE-ClJldGluYSAtIDxoMT5SZXRpbmEsIDQ2IGJ5dGVzPC9oMT4KQ0phbSAtIDxoMT5DSmFtLCA8cz4zMzwvcz4gMjYgYnl0ZXM8L2gxPgpSZXRpbmEgLSA8aDI-PGEgaHJlZj0iaHR0cHM6Ly9naXRodWIuY29tL21idWV0dG5lci9yZXRpbmEvIiByZWw9Im5vZm9sbG93Ij5SZXRpbmE8L2E-LCBDb2xvcGVlJ3Bva3JpLCA8cz4xNjU8L3M-IDxzPjE1Nzwvcz4gPHM-MTQzPC9zPiA8cz4xMjc8L3M-IDEyMyBieXRlczwvaDI-ClB5dGggLSA8aDI-UHl0aCwgMTE3IGJ5dGVzIChLcmljb2xhJ3BvcG8pPC9oMj4KR3Jvb3Z5IC0gPGgxPkdyb292eSA0NTwvaDE-CkphdmFTY3JpcHQgLSA8aDE-SmF2YVNjcmlwdCwgMjIwIGJ5dGVzLjwvaDE-Ckdyb292eSAtIDxoMT5Hcm9vdnkgNDU8L2gxPgpKYXZhU2NyaXB0IC0gPGgxPkphdmFTY3JpcHQsIDIyMCBieXRlcy48L2gxPgpEZXRvdXIgLSA8aDE-PGEgaHJlZj0iaHR0cDovL3Jhd2dpdC5jb20vY3lvY2UvZGV0b3VyL21hc3Rlci9pbnRlcnAuaHRtbCIgcmVsPSJub2ZvbGxvdyI-RGV0b3VyPC9hPiwgMiBieXRlczwvaDE-CkphdmFTY3JpcHQgRVM2IC0gPGgxPkphdmFTY3JpcHQgRVM2LCA3NSBieXRlczwvaDE-ClRjbCAtIDxoMj5UY2w8L2gyPgpQeXRob24gMiAtIDxoMj5QeXRob24gMjwvaDI-CkphdmEgLSA8aDE-SmF2YSwgPHM-OTkuMDQ8L3M-IDxzPjk4LjQ2PC9zPiA5Ny42NiBsY3MoKSBjYWxsczwvaDE-CkNqYW0gLSA8aDI-Q0phbSwgPHM-NDA8L3M-IDM5IGJ5dGVzPC9oMj4KUmV0aW5hIC0gPGgyPlJldGluYSwgPHM-ODI8L3M-IDxzPjgxPC9zPiA8cz43Nzwvcz4gPHM-NzQ8L3M-IDxzPjY4PC9zPiA2NyBieXRlczwvaDI-ClB5dGggLSA8aDI-UHl0aCwgPHN0cmlrZT4xODwvc3RyaWtlPiA8c3RyaWtlPjE2PC9zdHJpa2U-IDEwIGJ5dGVzPC9oMj4KUHl0aCAtIDxoMT5QeXRoLCA8cz4zMDwvcz4gMjggYnl0ZXM8L2gxPgpKYXZhU2NyaXB0IEVTNiAtIDxoMT5KYXZhU2NyaXB0IEVTNiwgNTQgYnl0ZXM8L2gxPgpQb3dlcnNoZWxsIC0gPGgyPlBvd2Vyc2hlbGwgLSA8cz4xNzI8L3M-IDxzPjE2Njwvcz4gMTkzIGJ5dGVzPC9oMj4Kc2VkIC0gPGgzPnNlZCwgPHM-MTM2PC9zPiAxMjggYnl0ZXM8L2gzPgpKYXZhU2NyaXB0IChFUzYpIC0gPGgxPkphdmFTY3JpcHQgKEVTNiksIDxzPjI1Njwvcz4gPHM-MjQ0PC9zPiA8cz4yMDg8L3M-IDE4NyBieXRlczwvaDE-CkphcHQgLSA8aDE-SmFwdCwgPHM-OTA8L3M-IDxzPjg3PC9zPiA4NiBieXRlczwvaDE-Ck1hdGhlbWF0aWNhIC0gPGgxPk1hdGhlbWF0aWNhLCA4MCBieXRlczwvaDE-Ck1BVEwgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9lc29sYW5ncy5vcmcvd2lraS9NQVRMIiByZWw9Im5vZm9sbG93Ij5NQVRMPC9hPiwgMzcgPHM-NDA8L3M-IGJ5dGVzPC9oMT4KTWF0aGVtYXRpY2EgLSA8aDE-TWF0aGVtYXRpY2EsIDxzPjMwPC9zPiA8cz4yNDwvcz4gMjIgYnl0ZXM8L2gxPgpSIC0gPGgxPlIgMjkgYnl0ZXM8L2gxPgpKYXZhU2NyaXB0IEVTNiAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCA8cz4xMDg8L3M-IDxzPjEwNzwvcz4gMTA2IGJ5dGVzPC9oMT4KTWF0bGFiIC0gPGgxPk1hdGxhYiwgMTU8L2gxPgpKYXZhU2NyaXB0IChFUzYpIC0gPGgxPkphdmFTY3JpcHQgKEVTNikgMTg0IDxzPjE4NyAxOTU8L3M-PC9oMT4KSmF2YSAtIDxoMT5KYXZhLCA8ZGVsPjE4MzwvZGVsPiAxODIgQnl0ZXM8L2gxPgpQeXRob24gMyAtIDxoMT5QeXRob24gMywgPHM-MTAxPC9zPiAxMDYgYnl0ZXM8L2gxPgpDIC0gPGgyPkMsIDI2IGJ5dGUgc291cmNlLCAyLDEzOSwxMDMsMzY3IGJ5dGUgb3V0cHV0LCB2YWxpZCBwcm9ncmFtPC9oMj4KV2luZG93cyBDYWxjdWxhdG9yIC0gPGgxPldpbmRvd3MgQ2FsY3VsYXRvciAtIDUgY2hhcmFjdGVyczwvaDE-ClBsYXR5UGFyIC0gPGgxPjxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9jeW9jZS9QbGF0eVBhciIgcmVsPSJub2ZvbGxvdyI-UGxhdHlQYXI8L2E-LCA0IGJ5dGVzPC9oMT4KUGVybCAtIDxoMT5QZXJsIDUgPHM-MjI4IDIwNSAxODYgMTg0IDE3OCAxNzcgMTUzIDE1MCAxNDkgMTQyPC9zPiAxMzcgKDEzNisxIGZvciAtRSk8L2gxPgpUSS1CQVNJQyAtIDxoMT5USS1CQVNJQywgPHM-NTk8L3M-IDxzPjU3PC9zPiA8cz41MDwvcz4gPHM-Mzc8L3M-IDM2IGJ5dGVzPC9oMT4K8J2UvPCdlYrwnZWE8J2VmvCdlZ8gLSA8aDE-8J2UvPCdlYrwnZWE8J2VmvCdlZ8sIDEyIGNoYXJzIC8gMjIgYnl0ZXM8L2gxPgpIYXNrZWxsIC0gPGgyPkhhc2tlbGwsIDI5IGJ5dGVzPC9oMj4KUHl0aG9uIC0gPGgxPlB5dGhvbiwgPHM-OTc8L3M-IDk1IGJ5dGVzPC9oMT4KSmF2YVNjcmlwdCAoRVM2KSAtIDxoMT5KYXZhU2NyaXB0IChFUzYpLCAzNTQgYnl0ZXMgKDIzMSBjaGFyYWN0ZXJzKTwvaDE-CkEtUmF5IC0gPGgyPjxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9tYW5ueW1hbmcvQS1SYXkiIHJlbD0ibm9mb2xsb3ciPkEtUmF5PC9hPiwgPHM-OTwvcz4gNyBieXRlczwvaDI-ClB5dGhvbiAzIC0gPGgxPlB5dGhvbiAzLCA8cz4xODc8L3M-IDxzPjE4MDwvcz4gPHM-MTczPC9zPiAxNTQgYnl0ZXM8L2gxPgpNQVRMQUIgLSA8aDE-TUFUTEFCLCAxNjcgYnl0ZXMvY2hhcmFjdGVyczo8L2gxPgpUcnVtcFNjcmlwdCAtIDxoMT48YSBocmVmPSJodHRwOi8vc2Ftc2hhZHdlbGwuZ2l0aHViLmlvL1RydW1wU2NyaXB0LyIgcmVsPSJub2ZvbGxvdyI-VHJ1bXBTY3JpcHQ8L2E-LCAzNyBieXRlczwvaDE-ClB1cmUgQmFzaCAtIDxoMT5QdXJlIEJhc2gsIDc8L2gxPgpSdWJ5IC0gPGgxPlJ1YnksIDxzPjY5PC9zPiA2NTwvaDE-CkMgLSA8aDE-QywgKDE0ICsgMTUpID0gMjkgYnl0ZSBzb3VyY2UsIDE3LDE3OSw4NzUsODM3ICgxNiBHQikgYnl0ZSBleGVjdXRhYmxlPC9oMT4KUiAtIDxoMT5SIC0gMzk8L2gxPgpDIC0gPGgxPkMsIDEyMyBieXRlczwvaDE-CkphcHQgLSA8aDE-SmFwdCwgMzggYnl0ZXM8L2gxPgpBY2MhISAtIDxoMj48YSBocmVmPSJodHRwOi8vY29kZWdvbGYuc3RhY2tleGNoYW5nZS5jb20vYS82MjQ5My8xNjc2NiI-QWNjISE8L2E-LCAxMjIgYnl0ZXM8L2gyPgpiYyAtIDxoMT5iYywgNzUgYnl0ZXM8L2gxPgpQSFAgLSA8aDE-UEhQIDxzdHJpa2U-NDA1PC9zdHJpa2U-IDMyNTwvaDE-ClBIUCAtIDxoMT5QSFAg4oCTIDMzMDIgYnl0ZXM8L2gxPgpKYXZhU2NyaXB0IC0gPHA-PHN0cm9uZz5KYXZhU2NyaXB0LCA8cz4yNjY8L3M-IDxzPjI2Mzwvcz4gMjQ0IGJ5dGVzPC9zdHJvbmc-PC9wPgpBV0sgLSA8cD48c3Ryb25nPkFXSyAtIDE0MCBieXRlczwvc3Ryb25nPjwvcD4KUmV0aW5hIC0gPGgxPjxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9tYnVldHRuZXIvcmV0aW5hIiByZWw9Im5vZm9sbG93Ij5SZXRpbmE8L2E-LCA1MCBieXRlcywgPHM-NzEuOCU8L3M-IDcyLjE1JTwvaDE-ClBvd2VyU2hlbGwgLSA8aDI-UG93ZXJTaGVsbCwgNDAgQnl0ZXM8L2gyPgpSdWJ5IC0gPGgxPlJ1YnksIDg1IGNoYXJhY3RlcnM8L2gxPgpicmFpbmZ1Y2sgLSA8aDE-YnJhaW5mdWNrLCA1MiBieXRlczwvaDE-ClJldGluYSAtIDxoMj48YSBocmVmPSJodHRwczovL2dpdGh1Yi5jb20vbWJ1ZXR0bmVyL3JldGluYSI-UmV0aW5hPC9hPiwgNDQgYnl0ZXM8L2gyPgpQeXRob24gMiAtIDxoMT5QeXRob24gMiwgPHM-MTU0PC9zPiAxNDcgYnl0ZXM8L2gxPgpIYXNrZWxsIC0gPGgxPkhhc2tlbGwsIDxzPjExMTwvcz4gMTA5IGJ5dGVzPC9oMT4KQ0phbSAtIDxoMj5DSmFtLCAxMCBieXRlczwvaDI-CkphdmFTY3JpcHQgRVM2IC0gPGgxPkphdmFTY3JpcHQgRVM2LCAzNiBieXRlczwvaDE-CkphcHQgLSA8aDE-SmFwdCwgMTMgYnl0ZXM8L2gxPgpIYXNrZWxsIC0gPGgyPkhhc2tlbGwsIDxzPjE2MDwvcz4gMTU3IGJ5dGVzPC9oMj4KUHl0aG9uIDMgLSA8aDE-UHl0aG9uIDMsIDM5IGJ5dGVzLjwvaDE-ClJ1YnkgLSA8aDE-UnVieSwgMzUgYnl0ZXM8L2gxPgpQeXRoIC0gPGgxPlB5dGgsIDxzPjQ2PC9zPiA8cz40NDwvcz4gPHM-NDM8L3M-IDxzPjQyPC9zPiA8cz4zOTwvcz4gMzUgYnl0ZXM8L2gxPgpNQVRMIC0gPGgxPjxhIGhyZWY9Imh0dHBzOi8vZXNvbGFuZ3Mub3JnL3dpa2kvTUFUTCIgcmVsPSJub2ZvbGxvdyI-TUFUTDwvYT4sIDQ4IDxzPjQ5PHM-IDxzPjUwPC9zPiA1Mzwvcz4gNTY8L3M-IGJ5dGVzPC9oMT4KUHl0aG9uIDIgLSA8aDI-UHl0aG9uIDIgJmFtcDsgUHVMUCDigJQgMiw2NDQsNjg4IHNxdWFyZXMgKG9wdGltYWxseSBtaW5pbWl6ZWQpOyAxMCw3NTMsNTUzIHNxdWFyZXMgKG9wdGltYWxseSBtYXhpbWl6ZWQpPC9oMj4KT0NhbWwgLSA8aDE-T0NhbWwsIDE1ODggKG4gPSAzNik8L2gxPgpQeXRob24gMiAtIDxiPlB5dGhvbiAyPC9iPgpIZWxwLCBXYXJEb3EhIC0gPGgxPjxhIGhyZWY9Imh0dHA6Ly9lc29sYW5ncy5vcmcvd2lraS9IZWxwLF9XYXJEb3ElMjEiPkhlbHAsIFdhckRvcSE8L2E-LCAxIGJ5dGU8L2gxPgpKYXZhU2NyaXB0IC0gPGgxPkphdmFTY3JpcHQgMjY4OCEhPC9oMT4KSGFza2VsbCAtIDxoMT5IYXNrZWxsICg1MCBjaGFyYWN0ZXJzKTwvaDE-CkhUTUwgKyBDU1MgLSA8aDE-SFRNTCArIENTUyA8ZGVsPjExODwvZGVsPiA8ZGVsPjc4PC9kZWw-IDxkZWw-Nzc8L2RlbD4gNzUgY2hhcmFjdGVyczwvaDE-ClB5dGhvbiAyIC0gPGgxPlB5dGhvbiAyICgyOSk8L2gxPgpIUTkrIC0gPHN0cm9uZz5IUTkrICgxIGNoYXJhY3Rlcik8L3N0cm9uZz4KQ3Jvc3MtYnJvd3NlciBKYXZhU2NyaXB0IC0gPGgyPkNyb3NzLWJyb3dzZXIgSmF2YVNjcmlwdCAoNDEgY2hhcmFjdGVycyk8L2gyPgpQSFAgLSA8aDI-UEhQIC0gNTQgY2hhcmFjdGVycyAobm8gY2hlYXRpbmcpPC9oMj4KRmlzaCAtIDxoMT48YSBocmVmPSJodHRwOi8vZXNvbGFuZ3Mub3JnL3dpa2kvRmlzaCI-RmlzaDwvYT4gLSA4IGNoYXJzPC9oMT4KQ2xvanVyZSAtIDxzdHJvbmc-Q2xvanVyZSAtIDEgY2hhciAoY2hlYXRpbmchKSBvciA5MSBjaGFyczwvc3Ryb25nPgoodWNiKWxvZ28gLSA8aDI-KHVjYilsb2dvIC0gMjggY2hhcnM8L2gyPgpFcmxhbmQgZXNjcmlwdCAtIDxoMj5FcmxhbmcgZXNjcmlwdCA8c3RyaWtlPjIyNTwvc3RyaWtlPiA8c3RyaWtlPjE2NDwvc3RyaWtlPiAxNDA8L2gyPgpUaS1CYXNpYyA4MyAtIDxoMj5UaS1CYXNpYyA4NCwgMTwvaDI-CkNoaWNrZW4gLSA8aDI-PGEgaHJlZj0iaHR0cDovL2Vzb2xhbmdzLm9yZy93aWtpL0NoaWNrZW4iPkNoaWNrZW48L2E-LCA3PC9oMj4KY2F0IC0gPGgxPmNhdCwgMCAtIOKIniBjaGFyYWN0ZXJzPC9oMT4KWm96dGV6IExpc3AgLSA8aDE-PGEgaHJlZj0iaHR0cDovL3N5bHdlc3Rlci5uby96b3pvdGV6LyIgcmVsPSJub2ZvbGxvdyI-Wm96b3RleiBMaXNwPC9hPjogNzM8L2gxPgpKIC0gPGgxPkogLSAyMCAoMTY_KSBjaGFyPC9oMT4KUmF3IC5leGUgLSA8c3Ryb25nPlJhdyAuZXhlLCAyNDcgYnl0ZXM8L3N0cm9uZz4KUXVpbmVQaWcgLSA8aDE-PGEgaHJlZj0iaHR0cHM6Ly9lc29sYW5ncy5vcmcvd2lraS9RdWluZVBpZyIgcmVsPSJub2ZvbGxvdyI-UXVpbmVQaWc8L2E-LCAzIEJ5dGVzIChtYWRlIGFmdGVyIHRoZSBjaGFsbGVuZ2UpPC9oMT4K4LKgX-CyoCAtIDxoMT48YSBocmVmPSJodHRwOi8vbWV0YS5jb2RlZ29sZi5zdGFja2V4Y2hhbmdlLmNvbS9hLzczOTAvNDEyNDciPuCyoF_gsqA8L2E-LDwvaDE-CkphdmFTY3JpcHQgLSA8c3Ryb25nPkphdmFTY3JpcHQgKDI5MSBjaGFyYWN0ZXJzKTo8L3N0cm9uZz4KSGFza2VsbCAtIDxoMj5IYXNrZWxsLCA8c3RyaWtlPjI3Mjwvc3RyaWtlPiwgPHN0cmlrZT4yNTA8L3N0cmlrZT4sIDI0MyBjaGFyYWN0ZXJzPC9oMj4). [Answer] # Jolf, 13 bytes, 85.94%, noncompeting ``` ρΥpΔid=',H',E pΔi remove all HTML tags from input, preserving content Υ d=',H slice from beginning until a member is a comma ρ ',E replace said comma with the empty string ``` I had this update on my computer. It was to my chagrin that I had forgotten to update the respective code for the interpreter. I don't feel like shooting for 100%. Maybe everyone should format their headers the same ¯\\_(ツ)\_/¯ ]
[Question] [ The challenge is to find the shortest implementation of the game of life in 3D ([example](http://gameoflife.samuellevy.com/)). These are the rules: Cells (in this case, cubes) with only 1 or less neighbours die, as if by lonliness. If exactly 5 cells surround an empty cell, they breed and fill it. If a cell has 8 or more neighbours, it dies from overcrowding. Make it at least a 10x10x10, where the layers are outputted individually like this: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X 0 0 X 0 0 0 0 0 0 0 X X X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Of course, a graphic 3D simulation is also accepted The starting position may be hardcoded but it must work if it is changed to any starting position. It must be able to calculate any amount of generations, and the user must be able to manually ask for the next generation. Shortest code in characters wins! I made my own implementation of this for any (cube) size: <http://jensrenders.site88.net/life3D.htm> You can use this to test, and you can base your code on mine, although I didn't comment it. [Answer] ## Mathematica - 120 bytes ``` g=CellularAutomaton[{(l=Flatten@#;c=l[[14]];n=Total@Drop[l,{14}];Which[n<2||n>7,0,n==5||c==1,1,0<1,0])&,{},{1,1,1}},##]& ``` Certainly not a contender for the win, but that was not my intention. Also, this could probably be golfed down significantly by just figuring out the rule number. I just really wanted to write a visualisation (although I'm actually sure there are already tons out there). So here we go): ``` animateGol3d[size_, i_, n_] := ListAnimate[ Graphics3D[ Cuboid /@ Position[#, 1], PlotRange -> {{0, size}, {0, size}, {0, size}} + 1 ] & /@ g[i, n] ]; ``` And after experimenting with a bunch of initial conditions, I got things like the following: ![enter image description here](https://i.stack.imgur.com/bvcK6.gif) And here is one with a grid size of `20x20x20`. This took a few seconds to simulate and render: ![enter image description here](https://i.stack.imgur.com/HqW9J.gif) By the way, this assumes periodic boundary conditions. [Answer] # APL, 46 It took me some time, but I got it down to 46 chars: ``` {(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵} ``` This is a function that takes a boolean 3D matrix of any size and computes the next generation, according to the given rules. Boundary conditions were not specified, so I chose to wrap around the other side, as in toroidal space. **Explanation** ``` { ⊂⍵} Take the argument matrix and enclose it in a scalar (i←2-⍳3) Prepare an array with values -1 0 1 and call it i ⌽[2]¨ Shift the matrix along the 2nd dim. by each of -1 0 1 i∘.⊖ Then for each result do the same along the 1st dimension i∘.⌽ And for each result again along the 3rd dimension m←⊃+/, Sum element-wise all 27 shifted matrices and call it m ``` The intermediate result `m` is a matrix with the same shape as the original matrix, which counts for each element how many cells are alive in its 3×3×3 neighbourhood, including itself. Then: ``` |5.5-m For each element (x) in m, take its distance from 5.5 ⍵∧3> If that distance is <3 (which means 3≤x≤8) and the original cell was 1, (5=m)∨ or if the element of m is 5, then the next generation cell will be 1. ``` **Example** Define a random 4×4×4 matrix with about 1/3 cells = 1 and compute its 1st and 2nd generation. The `⊂[2 3]` at the front is just a trick to print the planes horizontally instead of vertically: ``` ⊂[2 3] m←1=?4 4 4⍴3 1 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 1 0 0 1 0 ⊂[2 3] {(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵} m 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 ⊂[2 3] {(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵}⍣2⊢ m 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 0 1 0 1 0 1 0 0 0 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 0 1 0 0 0 1 0 ``` [Answer] # J - 42 char We are assuming a toroidal board (wraps around) in all three dimensions. J's automatic display of results appears to follow the output spec, using `1` for live cells and `0` for dead. This code works on boards of any width, length, and height (can be 10x10x10, 4x5x6, and so on). ``` (((1&<*<&8)@-*]+.5=-)~[:+/(,{3#<i:1)|.&><) ``` An explanation follows: * `,{3#<i:1` - Subexpression of the list of offsets for the cell and all its neighbours. + `<i:1` - The list of integers between 1 and -1 inclusive. + `,{3#` - Make three copies of the list (`3#`), and take the Cartesian product (`,{`). * `(,{3#<i:1)|.&><` - For each set of 3D offsets, shift the array. At a cost of 3 characters, you can change `|.&>` to `|.!.0&>` to not have wrap-around. * `[:+/` - Sum the all the shifted boards together. * `((1&<*<&8)@-*]+.5=-)~` - The long outer verb was a hook so it receives the board on the left and the right, and the side on the right we've been shifting and summing. The `~` swaps this around for this inner verb. + `5=-` - 1 in each cell that the sum-of-shifted-boards minus the original board (i.e. the neighbour count) equals 5, and 0 in all others. + `]+.` - Logical OR the above with the original board. + `(1&<*<&8)` - 1 if the number being compared between 1 and 8 exclusive, 0 otherwise. + `(1&<*<&8)@-*` - Compare (as above) the neighbour count, and multiply (i.e. logical AND when the domain is only 1 or 0) the logical OR result by this. Usage is as with the APL, just apply the function to the initial board for each step. J has a functional-power operator `^:` to make this easy. ``` life =: (((1&<*<&8)@-*]+.5=-)~[:+/(,{3#<i:1)|.&><) NB. for convenience board =: 1 = ?. 4 4 4 $ 4 NB. "random" 4x4x4 board with approx 1/4 ones <"2 board NB. we box each 2D plane for easier viewing +-------+-------+-------+-------+ |0 0 0 0|1 1 0 0|0 1 0 0|0 0 1 0| |0 1 0 0|0 0 0 0|0 0 0 1|1 0 0 0| |0 0 0 0|0 0 1 0|0 1 0 0|0 0 0 1| |1 1 0 0|1 0 0 0|0 0 0 1|0 1 1 0| +-------+-------+-------+-------+ <"2 life board +-------+-------+-------+-------+ |0 0 0 0|0 1 0 1|0 1 0 0|0 0 1 0| |1 1 1 1|0 0 0 0|0 0 0 1|1 1 0 0| |0 0 0 0|0 0 1 1|0 1 0 0|0 0 0 1| |1 0 0 0|1 0 0 1|0 0 0 1|0 1 1 1| +-------+-------+-------+-------+ <"2 life^:2 board NB. two steps +-------+-------+-------+-------+ |0 0 0 0|0 1 0 0|0 1 0 0|0 0 0 0| |0 1 0 0|0 0 0 0|0 0 0 1|0 1 0 0| |0 0 0 0|0 0 0 0|0 1 0 0|0 0 0 0| |0 0 0 0|0 0 0 1|0 0 0 0|0 1 1 1| +-------+-------+-------+-------+ <"2 life^:3 board NB. etc +-------+-------+-------+-------+ |0 1 0 0|1 1 1 0|0 1 0 0|0 1 0 0| |0 1 0 0|1 0 1 0|1 0 1 0|1 1 1 0| |1 0 0 0|0 0 0 0|0 1 0 0|0 1 0 0| |0 0 1 0|0 0 0 0|0 1 0 0|0 1 1 0| +-------+-------+-------+-------+ ``` I say "random" because the `?.` primitive gives reproducible random results by using a fixed seed every time. `?` is the true RNG. ]
[Question] [ [But Is It Art?](https://esolangs.org/wiki/But_Is_It_Art%3F) is an esolang created by [ais523](https://codegolf.stackexchange.com/users/76359/ais523), where one step is break the program into orthogonally connected "tiles": ``` A BBBB A B B AA CC A CC ``` Each separate letter shows a different tile. Interestingly, programs in But Is It Art? only rely on the orientations of the tiles themselves, not their placement. This means that the above program is functionally equivalent to ``` CC A CC A BBBB AA B B A ``` But this isn't equivalent to ``` BBB A B B AA CC A CC A ``` Or to ``` DDD A DDD AA CC ABBBB CC AB B ``` --- You are to take two binary rectangular matrices, \$A\$ and \$B\$. Each matrix will have zero or more "tiles" consisting of `1`s that are orthogonally connected to zero or more other `1`s. You should then output 2 distinctive consistent values that indicate whether the tiles in \$A\$ and \$B\$ are equivalent per But Is It Art?'s definition of equivalent grids. For example, ``` A = B = 0000111000 11000011 0110010010 10011100 0100011110 00101001 1011000001 10101111 1000000000 ``` Are equivalent. If you can't see it, try replacing the `1`s with letters, similar to above, to form groups of differently lettered tiles: ``` A = B = 0000AAA000 BB0000DD 0BB00A00A0 B00AAA00 0B000AAAA0 00C0A00A C0DD00000E E0C0AAAA C000000000 ``` You can assume that the matrices will always be rectangular and will only ever contain `1` and `0`. They will never be empty, but are not guaranteed to contain a `1`, or to be the same dimensions. You may take these matrices as newline separated strings, with a non-digit, non-newline separator between them; 2D nested arrays; a string representation of a matrix; or any reasonable representation of a binary matrix. You may take input as 2 lists of integers converted from binary, representing the rows (so the example `A` above would be `[56, 402, 286, 705, 512]`) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases | **A** | **B** | result | | --- | --- | --- | | ``` 1101110101001001011101100000101010000101011000101100111000001101101011 ``` | ``` 111110010101110001110011111101101000001011010101110111001010100011110011000010101101001000 ``` | false | | ``` 011011100110100101101111101001010010000011010011100000101101011 ``` | ``` 110000101000000000011011101101101011010110111111101010010100011 ``` | true | | ``` 111110110000100101011001001101100101000100110 ``` | ``` 11111011011011000001001010101001010101001001 ``` | true | | ``` 010010011111110001010001010111101101110001111111 ``` | ``` 000000000000000000000000000000000000000000000000 ``` | false | | ``` 1001 ``` | ``` 101 ``` | true | | ``` 1111111110011111110110000100000010001110011001101101001000100100011001 ``` | ``` 1111111110011111110110000100000010001110011001101101001000100100011001 ``` | true | | ``` 100000100110 ``` | ``` 100010100001 ``` | false | [Answer] # [J](http://jsoftware.com/), 80 bytes ``` -:&(1/:~@}.(#:i.)@$<@(-"1<./)/.~&(,/)[(*[:>./(0,(,-)=0 1)|.!.0])^:_[*i.@$)&(0,]) ``` [Try it online!](https://tio.run/##vVLBTsMwDL37K8KYumRqU5tjtqFKSJw4cZ3GtE1MjAs/APv1kjh2BhIr7ELU1olr@z0/57Uf@cneLIKZmNqgCfFtvLl7fLjvm1BZasOx@/D2Ohy868bzzjYjmvvWtf5Y2bp1SztdhlvfWqxt3bgFGnLv/srjyj2F9XJ68N3YVfHvyvUOYMNQOKkOfubXN8YypAMipPhCNBgfQD3HY1zsj1tAtgTJLZbjUpDEp0xwsD2LlBI4mVO5APA3HSlT4PJSLQdoFoLkJDqZHpVYTo3gz7uXN7MxdjbbO7M93zYSFfjSduJApzMmprk/QFK6XwkOt4tFOlmKmnuVCoJMBbug5/p/7YhVZIQ8LBkd6FhPey6dO/91XCQcdTJ6IbSSav8T0wHxlVNuO/Mphp06DnbmKzJAVvW91FxAmgkP6QVRj4sK6lIldET5MssUUQOwzEL8KJKJ@tv/gfneXv8J "J – Try It Online") Rather straight-forward approach. * `&(0,])` prepend a 0-line, so the first "tile" found is always the 0s * `[*i.@$` every 1 gets a unique index ``` 0 0 0 3 4 0 0 0 8 9 0 11 ``` * `[(*[:>./(0,(,-)=0 1)|.!.0])^:_` shift the board into the 4 directions, and reduce to the highest index. So each group tile will have the same index, e.g.: ``` 0 0 0 4 4 0 0 0 11 9 0 11 ``` * `(#:i.)@$` the coordinates of all the points `0 0, 0 1, 0 2,. 1 0, …` * `…/.~&(,/)` flatten both lists and group the coordinates by the indices * `<@(-"1<./)` normalize each group to `0 0`: * `1/:~@}.` drop the first group (the 0s) and sort the rest * `-:&` are the results for both inputs equal? [Answer] # [MATL](https://github.com/lmendo/MATL), ~~44~~ ~~43~~ ~~42~~ 39 bytes ``` ,i4&1ZIXKXz!"K@=&fJ*+!t1)-]N@-$XhoXS]X= ``` Inputs: two matrices (numerical 2D arrays), using `;` as row seperator. Output: `0` for falsy, `1` for truthy. [Try it online!](https://tio.run/##y00syfn/XyfTRM0wyjPCO6JKUcnbwVYtzUtLW7HEUFM31s9BVyUiIz8iODbC9v//aAMFQyCEkIbWBgoIvoG1AVwGSFobQtSgyYF1gPVBIMQUQxgbTc7AGm4CSC6WK9oQqtYAJoqkHgqtUdwIdQuSO5HsRPYLinsx3AyxHwA) Or [verify all test cases](https://tio.run/##zVOxakMxDNz7FU4pgaYN6KCbCWTo0gS6tINpeNAupYWELJn686@Jn22d9N7YoRiMbMmnk3Q@fJz2/Xt///0wx9tT2qaf2fV2vZp/bhZ3sxNul93zenmTvo7ppUur/vG13yEgSEBeEgdbhj2K8w2evFpkvotCJ8Qax6eKIs2nmCVLd7VDqEvfC90UOypi9YG4t@wGX9@6DKUaxhRXL0Z4LdeZtQQYfD1zDweOmPBJqZN6EzULnG@6a4Ypxdd5GY7UL0KyXPON4TviPJpay6KKIKVEJy0rDxqCttBJAoaqG7YTpcX1Y0MZm@WjRSsTb9cYO9QaQ6LMGXgAf27n7mTuFyueKzX9An06TH4XYSHz0OjDBqHfgpE6VZXube3y/@LzCw). ### How it works ``` , % Do twice i % Input: matrix 4&1ZI % Label connected components formed by the value 1, using 4-connectivity. % In the n-th component, 1 is replaced n XK % Copy this label matrix into clipboard K Xz! % Nonzeros as a row vector. Gives a vector containing the values 1, 2, % ..., N, where N is the number of connected components and each value % is repeated as many times as the size of that component " % For each n in that vector. Because of the above mentioned repetitions, % several iterations will give the same result. This is inefficient but % harmless K % Push label matrix @=&f % Push row and column indices of occurrences of n, as column vectors J*+! % Multiply by imaginary unit, add, transpose: combines the two column % vectors into a complex row vector which describes the connected % component with label n t1)- % Subtract first entry from the vector. This has the effect of % normalizing the *position* of each connected component ] % End N % Push current number of elements in the stack @- % Subtract 0 in the first iteration, or 1 in the second. The result is % the number of components of the latest input (in the second iteration % the bottom of the stack contains a result from the previous input) $Xh % Take that many elements from the stack and combine them into a cell % array. This cell array contains all row vectors of the components of % the latest input. Each component is repeated as many times as the % size of that component o % Convert into a matrix, right-padding with zeros if needed XS % Sort rows (atomically). This has the effect of normalizing the % *order* of the components ] % End X= % Are the two result matrices equal? Implicit display ``` [Answer] # [J](http://jsoftware.com/), 41 40 bytes ``` -:&([:/:~]-/~@#~&~.[:+./ .*^:_~1>:|@-/~) ``` [Try it online!](https://tio.run/##rVNNS8NAEL3PrxhSSRttNjMeV1MCgiB48lpsD9IivXiwR81fj7M7MzEKLQguSWZ38ubjvUkOQxHme2wjznGJhFHuOuDd0@P9UMdysY5N7J/rpu9mfdmHdbwKDYbLTdz2vIofnbyphgqOu/djG3AdcV@uGrztJBAXF3gITTeL@BC6ZYVFKOgmbK@r9Og@I8Du5fVNCraY4lN1AmZiuUEMyQXkZznKyn7ZAmXLkNxmMy6BDJ8ioea0FJMRGQf5mY6slXIWC1KARxFYTKqqXfCIzaFQQ2Vc@DcX6458pbw01rUeic0L2pLzznWh9pekAQ53sEGtiKYz/JQVn2nTCJusJjL4AL73uSPtw4VlY@Aa@oQ8wFWalv858XHQrApojdFkpxPOTp2c6GKK/tWc1CE1IbxAtufFYv3UePINKXlXkBxAo0DmJ6OmkvxvthMCsycCG5z/R0AWNnwB "J – Try It Online") -1 thanks to xash This J approach was different enough that I thought it deserved its own answer. We take input as lists of complex numbers representing the coordinates of the ones. ## the idea 1. Create an adjacency matrix of the points, using "distance <= 1" as the criterion for "adjacent". 2. Matrix multiply by itself until a fixed point. The rows now represent the groups. Rows with the same signature of ones are items in the same group, so we take the unique of the rows. 3. Use these as masks to pick out the actual points of each group. 4. For each of these, create a "subtraction table" of every group element with every other one. This will give a unique signature for the spatial pattern of the group, which is independent of its placement within the grid. 5. Sort these tables. 6. Check if the final two results are the same. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes ``` +þ2ŒRBU¤ẎQfðƬṪṢ W祀`Q1ị_Ɗ€Ṣ)E ``` [Try it online!](https://tio.run/##rVK9SgNBEO7nKWyDHOzkEQQfIIJamkaLkM7KLtocKFgkrTZGESSChQTOQIpbLu@x9yLn/O6lFQyXzM7c9818820ml9PpTdcdxu2wmZ8cndav6edxdBW/dqtUfaTqBc7je/3W3q3GI0ybh4vdPZ2pPjju0ub7jBJ6mjmBB7GEWKbqc9LOnup1vW5nz9AsUrVsb7ecXw8PYklofV8UhUC6DjEgfYFCoAeC55TSR@p0hCARgcsWBccgwzMT6MB1wQhCcCC/nKJOki5GUoCzAhiHp6oKzFihAoNz1yyaW2OfBxag6iCgq9ifK2Ktv76Sja25KjWgDcA8Ig/pdxaiGmW2gVvan4Whut0qtAnuinvuBN8bAfIdoUrRZjlI0Z2QopoO4Kv9NYBMowCkxASj3jvuXajq9uWDA0LezerBxOo2/9zNGWDm@r@Xd8Ff "Jelly – Try It Online") Accepts input as a list of (1-indexed) coordinates (though it doesn't really matter). -2 bytes thanks to caird coinheringaahing -1 byte thanks to Nick Kennedy This is one of the most fun challenges I've done in Jelly in a while. Thanks for the challenge :) ``` +þ2ŒRBU¤ẎQfðƬṪṢ Helper link; given a list containing coordinates ^ on the left and the list of filled coordinates ^ on the right, breadth-first fill from those ^ coordinates (initially accepts a singleton list ^ with the starting coordinate) +þ Outer product table on addition between each coordinate and 2ŒRBU¤ (As a nilad) 2ŒR [-2, -1, 0, 1, 2] B Binary; [[-1, 0], [-1], [0], [1], [1, 0]] U Vectorizing reverse; [[0, -1], [-1], [0], [1], [0, 1]] We now have the neighbors of each starting point Ẏ Tighten / flatten once, since outer product table gives a 2D list Q Remove duplicates f Filter to only keep cells that are part of the whole grid itself ðƬ Take that entire previous part and keep running it until ^ the results are no longer unique (i.e. we have filled ^ the whole block) (keeps intermediate values) Ṫ Keep the last of these Ṣ And sort it W祀`Q1ị_Ɗ€Ṣ)E Main Link; accepts a list of two matrices ) For each of the matrices ` With this list as the left and right arguments € For each coordinate Wç¥ Wrap the coordinate into a singleton list and call the helper ^ link on that with the list of coordinates on the right Q Remove any duplicates Ɗ€ For each shape 1ị Get the first coordinate _ Subtract each coordinate Ṣ Sort it E Are the two results equal? ``` [Answer] # JavaScript (ES10), ~~160~~ 145 bytes *Saved 15 bytes thanks to @tsh* Expects two binary matrices as `(a)(b)`. Returns a Boolean value. ``` a=>b=>(g=m=>m.map((r,Y)=>r.map((v,X)=>(h=(x,y,w=m[y])=>w&&w[x]?[[-1,w[x]=0,1,2].map(d=>d+h(x+d%2,y+--d%2))]:[])(X,Y))).flat(2).sort()+3)(a)==g(b) ``` [Try it online!](https://tio.run/##rVI9b9swEN35K7g0JmGKIN0tBdWpHbtkSaBooC3JVqEPl1JiG0F/u3s8krLXABUsH@/x3d17Z/@273baufY4Z8NY1dfGXK3JtyZne9ObvJe9PTLmxAs3uQvJu3iGhB0MO4uLOJm@uJQAnB4eTsW5/F4UmRb@ZJTQYlNiUWXyan1g53X1ZSMu6yyDyHn5WJScPUNzzmXT2ZltuJxGNzO@/sqZ5cbs2ZZfXf3nrXU1WzXTiktX2@pn29VPl2HHFJfz@DS7dtgzqD127cxWr0OWvQ5AbUb3w@4ObKImpx@E0oJaQbe0pIZONzZyvUzk3V1E2Hm4kFK64ObXW7@tHYj@Bi134zCNXS27cc8a0AyCAf/Lr1orDS@BoOBDVMohhQdxOBKFURMPx4g8T4p8X0ng4HHkIAN5BL99qsMk7BKLAiFVKRJr/NSgQi9cLCVZ5ulL30W2b65vufISgj6idNJxPxnlxgnhCj3H5kFrJMYBehmxDPG3oAjtYWlYVlwdSWu9nbEmKE/r0nFG2kzaeypI3nXwnloGOaHdEhBM20AwrJ6QZO@zwbvz80AtATWLWx3@Afrupw3q0wpUIqjFYcRVFIye/mu3fw "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 158 bytes ``` function(a,b,`+`=function(m,`?`=toString,x=seq(l=nrow(m))){for(i in x)x[K]=min(x[K<-as.matrix(dist(m))[i,]<=1]);?sort(by(m,x,function(d)?Map(rank,d)))})+a==+b ``` [Try it online!](https://tio.run/##rVPLbtswELzzK4j4YBJmA26uDeEPKHpyb6kB05ZUE5VIV6IbBYG/3eVDS9tJeihQQdCKq9mdnSHVn2d05@zvuve00743Ix3C0/6gxnpHNSZdE2Cur4zVvh7i0u9rCvOBdEY1R7vzxlmm@SuhdHWVEAOvWxZaDofW@LTmAdKNb4sobY2tB7UKmPl3O@c596BafTi0LwxDBImVmM@50MN95Y7bts7Yyt3vdNuyfmtsJdqHmD3FDyE@781uz7oxkCkF4hsnJ0Iadb4adCs2i81lqk5slhvl3Sq5IUY11L9Yq2zvnlnHOX9tXM9McImOfHz6sladsSy8PH4KY2XTWGUGH8FPRqwfFaz55@Xges@2L6H9KApXxZdf9YH12v4UVeh94gut1GJ7bliwl93JcAFAeBIZQ7pJDDEdXiGl45LkGK87LlJ1/gTpU@pCYjlkMKQOd5xwQmbU98c6@MKwDpsjX15nilxcumXmKSZcZk34WHkZB7IGIJOo8CRZCcA0VKrF0gzAKkmKbpwFCjaVJjUz2uh2CGpQjgQoTEVOpIPLOnoiJ7ck4GTXs8AbV7FA4uYUDRmONFCICpWcfH9n@yR3snYymuAmXN5Tj6zn1lyYmNFH3CssQ6c@5C@7DXnoTFJCSqJz@cRBPkKinFUpyb@G2z1DK@IYRRoJo//VsPwfSLg6RVk6uigRIIs9U778SVLeHtL/1vODmbEHudk9/K2iKXBryfkP "R – Try It Online") A function taking two matrices having two columns x,y with the coordinates of 1's and returning TRUE/FALSE. The order of the coordinates must be the same in the two matrices (e.g. both sorted by column then row). **Explanation:** ``` function(a,b){ # matrices a and b G=function(m){ # define function G taking a matrix m (same format as a,b) x=seq(l=nrow(m)) # init x = 1...nrow of m for(i in x){ # for i in 1...nrow of m D=as.matrix(dist(m))[i,] # compute D=euclidean distance of row i of m from all the other rows x[D<=1]=min(x[D<=1]) # replace all vals of x where D<=1 with the min value of x where D<=1 } # (now x contains an equal value for each group of connected tiles) B=by(m,x,function(d){ # for each group of connected tiles d (a sub-matrix of m) R=Map(rank,d)) # compute the rank of each vector of coordinates x and y toString(R) # concat the result into one string } # (now B = list of string for each group of tiles) toString(sort(B)) # sort B and concat into one string } # G(a)==G(b) # if G(a) == G(b) then they have the same connected tiles pattern } # ``` **Note:** we use `function()` keyword 3 times, with the new syntax `\()` of R 4.1.0+ we can save 21 bytes, but unfortunately is not on TIO (yet). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~151~~ 120 bytes ``` F²«≔⟦⟧θWS«≔⊕Lκη≔⁺θI⪪⁺κ0¹θ»Fη⊞θ⁰≔⟦⟧ζWΣθ«≔⟦⌕θ¹⟧εFε«§≔θλ⁰F⁺λ⟦η¹±¹±η⟧¿§θμ⊞εμ»⊞ζEε⟦⁻﹪λη﹪⌊εη÷⁻λ⌊εη⟧»≔⟦⟧θW⁻ζθF№ζ⌊κ⊞θ⌊κ⊞υθ»⁼⊟υ⊟υ ``` [Try it online!](https://tio.run/##dVFNa8MwDD3Xv8L0ZEMG9q47lW6DwDoKPZYeQuPWpqnzZXejo789kxT3Y4eFkEhPT0/P1tYW3bYuqmHY1R0Xz5L/sMms793ei/Um4618YZMv6yrDRe6bGFahc34vJBGvzNxvO3M0PphSfBi/D1YcpMy4xe4raVnFXrQZnxd9EKumcmGEDhmfqimwtcQemnhhE/JjJV/G3mKbQvzB2fnB2SoeRfvX0vrd@RL7tASyISMkaUZa4s1C7kvzjcQqzUg88gbY2oJGxj/NvghGaHkLrdzASLfj4kHkKJNjgzGqwVEmhJwzvigaLKwXzoP4oi5jVeMMC6opg5I7wnEMXR98ch9e3cmVRoxdQL9ziAQ2xiv7Z29j3xlByels8zr6QIaSEmzrftMPIIgQGkfFC1vC9oN4a2NR9WJZNyKChfEP7GFQWsOrmaJAMaUpYIDdcqhBXSGFUaavuWLEghwDQlIJH5bEUU5diWmAvo24DcHq8HSqfgE "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for equivalent, nothing if not. Explanation: ``` F²« ``` Process two matrices. ``` ≔⟦⟧θWS« ``` Start reading the matrix into a flat array. ``` ≔⊕Lκη ``` Keep track of the width of the matrix, including a safety margin. ``` ≔⁺θI⪪⁺κ0¹θ ``` Append the current row to the array, including a safety margin. ``` »Fη⊞θ⁰ ``` Append a safety margin to the bottom of the array. ``` ≔⟦⟧ζ ``` Start collecting the tiles. ``` WΣθ« ``` Repeat until all tiles have been found. ``` ≔⟦⌕θ¹⟧εFε« ``` Start a breadth-first search for the tile that includes the top leftmost `1`. ``` §≔θλ⁰ ``` Mark this cell has having been collected. ``` F⁺λ⟦η¹±¹±η⟧ ``` Check all orthogonally adjacent cells. ``` ¿§θμ⊞εμ ``` If this cell is a `1` then collect this cell. ``` »⊞ζEε⟦⁻﹪λη﹪⌊εη÷⁻λ⌊εη⟧ ``` Convert the position of all of the elements of this tile back to coordinates, then subtract the coordinates of the first element of the tile, and save the result to the list of normalised tiles. (Note that the subtraction is consistently off by one for cells to the left of the first cell, but because it's consistent, it won't affect the comparison between tiles.) ``` »≔⟦⟧θW⁻ζθF№ζ⌊κ⊞θ⌊κ ``` Sort the list of normalised tiles. ``` ⊞υθ ``` Save the sorted list. ``` »⁼⊟υ⊟υ ``` Compare the two lists of normalised tiles. ]
[Question] [ [Conways' Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are: * Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state * Any dead cell with exactly 3 living neighbours becomes a living cell * Any other cell becomes a dead cell Consider the following initial state: [![enter image description here](https://i.stack.imgur.com/zYFYa.png)](https://i.stack.imgur.com/zYFYa.png) That is, `PPCG` made up of living cells. Each letter is in a \$4×6\$ bounding box, with a single empty column of cells between boxes, for a total bounding box of \$19×6\$ After 217 generations, it reaches the following states: [![enter image description here](https://i.stack.imgur.com/3qZdQ.png)](https://i.stack.imgur.com/3qZdQ.png) From this point onwards, it is a "fixed state". All structures on the board are either still lifes or oscillators, so no meaningful change will occur. Your task is to improve this. [![enter image description here](https://i.stack.imgur.com/fUQNm.png)](https://i.stack.imgur.com/fUQNm.png) You may place up to 50 live cells in the \$5\times10\$ highlighted area, such that, when run, it takes more than 217 generations to reach a "fixed state". The answer with the highest number of generations wins, with ties being broken by the fewest number of placed living cells. For the purposes of this challenge, a "fixed state" means that all structures on the board are either still lifes or oscillators. If any spaceships or patterns of infinite growth are generated, the board will never reach a "fixed state" and such cases are invalid submissions. For example, this initial configuration takes 294 generations to reach a fixed state ([this](https://i.stack.imgur.com/JPIL8.png)), so is a valid submission with a score of 294: [![enter image description here](https://i.stack.imgur.com/jJQJe.png)](https://i.stack.imgur.com/jJQJe.png) [Preloaded](http://copy.sh/life/?gist=459828da945d707ff37e046dcf90c106) testable version, with the \$5\times10\$ box fully filled in. [Answer] # 2986 ~~2320~~ ~~1228~~ generations I wrote a rudimentary Python script for [Golly](http://golly.sourceforge.net) to generate random 5x10 patterns until it encountered one whose population was fixed, and whose bounding box was not too large (as would be expected of soups containing spaceships, as spaceships expand the bounding box as they travel). Here was what it came up with after about 50,000 patterns investigated, and I suspect this is not maximal. If anyone wants to continue this search by using my script, it's located below the pattern. [![enter image description here](https://i.stack.imgur.com/DI8MJ.png)](https://i.stack.imgur.com/DI8MJ.png) RLE of solution: ``` # 2986 generations x = 19, y = 20, rule = B3/S23 3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b o2bo$o4bo5b3o2b2o5$7bobobo$7b2ob2o$8bo2bo$11bo$10b2o$7bo2bo2$8b4o$7bo$ 7bo3bo! ``` Python script, to be run in Golly from File > Run Script (not golfed). You will need to paste/draw in the PPCG pattern and select the 5x10 rectangle first. ``` import golly as g from glife import rect, pattern g.setrule("B3/S23") #set the rule to Conway's Life soupcount = 0 #create a counter for # of soups processed while True: pop = 0 g.randfill(50) #randomly fill the 5x10 selection g.run(2400) #run the pattern for 2400 generations if g.getrect()[2] * g.getrect()[3] < 40000: #after 2400 generations, if the bounding box is small pop = g.getpop() #check to make sure the population is not the same (pattern is not static) g.run(120) if g.getpop() != pop: g.run(9880) #after 9880 more generations, if the bounding box is still small if g.getrect()[2] * g.getrect()[3] < 40000: #check to make sure the population is the same (pattern is static) pop = g.getpop() g.run(120) if g.getpop() == pop: g.reset() #if so, break the loop and return the pattern break g.reset() #repeat the loop and generate a new pattern if the pattern does not satisfy the conditions soupcount += 1 g.show(str(soupcount)) #continually show the # of soups processed to make sure the program isn't dead ``` **RLEs of old solutions:** ``` #C 2320 generations x = 19, y = 20, rule = B3/S23 3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b o2bo$o4bo5b3o2b2o5$7bo3bo$7b3o$10bo2$7bo$7bo2bo$7bo$7b2o$7bo3bo$7b2o2b o! ``` ``` #C 1228 generations, found manually with Ctrl+5 #C to continually generate random 5x10 patterns x = 19, y = 17, rule = B3/S23 3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b o2bo$o4bo5b3o2b2o5$7b5o$7bobobo$7b2obo$8bob2o$8b4o$8bo2bo$7bobo! ``` [Answer] # 887 generations ![Solution](https://i.stack.imgur.com/iVhI2.png) # Explanation …There is no explanation. I just brute-forced it manually and somehow beat ChartZ Belatedly by 90 generations. [Answer] # ~~884~~ 900 generations Just some random handcrafted pattern. [![pattern](https://i.stack.imgur.com/FrvND.png)](https://i.stack.imgur.com/FrvND.png) [Answer] # ~~3020~~ 3179 Generations ``` # # ### # # # ## ## # # # ## ## ``` Found by random search [Answer] # 3365 generations ``` _#_#_ ##__# _##__ _____ ##### _##__ #____ #_#_# ##___ _#_#_ ``` This 5x10 start can be expressed as 379744881760010 in decimal, 159603ec8570a in hex or 01010 11001 01100 00000 11111 01100 10000 10101 11000 01010 in 50-bit binary. Crossing my fingers that nobody starts a new alt-coin based on rewarding many generations in Conway's Game of Life...LifeCoins. ]
[Question] [ # Problem Let's define a generalized [Cantor set](https://en.wikipedia.org/wiki/Cantor_set) by iteratively deleting some rational length segments from the middle of all intervals that haven't yet been deleted, starting from a single continuous interval. Given the relative lengths of segments to delete or not, and the number of iterations to do, the problem is to write a [program or function](https://codegolf.meta.stackexchange.com/a/2422/60340) that outputs the relative lengths of the segments that have or have not been deleted after `n` iterations. [![Example 3,1,1,1,2](https://i.stack.imgur.com/L1tVT.png)](https://i.stack.imgur.com/L1tVT.png) Example: Iteratively delete the 4th and 6th eighth # Input: `n` – number of iterations, indexed starting from 0 or 1 `l` – list of segment lengths as positive integers with `gcd(l)=1` and odd length, representing the relative lengths of the parts that either stay as they are or get deleted, starting from a segment that doesn't get deleted. Since the list length is odd, the first and last segments never get deleted. For example for the regular Cantor set this would be [1,1,1] for one third that stays, one third that gets deleted and again one third that doesn't. # Output: Integer list `o`, `gcd(o)=1`, of relative segment lengths in the `n`th iteration when the segments that weren't deleted in the previous iteration are replaced by a scaled down copy of the list `l`. The first iteration is just `[1]`. You can use any unambiguous [output](https://codegolf.meta.stackexchange.com/q/2447/60340) method, even unary. # Examples ``` n=0, l=[3,1,1,1,2] → [1] n=1, l=[3,1,1,1,2] → [3, 1, 1, 1, 2] n=2, l=[3,1,1,1,2] → [9,3,3,3,6,8,3,1,1,1,2,8,6,2,2,2,4] n=3, l=[5,2,3] → [125,50,75,100,75,30,45,200,75,30,45,60,45,18,27] n=3, l=[1,1,1] → [1,1,1,3,1,1,1,9,1,1,1,3,1,1,1] ``` You can assume the input is valid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program measured in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15 13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to Dennis (using a Link rather than a chain allows right to be used implicitly by `¡`; No need to wrap the `1` in a list due to the fact that Jelly prints lists of one item the same as the item) -1 thanks to Erik the Outgolfer (use `Ɗ` to save the newline from using `Ç`) ``` 1×€³§JḤ$¦ẎƊ¡ ``` A full program printing a list in Jelly format (so `[1]` is printed as `1`) **[Try it online!](https://tio.run/##ASwA0/9qZWxsef//w5figqzCs8KnSuG4pCTCpuG6jgoxw4fCof///1s1LDIsM13/Mw "Jelly – Try It Online")** ### How? ``` 1×€³§JḤ$¦ẎƊ¡ - Main link: segmentLengths; iterations 1 - literal 1 (start with a single segment of length 1) ¡ - repeat... - ...times: implicitly use chain's right argument, iterations Ɗ - ...do: last 3 links as a monad (with 1 then the previous output): ³ - (1) program's 3rd argument = segmentLengths ×€ - 1 multiply €ach (e.g. [1,2,3] ×€ [1,2,1] = [[1,4,3],[2,4,2],[3,6,3]]) ¦ - 2 sparse application... $ - (2) ...to: indices: last two links as a monad: J - (2) range of length = [1,2,3,...,numberOfLists] Ḥ - (2) double [2,4,6,...] (note: out-of bounds are ignored by ¦) § - (2) ...of: sum each (i.e. total the now split empty spaces) Ẏ - 3 tighten (e.g. [[1,2,3],4,[5,6,7]] -> [1,2,3,4,5,6,7]) - implicit print ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ ~~107~~ ~~104~~ ~~103~~ ~~100~~ ~~99~~ 89 bytes ``` f=lambda n,l:n and[x*y for i,x in enumerate(l)for y in[f(n-1,l),[sum(l)**~-n]][i%2]]or[1] ``` [Try it online!](https://tio.run/##bU7bCoMwDH3fVxTGQCVCL/M22JeUPnSoTNAoTkFf9uuuFpw618BJcnKS02bsnjXyacrvpa4eqSYI5Q2JxlQO3kjyuiUFDKRAkmFfZa3uMqd0Z3o0pMwd9BmULshXX5mB5719VEoWF65U3UqmpqYtsCO5Q0EKYDa4cs/k8Iz4tIjZP7Gh5sQOyNdF/rsoExA2QojhOzJ1aHCO67osQAaGEasj4wEEFKIAGLVJULgazbYJLbIYeLQ7Za02p6zz8oMEdr2aPg "Python 2 – Try It Online") --- Saved * -10 bytes, thanks to Neil [Answer] # [R](https://www.r-project.org/), 94 bytes ``` f=function(n,a)"if"(n,unlist(Map(function(g,i)g(i),c(c,sum),split(m<-a%o%f(n-1,a),row(m)))),1) ``` [Try it online!](https://tio.run/##ZYwxCsMwDEX3HiMQkECB2qZbe4QewhgUBLEcYpse3xUZskR/0X9P6BiDP9w1NSkKShEn4cmWrpvUBt@4w6VXElxBkBIkqj0j1X2TBvm9xLnMDLo4@0BH@UFGG3I4GJ52H8id8YgPBncj/kaCkRd5Clc7LeL4Aw "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~76~~ 58 bytes ``` l%0=[1] l%n=do(x,m)<-l%(n-1)`zip`cycle[l,[sum l]];map(*x)m ``` [Try it online!](https://tio.run/##TYpBCsIwEEX3OcUsDCSSQtPgyuYInmAINLQFg5M0WIXq5WPNQuRv3n@8q19vM1EpxFuL2jHiyU6L2FSUfUNcpEbL4R3yML5GmpEUrs8I5Nw5@iyOm4wl@pDAwrQw2N0F8j2kBxy@BwQapes6xyVgW4n9GjypThnHzZ@q/a7KBw "Haskell – Try It Online") The function `(%)` takes the list of line lengths `l` as first argument and the number of iterations `n` as second input. *Thanks to Angs and Ørjan Johansen for -18 bytes!* [Answer] ## JavaScript (Firefox 42-57), 80 bytes ``` f=(n,l,i=0)=>n--?[for(x of l)for(y of(i^=1)?f(n,l):[eval(l.join`+`)**n])x*y]:[1] ``` Needs those specific versions because it uses both array comprehensions and exponentiation. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 71 bytes ``` l=>f=(n,c=1,e)=>n--?''+l.map(_=>(e=!e)?f(n,c*_):eval(l.join`+`)**n*c):c ``` [Try it online!](https://tio.run/##HcrBDoIwDADQu3/hiXZsS8AbpuPGTxgDyywGUjsiht@f0bzrW@MR9/Reto/T/OAyUBEKM4HaRI1lpKDO9VVVi3/FDUYKwHRm7OdfMSN2fEQB8WtedKonNEZNwi6V6yll3bOwl/yEAW4X2/y1d4QWsXwB "JavaScript (Node.js) – Try It Online") [Answer] # Java 10, 261 bytes ``` L->n->{if(n<1){L.clear();L.add(1);}else if(n>1){var C=new java.util.ArrayList<Integer>(L);for(int l=C.size(),i,x,t,s;n-->1;)for(i=x=0;i<L.size();){t=L.remove(i);if(i%2<1)for(;i%-~l<l;)L.add(i,C.get((i++-x)%l)*t);else{x++;s=0;for(int c:C)s+=c;L.add(i++,t*s);}}}} ``` Modifies the input-List instead of returning a new one to save bytes. [Try it online.](https://tio.run/##xVPBitswEL33K3QJaNayWCf0UtmGYigU3NMeSw@qI4dJFdlI4zSpSX89lb3ebim7e@lCJR3E6OnN07zRXh91ut9@uzZWh8A@aXTjG8YCacKG7eOpHAitbAfXEHZOflg2@ePZe@/1ucZA@UdHZmd8KZ66WXUuDAfjf6NK1rLiWqelS8sRW@7yDMZaNtZoz0HVUm@3PAN1MTYYNgHKCDhqz6rCme/sJQW8BtV2nqMjZotKBvxhOAgUJ0EiKJemZaZgRhSn4lZhXi8YBSMVtfTm0B0NR1AxMa7WUduEVrhKf9rcKriXh6KSO0OcY5KkJ1hZuCFQk@DxlCQqROoHGc27CkJSNMvD4gVBNyE@L46rikWPqx@@2lj3pfzHDrfsEC3hd@TR7T5/YRomexgjE4jfCvZMHfhfsSB1mOMbkc1zDQDqkSl7Nab1qzFt/ifTW7EWm39mmdUsLJd7h/@0dqadWsOJF5uZ1YvrrdR9b8@xuaVuGtMTd4vCu3Mgc5DdQLKPrULWTT9gTnu5/gI) ``` L->n->{ // Method with List and integer parameters and no return-type if(n<1){ // If `n` is 0: L.clear(); // Remove everything from the List L.add(1);} // And only add a single 1 // Else-if `n` is 1: Leave the List as is else if(n>1){ // Else-if `n` is 2 or larger: var C=new java.util.ArrayList<Integer>(L); // Create a copy of the input-List for(int l=C.size(), // Set `l` to the size of the input-List i,x,t,s; // Index and temp integers n-->1;) // Loop `n-1` times: for(i=x=0; // Reset `x` to 0 i<L.size();){ // Inner loop `i` over the input-List t=L.remove(i); // Remove the current item, saving its value in `t` if(i%2<1) // If the current iteration is even: for(;i%-~l<l;) // Loop over the copy-List L.add(i,C.get((i++-x)%l)*t); // And add the values multiplied by `t` // at index `i` to the List `L` else{ // Else (the current iteration is odd): x++; // Increase `x` by 1 s=0;for(int c:C)s+=c; // Calculate the sum of the copy-List L.add(i++,t*s);}}}} // Add this sum multiplied by `t` // at index `i` to the List `L` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Ø1××S¥ƭ€³Ẏ$¡Ṗ ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//w5gxw5fDl1PCpcat4oKswrPhuo4kwqHhuZb///9bNSwgMiwgM13/Mw "Jelly – Try It Online") Full program. Outputs `1` instead of `[1]`. Annoyingly, `ḋ` doesn't work like `×S¥` in this context, and `ƭ` doesn't work well with nilads. >\_< [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes ``` {(∊⊢×⍵(+/⍵)⍴⍨≢)⍣⍺,1} ``` [Try it online!](https://tio.run/##VU07DoJQEOw5xXZAhMjjj7chGAyRBAM0xlBpjGBI7KzFxgNoQ@tN9iLPBX/wJpmd2Z3d569idb7242ShBrGfZVHAeYj700bCQ4VV8zxj/ZAmU2IZ6zvWNywbUlesW4UVnOddmKZYXlKSWG1DCrczMVmKeNyJoR/FIjUokhaCJhnAeuhyrjCBDT38tKCP@h5NOtjg/jOkbeIOpmBIFlUD6FGe6RZYGjgWMK0vhgYmBYbG7pm5oDu0/b752e7x/ccb@xc "APL (Dyalog Classic) – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 27 bytes ``` {x{,/y*(#y)#x}[(y;+/y)]/,1} ``` [Try it online!](https://tio.run/##VU3LCoMwELz3KxbsQVuLWWN87aeEgL1YimJBPBiD/fU0RhDLwOzMLLPbPYbXYG1bm9nEib6FgY6CeZWhpnuiI5XEuFo71eYql@9Yt3Imraj5dBQ27fPdk/O00Bip9TJJRhzQI6UYlUvwlBxqW5wsVcA9cijhSJ3OHW/ItgIn4SQnTAUIBoUAZH5wBplbnU3uGUtIi73qb@58fKjgz6sf "K (ngn/k) – Try It Online") `{` `}` is a function with arguments `x` and `y` `(y;+/y)` a pair of `y` and its sum `{` `}[(y;+/y)]` projection (aka currying or partial application) of a dyadic function with one argument. `x` will be `(y;+/y)` and `y` will be the argument when applied. `,1` singleton list containing 1 `x{` `}[` `]/` apply the projection `x` times `(#y)#x` reshape to the length of the current result, i.e. alternate between the outer `y` and its sum `y*` multiply each element of the above with the corresponding element of the current result `,/` concatenate [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->a,l{r=[1];a.times{s=p;r=r.flat_map{|x|(s=!s)?l.map{|y|x*y}:x*l.sum}};r} ``` [Try it online!](https://tio.run/##ZcnBCgIhFIXhfU9Ru2m4SSptEpsHEQmDhEBBrjOgqM9u5KbFcFb/d3B75W5lvzwMuIJSUS0MWT/@HUuUQaBEYp1Zn96EUlOdojzF8@LI6FzTnNs9zY7EzbcmsPVwtOoKigMdY1offkT3xPbEQd2AAf/n@LXuXw "Ruby – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` us.e?%k2*bsQ*LbQGE]1 ``` Input is segment array `l`, then iterations `n`. Try it online [here](https://pyth.herokuapp.com/?code=us.e%3F%25k2%2AbsQ%2ALbQGE%5D1&input=%5B3%2C1%2C1%2C1%2C2%5D%0A2&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=us.e%3F%25k2%2AbsQ%2ALbQGE%5D1&test_suite=1&test_suite_input=%5B3%2C1%2C1%2C1%2C2%5D%0A0%0A%5B3%2C1%2C1%2C1%2C2%5D%0A1%0A%5B3%2C1%2C1%2C1%2C2%5D%0A2%0A%5B5%2C2%2C3%5D%0A3%0A%5B1%2C1%2C1%5D%0A3&debug=0&input_size=2). ``` us.e?%k2*bsQ*LbQGE]1 Implicit, Q=1st arg (segment array), E=2nd arg (iterations) u E Execute E times, with current value G... ]1 ... and initial value [1]: .e G Map G, with element b and index k: *bsQ Multiply b and the sum of Q {A} *LbQ Multiply each value of Q by b {B} ?%k2 If k is odd, yield {A}, otherwise yield {B} s Flatten the resulting nested array ``` ]
[Question] [ Inspired by this [unassuming StackOverflow question](https://stackoverflow.com/questions/48702999/in-java-8-whats-an-elegant-way-to-remove-certain-duplicate-words-from-a-string/). The idea is simple; given a String and an array of Strings, remove any instances of words in the array (ignoring case) from the input String other than the first, along with any additional whitespace this may leave. The words must match entire words in the input String, and not parts of words. e.g. `"A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", ["cat", "mat"]` should output `"A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat"` ## Input * Input can be taken as either a String, and an array of Strings or an array of Strings where the input String is the first element. These parameters can be in either order. * The input String may not be taken as a list of space-delimited Strings. * The input String will have no leading, trailing or consecutive spaces. * All input will only contain characters [A-Za-z0-9] with the exception of the input String also including spaces. * The input array may be empty or contain words not in the input String. ## Output * The output can either be the return value from a function, or printed to STDOUT * The output must be in the same case as the original String ## Test cases ``` the blue frog lived in a blue house, [blue] -> the blue frog lived in a house he liked to read but was filled with dread wherever he would tread while he read, [read] -> he liked to read but was filled with dread wherever he would tread while he this sentence has no matches, [ten, cheese] -> this sentence has no matches this one will also stay intact, [] -> this one will also stay intact All the faith he had had had had no effect on the outcome of his life, [had] -> All the faith he had no effect on the outcome of his life 5 times 5 is 25, [5, 6] -> 5 times is 25 Case for different case, [case] -> Case for different the letters in the array are in a different case, [In] -> the letters in the array are a different case This is a test Will this be correct Both will be removed, [this,will] -> This is a test Will be correct Both be removed ``` As this is code golf, lowest byte count wins! [Answer] # [R](https://www.r-project.org/), 84 bytes ``` function(s,w,S=el(strsplit(s," ")),t=tolower)cat(S[!duplicated(x<-t(S))|!x%in%t(w)]) ``` [Try it online!](https://tio.run/##ZVDBTgMhEL37FVOSppBsLyZ7sh6Mn9CjeqAwCJEFA0O3Jv77OqxeWg9kmDfvvXlQlhhORZcvOSH5bKu6c3DYL64lQyEnWYd5OD5ilJVK/YyBGBEglBrokXLMMxZlNMnjy8Y2nvMdrbwc9gwp9b25bEPakpzVm1qcFOQRTrEhuJLfIYYzWggJ9C/oc6soBtEboR667@417TiTFCyM4YPplKGgtnBqBLOu4EKMDM@BPNh1MnsseMYCrJlzi6z5w0PEDvaO16zlZg35UKFiIkyGueyfMkyajMcqBsMETCzlFjmqulE/xQj9iU73NL4b2KvDZugcGoKcVmZuZPLE1UHfHIPrH@D/B3vWlX1zARvYoHBCMHr9rbXcsEegMGGFEdj0fmTWeEVZfgA "R – Try It Online") Less than 100 bytes on a [string](/questions/tagged/string "show questions tagged 'string'") challenge that's not also [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'")? Explanation: After we break up the string into words, we need to exclude those that are 1. duplicates and 2. in `w` or alternatively, turning that on its head, keeping those that are 1. the first occurrence of a word OR 2. not in `w`. `duplicated` neatly returns logical indices of those that are not the first occurrence, so `!duplicated()` returns indices of those which are first occurrences, and `x%in%w` returns logical indices for `x` of those which are in `w`. Neat. [Answer] # Java 8, ~~117~~ 110 bytes ``` a->s->{for(String x:a)for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)";s.matches(x);s=s.replaceAll(x,"$1$3"));return s;} ``` **Explanation:** [Try it online.](https://tio.run/##nVPBjtowEL3vV4wsDskuRGoremgKVVu1t55A6qHqwXEmG7OOHdkTAqJ8Ox2HrAQ9FSRHid9M3sybZ2/kVs5ci3ZTvpyUkSHAD6nt4QEgkCStYMMZWUfaZFVnFWlns@/jx8cVeW2ff/2e/kfWFM7v5RIULE5ytgyz5aFyPjnjsPsg07jdLUTySadJ9iiedk8ie4R0@EjgzySiqchD1khSNYZkl@ZhETKPrZEKPxuT7KZi8mbyTqRp7pE6byHkx1POgni1XWFY0yht63QJDctNXoXINCoHWO0DYZO5jrKWI2RsojLZtmafWOzhNf0gCtOhOKZjTFCNECGovHsGo7dYgrYgz2DtuoCxsdtqeJTlRQ0uYfQLE5ODGIKiI@hlgEobw3CvqYZyiPQ1etyiB/6nd53hf0ZcG4zgQH1zQ4RWTAXPH8O1eB0goOWwYnbuyDoYjbq5yD@0zrIC1gfSBBf92/NcSSq6vfv6app8ZCC6Vsk4tjr2XV49rAGrChVxD0MmV1Cu4XcFsTOjqzs8nfMA31@0MQfSDQaYA1O@nd9OqOSVF195C3yboNTcvGdTYMi4w@tAF7xrXBFEDNbfVus76HhkLD1aeckaB8lLnql/6sEUBgoE5byP0//i2J/hCBTx3DaO79ZY//hwPP0F) ``` a->s->{ // Method with String-array and String parameters and String return for(String x:a) // Loop over the input-array for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)"; // Regex to match s.matches(x); // Inner loop as long as the input matches this regex s=s.replaceAll(x,"$1$3")); // Replace the regex-match with the 1st and 3rd capture groups return s;} // Return the modified input-String ``` Additional explanation for the regex: ``` (?i)(.*"+x+".* )"+x+"( |$)(.*) // Main regex to match: (?i) // Enable case insensitivity ( // Open capture group 1 .* // Zero or more characters "+x+" // The input-String .* // Zero or more characters, followed by a space ) // End of capture group 1 "+x+" // The input-String again ( // Open capture group 2 |$ // Either a space or the end of the String ) // End of capture group 2 ( // Open capture group 3 .* // Zero or more characters ) // End of capture group 3 $1$3 // Replace the entire match with: $1 // The match of capture group 1 $3 // concatted with the match of capture group 3 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ 18 bytes ``` "Ybtk@kmFyfX<(~)Zc ``` Inputs are: a cell array of strings, then a string. [Try it online!](https://tio.run/##y00syfn/XykyqSTbITvXrTItwkajTjMq@f//avXkxBJ1HQX1XCBVy6XuqADkA3FOTmqKAlCsRKEYyM/PU0gE8RQS81IUyvOLUoHcDCCXJNXqAA) Or [verify all test cases](https://tio.run/##lVHBSgQxDL37FcHLKHgSxpMHF0Xw7kEFwW4ntWU7LbSZHZZFf3186e4e9OahZJK89/KSGY3E5WM5f13L5m4zPu7cy@3F9@WbXd4fnpd9Z410V9SNCF9n3YqQ48XIA6EmVJHnREYzMmmgORdG6pH@C92d7bt1nFjHiGfSb3Ilf1IMW/CD0lrR56mywgubQeFAx7ABRjJpjdaT0GwqudBGz0E8Da0zey685ULgzHmK4BzrIbIWmya0hZPubT1zPXoKlSonNCyQUE9Z1wCignBC5ARhjCUTa6YqZgfnYmzbzx/8rtDWFZ1RY17Vhl8Pyuwc23YsReZJbB4RHemQGFw7QK8Wb1SyJwkjV@oJ7etem9YcjN8jksuFhgDNgg2otQB5SqdrRxbhUvXKmppSYNzg37Sz/2H@AA). ### How it works ``` " % Take 1st input (implicit): cell array of strings. For each Yb % Take 2nd input (implicit) in the first iteration: string; or % use the string from previous iteration. Split on spaces. Gives % a cell array of strings tk % Duplicate. Make lowercase @k % Push current string from the array taken as 1st input. Make % lowercase m % Membership: gives true-false array containing true for strings % in the first input argument that equal the string in the second % input argument F % Push false y % Duplicate from below: pushes the true-false array again f % Find: integer indices of true entries (may be empty) X< % Minimum (may be empty) ( % Assignment indexing: write false in the true-false array at that % position. So this replaces the first true (if any) by false ~ % Logical negate: false becomes true, true becomes false ) % Reference indexing: in the array of (sub)strings that was % obtained from the second input, keep only those indicated by the % (negated) true-false array Zc % Join strings in the resulting array, with a space between them % End (implicit). Display (implicit) ``` [Answer] ## [Perl 5](https://www.perl.org/), 49 bytes ``` @B=<>;$_=join$",grep!(/^$_$/xi~~@B&&$v{+lc}++),@F ``` [Try it online!](https://tio.run/##K0gtyjH9/9/BydbGzlol3jYrPzNPRUknvSi1QFFDP04lXkW/IrOuzsFJTU2lrFo7J7lWW1tTx8Ht//@QjMxiBSBKVChJLS5RCM/MyVEoAYklpSok5xcVpSaXKDjll2QolINkgIJFqbn5ZakpXCBFXCBBrn/5BSWZ@XnF/3ULEgE "Perl 5 – Try It Online") Saved 9 (!!) bytes thanks to [@TonHospel](https://codegolf.stackexchange.com/users/51507/ton-hospel)! [Answer] # Pyth, 27 bytes ``` jdeMf!}r0eT@mr0dQmr0dPT._cz ``` [Try it online](http://pyth.herokuapp.com/?code=jdeMf%21%7Dr0eT%40mr0dQmr0dPT._cz&input=%5B%27In%27%5D%0Athe%20letters%20in%20the%20array%20are%20in%20a%20different%20case&debug=0) ### Explanation ``` jdeMf!}r0eT@mr0dQmr0dPT._cz z Take the string input. ._c Get all the prefixes... f eT@ ... which end with something... !} Q PT ... which is not in the input and the prefix... r0 mr0d mr0d ... case insensitive. jdeM Join the ends of each valid prefix. ``` I'm sure the 10 bytes for case insensitive check can be reduced, but I don't see how. [Answer] # [Stax](https://github.com/tomtheisen/stax), 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` åìøΓ²¬$M¥øHΘQä~╥ôtΔ♫╟ ``` 25 bytes when unpacked, ``` vjcm[]Ii<;e{vm_]IU>*Ciyj@ ``` The result is an array. The convenient output for Stax is one element per line. [Run and debug online!](https://staxlang.xyz/#c=%C3%A5%C3%AC%C3%B8%CE%93%C2%B2%C2%AC%24M%C2%A5%C3%B8H%CE%98Q%C3%A4%7E%E2%95%A5%C3%B4t%CE%94%E2%99%AB%E2%95%9F&i=the+blue+frog+lived+in+a+blue+house%0A%5B%22blue%22%5D%0A%0Ahe+liked+to+read+but+was+filled+with+dread+wherever+he+would+tread+while+he+read%0A%5B%22read%22%5D%0A%0Athis+sentence+has+no+matches%0A%5B%22ten%22%2C+%22cheese%22%5D%0A%0Athis+one+will+also+stay+intact%0A%5B%5D%0A%0AAll+the+faith+he+had+had+had+had+no+effect+on+the+outcome+of+his+life%0A%5B%22had%22%5D%0A%0A5+times+5+is+25%0A%5B%225%22%2C+%226%22%5D%0A%0ACase+for+different+case%0A%5B%22case%22%5D%0A%0Athe+letters+in+the+array+are+in+a+different+case%0A%5B%22In%22%5D%0A%0AThis+is+a+test+Will+this+be+correct+Both+will+be+removed%0A%5B%22this%22%2C%22will%22%5D&a=1&m=1) ## Explanation ``` vj Convert 1st input to lowercase and split at spaces, c Duplicate at the main stack m Map array with the rest of the program Implicitly output []I Get the first index of the current array element in the array i< Test 1: The first index is smaller than the iteration index i.e. not the first appearance ; 2nd input {vm Lowercase all elements _]I Index of the current element in the 2nd input (-1 if not found) U> Test 2: The index is non-negative i.e. current element is a member of the 2nd input *C If test 1 and test 2, drop the current element and go on mapping the next iyj@ Fetch the corresponding element in the original input and return it as the mapped result This preserves the original case ``` [Answer] # [Perl 6](https://perl6.org), 49 bytes ``` ->$_,+w{~.words.grep:{.lc∉w».lc||!(%){.lc}++}} ``` [Test it](https://tio.run/##rVPNbhoxEL77KaYSKZBdtlIlOASCiHqq1GNvFFXO7ixr1axXtmGLCJzbZ@kj5JZH6YvQGcPmpwlSI/Xgn5n55psfjyu0erBfOoTVIEmHQizW8DY1GcLlvjdufY2jerNLamMzl8wtVhebRKe/f/ys727pcnPzpnPWZdU2irbbPTlPPDoPl6BViS5ZyOoCNgLgHS2A1sh5q8r5mACd5LwrgrYdQ/t4m7ZhB@1ZO0hTmIxC5AD/UkddmJ3D2WM89MbNvTXC7xWmHjOGJ1FQcuQhbR3Y3ceOYXf3q2FOPinnY7Y@eHfFVghuyWcqZSgqLUuIQl1DkRt7LJEid6B14IxhEuhiaDU00A11K9fLECu9Bm5qp8Ef4N1HeLHdX0EqPS2tyX0hvQdHsilBsgSyzIDckMSCxFehY5imvJNlxpm/PtQLyKco4QuEa71EyK2Z0/uvyEExLigLQx2lNFgIKZyEB6Qgq1bfSOcNWJQZXC891NJBrkIqtfIFZMFSF2hxhRbIpzZLTT5HvdLISpYoNB8h9H/kpqqVA4elxzIlBZGUhvuUFkjjMCV1DHRH11R9Gn7gMiVFojxAamfAebmmtniZ8hs@UJxEiStScm9zyVUUHCR7sigg5jkNHb8iI83Sp2ZBZw5MrVXOD1Ucm/Ui379wiD54tUAHffoF8L5PnLQGgbQxBYP4IOmz8c/KFJFa6g4NXJgWPoLDc0iYN43eo3U8OCxKa6kRkkYyTNIzuo/l/eid9Pzb7Q8 "Perl 6 – Try It Online") ## Expanded: ``` -> # pointy block lambda $_, # first param 「$_」 (string) +w # slurpy second param 「w」 (words) { ~ # stringify the following (joins with spaces) .words # split into words (implicit method call on 「$_」) .grep: # take only the words we want { .lc # lowercase the word being tested ∉ # is it not an element of w».lc # the list of words, lowercased || # if it was one of the words we need to do a secondary check ! # Boolean invert the following # (returns true the first time the word was found) ( % # anonymous state Hash variable ){ .lc }++ # look up with the lowercase of the current word, and increment } } ``` [Answer] # [Perl 5](https://www.perl.org/), ~~50~~ 48 bytes Includes `+1` for `-p` Give the target string followed by each filter word on separate lines on STDIN: ``` perl -pe '$"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop';echo This is a test Will this be correct Both will be removed this will ^D ^D ``` The `chop` is only needed to fix the trailing space in case the last word gets removed Just the code: ``` $"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop ``` [Try it online!](https://tio.run/##FcpBCsIwEIXhfU8xhlSUYmkXXUVFPIPgwrqwcTCBaEIm1kLt1Y0NvNX3fofeNPFNCE1ZV2UlImc79mWC8rZbHcbLdn@d1i3lfDkseD8ayeupKHKNj0FIZV2MJ6UJ5t0gIAU4a2MgJOsQpPUeZYCjDQo@6ZnR49P2eM9SlCX8WRe0fVHcuD8 "Perl 5 – Try It Online") [Answer] ## JavaScript (ES6), 98 bytes ``` s=>a=>s.split` `.filter(q=x=>(q[x=x.toLowerCase()]=eval(`/\\b${x}\\b/i`).test(a)<<q[x])<2).join` ` ``` [Answer] # [K4](http://kx.com/download/), 41 bytes **Solution:** ``` {" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x} ``` **Examples:** ``` q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat";("cat";"mat")] "A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat" q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["Case for different case";enlist "case"] "Case for different" q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["the letters in the array are in a different case";enlist "In"] "the letters in the array are a different case" q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["5 times 5 is 25";(1#"5";1#"6")] "5 times is 25" ``` **Explanation:** Split on whitespace, lowercase both inputs, look for matches, remove all but the first occurrence, join the string back together. ``` {" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x} / the solution { } / lambda with implicit x & y args " "\:x / split (\:) on whitespace " " x: / save result as x _ / lowercase x ~/:\: / match (~) each right (/:), each left (\:) (_y) / lowercase y &:' / where (&:) each ('), ie indices of matches 1_' / drop first of each result ,/ / flatten y: / save result as y y@> / descending indices (>) apply (@) to y x_/ / drop (_) from x " "/: / join (/:) on whitespace " " ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 bytes ``` f=(s,a)=>a.map(x=>s=s.replace(eval(`/\\b${x}\\b */ig`),s=>i++?"":s,i=0))&&s ``` [Try it online!](https://tio.run/##rVJdT8MwDHznV1gVQi2UDSGNB6QO8TsY0rzUWQNpM9XpCkL89uFkDMQ@ECAeqvTi893FyQMukVVrFv68cSWtVrpIOcesGOOgxkX6VIy54EFLC4uKUlqiTafDyWR2/PL0KgucDs18muVcjM3Z2U2SXHNuiossOznhlXINO0sD6@apTpNbUOjls5ZKqNF7YMGuAQwIsCmhdy0JrAT@ip3kcJeouCZSTe6zoviD3x7mlk92tHUoXxHMbEegWzcHa5aiYEJj3KxcxxTDBbiOdbBjTd5xELo1j0LyDlrCEmadhx4ZtIl5e@MrKGOlr6ilJbUgPb3rrPS87xtLYTOgGCf@xDj/Kb9vPIaBqfHUKKGIbOPChFVFHINIIVyaYOKPAX3Ts9/BNZJI8gJadsAen2WkHlV8GJ@ih2k7srfCCjelMZy/CjnKL59kIq1JxXcSmK7zytWyaghe1uj1zVebSe@V/JHMTroReFMTwwiEcjkKPqMcrqLNprauZKs3 "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript ES6, 78 Bytes ``` f=(s,a,t={})=>s.split` `.filter(w=>a.find(e=>w==e)?(t[w]?0:t[w]=1):1).join` ` ``` How it works: ``` f=(s,a,t={})=> // Function declaration; t is an empty object by default s.split` ` // Split the string into an array of words .filter(w=> // Declare a function that, if it returns false, will delete the word a.find(e=>w==e) // Returns undeclared (false) if the word isn't in the list ?(t[w]?0 // If it is in the list and t[w] exists, return 0 (false) :t[w]=1) // Else make t[w] exist and return 1 (true) :1) // If the word isn't in the array, return true (keep the word for sure) .join` ` // Rejoin the string ``` [Answer] # PowerShell v3 or later, 104 bytes ``` Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s ``` At the cost of one byte, it can run in PS 2.0 by replacing `$Matches.0` with `$Matches[0]`. **Long version:** ``` Param($s, $w) $w | Where-Object {$_ -and $s -match ($r = "\b$_(?: |$)")} | # Process each word in the word list, but only if it matches the RegEx (which will be saved in $r). ForEach-Object { # \b - word boundary, followed by the word $_, and either a space or the end of the string ($) $h, $t = $s -split $r # Split the string on all occurrences of the word; the first substring will end up in $h(ead), the rest in $t(ail) (might be an array) $s = "$h$($Matches.0)$(-join $t)" # Create a string from the head, the first match (can't use the word, because of the case), and the joined tail array } $s # Return the result ``` **Usage** Save as Whatever.ps1 and call with the string and the words as arguments. If more than one word needs to be passed, the words need to be wrapped in @(): ``` .\Whatever.ps1 -s "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat" -w @("cat", "mat") ``` **Alternative** without file (can be pasted directly into a PS console): Save the script as ScriptBlock (inside curly braces) in a variable, then call its Invoke() method, or use it with Invoke-Command: ``` $f={Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s} $f.Invoke("A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat")) Invoke-Command -ScriptBlock $f -ArgumentList "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat") ``` [Answer] # Javascript, 150 bytes ``` s=(x, y)=>{let z=new Array(y.length).fill(0);let w=[];for(f of x)(y.includes(f))?(!z[y.indexOf(f)])&&(z[y.indexOf(f)]=1,w.push(f)):w.push(f);return w} ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~153~~ ~~142~~ ~~138~~ 134 bytes ``` import StdEnv,StdLib,Text @ =toUpperCase $s w#s=split" "s =join" "[u\\u<-s&j<-[0..]|and[i<>j\\e<-w,i<-drop 1(elemIndices(@e)(map@s))]] ``` [Try it online!](https://tio.run/##LZDNSsRAEITveYomLpJAsug9kYB6WNiDsHpKcpjNdEzH@WNmslHw2R3HrKfq@pqCrh4EMhWk5otAkIxUIGm09XDy/FldiihHOhev@OmTBmqv34xB@8gcJjsH642rnRHkU0hdUs@aVJzapeuWqnS3c1W2d/t9/80Ub6l6mLsOq3ItqCq51QbuMxQoD4rTgC5rMM8kM43L874PJ8/iFTXsIJ0QBH0gB6/BIuNwXjyszMFIQkS8kp@Ab5t1QosXtBAzq15EzPxziv0i/HMptOmmffgZRsHeXSgPx/D0pZik4WpeBPOjtnIz1yf8Ag "Clean – Try It Online") Defines the function `$ :: String [String] -> String`, pretty much literally doing what the challenge describes. It finds and removes every occurrence after the first, for each target word. [Answer] # Retina, ~~46~~ 37 bytes ``` +i`(^|,)((.+),.*\3.* )\3( |$) $2 .*, ``` -14 bytes thanks to *@Neil*, and +5 bytes for a bug-fix. Input in the format `word1,word2,word3,sentence`, because I'm not sure how to have multi-line input (where the inputs are used differently).. **Explanation:** [Try it online.](https://tio.run/##VZDBboMwDIbveQofOgnaCGmt2L2bpj1AkXappgZwStRApsQUTeq7Mxt2mUSA/Lb/fPkjkhvM8/yUfVzmnbtkXw@dZ1mxy3WxPR@KLeTnQwaPTa42e1VstZrn2o@oqUOQH7AxXMG7O7bgBjCr2IUxoYpoWs193t24SgFEgHokmEwC67xneXLUQbtUpg4j3jECz0xh9DzzpzuPIspOEQ666RCTQLgECQeWGm5g0yFAb4jLSa3VMLAXnwTGpwCJzA9jkmlIdQx35ILcxBqh6MSj/bfYD63Fhtho6QwjNaHnrwWx986iKvWLLoFcjwlKYHVfqsYw3xu/wIYIrWOTyKAguhIyLVS6EhN@DBAmgk@3ALFQIzQhRjn5NTDbcodaIugDZ62kXVd4onWwej9VKljJhiGdJNKumd8Qv7lngKtE9gs) ``` +i`(^|,)((.+),.*\3.* )\3( |$) Main regex to match: +i` Enable case insensitivity (^|,) Either the start of the string, or a comma ( Open capture group 2 ( Open capture group 3 .+ 1 or more characters ) Close capture group 3 , A comma .* 0 or more characters \3 The match of capture group 3 .* 0 or more characters, followed by a space ) Close capture group 2 \3 The match of capture group 2 again ( |$) Followed by either a space, or it's the end of the string $2 And replace everything with: The match of capture group 2 .*, Then get everything before the last comma (the list) and remove it (including the comma itself) ``` [Answer] # [Red](http://www.red-lang.org), 98 bytes ``` func[s w][foreach v w[parse s[thru[any" "v ahead" "]any[to remove[" "v ahead[" "| end]]| skip]]]s] ``` [Try it online!](https://tio.run/##lVLLjhwhDLznK0p8QqTJIbfdnHKNIuWAODC0CWh7YAT0tFbaf5@UySrbm5wiNW1slx9l02S5f5MF1iF@vsetBNuxOxtrEx8Sbtjt1bcu6Haktllfng3MDT6JX3hzNNhR0eRSb2LffHp9gZTFuRf0p3x1znV3v7ZcBiLMA4IfPOvK8hc/Bjr1WuBVgy8LdjZBNVH9L7SBNUGFoc@4D39qjiQ4r5sgtvoTa74xWdYc05jq1kVjVTuGMWrNT8ROnn7BeRvYfUfMs589j4RlevYkTW7SwJi9bitjXu15FTW2OTZrpnQ49pY7upQhJRDJ7KUqt5CkG2toJh8q0uU9JYbVwmrsBX7tFX34Z9IaPugkDtgHInQE0WvDSass7w4rSowS5mQVWbcR6oUyQuusOc4BJe39Le8JI1@k4wRiPp4UwZ/5dMR88XxDfFVYMis08uQ2f497yr@2tMoY0rpuR1XfGjl5Lniu698cX8sxw3dtlp/HkD7wI0/iNJwFobamDB8rZzCHdpbX1zsXozg2rx7j7r8A "Red – Try It Online") ``` f: func [s w][ foreach v w [ ; for each string in the array parse s [ ; parse the input string as follows: thru [ ; keep everything thru: any " " ; 0 or more spaces followed by v ; the current string from the array followed by ahead " " ; look ahead for a space ] any [ to remove [ ; 0 or more: keep to here; then remove: " " ; a space followed by v ; the current string from the array ahead [" " | end]] ; look ahead for a space or the end of the string | skip ; or advance the input by one ] ] ] s ; return the processed string ] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` wüöVËm_Ṗ3+⁰ew ``` Takes a list of strings and a single string as arguments, in this order. Assumes that the list is duplicate-free. [Try it online!](https://tio.run/##yygtzv7/v/zwnsPbwg5358Y/3DnNWPtR44bU8v///0crlWRkFivpKJVn5uQoxf5XCgFyFYAoUaEktbhEIRworABSopCUqpCcX1SUmlyi4JRfkqEA0gASLErNzS9LTVECAA "Husk – Try It Online") ## Explanation ``` wüöVËm_Ṗ3+⁰ew Inputs: list of strings L (explicit, accessed with ⁰), string S (implicit). For example, L = ["CASE","for"], s = "Case for a different case". w Split S on spaces: ["Case","for","a","different","case"] ü Remove duplicates wrt an equality predicate. This means that a function is called on each pair of strings, and if it returns a truthy value, the second one is removed. öVËm_Ṗ3+⁰e The predicate. Arguments are two strings, say A = "Case", B = "case". e Put A and B into a list: ["Case","case"] +⁰ Concatenate with L: ["CASE","for","Case","case"] Ṗ3 All 3-element subsets: [["CASE","for","Case"],["CASE","for","case"], ["CASE","Case","case"],["for","Case","case"]] öV Does any of them satisfy this: Ë All strings are equal m_ after converting each character to lowercase. In this case, ["CASE","Case","case"] satisfies the condition. Result: ["Case","for","a","different"] w Join with spaces, print implicitly. ``` [Answer] # [Min](https://min-lang.org), 125 bytes ``` =a () =b a 1 get =c a 0 get " " split (:d (b d in?) ((c d in?) (d b append #b) unless) (d b append #b) if) foreach b " " join ``` Input is `quot` on stack with input String as first element, and a `quot` of the duplicate strings as second element, i.e. ``` ("this sentence has no matches" ("ten" "cheese")) ``` [Answer] # [Python 3](https://docs.python.org/3/), 168 bytes ``` def f(s,W): s=s.split(" ");c={w:0for w in W} for w in W: for i,v in enumerate(s): if v.lower()==w.lower(): c[w]+=1 if c[w]>1:s.pop(i) return" ".join(s) ``` [Try it online!](https://tio.run/##RY7BCgIhAETvfsWwJ6VFWroZ9ht7iA6xKRmbirorEX27uUJ0mzczDONf6e7soZSb0tA09iMTBFFGHv1sEu3QseMk31nstQvIMBbjh@APAgQNTb9uhrLLU4VrUjRuU4DRWPnssgqUSZl/smWYzvmyk0PTtbjhaRCRe@epYQRBpSXY@oI/nLF1spQv "Python 3 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 120 bytes ``` NR%2{for(;r++<NF;)R[tolower($r)]=1}NR%2==0{for(;i++<NF;$i=$(i+s))while(R[x=tolower($(i+s))])U[x]++?++s:i++;NF-=s}NR%2==0 ``` [Try it online!](https://tio.run/##VVHBSsNAEL3vV8yhQkMQtFAPxiAqFLz0UBQPpYdtMjGL2yzsTowifnt9k6hQyGYnb2Ze3puxw9vxuN6cLb5q9ixMm@I3eC6aEOexvChint@sV0W22UrwYeA4n8VsV15@a19ZXnxpYSodSt1UOnPlbO7ylGVD6zzPN9uP8r93Suyy5@3HLs9v8zxdo61Yr87L9Ed5PO59z0ZaJg2oieGVvHvnmlxHdgLb0Cc2kW1tUOfdG7ISSAHa90KDTdQ47wEPTlqqx8zQcuR3joSeIfQePb84lCo4Egp3VLXMSUW4RIk7QBUKQNoFOlhBOpkpGzpw4U9kfQqUxH5CpthKTAuuOyTUSWNVRasc9ckBHzcNVwKisTL0UoUD7oaU3ruGySzpCkfcgRMtCfBiaSoLgQ94EXZAtQNLhFJSnMxjN04Q6xSOSSennzZG6LORp1GeNk1@1It50giPJeEk9OJGGwD2TFWIUfXeBzgane91cIeADf0A "AWK – Try It Online") The "remove whitespace" part made this a bit more challenging than I first thought. Setting a field to `""`, removes a field, but leaves an extra separator. The TIO link has 28 extra bytes to allow multiple entries. Input is given over 2 lines. The first line is the list of words and the second is the "sentence". Note that "word" and "word," are not considered identical do to the attached punctuation. Having punctuation requirements would likely make this an even more *fun* problem. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~63 61 60~~ 59 bytes ``` ->s,w{w.any?{|i|s.sub! /\b(#{i}\b.*) #{i}\b/i,'\1'}?redo:s} ``` [Try it online!](https://tio.run/##rVPBbtswDL33K7jsoK3wUmxAegiwFd1Ouw/YIclBtulamGMFklwvSPLt2aPsJm6bDC3QILZE8vHxiaJdk673xdf9p28@aTftWNfrm83WbP3YN@k7upqnH95vzG6eji8/Ure7Momaf1a7G8e5nfrdfnZBNBvdUqYDnqrinJY6BPKwbU1aLNJ1Tq11DLOE@Sr0KAF/FtcRoqMF1teXO4F8UmaRyElUKJnSqmEqnL2jytwjzwg8OkvbeFZQpMRU0HI@ocP2tABV5g9CwZJjnVPaBGq1p8JEaa0JJeUx0pbs@J4dIae1TYWc3m8qFqdYUUPciIY3ZFeHPhhPnuvAdQY/uGorDcxK9rE4AlgVbPYPnfhPypDW1qgNZaQrb8kHvUbHgs6CEB@YzqN6rlvEpPuFluOVUjJ/9KA8FwVn8cIFaZuQ2SXWgqRCZYruMsu@jycZX8TSS5pQMEv2NCEEvkwiubzVdeR/CHfBPueH9qhoHeUGZRz6h3ntpyxuJPM5SA0GtuIQ2HmZOzG1c2iWxmjHQTzB@7M@zO7Z3GeJfcFfcmj8NQX2gX6b2DQ4UqbMOied@m7Rv3h5qczr0uKr6KYGQOmHxKKEU2xPiQYc0LAYs84wzpa2pl41IZGvOPeJ3AvMLUSuHCaFVAxPCT8lzibIKbEcETHzMSK6LkXjEXZnO5oBrJgNiy@OWP67gnDOp0dsJ6y3LrjO9/8A) ### A shorter version that's case sensitive and fails ~every 1015 times because of randomness (37 bytes) ``` ->s,w{s.uniq{|i|w.member?(i)?i:rand}} ``` [Answer] # [Python 2](https://docs.python.org/2/), 140 bytes ``` from re import* p='\s?%s' S,A=input() for a in A:S=sub(p%a,lambda s:s.end()==search(p%a,S,flags=I).end()and s.group()or'',S,flags=I) print S ``` [Try it online!](https://tio.run/##Tcq9CoMwEADg3ae4RS4pwaGjEIpj54xth6jRBMwPd3Ho06fQLp2/r7yrz@na2kY5AjkIsWSql65ofPKtZ@yMmnRI5axCdlsmsBASTKPRfM6i9FYdNs6rBR55cGkVUmt2lhb/RaO2w@6s7/KHNq3Aw075LEJmQvwbXaGQKpjWMOVo6@JRPbD6wKiwOq74@gA) Explanation: `re.sub(..)` can take as argument a function instead of replacement string. So here we have some fancy lambda. Function is called for each occurence of pattern and one object is passed to this function - matchobject. This object has information about founded occurence. I'm interested in index of this occurence, that can be retrieved by `start()` or `end()` function. Latter is shorter so it is used. To exclude replacement of first occurence of word, I used another regex search function to get exactly firts one and then compare indexes, using same `end()` Flag `re.I` is short version of `re.IGNORECASES` ]
[Question] [ You are to write a sequence of 10 programs `p1 p2 ... p10` that satisfy the following properties: * `pK` prints `pK+1` for `K` from 1 to 9 * `p10` prints `p10` * When the first `K` programs are concatenated, the resulting program `p1...pK` prints `p1...pK`. * Each program `pK` must be larger in byte size than the previous program `pK-1`. * All programs must be in the same language. * Built-in quining functions (e.g. `Q` in many languages) are allowed. Your score is the sum of the byte counts of the 10 programs. Since there are only ten programs, you must make your codes as short as possible. Good luck. [Answer] ## Seriously, 245 bytes: All ten programs concatenated: ``` Q9ucQc8<WX#dXεj0WX.Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. Q9ucQc8<WX#dXεj0WX. ``` There are invisible characters that become visible when executed, a strange property of byte 7F. The trailing newlines on each program are significant. In fact, Seriously automatically appends newlines to its output whether you want it to or not. This just counts the number of newlines in the output, and as soon as that number exceeds 8, it deletes the last character of output. As such, `p1..pK` will print `p1..pK` for all K>4. ``` Q Push source code. 9uc Push \n Qc Push the number of times it appears in source code. 8< Check if it appears more than 8 times. WX 0WX If so, run the included code. #dX Convert string to list, dequeue and discard a newline. εj Join list back into string. . Print and halt. (Invisible byte here.) ``` [Answer] ## JavaScript (ES6), 985 ``` function f(x){x<0||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(0); function f(x){x<1||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(1); function f(x){x<2||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(2); function f(x){x<3||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(3); function f(x){x<4||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(4); function f(x){x<5||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(5); function f(x){x<6||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(6); function f(x){x<7||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(7); function f(x){x<8||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(8); function f(x){x<9||x>8||f.a||x++;alert(f.a=' '.repeat(x)+`${f}f(${x});`.replace(/\d/,x))}f(9); ``` I misunderstood the rules earlier, so my previous answer was incorrect. This one uses function hoisting instead of variable hoisting, so it doesn't depend on program 10. In fact, I think it's a quine for any combination of two or more concatenated programs. Disclaimer: it's really late right now, so everything above could be completely wrong. [Answer] # Javascript ES6, 1935 bytes Ten programs: ``` a=_=>{t=`a=${a};a()`;setTimeout(_=>alert(t.length>200?t:";".repeat(82)+'a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\\s)+g,"$0$1"):u)};a();'))};a() ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;a=_=>{/* */u=";".repeat(82)+"a="+a+";a();";this.t?t+=u:alert(u.length<198?u.replace((\s)+g,"$0$1"):u)};a(); ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟 2, 214 chars / 334 bytes ``` ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ℹ)đ ⬭ď9)?ℹ):⬭+ℹ) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&code=%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29%0A%20%20%20%20%20%20%20%20%20%E2%84%B9%29%C4%91%20%E2%AC%AD%C4%8F9%29%3F%E2%84%B9%29%3A%E2%AC%AD%2B%E2%84%B9%29)` # Explanation ``` ℹ) // quine function: get source code đ ⬭ď9) // are there 9 spaces in a row anywhere in the source? ?ℹ): // if so, pass the source itself to implicit output ⬭+ℹ) // otherwise, add a leading space to the source and pass to implicit output ``` The program counts the searches for 9 spaces in a row, which is the amount of leading spaces in the 10th program. If it finds a match, then the source code is outputted; otherwise, the source code, lead by a space, is outputted. ]
[Question] [ ## Executive summary Given input `k`, find a partition of integers `1` to `n` into `k` sum-free subsets for the largest `n` you can within 10 minutes. ## Background: Schur numbers A set `A` is *sum-free* if its self-sum `A + A = { x + y | x, y in A}` has no elements in common with it. For every positive integer `k` there is a largest integer `S(k)` such that the set `{1, 2, ..., S(k)}` can be partitioned into `k` sum-free subsets. This number is called the kth [Schur number](http://mathworld.wolfram.com/SchurNumber.html) (OEIS [A045652](http://oeis.org/A045652)). For example, `S(2) = 4`. We can partition `{1, 2, 3, 4}` as `{1, 4}, {2, 3}`, and that is the unique partition into two sum-free subsets, but we can't now add a `5` to either part. ## Challenge Write a **deterministic program** which does the following: * Take a positive integer `k` as input * Write the current Unix timestamp to stdout * Outputs a sequence of partitions of `1` to `n` into `k` sum-free subsets for increasing `n`, following each sequence with the current Unix timestamp. The winner will be the program which prints a partition for the largest `n` within 10 minutes on my computer when given input `5`. Ties will be broken by the quickest time to find a partition for the largest `n`, averaged over three runs: that's why the output should include timestamps. Important details: * I have Ubuntu Precise, so if your language is not supported I will be unable to score it. * I have an Intel Core2 Quad CPU, so if you want to use multithreading there's no point using more than 4 threads. * If you want me to use any particular compiler flags or implementation, document that clearly in your answer. * You shall not special-case your code to handle the input `5`. * You are not required to output every improvement you find. E.g. for input `2` you could output only the partition for `n = 4`. However, if you don't output anything in the first 10 minutes then I will score that as `n = 0`. [Answer] ## Python 3, sort by greatest number, n = ~~92~~ 121 **Thanks to Martin Büttner for a suggestion that unexpectedly improved the maximum `n` reached.** Last output: ``` [2, 3, 11, 12, 29, 30, 38, 39, 83, 84, 92, 93, 110, 111, 119, 120] [1, 4, 10, 13, 28, 31, 37, 40, 82, 85, 91, 94, 109, 112, 118, 121] [5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 86, 87, 88, 89, 90, 113, 114, 115, 116, 117] [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108] [41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81] ``` The algorithm is the same as my previous answer, quoted below: > > There are k bins that have both the numbers in it so far and the numbers that can't go in it anymore. At each depth in the iteration (it's basically a depth-first search), the bin ordering is shuffled and the next number (nextN) is (sequentially) put into the bins that can take it and then goes one step deeper. If there are none, it returns, backing up one step. > > > ...with one exception: the bin ordering is *not* shuffled. Instead, it is *sorted* in such a way that the bins with the *greatest number* come first. This reached `n = 121` in 8 seconds! Code: ``` from copy import deepcopy from random import shuffle, seed from time import clock, time global maxN maxN = 0 clock() def search(k,nextN=1,sets=None): global maxN if clock() > 600: return if nextN == 1: #first iteration sets = [] for i in range(k): sets.append([[],[]]) sets.sort(key=lambda x:max(x[0]or[0]), reverse=True) for i in range(k): if clock() > 600: return if nextN not in sets[i][1]: sets2 = deepcopy(sets) sets2[i][0].append(nextN) sets2[i][1].extend([nextN+j for j in sets2[i][0]]) nextN2 = nextN + 1 if nextN > maxN: maxN = nextN print("New maximum!",maxN) for s in sets2: print(s[0]) print(time()) print() search(k, nextN2, sets2) search(5) ``` [Answer] # Python 3, 121, < 0.001s Improved heuristic thanks to Martin Buttner means we don't even need randomness. Output: ``` 1447152500.9339304 [1, 4, 10, 13, 28, 31, 37, 40, 82, 85, 91, 94, 109, 112, 118, 121] [2, 3, 11, 12, 29, 30, 38, 39, 83, 84, 92, 93, 110, 111, 119, 120] [5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 86, 87, 88, 89, 90, 113, 114, 115, 116, 117] [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108] [41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81] 1447152500.934646 121 ``` Code: ``` from copy import deepcopy from random import seed, randrange from time import clock, time from cProfile import run n = 5 seed(0) def heuristic(bucket): return len(bucket[0]) and bucket[0][-1] def search(): best = 0 next_add = 1 old_add = 0 lists = [[[],set()] for _ in range(n)] print(time()) while clock() < 600 and next_add != old_add: old_add = next_add lists.sort(key=heuristic, reverse=True) for i in range(n): if next_add not in lists[i][1]: lists[i][0].append(next_add) lists[i][1].update([next_add + old for old in lists[i][0]]) if next_add > best: best = next_add next_add += 1 break for l in lists: print(l[0]) print(time(), next_add-1, end='\n\n') search() ``` --- # Python 3, 112 ## Sort by sum of first 2 elements + skew ``` [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79] [7, 8, 9, 10, 11, 12, 13, 27, 28, 29, 30, 31, 32, 33, 80, 81, 82, 83, 84, 85, 86, 100, 101, 102, 103, 104, 105, 106] [3, 4, 14, 19, 21, 26, 36, 37, 87, 92, 94, 99, 109, 110] [2, 5, 16, 17, 20, 23, 24, 35, 38, 89, 90, 96, 97, 108, 111] [1, 6, 15, 18, 22, 25, 34, 39, 88, 91, 93, 95, 98, 107, 112] 1447137688.032085 138.917074 112 ``` I copied El'endia Starman's data structure, which consists of a list of pairs, where the first element of the pair is the elements in that bucket, and the second is the sums of that bucket. I start with the same "track what sums are availible" approach. My sorting heuristic is simply the sum of the smallest two elements in a given list. I also add a small random skew to try different possibilities. Each iteration simply places each the new number in the first avalible bin, similar to random greedy. Once this fails, it simply restarts. ``` from copy import deepcopy from random import seed, randrange from time import clock, time n = 5 seed(0) def skew(): return randrange(9) best = 0 next_add = old_add = 1 while clock() < 600: if next_add == old_add: lists = [[[],[]] for _ in range(n)] next_add = old_add = 1 old_add = next_add lists.sort(key=lambda x:sum(x[0][:2]) + skew(), reverse=True) for i in range(n): if next_add not in lists[i][1]: lists[i][0].append(next_add) lists[i][1].extend([next_add + old for old in lists[i][0]]) if next_add > best: best = next_add for l in lists: print(l[0]) print(time(), clock(), next_add, end='\n\n') next_add += 1 break ``` [Answer] # Java 8, n = 142 144 Last output: ``` @ 0m 31s 0ms n: 144 [9, 12, 17, 20, 22, 23, 28, 30, 33, 38, 41, 59, 62, 65, 67, 70, 72, 73, 75, 78, 80, 83, 86, 91, 107, 115, 117, 122, 123, 125, 128, 133, 136] [3, 8, 15, 24, 25, 26, 31, 35, 45, 47, 54, 58, 64, 68, 81, 87, 98, 100, 110, 114, 119, 120, 121, 130, 137, 142] [5, 13, 16, 19, 27, 36, 39, 42, 48, 50, 51, 94, 95, 97, 103, 106, 109, 112, 118, 126, 129, 132, 138, 140, 141] [2, 6, 11, 14, 34, 37, 44, 53, 56, 61, 69, 76, 79, 84, 89, 92, 101, 104, 108, 111, 124, 131, 134, 139, 143, 144] [1, 4, 7, 10, 18, 21, 29, 32, 40, 43, 46, 49, 52, 55, 57, 60, 63, 66, 71, 74, 77, 82, 85, 88, 90, 93, 96, 99, 102, 105, 113, 116, 127, 135] ``` Performs a seeded random search distributed over 4 threads. When it can't find a partition to fit `n` in it tries to free up space for `n` in one partition at a time by dumping as much as it can out of it into the other partitions. edit: tweaked the algorithm for freeing up space for `n`, also added ability to go back to a previous choice and choose again. note: the output is not strictly deterministic because there are multiple threads involved and they can end up updating the best `n` found so far in jumbled order; the eventual score of 144 is deterministic though and is reached fairly quickly: 30 seconds on my computer. Code is: ``` import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class SumFree { private static int best; public static void main(String[] args) { int k = 5; // Integer.valueOf(args[0]); int numThreadsPeterTaylorCanHandle = 4; long start = System.currentTimeMillis(); long end = start + TimeUnit.MINUTES.toMillis(10); System.out.println(start); Random rand = new Random("Lucky".hashCode()); for (int i = 0; i < numThreadsPeterTaylorCanHandle; i++) { new Thread(() -> search(k, new Random(rand.nextLong()), start, end)).start(); } } private static void search(int k, Random rand, long start, long end) { long now = System.currentTimeMillis(); int localBest = 0; do { // create k empty partitions List<Partition> partitions = new ArrayList<>(); for (int i = 0; i < k; i++) { partitions.add(new Partition()); } Deque<Choice> pastChoices = new ArrayDeque<>(); int bestNThisRun = 0; // try to fill up the partitions as much as we can for (int n = 1;; n++) { // list of partitions that can fit n List<Partition> partitionsForN = new ArrayList<>(k); for (Partition partition : partitions) { if (!partition.sums.contains(n)) { partitionsForN.add(partition); } } // if we can't fit n anywhere then try to free up some space // by rearranging partitions Set<Set<Set<Integer>>> rearrangeAttempts = new HashSet<>(); rearrange: while (partitionsForN.size() == 0 && rearrangeAttempts .add(partitions.stream().map(Partition::getElements).collect(Collectors.toSet()))) { Collections.shuffle(partitions, rand); for (int candidateIndex = 0; candidateIndex < k; candidateIndex++) { // partition we will try to free up Partition candidate = partitions.get(candidateIndex); // try to dump stuff that adds up to n into the other // partitions List<Integer> badElements = new ArrayList<>(candidate.elements.size()); for (int candidateElement : candidate.elements) { if (candidate.elements.contains(n - candidateElement)) { badElements.add(candidateElement); } } for (int i = 0; i < k && !badElements.isEmpty(); i++) { if (i == candidateIndex) { continue; } Partition other = partitions.get(i); for (int j = 0; j < badElements.size(); j++) { int candidateElement = badElements.get(j); if (!other.sums.contains(candidateElement) && !other.elements.contains(candidateElement + candidateElement)) { boolean canFit = true; for (int otherElement : other.elements) { if (other.elements.contains(candidateElement + otherElement)) { canFit = false; break; } } if (canFit) { other.elements.add(candidateElement); for (int otherElement : other.elements) { other.sums.add(candidateElement + otherElement); } candidate.elements.remove((Integer) candidateElement); badElements.remove(j--); } } } } // recompute the sums candidate.sums.clear(); List<Integer> elementList = new ArrayList<>(candidate.elements); int elementListSize = elementList.size(); for (int i = 0; i < elementListSize; i++) { int ithElement = elementList.get(i); for (int j = i; j < elementListSize; j++) { int jthElement = elementList.get(j); candidate.sums.add(ithElement + jthElement); } } // if candidate can now fit n then we can go on if (!candidate.sums.contains(n)) { partitionsForN.add(candidate); break rearrange; } } } // if we still can't fit in n, then go back in time to our last // choice (if it's saved) and this time choose differently if (partitionsForN.size() == 0 && !pastChoices.isEmpty() && bestNThisRun > localBest - localBest / 3) { Choice lastChoice = pastChoices.peek(); partitions = new ArrayList<>(lastChoice.partitions.size()); for (Partition partition : lastChoice.partitions) { partitions.add(new Partition(partition)); } n = lastChoice.n; Partition partition = lastChoice.unchosenPartitions .get(rand.nextInt(lastChoice.unchosenPartitions.size())); lastChoice.unchosenPartitions.remove(partition); partition = partitions.get(lastChoice.partitions.indexOf(partition)); partition.elements.add(n); for (int element : partition.elements) { partition.sums.add(element + n); } if (lastChoice.unchosenPartitions.size() == 0) { pastChoices.pop(); } continue; } if (partitionsForN.size() > 0) { // if we can fit in n somewhere, // pick that somewhere randomly Partition chosenPartition = partitionsForN.get(rand.nextInt(partitionsForN.size())); // if we're making a choice then record it so that we may // return to it later if we get stuck if (partitionsForN.size() > 1) { Choice choice = new Choice(); choice.n = n; for (Partition partition : partitions) { choice.partitions.add(new Partition(partition)); } for (Partition partition : partitionsForN) { if (partition != chosenPartition) { choice.unchosenPartitions.add(choice.partitions.get(partitions.indexOf(partition))); } } pastChoices.push(choice); // only keep 3 choices around if (pastChoices.size() > 3) { pastChoices.removeLast(); } } chosenPartition.elements.add(n); for (int element : chosenPartition.elements) { chosenPartition.sums.add(element + n); } bestNThisRun = Math.max(bestNThisRun, n); } if (bestNThisRun > localBest) { localBest = Math.max(localBest, bestNThisRun); synchronized (SumFree.class) { now = System.currentTimeMillis(); if (bestNThisRun > best) { // sanity check Set<Integer> allElements = new HashSet<>(); for (Partition partition : partitions) { for (int e1 : partition.elements) { if (!allElements.add(e1)) { throw new RuntimeException("Oops!"); } for (int e2 : partition.elements) { if (partition.elements.contains(e1 + e2)) { throw new RuntimeException("Oops!"); } } } } if (allElements.size() != bestNThisRun) { throw new RuntimeException("Oops!" + allElements.size() + "!=" + bestNThisRun); } best = bestNThisRun; System.out.printf("@ %dm %ds %dms\n", TimeUnit.MILLISECONDS.toMinutes(now - start), TimeUnit.MILLISECONDS.toSeconds(now - start) % 60, (now - start) % 1000); System.out.printf("n: %d\n", bestNThisRun); for (Partition partition : partitions) { // print in sorted order since everyone else // seems to to that List<Integer> partitionElementsList = new ArrayList<>(partition.elements); Collections.sort(partitionElementsList); System.out.println(partitionElementsList); } System.out.printf("timestamp: %d\n", now); System.out.println("------------------------------"); } } } if (partitionsForN.size() == 0) { break; } } } while (now < end); } // class representing a partition private static final class Partition { // the elements of this partition Set<Integer> elements = new HashSet<>(); // the sums of the elements of this partition Set<Integer> sums = new HashSet<>(); Partition() { } Partition(Partition toCopy) { elements.addAll(toCopy.elements); sums.addAll(toCopy.sums); } Set<Integer> getElements() { return elements; } } private static final class Choice { int n; List<Partition> partitions = new ArrayList<>(); List<Partition> unchosenPartitions = new ArrayList<>(); } } ``` [Answer] ## C, Random Greedy, n = 91 Just to provide a baseline solution, this iterates over `n`, keeping track of the bins and their sums and adds `n` to a random bin where it doesn't appear as a sum yet. It terminates once `n` appears in all `k` sums, and if the resulting `n` was better than any previous attempt, prints it to STDOUT. The input `k` is provided via a command-line argument. The maximum possible `k` is currently hardcoded to 10 because I was too lazy add dynamic memory allocation, but that could be fixed easily. I guess I could go hunting for a better seed now, but this answer is probably not particularly competitive anyway, so meh. Here is the partition for `n = 91`: ``` 1 5 12 18 22 29 32 35 46 48 56 59 62 69 72 76 79 82 86 89 2 3 10 11 16 17 25 30 43 44 51 52 57 64 71 83 84 90 91 6 8 13 15 24 31 33 38 40 42 49 54 61 63 65 77 81 88 9 14 19 21 27 34 37 45 60 67 70 73 75 78 80 85 4 7 20 23 26 28 36 39 41 47 50 53 55 58 66 68 74 87 ``` And finally, here is the code: ``` #include <stdlib.h> #include <stdio.h> #include <time.h> #define MAX_K 10 #define MAX_N 1024 int main(int argc, char **argv) { if (argc < 2) { printf("Pass in k as a command-line argument"); return 1; } printf("%u\n", (unsigned)time(NULL)); int k = atoi(argv[1]); int sizes[MAX_K]; int bins[MAX_K][MAX_N]; int sums[MAX_K][2*MAX_N]; int selection[MAX_K]; int available_bins; int best = 0; srand(1447101176); while (1) { int i,j; for (i = 0; i < k; ++i) sizes[i] = 0; for (i = 0; i < k*MAX_N; ++i) bins[0][i] = 0; for (i = 0; i < k*MAX_N*2; ++i) sums[0][i] = 0; int n = 1; while (1) { available_bins = 0; for (i = 0; i < k; ++i) if (!sums[i][n]) { selection[available_bins] = i; ++available_bins; } if (!available_bins) break; int bin = selection[rand() % available_bins]; bins[bin][sizes[bin]] = n; ++sizes[bin]; for (i = 0; i < sizes[bin]; ++i) sums[bin][bins[bin][i] + n] = 1; ++n; } if (n > best) { best = n; for (i = 0; i < k; ++i) { for (j = 0; j < sizes[i]; ++j) printf("%d ", bins[i][j]); printf("\n"); } printf("%u\n", (unsigned)time(NULL)); } } return 0; } ``` [Answer] # C++, 135 ``` #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> #include <set> #include <vector> #include <algorithm> using namespace std; vector<vector<int> > subset; vector<int> len, tmp; set<int> sums; bool is_sum_free_with(int elem, int subnr) { sums.clear(); sums.insert(elem+elem); for(int i=0; i<len[subnr]; ++i) { sums.insert(subset[subnr][i]+elem); for(int j=i; j<len[subnr]; ++j) sums.insert(subset[subnr][i]+subset[subnr][j]); } if(sums.find(elem)!=sums.end()) return false; for(int i=0; i<len[subnr]; ++i) if(sums.find(subset[subnr][i])!=sums.end()) return false; return true; } int main() { int k = 0; cin >> k; int start=time(0); cout << start << endl; int allmax=0, cnt=0; srand(0); do { len.clear(); len.resize(k); subset.clear(); subset.resize(k); for(int i=0; i<k; ++i) subset[i].resize((int)pow(3, k)); int n=0, last=0, c, y, g, h, t, max=0; vector<int> p(k); do { ++n; c=-1; for(int i=0; i++<k; ) { y=(last+i)%k; if(is_sum_free_with(n, y)) p[++c]=y; } if(c<0) --n; t=n; while(c<0) { g=rand()%k; h=rand()%len[g]; t=subset[g][h]; for(int l=h; l<len[g]-1; ++l) subset[g][l]=subset[g][l+1]; --len[g]; for(int i=0; i++<k; ) { y=(g+i)%k; if(is_sum_free_with(t, y) && y!=g) p[++c]=y; } if(c<0) subset[g][len[g]++]=t; } c=p[rand()%(c+1)]; subset[c][len[c]++]=t; last=c; if(n>max) { max=n; cnt=0; if(n>allmax) { allmax=n; for(int i=0; i<k; ++i) { tmp.clear(); for(int j=0; j<len[i]; ++j) tmp.push_back(subset[i][j]); sort(tmp.begin(), tmp.end()); for(int j=0; j<len[i]; ++j) cout << tmp[j] << " "; cout << endl; } cout << time(0) << " " << time(0)-start << " " << allmax << endl; } } } while(++cnt<50*n && time(0)-start<600); cnt=0; } while(time(0)-start<600); return 0; } ``` Appends the next n to a randomly chosen subset. If that's not possible it removes random numbers from subsets and appends them to others in the hope that that enables appending n somewhere. I prototyped this in awk, and because it looked promising, I translated it into C++ to speed it up. Using a `std::set` should even speed it up more. ### Output for n=135 (after around 230 seconds on my [old] machine) ``` 2 6 9 10 13 17 24 28 31 35 39 42 43 46 50 57 61 68 75 79 90 94 97 101 105 108 119 123 126 127 130 131 134 38 41 45 48 51 52 55 56 58 59 62 64 65 66 67 69 70 71 72 74 78 80 81 84 85 87 88 91 95 98 5 12 15 16 19 22 23 25 26 29 33 36 73 83 93 100 103 107 110 111 113 114 117 120 121 124 1 4 11 14 21 27 34 37 40 47 53 60 76 86 89 96 99 102 109 112 115 122 125 132 135 3 7 8 18 20 30 32 44 49 54 63 77 82 92 104 106 116 118 128 129 133 ``` I didn't recheck the validity, but it should be alright. [Answer] ## Python 3, random greedy, n = 61 Last output: ``` [5, 9, 13, 20, 24, 30, 32, 34, 42, 46, 49, 57, 61] [8, 12, 14, 23, 25, 44, 45, 47, 54] [2, 6, 7, 19, 22, 27, 35, 36, 39, 40, 52, 53, 56] [3, 10, 15, 16, 17, 29, 37, 51, 55, 59, 60] [1, 4, 11, 18, 21, 26, 28, 31, 33, 38, 41, 43, 48, 50, 58] ``` This uses effectively the same algorithm as [Martin Büttner's](https://codegolf.stackexchange.com/a/63471/12914), but I developed it independently. There are `k` bins that have both the numbers in it so far and the numbers that can't go in it anymore. At each depth in the iteration (it's basically a depth-first search), the bin ordering is shuffled and the next number (`nextN`) is (sequentially) put into the bins that can take it and then goes one step deeper. If there are none, it returns, backing up one step. ``` from copy import deepcopy from random import shuffle, seed from time import clock, time global maxN maxN = 0 clock() seed(0) def search(k,nextN=1,sets=None): global maxN if clock() > 600: return if nextN == 1: #first iteration sets = [] for i in range(k): sets.append([[],[]]) R = list(range(k)) shuffle(R) for i in R: if clock() > 600: return if nextN not in sets[i][1]: sets2 = deepcopy(sets) sets2[i][0].append(nextN) sets2[i][1].extend([nextN+j for j in sets2[i][0]]) nextN2 = nextN + 1 if nextN > maxN: maxN = nextN print("New maximum!",maxN) for s in sets2: print(s[0]) print(time()) print() search(k, nextN2, sets2) search(5) ``` [Answer] # Python, n = 31 ``` import sys k = int(sys.argv[1]) for i in range(k): print ([2**i * (2*j + 1) for j in range(2**(k - i - 1))]) ``` Ok, so it's obvisouly not a winner, but I felt it belonged here anyway. I've taken the liberty not to include timestamps, since it terminates instantaneously, and since it's not a real contender. First, note that the sum of any two odd numbers is even, so we can dump all the odd numbers in the first block. Then, since all the remaining numbers are even, we can divide them by 2. Once again, we can throw all the resulting odd numbers in the second block (after re-multiplying them by 2), divide the remaining numbers by 2 (i.e., by 4 overall), throw the odd ones in the third block (after re-multiplying them by 4), and so on... Or, to put in words you guys understand, we put all the numbers whose least-significant set bit is the first bit in the first block, all the numbers whose least-significant set bit is the second bit in the second block, and so on... For *k* blocks, we run into trouble once we reach *n* = 2*k*, since the least-significant set bit of *n* is the (*k* + 1)-th bit, which doesn't correspond to any block. In other words, this scheme works up to *n* = 2*k* - 1. So, while for *k* = 5 we only get a meager *n = 31*, this number grows exponentially with *k*. It also establishes that *S*(*k*) ≥ 2*k* - 1 (but we can actually find a better lower limit than that quite easily.) For reference, here's the result for *k* = 5: ``` [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31] [2, 6, 10, 14, 18, 22, 26, 30] [4, 12, 20, 28] [8, 24] [16] ``` ]
[Question] [ **Challenge** Given a number of seconds past midnight, output the smallest angle between any two hands on a clock face, using as few bytes as possible. You may assume that the number of seconds is always less than 86400. Angles may be represented in degrees or radians. A reference solution is at: <http://ideone.com/eVdgC0> **Test Cases** (results in degrees) ``` 0 -> 0 60 -> 0.5 600 -> 5 3600 -> 0 5400 -> 45 6930 -> 84.75 50000 -> 63.333 ``` **Clarificarions** * The clock has 3 hands: hours, minutes and seconds. * All hands move continuously, thus hour and minute hands can be found between graduations on the clock face. [Answer] # CJam, ~~36~~ ~~35~~ ~~34~~ ~~32~~ 30 bytes ``` riP*30/_60/_C/]2m*::-:mc:mC$3= ``` The output is in radians. I've verified the solutions for all 86400 possible inputs. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=riP*30%2F_60%2F_C%2F%5D_ff%7B-mcmC%7De_%243%3D&input=6930). ### Idea Since **2π** radians is a full lap, each minute/second interval on the clock is **2π/60 = π/30** radians wide. Thus, dividing the number of seconds by **π/30** yields the position of the second hand. The minute hand moves at one sixtieth of the pace of the second hand, so dividing the result from above by **60** yields the position of the minute hand. Likewise, dividing the last result by **12** yields the position of the hour hand. Note that our three quotient from above are not necessarily in the range **[0,2π).** By calculating all nine possible differences of the hands' angles, we obtain three **0**'s (angular distance between a hand and itself) and the six distances between the different hands. If the closest hands are on a half that does not include **12**, one of the differences from above will be the desired output (mod **2π**). However, at **01:55:30** (for example), the hour hand is at an angle of 1.008 rad (57.75 deg) and the minute hand at an angle of 5.812 rad (333.00 deg) from **12**, giving a difference of 4.804 rad (275.25 deg). By subtracting this result from a full lap, we obtain the angle measured "in the other direction", which equals 1.479 rad (84.75 rad). Now, rather than mapping each angle **θ** in **[0,2π)** and conditionally subtracting the result from **π**, we can simply calculate **arccos(cos(θ))**, since **cos** is both periodic and even, and **arccos** always yields a value in **[0,π)**. Skipping over the three smallest results (all zero), the fourth smallest will be the desired output. ### Code ``` ri e# Read an integer from STDIN. P*30/ e# Multiply by π and divide by 30. _60/ e# Divide a copy by 60. _C/ e# Divide a copy by 12. ]2m* e# Push the array of all pairs of quotients. ::- e# Replace each pair by its difference. :mc e# Apply cosine to each difference. :mC e# Apply arccosine to each cosine. $3= e# Sort and select the fourth smallest element. ``` ## Alternate version (34 bytes) ``` rd6*_60/_C/]360f%2m*::m360X$f-+$6= ``` The output is in degrees and no trigonometric functions are used. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=rd%5B120A6W%23%5Df%2F360f%252m*%3A%3Am360X%24f-%2B%246%3D&input=6930). [Answer] # Mathematica, 40 bytes ``` Min@Abs@Mod[#{11,708,719}/120,360,-180]& ``` Explanation: Let `t` be number of seconds since midnight. The position of each hand is ``` hour: t/120 (mod 360) min: t/10 (mod 360) sec: 6t (mod 360) ``` To calculate the absolute angular distance between `x` degrees and `y` degrees, we can mod `y - x` by 360 into the range `[-180, 180]` and then take the absolute value. (Note that there is no restriction on `x` and `y`.) So this function just calculates the pairwise differences `t/10-t/120`, `6t-t/10`, and `6t-t/120` and does that. [Answer] ## Python, 65 ``` lambda n,l={720,60,1}:6*min((n/x-n/y)%60for x in l for y in{x}^l) ``` The distance traveled by the hour, minute, and second hand, in units of 1/60 of the circle are `h,m,s = n/720, n/60, n/1`. We can take these mod 60 to get their position on the circle from `0` to `60`. If we take their difference mod 60, we get the number of units that one is in front of the other. We take all six possible differences, find the min, then multiply by `6` to rescale to `360` degrees. The two-layer list comprehension first chooses the first hand as represented by `720`, `60`, or `1`, then chooses the other hand out of that set with the first choice removed via set xor. I tested this exhaustively against the reference code. [Answer] # C#, 163 152 bytes This creates every hand twice to count for wrap-around, then loops through every combination and finds the minimum angle between hands. Calculations are performed in 60 divisions, then multiplied by 6 to get degrees. Indented for clarity: ``` float F(int s){ float b=60,c; float[]a={c=s/b/b%12*5,c+b,c=s/b%b,c+b,s%=60,s+b}; for(s=36;s-->0;) b=s%6!=s/6&(c=(c=a[s%6]-a[s/6])<0?-c:c)<b?c:b; return b*6; } ``` Example output: ``` 0 seconds, 00:00:00, smallest angle is 0° 43200 seconds, 12:00:00, smallest angle is 0° 86399 seconds, 23:59:59, smallest angle is 0.09164429° 3330 seconds, 00:55:30, smallest angle is 54.75° 39930 seconds, 11:05:30, smallest angle is 60.25001° 21955 seconds, 06:05:55, smallest angle is 65.49998° 21305 seconds, 05:55:05, smallest angle is 59.50001° 5455 seconds, 01:30:55, smallest angle is 75.45831° 41405 seconds, 11:30:05, smallest angle is 44.95834° ``` [Answer] # TI-BASIC, 17 bytes ``` min(cos⁻¹(cos(ΔList(Ans{6,.1,5!⁻¹,6 ``` Uses Dennis's `arccos(cos(` to normalize distances; however, rather than calculating all pairwise distances, it only calculates the three needed using `ΔList([seconds],[minutes],[hours],[seconds]`. This program expects `Degree` mode and returns the answer in degrees. EDIT: `5!` is one byte shorter than `120`. ]
[Question] [ You should write a program or function which receives a list of distinct integers as input and outputs or returns the number of occurrences of the input numbers in the following upside-down number pyramid. Starting from the original list in every step we create a new one with the maximal values of every pair of adjacent numbers (e.g. `5 1 2 6` becomes `5 2 6`). We stop when there is only one number in the list. The full pyramid for `5 1 2 6` is ``` 5 1 2 6 5 2 6 5 6 6 ``` The resulting number of occurrences are `3 1 2 4` (for `5 1 2 6` respectively). ## Input * A list of one or more integers with no repetition. (e.g. `1 5 1 6` is invalid.) ## Output * A list of positive integers. The `i`th element of the list is the number of occurrences of the `i`th input number in the pyramid. ## Examples Input => Output ``` -5 => 1 8 4 => 2 1 5 9 7 => 1 4 1 1 2 3 9 8 6 7 => 1 2 3 16 3 1 2 6 4 2 1 3 5 => 6 4 2 1 3 5 5 2 9 1 6 0 => 2 1 12 1 4 1 120 5 -60 9 12 1 3 0 1200 => 8 2 1 3 16 1 4 1 9 68 61 92 58 19 84 75 71 46 69 25 56 78 10 89 => 2 1 39 2 1 27 6 5 1 6 1 2 14 1 12 ``` This is code-golf so the shortest entry wins. *Bonus puzzle: can you solve the problem in `O(n*log n)` time?* [Answer] # Python, 81 ``` def f(L): if L:i=L.index(max(L));L=f(L[:i])+[~i*(i-len(L))]+f(L[i+1:]) return L ``` A divide-and-conquer solution. The maximum element `M` seeps all the way down the pyramid, splitting it into a rectangle of `M`'s and two subpyramids. ``` * * * M * * * * M M * * M M M M M M M M M ``` So, the overall result is the output for the left sublist, followed by the area of the rectangle, followed by the output for the right sublist. The input variable `L` is reused to stored the result so that the empty list is mapped to the empty list. The constructs in solution are wordy in Python. Maybe some language with pattern-matching can implement the following pseudocode? ``` def f(L): [] -> [] A+[max(L)]+B -> f(A)+[(len(A)+1)*(len(B)+1)]+f(B) ``` [Answer] # CJam, ~~23~~ 22 bytes Still looking for golfing options. ``` {]_,{)W$ew::e>~}%fe=~} ``` This is a CJam function (sort of). This expects the input numbers on stack and returns the corresponding output counts on the stack too. An example: ``` 5 1 2 6 {]_,{)W$ew::e>~}%fe=~}~ ``` leaves ``` 3 1 2 4 ``` on stack. Pretty sure that this is not in `O(n log n)` time. **Code expansion**: ``` ]_ e# Wrap the input numbers on stack in an array and take a copy ,{ }% e# Take length of the copy and run the loop from 0 to length - 1 )W$ e# Increment the iterating index and copy the parsed input array ew e# Get overlapping slices of iterating index + 1 size ::e> e# Get maximum from each slice ~ e# Unwrap so that there can be finally only 1 level array fe= e# For each of the original array, get the occurrence in this e# final array created by the { ... }% ~ e# Unwrap the count array and leave it on stack ``` Lets take a look at how it works by working up an example of `5 1 2 6` In the second row, `5 1 2 6` becomes `5 2 6` because `5, 2 and 6` are the maximum of `[5 1], [1 2] and [2 6]` respectively. In the third row, it becomes `5 6` because `5 and 6` are maximum of `[5 2] and [2 6]` respectively. This can also be written as maximum of `[5 1 2] and [1 2 6]` respectively. Similarly for last row, `6` is maximum of `[5 1 2 6]`. So we basically create the proper length slices starting from slice of length `1`, which is basically the original numbers, each wrapped in an array, to finally a slice of length `N` for the last row, where `N` is the number of input integers. [Try it online here](http://cjam.aditsu.net/#code=5%201%202%206%20%7B%5D_%2C%7B)W%24ew%3A%3Ae%3E~%7D%25fe%3D~%7D~ed) [Answer] # Pyth, ~~19~~ 17 bytes ``` m/smmeSb.:QhkUQdQ ``` Check out the [Online Demonstration](https://pyth.herokuapp.com/?code=m%2FsmmeSb.%3AQhkUQdQ&input=%5B5%2C+1%2C+2%2C+6%5D&debug=0) or the complete [Test Suite](https://pyth.herokuapp.com/?code=FQ.Qm%2FsmmeSb.%3AQhkUQdQ&input=%22Test+Cases%3A%22%0A%5B-5%5D%0A%5B8%2C+4%5D%0A%5B5%2C+9%2C+7%5D%0A%5B1%2C+2%2C+3%2C+9%2C+8%2C+6%2C+7%5D%0A%5B6%2C+4%2C+2%2C+1%2C+3%2C+5%5D%0A%5B5%2C+2%2C+9%2C+1%2C+6%2C+0%5D%0A%5B120%2C+5%2C+-60%2C+9%2C+12%2C+1%2C+3%2C+0%2C+1200%5D%0A%5B68%2C+61%2C+92%2C+58%2C+19%2C+84%2C+75%2C+71%2C+46%2C+69%2C+25%2C+56%2C+78%2C+10%2C+89%5D&debug=0) (first 4 byte iterate over the examples). This one is a little bit more clever than the naive approach. Each number of the triangle can be represented as the maximal value of a connected subset of `Q`. In the first line it uses the subsets of length 1, the second line of the triangle uses the subsets of length 2, ... ### Explanation ``` m/smmeSb.:QhkUQdQ implicit: Q = input() m UQ map each k in [0, 1, 2, ..., len(Q)-1] to: .:Qhk all subsets of Q of length (k + 1) meSb mapped to their maximum s join these lists together m Q map each d of Q to: / d its count in the computed list ``` To visualize this a little bit. `m.:QhdUQ` and the input `[5, 1, 2, 6]` gives me all possible subsets: ``` [[[5], [1], [2], [6]], [[5, 1], [1, 2], [2, 6]], [[5, 1, 2], [1, 2, 6]], [[5, 1, 2, 6]]] ``` And `mmeSk.:QhdUQ` gives me each of their maxima (which corresponds exactly to the rows in the pyramid): ``` [[5, 1, 2, 6], [5, 2, 6], [5, 6], [6]] ``` # Pyth, ~~23~~ 22 bytes ``` |u&aYGmeSd.:G2QQm/sYdQ ``` This is just the simple "do what you're told" approach. Check out the [Online Demonstration](https://pyth.herokuapp.com/?code=%7Cu%26aYGmeSd.%3AG2QQm%2FsYdQ&input=%5B5%2C+1%2C+2%2C+6%5D&debug=0) or a complete [Test Suite](https://pyth.herokuapp.com/?code=FQ.Q%7Cu%26aYGmeSd.%3AG2QQm%2FsYdQ&input=%22Test+Cases%3A%22%0A%5B-5%5D%0A%5B8%2C+4%5D%0A%5B5%2C+9%2C+7%5D%0A%5B1%2C+2%2C+3%2C+9%2C+8%2C+6%2C+7%5D%0A%5B6%2C+4%2C+2%2C+1%2C+3%2C+5%5D%0A%5B5%2C+2%2C+9%2C+1%2C+6%2C+0%5D%0A%5B120%2C+5%2C+-60%2C+9%2C+12%2C+1%2C+3%2C+0%2C+1200%5D%0A%5B68%2C+61%2C+92%2C+58%2C+19%2C+84%2C+75%2C+71%2C+46%2C+69%2C+25%2C+56%2C+78%2C+10%2C+89%5D&debug=0) (first 4 byte iterate over the examples). ### Explanation `meSd.:G2` maps each pair of `[(G[0], G[1]), (G[1], G[2]), ...]` to the maximal element. `Y` is an empty list, therefore `aYG` appends `G` to the `Y`. `u...QQ` repeatedly applies these two functions (`len(Q)` times) starting with `G = Q` and updating `G` after each run. `m/sYdQ` maps each element of the input list to their count in the flattened `Y` list. [Answer] # Mathematica, 72 bytes ``` Last/@Tally[Join@@NestList[MapThread[Max,{Most@#,Rest@#}]&,#,Length@#]]& ``` [Answer] # Python, 81 ``` lambda L:[sum(x==max(L[i:j])for j in range(len(L)+1)for i in range(j))for x in L] ``` Each entry of the pyramid is the maximum of the sublist atop its upward cone. So, we generate all these sublists, indexed by intervals `[i,j]` with `0 < i < j <= len(L)`, and count how many time each element appears as a maximum. A shorter way to enumerate the subintervals would likely save characters. A single-index parametrization of the pairs `[i,j]` would be a plausible approach. [Answer] # [Pip](https://github.com/dloscutoff/pip), 56 + 1 = 57 bytes Not competing much with the CJam voodoo, I'm afraid. Looks like I need a better algorithm. Run with `-s` flag to get space-delimited output. ``` l:gr:0*,#gg:0*g+1WrFir:{c:r@[a--a]c@($<l@c)}M1,#r++(gi)g ``` Ungolfed, with comments: ``` l:g l = input from cmdline args r:0*,#g r = current row as a list of indices into l g:0*g+1 Repurpose g to store the frequencies Wr Loop until r becomes empty Fir:{c:r@[a--a]c@($<l@c)}M1,#r Redefine r (see below) and loop over each i in it ++(gi) Increment g[i] g Output g ``` The redefinition of `r` each time through works as follows: ``` {c:r@[a--a]c@($<l@c)}M1,#r { }M1,#r Map this function to each a from 1 to len(r) - 1: c:r@[a--a] c is a two-item list containing r[a] and r[a-1] l@c The values of l at the indices contained in c $< Fold/less-than: true iff l[c[0]] < l[c[1]] c@( ) Return c[0] if the former is greater, c[1] otherwise ``` [Answer] # APL (24) ``` {+/⍵∘.={⍵≡⍬:⍵⋄⍵,∇2⌈/⍵}⍵} ``` This is a function that takes a list, like so; ``` {+/⍵∘.={⍵≡⍬:⍵⋄⍵,∇2⌈/⍵}⍵}68 61 92 58 19 84 75 71 46 69 25 56 78 10 89 2 1 39 2 1 27 6 5 1 6 1 2 14 1 12 ``` Explanation: * `{`...`}⍵`: apply the following function to ⍵: + `⍵≡⍬:⍵`: if ⍵ is empty, return ⍵ + `2⌈/⍵`: generate the next list + `⍵,∇`: return ⍵, followed by the result of applying this function to the next list * `⍵∘.=`: compare each element in ⍵ to each element in the result of the function * `+/`: sum the rows (representing elements in ⍵) [Answer] # Haskell, 78 bytes ``` l=length f x=[l[b|b<-concat$take(l x)$iterate(zipWith max=<<tail)x,a==b]|a<-x] ``` Usage: `f [68,61,92,58,19,84,75,71,46,69,25,56,78,10,89]`-> `[2,1,39,2,1,27,6,5,1,6,1,2,14,1,12]`. How it works ``` zipWith max=<<tail -- apply 'max' on neighbor elements of a list iterate (...) x -- repeatedly apply the above max-thing on the -- input list and build a list of the intermediate -- results take (l x) ... -- take the first n elements of the above list -- where n is the length of the input list concat -- concatenate into a single list. Now we have -- all elements of the pyramid in a single list. [ [b|b<-...,a==b] | a<-x] -- for all elements 'a' of the input list make a -- list of 'b's from the pyramid-list where a==b. l -- take the length of each of these lists ``` [Answer] # JavaScript, 109 bytes I think I found an interesting way to go about this, but only after I was done realized the code was too long to compete. Oh well, posting this anyway in case someone sees further golfing potential. ``` f=s=>{t=[];for(i=-1;s.length>++i;){j=k=i;l=r=1;for(;s[--j]<s[i];l++);for(;s[++k]<s[i];r++);t[i]=l*r}return t} ``` I'm making use of the following formula here: > > occurrences of i = (amount of consecutive numbers smaller than i to its left + 1) \* (amount of consecutive numbers smaller than i to its right + 1) > > > This way one doesn't need to actually generate the entire pyramid or subsets of it. (Which is why I initially thought it would run in O(n), but tough luck, we still need inner loops.) [Answer] ## MATLAB : (266 b) > > * the correction of the code costs more bytes, i will struggle how to reduce it later. > > > ``` v=input('');h=numel(v);for i=1:h,f=(v(i)>v(1));l=(v(i)>v(h));for j=h-1:-1:i+1,l=(v(i)>v(j))*(1+l);end,if(i>1),l=l+(v(i)>v(i-1))*l;end;for j=2:i-1,f=(v(i)>v(j))*(1+f);end,if(i<h),f=f+(v(i)>v(i+1))*f;end;s=f+l+1;if(i<h&&i>1),s=s-((v(i)>v(i+1))*(v(i)>v(i-1)));end;s end ``` ## INPUT a vector must be of the form [a b c d ...] * example: [2 4 7 11 3] ## OUTPUT pattern occurences. ``` s = 1 s = 2 s = 3 s = 8 s = 1 ``` ## EXPLANATION: if [a b c d] is an input the program calculates result g h i j as g= (a>b) + (a>b)*(a>c) + (a>b)*(a>c)\*(a>d) = (a>b)(1+(a>c)(1+(a>c) ))) h= (b>a) + (b>c) + (b>a)*(b>c) + (b>c)*(b>d)+(b>a)*(b>c)*(b>d) = ... 'simplified' i= (c>b) + (c>d) + (c>b)*(c>d) + (c>b)*(c>a)+(c>d)*(c>b)*(c>a) = .. j= (d>c) + (d>c)*(d>b) + (d>c)*(d>b)\*(d>a) = ... [Answer] # J (49) I suppose there is some room for improvement... ``` [:+/~.="1 0[:;([:i.#)<@:(4 :'(}:>.}.)^:x y')"0 1] ``` ]
[Question] [ ## The Task * You are given a mutable string that matches `[a-z]+( [a-z]+)*`. * You must mutate it into the string which contains the same words, but in reverse order, so that "hello there everyone" becomes "everyone there hello". * You are not permitted to use more than a constant amount of additional memory (so no copying the entire string or any whole word into a buffer you just allocated). * There are no time constraints. Being hopelessly inefficient will not harm your score. * If your language of choice does not permit mutation of strings, arrays of characters are an acceptable substitute. ## Your Score * Your score is counted purely on the number of assigments you make to string elements (small scores are best). If you use a library function that writes to the string, its writes also count. * Suppose the number of assignments you need for input *s* is *n(s)*. Then your score is the maximum (pedantically, supremum) over all inputs *s* (matching the regex specified above) of *n(s)/length(s)*. If you cannot calculate this precisely, you can use the lowest upper bound that you can prove. * You can break a tie if you can prove that your algorithm uses asymptotically fewer assignments (this can happen even if you have the same score, see below). If you can't do this, you can break a tie by showing that you use less additional memory. However, the first tie-break condition always takes precedence. * For some inputs every character needs to change, so it is not possible to score less than 1. * I can think of a simple algorithm with score 2 (but I'm not entering it). ### Notes on suprema and ties * A supremum of a set of numbers is the smallest number that is not smaller than any of them. This is much like the maximum of a set, except that some infinite sets like {2/3, 3/4, 4/5, 5/6, ...} have no single maximum element, but will still have a supremum, in this case 1. * If you manage to "save" only a constant number of assignments over my algorithm of score 2 (say), your score will still be 2, because you'll get arbitrarily close to 2 the larger your input gets. However, you win on the tie-break if it comes to that. [Answer] ## Perl, score 1.3̅ For each non-space character one assignment is performed, and for each space character two assignments. ~~Because space characters cannot amount to more than one half the total number of characters, the worst case score is *1.5*.~~ The algorithm hasn't changed, but I can prove a lower upper bound. Let us make two observations: 1. Spaces directly across from spaces do not need to be swapped. 2. Single character words directly across from spaces are not swapped during the main phase, but only once at the end. It can then be seen that the theoretical 'worst case' with asymptotically 1/2 spaces is not worst case at all: `ab c d e f g h i ...` ``` $ echo ab c d e f g h i j k l m n o p q r s t u v w x y z|perl reverse-inplace.pl z y x w v u t s r q p o n m l k j i h g f e d c ab swaps: 51; len: 50 ratio: 1.02 ``` In fact, it's quite a good case. In order to prevent observation one and two above, each one-character word would need to be repositioned into the middle of a word three or more characters long. This would suggest a worst case containing asymptotically 1/3 spaces: `a bcd a bcd a ... bc` ``` $ echo a bcd a bcd a bcd a bcd a bcd a bc|perl reverse-inplace.pl bc a bcd a bcd a bcd a bcd a bcd a swaps: 45; len: 34 ratio: 1.32352941176471 ``` Or equivalently, only two-character words: `a bc de fg hi jk ...` ``` $ echo a bc de fg hi jk lm no pq rs tu vx xy|perl reverse-inplace.pl xy vx tu rs pq no lm jk hi fg de bc a swaps: 49; len: 37 ratio: 1.32432432432432 ``` Because the worst case contains asymptotically 1/3 spaces, the worst case score becomes *1.3̅*. ``` #!perl -l use warnings; $words = <>; chomp($words); $len = length($words); $words .= ' '; $spaces = 0; # iterate over the string, count the spaces $spaces++ while $words =~ m/ /g; $origin = 0; $o = vec($words, $origin, 8); $cycle_begin = $origin; $swaps = 0; # this possibly terinates one iteration early, # if the last char is a one-cycle (i.e. moves to its current location) # one-cycles previous to the last are iterated, but not swapped. while ($i++ < $len - $spaces || !$was_cycle) { $w_start = rindex($words, ' ', $origin); $w_end = index($words, ' ', $origin); $pos = ($origin - $w_start) - 1; $target = $len - ($w_end - $pos); $t = vec($words, $target, 8); if ($t == 32) { $target = $len - $target - 1; $t = vec($words, $target, 8); } # char is already correct, possibly a one-cycle if ($t != $o) { $swaps += 1; vec($words, $target, 8) = $o; } $origin = $target; $o = $t; if ($origin == $cycle_begin) { if ($i < $len - $spaces) { # backtrack through everything we've done up to this point # to find the next unswapped char ...seriously. $origin += 1; if (vec($words, $origin, 8) == 32) { $origin += 1; } $bt_origin = 0; $bt_cycle_begin = 0; while ($bt_cycle_begin < $origin) { $w_start = rindex($words, ' ', $bt_origin); $w_end = index($words, ' ', $bt_origin); $pos = ($bt_origin - $w_start) - 1; $target = $len - ($w_end - $pos); $t = vec($words, $target, 8); if ($t == 32) { $target = $len - $target - 1; $t = vec($words, $target, 8); } if ($target == $bt_cycle_begin) { $bt_origin = ++$bt_cycle_begin; if (vec($words, $bt_origin, 8) == 32) { $bt_origin = ++$bt_cycle_begin; } } else { $bt_origin = $target; } if ($target == $origin) { $origin += 1; if (vec($words, $origin, 8) == 32) { $origin += 1; } $bt_origin = $bt_cycle_begin = 0; } } } $cycle_begin = $origin; $o = vec($words, $origin, 8); $was_cycle = 1; } else { $was_cycle = 0; } } for $i (0..$len/2-1) { $mirror = $len - $i - 1; $o = vec($words, $i, 8); $m = vec($words, $mirror, 8); # if exactly one is a space... if (($o == 32) ^ ($m == 32)) { $swaps += 2; vec($words, $mirror, 8) = $o; vec($words, $i, 8) = $m; } } chop($words); print $words; print "swaps: $swaps; len: $len"; print 'ratio: ', $swaps/$len; ``` ***Edit:** Added a swap counter, and the ratio.* Input is taken from stdin. Sample usage: ``` $ echo where in the world is carmen sandiego|perl reverse-inplace.pl sandiego carmen is world the in where swaps: 35; len: 37 ratio: 0.945945945945946 ``` --- **Method** To begin, the first character of the string is moved to its final destination. The character just replaced is then moved to its destination, etc. This continues until one of two conditions is met: 1. **The character should be swapped with a space.** When this occurs, the character is *not* swapped with the space, but rather into the mirror position of the space. The algorithm continues from that position. 2. **A cycle has been reached.** When the target returns to the initial starting position of the current cycle, the next unswapped character (or rather, any unswapped character would do) needs to be found. To do this under constant memory constraints, all swaps that have been made up to this point are back-tracked. After this phase, each non-space character has been moved at most once. To finish, all space characters are swapped with the characters at their mirror positions, requiring two assignment operations per space. [Answer] ### Ruby, score 2 As a starter a very basic algorithm. It first reverses the whole string and then reverses each word in the string again. In the worst case (one word, even number of characters) the score becomes 2. ``` def revstring(s, a, b) while a<b h = s[a] s[a] = s[b] s[b] = h a += 1 b -= 1 end s end def revwords(s) revstring(s, 0, s.length-1) a = 0 while a<s.length b = a+1 b += 1 while b<s.length and s[b]!=" " revstring(s, a, b-1) a = b+1 end s end ``` Usage: ``` > revwords("hello there everyone") "everyone there hello" ``` [Answer] **C++: Score 2** ``` #include<iostream> #include<algorithm> void rev(std::string& s) { std::reverse(s.begin(),s.end()); std::string::iterator i=s.begin(),j=s.begin(); while(i!=s.end()) { while(i!=s.end()&&(*i)==' ') i++; j=i; while(i!=s.end()&&(*i)!=' ') i++; std::reverse(j,i); } } int main() { std::string s; getline(std::cin,s); rev(s); std::cout<<s; } ``` [Answer] ## Python, Score: ~~2~~ ~~1.5~~ 1.25 This is the **direct** combination between primo's answer and my answer. So credits to him also! The proof is still in progress, but here is the code to play with! If you can find a counter example of score greater than 1.25 (or if there is a bug), let me know! Currently the worst case is: ``` a a ... a a dcb...cbd ``` where there are exactly **n** of each the letters "a", "b", "c", and " " (space), and exactly two "d"s. The length of the string is **4n+2** and the number of assignments is **5n+2**, giving a score of **5/4 = 1.25**. The algorithm works in two steps: 1. Find `k` such that `string[k]` and `string[n-1-k]` are word boundaries 2. Run any word reversing algorithm on `string[:k]+string[n-1-k:]` (i.e., concatenation of first `k` and last `k` chars) with small modification. where `n` is the length of the string. The improvement this algorithm gives comes from the "small modification" in Step 2. It's basically the knowledge that in the concatenated string, the characters at position `k` and `k+1` are word boundaries (which means they are spaces or first/last character in a word), and so we can directly replace the characters in position `k` and `k+1` with the corresponding character in the final string, saving a few assignments. **This removes the worst case from the host word-reversal algorithm** There are cases where we can't actually find such `k`, in that case, we just run the "any word reversal algorithm" on the whole string. The code is long to handle these four cases on running the word reversal algorithm on the "concatenated" string: 1. When `k` is not found (`f_long = -2`) 2. When `string[k] != ' ' and string[n-1-k] != ' '` (`f_long = 0`) 3. When `string[k] != ' ' and string[n-1-k] == ' '` (`f_long = 1`) 4. When `string[k] == ' ' and string[n-1-k] != ' '` (`f_long = -1`) I'm sure the code can be shortened. Currently it's long because I didn't have clear picture of the whole algorithm in the beginning. I'm sure one can design it to be represented in a shorter code =) Sample run (first is mine, second is primo's): ``` Enter string: a bc def ghij "ghij def bc a": 9, 13, 0.692 "ghij def bc a": 9, 13, 0.692 Enter string: ab c d e f g h i j k l m n o p q r s t u v w x y z "z y x w v u t s r q p o n m l k j i h g f e d c ab": 50, 50, 1.000 "z y x w v u t s r q p o n m l k j i h g f e d c ab": 51, 50, 1.020 Enter string: a b c d e f g hijklmnopqrstuvwx "hijklmnopqrstuvwx g f e d c b a": 38, 31, 1.226 "hijklmnopqrstuvwx g f e d c b a": 38, 31, 1.226 Enter string: a bc de fg hi jk lm no pq rs tu vw xy zc "zc xy vw tu rs pq no lm jk hi fg de bc a": 46, 40, 1.150 "zc xy vw tu rs pq no lm jk hi fg de bc a": 53, 40, 1.325 Enter string: a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a dcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbd "dcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbd a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a": 502, 402, 1.249 "dcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbd a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a": 502, 402, 1.249 ``` You can see that the score is almost the same, except for the worst case of the host word-reversal algorithm in the third example, for which my approach yields score of less than 1.25 ``` DEBUG = False def find_new_idx(string, pos, char, f_start, f_end, b_start, b_end, f_long): if DEBUG: print 'Finding new idx for s[%d] (%s)' % (pos, char) if f_long == 0: f_limit = f_end-1 b_limit = b_start elif f_long == 1: f_limit = f_end-1 b_limit = b_start+1 elif f_long == -1: f_limit = f_end-2 b_limit = b_start elif f_long == -2: f_limit = f_end b_limit = b_start if (f_start <= pos < f_limit or b_limit < pos < b_end) and char == ' ': word_start = pos word_end = pos+1 else: if pos < f_limit+1: word_start = f_start if DEBUG: print 'Assigned word_start from f_start (%d)' % f_start elif pos == f_limit+1: word_start = f_limit+1 if DEBUG: print 'Assigned word_start from f_limit+1 (%d)' % (f_limit+1) elif b_limit <= pos: word_start = b_limit if DEBUG: print 'Assigned word_start from b_limit (%d)' % b_limit elif b_limit-1 == pos: word_start = b_limit-1 if DEBUG: print 'Assigned word_start from b_limit-1 (%d)' % (b_limit-1) i = pos while f_start <= i <= f_limit or 0 < b_limit <= i < b_end: if i==f_limit or i==b_limit: cur_char = 'a' elif i!=pos: cur_char = string[i] else: cur_char = char if cur_char == ' ': word_start = i+1 if DEBUG: print 'Assigned word_start from loop' break i -= 1 if b_limit <= pos: word_end = b_end if DEBUG: print 'Assigned word_end from b_end (%d)' % b_end elif b_limit-1 == pos: word_end = b_limit if DEBUG: print 'Assigned word_end from b_limit (%d)' % (b_limit) elif pos < f_limit+1: word_end = f_limit+1 if DEBUG: print 'Assigned word_end from f_limit+1 (%d)' % (f_limit+1) elif pos == f_limit+1: word_end = f_limit+2 if DEBUG: print 'Assigned word_end from f_limit+2 (%d)' % (f_limit+2) i = pos while f_start <= i <= f_limit or 0 < b_limit <= i < b_end: if i==f_limit or i==b_limit: cur_char = 'a' elif i!=pos: cur_char = string[i] else: cur_char = char if cur_char == ' ': word_end = i if DEBUG: print 'Assigned word_end from loop' break i += 1 if DEBUG: print 'start, end: %d, %d' % (word_start, word_end) word_len = word_end - word_start offset = word_start-f_start result = (b_end-offset-(word_end-pos)) % b_end if string[result] == ' ' and (b_start == -1 or result not in {f_end-1, b_start}): return len(string)-1-result else: return result def process_loop(string, start_idx, f_start, f_end, b_start, b_end=-1, f_long=-2, dry_run=False): assignments = 0 pos = start_idx tmp = string[pos] processed_something = False count = 0 while pos != start_idx or not processed_something: count += 1 if DEBUG and count > 20: print '>>>>>Break!<<<<<' break new_pos = find_new_idx(string, pos, tmp, f_start, f_end, b_start, b_end, f_long) if DEBUG: if dry_run: print 'Test:', else: print '\t', print 'New idx for s[%d] (%s): %d (%s)' % (pos, tmp, new_pos, string[new_pos]) if dry_run: tmp = string[new_pos] if new_pos == dry_run: return True elif pos == new_pos: break elif tmp == string[new_pos]: pass else: tmp, string[new_pos] = string[new_pos], tmp assignments += 1 pos = new_pos processed_something = True if dry_run: return False return assignments def reverse(string, f_start, f_end, b_start, b_end=-1, f_long=-2): if DEBUG: print 'reverse: %d %d %d %d %d' % (f_start, f_end, b_start, b_end, f_long) if DEBUG: print if DEBUG: print ''.join(string) assignments = 0 n = len(string) if b_start == -1: for i in range(f_start, f_end): if string[i] == ' ': continue if DEBUG: print 'Starting from i=%d' % i if any(process_loop(string, j, f_start, f_end, -1, f_end, dry_run=i) for j in range(f_start, i) if string[j] != ' '): continue if DEBUG: print print 'Finished test' assignments += process_loop(string, i, f_start, f_end, -1, f_end) if DEBUG: print if DEBUG: print ''.join(string) for i in range(f_start, (f_start+f_end-1)/2): if (string[i] == ' ' and string[n-1-i] != ' ') or (string[i] != ' ' and string[n-1-i] == ' '): string[i], string[n-1-i] = string[n-1-i], string[i] assignments += 2 else: for i in range(f_start, f_end)+range(b_start, b_end): if string[i] == ' ' and i not in {f_end-1, b_start}: continue if DEBUG: print 'Starting from i=%d' % i if any(process_loop(string, j, f_start, f_end, b_start, b_end, f_long, i) for j in range(f_start, f_end)+range(b_start, b_end) if j<i and (string[j] != ' ' or j in {f_end-1, b_start})): continue assignments += process_loop(string, i, f_start, f_end, b_start, b_end, f_long) if DEBUG: print if DEBUG: print ''.join(string) for i in range(f_start, f_end-1): if (string[i] == ' ' and string[n-1-i] != ' ') or (string[i] != ' ' and string[n-1-i] == ' '): string[i], string[n-1-i] = string[n-1-i], string[i] assignments += 2 return assignments class SuperList(list): def index(self, value, start_idx=0): try: return self[:].index(value, start_idx) except ValueError: return -1 def rindex(self, value, end_idx=-1): end_idx = end_idx % (len(self)+1) try: result = end_idx - self[end_idx-1::-1].index(value) - 1 except ValueError: return -1 return result def min_reverse(string): assignments = 0 lower = 0 upper = len(string) while lower < upper: front = string.index(' ', lower) % (upper+1) back = string.rindex(' ', upper) while abs(front-lower - (upper-1-back)) > 1 and front < back: if front-lower < (upper-1-back): front = string.index(' ', front+1) % (upper+1) else: back = string.rindex(' ', back) if DEBUG: print lower, front, back, upper if front > back: break if DEBUG: print lower, front, back, upper if abs(front-lower - (upper-1-back)) > 1: assignments += reverse(string, lower, upper, -1) lower = upper elif front-lower < (upper-1-back): assignments += reverse(string, lower, front+1, back+1, upper, -1) lower = front+1 upper = back+1 elif front-lower > (upper-1-back): assignments += reverse(string, lower, front, back, upper, 1) lower = front upper = back else: assignments += reverse(string, lower, front, back+1, upper, 0) lower = front+1 upper = back return assignments def minier_find_new_idx(string, pos, char): n = len(string) try: word_start = pos - next(i for i, char in enumerate(string[pos::-1]) if char == ' ') + 1 except: word_start = 0 try: word_end = pos + next(i for i, char in enumerate(string[pos:]) if char == ' ') except: word_end = n word_len = word_end - word_start offset = word_start result = (n-offset-(word_end-pos))%n if string[result] == ' ': return n-result-1 else: return result def minier_process_loop(string, start_idx, dry_run=False): assignments = 0 pos = start_idx tmp = string[pos] processed_something = False while pos != start_idx or not processed_something: new_pos = minier_find_new_idx(string, pos, tmp) #print 'New idx for s[%d] (%s): %d (%s)' % (pos, tmp, new_pos, string[new_pos]) if pos == new_pos: break elif dry_run: tmp = string[new_pos] if new_pos == dry_run: return True elif tmp == string[new_pos]: pass else: tmp, string[new_pos] = string[new_pos], tmp assignments += 1 pos = new_pos processed_something = True if dry_run: return False return assignments def minier_reverse(string): assignments = 0 for i in range(len(string)): if string[i] == ' ': continue if any(minier_process_loop(string, j, dry_run=i) for j in range(i) if string[j] != ' '): continue assignments += minier_process_loop(string, i) n = len(string) for i in range(n/2): if string[i] == ' ' and string[n-i-1] != ' ': string[i], string[n-i-1] = string[n-i-1], string[i] assignments += 2 elif string[n-i-1] == ' ' and string[i] != ' ': string[i], string[n-i-1] = string[n-i-1], string[i] assignments += 2 return assignments def main(): while True: str_input = raw_input('Enter string: ') string = SuperList(str_input) result = min_reverse(string) n = len(string) print '"%s": %d, %d, %.3f' % (''.join(string), result, n, 1.0*result/n) string = SuperList(str_input) result2 = minier_reverse(string) print '"%s": %d, %d, %.3f' % (''.join(string), result2, n, 1.0*result2/n) if __name__ == '__main__': main() ``` --- ## Python, Score: 1.5 The exact number of assignments can be approximated by the formula: ``` n <= 1.5*length(string) ``` with the worst case being: ``` a b c d e f g h i jklmnopqrstuvwxyzzz ``` with 55 assignments on string with length 37. The idea is similar to my previous one, it's just that in this version I tried to find prefix and suffix at word boundaries with length difference at most 1. Then I run my previous algorithm on that prefix and suffix (imagine them as being concatenated). Then continue on unprocessed part. For example, for the previous worst case: ``` ab| a b| c ``` we will first do word reversal on "ab" and " c" (4 assignments) to be: ``` c | a b|ab ``` We know that at the boundary it used to be space (there are many cases to be handled, but you can do that), so we don't need to encode the space at the boundary, this is the main improvement from the previous algorithm. Then finally we run on the middle four characters to get: ``` c b a ab ``` in total 8 assignments, the optimal for this case, since all 8 characters changed. This eliminates the worst case in previous algorithm since the worst case in previous algorithm is eliminated. See some sample run (and comparison with @primo's answer - his is the second line): ``` Enter string: i can do anything "anything do can i": 20, 17 "anything do can i": 17, 17 Enter string: a b c d e f ghijklmnopqrs "ghijklmnopqrs f e d c b a": 37, 25 "ghijklmnopqrs f e d c b a": 31, 25 Enter string: a b c d e f ghijklmnopqrst "ghijklmnopqrst f e d c b a": 38, 26 "ghijklmnopqrst f e d c b a": 32, 26 Enter string: a b c d e f g h i jklmnozzzzzzzzzzzzzzzzz "jklmnozzzzzzzzzzzzzzzzz i h g f e d c b a": 59, 41 "jklmnozzzzzzzzzzzzzzzzz i h g f e d c b a": 45, 41 Enter string: a b c d e f g h i jklmnopqrstuvwxyzzz "jklmnopqrstuvwxyzzz i h g f e d c b a": 55, 37 "jklmnopqrstuvwxyzzz i h g f e d c b a": 45, 37 Enter string: ab a b a b a b a b a b a b a c "c a b a b a b a b a b a b a ab": 30, 30 "c a b a b a b a b a b a b a ab": 31, 30 Enter string: ab a b a b a b a b a b a b a b c "c b a b a b a b a b a b a b a ab": 32, 32 "c b a b a b a b a b a b a b a ab": 33, 32 Enter string: abc d abc "abc d abc": 0, 9 "abc d abc": 0, 9 Enter string: abc d c a "a c d abc": 6, 9 "a c d abc": 4, 9 Enter string: abc a b a b a b a b a b a b c "c b a b a b a b a b a b a abc": 7, 29 "c b a b a b a b a b a b a abc": 5, 29 ``` primo's answer is generally better, although in some cases I can have 1 point advantage =) Also his code is much shorter than mine, haha. ``` DEBUG = False def find_new_idx(string, pos, char, f_start, f_end, b_start, b_end, f_long): if DEBUG: print 'Finding new idx for s[%d] (%s)' % (pos, char) if f_long == 0: f_limit = f_end-1 b_limit = b_start elif f_long == 1: f_limit = f_end-1 b_limit = b_start+1 elif f_long == -1: f_limit = f_end-2 b_limit = b_start elif f_long == -2: f_limit = f_end b_limit = b_start if (f_start <= pos < f_limit or b_limit < pos < b_end) and (char == ' ' or char.isupper()): word_start = pos word_end = pos+1 else: if pos < f_limit+1: word_start = f_start if DEBUG: print 'Assigned word_start from f_start (%d)' % f_start elif pos == f_limit+1: word_start = f_limit+1 if DEBUG: print 'Assigned word_start from f_limit+1 (%d)' % (f_limit+1) elif b_limit <= pos: word_start = b_limit if DEBUG: print 'Assigned word_start from b_limit (%d)' % b_limit elif b_limit-1 == pos: word_start = b_limit-1 if DEBUG: print 'Assigned word_start from b_limit-1 (%d)' % (b_limit-1) i = pos if not (i < f_limit and b_limit < i): i -= 1 while f_start <= i < f_limit or 0 < b_limit < i < b_end: if i!=pos: cur_char = string[i] else: cur_char = char if cur_char == ' ' or cur_char.isupper(): word_start = i+1 if DEBUG: print 'Assigned word_start from loop' break i -= 1 if b_limit <= pos: word_end = b_end if DEBUG: print 'Assigned word_end from b_end (%d)' % b_end elif b_limit-1 == pos: word_end = b_limit if DEBUG: print 'Assigned word_end from b_limit (%d)' % (b_limit) elif pos < f_limit+1: word_end = f_limit+1 if DEBUG: print 'Assigned word_end from f_limit+1 (%d)' % (f_limit+1) elif pos == f_limit+1: word_end = f_limit+2 if DEBUG: print 'Assigned word_end from f_limit+2 (%d)' % (f_limit+2) i = pos if not (i < f_limit and b_limit < i): i += 1 while f_start <= i < f_limit or 0 < b_limit < i < b_end: if i!=pos: cur_char = string[i] else: cur_char = char if cur_char == ' ' or cur_char.isupper(): word_end = i if DEBUG: print 'Assigned word_end from loop' break i += 1 if DEBUG: print 'start, end: %d, %d' % (word_start, word_end) word_len = word_end - word_start offset = word_start-f_start return (b_end-offset-(word_end-pos)) % b_end def process_loop(string, start_idx, f_start, f_end, b_start, b_end=-1, f_long=-2, dry_run=False): assignments = 0 pos = start_idx tmp = string[pos] processed_something = False count = 0 while pos != start_idx or not processed_something: count += 1 if count > 20: if DEBUG: print 'Break!' break new_pos = find_new_idx(string, pos, tmp, f_start, f_end, b_start, b_end, f_long) #if dry_run: # if DEBUG: print 'Test:', if DEBUG: print 'New idx for s[%d] (%s): %d (%s)' % (pos, tmp, new_pos, string[new_pos]) if pos == new_pos: break elif dry_run: tmp = string[new_pos] if new_pos == dry_run: return True elif tmp == string[new_pos]: pass elif tmp == ' ': if b_start!=-1 and new_pos in {f_end-1, b_start}: tmp, string[new_pos] = string[new_pos], tmp else: tmp, string[new_pos] = string[new_pos], '@' assignments += 1 elif string[new_pos] == ' ': if b_start!=-1 and new_pos in {f_end-1, b_start}: tmp, string[new_pos] = string[new_pos], tmp else: tmp, string[new_pos] = string[new_pos], tmp.upper() assignments += 1 else: tmp, string[new_pos] = string[new_pos], tmp assignments += 1 pos = new_pos processed_something = True if dry_run: return False return assignments def reverse(string, f_start, f_end, b_start, b_end=-1, f_long=-2): if DEBUG: print 'reverse: %d %d %d %d %d' % (f_start, f_end, b_start, b_end, f_long) if DEBUG: print if DEBUG: print ''.join(string) assignments = 0 if b_start == -1: for i in range(f_start, (f_start+f_end)/2): if DEBUG: print 'Starting from i=%d' % i if any(process_loop(string, j, f_start, f_end, -1, f_end, dry_run=i) for j in range(f_start, i)): continue assignments += process_loop(string, i, f_start, f_end, -1, f_end) if DEBUG: print if DEBUG: print ''.join(string) else: for i in range(f_start, f_end): if DEBUG: print 'Starting from i=%d' % i if any(process_loop(string, j, f_start, f_end, b_start, b_end, f_long, i) for j in range(f_start, i)): continue assignments += process_loop(string, i, f_start, f_end, b_start, b_end, f_long) if DEBUG: print if DEBUG: print ''.join(string) for i in range(len(string)): if string[i] == '@': string[i] = ' ' assignments += 1 if string[i].isupper(): string[i] = string[i].lower() assignments += 1 return assignments class SuperList(list): def index(self, value, start_idx=0): try: return self[:].index(value, start_idx) except ValueError: return -1 def rindex(self, value, end_idx=-1): end_idx = end_idx % (len(self)+1) try: result = end_idx - self[end_idx-1::-1].index(value) - 1 except ValueError: return -1 return result def min_reverse(string): # My algorithm assignments = 0 lower = 0 upper = len(string) while lower < upper: front = string.index(' ', lower) % (upper+1) back = string.rindex(' ', upper) while abs(front-lower - (upper-1-back)) > 1 and front < back: if front-lower < (upper-1-back): front = string.index(' ', front+1) % (upper+1) else: back = string.rindex(' ', back) if DEBUG: print lower, front, back, upper if front > back: break if DEBUG: print lower, front, back, upper if abs(front-lower - (upper-1-back)) > 1: assignments += reverse(string, lower, upper, -1) lower = upper elif front-lower < (upper-1-back): assignments += reverse(string, lower, front+1, back+1, upper, -1) lower = front+1 upper = back+1 elif front-lower > (upper-1-back): assignments += reverse(string, lower, front, back, upper, 1) lower = front upper = back else: assignments += reverse(string, lower, front, back+1, upper, 0) lower = front+1 upper = back return assignments def minier_find_new_idx(string, pos, char): n = len(string) try: word_start = pos - next(i for i, char in enumerate(string[pos::-1]) if char == ' ') + 1 except: word_start = 0 try: word_end = pos + next(i for i, char in enumerate(string[pos:]) if char == ' ') except: word_end = n word_len = word_end - word_start offset = word_start result = (n-offset-(word_end-pos))%n if string[result] == ' ': return n-result-1 else: return result def minier_process_loop(string, start_idx, dry_run=False): assignments = 0 pos = start_idx tmp = string[pos] processed_something = False while pos != start_idx or not processed_something: new_pos = minier_find_new_idx(string, pos, tmp) #print 'New idx for s[%d] (%s): %d (%s)' % (pos, tmp, new_pos, string[new_pos]) if pos == new_pos: break elif dry_run: tmp = string[new_pos] if new_pos == dry_run: return True elif tmp == string[new_pos]: pass else: tmp, string[new_pos] = string[new_pos], tmp assignments += 1 pos = new_pos processed_something = True if dry_run: return False return assignments def minier_reverse(string): # primo's answer for comparison assignments = 0 for i in range(len(string)): if string[i] == ' ': continue if any(minier_process_loop(string, j, dry_run=i) for j in range(i) if string[j] != ' '): continue assignments += minier_process_loop(string, i) n = len(string) for i in range(n/2): if string[i] == ' ' and string[n-i-1] != ' ': string[i], string[n-i-1] = string[n-i-1], string[i] assignments += 2 elif string[n-i-1] == ' ' and string[i] != ' ': string[i], string[n-i-1] = string[n-i-1], string[i] assignments += 2 return assignments def main(): while True: str_input = raw_input('Enter string: ') string = SuperList(str_input) result = min_reverse(string) print '"%s": %d, %d' % (''.join(string), result, len(string)) string = SuperList(str_input) result2 = minier_reverse(string) print '"%s": %d, %d' % (''.join(string), result2, len(string)) if __name__ == '__main__': main() ``` --- [Answer] # Rebol ``` reverse-words: function [ "Reverse the order of words. Modifies and returns string (series)" series [string!] "At position (modified)" ][ first-time: on until [ reverse/part series f: any [ if first-time [tail series] find series space tail series ] unless first-time [series: next f] first-time: off tail? series ] series: head series ] ``` I'm unclear on the scoring for this. There is no direct string assignment in this code. Everything is handled by the one `reverse/part` which does in-place reversing within and initially on the whole the string. Some detail on the code: * Loop through string (`series`) until it reaches the `tail?` * First time in loop do full reverse of string - `reverse/part series tail series` (which is same as `reverse series`) * Then reverse every word found on further iterations - `reverse/part series find series space` * Once exhausted word finds then return `tail series` so that it will reverse last word in string - `reverse/part series tail series` Rebol allows traversing of a string via an internal *pointer*. You can see this at `series: next f` (move pointer to after space so beginning of next word) and `series: head series` (resets pointer back to the head). See [Series](http://www.rebol.com/docs/core23/rebolcore-6.html) for more info. Usage example in Rebol console: ``` >> reverse-words "everyone there hello" == "hello there everyone" >> x: "world hello" == "world hello" >> reverse-words x == "hello world" >> x == "hello world" >> reverse-words "hello" == "hello" ``` [Answer] **C : Score 2** This just flips the entire string once then reverses each word. ``` #include <stdio.h> #include <string.h> void reverse(char *s,unsigned n){ char c; unsigned i=0,r=1; while(i < n){ //no swap function in C c=s[i]; s[i++]=s[n]; s[n--]=c; } } unsigned wordlen(char *s){ unsigned i=0; while (s[i] != ' ' && s[i]) ++i; return i; } int main(int argc, char **argv) { char buf[]="reverse this also"; char *s=buf; unsigned wlen=0,len=strlen(s)-1; reverse(s,len); //reverse entire string while(wlen<len){ // iterate over each word till end of string wlen=wordlen(s); reverse(s,wlen-1); s+=wlen+1; len-=wlen; } printf("%s\n",buf); return 0; } ``` [Answer] ### Python: score 2 Almost identical to Howard's algorithm, but does the reversal steps in reverse (first flips words then flips the whole string). Additional memory used is 3 byte-size variables: `i`, `j`, and `t`. Technically, `find` and `len` are using some internal variables, but they could just as easily re-use `i` or `j` without any loss of function. *quick edit:* saving on string assignments by only swapping when characters differ, so I can grab some extra points from note #2. ``` from sys import stdin def word_reverse(string): # reverse each word i=0 j=string.find(' ')-1 if j == -2: j=len(string)-1 while True: while i<j: if string[i] != string[j]: t = string[i] string[i] = string[j] string[j] = t i,j = i+1,j-1 i=string.find(' ', i)+1 if i==0: break j=string.find(' ', i)-1 if j == -2: j=len(string)-1 # reverse the entire string i=0 j=len(string)-1 while i<j: if string[i] != string[j]: t = string[i] string[i] = string[j] string[j] = t i,j = i+1,j-1 return string for line in stdin.readlines(): # http://stackoverflow.com/a/3463789/1935085 line = line.strip() # no trailing newlines ore spaces to ensure it conforms to '[a-z]+( [a-z]+)*' print word_reverse(bytearray(line)) ``` [Answer] ## Batch I'll admit to not fully understand the scoring (I think it's two).. but I will say - ***it does the thing***. ``` @echo off setLocal enableDelayedExpansion set c= set s= for %%a in (%~1) do set /a c+=1 & echo %%a >> f!c! for /L %%a in (!c!, -1, 1) do ( set /p t=<f%%a set s=!s!!t! del f%%a ) echo !s! ``` Input is taken as first standard input value, and so needs to be surrounded by quotation marks - call: `script.bat "hello there everyone"` out: `everyone there hello`. Maybe someone else can score me (assuming I haven't, in some other way, disqualified myself). [Answer] # Javascript ``` function reverseWords(input) { if (input.match(/^[a-z]+( [a-z]+)*$/g)) { return input.split(' ').reverse().join(' '); } } ``` Usage: ``` > reverseWords('hello there everyone'); 'everyone there hello' ``` I get the strange feeling I missed something... ]
[Question] [ The parentheses on my keyboard are all worn out, and I want to avoid using them as much as possible. Your challenge is to balance a line containing parentheses by adding them in before and after each line. This is similar to TI-Basic's automatic parentheses and string closure (i.e. `Output(1, 1, "Hello, World!`). It also saves precious bytes from a program! Example input: ``` This line has no parentheses alert(Math.max(1, 2 1+1)*2).toString() function() { alert('Hello, World!'); })( ``` Example (possible) output: ``` This line has no parentheses alert(Math.max(1, 2)) ((1+1)*2).toString() (function() { alert('Hello, World!'); })() ``` Specification: * For each line of input, + Add as many open parentheses to the beginning and close parentheses to the end of the line as needed to balance the parentheses in the line - The definition of "balance" is: * Same amount of `(` and `)` in the line * For every substring starting from the beginning of the string, this substring must not have more closing parentheses than opening parentheses + For example, `(foo))(bar` is not balanced because `(foo))` has more closing parentheses than opening parentheses + You may add extra unnecessary parentheses if you want to, if it makes your code shorter + You do not need to worry about string literals or anything like that, assume that all parentheses need balancing * Output each line with parentheses balanced This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # GolfScript, 23 bytes ``` n/{"()"1/{.2$\-,*}%*n}/ ``` The loophole I'm exploiting is the ruling that: > > You may add extra unnecessary parentheses if you want to, if it makes your code shorter > > > Basically, for each line, this code counts the number of characters on the line that are *not* opening parentheses, and prepends that many extra opening parentheses to the line, and then does the same for closing parentheses. This is incredibly inefficient, but does ensure that all the parentheses on the output line are balanced. For example, given the input: ``` This line has no parentheses alert(Math.max(1, 2 1+1)*2).toString() function() { alert('Hello, World!'); })( ``` this program will output: ``` ((((((((((((((((((((((((((((This line has no parentheses)))))))))))))))))))))))))))) (((((((((((((((((alert(Math.max(1, 2))))))))))))))))))) (((((((((((((((((1+1)*2).toString()))))))))))))))) (((((((((((((((((((((((((((((((((((((function() { alert('Hello, World!'); })())))))))))))))))))))))))))))))))))))) ``` Ps. You can also [test this code online](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiVGhpcyBsaW5lIGhhcyBubyBwYXJlbnRoZXNlcwphbGVydChNYXRoLm1heCgxLCAyCjErMSkqMikudG9TdHJpbmcoKQpmdW5jdGlvbigpIHsgYWxlcnQoJ0hlbGxvLCBXb3JsZCEnKTsgfSkoIgoKIyBQcm9ncmFtOgpuL3siKCkiMS97LjIkXC0sKn0lKm59Lw%3D%3D). [Answer] # Perl, 32 = 31 + 1 or 73 = 72 + 1 (minimized parentheses) ## 32 = 31 + 1: with extra unnecessary parentheses **Edits:** * Fix, parentheses now counted with `y///`. * Unnecessary variable `$a` removed. ``` $_="("x y/)//.s|$|")"x y/(//|er ``` It is used with the run-time switch `-p` (+1 byte). **Test file `input.txt`:** ``` This line has no parentheses alert(Math.max(1, 2 1+1)*2).toString() function() { alert('Hello, World!'); })( (foo))(bar )))((( (( )) ``` **Command line:** ``` perl -p script.pl <input.txt ``` or ``` perl -pe '$_="("x y/)//.s|$|")"x y/(//|er' <input.txt ``` **Result:** ``` This line has no parentheses alert(Math.max(1, 2)) (((1+1)*2).toString()) (((function() { alert('Hello, World!'); })())) (((foo))(bar)) ((()))((())) (()) (()) ``` **Ungolfed:** The algorithm is simple, just add the counterpart for each found parentheses. ``` $_ = # $_ is provided as input by switch `-p` and # it is printed afterwards as output. # y/X// is used to count the character 'X' in $_ '(' x y/)// # add opening parentheses for each closing parentheses . s|$|')' x y/(//|er # go right before the end of line and insert # closing parentheses for each opening parentheses # in the original string ``` ## 73 = 72 + 1: adding *minimum* number of parentheses This script only adds the *minimum* number of parentheses to get a balanced output. ``` $a=y/()//cdr;1while$a=~s/\(\)//g;$_=$a=~y/)(/(/dr.$_;s|$|$a=~y/()/)/dr|e ``` It is used with the run-time switch `-p` (+1 byte). ``` perl -pe "$a=y/()//cdr;1while$a=~s/\(\)//g;$_=$a=~y/)(/(/dr.$_;s|$|$a=~y/()/)/dr|e" <input.txt ``` **Result:** ``` This line has no parentheses alert(Math.max(1, 2)) ((1+1)*2).toString() (function() { alert('Hello, World!'); })() ((foo))(bar) ((()))((())) (()) (()) ``` **Ungolfed:** ``` $a = y/()//cdr; # filter parentheses and store in $a 1 while $a =~ s/\(\)//g; # remove matching parentheses $_ = $a =~ y/)(/(/dr . $_; # add missing opening parentheses at start of string s|$|$a=~y/()/)/dr|e # insert missing closing parentheses at end of string ``` ## 81 = 80 + 1: adding *minimum* number of parentheses This is an older method to add the minimum number of parentheses for a balanced output. ``` my($l,$r);s/[()]/($&eq")"&&($r&&$r--||++$l))||$r++/ger;$_="("x$l.$_;s/$/")"x$r/e ``` It uses Perl 5.14 (because of the non-destructive substitution modifier) and the run-time switch `-p` (+1 byte). ``` perl -p script.pl <input.txt ``` **Result:** ``` This line has no parentheses alert(Math.max(1, 2)) ((1+1)*2).toString() (function() { alert('Hello, World!'); })() ((foo))(bar) ((()))((())) (()) (()) ``` **Ungolfed:** ``` # The while loop is added by option "-p". LINE: while (<>) { # $_ contains the current line my ($l, $r); # initializes $l and $r (to undef/kind of indirect 0) # Modifiers for the following substitution of $_: # /g: process all parentheses # /e: evaluate code # /r: does not change the original input string $_ (Perl 5.14) s/[()]/ # $& contains the matched parentheses # $r is a balance level counter; at the end $r contains # the number of needed closing parentheses # $l is the number of needed opening parentheses; # if $r would go negative, then an opening parentheses # is missing and $l is increases and $r remains zero. ( $& eq ")" && # case ")" ($r && $r-- # close a parentheses group and update balance counter || ++$l) # or update $l if an opening parentheses is needed ) || $r++ # case "(": increase balance counter /ger; $_ = "(" x $l . $_; # add opening parentheses at the begin of line s/$/")" x $r/e # add closing parentheses before the line end # the remainder is added by run-time switch "-p" } continue { print or die "-p destination: $!\n"; } ``` [Answer] # Python 2.7 3: 62 60 58 bytes ``` while 1:s=input();c=s.count;print('('*c(')')+s+')'*c('(')) ``` Not super golfed, but you know. I might be able to squeeze some more bytes out if I really tried. For each line, outputs `(`\*the number of `)` in the line, then the line, then `)`\*the number of `(` in the line. If I understand the rules correctly, this will always provide valid output. Exits by throwing an exception, as a result of the way I did input. (Input is always a hard part of these problems.) If this isn't acceptable, it'll cost me a few bytes to fix, though I'm not yet sure how many. Example output: ``` This line has no parentheses alert(Math.max(1, 2)) (((1+1)*2).toString()) (((function() { alert('Hello, World!'); })())) ``` [Answer] # Pure Bash, 72 bytes Uses the same algorithm as @undergroundmonorail's answer: ``` while read a;do o=${a//[!(]} c=${a//[!)]} echo ${c//)/(}$a${o//(/)} done ``` Output: ``` $ ./lazyparens.sh < input.txt This line has no parentheses alert(Math.max(1, 2)) (((1+1)*2).toString()) (((function() { alert('Hello, World!'); })())) $ ``` ]
[Question] [ The following is an unfolded milk carton: ``` +-----+-\|/-+-----+-\|/-+-+ | | / \ | | / \ | | +-----+/---\+-----+/---\+-+ | | | | | | | | | | | | | | | | | | +-----+-----+-----+-----+-+ \ / \ / \ / \ / \_/ \_/ \_/ \_/ ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge. Your task is to output the above ASCII-art milk carton. Your output may have any whitespace that does not affect the appearance of the image. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes ``` F⁷B⁻⁹&²ι⁻⁷&⁴ιP“↗⎇≦∨⎚üUP@>⁼γa”C⁶¦⁰M⁹→P^³M←\|/C¹²¦⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw1xTwSm/QsM3M6@0WMNSR8Eps6Q8szjVMS9Fw0hHIVNTU0cBImeOImcCltO05vItzSnJLCjKzCvRUIrJQ4YKMTEKCgr6QAaQFa@vBFTsnF9QqWGmo2AA0phflgqy0CooMz2jBNUkqzgdBWOYGiuf1DSQfADUkpgahFmGRmDD/v//r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁷B⁻⁹&²ι⁻⁷&⁴ι ``` Draw the front and what will become the overlap. ``` P“↗⎇≦∨⎚üUP@>⁼γa” ``` Draw one of the flaps at the bottom. ``` C⁶¦⁰ ``` Copy the front to the side. ``` M⁹→P^³M←\|/ ``` Draw the folds on the side. ``` C¹²¦⁰ ``` Copy to the back and other side. [Answer] # [Python](https://www.python.org), 133 bytes ``` for x in b"WwwWB7WQ&ff&6F&!WwwSwtWQ&ff&!&ff&!&ff&!WwwWQdfcfafH6fa".hex().translate(9*"_,|/\+ -").split(","):print((3*x[:-3]+x)[-27:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3W9PyixQqFDLzFJKUwsvLw53MwwPV0tLUzNzUFIH84PISCF8RQYCUBaakJaclpnmYpSUq6WWkVmho6pUUJeYV5ySWpGpYainF69Tox2gr6Cpp6hUX5GSWaCjpKGlaFRRl5pVoaBhrVURb6RrHaldoRusamVvFakIcA3UTzG0A) # [Python](https://www.python.org), 137 bytes ``` print(b"YWB7YWB7WQ(&6F(&6F&!YSwtYSwtWQ((((&!((((&!((((&!YYYYWQdfcdfcdfcdfca````".hex().translate(9*[*"|/\+ -",5*" ",5*"-"," \_/ ","\n"])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3OwuKMvNKNJKUIsOdzEE4PFBDzcwNhNUUI4PLS0AYKAYEaorIZCQQhAempCXDUWICECjpZaRWaGjqlRQl5hXnJJakalhqRWsp1ejHaCvoKumYaikpgEkgW0khJl4fyFOKyVOK1dSEOAjqLpj7AA) Could probably save a few more bytes allowing nonprintables. [Answer] # Vim, ~~100~~ ~~99~~ 97 bytes ``` 4i+-----<Esc>a+-+<Esc>yyppO<Esc>4i| <Esc>a| |<Esc>yyPPkPk8lqqR\|/<Esc>jr\jlr\4hr/klr/qk12l@qGo<Esc>4a \ /<Esc>o<Esc>4a \_/<Esc>0x­⁡​‎‎ ``` Where `<Esc>` is escape key. [Try it online?](https://tio.run/##HYs9C4AgFAB/yFveLvIqHBrbGpPmB@GWH5A6RIH/3bSbjoO7a1VWyA4YIQW8b4wbKFuwA6ZgaU1rr/0cUtq5ELjMLmRWZyYfMiU/TmFJ6wXKILeL4FdEPgiGp9YP "V (vim) – Try It Online") This is probably my first vim answer. Any help is welcome in the comments. -1 byte by changing `3h3xr+` to `a+-+<Esc>` -2 bytes by changing `qqr\jr/jhr/4lr\khr\kr/hr|q11l@q` to `qqR\|/<Esc>jr\jlr\4hr/klr/qk12l@q` ### Explanation: The explanation is separated into 5 smaller sections. #### 1 ``` 4i+-----<Esc>a+-+<Esc>­⁡​‎‎­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌­ 4i+-----<Esc> # ‎⁡insert "+-----" 4 times a+-+<Esc> # ‎⁢put "+-+" in the end of line ``` #### 2 ``` yyppO<Esc>4i| <Esc>a| |<Esc>­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏‏​⁡⁠⁡‌­ yy # ‎⁡‎⁤copy the entire line (not sure why Y doesn't work for me) pp # ‎⁢paste 2 times O<Esc> # ‎⁣make a new line above the current line 4i| <Esc> # ‎⁤insert "| " 4 times a| |<Esc> # ‎⁢⁡‎⁢⁤put the "| |" in end of line ``` #### 3 ``` yyPPkPk8l­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­ yy # ‎⁡copy the entire line PP # ‎⁢paste two times (above the current line) k # ‎⁣move up P # ‎⁤paste above of the line k # ‎⁢⁡‎⁤⁡move up 8l # ‎⁢⁢move right 8 cells ``` #### 4 ``` qqR\|/<Esc>jr\jlr\4hr/klr/qk12l@q­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁣⁣‏⁠⁠⁠‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁣⁤‏⁠⁠⁠‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌­ qq # ‎⁡record in the register q R\|/<Esc> # ‎⁢replace the actual cell with '\', then the next cell '|', then the next cell '/'. jr\ # ‎⁣move down, replace the actual cell with '\' jlr\ # ‎⁤move down, then right, then replace the actual cell with '\' 4h # ‎⁢⁡move left 4 times r/ # ‎⁢⁢replace the actual cell with '/' klr/ # ‎⁢⁣move up, then right, then replace the actual cell with '/' q # ‎⁢⁤stop recording k # ‎⁣⁡move up 12l # ‎⁣⁢move right 12 times @q # ‎⁣⁣playback register 'q' ``` #### 5 ``` Go<Esc>4a \ /<Esc>o<Esc>4a \_/<Esc>0x­⁡​‎‎­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠⁠⁠‏​⁡⁠⁡‌­ G # ‎⁡go to the last line o<Esc> # ‎⁢‎⁢⁤⁢make a new line. a \ /<Esc> # ‎⁣‎⁢⁤⁣insert " \ /" 4 times o<Esc> # ‎⁤‎⁢⁤⁤make a new line below the line 4a \_/<Esc> # ‎⁢⁡insert " \_/" 4 times 0x # ‎⁢⁢delete the first character of the line 💎 ``` Every section is created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 65 bytes ``` 81ᶴ|+y81ᶴ -y3YJṅ"ᶜgṢṆĊ“"|- \/"y⁻'-4«+JD2ΘṅWfT“" \ / \_/ "½ddJ” ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCI4MeG2tHwreTgx4ba0IC15M1lK4bmFXCLhtpxn4bmi4bmGxIrigJxcInwtIFxcL1wieeKBuyctNMKrK0pEMs6Y4bmFV2ZU4oCcXCIgXFwgICAvICBcXF8vIFwiwr1kZErigJ0iLCIiLCIiLCIzLjIuMCJd) **Explanation**: ``` 81ᶴ|+y81ᶴ -y3YJṅ"ᶜgṢṆĊ“"|- \/"y⁻'-4«+JD2ΘṅWfT“" \ / \_/ "½ddJ”­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠⁠⁠⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤⁤‏⁠‏​⁡⁠⁡‌⁢⁢​‎⁠⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‏​⁡⁠⁡‌⁣⁡​‎⁠⁠⁠⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏⁠‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏⁠‎⁡⁠⁤⁡⁤‏⁠‎⁡⁠⁤⁢⁡‏⁠‎⁡⁠⁤⁢⁢‏⁠‎⁡⁠⁤⁢⁣‏⁠‎⁡⁠⁤⁢⁤‏⁠‎⁡⁠⁤⁣⁡‏⁠‎⁡⁠⁤⁣⁢‏⁠‎⁡⁠⁤⁣⁣‏⁠‎⁡⁠⁤⁣⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁤⁤⁤‏⁠‎⁡⁠⁢⁡⁡⁡‏‏​⁡⁠⁡‌­ 81 y81 y # ‎⁡Base decompress 81 twice with chars ... |+ - # ‎⁢... "|+" and " -" (push "+|+|||+", "- - -") 3YJṅ # ‎⁣Repeat latter three times, join and palindromise "ᶜgṢṆĊ“"|- \/"y # ‎⁤Base decompress "ᶜgṢṆĊ“ (9709170788) with chars "|- \/" (push "- /\/-| -/\-- \") ⁻ # ‎⁢⁡Split into chunks of length 3 '-4«+J # ‎⁢⁢Append "-" and 3 spaces to each item, merge lists 2Θṅ # ‎⁢⁣Palindromise first two elements D WfT“ # ‎⁢⁤Insert result between two copies of the list, transpose " \ / \_/ " # ‎⁣⁡Halve string, quadruple each half J” # ‎⁣⁢Join with transposed list and format 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [///](https://esolangs.org/wiki////), ~~147~~ 141 bytes ``` /l/\/\///a/| lb/-----lc/aaaa| | lf/ d elg/ d_e lh/a| e d li/b+lj/+ie---dlk/+i-d|e-ld/\\\\le/\\\lkk+-+ hh| | jj+-+ ccc+iiii-+ ffff gggg ``` [Try it online!](https://tio.run/##Fcw7DsQgDATQPqdwj9BcKNKKgBM@09Fyd3Z4LjyyZU@mWX3uDeJWAQnLDj6IBzOSLFsXX1jRyvnBrPzcWKGNa8qGJ7AjNNdR4VCKZXlkwS300zhGiOGq9bzr/eScc2ii@Mr1yd5/ "/// – Try It Online") I'm not going to explain this one. -6 bytes thanks to [@Philippos](https://codegolf.stackexchange.com/users/72726/philippos) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 71 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "+--- |".B4и¨D1è4ǝ… \ Ćª„\_2úª.ºD"+-\| | / +/--".B.º2Ýǝ€¦øJεD¦y2£R'\KJ, ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fSVtXV5erRknPyeTCjkMrXAwPrzA5PvdRwzKFGIUjbYdWPWqYFxNvdHjXoVV6h3a5AFXH1HDVKOhzaevr6gI1AQWNDs8Famhac2jZ4R1e57a6HFpWaXRocZB6jLeXzv///3V18/J1cxKrKgE) **Explanation:** [Try it online with step-by-step debug lines.](https://tio.run/##fZNBaxNBFMfPyad47GUPzVobchKkWBbEiCA5L8g0eUlGJzvDzMQ0kkPx4Leol0Iopd5UShGEXcFb6WfoF4kzb3bTjYinbOb99/9@7/9mpWHHHDeb6PXcTMFOEcZSCLng@QSM1e7nCUSdaC9JkvYqSu9P11H5M@oU3w/b0ZE8AW59/dHRUzoZoEJm3SH0wPIZGl/s3V3X1Zl8j9REMONlOPOC4iLUn6Ol4uPkmBkcwUGlgbGWM2AwlGrp9elBebFL8iI3qKkv27Xo2SnwfIQnBPL7LDR6phTmIxIeS2uduV1IEDwPwM4aMvj1qbi8P/2cvemWN8VlePEV11pqQDackhwW3DVwQ2nBFAVR3ARlOleCD5n143LjxMZ2gLmm6n85py7obNVewX57bz9J/pk3MAMLFKKZe8XVpGlAsgnj@Q5dlRehueZK4Da5MdfGP2lEUNJwy2VuXIZUHNVTjWgi79ktz@pYG/sNLsMp02xoUYcNboko5I9XxbqiRz2proVfAcgx/Qk7MdYhygm6E@3fK6/71VtuRj9rsK0ybLeawWN1HJLXAY87w7/wKHoCiluHIevW9nsIFiHEYPQOUcHbOd3O2qv74EZ3KO3efi3OnV2AbQ3QoZomFA3zpakgPOZSt5hbzgTEWexVcXb34wGsL6tlhB2FyOqEAqCcWzWnz4FuhNWMCz9Djos6/ttvabFedovzQZy97Met8qqz2WySJJeJYB@WfwA) ``` "+--- |" # Push string "+---\n|" .B # Box it to ["+---","| "] 4и # Repeat it 4 times ¨ # Remove the last item D # Duplicate it 1è # Pop the copy and get the 0-based 1st item 4ǝ # Insert it at the 0-based 4th index … \ # Push string " \ " Ć # Enclose it; append its own head: " \ " ª # Append it to the list „\_ # Push string "\_" 2ú # Pad 2 leading spaces: " \_" ª # Append it to the list as well .º # Mirror each inner string with overlap D # Duplicate this list "+-\| | / +/--" # Push string "+-\|\n| /\n+/--" .B # Box it to ["+-\|","| / ","+/--"] .º # Mirror each inner string with overlap 2Ý # Push list [0,1,2] ǝ # Replace the strings at those three indices with this triplet-string €¦ # Remove the first character of each inner string øJ # Join the lines in the two lists together ε # Map over each line (used as foreach): D # Duplicate the line ¦ # Remove the first character of the copy y # Push the current line yet again 2£ # Only leave its first two characters R # Reverse it '\K '# Remove a potential "\" from this string J # Join all three strings on the stack together , # Pop and output it with trailing newline ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~108~~ ~~105~~ 102 bytes ``` 2*$(a+-\|/-)h2*$(b| / \ )| |¶2*$(a+/---\)h3*$(4*b| |¶)4*ah4*$( \ /)¶4*$( \_/ a +5*- b |5* h +-+¶ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwYKlpSVpuhY3s7iMtFQ0ErV1Y2r0dTUzQJykGgV9hRgFzRqFmkPbILL6urq6MZoZxkCOiVYSWELTRCsxwwQoAFSqoKCveWgbmKMQE6-vwJXIpW2qpcuVxFVjqqXAlcGlrat9aNuS4qTkYqi9MPsB) This is my first time using Retina so this can probably be improved on. This program uses Retina's repetition operator `*` extensively. I'm hoping to reduce the repeated part of `2*$(a+-\|/-)h2*$(b| / \ )| |¶2*$(a+/---\)h` (the `2*$(a+something)h` bit). Any ideas? [Answer] # [sed](https://www.gnu.org/software/sed/), 151 bytes ``` s_^_+-----+-\\|/-_ s/.*/&&+-+/ h p y_/\\-|+_\\/ |_ p x s_..|.._/---\\_gp x y_/\\_ _ p p p x y_/\\_--_ p s_.*_ \\ /_ s__&&&&_p sx\\ x \\_xg s_ __ ``` [Try it online!](https://tio.run/##Rc2xCgMxDAPQ3V/hKcMZxz8kqqUlnY6DUEgh/546t1Tjs4T76@nt/KzV@aD5jjkwwyk96hGlmFvIWy75MgCfRiBUJ5OGdNY6a2XkEmDbdhepuhuX/MV9Sy4OKqCqkU/IkmH6uG1o3jhaXpRc6wc "sed – Try It Online") [Answer] # JavaScript (ES11), 143 bytes A mix of maths and hardcoded XOR patterns. ``` f=(y=9,x)=>~y?` |-+/\\_ `[X=--x%6,x?y<2?x<3|X+~y?X+y-5?X|y?0:6:4:5:["70006","0504","0637"][y-6]?.[x%12-4]^648>>y&2|X==3|x<2:7]+f(y-!x,x||28):"" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY7BCoIwAEDvfUUNDEVna85pw7nfGOhKKNdF9FDBBqNf6AO6eKh7v9PfVEinB493ePdHPxzacXxezhrm75vmvuWbyAS8vFrRzB0MV3W9mzWV5BAaj0ZG2AILUyROht9EhhamQjorEKOMsJRVIEMIURABlCLyA00yoCoLqRJxZbw1hkRtKcnL0i6xk5wnzhSYZSrUvoULExnncB4wAKat137oT0PXxt1w9LUfBJP-X38A) For comparison, using [RegPack](https://siorki.github.io/regPack.html) gives [170 bytes](https://tio.run/##HYtBCsMgFET3nuLvooh1WwgBDyKYUAg1lChJUBM1V7e/fbMZ3jDLFKb9tVl/iPBszQxjSlxwEmOBQkLAnnMmvCKoL0QRgFP9cxcFUMUPjg0yuRF8XqC1kqfWRiZehdZFioiDRA@BV4kPrcd@dhu14OYuxHReWdW7Y9Eeb2oeu//Yg1rGzLA4u1LvPGWs95tdD2pYa18). ### Method We iterate from \$y=8\$ at the top to \$y=0\$ at the bottom, and from \$x=27\$ on the left to \$x=0\$ on the right. We also use \$X=x\bmod 6\$. Note that we have \$X=0\$ when we're at the middle of a bottom notch. ``` 2 1 0 7654321098765432109876543210 <-- x 8 +-----+-\|/-+-----+-\|/-+-+\n 7 | | / \ | | / \ | |\n 6 +-----+/---\+-----+/---\+-+\n 5 | | | | | |\n 4 | | | | | |\n 3 | | | | | |\n 2 +-----+-----+-----+-----+-+\n 1 \ / \ / \ / \ / \n 0 \_/ \_/ \_/ \_/ \n 3210543210543210543210543210 <-- X ``` The 8 distinct characters used in the ASCII art are encoded as follows: ``` 0 1 2 3 4 5 6 7 | - + / \ _ \n ``` The following algorithm is used to select the correct character code: ``` x ? // if this is not the end of line: y < 2 ? // if this is the bottom part: x < 3 | // if this is the rightmost part X + ~y ? // or X - y is not equal to 1: X + y - 5 ? // if X + y is not equal to 5: X | y ? // if X != 0 or y != 0: 0 // insert a space : // else: 6 // insert "_" : // else: 4 // insert "/" : // else: 5 // insert "\" : // else: [ "70006", // these are the XOR patterns "0504", // to apply for the most "0637" ] // complicated cuts at the top [y - 6] // i.e for 6 <= y <= 8 ?.[x % 12 - 4] // they are applied modulo 12 ^ // 648 >> y & 2 | // this gives 2 for y in [2, 6, 8] X == 3 | // standard vertical lines x < 2 // rightmost vertical line : // else: 7 // insert a linefeed ``` [Answer] # PowerShell, 139 ``` $m='-----+';"$("+$m-\|/-"*2)+-+ |$(' | / \ |'*2) | $("+$m/---\"*2)+-+" ,"$('| '*4)| |"*3 "+$($m*4)-+ $(,'\ /'*4) $(,' \_/ '*4)" ``` Not very golfed right now, but it's late [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0`, 133 bytes ``` $;="+-----";say"$;+-\\|/-"x2,$e="+-+ ",'| | / \ 'x2,$d="| | ","$;+/---\\"x2,$e,("| "x4,$d)x3,$;x4,$e,' \ /'x4,$/,' \_/ 'x4 ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJDs9XCIrLS0tLS1cIjtzYXlcIiQ7Ky1cXFxcfC8tXCJ4MiwkZT1cIistK1xuXCIsJ3wgICAgIHwgLyBcXCAneDIsJGQ9XCJ8IHxcblwiLFwiJDsrLy0tLVxcXFxcIngyLCRlLChcInwgICAgIFwieDQsJGQpeDMsJDt4NCwkZSwnIFxcICAgLyd4NCwkLywnICBcXF8vICd4NCIsImFyZ3MiOiItTTUuMTAuMCJ9) ]
[Question] [ For a 2 dimensional array we will define the elements in either the first row or the last column to be the largest "J-Bracket" of the array. For example in the following array elements in the J-bracket are highlighted: \$ \begin{bmatrix} \color{red}{\underline 1} & \color{red}{\underline 2} & \color{red}{\underline 4} & \color{red}{\underline 8} \\ 9 & 3 & 6 & \color{red}{\underline 7} \\ 3 & 3 & 2 & \color{red}{\underline 9} \end{bmatrix} \$ The J-bracket is given in order starting from the first element of the first row and going clockwise. The element that is in both the row and the column is not repeated. So for the above that is: \$ \left[1, 2, 4, 8, 7, 9\right] \$ To get the next largest J-bracket is just remove the largest J-bracket from the array and take the largest J-bracket of the remainder: \$ \begin{bmatrix} \color{lightgrey}{1} & \color{lightgrey}{2} & \color{lightgrey}{4} & \color{lightgrey}{8} \\ \color{red}{\underline 9} & \color{red}{\underline 3} & \color{red}{\underline 6} & \color{lightgrey}{7} \\ 3 & 3 & \color{red}{\underline 2} & \color{lightgrey}{9} \end{bmatrix} \$ and so on until every element is in exactly 1 J-bracket. The set of J-brackets from an array is not necessarily unique. In fact if the matrix is non-square every matrix has a twin with the same J-bracket set. \$ \begin{bmatrix} \color{red}{\underline 1} & \color{red}{\underline 2} & \color{red}{\underline 4} & \color{red}{\underline 8} \\ \color{green}9 & \color{green}3 & \color{green}6 & \color{red}{\underline 7} \\ \color{blue}{\overline 3} & \color{blue}{\overline 3} & \color{green}2 & \color{red}{\underline 9} \end{bmatrix} \cong \begin{bmatrix} \color{red}{\underline 1} & \color{red}{\underline 2} & \color{red}{\underline 4} \\ \color{green}{9} & \color{green}3 & \color{red}{\underline 8} \\ \color{blue}{\overline 3} & \color{green}6 & \color{red}{\underline 7} \\ \color{blue}{\overline 3} & \color{green}2 & \color{red}{\underline 9} \end{bmatrix} \$ This twin has the opposite dimensions and in the case of a square matrix it is its own twin. Your task is to take a 2D array of positive integers and output its J-twin. You may take input and output in any standard format but the input format should be the same as the output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal. # Test cases ``` [[2]] -> [[2]] [[1,2,3]] -> [[1],[2],[3]] [[1,2,4,8],[9,3,6,7],[3,3,2,9]] -> [[1,2,4],[9,3,8],[3,6,7],[3,2,9]] [[1,2,4],[9,3,8],[3,6,7],[3,2,9]] -> [[1,2,4,8],[9,3,6,7],[3,3,2,9]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ZL_Lṙ@ŒdŒḍ ``` A monadic Link that accepts a rectangular list of lists and yields its J-bracket-twin as a list of lists. **[Try it online!](https://tio.run/##pZGxUcQwEEVzV/EL@IF3JfvsjAKuAjQakiNhrgEqICK5CDrhYuYKuUrMX9kHM0TMkMjvW6vd/6Wnx@PxeVnu9w/76/n97nI6XE7Xj9fl80Xf89tSCoxwIhGZGIiR2BFT7VjMaE5LtEwbaCNNW3Pbmuk93ehOT3QVTLS@drXrSpmIqPRciSLQSXgKIVAnuIcQqDPcQgg0Cd6HEGgybA4R0ErWpRXM@jfVNuwW4Mcx8mYxGg7B8hqTxsYWYbBr7JFqTasY3/F@5fmjHcH/kle9x5omb11TmFsvJB5mQw@b9Qs "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##pZExbsMwDEV3n4JrgT@YlGxLWw@QC7SC0CVZglygJ@jUJVN7k2QucpCcxP2UkyboVKCL9b75TfLL281u9zrPz6uX1fn4@Xjar0/78@F9/nrjefx4eJpLEYUYJEAiZICMkAmSaoeiCjVogEboAB2hLOVWyrAepjCDBRgNCdrXrnZdKQniTosVUgj8Uiy4ILCTmLkgsLOYuiBwkljvgsDJotmFQ7Msj2bIfJdqG3YNcNtY4mVFbzg4c1efNDZWDyNTY/NUS1rG@In3K88f1yH8L3nl/yhWfYPCq0W4YQT7c07AiIkUSIZ8Z7iUUyteTYulfgM "Jelly – Try It Online"). ### How? ``` ZL_Lṙ@ŒdŒḍ - Link: list of lists, A Z - transpose A L - length of that -> columnCount(A) L - length of A -> rowCount(A) _ - columnCount(A) subtract rowCount(A) = N Œd - anti-diagonals of A ṙ@ - rotate this list of anti-diagonals left by N Œḍ - create a matrix with these anti-diagonals ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 154 74 72 bytes ``` {$[1=&/#'1*:\x;:+x;[r:,/(*x),1_-1#'x;(,(#x)#r),+(+o(1_-1_'x)),,(#x)_r]]} ``` [Try it online!](https://ngn.bitbucket.io/k#eJyrVok2tFXTV1Y31LKKqbC20q6wji6y0tHX0KrQ1DGM1zVUVq+w1tDRUK7QVC7S1NHW0M7XAAnHq1doauqAxeOLYmNrAX+yEfk=) [Answer] # [Python 3](https://docs.python.org/3/), 111 bytes ``` def f(x): r,*a=x;k=len(a) if k*r[1:]:r+=map(list.pop,a);x=*zip(r[:k],*f(a)),r[k:] return[*map(list,zip(*x))] ``` [Try it online!](https://tio.run/##TY9BCsMgEEX3PYVLtUMhsbSJwZOIC6FKJakRY8H28taEhnY1D/77M0x4pfvsWSk3Y5HFmfADikC1yMMoJuOxJgfkLBpplA1XPB7FQwc8uSWdwhxAkyEL@nYBR8lHBdTWBoEoR67qJpOe0Uu6V2AVaSZEFTtHlMySkPNIylYpqKOBFtgPz9ApkD0wuMC1EqvUQv8nfONuC3dpU@ofKETnE7Z4vUNI@QA "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org), 76 bytes ``` \(m)array(unsplit(split(m,i),rev(t(i<-pmin(row(m),rev(col(m)))))),dim(t(i))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY_PCoJAEIfvPoXQZRZmD7pRCtoTdOxmHsQSFlyVbe3Ps3QxqIeKXqbZ1YME7WFmGL7fN-z9oYdn5Sf81ZuKR-_tHhQrtC5u0DenrpYGxqpQMtTHMxiQCe-UbEC3F4LdsmxrGt3Dg1QWonFyfkClqjBaXqGEkGGAuGNs4fONn2VhnnsVZb05FGCI4gcMciQYM_EvsMQIYxS4wjVVQZuYUZsrLEUKS0VWZVnXiSUtGa2ZecpdmKccP9ldYsqMXxyGsX8B) As in [the other challenge](https://codegolf.stackexchange.com/a/245749/67312), `split`s the array to find the J-brackets. Then `unsplit`s and adds `array` structure to get to the J-twin as a matrix. Longer explanation to follow. [Answer] # [J](http://jsoftware.com/), ~~62~~ 60 bytes Quite messy. The logic is very similar to my Python answer. Porting the [Jelly answer](https://codegolf.stackexchange.com/a/245762/64121) might be shorter. ``` [:|:*@#@,(({.,{:"1@}.)((}.~#),~({.~#),.])|:@$:@:(}:"1)@}.^:) ``` [Try it online!](https://tio.run/##PYrBCsJADETv/YqhLXQja7Ddom2ksCB48uRV9CJW8eIHtNtfX2NFCZPM5M0zplz06AQFLFYQ1ZKxOx728SSjLHzmrTED20HS0gcmYwJPGdlJn5/LZxrF5@LFBK2Qdi5CkZI7Osbt@nh5s@0p0Vzq5Khm59SVqOA01f9Uo1XfqNbY6K7QKnf6//FmbnzpzOMb "J – Try It Online") [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 59 bytes ``` m->matrix(#m,#m~,i,j,m[i-d=min(l=i+j-1,#m)-min(l,#m~),j+d]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY1BCoMwEEWvEnST4GShKa0S9AY9QZASEMuII0FSaDe9SDdCKT1Tb9PE1tV_f94w83g7O-Pp7JZnz-rXxfey_GiSDVk_45WnBCndAWEAMii7mnDiY43ZIPNghFx73BEwZF0r_icm69x448Rkw9yMkw-YxJKwnpMQwMzRel4EiGlyKEC1cRxpB6WuQMEeDlqFLKBqN7WKUm8yqu3rsvzyCw) Shift the \$n\$-th anti-diagonal to lower left by \$\min(n,w)-\min(n,h)\$, where \$w\$ and \$h\$ are the number of columns and rows of the matrix respectively. [Answer] # [Python](https://www.python.org) + NumPy, 80 bytes ``` def f(a):b=0*a.T;b[1:,:-1]=a.any()and f(a[1:,:-1]);b[b<1]=a[a>0];a[:]=0;return b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY5NTsMwEIX3OcUsbTS1kqb0JyGcgQU7y0IT4ghL7dhyHaSchU02cKfehoTSDWI53_s07318hTG9eZ6mzyH1q_3lqbM99IJk1Tb5HannutVFhdWqMA0p4lFI4m4xbljORvuwxJoec1OTrkyT19GmITK0v39f3Cn4mICHUxiBzsAh630EB47BB8silypa6o6O7VnIKgMAajgoipFGYd_pKJyUCw7RcRKE8wj16sM8ScprzXQhrdfGZFoXuDaoS9zcLtzgfiYHLHGLu5-snOnhj436Hrf_MtS7xb42fQM) Accepts and destroys (overwrites with zeros) a NumPy array. Relies on elements being positive as promised in OP. [Answer] # [Haskell](https://www.haskell.org/), ~~132~~ 121 bytes *-11 thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)* ``` t[h]=pure<$>h t s@([x]:r)=[s>>=id] t(h:r)|n<-t$init<$>r,(a,b)<-splitAt(length r)$h++(last<$>r)=zipWith(\i->(++[i]))b(a:n) ``` [Try it online!](https://tio.run/##VcpBasMwEIXhvU@hhRYjPC7ELm0SLJOeoYsuVC0UaqKhiiKkMSkhd3eNaaHd/Y/3eVc@xxDmmY23Ok157OXgKxblAObL7rPSpgyDpg9bMfhl32PfsKRIvMiM4PCo@qakQPzCEMZ4Yi@ykr6uIbiyKqVvlN6IPbxTM0BdG7JKHcHto5rPjqLQIk38yllOMVAcizy7JKD4y/WBlTCVEMa01uIaG2yx@zsecWvR7LDDJ3xeqluqxd0/8gO26/3LVlQJO38D "Haskell – Try It Online") If the input list has only one row, or only one column, transpose it. Otherwise, recurse on the "nub" that results from removing the J-bracket; then split the J-bracket into two parts, put one part atop the nub, and append the other part itemwise to the right side of the nub. It's still pretty long, so I'm guessing there's a better way to do this... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ ~~43~~ 39 bytes ``` F⁺θ§θ⁰⊞υ⟦⟧UMθEι⊞O§υ⁺κμλ≦⮌υIE§θ⁰Eθ⊟§υ⁺κμ ``` [Try it online!](https://tio.run/##dY49D8IgEIZ3fwUjJGeirVGbTk0nByNxJQykRdtIS@Wj8d8jxTg4yPRwd@9z13TCNFqoEG7aIEyVt/gJqHKnsZWvBTeEEES97bAHxDgpV2cx1XoYxNgu/fjDPaSJyySNcNrgbzwmkvEBaCAEkIqulK@s7e8jvspZGisB@Vimph8droV1eHH@nPBZE5Hq6Y89vTIExtgWMtjBkQMrIIc9HCLlkTIoOOdhPas3 "Charcoal – Try It Online") Link is to verbose version of code. Outputs in Charcoal's default one-element-per-line format. Explanation: ``` F⁺θ§θ⁰⊞υ⟦⟧ ``` Create a list of empty lists that will eventually hold the antidiagonals. ``` UMθEι⊞O§υ⁺κμλ ``` Extract the antidiagonals from the input. (This replaces each element in the array with the antidiagonal to which it belongs, but unfortunately I can't make use of this fact.) ``` ≦⮌υ ``` Reverse the antidiagonals so that we can extract the elements in the original order using `Pop()`. ``` IE§θ⁰Eθ⊟§υ⁺κμ` ``` Transpose the array, but read the elements back from the antidiagonals. (If Charcoal had an equivalent of JavaScript's `unshift()` then I would be able to unshift directly from the transposed array's antidiagonals to recover the elements.) [Answer] # [Haskell](https://www.haskell.org/), 100 bytes -3 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard). ``` t m=[[m!!(i-1-x+y)!!(j+x-y)|j<-[0..l m-1],let[x,y]=min(i+j)<$>[l$m!!0,l m]]|i<-[1..l$m!!0]] l=length ``` [Try it online!](https://tio.run/##VcvBCoMwDIDhu08RwYPFVKyOTUH3BnuCEIYH2eraIlsPCr67K7LBdvuTfLn3r8dgzLZ5sB2RjeNUSyXnbBEhx2yWi1jHVlKR5wasVIxm8DTjwp3VLtXZKNrkTCYJrwUGwrzq4FXw@445Mp0Z3M3fN9trBx3YfrpcIZ2e2nnIwQugCICoZMY9FJZY/Q4HrBmpwQqPeApVhSqx@SMfUO/nL9tRBLy9AQ "Haskell – Try It Online") An ugly port of [my PARI/GP answer](https://codegolf.stackexchange.com/a/245758/9288). --- # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 101 bytes -4 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard). ``` t m=[[m!!(i-1-x+y)!!(j+x-y)|j<-[0..l m-1],let[x,y]=map(min$i+j)[l$m!!0,l m]]|i<-[1..l$m!!0]] l=length ``` [Try it online!](https://tio.run/##VYvdCoJAEEbvfYoRvFCcFX@iFPIReoJhCBGptV0R28AF392WpaDuzsx3Tv9aFivm7tE/992Abol0GMZSFGJNbeJwTFdhk208C8qzTIEWBaMaDK1oudXdHGs5RTIdE1KRa3N0DvMmXVC4wP@YA9WqYbqZ@647OUELrrxcIZ4XORnIwCRAAQBRyYweCiyx@j0OWDNSgxUe8eSoclRi86d8hNrPX81LAfD@Bg "Curry (PAKCS) – Try It Online") [Answer] # Python3, 234 bytes: ``` E=enumerate s=lambda m,d:(k for i,j in E(m)for x,k in E(j)if(i==d and x<(len(m[0])-d))or(i>d and x==(len(m[0])-1-d))) r=lambda d,m:[[next(d[min(x,len(m)-1-y)])for y,_ in E(m)]for x,_ in E(m[0])] lambda m:r({i:s(m,i)for i,_ in E(m)},m) ``` [Try it online!](https://tio.run/##hZFNbsIwEIXX9SlGbLClARVStRDV7Nj2AsZCRnZUQ@xETloFVT17agdC2VTdzZv3ef5cn9v3ymerOvQF3/WlcgetwOWBftm8oQ4tK6oAFvdgPWypY9/oGNly4z@cCao1pOHjK9Q5PcGFP458kh2eLvLIbEEt5xqU19C90tJ46sSjZDPNWBWo3Vwtzu@8RXIZCWMnjS4XwpuupVo462mHA5zIM5NDz/PvyPIyw6hTSdlbV1ehBdW0xPqaTyYTIZZSwmwDQ0CEWOASszG1kBjTKLKb9YSrqNeY4TO@JCdGS1zfHiTkCqwGe8QGiPxL3JX5q1Ocmgz3TqsVtmxNoG@VNxh1PW/q0rZ0uvNTxnLyoBAOwMGpmsat59GLH1juzacqIz/SqWvkI940Jh6ooIoB53Ag/Q8) ]
[Question] [ [Very related](https://codegolf.stackexchange.com/questions/181708/would-this-string-work-as-string?noredirect=1&lq=1) You're given a piece of ASCII art representing a piece of land, like so: ``` /‾\ __/ ‾\_ \_/‾\ \ ``` Since an overline (`‾`) is not ASCII, you can use a `~` or `-` instead. Your challenge is to determine if it is connected by the lines of the characters. For example, the above can be traced like so: [![enter image description here](https://i.stack.imgur.com/mvY5d.png)](https://i.stack.imgur.com/mvY5d.png) To clarify the connections: * `_` can only connect on the bottom on either side * `‾` (or `~` or `-`) can only connect on the top on either side * `/` can only connect on the top right and bottom left * `\` can only connect on the top left and bottom right It doesn't matter where the connections start and end as long as they go all the way across. Note that one line's bottom is the next line's top, so stuff like this is allowed: ``` _ ‾ \ \ _ / \ ‾ ``` You can assume input will only contain those characters plus spaces and newlines, and will only contain one non-space character per column. Input can be taken as ASCII art, an array of rows, a character matrix, etc. ## Testcases Separated by double newline. Truthy: ``` \ \ \_ \ /\/\_ ‾ \ /\ \/ \_ ‾\ /‾\ __/ ‾\_ \_/‾\ \ ``` Falsy: ``` / \ // ‾‾ / \ ‾ _ \____/ /‾‾‾\ ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 85 bytes Input is taken as a list of lines, with `‾` replaced with dashes (`-`). ``` lambda L,n=0:len({(n:=n+2-ord(c:=max(x))//2%5)-x.index(c)+(c<'0')for x in zip(*L)})<2 ``` [Try it online!](https://tio.run/##VU//aoMwEP4/T3EwSu5aNaVlMKS@gW@wDMk0pQGNwQizG4M92R5mL@IS7Qr7CORy34/Luet46e3xyQ3zuZBzq7rXRkGZ2GKft9riB9q8sLtD2g8N1nnRqQknIiEOm0dKp8zYRk9Y0w7rE99zOvcDTGAsvBuH25I@6XSYTef6YQR/9SzytfI6SsI782NjbDZo1SBl3rVmRC6ttJxytgqL5QoS16paI//5@uYJ8JQTg/KPvTtj9wGcakCr@gKtsRrezHgB74Lb3zOf@Sbdeg4bwLhSpxyGdRMoiRKYCO57lC8M3GDsiGeMXqJZMpCMyYoBSBBSLBWEf0FEoISMlLhpAhF6gRFLVVViVa@2FbJaSfiHGLXMYiKERU84TCxErKCKIwLEzShWSYz6BQ "Python 3.8 (pre-release) – Try It Online") [Answer] # [J](http://jsoftware.com/), 43 39 bytes ``` [:*/2=/@(I.@:*-1#.3 2&=+1&=)\' -\/'i.|: ``` [Try it online!](https://tio.run/##jU9RS8MwEH7Pr/hQade55Lb5Vq0UhYEgPohvRkJ0ma3UFtpIGbjfXpN0E/fmQcjd9913993HcCLiDbIUMWaYI3WPC9w@3q@G53RKy4zyyZ3I0ylfnIoLLKPsfBFliYzBJcWl@E6HhD3cCFRNb1o0tenQl1WFV4PO6nqt2/UMXQOpHInKbCwcCkW@bMv3wga5LbTFp9F1B131etuhbay2hgcFDz1e9xcl9IWpj8bKX8gWZj@embeiQfzUftliG4/VJrrGVT55uRRqme9E4n/s/PXpnDHJINkZk4rBTSRJIQOHD8@Q9AwderjHHEUuUe4yjwTFGFJ5AkfhFcnB2kpX3f@c0eiM/GpwzmicxBlUMOOC9puI8@ArGX4A "J – Try It Online") * `' -\/'i.|:` Transpose and convert characters to integers. * `2...(...)\` For each pair of rows... * `I.@:*` Get the indices of the non-zero (non-space) element... * `-1#.3 2&=+1&=` And adjust it as follows: + `1&=` If it's a `-` in either position, subtract 1. + `3 2&=` If it's a `/` on the left or a `\` on the right, subtract 1. * `=/@` Are the two row indices equal after this adjustment? * `[:*/` Are they all equal? [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 77 bytes ``` m/(?<=^|¶)([\\_]([_\/]|.*¶ [-\\])|[\/-][-\\]| [_\/].*¶[\/-])/+`^. ^\s*\S\s*$ ``` [Try it online!](https://tio.run/##VY8xDsIwDEV3n8JSQEqLWosdxCE6xqnLwMAAAzBm4FQdGXoULhLspAt/iL79/G3lcXld7@d9/r4/0MEyg4Nhcg62fnJa5hv50@E4pmVufGCW6IMwxdS3y4yhY45NCkxdLD5hoQZLs6HdNPYAIz9bHvTZ5MyADMACiIzEVBzqfTQpIjZE64wC7Smh4kSoTtdYFUuF@CdbVW4B6TLL2CepAHModkJFa5DqiK36AQ "Retina – Try It Online") Link includes test suite that takes double-spaced test cases and converts `‾` to `-` which the script actually uses. Explanation: ``` /(?<=^|¶)([\\_]([_\/]|.*¶ [-\\])|[\/-][-\\]| [_\/].*¶[\/-])/+ ``` Repeat while the first two columns have a valid join, either a `\` or `_` followed by either a `_` or `/` or a `-` or `\` on the next line, or a `/` or `-` followed by a `-` or `\`, or a `/` or `-` followed by a `_` or `/` on the previous line, ... ``` m`^. ``` ... delete the first character of each line. ``` ^\s*\S\s*$ ``` Check that only one column is left. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` WS⊞υι⬤Φθκ¬↨EE²⭆υ§ν⁺κλ⁺⌕λ⌈λ№⁺_§\/μ⌈λ±¹ ``` [Try it online!](https://tio.run/##TY1LCsIwEIb3PcXQ1QQiRbeuVBC6sBTcFkLQYIPTVNtEu/RkHsaLxMT6Ggjh@/557GrZ7VpJ3l9rTQowNydnt7bT5oCMQen6Gh0HzeZJGaTFBRGuNVnV4ZnDkXEoWotL2SvcyNPrzTiMGyKE4YXNzV4NaDiU5Ho8ciAW6o1rbfZIHDZy0I1rkGKyal049spTkf52pFWVBWxiz99AxEIdpFU4jcTm3gNA9rjdK/hUIkQWvujE23yzSoy9PzPqxE8u9AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangle of newline-terminated lines and outputs a Charcoal boolean, i.e. '-' for continuous, nothing if not. Assumes that any character not one of `\_/` or space is the overline character. Explanation: ``` WS⊞υι ``` Input the land. ``` ⬤Φθκ ``` Loop over all the columns except one. ``` E²⭆υ§ν⁺κλ ``` Get the current and the next column. ``` E...⁺⌕λ⌈λ№⁺_§\/μ⌈λ ``` Find the positions of the non-space characters, but add 1 if the character is a `_`, or if it is either `\` or `/` depending on the column. ``` ¬↨...±¹ ``` Ensure the positions are equal. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 35 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Uses `¯` *MACRON* instead of the overline. ``` ⌈˝{≡´¯1‿1↓¨((/˘𝕨=𝕩)-𝕨∊'¯'∾⊢)¨"/\"}⍉ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyIy5174omhwrTCrzHigL8x4oaTwqgoKC/LmPCdlag98J2VqSkt8J2VqOKIiifCryfiiL7iiqIpwqgiL1wifeKNiQoKUOKGkHs+8J2VqeKGkcucwqjijIjCtOKJoMKo8J2VqX0KCj7ii4jin5xGwqgg4p+oClAiXCLigL8iIFwiClAiXF8i4oC/IiAgXCAvXC9cXyLigL8iICAgwq8gICAgIFwiClAiL1wi4oC/IiAgXC8iClAiXF8i4oC/IiAgwq9cIgpQIiAgIC/Cr1wi4oC/Il9fLyAgIMKvXF8i4oC/IiAgICAgICAgIFxfL8KvXCLigL8iICAgICAgICAgICAgICBcIgpQIi8i4oC/IiBcIgpQ4ouIIi8vIgpQIiDCr8KvICLigL8iLyAgXCIKUCLCryLigL8iIF8iClAiXF9fX18vIuKAvyIgICAgICAv4oC+4oC+4oC+XCIK4p+p) ``` ┌─ ╵"\_ # Input character matrix - m \ /\/\_ ¯ \" ┘ "\_\¯/\/\_\" # collapsed - ⌈˝m ⟨ 0 0 1 2 1 1 1 1 1 2 ⟩ # the depth of each column - /˘(⌈˝m)=(⍉m) ⟨ 0 0 0 1 1 0 1 0 0 0 ⟩ # locations of '¯' and '/' - (⌈˝m)∊'¯'∾'/' ⟨ 0 0 1 1 0 1 0 1 1 2 ⟩ # depth - ^locations ⟨ 0 0 1 1 0 1 0 1 1 ⟩ # the last element dropped - ¯1↓... ⟨ 1 0 1 1 0 1 0 1 0 1 ⟩ # locations of '¯' and '\' - (⌈˝m)∊'¯'∾'\' ⟨ ¯1 0 0 1 1 0 1 0 1 1 ⟩ # depth - ^locations ⟨ 0 0 1 1 0 1 0 1 1 ⟩ # the first element dropped - 1↓... ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` “-\/_”iⱮⱮZTḢ+S+3BḊƲƲ€FḊs2E€Ạ ``` [Try it online!](https://tio.run/##VUwxCsJAEOz3FdtKOBb0B4J@QKuwcJWFks5Kq9NGsLVVEG1FMKhEhRSK@cfdR869XBpnB3bYmdnJKMtm3juzVUzamd3YXc7CdGiLQzJIOl1brKu8yt3y1Bc5bfdE2efefzf2cXSL8n2XudnXdS5tTD@rlvcMyACsAZGRmGqFCgPEIA4GNQklF7mTbK0p5GI8gnUw8A9SAIK45As6UwqBakcB6vBZQE2PYkDIPw "Jelly – Try It Online") ]
[Question] [ Swap encoding is an encoding method where you iterate through a string, reversing sections of it between pairs of identical characters. ### The basic algorithm For each character in the string: Check: Does the string contain the character again, after the instance you found? If so, then modify the string by reversing the section between the character and the next instance, inclusive. Otherwise do nothing. # Example Start with the string 'eat potatoes'. e is found again, so reverse that section: `eotatop taes` o is found again, so reverse that section (doing nothing as it is palindromic) t is found again, so reverse that section (doing nothing as it is palindromic) a is found again, so reverse that section: `eotat potaes` t is found again, so reverse that section: `eotatop taes` None of 'op taes' are found again, so `eotatop taes` is our final string! # Your challenge Your challenge is to make a program or function that takes a string as input and returns it encoded as above. Capital letters and lowercase letters are treated as different, and all characters, including spaces, can be swapped. # Testcases ``` Sandbox for Proposed Challenges => SahC Pr foropox dbosenallednges Collatz, Sort, Repeat => CoS ,ztrollaepeR ,tat Write a fast-growing assembly function => Wrgnufa ylbme asa f g-tesstcnoritiwoin Decompress a Sparse Matrix => Dera aM ssrtapmocese Sprix Rob the King: Hexagonal Mazes => Rog: Kinob eH lagnaM thezaxes Determine if a dot(comma) program halts => Detoc(tlamarommi finerp ha mrgod a) ets Closest Binary Fraction => CloinosestiB Fry tcaran Quote a rational number => Qunatebmuoiton re al ar Solve the Alien Probe puzzle => SorP Alveht en eilzzup elobe ``` Yes I just took the titles of various sandboxed challenges for the testcases. My reference implementation is available [here](https://tio.run/##TY5NCoMwEEb3PcV0lxAdtFvrGXoAERRN6ohESaIGime3/hTpbobvvW@mLafSVoYGF@q@luuqRl056jXYuRyY558bAEEKUbINc0OdZARP8NhJ/XbNkQOojfBoO6q2WMQcSdfSvxTzGeX8QEgxBfc0hTD@SQD@T4sC4iJDxKsnUILEg@do5CSNlYxj25MuChCXdSJH3XKeEWL/dF@MdKPR4JPbsq5f) if anyone wants it. This is actually an encoding as `reverse(swap(reverse(string)))` decodes it. [Answer] # JavaScript (ES6), 67 bytes ``` f=([c,...a])=>c?c+f([...a.splice(0,a.indexOf(c)).reverse(),...a]):a ``` [Try it online!](https://tio.run/##dZLBattAEIbvfYrBJ4naSs@BtDQ2JVBCE@uQQ@hhtBrJW1Y7Ynbk2Hp5d2RqWuRUN8H3fzP6R79wj8mJ73UVuabTqbnLXt2yKAr8md99dl/cxyZ7nV6L1AfvKPu0xMLHmg4/mszleSG0J0mU5X9Ct3hyHBMHKgK3WZMtSox1xQdoWOBJuOdENax3GALFltICLk@ew80NlLhbGzfhxh7AsoniRNcT/mFmX3MIqOMSShZdwpZ6Qv3rhJl9zSUsR5UpZegWloo6d76IVwKEBpOuWuE3H1vAlKirwhGaITr1HBcX54u0cWgQjqHqLJYsCO1KKSV1kc3l39jH@ZANOe56McomlT1aifCIKv6weG/xDQkCPkJKoth37Mj4sjd8Lt5yBboj@G5b38IDHbBl68/k479tX8RbNspYS9EDBGyjTbH8iIfrtjekJJ2PBL6xtWvWzL6iwxx64VawA7ur2pTL0sou04AdimEeGotKbxB00nINFiS9vmmwkyeFex9RjvBN8FL4@zcNVu854e8NPoI6FLwq/Hng81UFJ5kVEoeuIvmf9XmIqFR1A3vlCGLRAChza8lhT@e@vwZPcfrDK4J@GMdAi2ur/aVPRu5pp2A0@TCOQw8ULHX6DQ "JavaScript (Node.js) – Try It Online") ### How? `a.splice(0, n)` removes and returns the first \$n\$ entries in `a[]` if \$n\ge1\$ or removes nothing and returns an empty array if \$n<1\$. If `c` is not found in `a[]`, `a.indexOf(c)` returns \$-1\$ and we just pass `a[]` unchanged to the next iteration. [Answer] # [Python 3](https://docs.python.org/3/), 98 92 89 bytes ``` def f(s): if s:t=s[1:];i=t.find(s[0]);return s[0]+f([t,s[i::-1]+t[i+1:]][i>0]) return s ``` [Try it online!](https://tio.run/##ZZJNa9tAEIbv@hVTQbBEFNPQm4MDjUMIlEBiHXJQfRhJI3lhtbvsjhJbf96dlVvT0r0smvd5R/Ox7sh7a76dTi110GUhXyWgOggrXofqdrW7U2tedsq0Wai@7vI7Tzx6A/HjussqLkKlVqub2901V@paDLtK3QuYwB/yxBS4wUAB1pCmaYmmre0BOuvh1VtnA7Ww2aPWZPoI3UOJ@41oERH9AMIHMpFoI5JsrNbIUwGl9VzAlhwhR@PGllBM7KMuwS0UjJy8e8UECB0Gvum9/VSmBwyBhlofoRtNw8qa6H/3vRk7hKOuB3EE8UB/Iw1IB8ZKGvVplUkeqbGD8xKWrKVDHwhekL06xCSP5BHwBULwjG6wDYlcOlGTra2B9wQ/pIIVPNMBeyt9iXk6d761EhdVOHoGjb2RROKY8CB9PxKTH5ShuCKE1nImhQyYg/O29ziAjJHDuQi2TcYaB/SCKJAdkncCwOB724KYiGWUWkYbGB6UQX@EJ4@XYYgkhURVPYhwBNmiR5O8jXYep8dISvVmHGry0fI2GmSqh9EqliReMA3ok9LqD5o7/64Vmbj3msCN06RpXrj1ryJ90J5BZFJ6mkYHpAWTJ7MMTivOFj/NIk/@fk5V81tKY5Y0nx9VA8rAhdolSQwq4wqwI7t/RHnsclSXdZkAOazXM5Of4/HI2oykL8dG1hiWaT4rpAP9xzyh0qO0LI0vrsIiVjTfX9bzvUzhCrJLHQWc/5nnp18 "Python 3 – Try It Online") Thanks to this question, I am now absolutely confident of the usage of Python slices, which I had never remembered the off-by-one rules, especially when the step-size is negative. [Answer] # [J](http://jsoftware.com/), 39 38 bytes *-1 thanks to Jonah!* ``` 0}:@{&|:(}.(|.@{.,}.)~<:@#|}.i.{.)^:a: ``` [Try it online!](https://tio.run/##hZPBattAEIbveYohgdoCW6RXkYIahxBoUxL7kIOhMJJH8pbVjphdJbZslz5NH6wv4o4cN1EOJQddZr7/339nVj/2p/GggE8JDGAE55DoN45hMv16vT/fJenmwzYZ7uLhNk438WgXRz8vkvRsu4tNvImj7wkm@2@XMXiuCB5RDAbDzsOfX79Puvo82cSnH9PdOx49tgPnPfQsnW9NHB3A4UV6Fh3Y802cPgd7n32T4X@4ZohOKF8yFDAgDFBzwMDkB8/VoZZn6BYZr6BggTvhmj0tYLJEa8mVSkYwTjpqOdF2RymyApV4ch20OFCvfhO2FkM7ghlLGMGUaj346DLhGYzaIB2i9SmMNE5P@yAmECAU6MO4FH4yrgT0nqrMrqFoXN4t4mj2IKVrCoS1zXRN6FUG5TiQ9yF3rE7miY3ruV9RzlUtCugRsxrFE9xiELM6Ol6RIOAteC8B64pzUmJWd8Cry5QzCEuCL5otgRtaYck6CHVqX6Y1ZW0poCjdgMXSqauKWly9mdUVBZLKOAJTaKYFh6FGrDCCWrgUrED3EPxLvMD5MFisUJQyUKhSamWgkpIXoDoKb3ZhdUs@wKVxKGu4FuwPULsasQPMpfbWEHIU7E/svuHDPuTwA@glXVNlJEf9feMwUFY1bAI7ECUtoPTfFttHOkzrszXkuveVEdRN21r697BY7rT7SMsASpCxbdvUQFbJwf4v "J – Try It Online") ``` 0}:@{&|:(}.(|.@{.,}.)~<:@#|}.i.{.)^:a: ^:a: repeat until result does not change, keeping the results }.i.{. index of first character in the tail <:@#| if not found, set to 0 }.( )~ call with index and the tail |.@{. rotate up to the index ,}. append after the index unchanged |: transpose, 0 {& get the first char of each iteration }:@ and drop the last space ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~35~~ 31 bytes -4 bytes thanks to @coltim ``` *'{1<#x}{{(|x),y}.(1|2#*=x)_x}\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJxtkk1r3EAMhu/+FcI5dDc4hfQY2kOySwiUQLI+5FIosle2B2ZGRiM3Xm+2v72y6Xcyt0GPnhGvprk6f3e8/Hg2no7H1cu4Lg6n96vLlw9n55/G9dfx9CXL8hK7DTwINCzc8wj7ihNF9J72saWUw8/zvTE0WnWcUeswOtEeNt3MLmiWb7iEYlJh75F62kGhqL8Vf47JNjOjUwElixawM9zQLH+SNg4NwsFXgQATQgPthVJKWkcWp+6ZXcxnxZPdDIEGk160ws8uttaRKFT+AM0Qa3UczbklQcB7SEkU+8A1JYKyFzfm/4+1pZpDL/acicsexch71BnN8h23V/DZRa6A7sBjG02qHU04/pXU4tkZY5WZtp47GrFlS9Vc05LUlpTrlXoMKByCg8ZFkh46hCAt7wHXQJryZSQlCVYG19hQe9aVzRgM6IVbwWBNXpf4vUVjW0nqbuBWDqA1CsZXC5jj9wsHNy6igbeCv8J6HCIqVWFgpxxBLGEPKG9JHgdeFiA49xoWh1CRmMSW+gDX/ht1ChSBnJ+moQfyXFH+r6Rkw5asrr0z1n5WRdAP0+Qpz34AgpriaQ==) [Answer] # [R](https://www.r-project.org/), ~~104~~ 103 bytes *Edit: -1 byte thanks to Kirill L.* ``` function(s,t=utf8ToInt(s)){for(i in seq(t))if(e<-match(t[i],t[-1:-i],0))t[i+0:e]=t[i+e:0];intToUtf8(t)} ``` [Try it online!](https://tio.run/##TY0xCgIxEEWvEraawQ3ETqI5gP1aLUFCnGAKM@tmFgvx7DF2do8P77@11VdYrlQi38i1tJUomQvUUdwm6TDxuQhUxHfiFbLKRVV6giDmBHTSjyDxDjJnP8qs91Z3MIh92BlL3v2ArPHHXGTiS3/s7uc/CgMFUQtLEKY6YPsC "R – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` PθWKK«→≔⪫KDLθ→ωη¿ηP⮌…η⌕ηι ``` [Try it online!](https://tio.run/##TU1LCsIwEF03p5jlBOoF7EoqLsSC9AYhjs1gSGo6toh49piKCx883uL9rDPJRuNz7h5eeEwcBO@6UYtjT4BnohtqDS9VdXEm3PY8OCl@tZsmHgIeI4dvas@JrHAMeKIwiCsrNfziNSyFbq3xFdBp@HvraaY0EbZP66l1cURXw4HDZVXWBY1650xGYIxiJNKk8mb2Hw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Pθ ``` Print the input string to the canvas without moving the cursor. ``` WKK« ``` Repeat while the cursor is above a character of the input string: ``` → ``` Move to the next character. ``` ≔⪫KDLθ→ωη ``` Get the current suffix. ``` ¿ηP⮌…η⌕ηι ``` Print the reverse of the prefix of the suffix up to the first occurrence of the character that was moved away from, or the empty string if no such occurrence exists. (I need to check that the suffix is not empty because the `CycleChop` function fails for empty strings.) [Answer] # [C (clang)](http://clang.llvm.org/), ~~98~~ ~~96~~ 87 bytes ``` i;j;t;f(char*s){for(;*s;++s)for(i=0,j=index(s+1,*s)-s;j>i;s[j--]=t)t=s[i],s[i++]=s[j];} ``` [Try it online!](https://tio.run/##XZNRb5swEMff@ylOSJOggNZu2sPGUmlNN1WaKnXNwx6aPBhyEGfGRvbREqp89WVnktCsSCBz/vvv8@98RVoooavdTmbrjLIyLFbCnrvopTQ2zM5dFscu8mM5uUjWE6mX2IUuvkxYk7psfSUz97hO08WEIpq4R7lI@BPHCx6vF9l2JzVBLaQOo7OXM@Bn2AAIHbnHBUzgJZgJvcxNB7wN3FvTGIdLmK6EUqgrdEECwdQoJahPYGYsJfCADQryE7@tJAQBpXCUVtY8S12BcA7rXG2gbHVB0mivvMHC1I1F51g@a4R1CHeCrOz87IPJgVYIP3n9F7jFTlRGC8WKfp/BDRLaWmoEWbLB0lDIfrWIoLGmsqIGTpj2ySo@gSO4llrYDfywYkziV2uGdK3wEfbXbZ2j9VMzo55wyOGbkqg9iRyhafteYbDNTthh12BBuBzxraas9viYXQfM0qH29Jav@GaQ9GQ9RUb3AAkd8VW6LQVsVF5zXo5BQpVycRwV2jBb@WzkAZ8VIO7AOUuiqU2BzG/WjPiYGrNjingLSlSapXyWXnQjPlOEpEQtLGOTUDJK2zA0qG1llsAgccTHRp6gvGZ4G6BCWHHApwVhXrdGktFgOWUF4oDP3jO5J1wRMD2Uqu/bBlAxxf/xFSss/qBlejDwm3ffP8y7z1N@P3mnk/@Px5X@aob@Kg8NwMsussPwKzjZoynDY1Wi94fA@RjJII4HdQT7HjjpA/ba98IgWGRv5vO2LFlSczmZnyPLPRFSBDFcRq9ajhfNJvTiBOhkohxi0VtXZMvxFr3d2B@z4RZijfetm4MvRjDxBx@FXHxNZRjMg3duHkB6BYcRf3y5uFH3K4/EveviNDuLeJrg9my7@1uUfH3cLn3@Bw "C (clang) – Try It Online") Inputs a pointer to a string and swap encodes the string in place. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~67~~ 65 bytes ``` f=lambda s:s and s[0]+f(s[(j:=abs(s.find(s[0],1)))-1:0:-1]+s[j:]) ``` [Try it online!](https://tio.run/##RdJRa9swEAfw936Kwy@xqTOadbARyGBtGYVR6JqHPWR5ONtnR50sidO5TVz62dNTmmZ@kiX5/NdPF3ay8e7yW@D9vl1Y7KsGIc4joGsgri7W520eV/njfIFVzOOn1rgmT/PlrCiK6Wx@MZ/O1udx9ThfF3uhKBEWkGdL/b7yW2g9wz374CM1cL1Ba8l1FLMSsmtvLcpYwtKzlPBAgVDSwh82QoDQYpRpx/7ZuA4wRuoru4N2cLUY79LOG6p9H5ii5oVlQI4Edyhstmn1wVcgG4Jf@v0cbmmLnXdodcf4nuCGhLg3jsC0WqDxkmu9HgsI7DvGHjSwvIe1eoIocGUc8g5@Mp5C/B78IS5jmtH6bugr4rS09PaJDhl@WEMuSVQEYRhHS1lxRttAtSjMu9jmWjckMeXagvJFcgms@S@2hHIUTnCq9QClfIh1bmgRdrbqNUpUO@imehtRaueV0zx7cxRjBLyDGFkw9L4mJVuGk5hCKZfC0S1Y7Jxu1fgjbk9ivs5F@wRZpQxoPxAHdYKeO9@A2tFJTAslNHOlXjuQGhmPYg6Fqn7wRrwD1sgW8CjG94r1RBsBBSNjx3EIQFbhVKzeUP2POIFN/g6fv36pJyUcRrPLSXGWuk1KvU4Hown5oR1L@GAu5megT2rQNpfi8KInd5K3k@xFXjOYfofsJerg5fijFS0Wcf06KfZv "Python 3.8 (pre-release) – Try It Online") -2 bytes thanks to [@defald0r](https://codegolf.stackexchange.com/users/82619/delfad0r)! Always adds a (possibly empty) reversed prefix to a (possibly empty) suffix after chopping off the first element. [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~63~~ 58 bytes ``` $_.size.times{|i|$_[/(?<=^#{?.*i})(.).*?\1/]&&=$&.reverse} ``` [Try it online!](https://tio.run/##JY9Na8JAEIbv@RUDFVHRSK@lIq1SCqXQmkMPtZWJTuLCZmeZnViN@tebrvY4vF/PSJ0f2razSoNpKFVTUTiezKmz@hz3pveT75vjNB2Yc7@X9tPBdHk7/up2J51uKrQjCXRuW0IFz4rKFJIM3SbnPRQs8CbsOdAGZlu0llwZ9Rlbi9oMIWPRISzIx3jyIUYJEAoMOiqFf4wrAUOgKrcHKGq3VsMumdOaKy8UQvRmHuM@vKKK2ScLzkG3BC8xeQfPtMeSHdooN3F1TkpSGUdgihjdsPZiU4V98MKlYAWRUCOdjbxB4dE4lAM8Cf4Pv9d85RO8nLHW1VVOkmRsd3TdfbCG3OXjnMDXTWPpl/3FHNqR/wM "Ruby – Try It Online") Thanks to G B for -5 bytes. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` ^ ¶¶ {`¶¶(.*?(.))(.*?)\2 $1¶$3¶$2 }+`¶(.)(.*¶) ¶$2$1 ¶¶ ``` [Try it online!](https://tio.run/##JVBBTsNADLzvK3woUgKlUsuNC4JWgISQoDlwQahO46QrbdaRdwNpEN/KA/KxsNseLMsej2dsIa8tThfJ0276UuMwDup3F1OyuLxLFmkac/q5UrPlOMxuQqzU39Uu4hEah1TF3mx55k5ThrbIuYOSBd6EG3ZUwPqAxpCtyKk1G4O@n0PG4uewpYbQqw/RngChROevK@EfbStA56jOzRHK1u69Zqs2tOe6EXIuzGYNiiN4RS@6U1vOwR8IXgLzFp6pw4otmgD3QXVDnqTWlkCXgVqwT8KmGlNohCvBGoJDH9yZ4Nd5eAhPkSM8Cp6F31s@@ROMZVhr2zonURmbbzrp3htNNl6cEzRt3xv6Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^ ¶¶ ``` Insert two blank lines so that there are now three lines: the output area, the reversing area and the input area. ``` {` }` ``` Repeat until there are no duplicate characters in the input area. ``` ¶¶(.*?(.))(.*?)\2 $1¶$3¶$2 ``` Move the text up to and including the first duplicate into the output area and the text from after the first duplicate up to the second duplicate into the reversing area, leaving the second duplicate in the input area. ``` +`¶(.)(.*¶) ¶$2$1 ``` Reverse the text between the duplicates and move it back to the input area. ``` ¶¶ ``` Join the output area with any remaining text in the input area. [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` f(h:t)|(a,u:v)<-span(/=h)t=u:f(reverse a++h:v)|0<1=h:f t f e=e ``` [Try it online!](https://tio.run/##RZFBa9xADIXv/hU6FOIlXtrS23YdaHYpgTaQrA85y2vZHjoeGY28sU3@@1aTQHvV994b6U2P8Q95f722eb/TzVuOxbS7bPbbOGLIP5f9Rstp1@ZCF5JIgLe3vfG3L/uvZb9rQbMWqKTrgC6UDWeQu4L/22/Km83@011H@tsFysCTwly64BTc96VshEf4BmYbxQXNW4PlUszFsskgRV4rDE3NM7Qs8GRqjtTAoUfvKXQUobyDCvuDsSQxPoPpI4WkaJIkO7D3qGsBFYsWcKKRUJPxwBUUq0riNjxBoajZizi1O6HFqNtO@NWFDjBGGmq/QDuFszoOyf8iXZhahMXXgzmieaDbKsWo58AW417ZhexIZx5GsbGlViOmGh9Rxc0p5EiCgI8QoyiOA5/JcGV1zNmJa9Ce4JdtsIMHmrFju8vM68flJ7a5UdPRA3jsggWZY8XZ7j6SkgxWO7jWXm5Yc1tkwI2VzZ3gAFajxo8llM@5ehxQTOKgNZuMJoBBOm7ATKRWpbdqo8K9CygL/BT8V4YhWyRRd29gAT2jYMieJ36vUzApbfswDTVJsjxPAZXqYWKnFiIm84CSVewv9H75D@8opH@vCcZpXT29fzjLk6EL9QqGyfl1nUYgb7K/ "Haskell – Try It Online") [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 29 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⌽@(⍳(≢c)|c⍳⍞←⍵∩⍨⊃⍵)⊢c←1↓⍵}⍣≡ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q37Us9dB41HvZo1HnYuSNWuSgcxHvfMetU141Lv1UcfKR70rHnU1A9maj7oWJQOFDR@1TQZyax/1Ln7UuRAA&f=fZGxTsMwEIb3PMVtAalIsLJBKlQJVSqNEPOlOaeWbJ91vkCaB2ADsbDycHkS3K6k7N/v3/93BsoaQ9vwAIYFNsKRE7VQ7dE5Ch2lspg@fqb3r@nz@7mq4ea6KAyUFTuHOi6gZtEFbCkS6jz6IlYJEAwmveqE32zoAFMi37gDmD7s1HKYzy5pxz4KpZQfqCNKIlijih3m@S03oHuCx9xxCysasOOALmfGc0uWpCTeBgJrcknLepE7PV5CFO4EPWQVek6Dy7aSwr0NKAd4EPxnzFPPJxGCRyb/KvS@IZmHa3avdNpy5yyF42UagtiPo6O/iV8&i=AwA&r=tio&l=apl-dyalog&m=dfn&n=f) A dfn submission which takes the string as argument and outputs to STDOUT. Shortened from 32 with Bubbler's help. [Answer] # [PHP](https://php.net/), 121 bytes ``` for($a=$argn;$c=$a[$i++];)for($j=0;2*$j<-$i+$p=strpos($a,$c,$i);$a[$p-$j]=$b){$b=$a[$j+$i];$a[$j+$i]=$a[$p-++$j];}echo$a; ``` [Try it online!](https://tio.run/##PY0xC8IwEIX/SocbrGlBXK/BQegsOEqHtI1tQskdSQdB/OvGs4LL4/Huu/d45tycWPROcQdGg4lTQBjE3MAp1WG5Xbw@4HEPvqklBdZpjUxJPioYKnAlfnmuwXca@vIJ/VbgFbgO/07/IKUEw5cdZgKDOV9NGHt6FDJUXCJJrx2L82yWxYbJpjfx6iikXLcf "PHP – Try It Online") PHP still competing for one of the worse golfing language with brio! For the record, my best version with appropriate string functions is just the same number of bytes: # [PHP](https://php.net/), 121 bytes ``` for($a=$argn;$c=$a[$i++];)if($p=strpos($a,$c,$i))$a=substr_replace($a,strrev(substr($a,$i-1,$l=$p-$i+2)),$i-1,$l);echo$a; ``` [Try it online!](https://tio.run/##NY5BC8IwDIX/yg45rKw76LUWD4JnwaOIdF22FUoT2in@emtUvITkvY/3wgvX3Z5lTpRbcBZcnpMBL8sFQtddjQpTC2zLmpmKIBq8hqCUwOU@iHzLyNF5/HhyZny0P@MLh36jIVrgXuK2Sv0VZdAvBM7UenZpHOjZyAvNKZPU4NgcFhcjphnLi3gNlErtj28 "PHP – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 96 bytes ``` f=lambda s,i=0:i<len(s)and f(i<(j:=s[i+1:].find(s[i])+i+1)and s[:i]+s[j:i:-1]+s[j:]or s,i+1)or s ``` [Try it online!](https://tio.run/##RdLBbtswDAbge5@CyCU26gzrOmCD0QxYWwwFhgJdc9ghy4G2aUedLAkU3SYu@uwZlaSZT7JE078/M2xl7d3l18C7XTu32FcNQizM/GNpriy5LOboGmgzc5U9lfO4NOcX5epDa1yT6c0qP9eNfUlclmZ1HpdPpSlnF4fVynNqphVpsROKEmEO2WShT1R@A63uP7APPlIDN2u0@sqO4qSAyY23FmUsYOFZCnikQCjp4DcbIUBoMcqsY/9iXAcYI/WV3UI7uFqMd6nylmrfB6YYtXwRkCPBPQqbTTp99BXImuCnPl/CHW2w8w6tVoyHBLckxL1xBKbVBo2XTPv1mENg3zH2oIHlENbqF0SBa@OQt/CD8RTi1@D3cRnTjvZ3Q18Rp6OFt8@0z/DdGnJJoiIIwzhamuRntAlUi8IcxNY3WpDElGsDyhfJJbDmv9gCilE4wanWIxTyLta5oUXY2qrXKFHtoJvp34hSO6@c5sWboxgj4D3EyIKh9zUp2SKcxBRKuRSO7sBi57RU44@4OYn5OhMdI2SVMqBzQhzUCXrufANqRycxbZTQzLV6bUFqZDyKORSq@sEb8Q5YI1vAoxg/KNYzrQUUjIwdxyEAWYVTsXpN9V/iBDb9M3z68rmeFrBfXVxO87M0bVLo73QwmpDtx7GAd@a8PAO90oC2meT7G/1yJ1k7nbzK2wRm32DyGnXxenzRkubzuHqb5rt/ "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ !!!Batch is another derivative of the Windows Batch programming language, its wiki is [here](https://esolangs.org/wiki/!!!Batch) Your challenge is to create an compiler/translator that reads a !!!Batch program and returns a Windows Batch program. In !!!Batch each token braced in two question marks like `?!!!?` is converted to another ASCII character, like '?!?' -> 'a' and so on below, and after decoding the whole !!!Batch program it is a Windows batch program ``` '?!?', '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' '?!-?', '&' '?!!-?', ' ' '?!!!-?', '?' '?!!!!-?', '!' '?!!!!!-?', '%' '?!!!!!!-?', '/' '?!!!!!!!-?', '.' '?!!!!!!!!-?', ':' '?!!!!!!!!!-?', '0' '?!!!!!!!!!!-?', '1' '?!!!!!!!!!!!-?', '2' '?!!!!!!!!!!!!-?', '3' '?!!!!!!!!!!!!!-?', '4' '?!!!!!!!!!!!!!!-?', '5' '?!!!!!!!!!!!!!!!-?', '6' '?!!!!!!!!!!!!!!!!-?', '7' '?!!!!!!!!!!!!!!!!!-?', '8' '?!!!!!!!!!!!!!!!!!!-?', '9' '?!!!!!!!!!!!!!!!!!!!-?', '=' '?!!!!!!!!!!!!!!!!!!!!-?', '+' '?!!!!!!!!!!!!!!!!!!!!!-?', '-' '?!!!!!!!!!!!!!!!!!!!!!!-?', '<' '?!!!!!!!!!!!!!!!!!!!!!!!-?', '>' '?!!!!!!!!!!!!!!!!!!!!!!!!-?', '@' '?!!!!!!!!!!!!!!!!!!!!!!!!!-?', '*' '?!+?', 'A' '?!!+?', 'B' '?!!!+?', 'C' '?!!!!+?', 'D' '?!!!!!+?', 'E' '?!!!!!!+?', 'F' '?!!!!!!!+?', 'G' '?!!!!!!!!+?', 'H' '?!!!!!!!!!+?', 'I' '?!!!!!!!!!!+?', 'J' '?!!!!!!!!!!!+?', 'K' '?!!!!!!!!!!!!+?', 'L' '?!!!!!!!!!!!!!+?', 'M' '?!!!!!!!!!!!!!!+?', 'N' '?!!!!!!!!!!!!!!!+?', 'O' '?!!!!!!!!!!!!!!!!+?', 'P' '?!!!!!!!!!!!!!!!!!+?', 'Q' '?!!!!!!!!!!!!!!!!!!+?', 'R' '?!!!!!!!!!!!!!!!!!!!+?', 'S' '?!!!!!!!!!!!!!!!!!!!!+?', 'T' '?!!!!!!!!!!!!!!!!!!!!!+?', 'U' '?!!!!!!!!!!!!!!!!!!!!!!+?', 'V' '?!!!!!!!!!!!!!!!!!!!!!!!+?', 'W' '?!!!!!!!!!!!!!!!!!!!!!!!!+?', 'X' '?!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Y' '?!!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Z' ``` Example Input: ``` ?!!!!!!!!!!!!!!!!??!!!!!!!!!??!!!!!!!!!!!!!!??!!!!!!!??!!-??!!!!!!!??!!!!!!!!!!!!!!!??!!!!!!!!!!!!!!!??!!!!!!!??!!!!!!!!!!!!??!!!!!??!!!!!!!-??!!!??!!!!!!!!!!!!!!!??!!!!!!!!!!!!!? ``` Example output: ``` ping google.com ``` \*\*How the output? First break down into parts: ``` ?!!!!!!!!!!!!!!!!? -> 'p' ?!!!!!!!!!? - 'i' ``` and so on * For more clarification, please visit the [Wiki](https://esolangs.org/wiki/!!!Batch) or ask me here. * Standard loopholes apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins An un-golfed sample compiler in python 2, from the Wiki page > > > ``` > s = open(raw_input("Run Script: "), 'r').read() > s = s.replace('?!?', 'a') > s = s.replace('?!!?', 'b') > s = s.replace('?!!!?', 'c') > s = s.replace('?!!!!?', 'd') > s = s.replace('?!!!!!?', 'e') > s = s.replace('?!!!!!!?', 'f') > s = s.replace('?!!!!!!!?', 'g') > s = s.replace('?!!!!!!!!?', 'h') > s = s.replace('?!!!!!!!!!?', 'i') > s = s.replace('?!!!!!!!!!!?', 'j') > s = s.replace('?!!!!!!!!!!!?', 'k') > s = s.replace('?!!!!!!!!!!!!?', 'l') > s = s.replace('?!!!!!!!!!!!!!?', 'm') > s = s.replace('?!!!!!!!!!!!!!!?', 'n') > s = s.replace('?!!!!!!!!!!!!!!!?', 'o') > s = s.replace('?!!!!!!!!!!!!!!!!?', 'p') > s = s.replace('?!!!!!!!!!!!!!!!!!?', 'q') > s = s.replace('?!!!!!!!!!!!!!!!!!!?', 'r') > s = s.replace('?!!!!!!!!!!!!!!!!!!!?', 's') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!?', 't') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!?', 'u') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!?', 'v') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!?', 'w') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!?', 'x') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!?', 'y') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!!?', 'z') > s = s.replace('?!-?', '&') > s = s.replace('?!!-?', ' ') > s = s.replace('?!!!-?', '?') > s = s.replace('?!!!!-?', '!') > s = s.replace('?!!!!!-?', '%') > s = s.replace('?!!!!!!-?', '/') > s = s.replace('?!!!!!!!-?', '.') > s = s.replace('?!!!!!!!!-?', ':') > s = s.replace('?!!!!!!!!!-?', '0') > s = s.replace('?!!!!!!!!!!-?', '1') > s = s.replace('?!!!!!!!!!!!-?', '2') > s = s.replace('?!!!!!!!!!!!!-?', '3') > s = s.replace('?!!!!!!!!!!!!!-?', '4') > s = s.replace('?!!!!!!!!!!!!!!-?', '5') > s = s.replace('?!!!!!!!!!!!!!!!-?', '6') > s = s.replace('?!!!!!!!!!!!!!!!!-?', '7') > s = s.replace('?!!!!!!!!!!!!!!!!!-?', '8') > s = s.replace('?!!!!!!!!!!!!!!!!!!-?', '9') > s = s.replace('?!!!!!!!!!!!!!!!!!!!-?', '=') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!-?', '+') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!-?', '-') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!-?', '<') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!-?', '>') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!-?', '@') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!-?', '*') > s = s.replace('?!+?', 'A') > s = s.replace('?!!+?', 'B') > s = s.replace('?!!!+?', 'C') > s = s.replace('?!!!!+?', 'D') > s = s.replace('?!!!!!+?', 'E') > s = s.replace('?!!!!!!+?', 'F') > s = s.replace('?!!!!!!!+?', 'G') > s = s.replace('?!!!!!!!!+?', 'H') > s = s.replace('?!!!!!!!!!+?', 'I') > s = s.replace('?!!!!!!!!!!+?', 'J') > s = s.replace('?!!!!!!!!!!!+?', 'K') > s = s.replace('?!!!!!!!!!!!!+?', 'L') > s = s.replace('?!!!!!!!!!!!!!+?', 'M') > s = s.replace('?!!!!!!!!!!!!!!+?', 'N') > s = s.replace('?!!!!!!!!!!!!!!!+?', 'O') > s = s.replace('?!!!!!!!!!!!!!!!!+?', 'P') > s = s.replace('?!!!!!!!!!!!!!!!!!+?', 'Q') > s = s.replace('?!!!!!!!!!!!!!!!!!!+?', 'R') > s = s.replace('?!!!!!!!!!!!!!!!!!!!+?', 'S') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!+?', 'T') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!+?', 'U') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!+?', 'V') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!+?', 'W') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!+?', 'X') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Y') > s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Z') > print s > > ``` > > [Answer] # JavaScript, 118 bytes ``` s=>s.replace(/.+?\?/g,x=>x[i=x.length-2]>','?'& ?!%/.:0123456789=+-<>@*'[i-2]:String.fromCharCode(x[i]<'+'?96+i:63+i)) ``` [Try it online!](https://tio.run/##hY5BDoIwEEWvIgstWFoUFIVQxoQjuEQWBAvUICWFGG6PJBA2Jjir@S8vM/@VftI2U6LpSC2ffMjZ0LKwpYo3VZpx3aIYHmAVZs/CPhaspxWvi64kdhIiEwHabUDbWtQ/HG3ndHYvV49hEoS3PYrFKPn3Tom6oLmS76hMVTQ@0cdDSYAwAs/FwncdLAxjyGTdyorTShZ6riPQ5sEwrbCQf2kG5Ieu6uvSlBZGAI2Vvw "JavaScript (Node.js) – Try It Online") --- # JavaScript, 118 bytes ``` s=>s.replace(/.!+(.??)\?/g,(x,y)=>(i=x.length,y>','?'& ?!%/.:0123456789=+-<>@*'[i-4]:String.fromCharCode(61+i+33*!y))) ``` [Try it online!](https://tio.run/##hY5LDoIwGISvIgttS2kRQXzE8ptwBJfqgmCBGqSmECOnRxKIGxOc1cyXSWbuySupU6OeDav0TXaZ6GoR1dzIZ5mkErvcopgDkAu4uYPfTktEhJV481JWeVM4bYQcBGgxA2vu8v3SW/nBOtxsd4KyQ3S00Vmx4Lo/NUZVOc@MfsRFYuJ@C4ceVdT3baslhHSprmpdSl7qHGcYgTWKwmDhS/6lEbAfOlmfLg3pyxig/vIH "JavaScript (Node.js) – Try It Online") Quite trivial answer. --- Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), changing `String.fromCharCode(n)` into `Buffer([n])` under Node.js environment may save 11 bytes and results [107 bytes](https://tio.run/##hY5BDoIwEEWvIgsdtLQoKAqhHeM1kAXBFmsIEEDD7ZEEwsYE/2r@y5vkv5JP0qS1rlpalA/ZK943XDSsllWepNK0GcE72pnVcdFFmncsl0XWPqkTC7AAYbNCY22zYH9w3OPJO198TmgorjuI9CAFt7dSsjaj4TkOgQD6HtGB5xIdb7d9WhZNmUuWl5mpTEBjCsHxxJn8axOgP3RRX5bGNjOKMEz@Ag). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¬¡õKεθ„!+skADužh"& ?!%/.:ÿ=+-<>@*")ćèyć¢è ``` Output as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//0JpDCw9v9T639dyORw3zFLWLsx1dSo/uy1BSU7BXVNXXszq831Zb18bOQUtJ80j74RWVR9oPLTq84n@t1397RTRgb4@NicoHMXRReLiMwKIRQxguCDGSkHH2AA) (the footer is to join the resulting list to pretty-print as string; feel free to remove it to see the actual list output). **Explanation:** ``` ¬ # Push the first character of the (implicit) input-string: "?" ¡ # Split the input on that character õK # Remove all empty strings ε # Map over each string: θ # Pop and push its last character „!+ # Push string "!+" sk # Get the index of the last character in this string, # (-1 if not found, for the "-") A # Push the lowercase alphabet Du # Create an uppercase copy žh # Push builtin "0123456789" "& ?!%/.:ÿ=+-<>@*" # Push this string, where the `ÿ` is automatically filled with 0123456789 ) # Wrap all values into a list ć # Extract head; pop and push remainder-list and first item separated è # Use this index to (0-based modulair) index into the triplet # (where the -1 for "-" will index into the last item) y # Push the current string again ć # Extract its head as well: "!" ¢ # Count how many times it occurs in the remainder-string è # 0-based index this into the string # (after the map, the resulting list of characters is output implicitly) ``` Unfortunately the `"& ?!%/.:0123456789=+-<>@*"` is a bit too irregular to compress. The shortest alternative I could find for this straight-forward string was `žQ33£S•1δÁεöI‡β₆¡ÙÞ‹f31•.I` (`žQ` push printable ASCII builtin; `33£` leave just its first 33 characters; `S` convert it from a string to a list of characters; `•1δÁεöI‡β₆¡ÙÞ‹f30•.I` get the 1586478393328926104294588200482791040th permutation of this list), which is 6 bytes longer. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~53~~ 46 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é♫▼V0⌂Ä╟ì⌡(Φzf■£┘╔╣T╘K*╪☻w²¥íÑ╧zv-¼Ö╨◘P♦ε♦íäq* ``` [Run and debug it](https://staxlang.xyz/#p=820e1f56307f8ec78df528e87a66fe9cd9c9b954d44b2ad80277fd9da1a5cf7a762dac99d0085004ee04a184712a&i=%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%3F%3F%21%21-%3F%3F%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21-%3F%3F%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%3F%3F%21%21%21%21%21%21%21%21%21%21%21%21%21%3F) I wasn't able to find an expression that matches the symbols, so those are hardcoded (and take a lot of space.) ## Explanation `'?/{f{%_rh.-+I{"@*& ?!%/.:"Vd+"=+-<>"+@}{63+}{96+}3l@!m` `'?/` split on `?` `{f` remove empty lists `{..m` map the strings to: `%` push the length of the match `_` push the match again `rDh` get the second to last character `.-+I` index of that in "-+" `@!` execute the corresponding block for the index: `{"<>@*& ?!%/.:"Vd+"=+-"+@}{61+}{94+}3l` create a list of 3 blocks `{63+}` for `+`, add 63 to the length `{"@*& ?!%/.:"Vd+"=+-<>"+@}` for `-`, index into `<>@*& ?!%/.:0123456789=+-` using the length(modular) `{96+}` otherwise add 91 [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~142~~ ~~139~~ ~~130~~ 115 bytes Thanks to tsh for the -3 and gastropher for the -9. The function uses a state machine to determine the boundaries of each token: * loop: load the next input character until the end of the string * state 0 (initial `?`): clear the counter, then go to state 1 * state 1 (`!`, `+`, `-` or terminating `?`): increment on a `!`, otherwise print the character (adjusted count by 96 [`?`] or 64 [`+`], or indexed symbol [`-`]) and go to state 0, incrementing the input string if a `+` or `-`. ``` t,c,n;f(char*s){for(;c=*s++;)n=t?c-33?t=!putchar(c-63?s++,c-43?" & ?!%/.:0123456789=+-<>@*"[n]:n+64:n+96):n+1:t++;} ``` [Try it online!](https://tio.run/##hZDBTsMwEETv/oqNEch24kJJCDSu635AxY1T1UO0IW2k4qDahUOVXyc4PSClQuDD6o1nPZYG5Rax732CiVU1w115EI6f6vbAFGrh4lhxq71BmabG6@j96IcdhjJPTXATlFlqKNyAia5vJ8Xd9D7NHvLHp5mO5XyxFHRtN4WN8yyMWc7DnBY@pHb9VWNxf6xeYe581bST3YKQxnp4KxvLPtqm4nAiAMN3INx6owcFQE10cYz5Dcd6AGnoOOFy@4@LsTMO@vHkmf5LNTQ5v35@Wa0CdAkI4RUJOLTutVMQNISmHaOUc6iZCI1xRbr@C@t9uXW9/PwG "C (gcc) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~94~~ 94 bytes ``` \?! ! !\? a !\+\? A - !{5}\? % +T`_o`lL%/.:d=+\-<>@*!_`!(?![?!]). !\? $& & !(?=..(.))!*... $1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/xl6RCwhj7LkSgaQ2kHbk0uXiUqw2rQWyVbm0QxLi8xNyfFT19axSbLVjdG3sHLQU4xMUNewVo@0VYzX1wJpV1BTUuIBitnp6Gnqamopaenp6XCqG///bK6IBe3tsTFQ@iKGLwsNlBBaNGMJwQYiRhIyzBwA "Retina 0.8.2 – Try It Online") Edit: +1 byte to fix a bug but -1 thanks to @tsh. Explanation: ``` \?! ! ``` Remove the `?` at the start of a token. ``` !\? a ``` `?!?`, which is now `!?`, translates to `a`. ``` !\+\? A ``` `?!+?`, which is now `!+?`, translates to `A`. ``` - ``` Get rid of the `-`s. ``` !{5}\? % ``` `?!!!!!-?`, which is now `!!!!!?`, translates to `%`. ``` +T`_o`lL%/.:d=+\-<>@*!_`!(?![?!]). ``` For each additional `!`, cycle the following character; letters get incremented, while `d` represents digits which nestle among the symbols. ``` !\? $& & ``` The remaining `!?`s represent one of `!`, `?`, and `&` in reverse order, depending on the number of preceding `!`s. Add the other characters so that the correct decode can be selected. ``` !(?=..(.))!*... $1 ``` Decode the remaining `!?`, `!!?`, `!!!?` and `!!!!?` sequences appropriately. [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~96~~ ~~84~~ 83 bytes ``` say map/-/?substr' & ?!%/.:0123456789=+-<>@*',y///c,1:chr/!$/*32+64+y///c,/[^?]+/g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7FAX1ffvrg0qbikSF1BQU3BXlFVX8/KwNDI2MTUzNzC0lZb18bOQUtdp1JfXz9Zx9AqOaNIX1FFX8vYSNvMRBsiqh8dZx@rrZ/@/7@9Ihqwt8fGROWDGLooPFxGYNGIIQwXhBhJyDj7f/kFJZn5ecX/dX1N9QwMDf7r5gEA "Perl 5 – Try It Online") [Answer] # [Julia](http://julialang.org/), ~~108~~ ~~104~~ 102 bytes -4 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s better regex ``` s->replace(s,r".+?\?"=>x->(a='.'-x[(l=end)-1];["_& ?!%/.:0123456789=+-<>@*_"[l-2],l+'^',l+'='][a%11])) ``` [Try it online!](https://tio.run/##hVFhT8MgFPzeX/FKMoG1VOnc1Cmw/8HYQmqbYLAunSb8@wo1aqYzXvLg3uXekTye3ryzPIydGI9MDu3B26Ylx3JAVaG2CgkZmCRW4AqzoIkXbf9IGTf3Gu0vQOWzy2p9xevF9XJ1c3snCvYgN/M90p7VpvQF3uF0Cmy0nXFuKB0Pg@tffU86glT@A0qdo6d9Iuyk@yvizOAv@Uv8iPwvTiFKs6x7GYA0pXu2gYLrQaO4p3pVAmKJLCMpJsVkEJHsLvn4Oo1M2oQAApBCMAec452LdxMrKt@Wz21Fq4SOhPh8kuMvZLHGdw "Julia 1.0 – Try It Online") [Answer] # Batch ~~1139~~ ~~1034~~ ~~1009~~ 975 bytes. *Ouch!* Though I couldn't resist making a batch !!!batch translator. ``` @Echo off&Set $=Set &Set _=%* %$%_=%_:??=? ?% %$%"_=%_:!=^!%"&%$%".=!!!!" %$%"..=%.%%.%" %$%"...=%..%%..%" %$%?!-?=^&&%$%"?!!-?= "&%$%?!!!-?=?&%$%"?%.%-?=^!"&%$%"?%.%!-?=%%"&%$%?%.%!!-?=/ %$%?%.%!!!-?=.&%$%?%..%-?=:&%$%?%..%!-?=0&%$%?%..%!!-?=1&%$%?%..%!!!-?=2&%$%?%..%%.%-?=3 %$%?%..%%.%!-?=4&%$%?%..%%.%!!-?=5&%$%?%..%%.%!!!-?=6&%$%?%...%-?=7&%$%?%...%!-?=8 %$%?%...%!!-?=9&%$%?%...%!!!-?==&%$%?%...%%.%-?=+&%$%?%...%%.%!-?=-&%$%?%...%%.%!!-?=^< %$%?%...%%.%!!!-?=^>&%$%?%...%%..%-?=@&%$%?%...%%..%!-?=*&Setlocal EnableDelayedExpansion %$%e=&For /l %%i in (97 1 122)Do (%$%"e=!e!^!"&Cmd/cExit %%i %$%"?!e!?=!=ExitCodeASCII!"&For /f delims^= %%v in ('cmd/c%$%/A%%i-32')DO Cmd/cExit %%v %$%"?!e!+?=!=ExitCodeASCII!") %$%#=&%$%p=%%&%$%i=0&%$%"T[0]=%_: ="&Set/Ai+=1&Set "T[!i!]=%" For /l %%i in (0 1 !i!)Do For /f "tokens=1 delims==" %%v in ('%$%T[%%i]')Do (IF defined # (Call %$%"#=!#:^^=^!!p!!%%~v!!p!")Else Call %$%"#=!p!!%%~v:^^=^!!p!") Echo(!#:^^=!&Endlocal ``` How: * assigns each command token as a variable with it's respective character. * Split input on ??, assign each to a token array - T[#] * Iterates through the array of command tokens, expands each to its value (character) and appends to the command line variable # Notes: * run from the command line, input is as taken as a command line argument. * requires delayed expansion to be disable (default) [Answer] # [Red](http://www.red-lang.org), ~~164~~ 158 bytes ``` func[s][r: copy""parse s[any["?"(n: 0)any["!"(n: n + 1)]["+?"(c: to sp 64 + n)|"-?"(c: pick"& ?!%/.:0123456789=+-<>@*"n)|"?"(c: to sp 96 + n)](append r c)]]r] ``` [Try it online!](https://tio.run/##hYzLDoIwEEX3fMXQREMlKCqiNGr9BrdNF6SUhJiUpuCCqN@OPBIjinFW99yZOUYm9VkmjFspgTq9KsEKzgwBkesKIR2bQkLBYlUxRJGjCPi4A7sDBS4sMWfIbZaCQJlDoSEMwLUUviOvb3UmLmgK1J4s5sRfrtbBJtzuooPr7Y@nGWov39@jsLEqzJ1Ya6kSMCAw54bX2mSqhBRu1P4YSsfikNvgDeiXYuTxq36VvfKfjj7qJw "Red – Try It Online") ## Old, non-Parse solution, 169 bytes ``` func[s][r: copy""foreach c extract next split s"?"2[d: length? c append r switch to 1 last c[33[to sp 96 + d]43[to sp 63 + d]45[pick"& ?!%/.:0123456789=+-<>@*"d - 1]]]r] ``` [Try it online!](https://tio.run/##hYzBisIwFEX3/YprQBdKdWq1apkxfsNsQxYlSW2xpCHJMDPIfHusyAhqxbd43HN571glw6eSjEdljlB@acEcZzaHaM0vIWVrVSEqCKgfbwvhobsAZ5q624SSOZM5GqX3vqLdVWGM0hIW7rv2oop8iwRN4TwES1PWoTPYZJhA8sU/Z@mFl8zU4kBGoIPhbJq/JfN0scxW683HJH7f7sZEIkbCObc8GFtrjxJHOrgbSvviLZ9DfEPPFD2PD/W1vChf6ehfOAE "Red – Try It Online") [Answer] # Python 2, ~~191 161~~ 133 bytes -30 Thanks Kaddath! -28 Thanks tsh! ``` for e in input()[1:-1].split("??"):print(end={"!":chr(len(e)+96),"+":chr(len(e)+63),"-":('<>& ?!%/.:0123456789=+'*9)[len(e)]}[e[-1]]) ``` [Try it online!](https://tio.run/##hYzRCoIwGIXvfYr5Q7nltNSylGy9h3ghMlEYc9iCInp2S4TCMjpX53xwPnXVVSP9rsupTmqpzhqT1IsdL3NPStQaA2NAKIBRNi3iqJYojw1UUkFVUlQtFVxiTihPnxcD8Qsv8A1MiEHbSYmFHYUEKNhvEAY9cAZgHRdzxMzZ0o1Xnh@sN@F2FyX2/mClIoN7qjJiqLaWGumuA2Z@hLGpOt59cUbrl2Li@IVfcFD@0zF4AA) ## Explanation (Will update this later) Ungolfed: ``` a = input[1:-1].split("??") # Get every part t = "" # Output string for e in a: # Iterates over a f,l,p=chr,len(e),e[-1] # They are used many times, this is for shorter code exec({ "!":"t+=f(l+96)", # if ends with "!", get the l+96 -th ASCII char "+":"t+=f(l+63)", # ends with "+", get the l+63 -th "-":"t+='@*& ?!%/.:0123456789=+<>'[l]" # hard-coded string }[p]) print t # print the result ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` ⭆⪪S?⎇№ι!§⎇№ι-”‴"μ⮌w7L⁴Vp#ωδk4θO(”⎇№ι+αβ⊖№ι!ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQX5GSWaHjmFZSWQAQ1NHUUlOyVgGRIalFeYlGlhnN@KVBLJlBYESTsWOKZl5JaoYEprQuSVlJTsFdU1dezMjA0MjYxNTO3sLTV1rWxc9BSwmakNkhPoo5CkiaQdklNLkrNTc0rSU1BtRUkmQkkrf//t1dEA/b22JiofBBDF4WHywgsGjGE4YIQIwkZZ/9ftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⭆⪪S? ``` Split the input on `?`s and map over each substring. ``` ⎇№ι! ``` If this substring contains a `!`, then... ``` §⎇№ι-”‴"μ⮌w7L⁴Vp#ωδk4θO(”⎇№ι+αβ⊖№ι! ``` ... count the number of `!`s and use this to index into either the compressed string of non-alphabetic characters or the upper or lower case alphabet depending on whether there is a `-` or `+` or not. ``` ι ``` Otherwise leave the substring unchanged. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 125 bytes ``` s=>s.split`?`.map(a=>(b=a.length)?(z=a.slice(-1))==`-`?'& ?!%/.:0123456789=+-<>@*'[b-2]:Buffer([b+(63*z==`+`||96)]):a).join`` ``` [Try it online!](https://tio.run/##hYzRCoIwAEV/pR7KTdlKLStpLvoNCTZtK2M5cdaD@O9mBIFldJ/uuXDPhd@5ScusqFCuj6KVpDUkMtgUKqsYZfjKC8BJBBLCsRL5qTpDCuoOjMpSAZALISEMMWpNR3Q8meFw7nr@Yhms1hvioG20s604Qd4h3N@kFCWIEwcEvl13L4c1zSaABxhyiC86yxlrU50brQRW@gQksOj4I5QO1T4/C@rRL8XA8Wt@jy/lPx21IGwf "JavaScript (Node.js) – Try It Online") ``` s.split`?` splits the string at the char ?, results in an array .map(a=> pass item n in array to function and replace item with the return (b=a.length)?... if a is not empty do ... a.slice(-1)==`-`?... if last char in a is - do ... '& ?!%/.:0123456789=+-<>@*'[b-2] get character at index : else Buffer(b+(63*z==`+`||96)) character from code :a else return a ).join`` array to string ``` ``` ]
[Question] [ ### Introduction A double-castle number™ is a positive integer number that has a pattern of $$\underbrace{a\cdots a}\_{m\text{ }a\text{s}}b\underbrace{a\cdots a}\_{m\text{ }a\text{s}}b\underbrace{a\cdots a}\_{m\text{ }a\text{s}}\underbrace{a\cdots a}\_{n\text{ }a\text{s}}b\underbrace{a\cdots a}\_{n\text{ }a\text{s}}b\underbrace{a\cdots a}\_{n\text{ }a\text{s}}$$ Where \$m>0\$, \$n>0\$ and \$a-b=1\$ are all non-negative integers, when represented in an integer base \$B\$ where \$B\ge2\$. It is so named because a bar chart representing the base-\$B\$ digits of such a number resembles two castles of the same height place- side by side. For example, \$7029\$\* is a double-castle number because when represented in base 2 it becomes \$1101101110101\_2\$, which can be split into \$11011011\$ and \$10101\$. [![enter image description here](https://i.stack.imgur.com/WwmC1.png)](https://i.stack.imgur.com/WwmC1.png) This is the case when \$m=2\$, \$n=1\$, \$a=1\$, \$b=0\$ and \$B=2\$. \$305421994212\$ is also a double-castle number because when represented in base 8 it becomes \$4343444344344\_8\$, which can be split into \$43434\$ and \$44344344\$. [![enter image description here](https://i.stack.imgur.com/MIhKU.png)](https://i.stack.imgur.com/MIhKU.png) This is the case when \$m=1\$, \$n=2\$, \$a=4\$, \$b=3\$ and \$B=8\$. For \$a>=10\$, \$a\$ should be treated as a single base-\$B\$ "digit" with the value of \$a\$ in base-10. \$206247763570426655730674346\$ is a double-castle number in base-16, whose representation in base-16 is \$\text{AA9AA9AAAAAA9AAAA9AAAA}\_{16}\$. Here, \$a=10\$ but is treated as a single digit \$(10)\_{16}=\text{A}\_{16}\$. [![enter image description here](https://i.stack.imgur.com/6xXmK.png)](https://i.stack.imgur.com/6xXmK.png) This is the case when \$m=2\$, \$n=4\$, \$a=10\$, \$b=9\$ and \$B=16\$. ### Challenge Write a program or function that, given integers \$m>0\$, \$n>0\$, \$1\le a<B\$ and \$B\ge2\$, calculate the corresponding double-castle number™ and output it in base-10. ### Test Cases The input below are in base-10, but in the case say when \$a=11\$ and \$B=12\$ the input should be understood as \$B\_{12}\$. ``` m, n, a, B => Output 1, 1, 1, 2 => 693 2, 1, 1, 2 => 7029 1, 2, 3, 4 => 62651375 1, 2, 4, 8 => 305421994212 1, 4, 7, 10 => 7676777776777767777 2, 4, 8, 16 => 164983095594247313234036872 2, 4, 10, 16 => 206247763570426655730674346 ``` ### Winning Condition This is a code-golf challenge, the shortest submission in each language wins. No standard loopholes allowed. \*7029 comes from my ID minus it written reversed. [Answer] # [Python 2](https://docs.python.org/2/), ~~83 81 79~~ 72 bytes *-9 bytes thanks to @ovs!* *-2 bytes thanks to @dingledooper!* ``` m,n,a,B=input() r=0 for s in n,m+n,m,m:r+=B**n;n-=~s print~-B**n/~-B*a-r ``` [Try it online!](https://tio.run/##VY9NboMwEIX3PsUoG6CZpGCDCamcRc7RjZu4qiVsLHCrZJOr0zFBlepf@c2bT8/hHr8Gz@fLcDWgIMuy2aFHjWdlffiOecFGVbLPYYQJrAePbksb3XHcqvPLi3/zO/WYWBitj49dUl7TpXfjTDDGrAvDGGG6T2yh9NabBCJhP8Wr9UcGuUMCg0Y4FwjmFswlUhinQ25@dI9L034KvY15pk5ZUTBY0pGp1@7jqo/5mpoq5mYukP7DYEm1AhE2734zVwjPxQHUCWQnGP8vtSXvWHohCIT6aeOyqUTbrHqNcFh0UTY1r7qODp5qVGgJVS4cSTMN@XewtZcsMlkqWXcHUXZNQ4S6FZXgoi6FPLT8Fw "Python 2 – Try It Online") Calculate `aaaa...aaa` in base `B`, then subtract 1 at the appropriate digits. [Answer] # [C (gcc)](https://gcc.gnu.org/) -lm, ~~83~~ \$\cdots\$ ~~81~~ 80 bytes Saved ~~1~~ 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #define P-pow(B,n f(m,n,a,B){n=-(1 P*3+3*m+4))/~-B*a P)P-~n)P*3+2+m)P*3+3+2*m);} ``` [Try it online!](https://tio.run/##jZHfa4MwEMff@1ccjoKJCdXEn7juwbF339cyxGon1LSosEKxf/rcqdUW@rJ4d7ng574Xz5Tv07TrXnZZXqgMYn46/ugRU4tcL5liCYvIRa25bkFMpSFpadiErK48ognEJOZXRfoXwiiHHTNakrDtyqRQOoHLAnCl30lFofrcwhou2ub8ITbn4B3d0Rg8nqXWhkNFoRoKTVY3X@VYZTEQDKzJxBOnZm5E0Wy0Jy555OQAeQz8Jy4auVnJxwIT3X0ks/MpS5uRdANU80wRMHCF61jSc9oQVhSwjenYwgoCDCjmufj0y51Dr2sHvjQDx0HK9qQlhbRN6foefirQ1dAzP1agY2MosKEZ4vYKMgTDKKZJ324GNQK5fhtgsWXTjOY0uacRpiScy08VCuS6ttwxuDvwtz4u643SGPxfmEHN8M/jfdbTtIrt1K5dtN1vmh@Sfd3xQ/kH "C (gcc) – Try It Online") Calculates the wall to full height first and then crenellation is performed through subtraction. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` иεÐ)²<.ý}˜sβ ``` [Try it online](https://tio.run/##ASYA2f9vc2FiaWX//9C4zrXDkCnCsjwuw719y5xzzrL//1sxLDJdCjQKOA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQQuXh1uLQ/xd2nNt6eIJmhI3e4b21p@cUn9v0X@d/dHS0oY5hrI6hjlGsTnS0ERIbTBnrmMDZJjoWEDZQyFzH0ACiAcix0DE0g3MMDUC8WAA). +2 bytes as bugfix for \$a\geq10\$ (initial 10-byter answer: `×εЬ<ý}Jsö` - [Try it online](https://tio.run/##ASMA3P9vc2FiaWX//8OXzrXDkMKsPMO9fUpzw7b//1sxLDJdCjQKOA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQwv/D089tPTzh0Bqbw3trvYoPb/uv8z86OtpQxzBWx1DHKFYnOtoIiQ2mjHVM4GwTHQsIGyhkrmNoANEA5FjoGJrFxgIA)). **Explanation:** ``` и # Repeat the second (implicit) input the first (implicit) inputs amount of # times as list # i.e. [1,2] and 4 → [[4],[4,4]] ε # Map each to: Ð # Triplicate the value # i.e. STACK: [4,4],[4,4],[4,4] ) # Wrap them into a list # i.e. STACK: [[4,4],[4,4],[4,4]] ²< # Push the second input - 1 # i.e. STACK: [[4,4],[4,4],[4,4]],3 .ý # Intersperse this list with this value # i.e. STACK: [[4,4],3,[4,4],3,[4,4]] }˜ # After the map: flatten the list # i.e. [[[4],3,[4],3,[4]],[[4,4],3,[4,4],3,[4,4]]] # → [4,3,4,3,4,4,4,3,4,4,3,4,4] s # Swap to get the third (implicit) input β # Base-convert the list we created to an integer using the input as base # i.e. [4,3,4,3,4,4,4,3,4,4,3,4,4] and 8 → 305421994212 # (after which the result is output implicitly) ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 26 bytes ``` {z/,/(2+3*x)#'(x#'y),'y-1} ``` Explanation ``` {z/,/(2+3*x)#'(x#'y),'y-1} / using x=2 1; y=1; z=2 as an example (x#'y) / (m;n) copies of a; ex: (1 1;1) ,'y-1 / append b=a-1 to each ex: (1 1 0;1 0) (2+3*x) / length of each sublist ex: (8;5) #' / copy to each length ex: (1 1 0 1 1 0 1 1; 1 0 1 0 1) ,/ / join ex: (1 1 0 1 1 0 1 1 1 0 1 0 1) z/ / convert from base B ex: 7029 ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrpKX0dfw0jbWKtCU1ldo0JZvVJTR71S17D2f1q0oYKhtaG1UawCV1q0ERLbUMHI2tjaBM42sbaAsk2sza0NDWIV/gMA "K (ngn/k) – Try It Online") [Answer] # perl -Mbigint -alp, 87 bytes ``` ($m,$n,$a,$B)=@F;$o=$o*$B+$_ for(($a)x$m,$a-1)x2,($a)x$m,(($a)x$n,$a-1)x2,($a)x$n;$_=$o ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jva2D9X0MlV0clT0clUUfFSdPWwc0aKKySr6XipK0Sr5CWX6ShoZKoWQFSlKhrqFlhpAPjQyXy0CTyrFXigQb8/2@oAIJGXEZQGogVjBVMwLSJggWQNlEwVzA04AJzFQzN/uUXlGTm5xX/103MKfiv65uUmZ6ZVwIA "Perl 5 – Try It Online") We take the input, turn it into a corresponding list of digits, then convert it to base 10. Input is taken as space separated numbers on `STDIN`. The TIO code does have some header code; this is just there so it works with multiple inputs -- without the header, it will only do the first line correctly. (those header bytes aren't counted). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘3×þṬạṖ€Ẏḅ⁵ ``` A full program accepting three arguments: `[m,n] a B` which prints the result. **[Try it online!](https://tio.run/##ATIAzf9qZWxsef//4oCYM8OXw77huazhuqHhuZbigqzhuo7huIXigbX///9bMiw0Xf8xMP8xNg "Jelly – Try It Online")** ### How? ``` ‘3×þṬạṖ€Ẏḅ⁵ - Main Link: [m,n]; a ‘ - increment -> [m+1, n+1] 3 - three þ - outer product ([1, 2, 3] by [m+1, n+1]) with: × - multiplication -> indexes of low points (with an extra low on the right for each of castle) Ṭ - un-truth (vectorises) -> two lists of 1s and zeros (1s at low points) ạ - absolute difference (with a) -> convert zeros to a and 1s to a-1=b Ṗ€ - pop from each -> remove the extra low points) Ẏ - tighten -> from a list of two lists to a flat list ⁵ - programs 5th argument = B ḅ - convert dfrom base - implicit print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` Nθ≔⭆E²N⪫E³×0ι1δI⁻×N⍘⭆δ1θ⍘δθ ``` [Try it online!](https://tio.run/##VY3LCsIwEEX3/YohqwmMYOuyK3WlUBH0B2ITaqBN2zz8/dg0m5ZhGJh7OLf9CtuOoo/xZqbgH2H4KIszr4uzc7oz@PJWm64RE6atCLYc5wT3UZs1OxG89aAcsiMj0CljJUtHLrrnovF4Fc5jo01wmNmdjeAinMqNm2KZRQQz3yNyfXFex1gVZZp4@PV/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `B, m, n, a`. Explanation: ``` Nθ ``` Input `B`. ``` ≔⭆E²N⪫E³×0ι1δ ``` Input `m` and `n`. For each value, create a string of that many `0`s. Join 3 of those strings with `1`s. Join the final strings together. ``` I⁻×N⍘⭆δ1θ⍘δθ ``` Replace all of the characters in the string with `1`s, convert from base `B`, multiply by `a`, then subtract the string converted from base `B`, and output in decimal. Note that although Charcoal's string based conversion accepts numeric bases higher than 62 this only succeeds when (as here) all the digit values are less than 62. Slightly shorter solutions are possible that place upper limits on the supported value of `B`: ``` NθI↨E⭆E²N⪫E³×ι℅θ℅⊖θ℅ιN ``` [Try it online!](https://tio.run/##VY09DsIwDIX3niKjI4WBMnajLCDxI8EFTGqBpTQticv1Q5IFsGXJz5/9bJ8Y7IQupb2fFzkt450CvHTXXAJ7gR6jwBYjwRFnuEoePkpXqjXq90hrow4T@8o2Rt14pAhsVJ9/oJXqW5a@ekc20EheaKgsw3MY2KMDLuLfPkeX0rop2abV230A "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `a, m, n, B`. Works for `B` up to 65536. Works by creating a string of characters whose ordinal is `a` or `b`, then converting back into ordinals and decoding using base `B`. 22 bytes. ``` NθI⍘⭆E²N⪫E³×ι⍘θφ⍘⊖θφN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMpsTg1uATIT9eAUL6JBRogbKSjgKxNU1NHwSs/Mw8sZ6yjEJKZm1qskamjgGRAoY5CmiZIIZKYS2pyUWpual5JagrQapgCVJM1Na3//zfkAkGj/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `a, m, n, B`. Works for `B` up to 62. Works by creating a string of characters whose base `B` code is `a` or `b`, then decoding using base `B`. 21 bytes. ``` I⍘⭆E²N⪫E³×ιεI⊖εN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxODW4BMhP14BQvokFGiBspKPgmVdQWuJXmpuUWqShqamj4JWfmQeWM9ZRCMnMTS3WyNRRSAXJgI1ySU0uSs1NzStJTdEAioLEUU3Q1LT@/9@Qy5DLiMvwv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `a, m, n, B`. Works for `B` up to 10. Works by creating a string of characters whose value is `a` or `b`, then decoding using base `B`. 16 bytes. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS) ``` ⎕⊥⎕-~1\⍨∊5⍴¨⎕,¨0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqmPupYCSd06w5hHvSsedXSZPurdcmgFUEjn0AoDkKr/nGlcRgqGXIZcRlxApqGCEZcxlwkA "APL (Dyalog Unicode) – Try It Online") A full program that takes `m n`, `a`, `B` on three lines of stdin. ### How it works ``` ⎕⊥⎕-~1\⍨∊5⍴¨⎕,¨0 ⎕ ⍝ Take (m n) from stdin ,¨0 ⍝ Append 0 to each; (m 0)(n 0) 5⍴¨ ⍝ Repeat each to length 5; (m 0 m 0 m)(n 0 n 0 n) ∊ ⍝ Flatten; (m 0 m 0 m n 0 n 0 n) 1\⍨ ⍝ Expand 1 by above: m/n become m/n copies of 1, 0 becomes single 0 ~ ⍝ Boolean negate the above ⎕- ⍝ Subtract each from a (taken from stdin) ⎕⊥ ⍝ Convert from base B (taken from stdin) to integer ``` [Answer] # [J](http://jsoftware.com/), 35 bytes ``` {:@[#.((#10$5$0 1-~{.)~[:,5$"1,.&1) ``` [Try it online!](https://tio.run/##TY5NasNADEb3PYVITBKDM@hfHkMgEMiqq26zLA2lmx4gkKu7sh1MNehb6L0R@hk3ZX@H0wB76ABhyD4WuHy8X8fHcL5ty@GwJWysQaDj81Ha523orNlQV3bUju3b1@f3L3gVOAEBwz2TYJkGcl3HDPRy2Y0kLImAzh94IYKmTLVmcFKF/j8NzzeVr5FSAOFs6WKRa@0Fq1mu0RASFkXxPqaVffL5lpfN6CmFiwUqu5uFoIeK@nQ4rvr4Bw "J – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes ``` `BṁȯJ←¹R3`R ``` [Try it online!](https://tio.run/##ASMA3P9odXNr//9gQuG5gcivSuKGkMK5UjNgUv///zT/WzEsMl3/OA "Husk – Try It Online") Takes arguments in the order `a [m,n] B`. # Explanation ``` `BṁȯJ←¹R3`R Implicit arguments a, [m,n], B. Say a=3, m=1, n=2, B=4. ṁȯ Map over [m,n] and concatenate: Use n=2 as example. `R Repeat a that many times: [3,3] R3 Repeat three times: [[3,3],[3,3],[3,3]] ←¹ a decremented: 2 J Join by it: [3,3,2,3,3,2,3,3] Result: [3,2,3,2,3,3,3,2,3,3,2,3,3] `B Interpret in base B: 62651375 ``` [Answer] # JavaScript, 75 bytes There may be rounding errors due to JavaScript's integer limit. ``` (m,n,a,B)=>B**(3*(m+n)+4)/~-B*a-B**(n-~n)-B**(m+3*n+2)-B**(2*m-3*~n)-B**n-1 ``` [Try it online!](https://tio.run/##XY3NDsIgEITP@hQcgYKFXX7KQQ99k8ao0RRqrOnRV6/UEk1cyATmm8zeuqkbj4/r/SmnZj7vZxpFEp1o2f7Qck6R01glVhlWv2TLO7mYSb4S@7xihTxVsH6AR4m8oCT1fBzSOPSnXT9c6HZzplqQ9QITpK6JC7jY8Gd7BaHEM0JBTImDsxq9/TEjSLMyVNaADiELFJ6hz7WqlLp8lnFfKbuXkpxza047ExpUwdrcZTxqBDQKXeNhy@Y3 "JavaScript – Try It Online") ]
[Question] [ # Background The [traveling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) (TSP) asks for the shortest circuit that visits a given collection of cities. For the purposes of this question, the cities will be points in the plane and the distances between them will be the usual [Euclidean](https://en.wikipedia.org/wiki/Travelling_salesman_problem#Euclidean) distances (rounded to the nearest integer). The circuit must be "round-trip", meaning it must return to the starting city. The [Concorde TSP solver](https://en.wikipedia.org/wiki/Concorde_TSP_Solver) can solve instances of the Euclidean traveling salesman problem, *exactly* and much faster than one would expect. For example, Concorde was able to solve an [85,900-point instance](http://www.math.uwaterloo.ca/tsp/pla85900/index.html) exactly, parts of which look like this: [![Segment of Drawing of pla85900 Tour](https://i.stack.imgur.com/IDnTm.gif)](https://i.stack.imgur.com/IDnTm.gif) However, some TSP instances take too long, even for Concorde. For example, no one has been able to solve [this 100,000-point instance based on the Mona Lisa](http://www.math.uwaterloo.ca/tsp/data/ml/monalisa.html). (There is a $1,000 prize offered if you can solve it!) Concorde is [available for download](http://www.math.uwaterloo.ca/tsp/concorde/downloads/downloads.htm) as source code or an executable. By default, it uses the built-in linear program (LP) solver [QSopt](http://www.math.uwaterloo.ca/~bico/qsopt/), but it can also use better LP solvers like CPLEX. # The challenge What is the smallest TSP instance you can generate that takes Concorde more than *five minutes* to solve? You can write a program to output the instance, or use any other method you would like. # Scoring The fewer points in the instance the better. Ties will be broken by the file size of the instance (see below). # Standardization Different computers run faster or slower, so we will use [the NEOS Server for Concorde](https://neos-server.org/neos/solvers/co:concorde/TSP.html) as the standard of measurement for runtime. You can submit a list of points in the following simple 2-d coordinate form: ``` #cities x_0 y_0 x_1 y_1 . . . x_n-1 y_n-1 ``` The settings that should be used on NEOS are "Concorde data(xy-list file, L2 norm)", "Algorithm: Concorde(QSopt)", and "Random seed: fixed". # Baseline The 1,889-point instance `rl1889.tsp` from [TSPLIB](https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/tsp/) takes "Total Running Time: 871.18 (seconds)", which is more than five minutes. It looks like this: [![no-cities illustration of rl1889.tsp](https://i.stack.imgur.com/T2i8R.png)](https://i.stack.imgur.com/T2i8R.png) [Answer] # 88 Cities, 341 seconds runtime on NEOS In a recent paper we constructed a family of hard to solve euclidean TSP instances. You can download the instances from this family as well as code for generating them here: <http://www.or.uni-bonn.de/%7Ehougardy/HardTSPInstances.html> The 88 city instance from this family takes Concorde on the NEOS server more than 5 minutes. The 178-city instance from this family takes already more than a day to solve. [Answer] # 77 cities, 7.24 minutes (434.4 seconds) average run time on NEOS I’m a little late to the party, but I’d like to contribute a 77-node instance, weruSnowflake77. I created this instance while trying to understand which local and global characteristics impose an upward pressure on the amount of time concorde takes to match its best lower bound with the length of its shortest found tour. To construct this instance, I began with a base graph (13 x 13 square), and then systematically introduced new points or translated old points, retaining the adjustments that appeared to make concorde go deeper into its branches on average before cutting. The technique is similar to the way a genetic algorithm mutates existing tours and retains shorter tours for the next generation of mutations, except the graph itself is being mutated and the harder-to-solve graphs are retained. It's also similar to the way we mutate graphs using relaxations to help construct good lower bounds, except I'm going the opposite way, mutating an existing graph to construct a graph with hard to find lower bounds. In the process I’ve found a few smaller graphs that take concorde minutes to solve, but this is the first small graph I’ve found that takes concorde a minimum of 5 minutes. With 10 trial runs on NEOS using the fixed seed and QSopt, the average runtime was 7.24 minutes (434.531 seconds). The minimum runtime was 5.6 minutes (336.64 seconds). The maximum runtime was 8.6 minutes (515.80 seconds). No trials were discarded. Full benchmark table below: ## Benchmark results over 10 runs: ``` ---------------------------------- | Run | Job ID# | Total running | | | | time (seconds) | |-----|---------|----------------| | 1 | 7739963 | 513.44 | | 2 | 7740009 | 336.64 | | 3 | 7740023 | 514.25 | | 4 | 7740029 | 447.97 | | 5 | 7740038 | 357.10 | | 6 | 7740072 | 447.47 | | 7 | 7740073 | 336.19 | | 8 | 7740075 | 515.80 | | 9 | 7740088 | 361.26 | | 10 | 7740091 | 515.19 | ---------------------------------- ``` weruSnowflake77 (x-y list, L2 norm): ``` 77 -700 -700 700 -700 200 0 0 200 -200 0 0 -200 0 0 -600 600 -500 600 -400 600 -300 600 -200 600 -100 600 0 600 100 600 200 600 300 600 400 600 500 600 600 600 -600 -600 -500 -600 -400 -600 -300 -600 -200 -600 -100 -600 0 -600 100 -600 200 -600 300 -600 400 -600 500 -600 600 -600 600 -500 600 -400 600 -300 600 -200 600 -100 600 0 600 100 600 200 600 300 600 400 600 500 -600 -500 -600 -400 -600 -300 -600 -200 -600 -100 -600 0 -600 100 -600 200 -600 300 -600 400 -600 500 -500 -500 -400 -400 -300 -300 -200 -200 -100 -100 100 100 200 200 300 300 400 400 500 500 100 -100 200 -200 300 -300 400 -400 500 -500 -100 100 -200 200 -300 300 -400 400 -500 500 700 700 -700 700 ``` ## Repository * Github URL: <https://github.com/LDubya/weruSnowflake77> Problem set files from repo: * weruSnowflake77.txt (x-y list file, L2 norm) * weruSnowflake77.tsp (TSPLIB format, EUC\_2D) [Answer] # Python 3, 911 cities, 1418 seconds of run time on NEOS The following Python 3.x script generates the coordinates of 911 cities. [It took NEOS 1418 seconds to calculate](https://neos-server.org/neos/jobs/6550000/6559667.html) the shortest path of 47739. Here is A picture of thee shortest path (thanks to A. Rex): [![shortest path between 911 cities](https://i.stack.imgur.com/nhI2b.png)](https://i.stack.imgur.com/nhI2b.png) The code/algorithm is based on the [Feigenbaum bifurcation](https://en.wikipedia.org/wiki/Feigenbaum_constants), which I used to generate a series of values, which I used as a basis for generating the coordinates of the cities. I experimented with the parameters until I found a number of cities under 1000 that took NEOS a surprising amount of time (well above the required 5 minutes). ``` x = 0.579 coords = [] for _ in range(1301): if int(3001*x) not in coords: coords.append(int(3001*x)) x = 3.8*x*(1-x) coords = list(zip(coords, coords[::-1])) print(len(coords)) for coord in coords: print(f"{coord[0]} {coord[1]}") ``` PS: I have a script running in search for a lower number of cities that also take >5 minutes on NEOS. I'll post them in this answer if I find any. PS: Damn! Running this script with *l* parameter 1811 instead of 1301 results in 1156 cities with a [running time on NEOS of just over 4 hours](https://neos-server.org/neos/jobs/6550000/6559567.html), which is a lot more than other cases with similar parameters... ]
[Question] [ ## Challenge and origin On Stack Overflow a popular question is: [How to convert byte size into human readable format in java?](https://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java) The most up voted answer has a quite nice method for doing this, but this is codegolf and we can do better, can't we? > > Your challenge is to write a method or program that coverts the given > number of bytes to the correct human readable format and prints the > result to the standard out of your language.\* > > > \*See the rules for more clarification! ## Input The input will always be a positive number of bytes with a maximum of (2^31)-1. ## Output You may choose if you prefer the International System of Units or the binary notation as output (the SI notation probably saves you some bytes). ``` SI: B, kB, MB, GB Binary: B, KiB, MiB, GiB ``` Note: Higher units than GB or GiB are not posible due to the restricted input range. ## Example output International System of Units: ``` Input Output 0 0.0 B 999 999.0 B 1000 1.0 kB 1023 1.0 kB 1024 1.0 kB 1601 1.6 kB 160581 160.6 kB 4066888 4.1 MB 634000000 634.0 MB 2147483647 2.1 GB ``` Binary: ``` Input Output 0 0.0 B 999 999.0 B 1000 1000.0 B 1023 1023.0 B 1024 1.0 KiB 1601 1.6 KiB 160581 156.8 KiB 4066888 3.9 MiB 634000000 604.6 MiB 2147483647 2.0 GiB ``` ## Rules * Build-in functions for byte formatting are not allowed! * The output should always be in the same notation standard, you may not mix SI or binary; * The output should always be in the largest unit possible where the resulting number is still higher or equal to one; * The output should always have one decimal number, but you may choose to print an integer number when the resulting output is in bytes (B); * You may choose if you would like to add a space, tab or nothing between the number and the unit; * Input is received via STDIN or function parameters; * Output is printed to the console or returned as string (or similar character container); * This is code golf, so the shortest answer wins. Have fun! ## Edit: Even more clarification Some numbers have interesting rounding behaviors like the number 999950. Most code implementations would return 1000.0 kB instead of 1.0 MB. Why? Because 999950/1000 evaluates to 999.950 which is effectively rounded to 1000.0 when using String.format in Java (in most other languages too). Hench some extra checks are needed to handle cases like this. For this challenge both styles, 1000.0 kB and 1.0 MB are accepted, although the last style is preferred. **Pseudo code / java test code:** > > > ``` > > public static String bytesToSI(long bytes){ > if (bytes < 1000){ > return bytes + ".0 B"; > } > //Without this rounding check: > //999950 would be 1000.0 kB instead of 1.0 MB > //999950000 would be 1000.0 MB instead of 1.0 GB > int p = (int) Math.ceil(Math.log(bytes) / Math.log(1000)); > if(bytes/Math.pow(1000, p) < 0.99995){ > p--; > } > //Format > return String.format("%.1f %sB", bytes/Math.pow(1000, p), "kMGTPE".charAt(p-1)); > } > > ``` > > > > [Answer] # TI-BASIC, 44 Would be the right tool for the job if TI-BASIC had halfway decent string manipulation (I had to resort to overwriting the exponent of the number, displayed in engineering notation, with the unit). As it is it rounds and outputs correctly, but it's not even close to winning entries. Maybe a different calculator language could win this one? ``` Fix 1 Eng ClrHome Disp Ans Output(1,15,sub(" kMG",1+iPart(log(Ans+.5)/3),1)+"B ``` Input in the form `[number]:[program name]` on the homescreen. Given test cases: ``` Input Output (leading spaces intentional; screen clear before each output) 0 0.0 B 999 999.0 B 1000 1.0kB 1023 1.0kB 1024 1.0kB 1601 1.6kB 160581 160.6kB 4066888 4.1MB 634000000 634.0MB 2147483647 2.1GB ``` [Answer] # CJam, 35 27 bytes ``` ri{_e-3_i}g;1mOo]," kMG"='B ``` Thanks Dennis for removing 8 bytes. This doesn't print `.0` in the [online interpreter](http://cjam.aditsu.net/#code=ri%7B_e-3_i%7Dg%3B1mOo%5D%2C%22%20kMG%22%3D%27B&input=1149999). But as [Dennis has pointed out](https://codegolf.stackexchange.com/questions/51928/format-the-given-number-of-bytes-to-a-human-readable-format/51936#comment123505_51939), it works fine in the Java interpreter. ### Explanation ``` ri e# Read the input as an integer. { e# Do: _e-3 e# Make a copy and divide by 1000. e# This will generate one more item in the stack for each iteration. _i e# Make a copy and truncate to integer. }g e# until the integer part is 0. ; e# Discard the final value with integer part 0. 1mOo e# Output the number before it with the correct format. ], e# Count the number of iterations - 1. " kMG"= e# Select a character according to the number of iterations. 'B e# Output B. ``` [Answer] # Pyth, ~~29~~ 27 bytes ``` p@" kMG"Js.lQK^T3.RcQ^KJ1\B ``` [Demonstration.](https://pyth.herokuapp.com/?code=p%40%22+kMG%22Js.lQK%5ET3.RcQ%5EKJ1%5CB&input=634000123&debug=0) [Test Harness.](https://pyth.herokuapp.com/?code=FN.z%3DGvhcN)p%40%22+kMG%22J%2Ftl%60G3.RcG%5ET*3J1%5CB&input=0+++++++++++0+++++++B%0A999+++++++++999+++++B%0A1000++++++++1.0+++++kB%0A1023++++++++1.0+++++kB%0A1024++++++++1.0+++++kB%0A1601++++++++1.6+++++kB%0A160581++++++160.6+++kB%0A4066888+++++4.1+++++MB%0A634000000+++634.0+++MB%0A2147483647++2.1+++++GB&debug=0) Explanation: ``` p@" kMG"Js.lQK^T3.RcQ^KJ1\B Implicit: Q = eval(input()) p print, in the order 2nd arg then 1st arg: K^T3 K = 10^3 = 1000 .lQK log of Q base K s Floored J Store to J @" kMG"J The Jth character of ' kMG' ^KJ K^J cQ Q/K^J (Floating point division) .R 1 Round to 1 decimal place. \B Print a trailing 'B'. ``` [Answer] # CJam, 28 ``` r_dA@,(3/:X3*#/1mO" kMG"X='B ``` [Try it online](http://cjam.aditsu.net/#code=r_dA%40%2C(3%2F%3AX3*%23%2F1mO%22%20kMG%22X%3D'B&input=123450000) Note: it doesn't show ".0" with the online interpreter, but does so with the official [java interpreter](https://sourceforge.net/projects/cjam/). **Explanation:** ``` r_ read and duplicate dA convert to double and push 10 @ bring the initial string to the top ,( get the length and decrement 3/ divide by 3 (for thousands) :X3* store in X and multiply by 3 again # raise 10 to that power / divide the original number by it 1mO round to 1 decimal " kMG"X= convert X from 0/1/2/3 to space/k/M/G 'B add a 'B' ``` [Answer] # Python 2 - 76 bytes Uses the Internation System of Units, simply because it's easier to do in your head ;) ``` n=input();m=0;f=1e3 while n>=f:n/=f;m+=2 print"%.1f%s"%(n,'B kBMBGB'[m:m+2]) ``` [Answer] # Haskell, 119 I sadly couln't find a shorter way in Haskell to ensure 1 decimal place in floats, but I'm posting for posterity. ``` import Text.Printf a#n|p>=1=(a+1)#p|1<2=(a,n)where p=n/1000 m n=let(a,b)=0#n in printf"%.1f"b++["B","kB","MB","GB"]!!a ``` Usage: ``` > m 160581 "160.6kB" ``` Moderately less golfed version: ``` import Text.Printf countThousands :: Int -> Float -> (Int, Float) countThousands count num |nextNum >= 1 = countThousands (count+1) nextNum |otherwise = (count,num) where nextNum = num/1000 printHuman :: Float -> String printHuman n = let (a,b) = countThousands 0 n in (printf "%.1f" b) ++ (["B","kB","MB","GB"]!!a) ``` [Answer] ## Ruby, 84 ``` def f(n) n2=Math.log10(n).to_i/3 return '%.3f'% (n/1e3**n2)+['','k','M','G'][n2] end p f(9012345678.0)=='9.012G' ``` ## Python, 94 ``` import math def f(n): n2=int(math.log10(n)/3) return '%.3f'%(n/1e3**n2)+('','k','M','G')[n2] print(f(9012345678)=='9.012G') ``` ## JavaScript, 104 ``` function f(n){ let n2=Math.trunc(Math.log10(n)/3); return (n/1e3**n2).toFixed(3)+['','k','M','G'][n2]; } console.log(f(9012345678)=='9.012G'); ``` ## PHP, 105 ``` <?php function f($n){ $n2=(int)(log10($n)/3); return sprintf('%.3f',$n/1e3**$n2).['','k','M','G'][$n2]; } var_dump(f(9012345678)=='9.012G'); ``` ## Dart, 146 ``` import 'dart:math'; String f(double n){ var n2=(log(n)/ln10/3).toInt(); var n3=n/pow(1e3,n2); return n3.toStringAsFixed(3)+['','k','M','G'][n2]; } void main(){ print(f(9012345678)=='9.012G'); } ``` [Answer] **POWERSHELL,190** ``` $x=Read-Host function f($a,$b){"$x`t"+[math]::Round($x/$a,1).ToString("F1")+"`t$b"} if(1KB-gt$x){f 1 "B"}elseif(1MB-gt$x){f 1KB KiB} elseif(1GB-gt$x){f 1MB MiB}elseif(1TB-gt$x){f 1GB GiB} ``` usage ``` PS C:\> .\makehum.ps1 1601 1601 1.6 KiB PS C:\> .\makehum.ps1 4066888 4066888 3.9 MiB PS C:\> .\makehum.ps1 160581 160581 156.8 KiB PS C:\> .\makehum.ps1 634000000 634000000 604.6 MiB PS C:\> .\makehum.ps1 2147483647 2147483647 2.0 GiB PS C:\> ``` [Answer] # Java, 106 bytes This one's a method that takes a number and returns a string. ``` String f(int n){int k=0;for(;n>1e3;k++)n/=1e3;return(int)(10*n)/10.0+new String[]{"","k","M","G"}[k]+"B";} ``` [Answer] # C, 77 75 ``` f(float l){char*u=" kMG";while((l/=1e3)>=1)++u;printf("%.1f%cB",l*1e3,*u);} ``` This uses SI units and takes the 1000.0kB option for rounding. Expanded code: ``` f(float l) { char *u = " kMG"; while ((l/=1000) >= 1) ++u; printf("%.1f%cB", l*1000, *u); } ``` ### Output ``` 9 => 9.0 B 9999 => 10.0kB 1023 => 1.0kB 1024 => 1.0kB 999990 => 1000.0kB 1048575 => 1.0MB 1048576 => 1.0MB 2147483647 => 2.1GB ``` ### Variants To get binary units, change `1000` to `1024`, and add `i` to the format string if there's a multiplier. To avoid 4-digit rounding, compare `>=.95` instead of `>=1`. To accept larger units, extend the `u` string. Combining all these options, we get: ``` f(float l) { char*u=" kMGTPEZY"; while((l/=1024)>=.95)++u; printf(*u-' '?"%.1f%ciB":"%.0fB",l*1024,*u); } ``` ### Variant output ``` 9 => 9B 9999 => 9.8kiB 1023 => 1.0kiB 1024 => 1.0kiB 999990 => 1.0MiB 1048575 => 1.0MiB 1048576 => 1.0MiB 2147483647 => 2.0GiB 1000000000 => 953.7MiB 1000000000000 => 931.3GiB 1000000000000000 => 909.5TiB 1000000000000000000 => 888.2PiB 1000000000000000000000 => 867.4EiB 1000000000000000000000000 => 847.0ZiB 999999999999999999999999999 => 827.2YiB 1176043059457204080886151645 => 972.8YiB ``` ### Test program Pass any number of inputs as command-line arguments: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { while (*++argv) { printf("%s => ", *argv); f(strtod(*argv, 0)); puts(""); } return 0; } ``` [Answer] ## Rust, 124 ``` fn f(n:f64)->String{ let n2=n.log(1e3); let n3=n/1e3f64.powi(n2 as i32); format!("{:.3}",n3)+["","k","M","G"][n2 as usize] } fn main(){ println!("{}",f(9012345678e0)=="9.012G"); } ``` ## Nim, 139 ``` import math,strformat proc f(n:float):string= let n2=int log10(n)/3 let n3=n/pow(1e3,float n2) return fmt"{n3:.3f}"&["","k","M","G"][n2] echo f(9012345678e0)=="9.012G" ``` ## Go, 145 ``` package m import(."fmt" ."math") func f(g float64)string{h:=int(Log10(g))/3 i:=g/Pow10(h*3) return Sprintf("%.3f",i)+[]string{"","k","M","G"}[h]} ``` ## D, 156 ``` import std.format,std.math,std.stdio; string f(real n){ auto n2=cast(int)log10(n)/3; auto n3=n/pow(1e3,n2); return format("%.3f",n3)~["","k","M","G"][n2]; } void main(){ writeln(f(9012345678)=="9.012G"); } ``` ## C#, 168 ``` using System; class P{ static string f(double n){ var n2=(int)Math.Log10(n)/3; var n3=n/Math.Pow(1e3,n2); return String.Format("{0:f3}",n3)+new[]{"","k","M","G"}[n2]; } static void Main(){ Console.WriteLine(f(9012345678)=="9.012G"); } } ``` [Answer] # Python 2, 127 bytes Using the ISU. The snippet declares a function 'C' that takes the number to be converted as argument. ``` C=lambda v:min(['%.1f %sB'%(x,u)for x,u in[(v/1000.0**i,'bkMG'[i])for i in range(4)]if x>=1]).replace('.0 b',' ')if v else'0 B' ``` Some test code: ``` print 'Input\tOutput' for v in [0,999,1000,1023,1023,1601,160581,4066888,634000000,2147483647]: print v,C(v) ``` [Answer] # JavaScript (*ES6*), 71 Using SI units - A function returning the requested string. ``` f=(a,b=3)=>+(r=eval('a/1e'+b*3).toFixed(1))[0]?r+' kMG'[b]+'B':f(a,b-1) ``` This shorter one follows the rules, particularly 3 and 4 * The output should always be in the largest unit possible where the resulting number is still higher or equal to one **then 995 => 1.0kB** * The output should always have one decimal number, but you may choose to print an integer number when the resulting output is in bytes (B) **I choose not, so 10 => 10.0 B** Alas, this way, the results do not match the examples. To match the examples, here is a longer one, special cased for small numbers (82 bytes) ``` f=(a,b=3)=>a<1e3?a+'B':+(r=eval('a/1e'+b--*3).toFixed(1))[0]?r+'kMG'[b]+'B':f(a,b) ``` Run the snippet to test (being EcmaScript 6, Firefox only) ``` f=(a,b=3)=>+(r=eval('a/1e'+b*3).toFixed(1))[0]?r+' kMG'[b]+'B':f(a,b-1) ``` ``` Value <input id=I><button onclick="O.innerHTML+=f(+I.value)+'\n'">-></button><pre id=O></pre> ``` [Answer] # Ruby, 91 bytes ``` n=gets.to_i;i=0;while n>1023;n/=1024.0;i+=1;end;puts "#{n.round 1} #{%w[B KiB MiB GiB][i]}" ``` I could probably do a bit better if I tried harder but here's what I've got so far. [Answer] # Python, 61 bytes ``` f=lambda n,i=0:"%.1f%cB"%(n," kMG"[i])*(n<1e3)or f(n/1e3,i+1) ``` Call like `f(999)`. Note that `1e3` is a float, so this works with both Python 2 and Python 3. [Answer] # PHP4.1, ~~63~~ 62 bytes Not the best golfing, but surely is quite short. ``` <?for($S=kMG;$B>1e3;$I++)$B/=1e3;printf("%.1f{$S[$I-1]}B",$B); ``` To use it, access over POST/GET or set a value in the SESSION, on the key `B`. Leave the key `I` unset! [Answer] # SpecBAS - 100 bytes Using the ISU convention. I realised that having a variable set to 1e3 (which needs a LET statement to assign it), and then using that variable in the working out, actually used more characters than just hardcoding the 1e3 where it was needed. ``` 1 INPUT n: LET i=1 2 DO WHILE n>1e3: LET n=n/1e3: INC i: LOOP 3 PRINT USING$("&.*0#",n);" kMG"(i);"B" ``` [Answer] # Javascript ES5, 69 bytes This uses a different way to reach the end goal that [@edc65's answer](https://codegolf.stackexchange.com/a/51941/14732). Actually, this is pretty close to [my PHP answer](https://codegolf.stackexchange.com/a/51970/14732). ``` for(i=+prompt(z=0);i>1e3;z++)i/=1e3;alert(i.toFixed(1)+' kMG'[z]+'B') ``` Simply run the stack snippet or paste this on your console. [Answer] # Ruby, 128 bytes ``` c=->i{p i.to_s+'B'if i<1e3;p (i/1e3).to_s+'kB'if i>=1e3&&i<1e6;p (i/1e6).to_s+'MB'if i>=1e6&&i<1e9;p (i/1e9).to_s+'GB'if i>=1e9} ``` I did it the long way, this is pretty bad. # Output ``` c[0] # => "0B" c[999] # => "999B" c[1000] # => "1.0kB" c[1023] # => "1.023kB" c[1024] # => "1.024kB" c[1601] # => "1.601kB" c[160581] # => "160.581kB" c[4066888] # => "4.066888MB" c[634000000] # => "634.0MB" c[2147483647] # => "2.147483647GB" ``` # Edit Added TB for an extra 39 bytes ``` c=->i{p i.to_s+'B'if i<1e3;p (i/1e3).to_s+'kB'if i>=1e3&&i<1e6;p (i/1e6).to_s+'MB'if i>=1e6&&i<1e9;p (i/1e9).to_s+'GB'if i>=1e9&&i<1e12;p (i/1e12).to_s+'TB'if i>=1e12} ``` # Output: ``` c[1000000000000] # => "1.0TB" ``` [Answer] # Ruby, 90 bytes ``` proc{|n|q=((1..3).find{|i|n<(1<<i*10)}||4)-1;[n*10/(1<<q*10)/10.0,%w[B kB MB GB][q]].join} ``` [Answer] # Sed `-r`, 218+1 I'm using SI units; I think that choosing binary units would be *a courageous policy*. ;-) ``` s/(.)((...)+)$/\1z\2/;h;s/[^z]*z?//;s/.../k/g;s/kk/M/;s/Mk/G/;x;s/(z.)[5-9].*/\1c/;s/(z.c?).*/\1/;:;s/9c/c0/;s/zc/cz/;t;s/(^|0)c/1/;s/1c/2/;s/2c/3/;s/3c/4/;s/4c/5/;s/5c/6/;s/6c/7/;s/7c/8/;s/8c/9/;G;s/\n//;s/$/B/;y/z/./ ``` Reformatted: ``` #!/bin/sed -rf # Place decimal point (use z as shorthand for \.) s/(.)((...)+)$/\1z\2/ h # count thousands into hold space s/[^z]*z?// s/.../k/g s/kk/M/;s/Mk/G/ x # truncate to 1 decimal place s/(z.)[5-9].*/\1c/ s/(z.c?).*/\1/ # propagate carry : s/9c/c0/ s/zc/cz/ t s/(^|0)c/1/ s/1c/2/ s/2c/3/ s/3c/4/ s/4c/5/ s/5c/6/ s/6c/7/ s/7c/8/ s/8c/9/ # Append units G;s/\n// s/$/B/ y/z/./ ``` ### Output ``` 1 => 1B 9 => 9B 99 => 99B 999 => 999B 1000 => 1.0kB 9999 => 10.0kB 99949 => 99.9kB 99950 => 100.0kB 99999 => 100.0kB 999999 => 1000.0kB 9999999 => 10.0MB 9999999999 => 10.0GB 1000 => 1.0kB 10000 => 10.0kB 10005 => 10.0kB 10440 => 10.4kB 10450 => 10.5kB 10950 => 11.0kB ``` ### Variations The rules seem to imply round-to-nearest, but for human display, I believe rounding down is an acceptable alternative, and saves 123 bytes (better than 50%): ``` s/(.)((...)+)$/\1.\2/;h;s/[^\.]*\.?//;s/.../k/g;s/kk/M/;s/Mk/G/;x;s/(\..).*/\1/;G;s/\n//;s/$/B/ ``` The natural extension to larger units (still rounding down, 130+1 bytes): ``` s/(.)((...)+)$/\1.\2/;h;s/[^\.]*\.?//;s/.../k/g;s/kk/M/g;s/Mk/G/;s/MM/T/g;s/TT/Y/;s/TM/E/;s/TG/Z/;x;s/(\..).*/\1/;G;s/\n//;s/$/B/ ``` ### Variation output: ``` 1 => 1B 9 => 9B 99 => 99B 999 => 999B 1000 => 1.0kB 9999 => 9.9kB 99949 => 99.9kB 99950 => 99.9kB 99999 => 99.9kB 999999 => 999.9kB 9999999 => 9.9MB 9999999999 => 9.9GB 1000 => 1.0kB 10000 => 10.0kB 10005 => 10.0kB 10440 => 10.4kB 10450 => 10.4kB 10950 => 10.9kB 1000000000 => 1.0GB 1000000000000 => 1.0TB 1000000000000000 => 1.0MGB 1000000000000000000 => 1.0EB 1000000000000000000000 => 1.0ZB 1000000000000000000000000 => 1.0YB 999999999999999999999999999 => 999.9YB ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~396~~ 376 bytes ``` ,[<[->>+<<]>>+>,]<<[>[<<+>>-]<<<]<-------<---<--<-[>+>-->+>>>>>>+<<<<<<<<<-------]>>>>>>>+++>>++++<<<<<--[>>>+<<<++++++]+>-[-[-[-[-[-[-[-[-[-[-<->]<[>>.>.>.[<<]>.>>>-]>]<[->>.>>.>>.<<<.>>>>>.<<<.<<<<<]>]<[->>.>>.<.>>>.<.<<<<<]>]<[->>.>.>.>.[<]<]>]<[>>.>>.>>.<<<.>>>>>.[<<]>>.>>-]>]<[>>.>>.<.>>>.[<<]>>.>>-]>]<[->>.>.>.<<<<<<.>>]>]<[->>[.>>]<<[<<]]>]<[->>.>>.<<<<]>]<[->>.<<]<. ``` [Try it online!](https://tio.run/##bVBBCsJADHxQmkVQPA35SMhBhYIIHgTfvybZFFZttg1hZjqZ7vV1uT/X9@3R@6JQFiHAvMtigIoCJMI@w8CjMF6wuozZW5Z/WFU6kyKIslGRWmLKMvfQnQMW8wDS4miEahJJAuWA83GblktyygWzIsn2R5SnDWjHLPcFxpNimP1Qm9/4c4c3VGP2K3T5V6I5SFxq6/18PB2yPg "brainfuck – Try It Online") ]
[Question] [ Mission is simple. Just output number 2015 as QR code and write it to file named `newyear.png` in PNG format. Code must be valid any day, so maybe you shall not use current year. QR code as text looks like this: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` The result written in `newyear.png` must contain that QR code with white 5 pixel borders and one pixel sized dots. It must not contain anything else than QR code. [Answer] # Raw file, 184 bytes = 173-byte file + 11-byte filename I hope this does not break any standard loopholes. But the output "has a high [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") and the shortest way to produce it would (most likely) be to just print it literally...". ![newyear.png](https://i.stack.imgur.com/wjl1A.png) Base 64 of the file: ``` iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfAQAAAAA31SuUAAAAdElEQVR4XnXOMQ5BQRRA0euVRFgGCq1ubIyJpSh11I qJWIjo+fnt/JnJe55WornlycXMVAB+Qp49A7U/J8rqlIQReG5Quz6Rx8eA6VaF5R7a5arooXg2LaKvd8KGRyBPJLoy D640pxZ3pay/creL5KnEvwcfvE46ggJMibIAAAAASUVORK5CYII= ``` --- Instead of golfing a program I golfed the resulting PNG image. QR code is a very flexible format, there are many parameters that can be fiddled: the encoding of the input, the error correction level, and the masking image. These will all generate different symbols and thus compressed to files of different sizes. So I have written a program to generate all these combinations (resulting 6720 files), and then use PNGOUT to pick the one which compressed to the smallest file. It turns out to be a file that: * First write "20" in alphanumeric mode * Then write "1" in numeric mode * Then write "5" in numeric mode * Use the "H" (High) error correction level * Use the "110" data masking This is called `test-3-1-H-Diamonds.bmp` if you used the program below. This image is 175-byte long after running PNGOUT. With "high" error correction level in "version 1" QR code, we can modify up to 8 pixels in the data part without ruining the data. With a bit of manual trial-and-error I can reduce it further to 173 bytes presented above. It can probably be smaller but exhausting all combinations requires 208C8 ~ 7.5 × 1013 checks which I'm not going to do ;) --- The Rust (0.13.0-nightly (5ba610265)) program that generates all combinations: ``` /* Also put these into your Cargo.toml: [dependencies] qrcode = "0.0.3" bmp = "0.0.3" */ extern crate qrcode; extern crate bmp; use qrcode::bits::Bits; use qrcode::optimize::Segment; use qrcode::types::{Version, EcLevel, Mode}; use qrcode::ec::construct_codewords; use qrcode::canvas::{Canvas, MaskPattern, Module}; use bmp::{Image, Pixel}; use std::num::Int; const BLACK: Pixel = Pixel { r: 0, g: 0, b: 0}; const WHITE: Pixel = Pixel { r: 255, g: 255, b: 255 }; static SEGMENT_SEPARATIONS: [&'static [(uint, uint)]; 8] = [ &[(0, 1), (1, 2), (2, 3), (3, 4)], &[(0, 1), (1, 2), (2, 4)], &[(0, 1), (1, 3), (3, 4)], &[(0, 2), (2, 3), (3, 4)], &[(0, 1), (1, 4)], &[(0, 2), (2, 4)], &[(0, 3), (3, 4)], &[(0, 4)], ]; const ALL_EC_LEVELS: &'static [EcLevel] = &[EcLevel::L, EcLevel::M, EcLevel::Q, EcLevel::H]; const ALL_MODES: &'static [Mode] = &[Mode::Numeric, Mode::Alphanumeric, Mode::Byte]; const ALL_MASK_PATTERNS: &'static [MaskPattern] = &[ MaskPattern::Checkerboard, MaskPattern::HorizontalLines, MaskPattern::VerticalLines, MaskPattern::DiagonalLines, MaskPattern::LargeCheckerboard, MaskPattern::Fields, MaskPattern::Diamonds, MaskPattern::Meadow, ]; fn run(ec_level: EcLevel, mask_pattern: MaskPattern, segments: &[Segment], filename: &str) { let version = Version::Normal(1); let mut bits = Bits::new(version); if bits.push_segments(b"2015", segments.iter().map(|s| *s)).is_err() { return; } if bits.push_terminator(ec_level).is_err() { return; } let data = bits.into_bytes(); let (encoded_data, ec_data) = construct_codewords(&*data, version, ec_level).unwrap(); let mut canvas = Canvas::new(version, ec_level); canvas.draw_all_functional_patterns(); canvas.draw_data(&*encoded_data, &*ec_data); canvas.apply_mask(mask_pattern); let canvas = canvas; let width = version.width(); let real_image_size = (width + 10) as uint; let mut image = Image::new(real_image_size, real_image_size); for i in range(0, real_image_size) { for j in range(0, real_image_size) { image.set_pixel(i, j, WHITE); } } for i in range(0, width) { for j in range(0, width) { if canvas.get(i, j) == Module::Dark { image.set_pixel((i + 5) as uint, real_image_size - (j + 6) as uint, BLACK); } } } image.save(filename); } fn main() { for (z, separations) in SEGMENT_SEPARATIONS.iter().enumerate() { let mut segments = separations.iter().map(|&(b, e)| Segment { mode: Mode::Numeric, begin: b, end: e }).collect::<Vec<_>>(); let variations_count = ALL_MODES.len().pow(segments.len()); for i in range(0, variations_count) { let mut var = i; for r in segments.iter_mut() { r.mode = ALL_MODES[var % ALL_MODES.len()]; var /= ALL_MODES.len(); } for ec_level in ALL_EC_LEVELS.iter() { for mask_pattern in ALL_MASK_PATTERNS.iter() { let filename = format!("results/test-{}-{}-{}-{}.bmp", z, i, *ec_level, *mask_pattern); run(*ec_level, *mask_pattern, &*segments, &*filename); } } } println!("processed {}/{}", z, 8u); } } ``` [Answer] # Mathematica, ~~217~~ ~~177~~ ~~176~~ 166 bytes Here is a start: ``` "newyear.png"~Export~ImagePad[Image[IntegerDigits[36^^fl6ibg25c8z00uef53p4657dgd6hjzg41e5joead1qgz0l2xchqgso5r1a51v5no4zkw9v22okk‌​lg0cymmy2,2,441]~Partition~21],5,1] ``` Less golf: ``` "newyear.png"~Export~ImagePad[ Image[ IntegerDigits[ 36^^fl6ibg25c8z00uef53p4657dgd6hjzg41e5joead1qgz0l2xchqgso5r1a51v5no4zkw9v22okk‌​lg0cymmy2, 2, 441 ]~Partition~21 ], 5, 1 ] ``` The QR code is encoded in a base 36 number. Of course, I could encode it in extended ASCII (base 256), but that would only shorten the string by 30 bytes, and I'm not sure I can do the conversion at the cost of much less than that. Of course, this is Mathematica, so there's also the **63-byte** ``` "newyear.png"~Export~ImagePad[BarcodeImage["2015","QR",21],5,1] ``` but I guess that's a standard loophole. ;) (This produces a different QR code than the one in the challenge, so I guess the QR code isn't unique?) [Answer] # [Python 3](https://docs.python.org/3/), 261 bytes ``` from PIL import Image h=Image.new("1",[21]*2) h.putdata([int(u)for u in list("".join(format(ord(i),"08b")for i in'\x01\x0c\x03ï¯\x91MD\x8bª$]Q>þø\x05P\x1féÿY\x99ÔU-\x12 \\<ððVÖÿðü\x07IO¯\x0fEíj-\x83ÑT\x94û8\x80\x17Õ'))]) h.save("newyear.png") ``` Needs a better way of encoding ## Explanation ``` from PIL import Image # Import the Pillow library for images ima = Image.new("1", [21, 21]) # Create a new 21x21 Image in B/W mode ima.putdata( # Function to write a sequence to the pixels [int(u) for u in list( # convert string into list of bits to write "".join( # join into single string format(ord(byte),"08b" # format a unicode character into list of bits )for byte in'\x01\x0c\x03ï¯\x91MD\x8bª$]Q>þø\x05P\x1féÿY\x99ÔU-\x12 \\<ððVÖÿðü\x07IO¯\x0fEíj-\x83ÑT\x94û8\x80\x17Õ' # Loop through encoded qr data ) )] ) ima.save("newyear.png") # Save image ``` [Answer] # Matlab 545 Bytes ![newyear](https://i.stack.imgur.com/OehuJ.png) Hardcoded in painstaking manual work and ***without any fancy builtin string compression/conversation***. I know it still is not as good as the other answers but I am still happy=) ``` b=[[61:67,69,71:73,75:81,92,98]+100, 1,3:4,6,12,23,25:27,29,31:35,37,39:41,43,54,56:58,60,63:64,66,68,70:72,74,85,87:89,91,97,99]+200, [1:3,5,16,22,24:26,30,36,47:53,55,57,59,61:67,87:89]+300, [9,11,15:16,20:21,24,27,29,40,42,48:50,57,59,71,74:75,77:79,81,85,89:90]+400, [2,9,11:12,14:15,18,34:37,39,42:43,46:47,50:51,72,74:75,77:79,81:82,95:99]+500, [0:1,3:8,10:12,14:15,26,32,37,40:41,43:45,57,59:61,63,67:69,71:77,88,90:92,94,97]+600, [19,21:23,25,27,33,37:39,50,56,59,62,66,69,81:87,89:91,95,99:101]+700]; z=zeros(31);z(b)= 1;imwrite(~z,'newyear.png') ``` More unreadable (the actual 545 version): ``` z=zeros(31); z([ [61:67, 69, 71:73, 75:81, 92, 98] + 100, [1, 3:4, 6, 12, 23, 25:27, 29, 31:35, 37, 39:41, 43, 54, 56:58, 60, 63:64, 66, 68, 70:72, 74, 85, 87:89, 91, 97, 99] + 200, [1:3, 5, 16, 22, 24:26, 30, 36, 47:53, 55, 57, 59, 61:67, 87:89] + 300, [9, 11, 15:16, 20:21, 24, 27, 29, 40, 42, 48:50, 57, 59, 71, 74:75, 77:79, 81, 85, 89:90] + 400, [2, 9, 11:12, 14:15, 18, 34:37, 39, 42:43, 46:47, 50:51, 72, 74:75, 77:79, 81:82, 95:99] + 500, [0:1, 3:8, 10:12, 14:15, 26, 32, 37, 40:41, 43:45, 57, 59:61, 63, 67:69, 71:77, 88, 90:92, 94, 97] + 600, [19, 21:23, 25,27, 33, 37:39, 50, 56, 59, 62, 66, 69, 81:87, 89:91, 95, 99:101] + 700 ])= 1; imwrite(~z,'newyear.png') ``` We create a 31 x 31 zero matrix, but access it as vector to set all cells with the indices of `b` to `1`. The tricks I used were the notation of consecutive integers (like `[1,2,3,4] = 1:4`) and removing one the 100-digit by adding a scalar to every value of the vector. Let's see if anyone can beat that=) [Answer] # Python 2 + PIL, ~~216~~ 215 Basically a port of the Mathematica solution. ``` from PIL import* b=Image.new("1",[21]*2) b.putdata(map(int,'0'*7+bin(int('FL6IBG25C8Z00UEF53P4657DGD6HJZG41E5JOEAD1QGZ0L2XCHQGSO5R1A51V5NO4ZKW9V22OKKLG0CYMMY2',36))[2:])) ImageOps.expand(b,5,255).save("newyear.png") ``` [Answer] # Bash, 206 252 257 Bytes Using the `convert` command bundled in `imagemagick` saves 46 more bytes. ``` base64 -d<<<UDQKMzAgMzAKAAAAAAAAAAAAAAAAAAAAAAAAAAAH9L+ABBkggAXULoAF2S6ABdOugAQeoIAH+r+AB9zVAABIlwABHU6AAsIaAAFXS4AAD+QAB/ywAAQT5QAF3pIABd6SAAXdTgAEHBsAB/1OAAAAAAAAAAAAAAAAAAAAAAAAAAAA|convert - newyear.png ``` Converts the base64-encoded `pbm` image to a `png` image with `imagemagick`'s `convert`. > > You may need to adjust the `decode (-d)` parameter to your specific `base64` binary. > Tested on my Ubuntu 14.04 LTS. > > > Saved 5 bytes by using `<<<`/*here-string*. ``` base64 -d>newyear.png<<<iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeAQMAAAAB/jzhAAAABlBMVEX///8AAABVwtN+AAAAX0lEQVQI12PACdi/7G9gYJFUaGBgvaIHJG6CiMvrgGJyCxoY2H/tBxJ3rgIVekxnYGCU9WtgYDokBWSFezcwMPA/ARrwZwMDA4vwUwYG1nuTYMRdP6CYjDRQ9q8fbrsBLRkaYOOP83wAAAAASUVORK5CYII= ``` Old version (257 bytes): `echo iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeAQMAAAAB/jzhAAAABlBMVEX///8AAABVwtN+AAAAX0lEQVQI12PACdi/7G9gYJFUaGBgvaIHJG6CiMvrgGJyCxoY2H/tBxJ3rgIVekxnYGCU9WtgYDokBWSFezcwMPA/ARrwZwMDA4vwUwYG1nuTYMRdP6CYjDRQ9q8fbrsBLRkaYOOP83wAAAAASUVORK5CYII=|base64 -d > newyear.png` Just a simple shell command chain that writes the base64 encoded `png` file into stdin of `base64` that decodes it because of the `-d` flag and writes its stdout to newyear.png. [Answer] # HTML (Stack Snippet), 367 Edit: Oops! I forgot about the filename requirement. This makes a download link that prompts the user to download newyear.png. Due to browser security, I'm pretty sure I can't bypass that prompt. I tested this on Firefox, but FYI, the closing `</a>` tag doesn't seem to be required for this to still work: ``` <a href="data:png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfCAYAAAAfrhY5AAAAs0lEQVRIie2U4QrAIAiEff+Xdn9FPD1ta7AljJHhfVqm6IsmB37gqqoiAr9on42j4RN/O64S8xVbP4KjuFvgGfQbcNY/jRt3O/ovd3tlqPHaOpW49XXWSKeEWzH2qKNkUVIpHAlnU455FTQcZVz5O31Ad7utIDpeZp+Cd2xScQpn32vWG36/Bc/8j9+5F8ygWXLtO2fg0YDZUnk1aB69cw/xPpQ8De9MMJ/cUuW77MD/B78AsoJkRZwIeDUAAAAASUVORK5CYII=" download="newyear.png">a ``` Original answer that just displays the png: ``` <img src="data:png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfCAYAAAAfrhY5AAAAs0lEQVRIie2U4QrAIAiEff+Xdn9FPD1ta7AljJHhfVqm6IsmB37gqqoiAr9on42j4RN/O64S8xVbP4KjuFvgGfQbcNY/jRt3O/ovd3tlqPHaOpW49XXWSKeEWzH2qKNkUVIpHAlnU455FTQcZVz5O31Ad7utIDpeZp+Cd2xScQpn32vWG36/Bc/8j9+5F8ygWXLtO2fg0YDZUnk1aB69cw/xPpQ8De9MMJ/cUuW77MD/B78AsoJkRZwIeDUAAAAASUVORK5CYII="> ``` [Answer] # Common Shell tools + Imagemagick, 215 ``` (echo "P1 21 21" base64 -d<<<H95/ggoN1lduirt0VdggIP9V/ALAFMzFdVpdu/R4YeH1JSAB4H8W1goeF0JSuk+F1W1gmO/9BVA=|xxd -c99 -p|tr a-f A-F|dc -e2o16i?p|tr -d '\n\\'|fold -21)|convert -border 5 -bordercolor white - newyear.png ``` A bit convoluted, but shorter than the other shell answer. * Base64 converts from base64 to base 256 (extended ASCII) * xxd converts to hex * tr makes hex uppercase, suitable for dc * dc reads hex and prints binary string of 1s and 0s * tr removes \ and whitespace * fold makes lines 21 chars (21 pixels) long * This output, along with `P1\n21 21` is the [PBM P1 format](http://en.wikipedia.org/wiki/Netpbm_format) * convert (Imagemagick) converts this to .png with a 5 pixel border: ![enter image description here](https://i.stack.imgur.com/PgHO6.png) ]
[Question] [ You should all be familiar with the [Conway sequence (a.k.a. 'look-and-say'-sequence)](https://en.wikipedia.org/wiki/Look-and-say_sequence) by now: ``` 1 11 21 1211 111221 312211 etc ``` You can also start by any arbitrary number as starting point. Let `f(s)` be the next element of the sequence. Now for every given `s`we can find `f(s)`. The reverse is not as trivial: it is not for every `y` possible to find the predecessor `s` such that `f(s) = y`. E.g. for `y = 1` we cannot find a predecessor. But if `y` has an *even* length you can divide it into pairs of digits which describe each one part of a predecessor: ``` 513211 divides in 51,32,11 so: 51 comes from 11111 32 comes from 222 11 comes from 1 put together: 111112221 ``` So this way there we can define an *unique* predecessor for every `y` of even length. **Note**: The 'predecessor' `s` defined this way does generally NOT satisfy `f(s) = y`. ## Goal Write a function / program snippet that accepts a string of digits as input that * calculates the next element of the Conway sequence if the length of the input string is *odd* * calculates the predecessor of the input string as defined above if the input string length is *even*. Shortest code in bytes wins. **Recent Questions based on the look-and-say sequences:** * [Look and say sequence](https://codegolf.stackexchange.com/questions/2323/look-and-say-sequence) * [Point-free look and say sequence](https://codegolf.stackexchange.com/questions/23790/point-free-look-and-say-sequence) * [Quickly find length of n-th term of the look-and-say sequence](https://codegolf.stackexchange.com/questions/8431/quickly-find-length-of-n-th-term-of-the-look-and-say-sequence) [Answer] # Ruby, ~~125 120 119~~ 101 bytes ``` f=->n{c=n.chars;(n.size%2>0?c.chunk{|x|x}.map{|a,b|[b.size,a]}:c.each_slice(2).map{|a,b|b*a.hex})*''} ``` String input taken through function `f`: ``` f['111221'] # => "1211" f['513211'] # => "111112221" f['111112221'] # => "513211" ``` Expanded with notes: ``` # define lambda that takes one arg f = -> (n) { # store digits in c c = n.chars # n is of odd length if n.size % 2 > 0 # group identical numbers c.chunk{ |x| x }.map do |a, b| # array of [digit count, digit value] [b.size, a] end else # slice array into groups of two elements c.each_slice(2).map do |a, b| # repeat the second digit in a pair # the first digit-times. b * a.hex end end * '' # join array } ``` [Answer] ## Prolog - 170 bytes ``` []/[]. T/R:-0*_*T*R. C*X*[X|T]*R:-(C+1)*X*T*R. C*X*T*Y:-10*C+X+Y+R,T/R. N+R+A:-N=:=0,A=R;D is N mod 10,N//10+R+[D|A]. F-C-R:-C/N,(N=F,R=C;F-N-R). [1]-[1,1]. S-T:-S-[1]-T. ``` This snipped defines the function `(-)/2`. You can invoke it like ``` ?- [1,1,1,3,2,1,3,2,1,1]-T. T = [1, 3, 1, 1, 2, 2, 2, 1] . ?- [1]-T. T = [1, 1] . ``` There seems to be only one [lengths in this sequence](http://oeis.org/A005341) with an odd parity: the initial `[1]`. ``` wr_len :- wr_len(1, [1]). wr_len(N, Cur) :- length(Cur, Len), TrailingZeroes is lsb(Len), (TrailingZeroes > 0 -> Par = 'even'; Par = 'odd'), writef('%t\t%t\t%t\t%t\n', [N, Len, Par, TrailingZeroes]), get_next(Cur, Next), succ(N, O), !, wr_len(O, Next). ``` ``` % index, length, parity of length, num of trailing 0 in bin presentation of length ?- wr_len. 1 1 odd 0 2 2 even 1 3 2 even 1 4 4 even 2 5 6 even 1 6 6 even 1 7 8 even 3 8 10 even 1 9 14 even 1 10 20 even 2 11 26 even 1 12 34 even 1 13 46 even 1 14 62 even 1 15 78 even 1 16 102 even 1 17 134 even 1 18 176 even 4 19 226 even 1 20 302 even 1 21 408 even 3 22 528 even 4 23 678 even 1 24 904 even 3 25 1182 even 1 26 1540 even 2 27 2012 even 2 28 2606 even 1 29 3410 even 1 30 4462 even 1 31 5808 even 4 32 7586 even 1 33 9898 even 1 34 12884 even 2 35 16774 even 1 36 21890 even 1 37 28528 even 4 38 37158 even 1 39 48410 even 1 40 63138 even 1 41 82350 even 1 42 107312 even 4 43 139984 even 4 44 182376 even 3 45 237746 even 1 46 310036 even 2 47 403966 even 1 48 526646 even 1 49 686646 even 1 50 894810 even 1 51 1166642 even 1 52 1520986 even 1 53 1982710 even 1 54 2584304 even 4 55 3369156 even 2 56 4391702 even 1 57 5724486 even 1 58 7462860 even 2 59 9727930 even 1 ERROR: Out of global stack % I added a few "strategic" cuts (`!`) to get so far. ``` Readable: ``` get_next([], []). get_next(Current, Next) :- get_next_sub(0, _, Current, Next). get_next_sub(Length, Digit, [Digit|Tail], Result) :- get_next_sub(Length+1, Digit, Tail, Result). get_next_sub(Length, Digit, Further, Result) :- number_to_list(10*Length+Digit, Result, ResultTail), get_next(Further, ResultTail). number_to_list(Number, Result, Accumulator) :- 0 is Number -> Result = Accumulator; Digit is Number mod 10, number_to_list(Number // 10, Result, [Digit|Accumulator]). get_previous(Stop, Current, Result) :- get_next(Current, Next), ( Next = Stop -> Result = Current ; get_previous(Stop, Next, Result) ). get_prev_or_next(Input, Result) :- length(Input, Length), ( 1 is Length mod 2 -> get_next(Input, Result) ; get_previous(Input, [1], Result) ). ``` [Answer] # CJam, ~~46~~ ~~45~~ ~~44~~ ~~43~~ 42 bytes ``` l_,2%{0\{@)@@_2$=!{0\0}*;}*\)\}{2/{(~*}%}? ``` [Test it here.](http://cjam.aditsu.net/) It takes the number on STDIN and prints the result to STDOUT. [Answer] # Python: 139 chars ``` import re f=lambda s:''.join(['len(b)'+a for a,b in re.findall(r'((\d)\2*)',s)] if len(s)%2 else map(lambda a,b:b*int(a),s[::2],s[1::2])) ``` single test case ``` print f('1111122221111222112') >>> 514241322112 print f('514241322112') >>> 1111122221111222112 ``` [Answer] # Haskell, 134 128 115 ``` n=length l x=x#mod(n x)2 (a:b:c)#0=replicate(read[a])b++c#0 (a:b)#1=(\(c,d)->show(1+n c)++a:d#1)$span(==a)b _#_=[] ``` If it needs to be from stdin/stdout, add `main=interact l` for 150 144 131 total chars. The function is called `l`. ``` *Main> putStr . unlines $ map (\x->x++":\t"++l x) ([replicate n '1'|n<-[5..10]]++map show [0,6..30]++map show [n*n+n|n<-[2..10]]) 11111: 51 111111: 111 1111111: 71 11111111: 1111 111111111: 91 1111111111: 11111 0: 10 6: 16 12: 2 18: 8 24: 44 30: 000 6: 16 12: 2 20: 00 30: 000 42: 2222 56: 66666 72: 2222222 90: 000000000 110: 2110 ``` [Answer] # Perl - 98 bytes The size of all these control statements bugs me, but I'm pretty happy with how the regexes worked out. ``` ($_)=@ARGV;if(length()%2){$\=$&,s/^$&+//,print length$&while/^./}else{print$2x$1while s/^(.)(.)//} ``` Uncompressed: ``` ($_)=@ARGV; if(length()%2) { $\=$&, #Assigning the character to $\ causes it to be appended to the print (thanks, tips thread!) s/^$&+//, #Extract the string of characters print length$& #Print its length while/^./ #Get next character into $& }else{ print$2x$1 while s/^(.)(.)// } ``` [Answer] # Erlang, 205 ``` f(L)->g(L,L,[]). g([A,B|T],L,C)->g(T,L,lists:duplicate(A-$0,B)++C);g([],_,R)->R;g(_,L,_)->i(L,[]). h([A|T],A,N,B)->h(T,A,N+1,B);h(L,B,N,C)->i(L,integer_to_list(N)++[B|C]). i([H|T],A)->h(T,H,1,A);i(_,R)->R. ``` Main function is f, taking the input as an Erlang string and returning the output as a string as well. ``` f("11"). % returns "1" f("111"). % returns "31" f("1111111111111"). % returns "131" ``` The function can be made 15 bytes shorter (190) by dropping the more than 9 identical characters case requirement. `f` calls `g` which computes the predecessor recursively, and if the number of characters is odd (found at when computation ends), it calls function `i` which, paired with `h`, computes the next element. [Answer] # Haskell, 105 ``` import Data.List l=length c r|odd$l r=group r>>=(l>>=(.take 1).shows)|x:y:z<-r=[y|_<-['1'..x]]++c z|0<1=r ``` I think it's nice it turned out not using any helper functions :-). [Answer] ## APL (45) ``` ∊{2|⍴⍵:(⊃,⍨⍕∘⍴)¨⍵⊂⍨1,2≠/⍵⋄/⍨∘⍎/¨⌽¨⍵⊂⍨1 0⍴⍨⍴⍵} ``` Yes, that's a valid function definition, even with the `∊` on the outside. ``` ∊{2|⍴⍵:(⊃,⍨⍕∘⍴)¨⍵⊂⍨1,2≠/⍵⋄/⍨∘⍎/¨⌽¨⍵⊂⍨1 0⍴⍨⍴⍵}'513211' 111112221 ∊{2|⍴⍵:(⊃,⍨⍕∘⍴)¨⍵⊂⍨1,2≠/⍵⋄/⍨∘⍎/¨⌽¨⍵⊂⍨1 0⍴⍨⍴⍵}'111112221' 513211 f←∊{2|⍴⍵:(⊃,⍨⍕∘⍴)¨⍵⊂⍨1,2≠/⍵⋄/⍨∘⍎/¨⌽¨⍵⊂⍨1 0⍴⍨⍴⍵} f ¨ '513211' '111112221' ┌─────────┬──────┐ │111112221│513211│ └─────────┴──────┘ ``` [Answer] # **Java 7, Score = ~~252~~ 235 bytes** Yep, it's java again; the worst golfing language in the world. This approach uses strings. Arbitrarily large integers are supported in java but would take much more room to code in. Call with `f(intputString)`. Returns the corresponding string. Golfed: ``` String f(String a){char[]b=a.toCharArray();a="";int i=0,j=0,d=0,e=b.length;if(e%2==0)for(;i<e;i+=2)for(j=0;j<b[i]-48;j++)a+=b[i+1];else{for(;i<e;i++)d=d==0?(j=b[i]-48)*0+1:b[i]-48!=j?(a+=d+""+j).length()*--i*0:d+1;a+=d;a+=j;}return a;} ``` Golfed Expanded with structure code: ``` public class LookAndSayExpandedGolfed{ public static void main(String[] args){ System.out.println(new LookAndSayExpandedGolfed().f(args[0])); } String f(String a){ char[]b=a.toCharArray(); a=""; int i=0,j=0,d=0,e=b.length; if(e%2==0) for(;i<e;i+=2) for(j=0;j<b[i]-48;j++) a+=b[i+1]; else{ for(;i<e;i++) d=d==0?(j=b[i]-48)*0+1:b[i]-48!=j?(a+=d+""+j).length()*--i*0:d+1; a+=d; a+=j; } return a; } } ``` Partially Golfed: ``` public class LookAndSayPartiallyGolfed{ public static void main(String[] args){ System.out.println(new LookAndSayPartiallyGolfed().f(args[0])); } String f(String a){ char[] number = a.toCharArray(); String answer = ""; int i, j, longestStreakLength = 0; if (number.length % 2 == 0){ for (i = 0; i < number.length; i += 2) for (j = 0; j < number[i] - 48; j++) answer += number[i+1]; } else{ j = 0; for (i = 0; i < number.length; i++) longestStreakLength = longestStreakLength == 0 ? (j = number[i] - 48) * 0 + 1 : number[i] - 48 != j ? (answer += longestStreakLength + "" + j).length()*--i*0 : longestStreakLength + 1; answer += longestStreakLength; answer += j; } return answer; } } ``` Completely expanded: ``` public class LookAndSay{ public static void main(String[] args){ System.out.println(new LookAndSay().function(args[0])); } String function(String a){ char[] number = a.toCharArray(); if (number.length % 2 == 0){ String answer = ""; for (int i = 0; i < number.length; i += 2){ for (int j = 0; j < number[i] - '0'; j++){ answer += number[i+1]; } } return answer; } String answer = ""; int longestStreakLength = 0; int longestStreakNum = 0; for (int i = 0; i < number.length; i++){ if (longestStreakLength == 0){ longestStreakNum = number[i] - '0'; longestStreakLength = 1; continue; } if (number[i] - '0' != longestStreakNum){ answer += longestStreakLength; answer += longestStreakNum; longestStreakLength = 0; i--; } else { longestStreakLength++; } } answer += longestStreakLength; answer += longestStreakNum; return answer; } } ``` To run, first compile the second entry with: `javac LookAndSayExpandedGolfed.java` Then run with: `java LookAndSayExpandedGolfed` **Edit:** Fixed error. [Answer] # Javascript (in-browser, ES5, IE8+), 152 ``` var s=prompt(),r='',n=r,c=r,i=0;do{c!=s[i]?(r+=n+c,n=1,c=s[i]):n++;i++}while(c)n='';i=0;while(s[i]){n+=Array(1*s[i]+1).join(c=s[i+1]);i+=2}alert(c?n:r) ``` Can be shortened by 4 chars if you skip var, or a few more chars with other intermediate unvarred globals too, but let's pretend we are not bad programmers for a minute. Switching to ES6 short-syntax function with argument and return value instead of using prompt, alert for IO can save more. JSFiddle here: <http://jsfiddle.net/86L1w6Lk/> [Answer] # Python 3 - 159 bytes ``` import re;l=input();x=len;print(''.join([str(x(i))+j for i,j in re.findall('((.)\2*)',l)]if x(l)%2 else[j*int(i)for i,j in[l[i:i+2]for i in range(0,x(l),2)]])) ``` [Answer] # Cobra - 217 (186 if I can assume a `use` statement for `System.Text.RegularExpressions` exists elsewhere) ``` do(s='')=if((l=s.length)%2,System.Text.RegularExpressions.Regex.replace(s,(for x in 10 get'[x]+|').join(''),do(m=Match())="['[m]'.length]"+'[m]'[:1]),(for x in 0:l:2get'[s[x+1]]'.repeat(int.parse('[s[x]]'))).join('')) ``` [Answer] # JavaScript (ES6) 85 Using regular expression replace with function. Different regexp and different function depending on input length being even or odd. ``` F=s=>s.replace((i=s.length&1)?/(.)(\1*)/g:/../g,x=>i?x.length+x[0]:x[1].repeat(x[0])) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->s{s.size%2<1?s.gsub(/(.)(.)/){$2*$1.to_i}:s.gsub(/(.)\1*/){$&.size.to_s+$1}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3_XTtiquL9Yozq1JVjWwM7Yv10otLkzT0NfQ0gUhfs1rFSEvFUK8kPz6z1gpJMsZQCySpBtYJki7WVjGsrYWaqlJQWlKs4BatZGpobGRoqBTLBRMwBAEjIyOgGETtggUQGgA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 (or 17?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` S2ôø`s×IÅγs.ι‚JIgè ``` [Try it online](https://tio.run/##AS0A0v9vc2FiaWX//1Myw7TDuGBzw5dJw4XOs3MuzrnigJpKSWfDqP//NTEzMjExMDA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/YKPDWw7vSCg@PL3ycOu5zcV653Y@apjlVZl@eMV/nf/RBjqGOoZAwlDHyEDHyFDH2EjHFMQGChkBBQ2NjECSQAooBSINgdLGCMoALAuSNzKMBQA). Since the challenge asks for a string input, which by default allows for a list of characters, it would be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) less by removing the leading `S`: [Try it online](https://tio.run/##yy9OTMpM/f/f6PCWwzsSig9P9zzcem5zsd65nY8aZnl5ph9e8f9/tJKpko6SIRAbA7ERlA3CBmAcCwA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/o8NbDu9IKD48vfJw67nNxXrndj5qmOVVmX54xX@d/9HRSgZKsTrRSoZQUgfO14GKGcHFjOBixkCWEZhliqYOWT9EvQ6S2UZQjGyHDooMwnxUUZiMKZRnTKQMupvQsRGq3bEA). **Explanation:** ``` S # Convert the (implicit) input to a list of digits 2ô # Split it into parts of size 2 ø # Zip/transpose; swapping rows/columns ` # Pop and push both lists separately to the stack s # Swap the two lists on the stack # (or swap it with the implicit input if the input was a single digit number) × # Repeat the digits the numbers amount of times (at the same positions of the # lists) I # Push the input again Åγ # Run-length encode it, pushing the list of digits and list of lengths # separately to the stack s # Swap those two lists on the stack .ι # Interleave the two lists into one: # [a,b,c,...] and [d,e,f,...] → [a,d,b,e,c,f,...] ‚ # Pair the two lists together J # Join both inner lists to a number I # Push the input yet again g # Pop and push its length è # Modular 0-based index it into the pair # (after which the result is output implicitly) ``` ]
[Question] [ # Description The Caesar cipher is a cipher, where every letter in the alphabet will be rotated by a secret number. If the rotation is \$7\$, then `a` -> `h`, `g` -> `n`, `v` -> `c` and `z` -> `g`. Today, we're playing Caesar's Cipher with ASCII chars, (0-127 inclusive). So, with rotation \$7\$, `b` -> `i`, `Z` -> `a`, `x` -> `DEL (127)`, But, even if the encoder shifted the chars around the ASCII table, you know, that the original string consisted of only the lowercase, uppercase alphabet, and space. # Task You're given a string of ASCII code points, your task is to print all of the possible original strings if the encoder only used the lowercase and the upper case alphabet (plus space) in the original string. # Rules * The program must take the ASCII char codes of the encoded string as the input * The encoded string is not constricted on lowercase, uppercase, and space, it can (because it's ASCII shifted) include ASCII chars * The output must be all possible original strings (as a list, separated by newlines, etc.) * [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * Lowercase, uppercase, and space: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! --- # Examples ``` [In]: [91, 111, 112, 122, 39, 112, 122, 39, 104, 39, 123, 108, 122, 123, 39, 116, 108, 122, 122, 104, 110, 108] [Out]: This is a test message [In]: [43, 35, 49, 49, 31, 37, 35] MESSAGE NFTTBHF OGUUCIG PHVVDJH QIWWEKI RJXXFLJ SKYYGMK TLZZHNL message nfttbhf oguucig phvvdjh qiwweki rjxxflj skyygmk tlzzhnl [In]: [103, 123, 120, 51, 97, 124, 1, 120, 7, 120, 120, 1, 7, 123, 51, 85, 12, 7, 120] [Out]: The Nineteenth Byte [In]: [78, 82, 78, 78] [Out]: NRNN OSOO PTPP QUQQ RVRR SWSS TXTT UYUU VZVV aeaa bfbb cgcc dhdd eiee fjff gkgg hlhh imii jnjj kokk lpll mqmm nrnn osoo ptpp quqq rvrr swss txtt uyuu vzvv AEAA BFBB CGCC DHDD EIEE FJFF GKGG HLHH IMII JNJJ KOKK LPLL MQMM ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +ⱮØ⁷%Ø⁷ỌfƑƇØẠ;⁶¤ ``` A monadic Link that accepts a list of code-points and yields a list of lists of characters. **[Try it online!](https://tio.run/##y0rNyan8/1/70cZ1h2c8atyuCiYf7u5JOzbxWPvhGQ93LbB@1Ljt0JL/h9sj//@PNjQw1lEwNAITBjoKpoY6CpbmII4JkIAKmkNpCAHlG0MUW5iCODA1sQA "Jelly – Try It Online")** ### How? ``` +ⱮØ⁷%Ø⁷ỌfƑƇØẠ;⁶¤ - Link: list of code-points C Ø⁷ - 128 Ɱ - map (across v in [1..128]) with: + - C add v (vectorises) %Ø⁷ - modulo 128 Ọ - convert to characters (list of potentials, P) ¤ - nilad followed by link(s) as a nilad: ØẠ - alphabetic characters ⁶ - space character ; - concatenate (list of characters "A..Za..z ", A) Ƈ - filter keep those p in P for which: Ƒ - is invariant under: f - p filter keep only those in A ``` [Answer] # [R](https://www.r-project.org), 82 bytes ``` \(s)for(i in 0:127)if(all((x=(s+i)%%128)%in%c(32,97:122,65:90)))show(intToUtf8(x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZU87asQwEO33FGoMM8QBfWxLMvgSIenSLAaxAmPD2iG-SxrvQg6Vm6SMxhoXS4r5vDfvzUhft-t2D933xxKe3c_LO8wYpitEEUchW6UtxgDnYQBYO5ifIhaF0g6LOBY9GF16m0S6bOrWS0ScL9MnxHF5nd6W4GBF5M2_AXrwqhRK7UmnlHzC-H9IVtxoQ8jxbIdZ3jzymk1KyX2AeKJrFenrUlQ-h0mHjSWOBUqa44pOzjrNvSVAu5i0XHNibLLY1QQODS-16V2OSEdx_H_bcv0D) --- With the use of `grepl` instead of filtering char codes: ### [R](https://www.r-project.org), 84 bytes ``` \(s)for(i in 0:127)if(!grepl("[^ a-z]",v<-intToUtf8(x<-(s+i)%%128),T)&all(x))show(v) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZU_NasMwDL73KbxCh0QTiO1kdkb3FtmpP1DKvBlCU5KsK3uVXbLBHqpvsmOtWD2MHvRJ36dPkv313Q4_7un3vXepPVcr6NA1LXjh9yJ7lMqgd3D32r4capguN2Kbfq6nyXGR-n1fNc-9s3BapNDNPc5mUllMKrzf1jWcELu35gOOyLv_HOyglImQcgQVQAXQ5Q3Lci6UJma5N9Jof_ivKx6SMhsbiBO6lpO_SERextDhsDaksUFm-npFhcki9EtDhHaxaDhHYK6j2RZErh5easK7LImWAvn_wxDzBQ) `intToUtf8` has some weird behaviour with the input of `0` (it omits that char altogether) - the workaround here is using `all` to filter that out. [Answer] # [Perl 5](https://www.perl.org/) `-na`, 45 bytes ``` y//\1-\x7f\0/c,/[^\pL ]/||say for(pack'C*',@F)x128 ``` [Try it online!](https://tio.run/##VYzPCsIwDMbvfYqIh6lstGk32@FFEDz5Bk6hjO6iaNkcbLB3n2l3UcifX758iXfts5jXK08dspdlfeegcfbTtw46Ox7mkfMKs2rQTSV4nfLrvfIXuPFpojU073bjbf1ITrskPZ63A0ozzyUCYkgJKCWo8g9FHptUhCaqgaNp/yPJ6EQUQWM5OQrIyxAKQWkaGQq1/JECCoRSE9FJnHWsMSOr4DAF0bJi2oAhNhRf "Perl 5 – Try It Online") The program works as is, but replace `\0`, `\1` and `\x7f` with their literal equivalents for the claimed score. Very simple approach. 128 times, translate `\0-\x7f` to `\1-\x7f\0`, thus shifting each char by one, and check whether it meets the criteria. [Answer] **Based on ophact's [answer](https://codegolf.stackexchange.com/a/245818/111830).** (Sadly I don't have the reputation to comment this instead of duplicating it like this) # [Python 3.8+](https://docs.python.org/3.8/), 97 bytes ``` lambda l:[b for i in range(128)if(b:=bytes(i+c&127for c in l))*all(c==32or 64<c&95<91for c in b)] ``` [Try it online!](https://tio.run/##ZZHdjoMgEEbvfQquKu4aU0DrT@uTWC/EYsuGigFM06d3mWo3u9kLRr8zh8Hg9HQ3PbJiMstQnxfV3fmlQ6pqOBq0QRLJEZluvApMaBHJAfOq5k8nLJaf/Y7QHKweLBVFH51SuK9rRj08pKd@V2ankvwoPGoXeZ@0ccg@bQBcAW@CpiQxIuRVqC/UF1b@S/t0e6EMUrH1XnHVD3853TYRsn812jhoUpCzGKXlupg/leXAoEv27D2f@j2Zb5Y5BJiywXx7rmXLbJWLDMLbgYm5/5wCSAGrDdoKTUaODqsYhZPRl7kXFrmb8DeulH7I8Yomba3kSiDrvHq1VRgd/ZUl1l307JJBzfaGoyP6xfg8DMIkDyOdwDw8j2HypeWIB@z/jFfXM4FHyzc "Python 3.8 (pre-release) – Try It Online") Since both A-Z and a-z are permitted, we can ignore the "case bit" `0x20` (`c | 0x20` or `c & 0x5f`) to get a single range for the letters. There's no need to worry about the out of bounds `0x80`. As we can write `0x5b` (`b'Z'[0]+1`) as `91`, while `0x7b` (`b'z'[0]+1`) could only be as short as `123` (and `0x20==32` is as expensive as `0x5f==95`), we'll choose the uppercase letters' range. `bytes([1,2,3])` is, for all purposes I can think of "just read-only `[1,2,3]`" while already being something string-like we can return. # [Python 3.8+](https://docs.python.org/3.8/), 105 bytes If it **has to** output `str` instead for some reason, we need to add a `.decode()`: ``` lambda l:[w.decode()for i in range(128)if(w:=bytes(c+i&127for c in l))*all(64<c&95<91or c==32for c in w)] ``` [Try it online!](https://tio.run/##ZZDdjoMgEIXvfQquKuyaRkDrT@uTWC/8QcuGBaNuTJ/eZZQ22ewFA@ecbwbC@FweRvN0nLa@uG@q/m66Gqm8XM@daE0nMOnNhCSSGk21HgSmLCWyx2teNM9FzLj9lCfKEqBaoBQhH7VS@BLd2lMW3zIKSVFw9kZWUm0gFIjSKzMaIEr3wmxhtvDsnwojd2AcVOqyXR745a/PXBOl4R5UgVdGAMcBirJjcXsrT8CDlIb8NZ/ZntiGWQICpjgzcftRnOYHnMYgXgxMTOxzUnBSWJVX5WicpF6wCpA/Tqb7acWMlodAvVHKrFIPaDTzLBsl0LxYdJhzn1xdl3/X/vnLSI17bD/67ZPr9gs "Python 3.8 (pre-release) – Try It Online") ~~Is it required to be a `lambda`? Just the business part would be 86 bytes.~~ ``` b for i in range(128)if(b:=bytes(i+c&127for c in l))*all(c==32or 64<c&95<91for c in b) ``` You would get the same output by giving the input in the variable `l` and writing something like `sys.stdout.buffer.write(b'\n'.join(` -paste here- `))` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 85 bytes ``` a=>[...Array(128)].flatMap(_=>/[^a-z ]/i.test(s=Buffer(a=a.map(c=>c+1&127))+'')?[]:s) ``` [Try it online!](https://tio.run/##bY5BboMwEEX3PQWrxlaCw9hQm0qmavc9AaLRiOAqEYEI00jp5akNzqJtFv72n3njP0e8oK2Hw3mMu37fTEZPqIuSMfY6DHglwBWtmGlxfMcz2eliW35g/B1V2wMbGzsSq9@@jGkGghrZyTG1Luo1PAKXlK5XK/pSVs@WTnXf2b5tWNt/EkPKHDYRwCzcCXci8n8uScODC@9U6M12wZ9@13kYAkjmRkXpw5/k1M9mmyjNlyPcEkL62h0YEnFL5@7HzLG59MZnhKIM9yLBiwVWmTc35k6AdLsrDyh/HDD9AA "JavaScript (Node.js) – Try It Online") [Answer] ## PHP 4 (123 chars) The function **f** is accepting an encoded string. ``` function f($s){for($i=128;$i-=print chop($s,'A..Za..z ')?'':"$s\n";)for($j=strlen($s);$j--;)$s[$j]=chr(1+ord($s[$j])%128);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₅ÝIδ+žy%êçʒðKDáQ ``` Outputs as a list of list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//UVPr4bme57ZoH91XqXp41eHlpyYd3uDtcnhh4P//0SbGOgrGpjoKJpYQbGwIxOYgsVgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fx/1NR6eG7luS3aR/dVqh5edXj5qUmHN3i7HF4Y@L/W69BunUPb7P9HR1sa6hgagrCRjqGRkY6xJQrTwARMGRkDmRZgURAbrMgMScgIrNLQ0AAkFqsTbQJUY6pjYglCxoY6xuZALlDY0MAYYpaRgY6poY6lOZAF1Abmm4NJMAazjUEqLEyBLIgUULu5hY4FkGcBRLGxAA). **Explanation:** ``` ₅Ý # Push a list in the range [0,255] # (255 is the lowest single-byte value above 127) δ # Map over this list of integers: I + # Add the integer to each value in the input-list žy% # Modulo-128 ê # Sorted uniquify this list of lists ç # Convert each inner-most integer to a character with this codepoint ʒ # Filter this list of lists of characters by: ðK # Remove all spaces D # Duplicate it á # Only keep all ASCII letters Q # Check if both lists are the same # (after which the filtered list is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~17~~ 15 bytes ``` ₇ƛ⁰+₇%C;U'kBṄ↔⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigofGm+KBsCvigoclQztVJ2tC4bmE4oaU4oG8IiwiIiwiWzEwMywgMTIzLCAxMjAsIDUxLCA5NywgMTI0LCAxLCAxMjAsIDcsIDEyMCwgMTIwLCAxLCA3LCAxMjMsIDUxLCA4NSwgMTIsIDcsIDEyMF0iXQ==) -2 thanks to @lyxal Explanation is for my old code: ``` ₇ƛ⁰+₇%Cṅ;U'ðkB+↔= # This comment line needs some love ₇ # 128, implicitly cast to `0..128` ƛ ; # Map to... ⁰+ # The input plus the offset ₇% # Modulo 128 Cṅ # Converted into a string U # Remove duplicates ' # Filter by... = # Is the original string equal to... ↔ # The string with the following chars removed ðkB+ # " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 117 bytes ``` lambda l:[''.join(map(chr,w))for i in range(128)if(w:=[c+i&127for c in l])*all(64<c<91or 96<c<123or c==32for c in w)] ``` [Try it online!](https://tio.run/##ZZHLbsMgEEX3@QpWNbRWZcDvxF/ieOE4flARQNiV1a93GZtEqrqYYe6dMwMS5meZtOK5sdtQXTfZPm73FsmyDoLPLy0UfrQGd5MNV0IGbZFAQiHbqrHHlOVEDHgtq7r7EG@UZQB0AMiGvLdS4jS@dJeCOrtIXUUZB6KqOHuhK2k2EBJEfaoLGiJK98RcYi7x4p@KYl8wDir3vV0eePrXZ36I0mhvNOGpjgFOQhQXR3B3K8/Agy6N@HM/czOJaxYZCNjizcyfR/KaH3CegHgysDFzz8nBySGaU1MiY4VasAxRYKy@f3f9jJapR4OWUq9CjcjoeRY32aN5ceg4lwE5@6ngqvwfDVgS8vLJefsF "Python 3.8 (pre-release) – Try It Online") Yep... that long. Nothing much to say here; simply loops through the numbers from 0-127 and keeps the word found by shifting by that many units if all characters in such a word are part of the required alphabet. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 39 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Returns a matrix with one possible original per row. ``` 128⊸|{@+𝔽𝕩+⌜˜(∊/⊣)˝𝔽𝕩-˜⌜32∾⥊65‿97+⌜↕26} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMTI44oq4fHtAK/CdlL3wnZWpK+KMnMucKOKIii/iiqMpy53wnZS98J2VqS3LnOKMnDMy4oi+4qWKNjXigL85NyvijJzihpUyNn0KCkbCqCDin6gK4p+oOTEsIDExMSwgMTEyLCAxMjIsIDM5LCAxMTIsIDEyMiwgMzksIDEwNCwgMzksIDEyMywgMTA4LCAxMjIsIDEyMywgMzksIDExNiwgMTA4LCAxMjIsIDEyMiwgMTA0LCAxMTAsIDEwOOKfqQrin6g0MywgMzUsIDQ5LCA0OSwgMzEsIDM3LCAzNeKfqQrin6gxMDMsIDEyMywgMTIwLCA1MSwgOTcsIDEyNCwgMSwgMTIwLCA3LCAxMjAsIDEyMCwgMSwgNywgMTIzLCA1MSwgODUsIDEyLCA3LCAxMjDin6kK4p+oNzgsIDgyLCA3OCwgNzjin6kK4p+pCgo=) This computes the possible shifts for each character, takes the intersection, and shifts the input by all remaining numbers. Generating all shifts and then only keeping alphabetic ones is 2 bytes longer: ``` @+·(∧´˘∊⟜(32∾⥊65‿97+⌜↕26))⊸/128|(↕128)+⌜⊢ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgQCvCtyjiiKfCtMuY4oiK4p+cKDMy4oi+4qWKNjXigL85NyvijJzihpUyNikp4oq4LzEyOHwo4oaVMTI4KSvijJziiqIKCkbCqCDin6gK4p+oOTEsIDExMSwgMTEyLCAxMjIsIDM5LCAxMTIsIDEyMiwgMzksIDEwNCwgMzksIDEyMywgMTA4LCAxMjIsIDEyMywgMzksIDExNiwgMTA4LCAxMjIsIDEyMiwgMTA0LCAxMTAsIDEwOOKfqQrin6g0MywgMzUsIDQ5LCA0OSwgMzEsIDM3LCAzNeKfqQrin6gxMDMsIDEyMywgMTIwLCA1MSwgOTcsIDEyNCwgMSwgMTIwLCA3LCAxMjAsIDEyMCwgMSwgNywgMTIzLCA1MSwgODUsIDEyLCA3LCAxMjDin6kK4p+oNzgsIDgyLCA3OCwgNzjin6kK4p+pCg==) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` x=>Buffer(128).map(_=>/[^ a-z]/i.test(x=x.map(y=>y+1&127))||console.log(''+x)) ``` [Try it online!](https://tio.run/##ZU7LDoIwELz7FZykDc8tKBBTDv4GQUO0NRikBNCA4d8rhR40HnayszOzu/fiVXSXtmx6pxZXJjmVA02PT85Zi4DE2H0UDTrT1MtORuG8c690e9b1aKDDIo00HS3YAokwnqaLqDtRMbcSN2Sa1oCxPGw40vuyBGwDYAEyA5khSP6YH@qGBIrFWlvoat//zokOAfiLkGP8fTVUuZ1thMlawfxAEKmZMsoP "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 83 bytes ``` a=>[...Array(128)].flatMap(_=>/[^a-z ]/i.test(a=Buffer(a.map(c=>c+1&127)))?[]:a+'') ``` [Try it online!](https://tio.run/##bZBRb4MgEMff9yl8WiG2VEALLsFle1@/gHHLxUFr47RRtmT78g6UPqzrw/3hf/c77sIJvmCsh@ZsN13/riejJlBFSQh5Ggb4RpRJXBHTgn2BM3pTxbZ8hc1PVG0bYvVoEajnT2P0gIB8OKJWRR3Te8oExvixrB4gXq3wVPfd2LeatP0BGVTmdB1ROgtzwpzw/J9L0nBh3DsZarNd8N3fPAtNlCZzocL47mpy6nuzdZTmS3C3BBc@dwOmCb9MZ@7FzLG58MbPCEkRzkWC5wssM28uzI0Bwu0uPSB9XAOoGfew9/9HWt0d7DEWOzz9Ag "JavaScript (Node.js) – Try It Online") Handleing part already near Arnauld enough, so I place it here [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ΦE¹²⁸⭆θ℅﹪⁺ιλ¹²⁸⬤ι№⁺⁺αβ λ ``` [Try it online!](https://tio.run/##NYxBC8IwDIX/Stipgwibc2ziSQRvw4HHsUPdRAth1dr692va1Rxe@F7ey/SUZtKSvO@NWqw4K7J3Izr5EuW2Rbhath8B3wgXM6tFkuj07EiLntxHKATKETic8yAciYJ30o6/xUQUiXDjawZZHgo8B@@HoSyq0I1SINQlwr4JsGNJZpP2KomrNdzWAf6ZcfSbL/0A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ¹²⁸ Literal integer `128` E Map over implicit range θ Input array ⭆ Map over elements and join ι Outer value ⁺ Plus λ Inner value ﹪ Modulo ¹²⁸ Literal integer `128` ℅ Convert from ASCII code Φ Filtered where ι Current string ⬤ All characters satisfy № (Non-zero) Count of λ Current character in α Uppercase letters ⁺ Concatenated with β Lowercase letters ⁺ Concatenated with space Implicitly print each solution on its own line ``` [Answer] # [Perl 5](https://www.perl.org/), 63 bytes ``` sub{grep!/[^a-z ]/i,map{//;join'',map chr($_+$'&127),@_}0..127} ``` [Try it online!](https://tio.run/##ZVHZctpAEHwOX9GhiAUVbC5jwBQJNwKBuAQ@gLg4VgeIldDB5fK3EwlE2amodkfT3bOzo5ZODDV5Coi5k2nP3iWD6N8joz/T2yMmESW8nurvkUh2qSmUYVyEuWwEA28/A8xNLJ4KhfNvH9G7Oyf9OGV9omYEfSOMMrEwYrFziDsh7oRE5j8UvfeSeMJFaU87w0v5w7983DsUi0XPwsQH5H5hxAiyYsJZU1jEtLAmpjmVCDPBJOyOc@82TIZxn7nshDNZIuVy1w6bXbBV6fcLtQr4qiAU2SratcGgVK@hww6H5QaLbv3pqcLV0Ws8P1ebDfS5l5dai4PQfH1l@abTyHu820FFy5rJIjTJtueKBF3ebhdLGRtltyMrBcZyvxfVJczV4SCtV7DU41Gmaug6dSyauHoTd7436QydSbnAdcAjU977EjycuBSnky641nzxioBXKLEIoZaM4sH6NCrleJ12j6Td/cUcvsfzaPfbbXSETgfdQbeL3rDXQ/@p34fwLAgYvAwGGL4Oh5iS6RQzcTbDXJrPsZAXCxCFEIhLUfz0SVpJEmRVlqGsFQVLulxipa1WUHVVxXqzXoMalEIzNQ26pevY2JsNjK1hwNyZJqy9ZcE@2PZnz@1xu0WhUiigWC0WUaqVSiiz5TIq9UoF1Ua1ihpXq4FtsizqrXodDb7RANfmODQ7zSZa3Vbr8gdC7@e260MwoIQDJJTLB96yHpWXcjcBMZgPKKELpRsKtUT/j9sHc0wVqtvWo0s7BWNK9jqZW2Tx6EAyppJ20RxVGtMx9Yd93/yO4gfZwJ@X/PgNps0xeATDtwU4adb3cfoL "Perl 5 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 84 bytes ``` [ 128 iota [ '[ _ + 128 mod ] ""map-as ] with [ R/ [a-z ]+/i matches? ] map-filter ] ``` [Try it online!](https://tio.run/##VVDLTsMwELznK0a9cKiaxnZDEjhwRFw4gDhFEbLCprVok@AY6EP99rA2rQqWdz07MxpL2@jadXZ8eX54vL/BQB@f1NY0YKPdKv4iLw5o7C4QeCfb0hqWlrTtL@6Yts7qAb0l53a9Na3Dklqyem322pmuHXAbRYcIfA4oBITwJSGkhCr@wWQRHqkY5oH1OJiu/1AyOIVIAnc8RS/YmWJR@KsEVObHsygS9ZsrE6QCRcaII8KchR4qYOUdecroJJ1Dshy59D3zvx7HktUcpnMaJa5KvGIamE33hgqTyUb3M15NhW/DCyzxNEepZ3tU07nxS61XNNyx7H2NWTuyqEYe2BrHMQuk69X4Aw "Factor – Try It Online") [Answer] # APL+WIN, 74 bytes Prompts for code points ``` ⎕av[((⍴n)=+/m∊(i,53)⍴32,∊(⊂65 97)+¨⍳26)⌿m←i|((i,⍴n)⍴n)+⍉((⍴n←⎕),i)⍴⍳i←128] ``` Unfortunately Dyalog APL Classic's atomic vector does not line up with ASCII code points whereas APL+WIN does so I cannot demonstrate via TIO as I would do normally. [Answer] # [Behaviour](https://esolangs.org/wiki/Behaviour), 78 bytes ``` u=&(127*&(f=a;s=c*&(f+a)%127~(s<~&[a==32(a>64a<91)(a>96a<123)])@s*ascii>&a+b)) ``` test with: ``` @u:c={43 35 49 49 31 37 35} @u:c={91 111 112 122 39 112 122 39 104 39 123 108 122 123 39 116 108 122 122 104 110 108} ``` ungolfed and commented: ``` uncypher = &( 127*&( // do the following sequence 127 times off = a // get offset from iterator s = c*&(off+a)%128 // rotate each character from /c by the offset ~(s<~&[ // stop sequence if the previous result has any invalid character (a==32) (a>64 a<91) (a>96 a<123) ]) @(s*ascii)>&a+b // convert ascii num to char, reduce to string and print ) ) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~159~~ 136 bytes * -23 bytes thanks to ceilingcat As `NUL` is a valid character, also takes the counted string length. The function first iterates through each shifted string to verify that all the decoded characters are valid (and bails early if not), then prints the shifted string if it is still valid. ``` #define v;for(r=0;a&&r<l;r++ a,h,r,c;f(s,l)char*s;{for(h=128;a=h--;a&&puts("")){v)a=isalpha(c=s[r]+h&127)|c==32 v)putchar(s[r]+h&127);}} ``` [Try it online!](https://tio.run/##ZVHBbqMwEL3zFaNUjWwwqxiSAnLcL6j2tqdsDpYDBcklESbpIcuvLzsDVGq0SB785r15AzM2frd2HJ9OZdW0JdxUde5YpzfKrNfd3qkuigIjatEJqyrmheO2Nl3o1Z2EtZZJroyu45gKLtfes9WK8/uNG9144y61YVb7Q3eM6rVMMv7Hap0mcOOoJSf2jVPDMD41rXXXUwl735@a84/6NQhIB2Ff@v5w1PcAgFHmcOT3QgqQcgoJhgRDWvyHNtvlkqSE8oWb4Cx/ecwnS5GUm4kYxPemWyrbCdgW80mxf5pR7lEnN@lXzwR9digrMgLkvCSz5T2HBaezON8R@NI8emf4sTlxOZ2J@/nr7S0YVNC0Pbiy9TQr/JNMyEJsMT8RH6Zp2e3cnDjQIOfJhr3CO9GhQx0ArbbXNHABTpOZwvkr6KMIExTmTcf04LonL4BLhx4VWx2e/RH06@92JbCMq4msWIhuoZvgEAzjX1s58@7H@PMf "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 66 bytes ``` ->a{(1..127).map{|n|a.map{((_1+n)%128).chr}*""}.grep /^[a-z ]+$/i} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3nXTtEqs1DPX0DI3MNfVyEwuqa_JqEsEMDY14Q-08TVVDIwtNveSMolotJaVavfSi1AIF_bjoRN0qhVhtFf3MWqhJigUKbtHRJsY6CsamOgomlhBsbAjE5iCx2FiIwgULIDQA) ]
[Question] [ # Challenge Inspired by [this](https://www.youtube.com/watch?v=HY_OIwideLg) video. As you may know, a palindrome is a word that is spelled the same forward as it is backward. The word "PULP" is not a palindrome, but when translated into Morse Code (with the spacing between letters removed), "PULP" becomes ".--...-.-...--." which is a palindrome. Your task is to write a program or function which takes a string and returns whether that word is a palindrome in International Morse Code. ``` 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: --.. ``` # Rules ## Input Input can be taken in any reasonable format. The input string will contain only letters in any case you prefer. The string will not contain spaces, numbers, or punctuation. ## Output Your program should output 1 of 2 constant distinct results based on whether the input is a palindrome, e.g. True/False, 1/0, HOTDOG/NOTHOTDOG ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins. Standard loopholes are forbidden. # Test Cases | Input | Output | | --- | --- | | "PULP" | True | | "RESEARCHER" | True | | "HOTDOGS" | True | | "" | True | | "A" | False | | "RACECAR" | False | | "PROGRAMMING" | False | | "PUZZLES" | False | [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` ØAŻŻ“¡9o|çṫ¡X1ỴỌġQ’œ?iⱮḃ2FŒḂ ``` [Try it online!](https://tio.run/##y0rNyan8///wDMeju4/uftQw59BCy/yaw8sf7lx9aGGE4cPdWx7u7jmyMPBRw8yjk@0zH21c93BHs5Hb0UkPdzT9P9z@qGnN///RSgGhPgFKOgpKQa7Bro5Bzh6uQSCeh3@Ii797MIgJwo5gFY7Ors6OYOmAIH/3IEdfX08/dzA3NCrKxzVYKRYA "Jelly – Try It Online") ``` ØA The uppercase alphabet. ŻŻ Prepend two zeroes. “¡9o|çṫ¡X1ỴỌġQ’œ? Get the 73540211105102870315464559332nd permutation. (= “ETIANMSURWDKGOHVF0L0PJBXCYZQ”) iⱮ Find indices of input letters in this list. ḃ2 Bijective base 2: map [1,2,3,4,5…] to [1], [2], [1,1], [1,2], [2,1], … F Flatten. ŒḂ Is palindrome? ``` I wrote this answer looking at one of these (read the rows from right-to-left, and you get my magic string!): [![enter image description here](https://i.stack.imgur.com/zkE3i.png)](https://i.stack.imgur.com/zkE3i.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35 32 27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/Code-page) -2 thanks to Dennis (shift the permutation to avoid `%32`) ``` Oị“¡\ḣḶɼz3ç³ƝMƒ§’Œ?¤ḃ2FŒḂ ``` Takes input in upper-case; output is `1` for true, `0` for false. **[Try it online!](https://tio.run/##AUEAvv9qZWxsef//T@G7i@KAnMKhXOG4o@G4tsm8ejPDp8Kzxp1NxpLCp@KAmcWSP8Kk4biDMkbFkuG4gv///yJGT09MIg "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9//4e7uRw1zDi2Mebhj8cMd207uqTI@vPzQ5mNzfY9NOrT8UcPMo5PsDy15uKPZyO3opIc7mv4f3XO4/eHOfSqPmta4//8frRQQ6hOgpAADygq2dgohRaWpXDpKQa7Bro5Bzh6uQUpoMh7@IS7@7sFKmHoQJqHLOCphyLgl5hSDLXJ0dnV2DFLCIhUQ5O8e5Ojr6@nnroQuFRoV5eMajKkrFgA "Jelly – Try It Online"). ### How? ``` Oị“...’Œ?¤ḃ2FŒḂ - Link: list of characters (in [A-Za-z]), S e.g. 'FoOl' O - to ordinals [70,111,79,108] %32 - modulo by 32 (A->1, a->1, ...) [6,15,15,12] ¤ - nilad followed by link(s) as a nilad: “...’ - base 250 literal = 41482574787853596522350494865 Œ? - first permutation of [1,N] which resides at that - index when all permutations of [1,N] are sorted - = [8,16,10,24,26,27,18,20,4,23,25,11,1,17,13,15,3,22,12,19,6,5,14,21,28,9,7,2] - index into (modular-indexing & vectorises) [17,14,14,19] ḃ2 - to bijective base 2 (vectorises) [[1,1,2,1],[2,2,2],[2,2,2],[1,2,1,1]] F - flatten [1,1,0,1,0,0,0,0,0,0,1,0,1,1] ŒḂ - is palindromic? 1 ``` --- Previous 35 byte solution (also takes input in upper-case)... ``` ØẠḣ29“...’œ?iⱮ⁸d⁴BnⱮ/€FŒḂ - Link: list of characters (in [A-Z] only), S ØẠ - alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' ḣ29 - head to index 29 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabc' “...’ - base 250 literal = 1222276956185766767980461920692 œ? - permutation at index = 'EAIWRUSJPaLbFVHcTNMDKGOBXCYZQ' ⁸ - chain's left argument = S e.g. 'FOOL' Ɱ - map with: i - first index of (char in 'EAI...') [13,23,23,11] ⁴ - literal 16 16 d - divmod [[0,13],[1,7],[1,7],[0,11]] B - to binary (vectorises) [[[0],[1,1,0,1]],[[1],[1,1,1]],[[1],[1,1,1]],[[0],[1,0,1,1]]] € - for each: / - reduce by: Ɱ - map with: n - not equal [[1,1,0,1],[0,0,0],[0,0,0],[1,0,1,1]] F - flatten [1,1,0,1,0,0,0,0,0,0,1,0,1,1] ŒḂ - is palindromic? 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~172~~ ~~148~~ 104 bytes *First code golf ever. Please be kind and offer any help :)* This is based off the C# answer: <https://codegolf.stackexchange.com/a/175126/83877>. I took the same ideas and applied it to Python 3. I tried my best to golf-ify the code, but I am sure there is a lot more I can do. EDIT 1: Thanks @Stephen and @Cowabunghole for helping me remove some whitespace and unnecessary code. EDIT 2: Thanks @JoKing for the suggestion to do it in binary. This is a really neat trick where '-' and '.' are not even necessary. This led to a huge byte decrease. ## Solution ``` def b(w):x=''.join(map(lambda c:bin(' ETIANMSURWDKGOHVF L PJBXCYZQ'.index(c))[3:],w));return x==x[::-1] ``` [Try it online!](https://tio.run/##Vcy7DoIwAEDR3a/o1jZRE8NWw1Chggq2FvCBYQDBiNFKCMb69aiLScd7htu8u8tDWX1fVmdQoBcm2oZwfH3UCt3zBt3ye1Hm4ESKL0AAWLyg6zBK5M5dedzfzkEAxHK2dw7pBo5rVVYanTA@WiQbvjCetlX3bBXQtq2PhIwmWd@0tepQgaBIAgExHvxBsohR6fhMGuzz2OVeZJgR1LxQhznUXAjJPUnDcLH2TE/SNGC/df8B "Python 3 – Try It Online") [Answer] # [Dyalog APL](https://www.dyalog.com/), 24 bytes ``` ⎕CY'dfns' ⎕←(⌽≡⊢)∊morse⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1LiD7UdsEjUc9ex91LnzUtUjzUUdXbn5Rceqj3nn//weE@gQAAA "APL (Dyalog Unicode) – Try It Online") `dfns` never ceases to amaze [Answer] # [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), 325 bytes *First attempt, before the big guns get here* :-) ``` 1 DATA .-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.. 2 DIM C$(26):FOR I=1 TO 26:READ C$(I):NEXT:INPUT T$:FOR I=1 TO LEN(T$):N=ASC(MID$(T$,I,1))-64:S$=S$+C$(N):NEXT:L=LEN(S$):FOR I=1 TO L:IF MID$(S$,I,1)<>MID$(S$,(L+1)-I,1) THEN 4 3 NEXT:PRINT"True":END 4 PRINT"False ``` Output ``` ? PULP True ? RESEARCHER True ? HOTDOGS True ? True ? A False ? RACECAR False ? PROGRAMMING False ? PUZZLES False ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 111 bytes ``` x=>(u=[...x.replace(/./g,_=>"**ETIANMSURWDKGOHVF*L*PJBXCYZQ".indexOf(_).toString(2).slice(1))])+''==u.reverse() ``` [Try it online!](https://tio.run/##bczLCoJAGEDhfY/hxhmrX2obI5iNWVmaZldCRCcxxBFv@PaTrWv7HTjvqIvquMrKZlrwhAmTiJ5oqCUPAOihYmUexQypoKaTkGiSotDTRj/s/cC7rHZrxzqbiq242@XVuN2PEmRFwnrnhUIMDfebKitSNMdQ59lwmWH8xGNZJqQdzh2raoawWIxiXtQ8Z5DzFJlIcgPblTD@cY/6VPcMi3r/qv5F8QE "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 87 bytes ``` {$_ eq.flip}o*.trans(/./=>{S/.//}o{' ETIANMSURWDKGOHVF L PJBXCYZQ'.index($/).base(2)}) ``` [Try it online!](https://tio.run/##XcxNC4JAEAbgu79iWKI0YoUOXcJgs00rTdvVPryE0QqRZWlBIv52iyLI5vIyD@/MRaRxrzrl0IxAg6pobEFccRQfLmXSxrc0PGeyilVtUPBXqGVStACoNyFzm/tsNZoZjrkcgwXudLjWN8GihQ/nvXjIDVXBuzATclcplaovRUkKyPUtF8FntAF46V10JMQop4TpJmXoR03HGzkGR/Xu97quBNV0HMbZ@zHRqU4Y@mOXOQYjtj2ZG@iX/SCwKK@1oZBeWxbmEMn4KHJFKqsn "Perl 6 – Try It Online") Converts the word to a series of 1s and 0s and checks if it is palindromic. ### Explanation: ``` *.trans(/./=> # Translate each letter of the input to '...'.index($/) # The index of the letter in the lookup string .base(2) # Converted to binary {S/.//}o{ } # With the first digit removed {$_ eq.flip}o # Return if the string is equal to its reverse ``` [Answer] # Pyth, ~~35~~ 33 bytes The code contains unprintable characters, so here's a hexdump. ``` 00000000: 5f49 7358 7a47 632e 2207 0901 3f08 82ee _IsXzGc."...?... 00000010: bd3f c256 9d54 c381 7dac 6590 37d3 c8f5 .?.V.T..}.e.7... 00000020: 52 R ``` [Try it online.](http://pyth.herokuapp.com/?code=_IsXzGc.%22%07%09%01%3F%08%C2%82%C3%AE%C2%BD%3F%C3%82V%C2%9DT%C3%83%C2%81%7D%C2%ACe%C2%907%C3%93%C3%88%C3%B5R&input=researcher&test_suite_input=pulp%0Aresearcher%0Ahotdogs%0A%0Aa%0Aracecar%0Aprogramming%0Apuzzles&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=_IsXzGc.%22%07%09%01%3F%08%C2%82%C3%AE%C2%BD%3F%C3%82V%C2%9DT%C3%83%C2%81%7D%C2%ACe%C2%907%C3%93%C3%88%C3%B5R&input=researcher&test_suite=1&test_suite_input=pulp%0Aresearcher%0Ahotdogs%0A%0Aa%0Aracecar%0Aprogramming%0Apuzzles&debug=0) ### Explanation Starting from `."` the end of the code generates the Morse alphabet, with dots as `\x08` and dashes as `\x07`, and separated by tabs. `c` splits the string by the tabs. `XzG` translates (`X`) the input (`z`) from the alphabet (`G`) to this "Morse alphabet". `s` sums (joins) the Morse symbols together. For empty inputs, returns 0, but this is not a problem. `_I` checks if the result does not change (`I`) when reversed (`_`). For empty input, checks if 0 does not change when negated. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 107 bytes ``` PalindromeQ[##2&@@@(IntegerDigits[Tr@StringPosition[" ETIANMSURWDKGOHVF L PJBXCYZQ",#],2]&/@Characters@#)]& ``` [Try it online!](https://tio.run/##RcrRCoIwAIXhVxkTpEAQeoKZrlo1nXNlJl6MGjbICXN30bOb2UV35@P8nXQP1Umnb3JkVhtXj0w@tbnbvlN57XkrHyG0IMapVtlEt9oNtbCocFPcsn7QTvemhgALEqW0OPEyOWyz3XkDjoDt15e4uuYw8Jpg1fghih/SyptTdkDesvFHECLwgiQVmDOOBU5gAGCcUUaOv13OnyAUf1WcKP2L8UzgWGQ8ErOnkJOJFXw34wc "Wolfram Language (Mathematica) – Try It Online") Similar to [this](https://codegolf.stackexchange.com/a/174327/74672) Jelly answer: we think of Morse code as binary, and write down a string `" ETIANMSURWDKGOHVF L PJBXCYZQ"` where the position of a character, in binary, gives us its Morse code. But with an extra 1 prepended because we want to distinguish `S = 000` and `H = 0000`, for instance. Then `##2&@@@` simultaneously gets rid of this leading 1 and flattens. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~204~~ 187 bytes ``` param($a);$a|% t*y|%{$b+=[convert]::ToString(" ETIANMSURWDKGOHVF L PJBXCYZQ".IndexOf($_),2).substring(1)};$c=($b=($b|% *ce 0 .|% *ce 1 -)).ToCharArray();[array]::Reverse($c);$b-eq-join$c ``` [Try it online!](https://tio.run/##nVJdb9owFH1ufsWVZaYYmqzwWIS0jIaPDUiWhG4DodYJd6VVSDLHWYuA386MSNvwuD3YvvfonnOP7ZulzyjyFcbxgc6gA9tDxgVf65SzNuW7Gsj6Zlfb0rDRmUdp8geFXFxfB6kvxWPyoBMAOxhak7E/9b7ffO07g9sejMD98vlH9@fsGzGHyRJfnF86vWOXLWbmRZifmE22b9Ooo9PwuFSjeoRwBWYZNcFgzAzS7ooLSwi@0Vl7zo@Bau@h8pGjTiNlMjTwt/GUPiY0OuzbGpWYy1zd5JOuXRB3OnLJJZBAFEhU7tm@bXndge1V0YET3Dh9vwpZx6TH4/xEs7p21/LOMNdz@p41Hg8n/XN8OpuNbL@CMY2mhcyK0hbTrkxTP/k0Y0we5Opjy2gy2EENttpFWaxqJ/hsOOETRhKI658i8l6gCNZyaYxxHaKA8gw2GcIkleiKNFO/tQFjwtcKOm7GLY8LBHJPaGlg3qrTuwW7JxXdf5G1XzJlCpev0hVVaEBz8X@qHuZFLN809Q9qNg0OZ5bflHNodOC1i7Z/f@wd9FKx5tIIeBjj4TQMfwE "PowerShell – Try It Online") **Errors on null string... Can anyone help with this?** Test code (After wrapping the code in a Script Block and assigned to variable $Z...): ``` $tests = @( "PULP", "True" "RESEARCHER", "True" "HOTDOGS", "True" "A", "False" "RACECAR", "False" "PROGRAMMING", "False" "PUZZLES", "False" ) $outputs = @() for($i = 0; $i -lt $tests.length/2; $i++){ $output = New-Object "PSObject" $output | Add-Member -MemberType NoteProperty -Name Name -Value "`"$($tests[2*$i])`"" $output | Add-Member -MemberType NoteProperty -Name Expected -Value $tests[2*$i + 1] $output | Add-Member -MemberType NoteProperty -Name Result -Value $(&$Z -a $tests[2*$i]) $outputs += $output } $outputs | Format-Table ``` Output: ``` Name Expected Result ---- -------- ------ "PULP" True True "RESEARCHER" True True "HOTDOGS" True True "A" False False "RACECAR" False False "PROGRAMMING" False False "PUZZLES" False False ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 87 bytes ``` [B-ILNPRSZ] $&. [AJKMOQT-Y] $&- }T`L`\EDKN_UMS\EWNRTTMWGAI_ISADKG +`^(.)(.*)\1$ $2 ^.?$ ``` [Try it online!](https://tio.run/##Fce7DoIwFADQ/X5HNVVDE/0Bc4WmVPrytoQICDg4uDgYV7@9xrOd9@PzfN3zinO15OFUaOMCxf4GbC1gwHNj/SUV1/8L@KbFLKOsGje3No6yc5SS7RTqWUesGgW7ZeJiw8V2M@4ZsANM4shyDq0JQDJKpLKWBLVPlVcRAIGwlCUSBPKK0FrtFIS2742MPw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` [B-ILNPRSZ] $&. ``` All the Morse codes for the letters in this set end with `.`. ``` [AJKMOQT-Y] $&- ``` All the Morse codes for the letters in this set end with `-`. ``` T`L`\EDKN_UMS\EWNRTTMWGAI_ISADKG ``` Replace each letter with the letter whose Morse code is the prefix of that letter (here `E` and `T` are simply deleted via the unescaped `_`, but normally they would be turned into spaces). For instance, `P` is the Morse code for `W` with an extra `.` on the end; we added the `.` above so now all that remains is to decode the `W`. ``` } ``` Repeat the above stages until there are no letters left. ``` ^(.)(.*)\1$ $2 ``` If the first and last characters are the same, delete them both. ``` +` ``` Repeat for as many characters that match. ``` ^.?$ ``` If this was a palindrome, then there is at most one character left. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 37 bytes ``` v•1êÿµµÈ∞Ƶipδ8?a¡š%=тîδ/•3B0¡Aykè}JÂQ ``` [Try it online!](https://tio.run/##AU4Asf9vc2FiaWX//3bigKIxw6rDv8K1wrXDiOKInsa1aXDOtDg/YcKhxaElPdGCw67OtC/igKIzQjDCoUF5a8OofUrDglH//3Jlc2VhcmNoZXI "05AB1E – Try It Online") --- Encodes the alphabet in base 3, converted to base 255: ``` 12021110212102110101121022101111011012220212012110220210222012210221201210111020112011120122021120212202211 ``` Base 255: ``` •1êÿµµÈ∞Ƶipδ8?a¡š%=тîδ/• ``` Then basically, I break it apart on the 0's, construct the string by position and check for palindrome. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 191 bytes ``` a=>{var s="";int r=1,x=0,i;foreach(var t in a){var c="";for(i=" ETIANMSURWDKGOHVF L PJBXCYZQ".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;s+=c;}i=s.Length;for(;x<i;x++)r=s[x]==s[i-x-1]?r:0;return r;} ``` [Try it online!](https://tio.run/##fZBRa8IwFIXf/RWXwqBF26mPi3HUWqtba12rc1N8KDHqBZdCEqVD/O2uCsIetubhws35zs25YcpmueSXg0KxhfRbaf5F4HfnePl@z5nGXCgn4IJLZATYPlMKXDjVlM40MhgcBOsoLUtjA4XuwoZeMto9HTMJihoGKS9B0lajoM0Gkk35aMZ25lXWgAIy64ayK1qKJlID/OnIHUfpLJn3X4N4@D6AECYvvQ/vc/FmOCOx5kW8MbVFsNsk@EjbVmm3HWOJtv3QXtUZUXXKyBmpckIutnp3G02KDpKiXrckVctiRcuKdmG3Vs/yqUkk1wcpQJLzhdyXO@a4hihDYVqnGgB45V/ke@7MJWoeouDmxjQms3BiWBb5F0j81HcTb@gnldgwnvbjIK1kKkW3OoXr@Z5bHWGSxEHiRtFoHFRzs8Ui9P@OWur3PuHZ@maxruD5fOml1zP9AQ "C# (.NET Core) – Try It Online") Part of this answer was adapted from [Nick Larsen's morse code golf](https://codegolf.stackexchange.com/a/157/83280). Based on the comments on the answer, this could potentially be golfed further. Ungolfed: ``` a => { var s = ""; // initialize s int r = 1, x = 0, i; // initialize r, x, and i /* This portion was adapted from Nick Larsen. He described it as follows: -- The string of characters is a heap in which the left child is a dot and the right child is a dash. -- To build the letter, you traverse back up and reverse the order. I have edited it to remove number support, which saves 34 bytes. */ foreach(var t in a) { var c = ""; for(i = " ETIANMSURWDKGOHVF L PJBXCYZQ".IndexOf(t); i > 0; i /= 2) c = "-."[i-- % 2] + c; s += c; } i = s.Length; // reuse i and set to the length of the morse code string for(; x < i; x++) // increment x until x reaches i r = s[x] == s[i - x - 1] ? // if the xth character on the left side of s is equal to the xth character on the right side of s r : // true: do not change r 0; // false: set r to zero (set to false) return r; } ``` [Answer] # [Scala 3](https://www.scala-lang.org/), 121 bytes. Golfed version. [Try it online!](https://ato.pxeger.com/run?1=bU9Nb4JAFLzvr3jhtBy6SdNLY4IJ4hZtRShIP2was-Bqt4WFLKvBGH9JL17a_-Qv6bWkeGp4l5c3k5k38_ldpSxjV8cTFXlZKA1_N9lokZH0jQkp5JosECqSd55q8BoE9gihLcsg6UVaNbzVHxRFxpkE62ujVxfXp92C5KzEqdUfS83XXBFdDIRkatcqsAFAZ2N76kVx-Di8c_3Rww1MILgdPDnP83uDCLnktb_CqWmSapNUreyyufKP1oOUouS4tvq1ZdVE8S1XFTfPAX4AlnwFeRMXM7WuemArxXYvrfTV7EEshQar6QLNlA2qM4kTbATxJDBM8z8c0ojaoTOiYQc58mdD3406mA7I7nK3HerYXdZB6Luh7XnjqdvFxvP5hJ4fH9ABtfWPx3b_Ag) ``` _.map(c=>Integer.toBinaryString(" ETIANMSURWDKGOHVF L PJBXCYZQ".indexOf(c)).substring(1)).mkString.pipe(x=>x==x.reverse) ``` Ungolfed version. [Try it online!](https://tio.run/##bY67boMwGIV3nuIXk1mQuiJRyRAXaCFQCL1QdTDEQbRgIuMmRFWenVgh6lAxnvPpXIaKtnSa@vKLVRIi2nD41QC2bAclOlqQSdHw2rDA6fuWUQ72lQMcaAujUkezo3tUgX0PAZesZsKUvdNwKk5zFukAZBPgdZTl6evqyYv9lwcIIXl03tz34lk3G75lY7xDlWGYw085zLE7pbrvueO6qNZsGE3BDkwMTFln7fa0U7cRFfVgARaCnj7m1Ke6nfNG/n3eK1e2HJVIT/Iw0Q3jv52SjODU9Um6AP14s4q9bIEsWHipHbvExUvVSRp7KY6iYO0t0bwoQnIbPmtnbZou) ``` object Main { def b(w: String): Boolean = { val x = w.map(c => Integer.toBinaryString(" ETIANMSURWDKGOHVF L PJBXCYZQ".indexOf(c)).substring(1)).mkString x == x.reverse } def main(args: Array[String]): Unit = { println(b("PULP")) println(b("RESEARCHER")) println(b("HOTDOGS")) println(b("")) println(b("A")) println(b("RACECAR")) println(b("PROGRAMMING")) println(b("PUZZLES")) } } ``` [Answer] # GNU sed -E, 139 bytes ``` :r s/[AFHIJLPRSUVW]/E&/g s/[BCDGKMNOXYZ]/T&/g y/ABCDFGHIJKLMNOPQRSUVWXYZ/TSRIRNSEOADTEMGKNIAUMUWD/ tr :p s/^(.)(.*)\1$/\2/ tp /../c0 /0/!c1 ``` This program transforms each line of input (must be upper-case) to either `1` (for a Morse palindrome) or `0` (otherwise). The first loop (`r`=reduce) converts to Morse, represented using `T` for dash and `E` for dot (so we don't need to convert those two letters). The second loop (`p`=palindrome) removes matching start and end characters. If there are two or more symbols remaining, it's not a palindrome, so output `0`. If we didn't produce `0`, then the result should be `1`. --- I did attempt to convert to an easier alphabet to work with (so we could use character ranges in the `s` command), but none saved enough to outweigh the conversion cost. ]
[Question] [ [You run a political website](https://projects.fivethirtyeight.com/2018-midterm-election-forecast/house/), and have determined that [people have a better intuitive understanding](https://fivethirtyeight.com/features/the-media-has-a-probability-problem/) when the chance of winning or losing an election is expressed as a *ratio* ("5 in 7") than when it is expressed as a *percentage* ("71%"). But you also don't want to display confusing ratios like "58 in 82", you'd like them to be more easily understood, even if they aren't quite as precise. So, **given a percentage between 0.1% and 99.9%, return the closest "easy-to-understand" ratio "*x in y*", using the following rules**: 1. Most values (see exceptions below) should return the **closest ratio out of 10 or lower**. 55% should return "5 in 9", not "11 in 20". 2. Ratios should be **reduced to their lowest terms**. 65% should return "2 in 3", not "4 in 6". 3. Values under 10% should return the **closest ratio of the form "*1 in n*" where *n* is one of (10,12,15,20,30,40,50,60,70,80,90,100)**. For example, 6% should return "1 in 15". 4. Values over 90% should return the **closest ratio of the form "*n-1 in n*" where *n* is one of (10,12,15,20,30,40,50,60,70,80,90,100)**. For example, 98.7% should return "79 in 80". 5. Values under 1% should return "**<1 in 100**" 6. Values over 99% should return "**>99 in 100**" Or, to think about it another way, your program should return the **closest ratio from the following possible outputs** (I've included their approximate values for your convenience): ``` <1 in 100 1 in 100 = 1.00% 1 in 90 = 1.11% 1 in 80 = 1.25% 1 in 70 = 1.43% 1 in 60 = 1.67% 1 in 50 = 2.00% 1 in 40 = 2.50% 1 in 30 = 3.33% 1 in 20 = 5.00% 1 in 15 = 6.67% 1 in 12 = 8.33% 1 in 10 = 10.00% 1 in 9 = 11.11% 1 in 8 = 12.50% 1 in 7 = 14.29% 1 in 6 = 16.67% 1 in 5 = 20.00% 2 in 9 = 22.22% 1 in 4 = 25.00% 2 in 7 = 28.57% 3 in 10 = 30.00% 1 in 3 = 33.33% 3 in 8 = 37.50% 2 in 5 = 40.00% 3 in 7 = 42.86% 4 in 9 = 44.44% 1 in 2 = 50.00% 5 in 9 = 55.56% 4 in 7 = 57.14% 3 in 5 = 60.00% 5 in 8 = 62.50% 2 in 3 = 66.67% 7 in 10 = 70.00% 5 in 7 = 71.43% 3 in 4 = 75.00% 7 in 9 = 77.78% 4 in 5 = 80.00% 5 in 6 = 83.33% 6 in 7 = 85.71% 7 in 8 = 87.50% 8 in 9 = 88.89% 9 in 10 = 90.00% 11 in 12 = 91.67% 14 in 15 = 93.33% 19 in 20 = 95.00% 29 in 30 = 96.67% 39 in 40 = 97.50% 49 in 50 = 98.00% 59 in 60 = 98.33% 69 in 70 = 98.57% 79 in 80 = 98.75% 89 in 90 = 98.89% 99 in 100 = 99.00% >99 in 100 ``` **Other stipulations:** * Numeric input can be in the range of **0.1 to 99.9** or in the range of **0.001 to 0.999**, whichever is more convenient. You must handle at least 3 significant digits. * You must output a *ratio* ("3 in 4"), not the equivalent *fraction* ("3/4"). * If there are two ratios equally close to the input, your program can return either one. 7.5% could return "1 in 12" or "1 in 15". * Leading/trailing white space and/or new lines are fine **Examples**: ``` Input : Output 0.5 : <1 in 100 1.0 : 1 in 100 1.5 : 1 in 70 7.5 : 1 in 15 or 1 in 12 (either is acceptable) 9.2 : 1 in 10 13.1 : 1 in 8 29.2 : 2 in 7 29.3 : 3 in 10 52.7 : 1 in 2 52.8 : 5 in 9 72.0 : 5 in 7 73.9 : 3 in 4 88.8 : 8 in 9 90.8 : 9 in 10 94.2 : 19 in 20 98.7 : 79 in 80 98.9 : 89 in 90 99.0 : 99 in 100 99.1 : >99 in 100 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, shortest code in each language wins. (Similar to, but not duplicate of: [Convert a decimal to a fraction](https://codegolf.stackexchange.com/questions/17239/convert-a-decimal-to-a-fraction), [Closest fraction](https://codegolf.stackexchange.com/questions/26278/closest-fraction), [Approximate floating point number with n-digit precision](https://codegolf.stackexchange.com/questions/143016/approximate-floating-point-number-with-n-digit-precision)) [Answer] # T-SQL, 385 bytes ``` SELECT TOP 1IIF(i>.99,'>',IIF(i<.01,'<',''))+n+' in '+d FROM t,(SELECT ISNULL(PARSENAME(value,2),'1')n,PARSENAME(value,1)d FROM STRING_SPLIT('100,90,80,70,60,50,40,30,20,15,12,10,9,8,7,6,5,2.9,4,2.7,3.10,3,3.8,2.5,3.7,4.9,2,5.9,4.7,3.5,5.8,2.3,7.10,5.7,3.4,7.9,4.5,5.6,6.7,7.8,8.9,9.10,11.12,14.15,19.20,29.30,39.40,49.50,59.60,69.70,79.80,89.90,99.100',','))m ORDER BY ABS(i-ABS(n)/d) ``` Input is via pre-existing table **t** with numeric field **i**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). That input table is joined with an in-memory table parsed from a string via `STRING_SPLIT` (which separates rows) and `PARSENAME` (which separates numerator and denominator via `.`). The table is sorted by distance from the input value **i**, and returns the top row, formatted appropriately. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 84 bytes ``` NθF¹¹«F⊖ι⊞υ⟦⊕κι⟧≔⎇⊖ι∨×χι¹²¦¹⁵ιF²⊞υ⟦∨κ⊖ιι⟧»≔Eυ↔⁻θ∕§ι⁰§ι¹η≔⌕η⌊ηη×<‹θ·⁰¹×>›θ·⁹⁹⪫§υη in ``` [Try it online!](https://tio.run/##XZBRS8MwFIWf119x6dMNxNFOFIoyKIhScbqHvYkPXZvZy9bbLWmGIv72mpSqpXkISe75zjmkqHJdNPmh6zI@2vbZ1lul8SRugl2jAeNYwFcw6893qtCqVtyqEkkIWFtToZXwmvH/YC8k0JvDZ6kx9M64UZpz/TmhJbxo3FCtDMaRI9xDvPDblec93kcuRikO2EuYlBjCvoMhbZUfvTjdGlwRW4Mnh9CZSoVpm3GpPpAkRI4bXWPhl4TKOQ0@98QlVhKcCdW2xup3vtbE7dA8vA0lPCnTp8wjbzMRLJ3gQau89X/qNEky0jw2xH@trLeXEAIxhE7TddH88jrpLs6HHw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a decimal rather than a percentage. Explanation: ``` Nθ ``` Input the fraction. ``` F¹¹« ``` Run from \$ n = 0 \$ to \$ n = 10 \$. ``` F⊖ι⊞υ⟦⊕κι⟧ ``` Generate ratios for \$ \frac 1 n \$ to \$ \frac {n - 1} n \$. ``` ≔⎇⊖ι∨×χι¹²¦¹⁵ι ``` Get the \$ n^{th} \$ element of the list \$ 12, 15, 20 ... 100 \$ into \$ n \$. ``` F²⊞υ⟦∨κ⊖ιι⟧» ``` Generate ratios for \$ \frac {n - 1} n \$ and \$ \frac 1 n \$. ``` ≔Eυ↔⁻θ∕§ι⁰§ι¹η ``` Calculate the decimal values of all the ratios and take the absolute difference with the original input. ``` ≔⌕η⌊ηη ``` Find the index of the least absolute difference. In case of a tie (e.g. \$ \frac 1 2 \$ and \$ \frac 2 4 \$), take the ratio generated first. ``` ×<‹θ·⁰¹ ``` Print a `<` if the input is less than \$ 0.01 \$. ``` ×>›θ·⁹⁹ ``` Print a `>` if the input is greater than \$ 0.99 \$. ``` ⪫§υη in ``` Join the numerator and denominator of the appropriate ratio with `in` and print. [Answer] # JavaScript (ES7), ~~164~~ ~~159~~ 144 bytes Expects an input ratio in \$]0,1[\$. ``` r=>(g=m=>--n+11?g((q=n>1?n*10:n+10-~'13'[n],d=((p=r<.1?1:r>.9?q-1:n<0&&r*q+.5|0)/q-r)**2)>m?m:(o=p+' in '+q,d)):r<.01?'<'+o:r>.99?'>'+o:o)(n=11) ``` [Try it online!](https://tio.run/##ddLbboMgGADg@z0FVxW0Ij/WCEbgQZZdND2lSwuVLrta9urOmmypwO6AfPwneN9@bu87f759lNbtD@NRjV5pfFJXpcvSFgDmhPGgrAZjc2DddMTK7wzq7NW@rfcK45vyPQUDnddUmqGEzvZstfL5UNDmi5FqKD3Jc0701Vw77NStyNDZoqwY1ntCuuk2A5P1WeHmENJk@rF2BFsFQMads3d3OdCLO@EjRow2qELAGCGoqlAPj2DT9iVwQNmzQ/@7JnZtxNoUgwYh5383PLwjKU@VEDCoKcRMBIqHwfhcZ6zqhaqTKRtO2zglj5VYqOahZKBaHgy6SRXW1lTGhW0CJUSQUaQyShYomWxSbpYTg5nxiInlLNqZiQRbNCBmJiMml9OQMv3tJvf86PrPjT8 "JavaScript (Node.js) – Try It Online") ### How? We try all possible ratios \$p/q\$. For each of them, we compute: $$d=(p/q-r)^2$$ We update the best score \$m\$ (the lower, the better) each time \$d\$ is lower than or equal to \$m\$. We go from the highest value of \$q\$ to the lowest one, so that a smaller denominator is preferred in case of a tie. ### Commented ``` r => (g = m => // r = input; g() = recursive function, taking m = best score --n + 11 ? // decrement n; if n is still greater than or equal to -10: g( // do a recursive call to g(): ( q = // compute q = denominator: n > 1 ? // if n is greater than 1: n * 10 // q = n * 10 (20, 30, ..., 100) : // else: n + 10 - ~'13'[n], // q = 12 if n = 0, 15 if n = 1, n + 11 if n < 0 d = (( // compute d = (p / q - r)²: p = // compute p = numerator: r < .1 ? // if r is less than 0.01: 1 // p = 1 : // else: r > .9 ? // if r is greater than 0.90: q - 1 // p = q - 1 : // else: n < 0 && // if n is negative (i.e. q is in [1,10]): r * q + .5 | 0 // p = round(r * q) // otherwise: p = 0 (which will be ignored) ) / q - r // compute p / q - r ) ** 2 // and square the result (cheaper than absolute value) ) > m ? // if d is greater than m: m // leave m unchanged : ( // else: o = p + ' in ' + q, // update the output string o d // and update m to d )) // end of recursive call : // else (all possible ratios have been tried out): r < .01 ? '<' + o : // if r is less than 0.01, prefix with '<' r > .99 ? '>' + o : // if r is greater than 0.99, prefix with '>' o // otherwise, just return o )(n = 11) // initial call to g() with m = n = 11 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~261~~ ~~278~~ ~~261~~ ~~237~~ 177 bytes ``` lambda n:' <>'[(n<.01)-(n>.99)]+'%d in %d'%min([(a,b)for b in[[12,15]+r(10,110,10),r(1,11)][.1<n<.9]for a in r([1,b-1][n>.9],[b,2][n<.1])],key=lambda(a,b):abs(1.*a/b-n)) r=range ``` [Try it online!](https://tio.run/##bdHRboIwFAbge5/iJIuhnZX1FBmtQV@k60WrOMm0GuTGp3eAaNq5C5KWD/7zF87Xdn/y4rZbfd0O9ui2FvwygXKdaOLLlCOdE79OlaJmlky3UHuYbpPpsfZEE8sc3Z0acN1trVEwzM2sIcgZ9henrNt0a2p0imUXp0z/uO1TGqKRuTka3ccbph0T3bpM0VDDfqrr6l5nGLK07kIwfbcfbu4pnTSrxvrv6nZuat/CjvCU85wCvAGU2Kcj55MAuyoDwr@Yh/gZWREZ5gBd/3EjgFR1u68aqC9gN5vq3Fp3qGj4vhLx4MAww9BkQOL5muipiCgbKXtJzEURJoqI5Eh5TyqgQvCQwmFFpsJhi4CkfATKv4GKP0i9VFSL8WQ4mIhMjvWLwWRsYxM5mIpMjQdQ6vXvKnX/yusn3n4B "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 58 bytes ``` ⁵R×⁵;12,15µ’,1,€)Ẏ;⁵Œc¤ð÷/ạ¥ÞḢj“ in ” ”<”>“”>.99$?<.01$?;Ç ``` [Try it online!](https://tio.run/##y0rNyan8//9R49agw9OBpLWhkY6h6aGtjxpm6hjqPGpao/lwV581UOLopORDSw5vOLxd/@GuhYeWHp73cMeirEcNcxQy8xQeNczlAmIbILYDCoEoPUtLFXsbPQNDFXvrw@3///83AIpYAgA "Jelly – Try It Online") -16 bytes thanks to Arnauld (can just prepend the `<` and `>` instead of rewriting the whole phrase) -6 bytes and bug-fixes thanks to Jonathan Allan [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~224~~ ~~198~~ 197 bytes ``` import StdEnv,Data.List,Text t=toReal $p=if(p<1.0)"<"if(p>99.0)">"""+snd(minimum[(abs(p-t n*1E2/t d),n<+" in "<+d)\\i<-[10,12,15:[20,30..100]],(n,d)<-[(1,i),(i-1,i):diag2[1..10][1..10]]|gcd n d<2]) ``` [Try it online!](https://tio.run/##ZZJNb5wwEIbP5VeMnBxM1lBsgsARu6fkUCmRqqY3loODvStLYNDirVKpv72Ur2VZ9eTx83rembFdlEqYrqrluVRQCW06XTX1ycK7lS/mF3kWVvivurXkp/q0jt3a@ocSpXPfbPUBNyn1AxelaIh3nA@bHUJo0xqJK210da4yLD5a3HgWzAN9YV8tSJeYdINAG0DpRrr7vU69jAaEMkKjp4wFJAx8nwZBnhNsiHR7GVOiXYK1N6xPUosjy@hwKJ@X/M@xkGBApix3u3crTta5A6ta28IWMhz4EYEMpXSo23uj3CXOF9wPMOD/aLTQ@ALjFaQRIjCHbNa5z1ZWF6fQpwtNZsjmo2z0v8JwgOFNfsT8eMlnV5gMMBogv7THplGitWkc@nwxfZxhkkzpyTqdBxPkN@X54zzUiNmCk6mreMTJCo/VkhHzBfOpM85vb7nn493s1kLev9rhbAqra9M/3L2zBWEkZLp9U9WHOgFe1EadCmWsOCoX1GejCqsk7PeArwJZBBdSb/oOefe3OJTi2Hbet9fu@bcRlS6mzfdS2EN9qv4B "Clean – Try It Online") Explained: ``` t = toReal // give `toReal` a shorter name $ p = if(p < 1.0) // if the percentage is less than 1% "<" // prepend "<" if(p > 99.0) // if the percentage is > 99% ">" // prepend ">" "" // otherwise prepend nothing + snd ( // to the second element of minimum [ // the smallest item in a list composed of ( // pairs of abs ( // the absolute value of p - // the difference between the percentage t n*1E2 / t d // and the ratio ) , // associated with n <+ " in " <+ d // the string representation of the ratio ) // in the form of a tuple \\ i <- [10, 12, 15: [20, 30..100]] // for every special denominator `i` , (n, d) <- [(1, i), (i - 1, i): diag2 [1..10] [1..10]] // for every ratio `n` : `d` | gcd n d < 2 // where `n` / `d` cannot be further simplified ] ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~53~~ 52 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _.01,.99Ṡµ<0ịØ<ḣE⁵Ż×⁵+12,5Ṡ,’Ɗż€$Ẏ;⁵Œc¤÷/ạ¥Þ³Ḣj“ in ``` A full program which prints the result. **[Try it online!](https://tio.run/##AWkAlv9qZWxsef//Xy4wMSwuOTnhuaDCtTww4buLw5g84bijReKBtcW7w5figbUrMTIsNeG5oCzigJnGisW84oKsJOG6jjvigbXFkmPCpMO3L@G6ocKlw57Cs@G4omrigJwgaW4g////MC4wMDE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##Jcu7CsIwFAbgV@ngIpaapJb0YFefQsRBHCzi7lZFEBQcXFS84HUQxE206pRQ3yN5kZg003fO@f8Tt7vdvlJND2HXAxDpnj0iJD5TvozE61STg0f24QtNCRM30Lkrk9Vvkn3l8FYQ71nVNOYtdubPsngf2IXv2F28jrFMNk6n58hkq1jKriId8bEuP/VQFOlax0rVkYdQ4DoajCx2oxYgBuxjA7EbAd8QEGoJDZTk79QHQxjmR0CWSv4HIbXkFQBkwY0/ "Jelly – Try It Online") Note that the test-suite is altered to make the code a monadic link by: 1. using the register keep a track of the current "program input", with `³` to `®`; and 2. closing the list of characters code for " in ", with `“ in` to `“ in ”` ### How? Starts with code that forces any necessary printing of the `<` or `>` sign and then code which constructs all the numerator-denominator pairs (with some redundant not simplified form versions, all after their simplified form) and prints the minimally different division-evaluated entry using a stable sort joined with `in` . ``` _.01,.99Ṡµ<0ịØ<ḣE⁵Ż×⁵+12,5Ṡ,’Ɗż€$Ẏ;⁵Œc¤÷/ạ¥Þ³Ḣj“ in - Main Link: number in [0,1], n .01,.99 - literal pair = [0.01, 0.99] _ - subtract -> [n - 0.01, n - 0.99] Ṡ - sign (vectorises) (-1 if <0; 1 if >0; else 0) µ - start a new monadic link - call that X <0 - less than zero? (vectorises) Ø< - literal list of characters = "<>" ị - index into (vectorises) ("<<" if n < 0.01; ">>" if n >= 0.99; else "><") E - all (of X) equal? (1 if ((n < 0.01) OR (n > 0.99)) else 0 ḣ - head to index ("<" if n < 0.01; ">" if n > 0.99; else "") - (the following nilad forces a print of that) ⁵ - literal 10 Ż - zero-range -> [0,1,2,3,4,5,6,7,8,9,10] ×⁵ - multiply by 10 -> [0,10,20,30,40,50,60,70,80,90,100] 12,5 - literal pair = [12,5] + - add -> [12,15,20,30,40,50,60,70,80,90,100] $ - last two links as a monad Ɗ - last three links as a monad Ṡ - sign -> [1,1,1,1,1,1,1,1,1,1,1] ’ - decrement -> [11,14,19,29,39,49,59,69,79,89,99] , - pair -> [[1,1,1,1,1,1,1,1,1,1,1],[11,14,19,29,39,49,59,69,79,89,99]] ż€ - zip with for €ach -> [[[1,12],[1,15],[1,20],[1,30],[1,40],[1,50],[1,60],[1,70],[1,80],[1,90],[1,100]],[[11,12],[14,15],[19,20],[29,30],[39,40],[49,50],[59,60],[69,70],[79,80],[89,90],[99,100]]] Ẏ - tighten -> [[1,12],[1,15],[1,20],[1,30],[1,40],[1,50],[1,60],[1,70],[1,80],[1,90],[1,100],[11,12],[14,15],[19,20],[29,30],[39,40],[49,50],[59,60],[69,70],[79,80],[89,90],[99,100]] ¤ - nilad followed by link(s) as a nilad: ⁵ - literal 10 Œc - unordered pairs -> [[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[2,10],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[3,10],[4,5],[4,6],[4,7],[4,8],[4,9],[4,10],[5,6],[5,7],[5,8],[5,9],[5,10],[6,7],[6,8],[6,9],[6,10],[7,8],[7,9],[7,10],[8,9],[8,10],[9,10]] ; - concatenate -> [[1,12],[1,15],[1,20],[1,30],[1,40],[1,50],[1,60],[1,70],[1,80],[1,90],[1,100],[11,12],[14,15],[19,20],[29,30],[39,40],[49,50],[59,60],[69,70],[79,80],[89,90],[99,100],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[2,10],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[3,10],[4,5],[4,6],[4,7],[4,8],[4,9],[4,10],[5,6],[5,7],[5,8],[5,9],[5,10],[6,7],[6,8],[6,9],[6,10],[7,8],[7,9],[7,10],[8,9],[8,10],[9,10]] Þ - sort by: ¥ - last two links as a dyad: - ...(with right argument of ³ - the program input, n) / - reduce by: ÷ - division ạ - absolute difference Ḣ - head “ in - literal list of characters " in " ; - concatenate - implicit print ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 118 bytes ``` {'<'x(.01>$_)~'>'x($_>.99)~(|(1..9 X ^11),|map({|(1,$_-1 X$_)},12,15,|(^11 X*10))).min({abs $_-[/] @^a}).join(' in ')} ``` [Try it online!](https://tio.run/##FY7RaoNAEEV/5T5Id6dsJjtrjQ6k0s8QSiMGKqTUJCQvDWp@3Y4Pc5h7OTBz/b797pbhgZce78vo9u7Pc5Q6a@npagtZW7MqPf3khVnR4CBCYRq6qx@tC1m7ETTmz0FSkCJM3gw0rxKJiIfT2Y/d8Q7zPrdf@Dh0M/HPxWqH0xmO5uXePdDbpa3ESOgvN@wjFxCONgVKG@UEyVmQ1s2Qo0hcrqhQJjPL3L6rKosaV7yZp5UpBoWqKQapl38 "Perl 6 – Try It Online") ]
[Question] [ ### Background Based on a game my four-year-old got from his rabbi. The "goal" is to "find" the letters in a given order, e.g. `aecdb`. You are given a stack of letter cards, e.g. `daceb`. You can only search through the stack in the order given, albeit cyclically. When you meet a letter you need, you take that out of the stack. ### Objective Given an order and a stack (duplicate-free permutations of each other), find the sequence of top stack letters (it is all printable ASCII) you see while playing the game. ### Step-by-step example We need to find the order `aecdb`, given the stack `daceb`: Top of stack `d`: Not what we are looking for (`a`), so we add it to the sequence:`d` and rotate to get the stack:`acebd`. Top of stack `a`: Yes! so we add it to the sequence:`da` and remove it from the stack:`cebd`. Top of stack `c`: Not what we are looking for (`e`), so we add it to the sequence:`dac` and rotate to get the stack:`ebdc`. Top of stack `e`: Yes! so we add it to the sequence:`dace` and remove it from the stack:`bdc`. Top of stack `b`: Not what we are looking for (`c`), so we add it to the sequence:`daceb` and rotate to get the stack:`dcb`. Top of stack `d`: Not what we are looking for (`c`), so we add it to the sequence:`dacebd` and rotate to get the stack:`cbd`. Top of stack `c`: Yes! so we add it to the sequence:`dacebdc` and remove it from the stack:`bd`. Top of stack `b`: Not what we are looking for (`d`), so we add it to the sequence:`dacebdcb` and rotate to get the stack:`db`. Top of stack `d`: Yes! so we add it to the sequence:`dacebdcbd` and remove it from the stack:`b`. Top of stack `b`: Yes! so we add it to the sequence:`dacebdcbdb` and remove it from the stack:. And we are done. The result is `dacebdcbdb`. ### Reference implementation ``` def letters(target, stack): string = '' while stack: string += stack[0] if stack[0] == target[0]: stack.pop(0) target = target[1:] else: stack.append(stack.pop(0)) return string print letters('aecdb', list('daceb')) ``` [Try it online!](https://tio.run/##bY/BCsMgDIbvfYrcVFZGt2PBJxk72Jq2MrGiKWNP72QO28G8SPy/fCb@RcvqrilpnMAiEYbISYUZqYVIanyIvoF8IgXjZpDA2Kd@LsZiIQpwgE6yBLfuXiMz1TeQEsoXudibiyAjZ7963omfoPBQGy/9rkYb8Z9GeY9O86OzSAPSFtx32qbx@aK6PFM46oG1YE0kzrQacWBCpPQG "Python 2 – Try It Online") ### Test cases `try`, `yrt` → `yrtyry` `1234`, `4321` → `4321432434` `ABCDEFGHIJKLMNOPQRSTUVWXYZ`, `RUAHYKCLQZXEMPBWGDIOTVJNSF` → `RUAHYKCLQZXEMPBWGDIOTVJNSFRUHYKCLQZXEMPWGDIOTVJNSFRUHYKLQZXEMPWGIOTVJNSFRUHYKLQZXMPWGIOTVJNSRUHYKLQZXMPWIOTVJNSRUYKLQZXMPWOTVNSRUYQZXPWOTVSRUYQZXPWTVSRUYQZXWTVSRUYZXWTVSUYZXWTVUYZXWVYZXWYZXYZ` `?`, `?` → `?` `a`, `a` → `a a` `abcd`, `abcd` → `abcd` [Answer] Three fairly different methods are giving equal byte counts. # [Python 2](https://docs.python.org/2/), 59 bytes ``` s,t=input() for c in s*99: if c in t:print c;t=t.lstrip(c) ``` [Try it online!](https://tio.run/##Jcc5DoMwEADAnle4M0QoRTqIKLjv@6a1hLJSZCx7U@T1TpHpRnzxdfGH1spGD7j4oGkZ5yUJI8CJujmOaxA4/0VXSOBI2BM9vL8VShAms7Smw@xnexlW/bHFdResaZS301I0Y0Jt6gdhFCdplhdlVTdt1w/jNC/rth/0Bw "Python 2 – Try It Online") Prints each character in its own line. --- # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda s,t:[c==t[0]and t.pop(0)or c for c in s*99if c in t] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYp8QqOtnWtiTaIDYxL0WhRK8gv0DDQDO/SCFZIQ1MZuYpFGtZWmamQdglsf@LbXMyi0s01INCHT0ivZ19AqMiXH0DnMLdXTz9Q8K8/ILd1DW5SqCKHJ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqOAigqKMvNKFNI0gM7Q/A8A "Python 2 – Try It Online") Takes lists as input, and outputs a list. --- # [Python 3](https://docs.python.org/3/), 59 bytes ``` def f(s,t): for c in t:p,q=s.split(c);s=q+p;print(end=p+c) ``` [Try it online!](https://tio.run/##Jc25DoMgAADQ3a9gA6Pp0k3D4H3ft6tKStIgCku/njbpB7w8/pGvkz2V2g8CCBKm1C0NkPMGG6AMSIubFxYPwd9Uok23Bb4MbvObMokOtmNubLr6KQzbwYmXzMubdQ6K2p0iP6n6MS27EJrQcT0/CKM4SbO8KKu6abt@GKd5WaH2X9UX "Python 3 – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes ``` ∊⊢,⊢∘⊂~¨(,\⊣⊂⍨1,2>/⍋) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEcdXY@6FukA8aOOGY@6muoOrdDQiXnUtRjIftS7wlDHyE7/UW@35v//GuolRZXqaeqVRSXqmo86F4IYlUARLg11QyNjE6CMibGRIUQKxAJiE6AwUNrRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyCqgpKNTRI9Lb2ScwKsLVN8Ap3N3F0z8kzMsv2A1iFG75oFAkCXRxuDCGKJIgshhcCC4CFADzgTwwB86GM6EsCANKg6kwEAHEQB9yaaQBw1FH3R7sHRANDBGFRKDPExUgPkwE8oBiiUnJKSBREAURB7EA "APL (Dyalog Classic) – Try It Online") This is a train equivalent to `{∊⍵,(⊂⍵)~¨(,\⍺⊂⍨1,2>/⍺⍋⍵)}` `⍋` gives the permutation of right argument `⍵` in left argument `⍺` `1,2>/` compare consecutive pairs with `>` and prepend a 1 `⍺⊂⍨` use the above boolean mask to split `⍺` into groups; 1s in the mask mark the start of a new group `,\` cumulative concatenations of the groups `(⊂⍵)~¨` complement of each with respect to `⍵` `⍵,` prepend `⍵` `∊` flatten as a single string [Answer] ## Batch, 155 bytes ``` @set/pt= @set/ps= @set r= :l @set c=%s:~,1% @set r=%r%%c% @if %c%==%t:~,1% set t=%t:~1%&set c= @set s=%s:~1%%c% @if not "%t%"=="" goto l @echo %r% ``` Takes the target and stack as inputs on STDIN. [Answer] # JavaScript (ES6), 54 bytes Takes the target as a string and the stack as an array of characters. Returns a string. ``` f=(t,[c,...s])=>t&&c+f(t.slice(c==t[0]||!s.push(c)),s) ``` ### Test cases ``` f=(t,[c,...s])=>t&&c+f(t.slice(c==t[0]||!s.push(c)),s) console.log(f('try',[...'yrt'])) console.log(f('1234',[...'4321'])) console.log(f('aecdb',[...'daceb'])) console.log(f('ABCDEFGHIJKLMNOPQRSTUVWXYZ',[...'RUAHYKCLQZXEMPBWGDIOTVJNSF'])) console.log(f('?',[...'?'])) console.log(f(' a',[...'a '])) console.log(f('abcd',[...'abcd'])) ``` ### How? At each iteration, we extract the character `c` on the top of the stack and append it to the final result. We then perform a recursive call whose parameters depend on the result of `c == t[0]`, where `t[0]` is the next expected character. If `c` matches `t[0]`: * we remove `c` from the target string by passing `t.slice(1)` * we remove `c` from the stack by passing `s` unchanged If `c` doesn't match `t[0]`: * we let the target string unchanged by passing `t.slice(0)` * we push `c` back at the end of the stack [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes ``` f=lambda o,s,S='':s and f(o[s[0]==o[0]:],s[1:]+s[:s[0]!=o[0]],S+s[0])or S ``` [Try it online!](https://tio.run/##HYu7CsIwAAB/JU6xNIM6BjL0/X6m75ChUoqCNqVx8etj63JwB7d@Pw@x3JSayWt836cRCCQRJRBiCcZlAvNZMMkunBCxE3Mk2RVzXTJ81NO/ckT1wzSxAarW7bl89g8apmU7rucHYRQnaZYXJa3qpu36ASJY1obfR1ZcDJ2T5Gbr2UFWNWFKXaipHw "Python 2 – Try It Online") I suspect this is very highly golfable. [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` f=lambda o,s:o and s[0]+f(o[s[0]==o[0]:],s[1:]+s[0]*(s[0]!=o[0])) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIV@n2CpfITEvRaE42iBWO00jPxrEsLXNB5JWsTrF0YZWsdogIS0NEKkIltDU/F9QlJlXopCmoe7o5Ozi6ubu4enl7ePr5x8QGBQcEhoWHhEZpa6jHhTq6BHp7ewTGBXh6hvgFO7u4ukfEublF@ymrvkfAA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 46 bytes ``` q@(a:b)#(c:d)|a==c=a:b#d|e<-d++[c]=c:q#e a#_=a ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v9BBI9EqSVNZI9kqRbMm0dY22RbIV06pSbXRTdHWjk6OtU22KlRO5UpUjrdN/J@bmJmnYKtQUFoSXFLkk6egoqBUUlSppKxUWVSi9B8A "Haskell – Try It Online") Fairly simple. Left argument is the "goal" and the right is the stack. If the head of the goal matches the top of the stack we prepend it, and recur with the rest of the goal and the stack (without re-adding the item on top). Otherwise we prepend the top item and recur with the same goal, reading the top item to the end of the stack. When the goal is empty the pattern matching chooses the second line and the empty list is returned. EDIT: -3 bytes thanks to @GolfWolf and @Laikoni! [Answer] # [Clean](https://clean.cs.ru.nl), 85 bytes ``` import StdEnv g l[u:v][a:b]|a==u=g[a:l]v b=g[a:l][u:v](b++[a]) g l[]_=reverse l f=g[] ``` [Try it online!](https://tio.run/##Lcy9CsMgEAfwPU9xW1pCXyDg1g6FbhnlCKeeIqgpMREKffZaG7r94P@hA1OqcTF7YIjkU/XxuawbTJu5pdI5CHIfC0oaFb5JiF245oAF1F9HflLDIAnPxwBnsXLhNTOEzrYa1mmjdirAguyJtVE9NhnS/FP9aBvI5Xq5P@r1lSh6nb8 "Clean – Try It Online") Defines the partial function `f` taking `[Char]` and `[Char]`, where the first argument is the target and the second is the stack. [Answer] # Java 8, 88 bytes ``` a->b->{for(int c:a)for(char t=0;c!=t;System.out.print(t)){t=b.poll();if(c!=t)b.add(t);}} ``` Inputs as `char[]` and `java.util.LinkedList<Character>` (`java.util.Queue` implementation) **Explanation:** [Try it online.](https://tio.run/##rc9NT8JAEAbgO79i5bSbyEbEk4UaRBEU/MJPCIfpdquLZdtsp5qm4bfj1hCNyq1N9jDJzM487wLeoRHFUi/8t7UIIUnIGJTOa4QkCKgEWdgJnqIKeZBqgSrSvL8p2uIVzGy@u22mF@kkXUrT/umNlH6T/kgl2O7ZjyBQGtd1SUA6ZA0N12u4eRAZqjQScQisqIsLBDt7jtjpoDPJEpRLHqXIY2PHKDKWY8fjcRSGlDkqoMUc8zj4vm06q9XasVHsi1MvtGk2od4j5ZOlDUonaBe9zObAisyEBBziOMxoHaTwvTrHqLB2jYGMMsZBCBkj1fKDbAtGWZ5/s8Vh3Qch/y0pbKKwMefr5N9UoaabzjcGTVaWkhmsANLcbx2UlRy09psVULrHvZPT/tlgeH4xGl9eXd/cTu7uHx6fnqdlgbf33cHzRW90M306HV8fP56dDK/uHs4vJ/0K2EdldUcVIAiUVQCpgAGe8EtDtuz4TVnVVutP) ``` a->b->{ // Method with two parameters and no return-type for(int c:a) // Loop over the characters of the char-array for(char t=0;c!=t; // Inner loop until we've found the character in the queue System.out.print(t)){ // After every iteration: print the char `t` t=b.poll(); // Remove the top of the queue, and save it in `t` if(c!=t) // If this is not the character we're looking for: b.add(t);}} // Add it at the end of the queue again ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~38~~ 32 bytes Edit: Teal pelican has a much better `><>` approach [here](https://codegolf.stackexchange.com/a/153370/76162) that swaps the input methods ``` 0[i:0(1$. \~~l]1+{$[& /?=&:&:o:{ ``` [Try it online!](https://tio.run/##S8sszvj/3yA608pAw1BFjyumri4n1lC7WiVajUvf3lbNSs0q36r6/38TYyPD/7rFhkbGJgA "><> – Try It Online") Takes the order of the letters through the `-s` flag, and the stack through input. ### How It Works: ``` 0[.... Creates a new empty stack ...... This puts the order of the letters safely away ...... ..i:0(1$. Takes input until EOF (-1). This means input is in reverse ..~... And then teleports to the ~ on this line ...... ...... Gets the first character from the beginning of the order \.~l]1+{$[& And stores it in the register before going to the next line /..... ...... Output the bottom of the stack ...... Checks if the bottom of the stack is equal to the current character /?=&:&:o:{ If so, go to the second line, else cycle the stack and repeat 0..... Pop the extra 0 we collected \~~l]1+{$[& Pop the value that was equal and get the next character from the order /..... And go down to the last line. This will end with an error (which could be avoid with a mere 4 extra bytes ``` [Answer] # [Perl 5](https://www.perl.org/), 42 + 2 (`-pl`) = 44bytes ``` for$i(<>=~/./g){/$i/;$\.=$`.$i;$_=$'.$`}}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8PGzrZOX08/XbNaXyVT31olRs9WJUFPJdNaJd5WRV1PJaG2tvr//5TE5NQkrsTU5JSkf/kFJZn5ecX/dX1N9QwMDf7rFuQAAA "Perl 5 – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~21~~ 16 bytes ``` i$\~~ =?\$:{::o@ ``` [Try it online!](https://tio.run/##S8sszvj/P1Mlpq6Oy9Y@RsWq2soq3@H/f0MjY5P/usUmxkaGAA "><> – Try It Online") Flow changed to utilize the empty spaces and remove extra code rerouting. (-5 bytes) - Thanks to @JoKing # [><>](https://esolangs.org/wiki/Fish), 21 bytes ``` i:{:@=?v:o$! o~i00. > ``` [Try it online!](https://tio.run/##S8sszvj/P9Oq2srB1r7MKl9FkSu/LtPAQE/B7v9/QyNjk/@6xSbGRoYA "><> – Try It Online") The other ><> answer can be found [here.](https://codegolf.stackexchange.com/a/153328/620091) ### Explanation The stack starts with an initial set of characters using the -s flag. Input is the user given character order. This explanation will follow the flow of the code. ``` i$\ : Take input, swap the top 2 stack items then move to line 2; [1,2,3] -> [1,2,4,3] \$: : Swap the top 2 stack items then duplicate the top item; [1,2,4,3] -> [1,2,3,4,4] {::o : Move the stack items 1 left then duplicate the stack top twice and print one; [1,2,3,4,4] -> [2,3,4,4,1,1] =?\ @ : Swap the top three stack items left 1 then do an equal comparison, if equality move to line 1 else continue; [2,3,4,4,1,1] -> [2,3,4,1,1,4] -> [2,3,4,1] \~~ : Remove the top 2 stack items; [2,3,4,1] -> [2,3] ``` [Answer] # Perl, 62 bytes ``` sub{$_=$_[1];for$x(@{$_[0]}){/\Q$x\E/;$z.="$`$&";$_="$'$`"}$z} ``` Takes its first argument, the order, as a list of characters and its second, the stack, as a string. Ungolfed: ``` sub { $_ = $_[1]; for $x (@{$_[0]}) { /\Q$_\E/; $z.="$`$&"; $_ = "$'$`" } $z } ``` You ever wonder what all those obscure regex variables were for? Clearly, they were designed for this exact challenge. We match on the current character `$x` (which unfortunately has to be escaped in case it's a regex special character). This conveniently splits the string into "before the match" `$``, "the match" `$&`, and "after the match" `$'`. In the cyclic search, we clearly saw every character before the match and put them back into the stack. We also saw the current character but didn't put it back. So we append "before the match" to the "seen" list `$z` and construct the stack out of "after the match" followed by "before the match". [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 98 bytes ``` S =INPUT L =INPUT R S LEN(1) . X REM . S :F(END) OUTPUT =X L POS(0) X = :S(R) S =S X :(R) END ``` [Try it online!](https://tio.run/##NUy9CoAgEJ7Pp7hRl0hzEtwyCEzDK3Bujhp6f@wamr7/77nu4z5ta0Do57Tum4D4s8JmDElqhR1WLGFhJHCTDGlUAvK@cQ19/TZrJtkrrnlwJAvH/EhYwX2CB63ZwWihzWBf "SNOBOL4 (CSNOBOL4) – Try It Online") Prints each letter on a newline. Use [this version](https://tio.run/##NYw9C4AgEIbn81fcqEtkOQluGQTlhVfg3Bw19P@xa2h6vx7e57qP@3S1AmOY0rpvCubfZSnnmLQ12GDBHBdRBj9qMgoIA2H58JVYt0aIAJ51lk3OGAv4LxDQvsmd4CqmoVbXd1bZrncv "SNOBOL4 (CSNOBOL4) – Try It Online") to get everything to print on the same line. Takes input as stack, then target, separated by a newline. ``` S =INPUT ;*read stack L =INPUT ;*read letters R S LEN(1) . X REM . S :F(END) ;*set X to the first letter of S and S to the remainder. If S is empty, goto END. OUTPUT =X ;*output X L POS(0) X = :S(R) ;*if the first character of L matches X, remove it and goto R S =S X :(R) ;*else put X at the end of S and goto R END ``` [Answer] # Perl, 44 bytes Includes `+4` for `-lF` Give input as on STDIN as target then stack (this is the reverse order from the examples): ``` (echo daceb; echo aecdb) | perl -lF -E '$a=<>;say,$a=~s/^\Q$_//||push@F,$_ for@F' ``` If you don't mind a trailing newline this `40` works: ``` (echo daceb; echo aecdb) | perl -plE '$_=<>=~s%.%s/(.*)\Q$&//s;$_.=$1;$&%reg' ``` ]
[Question] [ The Pi function is an extension of the factorial over the reals (or even complex numbers). For integers *n*, *Π(n) = n!*, but to get a definition over the reals we define it using an integral: [![Pi(z) = integral t from 0 to infinity e^-t t^z dt](https://i.stack.imgur.com/KxqhA.png)](https://i.stack.imgur.com/KxqhA.png) In this challenge we will invert the *Π* function. Given a real number *z ≥ 1*, find positive *x* such that *Π(x) = z*. Your answer must be accurate for at least 5 decimal digits. --- Examples: ``` 120 -> 5.0000 10 -> 3.39008 3.14 -> 2.44815 2017 -> 6.53847 1.5 -> 1.66277 ``` [Answer] # Mathematica, ~~17~~ ~~15~~ 27 bytes ``` FindInstance[#==x!&&x>0,x]& ``` Output looks like `{{x -> n}}`, where `n` is the solution, which may not be allowed. [Answer] # Pyth, 4 bytes ``` .I.! ``` A program that takes input of a number and prints the result. [Test suite](http://pyth.herokuapp.com/?code=.I.%21&test_suite=1&test_suite_input=120%0A10%0A3.14%0A2017%0A1.5&debug=0) **How it works** ``` .I.! Program. Input: Q .I.!GQ Implicit variable fill .I Find x such that: .!G gamma(x+1) Q == Q Implicitly print ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` 1`1e-5+tQYgG< ``` This uses linear seach in steps of `1e-5` starting at `1`. So it is terribly slow, and times out in the online compiler. To test it, the following link replaces the `1e-5` accuracy requirement by `1e-2`. [Try it online!](https://tio.run/nexus/matl#@2@YYJiqa6RdEhiZ7m7z/7@xnqEJAA) ### Explanation ``` 1 % Push 1 (initial value) ` % Do...while 1e-5 % Push 1e-5 + % Add t % Duplicate QYg % Pi function (increase by 1, apply gamma function) G< % Is it less than the input? If so: next iteration % End (implicit) % Display (implicit) ``` [Answer] # [GeoGebra](https://www.geogebra.org/), 25 bytes ``` NSolve[Gamma(x+1)=A1,x=1] ``` Entered in the CAS input, and expects input of a number in spreadsheet cell `A1`. Returns a one-element array of the form `{x = <result>}`. Here is a gif of the execution: [![Execution of progrma](https://i.stack.imgur.com/5mRxl.gif)](https://i.stack.imgur.com/5mRxl.gif) **How it works** `N`umerically`Solve` the following equation: `Gamma(x+1)=A1`, with starting value `x=1`. [Answer] # MATLAB, 59 bytes ``` @(x)fminsearch(@(t)(gamma(t+1)-x)^2,1,optimset('TolF',eps)) ``` This is an anonymous function that finds the minimizer of the squared difference betweeen the Pi function and its input, starting at `1`, with very small tolerance (given by `eps`) to achieve the desired precision. Test cases (run on Matlab R2015b): ``` >> @(x)fminsearch(@(t)(gamma(t+1)-x)^2,1,optimset('TolF',eps)) ans = @(x)fminsearch(@(t)(gamma(t+1)-x)^2,1,optimset('TolF',eps)) >> f = ans; format long; f(120), f(10), f(3.14), f(2017) ans = 5.000000000000008 ans = 3.390077650547032 ans = 2.448151165246967 ans = 6.538472664321318 ``` You could [try it online](https://tio.run/nexus/octave#JcdBCoMwEEDRq2TnDI3FSYUupODKE3QtDCWxgpOImYW3j7Wu3v@lhx2DzDF73j5f6EERJhZh0BthvePoLNm06izZK1TvtAyV9WtGLMG8DMfcmZA2YTVLitNvgFyD9vTicaf2H66hJ5YD "Octave – TIO Nexus") in Octave, but unfortunately some of the results lack the required precision. [Answer] # J, ~~86~~ 33 bytes ``` ((]-(-~^.@!)%[:^.@!D.1])^:_>:)@^. ``` Uses Newton's method with log Pi to avoid overflow. This is the previous version that computes log Gamma using Stirling's approximation. The step size (1e3) and number of terms in log Gamma (3) can be increased for possibly higher accuracy at the cost of performance. ``` 3 :'(-(k-~g)%%&1e3(g=:((%~12 _360 1260 p.&:%*:)+-+^~-&^.%:@%&2p1)@>:)D:1])^:_>:k=:^.y' ``` Another version that computes the coefficient terms on the fly ``` 3 :'(-((-^.y)+g)%%&1e3(g=:((%~(((%1-^@-)t:%]*<:)+:>:i.3)p.%@*:)+(*^.)-]+-:@^.@%&2p1)@>:)D:1])^:_>:^.y' ``` [Try it online!](https://tio.run/nexus/j#@5@mYGuloKERq6uhWxen56CoqRptBaJd9AxjNeOs4u2sNB3i9Li4UpMz8hU0dPTSlAw0FQyNDBQMDRSM9QxNFIwMDM0VDPVMFQz//wcA) and to see the terms [converge](https://tio.run/nexus/j#@5@mYGuloKERq6uhWxen56CoqRptBaJd9AxjNeOsEq3srDQd4vS4uFKTM/IV0hQM9Uz//wcA). ## Explanation ``` ((]-(-~^.@!)%[:^.@!D.1])^:_>:)@^. Input: float y ( )@^. Operate on log(y) >: Increment, the initial guess is log(y)+1 ( )^:_ Repeat until convergence starting with x = log(y)+1 ] Get x ^.@! The log Pi verb [: D.1 Approximate its first derivative at x ^.@! Apply log Pi to x -~ Subtract log(y) from it % Divide it by the derivative ]- Subtract it from x and use as next value of x ``` [Answer] # Mathematica, 21 bytes ``` FindRoot[#-x!,{x,1}]& ``` `FindRoot` applies Newton's method internally when there is an initial value. The two methods below apply Newton's method directly. ### Alternative using FixedPoint 45 bytes ``` FixedPoint[#-(#!-y)/Gamma'[#+1]&,Log[y=#]+1]& ``` A more precise implementation of Newton's method for solving this since Mathematica can compute the derivative directly instead of approximating it. Using rules to replace repeatedly would be shorter, but there is a limit (65536) to how many iterations it can perform that might be hit whereas `FixedPoint` does not have a limit. ### Alternative using rules, 38 bytes ``` Log[y=#]+1//.x_->x-(x!-y)/Gamma'[x+1]& ``` ![Image](https://i.stack.imgur.com/2zhA3.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` Ḋ!Æl_® ȷİ‘×;µ!ÆlI÷I÷@Ç_@ḊḢ Æl©‘ÇÐĿ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR5fi4bac@EPruE5sP7LhUcOMw9OtD20FiXke3g5EDofb4x2Aqh7uWMQFFDy0EqSk/fAEn/9H9xxuf9S0xv3/f0MjAx0FQyA21jM00VEwMjA0B/L1TIEEAA) or [View the intermediate values as they converge](https://tio.run/nexus/jelly#@/9wR5fi4bac@EPruE5sP7LhUcOMw9OtD20FiXke3g5EDofb4x2Aqh7uWMQFFDy0EqSk/fCEI/v///9vqGcKAA). An implementation of J's combination of Newton's method and derivative approximation (secant method) to compute the inverse of *Π*(*n*). It solves for the inverse of log(*Π*(*n*)) instead in order to avoid overflow. It starts with an initial guess *x*0 = *y*+1 where *y* = log(*Π*(*n*)). Then it iterates until convergence using *x**n*+1 = *x**n* - (log(*Π*(*x**n*)) - *y*) / (log((*Π*(1.001 \* *x**n*)) - log(*Π*(*x**n*))) / (0.001 \* *x**n*)). [Answer] ## PARI/GP, 30 bytes ``` x->solve(t=1,x+1,gamma(t+1)-x) ``` Finds solution between `1` and`x+1`. Unfortunately, `x` is not big enough as upper bound for input like `1.5`. [Answer] ## Mathematica, 26 Bytes Yet another Mathematica solution! Equation solving can always be turned into a minimization problem. ``` NArgMin[{(#-x!)^2,x>0},x]& ``` Finds the argument that minimizes the difference between the left and right sides of the equation. Using NArgMin rather than NMinimize forces the output to just be the desired result rather than the usual verbose rule-based output (and it saves a byte!) [Answer] # C with libm, 111 **Update** - fixed for input 1.5. ``` f(double *z){double u=2**z,l=0,g=u,p=0;for(;log(fabs(g-p))>-14;)p=g,g=(u+l)/2,u=tgamma(g+1)>*z?g:(l=g,u);*z=g;} ``` `gamma(x+1)` is a monotonically increasing function over the range in question, shis is just a binary search until the difference between successive values is small. The starting lower bound is `0` and the starting upper bound is `2*x`. Input and output is via a pointer to a double passed to the function. I'm pretty sure this can be golfed deeper - in particular I don't think I need 4 local doubles, but so far I'm not seeing an easy way to reduce this. [Try it online](https://tio.run/nexus/bash#XU9hb4IwEP3Or7hscbZQEZjLktWyH@L8UGtbmgAlQDeD4be76lS2XdLL3bt3716lKCzMH00tSreXsO76vbFxkQcTVPG@8MhJob11u1JCOODjtXQsC8OBlCwhmjnSsIQq2yJaWo0U33VILxqM80W6orhh2pOQi0q8zIhjveZVxZGOUpyHw7t@Q6VnOEzDgWk6nkzdQ8VNDehc8VYLAsLWXQ@i4C2EoYc@MRwD8HH108uuF7yT3WYLDI6QEkizxCf/nuN0RSBL0lffxy8w0svmWdzQ3yIHGlxa/xN/2@skFAysAXVmkFah@xEMS/iPbZItxp4fRTdr5zh4lYlitvQ@UejpgKe2ab0fhR4UminMZuqjfiB/Ngnc6OMlt7J3be0tBmMwhxx43X3JNhaBFgIWZQULe8WmUbz8KU/f) - Builds (linking with libm) and runs in a bash script. Mildly ungolfed: ``` f(double *z){ double u=2**z,l=0,g=u,p=0; for(;log(fabs(g-p))>-14;){ p=g; g=(u+l)/2; u=tgamma(g+1)>*z?g:(l=g,u);*z=g; } } ``` ]
[Question] [ ## Introduction Consider a sequence of integers \$f\$ defined as follows: 1. \$f(2) = 2\$ 2. If \$n\$ is an odd prime, then \$f(n) = \frac{f(n-1) + f(n+1)}2\$ 3. If \$n = p\cdot q\$ is composite, then \$f(n) = f(p)\cdot f(q)\$ It's not very hard to see that \$f(n) = n\$ for every \$n \ge 2\$, and thus computing \$f\$ wouldn't be a very interesting challenge. Let's make a twist to the definition: halve the first case and double the second case. We get a new sequence \$g\$ defined as follows: 1. \$g(2) = 1\$ 2. If \$n\$ is an odd prime, then \$g(n) = g(n-1) + g(n+1)\$ 3. If \$n = p\cdot q\$ is composite, then \$g(n) = g(p)\cdot g(q)\$ ## The task Your task is to take an integer \$n \ge 2\$ as input, and produce \$g(n)\$ as output. You don't have to worry about integer overflow, but you should be able to compute \$g(1025) = 81\$ correctly, and your algorithm should theoretically work for arbitrarily large inputs. You can write a full program or a function. The lowest byte count wins. ## Example I claimed above that \$g(1025) = 81\$, so let's compute it by hand. The prime factorization of **1025** gives ``` 1025 = 5*5*41 => g(1025) = g(5)*g(5)*g(41) ``` Since **41** is prime, we get ``` g(41) = g(40) + g(42) ``` Next, we compute the prime factorizations of **40** and **42**: ``` 40 = 2*2*2*5 => g(40) = g(2)*g(2)*g(2)*g(5) = g(5) 42 = 2*3*7 => g(42) = g(2)*g(3)*g(7) = g(3)*g(7) ``` For these small primes we get ``` g(3) = g(2) + g(4) = 1 + 1 = 2 g(5) = g(4) + g(6) = 1 + 2 = 3 g(7) = g(6) + g(8) = 2 + 1 = 3 ``` This means that ``` g(41) = g(40) + g(42) = g(5) + g(3)*g(7) = 3 + 2*3 = 9 ``` and ``` g(1025) = g(5)*g(5)*g(41) = 3*3*9 = 81 ``` ## Test cases Here are the values of \$g\$ up to **50**. ``` 2 -> 1 3 -> 2 4 -> 1 5 -> 3 6 -> 2 7 -> 3 8 -> 1 9 -> 4 10 -> 3 11 -> 5 12 -> 2 13 -> 5 14 -> 3 15 -> 6 16 -> 1 17 -> 5 18 -> 4 19 -> 7 20 -> 3 21 -> 6 22 -> 5 23 -> 7 24 -> 2 25 -> 9 26 -> 5 27 -> 8 28 -> 3 29 -> 9 30 -> 6 31 -> 7 32 -> 1 33 -> 10 34 -> 5 35 -> 9 36 -> 4 37 -> 11 38 -> 7 39 -> 10 40 -> 3 41 -> 9 42 -> 6 43 -> 11 44 -> 5 45 -> 12 46 -> 7 47 -> 9 48 -> 2 49 -> 9 50 -> 9 ``` [Answer] ## Haskell, 69 bytes ``` x#a|x<3=1|a>x=a#2+(x-1)#2|mod x a<1,a<x=a#2*div x a#2|b<-a+1=x#b (#2) ``` Usage example: `(#2) 1025` -> `81` The parameter `a` is counted up until it divides `x` or it reaches `x` (i.e. `x` is prime). It it one byte shorter to test for `a > x` and add a further condition (`a < x`) to the modulus test instead of testing for `a == x`, because the former binds `a` to `x+1`, which helps in the recursive call. Compare: ``` |a==x=(x+1)#2+(x-1)#2|mod x a<1= |a>x=a#2+(x-1)#2|mod x a<1,a<x= ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ‘;’Ñ€Sµ1n2$? ÆfÇ€P ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYYb1o4aZhyc@aloTfGirYZ6Rij3X4ba0w@1AgYD///8bGhiZAgA "Jelly – TIO Nexus") This is basically just a direct translation of the specification. (After thinking about it a bit, I suspect that if there is a closed formula for finding the sequence, it'd be more bytes than the direct approach.) ## Explanation We have two mutually recursive functions. Here's the helper function (which calculates **g(n)** for prime **n**): ``` ‘;’Ñ€Sµ1n2$? ? If n2$ the input is not equal to 2 (parsed as a group due to $) µ then do all the following (parsed as a group due to µ): ‘;’ Find the list [n+1, n-1]; Ñ€ Call the main program on each element (i.e. [g(n+1),g(n-1)]); S and return the sum of the list (i.e. g(n+1)+g(n-1)). Otherwise: 1 Return 1. ``` And here's the main program, which calculates **g(n)** for any **n**: ``` ÆfÇ€P Æf Factorize the input into its prime factors; Ç€ Call the helper function on each element of that list; P Then take the product. ``` Clearly, if we call the main program on a prime number, everything's a no-op except the `Ç`, so it returns **g(n)** in this case. The rest of the program handles the behaviour for composite **n**. [Answer] ## JavaScript (ES6), 59 bytes ``` f=(n,d=2)=>n-2?d<n?n%d?f(n,d+1):f(n/d)*f(d):f(n-1)+f(n+1):1 ``` ### Test ``` f=(n,d=2)=>n-2?d<n?n%d?f(n,d+1):f(n/d)*f(d):f(n-1)+f(n+1):1 // f(2) to f(50) for(N = 2, list = []; N <= 50; N++) { list.push(N + ' -> ' + f(N)); } console.log(list.join(', ')); // f(1025) console.log(f(1025)); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Æfḟ2µ‘,’߀€SP ``` [Try it online!](https://tio.run/nexus/jelly#@3@4Le3hjvlGh7Y@apih86hh5uH5j5rWAFFwwH@jIlMDBUMDI1PrQ1uP7jncDhR1//8fJAAA "Jelly – TIO Nexus") ### How it works ``` Æfḟ2µ‘,’߀€SP Main link. Argument: n Æf Yield the array of prime factors of n. ḟ2 Remove all occurrences of 2. µ Begin a new, monadic chain. Argument: A (array of odd prime factors) ‘ Increment all elements of A. ’ Decrement all elements of A. , Pair; yield [A+1, A-1]. ߀€ Map the main link over all elements of A+1 and A-1. S Column-wise reduce by addition. P Reduce by multiplication. ``` [Answer] # Python 2, 85 69 bytes ``` g=lambda n,k=3:(n&~-n<1)or n%k and g(n,k+2)or(g(k+1)+g(k-1))*g(n/k,k) ``` [Answer] # Clojure, 126 bytes ``` (defn t[n](if(= n 2)1(let[a(+(.indexOf(for[b(range 2 n)](mod n b)2)0))](if(> a 1)(*(t(/ n a))(t a))(+(t(dec n))(t(inc n))))))) ``` Yay! It's almost twice as long as the Python answer! Ungolfed and an explanation: ``` (defn trivial [n] ; Define the function. (if (= n 2) 1 ; If the number is 2, return 1 (let [a (+ 2 (.indexOf (for [b (range 2 n)] (mod n b)) 0))] ; Let a be the lowest prime factor of n (if (> a 1) ; The .indexOf function returns -1 if a is a prime, so -1 + 2 = 1. ; Checks if a is a prime. (* (trivial (/ n a)) (trivial a)) ; If a is prime, return the trivial(a/n) * trivial(a). (+ (trivial (dec n)) (trivial (inc n))))))) ; Else, return trivial(n-1) + trivial(n + 1). ``` [Answer] # Mathematica, 83 bytes ``` Which[#<4,#-1,PrimeQ@#,Tr[#0/@({#-1,#+1}/2)],0<1,1##&@@#0/@Divisors@#~Part~{2,-2}]& ``` Unnamed recursive function of one positive integer argument, returning an integer. Not all that short, in the end. `Tr[#0/@({#-1,#+1}/2)]` (in the case where the input is prime) calls the function on both members of the ordered pair `{(#-1)/2,(#+1)/2}` and adds the results; this is fine since the function has the same value at `(#-1)/2` and `#-1`, for example. Similarly, `1##&@@#0/@Divisors@#~Part~{2,-2}` calls the function on the second-smallest divisor `#` and its complememtary divisor (the second-larget divisor) and multiplies the answers together. [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` f=lambda n,k=3:k>n or n%k and f(n,k+2)or(f(k-1)+f(k+1))*f(n/k) ``` [Try it online!](https://tio.run/nexus/python2#FYxBCoMwFETX9RSzCeY3ik1aN4JepLiIpCny7VeC90/j6sG84eU4bv63BA9peHwOPAn2BFEMLwFRl9k42pOOmltLpsBYonsxHVOO1xmr4G0frp9hkLx8P9o16C0N1e1Iq5yo1SugnaBcqKFQqleaKP8B "Python 2 – TIO Nexus") [Answer] ## Clojure, 120 bytes ``` (defn g[n](if(= n 2)1(if-let[F(first(for[i(range 2 n):when(=(mod n i)0)]i))](*(g F)(g(/ n F)))(+(g(dec n))(g(inc n)))))) ``` Uses `:when` to get divisors of `n`, `F` is `nil` if no such divisor is found (`n` is prime). [Answer] # [R](https://www.r-project.org/), 89 bytes ``` g=function(n)"if"(n<3,1,"if"(sum(y<-!n%%2:n)<2,g(n-1)+g(n+1),g(k<-1+which(y)[1])*g(n/k))) ``` [Try it online!](https://tio.run/##HYlLCoAwEMXOoiDMsy06FTdSTyKuBGsRR/CDePpaXCUhR4y@n2@ZrrALCfIw5ySu0ax/Pe@NXmcyKQrbCZzVnsQwVIJipFqdYfUsYVroxcAjyrSqFUD0xLVtET8 "R – Try It Online") ]
[Question] [ # Bailey–Borwein–Plouffe Iterations We've seen a few pi challenges on PPCG, but none that specifically dictate the algorithm you should be using. I'd like to see implementations of the [Bailey–Borwein–Plouffe algorithm](https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula) in any language up to iteration `n`. The formula is as follows: [![Modified formula.](https://i.stack.imgur.com/Emi5u.png)](https://i.stack.imgur.com/Emi5u.png) Your algorithm should output each iteration up to n, showing intermediate sums as well as the final result to form a "piangle". You may also use the reduced polynomial form of the algorithm shown on the wikipedia page. An example run for `n=50` is shown below: ``` 3 3.1 3.14 3.141 3.1415 3.14159 3.141592 3.1415926 3.14159265 3.141592653 3.1415926535 3.14159265358 3.141592653589 3.1415926535897 3.14159265358979 3.141592653589793 3.1415926535897932 3.14159265358979323 3.141592653589793238 3.1415926535897932384 3.14159265358979323846 3.141592653589793238462 3.1415926535897932384626 3.14159265358979323846264 3.141592653589793238462643 3.1415926535897932384626433 3.14159265358979323846264338 3.141592653589793238462643383 3.1415926535897932384626433832 3.14159265358979323846264338327 3.141592653589793238462643383279 3.1415926535897932384626433832795 3.14159265358979323846264338327950 3.141592653589793238462643383279502 3.1415926535897932384626433832795028 3.14159265358979323846264338327950288 3.141592653589793238462643383279502884 3.1415926535897932384626433832795028841 3.14159265358979323846264338327950288419 3.141592653589793238462643383279502884197 3.1415926535897932384626433832795028841971 3.14159265358979323846264338327950288419716 3.141592653589793238462643383279502884197169 3.1415926535897932384626433832795028841971693 3.14159265358979323846264338327950288419716939 3.141592653589793238462643383279502884197169399 3.1415926535897932384626433832795028841971693993 3.14159265358979323846264338327950288419716939937 3.141592653589793238462643383279502884197169399375 3.1415926535897932384626433832795028841971693993751 3.14159265358979323846264338327950288419716939937510 ``` The precision of each iteration should equal the `n` that is passed to the algorithm, that is to say that each iteration should calculate pi up to the passed `n` for all `k`. # Rules: * Built-ins are not allowed, nor is `pi`, you must use the formula. * You must support `n` up to a maximum that your language allows in terms of the calculation of `16^n`. If the input is causing an arithmetic overflow during calculation after `x<n` executions because your language only supports decimals up to `2^32-1`, this is fine. Any other assumptions on `n` are not fine. * You **MUST** provide an explanation of how you got the output if it is not obvious. For instance, if you're posting in a Golfing language a break-down is 100% required. This is to ensure you're using the algorithm that is specified. * Standard loop-holes are disallowed. * This is code-golf, lowest byte count wins here. Reference Code (Code used to Generate Example): ``` public static void main(String[] args) { (0..50).each { n-> def x=(0..n).collect { j-> def k=new BigDecimal(j) def s={it.setScale(n)} def a=s(1.0g).divide(s(16.0g)**s(k)) def b=s(4.0g)/(s(8.0g)*s(k)+s(1.0g)) def c=s(2.0g)/(s(8.0g)*s(k)+s(4.0g)) def d=s(1.0g)/(s(8.0g)*s(k)+s(5.0g)) def e=s(1.0g)/(s(8.0g)*s(k)+s(6.0g)) def f=a*(b-c-d-e) }.sum() println(n + "\t" + x.setScale(n, BigDecimal.ROUND_DOWN)) } } ``` This implementation caps out at `n=255`, you may cap out at less or more. This implementation was done in Groovy. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~63~~ ~~52~~ 50 bytes **Specialization formula** ``` ΃0NU62201122vy͹̰*8X*N>+÷+}16Xm÷+DX>£X__iÀ'.ìÁ}, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w47GkjBOVTYyMjAxMTIydnnDjcK5w4zCsCo4WCpOPivDtyt9MTZYbcO3K0RYPsKjWF9facOAJy7DrMOBfSw&input=MTAw) **BBP formula** ``` ƒ4¹>°UX*8N*©>÷YX*®4+÷-1X*®5+÷-1X*®6+÷-1X*16Nm÷*ODN>£N__iÀ'.ìÁ}, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xpI0wrk-wrBVWCo4TirCqT7Dt1lYKsKuNCvDty0xWCrCrjUrw7ctMVgqwq42K8O3LTFYKjE2Tm3DtypPRE4-wqNOX19pw4AnLsOsw4F9LA&input=MTAw) [Answer] # Python 2, ~~109~~ 108 bytes ``` def f(n):k=1;s=0;t=100**n;exec-~n*'s+=4*t/k-2*t/(k+3)-t/(k+4)-t/(k+5)>>k/2;print"3."[:k]+`s`[1:k/8+1];k+=8;' ``` Test it on [Ideone](http://ideone.com/H61RgM). [Answer] # PARI/GP, 86 bytes ``` n->for(k=p=0,n,printf("%."k"f\n",(p=16*p-4/(3-j=8*k+4)-2/j-1/j++-1/j++)\(8/5)^k/10^k)) ``` Or without the decimal point in **69 bytes**: ``` n->for(k=p=0,n,print((p=16*p-4/(3-j=8*k+4)-2/j-1/j++-1/j++)\(8/5)^k)) ``` Rather than dividing through by *16k* each iteration, the previous value of *p* is instead multiplied by *16*. Floor of *p ÷ (8/5)k* is then the value of *π* truncated to the correct number of digits. **Sample Usage** ``` $ gp ? n->for(k=p=0,n,printf("%."k"f\n",(p=16*p-4/(3-j=8*k+4)-2/j-1/j++-1/j++)\(8/5)^k/10^k)) ? %(20) 3 3.1 3.14 3.141 3.1415 3.14159 3.141592 3.1415926 3.14159265 3.141592653 3.1415926535 3.14159265358 3.141592653589 3.1415926535897 3.14159265358979 3.141592653589793 3.1415926535897932 3.14159265358979323 3.141592653589793238 3.1415926535897932384 3.14159265358979323846 ``` [Answer] # Python 2, 174 Bytes Man, this is a time when I wish that Python had some easier way of keeping infinite precision for decimals.. Possibly implementing your own infite accuracy type for this challenge is shorter but I can't imagine how. The formula is written verbatim. ``` from decimal import* n=input();d=Decimal;getcontext().prec=n+2;p=d(0) for i in range(n+1):f=8.*i;p+=d(16**(-i))*(4/d(f+1)-2/d(f+4)-1/d(f+5)-1/d(f+6));print str(p)[:-~i+(i>0)] ``` Example output for `n=100` (with some added line numbers): ``` 3 3.1 3.14 3.141 3.1415 3.14159 3.141592 3.1415926 3.14159265 3.141592653 3.1415926535 3.14159265358 3.141592653589 3.1415926535897 3.14159265358979 3.141592653589793 3.1415926535897932 3.14159265358979323 3.141592653589793238 3.1415926535897932384 3.14159265358979323846 3.141592653589793238462 3.1415926535897932384626 3.14159265358979323846264 3.141592653589793238462643 3.1415926535897932384626433 3.14159265358979323846264338 3.141592653589793238462643383 3.1415926535897932384626433832 3.14159265358979323846264338327 3.141592653589793238462643383279 3.1415926535897932384626433832795 3.14159265358979323846264338327950 3.141592653589793238462643383279502 3.1415926535897932384626433832795028 3.14159265358979323846264338327950288 3.141592653589793238462643383279502884 3.1415926535897932384626433832795028841 3.14159265358979323846264338327950288419 3.141592653589793238462643383279502884197 3.1415926535897932384626433832795028841971 3.14159265358979323846264338327950288419716 3.141592653589793238462643383279502884197169 3.1415926535897932384626433832795028841971693 3.14159265358979323846264338327950288419716939 3.141592653589793238462643383279502884197169399 3.1415926535897932384626433832795028841971693993 3.14159265358979323846264338327950288419716939937 3.141592653589793238462643383279502884197169399375 3.1415926535897932384626433832795028841971693993751 3.14159265358979323846264338327950288419716939937510 3.141592653589793238462643383279502884197169399375105 3.1415926535897932384626433832795028841971693993751058 3.14159265358979323846264338327950288419716939937510582 3.141592653589793238462643383279502884197169399375105820 3.1415926535897932384626433832795028841971693993751058209 3.14159265358979323846264338327950288419716939937510582097 3.141592653589793238462643383279502884197169399375105820974 3.1415926535897932384626433832795028841971693993751058209749 3.14159265358979323846264338327950288419716939937510582097494 3.141592653589793238462643383279502884197169399375105820974944 3.1415926535897932384626433832795028841971693993751058209749445 3.14159265358979323846264338327950288419716939937510582097494459 3.141592653589793238462643383279502884197169399375105820974944592 3.1415926535897932384626433832795028841971693993751058209749445923 3.14159265358979323846264338327950288419716939937510582097494459230 3.141592653589793238462643383279502884197169399375105820974944592307 3.1415926535897932384626433832795028841971693993751058209749445923078 3.14159265358979323846264338327950288419716939937510582097494459230781 3.141592653589793238462643383279502884197169399375105820974944592307816 3.1415926535897932384626433832795028841971693993751058209749445923078164 3.14159265358979323846264338327950288419716939937510582097494459230781640 3.141592653589793238462643383279502884197169399375105820974944592307816406 3.1415926535897932384626433832795028841971693993751058209749445923078164062 3.14159265358979323846264338327950288419716939937510582097494459230781640628 3.141592653589793238462643383279502884197169399375105820974944592307816406286 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 3.14159265358979323846264338327950288419716939937510582097494459230781640628620 3.141592653589793238462643383279502884197169399375105820974944592307816406286208 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 ``` This does seem to work for larger numbers, `n=1000` runs in a couple seconds and `n=10000` doesn't seem to have given me any errors yet! [Answer] # J, ~~73~~ ~~64~~ 62 bytes ``` (j.":"+10&^(<.@*%[)[:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8)@i.@>: ``` This outputs each approximation to *n* digits as a formatted string. This uses the polynomial simplification of the formula and gets the first *n* digits by multiplying the sum by a power of 10, flooring it, and dividing by that same power of 10. The input is taken as an extended integer, meaning that rationals are used when division occurs which keeps results exact. ## Usage This is the output for *n* = 100, showing the cumulative sums for *k* in [0, 100]. ``` f =: (j.":"+10&^(<.@*%[)[:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8)@i.@>: f 100x 3 3.1 3.14 3.141 3.1415 3.14159 3.141592 3.1415926 3.14159265 3.141592653 3.1415926535 3.14159265358 3.141592653589 3.1415926535897 3.14159265358979 3.141592653589793 3.1415926535897932 3.14159265358979323 3.141592653589793238 3.1415926535897932384 3.14159265358979323846 3.141592653589793238462 3.1415926535897932384626 3.14159265358979323846264 3.141592653589793238462643 3.1415926535897932384626433 3.14159265358979323846264338 3.141592653589793238462643383 3.1415926535897932384626433832 3.14159265358979323846264338327 3.141592653589793238462643383279 3.1415926535897932384626433832795 3.14159265358979323846264338327950 3.141592653589793238462643383279502 3.1415926535897932384626433832795028 3.14159265358979323846264338327950288 3.141592653589793238462643383279502884 3.1415926535897932384626433832795028841 3.14159265358979323846264338327950288419 3.141592653589793238462643383279502884197 3.1415926535897932384626433832795028841971 3.14159265358979323846264338327950288419716 3.141592653589793238462643383279502884197169 3.1415926535897932384626433832795028841971693 3.14159265358979323846264338327950288419716939 3.141592653589793238462643383279502884197169399 3.1415926535897932384626433832795028841971693993 3.14159265358979323846264338327950288419716939937 3.141592653589793238462643383279502884197169399375 3.1415926535897932384626433832795028841971693993751 3.14159265358979323846264338327950288419716939937510 3.141592653589793238462643383279502884197169399375105 3.1415926535897932384626433832795028841971693993751058 3.14159265358979323846264338327950288419716939937510582 3.141592653589793238462643383279502884197169399375105820 3.1415926535897932384626433832795028841971693993751058209 3.14159265358979323846264338327950288419716939937510582097 3.141592653589793238462643383279502884197169399375105820974 3.1415926535897932384626433832795028841971693993751058209749 3.14159265358979323846264338327950288419716939937510582097494 3.141592653589793238462643383279502884197169399375105820974944 3.1415926535897932384626433832795028841971693993751058209749445 3.14159265358979323846264338327950288419716939937510582097494459 3.141592653589793238462643383279502884197169399375105820974944592 3.1415926535897932384626433832795028841971693993751058209749445923 3.14159265358979323846264338327950288419716939937510582097494459230 3.141592653589793238462643383279502884197169399375105820974944592307 3.1415926535897932384626433832795028841971693993751058209749445923078 3.14159265358979323846264338327950288419716939937510582097494459230781 3.141592653589793238462643383279502884197169399375105820974944592307816 3.1415926535897932384626433832795028841971693993751058209749445923078164 3.14159265358979323846264338327950288419716939937510582097494459230781640 3.141592653589793238462643383279502884197169399375105820974944592307816406 3.1415926535897932384626433832795028841971693993751058209749445923078164062 3.14159265358979323846264338327950288419716939937510582097494459230781640628 3.141592653589793238462643383279502884197169399375105820974944592307816406286 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 3.14159265358979323846264338327950288419716939937510582097494459230781640628620 3.141592653589793238462643383279502884197169399375105820974944592307816406286208 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 ``` ## Explanation First make the range [0, *n*], shown for *n* = 5 ``` i. >: 5 0 1 2 3 4 5 ``` Multiply each by 8 ``` (*&8) i. >: 5 0 8 16 24 32 40 ``` Form the addition table between `[1, 4, 5, 6]` and the products with 8 ``` (1 4 5 6+/*&8) i. >: 5 1 9 17 25 33 41 4 12 20 28 36 44 5 13 21 29 37 45 6 14 22 30 38 46 ``` Divide each row by `[4, 2, -1, 1]` ``` (4 2 _1 1%1 4 5 6+/*&8) i. >: 5 4 0.444444 0.235294 0.16 0.121212 0.097561 0.5 0.166667 0.1 0.0714286 0.0555556 0.0454545 _0.2 _0.0769231 _0.047619 _0.0344828 _0.027027 _0.0222222 0.166667 0.0714286 0.0454545 0.0333333 0.0263158 0.0217391 ``` Then reduce the columns from bottom-to-top using subtraction ``` ([:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3.13333 0.129426 0.0422205 0.0207553 0.0123137 0.00814508 ``` Divide each 16*k* for *k* in [0, *n*] by each result ``` (16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3.13333 0.00808913 0.000164924 5.06722e_6 1.87893e_7 7.76775e_9 ``` Find the cumulative sums ``` ([:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3.13333 3.14142 3.14159 3.14159 3.14159 3.14159 ``` Compute 10*k* for *k* in [0, *n*] and multiply it with each ``` (10&^(*)[:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3.13333 31.4142 314.159 3141.59 31415.9 314159 ``` Then floor each of the products ``` (10&^(<.@*)[:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3 31 314 3141 31415 314159 ``` Divide it by the same power of 10 to get the results ``` (10&^(<.@*%[)[:+/\16&^%~[:-/4 2 _1 1%1 4 5 6+/*&8) i. >: 5 3 3.1 3.14 3.141 3.1415 3.14159 ``` [Answer] # C GCC, 118 bytes Golfed: ``` main(){double k,a,s=1,t;k=a=0;while(k<15){t=k++*8;a+=(4/(t+1)-2/(t+4)-1/(t+5)-1/(t+6))/s;s*=16;printf("%.15lf\n",a);}} ``` Ungolfed: ``` main(){ double k,a,s=1,t; k=a=0; while(k<15){ t=k++*8; a+=(4/(t+1)-2/(t+4)-1/(t+5)-1/(t+6))/s; s*=16; printf("%.15lf\n",a); } } ``` To change n, just change while(k<15) to while(k < n) output: ``` $ gcc pigolf.c -o pigolf some gcc screaming warnings $ ./pigolf 3.133333333333333 3.141422466422466 3.141587390346582 3.141592457567436 3.141592645460336 3.141592653228088 3.141592653572881 3.141592653588973 3.141592653589752 3.141592653589791 3.141592653589793 3.141592653589793 3.141592653589793 3.141592653589793 3.141592653589793 ``` max precision is 15 decimal places, i could increase to any value with gmp, but maybe next pi day :P ## with pretty print, 143 bytes Golfed: ``` main(){double k,a,s=1,t;char o[19];k=a=0;while(k<15){t=k++*8;a+=(4/(t+1)-2/(t+4)-1/(t+5)-1/(t+6))/s;s*=16;snprintf(o,k+3,"%.15lf",a);puts(o);}} ``` Ungolfed: ``` main(){ double k,a,s=1,t; char o[19]; k=a=0; while(k<15){ t=k++*8; a+=(4/(t+1)-2/(t+4)-1/(t+5)-1/(t+6))/s; s*=16; snprintf(o,k+3,"%.15lf",a); puts(o); } } ``` output: ``` $ gcc pigolf_pretty.c -o pigolf_pretty more gcc screaming warnings $ ./pigolf_pretty 3.1 3.14 3.141 3.1415 3.14159 3.141592 3.1415926 3.14159265 3.141592653 3.1415926535 3.14159265358 3.141592653589 3.1415926535897 3.14159265358979 3.141592653589793 ``` [Answer] ## Haskell, ~~101~~ 100 bytes Thanks to @nimi for a byte. ``` f n=take(n+2).show$sum[1/16^k*(4/(l+1)-2/(l+4)-1/(l+5)-1/(l+6))|k<-[0..100+n],l<-[8*fromIntegral k]] ``` Straightforward implementation. Calculates `n` up to 15 digits (standard double precision). [Answer] # IBM/Lotus Notes Formula, 125 bytes ``` p:=0;@For(n:=0;n<=a;n:=n+1;b:=8*n;p:=p+@Power(16;-n)*(4/(b+1)-2/(b+4)-1/(b+5)-1/(b+6));o:=o:@Left(@Text(p);n+@If(n=0;1;2)));o ``` Formula in a computed field with another field called "a" for input. Basically a port of the algorithm from the Python answer from @shebang. Calculates up to 15 digits after which it truncates due to a limitation of the language (see output). Had to waste 12 bytes with the @If statement at the end just to get rid of the . after the 3 at the start :-/ [![Sample Output](https://i.stack.imgur.com/tOrSJ.png)](https://i.stack.imgur.com/tOrSJ.png) **Ungolfed** ``` p:=0; @For(n:=0; n<=a; n:=n+1; b:=8*n; p:=p+@Power(16;-n)*(4/(b+1)-2/(b+4)-1/(b+5)-1/(b+6)); o:=o:@Left(@Text(p);n+@If(n=0;1;2)) ); o ``` [Answer] # C#, 183 bytes Golfed: ``` void F(int n){double s=0;for(int k=0;k<=n;k++){s+=1/Math.Pow(16,k)*(4.0/(8*k+1)-2.0/(8*k+4)-1.0/(8*k+5)-1.0/(8*k+6));double p=Math.Pow(10,k);Console.WriteLine(Math.Truncate(s*p)/p);}} ``` Ungolfed: ``` void F(int n) { double s = 0; for (int k = 0; k <= n; k++) { s += 1/Math.Pow(16, k)*(4.0/(8*k + 1) - 2.0/(8*k + 4) - 1.0/(8*k + 5) - 1.0/(8*k + 6)); double p = Math.Pow(10, k); Console.WriteLine(Math.Truncate(s*p)/p); } } ``` [Answer] # APL(NARS), 206 chars, 412 bytes ``` fdn←{1∧÷⍵}⋄fnm←{1∧⍵}⋄r2fs←{q←⌈-/10x⍟¨(fdn ⍵),fnm ⍵⋄m←⎕ct⋄⎕ct←0⋄a←⌊⍵×10x*⍺⋄⎕ct←m⋄k←≢b←⍕a⋄0≥k-⍺:'0.',((⍺-k)⍴'0'),b⋄((k-⍺)↑b),'.',(k-⍺)↓b}⋄p←{+/¨{k←1+8×⍵⋄(+/4 2 1 1÷k,-k+3..5)÷16*⍵}¨¨{0..⍵}¨0..⍵}⋄q←{⍪⍵r2fs¨p⍵} ``` This find all approssimation in big rational, than use one function that convert big rational in numeric string... test: ``` q 1x 3.1 3.1 q 2x 3.13 3.14 3.14 q 3x 3.133 3.141 3.141 3.141 q 10x 3.1333333333 3.1414224664 3.1415873903 3.1415924575 3.1415926454 3.1415926532 3.1415926535 3.1415926535 3.1415926535 3.1415926535 3.1415926535 q 20x 3.13333333333333333333 3.14142246642246642246 3.14158739034658152305 3.14159245756743538183 3.14159264546033631955 3.14159265322808753473 3.14159265357288082778 3.14159265358897270494 3.14159265358975227523 3.14159265358979114638 3.14159265358979312961 3.14159265358979323271 3.14159265358979323815 3.14159265358979323844 3.14159265358979323846 3.14159265358979323846 3.14159265358979323846 3.14159265358979323846 3.14159265358979323846 3.14159265358979323846 3.14159265358979323846 q 57x 3.133333333333333333333333333333333333333333333333333333333 3.141422466422466422466422466422466422466422466422466422466 3.141587390346581523052111287405405052463875993287757993640 3.141592457567435381837004555057293394007389950594818748976 3.141592645460336319557021222442381831727406617979907186696 3.141592653228087534734378035536204469558528012197801934814 3.141592653572880827785240761895898484239065603786606461624 3.141592653588972704940777767170189446971120489811822860633 3.141592653589752275236177868398102225795024633409061087027 3.141592653589791146388776965910347414779015888488996772587 3.141592653589793129614170564041344858816452676296281615895 3.141592653589793232711292261930077163422606275435901151635 3.141592653589793238154766322501863827762609260414389714560 3.141592653589793238445977501940281666096938425156252904675 3.141592653589793238461732482037982486800056278143046732780 3.141592653589793238462593174670682882792683045699610435502 3.141592653589793238462640595138128445061235672871301070791 3.141592653589793238462643227424822458237094279625505676929 3.141592653589793238462643374515761485970237552267559842751 3.141592653589793238462643382784091514246623611329334708720 3.141592653589793238462643383251362615881909316518417908555 3.141592653589793238462643383277897474896408560218644955706 3.141592653589793238462643383279410929692483875831459799593 3.141592653589793238462643383279497597978087353533999465917 3.141592653589793238462643383279502579284902684600486947911 3.141592653589793238462643383279502866555094658758532859204 3.141592653589793238462643383279502883173477103651067488504 3.141592653589793238462643383279502884137610730938143080855 3.141592653589793238462643383279502884193695667358321264063 3.141592653589793238462643383279502884196966326705909950134 3.141592653589793238462643383279502884197157502154596455091 3.141592653589793238462643383279502884197168700950456888403 3.141592653589793238462643383279502884197169358296080453391 3.141592653589793238462643383279502884197169396954642664355 3.141592653589793238462643383279502884197169399232246022950 3.141592653589793238462643383279502884197169399366660542801 3.141592653589793238462643383279502884197169399374605817825 3.141592653589793238462643383279502884197169399375076175949 3.141592653589793238462643383279502884197169399375104060947 3.141592653589793238462643383279502884197169399375105716347 3.141592653589793238462643383279502884197169399375105814747 3.141592653589793238462643383279502884197169399375105820603 3.141592653589793238462643383279502884197169399375105820952 3.141592653589793238462643383279502884197169399375105820973 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 3.141592653589793238462643383279502884197169399375105820974 ``` ]
[Question] [ Your task is to write 2 functions/programs. They may share code. The first function must, given a string and a character, output a new string that does not contain that character. The second function must, given the string from the previous function and the excluded character, reconstruct the original string. All input strings will be ASCII printable, all output strings must be ASCII printable. You may choose to include or exclude whitespace, if you exclude whitespace it must be excluded from both the input and the output. ### Examples One could try to use replace the character with an escape sequence. For example `\#bcda` with excluded character becomes `\\#bcd\#` then you'd know to replace `\#` with whatever character is excluded. However, the excluded character might itself be `#` or `\` so if one uses this method they'd need to be able to dynamically switch to a different escape sequence in that case. There is no length limit for the censored string so you could try to encode the entire string in unary, but be careful that the unary char you choose may not be the excluded char. This is code golf, shortest answer in each language wins. Brownie points for interesting solutions even if they are not the shortest though. [Answer] # JavaScript (ES6), 59 bytes ### Encoder (30 bytes) Expects `(string)(char)`. ``` s=>c=>btoa(s).split(c).join`#` ``` [Try it online!](https://tio.run/##Fcu9DsIgEADgvU9x1gGIShfj0tDBycnFFyil0NCcvYbDv6dHXb/km@3TsktxzYeFRl@aBlbCT4iIECjB9Yd65mrIZMEAg@ng/AjBJx0S3SXDDoRQOtMtp7hMUgyW/ekoVFtVwRQ2nTPdf0tWmleMWTqlZ4pLv@2Lo4UJvUaaZJD1xSPSHl6UcNzUStbvWqm2fAE "JavaScript (Node.js) – Try It Online") ### Decoder (29 bytes) Expects `(encoded_string)(char)`. ``` s=>c=>atob(s.replace(/#/g,c)) ``` [Try it online!](https://tio.run/##FcuxDoIwFEDRna94gaFtxHYxxsSUwQVZTAyJe6ktAQuP9CHRr0dcb87tzWLIxm6a9yM@3aoUTBi@vgsBPEa4bVH2lJgZG9BAoAu4vL13UfqIAyfYAWM5sMaQOx6YkDPWc@zGlotzkni9ki6sLv4/JxndFIx1XGWqza0Qq8WRMDgZsOWep3X5oKY8UXV9LnbIXtVd61Tw9JNu9gc "JavaScript (Node.js) – Try It Online") ### Explanation The encoder turns the input string `s` into a base-64 string, which may only contain `[a-z]`, `[A-Z]`, `[0-9]`, `+`, `/` and `=`. Then it replaces all occurrences of the forbidden character `c` with `#`. If `c` is not a base-64 character, this 2nd step has no effect at all. (In particular, note that the base-64 string can't possibly contain any `#`.) The decoder does the exact opposite: it replaces all occurrences of `#` with the forbidden character and decodes this as a base-64 string. [Answer] # [Ruby](https://www.ruby-lang.org/), 59 bytes ``` f=->s,c{"#{s.bytes}".tr c,?.} g=->s,c{(eval s.tr ?.,c).pack"U*"} ``` [Try it online!](https://tio.run/##KypNqvz/P81W165YJ7laSbm6WC@psiS1uFZJr6RIIVnHXq@WKx0qq5FalpijUAySsNfTSdbUK0hMzlYK1VKq/V9hmxatZGhkbJJYnJKmpGNvFMtVoFABxOnRFToKQO5/AA "Ruby – Try It Online") TIO says 64 byes, because 2 function headers and a newline are included. Inspired by Arnauld's JS answer. ### Encode First convert the string to a sequence of 8-bit values, then convert it to a string again, and finally replace the character to be excluded with a dot. The first step is equivalent to `unpack` using UTF-8 byte values, only slightly shorter. ### Decode Reverse order: first replace the character that was excluded, then convert it to an array of 8-bit values, and finally pack it to a string. This is equivalent to mapping the `&:chr` method on the list, and then joining the characters, only slightly shorter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 + 5 = 9 bytes (4 + 4 = 8 bytes if we do not need to handle the empty string\*, remove `€`.) Uses the same approach as others, port of [bsoelch's Python answer](https://codegolf.stackexchange.com/a/266522/53748). ### [Encoder](https://tio.run/##AS0A0v9qZWxsef//T@G5vuG5o0v/w6fhuKJ9//8iMjAxIGFuZCAzMDEsNDAxIv8iMCI "Jelly – Try It Online") A dyadic Link that accepts the plaintext on the left and the character on the right and yields the ciphertext. ``` OṾṣK - Link: plaintext, P; character, C e.g. P="20 cats"; C='0' O - cast P to ordinals [50,48,32,99,97,116,115] Ṿ - unevaluate "50,48,32,99,97,116,115" ṣ - split at occurrences of C ["5",",48,32,99,97,116,115"] K - join with spaces "5 ,48,32,99,97,116,115" (note that if C=' ' we get "50,48,32,99,97,116,115") ``` ### [Decoder](https://tio.run/##y0rNyan8///hjk1ZYQ939zxqWvP/8PKHOxbV/v@vZKqgY2KhY2KpY2ykY2muY2iooGOooADimRpCZUxMdEyNIGyl/0oGSgA "Jelly – Try It Online") A dyadic Link that accepts the ciphertext on the left and the character on the right and yields the plaintext. ``` ḲjVỌ€ - Link: cyphertext X; character C e.g. X="5 ,48,32,99,97,116,115", C='0' Ḳ - split X at spaces ["5",",48,32,99,97,116,115"] j - join with C "50,48,32,99,97,116,115" V - evaluate as Jelly code [50,48,32,99,97,116,115] Ọ€ - cast each to a character "20 cats" ``` \* An empty ciphertext evaluates (`V`) to the integer zero, so without `€` the cast (`Ọ`) will convert that to a NULL byte terminated empty string (in all other cases it will vectorise automatically but `€` will implicitly cast this edge-case zero to an empty range first). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 + 5 = 11 bytes Encoder: -1 thanks to @KevinCruijssen ``` ≠sÇ₁β× ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhZrH3UuKD7c_qip8dymw9OXFCclF0NlFiwx4IpRhrAB) Decoder: ``` g₁вçJ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=7dyxEUNgAIDRYdS5o8idGTJDGnIYgAzAGpq_IE5rBQuolSZRMEOq98pviK__xc8sT4oQxm9TPtK5Orp2W9bpNdT5p75r2N9RAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAD80zULPwE) `J` could be removed for -1 to output a list of characters instead of a string. Uses unary, with `0` if the character is `1` and `1` otherwise. [Answer] # [Python](https://www.python.org), 86 bytes *inspired by [Arnauld's JavaScript solution](https://codegolf.stackexchange.com/questions/266518/encode-the-input-to-exclude-a-given-character-part-1/266523#266523)* *-25 bytes, thanks to corvus\_192* Encoder: ``` lambda s,c:str([*map(ord,s)]).replace(c,"#") ``` Decoder: ``` lambda s,c:map(chr,eval(s.replace("#",c))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fdI7DgIhEAbg2HoKgg0Y3Ox2xsTeA5hYGAsEjJhx2QBqvIiNjY3eSU8juz7R1WS6-fgnk2F_KrZ-bvLD4bjys073PFZ94Mup5Mgx0XPeknF7yQtirGSOTmhiVQFcKCIYbmHalO-8hGJumVpzIO5JA2SCUnobcWnsCqtzTzBOFkbnJICBAjCY4QwH1ozb8gPE6lMHm2VpWlbg6a-82MSwJnKonA-U_4p79WNUE1VtgkbGggwv0N-F31lsa4I3GgBpj2ZcA66OU5_87e74dp7HT7gC) encodes string as an array sequence of character-codes --- # [Python](https://www.python.org), 182 bytes ``` def q(S,N,K,n,d): k=sum((ord(c)&K)*N**i for i,c in enumerate(S));s=[] while k:s+=[chr(k%n+d)];k//=n return s e=lambda s,c:q(s,128,-1,2,48+2*(c in"01")) d=lambda s,c:q(s,2,1,128,0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddGxTsMwEAbg3U9hWQKdkyuNI4YoVXakSl3KVnUIsaOYJE5rO0I8C0sXeATehZUnIYEilIhKt92n_-50L2-HZ1915nR67X25SD7epSrpEba4wTUalDwltM5c3wJ0VkLBr9c82ASBpmVnqcaCakOV6Vtlc69gy_nKZbs9oU-VbhStUxdmu6KyUF-ZUPL9ql4uM0OoVb63hjqisiZvH2ROHRbpERyKOMGFwBhvkzAOYBzAIsE4J3JOYxTfPOLn7T8PVhsPjN08dtqAAnanmqZjyMYATqZtOQNTNdeDFSKKxhp4dClvaqbwn8h75fxA80txf_0z-rn0919f) The encoder (`e(s,c)`) interprets the string as a base 128 number and converts it to binary (using `2` and `3` if the excluded character is `0` or `1`). The decoder (`d(s,c)`) converts a binary number to base 128 [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Ss`, 5 + 4 = 9 bytes ``` C?¬S* ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJTcyIsIiIsIkM/wqxTKiIsIiIsIltdXG4xIl0=) Input list of characters and then normal input. Outputs a string ``` ⌈@ꜝC ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJTcyIsIiIsIuKMiEDqnJ1DIiwiIiwiXCJcIiJd) Input the string from the encoder. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 + 4 bytes ## [Encoder](https://tio.run/#%23y0rNyan875N0YvvD3T3//R/uaAWxug/PeLhzWsXJ6fr///9XUlDSUUqrUAIA) ``` OḅȷịØṖxɗ/ ``` ## [Decoder](https://tio.run/#%23y0rNyan8/98n6cT2h7t7/v//b08X8D8NAA) ``` LbȷỌ ``` [Try it online!](https://tio.run/##y0rNyan875N0YvvD3T3//R/uaAWxug/PeLhzWsXJ6fr/sx41zNWxftQwR0HXTgHItj7cfminIVCJtc@jhpkqxzZZK4EkC3JKixVAjNz8olSQMoQOoBLDI/uPdR3r4nq4cxXY5HCdQ0sfNa053A4kIv//V9JQ0lFKq1ACAA "Jelly – Try It Online") Both are monadic links. The encoder takes a pair of Jelly strings (character followed by string to encode). The decoder takes the encoded string as the first argument and ignores the second argument (but doesn’t mind if it is the excluded character). This takes inspiration from [@CommandMaster’s 05AB1E answer](https://codegolf.stackexchange.com/a/266521/42248) so be sure to upvote that one too! Now fixed (properly!) to handle all printable ASCII and return strings. Thanks to @JonathanAllan for his patience in highlighting problems with previous versions. ## Explanations ### Encoder ``` O | Codepoints of strings ḅȷ | Convert both from base 1000 ɗ/ | Reduce using the following as a dyad: ịØṖ | - Index (the codepoint of the single character) into the list of printable ASCII (will always be a different character) x | - Repeat this as many times as the base-1000 decoded string ``` ### Decoder ``` L | Length bȷ | Convert to base 1000 Ọ | Convert from code points to ASCII ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 + 9 = 18 bytes ## Encoder, 9 bytes: ``` ⍘⍘S⁺¶γ⁻γS ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITEdmeuYVlJZA2Zo6CgE5pcUaSjF5SjoK6ZpAvm9mHlAgXUcBRR0QWP//75yfkqrgnp@TxpX/X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: "Decodes" the input as base 97 and "encodes" it as base 95. (Base 97 is needed to prevent the input from having leading zeros.) ## Decoder, 9 bytes: ``` ⍘⍘S⁻γS⁺¶γ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITEdmeuYVlJZA2Zo6Cr6ZeaXFGuk6CijimkCZgByghFJMnpKOQjpQwPr/f@8IW7eCBK0Efa78/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: "Decodes" the input as base 95 and "encodes" it as base 97. [Answer] # [Python](https://www.python.org), 68 bytes ``` e=lambda s,c:str([*s]).replace(c,'#') d=lambda s,c:eval(s.replace('#',c)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PVNtcxJzk1ISFYp1kq2KS4o0orWKYzX1ilILchKTUzWSddSV1TW5UpBVpZYl5mgUw5UAFegka2pCDfQuKMrMK9FI1UhS8kjNycnXUSjPL8pJUVTSUTJU0tTkgkgnVZakFmuk4FIGUQs1EuZWAA) Inspired by Arnauld's JS answer. The encoder converts to a stringified list of code points, replacing the excluded character with a "#". The decoder replaces "#" with the excluded character and returns a list of code points. # [Python](https://www.python.org), 73 bytes ``` e=lambda s,c:s.hex().replace(c,'#') d=lambda s,c:b''.fromhex(s.replace('#',c)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3_VJtcxJzk1ISFYp1kq2K9TJSKzQ09YpSC3ISk1M1knXUldU1uVKQ1SSpq-ulFeXnglQWw1UC1ekka2pCTXUpKMrMK9FI1UhS8kjNycnXUSjPL8pJUVTSUTJU0tTkgkin4FIAUQUxC-ZSAA) Also inspired by Arnauld's JS answer. Converts to/from hex, replacing the excluded character with a "#". [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` e=s=>c=>(s+"").split(c).join`#` d=s=>c=>s.replace(/#/g,c).split`,` ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XdBBCsIwEAXQvaeI6WaCMd0KUkFR8AC6b0lGqYREkkj1LG660CN4GG9jbRMXbv8f3gxzfxirsG2fl3CYzt4rLHyxkMUC_IRSJvxZ1wEkEydbmzIrRyr2Xjg860oi5Fl-5DKOlryM0ktjIGhkpytSEASDDdnhNWz6zAETQwt0i1pbThrrtBpTxoByyuYjaY23GoW2R4hQl35ZhYlN6BoTOnT9tn1twmzpXHUD9RN6nP3xEWTz4fj0jg8) (It's five bytes less than on ATO because of `e=`, newline and `d=`.). Encodes as a list of ascii codes, which normally contain only digits and commas. Then the forbidden character is replaced with `#`. The decoder does the reverse and returns an array of strings of ascii codes, like `["72","101", ...]`. There are JS functions that interpret this as a sequence of integers (in particular `new Uint8Array`). An iterable of integers [is a string](https://codegolf.meta.stackexchange.com/a/8964). [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 122 + 68 = 190 bytes ``` >-[-[-<]>>+<]>[->+>+>+>+<<<<]>>->>->+>+>,[-<<<-<->>>>]<<<[>>-<<[-]]<[>>-<<[-]]>>[->+<]>[<<<<++<++>>>>>-]<<<,[[-<<.>>]<.>,] ``` [Try it online!](https://tio.run/##TUzLCoAwDPsVPW/1C0rO/oGH0YOPCeJQEPz@merFJpSSJpmucTvWe95rhSRCDQhcSRA@KIeiOF2INKmKUgCMZ@KHW8x@J94GL/J8CKT7IZ6IyTs6j3eIVmvucylnbIbzKkv7AA "brainfuck – Try It Online") ``` ,[->+>+<<]>>[>+<[-<-<+>>]<[>>->.[-]<<<[-<+>]]>>[>+<[-]]<<<[->+<]>>,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXTttO28Ym1s4uGkhH69ro2mjb2cXaRNvZ6drpRevG2tiARLXtYuFKYiFiQDZQSCf2/39FKgEFRXoA@tgy7C0j1T6FgXL9oA6V0VRGriUKAA "brainfuck – Try It Online") A Simple Unary encoder. Typically uses `!` as the unary char and space as the separator, though if either of those chars are the exclusion char, uses `#` and `"` instead. (Char codes 32, 33, 34, and 35 respectively) ## With Comments ### Encoder ``` >-[-[-<]>>+<]> Load 33 [->+>+>+>+<<<<]> Smear it across 4 places This is used to check the exclusion character as well as to store them >->>-> Lower to 32 +>+> Load two not flags , Load the Exclusion Char [-<<<-<->>>>] Subtract any equals will be zeroed <<<[>>-<<[-]]<[>>-<<[-]] Invert the invert flags >>[->+<] Add them essentially an or >[<<<<++<++>>>>>-] If either are true increment both chars by 2 <<<, [ Main Loop WHILE we have input [- decrement the char <<.>> Output the unary char ] <.> Output the seperator , Read the next char ] ``` ### Decoder ``` ,[->+>+<<] Load the first char as the unary char and spread it to the working char as well >>[ While we have working chars >+< Set up the inverse flag [-<-<+>>] Compare to the unary char <[ if theyre not equal >>- flip the invert flag >.[-] output and clear the running total <<<[-<+>]] >>[ Otherwise >+< [-]] Increment the running total <<<[->+<] Restore the test char >> Go home ,] Repeat ``` [Answer] # [Uiua](https://uiua.org), 19 + 20 = 39 bytes Encode: ``` ++@0×2<@2∶♭⋯-@\0⊂@a ``` Decode: ``` ↘1+@\0⍘⋯↯~7-+@0×2<@2 ``` [Try them online!](https://www.uiua.org/pad?src=RW5jb2RlIOKGkCArK0Aww5cyPEAy4oi24pmt4ouvLUBcMOKKgkBhCkRlY29kZSDihpAg4oaYMStAXDDijZjii6_ihq9-Ny0rQDDDlzI8QDIKCkVuY29kZSAiYWJjZGUiIEAxCkVuY29kZSAiYWJjZGUiIEAyCgpEZWNvZGUgQDEgRW5jb2RlICIxMjM0IiBAMQpEZWNvZGUgQDIgRW5jb2RlICJhYmNkZSIgQDIK) --- To encode, we prepend "a" to the string, convert it to bitwise representation, and then: * if the excluded letter is less than ASCII '2', we use '2' and '3' for the bits * otherwise we use '0' and '1' for the bits The "a" is prepended to the string because it was the most character-efficient way of ensuring that the characters are always encoded into 7 bits each, otherwise a string like "1234" would be encoded as 6-byte characters ]
[Question] [ A palindrome is a word which is spelled the same backwards and forwards. For example, "racecar" is a palindrome as is "redder". A double palindrome is a palindrome whose halves are also palindromes. For example, "abbabba" is a double palindrome, as the half "abba" is also a palindrome. Similarily, "abaababaaba" is a triple palindrome and so on. Your task is to take a string and return the degree of palindromess. If the string is not a palindrome, return 0. In order to avoid ambiguity in some edge-cases, the first two letters are guranteed to be different, and the input has at least three letters. The input string consists entirely of lowercase letters. # Examples ``` "notapalindrome" -> 0 "madam" -> 1 "xyxxxyx" -> 1 "racecarracecar" -> 2 "ababababa" -> 3 "abbaabbaabbaabba" -> 3 ``` [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` f=lambda s:s==s[::-1]and-~f(s[len(s)/2:]) ``` [Try it online!](https://tio.run/##TU3NasMwDL77KXSrA03XZjeD@yKlByV2mMF/SBpbL3v1zC5tKUJI359Ub/JV8rRtq42YZofAhq3lizHj6YrZjX@r5kv0WfPwMZnrsIVUCwnwjdVaCGLIHkLu@MDiQjYK4KeQ24P/rX4R78BCwqpZqDko1P09dOAag@jdeN4NQ8u8uUMW/YRdIs/fUZqw6n65U5Wa6SXYV3rLRbBie@CoJA/jGY4qocPU15MiXPyC9BidmxTOj@rws8EZ3/vO/gM "Python 2 – Try It Online") Simple recursive function. If the string is not a palindrome, returns false instead of 0 (which I think is allowed for Python). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ‡Ḃ=‡½hŀL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigKHhuII94oChwr1oxYBMIiwiIiwiYWJhYmFiYWJhIl0=) ``` ‡ ‡ ŀ # Collect until false Ḃ= # Is a palindrome ½h # Get first half (rounded up) L # Get length ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ←VS≠↔¡o←½ ``` [Try it online!](https://tio.run/##yygtzv6fG6zzqKnx0Lb/j9omhAU/6lzwqG3KoYX5QN6hvf///8/LL0ksSMzJzEspys9N5cpNTEnM5SpKTE5NTiyCUlyJSVAIZCUlImMA "Husk – Try It Online") Longer recursion: `?K0ö→₀←½S≠↔` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 21 bytes ``` {𝕩≡⌽𝕩?1+𝕊𝕩↑˜⌈÷⟜2≠𝕩;0} ``` Anonymous function that takes a string and returns an integer. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiaHijL3wnZWpPzEr8J2VivCdlanihpHLnOKMiMO34p+cMuKJoPCdlak7MH0KCkbCqCDin6gibm9wZSIsICJtYWRhbSIsICJ4eXh4eHl4IiwgInJhY2VjYXJyYWNlY2FyIiwgImFiYWJhYmFiYSLin6k=) ### Explanation ``` {𝕩≡⌽𝕩?1+𝕊𝕩↑˜⌈÷⟜2≠𝕩;0} { } Define a block function ? If: ⌽𝕩 The argument, reversed 𝕩≡ is the same as the argument Then (the argument is a palindrome): ≠𝕩 Length of the argument ÷⟜2 Divided by 2 ⌈ Rounded up 𝕩↑˜ Take that many characters from the argument 𝕊 Recurse 1+ Add 1 to the result of the recursive call ; Else (the argument is not a palindrome): 0 0 ``` [Answer] # [R](https://www.r-project.org/), 61 bytes Or **[R](https://www.r-project.org/)>=4.1, 54 bytes** by replacing the word `function` with a `\`. ``` f=function(x)"if"(any(x-rev(x)),0,1+f(x[1:((sum(x|1)+1)/2)])) ``` [Try it online!](https://tio.run/##XYpBCsIwEEX3nkLiZoZWbOpGBA/g3p24mKYJBExSYiIRvHsssQsj84cP/z2f1WmOilYE7SwkZFoxIPuCtPXyOQ/Ydi1vFKQrPwI8ooH05thw3PV4Q8wKYlCHizvbAMy6QBPdtR29M5IhrjfdqjIMjWQK4DXwJKQgv1Qx@tqgYbkC9/9woN//OvkD "R – Try It Online") I hate and am ashamed of the part taking first half of the input, but couldn't think of something better... [Answer] # Java 8, 101 bytes ``` s->{int r=0;for(;s.contains(new StringBuffer(s).reverse());r++)s=s.substring(s.length()/2);return r;} ``` [Try it online.](https://tio.run/##TZBNb4MwDIbv/RUWp0Ss2bRjUXfYzuulx6oHE0xHB6GyTdeq4rezQNmHIsfJayfvIx/xjMtj8Tn4GkXgHatwWwBUQYlL9ASb8ToJ4M1WuQoHEJtFsV/ETRS18rCBAOtBli@3sZHXT1nZssnE@TZo/FNMoC@4P3/typLYiHVMZ2IhY23GaWplLU66XKYuI66mcNAPYx@fY5204wCc9UM2@p66vI6@s/25rQpoos9MuNsD2jv4yDFjK4m@oRCs4I9mt78loVU8YV2FgtuGkoekwQKbmDlOwCPPKQqYz2s65/g/onS5Xi4xkt5O3gDbqyg1ru3UnaKb1sH8UKTJCpI0OP@r2Hms/fAN) **Explanation:** ``` s->{ // Method with String parameter and integer return-type int r=0; // Result-integer, starting at 0 for(;s.contains(new StringBuffer(s).reverse()) // Loop as long as the String is a palindrome: ;r++) // After every iteration: Increase the result by 1 s= // Replace the String with: s.substring(s.length()/2); // Its second halve; substring at index-range [length//2,length) return r;} // After the loop, return the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒHḢ$ŒḂпL’ ``` A monadic Link accepting a list of characters that yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///oJI@HOxapHJ30cEfT4QmH9vs8apj5////xKQkBAIA "Jelly – Try It Online")** So many 2 byte instructions:( ### How? ``` ŒHḢ$ŒḂпL’ - Link: list of characters, S п - collect up input values while... ŒḂ - ...condition: is a palindrome? $ - ...next input: last two links as a monad: ŒH - split into halves (first 1 longer if odd length) Ḣ - head L - length ’ - decrement ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~10~~ 9 bytes *-1 byte thanks to a clever observation from [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` ↔?ḍt↰<|∧0 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFPuHO3pLHrVtsKl51LHc4P9/pYrKCiBS@h8BAA "Brachylog – Try It Online") Alternate 9-byte solution: `↔?ḍt↰<.∨0` ([Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFPuHO3pLHrVtsNF71LHC4P9/pYrKCiBS@h8BAA)) ### Explanation ``` ↔?ḍt↰<|∧0 ↔ The input reversed ? is the same as the input ḍ Split into two halves t Take the second half (which is the longer one if they aren't the same) ↰ Recurse < First integer greater than the result of the recursive call | If the preceding part failed (because the input isn't a palindrome): ∧ Break unification with the input 0 and set the output to 0 ``` [Answer] # Haskell, 51 bytes ``` v s|s/=reverse s=0|0<1=1+v(take(div(1+length s)2)s) ``` [Try it Online!](https://tio.run/##TYjBCsMgEER/ZZEelBQSe65fUnrYxKWRqJFd8ZR/t4TmUIbhzZsVZaMYe28gh4yOqRELgbjpmJ7W2aHpihtpH5q2Q6T8qSuIeRgxPWHIrnDI9ZawQIOXynvFgjFkz3sidQeV0GM6B@NCC/KF88H5yk9m/K969y8) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` +m`^((.)+.?)(?<-2>\2)+(?(2)^)$ $1¶ ¶ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXzs3IU5DQ09TW89eU8PeRtfILsZIU1vDXsNIM05ThUvF8NA2rkPb/v/Pyy9JLEjMycxLKcrPTeXKTUxJzOUqSkxOTU4sglJciUlQCGQlJSJjAA "Retina 0.8.2 – Try It Online") Link includes test cases. Accepts a double letter as a palindrome but not a single letter. Explanation: ``` +` ``` Repeat until no more matches can be made: ``` m`^((.)+.?) ``` Match the first half (including the middle character where relevant) of the palindrome, ... ``` (?<-2>\2)+(?(2)^)$ ``` ... then match the characters captured by capture group 2 in reverse, popping as we go, until there are none left, and... ``` $1¶ ``` ... replace the second half of the palindrome with a newline. ``` ¶ ``` Count the number of newlines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` W⁼θ⮌θ«≔∕⁺θψ²θ⊞υω»ILυ ``` [Try it online!](https://tio.run/##LYyxCgMhEETr8yssVzBN2qtCki6F5A8Ws5yCGHTVI4R8@0ZCimF4zGN8wOqfmET2EBNpuJaOiaFYfadBlQmKMUa/1XJijluGSxzxQeBS/1kvY/VxpphVLa5zgG71PuGjXI25wRm5wY3y1uY0r1aRip481n/JYaQv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W⁼θ⮌θ« ``` Repeat while the word equals its reverse... ``` ≔∕⁺θψ²θ ``` ... append a character, then halve its length, so that odd lengths get rounded up, and... ``` ⊞υω ``` ... keep track of how many times the loop executed. ``` »ILυ ``` Output the final number of loops. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 57 bytes ``` f=n=>n==[...n].reverse().join``&&f(n.slice(n.length/2))+1 ``` [Try it online!](https://tio.run/##bYrBCsMgEETv/ZBEKd3S3u2PlEI2uqYGsxtU8vsmhxxKkWF4MPNm3DDbFNZyY3FUqzdsXmzMGwD4A4k2SpmUhlkCD0PXecWQY7B0MBJP5Xt/an19VCucJRJEmZRXPUvBFWNgl2ShXuvLn7Cgw6WxJ7RkMZ1oCDieaX4j/vZQ6g4 "JavaScript (Node.js) – Try It Online") A port of Surculose Sputum's Python answer (I couldn't find any other shorter way). Replace `&&` with `?` and add `:0` at the end of the program to make it return 0 in cases where it currently returns `false`, for an extra byte. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [ÐRÊ#2äн}N ``` [Try it online](https://tio.run/##MzBNTDJM/f8/@vCEoMNdykaHl1zYW@v3/39iEhQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/6MMTgg53KRsdXnJhb63ff53/0Up5@SWJBYk5mXkpRfm5qUo6SrmJKYm5QLooMTk1ObEISgEFEpOgEMxOSkTGQKGKyooKIFaKBQA). **Explanation:** ``` [ # Loop indefinitely: Ð # Triplicate the current string # (which will be the implicit input in the first iteration) R # Reverse the top copy Ê # Pop the top two, and check whether they're NOT equal # # If this is truthy (it's not a palindrome): stop the infinite loop 2ä # Split the string into two equal-sized halves # (if the length is odd, the first string is one char longer) н # Pop and keep just the first item }N # After the infinite loop: push the (last) 0-based loop-index # (after which it is output implicitly as result) ``` Uses the legacy version, because pushing `N` outside of a loop will result in `0` in the new version of 05AB1E. ]
[Question] [ Natural numbers ≡ \$\mathbb{N}≡\{0,1,2,...\}\$ The submission can be either a program or a function, both cases will henceforth be referred to as "function". The task is to golf the shortest function \$\mathbb{N}^n→\mathbb{N}\$, i.e. a function that maps \$n\$ natural numbers (with \$n>0\$ being a number of your choosing) to a natural number, such that the function is not primitive recursive, that is, a function that is not composable from only the following functions (each variable being a natural number): (from <https://en.wikipedia.org/wiki/Primitive_recursive_function>) Zero $$Z()=0$$ Successor $$S(x)=x+1$$ Projection $$P\_i^n(x\_0,x\_1,\dots,x\_{n-1})=x\_i$$ Composition $$h(x\_0,x\_1,\dots,x\_m)=f(g\_1(x\_0,x\_1,\dots,x\_m),\dots,g\_k(x\_0,x\_1,\dots,x\_m))$$ Primitive recursion $$\begin{align}h(0,x\_0,\dots,x\_k)&=f(x\_0,\dots,x\_k)\\h(S(y),x\_0,\dots,x\_k)&=g(y,h(y,x\_0,\dots,x\_k),x\_0,\dots,x\_k)\end{align}$$ --- From the above five functions/operations, we can get many functions like the constant function, addition, multiplication, exponentiation, factorial, primality test, etc. A (total) function that is not primitive recursive could be one that grows faster than any primitive recursive function, like the [Ackermann function](https://codegolf.stackexchange.com/q/40141). Its proof of not being primitive recursive is [on Wikipedia](https://en.wikipedia.org/wiki/Ackermann_function#Proof_that_the_Ackermann_function_is_not_primitive_recursive). Or a function could be non primitive recursive due to contradictions that would arise otherwise; examples are provided in the answers to [this Math Stack Exchange question](https://math.stackexchange.com/q/75296) as pointed out by Bubbler. --- The submissions are free to use any radix as long as the same radix is used for each of the input and output numbers. Your submission can take input as a list of numbers, a list of strings representing numbers, a string containing (constant) delimiter-separated numbers, or the like. In the case of using a string or equivalent, your submissions are free to use any character to represent each digit of the radix chosen, as long the choice is consistent throughout all inputs and output. The function will always be called with the same number of inputs. The submission should always terminate and return a result, that is, it cannot loop indefinitely. The function should always give deterministic output. The submission should theoretically work for any input, including those outside of the used numeric data types. A proof accompanying your answer is appreciated, but not required. --- This challenge was drafted thanks to the helpful commenters at its [Sandbox](https://codegolf.meta.stackexchange.com/a/18671). [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` (+1)?(2?) z?f=(iterate f z!!) ``` [Try it online!](https://tio.run/##Jca7CoAgFADQva@4QYMSRa8x8UPM4RJakoqUU/Tt3YbOdHa8DuM9oViI1T2XbJC8uKUVzGVzYjZg4S5LTgFdBAHpdDFDBUohBIhPnBvVte2k9RP@jlrTu1qP20XNmtIH "Haskell – Try It Online") An Ackermann-like function. Starting the base numerical value at `2` makes for a simple base case. An annoying number of bytes are spent converting the arguments order for "apply `f` `n` times starting from `z`" from `iterate f z!!n` to `(?) z f n` which can be curried nicely. Same thing written more explicitly for 2 bytes longer: **31 bytes** ``` 0%n=n+1 m%n=iterate((m-1)%)2!!n ``` [Try it online!](https://tio.run/##JcZBCoMwEADAu69YwUBCSdC2R31JyGEJsQ3NLkFz9O1dBU8zX9x/qRSRUfHCj6mjy9zShi1pTXYyyjz7ngVhAa1MR5j5at0yNxjAewQCPni2fnTuHcJBd18hyD@uBT@72FjrCQ "Haskell – Try It Online") Another alternative to the original is to flip the two arguments to `?`, allowing it to be defined in a point-free way for the same byte count. **29 bytes** ``` (?2)?(+1) (?)=((!!).).iterate ``` [Try it online!](https://tio.run/##y0gszk7NyfmfaBvzX8PeSNNeQ9tQk0vDXtNWQ0NRUVNPUy@zJLUosST1f25iZp6CrUJBUWZeiYKKQnR0okKuQl5Nno1utIGenklsbE0uhGkcG/v/X3JaTmJ68X/d5IICAA "Haskell – Try It Online") **29 bytes** ``` (?2)?(+1) (?)f=(!!).iterate f ``` [Try it online!](https://tio.run/##Jca7CoAgFADQva@4QYMSSa8x8UPM4RJakoqUY9/ebehM58D7tCEQypWYGrli7cArpriTrK658MVeWCw4iugTSMiXTwUa0BohQnrS0uleiNmYJ/6djKF3cwH3m7ot5w8 "Haskell – Try It Online") **31 bytes** ``` n?0=n+1 0?m=2 n?m=(n-1)?m?(m-1) ``` [Try it online!](https://tio.run/##Pca9CoUwDEDhvU@RwaEilaqrJQ9SHIL4U2xC0Tv67Dc6uZzv7HQdS86qgj5I0xmPHHojb624rkZGy69KYc2pWKwNUxIIUM4kP6ggRgIGuWV00bftME03f6v/ec20XermUh4 "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) -lm, ~~268~~ ~~197~~ 194 bytes ``` x[9];e(n,c){int w=sqrt(n/6*8+1)/2-.5,b=n/6+w*~w/2,*z=x+b;for(n%=6;c--;)n-2?n-3?n-4?n-5?x[w-b]=n?*z:b:e(w-b,*z):e(w-b,1,e(b,1)):*z&&--*z:++*z;}main(n){e(x[1]=n,scanf("%d",&n));printf("%d",1+*x);} ``` [Try it online!](https://tio.run/##LU7RisIwEPyVQ7Bkk6y91GvVhtAPKT60uVaEumorNFT00y@3Dz7MMDPMwHg8eR9jqA9H2wnSHp5nenzNbrqPD0FpIffKQJrhJtetY69m@Z7TTMvFBdXa/joKWrvCekQLhFlFuGX8MPIq1DO2R0eVXMq27AQ7HsJHGd0JZoBSLkmCyCWl5GJfl@ZMguDZiVAbnuvJN9SL1fp3pRMCsLeRT34Co2QA@4rRFMUu237/@X5oTlPE4fIP "C (gcc) – Try It Online") *Now 3 more bytes off thanks to @ceilingcat again (saving a pointer `z` to `x[b]`, and then using `*z` instead of `x[b]` throughout).* *Thanks to C golfing expert @ceilingcat for reducing this by an amazing 71 bytes!* --- I decided to write an answer that works completely differently from the other solutions posted so far. This uses diagonalization of the primitive recursive functions (it's not a function that grows faster than any primitive recursive function, the way the Ackermann and Sudan functions do). I don't think there's any way to golf this to be as short as the Ackermann or Sudan programs, but it has two advantages: (1) It's easy to understand the proof that it's not primitive recursive, and (2) you can actually run it on reasonably sized inputs without running out of time or getting stack overflows! --- The basic idea behind this function \$F\$ is first to enumerate all programs to compute primitive recursive functions of one variable. Let \$P\_0, P\_1, ...\$ be this enumeration. Then, for any input \$n,\$ here's how to compute \$F(n)\$: First supply \$n\$ as input to the program \$P\_n\$ and run that. When \$P\_n\$ halts with an integer as output (as it's guaranteed to do, because it's computing a primitive recursive function), add \$1\$ to that output. That's \$F(n).\$ \$F\$ is clearly total. Now, * \$F\$ is not the function computed by \$P\_0\$ because \$F(0)\$ is one higher than the output of \$P\_0\$ on input \$0,\$ * \$F\$ is not the function computed by \$P\_1\$ because \$F(1)\$ is one higher than the output of \$P\_1\$ on input \$1,\$ * \$F\$ is not the function computed by \$P\_2\$ because \$F(2)\$ is one higher than the output of \$P\_2\$ on input \$2,\$ etc. In general, \$F\$ isn't the function computed by \$P\_n,\$ because \$F(n)\$ is one higher than the output of \$P\_n\$ on input \$n.\$ So \$F\$ isn't the same as the function computed by any of the programs \$P\_n.\$ But those are all the primitive recursive functions. So \$F\$ isn't primitive recursive. --- The way I enumerate all the primitive recursive functions is by implementing a variant of Uwe Schöning's programming language [LOOP](https://en.wikipedia.org/wiki/LOOP_(programming_language)). It is known that the functions computable by a LOOP program are precisely the primitive recursive functions. (These programs actually cover all primitive recursive functions, not just the primitive recursive functions of one variable, even though that's ultimately all we would need.) My variant miniLOOP is even simpler than the original language. Just as in LOOP, there are variables \$x\_0, x\_1, x\_2, \dots\$; each of these variables can hold a natural number (a non-negative integer). To use a miniLOOP program to compute a function of \$k\$ variables, you store the values of the \$k\$ arguments in \$x\_1, \dots, x\_k,\$ and then run the program. The output is the value of \$x\_0\$ at the end. Here are the basic programming statements available in miniLOOP (all variables are restricted to the natural numbers): * \$x\_n=m,\$ * \$x\_n=x\_m,\$ * \$x\_n\$++ (increment), * \$x\_n\$-- (decrement except that if \$x\_n\$ is equal to 0, its value is left unchanged, because we don't allow negative numbers). Statements can also be constructed from other statements using the following two constructs: * \$P;Q\$ where \$P\$ and \$Q\$ are statements; this means to execute \$P\$ first and then \$Q.\$ * \$\text{LOOP } x\_n \text{ DO } P \text{ END},\$ which means to execute \$P\$ repeatedly, \$x\_n\$ times in a row. (Repeating it 0 times means not doing it at all, of course.) Note that the number of repetitions is the value that \$x\_n\$ has when the loop starts. Even if the body of the loop changes the value of \$x\_n,\$ the number of repetitions won't change. This is the key thing that makes this an implementation of primitive recursion. --- For example, the following program doubles its input: ``` LOOP x1 DO x1++ END x0 = x1 ``` (Recall that a function of one variable takes its input in \$x\_1\$ and leaves its output in \$x\_0.\$) --- You can check that even though miniLOOP is a bit simpler than the LOOP language defined in the Wikipedia article, you can simulate all the LOOP constructs with miniLOOP programs. So miniLOOP also computes precisely the primitive recursive functions. --- Every miniLOOP program is assigned a number; that is how we enumerate them. This enumeration uses the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function) $$\pi(x,y)=\frac{(x+y)(x+y+1)}{2}+y.$$ Here is the numerical assignment: * \$x\_n=c\$ is assigned the number \$6 \pi(n,c).\$ * \$x\_n=x\_m\$ is assigned the number \$6 \pi(n,m)+1.\$ * \$x\_m\$++ is assigned all the numbers \$6 \pi(n,m)+2\$ for any \$n\$ (it doesn't matter that one program can be included multiple times in the enumeration). * \$x\_m\$-- is assigned all the numbers \$6 \pi(n,m)+3\$ for any \$n.\$ * \$P;Q\$ is assigned all the numbers \$6 \pi(q,p)+4\$, where \$p\$ is assigned to \$P\$ and \$q\$ is assigned to \$Q.\$ (\$q\$ and \$p\$ are "backwards" in this formula only because this is code golf and I ended up saving a few bytes by doing it that way.) * \$\text{LOOP } x\_n \text{ DO } P \text{ END}\$ is assigned the numbers \$6 \pi(p,n)+5,\$ where \$p\$ is a number assigned to \$P.\$ Note that every number is assigned to a unique program. (A program can have more than one number assigned to it, but a number is associated with exactly one program.) And it's easy to take a number and figure out what program it's assigned to. For example, you can check that the program above that doubles its input is assigned 1667230. This is computed as \$6 \pi(13,731)+4,\$ where \$13 =6\pi(0,1)+1\$ and \$731=6\pi(14,1)+5.\$ In that last formula, \$14=6\pi(0,1)+2.\$ --- In the C program, \$x\$ is a global array holding all the variables needed for what you're running. I've only declared it to hold 9 variables, since that's plenty for demonstrating it, but in practice you would really want to allow that to grow using `malloc` as needed. The function `e` takes an input `n` and runs the miniLOOP program assigned to `n`. It assumes that `x[1], ..., x[k]` have already been set up as desired for the input, and it leaves the output in `x[0]`. The main program simply takes its input `n`, stores it in `x[1]`, and calls `e(n)` to run the miniLOOP program assigned to `n`. It then adds `1` to the output and prints that as the output of the main program. As described in the outline at the beginning, this program halts on every input. But it's not primitive recursive, since it disagrees with miniLOOP program number `n` (at input `n`), and those miniLOOP programs compute all the primitive recursive functions. The TIO link shows what this program does with input `1667230`. Recall that `1667230` is assigned to a miniLOOP program that doubles its input, and you can see that the output of the main program here is `3334461` (which is not equal to double 1667230, being one higher, as intended). [Answer] # [Haskell](https://www.haskell.org/), ([Ackermann](https://en.wikipedia.org/wiki/Ackermann_function)-like) 31 bytes *Inspiration from [this answer](https://codegolf.stackexchange.com/a/40172/56656).* ``` 0%x=x+1 n%x=iterate((n-1)%)x!!x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30C1wrZC25ArD0hnlqQWJZakamjk6RpqqmpWKCpW/M9NzMyzLSjKzCtRMVI1@g8A "Haskell – Try It Online") Or if \$g^n\$ is \$n\$ compositions of \$g\$ then \$ f\_0(x)=x+1 \\ f\_n(x)=f\_{n-1}^x(x) \$ This function appears [here](http://builds.openlogicproject.org/content/computability/recursive-functions/non-pr-functions.pdf) with a proof that it is not primitive recursive. # [Haskell](https://www.haskell.org/), ([Ackermann](https://en.wikipedia.org/wiki/Ackermann_function)) 39 bytes ``` 0%n=n+1 m%0=(m-1)%1 m%n=(m-1)%(m%(n-1)) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30A1zzZP25ArV9XAViNX11BTFcTOg7I1clU18oAMzf@5iZl5tgVFmXklKkaqRv8B "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), ([Sudan](https://en.wikipedia.org/wiki/Sudan_function)) 45 bytes ``` (n#x)y|n<1=x+y|y<1=x|q<-n#x$y-1=(n-1)#q$q+y+1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNPuUKzsibPxtC2QruyphJE1xTa6AKFVSp1DW018nQNNZULVQq1K7UN/@cmZubZFhRl5pWoaBgqG2ka/QcA "Haskell – Try It Online") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 76 bytes ``` ?sysxsn[lx+q]sp[lydln*0=ply1-sylFxdSxly1+dsy+Syln1-snlFxln1+snLxsDLysD]dsFxp ``` [Try it online!](https://tio.run/##DcghDsAgDAXQq6BHlgz8MkNQOCRBrbJpWL5pT9/hXh697g8MChms8ZtYg41YjutebOmEcVXquh0JFrux7JW9GxHSFKUZyiRUXe45pBTyDw "dc – Try It Online") This implements [Sudan's function](https://en.wikipedia.org/wiki/Sudan_function), which I believe was the first computable but non-primitive-recursive function discovered. It grows faster than any primitive recursive function. Three space-separated arguments \$n, x,\$ and \$y\$ are read from stdin, and the output \$F(n, x, y)\$ is written to stdout. The function grows so quickly that you need something like dc that supports arbitrarily large integers to have a chance at computing any interesting examples at all. I'll post an explanation later (dc is a pain to document), but the TIO link shows how large its outputs get: \$F(2,11,2)\$ is 16,031 digits long! This appears to be the largest example I can compute on TIO without overflowing the stack (due to the heavy use of recursive calls). The Wikipedia link above has a table of sample outputs. You can run my program at TIO and see that it matches the ones that Wikipedia shows. There's a proof that it's not primitive recursive in [Theories of Computational Complexity](https://www.google.com/books/edition/Theories_of_Computational_Complexity/Q1MTwfc5sacC?hl=en&gbpv=1&printsec=frontcover), by Cristian Calude. [Answer] # [Zpr'(h](https://www.github.com/jfrech/Zpr-h), 81 bytes ``` (a () .n)|>(S n) (a (S .k) ())|>(a k (S ())) (a (S .k) (S .n))|>(a k (a (S k) n)) ``` ``` <| constants.zpr main |> (a 3 4) ``` # Execution ``` stdlib % ../Zprh --de-peano above.zpr 125 ``` # Explanation ``` ; implementation of the Ackermann-Peter function in Zpr'(h ; base case for k = 0 (ackermann-peter () .n) |> (S n) ; base case for n = 0 (ackermann-peter (S .k) ()) |> (ackermann-peter k (S ())) ; general case for k, n > 0 (ackermann-peter (S .k) (S .n)) |> (ackermann-peter k (ackermann-peter (S k) n)) ; include integer constants <| constants.zpr ; test the implementation main |> (ackermann-peter 3 4) ``` [Answer] # [Python](https://docs.python.org/3.8/) Ackermann, ~~78~~ \$\cdots\$ ~~59~~ 45 bytes Save 2 bytes (in pre production) thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805)!!! ``` A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n ``` [Try it online!](https://tio.run/##VY/BboMwDIbveQrfSLQw1UDbDS0HLnuC3boeWJtukYhBDhyqiL06C0jTNEuWvv@TD/6H@/jVU/k08LI0pmv9x7UFr6n20NIVGulz1PSCPa@sKUeles6/aXF@6HmEcA8i7WOwI9vLxMH11DnvRom7NEpYI1FDoaHUUGnY/@fDxgmOGp41IG4BkytSPKSIRRJKOLMTbOIbT7aesvepOGKZaXhtu/Arqks2i1v61IMj4JY@raxULWB19Of2q4NgtkIq4cCORnnLGhn9rCPNCgzEMEPkUzDGntz5PGfrpXswuPwA "Python 3.8 (pre-release) – Try It Online") Going with [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)'s most excellent advice and implementing the Ackermann function. [Answer] # [C (gcc)](https://gcc.gnu.org/) Ackermann, ~~37~~ 36 bytes ``` A(m,n){m=m?A(m-1,n?A(m,n-1):1):n+1;} ``` [Try it online!](https://tio.run/##VZDtaoMwFIb/exUHh5DgcTS2unWalTJ2FbU/ih9toEmHsUwQr90dI9soJPC8T94kJGV0Lstp2jONhg9a6h1hJNDsnIoEf6NhQpGN05My5fVe1ZB/l5dT@3x59/6V7Sp1m5UyHeiTMowPjuvDUQ4CIUZYI2wQkkdOHRO8IGwRhHBBkIspphRFnIyZO0vJ1QI285pby9xd5HS@ycJQcw9@rSFr8oSs4TB4AGBBwvLMbI5fLdUa5u9ZUGFQcVoNKvCRCmiXimqYlbI@qDA8cpjN366i/4yLfvtBc@0v7fpq66Vz79z/sFUfp8nr43WFcfXRG6cf "C (gcc) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~81~~ 76 bytes An inefficient but non-recursive1 implementation of the Ackermann function, accepting either Numbers or BigInts. Given enough time and memory, this should work in theory for any pair \$(m,n)\$. Takes input as `([m])(n)`. ``` s=>n=>eval("for(;s+s;){(m=s.pop())?s.push(~-m)&&n?s.push(n--&&m):n++:n++}n") ``` [Try it online!](https://tio.run/##NYxNCoNADEb3niJ04UyYKoVCF52OPYFeoHYhVvuDZsRYN2KvbmdAF@F7X17IpxgLLvt3N0RkH9VSm4VNQiapxqKRu9r2UrNijZNsDced7STi1cGXX/IXtRiGtFWKojBs8UxK@Zlph4t/wGBAiD2kLg@kXV4MHD0ohTAFAP4qW23m7cnDZgEYlIFa3tI7ygxBgcgHoZ2ag1WKnNxiDkpLbJsqbuxTMi5/ "JavaScript (Node.js) – Try It Online") --- *1: By 'non-recursive', I mean that there's no recursive function call. Therefore, the code does not depend on the size of the call stack, which is always bounded regardless of the total amount of available memory. Instead, it's using its own stack `s[]`.* [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ``` \d+ $* {`((1*)1,1*)1$ $2,$1 1,$ ,1 }`\B,(1*)$ 1$1 1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLqzpBQ8NQS9NQB0SocKkY6agYchnqqHDpGHLVJsQ46YBkVbgMQaL//xvrGAMA "Retina 0.8.2 – Try It Online") An implementation of the Ackermann function in unary arithmetic, so don't try to compute anything larger than `A(4, 1)` on TIO. Explanation: ``` \d+ $* ``` Convert to unary. ``` {` }` ``` Repeat the steps until there is only one value left on the stack. ``` ((1*)1,1*)1$ $2,$1 ``` If the top of the stack is `m+1, n+1` then decrement the latter to `n` and push a copy of `m` below `m+1` so the stack is now `m, m+1, n`. ``` 1,$ ,1 ``` If the top of the stack is `m+1, 0` then decrement the former to `m` and increment the latter to `1`. ``` \B,(1*)$ 1$1 ``` If the top of the stack is `0, n` then remove the `0` and increment `n`. ``` 1 ``` Convert to decimal. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes ``` {×⍺:∇⍣⍵⍨⍺-1⋄2+⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ee9u6wedbQ/6l38qHfro94VQL6u4aPuFiNtIL/2f9qjtgmPevse9U319H/U1XxovfGjtolAXnCQM5AM8fAM/m@gYKhgpGCs8Khjhl6aApQHAA "APL (Dyalog Unicode) – Try It Online") This function \$ f(\alpha,\omega) \$ is a variation of the commonly-known Ackermann function, which turns out as follows: $$ \begin{align} f(0,\omega)&= 2+\omega \\ f(1,\omega)&= 2\times\omega \\ f(2,\omega)&= 2^\omega \\ \end{align} $$ But the pattern doesn't extend for \$ \alpha \ge 3 \$. ### How it works ``` {×⍺:∇⍣⍵⍨⍺-1⋄2+⍵} {×⍺: } ⍝ If ⍺ is nonzero, ∇⍣⍵⍨⍺-1 ⍝ Compute this expression, which expands to... (⍺-1)(∇⍣⍵)⍺-1 ⍝ Recursively call self with left arg ⍺-1, ⍵ times ⍝ on the starting value of ⍺-1 ⋄2+⍵ ⍝ Otherwise, return 2+⍵ ``` [Answer] # MMIX, Ackermann, 60 bytes (15 instrs) (jxd) ``` 00000000: 5a000003 23000101 f8010000 5a010004 Z¡¡¤#¡¢¢ẏ¢¡¡Z¢¡¥ 00000010: e3010001 27000001 f1fffffa c1040000 ẉ¢¡¢'¡¡¢ȯ””«Ḋ¥¡¡ 00000020: 27050101 fe020004 f303fff6 f6040002 '¦¢¢“£¡¥ṙ¤”ẇẇ¥¡£ 00000030: c1010300 27000001 f1fffff2 Ḋ¢¤¡'¡¡¢ȯ””ṗ ``` Disassembly and explanation: ``` ack PBNZ $0,0F // if(!m) ADDU $0,$1,1 POP 1,0 // return n + 1 0H PBNZ $1,0F // if(!n) SETL $1,1 SUBU $0,$0,1 JMP ack // return ack(m - 1, 1) 0H SET $4,$0 SUBU $5,$1,1 GET $2,rJ PUSHJ $3,ack PUT rJ,$2 SET $1,$3 // n = ack(m, n - 1) SUBU $0,$0,1 // m-- JMP ack // return ack(m,n) ``` ]
[Question] [ I'm a musician, and I need more polyrhythms in my life! A polyrhythm occurs in music (and in nature) when two events (claps, notes, fireflies flashing etc.) are occurring at two different regular intervals. The two kinds of event happen a different number of times in the same interval. If I tap with my left hand twice, and with my right hand 3 times, in the same space of time, it looks a little bit like this: ``` ------ R . . . L . . ``` The hyphens at the top denote the length of the polyrthmic pattern, which is the lowest common multiple or 2 and 3. This can be understood as the point at which the pattern repeats. There's also a 'metarhythm', which is the pattern produced when either hand is tapping: ``` ------ R . . . L . . M . ... ``` This is a simple, and very common polyrhythm, with a ratio of 3:2. Let's just say I don't want to do a simple polyrhythm that I can work out in my head, so I need something to work it out for me. I could do it long-form on paper, or... --- Rules: * Write some code to generate and display a polyrhythm diagram, as described above. * Any old language, try for the fewest bytes. * Your code takes two arguments: + Number of taps with the Left hand (positive integer) + Number of taps with the right hand (positive integer) * It will work out the length, which is the lowest common multiple for the two arguments. * The top line will consist of two whitespace characters followed by hyphens displaying the length (length \* '-') * The second and third lines will show the pattern for the right and left hands: + It will start with an R or L, do denote which hand it is, followed by a space. + The interval for that hand is the length divided by it's argument. + The taps will start at the third character, denoted by any character you choose. From then on it will display the same character 'interval' characters apart. + It will not be longer than the length line. * The fourth line is the metarhythm: + It will start with an upper case M, followed by a space. + From the third character onwards, it will show a character (any character you choose) in every position where there's a tap on either the right or the left hand. * Trailing whitespace is irrelevant. --- Test cases: r = 3, l = 2 ``` ------ R . . . L . . M . ... ``` r = 4, l = 3 ``` ------------ R . . . . L . . . M . .. . .. ``` r = 4, l = 5 ``` -------------------- R . . . . L . . . . . M . .. . . . .. ``` r = 4, l = 7 ``` ---------------------------- R . . . . L . . . . . . . M . . .. . . . .. . ``` r = 4, l = 8 ``` -------- R . . . . L ........ M ........ ``` --- Happy golfing! [Answer] # JavaScript (ES6), 131 bytes Outputs `0` as the *tap* character. ``` r=>l=>` ${g=n=>n?s.replace(/./g,(_,x)=>[,a=x%(k/r),x%=k/l,a*x][n]&&' '):++k%l|k%r?'-'+g():`- `,s=g(k=0)}R ${g(1)}L ${g(2)}M `+g(3) ``` [Try it online!](https://tio.run/##bc3NCoJAFAXgfU/hIp25OWq/FMLVF6hNW5EcTIeaYZQxYqB8drN2gbvDdw6cO3/yrjS39hHo5loNNQ4GE4VJ4Tjzl0CNiU670FSt4mVFozASjF6YBUwyxtG6VEYGmHVRRorxhc0znXsecQjEvi9d9ZauSUlAfEEhLoJZwToUVOIS@vP3ga6gP/7CGvqTU4y7DQxlo7tGVaFqBK1HGEuY/eMWRp/A3RTup/AAMHwA "JavaScript (Node.js) – Try It Online") ### How? We use the same helper function \$g()\$ for two different purposes. When \$g()\$ is called with no argument or an argument equal to \$0\$, it recursively builds the hyphen string of length \$k=\operatorname{lcm}(l,r)\$ with a trailing linefeed: ``` g = _ => ++k % l | k % r ? '-' + g() : `-\n` ``` This string is saved in \$s\$. When \$g()\$ is called with \$1 \le n \le 3\$, it generates a *tap* string by replacing each hyphen at position \$x\$ in \$s\$ with either a space or \$0\$: ``` g = n => s.replace(/./g, (_, x) => [, a = x % (k / r), x %= k / l, a * x][n] && ' ') ``` [Answer] # Java 11, ~~226~~ ~~234~~ ~~233~~ 219 bytes ``` String h(int r,int l,int m){var s="";for(;m>0;)s+=m%r*(m--%l)<1?'.':32;return s;} r->l->{int a=r,b=l,m;for(;b>0;b=a%b,a=m)m=b;m=r*l/a;return" "+repeat("-",m)+"\nR "+h(m/r,m+1,m)+"\nL "+h(m/l,m+1,m)+"\nM "+h(m/r,m/l,m);} ``` Kind of lengthy; too bad Java does not have an `lcm()` function. Try it online [here](https://tio.run/##jVLLbtswEDzLX7EQYFiMHo7iAg2qUL0VaNFcmmPaA2XTlhySEpYrA4ahb3cpmU2KHOoeRC2Hs8/ZvTiIdL95OXd9pZo1rJWwFh5FY@A0CzxoSZD7HdpmA9o9RU@Ejdk9/wKBO8tGZrB3gbKeGpVte7OmpjXZF288fDUkdxIT@C/SJXhZwhY4nDEtVVqeGkMgOCYVV4kuti1GRVXeFhUX8yoRXDPNq0JzvFFLUaCkHk0IEMYoOykoCtMw0SwOf5ofDqwjvcREx7nHvntM/YU9vvFGnBXDOQgK1@jT0ZLUWdtT1rlCSZlom4muU8fojnljxdgV6oq9@lyjfvhD/XiV@lrA/UQdZu8lvMwW/FT8zSYwjtc4IWG5BNtXlhrqSYKbM3xzmkGeL6x3zryzc2FjNT6i0yoMx/ImbcCkKZRwW8BlOwKEmIMd3wf3XQQC/FeN9ZgBMBlPNZ2anQ4CwXKXaMqi3QYwG3M9x5tIp@lcsYf88yJbfFrd@SVwOYexqVqqTiJoSXW7mfpypsD6SLV2/d/nUB1J2tlw/g0) (TIO does not have Java 11 yet, so this uses a helper method instead of `String.repeat()`). My initial version took the interval between taps instead of the number of taps. Fixed now. Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 1 byte. Ungolfed: ``` String h(int r, int l, int m) { // helper function returning a line of metarhythm; parameters are: tap interval (right hand), tap interval (left hand), length var s = ""; // start with an empty String for(; m > 0; ) // repeat until the length is reached s += m % r * (m-- % l) < 1 ? '.' : 32; // if at least one of the hands taps, add a dot, otherwise add a space (ASCII code 32 is ' ') return s; // return the constructed line } r -> l -> { // lambda taking two integers in currying syntax and returning a String int a = r, b = l, m; // duplicate the inputs for(; b > 0; b = a % b, a = m) // calculate the GCD of r,l using Euclid's algorithm: m=b; // swap and replace one of the inputs by the remainder of their division; stop once it hits zero m = r * l / a; // calculate the length: LCM of r,l using a=GCD(r,l) return // build and return the output: " " + "-".repeat(m) // first line, m dashes preceded by two spaces + "\nR " + h(m / r, m + 1, m) // second line, create the right-hand rhythm; by setting l = m + 1 for a metarhythm, we ensure there will be no left-hand taps + "\nL " + h(m / l, m + 1, m) // third line, create the left-hand rhythm the same way; also note that we pass the tap interval instead of the number of taps + "\nM " + h(m / r, m / l, m); // fourth line, create the actual metarhythm } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~187~~ ~~185~~ ~~183~~ ~~174~~ ~~166~~ ~~156~~ ~~148~~ ~~147~~ 145 bytes Uses `-` as the tap character ``` a,b=r,l=input() while b:a,b=b,a%b w=r*l/a for x,y,z in zip(' RLM',(w,r,l,r),(w,r,l,l)):print x,''.join('- '[i%(w/y)!=0<i%(w/z)]for i in range(w)) ``` [Try it online!](https://tio.run/##NY5RC4IwFIXf769YgmyTW4YmhbSn6q0Ieo0etrBcyJRhTP3zNoUePjhczv04Td@WtUnGw/V4EkEQjBKVsFgJbZpvyzi4UlcFUfl0VyhDBU7YqIolvGpLOuxxINqQQTeMktv5QpE59AK0/J8qzvPGatP6OqWrT60No0tC7zpkLu75Qqz3cxz4Y5LqSWileRfMcT7Or@C3ARRd8STT1CgbU0xgg6kn82w9O/gB "Python 2 – Try It Online") --- Saved: * -2 bytes, thanks to Jonathan Frech [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~85~~ ~~80~~ 78 bytes *-2 bytes thanks to Jo King.* ``` {«' 'R L M»Z~'-'x($!=[lcm] @_),|(@_.=map:{' '~(0~' 'x$!/$_-1)x$_}),[~|] @_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/@tBqdQUF9SAFHwXfQ7uj6tR11Ss0VBRto3OSc2MVHOI1dWo0HOL1bHMTC6yq1RXU6zQM6oBUhYqivkq8rqFmhUp8raZOdF0NSHHt/7T8IgUNYx0FI00dBQ0THQVjKG0Kpc2htIWmQjUXp15xYqUCSEuahkq8pjUXJ5CvAaRr/wMA "Perl 6 – Try It Online") Returns a list of four lines. [Answer] # [Python 2](https://docs.python.org/2/), ~~185 228 223 234~~ 249 bytes ``` def f(r,l): c='.';d=' ';M,R,L=[r*l*[d]for _ in d*3] for i in range(r*l): if i%r<1:L[i]=M[i]=c if i%l<1:R[i]=M[i]=c if r<R.count(c)and l<L.count(c):R[i]=L[i]=M[i]=d;break print d,i*'-','\nR',''.join(R),'\nL',''.join(L),'\nM',''.join(M) ``` [Try it online!](https://tio.run/##VYyxCsIwFEX3fsVb5CUhFqxba/8gWbLWDoKNPmmSErr49TERanG5XM7h3uW9PoNvUrpPFiyLcuZtBa6fRex0PyDgKFxnfk1trQIbIhCQh3jzj4m5MgSyQId4ObVqoLHXJbDGTcxZmH@xRPJrvpRO4BElXr3JifUrkGeGF6B2oL5A70DzZFkjzzx9AA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` æl/Ḷ%Ɱµa/ṭ=0ị⁾. Z”-;ⱮZ“ RLM”żK€Y ``` [Try it online!](https://tio.run/##y0rNyan8///wshz9hzu2qT7auO7Q1kT9hzvX2ho83N39qHGfnkLUo4a5utZAGSBjjkKQjy@Qf3SP96OmNZH///831TEBAA "Jelly – Try It Online") Takes input as a list `[L,R]`. ``` æl/ Get LCM of this list. Ḷ Range [0..LCM-1] %Ɱ Modulo by-each-right (implicitly the input, [L,R]): [[0%L ... (LCM-1)%L], [0%R ... (LCM-1)%R]] µ Take this pair of lists, and: a/ṭ Append their pairwise AND to the pair. =0 Is zero? Now we have a result like: [[1 0 0 1 0 0 1 0 0 1 0 0 1 0 0] [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0] [1 0 0 1 0 1 1 0 0 1 1 0 1 0 0]] ị⁾. Convert this into dots and spaces. Z”-;ⱮZ Transpose, prepend a dash to each, transpose. Now we have ['---------------' '. . . . . ' '. . . ' '. . .. .. . '] “ RLM”ż zip(' RLM', this) K€ Join each by spaces. Y Join the whole thing by newlines. ``` [Answer] # C (gcc), 204 bytes ``` p(s){printf(s);} g(a,b){a=b?g(b,a%b):a;} h(r,l,m){for(;m;)p(m%r*(m--%l)?" ":".");} f(r,l,m,i){m=r*l/g(r,l);p(" ");for(i=m;i-->0;)p("-");p("\nR ");h(m/r,m+1,m);p("\nL ");h(m/l,m+1,m);p("\nM ");h(m/r,m/l,m);} ``` Port of my Java [answer](https://codegolf.stackexchange.com/a/169715/79343). Call with `f(number_of_right_hand_taps, number_of_left_hand_taps)`. Try it online [here](https://tio.run/##ZY9BawIxEIXP7q8IAwszOqmtChbD1j9QLz33kl3IGtjZhmhPwd@@TSqC4u3xvTfvMZ3uu26aAp4ohejHs8vKXKoeLbeUbNPue2zZ1i3tbOZHjDywUHI/EY0YCih1nKNoXQ@0BwU7eIHS4K5J9pSkifNh2RdAJiAolROlwDdivNYfr6UHNPy73@NX8Y8oy8iyeMtrV/x5w8MDPtyli5XHp/yIEutHJJWqmcMVqzWZahZ@zycEKNLhmtXqCW5YbZ9gPn/P6jL9AQ). [Answer] # Pyth, 53 bytes ``` j.b+NYc" L R M "2++*\-J/*FQiFQKm*d+N*\ t/JdQsmeSd.TK ``` Definitely room to golf. Will do so when I have time. [Try it here](http://pyth.herokuapp.com/?code=j.b%2BNYc%22%20%20L%20R%20M%20%222%2B%2B%2A%5C-J%2F%2AFQiFQKm%2Ad%2BN%2A%5C%20t%2FJdQsmeSd.TK&input=4%2C%207&debug=0) ### Explanation ``` j.b+NYc" L R M "2++*\-J/*FQiFQKm*d+N*\ t/JdQsmeSd.TK J/*FQiFQ Get the LCM. *\- Take that many '-'s. Km*d+N*\ t/dJQ Fill in the taps. smeSd.TK Get the metarhythm. ++ Append them all. c" L R M "2 Get the prefixes. .b+NY Prepend the prefixes. j Join with newlines. ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 254 bytes --- **Golfed** [Try it online!](https://tio.run/##ZVFba8IwGH1ef8VHUJrQ2Dl1F@xSHwaDQctG@7CH2odSoxZK3JLIHrL8dpeKbsUFcuFcck7aWo1q1Rye96J@fBF6OqFw2nItG7GJYQ3sgCVtCYtNIzQo1sZy0c4lzZmKvrZNy3E@bOPxdz6U8ZjkgYPV0QyfuHNUxEiu91IgFL5Vq6zZbDXOryvqhz4JM/7RVjXHKETUzT@F48EnJLKnyzL26VyS0OR4aAlNGUKRYvm5xWjk8lOGsyIvg8Qt8d1s4e6cI0AkSKNTC4Beigom1B/5JBigpcjAZHYpEjCJ21IwqUWRPUSed/woRVmUHrihudJPleIKGAj@Bb8sGO@qA4rSwJTCBCz9A2YUppfA7SVwfwk8dEAXal2N9U7yqt7ic@JvE2hErxVxPTrL006oXcvDd9lojmGAnO9jr@eQzcGc5cW4tBSSPnJTuue/7nWnXQqzxj0thZ6MWAQk@p@VNML90aVAjrSed@YyXq2OFIkOPw "C# (Visual C# Interactive Compiler) – Try It Online") ``` (r,l)=>{int s=l>r?l:r,S=s;while(S%l>0|S%r>0)S+=s;string q(int a){return"".PadRight(S/a,'.').Replace(".",".".PadRight(a,' '));}string R=q(S/r),L=q(S/l),M="";s=S;while(S-->0)M=(R[S]+L[S]>64?".":" ")+M;return" ".PadRight(s+2,'-')+$"\nR {R}\nL {L}\nM {M}";} ``` --- **Ungolfed** ``` ( r, l ) => { int s = l > r ? l : r, S = s; while( S % l > 0 | S % r > 0 ) S += s; string q( int a ) { return "".PadRight( S / a, '.' ).Replace( ".", ".".PadRight( a, ' ' ) ); } string R = q( S / r ), L = q( S / l ), M = ""; s = S; while( S-- > 0 ) M = ( R[ S ] + L[ S ] > 64 ? "." : " " ) + M; return " ".PadRight( s + 2, '-') + $"\nR {R}\nL {L}\nM {M}"; } ``` --- **Full code** ``` Func<Int32, Int32, String> f = ( r, l ) => { int s = l > r ? l : r, S = s; while( S % l > 0 | S % r > 0 ) S += s; string q( int a ) { return "".PadRight( S / a, '.' ).Replace( ".", ".".PadRight( a, ' ' ) ); } string R = q( S / r ), L = q( S / l ), M = ""; s = S; while( S-- > 0 ) M = ( R[ S ] + L[ S ] > 64 ? "." : " " ) + M; return " ".PadRight( s + 2, '-') + $"\nR {R}\nL {L}\nM {M}"; }; Int32[][] testCases = new Int32[][] { new []{ 3, 2 }, new []{ 4, 3 }, new []{ 4, 5 }, new []{ 4, 7 }, new []{ 4, 8 }, }; foreach( Int32[] testCase in testCases ) { Console.Write( $" Input: R: {testCase[0]}, L: {testCase[1]}\nOutput:\n{f(testCase[0], testCase[1])}" ); Console.WriteLine("\n"); } Console.ReadLine(); ``` --- **Releases** * **v1.0** - `254 bytes` - Initial solution. --- **Notes** * None [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔θζW﹪ζη≧⁺θζζ↙≔⮌Eζ⟦¬﹪×ιθζ¬﹪×ιηζ⟧ζFζ⊞ι⌈ι↓Eζ⭆ι§ .λ←↓RLM ``` [Try it online!](https://tio.run/##bY4xC8IwEIV3f8XR6Q6ii046CS6CkVLdxKFobAJpo01aS/98TGwVBJfj7t7d995F5vXF5Nr7tbWqqPDBoKfV5CmVFoDcXBttsGcgiYDn9@EqU4V0mOrGMhgf0lpVDmPHTStwuTHPaiduLixGciZaUVuBgRKBp71xH/5RlcKiCjCKtFD@iXIQz0SD5c3UEBwhbayMOs87VTYlKvrmeceIytvy4MKyiEO4XrttdRUdJjBLGGgi@mYfc/8gkmzHE1p5f1owmJ/9tNUv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔θζW﹪ζη≧⁺θζ ``` Calculate the LCM of the inputs by taking the first multiple of `R` that's divisible by `L`. ``` ζ↙ ``` Print the LCM, which automatically outputs the necessary row of `-`s. Then move to print the rhythm from right to left. ``` ≔⮌Eζ⟦¬﹪×ιθζ¬﹪×ιηζ⟧ζ ``` Loop over the numbers from the LCM down to 0 and create an array of lists representing the beats of the right and left hands. ``` Fζ⊞ι⌈ι ``` Loop over the beats and add the metarhythm. ``` ↓Eζ⭆ι§ .λ ``` Print the reversed beats downwards, but as this is an array they end up leftwards. ``` ←↓RLM ``` Print the header. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~130~~ 126 bytes ``` ->*a{puts" "+?-*s=a[0].lcm(a[1]) r,l=a.map!{|e|(?.+' '*(s/e-1))*e} [?R,?L,?M].zip(a<<r.gsub(/ /){l[$`.size]}){|e|puts e*" "}} ``` [Try it online!](https://tio.run/##JY3RCoIwGIXvfYq/FbStOSuLArW9QN10OwatWCUYiJsXNffsVnr1cQ6H7zTt9d3fiz4@UO3r1lkEgBYiprbQcql4dXthLVeKRA2rCs1fup74znRY8MUc5hTbxMQrQqgJkRRnJo5MnBT/lDXWed7wh22vOIGE@ErOLtyWH6MC@Rv@Z2AoAhRC74z9pQIkyJStFQO5YemI7YjdiL0CFQ1rbvTtCb5zHQwqNPUuoAzukjqVDV3ovw "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 117 bytes ``` a,b=input();n=a while n%b:n+=a for i in-1,1,2,3:print'_RLM '[i],''.join(' -'[i%2>>m*a%n|i/2>>m*b%n]for m in range(n)) ``` [Try it online!](https://tio.run/##JY3BCoJAFEX38xWDMIzWs3AsCkO/oDZtQ2KUKV/kU8SooH@fXrY4cC8Xzu3fY9OR8c8G704mmXu5OggCb6HKkfrHGEY7yq3476SqjOZcL90gUSLFCSRgIM36AWnU5@P@IPUJS9B6ceuQQi1j7soURTuzij64nGKlqPw5WnbIwdLVhRRFfrII/hc@BSNWkDJrZsNsxRc "Python 2 – Try It Online") [Answer] # Pyth, 49 bytes ``` J/*FQiFQjC+c2" RLM "ms@L" -"!M++0d*Fdm%Ld/LJQJ ``` Expects input in the form `[r,l]`. Uses `-` to display taps. Try it online [here](https://pyth.herokuapp.com/?code=J%2F%2AFQiFQjC%2Bc2%22%20RLM%20%20%20%20%22ms%40L%22%20-%22%21M%2B%2B0d%2AFdm%25Ld%2FLJQJ&input=%5B2%2C3%5D&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=J%2F%2AFQiFQjC%2Bc2%22%20RLM%20%20%20%20%22ms%40L%22%20-%22%21M%2B%2B0d%2AFdm%25Ld%2FLJQJ&test_suite=1&test_suite_input=%5B3%2C2%5D%0A%5B4%2C3%5D%0A%5B4%2C5%5D%0A%5B4%2C7%5D%0A%5B4%2C8%5D&debug=0). ``` J/*FQiFQjC+c2" RLM "ms@L" -"!M++0d*Fdm%Ld/LJQJ Implicit: Q=eval(input()) /*FQiFQ Compute LCM: (a*b)/(GCD(a,b)) J Store in J m J Map d in [0-LCM) using: /LJQ Get number of beats between taps for each hand %Ld Take d mod each of the above This gives a pair for each beat, with 0 indicating a tap m Map d in the above using: *Fd Multiply each pair (effecively an AND) ++0d Prepend 0 and the original pair !M NOT each element s@L" -" Map [false, true] to [' ', '-'], concatenate strings This gives each column of the output c2" RLM " [' RLM',' '] + Prepend the above to the rest of the output C Transpose j Join on newlines, implicit print ``` [Answer] # [R](https://www.r-project.org/), ~~161~~ ~~149~~ 146 bytes ``` function(a,b){l=numbers::LCM(a,b) d=c(0,' ') cat(' ',strrep('-',l),'\nR ',d[(x<-l:1%%a>0)+1],'\nL ',d[(y<-l:1%%b>0)+1],'\nM ',d[(x&y)+1],sep='')} ``` [Try it online!](https://tio.run/##K/qfa/s/rTQvuSQzP08jUSdJszrHNq80Nym1qNjKysfZFyzGlWKbrGGgo66grsmVnFiioa6goK5TXFJUlFqgoa6rrpOjqaMekxcEFEyJ1qiw0c2xMlRVTbQz0NQ2jAXJ@EBkKqEySQgZX6getUqwSHFqga26umbt/1wNUx1DQ83/AA "R – Try It Online") I definitely feel like there's room for improvement here, but I tried a few different approaches and this is the only one that stuck. ~~Getting rid of the internal function definition would make me quite happy, and I tried a bunch of restructures of the cat() to make it happen.~~ Nevermind, as soon as I posted I realised what I could do. Still definitely some efficiency savings to be found. There are other LCM functions in libraries with shorter names, but TIO has numbers and I considered that more valuable at this point. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 197 bytes ``` int f(int a,int b){std::string t=" ",l="\nL ",r="\nR ",m="\nM ";int c=-1,o,p=0;for(;++p%a||p%b;);for(;o=++c<p;t+="-")l+=a*c%p&&++o?" ":".",r+=b*c%p&&++o?" ":".",m+=o-3?".":" ";std::cout<<t+l+r+m;} ``` [Try it online!](https://tio.run/##jY@/bsMgEIf3PMWJypHdw1Uat2ploHmBduncBWM7smT@iOApybO74ERdupjh9N2P706gnCuPSs0Pg1Hj1HbAB3sKvpP6Yx5MgD5PVdJUm@J8Cm1dx/vBHCEIAkDoKMiP@YzgE3xH0Am@gLA0pET5TC11Ysd663OG6DJ5ubisYcUtsQJRcccCClKSYkQhH1XmtltEeyBAavIUl6No/qcahS2rQ8Q6Rmx5nbJT4DzgiB41uy6/0HIweQHnDcTT5xXdF2zhvwng/NZ0ph3Z3Xuh1UrvdaX3ttJ7v3u@C5M3sGOb6/wL "C++ (gcc) – Try It Online") ]
[Question] [ When you search something on google, within the results page, the user can see green links, for the first page of results. In the shortest form possible, in bytes, using any language, display those links to stdout in the form of a list. Here is an example, for the first results of the stack exchange query : [![A screen capture](https://i.stack.imgur.com/upTdZ.jpg)](https://i.stack.imgur.com/upTdZ.jpg) ### Input : you choose : the URL (`www.google.com/search?q=stackexchange&ie=utf-8&oe=utf-8`) or just `stackexchange` ### Output : ``` french.stackexchange.com/, stackoverflow.com/, fr.wikipedia.org/wiki/Stack_Exchange_Network, en.wikipedia.org/wiki/Stack_Exchange,... ``` ### Rules : * You may use URL shorteners or other search tools/APIs as long as the results would be the same as searching <https://www.google.com>. * It's ok if your program has side effects like opening a web browser so the cryptic Google html/js pages can be read as they are rendered. * You may use browser plugins, userscripts... * If you can't use stdout, print it to the screen with, eg. a popup or javascript alert ! * You don't need the ending / or the starting http(s):// * You should not show any other link * Shortest code wins ! * Good luck ! EDIT : This golf ends the 07/08/15. [Answer] # Bash + grep + lynx, 38 Since we can open a web browser, then I will use `lynx`: ``` lynx -dump $1|grep -Po '(?<=d:)[^&]+' ``` (Thanks to @manatwork for `grep` usage instead of `sed`) We pass in the whole URL in as a parameter: ``` $ ./gr.sh "www.google.com/search?q=stackexchange&ie=utf-8&oe=utf-8" http://stackexchange.com/ https://en.wikipedia.org/wiki/Stack_Exchange https://twitter.com/stackexchange https://play.google.com/store/apps/details?id=com.stackexchange.marvin https://github.com/StackExchange/StackExchange.Redis https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md https://www.crunchbase.com/organization/stack-exchange $ ``` Which gives the same list as: [![enter image description here](https://i.stack.imgur.com/TJ0a6.png)](https://i.stack.imgur.com/TJ0a6.png) [Answer] # Ruby, ~~91~~ 77 bytes ``` require'open-uri';open(gets).read.scan(/ed:(.*?)\+/){|x|puts URI.decode x[0]} ``` ~~Would've been shorter without all the `require`s. ARGH!!!~~ **EDIT**: So, turns out, I *don't* need the second require! Thanks to @manatwork for pointing that out. Older version (with the useless `require`): ``` require'open-uri';require 'uri';open(gets).read.scan(/ed:(.*?)\+/){|x|puts URI.decode x[0]} ``` [Answer] **Wolfram Language (Mathematica), 135** ``` StringJoin/@(Cases[URLExecute["www.google.com/search",{"q"->#},"XMLObject"],XMLElement["cite",_,l_]:>l,-1]/.XMLElement["b",_,{s_}]:>s)& ``` more readable: ``` StringJoin/@(Cases[ URLExecute["www.google.com/search",{"q"->#},"XMLObject"], XMLElement["cite",_,l_]:>l,-1] /. XMLElement["b",_,{s_}]:>s) ``` [Answer] # Python 3, 141 bytes Nowhere near Digital Trauma's answer, but it was fun to work out the regex :D ``` import re print('\n'.join(map(lambda x:x[3:],re.findall('te>http[s]?://\w+\.[a-z]+[](/a-z\.)?]+',__import__("requests").get(input()).text)))) ``` For input `http://www.google.com/search?q=stackexchange&ie=utf-8&oe=utf-8` the program outputs: ``` https://en.wikipedia.org/wiki/ https://twitter.com/ https://play.google.com/store/apps/details?id... https://www.crunchbase.com/organization/ https://www.facebook.com/ https://github.com/ ``` [Implements grc's tip](https://codegolf.stackexchange.com/a/54369/30525) [Answer] # Factor, 31 bytes There happens to be a library for this. ``` [ google-search [ url>> ] map ] ``` ]
[Question] [ *inspired by [Longest Increasing Substring](https://codegolf.stackexchange.com/q/173586/78410)* ## Task Given a list of non-negative integers, output the length of its longest alternating subsequence. An *alternating sequence* is a sequence of numbers which alternates between strictly increasing and strictly decreasing. `[]`, `[999]`, `[9, 1]`, and `[0, 5, 0, 3, 2, 4]` are examples of an alternating sequence, while `[0, 0]` and `[1, 3, 5]` are not. A mathematical definition: A sequence \$A = a\_1, a\_2, \cdots, a\_n\$ is alternating if * \$a\_k \ne a\_{k+1}\$ for \$k = 1, 2, \cdots, n-1\$, and * \$a\_k < a\_{k+1} \Rightarrow a\_{k+1} > a\_{k+2} \$ and \$a\_k > a\_{k+1} \Rightarrow a\_{k+1} < a\_{k+2}\$ for \$k = 1, 2, \cdots, n-2\$. If the input is `[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]`, the longest alternating subsequence is `[3, 1, 4, 1, 9, 2, 6, 3, 5]` and its length is 9. Note that the *subsequence* does not need to be contiguous. ## Scoring The score of your answer is calculated as follows: * Treat your source code as a list of bytes (or, if your language uses a non-256-char custom character set, the list of character codes within the character set). + If your language supports multiple encodings, you may use the one that gives the best score. However, the score and the code size must be calculated using the same encoding. * Give it as input to your own program, and the output is your score. The lowest score wins. Tiebreaker is shorter code in bytes. ## Test cases ``` [] => 0 [1] => 1 [1, 1] => 1 [9, 9, 9, 9, 9, 9, 9] => 1 [5, 10] => 2 [0, 1, 2] => 2 [5, 10, 10, 5] => 3 [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] => 9 [1, 2, 2, 2, 3, 3, 4, 4, 5, 6] => 2 [2, 2, 1, 2, 5, 6, 6, 5] => 4 ``` [Answer] # [Python 3](https://docs.python.org/3.8/), score 16, \$6.6 \times 10^{2073} \$ bytes ``` exec(b"".fromhex(str(len(" ")))) ``` [Try it online!](https://tio.run/##3VbbboMwDH3nK6zuoamGKnLjUolJ3W9U08S6tKBRioB129d3SRB7mBIJa30aCuBjHznGNlbar6E8Nzxtu@sdlMX@DWrVwHCGY3VRMJTK4ONQwvlgUT90VXM0qG@LveqDQNvzuji9vBbwvIllksYy5ixlCTNvyWTCjcwpjzjT@Lc@5tShNezUoc944mFnTnbqYUezfXNn1L74BBdONkV8u0B65gjP0ql15U56c5c692POjFKnliMqS5218tXQX60MsSdz@hbeSBiKnc7OFKYy7qzi@hHXY8ITs5jdeSbT8T/KKY4tZseBnZHzp0qGquz8mgjPhKU36UaBmCoUNY@jP2dO3uAPwvQ@RcYhZseByYbvS0ZtwrKr@lR78rJYrA/d@VSqT6KPEkQfHsgCFit9XT/KqlZANwFsw8e8atr3gazWfVtXA1lC/gDLVQA15KAuRU22GjQaVM1AHrXcqV6j@wOpNWg7o25Cow1HUw4a1qvr7sm4ioIdtQLVQgg/chbC7zWZpKZFFrBgF2kQApugtY23tDoe7LilCPuU1hULIbYyn2iZ3Z1Ni9sl7NK0eHI/WkemtE7iyYP4Bg "Python 3.8 (pre-release) – Try It Online") The string `" "` above should actually be the number of spaces below, about \$6.6 \times 10^{2073} \$, but somehow Stack Exchange won't let me post the whole string and TIO won't run it. ``` 6578656328272563252573272531303225272563252573272536312527256325257327253130382527256325257327253937252725632525732725313039252725632525732725393825272563252573272531303025272563252573272539372527256325257327253332252725632525732725313038252725632525732725343425272563252573272531313225272563252573272536312527256325257327253438252725632525732725343425272563252573272531313325272563252573272536312527256325257327253435252725632525732725343925272563252573272535382527256325257327253130382527256325257327253632252725632525732725393125272563252573272539332527256325257327253937252725632525732725313130252725632525732725313030252725632525732725333225272563252573272531303925272563252573272539372527256325257327253132302527256325257327253430252725632525732725313032252725632525732725343025272563252573272531303825272563252573272539312527256325257327253439252725632525732725353825272563252573272539332527256325257327253434252725632525732725313132252725632525732725343425272563252573272531313325272563252573272534312527256325257327253434252725632525732725343525272563252573272531323625272563252573272531303225272563252573272534302527256325257327253130382527256325257327253931252725632525732725343925272563252573272535382527256325257327253933252725632525732725343425272563252573272531313325272563252573272534342527256325257327253131342527256325257327253538252725632525732725363125272563252573272531303825272563252573272539312527256325257327253438252725632525732725393325272563252573272534312527256325257327253432252725632525732725343025272563252573272534302527256325257327253931252725632525732725313132252725632525732725343425272563252573272531313425272563252573272539332527256325257327253931252725632525732725313132252725632525732725363025272563252573272534382527256325257327253933252725632525732725343525272563252573272531313325272563252573272534312527256325257327253432252725632525732725343025272563252573272531313325272563252573272534352527256325257327253131342527256325257327253431252725632525732725363025272563252573272534382527256325257327253431252725632525732725343125272729 ``` Repeating a character many times in a row doesn't affect the score because an alternating subsequence can't contain two consecutive equal values. So, the game becomes to write a low-scoring wrapper that decodes a huge string of spaces (or any character) into arbitrary code and executes it. The ginormous number above corresponds to the following moderately-golfed code for the length of the longest alternating subsequence. Being an exponential-time algorithm, it's too slow to actually compute the result for the code itself with spaces de-duplicated. **91 bytes** ``` f=lambda l,p=0,q=-1:l>[]and max(f(l[1:],p,q),-~f(l[1:],q,r:=l[0])*(([p,r][p<0]-q)*(q-r)<0)) ``` [Try it online!](https://tio.run/##XY3NasMwEITvfoq9RWrXRf4lMVEgeQ2hg0sSYlBUWXH/Ln11d71GPRRGYr7dYTZ8T7c3X21DnOerdv399dyDw6AVjjovOncwtvdnuPdf4iqcKTqLAUeJ@U/CEWOnnVFWPglhAkZrwl7ZfCQe8yj3Ssr58za4CxRdBkc86cGH90nIl0dwwyQ2oA@wkRk40HD56J04EniCwU/iRD5eHkTPdJEgxGXscZniutJA6ORs7FKlMlOwKcgg/Pkdwn@lVUMxxVBmRhEglAl5t76GZ1VmKo7U/DdcVSK07KsU2/H1Mqli1SyKtal@3a7Jhkva1FD/Ag "Python 3.8 (pre-release) – Try It Online") The wrapper ``` exec(b"".fromhex(str(len(" ")))) ``` takes the length of a string of spaces, converts it to a hexadecimal string, interprets pairs of hex values as base 256 ASCII to convert it to a bytestring, and executes the result. Its longest alternating subsequence has length 16, as can be checked by an efficient implementation like [the last one here](https://www.techiedelight.com/longest-alternating-subsequence/), compared to 66 for the direct 91-byte code. The filler character can be replaced with any low-ASCII character without affecting the score, and single versus double quotes has no effect. Actually, you might notice that the length is converted to a base-10 string with `str()`, not hexadecimal. This byte-save makes the wrapper have fewer alternations, at the cost of only being able to generate code of ASCII values whose hex representation have no letters `a-f`. Luckily, this still allows all of `exc('%0)`, which already [suffice to run arbitrary Python 3 code, as shown by kzh](https://codegolf.stackexchange.com/a/250500/20260). We could start by converting our payload code to this restricted format, but the result is very long -- it won't fit in my computer's memory. So, we "golf" this by taking advantage of also having access to all digits `0-9` and the letter `s`. A string, for example `ABC` with ASCII values `[65,66,67]`, is converted to: ``` exec('%c%%s'%65%'%c%%s'%66%'%c%%s'%67%'') ``` which uses string formatting with `%s` to perform concatenation in place of the banned `+`. This format only gives a linear blow-up with 91 bytes becoming 1037, though this could surely be improved. Amusingly, I thought that the Sep 2022 [breaking change to Python string-converting large numbers](https://lwn.net/Articles/907572/) would make this overall submission invalid in up-to-date versions of Python without using a command-line flag -- that is, if we're pretending that code of length \$6.6 \times 10^{2073} \$ can run at all. But, the 2074 digits of the number of spaces falls under the cutoff of 4300 past which `str` now errors out. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~13~~ 14 bytes, score ~~9~~ 6 *Edit: +2 bytes to fix bug that counted repeated identical elements (thanks to Bubbler for spotting)* *Edit2: changed approach for +1 byte but reducing score by 3* ``` →OmöËεgfIẊo±-Ṗ ``` [Try it online!](https://tio.run/##yygtzv7//1HbJP/cw9sOd5/bmp7m@XBXV/6hjboPd077//9/tLGOoY4JEJvqWOoY6ZgBaWMd01gA "Husk – Try It Online") The codepoints of the program from the [Husk code page](https://github.com/barbuz/Husk/wiki/Codepage) are: `[8,80,110,248,239,157,104,103,74,212,112,22,46,207]`, giving a longest alternating subsequence of length 6 ([try it](https://tio.run/##yygtzv7//1HbJP/cw9sOd5/bmp7m@XBXV/6hjboPd077//9/tIWOhYGOoaGBjpGJhY6RsaWOoam5jqGBCRAb65ib6BgZGgGljXSMjHRMzHSMDMxjAQ)). The codepoints were calculated using [this program](https://tio.run/##FVFXcxJRGH33V0TsJfbeu8YWe8XYk2jEqDF2nd0LWXZZxsQkLliGsIGQKBkDhLJ3QZm5d3F4uvsbvu@P4PpyXs6cOa13cKCv1QogkVHOLUAy62Np9huVz6h8QmUMlXFURlAZRXWCZdqYyeoo1VDKoJRDKYmSiepX1NKoTbE8qgTVLKoJ1FTUkqiZGB1hs7zCY20L/b5Fi5csXbZ8xcpVq9vXrF23fsPGTZu3bN22fcfOXbv37N23/8DBQ4ePHD3WcfzEyVOnO8@cPXf@wsVLl69cvXbd77/RdfPW7Tt3793v7ul98LDvUeBx/5OnzwaeD754@er1m7fv3n9gFSTS/xaEIAkiCSEZQqIgCSNRkWgYVTHqYQSjuhgT4yIuvomESIqUyIgZ8UPkRUHMi6IoibKoCEtURU38cSVXdokbdEOu4oZd1dW8lRhlBTaPchHlEspllCsoWyhTNslS3oBs6u8oK6JRQKOGho2xEJtuZsAiTgSsiGOAlXCSYE06OacOVAIaav4CagCNA00C/Qm2AnYE7I@NanMarKCjg6U7MbAmHBOslJNvVhqeSgY61JwDGgP6BagJNAt2GGwd7OFGjc3wENf5MDf494bF4zzNs3yOl3mN17mFsQgaJiuzLKv6Wq2Wz/u3M@Cxuij1dHd47v0s3@5l8v0D). ``` mö # map over Ṗ # all subsequences of input ËεgfIẊo±- # calculating length if it's an alternating seqeunce, # or returning zero otherwise (see below), O # sort the results, → # and return the last (largest) element. Ẋo # map over all pairs of values ±- # getting the sign of the difference, fI # remove zeros, g # and group adjacent equal values; Ë # now, if all the groups ε # have a length of at most 1 # return the length +1 # (this is the length of the alternating subsequence) # otherwise return zero ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), score: 7, (15 bytes) ``` +!!Qlr8-._M.+QZ ``` [Try it online!](https://tio.run/##K6gsyfj/X1tRMTCnyEJXL95XTzsw6v//aBNjHQVjKLYw1FEwNLAAEoYmOgqmZjoKJqZADKQtgbS5OYRtAlVpaRALAA "Pyth – Try It Online") And as an added bonus it runs in `O(n)` time. ### explanation ``` .+Q difference between each pair of elements in the input ._M map list to the sign of the elements - Z remove all zeros lr8 number of sequences of repeated elements +!!Q add 1 if input is non-empty ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~13~~ ~~12~~ 7 (~~23~~ ~~21~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` ¥.±Igª¾Kγg ``` -1 score (and -2 bytes) taking inspiration from [*@DominicVanEssen*'s Husk answer](https://codegolf.stackexchange.com/a/252709/52210). -5 score (and -11 bytes) by porting [*@CursorCoercer*'s Pyth answer](https://codegolf.stackexchange.com/a/252725/52210), so make sure to upvote him/her as well! [Try it online](https://tio.run/##yy9OTMpM/f//0FK9Qxs90w@tOrTP@9zm9P//o411FAx1FEzApKmOgqWOgpGOghmYDZQyjQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Q0v1Dm2sTD@06tA@73Ob0//r/I@OjtWJNgRhHRBpqYMEgXxTHUMDIGWgY6hjBOWCkCmQbQwUMwFiU6BSIx0zIG0MFgeqBENjIDQBQlMdM6AoSAQkA@SB1MbGAgA). The program has [the following bytes](https://tio.run/##ASAA3/9vc2FiaWX//8W@xIZJU2v//8KlLsKxSWfCqsK@S86zZw), and using this [as input in my own program](https://tio.run/##yy9OTMpM/f//0FK9Qxs90w@tOrTP@9zm9P//ow3NTHUUTMx0FAzNzXUUzI2BDAMQYW4AJCyBhDlIHiwaCwA) results in `7` as its score. **Explanation:** `¾` is used instead of `0` and `γ` is used instead of `Ô` to improve the score. `¥` could alternatively be `ü-`; `I` could be `¹` or `s`; `ª` could be `š`; and `.±` could be `0.S`, but with any of those changes the score will remain the same, and combinations of some of these changes will also retain the same score, or even increase it. ``` ¥ # Get the deltas/forward-difference of the (implicit) input-list .± # Get the signum of each (0 if 0; -1 if <0; 1 if >0) Ig # Push the input-length ª # Append it to the list ¾K # Remove all 0s from the list γ # Split the list into groups of equal adjacent items g # Get the length to get the amount of groups # (which is output implicitly as result) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)), score 4 ``` I¹ƇṠŻạƝTL+JṂ ``` A monadic Link that accepts a list of non-negative integers and yields the length of the longest alternating subsequence. **[Try it online!](https://tio.run/##y0rNyan8/9/z0M5j7Q93Lji6@@Guhcfmhvhoez3c2fT///9oAx1DHSMdEx0LIDQGYoNYAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/z0M5j7Q93Lji6@@Guhcfmhvhoez3c2fT/6KSHO2foHG7PetQwR8HWTuFRw1zNyP//o6NjuXSiDcGEjgKYttRRQEcgYVOgtAGIYQBk6CgYwcUg2BTENwZLmYBJU7BWIx0FMzDbGKrEECwGQcZgZAJGQCVmIHmIDESVKVizGVhnLAA "Jelly – Try It Online"). The bytes are: `74 130 145 206 211 212 151 85 77 44 75 180` [See it score itself](https://tio.run/##ASkA1v9qZWxsef//w5hKaeKxrnZA////ScK5xofhuaDFu@G6ocadVEwrSuG5gg "Jelly – Try It Online") ### How? An alternating subsequence of maximal length can always be formed by taking the first element (if one exists) and appending the peaks and troughs, so the code calculates the length of that subsequence. ``` I¹ƇṠŻạƝTL+JṂ - Link: list of integers, A e.g. [2,2,1,2,5,6,6,5] OR [4] OR [] I - incremental differences (of A) [0,-1,1,3,1,0,-1] [] [] Ƈ - keep those for which: ¹ - no-op [-1,1,3,1,-1] [] [] Ṡ - sign [-1,1,1,1,-1] [] [] Ż - prepend a zero [0,-1,1,1,1,-1] [0] [0] Ɲ - for neighbours: ạ - absolute difference [1,2,0,0,2] [] [] T - truthy indices [1,2,5] [] [] L - length 3 0 0 J - range of length (of A) [1,2,3,4,5,6,7,8] [1] [] + - add (vectorises) [4,5,6,7,8,9,10,11] [1] [] Ṃ - minimum (empty list yields 0) 4 1 0 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), score 4, 8 bytes ``` ¯±ꜝĠL$ß› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqFgID0+IGAvdnbDuErin5FoREQiLCLCr8Kx6pydxKBMJMOf4oC6IiwiOm5oYCwgYGrDuEJgIDw9IGBwSlxcIEokbnQ9W1xc4pyFfFxc4p2MXUosIiwiW10gPT4gMFxuWzFdID0+IDFcblsxLCAxXSA9PiAxXG5bOSwgOSwgOSwgOSwgOSwgOSwgOV0gPT4gMVxuWzUsIDEwXSA9PiAyXG5bMCwgMSwgMl0gPT4gMlxuWzUsIDEwLCAxMCwgNV0gPT4gM1xuWzMsIDEsIDQsIDEsIDUsIDksIDIsIDYsIDUsIDMsIDVdID0+IDlcblsxLCAyLCAyLCAyLCAzLCAzLCA0LCA0LCA1LCA2XSA9PiAyXG5bMiwgMiwgMSwgMiwgNSwgNiwgNiwgNV0gPT4gNCJd) Port of CursorCoercer's Pyth answer, so upvote that! The bytes are `[212, 213, 222, 189, 76, 36, 14, 131]`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), score: 12 (18 bytes) ``` ⊇L{s₂ᶠ≠ᵐ}-ᵐṡᵐ↰₁∧Ll ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu0918aOmpofbFjzqXPBw64RaXSDxcOdCIPmobcOjpsZHHct9cv7/jzbWUTDUUTABk6Y6CpY6CkY6CmZgNlDKNPZ/FAA "Brachylog – Try It Online") [This scores 12 according to @Arnauld’s deleted JS answer](https://tio.run/##NYzdDoIgGIZvhUOoTwLKJDf0CroC5wEztZoJC8c66N4JnJ28e5/n@3lqr133ftglm82tD2FQuPFAKdUtOLBEVfzg66te7vSlP3jAetWAbaY82blKsa9VitWs5Ps0teAJKVnozOzM1NPJjPGqkYCKMyAujjF4ntolRi4AiSKVRCL6U76RYPLv1/VE2xMmW0LCDw), it times out on my own code. This code, according to [Brachylog’s code page](https://github.com/JCumin/Brachylog/wiki/Code-page), is the following string of char codes / integers: ``` [08, 4C, 7B, 73, 81, 98, 1B, 9F, 7D, 2D, 9F, D0, 9F, 0F, 80, 01, 4C, 6C] [8, 76, 123, 115, 129, 152, 27, 159, 125, 45, 159, 208, 159, 15, 128, 1, 76, 108] ``` ### Explanation ``` ⊇L L is a subset of the input L{s₂ᶠ≠ᵐ} Get all contiguous sublists of 2 elements, which must be different -ᵐṡᵐ Compute the signs of the subtraction of these sublists ↰₁ Get all contiguous sublists of 2 elements, which must be different ∧Ll Output the length of L ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~9~~ 10.5 bytes (21 nibbles), score ~~7~~ 6 *Edit: +1.5 bytes but -1 score from fixing potential bug with empty input array, spotted by CursorCoercer* ``` +`$,$,`=|!$>>@~`$-@$* ``` The 10 bytes + 1 half-byte of the [Nibbles](http://golfscript.com/nibbles/index.html) program are `8d 7d 3d b9 99 3c 04 0d 79 43 a` (in decimal `141 125 61 185 153 60 4 13 121 67 10`), giving a longest alternating subsequence of length 6. Note that [Nibbles](http://golfscript.com/nibbles/index.html) pads the saved program with a filler `6` nibble at the end for odd numbers of nibbles: this is not counted in the bytes of the program. ``` +`$,$,`=|!$>>@~`$-@$* ! # zip together $ # the input >>@ # and the input without its first element ~ # using the combined function -$@ # subtract arg2 from arg1 `$ # and get the sign | * # filter to keep only nonzero elements `= # and combine adjacent equal elements , # now get the length of this + # and add `$ # 1 if non-zero ,$ # the length of the input ``` [![enter image description here](https://i.stack.imgur.com/K7myv.png)](https://i.stack.imgur.com/K7myv.png) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes, score ~~28~~ 24 ``` ≔¬¬θεFε«≔⁰ζ≔§θζηFθ«≔⁻›ηκ›κηδ≔κη¿∧⁻ζδδ«≔δζ≦⊕ε»»»Iε ``` [Try it online!](https://tio.run/##XU/LasMwEDzLX6GjDC4o4LY2OZkcQg4pvYccZGldG6dyLavFpOTbXethJAraQTs7M9Lylik@sNuyVNPUfUjyNmhbY5pmGNJ90gwKE0jxb4K8hGb4vg62ttInKWAmo6Ez3JqRNY3WtMnOnfyeyFEB06BIm@F@FW9tb3xrL4x5c/Q@DHUNJpUUPuJuZKZc/KYW/lcIndmX506SK/gEqUG4ZRB6JOt5JO@qk5oc2KTX3dL9slwudC54hunMdgEbi/BskL@EOysMOn1NrZIFhuXB63goQoLj4wQmbA4EJdQRU0d8HlwxXzcG6S6k@XfzgPGLjnGa8tUij7Yr/yMv3fR6XZ5@bn8 "Charcoal – Try It Online") Link is to verbose version of code and includes the program's byte sequences using Charcoal's code page as sample input. Explanation: ``` ≔¬¬θε ``` Start with a sequence of length `1` unless the input is empty. ``` Fε« ``` Don't try to measure the length of the sequence if the input is empty. ``` ≔⁰ζ ``` Start with there not being a direction yet. ``` ≔§θζη ``` Start with a copy of the first element of the sequence. (This uses the variable I just set to `0` because this avoids a double alternation.) ``` Fθ« ``` Loop over the elements of the sequence. ``` ≔⁻›ηκ›κηδ ``` Calculate the direction between the previous and current element. ``` ≔κη ``` Save the current element as the previous element. ``` ¿∧⁻ζδδ« ``` If the direction is nonzero and has changed from the previous direction (tested in reverse order to avoid a double alternation), then... ``` ≔δζ ``` ... saved the new direction, and... ``` ≦⊕ε ``` ... increment the sequence length. ``` »»»Iε ``` Output the final sequence length. The program will also work on string input (using the Unicode code points of the characters); the rearrangement of the condition actually avoided four alternations so its score is now ~~32~~ 28 when measured this way. I looked into the possibility of renaming the variables but as far as I can tell my naming scheme was already optimal. ]
[Question] [ A perfect number is a positive integer whose sum of divisors (except itself) is equal to itself. E.g. 6 (1 + 2 + 3 = 6) and 28 (1 + 2 + 4 + 7 + 14 = 28) are perfect. A **sublime number** (OEIS [A081357](http://oeis.org/A081357)) is a positive integer whose count and sum of divisors (including itself) are both perfect. E.g. 12 is a sublime number because: * the divisors of 12 are 1, 2, 3, 4, 6, 12 * the count of divisors is 6 (perfect) * the sum of divisors is 28 (perfect) The next smallest known sublime number is ``` 6086555670238378989670371734243169622657830773351885970528324860512791691264 ``` and these two numbers are the only known sublime numbers as of 2022. The necessary and sufficient conditions for even sublime numbers have been found [in this paper (pdf)](https://web.archive.org/web/20200714113410/http://mathematicstoday.org/archives/V32_2016_5.pdf), but it remains unknown whether odd sublime numbers exist. The paper outlines the "algorithm" to find even sublime numbers: > > Suppose \$p\$ is a prime with the following properties, > > > * \$q = 2^p − 1\$ is a prime. > * \$2^q − 1\$ is a prime. > * \$q − 1\$ can be partitioned into distinct primes \$l\_1, \cdots , l\_{p−1}\$ such that \$m\_i = 2^{l\_i} − 1\$ are also prime for all \$i\$. > > > Then \$n = 2^{q−1} ( \prod{m\_i} )\$ is a sublime number. > > > This heavily relies on [Mersenne primes](https://en.wikipedia.org/wiki/Mersenne_prime), which are primes in the form of \$2^n-1\$. Let's define *Mersenne exponents* be the values of \$n\$ such that \$2^n-1\$ is prime. The list of known Mersenne exponents can be found [on this Wikipedia page](https://en.wikipedia.org/wiki/List_of_Mersenne_primes_and_perfect_numbers); it starts with ``` 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, ... ``` and only around 50 such exponents are known. We can rewrite the algorithm in terms of a known set \$L\$ of Mersenne exponents: > > Loop over \$p \in L\$: > > > * Check that \$q = 2^p - 1 \in L\$. If so, > * For each subset \$\{ l\_i \}\$ of \$L\$ of size \$p-1\$: > + If it sums to \$q-1\$, > + output \$n = 2^{q-1} ( \prod{(2^{l\_i}-1)} )\$ as a sublime number found. > > > Since the list of actual Mersenne exponents is fairly limited, we wouldn't get any more sublime numbers by using this algorithm on it. So let's run it on an arbitrary set of positive integers instead. ## Challenge Given a set of positive integers \$L\$, evaluate all possible outputs (values of \$n\$) the algorithm above would give you. Since \$p=1\$ is kind of an edge case, you may assume that \$L\$ does not contain 1. You may assume that \$L\$ is nonempty. If you take \$L\$ as a list (as opposed to an unordered set), you may assume that it is sorted. You may output the values of \$n\$ in any order, and may output the same value multiple times. If multiple subsets satisfy the condition for a single \$p\$, all possible resulting \$n\$s must be output. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Examples If \$L=\{2,3\}\$, \$p=2\$ satisfies the condition: * 2 is in \$L\$ and \$2^2-1 = 3\$ is also in \$L\$. * A subset of size \$p-1 = 1\$ with sum \$q-1 = 2\$ exists: \$\{2\}\$. * The output is \$n = 2^{3-1} (2^2-1) = 12\$. For \$L = \{2, 3, 4, 7\}\$, \$p=3\$ also does: * 3 is in \$L\$ and \$2^3-1 = 7\$ is also in \$L\$. * A subset of size \$p-1 = 2\$ with sum \$q-1 = 6\$ exists: \$\{2,4\}\$. (\$\{3,3\}\$ does not work since it is just \$\{3\}\$.) * The output is \$n = 2^{7-1} (2^2-1)(2^4-1) = 2880\$. ## Test cases ``` L => [n] [2] => [] [2, 3] => [12] [2, 3, 4] => [12] [2, 3, 4, 7] => [12, 2880] [3, 4, 7] => [] [3, 4, 5, 6, 7, 15] => [218480640 = 2^14(2^3-1)(2^4-1)(2^7-1), 223985664 = 2^14(2^3-1)(2^5-1)(2^6-1)] [2, 3, 5, 7, 15] => [12] (suggested by Jonathan Allan) (actual Mersenne exponents, truncated and 2 removed) [3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607] => [6086555670238378989670371734243169622657830773351885970528324860512791691264 = 2^126(2^3-1)(2^5-1)(2^7-1)(2^19-1)(2^31-1)(2^61-1)] ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 108 bytes ``` l->forsubset(#l,s,setminus([p=#s+1,q=2^p-1],l)||sum(i=1,#s,l[s[i]])-q--||print(prod(i=1,#s,2^l[s[i]]-1)<<q)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9fisJADMavEuzLDGagM1r_7FovMtRF0cpAtNNO-yD0JrJQWGTPtLfZlFYQfJh8v3yTkOT-6_eV-zr77ieH9NHUuVr9EaltXlShOYRTLSLCgAwXd22CsD6NwlRjmZqdVzpDkm0bmotwqcYoINlgXZZJVSrVtr5y11r4qjg-_81urFBabjallOPM7733dBMEagtDF8HkYyI_IRckEaw1GUeDMHsqwvwFEZZ99oYJwoINBJ2MZjKkTLrXNfdrLuK3YtZxbxoOienteMnXDEt23aD_) Takes input as sorted lists. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~119~~ 117 bytes Given a list of integers, prints the pseudo-sublime numbers. ``` L=>L.map(g=(p,_,a,s=L.includes(q=2**p-1)*--q,o=2**q)=>--p?a.map((x,i)=>g(p,_,a.slice(i+1),s-x,o*2**x-o)):s||print(o)) ``` [Try it online!](https://tio.run/##bY7BTsMwEETv@Yo92mFt1YG0hcjhxAVFcOBYRZUVmuCqbZw4VEGUbw@bpgIhcfDOzLPH2q05Gl@01nXiuBxKPWQ6zeTeOFZp5nCNBr3OpD0Uu/fXjWeNjsLQCcVDIRqsx9RwnQrh7s25xnq0BKqpLP3OFhtmrxRHL3qsQyr0oub8zp9OrrWHjlEYklUAsIpyPAvC9a9DuPkTEBZT/ifECHNCCCr@wfEEyKlRb@kXRc/oLMmr2QgjGnE04tkiD/JAlnX7YIo3ZkCn8AnToo8vz0/Sd@QrW34ww3kCJUlyuSfzxYdv "JavaScript (V8) – Try It Online") ### Commented ``` L => // L[] = input list L.map(g = // for each element in L[], ( // invoke the recursive callback function g: p, // p = current element from L[] _, // (ignored index of this element) a, // a[] = input list (truncated on subsequent calls) s = L.includes( // test whether L[] includes: q = 2 ** p - 1 // q = 2 ** p - 1 ) * --q, // decrement q and save either 0 or q in s, // which is our target sum o = 2 ** q // o = output product, initialized to 2 ** q ) => // --p ? // decrement p; if it's not 0: a.map((x, i) => // for each element x at position i in a[]: g( // do a recursive call: p, // new value of p _, // (ignored index) a.slice(i + 1), // remove the i + 1 first elements of a[] s - x, // subtract x from s o * 2 ** x - o // multiply o by 2 ** x - 1 ) // end of recursive call ) // end of inner map() : // else (p = 0): s || print(o) // print o if s = 0 ) // end of outer map() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` L‘2*’ṭƲf’iS{Ṗ ŒPçƇµ;S2*_ṠP) ``` A monadic Link that accepts a list of distinct integers greater than \$1\$ and yields a list of the implied pseudo-sublime numbers. **[Try it online!](https://tio.run/##y0rNyan8/9/nUcMMI61HDTMf7lx7bFMakJEZXP1w5zSuo5MCDi8/1n5oq3WwkVb8w50LAjT///8fbaSjYKyjYKqjYK6jYAhkGYJoS6CgoY6CGRBbANmGBiBBIyBhagQSNjCPBQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/nUcMMI61HDTMf7lx7bFMakJEZXP1w5zSuo5MCDi8/1n5oq3WwkVb8w50LAjT/6xxuPzrp4c4Zj5rWZD1qmKNga6fwqGGuZuT//9HRRrE60UY6xhBSxwRG65gDWTAaJGKqY65jaAoVNNUxQ3DBMsY6hkDSUsfYUMfMUMfCUsfQAMg3MtcxNQKKGJjHxgIA "Jelly – Try It Online"). ### How? ``` L‘2*’ṭƲf’iS{Ṗ - Helper Link, valid subset?: Subset; L L - length of Subset ‘ - increment -> p' Ʋ - last four links as a monad - f(p'): 2 - two * - exponentiate (p') ’ - decrement -> q' ṭ - tack -> [p', q'] f - filter keep only those of [p', q'] which are in L We now have one of: []; [p']; [q']; or [p'=p, q'=q] ’ - decrement -> F (e.g. F=[p-1, q-1]) { - using left argument, Subset: S - sum i - first 1-indexed index of that sum in F or 0 if not found Ṗ - pop (implicit range [1..that]) This yields: [] (falsey) when i resulted in 0 or 1; or [1] (truthy) when i resulted in 2 (i.e. p'=p, q'=q, and q-1=sum) ŒPçƇµ;S2*_ṠP) - Link, get pseudo-sublimes: set of integers > 1, L ŒP - powerset of L -> all subsets we could make Ƈ - filter-keep those for which: ç - call the Helper Link - f(subset, L) µ ) - for each: e.g. [a, b, ..., n] S - sum (Subset) a + b + ... + n = q-1 ; - concatenate -> [ a, b, ..., n, q-1 ] 2 - two * - exponentiate -> [ 2^a, 2^b, ..., 2^n, 2^(q-1)] Ṡ - sign (Subset)-> [ 1, 1, ..., 1] _ - subtract -> [2^a-1, 2^b-1, ..., 2^n-1, 2^(q-1)] P - product -> pseudo-sublime number ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~34~~ 24 bytes ``` ṗ'L›:E‹"?↔‹n∑ḟɾ;ƛ∑JEn±-Π ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZcnTOKAujpF4oC5XCI/4oaU4oC5buKIkeG4n8m+O8ab4oiRSkVuwrEtzqAiLCIiLCJbMywgNCwgNSwgNiwgNywgMTVdIl0=) ~~Mess.~~ Well, still a mess, but -10 bytes by porting Jonathan Allan's Jelly answer, upvote that! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 bytes (thanks @Steffan!) ``` 2*’ §=⁹aÇP€×2*⁹¤ʋ Ñe³ƊƇµ’³œcç"Ñ’$F¹Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8/99I61HDTK5Dy20fNe5MPNwe8KhpzeHpQMHGnYeWnOrmOjwx9dDmY13H2g9tBao7tPno5OTDy5UOTwRyVNwO7TzW/v///2hjHQUTHQVTHQUzHQVzHQVD01gA "Jelly – Try It Online") Also a mess. Link 1: computes \$2^x-1\$ ``` 2 Two * To the power of the input ’ Decrement ``` Link 2: given a list of subsets of length \$p-1\$ of the input list, and \$q-1\$ (as defined in the question), return a list with all valid answers or 0. ``` §=⁹aÇP€×2*⁹¤ʋ § Compute the sum of each sublist (vectorizes at depth 1) = Check if equal to... (vectorizes) ⁹ ...q-1 a Logical AND with... ʋ ...the four previous links as a dyad Ç The previous link as a monad (2^x-1 for each x in each subset) € For each subset: P Compute the product × Multiply by... ¤ ...a nilad followed by some links, as a nilad: 2 Two * To the power of... ⁹ ...q-1 ``` Link 3 (main link): given the input list, outputs all valid answers. ``` Ñe³ƊƇµ’³œcç"Ñ’$F¹Ƈ Ƈ Filter the list using: Ɗ The last three links as a monad Ñ The next link as a monad (wraps around to link 1) e Check if it's present in... ³ ...the input list µ Start a new monadic chain (At this point, the list contains all 'p' in the input list such that 2^p-1 is also in the input list.) ’ Decrement œc All combinations of ... of any length in the list (vectorizes over the right argument) ³ The input list " Zipping over the left and right arguments: ç Call the previous link as a dyad, with the next link as the right argument $ The last two links as a monad: Ñ The next link (wraps around to link 1) on each valid 'p', thus generating all the candidates for 'q' ’ Decrement (thus generating all the candidates for q-1) F Flatten Ƈ Filter the list using: ¹ The truth value of each element itself (thus removing all falsy values from the list) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` IEΦEX²LθΦθ&ιX²μ∧⁼Σι⊗⊖X²Lι∧№θ⊕Lι№θ⊕Σι×X²ΣιΠ⊖X²ι ``` [Try it online!](https://tio.run/##bY7LCsIwFER/JcsbiJsquHClrYKgUNBd6SK2wQbysHnYz4@pBivS3TD3zJ1pOmoaTUUIpeHKQU6tgzN9wIELx8xblnqIKiPoxNTdddBjTFC69wTtuBu4ZVvVAifoC0uMR260972nwsLFS@DRKrS/CdZCwRrDJFMu6v8Ojqd4rn1cFpuOagr8cATNEp@69OfKJbNTS7rFuUa3vnHzW1Iab0KoqowsyYqs6zosnuIF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` IEΦEX²LθΦθ&ιX²μ ``` For each subset of the input list, such that... ``` ∧⁼Σι⊗⊖X²Lι ``` ... the sum of each subset is two less than twice two to the power of its size, and... ``` ∧№θ⊕Lι ``` ... the size of the subset is one less than one of the integers in the input list, and... ``` №θ⊕Σι ``` ... the sum of the subset is also one less than one of the integers in the input list, ... ``` ×X²ΣιΠ⊖X²ι ``` ... raise two to the power of each of the integers in the subset, decrement the results, take the product, and multiply by two to the power of the sum of the subset. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 45 bytes ``` ∋P{;2↔^-₁}Q∈?∧P-₁~lċS⊆?∧S++₁Q-₁;2↔^R∧S↰₁ᵐ×;R× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FHd0C1tdGjtilxuo@aGmsDH3V02D/qWB4A4tXlHOkOftTVBhII1tYGigSChCHKg0CCj9o2AAUebp1weLp10OHp//9HG@somOoomOsoGAJZhiDaUkfB2FBHwQyILYBsQwOQoBGQMDUCCRuYx/6PAgA "Brachylog – Try It Online") [This is a generator that can be used to get all results.](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sW/H/U0R1QbW30qG1KnC5QqDbwUUeH/aOO5QEgXl3Oke7gR11tIIFgbW2gSCBIGKI8CCQINqjp4dYJh6dbBx2e/v9/tLGOgomOgqmOgpmOgrmOgqFp7P8oAA) There are surely some shorter ways to express things. ### Explanation ``` ∋P P is an element of the input {;2↔^-₁}Q Q = 2^P - 1 Q∈? Q is an element of the input ∧ P-₁~lċS S is a list of length P-1 S⊆? S is a subset of the input ∧ S++₁Q The elements of S sum to Q-1 Q-₁;2↔^R R = 2^(Q-1) ∧ S↰₁ᵐ Map the first predicate {;2↔^-₁} to each element of S × Multiply the result ;R× Multiply with R ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ ~~28~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) -6 bytes porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/251292/52210), thanks to *@Steffan*: ``` æʒg>Do<‚Ã<yOk}εo<PyOo* ``` [Try it online](https://tio.run/##yy9OTMpM/f//8LJTk9LtXPJtHjXMOtxsU@mfXXtua75NQKV/vtb//9FGOgrGOgqmOgrmOgqGprEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8PLzs1Kd3OJd/mUcOsQ@uKDzfbVPpn157bmm8TUOmfr/W/Vud/dLRRrE60kY4xhNQxgdE65kAWMm2qY6ZjrmNoClVgCuNAmcY6hkDSUsfYUMfMUMfCUsfQAMg3MtcxNQKKGJjHxgIA). **Original ~~30~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` æεg>©å*®o<åyO®oÍ©Q*iyo<®oªP, ``` Outputs the results on separated lines to STDOUT. [Try it online](https://tio.run/##yy9OTMpM/f//8LJzW9PtDq08vFTr0Lp8m8NLK/2B9OHeQysDtTIr822AnEOrAnT@/4820lEw1lEw1VEw11EwNI39r6ubl6@bk1hVCQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VS6hP4/vOzc1nS7Qysjig8vjdA6tC7f5vDSSn8gfbj30MpArczKfBsg59CqAJ3/tbWHttn/j442itWJNtIxhpA6JjBaxxzIQqZNdcx0zHUMTaEKTGEcKNNYxxBIWuoYG@qYGepYWOoYGgD5RuY6pkZAEQPz2Nj/urp5@bo5iVWVAA). **Explanation:** ``` æ # Get the powerset of the (implicit) input-list ʒ # Filter the inner lists `y` by: # (implicitly push list `y`) g # Pop and get the length of list `y` > # Increase it by 1 D # Duplicate this length+1 o # Take 2 to the power this value < # Decrease it by 1 ‚ # Pair them together: [length+1,2**(length+1)-1] à # Only keep those values from the (implicit) input-list < # Decrease each remaining value by 1 yO # Push the sum of list `y` k # Get its 0-based index in the list of 0, 1, or 2 items # (only 1 is truthy in 05AB1E) }ε # After the filter: map over the remaining inner lists `y`: o # Take 2 the power each value in the list < # Decrease each by 1 P # Take the product of these values yO # Then push the sum of list `y` o # Take 2 to the power this sum as well * # And multiply it to the earlier product # (after which the list is output implicitly as result) ``` ``` æ # Get the powerset of the (implicit) input-list ε # For each over the inner lists `y`: # (implicitly push list `y`) g # Pop and get the length of list `y` > # Increase it by 1 © # Store it in variable `®` (without popping) å # Check that it's in the (implicit) input-list * # Multiply this 0 or 1 to the (implicit) input-list, # so we either have a list of 0s, or the unmodified input-list ® # Push length+1 from variable `®` again o # Pop and push 2 to the power this < # Decrease it by 1 å # Check if it's in the earlier list (the input-list or list of 0s) yO # Push the sum of the current list `y` ®o # Push 2 to the power `®` again Í # Decrease it by 2 © # Store this as new variable `®` (without popping) Q # Check if it's equal to the sum *i # If both checks are truthy: y # Push list `y` again o # Calculate 2 to the power each value in the list < # Then decrease each by 1 ® # Push variable `®`: 2**(length+1)-2 o # Get 2 to the power this value ª # Append it to the list P # Get the product of this list , # Pop and print it to STDOUT with trailing newline ``` ]
[Question] [ ## Challenge Generate the 2D sequence of bits of [A141727](https://oeis.org/A141727). (Allowed I/O methods explained at the bottom.) ``` 1 1 0 1 1 0 0 1 0 1 0 1 0 1 0 0 1 0 0 1 1 0 1 1 1 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 1 1 1 0 0 1 0 1 0 1 0 0 0 1 1 0 0 1 1 1 1 0 0 1 1 0 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0 1 1 0 1 0 1 1 1 0 0 ``` This triangle is generated as follows: starting with a row of single 1, generate the bits row-by-row, from left to right. Each bit is the parity of the sum (in other words, XOR-sum) of the neighboring bits already placed (8-way neighborhood). ``` [1] initial condition 1 [1]? ? only one neighbor being 1, sum is 1 1 1[0]? two 1-neighbors, sum is 0 1 1 0[1] two neighbors (0 and 1), sum is 1 1 1 0 1 [1]? ? ? ? one neighbor, sum 1 1 1 0 1 1[0]? ? ? three neighbors, sum 0 1 1 0 1 1 0[0]? ? four neighbors, sum 0 1 1 0 1 1 0 0[1]? three neighbors, sum 1 1 1 0 1 1 0 0 1[0] two neighbors, sum 0 ... ``` [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") default I/O methods apply. In this challenge, you can interpret the sequence as a sequence of individual bits or a sequence of rows of bits, so the following are accepted: * Given `n` (0- or 1-indexed), output `n`-th bit or `n`-th row * Given `n` (positive), output first `n` bits or first `n` rows * Given no input, output the infinite sequence of bits or the sequence of rows (refer to [sequence rules](https://codegolf.stackexchange.com/tags/sequence/info) for exactly which methods count as infinite output) Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes Outputs an infinite sequence of rows. As a bonus, it runs extremely slowly. ``` n=1 while 1:print'%o'%n;x=n;n*=64;exec'n^=x;x/=8;'*x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WkKs8IzMnVcHQqqAoM69EXTVfXTXPusI2zzpPy9bMxDq1IjVZPS/OtsK6Qt/Wwlpdq@L/fwA "Python 2 – Try It Online") If the current row expressed in binary is `n`, the next row will be `a(n) ^ n*4`, where `a(n)` is the prefix xor sum of the bits. `a(n)` is also associated with [OEIS A006068](http://oeis.org/A006068). One annoying little thing about Python is that there is no format string to convert an integer to binary. The next best alternative is octal, which is what the code uses instead. ### [Python 2](https://docs.python.org/2/), 54 bytes Adding 2 more bytes gets the program to a reasonable speed. ``` n=1 while 1: print'%o'%n;x=n;n*=64 while x:n^=x;x/=8 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WkKs8IzMnVcHQikuhoCgzr0RdNV9dNc@6wjbPOk/L1syESwGioMIqL862wrpC39bi/38A "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 110 bytes ``` def f(n): if n<1:return[1] k=[1];p=f(n-1)+[0,0] for i in range(n*2):k+=[p[i-1]^p[i]^p[i+1]^k[-1]] return k ``` [Try it online!](https://tio.run/##XY3NCsIwEITPzVMMPSX9gabeqnmSUEGw0SWwDaFCffq41ZuX@YZhZza9t@fKp1LuS0DQbCZVUQBf7JSX7ZXZ21lV0QnOyclBb03rh26QNKwZBGLkGz8Wzc1optg6nzz1dr4KvtKKj14Sqfw2EcsOh3FQ6m9jP/6nTLzpGjUa6FFkR4@DZDo0QZMx5QM "Python 3 – Try It Online") A pretty basic and *very* sub-par solution to get things started. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 66 bytes ``` f=r=>b=r?f(r-1).map(_=>a[++i]=a[i-2]^b[i-3]^b[i],a=[i=1,0])&&a:[1] ``` [Try it online!](https://tio.run/##HcrBDoIgGADgu0/xnxRCmNilZdiDMGpo0H5n4tB1aT07aafv8g32bZc@4rzyKTxcSl5F1XYqXj2JXFLxsjO5q9ZqxtAoq5HX5tZtHP@Y0iqNSpaVoXluz1qa5EMEMroVEBRUzcYF5C5jFD4ZQB@mJYxOjOFJCihEdLOzK5En4FDDAZACA0@QiiHgtBdKm@ybfg "JavaScript (Node.js) – Try It Online") Input `r`, output an array for `r`-th row. --- # [JavaScript (Node.js)](https://nodejs.org), 48 bytes ``` f=r=>r?(g=a=>a^a/4^b/2^b*4?g(a+1):a)(b=f(r-1)):1 ``` [Try it online!](https://tio.run/##DcVBCoMwEADAu6/Y426DtSlCQbv6k8DGJiElGInSS@nbU@cyb/nIvpS4He2aX65Wz4WnMmNg4UmMdL2x3d3YSz8HFKVpEELLHkuriQZdfS6AyR0QgeE2nj3hcaYUwbcBWPK65@SuKQf0GInG5lf/ "JavaScript (Node.js) – Try It Online") Or output `r`-th row [as an integer](https://oeis.org/A141733) if it is allowed. --- ``` a b c d e f g h i j k l m n o p n = m xor g xor h xor i = (l xor f xor g xor h) xor g xor h xor i = l xor f xor i ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 22 bytes ``` FN«F⊕⊗ιI∨¬ι﹪№KM1²J±ⅈ⊕ⅉ ``` [Try it online!](https://tio.run/##TY0xC8IwFITn9leETi9Qwbo61kWhsYODjmn61NK0rzwTF/G3x4c4uNzBfXecu1t2ZH1KV2IF@3mJwcSpQwat1SvPfrFjnHAO2MOOYufFBy2Floc5QG0fAY4MhoLEpWqoj56gpiiwRRwbIkYQUlSF6EameptnhzgtJwKDNxsQzvJYqv@rC3x775SqdVo9/Qc "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` rows as a triangle. Explanation: ``` FN« ``` For each row: ``` F⊕⊗ι ``` For each bit in the row... ``` I∨¬ι﹪№KM1² ``` ... output the parity of the number of adjacent `1`s, except for the very first bit, which is always a `1`. ``` J±ⅈ⊕ⅉ ``` Jump to the start of the next row of bits. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~52~~ ~~51~~ 50 bytes ``` Nest[i+=#&/@{##,i=0,0}-{0,##,0}&@@#&,{1},#]~Mod~2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ6U9tWWU3foVpZWSfT1kDHoFa32kAHyDGoVXNwUFbTqTas1VGOrfPNT6kzUvvvkh8dUJSZV@KQ5pCpU52pY6BjWRv7HwA "Wolfram Language (Mathematica) – Try It Online") Returns the (0-indexed) \$n\$th row. Uses \$\displaystyle A\_{n+1}(m)=A\_n(m-1)\oplus\bigoplus\_{i\le m}A\_n(i)\$, where \$A\_n(m)\$ is the \$m\$th element of row \$n\$. This can be rewritten \$\displaystyle A\_{n+1}(m)=A\_n(m)\oplus\bigoplus\_{i\le m-2}^{}A\_n(i)\$. [Answer] # [Python 3](https://docs.python.org/3/), 98, 92, 88, 77, 76 bytes ``` v=-4**64;W=w=v*v;v+=w;O=1 while[print(hex(O)[2::32])]:O*=w;O^=O//v&W//v;W*=w ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8xW10RLy8zEOty23LZMq8y6TNu23Nrf1pCrPCMzJzW6oCgzr0QjI7VCw18z2sjKytgoVjPWyl8LpCjO1l9fv0wtHEhYhwNF/v8HAA "Python 3 – Try It Online") [Old version](https://tio.run/##K6gsycjPM/7/v8xW10RLy8zEOty23LZMq8y6TNu23Nrf1pCrPCMzJ1XB0KqgKDOvRCMjtULDXzPayMrK2ChW09pfC6QqztZfX79MLRxIWIcDRf7/BwA "Python 3 – Try It Online") [Old version](https://tio.run/##K6gsycjPM/7/v8xW10JLy8K63LZMq8y6TNu2nCvNNicxNyklUSFXx9/WUCfcttwqVyExLyU6I7VCw18z2sjKyiw2VjtNI1fXUMdfqzwOiPX1y9TCgYROuFa5Zn5RdOz/gqLMvBKNNA1DA03N/wA "Python 3 – Try It Online") [Old version](https://tio.run/##DctBCoMwEADAu6/IqSRbRK0gknWfEPYBpYdAEyKolSKuvj4691nPLf2WNudviCrq2dhCeeoBehTy4HEnKT06EoC5qnZkagolaZyC4sFZfpDD9T8um07h0GzeL2u7j0EGEuQn8Z1y1E1t8gU "Python 3 – Try It Online") [Old version](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1fTikvB37bc1kJLy8La17Zcq1xLS8NIK1dTX79Ot5xLoTwjMydVwd/G18rfVsNfzRciruZrXVCUmVeikZFaoeGvGW1kZWUWq2ntrwU0QMsYrESr/H@ahqGB5n8A "Python 3 – Try It Online") Probably not competitive but I think mildly amusing. Takes advantage of Python arbitary size integers to perform cumulative xor. In fact we simply do a cumulative sum over digits using the divide by 9 (or rather base-1) trick and take the base large enough that carry never becomes an issue. Runs "forever", only it maxes out at around m=2^23. That's not a principal limitation, just me being cheap on integer constants. n=2^127 (rowindex) which I hope is close enough to eternity. **UPDATE** simplified the maths using @dingledooper's formula. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes ``` n->for(i=a=1,n,a=a*x+a/(1-x)%x^(2*i+1));Vecrev(a)%2 ``` [Try it online!](https://tio.run/##FYsxCoAwDAC/EgQh0Ratq6TPcBSCWOkSSxHp72sd7oaDS5KjvVINwFWtD3fGyMLOqBGWoYwyobOF@rLjMsTREa3beeTzRaF@qf@gwDAbcI2Uoz4tdGB9U0AlovoB "Pari/GP – Try It Online") 0-indexed. ### Explanation See each row as a polynomial, starting with the constant term. `a*x` prepends a 0 to the list. `a/(1-x)` takes the cumulative sum of the list. `%x^(2*i+1)` truncates the list to the first `2*i+1` elements. [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes ``` f=->r,c{c<0||c>r*2?0:r<1?1:([*c-2..c].sum{|x|f[r-1,x]}+f[r,c-1])%2} ``` [Try it online!](https://tio.run/##ZY3LCoMwEEX3@YrBUnwmJG4K4uNDxIUNlXZhKVHBYvLtNrY@Us2QYZg5nCu663scqwSnIuADj6mUPBVemNFIxCxjkZN7HIeE8II0XT3IXla5wCzoC@XrKeCYFe45VGNd9pDABTmUED275Fby@yCFRPASj2cLFlieoy9YuF6IYOKITvLZgnKNLuxp@MoLBRYCpRVd29g2UiMcHkOHDdDDdtrRqaMDOX/zstBs7pttpedihnPNMG6b@S9rtW/@fSY1bL@UffZGG1kf "Ruby – Try It Online") * computes value at `r` row , `c` column * Values outside the triangle give 0 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` λb=Å»^}2β₁4*^ ``` [Try it online.](https://tio.run/##yy9OTMpM/f//3O4k28Oth3bH1Rqd2/SoqdFEK@7///@6unn5ujmJVZUA) Port of [*@dingledooper*'s Python 2 answer](https://codegolf.stackexchange.com/a/236788/52210), but using binary instead of octal integers, so make sure to upvote him/her as well! -1 byte thanks to *@CommandMaster*. **Explanation:** ``` λ # Start a recursive method, # to generate an infinite sequence, # starting at a(0)=1 by default # Where every next a(n) is calculated as follows: b # Convert the current implicit a(n-1) to a binary string = # Output it with trailing newline (without popping) Å» # Cumulative left-reduce its bits by: ^ # Bitwise-XORing } # After the cumulative left-reduce, 2β # Convert it from a binary-list to an integer ₁ # Push a(n-1) again 4* # Multiply it by 4 ^ # And Bitwise-XOR it to the integer ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` a=1;loop{puts"%b"%a;(a=2*z=2*a).times{a^=z/=2}} ``` [Try it online!](https://tio.run/##KypNqvz/P9HW0DonP7@guqC0pFhJNUlJNdFaI9HWSKsKiBM19Uoyc1OLqxPjbKv0bY1qa///BwA "Ruby – Try It Online") [Answer] # [Raku](http://raku.org/), 52 bytes ``` 1,{(1,{[+^] $^x,|(.[^3-1+$++]:v)}...*)[^(2+$_)]}...* ``` [Try it online!](https://tio.run/##K0gtyjH7r1ecWKmQll@koPHfUKdaA4ijteNiFVTiKnRqNPSi44x1DbVVtLVjrco0a/X09LQ0o@M0jLRV4jVjwdz/QL6hQex/AA "Perl 6 – Try It Online") This is an expression for a lazy, infinite sequence of rows. * `1, { ... } ... *` is the main sequence expression. `1` is the first row, and the bracketed anonymous function generates the next row from the previous row, passed in `$_`. * `(1, { ... } ... *)[^(2 + $_)]` likewise generates the elements of each row, starting with 1, from the previous element `$^x` and the previous row `$_`. The number of elements in each row is two greater than the size of the previous row: `2 + $_`. * The numbers to be xor-ed together are `$^x`, the previous element of the current row, and `.[^3 - 1 + $++]:v`, a sliding three-index window across the previous row. The `:v` adverb causes indexes out of the array's range, both positive and negative, to be skipped. * `+^` is the integer xor operator, and `[+^]` reduces the list of integers that contribute to the current element using that operator. ]
[Question] [ # Introduction Given this visualization of a playing field: ``` (0,0) +----------------------+(map_width, 0) | A | |-----+-----------+----| | D | W | B | |-----+-----------+----| | C | +----------------------+(map_width, map_height) (0, map_height) ``` The entire map the game is played on is the rectangle with the corner coordinates (0,0) and (map\_width, map\_height). The points eligible for spawning enemies is the Union $$S = \bigcup (A, B, C, D) $$ # The Challenge Write code that returns a random point(x, y) that is guaranteed to be inside S. Your code cannot introduce any additional bias, meaning that the probability of each coordinate is [uniformly distributed](https://en.wikipedia.org/wiki/Discrete_uniform_distribution) given the assumption that your choice of generating randomness (e.g. function|library|dev/urandom) is unbiased. Shortest solutions in bytes win! # Input You will be given a total of 6 positive integer input variables in order: `map_width, map_height, W_top_left_x, W_top_left_y, W_width, W_height`. You can assume that the (calculated) surface area of all regions(A,B,C,D,W) is each >10, so there are no empty spaces/regions. Example Input: `1000, 1000, 100, 100, 600, 400` The input has to contain the 6 values described above but it can be passed as fewer numbers of arguments and in any order. For instance passing `(map_width, map_height)` as python tuple is allowed. What is not allowed of course are calculated parameters like the bottom right point of the W. # Output 2 randomly generated integers (x, y) where $$(0 \leq x \lt \text{map\_width}) \land (0 \leq y \lt \text{map\_height}) \land[\neg (\text{W\_top\_left\_x} \leq x \lt \text{W\_top\_left\_x} + \text{view\_width})\lor \neg (\text{W\_top\_left\_y} \leq y \lt \text{W\_top\_left\_y} + \text{view\_height})]$$ holds. # Examples ``` Input Output(valid random samples) 1000 1000 100 100 600 400 10 10 1000 1000 100 100 600 400 800 550 1000 1000 100 100 600 400 800 10 1000 1000 100 100 600 400 10 550 ``` For details and limitations for input/output please refer to the [default input/output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) [Answer] # [Python 2](https://docs.python.org/2/), ~~114~~ ~~106~~ ~~102~~ 101 bytes ``` lambda w,h,X,Y,W,H:choice([(i%w,i/w)for i in range(w*h)if(W>i%w-X>-1<i/w-Y<H)<1]) from random import* ``` [Try it online!](https://tio.run/##RYxBCsIwFET3PUU2QlJ@MBF1UWrXvUFbVKS2TfPBJiUEgqePqSAuZmYxj7e@vbbmENXlFl/98hx7EkBDCx00UBeDtjhM9EpxFwD3gSnrCBI0xPVmnmjINUNFmyr9vK24LBPEu7JmpbyzTDm7bOSYBpfVOp/HzfD4G06syMjq0HiiqBRCwK@@OacchWDxAw "Python 2 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~85~~ 73 bytes -12 bytes thanks to mazzy ``` param($a,$b,$x,$y,$w,$h)$a,$b|%{0..--$x+($x+$w+2)..$_|random $x,$w=$y,$h} ``` [Try it online!](https://tio.run/##PcuxDoIwFIXh/T6Fw0EglJtbY1wMz2JqhHQAIWUoBvrspTA4/Gc4yTeNvnWzbfs@omvWOBlnhgJG4a2wKPwUvIItz2fLVmGuayxVkYKvbiUzXpsz38840AF8cxgbYiDSzFoSoiu6ixaR/5w9UneRZ55TiDs "PowerShell – Try It Online") Nice simple answer which cobbles together an array made of the range of values for each dimension and then picks one randomly for `x` and `y`. Manages to reuse most of the code by first processing `x`, then overwriting `$x` with `$y` and running it again. [Answer] # [R](https://www.r-project.org/), ~~89~~ 73 bytes ``` function(w,h,K,D,`*`=sample){while(all((o<-c(0:w*1,0:h*1))<=K+D&o>K))0 o} ``` [Try it online!](https://tio.run/##HclBCoMwEIXhvacIFMqMHSFqyUJiV@5yCUVMI8SkaEoWpWdPYzePj/fvSTNZsaTfbg6rdxDJkKKBxnLsj2l72QU/0ax2gclaAC@rGXgXy5p4Z8oaUfbqNlz9QyHywn@ThppzTv@ZT5/ETJF5z8RCgyCRn5baMzTUILIL035nYTnC6p7pBw "R – Try It Online") Takes input as `width,height,c(X,Y),c(W,H)`. Samples from \$[0,w]\times[0,h]\$ uniformly until it finds a point outside the inner rectangle. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ ~~21~~ ~~20~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L`â<ʒ²³+‹y²@«P≠}Ω ``` Input is in the format `[map_width, map_height], [W_top_left_x, W_top_left_y], [W_width, W_height]`. Thanks to *@Grimy* for -1 byte, and also for making me realize I introduced a bug after my latest edit. [Try it online](https://tio.run/##yy9OTMpM/f/fJ@HwIptTkw5tOrRZ@1HDzspDmxwOrQ541Lmg9tzK//@jDQ0MdIA4lgvIAjKAtJmBjolBLAA), [output 10 possible outputs at the same time](https://tio.run/##yy9OTMpM/f/fJ@HwIptTkw5tOrRZ@1HDzspDmxwOrQ541Lmg9n@Im8u5lTr/ow0NDHSAOJYLyAIygLSZgY6JQSwA) or [verify all possible coordinates](https://tio.run/##yy9OTMpM/f/fJ@HwIhuXc1sPbTq0WftRw87KQ5scDq0OeNS5oPbwjkO7//@PNjQw0AHiWC4gC8gA0mYGOiYGsQA). (Minor note: I've decreased the example input by a factor 10, because the filter and random choice builtin arer pretty slow for big lists.) **Explanation:** The inputs `map_width, map_height, [W_top_left_x, W_top_left_y], [W_width, W_height]` are referred to as `[Wm, Hm], [x, y], [w, h]` below: ``` L # Convert the values of the first (implicit) input to an inner list in # the range [1, n]: [[1,2,3,...,Wm],[1,2,3,....,Hm]] ` # Push both inner lists separated to the stack â # Get the cartesian product of both lists, creating each possible pair < # Decrease each pair by 1 to make it 0-based # (We now have: [[0,0],[0,1],[0,2],...,[Wm,Hm-2],[Wm,Hm-1],[Wm,Hm]]) ʒ # Filter this list of coordinates [Xr, Yr] by: ²³+ # Add the next two inputs together: [x+w, y+h] ‹ # Check for both that they're lower than the coordinate: [Xr<x+w, Yr<y+h] y # Push the coordinate again: [Xr, Yr] ² # Push the second input again: [x, y] @ # Check for both that the coordinate is larger than or equal to this given # input: [Xr>=x, Yr>=y] (the w,h in the input are ignored) « # Merge it with the checks we did earlier: [Xr<x+w, Yr<y+h, Xr>=x, Yr>=y] P≠ # And check if any of the four is falsey (by taking the product and !=1, # or alternatively `ß_`: minimum == 0) }Ω # After the filter: pick a random coordinate # (which is output implicitly as result) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 110 bytes ``` (a,b,c,d,e,f)=>{int g=c,h=d;for(var z=new Random();g>=c&g<e+c|h>=d&h<f+d;h=z.Next(b))g=z.Next(a);return(g,h);} ``` [Try it online!](https://tio.run/##bU7LTsMwELz3K/ZU2YpJDeIh1XEkLhwRokicXXtjW6IuclzatPTbg101Nw6zO9rZ2Vnd3@jejy@7oBsfEvsP5Epo28mRKLZmmhmGrKOyPeU5WKmZk0Z020h@VISjDLiHdxXMdkOosK3Uc9tgpX9dK83cNV1lhJPH@hUPiawptRNXVERMuxiIZY6K8yhm5WgJ8ZIL3zwIX1X09BbziHTklnPOpnLBY8Y955SK1dAn3NQfLqIyPtgrq1dfiN/kLu@I82yxAIfeugT5W9h7kxyoiFBuFvE5W@AT@qRi6kElIIdliYGhNHpxYTCT9JSlYVnyxz8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Julia](https://julialang.org/), ~~76~~ ~~71~~ 67 bytes ``` f(w,h,a,b,c,d)=rand(setdiff((0:w-1)'.=>0:h-1,(a:a+c-1)'.=>b:b+d-1)) ``` [Try it online!](https://tio.run/##PcpBCoAgEIXhq7RrpClGiBZC3WXUJCMkrLDbW4G0@fh5vPXaPMs7ZwcJF2TUaNCKMXKwcMyn9c4BkEqtFHU3TqSWViKw4saUSSvd2LdF3qMPJziQRITVb2H46Ine4wM) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` p/’$€+2¦ḟ/X ``` [Try it online!](https://tio.run/##y0rNyan8/79A/1HDTJVHTWu0jQ4te7hjvn7E////ow0NDHSAOFYn2sxAx8wg9r8hiA8A "Jelly – Try It Online") A dyadic link that takes two arguments, `[map_width, map_height], [W_width, W_height]` and `W_left, W_top` and returns a randomly selected point meeting the requirements. ## Explanation ``` $€ | For each of member of the left argument, do the following as a monad: p/ | - Reduce using Cartesian product (will generate [1,1],[1,2],... up to the width and height of each of the rectangles) ’ | - Decrease by 1 (because we want zero-indexing) +2¦ | Add the right argument to the second element of the resulting list ḟ/ | Reduce by filtering members of the second list from the first X | Select a random element ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~84~~ ~~68~~ 60 bytes ``` RandomChoice[g=Join@@List~Array~##&;#~g~0~Complement~g@##2]& ``` [Try it online!](https://tio.run/##FcaxCgIhGADg/V7jBycji2qJiz@uKRqiVRzk8u6EU8NcQvTVTZePz8iwKCODHmWZ@vKS9u3MsDg9Kj73d6ct4kN/Q756L38ZgJwhz5nlwZnPqoyyIc8IsBek3Bx/em0Dh81lQgRBj4JsMXYx7hhjtJFoe2vdqe5Ql7pU/g "Wolfram Language (Mathematica) – Try It Online") Take inputs as `{map_width, map_height}, {W_width, W_height}, {W_top_left_x, W_top_left_y}`. [Answer] # [Python 2](https://docs.python.org/2/), 100 bytes Input should be in the form of `((map_width, W_top_left_x, W_width),(map_height, W_top_left_y, W_height))` Output is given in the form: `[[x],[y]]` ``` lambda C:[c(s(r(i[0]))-s(r(i[1],i[1]+i[2])),1)for i in C] from random import*;c=sample;r=range;s=set ``` [Try it online!](https://tio.run/##RYu9DsIwEIP3PsWNOUiltEIMrTL1MUKFQttApOZHlyw8fUhhYLH92XJ851fwfTHyVnbtHquGaVALS4yYVWJGbH@xm/khZ6v6WvIOTSCwYD1Mc2MoOCDt12rWxUD5NC4yaRf3bSRZl@c2Jpm2XI7b/bh9S9YJHBqIZH0Gw1hlIXgVfhUC@R8vFRHLBw "Python 2 – Try It Online") Random outputs obtained from the example input: ``` [[72], [940]] [[45], [591]] [[59], [795]] [[860], [856]] [[830], [770]] [[829], [790]] [[995], [922]] [[23], [943]] [[761], [874]] [[816], [923]] ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 100 bytes ``` W->H->r->{int x=0,y=0;for(;r.contains(x+=W*Math.random(),y+=H*Math.random());x=y=0);return x+","+y;} ``` [Try it online!](https://tio.run/##VVC7coMwEOz5ihtXYB4j51UEQ5lxCjdJ4YKhUDA4ckAw0mHDePh2IhAmRMVpdXfa3bszvVC3rFJ@Pv70rKhKgXBWOY9e0Vv7xjJVI8u9rOYJspIPRaOqv3KWQJJTKWFPGYebYQBMaYkU1XUp2REKVTQ/UTB@imKg4iQt3QvwzvFtIt0u8Qw@0gQpP@WpA5ohDEPIIOgPbrhzQ@GGN8YRmoA4bUD8rBSmL7yk5KhEpdnYwWG9p/jtCcqPZWFaTmsHu/8py28C9dnyRYq14NDYK2dlt37X@9qlUohiZR1TiRICZR6mc9sQQhyY4xRehvBESOeMnd3Eo9yBOZKNVK@a0Jr5BvfDNExpEF9d24FOAdu2FqJ6ESBSWeeoWjOPVlXemgNbRGJr@dzMT55eYd6mLj7EzmgheryDpzt4jtVa/hRbiWnhlTV6ldLGnJtafe7p9KDGMKiKndH/Ag "Java (OpenJDK 8) – Try It Online") Uses [`java.awt.Rectangle`](https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/Rectangle.html#x) as holder of some of the parameters. Naturally, those use `int` fields, and not `float` or `double`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~55~~ 43 bytes ``` NθNηFE²N⊞υ⟦ιN⟧I‽ΦE×θη⟦﹪ιθ÷ιθ⟧⊙υ∨‹§ιμ§λ⁰¬‹§ιμΣλ ``` [Try it online!](https://tio.run/##bY27CgIxEEV7vyLlBCJEEZutRBEWXBW1E4voRhLIw81D9OtjwiqIOMwUd87cOxfB3MUylVJtbjGsoz5zBx2uBt9aZH21DkHDbjAm6JthjNE2egGRoKP8Yads3DppAsyZD7BjprUallKFTEvYQWruoSNI4GxvbBuVhZzS4ZIUFvIuW94vTnk1M8/yZ@Ngxb2HWahNyx@F60LfUhFEcdZrG/7e7aMGhT9VpTSiFPVTekrRhKbhXb0A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input the map size. (If they were last, I could input the height inline for a 1-byte saving.) ``` FE²N⊞υ⟦ιN⟧ ``` Input the inner rectangle. (If I could input in the order `left, width, top, height` then I could use `F²⊞υE²N` for a 3-byte saving.) ``` E×θη⟦﹪ιθ÷ιθ⟧ ``` Generate a list of all co-ordinates in the field. ``` Φ...⊙υ∨‹§ιμ§λ⁰¬‹§ιμΣλ ``` Filter out entries where both co-ordinates lie inside the rectangle. ``` I‽... ``` Print a random element of those that are left. [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 84 bytes ``` sub c{($c=0|rand((pop)+($l=pop)-"@_"))<$l?$c:$c+"@_"-$l}say c@F[4,2,0];$_=c@F[5,3,1] ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhuVpDJdnWoKYoMS9FQ6Mgv0BTW0MlxxbE0FVyiFfS1LRRybFXSbZSSdYG8XVVcmqLEysVkh3cok10jHQMYq1V4m1BPFMdYx3D2P//DQ0MDBRgBBibAbEJEP/LLyjJzM8r/q/ra6pnYGjwXzexAAA "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 172 bytes Randomness? Gotcha. ``` (a:Int,b:Int,c:Int,d:Int,e:Int,f:Int)=>{var r=new scala.util.Random var z=(0,0) do{z=(r.nextInt(a),r.nextInt(b))}while((c to e+c contains z._1)|(d to e+d contains z._2)) z} ``` A fun implementation I could think of. **How it works**: Generate a random pair in the map. If it is in the inner rectangle, try again. [Try it online!](https://tio.run/##VY5NasMwEIX3OsUsZ4hr5FCyKHUgyyy66QWKLMlEjTMystIUuz67K6uUkMV8zOO9@Rm06tTim0@rI7wpx2C/o2UzwKHvJyGMbeFcL6hejhyLJlNnmkyb2a6kej99qQChZnuDYV1cXqPrynfFxl/E6o01ykKSMH5KbSg5XUujqKi4i4Zovp1cZxE1RA92o0F7jum7Acbyo6IfNH@GeTC2RGKcl9YHdK9P1RqppKQ@OI4d4xmTksU/cu1SPacMCTEvvw "Scala – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~54~~ ~~47~~ ~~45~~ 39 bytes ``` (0?@{[)^:((-1&{)~(<*/@,0<:[)2{[)^:_{~&1 ``` [Try it online!](https://tio.run/##PYxNC4IwHMbv@xQPEW4Ls2nRQYykoFN06BoUYn9zgYumEiT41W146PB7Ds/bc5gEvMAmBocPhdgxD7A/Hw@DUNu0u8hrLMQ89DrZi2S2SH2VxBcZjcGt671wkOy0C0Cmbi2hKQnWPGCppqYGZXmJRleEj/Nbwyy9W@163LQVWZ1zZjNzf1X6S5yz8cnVoBuEahzWjPLylRaTCMJZS0SYukypv4ysHGulJGPDDw "J – Try It Online") Take input as a 3 x 2 grid like: ``` grid_height grid_width inner_top inner_left inner_height inner_width ``` * Pick a random point on the entire grid: `0?@{[` * Shift it left and down by the upper-left point of the interior rectangle: `(-1&{)~` * Return to step 1 if the chosen spot is within `(<*/@,0<:[)` the similarly shifted interior rectangle `2{[`. Otherwise return the original, unshifted random point. * Seed the whole process with a point we know is invalid, namely the upper left point of the interior rectangle, defined by elements 2 and 3 of the input list: `{~&1` # Another approach, 45 bytes ``` {.#:i.@{.(?@#{])@-.&,([:<@;&i./{:){1&{|.i.@{. ``` [Try it online!](https://tio.run/##PYw9C8IwGIT3/IrDSmNBX@MHDlGxKDiJg6s4SH1rIzRi2iIY/3sNHRyeG47n7tH2SOZYa0gMoaADI8LudNi3niJtKPU02KSRvyTpiOLh4KxX6TI2NPY68ZPYf6lz2kQctwS2VeMYdcFw9g7HFdcV@JoVqE3JeIe@scLxqzHBk7Yp2ZlMCne1t2dpPiyl6J6CBlNjorphJTgrnsgxwxT90Cr1j455YKGUEO0P "J – Try It Online") This one is conceptually simpler, and doesn't bother with looping. Instead, we construct a matrix of all the numbers 0 to (w x h), shift it by the inner starting point, grab just the points in the (0, 0) to (inner w, innner h) subgrid, remove them from the overall grid after flattening both, pick one at random from the remainder, and convert the integer back into a point using divmod `<.@% , |~` ]
[Question] [ Specifically, [Conway's PRIMEGAME](https://oeis.org/wiki/Conway's_PRIMEGAME). This is an algorithm devised by John H. Conway to generate primes using a sequence of 14 rational numbers: ``` A B C D E F G H I J K L M N 17 78 19 23 29 77 95 77 1 11 13 15 15 55 -- -- -- -- -- -- -- -- -- -- -- -- -- -- 91 85 51 38 33 29 23 19 17 13 11 14 2 1 ``` For example, F is the fraction `77/29`. So here's how the algorithm finds the prime numbers. Starting with the number `2`, find the first entry in the sequence that when multiplied together produces an integer. Here it's `M`, `15/2`, which produces `15`. Then, for that integer `15`, find the first entry in the sequence that when multiplied produces an integer. That is the last one, `N`, or `55/1`, which yields `825`. Write down the corresponding sequence. (The astute among you may recognize this as a [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) program.) After some iterations, you'll get the following: ``` 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132, 116, 308, 364, 68, 4 ... ``` Note that the last item listed is `4`, or `2^2`. Behold our first prime number (the `2` exponent) generated with this algorithm! Eventually, the sequence will look like the following: ``` 2 ... 2^2 ... 2^3 ... 2^5 ... 2^7 ... etc. ``` Thus, yielding the prime numbers. This is [OEIS A007542](http://oeis.org/A007542). ## The Challenge Given an input number `n`, either zero- or one-indexed (your choice), either output the first `n` numbers of this sequence, or output the `n`th number of this sequence. ## Examples The below examples are outputting the `n`th term of the zero-indexed sequence. ``` n output 5 2275 19 4 40 408 ``` ## Rules * If applicable, you can assume that the input/output will fit in your language's native Integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [FRACTRAN](https://github.com/DennisMitchell/ffi), 99 bytes ``` 17/2821 78/2635 19/1581 23/1178 29/1023 77/899 95/713 77/589 1/527 11/403 13/341 15/434 15/62 55/31 ``` [Try it online!](https://tio.run/##HcdLCsMwDAXAq2hdKM9PsiL5MoUQKHTjlDTnr/pZDXM/1u081lnFgKZSIqGLuXCAnhQ1kJGi3zc1iUCOIcMR/M9zCOEaQqI3ExqsU@jo1n8sKu4wVpVejLfe3vvzfOzzVdf5AQ "FRACTRAN – Try It Online") The program takes `2*31^n` as an input, which is used as the initial state. All the fractions in the original FRACTRAN program have been divided by 31 (the first unused prime register), so the program stops at the nth iteration. [Answer] # [Python 3](https://docs.python.org/3/), ~~173 165 153 145 144 136 135 127 126 125 108 107~~ 104 bytes ``` f=lambda n:2>>n*2or[f(n-1)*t//d for t,d in zip(b"N M_M \r7",b"[U3&! \r ")if f(n-1)*t%d<1][0] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc/KyM4uT8sovyg6TSNP11BTq0RfP0UhLb9IoUQnRSEzT6Eqs0AjSUnQT1hc1jfel5E7poif31xJJ0kpOtRYTVFWXFgwpoibj4lRSTMzTQFmhmqKjWFstEHsf5BBmSBjihLz0lM1zDStuBSAoKAoM69EI1MHqCFTU/M/AA "Python 3 – Try It Online") * -30 bytes thanks to Jonathan Frech! * -3 bytes thanks to Lynn! `2>>n*2` is `2` for `n==0` and `0` otherwise. [103 bytes](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc/KyM4uT8sovyg6TSNP11BTq0Q/RSEtv0ihRCdFITNPoSqzQCNJSdBPWFzWN96XkTumiJ/fXEknSSk61FhNUVZcWDCmiJuPiVFJMzNNAWaEaoqNYWy0Qex/kEGZIGOKEvPSUzXMNK24FICgoCgzr0QjUweoIVNT8z8A) if we can return floats. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ 43 bytes ``` ד×NŒçøM_M¢¿ÆÐÐ7‘“[U3&!øçŒ×ƿǣ¢‘:@xḍɗḢ 2Ç¡ ``` [Try it online!](https://tio.run/##y0rNyan8///w9EcNcw5P9zs66fDywzt8430PLTq0/3Db4QmHJ5g/apgBlIwONVZTPLzj8HKgkumH24Cy7YcWH1oElLRyqHi4o/fk9Ic7FnEZAUUX/v9vYgAA "Jelly – Try It Online") * -6 bytes thanks to miles [Answer] # [Python 3](https://docs.python.org/3/), 107 bytes ``` f=lambda n,k=2:n and f(n-1,[k*a//b for a,b in zip(b"N M_M \r7",b"[U3&! \r ")if k*a%b<1][0])or k ``` [Try it online!](https://tio.run/##Fc3BCoJAFEBRbCsk0sKV8BooZmLCTCiQ/ATbtVKJGWzqYT1lcFM/P@kH3HOH7/jqKXPOFG/10a0Ckl1xzAkUtWA47VNZdTuVJBpMb0FJDUjww4FrFl5XUVzeS8@vbRCcmdSsumXbdRytwtr6y4XHBBqY8o2@pE11aMREdG6GcGasoueDn0QOg0UaOcppiUK4Pw "Python 3 – Try It Online") Encodes the list of fractions by `zip`ing two bytestrings containing unprintable low-ASCII characters. If `n` is zero, we return the argument `k`; otherwise we recurse with new parameters. Our new `k` is the first value `k*a//b` corresponding to some fraction `(a, b)` in the list such that `k*a//b` is an integer, i.e. `k*a%b<1`. [Answer] # [MATL](https://github.com/lmendo/MATL), 50 bytes ``` Hi:"'0m26<l~l *,..V'31-*'{uSFA=731-+."!'32-&\w~)1) ``` [Try it online!](https://tio.run/##y00syfn/3yPTSkndINfIzCanLkdBS0dPL0zd2FBXS726NNjN0dYcyNbWU1JUNzbSVYspr9M01Pz/38QAAA "MATL – Try It Online") [Answer] # [J](http://jsoftware.com/), 116 110 bytes ``` g=.3 :0 ((1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x)([:({.@I.@(=<.){[)*)])^:y 2 ) ``` [Try it online!](https://tio.run/##LcY9CsJAEAbQPqdYEMOOxfLtzsz@BCNpPUOIjUiMhXYSyeFXC1/1HrXOvWPTobHWQ1LWqECIqQRJKOpDkehZ131rS9y55fmeSAUKQQ7IhSHC4FwQhT2nlezY2c0NZzfY/uhoG@lAE126jwkN1dv1/jLzr/@0J7O4gPoF "J – Try It Online") 0-indexed; returns the n-th number Some bytes can be saved by making the verb tacit, but I have problems making `^:` work. ## Explanation: [J](http://jsoftware.com/) describes the rational numbers in the form NrD, where N is the numerator and D is the denominator, for example `17r91 78r85 19r51 23r38...` I created 2 separate lists for the numerators and denominators and made 2 base-96 numbers from them. `1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x` converts the base-96 numbers to lists and constructs a list of fractions by divinding the two lists. ``` 1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x 17r91 78r85 19r51 23r38 29r33 77r29 95r23 77r19 1r17 11r13 13r11 15r14 15r2 55 ``` `2` start with 2 `^:y` repeat the verb on its left `n` times (y is the argument to the function) `]` the right argument (starts at 2, and then uses the result of each iteration) `*` multiply the list of fractions by the right argument `(=<.)` are the results integer (compare each number with its floor) `{.@I.@` finds the index `I.` of the first `{.` of the integers `{[` uses the index to retrieve the number [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~44~~ 43 bytes 0-indexed ``` 2sF•Ë₁ǝßÌ?ƒ¥"h2ÔδD‡béαA5À>,•тв2ä`Š*s‰ʒθ_}нн ``` [Try it online!](https://tio.run/##AVQAq/8wNWFiMWX//zJzRuKAosOL4oKBx53Dn8OMP8aSwqUiaDLDlM60ROKAoWLDqc6xQTXDgD4s4oCi0YLQsjLDpGDFoCpz4oCwypLOuF990L3Qvf//NDA "05AB1E – Try It Online") **Explanation** ``` 2 # initialize stack with 2 sF # input times do: •Ë₁ǝßÌ?ƒ¥"h2ÔδD‡béαA5À>,• # push a base-255 compressed large number тв # convert to a list of base-100 digits 2ä` # split in 2 parts to stack Š # move denominators to bottom of stack * # multiply the last result by the numerators s‰ # divmod with denominators ʒθ_} # filter, keep only those with mod result 0 нн # get the div result ``` The large number pushed is `17781923297795770111131515559185513833292319171311140201` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 121 bytes ``` n->a=2;for(i=1,n,a=[x|x<-a*[17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55],x\1==x][1]);a ``` [Try it online!](https://tio.run/##HY6xDsIgFEV/hTgVc8nzgoSSSn@kdmCp6YJN48Dgv2PrcE7Odu@W99W8traopFoxY052WN57tyaiIKepfuvD5OvEIJEIvfQejOIJ68T1sFGcQwhiI6IX@29GUBjAww50QoJeeD9t4f2M@mRKdZ446yG3c7IcF25Q9mDb1/LpCtRFmVFdoJauaK3bDw "Pari/GP – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 106 95 bytes * thanks to @Arnauld and @Neil for reducing by 11 bytes ``` (n,N=2,I=13,B=Buffer(`[U3&! \r N M_M \r7`))=>n--?f(n,N/B.find(x=>N%x<!!++I)*B[I]):N ``` [Try it online!](https://tio.run/##ZczPC4IwAIZh7JiQiIdOHTwUW2rpNMxoBbt5aLdOFSnmoogt1g/8720eY9fn43vv5bd8VfL2fAdcXOqW4RZwn2Lk5ziKfYLJh7FaguKwjyfuaOjYR2kOeoZNneFod94Z5lFaVlpAiDc8CLase8/JjN34BTR4Q8fN2nU9L4dTcshPcEXbSvCXeNSzh7gCBiKIcbSA/X9FSpdI41hxqnPSNTLdF8oRSjWPMjUkWiXsNFzC9gc "JavaScript (Node.js) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 213 bytes ``` K`17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶2 \d+ * "$+"+`((_+)/(_+)¶(.+¶)*)(\3)+$ $1$#5*$2 r`_\G ``` [Try it online!](https://tio.run/##tYyxDUMhDER7xvihACzFMsgCT5AiKyB9IiVFmhRfmY0BWIxvlBnS3Onu2Xe8vu/Pg@a8N8ooNHouWHh0EmRNMWEqaoIpKcsYZXRhjL9Emggpq6ppRwlJ30gvFlHAjKv453g09QkmmM3CBs25HTwuGd1dYXQfvKvJgzWW7IWDjeZoe73NSXIC "Retina – Try It Online") Explanation: ``` K`17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶2 ``` Replace the input with a list of all the fractions, plus the initial integer. ``` \d+ * ``` Convert everything to unary. ``` "$+"+` ``` Repeat the substitution the number of times given by the original input. ``` ((_+)/(_+)¶(.+¶)*)(\3)+$ ``` Find a denominator that evenly divides the integer. ``` $1$#5*$2 ``` Replace the integer with the result of the division multiplied by the numerator. ``` r`_\G ``` Convert the integer to decimal and output the result. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 81 bytes ``` Nest<~{Find[Integral,_*&`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]]},2~> ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX73y@1uMSmrtotMy8l2jOvJDW9KDFHJ15LLUFf39bOOSO/INq/KKVYUcmgKrfEKMjM1cYhx6bOLMdIwUBLR0dLT1dPMUxBSdfYUMcoNrZWx6jODmhiakpxtEpBQXJ6LFdAUWZeSQjQDufE4tTi6DQdhWhTHQVDSx0FE4PY2P8A "Attache – Try It Online") Outputs a [fraction](https://codegolf.meta.stackexchange.com/a/9264/31957) over 1. For example, input `5` returns `2275/1`. This can be fixed with plus 2 bytes by prepending `N@` to the program. ## Explanation This is a curried function, which curries `Nest` with two predefined arguments: ``` {Find[Integral,_*&`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]]} ``` and `2`. This last argument is simply the initial seed, and the argument that is passed to this function is the number of iterations to nest the given function. The following is used to encode PRIMEGAME: ``` &`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]] ``` This is evaluated as such: ``` A> "0zmt2R6E<@l<~6l2 0*,,*.-.!V " "0zmt2R6E<@l<~6l2 0*,,*.-.!V " A> Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V " [48, 122, 109, 116, 50, 82, 54, 69, 60, 64, 108, 60, 126, 54, 108, 50, 32, 48, 42, 44, 44, 42, 46, 45, 46, 33, 86, 32] A> Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31 [17, 91, 78, 85, 19, 51, 23, 38, 29, 33, 77, 29, 95, 23, 77, 19, 1, 17, 11, 13, 13, 11, 15, 14, 15, 2, 55, 1] A> Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2] 17 91 78 85 19 51 23 38 29 33 77 29 95 23 77 19 1 17 11 13 13 11 15 14 15 2 55 1 A> &`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2] [(17/91), (78/85), (19/51), (23/38), (29/33), (77/29), (95/23), (77/19), (1/17), (11/13), (13/11), (15/14), (15/2), (55/1)] ``` Let's replace this expression with `G` in the explanation. Our first function becomes: ``` {Find[Integral,_*G]} ``` This performs a single iteration of FRACTRAN code over `_`, the input to the function. It `Find`s an `Integral` member (one which is an integer) of the array `_*G`, which is the input `_` multiplied with each member of `G`. `Nest` simply applies this transformation the given number of times. ## Attache, 42 bytes I implemented parts of the `$langs` library, being inspired by this challenge, so I mark this section non-competing. ``` Needs[$langs]2&FRACTRAN_EXAMPLES.prime.run ``` This simply queries the list of `FRACTRAN_EXAMPLES` I have. Each example is a `FractranExample` instance, which calls the inbuilt `FRACTRAN` function. The `prime` example is Conway's PRIMEGAME. [Answer] # [F# (Mono)](http://www.mono-project.com/), 215 bytes ``` let q m= let rec i x y= if y=m then x else[17;91;78;85;19;51;23;38;29;33;77;29;95;23;77;19;1;17;11;13;13;11;15;14;15;2;55;1]|>List.chunkBySize 2|>List.find(fun[n;d]->x*n%d=0)|>fun[n;d]->i(x*n/d)(y+1) i 2 0 ``` [Try it online!](https://tio.run/##bY7BasJAEIbvPsWPICQtanbXJVkGc@i5tx7Fk9nFpWY0JoKRvHs6EaFQCsPMNx/zw4R2WZ/5PI4n36FBvZ1hoqs/IOKOXnbEILNGd/QsSoQ/tX6ncnKK8oIKS8qRVaQNmYK0I2MozydwdpLCcqBIEkq6eZaA5DZT12QF90P5GdtudTje@Puj/4oPD/1yIXKVhBvvmKr9sry/8aLaZulQ/rqYiF1XadK/qxSQNyM0srGBxVDico3cBcZ8EeezBsr9IzfZXzn@AA "F# (Mono) – Try It Online") [Answer] ## PHP, 183 bytes (189 with "php" tag) Golfed : ``` $t=2;for(;@$i++<$argv[1];){foreach([17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1]as$n){$a=$t*$n;if(preg_match('/^\d+$/',$a)){$t=$a;break;}}}echo$t; ``` Ungolfed: ``` <?php $t=2; for(;@$i++<$argv[1];){ foreach([17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1] as $n){ $a=$t*$n; if(preg_match('/^\d+$/',$a)){ $t=$a;break; } } } echo $t; ``` [Try it online!](https://tio.run/##HY7bCsIwEER/xYcFW7uwbGJMQ1r0P7wRtTdEDTX4UvrtMfpyOAwDM773MVZb3/sFhFrY9jVmdgdDUVTgxu6z56PNp5Q27tpne9ZkGHVJpUI2pBiFJFmiMCQlak3CoFEk/s4GmVgjJ0pkSczIinj9o0CV9Oje8MwncDWEFTzt0GZ@bLrzw4U0t6TT4VYALRFcnlqhBmcv6crdzvPcXPsXBBtj3MQv "PHP – Try It Online") [Answer] # MMIX, 84 bytes (14 instrs + 28 data bytes) jxd (everything from `5b553326` (`[U3&`) on is data) ``` 00000000: e3010002 f7010000 5a000002 f8020000 ẉ¢¡£ẋ¢¡¡Z¡¡£ẏ£¡¡ 00000010: f402000a 83030200 1e040103 feff0006 ṡ£¡½³¤£¡œ¥¢¤“”¡© 00000020: 23020201 5bfffffc 8303020d 1a010304 #££¢[””‘³¤£Æȷ¢¤¥ 00000030: 27000001 f1fffff5 5b553326 211d1713 '¡¡¢ȯ””ṫ[U3&!øçŒ 00000040: 110d0b0e 0201114e 13171d4d 5f4d010b ׯ¿Ç£¢×NŒçøM_M¢¿ 00000050: 0d0f0f37 ÆĐĐ7 ``` Disassembly and explanation: ``` primegm SET $1,2 // i = 2 PUT rD,0 // prep for division 0H PBNZ $0,1F // loop: if(steps) goto pass POP 2,0 // return i 1H GETA $2,0F // pass: den = &denoms 1H LDBU $3,$2 // try: d = *den DIVU $4,$1,$3 // n = i / d GET $255,rR // r = i % d ADDU $2,$2,1 // den++ PBNZ $255,1B // if(r) goto try LDBU $3,$2,13 // d = den[13] (the numerator) MULU $1,$3,$4 // i = n * d SUBU $0,$0,1 // steps-- JMP 0B // goto loop 0H BYTE 91,85,51,38,33,29,23,19,17,13,11,14,2,1 // denoms: [BYTES] BYTE 17,78,19,23,29,77,95,77,1,11,13,15,15,55 // nums: [BYTES] ``` It's quite useful that every single numerator and denominator fits into one byte. Else I'd have needed to use much more space to fit them. ]
[Question] [ Sometimes it really is a struggle to convert Cartesian coordinates `(x,y)` to Polar coordinates `(r,phi)`. While you can calculate `r = sqrt(x^2+y^2)` quite easily, you often need some distinction of cases when calculating the angle `phi` because `arcsin`,`arccos` and `arctan` and all other trigonometric functions have a co-domain that each only spans *half* the circle. In many languages there are built-ins for converting rectangular to polar coordinates, or at least have an `atan2` function, which - given `(x,y)` - calculate the angle `phi`. ### Task Your task is to write a program/function that takes two (floating point, not both zero) Cartesian coordinates `(x,y)`, and outputs the corresponding polar angle `phi`, where `phi` has to be in degrees, radians or grades (with *grades* I mean *gradians* which are 1/400 of the full circle), whichever is more convenient for you. The angle is measured in positive orientation, and we have the zero angle for `(1,0)`. ### Details You may not use built-ins that calculate the angle `phi` given two coordinates, including `atan2`,`rect2polar`,`argOfComplexNumber` and similar functions. However you can use the usual trigonometric functions and their reverses, that only take one argument. Any unit symbols are optional. The radius `r` must be non-negative, and `phi` must be in the range `[-360°, 360°]` (it does not matter whether you output `270°` or `-90°`). ### Examples ``` Input Output (1,1) 45° (0,3) 90° (-1,1) 135° (-5,0) 180° (-2,-2) 225° (0,-1.5) 270° (4,-5) 308.66° ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` yYy/X;0G0<?_ ``` The result is in radians. [Try it online!](http://matl.tryitonline.net/#code=eVl5L1g7MEcwPD9f&input=MAoz) Or [verify all test cases](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICAgICAlIGxvb3AgdG8gcmVhZCBhbGwgaW5wdXRzCnlZeS9YOzBHMDw_XyAgICAgJSBBQ1RVQUwgQ09ERQpdRFQgICAgICAgICAgICAgICUgZW5kIGlmLCBkaXNwbGF5LCBjbG9zZSBsb29w&input=MQoxCjAKMwotMQoxCi01CjAKLTIKLTIKMAotMS41CjQKLTU). ### Explanation MATL doesn't have an `atan` function (it has `atan2`, but it can't be used for this challenge). So I resorted to `acos`. ``` y % Take x, y implicitly. Duplicate x onto the top of the stack Yy % Compute hypothenuse from x, y / % Divide x by hypothenuse X; % Arccosine (inverse of cosine function) 0G % Push y again 0< % Is it negative? ?_ % If so, change sign. Implicitly end conditional branch. Implicitly display ``` [Answer] ## JavaScript (ES6), ~~50~~ 40 bytes ``` (x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0) ``` The result is in radians. Edit: Saved 10 bytes when I noticed that it's allowed for the result to be between -90° and 270°. Previous version with `-Math.PI<=result<Math.PI`: ``` (x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0)*(y>0||-1) ``` [Answer] # MATLAB / Octave, 24 bytes ``` @(x,y)atan(y/x)+pi*(x<0) ``` This defines an anonymous function that produces the result in radians. [Try it on ideone](http://ideone.com/u9ePZD). [Answer] # Javascript ES6, 54 bytes ``` (x,y,m=Math)=>x<0&!y?m.PI:m.atan(y/(m.hypot(x,y)+x))*2 ``` Uses radians. [Answer] # Python 3, ~~75~~ 67 bytes 8 bytes thanks to Dennis. ``` from math import* lambda x,y:pi*(x<0==y)or atan(y/(hypot(x,y)+x))*2 ``` [Ideone it!](http://ideone.com/hWhW2j) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 10 [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") -2 thanks to ngn. Anonymous tacit infix function. Uses [alephalpha's formula](https://codegolf.stackexchange.com/a/122685/48198). Takes `x` as right argument and `y` as left argument. Result is in radians. ``` 11○∘⍟0J1⊥, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///39Dw0fTuRx0zHvXON/AyfNS1VOd/2qO2CY96@x71TfX0f9TVfGi98aO2iUBecJAzkAzx8Az@b6iQpmDIZQwkDbhA7EPrDbkMwLQp16H1RmCWEZBlqGcKVgMUB9ImAA "APL (Dyalog Unicode) – Try It Online") `,` concatenate the `y` and `x` `0J1⊥` Evaluate as base *i* digits (i.e. y*i*¹+x*i*⁰) `⍟` natural logarithm of that `∘` then `11○` imaginary part of that [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` <0רP+÷@ÆṬ¥ ``` Output is in radians. Jelly had a sign bug in its division atoms which was fixed. [Try it online!](http://jelly.tryitonline.net/#code=PDDDl8OYUCvDt0DDhuG5rMKl&input=&args=MQ+MQ) or [verify all test cases](http://jelly.tryitonline.net/#code=PDDDl8OYUCvDt0DDhuG5rMKlCsOnIsOGwrBH&input=&args=MSwgMCwgLTEsIC01LCAtMiwgICAgMCwgIDQ+MSwgMywgIDEsICAwLCAtMiwgLTEuNSwgLTU) (converted to degrees). ### How it works ``` <0רP+÷@ÆṬ¥ Main link. Left argument x. Right argument: y <0 Compare x with 0. רP Multiply the resulting Boolean by Pi. ¥ Combine the two links to the left into a dyadic chain. ÷@ Divide y by x. ÆṬ Apply arctan to the result. + Add the results to both sides. ``` [Answer] # Mathematica, 16 bytes I am not sure whether `Log` is considered as a built-in that calculates the angle given two coordinates. ``` N@Im@Log[#+I#2]& ``` ### Example: ``` In[1]:= N@Im@Log[#+I#2]&[1,1] Out[1]= 0.785398 In[2]:= N@Im@Log[#+I#2]&[4,-5] Out[2]= -0.896055 ``` [Answer] # x86 machine language (32 bit Linux), ~~25~~ 13 bytes (noncompeting) ``` 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: dd 45 08 fldl 0x8(%ebp) 6: dd 45 10 fldl 0x10(%ebp) 9: d9 f3 fpatan b: c9 leave c: c3 ret ``` To [try it online](https://tio.run/nexus/c-gcc#VYzRaoMwGIXvfYqDZZB0UVZDocO6uz3CrpZdpNFEi8ahKQijr74sme1F4f/PORw@zqazqr/UzXF2dTfm7VuyuTeDdG0ovBrt7KBaOeH8@VWlH2I5vIql2QvO9@/itFrxIpY61JqLRQVXPC2TzjoMsrOE/iSAHieCeryc@ga6ynYl9DHKc5XvQBGRR8igQsRMxMwDBnxPYV0TpE95obFKPGFTBs1gGKSTtiAxUwZC1lWypbfEVqP0TANkKGj5v31N4l@9/1W6l2b2WT/4bODFHw "C (gcc) – TIO Nexus"), compile the following C program (don't forget `-m32` flag on x86\_64) ``` #include<stdio.h> #include<math.h> const char j[]="U\x89\xe5\335E\b\335E\20\xd9\xf3\xc9\xc3"; int main(){ for(double f=-1;f<1;f+=.1){ for(double g=-1;g<1;g+=.1){ printf("%.2f %.2f %f %f\n",f,g,atan2(f,g),((double(*)(double,double))j)(f,g)); } } } ``` [Answer] # [J](http://jsoftware.com/), 10 bytes Anonymous tacit infix function. Uses [alephalpha's formula](https://codegolf.stackexchange.com/a/122685/43319). Takes `x` as left argument and `y` as right argument. Result is in radians. ``` 11 o.^.@j. ``` [Try it online!](https://tio.run/##y/r/P83WytBQIV8vTs8hS@//f0OFNAVDLgMgacwVD@HEmwIpA654IyAVbwSWizfUM@UyATFMAQ "J – Try It Online") `j.` calculate `x` + `y`×*i* `@` then `^.` natural logarithm of that `11 o.` imaginary part of that [Answer] # Pyth, 26 bytes ``` AQ?|>G0Hy.tcH+@s^R2Q2G5.n0 ``` `theta` in radians. [Test suite.](http://pyth.herokuapp.com/?code=AQ%3F%7C%3EG0Hy.tcH%2B%40s%5ER2Q2G5.n0&test_suite=1&test_suite_input=%281%2C1%29%0A%280%2C3%29%0A%28-2%2C-2%29%0A%28-2%2C0%29%0A%282%2C0%29&debug=0) [Answer] # 𝔼𝕊𝕄𝕚𝕟, 13 chars / 17 bytes ``` î<0)*π+МǍ í/î ``` `[Try it here (ES6 browsers only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B-5%2C0%5D&code=%C3%AE%3C0)*%CF%80%2B%D0%9C%C7%8D%20%C3%AD%2F%C3%AE)` Uses `(x<0)*pi+tan(y/x)`. [Answer] # Python 3, 65 bytes ``` from math import* f=lambda x,y:atan(y/x if x else y*inf)+pi*(x<0) ``` This outputs radians in the range `[-π/2, 3π/2)`, equivalent to `[-90, 270)` degrees. [Answer] # Axiom, 58 bytes ``` f(a,b)==(a=0 and b=0=>%i;sign(b)*acos(a*1./sqrt(a^2+b^2))) ``` test (i use only acos() it returns radiants ) ``` (40) -> [[a,b,f(a,b)*180/%pi] for a in [1,0,-1,-5,-2,0,4] for b in [1,3,1,0,-2,-1.5,-5] ] (40) [[1.0,1.0,45.0], [0.0,3.0,90.0], [- 1.0,1.0,135.0], [- 5.0,0.0,180.0], [- 2.0,- 2.0,- 135.0], [0.0,- 1.5,- 90.0], [4.0,- 5.0,- 51.3401917459 09909396]] Type: List List Complex Float ``` [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda x,y:acos(x/hypot(x,y))/(-1,1)[y>0] from math import* ``` [Try it online!](https://tio.run/##TczRDoIgGIbhc6@CzRNooIBi1lY3Uh1QzeEmwogDuXqqMcX/8PnffTZ4ZWYeh8s9TlI/3xIsOJzly3zgUqtgjYc/QKiGhGGGbuFKH8XgjAZaegVGbY3zh2jdOHswwH8D0pWtKFamuNn4RDcmOS9Zk3MiMN283/UcE54eJef7ecIqgZIfc99iItadhvZV18Uv "Python 2 – Try It Online") Outputs in radians in range `[-pi,pi)` ]
[Question] [ Since I've been seeing more [><>](http://esolangs.org/wiki/Fish) submissions floating around lately, I thought it might be a good idea to have a tips page. Please stick to one tip per post, unless they are closely related. [Official Python interpreter](https://gist.github.com/anonymous/6392418) [Official Interpreter on TIO](https://tio.run/#fish) [Online interpreter](https://suppen.no/fishlanguage/) (some bugs present, but good for most cases) [Another Online Interpreter](https://mousetail.github.io/Fish/) [Answer] # Checking against 0 Using `?!` instead of `0=?` typically saves a byte. However, just a standard `?` may sometimes be better if you can afford a bit of restructuring ``` ?!vA B ``` versus ``` ?vB A ``` [Answer] # Checking for EOF When EOF is reached, ><> pushes a -1 onto the stack, which can be checked in one of two ways: ``` :0(? :1+? ``` For the purposes of checking for EOF, these two are negations, so which one is more beneficial depends on the structure of your program. [Answer] # Jump to circumvent starting new lines Starting a new line sometimes means wasting a lot of leading whitespace on the next line. In such a situation, jumping can be useful. For instance, ``` [lots of code here]>[loop body]v ^ ......... < ``` can be made to fit on one line like so: ``` [lots of code here][loop body][jump] ``` For a practical example, here's the Hello World program on one line: ``` "!dlroW ,olleH"l?!;oe0. ``` [Answer] ## Using jumps as a conditional Some times you'll wind up writing programs in ><> that require you to do different things upon receiving different inputs. Usually, you'd use conditionals (`?`) and direction changers to parse this. In some cases, that works fine (especially when there are fewer types of input to handle), but sometimes you end up with something looking like this. (Ignore the fact that this code can be reduced using some other tricks, it's just for demonstration) ``` i:"a"=?v:"b"=?v"c"=?v> .00n1< .00n2<.00n3< ``` While this is fine, it does have some whitespace (which I personally never like seeing) and it has a lot of repetition (`=?v` and `.00n`). Instead of that, you could use a jump and different lines as your conditionals. Here's an example: ``` i:"a")$"b")+1+0$.> v1 v2 v3 <.00n ``` This shaves 10 bytes off. Here's what's happening: `i:` We duplicate the input once so we can evaluate it twice `"a")$"b")+` This could be its own sort of tip, but what I'm doing here is checking to see if the input is greater than the character "a" and then if it's greater than the character "b" and adding the result. For "a," this will yield 0, for "b," 1, and for "c," 2. `1+0$.` This is where the magic happens; we take the result of this previous simplification and add 1 (giving 1 for "a", 2 for "b", 3 for "c"), then push 0 and swap the values. When we reach the jump, this will move to the line corresponding to the value we've assigned to those characters (e.g. line 1 for "a"). N.B. Line 0 is the top of the program. [Answer] ## Using modulus to simplify input This might be too simple of a tip, so if it is I'll just replace it or delete it. Let's say you want to take input of two characters, "a" and "b" and return 1, and 2 for each, respectively. You'd probably use conditionals for this, since it makes the most sense, and I'll be using a more condensed form for this specific example. ``` i:"a")+1+n ``` This checks to see if the input is greater than "a" and adds 1. Since "a" will return 0 and "b" 1, this will give 1 and 2. This does the job pretty well, but in the case of our inputs, we could go even further. ``` i:3%n ``` In mod 3, 97, which is "a"s numerical equivalent, becomes 1, and 98, which is "b"s, becomes 2. For two different numbers, there is guaranteed a mod which gives unique results for both. For more than two, there is a mod that gives unique results, but I don't have the mathematical prowess to find the smallest one in a simple way (e.g. if you have the set {100,101,102,103}, mod 104 would give unique results for each value in it but not in a very helpful fashion). However, in most cases, with input being restricted to a couple alphabetical characters, you can often find a mod that works. To find the smallest modulus that yields unique results for two numbers, a, and, b, you do as follows. Take the absolute value of the difference of a and b (`|a - b|`) and find the smallest number, n, which does not divide it. e.g. for 97 and 98, `|98 - 97| = 1`, and so 2 would be the smallest mod (but for our test program, this gives 1 for 97 and 0 for 98, so mod 3 is better). [Answer] # Writing code that can run two ways Trampolines (`!`) are very handy when you want your code to be run forwards and backwards (or up and down). These scenarios are somewhat unlikely, but for palindrome or similar challenges this tip could be useful. Here's an example: I want to run some code once, then loop through the stack discarding values until I reach 0, and then go down. The pointer enters this loop from the `>`. You could use a jump to accomplish this, e.g. `?!v80.>ao` (let's say I want to print a newline first) but if the code we want to run once (the code past the `>`) makes the line longer than 16 characters, we no longer can use the jump in three characters. However, this is an example where it is trivial to run forwards and backwards... `?!v!?<>ao>` Going forwards, we print a newline and then hit `?!v` which discards the value if it it isn't 0, then because of the trampoline we skip the next `?` and go backwards. The same thing happens and the loop continues until we hit a 0. This is an oddly specific example, but there are some (perhaps not many) applications. [Answer] ## Use char codes to store big numbers and use `g` to use them more than once Typically, you'd encode a large number as a char code, for example if you need `1001` you might write `'ϩ'` In utf-8 this character is encoded as 2 bytes. If you need this number again you can use `[coordinates]g` to get the char code at that position. This saves 1 byte as long as the character is in the 16 by 16 top left square. For example ``` 'ϩ'o'ϩ'o; ``` vs ``` 'ϩ'o10go; ``` Same number of characters but 1 byte shorter [Answer] # Use the code as infinite length array You can store values in the source code area with the `g` and `p` commands. For example, you could use the 7th row as a array and access it like this: `i3g` This is significantly shorter than if you used the stack: `i[{:}]` The stack has a additional disadvantage is you need to compensate for any other data you want on the stack. The code box is always accessible regardless of the state of your stack. You can also easily create multiple arrays, or even a 2-dimentional array this way. You don't even need to keep the row free, ><> will automatically add rows or columns when you write to them. You can read and write any number, even those not normally valid in source code, like line breaks and floating point numbers. This is a valid program that prints `0.5`: ``` 12,00p00gn; ``` Even if there is no character "0.5". This does not seem to work the same for strings. [Answer] # Use `i` as a shorthand for `-1` for programs that take no input, or after the input is exhausted Pusing `-1` is always a bit tricky, requiring `01-` (3 bytes). However, the `i` command pushes `-1` if there is no input. This can save 2 bytes. For example to invert a number normally requites `0$-` (3 bytes) but if you don't take input you can do `i*` (2 bytes) ]
[Question] [ Welcome to the world of compiler golf. Your task is to write a program that generates another program to play a variant of FizzBuzz on spec. # Your compiler Write a compiler that generates variants of the FizzBuzz program to spec. The spec of this variant is expressed in the form of an array of integer/string pairs. * The input may be in any form that is convenient to your language. (My examples use n:xxxx, but this is just for illustrative purposes.) * Each integer input may only be used once per invocation of your compiler. * The integer of each pair will have a value of at least one. * The string of each pair will be made of only exactly four ASCII letters. * The output must be a single complete program that conforms to the rules below. * The output may be in any convenient form, as long as it is a textual program. (So no returning lambda expressions.) Behavior is undefined for inputs not conforming to the above rules. # Your generated FizzBuzz program The program generated by your compiler will take a single integer, *n*, as input. It will output a sequence of numbers starting from one up to and including *n*, replacing numbers with FizzBuzz strings when required. * The generated program must be in the same language as the compiler. * The input *n* may be in any form convenient to your language. * *n* will have a value of at least one. * A number that is a multiple of at least one of the integers input to the compiler must be replaced by all of the strings paired with those integers joined together. * A number that is not to be replaced by a FizzBuzz string must be output in decimal ASCII. For example; ``` > GenFizzBuzz 3:Fizz 5:Buzz > a.out 5 1 2 Fizz 4 Buzz ``` # Scoring Your entry will be scored by the length of the programs your compiler generates added to the length of your compiler. Run your compiler many times with each the following parameters and add the lengths of the generated programs together with the length of the compiler to find your score. 1. Just Count. (No inputs - The generated program will count 1 to *n* without replacements.) 2. Just Golf. (1:Golf - The generated program will output "Golf" *n* times.) 3. Classic FizzBuzz. (3:Fizz, 5:Buzz) (Note that your compiler is required to generate code for any valid input, not just these listed.) [Answer] # Python 3 - 168 162 + 230 = 392 Oh, Python, you try so hard, but multiplying the `import sys;sys.argv` stuff by 4 really hurts! ``` import sys;a=eval(sys.argv[1]) print("import sys\nfor i in range(1,int(sys.argv[1])+1):print("+"+".join('"%s"*(i%%%d==0)'%t for t in a)+(a and"or str(i))"or"i)")) ``` Output programs: ``` import sys for i in range(1,int(sys.argv[1])+1):print(i) import sys for i in range(1,int(sys.argv[1])+1):print("Golf"*(i%1==0)or str(i)) import sys for i in range(1,int(sys.argv[1])+1):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or str(i)) ``` * Expected input for the main program is an eval-able sequence of Python tuples or `'()'` for no input. (You did say "convenient".) Example input: `'()'`, `'("Golf",1),'`, `'("Fizz",3),("Buzz",5)'` Note quoting for shell and trailing comma for one input. * Fixed 1am mistake by changing from dict (undefined ordering!) to tuples. * Expected input for the other programs is just the number [Answer] # perl6 376 340 84+115=199 UPDATE: switched from perl5 to perl6 to get `say` without `use feature`. UPDATE: three test cases instead of five There are hundreds of already-golfed solutions to FizzBuzz, and many contests end with the same result, so that's where I started. My compiler just produces a customized version of that solution. A few extra characters were inserted to account for the "just count" variation. compiler, expects arguments like so: "Fizz 3" "Buzz 5" ``` print'say(('.(join'.',map{'('.(join')[$_%',split).']'}@ARGV).')||$_)for 1..$ARGV[0]' ``` compiled programs, expect argument like so: 100 ``` say(()||$_)for 1..$ARGV[0] say(((Golf)[$_%1])||$_)for 1..$ARGV[0] say(((Fizz)[$_%3].(Buzz)[$_%5])||$_)for 1..$ARGV[0] ``` compiled programs for old test cases: ``` say(((Twoo)[$_%2].(Four)[$_%4].(Eiht)[$_%8])||$_)for 1..$ARGV[0] say(((Twoo)[$_%2].(Thre)[$_%3].(Five)[$_%5].(Sevn)[$_%7])||$_)for 1..$ARGV[0] ``` [Answer] # Pyth - 51 + (38 + 43 + 50) = 182 bytes Can probably golf the compiler a few bytes. The links on all of them are permalinks to the online interpreter. ### [Compiler](http://pyth.herokuapp.com/?code=%25%22K%5B%25s)%3Ddc%5C%22%25s%5C%22dFGr1hQJkFNKI!%25%25GN~J%40dxKN))%3FJJG%22%2Czw&input=3%205%0AFizz%20Buzz) - 51 bytes ``` %"K[%s)=dc\"%s\"dFGr1hQJkFNKI!%%GN~J@dxKN))?JJG",zw ``` Just does string formatting with an input tuple. Takes input like: ``` 3 5 Fizz Buzz ``` ### [Nothing](http://pyth.herokuapp.com/?code=K%5B)%3Ddc%22%22dFGr1hQJkFNKI!%25GN~J%40dxKN))%3FJJG&input=20) - 38 bytes ``` K[)=dc""dFGr1hQJkFNKI!%GN~J@dxKN))?JJG ``` ### [Just Golf](http://pyth.herokuapp.com/?code=K%5B1)%3Ddc%22Golf%22dFGr1hQJkFNKI!%25GN~J%40dxKN))%3FJJG&input=20)- 43 bytes ``` K[1)=dc"Golf"dFGr1hQJkFNKI!%GN~J@dxKN))?JJG ``` ### [Classic Fizz Buzz](http://pyth.herokuapp.com/?code=K%5B3%205)%3Ddc%22Fizz%20Buzz%22dFGr1hQJkFNKI!%25GN~J%40dxKN))%3FJJG&input=20) - 50 bytes ``` K[3 5)=dc"Fizz Buzz"dFGr1hQJkFNKI!%GN~J@dxKN))?JJG ``` [Answer] ## Common Lisp, ~~636~~ 577 ``` (ql:quickload'cl-ppcre)(lambda(z)(princ(subseq(ppcre:regex-replace-all" *([(')]) *"(with-output-to-string(@)(print`(lambda(n)(dotimes(i n)(loop for(m s)in ',z if(=(mod(1+ i)m)0)do(princ s))(do()((fresh-line))(princ (1+ i)))))@))"\\1")1))) ``` I took [my other answer](https://codegolf.stackexchange.com/a/58685/903) and wrapped it in quasiquotes while adding input parameters. I print the resulting form as a single-line and remove unnecessary whitespace characters. The compiler is a little longer than the previous version, but the resulting score is reduced. ### Score ``` (let ((*standard-output* (make-broadcast-stream))) (loop for form in '(215 ; Compiler () ; Count ((1 "Golf")) ; Golf ((3 "Fizz")(5 "Buzz"))) ; FizzBuzz for length = (if (numberp form) form (length (funcall *fun* form))) collect length into lengths sum length into sum finally (return (values sum lengths)))) ``` Returned values: ``` 574 (215 111 119 129) ``` ## Pretty ``` (defun fizz-buzz-compiler (z) (princ (subseq (cl-ppcre:regex-replace-all " *([(')]) *" (with-output-to-string (stream) (print `(lambda (n) (dotimes(i n) (loop for (m s) in ',z if (=(mod(1+ i)m)0) do (princ s)) (do () ((fresh-line)) (princ (1+ i))))) stream)) "\\1") 1))) ``` The input format is a list of `(number string)` couples. For example: ``` (fizz-buzz-compiler '((3 "Fizz")(5 "Buzz"))) ``` ... prints to standard output: ``` (LAMBDA(N)(DOTIMES(I N)(LOOP FOR(M S)IN'((3 "Fizz")(5 "Buzz"))IF(=(MOD(1+ I)M)0)DO(PRINC S))(DO NIL((FRESH-LINE))(PRINC(1+ I))))) ``` ... which, pretty-printed, is: ``` (lambda (n) (dotimes (i n) (loop for (m s) in '((3 "Fizz") (5 "Buzz")) if (= (mod (1+ i) m) 0) do (princ s)) (do () ((fresh-line)) (princ (1+ i))))) ``` Testing the resulting function: ``` CL-USER> ((lambda (n) (dotimes (i n) (loop for (m s) in '((3 "Fizz") (5 "Buzz")) if (= (mod (1+ i) m) 0) do (princ s)) (do () ((fresh-line)) (princ (1+ i))))) 20) 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 23+5+17+29=74 ``` ╥╟.└ç╘SJ∞CF╔v=▌╝Σ@∞ìé«g ``` [Run and debug it](https://staxlang.xyz/#p=d2c72ec087d4534aec4346c9763dddbce440ec8d82ae67&i=[]%0A[[1,%22Golf%22]]%0A[[3,%22Fizz%22],[5,%22Buzz%22]]&a=1&m=2) ~~Shortest answer so far~~ Not surprisingly beaten by Jelly. The string template provided in Stax is really neat and provides printf-like functions. The programs generated by the compiler are almost always as short as the best one can achieve by manually codegolfing, without using packing. The compiler itself is 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) long. The ASCII equivalent is: ``` {H34|S_h"_`c%z`n?+"m"mz`cc_? ``` Provided input `[]`, generates this one (5 bytes) ``` mzc_? ``` [Run and debug it](https://staxlang.xyz/#c=mzc_%3F&i=100&a=1) Provided input `[[1,"Golf"]]`, generates this one (17 bytes) ``` mz_1%z"Golf"?+c_? ``` [Run and debug it](https://staxlang.xyz/#c=mz_1%25z%22Golf%22%3F%2Bc_%3F&i=100&a=1) Provided input `[[3,"Fizz"],[5,"Buzz"]]`, generates this one (29 bytes) ``` mz_3%z"Fizz"?+_5%z"Buzz"?+c_? ``` [Run and debug it](https://staxlang.xyz/#c=mz_3%25z%22Fizz%22%3F%2B_5%25z%22Buzz%22%3F%2Bc_%3F&i=100&a=1) [Answer] # Ruby 99 + (86 + 94 + 103) = 382 ``` puts"(1..ARGV[0].to_i).each{|i|x=[];#{ARGV[0]}.each{|k,v|x<<v if i%k==0};puts x.size>0?x.join():i}" ``` Usage: ``` wc -c main.rb # 99 chars ruby main.rb "{}" | ruby - 100 # 1..2..3.. ruby main.rb "{}" | wc -c # 86 chars ruby main.rb "{1=>:Golf}" | ruby - 100 # Golf..Golf..Golf.. ruby main.rb "{1=>:Golf}" | wc -c # 94 chars ruby main.rb "{3=>:Fizz,5=>:Buzz}" | ruby - 100 # 1..2..Fizz..4..Buzz.. ruby main.rb "{3=>:Fizz,5=>:Buzz}" | wc -c # 103 chars ``` [Answer] # C, 1080 bytes total **# Compiler [369 bytes]** ``` #include<stdlib.h> r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);} ``` **# Fizz Buzz [241]** ``` #include<stdlib.h> r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);} ``` **# Golf [237]** ``` #include<stdlib.h> r,t,f=1,b=0,n;char*F="golf",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);} ``` **# Count [233 bytes]** ``` #include<stdlib.h> r,t,f=0,b=1,n;char*F="",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~88~~ ~~84~~ ~~83~~ 73 bytes Shortest answer so far (beats [the previous "shortest answer"](https://codegolf.stackexchange.com/questions/35459/create-a-fizzbuzz-compiler/161175#161175) by 1 byte) Compiler: ``` Ṿ€“ḍ@€“ẋ"ЀF€ȯ"”jµFF?⁾RY ``` [Try it online!](https://tio.run/##y0rNyan8///hzn2PmtY8apjzcEevA5S1q1vp8AQg2w2IT6xXetQwN@vQVjc3@0eN@4Ii////Hx1trGMaqxOt7pZZVaWuo@5UCqRiYwE "Jelly – Try It Online") (compiler) [Try it online!](https://tio.run/##bZHLasJAGIX38xQ/sRAFFWyxtWDvNAURCm1dFCsSk9FE4kzITGqULmy3UujSQvsGha4KvYCLuulrmBexk8QLtQaGzPyc8805SU1lxmQSA5dhHTgFjZJr7HCoO7QFpQslBw62Hcww4So3KQk0KAYFbFkdIdaxrTbwkgZpKod8HuTjU0WG3ZCZZgZqhibsgjwaFMzRg3/3QjPrOb/3qGc2/d5g/NUfDQwZ1uICkIAb8DwdUjakHCRICDFjhvpLb9mmhR00/hgKot97Gr/f7093n30pvEcR6@dV8nvPze83Rdnzb4dnlxE1BgxzoC63XR60i6q1RDWEPZuKb1E8qh4UizuYVEvnaZPRXC67nUHTOvV5AJDK5Y1ktpIsy4rZ7cpJ@dAVr0pFEinrYlITx5UuYYlUGnUJXynJBNgTatWnvIbY/s8e/rAgOsQZBYLblkkwA91ktqV2QGXCMZ@qRAdCOVx5W0piZdcAN@9JwjsheLKLWZh4aTbrKmaorUFKWzQJEZFnpppMfgE "Bash – Try It Online") (verify the bytecount) --- Statistics: ``` ~~19~~ 24 compiler 20 golf ~~17~~ 2 count 27 fizzbuzz ~~83~~ 73 total ``` [Answer] # C++11 ~ 486 + (234 + 244 + 255) = 1219 First participation here, this challenge is not among the most difficult ones so I thought I'd give it a try. Using C++ though, and even with C++11 additions it is still a pretty verbose language, but I'm sure there's room for improvement. ### Compiler (486): ``` #include<sstream> #include<iostream> using namespace std;main(int c,char**v){stringstream t;int i;string s,o;o="#include <iostream>\n#include <map>\nusing namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{";int z=2;for(int j=1;j<c;++j){t.str(v[j]);t.clear();t >> i; t >> s;o+="{"+to_string(i)+",\""+s+"\"}"+(z++==c?"":",");}o+= R"(};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}})";cout<<o;} ``` It assumes arguments in the form of `3Fizz 5Buzz` etc. ### Count (234): ``` #include <iostream> #include <map> using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}} ``` ### Golf (244): ``` #include <iostream> #include <map> using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{{1,"Golf"}};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}} ``` ### FizzBuzz (255): ``` #include <iostream> #include <map> using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{{3,"Fizz"},{5,"Buzz"}};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}} ``` ### Additional information Tested with GCC 4.8.1, no compiler cheats. Here is a small makefile to automate the generation of the test cases and run them (use `make run`): ``` run: g++ main.cpp --std=c++11 -o fbc ./fbc > count.cpp g++ count.cpp --std=c++11 echo "======= Count ========" ./a.out 15 ./fbc 1Golf > golf.cpp g++ golf.cpp --std=c++11 echo "======= Golf ========" ./a.out 15 ./fbc 3Fizz 5Buzz > fizzbuzz.cpp g++ fizzbuzz.cpp --std=c++11 echo "======= FizzBuzz ========" ./a.out 15 ``` [Answer] # [Perl 5](https://www.perl.org/), 77 + 93, 170 bytes ``` say"say",(map{++$i%2?"'$_":"'x!(\$_%$_)".($i<$#F?'.':'||$_')}@F),' for 1..<>' ``` [Try the compiler online!](https://tio.run/##FcXBCoIwGADgu0@x1i//hjpcsYtZRod16g2CsUPCwNzQgjJ79VYdPr5wGToVwW3LTRztk/7l7GrDK8vApauGIhhaUXws2BlMCoZTwcDVsNQNCqxwnsEgf@81z5G0fiBSiHqHMSZH37VEJtpNE1mTw/2X@vhwc74fY9HbWJyUKGX5BQ "Perl 5 – Try It Online") [Try just count online!](https://tio.run/##K0gtyjH9/784sVIhLb9IwVBPz8aO6/9/03/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Try just golf online!](https://tio.run/##K0gtyjH9/784sVLdPT8nTb1CUUMlXtVQs6ZGJV4hLb9IwVBPz8aO6/9/03/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Try fizz buzz online!](https://tio.run/##K0gtyjH9/784sVLdLbOqSr1CUUMlXtVYU0/dqRTONdWsqVGJV0jLL1Iw1NOzseP6/9/0X35BSWZ@XvF/XV9TPQNDAwA "Perl 5 – Try It Online") [Answer] # vim, 122 (compiler) + 73 (empty) + 90 (golf) + 123 (fizzbuzz) = 392 bytes ## Compiler ``` :%s/\v(.*):(.*)/qq\1jA\2<C-V><C-V><C-V><ESC>q=@qgg VgggJAddGdd:%s/\v[0-9]*([^0-9])/\1 <C-V><ESC>:%@n :w :so! % <ESC>ggii%s/=/<C-V><ESC><C-V><C-A>a/g<C-V><ESC>"ncc:%!seq 0 = <ESC> ``` ## Input format ``` 3:Fizz 5:Buzz ``` ## Generated code for FizzBuzz case ``` i%s/=/<ESC><C-A>a/g<ESC>"ncc:%!seq 0 = qq3jAFizz<C-V><ESC>q=@qggqq5jABuzz<C-V><ESC>q=@qggddGdd:%s/\v[0-9]*([^0-9])/\1 <ESC>:%@n :w :so! % ``` ### Generated Code, Annotated ``` # replace the input number with a regex that replaces the placeholder (=) # with the real number + 1 (we'll need an extra line as a terminator later) i%s/=/<ESC><C-A>a/g<ESC> # pull the substitution command into register c and enter insert mode "ncc # create the numbers 0..N+1 :%!seq 0 = # for each word, scan down k lines at a time and append the word to each qq3jAFizz<C-V><ESC>q=@qgg qq5jABuzz<C-V><ESC>q=@qgg # delete the 0 and N+1 lines ddGdd # remove the numbers from any line with words :%s/\v[0-9]*([^0-9])/\1 <ESC> # Run the command we created at the beginning, replacing the placeholder # with the real number :%@n # The file now contains yet another program, with the constants defined. # Save and run. :w :so! % # The file now contains a program that, when run on a buffer containing # a single line with a number, will produce the appropriate output ``` `<C-V>` is 0x16. `<ESC>` is 0x1b. `<C-A>` is 0x01. # Example session ``` $ cat code.txt 2:Foo 4:Bar $ cat input.txt 8 $ { cat compile.vim; echo ':wq'; } | vim code.txt # code.txt now contains the generated code $ { cat code.txt; echo ':wq'; } | vim input.txt $ cat input.txt 1 Foo 3 FooBar 5 Foo 7 FooBar ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 434 bytes ``` [:a]sa[91Pn93Pznlanps_znlanz0<R]sR[[[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sP]P]sI[[[]sF[pq]sP]nq]sN[z0=Nzn[sz]PlRxlIx]x[sn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx]P ``` [Try it online!](https://tio.run/##HYzBCoMwEAW/picpRKUHaxXqIeBB2XpdlpI0l4YlWJZCyM@nqZc3MDDPvXKL@p0SXXD6FmS8GhKDXQ2hayEFNmGX58GkbhvJhojs63NvoBZLMinx6Ni7phLfm5MaJvacRk2icW8eJEBAMpfsMJ@/CGVXTGpYU0BJBLxFniNFlKCcWKyrcss6Ils1wB0oKrGOw7iQkyUS5PwD "dc – Try It Online") Input for the compiler (168 bytes) should be placed on the stack as integer, string, integer, string, and so on (`3 [Fizz] 5 [Buzz]`). It should be given in the order one wants their fizzes and buzzes to be printed, which may be a bit of a cheat (having implemented bubble sort in `dc` before, I believe it would cost me around 100 bytes) but it also allows the user to, say, still have 'Fizz' run on 3 and 'Buzz' run on 5, but have 15 yield 'BuzzFizz'. I'm sure this can be golfed a bit more; the main macro in the final program (`M`) relies on two macros (`F` and `P`) that are rather unnecessary given no input. Right now the compiler checks for input and outputs different (much smaller) versions of these macros if there is none, but I'm not sure the whole setup is optimal. The compiler itself is pretty straightforward, it just checks to see if there are 'rules' on the stack, and if so it prints code that stores the stack depth in `z`, stores the stack in a 0-indexed array `a`, and then prints the generalized FizzBuzz code. If there was nothing on the stack, it really just prints a modified version of the FizzBuzz code. Test cases: [No input (46 bytes):](https://tio.run/##S0n@b2T6Pzq22C26oDC2OKA4zyClOCnaUNugOCvHrSI6J8nANsAxILbCoDgpJSfPzjc2pdi34v9/AA "dc – Try It Online") ``` []sF[pq]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx ``` [3[Fizz]5[Buzz] (117 bytes):](https://tio.run/##DcqxCsMgEADQPf/RKRRO0yyGBOrgFrDzcYP2lsoRCkdB/Hnr@ODxu9u1P7Sh/7VGi0vrZF3C8BkyLi0TDEkx9y1Fo5nUgxZkKWxnLVu6we6lSDsCacCvfZFGvYA1o5lHlVBRMuzxGamCZpbrOIn1rL3/AQ "dc – Try It Online") ``` 4sz[Buzz]3:a5 2:a[Fizz]1:a3 0:a[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx ``` [1[Golf] (103 bytes):](https://tio.run/##DcqxCsIwEAbg3fdwKsIl4NLSgh3SqRDn44bEw@E4qvAvoS8f/eZPXz3ee8TJ28ffEsYSLjQWdgu3qeSAKlgJxuqmcYBN5Urz6ubnkgSJv/EpyDhIUTkM/@qpsVea8yNLI1T1Y9lFsbfefw "dc – Try It Online") ``` 2sz[Golf]1:a1 0:a[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx ``` They all expect the *n* value on the stack, this gets stored in `n`. The ones that have 'rules' place them in the array `a`, with the strings at odd indices and the integers at evens. The main macro, `M`, increments whatever is on the stack, runs macro `F` which checks the value against array `a`, checks whether `F` set register `b` to truthy or not and prints the top of stack if so or a newline if not, resets `b` to falsy, and then keeps running itself if `n` hasn't been reached yet. Macro `F`, given rules, goes through the whole array looking for matches. It increments by two since our integers and strings are woven through the array, and on a match it calls macro `B`. Macro `B` just retrieves the string (current position in array less one), and prints it. It also sets `b` to truthy. Our compiler doesn't bother to print `B` for no input, and essentially makes `F` a nop. [Answer] # SlooSarksi .Lang, 179 ``` %%--43^jjk"/][][0[#!#111# h SD G ergDFGdfg[]9--99+== ``` ]
[Question] [ ## Introduction Dice 10,000 is a dice game which can be played with 6 dice and something to write. Players roll the dice multiple times a turn and gain a score at the end of it. The player who reaches 10,000 point first wins the game. Calculating the score of one roll is your job in this challenge. [Look here](https://en.wikipedia.org/wiki/Dice_10000) for the full rules. *Please note that the rules (especically the scoring) change from region to region since the game is widely known. We use the rules descibed below.* ## The Challenge Given a list of six numbers from one to six representing a dice roll, output their score. The score is calculated in the follwing way: * Ones counts **100** points * Fives counts **50** points * Triplets count their number **times 100** points. Three twos for example give 200 points. An exception are three ones which count **1000** points. * Six of the same number count like two triplets as described above. So six threes give 600 points. The same goes for the edge case with the ones: Six ones are 2,000 points. * One die can't be used more than once. If a die is part of a triplet, it does not count for other scorings. The fives in a triplet do **not** count 50 points in addition to the 500 points they give. * Triples are always counted first to maximize the score. So three fives are never counted as 150 points. Four fives are counted as one triplet and one ordinary five which then gives 550 points. ### Notes * The input will always contain six numbers from one to six. You will not recieve invalid input. * The numbers can be in any order. You may not assume any specific ordering. # Rules * Input format is up to you as long as it's not preprocessed. * Function or full program allowed. * [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. # Test cases ``` [1, 2, 3, 4, 5, 6] -> 150 [1, 1, 1, 2, 3, 5] -> 1050 [1, 1, 1, 1, 1, 1] -> 2000 [2, 2, 2, 2, 2, 2] -> 400 [6, 6, 1, 5, 5, 6] -> 800 [2, 3, 4, 6, 2, 4] -> 0 [1, 5, 1, 5, 1, 5] -> 1500 [5, 5, 5, 5, 2, 3] -> 550 [1, 1, 1, 1, 1, 5] -> 1250 [3, 3, 4, 4, 3, 4] -> 700 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~34~~ ~~31~~ 30 bytes ``` 7G¹N¢O3‰N*2LRN1Q+°*X5‚Nå_i¨}OO ``` **Explanation** ``` 7G # for N in 1..6 ¹N¢O # count number of occurrences of N in input 3‰ # divmod 3 N* # multiply by N 2LRN1Q+°* # multiply by 10, 100 or 1000 X5‚Nå_i¨} # if N is not 1 or 5, scrap the singles OO # sum all triple and single scores so far # implicitly display total sum ``` [Try it online](http://05ab1e.tryitonline.net/#code=N0fCuU7Cok8z4oCwTioyTFJOMVErwrAqWDXigJpOw6VfacKofU9P&input=WzEsIDEsIDEsIDIsIDMsIDVd) [Answer] # Python 2, ~~152~~ ~~148~~ 125 bytes Pretty simple solution. Can be golfed more. `L.count` is a bit long, but I couldn't remove the first call because L is updated. ``` def f(L):s=n=0;exec"n+=1\nwhile L.count(n)>2:s+=[n*100,1e3][n<2];exec'L.remove(n);'*3\n"*6;C=L.count;print s+100*C(1)+50*C(5) ``` [**Try it online**](http://ideone.com/5sXQ0L) - (all test cases) **Ungolfed:** ``` def f(L,s=0): L.sort() for n in range(1,7): while L.count(n)>2: s+=n*100*((n<2)*9+1) # multiply by 10 if n==1 i=L.index(n) L=L[:i]+L[i+3:] s+=100*L.count(1)+50*L.count(5) print s ``` *Some golf credit to [@Copper](https://codegolf.stackexchange.com/users/56755/copper), using some tips from his code* [Answer] ## PowerShell ~~v2+~~ v3+, ~~147~~ ~~144~~ ~~137~~ 133 bytes ``` $n=$args[0]|sort;while($n){if(($x=$n[0])-eq$n[2]){$s+=100*$x+900*($x-eq1);$a,$b,$n=$n}else{$s+=50*($x-in1,5)+50*($x-eq1)}$a,$n=$n};$s ``` *Crossed out 144 looks kinda like 144?* Takes input `$args[0]` and `sort`s it, stores it into `$n`. Then, `while` there are still elements left, we evaluate an `if`/`else`. If the first element (temp stored into `$x` to save some bytes) matches the third element, we have a triple. Add onto the `$s`um the result of some multiplication `100*$x` plus a Boolean-based `900` only if `$x` is `-eq`ual to `1`. This gets us the requisite `1000` for three ones. Then, peel off the first two elements into `$a`, and `$b`, and the remaining into `$n` -- removing the third element of the triple is handled later. Otherwise, we don't have a triple, so add on to `$s`um the result of another Boolean-based addition. We add `50` if `$x` is either `1` or `5`, then add on another `50` if it's `-eq`ual to `1`. This section now requires v3+ for the `-in` operator. In either case, we still have an element yet to remove, so peel off the first element into `$a` and leave the remaining in `$n`. Finally, once the loop is done, place `$s` on the pipeline. Output is an implicit `Write-Output` at the end of execution. ### Test cases ``` PS C:\Tools\Scripts\golfing> (1,2,3,4,5,6),(1,1,1,2,3,5),(1,1,1,1,1,1),(2,2,2,2,2,2),(6,6,1,5,5,6),(2,3,4,6,2,4),(1,5,1,5,1,5),(5,5,5,5,2,3),(1,1,1,1,1,5),(3,3,4,4,3,4)|%{($_-join',')+" -> "+(.\evaluate-dice-1000.ps1 $_)} 1,2,3,4,5,6 -> 150 1,1,1,2,3,5 -> 1050 1,1,1,1,1,1 -> 2000 2,2,2,2,2,2 -> 400 6,6,1,5,5,6 -> 800 2,3,4,6,2,4 -> 0 1,5,1,5,1,5 -> 1500 5,5,5,5,2,3 -> 550 1,1,1,1,1,5 -> 1250 3,3,4,4,3,4 -> 700 ``` [Answer] ## JavaScript (ES6), ~~87~~ 86 bytes ``` a=>a.sort().join``.replace(/(.)\1\1|1|5/g,s=>r+=s>>7?s/1.11:s>5?1e3:s>1?50:100,r=0)&&r ``` Sorts and stringifies the input so that scoring combinations can be identified by means of regexp. Edit: Saved 1 byte thanks to @Arnauld. [Answer] # Python 2 or 3, ~~123 122 121 116 109 108 104 102 100~~ 97 bytes **Python 2, 97 bytes** ``` lambda r:100*sum(c/3*((v<2)*9+v)+c%3*(v<2or(v==5)/2.)for v,c in enumerate(map(r.count,range(7)))) ``` Test cases are on [**ideone**](http://ideone.com/4guQTz) **Python 3, 97 bytes** ``` lambda r:100*sum(c//3*((v<2)*9+v)+c%3*(v<2or(v==5)/2)for v,c in enumerate(map(r.count,range(7)))) ``` [Answer] # Ruby, ~~80~~ 78 bytes [Try it online!](https://repl.it/CqHQ/3) -2 byte from @ezrast. ``` ->d{s=0;7.times{|i|c=d.count i;i<2&&i=10;s+=c>2?c/3*i*100:1>i%5?c%3*i*10:0};s} ``` [Answer] ## Haskell, ~~130~~ 123 bytes This is *not* a challenge for Haskell. Also I am in golfing this. Thanks to @nimi. ``` import Data.List f=g.sort g(x:a@(y:z:b))|x>z=j x+g a|0<1=100*h x+g b g(x:y)=j x+g a g _=0 h 1=10 h x=x j 1=100 j 5=50 j _=0 ``` [Answer] # Python 3, 131 bytes ``` lambda r,C=list.count:sum([x%7*100,1e3][x%7<2]*(C(r,x%7)>2and not exec('r.remove(x%7);'*3))for x in range(14))+50*C(r,5)+100*C(r,1) ``` This is a lambda expression; to use it, assign it by prepending `f=`. We first check for triples twice (by using modulus), removing the triples as we go; then we simply add the counts of `5` and `1` to the score and return it. [Try it on Ideone!](http://ideone.com/FLjD1h) (with all test cases) Here's my older Python 2 submission: ## Python 2, ~~176~~ ~~172~~ ~~171~~ ~~145~~ ~~136~~ ~~134~~ 133 bytes ``` def e(r):s=x=0;exec'x+=1;a=x%7;\nif r.count(a)>2:exec"r.remove(a);"*3;s+=[a*100,1e3][a<2]\n'*14;C=r.count;s+=50*C(5)+100*C(1);print s ``` *Saved a byte on the Python 2 solution thanks to @mbomb007!* [Answer] # BASH (sed + bc) 161 ``` sed -re's/([1-6])(.*)\1(.*)\1/\100\2\3/g;s/([1-6])( .*)\1( .*)\1/\100\2\3/g;s/10/1/g; s/1/100/g;s/5( |$)/50 /g;s/[1-6][^0]//g;s/ +/+/g;s/(^\+|\+$)//g;s/^$/0/'|bc ``` I wanted to do it all in sed, but addition is really hard... Explanation: 1. Find a triplet, add `00` to the first number and remove the other e.g. `1 2 1 3 1 4` -> `100 2 3 4` 2. Repeat step 1 incase there are two triples 3. Replace `10` with `1` then `1` with `100` e.g. `100` -> `10` -> `1000` or `1` -> `1` -> `100` 4. Replace each `5` not followed by `0` with `50` 5. Remove any number that doesn't end in `0` 6. Replace groups of spaces with `+` 7. Remove leading and trailing `+`s 8. If the string is empty, add a `0` 9. Lastly pipe to `bc` to add everything up. [Answer] # Perl, 69 bytes Includes +2 for `-ap` Run with the input on STDIN: ``` dice10000.pl <<< "5 1 1 1 1 1" ``` `dice10000.pl`: ``` #!/usr/bin/perl -ap $_=join 0,sort@F,A;print;s%(10|\d)\1\1|10|5%$n+=$1.0||$&%eg;$_=$n.0 ``` [Answer] ## Javascript (ES6), ~~85~~ 84 bytes ``` x=>x.map(v=>s+=v*(((z+=1<<v*3)>>v*3&7)%3?v-5?v-1?0:10:1:v-5?v-1?10:80:8),s=z=0)|10*s ``` Test cases: ``` let F = x=>x.map(v=>s+=v*(((z+=1<<v*3)>>v*3&7)%3?v-5?v-1?0:10:1:v-5?v-1?10:80:8),s=z=0)|10*s console.log(F([1, 2, 3, 4, 5, 6])); // 150 console.log(F([1, 1, 1, 2, 3, 5])); // 1050 console.log(F([1, 1, 1, 1, 1, 1])); // 2000 console.log(F([2, 2, 2, 2, 2, 2])); // 400 console.log(F([6, 6, 1, 5, 5, 6])); // 800 console.log(F([2, 3, 4, 6, 2, 4])); // 0 console.log(F([1, 5, 1, 5, 1, 5])); // 1500 console.log(F([5, 5, 5, 5, 2, 3])); // 550 console.log(F([1, 1, 1, 1, 1, 5])); // 1250 console.log(F([3, 3, 4, 4, 3, 4])); // 700 ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~228~~ 227 bytes ``` class A{static void Main(string[] a){int[] x=new int[7];int i=0,s=0;for(;i<6;i++)x[int.Parse(a[i])]++;while(i>0){while(x[i]>2){s+=i>1?10*i:100;x[i]-=3;}i--;}while(x[1]-->0)s+=10;while(x[5]-->0)s+=5;System.Console.Write(s*10);}} ``` [Try it online!](https://tio.run/##PYtBS8QwEIX/So7JxpREqYKzqYhnQfDgoeQQulEHuglkgrtS@ttjqqy8w3x8781Eako51DrNnog9LlR8wYl9JTywZ4@RU8kYP0bHvFgwlgZnG8OJbXznoB2GVl@R1fCeMgfc3wJKKc5jq7oXnylwP6ITTko4feIcOA5aLH/YVm64FgtJi4N5MHqH90Zr2LyyN7CiUrBetsYp1X7b2Gi4yP5f9vD6TSUcu6cUKc2he8tYAqed0QLWtdba/8Zs@QE "C# (.NET Core) – Try It Online") I feel like I'm missing many, many potential optimizations here, but I *did* save a byte by multiplying by 10 at the end. Input should be passed as separate command line args. [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 78 bytes ``` $_=join'',sort@F;s|(\d)\1\1|!($\+=$1*($1-1?2:20))|ge;$\+=y/5//+2*y/1//}{$\*=50 ``` [Try it online!](https://tio.run/##FcixCsIwEADQX4kQaJIaLxfIYgl1cvMPDkSwSEWa0HQppr/uSZc3vDzMn8As7/GdxqlpjiXNy@XalaroqQkJ60FJaqNEoyRa7P3ZO63ra@j2XiEAtN6sgADbV5KJwTGjQOHFbvilvIxpKmxv4eTQsX3kPw "Perl 5 – Try It Online") ]
[Question] [ In arithmetic, an [n-smooth number](https://en.wikipedia.org/wiki/Smooth_number), where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor. Define a *pretty smooth* number as a number with **no prime factors greater than its own square root.** Thus, the list of pretty smooth numbers can be formulated as follows: * *(EDITED!)* 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.) * Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor. * Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations. * Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations. * And so on, upgrading the criteria every time the square of the next prime number is reached. The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ... Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used. As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Æf>½S ³²ḊÇÐḟ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZmPsK9UwrCs8Ky4biKw4fDkOG4nw&input=) ### How it works ``` ³²ḊÇÐḟ Main link. No arguments. ³ Yield 100. ² Square it to yield 10,000. Ḋ Dequeue; yield [2, ..., 10,000]. ÇÐḟ Filter-false; keep elements for which the helper link returns 0. Æf>½S Helper link. Argument: n Æf Compute the prime factorization of n. >½ Compare the prime factors with the square root of n. S Sum; add the resulting Booleans. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~21~~ 19 bytes **1 byte thanks to Fatalize, for inspiration of another 1 byte.** ``` 100^:4reP$ph^<=P@w\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=MTAwXjo0cmVQJHBoXjw9UEB3XA&input=&debug=on) Takes about 6 seconds here. ``` 100^:4reP$ph^<=P@w\ 100 100 ^ squared :4 [10000,4] r [4,10000] eP P is an integer in that interval (choice point), P$ph^<=P P, prime factorized (from biggest to smallest), take the first element, squared, is less than or equal to P P@w Write P with a newline, \ Backtrack to the last choice point and make a different choice until there is no more choice and the program halts. ``` ## Previous 21-byte solution ``` 100^:4reP'($pe^>P)@w\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=MTAwXjo0cmVQJygkcGVePlApQHdc&input=&debug=on) Takes about 6 seconds here. ``` 100^:4reP'($pe^>P)@w\ 100 100 ^ squared :4 [10000,4] r [4,10000] eP P is an integer in that interval (choice point), P'( ) The following about P cannot be proved: $pe one of its prime factor ^ squared >P is greater than P @w Write P with a newline, \ Backtrack to the last choice point and make a different choice until there is no more choice and the program halts. ``` [Answer] ## Haskell, 53 bytes ``` r=[1..10^4] [n|n<-r,product[x|x<-r,x*x<=n]^n`mod`n<1] ``` I don't have time to golf this now, but I want to illustrate a method for testing if `n` is pretty smooth: Multiply the numbers from `1` to `sqrt(n)` (i.e. compute a factorial), raise the product to a high power, and check if the result is a multiple of `n`. Change to `r=[2..10^4]` if `1` should not be output. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~16~~ 15 bytes **1 byte thanks to Jakube.** ``` tf!f>*YYTPTS^T4 ``` [Try it online!](http://pyth.herokuapp.com/?code=tf%21f%3E%2aYYTPTS%5ET4&debug=0) ``` tf!f>*YYTPTS^T4 T 10 ^T4 10000 S^T4 [1,2,3,...,10000] f filter for elements as T for which the following is truthy: PT prime factorization of T f filter for factor as Y: *YY Y*Y > T greater than T ? ! logical negation t remove the first one (1) ``` [Answer] ## 05AB1E, ~~16~~ ~~14~~ 13 bytes ``` 4°L¦vyf¤yt›_— ``` **Explanation** ``` 4°L¦v # for each y in range 2..10000 yf¤ # largest prime factor of y yt # square root of y ›_ # less than or equal — # if true then print y with newline ``` [Try it online](http://05ab1e.tryitonline.net/#code=NMKwTMKmdnlmwqR5dOKAul_igJQ&input=) [Answer] ## Matlab, ~~58~~ ~~57~~ ~~56~~ ~~52~~ 48 bytes ``` for k=1:1e4 if factor(k).^2<=k disp‌​(k) end end ``` For each number it checks if all factors squared are not larger than the number itself. If yes, displays that number. *Thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for golfing this approach* --- Another approach (50 bytes): ``` n=1:10^4;for k=n z(k)=max(factor(k))^2>k;end n(~z) ``` For each number computes whether its maximum prime factor squared is less than the number itself. Then uses it for indexing. [Answer] ## Actually, 11 bytes ``` 4╤R`;yM²≤`░ ``` [Try it online!](http://actually.tryitonline.net/#code=NOKVpFJgO3lNwrLiiaRg4paR&input=) Does not include 1. Explanation: ``` 4╤R`;yM²≤`░ 4╤R range(10**4) `;yM²≤`░ filter: take values where ;yM² the square of the largest prime factor ≤ is less than or equal to the value ``` [Answer] # [SQF](https://community.bistudio.com/wiki/SQF_syntax), ~~252~~ ~~227~~ 220 Standard script format: ``` #define Q(A,B) for #A from 2 to B do{ Q(i,10000)if([i]call{params["j"];u=sqrt j;a=true;Q(k,u)a=a and((j%k!=0)or(j/k<u)or!([j/k]call{params["x"];q=true;Q(z,sqrt x)q=q and(x%z!=0)};q}))};a})then{systemChat format["%1",i]}} ``` Include the pre-processor in the compilation chain when calling eg: * `execVM "FILENAME.sqf"` * `call compile preprocessFile "FILENAME.sqf"` This writes to the System Chat log, which is the closest thing SQF has to stdout [Answer] # C, 113 bytes ``` #include<stdio.h> main(a){for(;++a<10001;){int n=2,c=a;for(;n*n<=a;n++)while(c%n<1)c/=n;if(c<2)printf("%d ",a);}} ``` [Ideone it!](http://ideone.com/uDB1ig) [Answer] ## Pyke, ~~13~~ ~~12~~ 11 bytes ``` T4^S#DP#X<! ``` [Try it here!](http://pyke.catbus.co.uk/?code=T3%5ES%23DP%23X%3C%21) (Link only goes up to 10^3 because 10^4 times out) ``` T4^S - one_range(10^4) #DP#X<! - filter_true(V, ^): (as i) P - factors(i) #X<! - filter_true(V, ^): X - ^ ** 2 <! - not (i < ^) ``` [Answer] # J, 20 bytes ``` (#~{:@q:<:%:)2+i.1e4 ``` Result: ``` (#~{:@q:<:%:)2+i.1e4 4 8 9 12 16 18 24 25 27 30 32 36 40 45 48 49 50 54 56 60 63 64 70 72 75 80... ``` [Try it online here.](http://tryj.tk/) [Answer] # Python 2, 90 bytes ``` for i in range(4,10001): n=2;j=i while n*n<=j: while i%n<1:i/=n n+=1 if i<2:print j ``` [Ideone it!](http://ideone.com/HHkgDD) [Answer] # R, 97 bytes ``` b=F;for(j in 1:1e4){for(i in which(!j%%1:j)[-1])if(which(!i%%1:i)[2]==i)b=i<=j^0.5;if(b)print(j)} ``` ungolfed ``` b <- F #Initializes for (j in 1:1e4){ #Loop across integers 1..10^4 a <- which(!j%%1:j)[-1] #Finds all factors for (i in a) #Loop across factors b <- which(!i%%1:i)[2]==i #Tests primeness if(b) c <- i<=j^0.5 #If prime, tests smoothness if(c) print(j) #If biggest prime factor gives smooth } #result, Prints the number. ``` [Answer] # Pyth, 12 bytes ``` g#^ePT2tS^T4 ``` Does not include 1. ]
[Question] [ This is my pet emoji, Billy: ``` -_- ``` Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better! ``` /\ / \ / \ -_- ``` This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered: ``` /\ / \ / \ -_- ``` In this case, sections 2 and 3 of his body are exposed to the rain. Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes `/` followed by a series of descending backslashes `\`. For example, these are all valid umbrellas: ``` /\ / \ / \ /\ /\ / \ / \ / \ / \ ``` And these are not: ``` / \ \/ \ / \ / \ 0\ / \ //\\ / \ ``` You need to determine which parts of my emoji are exposed to the rain. # Clarifications * Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc. * You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array). * You can assume that all inputs will have a valid umbrella, and the same emoji: `-_-`. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji. * Everything that isn't part of the umbrella or the emoji will be a space character or newline. * The input will be padded with spaces so that the length of each line is the same. Standard loopholes apply, and the shortest answer in bytes wins! # Test IO: All of the sample cases will use one-indexing. ``` /\ / \ / \ -_- Outputs: [] ---------------- /\ / \ -_- Outputs: [2, 3] ---------------- /\ -_- Outputs: [1] ---------------- /\ / \ / \ / \ / \ / \ -_- Outputs: [1, 2, 3] ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ 15 bytes Code: ``` |…-_-123:)ø€J€ï ``` Explanation: ``` | # Take all input as a list of strings. …-_- # 3-char string, which results into "-_-". 123:) # Replace "-_-" with 123. ø # Zip, resulting into the columns of the 2D array. €J # Join each of them. €ï # For each, convert to integer. If this is not possible, it will ignore the result. # Implicitly output the array. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=fOKApi1fLTEyMzopw7jigqxK4oKsw68&input=ICAgICAvXCAgICAgICAKICAgIC8gIFwgICAgICAKICAgLyAgICBcICAgICAKICAvICAgICAgXCAgICAKIC8gICAgICAgIFwgICAKLyAgICAgICAgICBcICAKICAgICAgICAgICAgICAKICAgICAgICAgICAgICAKICAgICAgICAgICAgICAKICAgICAgICAgICAgICAKICAgICAgICAgICAtXy0) (make sure to pad *all* lines with spaces to the same length.. [Answer] # JavaScript (ES6), 95 bytes ``` a=>[...a[n=0]].map((_,i)=>a.map(s=>(c=s[i])>"-"&c<"_"?p=1:n+=!++c,p=0)|p<!c&&o.push(n),o=[])&&o ``` Input should be an array of strings, with each line padded with spaces to form a square. Output is an array of 1-indexed numbers. ## Explanation ``` var solution = a=> [...a[n=0]].map((_,i)=> // n = current index of emoji, for each column i of input a.map(s=> // for each line s (c=s[i]) // c = character in column >"-"&c<"_"?p=1 // p = 1 if column is protected from rain :n+=!++c, // increment n if emoji character found, c = 1 if last line // contained a space in the current column p=0 ) |p<!c&&o.push(n), // if the emoji is not protected in the current column o=[] ) &&o ``` ``` <textarea id="input" rows="6" cols="40"> /\ / \ -_-</textarea><br /> <button onclick="result.textContent=solution(input.value.split('\n'))">Go</button> <pre id="result"></pre> ``` [Answer] ## JavaScript (ES6), 92 bytes ``` a=>a.map(s=>s.replace(/\S/g,(c,i)=>c>'-'&c<'_'?u[i]=3:++n&u[i]||r.push(n)),n=0,u=[],r=[])&&r ``` Accepts a ragged array of lines and returns a 1-indexed result. Explanation: ``` a=>a.map( Loop through all lines s=>s.replace(/\S/g, Loop through all non-whitepsace (c,i)=>c>'-'&c<'_' If it's part of the umbrella ?u[i]=3 Mark that column as dry :++n& Add 1 to the emoji index u[i]|| If the column is not dry r.push(n) Add the emoji index to the result ),n=0,u=[],r=[] Initialise variables )&&r Return result ``` [Answer] ## Java 8 lambda, ~~241~~ ~~218~~ ~~201~~ ~~191~~ ~~185~~ 184 (or 161) characters Because ya know, also Java needs dry emojis. ``` import java.util.*;f->{int e,i=e=-1,c,l=f.length-1;while(++e<f[l].length&&f[l][e]!=45);List p=new Stack();l:for(;++i<3;){for(char[]r:f)if((c=r[e+i])==47|c==92)continue l;p.add(i);}return p;} ``` It returns ~~an ArrayList~~ a HashSet a Stack containing the parts of the emoji which are exposed to the rain (indexing starts at 0). The whole thing unwrapped: ``` import java.util.*; public class Q82668 { static List isEmojiDryRevE(char[][] fieldToCheck) { int emojiStart, i = emojiStart = -1, j, rows = fieldToCheck.length - 1; while (++emojiStart < fieldToCheck[rows].length && fieldToCheck[rows][emojiStart] != 45) ; List parts = new Stack(); emojiLoop: for (; ++i < 3;) { for (j = -1; ++j < rows;) { if (fieldToCheck[j][emojiStart + i] > 46) { // umbrella part found continue emojiLoop; } } // no umbrella part found parts.add(i); } return parts; } } ``` --- **Updates** I did some basic golfing. This includes putting the declarations together, compare with the ascii values to save some characters and shorten the loops. Thanks to @user902383 for pointing out my dump mistake using ArrayLists instead of just Lists. I replaced the ArrayLists/Lists with HashSets/Sets which saves some more characters. Also thanks for his tip to use a foreach loop in the inner loop! Through that change I am able to create a variable for the index of the last grid row which shortens it a bit more. Overall 17 characters have been saved! @KevinCruijssen suggested to remove the generics in the initialization, I went one step further: Remove all the generics. This saves another 10 characters. I switched back from the foreach loop to the for loop. This makes it possible to skip comparing the last line which in turn allows me to shorten the comparison of the ascii values. In this context only '/', '\' and '\_' have an ascii value over 46. If we don't check the last line we can use a `> 46 check` instead to checks for the actual value. Thanks again to @user902383 for showing me that I use a lambda and can use List+Stack instead of Set+HashSet to shave off another character. --- **String returning version** @user902383 pointed out I can instead just create a String with the digits. This sounds very cheaty but others seem to solve it this way so here is a shorter version using a String return: ``` f->{int e,i=e=-1,c,r=f.length-1;while(++e<f[r].length&&f[r][e]!=45);String p="";l:for(;++i<3;){for(char[]o:f)if((c=o[e+i])==47|c ==92)continue l;p+=i;}return p;} ``` Ungolfed: ``` public class Q82668 { public static String isEmojiDryRevD(char[][] fieldToCheck) { int emojiStart, i = emojiStart = -1, c, rows = fieldToCheck.length - 1; while (++emojiStart < fieldToCheck[rows].length && fieldToCheck[rows][emojiStart] != 45) ; String parts = ""; emojiLoop: for (; ++i < 3;) { for (char[] row : fieldToCheck) { if ((c = row[emojiStart + i]) == 47 | c == 92) { // umbrella part found continue emojiLoop; } } // no umbrella part found parts += i; } return parts; } } ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~20~~ 19 bytes (non-competing) ``` G^R123?/ f\GddHÍó ``` Alternate, competing version (21 bytes): ``` G^R123?/ f\òjòddHÍó ``` [Try it online!](http://v.tryitonline.net/#code=OnNlIG5vc29sCkdeUjEyMxs_LwoWZlxHZGRIw43Dsw&input=ICAgIC9cCiAgIC1fLQ) (Note, tryitonline.net uses a slightly old version of V. To compensate for this, it uses this slightly longer version) Explanation: ``` G^ "Move to the first non-whitespace character on the last column R123<esc> "Replace the emojii with '123' ?/ "Move backwards to the last '/' character <C-v> "Start a blockwise selection f\G "Move the selection to the next '\', and then to the last line d "Delete the block selection dH "Delete the umbrella ``` This alone produces the correct result in 17 bytes. However, it also creates some extra whitespace. I don't mind it, but I don't want to give myself an unfair advantage, so I'm adding two bytes: ``` Íó "Remove all whitespace ``` [Answer] # JavaScript (ES6), ~~117~~ 112 bytes ``` s=>s.map(r=>r.map((c,i)=>~'-_'[o='indexOf'](c)&&!s.some(a=>~'/\\'[o](a[i]))?i-r[o]('-'):-1)).pop().filter(n=>~n) ``` Accepts a ragged array of ~~strings~~ [arrays of characters](https://codegolf.stackexchange.com/questions/82668/is-my-emoji-dry/82917#comment202118_82668), and returns 0-indexed results. ``` s=>s.map( // for each row r=> // row r.map( // for each character (c,i)=> // character, index ~'-_'[o='indexOf'](c) // if character is part of emoji && // and !s.some( // none of the rows have umbrella in this column a=>~'/\\'[o](a[i]) ) ? // then return 0-index of emoji i-r[o]('-') : // else return -1 -1 ) ) .pop() // get last element of string array .filter(n=>~n) // filter out -1s ``` ## Demo ``` f=s=>s.map(r=>r.map((c,i)=>~'-_'[x='indexOf'](c)&&!s.some(a=>~'/\\'[x](a[i]))?i-r[x]('-'):-1)).pop().filter(n=>~n) i.oninput=()=>o.value=f(i.value.split`\n`.map(r=>r.split``)) i.oninput() ``` ``` <textarea rows=6 cols=20 id=i> /\ / \ -_-</textarea> <br/> <input readonly id=o> ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 56 bytes Byte count assumes ISO 8859-1 encoding. ``` m`(?<!(?(2)!)^(?<-2>.)*\S(.*¶)+(.)*).(?<=([-_]+))|\D $.3 ``` [Try it online!](http://retina.tryitonline.net/#code=bWAoPzwhKD8oMikhKV4oPzwtMj4uKSpcUyguKsK2KSsoLikqKS4oPzw9KFstX10rKSl8XEQKJC4z&input=ICAgICAvXCAgIAogICAgLyAgXCAgCiAgICAgICAtXy0) This is a single substitution stage, where the regex matches one of the emoji characters, provided that there's a non-space character (i.e. a `/` or `\`) somewhere above in the same horizontal position, and then we capture the number of emoji characters up to that point. This match is replaced with the length of that last capture, which gives us the index of this unsheltered emoji character. The regex also contains a `|\D` to match everything else which gets replaced with nothing at all, so we remove all the other characters. [Answer] # Pyth, ~~27~~ 23 bytes 0-indexed. ``` -m.xsd;.T:R"-_-"s`M3.zd ``` [Try it online!](http://pyth.herokuapp.com/?code=-m.xsd%3B.T%3AR%22-_-%22s%60M3.zd&input=%0A+++%2F%5C%0A++%2F++%5C%0A%0A-_-%0A&debug=0) ### Explanation ``` -m.xsd;.T:R"-_-"s`M3.zd .z all lines of input, as a list :R"-_-"s`M3 replace "-_-" by "012" "012" is generated by s`M3 .T transpose, return all columns The sample input becomes: 0 1 /2 / \ \ m d for each line: .xs attempt to convert to integer. ; if errors, replace to space - d remove all spaces ``` ## History 27 bytes: `sM:#"^ *\d"0.T:R"-_-"s`M3.z` ([Try it online!](http://pyth.herokuapp.com/?code=sM%3A%23%22%5E+%2a%5Cd%220.T%3AR%22-_-%22s%60M3.z&input=%0A+++%2F%5C%0A++%2F++%5C%0A%0A-_-%0A&debug=0)) [Answer] ## Matlab, 43 bytes ``` @(x)find(sum((x(:,x(end,:)~=' '))~=' ')==1) ``` This code finds column positions of non-space characters in the final row of the input, sums the number of non-space characters in those columns, and finds where there's only one such character (the emoji's character, un-shielded by umbrella!). This code only returns proper results for well-formed umbrellas (it assumes any character above our emoji is part of a well-formed umbrella). Here is a bit of utility code for writing test cases and checking my work: ``` ws = @(x) repmat(' ',1,x); % for making strings of spaces % for writing three-storey umbrellas over an emoji located left-edge at position x thrht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/ \' ws(2); ws(1) '/' ws(4) '\' ws(1); ws(8)], [ws(x-1) '-_-']); twht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/ \' ws(2); ws(8)], [ws(x-1) '-_-']); ``` Running `x = thrht(7)` gives ``` x = /\ / \ / \ -_- ``` Or `x = twht(0)` gives ``` x = /\ / \ -_- ``` [Answer] # APL, 31 bytes ``` {(⍳3)∩,(~∨⌿⍵∊'/\')/+\+\'-_-'⍷⍵} ``` This takes a character matrix as input. Tests: ``` t1 t2 t3 t4 ┌──────┬────────┬──────┬─────────────────┐ │ /\ │ /\ │ /\│ /\ │ │ / \ │ / \ │ -_-│ / \ │ │/ \│ │ │ / \ │ │ │ -_-│ │ / \ │ │ -_- │ │ │ / \ │ │ │ │ │/ \ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -_-│ └──────┴────────┴──────┴─────────────────┘ {(⍳3)∩,(~∨⌿⍵∊'/\')/+\+\'-_-'⍷⍵} ¨ t1 t2 t3 t4 ┌┬───┬─┬─────┐ ││2 3│1│1 2 3│ └┴───┴─┴─────┘ ``` Explanation: * `'-_-'⍷⍵`: in a matrix of zeroes the size of the input, mark the position of the beginning of `'-_-'` in the input with a 1. * `+\+\`: Running sum over rows. The first one makes `0 0 0 1 0 0 ...` into `0 0 0 1 1 1 ...`, the second one then makes it into `0 0 0 1 2 3 ...`. * `⍵∊'/\'`: mark all occurrences of '/' and '\' in the input with 1s. * `∨⌿`: `or` over columns. This marks with an 1 all positions on the last row that are covered by the umbrella. * `~`: `not`, because we need the opposite * `(`...`)/`...: Select all uncovered columns from the running sum matrix from earlier * `,`: Get a list of all values in the resulting matrix. * `(⍳3)∩`: Intersection between that and `1 2 3` (this gets rid of any selected 0s or higher values, which would be spaces). [Answer] # Python 2, ~~114~~ 111 bytes ``` def f(a):c=a.find("\n")+1;r=a.rfind;g=lambda i:([i],[])[r("\\")%c>=r("-")%c-2+i>=r("/")%c];print g(0)+g(1)+g(2) ``` Uses 0 based indexing. [Try it here](https://repl.it/C1aw/1). ]
[Question] [ In [Gödel, Escher, Bach](http://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach), Douglas Hofstadter introduces an integer sequence which is commonly referred to as the figure-figure sequence: ``` 2, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, ... ``` You may enjoy working out the definition of the sequence yourself as part of the challenge, but if you can't or don't want to figure it out you can find it on OEIS as sequence [A030124](http://oeis.org/A030124) and a slightly clearer definition [on Wikipedia](http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences). Write a program or function which, given `n` via STDIN, ARGV or function argument, prints a list of the first `n` numbers of the sequence to STDOUT in any reasonable list format. This is code golf, the shortest solution in bytes wins. [Answer] # CJam, ~~38~~ ~~30~~ ~~29~~ 21 bytes ``` li_3*,2>\{(_pX+:X-}*; ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### How it works ``` li " Read an integer N from STDIN. "; _3*,2> " Push S := [ 2 3 ... (N * 3 - 1) ]. "; \{ }* " Do the following N times: "; ( " Shift an integer I from S. "; _p " Print a copy of I, followed by a linefeed. "; X+:X " Execute X += I. (X is initialized to 1.) "; - " Remove X from S. "; ; " Discard S from the stack. "; ``` ### Example run ``` $ cjam <(echo 'li_3*,2>\{(_pX+:X-}*;') <<< 20 2 4 5 6 8 9 10 11 13 14 15 16 17 19 20 21 22 23 24 25 ``` [Answer] # Haskell, ~~67~~ ~~61~~ ~~60~~ ~~56~~ ~~55~~ 53 characters ``` g n=take n$2:4:h a#(x:s)=[a..x-2]++x#s h=5#scanl(+)8h ``` back to the first algorithm. this solution computes the complement sequence by summing the starting elements of the sequence. it then computes the sequence as all the numbers between the complement's sequence numbers. `(#)` is the function that calculates the numbers between the complement sequence. `h` is the sequence itself. `g` is the function that answers the question. the g function is defined to just take the needed amount of elements from h. subtleties: `h` is actually the figure figure sequence except for the first 2 elements. not the complement sequence is computed, but the complement sequence with added 1 for each element. these two subtleties are the reason `scanl(+)8h` (which is the code for the complement sequence (except for the first 2 elements) with added 1's) has `8` in it. it is for the third element of the complement sequence with 1 added to it. the reason the computation is not missing the first two elements is because they are added in `g` in `2:4:h`. example: ``` >g 50 [2,4,5,6,8,9,10,11,13,14,15,16,17,19,20,21,22,23,24,25,27,28,29,30,31,32,33,34,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,57,58,59] ``` [Answer] # Ruby, ~~54~~ 48 ``` f=->n{x=1 b=*2..n*n n.times{b-=[x+=p(b.shift)]}} ``` [Demo](https://ideone.com/VIL5y5) Edit: Golfed this a bit more once I realized I don't need to hold the full complement sequence in memory. Here's how it works now: We use `x` to keep track of the largest computed number in the complement sequence, and `b` is a pool of candidates for the sequence. `n` times, we output the smallest remaining element in `b` and add it to `x` to compute the next number in the complement sequence. Then we remove both numbers from the pool of candidates, so we're always outputting the smallest number that wasn't already added to either sequence. Ruby golf tricks: Stabby lambda syntax is shorter than a method definition. The requirement that output is given to STDOUT instead of as return value inspired me to use the fact that the return value of `p(x)` is `x`, which I don't normally remember because it's not the case in the Ruby version used in Anarchy Golf. [Answer] ## GolfScript (24 21 bytes) ``` ~.3*,1>\{(\(.p@+\|}*; ``` [Online demo](http://golfscript.apphb.com/?c=OycyMCcKCn4uMyosMT5ceyhcKC5wQCtcfH0qOw%3D%3D) This started out quite differently, but ended up converging on a GolfScript port of [histocrat](https://codegolf.stackexchange.com/users/6828/histocrat)'s [Ruby solution](https://codegolf.stackexchange.com/a/37531/194) before [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) made some suggestions which take it in a slightly different direction. In particular, printing the numbers as we identify them saves quite a bit over gathering them in an array for printing at the end; the reason is that it means that at no point do we have to worry about more than 3 items on the stack. ### Dissection ``` ~.3*, # Eval input n, dup, multiply by 3, make list [0 1 ... 3n-1] 1> # Discard 0, which is part of neither sequence \{ # Execute n times: stack contains pool of numbers not yet seen # in either sequence and the first element of it is the next element of the # complement sequence (\( # Pop two numbers from the start of the pool: stack is # pool[0] pool[2..max] pool[1] .p # Print pool[1] @+ # Rotate pool[0] to top and add to pool[1] \| # Place pool[0]+pool[1] at the start of the pool and # (this is the clever bit) remove it from later in the pool }* ; # Discard the unused remainder of the pool ``` [Answer] # Java - ~~183~~ 158 This was the most I have ever golfed anything, and I am proud of it! (Although it is nowhere near the top of the charts(because it's Java)) Thanks to Peter Taylor for suggestions ``` class f{public static void main(String[]a){int q=1,m=Byte.valueOf(a[0]),w=2,n[]=new int[m*m*2];for(n[q+=w]=1;m-->0;){System.out.println(w);for(;n[++w]>0;);}}} ``` bigger - ``` public class f { public static void main(String[] a) { int q = 1, m = Byte.valueOf(a[0]), w = 2, n[] = new int[m * m * 2]; for (n[q += w] = 1; m-- > 0;) { System.out.println(w); for (; n[++w] > 0;) ; } } } ``` [Answer] # J - 28 char Function taking `n` as argument. ``` ($+/\(-.~2+i.)&:>:+/)^:_&2 4 ``` We run a function, with `n` as left argument, onto its right argument repeatedly until it produces no change. The argument to start is the list `2 4`. In the function itself, we take the partial sums `+/\` and the full sum `+/`, and then increment them both with `&:>:`. We then generate every integer from 2 to the one more than full sum (`2+i.`), and set subtract (`-.`) the partial sums, leaving a longer figure-figure sequence by definition. Finally, we shorten or cyclically extend the list to length `n`. The result is that `2 4` becomes `3 7`, and this is removed from `2..8` leaving `2 4 5 6 8`. After another round, `2 4 5 6 8` becomes `3 7 12 18 26` becomes ``` 2 4 5 6 8 9 10 11 13 14 15 16 17 19 20 21 22 23 24 25 27 ``` In this way, we repeatedly extend the figure-figure sequence. The `$` length behaviour is just a non-trivial character saving way of waiting for the sequence to grow to length `n` or greater, and outputting the `n` first values when they stop changing. We don't have to wait very long, either: we can get as many as 46336 terms from four applications of the inner verb. The same function in k: * k2, 37 chars: `{{x#y@&~_lin[y:1+!1+/y;1+\y]}[x]/2 4}` * k4, 36 chars: `{{x#y@&~(y:2+!1+/y)in\:1+\y}[x]/2 4}` [Answer] # Python 2 -- 77 bytes --- Code: ``` n=input();x=1;b=range(2,n*n) while n:v=b.pop(0);x+=v;print v;b.remove(x);n-=1 ``` Works the same as @histocrat's solution, except input comes from stdin. [Answer] # Python 2 - 68 ``` R=[1] s=0 n=input() while n:s+=1+(s+1in R);R+=[R[-1]+s];print s;n-=1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` SƤŻ‘µṀ‘Rḟ 2dz¡ḣ ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//U8akxbvigJjCteG5gOKAmFLhuJ8KMsOHwrPCoeG4o////zU "Jelly – Try It Online") Memory error at the input of 6. ### How it works ``` SƤŻ‘µṀ‘Rḟ Aux. link (monad). Input: part of the desired sequence SƤŻ‘ Sum of prefixes, then prepend a zero and increment This is a list of numbers to exclude from the next iteration µ Re-focus on the above Ṁ‘Rḟ Create range 1..Max + 1, then remove all elements of the above +1 is needed to progress from [2] to [2,4] 2dz¡ḣ Main link (monad). Input: n, number of terms 2dz¡ Starting from 2, apply aux. link n times ḣ Take n elements from the beginning ``` # More efficient version, 16 bytes ``` SƤŻ‘µṀ‘Rḟḣ³ 2ÇÐL ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//U8akxbvigJjCteG5gOKAmFLhuJ/huKPCswoyw4fDkEz///8yMA "Jelly – Try It Online") Uses an idea from [this J answer](https://codegolf.stackexchange.com/a/37614/78410). Truncate to the desired length each iteration, and take the fixpoint. I thought using `S` (sum) instead of `Ṁ‘` (max+1), but I can't guarantee its correctness. ]
[Question] [ ## Background A [one-time pad](http://en.wikipedia.org/wiki/One-time_pad) is a form of encryption that has been proven impossible to crack if used properly. Encryption is performed by taking a plaintext (comprised of only letters A-Z) and generating a random string on the same length (also only letters). This string acts as the key. Each character in the plaintext is then paired up with the corresponding character in the key. The ciphertext is computed as follows: For each pair, both characters are converted to numbers (A=0, B=1, ... Z=25). The two numbers are added modulo 26. This number is the converted back into a character. Decryption is exactly the opposite. The characters in the ciphertext and key are paired up and converted to numbers. The key is then subtracted from the ciphertext modulo 26, and the result is converted back into a character A-Z. ## The Challenge Your challenge is to write the shortest program possible that can both encrypt and decrypt a one-time pad. On the first line of input (to STDIN), there will be either the word "ENCRYPT" or the word "DECRYPT". If the word is encrypt, then the next line will be the plaintext. Your program should output two lines (to STDOUT), the first being the key, and the second being the ciphertext. If the word is decrypt, your program will get two more line of input. The first line will be the key, and the second line will be the ciphertext. You program should output one line, which will be the plaintext that has been decrypted. The plaintext, ciphertext, and key should always consist of uppercase letters A-Z. They will always be a single line and contain no whitespace. The key should always be random. No large parts of it should repeat between runs, and there should be no patterns that can be found in the text. Two simple examples: ``` ENCRYPT HAPPYBIRTHDAY >ABKJAQLRJESMG >HBZYYRTICLVME DECRYPT ABKJAQLRJESMG HBZYYRTICLVME >HAPPYBIRTHDAY ``` The `>` represents which lines are output, so you don't have to print that symbol as output. [Answer] ## GolfScript, 53 chars ``` n%(0=2%{~.,[{26rand 65+}*]:K]}*zip{{-}*~)26%65+}%K]n* ``` This is a task for which GolfScript seems just about perfectly suited. To keep the code short, I'm using the same code for both encryption and decryption: to decrypt, I subtract the key from the ciphertext, while for encryption, I first generate a random ciphertext and then subtract the plaintext from it. Even so, the extra code for implementing encryption mode takes just a little over half the length of the program. De-golfed version with comments: ``` n % # split input into an array of lines # KEY GENERATION FOR ENCRYPTION MODE: ( # extract the first line from the array 0 = 2 % # check if the first char of that line is odd (E = 69)... { # ...and execute this block if it is: ~ # dump the remaining lines (of which the should be only one) on the stack . , # calculate the length of the last line... [ { 26 rand 65 + } * ] # ...make an array of that many random letters... :K # ...and assign it to K ] # collect all the lines, including K, back into an array } * # ENCRYPTION / DECRYPTION ROUTINE: zip # transpose the array of 2 n-char strings into n 2-char strings... { # ...and execute this block for each 2-char string: {-} * # subtract the second char code from the first ~ ) # negate the result (using the two's complement trick -x = ~x+1) 26 % 65 + # reduce modulo 26 and add 65 = A } % # OUTPUT: K ] n* # join the result and K (if defined) with a newline, stringifying them ``` [Answer] # Ruby (200 185) sample runs + wc: ``` $ ruby onetimepad.rb ENCODE ANOTHERTESTINPUTZZZ ZYCLGHDWLDASFUTHWKC BPMIBXOXTPTQIVBMDPX $ ruby onetimepad.rb DECODE ZYCLGHDWLDASFUTHWKC BPMIBXOXTPTQIVBMDPX ANOTHERTESTINPUTZZZ $ wc onetimepad.rb 4 7 185 onetimepad.rb ``` ``` def f;gets.scan(/./).map{|b|b.ord-65};end s=->a{a.map{|b|(b+65).chr}*''} r=->b,a,o{s[a.zip(b).map{|a,b|(a.send o,b)%26}]} puts(gets=~/^D/?r[f,f,:+]:[s[k=(p=f).map{rand 26}],r[k,p,:-]]) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 46 bytes ``` ⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862guKwAKO0UZmNdXqfuqPOroe9c6zetTbWaHzqHeVBkjuUe/mck3tCqAWIzP7R70rHvVuKQdygOoedbfoPurZD1X0qG0iSKx3Xq1h7H@g2f@BhnO5@jkHRQaEcHm4@vj4cwFVAnWqq3OBpFxcIVK@QS7ekVwhYf5hvtgVODp5ezkG@gR5uQb7unN5OEVFRgaFeDr7hPm6AgA "APL (Dyalog Unicode) – Try It Online") The current full program is the result of a [2hr long session at The APL Orchard.](https://chat.stackexchange.com/transcript/message/55691568#55691568), with a lot of golfing input from Adám (-13 bytes!). Requires `⎕IO←0` (0-indexing). ## Explanation ``` ⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1] { }1 inner fn(called with junk param) ⍞ first input 'N'∊ is 'N' present in it? :⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞ if so, eNcrypt: w←⍞ store message in w 26?⍨⍴ generate 26 random numbers, x← store in x (⎕A⍳w)+ add that to the indices in the alphabet ⍪ table them x, join with the random numbers ⍉ transpose to get key and encrypted value ⋄-⌿⎕A⍳↑⍞⍞ else, decrypt: ⍞⍞ input key and value ↑ convert to matrix ⎕A⍳ get the indices of both in the alphabet -⌿ difference of all columns 26| mod the result of the inner fn. [ ] index the result of the program in ⎕A the capitalized alphabet. ``` [Answer] ## Haskell, 203 characters ``` import Random main=newStdGen>>=interact.(unlines.).(.lines).f.randomRs('A','Z') f k['E':_,x]=[z const k x,z(e(+))k x] f _[_,k,x]=[z(e(-))k x] e(%)k x=toEnum$65+o x%o k`mod`26 o c=fromEnum c-65;z=zipWith ``` **Example:** ``` $ runghc OneTimePad.hs <<< $'ENCRYPT\nHELLOWORLD' QMNQKGFZFD XQYBYCTQQG $ runghc OneTimePad.hs <<< $'DECRYPT\nQMNQKGFZFD\nXQYBYCTQQG' HELLOWORLD ``` [Answer] # Perl, 220 171 characters ``` if(<>=~/D/){$_=<>;$w=<>;print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g}else{$_=<>;$c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g;print$/.$c} ``` Sample Run: ``` ENCRYPT HELLO CCTKK JGEVY DECRYPT CCTKK JGEVY HELLO ``` Note: at least when I run it, "Press any key to continue..." is appended to the end of the last output. I hope this is ok, because it isn't part of the program. If not, I can make it so it appears on the next line. This is my first real program in Perl, and my first golf ever, so I would really appreciate tips. Also, I found `/(.)/g` on the internet, but I have no idea how it works (is it a regular expression? I haven't learnt those yet). Can somebody explain it to me? EDIT: Thanks to Ilmari Karonen for helping me out with the regexps, I used my new knowledge to save 7 characters! Expanded, slightly legible version: ``` if(<>=~/D/){ $_=<>; $w=<>; print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g } else{ $_=<>; $c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g; print$/.$c } ``` [Answer] # Python - 304 295 ``` import random r=raw_input R=lambda s:range(len(s)) o=lambda c:ord(c)-65 j=''.join if r()[0]=='D': s=r() d=r() print j(chr((o(s[i])-o(d[i]))%26+65)for i in R(s)) else: s=r() d=[random.randint(0,26)for i in R(s)] print j(chr((o(s[i])+d[i])%26+65)for i in R(s)) print j(chr(n+65)for n in d) ``` I believe that this meets the specs exactly (Including the `'>'` at the start of the input prompts.) It does not validate input, so I think that it will just produce garbage output if you give it characters outside of `[A-Z]`. It also only checks the first letter of the input command. Anything starting with `D` will result in a decryption and anything else at all will result in an encryption. [Answer] ## C++ - 220 241 chars, 4 lines ``` #include<cstdlib> #include<cstdio> #define a scanf("%s" char i,s[99],t[99];int main(){a,t);a,s);if(t[0]>68){for(;s[i];++i)s[i]=(s[i]+(t[i]=rand()%26+65))%26+65;puts(t);}else for(a,t);s[i];++i){s[i]=65+t[i]-s[i];if(s[i]<65)s[i]+=26;}puts(s);} ``` Edit 1- The MSVS standard library seems to include a lot of unnecessary files which meant that ios had all the includes that I needed but this didn't work with other compilers. Changed ios for the actual files that the functions needed appear in cstdlib and cstdio. Thanks to Ilmari Karonen for pointing this out. [Answer] ## Python - 270 ``` import random i=raw_input m=i() a=i() r=range(len(a)) o=ord j=''.join if m=='ENCRYPT': k=j(chr(65+random.randint(0,25)) for x in r) R=k+"\n"+j(chr((o(a[x])+o(k[x]))%26+65) for x in r) elif m=='DECRYPT': k=i() R=j(chr((o(k[x])-o(a[x]))%26+65) for x in r) print R ``` Sample output: ``` $ python onetimepad.py ENCRYPT HELLOWORLD UXCYNPXNNV BBNJBLLEYY $ python onetimepad.py DECRYPT UXCYNPXNNV BBNJBLLEYY HELLOWORLD ``` Character count: ``` $ wc -c onetimepad.py 270 onetimepad.py ``` [Answer] # J : 94 bytes ``` 3 :0]1 c=:(26&|@)(&.(65-~a.&i.)) r=:1!:1@1: ((],:+c)[:u:65+[:?26$~#)@r`(r-c r)@.('D'={.)r 1 ) ``` All necessary white space counted. Commented version: ``` 3 :0]1 NB. Make a function and call it c=:(26&|@)(&.(65-~a.&i.)) NB. Adverb for operating on the alphabet NB. (used for adding and subtracting the pad) r=:1!:1@1: NB. Read input line and decide (right to left) ((],:+c)[:u:65+[:?26$~#)@r ` (r-c r) @. ('D'={.)r 1 NB. Encryption (ger 0) | Decryption (ger 1)| Agenda NB. pad,:(crypt=:plain + pad)| crypt - pad | If D is first input, do (ger 1), else do (ger 0) ) ``` [Answer] # C# (445 416) Forgot about Aggregate. Cut off a good bit. Somewhat golfed: ``` namespace G { using System; using System.Linq; using x = System.Console; class P { static void Main() { string p = "", c = "", k = ""; Random r = new Random(); int i = 0; if (x.ReadLine()[0] == 'E') { p = x.ReadLine(); k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90)); c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65)); x.WriteLine(k + "\n" + c); } else { k = x.ReadLine(); c = x.ReadLine(); p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65)); x.WriteLine(p); } } } ``` } Golfed: ``` namespace G{using System;using System.Linq;using x=System.Console;class P{static void Main(){string p="",c="",k="";Random r=new Random();int i=0;if (x.ReadLine()[0]=='E'){p=x.ReadLine();k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90));c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65));x.WriteLine(k+"\n"+c);}else{k=x.ReadLine();c=x.ReadLine();p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65));x.WriteLine(p);}}}} ``` [Answer] # JavaScript 239 ``` var F=String.fromCharCode function R(l){var k='';while(l--)k+=F(~~(Math.random()*26)+65);return k} function X(s,k,d){var o='',i=0,a,b,c while(i<s.length)a=s.charCodeAt(i)-65,b=k.charCodeAt(i++)-65,c=d?26+(a-b):a+b,o+=F((c%26)+65) return o} ``` Usage: ``` var str = "HELLOWORLD"; var key = R(str.length); var enc = X(str, key, false); console.log(enc); console.log(X(enc,key, true)); ``` [Answer] # C (159 + 11 for compiler flags) Golfed: ``` d(a,b){return(a+b+26)%26+65;}a;char s[999],b,*c=s-1;main(){g;a=*s-69;g;while(*++c)a?b=-*c,*c=getchar():putchar(b=rand()%26+65),*c=d(*c,b);a||puts("");puts(s);} ``` Ungolfed: ``` d(a,b){ //*a = (*a + b - 2*65 + 26) % 26 + 65; return (a + b + 26) % 26 + 65; } a; char s[999], b, *c = s-1; main(){ gets(s); a = *s - 69; // -1 if decrypt 0 if encrypt gets(s); while(*++c){ if(!a) putchar(b = rand() % 26 + 65); // 'A' else b = -*c, *c = getchar(); *c = d(*c,b); } if(!a) puts(""); puts(s); } ``` Compile with `-Dg=gets(s)`. Example: ``` $./onetimepad ENCRYPT FOOBAR >PHQGHU >UVEHHL $./onetimepad DECRYPT PHQGHU UVEHHL >FOOBAR ``` [Answer] # Ruby - 184 179 177 chars ``` def g;gets.scan(/./).map{|c|c.ord-65}end m,=g k=(s=g).map{rand 26} m==4?(puts k.map{|c|(c+65).chr}*'';y=:+):(k,s=s,g) puts s.zip(k).map{|c,o|(c.send(y||:-,o).to_i%26+65).chr}*'' ``` Run it like this: `$ ruby pad-lock.rb` Here is the ungolfed version if anyone is interested (it's not quite up to date with the golfed one though) ``` def prompt gets.scan(/./).map{ |c|c.ord - 65 } end mode = prompt[0] operator = :- secret = prompt key = secret.map { |char| rand(26) } if mode == 4 # the letter E, or ENCRYPT key.map { |char| print (char + 65).chr } puts operator = :+ else # make the old secret the new key, # and get a new secret (that has been encrypted) key, secret = secret, prompt end chars = secret.zip(key).map do |secret_char, key_char| # if mode == 4 (E) then add, otherwise subtract i = secret_char.send(operator, key_char).to_i ((i % 26) + 65).chr end puts chars.join("") ``` ]
[Question] [ Given the following input to the program: 1. List of block start characters 2. List of block end characters 3. A string to format format the string with the blocks delimited by the two character sets indented. Formatting is done with two spaces per level and the parentheses are placed as shown in the example below. You may assume the sets of opening and closing characters to be disjoint. E.g. for `{[(<` and `}])>` as the opening and closing character sets and the following string: ``` abc{xyz{text[note{comment(t{ex}t)abc}]}} ``` the following output would be expected: ``` abc { xyz { text [ note { comment ( t { ex } t ) abc } ] } } ``` You may not hard-code the list of “parentheses” characters. How input is given is not specified, though; this could be either command-line arguments or via standard input, as you wish. [Answer] ## Ruby, 106 101 96 95 ``` s,e,i=$* i.scan(/[#{z=Regexp.quote s+e}]|[^#{z}]*/){|l|puts' '*(s[l]?~-$.+=1:e[l]?$.-=1:$.)+l} ``` Input is provided via the command line. [Answer] ## Perl - 131 96 94 chars ``` $i="";for$_(split/([\Q$ARGV[0]$ARGV[1]\E])/,$ARGV[2]){$i=~s/..// if/[\Q$ARGV[1]\E]/;print "$i$_\n"if$_;$i.=' 'if/[\Q$ARGV[0]\E]/;} ``` Seems like there should be room for eliminating common expressions, at least, but it's a quick take that handles the example, as well as Joey Adams's hypothetical about arbitrary brackets. --- There was, indeed, plenty of room for improvement: ``` $_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;for(split/($s|$e)/){print" "x($i-=/$e/),"$_\n"if$_;$i+=/$s/} ``` --- ...and still a little more: ``` $_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;map{print" "x($i-=/$e/),"$_\n"if$_;$i+=/$s/}split/($s|$e)/ ``` [Answer] # JavaScript, ~~255~~ ~~227~~ 205 characters ~~Hey, its length fits perfectly in a byte! :D~~ ``` function(s,e,t){R=eval.bind(0,"Array(n).join(' ')");for(i=n=0,b=r='';c=t[i++];)~s.indexOf(c)?(r+=b,b='\n'+R(++n)+c+'\n '+R(++n)):~e.indexOf(c)?b+='\n'+((n-=2)?R()+' ':'')+c+'\n'+(n?R()+' ':''):b+=c;return r+b} ``` It's a function, pass it the start characters, the end characters, then the text. [Answer] ## Python – 162 chars ``` i=f=0 s="" l,r,z=[raw_input()for c in' '] o=lambda:s+("\n"+" "*i)*f+c for c in z: if c in l:f=1;s=o();i+=1 elif c in r:i-=1;f=1;s=o() else:s=o();f=0 print s ``` [Answer] # Python 2.7.X - 136 chars ``` import sys a,c=sys.argv,0 for i in a[3]: if not(i in a[2]):print ' '*c+i else:print ' '*(c-4)+i if i in a[1]:c+=4 if i in a[2]:c-=4 ``` **Usage** : $ ./foo.py '(' ')' '(ab(cd(ef)gh)ij)' **Resulting Output:** ``` ( a b ( c d ( e f ) g h ) i j ) ``` [Answer] ### C - ~~213~~ 209 I hate stupid mistakes... >.< ``` #include<stdio.h> #include<string.h> int main(int i,char**s){for(char q,r,c,t,a=0;~(c=getchar());t=q|r){q=!!strchr(s[1],c);a-=r=!!strchr(s[2],c);for(i=0;t|q|r&&i<2*a+1;putchar(i++?' ':'\n'));a+=q;putchar(c);}} ``` Reads left-parens from first command-line argument, right-parens from second argument, and input to indent on stdin. Pretty-printed & commented: ``` int main(int i, char **s) { for (char q, r, /* is left-paren? is right-paren? */ c, /* character read from input */ t, /* last char was a paren-char */ a=0; /* indentation */ ~(c = getchar()); t = q|r) { q = !!strchr(s[1],c); a -= r = !!strchr(s[2],c); for (i=0; t|q|r && i<2*a+1; putchar(i++? ' ' : '\n')); a += q; putchar(c); } } ``` [Answer] # **C (159 225 chars)** ``` #define q(s,c)strchr(s,c) #define p(i,j,k)printf("\n%*s%c%c%*s",i,"",*s,k,j,"") g(char*b,char*e,char*s){int i;for(i=0;*s;s++)q(b,*s)?p(i-2,i+=2,'\n'):q(e,*s)?q(b,*(s+1))||q(e,*(s+1))?p(i-=2,i-2,0):p(i-=2,i-2,'\n'):putchar(*s);} ``` It cost me 66 extra characters just to fix the bug with the empty lines :( Frankly, I need a fresh approach, but I'll call it a day for now. ``` #define p(i,j)printf("\n%*s%c\n%*s",i,"",*s,j,"") f(char*b,char*e,char*s){int i;for(i=0;*s;s++){strchr(b,*s)?p(i-2,i+=2):strchr(e,*s)?p(i-=2,i-2):putchar(*s);}} ``` A rather quick & dirty approach. It has a bug of producing empty lines between consecutive closing parenthesis, but otherwise it does the job (or so I think). I will revisit it for a better & cleaner solution, sometime this week. **char \*b** is the opening parenthesis set, **char \*e** is the closing parenthesis set and **char \*s** is the input string. [Answer] ## Scala(2.9), 211 characters ``` object P extends App{def x(j:Int)={"\n"+" "*j} var(i,n)=(0,"") for(c<-args(2)){if(args(0).exists(_==c)){print(x(i)+c) i+=1 n=x(i)}else{if(args(1).exists(_==c)){i-=1 print(x(i)+c) n=x(i)}else{print(n+c) n=""}}}} ``` [Answer] ## Perl - 89 85 bytes A version of Hojung Youn's answer which accepts the block characters via two arguments. ``` #!perl -p BEGIN{$b=pop;$a=pop}s/([$a])|([$b])|\w+/" "x($1?$t++:$2?--$t:$t)."$& "/ge ``` Called like: ``` perl golf.pl<<<'abc{xyz{text[note{comment(t{ex}t)abc}]}}' '[{(<' ']})>' ``` [Answer] ## Python3, 184 182 chars ``` import sys _,p,q,t=sys.argv i,f,x=0,1,print for e in t: if e in p:f or x();x(' '*i+e);i+=2;f=1 elif e in q:f or x();i-=2;f=1;x(' '*i+e) else:not f or x(' '*i,end='');f=x(e,end='') ``` Example: ``` $ python3 ./a.py '{[(<' '}])>' 'abc{xyz{text[note{comment(t{ex}t)abc}]}}' abc { xyz { text [ note { comment ( t { ex } t ) abc } ] } } ``` [Answer] ## Groovy, 125 ``` p=args;i=0;s={a,b->"\n"+"\t"*(b?i++:--i)+a+"\n"+"\t"*i};p[0].each{c->print p[1].contains(c)?s(c,1):p[2].contains(c)?s(c,0):c} ``` You can save the script in a file indent.groovy and try it with: groovy indent.groovy "abc{xyz{text[note{comment(t{ex}t)abc}]}}" "{[(" ")]}" [Answer] # Python - 407 ``` from sys import*;o=argv[1];c=argv[2];t=argv[3];p=0;n=False;a=lambda:h not in e;b=lambda s:print(s+(" "*p)+h);r="";e=o+c for h in t: for k in o: if h==k: if(r in e)and(r!=""):b("") else:b("\n") p+=2;n=True;break for k in c: if h==k: p-=2 if(r in e)and(r!=""):b("") else:b("\n") n=True;break if a()and n:print((" "*p)+h,end="");n=False elif a():print(h,end="") r=h ``` An ungolfed version of the program: ``` import sys open_set = sys.argv[1] close_set = sys.argv[2] text = sys.argv[3] spaces = 0 newline = False a = lambda : char not in b_set b = lambda s: print(s + (" " * spaces) + char) prev = "" b_set = open_set + close_set for char in text: for bracket in open_set: if char == bracket: if (prev in b_set) and (prev != ""): b("") else: b("\n") spaces += 2 newline = True break for bracket in close_set: if char == bracket: spaces -= 2 if (prev in b_set) and (prev != ""): b("") else: b("\n") newline = True break if a() and newline: print((" " * spaces) + char, end="") newline = False elif a(): print(char, end="") prev = char ``` The arguments to the program are (in order): the opening parentheses, the closing parentheses, and the text to indent. Example ($ is command line prompt): ``` $ python indent.py "{[(<" "}])>" "abc{xyz{text[note{comment(t{ex}t)abc}]}}" abc { xyz { text [ note { comment ( t { ex } t ) abc } ] } } ``` [Answer] # C 284 Non White space Characters I'm no fan of obfuscation but well... ``` #include<cstdio> #include<cstring> #define g printf #define j char int main(int a,j**b){int c=0;for(j*f=b[3];*f!='\0';++f){if(strchr(b[1],*f)!=0){g("\n%*c\n%*c",c,*f,c+2,'\0');c+=2;}else if(strchr(b[2],*(f))!=0){c-=2;g("\n%*c",c,*f);if(strchr(b[2],*(f+1))==0)g("\n%*c",c,'\0');}else putchar(*f);}} ``` Usage: ./program start\_brackets end\_brackets string\_to\_parse [Answer] ## php (187) (153) ``` function a($s,$o,$e){while(''!=$c=$s[$i++]){$a=strpbrk($c,$o)?2:0;$b=strpbrk($c,$e)?2:0;echo ($a+$b||$r)?"\n".str_pad('',$t-=$b):'',$c;$t+=$a;$r=$a+$b;}} ``` Function takes string, opening delimiters, ending delimiters as arguments. [Answer] # C, 256 Parameters: * **e** is the ending char, * **n** is the indentation, * **b** the opening brackets, * **d** the closing brackets. I broke the code up to avoid the horizontal scrollbar. ``` #define r char #define P(c) putchar(c); #define N P(x) #define W printf("%*s",n,""); r*s,x='\n';i(r e,int n,r*b,r*d){r*t=s,*p;int l=0;W while(*s!=e) {if(p=strchr(b,*s)){if(s!=t){N W}P(*s++)N i(d[p-b],n+2,b,d); N W P(*s++);l=1;}else{if(l){N W l=0;}P(*s++)}}} ``` Complete program is 363 characters. ``` #include <stdlib.h> #include <string.h> #include <stdio.h> #define r char #define P(c) putchar(c); #define N P(x) #define W printf("%*s",n,""); r*s,x='\n';i(r e,int n,r*b,r*d) {r*t=s,*p;int l=0;W while(*s!=e) {if(p=strchr(b,*s)){if(s!=t){N W} P(*s++)N i(d[p-b],n+2,b,d); N W P(*s++);l=1;}else{if(l){N W l=0;} P(*s++)}}}main(int c,r*v[]){s = v[3];i('\0',0,v[1],v[2]);} ``` [Answer] # Powershell, 146 Bytes ``` param([char[]]$s,[char[]]$e,[char[]]$f)$f|%{}{if($_-in$s){$o;' '*$i+$_;$o=' '*++$i;}elseif($_-in$e){$o;' '*--$i+$_;$o=' '*$i}else{$o+=$_}}{$o} ``` Ungolfed Explanation ``` param([char[]]$start, # Cast as array of Chars [char[]]$end, [char[]]$string) $string | foreach-object { } { # For every char in string. Empty Begin block if ( $_ -in $start ) { # If char is in start $o # Print stack ($o) ' ' * $i + $_ # Newline, indent, insert start char $o = ' ' * ++$i # Set stack to ident (incremented) } elseif ( $_ -in $end ) { # If char is in end $o # Print stack ' ' * --$i + $_ # Newline, decrement indent, insert end char $o = ' ' * $i # Set stack to indent } else { $o+ = $_ # Otherwise add character to stack } } { $o } # Print remaining stack (if any) ``` [Answer] # C, 181 characters ``` #define d(m,f)if(strchr(v[m],*s)){puts("");for(j=f;j--;)printf(" ");} i;main(j,v,s)char**v,*s;{for(s=v[3];*s;s++){d(1,i++)d(2,--i)putchar(*s);d(1,i)if(!strchr(v[2],*(s+1)))d(2,i)}} ``` Pretty much the most straightforward approach imaginable. Iterate through the string (v[3]), if it's a left brace (as defined in v[1]), increase the indent level, if it's a right brace (as defined in v[2]), decrease the indent level. ]
[Question] [ Let's define a function \$f\$ which, given a positive integer \$x\$, returns the sum of: * \$x\$ * the smallest digit in the decimal representation of \$x\$ * the highest digit in the decimal representation of \$x\$ (which may be the same as the smallest one) For instance: * \$f(1)=1+1+1=3\$ * \$f(135)=135+1+5=141\$ * \$f(209)=209+0+9=218\$ We now define the sequence \$a\_k = f^k(1)\$. That is to say: * \$a\_1=1\$ * \$a\_k=f(a\_{k-1})\$ for \$k>1\$ The first few terms are: ``` 1, 3, 9, 27, 36, 45, 54, 63, 72, 81, 90, 99, 117, 125, 131, 135, 141, 146, ... ``` ## Challenge Given a positive integer \$x\$, you must return the smallest \$n\$ such that \$f^n(x)\$ belongs to the sequence. Or in other words: how many times \$f\$ should be applied consecutively to turn \$x\$ into a term of the sequence. You can assume that you'll never be given an input for which no solution exists. (Although I suspect that this can't happen, I didn't attempt to prove it.) You may also use 1-based indices (returning \$n+1\$ instead of \$n\$). Please make it clear in your answer if you do so. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Examples * Given \$x=45\$, the answer is \$0\$ because \$x\$ is already a term of the sequence (\$a\_6=45\$). * Given \$x=2\$, the answer is \$3\$ because 3 iterations are required: \$f(2)=2+2+2=6\$, \$f(6)=6+6+6=18\$, \$f(18)=18+1+8=27=a\_4\$. Or more concisely: \$f^3(2)=27\$. (These are the 0-based results. The answers would be \$1\$ and \$4\$ respectively if 1-based indices are used.) ## Test cases ``` Input : 0-based output 1 : 0 2 : 3 4 : 15 14 : 16 18 : 1 45 : 0 270 : 0 465 : 67 1497 : 33 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` $‚€λDZsßO}`.i1k ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f5VHDrEdNa87tdokqPjzfvzZBL9Mw@/9/EzNTAA "05AB1E – Try It Online") ``` $‚ # pair 1 and the input € # for each k of those two values λDZsß++} # calculate the infinite sequence given by f^n(k): D # duplicate the previous value Z # take the maximum digit of the copy without removing it from the stack sß # swap to the copy and get the minimum digit O # sum previous value, maximum digit and minimum digit ` # push both infinite sequences seperately on the stack .i # for each value in the sequence starting with the input: # is it contained in the other (non-decreasing) sequence? 1k # print the index of the first 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~20~~ 15 bytes *Edit: -5 bytes thanks to Razetime* ``` V£₁1₁ ¡S+o§+▲▼d ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8X/YocWPmpoMgZjr0MJg7fxDy7UfTdv0aNqelP///0cb6hjpmOgYApGFjompjpG5gY6JmSlQwNI8FgA "Husk – Try It Online") 1-based output. ``` ¡S+o§+▲▼d # helper function ₁: ¡ # generate infinite sequence by repeatedly applying: S+o§+▲▼d # function f: S+ # add the input to §+▲▼ # sum of the max and the min of o d # the digits of the input V£₁1₁ # main program: V # index of first truthy result of ... £ # getting the index (or zero if absent) of ₁1 # the infinite sequence of helper function starting with 1 ₁ # in the infinite sequence of helper function ₁ starting with the program input ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` Nθ≔¹η≔⁰ζW⁻θη¿‹ηθ≧⁺Σ⁺⌊Iη⌈Iηη«≧⁺Σ⁺⌊Iθ⌈Iθθ≦⊕ζ»Iζ ``` [Try it online!](https://tio.run/##lY/NCsIwEITP9ily3EAEC4JIT@KpYKXoE9Qam0ASmz@Vis8eE3so4snbfsPMLNOyxrTXRoRQqt67vZcnakDjIttYyzsFOUFsogVBQ6Q744IiqLjyFnRyYMQvCHbUWmAE6chV04@hA@@Yg1p4S9DRy8@VolxG2DbWQYyT6H98KUlLn6mwFD2z2R99@qdPj31p11QEpWoNlVQ5eh53vbLacOXGzIBxEUK@XK/C/Cbe "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `x`. ``` ≔¹η ``` Start with `a=1`. ``` ≔⁰ζ ``` Start with `n=0`. ``` W⁻θη ``` Repeat until `x=a`. ``` ¿‹ηθ≧⁺Σ⁺⌊Iη⌈Iηη ``` If `a<x` then calculate `a=f(a)`. ``` «≧⁺Σ⁺⌊Iθ⌈Iθθ ``` Otherwise calculate `x=f(x)`, ... ``` ≦⊕ζ» ``` ... and increment `n`. ``` Iζ ``` Output `n`. [Answer] # [R](https://www.r-project.org/), 109 bytes (or **[R](https://www.r-project.org/)>=4.1, 95 bytes** replacing both `function` appearances with `\`) ``` function(x,`!`=function(n)n+sum(range(n%/%10^(0:log10(n))%%10))){while({F=F+1;i=1;while(i<x)i=!i;i-x})x=!x;F} ``` [Try it online!](https://tio.run/##Pc3fCoIwFAbw@55CCWEHi7b8V67d@hhhRLMDNsGSBuKzr01t5@73ncN3eiOFkYO6f7BTRO/qsBaeClT8Hl6kv6nmQVR0iBi9Elq2XcOo3UJkAwAYv09sH2SsRBUzjoLxJcCLBhQhctzrCbQINa8mIwmDbeCmDOhGkqNXYpV6scySrbbMHU@e7jb7a@4p6MxFaZ6tyou551w42yeJ@QE "R – Try It Online") Returns 1-based result. [Answer] # Scala, 100 bytes ``` a(_)indexWhere(? =>a(1)takeWhile?.>=toSet?) val a=Stream.iterate(_:Int)(x=>x+s"$x".min+s"$x".max-96) ``` [Try it in Scastie!](https://scastie.scala-lang.org/vZnraF4UTAquZYeOreMAUQ) Pretty simple solution. `a` is a function that makes an infinite list of the sequence, given a starting number. We make a sequence starting at `x` using that, and find the first index where an item is inside the sequence starting at `1`. Since the sequence can only be added to, it's monotonic and therefore safe to only check the elements which are less than or equal to `x`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 114 bytes ``` d;s;m;x;f(n){for(s=m=n,x=0;n;n/=10)d=n%10,m=d<m?d:m,x=d>x?d:x;s+=m+x;}g(n){for(s=1;n>s;s=f(s));s=n<s?1+g(f(n)):0;} ``` [Try it online!](https://tio.run/##XU/RbsIwDHznK6xKSAkNooUBAxN4mPYVKw8oSbtqa0BNpUVD/fV1LpQyFsWJc76zc2qcKdU0Gh0W6DFllp/TY8mcLKQVXkZo0U5kHHEt7TCORCH1ptjpdUFFvfWUeXShLEKPdXZXx2i3Dp1MmeOcbrtxuzjMWDuAryOsm9xWUBxyyzicB0CrBSrjKve2BwnnWMBUwJOAuI1nSueELCNKFvMWXS1r7IXGn4yqjL5qiTQjSktbUAiILnuxJHx2V41AvRv1YcqrKkj86zTxqxeKeSDg73sWdDKyB6ydmFttPMki7NINuPzbHFN2@wufdMCoRxDC8MK@me6NU6er@Ut5jw/VkqoZq/gjagjtff@XnUqipCwYahhvgc6hSyyZqgSUovddSmn2Xdt6UDc/Kv08ZK4Zf/0C "C (gcc) – Try It Online") [Answer] ## JavaScript (ES6), ~~104~~ ~~86~~ 82 bytes *-2 thanks to @emanresuA and @Shaggy, and another -2 from @tsh (with an honorable mention for @m90 :p)* ``` r=x=>(f=x=>x+Math.min(...x+="")+Math.max(...x),g=y=>y<x?g(f(y)):y>x)(1)&&r(f(x))+1 ``` [Try it online!](https://tio.run/##LchBCoMwEAXQu7gIfwgOBAptF5Mb9BBBarRYU6LIBLx7tKWbt3ivsIWly@NnbbdbrVlUPKIU8cXrvpdWjYlA/321j7AO/B5nMLNaaRr6V9BfEaHQiSNjMnqcYV3t0ryk6clTishwl/uVqB4 "JavaScript (V8) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~128~~ \$\cdots\$ ~~98~~ 94 bytes ``` f=lambda n:n+int(min(`n`))+int(max(`n`)) g=lambda n,s=1:n>s and g(n,f(s))or n<s and-~g(f(n),s) ``` [Try it online!](https://tio.run/##TU/BboMwDL3nKywujTVXKjCgRU0v075inVQGgaKtLiI50B3268yh1bTIT/J7fpZfhps/XzmZ59Z8VZePpgIu@alnry896xOfEO@smu5MdX9GciYu@eCg4gY6zdRqh3gdgfeLtv7pdKsZyeHsrfMODOiYICF4JogDttJmohQbafIsqLsClZ0GW3vbhAWZpKKHWS4g2CyVF6KnqOqzrT/tGJzRcXpNjtPuRZBFBP95GqFqJZonsNAzfPeDXjIJfxzDUoG8kLLTHhcyjPL5sLSC9QFWBOKHx8k3a4x7n38B "Python 2 – Try It Online") Saved 17 bytes thanks to [gsitcia](https://codegolf.stackexchange.com/users/95116/gsitcia)!!! \$0\$-based return value and returns `False` for \$0\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;1DṀ+ṂƊ+Ɗ€</¦⁻/пḢ€QL ``` A monadic Link that accepts a positive integer and yields a positive integer (using the 1-indexed option). **[Try it online!](https://tio.run/##ATQAy/9qZWxsef//OzFE4bmAK@G5gsaKK8aK4oKsPC/CpuKBuy/DkMK/4bii4oKsUUz///8xNDk3 "Jelly – Try It Online")** ### How? Perhaps there is a more terse approach, but I have not thought of one yet. Starts with the input and \$1\$ and applies \$f\$ to the minimum of the two while they are unequal, then counts the number of values visited from the input to the final value. ``` ;1DṀ+ṂƊ+Ɗ€</¦⁻/пḢ€QL - Link: integer, x ;1 - concatenate a one п - collect while... ⁻/ - ...condition: reduce by not-equal € ¦ - ...do: sparse application... </ - ...to indices: reduce by less-than Ɗ - ...action: last three links as a monad, f(v) D - decimal digits Ṁ+ṂƊ - minimum plus maximum + - add (v) Ḣ€ - head each (all the values we got from x's side) Q - deduplicate L - length ``` --- #### 0-indexed alternative Also 21 bytes: ``` ;1DṀ+ṂƊ+Ɗ€</¦⁻/пnƝSḢ ``` [Answer] # [Julia 1.0](http://julialang.org/), 62 bytes ``` !a=a+sum(extrema(digits(a))) >(x,a=1)=x<a ? 1+(!x>a) : a!=x>!a ``` [Try it online!](https://tio.run/##RczLCsIwEIXh/TxFgpsZKqVj01aLiQ8iLgYsktIW6QXy9lEpwbP6Nv/pt8ELhxi1WMmWbcQurHM3Cj79y68LChGBw3AUy2TDVdRNcYY6OCHVKtE2OC3xPftpHaYcc4d3YPXboVUFnBJLMIlcAZvkGvicDKb6h02RaOpqZ918w0uz/5XwIIof "Julia 1.0 – Try It Online") ### Explanation * `!` is the function `f` * `a` is `fⁿ(1)` (we don't care about n) * `1+(!x>a)`: if `x<a`, we compute `f(x)` and add 1 to the result * `a!=x>!a` is parsed `a!=x && x>!a` + returns `false` if `a==x` (false is equivalent to 0) and doesn't evaluate the second part + if `a!=x`, computes `x>!a`, which means we compute `f(a)` and return `x>f(a)` ]
[Question] [ Write a program or function that fulfills the following * Scores less than 101 bytes under normal [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules * Takes no input1 and always outputs a single integer. * Every integer is a possible output. Your score will be the probability of the most frequent integer occurring, with a lower scoring being the goal. That is \$\mathrm{sup}\left\{P(x)|x\in\mathbb{Z}\right\}\$. Since a few of these properties are not program decidable, you should be ready to provide a proof that your answer is valid and obtains the score it claims. --- 1 You may optionally take a stream of random bits, or a subroutine which produces random bits on each call as an input to provide randomness. Each bit will be uniform and independent of other bits. [Answer] # [Python 3](https://docs.python.org/3/), score \$\approx \frac{1}{\sqrt{8\pi\lambda}}\$ where \$\lambda \approx 9\uparrow\uparrow (9\uparrow \uparrow (9 \uparrow \uparrow (9 \uparrow \uparrow (9\uparrow\uparrow 9)))))\$ [This is `g(9)`](https://www.wolframalpha.com/input/?i=9%5E9%5E9%5E9%5E9%5E9%5E9%5E9%5E9%5E0), approximately `10^(10^(10^(10^(10^(10^(10^8.567841344463464))))))`; I'm doing `g(g(g(g(g(9)))))` to get the \$\lambda\$ above. \$a \uparrow b\$ ([Knuth's up-arrow notation](https://en.m.wikipedia.org/wiki/Knuth%27s_up-arrow_notation)) is `a` to the power of `b`. \$a \uparrow\uparrow b\$ is `a` to the power of itself, `b` times. So \$9\uparrow\uparrow 3 = 9^{9^9}\$ and \$9\uparrow\uparrow 9 = 9^{9^{9^{9^{9^{9^{9^{9^{9}}}}}}}}\$ ``` from numpy.random import* g=lambda n:n and 9**g(n-1) print(choice([-1,1])*poisson(g(g(g(g(g(9))))))) ``` [DON'T Try it online!](https://tio.run/##Tck9CoAwDEDh3VN0TIoKxUnBk4hD/asFm4Rah56@Ovq2jyc5nUxdKUfkoOgJkttoafvgg3BMunLjZcOyWUUDqW@pXmsH1BisJHpKsJ7s1x2mxtRmRi3s75sJHPT/ELGUFw "Python 3 – Try It Online") Blows the recursion limit, of course. How it works: The [Poisson distribution](https://en.m.wikipedia.org/wiki/Poisson_distribution) is a random distribution that, by itself, already generates random positive integers from 0 to infinity. This distribution takes a parameter, \$\lambda \$, that affects how likely the smaller integers are. What we have to do is set \$\lambda\$ in such a way that small numbers become **very** unlikely. Then we use [the wiki page](https://en.m.wikipedia.org/wiki/Poisson_distribution) again to realize the *mode* of the distribution is related to its parameter and then we plug the mode into the probability density function to get the program's score. After that we use Sterling's approximation to simplify the expression to something that is only slightly more digestible. If I really can't waive the recursion limit then a similar approach with a loop gives ### [Python 2](https://docs.python.org/2/), score \$\approx \frac{1}{\sqrt{8\pi\lambda}}\$ where \$\lambda = 9\uparrow\uparrow (9 \uparrow\uparrow 7)\$ ``` from numpy.random import* print(choice([-1,1])*poisson(eval('**'.join(`9`*9**9**9**9**9**9**9**9)))) ``` [Don't try it online!](https://tio.run/##bYwxCoAwDEV3T@FmDCro5llEUNTSiE1CrYKnrwVXP294b/n6BCvcxWi8uJwvp0/jZ15TkFPxATP1xAEWK7RsMNRt1Y4lqtB5CsN2zwcUiEWzCzFM/YQ9/lGmxe/KQJf8BQ "Python 2 – Try It Online") Got some more bigness because @xnor taught me how `join` works when used directly on strings. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score 0.5 / 1000!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *bug fix thanks to FryAmTheEggman* *+1 `!` thanks to ExpiredData* ``` [₄!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!LΩ#¼]¾D±)Ω ``` [(dont't) Try it online!](https://tio.run/##yy9OTMpM/f8/@lFTiyKNgM@5lcqH9sQe2udyaKPmuZX//wMA "05AB1E – Try It Online") (will timeout). [Try it online without the factorials](https://tio.run/##AR0A4v9vc2FiaWX//1vigoRMzqkjwrxdwr5EwrEpzqn//w) ``` [ ] # loop: ₄ # 1000 !!...! # take the factorial, 88 times LΩ # pick a random number from 1 to that many # # if the number was 1, exit the loop ¼ # increment counter_variable ¾ # after the loop: push counter_variable D± # push its bitwise negation ) # wrap the two in a list Ω # pick a random element of that list ``` Any integer would work instead of `1000!!...!`, so this approach could score as low as `0.5 / BB(89)`, where `BB` is 05AB1E's Busy Beaver function. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 / 2M ?\*, \* Any help scoring this appreciated, 0 and -1 are the two equally most likely answers at \$\frac{1}{2M}\$ - see code breakdown. Inspiration taken from [Grimmy's 05AB1E answer](https://codegolf.stackexchange.com/a/200809/53748). ``` ‘ɼµ⁹!!!!;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊX’µ¿~2X¤¡ ``` [No point trying this online!](https://tio.run/##y0rNyan8//9Rw4yTew5tfdS4UxEIrB81zFV8uKtbJexY12BgRzxqmHlo66H9dUYRh5YcWvj/PwA "Jelly – Try It Online") **[Try incrementing with 4 increment tetrations](https://tio.run/##y0rNyan8//9Rw4yTew5tNQLScGT9qGEukHq4q1sl7FgX8byIRw0zD209tL/OKOLQkkML//8HAA "Jelly – Try It Online")** (with incrementing the self-referential tetration is just doubling, also start with 2 rather than 256 so n=(2+1+1+1+1)\*2\*2\*2\*2=96, much more likely to terminate) ### How? ``` ‘ɼµ⁹!!!!;”!ẋ$VƊ;”!ẋ$VƊ ... X’µ¿~2X¤¡ - Link, no arguments ¿ - while... µ µ - ...condition: monadic chain (f(0)): ⁹ - 256 ! - factorial = 256*255*...*1 = a ! - factorial = a*(a-1)*...*1 = b ! - factorial = b*(b-1)*...*1 = c ! - factorial = c*(c-1)*...*1 = A Ɗ - last three links as a monad: $ - last two links as a monad: ”! - literal '!' character ẋ - repeated A times ; - concatenate to A -> number A with A '!' after it V - evaluate as Jelly code -> A!!..! * (A!!..!-1) * ... * 1 ;”!ẋ$VƊ - call that B and repeat that process ... - repeat 10 more times giving us M X - choose a random integer in [1..M] inclusive ’ - decrement (i.e. while random choice != 1) ¡ - repeat... ¤ - ...number of times: 2 - two X - random integer in [1,2] inclusive ~ - ...action: bitwise NOT ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 99 bytes ``` f(b,t)long b(),t;{for(b()/4503599627370496&&printf("-");t-9007199254740992;t=b())putchar(t%10+48);} ``` `b` is a function returning 52 random bits in the form of an integer in the range of [0, 9007199254740992). [Try it online!](https://tio.run/##ZY8xb4MwEIV3/worVZGtQkoSEopIu1QdOnRL10RgG3ISMcg@MjTKb6cGgqqoXnz36b27dyIohei6guU@8qrWJc0Z9zG9FLVhrnyO1uFqnSSbZbyKwyjZeF5jQGPBZsGMpxgkYRgvkmS5juIodH@Kr87GmxbFMTMMHxfhU/TC02v3AFpUrVR022qwKOfHN/LHHKgg/8egvkcIJ9UTMmQ1mZY5IOPkQqh7RmFr9IAZp3vKWC/jt367pQuXhFwJcRfQUwaanWuQk9uiaQXSfoVtlKBo04G32kKplaS9y2XXgJBV8KNkSgbB5DiUCpmH1qe7z6@Pw/fund8UdoiAdo7ng7Zu9p6OzVg7XwNj5Lv5k71gt0v79N0v "C (gcc) – Try It Online") [Answer] # Pyth, score of the order \$f\_{\varphi(\omega,0)+1}(10^{10^{64}})^{-1}\$ ``` M,-.<hG@H1.<hH@G1+@G1@H1D%ZYI<hZ0R,_hZ@Z1J,1 0V.<1Y=J%gZJY)R,hJ+@J1YVC*GCG=T@%TT1)K0WOT=+K1)IO2K.?_K ``` [Don't try it online!](https://tio.run/##DcexCsMgEIDhV8niYDXidVZ6kILJSQkESfGWjLkxQ5Y@vXX4@fiv3y2tfezogiScoTNjAtPr91ZclyDsN3sIIwNZGPzuAtRI6mSqerNCBgnqPj3SlGJBVQro7L9riSaDXtZndq8jt/YH) # Pyth, score of the order \$f\_{\varphi(\omega,0)+\omega}(4)^{-1}\$ (More precisely around \$f\_{\varphi(\omega,0)+4}(10)^{-1}\$) ``` M,-.<hG@H1.<hH@G1+@G1@H1D%dYI<hd0R,_hd@d1J,1 0V.<1Y=J%gdJY)R,hJ+@J1YVTVTVTVT=T@%TT1;WOT=+Z1)IO2Z.?_Z ``` [Don't try it online!](https://tio.run/##K6gsyfj/31dHV88mw93BwxBIeTi4G2oDMZDnopoS6WmTkWIQpBOfkeKQYuilY6hgEKZnYxhp66WanuIVqRmkk@Gl7eBlGBkWAoG2IQ6qISGG1uH@IbbaUYaanv5GUXr28VH//wMA) # Original python, but in the Pyth I made changes to increase size: ``` import random g=lambda G,H:(G[0]<<H[1]-H[0]<<G[1],G[1]+H[1]) def C(Z,Y): if Z[0]<0: return -Z[0],Z[1] J=(1,0) for N in range(1<<Y):J=C(g(Z,J)) return J[0],J[1]+Y T=10 for N in range(T): T=C(T,T)[1] K=0 while random.randint(0,T): K+=1 if random.randint(0,1): print(K) else: print(-K) ``` # Explanation This uses the extremely fast growing functions \$M\_n\$ defined [here](https://arxiv.org/pdf/2205.11017.pdf). They're actually my go-to when I need fast-growing functions, since they have a growth rate approaching \$\varphi(\omega,0)\$ and are simple to implement. Since they operate on fractions, I use the representation \$(a,b)=\frac{a}{2^b}\$. I iterate the operation \$n\mapsto M\_{2^n}(n)\$ starting from 10 roughly \$10^{10^{64}}\$ times, then output integers in a geometric distribution with parameter \$\frac{1}{n}\$, with signs attached. Thus, the score is \$\frac{1}{n}\$. Yes, you can slightly improve it, but it's so big your improvements are negligible. Yes, this absolutely dominates every other entry so far. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes, score 0.0005 ``` W‽φ⊞υωI⎇‽²Lυ±⊕Lυ ``` [Try it online!](https://tio.run/##PYpBCoNADADvvmKPWbCw9urRk1BEih8Ia3CFNUKMFV8fpdDOaWAmJpS4YjY70pzJwRt5XBeoQgjeu37fEuylO3xd9DKzQoObwkDCKOdvfvrSvYgnvd9bO5pQCVqOQgux0gj/@qU2s8cnXw "Charcoal – Try It Online") Link is to verbose version of code. `0` and `-1` have probabilities of 0.0005, then each subsequent integer has a probability 0.999 times that of the previous. Obviously there are still 75 bytes with which to create some form of arbitrary large expression in order to obtain a lower score, but the resulting code would take longer than the heat death of the universe to run, so it's not quite suitable for TIO. Explanation: ``` W‽φ ``` While a random number `0..999` is non-zero... ``` ⊞υω ``` ...push the empty string to the empty list. ``` I⎇‽²Lυ±⊕Lυ ``` Randomly print either the length of the list or `-1` minus that length. [Answer] # bash + linux, 1 / big number ``` cat /dev/random | hexdump -n `b` -ve '/1 "%02u"' ``` This program will print out 'b' bytes of decimal digits, where b is a program producing a random input number. (edited to try to be more infinity-ish, although technically still limited by the bash shell) ]
[Question] [ \$GF(9)\$ or \$GF(3^2)\$ is the smallest [finite field](https://en.wikipedia.org/wiki/Finite_field) whose order isn't a prime or a power of two. Finite fields of prime order aren't particurlarly interesting and there are already challenges for \$GF(2^8)\$ ([link](https://codegolf.stackexchange.com/questions/82867/define-a-field-with-256-elements)) and \$GF(2^{64})\$ ([link](https://codegolf.stackexchange.com/questions/160069/finite-field-multiplication)). ### Challenge First define nine elements of the field. These must be *distinct integers from 0 to 255,* or the one-byte characters their code points represent. State in your answer which representation you choose. Then implement two binary operations, addition and multiplication, satisfying the [field axioms](https://en.wikipedia.org/wiki/Field_(mathematics)#Definition): * Both operations must be commutative and associative. * Addition has the identity element \$0\$ and an additive inverse for each element. * Multiplication has the identity element \$1\$ and a multiplicative inverse for each element except \$0\$. * Multiplication distributes over addition: \$a·(b+c) = (a·b)+(a·c)\$ Addition and multiplication can be implemented as functions or programs taking two field elements and producing one field element. Since the field is really small, you can test the axioms exhaustively to check your implementation or verify the addition and multiplication tables. ### Mathematical construction Elements of \$GF(3^2)\$ can be interpreted as polynomials of the form \$P(x)=a x+b\$ over \$GF(3)\$. (Addition and multiplication in \$GF(3)=\{0,1,2\}\$ are the standard integer operations modulo 3.) Then addition in \$GF(3^2)\$ is simply the addition of two polynomials. Multiplication is defined by the product of two polynomials, reduced modulo a polynomial of degree 2 which is [irreducible](https://en.wikipedia.org/wiki/Irreducible_polynomial) over \$GF(3)\$. ### Example Mapping polynomials to integers with \$n=3a+b\$ and using the irreducible polynomial \$x^2+1\$ yields the following addition and multiplication tables. Note that there are other possible isomorphisms of these tables. ``` + 0 1 2 3 4 5 6 7 8 * 0 1 2 3 4 5 6 7 8 ------------------ ------------------ 0 | 0 1 2 3 4 5 6 7 8 0 | 0 0 0 0 0 0 0 0 0 1 | 1 2 0 4 5 3 7 8 6 1 | 0 1 2 3 4 5 6 7 8 2 | 2 0 1 5 3 4 8 6 7 2 | 0 2 1 6 8 7 3 5 4 3 | 3 4 5 6 7 8 0 1 2 3 | 0 3 6 2 5 8 1 4 7 4 | 4 5 3 7 8 6 1 2 0 4 | 0 4 8 5 6 1 7 2 3 5 | 5 3 4 8 6 7 2 0 1 5 | 0 5 7 8 1 3 4 6 2 6 | 6 7 8 0 1 2 3 4 5 6 | 0 6 3 1 7 4 2 8 5 7 | 7 8 6 1 2 0 4 5 3 7 | 0 7 5 4 2 6 8 3 1 8 | 8 6 7 2 0 1 5 3 4 8 | 0 8 4 7 3 2 5 1 6 ``` Test of distributivity using the tables above: $$5 · (2 + 7) = 5 · 6 = 4$$ $$(5 · 2) + (5 · 7) = 7 + 6 = 4$$ *Note that simply using addition and multiplication modulo 9 won't work.* ### Scoring This is code golf. Your score is the sum of bytes of the functions (or programs) for addition and multiplication. Lowest number of bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ ~~17~~ 16 bytes Uses 0, 1, 2, 10, 11, 12, 20, 21, 22 as the 9 field elements. Addition, 5 bytes: ``` OS3%J ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fP9hY1ev/4fX/ow2NdIwMYgE "05AB1E – Try It Online") or [print the entire table](https://tio.run/##ASoA1f9vc2FiaWX/MsOdw6NKw6/Do861/09TMyVK/33Dr0RU4oC5w7o5w7TCu/8). ``` O # sum of the inputs S # split to a list of digits 3% # mod 3 each digit J # join ``` Multiplication, 11 bytes: ``` PƵÈ%98%S3%J ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/4NjWwx2qlhaqwcaqXv8Pr/8fbWikY2QQCwA "05AB1E – Try It Online") or [print the entire table](https://tio.run/##ATIAzf9vc2FiaWX/MsOdw6NKw6/Do861/1DGtcOIJTk4JVMzJUr/fcOvRFTigLnDujnDtMK7/w). ``` P # product of the inputs ƵÈ% # mod 300 98% # mod 98 S3%J # split, mod 3 each digit, join ``` [Answer] # [Haskell](https://www.haskell.org/), ~~118 112~~ 107 bytes Here I use the numbers \$n= 0,1,2,\ldots,8\$ to represent the field elements. Internally these are converted to a list \$[a,b]\$ that represents a polynomial \$aX+b\$, (using \$a = \lfloor n/3 \rfloor\$ and \$b = n \bmod 3 \$, or \$n=3a+b\$), and we then proceed using the usual arithmetic using these polynomials in \$(\mathbb Z / 3\mathbb Z)[X]/(X^2+1)\$. In this case we have $$(aX+b) + (cX+d) = (a+c)X + (b+d)$$ and similarly $$\begin{align\*} (aX+b) \cdot (cX+d) &= acX^2+(ad+bc)X + bd \\ & \equiv ac(-1) +(ad+bc)X + bd \pmod {X^2+1} \\ & \equiv (ad+bc)X+(bd-ac) \end{align\*}$$ Thanks for -6 bytes @WheatWizard! ``` i x=[div x 3,x] --conert integer to polynomial/list representation j[a,b]=mod(a*3+mod b 3)9 --inverse of i s=(.i).(j.).zipWith(+).i --"sum" m[a,b][c,d]=j[a*d+b*c,b*d-a*c] --core function of "product" p=(.i).m.i --"product" ``` [Try it online!](https://tio.run/##ZY5Na8MwDIbv/hUiBOKP1BR66UKd@2C3HXYwPjixIe6S2MTpmo3998xp2GEMIaRXrx6kTsd32/fr6mAR0rgPWOBULgpdpS4bJQZvsKYnlio0cCJPKArMHeH4ygn/cuHNzR1mhDs0PAjZlkaJRFPDGtqWDTUHTVuFws4N3K2zbnoLcZ7ABwG3sXejjZBDZ7WxE1TQePOJ4N7ZySL4HQvACWFMFseC8@JcKJLMbTVZk79f8lriY1U9jzPh/KySmaYwOdH6sdVzjmP30KSSW5f7kAS0vv9OeTn8gRVCg3bjdjTc5tf0ag54/ztjGURCoK5ht15GyFIk/X@XZhAIWX8A "Haskell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~53 + 111 = 164~~ 23 + 61 = 84 bytes Edit: Saved 80 bytes by switching to @Grimmy's I/O format. However, the provided links include a footer which converts the output back to `0-8` format and formats the results into a square. Addition (~~53~~ 23 bytes): ``` \d+ $* M`1 3$ 0 T`34`_1 ``` [Try it online!](https://tio.run/##JdAxTsNQEIThfs9hogSkyDOhQT4AFR1lJIwUChoKRIe4Vg6Qi5k3/8qy/Ea71vs03x8/n1/v293@ed3Ol4ea7utlVZ2mmut1PT2ub9r2x8OxJo1nV@dLVg7ZuV2rjr9PfzXtbtdtXuaaF43X@RKSlOhEM3RpbGpsaslZhCQlOtEMXR6bHptechYhSYlONMPxY65X7lcAQiAIwiAQQqFm4ACCpCltaUxrmoNHASkihSRMAiVUgiVcAubAHJgDMzADMzADMzADc2AOzIEZmIEZmIEZmLsomqIquuqyuq2uq/vqwgL7Bw "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` \d+ $* ``` Convert both arguments to unary. ``` M`1 ``` Take the sum and convert to decimal. ``` 3$ 0 T`34`_1 ``` Modulo the last digit by 3, and modulo by 30. Multiplication (~~111~~ 61 bytes): ``` \d+ $* 1(?=1*;(1*))|. $1 1{300}|1{98}|1{30} M`1 T`3-8`012012 ``` [Try it online!](https://tio.run/##JdA9TsNAFATg/p3DRLYjrJ1xk2iFKKnoKFMYKRQ0FIjO8bVygFzM7MyTf0f77P00v19/3z@f@1P/tuyX6zG6MdC/vmCsPcZhuE3RIbDOpWw3rOeT7nPZIt4XxMcyP5@WArZz76dBw@04xOWqHw2aedwjpvW8RXd43PdSS5SKdlFPByUoUpFeZKBNok2i6h0OSlCkIr3IYJtkm2TVOxyUoEhFerF9qO2h/SEALIAJsAFGwAokww5DLElKWhKTmuTYA4EgEUSCTTAKVsEs2AXDKBgFo2A0jIbRMBpGw2gYBaNgFIyG0TAaRsNoGLMoN@Wq3FWWlW1lXdlXFibYPw "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` \d+ $* ``` Convert to unary. ``` 1(?=1*;(1*))|. $1 ``` Take the product. ``` 1{300}|1{98}|1{30} ``` Modulo by 300, 98 and 30. ``` M`1 ``` Convert to decimal. ``` T`3-8`012012 ``` Modulo the last digit by 3. [Answer] # MATLAB, ~~106~~ ~~104~~ 102 bytes We encode \$\operatorname{GF}(9)\$ as \$\{0,\ldots,8\}\$ and map to \$\mathbb{Z}[i]/\langle 3\rangle\$ in order to add and multiply: ``` e=@(x)mod(x,3)+i*fix(x/3) d=@(x)[1 3]*mod([real(x);imag(x)],3) a=@(x,y)d(e(x)+e(y)) m=@(x,y)d(e(x)*e(y)) ``` @A.Rex pointed out this clever improvement: ``` e=@(x)mod(x,3)+i*round(x/3) d=@(x)mod(real(x)^3+3*imag(x),9) a=@(x,y)d(e(x)+e(y)) m=@(x,y)d(e(x)*e(y)) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 88 bytes Uses numbers 0 to 8 to represent the elements. Uses Pari/GP's built-in polynomial arithmetic. ``` f(a)=a%3+a\3*x g(a)=Vecrev(a%(x^2+1),2)%3*[1,3]~ s(a,b)=g(f(a)+f(b)) p(a,b)=g(f(a)*f(b)) ``` [Try it online!](https://tio.run/##bYuxDoMgEEB3/oPkDo4BmRz8jS5tTc5GCUObCxqDS3@dBieHju/lPeGcXJRaF2AcWAfLj2CKig1v8yvPO7CGMnbWI3Wog7l7Cs@vWoFpwiFCO@0CE6KSqzOnq5LTZ4M3bzkV6KmnQgetUJynw3ls179CLkX9AQ "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 86 bytes Inspired by [Dustin G. Mixon's answer](https://codegolf.stackexchange.com/a/197658/9288). ``` f(a)=a%3+a\3*I g(a)=[real(a),imag(a)]%3*[1,3]~ s(a,b)=g(f(a)+f(b)) p(a,b)=g(f(a)*f(b)) ``` [Try it online!](https://tio.run/##bYsxDoUgEAV77mGyi0tBqCw8wD@D32JNlJCo2aAFNl4dxcrC7r3JjHAMxkvOEzC2XLma/07/lC@3iyPP96CwcAF95XRnyfWn2oBpwNZD6eoJBkQlb6YfliWGdYeF9xgSNNRQooM2SMbSYSyW6suQl5Ev "Pari/GP – Try It Online") [Answer] # x86 32-bit machine code, ~~21~~ 16 bytes ``` f7 e2 28 e0 01 d0 27 2c 03 a8 08 75 f9 d4 30 c3 ``` -5 with another shorter way to reduce the coefficients modulo 3. Uses polynomials modulo \$X^2 + 1\$, represented by integers by substituting \$ X = 16 \$. The selected values correspond to canonical forms \$ aX + b\$ for \$a,b \in \{0,1,2\}\$ – hexadecimal 00, 01, 02, 10, 11, 12, 20, 21, 22. Uses the `regparm(2)` calling convention – arguments in EAX and EDX, result in AL. The multiplication function begins at the start of the code, and the addition function begins after the first four bytes. [Try it online!](https://tio.run/##lZPNbqMwEMfvfoop1UqQ0Io4l6Zpug@yrdAADnFknMiYit0or750MAmBNIeWgwf/Z/ybD0z6kKdp09xLnaoqE/BS2kzuHjevbCQpmbQaw7IAn3lv@jFXuwQV5OtFXFTKyr366107MMucNgx6dgrQQwqIrO73ZZUAqhBw0x8iwCWeNiCwDvtDRuwF2ktAhvgFNu8VK0rrpKde2up/0EEuSbCAqJ5HvWAEOYMli2O01siksiKOfd@IfI@m8HkQBFDpUuZaZJBu0IxG4o9dGF7FJj8m0xS@A2VSWyhQar99QZOnYeecTGjzEbADa7sbH/xAVf5ZvMMKDlEdRSFNIpq5lbfrzCkzp8ycwp3CncL5cemY650Bl9USKFqSuVsBJzudBi6gS90@e0Nxa9/Cb/Bg4sEzmakXLPuAnrXtWNuWtSB7Zl2RPPgV8doLu1a277dQskPJE0oOUYeb0Dc9pMoh9UdF3iq07X10Y045wnMHNJTzd792Deo4XmZa2bItmSYJ9hTReekqV0ZThezImuZ/ulaYl81DMee00J@9osqE@gQ "C (gcc) – Try It Online") ## Explanation ``` gf9_multiply: mul edx ``` Multiply the given polynomials (which are in EAX and EDX). Put the product in EDX:EAX – the value is small enough to fit in EAX, so EDX becomes 0. ``` sub al, ah ``` Subtract AH (the second-lowest byte of EAX) from AL (the lowest byte of EAX). This reduces the polynomial modulo \$ X^2 + 1 \$: AL now represents a polynomial equivalent to the result modulo 3, of the form \$ aX+b \$ for \$ 0 \le a \le 8, -4 \le b \le 4 \$. ``` gf9_add: add eax, edx ``` Here, the two functions merge. For `gf9_add`, this adds EDX and EAX (the arguments), so that AH represents a polynomial equivalent to the result modulo 3, of the form \$ aX+b \$ for \$ 0 \le a \le 4, 0 \le b \le 4 \$. For `gf9_multiply`, EDX will be 0 when we get here, and this instruction leaves EAX unchanged. ``` repeat: daa ``` This is one of several x86 instructions designed for handling numbers in [binary-coded decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal). `daa` stands for Decimal Adjust (AL) after Addition. "Decimal" in these instruction names refers to packed BCD, which puts one decimal digit in each [nybble](https://en.wikipedia.org/wiki/Nybble). As the instruction's name indicates, its intended purpose is to be used after a regular `add` or similar instruction, to correct the result for BCD. So what correction is needed? Consider the simple example of adding 2 (binary 00000010) and 8 (binary 00001000). The result of regular addition is regular 10 (binary 00001010), but the BCD sum should be BCD 10 (binary 00010000). The result thus has to be increased by 6, to change 10 to 16. That is one of the things that `daa` does. But how does it know whether this +6 should be applied? In this case, it is obvious from the value itself, because binary 1010 is not a valid BCD digit. But if the calculation were instead 8 plus 8, the result would be binary 00010000, which is valid BCD for 10, but the correct BCD sum is 16. This is where the "auxiliary carry flag" (AF) comes in. It is set by the `add` instruction based on whether it results in a carry across the centre of the byte, which covers the cases where the low nybble reaches 16 or higher and wraps back around to a valid BCD digit. The instruction `daa` adds 6 to AL if the low nybble of AL is 10 to 15 or AF is 1. `daa` also makes a similar adjustment for the high nybble of AL: if the high nybble's original value is 10 to 15, or the carry flag (CF) is 1 (which is based on carries off the top of the number), it adds 6 to the high nybble. Here, the flags AF and CF come from the preceding `add`, which always sets them to 0 here. The low nybble is 10 to 15 iff, in the current polynomial \$ aX+b \$ (with \$ 0 \le a \le 8, -4 \le b \le 4 \$), \$ b \$ is -4 to -1, in which case adding 6 results in \$ b \$ being 2 to 5. The high nybble is 10 to 15 only if \$ a \$ is 0 in addition to \$ b \$ being negative, in which case adding 6 to the high nybble makes \$ a \$ 6. Thus, after the `daa`, AL still represents a polynomial equivalent to the result modulo 3 of the form \$ aX+b \$, but now with \$ 0 \le a \le 8, 0 \le b \le 5 \$. ``` sub al, 3 ``` Subtract 3. Again, AL represents a polynomial equivalent to the result modulo 3 of the form \$ aX+b \$, and this time \$ 0 \le a \le 8, -3 \le b \le 2 \$. ``` test al, 8 ``` Look at the eights bit of AL, which is 1 if \$ b \$ is negative and 0 otherwise. ``` jnz repeat ``` Jump back if \$ b \$ is negative (-3 to -1). If that is the case, next `daa` adds 6 to \$ b \$ while possibly changing \$ a \$ from 0 to 6, similarly to before, and then `sub` takes 3 from \$ b \$, leaving it with a net +3, which puts it in the range 0 to 2, and then `test` sees that the eights bit is 0, and the jump does not happen again. In either case, AL now represents a polynomial equivalent to the result modulo 3 of the form \$ aX+b \$ with \$ 0 \le a \le 8, 0 \le b \le 2 \$. If it were possible to jump conditionally based on AF, the `test` could have been omitted for -2 bytes. ``` aam 0x30 ``` This is another BCD instruction. In its default form, `aam` converts a regular number in AL to an unpacked BCD (one byte per decimal digit) number in AH and AL, which is done by setting AH and AL to the quotient and remainder, respectively, of AL divided by 10. However, the instruction allows that number 10 to be changed. We set it to 0x30; the important part is that AL is reduced modulo 0x30, which means \$ a \$ is reduced modulo 3. At last, the polynomial has been reduced modulo 3 to its canonical form. ``` ret ``` Return. # Previous solution, also 16 bytes ``` f7 e2 d5 02 01 d0 99 d4 30 c0 c0 04 4a 7a f8 c3 ``` [Try it online!](https://tio.run/##lZPNbtswDMfvegrOwwA7cQtH3SXNsj3IWhiMpLgKZMeT5SJDkFefR8mJYwc5tD7o40/yJ5KSxUMhRNd91ZUwrVTwo3FS7x/ffrKJZPTGawybEmIWvVSPhdlv0ECxXeZla5yuzd/o1oBSBm3s9BwUoI8UUPIw7BElZIeMDyEUfvWmDSg8pJMQIf@EtVW1QjdyxpJQT9kg2L0BNCl8HxSpxAS1qxX0mGuQonWyYnmOzlm9aZ3K8zi2qqjRljFPkgTaqtFFpSSIN7STbsRTE6Y3vptPk6kFH4EyXTkoUVexX6AtRNobZzPavCfsyHx108B3NM3v5Sus4Uh3kKX@JhZh5H5cBGURlEVQeFB4UDg/rQJzu7cQTnUEylY0fVkDp3k@T4JDf7T/akt@29jBL4hgFsEzTfMoWQ0OA2vXs3aetaT5wrohRfAt44co7UvZvd5D6R6lzyg9Rh3vQl@qMVWPqZ9K8l6ivvbJizmfkV4qoKZc7v3WNMrjdO1p6xqfMnUS3Nmjt9JTbm1FGbIT67p/YmuwaLqH8onTQD/1mjJT5j8 "C (gcc) – Try It Online") Assembly: ``` .text .global gf9_multiply .global gf9_add .intel_syntax noprefix gf9_multiply: mul edx # Multiply EAX by EDX, placing the product in EDX:EAX. aad 0x02 # AL := 2 * AH + AL (AL is the low byte of EAX; AH is the next byte.) # AH := 0 Reduces the polynomial modulo X^2 - 2. gf9_add: # When falling through, EDX=0; the next instruction will do nothing. add eax, edx# Add EDX to EAX. Coming from either start point, # this produces in EAX a polynomial equivalent to the result mod 3. cdq # Set each bit of EDX to the high bit of EAX, here 0. repeat: aam 0x30 # (AH, AL) := (quotient, remainder) of AL / 0x30 # Reduces the coefficient of X modulo 3. rol al, 4 # Rotate left by 4 places, swapping the positions of the coefficients. # Next, we need to execute the same two instructions again, # to reduce the other coefficient modulo 3 and swap them back. # Simply repeating those instructions would take 5 bytes. # It is instead done in 4 bytes, including the earlier cdq: dec edx # Decrement EDX, to -1 the first time and -2 the second time. jpe repeat # Jump back if the sum of the eight low bits is even. # This is true for -1 (...11111111) but not for -2 (...11111110). ret # Return. ``` [Answer] # [Haskell](https://www.haskell.org/), 83 bytes This is a straightforward adaptation of [05AB1E](https://codegolf.stackexchange.com/a/197336/46245)'s answer. This function accepts 0, 1, 2, 10, 11, 12, 20, 21, and 22. ``` k=flip mod q=l.k 30 l a=a-z+k 3 z where z=k 10 a p=((q.k 98.k 300).).(*) s=(q.).(+) ``` ]
[Question] [ You are to create a program which, when given a positive integer \$n\$, outputs a second program. This second program, when run, must take a second positive integer \$x\$ and output one of two distinct values depending on whether \$x\$ is divisible by \$n\$. Those values must be consistent for a given \$n\$ but can be different values for different \$n\$. However, for each value of \$n\$, the outputted program may only contain bytes whose code points are divisible by \$n\$. You may use any *pre-existing* code page to score and restrict your answer, but the code pages used for both programs must be the same. In addition, both programs must be in the same language (including versions. Python 3 \$\ne\$ Python 2). Your score is the highest *consecutive* value of \$n\$ your program works for. That is, your program must work for \$n = 1, 2, 3\$ and \$4\$ in order to have a score of \$4\$. All solutions must work for \$n = 1\$ and \$n = 2\$ at a minimum. The program with the highest \$n\$ wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), n=13, 189 bytes ``` 'Ì6×ÐI" ÿB`0¢ "D"₁h44₁44÷÷÷ÝÐÃм₁hhhÐÃ44u4÷÷÷₁h44₁44÷÷÷ǝ÷ƶê4₁÷÷ 1 Èÿ°À4ô¤¬ xÒÍÍ<_Zÿ11*Ò88w8*н¡Ë18*Ë xh`H°` ₂6₂6₂6$--«üuÆ-«üuÆ-«üuÆΘ ÒæP<<<<<<<<<<n(Zd XXšXXÜýвXšXš¥Æ≠≠ ÿÿð¨и0Ì<0ǝÀ0ÿäÀ`∍`Ā"#Iè ``` [Try it online!](https://tio.run/##yy9OTMpM/W9o7Opnr6Sga6egZP9f/XCP2eHphyf4KSkc3u@UYHBokYKSi9KjpsYMExMgaWJyeDsYzj084XDzhT0giYwMENvEpBQqh6H4@NzD249tO7wKJAbiKxgqHO44vP/QhsMNJoe3HFpyaI1CxeFJh3sP99rERx3eb2iodXiShUW5hdaFvYcWHu42tNA63K1QkZHgcWhDgsKjpiYzGFbR1T20@vCe0sNt6PS5GQpAE5cF2MBBnkZUikJExNGFERGH5xzee2ETiHl04aGlh9sedS4AIqB/gXDDoRUXdhgc7rExALq6wQAosuRwQ8Kjjt6EIw1Kyn6HV/zX@Q8A "05AB1E – Try It Online") or [validate codepoint divisibility](https://tio.run/##yy9OTMpM/W9o7Opnr6Sga6egZO/n91/9cI/Z4emHJ/gpKRze75RgcGiRgpKL0qOmxgwTEyBpYnJ4OxjOPTzhcPOFPSCJjAwQ28SkFCqHofj43MPbj207vAokBuIrGCoc7ji8/9CGww0mh7ccWnJojULF4UmHew/32sRHHd5vaKh1eJKFRbmF1oW9hxYe7ja00DrcrVCRkeBxaEOCwqOmJjMYVtHVPbT68J7Sw23o9LkZCkATlwXYwEGeRlSKQkTE0YUREYfnHN57YROIeXThoaWH2x51LgAioH@BcMOhFRd2GBzusTEAurrBACiy5HBDwqOO3oQjDUrKfodX/D@670hbcXC23@FpOv8B). n=1: `1` simply returns 1, since all integers are divisible by 1. n=2: `È` is the built-in for that, and its codepoint is even. n=3 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/339gpweDQov86/wE): ``` 3B # convert input to base 3 ` # get the last digit 0¢ # count occurences of 0 in that digit ``` n=4 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/3/9CGww0mh7ccWnJozX@d/wA): ``` ° # 10**input À # rotate left 4ô # split in chunks of 4 digits ¤ # get the last chunk ¬ # get the first digit of that chunk ``` n=5 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/3v@LwpMO9h3tt4qP@6/wHAA): ``` x # double the input Ò # prime factorization ÍÍ< # subtract 5 from each prime _ # equal to 0? Z # maximum ``` n=6 works identically to n=3. n=7 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/339BQ6/AkC4tyC60Lew8tPNxtaKF1uPu/zn8A): ``` 11* # multiply the input by 11 Ò # prime factorization 88w8*н # first digit of 88*8, namely 7 ¡ # split the prime factorization on 7 Ë # are all sublists equal? 18* # multiply by 18 Ë # are all digits equal? ``` n=8 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/3vyIjwePQhoT/Ov8B): ``` x # double the input h # convert to hex ` # get the last digit H # convert from hex ° # 10**x ` # get the last digit ``` n=9 [TIO](https://tio.run/##yy9OTMpM/W9k6upnaBqYqaQLA0o6tf8fNTWZwbCKru6h1Yf3lB5uQ6fPzfiv89@Qy4jLmMuEy5TLjMucy4LL0IDL0oLLCAi4DKGAywwOuCwxgAWXJZchUAdQsyGXpYEB0AQDCzBhYWBgCDfEkMvYwMAAjIEWmJuZmhgbgezCBAA): ``` ₂ # push 26 6 # push 6 $ # push 1 and input - # subtract: 1 - input - # subtract: 6 - (1 - input) = 5 + input « # concatenate: "26" + (5 + input) üu # for each pair of digit, uppercase the second one # (used to convert to a list of digits, but drops the first digit) Æ # reduce by subtraction: 6 - sum(digits(5 + input)) # the above sequence is repeated twice, yielding 6 - sum(digits(sum(digits(sum(digits(5 + input)))))) Θ # is it equal to 1? ``` Note that this algorithm doesn’t work for arbitrary large numbers (but it still works up to 10^10000000000, which is good enough). n=10 [TIO](https://tio.run/##yy9OTMpM/W9k4Opnr6Sga6egZO/3//Ckw8sCbOAgTyMq5b/OfwA): ``` Ò # prime factorization of the input æ # power set P # product of each subset <<<<<<<<<< # subtract 10 from each n # square each ( # negate each Z # maximum d # is it >= 0? ``` Divisibility by 10 is usually the easiest, but unfortunately there’s no compliant way to get the last digit. n=11 [TIO](https://tio.run/##yy9OTMpM/W9s5upnr6Sga6egZO/3PyLi6MKIiMNzDu@9sAnEPLrw0NLDbY86FwDRf53/AA): ``` X # push 1 Xš # prepend 1: [1, 1] XXÜ # 1, with trailing 1s trimmed off (aka empty string) ý # join: 11 в # convert input to base 11 Xš # prepend 1 Xš # prepend 1 ¥ # deltas Æ # reduce by subtraction ≠≠ # is it equal to 1? ``` n=12 [TIO](https://tio.run/##yy9OTMpM/W9s5upnr6Sga6egZO/3/3APDrjh0IoLOwwO99gYHJ97uMEARW7J4QZs8NAKTJjwqKM34UjDf53/AA): ``` ÌÌÌÌÌÌÌÌÌÌÌÌ # add 24 to the input ð # space character ¨ # drop the last character (empty string) и # make a list of input empty strings 0Ì<0ǝ # replace the first element with 1 À # rotate left 0ÌÌÌÌÌÌä # split in 12 parts of approximately equal length # (if the input isn’t divisible by 12, the first sublists will be longer) À # rotate left ` # dump all to the stack ∍ # cycle the before-last sublist to match the length of the last sublist ` # get the last element Ā # truthify ``` n=13 (`[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`, `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`): [TIO](https://tio.run/##yy9OTMpM/W9q4Opnr6Sga6egZO/3/1FTY4aJCZA0MTm8HQznHp5wuPnCHpBERgaIbWJSCpXDUHx87uHtx7YdXgUSA/H/62jG/AcA) ``` ₁h44₁44÷÷÷ # hex(256) / (44 / (256 / 44)) = 12 Ý # range [0..12] Ðà # duplicate (well, triplicate then pop the third copy) м # remove (leaves a list of 13 empty strings) ₁hhhÐÃ44u4÷÷÷ # 13 ₁h44₁44÷÷÷ # 12 ǝ # set the element at index 12 to 13 ÷ # integer division # dividing by the empty string yields the numerator, # so the result is 12x the input, followed by input / 13 ƶ # multiply each element by its index # the last element is now equal to input iff 13 divides input ê # sorted uniquify 4₁÷÷ # divide by 0 (sets all elements to 0) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 108 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), n = 6 ``` g[P"1""v""¥r3""ì4 ¬t(´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D <(°D,°D""s7-2 ë2,-1 Z<7-2-2-2""NÌÀNÌr6"] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1tQIjEiInYiIqVyMyIi7DQgrHQotEQstEQstEQstEQstEQstEQstEQstEQstEQstEQstEQstEQstEQstEQgIDwosEQssEQiInM3LTIKCgoKCusyLC0xClo8Ny0yLTItMiIiTszATsxyNiJd&input=NA) ### 1 (1, no value) ``` 1 //Output 1 ``` ### 2 (1, 0) ``` v //Builtin, is divisible by 2 ``` ### 3 (true, false) ``` ¥ //Input equals r3 //Input rounded to nearest multiple of 3 ``` ### 4 (true, false) ``` ì4 //Convert to base-4 digits ¬ //Concatenate to string ´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D,´D //--D 14 times, D = -1 now t( //Take -1 element of the string < //Is that less than (°D,°D //++D 2 times (1) ``` ### 5 (true, false) ``` s7-2 //Convert to base-5 string ë2,-1 //Get every 2nd element of the string, starting from the last index, save in variable Z Z<7-2-2-2 //Is Z less than 1? ``` ### 6 (false, true) ``` NÌ //Last element of input array À //Doesn't equal NÌr6 //Last element of input array rounded to nearest multiple of 6 ``` Sadly, I think it's not possible to get n=7. There is not a single parentheses character, and there is no way to access the input variable `U` besides `¡` (maps each element in array/string to undefined by default, returns NaN if caller is number) and `Ë` (maps each element in string/array to iteself, returns NaN if caller is number). And since we don't have `}` or `Ã` (used to close functions), we cannot use `¡` or `Ë` effectively at all. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 103 bytes, n= 9 ``` “1“d2Ṫ“3ḍ“d4 0ị⁼0”⁾d«;“2_7ƊȦ”¤ṭ“HHHHHN6ƭ€0ị<0”ṭ“~“8¡~“1߬?”j”‘¤ṭ“00000008 8ƭ⁸¡”ṭ”‘x4¤”~;$;“6¡~ñ-H?”¤ṭ⁸ị ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxxDIE4xerhzFZA2frijF8Q1UTB4uLv7UeMeg0cNcx817ks5tNoaKG4Ub36s68QyoNihJQ93rgWKeICAn9mxtY@a1oC02IA0QKTqgNji0EIQZXh4/qE19kCZLJBxDTNgug0gwELBAmhA445DC2GaQYoqTA4tAbLqrFVAVpsBTTq8UdfDHm554w6gff8Pt2vrH530cOcMkCKFxJwchZTMsszizKScVIWkSgWgamugzFxba6DPDrcfnuGV@WjjukcNM49terhrwbEuLsvD7UCnR/4HAA "Jelly – Try It Online") ## Return values: ``` n div not 1 1 - 2 0 1 3 1 0 4 1 0 5 1 0 6 1 0 7 1 error 8 8 0 9 -1 error ``` ## Explanation ### n=1 ``` 1 | 1 ``` ### n=2 ``` d2 | divmod 2 Ṫ | tail ``` ### n=3 ``` 3ḍ | divisible by 3 ``` ### n=4 ``` d4 | divmod 4 0ị | last ⁼0 =0 ``` ### n=5 ``` d Ɗ | divmod following as a monad: «2 | - min of input and 2 _7 | - minus 7 Ȧ | each and all ``` ### n=6 HHHHHN6ƭ€ | For each number 1..z, half five out of every six numbers and negate the sixth 0ị | Last <0 | <0 ### n=7 ``` ~ | Bitwise not (effectively -1-z) ‘8¡ | Increment by 1 eight times ~ | Bitwise not ‘ | Increment by 1 1߬? | If non-zero, call this link again. Otherwise return 1 ``` ### n=8 ``` 00000008 8ƭ⁸¡ | Loop z times; for 7 out of 8 iterations, set value to 0 and for the eighth, set to 8 ``` ### n=9 ``` ~ | Bitwise not ‘‘‘ | Increment by 1 three times ‘6¡ | Increment by 1 six times ~ñ-H? | If non-zero, call this link again. Otherwise return -1 ``` Note (as pointed out by @Grimmy) that n=7 and n=9 will fail on larger inputs (>14651 and 14202 respectively) because of the recursion limits in Jelly/Python. ]
[Question] [ Given a list of jobs, which must be done in order, with each taking a slot to do, how long will it take to perform them all if after doing a job the same job cannot be done for the next two slots (cooling off slots)? However, a different job can be assigned in this cooling off slots. **For example,** ``` [9,10,9,8] => output: 5 ``` Because jobs will be allocated as `[9 10 _ 9 8]`. 1. First, 9 needs two cooling off spots \_ \_. So we start with `9 _ _`. 2. Next job 10 is different from the previous job 9, so we can allocate one of \_ \_. Then we will have `9 10 _`. 3. Third, 9 cannot be allocated now, since first job 9 is the same job and it needs cooling off time. `9 10 _ 9`. 4. Last, 8 is not same as any other previous two jobs, so it can be allocated right after 9 and since this is last job, it does not need cooling off time. Final list is `9 10 _ 9 8` and expected output is 5, which is the number of spots (or number of slots) **Test cases:** ``` [1,2,3,4,5,6,7,8,9,10] => output : 10 ([1 2 3 4 5 6 7 8 9 10]) [1,1,1] => output: 7 ([1 _ _ 1 _ _ 1]) [3,4,4,3] => output: 6 ([3 4 _ _ 4 3]) [3,4,5,3] => output: 4 ([3 4 5 3]) [3,4,3,4] => output : 5 ([3 4 _ 3 4]) [3,3,4,4] => output : 8 ([3 _ _ 3 4 _ _ 4]) [3,3,4,3] => output : 7 ([3 _ _ 3 4 _ 3]) [3,2,1,3,-4] => output : 5 ([3 2 1 3 -4]) [] => output : 0 ([]) [-1,-1] => output : 4 ([-1 _ _ -1]) ``` Input value can be any integer (negative, 0, positive). Length of job-list is 0 <= length <= 1,000,000. Output will be an integer, the total number of slots, which is indicated in test case as output. The list inside the parenthesis is how the output would be generated. **Winning criterion** [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` v¯R¬yQiõˆ}2£yåiˆ}yˆ}¯g ``` [Try it online](https://tio.run/##yy9OTMpM/f@/7ND6oENrKgMzD2893VZrdGhx5eGlmUBWJRAfWp/@/3@0oQ4IGukYxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2Sgq6dgpL9/7JD64MOrakMzDy89XRbrdGhxZWHl2ZGAJmVQHxoffp/nUNb/kdHG@oY6RjrmOiY6pjpmOtY6FjqGBrE6igAxYEQxABJmugYw5imCCYQQ5hgJQgmVIER0ARjHV2wBAjrGuroGsKNBklDOEZQTiwA). **Explanation:** ``` v # Loop over the integers `y` of the (implicit) input-list: ¯R # Push the global_array, and reverse it ¬ # Get the first item (without popping the reversed global_array itself) yQi } # If it's equal to the integer `y`: õˆ # Add an empty string to the global_array 2£ # Then only leave the first 2 items of the reversed global_array yåi } # If the integer `y` is in these first 2 items: ˆ # Add the (implicit) input-list to the global_array yˆ # And push the integer `y` itself to the global_array }¯g # After the loop: push the global array, and then pop and push its length # (which is output implicitly as result) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes It's always nice to see problem where Brachylog performs best ``` ⊆Is₃ᶠ≠ᵐ∧Il ``` # Explanation ``` ⊆I # Find the minimal ordered superset of the input (and store in I) where: s₃ᶠ # each substring of length 3 ≠ᵐ # has only distinct numbers ∧Il # and output the length of that superset ``` [Try it online!](https://tio.run/##AS8A0P9icmFjaHlsb2cy///iioZJc@KCg@G2oOKJoOG1kOKIp0ls//9bMywzLDQsNF3/Wg "Brachylog – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ṫ-i⁹⁶ẋ⁸;;µƒ⁶L’ ``` [Try it online!](https://tio.run/##y0rNyan8///hztW6mY8adz5q3PZwV/ejxh3W1oe2HpsE5Po8apj5////aGMdBSAyAaJYAA "Jelly – Try It Online") [Answer] # [R](https://www.r-project.org/), 123 bytes ``` `-`=nchar;x=scan(,'');while(x!=(y=gsub("([^,]+),(([^,]*,){0,1})\\1(,|$)","\\1,\\2,\\1\\4",x)))x=y;-gsub("[^,]","",y)+(-y>1) ``` [Try it online - single program!](https://tio.run/##JYxBCsIwEEXP4iB0xv6A0e7CeBFHaS1iBemiRUxQzx6jLh68xX9/yrl1rY790E0h6tx3I6OqJDyG6@3McaGc9DLfT0y8P@JQC/gnK8hzDf8WM894LYVARWG2KXizhhBFJGoK7n/wzcqKkKRml3Ze8hYNCvkD "R – Try It Online") [Try it online - multiple examples!](https://tio.run/##TY19T8JADMb/51NoY0IrzxFuG75kHl/E03AsTJaY0zDQjbnPPm9MhDRtnqf9td12ucn3PtsVH56dNGXm/LkxnU7FpYcn1XRLtTQ@27htWpkeYozHkn5vivc1V9eGa/NW7ldM/PyKl4mAj@IW0sygW7FWM35uhEBBwtoopLY2IVQiUpk6VcOBfi1QhFomrOqFlq4dFf6rKItV@JW5HTuQWhAOoCsOHEisJ5TrT0Mk0o5yJo0IMRLMcYd7POARekYyTEIMsgcSxGczvzQhT@YIXpp/LArXYqi/4VCVhgoful8 "R – Try It Online") A full program that reads a comma-separated list of integers as the input, and outputs the slots needed. I’m sure this could be golfed some more, and implementing this regex-based solution in some other languages would be more efficient in bytes. Note on the second TIO I’ve wrapped it in a function to permit multiple examples to be shown. This function also shows the final list, but this is not output my the main program if run in isolation. [Answer] # TSQL query, 158 bytes Input data as a table. The query is recursive so > > OPTION(MAXRECURSION 0) > > > is necessary, because the list of numbers can exceed 100 although it can only go handle 32,767 recursions - is the limitation really needed in this task ? ``` DECLARE @ table(a int, r int identity(1,1)) INSERT @ VALUES(3),(3),(4),(4); WITH k as(SELECT null b,null c,1p UNION ALL SELECT iif(a in(b,c),null,a),b,p+iif(a in(b,c),0,1)FROM @,k WHERE p=r)SELECT sum(1)-1FROM k OPTION(MAXRECURSION 0) ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1013378/calculating-total-slots)** [Answer] # [R](https://www.r-project.org/), ~~81~~ 70 bytes ``` sum(l<-rle(s<-scan())$l*3-3,1-l%/%6,((r=rle(diff(s,2)))$l+1)%/%2*!r$v) ``` [Try it online!](https://tio.run/##dZHJasMwEIbvfYopSUBKRzSSLC/B7q3PEYJjF4GX4qWX0md3JS@JoxCE5jDz/TOjX82QQ8wg76u003VFNIVfaNNzBcktSTVsPsu@OHe6@pqqed1Al7U2MbR9SYqYNUVG2pjZMqF0W@wlk8hZsXvf@UhIk1jgovOctCioJd44NUWxf222P3T4e8lJSiLkB4wwpHQDyQfUfffdd0dQY5GjQIkeKvQxwBAtfAfCEfgByMiCAAkeKPAhgBAiGFk6NzLHGREsupM5c7wK7FQPpSPxJ4kdY3EP5J1APQi8m0A5sLnuU9S6vYkrftzH5cOFP038tJSjkq4qeFStNxPGKons@XLCmCWBLXOqvswanRKXn7/l2plxZNyFZn/YZD/jrkP4xCnOHavW0TYZ/gE "R – Try It Online") After several unsuccessful attempts, the code turned rather ugly and not so short, but at least it works now... First, we evaluate the lengths of consecutive runs of the same job. E.g. for `3, 3, 4, 3` this gives: ``` Run Length Encoding lengths: int [1:3] 2 1 1 values : num [1:3] 3 4 3 ``` Each of these runs produces `(len - 1) * 3 + 1` steps (`+ 1` is handled separately). Next, we process occurrences of the same job 2 places apart, like: `x, y, x`, by using `diff(s, lag=2)`. The resulting vector is also chunked into consecutive runs (`r`) by `rle` function. Now, because of various interleaved alternations we need to add `ceiling(r$len/2)` steps for all runs of zeroes. E.g.: `x y x` (length 1) and `x y x y` (length 2) both need 1 extra step: `x y _ x (y)` `x y x y x` (length 3) and `x y x y x y` (length 4) both need 2 extra steps: `x y _ x y _ x (y)` Finally, we need to compensate for occurrences of these alternations in the middle of a long run of the same job: `x, x, x, x...`, hence `1-l%/%6` instead of simply `1`. [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` r=[] for x in input(): while x in r[-2:]:r+=r, r+=x, print len(r) ``` [Try it online!](https://tio.run/##PYzRCoMwDEXf@xXFJ2W3sFadW8EvKX0aHQpSJTjWfb1LdUgS7uHeJMt3HeZots8wTkFqG1J4FkWxUe@8eM0kkxwj9/Jey8oKeeztJjllrLd06QlCsiSIhca4yinEkqot/3EaBjUatLihwx0P6KsXbHOx5qhB/af2JJ6d9vykIzV8W0Nlm1tpKO1/ "Python 2 – Try It Online") Implements the challenge pretty literally. Uses copies of the list itself as "blanks", since these can't equal any number. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 23 bytes ``` Fθ«W№✂υ±²¦¦¦ι⊞υω⊞υι»ILυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BToZqLszwjMydVQcM5vzSvRCM4JzM5VaNUR8EvNT2xJFXDSFNTRyFTU1MhoLQ4AyRermnNxQnjZAI5tVwBRZlAnc6JxSUaPql56SVAKU1NTev//6OjjXUUTHQUQGRs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fθ« ``` Loop over the jobs. ``` W№✂υ±²¦¦¦ι⊞υω ``` Add cooling off spots while the job is one of the last two in the result. ``` ⊞υι» ``` Add the current job to the result. ``` ILυ ``` Print the number of spots. [Answer] # [R](https://www.r-project.org/), ~~74~~ 68 bytes ``` length(Reduce(function(x,y)c(y,rep("",match(y,x[2:1],0)),x),scan())) ``` [Try it online!](https://tio.run/##dZHbioMwEIbv9ymG9iaBCRjjmXbv9gX2dlmKZLUVqhYbwbLss7uJp9qUEgyYfN/M@Nv0OewY5G0lVVFXpKDwC1eZVrC/H9ICth9le05VUR3H27xuQGVXc9Cfs@qoTuQz@2llRharwxuV5IZNdiGbDZapkif92n25Cf9Gh1LsKJpihFLa/73lRJIYuYMxRpRuYf8OdasurUrAHy45uijQQx8DDDFCAz@AkAB3gAwsuCDAAx8CCCGCGAaWToX0slqEs3fQa9oXwXT1UFhKMCqmjcE9EA@C/yR4d8G3YP3Yn@Kvy@t9xQ/z2Hw084eRH4eyLGFb4bO1nszVUQlkr4dzdVgC2NynasusKSSx@em3LJUZR8ZtaMqHjfEzbieEL5Li3IpqvZsi/T8 "R – Try It Online") Constructs the work array (in reverse), then takes the length. Just a bit ~~shorter~~ longer than [Kirill L.'s answer](https://codegolf.stackexchange.com/a/182027/67312), so sometimes, the naive approach is pretty good. EDIT: shorter again! I also borrowed Kirill's test template. *-6 bytes replacing* `max(0,which(y==x[2:1]))` *with* `match(y,x,0)`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 98 bytes ``` {($!=$,|$_ Z$_ Z .[1..*+1])>>.repeated.squish(:with({$+^=[*] $! ne$^a ne$^b,$b==($!=$a)})).sum+$_} ``` [Try it online!](https://tio.run/##bdFLb8IwDADgO7/CQ9GUUDeQvmEq0w677bzDSqmKKAKJ12irCTF@e5ek5VE0RfHB/mon6T47rL1qc4TnBYTViZKnkOAvSeBLbeCR4LxniJiNx/yQ7bO0yOY8/y5X@ZKOflbFkp6IMQ2jXgzkCbYZmaY6zpDMwlC3S9mZMZ6XG4Mk52qxOwBdr7ZZzuDUAYBNn04i3nudxExGOpkbrP@iCnl6hAUlA/7@@fbBELoQjqGLQETnXEUCLbTRQRc99DHAIYpBrMSuLPZlASMQA6CRAAtscMAFD3wIYCjTMevIz@W68yNZVTqRq4mKqQkO2i3oSahaKuSAfWHuA3Ma5t6I3O0jutdWMtZKT2yrQKukVvXYm7Xb1n@wzWxLXtdG89/xlrywDabu2a6rB1RZU6Ap2iV1O7N@KFnqROpnNFvDAHQqwWu8R5r4D@QKLg9w18ORMZHpPw "Perl 6 – Try It Online") Blergh, there's got to be a better way of doing this. I'm not 100% sure this is fully correct, though it passes all the edge cases I could think of. Basically, this starts by grouping all the triplets of the input list, with padding to either side. For example, `[1,2,1,2]` becomes `(Any,1,2), (1,2,1), (2,1,2), (1,2,Nil)`. We get the `repeated` elements in each triplet, becoming `(), (1), (2), ()`. It then `squish`es consecutive elements that are not the same list, but are the same size (to not squish something like `[1,1,1]`), and the first element is not equal to the element before it (because we can't merge the hours in `[1,1,2,2]`), and finally the element before hasn't also been squished (`[1,2,1,2,1,2]`). So `(1), (2)` in the above example above would be squished together. Finally, we get the `sum` of all lengths of this list, which represent our inserted hours, and add the length of the original list. For example: ``` (1,1,1) => (Any,1,1),(1,1,1),(1,1,Nil) => (1),(1,1),(1) => (no squishes) => 4+3 = 7 (1,2,1,2,1,2) => (Any,1,2), (1,2,1), (2,1,2), (1,2,1), (2,1,2), (1,2,Nil) => (),(1),(2),(1),(2),() => squish (1),(2) and (1),(2) => 2+6 = 8 ``` [Answer] # JavaScript (ES6), 57 bytes ``` f=([x,...a],p,q)=>1/x?1+f(x!=p&x!=q?a:[x,...a,x=f],x,p):0 ``` [Try it online!](https://tio.run/##dZHNboMwEITvfYrtpQJ1DBjbQCLRPEiEIpSGqlUUyI8qvz1dA80BjFfe03yzo92f@re@H2/f3UNc2s9T3zdlsLeIoqiu0OEalh8ytjv53gT2tezeuF139XaSwJZNBYsu3Cb9sb3c2/MpOrdfQRPsJVIoaBhkyFFgA5lUYUgUxyQTYgGlpEiToYxyKmhDTvCysOEauNljm3xwOXBNfYm7BBpqacB4xrgL4FBNyg@bFVhPsFkD@XtB85zK3YcOkb1oMaCHER1jrxn4Q@czA2/0lDeuIOYRntFT3rYi4RntO9M/6y6@JISEWLuu27AYD@s0/R8 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [x, // x = next job ...a], // a[] = array of remaining jobs p, // p = previous job, initially undefined q // q = penultimate job, initially undefined ) => // 1 / x ? // if x is defined and numeric: 1 + // add 1 to the grand total f( // and do a recursive call to f: x != p & // if x is different from the previous job x != q ? // and different from the penultimate job: a // just pass the remaining jobs : // else: [ x, // pass x, which can't be assigned yet ...a, // pass the remaining jobs x = f // set x to a non-numeric value ], // x, // previous job = x p // penultimate job = previous job ) // end of recursive call : // else: 0 // stop recursion ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 69 bytes ``` f(j,l)int*j;{j=l>1?(*j-*++j?j[-1]==j[l>2]?j++,l--,3:1:3)+f(j,l-1):l;} ``` [Try it online!](https://tio.run/##VZLdjoIwEEbv@xTExATs17iluj8Q5EGQi11cN9RSkbhXyrOzU4xdSNtMTs900mZaiZ@qGoZjqGGi2l5XOr3pzOxkHq60WHGuc10IWWaZLswuLnPNOYwQUIlMVMTHg0JGiUn7ofmsbRjdGKNCwZ7VRZndJGIobLDFK97wjg/Ilx5MPxwNgpMDl7SBIjRP3I7YPJEWoX3gmE54/keX3D4wpsoKwiVc3A7FzkUhIWSfMtZ2dMdjuKiD5WFvFziGNV0silJvtDcaaipOXpywmQrjhZmLxotmLqwXdi7OXpznovWixXYqLl5cMHtH50WH2Imerdfd9/W3swG1WBeyzMdIzaW3cjn2k8vEQUwQR1wlE6NSKvCsvjwEk3m/L/CJL1Q40HdKhz8 "C (gcc) – Try It Online") Straightforward recursion. ``` f(j,l)int*j;{ //Jobs, (array) Length j=l>1 //if l > 1, do a recursion: ? (*j-*++j // check if first and second elements are equal (j++) ? j[-1]== // 1st!=2nd; check if first and third are equal j[l>2] // (first and second if l==2, but we already know 1st!=2nd) ? j++,l--,3 // 1st==3rd (j++,l--) return 3+f(j+2,l-2) : 1 // 1st!=3rd (or l==2) return 1+f(j+1,l-1) : 3 // 1st==2nd return 3+f(j+1,l-1) )+f(j,l-1) // j and l were modified as needed : l; // nothing more needed return l } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes ``` {$!=0;.map:{{$_=($!=$!+1 max$_)+3}((%){$_})};$!} ``` [Try it online!](https://tio.run/##bdBfa4MwEADw5/kpTnBrQs9iTPzTioM97G3PfRERYRUGdYq2bEX87O6ibp3rCAnk7pc7LvWhOfpDeYGHAuKhs8zYiTZlXu@6zspiRnfLXAso808r42vZM3bPKdPzPrLMfoiMomrg@PZ@aBmHzrhr8wtsPqrmtU1UirCCFULB5oiTbp73Ty88MvohEeiiRIUe@hhgiFsUTgrxI1TnU30@wQ6EAywR4IIEBR74EEAIWwqn3KDntJY@GHlGaz610y0UyqX0SeqiWimQ387769TsvKuhvTTeTy06JzX2XKpwVNmkpr5XK2/n@G3n3i5NLNH@t71LI0uwx5rLvP5DHbUF2uJ2Onv6KkrxLw "Perl 6 – Try It Online") **45 bytes** if the list has at least two elements: ``` +*.reduce:{$^b,|(*xx 3-(|$^a,*,$b...$b)),|$a} ``` [Try it online!](https://tio.run/##bdDLboJAFAbgdXmKf0EqQw/EYYaLGpt00V3X3RA0UCFpYosBSTXis9PhYi21mcwsznxz/pzZpcXWaz6OuM@wbB5Mu0g31Vs6P@mrhGrDPBwgLKPWVzGZpCe2besJY1Tr8blZaFleYPv@mZYGw0m7K@Mj7K@82JShjAgTTAiZMVSmkf38@vTCFtq5CTk5JEiSSx75FNCM@DTC8hF5td9Ve8zBpzBCDgcCEi48@AgwU@WIaeq5WmPvd3yt1nC2ro2QJMbSU7Jt2ioJcXHuXycH516N2mPj/vRSZ6@6zLEKOrXuVZ97teJ2jt92yHbUxIKsf@MdNbKA1fUc37d/2FYtTha/nc7qv0pdsW8 "Perl 6 – Try It Online") [Answer] # Smalltalk, 125 bytes ``` c:=0.n:=q size.1to:n-2do:[:i|(j:=q at:i)=(k:=q at:i+1)ifTrue:[c:=c+2].j=(m:=q at:i+2)ifTrue:[c:=c+1]].k=m ifTrue:[c:=c+1].c+n ``` **Explanation** ``` c : accumulator of proximity penalty q : input array. n := q length i : iteration index from 1 to: n-2 (arrays are 1-based in Smalltalk). j := memory for element i, saves some few bytes when reused k := similar to j but for i+1. m := similar to k but for i+2. ``` [Answer] # [Perl 5](https://www.perl.org/) `-pl`, ~~42~~ 40 bytes ``` $a{$_}=~s/.*/$\=$&if++$\<$&;$\+3/e}{$_=0 ``` [Try it online!](https://tio.run/##K0gtyjH9/18lsVolvta2rlhfT0tfJcZWRS0zTVtbJcZGRc1aJUbbWD@1FqjA1uD/f0suCy5LLkODf/kFJZn5ecX/dQtyAA "Perl 5 – Try It Online") [Answer] ## Batch, 184 bytes ``` @echo off @set l=- @set p=- @set n=0 @for %%j in (%*)do @call:c %%j @exit/b%n% :c @if %1==%l% (set l=-&set/an+=2)else if %1==%p% set l=-&set/an+=1 @set p=%l%&set l=%1&set/an+=1 ``` Input is via command-line arguments and output is via exit code. Explanation: ``` @set l=- @set p=- ``` Track the last two jobs. ``` @set n=0 ``` Initialise the count. ``` @for %%j in (%*)do @call:c %%j ``` Process each job. ``` @exit/b%n% ``` Output the final count. ``` :c ``` For each job: ``` @if %1==%l% (set l=-&set/an+=2)else if %1==%p% set l=-&set/an+=1 ``` If we processed the job recently, add in an appropriate number of cooling off spots. Additionally, clear the last job so that the next job only triggers cooling off if it's the same as this job. ``` @set p=%l%&set l=%1&set/an+=1 ``` Update the last two jobs and allocate a spot to this job. [Answer] **Swift, 114 bytes** ``` func t(a:[Int]){ var s=1 for i in 1...a.count-1{s = a[i-1]==a[i] ? s+3:i>1&&a[i-2]==a[i] ? s+2:s+1} print("\(s)")} ``` [Try it online!](https://tio.run/##Tc29CsMgFEDh3ae4ZAhKjPSmHRrBdu4zpA4SEO5iite0Q8iz25@p04FvOfyiWE61xjXNUGSw0y0VrzbxDBnYoYhLBgJKgMaYYOZlTaXHjcFBmKhH79ynHq7A3dHSBdv268O/D5Y73MUjUyqyuUtWjdrr7zZqPOhRn72qbw) [Answer] # [Python 3](https://docs.python.org/3/), ~~79~~ 75 bytes *-3 bytes thanks to mypetlion* *-1 byte thanks to Sara J* ``` f=lambda a,b=[]:a and f(*[a[1:],a,a[:1]+b,[b]+b][a[0]in b[:2]::2])or len(b) ``` [Try it online!](https://tio.run/##fdHRaoMwFAbg6@4pftiNbkcwxqgNuBcJoSR0skKnUuxFn96e1DKsyggJQf4v55j0t@Gna@U4NvXZ/fqjgyNfG6t50x7RRB/GGaEtOXJGC/vpyXheLX9O7amFNzqzmmfcXXD@biMfj/3l1A5RExlBGUnKSVFBJVW0J5HaOMY76i9016G/DtAQKTiKDBI5FAqUqLBHiL7NjuIR7G4355rDAR94PNe5CsVzkluuYBcKBpNDLpXaVvlTqbXguRb8e@qvEK@v6NHeJqoe6DChqcc1lZu0XNBFoxlfpKTkv14zvkqJ5KXiFF/mw8vNU4mgRGyeHC4umV4oJMY7) [Answer] # [Java (JDK)](http://jdk.java.net/), 110 bytes ``` j->{int p,q;for(p=q=j.length;p-->1;q+=j[p]==j[p-1]?2:(p>1&&j[p]==j[p-2]&(p<3||j[p-1]!=j[p-3]))?1:0);return q;} ``` [Try it online!](https://tio.run/##jdFPb4MgFADwez/F26XRDUnR2n9We1uyw047Nh5ca53OIiI2aVo/u0OrW7d5gBCCj9@DBybBKTCS/WcdH1nGBSTyG5ciTvGhpDsRZxQ/OqMRK9/TeAe7NCgKeA1iCpcRyFaIQMj4c2fXMRVbH8ELFWEUcg84uHVieBcZB4Zy55Bxjbm5m@A0pJH4cJhheMTJn9xky3y3GQ3ib8yVxjwyHv8ETX@ssbV1vd7EQxu0fF3fkNVEd3goSk4hd6paVttU1lXcFXjK4j0cZd3am@AxjTDGEPCo0Lt7NK2tHRICLlyAIDARWAimCGwEMwRzBAsESwRkApXzN8vss5o@sG6167f9ZLcGyPSO2MPEviPNOEBmPenOGiDz32TooEVPzPZGcmIM7bRs2P@wfKEm3ZCZRvsY3@DtXIjwiLNSYCb/g0ipxnHAWHrWEqLrjhI0VaGlCqeq0FaFM1U4V4ULVbhUhWTSy2pU1V8 "Java (JDK) – Try It Online") Ungolfed commented code: ``` j -> { int p, q = j.length; // Run all jobs for (p = q; p-- > 1;) { // reverse iterate q += j[p] == j[p - 1] ? 2 : // add 2 if prev same (p > 1 && j[p] == j[p - 2] & // 1 if 2prev same (p < 3 || j[p - 1] != j[p - 3]) // except already done ) ? 1 : 0; // otherwise 0 } return q; } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ṫ-i⁹⁶x; ⁶;ç³Ṫ¤¥¥³¿L’ ``` [Try it online!](https://tio.run/##y0rNyan8///hztW6mY8adz5q3FZhzQUkrQ8vP7T54c5Vh5YcWgqEmw/t93nUMPP///@GOkY6QAwA "Jelly – Try It Online") Although this is rather similar to [@EriktheOutgolfer’s shorter answer](https://codegolf.stackexchange.com/a/182046/42248), I wrote it without seeing his. In any case his is better! ### Explanation Helper dyadic link, takes current list as left item and next item as right ``` ṫ- | take the last two items in the list i⁹ | find the index of the new item ⁶x | that many space characters ; | prepend to new item ``` Main monadic link, takes list of integers as input ``` ⁶ | start with a single space ; | append... ç³Ṫ¤¥ | the helper link called with the current list | as left item and the next input item as right ¥³¿ | loop the last two as a dyad until the input is empty L | take the length ’ | subtract one for the original space ``` [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` lambda a:len(reduce(lambda b,c:b+[c]*-~((c in b[-2:])+(c in b[-1:])),a,[])) ``` [Try it online!](https://tio.run/##fdHbjoIwEAbga/cp/mRv6jpN7IGDTdwXYY0BxGjiIjFw4Y2vzk6FGASyaSgp@b/O0Fb3@nQtdXvc/rSX9Dc7pEjdpSjFrTg0eSH6bxnlLlsl@e5LPoTIcS6RJVK73XL1WileLSmlhF9tdTuXtTiKRJEmQ5YCCimimDak1hzAJ7bfuDZ11dRwUGtwFBoGFgFCRIixgY9@DLbi4e1iMeSOwx7vefTzUPnilsycC9n5gt5YmLEK5pXtVTAV/EwF/17wKsTzO3q2N4viJ9p3qOtxSs0sjUZ01KjmgzQk/@tV81EayLeKXXyc9zc3TElFUs3u7A9OdjfkE@0f "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` (a,i=0,h={})=>a.map(n=>h[n]=3+(i=h[n]>++i?h[n]:i))|i ``` [Try it online!](https://tio.run/##dZHPboMwDMbvewofE@G0QBKglcIepKqqqOufTB1U7bTLtmdnNnQ9QIgVywf/Pn@y3/2Xv@9v4fqpmvbt0B3BdcJjcCme3fevdLVffPiraFx93jRbpxMRHFd1koRXLtZByp/Q7dvm3l4Oi0t7EkexyTBHjQYtFlhihSvM0q2UAMslZClQA@SgwYCFAkqoYAXc8DKRoei50SOZslfZUTzyFGcHBvVUgPCCcDbAqAEdh@0MbB6wnQPpR0H7nEo5hvaWo2jVo7sBHWzPCcRNlyOBqPWcNq5RjS08ree0bQ0qMjp2pn@WLz4lVIZq7rq8YTUclnu6Pw "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes ``` ≢∊(⊢,⍨⊣,# #↓⍨⍳⍨)/⍵,⊂⍬⍬ ``` [Try it online!](https://tio.run/##bZDPSsNAEMbv@xQf9LAKKSZN@kffJqSsBIORdC8ivYjUGt0iiEcv9eJB6EFEKHjpo8yLpN9aT2l3d2Z39jfzzbLpVdEdX6dFed7NinQyybNGFq95KbPnUMn83jTysJR5fST1MhD3IfV70EFHZi8@cF/0xyfivgOpb8V9cjWsasQtInn61VMYKt3oQFPVW6WZrClI/MM4q7TREPdmq3RsLmFLcFPWVzGTzSsejbj1mTZpXrB8zftKHu90eaGnKkIPMRL0McAQI5wiCmHpSPxsDYuh8ukJi1pgoHY6eyD5A95aoE@wE2uB0T@IDzXv8VUxNqukpcW/w4FhEarNKoI37D@tuwU "APL (Dyalog Classic) – Try It Online") [Answer] # JavaScript (V8), 101 bytes ``` f=a=>for(var c=0,i=0;i<a.length;i++,c++)a[i-1]==a[i]?c+=2:a[i-2]==a[i]&&(c++,a[i-1]=void 0) return c} ``` [Try it online!](https://tio.run/##ddBLDsIgEAbgvadgZdowKPSh1YoexLAg2FZMUwzWboxnr2i6UEshhGTyZTLzX2Qnb8rqa0u6rO9LLvn@URobdNIixSloTnO9k4u6aKr2nGuMQWEcyqMmTHDufnFQmEfbdyUaKvN54BAMqDP6hGg4s0V7tw1Sz16Z5mbqYlGbKiiDI4MIYkgghRWsIYMNMCrCMEfLJWJ0NtLuCvR7Br3@x@@2CcTCh1c@nE7gxIfd8@J0jD@DeHHmx/4xPAtGLo8YyHfzqTH@U/vGo5wJAzKVc9K/AA "JavaScript (V8) – Try It Online") Unpacked code looks as follows: ``` function f(a) { var c = 0; for (var i = 0; i < a.length; i++, c++) { if (a[i - 1] == a[i]) c+=2; else if (a[i - 2] == a[i]) c++,a[i-1]=undefined; } return c; } ``` My first ever code-golf attempt, can probably be optimized a lot by shrinking the array and passing it recursively. [Answer] # [Zsh](https://www.zsh.org/), ~~66~~ 60 bytes *-6 bytes from implicit `"$@"`* ``` for j {((i=$a[(I)$j]))&&a= a=("$a[-1]" $j) ((x+=i+1))} <<<$x ``` [Try it online!](https://tio.run/##JYxBCsMgEEX3c4ohSJghuDBdVg/QM5QsBC1RgkLSUGnI2W2kfD68/xb/u831M4fF4@qtwyUkf0eXYfNvlBLFYZo66yuvGOEgCkbYJz1YxIm5760Ba6i7nFRThyIyEJXBhEExn6C1FqXuqd1ZLOBy8lXhiK23FlAXK/jvsRH8AA "Zsh – Try It Online") I highly recommend adding `set -x` to the start so you can follow along. ``` for j # Implicit "$@" { # Use '{' '}' instead of 'do' 'done' (( i=$a[(I)$j] )) \ # (see below) && a= # if the previous returned true, empty a a=( "$a[-1]" $j ) # set the array to its last element and the new job (( x += i + 1 )) # add number of slots we advanced } <<<$x # echo back our total ``` ``` ((i=$a[(I)$j])) $a[ ] # Array lookup (I)$j # Get highest index matched by $j, or 0 if not found i= # Set to i (( )) # If i was set nonzero, return true ``` `a` always contains the last two jobs, so if the lookup finds a matching job in `a[2]`, we increment by three (since the job slots will be `[... 3 _ _ 3 ...]`). If `a` is unset, the lookup will fail and the arithmetic expansion will return an error, but that only happens on the first job and isn't fatal. We can save one more byte if we use `$[x+=i+1]` instead, and there are no commands on the users system comprised entirely of digits. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 27 bytes ``` {#2_``{y,#[0|2-x?y;`],x}/x} ``` [Try it online!](https://tio.run/##RY3LCsIwEEX3fsWVulBoMI@@7Cz8kFCMm4pUKpQuEmr99ZhWgwwDc5jDvR3rb733bT0l8mLM5NJE85dk9uzINKmdj3b2Yz3ttHsPdQtL5tnR3rTX@4MsORoOzbwZtYCEQoYcBUpUOEFwErxZX2GoXM7FyKCoiJAHyCKEpfwLq0jVH1QMkCFNgf3MLae1gwkwEZL8Bw "K (ngn/k) – Try It Online") ]